SolidCraft: an open-source parametric 3D CAD application built in pure Rust. Desktop, web, and automation through MCP.
Agent chat: each design tab keeps its own conversation (#5439) (#5612)
raykholo38d7ea4198ec
diff --git a/crates/ui-egui/src/agent_chat/mod.rs b/crates/ui-egui/src/agent_chat/mod.rsindex 950b24f575..8332ac0c96 100644--- a/crates/ui-egui/src/agent_chat/mod.rs+++ b/crates/ui-egui/src/agent_chat/mod.rs@@ -244,6 +244,8 @@ pub enum Item {/// The message being answered: what undo and the limits need.struct Turn {+ /// Deferred requests stop being valid when this turn ends or its tab is left.+ active: Arc<std::sync::atomic::AtomicBool>,/// The design and the undo depth before it.start_doc: Arc<solidcraft_engine::doc::Document>,start_undo: usize,@@ -410,6 +412,33 @@ impl Drop for AgentChat {}impl AgentChat {+ /// Exchange document state, keeping window services and preferences UI in the window.+ pub(crate) fn swap_document(&mut self, other: &mut Self) {+ std::mem::swap(self, other);+ std::mem::swap(&mut self.open, &mut other.open);+ std::mem::swap(&mut self.settings, &mut other.settings);+ std::mem::swap(&mut self.control_starter, &mut other.control_starter);+ std::mem::swap(&mut self.models_cache, &mut other.models_cache);+ std::mem::swap(&mut self.window_placed, &mut other.window_placed);+ #[cfg(not(target_arch = "wasm32"))]+ {+ std::mem::swap(&mut self.detection, &mut other.detection);+ std::mem::swap(&mut self.detecting, &mut other.detecting);+ }+ // Hit regions must be measured again for the incoming conversation.+ self.panel_rect = None;+ self.dock_space = None;+ self.drop_rect = None;+ }++ pub(crate) fn disconnect_document(&mut self, session: &mut solidcraft_engine::Session, wait: bool) {+ finish_turn(self, session);+ self.stop_backend(wait);+ if self.state.is_some() {+ self.state = Some(State::Off);+ }+ }+/// Put a file on the next message with an id of its own; its name back.fn add_file(&mut self, file: attach::Attachment) -> String {let id = self.next_file_id();@@ -604,7 +633,7 @@ impl AgentChat {self.state = Some(State::NeedsAuth);self.picking = Some(false);// What was asked goes again once the login is done.- if self.queued.is_none() {+ if !self.stopped && self.queued.is_none() {self.queued = self.last.take();}}@@ -841,18 +870,37 @@ pub fn connect(app: &mut SolveApp, ctx: &egui::Context) {/// Stop the agent (and everything it started); the conversation stays.pub fn disconnect(app: &mut SolveApp) {- end_turn(app);- let chat = &mut app.agent_chat;- chat.stop_backend(false);- if chat.state.is_some() {- chat.state = Some(State::Off);- }+ app.agent_chat.disconnect_document(&mut app.session, false);}/// The app is quitting: end the agent and its helpers before the window goes.pub fn shutdown(app: &mut SolveApp) {+ app.agent_chat.disconnect_document(&mut app.session, true);+ crate::documents::disconnect_background_chats(app, true);+}++/// A tab switch stops this turn before its session leaves the app. Keep the backend's own+/// conversation, drafts and queue, but do not send that queue automatically on returning.+pub(crate) fn leave_document(app: &mut SolveApp) {+ if app.agent_chat.state() == State::Busy {+ cancel(app);+ }end_turn(app);- app.agent_chat.stop_backend(true);+ let chat = &mut app.agent_chat;+ chat.steering = false;+ chat.last = None;+ // A prompt waiting for startup or sign-in has not reached the backend yet. Keep it+ // with the explicit queue so a late Ready event cannot send it on returning to the tab.+ if let Some((text, image, at, files)) = chat.queued.take() {+ if let Some(at) = at.filter(|&at| matches!(chat.items.get(at), Some(Item::User { .. }))) {+ chat.items.remove(at);+ }+ // The text already carries the selection, so there is no context to show again.+ chat.pending.insert(0, Pending { text, image, context: Context::default(), files });+ }+ if !chat.pending.is_empty() {+ chat.stopped = true;+ }}/// Most messages waiting in the queue.@@ -1134,8 +1182,15 @@ fn start_turn_with(app: &mut SolveApp, text: String, image: bool, at: Option<usi// The undo step is named after the message, or its first file when it has no words.let first_line = text.lines().find(|l| !l.trim().is_empty()).or_else(|| files.first().map(|f| f.name.as_str())).unwrap_or("");let label: String = first_line.chars().take(48).collect();- app.agent_chat.turn =- Some(Turn { start_doc: app.session.doc.clone(), start_undo: app.session.undo.len(), changes: 0, requests: 0, limit_told: false, label });+ app.agent_chat.turn = Some(Turn {+ active: Arc::new(std::sync::atomic::AtomicBool::new(true)),+ start_doc: app.session.doc.clone(),+ start_undo: app.session.undo.len(),+ changes: 0,+ requests: 0,+ limit_told: false,+ label,+ });app.agent_chat.last = Some((text, image, at, files));app.agent_chat.state = Some(State::Busy);app.agent_chat.stopped = false;@@ -1350,11 +1405,16 @@ fn approve_with(app: &mut SolveApp, id: u64, allow: bool, why: &str) {/// The message is answered: its changes become one undo step, and what still waits is declined.fn end_turn(app: &mut SolveApp) {decline_all(app, "the message ended");- let Some(turn) = app.agent_chat.turn.take() else { return };- let steps = merge_undo(&mut app.session.undo, &turn.start_doc, turn.start_undo, &trf("ui.agent_chat_undo_label", &[("message", &turn.label)]));+ finish_turn(&mut app.agent_chat, &mut app.session);+}++fn finish_turn(chat: &mut AgentChat, session: &mut solidcraft_engine::Session) {+ let Some(turn) = chat.turn.take() else { return };+ turn.active.store(false, std::sync::atomic::Ordering::Relaxed);+ let steps = merge_undo(&mut session.undo, &turn.start_doc, turn.start_undo, &trf("ui.agent_chat_undo_label", &[("message", &turn.label)]));if steps > 0 {- let doc = app.session.doc.clone();- app.agent_chat.push(Item::Changes { steps, doc, undone: false });+ let doc = session.doc.clone();+ chat.push(Item::Changes { steps, doc, undone: false });}}@@ -1406,6 +1466,7 @@ fn pump_tools(app: &mut SolveApp) {refuse(req, "the agent chat has no message in progress".into());continue;};+ req.chat_turn = Some(Arc::clone(&turn.active));turn.requests += 1;// Requests without folders of their own stay inside the chat's working folder.if let Some(o) = req.params.as_object_mut()@@ -1516,6 +1577,7 @@ pub fn poll(app: &mut SolveApp, ctx: &egui::Context) {}// AI features turned off: nothing keeps running, nothing is looked for.if !shown(app) {+ crate::documents::disconnect_background_chats(app, false);if app.agent_chat.backend.is_some() || app.agent_chat.open {disconnect(app);app.agent_chat.open = false;@@ -1531,6 +1593,11 @@ pub fn poll(app: &mut SolveApp, ctx: &egui::Context) {end_turn(app);after_turn(app, ctx);}+ Some(Outcome::Permission { key, .. }) if app.agent_chat.turn.is_none() => {+ if let Some(b) = app.agent_chat.backend.as_mut() {+ b.answer_permission(key, None);+ }+ }Some(Outcome::Permission { key, title, options }) => on_permission(app, key, title, options),None => {}}diff --git a/crates/ui-egui/src/agent_chat/tests.rs b/crates/ui-egui/src/agent_chat/tests.rsindex ed714a3aaf..c2c3482d36 100644--- a/crates/ui-egui/src/agent_chat/tests.rs+++ b/crates/ui-egui/src/agent_chat/tests.rs@@ -454,7 +454,9 @@ impl ChatBackend for Script {fn set_model(&mut self, model: &str) {self.calls.lock().unwrap().push(format!("set_model: {model}"));}- fn answer_permission(&mut self, _: u64, _: Option<&str>) {}+ fn answer_permission(&mut self, key: u64, option: Option<&str>) {+ self.calls.lock().unwrap().push(format!("permission: {key} {option:?}"));+ }fn authenticate(&mut self, _: &str) {}fn shutdown(&mut self, _: bool) {}}@@ -472,6 +474,262 @@ fn ended(script: &Script, reason: &str) {script.report(Event::TurnEnded { reason: reason.into() });}+#[test]+fn document_tabs_keep_their_conversations_and_backend_context() {+ let (mut app, first, ctx) = app_with_script();+ app.agent_chat.open = true;+ app.agent_chat.control_starter = Some(Box::new(|_| Some(12345)));+ app.agent_chat.tools_port = Some(12345);+ app.agent_chat.settings.add = Some(settings::AddState::default());+ app.agent_chat.agent_id = Some("first-agent".into());+ app.agent_chat.input = "first draft".into();+ app.agent_chat.attach_view = true;+ app.agent_chat.add_file(attach::Attachment::imported("sample.step".into()));+ send(&mut app, &ctx, "first request".into());+ send(&mut app, &ctx, "first follow-up".into());++ crate::documents::open_tab(&mut app, solidcraft_engine::Session::default()).unwrap();+ assert!(app.agent_chat.items.is_empty() && app.agent_chat.input.is_empty());+ assert!(app.agent_chat.pending.is_empty() && app.agent_chat.attachments.is_empty());+ assert!(app.agent_chat.backend.is_none() && app.agent_chat.agent_id.is_none());+ assert!(app.agent_chat.tools_port.is_none() && app.agent_chat.tools_rx.is_none());+ assert!(!app.agent_chat.attach_view);+ assert!(app.agent_chat.open && app.agent_chat.control_starter.is_some());+ assert!(app.agent_chat.settings.add.is_some(), "settings belong to the window");+ assert!(first.calls().iter().any(|c| c == "cancel"));++ let second = Script::default();+ app.agent_chat.backend = Some(Box::new(second.clone()));+ app.agent_chat.state = Some(State::Ready);+ app.agent_chat.input = "second draft".into();+ send(&mut app, &ctx, "second request".into());+ ended(&second, "");+ poll(&mut app, &ctx);+ ended(&first, "cancelled");+ crate::documents::switch(&mut app, 0);+ poll(&mut app, &ctx);+ assert_eq!(app.agent_chat.input, "first draft");+ assert_eq!(app.agent_chat.agent_id.as_deref(), Some("first-agent"));+ assert_eq!(app.agent_chat.tools_port, Some(12345), "the endpoint belongs to its conversation");+ assert!(app.agent_chat.items.iter().any(|i| matches!(i, Item::User { files, .. } if files.iter().any(|name| name == "sample.step"))));+ assert_eq!(texts(&app), ["first follow-up"]);+ assert!(app.agent_chat.stopped, "returning must not send the stopped queue");+ assert_eq!(first.prompts().len(), 1);+ assert!(app.agent_chat.items.iter().any(|i| matches!(i, Item::User { text, .. } if text == "first request")));+ assert!(!app.agent_chat.items.iter().any(|i| matches!(i, Item::User { text, .. } if text == "second request")));+ assert!(app.agent_chat.attach_view);++ // Closing an earlier tab shifts indices, but the surviving backend and draft stay together.+ crate::documents::close(&mut app, 0, true);+ assert_eq!(app.docs.active, 0);+ assert_eq!(app.agent_chat.input, "second draft");+ assert!(!app.agent_chat.stopped, "leaving an idle conversation does not stop a turn");+ send(&mut app, &ctx, "second continuation".into());+ assert_eq!(second.prompts().len(), 2, "the same backend retains this tab's context");+ crate::documents::close(&mut app, 0, true);+ assert!(app.agent_chat.items.is_empty() && app.agent_chat.backend.is_none());+ assert!(app.agent_chat.open && app.agent_chat.control_starter.is_some());+}++#[test]+fn leaving_during_startup_or_sign_in_keeps_the_unsent_message_for_send() {+ for state in [State::Starting, State::NeedsAuth] {+ let (mut app, script, ctx) = app_with_script();+ app.agent_chat.state = Some(state);+ app.agent_chat.add_file(attach::Attachment::imported("sample.step".into()));+ send(&mut app, &ctx, "waiting request".into());+ assert!(script.prompts().is_empty());+ assert!(app.agent_chat.queued.is_some());+ crate::documents::open_tab(&mut app, solidcraft_engine::Session::default()).unwrap();+ // Both events may have been buffered while the original tab was hidden.+ script.report(Event::AuthRequired { methods: Vec::new() });+ script.report(Event::Ready { agent: "scripted".into(), images: false });+ crate::documents::switch(&mut app, 0);+ poll(&mut app, &ctx);+ assert!(script.prompts().is_empty(), "returning must not send a startup or sign-in retry");+ assert!(app.agent_chat.queued.is_none());+ assert_eq!(texts(&app), ["waiting request"]);+ assert_eq!(app.agent_chat.pending[0].files[0].name, "sample.step");+ send_now(&mut app, &ctx);+ assert_eq!(script.prompts().len(), 1, "an explicit Send resumes the message");+ assert_eq!(app.agent_chat.items.iter().filter(|i| matches!(i, Item::User { text, .. } if text == "waiting request")).count(), 1);+ }+}++#[test]+fn a_late_sign_in_retry_or_permission_cannot_restart_a_departed_turn() {+ let (mut app, script, ctx) = app_with_script();+ send(&mut app, &ctx, "first request".into());+ crate::documents::open_tab(&mut app, solidcraft_engine::Session::default()).unwrap();+ script.report(Event::Permission {+ key: 7,+ title: "mcp__solidcraft__batch".into(),+ options: vec![PermissionOption { id: "allow".into(), name: "Allow".into(), kind: "allow_once".into() }],+ });+ ended(&script, "auth");+ script.report(Event::AuthRequired { methods: Vec::new() });+ script.report(Event::Ready { agent: "scripted".into(), images: false });+ crate::documents::switch(&mut app, 0);+ poll(&mut app, &ctx);+ assert!(script.calls().iter().any(|c| c == "permission: 7 None"), "late permission is cancelled even for our own tools");+ assert_eq!(app.agent_chat.waiting(), 0);+ assert_eq!(script.prompts().len(), 1, "a cancelled turn must not retry after sign-in");+ assert!(app.agent_chat.turn.is_none() && app.agent_chat.queued.is_none());+}++#[test]+fn programmatic_replacement_clears_the_conversation_and_invalidates_its_requests() {+ for command in ["file.new", "FILE.NEW"] {+ let (mut app, script, ctx) = app_with_script();+ let (tx, rx) = channel();+ app.agent_chat.tools_rx = Some(rx);+ send(&mut app, &ctx, "first request".into());+ let queued = ask(&tx, "engine.execute", boxed(0.0));+ pump_tools(&mut app);+ app.run(command, json!({})).unwrap();+ app.drain_control(&ctx);+ assert_eq!(queued.try_recv().unwrap()["ok"], false);+ assert!(app.agent_chat.items.is_empty() && app.agent_chat.backend.is_none());+ assert!(app.session.doc.features.is_empty() && app.session.undo.is_empty());+ assert!(script.calls().iter().any(|c| c == "cancel"));+ }+}++#[test]+fn a_script_resets_chat_only_after_a_replacement_succeeds() {+ for (steps, replaced) in [+ (json!([{"command": "missing.command"}, {"command": "file.new"}]), false),+ (json!([{"command": "file.new"}]), true),+ (json!([{"id": "FILE.NEW"}]), true),+ (json!([{"command": "file.new"}, {"command": "missing.command"}]), true),+ ] {+ for params in [steps.clone(), json!({"commands": steps})] {+ let (mut app, _script, ctx) = app_with_script();+ send(&mut app, &ctx, "first request".into());+ let (req, reply) = ControlRequest::new("engine.script", params);+ app.run_control(&ctx, req);+ assert!(reply.try_recv().is_ok());+ assert_eq!(app.agent_chat.backend.is_none(), replaced);+ assert_eq!(app.agent_chat.items.is_empty(), replaced);+ assert_eq!(app.agent_chat.turn.is_none(), replaced);+ }+ }+}++#[test]+fn leaving_a_tab_refuses_computation_and_export_replies() {+ // The export deliberately omits its path: even a worker's error must be replaced by+ // cancellation after leaving, without writing a file or echoing into another document.+ for params in [boxed(0.0), json!({"command": "file.export", "params": {}})] {+ let (mut app, tx) = app_in_a_turn();+ let ctx = crate::fonts::test_context();+ app.apply_off_thread = Some(std::time::Duration::ZERO);+ app.preferences.agent_off_thread = true;+ app.preferences.ai_permissions = agents::Mode::All;+ let reply = ask(&tx, "engine.execute", params);+ pump_tools(&mut app);+ app.drain_control(&ctx);+ assert!(app.control_job.is_some() || !app.control_answering.is_empty(), "the worker result waits for a later frame");+ crate::documents::open_tab(&mut app, solidcraft_engine::Session::default()).unwrap();+ let incoming = app.session.doc.clone();+ let log = app.session.log.clone();+ app.poll_control_jobs(&ctx);+ let response = reply.try_recv().expect("cancellation must not wait for the worker");+ assert_eq!(response["ok"], false);+ assert!(response["error"].as_str().is_some_and(|e| e.contains("document tab was left")));+ assert!(app.control_job.is_none() && app.control_answering.is_empty());+ assert!(Arc::ptr_eq(&app.session.doc, &incoming));+ assert_eq!(app.session.log, log);+ assert!(app.session.undo.is_empty());+ crate::documents::switch(&mut app, 0);+ assert!(app.session.doc.features.is_empty() && app.session.undo.is_empty());+ }+}++#[test]+fn leaving_a_tab_refuses_admitted_commands_animations_and_screenshots() {+ for animate in [false, true] {+ let (mut app, tx) = app_in_a_turn();+ let ctx = crate::fonts::test_context();+ app.ui.agent_cursor.show = animate;+ crate::scenario::publish_handle("toolbar:solid.box", egui::pos2(100.0, 100.0));+ app.ui.agent_cursor.speed = crate::agent_cursor::Speed::Times(1.0);+ let change = ask(&tx, "engine.execute", boxed(0.0));+ let shot = ask(&tx, "ui.screenshot", json!({}));+ pump_tools(&mut app);+ // Capture a request already waiting for a frame, as well as a queued command.+ let screenshot = app.control_held.pop_back().unwrap();+ app.run_control(&ctx, screenshot);+ assert_eq!(app.pending_shots.len(), 1);+ if animate {+ app.drain_control(&ctx);+ assert!(app.agent.busy(), "the command is waiting on cursor animation");+ }+ crate::documents::open_tab(&mut app, solidcraft_engine::Session::default()).unwrap();+ let other = app.session.doc.clone();+ app.drain_control(&ctx);+ crate::agent_cursor::step(&mut app, &ctx);+ app.collect_screenshots(&ctx);+ for reply in [change, shot] {+ let response = reply.try_recv().expect("cancelled requests answer without running");+ assert_eq!(response["ok"], false);+ assert!(response["error"].as_str().is_some_and(|e| e.contains("document tab was left")));+ }+ assert!(Arc::ptr_eq(&app.session.doc, &other));+ assert!(app.session.undo.is_empty() && app.pending_shots.is_empty());+ assert!(app.queued_shots.is_empty(), "a cancelled screenshot must not capture the incoming tab");+ crate::documents::switch(&mut app, 0);+ assert!(app.session.doc.features.is_empty() && app.session.undo.is_empty());+ // Adopting into a blank tab replaces the document and clears its old conversation.+ app.agent_chat.input = "discarded draft".into();+ crate::documents::adopt(&mut app, solidcraft_engine::Session::default());+ assert!(app.agent_chat.input.is_empty() && app.agent_chat.items.is_empty());+ }+}++#[test]+fn late_events_approvals_and_undo_stay_with_the_originating_document() {+ let (mut app, first, ctx) = app_with_script();+ let (tx, rx) = channel();+ app.agent_chat.tools_rx = Some(rx);+ send(&mut app, &ctx, "make two blocks".into());+ for x in [0.0, 20.0] {+ let reply = ask(&tx, "engine.execute", boxed(x));+ frame(&mut app);+ assert_eq!(reply.try_recv().unwrap()["ok"], true);+ }+ assert_eq!(app.session.undo.len(), 2);+ app.preferences.ai_permissions = agents::Mode::Ask;+ let held = ask(&tx, "engine.execute", boxed(40.0));+ pump_tools(&mut app);+ assert_eq!(app.agent_chat.waiting(), 1);+ crate::documents::open_tab(&mut app, solidcraft_engine::Session::default()).unwrap();+ assert_eq!(held.try_recv().unwrap()["ok"], false);+ assert_eq!(app.agent_chat.waiting(), 0);+ first.report(Event::Text { thought: false, text: "Stopped in the first design".into() });+ ended(&first, "cancelled");+ let late = ask(&tx, "engine.execute", boxed(60.0));+ frame(&mut app);+ assert!(app.agent_chat.items.is_empty());+ assert!(app.session.doc.features.is_empty() && app.session.undo.is_empty());+ assert!(matches!(late.try_recv(), Err(std::sync::mpsc::TryRecvError::Empty)));++ crate::documents::switch(&mut app, 0);+ frame(&mut app);+ assert_eq!(late.try_recv().unwrap()["ok"], false);+ assert_eq!(app.session.doc.features.len(), 2);+ assert_eq!(app.session.undo.len(), 1, "the outgoing turn merged only its own undo");+ let changes = app.agent_chat.items.iter().position(|i| matches!(i, Item::Changes { steps: 2, .. })).unwrap();+ assert!(app.agent_chat.items.iter().any(|i| matches!(i, Item::Agent { text, .. } if text == "Stopped in the first design")));+ undo_changes(&mut app, changes);+ assert!(app.session.doc.features.is_empty());+ crate::documents::switch(&mut app, 1);+ app.preferences.ai_features = false;+ poll(&mut app, &ctx);+ crate::documents::switch(&mut app, 0);+ assert!(app.agent_chat.backend.is_none(), "disabling AI stops hidden conversations too");+}+fn texts(app: &SolveApp) -> Vec<String> {app.agent_chat.pending.iter().map(|p| p.text.clone()).collect()}diff --git a/crates/ui-egui/src/agent_cursor.rs b/crates/ui-egui/src/agent_cursor.rsindex 028284f12e..1012ad2c88 100644--- a/crates/ui-egui/src/agent_cursor.rs+++ b/crates/ui-egui/src/agent_cursor.rs@@ -134,6 +134,7 @@ pub struct Job {reply: Sender<ControlResponse>,/// Screen position and registry label, kept together even when several commands share a panel.stops: VecDeque<(Pos2, &'static str)>,+ chat_turn: Option<std::sync::Arc<std::sync::atomic::AtomicBool>>,/// Seconds per glide and per click for this request (within [`TIME_BUDGET`] in all).glide: f64,click: f64,@@ -329,7 +330,8 @@ fn walk<'a>(v: &'a Value, key: Option<&'a str>, f: &mut dyn FnMut(Option<&'a str/// Take over a control request when the pointer should act it out first: returns the request/// back when it should simply run.-pub fn intercept(app: &mut SolveApp, method: &str, params: &Value, reply: &Sender<ControlResponse>) -> bool {+pub fn intercept(app: &mut SolveApp, req: &crate::control::ControlRequest) -> bool {+ let (method, params, reply) = (req.method.as_str(), &req.params, &req.reply);let s = app.ui.agent_cursor;if !s.show || params.get("animate").and_then(Value::as_bool) == Some(false) {return false;@@ -367,6 +369,7 @@ pub fn intercept(app: &mut SolveApp, method: &str, params: &Value, reply: &Sendemethod: method.to_string(),params: params.clone(),reply: reply.clone(),+ chat_turn: req.chat_turn.clone(),stops,glide,click,@@ -398,6 +401,12 @@ pub fn step(app: &mut SolveApp, ctx: &egui::Context) {ctx.request_repaint();}let Some(job) = app.agent.job.as_mut() else { return };+ if crate::control::chat_turn_cancelled(job.chat_turn.as_deref()) {+ if let Some(job) = app.agent.job.take() {+ let _ = job.reply.send(crate::control::cancelled_chat_response());+ }+ return;+ }let (glide, click) = (job.glide, job.click);ctx.request_repaint();let Some(&(to, _)) = job.stops.front() else {@@ -431,6 +440,10 @@ pub fn step(app: &mut SolveApp, ctx: &egui::Context) {/// Run the held request now (as a call without animation) and send its reply.fn finish(app: &mut SolveApp, ctx: &egui::Context) {let Some(job) = app.agent.job.take() else { return };+ if crate::control::chat_turn_cancelled(job.chat_turn.as_deref()) {+ let _ = job.reply.send(crate::control::cancelled_chat_response());+ return;+ }let mut params = job.params;params["animate"] = json!(false);let cmd = params.get("command").or(params.get("id")).and_then(Value::as_str).unwrap_or_default().to_string();@@ -606,8 +619,9 @@ mod tests {h.call("ui.agent_cursor", json!({"show": true, "speed": 1}));assert!(crate::scenario::handle_at("toolbar:solid.box").is_none());assert!(button("solid.box").is_some(), "the closed group is the pointer's target");- let (tx, rx) = std::sync::mpsc::channel();- assert!(intercept(&mut h.app, "engine.execute", &json!({"command":"solid.box", "params":{"length":10,"width":10,"height":10}}), &tx));+ let (req, rx) =+ crate::control::ControlRequest::new("engine.execute", json!({"command":"solid.box", "params":{"length":10,"width":10,"height":10}}));+ assert!(intercept(&mut h.app, &req));h.frames(3);assert!(h.widget("Box").is_some(), "the command must be identified before it executes");assert!(rx.try_recv().is_err());@@ -624,12 +638,12 @@ mod tests {let mut h = crate::scenario::Harness::new();h.call("ui.agent_cursor", json!({"show": true, "speed": 1}));assert_eq!(button("solid.box"), button("solid.sphere"));- let (tx, rx) = std::sync::mpsc::channel();let params = json!({"commands":[{"command":"solid.box","params":{"length":10,"width":10,"height":10}},{"command":"solid.sphere","params":{"center":[30,0,0],"radius":3}}]});- assert!(intercept(&mut h.app, "engine.batch", ¶ms, &tx));+ let (req, rx) = crate::control::ControlRequest::new("engine.batch", params);+ assert!(intercept(&mut h.app, &req));let mut seen = Vec::new();for _ in 0..120 {h.frame();diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rsindex 0cd7098b48..590a8689c7 100644--- a/crates/ui-egui/src/control.rs+++ b/crates/ui-egui/src/control.rs@@ -58,13 +58,33 @@ pub struct ControlRequest {pub reply: Sender<ControlResponse>,/// Set once the window starts on it; until then it waits its turn (`control.running`, #3654).pub started: std::sync::Arc<std::sync::atomic::AtomicBool>,+ /// Chat requests already admitted by the gate may outlive a tab switch. This turn's+ /// validity follows them through queues, computation and cursor animation.+ pub(crate) chat_turn: Option<std::sync::Arc<std::sync::atomic::AtomicBool>>,}impl ControlRequest {pub fn new(method: impl Into<String>, params: Value) -> (Self, std::sync::mpsc::Receiver<ControlResponse>) {let (tx, rx) = std::sync::mpsc::channel();- (Self { method: method.into(), params, reply: tx, started: Default::default() }, rx)+ (Self { method: method.into(), params, reply: tx, started: Default::default(), chat_turn: None }, rx)}++ pub(crate) fn refuse_cancelled_chat(&self) -> bool {+ if chat_turn_cancelled(self.chat_turn.as_deref()) {+ let _ = self.reply.send(cancelled_chat_response());+ true+ } else {+ false+ }+ }+}++pub(crate) fn chat_turn_cancelled(turn: Option<&std::sync::atomic::AtomicBool>) -> bool {+ turn.is_some_and(|active| !active.load(std::sync::atomic::Ordering::Relaxed))+}++pub(crate) fn cancelled_chat_response() -> Value {+ json!({"ok": false, "error": "not run: the agent chat turn ended or its document tab was left"})}pub enum Outcome {@@ -351,7 +371,20 @@ fn dispatch(app: &mut SolveApp, ctx: &egui::Context, method: &str, p: &Value) ->ok(json!(app.ui.agent_cursor))}"engine.script" => {- let r = app.session.run_script(p).map(|v| json!(v)).map_err(|e| e.to_string());+ let steps = p.as_array().or_else(|| p.get("commands").and_then(Value::as_array));+ let mut replaced = false;+ let r = app+ .session+ .run_script_each(p, &mut |i, _| {+ let id = steps.and_then(|steps| steps.get(i)).and_then(command).and_then(solidcraft_engine::find_command).map(|spec| spec.id);+ replaced |= matches!(id, Some("file.new" | "doc.open" | "doc.recover"));+ })+ .map(|v| json!(v))+ .map_err(|e| e.to_string());+ // A successful replacement still happened if a later script step failed.+ if replaced {+ crate::documents::reset_chat(app);+ }app.follow_view_request(false);wrap(r)}diff --git a/crates/ui-egui/src/control_job.rs b/crates/ui-egui/src/control_job.rsindex 3268e0afb7..2e7f6de851 100644--- a/crates/ui-egui/src/control_job.rs+++ b/crates/ui-egui/src/control_job.rs@@ -382,6 +382,9 @@ impl SolveApp {/// An export's or a reading's reply, from its copy, with the echo an export leaves when it/// runs here.fn answered(&mut self, job: ControlJob, reply: Option<Value>) {+ if job.req.refuse_cancelled_chat() {+ return;+ }let reply = reply.unwrap_or_else(|| json!({"ok": false, "error": format!("`{}` ended without a reply", job.label)}));let export = executed(&job.req.params).and_then(|(command, _)| spec_id(command)).is_some_and(|id| ANSWERED_ON_A_COPY.contains(&id));if reply["ok"] == true && export {@@ -396,6 +399,10 @@ impl SolveApp {if !self.control_answering.is_empty() {let mut i = 0;while i < self.control_answering.len() {+ if self.control_answering.get(i).is_some_and(|job| job.req.refuse_cancelled_chat()) {+ self.control_answering.remove(i);+ continue;+ }match self.control_answering.get(i).and_then(ControlJob::poll) {Some(reply) => {let job = self.control_answering.remove(i);@@ -407,6 +414,10 @@ impl SolveApp {ctx.request_repaint_after(std::time::Duration::from_millis(100));}let Some(job) = &self.control_job else { return };+ if job.req.refuse_cancelled_chat() {+ self.control_job = None;+ return;+ }if job.poll().is_none() {ctx.request_repaint_after(std::time::Duration::from_millis(100));return;diff --git a/crates/ui-egui/src/documents.rs b/crates/ui-egui/src/documents.rsindex bb7c8e86ed..c42fb528e0 100644--- a/crates/ui-egui/src/documents.rs+++ b/crates/ui-egui/src/documents.rs@@ -1,6 +1,7 @@//! Several open designs, as tabs in the application bar. The active design lives in the app as//! always (`app.session`, `app.cam`…); the others wait here with their own session (undo,-//! selection), camera and per-design view state, and are swapped in when their tab is picked.+//! selection), camera, agent conversation and per-design view state, and are swapped in when+//! their tab is picked.//! Closing a design with unsaved changes asks first, and so does quitting: one "save changes?"//! per design with unsaved changes ([`request_quit`]).@@ -26,6 +27,7 @@ pub struct DocSlot {pre_sketch_marker: Option<Option<usize>>,view: DocView,occurrence_move: Option<crate::browser::OccMove>,+ agent_chat: crate::agent_chat::AgentChat,}/// The per-design part of the UI state the session doesn't keep (what is hidden, shown or locked@@ -45,6 +47,7 @@ impl DocSlot {pre_sketch_marker: None,view: DocView::default(),occurrence_move: None,+ agent_chat: Default::default(),}}}@@ -96,7 +99,7 @@ fn put_view(app: &mut SolveApp, v: DocView) {}/// Put `slot` into the app and return what was there.-fn swap_in(app: &mut SolveApp, slot: DocSlot) -> DocSlot {+fn swap_in(app: &mut SolveApp, mut slot: DocSlot) -> DocSlot {if crate::render_workspace::active(app) {let _ = crate::render_workspace::enter(app, false);}@@ -114,6 +117,8 @@ fn swap_in(app: &mut SolveApp, slot: DocSlot) -> DocSlot {app.viewport.hover = None;app.menu.props = None;crate::sketch_attachment_ui::clear(app);+ crate::agent_chat::leave_document(app);+ app.agent_chat.swap_document(&mut slot.agent_chat);let out_rev = app.session.revision;let mut out = DocSlot {session: std::mem::replace(&mut app.session, slot.session),@@ -123,6 +128,7 @@ fn swap_in(app: &mut SolveApp, slot: DocSlot) -> DocSlot {pre_sketch_marker: std::mem::replace(&mut app.pre_sketch_marker, slot.pre_sketch_marker),view: take_view(app),occurrence_move: std::mem::replace(&mut app.tree.occurrence_move, slot.occurrence_move),+ agent_chat: slot.agent_chat,};// Only the displayed design owns the process-wide crash replay journal.app.session.crash_journal = out.session.crash_journal;@@ -209,6 +215,7 @@ pub fn active_is_blank(app: &SolveApp) -> bool {pub fn adopt(app: &mut SolveApp, session: Session) {if active_is_blank(app) {let rev = app.session.revision;+ reset_chat(app);crate::dialogs::cancel(app);app.tool = None;app.menu.props = None;@@ -291,6 +298,7 @@ pub fn close(app: &mut SolveApp, i: usize, force: bool) {app.docs.closing = None;if n <= 1 {// The last design: a blank one takes its place.+ reset_chat(app);if let Some(a) = app.autosave.as_mut().and_then(|a| a.active.take()) {a.discard();}@@ -324,6 +332,19 @@ pub fn close(app: &mut SolveApp, i: usize, force: bool) {}}+/// A replacement design starts a fresh conversation while retaining the window's chat services.+pub(crate) fn reset_chat(app: &mut SolveApp) {+ crate::agent_chat::leave_document(app);+ app.agent_chat.swap_document(&mut crate::agent_chat::AgentChat::default());+}++/// Hidden conversations must also stop when AI is disabled or the application quits.+pub(crate) fn disconnect_background_chats(app: &mut SolveApp, wait: bool) {+ for slot in app.docs.background_mut() {+ slot.agent_chat.disconnect_document(&mut slot.session, wait);+ }+}+/// Close several tabs (Close Other Tabs, Close All Tabs; #3055): each with unsaved changes asks/// "save changes?" in turn, the others close; Cancel keeps the tabs not closed yet.pub fn close_many(app: &mut SolveApp, mut tabs: Vec<usize>) {diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rsindex a7d51498b7..169b7b220e 100644--- a/crates/ui-egui/src/lib.rs+++ b/crates/ui-egui/src/lib.rs@@ -519,6 +519,7 @@ pub struct SolveApp {/// The agent chat panel (docs/design/in-app-agent-chat.md).pub agent_chat: agent_chat::AgentChat,pending_shots: Vec<(u64, Option<String>, std::sync::mpsc::Sender<Value>, f64)>,+ shot_chat_turns: std::collections::HashMap<u64, std::sync::Arc<std::sync::atomic::AtomicBool>>,queued_shots: Vec<(u64, f64, u32)>,shot_token: u64,styled: bool,@@ -645,6 +646,7 @@ impl SolveApp {control_answering: Vec::new(),agent: Default::default(),pending_shots: Vec::new(),+ shot_chat_turns: Default::default(),queued_shots: Vec::new(),shot_token: 0,styled: false,@@ -904,6 +906,7 @@ impl SolveApp {/// What follows a command's run, whether it ran here or on a worker (a save): its echo,/// the status line when it failed, what opening and saving update, and the toolbar tab.pub(crate) fn finish_command(&mut self, id: &str, r: &Result<Value, String>) {+ let id = solidcraft_engine::find_command(id).map_or(id, |spec| spec.id);match r {Ok(v) => {// Programmatic callers (the control channel, scripts) run outside a render@@ -922,6 +925,7 @@ impl SolveApp {prefs::apply_new_design(self);}if matches!(id, "file.new" | "doc.open" | "doc.recover") {+ documents::reset_chat(self);render_workspace::reset_document(self);dim_view::cancel();self.menu.props = None;@@ -1943,6 +1947,9 @@ impl SolveApp {// Held requests go first, in order, once nothing makes them wait.let held = if waits || shot_waits { None } else { self.control_held.pop_front() };let Some(req) = held.or_else(|| rx.as_ref().and_then(|rx| rx.try_recv().ok())) else { break };+ if req.refuse_cancelled_chat() {+ continue;+ }if shot_waits {if self.control_held.len() < MAX_HELD {self.control_held.push_back(req);@@ -1969,8 +1976,7 @@ impl SolveApp {ctx.request_repaint();continue;};- let reply = req.reply.clone();- if agent_cursor::intercept(self, &req.method, &req.params, &reply) {+ if agent_cursor::intercept(self, &req) {ctx.request_repaint();continue;}@@ -1986,6 +1992,9 @@ impl SolveApp {/// Run a control request here, now, and reply (or queue the screenshot it asks for).pub(crate) fn run_control(&mut self, ctx: &egui::Context, req: ControlRequest) {+ if req.refuse_cancelled_chat() {+ return;+ }let reply = req.reply.clone();match control::handle(self, ctx, &req) {control::Outcome::Done(v) => {@@ -1999,6 +2008,9 @@ impl SolveApp {control::Outcome::Screenshot { path } => {self.shot_token += 1;let token = self.shot_token;+ if let Some(turn) = req.chat_turn {+ self.shot_chat_turns.insert(token, turn);+ }self.queued_shots.push((token, now_ms() + 150.0, 0));self.pending_shots.push((token, path, reply, now_ms() + 8000.0));}@@ -2023,6 +2035,19 @@ impl SolveApp {}fn collect_screenshots(&mut self, ctx: &egui::Context) {+ // A screenshot requested in one tab must never return or save a frame of another.+ let chat_turns = &mut self.shot_chat_turns;+ let queued_shots = &mut self.queued_shots;+ self.pending_shots.retain(|(token, _, reply, _)| {+ if control::chat_turn_cancelled(chat_turns.get(token).map(std::sync::Arc::as_ref)) {+ chat_turns.remove(token);+ queued_shots.retain(|(queued, ..)| queued != token);+ let _ = reply.send(control::cancelled_chat_response());+ false+ } else {+ true+ }+ });if self.pending_shots.is_empty() && !issue_report::pending(self) {return;}@@ -2043,17 +2068,19 @@ impl SolveApp {issue_report::receive(self, token, image.clone());if let Some(i) = self.pending_shots.iter().position(|(t, ..)| *t == token) {let (_, path, reply, _) = self.pending_shots.remove(i);+ self.shot_chat_turns.remove(&token);let _ = reply.send(control::save_screenshot(&image, path.as_deref()));}}let now = now_ms();// Hidden while waiting: no frame is coming.let hidden = window_hidden(ctx);- self.pending_shots.retain(|(_, _, reply, deadline)| {+ self.pending_shots.retain(|(token, _, reply, deadline)| {if now < *deadline && !hidden {return true;}let _ = reply.send(json!({"ok": false, "error": "no frame was presented (window hidden?); use ui.render"}));+ self.shot_chat_turns.remove(token);false});}diff --git a/docs/agent-chat.md b/docs/agent-chat.mdindex faf5cd2ec5..61c701a010 100644--- a/docs/agent-chat.md+++ b/docs/agent-chat.md@@ -108,6 +108,12 @@ clears the files waiting on the chips too.## Typing while the agent works+Each design tab has its own conversation, agent session, draft, attachments and queued messages.+A new tab starts with an empty chat. Switching away stops the current turn and keeps its+completed changes in that design's undo history. Returning restores the conversation; queued+messages wait for **Send**. Closing a design closes its conversation. Conversations are kept+only while the tabs remain open.+The input stays enabled during a turn. **Enter** queues the message: it shows in the conversationas a **Queued** bubble that you can **Edit** or remove (×) until it is sent. Several queuedmessages go as one prompt, in order, when the turn ends normally.diff --git a/docs/design/in-app-agent-chat.md b/docs/design/in-app-agent-chat.mdindex c529f29c82..ab4ac616ef 100644--- a/docs/design/in-app-agent-chat.md+++ b/docs/design/in-app-agent-chat.md@@ -169,6 +169,35 @@ design from before the turn), relabelled "Agent chat: <message>". If the historythe meantime the start is found by the design it holds; if it's gone, nothing is merged. Theconversation shows the merged step with an Undo button while it's still the latest thing done.+### Document ownership++Each open design tab owns an `AgentChat`, including its transcript, backend session, agent+selection, sign-in retry, draft, attachments, pending messages and approval state. `DocSlot`+parks that state alongside its `Session`; switching restores both together. Panel visibility,+placement, agent discovery, endpoint model cache, settings dialogs and the desktop endpoint+starter remain window state. A new tab gets a fresh conversation. Closing a tab drops its+backend; closing the last tab or replacing its design (including programmatic New, Open and+Recover commands or scripts) clears its conversation.+Conversation state is in memory only and does not change the design file format.++Leaving a tab cancels its running turn, declines outstanding approvals, and merges completed+changes into that design's undo history before swapping sessions. Its backend conversation+remains available when the tab is selected again. Pending messages stay with that tab and wait+for Send. Hidden backends are not polled and their tool endpoints never feed the active tab's+gate. Prompts waiting for startup or sign-in also move to the explicit Send queue on leaving.+Late events are received only when their owning tab is selected again; requests without a+running turn are refused, and late permission questions from a stopped turn are cancelled.+Turning off AI or quitting stops hidden backends as well.++Every admitted tool request also carries a shared turn validity flag. Ending the turn or+leaving the tab invalidates it. The app checks it before dispatch, after deferred computation,+before an animated command applies, and before returning or saving a window screenshot. A+cancelled computation or export releases its UI waiting slot without waiting for its worker;+already started file writes are not rolled back. Requests already past the gate cannot apply+commands to or return inspection or screenshot data from the next tab, even if tab indices+change through closing. Ordinary external control requests retain their existing active-design+behavior.+### The agent's own toolsACP lets the client offer a file system and a terminal; the chat offers neither, and starts the@@ -214,7 +243,7 @@ returns the whole state, for tests and screenshots.| Area | Work ||---|---|-| Conversation | Diffs, history per design, resume (`session/load`) |+| Conversation | Diffs, persisted conversation history, resume (`session/load`) || Session controls | Model and mode pickers from `configOptions` / `modes`, slash commands || Auth | An embedded terminal or "open a terminal here" for terminal logins on each OS; logout || Discovery | Read the ACP registry; keychain-aware login check on macOS |