Skip to content

Beautiful, AI-native markdown IDE and LLM wiki

Quote agent CLI launch prompts for fish login shells (PRD-9349) (#6228)

Andrew Mikofalvyf80d1788d7bc
diff --git a/.changeset/fish-agent-launch-quoting.md b/.changeset/fish-agent-launch-quoting.md
new file mode 100644
index 000000000..777092da4
--- /dev/null
+++ b/.changeset/fish-agent-launch-quoting.md
@@ -0,0 +1,5 @@
+---
+"@inkeep/open-knowledge": patch
+---
+
+Starting an agent CLI from Ask AI or Fix all with fish as your login shell no longer runs commands that the sent text happens to contain.
diff --git a/packages/app/src/components/TerminalPanel.dom.test.tsx b/packages/app/src/components/TerminalPanel.dom.test.tsx
index acaf89621..6e92da6de 100644
--- a/packages/app/src/components/TerminalPanel.dom.test.tsx
+++ b/packages/app/src/components/TerminalPanel.dom.test.tsx
@@ -2367,7 +2367,10 @@ describe('TerminalPanel', () => {
expect(originalTerm?.dispose).toHaveBeenCalledTimes(1);
expect(siblingTerm?.dispose).not.toHaveBeenCalled();
expect(terminal.create).toHaveBeenLastCalledWith(
- expect.objectContaining({ launchCli: cli, launchCommand: expect.any(String) }),
+ expect.objectContaining({
+ launchCli: cli,
+ launchCommand: expect.objectContaining({ executable: expect.any(String) }),
+ }),
);
expect(
cli === 'claude' ? terminal.claudePreflight : terminal.cliPreflight,
diff --git a/packages/app/src/components/TerminalPanel.launch.dom.test.tsx b/packages/app/src/components/TerminalPanel.launch.dom.test.tsx
index a57e32ac2..e7b107be3 100644
--- a/packages/app/src/components/TerminalPanel.launch.dom.test.tsx
+++ b/packages/app/src/components/TerminalPanel.launch.dom.test.tsx
@@ -179,6 +179,16 @@ function bakedLaunch(
return last?.launchCommand;
}
+function bakedArgv(createMock: ReturnType<typeof vi.fn>): string | readonly string[] | undefined {
+ const launch = bakedLaunch(createMock);
+ return typeof launch === 'object' ? [launch.executable, ...launch.args] : launch;
+}
+
+function bakedArgvText(createMock: ReturnType<typeof vi.fn>): string {
+ const argv = bakedArgv(createMock);
+ return Array.isArray(argv) ? argv.join(' ') : String(argv);
+}
+
function reportedCli(createMock: ReturnType<typeof vi.fn>): string | undefined {
const last = createMock.mock.calls.at(-1)?.[0] as { launchCli?: string } | undefined;
return last?.launchCli;
@@ -190,11 +200,17 @@ function launchInputWrites(inputMock: ReturnType<typeof vi.fn>): string[] {
.filter((d) => typeof d === 'string' && /^(claude|codex|cursor-agent|opencode) /.test(d));
}
-const CLAUDE_PRE = `--settings '{"enabledMcpjsonServers":["open-knowledge"],"permissions":{"allow":["mcp__open-knowledge","Bash(ok open:*)"],"ask":["mcp__open-knowledge__delete","mcp__open-knowledge__move","mcp__open-knowledge__share_link","mcp__open-knowledge__install","mcp__open-knowledge__import"]}}'`;
+const CLAUDE_PRE = [
+ '--settings',
+ '{"enabledMcpjsonServers":["open-knowledge"],"permissions":{"allow":["mcp__open-knowledge","Bash(ok open:*)"],"ask":["mcp__open-knowledge__delete","mcp__open-knowledge__move","mcp__open-knowledge__share_link","mcp__open-knowledge__install","mcp__open-knowledge__import"]}}',
+];
-const CLAUDE_TRUST_ONLY = `--settings '{"enabledMcpjsonServers":["open-knowledge"]}'`;
+const CLAUDE_TRUST_ONLY = ['--settings', '{"enabledMcpjsonServers":["open-knowledge"]}'];
-const CLAUDE_AUTO_ONLY = `--settings '{"permissions":{"allow":["mcp__open-knowledge","Bash(ok open:*)"],"ask":["mcp__open-knowledge__delete","mcp__open-knowledge__move","mcp__open-knowledge__share_link","mcp__open-knowledge__install","mcp__open-knowledge__import"]}}'`;
+const CLAUDE_AUTO_ONLY = [
+ '--settings',
+ '{"permissions":{"allow":["mcp__open-knowledge","Bash(ok open:*)"],"ask":["mcp__open-knowledge__delete","mcp__open-knowledge__move","mcp__open-knowledge__share_link","mcp__open-knowledge__install","mcp__open-knowledge__import"]}}',
+];
function renderWithAutoApproveOff(ui: ReactElement) {
const value = {
@@ -236,10 +252,8 @@ describe('TerminalPanel "Open in terminal" launch (baked into the PTY spawn)', (
render(<TerminalPanel bridge={bridge} launch={{ prompt, cli: 'claude', nonce: 1 }} />);
await waitFor(() => expect(terminal.create).toHaveBeenCalledTimes(1));
- expect(bakedLaunch(terminal.create)).toBe(
- `claude ${CLAUDE_PRE} 'Let'\\''s work on \`foo.md\` using OpenKnowledge.'`,
- );
- expect(bakedLaunch(terminal.create)).not.toContain('\r');
+ expect(bakedArgv(terminal.create)).toEqual(['claude', ...CLAUDE_PRE, prompt]);
+ expect(bakedArgvText(terminal.create)).not.toContain('\r');
expect(launchInputWrites(terminal.input)).toEqual([]);
});
@@ -471,7 +485,7 @@ describe('TerminalPanel "Open in terminal" launch (baked into the PTY spawn)', (
);
await waitFor(() => expect(terminal.create).toHaveBeenCalledTimes(1));
- expect(bakedLaunch(terminal.create)).toBe(`claude ${CLAUDE_PRE}`);
+ expect(bakedArgv(terminal.create)).toEqual(['claude', ...CLAUDE_PRE]);
await new Promise((r) => setTimeout(r, STAGE_PASTE_SETTLE_MS + 300));
expect(terminal.input).not.toHaveBeenCalled();
if (lastTerm !== null) lastTerm.modes.bracketedPasteMode = true;
@@ -546,8 +560,8 @@ describe('TerminalPanel "Open in terminal" launch (baked into the PTY spawn)', (
render(<TerminalPanel bridge={bridge} launch={{ prompt, cli: 'hermes', nonce: 1 }} />);
await waitFor(() => expect(terminal.create).toHaveBeenCalledTimes(1));
- expect(bakedLaunch(terminal.create)).toBe('hermes chat');
- expect(bakedLaunch(terminal.create)).not.toContain(prompt);
+ expect(bakedArgv(terminal.create)).toEqual(['hermes', 'chat']);
+ expect(bakedArgvText(terminal.create)).not.toContain(prompt);
await new Promise((r) => setTimeout(r, 80));
expect(terminal.input).not.toHaveBeenCalled();
@@ -606,8 +620,8 @@ describe('TerminalPanel "Open in terminal" launch (baked into the PTY spawn)', (
render(<TerminalPanel bridge={bridge} launch={{ prompt: 'hi', cli: 'claude', nonce: 1 }} />);
await waitFor(() => expect(terminal.create).toHaveBeenCalledTimes(1));
- expect(bakedLaunch(terminal.create)).toBe("claude 'hi'");
- expect(bakedLaunch(terminal.create)).not.toContain('--settings');
+ expect(bakedArgv(terminal.create)).toEqual(['claude', 'hi']);
+ expect(bakedArgv(terminal.create)).not.toContain('--settings');
});
test("does NOT pre-approve when the project MCP entry is not OK's own (mcpPreApprovable false)", async () => {
@@ -615,8 +629,8 @@ describe('TerminalPanel "Open in terminal" launch (baked into the PTY spawn)', (
render(<TerminalPanel bridge={bridge} launch={{ prompt: 'hi', cli: 'claude', nonce: 1 }} />);
await waitFor(() => expect(terminal.create).toHaveBeenCalledTimes(1));
- expect(bakedLaunch(terminal.create)).toBe("claude 'hi'");
- expect(bakedLaunch(terminal.create)).not.toContain('--settings');
+ expect(bakedArgv(terminal.create)).toEqual(['claude', 'hi']);
+ expect(bakedArgv(terminal.create)).not.toContain('--settings');
});
test('verifies pre-approval at LAUNCH time (the bake gates on the fresh preflight, not a stale snapshot)', async () => {
@@ -624,7 +638,7 @@ describe('TerminalPanel "Open in terminal" launch (baked into the PTY spawn)', (
render(<TerminalPanel bridge={bridge} launch={{ prompt: 'hi', cli: 'claude', nonce: 1 }} />);
await waitFor(() => expect(terminal.create).toHaveBeenCalledTimes(1));
- expect(bakedLaunch(terminal.create)).toBe("claude 'hi'");
+ expect(bakedArgv(terminal.create)).toEqual(['claude', 'hi']);
expect(terminal.claudePreflight).toHaveBeenCalled();
});
@@ -665,7 +679,7 @@ describe('TerminalPanel "Open in terminal" launch (baked into the PTY spawn)', (
await waitFor(() => expect(terminal.create).toHaveBeenCalledTimes(1));
expect(terminal.cliPreflight).toHaveBeenCalledTimes(1);
expect(terminal.cliPreflight.mock.calls[0]?.[0]).toBe('codex');
- expect(bakedLaunch(terminal.create)).toBe("codex 'hi'");
+ expect(bakedArgv(terminal.create)).toEqual(['codex', 'hi']);
expect(launchInputWrites(terminal.input)).toEqual([]);
});
@@ -674,9 +688,12 @@ describe('TerminalPanel "Open in terminal" launch (baked into the PTY spawn)', (
render(<TerminalPanel bridge={bridge} launch={{ prompt: 'hi', cli: 'codex', nonce: 1 }} />);
await waitFor(() => expect(terminal.create).toHaveBeenCalledTimes(1));
- expect(bakedLaunch(terminal.create)).toBe(
- `codex -c 'mcp_servers.open-knowledge.default_tools_approval_mode="approve"' 'hi'`,
- );
+ expect(bakedArgv(terminal.create)).toEqual([
+ 'codex',
+ '-c',
+ 'mcp_servers.open-knowledge.default_tools_approval_mode="approve"',
+ 'hi',
+ ]);
});
test('codex auto-approves only the server name main checked, and nothing without one', async () => {
@@ -688,9 +705,12 @@ describe('TerminalPanel "Open in terminal" launch (baked into the PTY spawn)', (
<TerminalPanel bridge={beta.bridge} launch={{ prompt: 'hi', cli: 'codex', nonce: 1 }} />,
);
await waitFor(() => expect(beta.terminal.create).toHaveBeenCalledTimes(1));
- expect(bakedLaunch(beta.terminal.create)).toBe(
- `codex -c 'mcp_servers.open-knowledge-beta.default_tools_approval_mode="approve"' 'hi'`,
- );
+ expect(bakedArgv(beta.terminal.create)).toEqual([
+ 'codex',
+ '-c',
+ 'mcp_servers.open-knowledge-beta.default_tools_approval_mode="approve"',
+ 'hi',
+ ]);
cleanup();
const unnamed = makeBridge(WIRED, { onPath: 'present', okServerConfigured: true });
@@ -698,7 +718,7 @@ describe('TerminalPanel "Open in terminal" launch (baked into the PTY spawn)', (
<TerminalPanel bridge={unnamed.bridge} launch={{ prompt: 'hi', cli: 'codex', nonce: 1 }} />,
);
await waitFor(() => expect(unnamed.terminal.create).toHaveBeenCalledTimes(1));
- expect(bakedLaunch(unnamed.terminal.create)).toBe("codex 'hi'");
+ expect(bakedArgv(unnamed.terminal.create)).toEqual(['codex', 'hi']);
});
test('codex stays BARE (no -c) when OK is not configured in codex — the launch never breaks', async () => {
@@ -709,8 +729,8 @@ describe('TerminalPanel "Open in terminal" launch (baked into the PTY spawn)', (
render(<TerminalPanel bridge={bridge} launch={{ prompt: 'hi', cli: 'codex', nonce: 1 }} />);
await waitFor(() => expect(terminal.create).toHaveBeenCalledTimes(1));
- expect(bakedLaunch(terminal.create)).toBe("codex 'hi'");
- expect(bakedLaunch(terminal.create)).not.toContain('-c');
+ expect(bakedArgv(terminal.create)).toEqual(['codex', 'hi']);
+ expect(bakedArgv(terminal.create)).not.toContain('-c');
});
test('toggle OFF: a WIRED claude launch keeps server trust but bakes no permissions block', async () => {
@@ -720,8 +740,8 @@ describe('TerminalPanel "Open in terminal" launch (baked into the PTY spawn)', (
);
await waitFor(() => expect(terminal.create).toHaveBeenCalledTimes(1));
- expect(bakedLaunch(terminal.create)).toBe(`claude ${CLAUDE_TRUST_ONLY} 'hi'`);
- expect(bakedLaunch(terminal.create)).not.toContain('permissions');
+ expect(bakedArgv(terminal.create)).toEqual(['claude', ...CLAUDE_TRUST_ONLY, 'hi']);
+ expect(bakedArgvText(terminal.create)).not.toContain('permissions');
});
test("toggle OFF: codex stays BARE (no -c) even when OK's server is configured", async () => {
@@ -731,7 +751,7 @@ describe('TerminalPanel "Open in terminal" launch (baked into the PTY spawn)', (
);
await waitFor(() => expect(terminal.create).toHaveBeenCalledTimes(1));
- expect(bakedLaunch(terminal.create)).toBe("codex 'hi'");
+ expect(bakedArgv(terminal.create)).toEqual(['codex', 'hi']);
});
test('cursor launch bakes the cursor-agent command (the agent CLI, not the editor)', async () => {
@@ -739,7 +759,7 @@ describe('TerminalPanel "Open in terminal" launch (baked into the PTY spawn)', (
render(<TerminalPanel bridge={bridge} launch={{ prompt: 'hi', cli: 'cursor', nonce: 1 }} />);
await waitFor(() => expect(terminal.create).toHaveBeenCalledTimes(1));
- expect(bakedLaunch(terminal.create)).toBe("cursor-agent 'hi'");
+ expect(bakedArgv(terminal.create)).toEqual(['cursor-agent', 'hi']);
});
test('opencode launch bakes the --prompt form (positional is the project dir)', async () => {
@@ -747,7 +767,7 @@ describe('TerminalPanel "Open in terminal" launch (baked into the PTY spawn)', (
render(<TerminalPanel bridge={bridge} launch={{ prompt: 'hi', cli: 'opencode', nonce: 1 }} />);
await waitFor(() => expect(terminal.create).toHaveBeenCalledTimes(1));
- expect(bakedLaunch(terminal.create)).toBe("opencode --prompt 'hi'");
+ expect(bakedArgv(terminal.create)).toEqual(['opencode', '--prompt', 'hi']);
});
test('codex not on PATH: spawns a plain shell + surfaces the missing-CLI banner', async () => {
@@ -784,7 +804,7 @@ describe('TerminalPanel "Open in terminal" launch (baked into the PTY spawn)', (
await waitFor(() => expect(terminal.create).toHaveBeenCalledTimes(1));
expect(terminal.cliPreflight).toHaveBeenCalledTimes(2);
- expect(bakedLaunch(terminal.create)).toBe("cursor-agent 'hi'");
+ expect(bakedArgv(terminal.create)).toEqual(['cursor-agent', 'hi']);
});
test('cliPreflight IPC rejection spawns plain + surfaces the UNVERIFIED banner (never "isn\'t installed")', async () => {
@@ -872,26 +892,26 @@ describe('the two --settings halves are gated independently, across all four MCP
const { bridge, terminal } = makeBridge(preflight);
render(<TerminalPanel bridge={bridge} launch={{ prompt: 'hi', cli: 'claude', nonce: 1 }} />);
await waitFor(() => expect(terminal.create).toHaveBeenCalledTimes(1));
- return bakedLaunch(terminal.create);
+ return bakedArgv(terminal.create);
}
test('global-only: OK tools are auto-approved, and no project server trust is claimed', async () => {
const baked = await bakeClaudeLaunch(WIRED_GLOBAL_ONLY);
- expect(baked).toBe(`claude ${CLAUDE_AUTO_ONLY} 'hi'`);
- expect(baked).not.toContain('enabledMcpjsonServers');
+ expect(baked).toEqual(['claude', ...CLAUDE_AUTO_ONLY, 'hi']);
+ expect(String(baked)).not.toContain('enabledMcpjsonServers');
});
test('project-only: both halves, exactly as before the split', async () => {
- expect(await bakeClaudeLaunch(PROJECT_ONLY)).toBe(`claude ${CLAUDE_PRE} 'hi'`);
+ expect(await bakeClaudeLaunch(PROJECT_ONLY)).toEqual(['claude', ...CLAUDE_PRE, 'hi']);
});
test('both scopes: both halves, in one settings object', async () => {
- expect(await bakeClaudeLaunch(BOTH_SCOPES)).toBe(`claude ${CLAUDE_PRE} 'hi'`);
+ expect(await bakeClaudeLaunch(BOTH_SCOPES)).toEqual(['claude', ...CLAUDE_PRE, 'hi']);
});
test('neither scope: a bare launch, no settings at all', async () => {
const baked = await bakeClaudeLaunch(NEITHER_SCOPE);
- expect(baked).toBe("claude 'hi'");
+ expect(baked).toEqual(['claude', 'hi']);
expect(baked).not.toContain('--settings');
});
@@ -901,21 +921,22 @@ describe('the two --settings halves are gated independently, across all four MCP
mcpPreApprovable: false,
okToolsAutoApprovable: false,
});
- expect(baked).toBe("claude 'hi'");
+ expect(baked).toEqual(['claude', 'hi']);
expect(baked).not.toContain('--settings');
});
test('names only the server main checked: a Beta verdict never approves open-knowledge', async () => {
const baked = await bakeClaudeLaunch({ ...BOTH_SCOPES, mcpServerName: 'open-knowledge-beta' });
- expect(baked).toContain('"enabledMcpjsonServers":["open-knowledge-beta"]');
- expect(baked).toContain('"mcp__open-knowledge-beta__delete"');
- expect(baked?.replaceAll('open-knowledge-beta', '')).not.toContain('open-knowledge');
+ const bakedText = String(baked);
+ expect(bakedText).toContain('"enabledMcpjsonServers":["open-knowledge-beta"]');
+ expect(bakedText).toContain('"mcp__open-knowledge-beta__delete"');
+ expect(bakedText.replaceAll('open-knowledge-beta', '')).not.toContain('open-knowledge');
});
test('a verdict that carries no server name bakes a bare launch, never a guessed name', async () => {
const { mcpServerName: _omitted, ...unnamed } = BOTH_SCOPES;
const baked = await bakeClaudeLaunch(unnamed);
- expect(baked).toBe("claude 'hi'");
+ expect(baked).toEqual(['claude', 'hi']);
});
test('toggle OFF on a global-only install: neither half, so the launch is bare', async () => {
@@ -925,8 +946,8 @@ describe('the two --settings halves are gated independently, across all four MCP
);
await waitFor(() => expect(terminal.create).toHaveBeenCalledTimes(1));
- expect(bakedLaunch(terminal.create)).toBe("claude 'hi'");
- expect(bakedLaunch(terminal.create)).not.toContain('--settings');
+ expect(bakedArgv(terminal.create)).toEqual(['claude', 'hi']);
+ expect(bakedArgv(terminal.create)).not.toContain('--settings');
});
});
@@ -944,7 +965,7 @@ describe('the agent CLI reported to the host alongside the spawn', () => {
await waitFor(() => expect(terminal.create).toHaveBeenCalledTimes(1));
expect(reportedCli(terminal.create)).toBe('claude');
- expect(bakedLaunch(terminal.create)).toBe(`claude ${CLAUDE_PRE} 'hi'`);
+ expect(bakedArgv(terminal.create)).toEqual(['claude', ...CLAUDE_PRE, 'hi']);
});
test('names the agent for a non-claude launch too', async () => {
diff --git a/packages/app/src/components/TerminalPanel.tsx b/packages/app/src/components/TerminalPanel.tsx
index 6fb9b3e48..c1ca4a3fb 100644
--- a/packages/app/src/components/TerminalPanel.tsx
+++ b/packages/app/src/components/TerminalPanel.tsx
@@ -7,7 +7,7 @@ import {
} from '@inkeep/open-knowledge-core/desktop-bridge';
import {
BRACKETED_PASTE_ENABLE_MARKER,
- buildCliLaunchArgString,
+ buildPosixCliLaunch,
buildStartupInjectionBytes,
buildTerminalInputBytes,
buildWindowsCliLaunch,
@@ -633,11 +633,11 @@ function TerminalSession({
const resolveLaunchCommand = async (
intent: TerminalCliLaunchIntent,
- ): Promise<string | TerminalLaunchCommand | undefined> => {
- const buildLaunch = (opts: Parameters<typeof buildCliLaunchArgString>[2]) =>
+ ): Promise<TerminalLaunchCommand | undefined> => {
+ const buildLaunch = (opts: Parameters<typeof buildPosixCliLaunch>[2]) =>
bridge.platform === 'win32'
? buildWindowsCliLaunch(intent.cli, intent.prompt, opts)
- : buildCliLaunchArgString(intent.cli, intent.prompt, opts);
+ : buildPosixCliLaunch(intent.cli, intent.prompt, opts);
if (intent.cli === 'claude') {
try {
const fresh = await bridge.terminal.claudePreflight();
diff --git a/packages/app/src/components/handoff/useHandoffDispatch.terminal-budget.test.ts b/packages/app/src/components/handoff/useHandoffDispatch.terminal-budget.test.ts
index 62316e133..0381dfde4 100644
--- a/packages/app/src/components/handoff/useHandoffDispatch.terminal-budget.test.ts
+++ b/packages/app/src/components/handoff/useHandoffDispatch.terminal-budget.test.ts
@@ -1,6 +1,6 @@
import {
assembleHandoffPrompt,
- buildCliLaunchArgString,
+ buildPosixCliLaunch,
composeAskPrompt,
composeSelectionPrompt,
shellSingleQuote,
@@ -16,6 +16,15 @@ const MACOS_ARG_MAX = 1_048_576;
const URL_INLINE_PROMPT_ENCODED_BUDGET = 4096 - 1024;
+function launchArgvBytes(cli: (typeof TERMINAL_CLI_IDS)[number], prompt: string): number {
+ const launch = buildPosixCliLaunch(cli, prompt);
+ const encoder = new TextEncoder();
+ return [launch.executable, ...launch.args].reduce(
+ (total, arg) => total + encoder.encode(arg).length + 1,
+ 0,
+ );
+}
+
const workspace = { contentDir: '/Users/u/notes', pathSeparator: '/' as const };
function terminalProse(chars: number): string {
@@ -44,7 +53,7 @@ describe('composeTerminalLaunchPrompt — terminal transport carries long instru
const prompt = composeTerminalLaunchPrompt(input, cli);
expect(prompt).toContain(instruction);
expect(prompt).not.toContain(TRUNCATION_MARKER);
- expect(buildCliLaunchArgString(cli, prompt).length).toBeLessThanOrEqual(MACOS_ARG_MAX);
+ expect(launchArgvBytes(cli, prompt)).toBeLessThanOrEqual(MACOS_ARG_MAX);
}
});
@@ -96,7 +105,7 @@ describe('composeTerminalLaunchPrompt — terminal transport carries long instru
expect(new TextEncoder().encode(shellSingleQuote(prompt)).length).toBeLessThanOrEqual(
TERMINAL_INLINE_PROMPT_BUDGET + 1024,
);
- expect(buildCliLaunchArgString('claude', prompt).length).toBeLessThanOrEqual(MACOS_ARG_MAX);
+ expect(launchArgvBytes('claude', prompt)).toBeLessThanOrEqual(MACOS_ARG_MAX);
expect(prompt).not.toContain(instruction);
expect(prompt).toContain(TRUNCATION_MARKER);
expect(prompt.length).toBeGreaterThan(TERMINAL_INLINE_PROMPT_BUDGET - 2_000);
diff --git a/packages/core/src/handoff/index.ts b/packages/core/src/handoff/index.ts
index b3fd11a9d..abd0d8fe3 100644
--- a/packages/core/src/handoff/index.ts
+++ b/packages/core/src/handoff/index.ts
@@ -28,13 +28,12 @@ export {
} from './prompt-composer.ts';
export {
BRACKETED_PASTE_ENABLE_MARKER,
- buildClaudeLaunchCommand,
- buildCliLaunchArgString,
- buildCliLaunchCommand,
+ buildPosixCliLaunch,
buildStartupInjectionBytes,
buildTerminalInputBytes,
buildWindowsCliLaunch,
composeWindowsShellLaunchArgs,
+ fishSingleQuote,
isTerminalLaunchEnvName,
isWindowsShellFamily,
isWindowsShellLaunchFailureReason,
diff --git a/packages/core/src/handoff/prompt-composer.test.ts b/packages/core/src/handoff/prompt-composer.test.ts
index 50b8713ba..947fbb6a4 100644
--- a/packages/core/src/handoff/prompt-composer.test.ts
+++ b/packages/core/src/handoff/prompt-composer.test.ts
@@ -20,7 +20,7 @@ import {
TERMINAL_INLINE_PROMPT_BUDGET,
withSkillPointer,
} from './prompt-composer.ts';
-import { shellSingleQuote, toTerminalPromptText } from './terminal-launch.ts';
+import { fishSingleQuote, shellSingleQuote, toTerminalPromptText } from './terminal-launch.ts';
import type { HandoffPayload, HandoffTarget } from './types.ts';
test('composeFilePrompt with autoOpen=true emits the file directive + Open-the-OK-editor trailer', () => {
@@ -1191,7 +1191,11 @@ test('assembleHandoffPrompt renders an anchor selection as the locus reference',
});
function quotedByteLength(prompt: string): number {
- return new TextEncoder().encode(shellSingleQuote(prompt)).length;
+ const encoder = new TextEncoder();
+ return Math.max(
+ encoder.encode(shellSingleQuote(prompt)).length,
+ encoder.encode(fishSingleQuote(prompt)).length,
+ );
}
function terminalProse(chars: number): string {
@@ -1288,6 +1292,31 @@ test('terminal transport measures shell-quoted BYTES — an apostrophe-dense ins
expect(quotedByteLength(out)).toBeLessThanOrEqual(TERMINAL_INLINE_PROMPT_BUDGET);
});
+test('terminal transport measures fish-quoted bytes too — a backslash-dense instruction trims by the longer of the POSIX and fish quotings', () => {
+ const instruction = 'y\\'.repeat(40_000);
+ const encoder = new TextEncoder();
+ expect(encoder.encode(shellSingleQuote(instruction)).length).toBeLessThan(
+ TERMINAL_INLINE_PROMPT_BUDGET,
+ );
+ expect(encoder.encode(fishSingleQuote(instruction)).length).toBeGreaterThan(
+ TERMINAL_INLINE_PROMPT_BUDGET,
+ );
+ const out = assembleHandoffPrompt({
+ scope: 'doc',
+ docRelativePath: 'plans/migration.md',
+ instruction,
+ mentions: [],
+ autoOpen: false,
+ target: 'claude-code',
+ transport: 'terminal',
+ });
+ expect(out).not.toContain(instruction);
+ expect(out).toContain(' …');
+ expect(encoder.encode(fishSingleQuote(out)).length).toBeLessThanOrEqual(
+ TERMINAL_INLINE_PROMPT_BUDGET,
+ );
+});
+
test('terminal transport measures the labeled bytes — a control-dense instruction trims by its labeled length, not its raw length', () => {
const instruction = 'x\u0003'.repeat(20_000);
expect(quotedByteLength(instruction)).toBeLessThan(TERMINAL_INLINE_PROMPT_BUDGET);
diff --git a/packages/core/src/handoff/prompt-composer.ts b/packages/core/src/handoff/prompt-composer.ts
index 40e99131d..7dd0cffb3 100644
--- a/packages/core/src/handoff/prompt-composer.ts
+++ b/packages/core/src/handoff/prompt-composer.ts
@@ -2,7 +2,7 @@
* They never carry file content, so the precedent #60 invariant ("agent grounds via OK MCP, not
* native attach") holds by virtue of the URL never carrying `file=` attach data.
*/
-import { shellSingleQuote, toTerminalPromptText } from './terminal-launch.ts';
+import { fishSingleQuote, shellSingleQuote, toTerminalPromptText } from './terminal-launch.ts';
import type { HandoffTarget } from './types.ts';
const PATH_INJECTION_SANITIZE_RE = new RegExp(
@@ -224,7 +224,11 @@ function promptTransportLength(
transport: PromptTransport,
): number {
if (transport === 'terminal') {
- return UTF8_ENCODER.encode(shellSingleQuote(toTerminalPromptText(prompt))).length;
+ const text = toTerminalPromptText(prompt);
+ return Math.max(
+ UTF8_ENCODER.encode(shellSingleQuote(text)).length,
+ UTF8_ENCODER.encode(fishSingleQuote(text)).length,
+ );
}
return encodedPromptLength(prompt, target);
}
diff --git a/packages/core/src/handoff/terminal-launch.test.ts b/packages/core/src/handoff/terminal-launch.test.ts
index 92bbc31c9..f44d3439f 100644
--- a/packages/core/src/handoff/terminal-launch.test.ts
+++ b/packages/core/src/handoff/terminal-launch.test.ts
@@ -16,9 +16,7 @@ const spawnSyncMock = vi.mocked(spawnSync);
import { MCP_SERVER_NAME } from '../constants/mcp.ts';
import { DESKTOP_PRODUCTS } from '../constants/product.ts';
import {
- buildClaudeLaunchCommand,
- buildCliLaunchArgString,
- buildCliLaunchCommand,
+ buildPosixCliLaunch,
buildStartupInjectionBytes,
buildTerminalInputBytes,
buildWindowsCliLaunch,
@@ -41,9 +39,12 @@ import {
WindowsShellLaunchError,
} from './terminal-launch.ts';
-const CLAUDE_PREAPPROVE = `--settings '{"enabledMcpjsonServers":["${MCP_SERVER_NAME}"]}'`;
const OK_ALLOW = `["mcp__${MCP_SERVER_NAME}","Bash(ok open:*)"]`;
const OK_ASK = `["mcp__${MCP_SERVER_NAME}__delete","mcp__${MCP_SERVER_NAME}__move","mcp__${MCP_SERVER_NAME}__share_link","mcp__${MCP_SERVER_NAME}__install","mcp__${MCP_SERVER_NAME}__import"]`;
+const CLAUDE_PREAPPROVE_JSON = `{"enabledMcpjsonServers":["${MCP_SERVER_NAME}"]}`;
+const CLAUDE_AUTO_APPROVE_JSON = `{"permissions":{"allow":${OK_ALLOW},"ask":${OK_ASK}}}`;
+const CLAUDE_BOTH_JSON = `{"enabledMcpjsonServers":["${MCP_SERVER_NAME}"],"permissions":{"allow":${OK_ALLOW},"ask":${OK_ASK}}}`;
+const CODEX_APPROVE = `mcp_servers.${MCP_SERVER_NAME}.default_tools_approval_mode="approve"`;
describe('TERMINAL_CLI_IDS', () => {
it('lists the CLIs in auto-pick priority order (claude > codex > opencode > cursor > copilot > pi > antigravity > openclaw > hermes)', () => {
@@ -855,174 +856,163 @@ describe('PowerShell launch composition read back by a real PowerShell parser',
});
});
-describe('buildClaudeLaunchCommand', () => {
- it("defaults to a bare `claude '<prompt>'` — no MCP pre-approval unless opted in", () => {
- expect(buildClaudeLaunchCommand("Let's work on `foo.md` using OpenKnowledge.")).toBe(
- "claude 'Let'\\''s work on `foo.md` using OpenKnowledge.'\r",
- );
+describe('buildPosixCliLaunch', () => {
+ it('passes the prompt as one unquoted argument after the fixed args, for every argv-prompt CLI', () => {
+ const prompt = "x\\'(touch pwned)\\' and '; rm -rf / # $(id) `id`\nline two";
+ for (const cli of TERMINAL_CLI_IDS) {
+ const launch = buildPosixCliLaunch(cli, prompt);
+ expect(launch.executable).toBe(TERMINAL_CLIS[cli].bin);
+ if (startupInjectionFor(cli, 'darwin') != null) {
+ expect(launch.args).not.toContain(prompt);
+ continue;
+ }
+ expect(launch.args.at(-1)).toBe(prompt);
+ expect(launch.args.filter((arg) => arg.includes('pwned'))).toHaveLength(1);
+ }
});
- it("with mcpPreApprove, produces the `claude --settings '<json>' '<prompt>'` shape", () => {
+ it('labels control characters in the prompt argument', () => {
+ expect(buildPosixCliLaunch('codex', 'fix\u0003 this\r\nnow').args).toEqual([
+ `fix<control-0003> this\nnow\n\n${TERMINAL_CONTROL_LABEL_NOTICE}`,
+ ]);
+ });
+
+ it('carries the claude settings and codex approval as separate raw arguments', () => {
expect(
- buildClaudeLaunchCommand("Let's work on `foo.md` using OpenKnowledge.", {
- mcpPreApprove: true,
+ buildPosixCliLaunch('claude', 'hi', { mcpPreApprove: true, mcpServerName: MCP_SERVER_NAME }),
+ ).toEqual({
+ executable: 'claude',
+ args: ['--settings', `{"enabledMcpjsonServers":["${MCP_SERVER_NAME}"]}`, 'hi'],
+ });
+ expect(
+ buildPosixCliLaunch('codex', 'hi', {
+ autoApproveOkTools: true,
mcpServerName: MCP_SERVER_NAME,
}),
- ).toBe(
- "claude --settings '{\"enabledMcpjsonServers\":[\"open-knowledge\"]}' 'Let'\\''s work on `foo.md` using OpenKnowledge.'\r",
- );
+ ).toEqual({
+ executable: 'codex',
+ args: ['-c', `mcp_servers.${MCP_SERVER_NAME}.default_tools_approval_mode="approve"`, 'hi'],
+ });
+ expect(buildPosixCliLaunch('openclaw', 'hi')).toEqual({
+ executable: 'openclaw',
+ args: ['chat', '--message', 'hi'],
+ });
});
- it('keeps an injection payload inert and contained in the prompt arg (pre-approved)', () => {
- const cmd = buildClaudeLaunchCommand("'; rm -rf / #", {
- mcpPreApprove: true,
- mcpServerName: MCP_SERVER_NAME,
- });
- expect(cmd).toBe(`claude ${CLAUDE_PREAPPROVE} ''\\''; rm -rf / #'\r`);
- expect(cmd.startsWith(`claude ${CLAUDE_PREAPPROVE} `)).toBe(true);
- expect(cmd.endsWith("''\\''; rm -rf / #'\r")).toBe(true);
+ it('launches promptless when there is no prompt or the CLI takes it by startup injection', () => {
+ expect(buildPosixCliLaunch('claude', null)).toEqual({ executable: 'claude', args: [] });
+ expect(buildPosixCliLaunch('copilot', '')).toEqual({ executable: 'copilot', args: [] });
+ expect(buildPosixCliLaunch('hermes', 'hi')).toEqual({ executable: 'hermes', args: ['chat'] });
});
});
-describe('buildCliLaunchCommand', () => {
- it('defaults to a bare positional single-quoted prompt per CLI (no pre-approval)', () => {
- expect(buildCliLaunchCommand('claude', 'hi')).toBe("claude 'hi'\r");
- expect(buildCliLaunchCommand('codex', 'hi')).toBe("codex 'hi'\r");
- expect(buildCliLaunchCommand('copilot', 'hi')).toBe("copilot --interactive 'hi'\r");
- expect(buildCliLaunchCommand('cursor', 'hi')).toBe("cursor-agent 'hi'\r");
- expect(buildCliLaunchCommand('opencode', 'hi')).toBe("opencode --prompt 'hi'\r");
- expect(buildCliLaunchCommand('pi', 'hi')).toBe("pi 'hi'\r");
- expect(buildCliLaunchCommand('antigravity', 'hi')).toBe("agy --prompt-interactive 'hi'\r");
- expect(buildCliLaunchCommand('openclaw', 'hi')).toBe("openclaw chat --message 'hi'\r");
- expect(buildCliLaunchCommand('hermes', 'hi')).toBe('hermes chat\r');
+describe('buildPosixCliLaunch per-CLI shape', () => {
+ it('keeps the fixed per-CLI shape (registry bin, subcommand and prompt flag, prompt last)', () => {
+ expect(buildPosixCliLaunch('claude', 'hi')).toEqual({ executable: 'claude', args: ['hi'] });
+ expect(buildPosixCliLaunch('codex', 'hi')).toEqual({ executable: 'codex', args: ['hi'] });
+ expect(buildPosixCliLaunch('copilot', 'hi')).toEqual({
+ executable: 'copilot',
+ args: ['--interactive', 'hi'],
+ });
+ expect(buildPosixCliLaunch('cursor', 'hi')).toEqual({
+ executable: 'cursor-agent',
+ args: ['hi'],
+ });
+ expect(buildPosixCliLaunch('opencode', 'hi')).toEqual({
+ executable: 'opencode',
+ args: ['--prompt', 'hi'],
+ });
+ expect(buildPosixCliLaunch('pi', 'hi')).toEqual({ executable: 'pi', args: ['hi'] });
+ expect(buildPosixCliLaunch('antigravity', 'hi')).toEqual({
+ executable: 'agy',
+ args: ['--prompt-interactive', 'hi'],
+ });
+ expect(buildPosixCliLaunch('openclaw', 'hi')).toEqual({
+ executable: 'openclaw',
+ args: ['chat', '--message', 'hi'],
+ });
+ expect(buildPosixCliLaunch('hermes', 'hi')).toEqual({ executable: 'hermes', args: ['chat'] });
});
- it('escapes the prompt identically for every argv-prompt CLI regardless of fixed args', () => {
+ it('keeps an injection payload as the final argument for every argv-prompt CLI with every option on', () => {
for (const cli of TERMINAL_CLI_IDS) {
if (startupInjectionFor(cli, 'darwin') != null) continue;
- const cmd = buildCliLaunchCommand(cli, "'; rm -rf / #", {
- mcpPreApprove: true,
- mcpServerName: MCP_SERVER_NAME,
- });
- expect(cmd.startsWith(`${TERMINAL_CLIS[cli].bin} `)).toBe(true);
- expect(cmd.endsWith("''\\''; rm -rf / #'\r")).toBe(true);
- }
- });
-
- it('buildClaudeLaunchCommand is the claude specialization (opts forwarded)', () => {
- expect(buildClaudeLaunchCommand('hi')).toBe(buildCliLaunchCommand('claude', 'hi'));
- expect(
- buildClaudeLaunchCommand('hi', { mcpPreApprove: true, mcpServerName: MCP_SERVER_NAME }),
- ).toBe(
- buildCliLaunchCommand('claude', 'hi', {
- mcpPreApprove: true,
- mcpServerName: MCP_SERVER_NAME,
- }),
- );
- });
-});
-
-describe('buildCliLaunchArgString', () => {
- it('is the launch command WITHOUT the trailing carriage return', () => {
- for (const cli of TERMINAL_CLI_IDS) {
- const arg = buildCliLaunchArgString(cli, 'hi', {
+ const launch = buildPosixCliLaunch(cli, "'; rm -rf / #", {
mcpPreApprove: true,
+ autoApproveOkTools: true,
mcpServerName: MCP_SERVER_NAME,
});
- expect(arg.endsWith('\r')).toBe(false);
- expect(`${arg}\r`).toBe(
- buildCliLaunchCommand(cli, 'hi', { mcpPreApprove: true, mcpServerName: MCP_SERVER_NAME }),
- );
+ expect(launch.executable).toBe(TERMINAL_CLIS[cli].bin);
+ expect(launch.args.at(-1)).toBe("'; rm -rf / #");
}
});
- it('keeps the fixed per-CLI shape (registry bin + single-quoted prompt)', () => {
- expect(buildCliLaunchArgString('claude', 'hi')).toBe("claude 'hi'");
- expect(buildCliLaunchArgString('codex', 'hi')).toBe("codex 'hi'");
- expect(buildCliLaunchArgString('copilot', 'hi')).toBe("copilot --interactive 'hi'");
- expect(buildCliLaunchArgString('cursor', 'hi')).toBe("cursor-agent 'hi'");
- expect(buildCliLaunchArgString('opencode', 'hi')).toBe("opencode --prompt 'hi'");
- expect(buildCliLaunchArgString('pi', 'hi')).toBe("pi 'hi'");
- expect(buildCliLaunchArgString('antigravity', 'hi')).toBe("agy --prompt-interactive 'hi'");
- expect(buildCliLaunchArgString('openclaw', 'hi')).toBe("openclaw chat --message 'hi'");
- expect(buildCliLaunchArgString('hermes', 'hi')).toBe('hermes chat');
- });
-
- it('keeps an injection payload inert and contained in the prompt arg', () => {
- const arg = buildCliLaunchArgString('claude', "'; rm -rf / #");
- expect(arg).toBe("claude ''\\''; rm -rf / #'");
- expect(arg.endsWith("''\\''; rm -rf / #'")).toBe(true);
- });
- it('labels control characters in the prompt arg instead of passing raw bytes to the CLI', () => {
- const arg = buildCliLaunchArgString('claude', 'fix\u0000 this\u001b[2J\r\nnow');
- expect(arg).toBe(
- `claude '${'fix<control-0000> this<control-001B>[2J\nnow'}\n\n${TERMINAL_CONTROL_LABEL_NOTICE}'`,
+ it('labels control characters in the prompt argument instead of passing raw bytes to the CLI', () => {
+ const prompt = buildPosixCliLaunch('claude', 'fix\u0000 this\u001b[2J\r\nnow').args.at(-1);
+ expect(prompt).toBe(
+ `fix<control-0000> this<control-001B>[2J\nnow\n\n${TERMINAL_CONTROL_LABEL_NOTICE}`,
);
- expect(arg).not.toMatch(TERMINAL_RAW_CONTROL_RE);
+ expect(prompt).not.toMatch(TERMINAL_RAW_CONTROL_RE);
});
});
-describe('buildCliLaunchArgString promptless (New chat)', () => {
- it('emits a bare `<bin>` for a null/undefined/empty prompt — no positional, no prompt flag', () => {
+describe('buildPosixCliLaunch promptless (New chat)', () => {
+ it('emits the bare executable for a null/undefined/empty prompt, with no positional and no prompt flag', () => {
for (const emptyPrompt of [null, undefined, ''] as const) {
- expect(buildCliLaunchArgString('claude', emptyPrompt)).toBe('claude');
- expect(buildCliLaunchArgString('codex', emptyPrompt)).toBe('codex');
- expect(buildCliLaunchArgString('copilot', emptyPrompt)).toBe('copilot');
- expect(buildCliLaunchArgString('cursor', emptyPrompt)).toBe('cursor-agent');
- expect(buildCliLaunchArgString('opencode', emptyPrompt)).toBe('opencode');
- expect(buildCliLaunchArgString('openclaw', emptyPrompt)).toBe('openclaw chat');
- expect(buildCliLaunchArgString('hermes', emptyPrompt)).toBe('hermes chat');
+ expect(buildPosixCliLaunch('claude', emptyPrompt)).toEqual({
+ executable: 'claude',
+ args: [],
+ });
+ expect(buildPosixCliLaunch('codex', emptyPrompt)).toEqual({ executable: 'codex', args: [] });
+ expect(buildPosixCliLaunch('copilot', emptyPrompt)).toEqual({
+ executable: 'copilot',
+ args: [],
+ });
+ expect(buildPosixCliLaunch('cursor', emptyPrompt)).toEqual({
+ executable: 'cursor-agent',
+ args: [],
+ });
+ expect(buildPosixCliLaunch('opencode', emptyPrompt)).toEqual({
+ executable: 'opencode',
+ args: [],
+ });
+ expect(buildPosixCliLaunch('openclaw', emptyPrompt)).toEqual({
+ executable: 'openclaw',
+ args: ['chat'],
+ });
+ expect(buildPosixCliLaunch('hermes', emptyPrompt)).toEqual({
+ executable: 'hermes',
+ args: ['chat'],
+ });
}
});
it('still applies Claude MCP pre-approval on a promptless launch when opted in', () => {
- const arg = buildCliLaunchArgString('claude', null, {
- mcpPreApprove: true,
- mcpServerName: MCP_SERVER_NAME,
- });
- expect(arg).toBe(`claude ${CLAUDE_PREAPPROVE}`);
- expect(arg.endsWith(' ')).toBe(false);
+ expect(
+ buildPosixCliLaunch('claude', null, { mcpPreApprove: true, mcpServerName: MCP_SERVER_NAME }),
+ ).toEqual({ executable: 'claude', args: ['--settings', CLAUDE_PREAPPROVE_JSON] });
});
it('still applies Claude OK auto-approve on a promptless launch, alone and merged with pre-approval', () => {
- const autoOnly = buildCliLaunchArgString('claude', null, {
- autoApproveOkTools: true,
- mcpServerName: MCP_SERVER_NAME,
- });
- expect(autoOnly).toBe(
- `claude --settings '{"permissions":{"allow":${OK_ALLOW},"ask":${OK_ASK}}}'`,
- );
- expect(autoOnly.endsWith(' ')).toBe(false);
-
- const both = buildCliLaunchArgString('claude', null, {
- mcpPreApprove: true,
- autoApproveOkTools: true,
- mcpServerName: MCP_SERVER_NAME,
- });
- expect(both).toBe(
- `claude --settings '{"enabledMcpjsonServers":["${MCP_SERVER_NAME}"],"permissions":{"allow":${OK_ALLOW},"ask":${OK_ASK}}}'`,
- );
- expect(both.endsWith(' ')).toBe(false);
- });
-
- it('never adds --prompt or a positional to a promptless opencode launch, even opted in', () => {
expect(
- buildCliLaunchArgString('opencode', '', {
+ buildPosixCliLaunch('claude', null, {
+ autoApproveOkTools: true,
+ mcpServerName: MCP_SERVER_NAME,
+ }).args,
+ ).toEqual(['--settings', CLAUDE_AUTO_APPROVE_JSON]);
+ expect(
+ buildPosixCliLaunch('claude', null, {
mcpPreApprove: true,
+ autoApproveOkTools: true,
mcpServerName: MCP_SERVER_NAME,
- }),
- ).toBe('opencode');
+ }).args,
+ ).toEqual(['--settings', CLAUDE_BOTH_JSON]);
});
- it('leaves the non-empty prompted shape byte-identical (promptless branch must not perturb it)', () => {
- expect(buildCliLaunchArgString('claude', 'hi')).toBe("claude 'hi'");
+ it('never adds --prompt or a positional to a promptless opencode launch, even opted in', () => {
expect(
- buildCliLaunchArgString('claude', 'hi', {
- mcpPreApprove: true,
- mcpServerName: MCP_SERVER_NAME,
- }),
- ).toBe(`claude ${CLAUDE_PREAPPROVE} 'hi'`);
- expect(buildCliLaunchArgString('opencode', 'hi')).toBe("opencode --prompt 'hi'");
+ buildPosixCliLaunch('opencode', '', { mcpPreApprove: true, mcpServerName: MCP_SERVER_NAME }),
+ ).toEqual({ executable: 'opencode', args: [] });
});
});
@@ -1180,142 +1170,77 @@ describe('buildTerminalInputBytes', () => {
describe('claude MCP pre-approval', () => {
it('is OFF by default and only added for claude when opted in', () => {
- expect(buildCliLaunchCommand('claude', 'hi')).not.toContain('--settings');
+ expect(buildPosixCliLaunch('claude', 'hi').args).not.toContain('--settings');
expect(
- buildCliLaunchCommand('claude', 'hi', {
- mcpPreApprove: true,
- mcpServerName: MCP_SERVER_NAME,
- }),
- ).toContain(CLAUDE_PREAPPROVE);
+ buildPosixCliLaunch('claude', 'hi', { mcpPreApprove: true, mcpServerName: MCP_SERVER_NAME })
+ .args,
+ ).toEqual(['--settings', CLAUDE_PREAPPROVE_JSON, 'hi']);
});
it('never added for codex/copilot/cursor/opencode, even when opted in (claude-only flag)', () => {
- expect(
- buildCliLaunchCommand('codex', 'hi', { mcpPreApprove: true, mcpServerName: MCP_SERVER_NAME }),
- ).toBe("codex 'hi'\r");
- expect(
- buildCliLaunchCommand('copilot', 'hi', {
- mcpPreApprove: true,
- mcpServerName: MCP_SERVER_NAME,
- }),
- ).toBe("copilot --interactive 'hi'\r");
- expect(
- buildCliLaunchCommand('cursor', 'hi', {
- mcpPreApprove: true,
- mcpServerName: MCP_SERVER_NAME,
- }),
- ).toBe("cursor-agent 'hi'\r");
- expect(
- buildCliLaunchCommand('opencode', 'hi', {
- mcpPreApprove: true,
- mcpServerName: MCP_SERVER_NAME,
- }),
- ).toBe("opencode --prompt 'hi'\r");
+ const opts = { mcpPreApprove: true, mcpServerName: MCP_SERVER_NAME };
+ expect(buildPosixCliLaunch('codex', 'hi', opts).args).toEqual(['hi']);
+ expect(buildPosixCliLaunch('copilot', 'hi', opts).args).toEqual(['--interactive', 'hi']);
+ expect(buildPosixCliLaunch('cursor', 'hi', opts).args).toEqual(['hi']);
+ expect(buildPosixCliLaunch('opencode', 'hi', opts).args).toEqual(['--prompt', 'hi']);
});
it('names the canonical MCP server, matching what editor wiring registers in .mcp.json', () => {
expect(
- buildCliLaunchCommand('claude', 'hi', {
- mcpPreApprove: true,
- mcpServerName: MCP_SERVER_NAME,
- }),
+ buildPosixCliLaunch('claude', 'hi', { mcpPreApprove: true, mcpServerName: MCP_SERVER_NAME })
+ .args[1],
).toContain(`["${MCP_SERVER_NAME}"]`);
});
});
describe('OK auto-approve (autoApproveOkTools)', () => {
+ const AUTO = { autoApproveOkTools: true, mcpServerName: MCP_SERVER_NAME };
+
it('adds the OK allow-list + destructive ask-list to Claude --settings when on', () => {
- expect(
- buildCliLaunchArgString('claude', 'hi', {
- autoApproveOkTools: true,
- mcpServerName: MCP_SERVER_NAME,
- }),
- ).toBe(`claude --settings '{"permissions":{"allow":${OK_ALLOW},"ask":${OK_ASK}}}' 'hi'`);
+ expect(buildPosixCliLaunch('claude', 'hi', AUTO).args).toEqual([
+ '--settings',
+ CLAUDE_AUTO_APPROVE_JSON,
+ 'hi',
+ ]);
});
it('merges server-trust + auto-approve into one --settings object when both on', () => {
- expect(
- buildCliLaunchArgString('claude', 'hi', {
- mcpPreApprove: true,
- autoApproveOkTools: true,
- mcpServerName: MCP_SERVER_NAME,
- }),
- ).toBe(
- `claude --settings '{"enabledMcpjsonServers":["${MCP_SERVER_NAME}"],"permissions":{"allow":${OK_ALLOW},"ask":${OK_ASK}}}' 'hi'`,
- );
+ expect(buildPosixCliLaunch('claude', 'hi', { ...AUTO, mcpPreApprove: true }).args).toEqual([
+ '--settings',
+ CLAUDE_BOTH_JSON,
+ 'hi',
+ ]);
});
it('keeps every gated tool in the ask list (never silently auto-approved)', () => {
- const arg = buildCliLaunchArgString('claude', 'hi', {
- autoApproveOkTools: true,
- mcpServerName: MCP_SERVER_NAME,
- });
+ const settings = buildPosixCliLaunch('claude', 'hi', AUTO).args[1];
expect(OK_GATED_TOOL_NAMES).toEqual(['delete', 'move', 'share_link', 'install', 'import']);
for (const gated of OK_GATED_TOOL_NAMES) {
- expect(arg).toContain(`"mcp__${MCP_SERVER_NAME}__${gated}"`);
+ expect(settings).toContain(`"mcp__${MCP_SERVER_NAME}__${gated}"`);
}
});
it('never gates with `deny` (that would hide the tools from the agent)', () => {
- const arg = buildCliLaunchArgString('claude', 'hi', {
- autoApproveOkTools: true,
- mcpServerName: MCP_SERVER_NAME,
- });
- expect(arg).not.toContain('"deny"');
+ expect(buildPosixCliLaunch('claude', 'hi', AUTO).args[1]).not.toContain('"deny"');
});
it('adds the codex per-server `-c approve` override only when on', () => {
- expect(
- buildCliLaunchArgString('codex', 'hi', {
- autoApproveOkTools: true,
- mcpServerName: MCP_SERVER_NAME,
- }),
- ).toBe(`codex -c 'mcp_servers.${MCP_SERVER_NAME}.default_tools_approval_mode="approve"' 'hi'`);
- expect(buildCliLaunchArgString('codex', 'hi')).toBe("codex 'hi'");
+ expect(buildPosixCliLaunch('codex', 'hi', AUTO).args).toEqual(['-c', CODEX_APPROVE, 'hi']);
+ expect(buildPosixCliLaunch('codex', 'hi').args).toEqual(['hi']);
});
it('is claude/codex only — copilot/cursor/opencode/pi never get an auto-approve arg', () => {
- expect(
- buildCliLaunchArgString('copilot', 'hi', {
- autoApproveOkTools: true,
- mcpServerName: MCP_SERVER_NAME,
- }),
- ).toBe("copilot --interactive 'hi'");
- expect(
- buildCliLaunchArgString('cursor', 'hi', {
- autoApproveOkTools: true,
- mcpServerName: MCP_SERVER_NAME,
- }),
- ).toBe("cursor-agent 'hi'");
- expect(
- buildCliLaunchArgString('opencode', 'hi', {
- autoApproveOkTools: true,
- mcpServerName: MCP_SERVER_NAME,
- }),
- ).toBe("opencode --prompt 'hi'");
- expect(
- buildCliLaunchArgString('pi', 'hi', {
- autoApproveOkTools: true,
- mcpServerName: MCP_SERVER_NAME,
- }),
- ).toBe("pi 'hi'");
+ expect(buildPosixCliLaunch('copilot', 'hi', AUTO).args).toEqual(['--interactive', 'hi']);
+ expect(buildPosixCliLaunch('cursor', 'hi', AUTO).args).toEqual(['hi']);
+ expect(buildPosixCliLaunch('opencode', 'hi', AUTO).args).toEqual(['--prompt', 'hi']);
+ expect(buildPosixCliLaunch('pi', 'hi', AUTO).args).toEqual(['hi']);
});
- it('keeps the prompt the final escaped arg with auto-approve on (injection inert)', () => {
- const arg = buildCliLaunchArgString('claude', "'; rm -rf / #", {
- autoApproveOkTools: true,
- mcpServerName: MCP_SERVER_NAME,
+ it('keeps the fixed args for a promptless auto-approve launch', () => {
+ expect(buildPosixCliLaunch('codex', null, AUTO)).toEqual({
+ executable: 'codex',
+ args: ['-c', CODEX_APPROVE],
});
- expect(arg.endsWith("''\\''; rm -rf / #'")).toBe(true);
- });
-
- it('emits a bare `<bin>` for a promptless auto-approve launch with the fixed args', () => {
- expect(
- buildCliLaunchArgString('codex', null, {
- autoApproveOkTools: true,
- mcpServerName: MCP_SERVER_NAME,
- }),
- ).toBe(`codex -c 'mcp_servers.${MCP_SERVER_NAME}.default_tools_approval_mode="approve"'`);
});
});
@@ -1323,11 +1248,11 @@ describe('launch approval names the server the main process checked', () => {
const BETA = DESKTOP_PRODUCTS.beta.mcpServerName;
const ALL_ON = { mcpPreApprove: true, autoApproveOkTools: true } as const;
- function artifacts(opts: Parameters<typeof buildCliLaunchArgString>[2]): string[] {
+ function artifacts(opts: Parameters<typeof buildPosixCliLaunch>[2]): string[] {
const winClaude = buildWindowsCliLaunch('claude', 'hi', opts);
return [
- buildCliLaunchArgString('claude', 'hi', opts),
- buildCliLaunchArgString('codex', 'hi', opts),
+ buildPosixCliLaunch('claude', 'hi', opts).args.join(' '),
+ buildPosixCliLaunch('codex', 'hi', opts).args.join(' '),
winClaude.supportFile?.contents ?? '',
buildWindowsCliLaunch('codex', 'hi', opts).args.join(' '),
];
@@ -1338,11 +1263,9 @@ describe('launch approval names the server the main process checked', () => {
try {
const out = artifacts({ ...ALL_ON, mcpServerName: BETA });
expect(out[0]).toBe(
- `claude --settings '{"enabledMcpjsonServers":["${BETA}"],"permissions":{"allow":["mcp__${BETA}","Bash(ok open:*)"],"ask":["mcp__${BETA}__delete","mcp__${BETA}__move","mcp__${BETA}__share_link","mcp__${BETA}__install","mcp__${BETA}__import"]}}' 'hi'`,
- );
- expect(out[1]).toBe(
- `codex -c 'mcp_servers.${BETA}.default_tools_approval_mode="approve"' 'hi'`,
+ `--settings {"enabledMcpjsonServers":["${BETA}"],"permissions":{"allow":["mcp__${BETA}","Bash(ok open:*)"],"ask":["mcp__${BETA}__delete","mcp__${BETA}__move","mcp__${BETA}__share_link","mcp__${BETA}__install","mcp__${BETA}__import"]}} hi`,
);
+ expect(out[1]).toBe(`-c mcp_servers.${BETA}.default_tools_approval_mode="approve" hi`);
expect(out[2]).toContain(`["${BETA}"]`);
expect(out[3]).toBe(`-c mcp_servers.${BETA}.default_tools_approval_mode=approve`);
for (const artifact of out) {
@@ -1355,8 +1278,14 @@ describe('launch approval names the server the main process checked', () => {
it('emits no pre-approval and no auto-approve when main supplied no name', () => {
for (const opts of [ALL_ON, { ...ALL_ON, mcpServerName: '' }]) {
- expect(buildCliLaunchArgString('claude', 'hi', opts)).toBe("claude 'hi'");
- expect(buildCliLaunchArgString('codex', 'hi', opts)).toBe("codex 'hi'");
+ expect(buildPosixCliLaunch('claude', 'hi', opts)).toEqual({
+ executable: 'claude',
+ args: ['hi'],
+ });
+ expect(buildPosixCliLaunch('codex', 'hi', opts)).toEqual({
+ executable: 'codex',
+ args: ['hi'],
+ });
expect(buildWindowsCliLaunch('claude', 'hi', opts)).toEqual({
executable: 'claude',
args: [],
@@ -1368,11 +1297,9 @@ describe('launch approval names the server the main process checked', () => {
it('keeps the Stable artifacts byte-identical when main supplies the Stable name', () => {
const out = artifacts({ ...ALL_ON, mcpServerName: 'open-knowledge' });
expect(out[0]).toBe(
- `claude --settings '{"enabledMcpjsonServers":["open-knowledge"],"permissions":{"allow":["mcp__open-knowledge","Bash(ok open:*)"],"ask":["mcp__open-knowledge__delete","mcp__open-knowledge__move","mcp__open-knowledge__share_link","mcp__open-knowledge__install","mcp__open-knowledge__import"]}}' 'hi'`,
- );
- expect(out[1]).toBe(
- `codex -c 'mcp_servers.open-knowledge.default_tools_approval_mode="approve"' 'hi'`,
+ `--settings {"enabledMcpjsonServers":["open-knowledge"],"permissions":{"allow":["mcp__open-knowledge","Bash(ok open:*)"],"ask":["mcp__open-knowledge__delete","mcp__open-knowledge__move","mcp__open-knowledge__share_link","mcp__open-knowledge__install","mcp__open-knowledge__import"]}} hi`,
);
+ expect(out[1]).toBe(`-c mcp_servers.open-knowledge.default_tools_approval_mode="approve" hi`);
expect(out[3]).toBe('-c mcp_servers.open-knowledge.default_tools_approval_mode=approve');
});
@@ -1381,9 +1308,10 @@ describe('launch approval names the server the main process checked', () => {
vi.resetModules();
try {
const mod = await import('./terminal-launch.ts');
- expect(mod.buildCliLaunchArgString('codex', 'hi', { autoApproveOkTools: true })).toBe(
- "codex 'hi'",
- );
+ expect(mod.buildPosixCliLaunch('codex', 'hi', { autoApproveOkTools: true })).toEqual({
+ executable: 'codex',
+ args: ['hi'],
+ });
} finally {
vi.unstubAllEnvs();
vi.resetModules();
diff --git a/packages/core/src/handoff/terminal-launch.ts b/packages/core/src/handoff/terminal-launch.ts
index 037d29f0b..6580de790 100644
--- a/packages/core/src/handoff/terminal-launch.ts
+++ b/packages/core/src/handoff/terminal-launch.ts
@@ -5,6 +5,10 @@ export function shellSingleQuote(s: string): string {
return `'${s.replace(/'/g, "'\\''")}'`;
}
+export function fishSingleQuote(s: string): string {
+ return `'${s.replace(/\\/g, '\\\\').replace(/'/g, "\\'")}'`;
+}
+
export interface TerminalLaunchCommand {
readonly executable: string;
readonly args: readonly string[];
@@ -304,11 +308,6 @@ function buildClaudeSettingsJson(opts: BuildCliLaunchOptions): string | null {
return JSON.stringify(settings);
}
-function buildClaudeSettingsArg(opts: BuildCliLaunchOptions): string {
- const settingsJson = buildClaudeSettingsJson(opts);
- return settingsJson === null ? '' : `--settings ${shellSingleQuote(settingsJson)}`;
-}
-
const ESC = '\x1b';
const BRACKETED_PASTE_START = `${ESC}[200~`;
const BRACKETED_PASTE_END = `${ESC}[201~`;
@@ -486,38 +485,28 @@ export function buildWindowsCliLaunch(
};
}
-export function buildCliLaunchArgString(
+export function buildPosixCliLaunch(
cli: TerminalCli,
prompt: string | null | undefined,
opts: BuildCliLaunchOptions = {},
-): string {
+): TerminalLaunchCommand {
const info: TerminalCliInfo = TERMINAL_CLIS[cli];
const server = approvedServerName(opts);
+ const settingsJson = cli === 'claude' ? buildClaudeSettingsJson(opts) : null;
const fixedArgs =
- cli === 'claude'
- ? buildClaudeSettingsArg(opts)
+ settingsJson !== null
+ ? ['--settings', settingsJson]
: cli === 'codex' && opts.autoApproveOkTools === true && server !== null
- ? `-c ${shellSingleQuote(codexAutoApproveSetting(server, '"'))}`
- : '';
- const fixedPrefix = fixedArgs ? `${fixedArgs} ` : '';
- const sub = info.subcommand ? `${info.subcommand} ` : '';
+ ? ['-c', codexAutoApproveSetting(server, '"')]
+ : [];
+ const args = [...(info.subcommand ? [info.subcommand] : []), ...fixedArgs];
if (info.startupInjection != null || prompt == null || prompt.length === 0) {
- return `${info.bin} ${sub}${fixedPrefix}`.trimEnd();
+ return { executable: info.bin, args };
}
- const promptFlag = info.promptFlag ? `${info.promptFlag} ` : '';
- return `${info.bin} ${sub}${fixedPrefix}${promptFlag}${shellSingleQuote(toTerminalPromptText(prompt))}`;
-}
-
-export function buildCliLaunchCommand(
- cli: TerminalCli,
- prompt: string,
- opts: BuildCliLaunchOptions = {},
-): string {
- return `${buildCliLaunchArgString(cli, prompt, opts)}\r`;
-}
-
-export function buildClaudeLaunchCommand(prompt: string, opts: BuildCliLaunchOptions = {}): string {
- return buildCliLaunchCommand('claude', prompt, opts);
+ return {
+ executable: info.bin,
+ args: [...args, ...(info.promptFlag ? [info.promptFlag] : []), toTerminalPromptText(prompt)],
+ };
}
export function startupInjectionFor(
diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts
index fff3536a1..b398e20c5 100644
--- a/packages/core/src/index.ts
+++ b/packages/core/src/index.ts
@@ -778,12 +778,10 @@ export {
assembleHandoffPrompt,
assertNeverUrnIpcLookup,
BRACKETED_PASTE_ENABLE_MARKER,
- buildClaudeLaunchCommand,
buildClaudeUrl,
- buildCliLaunchArgString,
- buildCliLaunchCommand,
buildCodexUrl,
buildCursorUrl,
+ buildPosixCliLaunch,
buildStartupInjectionBytes,
buildTerminalInputBytes,
buildWindowsCliLaunch,
@@ -803,6 +801,7 @@ export {
composeThreadBareLaunchPrompt,
composeWindowsShellLaunchArgs,
type DocContext,
+ fishSingleQuote,
type HandoffFailureReason,
type HandoffOutcome,
type HandoffPayload,
diff --git a/packages/core/tests/contract/subpath-types/consumer.ts b/packages/core/tests/contract/subpath-types/consumer.ts
index f9ceb1fd2..ec2b7ba15 100644
--- a/packages/core/tests/contract/subpath-types/consumer.ts
+++ b/packages/core/tests/contract/subpath-types/consumer.ts
@@ -318,9 +318,9 @@ export type {
AssembleHandoffPromptInput,
assembleHandoffPrompt,
buildClaudeUrl,
- buildCliLaunchArgString,
buildCodexUrl,
buildCursorUrl,
+ buildPosixCliLaunch,
buildStartupInjectionBytes,
buildWindowsCliLaunch,
ComposeSelection,
diff --git a/packages/desktop/src/shared/terminal-shell.ts b/packages/desktop/src/shared/terminal-shell.ts
index 6b767b3f4..32fe2bd4d 100644
--- a/packages/desktop/src/shared/terminal-shell.ts
+++ b/packages/desktop/src/shared/terminal-shell.ts
@@ -1,13 +1,9 @@
-import { shellSingleQuote } from '@inkeep/open-knowledge-core';
+import { fishSingleQuote, shellSingleQuote } from '@inkeep/open-knowledge-core';
export function interactiveShellArgs(platform: NodeJS.Platform): readonly string[] {
return platform === 'linux' ? ['-i'] : ['-l', '-i'];
}
-function fishSingleQuote(value: string): string {
- return `'${value.replace(/\\/g, '\\\\').replace(/'/g, "\\'")}'`;
-}
-
const POSIX_SHELL_NAMES = new Set(['ash', 'bash', 'dash', 'ksh', 'ksh93', 'mksh', 'sh', 'zsh']);
export type ShellCommandFamily = 'posix' | 'fish' | 'fallback';
diff --git a/packages/desktop/src/utility/pty-host.ts b/packages/desktop/src/utility/pty-host.ts
index 47954ece9..1402e3764 100644
--- a/packages/desktop/src/utility/pty-host.ts
+++ b/packages/desktop/src/utility/pty-host.ts
@@ -820,10 +820,15 @@ function unsetEnvStep(shell: string, names: readonly string[]): string {
: `unset ${names.join(' ')}; `;
}
+const BARE_COMMAND_NAME_RE = /^[A-Za-z0-9_][A-Za-z0-9_.-]*$/u;
+
function composeStructuredLaunch(shell: string, launch: TerminalLaunchCommand): string {
- const command = [launch.executable, ...launch.args]
- .map((token) => quoteShellArg(shell, token))
- .join(' ');
+ const executable = BARE_COMMAND_NAME_RE.test(launch.executable)
+ ? launch.executable
+ : quoteShellArg(shell, launch.executable);
+ const command = [executable, ...launch.args.map((token) => quoteShellArg(shell, token))].join(
+ ' ',
+ );
const slots = terminalLaunchEnvSlots(launch.env);
if (slots.length === 0) return command;
if (shellCommandFamily(shell) === 'fish') {
diff --git a/packages/desktop/tests/utility/pty-host-posix-launch-quoting.test.ts b/packages/desktop/tests/utility/pty-host-posix-launch-quoting.test.ts
new file mode 100644
index 000000000..f393e05eb
--- /dev/null
+++ b/packages/desktop/tests/utility/pty-host-posix-launch-quoting.test.ts
@@ -0,0 +1,120 @@
+import { existsSync, mkdirSync, mkdtempSync, readdirSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import {
+ buildPosixCliLaunch,
+ type TerminalLaunchCommand,
+} from '@inkeep/open-knowledge-core/handoff';
+import { afterEach, describe, expect, test } from 'vitest';
+import { buildShellArgs } from '../../src/utility/pty-host.ts';
+import { capturedTails, spawnSyncBounded } from '../support/bounded-sync-spawn.test-helper.ts';
+import { removeTempDirBestEffort } from '../support/temp-dir-cleanup.test-helper.ts';
+
+const PRINTF = '/usr/bin/printf';
+const ARGV_START = 'ok-launch-argv-start';
+
+const HOSTILE_PROMPT = [
+ "fish: x\\'(touch pwned-fish)\\'",
+ 'posix: $(touch pwned-posix) `touch pwned-tick`',
+ "quote: '; touch pwned-quote #",
+ 'backslashes: \\\\ \\n \\',
+ 'control: a\u0003b',
+].join('\n');
+
+const SHELL_CANDIDATES = [
+ '/bin/sh',
+ '/bin/bash',
+ '/bin/zsh',
+ '/usr/bin/fish',
+ '/usr/local/bin/fish',
+ '/opt/homebrew/bin/fish',
+];
+
+const tempDirs: string[] = [];
+
+function tempDir(prefix: string): string {
+ const dir = mkdtempSync(join(tmpdir(), prefix));
+ tempDirs.push(dir);
+ return dir;
+}
+
+afterEach(() => {
+ for (const dir of tempDirs.splice(0)) removeTempDirBestEffort(dir);
+});
+
+function writeProbeAliases(home: string): void {
+ const posixAlias = `alias okprobe=${PRINTF}\n`;
+ for (const rc of ['.bashrc', '.bash_profile', '.profile', '.shrc', '.zshrc']) {
+ writeFileSync(join(home, rc), posixAlias);
+ }
+ mkdirSync(join(home, 'fish'), { recursive: true });
+ writeFileSync(join(home, 'fish', 'config.fish'), `alias okprobe ${PRINTF}\n`);
+}
+
+function runLaunch(shell: string, launch: TerminalLaunchCommand) {
+ const cwd = tempDir('ok-posix-launch-cwd-');
+ const home = tempDir('ok-posix-launch-home-');
+ writeProbeAliases(home);
+ const run = spawnSyncBounded(shell, buildShellArgs(process.platform, shell, launch, []), {
+ cwd,
+ input: '',
+ env: {
+ PATH: '/usr/bin:/bin',
+ HOME: home,
+ ENV: join(home, '.shrc'),
+ XDG_CONFIG_HOME: home,
+ XDG_DATA_HOME: home,
+ ZDOTDIR: home,
+ },
+ timeoutMs: 20_000,
+ });
+ return { cwd, run };
+}
+
+function receivedArgv(stdout: string, count: number): string[] | null {
+ const start = stdout.indexOf(`${ARGV_START}\0`);
+ if (start < 0) return null;
+ return stdout
+ .slice(start + ARGV_START.length + 1)
+ .split('\0')
+ .slice(0, count);
+}
+
+describe.skipIf(process.platform === 'win32' || !existsSync(PRINTF))(
+ 'a POSIX agent CLI launch run through the real login shell',
+ () => {
+ test.for(SHELL_CANDIDATES)(
+ '%s hands the CLI the prompt as one argument and runs nothing in it',
+ (shell, ctx) => {
+ ctx.skip(!existsSync(shell), `${shell} is not installed`);
+ const launch = buildPosixCliLaunch('claude', HOSTILE_PROMPT, {
+ mcpPreApprove: true,
+ autoApproveOkTools: true,
+ mcpServerName: 'open-knowledge',
+ });
+ const { cwd, run } = runLaunch(shell, {
+ executable: PRINTF,
+ args: ['%s\\0', ARGV_START, ...launch.args],
+ });
+
+ const received = receivedArgv(run.stdout, launch.args.length);
+ expect(received, capturedTails(run)).toEqual(launch.args);
+ expect(received?.at(-1)).toContain("x\\'(touch pwned-fish)\\'");
+ expect(readdirSync(cwd).filter((name) => name.startsWith('pwned-'))).toEqual([]);
+ },
+ );
+
+ test.for(SHELL_CANDIDATES)(
+ '%s still resolves an alias for the CLI command name',
+ (shell, ctx) => {
+ ctx.skip(!existsSync(shell), `${shell} is not installed`);
+ const { run } = runLaunch(shell, {
+ executable: 'okprobe',
+ args: ['%s\\0', ARGV_START, 'hello world'],
+ });
+
+ expect(receivedArgv(run.stdout, 1), capturedTails(run)).toEqual(['hello world']);
+ },
+ );
+ },
+);
diff --git a/packages/desktop/tests/utility/pty-host.test.ts b/packages/desktop/tests/utility/pty-host.test.ts
index 2aec670b3..3cece40b6 100644
--- a/packages/desktop/tests/utility/pty-host.test.ts
+++ b/packages/desktop/tests/utility/pty-host.test.ts
@@ -4,6 +4,7 @@ import {
OK_DESKTOP_TERMINAL_ENV,
OK_HOSTED_AGENT_ENV,
posixOkManagedBinDir,
+ shellSingleQuote,
} from '@inkeep/open-knowledge-core';
import { TERMINAL_SHELL_NOTICE_REASONS } from '@inkeep/open-knowledge-core/desktop-bridge';
import { describe, expect, test, vi } from 'vitest';
@@ -2339,7 +2340,7 @@ describe('buildShellArgs', () => {
if (!call) throw new Error('no spawn');
const script = call.args[3] ?? '';
expect(script).toContain(
- `(export ZDOTDIR="$OK_TERMINAL_LAUNCH_ENV_0" AUGGIE_HOME="$OK_TERMINAL_LAUNCH_ENV_1"; exec 'agent' 'login'); unset OK_TERMINAL_LAUNCH_ENV_0 OK_TERMINAL_LAUNCH_ENV_1; exec`,
+ `(export ZDOTDIR="$OK_TERMINAL_LAUNCH_ENV_0" AUGGIE_HOME="$OK_TERMINAL_LAUNCH_ENV_1"; exec agent 'login'); unset OK_TERMINAL_LAUNCH_ENV_0 OK_TERMINAL_LAUNCH_ENV_1; exec`,
);
const pairs = [...script.matchAll(/(\w+)="\$(OK_TERMINAL_LAUNCH_ENV_\d+)"/g)].map((match) => [
match[1] ?? '',
@@ -2355,7 +2356,7 @@ describe('buildShellArgs', () => {
}
});
- test('a structured launch under fish uses fish quoting for every token', () => {
+ test('a structured launch under fish uses fish quoting for every argument', () => {
expect(
buildShellArgs(
'linux',
@@ -2366,10 +2367,31 @@ describe('buildShellArgs', () => {
).toEqual([
'-i',
'-c',
- `begin; set -lx A "$OK_TERMINAL_LAUNCH_ENV_0"; 'agent' 'it\\\\\\'s' 'trailing\\\\'; end; set -e OK_TERMINAL_LAUNCH_ENV_0; exec '/usr/bin/fish' -i`,
+ `begin; set -lx A "$OK_TERMINAL_LAUNCH_ENV_0"; agent 'it\\\\\\'s' 'trailing\\\\'; end; set -e OK_TERMINAL_LAUNCH_ENV_0; exec '/usr/bin/fish' -i`,
]);
});
+ test('a structured launch leaves a bare command name unquoted so shell aliases still resolve', () => {
+ expect(
+ buildShellArgs(
+ 'darwin',
+ '/bin/zsh',
+ { executable: 'claude', args: ['--settings', '{}'] },
+ [],
+ ),
+ ).toEqual(['-l', '-i', '-c', "claude '--settings' '{}'; exec '/bin/zsh' -l -i"]);
+ });
+
+ test('a structured launch quotes an executable that is a path or carries shell syntax', () => {
+ for (const executable of ['/opt/my tools/claude', '$(touch pwned)', '-claude', 'a;b']) {
+ const script = buildShellArgs('darwin', '/bin/zsh', { executable, args: [] }, [])[3];
+ expect(script).toBe(`${shellSingleQuote(executable)}; exec '/bin/zsh' -l -i`);
+ }
+ expect(buildShellArgs('linux', '/usr/bin/fish', { executable: "o'k\\", args: [] }, [])[2]).toBe(
+ "'o\\'k\\\\'; exec '/usr/bin/fish' -i",
+ );
+ });
+
test('uses fish list syntax for the reassert when the terminal shell is fish', () => {
expect(buildShellArgs('linux', '/usr/bin/fish', 'claude', ['/managed/bin'])).toEqual([
'-i',