Beautiful, AI-native markdown IDE and LLM wiki
TypeScript 2nd-brainagent-skillsclaudecodexcompany-braindocsknowledge-knowledge-baseknowledge-managementllmllm-wikillm-wiki-karpathymarkdownmarkdown-editormdmdxnotespkmsecond-brainskills
fix(ok): isolate Windows terminal smoke shell state per run (#4515)
Nick Gomez4f9e4a880a04
diff --git a/packages/desktop/tests/smoke/_helpers/platform-gate.ts b/packages/desktop/tests/smoke/_helpers/platform-gate.tsindex 130dcad2d..44aa34bee 100644--- a/packages/desktop/tests/smoke/_helpers/platform-gate.ts+++ b/packages/desktop/tests/smoke/_helpers/platform-gate.ts@@ -58,7 +58,7 @@ export const SPEC_PLATFORM_GATES = {'terminal-links.e2e.ts': ['!PTY_PLATFORM_SUPPORTED'],'terminal-movement.e2e.ts': ['!PTY_PLATFORM_SUPPORTED'],'terminal-process-restart.e2e.ts': ['!PTY_PLATFORM_SUPPORTED'],- 'terminal-tabs.e2e.ts': ['!PTY_PLATFORM_SUPPORTED'],+ 'terminal-tabs.e2e.ts': ['!PTY_PLATFORM_SUPPORTED', '!WINDOWS'],'terminal-window.e2e.ts': ['!PTY_PLATFORM_SUPPORTED'],'theme-sync.e2e.ts': ['!DARWIN'],'uninstall-ipc-bridge.e2e.ts': ['!DARWIN'],diff --git a/packages/desktop/tests/smoke/_helpers/terminal-smoke-shell.ts b/packages/desktop/tests/smoke/_helpers/terminal-smoke-shell.tsindex 7893f96f0..8a1f7218b 100644--- a/packages/desktop/tests/smoke/_helpers/terminal-smoke-shell.ts+++ b/packages/desktop/tests/smoke/_helpers/terminal-smoke-shell.ts@@ -1,10 +1,16 @@import { randomUUID } from 'node:crypto';-import { mkdirSync, writeFileSync } from 'node:fs';+import { mkdirSync, readFileSync, writeFileSync } from 'node:fs';import { join, win32 } from 'node:path';import { psQuoteArg } from '@inkeep/open-knowledge-core';import { getWindowsEnvValue, windowsPathKey } from '../../../src/shared/windows-env.ts';const POSIX_SYSTEM_PATH = '/usr/bin:/bin:/usr/sbin:/sbin';+const WINDOWS_PSREADLINE_HISTORY_SEGMENTS = ['PSReadLine', 'ConsoleHost_history.txt'] as const;+const WINDOWS_PROFILE_DIRECTORIES = ['PowerShell', 'WindowsPowerShell'] as const;+const WINDOWS_PROFILE_FILE = 'Microsoft.PowerShell_profile.ps1';+const PSREADLINE_PREDICTION_FLOOR = '2.1.0';+const UTF8_BOM = '\ufeff';+const WINDOWS_PROFILE_FAILURE_FILE = 'ok-shell-profile-error.log';function quotePosix(value: string): string {return `'${value.replaceAll("'", "'\\''")}'`;@@ -132,8 +138,8 @@ export function terminalSmokeEnvironment(}interface TerminalShellProfileOptions {- pathPrefix?: string;- restrictPath?: boolean;+ posixPathPrefix?: string;+ posixRestrictPath?: boolean;}export function seedTerminalShellProfiles(@@ -141,12 +147,21 @@ export function seedTerminalShellProfiles(options: TerminalShellProfileOptions,platform: NodeJS.Platform = process.platform,): void {- if (platform === 'win32') return;+ if (platform === 'win32') {+ const profile = windowsShellProfile(tmpHome);+ for (const directory of WINDOWS_PROFILE_DIRECTORIES) {+ const profileDirectory = join(tmpHome, 'Documents', directory);+ mkdirSync(profileDirectory, { recursive: true });+ writeFileSync(join(profileDirectory, WINDOWS_PROFILE_FILE), profile);+ }+ return;+ }+ if (!options.posixPathPrefix && !options.posixRestrictPath) return;const path = terminalSmokeEnvironment(tmpHome, {env: { PATH: process.env.PATH },- pathPrefix: options.pathPrefix,+ pathPrefix: options.posixPathPrefix,platform,- restrictPath: options.restrictPath,+ restrictPath: options.posixRestrictPath,}).PATH;const escapedPath = path.replace(/["\\$`]/g, '\\$&');const profile = `export PATH="${escapedPath}"\n`;@@ -154,6 +169,95 @@ export function seedTerminalShellProfiles(writeFileSync(join(tmpHome, '.zshrc'), profile);}+export function windowsPSReadLineHistoryPath(tmpHome: string): string {+ return win32.join(tmpHome, ...WINDOWS_PSREADLINE_HISTORY_SEGMENTS);+}++export function windowsShellProfileFailurePath(tmpHome: string): string {+ return win32.join(tmpHome, WINDOWS_PROFILE_FAILURE_FILE);+}++/*+ * UPSTREAM(PowerShell/PSReadLine#2189): the host supplies PSReadLine, so a bundled version older+ * than a parameter rejects it with a statement-terminating error.+ */+function windowsShellProfile(tmpHome: string): string {+ const history = psQuoteArg(windowsPSReadLineHistoryPath(tmpHome));+ const failure = psQuoteArg(windowsShellProfileFailurePath(tmpHome));+ return (+ UTF8_BOM ++ [+ 'try {',+ ' Import-Module PSReadLine -ErrorAction SilentlyContinue',+ ' $okPSReadLine = Get-Module PSReadLine',+ ' if ($okPSReadLine) {',+ ` Set-PSReadLineOption -HistorySavePath ${history}`,+ ` if ($okPSReadLine.Version -ge [version]'${PSREADLINE_PREDICTION_FLOOR}') {`,+ ' Set-PSReadLineOption -PredictionSource None',+ ' }',+ ' }',+ `} catch { $_ | Out-String | Set-Content -LiteralPath ${failure} -Encoding utf8 -ErrorAction SilentlyContinue }`,+ '',+ ].join('\r\n')+ );+}++export type WindowsShellProfileFailure =+ | { readonly kind: 'absent' }+ | { readonly kind: 'record'; readonly text: string }+ | { readonly kind: 'unreadable'; readonly code: string };++export function readWindowsShellProfileFailure(home: string): WindowsShellProfileFailure {+ const path = windowsShellProfileFailurePath(home);+ let text: string;+ try {+ text = readFileSync(path, 'utf8');+ } catch (error) {+ const code = (error as NodeJS.ErrnoException | null)?.code;+ if (code === 'ENOENT') return { kind: 'absent' };+ return { kind: 'unreadable', code: code ?? String(error) };+ }+ const trimmed = text.trim();+ return trimmed ? { kind: 'record', text: trimmed } : { kind: 'absent' };+}++export const WINDOWS_PSREADLINE_STATE_ABSENT = 'absent';+export const WINDOWS_PSREADLINE_PREDICTION_UNSUPPORTED = 'unsupported';+const WINDOWS_PSREADLINE_STATE_END = 'END';++export type WindowsPSReadLineStateField = 'version' | 'prediction' | 'history';++const WINDOWS_PSREADLINE_STATE_GROUPS = {+ version: 1,+ prediction: 2,+ history: 3,+} as const satisfies Record<WindowsPSReadLineStateField, number>;++export function windowsPSReadLineStateField(+ marker: string,+ text: string,+ field: WindowsPSReadLineStateField,+): string | null {+ const match = new RegExp(+ `${marker}=([^|]*)\\|([^|]*)\\|([^|]*)\\|${WINDOWS_PSREADLINE_STATE_END}`,+ ).exec(text);+ if (!match) return null;+ return match[WINDOWS_PSREADLINE_STATE_GROUPS[field]] ?? null;+}++export function windowsPSReadLineStateCommand(marker: string, tmpHome: string): string {+ const home = psQuoteArg(tmpHome);+ const absent = psQuoteArg(WINDOWS_PSREADLINE_STATE_ABSENT);+ return [+ '$okModule = Get-Module PSReadLine',+ '$okOptions = if ($okModule) { Get-PSReadLineOption } else { $null }',+ `$okVersion = if ($okModule) { [string]$okModule.Version } else { ${absent} }`,+ `$okPrediction = if (-not $okOptions) { ${absent} } elseif ($okOptions.PSObject.Properties['PredictionSource']) { [string]$okOptions.PredictionSource } else { ${psQuoteArg(WINDOWS_PSREADLINE_PREDICTION_UNSUPPORTED)} }`,+ `$okHistory = if ($okOptions) { [string]$okOptions.HistorySavePath.StartsWith(${home}, [System.StringComparison]::OrdinalIgnoreCase) } else { ${absent} }`,+ `Write-Output (${psQuoteArg(marker)} + '=' + $okVersion + '|' + $okPrediction + '|' + $okHistory + '|' + ${psQuoteArg(WINDOWS_PSREADLINE_STATE_END)})`,+ ].join('; ');+}+export type FakeClaudeMode = 'interactive' | 'version';export function writeFakeClaudeShim(diff --git a/packages/desktop/tests/smoke/terminal-collection-size.json b/packages/desktop/tests/smoke/terminal-collection-size.jsonindex 93cd1413e..c45fb8519 100644--- a/packages/desktop/tests/smoke/terminal-collection-size.json+++ b/packages/desktop/tests/smoke/terminal-collection-size.json@@ -1,4 +1,4 @@{"$comment": "Total tests collected by `playwright test tests/smoke/terminal-*.e2e.ts`, skipped ones included. Inkeep runs that collection sharded across parallel Windows CI cells and sums each shard's Playwright JSON stats against this number, so a shard that never ran cannot leave part of the collection unexecuted while every cell reads green. That guard and the workflow driving it live in Inkeep's internal monorepo, so whether a stale number fails anything depends on which checkout you are reading: it does there, and in the public mirror the guard is absent and nothing reads this file. Add or remove a terminal smoke test and this number moves with it either way; the guard prints the observed total when the two disagree.",- "terminalSmokeTestCount": 42+ "terminalSmokeTestCount": 43}diff --git a/packages/desktop/tests/smoke/terminal-dock.e2e.ts b/packages/desktop/tests/smoke/terminal-dock.e2e.tsindex 2ddee79c1..f572d7607 100644--- a/packages/desktop/tests/smoke/terminal-dock.e2e.ts+++ b/packages/desktop/tests/smoke/terminal-dock.e2e.ts@@ -21,6 +21,7 @@ import {import { expect, test } from './_helpers/smoke-test';import { waitForShellReady } from './_helpers/terminal-ready';import {+ buildInputReadyProbe,seedTerminalShellProfiles,terminalSmokeEnvironment,terminalSmokeShellCommands,@@ -78,12 +79,10 @@ function seed(prefix: string, opts: SeedOpts = {}): Seed {writeFakeClaudeShim(binDir, opts.fakeClaudeTui ? 'interactive' : 'version');pathPrefix = binDir;}- if (pathPrefix || opts.pinRestrictedPath) {- seedTerminalShellProfiles(tmpHome, {- ...(pathPrefix ? { pathPrefix } : {}),- restrictPath: opts.pinRestrictedPath,- });- }+ seedTerminalShellProfiles(tmpHome, {+ posixPathPrefix: pathPrefix ?? undefined,+ posixRestrictPath: opts.pinRestrictedPath,+ });const userDataDir = userDataDirFor(tmpHome);mkdirSync(userDataDir, { recursive: true });@@ -674,10 +673,11 @@ test.describe('Docked terminal — live Electron', () => {const tail = basename(s.realProjectDir);await expect.poll(() => readTerminalText(page), { timeout: 15_000 }).toContain(tail);- await typeInTerminal(page, `${SHELL_COMMANDS.output('OK_E2E_MARKER_123')}\r`);+ const afterMarker = buildInputReadyProbe();+ await typeInTerminal(page, `${afterMarker.command}\r`);await expect.poll(() => readTerminalText(page), { timeout: 15_000 })- .toContain('OK_E2E_MARKER_123');+ .toContain(afterMarker.marker);});test('a window-resize storm keeps the shell responsive and settles the PTY at the fitted grid', async ({@@ -920,8 +920,11 @@ test.describe('Docked terminal — live Electron', () => {await restart.click();await waitForStatus(page, 'running', 25_000);- await typeInTerminal(page, `${SHELL_COMMANDS.output('RESTARTED_OK')}\r`);- await expect.poll(() => readTerminalText(page), { timeout: 10_000 }).toContain('RESTARTED_OK');+ const afterRestart = buildInputReadyProbe();+ await typeInTerminal(page, `${afterRestart.command}\r`);+ await expect+ .poll(() => readTerminalText(page), { timeout: 15_000 })+ .toContain(afterRestart.marker);});test('QA-017 plain terminal stays quiet; missing Claude launch shows Get-Claude-Code banner', async ({diff --git a/packages/desktop/tests/smoke/terminal-links.e2e.ts b/packages/desktop/tests/smoke/terminal-links.e2e.tsindex 7cc58eb19..d5f8a57c4 100644--- a/packages/desktop/tests/smoke/terminal-links.e2e.ts+++ b/packages/desktop/tests/smoke/terminal-links.e2e.ts@@ -42,7 +42,7 @@ function seed(prefix: string): Seed {const binDir = join(tmpHome, 'fakebin');writeFakeClaudeShim(binDir, 'version');- seedTerminalShellProfiles(tmpHome, { pathPrefix: binDir });+ seedTerminalShellProfiles(tmpHome, { posixPathPrefix: binDir });const userDataDir = userDataDirFor(tmpHome);mkdirSync(userDataDir, { recursive: true });diff --git a/packages/desktop/tests/smoke/terminal-movement.e2e.ts b/packages/desktop/tests/smoke/terminal-movement.e2e.tsindex 1a2360832..f00db7822 100644--- a/packages/desktop/tests/smoke/terminal-movement.e2e.ts+++ b/packages/desktop/tests/smoke/terminal-movement.e2e.ts@@ -46,7 +46,7 @@ function seed({ skipRestoreState = false }: { skipRestoreState?: boolean } = {})writeFileSync(join(projectDir, '.ok', 'config.yml'), "content:\n dir: '.'\n");writeFileSync(join(projectDir, '.ok', 'local', 'config.yml'), 'terminal:\n enabled: true\n');writeFileSync(join(projectDir, 'start.md'), '# Start\n\nTerminal movement smoke.\n');- seedTerminalShellProfiles(tmpHome, { restrictPath: true });+ seedTerminalShellProfiles(tmpHome, { posixRestrictPath: true });const userDataDir = userDataDirFor(tmpHome);mkdirSync(userDataDir, { recursive: true });diff --git a/packages/desktop/tests/smoke/terminal-process-restart.e2e.ts b/packages/desktop/tests/smoke/terminal-process-restart.e2e.tsindex fc060d3d1..45884426c 100644--- a/packages/desktop/tests/smoke/terminal-process-restart.e2e.ts+++ b/packages/desktop/tests/smoke/terminal-process-restart.e2e.ts@@ -41,7 +41,7 @@ function seedRestartProfile(): RestartSeed {writeFileSync(join(projectDir, '.ok', 'config.yml'), "content:\n dir: '.'\n");writeFileSync(join(projectDir, '.ok', 'local', 'config.yml'), 'terminal:\n enabled: true\n');writeFileSync(join(projectDir, 'start.md'), '# Terminal restart\n');- seedTerminalShellProfiles(tmpHome, { restrictPath: true });+ seedTerminalShellProfiles(tmpHome, { posixRestrictPath: true });const userDataDir = userDataDirFor(tmpHome);mkdirSync(userDataDir, { recursive: true });writeFileSync(diff --git a/packages/desktop/tests/smoke/terminal-tabs.e2e.ts b/packages/desktop/tests/smoke/terminal-tabs.e2e.tsindex e758387a1..54f14509b 100644--- a/packages/desktop/tests/smoke/terminal-tabs.e2e.ts+++ b/packages/desktop/tests/smoke/terminal-tabs.e2e.ts@@ -13,9 +13,15 @@ import {import { expect, test } from './_helpers/smoke-test';import { waitForShellReady } from './_helpers/terminal-ready';import {+ buildInputReadyProbe,+ readWindowsShellProfileFailure,seedTerminalShellProfiles,terminalSmokeEnvironment,terminalSmokeShellCommands,+ WINDOWS_PSREADLINE_PREDICTION_UNSUPPORTED,+ type WindowsPSReadLineStateField,+ windowsPSReadLineStateCommand,+ windowsPSReadLineStateField,} from './_helpers/terminal-smoke-shell';import {expectTerminalTabOrder,@@ -31,6 +37,7 @@ const TARGET = resolveDesktopTarget();const SMOKE_ENABLED = process.env.OK_DESKTOP_E2E_SMOKE === '1';const PRIMARY_MODIFIER = process.platform === 'darwin' ? 'Meta' : 'Control';+const WINDOWS = process.platform === 'win32';const SHELL_COMMANDS = terminalSmokeShellCommands();interface Seed {@@ -46,7 +53,7 @@ function seed(prefix: string): Seed {writeFileSync(join(projectDir, '.ok', 'config.yml'), "content:\n dir: '.'\n");writeFileSync(join(projectDir, '.ok', 'local', 'config.yml'), 'terminal:\n enabled: true\n');writeFileSync(join(projectDir, 'start.md'), '# Start\n\nSeed document.\n');- seedTerminalShellProfiles(tmpHome, { restrictPath: true });+ seedTerminalShellProfiles(tmpHome, { posixRestrictPath: true });const userDataDir = userDataDirFor(tmpHome);mkdirSync(userDataDir, { recursive: true });@@ -329,8 +336,11 @@ test.describe('Terminal tabs — live Electron', () => {.click();await expectTerminalTabOrder(page, [survivingTabId]);await waitActiveRunning(page);- await typeInActive(page, `${SHELL_COMMANDS.output('SURVIVOR_CCC')}\r`);- await expect.poll(() => readActiveText(page), { timeout: 15_000 }).toContain('SURVIVOR_CCC');+ const afterSurvivor = buildInputReadyProbe();+ await typeInActive(page, `${afterSurvivor.command}\r`);+ await expect+ .poll(() => readActiveText(page), { timeout: 15_000 })+ .toContain(afterSurvivor.marker);});test('a manual rename pins over the program’s OSC title', async ({ captureStderrFor }) => {@@ -340,16 +350,75 @@ test.describe('Terminal tabs — live Electron', () => {const page = await findEditorWindow(app);await openTerminal(app, page);+ await typeInActive(page, `${SHELL_COMMANDS.oscTitle('PROGRAM_TITLE_ZZZ', 'OSC_FED_QQQ')}\r`);+ const afterProgramTitle = buildInputReadyProbe();+ await typeInActive(page, `${afterProgramTitle.command}\r`);+ await expect+ .poll(() => readActiveText(page), { timeout: 15_000 })+ .toContain(afterProgramTitle.marker);+ await expect(page.getByRole('tab', { name: 'PROGRAM_TITLE_ZZZ' })).toHaveCount(1, {+ timeout: 5_000,+ });+await terminalTabs(page).first().dblclick();const input = page.getByRole('textbox', { name: /^Rename/ });await input.fill('my build');await input.press('Enter');await expect(page.getByRole('tab', { name: 'my build' })).toBeVisible({ timeout: 5_000 });- await typeInActive(page, `${SHELL_COMMANDS.oscTitle('PROGRAM_TITLE_ZZZ', 'OSC_FED_QQQ')}\r`);- await expect.poll(() => readActiveText(page), { timeout: 15_000 }).toContain('OSC_FED_QQQ');+ await typeInActive(page, `${SHELL_COMMANDS.oscTitle('LATER_TITLE_XXX', 'OSC_LATER_PPP')}\r`);+ const afterOscTitle = buildInputReadyProbe();+ await typeInActive(page, `${afterOscTitle.command}\r`);+ await expect+ .poll(() => readActiveText(page), { timeout: 15_000 })+ .toContain(afterOscTitle.marker);await expect(terminalTabs(page)).toHaveText(['my build']);- await expect(page.getByRole('tab', { name: 'PROGRAM_TITLE_ZZZ' })).toHaveCount(0);++ await terminalTabs(page).first().dblclick();+ const clearLabel = page.getByRole('textbox', { name: /^Rename/ });+ await clearLabel.fill('');+ await clearLabel.press('Enter');+ await expect(terminalTabs(page)).toHaveText(['LATER_TITLE_XXX'], { timeout: 5_000 });+ });++ test('the seeded profile pins the shell’s PSReadLine state inside the run home', async ({+ captureStderrFor,+ }) => {+ test.skip(!WINDOWS, 'PSReadLine state only exists on the Windows shell rungs.');+ const s = seed('psreadline-state');+ const app = await launchApp(s);+ captureStderrFor(app, { home: s.tmpHome, cleanupDirs: [s.tmpHome, s.projectDir] });+ const page = await findEditorWindow(app);+ await openTerminal(app, page);++ expect(+ readWindowsShellProfileFailure(s.tmpHome),+ 'kind "record" is the seeded profile reporting its own failure; kind "unreadable" is a runner fault reading the harness log, not evidence about the profile',+ ).toEqual({ kind: 'absent' });++ const marker = `PSRL_STATE_${Date.now().toString(36)}`;+ const stateField = async (field: WindowsPSReadLineStateField): Promise<string | null> =>+ windowsPSReadLineStateField(marker, await readActiveText(page), field);+ await typeInActive(page, `${windowsPSReadLineStateCommand(marker, s.tmpHome)}\r`);++ await expect+ .poll(() => stateField('version'), {+ message: 'the shell reported no loaded PSReadLine for the profile to configure',+ timeout: 15_000,+ })+ .toMatch(/^\d+\.\d+/);+ await expect+ .poll(() => stateField('history'), {+ message: 'the PSReadLine history file resolved outside the run home',+ timeout: 5_000,+ })+ .toBe('True');+ await expect+ .poll(() => stateField('prediction'), {+ message: 'inline prediction stayed on, so other tests can bleed into the scraped buffer',+ timeout: 5_000,+ })+ .toMatch(new RegExp(`^(None|${WINDOWS_PSREADLINE_PREDICTION_UNSUPPORTED})$`));});test('keyboard reorder changes order, keeps sticky numbers, and preserves the live shell', async ({@@ -362,10 +431,14 @@ test.describe('Terminal tabs — live Electron', () => {await openTerminal(app, page);await typeInActive(page, `${SHELL_COMMANDS.setEnvironment('OK_TABMARK', 'SURVIVED_888')}\r`);- await typeInActive(page, `${SHELL_COMMANDS.output('BEFORE_REORDER_DDD')}\r`);+ if (!WINDOWS) {+ await typeInActive(page, `${SHELL_COMMANDS.output('BEFORE_REORDER_DDD')}\r`);+ }+ const beforeReorder = buildInputReadyProbe();+ await typeInActive(page, `${beforeReorder.command}\r`);await expect.poll(() => readActiveText(page), { timeout: 15_000 })- .toContain('BEFORE_REORDER_DDD');+ .toContain(beforeReorder.marker);const [firstTabId] = await terminalTabIds(page);if (firstTabId === undefined) throw new Error('first terminal tab was not created');@@ -384,7 +457,7 @@ test.describe('Terminal tabs — live Electron', () => {}await expect(terminalTabById(page, firstTabId)).toHaveAttribute('aria-selected', 'true');- if (process.platform !== 'win32') {+ if (!WINDOWS) {await expect.poll(() => readActiveText(page), { timeout: 15_000 }).toContain('BEFORE_REORDER_DDD');@@ -408,8 +481,12 @@ test.describe('Terminal tabs — live Electron', () => {page,`${SHELL_COMMANDS.setEnvironment('OK_DRAGMARK', 'DRAG_SURVIVED_444')}\r`,);- await typeInActive(page, `${SHELL_COMMANDS.output('BEFORE_DRAG_EEE')}\r`);- await expect.poll(() => readActiveText(page), { timeout: 15_000 }).toContain('BEFORE_DRAG_EEE');+ if (!WINDOWS) {+ await typeInActive(page, `${SHELL_COMMANDS.output('BEFORE_DRAG_EEE')}\r`);+ }+ const beforeDrag = buildInputReadyProbe();+ await typeInActive(page, `${beforeDrag.command}\r`);+ await expect.poll(() => readActiveText(page), { timeout: 15_000 }).toContain(beforeDrag.marker);const [firstTabId] = await terminalTabIds(page);if (firstTabId === undefined) throw new Error('first terminal tab was not created');@@ -426,7 +503,7 @@ test.describe('Terminal tabs — live Electron', () => {await activateTab(terminalTabById(page, firstTabId));await visibleSection(page).locator('.xterm').click();- if (process.platform !== 'win32') {+ if (!WINDOWS) {expect(await readActiveText(page)).toContain('BEFORE_DRAG_EEE');}await typeInActive(page, `${SHELL_COMMANDS.readEnvironment('OK_DRAGMARK', 'dm')}\r`);diff --git a/packages/desktop/tests/smoke/terminal-window.e2e.ts b/packages/desktop/tests/smoke/terminal-window.e2e.tsindex b953e04c1..caaa8c719 100644--- a/packages/desktop/tests/smoke/terminal-window.e2e.ts+++ b/packages/desktop/tests/smoke/terminal-window.e2e.ts@@ -34,7 +34,7 @@ function seed(prefix: string): Seed {writeFileSync(join(projectDir, '.ok', 'config.yml'), "content:\n dir: '.'\n");writeFileSync(join(projectDir, '.ok', 'local', 'config.yml'), 'terminal:\n enabled: true\n');writeFileSync(join(projectDir, 'start.md'), '# Start\n\nSeed document.\n');- seedTerminalShellProfiles(tmpHome, { restrictPath: true });+ seedTerminalShellProfiles(tmpHome, { posixRestrictPath: true });const userDataDir = userDataDirFor(tmpHome);mkdirSync(userDataDir, { recursive: true });diff --git a/packages/desktop/tests/unit/terminal-smoke-shell.test.ts b/packages/desktop/tests/unit/terminal-smoke-shell.test.tsindex 73a2e8dfb..cb30307d4 100644--- a/packages/desktop/tests/unit/terminal-smoke-shell.test.ts+++ b/packages/desktop/tests/unit/terminal-smoke-shell.test.ts@@ -1,11 +1,24 @@-import { existsSync, mkdtempSync, readFileSync, rmSync, statSync } from 'node:fs';+import {+ existsSync,+ mkdirSync,+ mkdtempSync,+ readFileSync,+ rmSync,+ statSync,+ writeFileSync,+} from 'node:fs';import { tmpdir } from 'node:os';-import { join } from 'node:path';+import { join, win32 } from 'node:path';import { afterEach, describe, expect, test } from 'vitest';import {+ readWindowsShellProfileFailure,seedTerminalShellProfiles,terminalSmokeEnvironment,terminalSmokeShellCommands,+ windowsPSReadLineHistoryPath,+ windowsPSReadLineStateCommand,+ windowsPSReadLineStateField,+ windowsShellProfileFailurePath,writeFakeClaudeShim,} from '../smoke/_helpers/terminal-smoke-shell.ts';@@ -37,6 +50,7 @@ describe('terminal smoke shell commands', () => {'Write-Output "marker=[$env:OK_MARK]"',);expect(commands.processId('SHELLPID')).toBe('Write-Output "SHELLPID=$PID"');+ expect(commands.output('MARK_ONE')).toBe("Write-Output 'MARK_ONE'");expect(commands.oscTitle('program', 'OSC_FED')).toBe('[Console]::Write("$([char]27)]0;program$([char]7)"); Write-Output \'OSC_FED\'',);@@ -54,6 +68,7 @@ describe('terminal smoke shell commands', () => {expect(commands.setEnvironment('OK_MARK', 'survived')).toBe("export OK_MARK='survived'");expect(commands.readEnvironment('OK_MARK', 'marker')).toBe('echo "marker=[$OK_MARK]"');expect(commands.processId('SHELLPID')).toBe('printf \'SHELLPID=%s\\n\' "$$"');+ expect(commands.output('MARK_ONE')).toBe("printf '%s\\n' 'MARK_ONE'");}});});@@ -110,18 +125,18 @@ describe('terminal smoke shell fixtures', () => {expect(readFileSync(windowsPath, 'utf8')).toContain('more.com');});- test('writes login profiles only for POSIX shells', () => {+ test('writes a zsh login profile for POSIX and no zsh profile for Windows', () => {const posixHome = temporaryDirectory('ok-terminal-posix-home-');const windowsHome = temporaryDirectory('ok-terminal-windows-home-');seedTerminalShellProfiles(posixHome,- { pathPrefix: '/tmp/fake-bin', restrictPath: true },+ { posixPathPrefix: '/tmp/fake-bin', posixRestrictPath: true },'linux',);seedTerminalShellProfiles(windowsHome,- { pathPrefix: 'C:\\fake-bin', restrictPath: true },+ { posixPathPrefix: 'C:\\fake-bin', posixRestrictPath: true },'win32',);@@ -134,4 +149,126 @@ describe('terminal smoke shell fixtures', () => {expect(existsSync(join(windowsHome, '.zprofile'))).toBe(false);expect(existsSync(join(windowsHome, '.zshrc'))).toBe(false);});++ test('leaves the POSIX login PATH alone when no PATH option asks for it, and still seeds Windows', () => {+ const posixHome = temporaryDirectory('ok-terminal-posix-unpinned-');+ const posixFalse = temporaryDirectory('ok-terminal-posix-restrict-false-');+ const windowsHome = temporaryDirectory('ok-terminal-windows-unpinned-');++ seedTerminalShellProfiles(posixHome, {}, 'linux');+ seedTerminalShellProfiles(posixFalse, { posixRestrictPath: false }, 'linux');+ seedTerminalShellProfiles(windowsHome, {}, 'win32');++ expect(existsSync(join(posixHome, '.zprofile'))).toBe(false);+ expect(existsSync(join(posixHome, '.zshrc'))).toBe(false);+ expect(existsSync(join(posixFalse, '.zprofile'))).toBe(false);+ expect(existsSync(join(posixFalse, '.zshrc'))).toBe(false);+ expect(+ existsSync(join(windowsHome, 'Documents', 'PowerShell', 'Microsoft.PowerShell_profile.ps1')),+ ).toBe(true);+ });++ test('seeds a PowerShell profile that pins history per run, turns prediction off, and cannot write to the terminal, for both Windows shell rungs', () => {+ const windowsHome = temporaryDirectory('ok-terminal-windows-profile-');++ seedTerminalShellProfiles(windowsHome, {}, 'win32');++ for (const directory of ['PowerShell', 'WindowsPowerShell']) {+ const profile = readFileSync(+ join(windowsHome, 'Documents', directory, 'Microsoft.PowerShell_profile.ps1'),+ 'utf8',+ );+ expect(profile.startsWith('\ufeff')).toBe(true);+ expect(profile).toContain(+ `Set-PSReadLineOption -HistorySavePath '${windowsPSReadLineHistoryPath(windowsHome)}'`,+ );+ expect(profile).toContain('Set-PSReadLineOption -PredictionSource None');+ expect(profile).toContain('Import-Module PSReadLine -ErrorAction SilentlyContinue');+ }+ });++ test('records a profile failure where the harness reads it back, never on the terminal', () => {+ const windowsHome = temporaryDirectory('ok-terminal-profile-failure-');+ const failurePath = windowsShellProfileFailurePath(windowsHome);+ cleanup.push(failurePath);++ seedTerminalShellProfiles(windowsHome, {}, 'win32');++ expect(readWindowsShellProfileFailure(windowsHome)).toEqual({ kind: 'absent' });++ const profile = readFileSync(+ join(windowsHome, 'Documents', 'PowerShell', 'Microsoft.PowerShell_profile.ps1'),+ 'utf8',+ );+ expect(/Set-Content -LiteralPath '([^']*)'/.exec(profile)?.[1]).toBe(failurePath);++ const record = [+ 'Set-PSReadLineOption : A parameter cannot be found that matches parameter name',+ "'PredictionSource'.",+ 'At C:\\Users\\runner\\Documents\\PowerShell\\Microsoft.PowerShell_profile.ps1:7 char:26',+ '+ Set-PSReadLineOption -PredictionSource None',+ ' + CategoryInfo : InvalidArgument: (:) [Set-PSReadLineOption], ParameterBindingException',+ ' + FullyQualifiedErrorId : NamedParameterNotFound,Microsoft.PowerShell.PSConsoleReadLine',+ ].join('\r\n');+ writeFileSync(failurePath, `\r\n${record}\r\n\r\n`);+ expect(readWindowsShellProfileFailure(windowsHome)).toEqual({ kind: 'record', text: record });++ writeFileSync(failurePath, ' \r\n\t\n');+ expect(readWindowsShellProfileFailure(windowsHome)).toEqual({ kind: 'absent' });+ });++ test('reports an unreadable failure record as unreadable, not as no record', () => {+ const windowsHome = temporaryDirectory('ok-terminal-profile-unreadable-');+ const failurePath = windowsShellProfileFailurePath(windowsHome);+ mkdirSync(failurePath, { recursive: true });+ cleanup.push(failurePath);++ const outcome = readWindowsShellProfileFailure(windowsHome);++ expect(outcome).toEqual({ kind: 'unreadable', code: 'EISDIR' });+ });++ test('keeps the profile failure record strictly inside the run home', () => {+ const relative = win32.relative('C:\\run-home', windowsShellProfileFailurePath('C:\\run-home'));++ expect(relative).toBe('ok-shell-profile-error.log');+ });++ test('keeps the PSReadLine history file strictly inside the run home', () => {+ const relative = win32.relative('C:\\run-home', windowsPSReadLineHistoryPath('C:\\run-home'));++ expect(relative).not.toBe('');+ expect(relative.startsWith('..')).toBe(false);+ expect(win32.isAbsolute(relative)).toBe(false);+ });++ test('builds a PSReadLine state probe that compares against the run home and never echoes its own marker', () => {+ const command = windowsPSReadLineStateCommand('PSRL_FIXED', 'C:\\run home');++ expect(command).not.toContain('PSRL_FIXED=');+ expect(command).toContain(+ "$okOptions.HistorySavePath.StartsWith('C:\\run home', [System.StringComparison]::OrdinalIgnoreCase)",+ );+ expect(command).toContain(+ "Write-Output ('PSRL_FIXED' + '=' + $okVersion + '|' + $okPrediction + '|' + $okHistory + '|' + 'END')",+ );+ });++ test('reads each state field only from a terminated probe line, ignoring glued neighbour rows', () => {+ const glued = 'PSRL_FIXED=2.4.5|None|True|ENDPS C:\\project>';++ expect(windowsPSReadLineStateField('PSRL_FIXED', glued, 'version')).toBe('2.4.5');+ expect(windowsPSReadLineStateField('PSRL_FIXED', glued, 'prediction')).toBe('None');+ expect(windowsPSReadLineStateField('PSRL_FIXED', glued, 'history')).toBe('True');+ expect(+ windowsPSReadLineStateField('PSRL_FIXED', 'PSRL_FIXED=2.4.5|None|Tru', 'history'),+ ).toBeNull();+ expect(+ windowsPSReadLineStateField(+ 'PSRL_FIXED',+ windowsPSReadLineStateCommand('PSRL_FIXED', 'C:\\h'),+ 'history',+ ),+ ).toBeNull();+ });});