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: require a real line end before calling a TUI request timeout terminal
[._.]/ Adam Eivyca7b17f0d8e6
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 4b84d03af8..c36319b103 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -20,6 +20,12 @@- Internal: [issue-3705] the MortalLoom store's boot/settings-change eviction pin no longer carries its own copy of the `brctl download` spawn/detach/exit-handler plumbing — it now delegates to the shared `icloudFile.requestMaterialization` helper the read paths already use. The helper gained an explicit dedupe policy (`retryAfterExit`): the read paths stay tracked in its capped in-flight map so a later read can retry, while the pin opts out and keeps its own single-sticky-path dedupe (re-pin only when the configured path changes) plus an `onFailure` hook that clears the sticky path so a failed or killed pin can retry. The once-per-process "brctl not found on PATH" warning also folded into the shared flag, so it fires at most once across the pin, read, and write paths rather than once per caller. ~40 lines of duplicated spawn plumbing removed. Two small, deliberate behavior changes come with the consolidation: the pin now inherits the shared 120s download deadline (a wedged boot pin is SIGKILL'd and left to the next `settings:updated` to retry, instead of lingering unref'd forever), and it now only spawns `brctl` for genuine iCloud (`/Library/Mobile Documents/`) paths rather than any macOS path — the pin exists solely for the iCloud store, so a non-iCloud configured path is no longer handed a doomed `brctl download`.+- **[issue-3715] A retrying AI run is no longer killed a second before it would have recovered.** When Claude Code hits a request timeout it retries on its own — up to ten attempts — and PortOS deliberately lets those retries play out. But PortOS reads the terminal a fragment at a time, and whenever a fragment happened to end right after "Request timed out", before the "Retrying in 38s, attempt 3/10" half of the line arrived, it was indistinguishable from the final give-up message. PortOS would fail the run there: an expensive stage re-ran on a fallback provider and a failure task landed in your queue, while the original run had been perfectly healthy and about to succeed. With a countdown repainting the screen hundreds of times per retry sequence, that mis-read was a matter of time rather than bad luck. PortOS now waits for the end of the line before judging it — and still catches the real give-up message, including when it is the last thing on screen as the tool exits.++- **[issue-3715] A finished answer is no longer thrown away when a provider error arrives moments after it was written.** PortOS waits for an AI run's answer file to stop growing before calling the run done, which leaves roughly a second between "the complete answer is on disk" and "the run is finalized". A provider error painting inside that window used to fail the run outright — and because PortOS only reads the answer file for successful runs, the finished work was discarded, the error screen was handed back in its place, and a fallback provider re-ran the same expensive stage. PortOS now looks for the completed answer first and returns it, the same way it already did when a run hit its overall time limit.++- Internal: [issue-3715] `createTerminalRequestTimeoutDetector` now tracks the same `truncated` slice-boundary signal as its sibling `createImmediateFallbackSignalDetector` — its rolling 512-char window rolls within a second on a TUI stream, and a `^`-anchored pattern would otherwise match a fabricated line start (a long line of agent prose sliced exactly before the gutter glyph). The repaint loop re-delivers the real banner with a witnessed line start moments later, so nothing genuine is lost.+## Added- **Series Autopilot can split one run across a writer and an independent critic.** Options now exposes separate soft provider/model/effort routes for creation-and-repair work versus judging-and-verification work, so a run can, for example, draft with Luna at max effort while Sol at xhigh independently evaluates whether those edits actually improved the story. The split applies across foundation judging, arc and beat verification, script/editorial analysis, iterative-quality judging, and pipeline diagnosis; corrective rewrites stay on the creative route, and exact stage pins in Prompts still take precedence. Cooperative stops and ordinary pauses preserve both routes for Resume instead of silently falling back to the series default.diff --git a/server/lib/aiToolkit/errorDetection.js b/server/lib/aiToolkit/errorDetection.jsindex 388a25cb2d..226c9c6610 100644--- a/server/lib/aiToolkit/errorDetection.js+++ b/server/lib/aiToolkit/errorDetection.js@@ -228,6 +228,11 @@ export function createTerminalModelErrorDetector({ maxBuffer = 512 } = {}) {};}+// A non-printing, non-line-terminator byte prefixed to a buffer whose index 0 is+// a slice boundary rather than a witnessed line start, so a `^…/m` pattern+// cannot match there. Full rationale on resolveSignalOrigin below.+const UNTRUSTED_BOUNDARY = '\x00';+// 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.@@ -240,11 +245,25 @@ export function createTerminalModelErrorDetector({ maxBuffer = 512 } = {}) {// 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) {+//+// The line must end with a REAL terminator (`\r` or `\n`) — `$` alone is a trap+// here (#3715). The streaming detector re-tests a rolling buffer whose end is+// always the newest byte received, so `$` also matched "the line so far",+// making a PTY chunk that split right after `Request timed out`+// indistinguishable from a finished line: the ` · Retrying in 38s · attempt+// 3/10` suffix simply had not been delivered yet. With a 200x50 PTY repainting+// on every countdown tick that split is a matter of time, not a rare race — and+// it killed the very runs this detector exists to let keep retrying. Requiring+// a terminator holds the candidate until the rest of the line lands; if that+// turns out to be a retry suffix, the match never happens. Trailing horizontal+// whitespace is tolerated, but `[^\S\r\n]` must not swallow the terminator.+const TERMINAL_REQUEST_TIMEOUT_PATTERN = /^[\s\u00a0]*⎿[\s\u00a0]*Request\s*timed\s*out\.?[^\S\r\n]*[\r\n]/im;++export function detectTerminalRequestTimeout(text, { lineStartTrusted = true } = {}) {if (!text) return null;- const match = String(text).match(TERMINAL_REQUEST_TIMEOUT_PATTERN);+ const value = String(text);+ const match = (lineStartTrusted ? value : `${UNTRUSTED_BOUNDARY}${value}`)+ .match(TERMINAL_REQUEST_TIMEOUT_PATTERN);if (!match) return null;return {hasError: true,@@ -260,12 +279,30 @@ export function detectTerminalRequestTimeout(text) {export function createTerminalRequestTimeoutDetector({ maxBuffer = 512 } = {}) {let buffer = '';+ // Mirrors createImmediateFallbackSignalDetector: once the window has dropped+ // anything, buffer[0] is a slice boundary, not a line start, and the+ // `^`-anchored pattern would happily match a fabricated one (a long line of+ // agent prose sliced exactly before the gutter glyph). A TUI stream rolls a+ // 512-char window within a second, so this matters in practice; the repaint+ // loop re-delivers the real banner with its own line start moments later.+ let truncated = false;const cap = Number.isFinite(maxBuffer) && maxBuffer > 0 ? maxBuffer : 512;- return (chunk) => {- if (!chunk) return null;- buffer = `${buffer}${String(chunk)}`.slice(-cap);- return detectTerminalRequestTimeout(buffer);+ // `endOfStream` reports that no more bytes can arrive (the PTY exited), which+ // is itself the terminator a held candidate was waiting for — nothing can+ // still complete the last line into a `· Retrying …` banner. Synthesizing the+ // newline there keeps the terminator requirement above from losing the case+ // where the banner is the final thing painted before exit.+ return (chunk, { endOfStream = false } = {}) => {+ if (chunk) {+ const next = `${buffer}${String(chunk)}`;+ if (next.length > cap) truncated = true;+ buffer = next.slice(-cap);+ } else if (!endOfStream) return null;+ return detectTerminalRequestTimeout(+ endOfStream ? `${buffer}\n` : buffer,+ { lineStartTrusted: !truncated },+ );};}@@ -364,8 +401,6 @@ export function analyzeError(errorText, exitCode = null) {* which is how a repainted TUI screen advances) still promotes, and nothing is* discarded. Pure.*/-const UNTRUSTED_BOUNDARY = '\x00';-function resolveSignalOrigin(signal, text, lineStartTrusted) {if (!signal.structuredMarker) return 'provider';const value = text || '';diff --git a/server/lib/aiToolkit/errorDetection.test.js b/server/lib/aiToolkit/errorDetection.test.jsindex a10df4f745..597b578ceb 100644--- a/server/lib/aiToolkit/errorDetection.test.js+++ b/server/lib/aiToolkit/errorDetection.test.js@@ -352,6 +352,64 @@ describe('Error Detection', () => {exitCode: 124,});});++ // #3715 — the whole-banner cases above all pass with a `$`-terminated+ // pattern too. What broke in production was the SPLIT: the buffered+ // detector re-tests a rolling buffer whose end is the newest byte, so+ // "line so far ends at 'Request timed out'" looked exactly like a finished+ // line and killed a run that was still happily retrying.+ it('does NOT fire when a PTY chunk boundary lands right after "Request timed out"', () => {+ const detect = createTerminalRequestTimeoutDetector();+ expect(detect(' ⎿ Request timed out')).toBeNull();+ });++ it('discards a split candidate that the next chunk completes into a retry banner', () => {+ const detect = createTerminalRequestTimeoutDetector();+ expect(detect(' ⎿ Request timed out')).toBeNull();+ expect(detect(' · Retrying in 38s · attempt 3/10\n')).toBeNull();+ // …and the countdown repaint that follows is still not a terminal state.+ expect(detect(' ⎿ Request timed out · Retrying in 37s · attempt 3/10\n')).toBeNull();+ });++ it('fires once the terminator for a split candidate finally arrives', () => {+ const detect = createTerminalRequestTimeoutDetector();+ expect(detect(' ⎿ Request timed out')).toBeNull();+ expect(detect('\n')).toMatchObject({ category: ERROR_CATEGORIES.TIMEOUT, exitCode: 124 });+ });++ it('accepts a bare CR terminator (how a repainted TUI screen advances)', () => {+ const detect = createTerminalRequestTimeoutDetector();+ expect(detect(' ⎿ Request timed out\r')).toMatchObject({ exitCode: 124 });+ });++ it('treats end of stream as the terminator a held candidate was waiting for', () => {+ const detect = createTerminalRequestTimeoutDetector();+ expect(detect(' ⎿ Request timed out')).toBeNull();+ // The PTY exited — nothing can still complete the line into a retry.+ expect(detect(null, { endOfStream: true })).toMatchObject({ exitCode: 124 });+ });++ it('does not invent a match at end of stream when the last line is a retry banner', () => {+ const detect = createTerminalRequestTimeoutDetector();+ detect(' ⎿ Request timed out · Retrying in 38s · attempt 3/10');+ expect(detect(null, { endOfStream: true })).toBeNull();+ });++ it('ignores a line start fabricated by the rolling window slice boundary', () => {+ // One long line of agent prose quoting the banner, with the window sized so+ // the slice lands EXACTLY on the gutter glyph. buffer[0] then looks like a+ // line start the stream never witnessed — matching there would kill a+ // healthy run over the agent's own output.+ const banner = '⎿ Request timed out\n';+ const detect = createTerminalRequestTimeoutDetector({ maxBuffer: banner.length });+ expect(detect(`while investigating I saw ${banner}`)).toBeNull();+ });++ it('still fires on a real line start inside a window that has already rolled', () => {+ const detect = createTerminalRequestTimeoutDetector({ maxBuffer: 32 });+ detect('a long banner line of TUI chrome that overflows the window\n');+ expect(detect(' ⎿ Request timed out\n')).toMatchObject({ exitCode: 124 });+ });});describe('extractWaitTime', () => {diff --git a/server/lib/tuiPromptRunner.js b/server/lib/tuiPromptRunner.jsindex 674c7a34e0..7ba297f1b3 100644--- a/server/lib/tuiPromptRunner.js+++ b/server/lib/tuiPromptRunner.js@@ -297,6 +297,13 @@ ${prompt}`;lastResponseLen = txt.length;return false;};+ // Stability doesn't apply once nothing can still be writing (hard timeout with+ // the TUI wedged, or the PTY already gone): non-empty content is the whole+ // answer by then.+ const responseFileHasContent = async () => {+ const txt = await tryReadFile(responseFilePath);+ return typeof txt === 'string' && !!txt.trim();+ };let readyTimer = null;let pasteEnterTimer = null;@@ -413,6 +420,36 @@ ${prompt}`;}};+ // A fallback signal means "this provider can't finish the job" — but the+ // model may have ALREADY finished it. responseFileWatchTimer only finalizes+ // after two 1s polls agree on the file size, so there is a ≥1s window where+ // the response file is complete on disk and the run hasn't finalized. A+ // signal painting inside that window used to finish({ success: false }),+ // and since resolveTuiResponseText only reads the file when `success` is+ // true, the finished response was discarded, the ANSI-stripped error screen+ // was returned in its place, and a fallback tier re-ran an expensive stage+ // (#3715). Check for a usable response file first — the same salvage net the+ // hard-timeout path already has. While the PTY is alive the file must be+ // size-stable (it could still be mid-write); once the process has exited+ // nothing can still be writing, so non-empty is enough.+ const finishWithFallbackSignal = async (signal, { processExited = false } = {}) => {+ const salvaged = processExited+ ? await responseFileHasContent()+ : await responseFileSettled();+ if (finalized) return;+ if (salvaged) {+ console.log(`📄 TUI run ${runId} salvaged its completed response file despite a fallback signal: ${signal.message}`);+ await finish({ success: true, exitCode: 0, reason: 'fallback-signal-response-file' });+ return;+ }+ await finish({+ success: false,+ exitCode: signal.exitCode ?? 1,+ error: signal.message || 'Provider requires fallback',+ reason: 'fallback-signal',+ });+ };+ptyProcess.onData((data) => {const text = data.toString();rawBuffer += text;@@ -435,11 +472,11 @@ ${prompt}`;|| detectTerminalModelError(stripped)|| detectTerminalRequestTimeout(stripped);if (fallbackSignal) {- finish({- success: false,- exitCode: fallbackSignal.exitCode ?? 1,- error: fallbackSignal.message || 'Provider requires fallback',- reason: 'fallback-signal'+ // Fire-and-forget like every other finish() call from this PTY+ // callback; finish() itself never rejects and the salvage read can't+ // throw, so the catch is belt-and-braces for a callback boundary.+ finishWithFallbackSignal(fallbackSignal).catch((err) => {+ console.error(`❌ TUI run ${runId} fallback-signal handling failed: ${err?.message || err}`);});return;}@@ -503,6 +540,19 @@ ${prompt}`;const canceled = killed && (stopRequested || hostInterrupted);const finalExitCode = typeof exitCode === 'number' ? exitCode : (killed ? 130 : 0);const success = !killed && finalExitCode === 0;+ // The terminal-timeout detector holds a candidate banner until a real line+ // terminator proves the line is finished (#3715). Process exit IS that+ // proof — no further byte can turn `⎿ Request timed out` into a+ // `· Retrying …` banner — so flush the held candidate here rather than+ // letting a clean exit 0 scrape the error screen as model output (the+ // exact failure the detector was added for).+ const heldTimeout = success ? detectTerminalRequestTimeout(null, { endOfStream: true }) : null;+ if (heldTimeout) {+ finishWithFallbackSignal(heldTimeout, { processExited: true }).catch((err) => {+ console.error(`❌ TUI run ${runId} exit-time timeout handling failed: ${err?.message || err}`);+ });+ return;+ }// Always set an explicit error string when finishing as failure. The// toolkit's errorDetection (if enabled) will fill in `error` inside// finalizeRunRecord, but if it's absent we'd persist `success: false`@@ -620,8 +670,7 @@ ${prompt}`;// triggering a pointless fallback retry. (The response-file watcher above// normally catches this within ~2s; this covers the boundary case where the// file lands right at the deadline or the watcher hadn't confirmed yet.)- const salvaged = await tryReadFile(responseFilePath);- if (typeof salvaged === 'string' && salvaged.trim()) {+ if (await responseFileHasContent()) {finish({ success: true, exitCode: 0, reason: 'timeout-response-file' });return;}diff --git a/server/lib/tuiPromptRunner.test.js b/server/lib/tuiPromptRunner.test.jsindex a659a81dc3..93da195516 100644--- a/server/lib/tuiPromptRunner.test.js+++ b/server/lib/tuiPromptRunner.test.js@@ -783,6 +783,104 @@ describe('executeTuiRun', () => {}));});+ it('keeps retrying when a PTY chunk boundary splits the retry banner right after "Request timed out"', async () => {+ const provider = { id: 'claude', type: 'tui', command: 'claude' };+ const promise = executeTuiRun({ runId: 'run-split-retry', provider, prompt: 'a prompt long enough', workspacePath: TEST_WORKSPACE, timeout: 60000 });+ await flushAsync();++ const pty = ptyInstances[0];+ // Ink repaints the countdown on every tick and the tty delivers those+ // frames in sub-frame chunks, so a split inside the ~30-char window+ // between "out" and " · Retrying" is routine. Before #3715 this first+ // chunk ALONE finalized the run as exitCode 124 and burned a fallback+ // tier — killing the retry sequence the detector exists to protect.+ pty.emitData(' ⎿ Request timed out');+ await flushAsync();+ expect(pty.kill).not.toHaveBeenCalled();+ expect(runnerMocks.finalizeRunRecord).not.toHaveBeenCalled();++ pty.emitData(' · Retrying in 38s · attempt 3/10\n');+ await flushAsync();+ expect(pty.kill).not.toHaveBeenCalled();+ expect(runnerMocks.finalizeRunRecord).not.toHaveBeenCalled();++ // Retries do eventually exhaust — the genuinely terminal banner (its own+ // complete line) must still fail the run.+ pty.emitData(' ⎿ Request timed out\n');+ await promise;+ expect(runnerMocks.finalizeRunRecord).toHaveBeenCalledWith(expect.objectContaining({+ runId: 'run-split-retry',+ success: false,+ exitCode: 124,+ extras: expect.objectContaining({ completionReason: 'fallback-signal' }),+ }));+ });++ it('flushes a held terminal banner at PTY exit rather than scraping the error screen as a success', async () => {+ const provider = { id: 'claude', type: 'tui', command: 'claude' };+ const promise = executeTuiRun({ runId: 'run-exit-timeout', provider, prompt: 'a prompt long enough', workspacePath: TEST_WORKSPACE, timeout: 60000 });+ await flushAsync();++ const pty = ptyInstances[0];+ // No terminator yet, so the candidate is held rather than acted on.+ pty.emitData(' ⎿ Request timed out');+ await flushAsync();+ expect(runnerMocks.finalizeRunRecord).not.toHaveBeenCalled();++ // Claude Code exits 0 with the error screen still up. Process exit is the+ // terminator the held candidate was waiting for.+ pty.emitExit({ exitCode: 0, signal: undefined });+ await promise;+ expect(runnerMocks.finalizeRunRecord).toHaveBeenCalledWith(expect.objectContaining({+ runId: 'run-exit-timeout',+ success: false,+ exitCode: 124,+ extras: expect.objectContaining({ completionReason: 'fallback-signal' }),+ }));+ });++ it('salvages a settled response file when a fallback signal paints inside the size-stability window', async () => {+ vi.useFakeTimers({+ toFake: ['setTimeout', 'clearTimeout', 'setInterval', 'clearInterval', 'Date'],+ });+ const provider = { id: 'claude', type: 'tui', command: 'claude', tuiPromptDelayMs: 50 };+ const runId = 'run-signal-salvage';+ const promise = executeTuiRun({ runId, provider, prompt: 'write the review then finish up properly', workspacePath: TEST_WORKSPACE, timeout: 60000 });+ await flushAsync();++ const pty = ptyInstances[0];+ pty.emitData('claude code ready> ');+ await vi.advanceTimersByTimeAsync(2000); // paste → response-file watcher armed+ await vi.advanceTimersByTimeAsync(4000); // enter++ const runDir = join(runsTmpDirRef.current, runId);+ await mkdir(runDir, { recursive: true });+ await writeFile(join(runDir, 'tui-response.txt'), 'the finished review body');+ // Poll 1 only seeds the size-stability baseline — the run is NOT finalized+ // yet even though the complete answer is already on disk.+ await vi.advanceTimersByTimeAsync(1100);+ expect(runnerMocks.finalizeRunRecord).not.toHaveBeenCalled();++ // A follow-up provider request times out and paints the terminal banner+ // inside that ≥1s window. Failing here would discard the finished+ // response (resolveTuiResponseText only reads the file on success) and+ // re-run an expensive stage on a fallback provider.+ pty.emitData('\n ⎿ Request timed out\n');+ await flushAsync();+ await promise;++ expect(runnerMocks.finalizeRunRecord).toHaveBeenCalledWith(expect.objectContaining({+ runId,+ success: true,+ exitCode: 0,+ output: 'the finished review body',+ extras: expect.objectContaining({+ completionReason: 'fallback-signal-response-file',+ usedResponseFile: true,+ }),+ }));+ });+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 });