diff --git a/crates/dim-acp/src/commands.rs b/crates/dim-acp/src/commands.rs index 0f4e7d0279..c4dc829a34 100644 --- a/crates/dim-acp/src/commands.rs +++ b/crates/dim-acp/src/commands.rs @@ -1,6 +1,6 @@ use crate::{config::Config, rpc::Rpc}; use agent_client_protocol::{Error, schema::v1 as acp}; -use dim_agent_types::{DEFAULT_BRANCH_ID, GoalRead, GoalViewStatus}; +use dim_agent_types::{GoalRead, GoalViewStatus}; use serde::Deserialize; use serde_json::{Value, json}; use tokio_util::sync::CancellationToken; @@ -80,6 +80,7 @@ pub(crate) fn available(config: &Config) -> Vec { pub(crate) async fn run( rpc: &Rpc, id: &str, + branch: &str, config: &Config, name: &str, words: &str, @@ -98,7 +99,7 @@ pub(crate) async fn run( let result = rpc .call( "session.context.compact", - json!({"sessionId":id,"branchId":DEFAULT_BRANCH_ID}), + json!({"sessionId":id,"branchId":branch}), ) .await; match result { @@ -114,8 +115,8 @@ pub(crate) async fn run( usage(rpc, &config.model.as_ref().unwrap().provider_id, cancelled).await? } "usage" => "Usage: /usage".into(), - "goal" => goal(rpc, id, words, cancelled).await?, - "loop" => loops(rpc, id, words, cancelled).await?, + "goal" => goal(rpc, id, branch, words, cancelled).await?, + "loop" => loops(rpc, id, branch, words, cancelled).await?, _ => unreachable!(), }; Ok(Some(text)) @@ -124,6 +125,7 @@ pub(crate) async fn run( async fn goal( rpc: &Rpc, id: &str, + branch: &str, words: &str, cancelled: &CancellationToken, ) -> Result { @@ -132,7 +134,7 @@ async fn goal( if matches!(verb, "set" | "edit") && rest.is_empty() { return Ok(GOAL_USAGE.into()); } - let query = json!({"sessionId":id,"branchId":DEFAULT_BRANCH_ID}); + let query = json!({"sessionId":id,"branchId":branch}); let mut read: GoalRead = rpc.typed("session.goal.get", query.clone()).await?; if !words.is_empty() { let (method, objective) = match verb { @@ -236,6 +238,7 @@ fn loop_report(loops: &[Loop]) -> String { async fn loops( rpc: &Rpc, id: &str, + branch: &str, words: &str, cancelled: &CancellationToken, ) -> Result { @@ -248,7 +251,7 @@ async fn loops( let listed: LoopList = rpc .typed( "session.loop.list", - json!({"sessionId":id,"branchId":DEFAULT_BRANCH_ID}), + json!({"sessionId":id,"branchId":branch}), ) .await?; if words.is_empty() { @@ -311,7 +314,8 @@ async fn loops( .checked_mul(scale) }) .filter(|seconds| *seconds > 0 && !rest.is_empty()); - let mut params = json!({"sessionId":id,"branchId":DEFAULT_BRANCH_ID,"prompt":if seconds.is_some() {rest} else {words}}); + let mut params = + json!({"sessionId":id,"branchId":branch,"prompt":if seconds.is_some() {rest} else {words}}); if let Some(seconds) = seconds { params["everySeconds"] = json!(seconds); } diff --git a/crates/dim-acp/src/config.rs b/crates/dim-acp/src/config.rs index ca8b963f56..0c77b72ca1 100644 --- a/crates/dim-acp/src/config.rs +++ b/crates/dim-acp/src/config.rs @@ -1,7 +1,7 @@ use crate::rpc::Rpc; use agent_client_protocol::{Error, schema::v1 as acp}; -use dim_agent_types::{DEFAULT_BRANCH_ID, ModelId, PermissionPolicy, PermissionPreset}; -use dim_client::wire::{Configuration, Event, EventContent}; +use dim_agent_types::{ModelId, PermissionPolicy, PermissionPreset, ROOT_BRANCH_ID}; +use dim_client::wire::{AdoptedConfiguration, Configuration, Event, EventContent}; use serde::Deserialize; use serde_json::json; use std::collections::{HashMap, HashSet}; @@ -97,10 +97,34 @@ pub(crate) async fn models(rpc: &Rpc) -> Result, Error> { Ok(choices) } +/// The configuration `branch` adopted at `through`, or at its head when +/// omitted, with that line's own committed cutoff. Callers ask a server that +/// offers the read: one without it cannot name this line's configuration, and +/// the attach reply's is the root's (design §14). +pub(crate) async fn adopted( + rpc: &Rpc, + session_id: &str, + branch: &str, + through: Option, +) -> Result<(u64, Option), Error> { + let mut params = json!({"sessionId":session_id,"branchId":branch}); + if let Some(through) = through { + params["through"] = json!(through); + } + let reply: AdoptedConfiguration = rpc.typed("session.model.get", params).await?; + if reply.branch_id != branch { + return Err(Error::internal_error().data(json!({"code":"model_get_answered_another_line"}))); + } + Ok((reply.through, reply.configuration.map(Configuration::from))) +} + impl Config { + /// Reads the Session's configuration for `branch`, the line its + /// conversation is on: its policy and its model are that line's (design §4). pub(crate) async fn read( rpc: &Rpc, id: &str, + branch: &str, model: Option, ) -> Result { let mut config = Self { @@ -134,7 +158,7 @@ impl Config { config.policy = Some( rpc.typed( "session.permission.get", - json!({"sessionId":id,"branchId":DEFAULT_BRANCH_ID}), + json!({"sessionId":id,"branchId":branch}), ) .await?, ); @@ -289,33 +313,36 @@ impl Config { } pub(crate) async fn recover_model(rpc: &Rpc, id: &str, value: &str) -> Result { - let mut config = Self::read(rpc, id, None).await?; - config.set_model(rpc, id, value, true).await?; - #[derive(Deserialize)] - struct Current { - configuration: Option, - } - #[derive(Deserialize)] - #[serde(rename_all = "camelCase")] - struct AdoptedConfiguration { - model: ModelId, - capability_snapshot: Option>, - model_preferences: Option, + let branch = if rpc.supports("session.branches") { + let directory: dim_client::wire::BranchDirectory = rpc + .typed("session.branches", json!({"sessionId":id})) + .await?; + directory + .default_branch_id + .unwrap_or_else(|| ROOT_BRANCH_ID.to_owned()) + } else { + ROOT_BRANCH_ID.to_owned() + }; + let mut config = Self::read(rpc, id, &branch, None).await?; + // `session.attach` checks its route against the root and `session.submit` + // against the line it targets: restore an expired route on both. + let root = config.set_model(rpc, id, ROOT_BRANCH_ID, value, true).await; + if branch == ROOT_BRANCH_ID { + root?; + } else { + let line = config.set_model(rpc, id, &branch, value, true).await; + match (root, line) { + (Ok(()), Ok(())) => {} + (Ok(()), Err(error)) | (Err(error), Ok(())) + if error.data.as_ref().is_some_and(|data| { + data["nativeAppError"] == "provider_route_not_expired" + }) => {} + (Err(error), _) => return Err(error), + (_, Err(error)) => return Err(error), + } } - let current: Current = rpc - .typed( - "session.model.get", - json!({"sessionId":id,"branchId":DEFAULT_BRANCH_ID}), - ) - .await?; - let current = current.configuration.ok_or_else(Error::internal_error)?; - config.model = Some(Configuration { - provider_id: current.model.provider_id, - model_id: current.model.model_id, - catalog_provider_id: None, - capability_snapshot: current.capability_snapshot, - model_preferences: current.model_preferences, - }); + let (_, current) = adopted(rpc, id, &branch, None).await?; + config.model = Some(current.ok_or_else(Error::internal_error)?); Ok(config) } @@ -323,6 +350,7 @@ impl Config { &mut self, rpc: &Rpc, id: &str, + branch: &str, value: &str, require_expired_route: bool, ) -> Result<(), Error> { @@ -335,7 +363,7 @@ impl Config { #[serde(rename_all = "camelCase")] struct Select<'a> { session_id: &'a str, - branch_id: &'static str, + branch_id: &'a str, provider_id: &'a str, model_id: &'a str, #[serde(skip_serializing_if = "Option::is_none")] @@ -348,7 +376,7 @@ impl Config { .ok_or_else(Error::invalid_params)?; let params = serde_json::to_value(Select { session_id: id, - branch_id: DEFAULT_BRANCH_ID, + branch_id: branch, provider_id: &model.provider, model_id: &model.id, require_expired_route: require_expired_route.then_some(true), @@ -373,6 +401,7 @@ impl Config { mut self, rpc: &Rpc, id: &str, + branch: &str, key: &str, value: &str, ) -> Result { @@ -381,17 +410,17 @@ impl Config { let current: Policy = rpc .typed( "session.permission.get", - json!({"sessionId":id,"branchId":DEFAULT_BRANCH_ID}), + json!({"sessionId":id,"branchId":branch}), ) .await?; let mut policy = current.policy; policy.preset = serde_json::from_value(json!(value)).map_err(|_| Error::invalid_params())?; - rpc.call("session.permission.update",json!({"sessionId":id,"branchId":DEFAULT_BRANCH_ID,"expectedVersion":current.version,"policy":policy})).await?; + rpc.call("session.permission.update",json!({"sessionId":id,"branchId":branch,"expectedVersion":current.version,"policy":policy})).await?; self.policy = Some( rpc.typed( "session.permission.get", - json!({"sessionId":id,"branchId":DEFAULT_BRANCH_ID}), + json!({"sessionId":id,"branchId":branch}), ) .await?, ); @@ -414,7 +443,7 @@ impl Config { let result: Adopted = rpc .typed( "session.model.update", - json!({"sessionId":id,"branchId":DEFAULT_BRANCH_ID,"modelPreferences":{"reasoningEffort":patch}}), + json!({"sessionId":id,"branchId":branch,"modelPreferences":{"reasoningEffort":patch}}), ) .await?; if !matches!(result.outcome.as_str(), "adopted" | "unchanged") { @@ -422,7 +451,7 @@ impl Config { } } "model" => { - self.set_model(rpc, id, value, false).await?; + self.set_model(rpc, id, branch, value, false).await?; self.models = models(rpc).await?; } _ => return Err(Error::invalid_params()), diff --git a/crates/dim-acp/src/gateway.rs b/crates/dim-acp/src/gateway.rs index 6fe28e9ea9..ea75984d52 100644 --- a/crates/dim-acp/src/gateway.rs +++ b/crates/dim-acp/src/gateway.rs @@ -6,14 +6,13 @@ use crate::{ }; use agent_client_protocol::{Client, ConnectionTo, Error, UntypedMessage, schema::v1 as acp}; use dim_agent_types::{ - DEFAULT_BRANCH_ID, ModelPreferenceUpdate, PermissionPreset, PreferenceUpdate, + ModelPreferenceUpdate, PermissionPreset, PreferenceUpdate, ROOT_BRANCH_ID, SessionConfigExpectation, TurnOutcome, }; use dim_client::window::Window; use dim_client::wire::{ - Attached, Configuration, DisplayNotice, DisplayPage, Event, EventContent, EventNotice, - HistoryWindow, PendingDelegations, PendingInputs, PendingQuestions, PendingTasks, Progress, - TurnRead, + Attached, DisplayNotice, DisplayPage, Event, EventContent, EventNotice, HistoryWindow, + PendingDelegations, PendingInputs, PendingQuestions, PendingTasks, Progress, TurnRead, }; use serde::{Deserialize, Serialize}; use serde_json::{Value, json}; @@ -32,6 +31,16 @@ pub(crate) enum Incoming { Work(u64, Box), } +/// A configuration re-read while a write was in flight: the line it belongs +/// to and, when the line's model was read, the cutoff that read answered at. +pub(crate) struct Refreshed { + branch: String, + /// The line's model cutoff; `None` when the refresh kept the model the + /// write started from instead of reading the line's. + model_through: Option, + config: Config, +} + pub(crate) enum Work { Providers { reply: Responder, @@ -88,7 +97,7 @@ pub(crate) enum Work { mode: bool, revision: Option, result: Result, - refreshed: Option, + refreshed: Option, }, Answer { key: String, @@ -255,6 +264,16 @@ fn cancelled_prompt(unconfirmed: bool) -> acp::PromptResponse { response } } + +/// The reply for a submitted prompt whose outcome this connection cannot read. +fn submission_unknown(session: &str, submission: &str) -> Error { + Error::new( + -32001, + "Submission outcome is unknown; load this Session before sending again", + ) + .data(json!({"code":"submission_unknown","sessionId":session,"submissionId":submission})) +} + struct Interaction { session: String, token: CancellationToken, @@ -1063,10 +1082,11 @@ impl Gateway { { return reply.respond_with_error(busy()); } + let conversation = session.projection.branch.clone(); let rpc = self.rpc.clone(); self.spawn(async move { let mut query = - json!({"sessionId":args.session_id,"branchId":DEFAULT_BRANCH_ID,"limit":limit}); + json!({"sessionId":args.session_id,"branchId":conversation,"limit":limit}); if rpc.supports("session.history.display.transcript") { query["tail"] = json!(true); query["transcript"] = json!(true); @@ -1154,7 +1174,9 @@ impl Gateway { { return Err(Error::invalid_params()); } - let mut params = json!({"sessionId":source,"branchId":DEFAULT_BRANCH_ID}); + // The fork copies the source's root, so its cut is a + // root position whatever line that Session shows. + let mut params = json!({"sessionId":source,"branchId":ROOT_BRANCH_ID}); if let Some(turn) = &controls.fork_turn { params["turnId"] = json!(turn); } @@ -1224,6 +1246,7 @@ impl Gateway { let name = name.to_owned(); let words = words.to_owned(); let config = session.config.clone(); + let conversation = session.projection.branch.clone(); let command_id = uuid::Uuid::new_v4(); let cancelled = CancellationToken::new(); session.command = Some(Command { @@ -1235,9 +1258,16 @@ impl Gateway { cancelled: cancelled.clone(), }); self.spawn(async move { - let result = - crate::commands::run(&rpc, &id, &config, &name, &words, &cancelled) - .await; + let result = crate::commands::run( + &rpc, + &id, + &conversation, + &config, + &name, + &words, + &cancelled, + ) + .await; Work::Command { id, command_id, @@ -1279,6 +1309,7 @@ impl Gateway { ended: HashMap::new(), deleted: HashSet::new(), }); + let conversation = session.projection.branch.clone(); let mcp = self.mcp.clone(); self.spawn(async move { let mut sent = false; @@ -1293,7 +1324,7 @@ impl Gateway { }; if uploading.is_cancelled() { return Err(Error::new(-32800, "Request cancelled before submission")); } sent = true; - rpc.typed("session.submit", json!({"sessionId":id,"branchId":DEFAULT_BRANCH_ID,"submissionId":submission,"user":user,"mode":"queue"})).await + rpc.typed("session.submit", json!({"sessionId":id,"branchId":conversation,"submissionId":submission,"user":user,"mode":"queue"})).await }.await; Work::Submitted { id, submission, result,sent } }); @@ -1405,9 +1436,13 @@ impl Gateway { } session.configuring = true; let config = session.config.clone(); + let conversation = session.projection.branch.clone(); let revision = session.config_revision; self.spawn(async move { - let result = config.clone().set(&rpc, &id, &key, &value).await; + let result = config + .clone() + .set(&rpc, &id, &conversation, &key, &value) + .await; let refreshed = if let Err(error) = &result { match error .data @@ -1418,13 +1453,17 @@ impl Gateway { let current = rpc .typed( "session.permission.get", - json!({"sessionId":id,"branchId":DEFAULT_BRANCH_ID}), + json!({"sessionId":id,"branchId":conversation}), ) .await; current.ok().map(|policy| { let mut config = config; config.policy = Some(policy); - config + Refreshed { + branch: conversation.clone(), + model_through: None, + config, + } }) } Some("configuration_superseded") => async { @@ -1439,14 +1478,29 @@ impl Gateway { params }) .await?; - let model = attached.model.map(|model| Configuration { - provider_id: model.provider_id, - catalog_provider_id: attached.catalog_provider_id, - model_id: model.model_id, - capability_snapshot: attached.capability_snapshot, - model_preferences: attached.model_preferences, - }); - Config::read(&rpc, &id, model).await + // The reply's model is the root's; the line being + // configured takes its own configuration at the + // line's head, re-read after the change it reported + // (design §14). + let (model, model_through) = if conversation == ROOT_BRANCH_ID + || attached.default_branch.is_none() + { + (attached.configuration(), Some(attached.sequence)) + } else if rpc.supports("session.model.get") { + let (cutoff, model) = + crate::config::adopted(&rpc, &id, &conversation, None) + .await?; + (model, Some(cutoff)) + } else { + (None, None) + }; + Config::read(&rpc, &id, &conversation, model) + .await + .map(|config| Refreshed { + branch: conversation, + model_through, + config, + }) } .await .ok(), @@ -1543,6 +1597,7 @@ impl Gateway { return; }; session.stopping = true; + let conversation = session.projection.branch.clone(); let (submission, input) = match &mut session.prompt { Some(prompt) => { prompt.cancelling = true; @@ -1558,7 +1613,7 @@ impl Gateway { let value = rpc .call( "session.input.withdraw", - json!({"sessionId":id,"branchId":DEFAULT_BRANCH_ID,"inputId":input}), + json!({"sessionId":id,"branchId":conversation,"inputId":input}), ) .await?; if value["status"] == "deleted" { @@ -1567,7 +1622,7 @@ impl Gateway { } rpc.call( "session.stop", - json!({"sessionId":id,"branchId":DEFAULT_BRANCH_ID}), + json!({"sessionId":id,"branchId":conversation}), ) .await } @@ -2151,14 +2206,24 @@ impl Gateway { } } Err(error) => { - if let Some(mut config) = refreshed { - if revision != session.config_revision { - config.model.clone_from(&session.config.model); - if let (Some(policy), Some(current)) = + if let Some(refreshed) = refreshed + && refreshed.branch == session.projection.branch + { + let mut config = refreshed.config; + if revision != session.config_revision + && let (Some(policy), Some(current)) = (&mut config.policy, &session.config.policy) - { - policy.policy = current.policy.clone(); + { + policy.policy = current.policy.clone(); + } + if let Some(through) = refreshed.model_through { + if through < session.model_through { + config.model.clone_from(&session.config.model); + } else { + session.model_through = through; } + } else { + config.model.clone_from(&session.config.model); } session.config = config; let options = session.config.options(); @@ -2291,7 +2356,11 @@ impl Gateway { input, prompt_turn, }) => { - let previous_through = session.projection.through; + // The reattach follows the Session's default branch: a + // history watermark is one line's, so another line's + // events are all news to this session (design §14). + let moved = session.projection.branch != prepared.branch; + let previous_through = if moved { 0 } else { session.projection.through }; let branch = prepared.branch; session.projection = Projection::new( branch.clone(), @@ -2344,6 +2413,18 @@ impl Gateway { } } } + // An accepted prompt stays on the line that accepted it, + // and this session now follows another: its outcome is + // not readable here, so the recovery answers it + // explicitly instead of leaving it open (design §14). + if moved + && let Some(prompt) = &mut session.prompt + && prompt.terminal.is_none() + && prompt.input.is_some() + { + prompt.terminal = + Some(Err(submission_unknown(&id, &prompt.submission))); + } let mut snapshots = Vec::new(); for event in &prepared.history { snapshots.extend(session.subagents.event(&id, &branch, event)); @@ -2405,7 +2486,10 @@ impl Gateway { if prompt.cancelled { prompt.reply.respond(cancelled_prompt(true))?; } else { - prompt.reply.respond_with_error(Error::new(-32001,"Submission outcome is unknown; load this Session before sending again").data(json!({"code":"submission_unknown","sessionId":id,"submissionId":prompt.submission})))?; + prompt.reply.respond_with_error(submission_unknown( + &id, + &prompt.submission, + ))?; } } else if session .prompt @@ -2576,11 +2660,11 @@ impl Gateway { } "session.model.progress" => { let progress: Progress = decode_native(params)?; - if progress.branch_id != DEFAULT_BRANCH_ID { - return Ok(()); - } let id = progress.session_id.clone(); if let Some(Slot::Ready(session)) = self.sessions.get_mut(&id) { + if progress.branch_id != session.projection.branch { + return Ok(()); + } let updates = session.projection.progress(progress); for update in updates { self.update(&id, update).await?; @@ -2843,6 +2927,7 @@ impl Gateway { Slot::Ready(session) => Some(( id.clone(), session.cwd.clone(), + session.projection.branch.clone(), session .prompt .as_ref() @@ -2864,7 +2949,7 @@ impl Gateway { if sessions.is_empty() { self.recovering = false; } - for (id, cwd, submission, accepted_input, turn_id) in sessions { + for (id, cwd, conversation, submission, accepted_input, turn_id) in sessions { let rpc = self.rpc.clone(); let mcp = self.mcp.clone(); self.spawn_generation(generation, async move { @@ -2880,7 +2965,7 @@ impl Gateway { loop { let query = json!({ "sessionId":id, - "branchId":DEFAULT_BRANCH_ID, + "branchId":conversation, "submissionId":submission, }); match rpc.typed("session.input_lookup", query).await? { @@ -2902,7 +2987,12 @@ impl Gateway { .as_ref() .map(|event| event.id.clone()) .or(accepted_input); - let prompt_turn = if turn_id.is_some() || input_id.is_some() { + // The prompt is on the branch that accepted it, and the + // reattach follows the Session's default branch: another + // line's cut and history cannot answer for it, so the + // recovery settles the prompt instead (design §14). + let kept = conversation == prepared.branch; + let prompt_turn = if kept && (turn_id.is_some() || input_id.is_some()) { let mut query = json!({"sessionId":id,"branchId":prepared.branch.clone(),"through":prepared.through}); if let Some(turn) = turn_id { @@ -3173,6 +3263,7 @@ impl Gateway { return; } session.usage_pending = true; + let conversation = session.projection.branch.clone(); let id = id.to_owned(); let rpc = self.rpc.clone(); self.spawn(async move { @@ -3180,7 +3271,7 @@ impl Gateway { result: rpc .call( "session.context.usage", - json!({"sessionId":id,"branchId":DEFAULT_BRANCH_ID}), + json!({"sessionId":id,"branchId":conversation}), ) .await, id, @@ -3293,9 +3384,7 @@ async fn read_history( } // The whole recovery reads one branch's conversation: the history window // that yields the cutoff, the pending requests read from that cutoff, and - // the reply check. It reads the branch the Session shows by default without - // reading the Session's default branch, so `DEFAULT_BRANCH_ID` names it. - let conversation = DEFAULT_BRANCH_ID; + // the reply check. #[derive(Serialize)] #[serde(rename_all = "camelCase")] struct Attach<'a> { @@ -3332,13 +3421,37 @@ async fn read_history( } })?; drop(route_admission); - let model = attached.model.map(|model| Configuration { - provider_id: model.provider_id, - catalog_provider_id: attached.catalog_provider_id, - model_id: model.model_id, - capability_snapshot: attached.capability_snapshot, - model_preferences: attached.model_preferences, - }); + // The attach reply names the conversation's line, and the directory answers + // only for a server that predates the field, whose Session is on its root + // (design §4, §14). + let directory: Option = if rpc.supports("session.branches") { + Some( + rpc.typed("session.branches", json!({"sessionId":id})) + .await?, + ) + } else { + None + }; + let conversation = attached + .default_branch + .as_ref() + .map(|cursor| cursor.branch_id.clone()) + .or_else(|| { + directory + .as_ref() + .and_then(|directory| directory.default_branch_id.clone()) + }) + .unwrap_or_else(|| ROOT_BRANCH_ID.to_owned()); + // The reply's configuration is the root's (design §14): a conversation on + // a line takes that line's own, through `session.model.get` below. A reply + // that names no line comes from a server that cannot move the default + // branch, so its model is the Session's. + let seeded = attached.default_branch.is_none() || conversation == ROOT_BRANCH_ID; + let model = if seeded { + attached.configuration() + } else { + None + }; let (history, through, before) = { if !rpc.supports("session.history.latestTurn") { @@ -3348,7 +3461,7 @@ async fn read_history( loop { let args = window.params_with_display( id, - conversation, + &conversation, rpc.supports("session.history.display.tail"), rpc.supports("session.history.display.transcript"), ); @@ -3374,21 +3487,39 @@ async fn read_history( window.before, ) }; - let config = Config::read(rpc, id, model).await?; + let mut config = Config::read(rpc, id, &conversation, model).await?; + // A line's configuration is the one it adopted at its own cutoff. A + // display transcript omits `context/configured` and a bounded window can + // start after the adoption, so the line's own read answers it; a server + // without that read cannot name this line's, and the attach reply is the + // root's (design §14). + let mut model_through = if seeded { + dim_client::wire::resume_cursor( + attached.default_branch.as_ref(), + attached.sequence, + &conversation, + ) + .unwrap_or(0) + } else { + 0 + }; + if !seeded && rpc.supports("session.model.get") { + let (cutoff, adopted) = + crate::config::adopted(rpc, id, &conversation, Some(through)).await?; + config.model = adopted; + model_through = cutoff; + } let mut questions = HashMap::new(); if config.methods.contains("session.question.pending") { - let mut branches = vec![conversation.to_owned()]; - if rpc.supports("session.branches") { - let directory: dim_client::wire::BranchDirectory = rpc - .typed("session.branches", json!({"sessionId":id})) - .await?; - branches = directory + let branches: Vec = match &directory { + Some(directory) => directory .branches - .into_iter() + .iter() .filter(|branch| branch.state != "ended") - .map(|branch| branch.branch_id) - .collect(); - } + .map(|branch| branch.branch_id.clone()) + .collect(), + None => vec![conversation.clone()], + }; for branch in branches { let mut params = json!({"sessionId":id,"branchId":branch}); if branch == conversation { @@ -3428,7 +3559,7 @@ async fn read_history( if !config.methods.contains(method) { continue; } - let mut params = json!({"sessionId":id,"branchId":conversation,"through":through}); + let mut params = json!({"sessionId":id,"branchId":&conversation,"through":through}); loop { let value = rpc.call(method, params.clone()).await?; let (branch, cut, next) = match method { @@ -3471,6 +3602,9 @@ async fn read_history( .turn .filter(|turn| !turn.ended) .map(|turn| turn.turn_id); + // The attach reply's `defaultBranch` is this conversation's own cursor; + // its `sequence` stays the root's (design §14). A line's configuration was + // read from its own history, so only a later fact may replace it. Ok(Prepared { branch: conversation.to_owned(), history, @@ -3485,6 +3619,6 @@ async fn read_history( inputs, turn, output, - model_through: attached.sequence, + model_through, }) } diff --git a/crates/dim-acp/tests/branch_flow.rs b/crates/dim-acp/tests/branch_flow.rs new file mode 100644 index 0000000000..233711e4cd --- /dev/null +++ b/crates/dim-acp/tests/branch_flow.rs @@ -0,0 +1,1160 @@ +#![cfg(unix)] + +use dim_acp::{AcpGateway, Io}; +use dim_client::{Client, ConnectionConfig, DaemonProfile, Server}; +use rutis::host::CtxHost; +use serde_json::{Value, json}; +use std::{os::unix::fs::PermissionsExt, time::Duration}; +use tokio::{ + io::{AsyncBufReadExt, AsyncWriteExt, BufReader}, + net::UnixListener, + sync::oneshot, +}; + +async fn read_frame(reader: &mut (impl AsyncBufReadExt + Unpin)) -> Option { + let mut line = String::new(); + let read = tokio::time::timeout(Duration::from_secs(5), reader.read_line(&mut line)) + .await + .unwrap() + .unwrap(); + (read > 0).then(|| serde_json::from_str(&line).unwrap()) +} + +async fn frame(reader: &mut (impl AsyncBufReadExt + Unpin)) -> Value { + read_frame(reader).await.expect("the peer stays open") +} + +/// The reply to `id`, skipping the notifications that may come first. +async fn reply(reader: &mut (impl AsyncBufReadExt + Unpin), id: u64) -> Value { + loop { + let frame = frame(reader).await; + if frame["id"] == json!(id) { + return frame; + } + } +} + +async fn send(writer: &mut (impl AsyncWriteExt + Unpin), value: Value) { + writer + .write_all(format!("{value}\n").as_bytes()) + .await + .unwrap(); + writer.flush().await.unwrap(); +} + +/// An ACP call names no line: the gateway reads the Session's default branch +/// once and every call it makes reaches it (design §4, §9, §14). +#[tokio::test] +async fn a_gateway_call_without_a_line_targets_the_default_branch() { + let home = tempfile::tempdir_in("/tmp").unwrap(); + let endpoint = home.path().join("daemon.sock"); + let cwd = home.path().to_str().unwrap().to_owned(); + let listener = UnixListener::bind(&endpoint).unwrap(); + std::fs::set_permissions(&endpoint, std::fs::Permissions::from_mode(0o600)).unwrap(); + let (submitted, submit_seen) = oneshot::channel(); + let daemon_cwd = cwd.clone(); + let server = tokio::spawn(async move { + let (stream, _) = listener.accept().await.unwrap(); + let (read, mut write) = stream.into_split(); + let mut read = BufReader::new(read); + let hello = frame(&mut read).await; + send(&mut write,json!({"jsonrpc":"2.0","id":hello["id"],"result":{"instanceId":"fixture","serverVersion":"fixture","protocolVersion":3,"daemonProfile":{"kind":"product"},"features":["session.create","session.attach","session.attach.expectedCwd","session.detach","session.history","session.history.latestTurn","session.input_lookup","session.submit","session.stop","session.branches","session.methods","session.input.pending","session.question.pending","session.turn.get","session.exec.pending"]}})).await; + let mut submitted = Some(submitted); + while let Some(request) = read_frame(&mut read).await { + let method = request["method"].as_str().unwrap_or_default().to_owned(); + let branch = request["params"]["branchId"] + .as_str() + .unwrap_or("main") + .to_owned(); + let through = request["params"]["through"].as_u64().unwrap_or(2); + let id = request["id"].clone(); + match method.as_str() { + "session.attach" => { + assert_eq!(request["params"]["expectedCwd"], json!(daemon_cwd)); + send( + &mut write, + json!({"jsonrpc":"2.0","id":id,"result":{ + "sequence":2,"cwd":daemon_cwd, + "model":{"providerId":"fixture","modelId":"fixture-model"}}}), + ) + .await; + } + "session.branches" => { + send(&mut write, json!({"jsonrpc":"2.0","id":id,"result":{ + "defaultBranchId":"line-1", + "branches":[ + {"branchId":"main","state":"open","head":2}, + {"branchId":"line-1","parentBranchId":"main","branchPoint":1,"state":"open","head":2}]}})).await; + } + "session.history" => { + assert_eq!(branch, "line-1", "the recovery reads the default branch"); + send( + &mut write, + json!({"jsonrpc":"2.0","id":id,"result":{ + "events":[],"through":2,"nextBefore":null,"nextAfter":2}}), + ) + .await; + } + "session.methods" => { + let methods: Vec<_> = [ + "session.input.pending", + "session.question.pending", + "session.exec.pending", + "session.turn.get", + ] + .into_iter() + .map(|name| json!({"name":name,"mutating":false})) + .collect(); + send( + &mut write, + json!({"jsonrpc":"2.0","id":id,"result":{"methods":methods}}), + ) + .await; + } + "session.question.pending" => { + send( + &mut write, + json!({"jsonrpc":"2.0","id":id,"result":{ + "branchId":branch,"through":through,"batches":[],"next":null}}), + ) + .await; + } + "session.exec.pending" => { + send( + &mut write, + json!({"jsonrpc":"2.0","id":id,"result":{ + "branchId":branch,"through":through,"tasks":[],"next":null}}), + ) + .await; + } + "session.input.pending" => { + send( + &mut write, + json!({"jsonrpc":"2.0","id":id,"result":{ + "branchId":branch,"through":through,"inputs":[],"next":null}}), + ) + .await; + } + "session.turn.get" => { + assert_eq!(branch, "line-1", "the turn read is the default branch's"); + send( + &mut write, + json!({"jsonrpc":"2.0","id":id,"result":{ + "branchId":branch,"through":through,"turn":null,"output":null}}), + ) + .await; + } + "session.submit" => { + assert_eq!( + request["params"]["branchId"], + json!("line-1"), + "a prompt with no line reaches the Session's default branch" + ); + send(&mut write, json!({"jsonrpc":"2.0","id":id,"result":{"event":{ + "id":"in-1","sequence":3,"create_at":1,"type":"input","name":"message", + "data":{"user":{"content":[{"type":"text","text":"hello"}]},"mode":"queue"}}}})).await; + submitted.take().unwrap().send(()).unwrap(); + } + "session.detach" => { + send(&mut write, json!({"jsonrpc":"2.0","id":id,"result":{}})).await; + break; + } + other => panic!("unexpected {other}: {request}"), + } + } + }); + let client = Client::connect(&ConnectionConfig { + endpoint, + server: Server { + program: "unused".into(), + embedded: false, + }, + profile: Some(DaemonProfile::Product), + client_kind: "other", + client_name: "AcpGateway", + protocol_version: 3, + }) + .await + .unwrap(); + let (peer, transport) = tokio::io::duplex(64 * 1024); + let (reader, writer) = tokio::io::split(transport); + let (gateway, finished) = AcpGateway::new( + client, + Io { + reader: Box::new(reader), + writer: Box::new(writer), + }, + None, + env!("CARGO_PKG_VERSION").to_owned(), + ); + let root = rutis::Ctx::root().unwrap(); + let mounted = root.plugin(gateway); + (&mounted).await.unwrap(); + let (read, mut write) = tokio::io::split(peer); + let mut read = BufReader::new(read); + send(&mut write,json!({"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":1,"clientCapabilities":{}}})).await; + let initialize = reply(&mut read, 1).await; + assert!(initialize["error"].is_null(), "{initialize}"); + send(&mut write,json!({"jsonrpc":"2.0","id":2,"method":"session/load","params":{"sessionId":"session","cwd":cwd,"mcpServers":[]}})).await; + let loaded = reply(&mut read, 2).await; + assert!(loaded["error"].is_null(), "{loaded}"); + send(&mut write,json!({"jsonrpc":"2.0","id":3,"method":"session/prompt","params":{"sessionId":"session","prompt":[{"type":"text","text":"hello"}]}})).await; + tokio::time::timeout(Duration::from_secs(5), submit_seen) + .await + .unwrap() + .unwrap(); + // The prompt is answered on the line the default branch names; the reply + // itself is not this test's subject. + drop(read); + let _ = write.shutdown().await; + let _ = tokio::time::timeout(Duration::from_secs(5), finished).await; + mounted.dispose().await.unwrap(); + root.shutdown().await.unwrap(); + server.await.unwrap(); +} + +/// The option a session reply or a config update states for `id`. +fn option<'a>(value: &'a Value, id: &str) -> &'a Value { + value + .pointer("/result/configOptions") + .or_else(|| value.pointer("/params/update/configOptions")) + .and_then(Value::as_array) + .expect("config options") + .iter() + .find(|option| option["id"] == json!(id)) + .expect("the named option") +} + +/// The next `session/update` that carries config options. +async fn config_update(reader: &mut (impl AsyncBufReadExt + Unpin)) -> Value { + loop { + let frame = frame(reader).await; + if frame["params"]["update"]["sessionUpdate"] == json!("config_option_update") { + return frame; + } + } +} + +/// The model is the loaded line's own, at or below its cursor: the attach +/// reply's model is the root's (design §14), so a Session whose conversation is +/// on a line shows the configuration that line adopted, and only the root takes +/// the reply's. The reply names the line and the directory only answers for a +/// server that does not carry the field (design §14). +#[tokio::test] +async fn a_gateway_load_folds_the_default_branchs_cursor() { + for (line, cursor, listed_line) in [ + ("main", 2, "main"), + ("line-1", 5, "line-1"), + ("line-1", 5, "main"), + ] { + let home = tempfile::tempdir_in("/tmp").unwrap(); + let endpoint = home.path().join("daemon.sock"); + let cwd = home.path().to_str().unwrap().to_owned(); + let listener = UnixListener::bind(&endpoint).unwrap(); + std::fs::set_permissions(&endpoint, std::fs::Permissions::from_mode(0o600)).unwrap(); + let daemon_cwd = cwd.clone(); + let server = tokio::spawn(async move { + let (stream, _) = listener.accept().await.unwrap(); + let (read, mut write) = stream.into_split(); + let mut read = BufReader::new(read); + let hello = frame(&mut read).await; + send(&mut write,json!({"jsonrpc":"2.0","id":hello["id"],"result":{"instanceId":"fixture","serverVersion":"fixture","protocolVersion":3,"daemonProfile":{"kind":"product"},"features":["session.create","session.attach","session.attach.expectedCwd","session.branches","session.detach","session.exec.pending","session.history","session.history.latestTurn","session.input.pending","session.input_lookup","session.methods","session.model.get","session.model.update","session.question.pending","session.stop","session.submit","session.summaries","session.turn.get","provider.models.query"]}})).await; + let mut listed = 0; + while let Some(request) = read_frame(&mut read).await { + let method = request["method"].as_str().unwrap_or_default().to_owned(); + let branch = request["params"]["branchId"] + .as_str() + .unwrap_or(line) + .to_owned(); + let through = request["params"]["through"].as_u64().unwrap_or(cursor); + let id = request["id"].clone(); + match method.as_str() { + "session.attach" => { + assert_eq!(request["params"]["expectedCwd"], json!(daemon_cwd)); + send(&mut write,json!({"jsonrpc":"2.0","id":id,"result":{"sequence":2,"cwd":daemon_cwd,"model":{"providerId":"fixture","modelId":"A"},"defaultBranch":{"branchId":line,"sequence":cursor}}})).await; + } + "session.branches" => { + let mut branches = vec![json!({"branchId":"main","state":"open","head":2})]; + if line != "main" { + branches.push(json!({"branchId":line,"parentBranchId":"main","branchPoint":1,"state":"open","head":2})); + } + send(&mut write,json!({"jsonrpc":"2.0","id":id,"result":{"defaultBranchId":listed_line,"branches":branches}})).await; + } + "session.history" => { + assert_eq!(branch, line, "the recovery reads the default branch"); + assert!( + request["params"].get("before").is_none(), + "a line's configuration is not paged out of its history" + ); + send(&mut write,json!({"jsonrpc":"2.0","id":id,"result":{"events":[],"through":cursor,"nextBefore":1,"nextAfter":cursor}})).await; + } + "session.model.get" => { + assert_eq!(branch, line, "a line's configuration is its own"); + assert_eq!(through, cursor, "read at the line's own cursor"); + send(&mut write,json!({"jsonrpc":"2.0","id":id,"result":{"branchId":line,"through":cursor,"configuration":{"model":{"providerId":"fixture","modelId":"B"}}}})).await; + } + "provider.models.query" => { + send(&mut write,json!({"jsonrpc":"2.0","id":id,"result":{"models":[{"providerId":"fixture","model":{"id":"A","name":"A"}},{"providerId":"fixture","model":{"id":"B","name":"B"}}],"next":null}})).await; + } + "session.summaries" => { + send(&mut write, json!({"jsonrpc":"2.0","id":id,"result":[]})).await; + if listed == 0 { + listed = 1; + let sequence = cursor + 1; + send(&mut write,json!({"jsonrpc":"2.0","method":"session.event","params":{"sessionId":"session","branchId":line,"event":{"id":format!("configured-{sequence}"),"sequence":sequence,"create_at":1,"type":"context","name":"configured","data":{"timeline":line,"revision":"r1","provider_id":"fixture","model_id":"B"}}}})).await; + } + } + "session.methods" => { + let methods: Vec<_> = [ + "session.input.pending", + "session.question.pending", + "session.exec.pending", + "session.turn.get", + ] + .into_iter() + .map(|name| json!({"name":name,"mutating":false})) + .collect(); + send( + &mut write, + json!({"jsonrpc":"2.0","id":id,"result":{"methods":methods}}), + ) + .await; + } + "session.exec.pending" => { + send(&mut write,json!({"jsonrpc":"2.0","id":id,"result":{"branchId":branch,"through":through,"tasks":[],"next":null}})).await; + } + "session.input.pending" => { + send(&mut write,json!({"jsonrpc":"2.0","id":id,"result":{"branchId":branch,"through":through,"inputs":[],"next":null}})).await; + } + "session.question.pending" => { + send(&mut write,json!({"jsonrpc":"2.0","id":id,"result":{"branchId":branch,"through":through,"batches":[],"next":null}})).await; + } + "session.turn.get" => { + send(&mut write,json!({"jsonrpc":"2.0","id":id,"result":{"branchId":branch,"through":through,"turn":null,"output":null}})).await; + } + "session.detach" => { + send(&mut write, json!({"jsonrpc":"2.0","id":id,"result":{}})).await; + break; + } + other => panic!("unexpected {other}: {request}"), + } + } + }); + let client = Client::connect(&ConnectionConfig { + endpoint, + server: Server { + program: "unused".into(), + embedded: false, + }, + profile: Some(DaemonProfile::Product), + client_kind: "other", + client_name: "AcpGateway", + protocol_version: 3, + }) + .await + .unwrap(); + let (peer, transport) = tokio::io::duplex(64 * 1024); + let (reader, writer) = tokio::io::split(transport); + let (gateway, finished) = AcpGateway::new( + client, + Io { + reader: Box::new(reader), + writer: Box::new(writer), + }, + None, + env!("CARGO_PKG_VERSION").to_owned(), + ); + let root = rutis::Ctx::root().unwrap(); + let mounted = root.plugin(gateway); + (&mounted).await.unwrap(); + let (read, mut write) = tokio::io::split(peer); + let mut read = BufReader::new(read); + send(&mut write,json!({"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":1,"clientCapabilities":{}}})).await; + let initialize = reply(&mut read, 1).await; + assert!(initialize["error"].is_null(), "{initialize}"); + send(&mut write,json!({"jsonrpc":"2.0","id":2,"method":"session/load","params":{"sessionId":"session","cwd":cwd,"mcpServers":[]}})).await; + let loaded = reply(&mut read, 2).await; + assert!(loaded["error"].is_null(), "{loaded}"); + // The reply's model is the root's, so only the root shows it; a line + // shows the configuration its own window adopted at or below the cursor. + assert_eq!( + option(&loaded, "model")["currentValue"], + json!(if line == "main" { "A" } else { "B" }), + "the load shows the model of the line its cursor names" + ); + send( + &mut write, + json!({"jsonrpc":"2.0","id":3,"method":"session/list","params":{}}), + ) + .await; + let update = config_update(&mut read).await; + assert_eq!( + option(&update, "model")["currentValue"], + json!("B"), + "a fact after the cursor reaches the options: {update}" + ); + drop(read); + let _ = write.shutdown().await; + let _ = tokio::time::timeout(Duration::from_secs(5), finished).await; + mounted.dispose().await.unwrap(); + root.shutdown().await.unwrap(); + server.await.unwrap(); + } +} + +/// The production display transcript omits `context/configured`: a line's +/// adopted model comes from `session.model.get` at the cursor its attach +/// reply names, and a superseded model update refreshes from the same read +/// rather than the reply's root configuration. +#[tokio::test] +async fn a_gateway_line_reads_its_model_when_display_omits_the_configuration() { + let home = tempfile::tempdir_in("/tmp").unwrap(); + let endpoint = home.path().join("daemon.sock"); + let cwd = home.path().to_str().unwrap().to_owned(); + let listener = UnixListener::bind(&endpoint).unwrap(); + std::fs::set_permissions(&endpoint, std::fs::Permissions::from_mode(0o600)).unwrap(); + let daemon_cwd = cwd.clone(); + let server = tokio::spawn(async move { + let (stream, _) = listener.accept().await.unwrap(); + let (read, mut write) = stream.into_split(); + let mut read = BufReader::new(read); + let hello = frame(&mut read).await; + send(&mut write,json!({"jsonrpc":"2.0","id":hello["id"],"result":{"instanceId":"fixture","serverVersion":"fixture","protocolVersion":3,"daemonProfile":{"kind":"product"},"features":["session.create","session.attach","session.attach.expectedCwd","session.branches","session.detach","session.exec.pending","session.history","session.history.display","session.history.detail","session.history.display.tail","session.history.display.transcript","session.history.latestTurn","session.input.pending","session.input_lookup","session.methods","session.model.get","session.model.update","session.question.pending","session.stop","session.submit","session.summaries","session.turn.get","provider.models.query"]}})).await; + let mut attachments = 0; + while let Some(request) = read_frame(&mut read).await { + let method = request["method"].as_str().unwrap_or_default().to_owned(); + let id = request["id"].clone(); + match method.as_str() { + "session.attach" => { + attachments += 1; + let (sequence, model) = if attachments == 1 { (5, "A") } else { (6, "C") }; + send(&mut write,json!({"jsonrpc":"2.0","id":id,"result":{"sequence":2,"cwd":daemon_cwd,"model":{"providerId":"fixture","modelId":model},"defaultBranch":{"branchId":"line-1","sequence":sequence}}})).await; + } + "session.branches" => { + send(&mut write,json!({"jsonrpc":"2.0","id":id,"result":{"defaultBranchId":"line-1","branches":[{"branchId":"main","state":"open","head":2},{"branchId":"line-1","parentBranchId":"main","branchPoint":1,"state":"open","head":5}]}})).await; + } + "session.history.display" => { + assert_eq!(request["params"]["branchId"], json!("line-1")); + send(&mut write,json!({"jsonrpc":"2.0","id":id,"result":{"items":[],"through":5,"nextBefore":1,"nextAfter":5,"done":true}})).await; + } + "session.model.get" => { + assert_eq!(request["params"]["branchId"], json!("line-1")); + let through = request["params"]["through"].as_u64().unwrap_or(6); + send(&mut write,json!({"jsonrpc":"2.0","id":id,"result":{"branchId":"line-1","through":through,"configuration":{"model":{"providerId":"fixture","modelId":"B"}}}})).await; + } + "session.methods" => { + let methods: Vec<_> = [ + "session.input.pending", + "session.question.pending", + "session.exec.pending", + "session.turn.get", + "session.model.update", + ] + .into_iter() + .map(|name| json!({"name":name,"mutating":name == "session.model.update"})) + .collect(); + send( + &mut write, + json!({"jsonrpc":"2.0","id":id,"result":{"methods":methods}}), + ) + .await; + } + "provider.models.query" => { + send( + &mut write, + json!({"jsonrpc":"2.0","id":id,"result":{"models":[ + {"providerId":"fixture","model":{"id":"A","name":"A"}}, + {"providerId":"fixture","model":{"id":"B","name":"B"}}, + {"providerId":"fixture","model":{"id":"C","name":"C"}}],"next":null}}), + ) + .await; + } + "session.model.update" => { + assert_eq!(request["params"]["branchId"], json!("line-1")); + send(&mut write,json!({"jsonrpc":"2.0","id":id,"error":{"code":-32000,"message":"Configuration was superseded by another update","data":{"appError":"configuration_superseded"}}})).await; + } + "session.summaries" => { + send(&mut write, json!({"jsonrpc":"2.0","id":id,"result":[]})).await; + } + "session.question.pending" => { + let branch = request["params"]["branchId"].clone(); + let through = request["params"]["through"].as_u64().unwrap_or(5); + send(&mut write,json!({"jsonrpc":"2.0","id":id,"result":{"branchId":branch,"through":through,"batches":[],"next":null}})).await; + } + "session.input.pending" => { + let branch = request["params"]["branchId"].clone(); + let through = request["params"]["through"].as_u64().unwrap_or(5); + send(&mut write,json!({"jsonrpc":"2.0","id":id,"result":{"branchId":branch,"through":through,"inputs":[],"next":null}})).await; + } + "session.exec.pending" => { + let branch = request["params"]["branchId"].clone(); + let through = request["params"]["through"].as_u64().unwrap_or(5); + send(&mut write,json!({"jsonrpc":"2.0","id":id,"result":{"branchId":branch,"through":through,"tasks":[],"next":null}})).await; + } + "session.turn.get" => { + let branch = request["params"]["branchId"].clone(); + let through = request["params"]["through"].as_u64().unwrap_or(5); + send(&mut write,json!({"jsonrpc":"2.0","id":id,"result":{"branchId":branch,"through":through,"turn":null,"output":null}})).await; + } + "session.detach" => { + send(&mut write, json!({"jsonrpc":"2.0","id":id,"result":{}})).await; + break; + } + other => panic!("unexpected {other}: {request}"), + } + } + }); + let client = Client::connect(&ConnectionConfig { + endpoint, + server: Server { + program: "unused".into(), + embedded: false, + }, + profile: Some(DaemonProfile::Product), + client_kind: "other", + client_name: "AcpGateway", + protocol_version: 3, + }) + .await + .unwrap(); + let (peer, transport) = tokio::io::duplex(64 * 1024); + let (reader, writer) = tokio::io::split(transport); + let (gateway, finished) = AcpGateway::new( + client, + Io { + reader: Box::new(reader), + writer: Box::new(writer), + }, + None, + env!("CARGO_PKG_VERSION").to_owned(), + ); + let root = rutis::Ctx::root().unwrap(); + let mounted = root.plugin(gateway); + (&mounted).await.unwrap(); + let (read, mut write) = tokio::io::split(peer); + let mut read = BufReader::new(read); + send(&mut write,json!({"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":1,"clientCapabilities":{}}})).await; + let initialize = reply(&mut read, 1).await; + assert!(initialize["error"].is_null(), "{initialize}"); + send(&mut write,json!({"jsonrpc":"2.0","id":2,"method":"session/load","params":{"sessionId":"session","cwd":cwd,"mcpServers":[]}})).await; + let loaded = reply(&mut read, 2).await; + assert!(loaded["error"].is_null(), "{loaded}"); + assert_eq!( + option(&loaded, "model")["currentValue"], + json!("B"), + "the load shows the model `session.model.get` adopted for the line, not the reply's root model" + ); + send(&mut write,json!({"jsonrpc":"2.0","id":3,"method":"session/set_config_option","params":{"sessionId":"session","configId":"model","value":"A"}})).await; + let refused = reply(&mut read, 3).await; + assert_eq!( + refused["error"]["data"]["nativeAppError"], + json!("configuration_superseded"), + "{refused}" + ); + let update = config_update(&mut read).await; + assert_eq!( + option(&update, "model")["currentValue"], + json!("B"), + "the refresh keeps the line's own model instead of reseeding the reply's root model: {update}" + ); + drop(read); + let _ = write.shutdown().await; + let _ = tokio::time::timeout(Duration::from_secs(5), finished).await; + mounted.dispose().await.unwrap(); + root.shutdown().await.unwrap(); + server.await.unwrap(); +} + +/// A superseded refresh re-reads the line's configuration at its own cutoff: +/// a configuration older than that cutoff arrives late and must not replace +/// the refreshed model. +#[tokio::test] +async fn a_gateway_refresh_keeps_its_cutoff_against_a_delayed_configuration() { + let home = tempfile::tempdir_in("/tmp").unwrap(); + let endpoint = home.path().join("daemon.sock"); + let cwd = home.path().to_str().unwrap().to_owned(); + let listener = UnixListener::bind(&endpoint).unwrap(); + std::fs::set_permissions(&endpoint, std::fs::Permissions::from_mode(0o600)).unwrap(); + let daemon_cwd = cwd.clone(); + let server = tokio::spawn(async move { + let (stream, _) = listener.accept().await.unwrap(); + let (read, mut write) = stream.into_split(); + let mut read = BufReader::new(read); + let hello = frame(&mut read).await; + send(&mut write,json!({"jsonrpc":"2.0","id":hello["id"],"result":{"instanceId":"fixture","serverVersion":"fixture","protocolVersion":3,"daemonProfile":{"kind":"product"},"features":["session.create","session.attach","session.attach.expectedCwd","session.branches","session.detach","session.exec.pending","session.history","session.history.display","session.history.detail","session.history.display.tail","session.history.display.transcript","session.history.latestTurn","session.input.pending","session.input_lookup","session.list","session.methods","session.model.get","session.model.update","session.question.pending","session.stop","session.submit","session.summaries","session.turn.get","provider.models.query"]}})).await; + let mut attachments = 0; + let mut delayed = false; + while let Some(request) = read_frame(&mut read).await { + let method = request["method"].as_str().unwrap_or_default().to_owned(); + let id = request["id"].clone(); + match method.as_str() { + "session.attach" => { + attachments += 1; + let (sequence, model) = if attachments == 1 { (5, "A") } else { (6, "C") }; + send(&mut write,json!({"jsonrpc":"2.0","id":id,"result":{"sequence":2,"cwd":daemon_cwd,"model":{"providerId":"fixture","modelId":model},"defaultBranch":{"branchId":"line-1","sequence":sequence}}})).await; + } + "session.branches" => { + send(&mut write,json!({"jsonrpc":"2.0","id":id,"result":{"defaultBranchId":"line-1","branches":[{"branchId":"main","state":"open","head":2},{"branchId":"line-1","parentBranchId":"main","branchPoint":1,"state":"open","head":7}]}})).await; + } + "session.history.display" => { + assert_eq!(request["params"]["branchId"], json!("line-1")); + send(&mut write,json!({"jsonrpc":"2.0","id":id,"result":{"items":[],"through":5,"nextBefore":1,"nextAfter":5,"done":true}})).await; + } + "session.model.get" => { + assert_eq!(request["params"]["branchId"], json!("line-1")); + let through = request["params"]["through"].as_u64().unwrap_or(7); + send(&mut write,json!({"jsonrpc":"2.0","id":id,"result":{"branchId":"line-1","through":through,"configuration":{"model":{"providerId":"fixture","modelId":"B"}}}})).await; + } + "session.methods" => { + let methods: Vec<_> = [ + "session.input.pending", + "session.question.pending", + "session.exec.pending", + "session.turn.get", + "session.model.update", + ] + .into_iter() + .map(|name| json!({"name":name,"mutating":name == "session.model.update"})) + .collect(); + send( + &mut write, + json!({"jsonrpc":"2.0","id":id,"result":{"methods":methods}}), + ) + .await; + } + "provider.models.query" => { + send( + &mut write, + json!({"jsonrpc":"2.0","id":id,"result":{"models":[ + {"providerId":"fixture","model":{"id":"A","name":"A"}}, + {"providerId":"fixture","model":{"id":"B","name":"B"}}, + {"providerId":"fixture","model":{"id":"C","name":"C"}}],"next":null}}), + ) + .await; + } + "session.model.update" => { + assert_eq!(request["params"]["branchId"], json!("line-1")); + send(&mut write,json!({"jsonrpc":"2.0","id":id,"error":{"code":-32000,"message":"Configuration was superseded by another update","data":{"appError":"configuration_superseded"}}})).await; + } + "session.summaries" => { + send(&mut write, json!({"jsonrpc":"2.0","id":id,"result":[]})).await; + if !delayed { + delayed = true; + send(&mut write,json!({"jsonrpc":"2.0","method":"session.event","params":{"sessionId":"session","branchId":"line-1","event":{"id":"configured-6","sequence":6,"create_at":1,"type":"context","name":"configured","data":{"timeline":"line-1","revision":"revision-1","provider_id":"fixture","model_id":"A"}}}})).await; + } + } + "session.question.pending" => { + let branch = request["params"]["branchId"].clone(); + let through = request["params"]["through"].as_u64().unwrap_or(5); + send(&mut write,json!({"jsonrpc":"2.0","id":id,"result":{"branchId":branch,"through":through,"batches":[],"next":null}})).await; + } + "session.input.pending" => { + let branch = request["params"]["branchId"].clone(); + let through = request["params"]["through"].as_u64().unwrap_or(5); + send(&mut write,json!({"jsonrpc":"2.0","id":id,"result":{"branchId":branch,"through":through,"inputs":[],"next":null}})).await; + } + "session.exec.pending" => { + let branch = request["params"]["branchId"].clone(); + let through = request["params"]["through"].as_u64().unwrap_or(5); + send(&mut write,json!({"jsonrpc":"2.0","id":id,"result":{"branchId":branch,"through":through,"tasks":[],"next":null}})).await; + } + "session.turn.get" => { + let branch = request["params"]["branchId"].clone(); + let through = request["params"]["through"].as_u64().unwrap_or(5); + send(&mut write,json!({"jsonrpc":"2.0","id":id,"result":{"branchId":branch,"through":through,"turn":null,"output":null}})).await; + } + "session.detach" => { + send(&mut write, json!({"jsonrpc":"2.0","id":id,"result":{}})).await; + break; + } + other => panic!("unexpected {other}: {request}"), + } + } + }); + let client = Client::connect(&ConnectionConfig { + endpoint, + server: Server { + program: "unused".into(), + embedded: false, + }, + profile: Some(DaemonProfile::Product), + client_kind: "other", + client_name: "AcpGateway", + protocol_version: 3, + }) + .await + .unwrap(); + let (peer, transport) = tokio::io::duplex(64 * 1024); + let (reader, writer) = tokio::io::split(transport); + let (gateway, finished) = AcpGateway::new( + client, + Io { + reader: Box::new(reader), + writer: Box::new(writer), + }, + None, + env!("CARGO_PKG_VERSION").to_owned(), + ); + let root = rutis::Ctx::root().unwrap(); + let mounted = root.plugin(gateway); + (&mounted).await.unwrap(); + let (read, mut write) = tokio::io::split(peer); + let mut read = BufReader::new(read); + send(&mut write,json!({"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":1,"clientCapabilities":{}}})).await; + let initialize = reply(&mut read, 1).await; + assert!(initialize["error"].is_null(), "{initialize}"); + send(&mut write,json!({"jsonrpc":"2.0","id":2,"method":"session/load","params":{"sessionId":"session","cwd":cwd,"mcpServers":[]}})).await; + let loaded = reply(&mut read, 2).await; + assert!(loaded["error"].is_null(), "{loaded}"); + assert_eq!( + option(&loaded, "model")["currentValue"], + json!("B"), + "the load shows the model `session.model.get` adopted for the line" + ); + send(&mut write,json!({"jsonrpc":"2.0","id":3,"method":"session/set_config_option","params":{"sessionId":"session","configId":"model","value":"A"}})).await; + let refused = reply(&mut read, 3).await; + assert_eq!( + refused["error"]["data"]["nativeAppError"], + json!("configuration_superseded"), + "{refused}" + ); + let refreshed = config_update(&mut read).await; + assert_eq!( + option(&refreshed, "model")["currentValue"], + json!("B"), + "the refresh reads the line's current configuration: {refreshed}" + ); + send( + &mut write, + json!({"jsonrpc":"2.0","id":4,"method":"session/list","params":{}}), + ) + .await; + let delayed = config_update(&mut read).await; + assert_eq!( + option(&delayed, "model")["currentValue"], + json!("B"), + "a configuration older than the refresh's cutoff must not replace its model: {delayed}" + ); + drop(read); + let _ = write.shutdown().await; + let _ = tokio::time::timeout(Duration::from_secs(5), finished).await; + mounted.dispose().await.unwrap(); + root.shutdown().await.unwrap(); + server.await.unwrap(); +} + +/// The requests a recovered Session makes, answered as a Session on `line` +/// would answer them. +async fn serve_recovery( + read: &mut BufReader, + write: &mut tokio::net::unix::OwnedWriteHalf, + line: &str, + cursor: u64, +) { + while let Some(request) = read_frame(read).await { + let method = request["method"].as_str().unwrap_or_default().to_owned(); + let branch = request["params"]["branchId"] + .as_str() + .unwrap_or(line) + .to_owned(); + let through = request["params"]["through"].as_u64().unwrap_or(cursor); + let id = request["id"].clone(); + match method.as_str() { + "session.attach" => { + send( + write, + json!({"jsonrpc":"2.0","id":id,"result":{ + "sequence":cursor,"model":{"providerId":"fixture","modelId":"A"}, + "defaultBranch":{"branchId":line,"sequence":cursor}}}), + ) + .await; + } + "session.branches" => { + let mut branches = vec![json!({"branchId":"main","state":"open","head":cursor})]; + if line != "main" { + branches.push(json!({"branchId":line,"parentBranchId":"main","branchPoint":1,"state":"open","head":cursor})); + } + send( + write, + json!({"jsonrpc":"2.0","id":id,"result":{ + "defaultBranchId":line,"branches":branches}}), + ) + .await; + } + "session.history" => { + send( + write, + json!({"jsonrpc":"2.0","id":id,"result":{ + "events":[],"through":cursor,"nextBefore":null,"nextAfter":cursor}}), + ) + .await; + } + "session.methods" => { + let methods: Vec<_> = [ + "session.input.pending", + "session.question.pending", + "session.exec.pending", + "session.turn.get", + ] + .into_iter() + .map(|name| json!({"name":name,"mutating":false})) + .collect(); + send( + write, + json!({"jsonrpc":"2.0","id":id,"result":{"methods":methods}}), + ) + .await; + } + "session.exec.pending" | "session.input.pending" | "session.question.pending" => { + let key = if method == "session.exec.pending" { + "tasks" + } else if method == "session.input.pending" { + "inputs" + } else { + "batches" + }; + send( + write, + json!({"jsonrpc":"2.0","id":id,"result":{ + "branchId":branch,"through":through,key:[],"next":null}}), + ) + .await; + } + "session.turn.get" => { + if request["params"] + .as_object() + .is_some_and(|params| params.contains_key("inputId")) + { + // The moved default holds no such input: a real server + // answers nothing for it, and this fixture says so. + send( + write, + json!({"jsonrpc":"2.0","id":id,"error":{ + "code":-32000,"message":"fixture: the input is not on this line", + "data":{"appError":"input_not_on_line"}}}), + ) + .await; + continue; + } + send( + write, + json!({"jsonrpc":"2.0","id":id,"result":{ + "branchId":branch,"through":through,"turn":null,"output":null}}), + ) + .await; + } + "session.detach" => { + send(write, json!({"jsonrpc":"2.0","id":id,"result":{}})).await; + break; + } + other => panic!("unexpected {other}: {request}"), + } + } +} + +/// A prompt in flight when the default branch moved is settled on the line that +/// accepted it: the reattach follows the new default, so this connection can no +/// longer carry the old line's turn, and the prompt is answered instead of +/// reading the new line for the old input (design §14). +#[tokio::test] +async fn a_recovery_settles_the_prompt_the_moved_default_left_behind() { + let home = tempfile::tempdir_in("/tmp").unwrap(); + let endpoint = home.path().join("daemon.sock"); + let cwd = home.path().to_str().unwrap().to_owned(); + let listener = UnixListener::bind(&endpoint).unwrap(); + std::fs::set_permissions(&endpoint, std::fs::Permissions::from_mode(0o600)).unwrap(); + let daemon_cwd = cwd.clone(); + let server = tokio::spawn(async move { + let (stream, _) = listener.accept().await.unwrap(); + let (read, mut write) = stream.into_split(); + let mut read = BufReader::new(read); + let hello = frame(&mut read).await; + send(&mut write,json!({"jsonrpc":"2.0","id":hello["id"],"result":{"instanceId":"fixture","serverVersion":"fixture","protocolVersion":3,"daemonProfile":{"kind":"product"},"features":["session.attach","session.attach.expectedCwd","session.create","session.branches","session.detach","session.exec.pending","session.history","session.history.latestTurn","session.input.pending","session.input_lookup","session.methods","session.model.update","session.question.pending","session.stop","session.submit","session.summaries","session.turn.get","session.turn.get.inputId"]}})).await; + while let Some(request) = read_frame(&mut read).await { + let method = request["method"].as_str().unwrap_or_default().to_owned(); + let id = request["id"].clone(); + if method == "session.submit" { + assert_eq!(request["params"]["branchId"], json!("main")); + let submission = request["params"]["submissionId"].clone(); + send( + &mut write, + json!({"jsonrpc":"2.0","id":id,"result":{"event":{ + "id":"in-1","sequence":3,"create_at":1,"type":"input","name":"message", + "data":{"user":{"content":[{"type":"text","text":"hello"}]},"mode":"queue"}}}}), + ) + .await; + send(&mut write,json!({"jsonrpc":"2.0","method":"session.event","params":{"sessionId":"session","branchId":"main","event":{"id":"in-1","sequence":3,"create_at":1,"type":"input","name":"message","data":{"submission_id":submission,"user":{"content":[{"type":"text","text":"hello"}]},"mode":"queue"}}}})).await; + break; + } + match method.as_str() { + "session.attach" => { + assert_eq!(request["params"]["expectedCwd"], json!(daemon_cwd)); + send(&mut write, json!({"jsonrpc":"2.0","id":id,"result":{ + "sequence":2,"cwd":daemon_cwd,"model":{"providerId":"fixture","modelId":"A"}, + "defaultBranch":{"branchId":"main","sequence":2}}})).await; + } + "session.branches" => { + send( + &mut write, + json!({"jsonrpc":"2.0","id":id,"result":{ + "defaultBranchId":"main", + "branches":[{"branchId":"main","state":"open","head":2}]}}), + ) + .await; + } + "session.history" => { + send( + &mut write, + json!({"jsonrpc":"2.0","id":id,"result":{ + "events":[],"through":2,"nextBefore":null,"nextAfter":2}}), + ) + .await; + } + "session.methods" => { + let methods: Vec<_> = [ + "session.input.pending", + "session.question.pending", + "session.exec.pending", + "session.turn.get", + ] + .into_iter() + .map(|name| json!({"name":name,"mutating":false})) + .collect(); + send( + &mut write, + json!({"jsonrpc":"2.0","id":id,"result":{"methods":methods}}), + ) + .await; + } + "session.input_lookup" => { + send( + &mut write, + json!({"jsonrpc":"2.0","id":id,"result":{"status":"unknown"}}), + ) + .await; + } + "session.exec.pending" | "session.input.pending" | "session.question.pending" => { + let branch = request["params"]["branchId"].clone(); + let through = request["params"]["through"].clone(); + let key = if method == "session.exec.pending" { + "tasks" + } else if method == "session.input.pending" { + "inputs" + } else { + "batches" + }; + send( + &mut write, + json!({"jsonrpc":"2.0","id":id,"result":{ + "branchId":branch,"through":through,key:[],"next":null}}), + ) + .await; + } + "session.turn.get" => { + let branch = request["params"]["branchId"].clone(); + let through = request["params"]["through"].clone(); + send( + &mut write, + json!({"jsonrpc":"2.0","id":id,"result":{ + "branchId":branch,"through":through,"turn":null,"output":null}}), + ) + .await; + } + other => panic!("unexpected {other}: {request}"), + } + } + drop(write); + drop(read); + // The client reconnects and recovers; the default moved to `line-1` + // while it was away. + let (stream, _) = listener.accept().await.unwrap(); + let (read, mut write) = stream.into_split(); + let mut read = BufReader::new(read); + let hello = frame(&mut read).await; + send(&mut write,json!({"jsonrpc":"2.0","id":hello["id"],"result":{"instanceId":"fixture","serverVersion":"fixture","protocolVersion":3,"daemonProfile":{"kind":"product"},"features":["session.attach","session.attach.expectedCwd","session.create","session.branches","session.detach","session.exec.pending","session.history","session.history.latestTurn","session.input.pending","session.input_lookup","session.methods","session.model.update","session.question.pending","session.stop","session.submit","session.summaries","session.turn.get","session.turn.get.inputId"]}})).await; + serve_recovery(&mut read, &mut write, "line-1", 5).await; + }); + let client = Client::connect(&ConnectionConfig { + endpoint, + server: Server { + program: "unused".into(), + embedded: false, + }, + profile: Some(DaemonProfile::Product), + client_kind: "other", + client_name: "AcpGateway", + protocol_version: 3, + }) + .await + .unwrap(); + let (peer, transport) = tokio::io::duplex(64 * 1024); + let (reader, writer) = tokio::io::split(transport); + let (gateway, finished) = AcpGateway::new( + client, + Io { + reader: Box::new(reader), + writer: Box::new(writer), + }, + None, + env!("CARGO_PKG_VERSION").to_owned(), + ); + let root = rutis::Ctx::root().unwrap(); + let mounted = root.plugin(gateway); + (&mounted).await.unwrap(); + let (read, mut write) = tokio::io::split(peer); + let mut read = BufReader::new(read); + send(&mut write,json!({"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":1,"clientCapabilities":{}}})).await; + let initialize = reply(&mut read, 1).await; + assert!(initialize["error"].is_null(), "{initialize}"); + send(&mut write,json!({"jsonrpc":"2.0","id":2,"method":"session/load","params":{"sessionId":"session","cwd":cwd,"mcpServers":[]}})).await; + let loaded = reply(&mut read, 2).await; + assert!(loaded["error"].is_null(), "{loaded}"); + send(&mut write,json!({"jsonrpc":"2.0","id":3,"method":"session/prompt","params":{"sessionId":"session","prompt":[{"type":"text","text":"hello"}]}})).await; + let settled = reply(&mut read, 3).await; + assert_eq!( + settled["error"]["data"]["code"], + json!("submission_unknown"), + "the moved default settles the prompt instead of reading another line: {settled}" + ); + drop(read); + let _ = write.shutdown().await; + let _ = tokio::time::timeout(Duration::from_secs(5), finished).await; + mounted.dispose().await.unwrap(); + root.shutdown().await.unwrap(); + server.await.unwrap(); +} + +/// A load whose default branch is a line hands the request's `expectedConfig` +/// to the checked attach, reads the directory only after the attach passed, +/// and shows that line's own model instead of the attach reply's root model. +/// Writing the model afterwards targets the line, and a temporary route keeps +/// the catalog provider the model was chosen under (design §14). +#[tokio::test] +async fn a_gateway_load_keeps_the_default_line_apart_from_the_root() { + let home = tempfile::tempdir_in("/tmp").unwrap(); + let endpoint = home.path().join("daemon.sock"); + let cwd = home.path().to_str().unwrap().to_owned(); + let listener = UnixListener::bind(&endpoint).unwrap(); + std::fs::set_permissions(&endpoint, std::fs::Permissions::from_mode(0o600)).unwrap(); + let daemon_cwd = cwd.clone(); + let server = tokio::spawn(async move { + let (stream, _) = listener.accept().await.unwrap(); + let (read, mut write) = stream.into_split(); + let mut read = BufReader::new(read); + let hello = frame(&mut read).await; + send(&mut write,json!({"jsonrpc":"2.0","id":hello["id"],"result":{"instanceId":"fixture","serverVersion":"fixture","protocolVersion":3,"daemonProfile":{"kind":"product"},"features":["session.attach","session.attach.expectedCwd","session.attach.expectedConfig","session.branches","session.create","session.detach","session.history","session.history.latestTurn","session.input_lookup","session.methods","session.model.get","session.model.update","session.stop","session.submit","session.turn.get","provider.models.query"]}})).await; + let mut attached = false; + while let Some(request) = read_frame(&mut read).await { + let method = request["method"].as_str().unwrap_or_default().to_owned(); + let branch = request["params"]["branchId"] + .as_str() + .unwrap_or("line-1") + .to_owned(); + let through = request["params"]["through"].as_u64().unwrap_or(5); + let id = request["id"].clone(); + match method.as_str() { + "session.attach" => { + assert_eq!(request["params"]["expectedCwd"], json!(daemon_cwd)); + assert_eq!( + request["params"]["expectedConfig"], + json!({"modelId":"B"}), + "the load hands the request's expectation to the attach" + ); + attached = true; + send(&mut write,json!({"jsonrpc":"2.0","id":id,"result":{"sequence":2,"cwd":daemon_cwd,"model":{"providerId":"root-route","modelId":"A"},"catalogProviderId":"root-catalog","defaultBranch":{"branchId":"line-1","sequence":5}}})).await; + } + "session.branches" => { + assert!( + attached, + "the checked attach passes before the directory is read" + ); + send(&mut write,json!({"jsonrpc":"2.0","id":id,"result":{"defaultBranchId":"line-1","branches":[{"branchId":"main","state":"open","head":2},{"branchId":"line-1","parentBranchId":"main","branchPoint":1,"state":"open","head":5}]}})).await; + } + "session.history" => { + assert_eq!(branch, "line-1", "the recovery reads the default line"); + send(&mut write,json!({"jsonrpc":"2.0","id":id,"result":{"events":[],"through":5,"nextBefore":null,"nextAfter":5}})).await; + } + "session.methods" => { + send(&mut write,json!({"jsonrpc":"2.0","id":id,"result":{"methods":[{"name":"session.model.update","mutating":true}]}})).await; + } + "provider.models.query" => { + send(&mut write,json!({"jsonrpc":"2.0","id":id,"result":{"models":[{"providerId":"fixture","model":{"id":"A","name":"A"}},{"providerId":"fixture","model":{"id":"B","name":"B"}},{"providerId":"fixture","model":{"id":"C","name":"C"}}],"next":null}})).await; + } + "session.model.get" => { + assert_eq!(branch, "line-1", "the line's configuration is its own"); + assert_eq!(through, 5, "read at the line's own cursor"); + send(&mut write,json!({"jsonrpc":"2.0","id":id,"result":{"branchId":"line-1","through":5,"configuration":{"model":{"providerId":"fixture","modelId":"B"}}}})).await; + } + "session.model.update" => { + assert_eq!(branch, "line-1", "the config write stays on the line"); + assert_eq!(request["params"]["providerId"], json!("fixture")); + assert_eq!(request["params"]["modelId"], json!("C")); + send(&mut write,json!({"jsonrpc":"2.0","id":id,"result":{"model":{"providerId":"route-1","modelId":"C"},"outcome":"adopted"}})).await; + } + "session.turn.get" => { + assert_eq!(branch, "line-1", "the turn read is the default line's"); + send(&mut write,json!({"jsonrpc":"2.0","id":id,"result":{"branchId":branch,"through":through,"turn":null,"output":null}})).await; + } + "session.detach" => { + send(&mut write, json!({"jsonrpc":"2.0","id":id,"result":{}})).await; + break; + } + other => panic!("unexpected {other}: {request}"), + } + } + }); + let client = Client::connect(&ConnectionConfig { + endpoint, + server: Server { + program: "unused".into(), + embedded: false, + }, + profile: Some(DaemonProfile::Product), + client_kind: "other", + client_name: "AcpGateway", + protocol_version: 3, + }) + .await + .unwrap(); + let (peer, transport) = tokio::io::duplex(64 * 1024); + let (reader, writer) = tokio::io::split(transport); + let (gateway, finished) = AcpGateway::new( + client, + Io { + reader: Box::new(reader), + writer: Box::new(writer), + }, + None, + env!("CARGO_PKG_VERSION").to_owned(), + ); + let root = rutis::Ctx::root().unwrap(); + let mounted = root.plugin(gateway); + (&mounted).await.unwrap(); + let (read, mut write) = tokio::io::split(peer); + let mut read = BufReader::new(read); + send(&mut write,json!({"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":1,"clientCapabilities":{}}})).await; + let initialize = reply(&mut read, 1).await; + assert!(initialize["error"].is_null(), "{initialize}"); + send(&mut write,json!({"jsonrpc":"2.0","id":2,"method":"session/load","params":{"sessionId":"session","cwd":cwd,"mcpServers":[],"_meta":{"lody":{"sessionConfig":{"version":1,"modelId":"B","configOptionValues":{}}}}}})).await; + let loaded = reply(&mut read, 2).await; + assert!(loaded["error"].is_null(), "{loaded}"); + assert_eq!( + option(&loaded, "model")["currentValue"], + json!("B"), + "the load shows the default line's model, not the attach reply's root model: {loaded}" + ); + send(&mut write,json!({"jsonrpc":"2.0","id":3,"method":"session/set_config_option","params":{"sessionId":"session","configId":"model","value":"C"}})).await; + let configured = reply(&mut read, 3).await; + assert!(configured["error"].is_null(), "{configured}"); + assert_eq!( + option(&configured, "model")["currentValue"], + json!("C"), + "the adopted model keeps the catalog provider its line chose: {configured}" + ); + drop(read); + let _ = write.shutdown().await; + let _ = tokio::time::timeout(Duration::from_secs(5), finished).await; + mounted.dispose().await.unwrap(); + root.shutdown().await.unwrap(); + server.await.unwrap(); +} diff --git a/crates/dim-cli/README.md b/crates/dim-cli/README.md index b1a96e764d..653dbb1546 100644 --- a/crates/dim-cli/README.md +++ b/crates/dim-cli/README.md @@ -701,17 +701,17 @@ The server resolves symlinks and new-file parents before checking the [workspace boundary](../../docs/architecture/rust-agent/plugins/Permission.md#workspace-write-targets). `--permission read-only|workspace-write|full-access` works with `dimcode`, `tui`, `exec` and -`exec resume`. A new Session receives it in `session.create`; a resumed Session's `main` branch +`exec resume`. A new Session receives it in `session.create`; a resumed Session's default 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`, whose [listing rules](../../docs/design/appserver/provider-management.md#32-writes-and-field-operations) govern connection edits and enablement. 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. Enabling a listable built-in with an empty bundle, such as Magpie, fetches models if no endpoint models are saved; a failed listing leaves it disabled. 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/lib.rs b/crates/dim-cli/src/lib.rs index f19c33f93e..64736942ab 100644 --- a/crates/dim-cli/src/lib.rs +++ b/crates/dim-cli/src/lib.rs @@ -152,7 +152,7 @@ async fn open_tui( .fullscreen .unwrap_or_else(|| ui::config::saved_fullscreen(&options.home)), initial, - resume: options.resume.is_some(), + resume: options.resume.clone(), }; let (leave, mut left) = tokio::sync::oneshot::channel(); let (leaf_end, mut leaf_ended) = tokio::sync::oneshot::channel(); diff --git a/crates/dim-cli/src/model/session.rs b/crates/dim-cli/src/model/session.rs index d2c5b5c459..ef8356684f 100644 --- a/crates/dim-cli/src/model/session.rs +++ b/crates/dim-cli/src/model/session.rs @@ -164,6 +164,17 @@ pub enum SessionsScope { All, } +/// Where a key's command was typed: on Home, before any Session, or in the +/// Session shown then. A command acts only on the origin it names, so a +/// command that waited while an attachment changed is cancelled instead of +/// reaching the new centre. Home keeps the startup path: its commands create +/// a Session or change the preference the next one starts with. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Origin { + Home, + Session(String), +} + pub enum Command { ToolOrigin { session_id: String, @@ -177,10 +188,28 @@ pub enum Command { projection_id: u64, targets: std::collections::BTreeSet, }, - Submit(String, SubmitMode), + /// A message and the origin and line its draft was typed on; a submit + /// whose origin or line is no longer the centre is cancelled and its + /// draft kept (design §14). + Submit { + text: String, + mode: SubmitMode, + line: String, + session: Origin, + }, /// A draft with pastes to store or content blocks to send. - SubmitDraft(Vec, SubmitMode), - Stop, + SubmitDraft { + parts: Vec, + mode: SubmitMode, + line: String, + session: Origin, + }, + /// Interrupt the run on the line the key was pressed on, unless the + /// Session has changed since (design §14). + Stop { + line: String, + session: Origin, + }, /// Answer an approval request. Approval { request_id: String, @@ -213,9 +242,13 @@ pub enum Command { input_id: String, action: &'static str, }, - /// Interrupt the run and reply once it has settled, so the interface can - /// submit the draft it held back (Ctrl+Enter). - SubmitNow, + /// Interrupt the run on the line the gesture started on and reply once it + /// has settled, so the interface can submit the draft it held back + /// (Ctrl+Enter); a Session handoff cancels it (design §14). + SubmitNow { + line: String, + session: Origin, + }, /// Stop a background command on its originating branch (`/tasks`). StopTask { session_id: String, @@ -236,6 +269,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 { @@ -354,21 +394,53 @@ pub enum Command { model_id: String, expected_version: u32, }, - /// Produce the `/usage` report. - Usage, - Earlier, + /// Produce the `/usage` report for the Session's default branch as it was + /// when the command was typed; a report whose line has moved is cancelled. + Usage { + line: String, + session: Origin, + }, + /// Load what is before the drawn top of the line the command was typed on; + /// a read whose line has moved is cancelled. + Earlier { + line: String, + session: Origin, + }, Export(crate::export::Format), - /// `/compact`: ask the shown line to compact its context. - Compact, + /// `/compact`: ask the line the command was typed on to compact its + /// context; a command whose line has moved is cancelled. + Compact { + line: String, + session: Origin, + }, /// `/rename`: set the shown Session's manual title, or clear it when /// `title` is `None`; an empty text is refused, and only `--clear` /// clears. Nothing here reaches the model. Rename(Option), - /// `/goal`: show, set, edit, pause, resume or clear the shown line's goal. - Goal(crate::goal::Request), - /// `/loop`: show, start or stop a loop on the shown line. - Loop(crate::loop_view::Request), - SetPermission(crate::permission::PresetSelection), + /// `/goal`: show, set, edit, pause, resume or clear the line the command + /// was typed on; `draft` restores the command when that line has moved. + Goal { + request: crate::goal::Request, + line: String, + session: Origin, + draft: String, + }, + /// `/loop`: show, start or stop a loop on the line the command was typed + /// on; `draft` restores the command when that line has moved. + Loop { + request: crate::loop_view::Request, + line: String, + session: Origin, + draft: String, + }, + /// Change the permission preset on the default branch the gesture saw; + /// a gesture made on Home changes the preset the next Session starts + /// with instead. + SetPermission { + change: crate::permission::PresetSelection, + session: Origin, + line: String, + }, /// List the providers of the `/connect` panel. ListProviders, /// Change one provider. @@ -400,11 +472,14 @@ pub enum Command { /// Sign the described account out. Logout(AccountTarget), /// Run a shell-mode command through the App Server; `private` (`!!`) - /// keeps its result out of the session. + /// keeps its result out of the session. The Session and line are the ones + /// the command was typed on (design §14). ShellRun { run_id: String, command: String, private: bool, + line: String, + session: Origin, }, /// Ask the run `run_id` to end. ShellStop { @@ -429,8 +504,13 @@ pub enum Command { /// Change one runtime; the worker lists the runtimes and the plugins /// again after it. Runtime(RuntimeAction), - /// A configuration command line (`/effort high`, `/agent`, ...). - Configure(String), + /// A configuration command line (`/effort high`, `/agent`, ...) and the + /// line its draft was typed on. + Configure { + text: String, + line: String, + session: Origin, + }, /// Make `(provider, model)` the default and the active session's model. /// `reasoning_effort` is set when the picker cycled that model's effort; /// `label` is the row's text the default's confirmation names back. @@ -1263,6 +1343,13 @@ pub enum Update { Stopped { error: Option, }, + /// `session.branch_set_default` refused the chosen line: the lines panel + /// shows the reason on the line the choice was made on (design §14). + LineRefusal { + projection_id: u64, + branch_id: String, + text: String, + }, Exported { format: crate::export::Format, path: std::path::PathBuf, @@ -1270,6 +1357,9 @@ pub enum Update { /// The startup preview or Session's adopted configuration: `provider / model` /// and its effective reasoning effort label the status line. Ready(Configuration), + /// The shown line has no configuration this client can show, so the status + /// line carries no model until a fact or a move supplies one (design §14). + NoModel, /// What the session's model offers, once its catalog entry is known: /// image input, and the priority/default service tiers of `/fast`. ModelFeatures { @@ -1392,6 +1482,11 @@ pub enum Update { /// A transient status-line message. Toast(String), Permissions(Result), + /// The shown line's policy is not known: the new centre's read is out, or + /// the line has one this client cannot read. The status line, Settings and + /// Permissions show no preset until a read or a fact supplies one (design + /// §14). + PermissionsUnknown, PermissionSelected(dim_agent_types::PermissionPreset), Providers(Result, String>), /// What a provider change came to. @@ -1495,11 +1590,16 @@ pub trait SessionPort { fn drain(&self) -> Vec; /// Closes the connection and gives the worker a moment to wind down. fn shutdown(self: Box); - fn submit(&self, text: String, mode: SubmitMode) { - self.send(Command::Submit(text, mode)); + fn submit(&self, text: String, mode: SubmitMode, line: String, session: Origin) { + self.send(Command::Submit { + text, + mode, + line, + session, + }); } - fn stop(&self) { - self.send(Command::Stop); + fn stop(&self, line: String, session: Origin) { + self.send(Command::Stop { line, session }); } } diff --git a/crates/dim-cli/src/model/view.rs b/crates/dim-cli/src/model/view.rs index 82191fb736..2f587af0af 100644 --- a/crates/dim-cli/src/model/view.rs +++ b/crates/dim-cli/src/model/view.rs @@ -509,6 +509,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 e8bac4edb3..f5f89f1d22 100644 --- a/crates/dim-cli/src/session.rs +++ b/crates/dim-cli/src/session.rs @@ -1,4 +1,4 @@ -use crate::wire::{Attached, Created, DisplayNotice, EventNotice, Progress}; +use crate::wire::{Attached, Created, DisplayNotice, EventNotice, Progress, resume_cursor}; use crate::{ Result, args::{Action, Options}, @@ -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, @@ -255,22 +270,15 @@ pub async fn chat( } created.session_id }; - let selected = if let (Some(preset), Some(_)) = (options.permission, &options.resume) { - if !client.supports(&permission::PRESET_METHODS) { - return Err( - "This daemon cannot change a Session's permission preset; omit --permission".into(), - ); - } - Some( - permission::select(client, &session_id, preset) - .await - .map_err(|error| { - crate::client::resume_failure("Cannot set the permission preset", error) - })?, - ) - } else { - None - }; + let listed = conversation(client, &session_id).await?; + if options.permission.is_some() + && options.resume.is_some() + && !client.supports(&permission::PRESET_METHODS) + { + return Err( + "This daemon cannot change a Session's permission preset; omit --permission".into(), + ); + } display.record(&format!( "{}: {}\nsession: {}", if interactive { @@ -281,6 +289,35 @@ pub async fn chat( options.launch_dir().display(), session_id ))?; + let mut params = json!({"sessionId":session_id}); + if !display.json + && client.offers("session.history.display") + && client.offers("session.history.detail") + { + params["display"] = json!(true); + } + let attached: Attached = client.typed("session.attach", params).await?; + let session_cwd = attached.cwd.clone(); + // The attach reply names the line the conversation is on, beside the + // root's `sequence`; a server that predates the field leaves the directory + // as its answer (design §14). + let conversation = attached + .default_branch + .as_ref() + .map_or(listed, |cursor| cursor.branch_id.clone()); + // The preset belongs to the line the reply names: the directory's answer is + // one round trip older, and the line may have moved between them + // (design §14). + let selected = match (options.permission, &options.resume) { + (Some(preset), Some(_)) => Some( + permission::select(client, &session_id, &conversation, preset) + .await + .map_err(|error| { + crate::client::resume_failure("Cannot set the permission preset", error) + })?, + ), + _ => None, + }; let policy = match (selected, options.permission) { (Some(policy), _) => Some(Ok(policy)), (None, Some(preset)) => Some(Ok(PermissionPolicy { @@ -288,7 +325,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), ), @@ -301,36 +338,60 @@ pub async fn chat( Some(Err(error)) => display.record(&format!("permission: unavailable ({error})"))?, None => {} } - let mut params = json!({"sessionId":session_id}); - if !display.json - && client.offers("session.history.display") - && client.offers("session.history.detail") - { - params["display"] = json!(true); - } - let attached: Attached = client.typed("session.attach", params).await?; - let session_cwd = attached.cwd; if options.resume.is_some() { - crate::session_host::adopt_startup(client, options, &session_id).await?; + crate::session_host::adopt_startup(client, options, &session_id, &conversation).await?; } let mut questions = Questions::default(); let result = async { display.muted = !interactive; - display.model = attached.model.map(|model| crate::wire::Configuration { - catalog_provider_id: attached.catalog_provider_id, - provider_id: model.provider_id, - model_id: model.model_id, - 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?; + // The reply's configuration is the root's (design §14): a conversation + // on a line reads that line's own adopted configuration at its cursor. + // A reply that names no line comes from a server that cannot move the + // default branch, so its model is the Session's. + let seeded = attached.default_branch.is_none() || conversation == ROOT_BRANCH_ID; + display.model = if seeded { + attached.configuration() + } else { + None + }; + // The attach reply's `defaultBranch` is the conversation's own cursor; + // its `sequence` stays the root's (design §14). + display.model_through = if seeded { + resume_cursor(attached.default_branch.as_ref(), attached.sequence, &conversation) + .unwrap_or(0) + } else { + 0 + }; + display.cursor = window::read(client, &session_id, &conversation, &mut display).await?; + // The display transcript omits `context/configured`, and a bounded + // window can start after the adoption: a line's configuration is read + // through `session.model.get` at the cursor the reply named. A server + // without that read cannot name this line's configuration, and the + // reply's is the root's, so none is shown (design §14). + if !display.json && !seeded && display.model.is_none() { + if client.offers("session.model.get") { + let (through, configuration) = dim_client::configuration::adopted( + client, + &session_id, + &conversation, + Some(display.history_through), + ) + .await?; + display.model = configuration; + display.model_through = through; + } else { + display.record(&format!( + "configuration: unavailable (this server cannot read line {conversation})" + ))?; + } + } + 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, @@ -353,6 +414,7 @@ pub async fn chat( return wait_turn( client, &session_id, + &conversation, Some(Submission::Message(UserInput { content })), &mut display, &mut input, @@ -411,7 +473,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 { @@ -427,6 +489,7 @@ pub async fn chat( reader, &mut interrupts, &session_id, + &conversation, text, &mut display, &mut listing, @@ -443,6 +506,7 @@ pub async fn chat( if let Err(error) = goal_command::command( client, &session_id, + &conversation, text, &mut display, &mut interrupts, @@ -459,7 +523,7 @@ pub async fn chat( if let Err(error) = loop_command::command( client, &session_id, - DEFAULT_BRANCH_ID, + &conversation, text, &mut display, &mut interrupts, @@ -480,7 +544,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; } @@ -562,6 +626,7 @@ pub async fn chat( code = match wait_turn( client, &session_id, + &conversation, Some(submission), &mut display, &mut input, @@ -626,12 +691,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, @@ -639,7 +705,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); } @@ -669,6 +735,7 @@ async fn read_history_mode( async fn configure( client: &mut Client, session_id: &str, + conversation: &str, text: &str, display: &mut Display, ) -> Result<()> { @@ -679,6 +746,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, @@ -686,7 +754,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)?; } @@ -694,6 +769,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, @@ -711,6 +787,7 @@ async fn configure( async fn wait_turn( client: &mut Client, session_id: &str, + conversation: &str, submission: Option, display: &mut Display, input: &mut Option, @@ -722,7 +799,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(); } @@ -731,7 +808,7 @@ async fn wait_turn( Some(Submission::Message(mut user)) => { crate::images::import(client, session_id, &mut user.content).await?; let submission_id = uuid::Uuid::new_v4().to_string(); - let mut params = json!({"sessionId":session_id,"branchId":DEFAULT_BRANCH_ID,"submissionId":submission_id.clone(),"mode":"queue"}); + let mut params = json!({"sessionId":session_id,"branchId":conversation,"submissionId":submission_id.clone(),"mode":"queue"}); match user.content.as_slice() { [ContentBlock::Text { text }] => params["text"] = json!(text), _ => params["user"] = json!(user), @@ -746,7 +823,7 @@ async fn wait_turn( client .send( "session.idle", - json!({"sessionId":session_id,"branchId":DEFAULT_BRANCH_ID}), + json!({"sessionId":session_id,"branchId":conversation}), ) .await?, ) @@ -891,7 +968,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?, ); @@ -935,7 +1012,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 { @@ -1006,7 +1083,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")?; @@ -1024,7 +1103,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; } @@ -1138,7 +1217,7 @@ async fn wait_turn( client .send( "session.idle", - json!({"sessionId":session_id,"branchId":DEFAULT_BRANCH_ID}), + json!({"sessionId":session_id,"branchId":conversation}), ) .await?, ); @@ -1278,7 +1357,7 @@ async fn wait_turn( approval_replies.insert(client.send("approval.respond", json!({"sessionId":session_id,"branchId":approval.branch_id,"requestId":approval.request_id,"decision":"deny"})).await?); code = 3; display.close_reply()?; - 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); } @@ -1363,13 +1442,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!() }; @@ -1381,7 +1465,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" @@ -1401,12 +1485,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; @@ -1416,7 +1500,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 72aa916622..1dce5ad70c 100644 --- a/crates/dim-cli/src/session_host.rs +++ b/crates/dim-cli/src/session_host.rs @@ -27,7 +27,7 @@ use crate::model::session::{ ACCOUNT_NAMESPACE, Account, AccountDescriptor, Command, CompactReply, ContextReading, DIM_OAUTH_ID, DeleteOutcome, DeleteReply, DraftPart, EmptyProvider, EmptyReason, ExecutionSnapshot, ManagementReply, ModelItem, ModelList, ModelOutcome, ModelPolicyUpdate, - NeedsLimitsProvider, OauthEvent, OauthStart, PluginItem, PluginReply, PromptField, + NeedsLimitsProvider, OauthEvent, OauthStart, Origin, PluginItem, PluginReply, PromptField, PromptSetting, ProviderAction, ProviderEntry, RuntimeAction, RuntimeItem, RuntimesError, SandboxBackend, SessionItem, SessionPort, SessionsScope, SubagentModelPolicy, SuggestionSetting, SwitchKind, Update, Usage, stored_title, @@ -279,6 +279,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, @@ -310,6 +313,14 @@ struct Worker { shell_stops: Vec, /// The model the session adopted, for the preference commands. model: Option, + /// The configuration each line folded from its own events, with the + /// sequence of the fact: the bar shows the default branch's own when the + /// conversation moves (design §14). + line_configurations: std::collections::HashMap, + /// The line this entry already reported a missing configuration for: the + /// window that follows a move stays quiet, and a later entry reports again + /// (design §14). + unreadable_line: Option, /// The model Home previews, which the first message's Session adopts. preview: Option, /// The preference Home chose for that model: the members it named, which @@ -328,6 +339,10 @@ struct Worker { /// Browser callbacks its local listener captured. login_callbacks: (UnboundedSender, UnboundedReceiver), opening_reads: Vec<(u64, OpeningRead)>, + /// The centre handoffs since this interface started: an opening read that + /// left before the last one describes a line that is no longer the + /// conversation's (design §14). + moves: u64, /// The composer's context reading is out of date: a model request on main /// finished, a run on main ended, a compaction result arrived on main, or /// the session or its model changed. @@ -361,7 +376,12 @@ struct OutputWatch { enum OpeningRead { Catalog(ModelId), - Permissions, + /// The policy of `line` as of the move `generation`: a reply that arrives + /// after the conversation moved on is stale (design §14). + Permissions { + line: String, + generation: u64, + }, Skills, } @@ -480,11 +500,15 @@ async fn run( tokio::select! { command = commands.recv() => { let Some(command) = command else { break }; + // The command is judged against the centre it was typed on + // before Home can start a Session: a send left over from a + // Session a handoff replaced starts nothing. + let Some(command) = worker.typed_command(command) else { continue }; if worker.session_id.is_empty() && matches!( command, - Command::Submit(..) - | Command::SubmitDraft(..) + Command::Submit { .. } + | Command::SubmitDraft { .. } | Command::ShellRun { .. } ) && let Err(error) = worker.start_session().await @@ -511,7 +535,14 @@ async fn run( }); continue; } - if matches!(command, Command::Submit(..) | Command::SubmitDraft(..)) + let submitted_line = match &command { + Command::Submit { line, .. } | Command::SubmitDraft { line, .. } => { + Some(line.as_str()) + } + _ => None, + }; + if let Some(line) = submitted_line + && line == worker.focus && worker .task_history .get(&worker.focus) @@ -622,6 +653,13 @@ fn tokens(value: f64) -> u64 { value.max(0.0).round() as u64 } +/// One line's adopted configuration and the sequence of the fact that carried +/// it: what the top bar shows while the conversation is on that line. +struct LineConfiguration { + sequence: u64, + configuration: Configuration, +} + /// The last `model/usage` fact on `main`: the counters `/usage` reports the /// cache read share of. #[derive(Clone, Copy)] @@ -717,6 +755,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(), @@ -738,6 +777,8 @@ impl Worker { ui_id: None, shell_stops: Vec::new(), model: None, + line_configurations: Default::default(), + unreadable_line: None, preview: None, pending: None, mcp_attempt: None, @@ -746,6 +787,7 @@ impl Worker { login: None, login_callbacks: unbounded_channel(), opening_reads: Vec::new(), + moves: 0, context_stale: false, context_request: None, last_usage: None, @@ -775,21 +817,40 @@ impl Worker { /// 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() { + if self.options.permission.is_some() + && !self.client.supports(&permission::PRESET_METHODS) + { + return Err( + "This daemon cannot change a Session's permission preset; omit --permission" + .into(), + ); + } + // A launch preset or model is applied to the line the attach reply + // names, after the attachment. Registering this interface first + // would make the resumed leaf observable, and addressable for + // approvals, while the old policy or model is still in force; it + // therefore registers once they are applied (design §14). + let deferred = self.options.permission.is_some() + || self.options.startup.is_some() + || self.options.effort.is_some() + || self.options.model.is_some(); + self.attach(id.clone(), SwitchKind::Resumed, !deferred) + .await?; + // The preset belongs to the line the attach reply named + // (design §14); a directory read would be one round trip older. if let Some(preset) = self.options.permission { - if !self.client.supports(&permission::PRESET_METHODS) { - return Err( - "This daemon cannot change a Session's permission preset; omit --permission" - .into(), - ); - } - permission::select(&mut self.client, &id, preset) + let branch = self.default_branch.clone(); + permission::select(&mut self.client, &id, &branch, preset) .await .map_err(|error| { client::resume_failure("Cannot set the permission preset", error) })?; } - adopt_startup(&mut self.client, &self.options, &id).await?; - return self.attach(id, SwitchKind::Resumed).await; + adopt_startup(&mut self.client, &self.options, &id, &self.default_branch).await?; + if deferred { + self.register_ui().await?; + } + return Ok(()); } if self.client.offers("session.model.preview") && let Err(error) = self.preview_model().await @@ -905,6 +966,7 @@ impl Worker { Some(created.model), SwitchKind::New, attached_session, + true, ) .await?; if let Some(worktree) = worktree { @@ -925,6 +987,7 @@ impl Worker { model: Option, kind: SwitchKind, attached_session: String, + register: bool, ) -> crate::Result<()> { if !attached_session.is_empty() && attached_session != session_id { self.client @@ -965,7 +1028,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, @@ -982,6 +1044,7 @@ impl Worker { self.title_revision = attached.title_revision; self.session_id = session_id.clone(); self.model_session = Some(session_id.clone()); + self.unreadable_line = None; // The method table is read once per Session, before anything can ask // for an offer or probe the settings source: a Session that does not // list the methods is never asked. @@ -990,24 +1053,40 @@ impl Worker { self.send(Update::SuggestionMethods(offered)); self.suggestion_throttle_noted = false; self.session_cwd = attached.cwd; - self.register_ui().await?; + if register { + self.register_ui().await?; + } self.mcp_required.clear(); - self.model = Some(configuration.clone()); + // The reply's record is the root's adopted configuration, the model the + // conversation keeps when it moves back to the root (design §14). + self.line_configurations.insert( + ROOT_BRANCH_ID.into(), + LineConfiguration { + sequence: 0, + configuration: 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 attach reply names that line beside the root's + // `sequence`, and the directory answers for a server that predates the + // field (§14). + self.default_branch = attached + .default_branch + .as_ref() + .map(|cursor| cursor.branch_id.clone()) + .unwrap_or_else(|| 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?; + if attached.default_branch.is_none() { + 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" { @@ -1019,8 +1098,46 @@ impl Worker { } } } + // This attachment's centre is the first move of this interface; the + // reads it starts belong to this generation (design §14). + self.moves += 1; + self.focus = self.default_branch.clone(); + let conversation_line = self.focus.clone(); + self.discover_branch(&conversation_line); + let conversation_cursor = dim_client::wire::resume_cursor( + attached.default_branch.as_ref(), + attached.sequence, + &conversation_line, + ); + 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); + } + // A conversation on the root takes the reply's configuration as its + // own; one on a line reads that line's adopted configuration at its + // cursor (a display transcript omits the fact, and a bounded window can + // start after it). A reply that names no line comes from a server that + // cannot move the default branch, so its model is the Session's + // (design §14). + let seeded = attached.default_branch.is_none() || conversation_line == ROOT_BRANCH_ID; + self.model_through = if seeded { + conversation_cursor.unwrap_or(0) + } else { + 0 + }; self.poll_task_history().await?; - self.send(Update::Ready(configuration)); + if seeded { + self.model = Some(configuration.clone()); + self.send(Update::Ready(configuration)); + } else { + self.model = None; + self.send(Update::NoModel); + } self.send(catalog_features(None)); self.send(Update::Skills(Vec::new())); self.send(Update::Switched { @@ -1028,6 +1145,11 @@ impl Worker { kind, cwd: self.session_cwd.clone(), }); + // The policy shown belonged to the Session this interface left; this + // Session's own read publishes its own, and a refused or failed read + // leaves it unknown rather than showing the outgoing preset (design + // §14). A daemon that serves no preset read cannot report one, and the + // launch preset stays the only policy this client knows. let mut reads = Vec::new(); if self.client.offers("provider.catalog") { reads.push(( @@ -1037,10 +1159,14 @@ impl Worker { )); } if self.client.supports(&permission::PRESET_METHODS) { + self.send(Update::PermissionsUnknown); reads.push(( "session.permission.get", - json!({"sessionId":session_id,"branchId":DEFAULT_BRANCH_ID}), - OpeningRead::Permissions, + json!({"sessionId":session_id,"branchId":self.default_branch}), + OpeningRead::Permissions { + line: self.default_branch.clone(), + generation: self.moves, + }, )); } if self.client.offers("skills.catalog") { @@ -1084,7 +1210,10 @@ impl Worker { }); self.send(catalog_features(entry)); } - OpeningRead::Permissions => { + OpeningRead::Permissions { line, generation } => { + if generation != self.moves || line != self.default_branch { + return; + } let policy = result .map_err(|error| error.to_string()) .and_then(|value| { @@ -1138,9 +1267,15 @@ impl Worker { .find(|entry| entry.id == model.model_id) } - async fn attach(&mut self, session_id: String, kind: SwitchKind) -> crate::Result<()> { + async fn attach( + &mut self, + session_id: String, + kind: SwitchKind, + register: bool, + ) -> crate::Result<()> { let attached_session = self.invalidate_projection(); - self.enter(session_id, None, kind, attached_session).await + self.enter(session_id, None, kind, attached_session, register) + .await } async fn suggestion_offered(&mut self) -> bool { @@ -1288,15 +1423,166 @@ impl Worker { self.report_failure(result); } + /// A command typed for a Session and line only runs while it still names + /// that pair: the shown line for a submit, a draft, a goal, a loop, a + /// configuration, a compaction, an earlier read or a shell command, and + /// the Session's default branch for `/usage` and a permission change, + /// which act on it. A move or a Session handoff the key could not see + /// cancels the command and returns what it carried to the draft, instead + /// of writing it into another line or Session. Home is its own origin: a + /// command typed there keeps the startup path it belongs to and never + /// reaches a Session that an attachment brought in. The stop gestures name + /// the Session and line they were pressed on: a handoff cancels them, while + /// a move within the same Session still stops the line the key saw (design + /// §14). + fn typed_command(&mut self, command: Command) -> Option { + const KEPT: &str = "The centre moved before the command ran; the draft was kept"; + let (origin, line, draft, cancelled) = match &command { + Command::Submit { + text, + line, + session, + .. + } => ( + session, + Some(line), + Some(vec![DraftPart::Text(text.clone())]), + KEPT, + ), + Command::SubmitDraft { + parts, + line, + session, + .. + } => (session, Some(line), Some(parts.clone()), KEPT), + Command::Goal { + line, + session, + draft, + .. + } => ( + session, + Some(line), + Some(vec![DraftPart::Text(draft.clone())]), + KEPT, + ), + Command::Loop { + line, + session, + draft, + .. + } => ( + session, + Some(line), + Some(vec![DraftPart::Text(draft.clone())]), + KEPT, + ), + Command::Configure { + text, + line, + session, + } => ( + session, + Some(line), + Some(vec![DraftPart::Text(text.clone())]), + KEPT, + ), + Command::Compact { line, session } => ( + session, + Some(line), + None, + "The centre moved before /compact ran; nothing was compacted", + ), + Command::Usage { line, session } => ( + session, + Some(line), + None, + "The centre moved before /usage ran; no report was printed", + ), + Command::Earlier { line, session } => ( + session, + Some(line), + None, + "The centre moved before /earlier ran; nothing was loaded", + ), + Command::SetPermission { session, line, .. } => ( + session, + Some(line), + None, + "The session or line moved before the permission change ran; nothing was changed", + ), + Command::Stop { session, .. } => ( + session, + None, + None, + "The session moved before the stop ran; nothing was stopped", + ), + Command::SubmitNow { session, .. } => { + (session, None, None, "The session moved before the send ran") + } + Command::ShellRun { line, session, .. } => ( + session, + Some(line), + None, + "The centre moved before the shell command ran; nothing was run", + ), + _ => return Some(command), + }; + let now = match &command { + Command::Usage { .. } | Command::SetPermission { .. } => &self.default_branch, + _ => &self.focus, + }; + if self.typed_at(origin) && line.is_none_or(|line| line.is_empty() || line == now) { + return Some(command); + } + match &command { + Command::SubmitNow { .. } => self.send(Update::Stopped { + error: Some(cancelled.into()), + }), + Command::ShellRun { run_id, .. } => self.send(Update::ShellDone { + run_id: run_id.clone(), + result: Err(cancelled.into()), + }), + _ => match draft { + Some(parts) => self.send(Update::DraftNotSent { + parts, + message: cancelled.into(), + }), + None => self.send(Update::Notice(cancelled.into())), + }, + }; + None + } + + /// Whether `origin` is the centre this worker shows: Home while it has no + /// Session, else that Session. A command read at another origin has been + /// overtaken by a handoff and is cancelled. + fn typed_at(&self, origin: &Origin) -> bool { + match origin { + Origin::Home => self.session_id.is_empty(), + Origin::Session(session) => session == &self.session_id, + } + } + async fn command(&mut self, command: Command) -> crate::Result<()> { match command { - Command::Submit(text, mode) => self.submit(text, mode.as_str()).await, - Command::SubmitDraft(parts, mode) => self.submit_draft(parts, mode.as_str()).await, + Command::Submit { text, mode, .. } => self.submit(text, mode.as_str()).await, + Command::SubmitDraft { parts, mode, .. } => { + self.submit_draft(parts, mode.as_str()).await + } Command::FocusLine(line) => self.focus_line(line).await, Command::CloseSide => { 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, @@ -1400,7 +1686,10 @@ impl Worker { ) .await; match forked { - Ok(forked) => self.attach(forked.session_id, SwitchKind::Forked).await?, + Ok(forked) => { + self.attach(forked.session_id, SwitchKind::Forked, true) + .await? + } Err(error) => { if !self.reportable( crate::report::Captured::observed( @@ -1416,19 +1705,19 @@ impl Worker { } } } - Command::Stop => { + Command::Stop { line, .. } => { let params = json!({ "sessionId": self.session_id, - "branchId": self.focus, + "branchId": line, "reason": crate::model::view::INTERRUPT_REASON, }); let result = self.client.rpc("session.stop", params).await; self.report_failure(result); } - Command::SubmitNow => { + Command::SubmitNow { line, .. } => { let params = json!({ "sessionId": self.session_id, - "branchId": self.focus, + "branchId": line, "reason": crate::model::view::INTERRUPT_REASON, }); // `session.stop` replies once the turn has settled, so its @@ -1544,16 +1833,22 @@ impl Worker { })); } Command::Resume(session_id) => { + self.attach(session_id.clone(), SwitchKind::Resumed, true) + .await?; 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 { - self.send(Update::Notice(format!( - "The permission preset was not applied: {error}" - ))); + // The preset lands on the line the attach reply named, + // which this Home was not (design §14). + let branch = self.default_branch.clone(); + if let Err(error) = + permission::select(&mut self.client, &session_id, &branch, preset).await + { + self.send(Update::Notice(format!( + "The permission preset was not applied: {error}" + ))); + } } - self.attach(session_id, SwitchKind::Resumed).await?; } Command::ListSessions { id, @@ -1612,8 +1907,8 @@ impl Worker { } } Command::CloseSessions => self.cancel_catalog().await?, - Command::Usage => { - self.request_context(true).await; + Command::Usage { line, .. } => { + self.request_context(true, &line).await; if self .model .as_ref() @@ -1623,7 +1918,7 @@ impl Worker { self.send(Update::UsageReport(usage)); } } - Command::Compact => self.compact().await, + Command::Compact { line, .. } => self.compact(&line).await, Command::Report(request) => self.report_request(request).await, Command::Export(format) => { let extension = match format { @@ -1646,9 +1941,9 @@ impl Worker { } } Command::Rename(title) => self.rename(title).await, - Command::Earlier => self.earlier(), - Command::Goal(request) => self.goal(request).await, - Command::Loop(request) => self.loop_command(request).await, + Command::Earlier { line, .. } => self.earlier(&line), + Command::Goal { request, .. } => self.goal(request).await, + Command::Loop { request, .. } => self.loop_command(request).await, Command::CheckUpdate => { let updates = self.updates.clone(); let managed = @@ -1954,7 +2249,7 @@ impl Worker { Err(error) => error.to_string(), })); } - Command::SetPermission(change) => { + Command::SetPermission { change, .. } => { let result = if self.session_id.is_empty() { Ok(dim_agent_types::PermissionPolicy { preset: change.resolve( @@ -1966,9 +2261,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); @@ -2068,6 +2368,7 @@ impl Worker { run_id, command, private, + .. } => { if self.shell.is_some() { self.send(Update::ShellDone { @@ -2174,7 +2475,7 @@ impl Worker { } } Command::SetLocale(language) => crate::management::use_language(language), - Command::Configure(text) => { + Command::Configure { text, .. } => { if self.session_id.is_empty() { if configure::needs_session(&text) { self.report(NO_SESSION.to_owned(), true); @@ -2184,8 +2485,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 @@ -2227,9 +2534,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); @@ -2337,7 +2645,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; @@ -2403,7 +2710,9 @@ impl Worker { ) } - async fn request_context(&mut self, report: bool) { + /// The context reading of `line`, the Session's default branch; `report` + /// also prints it as `/usage`'s report. + async fn request_context(&mut self, report: bool, line: &str) { if let Some((_, requested_report)) = &mut self.context_request { *requested_report |= report; return; @@ -2413,7 +2722,7 @@ impl Worker { .client .send( "session.context.usage", - json!({"sessionId": self.session_id, "branchId": DEFAULT_BRANCH_ID}), + json!({"sessionId": self.session_id, "branchId": line}), ) .await { @@ -2431,13 +2740,14 @@ impl Worker { /// whose usage is unknown shows none. async fn poll_context(&mut self) { if self.context_stale && !self.session_id.is_empty() && self.context_request.is_none() { - self.request_context(false).await; + let line = self.default_branch.clone(); + self.request_context(false, &line).await; } } - /// Asks the shown line to compact; committed outcomes reach its transcript. - async fn compact(&mut self) { - let params = json!({"sessionId": self.session_id, "branchId": self.focus}); + /// Asks `line` to compact; committed outcomes reach its transcript. + async fn compact(&mut self, line: &str) { + let params = json!({"sessionId": self.session_id, "branchId": line}); match self.client.send("session.context.compact", params).await { Ok(request) => self.compact_requests.push(request), Err(error) => self.send(Update::Compacted(CompactReply::Failed(error.to_string()))), @@ -2775,14 +3085,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 { .. } @@ -2832,7 +3142,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) @@ -3908,7 +4219,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), } @@ -4058,7 +4369,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) => { @@ -4578,7 +4889,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 @@ -4799,13 +5110,25 @@ impl Worker { } fn fold(&mut self, branch_id: &str, event: Event, replayed: bool) { - if branch_id == DEFAULT_BRANCH_ID - && event.sequence > self.model_through - && let EventContent::Configuration(configuration) = &event.content - { - self.model_through = event.sequence; - self.model = Some(configuration.clone()); - self.send(Update::Ready(configuration.clone())); + if let EventContent::Configuration(configuration) = &event.content { + if self + .line_configurations + .get(branch_id) + .is_none_or(|known| known.sequence < event.sequence) + { + self.line_configurations.insert( + branch_id.to_owned(), + LineConfiguration { + sequence: event.sequence, + configuration: configuration.clone(), + }, + ); + } + if branch_id == self.default_branch && event.sequence > self.model_through { + self.model_through = event.sequence; + self.model = Some(configuration.clone()); + self.send(Update::Ready(configuration.clone())); + } } self.discover_task_branches(&event); let captured = if self.report_available() @@ -4841,14 +5164,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)); + .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(_) @@ -4856,7 +5179,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 { @@ -4945,6 +5268,146 @@ 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.clone()}), + ) + .await + { + Ok(reply) => { + self.default_branch = reply.default_branch_id; + self.moves += 1; + self.continue_on_line().await; + } + Err(error) => self.send(Update::LineRefusal { + projection_id, + branch_id, + text: error.to_string(), + }), + } + } + + /// Shows the line the Session's conversation is on now: its transcript, + /// and its own model, permission and context in the top bar (design §14). + /// A line numbers its own events, so the model watermark starts from that + /// line's own last fact, whatever its sequence (timeline UI §5). + async fn continue_on_line(&mut self) { + self.side = None; + self.last_usage = None; + self.context_request = None; + self.model_through = 0; + self.model = None; + self.unreadable_line = None; + let line = self.default_branch.clone(); + let mut adopted = self + .line_configurations + .get(&line) + .map(|adopted| (adopted.sequence, Some(adopted.configuration.clone()))); + if adopted.is_none() && line != ROOT_BRANCH_ID { + let through = self + .task_history + .get(&line) + .and_then(|history| history.window.through); + adopted = self.line_configuration(&line, through).await; + } + if let Some((cutoff, configuration)) = adopted { + self.model_through = cutoff; + if let Some(configuration) = configuration { + self.model = Some(configuration.clone()); + self.line_configurations.insert( + line.clone(), + LineConfiguration { + sequence: cutoff, + configuration: configuration.clone(), + }, + ); + self.send(Update::Ready(configuration)); + } + } + if self.model.is_none() { + self.send(Update::NoModel); + } + // The policy shown belonged to the line that is no longer the centre; + // this line's own read publishes its own, and a refused or failed read + // leaves it unknown rather than showing the outgoing preset (design + // §14). + self.send(Update::PermissionsUnknown); + self.focus_line(line).await; + if self.client.supports(&permission::PRESET_METHODS) { + let params = json!({"sessionId":self.session_id,"branchId":self.default_branch}); + match self.client.send("session.permission.get", params).await { + Ok(id) => self.opening_reads.push(( + id, + OpeningRead::Permissions { + line: self.default_branch.clone(), + generation: self.moves, + }, + )), + Err(error) => self.send(Update::Notice(format!("permission: {error}"))), + } + } + let line = self.default_branch.clone(); + self.request_context(false, &line).await; + } + + /// One line's adopted configuration through `session.model.get`, at + /// `through` or at the line's head, with the line's own cutoff. A server + /// without that read cannot name this line's configuration, and the attach + /// reply's is the root's, so the line reports that and carries no model + /// (design §14). + async fn line_configuration( + &mut self, + line: &str, + through: Option, + ) -> Option<(u64, Option)> { + // The window that follows an entry asks again; the user hears the + // limitation once per entry, not once per page (design §14). + let reported = self.unreadable_line.as_deref() == Some(line); + if !self.client.offers("session.model.get") { + if !reported { + self.unreadable_line = Some(line.to_owned()); + self.send(Update::Notice(format!( + "Configuration: this server cannot read line {line}" + ))); + } + return None; + } + match dim_client::configuration::adopted(&mut self.client, &self.session_id, line, through) + .await + { + Ok(adopted) => Some(adopted), + Err(error) => { + if !reported { + self.unreadable_line = Some(line.to_owned()); + self.send(Update::Notice(format!("Configuration: {error}"))); + } + None + } + } + } + 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"))); @@ -5033,6 +5496,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_topic = self.projection.first_message(); snapshot.session_title = self.session_title.clone(); @@ -5158,11 +5622,15 @@ pub(crate) async fn adopt_startup( client: &mut Client, options: &Options, session_id: &str, + branch: &str, ) -> crate::Result<()> { 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 the line the attach reply named: a move between attach + // and this write must not apply the startup configuration to another line + // (design §9, §14). + let mut params = json!({"sessionId":session_id,"branchId":branch}); if let Some(startup) = &options.startup { params["startup"] = startup.clone(); } @@ -5740,7 +6208,7 @@ mod tests { let (mut worker, mut receiver, _sent) = test_worker(&TEST_FEATURES).await; worker - .attach("s2".into(), SwitchKind::Resumed) + .attach("s2".into(), SwitchKind::Resumed, true) .await .expect("the switch attaches"); let published = |receiver: &mut mpsc::Receiver| -> Vec { @@ -5789,7 +6257,7 @@ mod tests { async fn a_stale_fork_ends_with_a_notice_and_fork_failed() { let (mut worker, receiver, _sent) = test_worker(&TEST_FEATURES).await; worker - .attach("s2".into(), SwitchKind::Resumed) + .attach("s2".into(), SwitchKind::Resumed, true) .await .expect("the switch attaches"); receiver.try_iter().for_each(drop); @@ -5827,7 +6295,7 @@ mod tests { async fn a_refused_fork_ends_with_fork_failed() { let (mut worker, receiver, _sent) = test_worker_answering(&TEST_FEATURES, true, None).await; worker - .attach("s2".into(), SwitchKind::Resumed) + .attach("s2".into(), SwitchKind::Resumed, true) .await .expect("the switch attaches"); receiver.try_iter().for_each(drop); @@ -5865,7 +6333,7 @@ mod tests { let (mut worker, receiver, _sent) = test_worker_answering(&features, false, Some("refused")).await; worker - .attach("s1".into(), SwitchKind::Resumed) + .attach("s1".into(), SwitchKind::Resumed, true) .await .expect("the switch attaches"); receiver.try_iter().for_each(drop); @@ -5905,7 +6373,7 @@ mod tests { ); worker - .attach("s1".into(), SwitchKind::Resumed) + .attach("s1".into(), SwitchKind::Resumed, true) .await .expect("the switch attaches"); receiver.try_iter().for_each(drop); @@ -5944,7 +6412,7 @@ mod tests { let (mut worker, mut receiver, _sent) = test_worker(&TEST_FEATURES).await; worker - .attach("s2".into(), SwitchKind::Resumed) + .attach("s2".into(), SwitchKind::Resumed, true) .await .expect("the switch attaches"); let published = |receiver: &mut mpsc::Receiver| -> ViewSnapshot { @@ -5999,7 +6467,7 @@ mod tests { async fn every_live_line_carries_its_own_state_report() { let (mut worker, mut receiver, _sent) = test_worker(&TEST_FEATURES).await; worker - .attach("s2".into(), SwitchKind::Resumed) + .attach("s2".into(), SwitchKind::Resumed, true) .await .expect("the switch attaches"); let lines = |receiver: &mut mpsc::Receiver| { @@ -6068,7 +6536,7 @@ mod tests { async fn an_ended_line_is_listed_without_a_state_report() { let (mut worker, receiver, _sent) = test_worker(&TEST_FEATURES).await; worker - .attach("s2".into(), SwitchKind::Resumed) + .attach("s2".into(), SwitchKind::Resumed, true) .await .expect("the switch attaches"); let create = json!({ diff --git a/crates/dim-cli/src/session_host/report.rs b/crates/dim-cli/src/session_host/report.rs index 7215345687..c9cd79a62d 100644 --- a/crates/dim-cli/src/session_host/report.rs +++ b/crates/dim-cli/src/session_host/report.rs @@ -239,7 +239,7 @@ mod tests { worker.session_id = "attached".into(); assert!( worker - .attach("original".into(), SwitchKind::Resumed) + .attach("original".into(), SwitchKind::Resumed, true) .await .is_err() ); @@ -250,7 +250,7 @@ mod tests { )) ); worker - .attach("original".into(), SwitchKind::Resumed) + .attach("original".into(), SwitchKind::Resumed, true) .await .unwrap(); let error = receiver @@ -294,7 +294,7 @@ mod tests { // its own code and text. worker.session_id = "shown".into(); let refused = worker - .attach("legacy".into(), SwitchKind::Resumed) + .attach("legacy".into(), SwitchKind::Resumed, true) .await .expect_err("a classified refusal is the caller's error"); assert!( diff --git a/crates/dim-cli/src/session_host/tasks.rs b/crates/dim-cli/src/session_host/tasks.rs index c5bd6c904d..815e55dc3d 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,9 @@ impl Worker { self.context_stale = false; self.cursors.clear(); self.tool_origins.clear(); + self.default_branch = ROOT_BRANCH_ID.into(); + self.line_configurations.clear(); + self.unreadable_line = None; self.focus = DEFAULT_BRANCH_ID.into(); self.side = None; self.lines.clear(); @@ -208,7 +211,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()) { @@ -241,11 +244,11 @@ impl Worker { self.changed(); } - pub(super) fn earlier(&mut self) { + pub(super) fn earlier(&mut self, line: &str) { if self.earlier_member() { return; } - let Some(history) = self.task_history.get_mut(&self.focus) else { + let Some(history) = self.task_history.get_mut(line) else { return; }; if !history.done || history.earlier == EarlierRead::Reading { @@ -258,7 +261,7 @@ impl Worker { history.earlier = EarlierRead::Reading; history.window_complete = false; history.error = None; - self.task_history_queue.push_back(self.focus.clone()); + self.task_history_queue.push_back(line.to_owned()); } /// Whether the view `earlier()` would act on has older history to read. @@ -365,7 +368,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 { @@ -602,7 +605,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(), @@ -647,6 +650,43 @@ impl Worker { } } self.changed(); + // A display transcript omits `context/configured`, and a bounded window + // can start after it: the shown line's configuration is read through + // `session.model.get` once its window is ready, unless a later fact + // already set it (design §14). A server without the read names no + // configuration, and the reply's is the root's, so the line carries + // no model until a fact or a move supplies one. + if window_ready + && self.model.is_none() + && request.branch_id == self.default_branch + && self.default_branch != ROOT_BRANCH_ID + { + let through = self + .task_history + .get(&request.branch_id) + .and_then(|history| history.window.through); + if let Some((cutoff, configuration)) = + self.line_configuration(&request.branch_id, through).await + && request.branch_id == self.default_branch + && cutoff > self.model_through + { + self.model_through = cutoff; + if let Some(configuration) = configuration { + self.model = Some(configuration.clone()); + self.line_configurations.insert( + request.branch_id.clone(), + LineConfiguration { + sequence: cutoff, + configuration: configuration.clone(), + }, + ); + self.send(Update::Ready(configuration)); + } + } + if self.model.is_none() { + self.send(Update::NoModel); + } + } if window_ready { self.publish(); } @@ -803,7 +843,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) => { @@ -967,7 +1007,7 @@ mod tests { "the loaded window has older history" ); - worker.earlier(); + worker.earlier("main"); assert_eq!( worker.earlier_view(), Earlier::Reading, @@ -981,7 +1021,7 @@ mod tests { Earlier::Unread, "a failed earlier read leaves the older history to read" ); - worker.earlier(); + worker.earlier("main"); assert_eq!( worker.task_history["main"].earlier, EarlierRead::Reading, @@ -1016,7 +1056,7 @@ mod tests { } worker.apply("b-7c", event(300, "r-loaded", "the answer loaded first")); - worker.earlier(); + worker.earlier("b-7c"); worker.poll_task_history().await.unwrap(); fail(&mut worker, "the earlier read").await; @@ -1092,7 +1132,7 @@ mod tests { history.window.before = Some(200); history.window.through = Some(300); } - worker.earlier(); + worker.earlier("b-7c"); worker.poll_task_history().await.unwrap(); { let history = worker.task_history.get_mut("b-7c").unwrap(); @@ -1170,7 +1210,7 @@ mod tests { history.window.before = Some(7); history.window.through = Some(9); } - worker.earlier(); + worker.earlier("main"); worker.poll_task_history().await.unwrap(); fail(&mut worker, "the earlier read").await; @@ -1186,7 +1226,7 @@ mod tests { "the retried read is the earlier read the window still holds" ); worker.task_history_queue.clear(); - worker.earlier(); + worker.earlier("main"); assert!( worker.task_history_queue.is_empty(), "a press during the retried read queues nothing" @@ -1240,7 +1280,7 @@ mod tests { "the line's window starts after its start, so the cut counts nothing" ); - worker.earlier(); + worker.earlier("b-7c"); assert_eq!(worker.earlier_view(), Earlier::Reading); worker.poll_task_history().await.unwrap(); answer( @@ -1414,7 +1454,7 @@ mod tests { ); worker.task_history.get_mut("b-7c").unwrap().done = true; - worker.earlier(); + worker.earlier("b-7c"); assert_eq!(worker.earlier_view(), Earlier::Reading); worker.poll_task_history().await.unwrap(); answer( @@ -1515,7 +1555,7 @@ mod tests { ); worker.task_history.get_mut("b-7c").unwrap().done = true; - worker.earlier(); + worker.earlier("b-7c"); worker.poll_task_history().await.unwrap(); answer( &mut worker, @@ -1657,7 +1697,7 @@ mod tests { worker.task_history_queue.clear(); worker.task_history.get_mut("b-7c").unwrap().done = true; - worker.earlier(); + worker.earlier("b-7c"); for (first, count) in [(321, 10), (301, 20), (271, 30)] { worker.poll_task_history().await.unwrap(); answer( @@ -1694,7 +1734,7 @@ mod tests { Earlier::Unread, "the dropped page is the earlier history left to read" ); - worker.earlier(); + worker.earlier("b-7c"); worker.poll_task_history().await.unwrap(); answer(&mut worker, transcript_page(asked_page(11, 250), 11, true)).await; assert_eq!( diff --git a/crates/dim-cli/src/ui/approvals_panel.rs b/crates/dim-cli/src/ui/approvals_panel.rs index ba1e9ecba2..fa7f105687 100644 --- a/crates/dim-cli/src/ui/approvals_panel.rs +++ b/crates/dim-cli/src/ui/approvals_panel.rs @@ -12,24 +12,26 @@ use crate::ui::theme::Palette; pub struct ApprovalsPanel { list: ListPanel, - preset: PermissionPreset, + /// The preset the shown line is on; `None` when this client does not know + /// it, so no row claims to be the current mode. + preset: Option, } impl ApprovalsPanel { - pub fn new(policy: &PermissionPolicy) -> Self { + pub fn new(policy: Option<&PermissionPolicy>) -> Self { let mut panel = Self { list: ListPanel::new("Permissions", "", "", "", "", false) .without_filter() .with_inline_rows() .with_section_headings(), - preset: policy.preset, + preset: policy.map(|policy| policy.preset), }; panel.refresh(); panel } - pub fn set_policy(&mut self, policy: &PermissionPolicy) { - self.preset = policy.preset; + pub fn set_policy(&mut self, policy: Option<&PermissionPolicy>) { + self.preset = policy.map(|policy| policy.preset); self.refresh(); } @@ -38,7 +40,11 @@ impl ApprovalsPanel { let selected = self.list.selected_id(); let items = std::iter::once(Item::heading(t("Permission mode"))) .chain(PRESETS.into_iter().map(|preset| { - let marker = if preset == current { "(*)" } else { "( )" }; + let marker = if Some(preset) == current { + "(*)" + } else { + "( )" + }; Item::new( preset_name(preset), format!("{marker} {}", preset_label(preset)), @@ -51,10 +57,11 @@ impl ApprovalsPanel { Item::new("isolation", t("Process isolation"), "›"), ]) .collect::>(); - self.list.set_items( - Ok(items), - Some(selected.as_deref().unwrap_or(preset_name(current))), - ); + let focus = selected + .as_deref() + .or(current.map(preset_name)) + .unwrap_or_else(|| preset_name(PRESETS[0])); + self.list.set_items(Ok(items), Some(focus)); self.focus_hint(); } @@ -76,7 +83,7 @@ impl ApprovalsPanel { .find(|preset| Some(preset_name(*preset)) == name) .expect("permission rows name a preset"); ( - if preset == self.preset { + if Some(preset) == self.preset { t("keep mode") } else { t("use mode") @@ -161,7 +168,7 @@ mod tests { fn the_panel_draws_its_title_and_rows_in_the_interface_language() { let previous = crate::ui::i18n::active(); crate::ui::i18n::set(crate::ui::i18n::Locale::ZhCn); - let panel = ApprovalsPanel::new(&PermissionPolicy::default()); + let panel = ApprovalsPanel::new(Some(&PermissionPolicy::default())); let palette = terminal_palette(ColorMode::TrueColor, Appearance::Dark); let drawn = panel .render(80, 24, &palette) diff --git a/crates/dim-cli/src/ui/i18n/de/chrome.rs b/crates/dim-cli/src/ui/i18n/de/chrome.rs index 110572bf3a..62d6911b55 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.", @@ -613,6 +624,7 @@ pub fn lookup(english: &str) -> Option<&'static str> { "Send now failed: {error}; the draft was kept" => { "Sofort senden fehlgeschlagen: {error}; der Entwurf bleibt erhalten" } + "Send now failed: {error}" => "Sofort senden fehlgeschlagen: {error}", "Send now cancelled; the draft was kept" => { "Sofort senden abgebrochen; der Entwurf bleibt erhalten" } @@ -635,6 +647,7 @@ pub fn lookup(english: &str) -> Option<&'static str> { "Bei Auswahl Shift+Tab zum neueren Ziel · Esc zurück zur Eingabe" } "(shift+tab to cycle)" => "(Shift+Tab zum Wechseln)", + "Permission unavailable" => "Berechtigung nicht verfügbar", "Fullscreen" => "Vollbild", "PageUp/PageDown scroll · Home/End top or bottom (empty draft) · Tab pick a message, e edit it, q quote it" => { "PageUp/PageDown scrollen · Home/End Anfang/Ende (bei leerem Entwurf) · Tab Nachricht wählen, e bearbeiten, q zitieren" diff --git a/crates/dim-cli/src/ui/i18n/es/chrome.rs b/crates/dim-cli/src/ui/i18n/es/chrome.rs index b562f77159..3d6e807825 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.", @@ -617,6 +628,7 @@ pub fn lookup(english: &str) -> Option<&'static str> { "Send now failed: {error}; the draft was kept" => { "Enviar ya falló: {error}; el borrador se conserva" } + "Send now failed: {error}" => "Enviar ya falló: {error}", "Send now cancelled; the draft was kept" => "Enviar ya cancelado; el borrador se conserva", "Send now is still stopping the run; the draft was kept" => { "El envío inmediato aún está deteniendo la ejecución; el borrador se conserva" @@ -637,6 +649,7 @@ pub fn lookup(english: &str) -> Option<&'static str> { "Con selección, Shift+Tab al siguiente elemento más reciente · Esc volver a la entrada" } "(shift+tab to cycle)" => "(Shift+Tab para cambiar)", + "Permission unavailable" => "Permiso no disponible", "Fullscreen" => "Pantalla completa", "PageUp/PageDown scroll · Home/End top or bottom (empty draft) · Tab pick a message, e edit it, q quote it" => { "PageUp/PageDown desplazar · Home/End inicio o final (con el borrador vacío) · Tab elegir mensaje, e editar, q citar" diff --git a/crates/dim-cli/src/ui/i18n/fr/chrome.rs b/crates/dim-cli/src/ui/i18n/fr/chrome.rs index 40b6cc46d3..26a9e511c0 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.", @@ -605,6 +616,7 @@ pub fn lookup(english: &str) -> Option<&'static str> { "Send now failed: {error}; the draft was kept" => { "Échec de l’envoi immédiat : {error} ; le brouillon est conservé" } + "Send now failed: {error}" => "Échec de l’envoi immédiat : {error}", "Send now cancelled; the draft was kept" => { "Envoi immédiat annulé ; le brouillon est conservé" } @@ -627,6 +639,7 @@ pub fn lookup(english: &str) -> Option<&'static str> { "Sélection active : Shift+Tab vers une cible plus récente · Esc retour à la saisie" } "(shift+tab to cycle)" => "(Shift+Tab pour changer)", + "Permission unavailable" => "Autorisation indisponible", "Fullscreen" => "Plein écran", "PageUp/PageDown scroll · Home/End top or bottom (empty draft) · Tab pick a message, e edit it, q quote it" => { "PageUp/PageDown défiler · Home/End haut ou bas (brouillon vide) · Tab choisir un message, e modifier, q citer" diff --git a/crates/dim-cli/src/ui/i18n/id/chrome.rs b/crates/dim-cli/src/ui/i18n/id/chrome.rs index c7580c856d..ebf71e35c6 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.", @@ -599,6 +610,7 @@ pub fn lookup(english: &str) -> Option<&'static str> { "Send now failed: {error}; the draft was kept" => { "Kirim sekarang gagal: {error}; draf dipertahankan" } + "Send now failed: {error}" => "Kirim sekarang gagal: {error}", "Send now cancelled; the draft was kept" => "Kirim sekarang dibatalkan; draf dipertahankan", "Send now is still stopping the run; the draft was kept" => { "Kirim sekarang masih menghentikan proses; draf dipertahankan" @@ -619,6 +631,7 @@ pub fn lookup(english: &str) -> Option<&'static str> { "Saat dipilih, Shift+Tab ke target lebih baru · Esc kembali ke masukan" } "(shift+tab to cycle)" => "(Shift+Tab untuk beralih)", + "Permission unavailable" => "Izin tidak tersedia", "Fullscreen" => "Layar penuh", "PageUp/PageDown scroll · Home/End top or bottom (empty draft) · Tab pick a message, e edit it, q quote it" => { "PageUp/PageDown gulir · Home/End atas/bawah (saat draf kosong) · Tab pilih pesan, e edit, q kutip" diff --git a/crates/dim-cli/src/ui/i18n/ja/chrome.rs b/crates/dim-cli/src/ui/i18n/ja/chrome.rs index f71498586a..cdc02ea050 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" => "セッション自体", @@ -577,6 +590,7 @@ pub fn lookup(english: &str) -> Option<&'static str> { "Send now failed: {error}; the draft was kept" => { "即時送信に失敗しました: {error}。下書きは残しました" } + "Send now failed: {error}" => "即時送信に失敗しました: {error}", "Send now cancelled; the draft was kept" => "即時送信を取り消しました。下書きは残しました", "Send now is still stopping the run; the draft was kept" => { "送信即時はまだ実行を停止中です。下書きは保持されました" @@ -597,6 +611,7 @@ pub fn lookup(english: &str) -> Option<&'static str> { "選択中は Shift+Tab で新しい項目へ · Esc 入力欄に戻る" } "(shift+tab to cycle)" => "(Shift+Tab で切替)", + "Permission unavailable" => "権限を利用できません", "Fullscreen" => "全画面", "PageUp/PageDown scroll · Home/End top or bottom (empty draft) · Tab pick a message, e edit it, q quote it" => { "PageUp/PageDown スクロール · Home/End 先頭/末尾 (下書きが空の場合) · Tab メッセージ選択、e 編集、q 引用" diff --git a/crates/dim-cli/src/ui/i18n/ko/chrome.rs b/crates/dim-cli/src/ui/i18n/ko/chrome.rs index 321a0a135c..a85de65140 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" => "세션 자체", @@ -561,6 +574,7 @@ pub fn lookup(english: &str) -> Option<&'static str> { "Send now failed: {error}; the draft was kept" => { "즉시 전송 실패: {error}. 초안은 유지되었습니다" } + "Send now failed: {error}" => "즉시 전송 실패: {error}", "Send now cancelled; the draft was kept" => { "즉시 전송이 취소되었습니다. 초안은 유지되었습니다" } @@ -583,6 +597,7 @@ pub fn lookup(english: &str) -> Option<&'static str> { "선택 중 Shift+Tab으로 더 최근 항목 선택 · Esc 입력창으로 돌아가기" } "(shift+tab to cycle)" => "(Shift+Tab으로 전환)", + "Permission unavailable" => "권한을 사용할 수 없음", "Fullscreen" => "전체 화면", "PageUp/PageDown scroll · Home/End top or bottom (empty draft) · Tab pick a message, e edit it, q quote it" => { "PageUp/PageDown 스크롤 · Home/End 맨 위/아래 (초안이 비어 있을 때) · Tab 메시지 선택, e 편집, q 인용" diff --git a/crates/dim-cli/src/ui/i18n/mod.rs b/crates/dim-cli/src/ui/i18n/mod.rs index b00af21e59..d8a939a9fd 100644 --- a/crates/dim-cli/src/ui/i18n/mod.rs +++ b/crates/dim-cli/src/ui/i18n/mod.rs @@ -119,6 +119,7 @@ mod tests { "Message queued", "Ctrl+Enter interrupt and send now: the draft and every held message, as one message", "Send now failed: {error}; the draft was kept", + "Send now failed: {error}", "Send now cancelled; the draft was kept", "Send now is still stopping the run; the draft was kept", "Send now is stopping the run; paste again when the draft is sent", 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 872accf635..6e30b65e3f 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.", @@ -607,6 +618,7 @@ pub fn lookup(english: &str) -> Option<&'static str> { "Send now failed: {error}; the draft was kept" => { "Enviar já falhou: {error}; o rascunho foi mantido" } + "Send now failed: {error}" => "Enviar já falhou: {error}", "Send now cancelled; the draft was kept" => "Enviar já cancelado; o rascunho foi mantido", "Send now is still stopping the run; the draft was kept" => { "O envio imediato ainda está parando a execução; o rascunho foi mantido" @@ -627,6 +639,7 @@ pub fn lookup(english: &str) -> Option<&'static str> { "Com seleção, Shift+Tab para o alvo mais recente · Esc voltar à entrada" } "(shift+tab to cycle)" => "(Shift+Tab para alternar)", + "Permission unavailable" => "Permissão indisponível", "Fullscreen" => "Tela cheia", "PageUp/PageDown scroll · Home/End top or bottom (empty draft) · Tab pick a message, e edit it, q quote it" => { "PageUp/PageDown rolar · Home/End topo ou fim (com rascunho vazio) · Tab escolher mensagem, e editar, q citar" 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 a3961e9675..dd795c7129 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.", @@ -615,6 +626,7 @@ pub fn lookup(english: &str) -> Option<&'static str> { "Send now failed: {error}; the draft was kept" => { "Enviar já falhou: {error}; o rascunho foi mantido" } + "Send now failed: {error}" => "Enviar já falhou: {error}", "Send now cancelled; the draft was kept" => "Enviar já cancelado; o rascunho foi mantido", "Send now is still stopping the run; the draft was kept" => { "O envio imediato ainda está a parar a execução; o rascunho foi mantido" @@ -635,6 +647,7 @@ pub fn lookup(english: &str) -> Option<&'static str> { "Com seleção, Shift+Tab para o alvo mais recente · Esc voltar à entrada" } "(shift+tab to cycle)" => "(Shift+Tab para alternar)", + "Permission unavailable" => "Permissão indisponível", "Fullscreen" => "Ecrã inteiro", "PageUp/PageDown scroll · Home/End top or bottom (empty draft) · Tab pick a message, e edit it, q quote it" => { "PageUp/PageDown deslocar · Home/End topo ou fundo (com rascunho vazio) · Tab escolher mensagem, e editar, q citar" 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 cafa466a90..dd4732d527 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" => "会话本身", @@ -623,6 +636,7 @@ pub fn lookup(english: &str) -> Option<&'static str> { "Ctrl+Enter 中断并立即发送:草稿与所有暂存消息合成一条发出" } "Send now failed: {error}; the draft was kept" => "立即发送失败:{error};草稿已保留", + "Send now failed: {error}" => "立即发送失败:{error}", "Send now cancelled; the draft was kept" => "已取消立即发送;草稿保留", "Send now is still stopping the run; the draft was kept" => { "立即发送仍在停止运行;草稿已保留" @@ -643,6 +657,7 @@ pub fn lookup(english: &str) -> Option<&'static str> { "选中历史项时 Shift+Tab 选择较新项 · Esc 返回输入框" } "(shift+tab to cycle)" => "(Shift+Tab 切换)", + "Permission unavailable" => "权限不可用", "Fullscreen" => "全屏", "PageUp/PageDown scroll · Home/End top or bottom (empty draft) · Tab pick a message, e edit it, q quote it" => { "PageUp/PageDown 滚动 · Home/End 到顶部或底部 (草稿为空时) · Tab 选择消息,e 编辑,q 引用" 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 ed12072915..e926f2ba7b 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" => "工作階段本身", @@ -545,6 +558,7 @@ pub fn lookup(english: &str) -> Option<&'static str> { "Ctrl+Enter 中斷並立即傳送:草稿與所有暫存訊息合成一則送出" } "Send now failed: {error}; the draft was kept" => "立即傳送失敗:{error};草稿已保留", + "Send now failed: {error}" => "立即傳送失敗:{error}", "Send now cancelled; the draft was kept" => "已取消立即傳送;草稿保留", "Send now is still stopping the run; the draft was kept" => { "立即傳送仍在停止執行;草稿已保留" @@ -565,6 +579,7 @@ pub fn lookup(english: &str) -> Option<&'static str> { "選取歷史項時 Shift+Tab 選擇較新項 · Esc 返回輸入框" } "(shift+tab to cycle)" => "(Shift+Tab 切換)", + "Permission unavailable" => "權限不可用", "Fullscreen" => "全螢幕", "PageUp/PageDown scroll · Home/End top or bottom (empty draft) · Tab pick a message, e edit it, q quote it" => { "PageUp/PageDown 捲動 · Home/End 至頂端或底端 (草稿為空時) · Tab 選擇訊息,e 編輯,q 引用" diff --git a/crates/dim-cli/src/ui/lines_panel.rs b/crates/dim-cli/src/ui/lines_panel.rs index 89722d0ca5..093fd34ac6 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 + /// choice changes (design §14). + 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, on the + /// line that raised it, until the choice changes (design §14). + pub fn refuse(&mut self, projection_id: u64, branch_id: &str, text: String) -> bool { + if projection_id != self.projection_id { + return false; + } + self.refusal = Some((branch_id.to_owned(), text)); + self.refresh_note(); + true + } + + /// Refuses the action on the selected line, without a round trip. + fn refuse_selected(&mut self, text: String) { + let line = self.list.selected_id().unwrap_or_default(); + self.refuse(self.projection_id, &line, 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,99 @@ 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); + } + if self.lines.iter().any(|line| line.id == id) { + self.ask_to_end(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; + 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((line, refusal)) = &self.refusal + && *line == selected + { + notes.push(refusal.clone()); } + self.list.set_notes(notes); } pub fn cursor(&self, width: usize) -> Option<(usize, usize)> { @@ -243,7 +344,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 +373,7 @@ mod tests { session_id: "s1".into(), projection_id: 3, focus: focus.into(), + default_branch_id: "main".into(), lines: vec![ LineView { id: "main".into(), @@ -333,6 +435,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")); @@ -340,6 +461,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'))), @@ -375,6 +500,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] @@ -395,11 +524,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)) @@ -439,11 +564,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"), @@ -537,12 +658,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"); @@ -553,5 +670,91 @@ 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_on_the_line_that_raised_it() { + let mut panel = LinesPanel::new(&snapshot("main")); + assert!(panel.refuse( + 3, + "b-7c", + "branch_already_default: the line is already the default branch".into() + )); + assert!( + !text(&panel).contains("branch_already_default"), + "the refusal belongs to the line that raised it: {:#?}", + rows(&panel) + ); + assert!(matches!(panel.handle_key(key(KeyCode::Down)), Effect::None)); + 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, "b-7c", "another attachment".into())); } } diff --git a/crates/dim-cli/src/ui/mod.rs b/crates/dim-cli/src/ui/mod.rs index e3b0aeb387..fac2f6f8f2 100644 --- a/crates/dim-cli/src/ui/mod.rs +++ b/crates/dim-cli/src/ui/mod.rs @@ -24,8 +24,10 @@ pub struct Env { pub workspace: String, /// Start in the fullscreen interface instead of scrollback. pub fullscreen: bool, - /// A requested resume whose initial window has not loaded yet. - pub resume: bool, + /// The Session the invocation asked to resume: only its first message + /// (`-p`) names it while its first attachment has not loaded, and a key + /// pressed on the Home screen before that reply is Home's. + pub resume: Option, /// The first message to submit once the first frame is drawn. pub initial: Option, } diff --git a/crates/dim-cli/src/ui/prompts.rs b/crates/dim-cli/src/ui/prompts.rs index 8f93d0c100..f591828143 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 0539754e65..8ac17f7cf5 100644 --- a/crates/dim-cli/src/ui/tui.rs +++ b/crates/dim-cli/src/ui/tui.rs @@ -11,7 +11,7 @@ use std::time::{Duration, Instant}; use crate::management::{self, editor}; use crate::model::session::{ Area, Command, CompactReply, ContextReading, DIM_OAUTH_ID, DeleteOutcome, DeleteReply, - DraftPart, ManagementAction, ManagementRefusal, ManagementRequest, ManagementResult, + DraftPart, ManagementAction, ManagementRefusal, ManagementRequest, ManagementResult, Origin, PromptField, PromptSetting, RenameReply, SessionPort, SubmitMode, SuggestionSetting, SwitchKind, Update, }; @@ -301,10 +301,11 @@ fn run_terminal( ); app.fullscreen = full.is_some(); app.initial = surroundings.initial; - app.awaiting_window = surroundings.resume; - if surroundings.resume { + app.awaiting_window = surroundings.resume.is_some(); + if surroundings.resume.is_some() { app.begin_switch(SwitchKind::Resumed); } + app.startup_session = surroundings.resume; app.terminal_clipboard = terminal.clipboard_protocol() && crate::clipboard::terminal::native_unreachable(); app.host.send(Command::LoginStatus(DIM_OAUTH_ID.into())); @@ -1237,7 +1238,7 @@ struct App { /// A submitted first message no Session has taken yet: a refusal puts /// it back into the draft. unsent: Option, - permission_policy: dim_agent_types::PermissionPolicy, + permission_policy: Option, /// The main branch's context use. context: Option, /// The first attempt tag of the next `/login` panel, so a closed panel's @@ -1260,6 +1261,10 @@ struct App { /// The user message a `/timeline` jump or a loaded page lands on, once /// drawn: `(row id, pick it)`. landing: Option<(String, bool)>, + /// The Session the invocation asked to resume, until the interface shows + /// it: the invocation's first message names that Session, while no key + /// typed before the attachment does. + startup_session: Option, /// A session was just switched; the next snapshot decides the window. awaiting_window: bool, /// A Session switch the user asked for whose outcome has not arrived @@ -1557,9 +1562,18 @@ enum ClipboardRead { /// A Ctrl+Enter that has withdrawn the queue and asked for a stop. At most one /// is in flight: its reply decides for the gesture the user last meant. struct SendNow { + /// The line the gesture started on: its stop and the draft it settles + /// belong to that line, not to the centre a queued move may install. + line: String, + /// The Session the gesture started in: a handoff it could not see keeps + /// the draft out of the Session that replaced it. + session: Origin, /// Esc called off the submit. The stop still settles, and its reply /// releases the gesture without submitting anything. submit_cancelled: bool, + /// A Session switch cleared the composer before the stop settled, so the + /// reply must not claim the draft was kept. + draft_lost: bool, /// Where the next recalled message goes: past the ones already recalled, /// so they keep queue order ahead of the draft that was typed. at: usize, @@ -1682,10 +1696,10 @@ impl App { initial: None, unsent: None, send_now: None, - permission_policy: dim_agent_types::PermissionPolicy { + permission_policy: Some(dim_agent_types::PermissionPolicy { preset: dim_agent_types::PermissionPreset::WorkspaceWrite, ..Default::default() - }, + }), context: None, login_attempts: 0, theme_context: None, @@ -1695,6 +1709,7 @@ impl App { load_more: false, reveal_pending: false, landing: None, + startup_session: None, awaiting_window: false, switch_pending: false, switches: PendingSwitches::default(), @@ -2042,9 +2057,52 @@ impl App { /// Submits the draft a settled stop made ready, as a new message: the run /// is idle now, so the submit starts its own turn and takes whatever /// withdrawn messages joined the draft in the meantime. - fn submit_send_now(&mut self) { + fn submit_send_now(&mut self, line: String, session: Origin) { let outcome = self.composer.submit(); - self.dispatch_composer(outcome, SubmitMode::Queue); + self.dispatch_composer(outcome, SubmitMode::Queue, line, session); + } + + /// The origin a key's command belongs to: the Session shown, or Home. + /// `--resume` is not a key's origin: while the first attachment is still + /// in flight the interface shows Home, and a key typed there is Home's, + /// so no attachment can turn it into a command on the Session it brings + /// in (design §14). + fn target_session(&self) -> Origin { + if self.session_id.is_empty() { + Origin::Home + } else { + Origin::Session(self.session_id.clone()) + } + } + + /// A permission change and the Session and default line the gesture saw: + /// a move or handoff before it runs cancels it instead of changing the + /// policy of the new centre (design §14). + fn permission_change(&self, change: crate::permission::PresetSelection) -> Command { + Command::SetPermission { + change, + session: self.target_session(), + line: self.default_line(), + } + } + + /// The centre as this interface last saw it: the line a key's command + /// belongs to. Empty before the first Snapshot, when a command can only + /// be the invocation's first message (design §14). + fn target_line(&self) -> String { + self.snapshot + .as_ref() + .map(|snapshot| snapshot.focus.clone()) + .unwrap_or_default() + } + + /// The Session's default branch as this interface last saw it, the line + /// `/usage` reports (design §14). + fn default_line(&self) -> String { + self.snapshot + .as_ref() + .map(|snapshot| snapshot.default_branch_id.clone()) + .unwrap_or_default() } /// Ctrl+Enter: withdraws every held message into the draft, stops the run @@ -2060,11 +2118,17 @@ impl App { return; } self.send_now = Some(SendNow { + line: self.target_line(), + session: self.target_session(), submit_cancelled: false, + draft_lost: false, at: 0, }); self.recall_all_queued(); - self.host.send(Command::SubmitNow); + self.host.send(Command::SubmitNow { + line: self.target_line(), + session: self.target_session(), + }); } fn withdraw(&mut self, id: String) { @@ -2086,6 +2150,19 @@ impl App { }); } + /// Shows that the centre's policy is not known to this interface: the + /// status line, Settings and the Permissions panel stop naming the + /// outgoing preset (design §14). + fn show_permission_unknown(&mut self) { + if let Some(Prompt::Approvals(panel)) = &mut self.prompt { + panel.set_policy(None); + } + self.permission_policy = None; + if let Some(Prompt::Settings(panel)) = &self.prompt { + self.open_settings(panel.selected()); + } + } + fn set_notice(&mut self, text: impl Into) { self.notice = Some((text.into(), Instant::now() + NOTICE_TTL)); } @@ -2421,13 +2498,21 @@ impl App { } return; } - // The stop failed, so the combined draft stays in the - // composer with the reason: nothing typed is lost. + // A stop that failed for the Session still shown leaves the + // combined draft in the composer with the reason: nothing + // typed is lost. A switch already cleared it, so that notice + // does not claim the draft was kept. if let Some(error) = error { - self.notices.push(tf( - "Send now failed: {error}; the draft was kept", - &[("error", &crate::sanitize::safe_line(&error))], - )); + let error = crate::sanitize::safe_line(&error); + let text = if pending.draft_lost { + tf("Send now failed: {error}", &[("error", &error)]) + } else { + tf( + "Send now failed: {error}; the draft was kept", + &[("error", &error)], + ) + }; + self.notices.push(text); return; } // No read can start while the gesture is pending, so nothing @@ -2442,7 +2527,7 @@ impl App { self.set_notice(t("Send now is waiting for the insertion before sending")); return; } - self.submit_send_now(); + self.submit_send_now(pending.line, pending.session); } Update::Exported { format, path } => self.notices.push(tf( "Exported {format}: {path}", @@ -2454,6 +2539,7 @@ impl App { Update::Ready(configuration) => { self.label = Some(ModelLabel::new(&configuration)); } + Update::NoModel => self.label = None, Update::ModelFeatures { images, service_tiers, @@ -2461,6 +2547,21 @@ impl App { self.composer.set_accepts_images(images); self.service_tiers = service_tiers; } + Update::LineRefusal { + projection_id, + branch_id, + text, + } => { + let shown = match &mut self.prompt { + Some(Prompt::Lines(panel)) => { + panel.refuse(projection_id, &branch_id, text.clone()) + } + _ => false, + }; + if !shown { + self.set_notice(text); + } + } Update::Snapshot(snapshot) => { let was_running = self.running(); let switched = self @@ -2684,15 +2785,19 @@ impl App { Update::Permissions(policy) => match policy { Ok(policy) => { if let Some(Prompt::Approvals(panel)) = &mut self.prompt { - panel.set_policy(&policy); + panel.set_policy(Some(&policy)); } - self.permission_policy = policy; + self.permission_policy = Some(policy); if let Some(Prompt::Settings(panel)) = &self.prompt { self.open_settings(panel.selected()); } } - Err(error) => self.notices.push(error), + Err(error) => { + self.notices.push(error); + self.show_permission_unknown(); + } }, + Update::PermissionsUnknown => self.show_permission_unknown(), Update::PermissionSelected(preset) => { let label = format!("Permission: {}", crate::permission::name(preset)); let message = crate::ui::config::write( @@ -3253,6 +3358,9 @@ impl App { self.switches.clear(); self.failure = Some(message); self.failure_resumable = resumable; + // The resumed Session does not exist: a command typed now is + // Home's, not the invocation's resume. + self.startup_session = None; // A first message the invocation supplied has no Session // to take it: keep it in the draft and stay, rather than // exiting nonzero with nothing sent. @@ -3539,9 +3647,8 @@ impl App { && (key.mods == Modifiers::SHIFT || (key.code == KeyCode::BackTab && key.mods == Modifiers::NONE)) => { - self.host.send(Command::SetPermission( - crate::permission::PresetSelection::Next, - )); + self.host + .send(self.permission_change(crate::permission::PresetSelection::Next)); return Outcome::Continue; } KeyCode::Char('o' | 'p') if ctrl && !self.composer.palette_open() => { @@ -3631,7 +3738,7 @@ impl App { match self.composer.handle_key(key) { ComposerOutcome::Command { name, args } => return self.run_command(&name, &args), outcome => { - self.dispatch_composer(outcome, mode); + self.dispatch_composer(outcome, mode, self.target_line(), self.target_session()); } } if self.suggestion.is_some() && !self.composer.is_empty() { @@ -3666,7 +3773,13 @@ impl App { /// What a composer outcome does, the same for Enter and for the /// invocation's first message. - fn dispatch_composer(&mut self, outcome: ComposerOutcome, mode: SubmitMode) -> Outcome { + fn dispatch_composer( + &mut self, + outcome: ComposerOutcome, + mode: SubmitMode, + line: String, + session: Origin, + ) -> Outcome { // Every send key is refused before the composer acts (see // `settling_key_refused`), so an outcome that already cleared the draft // cannot arrive here while a gesture settles. If one ever does, the @@ -3707,7 +3820,7 @@ impl App { if mode == SubmitMode::Queue && self.running() { self.set_notice(t("Message queued")); } - self.host.submit(text, mode); + self.host.submit(text, mode, line, session); } ComposerOutcome::SubmitDraft { text, parts } => { let text = text.trim().to_owned(); @@ -3717,7 +3830,12 @@ impl App { if mode == SubmitMode::Queue && self.running() { self.set_notice(t("Message queued")); } - self.host.send(Command::SubmitDraft(parts, mode)); + self.host.send(Command::SubmitDraft { + parts, + mode, + line, + session, + }); } ComposerOutcome::Shell { command, shell } => { let entry = format!("{}{command}", shell.prefix()); @@ -3729,6 +3847,8 @@ impl App { run_id: running.run_id.clone(), command: running.command.clone(), private: running.private, + line, + session, }); self.shell = Some(running); } @@ -3765,7 +3885,20 @@ impl App { if submitted && self.session_id.is_empty() { self.unsent = Some(initial); } - self.dispatch_composer(outcome, SubmitMode::Queue) + // The invocation's first message belongs to the Session it asked to + // resume, not to the Home screen the first frame may still show. Its + // line is unknown here: the first frame may carry the line the first + // attachment invalidated, while the worker resolves an empty line to + // the line it shows when the message runs (design §14). + let session = if self.session_id.is_empty() { + match &self.startup_session { + Some(session) => Origin::Session(session.clone()), + None => Origin::Home, + } + } else { + Origin::Session(self.session_id.clone()) + }; + self.dispatch_composer(outcome, SubmitMode::Queue, String::new(), session) } /// Puts a first message no Session took back into the draft, unless the @@ -4011,7 +4144,9 @@ impl App { stop_turn: self.running(), }); } else { - self.host.stop(); + let line = self.target_line(); + let session = self.target_session(); + self.host.stop(line, session); } self.set_notice(t("Stopping")); } @@ -4274,6 +4409,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.begin_switch(SwitchKind::Resumed); self.host.send(Command::CloseSessions); @@ -4298,7 +4444,7 @@ impl App { }, Effect::OpenPermissions => { self.open_prompt(Prompt::Approvals(ApprovalsPanel::new( - &self.permission_policy, + self.permission_policy.as_ref(), ))); } Effect::OpenArea { area, note } => { @@ -4456,9 +4602,9 @@ impl App { } Effect::SetPermission(preset) => { self.prompt = None; - self.host.send(Command::SetPermission( - crate::permission::PresetSelection::Preset(preset), - )); + self.host.send( + self.permission_change(crate::permission::PresetSelection::Preset(preset)), + ); } Effect::Provider(action) => self.host.send(Command::Provider(action)), Effect::Plugin(action) => self.host.send(Command::Plugin(action)), @@ -4572,8 +4718,11 @@ impl App { .as_ref() .is_some_and(|label| label.model == model) { - self.host - .send(Command::Configure(format!("/effort {value}"))); + self.host.send(Command::Configure { + text: format!("/effort {value}"), + line: self.target_line(), + session: self.target_session(), + }); } else { self.set_notice(t( "Model changed; reopen /effort to choose its reasoning effort.", @@ -4603,7 +4752,7 @@ impl App { if self.prompt.is_none() && let Some(mut panel) = self.permissions_return.take() { - panel.set_policy(&self.permission_policy); + panel.set_policy(self.permission_policy.as_ref()); self.open_prompt(Prompt::Approvals(panel)); } if self.prompt.is_none() @@ -5032,7 +5181,10 @@ impl App { .as_ref() .map(|setting| setting.document.enabled), prompts: self.prompt_origins(), - permission: crate::permission::name(self.permission_policy.preset).to_owned(), + permission: self.permission_policy.as_ref().map_or_else( + || "Unavailable".to_owned(), + |policy| crate::permission::name(policy.preset).to_owned(), + ), }; self.open_prompt(Prompt::Settings(SettingsPanel::new(&values, select))); } @@ -5064,7 +5216,7 @@ impl App { self.settings_return = None; } Setting::Permission => { - let panel = ApprovalsPanel::new(&self.permission_policy); + let panel = ApprovalsPanel::new(self.permission_policy.as_ref()); self.open_prompt(Prompt::Approvals(panel)); } Setting::Isolation => { @@ -5573,18 +5725,27 @@ impl App { Outcome::Continue } "usage" => { - self.host.send(Command::Usage); + self.host.send(Command::Usage { + line: self.default_line(), + session: self.target_session(), + }); Outcome::Continue } "compact" => { - self.host.send(Command::Compact); + self.host.send(Command::Compact { + line: self.target_line(), + session: self.target_session(), + }); Outcome::Continue } "earlier" => { if self.fullscreen { self.show_earlier(); } else { - self.host.send(Command::Earlier); + self.host.send(Command::Earlier { + line: self.target_line(), + session: self.target_session(), + }); } Outcome::Continue } @@ -5620,7 +5781,16 @@ impl App { } "goal" => { match crate::goal::request(args) { - Some(request) => self.host.send(Command::Goal(request)), + Some(request) => self.host.send(Command::Goal { + request, + line: self.target_line(), + session: self.target_session(), + draft: if args.trim().is_empty() { + "/goal".to_owned() + } else { + format!("/goal {}", args.trim()) + }, + }), None => self.reports.push(Block::Status { text: crate::goal::USAGE.to_owned(), tone: Tone::Muted, @@ -5630,7 +5800,16 @@ impl App { } "loop" => { match crate::loop_view::request(args) { - Some(request) => self.host.send(Command::Loop(request)), + Some(request) => self.host.send(Command::Loop { + request, + line: self.target_line(), + session: self.target_session(), + draft: if args.trim().is_empty() { + "/loop".to_owned() + } else { + format!("/loop {}", args.trim()) + }, + }), None => self.reports.push(Block::Status { text: crate::loop_view::USAGE.to_owned(), tone: Tone::Muted, @@ -5653,8 +5832,11 @@ impl App { self.open_prompt(Prompt::Effort(EffortPrompt::new())); } let text = format!("/{name} {args}"); - self.host - .send(Command::Configure(text.trim_end().to_owned())); + self.host.send(Command::Configure { + text: text.trim_end().to_owned(), + line: self.target_line(), + session: self.target_session(), + }); Outcome::Continue } "report" => { @@ -5763,7 +5945,7 @@ impl App { // which opens holding where they work instead of ignoring // them, and says it until the user's first key there. if args.trim().is_empty() { - let panel = ApprovalsPanel::new(&self.permission_policy); + let panel = ApprovalsPanel::new(self.permission_policy.as_ref()); self.open_prompt(Prompt::Approvals(panel)); } else { self.open_management( @@ -7445,6 +7627,9 @@ impl App { } self.report_error = None; self.release_compaction_details(); + // The startup attachment has arrived: its Session is the centre, so + // later Home commands are Home's, not the invocation's resume. + self.startup_session = None; let first = self.session_id.is_empty(); // Home's first message started this Session: nothing shown to clear. if first @@ -7496,6 +7681,9 @@ impl App { kind => Some(kind), }; self.composer.clear(); + if let Some(pending) = &mut self.send_now { + pending.draft_lost = true; + } self.line_draft = None; self.suggestion = None; if let Some(text) = self.fork_draft.take() @@ -7605,7 +7793,10 @@ impl App { }; match snapshot.earlier { Earlier::Unread => { - self.host.send(Command::Earlier); + self.host.send(Command::Earlier { + line: self.target_line(), + session: self.target_session(), + }); self.reveal_pending = true; } Earlier::Reading => self.reveal_pending = true, @@ -8583,13 +8774,19 @@ impl App { fn status_line(&self, cols: usize) -> String { use dim_agent_types::PermissionPreset; let p = &self.palette; - let preset = self.permission_policy.preset; - let color = match preset { - PermissionPreset::ReadOnly => &p.permission_read, - PermissionPreset::WorkspaceWrite => &p.permission_write, - PermissionPreset::FullAccess => &p.permission_full, + let permission = match &self.permission_policy { + Some(policy) => { + let color = match policy.preset { + PermissionPreset::ReadOnly => &p.permission_read, + PermissionPreset::WorkspaceWrite => &p.permission_write, + PermissionPreset::FullAccess => &p.permission_full, + }; + fg(&format!("⏵⏵ {}", preset_label(policy.preset)), color) + } + // The line's policy is unknown until its own read or a fact + // arrives; the outgoing centre's preset is not shown for it. + None => fg(&format!("⏵⏵ {}", t("Permission unavailable")), &p.muted), }; - let permission = fg(&format!("⏵⏵ {}", preset_label(preset)), color); let hint = fg(t("(shift+tab to cycle)"), &p.muted); let total = cols.saturating_sub(2); let prefix = format!("{}{permission}", " ".repeat(MARGIN)); @@ -9613,7 +9810,7 @@ mod tests { drawn.key(KeyCode::Enter); assert!(matches!( sent.borrow().last(), - Some(Command::Submit(text, _)) if text == draft + Some(Command::Submit { text, .. }) if text == draft )); } } @@ -11567,7 +11764,7 @@ mod tests { } drawn.key(KeyCode::Enter); assert!( - matches!(sent.borrow().last(), Some(Command::Submit(text, _)) if text == &draft) + matches!(sent.borrow().last(), Some(Command::Submit { text, .. }) if text == &draft) ); } } @@ -12512,7 +12709,7 @@ mod tests { assert!(expected.ends_with(" appended")); press(&mut app, KeyCode::Enter); assert!( - matches!(sent.borrow().as_slice(), [Command::Submit(text, _)] if text == &expected) + matches!(sent.borrow().as_slice(), [Command::Submit { text, .. }] if text == &expected) ); } @@ -14753,7 +14950,7 @@ mod tests { } assert!(!sent.borrow().iter().any(|command| matches!( command, - Command::SetPermission(_) | Command::SaveIsolation { .. } + Command::SetPermission { .. } | Command::SaveIsolation { .. } ))); } } @@ -14803,9 +15000,12 @@ mod tests { app.handle_input(key(KeyCode::Enter)); assert!(matches!( sent.borrow().last(), - Some(Command::SetPermission( - crate::permission::PresetSelection::Preset(PermissionPreset::WorkspaceWrite) - )) + Some(Command::SetPermission { + change: crate::permission::PresetSelection::Preset( + PermissionPreset::WorkspaceWrite + ), + .. + }) )); app.apply(Update::PermissionSelected(PermissionPreset::WorkspaceWrite)); let saved: serde_json::Value = serde_json::from_str( @@ -14813,7 +15013,36 @@ mod tests { ) .unwrap(); assert_eq!(saved, serde_json::json!({"permission":"workspace-write"})); - assert_eq!(app.permission_policy.disallowed_tools, ["blocked"]); + assert_eq!( + app.permission_policy + .as_ref() + .expect("the read policy is shown") + .disallowed_tools, + ["blocked"] + ); + } + + #[test] + fn an_unknown_policy_hides_the_outgoing_preset() { + use dim_agent_types::{PermissionPolicy, PermissionPreset}; + + let (mut app, _home) = status_app("local", "fixture-model", None); + app.apply(Update::Permissions(Ok(PermissionPolicy { + preset: PermissionPreset::ReadOnly, + ..Default::default() + }))); + let (_, _, footer) = composer_chrome(&mut app, 100); + assert!(footer.contains("⏵⏵ Read only"), "{footer}"); + + app.apply(Update::PermissionsUnknown); + let (_, _, footer) = composer_chrome(&mut app, 100); + assert!(footer.contains("⏵⏵ Permission unavailable"), "{footer}"); + + app.apply(Update::Permissions(Err( + "permission: unavailable (denied)".into() + ))); + let (_, _, footer) = composer_chrome(&mut app, 100); + assert!(footer.contains("⏵⏵ Permission unavailable"), "{footer}"); } #[test] @@ -16231,7 +16460,7 @@ mod tests { assert!( matches!( sent.borrow().as_slice(), - [Command::Submit(text, _)] if text == "/skill:commit fix the parser" + [Command::Submit { text, .. }] if text == "/skill:commit fix the parser" ), "the draft is a message, never a command" ); @@ -18665,7 +18894,7 @@ mod tests { assert!(!drawn.app.composer.text().contains("[Image #1]")); drawn.key(KeyCode::Enter); match sent.borrow().last().unwrap() { - Command::Submit(text, _) => assert!(!text.contains("[Image #1]")), + Command::Submit { text, .. } => assert!(!text.contains("[Image #1]")), Command::OpenLine { prompt, .. } => assert_eq!(prompt, "look [Image #7]"), _ => panic!("message reuse must submit text or open a line"), } @@ -19185,7 +19414,7 @@ mod tests { assert!(app.notice.as_ref().unwrap().0.contains("/effort")); } else { assert!( - matches!(sent.borrow().last(), Some(Command::Configure(text)) if text == "/effort none") + matches!(sent.borrow().last(), Some(Command::Configure { text, .. }) if text == "/effort none") ); } } @@ -19319,7 +19548,7 @@ mod tests { press(&mut app, KeyCode::Enter); assert!(matches!( sent.borrow().as_slice(), - [Command::Goal(request)] if *request == expected + [Command::Goal { request, .. }] if *request == expected )); assert!(app.composer.is_empty()); } @@ -19364,7 +19593,7 @@ mod tests { assert!( matches!( sent.borrow().as_slice(), - [Command::Loop(request)] if *request == expected + [Command::Loop { request, .. }] if *request == expected ), "{words:?} dispatches {expected:?}" ); @@ -19422,10 +19651,10 @@ mod tests { commands .iter() .map(|command| match command { - Command::Submit(text, mode) => format!("submit:{}:{}", mode.as_str(), text), + Command::Submit { text, mode, .. } => format!("submit:{}:{}", mode.as_str(), text), Command::InputControl { input_id, action } => format!("{action}:{input_id}"), - Command::Stop => "stop".into(), - Command::SubmitNow => "submit-now".into(), + Command::Stop { .. } => "stop".into(), + Command::SubmitNow { .. } => "submit-now".into(), _ => "other".into(), }) .collect() @@ -19754,7 +19983,7 @@ mod tests { assert!( matches!( &sent_now[3..], - [Command::SubmitDraft(parts, SubmitMode::Queue)] + [Command::SubmitDraft { parts, mode: SubmitMode::Queue, .. }] if matches!(parts.as_slice(), [DraftPart::Text(text), DraftPart::Block(dim_agent_types::ContentBlock::Image { .. })] if text == "first\n") ), "the message is the text then the image, with no blank text: {}", @@ -19825,7 +20054,7 @@ mod tests { assert!( matches!( submitted, - [Command::SubmitDraft(parts, SubmitMode::Queue)] + [Command::SubmitDraft { parts, mode: SubmitMode::Queue, .. }] if matches!( parts.as_slice(), [ @@ -19886,7 +20115,7 @@ mod tests { assert!( matches!( &sent_now[2..], - [Command::SubmitDraft(parts, SubmitMode::Queue)] + [Command::SubmitDraft { parts, mode: SubmitMode::Queue, .. }] if matches!( parts.as_slice(), [ @@ -20178,7 +20407,7 @@ mod tests { assert!( matches!( &sent_now[2..], - [Command::SubmitDraft(parts, SubmitMode::Queue)] + [Command::SubmitDraft { parts, mode: SubmitMode::Queue, .. }] if matches!( parts.as_slice(), [ @@ -20255,7 +20484,10 @@ mod tests { sent_now .iter() .filter(|command| { - matches!(command, Command::Submit(..) | Command::SubmitDraft(..)) + matches!( + command, + Command::Submit { .. } | Command::SubmitDraft { .. } + ) }) .count(), 1, @@ -20276,9 +20508,10 @@ mod tests { error: Some("the stop failed".into()), }); assert!( - sent.borrow() - .iter() - .all(|command| !matches!(command, Command::Submit(..) | Command::SubmitDraft(..))), + sent.borrow().iter().all(|command| !matches!( + command, + Command::Submit { .. } | Command::SubmitDraft { .. } + )), "a cancelled submit sends nothing: {}", describe(&sent.borrow()).join(", ") ); @@ -20306,9 +20539,10 @@ mod tests { error: Some("the retry stop failed".into()), }); assert!( - sent.borrow() - .iter() - .all(|command| !matches!(command, Command::Submit(..) | Command::SubmitDraft(..))), + sent.borrow().iter().all(|command| !matches!( + command, + Command::Submit { .. } | Command::SubmitDraft { .. } + )), "no submit follows the retry's failed stop: {}", describe(&sent.borrow()).join(", ") ); @@ -20457,7 +20691,7 @@ mod tests { if image { assert!(matches!( sent.borrow().as_slice(), - [Command::SubmitDraft(parts, SubmitMode::Steer)] + [Command::SubmitDraft { parts, mode: SubmitMode::Steer, .. }] if matches!(parts.as_slice(), [DraftPart::Text(text), DraftPart::Block(dim_agent_types::ContentBlock::Image { .. })] if text == "look ") )); } else { @@ -20542,7 +20776,7 @@ mod tests { assert!( sent.borrow() .iter() - .all(|command| !matches!(command, Command::Submit(..))), + .all(|command| !matches!(command, Command::Submit { .. })), "nothing is submitted while the stop settles" ); press(&mut app, KeyCode::Enter); @@ -20550,7 +20784,7 @@ mod tests { assert!( sent.borrow() .iter() - .all(|command| !matches!(command, Command::Submit(..))), + .all(|command| !matches!(command, Command::Submit { .. })), "Enter and Ctrl+Enter send nothing while the stop settles" ); @@ -20567,7 +20801,7 @@ mod tests { assert!( matches!( submitted, - [Command::SubmitDraft(parts, SubmitMode::Queue)] + [Command::SubmitDraft { parts, mode: SubmitMode::Queue, .. }] if matches!(parts.first(), Some(DraftPart::Text(text)) if text == "first\nsecond\nand then ") && parts.iter().any(|part| matches!(part, DraftPart::Block(_))) ), @@ -20605,9 +20839,10 @@ mod tests { error: Some("the run would not stop".into()), }); assert!( - sent.borrow() - .iter() - .all(|command| !matches!(command, Command::Submit(..) | Command::SubmitDraft(..))), + sent.borrow().iter().all(|command| !matches!( + command, + Command::Submit { .. } | Command::SubmitDraft { .. } + )), "no submit follows a failed stop" ); assert_eq!(app.composer.text(), "first\nand then"); @@ -20701,7 +20936,7 @@ mod tests { press(&mut app, KeyCode::Enter); assert!(matches!( sent.borrow().as_slice(), - [Command::SubmitDraft(restored, _)] if restored == &parts + [Command::SubmitDraft { parts: restored, .. }] if restored == &parts )); } @@ -20818,7 +21053,7 @@ mod tests { ); press(&mut app, KeyCode::Enter); assert!( - matches!(sent.borrow().last(), Some(Command::Usage)), + matches!(sent.borrow().last(), Some(Command::Usage { .. })), "the palette ran /usage" ); assert_eq!( @@ -23051,7 +23286,7 @@ mod tests { let before = drawn.transcript(); drawn.app.show_earlier(); assert_eq!(sent.borrow().len(), 1, "an unread prefix is requested"); - assert!(matches!(sent.borrow()[0], Command::Earlier)); + assert!(matches!(sent.borrow()[0], Command::Earlier { .. })); drawn.draw(); assert_eq!(drawn.transcript(), before, "the request draws nothing"); let mut rows = window_rows(HISTORY_WINDOW); diff --git a/crates/dim-client/src/configuration.rs b/crates/dim-client/src/configuration.rs new file mode 100644 index 0000000000..ed803ea8c3 --- /dev/null +++ b/crates/dim-client/src/configuration.rs @@ -0,0 +1,27 @@ +//! One line's adopted configuration, read through `session.model.get`. +use crate::{ + Client, Result, + wire::{AdoptedConfiguration, Configuration}, +}; +use serde_json::json; + +/// The configuration `branch` adopted at `through`, or at its head when +/// omitted, with that line's own committed cutoff. The cutoff is the +/// watermark a client follows from: only that line's later +/// `context/configured` events apply to it (design §14). +pub async fn adopted( + client: &mut Client, + session_id: &str, + branch: &str, + through: Option, +) -> Result<(u64, Option)> { + let mut params = json!({"sessionId": session_id, "branchId": branch}); + if let Some(through) = through { + params["through"] = json!(through); + } + let reply: AdoptedConfiguration = client.typed("session.model.get", params).await?; + if reply.branch_id != branch { + return Err("session.model.get answered another line".into()); + } + Ok((reply.through, reply.configuration.map(Configuration::from))) +} diff --git a/crates/dim-client/src/lib.rs b/crates/dim-client/src/lib.rs index ec1a63f8c6..3564fa2036 100644 --- a/crates/dim-client/src/lib.rs +++ b/crates/dim-client/src/lib.rs @@ -1,6 +1,7 @@ //! Public RPC transport shared by native Dim clients; each connection negotiates its version. pub mod callback; +pub mod configuration; pub mod question; pub mod window; pub mod wire; diff --git a/crates/dim-client/src/wire.rs b/crates/dim-client/src/wire.rs index 64998ad058..5fd42075fd 100644 --- a/crates/dim-client/src/wire.rs +++ b/crates/dim-client/src/wire.rs @@ -58,6 +58,41 @@ pub struct Configuration { #[serde(default)] pub model_preferences: Option, } +/// The reply to `session.model.get`: one line's adopted configuration at that +/// line's own committed cutoff (design §14). +#[derive(Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct AdoptedConfiguration { + pub branch_id: String, + /// The requested line's committed cutoff, never an ancestor's sequence. + pub through: u64, + /// The line's configuration at that cutoff; `None` when it adopted none. + pub configuration: Option, +} +/// The configuration `session.model.get` answers with: the values a +/// `context/configured` event carries, under the adopted model's identity. +#[derive(Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct AdoptedModel { + pub model: dim_agent_types::ModelId, + #[serde(default)] + pub catalog_provider_id: Option, + #[serde(default)] + pub capability_snapshot: Option>, + #[serde(default)] + pub model_preferences: Option, +} +impl From for Configuration { + fn from(adopted: AdoptedModel) -> Self { + Self { + provider_id: adopted.model.provider_id, + catalog_provider_id: adopted.catalog_provider_id, + model_id: adopted.model.model_id, + capability_snapshot: adopted.capability_snapshot, + model_preferences: adopted.model_preferences, + } + } +} pub enum EventContent { BranchCreate(BranchCreateData), BranchStart(BranchStartData), @@ -397,6 +432,16 @@ impl HistoryWindow { } } +/// The line the Session's conversation is on, with that line's own sequence: +/// the branch-qualified cursor beside [`Attached::sequence`], which stays the +/// root's (design §14). +#[derive(Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct BranchCursor { + pub branch_id: String, + pub sequence: u64, +} + /// The record `session.attach` replies for the Session it opened. A server /// from before the record existed replies `{}`. #[derive(Deserialize)] @@ -404,6 +449,10 @@ impl HistoryWindow { pub struct Attached { #[serde(default)] pub sequence: u64, + /// The line the conversation is on and its own cursor; absent from a + /// server older than the field, whose Session is on its root (design §14). + #[serde(default)] + pub default_branch: Option, #[serde(default)] pub model: Option, #[serde(default)] @@ -424,6 +473,34 @@ pub struct Attached { #[serde(default)] pub title_revision: u64, } +impl Attached { + /// The reply's own configuration, which is the Session's and so the root's: + /// a conversation on a line reads that line's through `session.model.get` + /// (design §14). + pub fn configuration(&self) -> Option { + self.model.as_ref().map(|model| Configuration { + provider_id: model.provider_id.clone(), + catalog_provider_id: self.catalog_provider_id.clone(), + model_id: model.model_id.clone(), + capability_snapshot: self.capability_snapshot.clone(), + model_preferences: self.model_preferences.clone(), + }) + } +} + +/// The cursor a client resumes `line` from: the attach reply's own +/// `defaultBranch`, or the root's `sequence` on a server that predates the +/// field, whose Session is on its root (design §14). +pub fn resume_cursor( + default_branch: Option<&BranchCursor>, + sequence: u64, + line: &str, +) -> Option { + match default_branch { + Some(cursor) => (cursor.branch_id == line).then_some(cursor.sequence), + None => (line == dim_agent_types::ROOT_BRANCH_ID).then_some(sequence), + } +} #[derive(Deserialize)] #[serde(rename_all = "camelCase")] @@ -492,8 +569,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 407ac20e3a..7822fe80e2 100644 --- a/crates/dimcode/tests/cli_flow.rs +++ b/crates/dimcode/tests/cli_flow.rs @@ -14,6 +14,8 @@ mod accounts; mod acp; #[path = "cli_flow/hooks.rs"] mod hooks; +#[path = "cli_flow/lines.rs"] +mod lines; #[path = "cli_flow/mcp.rs"] mod mcp; #[path = "cli_flow/permission.rs"] diff --git a/crates/dimcode/tests/cli_flow/lines.rs b/crates/dimcode/tests/cli_flow/lines.rs new file mode 100644 index 0000000000..410607dc00 --- /dev/null +++ b/crates/dimcode/tests/cli_flow/lines.rs @@ -0,0 +1,3162 @@ +//! 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 { + next_usage(wire, &mut |_| None) +} + +/// The same requests, with the context reading answered when `usage` returns +/// one and reported unknown otherwise. +fn next_usage(wire: &mut Wire, usage: &mut impl FnMut(&Value) -> Option) -> 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" => match usage(&request) { + Some(reading) => wire.reply(&request, reading), + None => 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}) +} + +/// A user message `text` on the line, as its Timeline records it; the line +/// draws it as a row once [`applied`] carries its id. +fn said(sequence: u64, text: &str) -> Value { + json!({"id":format!("input-{sequence}"),"sequence":sequence,"create_at":1, + "type":"input","name":"message", + "data":{"user":{"content":[{"type":"text","text":text}]},"mode":"append"}}) +} + +/// The line adopted the message `input_id` the event `sequence` names: the +/// projection draws it as a transcript row from here. +fn applied(sequence: u64, input_id: &str) -> Value { + json!({"id":format!("applied-{sequence}"),"sequence":sequence,"create_at":1, + "type":"input","name":"applied", + "data":{"input_id":input_id,"mode":"append"}}) +} + +/// The model consumed the message `input_id`. +fn consumed(sequence: u64, input_id: &str) -> Value { + json!({"id":format!("consumed-{sequence}"),"sequence":sequence,"create_at":1, + "type":"input","name":"consumed","data":{"input_id":input_id}}) +} + +/// The composer's top border as the interface last painted it since +/// transcript offset `from`: that row carries the model label, and the +/// transcript still holds the label an earlier frame drew. A panel's border +/// names its title right after the corner; the composer's model label sits +/// at the right end of its own. +fn bar_since(terminal: &Terminal, from: usize) -> Option { + terminal.painted_rows(from).into_iter().rfind(|row| { + let row = row.trim_start(); + row.starts_with('╭') && row.ends_with('╮') && !row.starts_with("╭─ ") + }) +} + +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(); +} + +/// The shown line resumes from the cursor its attach reply carries: a line's +/// own sequence, and the root's `sequence` when the conversation is the root +/// (design §14). Its model is that line's own, adopted at or below the cursor, +/// read through `session.model.get`: the reply's model is the root's, and the +/// production display transcript omits `context/configured`. The reply's cursor +/// is authoritative: the directory only answers for a server that does not +/// carry the field. +#[test] +fn tui_resumes_the_shown_line_from_the_attach_cursor() { + for (line, cursor, listed, entries) in [ + ("main", 8, "main", &[("main", None)][..]), + ( + "line-1", + 5, + "line-1", + &[("main", None), ("line-1", Some("main"))][..], + ), + ( + "line-1", + 5, + "main", + &[("main", None), ("line-1", Some("main"))][..], + ), + ] { + let home = Home::new(); + let daemon = home.daemon(move |wire| { + wire.hello(&[ + "session.methods", + "session.branches", + "session.branch.get", + "session.branch_set_default", + "session.branch_end", + "session.history.display", + "session.history.detail", + "session.history.display.tail", + "session.history.display.transcript", + "session.model.get", + ]); + wire.2 = true; + let attach = wire.read("session.attach"); + let mut record = attach_record(&attach); + record["defaultBranch"] = json!({"branchId":line,"sequence":cursor}); + wire.reply(&attach, record); + let branches = next(wire); + assert_eq!(branches["method"], "session.branches"); + wire.reply(&branches, directory(listed, entries)); + let window = next(wire); + assert_eq!(window["method"], "session.history.display"); + assert_eq!(window["params"]["branchId"], json!(line)); + assert_eq!( + window["params"]["through"], + json!(cursor), + "the shown line resumes from the attach reply's default cursor" + ); + wire.reply( + &window, + json!({"items":[],"through":cursor,"nextBefore":1,"nextAfter":cursor,"done":true}), + ); + let parent = entries + .iter() + .find(|(id, _)| *id == line) + .and_then(|(_, parent)| *parent); + loop { + let request = next(wire); + match request["method"].as_str().unwrap() { + "session.branch.get" => { + assert_eq!(request["params"]["branchId"], json!(line)); + let detail = match parent { + Some(parent) => entry(line, parent), + None => json!({"branchId":line,"state":"open","head":8}), + }; + wire.reply(&request, detail); + } + "session.model.get" => { + assert_eq!(request["params"]["branchId"], json!(line)); + assert_eq!(request["params"]["through"], json!(cursor)); + assert!( + request["params"].get("before").is_none(), + "a line's configuration is read at one cutoff, not paged out of its history" + ); + wire.reply( + &request, + json!({"branchId":line,"through":cursor, + "configuration":{"model":{"providerId":"test","modelId":"line-model"}}}), + ); + } + other => panic!("unexpected {other}: {request}"), + } + } + }); + let mut command = home.command(); + sized(&mut command, 100, 32); + let mut terminal = Terminal::resume_tui(command); + terminal.until(match line { + "main" => "test / model", + _ => "test / line-model", + }); + home.kill(&terminal); + terminal.wait(); + daemon.join().unwrap(); + } +} + +/// Another client's adoption on a line reaches the bar when the user continues +/// there, and that line's own facts are read then (timeline UI §5, design §14). +fn adopted(wire: &mut Wire, branch: &str, sequence: u64, model: &str, preferences: Value) { + wire.notice( + "session.event", + json!({"sessionId":"session","branchId":branch, + "event":configured_event(sequence, model, preferences)}), + ); +} + +/// A context reading as `session.context.usage` reports one. +fn reading(input: f64) -> Value { + json!({"contextWindow":256000.0,"outputTokens":32000.0,"thresholdTokens":200000.0, + "estimatedInputTokens":input,"baselineSource":"estimate"}) +} + +fn policy(preset: &str) -> Value { + json!({"preset":preset,"allowedTools":[],"disallowedTools":[]}) +} + +/// `/resume` applies the launch preset to the line the attach reply names, the +/// line the conversation is on, not to the root the interface is leaving and +/// not to a line the directory reported before the attach (design §14). +#[test] +fn tui_resume_applies_the_preset_to_the_resumed_default_branch() { + let home = Home::new(); + let workspace = std::fs::canonicalize(&home.0).unwrap(); + let workspace = workspace.to_str().unwrap().to_owned(); + let daemon = home.daemon(move |wire| { + wire.hello(&[ + "session.methods", + "session.catalog", + "session.branches", + "session.permission.get", + "session.permission.update", + ]); + let providers = wire.read("account.providers"); + wire.reply(&providers, json!([])); + let catalog = wire.read("session.catalog"); + wire.reply( + &catalog, + json!({"sessions":[{"sessionId":"session","cwd":workspace, + "preview":"on the line","model":{"providerId":"test","modelId":"model"}, + "updatedAt":5}]}), + ); + // The directory's line and the attach reply's disagree: the reply is + // the one the write follows. + let directory = || directory("main", &[("main", None), ("line-1", Some("main"))]); + let mut opening_read = true; + loop { + let request = next(wire); + match request["method"].as_str().unwrap_or_default() { + "session.branches" => wire.reply(&request, directory()), + "session.attach" => { + let mut record = attach_record(&request); + record["defaultBranch"] = json!({"branchId":"line-1","sequence":5}); + wire.reply(&request, record); + } + "session.permission.get" => { + assert_eq!( + request["params"]["branchId"], + json!("line-1"), + "the preset follows the attach reply's line" + ); + wire.reply( + &request, + json!({"version":1,"policy":policy("workspace-write")}), + ); + if !opening_read { + break; + } + opening_read = false; + } + "session.history" => wire.reply(&request, history(5, vec![])), + other => panic!("unexpected {other}: {request}"), + } + } + let update = next(wire); + assert_eq!(update["method"], "session.permission.update"); + assert_eq!( + update["params"]["branchId"], + json!("line-1"), + "the write follows the attach reply's line" + ); + wire.reply(&update, json!({"version":2,"policy":policy("read-only")})); + loop { + let request = next(wire); + match request["method"].as_str().unwrap_or_default() { + "session.branches" => wire.reply(&request, directory()), + "session.permission.get" => { + wire.reply(&request, json!({"version":2,"policy":policy("read-only")})) + } + "session.attach" => { + let mut record = attach_record(&request); + record["defaultBranch"] = json!({"branchId":"line-1","sequence":5}); + wire.reply(&request, record); + } + "session.history" => wire.reply( + &request, + history(5, vec![configured_event(4, "line-model", json!({}))]), + ), + other => panic!("unexpected {other}: {request}"), + } + } + }); + let mut command = home.command(); + command.args(["--permission", "read-only"]); + sized(&mut command, 100, 32); + let mut terminal = Terminal::launch_tui(command); + terminal.until("Read only"); + terminal.write(b"/resume\r"); + terminal.until("on the line"); + terminal.write(b"\r"); + terminal.until("test / line-model"); + home.kill(&terminal); + terminal.wait(); + daemon.join().unwrap(); +} + +/// `p` continues on the moved line: its transcript, and its own model, +/// permission and context in the top bar, with its configuration facts folding +/// from then on even at a sequence below the root's (design §14, timeline UI §5). +#[test] +fn tui_p_shows_the_moved_lines_own_model_permission_and_usage() { + let home = Home::new(); + let (moved, move_seen) = std::sync::mpsc::channel(); + let (preset, presets) = 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", + "session.permission.get", + "session.permission.update", + "session.context.usage", + ]); + let attach = wire.read("session.attach"); + let mut record = attach_record(&attach); + record["defaultBranch"] = json!({"branchId":"main","sequence":8}); + wire.reply(&attach, record); + let branches = next(wire); + assert_eq!(branches["method"], "session.branches"); + wire.reply( + &branches, + directory("main", &[("main", None), ("line-1", Some("main"))]), + ); + let root = next(wire); + assert_eq!(root["method"], "session.history"); + wire.reply(&root, history(8, vec![])); + // Each line reports its own context: the root's, then the line's. + let mut usage = |request: &Value| { + let branch = request["params"]["branchId"].as_str().unwrap_or_default(); + Some(reading(if branch == "line-1" { 64000. } else { 1800. })) + }; + let mut root_preset = false; + loop { + let request = next_usage(wire, &mut usage); + let branch = request["params"]["branchId"].as_str().unwrap_or_default(); + match request["method"].as_str().unwrap_or_default() { + "session.permission.get" => match branch { + "main" => { + assert!(!root_preset, "the root's preset was read twice"); + root_preset = true; + wire.reply( + &request, + json!({"version":1,"policy":policy("workspace-write")}), + ); + // Another client adopts a model on the line while the + // root is still the default branch. + adopted( + wire, + "line-1", + 3, + "replacement", + json!({"reasoningEffort":"high"}), + ); + } + "line-1" => { + preset.send(branch.to_owned()).unwrap(); + wire.reply( + &request, + json!({"version":4,"policy":policy("full-access")}), + ); + } + other => panic!("permission read on {other}"), + }, + "session.branch_set_default" => { + assert_eq!(branch, "line-1"); + wire.reply(&request, json!({"defaultBranchId":"line-1"})); + moved.send(()).unwrap(); + } + "session.branch.get" => wire.reply(&request, entry("line-1", "main")), + "session.history" => { + let through = if branch == "line-1" { 3 } else { 8 }; + wire.reply(&request, history(through, vec![])); + } + "session.submit" => { + assert_eq!(branch, "line-1"); + wire.reply(&request, json!({"event":{}})); + // A fact below the root's cursor is still the line's own. + adopted( + wire, + "line-1", + 4, + "chosen", + json!({"reasoningEffort":"low"}), + ); + break; + } + other => panic!("unexpected {other}: {request}"), + } + } + wire.hold(); + }); + let mut command = home.command(); + sized(&mut command, 110, 34); + let mut terminal = Terminal::resume_tui(command); + terminal.until("test / model"); + terminal.until("1.8K / 256K"); + terminal.until("Workspace write"); + terminal.write(b"/lines\r"); + terminal.until("Main line"); + 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.until_anywhere("test / replacement · high"); + terminal.until_anywhere("⏵⏵ Full access"); + terminal.until_anywhere("64K / 256K"); + assert_eq!( + presets.recv_timeout(PATIENCE).unwrap(), + "line-1", + "the moved line's own preset is read" + ); + terminal.write(b"hello\r"); + terminal.until("test / chosen · low"); + home.kill(&terminal); + terminal.wait(); + daemon.join().unwrap(); +} + +/// A line whose configuration this client cannot read carries no model in the +/// bar, and moving back to the root shows the root's own again (design §14): +/// a server without `session.model.get`, and one that answers +/// `configuration: null`, both leave the moved line without a model. +#[test] +fn tui_a_line_without_a_readable_configuration_carries_no_model_and_the_root_restores_its_own() { + for offers in [false, true] { + let home = Home::new(); + let (moved, move_seen) = std::sync::mpsc::channel(); + let (back, back_seen) = std::sync::mpsc::channel(); + let daemon = home.daemon(move |wire| { + let mut features = vec![ + "session.methods", + "session.branches", + "session.branch.get", + "session.branch_set_default", + ]; + if offers { + features.push("session.model.get"); + } + wire.hello(&features); + let attach = wire.read("session.attach"); + let mut record = attach_record(&attach); + record["defaultBranch"] = json!({"branchId":"main","sequence":8}); + wire.reply(&attach, record); + let branches = next(wire); + assert_eq!(branches["method"], "session.branches"); + wire.reply( + &branches, + directory("main", &[("main", None), ("line-1", Some("main"))]), + ); + let root = next(wire); + assert_eq!(root["method"], "session.history"); + wire.reply(&root, history(8, vec![])); + let mut usage = |_request: &Value| None; + let mut moves = 0; + loop { + let request = next_usage(wire, &mut usage); + let branch = request["params"]["branchId"].as_str().unwrap_or_default(); + match request["method"].as_str().unwrap_or_default() { + "session.branch_set_default" => { + moves += 1; + let target = if moves == 1 { "line-1" } else { "main" }; + assert_eq!(branch, target); + wire.reply(&request, json!({"defaultBranchId":target})); + if moves == 1 { + moved.send(()).unwrap(); + } else { + back.send(()).unwrap(); + } + } + "session.branch.get" => { + assert_eq!(branch, "line-1"); + wire.reply(&request, entry("line-1", "main")); + } + "session.history" => { + let (through, events) = if branch == "line-1" { + (3, vec![said(2, "line window"), applied(3, "input-2")]) + } else { + (8, vec![]) + }; + wire.reply(&request, history(through, events)); + } + "session.model.get" => { + assert!(offers, "a server without the read is not asked"); + assert_eq!(branch, "line-1"); + wire.reply( + &request, + json!({"branchId":"line-1","through":3,"configuration":null}), + ); + } + other => panic!("unexpected {other}: {request}"), + } + } + }); + 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("Main line"); + let before_move = terminal.consumed; + terminal.write(b"\x1b[B"); + terminal.write(b"p"); + move_seen.recv_timeout(PATIENCE).unwrap(); + terminal.write(b"\x1b"); + terminal.until("line window"); + terminal.write(b"probe"); + terminal.until("probe"); + terminal.write(b"\x7f\x7f\x7f\x7f\x7f"); + let bar = bar_since(&terminal, before_move).expect("the bar was painted after the move"); + assert!( + !bar.contains("test / model"), + "offers={offers}: the moved line carries no model: {bar}" + ); + terminal.write(b"/lines\r"); + terminal.until("Main line"); + terminal.write(b"\x1b[A"); + terminal.write(b"p"); + back_seen.recv_timeout(PATIENCE).unwrap(); + terminal.until("test / model"); + home.kill(&terminal); + terminal.wait(); + daemon.join().unwrap(); + } +} + +/// A resumed Session whose conversation is on a line, with a server that +/// cannot read that line's configuration, shows no model and reports the +/// limitation once for the whole visit: not again when the window is ready, +/// when the user opens the line, or when `/earlier` reads another page of it +/// (design §14). +#[test] +fn tui_a_resumed_line_without_a_configuration_read_reports_it_once() { + let home = Home::new(); + let (switched, switch_seen) = std::sync::mpsc::channel(); + let (window, window_done) = std::sync::mpsc::channel(); + let (asked, earlier_seen) = std::sync::mpsc::channel(); + let daemon = home.daemon(move |wire| { + wire.hello(&[ + "session.methods", + "session.branches", + "session.branch.get", + "session.catalog", + ]); + fn page(through: u64, before: u64, events: Vec) -> Value { + json!({"events":events,"through":through,"nextAfter":through, + "nextBefore":before,"done":true}) + } + // Answers the inventory reads that follow a window, through the line's + // turn read that finishes it. + fn inventory(wire: &mut Wire) { + loop { + let request = wire.read_any(); + let branch = request["params"]["branchId"].as_str().unwrap_or_default(); + let through = request["params"]["through"].clone(); + match request["method"].as_str().unwrap_or_default() { + "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.branch.get" => { + wire.reply(&request, entry("line-1", "main")); + } + "session.turn.get" => { + wire.reply( + &request, + json!({"branchId":branch,"through":through,"turn":null,"output":null}), + ); + if branch == "line-1" { + break; + } + } + other => panic!("unexpected {other}: {request}"), + } + } + } + let mut usage = |_request: &Value| None; + let mut windows = 0; + loop { + let request = next_usage(wire, &mut usage); + let method = request["method"].as_str().unwrap_or_default().to_owned(); + let session = request["params"]["sessionId"].as_str().unwrap_or_default(); + let branch = request["params"]["branchId"].as_str().unwrap_or_default(); + match method.as_str() { + "session.attach" => { + let mut record = attach_record(&request); + if session == "on-the-line" { + record["defaultBranch"] = json!({"branchId":"line-1","sequence":5}); + switched.send(()).unwrap(); + } else { + record["defaultBranch"] = json!({"branchId":"main","sequence":8}); + } + wire.reply(&request, record); + } + "session.branches" => { + let default = if session == "on-the-line" { + "line-1" + } else { + "main" + }; + wire.reply( + &request, + directory(default, &[("main", None), ("line-1", Some("main"))]), + ); + } + "session.history" if branch != "line-1" => { + wire.reply(&request, history(8, vec![])); + } + "session.history" => { + let before = request["params"] + .get("before") + .and_then(serde_json::Value::as_u64); + match before { + // The resumed window, and later the line opened for + // view: one page that leaves older content unread. + None => { + wire.reply( + &request, + page( + 6, + 3, + vec![ + said(4, "resumed line"), + applied(5, "input-4"), + consumed(6, "input-4"), + ], + ), + ); + inventory(wire); + windows += 1; + if windows == 1 { + window.send(()).unwrap(); + } + } + // `/earlier`: the page that reaches the branch start. + Some(3) => { + wire.reply( + &request, + page(6, 1, vec![said(1, "older page"), applied(2, "input-1")]), + ); + asked.send(()).unwrap(); + break; + } + other => panic!("unexpected earlier cursor {other:?}: {request}"), + } + } + "session.catalog" => wire.reply( + &request, + json!({"sessions":[ + {"sessionId":"on-the-line","cwd":"/workspace","preview":"on the line", + "model":{"providerId":"test","modelId":"model"},"updatedAt":1}, + {"sessionId":"session","cwd":"/workspace","preview":"root work", + "model":{"providerId":"test","modelId":"model"},"updatedAt":2} + ]}), + ), + "session.detach" => wire.reply(&request, json!({})), + "session.branch.get" => wire.reply(&request, entry("line-1", "main")), + other => panic!("unexpected {other}: {request}"), + } + } + wire.hold(); + }); + let mut command = home.command(); + sized(&mut command, 100, 32); + let mut terminal = Terminal::resume_tui(command); + terminal.until("test / model"); + let before_switch = terminal.consumed; + terminal.write(b"/resume\r"); + terminal.until("on the line"); + terminal.write(b"\r"); + switch_seen.recv_timeout(PATIENCE).unwrap(); + terminal.until("Earlier content not loaded"); + // A composer echo proves the interface applied what the reply queued + // before it, the limitation notice among it. + terminal.write(b"probe"); + terminal.until("probe"); + terminal.write(b"\x7f\x7f\x7f\x7f\x7f"); + let bar = bar_since(&terminal, before_switch).expect("the bar was painted after the resume"); + assert!( + !bar.contains("test / model"), + "the resumed line carries no model: {bar}" + ); + let reported = |terminal: &Terminal| { + strip_ansi(&terminal.transcript) + .matches("cannot read line line-1") + .count() + }; + assert_eq!( + reported(&terminal), + 1, + "the resume reports the limitation once" + ); + window_done.recv_timeout(PATIENCE).unwrap(); + // Opening the line for view reads its window again, and makes its earlier + // pages draw; both stay within the visit the limitation was reported for. + terminal.write(b"/lines\r"); + terminal.until("Main line"); + terminal.write(b"\r"); + terminal.until("resumed line"); + // `/earlier` is a no-op until a window's inventory finishes; the read + // starts as soon as it has, and the daemon names the page it asks for. + terminal.write(b"/earlier\r"); + let mut attempts = 0; + while earlier_seen + .recv_timeout(Duration::from_millis(200)) + .is_err() + { + attempts += 1; + assert!(attempts < 25, "the earlier read never started"); + terminal.write(b"/earlier\r"); + } + terminal.write(b"/timeline\r"); + terminal.until("#1 older page"); + assert_eq!( + reported(&terminal), + 1, + "another page of the same line does not report it again" + ); + home.kill(&terminal); + terminal.wait(); + daemon.join().unwrap(); +} + +/// Continuing on a line whose configuration this client cannot read reports +/// the limitation once: the window that follows the move does not report it +/// again (design §14). +#[test] +fn tui_continuing_on_a_line_without_a_configuration_read_reports_it_once() { + 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", + ]); + let attach = wire.read("session.attach"); + let mut record = attach_record(&attach); + record["defaultBranch"] = json!({"branchId":"main","sequence":8}); + wire.reply(&attach, record); + let branches = next(wire); + assert_eq!(branches["method"], "session.branches"); + wire.reply( + &branches, + directory("main", &[("main", None), ("line-1", Some("main"))]), + ); + let root = next(wire); + assert_eq!(root["method"], "session.history"); + wire.reply(&root, history(8, vec![])); + let mut usage = |_request: &Value| None; + loop { + let request = next_usage(wire, &mut usage); + let branch = request["params"]["branchId"].as_str().unwrap_or_default(); + match request["method"].as_str().unwrap_or_default() { + "session.branch_set_default" => { + assert_eq!(branch, "line-1"); + wire.reply(&request, json!({"defaultBranchId":"line-1"})); + moved.send(()).unwrap(); + } + "session.branch.get" => { + assert_eq!(branch, "line-1"); + wire.reply(&request, entry("line-1", "main")); + } + "session.history" => { + let (through, events) = if branch == "line-1" { + (3, vec![said(2, "line window"), applied(3, "input-2")]) + } else { + (8, vec![]) + }; + wire.reply(&request, history(through, events)); + } + other => panic!("unexpected {other}: {request}"), + } + } + }); + 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("Main line"); + let before_move = terminal.consumed; + terminal.write(b"\x1b[B"); + terminal.write(b"p"); + move_seen.recv_timeout(PATIENCE).unwrap(); + terminal.write(b"\x1b"); + terminal.until("line window"); + terminal.write(b"probe"); + terminal.until("probe"); + let bar = bar_since(&terminal, before_move).expect("the bar was painted after the move"); + assert!( + !bar.contains("test / model"), + "the moved line carries no model: {bar}" + ); + assert_eq!( + strip_ansi(&terminal.transcript) + .matches("cannot read line line-1") + .count(), + 1, + "the move reports the limitation once" + ); + home.kill(&terminal); + terminal.wait(); + daemon.join().unwrap(); +} + +/// A policy read left before the conversation moved on does not become the new +/// centre's policy: the reply belongs to the line and the move that started it +/// (design §14). The new centre's read is released first, then the earlier +/// line's, so only the guard can keep the older reply out of the display. +#[test] +fn tui_a_late_policy_reply_from_an_earlier_line_does_not_replace_the_centres() { + let home = Home::new(); + let (moved, move_seen) = std::sync::mpsc::channel(); + let (back, back_seen) = std::sync::mpsc::channel(); + let (new_read, new_seen) = std::sync::mpsc::channel(); + let (release_old, release_old_rx) = std::sync::mpsc::channel::<()>(); + let daemon = home.daemon(move |wire| { + wire.hello(&[ + "session.methods", + "session.branches", + "session.branch.get", + "session.branch_set_default", + "session.permission.get", + "session.permission.update", + ]); + let attach = wire.read("session.attach"); + let mut record = attach_record(&attach); + record["defaultBranch"] = json!({"branchId":"main","sequence":8}); + wire.reply(&attach, record); + let branches = next(wire); + assert_eq!(branches["method"], "session.branches"); + wire.reply( + &branches, + directory("main", &[("main", None), ("line-1", Some("main"))]), + ); + let root = next(wire); + assert_eq!(root["method"], "session.history"); + wire.reply(&root, history(8, vec![])); + let mut usage = |_request: &Value| None; + let mut moves = 0; + let mut held: Option = None; + loop { + let request = next_usage(wire, &mut usage); + let branch = request["params"]["branchId"] + .as_str() + .unwrap_or_default() + .to_owned(); + match request["method"].as_str().unwrap_or_default() { + "session.permission.get" => match (moves, branch.as_str()) { + (0, "main") => wire.reply( + &request, + json!({"version":1,"policy":policy("workspace-write")}), + ), + (1, "line-1") => held = Some(request), + (2, "main") => { + wire.reply(&request, json!({"version":5,"policy":policy("read-only")})); + new_read.send(()).unwrap(); + release_old_rx.recv_timeout(PATIENCE).unwrap(); + wire.reply( + &held.take().expect("the earlier line's read"), + json!({"version":4,"policy":policy("full-access")}), + ); + wire.notice( + "session.event", + json!({"sessionId":"session","branchId":"main","event":said(9, "after the late policy")}), + ); + wire.notice( + "session.event", + json!({"sessionId":"session","branchId":"main","event":applied(10, "input-9")}), + ); + } + other => panic!("permission read on {other:?}"), + }, + "session.branch_set_default" => { + moves += 1; + let target = if moves == 1 { "line-1" } else { "main" }; + assert_eq!(branch, target); + wire.reply(&request, json!({"defaultBranchId":target})); + if moves == 1 { + moved.send(()).unwrap(); + } else { + back.send(()).unwrap(); + } + } + "session.branch.get" => { + assert_eq!(branch, "line-1"); + wire.reply(&request, entry("line-1", "main")); + } + "session.history" => wire.reply(&request, history(8, vec![])), + other => panic!("unexpected {other}: {request}"), + } + } + }); + let mut command = home.command(); + sized(&mut command, 110, 34); + let mut terminal = Terminal::resume_tui(command); + terminal.until("test / model"); + terminal.until("⏵⏵ Workspace write"); + + terminal.write(b"/lines\r"); + terminal.until("Main line"); + terminal.write(b"\x1b[B"); + terminal.write(b"p"); + move_seen.recv_timeout(PATIENCE).unwrap(); + + // The panel stays open across the move; the root becomes the centre again + // and its policy is read anew. + terminal.write(b"\x1b[A"); + terminal.write(b"p"); + back_seen.recv_timeout(PATIENCE).unwrap(); + let from = terminal.consumed; + new_seen.recv_timeout(PATIENCE).unwrap(); + terminal.until_anywhere("⏵⏵ Read only"); + + release_old.send(()).unwrap(); + terminal.until_anywhere("after the late policy"); + let painted = terminal.painted_rows(from); + assert!( + painted.iter().any(|row| row.contains("⏵⏵ Read only")), + "the new centre's own policy is shown: {painted:?}" + ); + assert!( + !painted.iter().any(|row| row.contains("⏵⏵ Full access")), + "the earlier line's late reply does not replace it: {painted:?}" + ); + home.kill(&terminal); + terminal.wait(); + daemon.join().unwrap(); +} + +/// A move whose new centre's policy read is refused shows that line's policy as +/// unavailable: the outgoing line's preset is not left in the status line or in +/// the Permissions panel (design §14). +#[test] +fn tui_a_moved_line_with_a_refused_policy_read_shows_no_outgoing_preset() { + 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.permission.get", + "session.permission.update", + "session.context.usage", + ]); + let attach = wire.read("session.attach"); + let mut record = attach_record(&attach); + record["defaultBranch"] = json!({"branchId":"main","sequence":8}); + wire.reply(&attach, record); + let branches = next(wire); + assert_eq!(branches["method"], "session.branches"); + wire.reply( + &branches, + directory("main", &[("main", None), ("line-1", Some("main"))]), + ); + let root = next(wire); + assert_eq!(root["method"], "session.history"); + wire.reply(&root, history(8, vec![])); + let mut usage = |_request: &Value| None; + loop { + let request = next_usage(wire, &mut usage); + let branch = request["params"]["branchId"].as_str().unwrap_or_default(); + match request["method"].as_str().unwrap_or_default() { + "session.permission.get" => match branch { + "main" => wire.reply( + &request, + json!({"version":1,"policy":policy("workspace-write")}), + ), + "line-1" => { + wire.send(json!({"jsonrpc":"2.0","id":request["id"],"error":{ + "code":-32000,"message":"fixture denied", + "data":{"appError":"denied"}}})); + moved.send(()).unwrap(); + break; + } + other => panic!("permission read on {other}"), + }, + "session.branch_set_default" => { + assert_eq!(branch, "line-1"); + wire.reply(&request, json!({"defaultBranchId":"line-1"})); + } + "session.branch.get" => wire.reply(&request, entry("line-1", "main")), + "session.history" => { + let through = if branch == "line-1" { 3 } else { 8 }; + wire.reply(&request, history(through, vec![])); + } + other => panic!("unexpected {other}: {request}"), + } + } + wire.hold(); + }); + let mut command = home.command(); + sized(&mut command, 110, 34); + let mut terminal = Terminal::resume_tui(command); + terminal.until("test / model"); + terminal.until("⏵⏵ Workspace write"); + + terminal.write(b"/lines\r"); + terminal.until("Main line"); + terminal.write(b"\x1b[B"); + terminal.write(b"p"); + move_seen.recv_timeout(PATIENCE).unwrap(); + // The panel keeps its selection across the move; Esc returns the keyboard + // to the composer. + terminal.write(b"\x1b"); + terminal.until("permission: unavailable"); + // A keystroke repaints every row from the state the failed read left. + terminal.write(b"probe"); + terminal.until("probe"); + terminal.write(b"\x7f\x7f\x7f\x7f\x7f"); + + let shown = strip_ansi(&terminal.transcript); + let footer = shown.rsplit("⏵⏵").next().expect("the footer was painted"); + assert!( + footer.trim_start().starts_with("Permission unavailable"), + "the moved line's policy is unknown, not the outgoing preset: {footer}" + ); + + terminal.write(b"/permissions\r"); + terminal.until("Permission mode"); + let shown = strip_ansi(&terminal.transcript); + let panel = &shown[shown.rfind("Permission mode").expect("the panel opened")..]; + assert!( + !panel.contains("(*)"), + "the panel marks no outgoing preset as current: {panel}" + ); + + home.kill(&terminal); + terminal.wait(); + daemon.join().unwrap(); +} + +/// A send-now pressed before a queued move reaches the centre stops the line +/// it was pressed on, and its draft goes back to the composer rather than to +/// the line the centre moved to (design §14). +#[test] +fn tui_send_now_keeps_its_draft_when_a_queued_move_reaches_the_centre_first() { + for fullscreen in [false, true] { + let home = Home::new(); + let (move_seen, moved) = std::sync::mpsc::channel(); + let (release_move, release) = std::sync::mpsc::channel::<()>(); + let (stop, stop_seen) = std::sync::mpsc::channel::(); + let (submit, submit_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.permission.get", + "session.permission.update", + ]); + let attach = wire.read("session.attach"); + let mut record = attach_record(&attach); + record["defaultBranch"] = json!({"branchId":"main","sequence":8}); + record["running"] = json!(true); + wire.reply(&attach, record); + let branches = next(wire); + assert_eq!(branches["method"], "session.branches"); + wire.reply( + &branches, + directory("main", &[("main", None), ("line-1", Some("main"))]), + ); + loop { + let request = next(wire); + match request["method"].as_str().unwrap_or_default() { + "session.branches" => wire.reply( + &request, + directory("main", &[("main", None), ("line-1", Some("main"))]), + ), + "session.history" => { + wire.reply(&request, history(8, vec![])); + break; + } + other => panic!("unexpected opening request: {other}: {request}"), + } + } + let mut usage = |_request: &Value| None; + let mut announced = false; + loop { + let request = next_usage(wire, &mut usage); + let branch = request["params"]["branchId"].as_str().unwrap_or_default(); + match request["method"].as_str().unwrap_or_default() { + "session.permission.get" => { + if !announced && branch == "main" { + announced = true; + wire.notice( + "session.state", + json!({"sessionId":"session","branchId":"main","running":true}), + ); + } + wire.reply( + &request, + json!({"version":1,"policy":policy(if branch == "line-1" { + "full-access" + } else { + "workspace-write" + })}), + ) + } + "session.branch_set_default" => { + assert_eq!(branch, "line-1"); + move_seen.send(()).unwrap(); + release.recv_timeout(PATIENCE).unwrap(); + wire.reply(&request, json!({"defaultBranchId":"line-1"})); + } + "session.branches" => wire.reply( + &request, + directory("main", &[("main", None), ("line-1", Some("main"))]), + ), + "session.branch.get" => wire.reply(&request, entry("line-1", "main")), + "session.history" => { + let through = if branch == "line-1" { 3 } else { 8 }; + wire.reply(&request, history(through, vec![])); + } + "session.stop" => { + stop.send(request["params"].clone()).unwrap(); + wire.reply(&request, json!({"sequence":9})); + } + "session.submit" => { + submit.send(request["params"].clone()).unwrap(); + wire.reply(&request, json!({"event":{}})); + wire.hold(); + return; + } + other => panic!("unexpected {other}: {request}"), + } + } + }); + let mut command = home.command(); + command.arg(if fullscreen { + "--fullscreen" + } else { + "--scrollback" + }); + sized(&mut command, 120, 36); + let mut terminal = Terminal::resume_tui(command); + terminal.until("test / model"); + terminal.until("⏵⏵ Workspace write"); + terminal.write(b"/lines\r"); + terminal.until("Main line"); + terminal.write(b"\x1b[B"); + terminal.write(b"p"); + moved.recv_timeout(PATIENCE).unwrap(); + // The panel can close before the move replies: Esc returns the keys to + // the composer while the move is still in flight. + terminal.write(b"\x1b[27u"); + terminal.write(b"carry on"); + terminal.until("carry on"); + terminal.write(b"\x1b[13;5u"); + release_move.send(()).unwrap(); + let stopped = stop_seen.recv_timeout(PATIENCE).unwrap(); + assert_eq!( + stopped["branchId"], "main", + "the stop stays on the line the gesture started on" + ); + // The cancelled submit reports itself; the draft is restored rather + // than written into the line the centre moved to. + terminal.until("The centre moved before the command ran"); + terminal.write(b"\r"); + let sent = submit_seen.recv_timeout(PATIENCE).unwrap(); + assert_eq!( + sent["branchId"], "line-1", + "the kept draft goes to the line the operator sees" + ); + assert_eq!(sent["text"], "carry on", "the whole draft is kept"); + home.kill(&terminal); + terminal.wait(); + daemon.join().unwrap(); + } +} + +/// A draft submitted while a move is in flight is not written into the line +/// the centre moved to: it is kept and reported, and a second Enter sends it +/// to the line on screen (design §14). +#[test] +fn tui_a_draft_typed_before_a_queued_move_does_not_go_to_the_new_centre() { + for fullscreen in [false, true] { + let home = Home::new(); + let (move_seen, moved) = std::sync::mpsc::channel(); + let (release_move, release) = std::sync::mpsc::channel::<()>(); + let (probe, probe_seen) = std::sync::mpsc::channel::>(); + let (submit, submit_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.permission.get", + "session.permission.update", + ]); + let attach = wire.read("session.attach"); + let mut record = attach_record(&attach); + record["defaultBranch"] = json!({"branchId":"main","sequence":8}); + wire.reply(&attach, record); + let branches = next(wire); + assert_eq!(branches["method"], "session.branches"); + wire.reply( + &branches, + directory("main", &[("main", None), ("line-1", Some("main"))]), + ); + loop { + let request = next(wire); + match request["method"].as_str().unwrap_or_default() { + "session.branches" => wire.reply( + &request, + directory("main", &[("main", None), ("line-1", Some("main"))]), + ), + "session.history" => { + wire.reply(&request, history(8, vec![])); + break; + } + other => panic!("unexpected opening request: {other}: {request}"), + } + } + let mut usage = |_request: &Value| None; + let mut submits: Vec = Vec::new(); + let mut probed = false; + loop { + let request = next_usage(wire, &mut usage); + let branch = request["params"]["branchId"].as_str().unwrap_or_default(); + match request["method"].as_str().unwrap_or_default() { + "session.permission.get" => wire.reply( + &request, + json!({"version":1,"policy":policy(if branch == "line-1" { + "full-access" + } else { + "workspace-write" + })}), + ), + "session.branch_set_default" => { + assert_eq!(branch, "line-1"); + move_seen.send(()).unwrap(); + release.recv_timeout(PATIENCE).unwrap(); + wire.reply(&request, json!({"defaultBranchId":"line-1"})); + } + "session.branches" => wire.reply( + &request, + directory("main", &[("main", None), ("line-1", Some("main"))]), + ), + "session.branch.get" => wire.reply(&request, entry("line-1", "main")), + "session.history" => { + let through = if branch == "line-1" { 3 } else { 8 }; + wire.reply(&request, history(through, vec![])); + } + "session.submit" => { + submits.push(request["params"].clone()); + wire.reply(&request, json!({"event":{}})); + if probed { + submit.send(request["params"].clone()).unwrap(); + wire.hold(); + return; + } + } + "session.permission.update" if !probed => { + probed = true; + probe.send(submits.clone()).unwrap(); + wire.reply(&request, json!({"version":2})); + } + other => panic!("unexpected {other}: {request}"), + } + } + }); + let mut command = home.command(); + command.arg(if fullscreen { + "--fullscreen" + } else { + "--scrollback" + }); + sized(&mut command, 120, 36); + let mut terminal = Terminal::resume_tui(command); + terminal.until("test / model"); + terminal.until("⏵⏵ Workspace write"); + terminal.write(b"/lines\r"); + terminal.until("Main line"); + terminal.write(b"\x1b[B"); + terminal.write(b"p"); + moved.recv_timeout(PATIENCE).unwrap(); + terminal.write(b"\x1b[27u"); + terminal.write(b"hello"); + terminal.until("hello"); + terminal.write(b"\r"); + release_move.send(()).unwrap(); + terminal.until_anywhere("⏵⏵ Full access"); + // A command queued after the draft's submit lets the daemon report + // which submits the submit decision let out. + terminal.write(b"\x1b[Z"); + let before = probe_seen.recv_timeout(PATIENCE).unwrap(); + assert_eq!( + before, + Vec::::new(), + "the draft typed on the outgoing line is not submitted to the new one" + ); + terminal.write(b"\r"); + let sent = submit_seen.recv_timeout(PATIENCE).unwrap(); + assert_eq!(sent["branchId"], "line-1"); + assert_eq!(sent["text"], "hello", "the kept draft is whole"); + home.kill(&terminal); + terminal.wait(); + daemon.join().unwrap(); + } +} + +/// `/resume` into a Session whose policy read is refused shows that Session's +/// policy as unavailable: the outgoing Session's preset is not left in the +/// status line, Settings or the Permissions panel (design §14). +#[test] +fn tui_resuming_into_a_refused_policy_read_shows_no_outgoing_preset() { + let home = Home::new(); + let daemon = home.daemon(move |wire| { + wire.hello(&[ + "session.methods", + "session.catalog", + "session.branches", + "session.permission.get", + "session.permission.update", + ]); + let attach = wire.read("session.attach"); + let mut record = attach_record(&attach); + record["defaultBranch"] = json!({"branchId":"main","sequence":8}); + wire.reply(&attach, record); + let mut usage = |_request: &Value| None; + loop { + let request = next_usage(wire, &mut usage); + let session = request["params"]["sessionId"].as_str().unwrap_or_default(); + match request["method"].as_str().unwrap_or_default() { + "session.branches" => wire.reply(&request, directory("main", &[("main", None)])), + "session.history" => wire.reply(&request, history(8, vec![])), + "session.permission.get" => { + if session == "other" { + wire.send(json!({"jsonrpc":"2.0","id":request["id"],"error":{ + "code":-32000,"message":"fixture denied", + "data":{"appError":"denied"}}})); + } else { + wire.reply( + &request, + json!({"version":1,"policy":policy("full-access")}), + ); + } + } + "session.catalog" => wire.reply( + &request, + json!({"sessions":[{"sessionId":"other","cwd":"/workspace", + "preview":"second conversation", + "model":{"providerId":"test","modelId":"model"},"updatedAt":9}]}), + ), + "session.detach" => wire.reply(&request, json!({})), + "session.attach" => { + let mut record = attach_record(&request); + record["defaultBranch"] = json!({"branchId":"main","sequence":8}); + wire.reply(&request, record); + } + other => panic!("unexpected {other}: {request}"), + } + } + }); + let mut command = home.command(); + command.arg("--scrollback"); + sized(&mut command, 110, 34); + let mut terminal = Terminal::resume_tui(command); + terminal.until("test / model"); + terminal.until("⏵⏵ Full access"); + terminal.write(b"/resume\r"); + terminal.until("second conversation"); + terminal.write(b"\r"); + terminal.until("permission: unavailable"); + // A keystroke repaints the status line from the state the failed read + // left. + terminal.write(b"probe"); + terminal.until("probe"); + terminal.write(b"\x7f\x7f\x7f\x7f\x7f"); + let shown = strip_ansi(&terminal.transcript); + let footer = shown.rsplit("⏵⏵").next().expect("the footer was painted"); + assert!( + footer.trim_start().starts_with("Permission unavailable"), + "the outgoing Session's preset is not left in the status line: {footer}" + ); + + terminal.write(b"/permissions\r"); + terminal.until("Permission mode"); + let shown = strip_ansi(&terminal.transcript); + let panel = &shown[shown.rfind("Permission mode").expect("the panel opened")..]; + assert!( + !panel.contains("(*)"), + "the panel marks no outgoing preset as current: {panel}" + ); + terminal.write(b"\x1b[27u"); + terminal.write(b"/settings\r"); + terminal.until_row("Permission", "Unavailable"); + home.kill(&terminal); + terminal.wait(); + daemon.join().unwrap(); +} + +/// `/compact` typed before a queued move reaches the centre compacts nothing: +/// the command carries the line it was typed on and is cancelled once that +/// line has moved, instead of compacting the new centre (design §14). +#[test] +fn tui_compact_typed_before_a_queued_move_compacts_nothing() { + for fullscreen in [false, true] { + let home = Home::new(); + let (move_seen, moved) = std::sync::mpsc::channel(); + let (release_move, release) = std::sync::mpsc::channel::<()>(); + let (compact, compact_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.permission.get", + ]); + let attach = wire.read("session.attach"); + let mut record = attach_record(&attach); + record["defaultBranch"] = json!({"branchId":"main","sequence":8}); + wire.reply(&attach, record); + let branches = next(wire); + assert_eq!(branches["method"], "session.branches"); + wire.reply( + &branches, + directory("main", &[("main", None), ("line-1", Some("main"))]), + ); + loop { + let request = next(wire); + match request["method"].as_str().unwrap_or_default() { + "session.branches" => wire.reply( + &request, + directory("main", &[("main", None), ("line-1", Some("main"))]), + ), + "session.history" => { + wire.reply(&request, history(8, vec![])); + break; + } + other => panic!("unexpected opening request: {other}: {request}"), + } + } + let mut usage = |_request: &Value| None; + loop { + let request = next_usage(wire, &mut usage); + let branch = request["params"]["branchId"].as_str().unwrap_or_default(); + match request["method"].as_str().unwrap_or_default() { + "session.permission.get" => wire.reply( + &request, + json!({"version":1,"policy":policy(if branch == "line-1" { + "full-access" + } else { + "workspace-write" + })}), + ), + "session.branch_set_default" => { + assert_eq!(branch, "line-1"); + move_seen.send(()).unwrap(); + release.recv_timeout(PATIENCE).unwrap(); + wire.reply(&request, json!({"defaultBranchId":"line-1"})); + } + "session.branches" => wire.reply( + &request, + directory("main", &[("main", None), ("line-1", Some("main"))]), + ), + "session.branch.get" => wire.reply(&request, entry("line-1", "main")), + "session.history" => { + let through = if branch == "line-1" { 3 } else { 8 }; + wire.reply(&request, history(through, vec![])); + } + "session.context.compact" => { + compact.send(request["params"].clone()).unwrap(); + wire.reply(&request, json!({"status":"completed"})); + } + other => panic!("unexpected {other}: {request}"), + } + } + }); + let mut command = home.command(); + command.arg(if fullscreen { + "--fullscreen" + } else { + "--scrollback" + }); + sized(&mut command, 120, 36); + let mut terminal = Terminal::resume_tui(command); + terminal.until("test / model"); + terminal.until("⏵⏵ Workspace write"); + terminal.write(b"/lines\r"); + terminal.until("Main line"); + terminal.write(b"\x1b[B"); + terminal.write(b"p"); + moved.recv_timeout(PATIENCE).unwrap(); + // The panel closes while the move is still in flight, so the command + // is typed and submitted before the centre changes. + terminal.write(b"\x1b[27u"); + terminal.write(b"/compact"); + terminal.until("/compact"); + terminal.write(b"\r"); + // The echo of a later key proves the interface handled Enter and sent + // the command while the centre was still the line it showed; the move + // replies only after that. + terminal.write(b"probe"); + terminal.until("probe"); + release_move.send(()).unwrap(); + terminal.until("The centre moved before /compact ran"); + assert!( + compact_seen.try_recv().is_err(), + "the line the centre moved to is not compacted" + ); + home.kill(&terminal); + terminal.wait(); + daemon.join().unwrap(); + } +} + +/// `/usage` typed before a queued move reaches the centre reports nothing: the +/// command carries the default branch it was typed on and is cancelled once +/// that line has moved, instead of reading the new centre's usage (design §14). +#[test] +fn tui_usage_typed_before_a_queued_move_reads_no_new_centre() { + for fullscreen in [false, true] { + let home = Home::new(); + let (move_seen, moved) = std::sync::mpsc::channel(); + let (release_move, release) = std::sync::mpsc::channel::<()>(); + let daemon = home.daemon(move |wire| { + wire.hello(&[ + "session.methods", + "session.branches", + "session.branch.get", + "session.branch_set_default", + "session.permission.get", + ]); + let attach = wire.read("session.attach"); + let mut record = attach_record(&attach); + record["defaultBranch"] = json!({"branchId":"main","sequence":8}); + wire.reply(&attach, record); + let branches = next(wire); + assert_eq!(branches["method"], "session.branches"); + wire.reply( + &branches, + directory("main", &[("main", None), ("line-1", Some("main"))]), + ); + loop { + let request = next(wire); + match request["method"].as_str().unwrap_or_default() { + "session.branches" => wire.reply( + &request, + directory("main", &[("main", None), ("line-1", Some("main"))]), + ), + "session.history" => { + wire.reply(&request, history(8, vec![])); + break; + } + other => panic!("unexpected opening request: {other}: {request}"), + } + } + let mut usage = |_request: &Value| Some(reading(1849.0)); + loop { + let request = next_usage(wire, &mut usage); + let branch = request["params"]["branchId"].as_str().unwrap_or_default(); + match request["method"].as_str().unwrap_or_default() { + "session.permission.get" => wire.reply( + &request, + json!({"version":1,"policy":policy(if branch == "line-1" { + "full-access" + } else { + "workspace-write" + })}), + ), + "session.branch_set_default" => { + assert_eq!(branch, "line-1"); + move_seen.send(()).unwrap(); + release.recv_timeout(PATIENCE).unwrap(); + wire.reply(&request, json!({"defaultBranchId":"line-1"})); + } + "session.branches" => wire.reply( + &request, + directory("main", &[("main", None), ("line-1", Some("main"))]), + ), + "session.branch.get" => wire.reply(&request, entry("line-1", "main")), + "session.history" => { + let through = if branch == "line-1" { 3 } else { 8 }; + wire.reply(&request, history(through, vec![])); + } + other => panic!("unexpected {other}: {request}"), + } + } + }); + let mut command = home.command(); + command.arg(if fullscreen { + "--fullscreen" + } else { + "--scrollback" + }); + sized(&mut command, 120, 36); + let mut terminal = Terminal::resume_tui(command); + terminal.until("test / model"); + terminal.until("⏵⏵ Workspace write"); + terminal.write(b"/lines\r"); + terminal.until("Main line"); + terminal.write(b"\x1b[B"); + terminal.write(b"p"); + moved.recv_timeout(PATIENCE).unwrap(); + // The panel closes while the move is still in flight, so the command + // is typed and submitted before the centre changes. + terminal.write(b"\x1b[27u"); + terminal.write(b"/usage"); + terminal.until("/usage"); + terminal.write(b"\r"); + // The echo of a later key proves the interface handled Enter and sent + // the command while the centre was still the line it showed; the move + // replies only after that. + terminal.write(b"probe"); + terminal.until("probe"); + release_move.send(()).unwrap(); + terminal.until("The centre moved before /usage ran"); + let shown = strip_ansi(&terminal.transcript); + assert!( + !shown.contains("Context:"), + "the cancelled command prints no usage report: {shown}" + ); + home.kill(&terminal); + terminal.wait(); + daemon.join().unwrap(); + } +} + +/// `/earlier` typed before a queued move reaches the centre loads nothing from +/// the new centre: the command carries the line it was typed on and is +/// cancelled once that line has moved (design §14). +#[test] +fn tui_earlier_typed_before_a_queued_move_loads_no_new_centre() { + for fullscreen in [false, true] { + let home = Home::new(); + let (move_seen, moved) = std::sync::mpsc::channel(); + let (release_move, release) = std::sync::mpsc::channel::<()>(); + let (earlier, earlier_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.permission.get", + ]); + let attach = wire.read("session.attach"); + let mut record = attach_record(&attach); + record["defaultBranch"] = json!({"branchId":"main","sequence":8}); + wire.reply(&attach, record); + let branches = next(wire); + assert_eq!(branches["method"], "session.branches"); + wire.reply( + &branches, + directory("main", &[("main", None), ("line-1", Some("main"))]), + ); + let root = next(wire); + assert_eq!(root["method"], "session.history"); + // The drawn top holds an older page, so both TUI modes ask for it. + let mut page = history(8, vec![said(2, "root window")]); + page["nextBefore"] = json!(2); + wire.reply(&root, page); + let mut usage = |_request: &Value| None; + loop { + let request = next_usage(wire, &mut usage); + let branch = request["params"]["branchId"].as_str().unwrap_or_default(); + match request["method"].as_str().unwrap_or_default() { + "session.permission.get" => wire.reply( + &request, + json!({"version":1,"policy":policy(if branch == "line-1" { + "full-access" + } else { + "workspace-write" + })}), + ), + "session.branch_set_default" => { + assert_eq!(branch, "line-1"); + move_seen.send(()).unwrap(); + release.recv_timeout(PATIENCE).unwrap(); + wire.reply(&request, json!({"defaultBranchId":"line-1"})); + } + "session.branches" => wire.reply( + &request, + directory("main", &[("main", None), ("line-1", Some("main"))]), + ), + "session.branch.get" => wire.reply(&request, entry("line-1", "main")), + "session.history" => { + let through = if branch == "line-1" { 3 } else { 8 }; + if request["params"].get("before").is_some() { + earlier.send(request["params"].clone()).unwrap(); + } + wire.reply(&request, history(through, vec![])); + } + other => panic!("unexpected {other}: {request}"), + } + } + }); + let mut command = home.command(); + command.arg(if fullscreen { + "--fullscreen" + } else { + "--scrollback" + }); + sized(&mut command, 120, 36); + let mut terminal = Terminal::resume_tui(command); + terminal.until("test / model"); + terminal.until("⏵⏵ Workspace write"); + terminal.write(b"/lines\r"); + terminal.until("Main line"); + terminal.write(b"\x1b[B"); + terminal.write(b"p"); + moved.recv_timeout(PATIENCE).unwrap(); + // The panel closes while the move is still in flight, so the command + // is typed and submitted before the centre changes. + terminal.write(b"\x1b[27u"); + terminal.write(b"/earlier"); + terminal.until("/earlier"); + terminal.write(b"\r"); + // The echo of a later key proves the interface handled Enter and sent + // the command while the centre was still the line it showed; the move + // replies only after that. + terminal.write(b"probe"); + terminal.until("probe"); + release_move.send(()).unwrap(); + terminal.until("The centre moved before /earlier ran"); + assert!( + earlier_seen.try_recv().is_err(), + "the line the centre moved to loads no earlier page" + ); + home.kill(&terminal); + terminal.wait(); + daemon.join().unwrap(); + } +} + +/// A permission change typed before a queued move reaches the centre changes +/// nothing: the gesture names the default line it saw, and the change is +/// cancelled once that line has moved (design §14). +#[test] +fn tui_a_permission_change_typed_before_a_queued_move_changes_nothing() { + let home = Home::new(); + let (move_seen, moved) = std::sync::mpsc::channel(); + let (release_move, release) = std::sync::mpsc::channel::<()>(); + let (changed, updates) = std::sync::mpsc::channel::(); + let daemon = home.daemon(move |wire| { + wire.hello(&[ + "session.methods", + "session.branches", + "session.branch.get", + "session.branch_set_default", + "session.permission.get", + "session.permission.update", + ]); + let attach = wire.read("session.attach"); + let mut record = attach_record(&attach); + record["defaultBranch"] = json!({"branchId":"main","sequence":8}); + wire.reply(&attach, record); + let branches = next(wire); + assert_eq!(branches["method"], "session.branches"); + wire.reply( + &branches, + directory("main", &[("main", None), ("line-1", Some("main"))]), + ); + loop { + let request = next(wire); + match request["method"].as_str().unwrap_or_default() { + "session.branches" => wire.reply( + &request, + directory("main", &[("main", None), ("line-1", Some("main"))]), + ), + "session.history" => { + wire.reply(&request, history(8, vec![])); + break; + } + other => panic!("unexpected opening request: {other}: {request}"), + } + } + let mut usage = |_request: &Value| None; + loop { + let request = next_usage(wire, &mut usage); + let branch = request["params"]["branchId"].as_str().unwrap_or_default(); + match request["method"].as_str().unwrap_or_default() { + "session.permission.get" => wire.reply( + &request, + json!({"version":1,"policy":policy(if branch == "line-1" { + "full-access" + } else { + "workspace-write" + })}), + ), + "session.permission.update" => { + changed.send(request["params"].clone()).unwrap(); + wire.reply(&request, json!({"version":2})); + } + "session.branch_set_default" => { + assert_eq!(branch, "line-1"); + move_seen.send(()).unwrap(); + release.recv_timeout(PATIENCE).unwrap(); + wire.reply(&request, json!({"defaultBranchId":"line-1"})); + } + "session.branches" => wire.reply( + &request, + directory("main", &[("main", None), ("line-1", Some("main"))]), + ), + "session.branch.get" => wire.reply(&request, entry("line-1", "main")), + "session.history" => { + let through = if branch == "line-1" { 3 } else { 8 }; + wire.reply(&request, history(through, vec![])); + } + other => panic!("unexpected {other}: {request}"), + } + } + }); + let mut command = home.command(); + command.arg("--scrollback"); + sized(&mut command, 120, 36); + let mut terminal = Terminal::resume_tui(command); + terminal.until("test / model"); + terminal.until("⏵⏵ Workspace write"); + terminal.write(b"/lines\r"); + terminal.until("Main line"); + terminal.write(b"\x1b[B"); + terminal.write(b"p"); + moved.recv_timeout(PATIENCE).unwrap(); + // The panel closes before the move replies, so the keys that follow act on + // the view that still shows the outgoing default line. + terminal.write(b"\x1b[27u"); + terminal.write(b"\x1b[Z"); + release_move.send(()).unwrap(); + terminal.until("The session or line moved before the permission change ran"); + assert!( + updates.try_recv().is_err(), + "the permission change typed on the outgoing default line writes nothing" + ); + // A second gesture names the line the centre moved to; its update is the + // only one the daemon sees. + terminal.write(b"\x1b[Z"); + let written = updates.recv_timeout(PATIENCE).unwrap(); + assert_eq!(written["branchId"], "line-1"); + assert!( + updates.try_recv().is_err(), + "the cancelled change and the later gesture do not both write" + ); + home.kill(&terminal); + terminal.wait(); + daemon.join().unwrap(); +} + +/// A draft submitted before a Session handoff replies is not written into the +/// Session that replaces it, even when both call their line `main`: it is +/// kept, reported, and a second Enter sends it to the Session on screen +/// (design §14). +#[test] +fn tui_a_draft_typed_before_a_session_handoff_does_not_go_to_the_new_session() { + let home = Home::new(); + let (attached, attach_seen) = std::sync::mpsc::channel(); + let (release_attach, release) = std::sync::mpsc::channel::<()>(); + let (probe, probed) = std::sync::mpsc::channel::>(); + let (submit, submit_seen) = std::sync::mpsc::channel::(); + let daemon = home.daemon(move |wire| { + wire.hello(&[ + "session.methods", + "session.catalog", + "session.branches", + "session.permission.get", + "session.permission.update", + ]); + let attach = wire.read("session.attach"); + let mut record = attach_record(&attach); + record["defaultBranch"] = json!({"branchId":"main","sequence":8}); + wire.reply(&attach, record); + let branches = next(wire); + assert_eq!(branches["method"], "session.branches"); + wire.reply(&branches, directory("main", &[("main", None)])); + let history_read = next(wire); + assert_eq!(history_read["method"], "session.history"); + wire.reply(&history_read, history(8, vec![])); + let mut usage = |_request: &Value| None; + let mut submits: Vec = Vec::new(); + loop { + let request = next_usage(wire, &mut usage); + let session = request["params"]["sessionId"].as_str().unwrap_or_default(); + match request["method"].as_str().unwrap_or_default() { + "session.catalog" => wire.reply( + &request, + json!({"sessions":[{"sessionId":"other","cwd":"/workspace", + "preview":"second conversation", + "model":{"providerId":"test","modelId":"model"},"updatedAt":9}]}), + ), + "session.detach" => wire.reply(&request, json!({})), + "session.attach" => { + let mut record = attach_record(&request); + record["defaultBranch"] = json!({"branchId":"main","sequence":8}); + if session == "other" { + attached.send(()).unwrap(); + release.recv_timeout(PATIENCE).unwrap(); + } + wire.reply(&request, record); + } + "session.branches" => wire.reply(&request, directory("main", &[("main", None)])), + "session.history" => wire.reply(&request, history(8, vec![])), + "session.permission.get" => wire.reply( + &request, + json!({"version":1,"policy":policy("workspace-write")}), + ), + "session.permission.update" => { + probe.send(submits.clone()).unwrap(); + wire.reply(&request, json!({"version":2})); + } + "session.submit" => { + submits.push(request["params"].clone()); + wire.reply(&request, json!({"event":{}})); + submit.send(request["params"].clone()).unwrap(); + } + other => panic!("unexpected {other}: {request}"), + } + } + }); + let mut command = home.command(); + command.arg("--scrollback"); + sized(&mut command, 120, 36); + let mut terminal = Terminal::resume_tui(command); + terminal.until("test / model"); + terminal.until("⏵⏵ Workspace write"); + terminal.write(b"/resume\r"); + terminal.until("second conversation"); + terminal.write(b"\r"); + attach_seen.recv_timeout(PATIENCE).unwrap(); + // The new attachment has not replied, so the interface still shows the + // outgoing Session: this draft belongs to that Session's view. + terminal.write(b"hello"); + terminal.until("hello"); + terminal.write(b"\r"); + release_attach.send(()).unwrap(); + terminal.until("The centre moved before the command ran"); + // The permission read the probe starts flushes every command queued ahead + // of it; no submit may come out before that. + terminal.write(b"\x1b[Z"); + let before = probed.recv_timeout(PATIENCE).unwrap(); + assert!( + before.is_empty(), + "a draft typed in the outgoing Session is not submitted to the new one" + ); + terminal.write(b"\r"); + let sent = submit_seen.recv_timeout(PATIENCE).unwrap(); + assert_eq!(sent["sessionId"], "other"); + assert_eq!(sent["branchId"], "main"); + assert_eq!(sent["text"], "hello", "the kept draft is whole"); + home.kill(&terminal); + terminal.wait(); + daemon.join().unwrap(); +} + +/// An interrupt pressed while a Session handoff is still in flight does not +/// stop the Session that replaces it: the gesture names the Session and line +/// it saw, and a handoff cancels it instead (design §14). A held `session.fork` +/// is the command in front of the handoff, so the interface still shows the +/// outgoing Session and its run when Esc is pressed. +#[test] +fn tui_an_interrupt_typed_before_a_session_handoff_does_not_stop_the_new_session() { + let home = Home::new(); + let (forked, fork_seen) = std::sync::mpsc::channel(); + let (release_fork, release) = std::sync::mpsc::channel::<()>(); + let (updated, update_seen) = std::sync::mpsc::channel::(); + let (stop, stop_seen) = std::sync::mpsc::channel::(); + let daemon = home.daemon(move |wire| { + wire.hello(&[ + "session.branches", + "session.fork", + "session.permission.get", + "session.permission.update", + ]); + let attach = wire.read("session.attach"); + let mut record = attach_record(&attach); + record["defaultBranch"] = json!({"branchId":"main","sequence":8}); + wire.reply(&attach, record); + wire.end(json!({"turn_id":"turn","status":"completed","reason":"done"})); + wire.notice( + "session.state", + json!({"sessionId":"session","branchId":"main","running":true}), + ); + let mut usage = |_request: &Value| None; + loop { + let request = next_usage(wire, &mut usage); + let session = request["params"]["sessionId"].as_str().unwrap_or_default(); + match request["method"].as_str().unwrap_or_default() { + "session.branches" => wire.reply(&request, directory("main", &[("main", None)])), + "session.history" if session == "forked" => wire.reply( + &request, + history(8, vec![said(3, "after the fork"), applied(4, "input-3")]), + ), + "session.history" => wire.reply(&request, history(8, vec![])), + "session.permission.get" => wire.reply( + &request, + json!({"version":1,"policy":policy("workspace-write")}), + ), + "session.fork" => { + forked.send(()).unwrap(); + release.recv_timeout(PATIENCE).unwrap(); + wire.reply(&request, json!({"sessionId":"forked"})); + } + "session.detach" => wire.reply(&request, json!({})), + "session.attach" => { + let mut record = attach_record(&request); + record["defaultBranch"] = json!({"branchId":"main","sequence":8}); + wire.reply(&request, record); + } + "session.permission.update" => { + updated.send(request["params"].clone()).unwrap(); + wire.reply(&request, json!({"version":2})); + } + "session.stop" => { + stop.send(request["params"].clone()).unwrap(); + wire.reply(&request, json!({"sequence":9})); + } + other => panic!("unexpected {other}: {request}"), + } + } + }); + let mut command = home.command(); + command.arg("--scrollback"); + sized(&mut command, 120, 36); + let mut terminal = Terminal::resume_tui(command); + terminal.until("test / model"); + terminal.until("⏵⏵ Workspace write"); + terminal.until("esc interrupt"); + terminal.write(b"/fork\r"); + terminal.until("Fork the session"); + terminal.write(b"y"); + fork_seen.recv_timeout(PATIENCE).unwrap(); + // The fork's reply is held, so the interface still shows the outgoing + // Session's running turn: this Esc belongs to it. + terminal.write(b"\x1b[27u"); + terminal.until("Stopping"); + release_fork.send(()).unwrap(); + terminal.until("after the fork"); + // The permission change the probe starts flushes every command queued + // ahead of it; the stop must have been decided by then. + terminal.write(b"\x1b[Z"); + let changed = update_seen.recv_timeout(PATIENCE).unwrap(); + assert_eq!(changed["sessionId"], "forked"); + assert!( + stop_seen.try_recv().is_err(), + "the interrupt pressed on the outgoing Session does not stop the new one" + ); + terminal.until("The session moved before the stop ran"); + home.kill(&terminal); + terminal.wait(); + daemon.join().unwrap(); +} + +/// The `Ctrl+Enter` gesture is on the same boundary: a handoff while its stop +/// is still queued cancels the stop without wedging the send key, and a later +/// gesture reaches the Session on screen (design §14). +#[test] +fn tui_a_send_now_typed_before_a_session_handoff_does_not_stop_the_new_session() { + let home = Home::new(); + let (forked, fork_seen) = std::sync::mpsc::channel(); + let (release_fork, release) = std::sync::mpsc::channel::<()>(); + let (stopped, stop_seen) = std::sync::mpsc::channel::(); + let (submitted, submit_seen) = std::sync::mpsc::channel::(); + let (updated, update_seen) = std::sync::mpsc::channel::(); + let daemon = home.daemon(move |wire| { + wire.hello(&[ + "session.branches", + "session.fork", + "session.permission.get", + "session.permission.update", + ]); + let attach = wire.read("session.attach"); + let mut record = attach_record(&attach); + record["defaultBranch"] = json!({"branchId":"main","sequence":8}); + wire.reply(&attach, record); + wire.end(json!({"turn_id":"turn","status":"completed","reason":"done"})); + wire.notice( + "session.state", + json!({"sessionId":"session","branchId":"main","running":true}), + ); + let mut usage = |_request: &Value| None; + loop { + let request = next_usage(wire, &mut usage); + let session = request["params"]["sessionId"].as_str().unwrap_or_default(); + match request["method"].as_str().unwrap_or_default() { + "session.branches" => wire.reply(&request, directory("main", &[("main", None)])), + "session.history" if session == "forked" => wire.reply( + &request, + history(8, vec![said(3, "after the fork"), applied(4, "input-3")]), + ), + "session.history" => wire.reply(&request, history(8, vec![])), + "session.permission.get" => wire.reply( + &request, + json!({"version":1,"policy":policy("workspace-write")}), + ), + "session.fork" => { + forked.send(()).unwrap(); + release.recv_timeout(PATIENCE).unwrap(); + wire.reply(&request, json!({"sessionId":"forked"})); + wire.notice( + "session.state", + json!({"sessionId":"forked","branchId":"main","running":true}), + ); + } + "session.detach" => wire.reply(&request, json!({})), + "session.attach" => { + let mut record = attach_record(&request); + record["defaultBranch"] = json!({"branchId":"main","sequence":8}); + wire.reply(&request, record); + } + "session.stop" => { + stopped.send(request["params"].clone()).unwrap(); + wire.reply(&request, json!({"sequence":9})); + } + "session.permission.update" => { + updated.send(request["params"].clone()).unwrap(); + wire.reply(&request, json!({"version":2})); + } + "session.submit" => { + submitted.send(request["params"].clone()).unwrap(); + wire.reply(&request, json!({"event":{}})); + wire.hold(); + return; + } + other => panic!("unexpected {other}: {request}"), + } + } + }); + let mut command = home.command(); + command.arg("--scrollback"); + sized(&mut command, 120, 36); + let mut terminal = Terminal::resume_tui(command); + terminal.until("test / model"); + terminal.until("⏵⏵ Workspace write"); + terminal.until("esc interrupt"); + terminal.write(b"/fork\r"); + terminal.until("Fork the session"); + terminal.write(b"y"); + fork_seen.recv_timeout(PATIENCE).unwrap(); + // The fork's reply is held: the draft and the gesture that stops its run + // belong to the Session still on screen. + terminal.write(b"carry on"); + terminal.until("carry on"); + terminal.write(b"\x1b[13;5u"); + terminal.write(b"x"); + terminal.until("carry onx"); + let painted_from = terminal.transcript.len(); + release_fork.send(()).unwrap(); + terminal.until("after the fork"); + // The permission change the probe starts flushes every command queued + // ahead of it; the send-now stop must have been decided by then. + terminal.write(b"\x1b[Z"); + let changed = update_seen.recv_timeout(PATIENCE).unwrap(); + assert_eq!(changed["sessionId"], "forked"); + assert!( + stop_seen.try_recv().is_err(), + "the send-now stop pressed on the outgoing Session does not stop the new one" + ); + terminal.until("Send now failed: The session moved before the send ran"); + terminal.until("esc interrupt"); + let notice = strip_ansi(&terminal.transcript[painted_from..]); + assert!( + !notice + .contains("Send now failed: The session moved before the send ran; the draft was kept"), + "the handoff cleared the composer, so the notice must not claim the draft was kept" + ); + terminal.write(b"again"); + terminal.until("again"); + terminal.write(b"\x1b[13;5u"); + let second = stop_seen.recv_timeout(PATIENCE).unwrap(); + assert_eq!(second["sessionId"], "forked"); + assert_eq!(second["branchId"], "main"); + let sent = submit_seen.recv_timeout(PATIENCE).unwrap(); + assert_eq!(sent["sessionId"], "forked"); + assert_eq!(sent["text"], "again"); + home.kill(&terminal); + terminal.wait(); + daemon.join().unwrap(); +} + +/// A message and a permission change typed on Home while a `/resume` is still +/// attaching belong to Home: neither is submitted to nor written on the +/// Session that attachment brings in (design §14). +#[test] +fn tui_a_home_send_and_permission_change_do_not_reach_the_resumed_session() { + for fullscreen in [false, true] { + let home = Home::new(); + let (attaching, attach_seen) = std::sync::mpsc::channel(); + let (release_attach, release) = std::sync::mpsc::channel::<()>(); + let (submitted, submit_seen) = std::sync::mpsc::channel::(); + let (updated, update_seen) = std::sync::mpsc::channel::(); + let daemon = home.daemon(move |wire| { + wire.hello(&[ + "session.catalog", + "session.branches", + "session.permission.get", + "session.permission.update", + ]); + let mut usage = |_request: &Value| None; + let mut version = 1; + loop { + let request = next_usage(wire, &mut usage); + let session = request["params"]["sessionId"].as_str().unwrap_or_default(); + match request["method"].as_str().unwrap_or_default() { + "session.catalog" => wire.reply( + &request, + json!({"sessions":[{"sessionId":"other","cwd":"/workspace", + "preview":"second conversation","model":{"providerId":"test","modelId":"model"}, + "updatedAt":9}]}), + ), + "session.attach" => { + assert_eq!(request["params"]["sessionId"], "other"); + attaching.send(()).unwrap(); + release.recv_timeout(PATIENCE).unwrap(); + let mut record = attach_record(&request); + record["defaultBranch"] = json!({"branchId":"main","sequence":8}); + wire.reply(&request, record); + } + "session.branches" => { + wire.reply(&request, directory("main", &[("main", None)])) + } + "session.history" => wire.reply( + &request, + history( + 8, + vec![said(3, "resumed conversation"), applied(4, "input-3")], + ), + ), + "session.permission.get" => { + let preset = if version == 1 { "read-only" } else { "workspace-write" }; + wire.reply( + &request, + json!({"version":version,"policy":policy(preset)}), + ); + } + "session.permission.update" => { + assert_eq!(session, "other"); + updated.send(request["params"].clone()).unwrap(); + version += 1; + wire.reply(&request, json!({"version":version})); + } + "session.submit" => { + submitted.send(request["params"].clone()).unwrap(); + wire.reply(&request, json!({"event":{}})); + } + other => panic!("unexpected {other}: {request}"), + } + } + }); + let mut command = home.command(); + command.arg(if fullscreen { + "--fullscreen" + } else { + "--scrollback" + }); + sized(&mut command, 120, 36); + let mut terminal = Terminal::launch_tui(command); + terminal.until("Ask anything"); + terminal.write(b"/resume\r"); + terminal.until("second conversation"); + terminal.write(b"\r"); + attach_seen.recv_timeout(PATIENCE).unwrap(); + // The attachment has not replied, so the interface still shows Home: + // this message and Shift-Tab belong to it, not to the Session coming. + terminal.write(b"hello\r"); + terminal.write(b"\x1b[Z"); + // Typed after the gestures, so reading it proves the interface has + // taken both before the attachment is released. + terminal.write(b"qzx"); + terminal.until("qzx"); + release_attach.send(()).unwrap(); + terminal.until("resumed conversation"); + // The permission change the probe starts flushes every command queued + // ahead of it: the Home send and Shift-Tab must be decided by then. + terminal.write(b"\x1b[Z"); + let changed = update_seen.recv_timeout(PATIENCE).unwrap(); + assert_eq!(changed["sessionId"], "other"); + assert_eq!(changed["branchId"], "main"); + assert_eq!( + changed["expectedVersion"], 1, + "the Home gesture must not have written the resumed line first" + ); + assert!( + submit_seen.try_recv().is_err(), + "a message typed on Home is not submitted to the resumed Session" + ); + // The two notices may have been painted in the frame that carried + // the resumed view, before the title echo this flow waited on. + terminal.until_anywhere("the draft was kept"); + terminal.until_anywhere("nothing was changed"); + home.kill(&terminal); + terminal.wait(); + daemon.join().unwrap(); + } +} + +/// A send left over from the Session `/new` left does not start a Session at +/// Home, and is not submitted there: the command names the Session it was +/// typed in, not Home (design §14). +#[test] +fn tui_a_stale_send_behind_new_does_not_start_a_session() { + for fullscreen in [false, true] { + let home = Home::new(); + let (forking, fork_seen) = std::sync::mpsc::channel(); + let (release_fork, release) = std::sync::mpsc::channel::<()>(); + let (created, create_seen) = std::sync::mpsc::channel::(); + let (submitted, submit_seen) = std::sync::mpsc::channel::(); + let daemon = home.daemon(move |wire| { + wire.hello(&[ + "session.branches", + "session.fork", + "session.permission.get", + "session.permission.update", + ]); + let mut usage = |_request: &Value| None; + let attach = wire.read("session.attach"); + let mut record = attach_record(&attach); + record["defaultBranch"] = json!({"branchId":"main","sequence":8}); + wire.reply(&attach, record); + loop { + let request = next_usage(wire, &mut usage); + match request["method"].as_str().unwrap_or_default() { + "session.branches" => { + wire.reply(&request, directory("main", &[("main", None)])) + } + "session.history" => wire.reply( + &request, + history( + 8, + vec![ + said(3, "the first turn"), + applied(4, "input-3"), + json!({"id":"end-5","sequence":5,"create_at":1,"type":"turn", + "name":"end","data":{"turn_id":"turn","status":"completed", + "reason":"done"}}), + ], + ), + ), + "session.permission.get" => wire.reply( + &request, + json!({"version":1,"policy":policy("workspace-write")}), + ), + "session.permission.update" => wire.reply(&request, json!({"version":2})), + "session.fork" => { + forking.send(()).unwrap(); + release.recv_timeout(PATIENCE).unwrap(); + wire.reply(&request, json!({"sessionId":"forked"})); + } + "session.attach" => { + let mut record = attach_record(&request); + record["defaultBranch"] = json!({"branchId":"main","sequence":8}); + wire.reply(&request, record); + } + "session.detach" => wire.reply(&request, json!({})), + "session.create" => { + created.send(request["params"].clone()).unwrap(); + wire.reply( + &request, + json!({"sessionId":"unexpected", + "model":{"providerId":"test","modelId":"model"}}), + ); + } + "session.submit" => { + submitted.send(request["params"].clone()).unwrap(); + wire.reply(&request, json!({"event":{}})); + } + other => panic!("unexpected {other}: {request}"), + } + } + }); + let mut command = home.command(); + command.arg(if fullscreen { + "--fullscreen" + } else { + "--scrollback" + }); + sized(&mut command, 120, 36); + let mut terminal = Terminal::resume_tui(command); + terminal.until("the first turn"); + terminal.until("test / model"); + terminal.write(b"/fork\r"); + terminal.until("Fork the session"); + terminal.write(b"y"); + fork_seen.recv_timeout(PATIENCE).unwrap(); + // The fork's reply is held, so the interface still shows the Session + // `/new` is about to leave: this draft belongs to that Session. + terminal.write(b"/new\r"); + terminal.write(b"stale"); + terminal.until("stale"); + terminal.write(b"\r"); + // Typed after the send, so reading it proves the interface has taken + // the send before the fork is released. + terminal.write(b"qzx"); + terminal.until("qzx"); + release_fork.send(()).unwrap(); + terminal.until("The centre moved before the command ran"); + assert!( + create_seen.try_recv().is_err(), + "a send from the Session `/new` left does not start a Session" + ); + assert!( + submit_seen.try_recv().is_err(), + "a send from the Session `/new` left is not submitted at Home" + ); + terminal.until("the draft was kept"); + home.kill(&terminal); + terminal.wait(); + daemon.join().unwrap(); + } +} + +/// The invocation's first message on a resumed Session is submitted on the +/// line the attach reply names, even when the first frame still shows the +/// line the attachment invalidated and the reply has not arrived (design §14). +#[test] +fn tui_the_first_prompt_of_a_resumed_session_follows_the_line_its_attach_names() { + for fullscreen in [false, true] { + let home = Home::new(); + let (attaching, attach_seen) = std::sync::mpsc::channel(); + let (release_attach, release) = std::sync::mpsc::channel::<()>(); + let (submitted, submit_seen) = std::sync::mpsc::channel::(); + let daemon = home.daemon(move |wire| { + wire.hello(&[]); + let attach = wire.read("session.attach"); + assert_eq!(attach["params"]["sessionId"], "session"); + let mut record = attach_record(&attach); + record["defaultBranch"] = json!({"branchId":"line-1","sequence":3}); + record["sequence"] = json!(3); + attaching.send(()).unwrap(); + release.recv_timeout(PATIENCE).unwrap(); + wire.reply(&attach, record); + let mut usage = |_request: &Value| None; + loop { + let request = next_usage(wire, &mut usage); + match request["method"].as_str().unwrap_or_default() { + "session.history" => wire.reply(&request, history(3, vec![])), + "session.submit" => { + submitted.send(request["params"].clone()).unwrap(); + wire.reply(&request, json!({"event":{}})); + } + other => panic!("unexpected {other}: {request}"), + } + } + }); + let mut command = home.command(); + command.args([ + "tui", + if fullscreen { + "--fullscreen" + } else { + "--scrollback" + }, + "--resume", + "session", + "-p", + "continue", + ]); + sized(&mut command, 120, 36); + let mut terminal = Terminal::launch_tui(command); + attach_seen.recv_timeout(PATIENCE).unwrap(); + // The reply is held, so the first frame drains the invalidated + // projection: the invocation's first message reads that frame's line, + // not the line the attachment is about to name. + terminal.until("Welcome to DIM"); + release_attach.send(()).unwrap(); + let sent = submit_seen.recv_timeout(PATIENCE).unwrap(); + assert_eq!(sent["sessionId"], "session"); + assert_eq!( + sent["branchId"], "line-1", + "the first message follows the attach reply's line" + ); + assert_eq!(sent["text"], "continue"); + home.kill(&terminal); + terminal.wait(); + daemon.join().unwrap(); + } +} + +/// A permission change typed on the Home screen `--resume` shows before its +/// attachment replies is Home's: no line of the resumed Session is written +/// (design §14). The `/compact` that follows the attachment arrives after +/// that gesture is decided, and the gesture typed on the attached Session is +/// the one whose write the daemon sees. +#[test] +fn tui_a_launch_home_permission_change_does_not_reach_the_resumed_session() { + for fullscreen in [false, true] { + for default in ["main", "line-1"] { + let home = Home::new(); + let (attaching, attach_seen) = std::sync::mpsc::channel(); + let (release_attach, release) = std::sync::mpsc::channel::<()>(); + let (updated, update_seen) = std::sync::mpsc::channel::(); + let (compacting, compact_seen) = std::sync::mpsc::channel::<()>(); + let daemon = home.daemon(move |wire| { + wire.hello(&[ + "session.branches", + "session.permission.get", + "session.permission.update", + ]); + let mut usage = |_request: &Value| None; + let mut version = 1; + loop { + let request = next_usage(wire, &mut usage); + let session = request["params"]["sessionId"].as_str().unwrap_or_default(); + match request["method"].as_str().unwrap_or_default() { + "session.attach" => { + assert_eq!(session, "session"); + let mut record = attach_record(&request); + record["defaultBranch"] = json!({"branchId":default,"sequence":8}); + attaching.send(()).unwrap(); + release.recv_timeout(PATIENCE).unwrap(); + wire.reply(&request, record); + } + "session.branches" => wire.reply( + &request, + directory(default, &[("main", None), ("line-1", Some("main"))]), + ), + "session.history" => wire.reply( + &request, + history( + 8, + vec![said(3, "resumed conversation"), applied(4, "input-3")], + ), + ), + "session.permission.get" => wire.reply( + &request, + json!({"version":version,"policy":policy("read-only")}), + ), + "session.permission.update" => { + updated.send(request["params"].clone()).unwrap(); + version += 1; + wire.reply(&request, json!({"version":version})); + } + "session.submit" => { + panic!("a Home message reached the resumed Session: {request}") + } + "session.context.compact" => { + assert_eq!(request["params"]["branchId"], default); + compacting.send(()).unwrap(); + wire.reply(&request, json!({"status":"completed"})); + } + other => panic!("unexpected {other}: {request}"), + } + } + }); + let mut command = home.command(); + command.args([ + "tui", + if fullscreen { + "--fullscreen" + } else { + "--scrollback" + }, + "--resume", + "session", + ]); + sized(&mut command, 120, 36); + let mut terminal = Terminal::launch_tui(command); + attach_seen.recv_timeout(PATIENCE).unwrap(); + // The screen is Home until the reply lands; the gesture read its + // text, so it is decided before the attachment is released. + terminal.until("Welcome to DIM"); + terminal.write(b"\x1b[Z"); + terminal.write(b"qzx"); + terminal.until("qzx"); + release_attach.send(()).unwrap(); + // The boundary row is out once the attachment's own projection is + // applied, so the commands below name the resumed Session. + terminal.until("resumed session"); + terminal.write(b"/compact\r"); + compact_seen.recv_timeout(PATIENCE).unwrap(); + assert!( + update_seen.try_recv().is_err(), + "the launch Home gesture writes no resumed line" + ); + // A gesture typed after the attachment names its line: its write + // is the only one, against the version the opening read reported. + terminal.write(b"\x1b[Z"); + let changed = update_seen.recv_timeout(PATIENCE).unwrap(); + assert_eq!(changed["sessionId"], "session"); + assert_eq!(changed["branchId"], default); + assert_eq!(changed["expectedVersion"], 1); + assert!( + update_seen.try_recv().is_err(), + "the launch Home gesture writes no resumed line of its own" + ); + terminal.until("nothing was changed"); + home.kill(&terminal); + terminal.wait(); + daemon.join().unwrap(); + } + } +} + +/// A shell command typed on a Session a `/resume` is about to leave does not +/// run in the Session the attachment brings in: the command names the Session +/// and line it was typed on, and the attachment has replaced both +/// (design §14). +#[test] +fn tui_a_shell_command_typed_before_a_resume_does_not_run_in_the_new_session() { + for fullscreen in [false, true] { + let home = Home::new(); + let (attaching, attach_seen) = std::sync::mpsc::channel(); + let (release_attach, release) = std::sync::mpsc::channel::<()>(); + let (shells, shell_seen) = std::sync::mpsc::channel::(); + let (compacting, compact_seen) = std::sync::mpsc::channel::<()>(); + let daemon = home.daemon(move |wire| { + wire.hello(&[ + "session.catalog", + "session.branches", + "session.permission.get", + "session.permission.update", + ]); + let mut usage = |_request: &Value| None; + let attach = wire.read("session.attach"); + let mut record = attach_record(&attach); + record["defaultBranch"] = json!({"branchId":"main","sequence":8}); + wire.reply(&attach, record); + loop { + let request = next_usage(wire, &mut usage); + match request["method"].as_str().unwrap_or_default() { + "session.catalog" => wire.reply( + &request, + json!({"sessions":[{"sessionId":"other","cwd":"/workspace", + "preview":"second conversation", + "model":{"providerId":"test","modelId":"model"}, + "updatedAt":9}]}), + ), + "session.branches" => { + wire.reply(&request, directory("main", &[("main", None)])) + } + "session.history" => { + let session = request["params"]["sessionId"].as_str().unwrap_or_default(); + wire.reply( + &request, + if session == "other" { + history(8, vec![said(3, "other conversation")]) + } else { + history(8, vec![said(3, "the first turn"), applied(4, "input-3")]) + }, + ); + } + "session.permission.get" => wire.reply( + &request, + json!({"version":1,"policy":policy("workspace-write")}), + ), + "session.permission.update" => wire.reply(&request, json!({"version":2})), + "session.attach" => { + assert_eq!(request["params"]["sessionId"], "other"); + let mut record = attach_record(&request); + record["defaultBranch"] = json!({"branchId":"main","sequence":8}); + attaching.send(()).unwrap(); + release.recv_timeout(PATIENCE).unwrap(); + wire.reply(&request, record); + } + "session.detach" => wire.reply(&request, json!({})), + "shell.run" => { + shells.send(request["params"].clone()).unwrap(); + wire.reply( + &request, + json!({"runId":request["params"]["runId"], + "status":"completed","exitCode":0,"output":"stale-output\n", + "truncated":false,"durationMs":1}), + ); + } + "session.context.compact" => { + assert_eq!(request["params"]["branchId"], "main"); + compacting.send(()).unwrap(); + wire.reply(&request, json!({"status":"completed"})); + } + other => panic!("unexpected {other}: {request}"), + } + } + }); + let mut command = home.command(); + command.arg(if fullscreen { + "--fullscreen" + } else { + "--scrollback" + }); + sized(&mut command, 120, 36); + let mut terminal = Terminal::resume_tui(command); + terminal.until("the first turn"); + terminal.until("test / model"); + terminal.write(b"/resume\r"); + terminal.until("second conversation"); + terminal.write(b"\r"); + attach_seen.recv_timeout(PATIENCE).unwrap(); + // The attachment's reply is held, so the interface still shows the + // Session the shell command is typed on. + terminal.write(b"!printf stale\r"); + terminal.until("Ctrl+C to interrupt"); + release_attach.send(()).unwrap(); + terminal.until("other conversation"); + // `/compact` on the attached Session is the boundary after the stale + // command: the daemon reads it whether that command ran or not, so an + // empty `shell.run` here is the refusal, not a race. + terminal.write(b"/compact\r"); + compact_seen.recv_timeout(PATIENCE).unwrap(); + assert!( + shell_seen.try_recv().is_err(), + "a shell command from the Session a resume left does not run in the new Session" + ); + home.kill(&terminal); + terminal.wait(); + daemon.join().unwrap(); + } +} + +/// A shell command left over from the Session `/new` left does not start a +/// Session at Home: the command names the Session it was typed in, and the +/// guard runs before Home can create one (design §14). +#[test] +fn tui_a_stale_shell_command_behind_new_does_not_start_a_session() { + for fullscreen in [false, true] { + let home = Home::new(); + let (attaching, attach_seen) = std::sync::mpsc::channel(); + let (release_attach, release) = std::sync::mpsc::channel::<()>(); + let (created, create_seen) = std::sync::mpsc::channel::(); + let daemon = home.daemon(move |wire| { + wire.hello(&[ + "session.catalog", + "session.branches", + "session.permission.get", + "session.permission.update", + ]); + let mut usage = |_request: &Value| None; + let attach = wire.read("session.attach"); + let mut record = attach_record(&attach); + record["defaultBranch"] = json!({"branchId":"main","sequence":8}); + wire.reply(&attach, record); + loop { + let request = next_usage(wire, &mut usage); + match request["method"].as_str().unwrap_or_default() { + "session.catalog" => wire.reply( + &request, + json!({"sessions":[{"sessionId":"other","cwd":"/workspace", + "preview":"second conversation", + "model":{"providerId":"test","modelId":"model"}, + "updatedAt":9}]}), + ), + "session.branches" => { + wire.reply(&request, directory("main", &[("main", None)])) + } + "session.history" => wire.reply( + &request, + history(8, vec![said(3, "the first turn"), applied(4, "input-3")]), + ), + "session.permission.get" => wire.reply( + &request, + json!({"version":1,"policy":policy("workspace-write")}), + ), + "session.permission.update" => wire.reply(&request, json!({"version":2})), + "session.attach" => { + assert_eq!(request["params"]["sessionId"], "other"); + let mut record = attach_record(&request); + record["defaultBranch"] = json!({"branchId":"main","sequence":8}); + attaching.send(()).unwrap(); + release.recv_timeout(PATIENCE).unwrap(); + wire.reply(&request, record); + } + "session.detach" => wire.reply(&request, json!({})), + "session.create" => { + created.send(request["params"].clone()).unwrap(); + wire.send(json!({"jsonrpc":"2.0","id":request["id"],"error":{ + "code":-32603,"message":"no Session was created"}})); + } + "provider.catalog" => wire.reply(&request, json!({})), + "shell.run" => panic!("a stale shell command runs at Home: {request}"), + other => panic!("unexpected {other}: {request}"), + } + } + }); + let mut command = home.command(); + command.arg(if fullscreen { + "--fullscreen" + } else { + "--scrollback" + }); + sized(&mut command, 120, 36); + let mut terminal = Terminal::resume_tui(command); + terminal.until("the first turn"); + terminal.until("test / model"); + terminal.write(b"/resume\r"); + terminal.until("second conversation"); + terminal.write(b"\r"); + attach_seen.recv_timeout(PATIENCE).unwrap(); + // The attachment's reply is held, so the interface still shows the + // Session `/new` is about to leave: this shell command belongs to it. + terminal.write(b"/new\r"); + terminal.write(b"!printf stale\r"); + terminal.until("Ctrl+C to interrupt"); + release_attach.send(()).unwrap(); + // The refusal is a `ShellDone` the interface draws; an unfixed command + // instead reaches `session.create` and shows its error there. + terminal.until("Shell: "); + assert!( + terminal + .transcript + .contains("The centre moved before the shell command ran"), + "the stale shell command is cancelled, not started at Home: {}", + terminal.transcript + ); + assert!( + create_seen.try_recv().is_err(), + "a shell command from the Session `/new` left starts no Session" + ); + home.kill(&terminal); + terminal.wait(); + daemon.join().unwrap(); + } +} + +/// A shell command typed on the Home screen `--resume` shows before its +/// attachment replies is Home's: once the reply lands, it does not run on the +/// resumed Session's default line (design §14). +#[test] +fn tui_a_launch_home_shell_command_does_not_run_in_the_resumed_session() { + for fullscreen in [false, true] { + let home = Home::new(); + let (attaching, attach_seen) = std::sync::mpsc::channel(); + let (release_attach, release) = std::sync::mpsc::channel::<()>(); + let (shells, shell_seen) = std::sync::mpsc::channel::(); + let (compacting, compact_seen) = std::sync::mpsc::channel::<()>(); + let daemon = home.daemon(move |wire| { + wire.hello(&["session.branches", "session.permission.get"]); + let mut usage = |_request: &Value| None; + loop { + let request = next_usage(wire, &mut usage); + match request["method"].as_str().unwrap_or_default() { + "session.attach" => { + let mut record = attach_record(&request); + record["defaultBranch"] = json!({"branchId":"line-1","sequence":8}); + record["sequence"] = json!(8); + attaching.send(()).unwrap(); + release.recv_timeout(PATIENCE).unwrap(); + wire.reply(&request, record); + } + "session.branches" => wire.reply( + &request, + directory("line-1", &[("main", None), ("line-1", Some("main"))]), + ), + "session.history" => wire.reply( + &request, + history( + 8, + vec![said(3, "resumed conversation"), applied(4, "input-3")], + ), + ), + "session.permission.get" => wire.reply( + &request, + json!({"version":1,"policy":policy("workspace-write")}), + ), + "shell.run" => { + shells.send(request["params"].clone()).unwrap(); + wire.reply( + &request, + json!({"runId":request["params"]["runId"], + "status":"completed","exitCode":0,"output":"stale-output\n", + "truncated":false,"durationMs":1}), + ); + } + "session.context.compact" => { + assert_eq!(request["params"]["branchId"], "line-1"); + compacting.send(()).unwrap(); + wire.reply(&request, json!({"status":"completed"})); + } + other => panic!("unexpected {other}: {request}"), + } + } + }); + let mut command = home.command(); + command.args([ + "tui", + if fullscreen { + "--fullscreen" + } else { + "--scrollback" + }, + "--resume", + "session", + ]); + sized(&mut command, 120, 36); + let mut terminal = Terminal::launch_tui(command); + attach_seen.recv_timeout(PATIENCE).unwrap(); + terminal.until("Welcome to DIM"); + // The screen is Home until the reply lands; this command is Home's. + terminal.write(b"!printf stale\r"); + terminal.until("Ctrl+C to interrupt"); + release_attach.send(()).unwrap(); + // The boundary row is drawn from the attachment's own projection. The + // stale command was queued before it, so `/compact` below is read only + // after that command was decided. + terminal.until("resumed session"); + // `/compact` is the boundary after the stale command, as in the + // `/resume` flow above. + terminal.write(b"/compact\r"); + compact_seen.recv_timeout(PATIENCE).unwrap(); + assert!( + shell_seen.try_recv().is_err(), + "a shell command typed on the launch Home does not run on the resumed line" + ); + 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..467636d71d 100644 --- a/crates/dimcode/tests/cli_flow/permission.rs +++ b/crates/dimcode/tests/cli_flow/permission.rs @@ -17,8 +17,13 @@ fn branch() -> Value { json!({"sessionId":"session","branchId":"main"}) } +/// A resumed launch writes the explicit preset on the line its attach reply +/// names, never on a line read from the directory before the attach: the +/// directory and the reply are one round trip apart (design §14). A refused +/// write ends the launch before the startup `--model` is adopted on any line +/// and before any turn runs. #[test] -fn tui_resume_requires_the_explicit_permission_before_attaching() { +fn tui_resume_writes_the_explicit_permission_on_the_attached_line() { for fullscreen in [false, true] { for leaf in [false, true] { for failure in ["unsupported", "read", "update"] { @@ -32,30 +37,88 @@ fn tui_resume_requires_the_explicit_permission_before_attaching() { methods.extend(PRESET_METHODS); } wire.hello(&methods); - if failure != "unsupported" { - let get = wire.read("session.permission.get"); - assert_eq!(get["params"], branch()); - if failure == "read" { - fail(wire, &get, "service_reloading"); - } else { - wire.reply( - &get, - json!({"version":7,"policy":policy("full-access", &["fixture-tool"], &["blocked"])}), - ); - let update = wire.read("session.permission.update"); - assert_eq!( - update["params"], - json!({"sessionId":"session","branchId":"main","expectedVersion":7, - "policy":policy("read-only", &["fixture-tool"], &["blocked"])}) - ); - fail(wire, &update, "permission_failed"); - } + if failure == "unsupported" { + assert_eq!( + wire.trailing_request(), + None, + "a daemon without the preset methods ends the launch before it attaches" + ); + return; } + wire.2 = true; + let attach = wire.read_any(); assert_eq!( - wire.trailing_request(), - None, - "a refused explicit permission must not adopt, attach, open a UI or submit" + attach["method"], + json!("session.attach"), + "the launch attaches before it adopts --model or writes the preset's line" ); + let mut record = attach_record(&attach); + record["defaultBranch"] = json!({"branchId":"line-1","sequence":5}); + wire.reply(&attach, record); + // The attach's own read of the line comes first; the write + // the launch asked for reads it again. + let mut reads = 0; + loop { + let request = wire.read_any(); + match request["method"].as_str().unwrap_or_default() { + "session.history" => wire.reply( + &request, + json!({"events":[],"through":5,"nextAfter":5,"done":true}), + ), + "session.permission.get" => { + assert_eq!( + request["params"], + json!({"sessionId":"session","branchId":"line-1"}), + "the preset is written on the attach reply's line" + ); + reads += 1; + if failure == "read" && reads == 2 { + fail(wire, &request, "service_reloading"); + break; + } + wire.reply( + &request, + json!({"version":7,"policy":policy("full-access", &["fixture-tool"], &["blocked"])}), + ); + } + "session.permission.update" => { + assert_eq!( + request["params"], + json!({"sessionId":"session","branchId":"line-1","expectedVersion":7, + "policy":policy("read-only", &["fixture-tool"], &["blocked"])}) + ); + fail(wire, &request, "permission_failed"); + break; + } + "session.model.update" => panic!( + "a refused preset must not adopt the startup model on any line: {request}" + ), + "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"}}})), + "ui.open" => { + wire.reply(&request, json!({"uiId":"ui-1","token":"token-1"})) + } + "account.providers" => wire.reply(&request, json!([])), + "provider.list" => wire.reply(&request, json!({"providers":[]})), + other => panic!("unexpected {other}: {request}"), + } + } + // The refused write ends the launch: no model is adopted + // and no turn runs. + while let Some(line) = wire.trailing_request() { + let request: Value = serde_json::from_str(&line).unwrap(); + assert_ne!( + request["method"], + json!("session.model.update"), + "a refused preset must not adopt the startup model on any line" + ); + assert_ne!( + request["method"], + json!("session.submit"), + "a refused explicit permission must not submit" + ); + } }); let mut command = home.command(); command.args(["--permission", "read-only", "--model", "replacement"]); @@ -77,6 +140,67 @@ fn tui_resume_requires_the_explicit_permission_before_attaching() { } } +/// A resumed launch registers its leaf only once the launch preset is in +/// force: another client cannot see the interface online, or address it for +/// approvals, while the resumed line still carries its old policy +/// (design §14). +#[test] +fn tui_resume_registers_its_leaf_after_the_launch_preset_is_applied() { + let home = Home::new(); + let (opened, open_seen) = std::sync::mpsc::channel(); + let daemon = home.daemon(move |wire| { + wire.hello(&[ + "ui.leaf.2", + "session.permission.get", + "session.permission.update", + ]); + wire.2 = true; + let attach = wire.read_any(); + assert_eq!(attach["method"], json!("session.attach")); + let mut record = attach_record(&attach); + record["defaultBranch"] = json!({"branchId":"line-1","sequence":5}); + wire.reply(&attach, record); + let update = loop { + let request = wire.read_any(); + match request["method"].as_str().unwrap_or_default() { + "session.history" => wire.reply( + &request, + json!({"events":[],"through":5,"nextAfter":5,"done":true}), + ), + "session.permission.get" => wire.reply( + &request, + json!({"version":7,"policy":policy("full-access", &[], &[])}), + ), + "session.permission.update" => break request, + "ui.open" => { + panic!("the leaf registers before the launch preset is applied: {request}") + } + "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"}}})) + } + other => panic!("unexpected {other}: {request}"), + } + }; + assert_eq!(update["params"]["policy"]["preset"], json!("read-only")); + wire.reply(&update, json!({"version":8})); + let open = wire.read("ui.open"); + wire.reply(&open, json!({"uiId":"ui-1","token":"token-1"})); + opened.send(()).unwrap(); + }); + let mut command = home.command(); + command.args(["--permission", "read-only"]); + sized(&mut command, 100, 32); + let mut terminal = Terminal::resume_tui(command); + open_seen.recv_timeout(PATIENCE).unwrap(); + home.kill(&terminal); + terminal.wait(); + daemon.join().unwrap(); +} + /// One submitted turn that completes without tool calls. fn quiet_turn(wire: &mut Wire) { let submit = wire.read("session.submit"); @@ -94,9 +218,7 @@ fn line_permission_controls_keep_tool_lists_report_conflicts_and_reject_unknown_ wire.hello(&PRESET_METHODS); wire.created(); let mut current = policy("read-only", &["read"], &["blocked"]); - let read = wire.read("session.permission.get"); - wire.reply(&read, json!({"version":1,"policy":current})); - wire.attached(); + wire.attached_with_policy(json!({"version":1,"policy":current})); let read = wire.read("session.permission.get"); wire.reply(&read, json!({"version":1,"policy":current})); let write = wire.read("session.permission.update"); @@ -129,7 +251,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"); @@ -351,6 +473,10 @@ fn permission_flag_selects_the_new_and_resumed_preset_with_version_checks() { let home = Home::new(); let daemon = home.daemon(|wire| { wire.hello(&PRESET_METHODS); + let attach = wire.read("session.attach"); + let mut record = attach_record(&attach); + record["defaultBranch"] = json!({"branchId":"main","sequence":8}); + wire.reply(&attach, record); let get = wire.read("session.permission.get"); assert_eq!(get["params"], branch()); wire.reply( @@ -378,7 +504,7 @@ fn permission_flag_selects_the_new_and_resumed_preset_with_version_checks() { &update, json!({"version":9,"policy":current}), ); - wire.attached(); + wire.resumed_on("main", 8); quiet_turn(wire); }); let output = home @@ -402,15 +528,37 @@ fn permission_flag_selects_the_new_and_resumed_preset_with_version_checks() { ); assert!(String::from_utf8_lossy(&output.stderr).contains("permission: full-access")); + // The resumed preset lands on the line the attach reply names, not on the + // line a directory read reported before it (design §14). let home = Home::new(); let daemon = home.daemon(|wire| { - wire.hello(&PRESET_METHODS); + wire.hello(&[ + "session.branches", + PRESET_METHODS[0], + PRESET_METHODS[1], + ]); + let branches = wire.read("session.branches"); + wire.reply( + &branches, + json!({"defaultBranchId":"main","branches":[ + {"branchId":"main","state":"open","head":8}, + {"branchId":"line-1","parentBranchId":"main","branchPoint":1,"state":"open","head":5}]}), + ); + let attach = wire.read("session.attach"); + let mut record = attach_record(&attach); + record["defaultBranch"] = json!({"branchId":"line-1","sequence":5}); + wire.reply(&attach, record); let get = wire.read("session.permission.get"); + assert_eq!( + get["params"], + json!({"sessionId":"session","branchId":"line-1"}), + "the write follows the attach reply's line, not the directory's" + ); wire.reply( &get, json!({"version":2,"policy":policy("read-only", &[], &[])}), ); - wire.attached(); + wire.resumed_on("line-1", 5); quiet_turn(wire); }); let output = home @@ -573,12 +721,9 @@ fn interactive_approvals_list_switch_and_edit_rules_with_version_checks() { methods.extend(RULE_METHODS); wire.hello(&methods); wire.created(); - let get = wire.read("session.permission.get"); - wire.reply( - &get, + wire.attached_with_policy( json!({"version":0,"policy":policy("workspace-write", &[], &["blocked-tool"])}), ); - wire.attached(); let state = |wire: &mut Wire, version: u64, preset: &str| { let get = wire.read("session.permission.get"); assert_eq!(get["params"], branch()); @@ -700,20 +845,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 +911,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 +919,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 +1195,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 +1210,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 +1224,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/protocol_version.rs b/crates/dimcode/tests/cli_flow/protocol_version.rs index a369eb2a6a..3c7f17f094 100644 --- a/crates/dimcode/tests/cli_flow/protocol_version.rs +++ b/crates/dimcode/tests/cli_flow/protocol_version.rs @@ -403,16 +403,17 @@ fn a_resumed_session_of_a_newer_protocol_names_both_versions_and_offers_no_retry let home = Home::new(); let daemon = home.daemon(|wire| { wire.hello(&["session.permission.get", "session.permission.update"]); - let get = wire.read("session.permission.get"); + let attach = wire.read("session.attach"); + assert_eq!(attach["params"]["sessionId"], json!("session")); refuse_session_version( wire, - &get, + &attach, "Session was created by protocol version 5; this connection speaks 4", ); assert_eq!( wire.trailing_request(), None, - "a refused Session must not be adopted, attached or submitted" + "a refused Session must not be adopted, written to or submitted" ); }); let mut command = home.command(); diff --git a/crates/dimcode/tests/cli_flow/startup.rs b/crates/dimcode/tests/cli_flow/startup.rs index 75bd316299..51a9f39b2a 100644 --- a/crates/dimcode/tests/cli_flow/startup.rs +++ b/crates/dimcode/tests/cli_flow/startup.rs @@ -844,7 +844,22 @@ fn resume_startup_is_adopted_or_explicitly_rejected_before_input_in_every_client let request = wire.read_any(); let update = if request["method"] == "session.attach" { wire.reply(&request, attach_record(&request)); - wire.read("session.model.update") + // The launch attaches before it adopts, and the attach + // opens the UI and the conversation's window first. + loop { + let next = wire.read_any(); + match next["method"].as_str().unwrap_or_default() { + "ui.open" => { + wire.reply(&next, json!({"uiId":"ui-1","token":"token-1"})) + } + "session.history" => wire.reply( + &next, + json!({"events":[],"through":8,"nextAfter":8,"done":true}), + ), + "session.model.update" => break next, + other => panic!("unexpected {other}: {next}"), + } + } } else { assert_eq!(request["method"], "session.model.update"); request diff --git a/crates/dimcode/tests/cli_flow/tasks.rs b/crates/dimcode/tests/cli_flow/tasks.rs index 51b41a8646..e32a741ba2 100644 --- a/crates/dimcode/tests/cli_flow/tasks.rs +++ b/crates/dimcode/tests/cli_flow/tasks.rs @@ -1179,7 +1179,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"); @@ -1590,7 +1590,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/crates/dimcode/tests/cli_tui_flow.rs b/crates/dimcode/tests/cli_tui_flow.rs index ca5f1e4a15..15efe28205 100644 --- a/crates/dimcode/tests/cli_tui_flow.rs +++ b/crates/dimcode/tests/cli_tui_flow.rs @@ -2017,6 +2017,162 @@ fn a_resumed_session_draws_the_adopted_model_and_effort() { daemon.join().unwrap(); } +/// The startup `--model` lands on the line the attach reply names: a move +/// between attach and the update must not write it on another line. +#[test] +fn a_resumed_tui_adopts_the_startup_model_on_the_attached_line() { + let home = Home::new(); + let daemon = home.daemon(|wire| { + wire.hello(&[]); + let attach = wire.read("session.attach"); + let mut record = attach_record(&attach); + record["defaultBranch"] = json!({"branchId":"line-1","sequence":5}); + wire.reply(&attach, record); + let history = wire.read("session.history"); + wire.reply( + &history, + json!({"events":[configured_event(4, "line-model", json!({}))], + "through":5,"nextAfter":5,"done":true}), + ); + let update = wire.read("session.model.update"); + assert_eq!( + update["params"]["branchId"], + json!("line-1"), + "the startup model follows the attach reply's line" + ); + assert_eq!(update["params"]["modelId"], json!("replacement")); + wire.reply( + &update, + json!({"outcome":"adopted","model":{"providerId":"test","modelId":"replacement"}}), + ); + wire.no_context(); + let providers = wire.read("account.providers"); + wire.reply(&providers, json!([])); + wire.hold(); + }); + let mut command = home.command(); + command.args(["--model", "replacement"]); + let mut terminal = Terminal::resume_tui(command); + terminal.until("test / line-model"); + home.kill(&terminal); + terminal.wait(); + daemon.join().unwrap(); +} + +/// The capability declaration a configuration states for `model_id`. +fn effort_snapshot(model_id: &str, efforts: &[&str]) -> Value { + let mut capabilities = dim_agent_types::ModelCapabilities::with_limits(64_000, 2_048); + capabilities.reasoning = true; + json!({"target":{"providerId":"test","modelId":model_id}, + "capabilities":capabilities, + "reasoning":{"supported":true,"effortOptions":efforts}}) +} + +/// A resumed Session folds the configuration of the line its cursor names: the +/// attach reply's model is the root's (design §14), so a Session whose +/// conversation is on a line shows the configuration that line adopted, read +/// through `session.model.get` at the reply's cursor, and only the root takes +/// the reply's. The reply's cursor stays the shown line's, and the directory +/// answers only for a server that does not carry the field. +#[test] +fn a_resumed_line_mode_session_folds_the_default_branchs_cursor() { + for (line, cursor, listed) in [ + ("main", 8, "main"), + ("line-1", 5, "line-1"), + ("line-1", 5, "main"), + ] { + let home = Home::new(); + let daemon = home.daemon(move |wire| { + wire.hello(&[ + "session.branches", + "session.history.display", + "session.history.detail", + "session.history.display.tail", + "session.history.display.transcript", + "session.model.get", + ]); + let branches = wire.read("session.branches"); + let mut entries = vec![json!({"branchId":"main","state":"open","head":8})]; + if line != "main" { + entries.push(json!({"branchId":line,"parentBranchId":"main","branchPoint":1,"state":"open","head":8})); + } + wire.reply(&branches, json!({"defaultBranchId":listed,"branches":entries})); + let attach = wire.read("session.attach"); + let mut record = attach_record(&attach); + record["defaultBranch"] = json!({"branchId":line,"sequence":cursor}); + record["capabilitySnapshot"] = effort_snapshot("model", &["low", "high"]); + wire.reply(&attach, record); + let update = wire.read("session.model.update"); + assert_eq!( + update["params"]["branchId"], + json!(line), + "the startup model follows the attach reply's line" + ); + assert_eq!(update["params"]["modelId"], json!("replacement")); + wire.reply( + &update, + json!({"outcome":"adopted","model":{"providerId":"test","modelId":"replacement"}}), + ); + let window = wire.read("session.history.display"); + assert_eq!(window["params"]["branchId"], json!(line)); + wire.reply( + &window, + json!({"items":[],"through":cursor,"nextBefore":1,"nextAfter":cursor,"done":true}), + ); + if line != "main" { + let read = wire.read("session.model.get"); + assert_eq!(read["params"]["branchId"], json!(line)); + assert_eq!(read["params"]["through"], json!(cursor)); + assert!( + read["params"].get("before").is_none(), + "a line's configuration is read at one cutoff, not paged out of its history" + ); + wire.reply( + &read, + json!({"branchId":line,"through":cursor, + "configuration":{"model":{"providerId":"test","modelId":"line-model"}, + "capabilitySnapshot":effort_snapshot("line-model", &["none", "minimal"])}}), + ); + } + let idle = wire.read("session.idle"); + assert_eq!(idle["params"]["branchId"], json!(line)); + wire.reply(&idle, json!({"sequence":cursor})); + loop { + let request = wire.read_any(); + match request["method"].as_str().unwrap() { + "session.history" => { + let through = request["params"]["through"].as_u64().unwrap_or(cursor); + wire.reply( + &request, + json!({"events":[],"through":through,"nextAfter":through,"done":true}), + ); + } + "session.history.display" => { + let through = request["params"]["after"].as_u64().unwrap_or(cursor); + wire.reply( + &request, + json!({"items":[],"through":through,"nextAfter":through,"done":true}), + ); + } + other => panic!("unexpected {other}: {request}"), + } + } + }); + let mut command = home.command(); + command.args(["--resume", "session", "--model", "replacement"]); + let mut terminal = Terminal::launch(command); + terminal.editor(); + terminal.write(b"/effort\r"); + terminal.until(match line { + "main" => "Reasoning effort choices: low, high", + _ => "Reasoning effort choices: none, minimal", + }); + home.kill(&terminal); + terminal.wait(); + daemon.join().unwrap(); + } +} + /// An adoption written by another client reaches the label as it arrives. #[test] fn another_clients_adoption_redraws_the_model_label() { @@ -5743,7 +5899,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/support/cli_harness.rs b/crates/dimcode/tests/support/cli_harness.rs index 66409ba0f1..860f9e6d45 100644 --- a/crates/dimcode/tests/support/cli_harness.rs +++ b/crates/dimcode/tests/support/cli_harness.rs @@ -383,14 +383,48 @@ impl Wire { pub fn attached(&mut self) { let attach = self.read("session.attach"); self.reply(&attach, attach_record(&attach)); + self.resumed_on("main", 8); + } + /// The attach reply, then the policy read of the line it names and the + /// window, pending-question and idle reads that follow: a Session's first + /// frame names one line, and the reply is where it comes from + /// (design §14). + pub fn attached_with_policy(&mut self, policy: Value) { + let attach = self.read("session.attach"); + self.reply(&attach, attach_record(&attach)); + let get = self.read("session.permission.get"); + assert_eq!( + get["params"], + json!({"sessionId":"session","branchId":"main"}) + ); + self.reply(&get, policy); + self.resumed_on("main", 8); + } + /// The window, pending-question and idle reads a resumed Session makes on + /// `branch`, after its attach reply. + pub fn resumed_on(&mut self, branch: &str, through: u64) { let history = self.read("session.history"); + assert_eq!(history["params"]["branchId"], branch); + // A line's window carries the configuration it adopted; the root takes + // the attach reply's model instead. + let events = if branch == "main" { + json!([]) + } else { + json!([configured_event(through - 1, "line-model", json!({}))]) + }; self.reply( &history, - json!({"events":[],"through":8,"nextAfter":8,"done":true}), + json!({"events":events,"through":through,"nextAfter":through,"done":true}), + ); + let question = self.read("session.question.pending"); + assert_eq!(question["params"]["branchId"], branch); + self.reply( + &question, + json!({"branchId":branch,"through":through,"batches":[],"next":null}), ); - self.no_pending_questions(8); let idle = self.read("session.idle"); - self.reply(&idle, json!({"sequence":8})); + assert_eq!(idle["params"]["branchId"], branch); + self.reply(&idle, json!({"sequence":through})); } pub fn no_pending_questions(&mut self, through: u64) { let request = self.read("session.question.pending"); @@ -855,6 +889,64 @@ impl Terminal { tail.find(expected).map(|index| index + expected.len()) }); } + /// The rows the interface painted from their first column since transcript + /// offset `from`, in the order it painted them. The live region is + /// repainted in place, so a row it drew before a change is still in the + /// transcript; a frame paints a row as one cursor move to its first column + /// and the row's text, and this reads those paints instead of every write + /// the transcript ever held. + pub fn painted_rows(&self, from: usize) -> Vec { + let mut rows = Vec::new(); + let mut row: Option = None; + let mut chars = self.transcript[from..].chars(); + while let Some(c) = chars.next() { + if c == '\u{1b}' { + match chars.next() { + Some('[') => { + let mut params = String::new(); + let final_byte = loop { + match chars.next() { + Some(c) if ('\u{40}'..='\u{7e}').contains(&c) => break Some(c), + Some(c) => params.push(c), + None => break None, + } + }; + // Styling splits a row into runs that still read as one; + // anything else (an erase, a move) ends the row. + if final_byte == Some('m') { + continue; + } + rows.extend(row.take()); + if final_byte == Some('H') && (params.is_empty() || params.ends_with(";1")) + { + row = Some(String::new()); + } + } + Some(']') | Some('P') => { + let mut previous = '\0'; + for c in chars.by_ref() { + if c == '\u{07}' || (previous == '\u{1b}' && c == '\\') { + break; + } + previous = c; + } + } + _ => {} + } + continue; + } + if c == '\r' || c == '\n' { + rows.extend(row.take()); + continue; + } + if let Some(row) = &mut row { + row.push(c); + } + } + rows.extend(row); + rows.retain(|row| !row.is_empty()); + rows + } /// Waits for text on the terminal screen at a completed synchronized frame. pub fn until_visible(&mut self, expected: &str) { let mut size = unsafe { std::mem::zeroed::() }; diff --git a/docs/design/cli-commands.md b/docs/design/cli-commands.md index 4bd10a9128..a899a0db5d 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). @@ -3152,7 +3152,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; @@ -3311,8 +3311,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/clients.md b/docs/design/clients.md index 613221a000..2b6bec2180 100644 --- a/docs/design/clients.md +++ b/docs/design/clients.md @@ -50,7 +50,7 @@ Dashed boxes are outside this repository (Desktop) or not implemented (remote de | --- | --- | | Wire protocol v4: framing, `hello` and feature advertisement, notifications | `crates/dim-app-server/src/protocol.rs` (no prose reference exists, §4 item 2); [App Server README](../../crates/dim-app-server/README.md) | | Session methods versus management methods, and which entry is served which | [Session boundary](contracts/session-boundary.md) (A.3 entries), [management methods](appserver/management-methods.md) | -| Reading a Session: `session.attach`, then `session.history` up to a fixed head, then live `session.event`, `session.state`, `session.model.progress`; clients fold these themselves. The attach reply carries that Session's `SessionInfo`, whose `model` follows the Session's latest adopted configuration, so a client that opens a known Session takes the model from it and reads no catalog; `session.summaries` items still report the creation model until [#795](https://github.com/arcships/dim/issues/795) lands. A reload leaves the title fields absent and `running` false, and the notices that follow correct them. The `session.create` and `session.attach` replies also carry `modelPreferences`, the preferences the Session's adopted configuration sends, derived from it and absent when it carries none; `session.summaries` items do not carry it. The attach reply's `sequence` stays the root's cutoff, and the line the conversation is on travels beside it as `defaultBranch {branchId, sequence}`; the cursor is that reply's alone, and `session.summaries` items carry none ([timeline branches §14](timeline-branches.md#14-clients)) | [Session access](contracts/session-access.md), [CLI commands](cli-commands.md); triage of [#276](https://github.com/arcships/dim/issues/276) | +| Reading a Session: `session.attach`, then `session.history` up to a fixed head, then live `session.event`, `session.state`, `session.model.progress`; clients fold these themselves. The attach reply carries that Session's `SessionInfo`, whose `model` is the root's adopted configuration, so a client that opens a known Session on the root takes the model from it and reads no catalog; a conversation on a line takes that line's own configuration through `session.model.get {sessionId, branchId, through}` at the reply's cursor ([timeline branches §14](timeline-branches.md#14-clients)); `session.summaries` items still report the creation model until [#795](https://github.com/arcships/dim/issues/795) lands. A reload leaves the title fields absent and `running` false, and the notices that follow correct them. The `session.create` and `session.attach` replies also carry `modelPreferences`, the preferences the root's adopted configuration sends, derived from it and absent when it carries none; `session.summaries` items do not carry it. The attach reply's `sequence` stays the root's cutoff, and the line the conversation is on travels beside it as `defaultBranch {branchId, sequence}`; the cursor is that reply's alone, and `session.summaries` items carry none ([timeline branches §14](timeline-branches.md#14-clients)) | [Session access](contracts/session-access.md), [CLI commands](cli-commands.md); triage of [#276](https://github.com/arcships/dim/issues/276) | | Broadcast notices that are not Timeline facts (`session.notice`, e.g. titles) | [Session notices](appserver/session-notices.md) | | Approvals and questions: `approval.request` / `cancelled` / `resolved`; a question is a pending `ask_user` call answered by `session.question.respond` | [ADR 003](../adr/003-approval-scope.md), [Questions](plugins/Questions.md) | | MCP App views: the document a tool declares (`session.mcp.app.widget`), a view's tool call (`session.mcp.app.call`), a view's message through `session.submit` | [MCP Apps](appserver/mcp-apps.md) | @@ -179,9 +179,11 @@ absence from a missing start event in the window: | Pending inputs | Unconsumed Queue/Steer input identities, modes and display content, excluding deleted inputs. | Ended branches remain directory entries but have no actionable inventories; clients read their -transcript and details only when selected. Configuration updates use the attach configuration +transcript and details only when selected. On the root, configuration updates use the attach configuration position independently of the transcript cursor, so a buffered configuration between attach and -the window head is still adopted. +the window head is still adopted; a conversation on a line reads its adopted configuration through +`session.model.get` at the window head, and takes the read's own committed cutoff as the watermark, so +a configuration buffered above it still applies and a pre-window adoption is not lost. The active-turn row and the last four rows raise requirements to InputQueue, Questions, BackgroundExec and Collaboration, plus Loop for current execution state, through the App Server. Each read must identify the branch and @@ -232,7 +234,7 @@ Include a turn longer than the page budget, an empty visible page, a question/task/delegation/input started before the window, a terminal event while state is loading, member switching, reconnect and a transport-oversized batch. Also verify that `/lines` lists a branch created before the window, line-mode -`/effort` uses the attach model, and an old ACP `forkAtTurn` anchor still resolves. +`/effort` uses the shown line's model, and an old ACP `forkAtTurn` anchor still resolves. `/goal` reads `session.goal.get` before choosing a command and after its write; a successful Goal read must not be discarded because the transcript failed, nor may a partial transcript decide whether a goal exists. Retrying a transcript never changes other branches into diff --git a/docs/design/plugins/Tui.md b/docs/design/plugins/Tui.md index 7472045f01..9b5b0620c8 100644 --- a/docs/design/plugins/Tui.md +++ b/docs/design/plugins/Tui.md @@ -458,6 +458,20 @@ 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 +the attach reply's `defaultBranch`, 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 with that line's own model, permission and usage in the top bar, +and the method's refusal is drawn in the panel on the line that raised it 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/design/timeline-branches.md b/docs/design/timeline-branches.md index f636b2df77..0ab9b4c138 100644 --- a/docs/design/timeline-branches.md +++ b/docs/design/timeline-branches.md @@ -665,6 +665,18 @@ Session never changes it, while `running` and `updatedAt` follow the default bra `updatedAt` in its own transaction from the new default's latest activity, and the switch itself counts as none, so an idle move never leaves the row recent by the line the Session left. +The reply's `model`, `modelPreferences` and `capabilitySnapshot` stay the root's adopted configuration, the watermark a +Session on its root has always read. A client that follows the move pairs the configuration with the cursor instead of +mixing the two: it takes the configuration of the line the cursor names through +`session.model.get {sessionId, branchId, through}`, so a Session whose conversation is on a line shows the model that +line adopted at or below its cursor, and the reply's record seeds the root alone. The read answers the line's own +configuration with its own committed cutoff, so it works when a display transcript omits `context/configured` and a +bounded window begins after the adoption; that cutoff is the watermark a later configuration must pass. A server that +cannot answer the read does not name that line's configuration, and its attach reply is the root's, so no client shows +the root's model for a line. A reply that +carries no `defaultBranch` names the root, because a server without the field cannot move the default branch, so +its record is the Session's one model and every client keeps using it. + The directory read performs no history I/O. Its display fields are null or absent. `session.branch.get {sessionId, branchId}` (v3, separately listed in `hello.features`) reads one line's directory record and display fields: diff --git a/docs/design/web-workspace.md b/docs/design/web-workspace.md index 9ad35687cb..abb2314aad 100644 --- a/docs/design/web-workspace.md +++ b/docs/design/web-workspace.md @@ -219,7 +219,7 @@ The Web workspace keeps the default branch's transcript in the center and follow | Derived data | `lines.ts` keeps directory metadata, not historical input identities. Unknown message counts remain absent. `projection.ts` owns visible rows and live controls. `stores/chat.ts` keeps each opened window’s fixed head, backward cursor and in-flight live queue. | | Actions | `session.branch_create {parentBranchId, at, prompt}`, `session.branch_end {branchId}`, `session.branch_set_default {branchId}` (continue from here), `session.submit`/`session.stop` with the line's `branchId`; approvals use the request's `branchId` | | Points | A user message's cut is its sequence minus one; a line's end is its newest `turn-end`. `session.branch_create` remains the validator; its refusal is shown in the dialog or line tab | -| Switching | Opening a line adds or activates a tab; closing a tab does not end the line; the center shows the default branch, which `session.branches` reports as `defaultBranchId`, and `session.branch_set_default` changes it. The root and that line are the two that can open a line, so the Lines tree marks both | +| Switching | Opening a line adds or activates a tab, the root included while another line is the default branch, so the root's own transcript and pending approvals and questions stay reachable without moving the Session back; closing a tab does not end the line; the center shows the default branch, which `session.branches` reports as `defaultBranchId`, and `session.branch_set_default` changes it. A move reads the new centre's window before the center changes hands, so the transcript on screen, its actions and the line they name change together, and a read that fails reports the failure instead of showing the outgoing transcript. The root and that line are the two that can open a line, so the Lines tree marks both | | Errors | `branch_missing`, `branch_ended`, `input_blocked`, an invalid cut and a disabled Branch tool are shown at the action that raised them; an ended line is read-only | | State | Line tabs are per Session and live in `stores/ui.ts`; the tree is read from the existing directory on reload and reconnect. No storage format is added | @@ -232,7 +232,9 @@ with `session.question.pending` and current execution/output offsets with `sessi window's cutoff. Lists use their own keyset continuation and retain that cutoff. Read current Goal state through `session.goal.get`; refresh it after Goal commands or relevant live input/deletion facts. The browser no longer parses Goal blocks or keeps historical Goal inputs. The attach reply supplies -the current model; a historical configuration in the window cannot overwrite it. +the root's model; a centre on a line reads the model that line adopted at the window's cutoff through +`session.model.get`, because the display transcript omits the fact and the reply's record belongs +to the root ([timeline branches §14](timeline-branches.md#14-clients)). Questions on unopened branches are restored at their directory heads without reading transcripts. Live question terminals update those control states. Directory discovery and background branch notices @@ -1021,6 +1023,7 @@ switches it, so a missing or unknown stored value means `steer`. | Combined draft | The recalled messages in queue order, then the draft that was typed, each message keeping its own content in the order it was written: a text run stays where it stood and an image keeps the place it held between text runs, as the TUI's inline token does. Recalled text goes ahead of the typed text through the same separator rule the TUI uses: a newline before a recalled message when the draft there does not end a line, one between two adjacent text blocks, and one after the message when typed text follows | | Recalled images | A recalled message's stored images keep the draft offset they stood at and are sent with it as their existing file references, the text around them split at that offset; the draft's own pasted or dropped files are uploaded as usual and follow. Editing the draft moves an image with the text it stood between, and an inserted `@` file is linked within the run of text it belongs to, so a link never straddles an image. A recalled message goes in as one insertion, so an image already in the draft moves with the words it stood between, and an edit during a submit only moves offsets: the accepted message still recognizes the images it took, so text typed while it is out goes out without them. Images at one offset are ordered by the gesture that recalled them: a later gesture's images come first in queue order, so an image-only message takes its place ahead of an image-only draft, while an image ending an earlier message of the same gesture keeps its place ahead of the next one | | Failed stop | Nothing is submitted: the whole combined draft stays in the composer with the reason, and the withdrawals that already went are not repeated | +| Moved centre | The gesture belongs to the line it started on. If the centre moves before it finishes, nothing is submitted and the whole combined draft stays in the composer with the reason; the draft is never written to the line the centre moved to | | Guards | An empty draft with nothing held is a no-op. While that stop is out, no other action sends anything and the ordinary Stop is unavailable, because the gesture owns that stop; a second trigger sends no second stop: one reply decides one submit. A command or `@` menu open takes `Ctrl+Enter` as Enter itself, and text composition (IME) never reaches the gesture | | Destination | After a submit during a run the composer says where it went, `Sent into the running turn` or `Held for the next turn`, and clears the line when the run ends. A held message's row is the queue strip's, not a second notice | | Preference | `Appearance` → `Send during a run`, saved in this browser beside the theme and font size, applying immediately. Browser storage that refuses the write keeps the choice for this page and says it will not survive a reload | diff --git a/docs/zh/design/cli-commands.md b/docs/zh/design/cli-commands.md index d81c3e3af1..2901ddc641 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` 中的账号视图保持可用。 @@ -1869,7 +1869,7 @@ permission: read-only > Fix the build Assistant: ... -[permission] main branch preset: workspace-write <- 由其他客户端修改 +[permission] preset: workspace-write <- 由其他客户端修改 ``` 两种 TUI 模式都在输入框下方绘制实时权限页脚,不带 `AGENT` 前缀;预设、颜色、本地化快捷键提示与 @@ -1935,7 +1935,7 @@ Session 创建配置 --> main 当前策略 --分支点--> 子分支策略 ### `/permissions` `/permissions` 是两种 TUI 模式下可见的菜单入口;`/approvals` 和 `/approval` 作为兼容别名打开同一组 -预设选择器。选择作用于 `main`,每次更新使用当前完整策略与版本,保留工具列表。 +预设选择器。选择作用于 Session 的默认分支,每次更新使用当前完整策略与版本,保留工具列表。 保存失败既不改变记住的选择,也不回退到其他预设。 Process isolation 行链接到 Settings 的进程隔离控件;Esc 返回本面板并保持该行的焦点。 diff --git a/docs/zh/design/clients.md b/docs/zh/design/clients.md index d311711c9f..f494af4dc3 100644 --- a/docs/zh/design/clients.md +++ b/docs/zh/design/clients.md @@ -50,7 +50,7 @@ flowchart TB | --- | --- | | 线路协议 v4:分帧、`hello` 与功能声明、通知 | `crates/dim-app-server/src/protocol.rs`(没有文字版参考,见 §4 第 4 条);[App Server README](../../../crates/dim-app-server/README.md) | | Session 方法与管理方法之分,以及每种入口提供哪些方法 | [Session 边界](contracts/session-boundary.md)(A.3 入口)、[管理方法](../../design/appserver/management-methods.md) | -| 读取 Session:先 `session.attach`,再按固定的头部读 `session.history`,然后接收实时的 `session.event`、`session.state`、`session.model.progress`;由客户端自己折叠。attach 的回复携带该 Session 的 `SessionInfo`,其中 `model` 取自该 Session 最近采纳的配置,而 `session.summaries` 的条目在 [#795](https://github.com/arcships/dim/issues/795) 完成前仍报告创建时的模型,因此打开已知 Session 的客户端从它取模型,不读目录;重载期间标题字段缺失、`running` 为 false,随后的通知将其更正 | [Session 访问](contracts/session-access.md)、[CLI 命令](cli-commands.md);[#276](https://github.com/arcships/dim/issues/276) 的处理结论 | +| 读取 Session:先 `session.attach`,再按固定的头部读 `session.history`,然后接收实时的 `session.event`、`session.state`、`session.model.progress`;由客户端自己折叠。attach 的回复携带该 Session 的 `SessionInfo`,其中 `model` 是根的采纳配置:打开已知 Session 的根对话时客户端从它取模型,不读目录;对话在线上时,取该线自己的配置,经 `session.model.get {sessionId, branchId, through}` 在回复的游标处读取([timeline branches §14](timeline-branches.md#14-clients)),而 `session.summaries` 的条目在 [#795](https://github.com/arcships/dim/issues/795) 完成前仍报告创建时的模型;重载期间标题字段缺失、`running` 为 false,随后的通知将其更正 | [Session 访问](contracts/session-access.md)、[CLI 命令](cli-commands.md);[#276](https://github.com/arcships/dim/issues/276) 的处理结论 | | 不属于 Timeline 事实的广播通知(`session.notice`,例如标题) | [Session 广播通知](appserver/session-notices.md) | | 审批与提问:`approval.request` / `cancelled` / `resolved`;提问是一次未完成的 `ask_user` 调用,用 `session.question.respond` 回答 | [ADR 003](../adr/003-approval-scope.md)、[Questions](plugins/Questions.md) | | 查看 Session 的界面:UI 登记处,终端界面作为 UI 叶子(`ui.open`、`ui.attach`、`ui.status`) | [Tui §3.6](../../design/plugins/Tui.md#36-ui-registry-and-ui-leaves) | diff --git a/docs/zh/design/timeline-branches.md b/docs/zh/design/timeline-branches.md index 3d974f8c76..88728b8f3e 100644 --- a/docs/zh/design/timeline-branches.md +++ b/docs/zh/design/timeline-branches.md @@ -596,6 +596,8 @@ WorkspaceTools 不变。 **旧连接上的默认分支。** 移动现在已能经 RPC 触达,但跟随它的客户端随后才到,所以现有客户端依赖的每个字段和行为都保持旧含义,新含义经新字段到达。v1 连接的事件投影只带根(`connection/subscription.rs` 的 `project` 与 v1 分支监视),因此在该连接上,省略 `branchId` 仍然指向根,适用于本节会路由默认值的每个调用:`session.submit`、`session.stop` 和 `session.idle`(v1 客户端可以不带分支发出的三个;其余被路由的调用从 v3 起才准入,而 v3 的投影带每条线)。所以较新的连接移动默认分支后,v1 客户端仍能看到它的输入所跑的轮次。v2 及以后带每条线,必须在 v1 不能命名处命名一条线;v3 连接的缺省调用跟随默认分支。旧客户端读到的其他内容含义都不变:`session.attach` 回复里的 `SessionInfo.sequence` 仍是根的序号——CLI 用作 `main` 窗口 `through` 和根模型更新水位的截止点——对话所在的线以 `defaultBranch {branchId, sequence}` 并列给出。该游标只属于这条回复:`session.summaries` 的条目是目录行,不带 `defaultBranch`,所以客户端在 attach 之后读这条线,而不是从列表里读。早于该字段的客户端忽略它;跟随移动的客户端据它续读那条线。目录行的 `sequence` 同理:在已加载覆盖和存储查询两种投影里都是根的,所以加载或卸载 Session 都不会改变它;`running` 与 `updatedAt` 跟随默认分支,持久化的移动在它自己的事务里用新默认分支的最新活动刷新 `updatedAt`,移动本身不算活动,所以空闲移动不会让该行按离开的那条线显得刚刚活动。 +回复里的 `model`、`modelPreferences` 和 `capabilitySnapshot` 仍是根的已采纳配置,也就是对话停在根上的 Session 一贯读的水位。跟随移动的客户端把配置与游标成对取用,不把两者混在一起:它取游标所指那条线的配置(经 `session.model.get {sessionId, branchId, through}`),所以对话在某条线上的 Session 显示那条线在游标处或之前采纳的模型,回复里的记录只给根做种子。这个读取回答那条线自己的配置和它自己的已提交截止位,所以显示 transcript 不带 `context/configured`、有限的窗口从采纳之后开始时也能用;那个截止位就是之后配置必须越过的水位。不能回答这个读取的服务器说不出那条线的配置,而它的 attach 回复是根的,所以任何客户端都不会把根的模型显示成某条线的。不带 `defaultBranch` 的回复说明该服务器还不能移动默认分支、对话在根上,它的记录就是该 Session 唯一的模型,所有客户端继续使用它。 + **Web** 让默认分支留在中央,在右侧详情面板里跟随其他线:Lines 树、每个打开的线一个标签,以及按 line 的发送、停止、审批和结束([Web 工作区 §4.1](../../design/web-workspace.md#41-lines-and-branch))。移动默认分支与 TUI 是同一个动作,经 `session.branch_set_default`。Lines 树标出根和默认分支,也就是能开线的两条线;其他线的 `create` 被拒绝,拒绝显示在发起该动作的地方。输入框提供的命令作用于当前居中的那条线,而不是根:`/goal`、`/compact`、`/usage` 和 `/effort` 不传分支或传当前显示的线,而 `/fork` 仍只复制根([Web 工作区](../../design/web-workspace.md))。会话列表显示一个 Session 的运行状态和最近活动,取自它的默认分支,所以对话在某条线上的 Session 按那条线读作繁忙或刚刚活动,而不是按它的根。Desktop 得到的是协议:`session.branch_set_default`,以及 v3 历史里的新事件。 ## 15. 改动 diff --git a/web/src/chat-ui/web-chat-timeline.test.ts b/web/src/chat-ui/web-chat-timeline.test.ts index 524d6d93b4..4defefdb9f 100644 --- a/web/src/chat-ui/web-chat-timeline.test.ts +++ b/web/src/chat-ui/web-chat-timeline.test.ts @@ -1,14 +1,16 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest" -import { computed, createApp, defineComponent, h, nextTick, reactive, ref, shallowReactive, type App } from "vue" +import { computed, createApp, defineComponent, h, nextTick, reactive, ref, shallowReactive, type App, type Ref } from "vue" import { createPinia, setActivePinia, type Pinia } from "pinia" import { createMemoryHistory, createRouter, type Router } from "vue-router" import type { ChatUiHost } from "@dimcode/chat-ui" +import type { WebChatActions } from "./web-host" import { i18n } from "../i18n" import { Projection } from "../projection" import type { ApprovalRequest, ModelRetryProgress, PendingQuestion, SessionEvent } from "../rpc/protocol" import { useChatStore } from "../stores/chat" import { useConnectionStore } from "../stores/connection" import { useSessionsStore } from "../stores/sessions" +import { readNotification } from "../rpc/read" import { createRowMapper } from "./rows" import { createWebChatUiHost } from "./web-host" import WebChatTimeline from "./WebChatTimeline.vue" @@ -1091,17 +1093,18 @@ describe("Web ChatUiHost commands", () => { } const rows = project(recorded).rows - function setup(features: readonly string[] = HELLO_FEATURES, methods: readonly string[] = SESSION_METHODS, view: "loaded" | "missing" = "loaded") { + function setup(features: readonly string[] = HELLO_FEATURES, methods: readonly string[] = SESSION_METHODS, view: "loaded" | "missing" = "loaded", branch = "main") { const pinia = stores(features, view === "missing" ? null : { approvals: [approval], questions: [question], methods }) const router = testRouter() const openBranch = vi.fn() const confirmFork = vi.fn(async () => true) let host!: ChatUiHost + let actions!: Ref const app = createApp({ setup() { - host = createWebChatUiHost({ + const created = createWebChatUiHost({ sessionId: ref("s-1"), - branchId: ref("main"), + branchId: ref(branch), rows: computed(() => createRowMapper()(rows, "s-1")), running: ref(false), branchable: ref(true), @@ -1109,13 +1112,15 @@ describe("Web ChatUiHost commands", () => { noticeText: () => "", confirmFork, openBranch, - }).host + }) + host = created.host + actions = created.actions return () => null }, }) app.use(pinia).use(router).use(i18n).mount(document.createElement("div")) mounted.push(app) - return { host, chat: useChatStore(pinia), sessions: useSessionsStore(pinia), router, openBranch, confirmFork } + return { host, actions, chat: useChatStore(pinia), sessions: useSessionsStore(pinia), router, openBranch, confirmFork } } it("maps each supported command to its chat store action", async () => { @@ -1158,6 +1163,17 @@ describe("Web ChatUiHost commands", () => { expect(answer).not.toHaveBeenCalled() }) + it("refuses a fork of a centre that is not the root, so a line's cut stays its own", async () => { + const { host, actions, chat, confirmFork } = setup(HELLO_FEATURES, SESSION_METHODS, "loaded", "worker") + const storeFork = vi.spyOn(chat, "fork").mockResolvedValue("s-2") + const availability = actions.value.fork + expect(availability.available).toBe(false) + expect(availability.available ? undefined : availability.reason).toBe("A fork copies the main line; branch opens a line here instead.") + await expect(host.commands.fork("user-9")).rejects.toThrow("A fork copies the main line") + expect(confirmFork).not.toHaveBeenCalled() + expect(storeFork).not.toHaveBeenCalled() + }) + it("approves through the built-in approval.respond, which hello does not announce", async () => { const { host, chat } = setup([]) expect(host.capabilities.value.interactive).toBe(true) @@ -1181,3 +1197,306 @@ describe("Web ChatUiHost commands", () => { expect(respond).not.toHaveBeenCalled() }) }) + +/** The features a Session on a line serves: a bounded transcript, the line's own configuration and its policy. */ +const LINE_FEATURES = ["session.branches", "session.methods", "session.history.display", "session.history.detail", "session.history.display.tail", "session.history.display.transcript", "session.history.latestTurn", "session.model.get", "session.permission.get"] + +function permission(preset: string, version = 1) { + return { version, policy: { preset, allowedTools: [], disallowedTools: [] } } +} + +/** Answers the reads a Session's attach and a move make, with per-method overrides. */ +function serveChat(overrides: Record) => unknown> = {}) { + const calls: Array<{ method: string; params: Record }> = [] + const client = useConnectionStore().client + vi.spyOn(client, "call").mockImplementation((async (method: string, params: Record, read: (value: unknown) => unknown) => { + calls.push({ method, params }) + const reply = overrides[method] !== undefined + ? overrides[method]!(params) + : (() => { + switch (method) { + case "session.attach": return { model: { providerId: "fixture", modelId: "root-model" } } + case "session.methods": return { methods: ["session.input.pending", "session.question.pending", "session.turn.get"].map(name => ({ name })) } + case "session.branches": return { defaultBranchId: "main", branches: [{ branchId: "main", state: "open", head: 8 }] } + case "session.branch_set_default": return { defaultBranchId: params.branchId } + case "session.history": return { events: [], through: 5, nextAfter: 5, done: true } + case "session.history.display": return { items: [], through: 5, nextBefore: 1, nextAfter: 5, done: true } + case "session.branch.get": return { branchId: params.branchId, parentBranchId: "main", branchPoint: 1, state: "open", head: 5 } + case "session.question.pending": return { branchId: params.branchId, through: 5, batches: [], next: null } + case "session.input.pending": return { branchId: params.branchId, through: 5, inputs: [], next: null } + case "session.turn.get": return { branchId: params.branchId, through: 5, turn: null, output: null } + case "session.model.get": return { branchId: params.branchId, through: 5, configuration: { model: { providerId: "fixture", modelId: `${params.branchId}-model` } } } + case "session.permission.get": return permission("workspace-write") + case "session.context.usage": return { contextWindow: 1000, outputTokens: 0, thresholdTokens: 900, estimatedInputTokens: 10, baselineSource: "usage" } + default: throw new Error(`unexpected ${method}`) + } + })() + return read(await reply) + }) as any) + return calls +} + +describe("chat store moves", () => { + beforeEach(() => { + vi.stubGlobal("matchMedia", (query: string) => ({ + matches: false, + media: query, + onchange: null, + addListener: () => {}, + removeListener: () => {}, + addEventListener: () => {}, + removeEventListener: () => {}, + dispatchEvent: () => false, + })) + }) + + it("installs an accepted move when its model read fails", async () => { + const pinia = stores(LINE_FEATURES, null) + const calls = serveChat({ + "session.model.get": (params) => { + if (params.branchId === "worker") throw new Error("the model read failed") + return { branchId: params.branchId, through: 5, configuration: { model: { providerId: "fixture", modelId: `${params.branchId}-model` } } } + }, + }) + const chat = useChatStore(pinia) + chat.open("s-1") + await vi.waitFor(() => expect(chat.views["s-1"]?.status).toBe("ready")) + + await expect(chat.setDefaultBranch("s-1", "worker")).resolves.toBeUndefined() + const view = chat.views["s-1"]! + expect(view.defaultBranchId).toBe("worker") + expect(view.model).toBeUndefined() + expect(view.status).toBe("ready") + expect(view.error).toBe("") + expect(view.permission?.preset).toBe("workspace-write") + await chat.usage("s-1") + expect(calls[calls.length - 1]?.params.branchId).toBe("worker") + }) + + it("applies a move's policy read only while that move owns the centre", async () => { + const pinia = stores(LINE_FEATURES, null) + const policy = new Map void>() + serveChat({ + "session.permission.get": (params) => { + if (params.branchId === "main") return permission("read-only") + return new Promise(resolve => policy.set(params.branchId, resolve)) + }, + }) + const chat = useChatStore(pinia) + chat.open("s-1") + await vi.waitFor(() => expect(chat.views["s-1"]?.status).toBe("ready")) + + const first = chat.setDefaultBranch("s-1", "worker") + await vi.waitFor(() => expect(policy.has("worker")).toBe(true)) + const second = chat.setDefaultBranch("s-1", "other") + await vi.waitFor(() => expect(policy.has("other")).toBe(true)) + expect(chat.views["s-1"]!.permission).toBeUndefined() + + policy.get("other")!(permission("full-access")) + await second + expect(chat.views["s-1"]!.permission?.preset).toBe("full-access") + policy.get("worker")!(permission("workspace-write")) + await first + expect(chat.views["s-1"]!.permission?.preset).toBe("full-access") + expect(chat.views["s-1"]!.defaultBranchId).toBe("other") + }) + + it("does not let a move's policy read undo a newer edit on the same line", async () => { + const pinia = stores(LINE_FEATURES, null) + const held: { resolve?: (value: unknown) => void } = {} + let reads = 0 + serveChat({ + "session.permission.get": (params) => { + if (params.branchId === "main") return permission("workspace-write") + reads += 1 + // The move's own read is held at the old version while the user edits + // the line it names. + return reads === 1 ? new Promise(resolve => { held.resolve = resolve }) : permission("workspace-write") + }, + "session.permission.update": () => ({ version: 2 }), + }) + const chat = useChatStore(pinia) + chat.open("s-1") + await vi.waitFor(() => expect(chat.views["s-1"]?.status).toBe("ready")) + + const moved = chat.setDefaultBranch("s-1", "worker") + await vi.waitFor(() => expect(reads).toBe(1)) + await expect(chat.setPermission("s-1", "read-only")).resolves.toBe("updated") + expect(chat.views["s-1"]!.permission?.preset).toBe("read-only") + held.resolve!(permission("workspace-write", 1)) + await moved + expect(chat.views["s-1"]!.permission?.preset).toBe("read-only") + expect(chat.views["s-1"]!.defaultBranchId).toBe("worker") + }) + + it("does not let a move's policy read undo a newer permission event on the same line", async () => { + const pinia = stores(LINE_FEATURES, null) + const held: { resolve?: (value: unknown) => void } = {} + let reads = 0 + serveChat({ + "session.permission.get": (params) => { + if (params.branchId === "main") return permission("workspace-write") + reads += 1 + return reads === 1 ? new Promise(resolve => { held.resolve = resolve }) : permission("workspace-write") + }, + }) + const chat = useChatStore(pinia) + chat.open("s-1") + await vi.waitFor(() => expect(chat.views["s-1"]?.status).toBe("ready")) + + const moved = chat.setDefaultBranch("s-1", "worker") + await vi.waitFor(() => expect(reads).toBe(1)) + // Another client changes the policy of the very line the move is reading, + // after the read left the server. + chat.receive(readNotification("session.event", { + sessionId: "s-1", + branchId: "worker", + event: { id: "e6", sequence: 6, create_at: 1, type: "permission", name: "changed", data: { policy: { preset: "read-only", allowedTools: [], disallowedTools: [] } } }, + })!) + await vi.waitFor(() => expect(chat.views["s-1"]!.permission?.preset).toBe("read-only")) + held.resolve!(permission("workspace-write", 1)) + await moved + expect(chat.views["s-1"]!.permission?.preset).toBe("read-only") + expect(chat.views["s-1"]!.defaultBranchId).toBe("worker") + }) + + it("does not let a live permission event undo a newer write on the same line", async () => { + const pinia = stores(LINE_FEATURES, null) + serveChat({ + "session.permission.get": () => permission("read-only", 6), + "session.permission.update": () => ({ version: 8 }), + }) + const chat = useChatStore(pinia) + chat.open("s-1") + await vi.waitFor(() => expect(chat.views["s-1"]?.status).toBe("ready")) + expect(chat.views["s-1"]!.permission?.preset).toBe("read-only") + expect(chat.views["s-1"]!.permissionVersion).toBe(6) + + await expect(chat.setPermission("s-1", "full-access")).resolves.toBe("updated") + expect(chat.views["s-1"]!.permission?.preset).toBe("full-access") + expect(chat.views["s-1"]!.permissionVersion).toBe(8) + + // The event was queued before the write and reaches the store after it. + chat.receive(readNotification("session.event", { + sessionId: "s-1", + branchId: "main", + event: { id: "e6", sequence: 6, create_at: 1, type: "permission", name: "changed", data: { policy: { preset: "read-only", allowedTools: [], disallowedTools: [] } } }, + })!) + await settle() + expect(chat.views["s-1"]!.permission?.preset).toBe("full-access") + expect(chat.views["s-1"]!.permissionVersion).toBe(8) + }) + + it("keeps a failed goal refresh on the line that issued it", async () => { + const pinia = stores(LINE_FEATURES, null) + const held: Record void; reject: (cause: unknown) => void }> = {} + let mainReads = 0 + serveChat({ + "session.methods": () => ({ methods: [...SESSION_METHODS, "session.goal.get"].map(name => ({ name })) }), + "session.goal.set": () => ({ reply: {} }), + "session.goal.get": (params) => { + if (params.branchId === "worker") return new Promise((resolve, reject) => { held.worker = { resolve, reject } }) + mainReads += 1 + // The centre's first read finishes the attach; the write's reread is + // the one that fails after the centre has moved. + return mainReads === 1 + ? { branchId: params.branchId, through: 5, goal: null } + : new Promise((resolve, reject) => { held.main = { resolve, reject } }) + }, + }) + const chat = useChatStore(pinia) + chat.open("s-1") + await vi.waitFor(() => expect(chat.views["s-1"]?.status).toBe("ready")) + + const written = chat.writeGoal("s-1", "set", "root work", "main").catch((cause: unknown) => cause) + await vi.waitFor(() => expect(held.main !== undefined).toBe(true)) + let finished = false + const moved = chat.setDefaultBranch("s-1", "worker").then(() => { finished = true }) + // The move continues on the new centre but waits for the goal refresh the + // outgoing line started, so it cannot finish while that read is held. + await vi.waitFor(() => expect(chat.views["s-1"]!.defaultBranchId).toBe("worker")) + await settle() + expect(finished).toBe(false) + + // The outgoing line's read fails only after the centre has moved on; the + // refresh the new centre asked for is still pending. + held.main!.reject(new Error("the goal read failed")) + await vi.waitFor(() => expect(held.worker !== undefined).toBe(true)) + held.worker!.resolve({ branchId: "worker", through: 5, goal: { objective: "worker work", status: { kind: "active" }, evaluator: false } }) + await moved + expect(chat.views["s-1"]!.defaultBranchId).toBe("worker") + expect(await written).toBeUndefined() + + const view = chat.views["s-1"]! + expect(view.defaultBranchId).toBe("worker") + expect(view.status).toBe("ready") + expect(view.error).toBe("") + await vi.waitFor(() => expect(view.goal?.objective).toBe("worker work")) + }) + + it("does not carry a failure from the outgoing line into the new centre", async () => { + const pinia = stores(LINE_FEATURES, null) + const held: Record void; reject: (cause: unknown) => void }> = {} + let mainReads = 0 + let releaseMove: ((value: unknown) => void) | undefined + serveChat({ + "session.methods": () => ({ methods: [...SESSION_METHODS, "session.goal.get"].map(name => ({ name })) }), + "session.goal.set": () => ({ reply: {} }), + "session.goal.get": (params) => { + if (params.branchId === "worker") return new Promise((resolve, reject) => { held.worker = { resolve, reject } }) + mainReads += 1 + return mainReads === 1 + ? { branchId: params.branchId, through: 5, goal: null } + : new Promise((resolve, reject) => { held.main = { resolve, reject } }) + }, + "session.branch_set_default": (params) => new Promise((resolve) => { releaseMove = () => resolve({ defaultBranchId: params.branchId }) }), + }) + const chat = useChatStore(pinia) + chat.open("s-1") + await vi.waitFor(() => expect(chat.views["s-1"]?.status).toBe("ready")) + + const written = chat.writeGoal("s-1", "set", "root work", "main").catch((cause: unknown) => cause) + await vi.waitFor(() => expect(held.main !== undefined).toBe(true)) + const moved = chat.setDefaultBranch("s-1", "worker") + await vi.waitFor(() => expect(releaseMove !== undefined).toBe(true)) + // The outgoing line's goal read fails before the move's reply, while that + // line is still the centre, so the failure is published to the page. + held.main!.reject(new Error("the goal read failed")) + await vi.waitFor(() => expect(chat.views["s-1"]?.status).toBe("failed")) + expect(await written).toBeInstanceOf(Error) + + releaseMove!({ defaultBranchId: "worker" }) + await vi.waitFor(() => expect(held.worker !== undefined).toBe(true)) + held.worker!.resolve({ branchId: "worker", through: 5, goal: { objective: "worker work", status: { kind: "active" }, evaluator: false } }) + await moved + + const view = chat.views["s-1"]! + expect(view.defaultBranchId).toBe("worker") + expect(view.status).toBe("ready") + expect(view.error).toBe("") + expect(view.goal?.objective).toBe("worker work") + }) + + it("publishes a model update only to the line that issued it", async () => { + const pinia = stores(LINE_FEATURES, null) + const held: { resolve?: (value: unknown) => void } = {} + const calls = serveChat({ + "session.model.update": () => new Promise(resolve => { held.resolve = resolve }), + }) + const chat = useChatStore(pinia) + chat.open("s-1") + await vi.waitFor(() => expect(chat.views["s-1"]?.status).toBe("ready")) + + const choosing = chat.setModel("s-1", { providerId: "fixture", modelId: "picked" }) + await vi.waitFor(() => expect(held.resolve).toBeDefined()) + expect(calls.find(call => call.method === "session.model.update")?.params.branchId).toBe("main") + await chat.setDefaultBranch("s-1", "worker") + expect(chat.views["s-1"]!.model).toEqual({ providerId: "fixture", modelId: "worker-model" }) + + // The reply reaches the line that asked for it after the centre moved. + held.resolve!({ model: { providerId: "fixture", modelId: "picked" }, outcome: "updated" }) + await choosing + expect(chat.views["s-1"]!.model).toEqual({ providerId: "fixture", modelId: "worker-model" }) + expect(chat.views["s-1"]!.defaultBranchId).toBe("worker") + }) +}) diff --git a/web/src/features/chat/ChatPage.test.ts b/web/src/features/chat/ChatPage.test.ts new file mode 100644 index 0000000000..3197852423 --- /dev/null +++ b/web/src/features/chat/ChatPage.test.ts @@ -0,0 +1,141 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest" +import { createApp, defineComponent, h, nextTick, type App } from "vue" +import { createMemoryHistory, createRouter } from "vue-router" +import { createPinia, setActivePinia } from "pinia" +import { i18n } from "../../i18n" +import { useChatStore } from "../../stores/chat" +import ChatPage from "./ChatPage.vue" + +const mocks = vi.hoisted(() => { + const branchIds: string[] = [] + const plain = (name: string) => async () => { + const { defineComponent, h } = await import("vue") + return { default: defineComponent({ name, setup: () => () => h("div") }) } + } + return { branchIds, plain } +}) + +vi.mock("../../chat-ui/timeline", async () => { + const { defineComponent, h } = await import("vue") + return { + WebChatTimeline: defineComponent({ + name: "WebChatTimeline", + props: { branchId: { type: String, required: true } }, + setup(props) { + mocks.branchIds.push(props.branchId!) + return () => h("div", { "data-timeline-branch": props.branchId }) + }, + }), + } +}) +vi.mock("./ComposerPanel.vue", mocks.plain("ComposerPanel")) +vi.mock("./ApprovalPrompt.vue", mocks.plain("ApprovalPrompt")) +vi.mock("./QueuedInputs.vue", mocks.plain("QueuedInputs")) +vi.mock("./QuestionPrompt.vue", mocks.plain("QuestionPrompt")) +vi.mock("../extensions/ExtensionMenu.vue", mocks.plain("ExtensionMenu")) +vi.mock("../../components/BrandMark.vue", mocks.plain("BrandMark")) +vi.mock("../../components/ConfirmDialog.vue", mocks.plain("ConfirmDialog")) + +const mounted: App[] = [] + +function simple(name: string) { + return defineComponent({ name, setup: () => () => h("div") }) +} + +beforeEach(() => { + vi.stubGlobal("matchMedia", (query: string) => ({ + matches: false, + media: query, + onchange: null, + addListener: () => {}, + removeListener: () => {}, + addEventListener: () => {}, + removeEventListener: () => {}, + dispatchEvent: () => false, + })) +}) + +afterEach(() => { + while (mounted.length > 0) mounted.pop()!.unmount() + document.body.replaceChildren() + mocks.branchIds.length = 0 + vi.restoreAllMocks() + vi.unstubAllGlobals() +}) + +async function mountPage(defaultBranchId: string, status: "ready" | "failed" = "ready", error = ""): Promise { + const container = document.createElement("div") + document.body.append(container) + const pinia = createPinia() + setActivePinia(pinia) + const chat = useChatStore() + vi.spyOn(chat, "open").mockImplementation(() => {}) + chat.views["s-1"] = { + sessionId: "s-1", + defaultBranchId, + status, + error, + rows: [], + running: false, + stopping: false, + retry: undefined, + sessionRunning: false, + approvals: [], + questions: [], + methods: [], + permission: undefined, + permissionVersion: undefined, + goal: undefined, + queued: [], + model: undefined, + lines: [], + branches: {}, + lastTurnEnd: undefined, + earlier: false, + loadingEarlier: false, + historyError: "", + } + const router = createRouter({ + history: createMemoryHistory(), + routes: [ + { path: "/chat/new", name: "chat-new", component: { render: () => null } }, + { path: "/chat/:sessionId", name: "chat-session", component: { render: () => null } }, + ], + }) + await router.push("/chat/s-1") + const app = createApp({ render: () => h(ChatPage, { sessionId: "s-1" }) }) + app.use(pinia).use(i18n).use(router) + app.component("UButton", defineComponent({ + name: "UButton", + setup: (_, { attrs, slots }) => () => h("button", attrs, slots.default?.()), + })) + app.component("UBadge", simple("UBadge")) + app.component("UCollapsible", defineComponent({ + name: "UCollapsible", + setup: (_, { slots }) => () => h("div", slots.default?.()), + })) + app.mount(container) + mounted.push(app) + await nextTick() + return container +} + +describe("ChatPage", () => { + it("tells the timeline which line the centre is", async () => { + await mountPage("worker") + expect(mocks.branchIds).toContain("worker") + expect(mocks.branchIds).not.toContain("main") + }) + + it("retries the accepted line's reads from the failed page", async () => { + const container = await mountPage("worker", "failed", "the line could not be read") + const chat = useChatStore() + const retry = vi.spyOn(chat, "retryCentre").mockImplementation(() => {}) + expect(container.textContent).toContain("the line could not be read") + const button = container.querySelector("button") + expect(button?.textContent?.trim()).toBe("Retry") + button!.click() + await nextTick() + expect(retry).toHaveBeenCalledWith("s-1") + }) +}) diff --git a/web/src/features/chat/ChatPage.vue b/web/src/features/chat/ChatPage.vue index 03b589aedf..ecb4ef7174 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 { WebChatTimeline } from "../../chat-ui/timeline" 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,8 +59,10 @@ 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>() +/** The centre as it is now, read by a composer a prompt has cached: its props keep the line it was hidden on. */ +const liveCentre = () => centred.value const lineCount = computed(() => view.value?.lines.filter((line) => line.id !== ROOT_BRANCH_ID).length ?? 0) const linesBusy = computed(() => { const approvals = view.value?.approvals ?? [] @@ -80,24 +84,30 @@ 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, } }) -function send(text: string, attachments: DraftAttachments, mode: SubmitMode): Promise { - return chat.submit(props.sessionId, DEFAULT_BRANCH_ID, text, attachments, mode) +/** + * Sends the composer's draft to the line it was written on, which the + * composer names: a centre that moved while the gesture was out keeps the + * draft rather than writing it into the new conversation (design §14). + */ +function send(text: string, attachments: DraftAttachments, mode: SubmitMode, branchId = centred.value): Promise { + if (branchId !== centred.value) return Promise.reject(new Error(t("composer.sendNowMoved"))) + return chat.submit(props.sessionId, branchId, text, attachments, mode) } -function stop(): Promise { - return chat.stop(props.sessionId, DEFAULT_BRANCH_ID) +function stop(branchId = centred.value): Promise { + return chat.stop(props.sessionId, branchId) } -/** 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) +/** Withdraws one held message of `branchId`, so the composer can recall it into the draft; reports a message the run already adopted. */ +async function withdrawHeld(input: QueuedInput, branchId = centred.value): Promise { + const result = await chat.withdrawInput(props.sessionId, branchId, input.id, undefined) if (result.status === "notHeld") toast.push({ tone: "info", title: t("queue.notHeld") }) return result.status } @@ -111,14 +121,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) } @@ -126,9 +137,9 @@ function failure(cause: unknown): void { toast.push({ tone: "danger", title: t("command.failed"), description: cause instanceof Error ? cause.message : String(cause) }) } -async function compact(): Promise { +async function compact(branchId: string): Promise { try { - const result = await chat.compact(props.sessionId) + const result = await chat.compact(props.sessionId, branchId) if (result.status === "completed") toast.push({ tone: "success", title: t("command.compacted") }) else toast.push({ tone: "info", title: t("command.compactSkipped"), description: result.reason }) } catch (cause) { @@ -150,9 +161,9 @@ function usageLine(reading: ContextUsage): string { }) } -async function usage(): Promise { +async function usage(branchId: string): Promise { try { - toast.push({ tone: "info", title: t("command.usageTitle"), description: usageLine(await chat.usage(props.sessionId)) }) + toast.push({ tone: "info", title: t("command.usageTitle"), description: usageLine(await chat.usage(props.sessionId, branchId)) }) } catch (cause) { failure(cause) } @@ -181,7 +192,7 @@ function showGoal(current: Goal | undefined): void { }) } -async function goal(words: string): Promise { +async function goal(words: string, branchId: string): Promise { const request = parseGoalRequest(words) if (request === undefined) { toast.push({ tone: "info", title: t("goal.usage") }) @@ -194,7 +205,7 @@ async function goal(words: string): Promise { return } try { - await chat.writeGoal(props.sessionId, call, goalObjective(request)) + await chat.writeGoal(props.sessionId, call, goalObjective(request), branchId) toast.push({ tone: "success", title: t("goal.sent", { action: t(`goal.action.${call}`) }) }) } catch (cause) { failure(cause) @@ -202,7 +213,7 @@ async function goal(words: string): Promise { } /** `/loop` shows the line's loops, starts one, or stops one, the same forms the terminal client takes. */ -async function loop(words: string): Promise { +async function loop(words: string, branchId: string): Promise { const request = parseLoopRequest(words) if (request === undefined) { toast.push({ tone: "info", title: t("loop.usage") }) @@ -210,18 +221,18 @@ async function loop(words: string): Promise { } try { if (request.form === "show") { - const loops = await chat.readLoops(props.sessionId) + const loops = await chat.readLoops(props.sessionId, branchId) toast.push({ tone: "info", title: loops.length === 0 ? t("loop.none") : t("loop.listed", { count: loops.length }), description: loopReport(loops).join("\n") }) return } if (request.form === "start") { - const id = await chat.startLoop(props.sessionId, request.prompt, request.interval === undefined ? undefined : intervalSeconds(request.interval)) + const id = await chat.startLoop(props.sessionId, request.prompt, request.interval === undefined ? undefined : intervalSeconds(request.interval), branchId) toast.push({ tone: "success", title: t("loop.started", { id }) }) return } let loopId = request.loopId if (loopId === undefined) { - const live = (await chat.readLoops(props.sessionId)).filter((entry) => !["stopped", "expired"].includes(entry.state)) + const live = (await chat.readLoops(props.sessionId, branchId)).filter((entry) => !["stopped", "expired"].includes(entry.state)) if (live.length !== 1) { toast.push({ tone: "info", title: t("loop.noSingle") }) return @@ -235,8 +246,8 @@ async function loop(words: string): Promise { } } -/** `/effort` with no words lists the choices; `/effort VALUE` sets the default branch's reasoning effort. */ -async function effort(words: string): Promise { +/** `/effort` with no words lists the choices; `/effort VALUE` sets the named line's reasoning effort. */ +async function effort(words: string, branchId: string): Promise { const choices = effortChoices.value const value = words.trim() if (choices === undefined) { @@ -256,7 +267,7 @@ async function effort(words: string): Promise { return } try { - const outcome = await chat.setEffort(props.sessionId, value) + const outcome = await chat.setEffort(props.sessionId, value, branchId) toast.push({ tone: "success", title: t("command.effortSet", { outcome, value }) }) } catch (cause) { failure(cause) @@ -272,12 +283,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) { @@ -296,6 +306,9 @@ async function fork(): Promise {

{{ title }}

{{ view.error }}

+ + {{ t("lines.retry") }} +
@@ -367,12 +380,12 @@ async function fork(): Promise { { @quote="composer?.quote($event)" />
- +
@@ -395,6 +408,7 @@ async function fork(): Promise { v-if="!prompting" ref="composer" :session-id="sessionId" + :branch-id="centred" :running="view.running" :stopping="view.stopping" :model="view.model" @@ -411,6 +425,7 @@ async function fork(): Promise { :open-lines="branchable ? () => ui.openLines(sessionId) : undefined" :session-commands="sessionCommands" :skills="skills" + :centre="liveCentre" />
diff --git a/web/src/features/chat/ComposerPanel.vue b/web/src/features/chat/ComposerPanel.vue index 612496461f..a697644622 100644 --- a/web/src/features/chat/ComposerPanel.vue +++ b/web/src/features/chat/ComposerPanel.vue @@ -16,15 +16,17 @@ import { quoteInto } from "./quote" /** The Session commands the menu lists, each only when given. Errors are reported by the callee. */ type SessionCommands = { - compact?: () => Promise - usage?: () => Promise + /** Compacts the line the command was typed on. */ + compact?: (branchId: string) => Promise + /** Reports the context window the line the command was typed on is using. */ + usage?: (branchId: string) => Promise fork?: () => Promise - /** Receives the words after `/goal`; empty shows the goal. */ - goal?: (words: string) => Promise - /** Receives the words after `/loop`; empty lists the line's loops. */ - loop?: (words: string) => Promise - /** Receives the words after `/effort`; empty lists the choices. */ - effort?: (words: string) => Promise + /** Receives the words after `/goal` and the line the draft was written on; empty shows the goal. */ + goal?: (words: string, branchId: string) => Promise + /** Receives the words after `/loop` and the line the draft was written on; empty lists the line's loops. */ + loop?: (words: string, branchId: string) => Promise + /** Receives the words after `/effort` and the line the draft was written on; empty lists the choices. */ + effort?: (words: string, branchId: string) => Promise } /** @@ -38,6 +40,14 @@ type SessionCommands = { const props = withDefaults(defineProps<{ running: boolean stopping?: boolean + /** The line this composer writes to; the send-now gesture belongs to it from start to finish. */ + branchId?: string + /** + * The centre as it is now, read at dispatch: a prompt that took the composer's + * place caches it, so its props keep the line it was hidden on while the page + * knows the live one. + */ + centre?: () => string model: ModelId | undefined /** * The new Session's model resolution: the state the menu shows and the two @@ -46,8 +56,8 @@ const props = withDefaults(defineProps<{ modelPreview?: ModelMenuPreview /** False when this connection may not change the model; the menu then only names it. */ modelSelectable: boolean - /** Sends the text and the draft's attachments in `mode`; resolves once the server accepted it. */ - send: (text: string, attachments: DraftAttachments, mode: SubmitMode) => Promise + /** Sends the text and the draft's attachments in `mode`, to `branchId` when the caller names the line the draft was written on; resolves once the server accepted it. */ + send: (text: string, attachments: DraftAttachments, mode: SubmitMode, branchId?: string) => Promise /** False where a draft cannot carry attachments, as on a new Session's page. */ attachments?: boolean /** True when the Session stores long pastes through `attachment.put`. */ @@ -56,14 +66,14 @@ const props = withDefaults(defineProps<{ searchFiles?: (query: string) => Promise /** The Session policy and its independent controls; absent where permission methods are unavailable. */ permission?: { policy: PermissionPolicy | undefined; select: (preset: PermissionPreset) => Promise } - stop?: () => Promise + stop?: (branchId?: string) => Promise /** * The messages the server holds for this branch, oldest first: the composer * recalls them into the draft through `withdrawHeld`. */ held?: readonly QueuedInput[] /** Withdraws one held message; absent where the Session serves no `session.input.withdraw`. */ - withdrawHeld?: (input: QueuedInput) => Promise + withdrawHeld?: (input: QueuedInput, branchId?: string) => Promise /** The Session whose stored image files a recalled message names, for its thumbnail. */ sessionId?: string selectModel: (model: ModelId) => Promise | void @@ -443,6 +453,15 @@ async function submit(sendMode: SubmitMode = primaryMode.value): Promise { error.value = t("composer.stillStopping") return } + // Every branch-scoped submit — a message, a recalled draft, a `/goal`, + // `/loop` or `/effort` — belongs to the line it was written on. A prompt can + // cache this composer while the centre moves, so the live centre is asked + // once here, before a command parses or a draft is cleared; a refusal keeps + // the draft whole (design §14). + if (props.centre !== undefined && props.branchId !== undefined && props.centre() !== props.branchId) { + error.value = t("composer.sendNowMoved") + return + } if (commandMode.value) { const row = menuRows.value[activeIndex.value] if (row?.kind === "skill") completeSkill(row.name.slice(SKILL_TOKEN_PREFIX.length)) @@ -450,6 +469,7 @@ async function submit(sendMode: SubmitMode = primaryMode.value): Promise { return } const message = text.value + const line = props.branchId if (!dismissed.value && connection.supports("schedule.list") && /^\/schedule(?:d)?\s*$/i.test(message)) { await runCommand("scheduled") return @@ -465,7 +485,7 @@ async function submit(sendMode: SubmitMode = primaryMode.value): Promise { text.value = "" await nextTick() resize() - await goal(goalCommand[1]?.trim() ?? "") + await goal(goalCommand[1]?.trim() ?? "", line ?? "") return } const loop = props.sessionCommands?.loop @@ -474,7 +494,7 @@ async function submit(sendMode: SubmitMode = primaryMode.value): Promise { text.value = "" await nextTick() resize() - await loop(loopCommand[1]?.trim() ?? "") + await loop(loopCommand[1]?.trim() ?? "", line ?? "") return } const effort = props.sessionCommands?.effort @@ -483,7 +503,7 @@ async function submit(sendMode: SubmitMode = primaryMode.value): Promise { text.value = "" await nextTick() resize() - await effort(effortCommand[1]?.trim() ?? "") + await effort(effortCommand[1]?.trim() ?? "", line ?? "") return } sending.value = true @@ -512,7 +532,7 @@ async function submit(sendMode: SubmitMode = primaryMode.value): Promise { cursor = offset } body += linkMentions(message.slice(cursor), sentMentions) - await props.send(body, { images: sentImages.map((image) => image.file), pastes: sentPastes.map((paste) => paste.text), ...(gaps.length === 0 ? {} : { restored: gaps }), onProgress: (percent) => { uploadProgress.value = percent } }, sendMode) + await props.send(body, { images: sentImages.map((image) => image.file), pastes: sentPastes.map((paste) => paste.text), ...(gaps.length === 0 ? {} : { restored: gaps }), onProgress: (percent) => { uploadProgress.value = percent } }, sendMode, line) fileMentions.value = fileMentions.value.filter((mention) => !sentMentions.includes(mention)) sentImages.forEach((image) => URL.revokeObjectURL(image.url)) images.value = images.value.filter((image) => !sentImages.includes(image)) @@ -543,7 +563,9 @@ async function submitAlternate(): Promise { * reply says the turn has settled. A submit written before the last interrupt * cannot start a run after it, so the order is the point. A stop that fails * keeps the whole draft, and a second trigger during the same stop sends - * nothing: one reply decides one submit. + * nothing: one reply decides one submit. The gesture belongs to the line it + * started on: if the centre moves before it finishes, it stops without + * submitting and keeps the draft. */ async function sendNowAndStop(): Promise { if (sendNow.value || composing.value) return @@ -555,28 +577,45 @@ async function sendNowAndStop(): Promise { sendNow.value = true error.value = "" destination.value = undefined + const line = props.branchId recallBatch++ let at = 0 for (const item of held.value) { if (props.withdrawHeld === undefined) break try { - if (await props.withdrawHeld(item) === "deleted") at = recall(item, at) + if (await props.withdrawHeld(item, line) === "deleted") at = recall(item, at) } catch (cause) { // A message that stays held is not recalled and so is not sent twice; // the reason is reported and the gesture goes on, as the TUI's Esc does. error.value = cause instanceof Error ? cause.message : String(cause) } + if (props.branchId !== line) { + sendNow.value = false + error.value = t("composer.sendNowMoved") + return + } } await nextTick() resize() + if (props.branchId !== line) { + sendNow.value = false + error.value = t("composer.sendNowMoved") + return + } try { - await props.stop?.() + await props.stop?.(line) } catch (cause) { sendNow.value = false error.value = t("composer.sendNowFailed", { error: cause instanceof Error ? cause.message : String(cause) }) return } sendNow.value = false + // The centre moved while the stop was out: the draft belongs to the line the + // gesture started on, so it is kept rather than written to the new one. + if (props.branchId !== line) { + error.value = t("composer.sendNowMoved") + return + } await submit("queue") // This draft opens the run after the stopped one, so neither destination // above describes it. @@ -587,7 +626,7 @@ async function stop(): Promise { if (sendNow.value) return error.value = "" try { - await props.stop?.() + await props.stop?.(props.branchId) } catch (cause) { error.value = cause instanceof Error ? cause.message : String(cause) } @@ -620,6 +659,10 @@ function completeSkill(name: string): void { async function runCommand(name: typeof availableCommands.value[number]["name"]): Promise { if (composing.value) return error.value = "" + // A command belongs to the line the draft was written on: the line is read + // here, before the tick that lets the menu close, so a move that completes + // while the command opens cannot retarget it (design §14). + const line = props.branchId ?? "" const argument = name === "branch" || name === "goal" || name === "loop" || name === "effort" text.value = argument ? `/${name} ` : "" await nextTick() @@ -638,7 +681,8 @@ async function runCommand(name: typeof availableCommands.value[number]["name"]): error.value = cause instanceof Error ? cause.message : String(cause) } } else if (name === "permissions") permissionMenu.value?.open() - else if (name === "compact" || name === "usage" || name === "fork") await props.sessionCommands?.[name]?.() + else if (name === "compact" || name === "usage") await props.sessionCommands?.[name]?.(line) + else if (name === "fork") await props.sessionCommands?.fork?.() } function onKeydown(event: KeyboardEvent): void { 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 @@