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

address review (codex): thread caller timeout override into API runs; guarantee onComplete on success-write failure (#2541)

[._.]/ Adam Eivycb93a58d4539
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 36a6e5b017..4d8c778cc0 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -63,4 +63,4 @@
- **Fix the DevTools → Usage page crashing with "(providers || []).map/filter is not a function".** `services/providers.getAllProviders()` returns the wrapped `{ activeProvider, providers }` object, but `routes/usage.js` (GET `/api/usage`) and `services/providerUsage.js#getProviderQuotas` (GET `/api/usage/providers`) passed that object straight into `.map`/`.filter`, throwing on every request so the Usage page showed "Couldn't read provider usage." / "No usage data available." Both call sites now unwrap `.providers` via the `Array.isArray(result) ? result : (result?.providers || [])` pattern already used in `jiraReports.js`/`loops.js`. The two test suites mocked `getAllProviders` as a bare array (masking the bug); their mocks now return the real object shape, plus a new `getProviderQuotas` regression test asserts the unwrap.
- **[issue-2598] Add Antigravity + Grok subscription-usage adapters via headless TUI `/usage` scrape.** DevTools → Usage previously showed "not available" placeholders for the `agy` (Antigravity) and `grok` (Grok Build) provider families, because neither CLI exposes quota in non-interactive `--print` mode (there `/usage` is treated as an LLM prompt — wrong data, and it burns tokens). Their real usage surface is an interactive slash command (`/usage` for agy, `/usage show` for grok), so a new `server/lib/tuiUsageScrape.js#scrapeTuiUsage` drives the TUI in a **sandbox PTY** (a fixed dir under the OS temp dir — never the user's project — trusted once via a primer Enter, output-idle-gated capture, hard-timeout backstop), and `providerUsage.js` parses the rendered panel into the common quota shape. Antigravity reports one card per model group (e.g. Gemini, Claude/GPT) with weekly + 5-hour meters and reset times, treating its bar percentage as **remaining**; Grok reports a single weekly meter treating `Weekly limit: N%` as **used**. Both scrapes are 0-token (the slash command renders synchronously, no LLM turn), user-triggered only, and cached 5 min with single-flight (each scrape costs ~12s). Parse failures degrade to a soft "no quota data" warning card rather than erroring the page. New unit tests cover both parsers, the relative-reset→ISO conversion, and the fetch/cache wiring.
- **[issue-2532] Extract the Shell page's socket/session/terminal lifecycle into a `useShellSession` hook.** `pages/Shell.jsx` inlined ~750 lines of xterm setup, the Socket.IO `shell:*` protocol, and the single-subscriber PTY attach/detach contract (the `pendingAttachRef {target,generation}` guards, `claim`-vs-user-intent handling, `userIdleRef` passive-idle gating, `mountedRef` deferred-work guards, and URL sync). That cohesive concern now lives in `client/src/hooks/useShellSession.js` — which documents the full attach/detach contract at the top of the file — and the route drops to a thin presentational shell (header, quick-commands, terminal container) plus two extracted panels, `components/shell/TerminalHotKeys.jsx` and `components/shell/ShellSessionTabs.jsx`. Pure structural refactor toward the WritersRoom pattern — behavior identical, generation guards preserved byte-for-byte, no route-contract change; lint, the hooks barrel test, and the client build stay green.
-- **[issue-2541] Add a wall-clock timeout to the AI toolkit's API runner so a hung provider can't leak `activeRuns`.** `runner.js#executeApiRun` attached an `AbortController` but armed no timer, so an upstream that opened the SSE stream then stalled (or never responded) held its controller in `activeRuns` — and thus the run slot — indefinitely; the CLI path (`executeCliRun`) already had an internal timeout, and the Runs-router path invoked the API runner with no outer guard. `executeApiRun` now accepts an optional `timeout` (falling back to `provider.timeout` then a 300s default, mirroring `aiProvider`/`askService`) and arms it before the fetch. A single-settlement gate (`markSettled()`) guarantees exactly one of {timer, response paths} finalizes the run: on timeout the timer aborts the fetch/reader AND independently finalizes the run as an `ERROR_CATEGORIES.TIMEOUT` failure — so a stalled fetch/stream, a provider that never responds, and even a `ensureProviderReady` hook that never reaches the fetch are all bounded, and the failure is recorded as a timeout instead of the raw AbortError's `UNKNOWN`/HTTP 0. The Runs router now threads its `effectiveTimeout` into the API branch (parity with the CLI branch). New unit tests prove both a hung stream and a hung readiness hook flip `isRunActive` back to false and complete with `errorCategory: 'timeout'`.
+- **[issue-2541] Add a wall-clock timeout to the AI toolkit's API runner so a hung provider can't leak `activeRuns`.** `runner.js#executeApiRun` attached an `AbortController` but armed no timer, so an upstream that opened the SSE stream then stalled (or never responded) held its controller in `activeRuns` — and thus the run slot — indefinitely; the CLI path (`executeCliRun`) already had an internal timeout, and the Runs-router path invoked the API runner with no outer guard. `executeApiRun` now accepts an optional `timeout` (falling back to `provider.timeout` then a 300s default, mirroring `aiProvider`/`askService`) and arms it before the fetch. A single-settlement gate (`markSettled()`) guarantees exactly one of {timer, response paths} finalizes the run: on timeout the timer aborts the fetch/reader AND independently finalizes the run as an `ERROR_CATEGORIES.TIMEOUT` failure — so a stalled fetch/stream, a provider that never responds, and even a `ensureProviderReady` hook that never reaches the fetch are all bounded, and the failure is recorded as a timeout instead of the raw AbortError's `UNKNOWN`/HTTP 0. Both the Runs router and `promptRunner` now thread their `effectiveTimeout` into the API call (parity with the CLI/TUI branches), so a per-call override — e.g. the importer's long stage timeout — governs the internal ceiling instead of being cut short by the provider/default fallback. New unit tests prove both a hung stream and a hung readiness hook flip `isRunActive` back to false and complete with `errorCategory: 'timeout'`.
diff --git a/server/lib/aiToolkit/runner.js b/server/lib/aiToolkit/runner.js
index 4ec0cef00c..1c71884040 100644
--- a/server/lib/aiToolkit/runner.js
+++ b/server/lib/aiToolkit/runner.js
@@ -712,22 +712,39 @@ export function createRunnerService(config = {}) {
// A timeout firing between the last read and here would have finalized
// the run already — don't overwrite a TIMEOUT with a spurious success.
+ // Once we claim settlement the outer processStream().catch bails, so
+ // this block owns cleanup end-to-end: release the slot up front and
+ // guarantee onComplete fires even if a persistence write throws (full
+ // disk, rename failure) — otherwise the caller would hang forever.
if (!markSettled()) return;
- await atomicWrite(outputPath, output);
activeRuns.delete(runId);
+ try {
+ await atomicWrite(outputPath, output);
- const metadata = safeJsonParse(await readFile(metadataPath, 'utf-8').catch(() => '{}'));
- metadata.endTime = new Date().toISOString();
- metadata.duration = Date.now() - startTime;
- metadata.exitCode = 0;
- metadata.success = true;
- metadata.outputSize = Buffer.byteLength(output);
- metadata.hadReasoning = reasoning.length > 0;
- metadata.usedReasoningAsFallback = usedReasoningAsFallback;
- await atomicWrite(metadataPath, metadata);
+ const metadata = safeJsonParse(await readFile(metadataPath, 'utf-8').catch(() => '{}'));
+ metadata.endTime = new Date().toISOString();
+ metadata.duration = Date.now() - startTime;
+ metadata.exitCode = 0;
+ metadata.success = true;
+ metadata.outputSize = Buffer.byteLength(output);
+ metadata.hadReasoning = reasoning.length > 0;
+ metadata.usedReasoningAsFallback = usedReasoningAsFallback;
+ await atomicWrite(metadataPath, metadata);
- hooks.onRunCompleted?.(metadata, output);
- onComplete?.(metadata);
+ safeSettle(() => hooks.onRunCompleted?.(metadata, output), `Run ${runId} onRunCompleted hook`);
+ safeSettle(() => onComplete?.(metadata), `Run ${runId} onComplete`);
+ } catch (writeErr) {
+ console.error(`❌ Run ${runId} success finalize error: ${writeErr.message}`);
+ const failMetadata = {
+ endTime: new Date().toISOString(),
+ duration: Date.now() - startTime,
+ success: false,
+ error: `Run finalization failed: ${writeErr.message}`,
+ outputSize: Buffer.byteLength(output),
+ };
+ safeSettle(() => hooks.onRunFailed?.(failMetadata, failMetadata.error, output), `Run ${runId} onRunFailed hook`);
+ safeSettle(() => onComplete?.(failMetadata), `Run ${runId} onComplete`);
+ }
};
processStream().catch(async (err) => {
diff --git a/server/lib/promptRunner.js b/server/lib/promptRunner.js
index 0232aa6ec6..0b40fc9675 100644
--- a/server/lib/promptRunner.js
+++ b/server/lib/promptRunner.js
@@ -1277,7 +1277,12 @@ async function executeProviderRunOnce({ provider, prompt, source, model, runId:
stopRun(runId).catch(() => { /* best-effort cancel */ });
safeReject(new Error(`API execution timed out after ${effectiveTimeout}ms`));
}, effectiveTimeout);
- executeApiRun({ runId, provider: effectiveProvider, model: effectiveModel, prompt, workspacePath: effectiveCwd, screenshots: Array.isArray(screenshots) ? screenshots : [], onData, onComplete }).catch(safeReject);
+ // Thread the caller's effectiveTimeout into the toolkit's own internal
+ // wall-clock timer so a per-call override (e.g. the importer's long stage
+ // timeout) isn't cut short by the runner's provider/default fallback —
+ // same caller-override precedence CLI/TUI runs already get. The outer
+ // apiTimeoutHandle above stays as a belt-and-suspenders backstop.
+ executeApiRun({ runId, provider: effectiveProvider, model: effectiveModel, prompt, workspacePath: effectiveCwd, screenshots: Array.isArray(screenshots) ? screenshots : [], onData, onComplete, timeout: effectiveTimeout }).catch(safeReject);
} else if (effectiveProvider.type === PROVIDER_TYPES.TUI) {
// `source` (e.g. 'pipeline-manuscript-completeness') labels the live,
// interactive view this TUI run surfaces in the Shell page.