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): finalize timed-out API runs as TIMEOUT via single-settlement gate, bound hung readiness hook (#2541)
[._.]/ Adam Eivy3e71c4ba34ee
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 87c38bee41..36a6e5b017 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`), arms it before the fetch and keeps it armed through the whole stream-consumption window, and clears it on every terminal path; a fired timeout aborts the controller, which routes into the existing `!response.ok`/`processStream().catch` cleanup so `activeRuns` is released. The Runs router now threads its `effectiveTimeout` into the API branch (parity with the CLI branch). New unit test proves a hung API run flips `isRunActive` back to false after the 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. 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'`.diff --git a/server/lib/aiToolkit/runner.js b/server/lib/aiToolkit/runner.jsindex b609183d38..4ec0cef00c 100644--- a/server/lib/aiToolkit/runner.js+++ b/server/lib/aiToolkit/runner.js@@ -523,25 +523,54 @@ export function createRunnerService(config = {}) {const controller = new AbortController();activeRuns.set(runId, controller);- // Wall-clock timeout: without this a hung provider (opens the stream then- // stalls, or never responds at all) holds the AbortController in- // `activeRuns` forever, leaking the run slot. Arm it BEFORE the fetch and- // keep it armed through the entire stream-consumption window — an abort- // rejects the pending fetch/reader, which routes into the `!response.ok`- // or `processStream().catch` paths below where `activeRuns` is cleaned up.- // Every terminal path calls `clearApiTimeout()` so the timer can't fire- // after a natural completion. Mirrors executeCliRun's `timeoutHandle`.+ // 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;- let apiTimeoutHandle = setTimeout(() => {- console.log(`⏱️ API run ${runId} timed out after ${effectiveTimeout}ms`);- controller.abort();- }, effectiveTimeout);- const clearApiTimeout = () => {+ let settled = false;+ let apiTimeoutHandle = null;+ const markSettled = () => {+ if (settled) return false;+ settled = true;if (apiTimeoutHandle) {clearTimeout(apiTimeoutHandle);apiTimeoutHandle = null;}+ return true;+ };+ const finalizeTimeout = async () => {+ if (!markSettled()) return;+ activeRuns.delete(runId);+ const error = `API execution timed out after ${effectiveTimeout}ms`;+ try {+ 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;+ metadata.error = error;+ metadata.errorCategory = ERROR_CATEGORIES.TIMEOUT;+ metadata.outputSize = Buffer.byteLength(output);+ await atomicWrite(metadataPath, metadata);+ safeSettle(() => hooks.onRunFailed?.(metadata, error, output), `Run ${runId} onRunFailed hook`);+ safeSettle(() => onComplete?.(metadata), `Run ${runId} onComplete`);+ } catch (finalErr) {+ console.error(`❌ API run ${runId} timeout finalize error: ${finalErr.message}`);+ safeSettle(() => onComplete?.({ success: false, error, endTime: new Date().toISOString(), duration: Date.now() - startTime, outputSize: Buffer.byteLength(output) }), `Run ${runId} onComplete`);+ }};+ apiTimeoutHandle = setTimeout(() => {+ console.log(`⏱️ API run ${runId} timed out after ${effectiveTimeout}ms`);+ controller.abort();+ finalizeTimeout().catch((err) => console.error(`❌ API run ${runId} timeout handler error: ${err.message}`));+ }, effectiveTimeout);hooks.onRunStarted?.({ runId, provider: provider.name, model });@@ -600,7 +629,10 @@ 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) {- clearApiTimeout();+ // 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.+ if (!markSettled()) return runId;activeRuns.delete(runId);const metadata = safeJsonParse(await readFile(metadataPath, 'utf-8').catch(() => '{}'));metadata.endTime = new Date().toISOString();@@ -678,7 +710,9 @@ export function createRunnerService(config = {}) {onData?.({ text: reasoning, isReasoning: true });}- clearApiTimeout();+ // A timeout firing between the last read and here would have finalized+ // the run already — don't overwrite a TIMEOUT with a spurious success.+ if (!markSettled()) return;await atomicWrite(outputPath, output);activeRuns.delete(runId);@@ -701,7 +735,9 @@ export function createRunnerService(config = {}) {// unguarded throw from handleProviderError/atomicWrite below would// surface as an unhandled rejection and crash the process. Wrap it.try {- clearApiTimeout();+ // If the timeout won the race (this catch is the aborted reader+ // rejecting), it already finalized as a TIMEOUT — bail out.+ if (!markSettled()) return;activeRuns.delete(runId);if (output) {diff --git a/server/lib/aiToolkit/runner.test.js b/server/lib/aiToolkit/runner.test.jsindex 07cfd7df23..f9cb3729d9 100644--- a/server/lib/aiToolkit/runner.test.js+++ b/server/lib/aiToolkit/runner.test.js@@ -234,7 +234,48 @@ describe('AI Toolkit runner service', () => {const metadata = await completed;// Timeout aborted the run, and the slot is released — not leaked.expect(await runner.isRunActive('run-timeout')).toBe(false);- expect(metadata).toMatchObject({ success: false });+ // The failure is classified as a timeout, not the AbortError's UNKNOWN/HTTP 0.+ expect(metadata).toMatchObject({ success: false, errorCategory: 'timeout' });+ expect(metadata.error).toMatch(/timed out/i);+ });++ it('bounds a run whose provider-readiness hook never resolves (fetch never reached)', async () => {+ const dataDir = await mkdtemp(join(tmpdir(), 'ai-toolkit-runner-'));+ tempDirs.push(dataDir);++ // ensureProviderReady hangs forever — the run never reaches the abortable+ // fetch, so aborting the controller alone can't release the slot. The+ // wall-clock timer must finalize the run independently.+ const fetch = vi.fn();+ vi.stubGlobal('fetch', fetch);+ const runner = createRunnerService({+ dataDir,+ hooks: { ensureProviderReady: () => new Promise(() => {}) }+ });++ let done;+ const completed = new Promise((resolve) => { done = resolve; });+ // Do NOT await the run promise — with a readiness hook that never resolves,+ // `executeApiRun` never returns. `activeRuns.set` runs synchronously before+ // the first await, so the slot is already occupied; completion comes only+ // from the wall-clock timer via onComplete.+ runner.executeApiRun({+ runId: 'run-hung-setup',+ provider: runReady(),+ model: null,+ prompt: 'hi',+ workspacePath: process.cwd(),+ screenshots: [],+ timeout: 20,+ onData: undefined,+ onComplete: (m) => done(m)+ }).catch(() => {});++ expect(await runner.isRunActive('run-hung-setup')).toBe(true);+ const metadata = await completed;+ expect(fetch).not.toHaveBeenCalled();+ expect(await runner.isRunActive('run-hung-setup')).toBe(false);+ expect(metadata).toMatchObject({ success: false, errorCategory: 'timeout' });});});