SolidCraft: an open-source parametric 3D CAD application built in pure Rust. Desktop, web, and automation through MCP.
Assistant: recover when an agent ignores Stop (#10800) (#10916)
Colin Faulkinghamad2388208052
diff --git a/assets/locales/pending/agent-cancel-timeout.json b/assets/locales/pending/agent-cancel-timeout.jsonnew file mode 100644index 0000000000..d0bc63647f--- /dev/null+++ b/assets/locales/pending/agent-cancel-timeout.json@@ -0,0 +1,10 @@+{+ "ar": { "ui.agent_chat_cancel_timeout": "لم يستجب الوكيل لطلب الإيقاف، فتم قطع الاتصال به. أعد الاتصال للمتابعة." },+ "de": { "ui.agent_chat_cancel_timeout": "Der Agent hat nicht auf Stopp reagiert und wurde getrennt. Zum Fortfahren erneut verbinden." },+ "en": { "ui.agent_chat_cancel_timeout": "The agent did not respond to Stop and was disconnected. Reconnect to continue." },+ "he": { "ui.agent_chat_cancel_timeout": "הסוכן לא הגיב לבקשת העצירה ונותק. יש להתחבר מחדש כדי להמשיך." },+ "ja": { "ui.agent_chat_cancel_timeout": "エージェントが停止要求に応答しなかったため、接続を切断しました。続行するには再接続してください。" },+ "ko": { "ui.agent_chat_cancel_timeout": "에이전트가 중지 요청에 응답하지 않아 연결이 끊어졌습니다. 계속하려면 다시 연결하세요." },+ "vi": { "ui.agent_chat_cancel_timeout": "Tác nhân không phản hồi yêu cầu Dừng nên đã bị ngắt kết nối. Hãy kết nối lại để tiếp tục." },+ "zh": { "ui.agent_chat_cancel_timeout": "代理未响应停止请求,已断开连接。请重新连接以继续。" }+}diff --git a/crates/ui-egui/src/agent_chat/acp_client.rs b/crates/ui-egui/src/agent_chat/acp_client.rsindex 6b453964c8..021eba0f5c 100644--- a/crates/ui-egui/src/agent_chat/acp_client.rs+++ b/crates/ui-egui/src/agent_chat/acp_client.rs@@ -3,6 +3,7 @@//! sign-in). The panel sees only [`Event`]s.use std::collections::HashMap;+use std::time::{Duration, Instant};use serde_json::{Value, json};@@ -21,6 +22,9 @@ enum Pending {SetConfig,}+/// Give a cancelled prompt time to finish before disconnecting an unresponsive agent.+const CANCEL_GRACE: Duration = Duration::from_secs(5);+/// Variables the agent doesn't inherit: a control token set for the app's own `--control` port/// would otherwise reach the agent and outrank the chat endpoint's own token file.const ENV_REMOVE: &[&str] = &["SOLIDCRAFT_CONTROL_TOKEN"];@@ -41,6 +45,7 @@ pub struct AcpBackend {/// Open permission questions: our key → the agent's request id.permissions: HashMap<u64, Value>,next_key: u64,+ cancelling: Option<(u64, Instant)>,exited: bool,config_pending: Option<(u64, String)>,modern_config: bool,@@ -68,6 +73,7 @@ impl AcpBackend {auth: Vec::new(),permissions: HashMap::new(),next_key: 0,+ cancelling: None,exited: false,config_pending: None,modern_config: false,@@ -93,6 +99,9 @@ impl AcpBackend {match msg {Incoming::Reply { id, result } => {let Some(what) = self.pending.remove(&id) else { return };+ if self.cancelling.is_some_and(|(request, _)| request == id) {+ self.cancelling = None;+ }match (what, result) {(Pending::Initialize, Ok(v)) => {self.agent = acp::agent_info(&v);@@ -104,6 +113,12 @@ impl AcpBackend {}(Pending::SessionNew, Ok(v)) => match v.get("sessionId").and_then(Value::as_str) {Some(s) => {+ // New chat has opened successfully: retire the old turn before Ready.+ // Its late reply and cancellation deadline must not end the new turn.+ if let Some((request, _)) = self.cancelling.take() {+ self.pending.remove(&request);+ out.push(Event::TurnEnded { reason: "cancelled".into() });+ }self.session = Some(s.to_string());match acp::config_options(&v) {acp::ConfigParse::Snapshot(options) => {@@ -198,10 +213,17 @@ impl AcpBackend {Incoming::Ignored => {}}}-}-impl ChatBackend for AcpBackend {- fn poll(&mut self) -> Vec<Event> {+ fn finish_exit(&mut self, tail: Vec<String>) -> Event {+ self.exited = true;+ self.session = None;+ self.pending.clear();+ self.cancelling = None;+ self.config_pending = None;+ Event::Exited { tail }+ }++ fn poll_at(&mut self, now: Instant) -> Vec<Event> {let mut out = Vec::new();if self.exited {return out;@@ -214,18 +236,25 @@ impl ChatBackend for AcpBackend {}}Ok(FromAgent::Exited(tail)) => {- self.exited = true;- self.session = None;- self.pending.clear();- self.config_pending = None;- out.push(Event::Exited { tail });+ out.push(self.finish_exit(tail));break;}Err(_) => break,}}+ // Drain replies first: an acknowledgement already waiting must keep the connection.+ if self.cancelling.is_some_and(|(_, started)| now.saturating_duration_since(started) >= CANCEL_GRACE) {+ self.proc.shutdown(false);+ out.push(self.finish_exit(vec![crate::i18n::tr("ui.agent_chat_cancel_timeout").to_string()]));+ }out}+}++impl ChatBackend for AcpBackend {+ fn poll(&mut self) -> Vec<Event> {+ self.poll_at(Instant::now())+ }fn prompt(&mut self, parts: &[PromptPart]) {if let Some(s) = self.session.clone() {@@ -240,6 +269,11 @@ impl ChatBackend for AcpBackend {}if let Some(s) = &self.session {self.proc.send(&acp::notification("session/cancel", json!({"sessionId": s})));+ // Repeated Stop presses must not postpone the fallback. An idle session needs none.+ if self.cancelling.is_none() {+ self.cancelling =+ self.pending.iter().find_map(|(&id, request)| (*request == Pending::Prompt).then_some(id)).map(|id| (id, Instant::now()));+ }}}@@ -343,6 +377,75 @@ mod tests {use super::*;use crate::agent_chat::backend::StartContext;+ fn ready_backend() -> Result<AcpBackend, String> {+ let ctx = StartContext { cwd: std::env::temp_dir(), bridge: None, tools: None, wake: Box::new(|| {}) };+ let mut backend = AcpBackend::start(&["sh".into(), "-c".into(), "cat >/dev/null".into()], ctx)?;+ let mut events = Vec::new();+ backend.handle(Incoming::Reply { id: 1, result: Ok(json!({"agentInfo":{"name":"fake"}})) }, &mut events);+ backend.handle(Incoming::Reply { id: 2, result: Ok(json!({"sessionId":"s1"})) }, &mut events);+ Ok(backend)+ }++ #[test]+ fn an_unresponsive_cancel_disconnects_the_agent() {+ let mut backend = ready_backend().unwrap();+ backend.prompt(&[PromptPart::Text("stalled search".into())]);+ backend.cancel();+ let started = backend.cancelling.unwrap().1;+ assert!(backend.poll_at(started + CANCEL_GRACE - Duration::from_millis(1)).is_empty());+ backend.cancel();+ let events = backend.poll_at(started + CANCEL_GRACE);+ assert!(matches!(events.as_slice(), [Event::Exited { .. }]), "Stop must not wait indefinitely: {events:?}");+ assert!(backend.pid().is_none());+ assert!(backend.session.is_none() && backend.pending.is_empty());+ assert!(backend.poll().is_empty(), "the exit is reported only once");+ }++ #[test]+ fn a_cancelled_prompt_reply_keeps_the_connection() {+ for reply in [Ok(json!({"stopReason":"cancelled"})), Err((-32603, "operation aborted".into()))] {+ let mut backend = ready_backend().unwrap();+ backend.prompt(&[PromptPart::Text("search".into())]);+ let request = backend.next_id;+ backend.cancel();+ let mut events = Vec::new();+ backend.handle(Incoming::Reply { id: request, result: reply }, &mut events);+ assert!(events.iter().any(|e| matches!(e, Event::TurnEnded { .. })));+ assert!(backend.poll_at(Instant::now() + CANCEL_GRACE).is_empty());+ assert!(backend.pid().is_some() && !backend.exited);+ backend.shutdown(true);+ }+ }++ #[test]+ fn cancelling_an_idle_session_does_not_disconnect_it() {+ let mut backend = ready_backend().unwrap();+ backend.cancel();+ assert!(backend.poll_at(Instant::now() + CANCEL_GRACE).is_empty());+ assert!(backend.pid().is_some() && !backend.exited);+ backend.shutdown(true);+ }++ #[test]+ fn a_new_session_retires_the_old_cancelled_prompt() {+ let mut backend = ready_backend().unwrap();+ backend.prompt(&[PromptPart::Text("old search".into())]);+ let old_prompt = backend.next_id;+ backend.cancel();+ ChatBackend::new_session(&mut backend);+ let mut events = Vec::new();+ backend.handle(Incoming::Reply { id: backend.next_id, result: Ok(json!({"sessionId":"s2"})) }, &mut events);+ assert!(matches!(events.first(), Some(Event::TurnEnded { reason }) if reason == "cancelled"));+ assert!(matches!(events.last(), Some(Event::Ready { .. })));+ backend.prompt(&[PromptPart::Text("new search".into())]);+ assert!(backend.poll_at(Instant::now() + CANCEL_GRACE).is_empty(), "a new session has no stale cancellation deadline");+ backend.cancel();+ events.clear();+ backend.handle(Incoming::Reply { id: old_prompt, result: Ok(json!({"stopReason":"cancelled"})) }, &mut events);+ assert!(events.is_empty(), "an old reply must not end the new turn or clear its cancellation deadline");+ assert!(matches!(backend.poll_at(Instant::now() + CANCEL_GRACE).as_slice(), [Event::Exited { .. }]));+ }+fn snapshot(session: &str, value: &str) -> Value {json!({"sessionId":session,"configOptions":[{"id":"provider.model","category":"model","name":"Model","type":"select","currentValue":value,"options":[{"value":"fast","name":"Fast"},{"value":"smart","name":"Smart"}]}]})}diff --git a/crates/ui-egui/src/agent_chat/mod.rs b/crates/ui-egui/src/agent_chat/mod.rsindex 952fd63ccf..8a9a7b6848 100644--- a/crates/ui-egui/src/agent_chat/mod.rs+++ b/crates/ui-egui/src/agent_chat/mod.rs@@ -834,6 +834,13 @@ impl AgentChat {self.clear_config();self.state = Some(if matches!(self.state(), State::Starting | State::Failed) { State::Failed } else { State::Exited });self.steering = false;+ for item in &mut self.items {+ if let Item::Tool { status, .. } = item+ && !matches!(status, Some(ToolStatus::Completed | ToolStatus::Failed))+ {+ *status = Some(ToolStatus::Failed);+ }+ }let last: Vec<String> = tail.into_iter().rev().take(6).collect::<Vec<_>>().into_iter().rev().collect();let detail = if last.is_empty() { String::new() } else { format!("\n{}", last.join("\n")) };self.notice(format!("{}{detail}", tr("ui.agent_chat_exited")), true);diff --git a/crates/ui-egui/src/agent_chat/tests.rs b/crates/ui-egui/src/agent_chat/tests.rsindex 7040dd8913..18aa273c09 100644--- a/crates/ui-egui/src/agent_chat/tests.rs+++ b/crates/ui-egui/src/agent_chat/tests.rs@@ -1127,6 +1127,51 @@ fn stop_keeps_the_queue() {assert!(app.agent_chat.pending.is_empty());}+#[test]+fn an_unresponsive_cancel_exit_keeps_the_queue_and_completed_changes() {+ let (mut app, script, ctx) = app_with_script();+ let (tx, rx) = channel();+ app.agent_chat.tools_rx = Some(rx);+ let before = app.session.doc.clone();+ send(&mut app, &ctx, "two boxes".into());+ let replies: Vec<_> = [0.0, 20.0].into_iter().map(|x| ask(&tx, "engine.execute", boxed(x))).collect();+ frame(&mut app);+ for reply in replies {+ assert_eq!(reply.recv_timeout(std::time::Duration::from_secs(30)).unwrap()["ok"], true);+ }+ let completed = app.session.doc.clone();+ let statuses = [Some(ToolStatus::Completed), Some(ToolStatus::Failed), Some(ToolStatus::Pending), Some(ToolStatus::InProgress), None];+ for (id, status) in statuses.into_iter().enumerate() {+ script.report(Event::Tool { id: id.to_string(), title: Some("search".into()), kind: None, status, input: None, output: None });+ }+ poll(&mut app, &ctx);+ send(&mut app, &ctx, "later".into());+ cancel(&mut app);+ script.report(Event::Exited { tail: vec![tr("ui.agent_chat_cancel_timeout").to_string()] });+ poll(&mut app, &ctx);+ assert_eq!(app.agent_chat.state(), State::Exited);+ assert!(app.agent_chat.backend.is_none() && app.agent_chat.turn.is_none());+ assert_eq!(texts(&app), ["later"]);+ assert_eq!(script.prompts().len(), 1, "disconnect must not send the queue");+ assert!(Arc::ptr_eq(&app.session.doc, &completed), "completed changes stay in the design");+ let statuses: Vec<_> = app+ .agent_chat+ .items+ .iter()+ .filter_map(|item| match item {+ Item::Tool { status, .. } => Some(*status),+ _ => None,+ })+ .collect();+ assert_eq!(+ statuses,+ [Some(ToolStatus::Completed), Some(ToolStatus::Failed), Some(ToolStatus::Failed), Some(ToolStatus::Failed), Some(ToolStatus::Failed)]+ );+ let changes = app.agent_chat.items.iter().rposition(|i| matches!(i, Item::Changes { steps: 2, .. })).expect("the completed changes are grouped");+ undo_changes(&mut app, changes);+ assert!(Arc::ptr_eq(&app.session.doc, &before), "the completed changes still undo together");+}+/// Send now: cancel first, the prompt only after the agent has ended the cancelled turn, with a/// note that the previous step was interrupted (shown without it in the conversation).#[test]diff --git a/docs/agent-chat.md b/docs/agent-chat.mdindex 5a3f31b1a5..ab6ea43d00 100644--- a/docs/agent-chat.md+++ b/docs/agent-chat.md@@ -167,7 +167,9 @@ messages go as one prompt, in order, when the turn ends normally.short note that the agent's previous step was interrupted. What the interrupted message changedundoes as one step, like any other message.- **Stop** (the square next to the input, or **Esc** in the input) stops the agent and keeps- the queue: the bubbles wait for **Send**.+ the queue: the bubbles wait for **Send**. If an external ACP agent does not finish its cancelled+ prompt within five seconds, SolidCraft disconnects it and stops its process in the background.+ Completed design changes stay undoable, and the queue stays put. Reconnect to start a new agent session.- **New chat** (the header button, **Ctrl+Shift+L** / **Cmd+Shift+L** with the chat focused)stops what runs, clears the conversation, the queue and the files on the chips, and starts afresh session on the same agent, keeping the agent and its mode. It asks first when a message