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(agent): actually cancel the tool call a timeout or Stop kills

purple6adefcea1709
diff --git a/src/api/agents/sub-agent.ts b/src/api/agents/sub-agent.ts
index 836ca1b6..9c99653f 100644
--- a/src/api/agents/sub-agent.ts
+++ b/src/api/agents/sub-agent.ts
@@ -696,8 +696,16 @@ async function resolveSubAgentLane(model: string | undefined): Promise<RunLane>
*/
export function buildDelegateExecutor(
runner: SubAgentRunner = defaultSubAgentRunner
-): (args: ToolArgs, run?: AgentRunContext) => Promise<string> {
- return async (args: ToolArgs, run?: AgentRunContext) => {
+): (args: ToolArgs, run?: AgentRunContext, abort?: AbortSignal) => Promise<string> {
+ // `abort` is the merged signal toolRegistry.execute() hands every
+ // executor: the run's own Stop AND (klaerung-n5a Fix 2) the JS timeout
+ // race's own controller, aborted the moment the cap fires. Foreground
+ // delegation now has no realistic cap of its own (tool-timeout.ts,
+ // AGENT_LOOP_TOOLS), but the race still exists as a formality and its
+ // signal has to reach the nested loop for the same reason Stop does:
+ // otherwise a timed-out call would still orphan the sub-agent, holding
+ // its local lane, exactly the bug this fix closes.
+ return async (args: ToolArgs, run?: AgentRunContext, abort?: AbortSignal) => {
const kappe = effectiveParallelCap(run?.conversationId)
if (_inFlight >= kappe) {
return `Error: Maximum sub-agent concurrency (${kappe}) reached. Wait for a running sub-agent to finish, or continue the task yourself.`
@@ -768,7 +776,16 @@ export function buildDelegateExecutor(
// vor und verklemmt sich hinter der eigenen Buchung dieses
// Sub-Agenten (dieselbe Fehlerform wie im Hintergrundzweig
// unten, nur eine Ebene hoeher).
- const kindLauf: AgentRunContext | undefined = run ? { ...run, heldLocalLane: held } : undefined
+ // `abort` (the race's own signal, klaerung-n5a Fix 2) wins over
+ // `run.abortSignal` because it is the SUPERSET: toolRegistry.
+ // execute() already merges the run's Stop into it before this
+ // executor ever sees it (see useAgentChat.ts/useCodex.ts's
+ // `raceWithToolTimeout` call). Falling back to `run.abortSignal`
+ // only covers a caller that predates the fourth argument (a
+ // test stubbing this executor directly).
+ const kindLauf: AgentRunContext | undefined = run
+ ? { ...run, abortSignal: abort ?? run.abortSignal, heldLocalLane: held }
+ : undefined
output = await runner(goal, context, { budget, run: kindLauf, model })
},
)
diff --git a/src/api/mcp/builtin-tools.ts b/src/api/mcp/builtin-tools.ts
index aeb19747..a5869475 100644
--- a/src/api/mcp/builtin-tools.ts
+++ b/src/api/mcp/builtin-tools.ts
@@ -1560,7 +1560,7 @@ async function executeGetCurrentTime(_args: ToolArgs): Promise<string> {
let _workflowDepth = 0
-async function executeRunWorkflow(args: ToolArgs, run?: AgentRunContext): Promise<string> {
+async function executeRunWorkflow(args: ToolArgs, run?: AgentRunContext, abort?: AbortSignal): Promise<string> {
const workflowName = argString(args, 'name')
if (!workflowName) return 'Error: No workflow name provided'
if (_workflowDepth >= 5) return 'Error: Maximum workflow nesting depth (5) exceeded'
@@ -1609,7 +1609,26 @@ async function executeRunWorkflow(args: ToolArgs, run?: AgentRunContext): Promis
// booking, so a stale or absent proof falls back to booking normally
// instead of silently trusting the marker.
const engine = new WorkflowEngine(workflow, 'tool-execution', callbacks, initialVars, _workflowDepth, run?.heldLocalLane ?? null)
- await engine.run()
+ // klaerung-n5a Fix 2: `abort` is the merged signal toolRegistry.execute()
+ // hands every executor now (the run's Stop AND, since run_workflow sits
+ // in tool-timeout.ts's AGENT_LOOP_TOOLS, the JS race's own timeout
+ // controller). WorkflowEngine already has everything needed to react:
+ // `cancel()` flips its internal AbortController, checked at the top of
+ // every step and threaded into every provider call, so this executor
+ // just has to call it. Without this wire, a timed-out or Stop-hit
+ // `run_workflow` kept its engine running underneath, orphaned, holding
+ // the local lane `runInLane` had booked for it, the same failure class
+ // measured for delegate_task.
+ const onAbort = () => engine.cancel()
+ if (abort) {
+ if (abort.aborted) onAbort()
+ else abort.addEventListener('abort', onAbort, { once: true })
+ }
+ try {
+ await engine.run()
+ } finally {
+ abort?.removeEventListener('abort', onAbort)
+ }
} finally {
_workflowDepth--
}
diff --git a/src/hooks/useAgentChat.ts b/src/hooks/useAgentChat.ts
index c49e2ebf..73dfc3ec 100644
--- a/src/hooks/useAgentChat.ts
+++ b/src/hooks/useAgentChat.ts
@@ -2093,11 +2093,14 @@ export function useAgentChat() {
// wedged the whole run with no way out but a restart.
execute: (name: string, args: ToolArgs, callRun?: AgentRunContext, signal?: AbortSignal) =>
raceWithToolTimeout(
- // The run's Stop travels into the tool itself (audit M1), not
- // just to the batch scheduler.
- toolRegistry.execute(name, args, 1, callRun, signal ?? abort.signal),
name,
toolCallCapMs(name, args, settings),
+ // The run's Stop travels into the tool itself (audit M1), not
+ // just to the batch scheduler. `raced` also carries the race's
+ // OWN timeout abort now (klaerung-n5a Fix 2), so a timed-out
+ // call is cancelled for real instead of left running orphaned.
+ (raced) => toolRegistry.execute(name, args, 1, callRun, raced),
+ signal ?? abort.signal,
),
lookupCache: convId ? makeInTurnCacheLookup({ convId, turnStartMs }) : undefined,
explainError: (toolName, err) => explainToolError(toolName, err),
diff --git a/src/hooks/useCodex.ts b/src/hooks/useCodex.ts
index 80da8ac3..1f6fe678 100644
--- a/src/hooks/useCodex.ts
+++ b/src/hooks/useCodex.ts
@@ -2063,13 +2063,17 @@ export function useCodex() {
// instead of parking a live closure for up to 615 s per call.
const withTimeout = (name: string, args: ToolArgs, signal?: AbortSignal) =>
raceWithToolTimeout(
+ name,
+ toolCallCapMs(name, args, settings),
// The run's Stop travels all the way INTO the tool now (audit M1).
// Before, the signal stopped at the batch scheduler: a shell command
// already in flight kept mutating the repository for the rest of its
// 615 s budget after the user hit the only brake the product has.
- toolRegistry.execute(name, args, 1, run, signal ?? abort.signal),
- name,
- toolCallCapMs(name, args, settings),
+ // `raced` also carries the race's own timeout abort (klaerung-n5a
+ // Fix 2), so a call the cap kills is actually cancelled, not just
+ // ignored.
+ (raced) => toolRegistry.execute(name, args, 1, run, raced),
+ signal ?? abort.signal,
)
// Die Ablage-Warteschlange und ALLES, was sie anfasst — die vier
diff --git a/src/lib/__tests__/agent-loop-tools-timeout-abort.test.ts b/src/lib/__tests__/agent-loop-tools-timeout-abort.test.ts
new file mode 100644
index 00000000..b9f13477
--- /dev/null
+++ b/src/lib/__tests__/agent-loop-tools-timeout-abort.test.ts
@@ -0,0 +1,197 @@
+/**
+ * klaerung-n5a, Frage 1, Fix 2: wenn der JS-Werkzeug-Deckel (tool-timeout.ts)
+ * doch einmal zuschlaegt, oder der Nutzer waehrenddessen Stop drueckt, darf
+ * der verlierende Lauf nicht mehr verwaist weiterlaufen und seine lokale
+ * Spur besetzt halten. Vorher tat er das: `Promise.race` ignoriert seinen
+ * Verlierer nur, es bricht ihn nie ab.
+ *
+ * Diese Datei prueft die beiden Werkzeuge mit eigener Spur-Belegung, fuer
+ * die tool-timeout.ts inzwischen KEINEN erreichbaren Deckel mehr setzt
+ * (`delegate_task` im Vordergrund, `run_workflow`): dass das Signal, das
+ * `raceWithToolTimeout` bei einem Abbruch abbricht (Timeout ODER Stop), auch
+ * wirklich bis in ihren jeweiligen Lauf durchgereicht wird und die Spur
+ * freigibt, und zwar nicht ueber den echten 615-Tage-Deckel, der in der
+ * Praxis nie feuert, sondern direkt am dritten `signal`-Argument, das
+ * `toolRegistry.execute()` jedem Ausfuehrer reicht (siehe tool-registry.ts).
+ *
+ * Lauf: npx vitest run src/lib/__tests__/agent-loop-tools-timeout-abort.test.ts
+ */
+import { describe, it, expect, beforeEach, vi } from 'vitest'
+import { localLaneHolder, queuedRunIds, __resetRunLanesForTests } from '../run-lanes'
+import { useGenerationStore } from '../../stores/generationStore'
+import { useModelStore } from '../../stores/modelStore'
+import { useMemoryStore } from '../../stores/memoryStore'
+import { useAgentWorkflowStore } from '../../stores/agentWorkflowStore'
+import { toolRegistry, registerBuiltinTools } from '../../api/mcp'
+import { buildDelegateExecutor, _setDepth, type SubAgentRunner } from '../../api/agents/sub-agent'
+import type { AgentRunContext } from '../../api/agent-context'
+import type { AgentWorkflow } from '../../types/agent-workflows'
+
+const LOCAL_MODEL = 'qwen3:8b'
+
+function makeRun(conversationId: string): AgentRunContext {
+ return {
+ token: 'run', chatId: null, conversationId, workspace: null,
+ artifactMode: false, readOnlyShellTurn: false, mode: null, artifacts: [],
+ }
+}
+
+const tick = () => new Promise((r) => setTimeout(r, 0))
+const takte = async (n = 20) => { for (let i = 0; i < n; i++) await tick() }
+
+beforeEach(() => {
+ __resetRunLanesForTests()
+ useGenerationStore.setState({ generating: {}, aborters: {}, runs: {} })
+ useModelStore.setState({ activeModel: LOCAL_MODEL })
+ _setDepth(0)
+})
+
+// ── delegate_task (Vordergrund) ─────────────────────────────────────────
+
+describe('delegate_task im Vordergrund: das dritte signal-Argument bricht den Sub-Agenten wirklich ab', () => {
+ it('Abbruch (Stellvertreter fuer den Race-Timeout) beendet den Lauf schnell und gibt die Spur frei', async () => {
+ // Steht fuer defaultSubAgentRunner's echte Schleife, die `gates.abortSignal
+ // ?.aborted` an jedem Schleifenkopf prueft (sub-agent.ts:545), hier als
+ // schneller Poll nachgebaut, damit der Test nicht auf echte Provider-
+ // Anbindung angewiesen ist.
+ const runner: SubAgentRunner = (_goal, _context, opts) =>
+ new Promise((resolve) => {
+ const check = () => {
+ if (opts.run?.abortSignal?.aborted) { resolve('(sub-agent stopped by the user)'); return }
+ setTimeout(check, 2)
+ }
+ check()
+ })
+
+ const exec = buildDelegateExecutor(runner)
+ const controller = new AbortController()
+ const lauf = exec({ goal: 'lang laufend' }, makeRun('conv-fg'), controller.signal)
+
+ await takte()
+ // Der Vordergrundzweig bucht seine EIGENE, generierte Kennung (nicht
+ // 'conv-fg'), aber IRGENDEINER haelt jetzt die lokale Spur.
+ expect(localLaneHolder()).not.toBeNull()
+ expect(queuedRunIds()).toEqual([])
+
+ const start = Date.now()
+ controller.abort()
+ const out = await lauf
+ const elapsedMs = Date.now() - start
+
+ expect(out).toMatch(/stopped by the user/)
+ // Schnell: der Poll steht alle 2ms an, kein Warten auf einen echten
+ // Deckel (der fuer dieses Werkzeug praktisch nie feuert, siehe
+ // tool-timeout.test.ts).
+ expect(elapsedMs).toBeLessThan(500)
+ expect(localLaneHolder()).toBeNull()
+ })
+
+ it('Negativkontrolle: ohne Abbruch laeuft derselbe Aufbau normal durch und gibt die Spur ebenso frei', async () => {
+ const runner: SubAgentRunner = async () => 'echtes Ergebnis, kein Abbruch'
+ const exec = buildDelegateExecutor(runner)
+ const controller = new AbortController()
+
+ const out = await exec({ goal: 'kurz' }, makeRun('conv-fg2'), controller.signal)
+
+ expect(out).toBe('echtes Ergebnis, kein Abbruch')
+ expect(controller.signal.aborted).toBe(false)
+ expect(localLaneHolder()).toBeNull()
+ })
+
+ it('Stop des Nutzers (run.abortSignal, kein separates signal-Argument) bricht ebenfalls ab', async () => {
+ const runner: SubAgentRunner = (_goal, _context, opts) =>
+ new Promise((resolve) => {
+ const check = () => {
+ if (opts.run?.abortSignal?.aborted) { resolve('(sub-agent stopped by the user)'); return }
+ setTimeout(check, 2)
+ }
+ check()
+ })
+ const exec = buildDelegateExecutor(runner)
+ const run = makeRun('conv-stop')
+ const stopController = new AbortController()
+ run.abortSignal = stopController.signal
+
+ // Kein drittes Argument: die einzige Quelle ist run.abortSignal, genau
+ // wie ein Aufrufer vor dem vierten `signal`-Parameter der Registry.
+ const lauf = exec({ goal: 'x' }, run)
+ await takte()
+ expect(localLaneHolder()).not.toBeNull()
+
+ stopController.abort()
+ const out = await lauf
+
+ expect(out).toMatch(/stopped by the user/)
+ expect(localLaneHolder()).toBeNull()
+ })
+})
+
+// ── run_workflow ─────────────────────────────────────────────────────────
+
+function userInputWorkflow(): AgentWorkflow {
+ return {
+ id: 'wf', name: 'haengt', description: '', icon: 'Zap',
+ steps: [{ id: 'warte', type: 'user_input', label: 'warte', userInputPrompt: '?' }],
+ variables: {}, isBuiltIn: false, createdAt: 0, updatedAt: 0,
+ }
+}
+
+function memoryWorkflow(): AgentWorkflow {
+ return {
+ id: 'wf2', name: 'kurz', description: '', icon: 'Zap',
+ steps: [{
+ id: 'merk', type: 'memory_save', label: 'merk',
+ memorySave: { type: 'reference', titleTemplate: 't', contentTemplate: 'x', tags: [] },
+ }],
+ variables: {}, isBuiltIn: false, createdAt: 0, updatedAt: 0,
+ }
+}
+
+describe('run_workflow: das signal-Argument bricht die WorkflowEngine wirklich ab (engine.cancel())', () => {
+ beforeEach(() => {
+ registerBuiltinTools(toolRegistry)
+ })
+
+ it('Abbruch waehrend eines wartenden Schritts beendet den Lauf und gibt die Spur frei', async () => {
+ useAgentWorkflowStore.setState({ workflows: [userInputWorkflow()] })
+ const controller = new AbortController()
+
+ const lauf = toolRegistry.execute('run_workflow', { name: 'haengt' }, 1, undefined, controller.signal)
+ await takte()
+ // executeRunWorkflow bucht die feste Kennung 'tool-execution' (builtin-
+ // tools.ts), unabhaengig vom aufrufenden Lauf.
+ expect(localLaneHolder()).toBe('tool-execution')
+
+ const start = Date.now()
+ controller.abort()
+ await lauf
+ const elapsedMs = Date.now() - start
+
+ expect(elapsedMs).toBeLessThan(500)
+ expect(localLaneHolder()).toBeNull()
+ expect(queuedRunIds()).toEqual([])
+ })
+
+ it('Negativkontrolle: ohne Abbruch laeuft ein kurzer Arbeitsablauf normal durch und gibt die Spur frei', async () => {
+ useAgentWorkflowStore.setState({ workflows: [memoryWorkflow()] })
+ vi.spyOn(useMemoryStore.getState(), 'addMemory').mockImplementation(() => 'mem-id')
+ const controller = new AbortController()
+
+ const out = await toolRegistry.execute('run_workflow', { name: 'kurz' }, 1, undefined, controller.signal)
+
+ expect(controller.signal.aborted).toBe(false)
+ expect(out).not.toMatch(/Cancelled/)
+ expect(localLaneHolder()).toBeNull()
+ })
+
+ it('ein schon VOR dem Aufruf abgebrochenes Signal laesst den Lauf nie anfangen (generischer Schutz in toolRegistry.execute)', async () => {
+ useAgentWorkflowStore.setState({ workflows: [userInputWorkflow()] })
+ const controller = new AbortController()
+ controller.abort()
+
+ const out = await toolRegistry.execute('run_workflow', { name: 'haengt' }, 1, undefined, controller.signal)
+
+ expect(out).toMatch(/cancelled by the user before "run_workflow" started/)
+ expect(localLaneHolder()).toBeNull()
+ })
+})
diff --git a/src/lib/__tests__/tool-timeout.test.ts b/src/lib/__tests__/tool-timeout.test.ts
index 5bf89e1b..f77314f6 100644
--- a/src/lib/__tests__/tool-timeout.test.ts
+++ b/src/lib/__tests__/tool-timeout.test.ts
@@ -1,23 +1,27 @@
/**
- * klaerung-n5a, Frage 1, Fix 1: `delegate_task` fiel unter denselben
- * generischen 60 s Werkzeug-Deckel wie jedes andere Werkzeug, obwohl sein
- * Vordergrundzweig ABSICHTLICH lange laeuft (das `background`-Feld existiert
- * nur dafuer, siehe sub-agent.ts). `run_workflow` sass in derselben Falle.
+ * klaerung-n5a, Frage 1: `delegate_task` fiel unter denselben generischen
+ * 60 s Werkzeug-Deckel wie jedes andere Werkzeug, obwohl sein Vordergrund-
+ * zweig ABSICHTLICH lange laeuft (das `background`-Feld existiert nur dafuer,
+ * siehe sub-agent.ts), und `Promise.race` brach den Verlierer nie ab, wenn
+ * der Deckel doch zuschlug: der Sub-Agent lief verwaist weiter und hielt
+ * seine lokale Spur, waehrend der Nutzer schon eine Fehlermeldung sah.
*
- * `toolCallCapMs` gibt beiden im Vordergrund keinen erreichbaren Deckel mehr,
- * weil beide ihre eigene Terminierung mitbringen (Iterations-/Schrittgrenze,
+ * Fix 1 (dieser Datei): `toolCallCapMs` gibt `delegate_task` (nur im
+ * Vordergrund) und `run_workflow` keinen erreichbaren Deckel mehr, weil
+ * beide ihre eigene Terminierung mitbringen (Iterations-/Schrittgrenze,
* eigenes Stop-Signal). `check_tasks`/`message_agent` bleiben bewusst beim
* generischen Deckel: sie lesen/schreiben nur den In-Memory-Task-Store, also
* kann keiner von beiden je in die Naehe von 60 s kommen (Negativkontrolle).
*
- * Fix 2 (dass ein zuschlagender Deckel den Verlierer auch wirklich abbricht)
- * ist ein separater Nachtrag zu dieser Datei.
+ * Fix 2 (dieser Datei): `raceWithToolTimeout` bricht den Verlierer jetzt
+ * wirklich ab, statt ihn nur zu ignorieren.
*
* Lauf: npx vitest run src/lib/__tests__/tool-timeout.test.ts
*/
-import { describe, it, expect } from 'vitest'
+import { describe, it, expect, vi, afterEach } from 'vitest'
import {
toolCallCapMs,
+ raceWithToolTimeout,
NO_PRACTICAL_CAP_MS,
SHELL_EXECUTE_DEFAULT_TIMEOUT_MS,
} from '../tool-timeout'
@@ -65,3 +69,108 @@ describe('toolCallCapMs, Fix 1: wer bekommt keinen erreichbaren Deckel', () => {
expect(NO_PRACTICAL_CAP_MS).toBeGreaterThan(SHELL_EXECUTE_DEFAULT_TIMEOUT_MS)
})
})
+
+describe('raceWithToolTimeout, Fix 2: der Verlierer wird wirklich abgebrochen', () => {
+ afterEach(() => {
+ vi.useRealTimers()
+ })
+
+ it('wenn der Deckel zuschlaegt: die Ablehnung nennt Name+Sekunden, UND das an run() gereichte Signal ist abgebrochen', async () => {
+ vi.useFakeTimers()
+ let seenSignal: AbortSignal | undefined
+ let signalWasAbortedWhenRejectFired = false
+ const run = (signal: AbortSignal) => {
+ seenSignal = signal
+ return new Promise<string>(() => {}) // haengt absichtlich, wie ein verwaister Lauf vor dem Fix
+ }
+
+ const promise = raceWithToolTimeout('delegate_task', 1_000, run)
+ const assertion = promise.catch((err: Error) => {
+ // Zur Zeit der Ablehnung MUSS das Signal schon abgebrochen sein (Reihenfolge:
+ // controller.abort() VOR reject(), siehe Kommentar in tool-timeout.ts).
+ signalWasAbortedWhenRejectFired = seenSignal?.aborted === true
+ return err.message
+ })
+
+ await vi.advanceTimersByTimeAsync(1_000)
+ const message = await assertion
+
+ expect(message).toBe('Tool execution timed out: delegate_task (1s)')
+ expect(seenSignal?.aborted).toBe(true)
+ expect(signalWasAbortedWhenRejectFired).toBe(true)
+ })
+
+ it('Negativkontrolle: gewinnt das Werkzeug vor dem Deckel, bleibt das Signal unabgebrochen und der Timer wird geraeumt', async () => {
+ vi.useFakeTimers()
+ let seenSignal: AbortSignal | undefined
+ const run = (signal: AbortSignal) => {
+ seenSignal = signal
+ return Promise.resolve('real answer')
+ }
+
+ const result = await raceWithToolTimeout('file_read', 5_000, run)
+
+ expect(result).toBe('real answer')
+ expect(seenSignal?.aborted).toBe(false)
+
+ // Der Timer ist im .finally() geraeumt (Audit B10): vorspulen darf jetzt
+ // keine unbehandelte Ablehnung mehr ausloesen.
+ let unhandled = false
+ const onUnhandled = () => { unhandled = true }
+ process.on('unhandledRejection', onUnhandled)
+ await vi.advanceTimersByTimeAsync(10_000)
+ process.off('unhandledRejection', onUnhandled)
+ expect(unhandled).toBe(false)
+ })
+
+ it('das Stop-Signal des Laufs (baseSignal) bricht sofort ab, ohne auf den Deckel zu warten', async () => {
+ const baseController = new AbortController()
+ let seenSignal: AbortSignal | undefined
+ const run = (signal: AbortSignal) => {
+ seenSignal = signal
+ return new Promise<string>(() => {})
+ }
+
+ // baseSignal schon abgebrochen, BEVOR der Aufruf ueberhaupt beginnt,
+ // genau der Fall, den toolRegistry.execute() als "cancelled before it
+ // started" behandelt.
+ baseController.abort()
+ raceWithToolTimeout('delegate_task', 60_000, run, baseController.signal)
+
+ expect(seenSignal?.aborted).toBe(true)
+ })
+
+ it('Negativkontrolle: ein baseSignal, das NIE abbricht, laesst run() unbeeinflusst laufen', async () => {
+ const baseController = new AbortController()
+ let seenSignal: AbortSignal | undefined
+ const run = (signal: AbortSignal) => {
+ seenSignal = signal
+ return Promise.resolve('ok')
+ }
+
+ const result = await raceWithToolTimeout('file_read', 5_000, run, baseController.signal)
+ expect(result).toBe('ok')
+ expect(seenSignal?.aborted).toBe(false)
+ })
+
+ it('kein spaeteres Ergebnis des Verlierers erreicht noch irgendjemanden, nachdem der Deckel gewonnen hat', async () => {
+ vi.useFakeTimers()
+ let resolveLate: (v: string) => void = () => {}
+ const run = () => new Promise<string>((res) => { resolveLate = res })
+
+ const promise = raceWithToolTimeout('delegate_task', 100, run)
+ const caught = promise.catch((err: Error) => err.message)
+
+ await vi.advanceTimersByTimeAsync(100)
+ const message = await caught
+ expect(message).toMatch(/timed out/)
+
+ // Der Verlierer loest jetzt SPAETER auf, nichts liest das mehr; die
+ // Zusicherung ist: `promise` selbst bleibt fuer immer die Ablehnung von
+ // oben, ein zweites .then/.catch auf demselben `promise` sieht dieselbe
+ // Ablehnung, nie den spaeten Wert.
+ resolveLate('LATE-RESULT, sollte nirgends ankommen')
+ await vi.advanceTimersByTimeAsync(1)
+ await expect(promise).rejects.toThrow(/timed out/)
+ })
+})
diff --git a/src/lib/tool-timeout.ts b/src/lib/tool-timeout.ts
index 1fc7e7e2..de51f838 100644
--- a/src/lib/tool-timeout.ts
+++ b/src/lib/tool-timeout.ts
@@ -38,9 +38,8 @@ export const NO_PRACTICAL_CAP_MS = 2_147_483_000
* Frage 1). Before this, both fell through to the generic 60 s default,
* exactly the "actual working limit" this file's own header says the cap
* must never become, and the measured cause of two real 60,0 s aborts whose
- * sub-agent then kept running, orphaned, holding the local lane. Making that
- * orphaned run actually stop is Fix 2, a separate change to
- * `raceWithToolTimeout` and to the two tools' own executors.
+ * sub-agent then kept running, orphaned, holding the local lane (see Fix 2
+ * in raceWithToolTimeout below).
*
* `delegate_task`'s BACKGROUND branch is excluded on purpose: it books its
* own conversation slot under a task id and returns in milliseconds (it
@@ -85,17 +84,55 @@ export function toolCallCapMs(
* Race a tool run against its cap. The timer is CLEARED when the tool wins
* (audit B10) — the old inline race left every winner's setTimeout parked
* for up to 615 s with the whole closure alive, times 200 iterations.
+ *
+ * Fix 2 (klaerung-n5a, Frage 1): `Promise.race` never cancels its loser, it
+ * only stops listening to it. Before this, a timed-out tool call reached the
+ * model as an error while the real call underneath ran on, unseen, holding
+ * whatever local resource it had booked (a sub-agent's local lane, a
+ * workflow's), until it ended on its own: the user-visible "Tool execution
+ * timed out" was true about the MESSAGE, not about the machine's state.
+ *
+ * `run` is now a factory, not an already-started promise: it receives the
+ * AbortSignal this function owns, so it can build the call's OWN signal
+ * (merged with `baseSignal`, the run's Stop) instead of racing a call that
+ * was already wired to something else. On timeout that signal is aborted
+ * BEFORE the rejection, so the loser gets exactly the same cancellation
+ * path Stop already uses, and, for every tool that honours its signal
+ * (shell_execute, and now delegate_task/run_workflow, see sub-agent.ts and
+ * builtin-tools.ts), actually winds down and releases what it held.
*/
-export function raceWithToolTimeout(run: Promise<string>, name: string, capMs: number): Promise<string> {
+export function raceWithToolTimeout(
+ name: string,
+ capMs: number,
+ run: (signal: AbortSignal) => Promise<string>,
+ baseSignal?: AbortSignal,
+): Promise<string> {
+ const controller = new AbortController()
+ if (baseSignal) {
+ if (baseSignal.aborted) controller.abort()
+ else baseSignal.addEventListener('abort', () => controller.abort(), { once: true })
+ }
let timer: ReturnType<typeof setTimeout> | undefined
const deadline = new Promise<string>((_, reject) => {
timer = setTimeout(
- // The tool name was passed in by both callers but never used, so every
- // timeout reached the model as an anonymous "Tool execution timed out"
- // — in a parallel batch it could not tell which tool had died.
- () => reject(new Error(`Tool execution timed out: ${name} (${Math.round(capMs / 1000)}s)`)),
+ () => {
+ // Abort BEFORE reject: a listener on the rejection path must see an
+ // already-aborted signal, not a race between the two.
+ controller.abort()
+ // The tool name was passed in by both callers but never used, so every
+ // timeout reached the model as an anonymous "Tool execution timed out",
+ // and in a parallel batch it could not tell which tool had died.
+ reject(new Error(`Tool execution timed out: ${name} (${Math.round(capMs / 1000)}s)`))
+ },
capMs,
)
})
- return Promise.race([run, deadline]).finally(() => clearTimeout(timer))
+ // The tool call is built to resolve, not reject, once it honours the
+ // signal (registry.execute() and every builtin executor return an "Error:
+ // ..."/"Cancelled: ..." STRING on abort, they do not throw), so the
+ // settled-late loser here is a resolved promise nobody reads again, never
+ // an unhandled rejection. Tools that DO throw on abort are caught the same
+ // way any other tool error already is, inside registry.execute()'s own
+ // try/catch, well before this race ever sees it.
+ return Promise.race([run(controller.signal), deadline]).finally(() => clearTimeout(timer))
}