From 2e092fc088ce41f1167127600583c45705192f8d Mon Sep 17 00:00:00 2001 From: huihui Date: Fri, 20 Nov 2026 16:42:18 +0800 Subject: [PATCH 01/83] feat(cli): follow the Session's default branch MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The worker reads defaultBranchId once per attachment and opens on that line: the initial focus, the transcript windows, the plain log's history and every request the clients make without choosing a line, and the top bar's model, permission and usage fold its events (design §4, §14). The lines panel marks the default branch and the root, p continues on the selected line through session.branch_set_default and then shows it, and the method's refusal is drawn in the panel. x is refused on the root, on the default branch and on every ancestor of the default branch, each with its own message, and the panel states what a move leaves in place. The plain log's history, idle, submit, stop, shell, goal, loop, permission and configuration calls name the conversation it read at attach. The marks and the key exist in every locale, and the README and Tui.md state them. --- crates/dim-cli/README.md | 16 +- crates/dim-cli/src/configure.rs | 10 +- crates/dim-cli/src/goal_command.rs | 16 +- crates/dim-cli/src/model/session.rs | 13 + crates/dim-cli/src/model/view.rs | 3 + crates/dim-cli/src/permission.rs | 50 ++-- crates/dim-cli/src/permission_command.rs | 38 ++- crates/dim-cli/src/question/line.rs | 11 +- crates/dim-cli/src/session.rs | 104 +++++-- crates/dim-cli/src/session/window.rs | 7 +- crates/dim-cli/src/session_host.rs | 171 ++++++++--- crates/dim-cli/src/session_host/tasks.rs | 11 +- crates/dim-cli/src/ui/i18n/de/chrome.rs | 15 +- crates/dim-cli/src/ui/i18n/es/chrome.rs | 15 +- crates/dim-cli/src/ui/i18n/fr/chrome.rs | 15 +- crates/dim-cli/src/ui/i18n/id/chrome.rs | 15 +- crates/dim-cli/src/ui/i18n/ja/chrome.rs | 15 +- crates/dim-cli/src/ui/i18n/ko/chrome.rs | 15 +- crates/dim-cli/src/ui/i18n/pt_br/chrome.rs | 15 +- crates/dim-cli/src/ui/i18n/pt_pt/chrome.rs | 15 +- crates/dim-cli/src/ui/i18n/zh_cn/chrome.rs | 15 +- crates/dim-cli/src/ui/i18n/zh_hant/chrome.rs | 15 +- crates/dim-cli/src/ui/lines_panel.rs | 279 +++++++++++++++--- crates/dim-cli/src/ui/prompts.rs | 6 + crates/dim-cli/src/ui/tui.rs | 23 ++ crates/dim-client/src/wire.rs | 6 + crates/dimcode/tests/cli_flow.rs | 5 +- crates/dimcode/tests/cli_flow/lines.rs | 285 +++++++++++++++++++ crates/dimcode/tests/cli_flow/permission.rs | 20 +- crates/dimcode/tests/cli_flow/startup.rs | 4 +- crates/dimcode/tests/cli_flow/tasks.rs | 4 +- docs/design/cli-commands.md | 8 +- docs/design/plugins/Tui.md | 13 + docs/zh/design/cli-commands.md | 6 +- 34 files changed, 1058 insertions(+), 201 deletions(-) create mode 100644 crates/dimcode/tests/cli_flow/lines.rs diff --git a/crates/dim-cli/README.md b/crates/dim-cli/README.md index 6c46e39085..d0dd07a5e2 100644 --- a/crates/dim-cli/README.md +++ b/crates/dim-cli/README.md @@ -704,14 +704,14 @@ parents before checking the [workspace boundary](../../docs/architecture/rust-ag `exec resume`. A new Session receives it in `session.create`; a resumed Session's `main` branch is changed with `session.permission.get/update` before attach, keeping its tool lists and retrying a version conflict. Without the flag a resumed Session keeps its preset. The header -shows the preset; `exec` prints it to stderr only when the flag is given. A live change on -`main`, from any client, prints `[permission] main branch preset: ...`. +shows the preset; `exec` prints it to stderr only when the flag is given. A live change on the +conversation's line, from any client, prints `[permission] preset: ...`. At the line-mode idle prompt, `/permissions` (aliases `/approvals` and `/approval`) shows the -preset, tool exceptions and the user's command rules. `/permissions PRESET` changes the active -main branch's preset; `full-access` asks `[y/N]` and only `y`/`yes` -confirms. `/approvals allow|deny exact|prefix COMMAND` adds a rule and `/approvals remove N` -removes rule N of the list printed last; both print the new numbered list. A preset or rule list +preset, tool exceptions and the user's command rules. `/permissions PRESET` changes the +conversation's line's preset; `full-access` asks `[y/N]` and only `y`/`yes` confirms. +`/approvals allow|deny exact|prefix COMMAND` adds a rule and `/approvals remove N` removes rule +N of the list printed last; both print the new numbered list. A preset or rule list that changed since it was shown is reported and nothing is written. Child branches and native members created later from the changed branch inherit its current policy; existing branches and members retain their own policies, including when a member is reused. Rules are user scope and apply in every Session: a deny rule under every preset, an allow rule only where the preset would ask. @@ -1505,10 +1505,10 @@ The terminal UI reaches the same Session methods as the line client: | `/connect` | Reads safe connection snapshots with `provider.management`. `Test + apply` probes the unsaved draft, then updates only changed fields at the form's original version with `provider.update`; a record whose models are its own has them replaced by the new endpoint's listing in that same write when the edit changes `baseUrl`, `credential` or `headers`, so the catalog follows the new endpoint, while a proxy or timeout edit saves alone and a builtin whose models are the bundled catalog's keeps them; unsupported model listing still permits saving and reports that the key was not tested. Other probe failures keep the draft. `Disconnect` atomically clears credentials and disables the record, and a catalog of the record's own goes with it, because the listing taken with that key is that key's view; the next connect lists the endpoint again. Enable/Disable update only that flag. With no unsaved connection edits, `Edit models` opens that Provider's `Models · ` management panel even while disabled; `Ctrl+R` in that panel fetches the catalog when the Provider offers `refresh`. `Add custom provider` probes a Name, Base URL and API Key draft, then calls `provider.create` with the form's retained UUID and discovered defaults. IDs never derive from names. Failures retain edits; rereads update the safe status/version and require confirmation before retrying. `Ctrl+R` rereads without discarding the draft. Fields and filters use the composer's line editor. A row whose entry carries an `account` descriptor opens the account step instead of the form: signed out, its row says `Sign in` and opening it starts the only flow the descriptor's `loginMethods` list, and signed in, it shows `Signed in` and signs out through `.logout`; a daemon that does not advertise the method reports that instead; a row whose namespace is `account` opens the Dim account's `/login` panel instead | | `/resume` | Lists saved Sessions, 50 at a time through `session.catalog`; moving near the end loads the next page. The first read carries the workspace `dimcode` was launched in, so every open starts there; git detection in the background names the local scope `This repository` even for one worktree, and re-reads the first page when the set holds more than one workspace. Ctrl+S toggles between that local scope and all workspaces — two states — and the title names the scope shown; a scope change keeps the query, drops the cursor and reads the first page again. Each row is labelled by the Session's creation origin — `[Chat]`, `[ACP ]` or `[Agent]` — and reads its title, else its first message, else its id; the placeholder `New session` counts as no title. Sessions Dim created for its own work are not listed; ACP Sessions are listed only while `/settings` → Show ACP sessions is on, and only on a daemon that advertises `session.catalog.origins`. The filter searches the server after 150 ms, including Sessions not loaded yet. Ctrl+R refreshes; closing, refreshing or replacing a search cancels the pending read when the daemon advertises `session.catalog.cancel`. Ctrl+X removes the selected row after `Delete "{name}"? Enter confirm · Esc cancel` — the name is captured at the key press, every other key cancels the question, Esc does not close the picker, and the row leaves on `{deleted:true}` with `Deleted {name}.`, a `{deleted:false}` reply re-reads the first page with `Nothing was removed: no stored Session {name}.`, an error keeps the row with `Delete failed · `, and a daemon without `session.delete` says it cannot delete Sessions; deleting the shown Session returns to Home as `/new` does. Older daemons use `session.summaries` and local filtering, with the scope applied to the rows the client receives | | `/models` | Shows three fixed sections ([CLI commands § The Models area](../../docs/design/cli-commands.md#the-models-area)): `Conversation model` lists enabled, executable models from `provider.list`/`provider.catalog`, `Subagent models` holds the policy entry, and `Model management` holds the `Manage models` entry and the compact diagnostics. Tab/Shift+Tab moves between the sections the daemon offers; Up/Down stays inside the focused one, and `←`/`→` and `Ctrl+X` act on the candidate list only. A model whose context window or maximum output no source declares is not offered; the diagnostics count such models, and they are not counted again as unavailable. A static provider whose catalog holds no models is asked to fill it with `provider.refresh` once per catalog version in a connection when the daemon says its models can be listed, and the picker shows what the catalog then holds, because the Provider owner decides what a catalog holds; a successful refresh records the version it wrote, so a listing that comes back empty is not asked for again, and a write to the record asks once more; the picker re-reads the list when such a refresh returns while it is open, and a reply that arrives after it closed is shown by the next open. `Manage models` opens a Provider list whose rows name each Provider and its state, including one that offers nothing selectable, and choosing a Provider opens its `Models · ` area; the focused Provider's guidance names the recovery command: `dimcode models PROVIDER --set-missing-limits` for missing limits, `dimcode models PROVIDER --refresh` for no models when the daemon says its models can be listed, `provider.models.create` when it cannot, an unreadable catalog, or how many models are unavailable, disabled, or both, with `dimcode models PROVIDER` for the details. Closing the area returns to the Provider list, and closing that returns to the sections with their search, selection and list position and reads the models again. Without `provider.management` there is no `Manage models` entry and the same guidance stays as read-only lines. An explicit pick sends the saved effort/tier preferences for that exact `{providerId, modelId}` with `session.create` or `session.model.update`, then saves the scoped default with `provider.select`. The adopted model stays in effect even when saving the default fails; the failure is reported as a notice. Unsupported saved preferences are reported and retained for the user to edit or clear; there is no silent fallback. When the daemon advertises `collaboration.model_policy`/`collaboration.set_model_policy`, the `Subagent models` section chooses Agent choice, Inherit requesting branch or a fixed model (from the same model list) for new Collaboration members; it writes only `collaboration.set_model_policy` with the revision it read, and after a revision conflict the next choice rereads before saving ([subagent model policy](../../docs/design/subagent-model-policy.md#5-native-cli-interaction)) | -| `/lines` | Lists `main` and every line under the line it was opened from, ordered by where it was cut and labelled `after message N`, each with its state (working, waiting, ended itself, ended by an operation, creation failed); while a line is shown the composer's bottom border names its path from `main` (`line main ▸ b-91 · after message 4`); Enter shows the selected line's conversation in place of `main`'s, and the composer, `!command` and the interrupt then address that line; `x`, then `y`, ends the selected line through `session.branch_end`, refused on `main` | +| `/lines` | Lists `main` and every line under the line it was opened from, ordered by where it was cut and labelled `after message N`, each with its state (working, waiting, ended itself, ended by an operation, creation failed); the Session's default branch is marked `Main line` and `main` is marked `Start`; while a line is shown the composer's bottom border names its path from `main` (`line main ▸ b-91 · after message 4`); Enter shows the selected line's conversation in place of the shown one, and the composer, `!command` and the interrupt then address that line; `p` continues from the selected line, sending `session.branch_set_default` and showing that line's conversation with its model, permission and usage in the top bar, and the method's refusal is drawn in the panel, which states that the old default branch stays open, that the two lines swap the right to open a line, and that the root keeps its own right in either direction; `x`, then `y`, ends the selected line through `session.branch_end`, refused on `main`, on the default branch and on every ancestor of the default branch | | `/timeline` | Lists the shown line's user messages, oldest first, numbered, each with the first text of its answer, the newest selected. `Enter` opens an action dialog: jump, edit as a new draft, quote, branch or fork. Up/Down and Enter choose; 1–5 select directly. Esc returns to the message list with its selection intact. Typing does not filter: `e`, `q`, `b` and `f` remain shortcuts in both lists. Jump picks the message in fullscreen, or draws an earlier-history page in scrollback when not drawn yet; otherwise scrollback says `/tui` can jump to it. Dialogs are live controls in scrollback and overlays in fullscreen ([timeline UI §4.6](../../docs/design/timeline-ui.md#46-timeline-jumping-to-a-message)) | | `/branch [TEXT]`, `/fork [TEXT]` | As `b` and `f` on a picked message, at the shown line's newest turn end: `/branch` puts `TEXT` in the composer as the new line's opening input; `/fork` opens a bordered confirmation naming the cut, with Cancel selected initially. Up/Down or Tab selects, Enter confirms, `1`/`y` forks and `2`/`n`/Esc cancels. Confirmation forks `main` there with `TEXT` in the fork's composer; cancellation restores the input or the Timeline action list | -| `/usage` | Reports main's context window from `session.context.usage`: estimated input tokens against the window, the output allowance and the compaction threshold; before a model has answered it says so, and a failed call is reported alone. With the reading it appends the cache read share of the last `model/usage` request on `main` (` · last request cached {percent}`), rounded down: `100%` only when every prompt token was a cache read, one decimal between `99%` and `100%`, an integer between `1%` and `99%`, `<1%` for a positive share below one percent, and `0%` for a request that reported no cache reads; the prompt token count includes cache writes, so a request that only writes the cache reads `0%`. The segment appears only once `main`'s history has finished loading, so a page that is not the last never reports its older request; after that it shows the newest request, whether it came from the history or a live event. It is absent when that request reported no cache read count or its counters cannot produce a share (cache reads above prompt tokens, or a zero prompt) | +| `/usage` | Reports the default branch's context window from `session.context.usage`: estimated input tokens against the window, the output allowance and the compaction threshold; before a model has answered it says so, and a failed call is reported alone. With the reading it appends the cache read share of the last `model/usage` request on that line (` · last request cached {percent}`), rounded down: `100%` only when every prompt token was a cache read, one decimal between `99%` and `100%`, an integer between `1%` and `99%`, `<1%` for a positive share below one percent, and `0%` for a request that reported no cache reads; the prompt token count includes cache writes, so a request that only writes the cache reads `0%`. The segment appears only once the default branch's history has finished loading, so a page that is not the last never reports its older request; after that it shows the newest request, whether it came from the history or a live event. It is absent when that request reported no cache read count or its counters cannot produce a share (cache reads above prompt tokens, or a zero prompt) | | `/compact` | Asks the shown line to compact its context with `session.context.compact`, during a run too. The matching Timeline row reports the work and its terminal outcome once; the RPC reply adds no second completed, skipped, failed or cancelled notice. Failures of the call itself and invalid replies are reported separately. A daemon without the method says it does not support context compaction | | `/rename TITLE`, `/rename --clear` | Sets, or clears, the shown Session's manual title with `session.rename` and reports the stored title or that the Session is untitled. Choosing `/rename` from the palette fills `/rename ` and waits; a bare `/rename` is refused with a notice and sends nothing, so `--clear` is the way to clear it without a title. The text is a command: it is never queued or submitted, also while a turn runs. With no Session shown it says so, and a Session that does not serve `session.rename` (`unknown_method`) reports that instead. The window title shows the stored title, or the first message's topic until the Session has one | | `/goal [OBJECTIVE \| set OBJECTIVE \| edit OBJECTIVE \| pause \| resume \| clear]` | Reads and writes the goal of the shown line through `session.goal.*`. Selecting it with Enter or Tab only fills `/goal ` for a separate submission. Bare `/goal` prints usage before the current goal/status, or before the no-goal notice (two lines when no goal is set). Writing forms start with the call, line and status, followed by the objective; `edited` found a live goal and changed only its objective, and a typed objective after a finished goal starts a new one. While the shown line follows a goal the status area carries `◎ goal active` or `◎ goal paused`. A daemon whose Session lists no `session.goal.set` says Goal is not available and calls nothing ([Goal](#goal)) | diff --git a/crates/dim-cli/src/configure.rs b/crates/dim-cli/src/configure.rs index b2e1eab4c7..af9bb8412c 100644 --- a/crates/dim-cli/src/configure.rs +++ b/crates/dim-cli/src/configure.rs @@ -6,7 +6,7 @@ use crate::{ client::Client, wire::{Configuration, ProviderCatalogSnapshot}, }; -use dim_agent_types::{DEFAULT_BRANCH_ID, ModelPreferences}; +use dim_agent_types::ModelPreferences; use serde::Deserialize; use serde_json::json; @@ -174,10 +174,12 @@ pub async fn preference( } /// Runs `text`, a configuration command line; `model` is the model the -/// Session adopted, which the preference commands read choices for. +/// Session adopted, which the preference commands read choices for, and +/// `branch` is the line the command acts on. pub async fn run( client: &mut Client, session_id: &str, + branch: &str, model: Option<&Configuration>, text: &str, ) -> Result { @@ -192,7 +194,7 @@ pub async fn run( let result: Configured = client .typed( "session.agent.update", - json!({"sessionId":session_id,"branchId":DEFAULT_BRANCH_ID,"agentId":agent_id}), + json!({"sessionId":session_id,"branchId":branch,"agentId":agent_id}), ) .await?; lines.push(format!( @@ -228,7 +230,7 @@ pub async fn run( let result: Configured = client .typed( "session.model.update", - json!({"sessionId":session_id,"branchId":DEFAULT_BRANCH_ID,"modelPreferences":preferences}), + json!({"sessionId":session_id,"branchId":branch,"modelPreferences":preferences}), ) .await?; lines.push(format!( diff --git a/crates/dim-cli/src/goal_command.rs b/crates/dim-cli/src/goal_command.rs index 068e52f5a4..942220ad3f 100644 --- a/crates/dim-cli/src/goal_command.rs +++ b/crates/dim-cli/src/goal_command.rs @@ -1,5 +1,6 @@ -//! `/goal` at the line-mode prompt: shows the goal in force on `main`, and -//! writes it through the methods Goal registers (cli-commands.md). +//! `/goal` at the line-mode prompt: shows the goal in force on the Session's +//! conversation, and writes it through the methods Goal registers +//! (cli-commands.md). use crate::{ Result, client::Client, @@ -7,7 +8,6 @@ use crate::{ goal, session::{Interrupts, settle}, }; -use dim_agent_types::DEFAULT_BRANCH_ID; /// What the prompt says when Ctrl+C arrives while a form is in flight. const NOTICE: &str = "Waiting for the goal command before accepting more input."; @@ -16,6 +16,7 @@ const NOTICE: &str = "Waiting for the goal command before accepting more input." pub async fn command( client: &mut Client, session_id: &str, + branch_id: &str, text: &str, display: &mut Display, interrupts: &mut Interrupts, @@ -32,13 +33,12 @@ pub async fn command( let mut state: dim_agent_types::GoalRead = client .typed( "session.goal.get", - serde_json::json!({"sessionId":session_id,"branchId":DEFAULT_BRANCH_ID}), + serde_json::json!({"sessionId":session_id,"branchId":branch_id}), ) .await?; let call = goal::call(&request, state.goal.as_ref()); if let Some(call) = call { - let mut params = - serde_json::json!({"sessionId": session_id, "branchId": DEFAULT_BRANCH_ID}); + let mut params = serde_json::json!({"sessionId": session_id, "branchId": branch_id}); if let Some(objective) = goal::objective(&request) { params["objective"] = serde_json::json!(objective); } @@ -51,7 +51,7 @@ pub async fn command( state = client .typed( "session.goal.get", - serde_json::json!({"sessionId":session_id,"branchId":DEFAULT_BRANCH_ID}), + serde_json::json!({"sessionId":session_id,"branchId":branch_id}), ) .await?; } @@ -60,7 +60,7 @@ pub async fn command( match settle(interrupts, NOTICE, operation).await? { Reply::Unavailable => display.record(goal::NOT_AVAILABLE)?, Reply::Done(call, goal) => { - for line in goal::report(DEFAULT_BRANCH_ID, call, goal.as_ref()) { + for line in goal::report(branch_id, call, goal.as_ref()) { display.record(&line)?; } } diff --git a/crates/dim-cli/src/model/session.rs b/crates/dim-cli/src/model/session.rs index ab14449d5c..763c55dc83 100644 --- a/crates/dim-cli/src/model/session.rs +++ b/crates/dim-cli/src/model/session.rs @@ -236,6 +236,13 @@ pub enum Command { projection_id: u64, branch_id: String, }, + /// Continue on a line: make it the Session's default branch and show it + /// (design §14). + SetDefaultLine { + session_id: String, + projection_id: u64, + branch_id: String, + }, /// Open a line of the displayed attachment at `at` of `parent`, with /// its opening input, and follow it in the side panel (timeline UI §4.7). OpenLine { @@ -1256,6 +1263,12 @@ pub enum Update { Stopped { error: Option, }, + /// `session.branch_set_default` refused the chosen line: the lines panel + /// shows the reason where the choice was made. + LineRefusal { + projection_id: u64, + text: String, + }, Exported { format: crate::export::Format, path: std::path::PathBuf, diff --git a/crates/dim-cli/src/model/view.rs b/crates/dim-cli/src/model/view.rs index 89016b6803..fb164ef37a 100644 --- a/crates/dim-cli/src/model/view.rs +++ b/crates/dim-cli/src/model/view.rs @@ -502,6 +502,9 @@ pub struct ViewSnapshot { /// `main` followed by this Session's lines, as the lines panel lists them. pub lines: Vec, pub unread_lines: std::collections::BTreeSet, + /// The line the Session's conversation is on (design §4): the lines panel + /// marks it and refuses to end it or an ancestor of it. + pub default_branch_id: String, pub focus: String, /// The line opened beside the shown one, while its panel is open. pub side: Option, diff --git a/crates/dim-cli/src/permission.rs b/crates/dim-cli/src/permission.rs index 8b3557f2cc..49022c6520 100644 --- a/crates/dim-cli/src/permission.rs +++ b/crates/dim-cli/src/permission.rs @@ -1,7 +1,7 @@ //! The permission operations of the CLI's clients, over existing App Server -//! methods: the `main` branch preset (`session.permission.get/update`), the -//! user's command rules (`permission.rules/set_rules`) and "always allow" -//! (F2 §5.4). Nothing here reads the terminal or prints: each operation +//! methods: the preset of the line the Session's conversation is on +//! (`session.permission.get/update`), the user's command rules +//! (`permission.rules/set_rules`) and "always allow" (F2 §5.4). Nothing here reads the terminal or prints: each operation //! returns what happened and the caller shows it. The App Server decides and //! enforces every call; a client only selects and writes. //! @@ -21,7 +21,7 @@ use crate::{ }; use dim_agent_types::{ ApprovalCallData, COMMAND_SEPARATORS, CommandMatch, CommandRule, CommandRuleDecision, - DEFAULT_BRANCH_ID, PermissionChangedData, PermissionPolicy, PermissionPreset, + PermissionChangedData, PermissionPolicy, PermissionPreset, }; use serde::{Deserialize, de::DeserializeOwned}; use serde_json::{Value, json}; @@ -60,6 +60,7 @@ pub fn creation_policy(options: &crate::args::Options) -> Option { pub async fn select_preset( client: &mut Client, session_id: &str, + branch_id: &str, selection: PresetSelection, ) -> Result { #[derive(Deserialize)] @@ -67,7 +68,7 @@ pub async fn select_preset( #[serde(rename = "version")] _version: u64, } - let mut state = read(client, session_id).await?; + let mut state = read(client, session_id, branch_id).await?; for _ in 0..ATTEMPTS { let preset = selection.resolve(state.policy.preset); if state.policy.preset == preset { @@ -76,11 +77,11 @@ pub async fn select_preset( state.policy.preset = preset; match client.typed::( "session.permission.update", - json!({"sessionId":session_id,"branchId":DEFAULT_BRANCH_ID,"expectedVersion":state.version,"policy":state.policy}), + json!({"sessionId":session_id,"branchId":branch_id,"expectedVersion":state.version,"policy":state.policy}), ).await { Ok(_) => return Ok(state.policy), Err(error) if client::app_error(&error) == Some("permission_conflict") => { - state = read(client, session_id).await?; + state = read(client, session_id, branch_id).await?; } Err(error) => return Err(error), } @@ -107,18 +108,18 @@ pub fn name(preset: PermissionPreset) -> &'static str { } } -/// The dispatched policy of `main` and the version a change must expect. +/// The dispatched policy of `branch_id` and the version a change must expect. #[derive(Deserialize)] pub struct State { pub version: u64, pub policy: PermissionPolicy, } -pub async fn read(client: &mut Client, session_id: &str) -> Result { +pub async fn read(client: &mut Client, session_id: &str, branch_id: &str) -> Result { client .typed( "session.permission.get", - json!({"sessionId":session_id,"branchId":DEFAULT_BRANCH_ID}), + json!({"sessionId":session_id,"branchId":branch_id}), ) .await } @@ -127,6 +128,7 @@ pub async fn read(client: &mut Client, session_id: &str) -> Result { async fn update( client: &mut Client, session_id: &str, + branch_id: &str, state: &State, preset: PermissionPreset, ) -> Result { @@ -141,7 +143,7 @@ async fn update( let updated: Updated = client .typed( "session.permission.update", - json!({"sessionId":session_id,"branchId":DEFAULT_BRANCH_ID,"expectedVersion":state.version,"policy":policy}), + json!({"sessionId":session_id,"branchId":branch_id,"expectedVersion":state.version,"policy":policy}), ) .await?; Ok(updated.version) @@ -149,46 +151,48 @@ async fn update( /// What [`switch`] did. pub enum Switch { - /// `main` already had the preset; nothing was written. + /// The line already had the preset; nothing was written. Unchanged, - /// `main` has the preset from this version on. + /// The line has the preset from this version on. Switched(u64), - /// `main` changed after the state the user saw; nothing was written. + /// The line changed after the state the user saw; nothing was written. /// Its state now. Conflict(State), } -/// Switches `main` from `seen`, the state the user decided on, so a version -/// conflict is reported with the state read after it, never retried. +/// Switches `branch_id` from `seen`, the state the user decided on, so a +/// version conflict is reported with the state read after it, never retried. pub async fn switch( client: &mut Client, session_id: &str, + branch_id: &str, seen: &State, preset: PermissionPreset, ) -> Result { if seen.policy.preset == preset { return Ok(Switch::Unchanged); } - match update(client, session_id, seen, preset).await { + match update(client, session_id, branch_id, seen, preset).await { Ok(version) => Ok(Switch::Switched(version)), Err(error) if client::app_error(&error) == Some("permission_conflict") => { - Ok(Switch::Conflict(read(client, session_id).await?)) + Ok(Switch::Conflict(read(client, session_id, branch_id).await?)) } Err(error) => Err(error), } } -/// Selects `preset` for `main` whatever it was before, as a startup choice -/// does: the preset does not depend on the read, so a version conflict reads -/// again and retries. +/// Selects `preset` for `branch_id` whatever it was before, as a startup +/// choice does: the preset does not depend on the read, so a version conflict +/// reads again and retries. pub async fn select( client: &mut Client, session_id: &str, + branch_id: &str, preset: PermissionPreset, ) -> Result { - let mut state = read(client, session_id).await?; + let mut state = read(client, session_id, branch_id).await?; for _ in 0..ATTEMPTS { - match switch(client, session_id, &state, preset).await? { + match switch(client, session_id, branch_id, &state, preset).await? { Switch::Conflict(current) => state = current, Switch::Unchanged | Switch::Switched(_) => { state.policy.preset = preset; diff --git a/crates/dim-cli/src/permission_command.rs b/crates/dim-cli/src/permission_command.rs index 4830634db7..367fe4da7d 100644 --- a/crates/dim-cli/src/permission_command.rs +++ b/crates/dim-cli/src/permission_command.rs @@ -64,18 +64,23 @@ fn require_rules(client: &Client) -> Result<()> { /// Runs `text`, an `/approvals` command line. `listing` is the rule list /// printed last, which `remove N` numbers from; its revision makes the write /// fail if the rules changed since. +#[expect( + clippy::too_many_arguments, + reason = "one parameter per piece of the prompt, the line and the listing it acts on" +)] pub async fn command( client: &mut Client, input: &mut Input, interrupts: &mut Interrupts, session_id: &str, + branch_id: &str, text: &str, display: &mut Display, listing: &mut Option, ) -> Result<()> { let words: Vec<_> = text.split_whitespace().collect(); match words[1..] { - [] => show(client, interrupts, session_id, display, listing).await, + [] => show(client, interrupts, session_id, branch_id, display, listing).await, ["remove", number] => { require_rules(client)?; let Some(seen) = listing.as_ref() else { @@ -107,7 +112,10 @@ pub async fn command( } [preset] if !matches!(preset, "remove" | "allow" | "deny") => { let preset = permission::parse_preset(preset)?; - switch(client, input, interrupts, session_id, preset, display).await + switch( + client, input, interrupts, session_id, branch_id, preset, display, + ) + .await } _ => { let Some((decision, matching, command)) = permission::parse_rule_words(&words[1..]) @@ -132,11 +140,17 @@ async fn show( client: &mut Client, interrupts: &mut Interrupts, session_id: &str, + branch_id: &str, display: &mut Display, listing: &mut Option, ) -> Result<()> { if client.supports(&PRESET_METHODS) { - let state = settle(interrupts, NOTICE, permission::read(client, session_id)).await?; + let state = settle( + interrupts, + NOTICE, + permission::read(client, session_id, branch_id), + ) + .await?; print_state(display, &state)?; } else { display.record("Permission presets: this daemon does not provide them")?; @@ -158,21 +172,27 @@ async fn switch( input: &mut Input, interrupts: &mut Interrupts, session_id: &str, + branch_id: &str, preset: PermissionPreset, display: &mut Display, ) -> Result<()> { if !client.supports(&PRESET_METHODS) { return Err("This daemon cannot change the permission preset".into()); } - let mut seen = settle(interrupts, NOTICE, permission::read(client, session_id)).await?; + let mut seen = settle( + interrupts, + NOTICE, + permission::read(client, session_id, branch_id), + ) + .await?; let name = permission::name(preset); if seen.policy.preset == preset { - display.record(&format!("Preset (main branch) is already {name}"))?; + display.record(&format!("Preset is already {name}"))?; return print_state(display, &seen); } if preset == PermissionPreset::FullAccess { display.record("Full access removes path limits and skips tool questions. Explicit denies and process isolation still apply.")?; - input.prompt("Switch the main branch to full-access? [y/N] ")?; + input.prompt("Switch to full-access? [y/N] ")?; let line = tokio::select! { biased; _ = interrupts.recv() => { @@ -193,15 +213,15 @@ async fn switch( match settle( interrupts, NOTICE, - permission::switch(client, session_id, &seen, preset), + permission::switch(client, session_id, branch_id, &seen, preset), ) .await? { - Switch::Unchanged => display.record(&format!("Preset (main branch) is already {name}"))?, + Switch::Unchanged => display.record(&format!("Preset is already {name}"))?, Switch::Switched(version) => { display.permission_seen = display.permission_seen.max(version); display.record(&format!( - "Preset (main branch): {name}. Child branches and members created later from main inherit it; existing branches and members keep their policies." + "Preset: {name}. Lines and members created later from this line inherit it; existing lines and members keep their policies." ))?; seen.policy.preset = preset; } diff --git a/crates/dim-cli/src/question/line.rs b/crates/dim-cli/src/question/line.rs index 06d58aeab9..1d89b3a815 100644 --- a/crates/dim-cli/src/question/line.rs +++ b/crates/dim-cli/src/question/line.rs @@ -91,9 +91,14 @@ fn key(call: &Call) -> (String, String, String) { } impl Questions { - /// Starts the main branch inventory independently of its transcript window. - pub async fn start(&mut self, client: &mut Client, session_id: &str) -> Result<()> { - self.read(client, session_id, ROOT_BRANCH_ID).await + /// Starts the conversation's inventory independently of its transcript window. + pub async fn start( + &mut self, + client: &mut Client, + session_id: &str, + branch_id: &str, + ) -> Result<()> { + self.read(client, session_id, branch_id).await } /// Whether a question prompt owns the terminal input. diff --git a/crates/dim-cli/src/session.rs b/crates/dim-cli/src/session.rs index aa551f7487..581033b6d0 100644 --- a/crates/dim-cli/src/session.rs +++ b/crates/dim-cli/src/session.rs @@ -14,7 +14,7 @@ use crate::{ question::line::Questions, }; use dim_agent_types::{ - ApprovalCallData, ContentBlock, DEFAULT_BRANCH_ID, PermissionPolicy, UserInput, + ApprovalCallData, ContentBlock, PermissionPolicy, ROOT_BRANCH_ID, UserInput, }; use serde::Deserialize; use serde_json::{Value, json}; @@ -107,6 +107,7 @@ struct RecordingError { async fn start_shell( client: &mut Client, session_id: &str, + conversation: &str, text: &str, display: &mut Display, ) -> Result> { @@ -119,7 +120,7 @@ async fn start_shell( return Ok(None); } let run_id = uuid::Uuid::new_v4().to_string(); - let request = client.send("shell.run", json!({"sessionId":session_id,"branchId":DEFAULT_BRANCH_ID,"runId":run_id,"command":command,"mode":mode})).await?; + let request = client.send("shell.run", json!({"sessionId":session_id,"branchId":conversation,"runId":run_id,"command":command,"mode":mode})).await?; display.record(&format!("[shell started] {mode}"))?; Ok(Some(ShellRun { request: Some(request), @@ -198,6 +199,20 @@ pub(crate) async fn settle( } } +/// The line the Session's conversation is on: the default branch the daemon +/// reports, or the root of a Session that has not moved it (design §4, §14). +async fn conversation(client: &mut Client, session_id: &str) -> Result { + if !client.supports(&["session.branches"]) { + return Ok(ROOT_BRANCH_ID.to_owned()); + } + let directory: dim_client::wire::BranchDirectory = client + .typed("session.branches", json!({"sessionId": session_id})) + .await?; + Ok(directory + .default_branch_id + .unwrap_or_else(|| ROOT_BRANCH_ID.to_owned())) +} + pub async fn chat( client: &mut Client, options: &Options, @@ -254,6 +269,7 @@ pub async fn chat( } created.session_id }; + let conversation = conversation(client, &session_id).await?; let selected = if let (Some(preset), Some(_)) = (options.permission, &options.resume) { if !client.supports(&permission::PRESET_METHODS) { return Err( @@ -261,7 +277,7 @@ pub async fn chat( ); } Some( - permission::select(client, &session_id, preset) + permission::select(client, &session_id, &conversation, preset) .await .map_err(|error| { crate::client::resume_failure("Cannot set the permission preset", error) @@ -287,7 +303,7 @@ pub async fn chat( ..Default::default() })), (None, None) if interactive && client.supports(&["session.permission.get"]) => Some( - permission::read(client, &session_id) + permission::read(client, &session_id, &conversation) .await .map(|state| state.policy), ), @@ -321,14 +337,23 @@ pub async fn chat( capability_snapshot: attached.capability_snapshot, model_preferences: attached.model_preferences, }); - display.model_through = attached.sequence; - display.cursor = window::read(client, &session_id, &mut display).await?; - questions.start(client, &session_id).await?; + // `attached.sequence` is the root's sequence, which is the + // conversation's own cursor only while the conversation is the root; a + // line's configuration arrives with its history until the App Server + // reports a branch-qualified cursor (design §14). + display.model_through = if conversation == ROOT_BRANCH_ID { + attached.sequence + } else { + 0 + }; + display.cursor = window::read(client, &session_id, &conversation, &mut display).await?; + questions.start(client, &session_id, &conversation).await?; display.failed = false; display.muted = false; let mut code = wait_turn( client, &session_id, + &conversation, None, &mut display, &mut input, @@ -351,6 +376,7 @@ pub async fn chat( return wait_turn( client, &session_id, + &conversation, Some(Submission::Message(UserInput { content })), &mut display, &mut input, @@ -409,7 +435,7 @@ pub async fn chat( let result = settle( &mut interrupts, "Waiting for configuration result before accepting more input.", - configure(client, &session_id, text, &mut display), + configure(client, &session_id, &conversation, text, &mut display), ) .await; if let Err(error) = result { @@ -425,6 +451,7 @@ pub async fn chat( reader, &mut interrupts, &session_id, + &conversation, text, &mut display, &mut listing, @@ -441,6 +468,7 @@ pub async fn chat( if let Err(error) = goal_command::command( client, &session_id, + &conversation, text, &mut display, &mut interrupts, @@ -457,7 +485,7 @@ pub async fn chat( if let Err(error) = loop_command::command( client, &session_id, - DEFAULT_BRANCH_ID, + &conversation, text, &mut display, &mut interrupts, @@ -478,7 +506,7 @@ pub async fn chat( continue; } Some("/earlier") => { - if let Err(error) = window::earlier(client, &session_id, &mut display).await { display.record(&format!("Error: {error}"))?; } + if let Err(error) = window::earlier(client, &session_id, &conversation, &mut display).await { display.record(&format!("Error: {error}"))?; } draft.clear(); continue; } @@ -560,6 +588,7 @@ pub async fn chat( code = match wait_turn( client, &session_id, + &conversation, Some(submission), &mut display, &mut input, @@ -623,12 +652,13 @@ pub async fn read_history( after: u64, sink: &mut impl HistorySink, ) -> Result { - read_history_mode(client, session_id, after, sink, false).await + read_history_mode(client, session_id, ROOT_BRANCH_ID, after, sink, false).await } async fn read_history_mode( client: &mut Client, session_id: &str, + branch_id: &str, mut after: u64, sink: &mut impl HistorySink, summaries: bool, @@ -636,7 +666,7 @@ async fn read_history_mode( let mut through = None; loop { let mut params = - json!({"sessionId":session_id,"branchId":DEFAULT_BRANCH_ID,"after":after,"limit":256}); + json!({"sessionId":session_id,"branchId":branch_id,"after":after,"limit":256}); if let Some(through) = through { params["through"] = json!(through); } @@ -666,6 +696,7 @@ async fn read_history_mode( async fn configure( client: &mut Client, session_id: &str, + conversation: &str, text: &str, display: &mut Display, ) -> Result<()> { @@ -676,6 +707,7 @@ async fn configure( display.cursor = read_history_mode( client, session_id, + conversation, display.cursor, &mut |value| display.event(serde_json::from_value(value)?, true), summaries, @@ -683,7 +715,14 @@ async fn configure( .await?; display.failed = false; } - let report = configure::run(client, session_id, display.model.as_ref(), text).await?; + let report = configure::run( + client, + session_id, + conversation, + display.model.as_ref(), + text, + ) + .await?; for line in &report.lines { display.record(line)?; } @@ -691,6 +730,7 @@ async fn configure( display.cursor = read_history_mode( client, session_id, + conversation, display.cursor, &mut |value| display.event(serde_json::from_value(value)?, true), summaries, @@ -708,6 +748,7 @@ async fn configure( async fn wait_turn( client: &mut Client, session_id: &str, + conversation: &str, submission: Option, display: &mut Display, input: &mut Option, @@ -719,7 +760,7 @@ async fn wait_turn( let mut shell = None; let mut submit = match submission { Some(Submission::Shell(text)) => { - shell = start_shell(client, session_id, &text, display).await?; + shell = start_shell(client, session_id, conversation, &text, display).await?; if let Some(draft) = draft.take() { draft.clear(); } @@ -727,7 +768,7 @@ async fn wait_turn( } Some(Submission::Message(mut user)) => { crate::images::import(client, session_id, &mut user.content).await?; - let mut params = json!({"sessionId":session_id,"branchId":DEFAULT_BRANCH_ID,"submissionId":uuid::Uuid::new_v4().to_string(),"mode":"queue"}); + let mut params = json!({"sessionId":session_id,"branchId":conversation,"submissionId":uuid::Uuid::new_v4().to_string(),"mode":"queue"}); match user.content.as_slice() { [ContentBlock::Text { text }] => params["text"] = json!(text), _ => params["user"] = json!(user), @@ -741,7 +782,7 @@ async fn wait_turn( client .send( "session.idle", - json!({"sessionId":session_id,"branchId":DEFAULT_BRANCH_ID}), + json!({"sessionId":session_id,"branchId":conversation}), ) .await?, ) @@ -882,7 +923,7 @@ async fn wait_turn( client .send( "session.stop", - json!({"sessionId":session_id,"branchId":DEFAULT_BRANCH_ID,"reason":reason}), + json!({"sessionId":session_id,"branchId":conversation,"reason":reason}), ) .await?, ); @@ -925,7 +966,7 @@ async fn wait_turn( code = 130; approvals.clear(); prompted = false; questions.interrupt(client, session_id).await?; - stop = Some(client.send("session.stop", json!({"sessionId":session_id,"branchId":DEFAULT_BRANCH_ID,"reason":"CLI interrupted"})).await?); + stop = Some(client.send("session.stop", json!({"sessionId":session_id,"branchId":conversation,"reason":"CLI interrupted"})).await?); continue; } line = async { @@ -996,7 +1037,9 @@ async fn wait_turn( if shell.is_some() { display.record("[shell busy] This caller already has a pending command")?; } else { - shell = start_shell(client, session_id, text, display).await?; + shell = + start_shell(client, session_id, conversation, text, display) + .await?; } } else if !text.trim().is_empty() { display.record("[busy] Wait for the prompt to send a message; !command and !!command remain available")?; @@ -1014,7 +1057,7 @@ async fn wait_turn( } if line.is_none() && stop.is_none() && settled.is_none() { code = 130; - stop = Some(client.send("session.stop", json!({"sessionId":session_id,"branchId":DEFAULT_BRANCH_ID,"reason":"CLI input closed"})).await?); + stop = Some(client.send("session.stop", json!({"sessionId":session_id,"branchId":conversation,"reason":"CLI input closed"})).await?); } continue; } @@ -1124,7 +1167,7 @@ async fn wait_turn( client .send( "session.idle", - json!({"sessionId":session_id,"branchId":DEFAULT_BRANCH_ID}), + json!({"sessionId":session_id,"branchId":conversation}), ) .await?, ); @@ -1263,7 +1306,7 @@ async fn wait_turn( display.record("Interactive approval required; the operation was denied. Rerun in a terminal to review it")?; approval_replies.insert(client.send("approval.respond", json!({"sessionId":session_id,"branchId":approval.branch_id,"requestId":approval.request_id,"decision":"deny"})).await?); code = 3; - stop = Some(client.send("session.stop", json!({"sessionId":session_id,"branchId":DEFAULT_BRANCH_ID,"reason":"Interactive approval required"})).await?); + stop = Some(client.send("session.stop", json!({"sessionId":session_id,"branchId":conversation,"reason":"Interactive approval required"})).await?); } else { approvals.push_back(approval); } @@ -1348,13 +1391,18 @@ async fn wait_turn( display.shell_progress(&progress.text)?; } notice @ Message::Notice { .. } => { - render(notice, session_id, display)?; + render(notice, session_id, conversation, display)?; } } } } -fn render(notice: Message, session_id: &str, display: &mut Display) -> Result<()> { +fn render( + notice: Message, + session_id: &str, + conversation: &str, + display: &mut Display, +) -> Result<()> { let Message::Notice { method, params } = notice else { unreachable!() }; @@ -1365,7 +1413,7 @@ fn render(notice: Message, session_id: &str, display: &mut Display) -> Result<() } let event = ¶ms["event"]; if method == "session.event" - && params["branchId"] == DEFAULT_BRANCH_ID + && params["branchId"] == conversation && event["type"] == "turn" && event["name"] == "end" && event["data"]["status"] == "failed" @@ -1385,12 +1433,12 @@ fn render(notice: Message, session_id: &str, display: &mut Display) -> Result<() } else { decode(params, &method)? }; - if notice.session_id == session_id && notice.branch_id == DEFAULT_BRANCH_ID { + if notice.session_id == session_id && notice.branch_id == conversation { if let Some((sequence, policy)) = changed && sequence > display.cursor.max(display.permission_seen) { display.record(&format!( - "[permission] main branch preset: {}", + "[permission] preset: {}", permission::name(policy.preset) ))?; display.permission_seen = sequence; @@ -1400,7 +1448,7 @@ fn render(notice: Message, session_id: &str, display: &mut Display) -> Result<() } "session.model.progress" => { let notice: Progress = decode(params, &method)?; - if notice.session_id == session_id && notice.branch_id == DEFAULT_BRANCH_ID { + if notice.session_id == session_id && notice.branch_id == conversation { display.progress(notice)?; } } diff --git a/crates/dim-cli/src/session/window.rs b/crates/dim-cli/src/session/window.rs index 4751a6bfc2..3c80a7d294 100644 --- a/crates/dim-cli/src/session/window.rs +++ b/crates/dim-cli/src/session/window.rs @@ -1,11 +1,11 @@ use crate::{Result, client::Client, display::Display, wire::HistoryWindow}; -use dim_agent_types::DEFAULT_BRANCH_ID; use dim_client::window::Window; use dim_client::wire::DisplayPage; pub(super) async fn read( client: &mut Client, session_id: &str, + conversation: &str, display: &mut Display, ) -> Result { if !client.supports(&["session.history.latestTurn"]) { @@ -17,7 +17,7 @@ pub(super) async fn read( loop { let params = window.params_with_display( session_id, - DEFAULT_BRANCH_ID, + conversation, !display.json && client.offers("session.history.display.tail"), !display.json && client.offers("session.history.display.transcript"), ); @@ -57,6 +57,7 @@ pub(super) async fn read( pub(super) async fn earlier( client: &mut Client, session_id: &str, + conversation: &str, display: &mut Display, ) -> Result<()> { let Some(before) = display.history_before else { @@ -66,7 +67,7 @@ pub(super) async fn earlier( loop { let params = window.params_with_display( session_id, - DEFAULT_BRANCH_ID, + conversation, !display.json && client.offers("session.history.display.tail"), !display.json && client.offers("session.history.display.transcript"), ); diff --git a/crates/dim-cli/src/session_host.rs b/crates/dim-cli/src/session_host.rs index 6ba2ccf94d..15bf36f6fd 100644 --- a/crates/dim-cli/src/session_host.rs +++ b/crates/dim-cli/src/session_host.rs @@ -286,6 +286,9 @@ struct Worker { cursors: std::collections::HashMap, tool_origins: std::collections::VecDeque<(String, String, String)>, projection_id: u64, + /// The line the Session's conversation is on: the target a request that + /// names no line reaches, and the line the top bar folds (design §4, §14). + default_branch: String, focus: String, /// The line the side panel follows. side: Option, @@ -726,6 +729,7 @@ impl Worker { cursors: Default::default(), tool_origins: Default::default(), projection_id: 0, + default_branch: ROOT_BRANCH_ID.into(), focus: DEFAULT_BRANCH_ID.into(), side: None, lines: Default::default(), @@ -781,6 +785,21 @@ impl Worker { scope_cwd(self.options.workspace().as_str(), scope) } + /// The line a Session's conversation is on: the default branch the daemon + /// reports, or the root of a Session that has not moved it (design §4). + async fn conversation_of(&mut self, session_id: &str) -> crate::Result { + if !self.client.supports(&["session.branches"]) { + return Ok(ROOT_BRANCH_ID.into()); + } + let directory: dim_client::wire::BranchDirectory = self + .client + .typed("session.branches", json!({"sessionId": session_id})) + .await?; + Ok(directory + .default_branch_id + .unwrap_or_else(|| ROOT_BRANCH_ID.into())) + } + /// Resumes the requested Session; an ordinary startup stays at Home. async fn open(&mut self) -> crate::Result<()> { if let Some(id) = self.options.resume.clone() { @@ -791,7 +810,8 @@ impl Worker { .into(), ); } - permission::select(&mut self.client, &id, preset) + let branch = self.conversation_of(&id).await?; + permission::select(&mut self.client, &id, &branch, preset) .await .map_err(|error| { client::resume_failure("Cannot set the permission preset", error) @@ -973,7 +993,6 @@ impl Worker { }; // Without a record, find the model in the catalog: this is the only // caller of `list()` besides `/resume`, and only for an older server. - self.model_through = attached.sequence; let model_preferences = attached.model_preferences; let model = match attached.model.or(model) { Some(model) => model, @@ -1002,19 +1021,21 @@ impl Worker { self.model = Some(configuration.clone()); self.preview = None; self.pending = None; - self.discover_branch(DEFAULT_BRANCH_ID); - if self.client.offers("session.history.display.transcript") { - self.task_history - .get_mut(DEFAULT_BRANCH_ID) - .unwrap() - .window - .through = Some(attached.sequence); - } + // The Session's conversation starts where its default branch is + // (design §4): the directory names that line. `attached.sequence` is + // the root's sequence, so it is the conversation's own cursor only + // while the conversation is the root; a line's window and model fold + // start from its own history until the App Server reports a + // branch-qualified cursor (§14). + self.default_branch = ROOT_BRANCH_ID.into(); if self.client.supports(&["session.branches"]) { let directory: dim_client::wire::BranchDirectory = self .client .typed("session.branches", json!({"sessionId":self.session_id})) .await?; + self.default_branch = directory + .default_branch_id + .unwrap_or_else(|| ROOT_BRANCH_ID.into()); for entry in directory.branches { self.projection.directory(&entry); if entry.state == "ended" { @@ -1026,6 +1047,21 @@ impl Worker { } } } + self.focus = self.default_branch.clone(); + let conversation_line = self.focus.clone(); + self.discover_branch(&conversation_line); + let conversation_cursor = + (self.default_branch == ROOT_BRANCH_ID).then_some(attached.sequence); + if self.client.offers("session.history.display.transcript") + && let Some(cursor) = conversation_cursor + { + self.task_history + .get_mut(&conversation_line) + .expect("the conversation is discovered") + .window + .through = Some(cursor); + } + self.model_through = conversation_cursor.unwrap_or(0); self.poll_task_history().await?; self.send(Update::Ready(configuration)); self.send(catalog_features(None)); @@ -1046,7 +1082,7 @@ impl Worker { if self.client.supports(&permission::PRESET_METHODS) { reads.push(( "session.permission.get", - json!({"sessionId":session_id,"branchId":DEFAULT_BRANCH_ID}), + json!({"sessionId":session_id,"branchId":self.default_branch}), OpeningRead::Permissions, )); } @@ -1304,6 +1340,14 @@ impl Worker { self.side = None; self.publish(); } + Command::SetDefaultLine { + session_id, + projection_id, + branch_id, + } => { + self.set_default_line(session_id, projection_id, branch_id) + .await; + } Command::EndLine { session_id, projection_id, @@ -1547,8 +1591,13 @@ impl Worker { Command::Resume(session_id) => { if let Some(preset) = self.options.permission && self.client.supports(&permission::PRESET_METHODS) - && let Err(error) = - permission::select(&mut self.client, &session_id, preset).await + && let Err(error) = permission::select( + &mut self.client, + &session_id, + &self.default_branch, + preset, + ) + .await { self.send(Update::Notice(format!( "The permission preset was not applied: {error}" @@ -1967,9 +2016,14 @@ impl Worker { }) } else { let session_id = self.session_id.clone(); - permission::select_preset(&mut self.client, &session_id, change) - .await - .map_err(|error| error.to_string()) + permission::select_preset( + &mut self.client, + &session_id, + &self.default_branch, + change, + ) + .await + .map_err(|error| error.to_string()) }; if let Ok(policy) = &result { self.options.permission = Some(policy.preset); @@ -2151,8 +2205,14 @@ impl Worker { return Ok(()); } let model = self.model.clone(); - let result = - configure::run(&mut self.client, &self.session_id, model.as_ref(), &text).await; + let result = configure::run( + &mut self.client, + &self.session_id, + &self.focus, + model.as_ref(), + &text, + ) + .await; if matches!(text.as_str(), "/effort" | "/reasoning") { self.send(Update::EffortChoices( result @@ -2194,9 +2254,10 @@ impl Worker { branch_id, stop_turn, } => { - let also_session_line = stop_turn && branch_id != DEFAULT_BRANCH_ID; + let session_line = self.default_branch.as_str(); + let also_session_line = stop_turn && branch_id != session_line; for branch in std::iter::once(branch_id.as_str()) - .chain(also_session_line.then_some(DEFAULT_BRANCH_ID)) + .chain(also_session_line.then_some(session_line)) { let result = self.client.rpc("session.stop", json!({"sessionId":session_id,"branchId":branch,"reason":crate::model::view::INTERRUPT_REASON})).await; self.report_failure(result); @@ -2304,7 +2365,6 @@ impl Worker { } let params = json!({ "sessionId": member_id, - "branchId": DEFAULT_BRANCH_ID, "reason": "stopped by the user", }); let result = self.client.rpc("session.stop", params).await; @@ -2380,7 +2440,7 @@ impl Worker { .client .send( "session.context.usage", - json!({"sessionId": self.session_id, "branchId": DEFAULT_BRANCH_ID}), + json!({"sessionId": self.session_id, "branchId": self.default_branch.clone()}), ) .await { @@ -2742,14 +2802,14 @@ impl Worker { if notice.session_id == self.session_id { // Live only: history pages arrive as `session.history` // replies applied by `apply`, so they spend no read. - if notice.branch_id == DEFAULT_BRANCH_ID + if notice.branch_id == self.default_branch && matches!(notice.event.content, EventContent::ModelEnd(_)) { self.context_stale = true; } let completed = match ¬ice.event.content { EventContent::TurnEnd(data) - if notice.branch_id == DEFAULT_BRANCH_ID + if notice.branch_id == self.default_branch && matches!( data.outcome, dim_agent_types::TurnOutcome::Completed { .. } @@ -2799,7 +2859,8 @@ impl Worker { { transcript.set_running(notice.running); } - self.context_stale |= notice.branch_id == DEFAULT_BRANCH_ID && !notice.running; + self.context_stale |= + notice.branch_id == self.default_branch && !notice.running; self.changed(); } else if notice.branch_id == DEFAULT_BRANCH_ID && self.observes_member(¬ice.session_id) @@ -3855,7 +3916,7 @@ impl Worker { let command = text.split_whitespace().next().unwrap_or_default(); let bare_effort = matches!(text, "/effort" | "/reasoning"); if command == "/agent" { - match configure::run(&mut self.client, "", None, text).await { + match configure::run(&mut self.client, "", ROOT_BRANCH_ID, None, text).await { Ok(report) => self.report(report.lines.join("\n"), false), Err(error) => self.report(error.to_string(), true), } @@ -4004,7 +4065,7 @@ impl Worker { model } else { let target = (provider_id.clone(), model_id.clone()); - let params = json!({"sessionId":self.session_id,"branchId":DEFAULT_BRANCH_ID,"providerId":provider_id,"modelId":model_id}); + let params = json!({"sessionId":self.session_id,"branchId":self.focus,"providerId":provider_id,"modelId":model_id}); let updated: Updated = match self.client.typed("session.model.update", params).await { Ok(updated) => updated, Err(error) => { @@ -4462,7 +4523,7 @@ impl Worker { let mut line = usage.describe(); let loaded = self .task_history - .get(DEFAULT_BRANCH_ID) + .get(&self.default_branch) .is_some_and(|history| history.done); if let Some(cached) = self .last_usage @@ -4683,7 +4744,7 @@ impl Worker { } fn fold(&mut self, branch_id: &str, event: Event, replayed: bool) { - if branch_id == DEFAULT_BRANCH_ID + if branch_id == self.default_branch && event.sequence > self.model_through && let EventContent::Configuration(configuration) = &event.content { @@ -4720,14 +4781,14 @@ impl Worker { } *cursor = event.sequence; self.discover_workflow(branch_id, &event); - if branch_id == DEFAULT_BRANCH_ID + if branch_id == self.default_branch && let EventContent::PermissionChanged(data) = &event.content { self.opening_reads .retain(|(_, kind)| !matches!(kind, OpeningRead::Permissions)); self.send(Update::Permissions(Ok(data.policy.clone()))); } - if branch_id == DEFAULT_BRANCH_ID + if branch_id == self.default_branch && matches!( event.content, EventContent::Compaction(_) | EventContent::CompactionSummary(_) @@ -4735,7 +4796,7 @@ impl Worker { { self.context_stale = true; } - if branch_id == DEFAULT_BRANCH_ID + if branch_id == self.default_branch && let EventContent::ModelUsage(data) = &event.content { self.last_usage = Some(LastUsage { @@ -4826,6 +4887,47 @@ impl Worker { lines } + /// `session.branch_set_default`, then shows the line the Session's + /// conversation is on now; a refusal goes back to the panel that asked + /// (design §14). + async fn set_default_line( + &mut self, + session_id: String, + projection_id: u64, + branch_id: String, + ) { + if !self.attached(&session_id, projection_id) { + self.send(Update::Notice( + "Session attachment changed; reopen the lines before choosing one".into(), + )); + return; + } + #[derive(Deserialize)] + #[serde(rename_all = "camelCase")] + struct Reply { + default_branch_id: String, + } + match self + .client + .typed::( + "session.branch_set_default", + json!({"sessionId": self.session_id, "branchId": branch_id}), + ) + .await + { + Ok(reply) => { + self.default_branch = reply.default_branch_id; + self.side = None; + let line = self.default_branch.clone(); + self.focus_line(line).await; + } + Err(error) => self.send(Update::LineRefusal { + projection_id, + text: error.to_string(), + }), + } + } + async fn focus_line(&mut self, line: String) { if line != ROOT_BRANCH_ID && !self.task_history.contains_key(&line) { self.send(Update::Notice(format!("No line {line} in this session"))); @@ -4914,6 +5016,7 @@ impl Worker { .map_or_else(Vec::new, |line| line.projection.rows().to_vec()), }) }); + snapshot.default_branch_id = self.default_branch.clone(); snapshot.focus = self.focus.clone(); snapshot.main_running = self.projection.running(); snapshot.main_topic = self.projection.first_message(); @@ -5044,7 +5147,9 @@ pub(crate) async fn adopt_startup( if options.startup.is_none() && options.effort.is_none() && options.model.is_none() { return Ok(()); } - let mut params = json!({"sessionId":session_id,"branchId":DEFAULT_BRANCH_ID}); + // The update names no line: a resume adopts the startup configuration on + // the Session's default branch, resolved once by the server (design §9). + let mut params = json!({"sessionId":session_id}); if let Some(startup) = &options.startup { params["startup"] = startup.clone(); } diff --git a/crates/dim-cli/src/session_host/tasks.rs b/crates/dim-cli/src/session_host/tasks.rs index fce7881f8c..51e12970d9 100644 --- a/crates/dim-cli/src/session_host/tasks.rs +++ b/crates/dim-cli/src/session_host/tasks.rs @@ -2,7 +2,7 @@ use std::collections::{HashSet, VecDeque}; -use dim_agent_types::BranchCreateFailedData; +use dim_agent_types::{BranchCreateFailedData, ROOT_BRANCH_ID}; use super::*; use crate::model::view::{MemberTarget, TaskKind}; @@ -95,6 +95,7 @@ impl Worker { self.context_stale = false; self.cursors.clear(); self.tool_origins.clear(); + self.default_branch = ROOT_BRANCH_ID.into(); self.focus = DEFAULT_BRANCH_ID.into(); self.side = None; self.lines.clear(); @@ -208,7 +209,7 @@ impl Worker { .expect("discovered branch"); history.ended |= matches!(event.content, EventContent::BranchEnd(_)); let mut unread_changed = false; - if branch_id != DEFAULT_BRANCH_ID + if branch_id != self.default_branch && event.sequence > applied.max(history.latest_reply) && matches!(&event.content, EventContent::Text(data) if !data.delta.trim().is_empty()) { @@ -365,7 +366,7 @@ impl Worker { "This daemon cannot read a bounded transcript window; update the daemon".into(), ); } - let (stage, method, params) = if branch_id != DEFAULT_BRANCH_ID + let (stage, method, params) = if branch_id != self.default_branch && !self.lines.contains_key(&branch_id) && !self.task_history[&branch_id].window_complete { @@ -596,7 +597,7 @@ impl Worker { if history.earlier == EarlierRead::Reading { history.earlier = EarlierRead::Failed; } - let fatal = request.branch_id == DEFAULT_BRANCH_ID && !history.done; + let fatal = request.branch_id == self.default_branch && !history.done; let report = crate::report::Captured::observed( crate::report::Operation::SessionRead, code.as_deref(), @@ -792,7 +793,7 @@ impl Worker { format!("member {session_id}"), "session.stop", json!({ - "sessionId": session_id, "branchId": DEFAULT_BRANCH_ID, "reason": "stopped by the user", + "sessionId": session_id, "reason": "stopped by the user", }), ), TaskKind::Member(MemberTarget::Starting | MemberTarget::Provider) => { diff --git a/crates/dim-cli/src/ui/i18n/de/chrome.rs b/crates/dim-cli/src/ui/i18n/de/chrome.rs index a05ffa9bc3..b10b6f15a8 100644 --- a/crates/dim-cli/src/ui/i18n/de/chrome.rs +++ b/crates/dim-cli/src/ui/i18n/de/chrome.rs @@ -41,8 +41,19 @@ pub fn lookup(english: &str) -> Option<&'static str> { } "Running" => "Läuft", "Lines" => "Zweige", - "Enter show the line · x end it · Esc close" => { - "Enter Zweig anzeigen · x beenden · Esc schließen" + "Enter show · p continue from here · x end it · Esc close" => { + "Enter anzeigen · p hier fortsetzen · x beenden · Esc schließen" + } + "Main line" => "Hauptzweig", + "Start" => "Ursprung", + "the default branch and the lines it continues from stay open; continue on another line first" => { + "Der Standardzweig und die Zweige, aus denen er fortgeführt wird, bleiben offen; fahre zuerst auf einem anderen Zweig fort" + } + "The old default branch stays open and keeps the lines it opened. The root keeps its own right to open a line in either direction." => { + "Der bisherige Standardzweig bleibt offen und behält die Zweige, die er geöffnet hat. Die Wurzel behält ihr eigenes Recht, in beide Richtungen einen Zweig zu öffnen." + } + "The old default branch stays open and keeps the lines it opened. The two lines swap the right to open a line." => { + "Der bisherige Standardzweig bleibt offen und behält die Zweige, die er geöffnet hat. Die beiden Zweige tauschen das Recht, einen zu öffnen." } "This session has no lines." => "Diese Sitzung hat keine Zweige.", "No matching lines." => "Keine passenden Zweige.", diff --git a/crates/dim-cli/src/ui/i18n/es/chrome.rs b/crates/dim-cli/src/ui/i18n/es/chrome.rs index c73a9ac8fb..b57b2d7586 100644 --- a/crates/dim-cli/src/ui/i18n/es/chrome.rs +++ b/crates/dim-cli/src/ui/i18n/es/chrome.rs @@ -39,8 +39,19 @@ pub fn lookup(english: &str) -> Option<&'static str> { } "Running" => "En curso", "Lines" => "Líneas", - "Enter show the line · x end it · Esc close" => { - "Enter ver la línea · x terminarla · Esc cerrar" + "Enter show · p continue from here · x end it · Esc close" => { + "Enter ver · p continuar desde aquí · x terminar · Esc cerrar" + } + "Main line" => "línea principal", + "Start" => "inicio", + "the default branch and the lines it continues from stay open; continue on another line first" => { + "La rama predeterminada y las líneas de las que continúa no se cierran; continúa primero en otra línea" + } + "The old default branch stays open and keeps the lines it opened. The root keeps its own right to open a line in either direction." => { + "La rama predeterminada anterior sigue abierta y conserva las líneas que abrió. La raíz conserva su propio derecho a abrir una línea en ambas direcciones." + } + "The old default branch stays open and keeps the lines it opened. The two lines swap the right to open a line." => { + "La rama predeterminada anterior sigue abierta y conserva las líneas que abrió. Las dos líneas intercambian el derecho a abrir una." } "This session has no lines." => "Esta sesión no tiene líneas.", "No matching lines." => "Ninguna línea coincide.", diff --git a/crates/dim-cli/src/ui/i18n/fr/chrome.rs b/crates/dim-cli/src/ui/i18n/fr/chrome.rs index 9c2f88f26d..376b35a6a8 100644 --- a/crates/dim-cli/src/ui/i18n/fr/chrome.rs +++ b/crates/dim-cli/src/ui/i18n/fr/chrome.rs @@ -37,8 +37,19 @@ pub fn lookup(english: &str) -> Option<&'static str> { } "Running" => "En cours", "Lines" => "Lignes", - "Enter show the line · x end it · Esc close" => { - "Enter afficher la ligne · x la terminer · Esc fermer" + "Enter show · p continue from here · x end it · Esc close" => { + "Enter afficher · p continuer ici · x terminer · Esc fermer" + } + "Main line" => "ligne principale", + "Start" => "origine", + "the default branch and the lines it continues from stay open; continue on another line first" => { + "La branche par défaut et les lignes dont elle continue restent ouvertes ; continuez d'abord sur une autre ligne" + } + "The old default branch stays open and keeps the lines it opened. The root keeps its own right to open a line in either direction." => { + "L'ancienne branche par défaut reste ouverte et conserve les lignes qu'elle a ouvertes. La racine garde son propre droit d'ouvrir une ligne dans les deux sens." + } + "The old default branch stays open and keeps the lines it opened. The two lines swap the right to open a line." => { + "L'ancienne branche par défaut reste ouverte et conserve les lignes qu'elle a ouvertes. Les deux lignes échangent le droit d'en ouvrir une." } "This session has no lines." => "Cette session n'a aucune ligne.", "No matching lines." => "Aucune ligne correspondante.", diff --git a/crates/dim-cli/src/ui/i18n/id/chrome.rs b/crates/dim-cli/src/ui/i18n/id/chrome.rs index d93ce423a3..18835fe895 100644 --- a/crates/dim-cli/src/ui/i18n/id/chrome.rs +++ b/crates/dim-cli/src/ui/i18n/id/chrome.rs @@ -37,8 +37,19 @@ pub fn lookup(english: &str) -> Option<&'static str> { } "Running" => "Berjalan", "Lines" => "Jalur", - "Enter show the line · x end it · Esc close" => { - "Enter lihat jalur · x hentikan · Esc tutup" + "Enter show · p continue from here · x end it · Esc close" => { + "Enter lihat · p lanjutkan dari sini · x akhiri · Esc tutup" + } + "Main line" => "jalur utama", + "Start" => "titik awal", + "the default branch and the lines it continues from stay open; continue on another line first" => { + "Jalur default dan jalur yang dilanjutkannya tetap terbuka; lanjutkan dulu di jalur lain" + } + "The old default branch stays open and keeps the lines it opened. The root keeps its own right to open a line in either direction." => { + "Jalur default lama tetap terbuka dan menyimpan jalur yang telah dibukanya. Akar mempertahankan haknya sendiri untuk membuka jalur ke dua arah." + } + "The old default branch stays open and keeps the lines it opened. The two lines swap the right to open a line." => { + "Jalur default lama tetap terbuka dan menyimpan jalur yang telah dibukanya. Kedua jalur bertukar hak untuk membuka jalur." } "This session has no lines." => "Sesi ini belum punya jalur.", "No matching lines." => "Tidak ada jalur yang cocok.", diff --git a/crates/dim-cli/src/ui/i18n/ja/chrome.rs b/crates/dim-cli/src/ui/i18n/ja/chrome.rs index 1dde5562aa..2516213372 100644 --- a/crates/dim-cli/src/ui/i18n/ja/chrome.rs +++ b/crates/dim-cli/src/ui/i18n/ja/chrome.rs @@ -35,7 +35,20 @@ pub fn lookup(english: &str) -> Option<&'static str> { "Branch history is incomplete; stop-all unavailable" => "ブランチ履歴が不完全。全停止不可", "Running" => "実行中", "Lines" => "ライン", - "Enter show the line · x end it · Esc close" => "Enter ライン表示 · x 終了 · Esc 閉じる", + "Enter show · p continue from here · x end it · Esc close" => { + "Enter 表示 · p ここから続ける · x 終了 · Esc 閉じる" + } + "Main line" => "メインライン", + "Start" => "起点", + "the default branch and the lines it continues from stay open; continue on another line first" => { + "デフォルトブランチとその元になるラインは閉じられません。先に別のラインで続けてください" + } + "The old default branch stays open and keeps the lines it opened. The root keeps its own right to open a line in either direction." => { + "以前のデフォルトブランチは開いたままで、開いたラインを保持します。ルートはどちらの方向でもラインを開く権利を保ちます。" + } + "The old default branch stays open and keeps the lines it opened. The two lines swap the right to open a line." => { + "以前のデフォルトブランチは開いたままで、開いたラインを保持します。2 本のラインはラインを開く権利を交換します。" + } "This session has no lines." => "このセッションにはまだラインがありません。", "No matching lines." => "一致するラインがありません。", "the session itself" => "セッション自体", diff --git a/crates/dim-cli/src/ui/i18n/ko/chrome.rs b/crates/dim-cli/src/ui/i18n/ko/chrome.rs index fe8ec73bc0..8e45d142a3 100644 --- a/crates/dim-cli/src/ui/i18n/ko/chrome.rs +++ b/crates/dim-cli/src/ui/i18n/ko/chrome.rs @@ -37,7 +37,20 @@ pub fn lookup(english: &str) -> Option<&'static str> { } "Running" => "실행 중", "Lines" => "라인", - "Enter show the line · x end it · Esc close" => "Enter 라인 보기 · x 종료 · Esc 닫기", + "Enter show · p continue from here · x end it · Esc close" => { + "Enter 보기 · p 여기서 계속 · x 종료 · Esc 닫기" + } + "Main line" => "메인 라인", + "Start" => "시작점", + "the default branch and the lines it continues from stay open; continue on another line first" => { + "기본 브랜치와 그 브랜치가 이어지는 라인은 닫을 수 없습니다. 먼저 다른 라인에서 계속하세요" + } + "The old default branch stays open and keeps the lines it opened. The root keeps its own right to open a line in either direction." => { + "이전 기본 브랜치는 열린 채로 남고 연 라인을 유지합니다. 루트는 어느 방향에서든 라인을 열 권리를 그대로 가집니다." + } + "The old default branch stays open and keeps the lines it opened. The two lines swap the right to open a line." => { + "이전 기본 브랜치는 열린 채로 남고 연 라인을 유지합니다. 두 라인이 라인을 열 권리를 교환합니다." + } "This session has no lines." => "이 세션에는 아직 라인이 없습니다.", "No matching lines." => "일치하는 라인이 없습니다.", "the session itself" => "세션 자체", diff --git a/crates/dim-cli/src/ui/i18n/pt_br/chrome.rs b/crates/dim-cli/src/ui/i18n/pt_br/chrome.rs index cb6b5d07b9..48b1d172dc 100644 --- a/crates/dim-cli/src/ui/i18n/pt_br/chrome.rs +++ b/crates/dim-cli/src/ui/i18n/pt_br/chrome.rs @@ -39,8 +39,19 @@ pub fn lookup(english: &str) -> Option<&'static str> { } "Running" => "Executando", "Lines" => "Linhas", - "Enter show the line · x end it · Esc close" => { - "Enter ver a linha · x encerrá-la · Esc fechar" + "Enter show · p continue from here · x end it · Esc close" => { + "Enter ver · p continuar daqui · x encerrar · Esc fechar" + } + "Main line" => "linha principal", + "Start" => "início", + "the default branch and the lines it continues from stay open; continue on another line first" => { + "A ramificação padrão e as linhas de onde ela continua permanecem abertas; continue primeiro em outra linha" + } + "The old default branch stays open and keeps the lines it opened. The root keeps its own right to open a line in either direction." => { + "A ramificação padrão anterior permanece aberta e mantém as linhas que abriu. A raiz mantém o próprio direito de abrir uma linha em qualquer direção." + } + "The old default branch stays open and keeps the lines it opened. The two lines swap the right to open a line." => { + "A ramificação padrão anterior permanece aberta e mantém as linhas que abriu. As duas linhas trocam o direito de abrir uma." } "This session has no lines." => "Esta sessão não tem linhas.", "No matching lines." => "Nenhuma linha correspondente.", diff --git a/crates/dim-cli/src/ui/i18n/pt_pt/chrome.rs b/crates/dim-cli/src/ui/i18n/pt_pt/chrome.rs index 522298a844..2948ee8b6f 100644 --- a/crates/dim-cli/src/ui/i18n/pt_pt/chrome.rs +++ b/crates/dim-cli/src/ui/i18n/pt_pt/chrome.rs @@ -39,8 +39,19 @@ pub fn lookup(english: &str) -> Option<&'static str> { } "Running" => "Em execução", "Lines" => "Linhas", - "Enter show the line · x end it · Esc close" => { - "Enter ver a linha · x terminá-la · Esc fechar" + "Enter show · p continue from here · x end it · Esc close" => { + "Enter ver · p continuar daqui · x terminar · Esc fechar" + } + "Main line" => "linha principal", + "Start" => "início", + "the default branch and the lines it continues from stay open; continue on another line first" => { + "O ramo predefinido e as linhas de onde continua permanecem abertos; continue primeiro noutra linha" + } + "The old default branch stays open and keeps the lines it opened. The root keeps its own right to open a line in either direction." => { + "O ramo predefinido anterior permanece aberto e mantém as linhas que abriu. A raiz mantém o seu próprio direito de abrir uma linha em qualquer direção." + } + "The old default branch stays open and keeps the lines it opened. The two lines swap the right to open a line." => { + "O ramo predefinido anterior permanece aberto e mantém as linhas que abriu. As duas linhas trocam o direito de abrir uma." } "This session has no lines." => "Esta sessão não tem linhas.", "No matching lines." => "Nenhuma linha correspondente.", diff --git a/crates/dim-cli/src/ui/i18n/zh_cn/chrome.rs b/crates/dim-cli/src/ui/i18n/zh_cn/chrome.rs index 55cf34b825..efb71c3e9f 100644 --- a/crates/dim-cli/src/ui/i18n/zh_cn/chrome.rs +++ b/crates/dim-cli/src/ui/i18n/zh_cn/chrome.rs @@ -30,7 +30,20 @@ pub fn lookup(english: &str) -> Option<&'static str> { "Branch history is incomplete; stop-all unavailable" => "分支历史尚未读完,暂不能停止全部", "Running" => "运行中", "Lines" => "线", - "Enter show the line · x end it · Esc close" => "Enter 查看该线 · x 结束 · Esc 关闭", + "Enter show · p continue from here · x end it · Esc close" => { + "Enter 查看 · p 从此继续 · x 结束 · Esc 关闭" + } + "Main line" => "主线", + "Start" => "起点", + "the default branch and the lines it continues from stay open; continue on another line first" => { + "默认分支和它延续的线都不能结束;请先切换到另一条线继续" + } + "The old default branch stays open and keeps the lines it opened. The root keeps its own right to open a line in either direction." => { + "原默认分支保持开启,并保留它已打开的线。根分支在任一方向都保有自己的开线权。" + } + "The old default branch stays open and keeps the lines it opened. The two lines swap the right to open a line." => { + "原默认分支保持开启,并保留它已打开的线。两条线互换开线的权利。" + } "This session has no lines." => "这个会话还没有线。", "No matching lines." => "没有匹配的线。", "the session itself" => "会话本身", diff --git a/crates/dim-cli/src/ui/i18n/zh_hant/chrome.rs b/crates/dim-cli/src/ui/i18n/zh_hant/chrome.rs index 2d1d0c33e6..dcbe245075 100644 --- a/crates/dim-cli/src/ui/i18n/zh_hant/chrome.rs +++ b/crates/dim-cli/src/ui/i18n/zh_hant/chrome.rs @@ -31,7 +31,20 @@ pub fn lookup(english: &str) -> Option<&'static str> { "Branch history is incomplete; stop-all unavailable" => "分支歷程尚未讀完,暫無法全部停止", "Running" => "執行中", "Lines" => "線", - "Enter show the line · x end it · Esc close" => "Enter 查看該線 · x 結束 · Esc 關閉", + "Enter show · p continue from here · x end it · Esc close" => { + "Enter 查看 · p 從此繼續 · x 結束 · Esc 關閉" + } + "Main line" => "主線", + "Start" => "起點", + "the default branch and the lines it continues from stay open; continue on another line first" => { + "預設分支和它延續的線都不能結束;請先切換到另一條線繼續" + } + "The old default branch stays open and keeps the lines it opened. The root keeps its own right to open a line in either direction." => { + "原預設分支保持開啟,並保留它已開啟的線。根分支在任一方向都保有自己的開線權。" + } + "The old default branch stays open and keeps the lines it opened. The two lines swap the right to open a line." => { + "原預設分支保持開啟,並保留它已開啟的線。兩條線互換開線的權利。" + } "This session has no lines." => "這個工作階段還沒有線。", "No matching lines." => "沒有符合的線。", "the session itself" => "工作階段本身", diff --git a/crates/dim-cli/src/ui/lines_panel.rs b/crates/dim-cli/src/ui/lines_panel.rs index 83d57cd59f..02e836dd25 100644 --- a/crates/dim-cli/src/ui/lines_panel.rs +++ b/crates/dim-cli/src/ui/lines_panel.rs @@ -8,7 +8,7 @@ use crate::ui::terminal::{KeyCode, KeyEvent, Modifiers}; use crate::ui::theme::Palette; use dim_agent_types::ROOT_BRANCH_ID; -const HINT: &str = "Enter show the line · x end it · Esc close"; +const HINT: &str = "Enter show · p continue from here · x end it · Esc close"; /// The rows in tree order: the session itself, then each line under the line /// that opened it, children by where they were cut from it and then in the @@ -77,10 +77,14 @@ pub struct LinesPanel { session_id: String, projection_id: u64, focus: String, + default_branch_id: String, lines: Vec, list: ListPanel, /// The line the confirmation names, until the user answers. confirm: Option, + /// Why an action was refused and the line it was raised on, until the + /// selection moves or the choice changes. + refusal: Option<(String, String)>, } impl LinesPanel { @@ -89,16 +93,18 @@ impl LinesPanel { session_id: snapshot.session_id.clone(), projection_id: snapshot.projection_id, focus: snapshot.focus.clone(), + default_branch_id: snapshot.default_branch_id.clone(), lines: Vec::new(), list: ListPanel::new( "Lines", - HINT, + t(HINT), "", "This session has no lines.", "No matching lines.", false, ), confirm: None, + refusal: None, }; panel.set_lines(snapshot); panel @@ -109,9 +115,30 @@ impl LinesPanel { self.session_id == snapshot.session_id && self.projection_id == snapshot.projection_id } + /// Shows why an action was refused, in the panel that raised it + /// (design §14), until the selection moves or another choice is made. + pub fn refuse(&mut self, projection_id: u64, text: String) -> bool { + if projection_id != self.projection_id { + return false; + } + let line = self.list.selected_id().unwrap_or_default(); + self.refusal = Some((line, text)); + self.refresh_note(); + true + } + + /// Refuses the action on the selected line, without a round trip. + fn refuse_selected(&mut self, text: String) { + self.refuse(self.projection_id, text); + } + pub fn set_lines(&mut self, snapshot: &ViewSnapshot) { let selected = self.list.selected_id(); self.focus = snapshot.focus.clone(); + if snapshot.default_branch_id != self.default_branch_id { + self.default_branch_id = snapshot.default_branch_id.clone(); + self.refusal = None; + } self.lines = snapshot.lines.clone(); let order = tree_order(&snapshot.lines); let items = order @@ -125,6 +152,15 @@ impl LinesPanel { } else { String::new() }; + let mut mark = String::new(); + if line.id == self.default_branch_id { + mark.push_str(" · "); + mark.push_str(t("Main line")); + } + if line.id == ROOT_BRANCH_ID { + mark.push_str(" · "); + mark.push_str(t("Start")); + } let mut detail = String::new(); let unread = snapshot.unread_lines.contains(&line.id); if unread { @@ -146,6 +182,7 @@ impl LinesPanel { safe(&line.purpose) }; detail.push_str(&state); + detail.push_str(&mark); detail.push_str(&viewed); Item::new( line.id.clone(), @@ -169,6 +206,7 @@ impl LinesPanel { }) .or_else(|| Some(self.focus.clone())); self.list.set_items(Ok(items), preselect.as_deref()); + self.refresh_note(); } pub fn paste(&mut self, text: &str) { @@ -195,36 +233,104 @@ impl LinesPanel { } return Effect::None; } - if key.code == KeyCode::Char('x') - && key.mods == Modifiers::NONE + if key.mods == Modifiers::NONE && self.list.filter_is_empty() && let Some(id) = self.list.selected_id() { - if id == ROOT_BRANCH_ID { - return Effect::Notice( - t("main is the session itself; a line ends, main does not").into(), - ); - } - if let Some(line) = self.lines.iter().find(|line| line.id == id) { - if matches!( - line.state, - LineState::Ended - | LineState::EndedItself - | LineState::EndedByOperation - | LineState::EndedWith(_) - | LineState::CreationFailed - ) { - return Effect::Notice(format!("{} {id}", t("Line has ended:"))); + if key.code == KeyCode::Char('x') { + let refusal = if id == ROOT_BRANCH_ID { + Some(t("main is the session itself; a line ends, main does not").to_owned()) + } else if self.is_default_or_above(&id) { + Some( + t("the default branch and the lines it continues from stay open; continue on another line first") + .to_owned(), + ) + } else { + self.lines + .iter() + .find(|line| line.id == id) + .filter(|line| { + matches!( + line.state, + LineState::Ended + | LineState::EndedItself + | LineState::EndedByOperation + | LineState::EndedWith(_) + | LineState::CreationFailed + ) + }) + .map(|_| format!("{} {id}", t("Line has ended:"))) + }; + if let Some(refusal) = refusal { + self.refuse_selected(refusal.clone()); + return Effect::Notice(refusal); } - self.ask_to_end(id); + if self.lines.iter().any(|line| line.id == id) { + self.ask_to_end(id); + } + return Effect::None; + } + if key.code == KeyCode::Char('p') { + self.confirm = None; + self.refusal = None; + self.list.set_hint(t(HINT).to_owned()); + return Effect::SetDefaultLine { + session_id: self.session_id.clone(), + projection_id: self.projection_id, + branch_id: id, + }; } - return Effect::None; } - match self.list.handle_key(key) { + let effect = match self.list.handle_key(key) { Event::None | Event::Refresh => Effect::None, Event::Close => Effect::Close, Event::Pick { id, .. } => Effect::FocusLine(id), + }; + self.refresh_note(); + effect + } + + /// Whether `id` is the default branch or an ancestor of it: no end of it + /// is admitted, because an end takes every line below it (design §10). + fn is_default_or_above(&self, id: &str) -> bool { + let mut current = Some(self.default_branch_id.as_str()); + while let Some(line) = current { + if line == id { + return true; + } + current = self + .lines + .iter() + .find(|candidate| candidate.id == line) + .and_then(|candidate| candidate.parent.as_deref()); } + false + } + + /// The panel's own paragraphs: what a move leaves in place, and the line + /// the last refusal named. The root keeps its right to open a line in + /// either direction, so it never trades it with the role (design §14). + fn refresh_note(&mut self) { + let selected = self.list.selected_id().unwrap_or_default(); + let keeps_its_right = + selected == ROOT_BRANCH_ID || self.default_branch_id == ROOT_BRANCH_ID; + if self + .refusal + .as_ref() + .is_some_and(|(line, _)| *line != selected) + { + self.refusal = None; + } + let mut notes = vec![t(if keeps_its_right { + "The old default branch stays open and keeps the lines it opened. The root keeps its own right to open a line in either direction." + } else { + "The old default branch stays open and keeps the lines it opened. The two lines swap the right to open a line." + }) + .to_owned()]; + if let Some((_, refusal)) = &self.refusal { + notes.push(refusal.clone()); + } + self.list.set_notes(notes); } pub fn cursor(&self, width: usize) -> Option<(usize, usize)> { @@ -243,7 +349,7 @@ impl LinesPanel { /// Drops the question and gives the panel its key hint back. fn answer(&mut self) { self.confirm = None; - self.list.set_hint(HINT.to_owned()); + self.list.set_hint(t(HINT).to_owned()); } pub fn render( @@ -272,6 +378,7 @@ mod tests { session_id: "s1".into(), projection_id: 3, focus: focus.into(), + default_branch_id: "main".into(), lines: vec![ LineView { id: "main".into(), @@ -325,6 +432,25 @@ mod tests { MarkdownRenderer::new(&Theme::system(ColorMode::TrueColor, Appearance::Dark, None)) } + fn rows(panel: &LinesPanel) -> Vec { + panel + .render(100, 20, &palette(), &markdown()) + .into_iter() + .map(|row| crate::ui::render::panel::strip_escapes(&row)) + .collect() + } + + /// The drawn rows as one string, borders and padding dropped, so a phrase + /// a wrap split still reads. + fn text(panel: &LinesPanel) -> String { + rows(panel) + .join(" ") + .replace(['│', '╭', '╮', '╰', '╯', '─'], " ") + .split_whitespace() + .collect::>() + .join(" ") + } + #[test] fn main_is_the_session_and_only_lines_end_after_a_confirmation() { let mut panel = LinesPanel::new(&snapshot("main")); @@ -332,6 +458,10 @@ mod tests { panel.handle_key(key(KeyCode::Char('x'))), Effect::Notice(_) )); + assert!( + text(&panel).contains(t("main is the session itself; a line ends, main does not")), + "the refusal is drawn in the panel" + ); assert!(matches!(panel.handle_key(key(KeyCode::Down)), Effect::None)); assert!(matches!( panel.handle_key(key(KeyCode::Char('x'))), @@ -367,6 +497,10 @@ mod tests { panel.handle_key(key(KeyCode::Char('x'))), Effect::Notice(_) )); + assert!( + text(&panel).contains(t("Line has ended:")), + "the refusal is drawn in the panel" + ); } #[test] @@ -387,11 +521,7 @@ mod tests { fn a_line_below_a_line_is_listed_under_its_parent_and_can_be_ended() { let snapshot = snapshot("main"); let mut panel = LinesPanel::new(&snapshot); - let rows = panel - .render(100, 20, &palette(), &markdown()) - .into_iter() - .map(|row| crate::ui::render::panel::strip_escapes(&row)) - .collect::>(); + let rows = rows(&panel); let position = |id: &str| { rows.iter() .position(|row| row.contains(id)) @@ -429,11 +559,7 @@ mod tests { sequence: 9, messages: 3, }); - let rows = LinesPanel::new(&snapshot) - .render(100, 20, &palette(), &markdown()) - .into_iter() - .map(|row| crate::ui::render::panel::strip_escapes(&row)) - .collect::>(); + let rows = rows(&LinesPanel::new(&snapshot)); let position = |id: &str| rows.iter().position(|row| row.contains(id)).unwrap(); assert!( position("b-02") < position("b-7c"), @@ -450,12 +576,8 @@ mod tests { let mut snapshot = snapshot("main"); snapshot.lines[1].state = LineState::EndedWith("main".into()); let mut panel = LinesPanel::new(&snapshot); - let rows = panel - .render(100, 20, &palette(), &markdown()) - .into_iter() - .map(|row| crate::ui::render::panel::strip_escapes(&row)) - .collect::>(); - let row = rows + let drawn = rows(&panel); + let row = drawn .iter() .find(|row| row.contains("b-7c")) .expect("the line is listed"); @@ -466,5 +588,84 @@ mod tests { panel.handle_key(key(KeyCode::Char('x'))), Effect::Notice(_) )); + assert!( + text(&panel).contains(t("Line has ended:")), + "an ended line is refused in the panel" + ); + } + + #[test] + fn the_root_and_the_default_branch_are_marked_and_p_chooses_a_line() { + let mut snapshot = snapshot("main"); + snapshot.default_branch_id = "b-7c".into(); + let mut panel = LinesPanel::new(&snapshot); + let drawn = rows(&panel); + let row = |id: &str| { + drawn + .iter() + .find(|row| row.contains(id)) + .unwrap_or_else(|| panic!("{id} is listed: {drawn:#?}")) + .clone() + }; + assert!(row("main").contains(t("Start")), "{drawn:#?}"); + assert!(row("b-7c").contains(t("Main line")), "{drawn:#?}"); + assert!(!row("b-7c").contains(t("Start")), "{drawn:#?}"); + assert!(!row("b-91").contains(t("Main line")), "{drawn:#?}"); + panel.handle_key(key(KeyCode::Down)); + match panel.handle_key(key(KeyCode::Char('p'))) { + Effect::SetDefaultLine { branch_id, .. } => assert_eq!(branch_id, "b-7c"), + _ => panic!("p continues on the selected line"), + } + } + + #[test] + fn x_is_refused_on_the_default_branch_and_on_a_line_above_it() { + let mut snapshot = snapshot("main"); + snapshot.default_branch_id = "b-91".into(); + let mut panel = LinesPanel::new(&snapshot); + for _ in 0..2 { + panel.handle_key(key(KeyCode::Down)); + } + let refusal = t( + "the default branch and the lines it continues from stay open; continue on another line first", + ); + assert!(matches!( + panel.handle_key(key(KeyCode::Char('x'))), + Effect::Notice(_) + )); + assert!( + text(&panel).contains(refusal), + "x on the default branch is refused in the panel" + ); + panel.handle_key(key(KeyCode::Up)); + assert!(matches!( + panel.handle_key(key(KeyCode::Char('x'))), + Effect::Notice(_) + )); + assert!( + text(&panel).contains(refusal), + "x on an ancestor of the default branch is refused in the panel" + ); + } + + #[test] + fn a_refused_move_is_shown_in_the_panel() { + let mut panel = LinesPanel::new(&snapshot("main")); + assert!(panel.refuse( + 3, + "branch_already_default: the line is already the default branch".into() + )); + let drawn = rows(&panel); + assert!( + drawn + .iter() + .any(|row| row.contains("branch_already_default")), + "{drawn:#?}" + ); + assert!( + text(&panel).contains("old default branch stays open"), + "the panel keeps its own paragraph: {drawn:#?}" + ); + assert!(!panel.refuse(4, "another attachment".into())); } } diff --git a/crates/dim-cli/src/ui/prompts.rs b/crates/dim-cli/src/ui/prompts.rs index f67fe3e9a9..6661a2d838 100644 --- a/crates/dim-cli/src/ui/prompts.rs +++ b/crates/dim-cli/src/ui/prompts.rs @@ -157,6 +157,12 @@ pub enum Effect { projection_id: u64, branch_id: String, }, + /// Continue on this line: make it the Session's default branch and show it. + SetDefaultLine { + session_id: String, + projection_id: u64, + branch_id: String, + }, /// Stop the background command on its originating branch. StopTask { session_id: String, diff --git a/crates/dim-cli/src/ui/tui.rs b/crates/dim-cli/src/ui/tui.rs index 6c4932ad45..8db3435ef1 100644 --- a/crates/dim-cli/src/ui/tui.rs +++ b/crates/dim-cli/src/ui/tui.rs @@ -2360,6 +2360,18 @@ impl App { self.composer.set_accepts_images(images); self.service_tiers = service_tiers; } + Update::LineRefusal { + projection_id, + text, + } => { + let shown = match &mut self.prompt { + Some(Prompt::Lines(panel)) => panel.refuse(projection_id, text.clone()), + _ => false, + }; + if !shown { + self.set_notice(text); + } + } Update::Snapshot(snapshot) => { let was_running = self.running(); let switched = self @@ -4157,6 +4169,17 @@ impl App { branch_id, }); } + Effect::SetDefaultLine { + session_id, + projection_id, + branch_id, + } => { + self.host.send(Command::SetDefaultLine { + session_id, + projection_id, + branch_id, + }); + } Effect::Resume(id) => { self.host.send(Command::CloseSessions); self.prompt = None; diff --git a/crates/dim-client/src/wire.rs b/crates/dim-client/src/wire.rs index 0bb3bcd9a9..9d37ce998c 100644 --- a/crates/dim-client/src/wire.rs +++ b/crates/dim-client/src/wire.rs @@ -480,8 +480,14 @@ pub struct TurnBoundary { } #[derive(Deserialize)] +#[serde(rename_all = "camelCase")] pub struct BranchDirectory { pub branches: Vec, + /// The line the Session's conversation is on (design §14). A server that + /// predates `session.branch_set_default` reports none, and such a Session + /// is on its root. + #[serde(default)] + pub default_branch_id: Option, } #[derive(Deserialize)] #[serde(rename_all = "camelCase")] diff --git a/crates/dimcode/tests/cli_flow.rs b/crates/dimcode/tests/cli_flow.rs index a23d2d31e9..d7007d4adf 100644 --- a/crates/dimcode/tests/cli_flow.rs +++ b/crates/dimcode/tests/cli_flow.rs @@ -30,6 +30,9 @@ mod hooks; #[path = "cli_flow/mcp.rs"] mod mcp; +#[path = "cli_flow/lines.rs"] +mod lines; + #[path = "cli_flow/migration.rs"] mod migration; #[path = "cli_flow/modality.rs"] @@ -10546,7 +10549,7 @@ fn tui_tasks_panel_stops_the_selected_command_or_member() { wire.notice("session.event", json!({"sessionId":"session","branchId":"main","event":{"id":"req-other","sequence":20,"create_at":1,"type":"collaboration","name":"request","data":{"turn_id":"t","request_id":"r4","call_id":"call-4","target":{"kind":"agent","agent_id":"writer"},"prompt":"Check the docs"}}})); wire.notice("session.event", json!({"sessionId":"session","branchId":"main","event":{"id":"del-other","sequence":21,"create_at":1,"type":"collaboration","name":"delivered","data":{"op_event_id":"req-other","status":"ok","agent_id":"writer","session_id":"other-member","input_event_id":"other-input"}}})); let stop = past_observations(wire, "session.stop"); - assert_eq!(stop["params"], json!({"sessionId":"member","branchId":"main","reason":"stopped by the user"})); + assert_eq!(stop["params"], json!({"sessionId":"member","reason":"stopped by the user"})); wire.reply(&stop, json!({})); wire.notice("session.event", json!({"sessionId":"session","branchId":"main","event":{"id":"res-1","sequence":22,"create_at":1,"type":"collaboration","name":"result","data":{"request_event_id":"req-1","agent_id":"reviewer","session_id":"member","text":"","status":"cancelled","reason":"stopped by the user"}}})); let submit = past_observations(wire, "session.submit"); diff --git a/crates/dimcode/tests/cli_flow/lines.rs b/crates/dimcode/tests/cli_flow/lines.rs new file mode 100644 index 0000000000..b7f013af64 --- /dev/null +++ b/crates/dimcode/tests/cli_flow/lines.rs @@ -0,0 +1,285 @@ +//! The lines panel and the Session's default branch: the root and the default +//! branch are marked, `p` continues on a line, and `x` ends neither the +//! default branch nor a line it continues from (design §14). +use super::*; + +/// A line's creation, as its parent's Timeline carries it. +/// The requests every flow meets besides the ones it asserts, answered here so +/// each flow reads only the requests it is about. +fn next(wire: &mut Wire) -> Value { + loop { + let request = wire.read_any(); + let branch = request["params"]["branchId"].clone(); + let through = request["params"]["through"].clone(); + match request["method"].as_str().unwrap_or_default() { + "session.methods" => { + let methods: Vec<_> = [ + "session.input.pending", + "session.exec.pending", + "session.turn.get", + ] + .into_iter() + .map(|name| json!({"name":name,"mutating":false})) + .collect(); + wire.reply(&request, json!({"methods":methods})); + } + "session.question.pending" => wire.reply( + &request, + json!({"branchId":branch,"through":through,"batches":[],"next":null}), + ), + "session.input.pending" => wire.reply( + &request, + json!({"branchId":branch,"through":through,"inputs":[],"next":null}), + ), + "session.exec.pending" => wire.reply( + &request, + json!({"branchId":branch,"through":through,"tasks":[],"next":null}), + ), + "session.turn.get" => wire.reply( + &request, + json!({"branchId":branch,"through":through,"turn":null,"output":null}), + ), + "account.providers" => wire.reply(&request, json!([])), + "provider.list" => wire.reply(&request, json!({"providers":[]})), + "session.context.usage" => { + wire.send(json!({"jsonrpc":"2.0","id":request["id"],"error":{ + "code":-32601,"message":"Unknown method: session.context.usage", + "data":{"appError":"unknown_method"}}})) + } + _ => return request, + } + } +} + +fn created(branch: &str, sequence: u64) -> Value { + json!({"id":format!("{branch}-create"),"sequence":sequence,"create_at":1,"type":"branch","name":"create","data":{ + "branch":branch,"at":{"kind":"create"}, + "source":{"kind":"tool","turn_id":"turn","request_id":"request","call_id":format!("{branch}-call")}, + "prompt":format!("{branch} work"), + }}) +} + +fn history(through: u64, events: Vec) -> Value { + json!({"events":events,"through":through,"nextAfter":through,"done":true}) +} + +fn directory(default_branch_id: &str, lines: &[(&str, Option<&str>)]) -> Value { + json!({ + "defaultBranchId": default_branch_id, + "branches": lines.iter().map(|(branch, parent)| match parent { + Some(parent) => json!({"branchId":branch,"parentBranchId":parent,"branchPoint":1,"state":"open","head":8,"purpose":format!("{branch} work")}), + None => json!({"branchId":branch,"state":"open","head":8}), + }).collect::>(), + }) +} + +fn entry(branch: &str, parent: &str) -> Value { + json!({"branchId":branch,"parentBranchId":parent,"branchPoint":2,"state":"open","head":8,"purpose":format!("{branch} work"),"cutMessages":0,"end":null}) +} + +/// The lines panel marks the root and the default branch; `p` continues on the +/// selected line, and the next message with no line chosen reaches it. +#[test] +fn tui_lines_panel_marks_the_default_branch_and_p_moves_it() { + let home = Home::new(); + let (moved, move_seen) = std::sync::mpsc::channel(); + let daemon = home.daemon(move |wire| { + wire.hello(&[ + "session.methods", + "session.branches", + "session.branch.get", + "session.branch_set_default", + "session.branch_end", + ]); + wire.2 = true; + let attach = wire.read("session.attach"); + wire.reply(&attach, attach_record(&attach)); + let branches = next(wire); + assert_eq!(branches["method"], "session.branches"); + wire.reply( + &branches, + directory("main", &[("main", None), ("line-1", Some("main"))]), + ); + let read = next(wire); + assert_eq!(read["method"], "session.history"); + assert_eq!(read["params"]["branchId"], "main"); + wire.reply(&read, history(8, vec![created("line-1", 2)])); + + let mut moved_on = false; + loop { + let request = next(wire); + match request["method"].as_str().unwrap() { + "session.branch_set_default" => { + assert_eq!( + request["params"]["branchId"], + json!("line-1"), + "p continues on the selected line" + ); + wire.reply(&request, json!({"defaultBranchId":"line-1"})); + moved_on = true; + moved.send(()).unwrap(); + } + "session.branch.get" => { + assert_eq!(request["params"]["branchId"], json!("line-1")); + wire.reply(&request, entry("line-1", "main")); + } + "session.history" => { + if moved_on { + assert_eq!( + request["params"]["branchId"], + json!("line-1"), + "the shown transcript is the line the move reached" + ); + } + wire.reply(&request, history(8, vec![])); + } + "session.submit" => { + assert_eq!( + request["params"]["branchId"], + json!("line-1"), + "a message with no line chosen reaches the default branch" + ); + break; + } + other => panic!("unexpected {other}: {request}"), + } + } + wire.detach(); + }); + let mut command = home.command(); + sized(&mut command, 100, 32); + let mut terminal = Terminal::resume_tui(command); + terminal.until("test / model"); + + terminal.write(b"/lines\r"); + terminal.until("the session itself"); + terminal.until("Main line"); + terminal.until("Start"); + terminal.write(b"\x1b[B"); + terminal.write(b"p"); + move_seen.recv_timeout(PATIENCE).unwrap(); + terminal.write(b"\x1b"); + terminal.until("⑂ main ▸ line-1 work"); + terminal.write(b"hello\r"); + home.kill(&terminal); + terminal.wait(); + daemon.join().unwrap(); +} + +/// `x` ends neither the default branch nor a line it continues from, so the +/// end of a line above the role is refused with its own message. +#[test] +fn tui_x_is_refused_on_the_default_branch_and_on_a_line_it_continues_from() { + let home = Home::new(); + let daemon = home.daemon(|wire| { + wire.hello(&[ + "session.methods", + "session.branches", + "session.branch.get", + "session.branch_set_default", + "session.branch_end", + ]); + wire.2 = true; + let attach = wire.read("session.attach"); + wire.reply(&attach, attach_record(&attach)); + let branches = next(wire); + assert_eq!(branches["method"], "session.branches"); + wire.reply( + &branches, + directory( + "line-2", + &[ + ("main", None), + ("line-1", Some("main")), + ("line-2", Some("line-1")), + ], + ), + ); + loop { + let request = next(wire); + match request["method"].as_str().unwrap() { + "session.history" => { + wire.reply(&request, history(8, vec![])); + } + "session.branch.get" => { + assert_eq!(request["params"]["branchId"], json!("line-2")); + wire.reply(&request, entry("line-2", "line-1")); + } + other => panic!("unexpected {other}: {request}"), + } + } + }); + let mut command = home.command(); + sized(&mut command, 120, 36); + let mut terminal = Terminal::resume_tui(command); + terminal.until("test / model"); + + // The panel opens on the shown line, which is the default branch. + terminal.write(b"/lines\r"); + terminal.until("Main line"); + terminal.write(b"x"); + terminal.until("the default branch and the lines it continues from stay open; continue on another line first"); + + // Reopened, the selection is the shown line again; one row up is the + // line it was opened from. + terminal.write(b"/lines\r"); + terminal.write(b"\x1b[A"); + terminal.write(b"x"); + terminal.until("the default branch and the lines it continues from stay open; continue on another line first"); + home.kill(&terminal); + terminal.wait(); + daemon.join().unwrap(); +} + +/// A refusal from `session.branch_set_default` is drawn in the panel that +/// raised it, not only reported elsewhere. +#[test] +fn tui_a_refused_continue_is_shown_in_the_lines_panel() { + let home = Home::new(); + let daemon = home.daemon(|wire| { + wire.hello(&[ + "session.methods", + "session.branches", + "session.branch.get", + "session.branch_set_default", + "session.branch_end", + ]); + wire.2 = true; + let attach = wire.read("session.attach"); + wire.reply(&attach, attach_record(&attach)); + let branches = next(wire); + assert_eq!(branches["method"], "session.branches"); + wire.reply( + &branches, + directory("main", &[("main", None), ("line-1", Some("main"))]), + ); + let refused = loop { + let request = next(wire); + match request["method"].as_str().unwrap() { + "session.history" => wire.reply(&request, history(8, vec![created("line-1", 2)])), + "session.branch.get" => wire.reply(&request, entry("line-1", "main")), + "session.branch_set_default" => break request, + other => panic!("unexpected {other}: {request}"), + } + }; + assert_eq!(refused["params"]["branchId"], json!("line-1")); + wire.send(json!({"jsonrpc":"2.0","id":refused["id"],"error":{ + "code":-32001, + "message":"the line was created through a client before the upgrade, so it cannot be the default branch", + "data":{"appError":"branch_not_selectable"}}})); + wire.detach(); + }); + let mut command = home.command(); + sized(&mut command, 120, 40); + let mut terminal = Terminal::resume_tui(command); + terminal.until("test / model"); + + terminal.write(b"/lines\r"); + terminal.until("the session itself"); + terminal.write(b"\x1b[B"); + terminal.write(b"p"); + terminal.until("so it cannot be the default branch"); + home.kill(&terminal); + terminal.wait(); + daemon.join().unwrap(); +} diff --git a/crates/dimcode/tests/cli_flow/permission.rs b/crates/dimcode/tests/cli_flow/permission.rs index 7414e83d9f..1d8086b045 100644 --- a/crates/dimcode/tests/cli_flow/permission.rs +++ b/crates/dimcode/tests/cli_flow/permission.rs @@ -129,7 +129,7 @@ fn line_permission_controls_keep_tool_lists_report_conflicts_and_reject_unknown_ terminal.until("Run the command again to switch."); terminal.until("\n> "); terminal.write(b"/permissions workspace-write\n"); - terminal.until("Preset (main branch): workspace-write"); + terminal.until("Preset: workspace-write"); terminal.until("\n> "); terminal.write(b"/permissions\n"); terminal.until("permission: workspace-write"); @@ -700,20 +700,20 @@ fn interactive_approvals_list_switch_and_edit_rules_with_version_checks() { terminal.until("Usage: /permissions"); terminal.until("\n> "); terminal.write(b"/approvals full-access\n"); - terminal.until("Switch the main branch to full-access? [y/N] "); + terminal.until("Switch to full-access? [y/N] "); terminal.write(b"\n"); terminal.until("Preset unchanged: workspace-write"); terminal.until("\n> "); terminal.write(b"/approvals full-access\n"); - terminal.until("Switch the main branch to full-access? [y/N] "); + terminal.until("Switch to full-access? [y/N] "); terminal.write(b"y\n"); terminal.until("The preset changed elsewhere and is now read-only; nothing was changed."); terminal.until("\n> "); terminal.write(b"/approvals read-only\n"); - terminal.until("Preset (main branch) is already read-only"); + terminal.until("Preset is already read-only"); terminal.until("\n> "); terminal.write(b"/permissions workspace-write\n"); - terminal.until("Preset (main branch): workspace-write. Child branches and members created later from main inherit it; existing branches and members keep their policies."); + terminal.until("Preset: workspace-write. Lines and members created later from this line inherit it; existing lines and members keep their policies."); terminal.until("\n> "); terminal.write(b"/approvals remove 1\n"); terminal.until("Rule removed: allow exact `cargo test`"); @@ -766,7 +766,7 @@ fn interactive_approvals_list_switch_and_edit_rules_with_version_checks() { terminal.until("Error: Usage: /permissions"); terminal.until("\n> "); terminal.write(b"after\n"); - terminal.until("[permission] main branch preset: full-access"); + terminal.until("[permission] preset: full-access"); terminal.until("\n> "); terminal.write(b"/exit\n"); assert!(terminal.wait().success()); @@ -774,7 +774,7 @@ fn interactive_approvals_list_switch_and_edit_rules_with_version_checks() { assert!( !terminal .transcript - .contains("[permission] main branch preset: workspace-write"), + .contains("[permission] preset: workspace-write"), "{}", terminal.transcript ); @@ -1050,7 +1050,7 @@ fn real_daemon_always_allow_saves_an_exact_rule_until_approvals_removes_it() { terminal.until("Rule removed: allow exact `printf always-ran`"); terminal.editor(); terminal.write(b"/approvals read-only\n"); - terminal.until("Preset (main branch): read-only."); + terminal.until("Preset: read-only."); terminal.editor(); let mark = terminal.transcript.len(); terminal.write(b"exec: printf always-ran\n"); @@ -1065,7 +1065,7 @@ fn real_daemon_always_allow_saves_an_exact_rule_until_approvals_removes_it() { terminal.until("permission: read-only"); terminal.editor(); terminal.write(b"/permissions full-access\n"); - terminal.until("Switch the main branch to full-access? [y/N] "); + terminal.until("Switch to full-access? [y/N] "); terminal.write(b"y\n"); terminal.until("permission: full-access"); terminal.editor(); @@ -1079,7 +1079,7 @@ fn real_daemon_always_allow_saves_an_exact_rule_until_approvals_removes_it() { terminal.transcript ); terminal.write(b"/permissions workspace-write\n"); - terminal.until("Preset (main branch): workspace-write"); + terminal.until("Preset: workspace-write"); terminal.editor(); let mark = terminal.transcript.len(); terminal.write(b"exec: printf ask-ran\n"); diff --git a/crates/dimcode/tests/cli_flow/startup.rs b/crates/dimcode/tests/cli_flow/startup.rs index 6a0dd9a794..6e25840f5c 100644 --- a/crates/dimcode/tests/cli_flow/startup.rs +++ b/crates/dimcode/tests/cli_flow/startup.rs @@ -849,7 +849,7 @@ fn resume_startup_is_adopted_or_explicitly_rejected_before_input_in_every_client assert_eq!(request["method"], "session.model.update"); request }; - let mut expected = json!({"sessionId":"session","branchId":"main", + let mut expected = json!({"sessionId":"session", "modelPreferences":{"reasoningEffort":"low"}, "startup":{"connection":{"baseUrl":"https://gateway.example/prefix", "apiFormat":"anthropic","apiKey":"resume-secret"},"autoCompactWindow":"auto"}}); @@ -904,7 +904,7 @@ fn resume_effort_only_sends_forced_inheritance_before_submitting() { let update = wire.read("session.model.update"); assert_eq!( update["params"], - json!({"sessionId":"session","branchId":"main", + json!({"sessionId":"session", "modelPreferences":{"reasoningEffort":"high"},"startup":{}}) ); wire.reply(&update, json!({"outcome":"adopted"})); diff --git a/crates/dimcode/tests/cli_flow/tasks.rs b/crates/dimcode/tests/cli_flow/tasks.rs index b27d649216..6f52ed6be5 100644 --- a/crates/dimcode/tests/cli_flow/tasks.rs +++ b/crates/dimcode/tests/cli_flow/tasks.rs @@ -1047,7 +1047,7 @@ fn tui_task_stop_all_keeps_its_finite_targets_and_waits_only_for_replies() { wire.reply(&submit, json!({"event":{}})); wire.send(json!({"jsonrpc":"2.0","id":first["id"],"error":{"code":-32000,"message":"first stop failed","data":{"appError":"service_reloading"}}})); let member = wire.read("session.stop"); - assert_eq!(member["params"], json!({"sessionId":"member","branchId":"main","reason":"stopped by the user"})); + assert_eq!(member["params"], json!({"sessionId":"member","reason":"stopped by the user"})); wire.quiet(Duration::from_millis(150)); wire.reply(&member, json!({})); let child = wire.read("session.exec.stop"); @@ -1458,7 +1458,7 @@ wire.reply(&second, json!({"events":[fact("member-input",1,1000,"input","message wire.notice("session.event", json!({"sessionId":"member","branchId":"main","event":fact("member-tool-result",7,3000,"step","tool-result",json!({"turn_id":"member-turn","request_id":"member-tools","results":[{"call_id":"member-exec","result":{"content":"member disclosure output"}}]}))})); wire.notice("session.model.progress", json!({"sessionId":"member","branchId":"main","requestId":"member-model","text":"","textOffset":0,"thinking":"live member thought\n\nmember thinking final paragraph","thinkingOffset":0})); let stop = wire.read("session.stop"); - assert_eq!(stop["params"], json!({"sessionId":"member","branchId":"main","reason":"stopped by the user"})); + assert_eq!(stop["params"], json!({"sessionId":"member","reason":"stopped by the user"})); wire.reply(&stop, json!({})); event(wire, "main", fact("leader-result",5,4000,"collaboration","result",json!({"request_event_id":"leader-member","agent_id":"reviewer","session_id":"member","status":"cancelled","reason":"stopped by the user","text":"real cancelled delegation result"}))); let detach = wire.read("session.detach"); diff --git a/docs/design/cli-commands.md b/docs/design/cli-commands.md index 270dcde1ac..3237b84353 100644 --- a/docs/design/cli-commands.md +++ b/docs/design/cli-commands.md @@ -540,7 +540,7 @@ queue strip when nothing is held: ## Usage report -In both TUI modes, `/usage` prints the main branch's context usage. When the +In both TUI modes, `/usage` prints the default branch's context usage. When the active model uses Dim OAuth, it also queries and prints the account's plan, credits, rolling windows and feature meters through the existing [account usage contract](../../crates/dim-oauth/docs/runtime-contract.md). @@ -3103,7 +3103,7 @@ permission: read-only > Fix the build Assistant: ... -[permission] main branch preset: workspace-write <- changed by another client +[permission] preset: workspace-write <- changed by another client ``` Both TUI modes draw a live permission footer under the composer, without an `AGENT` prefix; @@ -3253,8 +3253,8 @@ approves nor cancels work by that fact alone. ### `/permissions` `/permissions` is the visible menu entry in both TUI modes; `/approvals` and `/approval` open the -same preset picker as compatibility aliases. The control applies to `main`; selecting a preset -uses the current policy and version, preserving the tool lists. A failed save neither changes remembered choices nor falls back to another preset. +same preset picker as compatibility aliases. The control applies to the Session's default +branch; selecting a preset uses the current policy and version, preserving the tool lists. A failed save neither changes remembered choices nor falls back to another preset. The Process isolation row links to the Settings control; Esc returns to this panel with that row focused. The Command rules row opens the management panel diff --git a/docs/design/plugins/Tui.md b/docs/design/plugins/Tui.md index 7472045f01..659cf0dea6 100644 --- a/docs/design/plugins/Tui.md +++ b/docs/design/plugins/Tui.md @@ -458,6 +458,19 @@ usage pending -> /new -> new Session old reply -> discard ``` +### 3.8 The lines panel and the default branch + +The Session worker reads the Session's default branch once per attachment, from +`session.branches`'s `defaultBranchId`, and opens on it: the initial focus, the +transcript windows and the top bar's model, permission and usage read that line's +events. `/lines` marks that line `Main line` and `main` `Start`; `p` continues on +the selected line through `session.branch_set_default`, then shows its transcript +and names it in the top bar, and the method's refusal is drawn in the panel +rather than only reported elsewhere. `x` is refused on `main`, on the default +branch and on every line above the default branch. The panel's rows, refusals and +key rules are [timeline UI §6](../timeline-ui.md#6-lines-panel); the method is +`session.branch_set_default` in §6 below. + ## 4. Timing and conflicts | Case | Decision | diff --git a/docs/zh/design/cli-commands.md b/docs/zh/design/cli-commands.md index 6673fb81a7..11d1775757 100644 --- a/docs/zh/design/cli-commands.md +++ b/docs/zh/design/cli-commands.md @@ -235,7 +235,7 @@ shell 运行拦截,再是 steer 最早的排队消息,只有在没有排队 ## 用量报告 -两种 TUI 模式下,`/usage` 都输出主分支的上下文用量。当前模型使用 Dim OAuth 时, +两种 TUI 模式下,`/usage` 都输出默认分支的上下文用量。当前模型使用 Dim OAuth 时, 还通过现有[账号用量合同](../../../crates/dim-oauth/docs/runtime-contract.md)查询并输出账号的 套餐、积分、滚动窗口和功能额度。其他模型提供方只显示上下文用量;仅登录 Dim 账号不会启用 账号用量报告。`/login` 中的账号视图保持可用。 @@ -1865,7 +1865,7 @@ permission: read-only > Fix the build Assistant: ... -[permission] main branch preset: workspace-write <- 由其他客户端修改 +[permission] preset: workspace-write <- 由其他客户端修改 ``` 两种 TUI 模式都在输入框下方绘制实时权限页脚,不带 `AGENT` 前缀;预设、颜色、本地化快捷键提示与 @@ -1931,7 +1931,7 @@ Session 创建配置 --> main 当前策略 --分支点--> 子分支策略 ### `/permissions` `/permissions` 是两种 TUI 模式下可见的菜单入口;`/approvals` 和 `/approval` 作为兼容别名打开同一组 -预设选择器。选择作用于 `main`,每次更新使用当前完整策略与版本,保留工具列表。 +预设选择器。选择作用于 Session 的默认分支,每次更新使用当前完整策略与版本,保留工具列表。 保存失败既不改变记住的选择,也不回退到其他预设。 Process isolation 行链接到 Settings 的进程隔离控件;Esc 返回本面板并保持该行的焦点。 From 563f70f401c70bc88265ecab43f3ee0fdb355760 Mon Sep 17 00:00:00 2001 From: huihui Date: Fri, 20 Nov 2026 16:42:18 +0800 Subject: [PATCH 02/83] feat(web): centre the Session's default branch MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The Web reads defaultBranchId from the directory and centres that line: its transcript, running state, approvals, questions, submit, stop and withdraw are the default branch's, and the composer's /goal, /compact, /usage and /effort name it while /fork still copies only the root, which it reads at the action (design §9, §14). The Lines tree marks the root and the default branch, offers continue from here and draws session.branch_set_default's refusal on the row that raised it, and a move re-reads the new centre's transcript, goal and permission in one round trip. --- web/src/features/chat/ChatPage.vue | 32 ++--- web/src/features/chat/QueuedInputs.vue | 8 +- .../features/extensions/ExtensionPanel.vue | 11 +- web/src/features/lines/LineConversation.vue | 2 +- web/src/features/lines/LinesPanel.vue | 4 +- web/src/features/lines/LinesTree.vue | 51 +++++++- web/src/features/lines/line-state.ts | 27 +++- .../features/settings/ScheduledSettings.vue | 13 +- web/src/i18n/en.ts | 4 + web/src/i18n/zh-CN.ts | 4 + web/src/lines.test.mjs | 40 ++++-- web/src/rpc/protocol.ts | 6 - web/src/rpc/read.ts | 15 ++- web/src/rpc/scheduler.ts | 8 +- web/src/stores/chat.ts | 119 ++++++++++++------ web/src/stores/ui.ts | 11 +- web/tests/chat-history.mjs | 32 ++++- web/tests/settings-scheduled.mjs | 2 +- 18 files changed, 280 insertions(+), 109 deletions(-) diff --git a/web/src/features/chat/ChatPage.vue b/web/src/features/chat/ChatPage.vue index b610684352..90290bdfcf 100644 --- a/web/src/features/chat/ChatPage.vue +++ b/web/src/features/chat/ChatPage.vue @@ -10,7 +10,7 @@ import QueuedInputs from "./QueuedInputs.vue" import QuestionPrompt from "./QuestionPrompt.vue" import TimelineView from "./TimelineView.vue" import ExtensionMenu from "../extensions/ExtensionMenu.vue" -import { DEFAULT_BRANCH_ID, ROOT_BRANCH_ID, type ContextUsage, type DraftAttachments, type ModelId, type PermissionPreset, type QueuedInput, type SubmitMode, type WithdrawResult } from "../../rpc/protocol" +import { ROOT_BRANCH_ID, type ContextUsage, type DraftAttachments, type ModelId, type PermissionPreset, type QueuedInput, type SubmitMode, type WithdrawResult } from "../../rpc/protocol" import { goalCall, goalObjective, parseGoalRequest, type Goal, type GoalStatus } from "../../goal" import { intervalSeconds, loopReport, parseLoopRequest } from "../../loop" import { useChatStore } from "../../stores/chat" @@ -39,8 +39,10 @@ const title = computed(() => summary.value?.title ?? summary.value?.preview ?? t const parentId = computed(() => summary.value?.parentSessionId) const parent = computed(() => parentId.value === undefined ? undefined : sessions.byId.get(parentId.value)) const children = computed(() => sessions.summaries.filter((session) => session.parentSessionId === props.sessionId)) -const approval = computed(() => view.value?.approvals.find((request) => request.branchId === DEFAULT_BRANCH_ID)) -const questions = computed(() => view.value?.questions.filter((ask) => ask.branchId === DEFAULT_BRANCH_ID) ?? []) +/** The centre: the line the Session's conversation is on (design §4). */ +const centred = computed(() => view.value?.defaultBranchId ?? ROOT_BRANCH_ID) +const approval = computed(() => view.value?.approvals.find((request) => request.branchId === centred.value)) +const questions = computed(() => view.value?.questions.filter((ask) => ask.branchId === centred.value) ?? []) const prompting = computed(() => approval.value !== undefined || questions.value.length > 0) const rulesAvailable = computed(() => connection.supports("permission.rules") && connection.supports("permission.set_rules")) const storesPastes = computed(() => view.value?.methods.includes("attachment.put") === true) @@ -57,7 +59,7 @@ const permissionControl = computed(() => { if (session?.status !== "ready" || !connection.supports("session.permission.get") || !connection.supports("session.permission.update")) return undefined return { policy: session.permission, select: setPermission } }) -const approvalKeyboard = computed(() => ui.approvalKeyboard(props.sessionId, DEFAULT_BRANCH_ID, view.value?.approvals ?? [])) +const approvalKeyboard = computed(() => ui.approvalKeyboard(props.sessionId, centred.value, centred.value, view.value?.approvals ?? [])) const composer = ref>() const lineCount = computed(() => view.value?.lines.filter((line) => line.id !== ROOT_BRANCH_ID).length ?? 0) const linesBusy = computed(() => { @@ -80,7 +82,7 @@ const sessionCommands = computed(() => { return { compact: session.methods.includes("session.context.compact") ? compact : undefined, usage: session.methods.includes("session.context.usage") ? usage : undefined, - fork: connection.supports("session.fork") && session.lastTurnEnd !== undefined ? fork : undefined, + fork: connection.supports("session.fork") ? fork : undefined, goal: session.methods.includes("session.goal.set") ? goal : undefined, loop: session.methods.includes("session.loop.start") ? loop : undefined, effort: effortChoices.value !== undefined && effortChoices.value.length > 0 ? effort : undefined, @@ -88,16 +90,16 @@ const sessionCommands = computed(() => { }) function send(text: string, attachments: DraftAttachments, mode: SubmitMode): Promise { - return chat.submit(props.sessionId, DEFAULT_BRANCH_ID, text, attachments, mode) + return chat.submit(props.sessionId, centred.value, text, attachments, mode) } function stop(): Promise { - return chat.stop(props.sessionId, DEFAULT_BRANCH_ID) + return chat.stop(props.sessionId, centred.value) } /** Withdraws one held message of main, so the composer can recall it into the draft; reports a message the run already adopted. */ async function withdrawHeld(input: QueuedInput): Promise { - const result = await chat.withdrawInput(props.sessionId, DEFAULT_BRANCH_ID, input.id, undefined) + const result = await chat.withdrawInput(props.sessionId, centred.value, input.id, undefined) if (result.status === "notHeld") toast.push({ tone: "info", title: t("queue.notHeld") }) return result.status } @@ -111,14 +113,15 @@ function openLine(branchId: string): void { ui.openLine(props.sessionId, branchId) } +/** The shown transcript is the centre's, so a cut in it opens a child of that line. */ function branch(text: string, cut: number): void { - ui.requestNewLine({ sessionId: props.sessionId, parentBranchId: ROOT_BRANCH_ID, at: cut, text }) + ui.requestNewLine({ sessionId: props.sessionId, parentBranchId: centred.value, at: cut, text }) } async function createBranch(prompt: string): Promise { const at = view.value?.lastTurnEnd if (at === undefined) throw new Error(t("lines.noFinishedTurn")) - const branchId = await chat.createLine(props.sessionId, ROOT_BRANCH_ID, at, prompt) + const branchId = await chat.createLine(props.sessionId, centred.value, at, prompt) ui.openLine(props.sessionId, branchId) } @@ -272,12 +275,11 @@ async function setPermission(preset: PermissionPreset): Promise { } } +/** `/fork` copies only the root, whichever line the centre shows (design §9, §14). */ async function fork(): Promise { - const at = view.value?.lastTurnEnd - if (at === undefined) return if (!await forkConfirm.value?.open(t("fork.confirm"), { confirmLabel: t("fork.confirmLabel") })) return try { - const forked = await chat.fork(props.sessionId, at) + const forked = await chat.fork(props.sessionId) void sessions.refresh() await router.push({ name: "chat-session", params: { sessionId: forked } }) } catch (cause) { @@ -371,7 +373,7 @@ async function fork(): Promise { :earlier="view.earlier" :loading-earlier="view.loadingEarlier" :history-error="view.historyError" - @earlier="chat.loadEarlier(sessionId, ROOT_BRANCH_ID)" + @earlier="chat.loadEarlier(sessionId, centred)" :running="view.running" :retry="view.retry" :quotable="!approval && questions.length === 0" @@ -381,7 +383,7 @@ async function fork(): Promise { @quote="composer?.quote($event)" />
- +
diff --git a/web/src/features/chat/QueuedInputs.vue b/web/src/features/chat/QueuedInputs.vue index 55cf64e645..1d31386dc3 100644 --- a/web/src/features/chat/QueuedInputs.vue +++ b/web/src/features/chat/QueuedInputs.vue @@ -1,16 +1,16 @@