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
feat(agent): shell timeout hands the command over to a background task (T1)
purple920d3f36d91d
diff --git a/dev-server/__tests__/mlx-media-endpoint-coverage.test.ts b/dev-server/__tests__/mlx-media-endpoint-coverage.test.tsindex 28ef74b8..7465650d 100644--- a/dev-server/__tests__/mlx-media-endpoint-coverage.test.ts+++ b/dev-server/__tests__/mlx-media-endpoint-coverage.test.ts@@ -243,7 +243,7 @@ describe('endpointMap covers every backendCall/invokeMedia site the frontend can'restart_remote_server', 'restore_rag_chunks', 'restore_stores', 'revoke_remote_memory','save_text_file_dialog', 'self_migrate_finish', 'self_migrate_stage', 'set_chat_workspace_override','set_comfy_gpu_mode', 'set_gpu_selection', 'set_onboarding_done', 'shell_execute_cancel',- 'shell_task_kill', 'shell_task_list', 'shell_task_start', 'shell_task_status', 'stage_training_image',+ 'shell_task_start', 'stage_training_image','start_bundled_embed', 'start_bundled_engine', 'start_character_training', 'start_lmstudio_server','start_local_api', 'start_ollama', 'stop_bundled_embed', 'stop_bundled_engine', 'stop_local_api','swap_bundled_model', 'sync_custom_model_paths', 'synthesize', 'synthesize_external', 'system_health',diff --git a/dev-server/__tests__/shell-timeout-handover.test.ts b/dev-server/__tests__/shell-timeout-handover.test.tsnew file mode 100644index 00000000..acc9323b--- /dev/null+++ b/dev-server/__tests__/shell-timeout-handover.test.ts@@ -0,0 +1,102 @@+/**+ * T1 on the bench: the dev server's /local-api/shell-execute does what the+ * app's shell_execute does when the timeout hits and the caller asked for the+ * handover. The command runs on as a task, the answer carries `taskId` and+ * the output so far, and the shell_task_* routes read and stop it with the+ * Rust shapes. Without the switch the timeout still kills, as before.+ *+ * Real handler (registerExecRoutes), real socket, real processes. POSIX only:+ * the commands are `bash`, and the kill check reads a pid from `$!`.+ *+ * Run: npx vitest run dev-server/__tests__/shell-timeout-handover.test.ts+ */+import { afterAll, describe, expect, it } from 'vitest'+import { mkdtempSync, rmSync } from 'node:fs'+import { tmpdir } from 'node:os'+import { join } from 'node:path'+import { registerExecRoutes } from '../exec-routes'+import { killAllDevTasks } from '../shell-tasks'+import { anfrage, routeHolen } from './echte-anfrage'++const ws = mkdtempSync(join(tmpdir(), 'lu-t1-'))+afterAll(() => {+ killAllDevTasks()+ rmSync(ws, { recursive: true, force: true })+})++async function post(path: string, body: Record<string, unknown>) {+ const handler = routeHolen(registerExecRoutes, path)+ const r = await anfrage(handler, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify(body),+ })+ return { status: r.status, json: r.json() as Record<string, unknown> }+}++const shell = (command: string, timeout: number, handOver: boolean) =>+ post('/local-api/shell-execute', { command, timeout, shell: 'bash', workingDirectory: ws, backgroundOnTimeout: handOver })+const status = (id: string) => post('/local-api/shell-task-status', { args: { id } })++function alive(pid: number): boolean {+ try {+ process.kill(pid, 0)+ return true+ } catch {+ return false+ }+}++async function until(check: () => Promise<boolean> | boolean, ms = 8000): Promise<void> {+ const deadline = Date.now() + ms+ while (!(await check())) {+ if (Date.now() > deadline) throw new Error('condition not met in time')+ await new Promise((r) => setTimeout(r, 50))+ }+}++describe.skipIf(process.platform === 'win32')('dev server: timeout hands over to a task', () => {+ it('answers with the task id and the output so far, and the task finishes on its own', async () => {+ const r = await shell('echo before; sleep 1; echo after', 300, true)+ expect(r.status).toBe(200)+ expect(r.json.timedOut).toBe(true)+ expect(r.json.exitCode).toBe(-1)+ expect(String(r.json.stdout)).toContain('before')+ expect(String(r.json.stdout)).not.toContain('after')+ const id = String(r.json.taskId)+ expect(id).toMatch(/[0-9a-f-]{36}/)++ const first = await status(id)+ expect(first.json.running).toBe(true)+ await until(async () => (await status(id)).json.running === false)+ const done = await status(id)+ expect(done.json.exit_code).toBe(0)+ expect(String(done.json.output_tail)).toContain('after')++ const list = await post('/local-api/shell-task-list', { args: {} })+ expect((list.json.tasks as { id: string }[]).map((t) => t.id)).toContain(id)+ })++ it('kill takes the task and its children down', async () => {+ const r = await shell('sleep 30 & echo $!; wait', 300, true)+ const id = String(r.json.taskId)+ const worker = Number(String(r.json.stdout).trim().split('\n')[0])+ expect(alive(worker)).toBe(true)++ const k = await post('/local-api/shell-task-kill', { args: { id } })+ expect(k.json).toEqual({ ok: true, cancelled: true })+ await until(() => !alive(worker))+ await until(async () => (await status(id)).json.running === false)+ expect((await status(id)).json.cancelled).toBe(true)+ })++ it('without the switch the timeout still kills', async () => {+ const r = await shell('sleep 30', 300, false)+ expect(r.json.timedOut).toBe(true)+ expect(r.json.taskId).toBeUndefined()+ })++ it('an unknown task id is a 404', async () => {+ expect((await status('nope')).status).toBe(404)+ })+})diff --git a/dev-server/exec-routes.ts b/dev-server/exec-routes.tsindex 6b1b6a00..ff051290 100644--- a/dev-server/exec-routes.ts+++ b/dev-server/exec-routes.ts@@ -3,10 +3,11 @@ import { existsSync, mkdirSync, rmSync, statSync } from 'fs'import os from 'os'import { join, resolve as resolvePath } from 'path'import type { RouteMount } from './routes'-import { requirePost, withJsonBody } from './http'-import { bodyNumber, bodyString } from '../src/dev/http-body'+import { requirePost, sendJson, withJsonBody } from './http'+import { bodyFlag, bodyNumber, bodyString } from '../src/dev/http-body'import { devWorkspaceRoot } from '../src/lib/dev-fs-jail'import { fenceShell } from './bench-sandbox'+import { adoptProcess, devTaskKill, devTaskList, devTaskStatus } from './shell-tasks'/*** The folder a dev-server shell command runs in, the same rule as@@ -146,22 +147,42 @@ export function registerExecRoutes(routes: RouteMount): void {res.end(JSON.stringify({ stdout: '', stderr: fenced.refused, exitCode: 1 }))return}+ // T1, the same switch as the app's shell_execute: past the timeout the+ // command moves into the task registry (shell-tasks.ts) instead of+ // dying. It then gets a process group of its own on POSIX, so a kill+ // later takes its children along, and so does the dev server's exit+ // hook. The sandbox wrapping above stays as it is: the adopted process+ // is the fenced one.+ const handOver = bodyFlag(body, 'backgroundOnTimeout')+ const group = handOver && process.platform !== 'win32'+ const runCwd = devShellCwd(cwd, bodyString(body, 'chatId'), bodyString(body, 'workingDirectory'))const proc = spawn(fenced.bin, fenced.args, {- cwd: devShellCwd(cwd, bodyString(body, 'chatId'), bodyString(body, 'workingDirectory')),+ cwd: runCwd,stdio: ['ignore', 'pipe', 'pipe'],shell: false,+ detached: group,})+ let answered = falseconst timer = setTimeout(() => {+ if (handOver) {+ // Answer now with what came so far; the process runs on as a task.+ answered = true+ const soFar = stdout + (stderr ? `\n[stderr]\n${stderr}` : '')+ const taskId = adoptProcess({ proc, group, command, cwd: runCwd, soFar })+ sendJson(res, 200, { stdout, stderr, exitCode: -1, timedOut: true, taskId, timeoutMs: limit })+ return+ }killed = truetry { proc.kill('SIGKILL') } catch { /* dead */ }}, limit)- proc.stdout?.on('data', (d: Buffer) => { stdout += d.toString() })- proc.stderr?.on('data', (d: Buffer) => { stderr += d.toString() })+ proc.stdout?.on('data', (d: Buffer) => { if (!answered) stdout += d.toString() })+ proc.stderr?.on('data', (d: Buffer) => { if (!answered) stderr += d.toString() })proc.on('exit', (exitCode) => {clearTimeout(timer)+ if (answered) returnres.writeHead(200, { 'Content-Type': 'application/json' })res.end(JSON.stringify({stdout, stderr,@@ -172,6 +193,7 @@ export function registerExecRoutes(routes: RouteMount): void {proc.on('error', (err: Error) => {clearTimeout(timer)+ if (answered) returnres.writeHead(200, { 'Content-Type': 'application/json' })res.end(JSON.stringify({ stdout: '', stderr: err.message, exitCode: 1, timedOut: false }))})@@ -182,4 +204,33 @@ export function registerExecRoutes(routes: RouteMount): void {})})+ // T1: the tasks a timeout handed over. The same calls and shapes as the+ // app's shell_task_* commands, so the tool layer runs unchanged on the+ // bench. The body is the app's IPC payload, `{ args: { id } }`.+ const taskIdOf = (body: unknown): string => {+ const args = body && typeof body === 'object' ? (body as { args?: unknown }).args : undefined+ return bodyString(args, 'id') ?? ''+ }+ routes.use('/local-api/shell-task-status', (req, res) => {+ if (!requirePost(req, res)) return+ withJsonBody(req, res, (body) => {+ const id = taskIdOf(body)+ const s = devTaskStatus(id)+ if (!s) return sendJson(res, 404, { error: `task not found: ${id}` })+ sendJson(res, 200, s)+ })+ })+ routes.use('/local-api/shell-task-kill', (req, res) => {+ if (!requirePost(req, res)) return+ withJsonBody(req, res, (body) => {+ const id = taskIdOf(body)+ const r = devTaskKill(id)+ if (!r) return sendJson(res, 404, { error: `task not found: ${id}` })+ sendJson(res, 200, r)+ })+ })+ routes.use('/local-api/shell-task-list', (req, res) => {+ if (!requirePost(req, res)) return+ withJsonBody(req, res, () => sendJson(res, 200, { tasks: devTaskList() }))+ })}diff --git a/dev-server/shell-tasks.ts b/dev-server/shell-tasks.tsnew file mode 100644index 00000000..ff9d0ee7--- /dev/null+++ b/dev-server/shell-tasks.ts@@ -0,0 +1,142 @@+import type { ChildProcess } from 'child_process'+import { randomUUID } from 'crypto'++/**+ * The dev server's twin of the app's background-task registry+ * (src-tauri/src/commands/bg_tasks.rs), for T1: a `/local-api/shell-execute`+ * that outruns its timeout with `backgroundOnTimeout: true` is not killed but+ * moved here, and the bench reads and stops it through the same+ * `shell_task_status` / `shell_task_kill` / `shell_task_list` calls the app+ * makes (src/api/backend.ts maps them to the routes in exec-routes.ts).+ *+ * The status has the Rust shape (`BgTaskStatus`, snake_case, seconds), so+ * the tool layer cannot tell the two backends apart.+ *+ * The process is already inside the bench sandbox when it gets here: it was+ * spawned through `fenceShell` by the shell route, and adopting it changes+ * nothing about how it runs.+ */++/** How much output a task keeps, from its end. The Rust side keeps head and tail; here the end is enough for the bench. */+export const DEV_TASK_OUTPUT_MAX = 256 * 1024+/** Same cap as the Rust registry. */+const DEV_TASKS_MAX = 200++export interface DevTaskStatus {+ id: string+ command: string+ cwd: string | null+ started_at: number+ finished_at: number | null+ exit_code: number | null+ running: boolean+ cancelled: boolean+ output_tail: string+}++interface DevTask {+ status: DevTaskStatus+ proc: ChildProcess | null+ /** Spawned with `detached: true` on POSIX: the pid is a process group. */+ group: boolean+}++const TASKS = new Map<string, DevTask>()+let exitHookArmed = false++const nowSecs = () => Math.floor(Date.now() / 1000)++function append(task: DevTask, text: string): void {+ const next = task.status.output_tail + text+ task.status.output_tail = next.length > DEV_TASK_OUTPUT_MAX ? next.slice(-DEV_TASK_OUTPUT_MAX) : next+}++/** The shell and everything it started. A process group when there is one. */+export function killProcessTree(proc: ChildProcess, group: boolean): void {+ if (proc.pid === undefined) return+ try {+ if (group && process.platform !== 'win32') process.kill(-proc.pid, 'SIGKILL')+ else proc.kill('SIGKILL')+ } catch {+ // Already gone.+ }+}++/** Kill every task that still runs. Armed on process exit, so a dev server that stops leaves nothing behind. */+export function killAllDevTasks(): void {+ for (const t of TASKS.values()) {+ if (t.status.running && t.proc) killProcessTree(t.proc, t.group)+ }+}++function insert(id: string, task: DevTask): void {+ if (TASKS.size >= DEV_TASKS_MAX) {+ for (const [k, t] of TASKS) {+ if (!t.status.running) { TASKS.delete(k); break }+ }+ }+ TASKS.set(id, task)+ if (!exitHookArmed) {+ exitHookArmed = true+ process.on('exit', killAllDevTasks)+ }+}++/**+ * Take over a running shell process. `soFar` is what the route collected+ * until the timeout; everything after it is appended as it arrives.+ */+export function adoptProcess(input: {+ proc: ChildProcess+ group: boolean+ command: string+ cwd: string | null+ soFar: string+}): string {+ const id = randomUUID()+ const task: DevTask = {+ status: {+ id,+ command: input.command,+ cwd: input.cwd,+ started_at: nowSecs(),+ finished_at: null,+ exit_code: null,+ running: true,+ cancelled: false,+ output_tail: '',+ },+ proc: input.proc,+ group: input.group,+ }+ append(task, input.soFar)+ input.proc.stdout?.on('data', (d: Buffer) => append(task, d.toString()))+ input.proc.stderr?.on('data', (d: Buffer) => append(task, d.toString()))+ input.proc.on('exit', (code) => {+ task.status.running = false+ task.status.finished_at = nowSecs()+ task.status.exit_code = task.status.cancelled ? null : code+ task.proc = null+ })+ insert(id, task)+ return id+}++export function devTaskStatus(id: string): DevTaskStatus | undefined {+ const t = TASKS.get(id)+ return t ? { ...t.status } : undefined+}++export function devTaskKill(id: string): { ok: boolean; cancelled: boolean; reason?: string } | undefined {+ const t = TASKS.get(id)+ if (!t) return undefined+ if (!t.status.running || !t.proc) return { ok: true, cancelled: false, reason: 'already finished' }+ t.status.cancelled = true+ killProcessTree(t.proc, t.group)+ return { ok: true, cancelled: true }+}++/** Newest first, like the Rust listing. */+export function devTaskList(): DevTaskStatus[] {+ return [...TASKS.values()].map((t) => ({ ...t.status })).reverse()+}diff --git a/mobile-client/agent-core.js b/mobile-client/agent-core.jsindex 5c57b6c9..d8fc256e 100644--- a/mobile-client/agent-core.js+++ b/mobile-client/agent-core.js@@ -31,7 +31,7 @@ import { stripNonCanonicalTags } from './personas.js'parameters:[{name:'path',type:'string',description:'Directory to search in (recursive by default)',required:true},{name:'pattern',type:'string',description:'Regex pattern to search for',required:true},{name:'maxResults',type:'number',description:'Maximum matching files (default: 50)',required:false}]},- {name:'shell_execute', description:'THE terminal. Run a shell command: PowerShell on Windows, bash on Unix. Returns stdout, stderr, exit code. Everything runs here: git, tests, package managers, gh, python, platform utilities, and opening files, folders or apps. A recognised test run and the common git commands come back as a parsed summary. Feed a script through `stdin` instead of quoting it: set command to `python3 -` or `bash -s` (fresh process each call, no REPL state). For long work set `background: true` to get a task id back at once, then call again with `task: "status"` and `task_id` (or "list" / "kill"). PREFER dedicated tools where available: file_read over `cat`, file_list over `ls`, file_search over `grep`. `--no-verify` is refused, and NEVER delete permanently without confirmation. Default timeout 120 s, test runs 300 s.',+ {name:'shell_execute', description:'THE terminal. Run a shell command: PowerShell on Windows, bash on Unix. Returns stdout, stderr, exit code. Everything runs here: git, tests, package managers, gh, python, platform utilities, and opening files, folders or apps. A recognised test run and the common git commands come back as a parsed summary. Feed a script through `stdin` instead of quoting it: set command to `python3 -` or `bash -s` (fresh process each call, no REPL state). For long work set `background: true` to get a task id back at once, then call again with `task: "status"` and `task_id` (or "list" / "kill"). PREFER dedicated tools where available: file_read over `cat`, file_list over `ls`, file_search over `grep`. `--no-verify` is refused, and NEVER delete permanently without confirmation. Default timeout 120 s, test runs 300 s. A command still running at its timeout keeps running in the background under a task id.',parameters:[{name:'command',type:'string',description:'The full command to execute. Omit only for task actions.',required:false},{name:'cwd',type:'string',description:'Working directory (optional, relative to the workspace)',required:false},{name:'timeout',type:'number',description:'Timeout in milliseconds (default: 120000)',required:false},diff --git a/mobile-client/client.js b/mobile-client/client.jsindex 6675f299..28012b73 100644--- a/mobile-client/client.js+++ b/mobile-client/client.js@@ -292,6 +292,15 @@ import {if(data.exitCode!==undefined || data.stdout!==undefined){var out = data.stdout || '';var err = data.stderr || '';+ // T1: the desktop moved a command that outran its timeout into a+ // background task instead of killing it.+ if(data.timedOut && data.taskId){+ var soFar = (out + (err ? '\n[stderr]\n' + err : '')).replace(/\s+$/, '');+ if(soFar.length > 2000) soFar = '…' + soFar.slice(-2000);+ return 'Still running after its timeout, so it was not stopped: it keeps running in the background as task ' + data.taskId + '.\n'+ + (soFar ? 'Output so far:\n' + soFar + '\n' : '')+ + 'Use shell_execute with task "status" and task_id "' + data.taskId + '" to read its output, or task "kill" to stop it.';+ }if(data.timedOut) return 'Execution timed out.';if(data.exitCode && data.exitCode!==0) return 'Error ('+data.exitCode+'):\n'+(err||out);return out || (err ? 'stderr: '+err : 'Done.');diff --git a/src-tauri/src/commands/bg_tasks.rs b/src-tauri/src/commands/bg_tasks.rsindex 62a1609b..f2330537 100644--- a/src-tauri/src/commands/bg_tasks.rs+++ b/src-tauri/src/commands/bg_tasks.rs@@ -18,7 +18,9 @@//! `#[tauri::command]` for the desktop IPC bridge.use crate::os_error;+use crate::commands::shell::{captured_full, settle, Captured};use crate::commands::{bad_request, internal, not_found, CmdResult};+use std::sync::atomic::AtomicBool;use crate::state::AppState;use once_cell::sync::Lazy;use serde::{Deserialize, Serialize};@@ -67,6 +69,59 @@ struct BgTaskInner {/// the `Child`, so this is the only handle the shutdown sweep below has on/// a task it must kill.pid: Option<u32>,+ /// Set for a task that began life as a foreground `shell_execute` (T1).+ /// Its pipes are still read by `shell::drain`, into these buffers, so the+ /// output comes from here and `output_buf` stays empty.+ adopted: Option<AdoptedOutput>,+ /// A finished foreground run kept only so the model can read the output+ /// its tool result cut (`keep_finished_output`). Capped separately, see+ /// `KEPT_OUTPUTS_MAX`.+ kept_output: bool,+}++/// The two capture buffers of a foreground run, stdout and stderr.+#[derive(Clone)]+struct AdoptedOutput {+ out: Arc<Mutex<Captured>>,+ err: Arc<Mutex<Captured>>,+}++/// What `shell_execute` hands over when its timeout hits: the buffers its+/// drain threads fill, and the flags those threads set at EOF.+pub(crate) struct AdoptedPipes {+ pub out_buf: Arc<Mutex<Captured>>,+ pub err_buf: Arc<Mutex<Captured>>,+ pub out_done: Arc<AtomicBool>,+ pub err_done: Arc<AtomicBool>,+}++/// How many finished foreground outputs the registry keeps for reading. Each+/// holds up to 2 x (256 + 16) KiB; the 200-task cap alone would have allowed+/// a hundred megabytes of old build logs.+const KEPT_OUTPUTS_MAX: usize = 20;++impl BgTaskInner {+ /// The task's output as the status shows it.+ fn render_output(&self) -> String {+ match &self.adopted {+ Some(a) => render_adopted(a),+ None => render_tail(&self.output_buf),+ }+ }+}++/// stdout first, then stderr under a marker. Two pipes read by two threads+/// have no common order to restore, so this does not pretend to one.+fn render_adopted(a: &AdoptedOutput) -> String {+ let out = captured_full(&a.out);+ let err = captured_full(&a.err);+ if err.trim().is_empty() {+ return out;+ }+ if out.trim().is_empty() {+ return format!("[stderr]\n{err}");+ }+ format!("{out}\n[stderr]\n{err}")}#[derive(Clone)]@@ -84,6 +139,19 @@ impl BgRegistry {let mut g = self.tasks.lock().unwrap();// Cap the registry at 200 tasks — drop the oldest *finished* one// when we hit the cap so live tasks never get evicted by accident.+ // Kept foreground outputs have their own, smaller cap: drop the+ // oldest one before a new one comes in.+ if t.inner.lock().unwrap().kept_output {+ let kept: Vec<usize> = g+ .iter()+ .enumerate()+ .filter(|(_, t)| t.inner.lock().unwrap().kept_output)+ .map(|(i, _)| i)+ .collect();+ if kept.len() >= KEPT_OUTPUTS_MAX {+ g.remove(kept[0]);+ }+ }if g.len() >= 200 {if let Some(idx) = g.iter()@@ -386,6 +454,8 @@ pub(crate) async fn shell_task_start_impl(args: &Value) -> CmdResult {output_buf: Vec::with_capacity(8 * 1024),cancel_tx: Some(cancel_tx),pid: child.id(),+ adopted: None,+ kept_output: false,}));arm_exit_sweep();@@ -500,7 +570,7 @@ pub(crate) async fn shell_task_start_impl(args: &Value) -> CmdResult {g.status.cancelled = cancelled;g.status.running = false;g.status.finished_at = Some(now_secs());- g.status.output_tail = render_tail(&g.output_buf);+ g.status.output_tail = g.render_output();g.cancel_tx = None;// Already cleared above, in the same critical section as the reap —// this only pins the invariant for any path that reaches here without@@ -526,10 +596,145 @@ pub(crate) async fn shell_task_status_impl(args: &Value) -> CmdResult {.ok_or_else(|| not_found(format!("task not found: {}", a.id)))?;let mut g = task.inner.lock().unwrap();// Refresh the tail every time so live tasks aren't stuck at start-time.- g.status.output_tail = render_tail(&g.output_buf);+ g.status.output_tail = g.render_output();Ok(json!(g.status))}+/// Take over a foreground `shell_execute` whose timeout hit (T1).+///+/// WHY A HANDOVER AND NOT "START EVERYTHING AS A TASK": the foreground path+/// has what the task path lacks and the agent needs: stdin, separate stdout+/// and stderr (the git and test parsers read stdout alone), and the Stop+/// wiring through `shell_execute_cancel`. Starting every command here and+/// waiting on it would have meant rebuilding all three on this side. The+/// handover moves the live `Child` and the buffers its drain threads already+/// fill, so nothing about the process changes and no output is lost or read+/// twice.+///+/// The child is a `std::process::Child`, not a tokio one, so the reaper is a+/// plain thread. It keeps the same rule the async reaper above keeps: the+/// reap (`try_wait`) and clearing the pid happen in ONE critical section of+/// the task lock, and `kill_all_background_tasks` kills while holding that+/// same lock, so the exit sweep never shoots at a number the kernel has+/// already handed to somebody else.+pub(crate) fn adopt_foreground(+ mut child: std::process::Child,+ command: &str,+ cwd: Option<String>,+ pipes: AdoptedPipes,+) -> String {+ let id = Uuid::new_v4().to_string();+ let (cancel_tx, mut cancel_rx) = tokio::sync::oneshot::channel::<()>();+ let adopted = AdoptedOutput { out: pipes.out_buf, err: pipes.err_buf };+ let inner = Arc::new(Mutex::new(BgTaskInner {+ status: BgTaskStatus {+ id: id.clone(),+ command: command.to_string(),+ cwd,+ started_at: now_secs(),+ finished_at: None,+ exit_code: None,+ running: true,+ cancelled: false,+ output_tail: String::new(),+ },+ output_buf: Vec::new(),+ cancel_tx: Some(cancel_tx),+ pid: Some(child.id()),+ adopted: Some(adopted),+ kept_output: false,+ }));+ arm_exit_sweep();+ REGISTRY.insert(BgTask { inner: Arc::clone(&inner) });++ let (out_done, err_done) = (pipes.out_done, pipes.err_done);+ std::thread::spawn(move || {+ let (exit_code, cancelled) = loop {+ // Empty is the only answer that means "keep going". A sent+ // cancel and a dropped sender both stop the task, as the+ // `&mut cancel_rx` arm of the async reaper does.+ let cancel_requested = !matches!(+ cancel_rx.try_recv(),+ Err(tokio::sync::oneshot::error::TryRecvError::Empty)+ );+ if cancel_requested {+ // Out of the registry BEFORE the kill reaps it, as above.+ let pid = inner.lock().unwrap().pid.take();+ if let Some(pid) = pid {+ crate::commands::shell::kill_tree(pid);+ }+ let _ = child.kill();+ let _ = child.wait();+ break (None, true);+ }+ {+ let mut g = inner.lock().unwrap();+ match child.try_wait() {+ Ok(Some(status)) => {+ g.pid = None;+ break (status.code(), false);+ }+ Ok(None) => {}+ Err(_) => {+ g.pid = None;+ break (None, false);+ }+ }+ }+ std::thread::sleep(REAP_POLL);+ };+ // Never joined: a grandchild can hold the pipes open for as long as+ // it likes. The status reads the live buffers anyway, so a late line+ // still shows up.+ settle(&out_done, &err_done, std::time::Duration::from_millis(500));+ let mut g = inner.lock().unwrap();+ g.status.exit_code = exit_code;+ g.status.cancelled = cancelled;+ g.status.running = false;+ g.status.finished_at = Some(now_secs());+ g.status.output_tail = g.render_output();+ g.cancel_tx = None;+ g.pid = None;+ });+ id+}++/// Keep the output of a FINISHED foreground run readable under a task id, so+/// a tool result that was cut can point at the rest (T1). It is a finished+/// task from the start: nothing to kill, nothing for the sweep.+pub(crate) fn keep_finished_output(+ command: &str,+ cwd: Option<String>,+ exit_code: Option<i32>,+ out: Arc<Mutex<Captured>>,+ err: Arc<Mutex<Captured>>,+) -> String {+ let id = Uuid::new_v4().to_string();+ let now = now_secs();+ let adopted = AdoptedOutput { out, err };+ let output_tail = render_adopted(&adopted);+ let inner = Arc::new(Mutex::new(BgTaskInner {+ status: BgTaskStatus {+ id: id.clone(),+ command: command.to_string(),+ cwd,+ started_at: now,+ finished_at: Some(now),+ exit_code,+ running: false,+ cancelled: false,+ output_tail,+ },+ output_buf: Vec::new(),+ cancel_tx: None,+ pid: None,+ adopted: Some(adopted),+ kept_output: true,+ }));+ REGISTRY.insert(BgTask { inner });+ id+}+pub(crate) async fn shell_task_kill_impl(args: &Value) -> CmdResult {let a: IdArgs = serde_json::from_value(args.clone()).map_err(|e| bad_request(e.to_string()))?;let task = REGISTRY@@ -1274,6 +1479,7 @@ mod foreground_parity_tests {// beiden Wege, nicht den Stop. Der hat seine eigenen Tests in// commands/shell.rs.None,+ None,).await.expect("the foreground shell tool ran");@@ -1378,3 +1584,175 @@ mod foreground_parity_tests {);}}++/// T1: a foreground `shell_execute` that runs into its timeout moves into the+/// registry instead of dying, and everything that ends a task still ends it.+///+/// Unix only. The handover itself is platform neutral, but the commands and+/// the pid checks here are POSIX (`sh`, `$!`); the Windows path differs only+/// in the Job Object at spawn, which these tests cannot observe from a Mac.+///+/// Lauf: cargo test --lib handover+#[cfg(all(test, unix))]+mod handover_tests {+ use super::*;++ /// One foreground call, in a folder of its own so neither path falls+ /// back to the per-chat workspace in $HOME.+ async fn run(command: &str, timeout_ms: u64, hand_over: bool) -> Value {+ let dir = tempfile::tempdir().expect("tempdir");+ let path = dir.path().to_string_lossy().to_string();+ let command = command.to_string();+ let out = tokio::task::spawn_blocking(move || {+ crate::commands::shell::shell_execute_sync(+ command,+ None,+ Some(path.clone()),+ Some(timeout_ms),+ Some("sh".into()),+ None,+ None,+ Some(path),+ None,+ hand_over,+ )+ })+ .await+ .expect("join")+ .expect("the shell ran");+ drop(dir);+ out+ }++ fn alive(pid: u32) -> bool {+ let mut sys = sysinfo::System::new();+ sys.refresh_processes(sysinfo::ProcessesToUpdate::All, true);+ sys.process(sysinfo::Pid::from_u32(pid)).is_some()+ }++ async fn gone_within(pid: u32, secs: u64) {+ let deadline = std::time::Instant::now() + std::time::Duration::from_secs(secs);+ while alive(pid) {+ assert!(std::time::Instant::now() < deadline, "pid {pid} survived");+ tokio::time::sleep(std::time::Duration::from_millis(100)).await;+ }+ }++ /// The pid `sh` printed for its background `sleep`.+ fn first_line_pid(stdout: &str) -> u32 {+ stdout+ .lines()+ .next()+ .and_then(|l| l.trim().parse().ok())+ .expect("a pid on the first line")+ }++ #[tokio::test]+ async fn a_timed_out_command_keeps_running_as_a_task_and_finishes_there() {+ let _isolation = super::sweep_isolation().await;+ let out = run("echo before; sleep 2; echo after", 400, true).await;+ assert_eq!(out["timedOut"], true);+ assert_eq!(out["exitCode"], -1);+ let id = out["taskId"].as_str().expect("a task id").to_string();+ let so_far = out["stdout"].as_str().unwrap();+ assert!(so_far.contains("before"), "{so_far}");+ assert!(!so_far.contains("after"), "{so_far}");++ let st = shell_task_status_impl(&json!({ "id": id })).await.unwrap();+ assert_eq!(st["running"], true, "the process was killed instead of handed over");++ finish_test_task(&id).await;+ let st = shell_task_status_impl(&json!({ "id": id })).await.unwrap();+ assert_eq!(st["exit_code"], 0);+ assert_eq!(st["cancelled"], false);+ let all = st["output_tail"].as_str().unwrap();+ assert!(all.contains("before") && all.contains("after"), "{all}");+ }++ #[tokio::test]+ async fn killing_a_handed_over_task_takes_its_tree_down() {+ let _isolation = super::sweep_isolation().await;+ let out = run("sleep 30 & echo $!; wait", 400, true).await;+ let id = out["taskId"].as_str().expect("a task id").to_string();+ let worker = first_line_pid(out["stdout"].as_str().unwrap());+ assert!(alive(worker), "the worker died with the timeout");++ let r = shell_task_kill_impl(&json!({ "id": id })).await.unwrap();+ assert_eq!(r["cancelled"], true);+ finish_test_task(&id).await;+ let st = shell_task_status_impl(&json!({ "id": id })).await.unwrap();+ assert_eq!(st["cancelled"], true);+ gone_within(worker, 5).await;+ }++ #[tokio::test]+ async fn the_exit_sweep_reaches_a_handed_over_task() {+ let _isolation = super::sweep_isolation().await;+ let out = run("sleep 30 & echo $!; wait", 400, true).await;+ let id = out["taskId"].as_str().expect("a task id").to_string();+ let worker = first_line_pid(out["stdout"].as_str().unwrap());++ kill_all_background_tasks();+ gone_within(worker, 5).await;+ finish_test_task(&id).await;+ assert!(+ REGISTRY.get(&id).and_then(|t| t.inner.lock().unwrap().pid).is_none(),+ "a finished task still carries a pid",+ );+ }++ #[tokio::test]+ async fn without_the_switch_the_timeout_still_kills() {+ let _isolation = super::sweep_isolation().await;+ let out = run("sleep 30 & echo $!; wait", 400, false).await;+ assert_eq!(out["timedOut"], true);+ assert!(out.get("taskId").is_none(), "{out}");+ let worker = first_line_pid(out["stdout"].as_str().unwrap());+ gone_within(worker, 5).await;+ }++ #[tokio::test]+ async fn a_long_finished_output_stays_readable_under_an_id() {+ let out = run(+ "i=0; while [ $i -lt 400 ]; do echo line-$i-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx; i=$((i+1)); done; echo END",+ 20_000,+ true,+ )+ .await;+ assert_eq!(out["timedOut"], false);+ assert_eq!(out["exitCode"], 0);+ let id = out["outputId"].as_str().expect("an output id").to_string();+ let st = shell_task_status_impl(&json!({ "id": id })).await.unwrap();+ assert_eq!(st["running"], false);+ let all = st["output_tail"].as_str().unwrap();+ assert!(all.contains("line-0-") && all.contains("line-399-"), "{all}");+ assert!(all.trim_end().ends_with("END"), "{all}");+ // Nothing to kill on a kept output.+ let r = shell_task_kill_impl(&json!({ "id": id })).await.unwrap();+ assert_eq!(r["cancelled"], false);++ let short = run("echo short", 20_000, true).await;+ assert!(short.get("outputId").is_none(), "{short}");+ }++ #[test]+ fn kept_outputs_have_their_own_cap() {+ let ids: Vec<String> = (0..KEPT_OUTPUTS_MAX + 5)+ .map(|i| {+ let out = Arc::new(Mutex::new(Captured::default()));+ let err = Arc::new(Mutex::new(Captured::default()));+ keep_finished_output(&format!("echo {i}"), None, Some(0), out, err)+ })+ .collect();+ assert!(REGISTRY.get(&ids[0]).is_none(), "the oldest kept output was not dropped");+ assert!(REGISTRY.get(ids.last().unwrap()).is_some());+ let kept = REGISTRY+ .tasks+ .lock()+ .unwrap()+ .iter()+ .filter(|t| t.inner.lock().unwrap().kept_output)+ .count();+ assert!(kept <= KEPT_OUTPUTS_MAX, "{kept} kept outputs");+ }+}diff --git a/src-tauri/src/commands/remote.rs b/src-tauri/src/commands/remote.rsindex 08f42a41..04947883 100644--- a/src-tauri/src/commands/remote.rs+++ b/src-tauri/src/commands/remote.rs@@ -1309,7 +1309,10 @@ async fn handle_agent_tool(// 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+ // `Some(true)` (T1): a command that outruns its timeout keeps+ // running as a task the phone reaches with task "status" /+ // "kill" above, as the shared tool description promises.+ crate::commands::shell::shell_execute(command, None, cwd, timeout, shell, stdin, chat_id.clone(), None, None, Some(true)).await}}"system_info" => crate::commands::system::system_info(),diff --git a/src-tauri/src/commands/shell.rs b/src-tauri/src/commands/shell.rsindex 4b4da3bc..bcc6e369 100644--- a/src-tauri/src/commands/shell.rs+++ b/src-tauri/src/commands/shell.rs@@ -183,6 +183,53 @@ pub(crate) fn captured_text(buf: &Arc<Mutex<Captured>>) -> String {text}+/// Everything a capture still holds, in stream order: the head `kept`, a+/// marker for the bytes that fell between head and tail, and the tail ring.+///+/// `captured_text` stops at the head, which is right for a probe but wrong+/// for the agent's terminal: a build that printed 300 KiB ended at the 256 KiB+/// mark, and the last lines the model saw were not the last lines the build+/// wrote, which is where the error stands. The agent tool cuts this to its own+/// head and tail in TypeScript (`cutShellOutput` in builtin-tools.ts); the+/// whole text stays readable as a task in `bg_tasks`.+pub(crate) fn captured_full(buf: &Arc<Mutex<Captured>>) -> String {+ let c = match buf.lock() {+ Ok(c) => c,+ Err(poisoned) => poisoned.into_inner(),+ };+ let head = strip_ansi(&String::from_utf8_lossy(&c.kept));+ if c.total <= c.kept.len() {+ return head;+ }+ let tail: Vec<u8> = c.tail.iter().copied().collect();+ // Where the ring starts in the stream, and how much of it the head+ // already covers.+ let tail_start = c.total - tail.len();+ let overlap = c.kept.len().saturating_sub(tail_start).min(tail.len());+ let lost = tail_start.saturating_sub(c.kept.len());+ let mut text = head;+ if lost > 0 {+ text.push_str(&format!("\n[output truncated: {} bytes in the middle not kept]\n", lost));+ }+ text.push_str(&strip_ansi(&String::from_utf8_lossy(&tail[overlap..])));+ text+}++/// How many bytes went through a capture in all, kept or not.+pub(crate) fn captured_total(buf: &Arc<Mutex<Captured>>) -> usize {+ match buf.lock() {+ Ok(c) => c.total,+ Err(poisoned) => poisoned.into_inner().total,+ }+}++/// From this many captured bytes on, a finished foreground run is also kept+/// in the task registry, so the model can read what the tool result cut.+/// The TypeScript side cuts from 8000 characters on (2000 head + 6000 tail,+/// `SHELL_HEAD_CHARS` + `SHELL_TAIL_CHARS`), and a character is never less+/// than one byte here, so every result that gets cut has a task behind it.+pub(crate) const KEEP_OUTPUT_FROM_BYTES: usize = 8_000;+/// Die letzten `max_lines` nicht leeren Zeilen einer Ausgabe, aus dem/// Ringpuffer statt aus dem Anfang (C81). Die erste Zeile im Puffer kann/// abgeschnitten sein und faellt deshalb weg, sobald der Puffer voll war.@@ -929,10 +976,18 @@ pub(crate) fn default_shell(windows: bool) -> &'static str {}}-/// The eight arguments are the IPC contract: `#[tauri::command]` derives the+/// The arguments are the IPC contract: `#[tauri::command]` derives the/// invoke payload from this signature, so folding them into a struct would/// change the JSON the frontend sends. `clippy::too_many_arguments` is allowed/// here for that reason and not as a matter of taste.+///+/// `backgroundOnTimeout` (T1, CA rebuild): with `true`, a command that is+/// still running when its timeout hits is NOT killed. It moves into the+/// background-task registry (`bg_tasks::adopt_foreground`, the same ids as+/// `shell_task_*`) and the reply carries `taskId`. Without it, or with+/// `false`, the timeout kills the tree as it always has: every caller other+/// than the agent's terminal tool (the retired git helpers, the phone's remote+/// path) has nobody who would ever read or stop such a task.#[tauri::command]#[allow(non_snake_case, clippy::too_many_arguments)]pub async fn shell_execute(@@ -945,9 +1000,21 @@ pub async fn shell_execute(chatId: Option<String>,workingDirectory: Option<String>,callId: Option<String>,+ backgroundOnTimeout: Option<bool>,) -> Result<serde_json::Value, String> {tokio::task::spawn_blocking(move || {- shell_execute_sync(command, args, cwd, timeout, shell, stdin, chatId, workingDirectory, callId)+ shell_execute_sync(+ command,+ args,+ cwd,+ timeout,+ shell,+ stdin,+ chatId,+ workingDirectory,+ callId,+ backgroundOnTimeout.unwrap_or(false),+ )}).await.map_err(|e| format!("Task join error: {}", e))?@@ -957,7 +1024,7 @@ pub async fn shell_execute(/// blocking half of the same command, and a different shape here would be a/// second place to keep in step with the frontend contract.#[allow(clippy::too_many_arguments)]-fn shell_execute_sync(+pub(crate) fn shell_execute_sync(command: String,args: Option<Vec<String>>,cwd: Option<String>,@@ -967,6 +1034,7 @@ fn shell_execute_sync(chat_id: Option<String>,working_directory: Option<String>,call_id: Option<String>,+ background_on_timeout: bool,) -> 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.@@ -1040,6 +1108,17 @@ fn shell_execute_sync(let mut child = cmd.spawn().map_err(|e| format!("Spawn shell: {}", os_error::english(&e)))?;+ // A run that may outlive this call joins the kill-on-close Job Object at+ // once, exactly like a task started by `shell_task_start`: on Windows the+ // job is what takes background tasks down when LU quits (the atexit sweep+ // in bg_tasks is not armed there). At spawn and not at the handover,+ // because a job only catches the children created after the assignment,+ // and by the timeout the shell has long started its worker.+ #[cfg(target_os = "windows")]+ if background_on_timeout {+ crate::commands::process::assign_pid_to_kill_on_close_job(child.id());+ }+// 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.@@ -1096,14 +1175,56 @@ fn shell_execute_sync(match child.try_wait() {Ok(Some(status)) => {settle(&out_done, &err_done, std::time::Duration::from_millis(500));- return Ok(serde_json::json!({- "stdout": captured_text(&out_buf),- "stderr": captured_text(&err_buf),- "exitCode": status.code().unwrap_or(-1),+ let exit_code = status.code().unwrap_or(-1);+ let mut reply = serde_json::json!({+ "stdout": captured_full(&out_buf),+ "stderr": captured_full(&err_buf),+ "exitCode": exit_code,"timedOut": false,- }));+ });+ // A long result gets cut in the tool reply; what was cut stays+ // readable under this id (`shell_task_status`). Only the agent+ // tool asks for it, the same switch as the handover below.+ if background_on_timeout+ && captured_total(&out_buf) + captured_total(&err_buf) >= KEEP_OUTPUT_FROM_BYTES+ {+ let id = crate::commands::bg_tasks::keep_finished_output(+ &command,+ workdir_text(&workdir),+ status.code(),+ out_buf,+ err_buf,+ );+ reply["outputId"] = serde_json::Value::String(id);+ }+ return Ok(reply);}Ok(None) => {+ if start.elapsed() > timeout_dur && background_on_timeout {+ // HANDOVER instead of a kill (T1). The child, its pipe+ // readers and their buffers move into the task registry as+ // they are: nothing is restarted, nothing is read twice,+ // and the process never notices. From here on the+ // registry's reaper owns it, `shell_task_kill` and the+ // exit sweep reach it like any other task, and this call+ // returns what was printed so far.+ let stdout_so_far = captured_full(&out_buf);+ let stderr_so_far = captured_full(&err_buf);+ let id = crate::commands::bg_tasks::adopt_foreground(+ child,+ &command,+ workdir_text(&workdir),+ crate::commands::bg_tasks::AdoptedPipes { out_buf, err_buf, out_done, err_done },+ );+ return Ok(serde_json::json!({+ "stdout": stdout_so_far,+ "stderr": stderr_so_far,+ "exitCode": -1,+ "timedOut": true,+ "taskId": id,+ "timeoutMs": timeout_ms,+ }));+ }if start.elapsed() > timeout_dur {kill_tree(child.id());let _ = child.kill();@@ -1130,6 +1251,11 @@ fn shell_execute_sync(}}+/// The folder a run happened in, as the task registry shows it.+fn workdir_text(workdir: &Path) -> Option<String> {+ workdir.is_dir().then(|| workdir.to_string_lossy().to_string())+}+/// Der Abbruch eines schon gestarteten Befehls.////// Geprueft wird die BUCHFUEHRUNG, nicht das Toeten selbst: `kill_tree` haengt@@ -1534,6 +1660,7 @@ mod tests {None,None,None,+ false,).expect("the shell ran");let seen = out["stdout"].as_str().unwrap_or_default().to_string();@@ -1591,6 +1718,40 @@ mod tests {assert_eq!(text, "hello\n");}+ fn capture_full(bytes: Vec<u8>) -> String {+ let (buf, done) = drain(Cursor::new(bytes));+ settle(&done, &done, std::time::Duration::from_secs(2));+ captured_full(&buf)+ }++ /// T1: the agent's terminal reads the END of a long output too. Past the+ /// head, `captured_text` only said "truncated"; the last lines, where a+ /// build prints its error, were gone.+ #[test]+ fn the_full_capture_keeps_head_and_the_real_end() {+ let mut bytes = vec![b'a'; MAX_CAPTURE + 100_000];+ bytes.extend_from_slice(b"THE-LAST-LINE\n");+ let text = capture_full(bytes.clone());+ assert!(text.starts_with("aaaa"));+ assert!(text.ends_with("THE-LAST-LINE\n"), "the tail is missing");+ let lost = bytes.len() - MAX_CAPTURE - TAIL_CAPTURE;+ assert!(text.contains(&format!("[output truncated: {lost} bytes in the middle not kept]")), "no marker");+ }++ /// Head and tail overlap when the stream is only a little longer than the+ /// head: then nothing is lost and nothing may appear twice.+ #[test]+ fn an_overlapping_tail_is_not_repeated() {+ let bytes: Vec<u8> = (0..MAX_CAPTURE + 4_000).map(|i| b'a' + (i % 26) as u8).collect();+ let text = capture_full(bytes.clone());+ assert_eq!(text.as_bytes(), &bytes[..], "the stream did not come back exactly once");+ }++ #[test]+ fn a_short_full_capture_is_the_output_itself() {+ assert_eq!(capture_full(b"hello\n".to_vec()), "hello\n");+ }+/// The shell tool creates its fallback cwd with `create_dir_all`. With the/// local sanitiser copy that still allowed `.`, a chat id of ".." resolved/// to `~/agent-workspace/..` — the user's HOME — and every relative commanddiff --git a/src/api/agents/__tests__/shell-result.test.ts b/src/api/agents/__tests__/shell-result.test.tsnew file mode 100644index 00000000..5e91621d--- /dev/null+++ b/src/api/agents/__tests__/shell-result.test.ts@@ -0,0 +1,77 @@+/**+ * T1: the text rules of the terminal tool's result (agents/shell-result.ts).+ *+ * Run: npx vitest run src/api/agents/__tests__/shell-result.test.ts+ */+import { describe, it, expect } from 'vitest'+import {+ cutShellOutput,+ joinShellStreams,+ renderHandedOver,+ SHELL_HEAD_CHARS,+ SHELL_TAIL_CHARS,+} from '../shell-result'+import { truncateToolResult } from '../../../lib/truncate-tool-result'+import { resultCharsFor } from '../../../lib/agent-profile'++describe('cutShellOutput', () => {+ it('leaves an output up to head plus tail alone', () => {+ const text = 'a'.repeat(SHELL_HEAD_CHARS + SHELL_TAIL_CHARS)+ expect(cutShellOutput(text, 'id')).toBe(text)+ })++ it('keeps exactly the head and the tail and says what is missing', () => {+ const head = 'H'.repeat(SHELL_HEAD_CHARS)+ const middle = 'm\n'.repeat(500)+ const tail = 'T'.repeat(SHELL_TAIL_CHARS)+ const out = cutShellOutput(head + middle + tail)+ expect(out.startsWith(head)).toBe(true)+ expect(out.endsWith(tail)).toBe(true)+ expect(out).toContain(`[… ${middle.length} characters (500 lines) cut …]`)+ expect(out).not.toContain('task_id')+ })++ it('names where the full output is when there is an id', () => {+ const out = cutShellOutput('x'.repeat(20000), 'abc')+ expect(out).toContain('Full output: shell_execute with task "status" and task_id "abc".')+ })++ it('the compact profile cap still applies on top and keeps the end', () => {+ const text = `${'a'.repeat(30000)}END`+ const cut = cutShellOutput(text, 'abc')+ // The profile caps in the run loop; the tool result fits under the+ // compact cap, so the cap leaves it whole.+ expect(truncateToolResult(cut, resultCharsFor('compact'))).toBe(cut)+ // The tiny profile cuts further, and the end still survives.+ expect(truncateToolResult(cut, resultCharsFor('tiny')).endsWith('END')).toBe(true)+ })+})++describe('joinShellStreams', () => {+ it('marks stderr only when both streams have something', () => {+ expect(joinShellStreams('out\n', '')).toBe('out')+ expect(joinShellStreams('', 'err\n')).toBe('[stderr]\nerr')+ expect(joinShellStreams('out', 'err')).toBe('out\n[stderr]\nerr')+ })+})++describe('renderHandedOver', () => {+ it('says the command still runs, under which id, and how to read and stop it', () => {+ const out = renderHandedOver({ taskId: 't-1', timeoutMs: 120000, stdout: 'step 1\n', stderr: 'warn\n' })+ expect(out).toContain('Still running after 120 s, so it was not stopped')+ expect(out).toContain('in the background as task t-1.')+ expect(out).toContain('Output so far:\nstep 1\n[stderr]\nwarn')+ expect(out).toContain('Use check_tasks to read its output, or shell_execute with task "kill" and task_id "t-1" to stop it.')+ })++ it('a command that printed nothing yet says so', () => {+ expect(renderHandedOver({ taskId: 't-2', stdout: '', stderr: '' })).toContain('(no output so far)')+ })++ it('cuts a long output so far to head and tail', () => {+ const out = renderHandedOver({ taskId: 't-3', stdout: `${'z'.repeat(20000)}LAST`, stderr: '' })+ expect(out).toContain('LAST')+ expect(out).toContain('characters (')+ expect(out.length).toBeLessThan(SHELL_HEAD_CHARS + SHELL_TAIL_CHARS + 500)+ })+})diff --git a/src/api/agents/agent-task-tools.ts b/src/api/agents/agent-task-tools.tsindex 18095736..859f9108 100644--- a/src/api/agents/agent-task-tools.ts+++ b/src/api/agents/agent-task-tools.ts@@ -66,23 +66,63 @@ export const MESSAGE_AGENT_TOOL_DEF: MCPToolDefinition = {source: 'builtin',}+/**+ * How much of a shell task's output check_tasks shows: the end, where a+ * build or a server prints what matters now. The whole output is one+ * `shell_execute` with `task: "status"` away, and the line says so.+ */+export const SHELL_TASK_OUTPUT_CHARS = 2000++/**+ * The shell tasks of this conversation (T1): the ones a timeout handed over+ * and the ones started with `background: true`. A task the registry no+ * longer knows (evicted, or the app restarted) is left out, not reported as+ * an error: there is nothing the model could do about it.+ */+async function shellTaskBlocks(convId: string): Promise<string[]> {+ const { shellTasksOf, bgStatus, renderBgStatusOneLine } = await import('./bg-tasks')+ const ids = shellTasksOf(convId)+ const blocks: string[] = []+ for (const id of ids) {+ let s+ try {+ s = await bgStatus(id)+ } catch {+ continue+ }+ const kopf = `shell ${renderBgStatusOneLine(s)} (task_id ${s.id})`+ const out = (s.output_tail || '').replace(/\s+$/, '')+ if (!out) {+ blocks.push(`${kopf}\n(no output so far)`)+ continue+ }+ const cut = out.length > SHELL_TASK_OUTPUT_CHARS+ const tail = cut ? `…${out.slice(-SHELL_TASK_OUTPUT_CHARS)}` : out+ const more = cut ? `\n[last ${SHELL_TASK_OUTPUT_CHARS} of ${out.length} characters; all of it: shell_execute with task "status" and this task_id]` : ''+ blocks.push(`${kopf}\n${tail}${more}`)+ }+ return blocks+}+export function buildCheckTasksExecutor() {return async (_args: ToolArgs, run?: AgentRunContext): Promise<string> => {const convId = run?.conversationIdif (!convId) return 'No conversation, so there are no background tasks to list.'const { useAgentTaskStore } = await import('../../stores/agentTaskStore')const alle = useAgentTaskStore.getState().forConv(convId)- if (!alle.length) return 'No background tasks in this conversation.'+ const shell = await shellTaskBlocks(convId)+ if (!alle.length && !shell.length) return 'No background tasks in this conversation.'const now = Date.now()// Die fertigen tragen ihre Antwort gleich mit: das Modell hat sonst die// Kennung, muesste dann aber ein zweites Werkzeug rufen, um an das// Ergebnis zu kommen — und genau dafuer reicht ein kleines Modell nicht.- return alle.map((t) => {+ const agents = alle.map((t) => {const kopf = renderTaskOneLine(t, now)if (!isTerminal(t.status)) return kopfconst leib = t.status === 'done' ? (t.output || '(no answer)') : (t.error || `(${t.status})`)return `${kopf}\n${leib}`- }).join('\n\n')+ })+ return [...agents, ...shell].join('\n\n')}}diff --git a/src/api/agents/bg-tasks.ts b/src/api/agents/bg-tasks.tsindex d80d3f0f..51f3472f 100644--- a/src/api/agents/bg-tasks.ts+++ b/src/api/agents/bg-tasks.ts@@ -57,6 +57,34 @@ export async function bgList(): Promise<BgTaskListResult> {return backendCall<BgTaskListResult>('shell_task_list', { args: {} })}+/**+ * Which shell tasks a conversation started (T1). The Rust registry knows no+ * conversations, and check_tasks must list only the tasks of the chat that+ * asks, so the frontend keeps the pairing. Module state: a task dies with the+ * app (exit sweep, Job Object on Windows), so there is nothing to persist.+ * After a webview reload the pairing is gone while a task may still run; it+ * stays reachable through shell_execute with task "list".+ */+const SHELL_TASKS_BY_CONV = new Map<string, string[]>()+/** Per conversation; the registry itself caps at 200 tasks. */+const SHELL_TASKS_PER_CONV_MAX = 20++export function rememberShellTask(convId: string | null | undefined, id: string): void {+ if (!convId || !id) return+ const ids = (SHELL_TASKS_BY_CONV.get(convId) ?? []).filter((x) => x !== id)+ ids.push(id)+ SHELL_TASKS_BY_CONV.set(convId, ids.slice(-SHELL_TASKS_PER_CONV_MAX))+}++export function shellTasksOf(convId: string | null | undefined): string[] {+ return convId ? [...(SHELL_TASKS_BY_CONV.get(convId) ?? [])] : []+}++/** Tests only. */+export function _resetShellTasksForTests(): void {+ SHELL_TASKS_BY_CONV.clear()+}+/** Renders a status payload as a one-line summary for the model / UI. */export function renderBgStatusOneLine(s: BgTaskStatus): string {const phase = s.runningdiff --git a/src/api/agents/shell-result.ts b/src/api/agents/shell-result.tsnew file mode 100644index 00000000..55317651--- /dev/null+++ b/src/api/agents/shell-result.ts@@ -0,0 +1,76 @@+/**+ * What the terminal tool hands back to the model when a command printed a+ * lot, or is still running at its timeout (T1, CA rebuild).+ *+ * Pure text rules, no backend: the executor in builtin-tools.ts calls these,+ * the tests read them directly.+ *+ * The shape follows Claude Code and Codex: the start of a long output (the+ * command echo, the first error) and its end (the summary, the last error)+ * travel, the middle does not, and the cut says how much went missing and+ * where the rest is. The agent profile's own cap (16 000 characters for the+ * compact profile, `resultCharsFor` in lib/agent-profile.ts) still applies on+ * top, in the run loop, to whatever this returns.+ */++/** Characters kept from the start of a long output. */+export const SHELL_HEAD_CHARS = 2000+/** Characters kept from the end of a long output. */+export const SHELL_TAIL_CHARS = 6000++/**+ * Keep the first SHELL_HEAD_CHARS and the last SHELL_TAIL_CHARS of `text`,+ * with a marker in between that says how much was cut. `outputId` names the+ * task under which the whole output can be read; without it the marker says+ * only what was cut.+ *+ * Rust keeps a task for every output of 8000 bytes or more+ * (`KEEP_OUTPUT_FROM_BYTES` in shell.rs), and a character is never shorter+ * than a byte there, so whenever this cuts, Rust has kept the output.+ */+export function cutShellOutput(text: string, outputId?: string): string {+ if (text.length <= SHELL_HEAD_CHARS + SHELL_TAIL_CHARS) return text+ const head = text.slice(0, SHELL_HEAD_CHARS)+ const tail = text.slice(text.length - SHELL_TAIL_CHARS)+ const middle = text.slice(SHELL_HEAD_CHARS, text.length - SHELL_TAIL_CHARS)+ const lines = middle.split('\n').length - 1+ const where = outputId+ ? ` Full output: shell_execute with task "status" and task_id "${outputId}".`+ : ''+ return `${head}\n\n[… ${middle.length} characters (${lines} lines) cut …${where}]\n\n${tail}`+}++/** stdout and stderr as one text, stderr under a marker when both have something. */+export function joinShellStreams(stdout: string, stderr: string): string {+ const out = stdout.replace(/\s+$/, '')+ const err = stderr.replace(/\s+$/, '')+ if (!err) return out+ if (!out) return `[stderr]\n${err}`+ return `${out}\n[stderr]\n${err}`+}++/**+ * The result for a command that was still running at its timeout and now+ * runs on as a background task. The id is the one `shell_execute` with+ * `task: "status" | "kill"` and check_tasks know.+ *+ * The stop path is named as a shell_execute call and not as check_tasks:+ * check_tasks only reads, it runs without a confirmation, and killing a+ * process stays behind the same gate as starting one (and is refused in a+ * read-only turn).+ */+export function renderHandedOver(input: {+ taskId: string+ timeoutMs?: number+ stdout: string+ stderr: string+}): string {+ const secs = input.timeoutMs ? `${Math.round(input.timeoutMs / 1000)} s` : 'its timeout'+ const soFar = joinShellStreams(input.stdout, input.stderr)+ const body = soFar ? `Output so far:\n${cutShellOutput(soFar)}` : '(no output so far)'+ return (+ `Still running after ${secs}, so it was not stopped: it keeps running in the background as task ${input.taskId}.\n`+ + `${body}\n`+ + `Use check_tasks to read its output, or shell_execute with task "kill" and task_id "${input.taskId}" to stop it.`+ )+}diff --git a/src/api/backend.ts b/src/api/backend.tsindex 98af7ffb..e1c62913 100644--- a/src/api/backend.ts+++ b/src/api/backend.ts@@ -764,6 +764,12 @@ export async function backendCall<T = unknown>(remote_create_snapshot: { path: "/local-api/remote-create-snapshot" },// Agent tools (Phase 1 — new commands)shell_execute: { path: "/local-api/shell-execute", method: "POST" },+ // T1: a shell_execute that outran its timeout runs on as a task in the+ // dev server too (dev-server/exec-routes.ts), so the bench can read and+ // stop it like the app does.+ shell_task_status: { path: "/local-api/shell-task-status", method: "POST" },+ shell_task_kill: { path: "/local-api/shell-task-kill", method: "POST" },+ shell_task_list: { path: "/local-api/shell-task-list", method: "POST" },fs_read: { path: "/local-api/fs-read", method: "POST" },// Capped, jailed byte read for the Explorer image preview (2.6.6 C3).// Without this entry the browser dev surface answered "Unknown backenddiff --git a/src/api/mcp/__tests__/shell-timeout-handover.test.ts b/src/api/mcp/__tests__/shell-timeout-handover.test.tsnew file mode 100644index 00000000..244dd8b6--- /dev/null+++ b/src/api/mcp/__tests__/shell-timeout-handover.test.ts@@ -0,0 +1,185 @@+/**+ * T1 (CA rebuild): a command that outruns its timeout is not killed but keeps+ * running as a background task, and the model learns that, with the output so+ * far and the task id. check_tasks then reads the moved task, Stop still+ * reaches it, and a long finished output comes back as head and tail with a+ * pointer to the rest.+ *+ * The Rust half (the handover itself, kill, the exit sweep) has its own tests+ * in src-tauri/src/commands/bg_tasks.rs (`handover_tests`).+ *+ * Run: npx vitest run src/api/mcp/__tests__/shell-timeout-handover.test.ts+ */+import { describe, it, expect, vi, beforeEach } from 'vitest'++const backendCalls: { cmd: string; body: Record<string, unknown> }[] = []+/** What the next shell_execute answers. */+let shellReply: Record<string, unknown> = {}+/** What shell_task_status answers, per id. */+const statuses = new Map<string, Record<string, unknown>>()++vi.mock('../../backend', () => ({+ backendCall: vi.fn(async (cmd: string, body: Record<string, unknown>) => {+ backendCalls.push({ cmd, body })+ if (cmd === 'shell_execute') return shellReply+ if (cmd === 'shell_task_status') {+ const id = (body.args as { id: string }).id+ const s = statuses.get(id)+ if (!s) throw new Error(`task not found: ${id}`)+ return s+ }+ if (cmd === 'shell_task_kill') return { ok: true, cancelled: true }+ return { ok: true }+ }),+ fetchExternal: vi.fn(async () => ({ ok: true, status: 200, text: async () => '' })),+}))+vi.mock('../../agents/sub-agent', () => ({+ DELEGATE_TASK_TOOL_DEF: { name: 'delegate_task', description: '', category: 'system', inputSchema: {} },+ buildDelegateExecutor: () => async () => 'stub',+}))+vi.mock('../../../lib/workflow-engine', () => ({ WorkflowEngine: class {} }))++import { registerBuiltinTools } from '../builtin-tools'+import { ToolRegistry } from '../tool-registry'+import type { AgentRunContext } from '../../agent-context'+import { _resetShellTasksForTests, shellTasksOf } from '../../agents/bg-tasks'+import { SHELL_HEAD_CHARS, SHELL_TAIL_CHARS } from '../../agents/shell-result'++function makeRun(over: Partial<AgentRunContext> = {}): AgentRunContext {+ return {+ token: 'test-run',+ chatId: null,+ conversationId: 'conv-t1',+ workspace: null,+ artifactMode: false,+ readOnlyShellTurn: false,+ mode: null,+ artifacts: [],+ ...over,+ }+}++const registry = new ToolRegistry()+registerBuiltinTools(registry)++const TASK = '0f0e0d0c-1111-2222-3333-444455556666'++function runningStatus(output: string): Record<string, unknown> {+ return {+ id: TASK,+ command: 'npm run build',+ cwd: '/ws',+ started_at: Math.floor(Date.now() / 1000) - 130,+ finished_at: null,+ exit_code: null,+ running: true,+ cancelled: false,+ output_tail: output,+ }+}++beforeEach(() => {+ backendCalls.length = 0+ statuses.clear()+ _resetShellTasksForTests()+ shellReply = { stdout: 'ok', stderr: '', exitCode: 0, timedOut: false }+})++describe('a timeout hands the command over instead of killing it', () => {+ it('asks the backend for the handover', async () => {+ await registry.execute('shell_execute', { command: 'echo hi' }, 1, makeRun())+ const call = backendCalls.find((c) => c.cmd === 'shell_execute')+ expect(call?.body.backgroundOnTimeout).toBe(true)+ })++ it('tells the model the task id, the output so far and how to read or stop it', async () => {+ shellReply = { stdout: 'compiling 1/3\n', stderr: '', exitCode: -1, timedOut: true, taskId: TASK, timeoutMs: 120000 }+ const out = await registry.execute('shell_execute', { command: 'npm run build' }, 1, makeRun())+ expect(out).toContain(`in the background as task ${TASK}`)+ expect(out).toContain('Still running after 120 s')+ expect(out).toContain('compiling 1/3')+ expect(out).toContain('check_tasks')+ expect(out).toContain(`task "kill" and task_id "${TASK}"`)+ expect(out).not.toMatch(/^Timed out/)+ expect(shellTasksOf('conv-t1')).toEqual([TASK])+ })++ it('check_tasks reads the moved task of this conversation', async () => {+ shellReply = { stdout: 'compiling 1/3\n', stderr: '', exitCode: -1, timedOut: true, taskId: TASK, timeoutMs: 120000 }+ await registry.execute('shell_execute', { command: 'npm run build' }, 1, makeRun())+ statuses.set(TASK, runningStatus('compiling 1/3\ncompiling 2/3\n'))++ const listed = await registry.execute('check_tasks', {}, 1, makeRun())+ expect(listed).toContain(`task_id ${TASK}`)+ expect(listed).toContain('running')+ expect(listed).toContain('compiling 2/3')++ // Another conversation does not see it.+ const other = await registry.execute('check_tasks', {}, 1, makeRun({ conversationId: 'conv-other' }))+ expect(other).toBe('No background tasks in this conversation.')+ })++ it('check_tasks shows the end of a long task output and says where the rest is', async () => {+ shellReply = { stdout: '', stderr: '', exitCode: -1, timedOut: true, taskId: TASK }+ await registry.execute('shell_execute', { command: 'npm run build' }, 1, makeRun())+ statuses.set(TASK, runningStatus(`${'x'.repeat(5000)}THE-END`))+ const listed = await registry.execute('check_tasks', {}, 1, makeRun())+ expect(listed).toContain('THE-END')+ expect(listed).toContain('shell_execute with task "status"')+ expect(listed.length).toBeLessThan(3000)+ })++ it('a task the registry no longer knows is left out of check_tasks', async () => {+ shellReply = { stdout: '', stderr: '', exitCode: -1, timedOut: true, taskId: TASK }+ await registry.execute('shell_execute', { command: 'npm run build' }, 1, makeRun())+ const listed = await registry.execute('check_tasks', {}, 1, makeRun())+ expect(listed).toBe('No background tasks in this conversation.')+ })++ it('Stop after the handover kills the task', async () => {+ shellReply = { stdout: '', stderr: '', exitCode: -1, timedOut: true, taskId: TASK }+ const ctrl = new AbortController()+ await registry.execute('shell_execute', { command: 'npm run build' }, 1, makeRun(), ctrl.signal)+ expect(backendCalls.filter((c) => c.cmd === 'shell_task_kill')).toHaveLength(0)+ ctrl.abort()+ await new Promise((r) => setTimeout(r, 0))+ const kills = backendCalls.filter((c) => c.cmd === 'shell_task_kill')+ expect(kills).toHaveLength(1)+ expect(kills[0].body).toEqual({ args: { id: TASK } })+ })++ it('a backend without the handover keeps the old answer', async () => {+ shellReply = { stdout: '', stderr: 'Execution timed out after 1000ms', exitCode: -1, timedOut: true }+ const out = await registry.execute('shell_execute', { command: 'sleep 5' }, 1, makeRun())+ expect(out).toMatch(/^Timed out\./)+ })+})++describe('a long output comes back as head and tail', () => {+ it('keeps the start and the end, counts what was cut and names the id for the rest', async () => {+ const lines = Array.from({ length: 2000 }, (_, i) => `line ${i}`)+ const stdout = `${lines.join('\n')}\n`+ shellReply = { stdout, stderr: '', exitCode: 0, timedOut: false, outputId: 'out-1' }+ const out = await registry.execute('shell_execute', { command: 'cat big.log' }, 1, makeRun())+ expect(out.startsWith('line 0\nline 1\n')).toBe(true)+ expect(out).toContain('line 1999')+ const cut = stdout.length - SHELL_HEAD_CHARS - SHELL_TAIL_CHARS+ expect(out).toContain(`[… ${cut} characters (`)+ expect(out).toContain('task_id "out-1"')+ expect(out.length).toBeLessThan(SHELL_HEAD_CHARS + SHELL_TAIL_CHARS + 300)+ })++ it('a short output is unchanged', async () => {+ shellReply = { stdout: 'hello\n', stderr: '', exitCode: 0, timedOut: false }+ expect(await registry.execute('shell_execute', { command: 'echo hello' }, 1, makeRun())).toBe('hello\n')+ })++ it('a failing command with a long stderr is cut the same way', async () => {+ const stderr = `${'e'.repeat(10000)}\nfatal: the real error`+ shellReply = { stdout: '', stderr, exitCode: 2, timedOut: false, outputId: 'out-2' }+ const out = await registry.execute('shell_execute', { command: 'make' }, 1, makeRun())+ expect(out.startsWith('Error (2):\n')).toBe(true)+ expect(out).toContain('fatal: the real error')+ expect(out).toContain('task_id "out-2"')+ })+})diff --git a/src/api/mcp/__tests__/tool-catalog-tokens.test.ts b/src/api/mcp/__tests__/tool-catalog-tokens.test.tsindex 8a1849b8..8511de51 100644--- a/src/api/mcp/__tests__/tool-catalog-tokens.test.ts+++ b/src/api/mcp/__tests__/tool-catalog-tokens.test.ts@@ -148,7 +148,11 @@ const CODING_TOKEN_CEILING = 1730// integ/310: C60, C60-S5, C59 und P-L (web_research) zusammen, gemessen// 25.032 Zeichen. Token-Decke geschaetzt im selben Verhaeltnis wie oben// (5040 / 23200).-const FULL_CHAR_CEILING = 25080+// T1 (CA rebuild): +88 Zeichen fuer den einen Satz in shell_execute, dass ein+// Befehl ueber die Zeitgrenze hinaus als Hintergrundaufgabe weiterlaeuft.+// Gemessen 25.120, Deckel plus Rand. Der codierende Zug bleibt unter seiner+// Decke.+const FULL_CHAR_CEILING = 25150const FULL_TOKEN_CEILING = 5450describe('the coding step carries a catalog the diet actually shrank', () => {diff --git a/src/api/mcp/builtin-tools.ts b/src/api/mcp/builtin-tools.tsindex 0413cc8a..0c2464dd 100644--- a/src/api/mcp/builtin-tools.ts+++ b/src/api/mcp/builtin-tools.ts@@ -423,7 +423,8 @@ const BUILTIN_TOOLS: MCPToolDefinition[] = [+ 'For long work set `background: true` to get a task id back at once, then call again with `task: "status"` and `task_id` (or "list" / "kill"). '+ 'PREFER dedicated tools where available: file_read over `cat`, file_list over `ls`, file_search over `grep`. '+ '`--no-verify` is refused, and NEVER delete permanently without confirmation. '- + 'Default timeout 120 s, test runs 300 s.',+ + 'Default timeout 120 s, test runs 300 s. '+ + 'A command still running at its timeout keeps running in the background under a task id.',inputSchema: {type: 'object',properties: {@@ -1069,13 +1070,38 @@ async function executeShellExecute(timeout,shell: args.shell || null,stdin: argOptString(args, 'stdin') ?? null,+ // T1: a command still running at the timeout moves into the task+ // registry instead of being killed (shell.rs, bg_tasks::adopt_foreground).+ backgroundOnTimeout: true,...chatCtx(run),}, abort)- const output = data.stdout || ''- const err = data.stderr || ''+ const { cutShellOutput, renderHandedOver } = await import('../agents/shell-result')+ // Long outputs: head and tail only, the rest stays readable under+ // `outputId` (Rust keeps it as a finished task). The parsers below read+ // the uncut text, they summarise it themselves.+ const rawOut = data.stdout || ''+ const rawErr = data.stderr || ''+ const output = cutShellOutput(rawOut, data.outputId)+ const err = cutShellOutput(rawErr, data.outputId)// 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 && data.taskId) {+ const taskId = data.taskId+ const { bgKill, rememberShellTask } = await import('../agents/bg-tasks')+ rememberShellTask(run?.conversationId, taskId)+ // The foreground Stop wiring ended with the call (invokeShell removes its+ // listener), so Stop reaches the task the same way it reaches a+ // `background: true` start: through shell_task_kill.+ if (abort) {+ if (abort.aborted) {+ void bgKill(taskId).catch(() => {})+ return 'Cancelled: the user stopped the run.'+ }+ abort.addEventListener('abort', () => { void bgKill(taskId).catch(() => {}) }, { once: true })+ }+ return renderHandedOver({ taskId, timeoutMs: data.timeoutMs ?? timeout, stdout: rawOut, stderr: rawErr })+ }if (data.timedOut) return `Timed out.\n${err}`const kind = commandKind(command)@@ -1092,14 +1118,14 @@ async function executeShellExecute(: /pytest/.test(command)? 'pytest': 'unknown'- const combined = `${output}\n${err}`.trim()+ const combined = `${rawOut}\n${rawErr}`.trim()const tail = combined.length > 4000 ? `…${combined.slice(-4000)}` : combinedreturn `${renderResult(parseForRunner(runner, combined))}\n---\n${tail}`}if (data.exitCode && data.exitCode !== 0) return `Error (${data.exitCode}):\n${err || output}`if (kind === 'git-status' && /--porcelain=2/.test(command)) {const { parseGitStatus, renderGitStatus } = await import('../agents/git-tools')- return renderGitStatus(parseGitStatus(output))+ return renderGitStatus(parseGitStatus(rawOut))}if (kind === 'git-commit') {const combined = `${output}\n${err}`.trim()@@ -1226,7 +1252,7 @@ async function executeShellExecuteBg(run?: AgentRunContext,signal?: AbortSignal,): Promise<string> {- const { bgStart, bgKill } = await import('../agents/bg-tasks')+ const { bgStart, bgKill, rememberShellTask } = await import('../agents/bg-tasks')const command = argString(args, 'command')// Aus demselben Grund wie die `--no-verify`-Sperre darunter doppelt: über den// zurückgezogenen Namen kommt der Aufruf an executeShellExecute vorbei, und@@ -1257,6 +1283,8 @@ async function executeShellExecuteBg(shell: argOptString(args, 'shell'),...chatCtx(run),})+ // check_tasks lists it next to the tasks a timeout handed over (T1).+ rememberShellTask(run?.conversationId, id)// A detached task outlives the turn that started it BY DESIGN, but it must// not outlive the user pressing Stop: nothing polls it after the run ends, so// an unattended `npm run build`/deploy script would keep writing to the repodiff --git a/src/mobile/remote/remoteAgent.ts b/src/mobile/remote/remoteAgent.tsindex 645145dc..7f64f975 100644--- a/src/mobile/remote/remoteAgent.ts+++ b/src/mobile/remote/remoteAgent.ts@@ -271,6 +271,15 @@ export function toolObservation(result: AgentToolResult, args: Record<string, unif (obj.exitCode !== undefined || obj.stdout !== undefined) {const out = typeof obj.stdout === 'string' ? obj.stdout : ''const err = typeof obj.stderr === 'string' ? obj.stderr : ''+ // T1: the desktop moved a command that outran its timeout into a+ // background task instead of killing it (same text as mobile-client/client.js).+ if (obj.timedOut && typeof obj.taskId === 'string' && obj.taskId) {+ let soFar = `${out}${err ? `\n[stderr]\n${err}` : ''}`.replace(/\s+$/, '')+ if (soFar.length > 2000) soFar = `…${soFar.slice(-2000)}`+ return `Still running after its timeout, so it was not stopped: it keeps running in the background as task ${obj.taskId}.\n`+ + (soFar ? `Output so far:\n${soFar}\n` : '')+ + `Use shell_execute with task "status" and task_id "${obj.taskId}" to read its output, or task "kill" to stop it.`+ }if (obj.timedOut) return 'Execution timed out.'if (typeof obj.exitCode === 'number' && obj.exitCode !== 0) return `Error (${obj.exitCode}):\n${err || out}`return out || (err ? `stderr: ${err}` : 'Done.')diff --git a/src/types/bridge.ts b/src/types/bridge.tsindex 446e8614..82d73eb2 100644--- a/src/types/bridge.ts+++ b/src/types/bridge.ts@@ -29,6 +29,19 @@ export interface ShellExecResult {* Fehlt bei jedem Lauf, der ohne Abbruchkennung gestartet wurde.*/cancelled?: boolean+ /**+ * T1: the command was still running at its timeout and moved into the+ * background-task registry under this id (`shell_task_*`). Only set when+ * the call asked for it with `backgroundOnTimeout: true`.+ */+ taskId?: string+ /** The timeout that was hit, in ms, next to `taskId`. */+ timeoutMs?: number+ /**+ * T1: a finished run with a long output; the whole output stays readable+ * under this id (`shell_task_status`). Same switch as `taskId`.+ */+ outputId?: string}/** `fs_read` — commands/filesystem.rs. Binary files carry `bytes`, no `content`. */