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: quote agent TUI commands for their shell dialect (#4642)

Adam Eivya7f401ddebcc
diff --git a/server/lib/README.md b/server/lib/README.md
index 860f69be25..5044676a78 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -374,7 +374,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `objects.js` | Object utilities — `deepMerge` (recursive merge w/ array replacement), `isPlainObject` (non-null, non-array `object` guard for JSON / LLM payloads), `POLLUTING_KEYS` (shared `__proto__`/`constructor`/`prototype` denylist for sanitizers), `canonicalStringify` (recursive sorted-key JSON serialization for cross-machine content hashing), `isEmptyScalar` (true for null/undefined/whitespace-string/empty-array — merge gap-fill gate). |
| `openapiSpec.js` | `buildOpenApiSpec(settings, { baseUrl, version })` — builds an OpenAPI 3.1 document for the currently-exposed public APIs from `apiRegistry`, reusing route Zod schemas via `z.toJSONSchema`. Exposed+`requireAuth` operations get a `security` requirement; passwordless ones don't. Served by `routes/apiDocs.js`. |
| `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)` + `detectShellFlavor(shell, platform?)` — build a `cd` line for the shell a PTY session is ACTUALLY running (`cmd.exe` → `cd /d "…"`, PowerShell → `Set-Location -LiteralPath '…'`, everything else → POSIX `cd '…'` via `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`. |
+| `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` → 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. |
| `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/shellCd.js b/server/lib/shellCd.js
index 9b2fd9775b..ccfad0ba8b 100644
--- a/server/lib/shellCd.js
+++ b/server/lib/shellCd.js
@@ -53,6 +53,34 @@ export function detectShellFlavor(shell, platform = process.platform) {
return platform === 'win32' ? 'powershell' : 'posix';
}
+/**
+ * Quote one token for a shell dialect.
+ *
+ * PowerShell and cmd.exe deliberately quote every token so Windows paths and
+ * provider arguments are passed literally. PowerShell needs the call operator
+ * for a quoted command-position token; quoted arguments do not use it.
+ *
+ * @param {*} value - token to quote
+ * @param {'cmd'|'powershell'|'posix'} flavor - shell dialect
+ * @param {'command'|'argument'} [position='argument'] - token position
+ * @returns {string}
+ */
+export function quoteForShell(value, flavor = 'posix', position = 'argument') {
+ const text = String(value ?? '');
+ switch (flavor) {
+ case 'cmd':
+ // cmd.exe has no escape for an embedded double quote.
+ return `"${text.replace(/"/g, '')}"`;
+ case 'powershell': {
+ const quoted = `'${text.replace(/'/g, "''")}'`;
+ return position === 'command' ? `& ${quoted}` : quoted;
+ }
+ default:
+ // Keep the established POSIX rendering byte-for-byte identical.
+ return shellQuote(text);
+ }
+}
+
/**
* @param {string} dirPath - directory to change into
* @param {string} [shell] - the session's shell binary; see detectShellFlavor
@@ -63,10 +91,8 @@ export function buildCdCommand(dirPath, shell) {
// line and run the rest as its own command, and no directory name has one.
const path = String(dirPath ?? '').replace(/[\u0000-\u001f\u007f]/g, '');
switch (detectShellFlavor(shell)) {
- // cmd.exe has no escape for `"` inside a quoted token, and a Windows path
- // can't contain one — drop rather than emit an unparseable line.
- case 'cmd': return `cd /d "${path.replace(/"/g, '')}"`;
- case 'powershell': return `Set-Location -LiteralPath '${path.replace(/'/g, "''")}'`;
- default: return `cd ${shellQuote(path)}`;
+ case 'cmd': return `cd /d ${quoteForShell(path, 'cmd')}`;
+ case 'powershell': return `Set-Location -LiteralPath ${quoteForShell(path, 'powershell')}`;
+ default: return `cd ${quoteForShell(path, 'posix')}`;
}
}
diff --git a/server/lib/shellCd.test.js b/server/lib/shellCd.test.js
index fb04883ef0..c6256c0c84 100644
--- a/server/lib/shellCd.test.js
+++ b/server/lib/shellCd.test.js
@@ -1,5 +1,5 @@
import { describe, it, expect } from 'vitest';
-import { buildCdCommand, detectShellFlavor } from './shellCd.js';
+import { buildCdCommand, detectShellFlavor, quoteForShell } from './shellCd.js';
describe('detectShellFlavor', () => {
it('reads the flavor off the shell binary, ignoring path and case', () => {
@@ -63,3 +63,23 @@ describe('buildCdCommand', () => {
expect(buildCdCommand('C:\\code\\"app"', 'cmd.exe')).toBe('cd /d "C:\\code\\app"');
});
});
+
+describe('quoteForShell', () => {
+ it('preserves the existing POSIX output in command and argument positions', () => {
+ expect(quoteForShell('claude', 'posix', 'command')).toBe('claude');
+ expect(quoteForShell("/tmp/it's a file", 'posix', 'argument')).toBe("'/tmp/it'\\''s a file'");
+ });
+
+ it('uses the PowerShell call operator only for a quoted command token', () => {
+ expect(quoteForShell("C:\\Program Files\\Claude\\it's.cmd", 'powershell', 'command'))
+ .toBe("& 'C:\\Program Files\\Claude\\it''s.cmd'");
+ expect(quoteForShell("I:\\input folder\\it's.md", 'powershell', 'argument'))
+ .toBe("'I:\\input folder\\it''s.md'");
+ });
+
+ it('double-quotes cmd.exe tokens and drops embedded double quotes', () => {
+ expect(quoteForShell('C:\\Program Files\\claude.cmd', 'cmd', 'command'))
+ .toBe('"C:\\Program Files\\claude.cmd"');
+ expect(quoteForShell('arg"with space', 'cmd', 'argument')).toBe('"argwith space"');
+ });
+});
diff --git a/server/services/agentTuiSpawning.js b/server/services/agentTuiSpawning.js
index 7d2d3ab007..0a2013a18f 100644
--- a/server/services/agentTuiSpawning.js
+++ b/server/services/agentTuiSpawning.js
@@ -27,7 +27,8 @@ import { normalizeReviewers } from '../lib/validation.js';
import * as git from './git.js';
import { resolveReviewLoopOptions } from './codeReview.js';
import { spawnTuiSessionViaRunner } from './cosRunnerClient.js';
-import { shellQuote } from '../lib/shellQuote.js';
+import { resolveInteractiveShell } from '../lib/interactiveShellResolver.js';
+import { detectShellFlavor, quoteForShell } from '../lib/shellCd.js';
import { isClaudeCommand, applyLeanClaudeArgs, providerSuppliesGithubToken } from '../lib/providerModels.js';
import { createStreamingAnsiStripper, stripAnsi } from '../lib/ansiStrip.js';
import { createImmediateFallbackSignalDetector } from '../lib/aiToolkit/errorDetection.js';
@@ -201,7 +202,11 @@ function shellHasLiveChild(shellPid) {
});
}
-export function buildTuiSpawnConfig(provider, model, { systemPromptFile = null, effort = null } = {}) {
+export function buildTuiSpawnConfig(provider, model, {
+ systemPromptFile = null,
+ effort = null,
+ shell = resolveInteractiveShell(),
+} = {}) {
const command = provider?.command || inferTuiCommand(provider?.id);
const baseArgs = applyCommandDefaults(command, [...(provider?.args || [])]);
// Model+effort injection (including the antigravity-validates-the-pair special
@@ -216,11 +221,15 @@ export function buildTuiSpawnConfig(provider, model, { systemPromptFile = null,
if (systemPromptFile && isClaudeCommand(command)) {
args = [...args, '--append-system-prompt-file', systemPromptFile];
}
+ const flavor = detectShellFlavor(shell);
+ const commandLine = [command, ...args]
+ .map((value, index) => quoteForShell(value, flavor, index === 0 ? 'command' : 'argument'))
+ .join(' ');
return {
command,
args,
- commandLine: [command, ...args].map(shellQuote).join(' '),
+ commandLine,
promptDelayMs: provider?.tuiPromptDelayMs || DEFAULT_TUI_PROMPT_DELAY_MS
};
}
diff --git a/server/services/agentTuiSpawning.test.js b/server/services/agentTuiSpawning.test.js
index b50aec557a..0ed7e6b2d0 100644
--- a/server/services/agentTuiSpawning.test.js
+++ b/server/services/agentTuiSpawning.test.js
@@ -116,6 +116,7 @@ vi.mock('./agentWorktreeCleanup.js', () => ({
}));
vi.mock('fs', () => ({
+ readdirSync: vi.fn().mockReturnValue([]),
// Default: no .agent-done sentinel on disk. The completion-sentinel test
// overrides this to true. Re-set in beforeEach so it can't leak between tests.
existsSync: vi.fn().mockReturnValue(false),
@@ -355,6 +356,23 @@ describe('agent TUI spawning', () => {
expect(config).not.toHaveProperty('idleTimeoutMs');
});
+ it('quotes the command position for PowerShell and cmd.exe while preserving POSIX output', () => {
+ const provider = {
+ id: 'claude-code-tui',
+ name: 'Claude TUI',
+ type: 'tui',
+ command: 'C:\\Program Files\\Claude\\claude.cmd',
+ args: ['--append-system-prompt-file', "I:\\input folder\\it's.md"],
+ };
+
+ 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)
+ .toBe("& 'C:\\Program Files\\Claude\\claude.cmd' '--append-system-prompt-file' 'I:\\input folder\\it''s.md'");
+ expect(buildTuiSpawnConfig(provider, null, { shell: 'cmd.exe' }).commandLine)
+ .toBe('"C:\\Program Files\\Claude\\claude.cmd" "--append-system-prompt-file" "I:\\input folder\\it\'s.md"');
+ });
+
it('namespaces the Ollama model under ollama/ for an OpenCode TUI', () => {
const config = buildTuiSpawnConfig({
id: 'opencode-ollama-tui', type: 'tui', command: 'opencode', args: [], ollamaBacked: true,