From e85c20f0b7339f2bc422da41c13dacb4a74107b6 Mon Sep 17 00:00:00 2001 From: Simon Klee Date: Fri, 6 Nov 2026 02:08:24 +0100 Subject: [PATCH] fix(cli-rs): keep another client's switch batched with an acknowledgment The TUI reconciled a session's drafts once per store sync, against the session as the batch left it. When this client's commit was acknowledged and another client switched the model in the same batch, the commit never matched, the draft stayed, and the switch did not show. TS reconciles at each selection event. The store now records the session's agent and model after each selection event in Changes, and Local reconciles against each of them in order before the current session. --- packages/cli-rs/crates/store/src/changes.rs | 18 ++++++- packages/cli-rs/crates/store/src/lib.rs | 2 +- packages/cli-rs/crates/store/src/sessions.rs | 8 +++ packages/cli-rs/crates/tui/src/local.rs | 27 ++++++---- .../crates/tui/tests/all/shared_state.rs | 52 +++++++++++++++---- 5 files changed, 86 insertions(+), 21 deletions(-) diff --git a/packages/cli-rs/crates/store/src/changes.rs b/packages/cli-rs/crates/store/src/changes.rs index aefc7562bf2..248b696b1ca 100644 --- a/packages/cli-rs/crates/store/src/changes.rs +++ b/packages/cli-rs/crates/store/src/changes.rs @@ -6,15 +6,18 @@ use std::collections::{HashMap, HashSet, VecDeque}; -use opencode_api::generated::{SessionID, SessionMessageID}; +use opencode_api::generated::{AgentID, ModelRef, SessionID, SessionMessageID}; use crate::location::Location; /// Flushes kept for [`Log::since`]. A view further behind gets [`Changes::all`]. pub const LOG_LIMIT: usize = 256; +/// A session's agent and model. +pub type Selected = (Option, Option); + /// What changed. The query methods also answer true when a coarser entry covers the question. -#[derive(Debug, Clone, Default, PartialEq, Eq)] +#[derive(Debug, Clone, Default, PartialEq)] pub struct Changes { /// Everything may have changed: the view fell out of the log. pub all: bool, @@ -22,6 +25,9 @@ pub struct Changes { pub sessions: bool, /// Sessions whose info changed. pub session: HashSet, + /// A session's agent and model after each `session.agent.selected` or `session.model.selected`, in + /// order: a batch can hold this client's acknowledgment and then another client's switch. + pub selected: HashMap>, /// Sessions whose running state changed. pub status: HashSet, /// Sessions whose message list changed shape: insert, remove, reorder, reload, page. @@ -49,6 +55,7 @@ impl Changes { !self.all && !self.sessions && self.session.is_empty() + && self.selected.is_empty() && self.status.is_empty() && self.messages.is_empty() && self.message.is_empty() @@ -110,6 +117,9 @@ impl Changes { self.all |= other.all; self.sessions |= other.sessions; self.session.extend(other.session.iter().cloned()); + for (session, selected) in &other.selected { + self.selected.entry(session.clone()).or_default().extend(selected.iter().cloned()); + } self.status.extend(other.status.iter().cloned()); self.messages.extend(other.messages.iter().cloned()); for (session, messages) in &other.message { @@ -174,6 +184,10 @@ impl Log { self.current.session.insert(id.clone()); } + pub(crate) fn selected(&mut self, id: &SessionID, agent: Option, model: Option) { + self.current.selected.entry(id.clone()).or_default().push((agent, model)); + } + pub(crate) fn status(&mut self, id: &SessionID) { self.current.status.insert(id.clone()); } diff --git a/packages/cli-rs/crates/store/src/lib.rs b/packages/cli-rs/crates/store/src/lib.rs index 5feb62f8c64..4c05dd43e05 100644 --- a/packages/cli-rs/crates/store/src/lib.rs +++ b/packages/cli-rs/crates/store/src/lib.rs @@ -14,7 +14,7 @@ pub mod shells; pub mod state; pub mod target; -pub use changes::Changes; +pub use changes::{Changes, Selected}; pub use forms::Form; pub use inbox::{InboxExt, PendingStatus, Prompt}; pub use location::{Catalog, Location, LocationData}; diff --git a/packages/cli-rs/crates/store/src/sessions.rs b/packages/cli-rs/crates/store/src/sessions.rs index a272f994e1f..f8f7e2efd3d 100644 --- a/packages/cli-rs/crates/store/src/sessions.rs +++ b/packages/cli-rs/crates/store/src/sessions.rs @@ -226,6 +226,12 @@ impl State { } } + fn log_selected(&mut self, id: &SessionID) { + if let Some(info) = self.info.get(id) { + self.log.selected(id, info.agent.clone(), info.model.clone()); + } + } + /// True when a session read is worth revalidating: its info is loaded or a read is active. fn known(&self, id: &SessionID) -> bool { self.info.contains_key(id) || self.syncs.has(&format!("session:{}", id.0)) @@ -262,6 +268,7 @@ impl State { let data = &event.data; let previous = self.info.get(&data.session_id).and_then(|info| info.agent.clone()); self.edit_info(&data.session_id, |info| info.agent = Some(data.agent.clone())); + self.log_selected(&data.session_id); let row = SessionMessageAgentSelected { id: from_event(&event.id), r#type: "agent-switched".into(), @@ -278,6 +285,7 @@ impl State { let previous = data.previous.clone().or_else(|| self.info.get(&data.session_id).and_then(|info| info.model.clone())); self.edit_info(&data.session_id, |info| info.model = Some(data.model.clone())); + self.log_selected(&data.session_id); if !self.messages.contains_key(&data.session_id) { return Vec::new(); } diff --git a/packages/cli-rs/crates/tui/src/local.rs b/packages/cli-rs/crates/tui/src/local.rs index 2cf71e55a80..0925b0709e5 100644 --- a/packages/cli-rs/crates/tui/src/local.rs +++ b/packages/cli-rs/crates/tui/src/local.rs @@ -23,7 +23,7 @@ use opencode_local::model_pref::{self, Model, ModelPreferences, Preference}; use opencode_local::storage::Storage; use opencode_local::watch::Watch; use opencode_store::location::{Catalog, Location, LocationData}; -use opencode_store::{Changes, Data}; +use opencode_store::{Changes, Data, Selected}; use opencode_ui::bind; use opencode_ui::dialog::Dialogs; use opencode_ui::toast::{ToastOptions, Toasts, Variant}; @@ -210,19 +210,20 @@ impl Local { } else if changes.all || changes.location(&location) { self.notify(); } - let sessions: Vec = if changes.all { + let sessions: Vec = if changes.all { self.state .borrow() .commits .keys() .cloned() .chain(self.state.borrow().agent_drafts.keys().cloned()) + .map(SessionID) .collect() } else { - changes.session.iter().map(|id| id.0.clone()).collect() + changes.session.iter().cloned().collect() }; for id in sessions { - self.reconcile(&SessionID(id)); + self.reconcile(&id, changes.selected.get(&id).map_or(&[], Vec::as_slice)); } } @@ -742,14 +743,22 @@ impl Local { Selection { model: Model::new(&model.provider_id.0, &model.id), variant: model.variant.clone() }; self.state.borrow_mut().commits.insert(session.0.clone(), (agent.to_owned(), selection.key())); // An unchanged model emits no event; the agent may be the only durable change. - self.reconcile(session); + self.reconcile(session, &[]); } - // `reconcileSessionSelection` and the agent arm of `session.agent.selected`, from the session as the - // store holds it after the event. - fn reconcile(&self, id: &SessionID) { + // `reconcileSessionSelection` and the agent arm of `session.agent.selected`, once for the agent and + // model after each selection event of the batch, as TS handles each event, then for the session as the + // store holds it. + fn reconcile(&self, id: &SessionID, selected: &[Selected]) { let session = self.data.read(|state| state.session(id).cloned()); let Some(session) = session else { return }; + for (agent, model) in selected { + self.settle(id, &SessionInfo { agent: agent.clone(), model: model.clone(), ..session.clone() }); + } + self.settle(id, &session); + } + + fn settle(&self, id: &SessionID, session: &SessionInfo) { let agent = session.agent.as_ref().map(|agent| agent.0.clone()); { let mut state = self.state.borrow_mut(); @@ -765,7 +774,7 @@ impl Local { let Some((expected_agent, expected_selection)) = expected else { return; }; - let durable = Self::durable(Some(&session)); + let durable = Self::durable(Some(session)); if agent.as_ref() != Some(&expected_agent) || durable.is_none_or(|durable| durable.key() != expected_selection) { return; diff --git a/packages/cli-rs/crates/tui/tests/all/shared_state.rs b/packages/cli-rs/crates/tui/tests/all/shared_state.rs index 5a7bef2530c..64bc98d5ed3 100644 --- a/packages/cli-rs/crates/tui/tests/all/shared_state.rs +++ b/packages/cli-rs/crates/tui/tests/all/shared_state.rs @@ -128,15 +128,25 @@ impl Setup { /// A durable `ses_b` event, as another client's switch or this one's commit reports it. fn emit(&self, kind: &str, data: Value) { - self.seq.set(self.seq.get() + 1); - let event: V2Event = serde_json::from_value(json!({ - "id": format!("evt_{}", self.seq.get()), "created": self.seq.get(), "type": kind, - "durable": { "aggregateID": "ses_b", "seq": self.seq.get(), "version": 1 }, - "location": { "directory": "/project-b" }, - "data": data, - })) - .unwrap(); - self.tui.data.apply(&[event]); + self.emit_batch(&[(kind, data)]); + } + + /// Durable `ses_b` events that the store applies in one batch. + fn emit_batch(&self, events: &[(&str, Value)]) { + let events: Vec = events + .iter() + .map(|(kind, data)| { + self.seq.set(self.seq.get() + 1); + serde_json::from_value(json!({ + "id": format!("evt_{}", self.seq.get()), "created": self.seq.get(), "type": kind, + "durable": { "aggregateID": "ses_b", "seq": self.seq.get(), "version": 1 }, + "location": { "directory": "/project-b" }, + "data": data, + })) + .unwrap() + }) + .collect(); + self.tui.data.apply(&events); } fn file(&self, name: &str) -> String { @@ -206,6 +216,30 @@ fn acknowledged_commits_clear_the_drafts() { setup.wait("the other client's agent", || setup.agent().as_deref() == Some("reviewer")); } +/// carbon-3: the acknowledgments and another client's switch in one batch: TS handles each event in turn, so +/// the drafts give way and the switch shows. +#[test] +fn a_switch_batched_with_the_acknowledgments_shows() { + let setup = Setup::new(&[]); + setup.wait("the session's catalog", || setup.agent().as_deref() == Some("reviewer")); + setup.tui.local.set_agent("build"); + setup.tui.local.set(&Model::new("openai", "gpt-5"), false); + setup.submit("switch", 1); + setup.emit_batch(&[ + ("session.agent.selected", json!({ "sessionID": "ses_b", "agent": "build" })), + ("session.model.selected", json!({ "sessionID": "ses_b", "model": { "providerID": "openai", "id": "gpt-5" } })), + ( + "session.model.selected", + json!({ "sessionID": "ses_b", "model": { "providerID": "anthropic", "id": "claude-haiku" } }), + ), + ]); + setup.wait("the other client's model", || { + setup.tui.local.current() == Some(Model::new("anthropic", "claude-haiku")) + }); + setup.emit("session.agent.selected", json!({ "sessionID": "ses_b", "agent": "reviewer" })); + setup.wait("the other client's agent", || setup.agent().as_deref() == Some("reviewer")); +} + /// carbon-7: a pin keeps the pins another client wrote after this one read the file, and /// `session.deleted` prunes it. #[test]