Skip to content

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.

fix(shell): Stop faellt jetzt auch einen schon gestarteten Befehl

purple35059ff0d120
diff --git a/src-tauri/src/commands/bg_tasks.rs b/src-tauri/src/commands/bg_tasks.rs
index 30102b52..6a475460 100644
--- a/src-tauri/src/commands/bg_tasks.rs
+++ b/src-tauri/src/commands/bg_tasks.rs
@@ -1201,6 +1201,10 @@ mod foreground_parity_tests {
None,
None,
None,
+ // Keine Abbruchkennung: dieser Vergleich prueft die AUSGABE der
+ // beiden Wege, nicht den Stop. Der hat seine eigenen Tests in
+ // commands/shell.rs.
+ None,
)
.await
.expect("the foreground shell tool ran");
diff --git a/src-tauri/src/commands/remote.rs b/src-tauri/src/commands/remote.rs
index 630fd7a0..9c1d3285 100644
--- a/src-tauri/src/commands/remote.rs
+++ b/src-tauri/src/commands/remote.rs
@@ -928,7 +928,12 @@ async fn handle_agent_tool(
let timeout = body.args.get("timeout").and_then(|v| v.as_u64());
let shell = body.args.get("shell").and_then(|v| v.as_str()).map(String::from);
let stdin = body.args.get("stdin").and_then(|v| v.as_str()).map(String::from);
- crate::commands::shell::shell_execute(command, None, cwd, timeout, shell, stdin, chat_id.clone(), None).await
+ // `call_id` ist None: die Fernbruecke hat keinen Kanal, ueber
+ // den ein Abbruch zurueckkaeme. Ohne Kennung ist der Befehl
+ // nicht abbrechbar, und das ist ehrlicher als eine Kennung, die
+ // niemand je ruft. Der Weg dahin ist derselbe wie im Fenster:
+ // ein `shell_execute_cancel` in der Fernliste.
+ crate::commands::shell::shell_execute(command, None, cwd, timeout, shell, stdin, chat_id.clone(), None, None).await
}
}
"system_info" => crate::commands::system::system_info(),
diff --git a/src-tauri/src/commands/shell.rs b/src-tauri/src/commands/shell.rs
index ccd9f31e..6308c76c 100644
--- a/src-tauri/src/commands/shell.rs
+++ b/src-tauri/src/commands/shell.rs
@@ -224,6 +224,156 @@ pub(crate) fn kill_tree(root: u32) {
}
}
+// ── Stop erreicht einen schon gestarteten Befehl ──────────────────────────
+//
+// Bis heute konnte es das nicht, und der Kommentar an `executeShellExecute`
+// auf der anderen Seite der Bruecke sagte es offen: "the bridge has NO cancel
+// for it. Rust `shell_execute` takes no run id and there is no
+// shell_execute_cancel, so the child keeps running to its own timeout. The
+// executor stops WAITING on it, which ends the run and the UI, but the process
+// survives."
+//
+// Der Ausfuehrer hoert also auf zu warten, die Oberflaeche wird ruhig, und der
+// Befehl laeuft zu Ende: ein Build, ein Testlauf, ein Skript, das Dateien
+// anfasst, bis zu zwei Minuten nachdem der Mensch Stop gedrueckt hat. Das ist
+// dieselbe Sorte Luege wie ein Stopp-Knopf, der nichts abbricht, nur auf der
+// Maschine des Nutzers statt auf der Rechnung.
+//
+// Was fehlte, war eine KENNUNG: ohne sie hat der Abbruch nichts, worauf er
+// zeigen koennte. Der Aufrufer schickt jetzt eine mit, diese Karte haelt die
+// zugehoerige Prozesskennung, und `shell_execute_cancel` faellt den Baum mit
+// derselben `kill_tree`, die auch die Zeitgrenze benutzt.
+//
+// Der Wettlauf ist mitgedacht und der Grund fuer `cancelled` neben `pid`: der
+// Abbruch kann eintreffen, BEVOR der Prozess ueberhaupt existiert. Dann gibt es
+// keine Prozesskennung zu toeten, und ohne Merker liefe der Befehl los,
+// nachdem er abgebrochen wurde. Die Karte merkt sich den Abbruch also auch
+// ohne pid, und der Start sieht danach.
+
+/// Ein Vordergrundbefehl, solange er laeuft. `pid` fehlt im Fenster zwischen
+/// Anmelden und Start.
+#[derive(Default)]
+struct RunningShell {
+ pid: Option<u32>,
+ cancelled: bool,
+}
+
+static RUNNING_SHELLS: once_cell::sync::Lazy<Mutex<std::collections::HashMap<String, RunningShell>>> =
+ once_cell::sync::Lazy::new(Default::default);
+
+/// Diesen Lauf anmelden, bevor gestartet wird. Ein Abbruch, der schon da war,
+/// bleibt stehen — sonst gewaenne der Start den Wettlauf gegen den Stop.
+fn shell_register(call_id: &str) {
+ let mut karte = RUNNING_SHELLS.lock().unwrap();
+ karte.entry(call_id.to_string()).or_default();
+}
+
+/// Die Prozesskennung nachtragen. Gibt `true`, wenn inzwischen abgebrochen
+/// wurde: dann ist der eben gestartete Prozess sofort wieder zu toeten.
+fn shell_attach_pid(call_id: &str, pid: u32) -> bool {
+ let mut karte = RUNNING_SHELLS.lock().unwrap();
+ match karte.get_mut(call_id) {
+ Some(eintrag) => {
+ eintrag.pid = Some(pid);
+ eintrag.cancelled
+ }
+ // Nicht angemeldet heisst: dieser Lauf traegt keine Kennung, er ist
+ // also auch nicht abbrechbar. Kein Grund, ihn zu toeten.
+ None => false,
+ }
+}
+
+fn shell_is_cancelled(call_id: &str) -> bool {
+ RUNNING_SHELLS.lock().unwrap().get(call_id).map(|e| e.cancelled).unwrap_or(false)
+}
+
+fn shell_unregister(call_id: &str) {
+ RUNNING_SHELLS.lock().unwrap().remove(call_id);
+}
+
+/// Abmelden beim Verlassen, an EINER Stelle.
+///
+/// `shell_execute_sync` kehrt an sechs Stellen zurueck, darunter zwei
+/// Fehlerpfade mit `?`. Eine Aufraeumzeile, die an jeder davon stehen muss,
+/// steht irgendwann an einer nicht mehr, und der Eintrag bliebe fuer den Rest
+/// der Sitzung liegen: eine Karte, die nur waechst, und eine Kennung, die ein
+/// spaeterer Abbruch auf einen laengst toten Prozess zeigen laesst. Dieselbe
+/// Begruendung wie bei `lib/run-slot.ts` auf der anderen Seite.
+struct ShellSlot(Option<String>);
+
+impl ShellSlot {
+ 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() {
+ shell_register(id);
+ }
+ Self(kennung)
+ }
+
+ fn id(&self) -> Option<&str> {
+ self.0.as_deref()
+ }
+}
+
+impl Drop for ShellSlot {
+ fn drop(&mut self) {
+ if let Some(id) = self.0.as_deref() {
+ shell_unregister(id);
+ }
+ }
+}
+
+/// Abbrechen. Gibt die Prozesskennung zurueck, falls der Prozess schon lebt.
+///
+/// Der Eintrag wird ANGELEGT, wenn es ihn noch nicht gibt: ein Abbruch, der
+/// den Start ueberholt, muss stehen bleiben, bis der Start ihn liest.
+fn shell_mark_cancelled(call_id: &str) -> Option<u32> {
+ let mut karte = RUNNING_SHELLS.lock().unwrap();
+ let eintrag = karte.entry(call_id.to_string()).or_default();
+ eintrag.cancelled = true;
+ eintrag.pid
+}
+
+/// Was ein abgebrochener Befehl zurueckgibt.
+///
+/// Eigenes Feld `cancelled` und NICHT `timedOut`: eine Zeitgrenze ist etwas,
+/// das dem Befehl passiert ist, ein Abbruch etwas, das der Mensch getan hat.
+/// Auf der anderen Seite haengt daran, welchen Satz das Modell zu lesen bekommt.
+/// `exitCode` bleibt -1, wie bei der Zeitgrenze auch, denn einen echten gibt es
+/// nicht mehr.
+fn cancelled_result(stdout: String) -> serde_json::Value {
+ serde_json::json!({
+ "stdout": stdout,
+ "stderr": "Cancelled: the user stopped the run.",
+ "exitCode": -1,
+ "timedOut": false,
+ "cancelled": true,
+ })
+}
+
+/// Stop fuer einen laufenden `shell_execute`.
+///
+/// Ruft der Ausfuehrer, sobald das Abbruchsignal des Laufs feuert. Unbekannte
+/// Kennungen sind KEIN Fehler: der Befehl kann in derselben Millisekunde fertig
+/// geworden sein, und eine Fehlermeldung dafuer haette der Mensch nicht
+/// verursacht.
+#[tauri::command]
+#[allow(non_snake_case)]
+pub async fn shell_execute_cancel(callId: String) -> Result<bool, String> {
+ let pid = shell_mark_cancelled(&callId);
+ match pid {
+ Some(p) => {
+ tokio::task::spawn_blocking(move || kill_tree(p))
+ .await
+ .map_err(|e| format!("Task join error: {}", e))?;
+ Ok(true)
+ }
+ // Noch kein Prozess: der Merker steht, und der Start toetet sofort
+ // selbst, sobald er ihn liest.
+ None => Ok(false),
+ }
+}
+
/// Run a short-lived probe command with a HARD deadline and return its stdout.
///
/// `Command::output()` waits forever, and the tools this app probes with can
@@ -344,9 +494,10 @@ pub async fn shell_execute(
stdin: Option<String>,
chatId: Option<String>,
workingDirectory: Option<String>,
+ callId: Option<String>,
) -> Result<serde_json::Value, String> {
tokio::task::spawn_blocking(move || {
- shell_execute_sync(command, args, cwd, timeout, shell, stdin, chatId, workingDirectory)
+ shell_execute_sync(command, args, cwd, timeout, shell, stdin, chatId, workingDirectory, callId)
})
.await
.map_err(|e| format!("Task join error: {}", e))?
@@ -365,7 +516,11 @@ fn shell_execute_sync(
stdin: Option<String>,
chat_id: Option<String>,
working_directory: Option<String>,
+ call_id: Option<String>,
) -> Result<serde_json::Value, String> {
+ // VOR dem Bauen des Befehls angemeldet, damit ein Abbruch, der den Start
+ // ueberholt, einen Platz hat, an dem er stehen bleiben kann.
+ let slot = ShellSlot::new(call_id.as_deref());
let timeout_ms = timeout.unwrap_or(120_000);
// Shell name in, program + argument form out — the same function the
// background twin in bg_tasks.rs calls, so the two cannot drift apart.
@@ -419,6 +574,18 @@ fn shell_execute_sync(
let mut child = cmd.spawn().map_err(|e| format!("Spawn shell: {}", os_error::english(&e)))?;
+ // Der Abbruch kann zwischen Anmelden und Start eingetroffen sein. Dann gab
+ // es keine Prozesskennung zu toeten, und dieser Prozess hier ist genau der,
+ // den niemand mehr wollte.
+ if let Some(id) = slot.id() {
+ if shell_attach_pid(id, child.id()) {
+ kill_tree(child.id());
+ let _ = child.kill();
+ let _ = child.wait();
+ return Ok(cancelled_result(String::new()));
+ }
+ }
+
// Write on a thread: the child may fill its output pipes before it has
// consumed stdin, and a blocking write here would deadlock against the
// drain below.
@@ -447,6 +614,19 @@ fn shell_execute_sync(
let timeout_dur = std::time::Duration::from_millis(timeout_ms);
loop {
+ // Der Stop steht VOR dem Abholen des Endstands. Andersherum gewaenne
+ // ein Befehl, den `shell_execute_cancel` gerade erschlagen hat, einen
+ // gewoehnlichen Exit-Code, und das Modell bekaeme einen Fehlschlag
+ // gemeldet statt eines Abbruchs, den der Mensch selbst ausgeloest hat.
+ if slot.id().map(shell_is_cancelled).unwrap_or(false) {
+ kill_tree(child.id());
+ let _ = child.kill();
+ let _ = child.wait(); // reap, or the shell lingers as a zombie
+ settle(&out_done, &err_done, std::time::Duration::from_millis(200));
+ // Was der Befehl bis hierher gedruckt hat, kommt mit — dieselbe
+ // Regel wie bei der Zeitgrenze ein paar Zeilen weiter unten.
+ return Ok(cancelled_result(captured_text(&out_buf)));
+ }
match child.try_wait() {
Ok(Some(status)) => {
settle(&out_done, &err_done, std::time::Duration::from_millis(500));
@@ -484,6 +664,111 @@ fn shell_execute_sync(
}
}
+/// Der Abbruch eines schon gestarteten Befehls.
+///
+/// Geprueft wird die BUCHFUEHRUNG, nicht das Toeten selbst: `kill_tree` haengt
+/// am Betriebssystem und an echten Prozessen, die Reihenfolge dagegen ist
+/// reine Logik und genau die Stelle, an der ein Abbruch lautlos verlorengeht.
+///
+/// Der teuerste Fall steht zuerst: der Abbruch, der den Start UEBERHOLT. Ohne
+/// den Merker gaebe es in diesem Fenster keine Prozesskennung zu toeten, der
+/// Befehl liefe an, nachdem der Mensch ihn gestoppt hat, und niemand saehe es.
+///
+/// Lauf: cargo test shell_cancel
+#[cfg(test)]
+mod shell_cancel_tests {
+ use super::*;
+
+ /// Eigene Kennung je Test: die Karte ist prozessweit, und cargo faehrt die
+ /// Tests eines Binaries nebenlaeufig.
+ fn kennung(name: &str) -> String {
+ format!("test-{}-{:?}", name, std::thread::current().id())
+ }
+
+ #[test]
+ fn shell_cancel_ein_abbruch_vor_dem_start_bleibt_stehen() {
+ let id = kennung("vor-dem-start");
+ shell_register(&id);
+ // Der Abbruch kommt, waehrend noch kein Prozess existiert.
+ assert_eq!(shell_mark_cancelled(&id), None, "es gibt noch keine Prozesskennung");
+ // Und der Start liest ihn: `true` heisst "sofort wieder toeten".
+ assert!(shell_attach_pid(&id, 4242), "der Start muss den Abbruch sehen");
+ shell_unregister(&id);
+ }
+
+ #[test]
+ fn shell_cancel_ein_abbruch_ohne_anmeldung_legt_den_merker_an() {
+ // Die Reihenfolge, die der Wettlauf zwischen Fenster und Bruecke
+ // wirklich erzeugt: der Abbruch ist schneller als der Rust-Aufruf.
+ let id = kennung("ueberholt");
+ assert_eq!(shell_mark_cancelled(&id), None);
+ shell_register(&id); // darf den Merker NICHT ueberschreiben
+ assert!(shell_is_cancelled(&id));
+ assert!(shell_attach_pid(&id, 7));
+ shell_unregister(&id);
+ }
+
+ #[test]
+ fn shell_cancel_findet_den_laufenden_prozess() {
+ let id = kennung("laeuft");
+ shell_register(&id);
+ assert!(!shell_attach_pid(&id, 1234), "ohne Abbruch laeuft er weiter");
+ assert!(!shell_is_cancelled(&id));
+ assert_eq!(shell_mark_cancelled(&id), Some(1234), "die Prozesskennung kommt zurueck");
+ assert!(shell_is_cancelled(&id), "und die Schleife sieht den Abbruch");
+ shell_unregister(&id);
+ }
+
+ #[test]
+ fn shell_cancel_ein_lauf_ohne_kennung_ist_unberuehrt() {
+ // Altbestand und die Fernbruecke schicken keine Kennung. Die duerfen
+ // nicht plombiert werden, nur weil ein anderer Lauf abgebrochen wurde.
+ let id = kennung("fremd");
+ shell_mark_cancelled(&id);
+ assert!(!shell_attach_pid("gar-nicht-angemeldet", 99));
+ assert!(!shell_is_cancelled("gar-nicht-angemeldet"));
+ shell_unregister(&id);
+ }
+
+ #[test]
+ fn shell_cancel_der_platz_meldet_sich_beim_verlassen_ab() {
+ // Sonst waechst die Karte mit jedem Befehl, und eine spaeter erneut
+ // vergebene Kennung zeigte auf einen laengst toten Prozess.
+ let id = kennung("aufraeumen");
+ {
+ let slot = ShellSlot::new(Some(&id));
+ assert_eq!(slot.id(), Some(id.as_str()));
+ shell_attach_pid(&id, 31337);
+ assert_eq!(shell_mark_cancelled(&id), Some(31337));
+ }
+ assert!(!shell_is_cancelled(&id), "der Eintrag ist weg, nicht nur zurueckgesetzt");
+ assert_eq!(shell_mark_cancelled(&id), None);
+ shell_unregister(&id);
+ }
+
+ #[test]
+ fn shell_cancel_eine_leere_kennung_zaehlt_als_keine() {
+ // JSON aus dem Fenster kann "" liefern. Ein Platz unter dem leeren
+ // Namen waere ein Eimer, in dem sich alle Laeufe treffen.
+ let slot = ShellSlot::new(Some(" "));
+ assert_eq!(slot.id(), None);
+ let ohne = ShellSlot::new(None);
+ assert_eq!(ohne.id(), None);
+ }
+
+ #[test]
+ fn shell_cancel_die_antwort_nennt_den_abbruch_und_nicht_die_zeitgrenze() {
+ // Eine Zeitgrenze ist etwas, das dem Befehl passiert ist, ein Abbruch
+ // etwas, das der Mensch getan hat. Das Modell liest den Unterschied.
+ let v = cancelled_result("halb fertig".to_string());
+ assert_eq!(v["cancelled"], serde_json::json!(true));
+ assert_eq!(v["timedOut"], serde_json::json!(false));
+ assert_eq!(v["exitCode"], serde_json::json!(-1));
+ assert_eq!(v["stdout"], serde_json::json!("halb fertig"));
+ assert!(v["stderr"].as_str().unwrap().contains("stopped the run"));
+ }
+}
+
/// The argument form, asserted for both platforms from either platform.
///
/// `shell_argv` takes `windows` as a parameter precisely so this module can
diff --git a/src-tauri/src/main.rs b/src-tauri/src/main.rs
index ace5f4da..0d013f46 100644
--- a/src-tauri/src/main.rs
+++ b/src-tauri/src/main.rs
@@ -337,6 +337,7 @@ fn main() {
commands::agent::list_agent_workspaces,
// Shell
commands::shell::shell_execute,
+ commands::shell::shell_execute_cancel,
// Filesystem
commands::filesystem::fs_read,
commands::filesystem::fs_read_bytes,
diff --git a/src/api/mcp/__tests__/shell-honours-stop.test.ts b/src/api/mcp/__tests__/shell-honours-stop.test.ts
index 3105ee71..dacff636 100644
--- a/src/api/mcp/__tests__/shell-honours-stop.test.ts
+++ b/src/api/mcp/__tests__/shell-honours-stop.test.ts
@@ -7,12 +7,16 @@
*
* not started yet → refused; nothing runs.
* background task → really killed, via the bridge's shell_task_kill.
- * foreground child → NOT killable from here. Rust `shell_execute` takes no run
- * id and there is no shell_execute_cancel, so the process
- * runs to its own timeout. The executor stops WAITING on it
- * (see tool-executor-abort.test.ts), which ends the run and
- * frees the UI, but the child survives. Closing that hole
- * needs a bridge command; see the audit report.
+ * foreground child → killed, via shell_execute_cancel.
+ *
+ * Die dritte Zeile stand hier bis zur 3.0.0-Runde anders: der Vordergrundfall
+ * war NICHT abbrechbar, weil `shell_execute` keine Kennung nahm und es kein
+ * `shell_execute_cancel` gab. Der Ausfuehrer hoerte auf zu warten, damit endeten
+ * Lauf und Oberflaeche, und der Prozess lief bis zu seiner eigenen Zeitgrenze
+ * weiter: bis zu zwei Minuten Build oder Skript auf der Maschine des Nutzers,
+ * nachdem er Stop gedrueckt hat. Der alte Kommentar war der Merker dafuer, wo
+ * der echte Abbruch hingehoert; jetzt steht er dort, und diese Datei prueft ihn
+ * am Verhalten statt am Kommentar.
*
* Run: npx vitest run src/api/mcp/__tests__/shell-honours-stop.test.ts
*/
@@ -23,10 +27,24 @@ import { fileURLToPath } from 'node:url'
const backendCalls: { cmd: string; body: Record<string, unknown> }[] = []
+/**
+ * Ein `shell_execute`, das haengen bleibt, bis der Test es loslaesst.
+ *
+ * Ohne das gaebe es kein Fenster, in dem der Befehl LAEUFT — und genau in dem
+ * Fenster passiert der Fehler, um den es hier geht. Ein Aufruf, der sofort
+ * zurueckkehrt, koennte gar nicht abgebrochen werden und der Test waere gruen,
+ * ohne je etwas geprueft zu haben.
+ */
+let laufenLassen: (() => void) | null = null
+
vi.mock('../../backend', () => ({
backendCall: vi.fn(async (cmd: string, body: Record<string, unknown>) => {
backendCalls.push({ cmd, body })
- if (cmd === 'shell_execute') return { stdout: 'ran', stderr: '', exitCode: 0 }
+ if (cmd === 'shell_execute') {
+ if (laufenLassen === null) return { stdout: 'ran', stderr: '', exitCode: 0, timedOut: false }
+ await new Promise<void>((r) => { laufenLassen = 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 }
@@ -64,7 +82,9 @@ registerBuiltinTools(registry)
const ran = () => backendCalls.filter((c) => c.cmd === 'shell_execute')
const killed = () => backendCalls.filter((c) => c.cmd === 'shell_task_kill')
-beforeEach(() => { backendCalls.length = 0 })
+const cancelled = () => backendCalls.filter((c) => c.cmd === 'shell_execute_cancel')
+
+beforeEach(() => { backendCalls.length = 0; laufenLassen = null })
describe('shell_execute honours the run\'s Stop', () => {
it('a command that has not started yet does not start', async () => {
@@ -124,11 +144,47 @@ describe('shell_execute honours the run\'s Stop', () => {
expect(killed()).toHaveLength(0)
})
- it('the foreground path is documented as un-killable rather than pretending', () => {
- // If someone adds the bridge command, this comment (and this test) is the
- // marker that says where the real kill belongs.
+ it('ein schon GESTARTETER Vordergrundbefehl wird abgebrochen, nicht nur vergessen', async () => {
+ // Der Fall, der bis zur 3.0.0-Runde offen war. Bis zu zwei Minuten Build
+ // auf der Maschine des Nutzers, nachdem er Stop gedrueckt hat.
+ laufenLassen = () => {}
+ const ctrl = new AbortController()
+ const lauf = registry.execute('shell_execute', { command: 'npm run build' }, 1, undefined, ctrl.signal)
+ await new Promise((r) => setTimeout(r, 0))
+
+ const gestartet = ran()
+ expect(gestartet).toHaveLength(1)
+ const kennung = (gestartet[0].body as { callId?: string }).callId
+ expect(typeof kennung).toBe('string')
+ expect(kennung).toBeTruthy()
+ expect(cancelled()).toHaveLength(0)
+
+ ctrl.abort()
+ await new Promise((r) => setTimeout(r, 0))
+
+ // Dieselbe Kennung: ein Abbruch auf eine andere waere Buchhaltung ohne Wirkung.
+ expect(cancelled()).toEqual([{ cmd: 'shell_execute_cancel', body: { callId: kennung } }])
+
+ laufenLassen?.()
+ await expect(lauf).resolves.toMatch(/cancelled/i)
+ })
+
+ it('NEGATIVE CONTROL: ein Befehl, der durchlaeuft, wird nicht abgebrochen', async () => {
+ const ctrl = new AbortController()
+ await registry.execute('shell_execute', { command: 'echo hi' }, 1, undefined, ctrl.signal)
+ // Der Horcher muss beim Verlassen wieder ab: sonst schluege ein spaeterer
+ // Stop auf eine Kennung durch, hinter der laengst kein Prozess mehr steht.
+ ctrl.abort()
+ await new Promise((r) => setTimeout(r, 0))
+ expect(cancelled()).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.
const here = dirname(fileURLToPath(import.meta.url))
const src = readFileSync(resolve(here, '../builtin-tools.ts'), 'utf8')
- expect(src).toContain('the bridge has NO cancel for it')
+ expect(src).toContain("backendCall('shell_execute_cancel', { callId })")
+ expect(src).not.toContain('the bridge has NO cancel for it')
})
})
diff --git a/src/api/mcp/builtin-tools.ts b/src/api/mcp/builtin-tools.ts
index 58ba26fd..75faa070 100644
--- a/src/api/mcp/builtin-tools.ts
+++ b/src/api/mcp/builtin-tools.ts
@@ -6,6 +6,7 @@ import type {
WebSearchResult, WebFetchResult, ProcessListResult, ScreenshotResult, CurrentTimeResult,
} from '../../types/bridge'
import type { ToolRegistry } from './tool-registry'
+import { v4 as uuid } from 'uuid'
import { backendCall, fetchExternal } from '../backend'
import { getActiveChatId, getActiveConversationId, getActiveWorkspace, isChatArtifactMode, captureChatArtifact, isReadOnlyShellTurn } from '../agent-context'
import type { AgentRunContext } from '../agent-context'
@@ -750,16 +751,12 @@ async function executeShellExecute(
run?: AgentRunContext,
signal?: AbortSignal,
): Promise<string> {
- // Stop reaches the terminal tool now (audit M1). What it can guarantee
- // depends on the phase:
+ // Stop reaches the terminal tool in every phase now (audit M1, plus the
+ // foreground half that was still open until the 3.0.0 round):
// - not started yet → refused here, nothing runs;
- // - background task → really killed, via shell_task_kill;
- // - foreground, already spawned → the bridge has NO cancel for it. Rust
- // `shell_execute` takes no run id and there is no shell_execute_cancel,
- // so the child keeps running to its own timeout. The executor stops
- // WAITING on it (tool-executor raceAbort), which ends the run and the
- // UI, but the process survives. Closing that hole needs a bridge command
- // — noted in the audit report, deliberately not faked here.
+ // - background task → killed via shell_task_kill;
+ // - foreground, already spawned → killed via shell_execute_cancel, see
+ // `invokeShell`. Der Prozessbaum faellt, nicht nur das Warten darauf.
const abort = signal ?? run?.abortSignal
if (abort?.aborted) return 'Cancelled: the user stopped the run before this command started.'
// Background-task actions: the three shell_task_* tools folded in (2.6.6).
@@ -816,7 +813,7 @@ async function executeShellExecute(
// An explicit timeout wins; otherwise a recognised test run keeps the old
// run_tests budget (300 s) instead of the shell default.
const timeout = argNumber(args, 'timeout') || commandTimeoutMs(command, 120000)
- const data = await backendCall<ShellExecResult>('shell_execute', {
+ const data = await invokeShell({
command,
args: args.args || null,
cwd: args.cwd || null,
@@ -824,9 +821,12 @@ async function executeShellExecute(
shell: args.shell || null,
stdin: argOptString(args, 'stdin') ?? null,
...chatCtx(run),
- })
+ }, abort)
const output = data.stdout || ''
const err = data.stderr || ''
+ // Vor `timedOut` geprueft: der Abbruch ist die genauere Auskunft, und ein
+ // Befehl, den Stop gefaellt hat, ist nicht in eine Zeitgrenze gelaufen.
+ if (data.cancelled) return 'Cancelled: the user stopped the run.'
if (data.timedOut) return `Timed out.\n${err}`
const kind = commandKind(command)
@@ -881,20 +881,65 @@ async function executeCodeExecute(
return output || (err ? `stderr: ${err}` : 'Done.')
}
+/**
+ * `shell_execute`, mit einem Griff, den Stop erreicht.
+ *
+ * ── DAS LOCH, DAS DAS HIER STOPFT (Fehler s der 3.0.0-Liste) ───────────────
+ *
+ * An dieser Stelle stand bis heute ein Absatz, der das Problem offen zugab:
+ * die Bruecke hatte keinen Abbruch fuer einen schon gestarteten Befehl, weil
+ * `shell_execute` keine Kennung nahm und es kein `shell_execute_cancel` gab.
+ * Der Ausfuehrer hoerte auf zu WARTEN (tool-executor raceAbort), damit endeten
+ * Lauf und Oberflaeche, und der Prozess lief weiter bis zu seiner eigenen
+ * Zeitgrenze: bis zu zwei Minuten Build, Testlauf oder Skript, nachdem der
+ * Mensch Stop gedrueckt hat, auf seiner Maschine, ohne Anzeige.
+ *
+ * Jetzt traegt jeder Lauf eine Kennung, und das Abbruchsignal ruft damit
+ * `shell_execute_cancel`. Die Rust-Seite faellt den ganzen Prozessbaum mit
+ * derselben `kill_tree`, die auch die Zeitgrenze benutzt; der Wettlauf
+ * "Abbruch schneller als der Start" ist dort mitgedacht und getestet.
+ *
+ * Ohne Signal bleibt alles, wie es war: keine Kennung, kein Eintrag, kein
+ * Abbruch. Eine Kennung, die niemand ruft, waere nur Buchhaltung.
+ */
+async function invokeShell(
+ payload: Record<string, unknown>,
+ abort?: AbortSignal,
+): Promise<ShellExecResult> {
+ if (!abort) return backendCall<ShellExecResult>('shell_execute', payload)
+ const callId = uuid()
+ const cancel = () => {
+ void backendCall('shell_execute_cancel', { callId }).catch(() => {
+ // Ein fehlgeschlagener Abbruch darf den Lauf nicht auch noch mit einem
+ // Fehler beenden. Der Befehl faellt dann auf seine Zeitgrenze zurueck,
+ // also auf genau das Verhalten von vorher.
+ })
+ }
+ abort.addEventListener('abort', cancel, { once: true })
+ try {
+ return await backendCall<ShellExecResult>('shell_execute', { ...payload, callId })
+ } finally {
+ // Der Eintrag auf der Rust-Seite haengt am Leben DIESES Aufrufs. Bliebe
+ // der Horcher stehen, riefe ein spaeterer Stop denselben Abbruch auf eine
+ // Kennung, hinter der laengst kein Prozess mehr steht.
+ abort.removeEventListener('abort', cancel)
+ }
+}
+
async function runShell(
command: string,
cwd: string | undefined,
timeout = 60000,
run?: AgentRunContext,
): Promise<ShellExecResult> {
- return backendCall<ShellExecResult>('shell_execute', {
+ return invokeShell({
command,
args: null,
cwd: cwd || null,
timeout,
shell: null,
...chatCtx(run),
- })
+ }, run?.abortSignal)
}
async function executeShellExecuteBg(
@@ -1129,7 +1174,7 @@ async function executeGhPrCreate(args: ToolArgs, run?: AgentRunContext): Promise
return urlMatch ? `Opened PR: ${urlMatch[0]}\n${output}` : output
}
-async function executeRunTests(args: ToolArgs, run?: AgentRunContext): Promise<string> {
+async function executeRunTests(args: ToolArgs, run?: AgentRunContext, signal?: AbortSignal): Promise<string> {
const { commandForRunner, detectRunnerFromFiles, parseForRunner, renderResult } =
await import('../agents/test-runner')
@@ -1171,7 +1216,10 @@ async function executeRunTests(args: ToolArgs, run?: AgentRunContext): Promise<s
shell: null,
...chatCtx(run),
}
- const data = await backendCall<ShellExecResult>('shell_execute', shellArgs)
+ // Der laengste Befehl im Haus (300 s Vorgabe) und damit der, bei dem ein
+ // Stop, der den Prozess nicht erreicht, am laengsten weiterlaeuft.
+ const data = await invokeShell(shellArgs, signal ?? run?.abortSignal)
+ if (data.cancelled) return 'Cancelled: the user stopped the run.'
if (data.timedOut) {
return `Test run timed out after ${shellArgs.timeout / 1000}s. Partial output:\n${(data.stdout || '').slice(-2000)}`
}
diff --git a/src/types/bridge.ts b/src/types/bridge.ts
index 39cd7255..4a5801ef 100644
--- a/src/types/bridge.ts
+++ b/src/types/bridge.ts
@@ -21,6 +21,14 @@ export interface ShellExecResult {
/** `status.code()`, or -1 when the child was killed or timed out. */
exitCode: number
timedOut: boolean
+ /**
+ * Der Mensch hat Stop gedrueckt, und `shell_execute_cancel` hat den
+ * Prozessbaum gefaellt. Eigenes Feld neben `timedOut`, weil eine Zeitgrenze
+ * etwas ist, das dem Befehl passiert ist, und ein Abbruch etwas, das der
+ * Nutzer getan hat: das Modell soll den Unterschied lesen koennen.
+ * Fehlt bei jedem Lauf, der ohne Abbruchkennung gestartet wurde.
+ */
+ cancelled?: boolean
}
/** `fs_read` — commands/filesystem.rs. Binary files carry `bytes`, no `content`. */