Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

fix: stop killing a healthy streaming API run at the hung-provider ceiling (#7560)

[._.]/ Adam Eivy6ee460efde50
diff --git a/server/lib/aiToolkit/AGENTS.md b/server/lib/aiToolkit/AGENTS.md
index 931d938b54..a3c0aa3003 100644
--- a/server/lib/aiToolkit/AGENTS.md
+++ b/server/lib/aiToolkit/AGENTS.md
@@ -26,8 +26,15 @@ Inheritance mirrors `withGatewayApiKey`: a gateway-backed wrapper with no policy
**Runner extension points.** The runner exposes a small declared override surface (in `runner.js`) so the host (PortOS) supplies its own runners without reaching into private internals:
- `setCliRunner(fn)` / `setTuiRunner(fn)` — register host CLI/TUI runners (pass `null` to revert). PortOS calls both in `server/index.js`: its CLI variant is stdin-based and knows the per-CLI argv conventions (Codex `exec -`, Antigravity `agy --print`, Claude Code `-p -`); the TUI runner has no toolkit built-in, and `setTuiRunner` attaches/detaches `executeTuiRun` so the runs router's `typeof runnerService.executeTuiRun === 'function'` gate stays honest.
-- `registerExternalRun(runId, killable)` / `unregisterExternalRun(runId)` / `hasExternalRun(runId)` — track host-spawned child processes / ptys. The toolkit's own `stopRun`, `isRunActive`, and `deleteRun` consult this registry *first*, so **a host runner that spawns its own process MUST register it here** (PortOS does this in `services/runner.js`) — otherwise the runs router reports live runs as inactive and refuses to stop them, and deleting a live run leaks a zombie process. `stopRun` also stamps a one-shot marker consumed through `consumeExternalRunStop(runId)` before unregistering, which lets the host classify the resulting signal as cancellation instead of a provider failure. That classification rides out to callers as `canceled: true` on the run metadata and `code: 'RUN_CANCELED'` on the rejection the prompt runner raises — **anything that turns an LLM failure into a verdict (a pause kind, a filed gap/investigation task, a provider bench, an `error` status) must call `isRunCanceledError` from `errorDetection.js` first**, or it files bug reports about a human pressing Stop. **`executeApiRun` keeps its own equivalent marker internally**, because its killable is an `AbortController` whose reason-less `abort()` reaches the finalizer as Node's bare `AbortError: This operation was aborted` — a message no pattern matches, so every Stop of an API run finalized as an UNKNOWN provider failure, fired `onRunFailed`, and was escalated to a tier-4 investigation task. It now writes the same `canceled` / `completionReason` terminal shape the CLI path does and fires no failure hook; the wall-clock timeout still outranks it, since the timer's own abort is what ended that run. No sibling-method monkey-patching is needed: adding a new lifecycle method (e.g. `pauseRun`) just means having it consult `externalRuns` too.
+- `registerExternalRun(runId, killable)` / `unregisterExternalRun(runId)` / `hasExternalRun(runId)` — track host-spawned child processes / ptys. The toolkit's own `stopRun`, `isRunActive`, and `deleteRun` consult this registry *first*, so **a host runner that spawns its own process MUST register it here** (PortOS does this in `services/runner.js`) — otherwise the runs router reports live runs as inactive and refuses to stop them, and deleting a live run leaks a zombie process. `stopRun` also stamps a one-shot marker consumed through `consumeExternalRunStop(runId)` before unregistering, which lets the host classify the resulting signal as cancellation instead of a provider failure. That classification rides out to callers as `canceled: true` on the run metadata and `code: 'RUN_CANCELED'` on the rejection the prompt runner raises — **anything that turns an LLM failure into a verdict (a pause kind, a filed gap/investigation task, a provider bench, an `error` status) must call `isRunCanceledError` from `errorDetection.js` first**, or it files bug reports about a human pressing Stop. **`executeApiRun` keeps its own equivalent marker internally**, because its killable is an `AbortController` whose reason-less `abort()` reaches the finalizer as Node's bare `AbortError: This operation was aborted` — a message no pattern matches, so every Stop of an API run finalized as an UNKNOWN provider failure, fired `onRunFailed`, and was escalated to a tier-4 investigation task. It now writes the same `canceled` / `completionReason` terminal shape the CLI path does and fires no failure hook; a timeout still outranks it, since the timer's own abort is what ended that run. No sibling-method monkey-patching is needed: adding a new lifecycle method (e.g. `pauseRun`) just means having it consult `externalRuns` too.
- `createProviderStatusService({ prerequisitesMet })` — host gate for "can this provider run AT ALL?" (its CLI binary present). `getFallbackProvider` consults it on every candidate: task-level, configured, and system-priority alike. Injected rather than computed here because the answer needs host I/O (a PATH probe) and this directory stays self-contained; PortOS supplies `prerequisitesMetForRouting` from `services/providerPrerequisites.js` in `bootstrap.js`. It MUST be synchronous, and a missing / throwing / non-boolean answer deliberately reads as "yes" — an unknown answer has to route exactly as it did before, because emptying the fallback chain is a far worse failure than the late ENOENT the gate exists to prevent.
- Time-based state transitions need read-side mirrors. `providerStatus.init()` clears expired `estimatedRecovery` entries; every reader (`getStatus`, `getAllStatuses`, `isAvailable`) must re-apply the same recovery check on read — otherwise providers stay "unavailable" past their recovery deadline until the next process restart.
+**`provider.timeout` is a NO-PROGRESS bound in `executeApiRun`, not a wall clock.** A streaming run carries two ceilings, and conflating them is what #7560 fixed: one wall-clock timer could not tell a provider that opened the stream and stalled from one that was actively streaming and merely slow, so a reasoning model spending its whole budget in the hidden channel (NVIDIA NIM's nemotron sends 126 of 128 frames as `reasoning_content`) was killed mid-generation at 300s alongside genuinely dead upstreams.
+
+- **Stall bound** = `timeout || provider.timeout || DEFAULT_API_RUN_TIMEOUT_MS`, re-armed by every `reader.read()` that yields bytes. It is the hang detector, and it cuts a silent provider off at exactly the moment the single timer did — reinterpreting the field this way costs no protection, because catching a hung provider is the only job that timer ever actually did.
+- **Absolute cap** = `Math.max(DEFAULT_API_RUN_MAX_RUNTIME_MS, stallBound)`, never extended, so a provider trickling one byte per minute still cannot hold its `activeRuns` slot forever. The `Math.max` is load-bearing: an install that deliberately raised `provider.timeout` past the default cap must keep running as long as it asked to, never be clamped DOWN by a ceiling it never configured.
+
+Only the STREAMING path reads the field this way. `aiProvider.js`, `askService.js`, `services/runner.js` and `promptRunner.js` are non-streaming and keep reading it as a wall clock, which is correct there — no persisted field changed shape, so no migration and no schema parity work is owed. Both bounds finalize through the same `markSettled()` / `finalizeTimeout(bound)` pair, so the single-settlement gate, Stop-marker handling and reasoning salvage are shared. **`finalizeTimeout` names which bound fired** in the message and in `metadata.timeoutBound` (`'stall'` | `'absolute'`), because the two are different diagnoses — a provider that went quiet is a bench candidate, one that outran its budget while producing is not. Neither message may contain the literal `"timeout"`: `analyzeError`'s NETWORK_ERROR pattern matches that substring and is tested BEFORE the timeout pattern, so it would misclassify the run as a connectivity fault. `"timed out"` is the phrase that reaches `ERROR_CATEGORIES.TIMEOUT`.
+
The worked example for "barrel + documented exports" (see root `AGENTS.md` → Module Organization) is this directory's `index.js`.
diff --git a/server/lib/aiToolkit/runner.js b/server/lib/aiToolkit/runner.js
index 88bf8b1f1e..379956484e 100644
--- a/server/lib/aiToolkit/runner.js
+++ b/server/lib/aiToolkit/runner.js
@@ -22,11 +22,32 @@ const IS_WIN32 = process.platform === 'win32';
// wrappers (for Git Bash/WSL), and that stub is not natively launchable here.
const WIN_EXECUTABLE_EXTS = ['.exe', '.cmd', '.bat', '.com'];
-// Wall-clock ceiling for an API run when neither the caller nor the provider
+// No-progress ceiling for an API run when neither the caller nor the provider
// sets one. Mirrors aiProvider's DEFAULT_PROVIDER_TIMEOUT_MS / askService's
// `provider.timeout || 300000` so a hung upstream can't hold `activeRuns`
// (and thus the run slot) open forever.
const DEFAULT_API_RUN_TIMEOUT_MS = 300000;
+
+// Absolute runtime cap for a STREAMING API run, used when the configured
+// no-progress bound is the shorter of the two.
+//
+// `executeApiRun` used to bound a run with ONE wall-clock timer, which could
+// not tell a provider that opened the stream and STALLED (the leak the ceiling
+// exists to prevent) from one that is actively streaming and simply needs
+// longer. Both died at the same 300s. A reasoning model spends nearly its whole
+// budget in the hidden channel before the first content token — NVIDIA NIM's
+// `nvidia/nemotron-3.5-lightning-30b-a3b` sends 126 of 128 frames as
+// `reasoning_content` on a TRIVIAL prompt — so a ~26K-token prompt was killed
+// mid-generation while healthy and producing (#7560).
+//
+// The two bounds are now separate, and `provider.timeout` keeps the job the
+// single timer was actually written for: catching a provider that went quiet.
+// Read as a NO-PROGRESS bound it kills a hung upstream at exactly the moment it
+// always did — zero regression in that protection — while a stream that keeps
+// yielding bytes is no longer cut off for being slow. This cap is what still
+// bounds total runtime, so a provider that trickles one byte per minute cannot
+// hold a run slot forever.
+const DEFAULT_API_RUN_MAX_RUNTIME_MS = 1800000;
const DEFAULT_OUTPUT_RESERVE_TOKENS = 8000;
const CHARS_PER_TOKEN = 4;
@@ -630,26 +651,45 @@ export function createRunnerService(config = {}) {
activeStopRequests.delete(runId);
activeRuns.set(runId, controller);
- // Wall-clock timeout with a single-settlement gate. Without a ceiling a
- // hung provider (opens the stream then stalls, never responds, or — via
- // the `ensureProviderReady` hook — never even reaches the abortable
- // fetch) holds the AbortController in `activeRuns` forever, leaking the
- // run slot. `markSettled()` ensures exactly one of {timer, response
- // paths} finalizes the run: whoever wins clears the timer and flips the
- // flag; the losers no-op. When the timer wins it aborts the fetch/reader
- // AND independently finalizes the run as a TIMEOUT (so a hung setup hook
- // that never reaches the fetch is still bounded, and the failure is
- // classified as a timeout instead of the AbortError's UNKNOWN/HTTP-0).
- const effectiveTimeout = timeout || provider.timeout || DEFAULT_API_RUN_TIMEOUT_MS;
+ // TWO bounds with a single-settlement gate. Without a ceiling a hung
+ // provider (opens the stream then stalls, never responds, or — via the
+ // `ensureProviderReady` hook — never even reaches the abortable fetch)
+ // holds the AbortController in `activeRuns` forever, leaking the run
+ // slot. But one wall-clock ceiling cannot tell that hang apart from a
+ // healthy model that is streaming and simply slow, so it killed both
+ // (#7560). They are split:
+ //
+ // - `stallTimeout` — the NO-PROGRESS bound, re-armed by
+ // `noteStreamProgress()` on every read that yields bytes. This is the
+ // one that catches a genuinely hung upstream. It takes the caller's /
+ // provider's configured value, so a provider that goes quiet is still
+ // cut off at exactly the moment it was before this split.
+ // - `absoluteTimeout` — total runtime, never extended, so a provider
+ // trickling one byte per minute still cannot hold the slot forever.
+ // `Math.max` keeps it from ever landing BELOW the configured bound: an
+ // install that deliberately raised `provider.timeout` past the default
+ // cap keeps running exactly as long as it asked to.
+ //
+ // `markSettled()` ensures exactly one of {either timer, response paths}
+ // finalizes the run: whoever wins clears BOTH timers and flips the flag;
+ // the losers no-op. When a timer wins it aborts the fetch/reader AND
+ // independently finalizes the run as a TIMEOUT (so a hung setup hook that
+ // never reaches the fetch is still bounded, and the failure is classified
+ // as a timeout instead of the AbortError's UNKNOWN/HTTP-0).
+ const stallTimeout = timeout || provider.timeout || DEFAULT_API_RUN_TIMEOUT_MS;
+ const absoluteTimeout = Math.max(DEFAULT_API_RUN_MAX_RUNTIME_MS, stallTimeout);
let settled = false;
- let apiTimeoutHandle = null;
+ let stallTimeoutHandle = null;
+ let absoluteTimeoutHandle = null;
const markSettled = () => {
if (settled) return false;
settled = true;
- if (apiTimeoutHandle) {
- clearTimeout(apiTimeoutHandle);
- apiTimeoutHandle = null;
- }
+ // BOTH, or the survivor keeps the event loop alive past the run and
+ // fires an abort at a controller nobody is reading any more.
+ clearTimeout(stallTimeoutHandle);
+ clearTimeout(absoluteTimeoutHandle);
+ stallTimeoutHandle = null;
+ absoluteTimeoutHandle = null;
return true;
};
// A Stop is a lifecycle outcome, not a failed AI attempt. Finalize it as
@@ -678,13 +718,24 @@ export function createRunnerService(config = {}) {
});
safeSettle(() => onComplete?.(metadata), `Run ${runId} onComplete`);
};
- const finalizeTimeout = async () => {
+ // `bound` is 'stall' or 'absolute'. The two mean different things — one
+ // says the provider went quiet, the other says it was productive but ran
+ // past its budget — so the message names which fired and the metadata
+ // carries it as a field, letting a host's failure classifier branch on it
+ // without parsing prose. Neither message may contain the literal
+ // "timeout": `analyzeError`'s NETWORK_ERROR pattern matches that
+ // substring and is tested BEFORE the timeout pattern, so it would
+ // misclassify the run as a connectivity fault. "timed out" is the phrase
+ // that reaches ERROR_CATEGORIES.TIMEOUT.
+ const finalizeTimeout = async (bound) => {
if (!markSettled()) return;
activeRuns.delete(runId);
// The timer's own abort caused this, so TIMEOUT stays authoritative
// even if a Stop raced it — just drop the marker so it can't leak.
consumeActiveStop(runId);
- const error = `API execution timed out after ${effectiveTimeout}ms`;
+ const error = bound === 'absolute'
+ ? `API execution timed out after ${absoluteTimeout}ms: absolute runtime cap reached`
+ : `API execution timed out after ${stallTimeout}ms with no stream progress`;
try {
// A reasoning model spends its whole budget in the hidden channel
// before the first content token, so a run the ceiling cuts off
@@ -702,6 +753,11 @@ export function createRunnerService(config = {}) {
metadata.success = false;
metadata.error = error;
metadata.errorCategory = ERROR_CATEGORIES.TIMEOUT;
+ // Which ceiling ended the run: 'stall' (the provider went quiet) or
+ // 'absolute' (it stayed productive past the total-runtime cap). A
+ // stalled provider is a candidate for benching; a productive one that
+ // outran its budget is not.
+ metadata.timeoutBound = bound;
// Same two diagnostic flags the mid-stream-throw path sets, so a
// timeout that streamed is distinguishable from one that never got a
// byte without reading the output file back.
@@ -726,11 +782,25 @@ export function createRunnerService(config = {}) {
safeSettle(() => onComplete?.({ success: false, error, endTime: new Date().toISOString(), duration: Date.now() - startTime, outputSize: Buffer.byteLength(salvaged) }), `Run ${runId} onComplete`);
}
};
- apiTimeoutHandle = setTimeout(() => {
- console.log(`⏱️ API run ${runId} timed out after ${effectiveTimeout}ms`);
+ const fireTimeout = (bound) => {
+ console.log(`⏱️ API run ${runId} timed out: ${bound} bound of ${bound === 'absolute' ? absoluteTimeout : stallTimeout}ms`);
controller.abort();
- finalizeTimeout().catch((err) => console.error(`❌ API run ${runId} timeout handler error: ${err.message}`));
- }, effectiveTimeout);
+ finalizeTimeout(bound).catch((err) => console.error(`❌ API run ${runId} timeout handler error: ${err.message}`));
+ };
+ const armStallTimer = () => {
+ stallTimeoutHandle = setTimeout(() => fireTimeout('stall'), stallTimeout);
+ };
+ // Re-arm the no-progress bound from the read loop. Guarded on `settled`
+ // so a chunk that lands in the same tick a terminal path claimed the run
+ // cannot resurrect a timer nobody will ever clear — that would hold the
+ // event loop open past the run and fire an abort at a dead controller.
+ const noteStreamProgress = () => {
+ if (settled) return;
+ if (stallTimeoutHandle) clearTimeout(stallTimeoutHandle);
+ armStallTimer();
+ };
+ armStallTimer();
+ absoluteTimeoutHandle = setTimeout(() => fireTimeout('absolute'), absoluteTimeout);
hooks.onRunStarted?.({ runId, provider: provider.name, model });
@@ -914,6 +984,14 @@ export function createRunnerService(config = {}) {
const { done, value } = await reader.read();
if (done) break;
+ // Bytes arrived, so the upstream is alive: push the no-progress bound
+ // out. An EMPTY chunk is deliberately not progress — it proves the
+ // reader woke, not that the provider produced anything, and treating
+ // it as a heartbeat would let a reader spinning on zero-length reads
+ // hold the stall bound open indefinitely. The absolute cap is what
+ // bounds a provider that DOES trickle real bytes forever.
+ if (value?.byteLength > 0) noteStreamProgress();
+
buffer += decoder.decode(value, { stream: true });
const lines = buffer.split('\n');
// The last element is either an incomplete line or '' — either way it
diff --git a/server/lib/aiToolkit/runner.test.js b/server/lib/aiToolkit/runner.test.js
index 0317bdf4d9..3bd6ca8257 100644
--- a/server/lib/aiToolkit/runner.test.js
+++ b/server/lib/aiToolkit/runner.test.js
@@ -27,6 +27,10 @@ describe('AI Toolkit runner service', () => {
const tempDirs = [];
afterEach(async () => {
+ // Before restoreAllMocks: a spy restored while the clock is still faked is
+ // reinstalled onto the faked globals, so the next test inherits a timer
+ // that never fires. No-op when the test used real timers.
+ vi.useRealTimers();
vi.restoreAllMocks();
for (const dir of tempDirs.splice(0)) {
await rm(dir, { recursive: true, force: true });
@@ -628,6 +632,11 @@ describe('AI Toolkit runner service', () => {
// every API timeout reached the host's failure hook as an uncategorized
// failure and was escalated for investigation instead of read as a timeout.
expect(metadata.errorAnalysis).toMatchObject({ hasError: true, category: 'timeout' });
+ // Which of the two ceilings ended it. A provider that went quiet is a
+ // bench candidate; one that outran the absolute cap while producing is not,
+ // so the host's classifier must be able to tell them apart without prose.
+ expect(metadata.timeoutBound).toBe('stall');
+ expect(metadata.error).toMatch(/no stream progress/i);
});
it('bounds a run whose provider-readiness hook never resolves (fetch never reached)', async () => {
@@ -1193,6 +1202,149 @@ describe('AI Toolkit runner service', () => {
expect(await runner.isRunActive('run-timeout-pre-response')).toBe(false);
});
+ // A SSE reader whose chunks arrive on the (fake) clock, so a test can hold a
+ // stream open across the timeout bounds without sleeping. Rejects on abort
+ // the way a real reader does, so a timer that wins the race still unwinds
+ // `processStream` instead of leaving it parked on a read forever.
+ const clockDrivenReader = ({ intervalMs, frames = Infinity, signal }) => {
+ const encoder = new TextEncoder();
+ let sent = 0;
+ return {
+ read: () => new Promise((resolve, reject) => {
+ const fail = () => reject(Object.assign(new Error('The operation was aborted'), { name: 'AbortError' }));
+ if (signal?.aborted) return fail();
+ signal?.addEventListener('abort', fail, { once: true });
+ setTimeout(() => {
+ if (signal?.aborted) return fail();
+ if (sent >= frames) return resolve({ done: true, value: undefined });
+ sent += 1;
+ resolve({
+ done: false,
+ value: encoder.encode(`data: ${JSON.stringify({ choices: [{ delta: { content: 'tok' } }] })}\n`),
+ });
+ }, intervalMs);
+ }),
+ cancel: async () => {},
+ };
+ };
+
+ // The regression #7560 reports. A single wall-clock ceiling cannot tell a
+ // provider that opened the stream and STALLED from one that is actively
+ // streaming and simply needs longer, so both died at the same 300s — an
+ // NVIDIA NIM nemotron run spending its whole budget in the hidden reasoning
+ // channel was killed mid-generation while healthy and producing. Every chunk
+ // must push the no-progress bound out, so a run that keeps producing outlives
+ // that bound by any multiple.
+ it('lets a steadily streaming run outlive the configured no-progress bound', async () => {
+ const dataDir = await mkdtemp(join(tmpdir(), 'ai-toolkit-runner-'));
+ tempDirs.push(dataDir);
+ vi.useFakeTimers();
+
+ const FRAMES = 20;
+ const INTERVAL_MS = 400;
+ const STALL_MS = 1000;
+ vi.stubGlobal('fetch', vi.fn(async (_url, opts) => ({
+ ok: true,
+ body: { getReader: () => clockDrivenReader({ intervalMs: INTERVAL_MS, frames: FRAMES, signal: opts.signal }) },
+ })));
+ const runner = createRunnerService({
+ dataDir, hooks: { ensureProviderReady: async () => ({ success: true }) },
+ });
+ let complete;
+ const completed = new Promise(resolve => { complete = resolve; });
+
+ await runner.executeApiRun({
+ runId: 'run-slow-stream', provider: runReady(), model: null, prompt: 'hi',
+ workspacePath: process.cwd(), screenshots: [], timeout: STALL_MS,
+ onData: undefined, onComplete: complete,
+ });
+
+ // 8000ms of streaming against a 1000ms no-progress bound: the old single
+ // ceiling ended this run at 1000ms with `success: false`.
+ await vi.advanceTimersByTimeAsync(INTERVAL_MS * (FRAMES + 1));
+ const metadata = await completed;
+
+ expect(metadata).toMatchObject({ success: true, exitCode: 0 });
+ expect(metadata.duration).toBeGreaterThan(STALL_MS);
+ expect(await readFile(join(dataDir, 'runs', 'run-slow-stream', 'output.txt'), 'utf-8'))
+ .toBe('tok'.repeat(FRAMES));
+ expect(await runner.isRunActive('run-slow-stream')).toBe(false);
+ });
+
+ // The other half of the split: relaxing the no-progress bound must not let a
+ // provider that trickles bytes forever hold its `activeRuns` slot for good.
+ // The absolute cap never extends, and it says so — a run that outran its
+ // total budget while producing is a different diagnosis from one that stalled.
+ it('caps a run that never stops trickling, naming the absolute bound', async () => {
+ const dataDir = await mkdtemp(join(tmpdir(), 'ai-toolkit-runner-'));
+ tempDirs.push(dataDir);
+ vi.useFakeTimers();
+
+ // 55s between frames keeps the 120s no-progress bound permanently re-armed
+ // (and never lands on the same tick as the 30-minute cap).
+ vi.stubGlobal('fetch', vi.fn(async (_url, opts) => ({
+ ok: true,
+ body: { getReader: () => clockDrivenReader({ intervalMs: 55_000, signal: opts.signal }) },
+ })));
+ const runner = createRunnerService({
+ dataDir, hooks: { ensureProviderReady: async () => ({ success: true }) },
+ });
+ let complete;
+ const completed = new Promise(resolve => { complete = resolve; });
+
+ await runner.executeApiRun({
+ runId: 'run-trickle', provider: runReady(), model: null, prompt: 'hi',
+ workspacePath: process.cwd(), screenshots: [], timeout: 120_000,
+ onData: undefined, onComplete: complete,
+ });
+
+ await vi.advanceTimersByTimeAsync(1_800_000);
+ const metadata = await completed;
+
+ expect(metadata).toMatchObject({ success: false, errorCategory: 'timeout', timeoutBound: 'absolute' });
+ expect(metadata.error).toMatch(/absolute runtime cap/i);
+ // The cap is a ceiling on total runtime, not on the no-progress bound: it
+ // fired while the stream was still producing, so the partial output is
+ // salvaged rather than reported as a zero-byte "provider said nothing".
+ expect(metadata.outputSize).toBeGreaterThan(0);
+ expect(await runner.isRunActive('run-trickle')).toBe(false);
+ });
+
+ // `Math.max` against the default cap: an install that deliberately raised
+ // `provider.timeout` past 30 minutes keeps running exactly as long as it
+ // asked to, rather than being silently clamped DOWN by the new ceiling.
+ it('never caps a run below its configured no-progress bound', async () => {
+ const dataDir = await mkdtemp(join(tmpdir(), 'ai-toolkit-runner-'));
+ tempDirs.push(dataDir);
+ vi.useFakeTimers();
+
+ vi.stubGlobal('fetch', vi.fn(async (_url, opts) => ({
+ ok: true,
+ body: { getReader: () => clockDrivenReader({ intervalMs: 600_000, signal: opts.signal }) },
+ })));
+ const runner = createRunnerService({
+ dataDir, hooks: { ensureProviderReady: async () => ({ success: true }) },
+ });
+ let complete;
+ const completed = new Promise(resolve => { complete = resolve; });
+
+ // A 45-minute bound, past the 30-minute default cap.
+ await runner.executeApiRun({
+ runId: 'run-long-bound', provider: runReady(), model: null, prompt: 'hi',
+ workspacePath: process.cwd(), screenshots: [], timeout: 2_700_000,
+ onData: undefined, onComplete: complete,
+ });
+
+ // Past the default cap, before the configured bound — still running.
+ await vi.advanceTimersByTimeAsync(1_900_000);
+ expect(await runner.isRunActive('run-long-bound')).toBe(true);
+
+ await vi.advanceTimersByTimeAsync(1_000_000);
+ const metadata = await completed;
+ expect(metadata).toMatchObject({ success: false, errorCategory: 'timeout', timeoutBound: 'absolute' });
+ expect(metadata.error).toMatch(/2700000ms/);
+ });
+
// A stream that ends without [DONE] still has a complete frame sitting in the
// carry buffer; dropping it silently truncates the tail of the answer.
it('flushes a trailing frame left unterminated by the final read', async () => {