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: dialect-aware process liveness probe for agent-TUI spawner (#4623)
[._.]/ Adam Eivydcdd427ae297
diff --git a/server/lib/README.md b/server/lib/README.mdindex 40dc1e1663..cac274f486 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -386,6 +386,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `prDisposition.js` | `resolvePrCompletion(metadata)` resolves the explicit `review-then-merge` / `merge-on-green` / `leave-open` policy, with legacy `reviewLoop` fallback; `leavesPrForHuman(task)` + `PR_STAYS_OPEN_TASK_TYPES` keep JIRA hand-offs open. Shared by the agent prompt builder and `agentWorktreeCleanup` so both halves agree. `resolvePrCreation({taskOpenPR, agentOwnsPr, prClaimVerified})` → a `PR_CREATION` tri-state (`never` / `if-missing` / `always`) naming who opens the change request for a completing worktree agent, so the runner, TUI, and direct-CLI completion paths cannot drift into double-firing `gh pr create`. || `shellCd.js` | `buildCdCommand(path, shell)` + `formatShellCommandLine(command, args, 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. `formatShellCommandLine` joins a command + argv into one quoted line and is shared by `agentTuiSpawning.js#buildTuiSpawnConfig` and the AI Providers page's "Launch in Shell" deep link, so a hand-launched TUI provider is quoted exactly the way the CoS runner would quote it. 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. |+| `shellLivenessProbe.js` | `buildLivenessProbeCommand(shellPid, shell, platform?)` + `parseLivenessProbeOutput(stdout, shellPid, shell, platform?)` + `shellHasLiveChild(shellPid, opts?)` — dialect- and platform-aware process-liveness probe for a launched TUI command in a persistent PTY shell. POSIX (`ps -Ao ppid=`) / Windows (`Get-CimInstance Win32_Process -Filter "ParentProcessId = <pid>"` via PowerShell). Resolves true (assume alive) when the probe fails or cannot run. || `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). |diff --git a/server/lib/index.js b/server/lib/index.jsindex 9d053a91ae..eb0fd6ab3f 100644--- a/server/lib/index.js+++ b/server/lib/index.js@@ -363,6 +363,7 @@ export * from './openapiSpec.js';export * from './prDisposition.js';export * from './shellCd.js';export * from './shellExit.js';+export * from './shellLivenessProbe.js';export * from './shellQuote.js';export * from './shellReadinessProbe.js';export * from './sidecarProcess.js';diff --git a/server/lib/shellLivenessProbe.js b/server/lib/shellLivenessProbe.jsnew file mode 100644index 0000000000..91882956be--- /dev/null+++ b/server/lib/shellLivenessProbe.js@@ -0,0 +1,107 @@+/**+ * Build and run the process-liveness probe for a launched TUI command in a PTY+ * session.+ *+ * The TUI runs as a CHILD of a persistent PTY shell (e.g. `claude` spawned inside+ * `zsh` or `cmd.exe`). When that command exits early during startup (bad config,+ * command not found, auth error), the PTY itself stays open — the shell returns to+ * its prompt, and onExit never fires.+ *+ * "The shell PID has no live child process" means the launched command has+ * already died. In that case, the spawner skips pasting the prompt into the bare+ * shell prompt and finalizes failure early.+ *+ * The probe is dialect- and platform-aware:+ * • POSIX (macOS/Linux / bash): `ps -Ao ppid=` (lists parent PIDs)+ * • Windows (cmd.exe / PowerShell): `powershell -NoProfile -NonInteractive -Command ...`+ * using `Get-CimInstance Win32_Process` filtered by ParentProcessId.+ *+ * Resolves true (assume alive) if the probe fails or cannot run, so an environment+ * glitch never blocks an otherwise-healthy run.+ */++import { detectShellFlavor } from './shellCd.js';+import { execFile } from './childProcess.js';++/**+ * Build the file + argv for probing children of `shellPid`.+ *+ * @param {number} shellPid - PID of the hosting shell process+ * @param {string} [shell] - the session's shell binary; see detectShellFlavor+ * @param {string} [platform=process.platform] - OS platform+ * @returns {{ file: string, args: string[] }}+ */+export function buildLivenessProbeCommand(shellPid, shell, platform = process.platform) {+ const flavor = detectShellFlavor(shell, platform);+ switch (flavor) {+ case 'cmd':+ case 'powershell':+ return {+ file: 'powershell',+ args: [+ '-NoProfile',+ '-NonInteractive',+ '-Command',+ `Get-CimInstance Win32_Process -Filter "ParentProcessId = ${shellPid}" | Select-Object -ExpandProperty ProcessId`,+ ],+ };+ default:+ return {+ file: 'ps',+ args: ['-Ao', 'ppid='],+ };+ }+}++/**+ * Parse the output of the liveness probe.+ *+ * @param {string} stdout - raw stdout from the probe command+ * @param {number} shellPid - PID of the hosting shell process+ * @param {string} [shell] - the session's shell binary+ * @param {string} [platform=process.platform] - OS platform+ * @returns {boolean} true if child process(es) were found+ */+export function parseLivenessProbeOutput(stdout, shellPid, shell, platform = process.platform) {+ if (!stdout) return false;+ const flavor = detectShellFlavor(shell, platform);+ switch (flavor) {+ case 'cmd':+ case 'powershell':+ return String(stdout)+ .split('\n')+ .some((line) => {+ const num = parseInt(line.trim(), 10);+ return Number.isFinite(num) && num > 0;+ });+ default:+ return String(stdout)+ .split('\n')+ .some((line) => {+ const num = parseInt(line.trim(), 10);+ return Number.isFinite(num) && num === shellPid;+ });+ }+}++/**+ * Best-effort check if `shellPid` currently has any live child process.+ * Resolves `true` (assume alive) on error or missing PID.+ *+ * @param {number} shellPid+ * @param {{ shell?: string, platform?: string, execFileFn?: typeof execFile }} [options]+ * @returns {Promise<boolean>}+ */+export function shellHasLiveChild(shellPid, { shell, platform = process.platform, execFileFn = execFile } = {}) {+ if (!shellPid) return Promise.resolve(true);+ const { file, args } = buildLivenessProbeCommand(shellPid, shell, platform);+ return new Promise((resolve) => {+ execFileFn(file, args, { timeout: 2000 }, (err, stdout) => {+ if (err) {+ resolve(true);+ return;+ }+ resolve(parseLivenessProbeOutput(stdout, shellPid, shell, platform));+ });+ });+}diff --git a/server/lib/shellLivenessProbe.test.js b/server/lib/shellLivenessProbe.test.jsnew file mode 100644index 0000000000..6b5f7b4a04--- /dev/null+++ b/server/lib/shellLivenessProbe.test.js@@ -0,0 +1,128 @@+import { describe, it, expect, vi } from 'vitest';+import {+ buildLivenessProbeCommand,+ parseLivenessProbeOutput,+ shellHasLiveChild,+} from './shellLivenessProbe.js';++describe('buildLivenessProbeCommand', () => {+ it('builds a PowerShell Get-CimInstance query for cmd.exe', () => {+ const probe = buildLivenessProbeCommand(1234, 'C:\\WINDOWS\\system32\\cmd.exe');+ expect(probe.file).toBe('powershell');+ expect(probe.args).toEqual([+ '-NoProfile',+ '-NonInteractive',+ '-Command',+ 'Get-CimInstance Win32_Process -Filter "ParentProcessId = 1234" | Select-Object -ExpandProperty ProcessId',+ ]);+ });++ it('builds a PowerShell Get-CimInstance query for powershell.exe / pwsh', () => {+ const probe = buildLivenessProbeCommand(5678, 'pwsh.exe');+ expect(probe.file).toBe('powershell');+ expect(probe.args[3]).toContain('ParentProcessId = 5678');+ });++ it('builds a POSIX ps command for POSIX shells', () => {+ const probe = buildLivenessProbeCommand(1234, '/bin/zsh');+ expect(probe).toEqual({+ file: 'ps',+ args: ['-Ao', 'ppid='],+ });+ });++ it('keeps POSIX ps command for git-bash on Windows', () => {+ const probe = buildLivenessProbeCommand(1234, 'C:\\Program Files\\Git\\bin\\bash.exe', 'win32');+ expect(probe).toEqual({+ file: 'ps',+ args: ['-Ao', 'ppid='],+ });+ });++ it('falls back to platform default when no shell is recorded', () => {+ const winProbe = buildLivenessProbeCommand(1234, undefined, 'win32');+ expect(winProbe.file).toBe('powershell');++ const posixProbe = buildLivenessProbeCommand(1234, undefined, 'darwin');+ expect(posixProbe.file).toBe('ps');+ });+});++describe('parseLivenessProbeOutput', () => {+ it('parses POSIX ps output matching the shell pid', () => {+ expect(parseLivenessProbeOutput('1\n1\n1234\n999', 1234, '/bin/zsh')).toBe(true);+ expect(parseLivenessProbeOutput('1\n1\n999', 1234, '/bin/zsh')).toBe(false);+ });++ it('parses Windows powershell output returning child pids', () => {+ expect(parseLivenessProbeOutput('5678\n', 1234, 'cmd.exe')).toBe(true);+ expect(parseLivenessProbeOutput('5678\n9012\n', 1234, 'powershell.exe')).toBe(true);+ expect(parseLivenessProbeOutput('', 1234, 'cmd.exe')).toBe(false);+ expect(parseLivenessProbeOutput(' \n', 1234, 'cmd.exe')).toBe(false);+ });++ it('returns false for empty stdout on all flavors', () => {+ expect(parseLivenessProbeOutput('', 1234, '/bin/zsh')).toBe(false);+ expect(parseLivenessProbeOutput(null, 1234, '/bin/zsh')).toBe(false);+ expect(parseLivenessProbeOutput('', 1234, 'cmd.exe')).toBe(false);+ });+});++describe('shellHasLiveChild', () => {+ it('resolves true immediately if shellPid is missing or 0', async () => {+ expect(await shellHasLiveChild(null)).toBe(true);+ expect(await shellHasLiveChild(0)).toBe(true);+ expect(await shellHasLiveChild(undefined)).toBe(true);+ });++ it('resolves true (fails open) when the probe command errors', async () => {+ const mockExec = vi.fn((_file, _args, _opts, cb) => cb(new Error('command failed')));+ const result = await shellHasLiveChild(1234, {+ shell: '/bin/zsh',+ execFileFn: mockExec,+ });+ expect(result).toBe(true);+ });++ it('resolves true when POSIX ps detects a live child process', async () => {+ const mockExec = vi.fn((_file, _args, _opts, cb) => cb(null, '1\n1234\n999\n'));+ const result = await shellHasLiveChild(1234, {+ shell: '/bin/zsh',+ execFileFn: mockExec,+ });+ expect(result).toBe(true);+ });++ it('resolves false when POSIX ps detects no child process', async () => {+ const mockExec = vi.fn((_file, _args, _opts, cb) => cb(null, '1\n999\n'));+ const result = await shellHasLiveChild(1234, {+ shell: '/bin/zsh',+ execFileFn: mockExec,+ });+ expect(result).toBe(false);+ });++ it('resolves true when Windows probe returns child processes', async () => {+ const mockExec = vi.fn((file, args, _opts, cb) => {+ expect(file).toBe('powershell');+ cb(null, '4567\n');+ });+ const result = await shellHasLiveChild(1234, {+ shell: 'cmd.exe',+ execFileFn: mockExec,+ });+ expect(result).toBe(true);+ });++ it('resolves false when Windows probe returns empty stdout', async () => {+ const mockExec = vi.fn((file, args, _opts, cb) => {+ expect(file).toBe('powershell');+ cb(null, '\n');+ });+ const result = await shellHasLiveChild(1234, {+ shell: 'cmd.exe',+ execFileFn: mockExec,+ });+ expect(result).toBe(false);+ });+});diff --git a/server/services/agentTuiSpawning.js b/server/services/agentTuiSpawning.jsindex bcca46080a..7ca3507f4b 100644--- a/server/services/agentTuiSpawning.js+++ b/server/services/agentTuiSpawning.js@@ -66,7 +66,7 @@ import { agentGuardEnv } from '../lib/agentGuard/index.js';import { composeProviderEnv } from '../lib/cliChildEnv.js';import { ensureOllamaAgentContext } from './ollamaAgentContext.js';import { isOllamaBackedProvider } from './providers.js';-import { execFile } from '../lib/childProcess.js';+import { shellHasLiveChild } from '../lib/shellLivenessProbe.js';import { appendRunEvent } from './agentRunEventLog.js';// Agent-specific timing/lifecycle constants (not shared with the one-shot@@ -184,25 +184,6 @@ export async function createAgentTuiSession({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));- });- });-}-export function buildTuiSpawnConfig(provider, model, {systemPromptFile = null,effort = null,@@ -228,6 +209,7 @@ export function buildTuiSpawnConfig(provider, model, {command,args,commandLine,+ shell,promptDelayMs: provider?.tuiPromptDelayMs || DEFAULT_TUI_PROMPT_DELAY_MS};}@@ -341,7 +323,7 @@ function createPasteRetryController({// this pid have a live child?" is the wrong question (claude may have zero// children at paste time) and a TUI exit kills the PTY, firing onExit. Skip// the probe there.- if (!useDurableRunner && !(await shellHasLiveChild(pid))) {+ if (!useDurableRunner && !(await shellHasLiveChild(pid, { shell: tuiConfig?.shell }))) {if (isFinalized()) return; // a real onExit may have finalized during the probe awaitawait finishStartupFailure('tui-exited-early',diff --git a/server/services/agentTuiSpawning.test.js b/server/services/agentTuiSpawning.test.jsindex 02da3f5079..2a0ac96c5c 100644--- a/server/services/agentTuiSpawning.test.js+++ b/server/services/agentTuiSpawning.test.js@@ -365,6 +365,7 @@ describe('agent TUI spawning', () => {args: ['--append-system-prompt-file', "I:\\input folder\\it's.md"],};+ expect(buildTuiSpawnConfig(provider, null, { shell: '/bin/zsh' }).shell).toBe('/bin/zsh');expect(buildTuiSpawnConfig(provider, null, { shell: '/bin/zsh' }).commandLine).toBe("'C:\\Program Files\\Claude\\claude.cmd' --append-system-prompt-file 'I:\\input folder\\it'\\''s.md'");expect(buildTuiSpawnConfig(provider, null, { shell: 'pwsh.exe' }).commandLine)