Skip to content

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

fix(cos): make claude-code-tui agent spawn reliable

Adam Eivye31ad66d1341
diff --git a/server/lib/tuiHandshake.js b/server/lib/tuiHandshake.js
index 08d67c0eb0..faee36f5b1 100644
--- a/server/lib/tuiHandshake.js
+++ b/server/lib/tuiHandshake.js
@@ -23,6 +23,12 @@ import { ensureAntigravityTuiArgs, isAntigravityCommand } from './antigravity.js
export const READY_POLL_INTERVAL_MS = 300;
export const READY_IDLE_THRESHOLD_MS = 1200;
export const PASTE_DEADLINE_MS = 10000;
+// How long to wait for claude's POSITIVE input-ready footer (createInputReadyTracker)
+// before giving up and surfacing a startup failure. Generous because a cold
+// claude start can spend many seconds on banner + MCP-server + model init
+// (still well under the 180s idle timeout). Used only on the input-ready-gated
+// path; the non-claude providers use PASTE_DEADLINE_MS.
+export const TUI_INPUT_READY_DEADLINE_MS = 45000;
// Claude Code emits `[Pasted text #N +M lines]` after committing a paste.
// Watch for the marker (or fall back after PASTE_TO_ENTER_FALLBACK_MS)
@@ -85,6 +91,69 @@ export function detectPasteMarker(strippedText) {
return countPasteMarkers(strippedText) > 0;
}
+// Positive "the launched program's input is ready to receive a bracketed paste"
+// signal, derived from the terminal's bracketed-paste-mode toggles in the RAW
+// (un-stripped) PTY stream. A program enables bracketed-paste mode (`ESC[?2004h`)
+// exactly when its input prompt is live and ready to accept a paste — which is
+// precisely the precondition for the `ESC[200~…ESC[201~` paste the spawner is
+// about to send. The launch shell already had paste mode ON at its own prompt,
+// so we must NOT treat that initial ON as the signal: only an ON that arrives
+// AFTER the shell turned it OFF (`ESC[?2004l`) to run the command is the
+// launched program (e.g. Claude Code) declaring its input ready. The spawner
+// pairs this with a liveness probe to disambiguate "claude's prompt is ready"
+// from "claude exited and the shell's prompt came back" (both re-enable paste
+// mode). This replaces the old "saw some output, then went idle" heuristic that
+// fired during a startup lull — before claude's input existed — and dumped the
+// prompt into the bare shell.
+// Bracketed-paste mode toggles in the RAW stream — the RELIABLE input-ready
+// signal. `ESC[?2004h` = ON (the program will read `ESC[200~…ESC[201~` as a
+// paste); `ESC[?2004l` = OFF (then the leading `ESC` of our paste is read as
+// Escape, which CANCELS claude's input — the intermittent "something other than
+// Enter canceled it"). claude enables paste mode exactly when its input box is
+// live, so "paste mode re-enabled after the shell turned it off to run the
+// command" means claude is ready AND the paste won't be misread.
+//
+// (We deliberately do NOT key on claude's visible footer text — `bypass
+// permissions on (shift+tab to cycle)` etc. — because claude renders it with
+// inter-glyph cursor moves, so its spaces vanish after ANSI stripping and the
+// text is not reliably matchable. Terminal-mode toggles survive intact.)
+export const BRACKETED_PASTE_MODE_PATTERN = /\x1b\[\?2004([hl])/g;
+
+// Claude Code's first-run folder-trust gate ("Is this a project you trust? →
+// 1. Yes, I trust this folder / 2. No, exit"). `--dangerously-skip-permissions`
+// does NOT bypass it, and CoS agents can start in folders claude hasn't seen.
+// Matched against the WHITESPACE-STRIPPED text (same inter-glyph-spacing caveat
+// as the footer). The spawner auto-confirms the default ("Yes, I trust").
+export const TUI_TRUST_PROMPT_PATTERN =
+ /trustthisfolder|isthisaprojectyou(?:created|trust)/i;
+
+export function createInputReadyTracker() {
+ let pasteModeOn = false; // LIVE bracketed-paste mode state from the stream
+ let sawCommandRun = false; // shell turned paste mode OFF to run the command
+ let needsTrust = false;
+ return {
+ // Ready once claude has RE-ENABLED bracketed-paste mode after the launch
+ // shell turned it off to run the command — its input box is live and a
+ // paste will be read as a paste. (The launch shell's own initial ON does
+ // not count: sawCommandRun gates on the intervening OFF.)
+ get ready() { return sawCommandRun && pasteModeOn; },
+ get needsTrust() { return needsTrust; },
+ // rawText: un-stripped chunk (paste-mode toggles live here);
+ // strippedText: ANSI-stripped chunk (the trust-gate text).
+ observe(rawText, strippedText) {
+ if (rawText) {
+ for (const m of rawText.matchAll(BRACKETED_PASTE_MODE_PATTERN)) {
+ if (m[1] === 'l') { pasteModeOn = false; sawCommandRun = true; }
+ else pasteModeOn = true;
+ }
+ }
+ if (strippedText && !needsTrust && TUI_TRUST_PROMPT_PATTERN.test(strippedText.replace(/\s+/g, ''))) {
+ needsTrust = true;
+ }
+ },
+ };
+}
+
// "The model is actively processing a submitted prompt" signal. A TUI repaints
// its banner/status line continuously even with an UNSUBMITTED prompt sitting in
// the input box, so "any PTY output after the paste" cannot distinguish real
diff --git a/server/services/agentTuiSpawning.js b/server/services/agentTuiSpawning.js
index ec0831c935..96cd5f0bdb 100644
--- a/server/services/agentTuiSpawning.js
+++ b/server/services/agentTuiSpawning.js
@@ -29,11 +29,13 @@ import {
PASTE_MARKER_POLL_MS,
countPasteMarkers,
createWorkActivityTracker,
+ createInputReadyTracker,
rendersWorkCounter,
PASTE_TO_ENTER_MIN_DELAY_MS,
PASTE_TO_ENTER_FALLBACK_MS,
scheduleSubmitEnters,
PASTE_DEADLINE_MS,
+ TUI_INPUT_READY_DEADLINE_MS,
OUTPUT_BUFFER_CAP,
OUTPUT_BUFFER_HEADROOM,
RAW_SPOOL_MAX_BYTES,
@@ -41,6 +43,7 @@ import {
applyCommandDefaults,
} from '../lib/tuiHandshake.js';
import { agentGuardEnv } from '../lib/agentGuard/index.js';
+import { execFile } from 'child_process';
// Agent-specific timing/lifecycle constants (not shared with the one-shot
// runner — agents stay alive much longer and write a sentinel file when done).
@@ -130,6 +133,10 @@ export function createAgentTuiSession({ agentId, provider, tuiConfig, cwd, onDat
label: `${provider.name} ${agentId}`,
command: tuiConfig.commandLine,
initialCommand: tuiConfig.commandLine,
+ // Wait for the shell prompt to render before injecting the CLI command —
+ // a fixed delay races a heavy interactive shell and the launched TUI can
+ // fall straight back to the prompt (see shell.js waitForPromptReady).
+ waitForPromptReady: true,
// agentGuardEnv() prepends the pm2 shim to the agent session's PATH (and
// points it at the real pm2). Spread LAST so it wins over any provider PATH.
// Only AI agent sessions get this — the user's own Shell page does not.
@@ -146,6 +153,25 @@ export function createAgentTuiSession({ agentId, provider, tuiConfig, cwd, onDat
return { sessionId, ptyProcess, pid: ptyProcess?.pid || null };
}
+// Best-effort liveness probe for the launched TUI command. The TUI runs e.g.
+// `claude` as a CHILD of a persistent PTY shell (see createShellSession writing
+// initialCommand), so when that command exits at startup the PTY itself stays
+// open — the shell just returns to its prompt — and the spawner's onExit never
+// fires. "The shell PID has no live child process" therefore means the launched
+// command has already exited. Resolves true (assume alive) when the probe can't
+// run, so a flaky/absent `ps` never blocks an otherwise-healthy paste.
+function shellHasLiveChild(shellPid) {
+ if (!shellPid) return Promise.resolve(true);
+ return new Promise((resolve) => {
+ // `-Ao ppid=` is POSIX (all processes, ppid column only, no header) and
+ // works on both macOS (BSD ps) and Linux (procps).
+ execFile('ps', ['-Ao', 'ppid='], { timeout: 2000 }, (err, stdout) => {
+ if (err) { resolve(true); return; }
+ resolve(stdout.split('\n').some((line) => parseInt(line, 10) === shellPid));
+ });
+ });
+}
+
function appendModelArgs(args, model, command) {
if (isAntigravityCommand(command)) return args;
const effectiveModel = resolveCliModel(model);
@@ -235,6 +261,11 @@ export async function spawnTuiAgent({
// fallback idle-complete path from finalizing a never-submitted prompt as
// success (issue #1229).
const workActivity = createWorkActivityTracker();
+ // Tracks claude's interactive input-readiness (footer chrome) and its first-run
+ // folder-trust gate. Gates the prompt paste for the claude TUI so we never
+ // paste into a startup banner, a trust menu, or a returned shell prompt.
+ const inputReady = createInputReadyTracker();
+ let trustAccepted = false;
let firstOutputAt = null;
let lastOutputAt = Date.now();
let lastLine = '';
@@ -557,6 +588,10 @@ export async function spawnTuiAgent({
// — as this did before #1229 — left the marker unmatchable and the fast
// path dead.
if (postPasteBuffer !== null && stripped) postPasteBuffer += stripped;
+ // Observe claude's input-readiness / folder-trust chrome (before the
+ // paste). Raw `text` carries the bracketed-paste-mode toggles; `stripped`
+ // carries the visible footer/trust text.
+ if (!promptSentAt) inputReady.observe(text, stripped);
const now = Date.now();
// Once the prompt is SUBMITTED (Enter sent — not merely pasted), watch for
// proof the model is actually working. Keying on promptSubmittedAt (not
@@ -663,9 +698,43 @@ export async function spawnTuiAgent({
// prompts won't trigger the marker). All timers are tracked so finish()
// can cancel pending writes if the agent ends mid-handshake.
const startedAt = Date.now();
- const sendPrompt = (reason) => {
+
+ // Finalize a startup failure WITHOUT pasting — surfacing whatever the CLI
+ // printed (raw.txt tail) so the real cause is visible instead of a wedged
+ // shell. Shared by the liveness guard (command exited) and the readiness cap
+ // (claude never showed its input prompt).
+ const finishStartupFailure = async (reason, summary) => {
+ if (finalized) return;
+ const raw = await readFile(rawFile, 'utf8').catch(() => '');
+ const tail = raw
+ ? stripAnsi(raw).split('\n').map((s) => s.trimEnd()).filter(Boolean).slice(-12).join('\n')
+ : '';
+ appendLine(`❌ ${summary}`);
+ await finish({
+ success: false,
+ exitCode: 1,
+ error: `${summary}${tail ? `\nCaptured output:\n${tail}` : ' No output was captured.'}`,
+ reason,
+ });
+ };
+
+ const sendPrompt = async (reason) => {
if (finalized || promptSentAt) return;
promptSentAt = Date.now();
+ // Liveness guard: the TUI command runs as a child of the persistent PTY
+ // shell, so if it exited at startup (e.g. claude failing to enter
+ // interactive mode) the PTY stays open and onExit never fires. Pasting now
+ // would dump the bracketed-paste prompt into the bare shell — the wedged
+ // `^[[200~ …` session. If the shell has no live child, the command is gone:
+ // fail loudly with whatever it printed instead of pasting into the shell.
+ if (!(await shellHasLiveChild(pid))) {
+ if (finalized) return; // a real onExit may have finalized during the probe await
+ await finishStartupFailure(
+ 'tui-exited-early',
+ `${tuiConfig.command} exited at startup before the TUI was ready, so no prompt was sent.`,
+ );
+ return;
+ }
// Start capturing post-paste output. Set BEFORE writing the paste so
// every chunk that arrives in response gets appended. Cleared the moment
// detection resolves (marker seen or fallback elapsed) so the accumulator
@@ -711,6 +780,14 @@ export async function spawnTuiAgent({
}, PASTE_MARKER_POLL_MS);
};
+ // Claude Code renders a startup banner and (in unfamiliar folders) a
+ // folder-trust gate before its input box exists, and the old "saw output then
+ // went idle" heuristic fired during those lulls — pasting the prompt into the
+ // banner / trust menu / a returned shell. For claude we instead gate on its
+ // POSITIVE input-ready footer (see createInputReadyTracker), auto-confirm the
+ // trust gate, and NEVER blind-paste: if the prompt never appears we surface a
+ // failure. Other TUI providers keep the original idle heuristic + deadline.
+ const requireInputReady = commandName === 'claude';
const promptTimer = setInterval(() => {
if (finalized || promptSentAt) {
clearInterval(promptTimer);
@@ -718,6 +795,33 @@ export async function spawnTuiAgent({
}
const now = Date.now();
const elapsed = now - startedAt;
+
+ if (requireInputReady) {
+ // Auto-confirm claude's first-run "trust this folder?" gate (default is
+ // "Yes, I trust") so claims can run in fresh worktrees. Send Enter once.
+ if (inputReady.needsTrust && !trustAccepted) {
+ trustAccepted = true;
+ shellService.writeToSession(sessionId, '\r');
+ appendLine(`📟 Auto-confirmed claude folder-trust prompt for session ${sessionId.slice(0, 8)}`);
+ return;
+ }
+ if (inputReady.ready && elapsed >= tuiConfig.promptDelayMs) {
+ sendPrompt('input-ready');
+ clearInterval(promptTimer);
+ return;
+ }
+ // Never blind-paste for claude: if the input prompt never showed within
+ // the cap, finalize a startup failure with the captured output.
+ if (elapsed >= TUI_INPUT_READY_DEADLINE_MS) {
+ clearInterval(promptTimer);
+ finishStartupFailure(
+ 'tui-not-ready',
+ `${tuiConfig.command} did not present an input prompt within ${Math.round(TUI_INPUT_READY_DEADLINE_MS / 1000)}s, so no prompt was sent.`,
+ );
+ }
+ return;
+ }
+
if (elapsed >= PASTE_DEADLINE_MS) {
sendPrompt('fallback');
clearInterval(promptTimer);
diff --git a/server/services/agentTuiSpawning.test.js b/server/services/agentTuiSpawning.test.js
index 355e7a1861..42ce972beb 100644
--- a/server/services/agentTuiSpawning.test.js
+++ b/server/services/agentTuiSpawning.test.js
@@ -122,8 +122,18 @@ vi.mock('../lib/tuiHandshake.js', async (importOriginal) => {
};
});
+// child_process.execFile is used only by the TUI liveness probe
+// (shellHasLiveChild). Default to an error callback so the probe resolves
+// "assume alive" (guard bypassed) for every test that doesn't exercise it —
+// the early-exit test below overrides this to report no child process.
+vi.mock('child_process', async (importOriginal) => {
+ const actual = await importOriginal();
+ return { ...actual, execFile: vi.fn((_file, _args, _opts, cb) => cb(new Error('not mocked'))) };
+});
+
import { existsSync } from 'fs';
import { readFile } from 'fs/promises';
+import { execFile } from 'child_process';
import { buildTuiSpawnConfig, spawnTuiAgent } from './agentTuiSpawning.js';
import * as shellService from './shell.js';
import * as agentLifecycle from './agentLifecycle.js';
@@ -426,6 +436,140 @@ describe('spawnTuiAgent runtime', () => {
);
});
+ // ── 1b. Command exited before the prompt → don't paste into the bare shell ───
+ // The TUI command (claude/codex/…) runs as a CHILD of the persistent PTY
+ // shell, so if it exits at startup the PTY stays open and onExit never fires.
+ // The ready-gate would then paste the bracketed-paste prompt into the returned
+ // shell prompt — the wedged `^[[200~ …` session. The liveness probe must catch
+ // "shell has no live child", skip the paste, and finalize failure with the
+ // command's captured output.
+ it('tui-exited-early: skips the paste and finalizes failure when the command exited before the prompt', async () => {
+ let resolveComplete;
+ const completeDone = new Promise((r) => { resolveComplete = r; });
+ vi.mocked(agentLifecycle.finalizeAgent).mockImplementation(async () => { resolveComplete(); });
+
+ // Truthy pid so the probe runs; ps reports NO process whose ppid is 4242.
+ vi.mocked(shellService.getSessionProcess).mockReturnValue({ pid: 4242 });
+ vi.mocked(execFile).mockImplementation((_file, _args, _opts, cb) => cb(null, '1\n1\n999\n'));
+ // raw.txt tail surfaced in the error.
+ vi.mocked(readFile).mockResolvedValue('Error: claude exited at startup\n');
+
+ runSpawn();
+ await flushMicrotasks();
+
+ await capturedOnData(Buffer.from('booting...\n'));
+ await flushMicrotasks();
+
+ // Open the ready-gate (promptDelay floor + idle threshold) so sendPrompt fires.
+ await vi.advanceTimersByTimeAsync(2000);
+ await flushMicrotasks();
+
+ vi.useRealTimers();
+ await completeDone;
+
+ // The bracketed-paste prompt must NOT have been written.
+ const pasteWrites = vi.mocked(shellService.writeToSession).mock.calls
+ .filter(([, data]) => typeof data === 'string' && data.includes('\x1b[200~'));
+ expect(pasteWrites).toHaveLength(0);
+
+ expect(agentLifecycle.finalizeAgent).toHaveBeenCalledWith(
+ expect.objectContaining({
+ agentId: 'agent-1',
+ success: false,
+ completionReason: 'tui-exited-early',
+ })
+ );
+ });
+
+ // ── 1c. claude waits for bracketed-paste mode (input ready) before pasting ───
+ const claudeTuiConfig = { command: 'claude', args: [], commandLine: 'claude', promptDelayMs: 100, idleTimeoutMs: 50 };
+ const pasteCount = () => vi.mocked(shellService.writeToSession).mock.calls
+ .filter(([, d]) => typeof d === 'string' && d.includes('\x1b[200~')).length;
+ // The launch shell turns bracketed-paste OFF to run the command, then claude
+ // turns it back ON when its input box is ready — that OFF→ON is "ready".
+ const PASTE_OFF = '\x1b[?2004l';
+ const PASTE_ON = '\x1b[?2004h';
+
+ it('claude input-ready: does NOT paste on the startup banner, only once paste mode is re-enabled', async () => {
+ runSpawn({ tuiConfig: claudeTuiConfig });
+ await flushMicrotasks();
+
+ // Startup banner (and the shell turning paste mode OFF to run the command).
+ await capturedOnData(Buffer.from(`${PASTE_OFF}Claude Code v2.1.186\nOpus 4.8 (1M context) with high effort\n`));
+ await flushMicrotasks();
+ await vi.advanceTimersByTimeAsync(2000);
+ await flushMicrotasks();
+ expect(pasteCount()).toBe(0); // banner / paste-mode-off is not "input ready"
+
+ // claude re-enables bracketed-paste mode → input box live, safe to paste.
+ await capturedOnData(Buffer.from(PASTE_ON));
+ await flushMicrotasks();
+ await vi.advanceTimersByTimeAsync(400);
+ await flushMicrotasks();
+ expect(pasteCount()).toBe(1);
+ });
+
+ it('claude input-ready: holds the paste while paste mode is OFF (so the paste ESC cannot cancel the input)', async () => {
+ runSpawn({ tuiConfig: claudeTuiConfig });
+ await flushMicrotasks();
+
+ // Command launched, paste mode OFF — pasting now would send a bare ESC that
+ // cancels claude's input. Gate must NOT paste.
+ await capturedOnData(Buffer.from(PASTE_OFF));
+ await flushMicrotasks();
+ await vi.advanceTimersByTimeAsync(2000);
+ await flushMicrotasks();
+ expect(pasteCount()).toBe(0);
+
+ await capturedOnData(Buffer.from(PASTE_ON));
+ await flushMicrotasks();
+ await vi.advanceTimersByTimeAsync(400);
+ await flushMicrotasks();
+ expect(pasteCount()).toBe(1);
+ });
+
+ it('claude trust gate: auto-confirms the folder-trust prompt with Enter, then pastes once ready', async () => {
+ runSpawn({ tuiConfig: claudeTuiConfig });
+ await flushMicrotasks();
+
+ await capturedOnData(Buffer.from(`${PASTE_OFF}Is this a project you trust?\n 1. Yes, I trust this folder\n 2. No, exit\n`));
+ await flushMicrotasks();
+ await vi.advanceTimersByTimeAsync(700);
+ await flushMicrotasks();
+
+ // A bare Enter was sent to confirm the default ("Yes, I trust").
+ const enters = vi.mocked(shellService.writeToSession).mock.calls.filter(([, d]) => d === '\r');
+ expect(enters.length).toBeGreaterThanOrEqual(1);
+
+ // After trust is accepted claude's input box comes up (paste mode ON) → paste.
+ await capturedOnData(Buffer.from(PASTE_ON));
+ await flushMicrotasks();
+ await vi.advanceTimersByTimeAsync(400);
+ await flushMicrotasks();
+ expect(pasteCount()).toBe(1);
+ });
+
+ it('tui-not-ready: claude that never shows an input prompt finalizes failure without pasting', async () => {
+ let resolveComplete;
+ const completeDone = new Promise((r) => { resolveComplete = r; });
+ vi.mocked(agentLifecycle.finalizeAgent).mockImplementation(async () => { resolveComplete(); });
+
+ runSpawn({ tuiConfig: claudeTuiConfig });
+ await flushMicrotasks();
+ await capturedOnData(Buffer.from('some startup noise but no input box ever appears\n'));
+ await flushMicrotasks();
+
+ // Advance past TUI_INPUT_READY_DEADLINE_MS (45s).
+ await vi.advanceTimersByTimeAsync(46000);
+ vi.useRealTimers();
+ await completeDone;
+
+ expect(pasteCount()).toBe(0);
+ expect(agentLifecycle.finalizeAgent).toHaveBeenCalledWith(
+ expect.objectContaining({ agentId: 'agent-1', success: false, completionReason: 'tui-not-ready' })
+ );
+ });
+
// ── 1a-bis. Non-counter TUI provider keeps the permissive idle-complete ──────
// The work-counter signal only exists on Claude Code / Codex. On a provider
// that never renders it (Antigravity/Gemini), absence proves nothing — so a
diff --git a/server/services/shell.js b/server/services/shell.js
index a3f43803f8..e2c4757776 100644
--- a/server/services/shell.js
+++ b/server/services/shell.js
@@ -155,7 +155,37 @@ export function createShellSession(socket, options = {}) {
releaseExternalViews(socket, sessionId);
broadcastSessionList();
if (options.initialCommand) {
- setTimeout(() => writeToSession(sessionId, `${options.initialCommand}\n`), options.initialCommandDelayMs ?? 200);
+ const sendInitial = () => writeToSession(sessionId, `${options.initialCommand}\n`);
+ if (options.waitForPromptReady) {
+ // Inject the command only once the shell has FINISHED loading. A fixed
+ // delay races a heavy interactive shell, and a prompt-marker watch is
+ // fooled by powerlevel10k's *instant prompt*, which renders (and enables
+ // bracketed-paste mode) BEFORE `.zshrc`/plugins/nvm finish — so the
+ // command runs in a half-loaded shell and the launched TUI falls straight
+ // back to the prompt. Instead, wait for the shell's startup output to go
+ // QUIET: (re)arm a settle timer on every chunk and send only once no
+ // output has arrived for `promptReadySettleMs`. Theme-agnostic; a bounded
+ // fallback guarantees we never hang if the shell never quiets.
+ let sent = false;
+ let sub = null;
+ let settleTimer = null;
+ const settleMs = options.promptReadySettleMs ?? 750;
+ const fire = () => {
+ if (sent) return;
+ sent = true;
+ clearTimeout(fallback);
+ clearTimeout(settleTimer);
+ sub?.dispose?.();
+ sendInitial();
+ };
+ sub = ptyProcess.onData(() => {
+ clearTimeout(settleTimer);
+ settleTimer = setTimeout(fire, settleMs);
+ });
+ const fallback = setTimeout(fire, options.initialCommandDelayMs ?? 8000);
+ } else {
+ setTimeout(sendInitial, options.initialCommandDelayMs ?? 200);
+ }
}
return sessionId;
}
diff --git a/server/services/shell.test.js b/server/services/shell.test.js
index f2dbb21250..b0ad95f906 100644
--- a/server/services/shell.test.js
+++ b/server/services/shell.test.js
@@ -176,6 +176,33 @@ describe('createShellSession', () => {
expect(shell.getSession(id)).toBeTruthy();
vi.useRealTimers();
});
+
+ it('waitForPromptReady: holds initialCommand until the shell startup output goes quiet', () => {
+ vi.useFakeTimers();
+ shell.createShellSession(makeSocket(), { initialCommand: 'claude', waitForPromptReady: true, promptReadySettleMs: 750, initialCommandDelayMs: 8000 });
+ const pty = ptyInstances[0];
+ // Startup output is still streaming (e.g. p10k instant prompt, then .zshrc).
+ pty.emitData('instant prompt');
+ vi.advanceTimersByTime(500);
+ pty.emitData('...plugins loading...'); // resets the settle window
+ vi.advanceTimersByTime(500);
+ expect(pty.write).not.toHaveBeenCalledWith('claude\n'); // not quiet long enough yet
+ // Output stops → after the settle window the command is sent.
+ vi.advanceTimersByTime(750);
+ expect(pty.write).toHaveBeenCalledWith('claude\n');
+ vi.useRealTimers();
+ });
+
+ it('waitForPromptReady: falls back to sending after the timeout if the shell never quiets', () => {
+ vi.useFakeTimers();
+ shell.createShellSession(makeSocket(), { initialCommand: 'claude', waitForPromptReady: true, promptReadySettleMs: 750, initialCommandDelayMs: 8000 });
+ const pty = ptyInstances[0];
+ // Continuous output every 500ms keeps resetting the settle window…
+ for (let i = 0; i < 16; i++) { pty.emitData('tick'); vi.advanceTimersByTime(500); }
+ // …but the hard fallback (8000ms) fires regardless.
+ expect(pty.write).toHaveBeenCalledWith('claude\n');
+ vi.useRealTimers();
+ });
});
describe('attachSession', () => {