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: add wall-clock timeout to aiToolkit executeApiRun so hung API runs release activeRuns (#2541)
[._.]/ Adam Eivy93b74f601cd9
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 5d593be388..87c38bee41 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -63,3 +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.diff --git a/server/lib/aiToolkit/routes/runs.js b/server/lib/aiToolkit/routes/runs.jsindex 9398815918..2c99caa5cb 100644--- a/server/lib/aiToolkit/routes/runs.js+++ b/server/lib/aiToolkit/routes/runs.js@@ -112,6 +112,7 @@ export function createRunsRoutes(runnerService, options = {}) {onComplete: (finalMetadata) => {io?.emit(`run:${runId}:complete`, finalMetadata);},+ timeout: effectiveTimeout,});} else if (provider.type === 'tui' && typeof runnerService.executeTuiRun === 'function') {// Honor the user-picked model from the Runs UI — `executeTuiRun` readsdiff --git a/server/lib/aiToolkit/runner.js b/server/lib/aiToolkit/runner.jsindex 7235c41fcc..b609183d38 100644--- a/server/lib/aiToolkit/runner.js+++ b/server/lib/aiToolkit/runner.js@@ -20,6 +20,12 @@ 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+// 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;+/*** Resolve a bare command name to its full path WITH extension on Windows, so* the caller knows exactly which file (and which kind — `.exe` vs@@ -499,7 +505,7 @@ export function createRunnerService(config = {}) {return runId;},- async executeApiRun({ runId, provider, model, prompt, workspacePath, screenshots, onData, onComplete }) {+ async executeApiRun({ runId, provider, model, prompt, workspacePath, screenshots, onData, onComplete, timeout }) {const runDir = join(RUNS_PATH, runId);const outputPath = join(runDir, 'output.txt');const metadataPath = join(runDir, 'metadata.json');@@ -517,6 +523,26 @@ 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`.+ 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 = () => {+ if (apiTimeoutHandle) {+ clearTimeout(apiTimeoutHandle);+ apiTimeoutHandle = null;+ }+ };+hooks.onRunStarted?.({ runId, provider: provider.name, model });let messageContent;@@ -574,6 +600,7 @@ 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();activeRuns.delete(runId);const metadata = safeJsonParse(await readFile(metadataPath, 'utf-8').catch(() => '{}'));metadata.endTime = new Date().toISOString();@@ -651,6 +678,7 @@ export function createRunnerService(config = {}) {onData?.({ text: reasoning, isReasoning: true });}+ clearApiTimeout();await atomicWrite(outputPath, output);activeRuns.delete(runId);@@ -673,6 +701,7 @@ export function createRunnerService(config = {}) {// unguarded throw from handleProviderError/atomicWrite below would// surface as an unhandled rejection and crash the process. Wrap it.try {+ clearApiTimeout();activeRuns.delete(runId);if (output) {diff --git a/server/lib/aiToolkit/runner.test.js b/server/lib/aiToolkit/runner.test.jsindex a1bb47d8dd..07cfd7df23 100644--- a/server/lib/aiToolkit/runner.test.js+++ b/server/lib/aiToolkit/runner.test.js@@ -185,6 +185,57 @@ describe('AI Toolkit runner service', () => {errSpy.mockRestore();});++ it('times out a hung API run: aborts the fetch and releases activeRuns', async () => {+ const dataDir = await mkdtemp(join(tmpdir(), 'ai-toolkit-runner-'));+ tempDirs.push(dataDir);++ // Simulate a provider that opens the stream then stalls forever — the+ // reader only settles when the run's AbortController fires. Without the+ // wall-clock timeout this would hold `activeRuns` open indefinitely.+ const fetch = vi.fn(async (_url, opts) => {+ const { signal } = opts;+ const body = {+ getReader: () => ({+ 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 });+ }),+ cancel: async () => {}+ })+ };+ return { ok: true, body };+ });+ vi.stubGlobal('fetch', fetch);++ const runner = createRunnerService({+ dataDir,+ hooks: { ensureProviderReady: async () => ({ success: true }) }+ });++ let done;+ const completed = new Promise((resolve) => { done = resolve; });+ await runner.executeApiRun({+ runId: 'run-timeout',+ provider: runReady(),+ model: null,+ prompt: 'hi',+ workspacePath: process.cwd(),+ screenshots: [],+ timeout: 20,+ onData: undefined,+ onComplete: (m) => done(m)+ });++ // The stream is still hanging, so the run is active until the timer fires.+ expect(await runner.isRunActive('run-timeout')).toBe(true);++ 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 });+ });});describe('AI Toolkit runner — declared extension points', () => {