Skip to content

Beautiful, AI-native markdown IDE and LLM wiki

Escape curly single quotes when quoting for PowerShell (#5066)

Nick Gomezc40286d4871b
diff --git a/.changeset/powershell-curly-quote-paths.md b/.changeset/powershell-curly-quote-paths.md
new file mode 100644
index 000000000..2cfbf3be4
--- /dev/null
+++ b/.changeset/powershell-curly-quote-paths.md
@@ -0,0 +1,5 @@
+---
+"@inkeep/open-knowledge": patch
+---
+
+On Windows, dropping a file whose path contains a curly single quote onto a PowerShell terminal, or signing in to an agent whose command line contains one, no longer produces a broken command.
diff --git a/packages/app/BUNDLE-SIZE.md b/packages/app/BUNDLE-SIZE.md
index 17762deff..cdc3a499f 100644
--- a/packages/app/BUNDLE-SIZE.md
+++ b/packages/app/BUNDLE-SIZE.md
@@ -99,3 +99,5 @@ Combined-chunks 8.84->8.85 MB for GitHub Enterprise Server host handling in Sett
Combined-chunks 8.84->8.86 MB for repository-aware worktree discovery and presentation. A forced clean local build measured 8,840,825 B against the prior 8,840,000 B ceiling, with 26,938 B of growth over the same-machine `main` build at 8,813,887 B. The eager main-app and CSS budgets remain unchanged at 487 kB and 59 kB because this ratchet records the feature's aggregate chunk inventory rather than a new first-load allowance. The new ceiling leaves 19,175 B of headroom over that local measurement; the corresponding CI size job passed.
Combined-chunks 8.88->8.89 MB for GitHub reference links and hover cards in agent chat: `owner/repo#N` and configured ticket-prefix linking, the `hover-card` primitive, `GitHubReferenceCard` with its status line, and their strings compiled into every locale catalog. CI measured the pull request at 8,881,800 B, 1,800 B over the prior ceiling. Measured on one machine after the review fixes, `main` at `869755a` builds to 8,868,939 B and the same `main` with this branch merged builds to 8,881,731 B, so the branch adds 12,792 B. The main app bundle moved 36 B, to 441.88 kB against its 487 kB limit, and CSS stayed at 8.36 kB against 59 kB, because the chat that renders these links and the settings dialog body are already lazy chunks; the growth is on-demand chunk weight. The 10 kB ratchet leaves 8,269 B of headroom over the merged local build, and the lazy-load levers above remain the reclamation path.
+
+Combined-chunks 8.89->8.9 MB for PowerShell path quoting: `psQuoteArg` now doubles all five characters PowerShell reads as a single quote (U+0027 and U+2018-U+201B), not only the ASCII apostrophe, so a dropped file whose name contains a curly quote gives a working command. CI measured the pull request at 8,890,002 B, 2 B over the prior 8,890,000 B ceiling. Clean local builds of the same tree measured 8,889,973 B with the previous `psQuoteArg` and 8,890,002 B with the change, so it adds 29 B. The main app bundle measured 441.88 kB before the change and 441.87 kB with it, against its 487 kB limit, and CSS stayed at 8.36 kB against 59 kB, so neither eager budget moves. The 10 kB ratchet leaves 9,998 B of headroom over the local build.
diff --git a/packages/app/package.json b/packages/app/package.json
index 10b1dcafc..999efb466 100644
--- a/packages/app/package.json
+++ b/packages/app/package.json
@@ -64,7 +64,7 @@
{
"name": "all JS chunks combined (gzipped)",
"path": "dist/assets/*.js",
- "limit": "8.89 MB",
+ "limit": "8.9 MB",
"gzip": true,
"running": false
},
diff --git a/packages/app/src/components/TerminalPanel.dom.test.tsx b/packages/app/src/components/TerminalPanel.dom.test.tsx
index 8980d1cfb..d95f06a6e 100644
--- a/packages/app/src/components/TerminalPanel.dom.test.tsx
+++ b/packages/app/src/components/TerminalPanel.dom.test.tsx
@@ -869,6 +869,42 @@ describe('TerminalPanel', () => {
expect(terminal.input).toHaveBeenCalledWith('pty-1', "'C:\\Users\\O''Brien\\shot.png' ");
});
+ test('a PowerShell terminal doubles every curly single quote in dropped Windows paths', async () => {
+ const { bridge, terminal, pushNotice } = makeBridge(
+ { ok: true, ptyId: 'pty-1' },
+ WIRED,
+ undefined,
+ 'win32',
+ );
+ (bridge as unknown as { getPathForFile: (file: File) => string }).getPathForFile = (file) =>
+ `C:\\Users\\me\\${file.name}`;
+ render(<TerminalPanel bridge={bridge} />);
+ await waitFor(() => expect(lastTerm?.onDataCb).toBeTruthy());
+ act(() =>
+ pushNotice({
+ ptyId: 'pty-1',
+ notice: 'shell-resolved',
+ shellFamily: 'powershell',
+ }),
+ );
+
+ const container = document.querySelector('[data-terminal-status]');
+ if (container === null) throw new Error('terminal container not found');
+ const files = [
+ new File(['a'], '\u2018draft.md', { type: 'text/markdown' }),
+ new File(['b'], 'Nick\u2019s notes.md', { type: 'text/markdown' }),
+ new File(['c'], 'a\u201Ab.md', { type: 'text/markdown' }),
+ new File(['d'], 'a\u201Bb.md', { type: 'text/markdown' }),
+ ];
+ fireEvent.drop(container, { dataTransfer: { types: ['Files'], files } });
+
+ expect(terminal.input).toHaveBeenCalledWith(
+ 'pty-1',
+ "'C:\\Users\\me\\\u2018\u2018draft.md' 'C:\\Users\\me\\Nick\u2019\u2019s notes.md' 'C:\\Users\\me\\a\u201A\u201Ab.md' 'C:\\Users\\me\\a\u201B\u201Bb.md' ",
+ );
+ expect(screen.queryByTestId('terminal-path-drop-notice-banner')).toBeNull();
+ });
+
test('a Git Bash terminal POSIX-quotes dropped Windows paths', async () => {
const { bridge, terminal, pushNotice } = makeBridge(
{ ok: true, ptyId: 'pty-1' },
diff --git a/packages/core/src/handoff/terminal-launch.test.ts b/packages/core/src/handoff/terminal-launch.test.ts
index 71b3562cb..27fc6c2d9 100644
--- a/packages/core/src/handoff/terminal-launch.test.ts
+++ b/packages/core/src/handoff/terminal-launch.test.ts
@@ -3,6 +3,7 @@ import { spawnSync } from 'node:child_process';
import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
+import fc from 'fast-check';
import { describe, expect, it, vi } from 'vitest';
vi.mock('node:child_process', async (importOriginal) => {
@@ -435,6 +436,328 @@ describe('Git Bash structured launch, run by a real Bash', () => {
);
});
+const POWERSHELL_SINGLE_QUOTES = new Set(["'", '\u2018', '\u2019', '\u201A', '\u201B']);
+
+interface PowerShellLiteralReadback {
+ readonly literal: string | null;
+ readonly wholeLine: boolean;
+}
+
+function readFirstPowerShellLiteral(line: string): PowerShellLiteralReadback {
+ if (!POWERSHELL_SINGLE_QUOTES.has(line.charAt(0))) return { literal: null, wholeLine: false };
+ let literal = '';
+ let index = 1;
+ while (index < line.length) {
+ const char = line.charAt(index);
+ if (!POWERSHELL_SINGLE_QUOTES.has(char)) {
+ literal += char;
+ index += 1;
+ continue;
+ }
+ const next = line.charAt(index + 1);
+ if (!POWERSHELL_SINGLE_QUOTES.has(next)) {
+ return { literal, wholeLine: line.slice(index + 1).trim() === '' };
+ }
+ literal += next;
+ index += 2;
+ }
+ return { literal, wholeLine: false };
+}
+
+const PWSH_7_6_6_FIRST_LITERALS: ReadonlyArray<readonly [line: string, literal: string]> = [
+ ["'C:\\Users\\me\\O''Brien.md' ", "C:\\Users\\me\\O'Brien.md"],
+ ["'C:\\Users\\me\\Nick\u2019s notes.md' ", 'C:\\Users\\me\\Nick'],
+ ["'C:\\Users\\me\\\u2018draft.md' ", 'C:\\Users\\me\\'],
+ ["'C:\\Users\\me\\a\u201Ab.md' ", 'C:\\Users\\me\\a'],
+ ["'C:\\Users\\me\\a\u201Bb.md' ", 'C:\\Users\\me\\a'],
+ ["'C:\\Users\\me\\Nick\u2019\u2019s notes.md' ", 'C:\\Users\\me\\Nick\u2019s notes.md'],
+ ["'C:\\Users\\me\\Nick\u2019's notes.md' ", "C:\\Users\\me\\Nick's notes.md"],
+ [
+ "'C:\\Users\\me\\O''Brien\u2019\u2019s \u2018\u2018draft\u2019\u2019.md' ",
+ "C:\\Users\\me\\O'Brien\u2019s \u2018draft\u2019.md",
+ ],
+ [
+ "'C:\\Users\\me\\O''Brien\u2019's \u2018'draft\u2019'.md' ",
+ "C:\\Users\\me\\O'Brien's 'draft'.md",
+ ],
+ [
+ "'a\u2018\u2018b\u2019\u2019c\u201A\u201Ad\u201B\u201Be.md' ",
+ 'a\u2018b\u2019c\u201Ad\u201Be.md',
+ ],
+ ["'a\u2018'b\u2019'c\u201A'd\u201B'e.md' ", "a'b'c'd'e.md"],
+];
+
+const READ_BACK_NAMES: ReadonlyArray<readonly [label: string, name: string]> = [
+ ['a right single quotation mark', 'C:\\Users\\me\\Nick\u2019s notes.md'],
+ ['left and right single quotation marks', 'C:\\Users\\me\\\u2018draft\u2019.md'],
+ ['low-9 and high-reversed-9 quotation marks', 'C:\\Users\\me\\a\u201Ab\u201Bc.md'],
+ ['straight and curly quotes side by side', "C:\\Users\\me\\O'Brien\u2019s \u2018'\u2019 copy.md"],
+ [
+ 'curly double quotes and apostrophe-like letters',
+ 'C:\\Users\\me\\\u201ENotizen\u201C \u201Cnotes\u201D it\u02BCs 5\u2032.md',
+ ],
+];
+
+const POWERSHELL_PATH_NAME = fc.string({
+ unit: fc.constantFrom(
+ 'a',
+ 'Z',
+ ' ',
+ '\\',
+ '.',
+ "'",
+ '\u2018',
+ '\u2019',
+ '\u201A',
+ '\u201B',
+ '\u201C',
+ '\u201D',
+ '"',
+ '`',
+ '$',
+ '\u02BC',
+ '\u{1F4DD}',
+ ),
+ maxLength: 16,
+});
+
+describe('psQuoteArg with curly single quotes', () => {
+ it.each([
+ ['U+2018', '\u2018draft.md', "'\u2018\u2018draft.md'"],
+ ['U+2019', 'Nick\u2019s notes.md', "'Nick\u2019\u2019s notes.md'"],
+ ['U+201A', 'a\u201Ab.md', "'a\u201A\u201Ab.md'"],
+ ['U+201B', 'a\u201Bb.md', "'a\u201B\u201Bb.md'"],
+ ])(
+ 'doubles %s with itself, the way PowerShell escapes a single-quoted string',
+ (_codePoint, name, quoted) => {
+ expect(psQuoteArg(name)).toBe(quoted);
+ },
+ );
+});
+
+describe('psQuoteArg output read back by a model of the PowerShell tokenizer', () => {
+ it('reads the same first literal that PowerShell 7.6.6 read from each recorded line', () => {
+ expect(
+ PWSH_7_6_6_FIRST_LITERALS.map(([line]) => readFirstPowerShellLiteral(line).literal),
+ ).toEqual(PWSH_7_6_6_FIRST_LITERALS.map(([, literal]) => literal));
+ });
+
+ it.each(READ_BACK_NAMES)('reads back a name with %s exactly', (_label, name) => {
+ expect(readFirstPowerShellLiteral(psQuoteArg(name))).toEqual({
+ literal: name,
+ wholeLine: true,
+ });
+ });
+
+ it('reads back any name built from quotes, spaces and path characters exactly', () => {
+ fc.assert(
+ fc.property(POWERSHELL_PATH_NAME, (name) => {
+ expect(readFirstPowerShellLiteral(psQuoteArg(name))).toEqual({
+ literal: name,
+ wholeLine: true,
+ });
+ }),
+ { seed: 42 },
+ );
+ });
+});
+
+const POWERSHELL = process.env.OK_TEST_PWSH ?? 'pwsh';
+
+const POWERSHELL_READBACK_SCRIPT = [
+ "$ErrorActionPreference = 'Stop'",
+ '$lines = Get-Content -Raw -LiteralPath $env:OK_TEST_POWERSHELL_LINES | ConvertFrom-Json',
+ 'foreach ($line in $lines) {',
+ ' $tokens = $null',
+ ' $errors = $null',
+ ' [void][System.Management.Automation.Language.Parser]::ParseInput($line, [ref]$tokens, [ref]$errors)',
+ " $significant = @($tokens | Where-Object { $_.Kind -ne 'EndOfInput' -and $_.Kind -ne 'NewLine' })",
+ ' [ordered]@{',
+ ' errors = @($errors).Count',
+ " tokens = @($significant | ForEach-Object { [ordered]@{ kind = [string]$_.Kind; value = if ($_.Kind -eq 'StringLiteral') { $_.Value } else { $_.Text } } })",
+ ' } | ConvertTo-Json -Compress -Depth 5 -EscapeHandling EscapeNonAscii',
+ '}',
+].join('\n');
+
+interface PowerShellToken {
+ readonly kind: string;
+ readonly value: string;
+}
+
+interface PowerShellParse {
+ readonly errors: number;
+ readonly tokens: readonly PowerShellToken[];
+}
+
+function asciiJson(value: unknown): string {
+ return JSON.stringify(value).replace(/[^ -~]/gu, (char) =>
+ Array.from(
+ { length: char.length },
+ (_, index) => `\\u${char.charCodeAt(index).toString(16).padStart(4, '0')}`,
+ ).join(''),
+ );
+}
+
+function parseWithRealPowerShell(lines: readonly string[]): PowerShellParse[] | null {
+ const dir = mkdtempSync(join(tmpdir(), 'ok-powershell-readback-'));
+ try {
+ const linesPath = join(dir, 'lines.json');
+ const scriptPath = join(dir, 'readback.ps1');
+ writeFileSync(linesPath, asciiJson(lines));
+ writeFileSync(scriptPath, POWERSHELL_READBACK_SCRIPT);
+ const run = spawnSync(
+ POWERSHELL,
+ ['-NoLogo', '-NoProfile', '-NonInteractive', '-File', scriptPath],
+ {
+ ...REAL_BASH_PROBE_SPAWN_OPTIONS,
+ windowsHide: true,
+ env: {
+ ...process.env,
+ HOME: dir,
+ XDG_CACHE_HOME: join(dir, 'cache'),
+ XDG_CONFIG_HOME: join(dir, 'config'),
+ XDG_DATA_HOME: join(dir, 'data'),
+ POWERSHELL_TELEMETRY_OPTOUT: '1',
+ POWERSHELL_UPDATECHECK: 'Off',
+ OK_TEST_POWERSHELL_LINES: linesPath,
+ },
+ },
+ );
+ if ((run.error as { code?: unknown } | undefined)?.code === 'ENOENT') {
+ expect(
+ process.env.CI,
+ `${POWERSHELL} is not on PATH, and a CI run must read these lines back with a real PowerShell parser instead of skipping`,
+ ).not.toBe('true');
+ return null;
+ }
+ expect(run.error, `pwsh stderr: ${run.stderr}`).toBeUndefined();
+ expect(run.status, `pwsh stderr: ${run.stderr}`).toBe(0);
+ const parses = run.stdout
+ .split(/\r?\n/u)
+ .filter((line) => line.trim() !== '')
+ .map((line) => JSON.parse(line) as PowerShellParse);
+ expect(parses).toHaveLength(lines.length);
+ return parses;
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+}
+
+describe('psQuoteArg output read back by a real PowerShell parser', () => {
+ it('reads back every name exactly, as a value and as a command argument', (context) => {
+ const names = [
+ ...READ_BACK_NAMES.map(([, name]) => name),
+ ...fc.sample(POWERSHELL_PATH_NAME, { seed: 42, numRuns: 50 }),
+ ];
+ const recordedLines = PWSH_7_6_6_FIRST_LITERALS.map(([line]) => line);
+ const parses = parseWithRealPowerShell([
+ ...recordedLines,
+ ...names.map((name) => `${psQuoteArg(name)} `),
+ ...names.map((name) => `Write-Output ${psQuoteArg(name)} `),
+ ]);
+ if (parses === null) return context.skip(`${POWERSHELL} is not on PATH`);
+
+ expect(
+ parses
+ .slice(0, recordedLines.length)
+ .map((parse) => parse.tokens.find((token) => token.kind === 'StringLiteral')?.value),
+ ).toEqual(PWSH_7_6_6_FIRST_LITERALS.map(([, literal]) => literal));
+ expect(parses.slice(recordedLines.length, recordedLines.length + names.length)).toEqual(
+ names.map((name) => ({ errors: 0, tokens: [{ kind: 'StringLiteral', value: name }] })),
+ );
+ expect(parses.slice(recordedLines.length + names.length)).toEqual(
+ names.map((name) => ({
+ errors: 0,
+ tokens: [
+ { kind: 'Generic', value: 'Write-Output' },
+ { kind: 'StringLiteral', value: name },
+ ],
+ })),
+ );
+ });
+});
+
+const CURLY_QUOTE_LAUNCH = {
+ executable: 'C:\\Users\\me\\Nick\u2019s agents\\agent.exe',
+ args: ['--config', 'C:\\Users\\me\\\u2018work\u2019 profile.json', '--label', 'a\u201Ab\u201Bc'],
+};
+
+const CURLY_QUOTE_LAUNCH_WITH_ENV = {
+ ...CURLY_QUOTE_LAUNCH,
+ env: { AGENT_HOME: 'C:\\Users\\me\\.agent' },
+};
+
+const CURLY_QUOTE_LAUNCH_CALL =
+ "& 'C:\\Users\\me\\Nick\u2019\u2019s agents\\agent.exe' '--config' 'C:\\Users\\me\\\u2018\u2018work\u2019\u2019 profile.json' '--label' 'a\u201A\u201Ab\u201B\u201Bc'";
+
+function decodePowerShellLaunchScript(composed: string[] | string): string {
+ expect(Array.isArray(composed)).toBe(true);
+ expect(composed.slice(0, 2)).toEqual(['-NoExit', '-EncodedCommand']);
+ return Buffer.from(composed[2] ?? '', 'base64').toString('utf16le');
+}
+
+describe('PowerShell launch composition with curly single quotes', () => {
+ it('doubles each curly single quote in the executable and arguments with itself', () => {
+ expect(
+ decodePowerShellLaunchScript(composeWindowsShellLaunchArgs('pwsh.exe', CURLY_QUOTE_LAUNCH)),
+ ).toBe(CURLY_QUOTE_LAUNCH_CALL);
+ });
+
+ it('doubles them the same way in a launch that sets environment variables', () => {
+ expect(
+ decodePowerShellLaunchScript(
+ composeWindowsShellLaunchArgs('pwsh.exe', CURLY_QUOTE_LAUNCH_WITH_ENV),
+ ),
+ ).toBe(
+ "$__ok_names = @('AGENT_HOME'); $__ok_slots = @('OK_TERMINAL_LAUNCH_ENV_0'); $__ok_prev = @{}; " +
+ 'for ($__ok_i = 0; $__ok_i -lt $__ok_names.Length; $__ok_i++) { ' +
+ '$__ok_prev[$__ok_names[$__ok_i]] = [Environment]::GetEnvironmentVariable($__ok_names[$__ok_i]); ' +
+ "[Environment]::SetEnvironmentVariable($__ok_names[$__ok_i], [Environment]::GetEnvironmentVariable($__ok_slots[$__ok_i]), 'Process') }; " +
+ `try { ${CURLY_QUOTE_LAUNCH_CALL} } finally { ` +
+ 'for ($__ok_i = 0; $__ok_i -lt $__ok_names.Length; $__ok_i++) { ' +
+ "[Environment]::SetEnvironmentVariable($__ok_names[$__ok_i], $__ok_prev[$__ok_names[$__ok_i]], 'Process'); " +
+ "[Environment]::SetEnvironmentVariable($__ok_slots[$__ok_i], $null, 'Process') }; " +
+ 'Remove-Variable __ok_names, __ok_slots, __ok_prev, __ok_i -ErrorAction SilentlyContinue }',
+ );
+ });
+});
+
+describe('PowerShell launch composition read back by a real PowerShell parser', () => {
+ it('reads the call back as one string per launch token, with and without environment variables', (context) => {
+ const parses = parseWithRealPowerShell([
+ decodePowerShellLaunchScript(composeWindowsShellLaunchArgs('pwsh.exe', CURLY_QUOTE_LAUNCH)),
+ decodePowerShellLaunchScript(
+ composeWindowsShellLaunchArgs('pwsh.exe', CURLY_QUOTE_LAUNCH_WITH_ENV),
+ ),
+ ]);
+ if (parses === null) return context.skip(`${POWERSHELL} is not on PATH`);
+
+ const call = [
+ { kind: 'Ampersand', value: '&' },
+ ...[CURLY_QUOTE_LAUNCH.executable, ...CURLY_QUOTE_LAUNCH.args].map((value) => ({
+ kind: 'StringLiteral',
+ value,
+ })),
+ ];
+ const [plain, withEnv] = parses;
+ expect(plain).toEqual({ errors: 0, tokens: call });
+ const callStart = withEnv?.tokens.findIndex((token) => token.kind === 'Ampersand') ?? -1;
+ expect({
+ errors: withEnv?.errors,
+ tryBlock: withEnv?.tokens.slice(callStart - 2, callStart + call.length + 2),
+ }).toEqual({
+ errors: 0,
+ tryBlock: [
+ { kind: 'Try', value: 'try' },
+ { kind: 'LCurly', value: '{' },
+ ...call,
+ { kind: 'RCurly', value: '}' },
+ { kind: 'Finally', value: 'finally' },
+ ],
+ });
+ });
+});
+
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(
diff --git a/packages/core/src/handoff/terminal-launch.ts b/packages/core/src/handoff/terminal-launch.ts
index 3d52c1a6b..2a993fab7 100644
--- a/packages/core/src/handoff/terminal-launch.ts
+++ b/packages/core/src/handoff/terminal-launch.ts
@@ -39,8 +39,10 @@ export function isWindowsShellFamily(value: unknown): value is WindowsShellFamil
return typeof value === 'string' && WINDOWS_SHELL_FAMILIES.has(value as WindowsShellFamily);
}
+const POWERSHELL_SINGLE_QUOTE = /['\u2018\u2019\u201A\u201B]/g;
+
export function psQuoteArg(value: string): string {
- return `'${value.replace(/'/g, "''")}'`;
+ return `'${value.replace(POWERSHELL_SINGLE_QUOTE, '$&$&')}'`;
}
function encodeUtf8Base64(value: string): string {