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
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
fix: stop promptRunner's backstop killing healthy streaming API runs at 302s
Adam Eivya91de24a74cc
diff --git a/server/lib/aiToolkit/AGENTS.md b/server/lib/aiToolkit/AGENTS.mdindex c68c47d342..f0ad41f491 100644--- a/server/lib/aiToolkit/AGENTS.md+++ b/server/lib/aiToolkit/AGENTS.md@@ -26,7 +26,7 @@ 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; 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.+- `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. The cancel finalizer performs the same reasoning salvage the success/timeout/mid-stream-throw paths do — stopping a reasoning model mid-hidden-channel otherwise persisted `outputSize: 0` and discarded every token it had produced, which reads downstream as a provider that answered nothing. 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.@@ -37,6 +37,10 @@ Inheritance mirrors `withGatewayApiKey`: a gateway-backed wrapper with no policy- **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`.+Only the STREAMING path reads the field this way. `aiProvider.js`, `askService.js` and `services/runner.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 numbers and the `Math.max` live in `internal/runTimeouts.js`, a leaf module with no imports, because **a host that wraps `executeApiRun` in its own backstop timer must arm it against the ABSOLUTE bound** — which `apiRunAbsoluteTimeoutMs(stallBound)` exists to answer, and which a host reached by hundreds of suites must be able to import without dragging `runner.js`'s `fs`/`child_process` closure (server/AGENTS.md → Import scoping). `promptRunner.js` armed its backstop at `provider.timeout + 2s` and so killed every healthy streaming run at the old ceiling, making the 30-minute cap unreachable and reinstating precisely what #7560 removed. Worse, that backstop kills via `stopRun`, so the run finalized as a USER CANCEL: `onRunFailed` never fired (no bench, no investigation task) and `isRunCanceledError` callers skipped the fallback cascade — a productive run silently produced nothing. Sixteen NVIDIA NIM nemotron persistent-mind runs died that way at exactly 302s in the two days after #7560 merged, and none before (#7665). Derive the number from the exported helper rather than restating the `Math.max`, so the two cannot drift apart again.++Both bounds finalize through the same `markSettled()` / `finalizeTimeout(bound)` pair, so the single-settlement gate and Stop-marker handling are shared. **All three non-success terminal paths — cancel, timeout, mid-stream throw — open their record through `openTerminalMetadata()`**, which salvages the reasoning channel, persists `output.txt`, and stamps `outputSize` / `hadReasoning` / `usedReasoningAsFallback`. Stating that sequence per-path is how the cancel path went without the salvage entirely; a fourth terminal path must reuse the helper rather than restate it. **`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/internal/runTimeouts.js b/server/lib/aiToolkit/internal/runTimeouts.jsnew file mode 100644index 0000000000..8cd062dbd1--- /dev/null+++ b/server/lib/aiToolkit/internal/runTimeouts.js@@ -0,0 +1,57 @@+/**+ * The two ceilings that bound a streaming API run.+ *+ * A leaf module with no imports, because BOTH the runner that arms these timers+ * and any host wrapping `executeApiRun` in its own backstop have to agree on+ * the numbers. Declaring them here rather than in `../runner.js` lets+ * `server/services/promptRunner.js` — reached by ~400 server suites — read the+ * absolute bound without dragging the runner's `fs`/`child_process` closure+ * into every one of them (see server/AGENTS.md → Import scoping).+ */++// 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.+export 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.+export const DEFAULT_API_RUN_MAX_RUNTIME_MS = 1800000;++/**+ * The total-runtime ceiling an API run is ACTUALLY bounded by, given the+ * configured no-progress bound.+ *+ * A host wrapping `executeApiRun` in its own backstop timer has to arm that+ * timer against THIS number, not against `provider.timeout`. PortOS's+ * promptRunner did the latter and so shot every healthy streaming run at+ * `provider.timeout + 2s`, making the 30-minute cap unreachable and+ * reinstating the exact ceiling #7560 removed (#7665). Deriving it in one place+ * keeps the two from drifting apart again.+ *+ * 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.+ */+export const apiRunAbsoluteTimeoutMs = (stallTimeout) => Math.max(+ DEFAULT_API_RUN_MAX_RUNTIME_MS,+ Number(stallTimeout) > 0 ? Number(stallTimeout) : 0,+);diff --git a/server/lib/aiToolkit/runner.js b/server/lib/aiToolkit/runner.jsindex 379956484e..60ea267687 100644--- a/server/lib/aiToolkit/runner.js+++ b/server/lib/aiToolkit/runner.js@@ -8,6 +8,10 @@ import { randomUUID } from 'crypto';import { analyzeError, analyzeHttpError, ERROR_CATEGORIES } from './errorDetection.js';import { apiGenerationOptions } from './internal/generationOptions.js';import { describeTransportError, fetchWithPreHeaderRetry, isReplaySafeLocalRequest } from './internal/preHeaderRetry.js';+// The two streaming ceilings (no-progress bound, absolute runtime cap) live in+// a leaf module so a host's own backstop timer can read the absolute bound+// without dragging this file's fs/child_process closure with it.+import { DEFAULT_API_RUN_TIMEOUT_MS, apiRunAbsoluteTimeoutMs } from './internal/runTimeouts.js';// npm-installed CLI providers (claude, codex, opencode, …) are .cmd/.bat// shims on Windows; Node's spawn() can't execute those without going through@@ -22,32 +26,6 @@ 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'];-// 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;@@ -632,11 +610,46 @@ export function createRunnerService(config = {}) {// finalizing, leaking the run slot the timeout exists to reclaim.let reasoning = '';- // Asked on ALL THREE terminal paths, so it is stated once: a reasoning- // model that produced no content still produced an answer, and the run's- // text is its reasoning. Restating the test at each site is how they drift.+ // The question every terminal path asks, stated once: a reasoning model+ // that produced no content still produced an answer, and the run's text+ // is its reasoning. Restating the test at each site is how they drift.const reasoningIsTheOutput = () => !output.trim() && reasoning.trim().length > 0;+ /**+ * Open the metadata record for a NON-SUCCESS terminal path (cancel,+ * timeout, mid-stream throw), persisting whatever the run produced first.+ *+ * All three ended identically — salvage, write `output.txt`, re-read the+ * record, stamp endTime/duration/success and the three salvage fields —+ * and stating it three times is how they drifted: the cancel path never+ * had the salvage at all, so stopping a reasoning model (which spends+ * nearly its whole budget in the hidden channel before the first content+ * token) discarded every token it had produced and stamped+ * `outputSize: 0`, indistinguishable from a provider that answered+ * nothing. That is why 16 NVIDIA NIM nemotron runs killed at 302s by+ * promptRunner's mis-armed backstop read as dead-provider records rather+ * than the healthy streams they were (#7665). Stated once, a fourth+ * terminal path cannot quietly omit it.+ *+ * Returns the salvaged text alongside the record, because the failure+ * hooks take it as the output tail they quote.+ */+ const openTerminalMetadata = async () => {+ const usedReasoningAsFallback = reasoningIsTheOutput();+ const partialOutput = usedReasoningAsFallback ? reasoning : output;+ if (partialOutput) await atomicWrite(outputPath, partialOutput).catch(() => {});+ const metadata = safeJsonParse(await readFile(metadataPath, 'utf-8').catch(() => '{}'));+ metadata.endTime = new Date().toISOString();+ metadata.duration = Date.now() - startTime;+ metadata.success = false;+ metadata.outputSize = Buffer.byteLength(partialOutput);+ // Distinguishes a terminal run that streamed from one that never got a+ // byte, without reading the output file back.+ metadata.hadReasoning = reasoning.length > 0;+ metadata.usedReasoningAsFallback = usedReasoningAsFallback;+ return { metadata, partialOutput };+ };+const headers = {'Content-Type': 'application/json'};@@ -677,7 +690,7 @@ export function createRunnerService(config = {}) {// 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);+ const absoluteTimeout = apiRunAbsoluteTimeoutMs(stallTimeout);let settled = false;let stallTimeoutHandle = null;let absoluteTimeoutHandle = null;@@ -703,16 +716,11 @@ export function createRunnerService(config = {}) {// caller even if a write fails, or a canceled run hangs its awaiter.const finalizeCanceled = async () => {activeRuns.delete(runId);- if (output) await atomicWrite(outputPath, output).catch(() => {});- const metadata = safeJsonParse(await readFile(metadataPath, 'utf-8').catch(() => '{}'));- metadata.endTime = new Date().toISOString();- metadata.duration = Date.now() - startTime;- metadata.success = false;+ const { metadata } = await openTerminalMetadata();metadata.canceled = true;metadata.completionReason = 'canceled';metadata.error = 'API run canceled';metadata.errorCategory = ERROR_CATEGORIES.CANCELED;- metadata.outputSize = Buffer.byteLength(output);await atomicWrite(metadataPath, metadata).catch((err) => {console.error(`❌ API run ${runId} cancel finalize error: ${err.message}`);});@@ -737,20 +745,7 @@ export function createRunnerService(config = {}) {? `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- // routinely has an empty `output` and minutes of generation sitting- // in `reasoning`. The other two terminal paths already salvage it;- // this one wrote `output` alone and stamped `outputSize: 0`, which- // reads downstream as "the provider sent nothing" and escalates a- // healthy-but-slow model as a dead one.- const usedReasoningAsFallback = reasoningIsTheOutput();- const partialOutput = usedReasoningAsFallback ? reasoning : output;- if (partialOutput) await atomicWrite(outputPath, partialOutput).catch(() => {});- const metadata = safeJsonParse(await readFile(metadataPath, 'utf-8').catch(() => '{}'));- metadata.endTime = new Date().toISOString();- metadata.duration = Date.now() - startTime;- metadata.success = false;+ const { metadata, partialOutput } = await openTerminalMetadata();metadata.error = error;metadata.errorCategory = ERROR_CATEGORIES.TIMEOUT;// Which ceiling ended the run: 'stall' (the provider went quiet) or@@ -758,11 +753,6 @@ export function createRunnerService(config = {}) {// 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.- metadata.hadReasoning = reasoning.length > 0;- metadata.usedReasoningAsFallback = usedReasoningAsFallback;// Hosts classify a failure from `errorAnalysis`, not `errorCategory`// (PortOS's onRunFailed hook reads only the former), so setting the// category alone left every API-run timeout looking like an@@ -770,7 +760,6 @@ export function createRunnerService(config = {}) {// instead of recognized as the timeout it is. Build it from the same// pattern table the other failure paths use so the two can't drift.metadata.errorAnalysis = analyzeError(error);- metadata.outputSize = Buffer.byteLength(partialOutput);await atomicWrite(metadataPath, metadata);// The hook's third arg is the output tail the host quotes into an// investigation task, so it gets the salvaged text too.@@ -1086,30 +1075,12 @@ export function createRunnerService(config = {}) {activeRuns.delete(runId);- // A reasoning model emits its hidden channel well before its first- // content token, so a mid-stream failure routinely finds `output`- // empty while the generation so far sits in `reasoning`. The success- // path already falls back to it; doing the same here is the- // difference between salvaging a long run and reporting- // `outputSize: 0` after minutes of streaming.- const usedReasoningAsFallback = reasoningIsTheOutput();- const partialOutput = usedReasoningAsFallback ? reasoning : output;- if (partialOutput) {- await atomicWrite(outputPath, partialOutput).catch(() => {});- }-- const metadata = safeJsonParse(await readFile(metadataPath, 'utf-8').catch(() => '{}'));- metadata.endTime = new Date().toISOString();- metadata.duration = Date.now() - startTime;- metadata.success = false;+ const { metadata, partialOutput } = await openTerminalMetadata();const errorAnalysis = analyzeError(err.message);metadata.error = errorAnalysis.message || err.message;metadata.errorCategory = errorAnalysis.category;metadata.errorAnalysis = errorAnalysis;- metadata.outputSize = Buffer.byteLength(partialOutput);- metadata.hadReasoning = reasoning.length > 0;- metadata.usedReasoningAsFallback = usedReasoningAsFallback;if (errorAnalysis.hasError &&(errorAnalysis.category === ERROR_CATEGORIES.RATE_LIMIT ||diff --git a/server/lib/aiToolkit/runner.test.js b/server/lib/aiToolkit/runner.test.jsindex 3bd6ca8257..1a7b59a785 100644--- a/server/lib/aiToolkit/runner.test.js+++ b/server/lib/aiToolkit/runner.test.js@@ -747,6 +747,86 @@ describe('AI Toolkit runner service', () => {expect(persisted).toMatchObject({ canceled: true, errorCategory: 'canceled' });});+ // A reasoning model sends nearly its whole budget as `reasoning_content`+ // before the first content token, so a Stop mid-generation had `output` empty+ // and minutes of real generation sitting in `reasoning`. The cancel path+ // persisted `output` alone and stamped `outputSize: 0`, discarding all of it+ // and making a productive run read downstream as "the provider sent nothing".+ // That is how 16 NVIDIA NIM nemotron runs killed by promptRunner's mis-armed+ // backstop looked like dead-provider records instead of healthy streams+ // (#7665). The success/timeout/mid-stream-throw paths already salvage it.+ it('salvages reasoning as the output when a reasoning-only stream is stopped', async () => {+ const dataDir = await mkdtemp(join(tmpdir(), 'ai-toolkit-runner-'));+ tempDirs.push(dataDir);++ const frame = (obj) => `data: ${JSON.stringify(obj)}\n\n`;+ let sentReasoning = false;+ const fetch = vi.fn(async (_url, opts) => {+ const { signal } = opts;+ return {+ ok: true,+ body: {+ getReader: () => ({+ read: () => {+ // One reasoning frame, then park until the Stop aborts us.+ if (!sentReasoning) {+ sentReasoning = true;+ return Promise.resolve({+ done: false,+ value: new TextEncoder().encode(+ frame({ choices: [{ delta: { reasoning_content: 'deliberating at length' } }] })+ ),+ });+ }+ return new Promise((_resolve, reject) => {+ const fail = () => reject(signal.reason);+ if (signal.aborted) return fail();+ signal.addEventListener('abort', fail, { once: true });+ });+ },+ cancel: async () => {}+ })+ }+ };+ });+ vi.stubGlobal('fetch', fetch);++ const onRunFailed = vi.fn();+ const runner = createRunnerService({+ dataDir,+ hooks: { ensureProviderReady: async () => ({ success: true }), onRunFailed }+ });++ let done;+ const completed = new Promise((resolve) => { done = resolve; });+ await runner.executeApiRun({+ runId: 'run-stopped-reasoning',+ provider: runReady(),+ model: null,+ prompt: 'hi',+ workspacePath: process.cwd(),+ screenshots: [],+ timeout: 600_000,+ onData: undefined,+ onComplete: (m) => done(m)+ });++ expect(await runner.stopRun('run-stopped-reasoning')).toBe(true);++ const metadata = await completed;+ expect(metadata).toMatchObject({+ canceled: true,+ errorCategory: 'canceled',+ hadReasoning: true,+ usedReasoningAsFallback: true,+ });+ expect(metadata.outputSize).toBeGreaterThan(0);+ // A cancel is still not a provider failure, salvage or no salvage.+ expect(onRunFailed).not.toHaveBeenCalled();+ const persisted = await readFile(join(dataDir, 'runs', 'run-stopped-reasoning', 'output.txt'), 'utf-8');+ expect(persisted).toBe('deliberating at length');+ });+it('finalizes a Stop that lands before the response headers as canceled', async () => {const dataDir = await mkdtemp(join(tmpdir(), 'ai-toolkit-runner-'));tempDirs.push(dataDir);diff --git a/server/services/promptRunner.js b/server/services/promptRunner.jsindex 7d16c937d4..b2f250af01 100644--- a/server/services/promptRunner.js+++ b/server/services/promptRunner.js@@ -41,6 +41,7 @@ import { analyzeError, ERROR_CATEGORIES, isRunCanceledError } from '../lib/aiTooimport { isSchemaTypeCategory, resolveProviderBench } from '../lib/providerCooldown.js';import { isGenerationModel, isVisionCapableCliProvider } from '../lib/localModelHeuristics.js';import { contextWindowRejection } from '../lib/aiToolkit/providerStatus.js';+import { apiRunAbsoluteTimeoutMs } from '../lib/aiToolkit/internal/runTimeouts.js';import { withOllamaRuntimeContextWindow } from '../lib/ollamaContext.js';import { getAIToolkitInstance } from '../lib/aiToolkitState.js';import { createSingleFlight } from '../lib/singleFlight.js';@@ -110,10 +111,11 @@ export async function withObservedContextWindowsLazy(provider) {const CONTEXT_LENGTH_CATEGORY = 'context-length';export const DEFAULT_TIMEOUT_MS = 300000;-// Grace window past the runner's own API timeout before promptRunner's backstop-// timer fires. Lets executeApiRun's internal timeout win (aborting + finalizing-// as ERROR_CATEGORIES.TIMEOUT) so the normal path is classified correctly; the-// backstop only intervenes if the runner never reports completion at all.+// Grace window past the runner's own API deadline before promptRunner's+// backstop timer fires. Lets executeApiRun's internal timers win (aborting ++// finalizing as ERROR_CATEGORIES.TIMEOUT) so the normal path is classified+// correctly; the backstop only intervenes if the runner never reports+// completion at all.const API_TIMEOUT_BACKSTOP_GRACE_MS = 2000;const APPEND_CHUNK = (acc, chunk) => acc + (typeof chunk === 'string' ? chunk : (chunk?.text || ''));@@ -1657,10 +1659,24 @@ async function executeProviderRunOnce({// (meatspacePostLlm, pm2Standardizer, brain) never hang indefinitely.// The grace lets the runner's timeout win classification in the normal// path; safeReject/safeResolve clear this timer once onComplete lands.+ //+ // Armed against the runner's ABSOLUTE bound, not `effectiveTimeout`.+ // Since #7560 `effectiveTimeout` is the runner's re-armable NO-PROGRESS+ // bound — a run that keeps streaming legitimately outlives it, up to the+ // 30-minute total-runtime cap. This timer still fired at+ // `effectiveTimeout + 2s` and killed it anyway, which put back the exact+ // ceiling #7560 removed and made the new cap unreachable. Worse, it kills+ // via `stopRun`, so the runner finalized the run as a USER CANCEL:+ // `onRunFailed` never fired (no provider bench, no investigation task)+ // and `isRunCanceledError` callers skipped the fallback cascade — a+ // healthy, productive run silently produced nothing. Sixteen NVIDIA NIM+ // nemotron persistent-mind runs died this way at exactly 302s in the two+ // days after #7560 merged, and none before it (#7665).+ const backstopTimeout = apiRunAbsoluteTimeoutMs(effectiveTimeout);apiTimeoutHandle = setTimeout(() => {stopRun(runId).catch(() => { /* best-effort cancel */ });- safeReject(new Error(`API execution timed out after ${effectiveTimeout}ms`));- }, effectiveTimeout + API_TIMEOUT_BACKSTOP_GRACE_MS);+ safeReject(new Error(`API execution timed out after ${backstopTimeout}ms`));+ }, backstopTimeout + API_TIMEOUT_BACKSTOP_GRACE_MS);// Thread the caller's effectiveTimeout into the runner's internal timer so// a per-call override (e.g. the importer's long stage timeout) governs the// ceiling instead of the runner's provider/default fallback — samediff --git a/server/services/promptRunner.test.js b/server/services/promptRunner.test.jsindex ab860235df..85fdcbfc04 100644--- a/server/services/promptRunner.test.js+++ b/server/services/promptRunner.test.js@@ -82,6 +82,7 @@ const autoFixer = await import('./autoFixer.js');const toolkitState = await import('../lib/aiToolkitState.js');const observedWindows = await import('./observedContextWindows.js');const { ERROR_CATEGORIES } = await import('../lib/aiToolkit/errorDetection.js');+const { apiRunAbsoluteTimeoutMs } = await import('../lib/aiToolkit/internal/runTimeouts.js');const { CREATIVE_LATITUDE_HEADING, withCreativeLatitude } = await import('../lib/creativeLatitude.js');const { runPromptThroughProvider, resolveProviderAndModel, resolveEffectiveModel, pickConfigCorrectedModel, normalizeResponseSchema, coerceResponseToSchema, isSchemaTypeCategory, buildRequestCapabilities, assertVisionRunUsedImages } = await import('./promptRunner.js');@@ -938,13 +939,15 @@ describe('promptRunner — gateway sibling-key preservation', () => {});// =============================================================================-// API timeout enforcement — executeApiRun now owns the primary wall-clock-// timeout (it aborts + finalizes as TIMEOUT and fires onComplete). promptRunner-// keeps a SECONDARY backstop timer, delayed past the runner's deadline by-// API_TIMEOUT_BACKSTOP_GRACE_MS, purely for the pathological case where the-// runner (here a mock) neither throws nor ever calls onComplete. Verify that a-// stuck API run still rejects with the timeout error AND invokes stopRun.-// Regression guard for the round-2 review finding that API callers hung.+// API timeout enforcement — executeApiRun owns BOTH real deadlines: a+// re-armable no-progress bound (`timeout`) and a 30-minute absolute+// total-runtime cap (#7560). promptRunner keeps a SECONDARY backstop timer,+// armed against the ABSOLUTE bound plus API_TIMEOUT_BACKSTOP_GRACE_MS, purely+// for the pathological case where the runner (here a mock) neither throws nor+// ever calls onComplete. Verify that a stuck API run still rejects with the+// timeout error AND invokes stopRun — and, crucially, that the backstop does+// NOT fire at `timeout + grace`, which is where it used to kill healthy+// streaming runs and persist them as user cancels (#7665).// =============================================================================describe('promptRunner — API timeout enforcement', () => {@@ -962,18 +965,53 @@ describe('promptRunner — API timeout enforcement', () => {prompt: 'p', source: 't',timeout: 5000,});- const assertion = expect(promise).rejects.toThrow(/API execution timed out after 5000ms/);+ const backstopMs = apiRunAbsoluteTimeoutMs(5000);+ const assertion = expect(promise).rejects.toThrow(+ new RegExp(`API execution timed out after ${backstopMs}ms`)+ );- // Backstop fires at timeout + grace (5000 + 2000) — advance past it.- await vi.advanceTimersByTimeAsync(8000);+ // Backstop fires at the ABSOLUTE bound + grace — advance past it.+ await vi.advanceTimersByTimeAsync(backstopMs + 2000 + 1);await assertion;expect(runner.stopRun).toHaveBeenCalledWith('run-xyz');- // The runner's effective timeout is threaded through for its own internal timer.+ // The runner's effective timeout is threaded through for its own internal+ // no-progress timer, unchanged — only the backstop moved.expect(runner.executeApiRun).toHaveBeenCalledWith(expect.objectContaining({ timeout: 5000 }));vi.useRealTimers();});+ // The regression itself. #7560 made `timeout` a bound the runner RE-ARMS on+ // every byte, so a run that streams past it is healthy, not hung. This+ // backstop kept firing at `timeout + 2s` regardless of progress and killed it+ // via `stopRun`, which the runner records as a user CANCEL — suppressing+ // `onRunFailed`, the provider bench and the fallback cascade. Sixteen NVIDIA+ // NIM nemotron runs died at exactly 302s this way (#7665).+ it('backstop does not fire at the runner\'s no-progress bound while a run is still streaming', async () => {+ vi.useFakeTimers();+ let finish;+ runner.executeApiRun.mockImplementation(({ onComplete }) => {+ finish = () => onComplete({ success: true });+ return new Promise(() => {});+ });++ const promise = runPromptThroughProvider({+ provider: apiProvider(),+ prompt: 'p', source: 't',+ timeout: 5000,+ });++ // Well past the old backstop deadline (5000 + 2000) and past the default+ // 300s provider bound, but nowhere near the absolute cap.+ await vi.advanceTimersByTimeAsync(600_000);+ expect(runner.stopRun).not.toHaveBeenCalled();++ finish();+ await promise;+ expect(runner.stopRun).not.toHaveBeenCalled();+ vi.useRealTimers();+ });+it('does not call stopRun when API completes within the timeout', async () => {vi.useFakeTimers();runner.executeApiRun.mockImplementation(async ({ onData, onComplete }) => {