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
address review (codex): keep abort timer armed for error-body read, preserve run identity on write failure, demote promptRunner timer to backstop (#2541)
[._.]/ Adam Eivy3dcc53e27be5
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 4d8c778cc0..e8c1d92efe 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. 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'`.+- **[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 ceiling instead of being cut short by the provider/default fallback; `promptRunner`'s own timer is demoted to a delayed backstop so the runner's timeout wins classification. The non-2xx error-body read now runs with the abort timer still armed (a provider that sends error headers then stalls the body is cancelled, not hung), and the success-path finalization-failure fallback rebuilds metadata from the stored record so run identity survives a write error. 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.jsindex 1c71884040..fbb28306e5 100644--- a/server/lib/aiToolkit/runner.js+++ b/server/lib/aiToolkit/runner.js@@ -629,9 +629,19 @@ export function createRunnerService(config = {}) {: { ok: false, error: `Ollama is not running and PortOS could not start it: ${ready.error || 'unknown error'}`, status: 0 };if (!response.ok) {+ // Read the (possibly stalled) error body BEFORE claiming settlement so+ // the abort timer stays armed through the read — a provider that sends+ // non-2xx headers then holds the body open is cancelled by the timeout+ // instead of hanging here forever. `response.text()` consumes the same+ // signal-bound body, so an abort rejects it (swallowed to the fallback).+ let responseBody = response.error || '';+ if (response.text) {+ responseBody = await response.text().catch(() => response.error || '');+ }+// The timeout path may already own this run (an abort surfaces here as- // a rejected fetch) — if so it has finalized as a TIMEOUT; don't- // double-complete or reclassify.+ // a rejected fetch, or the read above was aborted) — if so it has+ // finalized as a TIMEOUT; don't double-complete or reclassify.if (!markSettled()) return runId;activeRuns.delete(runId);const metadata = safeJsonParse(await readFile(metadataPath, 'utf-8').catch(() => '{}'));@@ -639,11 +649,6 @@ export function createRunnerService(config = {}) {metadata.duration = Date.now() - startTime;metadata.success = false;- let responseBody = response.error || '';- if (response.text) {- responseBody = await response.text().catch(() => response.error || '');- }-const errorAnalysis = analyzeHttpError({status: response.status || 0,statusText: response.statusText || '',@@ -735,13 +740,17 @@ export function createRunnerService(config = {}) {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),- };+ // Build the failure from the stored record so runId/provider/model/+ // workspace survive, and best-effort persist it so run history is+ // terminal rather than stuck at `success: null`.+ const failMetadata = safeJsonParse(await readFile(metadataPath, 'utf-8').catch(() => '{}'));+ failMetadata.endTime = new Date().toISOString();+ failMetadata.duration = Date.now() - startTime;+ failMetadata.success = false;+ failMetadata.error = `Run finalization failed: ${writeErr.message}`;+ failMetadata.errorCategory = ERROR_CATEGORIES.UNKNOWN;+ failMetadata.outputSize = Buffer.byteLength(output);+ await atomicWrite(metadataPath, failMetadata).catch(() => {});safeSettle(() => hooks.onRunFailed?.(failMetadata, failMetadata.error, output), `Run ${runId} onRunFailed hook`);safeSettle(() => onComplete?.(failMetadata), `Run ${runId} onComplete`);}diff --git a/server/lib/promptRunner.js b/server/lib/promptRunner.jsindex 0b40fc9675..3f15267a48 100644--- a/server/lib/promptRunner.js+++ b/server/lib/promptRunner.js@@ -47,6 +47,11 @@ function loadAutoFixer() {}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.+const API_TIMEOUT_BACKSTOP_GRACE_MS = 2000;const APPEND_CHUNK = (acc, chunk) => acc + (typeof chunk === 'string' ? chunk : (chunk?.text || ''));// ── Local-backend concurrency gate ─────────────────────────────────────────@@ -1266,22 +1271,24 @@ async function executeProviderRunOnce({ provider, prompt, source, model, runId:executeCliRun({ runId, provider: providerForRun, prompt, workspacePath: effectiveCwd, onData, onComplete, timeout: effectiveTimeout }).catch(safeReject);} else if (effectiveProvider.type === PROVIDER_TYPES.API) {// API runs take model as a first-class arg — no clone needed. The- // toolkit's executeApiRun uses AbortController without a timer, so- // we enforce the per-call timeout here: if it fires before- // onComplete, reject with the same timeout shape CLI/TUI use and- // attempt to stop the run. Without this guard, API callers that- // used to enforce timeouts via fetchWithTimeout / AbortSignal.timeout- // (meatspacePostLlm, pm2Standardizer, brain) regress to hanging- // indefinitely on a stuck endpoint.+ // toolkit's executeApiRun now owns the primary wall-clock timeout (it+ // aborts AND finalizes the run as an ERROR_CATEGORIES.TIMEOUT, firing+ // onComplete → our reject below with a proper timeout classification).+ // We keep a SECONDARY backstop timer here — delayed past the runner's+ // own deadline by a grace window — purely for the pathological case+ // where the runner neither throws nor ever calls onComplete (e.g. a+ // future override): it best-effort stops the run and rejects so callers+ // (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.apiTimeoutHandle = setTimeout(() => {stopRun(runId).catch(() => { /* best-effort cancel */ });safeReject(new Error(`API execution timed out after ${effectiveTimeout}ms`));- }, effectiveTimeout);- // 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.+ }, effectiveTimeout + 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 — same+ // caller-override precedence CLI/TUI runs already get.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,diff --git a/server/lib/promptRunner.test.js b/server/lib/promptRunner.test.jsindex 9021be129c..83c3d32484 100644--- a/server/lib/promptRunner.test.js+++ b/server/lib/promptRunner.test.js@@ -593,17 +593,20 @@ describe('promptRunner — TUI provider routing', () => {});// =============================================================================-// API timeout enforcement — the toolkit's executeApiRun has no internal-// timer, so the central handler races a setTimeout against onComplete.-// Verify that a stuck API run rejects with the timeout error AND that-// stopRun is invoked for best-effort cancellation. Regression guard for-// the round-2 review finding that API callers were hanging indefinitely.+// 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.// =============================================================================describe('promptRunner — API timeout enforcement', () => {- it('rejects with timeout error when executeApiRun never completes and calls stopRun', async () => {+ it('backstop rejects with timeout error when executeApiRun never completes and calls stopRun', async () => {vi.useFakeTimers();- // executeApiRun hangs — never invokes onComplete or onData.+ // executeApiRun hangs — never invokes onComplete or onData (as a mock it+ // has no internal timer, so only promptRunner's backstop can fire).runner.executeApiRun.mockImplementation(() => new Promise(() => {}));// Kick off the call and attach the rejection assertion BEFORE advancing@@ -616,10 +619,13 @@ describe('promptRunner — API timeout enforcement', () => {});const assertion = expect(promise).rejects.toThrow(/API execution timed out after 5000ms/);- await vi.advanceTimersByTimeAsync(6000);+ // Backstop fires at timeout + grace (5000 + 2000) — advance past it.+ await vi.advanceTimersByTimeAsync(8000);await assertion;expect(runner.stopRun).toHaveBeenCalledWith('run-xyz');+ // The runner's effective timeout is threaded through for its own internal timer.+ expect(runner.executeApiRun).toHaveBeenCalledWith(expect.objectContaining({ timeout: 5000 }));vi.useRealTimers();});