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: reject exhausted TUI request timeouts
[._.]/ Adam Eivydda8f4226317
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 344d1cc1f6..394fc0a350 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -36,6 +36,8 @@## Fixed+- **A TUI provider that exhausts its own request retries no longer returns an error screen as successful story output.** Claude Code may retry a backend timeout ten times, render a final `Request timed out` banner, and still exit with code 0. One long foundation repair consequently spent nearly an hour, produced no response file, and then sent terminal chrome into the universe JSON parser as if it were a 13K-character bible. The one-shot TUI runner now distinguishes recoverable `Retrying … attempt N/10` banners from the terminal gutter-owned timeout, records the latter as a real timeout, and enters the existing fallback cascade. Genuine long-running model work keeps its configured ceiling; only the provider's explicit exhausted-retry state ends the call.+- Foundation-judge completion logs now report the provider and model that actually produced the verdict after fallback, rather than the primary pair that was requested. The persisted snapshot already distinguished requested from actual routing; live Autopilot supervision now tells the same truth.- **Stopping a one-shot AI run no longer poisons provider health or repeats the work on a fallback.** PortOS restarts and the Runs UI both terminate an in-flight TUI with a signal. That intentional exit was previously finalized as an ordinary provider failure; worse, the error classifier scanned the whole prompt/screen, so an unrelated story word such as “credit” could relabel the stop as quota exhaustion, bench a healthy provider for an hour, queue an investigation, and begin the same expensive stage on a fallback while the server was already shutting down. External run stops are now tracked explicitly, host shutdown uses the existing process lifecycle latch, and both paths finalize as canceled: the run remains diagnosable in history but skips provider error analysis, failure hooks, fallback tiers, and health penalties. An unexpected PTY signal remains a real failure.diff --git a/server/lib/aiToolkit/errorDetection.js b/server/lib/aiToolkit/errorDetection.jsindex 0e95e1b250..388a25cb2d 100644--- a/server/lib/aiToolkit/errorDetection.js+++ b/server/lib/aiToolkit/errorDetection.js@@ -228,6 +228,47 @@ export function createTerminalModelErrorDetector({ maxBuffer = 512 } = {}) {};}+// Claude Code retries transient provider failures inside the TUI. Let those+// retries run: a line such as `Request timed out · Retrying … attempt 7/10` is+// still recoverable and may eventually produce the requested response file.+// Once all retries are exhausted, however, Claude Code renders a terminal+// gutter line (`⎿ Request timed out`) and may still exit with code 0. Without a+// one-shot-only detector, the runner calls that a success and hands the error+// screen to downstream JSON/prose consumers as if it were model output.+//+// Require the gutter glyph and the whole line. This deliberately does not match+// ordinary generated prose mentioning a request timeout, nor an in-progress+// retry banner. `\s*` between words also matches the cursor-positioned,+// ANSI-stripped shape observed from the TUI (`Requesttimedout`).+const TERMINAL_REQUEST_TIMEOUT_PATTERN = /^[\s\u00a0]*⎿[\s\u00a0]*Request\s*timed\s*out\.?[\s\u00a0]*$/im;++export function detectTerminalRequestTimeout(text) {+ if (!text) return null;+ const match = String(text).match(TERMINAL_REQUEST_TIMEOUT_PATTERN);+ if (!match) return null;+ return {+ hasError: true,+ category: ERROR_CATEGORIES.TIMEOUT,+ message: 'Provider request timed out after exhausting TUI retries',+ waitTime: null,+ requiresFallback: true,+ actionable: false,+ suggestedFix: 'The provider exhausted its internal request retries — retrying with a fallback provider.',+ exitCode: 124,+ };+}++export function createTerminalRequestTimeoutDetector({ maxBuffer = 512 } = {}) {+ let buffer = '';+ const cap = Number.isFinite(maxBuffer) && maxBuffer > 0 ? maxBuffer : 512;++ return (chunk) => {+ if (!chunk) return null;+ buffer = `${buffer}${String(chunk)}`.slice(-cap);+ return detectTerminalRequestTimeout(buffer);+ };+}+export function extractWaitTime(text) {if (!text) return null;diff --git a/server/lib/aiToolkit/errorDetection.test.js b/server/lib/aiToolkit/errorDetection.test.jsindex d2d196bf66..a10df4f745 100644--- a/server/lib/aiToolkit/errorDetection.test.js+++ b/server/lib/aiToolkit/errorDetection.test.js@@ -4,8 +4,10 @@ import {analyzeHttpError,createImmediateFallbackSignalDetector,createTerminalModelErrorDetector,+ createTerminalRequestTimeoutDetector,detectImmediateFallbackSignal,detectTerminalModelError,+ detectTerminalRequestTimeout,extractWaitTime,ERROR_CATEGORIES} from './errorDetection.js';@@ -324,6 +326,34 @@ describe('Error Detection', () => {});});+ describe('detectTerminalRequestTimeout', () => {+ it('detects Claude Code exhausting all internal request retries', () => {+ expect(detectTerminalRequestTimeout(' ⎿\u00a0Requesttimedout\n')).toMatchObject({+ category: ERROR_CATEGORIES.TIMEOUT,+ requiresFallback: true,+ actionable: false,+ exitCode: 124,+ });+ });++ it('does not interrupt an in-progress internal retry', () => {+ expect(detectTerminalRequestTimeout('⎿ Request timed out · Retrying in 38s · attempt 9/10\n')).toBeNull();+ });++ it('does not treat generated prose mentioning a timeout as provider chrome', () => {+ expect(detectTerminalRequestTimeout('The report says the request timed out before the retry.')).toBeNull();+ });++ it('buffers the terminal banner across stream chunks', () => {+ const detect = createTerminalRequestTimeoutDetector();+ expect(detect(' ⎿ Request')).toBeNull();+ expect(detect(' timed out\n')).toMatchObject({+ category: ERROR_CATEGORIES.TIMEOUT,+ exitCode: 124,+ });+ });+ });+describe('extractWaitTime', () => {it('should extract "X day X hour X minutes" format', () => {const result = extractWaitTime('try again in 1 day 2 hours 30 minutes');diff --git a/server/lib/tuiPromptRunner.js b/server/lib/tuiPromptRunner.jsindex ed088c2d24..674c7a34e0 100644--- a/server/lib/tuiPromptRunner.js+++ b/server/lib/tuiPromptRunner.js@@ -37,7 +37,11 @@ import { spawn as ptySpawn } from 'node-pty';import { join, resolve } from 'path';import { ensureDir, PATHS, tryReadFile } from './fileUtils.js';import { createStreamingAnsiStripper, stripAnsi } from './ansiStrip.js';-import { createImmediateFallbackSignalDetector, createTerminalModelErrorDetector } from './aiToolkit/errorDetection.js';+import {+ createImmediateFallbackSignalDetector,+ createTerminalModelErrorDetector,+ createTerminalRequestTimeoutDetector,+} from './aiToolkit/errorDetection.js';import { getRunsPath, finalizeRunRecord, emitRunStarted, registerActiveRun, unregisterActiveRun, consumeRunStopRequested, resolveRunCwd } from '../services/runner.js';import { registerExternalSession, unregisterExternalSession, isExternalSessionAttached } from '../services/shell.js';import { isHostShuttingDown } from './hostShutdown.js';@@ -265,6 +269,10 @@ ${prompt}`;// (not in the shared fallback detector) so it can't kill a long-running agent// that merely echoes the error line — see errorDetection.js for the rationale.const detectTerminalModelError = createTerminalModelErrorDetector();+ // Claude Code can exhaust all of its own request retries and then exit 0 with+ // only `⎿ Request timed out` on screen. This one-shot-only detector lets the+ // central runner fall back instead of parsing that terminal as creative output.+ const detectTerminalRequestTimeout = createTerminalRequestTimeoutDetector();// True once outputBuffer overflowed OUTPUT_BUFFER_HEADROOM and the head was// dropped. We warn once and surface it in the run record so /runs can flag// responses where the fallback path may have lost the start.@@ -423,11 +431,13 @@ ${prompt}`;}onData?.(stripped);- const fallbackSignal = detectImmediateFallbackSignal(stripped) || detectTerminalModelError(stripped);+ const fallbackSignal = detectImmediateFallbackSignal(stripped)+ || detectTerminalModelError(stripped)+ || detectTerminalRequestTimeout(stripped);if (fallbackSignal) {finish({success: false,- exitCode: 1,+ exitCode: fallbackSignal.exitCode ?? 1,error: fallbackSignal.message || 'Provider requires fallback',reason: 'fallback-signal'});diff --git a/server/lib/tuiPromptRunner.test.js b/server/lib/tuiPromptRunner.test.jsindex 791f48c459..a659a81dc3 100644--- a/server/lib/tuiPromptRunner.test.js+++ b/server/lib/tuiPromptRunner.test.js@@ -755,6 +755,34 @@ describe('executeTuiRun', () => {}));});+ it('fails as a timeout after Claude exhausts its internal request retries instead of parsing the error screen as output', async () => {+ const provider = { id: 'claude', type: 'tui', command: 'claude' };+ const onComplete = vi.fn();+ const promise = executeTuiRun({ runId: 'run-request-timeout', provider, prompt: 'a prompt long enough', workspacePath: TEST_WORKSPACE, onData: undefined, onComplete, timeout: 60000 });+ await flushAsync();++ // Retry banners are recoverable and must not be interrupted. The final+ // gutter-owned line is what Claude Code shows only after retry 10/10.+ ptyInstances[0].emitData('⎿ Request timed out · Retrying in 38s · attempt 9/10\n');+ expect(ptyInstances[0].kill).not.toHaveBeenCalled();+ ptyInstances[0].emitData(' ⎿\u00a0Requesttimedout\n');++ await promise;+ expect(ptyInstances[0].kill).toHaveBeenCalled();+ expect(runnerMocks.finalizeRunRecord).toHaveBeenCalledWith(expect.objectContaining({+ runId: 'run-request-timeout',+ success: false,+ exitCode: 124,+ error: expect.stringContaining('timed out'),+ extras: expect.objectContaining({ completionReason: 'fallback-signal' }),+ }));+ expect(onComplete).toHaveBeenCalledWith(expect.objectContaining({+ success: false,+ exitCode: 124,+ completionReason: 'fallback-signal',+ }));+ });+it('finishes with reason "exit" + exitCode 0 when the PTY closes cleanly', async () => {const provider = { id: 'claude', type: 'tui', command: 'echo' };const promise = executeTuiRun({ runId: 'run-exit', provider, prompt: 'a prompt long enough', workspacePath: TEST_WORKSPACE, onData: undefined, onComplete: undefined, timeout: 60000 });