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(tui): prove shell readiness with a round-trip probe before injecting the CLI command

Adam Eivyc8b3fa2a28a4
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index fa88a554f8..5a004b257f 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -36,7 +36,7 @@
## Fixed
-- **Claude Code TUI agents now reliably wait for the input prompt before sending their task (and no longer wedge the shell on startup hiccups).** TUI-provider CoS agents (e.g. `claude-code-tui`) run their CLI as a *child* of a persistent PTY shell, and the old prompt-delivery gate fired on a crude "saw output, then went idle" heuristic. During Claude Code's startup that lull happens *before* the input box exists — and on a folder it hasn't seen, claude shows a **"trust this folder?" gate** that `--dangerously-skip-permissions` does not bypass (common because agents start in fresh worktrees). The gate would paste the task into the banner / trust menu, or — if claude had already exited — into the returned shell prompt, leaving a frozen, un-typeable session showing a literal `^[[200~ …` and a silently-failed run. The spawner now (1) **waits for the shell to finish loading** before injecting the CLI command — a fixed 200 ms delay raced a heavy interactive shell (powerlevel10k / async plugins / nvm-PATH setup), so the command ran before the env was ready and the launched TUI fell straight back to the prompt. It now waits for the shell's startup output to go QUIET (a settle window re-armed on each chunk, with a bounded fallback) rather than watching for a prompt marker — because powerlevel10k's *instant prompt* renders a fake-ready prompt before `.zshrc` finishes, which a marker watch would fire on too early, (2) gates the paste on claude **re-enabling bracketed-paste mode** (`ESC[?2004h`, after the shell turned it off to run the command) as the input-ready signal — this is what makes the paste's leading `ESC` read as a paste rather than as Escape (which cancels claude's input — the intermittent "something other than Enter canceled it" failure); the visible footer text (`bypass permissions on (shift+tab to cycle)`) is deliberately NOT used because claude renders it with inter-glyph cursor moves that strip its spaces after ANSI-stripping, making it unmatchable, (3) **auto-confirms the folder-trust prompt** (Enter on the default "Yes, I trust") so claims run in fresh worktrees, (4) probes that the CLI is still a live child of the shell before pasting, and (5) **never blind-pastes** — if the input prompt never appears within 45 s (or the CLI exited), it finalizes the run as a failure carrying the CLI's captured output (`tui-not-ready` / `tui-exited-early`) instead of dumping into the shell. Non-claude TUI providers keep their existing handshake. (`server/services/agentTuiSpawning.js`, `server/lib/tuiHandshake.js`, `server/services/shell.js`)
+- **Claude Code TUI agents now reliably wait for the input prompt before sending their task (and no longer wedge the shell on startup hiccups).** TUI-provider CoS agents (e.g. `claude-code-tui`) run their CLI as a *child* of a persistent PTY shell, and the old prompt-delivery gate fired on a crude "saw output, then went idle" heuristic. During Claude Code's startup that lull happens *before* the input box exists — and on a folder it hasn't seen, claude shows a **"trust this folder?" gate** that `--dangerously-skip-permissions` does not bypass (common because agents start in fresh worktrees). The gate would paste the task into the banner / trust menu, or — if claude had already exited — into the returned shell prompt, leaving a frozen, un-typeable session showing a literal `^[[200~ …` and a silently-failed run. The spawner now (1) **waits until the shell can actually run commands** before injecting the CLI command — a fixed 200 ms delay raced a heavy interactive shell (powerlevel10k / async plugins / nvm-PATH setup), so the command ran before the env was ready and the launched TUI fell straight back to the prompt. Heuristic timing watches (a prompt-marker, or settle-on-output-quiet) are *both* fooled by powerlevel10k's *instant prompt* (it renders a fake-ready prompt — and enables bracketed-paste mode — before `.zshrc` finishes) and by slow mid-load quiet gaps (nvm/plugins) that trip a settle timer just as easily, sending the command into a half-loaded shell where the instant-prompt→real-prompt redraw swallows it (the command sits echoed-but-unexecuted at a bare prompt — the intermittent wedge). It now **proves the shell is executing commands with a round-trip probe**: it prints a unique nonce and waits to *see that nonce in the output* before injecting the command. The nonce is split in the probe source (`'PORTOSRDY' '<nonce>'`) so the command echo never contains the assembled string — only the executed output matches — and instant-prompt keystroke buffering replays the probe into the real shell, so the gate is theme- and shell-agnostic with a bounded fallback if the probe never round-trips, (2) gates the paste on claude **re-enabling bracketed-paste mode** (`ESC[?2004h`, after the shell turned it off to run the command) as the input-ready signal — this is what makes the paste's leading `ESC` read as a paste rather than as Escape (which cancels claude's input — the intermittent "something other than Enter canceled it" failure); the visible footer text (`bypass permissions on (shift+tab to cycle)`) is deliberately NOT used because claude renders it with inter-glyph cursor moves that strip its spaces after ANSI-stripping, making it unmatchable, (3) **auto-confirms the folder-trust prompt** (Enter on the default "Yes, I trust") so claims run in fresh worktrees, (4) probes that the CLI is still a live child of the shell before pasting, and (5) **never blind-pastes** — if the input prompt never appears within 45 s (or the CLI exited), it finalizes the run as a failure carrying the CLI's captured output (`tui-not-ready` / `tui-exited-early`) instead of dumping into the shell. Non-claude TUI providers keep their existing handshake. (`server/services/agentTuiSpawning.js`, `server/lib/tuiHandshake.js`, `server/services/shell.js`)
- **AudioLDM2 music generation no longer crashes on current transformers.** Rendering with the AudioLDM2 engine failed mid-generation with `AttributeError: 'GPT2Model' object has no attribute '_update_model_kwargs_for_generation'`. AudioLDM2's internal language model is a bare `GPT2Model` (the pipeline reads its hidden states), and diffusers' `generate_language_model` drives it by hand using generation helpers that used to live on every `PreTrainedModel` — but transformers ≥4.50 decoupled `GenerationMixin`, so non-generative base models like `GPT2Model` no longer carry them, leaving diffusers calling a method that no longer exists. The AudioLDM2 sidecar now re-binds the missing helpers (`_update_model_kwargs_for_generation`, `_get_initial_cache_position`) from `GenerationMixin` onto the language model after loading the pipeline — keeping the runtime on a current transformers instead of pinning an EOL release, and a no-op on older transformers where the methods are already present. (`scripts/generate_audioldm2.py`)
- **Client test suite no longer floods CI with React "not wrapped in act(...)" warnings.** Across eight component/page suites, state updates were being driven outside `act()` — hand-fired mock-EventSource frames (`emit`/`fail`), raw DOM `.blur()` calls, manually-invoked tracker callbacks, and resolved in-flight gates whose follow-up `setState` landed after the test body returned (plus a few synchronous tests whose mount-time fetches resolved late). These surfaced only under CI's verbose reporter (the default reporter hides console output), so they were invisible locally. Each driving call is now wrapped in `act()` (or switched to `fireEvent`, which wraps internally), and synchronous tests that mount components with async effects now flush inside `act()`. The full client suite (2497 tests) runs clean with zero act warnings. (`PipelineManuscriptEditor`, `Layout`, `WidgetSuggestions`, `ApiAccessTab`, `PitchTuner`, `SongTraining`, `AudioStage`, `LocalLlmPlayground` test suites)
- **Deleting a generated image or video now asks for confirmation.** The trash button on image/video preview cards (the Image Gen page's recent-renders strip and the Media History grid) deleted the asset immediately on a single click, with no undo. It now arms an inline confirm row ("Delete this image?" / "Delete this video?" with Delete + Cancel) so an accidental click can't wipe a render. Fixed once in the shared `MediaCard` component, so both surfaces are covered. (`client/src/components/media/MediaCard.jsx`)
diff --git a/server/services/agentTuiSpawning.js b/server/services/agentTuiSpawning.js
index ff5748bda7..1a31a72754 100644
--- a/server/services/agentTuiSpawning.js
+++ b/server/services/agentTuiSpawning.js
@@ -125,7 +125,7 @@ function shellQuote(value) {
* to create the session, `sessionId` is null and the caller is expected
* to bail out via its `finish` path.
*/
-export function createAgentTuiSession({ agentId, provider, tuiConfig, cwd, onData, onExit }) {
+export function createAgentTuiSession({ agentId, provider, tuiConfig, cwd, onData, onExit, onInitialCommandSent }) {
const sessionId = shellService.createShellSession(null, {
cwd,
kind: 'agent-tui',
@@ -133,10 +133,15 @@ 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).
+ // Wait until the shell can actually RUN commands before injecting the CLI
+ // command — a fixed delay races a heavy interactive shell and the launched
+ // TUI can fall straight back to a half-loaded prompt (see shell.js
+ // waitForPromptReady, which proves readiness with a round-trip probe).
waitForPromptReady: true,
+ // Fires when the CLI command is actually injected. We start observing
+ // claude's input-readiness only after this so the readiness probe's own
+ // shell activity can't prematurely open the paste gate.
+ onInitialCommandSent,
// 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.
@@ -266,6 +271,13 @@ export async function spawnTuiAgent({
// paste into a startup banner, a trust menu, or a returned shell prompt.
const inputReady = createInputReadyTracker();
let trustAccepted = false;
+ // True once shell.js actually injects the `claude` command (after its
+ // round-trip readiness probe). The probe runs its OWN shell command first,
+ // which toggles bracketed-paste mode and would otherwise advance the
+ // input-ready tracker (sawCommandRun + pasteModeOn) while still at the bare
+ // shell prompt — pasting the prompt into claude's startup banner. Gating
+ // observation on this discards every pre-command toggle.
+ let commandInjected = false;
let firstOutputAt = null;
let lastOutputAt = Date.now();
let lastLine = '';
@@ -590,8 +602,10 @@ export async function spawnTuiAgent({
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);
+ // carries the visible footer/trust text. Only AFTER the CLI command is
+ // injected — earlier toggles belong to shell startup and the readiness
+ // probe, not to claude.
+ if (!promptSentAt && commandInjected) 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
@@ -667,6 +681,7 @@ export async function spawnTuiAgent({
cwd,
onData: handleData,
onExit: handleExit,
+ onInitialCommandSent: () => { commandInjected = true; },
});
sessionId = session.sessionId;
diff --git a/server/services/agentTuiSpawning.test.js b/server/services/agentTuiSpawning.test.js
index 42ce972beb..c1e6a609c5 100644
--- a/server/services/agentTuiSpawning.test.js
+++ b/server/services/agentTuiSpawning.test.js
@@ -304,10 +304,15 @@ describe('spawnTuiAgent runtime', () => {
// this same spy to assert the warn fired.
warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});
- // Default createShellSession captures callbacks and returns a valid session id
+ // Default createShellSession captures callbacks and returns a valid session id.
+ // Real shell.js fires onInitialCommandSent when it injects the CLI command
+ // (after its round-trip readiness probe); the claude input-ready gate only
+ // observes paste-mode toggles AFTER that fires, so invoke it here to mirror
+ // the real flow (otherwise commandInjected stays false and no paste ever gates).
vi.mocked(shellService.createShellSession).mockImplementation((_socket, opts) => {
capturedOnData = opts.onData;
capturedOnExit = opts.onExit;
+ opts.onInitialCommandSent?.();
return SESSION_ID;
});
diff --git a/server/services/shell.js b/server/services/shell.js
index e2c4757776..c1d88f85fc 100644
--- a/server/services/shell.js
+++ b/server/services/shell.js
@@ -155,33 +155,59 @@ export function createShellSession(socket, options = {}) {
releaseExternalViews(socket, sessionId);
broadcastSessionList();
if (options.initialCommand) {
- const sendInitial = () => writeToSession(sessionId, `${options.initialCommand}\n`);
+ // onInitialCommandSent fires at the exact moment the command is injected,
+ // regardless of which branch sent it. The agent-TUI spawner uses this to
+ // start observing claude's input-readiness ONLY after the real command is
+ // in flight — so the readiness probe's own shell activity (below) can't
+ // prematurely satisfy its bracketed-paste gate.
+ const sendInitial = () => {
+ options.onInitialCommandSent?.();
+ 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.
+ // Inject the command only once the shell can ACTUALLY run commands. A fixed
+ // delay races a heavy interactive shell; a prompt-marker / settle-on-quiet
+ // watch is fooled by powerlevel10k's *instant prompt*, which renders (and
+ // enables bracketed-paste mode) BEFORE `.zshrc`/plugins/nvm finish — and a
+ // slow mid-load quiet gap (nvm/plugins) trips a settle timer just as
+ // easily, sending the command into a half-loaded shell where it's swallowed
+ // when the real prompt redraws (the command sits echoed but unexecuted —
+ // exactly the wedged `claude …` at a bare prompt users hit). Instead, PROVE
+ // the shell is executing commands with a round-trip probe: print a unique
+ // nonce and wait until we SEE it in the OUTPUT. The nonce is split in the
+ // probe source (`'PORTOSRDY' '<nonce>'`) so the command ECHO never contains
+ // the assembled string — only the executed output matches, so a single
+ // sighting is unambiguous. Instant-prompt keystroke buffering replays the
+ // probe into the real shell, so this is theme- and shell-agnostic. A
+ // bounded fallback still injects the command if the probe never round-trips.
+ // NOTE: the probe is POSIX (`printf`). The only caller of waitForPromptReady
+ // is the agent-TUI path, which is developer-machine (mac/linux) only; on a
+ // Windows cmd.exe shell `printf` no-ops and the command simply injects on the
+ // bounded fallback below (slower, never broken). A Windows port would need a
+ // platform-aware probe.
let sent = false;
let sub = null;
- let settleTimer = null;
- const settleMs = options.promptReadySettleMs ?? 750;
+ const nonce = uuidv4().replace(/-/g, '').slice(0, 12);
+ const marker = `PORTOSRDY${nonce}`;
+ const probe = `printf '%s\\n' 'PORTOSRDY''${nonce}'\n`;
+ let seen = '';
const fire = () => {
if (sent) return;
sent = true;
clearTimeout(fallback);
- clearTimeout(settleTimer);
sub?.dispose?.();
sendInitial();
};
- sub = ptyProcess.onData(() => {
- clearTimeout(settleTimer);
- settleTimer = setTimeout(fire, settleMs);
+ sub = ptyProcess.onData((chunk) => {
+ seen += chunk;
+ if (seen.length > 8192) seen = seen.slice(-8192);
+ if (seen.includes(marker)) fire();
});
+ // Give the freshly-spawned PTY a tick to come up, then send the probe.
+ // Writing earlier is harmless (zsh's line editor / p10k instant-prompt
+ // buffer holds it until the prompt is live and replays it), but a small
+ // delay avoids racing node-pty's own spawn handshake.
+ setTimeout(() => { if (!sent) writeToSession(sessionId, probe); }, 50);
const fallback = setTimeout(fire, options.initialCommandDelayMs ?? 8000);
} else {
setTimeout(sendInitial, options.initialCommandDelayMs ?? 200);
diff --git a/server/services/shell.test.js b/server/services/shell.test.js
index b0ad95f906..d92c2362b1 100644
--- a/server/services/shell.test.js
+++ b/server/services/shell.test.js
@@ -177,29 +177,41 @@ describe('createShellSession', () => {
vi.useRealTimers();
});
- it('waitForPromptReady: holds initialCommand until the shell startup output goes quiet', () => {
+ it('waitForPromptReady: holds initialCommand until the readiness probe round-trips, and fires onInitialCommandSent', () => {
vi.useFakeTimers();
- shell.createShellSession(makeSocket(), { initialCommand: 'claude', waitForPromptReady: true, promptReadySettleMs: 750, initialCommandDelayMs: 8000 });
+ const onInitialCommandSent = vi.fn();
+ shell.createShellSession(makeSocket(), { initialCommand: 'claude', waitForPromptReady: true, initialCommandDelayMs: 8000, onInitialCommandSent });
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);
+ // The probe is written after a short PTY-spawn settle, not immediately.
+ expect(pty.write).not.toHaveBeenCalled();
+ vi.advanceTimersByTime(50);
+ const probeCall = pty.write.mock.calls.find(([d]) => /printf/.test(d));
+ expect(probeCall).toBeTruthy();
+ const nonce = probeCall[0].match(/PORTOSRDY''([0-9a-f]+)'/)[1];
+ const marker = `PORTOSRDY${nonce}`;
+ // Startup noise and the ECHO of the probe command (split marker, so the
+ // assembled string never appears contiguously) must NOT trip readiness.
+ pty.emitData('instant prompt rendering…');
+ pty.emitData(`% printf '%s\\n' 'PORTOSRDY''${nonce}'`);
+ expect(pty.write).not.toHaveBeenCalledWith('claude\n');
+ expect(onInitialCommandSent).not.toHaveBeenCalled();
+ // The assembled marker appears in the OUTPUT → shell proven, command injected.
+ pty.emitData(`${marker}\n`);
expect(pty.write).toHaveBeenCalledWith('claude\n');
+ expect(onInitialCommandSent).toHaveBeenCalledTimes(1);
vi.useRealTimers();
});
- it('waitForPromptReady: falls back to sending after the timeout if the shell never quiets', () => {
+ it('waitForPromptReady: injects the command on the fallback timeout if the probe never round-trips', () => {
vi.useFakeTimers();
- shell.createShellSession(makeSocket(), { initialCommand: 'claude', waitForPromptReady: true, promptReadySettleMs: 750, initialCommandDelayMs: 8000 });
+ shell.createShellSession(makeSocket(), { initialCommand: 'claude', waitForPromptReady: true, 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.
+ vi.advanceTimersByTime(50); // probe written
+ // Output streams but the assembled marker never appears.
+ for (let i = 0; i < 10; i++) { pty.emitData('tick'); vi.advanceTimersByTime(500); }
+ expect(pty.write).not.toHaveBeenCalledWith('claude\n');
+ // …but the hard fallback (8000ms from creation) injects the command regardless.
+ vi.advanceTimersByTime(8000);
expect(pty.write).toHaveBeenCalledWith('claude\n');
vi.useRealTimers();
});