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([issue-4638]): make the shell readiness probe dialect-aware
[._.]/ Adam Eivy1411aa305ac5
diff --git a/server/lib/README.md b/server/lib/README.mdindex 6c47ed877c..4b8084b3a5 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -377,6 +377,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `shellCd.js` | `buildCdCommand(path, shell)` + `detectShellFlavor(shell, platform?)` + `quoteForShell(value, flavor, position?)` — build `cd` and arbitrary command-token lines for the shell a PTY session is ACTUALLY running (`cmd.exe` → Windows-escaped double quotes, PowerShell → doubled single quotes with `&` for a quoted command token, everything else → POSIX `shellQuote`). The Shell page's "cd to app" picker used to hard-code the POSIX form, which on Windows both mis-quoted the path and silently refused to cross drives (a bare `cd` does not switch drive). Flavor comes from the shell binary name, not the platform, so git-bash on Windows still gets POSIX quoting. Renders the LINE only; the Enter byte that submits it is `SUBMIT_KEY` in `tuiHandshake.js`. || `shellExit.js` | `buildRunThenExitCommand(commandLine, shell)` — "run this CLI, then close the shell with its status", in the dialect the session speaks. An agent TUI shell exists only to host one CLI and must die with it. The POSIX `cmd; exit $?` was applied everywhere and is actively wrong off-POSIX: in PowerShell `$?` is a BOOLEAN, so `exit $?` reports success as 1 and failure as 0 (inverted) — use `$LASTEXITCODE`, pre-seeded to 1 so a command that never ran still exits non-zero; in cmd.exe `;` is an argument separator, so the CLI is handed `;`/`exit`/`$?` as arguments — use `& exit`. Verified against node-pty on Windows 11 for pwsh 7, PowerShell 5.1 and cmd.exe. || `shellQuote.js` | `shellQuote(value)` — POSIX single-quote escaping for values interpolated into shell command strings (display command lines, copy-paste blocks in agent prompts). Bare-safe tokens pass through; everything else is single-quoted. Canonical escaper — don't hand-roll. |+| `shellReadinessProbe.js` | `buildReadinessProbe(nonce, shell)` — the round-trip "can this shell actually run commands yet?" probe `createShellSession`'s `waitForPromptReady` sends and watches for, in the dialect the session speaks: POSIX `printf '%s\n' 'PORTOSRDY''<nonce>'` (unchanged), PowerShell `Write-Output ('PORTOSRDY' + '<nonce>')`, `cmd.exe` → `null` (no split-literal concatenation operator exists there, so the caller skips straight to the bounded fallback timer instead of risking an always-matching probe). The split-literal property is load-bearing in every dialect: the probe source never contains the assembled marker, so seeing it in the output can only mean the shell executed the probe. || `sidecarProcess.js` | `runSidecarProcess({bin,args,env,signal,onStage,onProcess})` + `parseSidecarResult(stdout)` — the shared Python-sidecar STAGE:/RESULT: wire-protocol runner (spawn, tail-capped stdout/stderr, per-STAGE-line callback, abort/SIGTERM → `canceled`, non-zero exit → stderr-tail reason). Used by `pipeline/musicGen.js` (all music backends) and `audioMidiTranscription.js` (MuScriptor). || `slashdoCatalog.js` | The single catalog of which bundled slashdo workflows PortOS offers as a one-click agent run — `SLASHDO_WORKFLOWS` (`{command, label, description, icon, templateName, templatePrompt?, settings, appTypes, configurable?}`), `getSlashdoWorkflow()` (the allowlist gate for `POST /api/cos/tasks/slashdo`), `SLASHDO_COMMAND_NAMES`, `slashdoWorkflowsForApp(isSwiftApp)`, `SLASHDO_APP_TYPES`, and the two run-shape postures `WORKFLOW_OWNS_ITS_OWN_GIT` (commit-shaped) / `WORKFLOW_REPORTS_NO_CODE` (report-shaped — carries `worktreeChangesExpected: false` so a filed-issue/printed-report run retains its non-code deliverable posture). Backs the Agent Operations buttons, the CoS quick templates (`taskTemplates.js`), and the route allowlist, replacing two catalogs that had drifted. Mirrored in `client/src/lib/slashdoCatalog.js` (button styling only), pinned by `slashdoCatalog.test.js`. || `slashdoInvocation.js` | Resolves how a bundled slashdo workflow is invoked on a given host CLI. `resolveSlashdoInvocation({command, args, providerId, providerCommand, leanMode})` → `{command, args, style, invocation, skillName}` for the three shapes slashdo's installer produces (`slash-namespaced` `/do:x` for Claude Code, `slash-flat` `/do-x` for OpenCode, `skill` — an Agent Skill selected by name — for codex/grok/antigravity and any unidentified provider). Plus `buildSlashdoSection(resolved, body, {bodyPath, reviewWith})` (pure renderer; the caller loads the body via `loadSlashdoFile`. Over `SLASHDO_INLINE_BUDGET_CHARS` (24,000) with a `bodyPath` it emits a filesystem pointer instead of the text — #3110), `unreachableReviewerIncludes({reviewers, usernames})` → the reviewer-variant lib includes a run can never reach (the `skipIncludes` set for `loadSlashdoFile`; defaults to pruning NOTHING for an unresolved/unrecognized reviewer set, since an over-pruned prompt is worse than a fat one), `SLASHDO_REVIEWER_INCLUDES`/`SLASHDO_REVIEWER_INCLUDE_NAMES`, `slashdoSkillName`, `isValidSlashdoCommand` (the one definition of the safe bare-command shape, also gating the Zod schemas), `agentOwnsPrWorkflow({providerType, leanMode})` — a strictly WEAKER question than typing a slash command: any local `cli`/`tui` harness that is not a lean `--bare` session drives its own commit → push → PR → review → merge (#3733), with `resolveOwnsPrWorkflow({persisted, …})` reading the value stamped on a completed agent record and falling back to the slash-command gate for pre-#3733 records; `oversizedBodyPointer(bodyPath, body)` (the shared "it is on disk, go read it" line); and `canTypeSlashCommands()` — the single predicate behind `agentPromptBuilder.js`'s completion-workflow gates (can this session TYPE `/do:pr` / `/simplify`?), which reads `resolveSlashdoStyle`'s `assumeClaudeWhenUnknown` posture because the spawners resolve a blank command to `claude`. Provider is only known at spawn time, so a task persists the BARE command name — never a rendered `/do:x` string. |diff --git a/server/lib/index.js b/server/lib/index.jsindex 204bb90c4d..fea28da36d 100644--- a/server/lib/index.js+++ b/server/lib/index.js@@ -354,6 +354,7 @@ export * from './prDisposition.js';export * from './shellCd.js';export * from './shellExit.js';export * from './shellQuote.js';+export * from './shellReadinessProbe.js';export * from './sidecarProcess.js';export * from './slashdoCatalog.js';export * from './slashdoInvocation.js';diff --git a/server/lib/shellReadinessProbe.js b/server/lib/shellReadinessProbe.jsnew file mode 100644index 0000000000..c3f4434a47--- /dev/null+++ b/server/lib/shellReadinessProbe.js@@ -0,0 +1,37 @@+/**+ * Build the round-trip "can this shell actually run commands yet?" probe for+ * the shell a PTY session is actually running (see `createShellSession`'s+ * `waitForPromptReady` in `services/shell.js`).+ *+ * The probe prints a unique nonce and the caller waits to SEE it in the PTY+ * output before injecting the real command — proof the shell is executing,+ * not just echoing keystrokes. The split-literal property is load-bearing and+ * must survive in every dialect: the probe SOURCE must never contain the+ * assembled `PORTOSRDY<nonce>` string, only its two halves as separate+ * literals, so a sighting of the assembled marker in the output can only mean+ * the shell EXECUTED the probe (not merely echoed the command line back).+ *+ * `printf` (POSIX) and `Write-Output` (PowerShell) both support string+ * concatenation from two literals, so both dialects get a real probe.+ * `cmd.exe` has no such operator — `echo` prints its argument line as typed —+ * so there is no way to keep the marker split in `cmd`'s source while still+ * producing it in the output; `null` tells the caller to skip straight to the+ * bounded fallback timer instead of risking an always-matching probe.+ */+import { detectShellFlavor } from './shellCd.js';++/**+ * @param {string} nonce - unique per-probe token (opaque; not shell-quoted, so+ * callers must keep it to a safe charset, e.g. hex)+ * @param {string} [shell] - the session's shell binary; see detectShellFlavor+ * @returns {string|null} a single command line with no trailing terminator,+ * or `null` when this dialect has no safe split-literal probe+ */+export function buildReadinessProbe(nonce, shell) {+ switch (detectShellFlavor(shell)) {+ case 'cmd': return null;+ case 'powershell': return `Write-Output ('PORTOSRDY' + '${nonce}')`;+ // Keep byte-identical to the pre-dialect-aware probe.+ default: return `printf '%s\\n' 'PORTOSRDY''${nonce}'`;+ }+}diff --git a/server/lib/shellReadinessProbe.test.js b/server/lib/shellReadinessProbe.test.jsnew file mode 100644index 0000000000..e962dc1dca--- /dev/null+++ b/server/lib/shellReadinessProbe.test.js@@ -0,0 +1,33 @@+import { describe, it, expect } from 'vitest';+import { buildReadinessProbe } from './shellReadinessProbe.js';++describe('buildReadinessProbe', () => {+ it('renders the POSIX printf probe byte-identical to the pre-dialect-aware form', () => {+ expect(buildReadinessProbe('abc123', '/bin/zsh')).toBe("printf '%s\\n' 'PORTOSRDY''abc123'");+ expect(buildReadinessProbe('abc123', '/bin/bash')).toBe("printf '%s\\n' 'PORTOSRDY''abc123'");+ });++ it('renders a split-literal Write-Output probe on PowerShell', () => {+ expect(buildReadinessProbe('abc123', 'pwsh.exe')).toBe("Write-Output ('PORTOSRDY' + 'abc123')");+ expect(buildReadinessProbe('abc123', 'powershell.exe')).toBe("Write-Output ('PORTOSRDY' + 'abc123')");+ });++ it('returns null for cmd.exe — no safe split-literal probe exists', () => {+ expect(buildReadinessProbe('abc123', 'cmd.exe')).toBeNull();+ expect(buildReadinessProbe('abc123', 'C:\\WINDOWS\\system32\\cmd.exe')).toBeNull();+ });++ it('keeps POSIX quoting for git-bash on Windows', () => {+ expect(buildReadinessProbe('abc123', 'C:\\Program Files\\Git\\bin\\bash.exe'))+ .toBe("printf '%s\\n' 'PORTOSRDY''abc123'");+ });++ it('never contains the assembled marker in its own source, in any dialect', () => {+ const marker = 'PORTOSRDYabc123';+ for (const shell of ['/bin/zsh', 'pwsh.exe', 'powershell.exe']) {+ const probe = buildReadinessProbe('abc123', shell);+ expect(probe).not.toBeNull();+ expect(probe).not.toContain(marker);+ }+ });+});diff --git a/server/services/agentTuiSpawning.js b/server/services/agentTuiSpawning.jsindex edfdbbfe3f..9375af5616 100644--- a/server/services/agentTuiSpawning.js+++ b/server/services/agentTuiSpawning.js@@ -1064,8 +1064,20 @@ export async function spawnTuiAgent({// still latches — the swallowed paste never sets promptSubmittedAt.if (isCodexSession && !promptSubmittedAt && stripped && !mcpBoot.active) mcpBoot.observe(stripped);const now = Date.now();- lastOutputAt = now;- if (firstOutputAt === null) firstOutputAt = lastOutputAt;+ // Startup-idle detection (the promptTimer's non-inputReady branch below)+ // reads lastOutputAt/firstOutputAt to decide the TUI has gone quiet and is+ // ready for the prompt paste. Gate them on commandInjected for the same+ // reason inputReady.observe is gated above: the shell-level readiness+ // probe (posix printf / PowerShell Write-Output) round-trips its own+ // marker through this same onData hook BEFORE the real CLI command is+ // injected, so counting it would seed the idle clock from probe echo+ // instead of the CLI's own output — falsely satisfying "quiet" while a+ // still-loading CLI (e.g. PowerShell's heavier startup) hasn't painted+ // anything yet, and pasting the prompt into it.+ if (commandInjected) {+ lastOutputAt = now;+ if (firstOutputAt === null) firstOutputAt = lastOutputAt;+ }recordFirstOutput('tui-pty');if (!hasStartedWorking) {diff --git a/server/services/agentTuiSpawning.test.js b/server/services/agentTuiSpawning.test.jsindex 92239d5ad8..02da3f5079 100644--- a/server/services/agentTuiSpawning.test.js+++ b/server/services/agentTuiSpawning.test.js@@ -1414,6 +1414,55 @@ describe('spawnTuiAgent runtime', () => {expect(pasteWrites()).toHaveLength(1);});+ // ── 1c2. The readiness probe's own echo must not seed the startup-idle clock ──+ // shell.js's waitForPromptReady round-trips a shell-level probe (posix printf /+ // PowerShell Write-Output) BEFORE injecting the real CLI command, and fires+ // onInitialCommandSent only once that command is actually typed in. If PTY+ // output that arrives before onInitialCommandSent counted toward+ // lastOutputAt/firstOutputAt, a quiet gap after the probe's own echo — e.g.+ // PowerShell's heavier startup, which is slower than bash — would satisfy the+ // idle-based "ready" check and paste the prompt into a still-loading CLI (codex+ // review [P1] on the dialect-aware probe, #4638).+ it('idle-detection: pre-injection PTY output does not satisfy startup-idle readiness', async () => {+ let sendInitialCommand = null;+ vi.mocked(shellService.createShellSession).mockImplementation((_socket, opts) => {+ capturedOnData = opts.onData;+ capturedOnExit = opts.onExit;+ // Do NOT fire onInitialCommandSent yet — mirrors the real shell.js+ // waitForPromptReady gap between the probe round-trip and command+ // injection, unlike the suite's default mock (which fires it immediately).+ sendInitialCommand = () => opts.onInitialCommandSent?.();+ return SESSION_ID;+ });++ runSpawn({ prompt: 'evaluate our animation prompts and generate drafts' });+ await flushMicrotasks();++ // Shell-level probe echo/noise arrives BEFORE the real command is injected.+ await capturedOnData(Buffer.from("bash-5.2$ printf '%s\\n' 'PORTOSRDY''abc123'\nPORTOSRDYabc123\n"));+ await flushMicrotasks();++ // Advance well past promptDelayMs + the idle threshold. Pre-fix, this probe+ // echo would have seeded firstOutputAt/lastOutputAt and the idle poll would+ // have fired the paste here — before the CLI command was ever typed in.+ await vi.advanceTimersByTimeAsync(2000);+ await flushMicrotasks();++ const pasteWrites = () => vi.mocked(shellService.writeToSession).mock.calls+ .filter(([id, data]) => id === SESSION_ID && data.startsWith('\x1b[200~'));+ expect(pasteWrites()).toHaveLength(0);++ // Now the real command is injected and the CLI produces its own output —+ // the idle clock should start from here and the paste should proceed.+ sendInitialCommand();+ await capturedOnData(Buffer.from('Codex booting...\n'));+ await flushMicrotasks();+ await vi.advanceTimersByTimeAsync(2000);+ await flushMicrotasks();++ expect(pasteWrites()).toHaveLength(1);+ });+// ── 1d. Codex MCP-server boot patience (incident 2026-07-10, agent-c5a26b40) ──// Codex boots the user's globally-configured MCP servers (playwright via npx,// a node_repl with startup_timeout_sec=120) on every headless spawn. Duringdiff --git a/server/services/shell.js b/server/services/shell.jsindex d5a91bf16e..d4f1f5d0fb 100644--- a/server/services/shell.js+++ b/server/services/shell.js@@ -6,6 +6,7 @@ import { scheduleSubmitEnters, SUBMIT_KEY } from '../lib/tuiHandshake.js';import { buildCdCommand } from '../lib/shellCd.js';import { resolveInteractiveShell } from '../lib/interactiveShellResolver.js';import { buildRunThenExitCommand } from '../lib/shellExit.js';+import { buildReadinessProbe } from '../lib/shellReadinessProbe.js';// Store active shell sessions (persist across socket reconnects)const shellSessions = new Map();@@ -264,24 +265,18 @@ export function createShellSession(socket, options = {}) {// 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+ // probe source (see buildReadinessProbe) 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 still POSIX-only (`printf`), unlike the `cd` and- // run-then-exit lines, which are rendered per dialect. On a Windows shell- // (PowerShell or cmd.exe) `printf` isn't a command, so the probe errors- // out, the marker never appears, and the command injects on the bounded- // fallback below — i.e. every Windows agent-TUI spawn waits the full 8s- // and then injects blind, which is exactly what the probe exists to avoid.- // Never broken, just slow and unproven. Making it dialect-aware is #4638.+ // probe into the real shell, so this is theme-agnostic. A bounded fallback+ // still injects the command if the probe never round-trips (or the dialect+ // has none — cmd.exe, see buildReadinessProbe).let sent = false;let sub = null;let exitSub = null;const nonce = uuidv4().replace(/-/g, '').slice(0, 12);const marker = `PORTOSRDY${nonce}`;- const probe = `printf '%s\\n' 'PORTOSRDY''${nonce}'`;+ const probe = buildReadinessProbe(nonce, shell);let seen = '';// Tear down every pending timer + listener. Called both on success// (fire) and when the PTY exits before the probe round-trips, so no@@ -298,11 +293,15 @@ export function createShellSession(socket, options = {}) {stop();sendInitial();};- sub = ptyProcess.onData((chunk) => {- seen += chunk;- if (seen.length > 8192) seen = seen.slice(-8192);- if (seen.includes(marker)) fire();- });+ // No probe for this dialect (cmd.exe) — skip the marker watch entirely and+ // rely on the bounded fallback below, same as a probe that never round-trips.+ if (probe) {+ sub = ptyProcess.onData((chunk) => {+ seen += chunk;+ if (seen.length > 8192) seen = seen.slice(-8192);+ if (seen.includes(marker)) fire();+ });+ }// If the shell dies before the probe round-trips, cancel the pending// writes/timers — sent stays true so the fallback can't resurrect a// send into the gone session.@@ -311,7 +310,9 @@ export function createShellSession(socket, options = {}) {// 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.- const probeTimer = setTimeout(() => { if (!sent) submitToSession(sessionId, probe); }, 50);+ const probeTimer = probe+ ? setTimeout(() => { if (!sent) submitToSession(sessionId, probe); }, 50)+ : null;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.jsindex 8d32d0800a..19bad6ed48 100644--- a/server/services/shell.test.js+++ b/server/services/shell.test.js@@ -192,7 +192,7 @@ describe('createShellSession', () => {it('waitForPromptReady: holds initialCommand until the readiness probe round-trips, and fires onInitialCommandSent', () => {vi.useFakeTimers();const onInitialCommandSent = vi.fn();- shell.createShellSession(makeSocket(), { initialCommand: 'claude', waitForPromptReady: true, initialCommandDelayMs: 8000, onInitialCommandSent });+ shell.createShellSession(makeSocket(), { shell: '/bin/zsh', initialCommand: 'claude', waitForPromptReady: true, initialCommandDelayMs: 8000, onInitialCommandSent });const pty = ptyInstances[0];// The probe is written after a short PTY-spawn settle, not immediately.expect(pty.write).not.toHaveBeenCalled();@@ -216,7 +216,7 @@ describe('createShellSession', () => {it('waitForPromptReady: injects the command on the fallback timeout if the probe never round-trips', () => {vi.useFakeTimers();- shell.createShellSession(makeSocket(), { initialCommand: 'claude', waitForPromptReady: true, initialCommandDelayMs: 8000 });+ shell.createShellSession(makeSocket(), { shell: '/bin/zsh', initialCommand: 'claude', waitForPromptReady: true, initialCommandDelayMs: 8000 });const pty = ptyInstances[0];vi.advanceTimersByTime(50); // probe written// Output streams but the assembled marker never appears.@@ -230,7 +230,7 @@ describe('createShellSession', () => {it('waitForPromptReady: if the shell exits before the probe round-trips, the fallback never injects the command', () => {vi.useFakeTimers();- shell.createShellSession(makeSocket(), { initialCommand: 'claude', waitForPromptReady: true, initialCommandDelayMs: 8000 });+ shell.createShellSession(makeSocket(), { shell: '/bin/zsh', initialCommand: 'claude', waitForPromptReady: true, initialCommandDelayMs: 8000 });const pty = ptyInstances[0];vi.advanceTimersByTime(50); // probe written// The shell dies before the marker round-trips → cancels pending timers.@@ -239,6 +239,43 @@ describe('createShellSession', () => {expect(pty.write).not.toHaveBeenCalledWith('claude\r');vi.useRealTimers();});++ it('waitForPromptReady: uses a Write-Output probe on PowerShell and round-trips it the same way', () => {+ vi.useFakeTimers();+ const onInitialCommandSent = vi.fn();+ shell.createShellSession(makeSocket(), { shell: 'pwsh.exe', initialCommand: 'claude', waitForPromptReady: true, initialCommandDelayMs: 8000, onInitialCommandSent });+ const pty = ptyInstances[0];+ expect(pty.write).not.toHaveBeenCalled();+ vi.advanceTimersByTime(50);+ const probeCall = pty.write.mock.calls.find(([d]) => /Write-Output/.test(d));+ expect(probeCall).toBeTruthy();+ const nonce = probeCall[0].match(/'PORTOSRDY' \+ '([0-9a-f]+)'/)[1];+ const marker = `PORTOSRDY${nonce}`;+ // The echoed command line (split literals) must not trip readiness.+ pty.emitData(`PS C:\\> Write-Output ('PORTOSRDY' + '${nonce}')`);+ expect(pty.write).not.toHaveBeenCalledWith('claude\r');+ expect(onInitialCommandSent).not.toHaveBeenCalled();+ pty.emitData(`${marker}\r\n`);+ expect(pty.write).toHaveBeenCalledWith('claude\r');+ expect(onInitialCommandSent).toHaveBeenCalledTimes(1);+ vi.useRealTimers();+ });++ it('waitForPromptReady: cmd.exe has no probe and relies solely on the fallback timeout', () => {+ vi.useFakeTimers();+ const onInitialCommandSent = vi.fn();+ shell.createShellSession(makeSocket(), { shell: 'cmd.exe', initialCommand: 'claude', waitForPromptReady: true, initialCommandDelayMs: 8000, onInitialCommandSent });+ const pty = ptyInstances[0];+ vi.advanceTimersByTime(50);+ // No probe is ever written — cmd has no safe split-literal marker.+ expect(pty.write).not.toHaveBeenCalled();+ vi.advanceTimersByTime(7949); // total elapsed: 7999+ expect(pty.write).not.toHaveBeenCalledWith('claude\r');+ vi.advanceTimersByTime(1); // total elapsed: 8000+ expect(pty.write).toHaveBeenCalledWith('claude\r');+ expect(onInitialCommandSent).toHaveBeenCalledTimes(1);+ vi.useRealTimers();+ });});describe('attachSession', () => {