The all-in-one local AI studio for your desktop: chat, image and video generation and a coding agent in one free, open source app. Windows and Linux. No Docker, no terminal, no cloud required.
TypeScript agentai-chatai-studioall-in-onecoding-agentdesktop-appfluximage-generationlinuxllmlocal-ailocal-llmopen-sourceprivacyself-hostedstable-diffusionuncensoreduncensored-aivideo-generationwindows
fix(agent): execute_code haelt sich jetzt an Stop wie shell_execute (R2-44)
purplec390cca2e9fe
diff --git a/src-tauri/src/commands/agent.rs b/src-tauri/src/commands/agent.rsindex f2d64a87..81ef5421 100644--- a/src-tauri/src/commands/agent.rs+++ b/src-tauri/src/commands/agent.rs@@ -2,6 +2,7 @@ use crate::os_error;use std::fs;use std::path::PathBuf;use std::process::Stdio;+use std::sync::Mutex;use tauri::{AppHandle, Manager, State};@@ -383,6 +384,165 @@ mod path_tests {}}+/// R2-44: `execute_code` used to take no run id, so Stop had nothing to cancel+/// once the interpreter had started — same hole `shell_execute_cancel` closed+/// for the shell tool (see the comment there). This is the same fix, on its+/// own registry: code execution is always foreground here, no background+/// tasks, so it needs neither the task-list nor the stale-entry sweep the+/// shell registry carries.+#[derive(Default)]+struct RunningCode {+ pid: Option<u32>,+ cancelled: bool,+}+static RUNNING_CODE: once_cell::sync::Lazy<Mutex<std::collections::HashMap<String, RunningCode>>> =+ once_cell::sync::Lazy::new(Default::default);++fn code_register(call_id: &str) {+ RUNNING_CODE.lock().unwrap().entry(call_id.to_string()).or_default();+}++/// Attach the just-spawned pid. Returns `true` if a cancel already arrived+/// (the race the shell registry documents: abort can beat the spawn).+fn code_attach_pid(call_id: &str, pid: u32) -> bool {+ let mut karte = RUNNING_CODE.lock().unwrap();+ match karte.get_mut(call_id) {+ Some(eintrag) => {+ eintrag.pid = Some(pid);+ eintrag.cancelled+ }+ None => false,+ }+}++fn code_is_cancelled(call_id: &str) -> bool {+ RUNNING_CODE.lock().unwrap().get(call_id).map(|e| e.cancelled).unwrap_or(false)+}++fn code_unregister(call_id: &str) {+ RUNNING_CODE.lock().unwrap().remove(call_id);+}++fn code_mark_cancelled(call_id: &str) -> Option<u32> {+ let mut karte = RUNNING_CODE.lock().unwrap();+ let eintrag = karte.entry(call_id.to_string()).or_default();+ eintrag.cancelled = true;+ eintrag.pid+}++/// Abmelden beim Verlassen, an EINER Stelle — dieselbe Begruendung wie+/// `ShellSlot` in shell.rs: `execute_code_blocking` kehrt an mehreren Stellen+/// zurueck, eine Aufraeumzeile an jeder davon bliebe irgendwann an einer nicht+/// mehr stehen.+struct CodeSlot(Option<String>);+impl CodeSlot {+ fn new(call_id: Option<&str>) -> Self {+ let kennung = call_id.map(str::trim).filter(|s| !s.is_empty()).map(str::to_string);+ if let Some(id) = kennung.as_deref() {+ code_register(id);+ }+ Self(kennung)+ }+ fn id(&self) -> Option<&str> {+ self.0.as_deref()+ }+}+impl Drop for CodeSlot {+ fn drop(&mut self) {+ if let Some(id) = self.0.as_deref() {+ code_unregister(id);+ }+ }+}++/// Stop fuer einen laufenden `execute_code`. Unbekannte Kennungen sind KEIN+/// Fehler, wie bei `shell_execute_cancel`: der Lauf kann in derselben+/// Millisekunde fertig geworden sein.+#[tauri::command]+#[allow(non_snake_case)]+pub async fn execute_code_cancel(callId: String) -> Result<bool, String> {+ let pid = code_mark_cancelled(&callId);+ match pid {+ Some(p) => {+ tokio::task::spawn_blocking(move || super::shell::kill_tree(p))+ .await+ .map_err(|e| format!("Task join error: {}", e))?;+ Ok(true)+ }+ None => Ok(false),+ }+}++/// Same shape as shell.rs's `shell_cancel_*` tests, on the code-execution+/// registry: registration, the race between abort and spawn, and the empty-id+/// no-op. No stale-entry sweep here (unlike shell.rs) because there is no+/// background-task mode to age out.+#[cfg(test)]+mod code_cancel_tests {+ use super::*;++ #[test]+ fn ein_abbruch_vor_dem_start_bleibt_stehen() {+ let id = format!("code-test-{}", std::process::id());+ code_register(&id);+ assert_eq!(code_mark_cancelled(&id), None, "es gibt noch keine Prozesskennung");+ // Der Start liest den Merker beim Anhaengen der Kennung.+ assert!(code_attach_pid(&id, 4242), "der Start muss den Abbruch sehen");+ code_unregister(&id);+ }++ #[test]+ fn ein_abbruch_ohne_anmeldung_legt_den_merker_an() {+ let id = format!("code-test-{}", std::process::id() as u64 + 1);+ // R2-44: derselbe Wettlauf wie beim Shell-Werkzeug, der Abbruch kann+ // eintreffen, bevor `execute_code_blocking` registriert hat.+ assert_eq!(code_mark_cancelled(&id), None);+ code_register(&id); // darf den Merker NICHT ueberschreiben+ assert!(code_attach_pid(&id, 7));+ code_unregister(&id);+ }++ #[test]+ fn findet_den_laufenden_prozess() {+ let id = format!("code-test-{}", std::process::id() as u64 + 2);+ code_register(&id);+ assert!(!code_attach_pid(&id, 1234), "ohne Abbruch laeuft er weiter");+ assert!(!code_is_cancelled(&id));+ assert_eq!(code_mark_cancelled(&id), Some(1234), "die Prozesskennung kommt zurueck");+ assert!(code_is_cancelled(&id));+ code_unregister(&id);+ }++ #[test]+ fn ein_lauf_ohne_kennung_ist_unberuehrt() {+ // `CodeSlot::new(None)` (kein callId vom Aufrufer) darf nie etwas anmelden.+ let slot = CodeSlot::new(None);+ assert_eq!(slot.id(), None);+ assert!(!code_is_cancelled("gar-nicht-angemeldet"));+ }++ #[test]+ fn eine_leere_kennung_zaehlt_als_keine() {+ let slot = CodeSlot::new(Some(" "));+ assert_eq!(slot.id(), None, "eine reine Leerraum-Kennung haette sich angemeldet");+ }++ #[test]+ fn der_platz_meldet_sich_beim_verlassen_ab() {+ let id = format!("code-test-{}", std::process::id() as u64 + 3);+ {+ let slot = CodeSlot::new(Some(&id));+ code_attach_pid(&id, 31337);+ assert_eq!(code_mark_cancelled(&id), Some(31337));+ let _ = slot;+ }+ // Nach dem Drop ist die Karte weg: ein spaeterer Abbruch auf dieselbe+ // Kennung legt einen FRISCHEN, unbeteiligten Eintrag an.+ assert_eq!(code_mark_cancelled(&id), None);+ code_unregister(&id);+ }+}+/// Runs on the blocking pool: the poll loop below waits for the Python process/// for up to `timeout_ms`, and a sync #[command] would spend all of that on the/// Tauri main thread with the window frozen (same class as the installer tree and the@@ -394,10 +554,11 @@ pub async fn execute_code(timeout: Option<u64>,#[allow(non_snake_case)] chatId: Option<String>,#[allow(non_snake_case)] workingDirectory: Option<String>,+ #[allow(non_snake_case)] callId: Option<String>,) -> Result<serde_json::Value, String> {tauri::async_runtime::spawn_blocking(move || {let state = app.state::<AppState>();- execute_code_blocking(code, timeout, chatId, workingDirectory, &state)+ execute_code_blocking(code, timeout, chatId, workingDirectory, callId, &state)}).await.map_err(|e| format!("Code execution task failed to run: {e}"))?@@ -427,9 +588,13 @@ pub(crate) fn execute_code_blocking(timeout: Option<u64>,chatId: Option<String>,workingDirectory: Option<String>,+ callId: Option<String>,state: &State<'_, AppState>,) -> Result<serde_json::Value, String> {let timeout_ms = timeout.unwrap_or(30000);+ // R2-44: registered BEFORE spawn, same race the shell registry documents —+ // a cancel can arrive before the process exists at all.+ let slot = CodeSlot::new(callId.as_deref());// The handle is never read, only held: dropping it deletes the directory,// and it must outlive the interpreter that is running the script in it.@@ -462,6 +627,10 @@ pub(crate) fn execute_code_blocking(let mut child = cmd.spawn().map_err(|e| format!("Spawn Python: {}", os_error::english(&e)))?;+ // Attach the pid; if a cancel already arrived (raced the spawn above),+ // kill immediately instead of letting the poll loop run one lap first.+ let already_cancelled = slot.id().map(|id| code_attach_pid(id, child.id())).unwrap_or(false);+// Both pipes are drained on their own threads from here on. A script that// prints more than a pipe buffer would otherwise block on write and never// exit — the tool call ate the full timeout and returned nothing. Same@@ -469,11 +638,36 @@ pub(crate) fn execute_code_blocking(let (out_buf, out_done) = super::shell::drain(child.stdout.take().expect("stdout is piped"));let (err_buf, err_done) = super::shell::drain(child.stderr.take().expect("stderr is piped"));+ let cancelled_result = |stdout: String| {+ serde_json::json!({+ "stdout": stdout,+ "stderr": "Cancelled: the user stopped the run.",+ "exitCode": -1,+ "timedOut": false,+ "cancelled": true,+ })+ };++ if already_cancelled {+ super::shell::kill_tree(child.id());+ let _ = child.kill();+ let _ = child.wait();+ super::shell::settle(&out_done, &err_done, std::time::Duration::from_millis(200));+ return Ok(cancelled_result(super::shell::captured_text(&out_buf)));+ }+// Poll-based timeout since std::process::Child has no wait_timeoutlet start = std::time::Instant::now();let timeout_dur = std::time::Duration::from_millis(timeout_ms);loop {+ if slot.id().map(code_is_cancelled).unwrap_or(false) {+ super::shell::kill_tree(child.id());+ let _ = child.kill();+ let _ = child.wait();+ super::shell::settle(&out_done, &err_done, std::time::Duration::from_millis(200));+ return Ok(cancelled_result(super::shell::captured_text(&out_buf)));+ }match child.try_wait() {Ok(Some(status)) => {super::shell::settle(&out_done, &err_done, std::time::Duration::from_millis(500));diff --git a/src-tauri/src/commands/remote.rs b/src-tauri/src/commands/remote.rsindex 32a8fecc..2563ee0d 100644--- a/src-tauri/src/commands/remote.rs+++ b/src-tauri/src/commands/remote.rs@@ -823,7 +823,7 @@ async fn handle_agent_tool(let code = body.args.get("code").and_then(|v| v.as_str()).unwrap_or("").to_string();let timeout = body.args.get("timeout").and_then(|v| v.as_u64());if code.is_empty() { Err("code_execute needs a non-empty `code` argument.".into()) }- else { crate::commands::agent::execute_code_blocking(code, timeout, chat_id.clone(), None, &app_state) }+ else { crate::commands::agent::execute_code_blocking(code, timeout, chat_id.clone(), None, None, &app_state) }}"web_search" => {let query = body.args.get("query").and_then(|v| v.as_str()).unwrap_or("").to_string();diff --git a/src-tauri/src/main.rs b/src-tauri/src/main.rsindex e0442a45..8243e0e2 100644--- a/src-tauri/src/main.rs+++ b/src-tauri/src/main.rs@@ -507,6 +507,7 @@ fn main() {commands::tts::installed_piper_voices,// Agent tools (legacy)commands::agent::execute_code,+ commands::agent::execute_code_cancel,commands::agent::file_read,commands::agent::file_write,commands::agent::set_chat_workspace_override,diff --git a/src/api/mcp/__tests__/shell-honours-stop.test.ts b/src/api/mcp/__tests__/shell-honours-stop.test.tsindex dacff636..8e5a422a 100644--- a/src/api/mcp/__tests__/shell-honours-stop.test.ts+++ b/src/api/mcp/__tests__/shell-honours-stop.test.ts@@ -37,6 +37,9 @@ const backendCalls: { cmd: string; body: Record<string, unknown> }[] = []*/let laufenLassen: (() => void) | null = null+/** Same latch as `laufenLassen`, its own so the two tools don't interfere. */+let codeLaufenLassen: (() => void) | null = null+vi.mock('../../backend', () => ({backendCall: vi.fn(async (cmd: string, body: Record<string, unknown>) => {backendCalls.push({ cmd, body })@@ -45,6 +48,11 @@ vi.mock('../../backend', () => ({await new Promise<void>((r) => { laufenLassen = r })return { stdout: '', stderr: 'Cancelled: the user stopped the run.', exitCode: -1, timedOut: false, cancelled: true }}+ if (cmd === 'execute_code') {+ if (codeLaufenLassen === null) return { stdout: 'ran', stderr: '', exitCode: 0, timedOut: false }+ await new Promise<void>((r) => { codeLaufenLassen = r })+ return { stdout: '', stderr: 'Cancelled: the user stopped the run.', exitCode: -1, timedOut: false, cancelled: true }+ }if (cmd === 'shell_task_start') return { id: 'task-1' }if (cmd === 'shell_task_kill') return { ok: true, cancelled: true }return { ok: true }@@ -83,8 +91,10 @@ const ran = () => backendCalls.filter((c) => c.cmd === 'shell_execute')const killed = () => backendCalls.filter((c) => c.cmd === 'shell_task_kill')const cancelled = () => backendCalls.filter((c) => c.cmd === 'shell_execute_cancel')+const codeRan = () => backendCalls.filter((c) => c.cmd === 'execute_code')+const codeCancelled = () => backendCalls.filter((c) => c.cmd === 'execute_code_cancel')-beforeEach(() => { backendCalls.length = 0; laufenLassen = null })+beforeEach(() => { backendCalls.length = 0; laufenLassen = null; codeLaufenLassen = null })describe('shell_execute honours the run\'s Stop', () => {it('a command that has not started yet does not start', async () => {@@ -179,6 +189,39 @@ describe('shell_execute honours the run\'s Stop', () => {expect(cancelled()).toHaveLength(0)})+ it('R2-44: code_execute (retired name, redirected) is also cancelled once started', async () => {+ // `code_execute` has no entry in the registry itself, it only runs via+ // the retired-tool redirect (`runRetiredTool`), which used to drop the+ // signal `execute()` had already resolved from run/signal.+ codeLaufenLassen = () => {}+ const ctrl = new AbortController()+ const lauf = registry.execute('code_execute', { code: 'print(1)' }, 1, undefined, ctrl.signal)+ await new Promise((r) => setTimeout(r, 0))++ const gestartet = codeRan()+ expect(gestartet).toHaveLength(1)+ const kennung = (gestartet[0].body as { callId?: string }).callId+ expect(typeof kennung).toBe('string')+ expect(kennung).toBeTruthy()+ expect(codeCancelled()).toHaveLength(0)++ ctrl.abort()+ await new Promise((r) => setTimeout(r, 0))++ expect(codeCancelled()).toEqual([{ cmd: 'execute_code_cancel', body: { callId: kennung } }])++ codeLaufenLassen?.()+ await expect(lauf).resolves.toMatch(/cancelled/i)+ })++ it('NEGATIVE CONTROL: a code_execute run that finishes on its own is not cancelled', async () => {+ const ctrl = new AbortController()+ await registry.execute('code_execute', { code: 'print(1)' }, 1, undefined, ctrl.signal)+ ctrl.abort()+ await new Promise((r) => setTimeout(r, 0))+ expect(codeCancelled()).toHaveLength(0)+ })+it('der Vordergrundpfad schickt seine Kennung wirklich mit', () => {// Ohne sie haette die Rust-Seite nichts, worauf ein Abbruch zeigen koennte,// und `shell_execute_cancel` waere eine Zeile, die nie etwas findet.diff --git a/src/api/mcp/builtin-tools.ts b/src/api/mcp/builtin-tools.tsindex 778e40e2..fe310494 100644--- a/src/api/mcp/builtin-tools.ts+++ b/src/api/mcp/builtin-tools.ts@@ -860,22 +860,52 @@ async function executeShellExecute(return output || (err ? `stderr: ${err}` : 'Done.')}+/**+ * `execute_code`, with the same abort griff as `invokeShell` (R2-44): a+ * callId lets Stop reach a script that has already started, via+ * `execute_code_cancel` (Rust `commands/agent.rs`). Without a signal, nothing+ * changes: no callId, no listener, no cancel.+ */+async function invokeCode(+ payload: Record<string, unknown>,+ abort?: AbortSignal,+): Promise<ShellExecResult> {+ if (!abort) return backendCall<ShellExecResult>('execute_code', payload)+ const callId = uuid()+ const cancel = () => {+ void backendCall('execute_code_cancel', { callId }).catch(() => {+ // A failed cancel must not also fail the run with an error; the script+ // then falls back to its own timeout, same as before this fix.+ })+ }+ abort.addEventListener('abort', cancel, { once: true })+ try {+ return await backendCall<ShellExecResult>('execute_code', { ...payload, callId })+ } finally {+ abort.removeEventListener('abort', cancel)+ }+}+async function executeCodeExecute(args: ToolArgs,run?: AgentRunContext,signal?: AbortSignal,): Promise<string> {+ const abort = signal ?? run?.abortSignal// Same contract as shell_execute: a stopped run does not START new code.- if ((signal ?? run?.abortSignal)?.aborted) {+ if (abort?.aborted) {return 'Cancelled: the user stopped the run before this code ran.'}// Erreichbar nur noch über runRetiredTool, also OHNE die Prüfungen von// executeShellExecute — die eigene braucht es hier trotzdem.const bad = missingArgs('code_execute', args, 'code')if (bad) return bad- const data = await backendCall<ShellExecResult>('execute_code', { code: argString(args, 'code'), timeout: 30000, ...chatCtx(run) })+ const data = await invokeCode({ code: argString(args, 'code'), timeout: 30000, ...chatCtx(run) }, abort)const output = data.stdout || ''const err = data.stderr || ''+ // Vor `timedOut` geprueft, wie im Shell-Werkzeug: der Abbruch ist die+ // genauere Auskunft.+ if (data.cancelled) return 'Cancelled: the user stopped the run.'if (data.timedOut) return `Timed out.\n${err}`if (data.exitCode && data.exitCode !== 0) return `Error (${data.exitCode}):\n${err || output}`return output || (err ? `stderr: ${err}` : 'Done.')@@ -1707,7 +1737,7 @@ const RETIRED_HINT: Record<string, string> = {shell_task_list: 'shell_execute with task: "list"',}-const RETIRED_EXECUTORS: Record<string, (args: ToolArgs, run?: AgentRunContext) => Promise<string>> = {+const RETIRED_EXECUTORS: Record<string, (args: ToolArgs, run?: AgentRunContext, signal?: AbortSignal) => Promise<string>> = {git_status: executeGitStatus,git_log: executeGitLog,git_diff: executeGitDiff,@@ -1749,6 +1779,7 @@ export async function runRetiredTool(name: string,args: ToolArgs,run?: AgentRunContext,+ signal?: AbortSignal,): Promise<string | null> {const exec = RETIRED_EXECUTORS[name]if (!exec) return null@@ -1757,7 +1788,10 @@ export async function runRetiredTool(if (isReadOnlyShellTurn(run) && RETIRED_MUTATING_NAMES.has(name)) {return `Refused: this turn is read-only (/review, Code-Review Mode or Plan mode); ${name} changes state.`}- const result = await exec(args, run)+ // R2-44: the registry's own `execute()` receives a signal, but the retired-+ // name redirect used to drop it here, so a retired tool (code_execute via+ // this path) never saw Stop except through run.abortSignal.+ const result = await exec(args, run, signal)const hint = RETIRED_HINT[name]return hint ? `${result}\n\n(Note: ${name} is retired, next time use ${hint}.)` : result}diff --git a/src/api/mcp/tool-registry.ts b/src/api/mcp/tool-registry.tsindex 1ade4040..af80145c 100644--- a/src/api/mcp/tool-registry.ts+++ b/src/api/mcp/tool-registry.ts@@ -82,14 +82,14 @@ export class ToolRegistry {* Warnung weg.*/private retiredRunner:- | ((name: string, args: ToolArgs, run?: AgentRunContext) => Promise<string | null>)+ | ((name: string, args: ToolArgs, run?: AgentRunContext, signal?: AbortSignal) => Promise<string | null>)| null = null// ── Registration ──────────────────────────────────────────────/** Siehe `retiredRunner`. Wird von registerBuiltinTools() verdrahtet. */setRetiredRunner(- run: (name: string, args: ToolArgs, run?: AgentRunContext) => Promise<string | null>,+ run: (name: string, args: ToolArgs, run?: AgentRunContext, signal?: AbortSignal) => Promise<string | null>,) {this.retiredRunner = run}@@ -239,7 +239,7 @@ export class ToolRegistry {// model that knows git_status from its context must not burn the step// on "Unknown tool". Der Redirect kommt über setRetiredRunner herein// (siehe `retiredRunner`) statt über einen Rück-Import auf builtin-tools.- const redirected = this.retiredRunner ? await this.retiredRunner(name, args, run) : null+ const redirected = this.retiredRunner ? await this.retiredRunner(name, args, run, abort) : nullif (redirected !== null) return redirectedreturn `Error: Unknown tool "${name}"`}