Beautiful, AI-native markdown IDE and LLM wiki
TypeScript 2nd-brainagent-skillsclaudecodexcompany-braindocsknowledge-knowledge-baseknowledge-managementllmllm-wikillm-wiki-karpathymarkdownmarkdown-editormdmdxnotespkmsecond-brainskills
PRD-8001 Add Windows terminal support (#3923)
serafin-garcia3212159a1aea
diff --git a/.changeset/windows-terminal-support.md b/.changeset/windows-terminal-support.mdnew file mode 100644index 000000000..2c378efb3--- /dev/null+++ b/.changeset/windows-terminal-support.md@@ -0,0 +1,5 @@+---+"@inkeep/open-knowledge": minor+---++OpenKnowledge Desktop's built-in terminal now works on Windows 10 version 1809 or later, Windows 11, and Windows Server 2019 or later. The Windows terminal includes automatic Windows PowerShell, PowerShell 7, and `cmd.exe` discovery, Git Bash support through an explicit `terminal.shell` override, agent CLI and managed-command launching, clipboard shortcuts, packaged ConPTY support, and update-time cleanup for console hosts owned by the installed app. Agent-launch prompts are pasted without being submitted automatically, so review the prompt and press Enter to send it. Existing absolute overrides outside the supported shell families remain usable for plain terminal tabs, with a capability notice explaining their launch and dropped-file limits.diff --git a/.github/scripts/release-cascade-shape.test.mjs b/.github/scripts/release-cascade-shape.test.mjsindex 38a8d2b8b..334d1f897 100644--- a/.github/scripts/release-cascade-shape.test.mjs+++ b/.github/scripts/release-cascade-shape.test.mjs@@ -22,6 +22,7 @@ import { smokePackagedDmg, VERDICT } from './smoke-packaged-dmg.mjs';const WORKFLOWS = join(dirname(fileURLToPath(import.meta.url)), '..', 'workflows');const read = (name) => readFileSync(join(WORKFLOWS, name), 'utf8');const desktopRelease = read('desktop-release.yml');+const desktopBuildWinLinux = read('desktop-build-win-linux.yml');const promoteStable = read('promote-stable.yml');const releaseYml = read('release.yml');const bugLane = read('bug-lane.yml');@@ -41,13 +42,14 @@ const bugLaneVerify = read('bug-lane-verify.yml');* same. Both holes were shipped and caught by mutation testing rather than by* review, which is why this is the only way these files slice a step.*/-const bugLaneVerifyStep = (name) => {- const start = bugLaneVerify.indexOf(`- name: ${name}`);- if (start === -1) throw new Error(`bug-lane-verify.yml has no step named ${name}`);- const rest = bugLaneVerify.slice(start);+const workflowStep = (source, workflowName, name) => {+ const start = source.indexOf(`- name: ${name}`);+ if (start === -1) throw new Error(`${workflowName} has no step named ${name}`);+ const rest = source.slice(start);const end = rest.indexOf('\n - name: ');return end === -1 ? rest : rest.slice(0, end);};+const bugLaneVerifyStep = (name) => workflowStep(bugLaneVerify, 'bug-lane-verify.yml', name);const selectBeta = read('select-beta-to-promote.yml');/**@@ -199,7 +201,7 @@ describe('the Azure signing flag set satisfies the schema', () => {const required = scheme.definitions.WindowsAzureSigningConfiguration.required;expect(required.length).toBeGreaterThanOrEqual(3); // schema sanity, not vacuous- for (const workflow of [desktopRelease, read('desktop-build-win-linux.yml')]) {+ for (const workflow of [desktopRelease, desktopBuildWinLinux]) {const passed = [...workflow.matchAll(/--config\.win\.azureSignOptions\.([A-Za-z]+)=/g)].map((m) => m[1],);@@ -212,6 +214,79 @@ describe('the Azure signing flag set satisfies the schema', () => {});});+describe('the optional Windows signing lane proves what it reports', () => {+ test('signing_ran is authored only after Authenticode attestation succeeds', () => {+ const attestation = desktopBuildWinLinux.indexOf('id: attest-windows-signing');+ expect(attestation).toBeGreaterThan(0);+ expect(desktopBuildWinLinux.slice(0, attestation)).not.toContain('signing_ran=true');+ expect(desktopBuildWinLinux.slice(attestation)).toContain(+ "Add-Content -LiteralPath $env:GITHUB_OUTPUT -Value 'signing_ran=true'",+ );+ expect(desktopBuildWinLinux).toContain(+ 'steps.attest-windows-signing.outputs.signing_ran',+ );+ });++ test('attests and package-checks both Windows outer architectures', () => {+ for (const dir of ['dist-desktop/win-unpacked', 'dist-desktop/win-arm64-unpacked']) {+ expect(desktopBuildWinLinux).toContain(`Path = '${dir}'`);+ expect(desktopBuildWinLinux).toContain(`OK_WIN_PACKAGE_DIR: ${dir}`);+ }+ });+});++describe('the publishing Windows lane attests its signed native payload', () => {+ test('checks both outer architectures before staging release assets', () => {+ const attest = desktopRelease.indexOf(+ '- name: Attest signed Windows packages and preserved Microsoft signatures',+ );+ const asar = desktopRelease.indexOf(+ '- name: Assert the packaged asar carries its dependencies',+ attest,+ );+ const upload = desktopRelease.indexOf(+ '- name: Upload Windows release assets for the fan-in publisher',+ attest,+ );++ expect(attest).toBeGreaterThan(0);+ expect(attest).toBeLessThan(asar);+ expect(asar).toBeLessThan(upload);+ const attestationSteps = desktopRelease.slice(attest, asar);+ expect(attestationSteps).toContain('Get-AuthenticodeSignature');+ expect(attestationSteps).toContain("-notmatch 'Microsoft'");+ expect(attestationSteps.match(/OK_WIN_PACKAGE_REQUIRED: "1"/gu) ?? []).toHaveLength(2);+ expect(attestationSteps).not.toMatch(/^\s+if:/mu);+ expect(attestationSteps).not.toContain('continue-on-error:');+ for (const dir of ['dist-desktop/win-unpacked', 'dist-desktop/win-arm64-unpacked']) {+ expect(attestationSteps).toContain(`Path = '${dir}'`);+ expect(attestationSteps).toContain(`OK_WIN_PACKAGE_DIR: ${dir}`);+ }+ });++ test('keeps the shared signature-preservation core in both Windows lanes', () => {+ for (const [workflowName, workflow] of [+ ['desktop-release.yml', desktopRelease],+ ['desktop-build-win-linux.yml', desktopBuildWinLinux],+ ]) {+ const attestationStep = workflowStep(+ workflow,+ workflowName,+ 'Attest signed Windows packages and preserved Microsoft signatures',+ );+ for (const token of [+ '$signature = Get-AuthenticodeSignature $appExecutable',+ '$signature = Get-AuthenticodeSignature $path',+ "-notmatch 'Microsoft'",+ "foreach ($name in @('conpty.dll', 'OpenConsole.exe'))",+ 'node-pty[\\\\/]prebuilds[\\\\/]win32-(x64|arm64)[\\\\/]conpty$',+ ]) {+ expect(attestationStep).toContain(token);+ }+ }+ });+});+describe('the fan-in publication DAG gates every platform', () => {test('publish-assets waits on all four build jobs', () => {// The single publication point must sit downstream of EVERY packagingdiff --git a/.github/workflows/desktop-build-win-linux.yml b/.github/workflows/desktop-build-win-linux.ymlindex ecdc5977a..390fa5d87 100644--- a/.github/workflows/desktop-build-win-linux.yml+++ b/.github/workflows/desktop-build-win-linux.yml@@ -5,7 +5,7 @@ name: Desktop build (manual, Windows/Linux)# tags, or touches the release cadence — the operator downloads the# installers from the run's artifacts for VM/hardware QA. The release# path is desktop-release.yml, which builds these same targets signed-# and publishes them; this workflow stays the unsigned QA lane.+# and publishes them; this workflow stays the non-publishing QA lane.## Topology: one `prepare` job on ubuntu builds the workspace (the CLI# build chain uses `cp -r`/`mkdir -p` bash-isms that don't survive a@@ -24,7 +24,7 @@ name: Desktop build (manual, Windows/Linux)# way.## Windows signing (D3, Azure Artifact Signing): OPTIONAL here. When the-# three AZURE_* secrets + three AZURE_SIGNING_* repo variables are+# three AZURE_* secrets + four AZURE_SIGNING_* repo variables are# configured, the Windows job passes win.azureSignOptions to# electron-builder; when absent it builds unsigned (acceptable for# internal QA only — unsigned Windows builds are never published, and@@ -231,6 +231,7 @@ jobs:# so the signed branch requires the full set and PUBLISHER joins the# presence check.- name: Package NSIS installers (x64 + arm64)+ id: package-windowsworking-directory: packages/desktopenv:AZURE_TENANT_ID: ${{ secrets.AZURE_TENANT_ID }}@@ -243,8 +244,9 @@ jobs:run: |set -euo pipefailextra=()- if [[ -n "${AZURE_CLIENT_SECRET:-}" && -n "${AZURE_SIGNING_ENDPOINT:-}" && -n "${AZURE_SIGNING_PUBLISHER:-}" ]]; then+ if [[ -n "${AZURE_TENANT_ID:-}" && -n "${AZURE_CLIENT_ID:-}" && -n "${AZURE_CLIENT_SECRET:-}" && -n "${AZURE_SIGNING_ENDPOINT:-}" && -n "${AZURE_SIGNING_ACCOUNT:-}" && -n "${AZURE_SIGNING_PROFILE:-}" && -n "${AZURE_SIGNING_PUBLISHER:-}" ]]; thenecho "::notice::Azure Trusted Signing credentials present — building SIGNED installers."+ echo "signing_requested=true" >> "$GITHUB_OUTPUT"extra+=("--config.win.azureSignOptions.endpoint=${AZURE_SIGNING_ENDPOINT}""--config.win.azureSignOptions.codeSigningAccountName=${AZURE_SIGNING_ACCOUNT}"@@ -253,9 +255,97 @@ jobs:)elseecho "::warning::No (complete) Azure signing config — building UNSIGNED installers (internal QA only; never distribute)."+ echo "signing_requested=false" >> "$GITHUB_OUTPUT"fipnpm exec electron-builder --win --publish never "${extra[@]}"+ - name: Attest signed Windows packages and preserved Microsoft signatures+ id: attest-windows-signing+ if: ${{ !cancelled() && steps.package-windows.outputs.signing_requested == 'true' }}+ shell: pwsh+ working-directory: packages/desktop+ env:+ OK_SIGNING_REQUESTED: ${{ steps.package-windows.outputs.signing_requested }}+ run: |+ $ErrorActionPreference = 'Stop'+ if ($env:OK_SIGNING_REQUESTED -ne 'true') {+ throw 'Signature rider ran without a signing-enabled package step.'+ }++ $packages = @(+ [pscustomobject]@{ Arch = 'x64'; Path = 'dist-desktop/win-unpacked' },+ [pscustomobject]@{ Arch = 'arm64'; Path = 'dist-desktop/win-arm64-unpacked' }+ )+ foreach ($package in $packages) {+ if (-not (Test-Path -LiteralPath $package.Path -PathType Container)) {+ throw "Signing-enabled build produced no $($package.Arch) outer package at $($package.Path)."+ }++ $appExecutable = Join-Path $package.Path 'OpenKnowledge.exe'+ if (-not (Test-Path -LiteralPath $appExecutable -PathType Leaf)) {+ throw "Signing-enabled $($package.Arch) package has no OpenKnowledge.exe."+ }+ $signature = Get-AuthenticodeSignature $appExecutable+ if ($signature.Status -ne 'Valid') {+ throw "Our signing pass did not leave a valid signature on ${appExecutable}: $($signature.Status)"+ }++ $pairDirectories = @(Get-ChildItem $package.Path -Recurse -Directory -Filter 'conpty' |+ Where-Object { $_.FullName -match 'node-pty[\\/]prebuilds[\\/]win32-(x64|arm64)[\\/]conpty$' })+ if ($pairDirectories.Count -ne 2) {+ throw "Expected both ConPTY architecture directories in the $($package.Arch) package; found $($pairDirectories.Count)."+ }+ foreach ($directory in $pairDirectories) {+ foreach ($name in @('conpty.dll', 'OpenConsole.exe')) {+ $path = Join-Path $directory.FullName $name+ if (-not (Test-Path -LiteralPath $path -PathType Leaf)) {+ throw "Packaged Microsoft ConPTY pair is incomplete: $path"+ }+ $signature = Get-AuthenticodeSignature $path+ if ($signature.Status -ne 'Valid') {+ throw "Microsoft signature is not valid on ${path}: $($signature.Status)"+ }+ if ($signature.SignerCertificate.Subject -notmatch 'Microsoft') {+ throw "Expected the original Microsoft signer on ${path}; got $($signature.SignerCertificate.Subject)"+ }+ }+ }+ }+ Add-Content -LiteralPath $env:GITHUB_OUTPUT -Value 'signing_ran=true'+ "### Windows signature rider: PASSED`n`nBoth outer architectures carry a signed app, and Microsoft signatures remain valid on every packaged ConPTY pair." |+ Add-Content -LiteralPath $env:GITHUB_STEP_SUMMARY++ - name: Require completed Windows signing attestation+ if: ${{ !cancelled() && steps.package-windows.outputs.signing_requested == 'true' }}+ shell: pwsh+ env:+ OK_SIGNING_RAN: ${{ steps.attest-windows-signing.outputs.signing_ran }}+ run: |+ if ($env:OK_SIGNING_RAN -ne 'true') {+ throw 'Azure signing was requested, but both signed outer packages were not attested.'+ }++ - name: Report Windows signature rider skipped+ if: ${{ !cancelled() && steps.package-windows.outputs.signing_requested != 'true' }}+ shell: pwsh+ run: |+ "### Windows signature rider: SKIPPED`n`nThis dispatch built unsigned QA artifacts, so the post-signature rider did not run and must not be read as green evidence." |+ Add-Content -LiteralPath $env:GITHUB_STEP_SUMMARY++ - name: Assert Windows x64 terminal native package compatibility+ working-directory: packages/desktop+ env:+ OK_WIN_PACKAGE_DIR: dist-desktop/win-unpacked+ OK_WIN_PACKAGE_REQUIRED: "1"+ run: pnpm exec vitest run tests/unit/windows-package-native-guards.test.ts++ - name: Assert Windows arm64 terminal native package compatibility+ working-directory: packages/desktop+ env:+ OK_WIN_PACKAGE_DIR: dist-desktop/win-arm64-unpacked+ OK_WIN_PACKAGE_REQUIRED: "1"+ run: pnpm exec vitest run tests/unit/windows-package-native-guards.test.ts+# Fail before uploading an installer that cannot start. An asar packed# without `node_modules` produces a binary that dies on its first bare# import, before `app.ready` — no window, no dialog — so an operatordiff --git a/.github/workflows/desktop-release.yml b/.github/workflows/desktop-release.ymlindex ce308d47a..a608690ad 100644--- a/.github/workflows/desktop-release.yml+++ b/.github/workflows/desktop-release.yml@@ -1012,6 +1012,67 @@ jobs:bash -c "$PKG_CMD"fi+ - name: Attest signed Windows packages and preserved Microsoft signatures+ shell: pwsh+ working-directory: packages/desktop+ run: |+ $ErrorActionPreference = 'Stop'+ $packages = @(+ [pscustomobject]@{ Arch = 'x64'; Path = 'dist-desktop/win-unpacked' },+ [pscustomobject]@{ Arch = 'arm64'; Path = 'dist-desktop/win-arm64-unpacked' }+ )+ foreach ($package in $packages) {+ if (-not (Test-Path -LiteralPath $package.Path -PathType Container)) {+ throw "Signed release produced no $($package.Arch) outer package at $($package.Path)."+ }++ $appExecutable = Join-Path $package.Path 'OpenKnowledge.exe'+ if (-not (Test-Path -LiteralPath $appExecutable -PathType Leaf)) {+ throw "Signed $($package.Arch) release package has no OpenKnowledge.exe."+ }+ $signature = Get-AuthenticodeSignature $appExecutable+ if ($signature.Status -ne 'Valid') {+ throw "Our signing pass did not leave a valid signature on ${appExecutable}: $($signature.Status)"+ }++ $pairDirectories = @(Get-ChildItem $package.Path -Recurse -Directory -Filter 'conpty' |+ Where-Object { $_.FullName -match 'node-pty[\\/]prebuilds[\\/]win32-(x64|arm64)[\\/]conpty$' })+ if ($pairDirectories.Count -ne 2) {+ throw "Expected both ConPTY architecture directories in the $($package.Arch) release package; found $($pairDirectories.Count)."+ }+ foreach ($directory in $pairDirectories) {+ foreach ($name in @('conpty.dll', 'OpenConsole.exe')) {+ $path = Join-Path $directory.FullName $name+ if (-not (Test-Path -LiteralPath $path -PathType Leaf)) {+ throw "Packaged Microsoft ConPTY pair is incomplete: $path"+ }+ $signature = Get-AuthenticodeSignature $path+ if ($signature.Status -ne 'Valid') {+ throw "Microsoft signature is not valid on ${path}: $($signature.Status)"+ }+ if ($signature.SignerCertificate.Subject -notmatch 'Microsoft') {+ throw "Expected the original Microsoft signer on ${path}; got $($signature.SignerCertificate.Subject)"+ }+ }+ }+ }+ "### Windows release signature rider: PASSED`n`nBoth outer architectures carry a signed app, and Microsoft signatures remain valid on every packaged ConPTY pair." |+ Add-Content -LiteralPath $env:GITHUB_STEP_SUMMARY++ - name: Assert Windows x64 terminal native package compatibility+ working-directory: packages/desktop+ env:+ OK_WIN_PACKAGE_DIR: dist-desktop/win-unpacked+ OK_WIN_PACKAGE_REQUIRED: "1"+ run: pnpm exec vitest run tests/unit/windows-package-native-guards.test.ts++ - name: Assert Windows arm64 terminal native package compatibility+ working-directory: packages/desktop+ env:+ OK_WIN_PACKAGE_DIR: dist-desktop/win-arm64-unpacked+ OK_WIN_PACKAGE_REQUIRED: "1"+ run: pnpm exec vitest run tests/unit/windows-package-native-guards.test.ts+# Fail before staging an installer that cannot start. An asar packed# without `node_modules` produces a binary that dies on its first bare# import, before `app.ready` — no window, no dialog.diff --git a/biome-plugins/README.md b/biome-plugins/README.mdindex 7c645346f..be4aaccdd 100644--- a/biome-plugins/README.md+++ b/biome-plugins/README.md@@ -223,7 +223,7 @@ Windows console-flash prevention. Every hand-rolled `node:child_process` process`simple-git` already sets `windowsHide: true` internally, so git routed through it (shadow repo, share, conflicts) is out of scope by nature — this rule governs only the hand-rolled call sites that bypass it.-**Scoped via `overrides[].plugins`** to `packages/{server,cli}/src/**/*.ts` (the packages that spawn processes at runtime on Windows), with `!**/*.test.ts` + `!**/*.test-helper.ts` excluded. `packages/desktop` is deliberately **out of scope** — the Electron app is macOS-only and never runs on Windows.+**Scoped via `overrides[].plugins`** to `packages/{server,cli,desktop}/src/**/*.ts` (the packages that spawn processes at runtime on Windows), with `!**/*.test.ts` + `!**/*.test-helper.ts` excluded.**Opting out (macOS/Linux-only spawns).** For a spawn that only ever runs on macOS and/or Linux — `codesign`, `sw_vers`, an `open(1)` launch — hiding a console is meaningless. Either add the flag anyway (a harmless no-op that keeps the rule uniform) or suppress that one call with a reason:diff --git a/biome-plugins/require-windowshide-on-spawn.grit b/biome-plugins/require-windowshide-on-spawn.gritindex a3371b15d..a02c64612 100644--- a/biome-plugins/require-windowshide-on-spawn.grit+++ b/biome-plugins/require-windowshide-on-spawn.grit@@ -33,9 +33,8 @@// // biome-ignore lint/plugin/require-windowshide-on-spawn: macOS-only (never spawned on Windows)// const r = spawnSync('codesign', [...], { ... });//-// Scoped via `overrides[].plugins` to `packages/{server,cli}/src/**` — the-// packages that spawn processes at runtime on Windows. `packages/desktop` is-// macOS-only (the Electron app never runs on Windows), so it is out of scope.+// Scoped via `overrides[].plugins` to `packages/{server,cli,desktop}/src/**` —+// the packages that spawn processes at runtime on Windows.//// The rule keys on the CALL-EXPRESSION CALLEE IDENTIFIER, so it can't tell a// real `node:child_process` import from a same-named wrapper. A few call sitesdiff --git a/biome.jsonc b/biome.jsoncindex fe9197271..6aa71d903 100644--- a/biome.jsonc+++ b/biome.jsonc@@ -130,13 +130,14 @@// spawn in the runtime-spawning packages must hide the Windows console// (via `withHiddenWindowsConsole(...)` or `windowsHide: true`), else a// console-less parent (MCP-spawned/detached OK server) flashes a terminal- // window per spawn on Windows. Scoped to server + cli (the packages that- // spawn on Windows); `packages/desktop` is macOS-only and out of scope.+ // window per spawn on Windows. Scoped to the server, CLI, and desktop+ // packages that spawn processes on Windows.// Tests excluded. `simple-git` sets the flag internally, so git routed// through it is out of scope by nature."includes": ["packages/server/src/**/*.ts","packages/cli/src/**/*.ts",+ "packages/desktop/src/**/*.ts","!**/*.test.ts","!**/*.test-helper.ts","biome-plugins/__fixtures__/require-windowshide-on-spawn.fixture.tsx"diff --git a/docs/content/features/editor.mdx b/docs/content/features/editor.mdxindex 6c9afa986..0cdf5b158 100644--- a/docs/content/features/editor.mdx+++ b/docs/content/features/editor.mdx@@ -96,7 +96,7 @@ Surfaces with their own specialized right-click menus — asset and wiki-link chAn **Ask AI** composer is docked at the bottom of the editor — in the desktop app and in a regular browser — whenever a doc or folder view is open. It's a slim, single-line entry field that expands as you type to accept a fuller prompt (and `@`-mentions); in the desktop app, `Cmd+L` opens and focuses it. Type an instruction — "condense this doc", "research X", "make a spec from this user story" — and press Enter to hand it to an agent. `Shift+Enter` inserts a newline; the field clears once the prompt is sent.-It's the primary in-editor way to hand work to an agent, and the freetext companion to the menu-driven [Open with AI](#open-with-ai) (whole file / folder / project). Submitting dispatches the typed prompt to your **default agent**, scoped to the current doc (or, in a folder view, the folder), which the agent receives as an `@`-mention. Until you pick something else, that default is an **In app** agent, so the conversation stays inside OpenKnowledge; it falls back to a **Terminal** CLI — preferring one detected on this machine — and then to an **External app**, when no higher option is available here. The agent picker beside the field overrides the default per send, listing In app agents first, then the [Terminal](#open-with-ai) CLIs available on this machine (macOS and Linux desktop apps), then the external agent apps detected here. Whatever you pick is remembered on that machine and stays your default until you change it or turn it off in **Configure agents**. Success and failure use the same handoff toast as Open with AI.+It's the primary in-editor way to hand work to an agent, and the freetext companion to the menu-driven [Open with AI](#open-with-ai) (whole file / folder / project). Submitting dispatches the typed prompt to your **default agent**, scoped to the current doc (or, in a folder view, the folder), which the agent receives as an `@`-mention. Until you pick something else, that default is an **In app** agent, so the conversation stays inside OpenKnowledge; it falls back to a **Terminal** CLI — preferring one detected on this machine — and then to an **External app**, when no higher option is available here. The agent picker beside the field overrides the default per send, listing In app agents first, then the [Terminal](#open-with-ai) CLIs available on this machine, then the external agent apps detected here. Whatever you pick is remembered on that machine and stays your default until you change it or turn it off in **Configure agents**. Success and failure use the same handoff toast as Open with AI.The composer stays out of the way where it doesn't belong: it's hidden inside an AI editor's embedded view, while the [docked terminal](#terminal) is open (the terminal is its own AI entry point), and when no doc or folder is open (the empty state already offers project handoff). It's also dismissible — an **Ask AI** badge in the status bar brings it back.@@ -106,9 +106,11 @@ Select text in the WYSIWYG editor and the selection bubble menu shows a **Commen## Terminal-The desktop app on macOS and Linux has a built-in terminal with real interactive shells inside the editor window. On Linux, OpenKnowledge inherits Electron's supported distribution range: releases of the major distributions that both Chromium and the distribution vendor still support. Toggle it with `Cmd+J` on macOS or `Ctrl+J` on Linux, with `` Ctrl+` `` on either platform (which also works from inside a focused terminal), or with **View ▸ Show / Hide Terminal**. It opens at the placement saved for this installation (the bottom dock by default). Right-click a bottom-dock tab and choose **Move to right panel**, use the matching command in the command palette or **Terminal** menu, or use the right-panel header button to move it back to the bottom. Moving or hiding the Terminal keeps its live shells, tabs, and scrollback intact.+The desktop app on macOS, Windows, and Linux has a built-in terminal with real interactive shells inside the editor window. On Windows, the terminal requires Windows 10 version 1809 (build 17763) or later, Windows 11, or Windows Server 2019 or later. On Linux, OpenKnowledge inherits Electron's supported distribution range: releases of the major distributions that both Chromium and the distribution vendor still support. Toggle it with `Cmd+J` on macOS or `Ctrl+J` on Windows and Linux, with `` Ctrl+` `` on any desktop platform (which also works from inside a focused terminal), or with **View ▸ Show / Hide Terminal**. It opens at the placement saved for this installation (the bottom dock by default). Right-click a bottom-dock tab and choose **Move to right panel**, use the matching command in the command palette or **Terminal** menu, or use the right-panel header button to move it back to the bottom. Moving or hiding the Terminal keeps its live shells, tabs, and scrollback intact.-The terminal is also the editor's AI-chat surface: opening it starts your remembered CLI pick, or a plain shell when you have none, and the tab strip's **+** button opens another tab with whatever you picked last — a CLI chat or a plain shell. Its dropdown switches that pick and opens a tab in the thing you picked, in one action. A CLI pick sticks and is shared with the Ask AI composer; the plain-shell pick is remembered for the terminal only. In-app agents run in the Agents panel, which has its own tab strip and **+** button; picking an agent there sticks the same way and also becomes your Ask AI default. With text selected in the editor, `Cmd+J` on macOS, `Ctrl+J` on Linux, and `` Ctrl+` `` on either platform stage the passage into the active CLI's input (or open a new CLI tab when none is running) instead of toggling — they share one handler. `Cmd+Shift+J` on macOS or `Ctrl+Shift+J` on Linux always stages it into a new CLI tab; the passage sits in the input for you to add to, and nothing is submitted until you press Enter. **Terminal ▸ New Terminal Window** (see [Terminal menu](#terminal-menu)) opens a dedicated window with the same multi-session tabs, `Cmd+<number>` tab switching, and shells starting at the project root.+The terminal is also the editor's AI-chat surface: opening it starts your remembered CLI pick, or a plain shell when you have none, and the tab strip's **+** button opens another tab with whatever you picked last — a CLI chat or a plain shell. Its dropdown switches that pick and opens a tab in the thing you picked, in one action. A CLI pick sticks and is shared with the Ask AI composer; the plain-shell pick is remembered for the terminal only. In-app agents run in the Agents panel, which has its own tab strip and **+** button; picking an agent there sticks the same way and also becomes your Ask AI default. With text selected in the editor, `Cmd+J` on macOS, `Ctrl+J` on Windows or Linux, and `` Ctrl+` `` on any desktop platform stage the passage into the active CLI's input (or open a new CLI tab when none is running) instead of toggling — they share one handler. `Cmd+Shift+J` on macOS or `Ctrl+Shift+J` on Windows or Linux always stages it into a new CLI tab; the passage sits in the input for you to add to, and nothing is submitted until you press Enter. **Terminal ▸ New Terminal Window** (see [Terminal menu](#terminal-menu)) opens a dedicated window with the same multi-session tabs, switched with `Cmd+<number>` on macOS or `Ctrl+<number>` on Windows and Linux, and shells starting at the project root.++On Windows, type `wsl` in any terminal tab to enter your default WSL distribution; OpenKnowledge's CLI detection and bundled `ok` command stay Windows-side, so install agent CLIs on Windows for them to appear in the launcher.Rename a tab by double-clicking it or pressing `F2`; the name you set pins over whatever title the running program reports, and clearing it falls back to that title. Reorder tabs by dragging, or move the active tab with `Cmd+Shift+←` / `Cmd+Shift+→` — untitled tabs keep a number that stays with their session as the strip is rearranged.@@ -116,7 +118,7 @@ The desktop app restores the Terminal's placement, right-panel width, tab order,On a narrow window, the right-side Terminal and Agents panel cannot remain open together. Opening either one closes the other and shows an in-app notice; closing the visible panel does not reopen the one that was displaced.-The shells run at full user privilege. To turn the terminal off for a project on this machine, use **Settings ▸ Terminal** or set `terminal.enabled: false` in `.ok/local/config.yml` (see the [configuration reference](../reference/configuration.mdx)); the setting is project-local, never shared via git or sync, and not agent-settable — only a human can flip it.+The shells run at full user privilege. To turn the terminal off for a project on this machine, use **Settings ▸ Terminal** or set `terminal.enabled: false` in `.ok/local/config.yml` (see the [configuration reference](../reference/configuration.mdx)); the setting is project-local, never shared via git or sync, and not agent-settable — only a human can flip it. On Windows, set `terminal.shell` in the same file to an absolute shell executable if you want to override automatic PowerShell and `cmd.exe` discovery. PowerShell, `cmd.exe`, and Git Bash (`bash.exe`) support OpenKnowledge-managed launches (agent chat tabs and fixed commands such as **Resolve in terminal** or **Install Slidev**) and dropped-file path insertion. A different existing executable remains active for plain terminal tabs and shows a capability notice; requested agent and command launches open only the plain shell without running the agent or command, and dropped-file paths are refused. Enter WSL by running `wsl` inside a supported shell rather than setting `wsl.exe` as the override.## Properties@@ -196,7 +198,7 @@ To send your own freetext instruction along with the handoff, use the bottom [AsSee the [per-integration pages](../integrations/claude-code.mdx) for what each agent receives once dispatched.-The menu is organized into three sections, in the order the default follows. **In app** leads: a row for each in-app agent you've enabled or that detection turned up, which opens the conversation in OpenKnowledge's Agents panel without leaving the app. **Terminal** (macOS and Linux desktop apps) follows: a row for every agent CLI OpenKnowledge can launch — **Claude**, **Codex**, **OpenCode**, **Cursor**, **GitHub Copilot**, **Pi**, **Antigravity**, **OpenClaw**, and **Hermes** — each running its own command in OpenKnowledge's [docked terminal](#terminal) with the same scoped prompt. A CLI the PATH probe reports absent is hidden until you turn it on in **Configure agents**. **External apps** comes last, listing the agent apps detected on this machine — **Claude Desktop**, **ChatGPT Desktop** (Codex's desktop app is branded ChatGPT), and **Cursor Desktop** — plus any you turned on in **Configure agents** (those route to the app's installer); selecting one launches it via its deep link and hands the work out of OpenKnowledge. Because the sections can carry the same brand name, the **Desktop** suffix is what tells a Terminal **Claude** (the CLI) apart from an External apps **Claude Desktop** (the app) on screen; screen readers additionally get "Claude CLI" as the Terminal row's accessible name. Each section renders only when it has something to launch, so on the web build and in the Windows app, which has no docked terminal, the Terminal section is absent, and a saved CLI pick degrades to the same order the default follows: an In app agent when one is available, otherwise an external app. A **Configure agents** row is always last.+The menu is organized into three sections, in the order the default follows. **In app** leads: a row for each in-app agent you've enabled or that detection turned up, which opens the conversation in OpenKnowledge's Agents panel without leaving the app. **Terminal** (desktop app) follows: a row for every agent CLI OpenKnowledge can launch — **Claude**, **Codex**, **OpenCode**, **Cursor**, **GitHub Copilot**, **Pi**, **Antigravity**, **OpenClaw**, and **Hermes** — each running its own command in OpenKnowledge's [docked terminal](#terminal) with the same scoped prompt. On Windows, OpenKnowledge pastes that prompt without submitting it because a generic ConPTY readiness signal cannot safely identify the active input; review the prompt, then press Enter to send it. A CLI the PATH probe reports absent is hidden until you turn it on in **Configure agents**. **External apps** comes last, listing the agent apps detected on this machine — **Claude Desktop**, **ChatGPT Desktop** (Codex's desktop app is branded ChatGPT), and **Cursor Desktop** — plus any you turned on in **Configure agents** (those route to the app's installer); selecting one launches it via its deep link and hands the work out of OpenKnowledge. Because the sections can carry the same brand name, the **Desktop** suffix is what tells a Terminal **Claude** (the CLI) apart from an External apps **Claude Desktop** (the app) on screen; screen readers additionally get "Claude CLI" as the Terminal row's accessible name. Each section renders only when it has something to launch, so on the web build, which has no docked terminal, the Terminal section is absent, and a saved CLI pick degrades to the same order the default follows: an In app agent when one is available, otherwise an external app. A **Configure agents** row is always last.The empty-state create composer on a fresh project carries the same three-way split: its In app rows pick the in-app agent the **Create** button uses, its Terminal rows (desktop only, disabled until the workspace resolves) launch any of those CLIs with the brief you typed, and its External apps rows hand that brief to an agent app installed here.@@ -252,9 +254,9 @@ Keyboard shortcuts (on Windows / Linux, use `Ctrl` in place of `Cmd` and `Alt` i| `Cmd+Option+B` | Show / Hide the document panel (right). Matches VS Code's Secondary Side Bar accelerator. || `Cmd+Option+M` | Toggle between the visual and source editors, keeping your place. || `Cmd+Option+E` | **View in source** — jump from the visual editor to the Markdown for the block at the cursor, centered and highlighted (visual editor only). |-| `Cmd+J` / `Ctrl+J` | Show / Hide the Terminal in its current placement (macOS / Linux desktop app). With text selected, stages the passage into the AI CLI's input instead — nothing runs until you press Enter. |-| `` Ctrl+` `` | Show / Hide the Terminal too — the VS Code / Zed chord, literal `Ctrl` (macOS and Linux desktop apps). Works even while a terminal holds focus. With text selected it stages the passage like `Cmd+J` instead of toggling. |-| `Cmd+Shift+J` / `Ctrl+Shift+J` | Open an additional terminal tab (macOS / Linux desktop app). With text selected, stages the passage into the new tab's AI CLI input. |+| `Cmd+J` / `Ctrl+J` | Show / Hide the Terminal in its current placement (macOS / Windows and Linux desktop apps). With text selected, stages the passage into the AI CLI's input instead — nothing runs until you press Enter. |+| `` Ctrl+` `` | Show / Hide the Terminal too — the VS Code / Zed chord, literal `Ctrl` (desktop app). Works even while a terminal holds focus. With text selected it stages the passage like `Cmd+J` instead of toggling. |+| `Cmd+Shift+J` / `Ctrl+Shift+J` | Open an additional terminal tab (macOS / Windows and Linux desktop apps). With text selected, stages the passage into the new tab's AI CLI input. || `Cmd+P` | Open the [command palette](#command-palette) from anywhere — unlike `Cmd+K`, it opens the palette even while text is selected in the visual editor. || `Cmd+L` | Open and focus the [Ask AI](#ask-ai) composer (desktop app). || `Cmd+Shift+D` / `Ctrl+Shift+D` | Start a bug report (desktop app). The screenshot it attaches is the screen exactly as it looks when you press the chord — open menus, tooltips and hover states included — plus a marker drawn where your pointer was, since a screenshot never includes the cursor. No marker appears if the pointer has not moved since the window loaded, or has since left the window. Nothing is sent until you press Send. |@@ -316,7 +318,7 @@ Toggling the menu checkboxes flips the underlying config field, which propagates| Item | Accelerator | Behavior || --- | --- | --- || **New Terminal** | (none) | Opens a new terminal tab, revealing the Terminal in its current placement if it's hidden. |-| **New Terminal Window** | (none) | Opens a terminal in its own window — the same multi-session tabs, switched with `Cmd+<number>`, shells starting at the project root. |+| **New Terminal Window** | (none) | Opens a terminal in its own window — the same multi-session tabs, switched with `Cmd+<number>` on macOS or `Ctrl+<number>` on Windows and Linux, shells starting at the project root. || **Move Terminal to right / bottom** | (none) | Moves the live Terminal workspace to the opposite placement. The label names the destination. || **Kill Terminal** | (none) | Closes the active terminal tab and kills its shell. |diff --git a/docs/content/get-started/overview.mdx b/docs/content/get-started/overview.mdxindex 392196a81..0a90fa906 100644--- a/docs/content/get-started/overview.mdx+++ b/docs/content/get-started/overview.mdx@@ -18,7 +18,7 @@ OpenKnowledge is three layers working together: a WYSIWYG editor for you, MCP an<LayerStack />## Additional Features-- **[Ask AI](../features/editor.mdx#ask-ai)** experience: chat with your agent **in app** without leaving OpenKnowledge, or hand the work to an external agent app or the built-in **[TUI](../features/editor.mdx#terminal)** on the macOS and Linux desktop apps.+- **[Ask AI](../features/editor.mdx#ask-ai)** experience: chat with your agent **in app** without leaving OpenKnowledge, or hand the work to an external agent app or the built-in **[TUI](../features/editor.mdx#terminal)** in the desktop app.- Annotate your knowledge base with **[comments](../features/comments.mdx)**, then resolve them with AI.- **[Auto-sync](../features/github-sync.mdx)** knowledge base changes with your team using Git.- Explore your knowledge base through **[graph and wiki-link visualizations](../reference/core-concepts.md#links-and-backlinks)**.diff --git a/docs/content/get-started/quickstart.mdx b/docs/content/get-started/quickstart.mdxindex 909c6e527..4d84d586b 100644--- a/docs/content/get-started/quickstart.mdx+++ b/docs/content/get-started/quickstart.mdx@@ -54,7 +54,7 @@ From your newly created project, select **Knowledge base** from the landing page### Open the knowledge base in your AI agent-With no documents open, you will see a screen with an input box and a button labeled **Ask** followed by an agent's name. When an in-app agent is available, that is the default, so the conversation stays inside OpenKnowledge; on a machine where none is set up yet the button falls back to a Terminal CLI, and then to an external app. Type what you want to learn about in the input box and click the button; it hands your project to the agent with your prompt as the starter. Use the chevron beside the button to pick a different agent instead — another in-app agent, a Terminal CLI (macOS and Linux desktop apps), or an external app such as Claude, Codex, or Cursor — and the pick is remembered next time. Your agent may take a few seconds to load the project.+With no documents open, you will see a screen with an input box and a button labeled **Ask** followed by an agent's name. When an in-app agent is available, that is the default, so the conversation stays inside OpenKnowledge; on a machine where none is set up yet the button falls back to a Terminal CLI, and then to an external app. Type what you want to learn about in the input box and click the button; it hands your project to the agent with your prompt as the starter. Use the chevron beside the button to pick a different agent instead — another in-app agent, a Terminal CLI, or an external app such as Claude, Codex, or Cursor — and the pick is remembered next time. Your agent may take a few seconds to load the project.Not sure what to write? Paste this into the input box (or use a topic of your choice):diff --git a/docs/content/integrations/antigravity.mdx b/docs/content/integrations/antigravity.mdxindex a40dd647c..f0dfbf62a 100644--- a/docs/content/integrations/antigravity.mdx+++ b/docs/content/integrations/antigravity.mdx@@ -37,7 +37,7 @@ cd /path/to/your/knowledge-baseagy "Summarize the open questions across this project's specs."```-The session stays open for follow-ups. From the **OpenKnowledge desktop app on macOS or Linux**, the "Open in Antigravity" action launches `agy` in the docked terminal, pre-filled with a prompt scoped to the doc, folder, or project you're on. The row appears only when `agy` is detected on your `PATH` (the installer drops it at `~/.local/bin/agy`).+The session stays open for follow-ups. From the **OpenKnowledge desktop app**, the "Open in Antigravity" action launches `agy` in the docked terminal, pre-filled with a prompt scoped to the doc, folder, or project you're on. The row appears only when `agy` is detected on your `PATH`; its installation directory varies by platform.## Initialize a knowledge base@@ -71,7 +71,7 @@ For the complete tool surface, see the [MCP reference](/docs/reference/mcp).| `ok init` showed Antigravity as `config root missing; skipped` | `~/.gemini/` doesn't exist yet, so Antigravity wasn't detected | Launch Antigravity or run `agy` once (it creates the directory), then re-run `ok init` || `ok init` reported the config was `left unchanged` | OpenKnowledge declined to edit `~/.gemini/config/mcp_config.json` for the reason shown in parentheses | Fix what the reason names (invalid JSON, a duplicated server block), then re-run `ok init` || Antigravity doesn't see the `open-knowledge` tools | MCP servers not reloaded, or the agent's process predates the entry | Reload MCP servers (or restart `agy`), and confirm the server is enabled |-| "Open in Antigravity" row is missing in the desktop app | `agy` isn't on `PATH` | Install the Antigravity CLI (`~/.local/bin/agy`) and ensure that directory is on your `PATH` |+| "Open in Antigravity" row is missing in the desktop app | `agy` isn't on `PATH` | Install the Antigravity CLI and ensure its platform-specific install directory is on your `PATH` || `write` / `edit` -> "Hocuspocus server is not running" | OK server not started | Run `ok start` (or leave the desktop app running) and retry || Preview "doesn't open" | used the route-only `/#/…` path in a browser | Call `preview_url` for the full URL |diff --git a/docs/content/integrations/github-copilot-cli.mdx b/docs/content/integrations/github-copilot-cli.mdxindex 6d0bbcfc1..7e68f90cc 100644--- a/docs/content/integrations/github-copilot-cli.mdx+++ b/docs/content/integrations/github-copilot-cli.mdx@@ -18,7 +18,7 @@ It also installs the project skill at `.github/skills/open-knowledge/SKILL.md` s## Open with AI-In OpenKnowledge's docked terminal on macOS or Linux, select **GitHub Copilot** from the new-chat picker. It starts Copilot CLI in interactive mode with context for the current project. The option is hidden when the `copilot` executable is not installed.+In OpenKnowledge's docked terminal, select **GitHub Copilot** from the new-chat picker. It starts Copilot CLI in interactive mode with context for the current project. The option is hidden when the `copilot` executable is not installed.## Verifydiff --git a/docs/content/reference/configuration.mdx b/docs/content/reference/configuration.mdxindex 7442c88f5..101a78c68 100644--- a/docs/content/reference/configuration.mdx+++ b/docs/content/reference/configuration.mdx@@ -64,9 +64,10 @@ A key set in a file more specific than its scope (a user-scope key in `.ok/confi| `editor.wordWrap` | boolean | `true` | user | Soft-wrap long lines in the source-mode CodeMirror editor. A personal preference, not project-shared. Toggle from the Settings pane. || `editor.previewTabs` | boolean | `true` | user | Reuse one replaceable preview tab for single clicks in the Files tree and Skills sidebar, so browsing does not accumulate tabs. Double-click the tab title, pin it, or choose **Keep open** from its context menu to make it permanent. Set `false` to open every click in its own tab. Rename transitions still reuse the current tab; back/forward navigation focuses the target's existing tab, or opens a permanent one when it is no longer open. A personal preference; toggle it from **Settings → Preferences → Preview tabs**. || `appearance.preview.autoOpen` | boolean | `true` | user | Whether the agent should open or refresh the OpenKnowledge preview when it edits a doc through the MCP. Default `true` lets the agent route the preview by host capability: the host's in-app browser (Cursor preview pane, Codex's built-in browser, Claude Code Desktop) when one exists, the system browser otherwise. Set `false` to keep the agent's hands off your preview window. This is useful when you're already viewing the doc in OK Desktop, a browser tab on a second display, a non-default browser, or any flow where your extensions / accessibility tooling only work in your own browser. The agent then surfaces the URL on request but does not navigate. The change takes effect on the next preview-related tool call. Toggle from **Settings → Preferences → "Open preview when agent edits"**. |-| `terminal.enabled` | `boolean \| null` | `null` | project-local | Opt-out for the in-app terminal on macOS and Linux (a real OS shell at full user privilege). On by default; set `false` to disable it for this project on this machine. |+| `terminal.enabled` | `boolean \| null` | `null` | project-local | Opt-out for the in-app terminal (a real OS shell at full user privilege). On by default; set `false` to disable it for this project on this machine. |+| `terminal.shell` | string | (unset) | project-local | Absolute Windows shell executable override, for example `C:\Program Files\PowerShell\7\pwsh.exe`. PowerShell, `cmd.exe`, and Git Bash (`bash.exe`) support OpenKnowledge-managed launches (agent chat tabs and fixed commands such as **Resolve in terminal** or **Install Slidev**) and dropped-file path insertion. A different existing executable remains active for plain terminal tabs and shows a capability notice; requested agent and command launches open only the plain shell without running the agent or command, and dropped-file paths are refused. Use `wsl` inside a supported shell rather than setting `wsl.exe` here. Agent-launch prompts are pasted without being submitted on Windows, so review the prompt and press Enter to send it. Empty or unset values use automatic discovery (PowerShell 7, Windows PowerShell, then `ComSpec` / `cmd.exe`). Unreadable, invalid, relative, or missing paths show a notice and fall back to discovery. Human-managed and never shared through git, clone, or sync. || `slides.enabled` | boolean | `false` | user | Whether the [Slidev plugin](/docs/plugins/slidev) appears in **Settings → Plugins**. Off by default. When on, a document whose frontmatter contains `slides: true` gets an **Open in Slidev** action that opens the deck in its own window, rendered by a [Slidev](https://sli.dev/) you install yourself — OpenKnowledge does not download or bundle one. Install it globally (`npm install -g @slidev/cli @slidev/theme-default`) or add those packages to the project (a project-local install takes precedence). Slidev themes ship separately from the CLI and a deck cannot open without the theme it declares. Desktop only; the action stays hidden until a `slidev` binary resolves. |-| `agents.autoApproveOkTools` | boolean | `true` | user | Auto-approve OpenKnowledge's own MCP tools (and the `ok open` command on Claude) for agents launched from the built-in [docked terminal](/docs/features/editor#terminal) on macOS and Linux, so reading and writing the knowledge base runs without a per-call approval prompt. Destructive tools (`delete`, `move`, `share_link`, `install`, `import`) still prompt; other shell commands and non-OpenKnowledge file edits are untouched. Per-machine preference; toggle from **Settings → Terminal**. Best-effort per agent — Claude uses an allow/ask list, Codex uses its per-server `approve` mode (and only when its OpenKnowledge entry is already configured). |+| `agents.autoApproveOkTools` | boolean | `true` | user | Auto-approve OpenKnowledge's own MCP tools (and the `ok open` command on Claude) for agents launched from the built-in [docked terminal](/docs/features/editor#terminal), so reading and writing the knowledge base runs without a per-call approval prompt. Destructive tools (`delete`, `move`, `share_link`, `install`, `import`) still prompt; other shell commands and non-OpenKnowledge file edits are untouched. Per-machine preference; toggle from **Settings → Terminal**. Best-effort per agent — Claude uses an allow/ask list, Codex uses its per-server `approve` mode (and only when its OpenKnowledge entry is already configured). || `telemetry.localSink.enabled` | boolean | `true` | project | Write local diagnostic spans + logs under `.ok/local/` for `ok diagnose bundle` to collect. Local-only: nothing leaves the machine until you run `bundle`. Set `false` for sensitive workspaces. || `telemetry.localSink.spans.maxBytes` | number | `52428800` (~50 MB) | project | Max size of the local diagnostic spans file before it rotates. || `telemetry.localSink.logs.maxBytes` | number | `26214400` (~25 MB) | project | Max size of the local diagnostic logs file before it rotates. |diff --git a/docs/content/reference/what-open-knowledge-writes.mdx b/docs/content/reference/what-open-knowledge-writes.mdxindex 888a890e3..745c10230 100644--- a/docs/content/reference/what-open-knowledge-writes.mdx+++ b/docs/content/reference/what-open-knowledge-writes.mdx@@ -64,7 +64,7 @@ The first two rows below live in OpenKnowledge's own `~/.ok/` directory and are| `~/.ok/env.sh` | A managed shim that prepends `~/.ok/bin` to your `PATH` | Outside-project (home dir) || `~/.zshrc`, `~/.bash_profile`, `~/.config/fish/conf.d/open-knowledge.fish` | A **fenced managed block** that sources `~/.ok/env.sh` — written **only if you consent** in the first-launch dialog | Outside-project (shell config) |-If you decline, only `ok` typed in an *external* terminal (Terminal, iTerm) is affected — the app's built-in terminal on macOS and Linux, the MCP server, and the "Open with AI" launches all work without it. You can add it later from **File → Set up OpenKnowledge integrations…**. Machines that already had the block from a version before the consent dialog are treated as consented: the block is left in place and maintained.+If you decline, only `ok` typed in an *external* terminal (Terminal, iTerm) is affected — the app's built-in terminal, the MCP server, and the "Open with AI" launches all work without it. You can add it later from **File → Set up OpenKnowledge integrations…**. Machines that already had the block from a version before the consent dialog are treated as consented: the block is left in place and maintained.The managed block is clearly fenced so you can see and remove it:@@ -119,6 +119,7 @@ The app runs a collaboration server for the open project. It writes runtime stat| `.ok/local/logs/server-*.jsonl` | Local server logs, rotated at ~25 MB | In-project, gitignored || `.ok/local/cache/<branch>/backlinks.json` | Backlink-graph cache | In-project, gitignored || `.ok/local/installed-skills.json` | Per-project skill-install markers (which editors each skill is projected into) | In-project, gitignored |+| `.ok/local/terminal/claude-settings-{mcp,tools,mcp-tools}.json` | Windows-only Claude launch settings written when **Open in Claude** requests MCP or tool preapproval; one of three possible files, overwritten rather than appended on each launch that uses that combination. macOS and Linux pass the same settings inline | In-project, gitignored || `.ok/local/comments/` | [Comments](/docs/features/comments) left on documents, one JSON file each — the note, the passage it quotes, and whether it has been sent | In-project, gitignored || `.ok/worktrees/<branch>/` | Git worktree checkout created when you open a branch in its own window (project switcher); the path is also added to `.git/info/exclude` | In-project, gitignored || `.git/ok/` — or `.git/worktrees/<name>/ok/` in a linked worktree, or the enclosing repo's `.git/ok-<slug>/` when your project is a subfolder of a larger repo | Shadow git repo holding per-writer work-in-progress refs; always inside a git admin dir, never in your content tree | In-project, gitignored (inside `.git/`) |diff --git a/packages/app/BUNDLE-SIZE.md b/packages/app/BUNDLE-SIZE.mdindex c784187ea..d33276122 100644--- a/packages/app/BUNDLE-SIZE.md+++ b/packages/app/BUNDLE-SIZE.md@@ -72,3 +72,5 @@ Combined-chunks 4.75->4.78 MB for the Open Knowledge Format plugin controls, genCombined-chunks 4.85->4.95 MB for Korean (`ko`), the twelfth supported locale. Its catalog is emitted as a separate on-demand chunk, so the increase is combined-chunk inventory rather than eager weight: the branch measured 4.86 MB locally, 8.85 kB over the prior ceiling, while the main app remained at 420.63 kB against its 487 kB limit and CSS at 8.36 kB against 59 kB. The new ceiling leaves about 91 kB (1.9%) of headroom for the local-to-CI variance recorded above.Combined-chunks 4.95->6.55 MB for the `.excalidraw` canvas doc editor (`@excalidraw/excalidraw@^0.18.1`, matched to Excalidraw's own file format via `serializeAsJSON` / `restore`). Weight is entirely on-demand: `ExcalidrawDocEditor` mounts through `EditorActivityPool` behind the existing `React.lazy` gate, and Excalidraw itself defers its scene renderer, mermaid-to-excalidraw importer, and rough.js / perfect-freehand stack into its own async chunks — the eager main bundle is unaffected (measured 421.2 kB against its 487 kB limit). The gzipped total across the added `chunk-EIO257PC-*.js` + `dist-*.js` + `ExcalidrawDocEditor-*.js` chunks measures 6.41 MB locally, ~1.46 MB above the prior 4.95 MB ceiling; 6.55 MB carries the addition with ~140 kB headroom for the local-to-CI variance recorded above. No smaller Excalidraw slice exists on npm (the package ships one entry with the scene renderer, roughjs, perfect-freehand, `@excalidraw/laser-pointer`, and `@excalidraw/mermaid-to-excalidraw` all wired together), and the workspace deliberately vendors the fonts to `packages/app/public/excalidraw-assets/` rather than accepting the upstream `esm.sh` CDN fallback (see `scripts/copy-excalidraw-assets.mjs`) — the vendored assets are static files under `public/`, not JS, so they do not count against this budget.++Combined-chunks 6.55->6.56 MB for reload-safe terminal consent across config-epoch rebuilds. The gate retains the last fully synced project-local value so a live adopted PTY is not unmounted during the transient unsynced window, while an explicit opt-out remains closed. Exact CI measured 6,550,051 B, 51 B over the former ceiling; the eager main bundle remained at 438.61 kB against 487 kB because the terminal session surface is lazy. The 10 kB ratchet records the measured state-machine cost without changing the eager-load budget.diff --git a/packages/app/package.json b/packages/app/package.jsonindex 89f0aa0b0..7a10e0cad 100644--- a/packages/app/package.json+++ b/packages/app/package.json@@ -55,7 +55,7 @@{"name": "all JS chunks combined (gzipped)","path": "dist/assets/*.js",- "limit": "6.55 MB",+ "limit": "6.56 MB","gzip": true,"running": false},diff --git a/packages/app/src/App.tsx b/packages/app/src/App.tsxindex a19f598d0..9a127bf03 100644--- a/packages/app/src/App.tsx+++ b/packages/app/src/App.tsx@@ -777,9 +777,8 @@ function AppBody() {// carries: the terminal launches next to an already-open editor, so that// directive would point the agent at a surface the user is already viewing.// Null on the web host (no real OS shell) AND on desktop hosts where the PTY- // is unavailable (`config.ptyAvailable` is false on Windows), so the menu- // rows that consume it render- // nothing rather than a silent no-op: the docked terminal in EditorPane is+ // is unavailable (`config.ptyAvailable` is false), so the menu rows that+ // consume it render nothing rather than a silent no-op: the docked terminal in EditorPane is// gated on the same `ptyAvailable` flag, so a Terminal row here would launch// into a surface that never mounts. Mirrors the gate in EditorPane / Settings// / AppMenubar.diff --git a/packages/app/src/components/AppMenubar.dom.test.tsx b/packages/app/src/components/AppMenubar.dom.test.tsxindex d40b67576..5e8985042 100644--- a/packages/app/src/components/AppMenubar.dom.test.tsx+++ b/packages/app/src/components/AppMenubar.dom.test.tsx@@ -245,6 +245,16 @@ describe('AppMenubar View terminal toggle', () => {expect(screen.queryByRole('menuitem', { name: /Show Terminal/ })).toBeNull();expect(screen.queryByRole('menuitem', { name: /Hide Terminal/ })).toBeNull();});++ test('Windows exposes the terminal toggle when the build supports PTYs', async () => {+ installBridge('win32', 'editor', {+ ptyAvailable: true,+ queryResult: snapshot(false),+ });+ await openMenu('View');++ expect(await screen.findByRole('menuitem', { name: /Show Terminal/ })).not.toBeNull();+ });});describe('AppMenubar drag-suspension attributes', () => {diff --git a/packages/app/src/components/AppMenubar.tsx b/packages/app/src/components/AppMenubar.tsxindex ffcde540f..f2ff1d68b 100644--- a/packages/app/src/components/AppMenubar.tsx+++ b/packages/app/src/components/AppMenubar.tsx@@ -17,8 +17,8 @@* that drives the native menu's rendering — refreshed each time a menu* opens, so it is at most one open stale.*- * Terminal controls stay capability-gated: Linux exposes the View toggle,- * while Windows keeps it absent until its PTY implementation ships.+ * Terminal controls stay capability-gated so hosts without a usable PTY never+ * render actions that can only fail.*/import { useLingui } from '@lingui/react/macro';diff --git a/packages/app/src/components/ClaudeReadinessBanner.tsx b/packages/app/src/components/ClaudeReadinessBanner.tsxindex d8df07b7e..b2fc12cca 100644--- a/packages/app/src/components/ClaudeReadinessBanner.tsx+++ b/packages/app/src/components/ClaudeReadinessBanner.tsx@@ -19,10 +19,10 @@* it never covers the shell prompt or first output in the degraded states.*/import { useLingui } from '@lingui/react/macro';-import { X } from 'lucide-react';import { toast } from 'sonner';import { Button } from '@/components/ui/button';import type { ClaudeReadiness, OkDesktopBridge } from '@/lib/desktop-bridge-types';+import { TerminalNoticeBanner } from './TerminalNoticeBanner';/** Claude Code docs landing — install + setup instructions live here. */const CLAUDE_CODE_DOCS_URL = 'https://docs.claude.com/en/docs/claude-code';@@ -85,28 +85,20 @@ export function ClaudeReadinessBanner({}return (- <div- role="status"+ <TerminalNoticeBanner// Stable test seam: the editor page carries several app-wide role="status"// nodes (SelectionAnnouncer, ConnectingBanner), so smoke tests scope to this// attribute instead of an ambiguous getByRole('status'). Mirrors the// [data-terminal-status] / settings-terminal-toggle data-testid convention.- data-testid="terminal-readiness-banner"- className="flex shrink-0 items-center gap-3 border-border border-b bg-muted px-3 py-2 text-foreground text-xs"+ testId="terminal-readiness-banner"+ onDismiss={onDismiss}+ action={+ <Button size="sm" variant="secondary" className="shrink-0" onClick={handleAction}>+ {actionLabel}+ </Button>+ }>- <p className="min-w-0 flex-1">{message}</p>- <Button size="sm" variant="secondary" className="shrink-0" onClick={handleAction}>- {actionLabel}- </Button>- <Button- size="icon"- variant="ghost"- aria-label={t`Dismiss`}- className="size-6 shrink-0"- onClick={onDismiss}- >- <X aria-hidden="true" className="size-4" />- </Button>- </div>+ {message}+ </TerminalNoticeBanner>);}diff --git a/packages/app/src/components/CommandPalette.dom.test.tsx b/packages/app/src/components/CommandPalette.dom.test.tsxindex 030e61145..b8eb38bb6 100644--- a/packages/app/src/components/CommandPalette.dom.test.tsx+++ b/packages/app/src/components/CommandPalette.dom.test.tsx@@ -1412,7 +1412,7 @@ describe('Cmd+K menu-parity backfill', () => {}});- test('off-mac and incomplete desktop bridges hide every PTY-backed palette command', async () => {+ test('PTY-less and incomplete desktop bridges hide every PTY-backed palette command', async () => {const terminalCommands = [['show terminal', 'toggle-terminal'],['new terminal', 'new-terminal'],diff --git a/packages/app/src/components/EditorPane.tsx b/packages/app/src/components/EditorPane.tsxindex 19d2044dd..fb0e4b3cb 100644--- a/packages/app/src/components/EditorPane.tsx+++ b/packages/app/src/components/EditorPane.tsx@@ -172,8 +172,8 @@ export function EditorPane({ onOpenSearch }: EditorPaneProps = {}) {// The terminal feature (dock + header New chat / toggle) needs not just a// desktop bridge but one that actually exposes the `terminal` surface — a// session-only bridge (some E2E hosts) has none — AND a host that can- // actually spawn a PTY: `config.ptyAvailable` is false on Windows, where a- // rendered affordance would only surface a spawn failure. Gate every+ // actually spawn a PTY: `config.ptyAvailable` is false on unsupported hosts,+ // where a rendered affordance would only surface a spawn failure. Gate every// terminal affordance on both so a control that can't launch never renders.// A popped-out note window is a reading/writing surface for one document, so// it carries no docked terminal. Deferred rather than refused: the surface is@@ -809,10 +809,10 @@ export function EditorPane({ onOpenSearch }: EditorPaneProps = {}) {</div></div>{/* The agents host mounts UNCONDITIONALLY — agent threads are server-hosted,- so the panel works on the web host and on Windows/Linux where pty is- unavailable. The terminal host mounts only where a shell can actually- spawn (`terminalAvailable` folds in `ptyAvailable`); an empty terminal- dock on those hosts would be a control that can never do anything. */}+ so the panel works on the web host and on hosts where pty is unavailable.+ The terminal host mounts only where a shell can actually spawn+ (`terminalAvailable` folds in `ptyAvailable`); an empty terminal dock+ on those hosts would be a control that can never do anything. */}{noteWindow ? null : (<Suspense fallback={null}><SessionsHostdiff --git a/packages/app/src/components/TerminalCliMissingBanner.tsx b/packages/app/src/components/TerminalCliMissingBanner.tsxindex 60173fc5b..9fb9dde7f 100644--- a/packages/app/src/components/TerminalCliMissingBanner.tsx+++ b/packages/app/src/components/TerminalCliMissingBanner.tsx@@ -13,9 +13,9 @@*/import { TERMINAL_CLIS, type TerminalCli } from '@inkeep/open-knowledge-core';import { useLingui } from '@lingui/react/macro';-import { X } from 'lucide-react';import { Button } from '@/components/ui/button';import type { OkDesktopBridge } from '@/lib/desktop-bridge-types';+import { TerminalNoticeBanner } from './TerminalNoticeBanner';interface TerminalCliMissingBannerProps {readonly cli: TerminalCli;@@ -33,31 +33,21 @@ export function TerminalCliMissingBanner({const { bin, displayName, docsUrl } = TERMINAL_CLIS[cli];return (- <div- role="status"- data-testid="terminal-cli-missing-banner"- className="flex shrink-0 items-center gap-3 border-border border-b bg-muted px-3 py-2 text-foreground text-xs"+ <TerminalNoticeBanner+ testId="terminal-cli-missing-banner"+ onDismiss={onDismiss}+ action={+ <Button+ size="sm"+ variant="secondary"+ className="shrink-0"+ onClick={() => void bridge.shell.openExternal(docsUrl)}+ >+ {t`Get ${displayName}`}+ </Button>+ }>- <p className="min-w-0 flex-1">- {t`${displayName} (${bin}) isn't installed or on your PATH.`}- </p>- <Button- size="sm"- variant="secondary"- className="shrink-0"- onClick={() => void bridge.shell.openExternal(docsUrl)}- >- {t`Get ${displayName}`}- </Button>- <Button- size="icon"- variant="ghost"- aria-label={t`Dismiss`}- className="size-6 shrink-0"- onClick={onDismiss}- >- <X aria-hidden="true" className="size-4" />- </Button>- </div>+ {t`${displayName} (${bin}) isn't installed or on your PATH.`}+ </TerminalNoticeBanner>);}diff --git a/packages/app/src/components/TerminalCliUnverifiedBanner.tsx b/packages/app/src/components/TerminalCliUnverifiedBanner.tsxindex 8d2e5d9b8..0a6509360 100644--- a/packages/app/src/components/TerminalCliUnverifiedBanner.tsx+++ b/packages/app/src/components/TerminalCliUnverifiedBanner.tsx@@ -13,8 +13,7 @@*/import { TERMINAL_CLIS, type TerminalCli } from '@inkeep/open-knowledge-core';import { useLingui } from '@lingui/react/macro';-import { X } from 'lucide-react';-import { Button } from '@/components/ui/button';+import { TerminalNoticeBanner } from './TerminalNoticeBanner';interface TerminalCliUnverifiedBannerProps {readonly cli: TerminalCli;@@ -27,23 +26,8 @@ export function TerminalCliUnverifiedBanner({ cli, onDismiss }: TerminalCliUnverconst { bin, displayName } = TERMINAL_CLIS[cli];return (- <div- role="status"- data-testid="terminal-cli-unverified-banner"- className="flex shrink-0 items-center gap-3 border-border border-b bg-muted px-3 py-2 text-foreground text-xs"- >- <p className="min-w-0 flex-1">- {t`Couldn't verify that ${displayName} (${bin}) is available, so this is a plain shell. You can still run ${bin} yourself.`}- </p>- <Button- size="icon"- variant="ghost"- aria-label={t`Dismiss`}- className="size-6 shrink-0"- onClick={onDismiss}- >- <X aria-hidden="true" className="size-4" />- </Button>- </div>+ <TerminalNoticeBanner testId="terminal-cli-unverified-banner" onDismiss={onDismiss}>+ {t`Couldn't verify that ${displayName} (${bin}) is available, so this is a plain shell. You can still run ${bin} yourself.`}+ </TerminalNoticeBanner>);}diff --git a/packages/app/src/components/TerminalGate.dom.test.tsx b/packages/app/src/components/TerminalGate.dom.test.tsxindex ba6e30795..517b164c9 100644--- a/packages/app/src/components/TerminalGate.dom.test.tsx+++ b/packages/app/src/components/TerminalGate.dom.test.tsx@@ -11,7 +11,7 @@*/import { act, cleanup, render, screen } from '@testing-library/react';-import type { ReactNode } from 'react';+import { type ReactNode, useEffect } from 'react';import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';import type { OkDesktopBridge } from '@/lib/desktop-bridge-types';@@ -45,6 +45,9 @@ vi.doMock('@/hooks/use-terminal-enabled', () => ({// biome-ignore lint/suspicious/noExplicitAny: captured mock-component props, asserted structurallylet lastPanelProps: Record<string, any> | null = null;+let panelRenders = 0;+let panelMounts = 0;+let panelUnmounts = 0;// Named so the Suspense-fallback test below — which calls vi.resetModules() and// registers its own deferred ./TerminalPanel stub to get a fresh module graph —// can put the file-level stub back afterward. Without that restore the registry@@ -54,7 +57,14 @@ let lastPanelProps: Record<string, any> | null = null;const mockPanelModule = () => ({// biome-ignore lint/suspicious/noExplicitAny: test stubTerminalPanel: (props: any) => {+ panelRenders += 1;lastPanelProps = props;+ useEffect(() => {+ panelMounts += 1;+ return () => {+ panelUnmounts += 1;+ };+ }, []);return <span data-testid="terminal-panel" />;},});@@ -72,6 +82,20 @@ function notice() {return screen.queryByRole('region', { name: 'Terminal disabled' });}+async function resolvePanelPayloadForSyncAssertion() {+ // The Suspense fallback and the pre-sync branch show the same notice. Resolve+ // the lazy payload first so a wrongly opened gate cannot hide behind fallback+ // DOM, and so a suspended pass is not lost when a render count is asserted.+ // Returns with consentState open and synced; callers must re-seed it.+ consentState = { enabled: true, synced: true };+ const warmup = renderGate();+ await screen.findByTestId('terminal-panel');+ warmup.unmount();+ panelRenders = 0;+ panelMounts = 0;+ panelUnmounts = 0;+}+describe('TerminalGate', () => {beforeEach(() => {consentState = { enabled: null, synced: true };@@ -82,6 +106,9 @@ describe('TerminalGate', () => {writerCalls.length = 0;toastErrors.length = 0;lastPanelProps = null;+ panelRenders = 0;+ panelMounts = 0;+ panelUnmounts = 0;});afterEach(() => {cleanup();@@ -149,7 +176,8 @@ describe('TerminalGate', () => {expect(screen.queryByTestId('terminal-panel')).toBeNull();});- test('does not flash the shell before the binding syncs (cold start)', () => {+ test('does not flash the shell before the binding syncs (cold start)', async () => {+ await resolvePanelPayloadForSyncAssertion();// Pre-sync the leaf reads as the cold-start null; mounting now would spawn a// PTY the main backstop refuses if the project turns out to be opted out.consentState = { enabled: null, synced: false };@@ -158,7 +186,75 @@ describe('TerminalGate', () => {expect(notice()).toBeNull();});- test('announces that the terminal is starting while the binding syncs (PRD-8313)', () => {+ test('mounts directly when the first project-local consent sync completes', async () => {+ await resolvePanelPayloadForSyncAssertion();++ consentState = { enabled: null, synced: false };+ const view = renderGate();+ expect(screen.queryByTestId('terminal-panel')).toBeNull();++ const rendersBeforeSync = panelRenders;+ consentState = { enabled: true, synced: true };+ view.rerender(<TerminalGate bridge={bridge} />);++ expect(await screen.findByTestId('terminal-panel')).toBeTruthy();+ // The live binding opens the gate in the transition's first pass; the+ // settled-consent update produces the second render without remounting.+ expect(panelRenders).toBe(rendersBeforeSync + 2);+ expect(panelMounts).toBe(1);+ });++ test('keeps a mounted terminal alive through a transient config epoch rebuild', async () => {+ consentState = { enabled: true, synced: true };+ const view = renderGate();+ expect(await screen.findByTestId('terminal-panel')).toBeTruthy();+ expect(panelMounts).toBe(1);++ consentState = { enabled: null, synced: false };+ view.rerender(<TerminalGate bridge={bridge} />);++ expect(screen.getByTestId('terminal-panel')).toBeTruthy();+ expect(panelMounts).toBe(1);+ expect(panelUnmounts).toBe(0);++ consentState = { enabled: true, synced: true };+ view.rerender(<TerminalGate bridge={bridge} />);+ expect(screen.getByTestId('terminal-panel')).toBeTruthy();+ expect(panelMounts).toBe(1);+ expect(panelUnmounts).toBe(0);+ });++ test('retains an explicit opt-out through a transient config epoch rebuild', () => {+ consentState = { enabled: false, synced: true };+ const view = renderGate();+ expect(screen.getByRole('region', { name: 'Terminal disabled' })).toBeTruthy();++ consentState = { enabled: null, synced: false };+ view.rerender(<TerminalGate bridge={bridge} />);++ expect(screen.getByRole('region', { name: 'Terminal disabled' })).toBeTruthy();+ expect(screen.queryByTestId('terminal-panel')).toBeNull();+ expect(panelMounts).toBe(0);+ });++ test('an explicit synced revoke still unmounts a running terminal', async () => {+ consentState = { enabled: true, synced: true };+ const view = renderGate();+ expect(await screen.findByTestId('terminal-panel')).toBeTruthy();+ const rendersBeforeRevoke = panelRenders;++ consentState = { enabled: false, synced: true };+ view.rerender(<TerminalGate bridge={bridge} />);++ expect(screen.getByRole('region', { name: 'Terminal disabled' })).toBeTruthy();+ expect(screen.queryByTestId('terminal-panel')).toBeNull();+ expect(panelRenders).toBe(rendersBeforeRevoke);+ expect(panelMounts).toBe(1);+ expect(panelUnmounts).toBe(1);+ });++ test('announces that the terminal is starting while the binding syncs (PRD-8313)', async () => {+ await resolvePanelPayloadForSyncAssertion();// Holding the mount is right; rendering nothing while we hold it is not. A// featureless pane is indistinguishable from "the keystroke did nothing", so// a user whose cold start runs long re-invokes and stacks up tabs. The panediff --git a/packages/app/src/components/TerminalGate.tsx b/packages/app/src/components/TerminalGate.tsxindex d631ea27d..0e529e2f8 100644--- a/packages/app/src/components/TerminalGate.tsx+++ b/packages/app/src/components/TerminalGate.tsx@@ -7,19 +7,20 @@* (human-only), so an agent can never silence a human who wants the terminal nor* re-enable a shell a human turned off; the explicit opt-out is the only refusal.*- * The mount waits for the project-local binding to sync, so an opted-out project- * never flashes the shell (nor fires a PTY spawn the main backstop would refuse)- * during the cold-start window before the real value is known. That wait is- * unbounded — the binding syncs over the collab WebSocket, and a congested cold- * start can hold it for seconds — so both pre-mount states render a pending- * notice rather than an empty pane: withholding the shell is right, but saying- * nothing while withholding it reads as a dead keystroke and gets re-invoked.+ * The first mount waits for the project-local binding to sync, so an opted-out+ * project never flashes the shell (nor fires a PTY spawn the main backstop would+ * refuse) during cold start. After that first sync, the last settled decision is+ * retained through config-binding rebuilds: a live terminal stays mounted, and+ * an opted-out project stays closed. The cold-start wait is unbounded — the+ * binding syncs over the collab WebSocket, and congestion can hold it for seconds+ * — so both pre-mount states render a pending notice rather than an empty pane+ * that would make the user's toggle look unresponsive.*- * Opting out while a shell is running unmounts TerminalPanel, whose cleanup kills- * the PTY — turning the terminal off takes effect immediately.+ * A newly-synced opt-out while a shell is running unmounts TerminalPanel, whose+ * cleanup kills the PTY — turning the terminal off takes effect immediately.*/import { useLingui } from '@lingui/react/macro';-import { Suspense, useEffect } from 'react';+import { Suspense, useEffect, useState } from 'react';import { ErrorBoundary, type FallbackProps } from 'react-error-boundary';import { toast } from 'sonner';import { Button } from '@/components/ui/button';@@ -69,7 +70,30 @@ export function TerminalGate({const writer = useTerminalEnabledWriter();const { t } = useLingui();- const optedOut = synced && enabled === false;+ // Starts unlatched even when the current binding is already synced. Pre-sync+ // `gateEnabled` reads as this null, but `hasSynced: false` holds `gateSynced`+ // false. Both consumers require `gateSynced`, so the null cannot be observed+ // as permission before this latch settles.+ const [settledConsent, setSettledConsent] = useState<{+ enabled: boolean | null;+ hasSynced: boolean;+ }>({ enabled: null, hasSynced: false });+ useEffect(() => {+ if (!synced) return;+ setSettledConsent((previous) =>+ previous.hasSynced && previous.enabled === enabled ? previous : { enabled, hasSynced: true },+ );+ }, [enabled, synced]);++ // Config bindings rebuild when the server epoch arrives or changes. Keep the+ // last fully-synced consent during that transient so a live terminal is not+ // unmounted and killed, while an opted-out project cannot briefly spawn one.+ // A newly-synced explicit revoke still wins immediately.+ // Project opens currently create a new renderer. If same-renderer project+ // switching gains a main-process sender, key or reset this latch by project.+ const gateSynced = synced || settledConsent.hasSynced;+ const gateEnabled = synced ? enabled : settledConsent.enabled;+ const optedOut = gateSynced && gateEnabled === false;// Warm the panel chunk without waiting for the gate to open. Plain `lazy()`// runs its factory only when the lazy element first renders, and that render@@ -78,18 +102,11 @@ export function TerminalGate({// it does not weaken what the gate withholds; it only stops the two waits from// being serialized. `.preload()` is idempotent, so repeat calls are free.//- // Skipped once the project is known to have opted out. `synced` is NOT- // monotonic — ConfigProvider re-keys its bindings on `[collabUrl,- // serverInstanceId]` and every rebuild nulls the state, so it goes back to- // false on the boot-time epoch landing, on a server respawn, and on a project- // switch. So this is a best-effort skip, not a guarantee: `optedOut` reads- // false during each of those windows and the warm proceeds. The cost when it- // does is a chunk fetched and never mounted — genuinely new here, since plain- // `lazy()` only ran its factory from inside the opened gate and so an- // opted-out project fetched nothing at all. It stays bounded because- // `.preload()` memoizes: one fetch per renderer, worst case. What the guard- // buys is the common dock-reveal case on an opted-out project, where the- // value is already known at mount.+ // Skipped once the project is known to have opted out. The settled-consent+ // latch above carries that decision through config binding rebuilds, so an+ // opted-out project stops re-warming on every rebuild. It stays best-effort on+ // cold start: before the first sync `hasSynced` is false, so an opted-out+ // project still warms once per renderer.useEffect(() => {if (optedOut) return;TerminalPanel.preload();@@ -104,7 +121,7 @@ export function TerminalGate({if (!result.ok) toast.error(t`Could not enable the terminal: ${result.error}`);}- if (synced && !optedOut) {+ if (gateSynced && !optedOut) {return (// Boundary OUTER, Suspense INNER (same composition as SettingsDialog /// EditorActivityPool): Suspense only covers the lazy chunk's pending state.diff --git a/packages/app/src/components/TerminalNoticeBanner.dom.test.tsx b/packages/app/src/components/TerminalNoticeBanner.dom.test.tsxnew file mode 100644index 000000000..ba3c4f8ef--- /dev/null+++ b/packages/app/src/components/TerminalNoticeBanner.dom.test.tsx@@ -0,0 +1,93 @@+import * as actualLinguiMacro from '@lingui/react/macro';+import { cleanup, render, screen } from '@testing-library/react';+import userEvent from '@testing-library/user-event';+import { afterEach, describe, expect, test, vi } from 'vitest';+import { Button } from '@/components/ui/button';++vi.doMock('@lingui/react/macro', () => ({+ ...actualLinguiMacro,+ useLingui: () => ({+ t: (strings: TemplateStringsArray, ...values: unknown[]) =>+ strings.reduce((acc, part, index) => `${acc}${part}${values[index] ?? ''}`, ''),+ }),+}));++const { TerminalNoticeBanner } = await import('./TerminalNoticeBanner');++describe('TerminalNoticeBanner', () => {+ afterEach(cleanup);++ test('is a non-shrinking status strip with a stable test id', () => {+ render(+ <TerminalNoticeBanner testId="terminal-test-notice" onDismiss={() => {}}>+ Recoverable notice+ </TerminalNoticeBanner>,+ );+ const banner = screen.getByTestId('terminal-test-notice');+ expect(banner.getAttribute('role')).toBe('status');+ expect(banner.className).toContain('shrink-0');+ });++ test('dismisses through the shared icon control', async () => {+ const onDismiss = vi.fn();+ render(+ <TerminalNoticeBanner testId="terminal-test-notice" onDismiss={onDismiss}>+ Recoverable notice+ </TerminalNoticeBanner>,+ );+ await userEvent.click(screen.getByRole('button', { name: 'Dismiss' }));+ expect(onDismiss).toHaveBeenCalledOnce();+ });++ test('offers only the dismiss control when no action is supplied', () => {+ render(+ <TerminalNoticeBanner testId="terminal-test-notice" onDismiss={() => {}}>+ Recoverable notice+ </TerminalNoticeBanner>,+ );+ const buttons = screen.getAllByRole('button');+ expect(buttons).toHaveLength(1);+ expect(buttons[0]?.getAttribute('aria-label')).toBe('Dismiss');+ });++ test('renders a supplied action between the message and the dismiss control', () => {+ render(+ <TerminalNoticeBanner+ testId="terminal-test-notice"+ onDismiss={() => {}}+ action={<Button size="sm">Do the thing</Button>}+ >+ Recoverable notice+ </TerminalNoticeBanner>,+ );++ const message = screen.getByText('Recoverable notice');+ const action = screen.getByRole('button', { name: 'Do the thing' });+ const dismiss = screen.getByRole('button', { name: 'Dismiss' });++ expect(message.compareDocumentPosition(action) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();+ expect(action.compareDocumentPosition(dismiss) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();+ });++ test('an action click does not dismiss the notice', async () => {+ const onAction = vi.fn();+ const onDismiss = vi.fn();+ render(+ <TerminalNoticeBanner+ testId="terminal-test-notice"+ onDismiss={onDismiss}+ action={+ <Button size="sm" onClick={onAction}>+ Do the thing+ </Button>+ }+ >+ Recoverable notice+ </TerminalNoticeBanner>,+ );++ await userEvent.click(screen.getByRole('button', { name: 'Do the thing' }));+ expect(onAction).toHaveBeenCalledOnce();+ expect(onDismiss).not.toHaveBeenCalled();+ });+});diff --git a/packages/app/src/components/TerminalNoticeBanner.tsx b/packages/app/src/components/TerminalNoticeBanner.tsxnew file mode 100644index 000000000..670c4e27f--- /dev/null+++ b/packages/app/src/components/TerminalNoticeBanner.tsx@@ -0,0 +1,41 @@+import { useLingui } from '@lingui/react/macro';+import { X } from 'lucide-react';+import type { ReactNode } from 'react';+import { Button } from '@/components/ui/button';++interface TerminalNoticeBannerProps {+ readonly testId: string;+ readonly children: ReactNode;+ /** Optional affordance rendered between the message and the dismiss control. */+ readonly action?: ReactNode;+ readonly onDismiss: () => void;+}++/** Dismissible, non-blocking status strip shared by recoverable terminal notices. */+export function TerminalNoticeBanner({+ testId,+ children,+ action,+ onDismiss,+}: TerminalNoticeBannerProps) {+ const { t } = useLingui();+ return (+ <div+ role="status"+ data-testid={testId}+ className="flex shrink-0 items-center gap-3 border-border border-b bg-muted px-3 py-2 text-foreground text-xs"+ >+ <p className="min-w-0 flex-1">{children}</p>+ {action}+ <Button+ size="icon"+ variant="ghost"+ aria-label={t`Dismiss`}+ className="size-6 shrink-0"+ onClick={onDismiss}+ >+ <X aria-hidden="true" className="size-4" />+ </Button>+ </div>+ );+}diff --git a/packages/app/src/components/TerminalPanel.dom.test.tsx b/packages/app/src/components/TerminalPanel.dom.test.tsxindex d65a7d43a..0ad7d5f81 100644--- a/packages/app/src/components/TerminalPanel.dom.test.tsx+++ b/packages/app/src/components/TerminalPanel.dom.test.tsx@@ -11,12 +11,14 @@*/import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';-import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';+import { afterEach, beforeEach, describe, expect, onTestFinished, test, vi } from 'vitest';import type {ClaudeReadiness,OkDesktopBridge,+ OkPtyAdoptResult,OkPtyData,OkPtyExit,+ OkPtyNotice,} from '@/lib/desktop-bridge-types';import {applyModelledScroll,@@ -62,6 +64,9 @@ class MockTerminal {selection = '';hasSelection = vi.fn(() => this.selection.length > 0);getSelection = vi.fn(() => this.selection);+ clearSelection = vi.fn(() => {+ this.selection = '';+ });get _core() {return {coreMouseService: { activeEncoding: this.mouseEncoding },@@ -160,9 +165,20 @@ class MockTerminal {focus = vi.fn(() => {});dispose = vi.fn(() => {});paste = vi.fn((_data: string) => {});- write = vi.fn((_data: string, cb?: () => void) => {- cb?.();+ pendingWrites: Array<{ data: string; callback?: () => void }> = [];+ write = vi.fn((data: string, callback?: () => void) => {+ if (deferTerminalWrites) {+ this.pendingWrites.push({ data, callback });+ return;+ }+ callback?.();});+ flushPendingWrites(): void {+ for (const pending of this.pendingWrites.splice(0)) {+ if (terminalGeneratedInput !== null) this.onDataCb?.(terminalGeneratedInput);+ pending.callback?.();+ }+ }loadAddon = vi.fn((addon: unknown) => {if (webglThrows && addon instanceof MockWebglAddon) throw new Error('no webgl2 context');});@@ -205,6 +221,8 @@ class MockTerminal {let lastTerm: MockTerminal | null = null;let lastFit: MockFitAddon | null = null;let webglThrows = false;+let deferTerminalWrites = false;+let terminalGeneratedInput: string | null = null;// Drives the mocked next-themes `resolvedTheme`; mutate + rerender to exercise// a live light/dark switch.let mockResolvedTheme: string | undefined = 'dark';@@ -250,9 +268,7 @@ const WIRED: ClaudeReadiness = { claude: 'present', mcp: 'wired' };function makeBridge(createResult: CreateResult,preflight: ClaudeReadiness = WIRED,- adopt: (- id: string,- ) => Promise<{ ok: true; replay?: string } | { ok: false; reason: string }> = async () => ({+ adopt: (id: string) => Promise<OkPtyAdoptResult> = async () => ({ok: true,replay: '',}),@@ -260,8 +276,10 @@ function makeBridge() {const dataSubs: Array<(m: OkPtyData) => void> = [];const exitSubs: Array<(m: OkPtyExit) => void> = [];+ const noticeSubs: Array<(m: OkPtyNotice) => void> = [];const unsubData = vi.fn(() => {});const unsubExit = vi.fn(() => {});+ const unsubNotice = vi.fn(() => {});const openExternal = vi.fn(async (_url: string) => {});const openAsset = vi.fn(async (_relPath: string): Promise<{ ok: true } | { ok: false; reason: string }> => ({@@ -293,6 +311,10 @@ function makeBridge(exitSubs.push(cb);return unsubExit;}),+ onNotice: vi.fn((cb: (m: OkPtyNotice) => void) => {+ noticeSubs.push(cb);+ return unsubNotice;+ }),claudePreflight: vi.fn(async () => preflight),cliPreflight: vi.fn(async () => ({ onPath: 'present' as const })),rewireClaudeMcp,@@ -317,12 +339,16 @@ function makeBridge(rewireClaudeMcp,unsubData,unsubExit,+ unsubNotice,pushData: (m: OkPtyData) => {for (const f of dataSubs) f(m);},pushExit: (m: OkPtyExit) => {for (const f of exitSubs) f(m);},+ pushNotice: (m: OkPtyNotice) => {+ for (const f of noticeSubs) f(m);+ },};}@@ -336,6 +362,8 @@ describe('TerminalPanel', () => {roCallback = null;allROs = [];webglThrows = false;+ deferTerminalWrites = false;+ terminalGeneratedInput = null;mockResolvedTheme = 'dark';(globalThis as { ResizeObserver: unknown }).ResizeObserver = MockResizeObserver;Object.defineProperty(globalThis.navigator, 'clipboard', {@@ -438,6 +466,8 @@ describe('TerminalPanel', () => {// The adopted shell is nudged to repaint at the current viewport so a// full-screen TUI (claude, vim) redraws its screen after the reload.expect(terminal.resize).toHaveBeenCalledWith('pty-survivor', 80, 24);+ act(() => lastTerm?.onDataCb?.('user input'));+ expect(terminal.input).toHaveBeenCalledWith('pty-survivor', 'user input');});test('reload rehydration: writes the adopted session replay into xterm so the screen repaints', async () => {@@ -452,7 +482,7 @@ describe('TerminalPanel', () => {// fresh xterm so the reconnected tab repaints instead of coming back blank.// This is the renderer half of the replay contract the// main-process test pins on the producing side.- expect(lastTerm?.write).toHaveBeenCalledWith('REPLAYED-SCREEN-BYTES');+ expect(lastTerm?.write).toHaveBeenCalledWith('REPLAYED-SCREEN-BYTES', expect.any(Function));expect(terminal.create).not.toHaveBeenCalled();// Replayed bytes are output, so the pending notice must clear. Without the// markFirstOutput() call on this path a reload-recovered terminal would sit@@ -461,6 +491,149 @@ describe('TerminalPanel', () => {expect(screen.queryByTestId('terminal-starting-notice')).toBeNull();});+ test('reload rehydration: does not send replay-generated terminal replies into the live shell', async () => {+ deferTerminalWrites = true;+ terminalGeneratedInput = '\x1b[?1;2c';+ const { bridge, terminal } = makeBridge({ ok: true, ptyId: 'pty-fresh' }, WIRED, async () => ({+ ok: true,+ replay: '\x1b[c',+ }));+ render(<TerminalPanel bridge={bridge} adoptPtyId="pty-survivor" />);++ await waitFor(() => expect(terminal.onData).toHaveBeenCalledTimes(1));+ expect(document.querySelector('[data-terminal-status="starting"]')).toBeTruthy();+ expect(lastTerm?.focus).not.toHaveBeenCalled();+ act(() => lastTerm?.onDataCb?.('early user input'));+ expect(terminal.input).not.toHaveBeenCalledWith('pty-survivor', 'early user input');+ // The replay callback is still pending, so the TUI repaint nudge cannot be+ // gated behind replay parsing.+ expect(terminal.resize).toHaveBeenCalledWith('pty-survivor', 80, 24);+ act(() => lastTerm?.flushPendingWrites());++ // Replaying a retained Device Attributes request makes xterm answer it.+ // That answer belongs to the old screen reconstruction, not the live PTY;+ // forwarding it corrupts PowerShell's line editor before the next command.+ expect(terminal.input).not.toHaveBeenCalledWith('pty-survivor', '\x1b[?1;2c');+ expect(document.querySelector('[data-terminal-status="running"]')).toBeTruthy();+ expect(lastTerm?.focus).toHaveBeenCalledTimes(1);++ act(() => lastTerm?.onDataCb?.('user input'));+ expect(terminal.input).toHaveBeenCalledWith('pty-survivor', 'user input');+ });++ test('reload rehydration: gates direct input surfaces until replay completes', async () => {+ deferTerminalWrites = true;+ const { bridge, terminal, pushNotice } = makeBridge(+ { ok: true, ptyId: 'pty-fresh' },+ WIRED,+ async () => ({ ok: true, replay: 'REPLAYED-SCREEN-BYTES' }),+ 'win32',+ );+ render(<TerminalPanel bridge={bridge} adoptPtyId="pty-survivor" />);++ await waitFor(() => expect(lastTerm?.onDataCb).toBeTruthy());+ const term = lastTerm;+ if (term?.keyHandler == null || term.wheelHandler == null) {+ throw new Error('terminal input handlers not attached');+ }+ act(() =>+ pushNotice({+ ptyId: 'pty-survivor',+ notice: 'shell-resolved',+ shellFamily: 'powershell',+ }),+ );++ const shiftEnter = {+ type: 'keydown',+ key: 'Enter',+ shiftKey: true,+ preventDefault: vi.fn(() => {}),+ } as unknown as KeyboardEvent;+ expect(term.keyHandler(shiftEnter)).toBe(false);++ term.modes.mouseTrackingMode = 'any';+ term.mouseEncoding = 'SGR';+ expect(term.wheelHandler({ deltaY: 120, deltaMode: 0 } as unknown as WheelEvent)).toBe(true);++ const container = document.querySelector('[data-terminal-status]');+ if (container === null) throw new Error('terminal container not found');+ const file = new File(['x'], 'shot.png', { type: 'image/png' });+ fireEvent.drop(container, { dataTransfer: { types: ['Files'], files: [file] } });++ const ctrlV = {+ type: 'keydown',+ key: 'v',+ ctrlKey: true,+ shiftKey: false,+ altKey: false,+ metaKey: false,+ preventDefault: vi.fn(() => {}),+ } as unknown as KeyboardEvent;+ expect(term.keyHandler(ctrlV)).toBe(false);+ await act(async () => {});++ expect(terminal.input).not.toHaveBeenCalled();+ expect(navigator.clipboard.readText).not.toHaveBeenCalled();+ expect(term.paste).not.toHaveBeenCalled();++ act(() => term.flushPendingWrites());+ terminal.input.mockClear();++ expect(term.keyHandler(shiftEnter)).toBe(false);+ expect(terminal.input).toHaveBeenLastCalledWith('pty-survivor', '\n');++ terminal.input.mockClear();+ expect(term.wheelHandler({ deltaY: 120, deltaMode: 0 } as unknown as WheelEvent)).toBe(false);+ expect(terminal.input).toHaveBeenCalledTimes(1);++ terminal.input.mockClear();+ fireEvent.drop(container, { dataTransfer: { types: ['Files'], files: [file] } });+ expect(terminal.input).toHaveBeenCalledWith('pty-survivor', "'/dropped/shot.png' ");++ expect(term.keyHandler(ctrlV)).toBe(false);+ await act(async () => {});+ expect(navigator.clipboard.readText).toHaveBeenCalledTimes(1);+ expect(term.paste).toHaveBeenCalledWith('clipboard paste');+ });++ test('reload rehydration: a shell that exits during replay stays exited', async () => {+ deferTerminalWrites = true;+ const { bridge, terminal, pushExit } = makeBridge(+ { ok: true, ptyId: 'pty-fresh' },+ WIRED,+ async () => ({ ok: true, replay: 'REPLAYED-SCREEN-BYTES' }),+ );+ render(<TerminalPanel bridge={bridge} adoptPtyId="pty-survivor" />);++ await waitFor(() => expect(terminal.onExit).toHaveBeenCalledTimes(1));+ act(() => pushExit({ ptyId: 'pty-survivor', exitCode: 1, signal: null }));+ act(() => lastTerm?.flushPendingWrites());++ expect(document.querySelector('[data-terminal-status="exited"]')).toBeTruthy();+ expect(screen.getByRole('button', { name: 'Restart terminal' })).toBeTruthy();+ expect(lastTerm?.focus).not.toHaveBeenCalled();+ });++ test('reload rehydration: restores a standing unsupported-shell capability notice', async () => {+ const { bridge, terminal } = makeBridge(+ { ok: true, ptyId: 'pty-fresh' },+ WIRED,+ async () => ({+ ok: true,+ replay: '',+ shellNoticeReason: 'unsupported-family',+ }),+ 'win32',+ );+ render(<TerminalPanel bridge={bridge} adoptPtyId="pty-survivor" />);++ await waitFor(() => expect(terminal.adopt).toHaveBeenCalledWith('pty-survivor'));+ expect(screen.getByTestId('terminal-shell-notice-banner').textContent).toMatch(+ /\.ok\/local\/config\.yml.*PowerShell.*cmd\.exe.*Git Bash.*plain terminal only.*agent and command launches do not run/i,+ );+ });+test('reload rehydration: a refused adopt (session died in the gap) falls through to a fresh create', async () => {const { bridge, terminal } = makeBridge({ ok: true, ptyId: 'pty-fresh' }, WIRED, async () => ({ok: false,@@ -661,6 +834,81 @@ describe('TerminalPanel', () => {);});+ test('a PowerShell terminal doubles quotes 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\\O'Brien\\${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 file = new File(['x'], 'shot.png', { type: 'image/png' });+ const dataTransfer = { types: ['Files'], files: [file] };+ fireEvent.drop(container, { dataTransfer });++ expect(terminal.input).toHaveBeenCalledWith('pty-1', "'C:\\Users\\O''Brien\\shot.png' ");+ });++ test('a Git Bash terminal POSIX-quotes 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\\O'Brien\\${file.name}`;+ render(<TerminalPanel bridge={bridge} />);+ await waitFor(() => expect(lastTerm?.onDataCb).toBeTruthy());+ act(() => pushNotice({ ptyId: 'pty-1', notice: 'shell-resolved', shellFamily: 'bash' }));++ const container = document.querySelector('[data-terminal-status]');+ if (container === null) throw new Error('terminal container not found');+ const file = new File(['x'], 'shot.png', { type: 'image/png' });+ fireEvent.drop(container, { dataTransfer: { types: ['Files'], files: [file] } });++ expect(terminal.input).toHaveBeenCalledWith('pty-1', "'C:\\Users\\O'\\''Brien\\shot.png' ");+ });++ test('a cmd terminal quotes safe paths and refuses variable-expanding 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) =>+ file.name === 'unsafe.png' ? 'C:\\Users\\%USERNAME%\\unsafe.png' : 'C:\\Users\\A B\\safe.png';+ render(<TerminalPanel bridge={bridge} />);+ await waitFor(() => expect(lastTerm?.onDataCb).toBeTruthy());+ act(() => pushNotice({ ptyId: 'pty-1', notice: 'shell-resolved', shellFamily: 'cmd' }));++ const container = document.querySelector('[data-terminal-status]');+ if (container === null) throw new Error('terminal container not found');+ const safe = new File(['x'], 'safe.png', { type: 'image/png' });+ const unsafe = new File(['y'], 'unsafe.png', { type: 'image/png' });+ const dataTransfer = { types: ['Files'], files: [safe, unsafe] };+ fireEvent.drop(container, { dataTransfer });++ expect(terminal.input).toHaveBeenCalledWith('pty-1', '"C:\\Users\\A B\\safe.png" ');+ expect(screen.getByTestId('terminal-path-drop-notice-banner').textContent).toMatch(+ /could not be inserted safely/i,+ );+ });+test('a drop where every file resolves to no disk path writes nothing (clipboard blobs)', async () => {const { bridge, terminal } = makeBridge({ ok: true, ptyId: 'pty-1' });// Electron `webUtils.getPathForFile` returns '' for a File with no disk@@ -679,6 +927,7 @@ describe('TerminalPanel', () => {fireEvent.drop(container, { dataTransfer });expect(terminal.input).not.toHaveBeenCalled();+ expect(screen.getByTestId('terminal-path-drop-notice-banner')).toBeTruthy();});test('a mixed drop writes only the files that resolve to a disk path', async () => {@@ -1077,6 +1326,103 @@ describe('TerminalPanel', () => {expect(navigator.clipboard.writeText).not.toHaveBeenCalled();});+ test('Windows Ctrl+C copies with a selection and interrupts without one', async () => {+ const { bridge, terminal } = makeBridge(+ { ok: true, ptyId: 'pty-1' },+ WIRED,+ undefined,+ 'win32',+ );+ render(<TerminalPanel bridge={bridge} />);+ await waitFor(() => expect(lastTerm?.keyHandler).toBeTruthy());+ const handler = lastTerm?.keyHandler;++ if (lastTerm) lastTerm.selection = 'selected output';+ const copyPreventDefault = vi.fn(() => {});+ expect(+ handler?.({+ type: 'keydown',+ key: 'c',+ ctrlKey: true,+ shiftKey: false,+ altKey: false,+ metaKey: false,+ preventDefault: copyPreventDefault,+ } as unknown as KeyboardEvent),+ ).toBe(false);+ expect(copyPreventDefault).toHaveBeenCalledTimes(1);+ await waitFor(() =>+ expect(navigator.clipboard.writeText).toHaveBeenCalledWith('selected output'),+ );++ vi.mocked(navigator.clipboard.writeText).mockClear();+ expect(lastTerm?.clearSelection).toHaveBeenCalledTimes(1);+ const interruptPreventDefault = vi.fn(() => {});+ expect(+ handler?.({+ type: 'keydown',+ key: 'c',+ ctrlKey: true,+ shiftKey: false,+ altKey: false,+ metaKey: false,+ preventDefault: interruptPreventDefault,+ } as unknown as KeyboardEvent),+ ).toBe(true);+ expect(interruptPreventDefault).toHaveBeenCalledTimes(1);+ expect(navigator.clipboard.writeText).not.toHaveBeenCalled();+ act(() => lastTerm?.onDataCb?.('\x03'));+ expect(terminal.input).toHaveBeenLastCalledWith('pty-1', '\x03');+ });++ test('Windows Ctrl+Shift+C copies and both Ctrl+V chords paste', async () => {+ const { bridge, terminal } = makeBridge(+ { ok: true, ptyId: 'pty-1' },+ WIRED,+ undefined,+ 'win32',+ );+ render(<TerminalPanel bridge={bridge} />);+ await waitFor(() => expect(lastTerm?.keyHandler).toBeTruthy());+ const handler = lastTerm?.keyHandler;+ if (lastTerm) lastTerm.selection = 'shift-selected';++ expect(+ handler?.({+ type: 'keydown',+ key: 'C',+ ctrlKey: true,+ shiftKey: true,+ altKey: false,+ metaKey: false,+ preventDefault: vi.fn(() => {}),+ } as unknown as KeyboardEvent),+ ).toBe(false);+ await waitFor(() =>+ expect(navigator.clipboard.writeText).toHaveBeenCalledWith('shift-selected'),+ );++ for (const shiftKey of [false, true]) {+ const preventDefault = vi.fn(() => {});+ expect(+ handler?.({+ type: 'keydown',+ key: 'V',+ ctrlKey: true,+ shiftKey,+ altKey: false,+ metaKey: false,+ preventDefault,+ } as unknown as KeyboardEvent),+ ).toBe(false);+ expect(preventDefault).toHaveBeenCalledTimes(1);+ }+ await waitFor(() => expect(lastTerm?.paste).toHaveBeenCalledTimes(2));+ expect(lastTerm?.paste).toHaveBeenNthCalledWith(1, 'clipboard paste');+ expect(lastTerm?.paste).toHaveBeenNthCalledWith(2, 'clipboard paste');+ expect(terminal.input).not.toHaveBeenCalledWith('pty-1', 'clipboard paste');+ });+test('Linux paste ignores clipboard text that resolves after the terminal unmounts', async () => {let resolveClipboard: ((text: string) => void) | null = null;Object.defineProperty(globalThis.navigator, 'clipboard', {@@ -1316,6 +1662,66 @@ describe('TerminalPanel', () => {for (const ro of ros) expect(ro.disconnect).toHaveBeenCalledTimes(1);});+ test('leaves a PTY for reload adoption only while a non-bfcache pagehide remains active', async () => {+ const removeWindowListener = vi.spyOn(window, 'removeEventListener');+ const removeDocumentListener = vi.spyOn(document, 'removeEventListener');+ const originalVisibilityState = Object.getOwnPropertyDescriptor(document, 'visibilityState');+ onTestFinished(() => {+ removeWindowListener.mockRestore();+ removeDocumentListener.mockRestore();+ if (originalVisibilityState === undefined) {+ Reflect.deleteProperty(document, 'visibilityState');+ } else {+ Object.defineProperty(document, 'visibilityState', originalVisibilityState);+ }+ });+ const first = makeBridge({ ok: true, ptyId: 'pty-reload' });+ const firstView = render(<TerminalPanel bridge={first.bridge} />);+ await waitFor(() => expect(first.terminal.create).toHaveBeenCalledTimes(1));++ act(() => {+ window.dispatchEvent(new PageTransitionEvent('pagehide', { persisted: false }));+ firstView.unmount();+ });+ expect(first.terminal.kill).not.toHaveBeenCalled();+ expect(removeWindowListener).toHaveBeenCalledWith('pagehide', expect.any(Function));+ expect(removeDocumentListener).toHaveBeenCalledWith('visibilitychange', expect.any(Function));++ const second = makeBridge({ ok: true, ptyId: 'pty-bfcache' });+ const secondView = render(<TerminalPanel bridge={second.bridge} />);+ await waitFor(() => expect(second.terminal.create).toHaveBeenCalledTimes(1));++ act(() => {+ window.dispatchEvent(new PageTransitionEvent('pagehide', { persisted: true }));+ secondView.unmount();+ });+ expect(second.terminal.kill).toHaveBeenCalledWith('pty-bfcache');++ const hidden = makeBridge({ ok: true, ptyId: 'pty-still-unloading' });+ const hiddenView = render(<TerminalPanel bridge={hidden.bridge} />);+ await waitFor(() => expect(hidden.terminal.create).toHaveBeenCalledTimes(1));++ act(() => {+ window.dispatchEvent(new PageTransitionEvent('pagehide', { persisted: false }));+ Object.defineProperty(document, 'visibilityState', { configurable: true, value: 'hidden' });+ document.dispatchEvent(new Event('visibilitychange'));+ hiddenView.unmount();+ });+ expect(hidden.terminal.kill).not.toHaveBeenCalled();++ const visible = makeBridge({ ok: true, ptyId: 'pty-restored' });+ const visibleView = render(<TerminalPanel bridge={visible.bridge} />);+ await waitFor(() => expect(visible.terminal.create).toHaveBeenCalledTimes(1));++ act(() => {+ window.dispatchEvent(new PageTransitionEvent('pagehide', { persisted: false }));+ Object.defineProperty(document, 'visibilityState', { configurable: true, value: 'visible' });+ document.dispatchEvent(new Event('visibilitychange'));+ visibleView.unmount();+ });+ expect(visible.terminal.kill).toHaveBeenCalledWith('pty-restored');+ });+test('degrades to the DOM renderer when WebGL is unavailable instead of failing the mount', async () => {webglThrows = true;const { bridge, terminal, pushData } = makeBridge({ ok: true, ptyId: 'pty-1' });@@ -1341,6 +1747,184 @@ describe('TerminalPanel', () => {expect(lastTerm?.write.mock.calls[0]?.[0]).toBe('mine');});+ test('shows a translated pane notice when an invalid shell override is skipped', async () => {+ const { bridge, terminal, pushNotice } = makeBridge(+ { ok: true, ptyId: 'pty-1' },+ WIRED,+ undefined,+ 'win32',+ );+ render(<TerminalPanel bridge={bridge} />);+ await waitFor(() => expect(terminal.onNotice).toHaveBeenCalledTimes(1));++ act(() =>+ pushNotice({ ptyId: 'pty-1', notice: 'invalid-shell-override', reason: 'not-found' }),+ );++ const banner = screen.getByTestId('terminal-shell-notice-banner');+ expect(banner.textContent).toMatch(/terminal\.shell executable.*was not found/i);+ fireEvent.click(screen.getByRole('button', { name: 'Dismiss' }));+ expect(screen.queryByTestId('terminal-shell-notice-banner')).toBeNull();+ });++ test('explains the capability boundary for an unsupported Windows shell override', async () => {+ const { bridge, terminal, pushNotice } = makeBridge(+ { ok: true, ptyId: 'pty-1' },+ WIRED,+ undefined,+ 'win32',+ );+ render(<TerminalPanel bridge={bridge} />);+ await waitFor(() => expect(terminal.onNotice).toHaveBeenCalledTimes(1));++ act(() =>+ pushNotice({+ ptyId: 'pty-1',+ notice: 'invalid-shell-override',+ reason: 'unsupported-family',+ }),+ );++ expect(screen.getByTestId('terminal-shell-notice-banner').textContent).toMatch(+ /\.ok\/local\/config\.yml.*PowerShell.*cmd\.exe.*Git Bash.*plain terminal only.*agent and command launches do not run/i,+ );+ });++ test('does not lose a shell notice delivered before create resolves', async () => {+ const h = makeBridge({ ok: true, ptyId: 'pty-1' }, WIRED, undefined, 'win32');+ h.terminal.create.mockImplementationOnce(async () => {+ h.pushNotice({+ ptyId: 'pty-1',+ notice: 'invalid-shell-override',+ reason: 'not-found',+ });+ return { ok: true as const, ptyId: 'pty-1' };+ });++ render(<TerminalPanel bridge={h.bridge} />);++ expect((await screen.findByTestId('terminal-shell-notice-banner')).textContent).toMatch(+ /terminal\.shell executable.*was not found/i,+ );+ });++ test.each([+ ['containment-refused', /not safely contained.*not a link.*approve OpenKnowledge/i],+ ['write-failed', /\.ok\/local\/terminal.*folder is writable.*approve OpenKnowledge/i],+ ] as const)('shows the support-file degradation notice for %s', async (reason, copy) => {+ const { bridge, terminal, pushNotice } = makeBridge(+ { ok: true, ptyId: 'pty-1' },+ WIRED,+ undefined,+ 'win32',+ );+ render(<TerminalPanel bridge={bridge} />);+ await waitFor(() => expect(terminal.onNotice).toHaveBeenCalledTimes(1));++ act(() => pushNotice({ ptyId: 'pty-1', notice: 'support-file-degraded', reason }));++ const banner = screen.getByTestId('terminal-support-file-notice-banner');+ expect(banner.textContent).toMatch(copy);+ });++ test('shows one operational notice at a time and reveals the next after dismissal', async () => {+ const { bridge, terminal, pushNotice } = makeBridge(+ { ok: true, ptyId: 'pty-1' },+ WIRED,+ undefined,+ 'win32',+ );+ render(<TerminalPanel bridge={bridge} />);+ await waitFor(() => expect(terminal.onNotice).toHaveBeenCalledTimes(1));++ act(() => {+ pushNotice({ ptyId: 'pty-1', notice: 'invalid-shell-override', reason: 'not-found' });+ pushNotice({ ptyId: 'pty-1', notice: 'support-file-degraded', reason: 'write-failed' });+ });++ expect(screen.getByTestId('terminal-support-file-notice-banner')).toBeTruthy();+ expect(screen.queryByTestId('terminal-shell-notice-banner')).toBeNull();+ fireEvent.click(screen.getByRole('button', { name: 'Dismiss' }));+ expect(screen.getByTestId('terminal-shell-notice-banner')).toBeTruthy();+ });++ test('a new launch clears shell and dropped-path notices from the previous session', async () => {+ const { bridge, terminal, pushNotice } = makeBridge(+ { ok: true, ptyId: 'pty-1' },+ WIRED,+ undefined,+ 'win32',+ );+ (bridge as unknown as { getPathForFile: (file: File) => string }).getPathForFile = () =>+ 'C:\\Users\\%USERNAME%\\unsafe.png';+ const { rerender } = render(+ <TerminalPanel bridge={bridge} launch={{ prompt: null, cli: 'claude', nonce: 1 }} />,+ );+ await waitFor(() => expect(terminal.onNotice).toHaveBeenCalledTimes(1));++ act(() => {+ pushNotice({ ptyId: 'pty-1', notice: 'shell-resolved', shellFamily: 'cmd' });+ pushNotice({ ptyId: 'pty-1', notice: 'invalid-shell-override', reason: 'not-found' });+ });+ const container = document.querySelector('[data-terminal-status]');+ if (container === null) throw new Error('terminal container not found');+ fireEvent.drop(container, {+ dataTransfer: {+ types: ['Files'],+ files: [new File(['x'], 'unsafe.png', { type: 'image/png' })],+ },+ });++ rerender(<TerminalPanel bridge={bridge} launch={{ prompt: null, cli: 'claude', nonce: 2 }} />);+ await waitFor(() => expect(terminal.create).toHaveBeenCalledTimes(2));+ expect(screen.queryByTestId('terminal-shell-notice-banner')).toBeNull();+ expect(screen.queryByTestId('terminal-path-drop-notice-banner')).toBeNull();+ });++ test('shows operational notices before the routine manual-submit notice', async () => {+ const { bridge, terminal, pushNotice } = makeBridge(+ { ok: true, ptyId: 'pty-1' },+ WIRED,+ undefined,+ 'win32',+ );+ (bridge as unknown as { getPathForFile: (file: File) => string }).getPathForFile = () =>+ 'C:\\Users\\%USERNAME%\\unsafe.png';+ render(+ <TerminalPanel+ bridge={bridge}+ launch={{ prompt: 'review this safely', cli: 'claude', nonce: 1 }}+ />,+ );+ await waitFor(() =>+ expect(document.querySelector('[data-terminal-status="running"]')).not.toBeNull(),+ );++ act(() => {+ pushNotice({ ptyId: 'pty-1', notice: 'shell-resolved', shellFamily: 'cmd' });+ pushNotice({ ptyId: 'pty-1', notice: 'invalid-shell-override', reason: 'not-found' });+ pushNotice({ ptyId: 'pty-1', notice: 'support-file-degraded', reason: 'write-failed' });+ });+ const container = document.querySelector('[data-terminal-status]');+ if (container === null) throw new Error('terminal container not found');+ fireEvent.drop(container, {+ dataTransfer: {+ types: ['Files'],+ files: [new File(['x'], 'unsafe.png', { type: 'image/png' })],+ },+ });++ await waitFor(() => expect(terminal.input).toHaveBeenCalled(), { timeout: 6_000 });+ expect(screen.getByTestId('terminal-path-drop-notice-banner')).toBeTruthy();+ expect(screen.queryByTestId('terminal-manual-submit-notice-banner')).toBeNull();+ fireEvent.click(screen.getByRole('button', { name: 'Dismiss' }));+ expect(screen.getByTestId('terminal-support-file-notice-banner')).toBeTruthy();+ fireEvent.click(screen.getByRole('button', { name: 'Dismiss' }));+ expect(screen.getByTestId('terminal-shell-notice-banner')).toBeTruthy();+ fireEvent.click(screen.getByRole('button', { name: 'Dismiss' }));+ expect(screen.getByTestId('terminal-manual-submit-notice-banner')).toBeTruthy();+ }, 10_000);+test('reports the no-project state and wires no data stream when the window has no project', async () => {const { bridge, terminal } = makeBridge({ ok: false, reason: 'no-project' });render(<TerminalPanel bridge={bridge} />);@@ -1403,6 +1987,7 @@ describe('TerminalPanel', () => {drain: vi.fn(() => {}),onData: vi.fn(() => vi.fn(() => {})),onExit: vi.fn(() => vi.fn(() => {})),+ onNotice: vi.fn(() => vi.fn(() => {})),};const bridge = { terminal, config: { e2eSmoke: false } } as unknown as OkDesktopBridge;@@ -1500,6 +2085,7 @@ describe('TerminalPanel', () => {drain: vi.fn(() => {}),onData: vi.fn(() => vi.fn(() => {})),onExit: vi.fn(() => vi.fn(() => {})),+ onNotice: vi.fn(() => vi.fn(() => {})),claudePreflight: vi.fn(async () => WIRED),cliPreflight: vi.fn(async () => ({ onPath: 'present' as const })),rewireClaudeMcp: vi.fn(async () => WIRED),@@ -1743,6 +2329,7 @@ describe('TerminalPanel', () => {exitSubs.push(cb);return vi.fn(() => {});}),+ onNotice: vi.fn(() => vi.fn(() => {})),claudePreflight: vi.fn(async () => WIRED),rewireClaudeMcp: vi.fn(async () => WIRED),};diff --git a/packages/app/src/components/TerminalPanel.launch.dom.test.tsx b/packages/app/src/components/TerminalPanel.launch.dom.test.tsxindex 51d3dc218..7af482f2b 100644--- a/packages/app/src/components/TerminalPanel.launch.dom.test.tsx+++ b/packages/app/src/components/TerminalPanel.launch.dom.test.tsx@@ -14,7 +14,11 @@* boundary, mirroring `TerminalPanel.dom.test.tsx`.*/-import { buildStartupInjectionBytes, type TerminalCli } from '@inkeep/open-knowledge-core';+import {+ buildStartupInjectionBytes,+ type TerminalCli,+ type TerminalLaunchCommand,+} from '@inkeep/open-knowledge-core';import { act, cleanup, render, screen, waitFor } from '@testing-library/react';import type { ReactElement } from 'react';import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';@@ -24,6 +28,7 @@ import type {CliReadiness,OkDesktopBridge,OkPtyData,+ OkPtyNotice,} from '@/lib/desktop-bridge-types';class MockFitAddon {@@ -33,6 +38,8 @@ class MockWebglAddon {}class MockWebLinksAddon {}class MockUnicode11Addon {}+let lastTerm: MockTerminal | null = null;+class MockTerminal {cols = 80;rows = 24;@@ -40,11 +47,16 @@ class MockTerminal {onDataCb: ((d: string) => void) | null = null;keyHandler: ((e: KeyboardEvent) => boolean) | null = null;options: Record<string, unknown>;- hasSelection = vi.fn(() => false);- getSelection = vi.fn(() => '');+ selection = '';+ hasSelection = vi.fn(() => this.selection.length > 0);+ getSelection = vi.fn(() => this.selection);+ clearSelection = vi.fn(() => {+ this.selection = '';+ });open = vi.fn(() => {});focus = vi.fn(() => {});dispose = vi.fn(() => {});+ paste = vi.fn((_data: string) => {});write = vi.fn((_data: string, cb?: () => void) => {cb?.();});@@ -71,6 +83,7 @@ class MockTerminal {}constructor(options: Record<string, unknown>) {this.options = options;+ lastTerm = this;}}@@ -109,11 +122,18 @@ function makeBridge(platform: OkDesktopBridge['platform'] = 'darwin',) {const dataSubs: Array<(m: OkPtyData) => void> = [];+ const noticeSubs: Array<(m: OkPtyNotice) => void> = [];const terminal = {- create: vi.fn(async (_opts: { cols: number; rows: number; launchCommand?: string }) => ({- ok: true as const,- ptyId: 'pty-1',- })),+ create: vi.fn(+ async (_opts: {+ cols: number;+ rows: number;+ launchCommand?: string | TerminalLaunchCommand;+ }) => ({+ ok: true as const,+ ptyId: 'pty-1',+ }),+ ),input: vi.fn((_id: string, _d: string) => {}),resize: vi.fn(() => {}),kill: vi.fn(async () => {}),@@ -129,6 +149,10 @@ function makeBridge(return vi.fn(() => {});}),onExit: vi.fn(() => vi.fn(() => {})),+ onNotice: vi.fn((cb: (m: OkPtyNotice) => void) => {+ noticeSubs.push(cb);+ return vi.fn(() => {});+ }),claudePreflight: vi.fn(async () => preflight),cliPreflight: vi.fn(async (_cli: TerminalCli) => cliReadiness),rewireClaudeMcp: vi.fn(async () => preflight),@@ -144,6 +168,9 @@ function makeBridge(pushData: (m: OkPtyData) => {for (const f of dataSubs) f(m);},+ pushNotice: (m: OkPtyNotice) => {+ for (const f of noticeSubs) f(m);+ },};}@@ -151,9 +178,11 @@ const { TerminalPanel, STAGE_PASTE_SETTLE_MS } = await import('./TerminalPanel')/** The `launchCommand` baked into the (single) `create` call, or undefined when* none was passed (plain shell). The launch's only sanctioned transport. */-function bakedLaunch(createMock: ReturnType<typeof vi.fn>): string | undefined {+function bakedLaunch(+ createMock: ReturnType<typeof vi.fn>,+): string | TerminalLaunchCommand | undefined {const calls = createMock.mock.calls;- const last = calls.at(-1)?.[0] as { launchCommand?: string } | undefined;+ const last = calls.at(-1)?.[0] as { launchCommand?: string | TerminalLaunchCommand } | undefined;return last?.launchCommand;}@@ -210,7 +239,15 @@ function renderWithAutoApproveOff(ui: ReactElement) {describe('TerminalPanel "Open in terminal" launch (baked into the PTY spawn)', () => {beforeEach(() => {+ lastTerm = null;(globalThis as { ResizeObserver: unknown }).ResizeObserver = MockResizeObserver;+ Object.defineProperty(globalThis.navigator, 'clipboard', {+ configurable: true,+ value: {+ readText: vi.fn(async () => 'launch clipboard paste'),+ writeText: vi.fn(async () => {}),+ },+ });});afterEach(() => {cleanup();@@ -234,6 +271,201 @@ describe('TerminalPanel "Open in terminal" launch (baked into the PTY spawn)', (expect(launchInputWrites(terminal.input)).toEqual([]);});+ test('Windows keeps the CLI structured and bracketed-pastes the prompt after readiness', async () => {+ const { bridge, terminal, pushData } = makeBridge(WIRED, ON_PATH, 'win32');+ const prompt = 'review {"quoted":"JSON"}; & calc';+ render(<TerminalPanel bridge={bridge} launch={{ prompt, cli: 'claude', nonce: 1 }} />);++ await waitFor(() => expect(terminal.create).toHaveBeenCalledTimes(1));+ const launch = bakedLaunch(terminal.create);+ expect(launch).toMatchObject({+ executable: 'claude',+ args: ['--settings', '.ok/local/terminal/claude-settings-mcp-tools.json'],+ supportFile: {+ kind: 'claude-settings',+ relativePath: '.ok/local/terminal/claude-settings-mcp-tools.json',+ },+ });+ if (typeof launch !== 'object' || launch === null || launch.supportFile === undefined) {+ throw new Error('expected a structured Claude launch with settings support file');+ }+ expect(JSON.parse(launch.supportFile.contents)).toEqual({+ 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',+ ],+ },+ });+ expect(JSON.stringify(bakedLaunch(terminal.create))).not.toContain(prompt);+ const submittedBytes = buildStartupInjectionBytes('claude', prompt, 'win32');+ expect(submittedBytes).not.toBeNull();+ const stagedBytes = submittedBytes?.slice(0, -1);+ await new Promise((resolve) => setTimeout(resolve, 80));+ expect(terminal.input).not.toHaveBeenCalled();+ pushData({ ptyId: 'pty-1', data: '\x1b[?2004h' });+ await waitFor(() => expect(terminal.input).toHaveBeenCalledWith('pty-1', stagedBytes), {+ timeout: 2_000,+ });+ expect(terminal.input).not.toHaveBeenCalledWith('pty-1', submittedBytes);+ const notice = await screen.findByTestId('terminal-manual-submit-notice-banner');+ expect(notice.textContent).toContain('not submitted automatically');+ expect(notice.textContent).toContain('Review it');+ });++ test('Windows cap fallback stages the prompt without submitting when readiness never arrives', async () => {+ const { bridge, terminal } = makeBridge(WIRED, ON_PATH, 'win32');+ const prompt = 'review this safely';+ render(<TerminalPanel bridge={bridge} launch={{ prompt, cli: 'claude', nonce: 1 }} />);++ await waitFor(() => expect(terminal.create).toHaveBeenCalledTimes(1));+ const submitted = buildStartupInjectionBytes('claude', prompt, 'win32');+ expect(submitted).not.toBeNull();+ const staged = submitted?.slice(0, -1);+ await waitFor(() => expect(terminal.input).toHaveBeenCalledWith('pty-1', staged), {+ timeout: 6_000,+ });+ expect(terminal.input).not.toHaveBeenCalledWith('pty-1', submitted);+ // Withholding Enter is invisible in the terminal, so the panel says so.+ const notice = await screen.findByTestId('terminal-manual-submit-notice-banner');+ expect(notice.textContent).toContain('not submitted automatically');+ expect(notice.textContent).toContain('press Enter');+ }, 10_000);++ test('Windows suppresses prompt injection when the configured shell cannot run the agent launch', async () => {+ const { bridge, terminal, pushData, pushNotice } = makeBridge(WIRED, ON_PATH, 'win32');+ terminal.create.mockImplementationOnce(async () => {+ pushNotice({+ ptyId: 'pty-1',+ notice: 'invalid-shell-override',+ reason: 'unsupported-family',+ });+ return { ok: true as const, ptyId: 'pty-1' };+ });+ render(+ <TerminalPanel+ bridge={bridge}+ launch={{ prompt: 'do not paste this into a plain shell', cli: 'claude', nonce: 1 }}+ />,+ );++ await waitFor(() => expect(terminal.create).toHaveBeenCalledTimes(1));+ expect(bakedLaunch(terminal.create)).toMatchObject({ executable: 'claude' });+ expect(await screen.findByTestId('terminal-shell-notice-banner')).toBeTruthy();+ act(() => pushData({ ptyId: 'pty-1', data: '\x1b[?2004h' }));+ await act(async () => {+ await new Promise((resolve) => setTimeout(resolve, STAGE_PASTE_SETTLE_MS * 3));+ });+ expect(terminal.input).not.toHaveBeenCalled();+ expect(screen.queryByTestId('terminal-manual-submit-notice-banner')).toBeNull();+ });++ test('Windows cancels an armed prompt injection when the unsupported-shell notice arrives after attach', async () => {+ const { bridge, terminal, pushData, pushNotice } = makeBridge(WIRED, ON_PATH, 'win32');+ render(+ <TerminalPanel+ bridge={bridge}+ launch={{ prompt: 'never execute this in the plain shell', cli: 'claude', nonce: 1 }}+ />,+ );++ await waitFor(() => expect(terminal.create).toHaveBeenCalledTimes(1));+ await waitFor(() =>+ expect(document.querySelector('[data-terminal-status="running"]')).not.toBeNull(),+ );+ act(() => pushData({ ptyId: 'pty-1', data: '\x1b[?2004h' }));+ act(() =>+ pushNotice({+ ptyId: 'pty-1',+ notice: 'invalid-shell-override',+ reason: 'unsupported-family',+ }),+ );+ await act(async () => {+ await new Promise((resolve) => setTimeout(resolve, STAGE_PASTE_SETTLE_MS * 3));+ });++ expect(await screen.findByTestId('terminal-shell-notice-banner')).toBeTruthy();+ expect(terminal.input).not.toHaveBeenCalled();+ expect(screen.queryByTestId('terminal-manual-submit-notice-banner')).toBeNull();+ });++ test('Windows carries Codex auto-approval as cmd-safe structured argv', async () => {+ const { bridge, terminal, pushData } = makeBridge(WIRED, CODEX_OK_CONFIGURED, 'win32');+ render(+ <TerminalPanel bridge={bridge} launch={{ prompt: 'review this', cli: 'codex', nonce: 1 }} />,+ );++ await waitFor(() => expect(terminal.create).toHaveBeenCalledTimes(1));+ expect(bakedLaunch(terminal.create)).toEqual({+ executable: 'codex',+ args: ['-c', 'mcp_servers.open-knowledge.default_tools_approval_mode=approve'],+ });+ pushData({ ptyId: 'pty-1', data: '\x1b[?2004h' });+ const submittedBytes = buildStartupInjectionBytes('codex', 'review this', 'win32');+ expect(submittedBytes).not.toBeNull();+ await waitFor(() =>+ expect(terminal.input).toHaveBeenCalledWith('pty-1', submittedBytes?.slice(0, -1)),+ );+ expect(terminal.input).not.toHaveBeenCalledWith('pty-1', submittedBytes);+ expect(await screen.findByTestId('terminal-manual-submit-notice-banner')).toBeTruthy();+ });++ test('Windows launch panels preserve selection-conditional Ctrl+C and Ctrl+V paste', async () => {+ const { bridge, terminal } = makeBridge(WIRED, ON_PATH, 'win32');+ render(<TerminalPanel bridge={bridge} launch={{ prompt: null, cli: 'claude', nonce: 1 }} />);+ await waitFor(() => expect(terminal.create).toHaveBeenCalledTimes(1));+ const handler = lastTerm?.keyHandler;+ expect(handler).toBeTruthy();++ expect(+ handler?.({+ type: 'keydown',+ key: 'c',+ ctrlKey: true,+ shiftKey: false,+ altKey: false,+ metaKey: false,+ preventDefault: vi.fn(() => {}),+ } as unknown as KeyboardEvent),+ ).toBe(true);+ expect(navigator.clipboard.writeText).not.toHaveBeenCalled();++ if (lastTerm) lastTerm.selection = 'launch selection';+ expect(+ handler?.({+ type: 'keydown',+ key: 'c',+ ctrlKey: true,+ shiftKey: false,+ altKey: false,+ metaKey: false,+ preventDefault: vi.fn(() => {}),+ } as unknown as KeyboardEvent),+ ).toBe(false);+ await waitFor(() =>+ expect(navigator.clipboard.writeText).toHaveBeenCalledWith('launch selection'),+ );++ expect(+ handler?.({+ type: 'keydown',+ key: 'v',+ ctrlKey: true,+ shiftKey: false,+ altKey: false,+ metaKey: false,+ preventDefault: vi.fn(() => {}),+ } as unknown as KeyboardEvent),+ ).toBe(false);+ await waitFor(() => expect(lastTerm?.paste).toHaveBeenCalledWith('launch clipboard paste'));+ });+test('a launch carrying stagePaste writes it into the CLI input after the TUI settles — no submit', async () => {const { bridge, terminal } = makeBridge(WIRED);const staged = 'work on @notes.md — the selected passage\n\n';@@ -278,7 +510,7 @@ describe('TerminalPanel "Open in terminal" launch (baked into the PTY spawn)', (// Now the composed prompt lands via `input`, wrapped in bracketed paste// (multi-line-safe) and followed by the submit byte. Derived from core so the// escape framing can't rot into a hand-copied literal.- const expectedBytes = buildStartupInjectionBytes('hermes', prompt);+ const expectedBytes = buildStartupInjectionBytes('hermes', prompt, 'darwin');expect(expectedBytes).not.toBeNull();await waitFor(() => expect(terminal.input).toHaveBeenCalledWith('pty-1', expectedBytes), {timeout: 2_000,@@ -298,7 +530,7 @@ describe('TerminalPanel "Open in terminal" launch (baked into the PTY spawn)', (// No marker is ever pushed. The prompt must still be delivered (the cap// fallback), so a future Hermes that changed its ready signal never silently// drops it.- const expectedBytes = buildStartupInjectionBytes('hermes', prompt);+ const expectedBytes = buildStartupInjectionBytes('hermes', prompt, 'darwin');await waitFor(() => expect(terminal.input).toHaveBeenCalledWith('pty-1', expectedBytes), {timeout: 6_000,});diff --git a/packages/app/src/components/TerminalPanel.tsx b/packages/app/src/components/TerminalPanel.tsxindex 14d48a755..1a4be851c 100644--- a/packages/app/src/components/TerminalPanel.tsx+++ b/packages/app/src/components/TerminalPanel.tsx@@ -3,9 +3,13 @@ import '@xterm/xterm/css/xterm.css';import {buildCliLaunchArgString,buildStartupInjectionBytes,+ buildWindowsCliLaunch,+ quoteWindowsShellPath,shellSingleQuote,startupInjectionFor,type TerminalCli,+ type TerminalLaunchCommand,+ type WindowsShellFamily,} from '@inkeep/open-knowledge-core';import { useLingui } from '@lingui/react/macro';import { FitAddon } from '@xterm/addon-fit';@@ -16,17 +20,22 @@ import { Terminal } from '@xterm/xterm';import { useTheme } from 'next-themes';import { use, useEffect, useRef, useState } from 'react';import { ConfigContext } from '@/lib/config-context';-import type { ClaudeReadiness, OkDesktopBridge } from '@/lib/desktop-bridge-types';+import type { ClaudeReadiness, OkDesktopBridge, OkPtyNotice } from '@/lib/desktop-bridge-types';import { cn } from '@/lib/utils';import { getPageListCache } from '../editor/page-list-cache';import { filePathToDocName, hashFromDocName, hashFromFolderPath } from '../lib/doc-hash';import { ClaudeReadinessBanner } from './ClaudeReadinessBanner';import type { TerminalLaunchIntent } from './EditorPane';import { filesFromExternalDrop, isExternalFileDrag } from './file-tree-adapter';-import { type TerminalCommandId, terminalCommandFor } from './handoff/terminal-command-events';+import {+ type TerminalCommandId,+ terminalCommandFor,+ windowsTerminalCommandFor,+} from './handoff/terminal-command-events';import { TerminalCliMissingBanner } from './TerminalCliMissingBanner';import { TerminalCliUnverifiedBanner } from './TerminalCliUnverifiedBanner';import { type TerminalExitInfo, TerminalExitNotice } from './TerminalExitNotice';+import { TerminalNoticeBanner } from './TerminalNoticeBanner';import { TerminalRefusalNotice } from './TerminalRefusalNotice';import { TerminalStartingNotice } from './TerminalStartingNotice';import { createTerminalFileLinkProvider } from './terminal-link-provider';@@ -204,6 +213,7 @@ function TerminalSession({adoptPtyId = null,onPtyId,}: TerminalSessionProps) {+ const { t } = useLingui();const containerRef = useRef<HTMLDivElement | null>(null);const onExitRef = useRef(onExit);const onTitleChangeRef = useRef(onTitleChange);@@ -218,16 +228,34 @@ function TerminalSession({// theme changes flow through the dedicated effect below.const initialXtermThemeRef = useRef(xtermTheme);const [status, setStatus] = useState<SessionStatus>('starting');- // Whether any shell byte has landed yet. `status` cannot answer this: it flips- // to 'running' the instant a ptyId comes back, which is BEFORE the utility- // process forks a PTY host and the login shell sources its rc chain — the- // seconds a user actually waits. Without this the pane looks identical whether- // a shell is coming or nothing happened at all.+ // Whether any shell byte has landed yet. `status` cannot answer this: on a+ // fresh create it flips to 'running' the instant a ptyId comes back, which is+ // BEFORE the utility process forks a PTY host and the login shell sources its+ // rc chain — the seconds a user actually waits. Without this the pane looks+ // identical whether a shell is coming or nothing happened at all.const [hasOutput, setHasOutput] = useState(false);const [readiness, setReadiness] = useState<ClaudeReadiness | null>(null);const [exitInfo, setExitInfo] = useState<TerminalExitInfo | null>(null);+ const [shellNotice, setShellNotice] = useState<Extract<+ OkPtyNotice,+ { notice: 'invalid-shell-override' }+ > | null>(null);+ const [supportFileNotice, setSupportFileNotice] = useState<Extract<+ OkPtyNotice,+ { notice: 'support-file-degraded' }+ > | null>(null);+ const [pathDropNotice, setPathDropNotice] = useState(false);+ // Windows startup injection always stages the prompt WITHOUT its submit key,+ // so the user can review it before deciding to run it. Scoped to one launch+ // and dismissible.+ const [manualSubmitNotice, setManualSubmitNotice] = useState(false);// Live PTY id, mirrored out of the mount effect for the keyboard handlers.const ptyIdRef = useRef<string | null>(null);+ // These refs are shared with the external-drop effect below. Keeping the gate+ // and its single input chokepoint outside the session effect prevents that+ // listener from capturing stale session state across a replay or restart.+ const terminalInputEnabledRef = useRef(false);+ const terminalInputRef = useRef<(data: string) => void>(() => undefined);// Set when a launch suppressed its bake off a non-`present` verdict — drives// the per-CLI banner strip. `not-found` is the VERIFIED absence (the probe// ran and the binary is genuinely off the PATH); `unverified` covers a@@ -249,6 +277,7 @@ function TerminalSession({// effect (which would respawn the PTY) — the launch reads it once.const configCtx = use(ConfigContext);const autoApproveOkToolsRef = useRef(configCtx?.userConfig?.agents?.autoApproveOkTools ?? true);+ const shellFamilyRef = useRef<WindowsShellFamily | null>(null);// Keep the callbacks fresh without re-running the mount effect — a new// callback identity must NOT tear down and respawn the PTY.@@ -263,10 +292,23 @@ function TerminalSession({const container = containerRef.current;if (!container) return;+ // This effect run IS the session: a new launch re-runs it, so per-launch+ // notice state resets here rather than surviving into a session it does not+ // describe.+ setManualSubmitNotice(false);+ setSupportFileNotice(null);+ setShellNotice(null);+ setPathDropNotice(false);+ terminalInputEnabledRef.current = false;+let cancelled = false;+ let sessionEnded = false;let ptyId: string | null = null;let unsubData: (() => void) | undefined;let unsubExit: (() => void) | undefined;+ let unsubNotice: (() => void) | undefined;+ let pendingShellNotices: OkPtyNotice[] = [];+ let launchCapabilityLimited = false;// Startup-injection readiness: for a `startupInjection` CLI (Hermes), this// scans the PTY output for the CLI's ready marker so the prompt is pasted the// instant the input widget is live. Fed from attachSession's onData; armed by@@ -279,6 +321,45 @@ function TerminalSession({let observer: ResizeObserver | undefined;let canvasPixelObserver: ResizeObserver | undefined;let ptyResizeThrottle: ReturnType<typeof createResizeThrottle> | undefined;+ let documentUnloading = false;+ const markDocumentUnloading = (event: PageTransitionEvent): void => {+ // A bfcache hide preserves this renderer and must not suppress a later+ // explicit tab-close reap. A real navigation/reload tears the document+ // down after this event, while main keeps the window-scoped PTY available+ // for the next renderer to list and adopt.+ documentUnloading = !event.persisted;+ };+ const markDocumentVisible = (): void => {+ // Re-arms the ordinary tab-close reap for the case `pagehide` cannot+ // settle: a non-persisted hide on a document that then survives. A real+ // bfcache hide reports `persisted: true` above and never sets the flag.+ if (document.visibilityState === 'visible') documentUnloading = false;+ };+ window.addEventListener('pagehide', markDocumentUnloading);+ document.addEventListener('visibilitychange', markDocumentVisible);++ const applyShellNotice = (notice: OkPtyNotice): void => {+ if (notice.notice === 'shell-resolved') {+ shellFamilyRef.current = notice.shellFamily;+ } else if (notice.notice === 'invalid-shell-override') {+ if (notice.reason === 'unsupported-family') launchCapabilityLimited = true;+ setShellNotice(notice);+ } else {+ setSupportFileNotice(notice);+ }+ };++ // Subscribe before create() so a fast utility response cannot outrun the+ // renderer's listener. Until this panel knows its ptyId, retain every notice+ // and address-check each one when attachSession wires the created shell.+ unsubNotice = bridge.terminal.onNotice((msg) => {+ if (ptyId === null) {+ pendingShellNotices.push(msg);+ return;+ }+ if (msg.ptyId !== ptyId) return;+ applyShellNotice(msg);+ });// xterm's screen-reader mode mirrors the viewport into a live a11y DOM on// every write and scroll — "a significant performance drop" per xterm's own@@ -510,11 +591,29 @@ function TerminalSession({if (!cancelled) onTitleChangeRef.current?.(title);});+ // Every renderer-to-PTY input path shares this gate. An adopted session is+ // wired before its replay is parsed so live output queues behind the replay,+ // but neither parser replies nor user gestures may reach the surviving shell+ // until that parse finishes. Exit closes the gate permanently for this run.+ const sendInput = (data: string): void => {+ const livePtyId = ptyIdRef.current;+ if (cancelled || !terminalInputEnabledRef.current || livePtyId === null) return;+ bridge.terminal.input(livePtyId, data);+ };+ terminalInputRef.current = sendInput;+ const markInteractive = (): void => {+ if (cancelled || sessionEnded || terminalInputEnabledRef.current) return;+ terminalInputEnabledRef.current = true;+ setStatus('running');+ term.focus();+ };+// Every key (including Escape) goes to the PTY so terminal apps (vim, the// `claude` TUI) work — the keyboard exit is ⌘J. Linux owns the conventional- // Ctrl+Shift+C/V clipboard chords; plain Ctrl+C/V still run through xterm- // after cancelling Electron's hidden Edit-menu accelerator. The remaining- // two Shift-chord patches are shared across platforms:+ // Ctrl+Shift+C/V clipboard chords; Windows additionally makes Ctrl+C copy+ // only when xterm has a selection and treats both Ctrl+V chords as paste.+ // A selection-free Ctrl+C still runs through xterm as an interrupt. The+ // remaining two Shift-chord patches are shared across platforms://// - Shift+Tab: xterm emits the reverse-tab sequence (ESC [ Z) but, unlike// plain Tab, does NOT call preventDefault, so the browser's@@ -529,28 +628,32 @@ function TerminalSession({if (event.type !== 'keydown') return true;const key = event.key.toLowerCase();- const linuxClipboardKey =- bridge.platform === 'linux' &&+ const platformClipboardKey =+ (bridge.platform === 'linux' || bridge.platform === 'win32') &&event.ctrlKey &&!event.altKey &&!event.metaKey &&(key === 'c' || key === 'v');- if (linuxClipboardKey) {+ if (platformClipboardKey) {// Prevent Electron's hidden native Edit menu from consuming Ctrl+C/V.- // Returning true for the plain chords still tells xterm to encode them- // for the PTY (SIGINT / literal-next); shifted chords are handled here.+ // Returning true still tells xterm to encode the key for the PTY.event.preventDefault();- if (!event.shiftKey) return true;if (key === 'c') {- if (term.hasSelection() && navigator.clipboard?.writeText) {+ const hasSelection = term.hasSelection();+ const copiesSelection = event.shiftKey || (bridge.platform === 'win32' && hasSelection);+ if (!copiesSelection) return true;+ if (hasSelection && navigator.clipboard?.writeText) {void navigator.clipboard.writeText(term.getSelection()).catch((err) => console.warn('[terminal] clipboard copy failed', err));}+ if (bridge.platform === 'win32') term.clearSelection();return false;}+ if (!event.shiftKey && bridge.platform !== 'win32') return true;+ if (!terminalInputEnabledRef.current) return false;if (navigator.clipboard?.readText) {void navigator.clipboard.readText()@@ -570,11 +673,12 @@ function TerminalSession({}if (event.key === 'Enter') {const ptyId = ptyIdRef.current;- // Before the PTY is live there is nothing to write to; let xterm- // handle the key with its default behavior.+ // Before a PTY exists, let xterm handle the key normally. Once a PTY id+ // exists, suppress xterm's CR and route the LF through the interaction+ // gate so replay cannot leak it into a surviving shell.if (ptyId === null) return true;event.preventDefault();- bridge.terminal.input(ptyId, '\n');+ sendInput('\n');return false;}return true;@@ -616,8 +720,7 @@ function TerminalSession({wheelRowAccumulator = 0; // reset between gestures/apps; defer to xtermreturn true;}- const ptyId = ptyIdRef.current;- if (ptyId === null || event.deltaY === 0) return true;+ if (!terminalInputEnabledRef.current || event.deltaY === 0) return true;const measuredCellHeight = core?._renderService?.dimensions?.css?.cell?.height;if (measuredCellHeight === undefined && !warnedMissingCellHeight) {warnedMissingCellHeight = true;@@ -655,18 +758,16 @@ function TerminalSession({pixels: encoding === 'SGR_PIXELS',},);- bridge.terminal.input(ptyId, sgrWheelReport(button, position).repeat(count));+ sendInput(sgrWheelReport(button, position).repeat(count));}return false;});// First byte from the shell: drop the pending notice. Idempotent — the data// subscription fires per chunk, and an adopted session replays its retained- // screen through here too. The guard is a plain effect-scoped `let` because- // nothing outside this effect reads it; a ref would work identically (every- // new session is a fresh TerminalSession instance, so a ref could not carry- // state across sessions either), it just puts an instance-lifetime cell- // where an effect-lifetime one is what the code means.+ // screen through here too. Unlike the cross-effect input gate above,+ // nothing outside this effect reads this state, so its lifetime is the+ // session effect rather than the component instance.let sawFirstOutput = false;const markFirstOutput = () => {if (sawFirstOutput) return;@@ -675,21 +776,26 @@ function TerminalSession({};// Wire a now-live ptyId (freshly created OR adopted from a survivor) into- // this session: route xterm I/O, exit, and resize through it, and focus it.+ // this session: route xterm I/O, exit, and resize through it. The acquisition+ // branch marks it interactive only when input can safely reach the shell.// The wiring is identical for both acquisition paths — only how the id is// obtained differs — so both branches below call this.// A const arrow (not a hoisted `function`) so it observes the non-null// `container` narrowed by the early return above.- const attachSession = (livePtyId: string) => {+ const attachSession = (livePtyId: string): void => {ptyId = livePtyId;ptyIdRef.current = livePtyId;// Report the live id up so the host can reuse this session for a later// "Ask AI" launch (write into this PTY) instead of opening a new tab.onPtyIdRef.current?.(livePtyId);- setStatus('running');+ for (const notice of pendingShellNotices) {+ if (notice.ptyId !== livePtyId) continue;+ applyShellNotice(notice);+ }+ pendingShellNotices = [];term.onData((data) => {- if (ptyId) bridge.terminal.input(ptyId, data);+ sendInput(data);});unsubData = bridge.terminal.onData((msg) => {@@ -704,6 +810,8 @@ function TerminalSession({unsubExit = bridge.terminal.onExit((msg) => {if (msg.ptyId !== ptyId) return;+ sessionEnded = true;+ terminalInputEnabledRef.current = false;setExitInfo({ exitCode: msg.exitCode, signal: msg.signal, error: msg.error });setStatus('exited');onExitRef.current?.({ exitCode: msg.exitCode, signal: msg.signal });@@ -749,20 +857,17 @@ function TerminalSession({});observer.observe(container);- term.focus();-// No readiness probe here: attachSession runs for every session, including// plain and adopted tabs. Readiness feedback is scoped to a fresh,// product-initiated Claude launch, so only `resolveLaunchCommand` produces// the verdict while resolving that launch.};- // "Open in <Agent>" launch: resolve the command we BAKE into the shell spawn- // BEFORE create, so the agent rides on `$SHELL -l -i -c '<cmd>; exec …'` rather- // than being typed into the live shell. A `-c` command never reaches the line- // editor, so it is never written to the user's persistent history (the launch- // clutter + doc-content-on-disk leak this fixes); the spawn's `exec` tail hands- // the tab back to a fresh interactive shell after the agent exits.+ // "Open in <Agent>" launch: resolve the payload BEFORE create so the host+ // bakes it into shell startup rather than typing it through the live line+ // editor. POSIX carries its existing composed string; Windows carries+ // structured argv and injects user prompt text only after the TUI starts.+ // Both paths bypass persistent shell history and remain interactive on exit.//// The bake is gated on a CLI confirmed present on PATH — exactly today's// guarantee that the terminal never shows a raw `command not found`. Any@@ -778,7 +883,11 @@ function TerminalSession({// gets, since it runs immediately before the spawn.const resolveLaunchCommand = async (intent: TerminalLaunchIntent,- ): Promise<string | undefined> => {+ ): Promise<string | TerminalLaunchCommand | undefined> => {+ const buildLaunch = (opts: Parameters<typeof buildCliLaunchArgString>[2]) =>+ bridge.platform === 'win32'+ ? buildWindowsCliLaunch(intent.cli, intent.prompt, opts)+ : buildCliLaunchArgString(intent.cli, intent.prompt, opts);if (intent.cli === 'claude') {try {const fresh = await bridge.terminal.claudePreflight();@@ -787,7 +896,7 @@ function TerminalSession({// rewire banner when OK tools need rewiring, and stays silent when// fully wired.if (!cancelled) setReadiness(fresh);- return buildCliLaunchArgString('claude', intent.prompt, {+ return buildLaunch({mcpPreApprove: fresh.mcpPreApprovable === true,// Auto-approve OK's tools only when the project's `.mcp.json` entry is// verified OK's own (same gate as server-trust): auto-approving an@@ -831,7 +940,7 @@ function TerminalSession({// PATH (this branch), AND OK's server already configured in codex —// else the `-c` override would break codex's config load. Other CLIs// (cursor/opencode/pi) never receive it.- return buildCliLaunchArgString(intent.cli, intent.prompt, {+ return buildLaunch({autoApproveOkTools:intent.cli === 'codex' &&res.okServerConfigured === true &&@@ -876,18 +985,40 @@ function TerminalSession({// kill it the way a cancelled create reaps the orphan it just made.if (cancelled) return;if (adopted.ok) {- // Repaint the pre-reload screen + scrollback the main process retained- // for this PTY BEFORE wiring live delivery — without it the adopted tab- // comes back blank (the shell reconnects but its- // screen is gone). Written synchronously here, ahead of attachSession's- // onData subscription, so no live byte can interleave before the replay.- if (adopted.replay) {- markFirstOutput();- term.write(adopted.replay);+ shellFamilyRef.current = adopted.shellFamily ?? null;+ if (adopted.shellNoticeReason !== undefined) {+ applyShellNotice({+ ptyId: adoptPtyId,+ notice: 'invalid-shell-override',+ reason: adopted.shellNoticeReason,+ });}+ // Subscribe to live output before replay so bytes emitted during the+ // restore queue behind it in xterm. Input forwarding stays gated until+ // xterm finishes parsing the replay: retained terminal queries can make+ // xterm emit replies that belong to screen reconstruction, and sending+ // those replies into the live shell corrupts its line editor. This also+ // suppresses replies to queries first emitted while the renderer was+ // absent, which nothing else will answer. Separating those replies+ // would require preserving the undelivered outbound-suffix boundary+ // that adoptSession (main's terminal-manager) currently drops when+ // returning one replay string.+ const replay = adopted.replay;+ const hasReplay = replay !== '';+ // Keep the panel in its non-interactive starting state while replay+ // owns xterm's parser. The input gate cannot distinguish a protocol+ // reply from a real keystroke, so advertising `running` here would let+ // user input race the gate and be dropped mid-command.attachSession(adoptPtyId);+ if (hasReplay) {+ markFirstOutput();+ term.write(replay, markInteractive);+ } else {+ markInteractive();+ }// Nudge the surviving shell to repaint at the current viewport so a- // full-screen TUI (claude, vim) redraws its screen after the reload.+ // full-screen TUI redraws its screen after the reload. Output from the+ // resize queues behind replay in xterm's FIFO write buffer.bridge.terminal.resize(adoptPtyId, term.cols, term.rows);return;}@@ -898,7 +1029,7 @@ function TerminalSession({// Only for a freshly-spawned launch tab: a failed adopt (adoptPtyId set but// the survivor is gone) must NOT re-issue the original launch — matching the// prior behavior where a re-mounted launch session never replayed its intent.- let launchCommand: string | undefined;+ let launchCommand: string | TerminalLaunchCommand | undefined;if (launch !== null && adoptPtyId === null) {launchCommand = await resolveLaunchCommand(launch);if (cancelled) return;@@ -908,7 +1039,10 @@ function TerminalSession({// the login shell the spawn already uses is what makes a global npm// install resolvable from a GUI-launched app. Same adopt guard as// above, so a failed adopt never silently re-runs the command.- launchCommand = terminalCommandFor(commandId);+ launchCommand =+ bridge.platform === 'win32'+ ? windowsTerminalCommandFor(commandId)+ : terminalCommandFor(commandId);}let result: Awaited<ReturnType<typeof bridge.terminal.create>>;@@ -952,48 +1086,45 @@ function TerminalSession({}attachSession(result.ptyId);+ markInteractive();// Stage the ⌘J/⇧⌘J selection into the freshly-launched CLI's input — once,- // and NOT submitted. Gated on the bake actually happening: when the- // preflight suppressed `launchCommand`, this PTY is a BARE shell where- // every staged `\n` would EXECUTE as a command — the exact mangling the- // staging design exists to avoid — so the passage is dropped and the- // missing-CLI / readiness banner explains why nothing arrived. The short- // beat lets the TUI's stdin reader attach (a write at raw PTY-live can- // race it); unmount cancels the timer.+ // and NOT submitted. A suppressed launch or capability-limited Windows+ // shell is a BARE shell where every staged `\n` would EXECUTE as a command,+ // so the passage is dropped. The short beat lets the TUI's stdin reader+ // attach (a write at raw PTY-live can race it); unmount cancels the timer.const staged = launch?.stagePaste;- // Hermes-class CLIs take no starting-prompt argument, so their `chat` TUI is- // launched promptless (`launchCommand` = `hermes chat`) and the composed- // prompt is delivered HERE as a bracketed-paste PTY write once the TUI's- // stdin reader has attached — the same `bridge.terminal.input` channel as- // stagePaste, but framed (multi-line-safe) and submitted. Non-null only for- // a `startupInjection` CLI with a non-empty prompt AND a confirmed bake- // (preflight put the CLI on PATH); a suppressed launchCommand means a bare- // shell, where injecting would mangle, so it stays null. `settleMs` is the- // known-fragile knob — if it proves unreliable the fallback is clipboard +- // a paste hint, not a longer guess.+ // Hermes on POSIX and every Windows CLI launch promptless, then receive the+ // composed prompt HERE as a bracketed-paste PTY write once the TUI's stdin+ // reader has attached. inject() owns the capability gate because the host's+ // notice can arrive after create resolves but before the settle timer fires.const injectionBytes =launch != null && launchCommand !== undefined && launch.prompt != null- ? buildStartupInjectionBytes(launch.cli, launch.prompt)+ ? buildStartupInjectionBytes(launch.cli, launch.prompt, bridge.platform): null;if (injectionBytes != null && launch != null) {- const cfg = startupInjectionFor(launch.cli);+ const cfg = startupInjectionFor(launch.cli, bridge.platform);const settleMs = cfg?.settleMs ?? STAGE_PASTE_SETTLE_MS;const marker = cfg?.readyMarker;const bytes = injectionBytes;+ const stagedBytes =+ bridge.platform === 'win32' && cfg != null && bytes.endsWith(cfg.submit)+ ? bytes.slice(0, -cfg.submit.length)+ : bytes;let fired = false;- const inject = () => {+ const inject = (): void => {if (fired) return;fired = true;readinessScan = undefined;if (stagePasteTimer !== undefined) clearTimeout(stagePasteTimer);if (injectCapTimer !== undefined) clearTimeout(injectCapTimer);- if (cancelled || ptyIdRef.current === null) return;- bridge.terminal.input(ptyIdRef.current, bytes);+ if (cancelled || !terminalInputEnabledRef.current || launchCapabilityLimited) return;+ const isWindowsStagedPaste = bridge.platform === 'win32';+ const payload = isWindowsStagedPaste ? stagedBytes : bytes;+ sendInput(payload);term.focus();+ if (isWindowsStagedPaste) setManualSubmitNotice(true);};- // Cap fallback: inject even if the marker never appears, so a future TUI- // that changed its ready signal never silently drops the prompt.injectCapTimer = setTimeout(inject, cfg?.capMs ?? settleMs);if (marker != null) {// Inject once the input widget signals ready (Hermes: bracketed-paste@@ -1029,8 +1160,8 @@ function TerminalSession({);} else if (launchCommand !== undefined && staged != null && staged !== '') {stagePasteTimer = setTimeout(() => {- if (cancelled || ptyIdRef.current === null) return;- bridge.terminal.input(ptyIdRef.current, staged);+ if (cancelled || !terminalInputEnabledRef.current || launchCapabilityLimited) return;+ sendInput(staged);term.focus();}, STAGE_PASTE_SETTLE_MS);}@@ -1038,6 +1169,10 @@ function TerminalSession({return () => {cancelled = true;+ terminalInputEnabledRef.current = false;+ terminalInputRef.current = () => undefined;+ window.removeEventListener('pagehide', markDocumentUnloading);+ document.removeEventListener('visibilitychange', markDocumentVisible);if (stagePasteTimer !== undefined) clearTimeout(stagePasteTimer);if (injectCapTimer !== undefined) clearTimeout(injectCapTimer);readinessScan = undefined;@@ -1051,10 +1186,14 @@ function TerminalSession({ptyResizeThrottle?.cancel();unsubData?.();unsubExit?.();+ unsubNotice?.();titleDisposable?.dispose();linkProviderDisposable?.dispose();term.dispose();- if (ptyId)+ // BrowserWindow close and app quit reap in main. A renderer reload keeps+ // the window alive, so leave that PTY for the replacement renderer to+ // adopt instead of turning reload into a fresh shell.+ if (ptyId && !documentUnloading)void bridge.terminal.kill(ptyId).catch((err) => console.warn('[terminal] kill on unmount failed:', err));@@ -1109,9 +1248,9 @@ function TerminalSession({function onDrop(event: DragEvent) {if (!isExternalFileDrag(event)) return;event.preventDefault();- const livePtyId = ptyIdRef.current;- if (livePtyId === null) return;- const paths = filesFromExternalDrop(event)+ if (!terminalInputEnabledRef.current) return;+ const droppedFiles = filesFromExternalDrop(event);+ const paths = droppedFiles.map((file) => bridge.getPathForFile(file))// Drop any path carrying an ASCII control char (newline/CR/tab, etc).// The tty line discipline acts on those bytes before the shell sees the@@ -1124,10 +1263,26 @@ function TerminalSession({(path): path is string =>path !== null && path !== '' && !Array.from(path).some((ch) => ch.charCodeAt(0) < 0x20),);- if (paths.length === 0) return;+ let rejectedCount = droppedFiles.length - paths.length;+ const escapedPaths = paths.flatMap((path) => {+ if (bridge.platform !== 'win32') return [shellSingleQuote(path)];+ const family = shellFamilyRef.current;+ if (family === null) {+ rejectedCount += 1;+ return [];+ }+ const quoted = quoteWindowsShellPath(family, path);+ if (quoted === null) {+ rejectedCount += 1;+ return [];+ }+ return [quoted];+ });+ if (rejectedCount > 0) setPathDropNotice(true);+ if (escapedPaths.length === 0) return;// Trailing space so a following drop or keystroke doesn't glue onto the// path; no newline — the user reviews the composed prompt before submitting.- bridge.terminal.input(livePtyId, `${paths.map(shellSingleQuote).join(' ')} `);+ terminalInputRef.current(`${escapedPaths.join(' ')} `);}// Capture phase (mirrors FileTree's external-drop listeners) so the drop is// seen before xterm's canvas child can stopPropagation/preventDefault it.@@ -1162,6 +1317,47 @@ function TerminalSession({<TerminalCliUnverifiedBanner cli={cliNotice.cli} onDismiss={() => setCliNotice(null)} />)) : null}+ {status === 'running' ? (+ pathDropNotice ? (+ <TerminalNoticeBanner+ testId="terminal-path-drop-notice-banner"+ onDismiss={() => setPathDropNotice(false)}+ >+ {t`Some dropped files could not be inserted safely.`}+ </TerminalNoticeBanner>+ ) : supportFileNotice ? (+ <TerminalNoticeBanner+ testId="terminal-support-file-notice-banner"+ onDismiss={() => setSupportFileNotice(null)}+ >+ {supportFileNotice.reason === 'containment-refused'+ ? t`OpenKnowledge couldn't write launch settings under .ok/local/terminal because the folder is not safely contained in this project. Check that it is a real folder inside the project, not a link. Claude will ask you to approve OpenKnowledge.`+ : t`OpenKnowledge couldn't write launch settings under .ok/local/terminal this time. Check that the folder is writable. Claude will ask you to approve OpenKnowledge.`}+ </TerminalNoticeBanner>+ ) : shellNotice ? (+ <TerminalNoticeBanner+ testId="terminal-shell-notice-banner"+ onDismiss={() => setShellNotice(null)}+ >+ {shellNotice.reason === 'config-unreadable'+ ? t`OpenKnowledge couldn't read terminal.shell in .ok/local/config.yml. Using an available Windows shell instead.`+ : shellNotice.reason === 'invalid-value'+ ? t`terminal.shell in .ok/local/config.yml must be a string. Using an available Windows shell instead.`+ : shellNotice.reason === 'not-absolute'+ ? t`terminal.shell in .ok/local/config.yml must be an absolute Windows path. Using an available Windows shell instead.`+ : shellNotice.reason === 'unsupported-family'+ ? t`terminal.shell in .ok/local/config.yml supports PowerShell, cmd.exe, or Git Bash for OpenKnowledge-managed launches and dropped-file paths. This shell opens a plain terminal only; agent and command launches do not run in it.`+ : t`The terminal.shell executable in .ok/local/config.yml was not found. Using an available Windows shell instead.`}+ </TerminalNoticeBanner>+ ) : manualSubmitNotice ? (+ <TerminalNoticeBanner+ testId="terminal-manual-submit-notice-banner"+ onDismiss={() => setManualSubmitNotice(false)}+ >+ {t`The prompt was pasted but not submitted automatically. Review it, then press Enter to send it.`}+ </TerminalNoticeBanner>+ ) : null+ ) : null}{/* This wrapper exists so the pending notice covers the CANVAS only. Thereadiness / CLI banners above are gated on `status === 'running'`, and`resolveLaunchCommand` sets their verdicts BEFORE `create()` resolves,diff --git a/packages/app/src/components/handoff/terminal-command-events.test.ts b/packages/app/src/components/handoff/terminal-command-events.test.tsindex 5a1b879b3..7c58b85e2 100644--- a/packages/app/src/components/handoff/terminal-command-events.test.ts+++ b/packages/app/src/components/handoff/terminal-command-events.test.ts@@ -10,6 +10,7 @@ import {requestTerminalCommand,subscribeToTerminalCommandRequests,terminalCommandFor,+ windowsTerminalCommandFor,} from './terminal-command-events';describe('terminalCommandFor', () => {@@ -26,6 +27,18 @@ describe('terminalCommandFor', () => {expect(terminalCommandFor('constructor')).toBeUndefined();expect(terminalCommandFor('__proto__')).toBeUndefined();});++ test('keeps the Windows install command structured until shell composition', () => {+ expect(windowsTerminalCommandFor('install-slidev')).toEqual({+ executable: 'npm',+ args: ['install', '-g', '@slidev/cli', '@slidev/theme-default'],+ });+ expect(windowsTerminalCommandFor('git-status')).toEqual({+ executable: 'git',+ args: ['status'],+ });+ expect(windowsTerminalCommandFor('npm publish')).toBeUndefined();+ });});describe('the bus', () => {diff --git a/packages/app/src/components/handoff/terminal-command-events.ts b/packages/app/src/components/handoff/terminal-command-events.tsindex 39742aa09..08d70a15e 100644--- a/packages/app/src/components/handoff/terminal-command-events.ts+++ b/packages/app/src/components/handoff/terminal-command-events.ts@@ -12,13 +12,13 @@* shell text: an id that is not in {@link TERMINAL_COMMANDS} resolves to* nothing and the request is dropped.*- * The resolved string is baked into the PTY spawn as- * `$SHELL -l -i -c '<cmd>; exec …'` (see TerminalPanel), not typed into a live- * shell — so it never reaches the line editor, never lands in shell history,- * and runs under a login+interactive shell, which is what makes a global `npm`- * install resolve at all from a GUI-launched app.+ * The resolved payload is baked into the PTY spawn (a POSIX command string or+ * structured Windows argv), not typed into a live shell, so it never reaches+ * the line editor or persistent history.*/+import { shellSingleQuote, type TerminalLaunchCommand } from '@inkeep/open-knowledge-core';+/** Commands a UI surface may ask the terminal to run. Closed by design. */export type TerminalCommandId = 'install-slidev' | 'git-status';@@ -31,19 +31,36 @@ export type TerminalCommandId = 'install-slidev' | 'git-status';* on boot without it. Installing only the CLI leaves the user with a Slides* action that opens nothing.*/-const TERMINAL_COMMANDS: Record<TerminalCommandId, string> = {- 'install-slidev': 'npm install -g @slidev/cli @slidev/theme-default',+const TERMINAL_COMMANDS: Record<TerminalCommandId, TerminalLaunchCommand> = {+ 'install-slidev': {+ executable: 'npm',+ args: ['install', '-g', '@slidev/cli', '@slidev/theme-default'],+ },// The sync panel's "Resolve in terminal": land the user in the project with// the state of the working tree already printed, rather than in a bare shell// they have to orient themselves in. Read-only by construction — resolving is// theirs to drive, and a constant keeps the closed-union contract (no path,// no branch name, nothing interpolated into shell text).- 'git-status': 'git status',+ 'git-status': {+ executable: 'git',+ args: ['status'],+ },};+function posixCommandToken(token: string): string {+ return /^[A-Za-z0-9_@%+=:,./-]+$/u.test(token) ? token : shellSingleQuote(token);+}+/** The shell text for `id`, or undefined when the id is not in the union (a* stale event from an older renderer, or a hand-fired one). */export function terminalCommandFor(id: string): string | undefined {+ if (!Object.hasOwn(TERMINAL_COMMANDS, id)) return undefined;+ const command = TERMINAL_COMMANDS[id as TerminalCommandId];+ return [command.executable, ...command.args].map(posixCommandToken).join(' ');+}++/** Structured Windows counterpart; shell-family composition stays in the PTY host. */+export function windowsTerminalCommandFor(id: string): TerminalLaunchCommand | undefined {return Object.hasOwn(TERMINAL_COMMANDS, id)? TERMINAL_COMMANDS[id as TerminalCommandId]: undefined;diff --git a/packages/app/src/lib/command-menu-parity.test.ts b/packages/app/src/lib/command-menu-parity.test.tsindex a91955d52..572d957a1 100644--- a/packages/app/src/lib/command-menu-parity.test.ts+++ b/packages/app/src/lib/command-menu-parity.test.ts@@ -192,6 +192,7 @@ function makeFullDeps(): MenuDeps {onNewTerminal: noop,onKillTerminal: noop,onNewTerminalWindow: noop,+ terminalCapable: true,terminalLive: true,agentPanelVisible: true,onToggleAgentPanel: noop,diff --git a/packages/app/src/locales/ar/messages.json b/packages/app/src/locales/ar/messages.jsonindex 9f729c1f8..17173628d 100644--- a/packages/app/src/locales/ar/messages.json+++ b/packages/app/src/locales/ar/messages.json@@ -108,6 +108,7 @@"0NkNB5": ["قبل ", ["0"], " شهر"],"0QVrvp": ["يعمل الحد الأقصى من الوكلاء بالفعل"],"0TnCvC": ["إعادة تسمية ", ["0"]],+ "0WsUA2": ["تم لصق المطالبة ولكن لم يتم إرسالها تلقائيًا. راجعها، ثم اضغط على Enter لإرسالها."],"0YUS3Q": ["مجلد فرعي تحت المجلد الحالي"],"0_J12R": ["ملف جديد من القالب «",@@ -142,6 +143,9 @@"0pZmTP": ["تعذّرت مشاركة هذا المسار."],"0qyKG6": ["متزامن من القرص"],"0r6d6v": ["حُفظت التغييرات تلقائيًا."],+ "0rT21w": [+ "يدعم terminal.shell في .ok/local/config.yml PowerShell أو cmd.exe أو Git Bash لعمليات التشغيل التي يديرها OpenKnowledge ولمسارات الملفات المُسقطة. يفتح هذا الغلاف طرفية عادية فقط؛ ولا تعمل عمليات تشغيل الوكلاء والأوامر فيه."+ ],"0rwwOn": ["حسب الوسم"],"0s8-e8": ["حدّد مكوّنات الكتل وكتل المصدر الاحتياطية أو ادخلها أو غادرها من حدود لوحة المفاتيح."@@ -551,6 +555,9 @@"65Ea2s": ["يثبّت الكشف منفذًا ثابتًا لكي يبقى هدف النفق مستقرًا عبر عمليات إعادة التشغيل."],"67Dpmh": ["اقتراحات أوامر الشرطة المائلة"],"67f-3g": ["نجح التكرار لكن الشريط الجانبي قد يكون قديمًا — حدّث لإعادة المزامنة"],+ "69E1Pq": [+ "يجب أن تكون terminal.shell في .ok/local/config.yml سلسلة نصية. سيتم استخدام صدفة Windows متاحة بدلًا منها."+ ],"69KLIV": ["إفلات"],"6ASTuj": ["تُنفَّذ الأوامر بكامل صلاحيات حساب المستخدم الخاص بك على هذا الجهاز. أوقف هذا الخيار لتعطيل الصدفة."@@ -943,6 +950,9 @@]],"ALhMYW": ["الطرفية"],+ "AN-UPd": [+ "يجب أن تكون terminal.shell في .ok/local/config.yml مسار Windows مطلقًا. سيتم استخدام صدفة Windows متاحة بدلًا منها."+ ],"ANFxWn": ["تعذّر حذف هذه السمة. حدّث الصفحة وحاول مرة أخرى."],"APNlbk": ["خروج ", ["0"]],"AQ-Lfg": ["تعذّر تحميل القوالب"],@@ -985,6 +995,7 @@"AqnqMJ": ["تم ضبط مفتاح API"],"AsqRE_": ["الموقع الافتراضي للمرفقات الجديدة"],"AtBdnD": ["تعذّر حذف المهارة: ", ["error"]],+ "AvqEDl": ["تعذّر إدراج بعض الملفات التي تم إفلاتها بأمان."],"AwLCZA": ["استجابت نقطة النهاية، لكن ليس باستجابة تضمينات متوافقة مع OpenAI. تحقق من الرابط الأساسي."],@@ -1170,6 +1181,9 @@"D12vtS": ["(منفصل)"],"D2emTw": ["حدث خطأ ما أثناء إرسال ملاحظاتك. يرجى المحاولة مرة أخرى."],"D4H2N6": ["إزالة ", ["tag"]],+ "D7gKrd": [+ "تعذّر على OpenKnowledge كتابة إعدادات التشغيل ضمن .ok/local/terminal لأن المجلد غير موجود بأمان داخل هذا المشروع. تحقّق من أنه مجلد حقيقي داخل المشروع وليس رابطًا. سيطلب منك Claude الموافقة على OpenKnowledge."+ ],"D7hnvB": ["يجري التمعّن…"],"D8JJwQ": ["الملاحظات غير متاحة الآن. يرجى المحاولة لاحقًا."],"D8OV7J": ["المتعاونون فقط"],@@ -1780,6 +1794,9 @@"K6jxcj": ["إضافة مفتاح"],"K7NMEc": [["uploadFolderName"], " — ", ["0"], " ملف"],"K8-WWn": ["التنقل بين خلايا الجدول"],+ "K8EvAV": [+ "تعذّر على OpenKnowledge قراءة terminal.shell في .ok/local/config.yml. سيتم استخدام صدفة Windows متاحة بدلًا منها."+ ],"K9J00P": ["فشل الاستنساخ — خطأ في الاتصال"],"KDrbNG": ["بحث OpenKnowledge عن روابط ", ["subject"]],"KDuPiY": ["يجري رفع ", ["fileName"]],@@ -1793,6 +1810,9 @@"KOZud0": ["ابنِ قاعدة معرفة لبحث المنافسين. ابدأ بصفحة نظرة عامة، ثم أضف صفحات مترابطة لكل منافس، ومنتجاته وأسعاره، والمصادر وراء كل ادعاء."],+ "KOeFXa": [+ "تعذّر على OpenKnowledge كتابة إعدادات التشغيل ضمن .ok/local/terminal هذه المرة. تحقّق من أن المجلد قابل للكتابة. سيطلب منك Claude الموافقة على OpenKnowledge."+ ],"KPW5WC": ["نقل قالبًا"],"KQGZuq": ["يُعاد استخدامه إن كان موجودًا، ويُنشأ إن لم يكن."],"KRJ6xh": ["لا توجد وسوم بعد. تابع الكتابة لإنشاء واحد."],@@ -4178,6 +4198,9 @@"kEiVv6": ["تعلّم هذه المهاراتُ أدواتِك كيفية العمل مع OpenKnowledge. تثبيت واحدة يضيفها إلى كل أداة ذكاء اصطناعي على هذا الجهاز."],+ "kF2Yua": [+ "لم يتم العثور على الملف التنفيذي terminal.shell المحدد في .ok/local/config.yml. سيتم استخدام صدفة Windows متاحة بدلًا منه."+ ],"kFLlsI": ["أدرج مرجع حاشية مع بذرة تعريف مطابقة."],"kGp168": ["تعذّر تجهيز هذا المشروع للنشر."],"kI5pWt": ["الصورة غير موجودة: ", ["errorLabel"]],diff --git a/packages/app/src/locales/ar/messages.po b/packages/app/src/locales/ar/messages.poindex 4e35a24ad..92ae1a21d 100644--- a/packages/app/src/locales/ar/messages.po+++ b/packages/app/src/locales/ar/messages.po@@ -4729,12 +4729,10 @@ msgstr "يجري قطع الاتصال"#: src/components/BranchRecycleBanner.tsx#: src/components/BugReportSendToast.tsx-#: src/components/ClaudeReadinessBanner.tsx#: src/components/NavigatorApp.tsx#: src/components/OnboardingCard.tsx#: src/components/settings/SharingSection.tsx-#: src/components/TerminalCliMissingBanner.tsx-#: src/components/TerminalCliUnverifiedBanner.tsx+#: src/components/TerminalNoticeBanner.tsxmsgid "Dismiss"msgstr "تجاهل"@@ -9422,6 +9420,18 @@ msgstr "تحقق OpenKnowledge من التعارضات"msgid "OpenKnowledge checked the project"msgstr "تحقق OpenKnowledge من المشروع"+#: src/components/TerminalPanel.tsx+msgid "OpenKnowledge couldn't read terminal.shell in .ok/local/config.yml. Using an available Windows shell instead."+msgstr "تعذّر على OpenKnowledge قراءة terminal.shell في .ok/local/config.yml. سيتم استخدام صدفة Windows متاحة بدلًا منها."++#: src/components/TerminalPanel.tsx+msgid "OpenKnowledge couldn't write launch settings under .ok/local/terminal because the folder is not safely contained in this project. Check that it is a real folder inside the project, not a link. Claude will ask you to approve OpenKnowledge."+msgstr "تعذّر على OpenKnowledge كتابة إعدادات التشغيل ضمن .ok/local/terminal لأن المجلد غير موجود بأمان داخل هذا المشروع. تحقّق من أنه مجلد حقيقي داخل المشروع وليس رابطًا. سيطلب منك Claude الموافقة على OpenKnowledge."++#: src/components/TerminalPanel.tsx+msgid "OpenKnowledge couldn't write launch settings under .ok/local/terminal this time. Check that the folder is writable. Claude will ask you to approve OpenKnowledge."+msgstr "تعذّر على OpenKnowledge كتابة إعدادات التشغيل ضمن .ok/local/terminal هذه المرة. تحقّق من أن المجلد قابل للكتابة. سيطلب منك Claude الموافقة على OpenKnowledge."+#: src/lib/acp/tool-call-display.tsmsgid "OpenKnowledge created a share link"msgstr "أنشأ OpenKnowledge رابط مشاركة"@@ -12342,6 +12352,10 @@ msgstr "انتهت مهلة بدء تشغيل Slidev. حاول مرة أخرى."msgid "Small section heading."msgstr "عنوان قسم صغير."+#: src/components/TerminalPanel.tsx+msgid "Some dropped files could not be inserted safely."+msgstr "تعذّر إدراج بعض الملفات التي تم إفلاتها بأمان."+#: src/components/SyncStatusBadge.tsxmsgid "Some files are not listed — the working tree has too many changes."msgstr "بعض الملفات غير مدرجة: شجرة العمل تحتوي على تغييرات كثيرة جدًا."@@ -13003,6 +13017,18 @@ msgstr "لم تُحمَّل إعدادات الطرفية بعد — أعد الmsgid "Terminal settings not yet loaded — try again in a moment"msgstr "لم تُحمَّل إعدادات الطرفية بعد — أعد المحاولة بعد قليل"+#: src/components/TerminalPanel.tsx+msgid "terminal.shell in .ok/local/config.yml must be a string. Using an available Windows shell instead."+msgstr "يجب أن تكون terminal.shell في .ok/local/config.yml سلسلة نصية. سيتم استخدام صدفة Windows متاحة بدلًا منها."++#: src/components/TerminalPanel.tsx+msgid "terminal.shell in .ok/local/config.yml must be an absolute Windows path. Using an available Windows shell instead."+msgstr "يجب أن تكون terminal.shell في .ok/local/config.yml مسار Windows مطلقًا. سيتم استخدام صدفة Windows متاحة بدلًا منها."++#: src/components/TerminalPanel.tsx+msgid "terminal.shell in .ok/local/config.yml supports PowerShell, cmd.exe, or Git Bash for OpenKnowledge-managed launches and dropped-file paths. This shell opens a plain terminal only; agent and command launches do not run in it."+msgstr "يدعم terminal.shell في .ok/local/config.yml PowerShell أو cmd.exe أو Git Bash لعمليات التشغيل التي يديرها OpenKnowledge ولمسارات الملفات المُسقطة. يفتح هذا الغلاف طرفية عادية فقط؛ ولا تعمل عمليات تشغيل الوكلاء والأوامر فيه."+#: src/components/settings/SearchSection.tsxmsgid "Test connection"msgstr "اختبار الاتصال"@@ -13203,6 +13229,10 @@ msgstr "تحظر المعاينة الموارد التي لا تستوفي قوmsgid "The project's server is on a different branch than this window — content can't load."msgstr "خادم هذا المشروع على فرع مختلف عن هذه النافذة — يتعذر تحميل المحتوى."+#: src/components/TerminalPanel.tsx+msgid "The prompt was pasted but not submitted automatically. Review it, then press Enter to send it."+msgstr "تم لصق المطالبة ولكن لم يتم إرسالها تلقائيًا. راجعها، ثم اضغط على Enter لإرسالها."+#: src/components/PropertyPanel.tsxmsgid "The properties block at the top of this doc has a formatting error. Switch to source mode to fix it."msgstr "كتلة الخصائص أعلى هذا المستند بها خطأ تنسيقي. بدّل إلى وضع المصدر لإصلاحه."@@ -13315,6 +13345,10 @@ msgstr "انتهت جلسة الطرفية."msgid "The terminal stopped unexpectedly."msgstr "توقفت الطرفية على نحو غير متوقع."+#: src/components/TerminalPanel.tsx+msgid "The terminal.shell executable in .ok/local/config.yml was not found. Using an available Windows shell instead."+msgstr "لم يتم العثور على الملف التنفيذي terminal.shell المحدد في .ok/local/config.yml. سيتم استخدام صدفة Windows متاحة بدلًا منه."+#: src/components/AuthModal.tsxmsgid "The token needs the repo and read:user scopes."msgstr "يحتاج الرمز إلى نطاقي repo وread:user."diff --git a/packages/app/src/locales/bn/messages.json b/packages/app/src/locales/bn/messages.jsonindex 1c6aa8a10..56a231c03 100644--- a/packages/app/src/locales/bn/messages.json+++ b/packages/app/src/locales/bn/messages.json@@ -82,6 +82,9 @@"0NkNB5": [["0"], " মাস আগে"],"0QVrvp": ["সর্বোচ্চসংখ্যক এজেন্ট আগে থেকেই চলছে"],"0TnCvC": [["0"], "-এর নাম বদলান"],+ "0WsUA2": [+ "প্রম্পটটি পেস্ট করা হয়েছে, কিন্তু স্বয়ংক্রিয়ভাবে জমা দেওয়া হয়নি। এটি পর্যালোচনা করুন, তারপর পাঠাতে Enter চাপুন।"+ ],"0YUS3Q": ["বর্তমান ফোল্ডারের নিচে উপ-ফোল্ডার"],"0_J12R": [["targetLabel"],@@ -115,6 +118,9 @@"0pZmTP": ["এই পাথ শেয়ার করা যাচ্ছে না।"],"0qyKG6": ["ডিস্ক থেকে সিঙ্ক করা"],"0r6d6v": ["পরিবর্তনগুলি স্বয়ংক্রিয়ভাবে সংরক্ষিত হয়েছে।"],+ "0rT21w": [+ ".ok/local/config.yml-এ terminal.shell OpenKnowledge-পরিচালিত লঞ্চ এবং ড্রপ করা ফাইলের পাথের জন্য PowerShell, cmd.exe অথবা Git Bash সমর্থন করে। এই শেলটি শুধু একটি সাধারণ টার্মিনাল খোলে; এজেন্ট এবং কমান্ড লঞ্চ এতে চলে না।"+ ],"0rwwOn": ["ট্যাগ অনুসারে"],"0s8-e8": ["কীবোর্ডের সীমানা থেকে ব্লক কম্পোনেন্ট ও ফলব্যাক সোর্স ব্লক নির্বাচন করুন, তাতে ঢুকুন, বা বেরিয়ে আসুন।"@@ -477,6 +483,9 @@],"67Dpmh": ["স্ল্যাশ কমান্ডের প্রস্তাবনা"],"67f-3g": ["প্রতিলিপি সফল হয়েছে কিন্তু সাইডবার পুরোনো হতে পারে — আবার সিঙ্ক করতে সতেজ করুন"],+ "69E1Pq": [+ ".ok/local/config.yml-এ terminal.shell অবশ্যই একটি স্ট্রিং হতে হবে। পরিবর্তে একটি উপলভ্য Windows শেল ব্যবহার করা হচ্ছে।"+ ],"69KLIV": ["Escape"],"6ASTuj": ["এই মেশিনে কমান্ডগুলো আপনার ইউজার অ্যাকাউন্টের পূর্ণ অ্যাক্সেস নিয়ে চলে। শেল বন্ধ করতে এটি বন্ধ করুন।"@@ -794,6 +803,9 @@"AJ7_B2": ["নতুন থিম তৈরি করুন"],"AKxFtn": [["openedWorktreeCount", "plural", { "one": ["ওয়ার্কট্রি"], "other": ["ওয়ার্কট্রি"] }]],"ALhMYW": ["টার্মিনাল"],+ "AN-UPd": [+ ".ok/local/config.yml-এ terminal.shell অবশ্যই একটি সম্পূর্ণ Windows পাথ হতে হবে। পরিবর্তে একটি উপলভ্য Windows শেল ব্যবহার করা হচ্ছে।"+ ],"ANFxWn": ["এই থিম মুছে ফেলা যায়নি। রিফ্রেশ করে আবার চেষ্টা করুন।"],"APNlbk": ["প্রস্থান ", ["0"]],"AQ-Lfg": ["টেমপ্লেট লোড করা যায়নি"],@@ -836,6 +848,7 @@"AqnqMJ": ["API কী নির্ধারিত"],"AsqRE_": ["নতুন সংযুক্তির ডিফল্ট জায়গা"],"AtBdnD": ["স্কিল মুছে ফেলা যায়নি: ", ["error"]],+ "AvqEDl": ["ফেলে দেওয়া কিছু ফাইল নিরাপদে সন্নিবেশ করা যায়নি।"],"AwLCZA": ["এন্ডপয়েন্ট সাড়া দিয়েছে, কিন্তু OpenAI-সঙ্গতিপূর্ণ এমবেডিং সাড়া দিয়ে নয়। ভিত্তি URL দেখুন।"],"AwrGuz": ["এই নথিতে আবশ্যক প্রপার্টি অনুপস্থিত"],"AyKwqp": ["আপনার হোম ফোল্ডারে — এই মেশিনের প্রতিটি প্রজেক্টে, শুধু আপনার জন্য।"],@@ -973,6 +986,9 @@"D12vtS": ["(বিচ্ছিন্ন)"],"D2emTw": ["আপনার মতামত পাঠানোর সময় কিছু একটা ভুল হয়েছে। অনুগ্রহ করে আবার চেষ্টা করুন।"],"D4H2N6": [["tag"], " সরান"],+ "D7gKrd": [+ "OpenKnowledge .ok/local/terminal-এর অধীনে লঞ্চ সেটিংস লিখতে পারেনি, কারণ ফোল্ডারটি এই প্রকল্পের মধ্যে নিরাপদভাবে অবস্থিত নয়। নিশ্চিত করুন যে এটি প্রকল্পের ভেতরের একটি আসল ফোল্ডার, কোনো লিংক নয়। Claude আপনাকে OpenKnowledge অনুমোদন করতে বলবে।"+ ],"D7hnvB": ["ভেবে দেখা হচ্ছে…"],"D8JJwQ": ["মতামত এখন পাওয়া যাচ্ছে না। অনুগ্রহ করে পরে আবার চেষ্টা করুন।"],"D8OV7J": ["কেবল সহযোগীরা"],@@ -1507,6 +1523,9 @@"K6jxcj": ["একটি কী যোগ করুন"],"K7NMEc": [["uploadFolderName"], " — ", ["0"], "টি ফাইল"],"K8-WWn": ["টেবিলের ঘরগুলোর মধ্যে সরুন"],+ "K8EvAV": [+ "OpenKnowledge .ok/local/config.yml-এ terminal.shell পড়তে পারেনি। পরিবর্তে একটি উপলভ্য Windows শেল ব্যবহার করা হচ্ছে।"+ ],"K9J00P": ["ক্লোন ব্যর্থ — সংযোগ ত্রুটি"],"KDrbNG": ["OpenKnowledge ", ["subject"], " এর লিংক খুঁজেছে"],"KDuPiY": [["fileName"], " আপলোড করা হচ্ছে"],@@ -1522,6 +1541,9 @@"KOZud0": ["প্রতিযোগী গবেষণার একটি জ্ঞানভাণ্ডার গড়ুন। একটি সংক্ষিপ্তসার পাতা দিয়ে শুরু করুন, তারপর প্রতিটি প্রতিযোগী, তাদের পণ্য ও মূল্য, এবং প্রতিটি দাবির পেছনের উৎসের জন্য পরস্পর-যুক্ত পাতা যোগ করুন।"],+ "KOeFXa": [+ "OpenKnowledge এবার .ok/local/terminal-এর অধীনে লঞ্চ সেটিংস লিখতে পারেনি। ফোল্ডারটিতে লেখার অনুমতি আছে কি না পরীক্ষা করুন। Claude আপনাকে OpenKnowledge অনুমোদন করতে বলবে।"+ ],"KPW5WC": ["টেমপ্লেট সরানো হয়েছে"],"KQGZuq": ["আগে থেকে থাকলে পুনরায় ব্যবহার করা হয়, না থাকলে তৈরি করা হয়।"],"KRJ6xh": ["এখনও কোনো ট্যাগ নেই। একটি তৈরি করতে লিখতে থাকুন।"],@@ -3579,6 +3601,9 @@"kEiVv6": ["এগুলি আপনার AI টুলকে OpenKnowledge-এর সঙ্গে কাজ করতে শেখায়। একটি ইনস্টল করলে সেটি এই মেশিনের প্রতিটি AI টুলে যুক্ত হয়।"],+ "kF2Yua": [+ ".ok/local/config.yml-এ terminal.shell এক্সিকিউটেবলটি পাওয়া যায়নি। পরিবর্তে একটি উপলভ্য Windows শেল ব্যবহার করা হচ্ছে।"+ ],"kFLlsI": ["একটি পাদটীকা রেফারেন্স + মিলে যাওয়া সংজ্ঞার কাঠামো ঢোকান।"],"kGp168": ["এই প্রকল্পটি প্রকাশের জন্য প্রস্তুত করা যায়নি।"],"kI5pWt": ["ছবি পাওয়া যায়নি: ", ["errorLabel"]],diff --git a/packages/app/src/locales/bn/messages.po b/packages/app/src/locales/bn/messages.poindex 2dc9f7566..c709df541 100644--- a/packages/app/src/locales/bn/messages.po+++ b/packages/app/src/locales/bn/messages.po@@ -4725,12 +4725,10 @@ msgstr "সংযোগ বিচ্ছিন্ন করা হচ্ছে"#: src/components/BranchRecycleBanner.tsx#: src/components/BugReportSendToast.tsx-#: src/components/ClaudeReadinessBanner.tsx#: src/components/NavigatorApp.tsx#: src/components/OnboardingCard.tsx#: src/components/settings/SharingSection.tsx-#: src/components/TerminalCliMissingBanner.tsx-#: src/components/TerminalCliUnverifiedBanner.tsx+#: src/components/TerminalNoticeBanner.tsxmsgid "Dismiss"msgstr "সরিয়ে দিন"@@ -9418,6 +9416,18 @@ msgstr "OpenKnowledge দ্বন্দ্ব পরীক্ষা করেmsgid "OpenKnowledge checked the project"msgstr "OpenKnowledge প্রকল্প পরীক্ষা করেছে"+#: src/components/TerminalPanel.tsx+msgid "OpenKnowledge couldn't read terminal.shell in .ok/local/config.yml. Using an available Windows shell instead."+msgstr "OpenKnowledge .ok/local/config.yml-এ terminal.shell পড়তে পারেনি। পরিবর্তে একটি উপলভ্য Windows শেল ব্যবহার করা হচ্ছে।"++#: src/components/TerminalPanel.tsx+msgid "OpenKnowledge couldn't write launch settings under .ok/local/terminal because the folder is not safely contained in this project. Check that it is a real folder inside the project, not a link. Claude will ask you to approve OpenKnowledge."+msgstr "OpenKnowledge .ok/local/terminal-এর অধীনে লঞ্চ সেটিংস লিখতে পারেনি, কারণ ফোল্ডারটি এই প্রকল্পের মধ্যে নিরাপদভাবে অবস্থিত নয়। নিশ্চিত করুন যে এটি প্রকল্পের ভেতরের একটি আসল ফোল্ডার, কোনো লিংক নয়। Claude আপনাকে OpenKnowledge অনুমোদন করতে বলবে।"++#: src/components/TerminalPanel.tsx+msgid "OpenKnowledge couldn't write launch settings under .ok/local/terminal this time. Check that the folder is writable. Claude will ask you to approve OpenKnowledge."+msgstr "OpenKnowledge এবার .ok/local/terminal-এর অধীনে লঞ্চ সেটিংস লিখতে পারেনি। ফোল্ডারটিতে লেখার অনুমতি আছে কি না পরীক্ষা করুন। Claude আপনাকে OpenKnowledge অনুমোদন করতে বলবে।"+#: src/lib/acp/tool-call-display.tsmsgid "OpenKnowledge created a share link"msgstr "OpenKnowledge একটি শেয়ার লিংক তৈরি করেছে"@@ -12338,6 +12348,10 @@ msgstr "Slidev চালু হতে সময় শেষ হয়ে গেmsgid "Small section heading."msgstr "ছোট বিভাগ শিরোনাম।"+#: src/components/TerminalPanel.tsx+msgid "Some dropped files could not be inserted safely."+msgstr "ফেলে দেওয়া কিছু ফাইল নিরাপদে সন্নিবেশ করা যায়নি।"+#: src/components/SyncStatusBadge.tsxmsgid "Some files are not listed — the working tree has too many changes."msgstr "কিছু ফাইল তালিকায় নেই: ওয়ার্কিং ট্রিতে অনেক বেশি পরিবর্তন আছে।"@@ -12999,6 +13013,18 @@ msgstr "টার্মিনালের সেটিং এখনও লোডmsgid "Terminal settings not yet loaded — try again in a moment"msgstr "টার্মিনালের সেটিং এখনও লোড হয়নি — একটু পরে আবার চেষ্টা করুন"+#: src/components/TerminalPanel.tsx+msgid "terminal.shell in .ok/local/config.yml must be a string. Using an available Windows shell instead."+msgstr ".ok/local/config.yml-এ terminal.shell অবশ্যই একটি স্ট্রিং হতে হবে। পরিবর্তে একটি উপলভ্য Windows শেল ব্যবহার করা হচ্ছে।"++#: src/components/TerminalPanel.tsx+msgid "terminal.shell in .ok/local/config.yml must be an absolute Windows path. Using an available Windows shell instead."+msgstr ".ok/local/config.yml-এ terminal.shell অবশ্যই একটি সম্পূর্ণ Windows পাথ হতে হবে। পরিবর্তে একটি উপলভ্য Windows শেল ব্যবহার করা হচ্ছে।"++#: src/components/TerminalPanel.tsx+msgid "terminal.shell in .ok/local/config.yml supports PowerShell, cmd.exe, or Git Bash for OpenKnowledge-managed launches and dropped-file paths. This shell opens a plain terminal only; agent and command launches do not run in it."+msgstr ".ok/local/config.yml-এ terminal.shell OpenKnowledge-পরিচালিত লঞ্চ এবং ড্রপ করা ফাইলের পাথের জন্য PowerShell, cmd.exe অথবা Git Bash সমর্থন করে। এই শেলটি শুধু একটি সাধারণ টার্মিনাল খোলে; এজেন্ট এবং কমান্ড লঞ্চ এতে চলে না।"+#: src/components/settings/SearchSection.tsxmsgid "Test connection"msgstr "সংযোগ পরীক্ষা করুন"@@ -13199,6 +13225,10 @@ msgstr "প্রাকদর্শন সেসব সম্পদ আটকেmsgid "The project's server is on a different branch than this window — content can't load."msgstr "এই প্রজেক্টের সার্ভার এই উইন্ডো থেকে ভিন্ন ব্রাঞ্চে আছে — কনটেন্ট লোড করা যাচ্ছে না।"+#: src/components/TerminalPanel.tsx+msgid "The prompt was pasted but not submitted automatically. Review it, then press Enter to send it."+msgstr "প্রম্পটটি পেস্ট করা হয়েছে, কিন্তু স্বয়ংক্রিয়ভাবে জমা দেওয়া হয়নি। এটি পর্যালোচনা করুন, তারপর পাঠাতে Enter চাপুন।"+#: src/components/PropertyPanel.tsxmsgid "The properties block at the top of this doc has a formatting error. Switch to source mode to fix it."msgstr "এই নথির উপরের প্রপার্টি ব্লকে একটি বিন্যাস ত্রুটি আছে। এটি ঠিক করতে সোর্স মোডে যান।"@@ -13311,6 +13341,10 @@ msgstr "টার্মিনাল সেশন শেষ হয়েছে।msgid "The terminal stopped unexpectedly."msgstr "টার্মিনাল অপ্রত্যাশিতভাবে থেমে গেছে।"+#: src/components/TerminalPanel.tsx+msgid "The terminal.shell executable in .ok/local/config.yml was not found. Using an available Windows shell instead."+msgstr ".ok/local/config.yml-এ terminal.shell এক্সিকিউটেবলটি পাওয়া যায়নি। পরিবর্তে একটি উপলভ্য Windows শেল ব্যবহার করা হচ্ছে।"+#: src/components/AuthModal.tsxmsgid "The token needs the repo and read:user scopes."msgstr "টোকেনটির repo ও read:user স্কোপ দরকার।"diff --git a/packages/app/src/locales/en/messages.json b/packages/app/src/locales/en/messages.jsonindex a9092f072..326833445 100644--- a/packages/app/src/locales/en/messages.json+++ b/packages/app/src/locales/en/messages.json@@ -86,6 +86,9 @@"0NkNB5": [["0"], "mo ago"],"0QVrvp": ["Maximum agents already running"],"0TnCvC": ["Rename ", ["0"]],+ "0WsUA2": [+ "The prompt was pasted but not submitted automatically. Review it, then press Enter to send it."+ ],"0YUS3Q": ["Subfolder under current folder"],"0_J12R": ["New file from template \"",@@ -119,6 +122,9 @@"0pZmTP": ["Can't share this path."],"0qyKG6": ["Synced from disk"],"0r6d6v": ["Changes saved automatically."],+ "0rT21w": [+ "terminal.shell in .ok/local/config.yml supports PowerShell, cmd.exe, or Git Bash for OpenKnowledge-managed launches and dropped-file paths. This shell opens a plain terminal only; agent and command launches do not run in it."+ ],"0rwwOn": ["By tag"],"0s8-e8": ["Select, enter, or leave block components and fallback source blocks from keyboard boundaries."@@ -480,6 +486,9 @@"65Ea2s": ["Exposing pins a fixed port so the tunnel's target stays stable across restarts."],"67Dpmh": ["Slash command suggestions"],"67f-3g": ["Duplicate succeeded but the sidebar may be out of date — refresh to resync"],+ "69E1Pq": [+ "terminal.shell in .ok/local/config.yml must be a string. Using an available Windows shell instead."+ ],"69KLIV": ["Escape"],"6ASTuj": ["Commands run with the full access of your user account on this machine. Turn this off to disable the shell."@@ -812,6 +821,9 @@"AJ7_B2": ["Create new theme"],"AKxFtn": [["openedWorktreeCount", "plural", { "one": ["worktree"], "other": ["worktrees"] }]],"ALhMYW": ["Terminal"],+ "AN-UPd": [+ "terminal.shell in .ok/local/config.yml must be an absolute Windows path. Using an available Windows shell instead."+ ],"ANFxWn": ["Couldn’t delete this theme. Refresh and try again."],"APNlbk": ["exit ", ["0"]],"AQ-Lfg": ["Couldn't load templates"],@@ -854,6 +866,7 @@"AqnqMJ": ["API key set"],"AsqRE_": ["Default location for new attachments"],"AtBdnD": ["Couldn't delete skill: ", ["error"]],+ "AvqEDl": ["Some dropped files could not be inserted safely."],"AwLCZA": ["The endpoint answered, but not with an OpenAI-compatible embeddings response. Check the base URL."],@@ -1003,6 +1016,9 @@"D12vtS": ["(detached)"],"D2emTw": ["Something went wrong sending your feedback. Please try again."],"D4H2N6": ["Remove ", ["tag"]],+ "D7gKrd": [+ "OpenKnowledge couldn't write launch settings under .ok/local/terminal because the folder is not safely contained in this project. Check that it is a real folder inside the project, not a link. Claude will ask you to approve OpenKnowledge."+ ],"D7hnvB": ["Pondering…"],"D8JJwQ": ["Feedback isn't available right now. Please try again later."],"D8OV7J": ["Only collaborators"],@@ -1549,6 +1565,9 @@"K6jxcj": ["Add a key"],"K7NMEc": [["uploadFolderName"], " — ", ["0"], " files"],"K8-WWn": ["Move between table cells"],+ "K8EvAV": [+ "OpenKnowledge couldn't read terminal.shell in .ok/local/config.yml. Using an available Windows shell instead."+ ],"K9J00P": ["Clone failed — connection error"],"KDrbNG": ["OpenKnowledge looked up links for ", ["subject"]],"KDuPiY": ["Uploading ", ["fileName"]],@@ -1564,6 +1583,9 @@"KOZud0": ["Build a competitor research knowledge base. Start with an overview page, then add cross-linked pages for each competitor, their products and pricing, and the sources behind every claim."],+ "KOeFXa": [+ "OpenKnowledge couldn't write launch settings under .ok/local/terminal this time. Check that the folder is writable. Claude will ask you to approve OpenKnowledge."+ ],"KPW5WC": ["moved template"],"KQGZuq": ["Reused if it already exists, created if not."],"KRJ6xh": ["No tags yet. Continue typing to create one."],@@ -3681,6 +3703,9 @@"kEiVv6": ["These teach your AI tools how to work with OpenKnowledge. Installing one adds it to every AI tool on this machine."],+ "kF2Yua": [+ "The terminal.shell executable in .ok/local/config.yml was not found. Using an available Windows shell instead."+ ],"kFLlsI": ["Insert a footnote reference + matching definition stub."],"kGp168": ["Couldn't prepare this project for publish."],"kI5pWt": ["Image not found: ", ["errorLabel"]],diff --git a/packages/app/src/locales/en/messages.po b/packages/app/src/locales/en/messages.poindex 67327a653..56133e97d 100644--- a/packages/app/src/locales/en/messages.po+++ b/packages/app/src/locales/en/messages.po@@ -4729,12 +4729,10 @@ msgstr "Disconnecting"#: src/components/BranchRecycleBanner.tsx#: src/components/BugReportSendToast.tsx-#: src/components/ClaudeReadinessBanner.tsx#: src/components/NavigatorApp.tsx#: src/components/OnboardingCard.tsx#: src/components/settings/SharingSection.tsx-#: src/components/TerminalCliMissingBanner.tsx-#: src/components/TerminalCliUnverifiedBanner.tsx+#: src/components/TerminalNoticeBanner.tsxmsgid "Dismiss"msgstr "Dismiss"@@ -9422,6 +9420,18 @@ msgstr "OpenKnowledge checked for conflicts"msgid "OpenKnowledge checked the project"msgstr "OpenKnowledge checked the project"+#: src/components/TerminalPanel.tsx+msgid "OpenKnowledge couldn't read terminal.shell in .ok/local/config.yml. Using an available Windows shell instead."+msgstr "OpenKnowledge couldn't read terminal.shell in .ok/local/config.yml. Using an available Windows shell instead."++#: src/components/TerminalPanel.tsx+msgid "OpenKnowledge couldn't write launch settings under .ok/local/terminal because the folder is not safely contained in this project. Check that it is a real folder inside the project, not a link. Claude will ask you to approve OpenKnowledge."+msgstr "OpenKnowledge couldn't write launch settings under .ok/local/terminal because the folder is not safely contained in this project. Check that it is a real folder inside the project, not a link. Claude will ask you to approve OpenKnowledge."++#: src/components/TerminalPanel.tsx+msgid "OpenKnowledge couldn't write launch settings under .ok/local/terminal this time. Check that the folder is writable. Claude will ask you to approve OpenKnowledge."+msgstr "OpenKnowledge couldn't write launch settings under .ok/local/terminal this time. Check that the folder is writable. Claude will ask you to approve OpenKnowledge."+#: src/lib/acp/tool-call-display.tsmsgid "OpenKnowledge created a share link"msgstr "OpenKnowledge created a share link"@@ -12342,6 +12352,10 @@ msgstr "Slidev timed out while starting. Try again."msgid "Small section heading."msgstr "Small section heading."+#: src/components/TerminalPanel.tsx+msgid "Some dropped files could not be inserted safely."+msgstr "Some dropped files could not be inserted safely."+#: src/components/SyncStatusBadge.tsxmsgid "Some files are not listed — the working tree has too many changes."msgstr "Some files are not listed — the working tree has too many changes."@@ -13003,6 +13017,18 @@ msgstr "Terminal settings not loaded yet — try again in a moment."msgid "Terminal settings not yet loaded — try again in a moment"msgstr "Terminal settings not yet loaded — try again in a moment"+#: src/components/TerminalPanel.tsx+msgid "terminal.shell in .ok/local/config.yml must be a string. Using an available Windows shell instead."+msgstr "terminal.shell in .ok/local/config.yml must be a string. Using an available Windows shell instead."++#: src/components/TerminalPanel.tsx+msgid "terminal.shell in .ok/local/config.yml must be an absolute Windows path. Using an available Windows shell instead."+msgstr "terminal.shell in .ok/local/config.yml must be an absolute Windows path. Using an available Windows shell instead."++#: src/components/TerminalPanel.tsx+msgid "terminal.shell in .ok/local/config.yml supports PowerShell, cmd.exe, or Git Bash for OpenKnowledge-managed launches and dropped-file paths. This shell opens a plain terminal only; agent and command launches do not run in it."+msgstr "terminal.shell in .ok/local/config.yml supports PowerShell, cmd.exe, or Git Bash for OpenKnowledge-managed launches and dropped-file paths. This shell opens a plain terminal only; agent and command launches do not run in it."+#: src/components/settings/SearchSection.tsxmsgid "Test connection"msgstr "Test connection"@@ -13203,6 +13229,10 @@ msgstr "The preview blocks resources that don't meet its security rules (for examsgid "The project's server is on a different branch than this window — content can't load."msgstr "The project's server is on a different branch than this window — content can't load."+#: src/components/TerminalPanel.tsx+msgid "The prompt was pasted but not submitted automatically. Review it, then press Enter to send it."+msgstr "The prompt was pasted but not submitted automatically. Review it, then press Enter to send it."+#: src/components/PropertyPanel.tsxmsgid "The properties block at the top of this doc has a formatting error. Switch to source mode to fix it."msgstr "The properties block at the top of this doc has a formatting error. Switch to source mode to fix it."@@ -13315,6 +13345,10 @@ msgstr "The terminal session ended."msgid "The terminal stopped unexpectedly."msgstr "The terminal stopped unexpectedly."+#: src/components/TerminalPanel.tsx+msgid "The terminal.shell executable in .ok/local/config.yml was not found. Using an available Windows shell instead."+msgstr "The terminal.shell executable in .ok/local/config.yml was not found. Using an available Windows shell instead."+#: src/components/AuthModal.tsxmsgid "The token needs the repo and read:user scopes."msgstr "The token needs the repo and read:user scopes."diff --git a/packages/app/src/locales/es/messages.json b/packages/app/src/locales/es/messages.jsonindex fe50232b8..253c441fe 100644--- a/packages/app/src/locales/es/messages.json+++ b/packages/app/src/locales/es/messages.json@@ -102,6 +102,9 @@"0NkNB5": ["hace ", ["0"], " meses"],"0QVrvp": ["Ya hay el máximo de agentes en marcha"],"0TnCvC": ["Renombrar ", ["0"]],+ "0WsUA2": [+ "El prompt se pegó, pero no se envió automáticamente. Revísalo y pulsa Enter para enviarlo."+ ],"0YUS3Q": ["Subcarpeta dentro de la carpeta actual"],"0_J12R": ["Archivo nuevo a partir de la plantilla \"",@@ -137,6 +140,9 @@"0pZmTP": ["No se puede compartir esta ruta."],"0qyKG6": ["Sincronizado desde el disco"],"0r6d6v": ["Los cambios se guardaron automáticamente."],+ "0rT21w": [+ "terminal.shell en .ok/local/config.yml admite PowerShell, cmd.exe o Git Bash para los inicios administrados por OpenKnowledge y las rutas de archivos soltados. Este shell solo abre un terminal normal; los inicios de agentes y comandos no se ejecutan en él."+ ],"0rwwOn": ["Por etiqueta"],"0s8-e8": ["Selecciona, entra o sale de componentes de bloque y bloques de código alternativos desde los límites del teclado."@@ -569,6 +575,9 @@"67f-3g": ["Se duplicó correctamente, pero puede que la barra lateral esté desactualizada; actualízala para resincronizar"],+ "69E1Pq": [+ "terminal.shell en .ok/local/config.yml debe ser una cadena. Se usará un shell de Windows disponible."+ ],"69KLIV": ["Esc"],"6ASTuj": ["Los comandos se ejecutan con todo el acceso de tu cuenta de usuario en este equipo. Desactiva esto para deshabilitar el shell."@@ -957,6 +966,9 @@]],"ALhMYW": ["Terminal"],+ "AN-UPd": [+ "terminal.shell en .ok/local/config.yml debe ser una ruta absoluta de Windows. Se usará un shell de Windows disponible."+ ],"ANFxWn": ["No se pudo eliminar este tema. Actualiza e inténtalo de nuevo."],"APNlbk": ["salida ", ["0"]],"AQ-Lfg": ["No se pudieron cargar las plantillas"],@@ -1003,6 +1015,7 @@"AqnqMJ": ["Clave de API definida"],"AsqRE_": ["Ubicación por defecto de los adjuntos nuevos"],"AtBdnD": ["No se pudo eliminar la habilidad: ", ["error"]],+ "AvqEDl": ["Algunos archivos soltados no se pudieron insertar de forma segura."],"AwLCZA": ["El endpoint respondió, pero no con una respuesta de embeddings compatible con OpenAI. Revisa la URL base."],@@ -1186,6 +1199,9 @@"D12vtS": ["(desacoplado)"],"D2emTw": ["Algo salió mal al enviar tus comentarios. Inténtalo de nuevo."],"D4H2N6": ["Quitar ", ["tag"]],+ "D7gKrd": [+ "OpenKnowledge no pudo escribir la configuración de inicio en .ok/local/terminal porque la carpeta no está contenida de forma segura en este proyecto. Comprueba que sea una carpeta real dentro del proyecto y no un enlace. Claude te pedirá que apruebes OpenKnowledge."+ ],"D7hnvB": ["Meditando…"],"D8JJwQ": ["Ahora mismo no se pueden enviar comentarios. Inténtalo más tarde."],"D8OV7J": ["Solo colaboradores"],@@ -1814,6 +1830,9 @@"K6jxcj": ["Añadir una clave"],"K7NMEc": [["uploadFolderName"], " — ", ["0"], " archivos"],"K8-WWn": ["Moverse entre celdas de la tabla"],+ "K8EvAV": [+ "OpenKnowledge no pudo leer terminal.shell en .ok/local/config.yml. Se usará un shell de Windows disponible."+ ],"K9J00P": ["No se pudo clonar: error de conexión"],"KDrbNG": ["OpenKnowledge consultó los enlaces de ", ["subject"]],"KDuPiY": ["Subiendo ", ["fileName"]],@@ -1829,6 +1848,9 @@"KOZud0": ["Crea una base de conocimiento de investigación de la competencia. Empieza con una página general y añade después páginas enlazadas entre sí para cada competidor, sus productos y precios, y las fuentes que respaldan cada afirmación."],+ "KOeFXa": [+ "OpenKnowledge no pudo escribir la configuración de inicio en .ok/local/terminal esta vez. Comprueba que se pueda escribir en la carpeta. Claude te pedirá que apruebes OpenKnowledge."+ ],"KPW5WC": ["plantilla movida"],"KQGZuq": ["Se reutiliza si ya existe; si no, se crea."],"KRJ6xh": ["Todavía no hay etiquetas. Sigue escribiendo para crear una."],@@ -4274,6 +4296,9 @@"kEiVv6": ["Estas enseñan a tus herramientas de IA a trabajar con OpenKnowledge. Al instalar una se añade a todas las herramientas de IA de este equipo."],+ "kF2Yua": [+ "No se encontró el ejecutable terminal.shell de .ok/local/config.yml. Se usará un shell de Windows disponible."+ ],"kFLlsI": ["Inserta una referencia a nota al pie y su definición correspondiente."],"kGp168": ["No se pudo preparar este proyecto para publicarlo."],"kI5pWt": ["No se encontró la imagen: ", ["errorLabel"]],diff --git a/packages/app/src/locales/es/messages.po b/packages/app/src/locales/es/messages.poindex b77de51cb..a2d27c6c1 100644--- a/packages/app/src/locales/es/messages.po+++ b/packages/app/src/locales/es/messages.po@@ -4729,12 +4729,10 @@ msgstr "Desconectando"#: src/components/BranchRecycleBanner.tsx#: src/components/BugReportSendToast.tsx-#: src/components/ClaudeReadinessBanner.tsx#: src/components/NavigatorApp.tsx#: src/components/OnboardingCard.tsx#: src/components/settings/SharingSection.tsx-#: src/components/TerminalCliMissingBanner.tsx-#: src/components/TerminalCliUnverifiedBanner.tsx+#: src/components/TerminalNoticeBanner.tsxmsgid "Dismiss"msgstr "Descartar"@@ -9422,6 +9420,18 @@ msgstr "OpenKnowledge buscó conflictos"msgid "OpenKnowledge checked the project"msgstr "OpenKnowledge revisó el proyecto"+#: src/components/TerminalPanel.tsx+msgid "OpenKnowledge couldn't read terminal.shell in .ok/local/config.yml. Using an available Windows shell instead."+msgstr "OpenKnowledge no pudo leer terminal.shell en .ok/local/config.yml. Se usará un shell de Windows disponible."++#: src/components/TerminalPanel.tsx+msgid "OpenKnowledge couldn't write launch settings under .ok/local/terminal because the folder is not safely contained in this project. Check that it is a real folder inside the project, not a link. Claude will ask you to approve OpenKnowledge."+msgstr "OpenKnowledge no pudo escribir la configuración de inicio en .ok/local/terminal porque la carpeta no está contenida de forma segura en este proyecto. Comprueba que sea una carpeta real dentro del proyecto y no un enlace. Claude te pedirá que apruebes OpenKnowledge."++#: src/components/TerminalPanel.tsx+msgid "OpenKnowledge couldn't write launch settings under .ok/local/terminal this time. Check that the folder is writable. Claude will ask you to approve OpenKnowledge."+msgstr "OpenKnowledge no pudo escribir la configuración de inicio en .ok/local/terminal esta vez. Comprueba que se pueda escribir en la carpeta. Claude te pedirá que apruebes OpenKnowledge."+#: src/lib/acp/tool-call-display.tsmsgid "OpenKnowledge created a share link"msgstr "OpenKnowledge creó un enlace para compartir"@@ -12342,6 +12352,10 @@ msgstr "Slidev tardó demasiado en iniciarse. Inténtalo de nuevo."msgid "Small section heading."msgstr "Encabezado de sección pequeño."+#: src/components/TerminalPanel.tsx+msgid "Some dropped files could not be inserted safely."+msgstr "Algunos archivos soltados no se pudieron insertar de forma segura."+#: src/components/SyncStatusBadge.tsxmsgid "Some files are not listed — the working tree has too many changes."msgstr "Algunos archivos no aparecen: el árbol de trabajo tiene demasiados cambios."@@ -13003,6 +13017,18 @@ msgstr "Los ajustes de la terminal aún no se han cargado; inténtalo de nuevo emsgid "Terminal settings not yet loaded — try again in a moment"msgstr "Los ajustes de la terminal aún no se han cargado; inténtalo de nuevo en un momento"+#: src/components/TerminalPanel.tsx+msgid "terminal.shell in .ok/local/config.yml must be a string. Using an available Windows shell instead."+msgstr "terminal.shell en .ok/local/config.yml debe ser una cadena. Se usará un shell de Windows disponible."++#: src/components/TerminalPanel.tsx+msgid "terminal.shell in .ok/local/config.yml must be an absolute Windows path. Using an available Windows shell instead."+msgstr "terminal.shell en .ok/local/config.yml debe ser una ruta absoluta de Windows. Se usará un shell de Windows disponible."++#: src/components/TerminalPanel.tsx+msgid "terminal.shell in .ok/local/config.yml supports PowerShell, cmd.exe, or Git Bash for OpenKnowledge-managed launches and dropped-file paths. This shell opens a plain terminal only; agent and command launches do not run in it."+msgstr "terminal.shell en .ok/local/config.yml admite PowerShell, cmd.exe o Git Bash para los inicios administrados por OpenKnowledge y las rutas de archivos soltados. Este shell solo abre un terminal normal; los inicios de agentes y comandos no se ejecutan en él."+#: src/components/settings/SearchSection.tsxmsgid "Test connection"msgstr "Probar conexión"@@ -13203,6 +13229,10 @@ msgstr "La vista previa bloquea los recursos que no cumplen sus reglas de segurimsgid "The project's server is on a different branch than this window — content can't load."msgstr "El servidor de este proyecto está en una rama distinta a la de esta ventana: el contenido no se puede cargar."+#: src/components/TerminalPanel.tsx+msgid "The prompt was pasted but not submitted automatically. Review it, then press Enter to send it."+msgstr "El prompt se pegó, pero no se envió automáticamente. Revísalo y pulsa Enter para enviarlo."+#: src/components/PropertyPanel.tsxmsgid "The properties block at the top of this doc has a formatting error. Switch to source mode to fix it."msgstr "El bloque de propiedades del principio de este documento tiene un error de formato. Cambia al modo código para arreglarlo."@@ -13315,6 +13345,10 @@ msgstr "La sesión de terminal terminó."msgid "The terminal stopped unexpectedly."msgstr "La terminal se detuvo de forma inesperada."+#: src/components/TerminalPanel.tsx+msgid "The terminal.shell executable in .ok/local/config.yml was not found. Using an available Windows shell instead."+msgstr "No se encontró el ejecutable terminal.shell de .ok/local/config.yml. Se usará un shell de Windows disponible."+#: src/components/AuthModal.tsxmsgid "The token needs the repo and read:user scopes."msgstr "El token necesita los ámbitos repo y read:user."diff --git a/packages/app/src/locales/fr/messages.json b/packages/app/src/locales/fr/messages.jsonindex 4aec38c3c..e4c9c310b 100644--- a/packages/app/src/locales/fr/messages.json+++ b/packages/app/src/locales/fr/messages.json@@ -104,6 +104,9 @@"0NkNB5": ["il y a ", ["0"], " mois"],"0QVrvp": ["Nombre maximal d'agents déjà en cours d'exécution"],"0TnCvC": ["Renommer ", ["0"]],+ "0WsUA2": [+ "Le prompt a été collé, mais pas envoyé automatiquement. Vérifiez-le, puis appuyez sur Entrée pour l’envoyer."+ ],"0YUS3Q": ["Sous-dossier du dossier actuel"],"0_J12R": ["Nouveau fichier à partir du modèle « ",@@ -139,6 +142,9 @@"0pZmTP": ["Impossible de partager ce chemin."],"0qyKG6": ["Synchronisé depuis le disque"],"0r6d6v": ["Modifications enregistrées automatiquement."],+ "0rT21w": [+ "terminal.shell dans .ok/local/config.yml prend en charge PowerShell, cmd.exe ou Git Bash pour les lancements gérés par OpenKnowledge et les chemins des fichiers déposés. Ce shell ouvre uniquement un terminal simple ; les lancements d’agents et de commandes ne s’y exécutent pas."+ ],"0rwwOn": ["Par étiquette"],"0s8-e8": ["Sélectionnez, entrez dans ou quittez les composants de bloc et les blocs source de repli depuis les limites clavier."@@ -587,6 +593,9 @@"67f-3g": ["Duplication réussie, mais la barre latérale n'est peut-être pas à jour — actualisez pour resynchroniser"],+ "69E1Pq": [+ "terminal.shell dans .ok/local/config.yml doit être une chaîne. Un shell Windows disponible sera utilisé à la place."+ ],"69KLIV": ["Échap"],"6ASTuj": ["Les commandes s'exécutent avec tous les droits de votre compte utilisateur sur cette machine. Désactivez ceci pour désactiver le shell."@@ -979,6 +988,9 @@]],"ALhMYW": ["Terminal"],+ "AN-UPd": [+ "terminal.shell dans .ok/local/config.yml doit être un chemin Windows absolu. Un shell Windows disponible sera utilisé à la place."+ ],"ANFxWn": ["Impossible de supprimer ce thème. Actualisez la page et réessayez."],"APNlbk": ["quitter ", ["0"]],"AQ-Lfg": ["Impossible de charger les modèles"],@@ -1025,6 +1037,7 @@"AqnqMJ": ["Clé API définie"],"AsqRE_": ["Emplacement par défaut des nouvelles pièces jointes"],"AtBdnD": ["Impossible de supprimer la compétence : ", ["error"]],+ "AvqEDl": ["Certains fichiers déposés n’ont pas pu être insérés en toute sécurité."],"AwLCZA": ["Le point de terminaison a répondu, mais pas avec une réponse d'embeddings compatible OpenAI. Vérifiez l'URL de base."],@@ -1208,6 +1221,9 @@"D12vtS": ["(détaché)"],"D2emTw": ["Une erreur s'est produite lors de l'envoi de votre retour. Veuillez réessayer."],"D4H2N6": ["Retirer ", ["tag"]],+ "D7gKrd": [+ "OpenKnowledge n’a pas pu écrire les paramètres de lancement dans .ok/local/terminal, car le dossier n’est pas contenu de manière sûre dans ce projet. Vérifiez qu’il s’agit d’un vrai dossier du projet, et non d’un lien. Claude vous demandera d’approuver OpenKnowledge."+ ],"D7hnvB": ["Réflexion…"],"D8JJwQ": ["Le retour d'expérience n'est pas disponible pour le moment. Veuillez réessayer plus tard."@@ -1841,6 +1857,9 @@"K6jxcj": ["Ajouter une clé"],"K7NMEc": [["uploadFolderName"], " — ", ["0"], " fichiers"],"K8-WWn": ["Se déplacer entre les cellules du tableau"],+ "K8EvAV": [+ "OpenKnowledge n’a pas pu lire terminal.shell dans .ok/local/config.yml. Un shell Windows disponible sera utilisé à la place."+ ],"K9J00P": ["Échec du clonage — erreur de connexion"],"KDrbNG": ["OpenKnowledge a consulté les liens de ", ["subject"]],"KDuPiY": ["Envoi de ", ["fileName"]],@@ -1856,6 +1875,9 @@"KOZud0": ["Construis une base de connaissances d'étude concurrentielle. Commence par une page de synthèse, puis ajoute des pages liées entre elles pour chaque concurrent, leurs produits et leurs tarifs, ainsi que les sources derrière chaque affirmation."],+ "KOeFXa": [+ "OpenKnowledge n’a pas pu écrire les paramètres de lancement dans .ok/local/terminal cette fois-ci. Vérifiez que le dossier est accessible en écriture. Claude vous demandera d’approuver OpenKnowledge."+ ],"KPW5WC": ["modèle déplacé"],"KQGZuq": ["Réutilisé s'il existe déjà, créé sinon."],"KRJ6xh": ["Pas encore d'étiquettes. Continuez à saisir pour en créer une."],@@ -4302,6 +4324,9 @@"kEiVv6": ["Elles apprennent à vos outils IA à travailler avec OpenKnowledge. En installer une l'ajoute à tous les outils IA de cette machine."],+ "kF2Yua": [+ "L’exécutable terminal.shell indiqué dans .ok/local/config.yml est introuvable. Un shell Windows disponible sera utilisé à la place."+ ],"kFLlsI": ["Insère une référence de note de bas de page et l'ébauche de définition correspondante."],diff --git a/packages/app/src/locales/fr/messages.po b/packages/app/src/locales/fr/messages.poindex 3829c6229..1f82f0366 100644--- a/packages/app/src/locales/fr/messages.po+++ b/packages/app/src/locales/fr/messages.po@@ -4729,12 +4729,10 @@ msgstr "Déconnexion"#: src/components/BranchRecycleBanner.tsx#: src/components/BugReportSendToast.tsx-#: src/components/ClaudeReadinessBanner.tsx#: src/components/NavigatorApp.tsx#: src/components/OnboardingCard.tsx#: src/components/settings/SharingSection.tsx-#: src/components/TerminalCliMissingBanner.tsx-#: src/components/TerminalCliUnverifiedBanner.tsx+#: src/components/TerminalNoticeBanner.tsxmsgid "Dismiss"msgstr "Ignorer"@@ -9422,6 +9420,18 @@ msgstr "OpenKnowledge a recherché des conflits"msgid "OpenKnowledge checked the project"msgstr "OpenKnowledge a vérifié le projet"+#: src/components/TerminalPanel.tsx+msgid "OpenKnowledge couldn't read terminal.shell in .ok/local/config.yml. Using an available Windows shell instead."+msgstr "OpenKnowledge n’a pas pu lire terminal.shell dans .ok/local/config.yml. Un shell Windows disponible sera utilisé à la place."++#: src/components/TerminalPanel.tsx+msgid "OpenKnowledge couldn't write launch settings under .ok/local/terminal because the folder is not safely contained in this project. Check that it is a real folder inside the project, not a link. Claude will ask you to approve OpenKnowledge."+msgstr "OpenKnowledge n’a pas pu écrire les paramètres de lancement dans .ok/local/terminal, car le dossier n’est pas contenu de manière sûre dans ce projet. Vérifiez qu’il s’agit d’un vrai dossier du projet, et non d’un lien. Claude vous demandera d’approuver OpenKnowledge."++#: src/components/TerminalPanel.tsx+msgid "OpenKnowledge couldn't write launch settings under .ok/local/terminal this time. Check that the folder is writable. Claude will ask you to approve OpenKnowledge."+msgstr "OpenKnowledge n’a pas pu écrire les paramètres de lancement dans .ok/local/terminal cette fois-ci. Vérifiez que le dossier est accessible en écriture. Claude vous demandera d’approuver OpenKnowledge."+#: src/lib/acp/tool-call-display.tsmsgid "OpenKnowledge created a share link"msgstr "OpenKnowledge a créé un lien de partage"@@ -12342,6 +12352,10 @@ msgstr "Slidev a mis trop de temps à démarrer. Réessayez."msgid "Small section heading."msgstr "Petit titre de section."+#: src/components/TerminalPanel.tsx+msgid "Some dropped files could not be inserted safely."+msgstr "Certains fichiers déposés n’ont pas pu être insérés en toute sécurité."+#: src/components/SyncStatusBadge.tsxmsgid "Some files are not listed — the working tree has too many changes."msgstr "Certains fichiers ne sont pas listés : l'arbre de travail contient trop de modifications."@@ -13003,6 +13017,18 @@ msgstr "Les paramètres du terminal ne sont pas encore chargés — réessayez dmsgid "Terminal settings not yet loaded — try again in a moment"msgstr "Les paramètres du terminal ne sont pas encore chargés — réessayez dans un instant"+#: src/components/TerminalPanel.tsx+msgid "terminal.shell in .ok/local/config.yml must be a string. Using an available Windows shell instead."+msgstr "terminal.shell dans .ok/local/config.yml doit être une chaîne. Un shell Windows disponible sera utilisé à la place."++#: src/components/TerminalPanel.tsx+msgid "terminal.shell in .ok/local/config.yml must be an absolute Windows path. Using an available Windows shell instead."+msgstr "terminal.shell dans .ok/local/config.yml doit être un chemin Windows absolu. Un shell Windows disponible sera utilisé à la place."++#: src/components/TerminalPanel.tsx+msgid "terminal.shell in .ok/local/config.yml supports PowerShell, cmd.exe, or Git Bash for OpenKnowledge-managed launches and dropped-file paths. This shell opens a plain terminal only; agent and command launches do not run in it."+msgstr "terminal.shell dans .ok/local/config.yml prend en charge PowerShell, cmd.exe ou Git Bash pour les lancements gérés par OpenKnowledge et les chemins des fichiers déposés. Ce shell ouvre uniquement un terminal simple ; les lancements d’agents et de commandes ne s’y exécutent pas."+#: src/components/settings/SearchSection.tsxmsgid "Test connection"msgstr "Tester la connexion"@@ -13203,6 +13229,10 @@ msgstr "L'aperçu bloque les ressources qui ne respectent pas ses règles de sémsgid "The project's server is on a different branch than this window — content can't load."msgstr "Le serveur de ce projet est sur une branche différente de cette fenêtre — le contenu ne peut pas se charger."+#: src/components/TerminalPanel.tsx+msgid "The prompt was pasted but not submitted automatically. Review it, then press Enter to send it."+msgstr "Le prompt a été collé, mais pas envoyé automatiquement. Vérifiez-le, puis appuyez sur Entrée pour l’envoyer."+#: src/components/PropertyPanel.tsxmsgid "The properties block at the top of this doc has a formatting error. Switch to source mode to fix it."msgstr "Le bloc de propriétés en haut de ce document contient une erreur de mise en forme. Passez en mode source pour la corriger."@@ -13315,6 +13345,10 @@ msgstr "La session de terminal s'est terminée."msgid "The terminal stopped unexpectedly."msgstr "Le terminal s'est arrêté de façon inattendue."+#: src/components/TerminalPanel.tsx+msgid "The terminal.shell executable in .ok/local/config.yml was not found. Using an available Windows shell instead."+msgstr "L’exécutable terminal.shell indiqué dans .ok/local/config.yml est introuvable. Un shell Windows disponible sera utilisé à la place."+#: src/components/AuthModal.tsxmsgid "The token needs the repo and read:user scopes."msgstr "Le jeton doit avoir les portées repo et read:user."diff --git a/packages/app/src/locales/hi/messages.json b/packages/app/src/locales/hi/messages.jsonindex 3162fc5b7..57dc3b167 100644--- a/packages/app/src/locales/hi/messages.json+++ b/packages/app/src/locales/hi/messages.json@@ -86,6 +86,9 @@"0NkNB5": [["0"], " माह पहले"],"0QVrvp": ["अधिकतम एजेंट पहले से चल रहे हैं"],"0TnCvC": [["0"], " का नाम बदलें"],+ "0WsUA2": [+ "प्रॉम्प्ट पेस्ट किया गया, लेकिन अपने आप सबमिट नहीं हुआ। इसकी समीक्षा करें, फिर भेजने के लिए Enter दबाएँ।"+ ],"0YUS3Q": ["मौजूदा फ़ोल्डर के अंतर्गत उप-फ़ोल्डर"],"0_J12R": [["targetLabel"],@@ -119,6 +122,9 @@"0pZmTP": ["यह पथ साझा नहीं किया जा सकता।"],"0qyKG6": ["डिस्क से सिंक किया गया"],"0r6d6v": ["बदलाव अपने आप सहेज दिए गए।"],+ "0rT21w": [+ ".ok/local/config.yml में terminal.shell, OpenKnowledge द्वारा प्रबंधित लॉन्च और ड्रॉप की गई फ़ाइलों के पाथ के लिए PowerShell, cmd.exe या Git Bash का समर्थन करता है। यह शेल केवल एक सामान्य टर्मिनल खोलता है; एजेंट और कमांड लॉन्च इसमें नहीं चलते।"+ ],"0rwwOn": ["टैग के अनुसार"],"0s8-e8": ["कीबोर्ड सीमाओं से ब्लॉक कंपोनेंट और फ़ॉलबैक स्रोत ब्लॉक चुनें, उनमें जाएँ, या उनसे बाहर आएँ।"],"0t0bbC": ["सिंक वरीयता नहीं सहेजी जा सकी: ", ["detail"]],@@ -478,6 +484,9 @@],"67Dpmh": ["स्लैश कमांड सुझाव"],"67f-3g": ["नकल बन गई पर साइडबार पुराना हो सकता है — फिर से सिंक करने के लिए ताज़ा करें"],+ "69E1Pq": [+ ".ok/local/config.yml में terminal.shell एक स्ट्रिंग होना चाहिए। इसके बजाय उपलब्ध Windows शेल का उपयोग किया जा रहा है।"+ ],"69KLIV": ["Escape"],"6ASTuj": ["कमांड इस मशीन पर आपके उपयोगकर्ता खाते की पूरी पहुँच के साथ चलते हैं। शेल बंद करने के लिए इसे बंद करें।"@@ -790,6 +799,9 @@"AJ7_B2": ["नई थीम बनाएँ"],"AKxFtn": [["openedWorktreeCount", "plural", { "one": ["वर्कट्री"], "other": ["वर्कट्री"] }]],"ALhMYW": ["टर्मिनल"],+ "AN-UPd": [+ ".ok/local/config.yml में terminal.shell एक निरपेक्ष Windows पथ होना चाहिए। इसके बजाय उपलब्ध Windows शेल का उपयोग किया जा रहा है।"+ ],"ANFxWn": ["यह थीम नहीं हटाई जा सकी। रीफ़्रेश करके फिर से कोशिश करें।"],"APNlbk": ["निकास ", ["0"]],"AQ-Lfg": ["टेम्पलेट लोड नहीं हो सके"],@@ -832,6 +844,7 @@"AqnqMJ": ["API कुंजी सेट है"],"AsqRE_": ["नए संलग्नकों का डिफ़ॉल्ट स्थान"],"AtBdnD": ["स्किल नहीं हटाई जा सकी: ", ["error"]],+ "AvqEDl": ["छोड़ी गई कुछ फ़ाइलों को सुरक्षित रूप से सम्मिलित नहीं किया जा सका।"],"AwLCZA": ["एंडपॉइंट ने उत्तर तो दिया, पर वह OpenAI-संगत एम्बेडिंग प्रतिक्रिया नहीं थी। आधार URL जाँचें।"],"AwrGuz": ["इस दस्तावेज़ में आवश्यक प्रॉपर्टी अनुपस्थित हैं"],"AyKwqp": ["आपके होम फ़ोल्डर में — इस मशीन के हर प्रोजेक्ट में, सिर्फ़ आपके लिए।"],@@ -977,6 +990,9 @@"D12vtS": ["(अलग किया हुआ)"],"D2emTw": ["आपकी प्रतिक्रिया भेजते समय कुछ ग़लत हो गया। कृपया फिर कोशिश करें।"],"D4H2N6": [["tag"], " हटाएँ"],+ "D7gKrd": [+ "OpenKnowledge .ok/local/terminal में लॉन्च सेटिंग्स नहीं लिख सका, क्योंकि फ़ोल्डर इस प्रोजेक्ट के अंदर सुरक्षित रूप से मौजूद नहीं है। जाँचें कि यह प्रोजेक्ट के अंदर एक वास्तविक फ़ोल्डर है, लिंक नहीं। Claude आपसे OpenKnowledge को मंज़ूरी देने के लिए कहेगा।"+ ],"D7hnvB": ["विचार किया जा रहा है…"],"D8JJwQ": ["प्रतिक्रिया अभी उपलब्ध नहीं है। कृपया बाद में फिर कोशिश करें।"],"D8OV7J": ["केवल सहयोगी"],@@ -1505,6 +1521,9 @@"K6jxcj": ["एक कुंजी जोड़ें"],"K7NMEc": [["uploadFolderName"], " — ", ["0"], " फ़ाइलें"],"K8-WWn": ["तालिका की कोशिकाओं के बीच जाएँ"],+ "K8EvAV": [+ "OpenKnowledge .ok/local/config.yml में terminal.shell नहीं पढ़ सका। इसके बजाय उपलब्ध Windows शेल का उपयोग किया जा रहा है।"+ ],"K9J00P": ["क्लोन विफल — कनेक्शन त्रुटि"],"KDrbNG": ["OpenKnowledge ने ", ["subject"], " के लिंक खोजे"],"KDuPiY": [["fileName"], " अपलोड की जा रही है"],@@ -1520,6 +1539,9 @@"KOZud0": ["प्रतिस्पर्धी शोध का एक ज्ञान आधार बनाएँ। एक सिंहावलोकन पेज से शुरू करें, फिर हर प्रतिस्पर्धी, उनके उत्पादों और मूल्य-निर्धारण, और हर दावे के पीछे के स्रोतों के लिए आपस में जुड़े पेज जोड़ें।"],+ "KOeFXa": [+ "OpenKnowledge इस बार .ok/local/terminal में लॉन्च सेटिंग्स नहीं लिख सका। जाँचें कि फ़ोल्डर में लिखा जा सकता है। Claude आपसे OpenKnowledge को मंज़ूरी देने के लिए कहेगा।"+ ],"KPW5WC": ["टेम्पलेट हिलाया गया"],"KQGZuq": ["यदि पहले से मौजूद है तो पुन: उपयोग किया जाता है, वरना बना दिया जाता है।"],"KRJ6xh": ["अभी कोई टैग नहीं। एक बनाने के लिए लिखते रहें।"],@@ -3570,6 +3592,9 @@"kEiVv6": ["ये आपके AI टूल को OpenKnowledge के साथ काम करना सिखाती हैं। किसी एक को इंस्टॉल करने पर वह इस मशीन के हर AI टूल में जुड़ जाती है।"],+ "kF2Yua": [+ ".ok/local/config.yml में terminal.shell एक्ज़ीक्यूटेबल नहीं मिला। इसके बजाय उपलब्ध Windows शेल का उपयोग किया जा रहा है।"+ ],"kFLlsI": ["एक फ़ुटनोट संदर्भ + उससे मेल खाती परिभाषा का ढाँचा डालें।"],"kGp168": ["इस प्रोजेक्ट को प्रकाशन के लिए तैयार नहीं किया जा सका।"],"kI5pWt": ["छवि नहीं मिली: ", ["errorLabel"]],diff --git a/packages/app/src/locales/hi/messages.po b/packages/app/src/locales/hi/messages.poindex 2d7f8bf18..d8be162e4 100644--- a/packages/app/src/locales/hi/messages.po+++ b/packages/app/src/locales/hi/messages.po@@ -4725,12 +4725,10 @@ msgstr "कनेक्शन तोड़ा जा रहा है"#: src/components/BranchRecycleBanner.tsx#: src/components/BugReportSendToast.tsx-#: src/components/ClaudeReadinessBanner.tsx#: src/components/NavigatorApp.tsx#: src/components/OnboardingCard.tsx#: src/components/settings/SharingSection.tsx-#: src/components/TerminalCliMissingBanner.tsx-#: src/components/TerminalCliUnverifiedBanner.tsx+#: src/components/TerminalNoticeBanner.tsxmsgid "Dismiss"msgstr "ख़ारिज करें"@@ -9418,6 +9416,18 @@ msgstr "OpenKnowledge ने विरोधों की जाँच की"msgid "OpenKnowledge checked the project"msgstr "OpenKnowledge ने प्रोजेक्ट की जाँच की"+#: src/components/TerminalPanel.tsx+msgid "OpenKnowledge couldn't read terminal.shell in .ok/local/config.yml. Using an available Windows shell instead."+msgstr "OpenKnowledge .ok/local/config.yml में terminal.shell नहीं पढ़ सका। इसके बजाय उपलब्ध Windows शेल का उपयोग किया जा रहा है।"++#: src/components/TerminalPanel.tsx+msgid "OpenKnowledge couldn't write launch settings under .ok/local/terminal because the folder is not safely contained in this project. Check that it is a real folder inside the project, not a link. Claude will ask you to approve OpenKnowledge."+msgstr "OpenKnowledge .ok/local/terminal में लॉन्च सेटिंग्स नहीं लिख सका, क्योंकि फ़ोल्डर इस प्रोजेक्ट के अंदर सुरक्षित रूप से मौजूद नहीं है। जाँचें कि यह प्रोजेक्ट के अंदर एक वास्तविक फ़ोल्डर है, लिंक नहीं। Claude आपसे OpenKnowledge को मंज़ूरी देने के लिए कहेगा।"++#: src/components/TerminalPanel.tsx+msgid "OpenKnowledge couldn't write launch settings under .ok/local/terminal this time. Check that the folder is writable. Claude will ask you to approve OpenKnowledge."+msgstr "OpenKnowledge इस बार .ok/local/terminal में लॉन्च सेटिंग्स नहीं लिख सका। जाँचें कि फ़ोल्डर में लिखा जा सकता है। Claude आपसे OpenKnowledge को मंज़ूरी देने के लिए कहेगा।"+#: src/lib/acp/tool-call-display.tsmsgid "OpenKnowledge created a share link"msgstr "OpenKnowledge ने साझा लिंक बनाया"@@ -12338,6 +12348,10 @@ msgstr "Slidev शुरू होने में बहुत समय लगmsgid "Small section heading."msgstr "छोटा अनुभाग शीर्षक।"+#: src/components/TerminalPanel.tsx+msgid "Some dropped files could not be inserted safely."+msgstr "छोड़ी गई कुछ फ़ाइलों को सुरक्षित रूप से सम्मिलित नहीं किया जा सका।"+#: src/components/SyncStatusBadge.tsxmsgid "Some files are not listed — the working tree has too many changes."msgstr "कुछ फ़ाइलें सूचीबद्ध नहीं हैं: वर्किंग ट्री में बहुत अधिक बदलाव हैं।"@@ -12999,6 +13013,18 @@ msgstr "टर्मिनल सेटिंग अभी लोड नहीmsgid "Terminal settings not yet loaded — try again in a moment"msgstr "टर्मिनल सेटिंग अभी लोड नहीं हुईं — कुछ देर बाद फिर कोशिश करें"+#: src/components/TerminalPanel.tsx+msgid "terminal.shell in .ok/local/config.yml must be a string. Using an available Windows shell instead."+msgstr ".ok/local/config.yml में terminal.shell एक स्ट्रिंग होना चाहिए। इसके बजाय उपलब्ध Windows शेल का उपयोग किया जा रहा है।"++#: src/components/TerminalPanel.tsx+msgid "terminal.shell in .ok/local/config.yml must be an absolute Windows path. Using an available Windows shell instead."+msgstr ".ok/local/config.yml में terminal.shell एक निरपेक्ष Windows पथ होना चाहिए। इसके बजाय उपलब्ध Windows शेल का उपयोग किया जा रहा है।"++#: src/components/TerminalPanel.tsx+msgid "terminal.shell in .ok/local/config.yml supports PowerShell, cmd.exe, or Git Bash for OpenKnowledge-managed launches and dropped-file paths. This shell opens a plain terminal only; agent and command launches do not run in it."+msgstr ".ok/local/config.yml में terminal.shell, OpenKnowledge द्वारा प्रबंधित लॉन्च और ड्रॉप की गई फ़ाइलों के पाथ के लिए PowerShell, cmd.exe या Git Bash का समर्थन करता है। यह शेल केवल एक सामान्य टर्मिनल खोलता है; एजेंट और कमांड लॉन्च इसमें नहीं चलते।"+#: src/components/settings/SearchSection.tsxmsgid "Test connection"msgstr "कनेक्शन जाँचें"@@ -13199,6 +13225,10 @@ msgstr "पूर्वावलोकन उन संसाधनों कोmsgid "The project's server is on a different branch than this window — content can't load."msgstr "इस प्रोजेक्ट का सर्वर इस विंडो से अलग ब्रांच पर है — सामग्री लोड नहीं हो सकती।"+#: src/components/TerminalPanel.tsx+msgid "The prompt was pasted but not submitted automatically. Review it, then press Enter to send it."+msgstr "प्रॉम्प्ट पेस्ट किया गया, लेकिन अपने आप सबमिट नहीं हुआ। इसकी समीक्षा करें, फिर भेजने के लिए Enter दबाएँ।"+#: src/components/PropertyPanel.tsxmsgid "The properties block at the top of this doc has a formatting error. Switch to source mode to fix it."msgstr "इस दस्तावेज़ के ऊपर मौजूद प्रॉपर्टी ब्लॉक में एक फ़ॉर्मैटिंग त्रुटि है। इसे ठीक करने के लिए स्रोत मोड पर जाएँ।"@@ -13311,6 +13341,10 @@ msgstr "टर्मिनल सत्र समाप्त हो गयाmsgid "The terminal stopped unexpectedly."msgstr "टर्मिनल अप्रत्याशित रूप से रुक गया।"+#: src/components/TerminalPanel.tsx+msgid "The terminal.shell executable in .ok/local/config.yml was not found. Using an available Windows shell instead."+msgstr ".ok/local/config.yml में terminal.shell एक्ज़ीक्यूटेबल नहीं मिला। इसके बजाय उपलब्ध Windows शेल का उपयोग किया जा रहा है।"+#: src/components/AuthModal.tsxmsgid "The token needs the repo and read:user scopes."msgstr "टोकन को repo और read:user स्कोप चाहिए।"diff --git a/packages/app/src/locales/id/messages.json b/packages/app/src/locales/id/messages.jsonindex dd3cfdefb..15b714e60 100644--- a/packages/app/src/locales/id/messages.json+++ b/packages/app/src/locales/id/messages.json@@ -86,6 +86,9 @@"0NkNB5": [["0"], " bln lalu"],"0QVrvp": ["Jumlah agen yang berjalan sudah maksimal"],"0TnCvC": ["Ganti nama ", ["0"]],+ "0WsUA2": [+ "Prompt telah ditempel, tetapi tidak dikirim secara otomatis. Tinjau prompt tersebut, lalu tekan Enter untuk mengirimnya."+ ],"0YUS3Q": ["Subfolder di bawah folder saat ini"],"0_J12R": ["Berkas baru dari templat \"",@@ -119,6 +122,9 @@"0pZmTP": ["Tidak dapat membagikan jalur ini."],"0qyKG6": ["Tersinkron dari disk"],"0r6d6v": ["Perubahan disimpan otomatis."],+ "0rT21w": [+ "terminal.shell di .ok/local/config.yml mendukung PowerShell, cmd.exe, atau Git Bash untuk peluncuran yang dikelola OpenKnowledge dan jalur file yang diletakkan. Shell ini hanya membuka terminal biasa; peluncuran agen dan perintah tidak berjalan di dalamnya."+ ],"0rwwOn": ["Berdasarkan tag"],"0s8-e8": ["Memilih, masuk, atau keluar dari komponen blok dan blok sumber cadangan dari batas papan ketik."@@ -499,6 +505,9 @@"67f-3g": ["Penggandaan berhasil tetapi bilah sisi mungkin tidak mutakhir — segarkan untuk menyinkronkan ulang"],+ "69E1Pq": [+ "terminal.shell di .ok/local/config.yml harus berupa string. Shell Windows yang tersedia akan digunakan sebagai gantinya."+ ],"69KLIV": ["Escape"],"6ASTuj": ["Perintah berjalan dengan akses penuh akun pengguna Anda di mesin ini. Matikan ini untuk menonaktifkan shell."@@ -813,6 +822,9 @@"AJ7_B2": ["Buat tema baru"],"AKxFtn": [["openedWorktreeCount", "plural", { "other": ["worktree"] }]],"ALhMYW": ["Terminal"],+ "AN-UPd": [+ "terminal.shell di .ok/local/config.yml harus berupa jalur Windows absolut. Shell Windows yang tersedia akan digunakan sebagai gantinya."+ ],"ANFxWn": ["Tema ini tidak dapat dihapus. Muat ulang lalu coba lagi."],"APNlbk": ["keluar ", ["0"]],"AQ-Lfg": ["Templat tidak bisa dimuat"],@@ -855,6 +867,7 @@"AqnqMJ": ["Kunci API disetel"],"AsqRE_": ["Lokasi bawaan untuk lampiran baru"],"AtBdnD": ["Keterampilan tidak bisa dihapus: ", ["error"]],+ "AvqEDl": ["Beberapa file yang dilepas tidak dapat disisipkan dengan aman."],"AwLCZA": ["Endpoint-nya menjawab, tetapi bukan dengan respons embedding yang kompatibel dengan OpenAI. Periksa URL dasarnya."],@@ -992,6 +1005,9 @@"D12vtS": ["(terlepas)"],"D2emTw": ["Ada yang tidak beres saat mengirim masukan Anda. Silakan coba lagi."],"D4H2N6": ["Hapus ", ["tag"]],+ "D7gKrd": [+ "OpenKnowledge tidak dapat menulis pengaturan peluncuran di .ok/local/terminal karena folder tersebut tidak berada dengan aman di dalam proyek ini. Pastikan folder tersebut adalah folder nyata di dalam proyek, bukan tautan. Claude akan meminta Anda menyetujui OpenKnowledge."+ ],"D7hnvB": ["Menimbang…"],"D8JJwQ": ["Masukan tidak tersedia saat ini. Silakan coba lagi nanti."],"D8OV7J": ["Hanya kolaborator"],@@ -1564,6 +1580,9 @@"K6jxcj": ["Tambahkan kunci"],"K7NMEc": [["uploadFolderName"], " — ", ["0"], " berkas"],"K8-WWn": ["Berpindah antarsel tabel"],+ "K8EvAV": [+ "OpenKnowledge tidak dapat membaca terminal.shell di .ok/local/config.yml. Shell Windows yang tersedia akan digunakan sebagai gantinya."+ ],"K9J00P": ["Kloning gagal — galat koneksi"],"KDrbNG": ["OpenKnowledge mencari tautan untuk ", ["subject"]],"KDuPiY": ["Mengunggah ", ["fileName"]],@@ -1579,6 +1598,9 @@"KOZud0": ["Bangun basis pengetahuan riset pesaing. Mulai dengan halaman ikhtisar, lalu tambahkan halaman yang saling tertaut untuk tiap pesaing, produk dan harganya, serta sumber di balik setiap klaim."],+ "KOeFXa": [+ "OpenKnowledge tidak dapat menulis pengaturan peluncuran di .ok/local/terminal kali ini. Pastikan folder tersebut dapat ditulisi. Claude akan meminta Anda menyetujui OpenKnowledge."+ ],"KPW5WC": ["templat dipindahkan"],"KQGZuq": ["Dipakai ulang jika sudah ada, dibuat jika belum."],"KRJ6xh": ["Belum ada tag. Lanjutkan mengetik untuk membuat satu."],@@ -3713,6 +3735,9 @@"kEiVv6": ["Keterampilan ini mengajarkan alat AI Anda cara bekerja dengan OpenKnowledge. Memasang satu akan menambahkannya ke setiap alat AI di mesin ini."],+ "kF2Yua": [+ "Executable terminal.shell di .ok/local/config.yml tidak ditemukan. Shell Windows yang tersedia akan digunakan sebagai gantinya."+ ],"kFLlsI": ["Menyisipkan rujukan catatan kaki + kerangka definisi yang sesuai."],"kGp168": ["Tidak dapat menyiapkan proyek ini untuk diterbitkan."],"kI5pWt": ["Gambar tidak ditemukan: ", ["errorLabel"]],diff --git a/packages/app/src/locales/id/messages.po b/packages/app/src/locales/id/messages.poindex 41596914a..d764c5a6a 100644--- a/packages/app/src/locales/id/messages.po+++ b/packages/app/src/locales/id/messages.po@@ -4725,12 +4725,10 @@ msgstr "Memutus koneksi"#: src/components/BranchRecycleBanner.tsx#: src/components/BugReportSendToast.tsx-#: src/components/ClaudeReadinessBanner.tsx#: src/components/NavigatorApp.tsx#: src/components/OnboardingCard.tsx#: src/components/settings/SharingSection.tsx-#: src/components/TerminalCliMissingBanner.tsx-#: src/components/TerminalCliUnverifiedBanner.tsx+#: src/components/TerminalNoticeBanner.tsxmsgid "Dismiss"msgstr "Tutup"@@ -9418,6 +9416,18 @@ msgstr "OpenKnowledge memeriksa konflik"msgid "OpenKnowledge checked the project"msgstr "OpenKnowledge memeriksa proyek"+#: src/components/TerminalPanel.tsx+msgid "OpenKnowledge couldn't read terminal.shell in .ok/local/config.yml. Using an available Windows shell instead."+msgstr "OpenKnowledge tidak dapat membaca terminal.shell di .ok/local/config.yml. Shell Windows yang tersedia akan digunakan sebagai gantinya."++#: src/components/TerminalPanel.tsx+msgid "OpenKnowledge couldn't write launch settings under .ok/local/terminal because the folder is not safely contained in this project. Check that it is a real folder inside the project, not a link. Claude will ask you to approve OpenKnowledge."+msgstr "OpenKnowledge tidak dapat menulis pengaturan peluncuran di .ok/local/terminal karena folder tersebut tidak berada dengan aman di dalam proyek ini. Pastikan folder tersebut adalah folder nyata di dalam proyek, bukan tautan. Claude akan meminta Anda menyetujui OpenKnowledge."++#: src/components/TerminalPanel.tsx+msgid "OpenKnowledge couldn't write launch settings under .ok/local/terminal this time. Check that the folder is writable. Claude will ask you to approve OpenKnowledge."+msgstr "OpenKnowledge tidak dapat menulis pengaturan peluncuran di .ok/local/terminal kali ini. Pastikan folder tersebut dapat ditulisi. Claude akan meminta Anda menyetujui OpenKnowledge."+#: src/lib/acp/tool-call-display.tsmsgid "OpenKnowledge created a share link"msgstr "OpenKnowledge membuat tautan berbagi"@@ -12338,6 +12348,10 @@ msgstr "Slidev terlalu lama saat memulai. Coba lagi."msgid "Small section heading."msgstr "Judul bagian kecil."+#: src/components/TerminalPanel.tsx+msgid "Some dropped files could not be inserted safely."+msgstr "Beberapa file yang dilepas tidak dapat disisipkan dengan aman."+#: src/components/SyncStatusBadge.tsxmsgid "Some files are not listed — the working tree has too many changes."msgstr "Sebagian file tidak ditampilkan: working tree memiliki terlalu banyak perubahan."@@ -12999,6 +13013,18 @@ msgstr "Pengaturan terminal belum dimuat — coba lagi sebentar."msgid "Terminal settings not yet loaded — try again in a moment"msgstr "Pengaturan terminal belum dimuat — coba lagi sebentar"+#: src/components/TerminalPanel.tsx+msgid "terminal.shell in .ok/local/config.yml must be a string. Using an available Windows shell instead."+msgstr "terminal.shell di .ok/local/config.yml harus berupa string. Shell Windows yang tersedia akan digunakan sebagai gantinya."++#: src/components/TerminalPanel.tsx+msgid "terminal.shell in .ok/local/config.yml must be an absolute Windows path. Using an available Windows shell instead."+msgstr "terminal.shell di .ok/local/config.yml harus berupa jalur Windows absolut. Shell Windows yang tersedia akan digunakan sebagai gantinya."++#: src/components/TerminalPanel.tsx+msgid "terminal.shell in .ok/local/config.yml supports PowerShell, cmd.exe, or Git Bash for OpenKnowledge-managed launches and dropped-file paths. This shell opens a plain terminal only; agent and command launches do not run in it."+msgstr "terminal.shell di .ok/local/config.yml mendukung PowerShell, cmd.exe, atau Git Bash untuk peluncuran yang dikelola OpenKnowledge dan jalur file yang diletakkan. Shell ini hanya membuka terminal biasa; peluncuran agen dan perintah tidak berjalan di dalamnya."+#: src/components/settings/SearchSection.tsxmsgid "Test connection"msgstr "Uji koneksi"@@ -13199,6 +13225,10 @@ msgstr "Pratinjau memblokir sumber daya yang tidak memenuhi aturan keamanannya (msgid "The project's server is on a different branch than this window — content can't load."msgstr "Server proyek ini berada di branch yang berbeda dari jendela ini — konten tidak dapat dimuat."+#: src/components/TerminalPanel.tsx+msgid "The prompt was pasted but not submitted automatically. Review it, then press Enter to send it."+msgstr "Prompt telah ditempel, tetapi tidak dikirim secara otomatis. Tinjau prompt tersebut, lalu tekan Enter untuk mengirimnya."+#: src/components/PropertyPanel.tsxmsgid "The properties block at the top of this doc has a formatting error. Switch to source mode to fix it."msgstr "Blok properti di bagian atas dokumen ini punya galat format. Beralihlah ke mode sumber untuk memperbaikinya."@@ -13311,6 +13341,10 @@ msgstr "Sesi terminal berakhir."msgid "The terminal stopped unexpectedly."msgstr "Terminal berhenti tak terduga."+#: src/components/TerminalPanel.tsx+msgid "The terminal.shell executable in .ok/local/config.yml was not found. Using an available Windows shell instead."+msgstr "Executable terminal.shell di .ok/local/config.yml tidak ditemukan. Shell Windows yang tersedia akan digunakan sebagai gantinya."+#: src/components/AuthModal.tsxmsgid "The token needs the repo and read:user scopes."msgstr "Token itu memerlukan cakupan repo dan read:user."diff --git a/packages/app/src/locales/ko/messages.json b/packages/app/src/locales/ko/messages.jsonindex caf4c8779..21603eaf0 100644--- a/packages/app/src/locales/ko/messages.json+++ b/packages/app/src/locales/ko/messages.json@@ -80,6 +80,9 @@"0NkNB5": [["0"], "개월 전"],"0QVrvp": ["에이전트 최대 실행 수 도달"],"0TnCvC": [["0"], " 이름 변경"],+ "0WsUA2": [+ "프롬프트를 붙여 넣었지만 자동으로 제출하지 않았습니다. 내용을 검토한 다음 Enter를 눌러 전송하세요."+ ],"0YUS3Q": ["현재 폴더의 하위 폴더"],"0_J12R": ["템플릿 \"",@@ -114,6 +117,9 @@"0pZmTP": ["이 경로는 공유할 수 없습니다."],"0qyKG6": ["디스크에서 동기화됨"],"0r6d6v": ["변경사항이 자동으로 저장되었습니다."],+ "0rT21w": [+ ".ok/local/config.yml의 terminal.shell은 OpenKnowledge 관리 실행 및 드롭된 파일 경로에 PowerShell, cmd.exe 또는 Git Bash를 지원합니다. 이 셸에서는 일반 터미널만 열리며, 에이전트 및 명령 실행은 여기서 작동하지 않습니다."+ ],"0rwwOn": ["태그순"],"0s8-e8": ["블록 경계에서 블록 구성 요소와 대체 소스 블록을 선택, 입력 또는 빠져나갑니다."],"0t0bbC": ["동기화 환경설정을 저장할 수 없습니다: ", ["detail"]],@@ -479,6 +485,9 @@"67f-3g": ["복제는 성공했지만 사이드바가 최신 상태가 아닐 수 있습니다. 다시 동기화하려면 새로 고침하세요."],+ "69E1Pq": [+ ".ok/local/config.yml의 terminal.shell은 문자열이어야 합니다. 대신 사용 가능한 Windows 셸을 사용합니다."+ ],"69KLIV": ["Escape"],"6ASTuj": ["이 컴퓨터에서 사용자 계정의 전체 권한으로 명령을 실행합니다. 셸을 끄려면 이 설정을 끕니다."@@ -786,6 +795,9 @@"AJ7_B2": ["새 테마 만들기"],"AKxFtn": [["openedWorktreeCount", "plural", { "other": ["워크트리"] }]],"ALhMYW": ["터미널"],+ "AN-UPd": [+ ".ok/local/config.yml의 terminal.shell은 Windows 절대 경로여야 합니다. 대신 사용 가능한 Windows 셸을 사용합니다."+ ],"ANFxWn": ["이 테마를 삭제하지 못했습니다. 새로 고친 후 다시 시도합니다."],"APNlbk": ["exit ", ["0"]],"AQ-Lfg": ["템플릿을 불러오지 못했습니다"],@@ -830,6 +842,7 @@"AqnqMJ": ["API 키 설정됨"],"AsqRE_": ["새 첨부 파일의 기본 위치"],"AtBdnD": ["스킬 삭제 실패: ", ["error"]],+ "AvqEDl": ["놓은 파일 중 일부를 안전하게 삽입할 수 없습니다."],"AwLCZA": ["엔드포인트가 응답했지만 OpenAI 호환 임베딩 응답이 아닙니다. 기본 URL을 확인합니다."],@@ -963,6 +976,9 @@"D12vtS": ["(분리됨)"],"D2emTw": ["피드백을 보내는 중 문제가 발생했습니다. 다시 시도하세요."],"D4H2N6": [["tag"], " 제거"],+ "D7gKrd": [+ "폴더가 이 프로젝트 안에 안전하게 포함되어 있지 않아 OpenKnowledge가 .ok/local/terminal 아래에 실행 설정을 쓸 수 없습니다. 프로젝트 내부의 실제 폴더이며 링크가 아닌지 확인하세요. Claude가 OpenKnowledge 승인을 요청합니다."+ ],"D7hnvB": ["숙고 중…"],"D8JJwQ": ["현재 피드백을 사용할 수 없습니다. 나중에 다시 시도하세요."],"D8OV7J": ["공동 작업자만"],@@ -1502,6 +1518,9 @@"K6jxcj": ["키 추가"],"K7NMEc": [["uploadFolderName"], " … 파일 ", ["0"], "개"],"K8-WWn": ["표 셀 사이를 이동합니다."],+ "K8EvAV": [+ "OpenKnowledge가 .ok/local/config.yml의 terminal.shell을 읽을 수 없습니다. 대신 사용 가능한 Windows 셸을 사용합니다."+ ],"K9J00P": ["클론 실패. 연결 오류"],"KDrbNG": ["OpenKnowledge에서 ", ["subject"], " 링크 조회"],"KDuPiY": [["fileName"], " 업로드 중"],@@ -1517,6 +1536,9 @@"KOZud0": ["경쟁사 조사를 위한 지식 베이스를 구축합니다. 개요 페이지로 시작한 다음, 각 경쟁사와 제품 및 가격, 모든 주장에 대한 출처를 서로 연결된 페이지로 추가합니다."],+ "KOeFXa": [+ "이번에는 OpenKnowledge가 .ok/local/terminal 아래에 실행 설정을 쓸 수 없습니다. 폴더에 쓰기 권한이 있는지 확인하세요. Claude가 OpenKnowledge 승인을 요청합니다."+ ],"KPW5WC": ["템플릿 이동됨"],"KQGZuq": ["이미 있으면 재사용하고, 없으면 생성합니다."],"KRJ6xh": ["아직 태그가 없습니다. 계속 입력하여 태그를 만드세요."],@@ -3565,6 +3587,9 @@"kEiVv6": ["이 스킬들은 AI 도구가 OpenKnowledge와 함께 작동하는 방법을 가르칩니다. 하나를 설치하면 이 컴퓨터의 모든 AI 도구에 추가됩니다."],+ "kF2Yua": [+ ".ok/local/config.yml의 terminal.shell 실행 파일을 찾을 수 없습니다. 대신 사용 가능한 Windows 셸을 사용합니다."+ ],"kFLlsI": ["각주 참조와 대응하는 정의 초안을 삽입합니다."],"kGp168": ["이 프로젝트를 게시할 준비를 할 수 없습니다."],"kI5pWt": ["이미지를 찾을 수 없음: ", ["errorLabel"]],diff --git a/packages/app/src/locales/ko/messages.po b/packages/app/src/locales/ko/messages.poindex 1e2b0968a..a491e3221 100644--- a/packages/app/src/locales/ko/messages.po+++ b/packages/app/src/locales/ko/messages.po@@ -4729,12 +4729,10 @@ msgstr "연결 해제 중"#: src/components/BranchRecycleBanner.tsx#: src/components/BugReportSendToast.tsx-#: src/components/ClaudeReadinessBanner.tsx#: src/components/NavigatorApp.tsx#: src/components/OnboardingCard.tsx#: src/components/settings/SharingSection.tsx-#: src/components/TerminalCliMissingBanner.tsx-#: src/components/TerminalCliUnverifiedBanner.tsx+#: src/components/TerminalNoticeBanner.tsxmsgid "Dismiss"msgstr "닫기"@@ -9422,6 +9420,18 @@ msgstr "OpenKnowledge에서 충돌 확인"msgid "OpenKnowledge checked the project"msgstr "OpenKnowledge에서 프로젝트 확인"+#: src/components/TerminalPanel.tsx+msgid "OpenKnowledge couldn't read terminal.shell in .ok/local/config.yml. Using an available Windows shell instead."+msgstr "OpenKnowledge가 .ok/local/config.yml의 terminal.shell을 읽을 수 없습니다. 대신 사용 가능한 Windows 셸을 사용합니다."++#: src/components/TerminalPanel.tsx+msgid "OpenKnowledge couldn't write launch settings under .ok/local/terminal because the folder is not safely contained in this project. Check that it is a real folder inside the project, not a link. Claude will ask you to approve OpenKnowledge."+msgstr "폴더가 이 프로젝트 안에 안전하게 포함되어 있지 않아 OpenKnowledge가 .ok/local/terminal 아래에 실행 설정을 쓸 수 없습니다. 프로젝트 내부의 실제 폴더이며 링크가 아닌지 확인하세요. Claude가 OpenKnowledge 승인을 요청합니다."++#: src/components/TerminalPanel.tsx+msgid "OpenKnowledge couldn't write launch settings under .ok/local/terminal this time. Check that the folder is writable. Claude will ask you to approve OpenKnowledge."+msgstr "이번에는 OpenKnowledge가 .ok/local/terminal 아래에 실행 설정을 쓸 수 없습니다. 폴더에 쓰기 권한이 있는지 확인하세요. Claude가 OpenKnowledge 승인을 요청합니다."+#: src/lib/acp/tool-call-display.tsmsgid "OpenKnowledge created a share link"msgstr "OpenKnowledge에서 공유 링크 생성"@@ -12342,6 +12352,10 @@ msgstr "Slidev 시작 시간이 초과되었습니다. 다시 시도하세요."msgid "Small section heading."msgstr "작은 섹션 제목입니다."+#: src/components/TerminalPanel.tsx+msgid "Some dropped files could not be inserted safely."+msgstr "놓은 파일 중 일부를 안전하게 삽입할 수 없습니다."+#: src/components/SyncStatusBadge.tsxmsgid "Some files are not listed — the working tree has too many changes."msgstr "일부 파일이 표시되지 않았습니다. 작업 트리의 변경 사항이 너무 많습니다."@@ -13003,6 +13017,18 @@ msgstr "터미널 설정 미로드 상태. 잠시 후 다시 시도하세요."msgid "Terminal settings not yet loaded — try again in a moment"msgstr "터미널 설정을 아직 불러오지 못했습니다. 잠시 후 다시 시도합니다."+#: src/components/TerminalPanel.tsx+msgid "terminal.shell in .ok/local/config.yml must be a string. Using an available Windows shell instead."+msgstr ".ok/local/config.yml의 terminal.shell은 문자열이어야 합니다. 대신 사용 가능한 Windows 셸을 사용합니다."++#: src/components/TerminalPanel.tsx+msgid "terminal.shell in .ok/local/config.yml must be an absolute Windows path. Using an available Windows shell instead."+msgstr ".ok/local/config.yml의 terminal.shell은 Windows 절대 경로여야 합니다. 대신 사용 가능한 Windows 셸을 사용합니다."++#: src/components/TerminalPanel.tsx+msgid "terminal.shell in .ok/local/config.yml supports PowerShell, cmd.exe, or Git Bash for OpenKnowledge-managed launches and dropped-file paths. This shell opens a plain terminal only; agent and command launches do not run in it."+msgstr ".ok/local/config.yml의 terminal.shell은 OpenKnowledge 관리 실행 및 드롭된 파일 경로에 PowerShell, cmd.exe 또는 Git Bash를 지원합니다. 이 셸에서는 일반 터미널만 열리며, 에이전트 및 명령 실행은 여기서 작동하지 않습니다."+#: src/components/settings/SearchSection.tsxmsgid "Test connection"msgstr "연결 테스트"@@ -13203,6 +13229,10 @@ msgstr "미리보기는 보안 규칙을 충족하지 않는 리소스를 차단msgid "The project's server is on a different branch than this window — content can't load."msgstr "이 프로젝트의 서버가 이 창과 다른 브랜치에 있어 콘텐츠를 불러올 수 없습니다."+#: src/components/TerminalPanel.tsx+msgid "The prompt was pasted but not submitted automatically. Review it, then press Enter to send it."+msgstr "프롬프트를 붙여 넣었지만 자동으로 제출하지 않았습니다. 내용을 검토한 다음 Enter를 눌러 전송하세요."+#: src/components/PropertyPanel.tsxmsgid "The properties block at the top of this doc has a formatting error. Switch to source mode to fix it."msgstr "이 문서 위쪽의 속성 블록에 서식 오류가 있습니다. 소스 모드로 전환하여 수정하세요."@@ -13315,6 +13345,10 @@ msgstr "터미널 세션 종료."msgid "The terminal stopped unexpectedly."msgstr "터미널 예기치 않게 중지됨."+#: src/components/TerminalPanel.tsx+msgid "The terminal.shell executable in .ok/local/config.yml was not found. Using an available Windows shell instead."+msgstr ".ok/local/config.yml의 terminal.shell 실행 파일을 찾을 수 없습니다. 대신 사용 가능한 Windows 셸을 사용합니다."+#: src/components/AuthModal.tsxmsgid "The token needs the repo and read:user scopes."msgstr "토큰에 repo 및 read:user 범위가 필요합니다."diff --git a/packages/app/src/locales/pseudo/messages.json b/packages/app/src/locales/pseudo/messages.jsonindex effcb3933..78793bdc1 100644--- a/packages/app/src/locales/pseudo/messages.json+++ b/packages/app/src/locales/pseudo/messages.json@@ -86,6 +86,9 @@"0NkNB5": [["0"], "ḿō àĝō"],"0QVrvp": ["Ḿàxĩḿũḿ àĝēńţś àĺŕēàďŷ ŕũńńĩńĝ"],"0TnCvC": ["Ŕēńàḿē ", ["0"]],+ "0WsUA2": [+ "Ţĥē ƥŕōḿƥţ ŵàś ƥàśţēď ƀũţ ńōţ śũƀḿĩţţēď àũţōḿàţĩćàĺĺŷ. Ŕēvĩēŵ ĩţ, ţĥēń ƥŕēśś Ēńţēŕ ţō śēńď ĩţ."+ ],"0YUS3Q": ["Śũƀƒōĺďēŕ ũńďēŕ ćũŕŕēńţ ƒōĺďēŕ"],"0_J12R": ["Ńēŵ ƒĩĺē ƒŕōḿ ţēḿƥĺàţē \"",@@ -119,6 +122,9 @@"0pZmTP": ["Ćàń'ţ śĥàŕē ţĥĩś ƥàţĥ."],"0qyKG6": ["Śŷńćēď ƒŕōḿ ďĩśķ"],"0r6d6v": ["Ćĥàńĝēś śàvēď àũţōḿàţĩćàĺĺŷ."],+ "0rT21w": [+ "ţēŕḿĩńàĺ.śĥēĺĺ ĩń .ōķ/ĺōćàĺ/ćōńƒĩĝ.ŷḿĺ śũƥƥōŕţś ƤōŵēŕŚĥēĺĺ, ćḿď.ēxē, ōŕ Ĝĩţ ßàśĥ ƒōŕ ŌƥēńĶńōŵĺēďĝē-ḿàńàĝēď ĺàũńćĥēś àńď ďŕōƥƥēď-ƒĩĺē ƥàţĥś. Ţĥĩś śĥēĺĺ ōƥēńś à ƥĺàĩń ţēŕḿĩńàĺ ōńĺŷ; àĝēńţ àńď ćōḿḿàńď ĺàũńćĥēś ďō ńōţ ŕũń ĩń ĩţ."+ ],"0rwwOn": ["ßŷ ţàĝ"],"0s8-e8": ["Śēĺēćţ, ēńţēŕ, ōŕ ĺēàvē ƀĺōćķ ćōḿƥōńēńţś àńď ƒàĺĺƀàćķ śōũŕćē ƀĺōćķś ƒŕōḿ ķēŷƀōàŕď ƀōũńďàŕĩēś."@@ -480,6 +486,9 @@"65Ea2s": ["Ēxƥōśĩńĝ ƥĩńś à ƒĩxēď ƥōŕţ śō ţĥē ţũńńēĺ'ś ţàŕĝēţ śţàŷś śţàƀĺē àćŕōśś ŕēśţàŕţś."],"67Dpmh": ["Śĺàśĥ ćōḿḿàńď śũĝĝēśţĩōńś"],"67f-3g": ["Ďũƥĺĩćàţē śũććēēďēď ƀũţ ţĥē śĩďēƀàŕ ḿàŷ ƀē ōũţ ōƒ ďàţē — ŕēƒŕēśĥ ţō ŕēśŷńć"],+ "69E1Pq": [+ "ţēŕḿĩńàĺ.śĥēĺĺ ĩń .ōķ/ĺōćàĺ/ćōńƒĩĝ.ŷḿĺ ḿũśţ ƀē à śţŕĩńĝ. Ũśĩńĝ àń àvàĩĺàƀĺē Ŵĩńďōŵś śĥēĺĺ ĩńśţēàď."+ ],"69KLIV": ["Ēśćàƥē"],"6ASTuj": ["Ćōḿḿàńďś ŕũń ŵĩţĥ ţĥē ƒũĺĺ àććēśś ōƒ ŷōũŕ ũśēŕ àććōũńţ ōń ţĥĩś ḿàćĥĩńē. Ţũŕń ţĥĩś ōƒƒ ţō ďĩśàƀĺē ţĥē śĥēĺĺ."@@ -812,6 +821,9 @@"AJ7_B2": ["Ćŕēàţē ńēŵ ţĥēḿē"],"AKxFtn": [["openedWorktreeCount", "plural", { "one": ["ŵōŕķţŕēē"], "other": ["ŵōŕķţŕēēś"] }]],"ALhMYW": ["Ţēŕḿĩńàĺ"],+ "AN-UPd": [+ "ţēŕḿĩńàĺ.śĥēĺĺ ĩń .ōķ/ĺōćàĺ/ćōńƒĩĝ.ŷḿĺ ḿũśţ ƀē àń àƀśōĺũţē Ŵĩńďōŵś ƥàţĥ. Ũśĩńĝ àń àvàĩĺàƀĺē Ŵĩńďōŵś śĥēĺĺ ĩńśţēàď."+ ],"ANFxWn": ["Ćōũĺďń’ţ ďēĺēţē ţĥĩś ţĥēḿē. Ŕēƒŕēśĥ àńď ţŕŷ àĝàĩń."],"APNlbk": ["ēxĩţ ", ["0"]],"AQ-Lfg": ["Ćōũĺďń'ţ ĺōàď ţēḿƥĺàţēś"],@@ -854,6 +866,7 @@"AqnqMJ": ["ÀƤĨ ķēŷ śēţ"],"AsqRE_": ["Ďēƒàũĺţ ĺōćàţĩōń ƒōŕ ńēŵ àţţàćĥḿēńţś"],"AtBdnD": ["Ćōũĺďń'ţ ďēĺēţē śķĩĺĺ: ", ["error"]],+ "AvqEDl": ["Śōḿē ďŕōƥƥēď ƒĩĺēś ćōũĺď ńōţ ƀē ĩńśēŕţēď śàƒēĺŷ."],"AwLCZA": ["Ţĥē ēńďƥōĩńţ àńśŵēŕēď, ƀũţ ńōţ ŵĩţĥ àń ŌƥēńÀĨ-ćōḿƥàţĩƀĺē ēḿƀēďďĩńĝś ŕēśƥōńśē. Ćĥēćķ ţĥē ƀàśē ŨŔĹ."],@@ -1003,6 +1016,9 @@"D12vtS": ["(ďēţàćĥēď)"],"D2emTw": ["Śōḿēţĥĩńĝ ŵēńţ ŵŕōńĝ śēńďĩńĝ ŷōũŕ ƒēēďƀàćķ. Ƥĺēàśē ţŕŷ àĝàĩń."],"D4H2N6": ["Ŕēḿōvē ", ["tag"]],+ "D7gKrd": [+ "ŌƥēńĶńōŵĺēďĝē ćōũĺďń'ţ ŵŕĩţē ĺàũńćĥ śēţţĩńĝś ũńďēŕ .ōķ/ĺōćàĺ/ţēŕḿĩńàĺ ƀēćàũśē ţĥē ƒōĺďēŕ ĩś ńōţ śàƒēĺŷ ćōńţàĩńēď ĩń ţĥĩś ƥŕōĴēćţ. Ćĥēćķ ţĥàţ ĩţ ĩś à ŕēàĺ ƒōĺďēŕ ĩńśĩďē ţĥē ƥŕōĴēćţ, ńōţ à ĺĩńķ. Ćĺàũďē ŵĩĺĺ àśķ ŷōũ ţō àƥƥŕōvē ŌƥēńĶńōŵĺēďĝē."+ ],"D7hnvB": ["Ƥōńďēŕĩńĝ…"],"D8JJwQ": ["Ƒēēďƀàćķ ĩśń'ţ àvàĩĺàƀĺē ŕĩĝĥţ ńōŵ. Ƥĺēàśē ţŕŷ àĝàĩń ĺàţēŕ."],"D8OV7J": ["Ōńĺŷ ćōĺĺàƀōŕàţōŕś"],@@ -1549,6 +1565,9 @@"K6jxcj": ["Àďď à ķēŷ"],"K7NMEc": [["uploadFolderName"], " — ", ["0"], " ƒĩĺēś"],"K8-WWn": ["Ḿōvē ƀēţŵēēń ţàƀĺē ćēĺĺś"],+ "K8EvAV": [+ "ŌƥēńĶńōŵĺēďĝē ćōũĺďń'ţ ŕēàď ţēŕḿĩńàĺ.śĥēĺĺ ĩń .ōķ/ĺōćàĺ/ćōńƒĩĝ.ŷḿĺ. Ũśĩńĝ àń àvàĩĺàƀĺē Ŵĩńďōŵś śĥēĺĺ ĩńśţēàď."+ ],"K9J00P": ["Ćĺōńē ƒàĩĺēď — ćōńńēćţĩōń ēŕŕōŕ"],"KDrbNG": ["ŌƥēńĶńōŵĺēďĝē ĺōōķēď ũƥ ĺĩńķś ƒōŕ ", ["subject"]],"KDuPiY": ["Ũƥĺōàďĩńĝ ", ["fileName"]],@@ -1564,6 +1583,9 @@"KOZud0": ["ßũĩĺď à ćōḿƥēţĩţōŕ ŕēśēàŕćĥ ķńōŵĺēďĝē ƀàśē. Śţàŕţ ŵĩţĥ àń ōvēŕvĩēŵ ƥàĝē, ţĥēń àďď ćŕōśś-ĺĩńķēď ƥàĝēś ƒōŕ ēàćĥ ćōḿƥēţĩţōŕ, ţĥēĩŕ ƥŕōďũćţś àńď ƥŕĩćĩńĝ, àńď ţĥē śōũŕćēś ƀēĥĩńď ēvēŕŷ ćĺàĩḿ."],+ "KOeFXa": [+ "ŌƥēńĶńōŵĺēďĝē ćōũĺďń'ţ ŵŕĩţē ĺàũńćĥ śēţţĩńĝś ũńďēŕ .ōķ/ĺōćàĺ/ţēŕḿĩńàĺ ţĥĩś ţĩḿē. Ćĥēćķ ţĥàţ ţĥē ƒōĺďēŕ ĩś ŵŕĩţàƀĺē. Ćĺàũďē ŵĩĺĺ àśķ ŷōũ ţō àƥƥŕōvē ŌƥēńĶńōŵĺēďĝē."+ ],"KPW5WC": ["ḿōvēď ţēḿƥĺàţē"],"KQGZuq": ["Ŕēũśēď ĩƒ ĩţ àĺŕēàďŷ ēxĩśţś, ćŕēàţēď ĩƒ ńōţ."],"KRJ6xh": ["Ńō ţàĝś ŷēţ. Ćōńţĩńũē ţŷƥĩńĝ ţō ćŕēàţē ōńē."],@@ -3681,6 +3703,9 @@"kEiVv6": ["Ţĥēśē ţēàćĥ ŷōũŕ ÀĨ ţōōĺś ĥōŵ ţō ŵōŕķ ŵĩţĥ ŌƥēńĶńōŵĺēďĝē. Ĩńśţàĺĺĩńĝ ōńē àďďś ĩţ ţō ēvēŕŷ ÀĨ ţōōĺ ōń ţĥĩś ḿàćĥĩńē."],+ "kF2Yua": [+ "Ţĥē ţēŕḿĩńàĺ.śĥēĺĺ ēxēćũţàƀĺē ĩń .ōķ/ĺōćàĺ/ćōńƒĩĝ.ŷḿĺ ŵàś ńōţ ƒōũńď. Ũśĩńĝ àń àvàĩĺàƀĺē Ŵĩńďōŵś śĥēĺĺ ĩńśţēàď."+ ],"kFLlsI": ["Ĩńśēŕţ à ƒōōţńōţē ŕēƒēŕēńćē + ḿàţćĥĩńĝ ďēƒĩńĩţĩōń śţũƀ."],"kGp168": ["Ćōũĺďń'ţ ƥŕēƥàŕē ţĥĩś ƥŕōĴēćţ ƒōŕ ƥũƀĺĩśĥ."],"kI5pWt": ["Ĩḿàĝē ńōţ ƒōũńď: ", ["errorLabel"]],diff --git a/packages/app/src/locales/pseudo/messages.po b/packages/app/src/locales/pseudo/messages.poindex 3f7c0e7d3..cd6139b53 100644--- a/packages/app/src/locales/pseudo/messages.po+++ b/packages/app/src/locales/pseudo/messages.po@@ -4725,12 +4725,10 @@ msgstr ""#: src/components/BranchRecycleBanner.tsx#: src/components/BugReportSendToast.tsx-#: src/components/ClaudeReadinessBanner.tsx#: src/components/NavigatorApp.tsx#: src/components/OnboardingCard.tsx#: src/components/settings/SharingSection.tsx-#: src/components/TerminalCliMissingBanner.tsx-#: src/components/TerminalCliUnverifiedBanner.tsx+#: src/components/TerminalNoticeBanner.tsxmsgid "Dismiss"msgstr ""@@ -9418,6 +9416,18 @@ msgstr ""msgid "OpenKnowledge checked the project"msgstr ""+#: src/components/TerminalPanel.tsx+msgid "OpenKnowledge couldn't read terminal.shell in .ok/local/config.yml. Using an available Windows shell instead."+msgstr ""++#: src/components/TerminalPanel.tsx+msgid "OpenKnowledge couldn't write launch settings under .ok/local/terminal because the folder is not safely contained in this project. Check that it is a real folder inside the project, not a link. Claude will ask you to approve OpenKnowledge."+msgstr ""++#: src/components/TerminalPanel.tsx+msgid "OpenKnowledge couldn't write launch settings under .ok/local/terminal this time. Check that the folder is writable. Claude will ask you to approve OpenKnowledge."+msgstr ""+#: src/lib/acp/tool-call-display.tsmsgid "OpenKnowledge created a share link"msgstr ""@@ -12338,6 +12348,10 @@ msgstr ""msgid "Small section heading."msgstr ""+#: src/components/TerminalPanel.tsx+msgid "Some dropped files could not be inserted safely."+msgstr ""+#: src/components/SyncStatusBadge.tsxmsgid "Some files are not listed — the working tree has too many changes."msgstr ""@@ -12999,6 +13013,18 @@ msgstr ""msgid "Terminal settings not yet loaded — try again in a moment"msgstr ""+#: src/components/TerminalPanel.tsx+msgid "terminal.shell in .ok/local/config.yml must be a string. Using an available Windows shell instead."+msgstr ""++#: src/components/TerminalPanel.tsx+msgid "terminal.shell in .ok/local/config.yml must be an absolute Windows path. Using an available Windows shell instead."+msgstr ""++#: src/components/TerminalPanel.tsx+msgid "terminal.shell in .ok/local/config.yml supports PowerShell, cmd.exe, or Git Bash for OpenKnowledge-managed launches and dropped-file paths. This shell opens a plain terminal only; agent and command launches do not run in it."+msgstr ""+#: src/components/settings/SearchSection.tsxmsgid "Test connection"msgstr ""@@ -13199,6 +13225,10 @@ msgstr ""msgid "The project's server is on a different branch than this window — content can't load."msgstr ""+#: src/components/TerminalPanel.tsx+msgid "The prompt was pasted but not submitted automatically. Review it, then press Enter to send it."+msgstr ""+#: src/components/PropertyPanel.tsxmsgid "The properties block at the top of this doc has a formatting error. Switch to source mode to fix it."msgstr ""@@ -13311,6 +13341,10 @@ msgstr ""msgid "The terminal stopped unexpectedly."msgstr ""+#: src/components/TerminalPanel.tsx+msgid "The terminal.shell executable in .ok/local/config.yml was not found. Using an available Windows shell instead."+msgstr ""+#: src/components/AuthModal.tsxmsgid "The token needs the repo and read:user scopes."msgstr ""diff --git a/packages/app/src/locales/pt-BR/messages.json b/packages/app/src/locales/pt-BR/messages.jsonindex 8ade93e37..38ebb77d3 100644--- a/packages/app/src/locales/pt-BR/messages.json+++ b/packages/app/src/locales/pt-BR/messages.json@@ -100,6 +100,9 @@"0NkNB5": ["há ", ["0"], " meses"],"0QVrvp": ["Já está no número máximo de agentes em execução"],"0TnCvC": ["Renomear ", ["0"]],+ "0WsUA2": [+ "O prompt foi colado, mas não foi enviado automaticamente. Revise-o e pressione Enter para enviá-lo."+ ],"0YUS3Q": ["Subpasta dentro da pasta atual"],"0_J12R": ["Novo arquivo a partir do modelo \"",@@ -133,6 +136,9 @@"0pZmTP": ["Não é possível compartilhar este caminho."],"0qyKG6": ["Sincronizado a partir do disco"],"0r6d6v": ["Alterações salvas automaticamente."],+ "0rT21w": [+ "terminal.shell em .ok/local/config.yml aceita PowerShell, cmd.exe ou Git Bash para inicializações gerenciadas pelo OpenKnowledge e caminhos de arquivos soltos. Este shell abre apenas um terminal comum; inicializações de agentes e comandos não são executadas nele."+ ],"0rwwOn": ["Por tag"],"0s8-e8": ["Seleciona, entra ou sai de componentes de bloco e blocos de código alternativos a partir dos limites do teclado."@@ -563,6 +569,9 @@"67f-3g": ["A duplicação deu certo, mas a barra lateral pode estar desatualizada — atualize para ressincronizar"],+ "69E1Pq": [+ "terminal.shell em .ok/local/config.yml deve ser uma string. Um shell do Windows disponível será usado."+ ],"69KLIV": ["Esc"],"6ASTuj": ["Os comandos rodam com todo o acesso da sua conta de usuário nesta máquina. Desative isto para desabilitar o shell."@@ -941,6 +950,9 @@]],"ALhMYW": ["Terminal"],+ "AN-UPd": [+ "terminal.shell em .ok/local/config.yml deve ser um caminho absoluto do Windows. Um shell do Windows disponível será usado."+ ],"ANFxWn": ["Não foi possível excluir este tema. Atualize a página e tente novamente."],"APNlbk": ["saída ", ["0"]],"AQ-Lfg": ["Não foi possível carregar os modelos"],@@ -985,6 +997,7 @@"AqnqMJ": ["Chave de API definida"],"AsqRE_": ["Local padrão para novos anexos"],"AtBdnD": ["Não deu para excluir a habilidade: ", ["error"]],+ "AvqEDl": ["Alguns arquivos soltos não puderam ser inseridos com segurança."],"AwLCZA": ["O endpoint respondeu, mas não com uma resposta de embeddings compatível com a OpenAI. Verifique a URL base."],@@ -1160,6 +1173,9 @@"D12vtS": ["(desanexado)"],"D2emTw": ["Algo deu errado ao enviar seus comentários. Tente de novo."],"D4H2N6": ["Remover ", ["tag"]],+ "D7gKrd": [+ "O OpenKnowledge não conseguiu gravar as configurações de inicialização em .ok/local/terminal porque a pasta não está contida com segurança neste projeto. Verifique se ela é uma pasta real dentro do projeto, e não um link. O Claude pedirá que você aprove o OpenKnowledge."+ ],"D7hnvB": ["Ponderando…"],"D8JJwQ": ["Não dá para enviar comentários agora. Tente mais tarde."],"D8OV7J": ["Somente colaboradores"],@@ -1786,6 +1802,9 @@"K6jxcj": ["Adicionar uma chave"],"K7NMEc": [["uploadFolderName"], " — ", ["0"], " arquivos"],"K8-WWn": ["Mover entre as células da tabela"],+ "K8EvAV": [+ "O OpenKnowledge não conseguiu ler terminal.shell em .ok/local/config.yml. Um shell do Windows disponível será usado."+ ],"K9J00P": ["Falha ao clonar — erro de conexão"],"KDrbNG": ["OpenKnowledge consultou os links de ", ["subject"]],"KDuPiY": ["Enviando ", ["fileName"]],@@ -1801,6 +1820,9 @@"KOZud0": ["Monte uma base de conhecimento sobre a concorrência. Comece com uma página geral e depois acrescente páginas interligadas para cada concorrente, seus produtos e preços, e as fontes por trás de cada afirmação."],+ "KOeFXa": [+ "O OpenKnowledge não conseguiu gravar as configurações de inicialização em .ok/local/terminal desta vez. Verifique se a pasta permite gravação. O Claude pedirá que você aprove o OpenKnowledge."+ ],"KPW5WC": ["modelo movido"],"KQGZuq": ["Reaproveitada se já existir; criada se não."],"KRJ6xh": ["Ainda não há tags. Continue digitando para criar uma."],@@ -4182,6 +4204,9 @@"kEiVv6": ["Elas ensinam suas ferramentas de IA a trabalhar com o OpenKnowledge. Instalar uma a adiciona a todas as ferramentas de IA desta máquina."],+ "kF2Yua": [+ "O executável terminal.shell em .ok/local/config.yml não foi encontrado. Um shell do Windows disponível será usado."+ ],"kFLlsI": ["Insere uma referência de nota de rodapé e a definição correspondente."],"kGp168": ["Não foi possível preparar este projeto para publicação."],"kI5pWt": ["Imagem não encontrada: ", ["errorLabel"]],diff --git a/packages/app/src/locales/pt-BR/messages.po b/packages/app/src/locales/pt-BR/messages.poindex 1f6079903..447caba42 100644--- a/packages/app/src/locales/pt-BR/messages.po+++ b/packages/app/src/locales/pt-BR/messages.po@@ -4725,12 +4725,10 @@ msgstr "Desconectando"#: src/components/BranchRecycleBanner.tsx#: src/components/BugReportSendToast.tsx-#: src/components/ClaudeReadinessBanner.tsx#: src/components/NavigatorApp.tsx#: src/components/OnboardingCard.tsx#: src/components/settings/SharingSection.tsx-#: src/components/TerminalCliMissingBanner.tsx-#: src/components/TerminalCliUnverifiedBanner.tsx+#: src/components/TerminalNoticeBanner.tsxmsgid "Dismiss"msgstr "Dispensar"@@ -9418,6 +9416,18 @@ msgstr "OpenKnowledge verificou se há conflitos"msgid "OpenKnowledge checked the project"msgstr "OpenKnowledge verificou o projeto"+#: src/components/TerminalPanel.tsx+msgid "OpenKnowledge couldn't read terminal.shell in .ok/local/config.yml. Using an available Windows shell instead."+msgstr "O OpenKnowledge não conseguiu ler terminal.shell em .ok/local/config.yml. Um shell do Windows disponível será usado."++#: src/components/TerminalPanel.tsx+msgid "OpenKnowledge couldn't write launch settings under .ok/local/terminal because the folder is not safely contained in this project. Check that it is a real folder inside the project, not a link. Claude will ask you to approve OpenKnowledge."+msgstr "O OpenKnowledge não conseguiu gravar as configurações de inicialização em .ok/local/terminal porque a pasta não está contida com segurança neste projeto. Verifique se ela é uma pasta real dentro do projeto, e não um link. O Claude pedirá que você aprove o OpenKnowledge."++#: src/components/TerminalPanel.tsx+msgid "OpenKnowledge couldn't write launch settings under .ok/local/terminal this time. Check that the folder is writable. Claude will ask you to approve OpenKnowledge."+msgstr "O OpenKnowledge não conseguiu gravar as configurações de inicialização em .ok/local/terminal desta vez. Verifique se a pasta permite gravação. O Claude pedirá que você aprove o OpenKnowledge."+#: src/lib/acp/tool-call-display.tsmsgid "OpenKnowledge created a share link"msgstr "OpenKnowledge criou um link de compartilhamento"@@ -12338,6 +12348,10 @@ msgstr "O Slidev demorou demais para iniciar. Tente novamente."msgid "Small section heading."msgstr "Título de seção pequeno."+#: src/components/TerminalPanel.tsx+msgid "Some dropped files could not be inserted safely."+msgstr "Alguns arquivos soltos não puderam ser inseridos com segurança."+#: src/components/SyncStatusBadge.tsxmsgid "Some files are not listed — the working tree has too many changes."msgstr "Alguns arquivos não estão listados: a árvore de trabalho tem alterações demais."@@ -12999,6 +13013,18 @@ msgstr "As configurações do terminal ainda não carregaram — tente de novo emsgid "Terminal settings not yet loaded — try again in a moment"msgstr "As configurações do terminal ainda não carregaram — tente de novo em instantes"+#: src/components/TerminalPanel.tsx+msgid "terminal.shell in .ok/local/config.yml must be a string. Using an available Windows shell instead."+msgstr "terminal.shell em .ok/local/config.yml deve ser uma string. Um shell do Windows disponível será usado."++#: src/components/TerminalPanel.tsx+msgid "terminal.shell in .ok/local/config.yml must be an absolute Windows path. Using an available Windows shell instead."+msgstr "terminal.shell em .ok/local/config.yml deve ser um caminho absoluto do Windows. Um shell do Windows disponível será usado."++#: src/components/TerminalPanel.tsx+msgid "terminal.shell in .ok/local/config.yml supports PowerShell, cmd.exe, or Git Bash for OpenKnowledge-managed launches and dropped-file paths. This shell opens a plain terminal only; agent and command launches do not run in it."+msgstr "terminal.shell em .ok/local/config.yml aceita PowerShell, cmd.exe ou Git Bash para inicializações gerenciadas pelo OpenKnowledge e caminhos de arquivos soltos. Este shell abre apenas um terminal comum; inicializações de agentes e comandos não são executadas nele."+#: src/components/settings/SearchSection.tsxmsgid "Test connection"msgstr "Testar conexão"@@ -13199,6 +13225,10 @@ msgstr "A pré-visualização bloqueia recursos que não atendem às regras de smsgid "The project's server is on a different branch than this window — content can't load."msgstr "O servidor deste projeto está em uma branch diferente desta janela — o conteúdo não pode ser carregado."+#: src/components/TerminalPanel.tsx+msgid "The prompt was pasted but not submitted automatically. Review it, then press Enter to send it."+msgstr "O prompt foi colado, mas não foi enviado automaticamente. Revise-o e pressione Enter para enviá-lo."+#: src/components/PropertyPanel.tsxmsgid "The properties block at the top of this doc has a formatting error. Switch to source mode to fix it."msgstr "O bloco de propriedades no topo deste documento tem um erro de formatação. Mude para o modo código para corrigir."@@ -13311,6 +13341,10 @@ msgstr "A sessão de terminal terminou."msgid "The terminal stopped unexpectedly."msgstr "O terminal parou de forma inesperada."+#: src/components/TerminalPanel.tsx+msgid "The terminal.shell executable in .ok/local/config.yml was not found. Using an available Windows shell instead."+msgstr "O executável terminal.shell em .ok/local/config.yml não foi encontrado. Um shell do Windows disponível será usado."+#: src/components/AuthModal.tsxmsgid "The token needs the repo and read:user scopes."msgstr "O token precisa dos escopos repo e read:user."diff --git a/packages/app/src/locales/ur/messages.json b/packages/app/src/locales/ur/messages.jsonindex aaaedd5dd..17f92a7ae 100644--- a/packages/app/src/locales/ur/messages.json+++ b/packages/app/src/locales/ur/messages.json@@ -84,6 +84,9 @@"0NkNB5": [["0"], " ماہ پہلے"],"0QVrvp": ["زیادہ سے زیادہ ایجنٹس پہلے ہی چل رہے ہیں"],"0TnCvC": [["0"], " کا نام بدلیں"],+ "0WsUA2": [+ "پرامپٹ چسپاں کر دیا گیا لیکن خودکار طور پر جمع نہیں کیا گیا۔ اس کا جائزہ لیں، پھر بھیجنے کے لیے Enter دبائیں۔"+ ],"0YUS3Q": ["موجودہ فولڈر کے تحت ذیلی فولڈر"],"0_J12R": [["targetLabel"],@@ -117,6 +120,9 @@"0pZmTP": ["یہ راستہ شیئر نہیں کیا جا سکتا۔"],"0qyKG6": ["ڈسک سے مطابق"],"0r6d6v": ["تبدیلیاں خودکار طور پر محفوظ ہو گئیں۔"],+ "0rT21w": [+ ".ok/local/config.yml میں terminal.shell، OpenKnowledge کے زیر انتظام لانچز اور ڈراپ کی گئی فائلوں کے پاتھ کے لیے PowerShell، cmd.exe یا Git Bash کو سپورٹ کرتا ہے۔ یہ شیل صرف ایک سادہ ٹرمینل کھولتا ہے؛ ایجنٹ اور کمانڈ لانچز اس میں نہیں چلتے۔"+ ],"0rwwOn": ["ٹیگ کے لحاظ سے"],"0s8-e8": ["کی بورڈ کی حدود سے بلاک اجزاء اور متبادل سورس بلاکس منتخب کریں، ان میں داخل ہوں یا ان سے نکلیں۔"@@ -500,6 +506,9 @@],"67Dpmh": ["سلیش کمانڈ کی تجاویز"],"67f-3g": ["نقل بن گئی مگر سائیڈ بار پرانا ہو سکتا ہے — دوبارہ مطابقت کے لیے تازہ کریں"],+ "69E1Pq": [+ ".ok/local/config.yml میں terminal.shell کا سٹرنگ ہونا ضروری ہے۔ اس کے بجائے دستیاب Windows شیل استعمال کیا جا رہا ہے۔"+ ],"69KLIV": ["Escape"],"6ASTuj": ["کمانڈز اس مشین پر آپ کے صارف اکاؤنٹ کی مکمل رسائی کے ساتھ چلتی ہیں۔ شیل بند کرنے کے لیے اسے آف کریں۔"@@ -828,6 +837,9 @@"AJ7_B2": ["نئی تھیم بنائیں"],"AKxFtn": [["openedWorktreeCount", "plural", { "one": ["ورک ٹری"], "other": ["ورک ٹریز"] }]],"ALhMYW": ["ٹرمینل"],+ "AN-UPd": [+ ".ok/local/config.yml میں terminal.shell کا مکمل Windows پاتھ ہونا ضروری ہے۔ اس کے بجائے دستیاب Windows شیل استعمال کیا جا رہا ہے۔"+ ],"ANFxWn": ["یہ تھیم حذف نہیں کی جا سکی۔ تازہ کر کے دوبارہ کوشش کریں۔"],"APNlbk": [["0"], " سے باہر نکلیں"],"AQ-Lfg": ["ٹیمپلیٹس لوڈ نہیں ہو سکے"],@@ -870,6 +882,7 @@"AqnqMJ": ["API کلید مقرر ہے"],"AsqRE_": ["نئے منسلکات کے لیے طے شدہ مقام"],"AtBdnD": ["مہارت حذف نہیں ہو سکی: ", ["error"]],+ "AvqEDl": ["چھوڑی گئی کچھ فائلیں محفوظ طریقے سے شامل نہیں کی جا سکیں۔"],"AwLCZA": ["اینڈ پوائنٹ نے جواب دیا، مگر OpenAI سے ہم آہنگ ایمبیڈنگز جواب نہیں۔ بنیادی URL دیکھیں۔"],@@ -1019,6 +1032,9 @@"D12vtS": ["(منقطع)"],"D2emTw": ["آپ کی رائے بھیجتے ہوئے کچھ غلط ہو گیا۔ براہِ کرم دوبارہ کوشش کریں۔"],"D4H2N6": [["tag"], " ہٹائیں"],+ "D7gKrd": [+ "OpenKnowledge .ok/local/terminal کے تحت لانچ کی ترتیبات نہیں لکھ سکا کیونکہ فولڈر اس پروجیکٹ کے اندر محفوظ طور پر موجود نہیں ہے۔ تصدیق کریں کہ یہ پروجیکٹ کے اندر ایک حقیقی فولڈر ہے، لنک نہیں۔ Claude آپ سے OpenKnowledge کو منظور کرنے کے لیے کہے گا۔"+ ],"D7hnvB": ["غور کیا جا رہا ہے…"],"D8JJwQ": ["رائے ابھی دستیاب نہیں۔ براہِ کرم بعد میں دوبارہ کوشش کریں۔"],"D8OV7J": ["صرف ساتھی"],@@ -1588,6 +1604,9 @@"K6jxcj": ["کلید شامل کریں"],"K7NMEc": [["uploadFolderName"], " — ", ["0"], " فائلیں"],"K8-WWn": ["ٹیبل کے خانوں کے درمیان جائیں"],+ "K8EvAV": [+ "OpenKnowledge .ok/local/config.yml میں terminal.shell نہیں پڑھ سکا۔ اس کے بجائے دستیاب Windows شیل استعمال کیا جا رہا ہے۔"+ ],"K9J00P": ["کلون ناکام — کنکشن کی خرابی"],"KDrbNG": ["OpenKnowledge نے ", ["subject"], " کے لنکس تلاش کیے"],"KDuPiY": [["fileName"], " اپ لوڈ ہو رہی ہے"],@@ -1603,6 +1622,9 @@"KOZud0": ["حریفوں کی تحقیق کا نالج بیس بنائیں۔ ایک جائزہ صفحے سے شروع کریں، پھر ہر حریف، ان کی مصنوعات اور قیمتوں، اور ہر دعوے کے پیچھے موجود مآخذ کے لیے باہم مربوط صفحات شامل کریں۔"],+ "KOeFXa": [+ "OpenKnowledge اس بار .ok/local/terminal کے تحت لانچ کی ترتیبات نہیں لکھ سکا۔ تصدیق کریں کہ فولڈر میں لکھا جا سکتا ہے۔ Claude آپ سے OpenKnowledge کو منظور کرنے کے لیے کہے گا۔"+ ],"KPW5WC": ["ٹیمپلیٹ منتقل کیا"],"KQGZuq": ["اگر پہلے سے موجود ہو تو دوبارہ استعمال ہوتا ہے، ورنہ بن جاتا ہے۔"],"KRJ6xh": ["ابھی کوئی ٹیگ نہیں۔ ایک بنانے کے لیے لکھتے رہیں۔"],@@ -3767,6 +3789,9 @@"kEiVv6": ["یہ آپ کے AI ٹولز کو OpenKnowledge کے ساتھ کام کرنا سکھاتی ہیں۔ کسی ایک کو نصب کرنے سے وہ اس مشین کے ہر AI ٹول میں شامل ہو جاتی ہے۔"],+ "kF2Yua": [+ ".ok/local/config.yml میں terminal.shell ایگزیکیوٹیبل نہیں ملا۔ اس کے بجائے دستیاب Windows شیل استعمال کیا جا رہا ہے۔"+ ],"kFLlsI": ["فٹ نوٹ کا حوالہ + اس سے مماثل تعریف کا خاکہ داخل کریں۔"],"kGp168": ["اس پروجیکٹ کو اشاعت کے لیے تیار نہیں کیا جا سکا۔"],"kI5pWt": ["تصویر نہیں ملی: ", ["errorLabel"]],diff --git a/packages/app/src/locales/ur/messages.po b/packages/app/src/locales/ur/messages.poindex 8bef0a5cc..da8c88e13 100644--- a/packages/app/src/locales/ur/messages.po+++ b/packages/app/src/locales/ur/messages.po@@ -4729,12 +4729,10 @@ msgstr "منقطع کیا جا رہا ہے"#: src/components/BranchRecycleBanner.tsx#: src/components/BugReportSendToast.tsx-#: src/components/ClaudeReadinessBanner.tsx#: src/components/NavigatorApp.tsx#: src/components/OnboardingCard.tsx#: src/components/settings/SharingSection.tsx-#: src/components/TerminalCliMissingBanner.tsx-#: src/components/TerminalCliUnverifiedBanner.tsx+#: src/components/TerminalNoticeBanner.tsxmsgid "Dismiss"msgstr "برخاست کریں"@@ -9422,6 +9420,18 @@ msgstr "OpenKnowledge نے تنازعات کی جانچ کی"msgid "OpenKnowledge checked the project"msgstr "OpenKnowledge نے پروجیکٹ کی جانچ کی"+#: src/components/TerminalPanel.tsx+msgid "OpenKnowledge couldn't read terminal.shell in .ok/local/config.yml. Using an available Windows shell instead."+msgstr "OpenKnowledge .ok/local/config.yml میں terminal.shell نہیں پڑھ سکا۔ اس کے بجائے دستیاب Windows شیل استعمال کیا جا رہا ہے۔"++#: src/components/TerminalPanel.tsx+msgid "OpenKnowledge couldn't write launch settings under .ok/local/terminal because the folder is not safely contained in this project. Check that it is a real folder inside the project, not a link. Claude will ask you to approve OpenKnowledge."+msgstr "OpenKnowledge .ok/local/terminal کے تحت لانچ کی ترتیبات نہیں لکھ سکا کیونکہ فولڈر اس پروجیکٹ کے اندر محفوظ طور پر موجود نہیں ہے۔ تصدیق کریں کہ یہ پروجیکٹ کے اندر ایک حقیقی فولڈر ہے، لنک نہیں۔ Claude آپ سے OpenKnowledge کو منظور کرنے کے لیے کہے گا۔"++#: src/components/TerminalPanel.tsx+msgid "OpenKnowledge couldn't write launch settings under .ok/local/terminal this time. Check that the folder is writable. Claude will ask you to approve OpenKnowledge."+msgstr "OpenKnowledge اس بار .ok/local/terminal کے تحت لانچ کی ترتیبات نہیں لکھ سکا۔ تصدیق کریں کہ فولڈر میں لکھا جا سکتا ہے۔ Claude آپ سے OpenKnowledge کو منظور کرنے کے لیے کہے گا۔"+#: src/lib/acp/tool-call-display.tsmsgid "OpenKnowledge created a share link"msgstr "OpenKnowledge نے شیئر لنک بنایا"@@ -12342,6 +12352,10 @@ msgstr "Slidev شروع ہوتے ہوئے وقت ختم ہو گیا۔ دوبارmsgid "Small section heading."msgstr "چھوٹا سیکشن عنوان۔"+#: src/components/TerminalPanel.tsx+msgid "Some dropped files could not be inserted safely."+msgstr "چھوڑی گئی کچھ فائلیں محفوظ طریقے سے شامل نہیں کی جا سکیں۔"+#: src/components/SyncStatusBadge.tsxmsgid "Some files are not listed — the working tree has too many changes."msgstr "کچھ فائلیں فہرست میں نہیں ہیں: ورکنگ ٹری میں بہت زیادہ تبدیلیاں ہیں۔"@@ -13003,6 +13017,18 @@ msgstr "ٹرمینل کی ترتیبات ابھی لوڈ نہیں ہوئیں —msgid "Terminal settings not yet loaded — try again in a moment"msgstr "ٹرمینل کی ترتیبات ابھی لوڈ نہیں ہوئیں — تھوڑی دیر بعد دوبارہ کوشش کریں"+#: src/components/TerminalPanel.tsx+msgid "terminal.shell in .ok/local/config.yml must be a string. Using an available Windows shell instead."+msgstr ".ok/local/config.yml میں terminal.shell کا سٹرنگ ہونا ضروری ہے۔ اس کے بجائے دستیاب Windows شیل استعمال کیا جا رہا ہے۔"++#: src/components/TerminalPanel.tsx+msgid "terminal.shell in .ok/local/config.yml must be an absolute Windows path. Using an available Windows shell instead."+msgstr ".ok/local/config.yml میں terminal.shell کا مکمل Windows پاتھ ہونا ضروری ہے۔ اس کے بجائے دستیاب Windows شیل استعمال کیا جا رہا ہے۔"++#: src/components/TerminalPanel.tsx+msgid "terminal.shell in .ok/local/config.yml supports PowerShell, cmd.exe, or Git Bash for OpenKnowledge-managed launches and dropped-file paths. This shell opens a plain terminal only; agent and command launches do not run in it."+msgstr ".ok/local/config.yml میں terminal.shell، OpenKnowledge کے زیر انتظام لانچز اور ڈراپ کی گئی فائلوں کے پاتھ کے لیے PowerShell، cmd.exe یا Git Bash کو سپورٹ کرتا ہے۔ یہ شیل صرف ایک سادہ ٹرمینل کھولتا ہے؛ ایجنٹ اور کمانڈ لانچز اس میں نہیں چلتے۔"+#: src/components/settings/SearchSection.tsxmsgid "Test connection"msgstr "کنکشن جانچیں"@@ -13203,6 +13229,10 @@ msgstr "پیش منظر ان وسائل کو روکتا ہے جو اس کے سیmsgid "The project's server is on a different branch than this window — content can't load."msgstr "اس پروجیکٹ کا سرور اس ونڈو سے مختلف برانچ پر ہے — مواد لوڈ نہیں ہو سکتا۔"+#: src/components/TerminalPanel.tsx+msgid "The prompt was pasted but not submitted automatically. Review it, then press Enter to send it."+msgstr "پرامپٹ چسپاں کر دیا گیا لیکن خودکار طور پر جمع نہیں کیا گیا۔ اس کا جائزہ لیں، پھر بھیجنے کے لیے Enter دبائیں۔"+#: src/components/PropertyPanel.tsxmsgid "The properties block at the top of this doc has a formatting error. Switch to source mode to fix it."msgstr "اس دستاویز کے اوپر خصوصیات کے بلاک میں فارمیٹنگ کی خرابی ہے۔ اسے ٹھیک کرنے کے لیے سورس موڈ پر جائیں۔"@@ -13315,6 +13345,10 @@ msgstr "ٹرمینل کا سیشن ختم ہو گیا۔"msgid "The terminal stopped unexpectedly."msgstr "ٹرمینل غیر متوقع طور پر رک گیا۔"+#: src/components/TerminalPanel.tsx+msgid "The terminal.shell executable in .ok/local/config.yml was not found. Using an available Windows shell instead."+msgstr ".ok/local/config.yml میں terminal.shell ایگزیکیوٹیبل نہیں ملا۔ اس کے بجائے دستیاب Windows شیل استعمال کیا جا رہا ہے۔"+#: src/components/AuthModal.tsxmsgid "The token needs the repo and read:user scopes."msgstr "ٹوکن کو repo اور read:user دائرہ کار درکار ہیں۔"diff --git a/packages/app/src/locales/zh-Hans/messages.json b/packages/app/src/locales/zh-Hans/messages.jsonindex 3ba9a65bd..70bdd6190 100644--- a/packages/app/src/locales/zh-Hans/messages.json+++ b/packages/app/src/locales/zh-Hans/messages.json@@ -78,6 +78,7 @@"0NkNB5": [["0"], " 个月前"],"0QVrvp": ["运行中的智能体已达上限"],"0TnCvC": ["重命名 ", ["0"]],+ "0WsUA2": ["提示词已粘贴,但未自动提交。请检查内容,然后按 Enter 发送。"],"0YUS3Q": ["当前文件夹下的子文件夹"],"0_J12R": ["在 ",@@ -112,6 +113,9 @@"0pZmTP": ["无法共享此路径。"],"0qyKG6": ["已从磁盘同步"],"0r6d6v": ["更改已自动保存。"],+ "0rT21w": [+ ".ok/local/config.yml 中的 terminal.shell 支持使用 PowerShell、cmd.exe 或 Git Bash 执行 OpenKnowledge 管理的启动以及插入拖放文件的路径。此 shell 仅打开普通终端;智能体和命令启动无法在其中运行。"+ ],"0rwwOn": ["按标签"],"0s8-e8": ["从键盘边界选中、进入或离开块组件和回退源码块。"],"0t0bbC": ["无法保存同步偏好:", ["detail"]],@@ -446,6 +450,9 @@"65Ea2s": ["公开时会固定一个端口,使隧道的目标在重启后保持稳定。"],"67Dpmh": ["斜杠命令建议"],"67f-3g": ["副本创建成功,但侧边栏可能不是最新的——请刷新以重新同步"],+ "69E1Pq": [+ ".ok/local/config.yml 中的 terminal.shell 必须是字符串,将改用可用的 Windows shell。"+ ],"69KLIV": ["Esc"],"6ASTuj": ["命令将以你在本机用户账户的完整权限运行。关闭此项可禁用 shell。"],"6Aih4U": ["离线"],@@ -727,6 +734,9 @@"AJ7_B2": ["创建新主题"],"AKxFtn": [["openedWorktreeCount", "plural", { "other": ["worktree"] }]],"ALhMYW": ["终端"],+ "AN-UPd": [+ ".ok/local/config.yml 中的 terminal.shell 必须是 Windows 绝对路径,将改用可用的 Windows shell。"+ ],"ANFxWn": ["无法删除此主题。请刷新后重试。"],"APNlbk": ["退出 ", ["0"]],"AQ-Lfg": ["无法加载模板"],@@ -767,6 +777,7 @@"AqnqMJ": ["API 密钥已设置"],"AsqRE_": ["新附件的默认位置"],"AtBdnD": ["无法删除技能:", ["error"]],+ "AvqEDl": ["部分拖放的文件无法安全插入。"],"AwLCZA": ["端点有响应,但返回的不是兼容 OpenAI 的嵌入响应。请检查基础 URL。"],"AwrGuz": ["这个文档缺少必需的属性"],"AyKwqp": ["位于你的主目录中——此电脑上的每个项目,仅限你自己。"],@@ -888,6 +899,9 @@"D12vtS": ["(游离状态)"],"D2emTw": ["发送你的反馈时出了点问题。请重试。"],"D4H2N6": ["移除 ", ["tag"]],+ "D7gKrd": [+ "OpenKnowledge 无法在 .ok/local/terminal 下写入启动设置,因为该文件夹未安全地包含在此项目中。请确认它是项目内的真实文件夹,而不是链接。Claude 将要求你批准 OpenKnowledge。"+ ],"D7hnvB": ["正在思量…"],"D8JJwQ": ["反馈功能暂时不可用。请稍后再试。"],"D8OV7J": ["仅协作者"],@@ -1364,6 +1378,9 @@"K6jxcj": ["添加键"],"K7NMEc": [["uploadFolderName"], " — ", ["0"], " 个文件"],"K8-WWn": ["在表格单元格之间移动"],+ "K8EvAV": [+ "OpenKnowledge 无法读取 .ok/local/config.yml 中的 terminal.shell,将改用可用的 Windows shell。"+ ],"K9J00P": ["克隆失败——连接出错"],"KDrbNG": ["OpenKnowledge 查找了 ", ["subject"], " 的链接"],"KDuPiY": ["正在上传 ", ["fileName"]],@@ -1377,6 +1394,9 @@"KOZud0": ["搭建一个竞品调研知识库。先写一页总览,再为每个竞争对手、他们的产品与定价,以及每条论断背后的信息来源添加相互链接的页面。"],+ "KOeFXa": [+ "OpenKnowledge 此次无法在 .ok/local/terminal 下写入启动设置。请确认该文件夹可写。Claude 将要求你批准 OpenKnowledge。"+ ],"KPW5WC": ["已移动模板"],"KQGZuq": ["如果已存在就复用,否则就新建。"],"KRJ6xh": ["还没有标签。继续输入即可新建一个。"],@@ -3252,6 +3272,9 @@"kEiVv6": ["它们教你的 AI 工具如何使用 OpenKnowledge。安装其中一个,会把它添加到本机的每个 AI 工具。"],+ "kF2Yua": [+ "未找到 .ok/local/config.yml 中指定的 terminal.shell 可执行文件,将改用可用的 Windows shell。"+ ],"kFLlsI": ["插入一个脚注引用及其对应的定义占位。"],"kGp168": ["无法为发布准备此项目。"],"kI5pWt": ["找不到图片:", ["errorLabel"]],diff --git a/packages/app/src/locales/zh-Hans/messages.po b/packages/app/src/locales/zh-Hans/messages.poindex 85ad31a6e..0fcbab198 100644--- a/packages/app/src/locales/zh-Hans/messages.po+++ b/packages/app/src/locales/zh-Hans/messages.po@@ -4729,12 +4729,10 @@ msgstr "正在断开连接"#: src/components/BranchRecycleBanner.tsx#: src/components/BugReportSendToast.tsx-#: src/components/ClaudeReadinessBanner.tsx#: src/components/NavigatorApp.tsx#: src/components/OnboardingCard.tsx#: src/components/settings/SharingSection.tsx-#: src/components/TerminalCliMissingBanner.tsx-#: src/components/TerminalCliUnverifiedBanner.tsx+#: src/components/TerminalNoticeBanner.tsxmsgid "Dismiss"msgstr "忽略"@@ -9422,6 +9420,18 @@ msgstr "OpenKnowledge 检查了冲突"msgid "OpenKnowledge checked the project"msgstr "OpenKnowledge 检查了项目"+#: src/components/TerminalPanel.tsx+msgid "OpenKnowledge couldn't read terminal.shell in .ok/local/config.yml. Using an available Windows shell instead."+msgstr "OpenKnowledge 无法读取 .ok/local/config.yml 中的 terminal.shell,将改用可用的 Windows shell。"++#: src/components/TerminalPanel.tsx+msgid "OpenKnowledge couldn't write launch settings under .ok/local/terminal because the folder is not safely contained in this project. Check that it is a real folder inside the project, not a link. Claude will ask you to approve OpenKnowledge."+msgstr "OpenKnowledge 无法在 .ok/local/terminal 下写入启动设置,因为该文件夹未安全地包含在此项目中。请确认它是项目内的真实文件夹,而不是链接。Claude 将要求你批准 OpenKnowledge。"++#: src/components/TerminalPanel.tsx+msgid "OpenKnowledge couldn't write launch settings under .ok/local/terminal this time. Check that the folder is writable. Claude will ask you to approve OpenKnowledge."+msgstr "OpenKnowledge 此次无法在 .ok/local/terminal 下写入启动设置。请确认该文件夹可写。Claude 将要求你批准 OpenKnowledge。"+#: src/lib/acp/tool-call-display.tsmsgid "OpenKnowledge created a share link"msgstr "OpenKnowledge 创建了分享链接"@@ -12342,6 +12352,10 @@ msgstr "Slidev 启动超时。请重试。"msgid "Small section heading."msgstr "小号章节标题。"+#: src/components/TerminalPanel.tsx+msgid "Some dropped files could not be inserted safely."+msgstr "部分拖放的文件无法安全插入。"+#: src/components/SyncStatusBadge.tsxmsgid "Some files are not listed — the working tree has too many changes."msgstr "部分文件未列出:工作区的更改过多。"@@ -13003,6 +13017,18 @@ msgstr "终端设置尚未加载——请稍后再试。"msgid "Terminal settings not yet loaded — try again in a moment"msgstr "终端设置尚未加载——请稍后再试"+#: src/components/TerminalPanel.tsx+msgid "terminal.shell in .ok/local/config.yml must be a string. Using an available Windows shell instead."+msgstr ".ok/local/config.yml 中的 terminal.shell 必须是字符串,将改用可用的 Windows shell。"++#: src/components/TerminalPanel.tsx+msgid "terminal.shell in .ok/local/config.yml must be an absolute Windows path. Using an available Windows shell instead."+msgstr ".ok/local/config.yml 中的 terminal.shell 必须是 Windows 绝对路径,将改用可用的 Windows shell。"++#: src/components/TerminalPanel.tsx+msgid "terminal.shell in .ok/local/config.yml supports PowerShell, cmd.exe, or Git Bash for OpenKnowledge-managed launches and dropped-file paths. This shell opens a plain terminal only; agent and command launches do not run in it."+msgstr ".ok/local/config.yml 中的 terminal.shell 支持使用 PowerShell、cmd.exe 或 Git Bash 执行 OpenKnowledge 管理的启动以及插入拖放文件的路径。此 shell 仅打开普通终端;智能体和命令启动无法在其中运行。"+#: src/components/settings/SearchSection.tsxmsgid "Test connection"msgstr "测试连接"@@ -13203,6 +13229,10 @@ msgstr "预览会拦截不符合其安全规则的资源(例如纯 http:// 的msgid "The project's server is on a different branch than this window — content can't load."msgstr "该项目的服务器所在分支与此窗口不一致,内容无法加载。"+#: src/components/TerminalPanel.tsx+msgid "The prompt was pasted but not submitted automatically. Review it, then press Enter to send it."+msgstr "提示词已粘贴,但未自动提交。请检查内容,然后按 Enter 发送。"+#: src/components/PropertyPanel.tsxmsgid "The properties block at the top of this doc has a formatting error. Switch to source mode to fix it."msgstr "这个文档顶部的属性块有格式错误。请切换到源码模式修复。"@@ -13315,6 +13345,10 @@ msgstr "终端会话已结束。"msgid "The terminal stopped unexpectedly."msgstr "终端意外停止了。"+#: src/components/TerminalPanel.tsx+msgid "The terminal.shell executable in .ok/local/config.yml was not found. Using an available Windows shell instead."+msgstr "未找到 .ok/local/config.yml 中指定的 terminal.shell 可执行文件,将改用可用的 Windows shell。"+#: src/components/AuthModal.tsxmsgid "The token needs the repo and read:user scopes."msgstr "这个令牌需要 repo 和 read:user 权限范围。"diff --git a/packages/app/src/locales/zh-Hant/messages.json b/packages/app/src/locales/zh-Hant/messages.jsonindex 87c1217ac..17368eeda 100644--- a/packages/app/src/locales/zh-Hant/messages.json+++ b/packages/app/src/locales/zh-Hant/messages.json@@ -78,6 +78,7 @@"0NkNB5": [["0"], " 個月前"],"0QVrvp": ["同時執行的代理已達上限"],"0TnCvC": ["重新命名 ", ["0"]],+ "0WsUA2": ["提示詞已貼上,但未自動提交。請檢查內容,然後按 Enter 傳送。"],"0YUS3Q": ["目前資料夾底下的子資料夾"],"0_J12R": ["在 ",@@ -112,6 +113,9 @@"0pZmTP": ["無法分享這個路徑。"],"0qyKG6": ["已從磁碟同步"],"0r6d6v": ["變更已自動儲存。"],+ "0rT21w": [+ ".ok/local/config.yml 中的 terminal.shell 支援使用 PowerShell、cmd.exe 或 Git Bash 執行 OpenKnowledge 管理的啟動以及插入拖放檔案的路徑。此 shell 僅開啟一般終端;代理程式和命令啟動無法在其中執行。"+ ],"0rwwOn": ["依標籤"],"0s8-e8": ["從鍵盤邊界選取、進入或離開區塊元件和備用的原始碼區塊。"],"0t0bbC": ["無法儲存同步偏好設定:", ["detail"]],@@ -450,6 +454,7 @@"65Ea2s": ["公開會鎖定一個固定連接埠,讓通道的目標在重新啟動後保持穩定。"],"67Dpmh": ["斜線指令建議"],"67f-3g": ["副本已建立,但側邊欄可能不是最新的——請重新整理以重新同步"],+ "69E1Pq": [".ok/local/config.yml 中的 terminal.shell 必須是字串,將改用可用的 Windows shell。"],"69KLIV": ["Esc"],"6ASTuj": ["命令會以你在這台電腦上使用者帳戶的完整權限執行。關閉此項可停用 shell。"],"6Aih4U": ["離線"],@@ -731,6 +736,9 @@"AJ7_B2": ["建立新主題"],"AKxFtn": [["openedWorktreeCount", "plural", { "other": ["worktree"] }]],"ALhMYW": ["終端機"],+ "AN-UPd": [+ ".ok/local/config.yml 中的 terminal.shell 必須是 Windows 絕對路徑,將改用可用的 Windows shell。"+ ],"ANFxWn": ["無法刪除這個主題。請重新整理後再試一次。"],"APNlbk": ["結束 ", ["0"]],"AQ-Lfg": ["無法載入範本"],@@ -771,6 +779,7 @@"AqnqMJ": ["API 金鑰已設定"],"AsqRE_": ["新附件的預設位置"],"AtBdnD": ["無法刪除技能:", ["error"]],+ "AvqEDl": ["部分拖放的檔案無法安全插入。"],"AwLCZA": ["端點有回應,但傳回的不是相容 OpenAI 的嵌入回應。請檢查基底 URL。"],"AwrGuz": ["這份文件缺少必要的屬性"],"AyKwqp": ["位於你的主目錄中——此電腦上的每個專案,僅限你自己。"],@@ -894,6 +903,9 @@"D12vtS": ["(分離狀態)"],"D2emTw": ["傳送你的意見回饋時出了點問題。請再試一次。"],"D4H2N6": ["移除 ", ["tag"]],+ "D7gKrd": [+ "OpenKnowledge 無法在 .ok/local/terminal 下寫入啟動設定,因為該資料夾未安全地包含在此專案中。請確認它是專案內的真實資料夾,而不是連結。Claude 將要求你核准 OpenKnowledge。"+ ],"D7hnvB": ["思量中…"],"D8JJwQ": ["意見回饋功能目前無法使用。請稍後再試。"],"D8OV7J": ["僅協作者"],@@ -1378,6 +1390,9 @@"K6jxcj": ["新增索引鍵"],"K7NMEc": [["uploadFolderName"], " — ", ["0"], " 個檔案"],"K8-WWn": ["在表格儲存格之間移動"],+ "K8EvAV": [+ "OpenKnowledge 無法讀取 .ok/local/config.yml 中的 terminal.shell,將改用可用的 Windows shell。"+ ],"K9J00P": ["複製失敗——連線出錯"],"KDrbNG": ["OpenKnowledge 查詢了 ", ["subject"], " 的連結"],"KDuPiY": ["正在上傳 ", ["fileName"]],@@ -1391,6 +1406,9 @@"KOZud0": ["建立一個競品研究知識庫。先寫一頁總覽,再為每個競爭對手、他們的產品與定價,以及每項說法背後的來源,加上互相連結的頁面。"],+ "KOeFXa": [+ "OpenKnowledge 此次無法在 .ok/local/terminal 下寫入啟動設定。請確認該資料夾可寫入。Claude 將要求你核准 OpenKnowledge。"+ ],"KPW5WC": ["已移動範本"],"KQGZuq": ["如果已經存在就重複使用,否則就建立。"],"KRJ6xh": ["還沒有標籤。繼續輸入就能建立一個。"],@@ -3278,6 +3296,9 @@"kEiVv6": ["它們教你的 AI 工具如何使用 OpenKnowledge。安裝其中一個,會把它加入本機的每個 AI 工具。"],+ "kF2Yua": [+ "找不到 .ok/local/config.yml 中指定的 terminal.shell 執行檔,將改用可用的 Windows shell。"+ ],"kFLlsI": ["插入一個註腳參照,以及對應的定義草稿。"],"kGp168": ["無法為發布準備這個專案。"],"kI5pWt": ["找不到圖片:", ["errorLabel"]],diff --git a/packages/app/src/locales/zh-Hant/messages.po b/packages/app/src/locales/zh-Hant/messages.poindex a85a0495b..2460c37bc 100644--- a/packages/app/src/locales/zh-Hant/messages.po+++ b/packages/app/src/locales/zh-Hant/messages.po@@ -4729,12 +4729,10 @@ msgstr "正在中斷連接"#: src/components/BranchRecycleBanner.tsx#: src/components/BugReportSendToast.tsx-#: src/components/ClaudeReadinessBanner.tsx#: src/components/NavigatorApp.tsx#: src/components/OnboardingCard.tsx#: src/components/settings/SharingSection.tsx-#: src/components/TerminalCliMissingBanner.tsx-#: src/components/TerminalCliUnverifiedBanner.tsx+#: src/components/TerminalNoticeBanner.tsxmsgid "Dismiss"msgstr "關閉"@@ -9422,6 +9420,18 @@ msgstr "OpenKnowledge 檢查了衝突"msgid "OpenKnowledge checked the project"msgstr "OpenKnowledge 檢查了專案"+#: src/components/TerminalPanel.tsx+msgid "OpenKnowledge couldn't read terminal.shell in .ok/local/config.yml. Using an available Windows shell instead."+msgstr "OpenKnowledge 無法讀取 .ok/local/config.yml 中的 terminal.shell,將改用可用的 Windows shell。"++#: src/components/TerminalPanel.tsx+msgid "OpenKnowledge couldn't write launch settings under .ok/local/terminal because the folder is not safely contained in this project. Check that it is a real folder inside the project, not a link. Claude will ask you to approve OpenKnowledge."+msgstr "OpenKnowledge 無法在 .ok/local/terminal 下寫入啟動設定,因為該資料夾未安全地包含在此專案中。請確認它是專案內的真實資料夾,而不是連結。Claude 將要求你核准 OpenKnowledge。"++#: src/components/TerminalPanel.tsx+msgid "OpenKnowledge couldn't write launch settings under .ok/local/terminal this time. Check that the folder is writable. Claude will ask you to approve OpenKnowledge."+msgstr "OpenKnowledge 此次無法在 .ok/local/terminal 下寫入啟動設定。請確認該資料夾可寫入。Claude 將要求你核准 OpenKnowledge。"+#: src/lib/acp/tool-call-display.tsmsgid "OpenKnowledge created a share link"msgstr "OpenKnowledge 建立了分享連結"@@ -12342,6 +12352,10 @@ msgstr "Slidev 啟動逾時。請再試一次。"msgid "Small section heading."msgstr "小型章節標題。"+#: src/components/TerminalPanel.tsx+msgid "Some dropped files could not be inserted safely."+msgstr "部分拖放的檔案無法安全插入。"+#: src/components/SyncStatusBadge.tsxmsgid "Some files are not listed — the working tree has too many changes."msgstr "部分檔案未列出:工作區的變更過多。"@@ -13003,6 +13017,18 @@ msgstr "終端機設定尚未載入——請稍候再試。"msgid "Terminal settings not yet loaded — try again in a moment"msgstr "終端機設定尚未載入——請稍候再試"+#: src/components/TerminalPanel.tsx+msgid "terminal.shell in .ok/local/config.yml must be a string. Using an available Windows shell instead."+msgstr ".ok/local/config.yml 中的 terminal.shell 必須是字串,將改用可用的 Windows shell。"++#: src/components/TerminalPanel.tsx+msgid "terminal.shell in .ok/local/config.yml must be an absolute Windows path. Using an available Windows shell instead."+msgstr ".ok/local/config.yml 中的 terminal.shell 必須是 Windows 絕對路徑,將改用可用的 Windows shell。"++#: src/components/TerminalPanel.tsx+msgid "terminal.shell in .ok/local/config.yml supports PowerShell, cmd.exe, or Git Bash for OpenKnowledge-managed launches and dropped-file paths. This shell opens a plain terminal only; agent and command launches do not run in it."+msgstr ".ok/local/config.yml 中的 terminal.shell 支援使用 PowerShell、cmd.exe 或 Git Bash 執行 OpenKnowledge 管理的啟動以及插入拖放檔案的路徑。此 shell 僅開啟一般終端;代理程式和命令啟動無法在其中執行。"+#: src/components/settings/SearchSection.tsxmsgid "Test connection"msgstr "測試連線"@@ -13203,6 +13229,10 @@ msgstr "預覽會擋掉不符合它安全性規則的資源(例如純 http://msgid "The project's server is on a different branch than this window — content can't load."msgstr "該專案的伺服器所在分支與此視窗不一致,內容無法載入。"+#: src/components/TerminalPanel.tsx+msgid "The prompt was pasted but not submitted automatically. Review it, then press Enter to send it."+msgstr "提示詞已貼上,但未自動提交。請檢查內容,然後按 Enter 傳送。"+#: src/components/PropertyPanel.tsxmsgid "The properties block at the top of this doc has a formatting error. Switch to source mode to fix it."msgstr "這份文件最上面的屬性區塊有格式錯誤。請切換到原始碼模式修正。"@@ -13315,6 +13345,10 @@ msgstr "終端機工作階段已結束。"msgid "The terminal stopped unexpectedly."msgstr "終端機非預期地停止了。"+#: src/components/TerminalPanel.tsx+msgid "The terminal.shell executable in .ok/local/config.yml was not found. Using an available Windows shell instead."+msgstr "找不到 .ok/local/config.yml 中指定的 terminal.shell 執行檔,將改用可用的 Windows shell。"+#: src/components/AuthModal.tsxmsgid "The token needs the repo and read:user scopes."msgstr "這個權杖需要 repo 和 read:user 權限範圍。"diff --git a/packages/app/tests/stress/fixtures/handoff-mocks.ts b/packages/app/tests/stress/fixtures/handoff-mocks.tsindex 3fd3ee7c4..7c6ebd846 100644--- a/packages/app/tests/stress/fixtures/handoff-mocks.ts+++ b/packages/app/tests/stress/fixtures/handoff-mocks.ts@@ -637,6 +637,7 @@ export async function installHandoffMocks(page: Page, cfg: HandoffMockConfig): PsetDockState: async () => ({ ok: true as const }),onData: () => () => {},onExit: () => () => {},+ onNotice: () => () => {},claudePreflight: async () => ({ claude: 'present' as const, mcp: 'wired' as const }),cliPreflight: async () => ({ onPath: 'present' as const }),cliInstalledMap: async () => ({diff --git a/packages/core/src/config/field-registry.test.ts b/packages/core/src/config/field-registry.test.tsindex 000581e5f..0a2e9c7c1 100644--- a/packages/core/src/config/field-registry.test.ts+++ b/packages/core/src/config/field-registry.test.ts@@ -282,7 +282,7 @@ describe('ConfigSchema coverage (NR3 — every leaf has fieldRegistry metadata)']);});- test('project-local-strict fields cover autoSync.mode + autoSync.enabled + appearance.sidebar.* + linkPreviews.enabled + search.semantic.* + terminal.enabled', () => {+ test('project-local-strict fields cover autoSync.mode + autoSync.enabled + appearance.sidebar.* + linkPreviews.enabled + search.semantic.* + terminal.*', () => {// Project-local fields are per-machine, per-project: each teammate's// choice never crosses the git boundary.// `<projectDir>/.ok/local/config.yml` is gitignored and never mirrored@@ -334,6 +334,7 @@ describe('ConfigSchema coverage (NR3 — every leaf has fieldRegistry metadata)''server.idleShutdown','server.openBrowser','terminal.enabled',+ 'terminal.shell',]);});diff --git a/packages/core/src/config/merge-layered.test.ts b/packages/core/src/config/merge-layered.test.tsindex a1d039a52..c60ad6639 100644--- a/packages/core/src/config/merge-layered.test.ts+++ b/packages/core/src/config/merge-layered.test.ts@@ -214,6 +214,15 @@ describe('mergeLayered — scope-aware leaf short-circuits', () => {expect(merged.terminal?.enabled).toBe(true);});+ test("scope: 'project-local' (terminal.shell) returns only the machine-local override", () => {+ const user = makeConfig({ terminal: { shell: 'user-shell.exe' } });+ const project = makeConfig({ terminal: { shell: 'project-shell.exe' } });+ const projectLocal = makeConfig({ terminal: { shell: 'C:\\Tools\\pwsh.exe' } });++ const merged = mergeLayered(user, project, projectLocal);+ expect(merged.terminal?.shell).toBe('C:\\Tools\\pwsh.exe');+ });+test('a clone without the project-local layer resolves terminal.enabled to null (grant never inherited)', () => {// Simulates a fresh clone/checkout: the gitignored .ok/local/ layer is// absent, and terminal.enabled can never sit in the committed project filediff --git a/packages/core/src/config/schema-leaf.test.ts b/packages/core/src/config/schema-leaf.test.tsindex 0ee17fc06..76f5e91ae 100644--- a/packages/core/src/config/schema-leaf.test.ts+++ b/packages/core/src/config/schema-leaf.test.ts@@ -106,6 +106,17 @@ describe('getLeafFieldMeta', () => {});});+ test('resolves metadata for the project-local terminal.shell leaf', () => {+ const meta = getLeafFieldMeta(ConfigSchema, ['terminal', 'shell']);+ expect(meta).toEqual({+ scope: 'project-local',+ agentSettable: false,+ reload: 'live',+ defaultScope: 'project-local',+ description: expect.any(String),+ });+ });+test('resolves metadata for the committed autoSync.default union leaf (.register before wrappers)', () => {const meta = getLeafFieldMeta(ConfigSchema, ['autoSync', 'default']);expect(meta).toEqual({diff --git a/packages/core/src/config/schema.ts b/packages/core/src/config/schema.tsindex 2e51e6357..04c7cc177 100644--- a/packages/core/src/config/schema.ts+++ b/packages/core/src/config/schema.ts@@ -787,6 +787,17 @@ export const ConfigSchema = z.looseObject({}).nullable().default(null),+ shell: z+ .string()+ .register(fieldRegistry, {+ scope: 'project-local',+ agentSettable: false,+ reload: 'live',+ defaultScope: 'project-local',+ description:+ 'Absolute Windows shell executable override for the in-app terminal. PowerShell, cmd.exe, and Git Bash support OpenKnowledge-managed launches (agent chat tabs and fixed commands such as Resolve in terminal or Install Slidev) and dropped-file path insertion. A different existing executable remains usable for plain terminal tabs and shows a capability notice; requested agent and command launches open only the plain shell without running the agent or command, and dropped-file paths are refused. Empty values use automatic shell discovery. Per-machine (project-local), human-managed, and never shared via git, clone, or sync.',+ })+ .optional(),}).default({ enabled: null }),// USER-scope: whether the Slides plugin is offered is a personal preference,diff --git a/packages/core/src/config/write-config-patch.test.ts b/packages/core/src/config/write-config-patch.test.tsindex 9a2e0674a..ce323d353 100644--- a/packages/core/src/config/write-config-patch.test.ts+++ b/packages/core/src/config/write-config-patch.test.ts@@ -259,6 +259,20 @@ describe('writeConfigPatch — project-local scope', () => {expect(after).not.toContain('enabled: true');});+ test('persists terminal.shell only to .ok/local/config.yml', async () => {+ const result = await writeConfigPatch({+ cwd: testDir,+ scope: 'project-local',+ patch: { terminal: { shell: 'C:\\Tools\\pwsh.exe' } },+ });+ expect(result.ok).toBe(true);+ if (!result.ok) throw new Error('expected success');+ expect(result.appliedPaths).toContain('terminal.shell');+ expect(result.effective.terminal.shell).toBe('C:\\Tools\\pwsh.exe');+ expect(readFileSync(projectLocalConfigPath(), 'utf-8')).toContain('shell: C:\\Tools\\pwsh.exe');+ expect(existsSync(projectConfigPath())).toBe(false);+ });+test('terminal.enabled grant lands ONLY in the gitignored .ok/local/ file, never the committed project file', async () => {// The grant must never reach <cwd>/.ok/config.yml — that file is committed// and would carry the consent across a clone/sync/share, which the@@ -573,6 +587,26 @@ describe('writeConfigPatch — scope-violation gate', () => {expect(result.error.actualScope).toBe('user');expect(existsSync(userConfigPath(testDir))).toBe(false);});++ test.each([+ 'project',+ 'user',+ ] as const)('%s writer rejects terminal.shell with SCOPE_VIOLATION', async (scope) => {+ const result = await writeConfigPatch({+ cwd: testDir,+ scope,+ homedirOverride: testDir,+ patch: { terminal: { shell: 'C:\\Tools\\pwsh.exe' } },+ });+ expect(result.ok).toBe(false);+ if (result.ok) throw new Error('expected SCOPE_VIOLATION');+ if (!isKnownConfigError(result.error)) throw new Error('expected known error');+ expect(result.error.code).toBe('SCOPE_VIOLATION');+ if (result.error.code !== 'SCOPE_VIOLATION') throw new Error('wrong code');+ expect(result.error.path).toEqual(['terminal', 'shell']);+ expect(result.error.expectedScope).toBe('project-local');+ expect(result.error.actualScope).toBe(scope);+ });});describe('writeConfigPatch — concurrent writes (file lock)', () => {diff --git a/packages/core/src/desktop-bridge.test.ts b/packages/core/src/desktop-bridge.test.tsnew file mode 100644index 000000000..53dfd53ee--- /dev/null+++ b/packages/core/src/desktop-bridge.test.ts@@ -0,0 +1,64 @@+import { describe, expect, it } from 'vitest';+import {+ isTerminalShellNoticeReason,+ isTerminalSupportFileNoticeReason,+ TERMINAL_SHELL_NOTICE_REASONS,+ TERMINAL_SUPPORT_FILE_NOTICE_REASONS,+} from './desktop-bridge.ts';++// Spelled out here rather than read back from the module. The set and the union+// cannot disagree - both derive from one `as const` vocabulary tuple in the+// source - so there is no agreement left to test; what is worth pinning is the+// vocabulary itself, which the renderer's notice handling is written against.+// A rename or removal then has to be a deliberate edit on both sides.+const WIRE_REASONS = [+ 'config-unreadable',+ 'invalid-value',+ 'not-absolute',+ 'not-found',+ 'unsupported-family',+];+const SUPPORT_FILE_REASONS = ['containment-refused', 'write-failed'];++describe('TERMINAL_SHELL_NOTICE_REASONS', () => {+ it('exposes exactly the wire vocabulary', () => {+ expect([...TERMINAL_SHELL_NOTICE_REASONS].sort()).toEqual([...WIRE_REASONS].sort());+ });+});++describe('isTerminalShellNoticeReason', () => {+ it('accepts every reason in the wire vocabulary', () => {+ for (const reason of WIRE_REASONS) {+ expect(isTerminalShellNoticeReason(reason)).toBe(true);+ }+ });++ it('rejects unknown strings', () => {+ expect(isTerminalShellNoticeReason('unreadable')).toBe(false);+ expect(isTerminalShellNoticeReason('')).toBe(false);+ expect(isTerminalShellNoticeReason('Invalid-Value')).toBe(false);+ expect(isTerminalShellNoticeReason('__proto__')).toBe(false);+ });++ it('rejects non-string inputs (defends the IPC boundary against arbitrary payloads)', () => {+ expect(isTerminalShellNoticeReason(undefined)).toBe(false);+ expect(isTerminalShellNoticeReason(null)).toBe(false);+ expect(isTerminalShellNoticeReason(0)).toBe(false);+ expect(isTerminalShellNoticeReason(false)).toBe(false);+ expect(isTerminalShellNoticeReason({})).toBe(false);+ expect(isTerminalShellNoticeReason(['invalid-value'])).toBe(false);+ });+});++describe('terminal support-file notice reasons', () => {+ it('exposes and accepts exactly the wire vocabulary', () => {+ expect([...TERMINAL_SUPPORT_FILE_NOTICE_REASONS].sort()).toEqual(+ [...SUPPORT_FILE_REASONS].sort(),+ );+ for (const reason of SUPPORT_FILE_REASONS) {+ expect(isTerminalSupportFileNoticeReason(reason)).toBe(true);+ }+ expect(isTerminalSupportFileNoticeReason('escape')).toBe(false);+ expect(isTerminalSupportFileNoticeReason(null)).toBe(false);+ });+});diff --git a/packages/core/src/desktop-bridge.ts b/packages/core/src/desktop-bridge.tsindex e80aeda58..88e1e2988 100644--- a/packages/core/src/desktop-bridge.ts+++ b/packages/core/src/desktop-bridge.ts@@ -16,7 +16,11 @@ import type {WorktreeCreateResult,WorktreeListResult,} from './git/worktree-selector-model.ts';-import type { TerminalCli } from './handoff/terminal-launch.ts';+import type {+ TerminalCli,+ TerminalLaunchCommand,+ WindowsShellFamily,+} from './handoff/terminal-launch.ts';import type { HandoffFailureReason, HandoffScope } from './handoff/types.ts';import type { LanguagePreference } from './i18n/locales.ts';import type {@@ -1280,7 +1284,13 @@ export interface OkPtyListEntry {/** Result of `terminal.adopt`. */export type OkPtyAdoptResult =- | { readonly ok: true; readonly replay: string }+ | {+ readonly ok: true;+ readonly replay: string;+ readonly shellFamily?: WindowsShellFamily;+ /** Standing capability notice restored when a live session is adopted after reload. */+ readonly shellNoticeReason?: Extract<TerminalShellNoticeReason, 'unsupported-family'>;+ }| { readonly ok: false; readonly reason: 'unknown-session' };/** Push payload for `ok:pty:data`. */@@ -1297,6 +1307,67 @@ export interface OkPtyExit {readonly error?: string;}+/** Add recoverable shell-resolution reasons here and nowhere else. */+const TERMINAL_SHELL_NOTICE_REASON_VOCABULARY = [+ 'config-unreadable',+ 'invalid-value',+ 'not-absolute',+ 'not-found',+ 'unsupported-family',+] as const;++/** Push payload for a recoverable PTY shell-resolution notice. */+export type TerminalShellNoticeReason = (typeof TERMINAL_SHELL_NOTICE_REASON_VOCABULARY)[number];++export const TERMINAL_SHELL_NOTICE_REASONS: ReadonlySet<TerminalShellNoticeReason> = new Set(+ TERMINAL_SHELL_NOTICE_REASON_VOCABULARY,+);++/** Guard the reason after its JSON IPC round-trip. */+export function isTerminalShellNoticeReason(value: unknown): value is TerminalShellNoticeReason {+ return (+ typeof value === 'string' &&+ TERMINAL_SHELL_NOTICE_REASONS.has(value as TerminalShellNoticeReason)+ );+}++const TERMINAL_SUPPORT_FILE_NOTICE_REASON_VOCABULARY = [+ 'containment-refused',+ 'write-failed',+] as const;++export type TerminalSupportFileNoticeReason =+ (typeof TERMINAL_SUPPORT_FILE_NOTICE_REASON_VOCABULARY)[number];++export const TERMINAL_SUPPORT_FILE_NOTICE_REASONS: ReadonlySet<TerminalSupportFileNoticeReason> =+ new Set(TERMINAL_SUPPORT_FILE_NOTICE_REASON_VOCABULARY);++export function isTerminalSupportFileNoticeReason(+ value: unknown,+): value is TerminalSupportFileNoticeReason {+ return (+ typeof value === 'string' &&+ TERMINAL_SUPPORT_FILE_NOTICE_REASONS.has(value as TerminalSupportFileNoticeReason)+ );+}++export type OkPtyNotice =+ | {+ readonly ptyId: string;+ readonly notice: 'invalid-shell-override';+ readonly reason: TerminalShellNoticeReason;+ }+ | {+ readonly ptyId: string;+ readonly notice: 'shell-resolved';+ readonly shellFamily: WindowsShellFamily;+ }+ | {+ readonly ptyId: string;+ readonly notice: 'support-file-degraded';+ readonly reason: TerminalSupportFileNoticeReason;+ };+/*** Claude Code readiness for the docked terminal.*/@@ -2136,7 +2207,7 @@ export interface OkDesktopBridge {create(opts: {cols: number;rows: number;- launchCommand?: string;+ launchCommand?: string | TerminalLaunchCommand;}): Promise<OkPtyCreateResult>;input(ptyId: string, data: string): void;resize(ptyId: string, cols: number, rows: number): void;@@ -2163,6 +2234,7 @@ export interface OkDesktopBridge {setDockState(state: OkTerminalDockStateUpdate): Promise<OkTerminalDockStateWriteResult>;onData(cb: (msg: OkPtyData) => void): OkUnsubscribe;onExit(cb: (msg: OkPtyExit) => void): OkUnsubscribe;+ onNotice(cb: (msg: OkPtyNotice) => void): OkUnsubscribe;claudePreflight(): Promise<ClaudeReadiness>;cliPreflight(cli: TerminalCli): Promise<CliReadiness>;/**diff --git a/packages/core/src/handoff/index.ts b/packages/core/src/handoff/index.tsindex 68e90c411..d501cde0b 100644--- a/packages/core/src/handoff/index.ts+++ b/packages/core/src/handoff/index.ts@@ -39,13 +39,23 @@ export {buildCliLaunchArgString,buildCliLaunchCommand,buildStartupInjectionBytes,+ buildWindowsCliLaunch,+ composeWindowsShellLaunchArgs,+ isWindowsShellFamily,+ launchWithoutSupportFile,OK_GATED_TOOL_NAMES,+ psQuoteArg,+ quoteWindowsShellPath,+ resolveWindowsShellFamily,shellSingleQuote,startupInjectionFor,TERMINAL_CLI_IDS,TERMINAL_CLIS,type TerminalCli,type TerminalCliInfo,+ type TerminalLaunchCommand,+ WINDOWS_SHELL_FAMILIES,+ type WindowsShellFamily,} from './terminal-launch.ts';export type {DocContext,diff --git a/packages/core/src/handoff/terminal-launch.test.ts b/packages/core/src/handoff/terminal-launch.test.tsindex bdbab0781..e294dbfee 100644--- a/packages/core/src/handoff/terminal-launch.test.ts+++ b/packages/core/src/handoff/terminal-launch.test.ts@@ -1,3 +1,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 { describe, expect, it } from 'vitest';import { MCP_SERVER_NAME } from '../constants/mcp.ts';import {@@ -5,11 +9,20 @@ import {buildCliLaunchArgString,buildCliLaunchCommand,buildStartupInjectionBytes,+ buildWindowsCliLaunch,+ composeWindowsShellLaunchArgs,+ encodePowerShellCommand,+ isWindowsShellFamily,+ launchWithoutSupportFile,OK_GATED_TOOL_NAMES,+ psQuoteArg,+ quoteWindowsShellPath,+ resolveWindowsShellFamily,shellSingleQuote,startupInjectionFor,TERMINAL_CLI_IDS,TERMINAL_CLIS,+ WINDOWS_SHELL_FAMILIES,} from './terminal-launch.ts';// The `--settings` JSON Claude launches carry to pre-approve OK's project@@ -90,6 +103,247 @@ describe('shellSingleQuote', () => {});});+describe('Windows launch composition', () => {+ it('quotes PowerShell arguments with doubled embedded single quotes', () => {+ expect(psQuoteArg("a'b")).toBe("'a''b'");+ expect(psQuoteArg('{"nested":"value"}')).toBe('\'{"nested":"value"}\'');+ });++ it('encodes PowerShell startup scripts as base64 UTF-16LE', () => {+ const script = "& 'native.exe' '--settings' '{\"nested\":\"a''''b\"}'";+ expect(Buffer.from(encodePowerShellCommand(script), 'base64').toString('utf16le')).toBe(script);+ });++ it('keeps Windows prompts out of argv and carries pre-approval through cmd-safe data', () => {+ const prompt = `review "quoted" JSON; & calc`;+ expect(+ buildWindowsCliLaunch('claude', prompt, {+ mcpPreApprove: true,+ autoApproveOkTools: true,+ }),+ ).toEqual({+ executable: 'claude',+ args: ['--settings', '.ok/local/terminal/claude-settings-mcp-tools.json'],+ supportFile: {+ kind: 'claude-settings',+ relativePath: '.ok/local/terminal/claude-settings-mcp-tools.json',+ contents: `{"enabledMcpjsonServers":["${MCP_SERVER_NAME}"],"permissions":{"allow":${OK_ALLOW},"ask":${OK_ASK}}}`,+ },+ });+ expect(buildWindowsCliLaunch('codex', prompt, { autoApproveOkTools: true })).toEqual({+ executable: 'codex',+ args: ['-c', `mcp_servers.${MCP_SERVER_NAME}.default_tools_approval_mode=approve`],+ });+ expect(buildWindowsCliLaunch('openclaw', prompt)).toEqual({+ executable: 'openclaw',+ args: ['chat'],+ });+ });++ it('degrades a support-file launch to the bare launch the same builder would emit', () => {+ const prompt = 'review the failing gate';+ for (const opts of [+ { mcpPreApprove: true },+ { autoApproveOkTools: true },+ { mcpPreApprove: true, autoApproveOkTools: true },+ ]) {+ const withSupport = buildWindowsCliLaunch('claude', prompt, opts);+ expect(withSupport.supportFile).toBeDefined();+ expect(launchWithoutSupportFile(withSupport)).toEqual(+ buildWindowsCliLaunch('claude', prompt, {}),+ );+ }+ });++ it('leaves a launch that carries no support file untouched', () => {+ const bare = buildWindowsCliLaunch('codex', null, { autoApproveOkTools: true });+ expect(launchWithoutSupportFile(bare)).toBe(bare);+ });++ it('cannot retain coupled arguments when degrading a support-file launch', () => {+ expect(+ launchWithoutSupportFile({+ executable: 'claude',+ args: ['--settings', 'unexpected.json', '--future-coupled-token'],+ supportFile: {+ kind: 'claude-settings',+ relativePath: '.ok/local/terminal/claude-settings-mcp-tools.json',+ contents: '{}',+ },+ }),+ ).toEqual({ executable: 'claude', args: [] });+ });++ it('composes PowerShell as -NoExit -EncodedCommand with quoted structured args', () => {+ const args = composeWindowsShellLaunchArgs('C:\\Program Files\\PowerShell\\7\\pwsh.exe', {+ executable: 'native.exe',+ args: ['--settings', '{"nested":"a\'b"}'],+ });+ expect(Array.isArray(args)).toBe(true);+ expect(args.slice(0, 2)).toEqual(['-NoExit', '-EncodedCommand']);+ expect(Buffer.from(args[2] ?? '', 'base64').toString('utf16le')).toBe(+ "& 'native.exe' '--settings' '{\"nested\":\"a''b\"}'",+ );+ });++ it('composes cmd as an owned /K command line and rejects BatBadBut-shaped batch args', () => {+ expect(+ composeWindowsShellLaunchArgs('C:\\Windows\\System32\\cmd.exe', {+ executable: 'npm',+ args: ['install', '-g', '@slidev/cli'],+ }),+ ).toBe('/K npm install -g @slidev/cli');+ expect(() =>+ composeWindowsShellLaunchArgs('C:\\Program Files\\PowerShell\\7\\pwsh.exe', {+ executable: 'agent.cmd',+ args: ['safe', '" & calc & "'],+ }),+ ).toThrow(/unsafe batch argument/);+ });++ it('base64-transports Git Bash argv across the MSYS parser without interpolation or byte loss', () => {+ const shell = 'C:\\Program Files\\Git\\bin\\bash.exe';+ expect(resolveWindowsShellFamily(shell)).toBe('bash');+ const launchTokens = [+ 'claude',+ '--settings',+ '.ok/local/terminal/settings with spaces.json',+ "'; calc #",+ 'trailing newline\n',+ ];+ const composed = composeWindowsShellLaunchArgs(shell, {+ executable: launchTokens[0] ?? '',+ args: launchTokens.slice(1),+ });+ expect(Array.isArray(composed)).toBe(true);+ if (!Array.isArray(composed)) throw new Error('expected Git Bash argv');++ expect(composed.slice(0, 3)).toEqual(['--login', '-i', '-c']);+ expect(composed[3]).toContain('base64 -d');+ const quotedArgvExpansion = '"$' + '{__ok_argv[@]}"';+ expect(composed[3]).toContain(quotedArgvExpansion);+ expect(composed[3]).not.toContain('claude');+ expect(composed[4]).toBe('bash');+ expect(+ Buffer.from(composed[5] ?? '', 'base64')+ .toString('utf8')+ .split('\u0000'),+ ).toEqual([...launchTokens, '']);+ });++ it('escapes dropped paths per shell and refuses cmd expansion surfaces', () => {+ expect(quoteWindowsShellPath('powershell', "C:\\Users\\O'Brien\\shot.png")).toBe(+ "'C:\\Users\\O''Brien\\shot.png'",+ );+ expect(quoteWindowsShellPath('cmd', 'C:\\Users\\A B\\shot.png')).toBe(+ '"C:\\Users\\A B\\shot.png"',+ );+ expect(quoteWindowsShellPath('cmd', 'C:\\Users\\%USERNAME%\\shot.png')).toBeNull();+ expect(quoteWindowsShellPath('cmd', 'C:\\Users\\!name!\\shot.png')).toBeNull();+ expect(quoteWindowsShellPath('bash', "C:\\Users\\O'Brien\\shot.png")).toBe(+ "'C:\\Users\\O'\\''Brien\\shot.png'",+ );+ });+});++/**+ * The first Bash on this host new enough to run the generated launch script, or+ * an empty string when there is none.+ *+ * `mapfile -d ''` — the NUL-delimited read the decoder is built on — arrived in+ * Bash 4.4, so mere presence is the wrong gate: macOS still ships 3.2 at+ * `/bin/bash`, where the same script parses cleanly and reads nothing at all.+ * Probing the version keeps the skip honest rather than green and vacuous. Set+ * `OK_TEST_BASH` to point the probe at a specific build.+ */+function findNulMapfileBash(): string {+ const candidates = [+ process.env.OK_TEST_BASH,+ 'bash',+ '/opt/homebrew/bin/bash',+ '/usr/local/bin/bash',+ '/bin/bash',+ ];+ for (const candidate of candidates) {+ if (candidate === undefined || candidate.length === 0) continue;+ const probe = spawnSync(candidate, ['-c', 'echo $BASH_VERSION'], { encoding: 'utf8' });+ if (probe.status !== 0) continue;+ const version = /^(\d+)\.(\d+)/.exec(probe.stdout.trim());+ if (version === null) continue;+ const major = Number(version[1]);+ const minor = Number(version[2]);+ if (major > 4 || (major === 4 && minor >= 4)) return candidate;+ }+ return '';+}++const NUL_MAPFILE_BASH = findNulMapfileBash();++describe('Git Bash structured launch, run by a real Bash', () => {+ // The sibling composition test decodes the payload in JavaScript, which proves+ // what OK encoded but not what Bash reconstructs from it. This one hands the+ // generated `-c` script to a real Bash and reads back the argv the launched+ // program actually received, so a decoder that loses a token — or silently+ // drops the empty and newline-tailed ones, the two the NUL framing exists for+ // — fails here instead of on a user's Windows box.+ it.skipIf(NUL_MAPFILE_BASH === '')(+ 'reconstructs every launch token byte-for-byte, empty argument and trailing newline included',+ () => {+ const dir = mkdtempSync(join(tmpdir(), 'ok-git-bash-launch-'));+ try {+ const capturedArgvPath = join(dir, 'argv');+ const capturePath = join(dir, 'capture.cjs');+ // Stands in for the agent CLI so the test stays deterministic and+ // offline: it records the argv Bash handed it, NUL-delimited so tokens+ // carrying spaces or newlines stay separable on the way back out.+ writeFileSync(+ capturePath,+ "const { writeFileSync } = require('node:fs');\n" ++ "writeFileSync(process.env.OK_CAPTURED_ARGV, [process.argv0, ...process.argv.slice(1)].join('\\0') + '\\0');\n",+ );++ const launchTokens = [+ process.execPath,+ capturePath,+ '--settings',+ '.ok/local/terminal/settings with spaces.json',+ "'; calc #",+ '',+ 'trailing newline\n',+ ];+ const composed = composeWindowsShellLaunchArgs('C:\\Program Files\\Git\\bin\\bash.exe', {+ executable: launchTokens[0] ?? '',+ args: launchTokens.slice(1),+ });+ if (!Array.isArray(composed)) throw new Error('expected Git Bash argv');++ const run = spawnSync(NUL_MAPFILE_BASH, composed, {+ // `HOME` points at the scratch dir so the login shell the script execs+ // last cannot read the developer's dotfiles, and stdin is closed so+ // that shell hits EOF and exits instead of waiting for input.+ env: { ...process.env, HOME: dir, OK_CAPTURED_ARGV: capturedArgvPath },+ stdio: ['ignore', 'pipe', 'pipe'],+ timeout: 20_000,+ encoding: 'utf8',+ });+ expect(run.error).toBeUndefined();+ // The exit code belongs to the interactive login shell the script execs+ // last, not to the decode, so the captured argv is the only oracle.+ expect(existsSync(capturedArgvPath), `bash stderr: ${run.stderr}`).toBe(true);++ // The capture script terminates the payload with a trailing NUL, so the+ // split has one trailing empty element past the last argument.+ expect(readFileSync(capturedArgvPath, 'utf8').split('\u0000')).toEqual([+ ...launchTokens,+ '',+ ]);+ } finally {+ rmSync(dir, { recursive: true, force: true });+ }+ },+ );+});+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(@@ -149,7 +403,7 @@ describe('buildCliLaunchCommand', () => {// Injection CLIs (Hermes) deliver the prompt out-of-band, not on the argv —// their command is the promptless `<bin> <subcommand>`, so the "prompt is the// final escaped arg" invariant doesn't apply. Covered by the injection tests.- if (startupInjectionFor(cli) != null) continue;+ if (startupInjectionFor(cli, 'darwin') != null) continue;const cmd = buildCliLaunchCommand(cli, "'; rm -rf / #", { mcpPreApprove: true });// Whatever fixed args precede it, the prompt is the final, escaped arg.expect(cmd.startsWith(`${TERMINAL_CLIS[cli].bin} `)).toBe(true);@@ -261,31 +515,42 @@ describe('buildStartupInjectionBytes', () => {it('returns null for CLIs that carry the prompt on the argv (nothing to inject)', () => {for (const cli of TERMINAL_CLI_IDS) {- if (startupInjectionFor(cli) != null) continue;- expect(buildStartupInjectionBytes(cli, 'hi')).toBeNull();+ if (startupInjectionFor(cli, 'darwin') != null) continue;+ expect(buildStartupInjectionBytes(cli, 'hi', 'darwin')).toBeNull();}});it('frames a Hermes prompt in bracketed paste + the registry submit byte', () => {// Bracketed paste (DEC 2004) makes the TUI treat the bytes as literal pasted// text, then `\r` submits the now-complete input.- expect(buildStartupInjectionBytes('hermes', 'do the thing')).toBe(+ expect(buildStartupInjectionBytes('hermes', 'do the thing', 'darwin')).toBe(`${START}do the thing${END}\r`,);});+ it('uses bracketed-paste delivery for every Windows CLI', () => {+ for (const cli of TERMINAL_CLI_IDS) {+ expect(startupInjectionFor(cli, 'win32')).toEqual(+ expect.objectContaining({ readyMarker: '\x1b[?2004h' }),+ );+ expect(buildStartupInjectionBytes(cli, '" & calc & "', 'win32')).toBe(+ `${START}" & calc & "${END}\r`,+ );+ }+ });+it('keeps a multi-line prompt intact inside the paste frame (no early submit)', () => {// A bare newline in a TUI input box normally submits; inside bracketed paste it// is preserved, so the whole multi-line prompt lands as one input.const multi = 'line one\nline two\nline three';- expect(buildStartupInjectionBytes('hermes', multi)).toBe(`${START}${multi}${END}\r`);+ expect(buildStartupInjectionBytes('hermes', multi, 'darwin')).toBe(`${START}${multi}${END}\r`);});it('strips ESC so the prompt cannot terminate the paste frame or inject a sequence', () => {// A literal END sentinel (or any ESC) in the prompt would break out of the// paste; every ESC byte is removed, neutralizing the break-out.const hostile = `abc${END}rm -rf /\x1b[2J`;- const bytes = buildStartupInjectionBytes('hermes', hostile);+ const bytes = buildStartupInjectionBytes('hermes', hostile, 'darwin');// Exactly one START and one END remain — the frame we added, not the payload's.expect(bytes).toBe(`${START}abc[201~rm -rf /[2J${END}\r`);expect(bytes?.split(START).length).toBe(2);@@ -294,12 +559,12 @@ describe('buildStartupInjectionBytes', () => {it('returns null for an empty/absent prompt (a promptless New-chat launch)', () => {for (const emptyPrompt of [null, undefined, ''] as const) {- expect(buildStartupInjectionBytes('hermes', emptyPrompt)).toBeNull();+ expect(buildStartupInjectionBytes('hermes', emptyPrompt, 'darwin')).toBeNull();}});it('Hermes waits on the DEC-2004 bracketed-paste-enable marker, with a cap beyond the debounce', () => {- const cfg = startupInjectionFor('hermes');+ const cfg = startupInjectionFor('hermes', 'darwin');// Keying on the terminal-protocol escape (not UI prose) is what makes the// ready detection language- and version-stable; it's also the exact// precondition for the paste to be honored.@@ -402,3 +667,52 @@ describe('OK auto-approve (autoApproveOkTools)', () => {);});});++// Spelled out here rather than read back from the module. The set and the union+// cannot disagree - both derive from one `as const` vocabulary tuple in the+// source - so there is no agreement left to test; what is worth pinning is the+// vocabulary itself, which the launch composers and the renderer's notice+// handling are written against.+const WIRE_FAMILIES = ['powershell', 'cmd', 'bash'];++describe('WINDOWS_SHELL_FAMILIES', () => {+ it('exposes exactly the wire vocabulary', () => {+ expect([...WINDOWS_SHELL_FAMILIES].sort()).toEqual([...WIRE_FAMILIES].sort());+ });+});++describe('isWindowsShellFamily', () => {+ it('accepts every family in the wire vocabulary', () => {+ for (const family of WIRE_FAMILIES) {+ expect(isWindowsShellFamily(family)).toBe(true);+ }+ });++ it('agrees with the resolver about what counts as a supported family', () => {+ for (const shell of [+ 'C:\\Program Files\\PowerShell\\7\\pwsh.exe',+ 'C:\\Windows\\System32\\cmd.exe',+ 'C:\\Program Files\\Git\\bin\\bash.exe',+ ]) {+ expect(isWindowsShellFamily(resolveWindowsShellFamily(shell))).toBe(true);+ }+ expect(resolveWindowsShellFamily('C:\\Windows\\System32\\wsl.exe')).toBeNull();+ });++ it('rejects unknown strings', () => {+ expect(isWindowsShellFamily('pwsh')).toBe(false);+ expect(isWindowsShellFamily('zsh')).toBe(false);+ expect(isWindowsShellFamily('')).toBe(false);+ expect(isWindowsShellFamily('PowerShell')).toBe(false);+ expect(isWindowsShellFamily('__proto__')).toBe(false);+ });++ it('rejects non-string inputs (defends the IPC boundary against arbitrary payloads)', () => {+ expect(isWindowsShellFamily(undefined)).toBe(false);+ expect(isWindowsShellFamily(null)).toBe(false);+ expect(isWindowsShellFamily(0)).toBe(false);+ expect(isWindowsShellFamily(false)).toBe(false);+ expect(isWindowsShellFamily({})).toBe(false);+ expect(isWindowsShellFamily(['cmd'])).toBe(false);+ });+});diff --git a/packages/core/src/handoff/terminal-launch.ts b/packages/core/src/handoff/terminal-launch.tsindex 8a98b1b17..d21b24560 100644--- a/packages/core/src/handoff/terminal-launch.ts+++ b/packages/core/src/handoff/terminal-launch.ts@@ -10,12 +10,11 @@* deep link, quoted-argv-byte budget for the PTY — see `PromptTransport` in* `prompt-composer.ts`), and threaded into either transport.*- * This module owns the shell-injection-safe wrapping. The terminal write is a- * FIXED `<bin> [<fixed-args>…] '<prompt>'` shape — never an arbitrary command.- * Both `<bin>` and any `<fixed-args>` come only from the {@link TERMINAL_CLIS}- * registry, never from user input. The prompt — the only user-influenced- * portion — is single-quote-wrapped so it can never break out of its argument- * or inject shell, regardless of what bytes the composed prompt carries.+ * This module owns the shell-injection-safe wrapping. POSIX uses a fixed+ * `<bin> [<fixed-args>…] '<prompt>'` command with single-quote containment.+ * Windows keeps `<bin>` and argv structured until the resolved shell composes+ * them, then delivers the prompt by bracketed paste so user text never crosses+ * a PowerShell, cmd, or Git Bash parse surface.*/import { MCP_SERVER_NAME } from '../constants/mcp.ts';@@ -39,6 +38,159 @@ export function shellSingleQuote(s: string): string {return `'${s.replace(/'/g, "'\\''")}'`;}+/** A CLI launch kept as data until the resolved Windows shell is known. */+export interface TerminalLaunchCommand {+ readonly executable: string;+ readonly args: readonly string[];+ /** Registry-authored support file materialized beneath the terminal cwd before+ * launch. This keeps JSON policy out of cmd/npm-shim argument parsing while+ * preserving per-launch settings rather than mutating the user's config. */+ readonly supportFile?: {+ readonly kind: 'claude-settings';+ readonly relativePath: string;+ readonly contents: string;+ };+}++/** Sole author of the support-file/argv coupling. */+function claudeSettingsFileArgs(relativePath: string): readonly string[] {+ return ['--settings', relativePath];+}++/**+ * The launch to run when its support file could not be materialized. The file+ * and every argument are one coupled, registry-authored unit, so no argument is+ * safe to retain without the file. Degrade to the bare executable and let the+ * CLI run its own trust flow instead of cancelling the terminal.+ */+export function launchWithoutSupportFile(launch: TerminalLaunchCommand): TerminalLaunchCommand {+ if (launch.supportFile === undefined) return launch;+ return { executable: launch.executable, args: [] };+}++/** Add Windows shell families here and nowhere else. */+const WINDOWS_SHELL_FAMILY_VOCABULARY = ['powershell', 'cmd', 'bash'] as const;++export type WindowsShellFamily = (typeof WINDOWS_SHELL_FAMILY_VOCABULARY)[number];++export const WINDOWS_SHELL_FAMILIES: ReadonlySet<WindowsShellFamily> = new Set(+ WINDOWS_SHELL_FAMILY_VOCABULARY,+);++/** Guard the resolved family after its JSON IPC round-trip. */+export function isWindowsShellFamily(value: unknown): value is WindowsShellFamily {+ return typeof value === 'string' && WINDOWS_SHELL_FAMILIES.has(value as WindowsShellFamily);+}++/** PowerShell's verbatim single-quoted string form. */+export function psQuoteArg(value: string): string {+ return `'${value.replace(/'/g, "''")}'`;+}++function encodeUtf8Base64(value: string): string {+ const bytes = new TextEncoder().encode(value);+ let binary = '';+ for (const byte of bytes) binary += String.fromCharCode(byte);+ return btoa(binary);+}++const BASH_STRUCTURED_LAUNCH_SCRIPT =+ `mapfile -d '' -t __ok_argv < <(printf '%s' "$1" | base64 -d); ` ++ `((\${#__ok_argv[@]})) || exit 1; "\${__ok_argv[@]}"; exec "$BASH" --login -i`;++/** Encode a PowerShell startup script for `-EncodedCommand` without Node-only APIs. */+export function encodePowerShellCommand(script: string): string {+ let binary = '';+ for (let i = 0; i < script.length; i += 1) {+ const codeUnit = script.charCodeAt(i);+ binary += String.fromCharCode(codeUnit & 0xff, codeUnit >>> 8);+ }+ return btoa(binary);+}++/** Classify only the Windows shells whose launch semantics OK supports. */+export function resolveWindowsShellFamily(shell: string): WindowsShellFamily | null {+ const base = shell.split(/[\\/]/).at(-1)?.toLowerCase();+ if (+ base === 'pwsh' ||+ base === 'pwsh.exe' ||+ base === 'powershell' ||+ base === 'powershell.exe'+ ) {+ return 'powershell';+ }+ if (base === 'cmd' || base === 'cmd.exe') return 'cmd';+ if (base === 'bash' || base === 'bash.exe') return 'bash';+ return null;+}++function isCmdSafeToken(value: string): boolean {+ return (+ value.length > 0 &&+ !Array.from(value).some((ch) => ch.charCodeAt(0) < 0x20) &&+ !/[\s"%!&|<>^()]/u.test(value)+ );+}++/**+ * Compose the exact node-pty argv shape for a resolved Windows shell.+ * PowerShell receives CRT-safe array args; cmd receives an owned string because+ * its parser does not implement CommandLineToArgvW escaping.+ */+export function composeWindowsShellLaunchArgs(+ shell: string,+ launch: TerminalLaunchCommand,+): string[] | string {+ const family = resolveWindowsShellFamily(shell);+ if (family === null) throw new Error('unsupported Windows terminal shell');+ if (+ launch.executable.length === 0 ||+ launch.executable.includes('\u0000') ||+ launch.args.some((arg) => arg.includes('\u0000'))+ ) {+ throw new Error('invalid Windows terminal launch');+ }+ if (family === 'bash') {+ // Git for Windows applies an MSYS parsing pass before `bash -c`; raw+ // apostrophes can be stripped even when node-pty received an argv array.+ // Base64 keeps every launch token parser-inert. The fixed script decodes+ // one NUL-delimited payload into a quoted Bash array; the delimiters also+ // preserve empty arguments and trailing newlines without one process per+ // token.+ return [+ '--login',+ '-i',+ '-c',+ BASH_STRUCTURED_LAUNCH_SCRIPT,+ 'bash',+ encodeUtf8Base64(`${[launch.executable, ...launch.args].join('\u0000')}\u0000`),+ ];+ }+ const batchTarget = /\.(?:cmd|bat)$/iu.test(launch.executable);+ if (family === 'cmd' || batchTarget) {+ const tokens = [launch.executable, ...launch.args];+ if (tokens.some((token) => !isCmdSafeToken(token))) {+ throw new Error('unsafe batch argument');+ }+ if (family === 'cmd') return `/K ${tokens.join(' ')}`;+ }+ const script = `& ${psQuoteArg(launch.executable)}${launch.args+ .map((arg) => ` ${psQuoteArg(arg)}`)+ .join('')}`;+ return ['-NoExit', '-EncodedCommand', encodePowerShellCommand(script)];+}++/** Quote a dropped Windows path for the resolved interactive shell. */+export function quoteWindowsShellPath(family: WindowsShellFamily, path: string): string | null {+ if (path.length === 0 || Array.from(path).some((ch) => ch.charCodeAt(0) < 0x20)) return null;+ if (family === 'powershell') return psQuoteArg(path);+ if (family === 'bash') return shellSingleQuote(path);+ // cmd expands `%VAR%` and delayed `!VAR!` even inside double quotes. Refuse+ // those paths instead of claiming an escape that cmd does not provide.+ if (/["%!]/u.test(path)) return null;+ return `"${path}"`;+}+/*** The agent CLIs the docked terminal can launch. Each starts an INTERACTIVE* session that stays open with the composed prompt threaded in — NOT the@@ -192,7 +344,7 @@ const CODEX_OK_AUTO_APPROVE_ARG = `-c ${shellSingleQuote(* so nothing is written to disk. Returns '' when neither opt-in is set. Content is* registry-fixed and single-quoted — never user input.*/-function buildClaudeSettingsArg(opts: BuildCliLaunchOptions): string {+function buildClaudeSettingsJson(opts: BuildCliLaunchOptions): string | null {const settings: {enabledMcpjsonServers?: string[];permissions?: { allow: string[]; ask: string[] };@@ -207,9 +359,14 @@ function buildClaudeSettingsArg(opts: BuildCliLaunchOptions): string {};}if (settings.enabledMcpjsonServers === undefined && settings.permissions === undefined) {- return '';+ return null;}- return `--settings ${shellSingleQuote(JSON.stringify(settings))}`;+ return JSON.stringify(settings);+}++function buildClaudeSettingsArg(opts: BuildCliLaunchOptions): string {+ const settingsJson = buildClaudeSettingsJson(opts);+ return settingsJson === null ? '' : `--settings ${shellSingleQuote(settingsJson)}`;}/**@@ -234,9 +391,17 @@ const BRACKETED_PASTE_END = `${ESC}[201~`;* the hard fallback: inject anyway if the marker never appears (e.g. a future* Hermes that changed its ready signal), so the prompt is never silently dropped.*/-const HERMES_READY_MARKER = '\x1b[?2004h';+const BRACKETED_PASTE_ENABLE_MARKER = '\x1b[?2004h';const HERMES_INJECT_DEBOUNCE_MS = 300;const HERMES_INJECT_CAP_MS = 4000;+const WINDOWS_INJECT_SETTLE_MS = 800;+const WINDOWS_INJECT_CAP_MS = 4000;+const WINDOWS_STARTUP_INJECTION: NonNullable<TerminalCliInfo['startupInjection']> = {+ submit: '\r',+ readyMarker: BRACKETED_PASTE_ENABLE_MARKER,+ settleMs: WINDOWS_INJECT_SETTLE_MS,+ capMs: WINDOWS_INJECT_CAP_MS,+};/*** Static registry for each launchable CLI. Cursor's agent CLI binary is@@ -336,7 +501,7 @@ export const TERMINAL_CLIS = {handoffTarget: 'hermes',startupInjection: {submit: '\r',- readyMarker: HERMES_READY_MARKER,+ readyMarker: BRACKETED_PASTE_ENABLE_MARKER,settleMs: HERMES_INJECT_DEBOUNCE_MS,capMs: HERMES_INJECT_CAP_MS,},@@ -383,6 +548,56 @@ export interface BuildCliLaunchOptions {readonly autoApproveOkTools?: boolean;}+/**+ * Build the Windows half of an agent launch as structured data. The prompt is+ * deliberately absent: Windows delivers it after the TUI starts via bracketed+ * paste, so user text never crosses PowerShell, cmd, or Git Bash parsing. JSON-bearing+ * Claude's JSON policy is carried in a registry-authored project-local support+ * file because a PATH binary may resolve to an npm `.cmd` shim whose second-hop+ * argument parser cannot safely preserve inline JSON. Codex uses an unquoted+ * literal config value, which remains two cmd-safe argv tokens.+ */+export function buildWindowsCliLaunch(+ cli: TerminalCli,+ _prompt: string | null | undefined,+ opts: BuildCliLaunchOptions = {},+): TerminalLaunchCommand {+ const info: TerminalCliInfo = TERMINAL_CLIS[cli];+ if (cli === 'claude') {+ const settingsJson = buildClaudeSettingsJson(opts);+ if (settingsJson !== null) {+ const variant = [+ opts.mcpPreApprove === true ? 'mcp' : null,+ opts.autoApproveOkTools === true ? 'tools' : null,+ ]+ .filter((part): part is string => part !== null)+ .join('-');+ const relativePath = `.ok/local/terminal/claude-settings-${variant}.json`;+ return {+ executable: info.bin,+ args: [...claudeSettingsFileArgs(relativePath)],+ supportFile: {+ kind: 'claude-settings',+ relativePath,+ contents: settingsJson,+ },+ };+ }+ }+ if (cli === 'codex' && opts.autoApproveOkTools === true) {+ // Codex treats a non-TOML override value as a literal string. Keeping the+ // value unquoted makes the two argv tokens safe through cmd and npm shims.+ return {+ executable: info.bin,+ args: ['-c', `mcp_servers.${MCP_SERVER_NAME}.default_tools_approval_mode=approve`],+ };+ }+ return {+ executable: info.bin,+ args: info.subcommand ? [info.subcommand] : [],+ };+}+/*** Build the fixed `<bin> [<fixed-args>…] '<prompt>'` launch shape WITHOUT a* trailing newline — the CLI's registry binary, then the opted-in fixed args@@ -482,21 +697,25 @@ export function buildClaudeLaunchCommand(prompt: string, opts: BuildCliLaunchOpt* This is the only user-influenced portion; everything around it is registry-fixed.*//**- * The startup-injection descriptor for a CLI, or `undefined` when it delivers its- * prompt on the argv. A typed accessor so consumers don't cast around the- * `as const satisfies` registry's per-entry literal types (which drop optional- * fields from members that don't set them).+ * The startup-injection descriptor for a CLI. Windows supplies a safe default+ * for every CLI because prompts never ride argv there; POSIX returns a registry+ * descriptor only for CLIs that cannot accept an argv prompt. A typed accessor+ * keeps consumers from casting around the registry's per-entry literal types.*/-export function startupInjectionFor(cli: TerminalCli): TerminalCliInfo['startupInjection'] {+export function startupInjectionFor(+ cli: TerminalCli,+ platform: NodeJS.Platform,+): TerminalCliInfo['startupInjection'] {const info: TerminalCliInfo = TERMINAL_CLIS[cli];- return info.startupInjection;+ return info.startupInjection ?? (platform === 'win32' ? WINDOWS_STARTUP_INJECTION : undefined);}export function buildStartupInjectionBytes(cli: TerminalCli,prompt: string | null | undefined,+ platform: NodeJS.Platform,): string | null {- const injection = startupInjectionFor(cli);+ const injection = startupInjectionFor(cli, platform);if (injection == null || prompt == null || prompt.length === 0) return null;// Strip ESC (0x1b) — the byte that would let the prompt terminate the paste// frame early or smuggle in a control sequence. A plain-string `replaceAll`diff --git a/packages/core/src/index.ts b/packages/core/src/index.tsindex affd2bb8a..ea3db02fa 100644--- a/packages/core/src/index.ts+++ b/packages/core/src/index.ts@@ -587,6 +587,7 @@ export {buildCodexUrl,buildCursorUrl,buildStartupInjectionBytes,+ buildWindowsCliLaunch,type ComposeSelection,type CreateScenario,composeAskProjectPrompt,@@ -601,6 +602,7 @@ export {composeSkillPrompt,composeTerminalBareLaunchPrompt,composeThreadBareLaunchPrompt,+ composeWindowsShellLaunchArgs,type DocContext,type HandoffFailureReason,type HandoffOutcome,@@ -610,13 +612,18 @@ export {type InstallState,type IpcChannelReason,type IpcChannelWithUrn,+ isWindowsShellFamily,type LintFixPromptInput,+ launchWithoutSupportFile,lookupUrnInRegistry,OK_GATED_TOOL_NAMES,OK_PROJECT_SKILL_POINTER,OK_TERMINAL_SURFACE_PREAMBLE,OK_THREAD_SURFACE_PREAMBLE,type PromptTransport,+ psQuoteArg,+ quoteWindowsShellPath,+ resolveWindowsShellFamily,shellSingleQuote,startupInjectionFor,type TargetData,@@ -625,9 +632,12 @@ export {TERMINAL_INLINE_PROMPT_BUDGET,type TerminalCli,type TerminalCliInfo,+ type TerminalLaunchCommand,URN_HTTP_ONLY,URN_IPC_REGISTRY,type UrnIpcLookup,+ WINDOWS_SHELL_FAMILIES,+ type WindowsShellFamily,withSkillPointer,} from './handoff/index.ts';// Interface locales — the single source of truth the config enum, the Linguidiff --git a/packages/desktop/electron-builder.yml b/packages/desktop/electron-builder.ymlindex e5ead8f8a..44390ce4d 100644--- a/packages/desktop/electron-builder.yml+++ b/packages/desktop/electron-builder.yml@@ -196,6 +196,14 @@ asarUnpack:# The prebuilt spawn-helper ships mode 0644 (node-pty#850) — scripts/afterPack.mjs# chmods it 0755 before signing; the unpack rule and that chmod move in lockstep.- "**/node-pty/prebuilds/**"+ # On Windows node-pty reads ConPTY output on a worker thread+ # (lib/worker/conoutSocketWorker.js). worker_threads cannot load JS from+ # inside an asar, and the worker's CJS require() resolution needs node-pty's+ # package.json on the real filesystem beside lib/ — VS Code unpacks the same+ # set. Darwin/Linux never reach this path (the conout worker is win32-only+ # code), so unpacking these everywhere is layout-only, not behavioral.+ - "**/node-pty/lib/**"+ - "**/node-pty/package.json"mac:category: public.app-category.productivity@@ -397,17 +405,37 @@ win:# belong hardcoded here while unknown. Unsigned Windows artifacts are# never published (internal QA only).#- # The terminal dock is dark on Windows: node-pty and its- # prebuilds must not ship in the Windows package. `files` merges with the- # top-level list.+ # node-pty ships in the Windows package: the terminal runs on ConPTY via the+ # win32 prebuilds. `files` merges with the top-level list. The prune mirrors+ # the Linux block (no foreign-platform prebuilds, no ~10 MB/arch .pdb debug+ # symbols), and BOTH win32 arch prebuilds stay in BOTH per-arch installers —+ # the addon picks prebuilds/win32-<process.arch> at runtime, which keeps+ # x64-under-emulation working on arm64 hosts.+ #+ # Unlike Linux (whose overlay skips the rebuild pass entirely), mac/win keep+ # @electron/rebuild enabled, and node-pty's node-gyp output under build/+ # shadows the prebuilds at require() time — a cross-arch build would then+ # ship builder-host binaries. Pruning build/** makes the per-arch prebuild+ # the only loadable addon. third_party/ is ConPTY C++ source weight with no+ # runtime role.## native-config's cargo `target/` tree is darwin build intermediates that# the blanket asarUnpack rule would otherwise drag in. Beyond dead weight,# its `.fingerprint` paths nest past MAX_PATH under the install dir and# the x86 NSIS uninstaller cannot delete them (VM-verified residue).files:- - "!**/node_modules/node-pty/**"+ - "!**/node_modules/node-pty/prebuilds/**/*.pdb"+ - "!**/node_modules/node-pty/prebuilds/darwin-*/**"+ - "!**/node_modules/node-pty/prebuilds/linux-*/**"+ - "!**/node_modules/node-pty/build/**"+ - "!**/node_modules/node-pty/third_party/**"- "!**/node_modules/@inkeep/open-knowledge-native-config/target/**"+ # conpty.dll + OpenConsole.exe (under prebuilds/win32-*/conpty/) ship with+ # Microsoft's Authenticode signatures and must keep them — re-signing would+ # replace Microsoft's signature with ours and split the pair's provenance.+ # The signing pass covers .exe files only, so this negative pattern excludes+ # the one Microsoft .exe; conpty.dll is never in the default signing set.+ signExts: ["!OpenConsole.exe"]extraResources:- from: "resources/cli/bin/ok.cmd"to: "cli/bin/ok.cmd"diff --git a/packages/desktop/scripts/assert-asar-complete.mjs b/packages/desktop/scripts/assert-asar-complete.mjsindex c0523f7f7..c02e3506c 100644--- a/packages/desktop/scripts/assert-asar-complete.mjs+++ b/packages/desktop/scripts/assert-asar-complete.mjs@@ -20,16 +20,20 @@* <search-root> directory to find app.asar under (e.g. dist-desktop)*/-import { closeSync, existsSync, openSync, readdirSync, readSync, statSync } from 'node:fs';+import { existsSync, readdirSync, statSync } from 'node:fs';import { join } from 'node:path';+import { readAsarHeader } from './lib/asar-header.mjs';/*** Packages asserted present by name. `pino` is the one that actually broke —* `desktop-logger` imports it at module scope, so it is the first bare specifier* the main process resolves and thus the observed failure. The others are listed* so a partial collection (rather than a wholesale omission) still fails.+ * `node-pty` pins the terminal payload on every platform: the win files rules+ * once excluded it wholesale, and a regressed exclude would ship a+ * dead-on-arrival terminal while every other packaging control stays green.*/-const REQUIRED_PACKAGES = ['pino', 'electron-updater'];+const REQUIRED_PACKAGES = ['pino', 'electron-updater', 'node-pty'];/*** EVERY asar under the root, not the first one found. A single `electron-builder@@ -60,32 +64,6 @@ function findAsars(root) {return found.sort();}-/** Guards against a truncated or corrupt asar producing a bare stack trace. */-const MAX_HEADER_BYTES = 64 * 1024 * 1024;--function readAsarHeader(asarPath) {- const fd = openSync(asarPath, 'r');- try {- const prefix = Buffer.alloc(16);- if (readSync(fd, prefix, 0, 16, 0) < 16) {- throw new Error('file is shorter than the 16-byte asar header prefix');- }- const jsonSize = prefix.readUInt32LE(12);- if (jsonSize === 0 || jsonSize > MAX_HEADER_BYTES) {- throw new Error(- `implausible asar header length (${jsonSize} bytes) — file is not a valid asar`,- );- }- const json = Buffer.alloc(jsonSize);- if (readSync(fd, json, 0, jsonSize, 16) < jsonSize) {- throw new Error(`asar header truncated (wanted ${jsonSize} bytes)`);- }- return JSON.parse(json.toString('utf8'));- } finally {- closeSync(fd);- }-}-const searchRoot = process.argv[2];const label = process.argv[3] ?? searchRoot;diff --git a/packages/desktop/scripts/lib/asar-header.mjs b/packages/desktop/scripts/lib/asar-header.mjsnew file mode 100644index 000000000..1f95b5bd7--- /dev/null+++ b/packages/desktop/scripts/lib/asar-header.mjs@@ -0,0 +1,28 @@+import { closeSync, openSync, readSync } from 'node:fs';++/** Prevent a corrupt prefix from allocating an attacker-sized buffer. */+export const MAX_ASAR_HEADER_BYTES = 64 * 1024 * 1024;++/** Read and parse the bounded JSON directory header from an Electron asar. */+export function readAsarHeader(asarPath) {+ const fd = openSync(asarPath, 'r');+ try {+ const prefix = Buffer.alloc(16);+ if (readSync(fd, prefix, 0, 16, 0) < 16) {+ throw new Error('file is shorter than the 16-byte asar header prefix');+ }+ const jsonSize = prefix.readUInt32LE(12);+ if (jsonSize === 0 || jsonSize > MAX_ASAR_HEADER_BYTES) {+ throw new Error(+ `implausible asar header length (${jsonSize} bytes) — file is not a valid asar`,+ );+ }+ const json = Buffer.alloc(jsonSize);+ if (readSync(fd, json, 0, jsonSize, 16) < jsonSize) {+ throw new Error(`asar header truncated (wanted ${jsonSize} bytes)`);+ }+ return JSON.parse(json.toString('utf8'));+ } finally {+ closeSync(fd);+ }+}diff --git a/packages/desktop/scripts/smoke-linux-terminal-package.py b/packages/desktop/scripts/smoke-linux-terminal-package.pydeleted file mode 100755index 21dc0da18..000000000--- a/packages/desktop/scripts/smoke-linux-terminal-package.py+++ /dev/null@@ -1,117 +0,0 @@-#!/usr/bin/env python3-"""Drive one PTY echo through the installed app's smoke-only preload bridge."""--import json-import sys-import time-import urllib.request-from typing import Dict, Optional--import websocket---DEBUG_TARGETS_URL = "http://127.0.0.1:9222/json/list"-MARKER = "OK_PACKAGED_LINUX_PTY_ECHO"---def find_page_websocket() -> str:- deadline = time.monotonic() + 20- last_error: Optional[Exception] = None- while time.monotonic() < deadline:- try:- with urllib.request.urlopen(DEBUG_TARGETS_URL, timeout=2) as response:- targets = json.load(response)- for target in targets:- if target.get("type") == "page" and target.get("webSocketDebuggerUrl"):- return str(target["webSocketDebuggerUrl"])- except Exception as error: # The app may still be creating its first page.- last_error = error- time.sleep(0.25)- raise RuntimeError(f"no renderer debug target appeared: {last_error}")---def evaluate_pty_echo(socket_url: str) -> Dict[str, object]:- connection = websocket.create_connection(socket_url, timeout=30, origin="http://localhost")- expression = f"""- (async () => {{- const bridge = window.okDesktop;- if (!bridge?.config?.ptyAvailable) {{- throw new Error('packaged renderer did not expose Linux PTY capability');- }}- const marker = {json.dumps(MARKER)};- return await new Promise(async (resolve, reject) => {{- let output = '';- let ptyId = null;- let unsubscribe = () => {{}};- const finish = async (error) => {{- clearTimeout(timeout);- unsubscribe();- if (ptyId !== null) await bridge.terminal.kill(ptyId).catch(() => {{}});- if (error) reject(error);- else resolve({{ marker, output }});- }};- const timeout = setTimeout(- () => void finish(new Error(`PTY echo timed out; output=${{JSON.stringify(output)}}`)),- 20000,- );- unsubscribe = bridge.terminal.onData((message) => {{- if (message.ptyId !== ptyId) return;- output += message.data;- if (output.includes(marker)) void finish(null);- }});- const created = await bridge.terminal.create({{ cols: 80, rows: 24 }});- if (!created.ok) {{- await finish(new Error(`PTY create failed: ${{created.reason}}`));- return;- }}- ptyId = created.ptyId;- bridge.terminal.input(ptyId, `printf '${{marker}}\\n'\r`);- }});- }})()- """- request = {- "id": 1,- "method": "Runtime.evaluate",- "params": {- "expression": expression,- "awaitPromise": True,- "returnByValue": True,- },- }- connection.send(json.dumps(request))- try:- while True:- message = json.loads(connection.recv())- if message.get("id") != 1:- continue- if "error" in message:- raise RuntimeError(f"CDP evaluation failed: {message['error']}")- result = message.get("result", {})- if result.get("exceptionDetails"):- detail = result["exceptionDetails"]- exception = detail.get("exception", {}).get("description")- raise RuntimeError(exception or detail.get("text", "renderer evaluation threw"))- value = result.get("result", {}).get("value")- if not isinstance(value, dict):- raise RuntimeError(f"renderer returned no PTY smoke result: {result}")- return value- finally:- connection.close()---def main() -> int:- try:- result = evaluate_pty_echo(find_page_websocket())- except Exception as error:- print(f"ERROR: packaged PTY echo failed: {error}", file=sys.stderr)- return 1- output = str(result.get("output", ""))- if MARKER not in output:- print(f"ERROR: PTY output omitted marker; output={output!r}", file=sys.stderr)- return 1- print(f"PTY echo marker observed: {MARKER}")- return 0---if __name__ == "__main__":- raise SystemExit(main())diff --git a/packages/desktop/scripts/smoke-linux-terminal-package.sh b/packages/desktop/scripts/smoke-linux-terminal-package.shindex 9798ad69e..d74f479d1 100755--- a/packages/desktop/scripts/smoke-linux-terminal-package.sh+++ b/packages/desktop/scripts/smoke-linux-terminal-package.sh@@ -21,7 +21,7 @@ set -euo pipefail# OK_CONTAINER_SANDBOX=disable to use --no-sandbox immediately.SCRIPT_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd -P)-DRIVER_PATH="$SCRIPT_DIR/smoke-linux-terminal-package.py"+DRIVER_PATH="$SCRIPT_DIR/smoke-terminal-package-cdp.py"usage() {printf '%s\n' \@@ -197,7 +197,7 @@ inside_container() {fifi- runuser -u ok-smoke -- python3 /tmp/smoke-linux-terminal-package.py+ runuser -u ok-smoke -- python3 /tmp/smoke-terminal-package-cdp.pyprintf 'PASS: installed %s package launched and completed a packaged PTY echo round-trip\n' "$requested_arch"}@@ -252,7 +252,7 @@ host_main() {--platform "$(docker_platform "$normalized_arch")" \--mount "type=bind,src=$absolute_package,dst=$container_artifact,readonly" \--mount "type=bind,src=$SCRIPT_DIR/smoke-linux-terminal-package.sh,dst=/tmp/smoke-linux-terminal-package.sh,readonly" \- --mount "type=bind,src=$DRIVER_PATH,dst=/tmp/smoke-linux-terminal-package.py,readonly" \+ --mount "type=bind,src=$DRIVER_PATH,dst=/tmp/smoke-terminal-package-cdp.py,readonly" \--env "OK_CONTAINER_SANDBOX=${OK_CONTAINER_SANDBOX:-auto}" \"$image" \bash /tmp/smoke-linux-terminal-package.sh \diff --git a/packages/desktop/scripts/smoke-terminal-package-cdp.py b/packages/desktop/scripts/smoke-terminal-package-cdp.pynew file mode 100755index 000000000..3e76ae1d6--- /dev/null+++ b/packages/desktop/scripts/smoke-terminal-package-cdp.py@@ -0,0 +1,213 @@+#!/usr/bin/env python3+"""Drive one PTY echo through a packaged app's preload bridge."""++import json+import os+import sys+import time+import urllib.request+from typing import Dict, List, Optional, Tuple++import websocket+++DEBUG_TARGETS_URL = "http://127.0.0.1:9222/json/list"+MARKER = "OK_PACKAGED_PTY_ECHO"+MAX_OBSERVED_TARGETS = 8+MAX_TARGET_FIELD_LENGTH = 160+++def summarize_target(target: Dict[str, object]) -> Tuple[str, str, str]:+ def bounded(field: str) -> str:+ return str(target.get(field, ""))[:MAX_TARGET_FIELD_LENGTH]++ return (bounded("type"), bounded("url"), bounded("title"))+++def record_observed_target(+ observed_targets: List[Tuple[str, str, str]], target: Dict[str, object]+) -> None:+ summary = summarize_target(target)+ if summary in observed_targets:+ observed_targets.remove(summary)+ observed_targets.append(summary)+ del observed_targets[:-MAX_OBSERVED_TARGETS]+++def evaluate_value(socket_url: str, expression: str, timeout: float = 5) -> object:+ connection = websocket.create_connection(+ socket_url, timeout=timeout, origin="http://localhost"+ )+ request = {+ "id": 1,+ "method": "Runtime.evaluate",+ "params": {+ "expression": expression,+ "awaitPromise": True,+ "returnByValue": True,+ },+ }+ connection.send(json.dumps(request))+ try:+ while True:+ message = json.loads(connection.recv())+ if message.get("id") != 1:+ continue+ if "error" in message:+ raise RuntimeError(f"CDP evaluation failed: {message['error']}")+ result = message.get("result", {})+ if result.get("exceptionDetails"):+ detail = result["exceptionDetails"]+ exception = detail.get("exception", {}).get("description")+ raise RuntimeError(+ exception or detail.get("text", "renderer evaluation threw")+ )+ return result.get("result", {}).get("value")+ finally:+ connection.close()+++def find_editor_websocket() -> str:+ deadline = time.monotonic() + 20+ last_error: Optional[Exception] = None+ observed_targets: List[Tuple[str, str, str]] = []+ while time.monotonic() < deadline:+ try:+ with urllib.request.urlopen(DEBUG_TARGETS_URL, timeout=2) as response:+ targets = json.load(response)+ for target in targets:+ socket_url = target.get("webSocketDebuggerUrl")+ if target.get("type") != "page" or not socket_url:+ continue+ record_observed_target(observed_targets, target)+ try:+ is_project_editor = evaluate_value(+ str(socket_url),+ "window.okDesktop?.config?.mode === 'editor'"+ " && window.okDesktop.config.projectPath.length > 0",+ timeout=2,+ )+ if is_project_editor is True:+ return str(socket_url)+ except Exception as error:+ # A renderer can disappear or still be loading while the+ # project deep link replaces the initial Navigator window.+ last_error = error+ except Exception as error: # The app may still be creating its first page.+ last_error = error+ time.sleep(0.25)+ raise RuntimeError(+ "no project editor debug target appeared; "+ f"last_error={last_error!r}; observed_targets={observed_targets!r}"+ )+++def evaluate_pty_echo(socket_url: str) -> Dict[str, object]:+ expression = f"""+ (async () => {{+ const bridge = window.okDesktop;+ if (!bridge?.config?.ptyAvailable) {{+ throw new Error('packaged renderer did not expose PTY capability');+ }}+ if (typeof bridge.platform !== 'string') {{+ throw new Error('packaged renderer did not expose its platform');+ }}+ const marker = {json.dumps(MARKER)};+ return await new Promise(async (resolve, reject) => {{+ let output = '';+ let ptyId = null;+ let settled = false;+ const pendingData = [];+ let unsubscribe = () => {{}};+ const finish = async (error) => {{+ if (settled) return;+ settled = true;+ clearTimeout(timeout);+ unsubscribe();+ if (ptyId !== null) await bridge.terminal.kill(ptyId).catch(() => {{}});+ if (error) reject(error);+ else resolve({{ output, platform: bridge.platform }});+ }};+ const consume = (data) => {{+ output += data;+ const plainOutput = output+ .replace(+ /\\u001b\\](?:[^\\u0007\\u001b]|\\u001b(?!\\\\))*(?:\\u0007|\\u001b\\\\)/g,+ '',+ )+ .replace(/\\u001b\\[[0-?]*[ -/]*[@-~]/g, '');+ // Windows bakes the marker command into shell startup. POSIX types+ // it only after creation, where the echoed input includes `echo `.+ // Requiring a marker-only output line rejects that input echo on+ // both paths and rejects partial writes.+ const markerReachedOutput =+ plainOutput+ .match(/[^\\r\\n]*(?:\\r\\n|\\r|\\n)/g)+ ?.some((line) => line.trim() === marker) ?? false;+ if (markerReachedOutput) void finish(null);+ }};+ const timeout = setTimeout(+ () => void finish(new Error(`PTY echo timed out; output=${{JSON.stringify(output)}}`)),+ 20000,+ );+ unsubscribe = bridge.terminal.onData((message) => {{+ if (ptyId === null) {{+ pendingData.push(message);+ return;+ }}+ if (message.ptyId !== ptyId) return;+ consume(message.data);+ }});+ const isWindows = bridge.platform === 'win32';+ const created = await bridge.terminal.create({{+ cols: 80,+ rows: 24,+ ...(isWindows+ ? {{+ launchCommand: {{+ executable: 'cmd.exe',+ args: ['/d', '/c', 'echo', marker],+ }},+ }}+ : {{}}),+ }});+ if (!created.ok) {{+ await finish(new Error(`PTY create failed: ${{created.reason}}`));+ return;+ }}+ ptyId = created.ptyId;+ for (const message of pendingData) {{+ if (message.ptyId === ptyId) consume(message.data);+ }}+ if (!isWindows) bridge.terminal.input(ptyId, `echo ${{marker}}\\r`);+ }});+ }})()+ """+ value = evaluate_value(socket_url, expression, timeout=30)+ if not isinstance(value, dict):+ raise RuntimeError(f"renderer returned no PTY smoke result: {value}")+ return value+++def main() -> int:+ try:+ result = evaluate_pty_echo(find_editor_websocket())+ except Exception as error:+ print(f"ERROR: packaged PTY echo failed: {error}", file=sys.stderr)+ return 1+ # A driver tunneled to a packaged app on another OS pins the target via the+ # environment; a local driver defaults to its own platform.+ expected_platform = os.environ.get("OK_SMOKE_EXPECT_PLATFORM") or sys.platform+ if result.get("platform") != expected_platform:+ print(+ "ERROR: packaged PTY driver exercised "+ f"{result.get('platform')!r}, expected {expected_platform!r}; result={result!r}",+ file=sys.stderr,+ )+ return 1+ print(f"PTY echo marker observed: {MARKER}")+ return 0+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/packages/desktop/scripts/smoke-windows-terminal-package.mjs b/packages/desktop/scripts/smoke-windows-terminal-package.mjsnew file mode 100644index 000000000..4f0f409c7--- /dev/null+++ b/packages/desktop/scripts/smoke-windows-terminal-package.mjs@@ -0,0 +1,139 @@+#!/usr/bin/env node++import { spawn, spawnSync } from 'node:child_process';+import {+ closeSync,+ existsSync,+ mkdirSync,+ mkdtempSync,+ openSync,+ readFileSync,+ rmSync,+ writeFileSync,+} from 'node:fs';+import { tmpdir } from 'node:os';+import { dirname, join, resolve } from 'node:path';+import { fileURLToPath, pathToFileURL } from 'node:url';++const scriptDir = dirname(fileURLToPath(import.meta.url));+const defaultPackageDir = resolve(scriptDir, '../dist-desktop/win-unpacked');+const cdpDriver = join(scriptDir, 'smoke-terminal-package-cdp.py');++export function windowsPackageLaunchArgs(projectDir, userDataDir) {+ const project = encodeURIComponent(projectDir);+ return [+ '--disable-gpu',+ '--remote-debugging-address=127.0.0.1',+ '--remote-debugging-port=9222',+ '--remote-allow-origins=*',+ `--user-data-dir=${userDataDir}`,+ `openknowledge://open?project=${project}&doc=start`,+ ];+}++export function windowsPtyDriverEnv(env = process.env) {+ return { ...env, OK_SMOKE_EXPECT_PLATFORM: 'win32' };+}++export function seedWindowsPtySmokeProject(rootDir, shellPath) {+ const projectDir = join(rootDir, 'project');+ const userDataDir = join(rootDir, 'user-data');+ mkdirSync(join(projectDir, '.ok', 'local'), { recursive: true });+ mkdirSync(userDataDir, { recursive: true });+ writeFileSync(join(projectDir, '.ok', 'config.yml'), "content:\n dir: '.'\n");+ writeFileSync(+ join(projectDir, '.ok', 'local', 'config.yml'),+ `terminal:\n enabled: true\n shell: ${JSON.stringify(shellPath.trim())}\n`,+ );+ writeFileSync(join(projectDir, 'start.md'), '# Packaged Windows terminal smoke\n');+ return { projectDir, userDataDir };+}++function fail(message) {+ throw new Error(message);+}++function printAppLog(logPath) {+ if (!existsSync(logPath)) return;+ const contents = readFileSync(logPath, 'utf8');+ const tail = contents.slice(-20_000);+ if (tail.trim() !== '') console.error(`Packaged app log (tail):\n${tail}`);+}++export function runWindowsPackageTerminalSmoke({+ packageDir = defaultPackageDir,+ platform = process.platform,+ env = process.env,+ python = env.OK_PYTHON ?? 'python',+} = {}) {+ if (platform !== 'win32') fail('the packaged Windows PTY smoke must run on Windows');+ const shellPath = env.ComSpec;+ if (typeof shellPath !== 'string' || shellPath.trim() === '') {+ fail('the packaged Windows PTY smoke requires ComSpec in its environment');+ }++ const resolvedPackageDir = resolve(packageDir);+ const executable = join(resolvedPackageDir, 'OpenKnowledge.exe');+ if (!existsSync(executable)) fail(`packaged executable not found: ${executable}`);++ const smokeRoot = mkdtempSync(join(tmpdir(), 'ok-packaged-win-pty-'));+ const logPath = join(smokeRoot, 'openknowledge.log');+ // This headless ABI probe pins ComSpec/cmd for deterministic shell-family+ // coverage because discovery varies across Windows runners. The required+ // real-PTY harness separately covers the PowerShell structured-launch path.+ const { projectDir, userDataDir } = seedWindowsPtySmokeProject(smokeRoot, shellPath);+ const logFd = openSync(logPath, 'w');+ let app = null;++ try {+ app = spawn(executable, windowsPackageLaunchArgs(projectDir, userDataDir), {+ cwd: resolvedPackageDir,+ env: { ...env, OK_DESKTOP_E2E_SMOKE: '1' },+ stdio: ['ignore', logFd, logFd],+ windowsHide: true,+ });++ const driver = spawnSync(python, [cdpDriver], {+ cwd: resolvedPackageDir,+ encoding: 'utf8',+ env: windowsPtyDriverEnv(env),+ timeout: 60_000,+ });+ if (driver.stdout) process.stdout.write(driver.stdout);+ if (driver.stderr) process.stderr.write(driver.stderr);+ if (driver.error) fail(`could not run packaged PTY CDP driver: ${driver.error.message}`);+ if (driver.status !== 0) fail(`packaged PTY CDP driver exited ${driver.status}`);+ } catch (error) {+ closeSync(logFd);+ printAppLog(logPath);+ throw error;+ } finally {+ if (app?.pid) {+ spawnSync('taskkill', ['/PID', String(app.pid), '/T', '/F'], {+ stdio: 'ignore',+ windowsHide: true,+ });+ }+ try {+ closeSync(logFd);+ } catch {+ // The failure path closes the descriptor before printing the log.+ }+ try {+ rmSync(smokeRoot, { recursive: true, force: true });+ } catch (error) {+ console.warn(`Could not remove packaged PTY smoke fixture ${smokeRoot}: ${error.message}`);+ }+ }+}++const invokedPath = process.argv[1] ? pathToFileURL(resolve(process.argv[1])).href : '';+if (import.meta.url === invokedPath) {+ try {+ runWindowsPackageTerminalSmoke({ packageDir: process.argv[2] ?? defaultPackageDir });+ console.log('Packaged Windows PTY CDP round-trip passed.');+ } catch (error) {+ console.error(`ERROR: ${(error instanceof Error ? error : new Error(String(error))).message}`);+ process.exitCode = 1;+ }+}diff --git a/packages/desktop/scripts/smoke-windows-terminal-package.test.mjs b/packages/desktop/scripts/smoke-windows-terminal-package.test.mjsnew file mode 100644index 000000000..f68ab7caf--- /dev/null+++ b/packages/desktop/scripts/smoke-windows-terminal-package.test.mjs@@ -0,0 +1,66 @@+import { mkdtempSync, readFileSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { afterEach, describe, expect, test } from 'vitest';+import {+ runWindowsPackageTerminalSmoke,+ seedWindowsPtySmokeProject,+ windowsPackageLaunchArgs,+ windowsPtyDriverEnv,+} from './smoke-windows-terminal-package.mjs';++const fixtures = [];++afterEach(() => {+ for (const fixture of fixtures.splice(0)) rmSync(fixture, { recursive: true, force: true });+});++describe('packaged Windows terminal smoke driver', () => {+ test('seeds deterministic project-local terminal config for the packaged app', () => {+ const root = mkdtempSync(join(tmpdir(), 'ok-win-pty-smoke-test-'));+ fixtures.push(root);+ const { projectDir, userDataDir } = seedWindowsPtySmokeProject(+ root,+ 'C:\\Windows\\System32\\cmd.exe',+ );++ expect(readFileSync(join(projectDir, '.ok', 'config.yml'), 'utf8')).toBe(+ "content:\n dir: '.'\n",+ );+ expect(readFileSync(join(projectDir, '.ok', 'local', 'config.yml'), 'utf8')).toBe(+ 'terminal:\n enabled: true\n shell: "C:\\\\Windows\\\\System32\\\\cmd.exe"\n',+ );+ expect(readFileSync(join(projectDir, 'start.md'), 'utf8')).toContain('Windows terminal');+ expect(userDataDir).toBe(join(root, 'user-data'));+ });++ test('fails closed on missing ComSpec before touching a package', () => {+ expect(() => runWindowsPackageTerminalSmoke({ platform: 'win32', env: {} })).toThrow(+ /requires ComSpec in its environment/,+ );+ });++ test('launches a unique project through a loopback-only CDP endpoint', () => {+ const args = windowsPackageLaunchArgs('C:\\Temp\\Project With Spaces', 'C:\\Temp\\User Data');++ expect(args).toContain('--remote-debugging-address=127.0.0.1');+ expect(args).toContain('--remote-debugging-port=9222');+ expect(args).toContain('--user-data-dir=C:\\Temp\\User Data');+ expect(args.at(-1)).toBe(+ 'openknowledge://open?project=C%3A%5CTemp%5CProject%20With%20Spaces&doc=start',+ );+ });++ test('fails closed when invoked anywhere except a real Windows runner', () => {+ expect(() => runWindowsPackageTerminalSmoke({ platform: 'linux' })).toThrow(+ /must run on Windows/,+ );+ });++ test('requires the CDP driver to exercise its Windows branch', () => {+ expect(windowsPtyDriverEnv({ SENTINEL: 'preserved' })).toEqual({+ SENTINEL: 'preserved',+ OK_SMOKE_EXPECT_PLATFORM: 'win32',+ });+ });+});diff --git a/packages/desktop/src/main/appimage-integration.ts b/packages/desktop/src/main/appimage-integration.tsindex 5cbcab70f..40f52658a 100644--- a/packages/desktop/src/main/appimage-integration.ts+++ b/packages/desktop/src/main/appimage-integration.ts@@ -101,7 +101,7 @@ export async function registerAppImageDeepLinks(const execFileFn =deps.execFileImpl ??((cmd: string, args: string[], cb: (err: Error | null) => void) => {- execFile(cmd, args, { timeout: 5_000 }, (err) => cb(err));+ execFile(cmd, args, { timeout: 5_000, windowsHide: true }, (err) => cb(err));});try {diff --git a/packages/desktop/src/main/auto-instance.ts b/packages/desktop/src/main/auto-instance.tsindex 04367dd49..e65df8763 100644--- a/packages/desktop/src/main/auto-instance.ts+++ b/packages/desktop/src/main/auto-instance.ts@@ -40,6 +40,7 @@ function runGit(args: readonly string[], dir: string): string | null {// Silence git's stderr — a non-repo / missing-git failure is expected// and handled via the null return, not surfaced to the desktop log.stdio: ['ignore', 'pipe', 'ignore'],+ windowsHide: true,}).trim();return out.length > 0 ? out : null;} catch {diff --git a/packages/desktop/src/main/auto-updater.ts b/packages/desktop/src/main/auto-updater.tsindex 53c069f19..d8cde42c8 100644--- a/packages/desktop/src/main/auto-updater.ts+++ b/packages/desktop/src/main/auto-updater.ts@@ -37,6 +37,7 @@ import {manualInstallPlanFor,} from './linux-install-fallback.ts';import type { AppState, UpdateChannel } from './state-store.ts';+import type { WindowsUpdateSurvivorSweepResult } from './windows-update-survivor-sweep.ts';/** GitHub provider coordinates — must match `electron-builder.yml` `publish:`. */const GITHUB_OWNER = 'inkeep';@@ -264,6 +265,13 @@ interface StartAutoUpdaterOpts {* shutdown (SIGTERM → poll → SIGKILL) can complete cleanly.*/prepareForRelaunch?: () => void | Promise<void>;+ /**+ * Last-moment recovery sweep before the updater replaces installed files.+ * Production uses this on Windows to terminate console hosts proven to+ * belong to this installation. Kept separate from server teardown so the+ * updater owns the ordering immediately before `quitAndInstall()`.+ */+ sweepUpdateSurvivors?: () => WindowsUpdateSurvivorSweepResult | undefined;/*** Reclaim electron-updater's staged-installer cache (`pending/` under the* updater cache dir). Invoked once per boot, from the reconciliation@@ -2333,6 +2341,18 @@ export function startAutoUpdater(opts: StartAutoUpdaterOpts): StartAutoUpdaterHa});}}+ if (opts.sweepUpdateSurvivors) {+ try {+ const result = opts.sweepUpdateSurvivors();+ if (result && (result.scanFailed || result.revalidationFailed || result.failedCount > 0)) {+ logger.warn('update survivor sweep incomplete — proceeding to quitAndInstall anyway', {+ result,+ });+ }+ } catch (err) {+ logger.warn('update survivor sweep threw — proceeding to quitAndInstall anyway', { err });+ }+ }logger.info('relaunch-now invoked — calling autoUpdater.quitAndInstall', {pending,stagingAgeMs,diff --git a/packages/desktop/src/main/boot-session.ts b/packages/desktop/src/main/boot-session.tsindex d142425ab..be665a69f 100644--- a/packages/desktop/src/main/boot-session.ts+++ b/packages/desktop/src/main/boot-session.ts@@ -20,6 +20,7 @@ export function readBootSessionUuid(platform: NodeJS.Platform = process.platformconst out = execFileSync('/usr/sbin/sysctl', ['-n', 'kern.bootsessionuuid'], {encoding: 'utf8',timeout: 2_000,+ windowsHide: true,});return normalize(out);}diff --git a/packages/desktop/src/main/claude-readiness.ts b/packages/desktop/src/main/claude-readiness.tsindex 86fcdfad1..a50849075 100644--- a/packages/desktop/src/main/claude-readiness.ts+++ b/packages/desktop/src/main/claude-readiness.ts@@ -24,6 +24,7 @@ import type { McpEntryClassification } from '@inkeep/open-knowledge';import { TERMINAL_CLI_IDS, TERMINAL_CLIS, type TerminalCli } from '@inkeep/open-knowledge-core';import type { ClaudeReadiness, CliReadiness } from '../shared/bridge-contract.ts';import { interactiveShellArgs } from '../shared/terminal-shell.ts';+import { windowsWherePathArgs } from '../shared/windows-env.ts';import { getLogger } from './desktop-logger.ts';export type ClaudeOnPath = ClaudeReadiness['claude'];@@ -69,47 +70,63 @@ export interface ProbeTimers {clearTimer(token: unknown): void;}+/** One platform's executable-lookup probe expressed against the injected+ * spawn/timer seams. `attrs` are the bounded-cardinality log fields that+ * identify the probe in an operator's log (fixed argv + registry values only —+ * never a raw user path or free-form string). */+interface InjectedProbeSpec {+ readonly spawn: ProbeSpawn;+ readonly file: string;+ readonly args: readonly string[];+ readonly timers: ProbeTimers;+ readonly timeoutMs: number;+ readonly loggerName: string;+ /** Names the probe in each degradation message ("<label> PATH probe ..."). */+ readonly label: string;+ readonly attrs: Record<string, unknown>;+}+/**- * Run the interactive-shell `command -v claude` probe. Resolves the child's exit- * code, or `null` when the probe could not produce a verdict — a synchronous- * `spawn` throw (EMFILE/ENOMEM resource exhaustion), an async `'error'`- * (ENOENT shell, EACCES), or a timeout (an interactive shell that hung). `null`- * is deliberately distinct from a non-zero exit: a non-zero exit means- * `command -v` ran and `claude` is genuinely absent, whereas `null` means the- * probe itself failed and claude's presence is UNKNOWN — the caller must not- * render a "not installed" message off an UNKNOWN.+ * The one settle-once/timeout/observability engine every platform's PATH probe+ * runs on. Resolves the child's exit code, or `null` when the probe could not+ * produce a verdict — a synchronous `spawn` throw (EMFILE/ENOMEM resource+ * exhaustion), an async `'error'` (ENOENT/EACCES on the probe binary), or a+ * timeout (a lookup that hung). `null` is deliberately distinct from a non-zero+ * exit: a non-zero exit means the lookup RAN and the binary is genuinely+ * absent, whereas `null` means the probe itself failed and the binary's+ * presence is UNKNOWN — the caller must not render a "not installed" message+ * off an UNKNOWN.*- * Every `null` resolution logs at warn: this probe gates launch baking and the+ * Every `null` resolution logs at warn: these probes gate launch baking and the* installed-map row gating, and a silent degradation makes a field report of* "isn't installed" undiagnosable (genuine PATH loss and a probe flake would* otherwise leave identical artifacts).+ *+ * The timeout is unconditional, so a wedged lookup binary settles the promise+ * instead of leaving the readiness IPC awaiting forever.*/-export function runLoginShellProbe(- spawn: ProbeSpawn,- shell: string,- timers: ProbeTimers,- timeoutMs: number = PROBE_TIMEOUT_MS,- args: readonly string[] = CLAUDE_PROBE_ARGS,-): Promise<number | null> {+function runInjectedProbe(spec: InjectedProbeSpec): Promise<number | null> {+ const { spawn, file, args, timers, timeoutMs, loggerName, label, attrs } = spec;return new Promise<number | null>((resolve) => {let child: ProbeChild;try {- child = spawn(shell, args);+ // biome-ignore lint/plugin/require-windowshide-on-spawn: injected probe seam; the production child_process adapter owns its spawn options+ child = spawn(file, args);} catch (err) {// partial-failure boundary: spawn can throw synchronously on resource- // exhaustion. Claude presence is UNKNOWN, not absent.- getLogger('interactive-shell-probe').warn(- { shell, args, err },- 'interactive-shell PATH probe spawn threw; presence unknown',+ // exhaustion. Presence is UNKNOWN, not absent.+ getLogger(loggerName).warn(+ { ...attrs, err },+ `${label} PATH probe spawn threw; presence unknown`,);resolve(null);return;}let settled = false;const timer = timers.setTimer(() => {- getLogger('interactive-shell-probe').warn(- { shell, args, timeoutMs },- 'interactive-shell PATH probe timed out; presence unknown',+ getLogger(loggerName).warn(+ { ...attrs, timeoutMs },+ `${label} PATH probe timed out; presence unknown`,);child.kill();finish(null);@@ -122,9 +139,9 @@ export function runLoginShellProbe(}child.onError((err) => {if (!settled) {- getLogger('interactive-shell-probe').warn(- { shell, args, err },- 'interactive-shell PATH probe failed to run; presence unknown',+ getLogger(loggerName).warn(+ { ...attrs, err },+ `${label} PATH probe failed to run; presence unknown`,);}finish(null);@@ -133,6 +150,50 @@ export function runLoginShellProbe(});}+/**+ * Run the interactive-shell `command -v claude` probe. Tri-state per+ * {@link runInjectedProbe}: exit code, or `null` for UNKNOWN.+ */+export function runLoginShellProbe(+ spawn: ProbeSpawn,+ shell: string,+ timers: ProbeTimers,+ timeoutMs: number = PROBE_TIMEOUT_MS,+ args: readonly string[] = CLAUDE_PROBE_ARGS,+): Promise<number | null> {+ return runInjectedProbe({+ spawn,+ file: shell,+ args,+ timers,+ timeoutMs,+ loggerName: 'interactive-shell-probe',+ label: 'interactive-shell',+ attrs: { shell, args },+ });+}++/** Windows `where.exe` counterpart to {@link runLoginShellProbe}. */+export function runWindowsPathProbe(+ spawn: ProbeSpawn,+ whereExe: string,+ bin: string,+ timers: ProbeTimers,+ timeoutMs: number = PROBE_TIMEOUT_MS,+): Promise<number | null> {+ const args = windowsWherePathArgs(bin);+ return runInjectedProbe({+ spawn,+ file: whereExe,+ args,+ timers,+ timeoutMs,+ loggerName: 'windows-path-probe',+ label: 'where.exe',+ attrs: { whereExe, bin, args },+ });+}+/** Probe exit code → claude-on-PATH verdict. `null` (probe failed) → UNKNOWN. */export function interpretClaudeProbe(code: number | null): ClaudeOnPath {if (code === null) return 'unknown';@@ -204,8 +265,7 @@ export async function resolveClaudeReadiness(}export interface ResolveCliOnPathDeps {- /** Runs the interactive-shell PATH probe for the CLI's binary; resolves the exit- * code or `null` (probe failed → UNKNOWN). */+ /** Tri-state PATH probe per {@link runInjectedProbe}. */probe(): Promise<number | null>;/** Codex-only: whether OK's MCP server is already configured in the user's* codex config (gates the per-launch `-c` auto-approve override). Synchronous;@@ -215,14 +275,7 @@ export interface ResolveCliOnPathDeps {okServerConfigured?(): boolean;}-/**- * Generic on-PATH readiness for a non-Claude agent CLI (codex / cursor-agent).- * Unlike {@link resolveClaudeReadiness} there is no MCP-wiring concept — these- * CLIs ground via the OK MCP server configured in their own way — so the result- * is purely the on-PATH verdict. Reuses {@link interpretClaudeProbe}: `null`- * (probe failed) → `unknown`, so the caller never renders a false "not- * installed" off a flaky probe.- */+/** Generic on-PATH readiness for a non-Claude agent CLI. */export async function resolveCliOnPath(deps: ResolveCliOnPathDeps): Promise<CliReadiness> {const code = await deps.probe().catch((err) => {getLogger('cli-readiness').warn(@@ -246,23 +299,11 @@ export async function resolveCliOnPath(deps: ResolveCliOnPathDeps): Promise<CliR}export interface ResolveCliInstalledMapDeps {- /** Login-shell PATH probe for a CLI's registry binary; resolves the exit code- * or `null` (probe failed → UNKNOWN, that entry is omitted from the map). */+ /** Tri-state PATH probe per {@link runInjectedProbe}. */probe(cli: TerminalCli): Promise<number | null>;}-/**- * Batched on-PATH readiness for every launchable CLI as an installed map:- * `present` ⇒ `true`, `not-found` ⇒ `false`, and `unknown` ⇒ the entry is- * OMITTED — an absent key means the probe could not verify either way, and- * consumers must not read it as absence (row gating fails open on `undefined`;- * auto-pick requires `=== true`, so an unverifiable CLI is still never a safe- * auto-pick and the resolver's final fallback stays claude). This is the "which- * CLIs can I launch?" answer the New-chat default-CLI auto-pick needs — one- * query instead of a per-CLI {@link resolveCliOnPath} preflight fan-out. Each- * entry still routes through {@link resolveCliOnPath}, so a flaky or rejected- * probe degrades that one entry without crashing the batch.- */+/** Batched CLI readiness; unknown probes are omitted from the installed map. */export async function resolveCliInstalledMap(deps: ResolveCliInstalledMapDeps,): Promise<Partial<Record<TerminalCli, boolean>>> {@@ -282,7 +323,18 @@ export async function resolveCliInstalledMap(export interface ResolvePlatformCliInstalledMapDeps {readonly platform: NodeJS.Platform;readonly probePosix: (args: readonly string[]) => Promise<number | null>;- readonly probeWindows: (bin: string) => Promise<boolean>;+ /** Windows tri-state executable lookup for one binary. */+ readonly probeWindows: (bin: string) => Promise<number | null>;+}++export interface ProbePlatformCliOnPathDeps extends ResolvePlatformCliInstalledMapDeps {+ readonly bin: string;+}++/** Probe one registered CLI with the host platform's executable lookup. */+export function probePlatformCliOnPath(deps: ProbePlatformCliOnPathDeps): Promise<number | null> {+ if (deps.platform === 'win32') return deps.probeWindows(deps.bin);+ return deps.probePosix(cliProbeArgs(deps.bin, deps.platform));}/**@@ -296,8 +348,7 @@ export function resolvePlatformCliInstalledMap(return resolveCliInstalledMap({probe: async (cli) => {const bin = TERMINAL_CLIS[cli].bin;- if (deps.platform === 'win32') return (await deps.probeWindows(bin)) ? 0 : 127;- return deps.probePosix(cliProbeArgs(bin, deps.platform));+ return probePlatformCliOnPath({ ...deps, bin });},});}diff --git a/packages/desktop/src/main/desktop-uninstall.ts b/packages/desktop/src/main/desktop-uninstall.tsindex e0eb86911..b9e53084b 100644--- a/packages/desktop/src/main/desktop-uninstall.ts+++ b/packages/desktop/src/main/desktop-uninstall.ts@@ -582,6 +582,7 @@ export function runDesktopUninstallCleanup(cwd: '/',detached: false,stdio: 'ignore',+ windowsHide: true,});child.once('error', (err) => finish({ ok: false, error: err.message }));child.once('close', (code, signal) => {diff --git a/packages/desktop/src/main/folder-admission.ts b/packages/desktop/src/main/folder-admission.tsindex 45837b5fb..ee987bdda 100644--- a/packages/desktop/src/main/folder-admission.ts+++ b/packages/desktop/src/main/folder-admission.ts@@ -420,7 +420,10 @@ function isPickedPathLinkedWorktreeRoot(pickedPath: string): boolean {*/export async function defaultGitTopLevel(cwd: string): Promise<string | null> {try {- const { stdout } = await execFileAsync('git', ['rev-parse', '--show-toplevel'], { cwd });+ const { stdout } = await execFileAsync('git', ['rev-parse', '--show-toplevel'], {+ cwd,+ windowsHide: true,+ });const trimmed = stdout.trim();return trimmed.length > 0 ? trimmed : null;} catch {diff --git a/packages/desktop/src/main/index.ts b/packages/desktop/src/main/index.tsindex 77c19fe8d..0e86b3368 100644--- a/packages/desktop/src/main/index.ts+++ b/packages/desktop/src/main/index.ts@@ -166,8 +166,8 @@ import type {} from '../shared/ipc-channels.ts';import { createHandler } from '../shared/ipc-handler.ts';import { registerPendingDelivery, sendToRenderer } from '../shared/ipc-send.ts';-import { isTerminalPlatform } from '../shared/terminal-platform.ts';import { UNINSTALL_PRELOAD_ARG } from '../shared/uninstall-preload-arg.ts';+import { getWindowsEnvValue } from '../shared/windows-env.ts';import { resolveShell } from '../utility/pty-host.ts';import { buildAboutPanelOptions } from './about-panel.ts';import {@@ -219,10 +219,14 @@ import {} from './check-target-exists.ts';import {cliProbeArgs,+ type ProbeChild,+ type ProbeTimers,+ probePlatformCliOnPath,resolveClaudeReadiness,resolveCliOnPath,resolvePlatformCliInstalledMap,runLoginShellProbe,+ runWindowsPathProbe,} from './claude-readiness.ts';import { requestUserConsent, walkExceedsCap } from './consent-dialog.ts';import { copyImageToClipboard } from './copy-image-clipboard.ts';@@ -446,7 +450,12 @@ import {windowRestoreKey,} from './state-store.ts';import { quoteStopCommandPath } from './stop-command.ts';-import { isTerminalConsented, isTerminalConsentedWithGrace } from './terminal-consent.ts';+import { isTerminalAvailable, withTerminalCapabilityArg } from './terminal-capability.ts';+import {+ isTerminalConsented,+ isTerminalConsentedWithGrace,+ readTerminalShellSetting,+} from './terminal-consent.ts';import { commitTerminalDockState } from './terminal-dock-persistence.ts';import { type TerminalReaper, wireWindowTerminalReap } from './terminal-lifecycle.ts';import {@@ -456,6 +465,7 @@ import {DEFAULT_PTY_ROWS,type PtyUtilityLike,} from './terminal-manager.ts';+import { createTerminalQuitDrain } from './terminal-quit-drain.ts';import { terminalStateKeyForContext } from './terminal-state-key.ts';import {recordConcurrentSessions,@@ -504,6 +514,10 @@ import {} from './window-manager.ts';import { WINDOW_MIN_SIZE } from './window-min-size.ts';import { resolveRestoredPlacement, sortWindowsByFocusSequence } from './window-placement.ts';+import {+ sweepWindowsUpdateSurvivors,+ type WindowsUpdateSurvivorSweepResult,+} from './windows-update-survivor-sweep.ts';import {classifyRecentGit,classifyRecentGitAsync,@@ -1153,6 +1167,17 @@ let wm: WindowManager;* quit — callers guard with `?.` / a truthiness check.*/let terminalReaper: TerminalReaper | null = null;++function sweepConsoleHostsBeforeUpdate(): WindowsUpdateSurvivorSweepResult {+ const logger = getLogger('updater');+ return sweepWindowsUpdateSurvivors({+ installTree: process.resourcesPath,+ logger: {+ info: (event) => logger.info(event, 'Windows update console-host sweep complete'),+ warn: (event) => logger.warn(event, 'Windows update console-host sweep warning'),+ },+ });+}/*** Every open Slidev deck (server + its window), keyed by deck path. Module-scoped* so the `ok:slides:dispatch` `open` handler can focus-existing / open, each@@ -1645,15 +1670,12 @@ function runDriverBootSmokeInProduction(): void {});}-/**- * Appends the `--ok-debug-keyring-smoke=1` argv flag when the gate allows it,- * so the preload can populate `bridge.debug`. Preload reads the flag via- * `parseArg` just like the other window-bound config fields.- */-function withDebugFlagIfAllowed(args: readonly string[]): string[] {+/** Add main-owned runtime facts to every editor-renderer window. */+function withWindowRuntimeArgs(args: readonly string[]): string[] {const withDebug = isDebugKeyringSmokeAllowed()? [...args, '--ok-debug-keyring-smoke=1']: [...args];+ const withTerminalCapability = withTerminalCapabilityArg(withDebug, isTerminalAvailable());// Under the Electron smoke suite, force xterm's DOM renderer (not the WebGL// canvas) via this flag — the canvas can't be read by the DOM-based smoke// assertions and captures focus from synthetic keystrokes. Gating only xterm@@ -1661,7 +1683,9 @@ function withDebugFlagIfAllowed(args: readonly string[]): string[] {// suite doesn't trigger whole-app software rendering that starves CPU on// constrained CI runners. See TerminalPanel's WebGL gate.const withSmoke =- process.env.OK_DESKTOP_E2E_SMOKE === '1' ? [...withDebug, '--ok-e2e-smoke=1'] : withDebug;+ process.env.OK_DESKTOP_E2E_SMOKE === '1'+ ? [...withTerminalCapability, '--ok-e2e-smoke=1']+ : withTerminalCapability;// Cold-start assistive-tech signal for the preload's live mirror (see// `ok:accessibility:changed` in ipc-events.ts): the terminal gates xterm's// costly `screenReaderMode` on it. Read per window creation so a window@@ -1757,7 +1781,7 @@ function ensureWindowManager() {title: opts.title,webPreferences: {...DEFAULT_WIN_OPTS.webPreferences,- additionalArguments: withDebugFlagIfAllowed(opts.additionalArguments),+ additionalArguments: withWindowRuntimeArgs(opts.additionalArguments),preload: join(__dirname, '../preload/index.js'),},});@@ -1945,7 +1969,10 @@ function ensureWindowManager() {let childRef: ReturnType<typeof spawn>;startupWaterfall.mark('serverSpawned');try {- childRef = spawn(spawnArgs.file, spawnArgs.args, spawnArgs.opts);+ childRef = spawn(spawnArgs.file, spawnArgs.args, {+ ...spawnArgs.opts,+ windowsHide: true,+ });} catch (spawnErr) {// Synchronous spawn failure — close fd before rethrowing.// Re-throw with the same `kind: 'spawn-error'` discriminant the@@ -2234,7 +2261,7 @@ function openNavigator(pendingPayload?: ShareNavigatorPayload) {height: 680,webPreferences: {...DEFAULT_WIN_OPTS.webPreferences,- additionalArguments: withDebugFlagIfAllowed(opts.additionalArguments),+ additionalArguments: withWindowRuntimeArgs(opts.additionalArguments),preload: join(__dirname, '../preload/index.js'),},});@@ -3513,6 +3540,7 @@ async function runApplicationMenuRefresh(): Promise<void> {// `-beta.N` via `--config.extraMetadata.version=X.Y.Z`. Reuses// `channelFromVersion` so this stays aligned with the auto-updater channel.showDevToolsMenu: !app.isPackaged || channelFromVersion(app.getVersion()) === 'beta',+ terminalCapable: isTerminalAvailable(),dialog,openNavigator,openProject: (path, entryPoint) => openProjectOrFallbackToNavigator(path, entryPoint),@@ -3661,7 +3689,7 @@ async function runApplicationMenuRefresh(): Promise<void> {// Overrides the three handlers `buildViewMenuStateDeps` just spread in.// `onToggleAgentPanel` is deliberately absent from the strip list: agent// threads are server-hosted, so the agents panel works everywhere pty does not.- ...(isTerminalPlatform(process.platform)+ ...(isTerminalAvailable()? { onNewTerminalWindow: () => openTerminalWindow() }: {onToggleTerminal: undefined,@@ -4449,7 +4477,7 @@ function openTerminalWindow(): void {title: opts.title,webPreferences: {...DEFAULT_WIN_OPTS.webPreferences,- additionalArguments: withDebugFlagIfAllowed(opts.additionalArguments),+ additionalArguments: withWindowRuntimeArgs(opts.additionalArguments),preload: join(__dirname, '../preload/index.js'),},});@@ -4644,7 +4672,7 @@ function openNoteWindowForDoc(args: {title: opts.title,webPreferences: {...DEFAULT_WIN_OPTS.webPreferences,- additionalArguments: withDebugFlagIfAllowed(opts.additionalArguments),+ additionalArguments: withWindowRuntimeArgs(opts.additionalArguments),preload: join(__dirname, '../preload/index.js'),},});@@ -5014,56 +5042,60 @@ function formatUnknownError(err: unknown): string {return err instanceof Error ? err.message : String(err);}-/**- * Run an interactive-shell `command -v <bin>` probe in the real shell (the same- * `resolveShell` the PTY spawns), with `spawn` + timers wired to the OS. Shared- * by the Claude readiness path and the generic non-Claude CLI path; the- * timeout/exit-code routing is unit-tested in claude-readiness.test.ts via an- * injected spawn. `args` selects the binary (`cliProbeArgs(bin)`); it defaults- * to the `claude` probe.- */+/** The real `child_process` + timer wiring behind both platform probes. The+ * timeout/exit-code/settle-once routing they share is unit-tested in+ * claude-readiness.test.ts against these seams. */+function realProbeSpawn(file: string, spawnArgs: readonly string[]): ProbeChild {+ const child = spawn(file, [...spawnArgs], {+ stdio: 'ignore',+ shell: false,+ windowsHide: true,+ });+ return {+ onExit: (cb) => {+ child.on('exit', (code) => cb(code));+ },+ onError: (cb) => {+ child.on('error', (err) => cb(err));+ },+ kill: () => {+ child.kill('SIGKILL');+ },+ };+}++const realProbeTimers: ProbeTimers = {+ setTimer: (cb, ms) => setTimeout(cb, ms),+ clearTimer: (token) => clearTimeout(token as ReturnType<typeof setTimeout>),+};+/*** Windows counterpart to {@link probeLoginShellOnPath}: is `bin` resolvable on- * this process's PATH? `where.exe` honours PATHEXT, so it finds the `.cmd`- * shim that `CreateProcess` can actually run — an extension-less existence- * check would report a POSIX shim that then fails to spawn. Exit 0 = found.+ * this process's PATH? Resolves `where.exe` under the real `SystemRoot` and+ * hands the tri-state routing to {@link runWindowsPathProbe} — exit code, or+ * `null` when the probe could not produce a verdict.*/-function probeWindowsPath(bin: string): Promise<boolean> {- return new Promise((resolveProbe) => {- try {- // `where`, not `where.exe` — matches the binary name the CLI's git- // preflight already uses (and the one knip's ignore list declares).- // CreateProcess resolves it via PATHEXT either way.- const child = spawn('where', [bin], { stdio: 'ignore', shell: false, windowsHide: true });- child.on('exit', (code) => resolveProbe(code === 0));- child.on('error', () => resolveProbe(false));- } catch {- resolveProbe(false);- }- });+function probeWindowsPath(bin: string): Promise<number | null> {+ const systemRoot = getWindowsEnvValue(process.env, 'SystemRoot') ?? 'C:\\Windows';+ return runWindowsPathProbe(+ realProbeSpawn,+ join(systemRoot, 'System32', 'where.exe'),+ bin,+ realProbeTimers,+ );}+/**+ * Run an interactive-shell `command -v <bin>` probe in the real shell (the same+ * `resolveShell` the PTY spawns), with `spawn` + timers wired to the OS. Shared+ * by the Claude readiness path and the generic non-Claude CLI path. `args`+ * selects the binary (`cliProbeArgs(bin)`); it defaults to the `claude` probe.+ */function probeLoginShellOnPath(args?: readonly string[]): Promise<number | null> {return runLoginShellProbe(- (file, spawnArgs) => {- const child = spawn(file, [...spawnArgs], { stdio: 'ignore', shell: false });- return {- onExit: (cb) => {- child.on('exit', (code) => cb(code));- },- onError: (cb) => {- child.on('error', (err) => cb(err));- },- kill: () => {- child.kill('SIGKILL');- },- };- },+ realProbeSpawn,resolveShell(process.env, { platform: process.platform }),- {- setTimer: (cb, ms) => setTimeout(cb, ms),- clearTimer: (token) => clearTimeout(token as ReturnType<typeof setTimeout>),- },+ realProbeTimers,undefined,args,);@@ -5097,7 +5129,13 @@ function isProjectClaudeMcpOwn(projectRoot: string | undefined): boolean {*/function resolveTerminalClaudeReadiness(projectRoot: string | undefined): Promise<ClaudeReadiness> {return resolveClaudeReadiness({- probeClaude: () => probeLoginShellOnPath(),+ probeClaude: () =>+ probePlatformCliOnPath({+ platform: process.platform,+ bin: 'claude',+ probePosix: (args) => probeLoginShellOnPath(args),+ probeWindows: (bin) => probeWindowsPath(bin),+ }),classifyMcpEntry: () =>createMcpWiringCliSurface().classifyExistingMcpEntry('claude', osHomedir()).kind,isProjectMcpPreApprovable: () => isProjectClaudeMcpOwn(projectRoot),@@ -5112,7 +5150,13 @@ function resolveTerminalClaudeReadiness(projectRoot: string | undefined): Promis*/function resolveTerminalCliOnPath(cli: TerminalCli): Promise<CliReadiness> {return resolveCliOnPath({- probe: () => probeLoginShellOnPath(cliProbeArgs(TERMINAL_CLIS[cli].bin, process.platform)),+ probe: () =>+ probePlatformCliOnPath({+ platform: process.platform,+ bin: TERMINAL_CLIS[cli].bin,+ probePosix: (args) => probeLoginShellOnPath(args),+ probeWindows: (bin) => probeWindowsPath(bin),+ }),// Codex-only: report whether OK's `open-knowledge` server is already in the// user's codex config, so the launch site adds the `-c` tool-auto-approve// override only when it won't break config load (a `-c` under an undefined@@ -5321,6 +5365,7 @@ function registerIpcHandlers() {utilityProcess.fork(join(__dirname, 'utility/pty-host.js')) as unknown as PtyUtilityLike,sendData: (wc, payload) => sendToRenderer(wc, 'ok:pty:data', payload),sendExit: (wc, payload) => sendToRenderer(wc, 'ok:pty:exit', payload),+ sendNotice: (wc, payload) => sendToRenderer(wc, 'ok:pty:notice', payload),newPtyId: () => randomUUID(),setTimer: (cb, ms) => setTimeout(cb, ms),clearTimer: (token) => clearTimeout(token as ReturnType<typeof setTimeout>),@@ -5378,12 +5423,18 @@ function registerIpcHandlers() {});return { ok: false, reason: 'not-consented' };}+ const shellSetting =+ process.platform === 'win32'+ ? readTerminalShellSetting(projectPath)+ : { kind: 'unset' as const };return terminalManager.create({windowId: win.id,webContents: win.webContents,projectRoot: projectPath,cols: clampPtyDimension(opts.cols, DEFAULT_PTY_COLS),rows: clampPtyDimension(opts.rows, DEFAULT_PTY_ROWS),+ ...(shellSetting.kind === 'configured' ? { shell: shellSetting.shell } : {}),+ ...(shellSetting.kind === 'invalid' ? { shellInvalidReason: shellSetting.reason } : {}),launchCommand: opts.launchCommand,});});@@ -5638,6 +5689,7 @@ function registerIpcHandlers() {shell: false,timeout: timeoutMs,stdio: ['ignore', 'ignore', 'pipe'],+ windowsHide: true,});// Drain stderr so a chatty child can't block on a full pipe buffer.child.stderr?.on('data', () => {});@@ -6136,7 +6188,7 @@ function registerIpcHandlers() {singleFile: ctx.ephemeral !== undefined,// Mirrors the preload's cold-start config: PTY capability is the same// platform fact for a re-queried live window.- ptyAvailable: isTerminalPlatform(process.platform),+ ptyAvailable: isTerminalAvailable(),// `initialDoc` is a cold-start-only hash seed (consumed once at renderer// boot from the preload-injected bridge config). A live window queried via// get-info has already navigated, so there is nothing to re-seed → null.@@ -6184,25 +6236,16 @@ function registerIpcHandlers() {// has neither that problem (a GUI process inherits the user PATH from the// registry) nor a POSIX login shell to run `-l -i -c` against, so it uses// `where.exe`, which also honours PATHEXT and finds the `.cmd` shim.+ // This yes/no surface admits only a verified exit-zero probe.isOnLoginPath: async (bin: string) =>- process.platform === 'win32'- ? await probeWindowsPath(bin)- : (await probeLoginShellOnPath(cliProbeArgs(bin, process.platform))) === 0,+ (await (process.platform === 'win32'+ ? probeWindowsPath(bin)+ : probeLoginShellOnPath(cliProbeArgs(bin, process.platform)))) === 0,};if (request.kind === 'status') {return handleSlidesStatus(projectRoot, probes);}// Trust boundary: the deck path is a renderer-supplied string over IPC.- // Require a bound project and a well-formed absolute path, then canonicalize- // via realpath and enforce project containment on the RESOLVED path before- // spawning a server against it — the same order the trash / asset handlers- // apply. Lexical containment alone would let an in-project symlink whose- // target is OUTSIDE the project pass, and Slidev/Vite would then serve that- // out-of-project target over loopback; realpath collapses the symlink so the- // escape is refused (the window's projectPath is already realpath-canonical- // via discoverProject). A window with no project has nothing to contain- // against, so it is refused.- // Trust boundary: the deck path is a renderer-supplied string over IPC.// The admission decision (bound project + well-formed absolute path +// realpath-then-contain, so an in-project symlink cannot escape) lives in// `slides-deck-path.ts` where it is reachable from a test against a real@@ -8156,7 +8199,7 @@ function bootPrimaryInstance(): void {// Assistive-tech flips (e.g. VoiceOver, NVDA attach/detach) fan out to every window so// the preload's live mirror stays current and an open terminal can toggle// xterm's `screenReaderMode` in place. Cold-start value rides window- // creation via `--ok-screen-reader-active` (see withDebugFlagIfAllowed).+ // creation via `--ok-screen-reader-active` (see withWindowRuntimeArgs).app.on('accessibility-support-changed', (_event, screenReaderActive) => {// Logged before the fan-out, so the record survives a send that throws.// The timestamp is the point: it places an AT client attaching against the@@ -9142,6 +9185,10 @@ function bootPrimaryInstance(): void {// that completes well before `stopAllOwnedServers` returns or// `quitAndInstall()` fires.captureWindowRestoreSnapshot('prepare-for-relaunch');+ // Start the terminal hosts' graceful shutdown before waiting on the+ // server drain. Any bundled console host still present after that+ // wait is then removed by the install-tree-owned survivor sweep.+ await terminalReaper?.killAll();// Two-phase shutdown: SIGTERM detached server pids (and SIGKILL any// dev-path utilityProcess.fork helpers), then poll the lock files// until they release or 10 s elapses, then escalate to SIGKILL on@@ -9155,6 +9202,7 @@ function bootPrimaryInstance(): void {// never reach disk (the destination is `sync: false`).flushDesktopLogger();},+ sweepUpdateSurvivors: sweepConsoleHostsBeforeUpdate,// User feedback for menu-driven `Check for Updates…` clicks. The// periodic hourly check stays silent on a no-update outcome (the// existing `update-not-available` log-only handler), but a manual@@ -9315,6 +9363,18 @@ function bootPrimaryInstance(): void {// capture point. Write-once, so the "Relaunch now" path (already// snapshotted in `prepareForRelaunch`) no-ops here.captureWindowRestoreSnapshot('before-quit-for-update');+ // The silent install-on-quit path bypasses prepareForRelaunch. Start the+ // same bounded terminal drain; the will-quit barrier below keeps the main+ // process alive, and the survivor sweep follows only after the drain.+ void (terminalReaper?.killAll() ?? Promise.resolve()).then(() => {+ const result = sweepConsoleHostsBeforeUpdate();+ if (result.scanFailed || result.revalidationFailed || result.failedCount > 0) {+ getLogger('updater').warn(+ { result },+ 'Silent update console-host sweep incomplete — continuing shutdown',+ );+ }+ });// Shut down the servers this desktop spawned BEFORE the swap completes, so// the relaunched (new-version) app spawns fresh instead of attaching to a// stale old-version server and showing the version-drift toast. Fires on@@ -9331,9 +9391,16 @@ function bootPrimaryInstance(): void {// Cleared on `will-quit` (canonical shutdown ordering — NOT `before-quit`,// which fires earlier in the shutdown sequence). Each handle's teardown- // method (`destroy()` or `stop()`) is idempotent, and the null-assignment- // after each call makes subsequent will-quit re-entrances no-ops.- app.on('will-quit', () => {+ // method (`destroy()` or `stop()`) is idempotent. The first pass holds quit+ // for the terminal drain; the re-entrant pass performs the remaining teardown.+ // Windows session-end terminates without `will-quit`, so this drain does not run there.+ const runTerminalQuitDrain = createTerminalQuitDrain({+ defer: (callback) => setImmediate(callback),+ drain: () => terminalReaper?.killAll() ?? Promise.resolve(),+ resumeQuit: () => app.quit(),+ });+ app.on('will-quit', (event) => {+ if (runTerminalQuitDrain(event)) return;getLogger('lifecycle').info({}, 'will-quit');// A quit that reaches here was orderly — clear the dirty-shutdown// sentinel so the next boot doesn't read this session as a crash.@@ -9351,7 +9418,7 @@ function bootPrimaryInstance(): void {rendererRecovery = null;// Reap every window's PTY host first so no user shell / spawn-helper// outlives the app. Idempotent (clears the map; a second pass no-ops).- terminalReaper?.killAll();+ void terminalReaper?.killAll();// Reap every spawned Slidev server for the same reason. Idempotent.slidesDeckRegistry.reapAll();dockVisibleForWindow.clear();diff --git a/packages/desktop/src/main/ipc-handlers.ts b/packages/desktop/src/main/ipc-handlers.tsindex acf20b64e..d948825e2 100644--- a/packages/desktop/src/main/ipc-handlers.ts+++ b/packages/desktop/src/main/ipc-handlers.ts@@ -104,7 +104,7 @@ function xdgMimeReal(scheme: string, timeoutMs: number): Promise<{ stdout: strinexecFile('xdg-mime',['query', 'default', `x-scheme-handler/${scheme}`],- { timeout: timeoutMs, encoding: 'utf-8' },+ { timeout: timeoutMs, encoding: 'utf-8', windowsHide: true },(err, stdout) => {if (err) {// Treat timeout / missing xdg-mime / non-zero exit as "not registered"diff --git a/packages/desktop/src/main/ipc/local-op.ts b/packages/desktop/src/main/ipc/local-op.tsindex 718a80eba..266080708 100644--- a/packages/desktop/src/main/ipc/local-op.ts+++ b/packages/desktop/src/main/ipc/local-op.ts@@ -251,6 +251,7 @@ function runCoalescedAuthQuery<T>(if (inFlight.size >= MAX_CONCURRENT_AUTH_QUERIES) {return Promise.resolve(tooManyError(host));}+ // biome-ignore lint/plugin/require-windowshide-on-spawn: callback starts a request; it is not node:child_process.spawnconst promise = spawn().finally(() => {inFlight.delete(host);});diff --git a/packages/desktop/src/main/linux-install-fallback.ts b/packages/desktop/src/main/linux-install-fallback.tsindex 0537ec27f..b8252da51 100644--- a/packages/desktop/src/main/linux-install-fallback.ts+++ b/packages/desktop/src/main/linux-install-fallback.ts@@ -140,6 +140,7 @@ export function hasCommandOnPath(shell: true,stdio: 'ignore',timeout: timeoutMs,+ windowsHide: true,});return result.error == null && result.status === 0;} catch (err) {diff --git a/packages/desktop/src/main/list-git-worktrees.ts b/packages/desktop/src/main/list-git-worktrees.tsindex 969f49ab9..2f11feb7d 100644--- a/packages/desktop/src/main/list-git-worktrees.ts+++ b/packages/desktop/src/main/list-git-worktrees.ts@@ -64,6 +64,7 @@ export async function listGitWorktrees(anchorPath: string): Promise<BridgeWorktrcwd: anchorPath,env: gitSpawnEnv(),maxBuffer: MAX_STDOUT_BYTES,+ windowsHide: true,});stdout = String(result.stdout);} catch (err) {diff --git a/packages/desktop/src/main/menu.ts b/packages/desktop/src/main/menu.tsindex e20709368..189b7f9ad 100644--- a/packages/desktop/src/main/menu.ts+++ b/packages/desktop/src/main/menu.ts@@ -50,7 +50,6 @@ import {import type { Dialog, MenuItemConstructorOptions } from 'electron';import type { EntryPoint } from '../shared/entry-point.ts';import type { EditorActiveTargetSnapshot } from '../shared/ipc-channels.ts';-import { isTerminalPlatform } from '../shared/terminal-platform.ts';import { promptForExistingFolder, promptForExistingMarkdownFile } from './dialog-helpers.ts';import { type MenuTranslator, translateEnglish } from './menu-translator.ts';@@ -65,6 +64,8 @@ export interface MenuDeps {* Caller decides; this module just renders.*/showDevToolsMenu: boolean;+ /** Main-owned host capability, including the Windows ConPTY build floor. */+ terminalCapable: boolean;/** `electron.dialog` — injected so the File → Open folder click handler* can call `promptForExistingFolder(dialog)` without importing `dialog`* at module scope (breaks Vitest module load). */@@ -700,7 +701,7 @@ function menuCommandContext(deps: MenuDeps): CommandContext {activeTargetKind: menuTargetKind(deps.activeTarget),// The native menu has no single-file concept; those commands never gate here.singleFile: false,- terminalCapable: isTerminalPlatform(process.platform),+ terminalCapable: deps.terminalCapable,terminalLive: deps.terminalLive === true,canExpandAll: deps.canExpandAll ?? true,canCollapseAll: deps.canCollapseAll ?? true,diff --git a/packages/desktop/src/main/path-containment.test.ts b/packages/desktop/src/main/path-containment.test.tsindex cbbfb0b48..e192a129c 100644--- a/packages/desktop/src/main/path-containment.test.ts+++ b/packages/desktop/src/main/path-containment.test.ts@@ -68,6 +68,11 @@ describe('isPathWithinProject — win32', () => {expect(isPathWithinProject('c:\\proj\\file.zip', 'C:\\proj', 'win32')).toBe(true);});+ test('does not apply cmd.exe grammar to a lexical containment check', () => {+ expect(isPathWithinProject('C:\\proj%20\\.ok', 'C:\\proj%20', 'win32')).toBe(true);+ expect(validateSpawnPath('C:\\proj%20\\.ok', 'win32')).toBe(false);+ });+test('rejects dot-dot escapes and the sibling-prefix collision', () => {expect(isPathWithinProject('C:\\proj\\..\\windows\\evil.zip', 'C:\\proj', 'win32')).toBe(false);expect(isPathWithinProject('C:\\proj-evil\\file.zip', 'C:\\proj', 'win32')).toBe(false);@@ -106,7 +111,7 @@ describe('isPathWithinProject — win32', () => {describe('isPathWithinProject — parity with the server isPathWithinDir', () => {// The two functions implement one security contract from independent copies- // (see the module header's consolidation note). This matrix pins them to+ // (see the shared implementation's trust-boundary note). This matrix pins them to// identical verdicts so a fix or hardening applied to only one of them// fails here instead of drifting silently. Lexical, symlink-free vectors// only — neither implementation resolves symlinks.diff --git a/packages/desktop/src/main/path-containment.ts b/packages/desktop/src/main/path-containment.tsindex b045d3ccc..457cb2878 100644--- a/packages/desktop/src/main/path-containment.ts+++ b/packages/desktop/src/main/path-containment.ts@@ -1,106 +1,3 @@-/**- * Renderer-path containment primitives shared by every IPC handler that acts- * on a renderer-supplied filesystem path (`spawnCursor`, `showItemInFolder`,- * `trashItem`, asset opens, bug-report send). Lives in its own leaf module —- * importing only `node:path` — so validation-only consumers don't drag in the- * rest of the handler surface (and its `@inkeep/open-knowledge-server`- * dependency, which several sibling test suites replace via `vi.doMock`).- */--import { posix as pathPosix, win32 as pathWin32 } from 'node:path';--/** Reject non-absolute paths, null bytes, and empties. Shared with tests. */-export function validateSpawnPath(path: string, platform: NodeJS.Platform): boolean {- if (!path || typeof path !== 'string') return false;- if (path.includes('\0')) return false;- if (platform === 'win32') {- // The Windows spawn path runs through `cmd.exe` (the only way to launch a- // `.cmd` shim, and how a global install resolves against PATHEXT), so the- // deck path is re-parsed under cmd's grammar after Node builds the command- // line. Quoting makes `& | < > ^` inert, but two characters survive it:- // `%` still expands inside double quotes, and `"` cannot be quoted at all.- // Both are refused here rather than escaped — neither is legal in a Windows- // filename anyway (`"`) or plausible in a deck name (`%`), so refusing costs- // nothing and removes the class instead of trying to out-escape cmd.- if (/["%]/.test(path)) return false;- // Match `C:\…`, `C:/…`, or UNC `\\server\share\…`.- return /^([a-zA-Z]:[\\/]|\\\\)/.test(path);- }- // POSIX (darwin / linux) — absolute paths start with `/`.- return path.startsWith('/');-}--/**- * Resolve both paths canonically and verify `path` lies at or under- * `projectPath`. Returns false on invalid inputs or boundary escape.- *- * Uses `path/posix` or `path/win32` explicitly instead of the host default so- * Windows inputs resolve correctly on a POSIX dev runner under test, and- * production behavior follows the caller's platform regardless of Node's- * runtime `path` module.- *- * On Windows, also rejects when the two paths don't share a canonical root- * (drive letter or `\\server\share` for UNC, `\\?\…` / `\\.\…` for device- * namespaces). Without that check, `path.win32.relative()` returns the- * absolute "to" path when roots differ — and the rel-shape probes below- * miss the UNC / device-prefix forms because they don't begin with a drive- * letter. Root comparison is case-insensitive (Windows filesystem semantics).- *- * Lexical comparison only — does not resolve symlinks. A symlink inside- * `projectPath` that targets a path outside (e.g. `<proj>/notes -> /etc`)- * passes this check; the OS will follow it at use time.- *- * **Logical sibling of `isPathWithinDir` in `@inkeep/open-knowledge-server`.**- * Both implement the same containment algorithm; the desktop version is- * retained because its test suite exercises edge cases this file uniquely- * cares about (Electron `showItemInFolder` UNC + device-namespace handling).- * If the two versions ever drift, consolidate by re-exporting one as the- * other — they share a security contract. A parity matrix in- * `path-containment.test.ts` pins the two to identical verdicts.- */-export function isPathWithinProject(- userPath: string,- projectPath: string,- platform: NodeJS.Platform,-): boolean {- if (!validateSpawnPath(userPath, platform)) return false;- if (!validateSpawnPath(projectPath, platform)) return false;- const p = platform === 'win32' ? pathWin32 : pathPosix;- try {- const canonicalUser = p.resolve(userPath);- const canonicalProject = p.resolve(projectPath);- if (platform === 'win32') {- const userRoot = p.parse(canonicalUser).root.toLowerCase();- const projectRoot = p.parse(canonicalProject).root.toLowerCase();- if (!userRoot || !projectRoot || userRoot !== projectRoot) return false;- }- if (canonicalUser === canonicalProject) return true;- const rel = p.relative(canonicalProject, canonicalUser);- // `relative` returns `..` / `..\foo` / `../foo` when `userPath` escapes- // the project root, or an absolute form when roots differ on Windows.- if (rel === '' || rel === '.') return true;- if (rel === '..' || rel.startsWith(`..${p.sep}`)) return false;- // Defense-in-depth — the root check above already rejects cross-root,- // but if a future code path introduces another way for `rel` to come- // back absolute (drive `D:\…`, UNC `\\server\…`, device `\\?\…`,- // `\\.\…`), refuse it here.- if (platform === 'win32' && (/^[a-zA-Z]:[\\/]/.test(rel) || rel.startsWith('\\\\'))) {- return false;- }- if (platform !== 'win32' && rel.startsWith('/')) return false;- return true;- } catch (err) {- // path.resolve / path.parse are total on inputs that pass the shape- // checks above — a throw here is unexpected (corrupted unicode, a- // Node-internals regression). Warn so an engineer debugging an- // unexplained containment refusal sees the root cause instead of- // investigating a phantom path-escape — same semantics as- // `isPathWithinDir` in `@inkeep/open-knowledge-server`.- // Deliberate `console.warn` rather than the pino desktop logger (the- // AGENTS.md default): this is a dependency-free leaf containment util- // shared with contexts that inject no logger, mirroring the logger-free- // server `isPathWithinDir` it must stay verdict-compatible with.- console.warn('[path-containment] unexpected path-resolution error:', err);- return false;- }-}+// Compatibility facade for main-process imports; the implementation is shared+// with utility-process call sites so both process boundaries enforce one rule.+export { isPathWithinProject, validateSpawnPath } from '../shared/path-containment.ts';diff --git a/packages/desktop/src/main/path-install.ts b/packages/desktop/src/main/path-install.tsindex 655d82441..e2a11775d 100644--- a/packages/desktop/src/main/path-install.ts+++ b/packages/desktop/src/main/path-install.ts@@ -359,6 +359,7 @@ export async function defaultSpawn(const child = nodeSpawn(command, args, {env: opts.env as NodeJS.ProcessEnv,stdio: ['ignore', 'pipe', 'pipe'],+ windowsHide: true,});// A stuck shell (slow .zshrc, network-mounted home) must never hold// the main process open at quit, accumulate output past the timeout,@@ -409,6 +410,7 @@ async function discoverRealInteractivePath(const spawn = opts.spawn ?? defaultSpawn;const logger = opts.logger ?? DEFAULT_LOGGER;try {+ // biome-ignore lint/plugin/require-windowshide-on-spawn: injected command-runner seam; defaultSpawn owns child_process optionsconst result = await spawn(shell, ['-ilc', 'printf %s "$PATH"'], { timeoutMs: 2000, env });if (result.code !== 0 || result.timedOut || !result.stdout) {logger.event({diff --git a/packages/desktop/src/main/shell-env.ts b/packages/desktop/src/main/shell-env.tsindex 88bd066a7..df39ea5c2 100644--- a/packages/desktop/src/main/shell-env.ts+++ b/packages/desktop/src/main/shell-env.ts@@ -62,6 +62,7 @@ export async function harvestShellAuthSock(const spawn = opts.spawn ?? defaultSpawn;const logger = opts.logger ?? DEFAULT_LOGGER;try {+ // biome-ignore lint/plugin/require-windowshide-on-spawn: injected command-runner seam; defaultSpawn owns child_process optionsconst result = await spawn(shell, ['-ilc', `printf %s "${MARK}$SSH_AUTH_SOCK${MARK}"`], {timeoutMs: opts.timeoutMs ?? 2000,env,diff --git a/packages/desktop/src/main/slides-deck-path.test.ts b/packages/desktop/src/main/slides-deck-path.test.tsindex ed1ef0304..1069395b3 100644--- a/packages/desktop/src/main/slides-deck-path.test.ts+++ b/packages/desktop/src/main/slides-deck-path.test.ts@@ -8,9 +8,10 @@* fake, not the guard. These build genuine symlinks in a temp dir and let the* real `realpathSync` resolve them.*- * `realpath` stays injected only for the throwing paths (ENOENT / ELOOP), where- * provoking the real errno is either slow or platform-fragile — and those cases- * assert the refusal, not a resolved value.+ * `realpath` stays injected for OS-returned canonical-path edge cases and the+ * throwing paths (ENOENT / ELOOP), where provoking the real behavior is either+ * slow or platform-fragile — and those cases assert the refusal, not a resolved+ * value.*/import { mkdirSync, mkdtempSync, realpathSync, rmSync, symlinkSync, writeFileSync } from 'node:fs';@@ -124,6 +125,41 @@ describe('resolveDeckPath — refuses an escape', () => {expect(result).toEqual({ ok: false, reason: 'invalid-path' });});+ test.each([+ {+ name: 'resolved deck path',+ docPath: 'C:\\project\\decks\\talk.md',+ projectRoot: 'C:\\project',+ resolvedDocPath: 'C:\\project\\decks\\%CMDCMDLINE%.md',+ },+ {+ name: 'canonical project root',+ docPath: 'C:\\project\\decks\\talk.md',+ projectRoot: 'C:\\project%CMDCMDLINE%',+ resolvedDocPath: 'C:\\project%CMDCMDLINE%\\decks\\talk.md',+ },+ {+ name: 'quoted resolved deck path',+ docPath: 'C:\\project\\decks\\talk.md',+ projectRoot: 'C:\\project',+ resolvedDocPath: 'C:\\project\\decks\\talk"notes.md',+ },+ {+ name: 'quoted canonical project root',+ docPath: 'C:\\project\\decks\\talk.md',+ projectRoot: 'C:\\project"notes',+ resolvedDocPath: 'C:\\project"notes\\decks\\talk.md',+ },+ ])('refuses cmd.exe grammar in the post-realpath $name', (input) => {+ const result = resolveDeckPath({+ platform: 'win32',+ docPath: input.docPath,+ projectRoot: input.projectRoot,+ realpath: () => input.resolvedDocPath,+ });+ expect(result).toEqual({ ok: false, reason: 'invalid-path' });+ });+test('surfaces a symlink loop as a refusal with its code', () => {// ELOOP is awkward to provoke portably, so this one case uses an injected// resolver — it asserts the refusal shape, never a resolved path.diff --git a/packages/desktop/src/main/slides-deck-path.ts b/packages/desktop/src/main/slides-deck-path.tsindex ec60769a2..31a7f785b 100644--- a/packages/desktop/src/main/slides-deck-path.ts+++ b/packages/desktop/src/main/slides-deck-path.ts@@ -17,10 +17,10 @@* realpath-canonical via discoverProject). A window with no project has nothing* to contain against, so it is refused.*- * `realpath` is injected so a test can drive the throwing paths (ENOENT on a- * broken symlink, ELOOP on a cycle) deterministically; the real filesystem is- * the higher-fidelity default and is what the suite exercises for the escape- * case, using a genuine symlink rather than a stubbed resolver.+ * `realpath` is injected so tests can drive filesystem failures and returned+ * canonical-path edge cases deterministically; the real filesystem is the+ * higher-fidelity default and is what the suite exercises for the escape case,+ * using a genuine symlink rather than a stubbed resolver.*/import { isPathWithinProject, validateSpawnPath } from './path-containment.ts';@@ -48,8 +48,8 @@ export interface ResolveDeckPathDeps {* when the window has no project — nothing to contain against. */readonly projectRoot: string | undefined;readonly platform: NodeJS.Platform;- /** Injected so the throwing paths are drivable; production passes the real- * `node:fs` `realpathSync`. */+ /** Injected so filesystem boundary cases are drivable; production passes+ * the real `node:fs` `realpathSync`. */realpath(path: string): string;}@@ -72,7 +72,11 @@ export function resolveDeckPath(deps: ResolveDeckPathDeps): DeckPathResolution {};}- if (!isPathWithinProject(resolvedDocPath, projectRoot, platform)) {+ if (+ !validateSpawnPath(resolvedDocPath, platform) ||+ !validateSpawnPath(projectRoot, platform) ||+ !isPathWithinProject(resolvedDocPath, projectRoot, platform)+ ) {return { ok: false, reason: 'invalid-path' };}return { ok: true, resolvedDocPath, projectRoot };diff --git a/packages/desktop/src/main/slidev-server.ts b/packages/desktop/src/main/slidev-server.tsindex f0bb4218a..ed6585383 100644--- a/packages/desktop/src/main/slidev-server.ts+++ b/packages/desktop/src/main/slidev-server.ts@@ -289,8 +289,8 @@ function shSingleQuote(value: string): string {}/** Wrap a token for `cmd.exe`. Double quotes make `& | < > ^` inert; the- * two characters quoting cannot neutralize (`"` and `%`) are refused at- * admission by `validateSpawnPath`, so there is nothing left to escape. */+ * two characters quoting cannot neutralize (`"` and `%`) are refused by the+ * post-realpath spawn-path admission, so there is nothing left to escape. */function cmdQuote(value: string): string {return `"${value}"`;}@@ -331,8 +331,8 @@ export function buildSlidevInvocation(? projectLocalSlidevBin(config.projectRoot, platform): 'slidev';// `/s` strips exactly the outer quote pair and treats the remainder- // literally, so each token can carry its own quotes. `"` and `%` are refused- // upstream by `validateSpawnPath` because quoting cannot neutralize them.+ // literally, so each token can carry its own quotes. `resolveDeckPath`+ // rejects `"` and `%` after realpath because quoting cannot neutralize them.const cmdline = `"${cmdQuote(target)} ${cmdQuote(config.docPath)} ${portArgs.join(' ')}"`;return {mode: 'windows-shell',diff --git a/packages/desktop/src/main/terminal-capability.test.ts b/packages/desktop/src/main/terminal-capability.test.tsnew file mode 100644index 000000000..050446e7f--- /dev/null+++ b/packages/desktop/src/main/terminal-capability.test.ts@@ -0,0 +1,44 @@+import { describe, expect, test } from 'vitest';+import {+ isTerminalAvailable,+ parseWindowsBuildNumber,+ TERMINAL_AVAILABLE_ARG,+ WINDOWS_CONPTY_MIN_BUILD,+ withTerminalCapabilityArg,+} from './terminal-capability.ts';++describe('Windows terminal capability floor', () => {+ test('parses the Windows build component from os.release()', () => {+ expect(parseWindowsBuildNumber('10.0.17763')).toBe(17763);+ expect(parseWindowsBuildNumber('10.0.26100')).toBe(26100);+ expect(parseWindowsBuildNumber('10.0')).toBeNull();+ expect(parseWindowsBuildNumber('10.0.preview')).toBeNull();+ });++ test('keeps every terminal affordance unavailable below Windows 10 1809', () => {+ expect(isTerminalAvailable('win32', WINDOWS_CONPTY_MIN_BUILD - 1)).toBe(false);+ });++ test('enables Windows at the 1809 floor and above', () => {+ expect(isTerminalAvailable('win32', WINDOWS_CONPTY_MIN_BUILD)).toBe(true);+ expect(isTerminalAvailable('win32', WINDOWS_CONPTY_MIN_BUILD + 1)).toBe(true);+ });++ test('keeps the existing macOS and Linux capability independent of the Windows build', () => {+ expect(isTerminalAvailable('darwin', null)).toBe(true);+ expect(isTerminalAvailable('linux', null)).toBe(true);+ });++ test('fails closed when a Windows build cannot be determined', () => {+ expect(isTerminalAvailable('win32', null)).toBe(false);+ expect(isTerminalAvailable('win32', Number.NaN)).toBe(false);+ });++ test('feeds only a positive capability verdict into renderer-window argv', () => {+ expect(withTerminalCapabilityArg(['--ok-mode=editor'], false)).toEqual(['--ok-mode=editor']);+ expect(withTerminalCapabilityArg(['--ok-mode=editor'], true)).toEqual([+ '--ok-mode=editor',+ TERMINAL_AVAILABLE_ARG,+ ]);+ });+});diff --git a/packages/desktop/src/main/terminal-capability.ts b/packages/desktop/src/main/terminal-capability.tsnew file mode 100644index 000000000..e17da5d1c--- /dev/null+++ b/packages/desktop/src/main/terminal-capability.ts@@ -0,0 +1,33 @@+import { release as osRelease } from 'node:os';+import { isTerminalPlatform } from '../shared/terminal-platform.ts';++/** Windows 10 version 1809, the first release with the ConPTY API. */+export const WINDOWS_CONPTY_MIN_BUILD = 17763;+export const TERMINAL_AVAILABLE_ARG = '--ok-pty-available=1';++/** Extract the numeric build component from Node's Windows os.release() value. */+export function parseWindowsBuildNumber(release: string): number | null {+ const build = release.split('.')[2];+ if (build === undefined || !/^\d+$/.test(build)) return null;+ const parsed = Number(build);+ return Number.isSafeInteger(parsed) ? parsed : null;+}++/** Main-process terminal capability, with an injectable Windows build seam. */+export function isTerminalAvailable(+ platform: NodeJS.Platform = process.platform,+ windowsBuildNumber?: number | null,+): boolean {+ if (!isTerminalPlatform(platform)) return false;+ if (platform !== 'win32') return true;+ const build =+ windowsBuildNumber === undefined ? parseWindowsBuildNumber(osRelease()) : windowsBuildNumber;+ return (+ typeof build === 'number' && Number.isSafeInteger(build) && build >= WINDOWS_CONPTY_MIN_BUILD+ );+}++/** Carry main's capability verdict into the sandboxed preload. */+export function withTerminalCapabilityArg(args: readonly string[], available: boolean): string[] {+ return available ? [...args, TERMINAL_AVAILABLE_ARG] : [...args];+}diff --git a/packages/desktop/src/main/terminal-consent.test.ts b/packages/desktop/src/main/terminal-consent.test.tsindex 7adf98207..f9922cd04 100644--- a/packages/desktop/src/main/terminal-consent.test.ts+++ b/packages/desktop/src/main/terminal-consent.test.ts@@ -19,6 +19,7 @@ import { describe, expect, test } from 'vitest';import {isTerminalConsented,isTerminalConsentedWithGrace,+ readTerminalShellSetting,TERMINAL_CONSENT_GRACE_TIMEOUT_MS,} from './terminal-consent.ts';@@ -120,6 +121,64 @@ describe('isTerminalConsented (fail-open backstop)', () => {});});+describe('readTerminalShellSetting', () => {+ test('reads a configured non-empty string from project-local config', () => {+ const dir = makeProjectDir();+ try {+ writeRaw(dir, 'terminal:\n shell: C:\\Tools\\pwsh.exe\n');+ expect(readTerminalShellSetting(dir)).toEqual({+ kind: 'configured',+ shell: 'C:\\Tools\\pwsh.exe',+ });+ } finally {+ rmSync(dir, { recursive: true, force: true });+ }+ });++ test.each(['', ' '])('treats %j as unset', (shell) => {+ const dir = makeProjectDir();+ try {+ writeRaw(dir, `terminal:\n shell: ${JSON.stringify(shell)}\n`);+ expect(readTerminalShellSetting(dir)).toEqual({ kind: 'unset' });+ } finally {+ rmSync(dir, { recursive: true, force: true });+ }+ });++ test('classifies a present non-string override as invalid', () => {+ const dir = makeProjectDir();+ try {+ writeRaw(dir, 'terminal:\n shell: 42\n');+ expect(readTerminalShellSetting(dir)).toEqual({+ kind: 'invalid',+ reason: 'invalid-value',+ });+ } finally {+ rmSync(dir, { recursive: true, force: true });+ }+ });++ test('missing and absent settings are unset while malformed YAML is diagnosed', () => {+ const missing = makeProjectDir();+ const malformed = makeProjectDir();+ const absent = makeProjectDir();+ try {+ writeRaw(malformed, 'terminal:\n shell: [');+ writeRaw(absent, 'terminal:\n enabled: true\n');+ expect(readTerminalShellSetting(missing)).toEqual({ kind: 'unset' });+ expect(readTerminalShellSetting(malformed)).toEqual({+ kind: 'invalid',+ reason: 'config-unreadable',+ });+ expect(readTerminalShellSetting(absent)).toEqual({ kind: 'unset' });+ } finally {+ for (const dir of [missing, malformed, absent]) {+ rmSync(dir, { recursive: true, force: true });+ }+ }+ });+});+describe('grace budget vs. store debounce', () => {// Guards the calibration directly: shrinking the default back below the// debounce reintroduces the "re-enable does nothing until reopen" bug.diff --git a/packages/desktop/src/main/terminal-consent.ts b/packages/desktop/src/main/terminal-consent.tsindex 47064cd9c..8ac10c831 100644--- a/packages/desktop/src/main/terminal-consent.ts+++ b/packages/desktop/src/main/terminal-consent.ts@@ -25,12 +25,47 @@ import { existsSync, readFileSync } from 'node:fs';import { sleep } from '@inkeep/open-knowledge-core';import { resolveConfigPath } from '@inkeep/open-knowledge-core/server';import { parse as parseYaml } from 'yaml';+import type { TerminalShellNoticeReason } from '../shared/bridge-contract.ts';import { getLogger } from './desktop-logger.ts';function isObject(v: unknown): v is Record<string, unknown> {return typeof v === 'object' && v !== null && !Array.isArray(v);}+export type TerminalShellSetting =+ | { readonly kind: 'unset' }+ | { readonly kind: 'configured'; readonly shell: string }+ | {+ readonly kind: 'invalid';+ // The two reasons this reader can produce, carved out of the shared notice+ // union rather than restated, so the narrowing stays wired to the contract+ // the renderer eventually receives.+ readonly reason: Extract<TerminalShellNoticeReason, 'config-unreadable' | 'invalid-value'>;+ };++/** Read the raw project-local shell override without applying schema defaults. */+export function readTerminalShellSetting(projectDir: string): TerminalShellSetting {+ const path = resolveConfigPath('project-local', projectDir);+ if (!existsSync(path)) return { kind: 'unset' };+ let parsed: unknown;+ try {+ parsed = parseYaml(readFileSync(path, 'utf-8'));+ } catch (err) {+ getLogger('terminal-consent').warn(+ { err },+ 'shell override read/parse failed; treating as unset',+ );+ return { kind: 'invalid', reason: 'config-unreadable' };+ }+ if (!isObject(parsed) || !isObject(parsed.terminal) || !('shell' in parsed.terminal)) {+ return { kind: 'unset' };+ }+ const shell = parsed.terminal.shell;+ if (typeof shell !== 'string') return { kind: 'invalid', reason: 'invalid-value' };+ if (shell.trim().length === 0) return { kind: 'unset' };+ return { kind: 'configured', shell };+}+/*** False only when the project-local config explicitly sets* `terminal.enabled: false`. A missing file, unreadable file, malformed YAML, andiff --git a/packages/desktop/src/main/terminal-lifecycle.ts b/packages/desktop/src/main/terminal-lifecycle.tsindex f9afab75a..3f53e8b8b 100644--- a/packages/desktop/src/main/terminal-lifecycle.ts+++ b/packages/desktop/src/main/terminal-lifecycle.ts@@ -13,7 +13,7 @@/** The reap surface the manager exposes; `TerminalManager` satisfies it structurally. */export interface TerminalReaper {killForWindow(windowId: number): void;- killAll(): void;+ killAll(): Promise<void>;}/** Minimal BrowserWindow shape the reap wiring reads — id + a close subscription. */diff --git a/packages/desktop/src/main/terminal-manager.ts b/packages/desktop/src/main/terminal-manager.tsindex b5155dcd8..5d3e34720 100644--- a/packages/desktop/src/main/terminal-manager.ts+++ b/packages/desktop/src/main/terminal-manager.ts@@ -24,7 +24,21 @@* unit-testable without an Electron runtime.*/-import type { OkPtyAdoptResult, OkPtyListEntry } from '../shared/bridge-contract.ts';+import {+ isWindowsShellFamily,+ type TerminalLaunchCommand,+ type WindowsShellFamily,+} from '@inkeep/open-knowledge-core';+import {+ isTerminalShellNoticeReason,+ isTerminalSupportFileNoticeReason,+} from '@inkeep/open-knowledge-core/desktop-bridge';+import type {+ OkPtyAdoptResult,+ OkPtyListEntry,+ OkPtyNotice,+ TerminalShellNoticeReason,+} from '../shared/bridge-contract.ts';import type { SendableWebContents } from '../shared/ipc-send.ts';import type { PtyHostIncomingMessage, PtyHostOutgoingMessage } from '../utility/pty-host.ts';@@ -49,6 +63,8 @@ export interface TerminalManagerDeps {webContents: SendableWebContents,payload: { ptyId: string; exitCode: number; signal: number | null; error?: string },) => void;+ /** Push a shell-resolution notice to the addressed terminal panel. */+ sendNotice?: (webContents: SendableWebContents, payload: OkPtyNotice) => void;/** Fresh PTY id — `randomUUID` in production; deterministic in tests. */newPtyId: () => string;/** Schedule a coalesce flush. `setTimeout` in production; captured in tests. */@@ -64,6 +80,8 @@ export interface TerminalManagerDeps {/** Cap on the per-session reload-replay ring (retained screen + scrollback the* reloaded renderer repaints on adopt). Default 256 KiB. */replayCapBytes?: number;+ /** Grace period after host shutdown IPC before force-kill. Default 2 seconds. */+ shutdownMs?: number;/** Optional structured warn sink (pino `getLogger` in production). */logger?: { warn: (o: Record<string, unknown>) => void };/**@@ -98,14 +116,17 @@ interface TerminalCreateRequest {projectRoot: string | null;cols: number;rows: number;+ /** Project-local executable override; the utility resolver validates it. */+ shell?: string;+ /** A present project-local override could not be used. */+ shellInvalidReason?: TerminalShellNoticeReason;/**- * "Open in <Agent>" launch command — the fixed `<bin> [pre-approve] '<prompt>'`- * shape (no trailing `\r`). When present, the host bakes it into the shell- * spawn (`$SHELL -l -i -c '<this>; exec …'`) so the agent runs without the- * command being typed into the shell and thus recorded in the user's history.- * Omitted for a plain terminal tab. Forwarded verbatim to the host's create.+ * "Open in <Agent>" launch. POSIX uses its composed command string; Windows+ * uses structured executable + argv data. The host bakes either form into the+ * resolved shell's startup args, bypassing the interactive line editor and+ * persistent history. Omitted for a plain terminal tab.*/- launchCommand?: string;+ launchCommand?: string | TerminalLaunchCommand;}interface TerminalAddressedRequest {@@ -163,6 +184,10 @@ interface SessionState {* overwrites it via set-order on a drag / keyboard reorder, and `listSessions`* sorts by it so a reload restores the user's arrangement. */order: number;+ /** Resolved Windows shell parser, retained so reload adoption keeps path escaping correct. */+ shellFamily: WindowsShellFamily | null;+ /** Standing capability limit retained so reload adoption restores its explanation. */+ shellNoticeReason: Extract<TerminalShellNoticeReason, 'unsupported-family'> | null;}interface PtyWindowHandle {@@ -170,6 +195,9 @@ interface PtyWindowHandle {utility: PtyUtilityLike;/** Live sessions keyed by ptyId — one per terminal tab in this window. */sessions: Map<string, SessionState>;+ shutdownToken: TimerToken | null;+ shutdownPromise: Promise<void> | null;+ shutdownResolve: (() => void) | null;}/**@@ -192,6 +220,7 @@ const DEFAULT_LOW_WATER = 256 * 1024;* the session exits). Overridable via `deps.replayCapBytes`.*/const DEFAULT_REPLAY_CAP = 256 * 1024;+const DEFAULT_SHUTDOWN_MS = 2000;/** Sane fallback PTY size when the renderer sends an out-of-range dimension. */export const DEFAULT_PTY_COLS = 80;@@ -262,7 +291,7 @@ export interface TerminalManager {/** Window-close reap. Idempotent. */killForWindow(windowId: number): void;/** App-quit reap of every window's PTY host. */- killAll(): void;+ killAll(): Promise<void>;}export function createTerminalManager(deps: TerminalManagerDeps): TerminalManager {@@ -270,7 +299,9 @@ export function createTerminalManager(deps: TerminalManagerDeps): TerminalManageconst highWater = deps.highWaterBytes ?? DEFAULT_HIGH_WATER;const lowWater = deps.lowWaterBytes ?? DEFAULT_LOW_WATER;const replayCap = deps.replayCapBytes ?? DEFAULT_REPLAY_CAP;+ const shutdownMs = deps.shutdownMs ?? DEFAULT_SHUTDOWN_MS;const handles = new Map<number, PtyWindowHandle>();+ const pendingShutdowns = new Set<Promise<void>>();/** Kill a host without letting a throw abort a multi-window reap loop. The* utilityProcess may already be gone (TOCTOU) so `kill()` can throw; mirrors@@ -290,6 +321,51 @@ export function createTerminalManager(deps: TerminalManagerDeps): TerminalManage}}+ function warnPostFailed(event: string, err: unknown, extra?: Record<string, unknown>): void {+ deps.logger?.warn({+ event,+ code: (err as { code?: string } | null)?.code ?? 'unknown',+ ...extra,+ });+ }++ function clearShutdownDeadline(handle: PtyWindowHandle): void {+ if (handle.shutdownToken === null) return;+ deps.clearTimer(handle.shutdownToken);+ handle.shutdownToken = null;+ }++ function finishHostShutdown(handle: PtyWindowHandle): void {+ clearShutdownDeadline(handle);+ handle.shutdownResolve?.();+ handle.shutdownResolve = null;+ }++ function beginHostShutdown(handle: PtyWindowHandle): Promise<void> {+ if (handle.shutdownPromise !== null) return handle.shutdownPromise;+ const shutdownPromise = new Promise<void>((resolve) => {+ handle.shutdownResolve = resolve;+ });+ handle.shutdownPromise = shutdownPromise;+ pendingShutdowns.add(shutdownPromise);+ void shutdownPromise.finally(() => pendingShutdowns.delete(shutdownPromise));+ handle.shutdownToken = deps.setTimer(() => {+ handle.shutdownToken = null;+ deps.logger?.warn({ event: 'terminal-manager-shutdown-deadline' });+ safeKillUtility(handle);+ finishHostShutdown(handle);+ }, shutdownMs);+ try {+ handle.utility.postMessage({ type: 'shutdown' });+ } catch (err) {+ clearShutdownDeadline(handle);+ warnPostFailed('terminal-manager-shutdown-send-failed', err);+ safeKillUtility(handle);+ finishHostShutdown(handle);+ }+ return shutdownPromise;+ }+function pushData(handle: PtyWindowHandle, ptyId: string, data: string): void {// The window can close mid-stream — `webContents.send` throws on a// destroyed WebContents and crashes main. Cross-time-mutation boundary;@@ -300,10 +376,20 @@ export function createTerminalManager(deps: TerminalManagerDeps): TerminalManagefunction pushExit(handle: PtyWindowHandle,- payload: { ptyId: string; exitCode: number; signal: number | null; error?: string },+ payload: {+ ptyId: string;+ exitCode: number | undefined;+ signal: number | null;+ error?: string;+ },): void {if (handle.webContents.isDestroyed?.()) return;- deps.sendExit(handle.webContents, payload);+ deps.sendExit(handle.webContents, { ...payload, exitCode: payload.exitCode ?? -1 });+ }++ function pushNotice(handle: PtyWindowHandle, payload: OkPtyNotice): void {+ if (handle.webContents.isDestroyed?.()) return;+ deps.sendNotice?.(handle.webContents, payload);}/**@@ -365,11 +451,18 @@ export function createTerminalManager(deps: TerminalManagerDeps): TerminalManagecase 'data':return typeof m.data === 'string' ? (raw as PtyHostOutgoingMessage) : null;case 'exit':- return typeof m.exitCode === 'number' && (m.signal === null || typeof m.signal === 'number')+ return (m.exitCode === undefined || typeof m.exitCode === 'number') &&+ (m.signal === null || typeof m.signal === 'number')? (raw as PtyHostOutgoingMessage): null;case 'spawn-error':return typeof m.message === 'string' ? (raw as PtyHostOutgoingMessage) : null;+ case 'shell-notice':+ return (m.notice === 'invalid-shell-override' && isTerminalShellNoticeReason(m.reason)) ||+ (m.notice === 'shell-resolved' && isWindowsShellFamily(m.shellFamily)) ||+ (m.notice === 'support-file-degraded' && isTerminalSupportFileNoticeReason(m.reason))+ ? (raw as PtyHostOutgoingMessage)+ : null;default:return null;}@@ -428,12 +521,39 @@ export function createTerminalManager(deps: TerminalManagerDeps): TerminalManagepushExit(handle, { ptyId, exitCode: 1, signal: null, error: message.message });break;}+ case 'shell-notice':+ if (message.notice === 'shell-resolved') {+ session.shellFamily = message.shellFamily;+ pushNotice(handle, {+ ptyId: message.ptyId,+ notice: message.notice,+ shellFamily: message.shellFamily,+ });+ // Keep the reason-carrying notices split: their reason unions differ,+ // so merging them would lose the notice-to-reason correlation.+ } else if (message.notice === 'invalid-shell-override') {+ if (message.reason === 'unsupported-family') {+ session.shellNoticeReason = message.reason;+ }+ pushNotice(handle, {+ ptyId: message.ptyId,+ notice: message.notice,+ reason: message.reason,+ });+ } else {+ pushNotice(handle, {+ ptyId: message.ptyId,+ notice: message.notice,+ reason: message.reason,+ });+ }+ break;}}- function onUtilityExit(windowId: number, code: number | null): void {- const handle = handles.get(windowId);- if (!handle) return;+ function onUtilityExit(windowId: number, handle: PtyWindowHandle, code: number | null): void {+ finishHostShutdown(handle);+ if (handles.get(windowId) !== handle) return;// The host process itself died (a native crash escaping pty-host's own// containment), taking every shell it multiplexed with it. Surface an exit// on each live session so no panel hangs, then drop the dead host so the@@ -482,10 +602,13 @@ export function createTerminalManager(deps: TerminalManagerDeps): TerminalManagewebContents: req.webContents,utility,sessions: new Map(),+ shutdownToken: null,+ shutdownPromise: null,+ shutdownResolve: null,};handles.set(req.windowId, handle);utility.on('message', (raw) => onUtilityMessage(req.windowId, raw));- utility.on('exit', (code) => onUtilityExit(req.windowId, code));+ utility.on('exit', (code) => onUtilityExit(req.windowId, handle, code));return handle;}@@ -518,6 +641,8 @@ export function createTerminalManager(deps: TerminalManagerDeps): TerminalManagecustomLabel: null,ordinal: null,order: nextOrder,+ shellFamily: null,+ shellNoticeReason: null,});// Record the concurrency reached by this open (1 for a solo tab, N for the// Nth concurrent tab). Concurrency only rises on create, so the per-window@@ -529,7 +654,11 @@ export function createTerminalManager(deps: TerminalManagerDeps): TerminalManagecwd: req.projectRoot,cols: req.cols,rows: req.rows,- launchCommand: req.launchCommand,+ ...(req.shell === undefined ? {} : { shell: req.shell }),+ ...(req.shellInvalidReason === undefined+ ? {}+ : { shellInvalidReason: req.shellInvalidReason }),+ ...(req.launchCommand === undefined ? {} : { launchCommand: req.launchCommand }),});return { ok: true, ptyId };},@@ -639,21 +768,12 @@ export function createTerminalManager(deps: TerminalManagerDeps): TerminalManagetry {handle.utility.postMessage({ type: 'resume', ptyId: req.ptyId });} catch (err) {- // The PTY host can exit in the same list()->adopt TOCTOU window the- // session-presence check above guards (postMessage on a dead- // utilityProcess throws). A dead host means a dead session, so refuse- // the adopt and let the panel spawn fresh rather than wire xterm to it.- // ESRCH is the expected host-already-gone code; surface anything else- // for diagnostics. Mirrors safeKillUtility's TOCTOU handling.- const code = (err as { code?: string } | null)?.code;- if (code !== 'ESRCH') {- deps.logger?.warn({- event: 'terminal-manager-adopt-resume-failed',- code: code ?? 'unknown',- windowId: req.windowId,- ptyId: req.ptyId,- });- }+ // A host we cannot post to is one we cannot drive, so refuse the adopt+ // and let the panel spawn fresh rather than wire xterm to it.+ warnPostFailed('terminal-manager-adopt-resume-failed', err, {+ windowId: req.windowId,+ ptyId: req.ptyId,+ });return { ok: false, reason: 'unknown-session' };}// Rebind delivery to the reloaded page's webContents (a normal in-page@@ -664,8 +784,16 @@ export function createTerminalManager(deps: TerminalManagerDeps): TerminalManagehandle.webContents = req.webContents;// Hand back the retained screen + scrollback so the fresh xterm repaints it// before live delivery resumes — without this the adopted tab is blank- // (issue #351 follow-up). The renderer writes `replay`, then wires onData.- return { ok: true, replay: session.replay };+ // (issue #351 follow-up). The renderer wires delivery first, then writes+ // `replay`, gating its own input until xterm finishes parsing it.+ return {+ ok: true,+ replay: session.replay,+ ...(session.shellFamily === null ? {} : { shellFamily: session.shellFamily }),+ ...(session.shellNoticeReason === null+ ? {}+ : { shellNoticeReason: session.shellNoticeReason }),+ };},killForWindow(windowId): void {@@ -680,18 +808,21 @@ export function createTerminalManager(deps: TerminalManagerDeps): TerminalManage// Delete first so the resulting utility `'exit'` event no-ops instead of// pushing spurious `ok:pty:exit`s into the closing window.handles.delete(windowId);- safeKillUtility(handle);+ void beginHostShutdown(handle);},- killAll(): void {+ async killAll(): Promise<void> {+ const shutdowns: Promise<void>[] = [];for (const handle of handles.values()) {for (const session of handle.sessions.values()) {clearFlush(session);maybeRecordSession(session);}- safeKillUtility(handle);+ shutdowns.push(beginHostShutdown(handle));}handles.clear();+ shutdowns.push(...pendingShutdowns);+ await Promise.all(shutdowns);},};}diff --git a/packages/desktop/src/main/terminal-quit-drain.test.ts b/packages/desktop/src/main/terminal-quit-drain.test.tsnew file mode 100644index 000000000..2c81535c2--- /dev/null+++ b/packages/desktop/src/main/terminal-quit-drain.test.ts@@ -0,0 +1,81 @@+import { describe, expect, test, vi } from 'vitest';+import { createTerminalQuitDrain } from './terminal-quit-drain.ts';++function deferred<T>() {+ let resolve!: (value: T | PromiseLike<T>) => void;+ let reject!: (reason?: unknown) => void;+ const promise = new Promise<T>((resolvePromise, rejectPromise) => {+ resolve = resolvePromise;+ reject = rejectPromise;+ });+ return { promise, reject, resolve };+}++describe('createTerminalQuitDrain', () => {+ test('defers quit re-entry until after the terminal drain and native event turn', async () => {+ const drain = deferred<void>();+ const deferredCallbacks: Array<() => void> = [];+ const resumeQuit = vi.fn();+ const onWillQuit = createTerminalQuitDrain({+ defer: (callback) => deferredCallbacks.push(callback),+ drain: () => drain.promise,+ resumeQuit,+ });+ const event = { preventDefault: vi.fn() };++ expect(onWillQuit(event)).toBe(true);+ expect(event.preventDefault).toHaveBeenCalledOnce();+ expect(resumeQuit).not.toHaveBeenCalled();++ drain.resolve();+ await drain.promise;+ await Promise.resolve();++ expect(resumeQuit).not.toHaveBeenCalled();+ expect(deferredCallbacks).toHaveLength(1);+ deferredCallbacks[0]?.();+ expect(resumeQuit).toHaveBeenCalledOnce();++ const reentrantEvent = { preventDefault: vi.fn() };+ expect(onWillQuit(reentrantEvent)).toBe(false);+ expect(reentrantEvent.preventDefault).not.toHaveBeenCalled();+ });++ test('coalesces repeated will-quit events while the drain is pending', () => {+ const drain = deferred<void>();+ const drainTerminals = vi.fn(() => drain.promise);+ const onWillQuit = createTerminalQuitDrain({+ defer: vi.fn(),+ drain: drainTerminals,+ resumeQuit: vi.fn(),+ });+ const firstEvent = { preventDefault: vi.fn() };+ const secondEvent = { preventDefault: vi.fn() };++ expect(onWillQuit(firstEvent)).toBe(true);+ expect(onWillQuit(secondEvent)).toBe(true);+ expect(firstEvent.preventDefault).toHaveBeenCalledOnce();+ expect(secondEvent.preventDefault).toHaveBeenCalledOnce();+ expect(drainTerminals).toHaveBeenCalledOnce();+ });++ test('resumes quit after a rejected best-effort drain', async () => {+ const drain = deferred<void>();+ const deferredCallbacks: Array<() => void> = [];+ const resumeQuit = vi.fn();+ const onWillQuit = createTerminalQuitDrain({+ defer: (callback) => deferredCallbacks.push(callback),+ drain: () => drain.promise,+ resumeQuit,+ });++ expect(onWillQuit({ preventDefault: vi.fn() })).toBe(true);+ drain.reject(new Error('drain failed'));+ await drain.promise.catch(() => undefined);+ await Promise.resolve();++ expect(deferredCallbacks).toHaveLength(1);+ deferredCallbacks[0]?.();+ expect(resumeQuit).toHaveBeenCalledOnce();+ });+});diff --git a/packages/desktop/src/main/terminal-quit-drain.ts b/packages/desktop/src/main/terminal-quit-drain.tsnew file mode 100644index 000000000..e313a2ca2--- /dev/null+++ b/packages/desktop/src/main/terminal-quit-drain.ts@@ -0,0 +1,38 @@+export interface QuitEventLike {+ preventDefault(): void;+}++export interface TerminalQuitDrainDeps {+ defer(callback: () => void): void;+ drain(): Promise<void>;+ resumeQuit(): void;+}++/**+ * Holds the first will-quit event open until terminal hosts settle. Resuming on+ * a later event-loop turn is load-bearing: an already-resolved drain otherwise+ * re-enters app.quit() from a Promise microtask before Electron has unwound the+ * prevented native event, and that re-entry is ignored.+ */+export function createTerminalQuitDrain(deps: TerminalQuitDrainDeps) {+ let drainStarted = false;+ let drainComplete = false;++ return (event: QuitEventLike): boolean => {+ if (drainComplete) return false;++ event.preventDefault();+ if (drainStarted) return true;+ drainStarted = true;++ const scheduleQuitResume = () => {+ deps.defer(() => {+ drainComplete = true;+ deps.resumeQuit();+ });+ };++ void deps.drain().then(scheduleQuitResume, scheduleQuitResume);+ return true;+ };+}diff --git a/packages/desktop/src/main/terminal-telemetry.test.ts b/packages/desktop/src/main/terminal-telemetry.test.tsindex 870d70fd1..8f7594841 100644--- a/packages/desktop/src/main/terminal-telemetry.test.ts+++ b/packages/desktop/src/main/terminal-telemetry.test.ts@@ -42,19 +42,25 @@ describe('recordShellExit — span name + crashed attribute', () => {recordShellExit({ crashed: false });expect(capturedCalls).toHaveLength(1);expect(capturedCalls[0]?.name).toBe('ok.desktop.shellExit');- expect(capturedCalls[0]?.options?.attributes).toEqual({ 'ok.desktop.shell_crashed': false });+ expect(capturedCalls[0]?.options?.attributes).toEqual({+ 'ok.desktop.shell_crashed': false,+ 'ok.platform': process.platform,+ });});test('a crash emits ok.desktop.shellExit with shell_crashed=true', () => {recordShellExit({ crashed: true });expect(capturedCalls).toHaveLength(1);- expect(capturedCalls[0]?.options?.attributes).toEqual({ 'ok.desktop.shell_crashed': true });+ expect(capturedCalls[0]?.options?.attributes).toEqual({+ 'ok.desktop.shell_crashed': true,+ 'ok.platform': process.platform,+ });});- test('the only attribute is the bounded crashed boolean — no path / code / signal leaks', () => {+ test('attributes stay bounded — no path / code / signal leaks', () => {recordShellExit({ crashed: true });const attrs = capturedCalls[0]?.options?.attributes ?? {};- expect(Object.keys(attrs)).toEqual(['ok.desktop.shell_crashed']);+ expect(Object.keys(attrs)).toEqual(['ok.desktop.shell_crashed', 'ok.platform']);});});@@ -63,11 +69,11 @@ describe('recordTerminalSession — count-only marker', () => {capturedCalls.length = 0;});- test('emits ok.desktop.terminalSession with no attributes (the span is the count)', () => {+ test('emits ok.desktop.terminalSession with only the bounded platform attribute', () => {recordTerminalSession();expect(capturedCalls).toHaveLength(1);expect(capturedCalls[0]?.name).toBe('ok.desktop.terminalSession');- expect(capturedCalls[0]?.options?.attributes ?? {}).toEqual({});+ expect(capturedCalls[0]?.options?.attributes).toEqual({ 'ok.platform': process.platform });});});@@ -80,13 +86,16 @@ describe('recordConcurrentSessions — count-only concurrency signal', () => {recordConcurrentSessions({ count: 3 });expect(capturedCalls).toHaveLength(1);expect(capturedCalls[0]?.name).toBe('ok.desktop.terminalConcurrentSessions');- expect(capturedCalls[0]?.options?.attributes).toEqual({ 'ok.desktop.concurrent_sessions': 3 });+ expect(capturedCalls[0]?.options?.attributes).toEqual({+ 'ok.desktop.concurrent_sessions': 3,+ 'ok.platform': process.platform,+ });});- test('the only attribute is the bounded count — no ptyId / path / command content leaks', () => {+ test('attributes stay bounded — no ptyId / path / command content leaks', () => {recordConcurrentSessions({ count: 2 });const attrs = capturedCalls[0]?.options?.attributes ?? {};- expect(Object.keys(attrs)).toEqual(['ok.desktop.concurrent_sessions']);+ expect(Object.keys(attrs)).toEqual(['ok.desktop.concurrent_sessions', 'ok.platform']);});});@@ -95,10 +104,10 @@ describe('recordTerminalWindowOpened — count-only adoption marker', () => {capturedCalls.length = 0;});- test('emits ok.desktop.terminalWindowOpened with no attributes (the span is the count)', () => {+ test('emits ok.desktop.terminalWindowOpened with only the bounded platform attribute', () => {recordTerminalWindowOpened();expect(capturedCalls).toHaveLength(1);expect(capturedCalls[0]?.name).toBe('ok.desktop.terminalWindowOpened');- expect(capturedCalls[0]?.options?.attributes ?? {}).toEqual({});+ expect(capturedCalls[0]?.options?.attributes).toEqual({ 'ok.platform': process.platform });});});diff --git a/packages/desktop/src/main/terminal-telemetry.ts b/packages/desktop/src/main/terminal-telemetry.tsindex 79d939672..c256735ec 100644--- a/packages/desktop/src/main/terminal-telemetry.ts+++ b/packages/desktop/src/main/terminal-telemetry.ts@@ -17,6 +17,10 @@import { withSpanSync } from '@inkeep/open-knowledge-server';+function platformAttributes(): { 'ok.platform': NodeJS.Platform } {+ return { 'ok.platform': process.platform };+}+/*** Emit one `ok.desktop.shellExit` span. `crashed` distinguishes a PTY/host* crash or spawn failure from a clean shell exit — the reliability signal. No@@ -27,7 +31,12 @@ import { withSpanSync } from '@inkeep/open-knowledge-server';export function recordShellExit(info: { crashed: boolean }): void {withSpanSync('ok.desktop.shellExit',- { attributes: { 'ok.desktop.shell_crashed': info.crashed } },+ {+ attributes: {+ 'ok.desktop.shell_crashed': info.crashed,+ ...platformAttributes(),+ },+ },() => undefined,);}@@ -41,7 +50,7 @@ export function recordShellExit(info: { crashed: boolean }): void {* carried a line terminator). SDK disabled → no-op.*/export function recordTerminalSession(): void {- withSpanSync('ok.desktop.terminalSession', {}, () => undefined);+ withSpanSync('ok.desktop.terminalSession', { attributes: platformAttributes() }, () => undefined);}/**@@ -55,7 +64,12 @@ export function recordTerminalSession(): void {export function recordConcurrentSessions(info: { count: number }): void {withSpanSync('ok.desktop.terminalConcurrentSessions',- { attributes: { 'ok.desktop.concurrent_sessions': info.count } },+ {+ attributes: {+ 'ok.desktop.concurrent_sessions': info.count,+ ...platformAttributes(),+ },+ },() => undefined,);}@@ -67,5 +81,9 @@ export function recordConcurrentSessions(info: { count: number }): void {* `recordTerminalSession`. SDK disabled → no-op.*/export function recordTerminalWindowOpened(): void {- withSpanSync('ok.desktop.terminalWindowOpened', {}, () => undefined);+ withSpanSync(+ 'ok.desktop.terminalWindowOpened',+ { attributes: platformAttributes() },+ () => undefined,+ );}diff --git a/packages/desktop/src/main/terminal-window.test.ts b/packages/desktop/src/main/terminal-window.test.tsindex 68be0eb1d..8d7b2e766 100644--- a/packages/desktop/src/main/terminal-window.test.ts+++ b/packages/desktop/src/main/terminal-window.test.ts@@ -49,7 +49,10 @@ function makeDeps(opts: {const register = vi.fn((_window: unknown, _opts?: { kind?: string }) => disposeShowGate);const showGate = { register, fireThemeApplied: () => {} } as unknown as ShowGateRegistry;const killForWindow = vi.fn((_id: number) => {});- const terminalReaper = { killForWindow, killAll: () => {} } as unknown as TerminalReaper;+ const terminalReaper = {+ killForWindow,+ killAll: () => Promise.resolve(),+ } satisfies TerminalReaper;return {fake,createWindow,diff --git a/packages/desktop/src/main/window-manager.ts b/packages/desktop/src/main/window-manager.tsindex 14b861cc4..af3dc2c9a 100644--- a/packages/desktop/src/main/window-manager.ts+++ b/packages/desktop/src/main/window-manager.ts@@ -3101,11 +3101,9 @@ export class WindowManager {// Drop any stale show-gate state — a window destroyed before either// signal arrives must not hold a slot in the registry's Map.disposeShowGate();- // Guard against detached IPC port — the utility may have already exited- // (e.g. crash, parent-death poll beat us) in which case `postMessage`- // throws ERR_IPC_CHANNEL_CLOSED. The utility's shutdown drain +- // parentLifecycleBound takes care of the forked process regardless;- // windowsByPath.delete fires from the utility's exit event above.+ // A send failure must not keep a closing window alive. The utility's+ // shutdown drain + parentLifecycleBound takes care of the forked+ // process regardless; windowsByPath.delete fires from its exit event.try {utility.postMessage({ type: 'shutdown' });} catch (err) {diff --git a/packages/desktop/src/main/windows-update-survivor-sweep.ts b/packages/desktop/src/main/windows-update-survivor-sweep.tsnew file mode 100644index 000000000..df6c488c1--- /dev/null+++ b/packages/desktop/src/main/windows-update-survivor-sweep.ts@@ -0,0 +1,276 @@+import { execFileSync } from 'node:child_process';+import { win32 } from 'node:path';+import { getWindowsEnvValue } from '../shared/windows-env.ts';++interface WindowsConsoleProcess {+ processId: number;+ name: string;+ executablePath: string | null;+ commandLine: string | null;+ creationDate: string;+}++export interface WindowsUpdateSurvivorSweepResult {+ candidateCount: number;+ terminatedCount: number;+ failedCount: number;+ scanFailed: boolean;+ revalidationFailed: boolean;+}++interface WindowsUpdateSurvivorSweepOptions {+ installTree: string;+ platform?: NodeJS.Platform;+ env?: NodeJS.ProcessEnv;+ listProcesses?: () => readonly WindowsConsoleProcess[];+ revalidateProcesses?: (processIds: readonly number[]) => readonly WindowsConsoleProcess[];+ terminateProcess?: (pid: number) => void;+ logger?: {+ info: (event: Record<string, unknown>) => void;+ warn: (event: Record<string, unknown>) => void;+ };+}++const EMPTY_RESULT: WindowsUpdateSurvivorSweepResult = {+ candidateCount: 0,+ terminatedCount: 0,+ failedCount: 0,+ scanFailed: false,+ revalidationFailed: false,+};++const PROCESS_QUERY_FIELDS =+ "Select-Object @{Name='processId';Expression={[int]$_.ProcessId}}, @{Name='name';Expression={$_.Name}}, @{Name='executablePath';Expression={$_.ExecutablePath}}, @{Name='commandLine';Expression={$_.CommandLine}}, @{Name='creationDate';Expression={if ($null -eq $_.CreationDate) {$null} else {$_.CreationDate.ToUniversalTime().ToString('O')}}}";++const PROCESS_QUERY_TIMEOUT_MS = 5_000;++function processQuery(filter: string): string {+ return [+ "$ErrorActionPreference = 'Stop'",+ '[Console]::OutputEncoding = [System.Text.UTF8Encoding]::new($false)',+ `$items = Get-CimInstance Win32_Process -Filter "${filter}" | ${PROCESS_QUERY_FIELDS}`,+ 'ConvertTo-Json -Compress -InputObject @($items)',+ ].join('; ');+}++function parseProcessList(raw: string): WindowsConsoleProcess[] {+ const trimmed = raw.trim().replace(/^\uFEFF/u, '');+ if (trimmed.length === 0) return [];+ const parsed: unknown = JSON.parse(trimmed);+ if (!Array.isArray(parsed)) throw new Error('process query did not return an array');+ const processes: WindowsConsoleProcess[] = [];+ for (const value of parsed) {+ if (typeof value !== 'object' || value === null) continue;+ const record = value as Record<string, unknown>;+ if (+ !Number.isInteger(record.processId) ||+ (record.processId as number) <= 0 ||+ typeof record.name !== 'string' ||+ typeof record.creationDate !== 'string'+ )+ continue;+ processes.push({+ processId: record.processId as number,+ name: record.name,+ executablePath: typeof record.executablePath === 'string' ? record.executablePath : null,+ commandLine: typeof record.commandLine === 'string' ? record.commandLine : null,+ creationDate: record.creationDate,+ });+ }+ return processes;+}++/**+ * One PowerShell spawn per call. `processIds`, when given, is re-queried as a+ * single `ProcessId = a OR ProcessId = b` filter rather than one query each, so+ * a sweep costs at most two cold PowerShell/WMI starts no matter how many+ * console hosts leaked — this runs on the main process immediately before an+ * update installs. The ids are integers `parseProcessList` already validated,+ * so interpolating them into the filter cannot inject.+ */+function listWindowsConsoleProcesses(+ env: NodeJS.ProcessEnv,+ processIds?: readonly number[],+): WindowsConsoleProcess[] {+ const systemRoot = getWindowsEnvValue(env, 'SystemRoot') ?? 'C:\\Windows';+ const powershell = win32.join(+ systemRoot,+ 'System32',+ 'WindowsPowerShell',+ 'v1.0',+ 'powershell.exe',+ );+ const output = execFileSync(+ powershell,+ [+ '-NoLogo',+ '-NoProfile',+ '-NonInteractive',+ '-Command',+ processQuery(+ processIds === undefined+ ? "Name = 'OpenConsole.exe' OR Name = 'conhost.exe'"+ : processIds.map((processId) => `ProcessId = ${processId}`).join(' OR '),+ ),+ ],+ {+ encoding: 'utf8',+ windowsHide: true,+ stdio: ['ignore', 'pipe', 'pipe'],+ maxBuffer: 1024 * 1024,+ timeout: PROCESS_QUERY_TIMEOUT_MS,+ },+ );+ return parseProcessList(output);+}++function normalizeWindowsPath(path: string): string {+ return win32.resolve(path).replaceAll('/', '\\').toLowerCase();+}++function commandExecutablePath(commandLine: string): string | null {+ const trimmed = commandLine.trimStart();+ if (trimmed.length === 0) return null;+ if (trimmed.startsWith('"')) {+ const end = trimmed.indexOf('"', 1);+ return end > 1 ? trimmed.slice(1, end) : null;+ }+ return trimmed.match(/^\S+/u)?.[0] ?? null;+}++function belongsToInstallTree(process: WindowsConsoleProcess, installTree: string): boolean {+ const root = normalizeWindowsPath(installTree);+ const rootPrefix = root.endsWith('\\') ? root : `${root}\\`;+ if (process.executablePath && win32.isAbsolute(process.executablePath)) {+ const executable = normalizeWindowsPath(process.executablePath);+ if (executable === root || executable.startsWith(rootPrefix)) return true;+ }+ const commandExecutable = process.commandLine ? commandExecutablePath(process.commandLine) : null;+ if (commandExecutable && win32.isAbsolute(commandExecutable)) {+ const executable = normalizeWindowsPath(commandExecutable);+ return executable === root || executable.startsWith(rootPrefix);+ }+ return false;+}++function errorCode(error: unknown): string {+ const code = (error as { code?: unknown } | null)?.code;+ return typeof code === 'string' ? code : 'unknown';+}++/**+ * Remove console hosts that can hold files inside the installed app tree open+ * while an in-place update replaces that tree. Process-name matching alone is+ * insufficient: conhost.exe is shared Windows infrastructure, so ownership is+ * proven by an executable path or command line rooted under this installation.+ */+export function sweepWindowsUpdateSurvivors(+ options: WindowsUpdateSurvivorSweepOptions,+): WindowsUpdateSurvivorSweepResult {+ const platform = options.platform ?? process.platform;+ if (platform !== 'win32') return EMPTY_RESULT;+ if (!win32.isAbsolute(options.installTree)) {+ options.logger?.warn({+ event: 'windows-update-survivor-scan-failed',+ code: 'invalid-install-tree',+ });+ return { ...EMPTY_RESULT, scanFailed: true };+ }++ let listed: readonly WindowsConsoleProcess[];+ try {+ listed = (+ options.listProcesses ?? (() => listWindowsConsoleProcesses(options.env ?? process.env))+ )();+ } catch (error) {+ options.logger?.warn({+ event: 'windows-update-survivor-scan-failed',+ code: errorCode(error),+ });+ return { ...EMPTY_RESULT, scanFailed: true };+ }++ const candidates = new Map<number, WindowsConsoleProcess>();+ for (const candidate of listed) {+ const name = candidate.name.toLowerCase();+ if (name !== 'openconsole.exe' && name !== 'conhost.exe') continue;+ if (belongsToInstallTree(candidate, options.installTree)) {+ candidates.set(candidate.processId, candidate);+ }+ }++ const terminateProcess = options.terminateProcess ?? ((pid: number) => process.kill(pid));+ const revalidateProcesses =+ options.revalidateProcesses ??+ ((processIds: readonly number[]) =>+ options.listProcesses+ ? options.listProcesses().filter((entry) => processIds.includes(entry.processId))+ : listWindowsConsoleProcesses(options.env ?? process.env, processIds));++ // One re-query for the whole candidate set, matched back by PID below: the+ // scan-to-kill window is what makes revalidation necessary, but the re-query+ // is itself an out-of-process call that can fail or time out, and a failure+ // there leaves every identity unproven, so nothing gets terminated.+ const revalidated = new Map<number, WindowsConsoleProcess>();+ let revalidationFailed = false;+ if (candidates.size > 0) {+ try {+ for (const entry of revalidateProcesses([...candidates.keys()])) {+ revalidated.set(entry.processId, entry);+ }+ } catch (error) {+ revalidationFailed = true;+ options.logger?.warn({+ event: 'windows-update-survivor-revalidate-failed',+ code: errorCode(error),+ });+ }+ }++ let terminatedCount = 0;+ let failedCount = 0;+ if (!revalidationFailed) {+ for (const candidate of candidates.values()) {+ const latest = revalidated.get(candidate.processId) ?? null;+ if (+ latest === null ||+ latest.creationDate !== candidate.creationDate ||+ latest.name.toLowerCase() !== candidate.name.toLowerCase() ||+ !belongsToInstallTree(latest, options.installTree)+ ) {+ options.logger?.warn({+ event: 'windows-update-survivor-identity-changed',+ processName: candidate.name.toLowerCase(),+ });+ continue;+ }+ try {+ terminateProcess(candidate.processId);+ terminatedCount += 1;+ } catch (error) {+ const code = errorCode(error);+ if (code === 'ESRCH') continue;+ failedCount += 1;+ options.logger?.warn({+ event: 'windows-update-survivor-terminate-failed',+ processName: candidate.name.toLowerCase(),+ code,+ });+ }+ }+ }++ const result = {+ candidateCount: candidates.size,+ terminatedCount,+ failedCount,+ scanFailed: false,+ revalidationFailed,+ };+ if (failedCount > 0 || revalidationFailed) {+ options.logger?.warn({ event: 'windows-update-survivor-sweep-incomplete', ...result });+ } else {+ options.logger?.info({ event: 'windows-update-survivor-sweep', ...result });+ }+ return result;+}diff --git a/packages/desktop/src/main/worktree-recents.ts b/packages/desktop/src/main/worktree-recents.tsindex 9e60441db..e0f9f0ddc 100644--- a/packages/desktop/src/main/worktree-recents.ts+++ b/packages/desktop/src/main/worktree-recents.ts@@ -60,6 +60,7 @@ export function readWorktreeBranch(projectPath: string): string | null {execFileSync('git', ['symbolic-ref', '--quiet', '--short', 'HEAD'], {cwd: projectPath,env: gitSpawnEnv(),+ windowsHide: true,}),).trim();return out.length > 0 ? out : null;@@ -83,6 +84,7 @@ export async function readWorktreeBranchAsync(projectPath: string): Promise<striconst { stdout } = await execFileAsync('git', ['symbolic-ref', '--quiet', '--short', 'HEAD'], {cwd: projectPath,env: gitSpawnEnv(),+ windowsHide: true,});const out = stdout.trim();return out.length > 0 ? out : null;@@ -143,7 +145,13 @@ const REV_PARSE_ARGS = [function computeRecentGit(realPath: string): RecentGitInfo {let out: string;try {- out = String(execFileSync('git', [...REV_PARSE_ARGS], { cwd: realPath, env: gitSpawnEnv() }));+ out = String(+ execFileSync('git', [...REV_PARSE_ARGS], {+ cwd: realPath,+ env: gitSpawnEnv(),+ windowsHide: true,+ }),+ );} catch {return EMPTY;}@@ -156,6 +164,7 @@ async function computeRecentGitAsync(realPath: string): Promise<RecentGitInfo> {const { stdout } = await execFileAsync('git', [...REV_PARSE_ARGS], {cwd: realPath,env: gitSpawnEnv(),+ windowsHide: true,});out = stdout;} catch {diff --git a/packages/desktop/src/main/worktree-service.ts b/packages/desktop/src/main/worktree-service.tsindex 4d4ba9162..5c3779997 100644--- a/packages/desktop/src/main/worktree-service.ts+++ b/packages/desktop/src/main/worktree-service.ts@@ -200,7 +200,11 @@ export async function createWorktree(args: CreateWorktreeArgs): Promise<Worktreeconst addArgs = buildAddArgs(args, worktreePath);try {- await execFileAsync('git', addArgs, { cwd: args.anchorPath, env: gitSpawnEnv() });+ await execFileAsync('git', addArgs, {+ cwd: args.anchorPath,+ env: gitSpawnEnv(),+ windowsHide: true,+ });} catch (err) {const classified = classifyAddError(err);// A repo with no commits has no resolvable base ref, so git rejects the add@@ -331,6 +335,7 @@ async function refExists(anchorPath: string, ref: string): Promise<boolean> {cwd: anchorPath,env: gitSpawnEnv(),timeout: 5_000,+ windowsHide: true,});return true;} catch (err) {@@ -360,6 +365,7 @@ async function fetchShareBranch(cwd: anchorPath,env: fetchGitEnv(),timeout: timeoutMs,+ windowsHide: true,});return null;} catch (err) {@@ -449,7 +455,7 @@ async function listLocalBranches(anchorPath: string): Promise<string[]> {const { stdout } = await execFileAsync('git',['for-each-ref', '--format=%(refname:short)', 'refs/heads/'],- { cwd: anchorPath, env: gitSpawnEnv() },+ { cwd: anchorPath, env: gitSpawnEnv(), windowsHide: true },);return parseBranchList(String(stdout));} catch {@@ -472,7 +478,7 @@ async function listRemoteBranches(anchorPath: string): Promise<string[]> {const { stdout } = await execFileAsync('git',['for-each-ref', '--format=%(refname:short)', 'refs/remotes/'],- { cwd: anchorPath, env: gitSpawnEnv() },+ { cwd: anchorPath, env: gitSpawnEnv(), windowsHide: true },);// `refname:short` renders a `<remote>/HEAD` pointer as `<remote>` (no// trailing `/HEAD`) — drop any ref with no slash (a bare remote name), plus@@ -512,7 +518,7 @@ async function computeBehindCounts(const { stdout } = await execFileAsync('git',['rev-list', '--count', `${branch}..${upstream}`],- { cwd: anchorPath, env: gitSpawnEnv() },+ { cwd: anchorPath, env: gitSpawnEnv(), windowsHide: true },);const n = Number.parseInt(String(stdout).trim(), 10);if (Number.isFinite(n) && n >= 0) out[branch] = n;@@ -576,6 +582,7 @@ async function repoHasAnyRef(cwd: string): Promise<boolean> {const { stdout } = await execFileAsync('git', ['for-each-ref', '--count=1', 'refs/'], {cwd,env: gitSpawnEnv(),+ windowsHide: true,});return stdout.trim().length > 0;} catch {@@ -588,7 +595,9 @@ async function repoHasAnyRef(cwd: string): Promise<boolean> {/** Synchronous git read that returns the trimmed stdout, or null on failure. */function execFileSyncTrim(cmd: string, cmdArgs: string[], cwd: string): string | null {try {- return String(execFileSync(cmd, cmdArgs, { cwd, env: gitSpawnEnv() })).trim();+ return String(+ execFileSync(cmd, cmdArgs, { cwd, env: gitSpawnEnv(), windowsHide: true }),+ ).trim();} catch {return null;}diff --git a/packages/desktop/src/preload/index.ts b/packages/desktop/src/preload/index.tsindex 63915826f..8208825c9 100644--- a/packages/desktop/src/preload/index.ts+++ b/packages/desktop/src/preload/index.ts@@ -60,6 +60,7 @@ import type {OkOnboardingShowPayload,OkPtyData,OkPtyExit,+ OkPtyNotice,OkRecentRemovedMissingInfo,OkServerRestartedInfo,OkServerVersionDriftInfo,@@ -84,7 +85,6 @@ import type {} from '../shared/ipc-channels.ts';import { createInvoker } from '../shared/ipc-invoke.ts';import { resolveOkDesktopMode } from '../shared/ok-desktop-mode.ts';-import { isTerminalPlatform } from '../shared/terminal-platform.ts';import { isUninstallPreload } from '../shared/uninstall-preload-arg.ts';import { createSlidesBridge } from './slides-bridge.ts';import { createUninstallBridge } from './uninstall.ts';@@ -279,10 +279,10 @@ function readConfigFromArgv(): OkDesktopConfig {// when OTel is enabled in main; the renderer extracts it to parent its startup// span into the launch trace. Absent → renderer skips the startup span.const startupTraceparent = parseArg('startup-traceparent');- // Terminal-dock PTY capability. Platform is the whole signal: a supported- // install with a broken node-pty still surfaces the existing- // spawn-error UX, which is the correct diagnostic there.- const ptyAvailable = isTerminalPlatform(process.platform);+ // Main owns the host capability decision and injects it per window. Keeping+ // the Windows build-floor check out of this sandboxed preload also prevents+ // an unavailable node:os import from taking down the entire bridge.+ const ptyAvailable = parseArg('pty-available') === '1';return Object.freeze({collabUrl,apiOrigin,@@ -1089,6 +1089,12 @@ const bridge: OkDesktopBridge = {ipcRenderer.on('ok:pty:exit', listener);return () => ipcRenderer.removeListener('ok:pty:exit', listener);},+ onNotice(cb) {+ const listener = (_event: IpcRendererEvent, msg: OkPtyNotice) => cb(msg);+ // biome-ignore lint/plugin/no-loosely-typed-webcontents-ipc: preload-side subscription wrapper (precedent #14)+ ipcRenderer.on('ok:pty:notice', listener);+ return () => ipcRenderer.removeListener('ok:pty:notice', listener);+ },claudePreflight: () => invoke('ok:terminal:claude-assist', { action: 'preflight' }),cliPreflight: (cli) => invoke('ok:terminal:cli-preflight', { cli }),cliInstalledMap: () => invoke('ok:terminal:cli-installed-map'),diff --git a/packages/desktop/src/shared/ipc-channels.ts b/packages/desktop/src/shared/ipc-channels.tsindex 223d65cab..02646e0de 100644--- a/packages/desktop/src/shared/ipc-channels.ts+++ b/packages/desktop/src/shared/ipc-channels.ts@@ -19,7 +19,8 @@* `input`/`resize`/`kill`/`drain`, plus the reload-survival `list`/`adopt`)* could not be folded: the STOP rule forbids any arbitrary-exec IPC outside the* `ok:pty:*` framing, and they are the smallest faithful PTY protocol. Streaming- * output + exit ride `EventChannels` (`ok:pty:data` / `ok:pty:exit`). The+ * output, exit, and notices ride `EventChannels` (`ok:pty:data` / `ok:pty:exit` /+ * `ok:pty:notice`). The* `ok:terminal:*` reads — `claude-assist` (Claude readiness preflight + MCP* re-arm) and `dock-state` (per-window dock visibility, read on reload) — are* NOT exec channels. The full could-not-fold rationale lives in the ratchet test.@@ -117,6 +118,7 @@ import type {ShareTargetStatusResponse,SkillCostTiers,TerminalCli,+ TerminalLaunchCommand,UninstallDispatchRequest,UninstallDispatchResult,WorktreeCreateRequest,@@ -1716,11 +1718,17 @@ export interface RequestChannels {* fire-and-forget invokes keyed by ptyId; main drops a mismatched ptyId so* a stale renderer can't drive a successor PTY. `drain` is the renderer's* backpressure ack (consumed byte count) so main can resume a paused PTY.- * Streaming output + exit are `EventChannels` pushes (`ok:pty:data` /- * `ok:pty:exit`).+ * Streaming output, exit, and shell-resolution notices are `EventChannels`+ * pushes (`ok:pty:data` / `ok:pty:exit` / `ok:pty:notice`).*/'ok:pty:create': {- args: [opts: { cols: number; rows: number; launchCommand?: string }];+ args: [+ opts: {+ cols: number;+ rows: number;+ launchCommand?: string | TerminalLaunchCommand;+ },+ ];result: OkPtyCreateResult;};'ok:pty:input': {diff --git a/packages/desktop/src/shared/ipc-events.ts b/packages/desktop/src/shared/ipc-events.tsindex 9497e598d..70c1146a8 100644--- a/packages/desktop/src/shared/ipc-events.ts+++ b/packages/desktop/src/shared/ipc-events.ts@@ -23,6 +23,7 @@ import type {OkMenuActionDispatch,OkPtyData,OkPtyExit,+ OkPtyNotice,OkRecentRemovedMissingInfo,OkServerRestartedInfo,OkServerVersionDriftInfo,@@ -328,6 +329,8 @@ export interface EventChannels {* normal exit carries `exitCode`/`signal`.*/'ok:pty:exit': { payload: OkPtyExit };+ /** Main → renderer when shell discovery skips an invalid configured override. */+ 'ok:pty:notice': { payload: OkPtyNotice };/*** Main → every window when Electron's assistive-tech signal flips* (`app.on('accessibility-support-changed')` — a screen reader such asdiff --git a/packages/desktop/src/shared/path-containment.ts b/packages/desktop/src/shared/path-containment.tsnew file mode 100644index 000000000..adbacf742--- /dev/null+++ b/packages/desktop/src/shared/path-containment.ts@@ -0,0 +1,55 @@+import { posix as pathPosix, win32 as pathWin32 } from 'node:path';++// The server keeps an independent sibling at its package boundary; the desktop+// parity matrix pins both implementations to the same lexical verdicts.++function isContainablePath(path: string, platform: NodeJS.Platform): boolean {+ if (!path || typeof path !== 'string' || path.includes('\0')) return false;+ if (platform === 'win32') return /^([a-zA-Z]:[\\/]|\\\\)/.test(path);+ return path.startsWith('/');+}++/** Reject path forms that cannot safely pass through the Windows spawn shell. */+export function validateSpawnPath(path: string, platform: NodeJS.Platform): boolean {+ if (!isContainablePath(path, platform)) return false;+ // `%` expands inside cmd.exe double quotes, while `"` cannot be quoted.+ return platform !== 'win32' || !/["%]/.test(path);+}++/**+ * Lexically verify that `userPath` lies at or below `projectPath`. Callers at a+ * filesystem trust boundary must realpath first so an admitted symlink cannot+ * escape after this check.+ */+export function isPathWithinProject(+ userPath: string,+ projectPath: string,+ platform: NodeJS.Platform,+): boolean {+ if (!isContainablePath(userPath, platform)) return false;+ if (!isContainablePath(projectPath, platform)) return false;+ const p = platform === 'win32' ? pathWin32 : pathPosix;+ try {+ const canonicalUser = p.resolve(userPath);+ const canonicalProject = p.resolve(projectPath);+ if (platform === 'win32') {+ const userRoot = p.parse(canonicalUser).root.toLowerCase();+ const projectRoot = p.parse(canonicalProject).root.toLowerCase();+ if (!userRoot || !projectRoot || userRoot !== projectRoot) return false;+ }+ if (canonicalUser === canonicalProject) return true;+ const rel = p.relative(canonicalProject, canonicalUser);+ if (rel === '' || rel === '.') return true;+ if (rel === '..' || rel.startsWith(`..${p.sep}`)) return false;+ if (platform === 'win32' && (/^[a-zA-Z]:[\\/]/.test(rel) || rel.startsWith('\\\\'))) {+ return false;+ }+ if (platform !== 'win32' && rel.startsWith('/')) return false;+ return true;+ } catch (err) {+ // This shared module stays dependency-free so main and utility processes+ // can use identical containment semantics without pulling in pino.+ console.warn('[path-containment] unexpected path-resolution error:', err);+ return false;+ }+}diff --git a/packages/desktop/src/shared/terminal-platform.test.ts b/packages/desktop/src/shared/terminal-platform.test.tsindex 15d16c4be..1fa5642cb 100644--- a/packages/desktop/src/shared/terminal-platform.test.ts+++ b/packages/desktop/src/shared/terminal-platform.test.ts@@ -2,9 +2,9 @@ import { describe, expect, test } from 'vitest';import { isTerminalPlatform } from './terminal-platform.ts';describe('isTerminalPlatform', () => {- test('enables PTY-backed terminal surfaces on macOS and Linux only', () => {+ test('enables PTY-backed terminal surfaces on every desktop platform', () => {expect(isTerminalPlatform('darwin')).toBe(true);expect(isTerminalPlatform('linux')).toBe(true);- expect(isTerminalPlatform('win32')).toBe(false);+ expect(isTerminalPlatform('win32')).toBe(true);});});diff --git a/packages/desktop/src/shared/terminal-platform.ts b/packages/desktop/src/shared/terminal-platform.tsindex 5c73812f6..443551d8d 100644--- a/packages/desktop/src/shared/terminal-platform.ts+++ b/packages/desktop/src/shared/terminal-platform.ts@@ -1,3 +1,3 @@export function isTerminalPlatform(platform: NodeJS.Platform): boolean {- return platform === 'darwin' || platform === 'linux';+ return platform === 'darwin' || platform === 'linux' || platform === 'win32';}diff --git a/packages/desktop/src/shared/windows-env.test.ts b/packages/desktop/src/shared/windows-env.test.tsnew file mode 100644index 000000000..5c551808d--- /dev/null+++ b/packages/desktop/src/shared/windows-env.test.ts@@ -0,0 +1,13 @@+import { describe, expect, test } from 'vitest';+import { getWindowsEnvValue, windowsPathKey } from './windows-env.ts';++describe('Windows environment helpers', () => {+ test('looks up names case-insensitively without returning undefined shadows', () => {+ expect(getWindowsEnvValue({ PATH: undefined, Path: 'C:\\Tools' }, 'path')).toBe('C:\\Tools');+ });++ test('preserves inherited PATH casing and falls back to PATH', () => {+ expect(windowsPathKey({ Path: 'C:\\Tools' })).toBe('Path');+ expect(windowsPathKey({})).toBe('PATH');+ });+});diff --git a/packages/desktop/src/shared/windows-env.ts b/packages/desktop/src/shared/windows-env.tsnew file mode 100644index 000000000..504bd359a--- /dev/null+++ b/packages/desktop/src/shared/windows-env.ts@@ -0,0 +1,19 @@+/** Case-insensitive Windows environment lookup that preserves the original value. */+export function getWindowsEnvValue(+ env: Record<string, string | undefined>,+ wantedKey: string,+): string | undefined {+ return Object.entries(env).find(+ ([key, value]) => key.toLowerCase() === wantedKey.toLowerCase() && value !== undefined,+ )?.[1];+}++/** Preserve inherited PATH key casing when constructing a child environment. */+export function windowsPathKey(env: Record<string, string | undefined>): string {+ return Object.keys(env).find((key) => key.toLowerCase() === 'path') ?? 'PATH';+}++/** PATH-only, PATHEXT-aware `where.exe` query for a registry-authored binary name. */+export function windowsWherePathArgs(bin: string): readonly string[] {+ return [`$PATH:${bin}`];+}diff --git a/packages/desktop/src/utility/pty-host.ts b/packages/desktop/src/utility/pty-host.tsindex 8dff40a19..a15f6f95c 100644--- a/packages/desktop/src/utility/pty-host.ts+++ b/packages/desktop/src/utility/pty-host.ts@@ -10,11 +10,29 @@* (see `tests/utility/pty-host.real-io-harness.ts`).*/-import { existsSync } from 'node:fs';+import { execFileSync } from 'node:child_process';+import { existsSync, readdirSync } from 'node:fs';import { userInfo } from 'node:os';-import { basename, delimiter, join } from 'node:path';-import { OK_DESKTOP_TERMINAL_ENV } from '@inkeep/open-knowledge-core';+import { basename, delimiter, join, win32 } from 'node:path';+import {+ composeWindowsShellLaunchArgs,+ launchWithoutSupportFile,+ OK_DESKTOP_TERMINAL_ENV,+ resolveWindowsShellFamily,+ type TerminalLaunchCommand,+ type WindowsShellFamily,+} from '@inkeep/open-knowledge-core';+import { isTerminalShellNoticeReason } from '@inkeep/open-knowledge-core/desktop-bridge';+import type {+ TerminalShellNoticeReason,+ TerminalSupportFileNoticeReason,+} from '../shared/bridge-contract.ts';import { interactiveShellArgs } from '../shared/terminal-shell.ts';+import { getWindowsEnvValue, windowsPathKey, windowsWherePathArgs } from '../shared/windows-env.ts';+import {+ materializeSupportFileSync,+ TERMINAL_SUPPORT_FILE_ESCAPE_CODE,+} from './support-file-write.ts';const DARWIN_FALLBACK_SHELL = '/bin/zsh';@@ -30,18 +48,17 @@ export interface PtyCreateMessage {cwd: string;cols: number;rows: number;- /** Test-only shell override. Production uses the platform shell resolver. */+ /** Per-machine shell override read from project-local config. */shell?: string;+ /** The configured override could not be read or was not a string. */+ shellInvalidReason?: TerminalShellNoticeReason;/**- * "Open in <Agent>" launch: the fixed `<bin> [pre-approve] '<prompt>'` shape- * (built by core's `buildCliLaunchArgString`, no trailing `\r`). When present,- * the shell is spawned with the platform's interactive argv plus `-c`- * so the agent runs WITHOUT the command being typed through the line editor —- * i.e. it never lands in the user's shell history. The- * `exec` tail hands the tab back to a fresh interactive shell after the agent- * exits. Omitted for a plain terminal tab.+ * OpenKnowledge-composed launch. POSIX carries core's command string;+ * Windows carries structured executable + argv data so this host can choose+ * EncodedCommand or cmd string mode after resolving the shell. Omitted for a+ * plain terminal tab.*/- launchCommand?: string;+ launchCommand?: string | TerminalLaunchCommand;}interface PtyInputMessage {type: 'input';@@ -66,13 +83,17 @@ interface PtyResumeMessage {type: 'resume';ptyId: string;}+interface PtyShutdownMessage {+ type: 'shutdown';+}export type PtyHostIncomingMessage =| PtyCreateMessage| PtyInputMessage| PtyResizeMessage| PtyKillMessage| PtyPauseMessage- | PtyResumeMessage;+ | PtyResumeMessage+ | PtyShutdownMessage;interface PtyDataMessage {type: 'data';@@ -82,7 +103,7 @@ interface PtyDataMessage {interface PtyExitMessage {type: 'exit';ptyId: string;- exitCode: number;+ exitCode: number | undefined;signal: number | null;}interface PtySpawnErrorMessage {@@ -90,13 +111,36 @@ interface PtySpawnErrorMessage {ptyId: string;message: string;}-export type PtyHostOutgoingMessage = PtyDataMessage | PtyExitMessage | PtySpawnErrorMessage;+type PtyShellNoticeMessage =+ | {+ type: 'shell-notice';+ ptyId: string;+ notice: 'invalid-shell-override';+ reason: TerminalShellNoticeReason;+ }+ | {+ type: 'shell-notice';+ ptyId: string;+ notice: 'shell-resolved';+ shellFamily: WindowsShellFamily;+ }+ | {+ type: 'shell-notice';+ ptyId: string;+ notice: 'support-file-degraded';+ reason: TerminalSupportFileNoticeReason;+ };+export type PtyHostOutgoingMessage =+ | PtyDataMessage+ | PtyExitMessage+ | PtySpawnErrorMessage+ | PtyShellNoticeMessage;/** Minimal subset of node-pty's `IPty` the host depends on. */export interface PtyProcessLike {readonly pid: number;onData(listener: (data: string) => void): void;- onExit(listener: (event: { exitCode: number; signal?: number }) => void): void;+ onExit(listener: (event: { exitCode: number | undefined; signal?: number }) => void): void;write(data: string): void;resize(cols: number, rows: number): void;kill(signal?: string): void;@@ -116,8 +160,14 @@ export interface PtySpawnOptions {/** Decode the PTY stream as UTF-8 strings; node-pty's StringDecoder keeps* multibyte sequences intact across read boundaries. */encoding: 'utf8';+ /** Windows only: prefer the matched bundled ConPTY dll + OpenConsole pair. */+ useConptyDll?: boolean;}-export type SpawnPty = (file: string, args: string[], options: PtySpawnOptions) => PtyProcessLike;+export type SpawnPty = (+ file: string,+ args: string[] | string,+ options: PtySpawnOptions,+) => PtyProcessLike;interface PtyHostParentPort {on(event: 'message', handler: (event: { data: unknown }) => void): void;@@ -144,6 +194,14 @@ export interface SetupPtyHostDeps {parentPort: PtyHostParentPort | null;/** node-pty's `spawn`, injected so message routing is testable without a real PTY. */spawn: SpawnPty;+ /** Host-exit seam used after a message-driven shutdown; defaults to no-op in tests. */+ exitHost?: (code: number) => void;+ /** Flush the host's async logger destination before process exit. */+ flushLogger?: () => void;+ /** Host-local grace period before exiting despite a deferred PTY kill. */+ shutdownMs?: number;+ setTimer?: (cb: () => void, ms: number) => ReturnType<typeof setTimeout>;+ clearTimer?: (token: ReturnType<typeof setTimeout>) => void;/** Defaults to `process.env`. Injected so env-stripping is unit-testable. */env?: Record<string, string | undefined>;/** Defaults to `process.platform`. */@@ -152,8 +210,22 @@ export interface SetupPtyHostDeps {userInfoShell?: () => string | null;/** Defaults to `existsSync`. */shellExists?: (path: string) => boolean;+ /** PATH-scoped, PATHEXT-aware executable lookup; defaults to `where.exe`. */+ pathProbe?: (command: string, env: Record<string, string | undefined>) => string | null;+ /** Directory seam for Microsoft Store PowerShell aliases. */+ listDirectory?: (path: string) => readonly string[];+ /** Packaged `resources/cli/bin` directory prepended to PATH on Windows. */+ cliBinDir?: string;+ /** Materialize a registry-authored launch support file beneath the PTY cwd. */+ materializeSupportFile?: (+ cwd: string,+ file: NonNullable<TerminalLaunchCommand['supportFile']>,+ ) => void;/** Optional structured warn sink for unrecognized/malformed messages. */- logger?: { warn: (o: Record<string, unknown>) => void };+ logger?: {+ warn: (o: Record<string, unknown>) => void;+ info?: (o: Record<string, unknown>) => void;+ };}/**@@ -167,23 +239,54 @@ function asIncomingMessage(raw: unknown): PtyHostIncomingMessage | null {if (typeof raw !== 'object' || raw === null) return null;const m = raw as Record<string, unknown>;if (typeof m.type !== 'string') return null;+ if (m.type === 'shutdown') return raw as PtyShutdownMessage;if (typeof m.ptyId !== 'string' || m.ptyId.length === 0) return null;// Validate the per-variant payload before the cast: a contract skew that sends// a valid `type`+`ptyId` but omits `data`/`cols`/`rows` would otherwise reach// node-pty's native binding with `undefined` arguments. Mirrors the sibling// `asHostMessage` guard in terminal-manager.ts.switch (m.type) {- case 'create':- // `launchCommand` is optional; when present it must be a string (it ends up- // in the spawn argv). A non-string value from a contract skew causes the- // entire create message to be rejected (asIncomingMessage → null → the- // handler warns and returns) rather than reach node-pty with an undefined arg.+ case 'create': {+ // POSIX carries the existing composed string; Windows carries a structured+ // executable + argv object until this host has resolved the shell family.+ // Reject any other shape before it can reach node-pty.+ const launch = m.launchCommand;+ const supportFile =+ typeof launch === 'object' && launch !== null+ ? (launch as Record<string, unknown>).supportFile+ : undefined;+ const supportFileValid =+ supportFile === undefined ||+ (typeof supportFile === 'object' &&+ supportFile !== null &&+ (supportFile as Record<string, unknown>).kind === 'claude-settings' &&+ typeof (supportFile as Record<string, unknown>).relativePath === 'string' &&+ /^\.ok\/local\/terminal\/claude-settings-(?:mcp|tools|mcp-tools)\.json$/u.test(+ (supportFile as Record<string, unknown>).relativePath as string,+ ) &&+ typeof (supportFile as Record<string, unknown>).contents === 'string' &&+ ((supportFile as Record<string, unknown>).contents as string).length <= 16_384 &&+ (launch as Record<string, unknown>).executable === 'claude');+ const launchValid =+ launch === undefined ||+ typeof launch === 'string' ||+ (typeof launch === 'object' &&+ launch !== null &&+ typeof (launch as Record<string, unknown>).executable === 'string' &&+ Array.isArray((launch as Record<string, unknown>).args) &&+ ((launch as Record<string, unknown>).args as unknown[]).every(+ (arg) => typeof arg === 'string',+ ) &&+ supportFileValid);return typeof m.cwd === 'string' &&typeof m.cols === 'number' &&typeof m.rows === 'number' &&- (m.launchCommand === undefined || typeof m.launchCommand === 'string')+ (m.shell === undefined || typeof m.shell === 'string') &&+ (m.shellInvalidReason === undefined || isTerminalShellNoticeReason(m.shellInvalidReason)) &&+ launchValid? (raw as PtyHostIncomingMessage): null;+ }case 'input':return typeof m.data === 'string' ? (raw as PtyHostIncomingMessage) : null;case 'resize':@@ -207,9 +310,93 @@ export interface PtyHostHandle {export interface ResolveShellOptions {platform: NodeJS.Platform;override?: string;+ overrideInvalidReason?: TerminalShellNoticeReason;userInfoShell?: () => string | null;shellExists?: (path: string) => boolean;- logger?: { warn: (o: Record<string, unknown>) => void };+ pathProbe?: (command: string, env: Record<string, string | undefined>) => string | null;+ listDirectory?: (path: string) => readonly string[];+ logger?: {+ warn: (o: Record<string, unknown>) => void;+ info?: (o: Record<string, unknown>) => void;+ };+}++export type ShellResolutionRung =+ | 'override'+ | 'pwsh-path'+ | 'pwsh-known-install'+ | 'windows-powershell'+ | 'comspec'+ | 'cmd'+ | 'env-shell'+ | 'platform-fallback'+ | 'passwd-shell'+ | 'bash'+ | 'sh';++export interface ShellResolution {+ shell: string;+ rung: ShellResolutionRung;+ invalidOverride: boolean;+ invalidOverrideReason?: TerminalShellNoticeReason;+}++/**+ * Deadline for the `where.exe` probe. The probe runs synchronously inside the+ * host's single `parentPort` message handler, so while it blocks, every OTHER+ * tab in the window is unserved — `input`, `resize`, `kill`, `pause`, `resume`+ * all wait behind it. `where.exe` walks every `PATH` entry, so a `PATH`+ * carrying a dead UNC path or a disconnected mapped drive makes its duration a+ * function of network state, i.e. unbounded without this cap. Matches the+ * interactive-shell probe's bound in `claude-readiness.ts`.+ */+const PATH_PROBE_TIMEOUT_MS = 5000;++function defaultWindowsPathProbe(+ command: string,+ env: Record<string, string | undefined>,+ logger?: ResolveShellOptions['logger'],+): string | null {+ const systemRoot = getWindowsEnvValue(env, 'SystemRoot') ?? 'C:\\Windows';+ const whereExe = win32.join(systemRoot, 'System32', 'where.exe');+ try {+ const output = execFileSync(whereExe, windowsWherePathArgs(command), {+ encoding: 'utf8',+ env: { ...process.env, ...env },+ windowsHide: true,+ stdio: ['ignore', 'pipe', 'ignore'],+ // On expiry `execFileSync` throws ETIMEDOUT, which the catch below already+ // treats as "not found" — the ladder falls through to the next rung, so+ // bounding the call needs no new error path.+ timeout: PATH_PROBE_TIMEOUT_MS,+ });+ return (+ output+ .split(/\r?\n/u)+ .map((line) => line.trim())+ .find((line) => win32.isAbsolute(line) && line.toLowerCase().endsWith('.exe')) ?? null+ );+ } catch (error) {+ const code = (error as { code?: string } | null)?.code ?? 'unknown';+ if (code === 'ETIMEDOUT') {+ logger?.warn({+ event: 'pty-host-shell-path-probe-timed-out',+ command,+ timeoutMs: PATH_PROBE_TIMEOUT_MS,+ });+ } else {+ logger?.warn({ event: 'pty-host-shell-path-probe-failed', command, code });+ }+ return null;+ }+}++function defaultListDirectory(path: string): readonly string[] {+ try {+ return readdirSync(path);+ } catch {+ return [];+ }}function isFalseStyleShell(shell: string): boolean {@@ -226,27 +413,118 @@ function isUsableShell();}-/** Resolve the user's interactive shell with platform-native fallbacks. */-export function resolveShell(+/** Resolve the user's interactive shell and the bounded ladder rung used. */+export function resolveShellWithDetails(env: Record<string, string | undefined>,options: ResolveShellOptions,-): string {- if (options.override && options.override.length > 0) return options.override;+): ShellResolution {+ if (options.platform === 'win32') {+ const shellExists = options.shellExists ?? existsSync;+ const override = options.override?.trim();+ let invalidOverride = options.overrideInvalidReason !== undefined;+ let invalidOverrideReason = options.overrideInvalidReason;+ if (override) {+ if (win32.isAbsolute(override) && shellExists(override)) {+ const unsupportedFamily = resolveWindowsShellFamily(override) === null;+ return {+ shell: override,+ rung: 'override',+ invalidOverride: unsupportedFamily,+ invalidOverrideReason: unsupportedFamily ? 'unsupported-family' : undefined,+ };+ }+ invalidOverride = true;+ invalidOverrideReason = win32.isAbsolute(override) ? 'not-found' : 'not-absolute';+ }++ const pathShell = options.pathProbe+ ? options.pathProbe('pwsh', env)+ : defaultWindowsPathProbe('pwsh', env, options.logger);+ if (pathShell && win32.isAbsolute(pathShell) && shellExists(pathShell)) {+ return { shell: pathShell, rung: 'pwsh-path', invalidOverride, invalidOverrideReason };+ }++ const programFiles = getWindowsEnvValue(env, 'ProgramFiles');+ if (programFiles) {+ const knownPwsh = win32.join(programFiles, 'PowerShell', '7', 'pwsh.exe');+ if (shellExists(knownPwsh)) {+ return {+ shell: knownPwsh,+ rung: 'pwsh-known-install',+ invalidOverride,+ invalidOverrideReason,+ };+ }+ }++ const localAppData = getWindowsEnvValue(env, 'LOCALAPPDATA');+ if (localAppData) {+ const windowsApps = win32.join(localAppData, 'Microsoft', 'WindowsApps');+ const entries = (options.listDirectory ?? defaultListDirectory)(windowsApps);+ for (const entry of entries) {+ if (!entry.toLowerCase().startsWith('microsoft.powershell_')) continue;+ const alias = win32.join(windowsApps, entry, 'pwsh.exe');+ if (shellExists(alias)) {+ return {+ shell: alias,+ rung: 'pwsh-known-install',+ invalidOverride,+ invalidOverrideReason,+ };+ }+ }+ }++ const systemRoot = getWindowsEnvValue(env, 'SystemRoot') ?? 'C:\\Windows';+ const windowsPowerShell = win32.join(+ systemRoot,+ 'System32',+ 'WindowsPowerShell',+ 'v1.0',+ 'powershell.exe',+ );+ if (shellExists(windowsPowerShell)) {+ return {+ shell: windowsPowerShell,+ rung: 'windows-powershell',+ invalidOverride,+ invalidOverrideReason,+ };+ }++ const comspec = getWindowsEnvValue(env, 'ComSpec');+ if (comspec && win32.isAbsolute(comspec) && shellExists(comspec)) {+ return { shell: comspec, rung: 'comspec', invalidOverride, invalidOverrideReason };+ }++ return {+ shell: win32.join(systemRoot, 'System32', 'cmd.exe'),+ rung: 'cmd',+ invalidOverride,+ invalidOverrideReason,+ };+ }++ if (options.override && options.override.length > 0) {+ return { shell: options.override, rung: 'override', invalidOverride: false };+ }const configuredShell = env.SHELL;if (options.platform === 'darwin') {return typeof configuredShell === 'string' && configuredShell.length > 0- ? configuredShell- : DARWIN_FALLBACK_SHELL;+ ? { shell: configuredShell, rung: 'env-shell', invalidOverride: false }+ : { shell: DARWIN_FALLBACK_SHELL, rung: 'platform-fallback', invalidOverride: false };}if (options.platform !== 'linux') {return typeof configuredShell === 'string' && configuredShell.length > 0- ? configuredShell- : '/bin/sh';+ ? { shell: configuredShell, rung: 'env-shell', invalidOverride: false }+ : { shell: '/bin/sh', rung: 'platform-fallback', invalidOverride: false };}const shellExists = options.shellExists ?? existsSync;- if (isUsableShell(configuredShell, shellExists)) return configuredShell;+ if (isUsableShell(configuredShell, shellExists)) {+ return { shell: configuredShell, rung: 'env-shell', invalidOverride: false };+ }let passwdShell: string | null = null;try {@@ -259,13 +537,31 @@ export function resolveShell(});passwdShell = null;}- if (isUsableShell(passwdShell, shellExists)) return passwdShell;- return shellExists('/bin/bash') ? '/bin/bash' : '/bin/sh';+ if (isUsableShell(passwdShell, shellExists)) {+ return { shell: passwdShell, rung: 'passwd-shell', invalidOverride: false };+ }+ return shellExists('/bin/bash')+ ? { shell: '/bin/bash', rung: 'bash', invalidOverride: false }+ : { shell: '/bin/sh', rung: 'sh', invalidOverride: false };+}++/** Resolve only the executable path for callers that do not need diagnostics. */+export function resolveShell(+ env: Record<string, string | undefined>,+ options: ResolveShellOptions,+): string {+ return resolveShellWithDetails(env, options).shell;}/*** Compute the shell argv for a PTY.*+ * Windows keeps a structured executable/argv launch until the resolved shell+ * family is known. PowerShell receives an EncodedCommand, cmd receives its+ * owned `/K` command string, and Git Bash receives base64-transported argv+ * behind a fixed decoder script; the renderer delivers user prompt text later by+ * readiness-gated bracketed paste. Plain Windows tabs use empty argv.+ ** macOS uses a login interactive shell; Linux uses an interactive non-login* shell, matching each platform's terminal convention. "Open in <Agent>"* keeps the same flags in its exec tail, but the agent command rides on `-c`.@@ -284,10 +580,15 @@ export function resolveShell(export function buildShellArgs(platform: NodeJS.Platform,shell: string,- launchCommand?: string,-): string[] {+ launchCommand?: string | TerminalLaunchCommand,+): string[] | string {+ if (platform === 'win32') {+ return typeof launchCommand === 'object'+ ? composeWindowsShellLaunchArgs(shell, launchCommand)+ : [];+ }const interactiveArgs = [...interactiveShellArgs(platform)];- if (launchCommand === undefined || launchCommand.length === 0) return interactiveArgs;+ if (typeof launchCommand !== 'string' || launchCommand.length === 0) return interactiveArgs;// Single-quote the shell path in the `exec` tail (POSIX close-escape-reopen),// so a shell path containing a space or quote can't break the launcher line.const quotedShell = `'${shell.replace(/'/g, "'\\''")}'`;@@ -306,6 +607,7 @@ export function buildShellArgs(*/export function buildShellEnv(parentEnv: Record<string, string | undefined>,+ options: { platform?: NodeJS.Platform; cliBinDir?: string } = {},): Record<string, string> {const stripped = new Set<string>(STRIPPED_ENV_MARKERS);const out: Record<string, string> = {};@@ -319,12 +621,20 @@ export function buildShellEnv(// here touches no file OK doesn't own. The env shim the rc block sources// dedups by substring match, so a consenting user's login shell won't// re-prepend it. A missing HOME just skips the injection.+ const platform = options.platform ?? process.platform;+ const pathKey = windowsPathKey(out);+ if (platform === 'win32' && options.cliBinDir) {+ const entries = (out[pathKey] ?? '').split(';').filter(Boolean);+ if (!entries.some((entry) => entry.toLowerCase() === options.cliBinDir?.toLowerCase())) {+ out[pathKey] = [options.cliBinDir, ...entries].join(';');+ }+ }const home = out.HOME;- if (home) {+ if (platform !== 'win32' && home) {const okBin = join(home, '.ok', 'bin');- const entries = (out.PATH ?? '').split(delimiter).filter(Boolean);+ const entries = (out[pathKey] ?? '').split(delimiter).filter(Boolean);if (!entries.includes(okBin)) {- out.PATH = [okBin, ...entries].join(delimiter);+ out[pathKey] = [okBin, ...entries].join(delimiter);}}// Positive identity for an agent running in this shell: it's the OK Desktop@@ -336,12 +646,49 @@ export function buildShellEnv(return out;}+const CONPTY_DLL_LOAD_ERROR_PREFIXES = {+ 'Cannot find conpty.dll': 'not-found',+ 'Failed to get conpty.node module handle': 'module-handle',+ 'Failed to get conpty.node module file name': 'module-file-name',+ 'Failed to load conpty.dll': 'load-failed',+} as const;++function conptyDllLoadFailureReason(+ error: unknown,+): (typeof CONPTY_DLL_LOAD_ERROR_PREFIXES)[keyof typeof CONPTY_DLL_LOAD_ERROR_PREFIXES] | null {+ const message = error instanceof Error ? error.message : String(error);+ const prefix = Object.keys(CONPTY_DLL_LOAD_ERROR_PREFIXES).find((candidate) =>+ message.startsWith(candidate),+ ) as keyof typeof CONPTY_DLL_LOAD_ERROR_PREFIXES | undefined;+ return prefix === undefined ? null : CONPTY_DLL_LOAD_ERROR_PREFIXES[prefix];+}+export function setupPtyHost(deps: SetupPtyHostDeps): PtyHostHandle {const env = deps.env ?? (process.env as Record<string, string | undefined>);const platform = deps.platform ?? process.platform;// One host per window multiplexes every terminal tab's shell, keyed by the// renderer-minted ptyId. Each create adds an entry; tabs are independent.const sessions = new Map<string, PtyProcessLike>();+ const shutdownMs = deps.shutdownMs ?? 1_500;+ const setHostTimer = deps.setTimer ?? setTimeout;+ const clearHostTimer = deps.clearTimer ?? clearTimeout;+ const materializeSupportFile = deps.materializeSupportFile ?? materializeSupportFileSync;+ const cachedWindowsPaths = new Map<string, string>();++ function probeWindowsShellPath(+ command: string,+ probeEnv: Record<string, string | undefined>,+ ): string | null {+ const cached = cachedWindowsPaths.get(command);+ if (cached !== undefined) return cached;+ const resolved = deps.pathProbe+ ? deps.pathProbe(command, probeEnv)+ : defaultWindowsPathProbe(command, probeEnv, deps.logger);+ // A miss or failure is retried by the next create so a transient problem+ // cannot pin every later terminal in this utility host to a fallback shell.+ if (resolved !== null) cachedWindowsPaths.set(command, resolved);+ return resolved;+ }function post(message: PtyHostOutgoingMessage): void {deps.parentPort?.postMessage(message);@@ -374,35 +721,148 @@ export function setupPtyHost(deps: SetupPtyHostDeps): PtyHostHandle {safeKill(stale);sessions.delete(ptyId);}- const shell = resolveShell(env, {+ const resolution = resolveShellWithDetails(env, {platform,override: message.shell,+ overrideInvalidReason: message.shellInvalidReason,userInfoShell: deps.userInfoShell,shellExists: deps.shellExists,+ pathProbe: platform === 'win32' ? probeWindowsShellPath : deps.pathProbe,+ listDirectory: deps.listDirectory,logger: deps.logger,});- const shellEnv = buildShellEnv(env);+ if (resolution.invalidOverride) {+ const reason = resolution.invalidOverrideReason ?? 'invalid-value';+ deps.logger?.warn({+ event:+ reason === 'unsupported-family'+ ? 'pty-host-shell-override-capability-limited'+ : 'pty-host-shell-override-invalid',+ platform,+ reason,+ });+ post({+ type: 'shell-notice',+ ptyId,+ notice: 'invalid-shell-override',+ reason,+ });+ }+ deps.logger?.info?.({+ event: 'pty-host-shell-resolved',+ platform,+ rung: resolution.rung,+ });+ const shell = resolution.shell;+ if (platform === 'win32') {+ const shellFamily = resolveWindowsShellFamily(shell);+ if (shellFamily !== null) {+ post({ type: 'shell-notice', ptyId, notice: 'shell-resolved', shellFamily });+ }+ }+ const shellEnv = buildShellEnv(env, { platform, cliBinDir: deps.cliBinDir });+ let launchCommand = message.launchCommand;+ if (+ platform === 'win32' &&+ typeof launchCommand === 'object' &&+ resolution.invalidOverrideReason === 'unsupported-family'+ ) {+ // Structured launches need a known shell parser; an unknown family can+ // safely host an interactive tab but cannot receive composed argv.+ deps.logger?.warn({+ event: 'pty-host-launch-degraded-unsupported-shell',+ platform,+ rung: resolution.rung,+ });+ launchCommand = undefined;+ }+ if (+ platform === 'win32' &&+ typeof launchCommand === 'object' &&+ launchCommand.supportFile !== undefined+ ) {+ // The settings file is optional pre-approval. If the project or writer+ // refuses it, degrade to the producer's coupled bare launch so Claude can+ // show its own trust prompt without leaving argv pointed at a missing file.+ try {+ materializeSupportFile(message.cwd, launchCommand.supportFile);+ } catch (error) {+ // Distinct from `pty-host-launch-compose-failed` so a degraded launch is+ // never read as an aborted one.+ deps.logger?.warn({+ event: 'pty-host-support-file-materialize-failed',+ kind: launchCommand.supportFile.kind,+ code: (error as { code?: string } | null)?.code ?? 'unknown',+ });+ post({+ type: 'shell-notice',+ ptyId,+ notice: 'support-file-degraded',+ reason:+ (error as { code?: string } | null)?.code === TERMINAL_SUPPORT_FILE_ESCAPE_CODE+ ? 'containment-refused'+ : 'write-failed',+ });+ launchCommand = launchWithoutSupportFile(launchCommand);+ }+ }+ let shellArgs: string[] | string;+ try {+ shellArgs = buildShellArgs(platform, shell, launchCommand);+ } catch (error) {+ deps.logger?.warn({+ event: 'pty-host-launch-compose-failed',+ platform,+ rung: resolution.rung,+ });+ post({+ type: 'spawn-error',+ ptyId,+ message: error instanceof Error ? error.message : String(error),+ });+ return;+ }+ const spawnOptions: PtySpawnOptions = {+ name: 'xterm-256color',+ cols: message.cols,+ rows: message.rows,+ cwd: message.cwd,+ env: shellEnv,+ encoding: 'utf8',+ };let pty: PtyProcessLike;try {- pty = deps.spawn(shell, buildShellArgs(platform, shell, message.launchCommand), {- name: 'xterm-256color',- cols: message.cols,- rows: message.rows,- cwd: message.cwd,- env: shellEnv,- encoding: 'utf8',+ pty = deps.spawn(shell, shellArgs, {+ ...spawnOptions,+ ...(platform === 'win32' ? { useConptyDll: true } : {}),});} catch (err) {- // node-pty can throw synchronously at spawn on resource exhaustion- // (EMFILE/ENOMEM). Contain it as an error message so the utility- // process survives instead of crashing the window (a bad shell path- // is NOT this path — that surfaces as an async exit with code 1).- // A non-Error throw must still yield a string: the main-side- // `asHostMessage` drops a spawn-error whose `message` is not a string,- // which would strand the panel with no exit ever routed.- const message = err instanceof Error ? err.message : String(err);- post({ type: 'spawn-error', ptyId, message });- return;+ const conptyFailureReason = platform === 'win32' ? conptyDllLoadFailureReason(err) : null;+ if (conptyFailureReason !== null) {+ deps.logger?.warn({+ event: 'pty-host-conpty-dll-fallback',+ reason: conptyFailureReason,+ });+ try {+ pty = deps.spawn(shell, shellArgs, { ...spawnOptions, useConptyDll: false });+ } catch (fallbackErr) {+ const fallbackMessage =+ fallbackErr instanceof Error ? fallbackErr.message : String(fallbackErr);+ post({ type: 'spawn-error', ptyId, message: fallbackMessage });+ return;+ }+ } else {+ // node-pty can throw synchronously at spawn on resource exhaustion or a+ // Windows CreateProcessW failure; other Windows launch failures arrive+ // asynchronously as exits whose value may be a Win32 error or -1.+ // Contain the synchronous shape so the utility process survives.+ // A non-Error throw must still yield a string: the main-side+ // `asHostMessage` drops a spawn-error whose `message` is not a string,+ // which would strand the panel with no exit ever routed.+ const spawnMessage = err instanceof Error ? err.message : String(err);+ post({ type: 'spawn-error', ptyId, message: spawnMessage });+ return;+ }}sessions.set(ptyId, pty);pty.onData((data) => {@@ -413,6 +873,7 @@ export function setupPtyHost(deps: SetupPtyHostDeps): PtyHostHandle {pty.onExit(({ exitCode, signal }) => {if (sessions.get(ptyId) === pty) sessions.delete(ptyId);post({ type: 'exit', ptyId, exitCode, signal: signal ?? null });+ if (shuttingDown && sessions.size === 0) finishShutdown();});}@@ -437,6 +898,42 @@ export function setupPtyHost(deps: SetupPtyHostDeps): PtyHostHandle {sessions.get(message.ptyId)?.resume();}+ function killActiveSessions(): void {+ for (const pty of sessions.values()) safeKill(pty);+ sessions.clear();+ }++ let shuttingDown = false;+ let shutdownToken: ReturnType<typeof setTimeout> | null = null;+ let hostExited = false;++ function finishShutdown(): void {+ if (hostExited) return;+ hostExited = true;+ if (shutdownToken !== null) {+ clearHostTimer(shutdownToken);+ shutdownToken = null;+ }+ sessions.clear();+ deps.flushLogger?.();+ deps.exitHost?.(0);+ }++ function handleShutdown(): void {+ if (shuttingDown) return;+ shuttingDown = true;+ for (const pty of sessions.values()) safeKill(pty);+ if (sessions.size === 0) {+ finishShutdown();+ return;+ }+ shutdownToken = setHostTimer(() => {+ shutdownToken = null;+ deps.logger?.warn({ event: 'pty-host-shutdown-deadline', remaining: sessions.size });+ finishShutdown();+ }, shutdownMs);+ }+deps.parentPort?.on('message', (event) => {const message = asIncomingMessage(event.data);if (!message) {@@ -462,6 +959,9 @@ export function setupPtyHost(deps: SetupPtyHostDeps): PtyHostHandle {case 'resume':handleResume(message);break;+ case 'shutdown':+ handleShutdown();+ break;default:// `asIncomingMessage` admits any string `type`, so an unknown variant// (a future/stale contract) lands here visibly instead of silently.@@ -477,8 +977,7 @@ export function setupPtyHost(deps: SetupPtyHostDeps): PtyHostHandle {killActive(): void {// safeKill per entry so one shell's ESRCH (already exited) cannot abort// the reap of the rest.- for (const pty of sessions.values()) safeKill(pty);- sessions.clear();+ killActiveSessions();},};}@@ -540,12 +1039,16 @@ if ((process as NodeJS.Process & { parentPort?: unknown }).parentPort) {void (async () => {let log: {warn(data: Record<string, unknown>, message?: string): void;+ info(data: Record<string, unknown>, message?: string): void;} = {warn: (data, message) => console.warn(message ?? '[pty-host] warning', data),+ info: (data, message) => console.info(message ?? '[pty-host] info', data),};+ let flushLogger = () => {};try {- const { getLogger } = await import('../main/desktop-logger.ts');+ const { flushDesktopLogger, getLogger } = await import('../main/desktop-logger.ts');log = getLogger('pty-host');+ flushLogger = flushDesktopLogger;} catch (err) {const code = (err as { code?: unknown } | null)?.code;console.warn('[pty-host] logger unavailable; using console fallback', {@@ -567,8 +1070,21 @@ if ((process as NodeJS.Process & { parentPort?: unknown }).parentPort) {const handle = setupPtyHost({parentPort,spawn,+ exitHost: (code) => process.exit(code),+ flushLogger,env: process.env,- logger: { warn: (o) => log.warn(o, 'unexpected pty-host message') },+ cliBinDir:+ process.platform === 'win32'+ ? join(+ (process as NodeJS.Process & { resourcesPath: string }).resourcesPath,+ 'cli',+ 'bin',+ )+ : undefined,+ logger: {+ warn: (o) => log.warn(o, 'pty-host warning'),+ info: (o) => log.info(o, 'pty-host shell resolution'),+ },});installHostReaping(handle, process);})();diff --git a/packages/desktop/src/utility/support-file-write.ts b/packages/desktop/src/utility/support-file-write.tsnew file mode 100644index 000000000..24c99aa5d--- /dev/null+++ b/packages/desktop/src/utility/support-file-write.ts@@ -0,0 +1,134 @@+/**+ * Materialize a registry-authored launch support file beneath the PTY cwd.+ *+ * Trust boundary: the file lands below a project the user merely OPENED, whose+ * contents are attacker-controlled in the sense that matters here — a Windows+ * Git checkout with symlink support (`core.symlinks=true`) materializes tracked+ * symlinks and junctions on clone. The relative path is already pinned to one+ * literal shape by the message guard in `pty-host.ts`, but that guard is lexical+ * and a lexical guard cannot see a symlink: `join` resolves nothing, recursive+ * `mkdir` traverses an existing symlinked component rather than refusing it, and+ * `writeFile` follows a symlinked leaf. So the guard pins the string while the+ * resolved write location stays unconstrained.+ *+ * The order here is the same one the deck / trash / asset handlers apply:+ * canonicalize via realpath, then enforce containment on the RESOLVED path.+ * Applied per segment rather than once at the end, because "check afterwards"+ * would already have created directories under the attacker's target — the walk+ * refuses BEFORE anything outside the project is written. A segment that does+ * not exist yet is created as a real directory inside an already-verified+ * parent, so it cannot be a link; a segment that does exist is resolved and+ * contained before the walk descends into it. Windows junctions need no separate+ * handling: `realpath` collapses them exactly as it collapses symlinks, and+ * libuv reports junction mount points and symlinks as symbolic links at the+ * leaf, so the same `lstat` guard refuses either shape.+ *+ * The leaf is refused if it is a link of any kind — including one that resolves+ * back inside the project, since this path is one OK owns outright and a link+ * there is not a shape it authored. `lstat` gives that a uniform refusal on+ * every platform; `O_NOFOLLOW` then makes the POSIX write race-free against a+ * link planted between the check and the open. Windows has no `O_NOFOLLOW` in+ * libuv (and no `FILE_FLAG_OPEN_REPARSE_POINT` exposed through Node), so the+ * Windows leaf write remains TOCTOU-bounded by the `lstat` — the strongest+ * boundary reachable with current Node filesystem APIs. The per-segment+ * `realpath` checks refuse pre-existing symlink and junction escapes before the+ * walk creates anything outside the project. Node does not expose an openat-style+ * race-free directory traversal, so concurrent replacement of an already-verified+ * parent remains outside this boundary on every platform.+ *+ * A refusal throws, which routes into the caller's existing optional-support-file+ * degradation: the terminal opens a bare Claude launch (Claude then shows its own+ * trust prompt) instead of cancelling or writing outside the project.+ */++import {+ closeSync,+ constants,+ lstatSync,+ mkdirSync,+ openSync,+ realpathSync,+ writeFileSync,+} from 'node:fs';+import { join } from 'node:path';+import type { TerminalLaunchCommand } from '@inkeep/open-knowledge-core';+import { isPathWithinProject } from '../shared/path-containment.ts';++/** Refusal code surfaced on the caller's `pty-host-support-file-materialize-failed`+ * warn, so a containment refusal is distinguishable from a disk error (EROFS,+ * ENOSPC, AV lock) at triage. Bounded cardinality — one literal. */+export const TERMINAL_SUPPORT_FILE_ESCAPE_CODE = 'ERR_TERMINAL_SUPPORT_FILE_ESCAPE';++function refuseEscape(detail: string, cause?: unknown): NodeJS.ErrnoException {+ return Object.assign(+ new Error(`support file would escape the project root: ${detail}`, { cause }),+ { code: TERMINAL_SUPPORT_FILE_ESCAPE_CODE },+ );+}++/**+ * Reject traversal and separator ambiguity at the write boundary. The sole producer+ * pins the full registry-authored filename separately.+ */+function splitRelativePath(relativePath: string): { segments: string[]; leaf: string } {+ if (relativePath.length === 0 || relativePath.includes('\0') || relativePath.includes('\\')) {+ throw refuseEscape('malformed relative path');+ }+ const parts = relativePath.split('/');+ if (parts.some((part) => part.length === 0 || part === '.' || part === '..')) {+ throw refuseEscape('malformed relative path');+ }+ const leaf = parts.pop();+ if (leaf === undefined || parts.length === 0) throw refuseEscape('malformed relative path');+ return { segments: parts, leaf };+}++export function materializeSupportFileSync(+ cwd: string,+ file: NonNullable<TerminalLaunchCommand['supportFile']>,+): void {+ // The host platform, NOT the logical launch platform the PTY host was told to+ // compose for. These are real paths on the machine actually running, and tests+ // drive win32 launch composition on a POSIX runner — reading the logical+ // platform here would apply win32 path grammar to POSIX paths and refuse+ // everything.+ const platform = process.platform;+ const { segments, leaf } = splitRelativePath(file.relativePath);++ const root = realpathSync(cwd);++ let dir = root;+ for (const segment of segments) {+ const next = join(dir, segment);+ try {+ mkdirSync(next);+ } catch (err) {+ if ((err as NodeJS.ErrnoException | null)?.code !== 'EEXIST') throw err;+ }+ try {+ dir = realpathSync(next);+ } catch (error) {+ const code = (error as NodeJS.ErrnoException | null)?.code;+ if (code !== 'ENOENT' && code !== 'ELOOP') throw error;+ throw refuseEscape(`directory segment ${segment} cannot be resolved`, error);+ }+ if (!isPathWithinProject(dir, root, platform)) {+ throw refuseEscape(`directory segment ${segment} resolves outside the project`);+ }+ }++ const target = join(dir, leaf);+ if (lstatSync(target, { throwIfNoEntry: false })?.isSymbolicLink() === true) {+ throw refuseEscape('settings file is a symlink');+ }+ const fd = openSync(+ target,+ constants.O_WRONLY | constants.O_CREAT | constants.O_TRUNC | (constants.O_NOFOLLOW ?? 0),+ 0o600,+ );+ try {+ writeFileSync(fd, file.contents, { encoding: 'utf8' });+ } finally {+ closeSync(fd);+ }+}diff --git a/packages/desktop/tests/integration/auto-updater.test.ts b/packages/desktop/tests/integration/auto-updater.test.tsindex 554a75b5e..2b3690333 100644--- a/packages/desktop/tests/integration/auto-updater.test.ts+++ b/packages/desktop/tests/integration/auto-updater.test.ts@@ -226,6 +226,8 @@ function makeRig(* another process claiming the app's bundle URL and so cannot see these.*/prepareForRelaunch?: () => void;+ /** Windows install-tree console-host cleanup immediately before install. */+ sweepUpdateSurvivors?: Parameters<typeof startAutoUpdater>[0]['sweepUpdateSurvivors'];/*** Menu-driven check-result dispatcher — production renders a* `dialog.showMessageBox`. Tests pass a spy to assert the@@ -276,6 +278,7 @@ function makeRig(updaterSetup,extraWindowCount = 0,prepareForRelaunch,+ sweepUpdateSurvivors,showCheckNowResult,reclaimStagedUpdateCache,linuxInstallSupport,@@ -332,6 +335,7 @@ function makeRig(feedUrl,proxyFeed,prepareForRelaunch,+ sweepUpdateSurvivors,showCheckNowResult,reclaimStagedUpdateCache,linuxInstallSupport,@@ -3241,7 +3245,7 @@ describe('ok:update:relaunch-now IPC handler (AC18)', () => {expect(rig.ipc.handlers.has('ok:update:relaunch-now')).toBe(false);});- test('prepareForRelaunch fires BEFORE quitAndInstall — utility kill ordering', async () => {+ test('teardown and survivor sweep fire before quitAndInstall in that order', async () => {const calls: string[] = [];const updater = new FakeUpdater();updater.quitAndInstall = vi.fn(() => {@@ -3267,6 +3271,9 @@ describe('ok:update:relaunch-now IPC handler (AC18)', () => {prepareForRelaunch: async () => {calls.push('prepareForRelaunch');},+ sweepUpdateSurvivors: () => {+ calls.push('sweepUpdateSurvivors');+ },clock: makeFakeClock(),now: () => new Date(),logger: {@@ -3277,7 +3284,7 @@ describe('ok:update:relaunch-now IPC handler (AC18)', () => {},});await ipc.invoke('ok:update:relaunch-now');- expect(calls).toEqual(['prepareForRelaunch', 'quitAndInstall']);+ expect(calls).toEqual(['prepareForRelaunch', 'sweepUpdateSurvivors', 'quitAndInstall']);});test('prepareForRelaunch does NOT fire when versionPendingInstall is null', () => {@@ -3298,6 +3305,36 @@ describe('ok:update:relaunch-now IPC handler (AC18)', () => {expect(rig.updater.quitAndInstall).toHaveBeenCalledTimes(1);expect(rig.logger.warn).toHaveBeenCalled();});++ test('survivor sweep throw does NOT block quitAndInstall', async () => {+ const sweepUpdateSurvivors = vi.fn(() => {+ throw new Error('process query failed');+ });+ const { rig } = makeRig({ versionPendingInstall: '0.3.2', sweepUpdateSurvivors });+ await rig.ipc.invoke('ok:update:relaunch-now');+ expect(sweepUpdateSurvivors).toHaveBeenCalledTimes(1);+ expect(rig.updater.quitAndInstall).toHaveBeenCalledTimes(1);+ expect(rig.logger.warn).toHaveBeenCalled();+ });++ test('incomplete survivor sweep is observable and does NOT block quitAndInstall', async () => {+ const sweepUpdateSurvivors = vi.fn(() => ({+ candidateCount: 2,+ terminatedCount: 0,+ failedCount: 0,+ scanFailed: false,+ revalidationFailed: true,+ }));+ const { rig } = makeRig({ versionPendingInstall: '0.3.2', sweepUpdateSurvivors });++ await rig.ipc.invoke('ok:update:relaunch-now');++ expect(rig.updater.quitAndInstall).toHaveBeenCalledTimes(1);+ expect(rig.logger.warn).toHaveBeenCalledWith(+ 'update survivor sweep incomplete — proceeding to quitAndInstall anyway',+ { result: expect.objectContaining({ revalidationFailed: true }) },+ );+ });});// ————————————————————————————————————————————————————————diff --git a/packages/desktop/tests/main/claude-readiness.test.ts b/packages/desktop/tests/main/claude-readiness.test.tsindex 9f6b75801..c8ceca518 100644--- a/packages/desktop/tests/main/claude-readiness.test.ts+++ b/packages/desktop/tests/main/claude-readiness.test.ts@@ -7,11 +7,13 @@ import {mcpStatusFromClassification,type ProbeChild,type ProbeTimers,+ probePlatformCliOnPath,resolveClaudeReadiness,resolveCliInstalledMap,resolveCliOnPath,resolvePlatformCliInstalledMap,runLoginShellProbe,+ runWindowsPathProbe,} from '../../src/main/claude-readiness.ts';/** Spy logger shared by every `getLogger(name)` call inside claude-readiness —@@ -217,6 +219,159 @@ describe('runLoginShellProbe', () => {});});+describe('runWindowsPathProbe', () => {+ test('spawns where.exe with the PATHEXT-aware $PATH: query for the binary', async () => {+ const { child, emitExit } = makeFakeChild();+ const { timers } = makeFakeTimers();+ let spawnedFile = '';+ let spawnedArgs: readonly string[] = [];+ const p = runWindowsPathProbe(+ (file, args) => {+ spawnedFile = file;+ spawnedArgs = args;+ return child;+ },+ 'C:\\Windows\\System32\\where.exe',+ 'claude',+ timers,+ );+ emitExit(0);+ await p;+ expect(spawnedFile).toBe('C:\\Windows\\System32\\where.exe');+ expect(spawnedArgs).toEqual(['$PATH:claude']);+ });++ test('exit 0 resolves 0 and clears the timeout', async () => {+ const { child, emitExit } = makeFakeChild();+ const { timers, wasCleared } = makeFakeTimers();+ const p = runWindowsPathProbe(() => child, 'where.exe', 'claude', timers);+ emitExit(0);+ expect(await p).toBe(0);+ expect(wasCleared()).toBe(true);+ });++ test('a non-zero exit resolves that code (where.exe ran; the binary is absent)', async () => {+ const { child, emitExit } = makeFakeChild();+ const { timers } = makeFakeTimers();+ const p = runWindowsPathProbe(() => child, 'where.exe', 'codex', timers);+ emitExit(1);+ expect(await p).toBe(1);+ });++ test("an async spawn 'error' resolves null (UNKNOWN, not absent)", async () => {+ const { child, emitError } = makeFakeChild();+ const { timers, wasCleared } = makeFakeTimers();+ const p = runWindowsPathProbe(() => child, 'where.exe', 'claude', timers);+ emitError(new Error('spawn where.exe ENOENT'));+ expect(await p).toBe(null);+ expect(wasCleared()).toBe(true);+ });++ test('a synchronous spawn throw resolves null (UNKNOWN, not absent)', async () => {+ const { timers } = makeFakeTimers();+ const p = runWindowsPathProbe(+ () => {+ throw new Error('spawn EMFILE');+ },+ 'where.exe',+ 'claude',+ timers,+ );+ expect(await p).toBe(null);+ });++ test('a wedged where.exe times out, is killed, and resolves null', async () => {+ const { child, wasKilled } = makeFakeChild();+ const { timers, fireTimeout } = makeFakeTimers();+ const p = runWindowsPathProbe(() => child, 'where.exe', 'claude', timers, 5000);+ // where.exe never exits — fire the injected timeout.+ fireTimeout();+ expect(await p).toBe(null);+ expect(wasKilled()).toBe(true);+ });++ test('settles once — a late exit after the timeout does not overwrite UNKNOWN', async () => {+ const { child, emitExit } = makeFakeChild();+ const { timers, fireTimeout } = makeFakeTimers();+ const p = runWindowsPathProbe(() => child, 'where.exe', 'claude', timers);+ fireTimeout();+ emitExit(0); // late — already settled to null+ expect(await p).toBe(null);+ });++ test("settles once — an exit after an 'error' does not overwrite UNKNOWN", async () => {+ const { child, emitError, emitExit } = makeFakeChild();+ const { timers } = makeFakeTimers();+ const p = runWindowsPathProbe(() => child, 'where.exe', 'claude', timers);+ emitError(new Error('spawn where.exe EACCES'));+ emitExit(0); // Windows emits 'error' then 'exit'; the first settle wins.+ expect(await p).toBe(null);+ });+});++describe('windows probe verdict observability (an UNKNOWN must leave a trace)', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ });++ test('a where.exe timeout emits an operator-visible record naming the failure class', async () => {+ const { child } = makeFakeChild();+ const { timers, fireTimeout } = makeFakeTimers();+ const p = runWindowsPathProbe(() => child, 'where.exe', 'claude', timers, 5000);+ fireTimeout();+ expect(await p).toBe(null);+ const messages = operatorVisibleRecords().map((call) => call.map(String).join(' '));+ expect(messages.some((m) => /timed?\s*out/i.test(m))).toBe(true);+ });++ test("an async where.exe 'error' emits an operator-visible record carrying the cause", async () => {+ const { child, emitError } = makeFakeChild();+ const { timers } = makeFakeTimers();+ const p = runWindowsPathProbe(() => child, 'where.exe', 'claude', timers);+ const spawnFailure = new Error('spawn where.exe ENOENT');+ emitError(spawnFailure);+ expect(await p).toBe(null);+ expect(+ operatorVisibleRecords().some((call) =>+ call.some((arg) => (arg as { err?: unknown })?.err === spawnFailure),+ ),+ ).toBe(true);+ });++ test('a synchronous where.exe spawn throw emits an operator-visible record carrying the cause', async () => {+ const { timers } = makeFakeTimers();+ const spawnFailure = new Error('spawn EMFILE');+ const p = runWindowsPathProbe(+ () => {+ throw spawnFailure;+ },+ 'where.exe',+ 'claude',+ timers,+ );+ expect(await p).toBe(null);+ expect(+ operatorVisibleRecords().some((call) =>+ call.some((arg) => (arg as { err?: unknown })?.err === spawnFailure),+ ),+ ).toBe(true);+ });++ test('the logged attributes stay bounded-cardinality (registry bin, no free-form strings)', async () => {+ const { child } = makeFakeChild();+ const { timers, fireTimeout } = makeFakeTimers();+ const p = runWindowsPathProbe(() => child, 'where.exe', 'claude', timers, 5000);+ fireTimeout();+ expect(await p).toBe(null);+ const attrs = operatorVisibleRecords()+ .flat()+ .find((arg): arg is Record<string, unknown> => typeof arg === 'object' && arg !== null);+ expect(attrs).toBeDefined();+ expect(attrs?.bin).toBe('claude');+ expect(Object.keys(attrs ?? {}).sort()).toEqual(['args', 'bin', 'timeoutMs', 'whereExe']);+ });+});+describe('probe verdict observability (an UNKNOWN must leave a trace)', () => {// The launch gate and the row-hiding installed map both key off this probe's// verdict. Standing contract: every probe-failure resolution must emit an@@ -452,10 +607,74 @@ describe('resolveCliInstalledMap', () => {});});+describe('probePlatformCliOnPath', () => {+ test('Windows uses the PATHEXT-aware native probe and never builds POSIX argv', async () => {+ const probePosix = vi.fn(async () => 0);+ const probeWindows = vi.fn(async (bin: string) => (bin === 'claude' ? 0 : 1));++ await expect(+ probePlatformCliOnPath({+ platform: 'win32',+ bin: 'claude',+ probePosix,+ probeWindows,+ }),+ ).resolves.toBe(0);+ await expect(+ probePlatformCliOnPath({+ platform: 'win32',+ bin: 'codex',+ probePosix,+ probeWindows,+ }),+ ).resolves.toBe(1);++ expect(probeWindows).toHaveBeenCalledWith('claude');+ expect(probeWindows).toHaveBeenCalledWith('codex');+ expect(probePosix).not.toHaveBeenCalled();+ });++ test('Windows passes an UNKNOWN through as null, never collapsing it to a not-found code', async () => {+ // A wedged / unspawnable where.exe means presence is UNVERIFIABLE. Mapping+ // it to a definitive exit code here is what turns an infrastructure failure+ // into a false "not installed" verdict downstream.+ await expect(+ probePlatformCliOnPath({+ platform: 'win32',+ bin: 'claude',+ probePosix: vi.fn(async () => 0),+ probeWindows: vi.fn(async () => null),+ }),+ ).resolves.toBe(null);+ });++ test('macOS and Linux preserve their interactive command-v argv', async () => {+ const probePosix = vi.fn(async () => 0);+ const probeWindows = vi.fn(async () => 1);++ await probePlatformCliOnPath({+ platform: 'darwin',+ bin: 'claude',+ probePosix,+ probeWindows,+ });+ await probePlatformCliOnPath({+ platform: 'linux',+ bin: 'cursor-agent',+ probePosix,+ probeWindows,+ });++ expect(probeWindows).not.toHaveBeenCalled();+ expect(probePosix).toHaveBeenNthCalledWith(1, cliProbeArgs('claude', 'darwin'));+ expect(probePosix).toHaveBeenNthCalledWith(2, cliProbeArgs('cursor-agent', 'linux'));+ });+});+describe('resolvePlatformCliInstalledMap', () => {test('Windows resolves registry binaries with the native PATH probe', async () => {const probePosix = vi.fn(async () => 127);- const probeWindows = vi.fn(async (bin: string) => bin === 'codex');+ const probeWindows = vi.fn(async (bin: string) => (bin === 'codex' ? 0 : 1));const map = await resolvePlatformCliInstalledMap({platform: 'win32',@@ -470,11 +689,25 @@ describe('resolvePlatformCliInstalledMap', () => {expect(probeWindows).toHaveBeenCalledWith('cursor-agent');});+ test('an unverifiable Windows probe omits the entry rather than caching a false negative', async () => {+ const map = await resolvePlatformCliInstalledMap({+ platform: 'win32',+ probePosix: vi.fn(async () => 0),+ probeWindows: vi.fn(async (bin: string) => (bin === 'claude' ? null : 1)),+ });++ // Omitted (UNKNOWN), NOT `false` — row gating fails open on `undefined`,+ // and auto-pick requires `=== true`, so an unverifiable CLI is never+ // rendered as "not installed" off a probe that could not run.+ expect('claude' in map).toBe(false);+ expect(map.codex).toBe(false);+ });+test('macOS probes with the login-interactive shell argv', async () => {const probePosix = vi.fn(async (args: readonly string[]) =>args.at(-1) === 'command -v cursor-agent' ? 0 : 127,);- const probeWindows = vi.fn(async () => false);+ const probeWindows = vi.fn(async () => 1);const map = await resolvePlatformCliInstalledMap({platform: 'darwin',@@ -498,7 +731,7 @@ describe('resolvePlatformCliInstalledMap', () => {await resolvePlatformCliInstalledMap({platform: 'linux',probePosix,- probeWindows: vi.fn(async () => false),+ probeWindows: vi.fn(async () => 1),});expect(probed).toContainEqual(['-i', '-c', 'command -v claude']);diff --git a/packages/desktop/tests/main/menu-localization.test.ts b/packages/desktop/tests/main/menu-localization.test.tsindex 55856a547..95b1642b2 100644--- a/packages/desktop/tests/main/menu-localization.test.ts+++ b/packages/desktop/tests/main/menu-localization.test.ts@@ -20,6 +20,7 @@ function makeDeps(overrides: Partial<MenuDeps> = {}): MenuDeps {return {appName: 'OpenKnowledge',showDevToolsMenu: true,+ terminalCapable: true,dialog: {} as Dialog,openNavigator: vi.fn(),openProject: vi.fn(async () => {}),diff --git a/packages/desktop/tests/main/menu.test.ts b/packages/desktop/tests/main/menu.test.tsindex b68420726..00b219f6e 100644--- a/packages/desktop/tests/main/menu.test.ts+++ b/packages/desktop/tests/main/menu.test.ts@@ -29,6 +29,7 @@ function makeDeps(overrides: Partial<MenuDeps> = {}): MenuDeps {return {appName: 'OpenKnowledge',showDevToolsMenu: true,+ terminalCapable: true,dialog: {} as MenuDeps['dialog'],openNavigator: vi.fn(() => {}),openProject: vi.fn(() => Promise.resolve()),@@ -1498,7 +1499,7 @@ describe('buildMenuTemplate — top-level Terminal menu', () => {expect(findByLabel(linux, 'Kill Terminal')?.enabled).toBe(true);});- test('PTY-backed commands stay disabled on unsupported platforms', () => {+ test('PTY-backed commands are enabled on supported Windows builds', () => {const windows = buildMenuTemplateForPlatform('win32',makeDeps({@@ -1511,6 +1512,27 @@ describe('buildMenuTemplate — top-level Terminal menu', () => {}),);+ expect(findByLabel(windows, 'Show Terminal')?.enabled).toBe(true);+ expect(findByLabel(windows, 'Move Terminal to right')?.enabled).toBe(true);+ expect(findByLabel(windows, 'New Terminal')?.enabled).toBe(true);+ expect(findByLabel(windows, 'New Terminal Window')?.enabled).toBe(true);+ expect(findByLabel(windows, 'Kill Terminal')?.enabled).toBe(true);+ });++ test('pre-floor Windows disables every PTY-backed menu affordance', () => {+ const windows = buildMenuTemplateForPlatform(+ 'win32',+ makeDeps({+ terminalCapable: false,+ onToggleTerminal: vi.fn(() => {}),+ onMoveTerminal: vi.fn(() => {}),+ onNewTerminal: vi.fn(() => {}),+ onNewTerminalWindow: vi.fn(() => {}),+ onKillTerminal: vi.fn(() => {}),+ terminalLive: true,+ }),+ );+expect(findByLabel(windows, 'Show Terminal')?.enabled).toBe(false);expect(findByLabel(windows, 'Move Terminal to right')?.enabled).toBe(false);expect(findByLabel(windows, 'New Terminal')?.enabled).toBe(false);diff --git a/packages/desktop/tests/main/terminal-lifecycle.test.ts b/packages/desktop/tests/main/terminal-lifecycle.test.tsindex 2aaefa1e1..89985a947 100644--- a/packages/desktop/tests/main/terminal-lifecycle.test.ts+++ b/packages/desktop/tests/main/terminal-lifecycle.test.ts@@ -28,17 +28,20 @@ import type { PtyHostIncomingMessage } from '../../src/utility/pty-host.ts';class FakeUtility {posted: PtyHostIncomingMessage[] = [];killed = 0;+ private exitCb: ((code: number | null) => void) | null = null;postMessage(m: PtyHostIncomingMessage): void {this.posted.push(m);}- on(_event: 'message' | 'exit', _cb: (arg: never) => void): void {- // The lifecycle harness drives create/input/kill, not host-originated- // data/exit, so the message/exit subscriptions are intentionally inert.+ on(event: 'message' | 'exit', cb: (arg: never) => void): void {+ if (event === 'exit') this.exitCb = cb as (code: number | null) => void;}kill(): boolean {this.killed += 1;return true;}+ emitExit(code: number | null): void {+ this.exitCb?.(code);+ }}function makeWebContents(): SendableWebContents {@@ -72,6 +75,8 @@ const PROJECT = '/Users/me/project';function makeRig() {const forked: FakeUtility[] = [];+ const timers: Array<{ cb: () => void; ms: number; cancelled: boolean }> = [];+ const warnings: Array<Record<string, unknown>> = [];let idn = 0;const mgr: TerminalManager = createTerminalManager({forkPtyHost: () => {@@ -82,8 +87,14 @@ function makeRig() {sendData: () => {},sendExit: () => {},newPtyId: () => `pty-${++idn}`,- setTimer: () => 0,- clearTimer: () => {},+ setTimer: (cb, ms) => {+ timers.push({ cb, ms, cancelled: false });+ return timers.length - 1;+ },+ clearTimer: (token) => {+ if (typeof token === 'number' && timers[token]) timers[token].cancelled = true;+ },+ logger: { warn: (event) => warnings.push(event) },});const reaper: TerminalReaper = mgr;// Open a terminal for a fresh window and wire its close-reap, as production@@ -101,17 +112,28 @@ function makeRig() {if (!res.ok) throw new Error('expected a terminal to be created');return { win, ptyId: res.ptyId };}- return { mgr, reaper, forked, openTerminalWindow };+ const runTimers = (): void => {+ for (const timer of timers) {+ if (!timer.cancelled) timer.cb();+ timer.cancelled = true;+ }+ };+ return { mgr, reaper, forked, timers, warnings, runTimers, openTerminalWindow };}describe('terminal lifecycle — window close reap', () => {- test('closing a window kills its PTY host and deletes the map entry', () => {+ test('closing a window requests host shutdown and force-kills after two seconds', () => {const rig = makeRig();const { win } = rig.openTerminalWindow(1);expect(rig.forked[0]?.killed).toBe(0);win.close();+ expect(rig.forked[0]?.posted.at(-1)).toEqual({ type: 'shutdown' });+ expect(rig.forked[0]?.killed).toBe(0);+ expect(rig.timers.at(-1)?.ms).toBe(2000);+ rig.runTimers();expect(rig.forked[0]?.killed).toBe(1);+ expect(rig.warnings).toContainEqual({ event: 'terminal-manager-shutdown-deadline' });// Map entry deleted — a later create on the same window id forks anew.rig.openTerminalWindow(1);@@ -124,7 +146,10 @@ describe('terminal lifecycle — window close reap', () => {// close() destroys the native window before firing 'closed' (FakeWindow.id// then throws). The reap must use the snapshotted id, not a deferred read.expect(() => win.close()).not.toThrow();- expect(rig.forked[0]?.killed).toBe(1);+ expect(rig.forked[0]?.posted.at(-1)).toEqual({ type: 'shutdown' });+ rig.forked[0]?.emitExit(0);+ rig.runTimers();+ expect(rig.forked[0]?.killed).toBe(0);});test('closing a window that never opened a terminal is a no-op', () => {@@ -143,6 +168,8 @@ describe('terminal lifecycle — per-window isolation', () => {const b = rig.openTerminalWindow(2);a.win.close();+ expect(rig.forked[0]?.posted.at(-1)).toEqual({ type: 'shutdown' });+ rig.runTimers();expect(rig.forked[0]?.killed).toBe(1);expect(rig.forked[1]?.killed).toBe(0);@@ -180,6 +207,9 @@ describe('terminal lifecycle — app quit reap', () => {rig.openTerminalWindow(2);rig.reaper.killAll();+ expect(rig.forked[0]?.posted.at(-1)).toEqual({ type: 'shutdown' });+ expect(rig.forked[1]?.posted.at(-1)).toEqual({ type: 'shutdown' });+ rig.runTimers();expect(rig.forked[0]?.killed).toBe(1);expect(rig.forked[1]?.killed).toBe(1);diff --git a/packages/desktop/tests/main/terminal-manager.test.ts b/packages/desktop/tests/main/terminal-manager.test.tsindex d4c5b8820..1afa19061 100644--- a/packages/desktop/tests/main/terminal-manager.test.ts+++ b/packages/desktop/tests/main/terminal-manager.test.ts@@ -1,4 +1,9 @@-import { describe, expect, test } from 'vitest';+import { WINDOWS_SHELL_FAMILIES } from '@inkeep/open-knowledge-core';+import {+ TERMINAL_SHELL_NOTICE_REASONS,+ TERMINAL_SUPPORT_FILE_NOTICE_REASONS,+} from '@inkeep/open-knowledge-core/desktop-bridge';+import { describe, expect, test, vi } from 'vitest';import {clampPtyDimension,createTerminalManager,@@ -26,9 +31,15 @@ import type { PtyHostIncomingMessage } from '../../src/utility/pty-host.ts';class FakeUtility {posted: PtyHostIncomingMessage[] = [];killed = 0;+ /**+ * When set, `postMessage` throws this instead of recording. The utility is an+ * injected dep, so this is the transport seam itself, not a stubbed internal.+ */+ throwOnPost: unknown = null;private msgCb: ((raw: unknown) => void) | null = null;private exitCb: ((code: number | null) => void) | null = null;postMessage(m: PtyHostIncomingMessage): void {+ if (this.throwOnPost !== null) throw this.throwOnPost;this.posted.push(m);}on(event: 'message' | 'exit', cb: (arg: never) => void): void {@@ -70,6 +81,7 @@ function makeManager(over?: Partial<TerminalManagerDeps>) {const sent: SentRecord[] = [];const forked: FakeUtility[] = [];const timers: Array<(() => void) | null> = [];+ const timerDelays: number[] = [];const warns: Array<Record<string, unknown>> = [];let idn = 0;const mgr = createTerminalManager({@@ -84,9 +96,16 @@ function makeManager(over?: Partial<TerminalManagerDeps>) {sendExit: (_wc, payload) => {sent.push({ channel: 'ok:pty:exit', payload: payload as unknown as Record<string, unknown> });},+ sendNotice: (_wc, payload) => {+ sent.push({+ channel: 'ok:pty:notice',+ payload: payload as unknown as Record<string, unknown>,+ });+ },newPtyId: () => `pty-${++idn}`,- setTimer: (cb) => {+ setTimer: (cb, ms) => {timers.push(cb);+ timerDelays.push(ms);return timers.length - 1;},clearTimer: (t) => {@@ -113,7 +132,17 @@ function makeManager(over?: Partial<TerminalManagerDeps>) {const exits = (): Array<Record<string, unknown>> =>sent.filter((s) => s.channel === 'ok:pty:exit').map((s) => s.payload);const liveTimerCount = (): number => timers.filter((t) => t !== null).length;- return { mgr, sent, forked, warns, runTimers, dataPayloads, exits, liveTimerCount };+ return {+ mgr,+ sent,+ forked,+ warns,+ runTimers,+ dataPayloads,+ exits,+ liveTimerCount,+ timerDelays,+ };}const PROJECT = '/Users/me/project';@@ -136,6 +165,215 @@ describe('createTerminalManager — create', () => {]);});+ test('forwards configured and invalid shell override state to the host resolver', () => {+ const h = makeManager();+ const wc = makeWebContents();+ h.mgr.create({+ windowId: 1,+ webContents: wc,+ projectRoot: PROJECT,+ cols: 80,+ rows: 24,+ shell: 'C:\\Tools\\pwsh.exe',+ shellInvalidReason: 'invalid-value',+ });++ expect(h.forked[0]?.posted[0]).toEqual({+ type: 'create',+ ptyId: 'pty-1',+ cwd: PROJECT,+ cols: 80,+ rows: 24,+ shell: 'C:\\Tools\\pwsh.exe',+ shellInvalidReason: 'invalid-value',+ });+ });++ test('forwards an invalid-override notice only to the addressed renderer session', () => {+ const h = makeManager();+ h.mgr.create({+ windowId: 1,+ webContents: makeWebContents(),+ projectRoot: PROJECT,+ cols: 80,+ rows: 24,+ });++ h.forked[0]?.emitMessage({+ type: 'shell-notice',+ ptyId: 'pty-1',+ notice: 'invalid-shell-override',+ reason: 'not-found',+ });++ expect(h.sent).toContainEqual({+ channel: 'ok:pty:notice',+ payload: { ptyId: 'pty-1', notice: 'invalid-shell-override', reason: 'not-found' },+ });+ });++ test('forwards the resolved Windows shell family to the addressed renderer session', () => {+ const h = makeManager();+ h.mgr.create({+ windowId: 1,+ webContents: makeWebContents(),+ projectRoot: PROJECT,+ cols: 80,+ rows: 24,+ });++ h.forked[0]?.emitMessage({+ type: 'shell-notice',+ ptyId: 'pty-1',+ notice: 'shell-resolved',+ shellFamily: 'bash',+ });++ expect(h.sent).toContainEqual({+ channel: 'ok:pty:notice',+ payload: { ptyId: 'pty-1', notice: 'shell-resolved', shellFamily: 'bash' },+ });+ });++ // Both notice payloads narrow through the shared guards, whose accepted sets+ // are built from the same vocabulary tuples the unions derive from, so what+ // this hop forwards is exactly the union. A reason or family added to a+ // vocabulary reaches the renderer without a second edit here, instead of+ // being silently dropped by a hand-mirrored literal chain.+ test.each([+ ...TERMINAL_SHELL_NOTICE_REASONS,+ ])('forwards the shared invalid-override reason %s to the renderer', (reason) => {+ const h = makeManager();+ h.mgr.create({+ windowId: 1,+ webContents: makeWebContents(),+ projectRoot: PROJECT,+ cols: 80,+ rows: 24,+ });++ h.forked[0]?.emitMessage({+ type: 'shell-notice',+ ptyId: 'pty-1',+ notice: 'invalid-shell-override',+ reason,+ });++ expect(h.sent).toContainEqual({+ channel: 'ok:pty:notice',+ payload: { ptyId: 'pty-1', notice: 'invalid-shell-override', reason },+ });+ });++ test.each([+ ...WINDOWS_SHELL_FAMILIES,+ ])('forwards the shared resolved shell family %s to the renderer', (shellFamily) => {+ const h = makeManager();+ h.mgr.create({+ windowId: 1,+ webContents: makeWebContents(),+ projectRoot: PROJECT,+ cols: 80,+ rows: 24,+ });++ h.forked[0]?.emitMessage({+ type: 'shell-notice',+ ptyId: 'pty-1',+ notice: 'shell-resolved',+ shellFamily,+ });++ expect(h.sent).toContainEqual({+ channel: 'ok:pty:notice',+ payload: { ptyId: 'pty-1', notice: 'shell-resolved', shellFamily },+ });+ });++ test.each([+ ...TERMINAL_SUPPORT_FILE_NOTICE_REASONS,+ ])('forwards the support-file degradation reason %s to the renderer', (reason) => {+ const h = makeManager();+ h.mgr.create({+ windowId: 1,+ webContents: makeWebContents(),+ projectRoot: PROJECT,+ cols: 80,+ rows: 24,+ });++ h.forked[0]?.emitMessage({+ type: 'shell-notice',+ ptyId: 'pty-1',+ notice: 'support-file-degraded',+ reason,+ });++ expect(h.sent).toContainEqual({+ channel: 'ok:pty:notice',+ payload: { ptyId: 'pty-1', notice: 'support-file-degraded', reason },+ });+ });++ test('drops a shell notice whose reason or family is outside the shared sets', () => {+ const h = makeManager();+ h.mgr.create({+ windowId: 1,+ webContents: makeWebContents(),+ projectRoot: PROJECT,+ cols: 80,+ rows: 24,+ });++ h.forked[0]?.emitMessage({+ type: 'shell-notice',+ ptyId: 'pty-1',+ notice: 'invalid-shell-override',+ reason: 'not-found-ish',+ });+ h.forked[0]?.emitMessage({+ type: 'shell-notice',+ ptyId: 'pty-1',+ notice: 'shell-resolved',+ shellFamily: 'zsh',+ });+ h.forked[0]?.emitMessage({+ type: 'shell-notice',+ ptyId: 'pty-1',+ notice: 'support-file-degraded',+ reason: 'escaped',+ });++ expect(h.sent.filter((s) => s.channel === 'ok:pty:notice')).toEqual([]);+ expect(h.warns.length).toBeGreaterThan(0);+ });++ test('drops a shell notice when the addressed WebContents is already destroyed', () => {+ const sendNotice = vi.fn((wc: SendableWebContents) => {+ if (wc.isDestroyed?.()) throw new Error('send on destroyed WebContents');+ });+ const h = makeManager({ sendNotice });+ const wc = makeWebContents();+ h.mgr.create({+ windowId: 1,+ webContents: wc,+ projectRoot: PROJECT,+ cols: 80,+ rows: 24,+ });+ wc.destroyed = true;++ expect(() =>+ h.forked[0]?.emitMessage({+ type: 'shell-notice',+ ptyId: 'pty-1',+ notice: 'invalid-shell-override',+ reason: 'not-found',+ }),+ ).not.toThrow();+ expect(sendNotice).not.toHaveBeenCalled();+ });+test('a window with no project root gets no terminal and no fork', () => {const h = makeManager();const r = h.mgr.create({@@ -312,6 +550,25 @@ describe('createTerminalManager — exit + crash surfacing', () => {expect(h.exits()[0]).toEqual({ ptyId: 'pty-1', exitCode: 0, signal: 9 });});+ test('normalizes the node-pty undefined exitCode race before renderer delivery', () => {+ const h = makeManager();+ h.mgr.create({+ windowId: 1,+ webContents: makeWebContents(),+ projectRoot: PROJECT,+ cols: 80,+ rows: 24,+ });+ h.forked[0]?.emitMessage({+ type: 'exit',+ ptyId: 'pty-1',+ exitCode: undefined,+ signal: null,+ });++ expect(h.exits()[0]).toEqual({ ptyId: 'pty-1', exitCode: -1, signal: null });+ });+test('maps a host spawn-error to a crashed exit carrying the message', () => {const h = makeManager();h.mgr.create({@@ -493,7 +750,7 @@ describe('createTerminalManager — destroyed-window guard', () => {});describe('createTerminalManager — lifecycle reap', () => {- test('killForWindow kills the host, deletes it, and silences its exit event', () => {+ test('killForWindow requests shutdown, then force-kills at the deadline', () => {const h = makeManager();h.mgr.create({windowId: 1,@@ -504,7 +761,12 @@ describe('createTerminalManager — lifecycle reap', () => {});const utility = h.forked[0];h.mgr.killForWindow(1);+ expect(utility?.posted.at(-1)).toEqual({ type: 'shutdown' });+ expect(utility?.killed).toBe(0);+ expect(h.timerDelays.at(-1)).toBe(2000);+ h.runTimers();expect(utility?.killed).toBe(1);+ expect(h.warns).toContainEqual({ event: 'terminal-manager-shutdown-deadline' });// The kill triggers a utility exit — it must NOT push into the gone window.utility?.emitExit(0);expect(h.exits()).toEqual([]);@@ -519,6 +781,24 @@ describe('createTerminalManager — lifecycle reap', () => {expect(h.forked).toHaveLength(2);});+ test('a cooperative host exit cancels the force-kill deadline', () => {+ const h = makeManager();+ h.mgr.create({+ windowId: 1,+ webContents: makeWebContents(),+ projectRoot: PROJECT,+ cols: 80,+ rows: 24,+ });+ const utility = h.forked[0];+ h.mgr.killForWindow(1);+ utility?.emitExit(0);+ h.runTimers();++ expect(utility?.posted.at(-1)).toEqual({ type: 'shutdown' });+ expect(utility?.killed).toBe(0);+ });+test('killForWindow on an unknown window is a no-op', () => {const h = makeManager();expect(() => h.mgr.killForWindow(42)).not.toThrow();@@ -541,6 +821,11 @@ describe('createTerminalManager — lifecycle reap', () => {rows: 24,});h.mgr.killAll();+ expect(h.forked[0]?.posted.at(-1)).toEqual({ type: 'shutdown' });+ expect(h.forked[1]?.posted.at(-1)).toEqual({ type: 'shutdown' });+ expect(h.forked[0]?.killed).toBe(0);+ expect(h.forked[1]?.killed).toBe(0);+ h.runTimers();expect(h.forked[0]?.killed).toBe(1);expect(h.forked[1]?.killed).toBe(1);// The map is cleared — a later create forks anew.@@ -554,10 +839,63 @@ describe('createTerminalManager — lifecycle reap', () => {expect(h.forked).toHaveLength(3);});+ // `main` awaits killAll() before letting Electron quit or apply an update, so+ // the promise's settlement is the contract — a reap that resolves early kills+ // shells the user is still using, and one that never resolves wedges quit.+ // These two pin both ends of it through the real manager/host seam.+ test('the killAll promise stays pending until the host exit arrives', async () => {+ const h = makeManager();+ h.mgr.create({+ windowId: 1,+ webContents: makeWebContents(),+ projectRoot: PROJECT,+ cols: 80,+ rows: 24,+ });++ let settled = false;+ const quit = h.mgr.killAll().then(() => {+ settled = true;+ });+ // Drain the whole microtask queue: a killAll that did not wait on its host+ // would already have set the flag by the time this resolves.+ await new Promise((resolve) => setImmediate(resolve));+ expect(settled).toBe(false);++ h.forked[0]?.emitExit(0);+ await quit;+ expect(settled).toBe(true);+ });++ test('the killAll promise settles at the deadline when the host never exits', async () => {+ const h = makeManager();+ h.mgr.create({+ windowId: 1,+ webContents: makeWebContents(),+ projectRoot: PROJECT,+ cols: 80,+ rows: 24,+ });++ let settled = false;+ const quit = h.mgr.killAll().then(() => {+ settled = true;+ });+ await new Promise((resolve) => setImmediate(resolve));+ expect(settled).toBe(false);++ // The host stays silent, so only the force-kill deadline can end the reap.+ h.runTimers();+ await quit;+ expect(settled).toBe(true);+ expect(h.forked[0]?.killed).toBe(1);+ });+test('killAll completes the reap even when one host throws on kill (no orphans)', () => {// A throwing kill on one host must not abort the loop — the remaining// windows' hosts would otherwise outlive the app (orphan shells).const forked: ThrowingUtility[] = [];+ const timers: Array<() => void> = [];let idn = 0;const mgr = createTerminalManager({forkPtyHost: () => {@@ -568,7 +906,10 @@ describe('createTerminalManager — lifecycle reap', () => {sendData: () => {},sendExit: () => {},newPtyId: () => `pty-${++idn}`,- setTimer: () => 0,+ setTimer: (cb) => {+ timers.push(cb);+ return timers.length - 1;+ },clearTimer: () => {},});for (const windowId of [1, 2, 3]) {@@ -582,12 +923,40 @@ describe('createTerminalManager — lifecycle reap', () => {}expect(() => mgr.killAll()).not.toThrow();+ for (const timer of timers) expect(() => timer()).not.toThrow();// Every host had kill() attempted despite the first one throwing.expect(forked.map((u) => u.killAttempts)).toEqual([1, 1, 1]);});+ // `postMessage` and `kill()` are different boundaries. A kill-shaped code on+ // a send must still reach the warn sink instead of inheriting kill's ESRCH+ // suppression.+ test('a shutdown-send failure is surfaced even when it carries a kill-shaped code', () => {+ const h = makeManager();+ h.mgr.create({+ windowId: 1,+ webContents: makeWebContents(),+ projectRoot: PROJECT,+ cols: 80,+ rows: 24,+ });+ const utility = h.forked[0];+ if (utility) utility.throwOnPost = Object.assign(new Error('post failed'), { code: 'ESRCH' });++ h.mgr.killForWindow(1);++ expect(h.warns).toContainEqual({+ event: 'terminal-manager-shutdown-send-failed',+ code: 'ESRCH',+ });+ // The failure branch is unchanged: deadline dropped, host force-killed.+ expect(utility?.killed).toBe(1);+ expect(h.liveTimerCount()).toBe(0);+ });+test('killForWindow swallows a throwing kill instead of crashing the reap', () => {const forked: ThrowingUtility[] = [];+ const timers: Array<() => void> = [];let idn = 0;const mgr = createTerminalManager({forkPtyHost: () => {@@ -598,7 +967,10 @@ describe('createTerminalManager — lifecycle reap', () => {sendData: () => {},sendExit: () => {},newPtyId: () => `pty-${++idn}`,- setTimer: () => 0,+ setTimer: (cb) => {+ timers.push(cb);+ return timers.length - 1;+ },clearTimer: () => {},});mgr.create({@@ -609,6 +981,7 @@ describe('createTerminalManager — lifecycle reap', () => {rows: 24,});expect(() => mgr.killForWindow(1)).not.toThrow();+ expect(() => timers[0]?.()).not.toThrow();expect(forked[0]?.killAttempts).toBe(1);});});@@ -978,6 +1351,8 @@ describe('createTerminalManager — concurrent sessions', () => {const { h } = twoSessions();h.mgr.killForWindow(1);expect(h.forked).toHaveLength(1);+ expect(h.forked[0]?.posted.at(-1)).toEqual({ type: 'shutdown' });+ h.runTimers();expect(h.forked[0]?.killed).toBe(1);});});diff --git a/packages/desktop/tests/main/terminal-reload-survival.test.ts b/packages/desktop/tests/main/terminal-reload-survival.test.tsindex b05d049f9..86ea2e9ad 100644--- a/packages/desktop/tests/main/terminal-reload-survival.test.ts+++ b/packages/desktop/tests/main/terminal-reload-survival.test.ts@@ -347,6 +347,56 @@ describe('issue #351 — re-adopting a surviving session is edge-correct acrossexpect(replay).toContain('hi');});+ test('adoption retains the resolved Windows shell family for path escaping', () => {+ const h = makeManager();+ const created = h.mgr.create({+ windowId: 1,+ webContents: makeWebContents(),+ projectRoot: PROJECT,+ cols: 80,+ rows: 24,+ });+ const ptyId = (created as { ok: true; ptyId: string }).ptyId;+ h.forked[0]?.emitMessage({+ type: 'shell-notice',+ ptyId,+ notice: 'shell-resolved',+ shellFamily: 'powershell',+ });++ const outcome = adoptViaManager(h.mgr, {+ windowId: 1,+ ptyId,+ webContents: makeWebContents(),+ });+ expect(outcome).toMatchObject({ ok: true, shellFamily: 'powershell' });+ });++ test('adoption retains a standing unsupported-shell capability notice', () => {+ const h = makeManager();+ const created = h.mgr.create({+ windowId: 1,+ webContents: makeWebContents(),+ projectRoot: PROJECT,+ cols: 80,+ rows: 24,+ });+ const ptyId = (created as { ok: true; ptyId: string }).ptyId;+ h.forked[0]?.emitMessage({+ type: 'shell-notice',+ ptyId,+ notice: 'invalid-shell-override',+ reason: 'unsupported-family',+ });++ const outcome = adoptViaManager(h.mgr, {+ windowId: 1,+ ptyId,+ webContents: makeWebContents(),+ });+ expect(outcome).toMatchObject({ ok: true, shellNoticeReason: 'unsupported-family' });+ });+test('adopt clears the stale outbound buffer so replayed bytes are not also delivered live (no duplicate)', () => {// Controllable timer + delivery capture: the default harness never fires// flushes, but this bug is exactly about a flush firing post-adopt against the@@ -446,13 +496,13 @@ describe('issue #351 — re-adopting a surviving session is edge-correct across});const idLive = (created as { ok: true; ptyId: string }).ptyId;- // The genuine TOCTOU on the WRITE: the session is present, but the pty host- // exits in the instant before adopt's resume post — posting to a dead- // utilityProcess throws. An unexpected (non-ESRCH) code is surfaced.+ // A failure on the WRITE: the session is present, but the resume post to+ // the pty host throws. Even a kill-shaped ESRCH code must be surfaced here;+ // send failures do not inherit kill()'s host-already-gone suppression.const host = h.forked[0];if (!host) throw new Error('expected window 1 to have forked a pty host');host.postMessage = (m: PtyHostIncomingMessage) => {- if (m.type === 'resume') throw Object.assign(new Error('gone'), { code: 'EPERM' });+ if (m.type === 'resume') throw Object.assign(new Error('gone'), { code: 'ESRCH' });};const outcome = adoptViaManager(h.mgr, {@@ -466,41 +516,12 @@ describe('issue #351 — re-adopting a surviving session is edge-correct acrossexpect(warns).toHaveLength(1);expect(warns[0]).toMatchObject({event: 'terminal-manager-adopt-resume-failed',- code: 'EPERM',+ code: 'ESRCH',windowId: 1,ptyId: idLive,});});- test('the expected ESRCH host-already-gone code is refused silently (a normal reload race, not a fault)', () => {- const warns: Record<string, unknown>[] = [];- const h = makeManager({ logger: { warn: (o) => warns.push(o) } });- const created = h.mgr.create({- windowId: 1,- webContents: makeWebContents(),- projectRoot: PROJECT,- cols: 80,- rows: 24,- });- const idLive = (created as { ok: true; ptyId: string }).ptyId;-- const host = h.forked[0];- if (!host) throw new Error('expected window 1 to have forked a pty host');- host.postMessage = (m: PtyHostIncomingMessage) => {- if (m.type === 'resume') throw Object.assign(new Error('gone'), { code: 'ESRCH' });- };-- const outcome = adoptViaManager(h.mgr, {- windowId: 1,- ptyId: idLive,- webContents: makeWebContents(),- });- expect(outcome).toEqual({ ok: false, reason: 'unknown-session' });- // ESRCH is the expected host-gone signal — refuse, but do not log it as a- // diagnostic; mirrors safeKillUtility's TOCTOU handling.- expect(warns).toHaveLength(0);- });-test('a ptyId belonging to another window is refused (no cross-window adoption)', () => {const h = makeManager();// Window 1 owns a live session; window 2 has its own independent host.diff --git a/packages/desktop/tests/main/terminal-window-attach-survival.test.ts b/packages/desktop/tests/main/terminal-window-attach-survival.test.tsindex f409f1e4e..c50ef78d9 100644--- a/packages/desktop/tests/main/terminal-window-attach-survival.test.ts+++ b/packages/desktop/tests/main/terminal-window-attach-survival.test.ts@@ -78,6 +78,7 @@ function makeWebContents(): SendableWebContents & { destroyed: boolean } {function makeTerminalManager() {const forked: FakeHost[] = [];const dataPushes: Array<{ ptyId: string; data: string }> = [];+ const shutdownTimers: Array<() => void> = [];let idn = 0;const mgr = createTerminalManager({forkPtyHost: () => {@@ -90,14 +91,18 @@ function makeTerminalManager() {newPtyId: () => `pty-${++idn}`,// Fire the coalesce flush synchronously so a host->renderer `data` push is// observable within the test without real timers.- setTimer: (cb: () => void) => {- cb();- return 0;+ setTimer: (cb: () => void, ms: number) => {+ if (ms === 2000) shutdownTimers.push(cb);+ else cb();+ return shutdownTimers.length;},clearTimer: () => {},logger: { warn: () => {} },});- return { mgr, forked, dataPushes };+ const runShutdownTimers = (): void => {+ for (const cb of shutdownTimers) cb();+ };+ return { mgr, forked, dataPushes, runShutdownTimers };}// --- WindowManager attach harness (owner editor window owns the server) ------@@ -220,7 +225,7 @@ describe('terminal window PTY survives owner-server teardown (seam 6 / FR4 / D2)expect(cwd).toBe(PROJECT);// 3) The terminal window spawns a live PTY at the inherited cwd.- const { mgr, forked, dataPushes } = makeTerminalManager();+ const { mgr, forked, dataPushes, runShutdownTimers } = makeTerminalManager();const termWc = makeWebContents();const created = mgr.create({windowId: TERM_WIN_ID,@@ -272,6 +277,9 @@ describe('terminal window PTY survives owner-server teardown (seam 6 / FR4 / D2)// Sanity: reaping the TERMINAL window (its own close) is what kills its PTY// — proving step 5 was not a no-op because nothing reaps anything.mgr.killForWindow(TERM_WIN_ID);+ expect(host.posted.at(-1)).toEqual({ type: 'shutdown' });+ expect(host.killed).toBe(false);+ runShutdownTimers();expect(host.killed).toBe(true);});});diff --git a/packages/desktop/tests/main/window-manager.test.ts b/packages/desktop/tests/main/window-manager.test.tsindex 0330d5a91..36ad6081f 100644--- a/packages/desktop/tests/main/window-manager.test.ts+++ b/packages/desktop/tests/main/window-manager.test.ts@@ -610,14 +610,13 @@ describe('WindowManager', () => {expect(wm.closeProjectWindow('/tmp/never-opened')).toBe(false);});- test('closeProjectWindow swallows postMessage errors (utility already exited)', async () => {+ test('closeProjectWindow swallows postMessage errors', async () => {const wm = new WindowManager(env.deps);const p = wm.createProjectWindow({ projectPath: '/tmp/detached-port' });env.utilities[0]?.fire({ type: 'ready', port: 51099, apiOrigin: 'http://localhost:51099' });await p;- // Simulate the utility having already exited — postMessage throws- // (ERR_IPC_CHANNEL_CLOSED in production).+ // Inject a transport failure at the utilityProcess boundary.const utility = env.utilities[0];if (!utility) throw new Error('utility missing');utility.postMessage = vi.fn(() => {diff --git a/packages/desktop/tests/main/windows-update-survivor-sweep-process-list.test.ts b/packages/desktop/tests/main/windows-update-survivor-sweep-process-list.test.tsnew file mode 100644index 000000000..62a19c6ef--- /dev/null+++ b/packages/desktop/tests/main/windows-update-survivor-sweep-process-list.test.ts@@ -0,0 +1,200 @@+import { execFileSync } from 'node:child_process';+import { beforeEach, describe, expect, test, vi } from 'vitest';+import { sweepWindowsUpdateSurvivors } from '../../src/main/windows-update-survivor-sweep.ts';++/**+ * Coverage for the PowerShell JSON the sweep actually parses. Every case in+ * `windows-update-survivor-sweep.test.ts` injects already-typed `listProcesses`+ * values, so the parse — the boundary where another process's bytes become+ * typed records — never runs there. These tests omit the injection so the+ * default path runs, and mock `execFileSync` as the seam: the scan is a+ * synchronous Win32/WMI query that cannot be produced on a non-Windows host.+ *+ * The mock answers the scan and the batched revalidation with the same output,+ * so a record that survives the parse is proven twice and terminated, and a+ * record the parse drops is simply absent from both.+ */+vi.mock('node:child_process', async (importOriginal) => ({+ ...(await importOriginal<typeof import('node:child_process')>()),+ execFileSync: vi.fn(),+}));++const execFileSyncMock = vi.mocked(execFileSync);++const INSTALL_TREE = 'C:\\Program Files\\Open Knowledge\\resources';+const WIN_ENV = { SystemRoot: 'C:\\Windows' };+const BOM = '\uFEFF';++/** One owned console host, as `ConvertTo-Json -Compress` writes it. */+const OWNED_HOST = String.raw`{"processId":101,"name":"OpenConsole.exe","executablePath":"C:\\Program Files\\Open Knowledge\\resources\\node-pty\\OpenConsole.exe","commandLine":null,"creationDate":"2026-08-25T12:00:00.0000000Z"}`;++/** Runs a sweep whose scan and revalidation both read `output`. */+function sweepProcessListOutput(output: string) {+ execFileSyncMock.mockReturnValue(output);+ const terminated: number[] = [];+ const info: Record<string, unknown>[] = [];+ const warnings: Record<string, unknown>[] = [];+ const result = sweepWindowsUpdateSurvivors({+ platform: 'win32',+ env: WIN_ENV,+ installTree: INSTALL_TREE,+ terminateProcess: (pid) => terminated.push(pid),+ logger: { info: (event) => info.push(event), warn: (event) => warnings.push(event) },+ });+ return { result, terminated, info, warnings };+}++beforeEach(() => {+ execFileSyncMock.mockReset();+});++describe('sweepWindowsUpdateSurvivors reading a real PowerShell process list', () => {+ test('terminates the owned host when the output carries a UTF-8 BOM', () => {+ const foreignHost = String.raw`{"processId":201,"name":"conhost.exe","executablePath":"C:\\Windows\\System32\\conhost.exe","commandLine":null,"creationDate":"2026-08-25T12:00:00.0000000Z"}`;++ const { result, terminated } = sweepProcessListOutput(`${BOM}[${OWNED_HOST},${foreignHost}]`);++ expect(terminated).toEqual([101]);+ expect(result).toEqual({+ candidateCount: 1,+ terminatedCount: 1,+ failedCount: 0,+ scanFailed: false,+ revalidationFailed: false,+ });+ });++ test('terminates the owned host from a one-element array', () => {+ const { result, terminated } = sweepProcessListOutput(`[${OWNED_HOST}]`);++ expect(terminated).toEqual([101]);+ expect(result).toEqual({+ candidateCount: 1,+ terminatedCount: 1,+ failedCount: 0,+ scanFailed: false,+ revalidationFailed: false,+ });+ });++ test('revalidates multiple candidates in one PID-filtered query', () => {+ const secondOwnedHost = OWNED_HOST.replace('"processId":101', '"processId":102');++ const { result, terminated } = sweepProcessListOutput(`[${OWNED_HOST},${secondOwnedHost}]`);++ expect(result).toEqual({+ candidateCount: 2,+ terminatedCount: 2,+ failedCount: 0,+ scanFailed: false,+ revalidationFailed: false,+ });+ expect(terminated).toEqual([101, 102]);+ expect(execFileSyncMock).toHaveBeenCalledTimes(2);+ const revalidationArgs = execFileSyncMock.mock.calls[1]?.[1];+ expect(revalidationArgs).toEqual(expect.arrayContaining(['-Command']));+ expect(revalidationArgs?.at(-1)).toContain(+ 'Get-CimInstance Win32_Process -Filter "ProcessId = 101 OR ProcessId = 102"',+ );+ });++ test('skips records with a null or absent creation date and sweeps the rest', () => {+ const nullCreationDate = String.raw`{"processId":102,"name":"OpenConsole.exe","executablePath":"C:\\Program Files\\Open Knowledge\\resources\\node-pty\\OpenConsole.exe","commandLine":null,"creationDate":null}`;+ const noCreationDate = String.raw`{"processId":103,"name":"OpenConsole.exe","executablePath":"C:\\Program Files\\Open Knowledge\\resources\\node-pty\\OpenConsole.exe","commandLine":null}`;++ const { result, terminated, info, warnings } = sweepProcessListOutput(+ `[${OWNED_HOST},${nullCreationDate},${noCreationDate}]`,+ );++ // A host whose creation date the query could not stamp has no identity to+ // re-prove across the scan-to-kill window, so it is left alone. Dropping+ // that one record must not cost the sweep the hosts it can prove.+ expect(terminated).toEqual([101]);+ expect(result).toEqual({+ candidateCount: 1,+ terminatedCount: 1,+ failedCount: 0,+ scanFailed: false,+ revalidationFailed: false,+ });+ expect(info).toContainEqual({+ event: 'windows-update-survivor-sweep',+ candidateCount: 1,+ terminatedCount: 1,+ failedCount: 0,+ scanFailed: false,+ revalidationFailed: false,+ });+ expect(warnings).toEqual([]);+ });++ test('skips malformed records and sweeps the rest', () => {+ const garbage = [+ 'null',+ '"OpenConsole.exe"',+ '42',+ '[]',+ String.raw`{"processId":"104","name":"OpenConsole.exe","executablePath":"C:\\Program Files\\Open Knowledge\\resources\\OpenConsole.exe","commandLine":null,"creationDate":"2026-08-25T12:00:00.0000000Z"}`,+ String.raw`{"processId":0,"name":"OpenConsole.exe","executablePath":"C:\\Program Files\\Open Knowledge\\resources\\OpenConsole.exe","commandLine":null,"creationDate":"2026-08-25T12:00:00.0000000Z"}`,+ String.raw`{"processId":105,"name":42,"executablePath":"C:\\Program Files\\Open Knowledge\\resources\\OpenConsole.exe","commandLine":null,"creationDate":"2026-08-25T12:00:00.0000000Z"}`,+ ].join(',');++ const { result, terminated, warnings } = sweepProcessListOutput(`[${OWNED_HOST},${garbage}]`);++ expect(terminated).toEqual([101]);+ expect(result).toEqual({+ candidateCount: 1,+ terminatedCount: 1,+ failedCount: 0,+ scanFailed: false,+ revalidationFailed: false,+ });+ expect(warnings).toEqual([]);+ });++ test('abandons the sweep when the output is not a JSON array', () => {+ // Without the query's `@()` wrapper PowerShell writes a lone object for a+ // lone match. Guessing a shape for output that broke its own contract would+ // aim `process.kill` at whatever the guess produced, so the scan is failed.+ const { result, terminated, warnings } = sweepProcessListOutput(OWNED_HOST);++ expect(terminated).toEqual([]);+ expect(result).toEqual({+ candidateCount: 0,+ terminatedCount: 0,+ failedCount: 0,+ scanFailed: true,+ revalidationFailed: false,+ });+ expect(warnings).toContainEqual({+ event: 'windows-update-survivor-scan-failed',+ code: 'unknown',+ });+ });++ test('reports a clean no-survivors sweep when the query prints nothing', () => {+ for (const output of ['', '\r\n', `${BOM}\r\n`]) {+ const { result, terminated, info, warnings } = sweepProcessListOutput(output);++ expect(terminated).toEqual([]);+ expect(result).toEqual({+ candidateCount: 0,+ terminatedCount: 0,+ failedCount: 0,+ scanFailed: false,+ revalidationFailed: false,+ });+ // Distinguishes "no console host survived" from the failed scan above,+ // which reports the same counts.+ expect(info).toContainEqual({+ event: 'windows-update-survivor-sweep',+ candidateCount: 0,+ terminatedCount: 0,+ failedCount: 0,+ scanFailed: false,+ revalidationFailed: false,+ });+ expect(warnings).toEqual([]);+ }+ });+});diff --git a/packages/desktop/tests/main/windows-update-survivor-sweep.test.ts b/packages/desktop/tests/main/windows-update-survivor-sweep.test.tsnew file mode 100644index 000000000..d0a3c1d93--- /dev/null+++ b/packages/desktop/tests/main/windows-update-survivor-sweep.test.ts@@ -0,0 +1,349 @@+import { describe, expect, test } from 'vitest';+import { sweepWindowsUpdateSurvivors } from '../../src/main/windows-update-survivor-sweep.ts';++const INSTALL_TREE = 'C:\\Program Files\\Open Knowledge\\resources';+const CREATED = '2026-08-25T12:00:00.0000000Z';++describe('sweepWindowsUpdateSurvivors', () => {+ test('terminates only console hosts owned by the install tree and logs the sweep', () => {+ const terminated: number[] = [];+ const info: Record<string, unknown>[] = [];+ const result = sweepWindowsUpdateSurvivors({+ platform: 'win32',+ installTree: INSTALL_TREE,+ listProcesses: () => [+ {+ processId: 101,+ name: 'OpenConsole.exe',+ executablePath: `${INSTALL_TREE}\\app.asar.unpacked\\node_modules\\node-pty\\OpenConsole.exe`,+ commandLine: null,+ creationDate: CREATED,+ },+ {+ processId: 102,+ name: 'OpenConsole.exe',+ executablePath: null,+ commandLine: `"${INSTALL_TREE}\\node-pty\\OpenConsole.exe" --server`,+ creationDate: CREATED,+ },+ {+ processId: 201,+ name: 'OpenConsole.exe',+ executablePath: 'D:\\Other App\\OpenConsole.exe',+ commandLine: null,+ creationDate: CREATED,+ },+ {+ processId: 202,+ name: 'conhost.exe',+ executablePath: 'C:\\Windows\\System32\\conhost.exe',+ commandLine: `conhost.exe --title "${INSTALL_TREE}\\mentioned-only"`,+ creationDate: CREATED,+ },+ {+ processId: 203,+ name: 'OpenConsole.exe',+ executablePath: `${INSTALL_TREE}-old\\OpenConsole.exe`,+ commandLine: null,+ creationDate: CREATED,+ },+ {+ processId: 204,+ name: 'notepad.exe',+ executablePath: `${INSTALL_TREE}\\notepad.exe`,+ commandLine: null,+ creationDate: CREATED,+ },+ ],+ terminateProcess: (pid) => terminated.push(pid),+ logger: { info: (event) => info.push(event), warn: () => {} },+ });++ expect(terminated).toEqual([101, 102]);+ expect(result).toEqual({+ candidateCount: 2,+ terminatedCount: 2,+ failedCount: 0,+ scanFailed: false,+ revalidationFailed: false,+ });+ expect(info).toContainEqual({+ event: 'windows-update-survivor-sweep',+ candidateCount: 2,+ terminatedCount: 2,+ failedCount: 0,+ scanFailed: false,+ revalidationFailed: false,+ });+ });++ test('logs a no-survivors sweep without attempting termination', () => {+ const terminated: number[] = [];+ const info: Record<string, unknown>[] = [];+ const result = sweepWindowsUpdateSurvivors({+ platform: 'win32',+ installTree: INSTALL_TREE,+ listProcesses: () => [],+ terminateProcess: (pid) => terminated.push(pid),+ logger: { info: (event) => info.push(event), warn: () => {} },+ });++ expect(terminated).toEqual([]);+ expect(result).toEqual({+ candidateCount: 0,+ terminatedCount: 0,+ failedCount: 0,+ scanFailed: false,+ revalidationFailed: false,+ });+ expect(info).toContainEqual({+ event: 'windows-update-survivor-sweep',+ candidateCount: 0,+ terminatedCount: 0,+ failedCount: 0,+ scanFailed: false,+ revalidationFailed: false,+ });+ });++ test('continues after one termination failure and reports the bounded diagnostic', () => {+ const warnings: Record<string, unknown>[] = [];+ const terminated: number[] = [];+ const result = sweepWindowsUpdateSurvivors({+ platform: 'win32',+ installTree: INSTALL_TREE,+ listProcesses: () => [+ {+ processId: 101,+ name: 'OpenConsole.exe',+ executablePath: `${INSTALL_TREE}\\one\\OpenConsole.exe`,+ commandLine: null,+ creationDate: CREATED,+ },+ {+ processId: 102,+ name: 'OpenConsole.exe',+ executablePath: `${INSTALL_TREE}\\two\\OpenConsole.exe`,+ commandLine: null,+ creationDate: CREATED,+ },+ ],+ terminateProcess: (pid) => {+ if (pid === 101) throw Object.assign(new Error('access denied'), { code: 'EPERM' });+ terminated.push(pid);+ },+ logger: { info: () => {}, warn: (event) => warnings.push(event) },+ });++ expect(terminated).toEqual([102]);+ expect(result).toEqual({+ candidateCount: 2,+ terminatedCount: 1,+ failedCount: 1,+ scanFailed: false,+ revalidationFailed: false,+ });+ expect(warnings).toContainEqual({+ event: 'windows-update-survivor-terminate-failed',+ processName: 'openconsole.exe',+ code: 'EPERM',+ });+ expect(warnings).toContainEqual({+ event: 'windows-update-survivor-sweep-incomplete',+ candidateCount: 2,+ terminatedCount: 1,+ failedCount: 1,+ scanFailed: false,+ revalidationFailed: false,+ });+ });++ test('does not terminate a reused PID whose creation identity changed', () => {+ const terminated: number[] = [];+ const warnings: Record<string, unknown>[] = [];+ const candidate = {+ processId: 101,+ name: 'OpenConsole.exe',+ executablePath: `${INSTALL_TREE}\\OpenConsole.exe`,+ commandLine: null,+ creationDate: CREATED,+ };+ const result = sweepWindowsUpdateSurvivors({+ platform: 'win32',+ installTree: INSTALL_TREE,+ listProcesses: () => [candidate],+ revalidateProcesses: () => [+ {+ ...candidate,+ executablePath: 'C:\\Windows\\System32\\notepad.exe',+ creationDate: '2026-08-25T12:00:01.0000000Z',+ },+ ],+ terminateProcess: (pid) => terminated.push(pid),+ logger: { info: () => {}, warn: (event) => warnings.push(event) },+ });++ expect(terminated).toEqual([]);+ expect(result).toEqual({+ candidateCount: 1,+ terminatedCount: 0,+ failedCount: 0,+ scanFailed: false,+ revalidationFailed: false,+ });+ expect(warnings).toContainEqual({+ event: 'windows-update-survivor-identity-changed',+ processName: 'openconsole.exe',+ });+ });++ test('revalidates every candidate with one query however many hosts leaked', () => {+ const sweepLeakedHosts = (survivorCount: number) => {+ const survivors = Array.from({ length: survivorCount }, (_unused, index) => ({+ processId: 101 + index,+ name: 'OpenConsole.exe',+ executablePath: `${INSTALL_TREE}\\pty-${index}\\OpenConsole.exe`,+ commandLine: null,+ creationDate: CREATED,+ }));+ const terminated: number[] = [];+ let queries = 0;+ const result = sweepWindowsUpdateSurvivors({+ platform: 'win32',+ installTree: INSTALL_TREE,+ listProcesses: () => {+ queries += 1;+ return survivors;+ },+ terminateProcess: (pid) => terminated.push(pid),+ });+ return { queries, terminated, result };+ };++ const oneSurvivor = sweepLeakedHosts(1);+ const manySurvivors = sweepLeakedHosts(12);++ expect(oneSurvivor.terminated).toHaveLength(1);+ expect(manySurvivors.terminated).toHaveLength(12);+ expect(manySurvivors.result).toEqual({+ candidateCount: 12,+ terminatedCount: 12,+ failedCount: 0,+ scanFailed: false,+ revalidationFailed: false,+ });+ // The scan plus one batched revalidation, so the main process pays two cold+ // PowerShell starts whether one host leaked or a dozen did.+ expect(oneSurvivor.queries).toBe(2);+ expect(manySurvivors.queries).toBe(oneSurvivor.queries);+ });++ test('terminates only the candidates the batched revalidation still confirms', () => {+ const alive = {+ processId: 101,+ name: 'OpenConsole.exe',+ executablePath: `${INSTALL_TREE}\\alive\\OpenConsole.exe`,+ commandLine: null,+ creationDate: CREATED,+ };+ const exited = { ...alive, processId: 102 };+ const recycled = { ...alive, processId: 103 };+ const terminated: number[] = [];+ const warnings: Record<string, unknown>[] = [];+ let requested: readonly number[] = [];++ const result = sweepWindowsUpdateSurvivors({+ platform: 'win32',+ installTree: INSTALL_TREE,+ listProcesses: () => [alive, exited, recycled],+ revalidateProcesses: (processIds) => {+ requested = processIds;+ return [alive, { ...recycled, creationDate: '2026-08-25T12:00:02.0000000Z' }];+ },+ terminateProcess: (pid) => terminated.push(pid),+ logger: { info: () => {}, warn: (event) => warnings.push(event) },+ });++ expect(requested).toEqual([101, 102, 103]);+ expect(terminated).toEqual([101]);+ expect(result).toEqual({+ candidateCount: 3,+ terminatedCount: 1,+ failedCount: 0,+ scanFailed: false,+ revalidationFailed: false,+ });+ expect(+ warnings.filter((event) => event.event === 'windows-update-survivor-identity-changed'),+ ).toHaveLength(2);+ });++ test('terminates nothing and reports the sweep incomplete when revalidation fails', () => {+ const survivor = {+ processId: 101,+ name: 'OpenConsole.exe',+ executablePath: `${INSTALL_TREE}\\one\\OpenConsole.exe`,+ commandLine: null,+ creationDate: CREATED,+ };+ const terminated: number[] = [];+ const warnings: Record<string, unknown>[] = [];++ const result = sweepWindowsUpdateSurvivors({+ platform: 'win32',+ installTree: INSTALL_TREE,+ listProcesses: () => [survivor, { ...survivor, processId: 102 }],+ revalidateProcesses: () => {+ throw Object.assign(new Error('powershell timed out'), { code: 'ETIMEDOUT' });+ },+ terminateProcess: (pid) => terminated.push(pid),+ logger: { info: () => {}, warn: (event) => warnings.push(event) },+ });++ expect(terminated).toEqual([]);+ expect(result).toEqual({+ candidateCount: 2,+ terminatedCount: 0,+ failedCount: 0,+ scanFailed: false,+ revalidationFailed: true,+ });+ expect(warnings).toContainEqual({+ event: 'windows-update-survivor-revalidate-failed',+ code: 'ETIMEDOUT',+ });+ expect(warnings).toContainEqual({+ event: 'windows-update-survivor-sweep-incomplete',+ candidateCount: 2,+ terminatedCount: 0,+ failedCount: 0,+ scanFailed: false,+ revalidationFailed: true,+ });+ });++ test('is a strict no-op on macOS and Linux', () => {+ for (const platform of ['darwin', 'linux'] as const) {+ let listed = false;+ const result = sweepWindowsUpdateSurvivors({+ platform,+ installTree: INSTALL_TREE,+ listProcesses: () => {+ listed = true;+ return [];+ },+ terminateProcess: () => {+ throw new Error('must not terminate');+ },+ });+ expect(listed).toBe(false);+ expect(result).toEqual({+ candidateCount: 0,+ terminatedCount: 0,+ failedCount: 0,+ scanFailed: false,+ revalidationFailed: false,+ });+ }+ });+});diff --git a/packages/desktop/tests/smoke/_helpers/platform-gate.test.ts b/packages/desktop/tests/smoke/_helpers/platform-gate.test.tsindex 68dea7d85..20868aee5 100644--- a/packages/desktop/tests/smoke/_helpers/platform-gate.test.ts+++ b/packages/desktop/tests/smoke/_helpers/platform-gate.test.ts@@ -614,10 +614,10 @@ describe('deriveGates — predicate bindings', () => {* the check meaningful wherever it runs.*/describe('shared predicates — meaning', () => {- test('the terminal platform set is macOS and Linux', () => {+ test('the terminal platform set is the three desktop targets', () => {expect(isTerminalPlatform('darwin')).toBe(true);expect(isTerminalPlatform('linux')).toBe(true);- expect(isTerminalPlatform('win32')).toBe(false);+ expect(isTerminalPlatform('win32')).toBe(true);});test('the harness-supported platform set is the three desktop targets', () => {diff --git a/packages/desktop/tests/smoke/_helpers/platform-gate.ts b/packages/desktop/tests/smoke/_helpers/platform-gate.tsindex f83c54264..172416dc2 100644--- a/packages/desktop/tests/smoke/_helpers/platform-gate.ts+++ b/packages/desktop/tests/smoke/_helpers/platform-gate.ts@@ -14,9 +14,9 @@* - CROSS-PLATFORM specs gate on {@link PLATFORM_SUPPORTED}. They run on* every OS the harness can drive. A spec belongs here when nothing in it* is macOS-specific.- * - PTY specs gate on {@link PTY_PLATFORM_SUPPORTED}. The terminal ships on- * macOS and Linux; Windows remains outside this capability until its- * ConPTY implementation lands.+ * - PTY specs gate on {@link PTY_PLATFORM_SUPPORTED}. They run on macOS,+ * Linux, and Windows; main separately hides the product below Windows'+ * ConPTY build floor.* - DARWIN-ONLY specs keep their local `DARWIN` constant. A spec belongs* there when it drives a genuinely macOS-only surface: `open(1)` / Apple* Event URL delivery or the darwin chrome stack (vibrancy / hiddenInsetdiff --git a/packages/desktop/tests/smoke/_helpers/terminal-ready.test.ts b/packages/desktop/tests/smoke/_helpers/terminal-ready.test.tsnew file mode 100644index 000000000..ea1121afd--- /dev/null+++ b/packages/desktop/tests/smoke/_helpers/terminal-ready.test.ts@@ -0,0 +1,152 @@+import { describe, expect, test } from 'vitest';+import { waitForShellReady } from './terminal-ready';++describe('terminal smoke shell readiness', () => {+ test('requires evaluated Windows output instead of accepting the echoed probe', async () => {+ let text = '\u001b]0;C:\\Program Files\\PowerShell\\7\\pwsh.exe\u0007';+ const commands: string[] = [];+ const resets: number[] = [];+ let continuationPrompt = false;++ await waitForShellReady(+ () => Promise.resolve(text),+ (command) => {+ commands.push(command);+ if (continuationPrompt) {+ text += `\r\n>> ${command}`;+ } else if (commands.length === 1) {+ text += `\r\n>> ${command}`;+ continuationPrompt = true;+ } else {+ text += `\r\n${command}`;+ text += `\r\n${command.replace(/\$\(\((\d+)\*(\d+)\)\)/u, (_match, left, right) =>+ String(Number(left) * Number(right)),+ )}`;+ }+ return Promise.resolve();+ },+ {+ platform: 'win32',+ interval: 5,+ timeout: 1_000,+ resetTerminalInput: async () => {+ await Promise.resolve();+ resets.push(commands.length);+ continuationPrompt = false;+ },+ },+ );++ expect(commands).toHaveLength(2);+ expect(commands[0]).toBe(commands[1]);+ expect(resets).toEqual([1]);+ });++ test('observes delayed Windows output before cancelling a successful probe', async () => {+ let command = '';+ let readsAfterSend = 0;+ let commandsSent = 0;+ let resets = 0;++ await waitForShellReady(+ () => {+ if (command === '') return Promise.resolve('PowerShell startup');+ readsAfterSend += 1;+ if (readsAfterSend === 1) return Promise.resolve(command);+ return Promise.resolve(+ command.replace(/\$\(\((\d+)\*(\d+)\)\)/u, (_match, left, right) =>+ String(Number(left) * Number(right)),+ ),+ );+ },+ (nextCommand) => {+ commandsSent += 1;+ command = nextCommand;+ return Promise.resolve();+ },+ {+ platform: 'win32',+ interval: 5,+ timeout: 1_000,+ resetTerminalInput: () => {+ resets += 1;+ return Promise.resolve();+ },+ },+ );++ expect(commandsSent).toBe(1);+ expect(resets).toBe(0);+ });++ test('waits for rendered Windows startup output to settle before probing', async () => {+ let text = 'PowerShell starting';+ let reads = 0;+ let commandSentAtRead = 0;++ await waitForShellReady(+ () => {+ reads += 1;+ if (reads === 2) text += ' profile loaded';+ return Promise.resolve(text);+ },+ (command) => {+ commandSentAtRead = reads;+ text += `\r\n${command.replace(/\$\(\((\d+)\*(\d+)\)\)/u, (_match, left, right) =>+ String(Number(left) * Number(right)),+ )}`;+ return Promise.resolve();+ },+ {+ platform: 'win32',+ interval: 5,+ quietPolls: 2,+ timeout: 1_000,+ resetTerminalInput: () => Promise.resolve(),+ },+ );++ // Two reads observe the buffer change, `quietPolls` matching reads clear+ // the gate, then one probe-phase read occurs before the first send.+ expect(commandSentAtRead).toBe(5);+ });++ test('fails loud when a Windows caller omits the line reset', async () => {+ await expect(+ waitForShellReady(+ () => Promise.resolve(''),+ () => Promise.resolve(),+ {+ platform: 'win32',+ },+ ),+ ).rejects.toThrow(/requires resetTerminalInput/u);+ });++ test('retains the quiet-buffer readiness contract on POSIX', async () => {+ let text = 'shell startup';+ let commandsSent = 0;+ const started = Date.now();+ const timer = setTimeout(() => {+ text += ' complete';+ }, 25);++ try {+ await waitForShellReady(+ () => Promise.resolve(text),+ () => {+ commandsSent += 1;+ return Promise.resolve();+ },+ { platform: 'linux', interval: 10, quietPolls: 3, timeout: 2_000 },+ );+ expect(commandsSent).toBe(0);+ expect(text).toContain('complete');+ // The buffer goes quiet, then changes again, so `stable` is positive when+ // the mismatch arrives and a reset that merely held would resolve early.+ expect(Date.now() - started).toBeGreaterThanOrEqual(55);+ } finally {+ clearTimeout(timer);+ }+ });+});diff --git a/packages/desktop/tests/smoke/_helpers/terminal-ready.ts b/packages/desktop/tests/smoke/_helpers/terminal-ready.tsindex 1a2db2802..6cf0956b3 100644--- a/packages/desktop/tests/smoke/_helpers/terminal-ready.ts+++ b/packages/desktop/tests/smoke/_helpers/terminal-ready.ts@@ -1,4 +1,10 @@+import { randomUUID } from 'node:crypto';import { expect } from '@playwright/test';+import { terminalSmokeShellCommands } from './terminal-smoke-shell';++// Reserve most of the default Windows budget for the evaluated input probe;+// startup output settling is only the guard that makes sending that probe safe.+const WINDOWS_SETTLE_TIMEOUT_MS = 10_000;/*** Wait until the shell inside a terminal is ready to READ input.@@ -10,21 +16,83 @@ import { expect } from '@playwright/test';* swallowed, so the row buffer ends up holding a prompt with no echo of the* command, and the caller times out waiting for output that never ran.*- * Readiness is defined as "the buffer has printed something and then stopped- * changing". That is deliberately prompt-shape agnostic: pinning a PS1 pattern- * would break on bash vs zsh vs a themed prompt, and the quiet period is the- * property that actually matters — it is the shell having finished startup.+ * POSIX readiness is a quiet buffer because prompt shapes vary across bash,+ * zsh, and themes. Windows first uses the same quiet-buffer gate so no probe or+ * reset lands while the process is still attaching its console reader. It then+ * avoids prompt matching because prompt shapes are shell- and theme-specific;+ * instead it proves PowerShell evaluated a randomized arithmetic command whose+ * result cannot occur in the echoed input.+ * These fixtures do not pin `terminal.shell`: this probe relies on the product+ * ladder landing on a PowerShell rung. That holds on `windows-latest` because+ * the PowerShell rungs probe absolute paths under `%ProgramFiles%` and+ * `%SystemRoot%` rather than searching PATH, so the restricted test PATH only+ * defeats the `pwsh`-on-PATH rung. A fallthrough to cmd fails this gate closed.+ * Do not copy the packaged ABI probe's deliberate ComSpec pin into these+ * rendered smokes. This typed probe is deliberately renderer-only: xterm+ * answers the device queries PowerShell emits during startup. The raw-PTY+ * harness has no terminal emulator to answer them, so it waits for a structured+ * launch marker without writing into ConPTY during startup.*- * Callers pass their own reader because each terminal smoke test scopes to a- * different section (docked, active, visible).+ * Callers pass their own reader and command sender because each terminal smoke+ * test scopes to a different section (docked, active, visible).*/export async function waitForShellReady(readTerminalText: () => Promise<string>,- { timeout = 30_000, quietPolls = 3, interval = 250 }: WaitForShellReadyOptions = {},+ sendTerminalCommand: (command: string) => Promise<void>,+ {+ timeout = 30_000,+ quietPolls = 3,+ interval = 250,+ platform = process.platform,+ resetTerminalInput,+ }: WaitForShellReadyOptions = {},+): Promise<void> {+ if (platform === 'win32') {+ if (resetTerminalInput === undefined) {+ throw new Error('Windows shell readiness requires resetTerminalInput');+ }+ const startedAt = Date.now();+ await waitForQuietTerminalText(+ readTerminalText,+ Math.min(timeout, WINDOWS_SETTLE_TIMEOUT_MS),+ quietPolls,+ interval,+ );++ const token = `OK_INPUT_READY_${randomUUID().replaceAll('-', '')}`;+ const marker = `${token}_42_READY`;+ const probe = terminalSmokeShellCommands('win32').arithmetic(token, 6, 7, 'READY');+ let attempted = false;+ const remainingTimeout = Math.max(interval, timeout - (Date.now() - startedAt));+ await expect(async () => {+ // Output can arrive after the send callback returns. Observe it before+ // cancelling the line so a slow but successful probe is not interrupted.+ if ((await readTerminalText()).includes(marker)) return;++ // A prior attempt can leave PowerShell at its continuation prompt when+ // only part of the command reached the line editor. Cancel that buffer+ // before retrying so probes do not compound into one malformed command.+ if (attempted) {+ await resetTerminalInput();+ }+ attempted = true;+ await sendTerminalCommand(probe);+ expect(await readTerminalText()).toContain(marker);+ }).toPass({ timeout: remainingTimeout, intervals: [interval] });+ return;+ }++ await waitForQuietTerminalText(readTerminalText, timeout, quietPolls, interval);+}++async function waitForQuietTerminalText(+ readTerminalText: () => Promise<string>,+ timeout: number,+ quietPolls: number,+ interval: number,): Promise<void> {let previous: string | null = null;let stable = 0;-await expect(async () => {const current = (await readTerminalText()).replace(/\s+$/, '');stable = current.length > 0 && current === previous ? stable + 1 : 0;@@ -34,10 +102,14 @@ export async function waitForShellReady(}export interface WaitForShellReadyOptions {- /** Overall budget before the shell is declared unusable. */+ /** Overall budget; Windows shares it between startup settling and its evaluated probe. */timeout?: number;/** Consecutive unchanged reads required to call startup finished. */quietPolls?: number;/** Gap between reads. `quietPolls * interval` is the quiet period. */interval?: number;+ /** Override used by the cross-platform contract tests. */+ platform?: NodeJS.Platform;+ /** Cancel any partial Windows shell line before sending the next probe. */+ resetTerminalInput?: () => Promise<void>;}diff --git a/packages/desktop/tests/smoke/_helpers/terminal-smoke-shell.ts b/packages/desktop/tests/smoke/_helpers/terminal-smoke-shell.tsnew file mode 100644index 000000000..124b7937d--- /dev/null+++ b/packages/desktop/tests/smoke/_helpers/terminal-smoke-shell.ts@@ -0,0 +1,170 @@+import { mkdirSync, 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';++function quotePosix(value: string): string {+ return `'${value.replaceAll("'", "'\\''")}'`;+}++function validateEnvironmentName(name: string): void {+ if (!/^[A-Z_][A-Z0-9_]*$/i.test(name)) {+ throw new Error(`invalid terminal smoke environment name: ${name}`);+ }+}++export interface TerminalSmokeShellCommands {+ readonly cwd: string;+ arithmetic(prefix: string, left: number, right: number, suffix: string): string;+ columns(marker: string): string;+ oscTitle(title: string, marker: string): string;+ output(value: string): string;+ processId(marker: string): string;+ readEnvironment(name: string, label: string): string;+ scroll(sentinel: string, start: string, prefix: string, count: number): string;+ setEnvironment(name: string, value: string): string;+}++/** Commands used by live terminal smokes against either PowerShell or a POSIX shell. */+export function terminalSmokeShellCommands(+ platform: NodeJS.Platform = process.platform,+): TerminalSmokeShellCommands {+ if (platform === 'win32') {+ return {+ cwd: 'Get-Location',+ arithmetic: (prefix, left, right, suffix) =>+ `Write-Output "${prefix}_$((${left}*${right}))_${suffix}"`,+ columns: (marker) => `Write-Output "${marker}=$($Host.UI.RawUI.WindowSize.Width)"`,+ oscTitle: (title, marker) =>+ `[Console]::Write("$([char]27)]0;${title}$([char]7)"); Write-Output ${psQuoteArg(marker)}`,+ output: (value) => `Write-Output ${psQuoteArg(value)}`,+ processId: (marker) => `Write-Output "${marker}=$PID"`,+ readEnvironment: (name, label) => {+ validateEnvironmentName(name);+ return `Write-Output "${label}=[$env:${name}]"`;+ },+ scroll: (sentinel, start, prefix, count) =>+ `Write-Output ${psQuoteArg(sentinel)},${psQuoteArg(start)}; 1..${count} | ForEach-Object { ${psQuoteArg(`${prefix}{0:D3}`)} -f $_ }`,+ setEnvironment: (name, value) => {+ validateEnvironmentName(name);+ return `$env:${name}=${psQuoteArg(value)}`;+ },+ };+ }++ return {+ cwd: 'pwd',+ arithmetic: (prefix, left, right, suffix) => `echo ${prefix}_$((${left}*${right}))_${suffix}`,+ columns: (marker) => `echo ${marker}=$(tput cols)`,+ oscTitle: (title, marker) =>+ `printf '\\033]0;${title}\\007'; printf '%s\\n' ${quotePosix(marker)}`,+ output: (value) => `printf '%s\\n' ${quotePosix(value)}`,+ processId: (marker) => `printf '${marker}=%s\\n' "$$"`,+ readEnvironment: (name, label) => {+ validateEnvironmentName(name);+ return `echo "${label}=[$${name}]"`;+ },+ scroll: (sentinel, start, prefix, count) =>+ `printf '%s\\n' ${quotePosix(sentinel)} ${quotePosix(start)}; i=1; while [ "$i" -le ${count} ]; do printf '${prefix}%03d\\n' "$i"; i=$((i+1)); done`,+ setEnvironment: (name, value) => {+ validateEnvironmentName(name);+ return `export ${name}=${quotePosix(value)}`;+ },+ };+}++interface TerminalSmokeEnvironmentOptions {+ env?: Record<string, string | undefined>;+ pathPrefix?: string;+ pinPosixZsh?: boolean;+ platform?: NodeJS.Platform;+ restrictPath?: boolean;+}++/** Hermetic home/PATH overrides for terminal smoke Electron launches. */+export function terminalSmokeEnvironment(+ tmpHome: string,+ options: TerminalSmokeEnvironmentOptions = {},+): Record<string, string> {+ const platform = options.platform ?? process.platform;+ const env = options.env ?? (process.env as Record<string, string | undefined>);+ const pathKey = windowsPathKey(env);+ let basePath: string;+ if (!options.restrictPath) {+ basePath = getWindowsEnvValue(env, 'PATH') ?? '';+ } else if (platform === 'win32') {+ const systemRoot = getWindowsEnvValue(env, 'SystemRoot') ?? 'C:\\Windows';+ basePath = [+ win32.join(systemRoot, 'System32'),+ systemRoot,+ win32.join(systemRoot, 'System32', 'WindowsPowerShell', 'v1.0'),+ ].join(';');+ } else {+ basePath = POSIX_SYSTEM_PATH;+ }++ const separator = platform === 'win32' ? ';' : ':';+ const path = options.pathPrefix+ ? [options.pathPrefix, basePath].filter(Boolean).join(separator)+ : basePath;+ return {+ HOME: tmpHome,+ ...(platform === 'win32' ? { USERPROFILE: tmpHome } : {}),+ [pathKey]: path,+ ...(options.pinPosixZsh && platform !== 'win32' ? { SHELL: '/bin/zsh' } : {}),+ };+}++interface TerminalShellProfileOptions {+ pathPrefix?: string;+ restrictPath?: boolean;+}++/** Seed zsh startup files without writing POSIX artifacts into Windows profiles. */+export function seedTerminalShellProfiles(+ tmpHome: string,+ options: TerminalShellProfileOptions,+ platform: NodeJS.Platform = process.platform,+): void {+ if (platform === 'win32') return;+ const path = terminalSmokeEnvironment(tmpHome, {+ env: { PATH: process.env.PATH },+ pathPrefix: options.pathPrefix,+ platform,+ restrictPath: options.restrictPath,+ }).PATH;+ const escapedPath = path.replace(/["\\$`]/g, '\\$&');+ const profile = `export PATH="${escapedPath}"\n`;+ writeFileSync(join(tmpHome, '.zprofile'), profile);+ writeFileSync(join(tmpHome, '.zshrc'), profile);+}++export type FakeClaudeMode = 'interactive' | 'version';++/** Write the fake Claude executable in the shape each platform's PATH probe discovers. */+export function writeFakeClaudeShim(+ binDir: string,+ mode: FakeClaudeMode,+ platform: NodeJS.Platform = process.platform,+): string {+ mkdirSync(binDir, { recursive: true });+ if (platform === 'win32') {+ const shim = join(binDir, 'claude.cmd');+ const contents =+ mode === 'interactive'+ ? '@echo off\r\nif /i "%~1"=="--version" (\r\n echo claude 0.0.0-fake\r\n exit /b 0\r\n)\r\necho FAKE_CLAUDE_TUI_READY\r\nmore.com\r\n'+ : '@echo off\r\necho claude 0.0.0-fake\r\n';+ writeFileSync(shim, contents);+ return shim;+ }++ const shim = join(binDir, 'claude');+ const contents =+ mode === 'interactive'+ ? '#!/bin/sh\nif [ "$1" = "--version" ]; then echo "claude 0.0.0-fake"; exit 0; fi\necho FAKE_CLAUDE_TUI_READY\nexec cat\n'+ : '#!/bin/sh\necho "claude 0.0.0-fake"\n';+ writeFileSync(shim, contents, { mode: 0o755 });+ return shim;+}diff --git a/packages/desktop/tests/smoke/_helpers/terminal-tabs.test-helper.test.ts b/packages/desktop/tests/smoke/_helpers/terminal-tabs.test-helper.test.tsnew file mode 100644index 000000000..3f741e486--- /dev/null+++ b/packages/desktop/tests/smoke/_helpers/terminal-tabs.test-helper.test.ts@@ -0,0 +1,15 @@+import { describe, expect, test } from 'vitest';+import { findNewTerminalTabId } from './terminal-tabs.test-helper';++describe('findNewTerminalTabId', () => {+ test('identifies the created tab even when the row order changes', () => {+ expect(findNewTerminalTabId(['tab-1', 'tab-2'], ['tab-3', 'tab-1', 'tab-2'])).toBe('tab-3');+ });++ test('rejects a snapshot that does not contain exactly one new tab', () => {+ expect(() => findNewTerminalTabId(['tab-1'], ['tab-1'])).toThrow(/exactly one new tab/u);+ expect(() => findNewTerminalTabId(['tab-1'], ['tab-1', 'tab-2', 'tab-3'])).toThrow(+ /exactly one new tab/u,+ );+ });+});diff --git a/packages/desktop/tests/smoke/_helpers/terminal-tabs.test-helper.ts b/packages/desktop/tests/smoke/_helpers/terminal-tabs.test-helper.tsnew file mode 100644index 000000000..b37bd1806--- /dev/null+++ b/packages/desktop/tests/smoke/_helpers/terminal-tabs.test-helper.ts@@ -0,0 +1,80 @@+import type { Locator, Page } from '@playwright/test';+import { expect } from './smoke-test';++/**+ * Scope terminal-tab queries to their named tablist. The editor sidebar and+ * Agents panel also render tabs, so whole-page role or row locators are+ * ambiguous. `data-tab-id` is renderer-lifetime identity: rehydration re-mints+ * IDs from the survivor-array index, so assertions across reload or app restart+ * must use labels rather than IDs.+ */+export const terminalTabs = (page: Page): Locator =>+ page.getByRole('tablist', { name: 'Terminal sessions' }).getByRole('tab');++export const terminalTabRow = (page: Page): Locator =>+ page+ .locator('[data-terminal-tab-row]')+ .filter({ has: page.getByRole('tablist', { name: 'Terminal sessions' }) });++export const terminalTabById = (page: Page, id: string): Locator =>+ page+ .getByRole('tablist', { name: 'Terminal sessions' })+ .locator(`[role="tab"][data-tab-id="${id}"]`);++export async function terminalTabIds(page: Page): Promise<string[]> {+ const ids = await terminalTabs(page).evaluateAll((tabs) =>+ tabs.map((tab) => tab.getAttribute('data-tab-id')),+ );+ if (ids.some((id) => id === null)) throw new Error('terminal tab is missing data-tab-id');+ return ids as string[];+}++export function findNewTerminalTabId(+ beforeIds: readonly string[],+ afterIds: readonly string[],+): string {+ const before = new Set(beforeIds);+ const created = afterIds.filter((id) => !before.has(id));+ if (created.length !== 1) {+ throw new Error(+ `expected exactly one new tab; before=${JSON.stringify(beforeIds)} after=${JSON.stringify(afterIds)}`,+ );+ }+ return created[0] as string;+}++/** Create a bare terminal and wait until that new tab, rather than the old+ * running tab, is active before applying the caller's shell-ready gate. */+export async function openBareTerminalTab(+ page: Page,+ waitUntilReady: () => Promise<void>,+ timeout = 25_000,+): Promise<string> {+ const beforeIds = await terminalTabIds(page);+ await page.getByTestId('terminal-new-chat-menu').click();+ await page.getByRole('menuitem', { name: 'Terminal' }).click();+ await expect.poll(() => terminalTabIds(page), { timeout }).toHaveLength(beforeIds.length + 1);++ const createdId = findNewTerminalTabId(beforeIds, await terminalTabIds(page));+ await expect(terminalTabById(page, createdId)).toHaveAttribute('aria-selected', 'true', {+ timeout,+ });+ await waitUntilReady();+ return createdId;+}++export async function renameTerminalTab(page: Page, tab: Locator, label: string): Promise<void> {+ await tab.dblclick();+ const input = page.getByRole('textbox', { name: /^Rename/ });+ await input.fill(label);+ await input.press('Enter');+ await expect(tab).toHaveText(label);+}++export async function expectTerminalTabOrder(+ page: Page,+ expectedIds: readonly string[],+ timeout = 5_000,+): Promise<void> {+ await expect.poll(() => terminalTabIds(page), { timeout }).toEqual(expectedIds);+}diff --git a/packages/desktop/tests/smoke/terminal-dock.e2e.ts b/packages/desktop/tests/smoke/terminal-dock.e2e.tsindex e0a0fd0c7..e4ab16b9e 100644--- a/packages/desktop/tests/smoke/terminal-dock.e2e.ts+++ b/packages/desktop/tests/smoke/terminal-dock.e2e.ts@@ -14,7 +14,6 @@*/import {- chmodSync,existsSync,mkdirSync,mkdtempSync,@@ -24,19 +23,29 @@ import {writeFileSync,} from 'node:fs';import { tmpdir } from 'node:os';-import { join } from 'node:path';+import { basename, join } from 'node:path';import type { ElectronApplication, Locator, Page } from '@playwright/test';import { _electron as electron } from '@playwright/test';import { desktopLaunchOptions, resolveDesktopTarget } from './_helpers/launch-desktop';-import { PTY_PLATFORM_SKIP_REASON, PTY_PLATFORM_SUPPORTED } from './_helpers/platform-gate';+import {+ PTY_PLATFORM_SKIP_REASON,+ PTY_PLATFORM_SUPPORTED,+ userDataDirFor,+} from './_helpers/platform-gate';import { expect, test } from './_helpers/smoke-test';import { waitForShellReady } from './_helpers/terminal-ready';+import {+ seedTerminalShellProfiles,+ terminalSmokeEnvironment,+ terminalSmokeShellCommands,+ writeFakeClaudeShim,+} from './_helpers/terminal-smoke-shell';const TARGET = resolveDesktopTarget();const SMOKE_ENABLED = process.env.OK_DESKTOP_E2E_SMOKE === '1';-const DESKTOP_PRODUCT_NAME = '@inkeep/open-knowledge-desktop';const PRIMARY_MODIFIER = process.platform === 'darwin' ? 'Meta' : 'Control';+const SHELL_COMMANDS = terminalSmokeShellCommands();interface SeedOpts {/** Pre-grant consent by seeding .ok/local/config.yml terminal.enabled: true. */@@ -99,34 +108,28 @@ function seed(prefix: string, opts: SeedOpts = {}): Seed {if (opts.fakeClaudeOnPath || opts.fakeClaudeTui) {const binDir = join(tmpHome, 'fakebin');mkdirSync(binDir, { recursive: true });- const claudeBin = join(binDir, 'claude');- // The TUI variant still answers `--version` and exits (keeps any probe that- // executes the binary from hanging on `cat`).- writeFileSync(- claudeBin,- opts.fakeClaudeTui- ? '#!/bin/sh\nif [ "$1" = "--version" ]; then echo "claude 0.0.0-fake"; exit 0; fi\necho FAKE_CLAUDE_TUI_READY\nexec cat\n'- : '#!/bin/sh\necho "claude 0.0.0-fake"\n',- );- chmodSync(claudeBin, 0o755);+ // The TUI variant still answers `--version` and exits so an executing+ // readiness probe cannot hang on its stdin relay.+ writeFakeClaudeShim(binDir, opts.fakeClaudeTui ? 'interactive' : 'version');pathPrefix = binDir;// The PTY runs `$SHELL -l -i`, whose /etc/zprofile `path_helper` REORDERS// PATH: /etc/paths + /etc/paths.d dirs (incl. /opt/homebrew/bin, where a// real `claude` cask may live) jump AHEAD of the env's fakebin prefix.// Re-prepend fakebin from the test HOME's own rc files — they source after// path_helper, so the fake wins deterministically in probe and PTY alike.- const prepend = `export PATH="${binDir}:$PATH"\n`;- writeFileSync(join(tmpHome, '.zprofile'), prepend);- writeFileSync(join(tmpHome, '.zshrc'), prepend);- } else if (opts.pinRestrictedPath) {+ }+ if (pathPrefix || opts.pinRestrictedPath) {// No fakebin: pin the bare system PATH after path_helper so a host-machine// claude (e.g. the /opt/homebrew/bin cask) cannot leak into the probe.- const pin = 'export PATH="/usr/bin:/bin:/usr/sbin:/sbin"\n';- writeFileSync(join(tmpHome, '.zprofile'), pin);- writeFileSync(join(tmpHome, '.zshrc'), pin);+ // On Windows the probe reads the process PATH directly, so no POSIX startup+ // files are written into the temporary profile.+ seedTerminalShellProfiles(tmpHome, {+ ...(pathPrefix ? { pathPrefix } : {}),+ restrictPath: opts.pinRestrictedPath,+ });}- const userDataDir = join(tmpHome, 'Library', 'Application Support', DESKTOP_PRODUCT_NAME);+ const userDataDir = userDataDirFor(tmpHome);mkdirSync(userDataDir, { recursive: true });if (!opts.skipRestoreState) {writeFileSync(@@ -154,11 +157,6 @@ interface LaunchOpts {async function launchApp(s: Seed, opts: LaunchOpts = {}): Promise<ElectronApplication> {const deepLink = `openknowledge://open?project=${encodeURIComponent(s.projectDir)}&doc=start`;- // A clean, system-only PATH so the readiness probe's `command -v claude`- // verdict is determined solely by the test's fakebin (not the dev's- // ~/.local/bin). The fake-claude prefix, when present, is prepended.- const basePath = opts.restrictPath ? '/usr/bin:/bin:/usr/sbin:/sbin' : (process.env.PATH ?? '');- const PATH = s.pathPrefix ? `${s.pathPrefix}:${basePath}` : basePath;return electron.launch(desktopLaunchOptions({target: TARGET,@@ -170,8 +168,10 @@ async function launchApp(s: Seed, opts: LaunchOpts = {}): Promise<ElectronApplictimeout: 30_000,env: {...process.env,- HOME: s.tmpHome,- PATH,+ ...terminalSmokeEnvironment(s.tmpHome, {+ ...(s.pathPrefix ? { pathPrefix: s.pathPrefix } : {}),+ restrictPath: opts.restrictPath,+ }),OK_DESKTOP_E2E_SMOKE: '1',OK_RECLAIM_DISABLE: '1',},@@ -462,13 +462,24 @@ async function waitForTerminalWidthStable(page: Page): Promise<void> {await page.waitForTimeout(500);}-async function waitForStatus(page: Page, status: string, timeoutMs = 20_000): Promise<void> {+async function waitForStatus(+ page: Page,+ status: string,+ timeoutMs = 20_000,+ { foreground = 'shell' }: { foreground?: 'shell' | 'program' } = {},+): Promise<void> {await expect(terminalStatus(page)).toHaveAttribute('data-terminal-status', status, {timeout: timeoutMs,});// `running` means the PTY spawned, not that the shell has reached its read// loop. Typing before it does swallows the keystrokes.- if (status === 'running') await waitForShellReady(() => readTerminalText(page));+ if (status === 'running' && foreground === 'shell') {+ await waitForShellReady(+ () => readTerminalText(page),+ (command) => typeInTerminal(page, `${command}\r`),+ { resetTerminalInput: () => page.keyboard.press('Control+C') },+ );+ }}/** Wait for the bottom terminal panel. The terminal owns the bottom edge outright@@ -787,7 +798,7 @@ test.describe('Docked terminal — live Electron', () => {).toBeGreaterThan(739);await waitForStatus(page, 'running', 25_000);- await typeInTerminal(page, 'echo RAIL_COLS=$(tput cols)\r');+ await typeInTerminal(page, `${SHELL_COMMANDS.columns('RAIL_COLS')}\r`);await expect.poll(() => readTerminalText(page), { timeout: 15_000 }).toMatch(/RAIL_COLS=\d+/);const columns = (await readTerminalText(page)).match(/RAIL_COLS=(\d+)/)?.[1];expect(Number(columns)).toBeGreaterThanOrEqual(92);@@ -813,9 +824,12 @@ test.describe('Docked terminal — live Electron', () => {await expectCollapsedRailColumn(page, '#terminal-column');});- // The menu-to-mount path stays responsive; the 150ms visual transition is- // cosmetic and is not part of this assertion.- test('QA-022 toggle mounts within 2 seconds', async ({ captureStderrFor }) => {+ // Keep separate bounds on the immediate dock response and the gated live+ // panel. The latter includes project-config sync, capability admission, and+ // the lazy xterm chunk; its 15s ceiling matches the suite's reveal helper.+ test('QA-022 toggle reveals the dock within 2 seconds and mounts within 15 seconds', async ({+ captureStderrFor,+ }) => {const s = seed('perf', { consent: true });track(s.tmpHome, s.projectDir);const app = await launchApp(s);@@ -833,16 +847,25 @@ test.describe('Docked terminal — live Electron', () => {// `page` is handed over so the non-darwin dispatch path does not re-discover// the editor window on the clock. That rediscovery is harness cost, and it// is why this budget read ~400ms higher on Linux than on macOS.- await clickViewTerminalItem(app, page);- // The section becomes present synchronously on the state flip.+ expect(await clickViewTerminalItem(app, page)).toBe('Show Terminal');+ await page.waitForSelector('#terminal-dock-panel', {+ state: 'visible',+ timeout: 5_000,+ });+ const dockElapsed = await page.evaluate((start) => performance.now() - start, t0);+ // IPC round-trip (menu→main→renderer), state flip, and the first non-zero+ // frame of the dock expansion stay inside the interaction budget.+ expect(dockElapsed).toBeLessThan(2000);++ const mountBudgetMs = 15_000;await page.waitForSelector('section[aria-label="Terminal"]', {state: 'attached',- timeout: 5_000,+ // Liveness is deliberately looser than the performance budget so an+ // over-budget mount reaches the assertion with its actual elapsed time.+ timeout: mountBudgetMs * 2,});- const elapsed = await page.evaluate((start) => performance.now() - start, t0);- // Generous ceiling: IPC round-trip (menu→main→renderer) + synchronous flip.- // The visual transition (150ms) is cosmetic; we measure mount, not animation.- expect(elapsed).toBeLessThan(2000);+ const mountElapsed = await page.evaluate((start) => performance.now() - start, t0);+ expect(mountElapsed).toBeLessThan(mountBudgetMs);});// Terminal opens at the project root and runs an arbitrary command.@@ -855,11 +878,11 @@ test.describe('Docked terminal — live Electron', () => {await openTerminal(app, page);await waitForStatus(page, 'running', 25_000);- await typeInTerminal(page, 'pwd\r');- const tail = s.realProjectDir.split('/').slice(-1)[0];+ await typeInTerminal(page, `${SHELL_COMMANDS.cwd}\r`);+ const tail = basename(s.realProjectDir);await expect.poll(() => readTerminalText(page), { timeout: 15_000 }).toContain(tail);- await typeInTerminal(page, 'echo OK_E2E_MARKER_123\r');+ await typeInTerminal(page, `${SHELL_COMMANDS.output('OK_E2E_MARKER_123')}\r`);await expect.poll(() => readTerminalText(page), { timeout: 15_000 }).toContain('OK_E2E_MARKER_123');@@ -884,7 +907,7 @@ test.describe('Docked terminal — live Electron', () => {await openTerminal(app, page);await waitForStatus(page, 'running', 25_000);- await typeInTerminal(page, 'echo BEFORE_COLS=$(tput cols)\r');+ await typeInTerminal(page, `${SHELL_COMMANDS.columns('BEFORE_COLS')}\r`);await expect.poll(() => readTerminalText(page), { timeout: 15_000 }).toMatch(/BEFORE_COLS=\d+/);const before = (await readTerminalText(page)).match(/BEFORE_COLS=(\d+)/)?.[1];@@ -916,7 +939,7 @@ test.describe('Docked terminal — live Electron', () => {// winsize settled back to the pre-storm width — the trailing throttled// resize landed. Polled: the trailing PTY resize lands within ~100ms of// the last step, but the storm's queued SIGWINCH redraws drain async.- await typeInTerminal(page, 'echo AFTER_COLS=$(tput cols)\r');+ await typeInTerminal(page, `${SHELL_COMMANDS.columns('AFTER_COLS')}\r`);await expect.poll(() => readTerminalText(page), { timeout: 15_000 }).toMatch(/AFTER_COLS=\d+/);const beforeColumns = Number(before);expect(beforeColumns).toBeGreaterThan(0);@@ -1172,7 +1195,7 @@ test.describe('Docked terminal — live Electron', () => {// Restart spawns a fresh PTY at the same cwd.await restart.click();await waitForStatus(page, 'running', 25_000);- await typeInTerminal(page, 'echo RESTARTED_OK\r');+ await typeInTerminal(page, `${SHELL_COMMANDS.output('RESTARTED_OK')}\r`);await expect.poll(() => readTerminalText(page), { timeout: 10_000 }).toContain('RESTARTED_OK');});@@ -1282,7 +1305,14 @@ test.describe('Docked terminal — live Electron', () => {// Mark the live shell's process state so we can prove the SAME shell survives:// an env var set here lives only in this exact PTY process, so a fresh spawn// after the reload would not carry it.- await typeInTerminal(page, 'export OK_RELOAD_MARKER=OKRELOAD_SURVIVED_351\r');+ await typeInTerminal(+ page,+ `${SHELL_COMMANDS.setEnvironment('OK_RELOAD_MARKER', 'OKRELOAD_SURVIVED_351')}\r`,+ );+ await typeInTerminal(page, `${SHELL_COMMANDS.readEnvironment('OK_RELOAD_MARKER', 'before')}\r`);+ await expect+ .poll(() => readTerminalText(page), { timeout: 15_000 })+ .toContain('before=[OKRELOAD_SURVIVED_351]');// The bug trigger: reload the renderer page. Main and the per-window PTY host// are untouched (a reload emits neither 'closed' nor 'will-quit'); only the@@ -1300,7 +1330,7 @@ test.describe('Docked terminal — live Electron', () => {// unexpanded `$OK_RELOAD_MARKER`, so the literal value can appear in the// rendered output only when the live shell expanded it — a fresh shell prints// an empty value.- await typeInTerminal(page, 'echo "marker=[$OK_RELOAD_MARKER]"\r');+ await typeInTerminal(page, `${SHELL_COMMANDS.readEnvironment('OK_RELOAD_MARKER', 'marker')}\r`);await expect.poll(() => readTerminalText(page), { timeout: 15_000 }).toContain('marker=[OKRELOAD_SURVIVED_351]');@@ -1346,7 +1376,9 @@ test.describe('Docked terminal — live Electron', () => {// The editor mounts before the CRDT doc body arrives — select-all on the// empty doc publishes an empty snapshot, so wait for the seeded text first.await expect(editor).toContainText('Seed document', { timeout: 30_000 });- await editor.click();+ // This case owns keyboard selection rather than pointer hit testing; the+ // assertion below independently proves focus and Select All reached the doc.+ await editor.focus();await page.keyboard.press(`${PRIMARY_MODIFIER}+a`);await expect.poll(() => page.evaluate(() => String(window.getSelection() ?? '')))@@ -1358,7 +1390,7 @@ test.describe('Docked terminal — live Electron', () => {// input once the PTY is live.await page.keyboard.press(`${PRIMARY_MODIFIER}+Shift+j`);await expect(terminalSection(page)).toBeVisible({ timeout: 15_000 });- await waitForStatus(page, 'running', 25_000);+ await waitForStatus(page, 'running', 25_000, { foreground: 'program' });// The staged bytes reached the CLI's PTY: the composed prompt names the doc// and carries the selected passage verbatim (short selections inline).await expect.poll(() => readTerminalText(page), { timeout: 20_000 }).toContain('start.md');@@ -1370,7 +1402,8 @@ test.describe('Docked terminal — live Electron', () => {// CmdOrCtrl+J route via its View-menu accelerator item (the real menu→IPC→renderer// chain; raw OS key capture is not synthesizable from Playwright). A live// selection must not change the toggle contract or leak into the PTY.- await editor.click();+ // Refocus directly because the selection bubble can cover the editor's hit target.+ await editor.focus();await page.keyboard.press(`${PRIMARY_MODIFIER}+a`);await page.keyboard.type('Reuse marker OKSTAGE_REUSE_742 body');await waitForMenuSelectionState(page, false);@@ -1386,7 +1419,7 @@ test.describe('Docked terminal — live Electron', () => {expect(await clickViewTerminalItem(app)).toBe('Show Terminal');await expect(terminalSection(page)).toBeVisible();- await waitForStatus(page, 'running', 25_000);+ await waitForStatus(page, 'running', 25_000, { foreground: 'program' });expect(await terminalTabs().count()).toBe(tabsAfterLaunch);expect(await readTerminalText(page)).toContain('Seed document');expect(await readTerminalText(page)).not.toContain('OKSTAGE_REUSE_742');diff --git a/packages/desktop/tests/smoke/terminal-links.e2e.ts b/packages/desktop/tests/smoke/terminal-links.e2e.tsindex 3db6357b7..3ca648e60 100644--- a/packages/desktop/tests/smoke/terminal-links.e2e.ts+++ b/packages/desktop/tests/smoke/terminal-links.e2e.ts@@ -16,25 +16,37 @@* (out/main/index.js).*/-import { chmodSync, mkdirSync, mkdtempSync, realpathSync, rmSync, writeFileSync } from 'node:fs';+import { mkdirSync, mkdtempSync, realpathSync, writeFileSync } from 'node:fs';import { tmpdir } from 'node:os';import { join } from 'node:path';import type { ElectronApplication, Page } from '@playwright/test';import { _electron as electron } from '@playwright/test';+import { removeTempDirBestEffort } from '../support/temp-dir-cleanup.test-helper';import { desktopLaunchOptions, resolveDesktopTarget } from './_helpers/launch-desktop';-import { PTY_PLATFORM_SKIP_REASON, PTY_PLATFORM_SUPPORTED } from './_helpers/platform-gate';+import {+ PTY_PLATFORM_SKIP_REASON,+ PTY_PLATFORM_SUPPORTED,+ userDataDirFor,+} from './_helpers/platform-gate';import { expect, test } from './_helpers/smoke-test';import { waitForShellReady } from './_helpers/terminal-ready';+import {+ seedTerminalShellProfiles,+ terminalSmokeEnvironment,+ terminalSmokeShellCommands,+ writeFakeClaudeShim,+} from './_helpers/terminal-smoke-shell';const TARGET = resolveDesktopTarget();const SMOKE_ENABLED = process.env.OK_DESKTOP_E2E_SMOKE === '1';-const DESKTOP_PRODUCT_NAME = '@inkeep/open-knowledge-desktop';+const SHELL_COMMANDS = terminalSmokeShellCommands();interface Seed {tmpHome: string;projectDir: string;pathPrefix: string;+ userDataDir: string;}/** Seed a consented project with a `notes.md` doc for the file-path case. */@@ -50,11 +62,10 @@ function seed(prefix: string): Seed {// A fake `claude` on PATH so the readiness probe resolves deterministically// (mirrors the sibling terminal smokes; the banner isn't under test here).const binDir = join(tmpHome, 'fakebin');- mkdirSync(binDir, { recursive: true });- writeFileSync(join(binDir, 'claude'), '#!/bin/sh\necho "claude 0.0.0-fake"\n');- chmodSync(join(binDir, 'claude'), 0o755);+ writeFakeClaudeShim(binDir, 'version');+ seedTerminalShellProfiles(tmpHome, { pathPrefix: binDir });- const userDataDir = join(tmpHome, 'Library', 'Application Support', DESKTOP_PRODUCT_NAME);+ const userDataDir = userDataDirFor(tmpHome);mkdirSync(userDataDir, { recursive: true });writeFileSync(join(userDataDir, 'state.json'),@@ -70,7 +81,7 @@ function seed(prefix: string): Seed {}),);- return { tmpHome, projectDir, pathPrefix: binDir };+ return { tmpHome, projectDir, pathPrefix: binDir, userDataDir };}async function launchApp(s: Seed): Promise<ElectronApplication> {@@ -78,15 +89,11 @@ async function launchApp(s: Seed): Promise<ElectronApplication> {return electron.launch(desktopLaunchOptions({target: TARGET,- args: [- `--user-data-dir=${join(s.tmpHome, 'Library', 'Application Support', DESKTOP_PRODUCT_NAME)}`,- deepLink,- ],+ args: [`--user-data-dir=${s.userDataDir}`, deepLink],timeout: 30_000,env: {...process.env,- HOME: s.tmpHome,- PATH: `${s.pathPrefix}:${process.env.PATH ?? ''}`,+ ...terminalSmokeEnvironment(s.tmpHome, { pathPrefix: s.pathPrefix }),OK_DESKTOP_E2E_SMOKE: '1',OK_RECLAIM_DISABLE: '1',},@@ -134,16 +141,22 @@ async function openRunningTerminal(app: ElectronApplication, page: Page): Promis);// `running` means the PTY spawned, not that the shell has reached its read// loop. Typing before it does swallows the keystrokes.- await waitForShellReady(() =>- page.locator('section[aria-label="Terminal"] .xterm-rows').innerText(),+ await waitForShellReady(+ () => page.locator('section[aria-label="Terminal"] .xterm-rows').innerText(),+ (command) => typeTerminalCommand(page, command),+ { resetTerminalInput: () => page.keyboard.press('Control+C') },);}-/** Run a command in the focused xterm and wait for `marker` to render. */-async function runInTerminal(page: Page, command: string, marker: string): Promise<void> {+async function typeTerminalCommand(page: Page, command: string): Promise<void> {await page.locator('section[aria-label="Terminal"] .xterm').click();await page.keyboard.type(command);await page.keyboard.press('Enter');+}++/** Run a command in the focused xterm and wait for `marker` to render. */+async function runInTerminal(page: Page, command: string, marker: string): Promise<void> {+ await typeTerminalCommand(page, command);// The command echoes + its output prints; wait for the marker to appear in the// rendered rows (DOM renderer under OK_DESKTOP_E2E_SMOKE=1).await expect(page.locator('section[aria-label="Terminal"] .xterm-rows')).toContainText(marker, {@@ -204,7 +217,7 @@ test.describe('Terminal clickable links — live Electron', () => {test.skip(!PTY_PLATFORM_SUPPORTED, PTY_PLATFORM_SKIP_REASON);test.skip(!TARGET.exists, TARGET.missingReason);test.afterAll(() => {- for (const p of cleanup.splice(0)) rmSync(p, { recursive: true, force: true });+ for (const p of cleanup.splice(0)) removeTempDirBestEffort(p);});// Quarantined: these two have been failing in CI since before the readiness@@ -228,7 +241,7 @@ test.describe('Terminal clickable links — live Electron', () => {await openRunningTerminal(app, page);const url = 'https://ok-smoke.example/link';- await runInTerminal(page, `echo ${url}`, 'ok-smoke.example');+ await runInTerminal(page, SHELL_COMMANDS.output(url), 'ok-smoke.example');// The click has to be inside the retry, not before it. Coordinates come from// the span's box, and an xterm repaint between measuring and clicking leaves@@ -251,7 +264,7 @@ test.describe('Terminal clickable links — live Electron', () => {const page = await findEditorWindow(app);await openRunningTerminal(app, page);- await runInTerminal(page, 'echo notes.md', 'notes.md');+ await runInTerminal(page, SHELL_COMMANDS.output('notes.md'), 'notes.md');// The doc link routes an in-editor hash navigation to `notes`. Click inside// the retry for the same reason as the URL case above — a repaint betweendiff --git a/packages/desktop/tests/smoke/terminal-movement.e2e.ts b/packages/desktop/tests/smoke/terminal-movement.e2e.tsindex 75858e3ef..118566c85 100644--- a/packages/desktop/tests/smoke/terminal-movement.e2e.ts+++ b/packages/desktop/tests/smoke/terminal-movement.e2e.ts@@ -5,14 +5,31 @@ import { join } from 'node:path';import type { ElectronApplication, ElementHandle, Page } from '@playwright/test';import { _electron as electron } from '@playwright/test';import { desktopLaunchOptions, resolveDesktopTarget } from './_helpers/launch-desktop';-import { PTY_PLATFORM_SKIP_REASON, PTY_PLATFORM_SUPPORTED } from './_helpers/platform-gate';+import {+ PTY_PLATFORM_SKIP_REASON,+ PTY_PLATFORM_SUPPORTED,+ userDataDirFor,+} from './_helpers/platform-gate';import { expect, test } from './_helpers/smoke-test';import { waitForShellReady } from './_helpers/terminal-ready';+import {+ seedTerminalShellProfiles,+ terminalSmokeEnvironment,+ terminalSmokeShellCommands,+} from './_helpers/terminal-smoke-shell';+import {+ expectTerminalTabOrder,+ openBareTerminalTab,+ renameTerminalTab,+ terminalTabById,+ terminalTabIds,+ terminalTabs,+} from './_helpers/terminal-tabs.test-helper';const TARGET = resolveDesktopTarget();const SMOKE_ENABLED = process.env.OK_DESKTOP_E2E_SMOKE === '1';-const DESKTOP_PRODUCT_NAME = '@inkeep/open-knowledge-desktop';const PRIMARY_MODIFIER = process.platform === 'darwin' ? 'Meta' : 'Control';+const SHELL_COMMANDS = terminalSmokeShellCommands();type TerminalHome = 'bottom' | 'right';@@ -29,10 +46,9 @@ 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');- writeFileSync(join(tmpHome, '.zprofile'), 'export PATH="/usr/bin:/bin:/usr/sbin:/sbin"\n');- writeFileSync(join(tmpHome, '.zshrc'), 'export PATH="/usr/bin:/bin:/usr/sbin:/sbin"\n');+ seedTerminalShellProfiles(tmpHome, { restrictPath: true });- const userDataDir = join(tmpHome, 'Library', 'Application Support', DESKTOP_PRODUCT_NAME);+ const userDataDir = userDataDirFor(tmpHome);mkdirSync(userDataDir, { recursive: true });if (!skipRestoreState) {writeFileSync(@@ -66,9 +82,10 @@ async function launchApp(s: Seed): Promise<ElectronApplication> {timeout: 30_000,env: {...process.env,- HOME: s.tmpHome,- PATH: '/usr/bin:/bin:/usr/sbin:/sbin',- SHELL: '/bin/zsh',+ ...terminalSmokeEnvironment(s.tmpHome, {+ restrictPath: true,+ pinPosixZsh: true,+ }),OK_DESKTOP_E2E_SMOKE: '1',OK_RECLAIM_DISABLE: '1',},@@ -189,8 +206,6 @@ async function clickTerminalPlacementItemRapidly(}const visibleTerminal = (page: Page) => page.locator('section[aria-label="Terminal"]:visible');-const terminalTabs = (page: Page) =>- page.getByRole('tablist', { name: 'Terminal sessions' }).getByRole('tab');/*** Widen the editor window and PROVE the width stuck.@@ -264,20 +279,26 @@ async function openTerminal(app: ElectronApplication, page: Page): Promise<void>);// `running` means the PTY spawned, not that the shell has reached its read// loop. Typing before it does swallows the keystrokes.- await waitForShellReady(() => readActiveTerminal(page));+ await waitForShellReady(+ () => readActiveTerminal(page),+ (command) => typeInActiveTerminal(page, `${command}\r`),+ { resetTerminalInput: () => page.keyboard.press('Control+C') },+ );}async function openBareTab(page: Page): Promise<void> {- await page.getByTestId('terminal-new-chat-menu').click();- await page.getByRole('menuitem', { name: 'Terminal' }).click();- await expect(visibleTerminal(page).locator('[data-terminal-status]')).toHaveAttribute(- 'data-terminal-status',- 'running',- { timeout: 25_000 },- );- // `running` means the PTY spawned, not that the shell has reached its read- // loop. Typing before it does swallows the keystrokes.- await waitForShellReady(() => readActiveTerminal(page));+ await openBareTerminalTab(page, async () => {+ await expect(visibleTerminal(page).locator('[data-terminal-status]')).toHaveAttribute(+ 'data-terminal-status',+ 'running',+ { timeout: 25_000 },+ );+ await waitForShellReady(+ () => readActiveTerminal(page),+ (command) => typeInActiveTerminal(page, `${command}\r`),+ { resetTerminalInput: () => page.keyboard.press('Control+C') },+ );+ });}async function typeInActiveTerminal(page: Page, text: string): Promise<void> {@@ -336,11 +357,12 @@ async function readActiveTerminal(page: Page): Promise<string> {** `Shift+PageUp` is animated too — `scrollPages` reaches the same viewport the* wheel does — so this does not escape the animation, it stops racing it. Each- * press asks for one page rather than the wheel's several, the loop re-reads- * between presses, and paging past the top is inert, so the presses converge on- * the top instead of overshooting a target still being interpolated toward. The- * ceiling is several times the pages either home needs to cross this fixture's- * scrollback, so it bounds a stuck loop rather than the travel.+ * press asks for one page rather than the wheel's several, then two animation+ * frames let xterm advance before the loop samples and presses again. Paging+ * past the top is inert, so the presses converge on the top instead of repeatedly+ * retargeting from a position that has not painted yet. The ceiling is several+ * times the pages either home needs to cross this fixture's scrollback, so it+ * bounds a stuck loop rather than the travel.*/async function expectScrollbackRetains(page: Page, ...markers: string[]): Promise<void> {// Focus the node xterm actually reads keys from. Clicking the row grid would@@ -352,6 +374,12 @@ async function expectScrollbackRetains(page: Page, ...markers: string[]): Promislet text = await readTerminalRows(page);for (let step = 0; step < 40 && !markers.every((marker) => text.includes(marker)); step += 1) {await page.keyboard.press('Shift+PageUp');+ await page.evaluate(+ () =>+ new Promise<void>((resolve) =>+ requestAnimationFrame(() => requestAnimationFrame(() => resolve())),+ ),+ );text = await readTerminalRows(page);}for (const marker of markers) {@@ -502,7 +530,7 @@ async function expectTerminalMovedNotRebuilt(* Which reader any given site wants is set out on `readTerminalRows`.*/async function readShellPid(page: Page, marker: string): Promise<number> {- await typeInActiveTerminal(page, `printf '${marker}=%s\\n' "$$"\r`);+ await typeInActiveTerminal(page, `${SHELL_COMMANDS.processId(marker)}\r`);let processId = 0;await expect.poll(@@ -584,12 +612,13 @@ test.describe('Terminal placement continuity — live Electron', () => {await widenEditorWindow(app, page, 1900, 900);await openTerminal(app, page);+ const [firstTabId] = await terminalTabIds(page);+ if (firstTabId === undefined) throw new Error('first terminal tab was not created');await openBareTab(page);- await expect(terminalTabs(page)).toHaveText(['Terminal 1', 'Terminal 2']);- await expect(page.getByRole('tab', { name: 'Terminal 2' })).toHaveAttribute(- 'aria-selected',- 'true',- );+ const [, secondTabId] = await terminalTabIds(page);+ if (secondTabId === undefined) throw new Error('second terminal tab was not created');+ await expectTerminalTabOrder(page, [firstTabId, secondTabId]);+ await expect(terminalTabById(page, secondTabId)).toHaveAttribute('aria-selected', 'true');const token = randomUUID().replaceAll('-', '');const processMarker = `PROCESS_${token}`;@@ -598,7 +627,7 @@ test.describe('Terminal placement continuity — live Electron', () => {const processId = await readShellPid(page, processMarker);await typeInActiveTerminal(page,- `printf '${sentinel}\\n${scrollStart}\\n'; i=1; while [ "$i" -le 120 ]; do printf 'SCROLL_${token}_%03d\\n' "$i"; i=$((i+1)); done\r`,+ `${SHELL_COMMANDS.scroll(sentinel, scrollStart, `SCROLL_${token}_`, 120)}\r`,);await expect.poll(() => readActiveTerminal(page), { timeout: 15_000 })@@ -609,11 +638,8 @@ test.describe('Terminal placement continuity — live Electron', () => {await moveTerminal(app, page, 'right');await expectTerminalMovedNotRebuilt(liveSurface, 'right');await expectStillScrolledBack(page, `SCROLL_${token}_120`);- await expect(terminalTabs(page)).toHaveText(['Terminal 1', 'Terminal 2']);- await expect(page.getByRole('tab', { name: 'Terminal 2' })).toHaveAttribute(- 'aria-selected',- 'true',- );+ await expectTerminalTabOrder(page, [firstTabId, secondTabId]);+ await expect(terminalTabById(page, secondTabId)).toHaveAttribute('aria-selected', 'true');// Content retention across the GROW, not reach: the view enters this move// at the top of the buffer, and growing 15 rows to 52 leaves almost nothing// above it for a broken restore to swallow. The shrink leg below is where@@ -621,7 +647,7 @@ test.describe('Terminal placement continuity — live Electron', () => {await expectScrollbackRetains(page, sentinel, scrollStart);expect(await readShellPid(page, processMarker)).toBe(processId);const rightOutput = `RIGHT_OUTPUT_${token}`;- await typeInActiveTerminal(page, `printf '${rightOutput}\\n'\r`);+ await typeInActiveTerminal(page, `${SHELL_COMMANDS.output(rightOutput)}\r`);await expect.poll(() => readActiveTerminal(page), { timeout: 15_000 }).toContain(rightOutput);// The shrink is the leg that can lose reach: 52 rows down to 15 anchors the@@ -631,15 +657,12 @@ test.describe('Terminal placement continuity — live Electron', () => {await moveTerminal(app, page, 'bottom');await expectTerminalMovedNotRebuilt(liveSurface, 'bottom');await expectStillScrolledBack(page, `SCROLL_${token}_120`);- await expect(terminalTabs(page)).toHaveText(['Terminal 1', 'Terminal 2']);- await expect(page.getByRole('tab', { name: 'Terminal 2' })).toHaveAttribute(- 'aria-selected',- 'true',- );+ await expectTerminalTabOrder(page, [firstTabId, secondTabId]);+ await expect(terminalTabById(page, secondTabId)).toHaveAttribute('aria-selected', 'true');await expectScrollbackRetains(page, sentinel, scrollStart);expect(await readShellPid(page, processMarker)).toBe(processId);const bottomOutput = `BOTTOM_OUTPUT_${token}`;- await typeInActiveTerminal(page, `printf '${bottomOutput}\\n'\r`);+ await typeInActiveTerminal(page, `${SHELL_COMMANDS.output(bottomOutput)}\r`);await expect.poll(() => readActiveTerminal(page), { timeout: 15_000 }).toContain(bottomOutput);const rapidSettlement = waitForTerminalHome(page, 'right');@@ -652,14 +675,11 @@ test.describe('Terminal placement continuity — live Electron', () => {await expect(page.locator('#terminal-dock-panel section[aria-label="Terminal"]')).toHaveCount(0,);- await expect(terminalTabs(page)).toHaveText(['Terminal 1', 'Terminal 2']);- await expect(page.getByRole('tab', { name: 'Terminal 2' })).toHaveAttribute(- 'aria-selected',- 'true',- );+ await expectTerminalTabOrder(page, [firstTabId, secondTabId]);+ await expect(terminalTabById(page, secondTabId)).toHaveAttribute('aria-selected', 'true');expect(await readShellPid(page, processMarker)).toBe(processId);const rapidOutput = `RAPID_OUTPUT_${token}`;- await typeInActiveTerminal(page, `printf '${rapidOutput}\\n'\r`);+ await typeInActiveTerminal(page, `${SHELL_COMMANDS.output(rapidOutput)}\r`);await expect.poll(() => readActiveTerminal(page), { timeout: 15_000 }).toContain(rapidOutput);await expectScrollbackRetains(page, sentinel, scrollStart);});@@ -678,12 +698,25 @@ test.describe('Terminal placement continuity — live Electron', () => {await widenEditorWindow(app, page, 1900, 900);await openTerminal(app, page);+ const [firstTabId] = await terminalTabIds(page);+ if (firstTabId === undefined) throw new Error('first terminal tab was not created');await openBareTab(page);+ const [, secondTabId] = await terminalTabIds(page);+ if (secondTabId === undefined) throw new Error('second terminal tab was not created');+ await renameTerminalTab(page, terminalTabById(page, firstTabId), 'restart first');+ // Preserve the default-ordinal reload assertion where shell titles are+ // stable; ConPTY can replace it with an OSC title on Windows.+ const secondLabel = process.platform === 'win32' ? 'restart second' : 'Terminal 2';+ if (process.platform === 'win32') {+ await renameTerminalTab(page, terminalTabById(page, secondTabId), secondLabel);+ }+ await terminalTabById(page, secondTabId).click();+ await expect(terminalTabById(page, secondTabId)).toHaveAttribute('aria-selected', 'true');const token = randomUUID().replaceAll('-', '');const processMarker = `RESTART_PROCESS_${token}`;const processId = await readShellPid(page, processMarker);const beforeRestart = `BEFORE_RESTART_${token}`;- await typeInActiveTerminal(page, `printf '${beforeRestart}\\n'\r`);+ await typeInActiveTerminal(page, `${SHELL_COMMANDS.output(beforeRestart)}\r`);await expect.poll(() => readActiveTerminal(page), { timeout: 15_000 }).toContain(beforeRestart);// This test owns restart persistence; the dedicated terminal-tabs smoke@@ -691,11 +724,8 @@ test.describe('Terminal placement continuity — live Electron', () => {// setup independent of right-column overlay geometry.await visibleTerminal(page).locator('.xterm').click();await page.keyboard.press(`${PRIMARY_MODIFIER}+Shift+ArrowLeft`);- await expect(terminalTabs(page)).toHaveText(['Terminal 2', 'Terminal 1']);- await expect(page.getByRole('tab', { name: 'Terminal 2' })).toHaveAttribute(- 'aria-selected',- 'true',- );+ await expectTerminalTabOrder(page, [secondTabId, firstTabId]);+ await expect(terminalTabById(page, secondTabId)).toHaveAttribute('aria-selected', 'true');await moveTerminal(app, page, 'right');const restoredWidth = await growRightTerminal(page, 120);@@ -716,8 +746,10 @@ test.describe('Terminal placement continuity — live Electron', () => {await expect(page.locator('#terminal-column')).toBeVisible({ timeout: 20_000 });await expect(page.locator('#terminal-dock-panel')).toHaveCount(0);- await expect(terminalTabs(page)).toHaveText(['Terminal 2', 'Terminal 1'], { timeout: 25_000 });- await expect(page.getByRole('tab', { name: 'Terminal 2' })).toHaveAttribute(+ await expect(terminalTabs(page)).toHaveText([secondLabel, 'restart first'], {+ timeout: 25_000,+ });+ await expect(page.getByRole('tab', { name: secondLabel })).toHaveAttribute('aria-selected','true',);@@ -731,7 +763,7 @@ test.describe('Terminal placement continuity — live Electron', () => {.toBeLessThan(20);expect(await readShellPid(page, processMarker)).toBe(processId);const afterRestart = `AFTER_RESTART_${token}`;- await typeInActiveTerminal(page, `printf '${afterRestart}\\n'\r`);+ await typeInActiveTerminal(page, `${SHELL_COMMANDS.output(afterRestart)}\r`);await expect.poll(() => readActiveTerminal(page), { timeout: 15_000 }).toContain(afterRestart);await clickViewAgentsItem(app);@@ -754,6 +786,13 @@ test.describe('Terminal placement continuity — live Electron', () => {await expect(page.locator('#terminal-column')).toBeVisible({ timeout: 20_000 });await expectCollapsedRailColumn(page, '#agents-column');await expect(page.getByText('Agent panel closed to keep Terminal readable.')).toBeVisible();+ await editorWindow.evaluate((windowHandle: unknown) => {+ const target = windowHandle as {+ setSize: (width: number, height: number, animate: boolean) => void;+ };+ target.setSize(1900, 900, false);+ });+ await expect(visibleTerminal(page).locator('.xterm')).toBeVisible({ timeout: 10_000 });expect(await readShellPid(page, processMarker)).toBe(processId);});@@ -794,7 +833,7 @@ test.describe('Terminal placement continuity — live Electron', () => {});expect(await readShellPid(page, processMarker)).toBe(processId);const output = `AFTER_MALFORMED_RESTART_${token}`;- await typeInActiveTerminal(page, `printf '${output}\\n'\r`);+ await typeInActiveTerminal(page, `${SHELL_COMMANDS.output(output)}\r`);await expect.poll(() => readActiveTerminal(page), { timeout: 15_000 }).toContain(output);});});diff --git a/packages/desktop/tests/smoke/terminal-process-restart.e2e.ts b/packages/desktop/tests/smoke/terminal-process-restart.e2e.tsindex 2217d625d..92068eced 100644--- a/packages/desktop/tests/smoke/terminal-process-restart.e2e.ts+++ b/packages/desktop/tests/smoke/terminal-process-restart.e2e.ts@@ -5,12 +5,27 @@ import { join } from 'node:path';import type { ElectronApplication, Page } from '@playwright/test';import { _electron as electron } from '@playwright/test';import { desktopLaunchOptions, resolveDesktopTarget } from './_helpers/launch-desktop';-import { PTY_PLATFORM_SKIP_REASON, PTY_PLATFORM_SUPPORTED } from './_helpers/platform-gate';+import {+ PTY_PLATFORM_SKIP_REASON,+ PTY_PLATFORM_SUPPORTED,+ userDataDirFor,+} from './_helpers/platform-gate';import { expect, test } from './_helpers/smoke-test';+import {+ seedTerminalShellProfiles,+ terminalSmokeEnvironment,+} from './_helpers/terminal-smoke-shell';+import {+ expectTerminalTabOrder,+ openBareTerminalTab,+ renameTerminalTab,+ terminalTabById,+ terminalTabIds,+ terminalTabs,+} from './_helpers/terminal-tabs.test-helper';const TARGET = resolveDesktopTarget();const ENABLED = process.env.OK_DESKTOP_E2E_SMOKE === '1';-const DESKTOP_PRODUCT_NAME = '@inkeep/open-knowledge-desktop';const PRIMARY_MODIFIER = process.platform === 'darwin' ? 'Meta' : 'Control';interface RestartSeed {@@ -26,9 +41,8 @@ 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');- writeFileSync(join(tmpHome, '.zprofile'), 'export PATH="/usr/bin:/bin:/usr/sbin:/sbin"\n');- writeFileSync(join(tmpHome, '.zshrc'), 'export PATH="/usr/bin:/bin:/usr/sbin:/sbin"\n');- const userDataDir = join(tmpHome, 'Library', 'Application Support', DESKTOP_PRODUCT_NAME);+ seedTerminalShellProfiles(tmpHome, { restrictPath: true });+ const userDataDir = userDataDirFor(tmpHome);mkdirSync(userDataDir, { recursive: true });writeFileSync(join(userDataDir, 'state.json'),@@ -54,9 +68,10 @@ async function launchRestartProfile(seed: RestartSeed): Promise<ElectronApplicatargs: [`--user-data-dir=${seed.userDataDir}`, deepLink],env: {...process.env,- HOME: seed.tmpHome,- PATH: '/usr/bin:/bin:/usr/sbin:/sbin',- SHELL: '/bin/zsh',+ ...terminalSmokeEnvironment(seed.tmpHome, {+ restrictPath: true,+ pinPosixZsh: true,+ }),OK_DESKTOP_E2E_SMOKE: '1',OK_RECLAIM_DISABLE: '1',},@@ -115,9 +130,6 @@ async function dispatchRendererMenuAction(}, action);}-const terminalTabs = (page: Page) =>- page.getByRole('tablist', { name: 'Terminal sessions' }).getByRole('tab');-async function openTerminal(page: Page): Promise<void> {const terminal = page.locator('section[aria-label="Terminal"]:visible');await expect(async () => {@@ -134,9 +146,11 @@ async function openTerminal(page: Page): Promise<void> {}async function openBareTab(page: Page): Promise<void> {- await page.getByTestId('terminal-new-chat-menu').click();- await page.getByRole('menuitem', { name: 'Terminal' }).click();- await expect(terminalTabs(page)).toHaveCount(2, { timeout: 25_000 });+ await openBareTerminalTab(page, async () => {+ await expect(+ page.locator('section[aria-label="Terminal"]:visible [data-terminal-status]'),+ ).toHaveAttribute('data-terminal-status', 'running', { timeout: 25_000 });+ });}async function applyPersistedRightTerminalWidth(page: Page, width: number): Promise<number> {@@ -190,24 +204,39 @@ test.describe('terminal process restart', () => {const firstPage = await findEditorWindow(firstApp);await setWindowSize(firstApp, firstPage, 1900, 900);await openTerminal(firstPage);+ const [firstTabId] = await terminalTabIds(firstPage);+ if (firstTabId === undefined) throw new Error('first terminal tab was not created');await openBareTab(firstPage);+ const [, secondTabId] = await terminalTabIds(firstPage);+ if (secondTabId === undefined) throw new Error('second terminal tab was not created');+ await renameTerminalTab(firstPage, terminalTabById(firstPage, firstTabId), 'process first');+ // The default label pins ordinal persistence on POSIX. ConPTY can replace+ // default labels with OSC titles, so Windows needs a durable custom label.+ const secondLabel = process.platform === 'win32' ? 'process second' : 'Terminal 2';+ if (process.platform === 'win32') {+ await renameTerminalTab(firstPage, terminalTabById(firstPage, secondTabId), secondLabel);+ }+ await terminalTabById(firstPage, secondTabId).click();+ await expect(terminalTabById(firstPage, secondTabId)).toHaveAttribute('aria-selected', 'true');// This test owns process-restart persistence; the dedicated terminal-tabs// smoke owns pointer-drag behavior. Reordering in the bottom dock keeps// this setup independent of right-column overlay geometry.await firstPage.locator('section[aria-label="Terminal"]:visible .xterm').click();await firstPage.keyboard.press(`${PRIMARY_MODIFIER}+Shift+ArrowLeft`);- await expect(terminalTabs(firstPage)).toHaveText(['Terminal 2', 'Terminal 1']);- await expect(firstPage.getByRole('tab', { name: 'Terminal 2' })).toHaveAttribute(+ await expectTerminalTabOrder(firstPage, [secondTabId, firstTabId]);+ await expect(terminalTabById(firstPage, secondTabId)).toHaveAttribute('aria-selected', 'true');+ await dispatchRendererMenuAction(firstPage, 'move-terminal');+ await expect(firstPage.locator('#terminal-column')).toBeVisible({ timeout: 10_000 });+ await expect(terminalTabs(firstPage)).toHaveText([secondLabel, 'process first']);+ await expect(firstPage.getByRole('tab', { name: secondLabel })).toHaveAttribute('aria-selected','true',);- await dispatchRendererMenuAction(firstPage, 'move-terminal');- await expect(firstPage.locator('#terminal-column')).toBeVisible({ timeout: 10_000 });// Pointer-drag behavior has its own live smoke. Here a deterministic// persisted width isolates the cross-process contract this test owns.const retainedWidth = await applyPersistedRightTerminalWidth(firstPage, 860);- await expect(terminalTabs(firstPage)).toHaveText(['Terminal 2', 'Terminal 1']);- await expect(firstPage.getByRole('tab', { name: 'Terminal 2' })).toHaveAttribute(+ await expect(terminalTabs(firstPage)).toHaveText([secondLabel, 'process first']);+ await expect(firstPage.getByRole('tab', { name: secondLabel })).toHaveAttribute('aria-selected','true',);@@ -219,10 +248,10 @@ test.describe('terminal process restart', () => {await setWindowSize(secondApp, secondPage, 1900, 900);await expect(secondPage.locator('#terminal-column')).toBeVisible({ timeout: 25_000 });await expect(secondPage.locator('#terminal-dock-panel')).toHaveCount(0);- await expect(terminalTabs(secondPage)).toHaveText(['Terminal 2', 'Terminal 1'], {+ await expect(terminalTabs(secondPage)).toHaveText([secondLabel, 'process first'], {timeout: 25_000,});- await expect(secondPage.getByRole('tab', { name: 'Terminal 2' })).toHaveAttribute(+ await expect(secondPage.getByRole('tab', { name: secondLabel })).toHaveAttribute('aria-selected','true',);diff --git a/packages/desktop/tests/smoke/terminal-tabs.e2e.ts b/packages/desktop/tests/smoke/terminal-tabs.e2e.tsindex 7ca6da8a2..97c17e0ac 100644--- a/packages/desktop/tests/smoke/terminal-tabs.e2e.ts+++ b/packages/desktop/tests/smoke/terminal-tabs.e2e.ts@@ -27,18 +27,36 @@import { mkdirSync, mkdtempSync, realpathSync, rmSync, writeFileSync } from 'node:fs';import { tmpdir } from 'node:os';import { join } from 'node:path';-import type { ElectronApplication, Page } from '@playwright/test';+import type { ElectronApplication, Locator, Page } from '@playwright/test';import { _electron as electron } from '@playwright/test';import { desktopLaunchOptions, resolveDesktopTarget } from './_helpers/launch-desktop';-import { PTY_PLATFORM_SKIP_REASON, PTY_PLATFORM_SUPPORTED } from './_helpers/platform-gate';+import {+ PTY_PLATFORM_SKIP_REASON,+ PTY_PLATFORM_SUPPORTED,+ userDataDirFor,+} from './_helpers/platform-gate';import { expect, test } from './_helpers/smoke-test';import { waitForShellReady } from './_helpers/terminal-ready';+import {+ seedTerminalShellProfiles,+ terminalSmokeEnvironment,+ terminalSmokeShellCommands,+} from './_helpers/terminal-smoke-shell';+import {+ expectTerminalTabOrder,+ openBareTerminalTab,+ renameTerminalTab,+ terminalTabById,+ terminalTabIds,+ terminalTabRow,+ terminalTabs,+} from './_helpers/terminal-tabs.test-helper';const TARGET = resolveDesktopTarget();const SMOKE_ENABLED = process.env.OK_DESKTOP_E2E_SMOKE === '1';-const DESKTOP_PRODUCT_NAME = '@inkeep/open-knowledge-desktop';const PRIMARY_MODIFIER = process.platform === 'darwin' ? 'Meta' : 'Control';+const SHELL_COMMANDS = terminalSmokeShellCommands();interface Seed {tmpHome: string;@@ -54,8 +72,9 @@ function seed(prefix: string): Seed {// Pre-grant terminal consent so the shell spawns without the enable gate.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 });- const userDataDir = join(tmpHome, 'Library', 'Application Support', DESKTOP_PRODUCT_NAME);+ const userDataDir = userDataDirFor(tmpHome);mkdirSync(userDataDir, { recursive: true });writeFileSync(join(userDataDir, 'state.json'),@@ -75,9 +94,6 @@ function seed(prefix: string): Seed {async function launchApp(s: Seed): Promise<ElectronApplication> {const deepLink = `openknowledge://open?project=${encodeURIComponent(s.projectDir)}&doc=start`;- // Restricted, system-only PATH: the New-chat carat opens a BARE shell (the- // "Terminal" pick) so no `claude` install is needed to spawn a live PTY.- const PATH = '/usr/bin:/bin:/usr/sbin:/sbin';return electron.launch(desktopLaunchOptions({target: TARGET,@@ -85,8 +101,9 @@ async function launchApp(s: Seed): Promise<ElectronApplication> {timeout: 30_000,env: {...process.env,- HOME: s.tmpHome,- PATH,+ // Restricted, system-only PATH: the New-chat carat opens a BARE shell+ // so no host `claude` install participates in the fixture.+ ...terminalSmokeEnvironment(s.tmpHome, { restrictPath: true }),OK_DESKTOP_E2E_SMOKE: '1',OK_RECLAIM_DISABLE: '1',},@@ -130,12 +147,6 @@ async function clickViewTerminalItem(app: ElectronApplication): Promise<void> {// unambiguous once a second tab exists (each session mounts its own section +// status via forceMount).const visibleSection = (page: Page) => page.locator('section[aria-label="Terminal"]:visible');-// Scope to the terminal strip's own tablist — the editor sidebar also renders-// role="tab" (Outline / Links / Graph / Timeline), so an unscoped query is-// ambiguous.-const terminalTabs = (page: Page) =>- page.getByRole('tablist', { name: 'Terminal sessions' }).getByRole('tab');-/*** Open the dock and wait for the first session's shell to be running. The live* shell occasionally exits before reaching "running" on constrained hardware@@ -156,7 +167,11 @@ async function openTerminal(app: ElectronApplication, page: Page): Promise<void>{ timeout: 8_000 },);}).toPass({ timeout: 40_000, intervals: [2_000] });- await waitForShellReady(() => readActiveText(page));+ await waitForShellReady(+ () => readActiveText(page),+ (command) => typeInActive(page, `${command}\r`),+ { resetTerminalInput: () => page.keyboard.press('Control+C') },+ );}/**@@ -173,20 +188,22 @@ async function waitActiveRunning(page: Page, timeoutMs = 25_000): Promise<void>'running',{ timeout: timeoutMs },);- await waitForShellReady(() => readActiveText(page));+ await waitForShellReady(+ () => readActiveText(page),+ (command) => typeInActive(page, `${command}\r`),+ { resetTerminalInput: () => page.keyboard.press('Control+C') },+ );}/** Open a second (or further) tab running a BARE shell via the New-chat carat →* "Terminal" pick. The new tab activates; wait for its shell to be running. */async function openBareTab(page: Page): Promise<void> {- await page.getByTestId('terminal-new-chat-menu').click();- await page.getByRole('menuitem', { name: 'Terminal' }).click();- await waitActiveRunning(page);+ await openBareTerminalTab(page, () => waitActiveRunning(page));}-async function activateTab(page: Page, name: string): Promise<void> {- await page.getByRole('tab', { name }).click();- await expect(page.getByRole('tab', { name })).toHaveAttribute('aria-selected', 'true');+async function activateTab(tab: Locator): Promise<void> {+ await tab.click();+ await expect(tab).toHaveAttribute('aria-selected', 'true');}/**@@ -195,10 +212,10 @@ async function activateTab(page: Page, name: string): Promise<void> {* over the target in steps, then release. Used to exercise the pointer path* (the keyboard chord is covered separately).*/-async function dragTabOnto(page: Page, fromName: string, toName: string): Promise<void> {- const from = await page.getByRole('tab', { name: fromName }).boundingBox();- const to = await page.getByRole('tab', { name: toName }).boundingBox();- if (!from || !to) throw new Error(`tab bounding box missing (${fromName} → ${toName})`);+async function dragTabOnto(page: Page, fromTab: Locator, toTab: Locator): Promise<void> {+ const from = await fromTab.boundingBox();+ const to = await toTab.boundingBox();+ if (!from || !to) throw new Error('terminal tab bounding box missing');await page.mouse.move(from.x + from.width / 2, from.y + from.height / 2);await page.mouse.down();// Cross the 8px activation threshold before moving to the target so the drag@@ -253,16 +270,16 @@ test.describe('Terminal tabs — live Electron', () => {await openTerminal(app, page);// Tab 1: write a marker into its shell.- await typeInActive(page, 'echo TAB1_ONLY_AAA\r');+ await typeInActive(page, `${SHELL_COMMANDS.output('TAB1_ONLY_AAA')}\r`);await expect.poll(() => readActiveText(page), { timeout: 15_000 }).toContain('TAB1_ONLY_AAA');// Open a second bare tab — it gets its own PTY and becomes active.await openBareTab(page);- await expect(terminalTabs(page)).toHaveText(['Terminal 1', 'Terminal 2']);+ await expect(terminalTabs(page)).toHaveCount(2);// Tab 2 is a distinct shell: it has never seen tab 1's marker, and its own// marker is independent.- await typeInActive(page, 'echo TAB2_ONLY_BBB\r');+ await typeInActive(page, `${SHELL_COMMANDS.output('TAB2_ONLY_BBB')}\r`);await expect.poll(() => readActiveText(page), { timeout: 15_000 }).toContain('TAB2_ONLY_BBB');expect(await readActiveText(page)).not.toContain('TAB1_ONLY_AAA');});@@ -277,12 +294,17 @@ test.describe('Terminal tabs — live Electron', () => {const page = await findEditorWindow(app);await openTerminal(app, page);await openBareTab(page); // Terminal 1 + Terminal 2+ const [, survivingTabId] = await terminalTabIds(page);+ if (survivingTabId === undefined) throw new Error('second terminal tab was not created');// Close Terminal 1; Terminal 2 remains and its shell is still live.- await page.getByRole('button', { name: 'Close Terminal 1' }).click();- await expect(terminalTabs(page)).toHaveText(['Terminal 2']);+ await terminalTabRow(page)+ .getByRole('button', { name: /^Close / })+ .first()+ .click();+ await expectTerminalTabOrder(page, [survivingTabId]);await waitActiveRunning(page);- await typeInActive(page, 'echo SURVIVOR_CCC\r');+ await typeInActive(page, `${SHELL_COMMANDS.output('SURVIVOR_CCC')}\r`);await expect.poll(() => readActiveText(page), { timeout: 15_000 }).toContain('SURVIVOR_CCC');});@@ -295,7 +317,7 @@ test.describe('Terminal tabs — live Electron', () => {await openTerminal(app, page);// Double-click the tab to rename it, commit with Enter.- await page.getByRole('tab', { name: 'Terminal 1' }).dblclick();+ await terminalTabs(page).first().dblclick();const input = page.getByRole('textbox', { name: /^Rename/ });await input.fill('my build');await input.press('Enter');@@ -309,7 +331,7 @@ test.describe('Terminal tabs — live Electron', () => {// a fixed sleep) is what keeps the pin assertion from passing vacuously — if// the OSC were slow, the challenge simply hasn't landed yet and we keep// polling rather than asserting into an empty window.- await typeInActive(page, "printf '\\033]0;PROGRAM_TITLE_ZZZ\\007'; echo OSC_FED_QQQ\r");+ 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 expect(terminalTabs(page)).toHaveText(['my build']);await expect(page.getByRole('tab', { name: 'PROGRAM_TITLE_ZZZ' })).toHaveCount(0);@@ -328,16 +350,20 @@ test.describe('Terminal tabs — live Electron', () => {// Terminal 1: pin the live shell with an env marker (survives only in THIS// PTY process) and print a scrollback marker (survives only if the xterm is// not reset/cleared by the reorder).- await typeInActive(page, 'export OK_TABMARK=SURVIVED_888\r');- await typeInActive(page, 'echo BEFORE_REORDER_DDD\r');+ await typeInActive(page, `${SHELL_COMMANDS.setEnvironment('OK_TABMARK', 'SURVIVED_888')}\r`);+ await typeInActive(page, `${SHELL_COMMANDS.output('BEFORE_REORDER_DDD')}\r`);await expect.poll(() => readActiveText(page), { timeout: 15_000 }).toContain('BEFORE_REORDER_DDD');// Open a second tab, then re-activate Terminal 1 and focus its shell.+ const [firstTabId] = await terminalTabIds(page);+ if (firstTabId === undefined) throw new Error('first terminal tab was not created');await openBareTab(page);- await expect(terminalTabs(page)).toHaveText(['Terminal 1', 'Terminal 2']);- await activateTab(page, 'Terminal 1');+ const [, secondTabId] = await terminalTabIds(page);+ if (secondTabId === undefined) throw new Error('second terminal tab was not created');+ await expectTerminalTabOrder(page, [firstTabId, secondTabId]);+ await activateTab(terminalTabById(page, firstTabId));await visibleSection(page).locator('.xterm').click();// CmdOrCtrl+Shift+Right moves the active tab (Terminal 1) one slot right.@@ -345,18 +371,21 @@ test.describe('Terminal tabs — live Electron', () => {// Order changed; the sticky numbers rode with their sessions (NOT renumbered// by position).- await expect(terminalTabs(page)).toHaveText(['Terminal 2', 'Terminal 1']);+ await expectTerminalTabOrder(page, [secondTabId, firstTabId]);+ // ConPTY can replace default labels with OSC shell titles on Windows.+ if (process.platform !== 'win32') {+ await expect(terminalTabs(page)).toHaveText(['Terminal 2', 'Terminal 1']);+ }// Terminal 1 is still the active tab and STILL THE SAME LIVE SHELL: the env// marker (same PTY) and the pre-reorder scrollback both survive. On the// pre-fix code the panel's xterm moved in the DOM and the running program// reset — here it is untouched.- await expect(page.getByRole('tab', { name: 'Terminal 1' })).toHaveAttribute(- 'aria-selected',- 'true',- );- expect(await readActiveText(page)).toContain('BEFORE_REORDER_DDD');- await typeInActive(page, 'echo "mk=[$OK_TABMARK]"\r');+ await expect(terminalTabById(page, firstTabId)).toHaveAttribute('aria-selected', 'true');+ await expect+ .poll(() => readActiveText(page), { timeout: 15_000 })+ .toContain('BEFORE_REORDER_DDD');+ await typeInActive(page, `${SHELL_COMMANDS.readEnvironment('OK_TABMARK', 'mk')}\r`);await expect.poll(() => readActiveText(page), { timeout: 15_000 }).toContain('mk=[SURVIVED_888]');@@ -373,30 +402,41 @@ test.describe('Terminal tabs — live Electron', () => {await openTerminal(app, page);// Terminal 1: pin its live shell with an env marker + a scrollback marker.- await typeInActive(page, 'export OK_DRAGMARK=DRAG_SURVIVED_444\r');- await typeInActive(page, 'echo BEFORE_DRAG_EEE\r');+ await typeInActive(+ 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');// Open a second tab, then DRAG Terminal 1 onto Terminal 2 with the pointer.+ const [firstTabId] = await terminalTabIds(page);+ if (firstTabId === undefined) throw new Error('first terminal tab was not created');await openBareTab(page);- await expect(terminalTabs(page)).toHaveText(['Terminal 1', 'Terminal 2']);- await dragTabOnto(page, 'Terminal 1', 'Terminal 2');+ const [, secondTabId] = await terminalTabIds(page);+ if (secondTabId === undefined) throw new Error('second terminal tab was not created');+ await expectTerminalTabOrder(page, [firstTabId, secondTabId]);+ await dragTabOnto(page, terminalTabById(page, firstTabId), terminalTabById(page, secondTabId));// Order changed via the real drag; sticky numbers rode with their sessions.- await expect(terminalTabs(page)).toHaveText(['Terminal 2', 'Terminal 1']);+ await expectTerminalTabOrder(page, [secondTabId, firstTabId]);+ // ConPTY can replace default labels with OSC shell titles on Windows.+ if (process.platform !== 'win32') {+ await expect(terminalTabs(page)).toHaveText(['Terminal 2', 'Terminal 1']);+ }// Terminal 1's shell is the SAME live session (env marker) with intact// scrollback (the pre-drag echo) — a pointer drag must not reset it either.- await activateTab(page, 'Terminal 1');+ await activateTab(terminalTabById(page, firstTabId));await visibleSection(page).locator('.xterm').click();expect(await readActiveText(page)).toContain('BEFORE_DRAG_EEE');- await typeInActive(page, 'echo "dm=[$OK_DRAGMARK]"\r');+ await typeInActive(page, `${SHELL_COMMANDS.readEnvironment('OK_DRAGMARK', 'dm')}\r`);await expect.poll(() => readActiveText(page), { timeout: 15_000 }).toContain('dm=[DRAG_SURVIVED_444]');});- test('a renderer reload preserves custom names and tab order', async ({ captureStderrFor }) => {+ test('a renderer reload preserves tab labels and order', async ({ captureStderrFor }) => {const s = seed('reload-preserve');track(s.tmpHome, s.projectDir);const app = await launchApp(s);@@ -404,22 +444,27 @@ test.describe('Terminal tabs — live Electron', () => {const page = await findEditorWindow(app);await openTerminal(app, page);- // Two tabs: rename Terminal 1 -> "build", then reorder so Terminal 2 leads.+ // Keep one default label on POSIX to cover ordinal rehydration. ConPTY can+ // replace default labels with OSC titles, so Windows uses a durable custom+ // label for the same order assertion.await openBareTab(page);- await expect(terminalTabs(page)).toHaveText(['Terminal 1', 'Terminal 2']);- await page.getByRole('tab', { name: 'Terminal 1' }).dblclick();- const input = page.getByRole('textbox', { name: /^Rename/ });- await input.fill('build');- await input.press('Enter');- await expect(terminalTabs(page)).toHaveText(['build', 'Terminal 2']);- await dragTabOnto(page, 'build', 'Terminal 2');- await expect(terminalTabs(page)).toHaveText(['Terminal 2', 'build']);+ const [firstTabId, secondTabId] = await terminalTabIds(page);+ if (firstTabId === undefined || secondTabId === undefined) {+ throw new Error('two terminal tabs were not created');+ }+ await renameTerminalTab(page, terminalTabById(page, firstTabId), 'build');+ const secondLabel = process.platform === 'win32' ? 'shell' : 'Terminal 2';+ if (process.platform === 'win32') {+ await renameTerminalTab(page, terminalTabById(page, secondTabId), secondLabel);+ }+ await dragTabOnto(page, terminalTabById(page, firstTabId), terminalTabById(page, secondTabId));+ await expectTerminalTabOrder(page, [secondTabId, firstTabId]);// Reload the renderer (⌘R). Main + the per-window PTY host — and the tab name// + order they now retain — survive the reload; the reloaded dock rehydrates// from main rather than resetting to positional creation order (the bug fixed).await page.reload();await expect(visibleSection(page)).toBeVisible({ timeout: 20_000 });- await expect(terminalTabs(page)).toHaveText(['Terminal 2', 'build'], { timeout: 25_000 });+ await expect(terminalTabs(page)).toHaveText([secondLabel, 'build'], { timeout: 25_000 });});});diff --git a/packages/desktop/tests/smoke/terminal-window.e2e.ts b/packages/desktop/tests/smoke/terminal-window.e2e.tsindex ef4fd49cb..cdc25685a 100644--- a/packages/desktop/tests/smoke/terminal-window.e2e.ts+++ b/packages/desktop/tests/smoke/terminal-window.e2e.ts@@ -17,17 +17,26 @@import { mkdirSync, mkdtempSync, realpathSync, rmSync, writeFileSync } from 'node:fs';import { tmpdir } from 'node:os';-import { join } from 'node:path';+import { basename, join } from 'node:path';import type { ElectronApplication, Page } from '@playwright/test';import { _electron as electron } from '@playwright/test';import { desktopLaunchOptions, resolveDesktopTarget } from './_helpers/launch-desktop';-import { PTY_PLATFORM_SKIP_REASON, PTY_PLATFORM_SUPPORTED } from './_helpers/platform-gate';+import {+ PTY_PLATFORM_SKIP_REASON,+ PTY_PLATFORM_SUPPORTED,+ userDataDirFor,+} from './_helpers/platform-gate';import { expect, test } from './_helpers/smoke-test';+import {+ seedTerminalShellProfiles,+ terminalSmokeEnvironment,+ terminalSmokeShellCommands,+} from './_helpers/terminal-smoke-shell';const TARGET = resolveDesktopTarget();const SMOKE_ENABLED = process.env.OK_DESKTOP_E2E_SMOKE === '1';-const DESKTOP_PRODUCT_NAME = '@inkeep/open-knowledge-desktop';+const SHELL_COMMANDS = terminalSmokeShellCommands();interface Seed {tmpHome: string;@@ -43,8 +52,9 @@ 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 });- const userDataDir = join(tmpHome, 'Library', 'Application Support', DESKTOP_PRODUCT_NAME);+ const userDataDir = userDataDirFor(tmpHome);mkdirSync(userDataDir, { recursive: true });writeFileSync(join(userDataDir, 'state.json'),@@ -71,8 +81,7 @@ async function launchApp(s: Seed): Promise<ElectronApplication> {timeout: 30_000,env: {...process.env,- HOME: s.tmpHome,- PATH: '/usr/bin:/bin:/usr/sbin:/sbin',+ ...terminalSmokeEnvironment(s.tmpHome, { restrictPath: true }),OK_DESKTOP_E2E_SMOKE: '1',OK_RECLAIM_DISABLE: '1',},@@ -218,13 +227,13 @@ test.describe('Standalone terminal window — live Electron', () => {'running',{ timeout: 25_000 },);- await expect(term.getByRole('tab', { name: 'Terminal 1' })).toBeVisible();+ await expect(term.getByRole('tab')).toHaveCount(1);// The shell's cwd is the inherited project root (the registry resolution// reaching a real shell).await term.locator('section[aria-label="Terminal"] .xterm').first().click();- await term.keyboard.type('pwd\r');- const tail = s.projectDir.split('/').slice(-1)[0] ?? '';+ await term.keyboard.type(`${SHELL_COMMANDS.cwd}\r`);+ const tail = basename(s.projectDir);await expect.poll(() =>@@ -239,7 +248,7 @@ test.describe('Standalone terminal window — live Electron', () => {.toContain(tail);// Closing the last tab closes the window (it does not collapse a panel).- await term.getByRole('button', { name: 'Close Terminal 1' }).click();+ await term.getByRole('button', { name: /^Close / }).click();await expect.poll(() => terminalWindowCount(app), { timeout: 15_000 }).toBe(0);});diff --git a/packages/desktop/tests/support/pty-readiness.test-helper.ts b/packages/desktop/tests/support/pty-readiness.test-helper.tsnew file mode 100644index 000000000..8629469bf--- /dev/null+++ b/packages/desktop/tests/support/pty-readiness.test-helper.ts@@ -0,0 +1,194 @@+/**+ * Host probe + wait primitives shared by the real-shell PTY harness and its+ * contract tests.+ *+ * `createPtyHostProbe` wraps `setupPtyHost` in a recording `parentPort` and+ * exposes one `PtyStream` per PTY id, so a waiter can see both what the shell+ * has emitted and whether it failed.+ *+ * A PTY carries no "the shell is ready to read input" event. The first bytes a+ * terminal emits are its own setup paint, and on ConPTY that lands well before+ * the shell has attached a console input reader; anything written into that+ * window is dropped rather than buffered the way a POSIX tty's line discipline+ * would. So "some byte arrived" is spawn liveness, not readiness, and a caller+ * that treats it as readiness types into a shell that is not listening.+ * POSIX `waitForShellReady` therefore takes readiness to be "the stream+ * produced output and then stopped changing". The real Windows harness starts+ * each input-driven scenario with a structured launch marker instead: seeing+ * that marker proves PowerShell executed its startup command without injecting+ * an edit or control event into a line editor that may not exist yet.+ *+ * Every wait also watches the stream's failure channel, so a shell that dies or+ * never spawns aborts with its own reason instead of expiring as an anonymous+ * timeout that names only the condition nobody reached.+ */++import {+ type PtyHostIncomingMessage,+ type PtyHostOutgoingMessage,+ type SpawnPty,+ setupPtyHost,+} from '../../src/utility/pty-host.ts';++/** One PTY's observable surface: its bytes, and its failure channel. */+export interface PtyStream {+ /** Everything this PTY has emitted so far. */+ read(): string;+ /** A description of a spawn failure or exit, once one has occurred. */+ failure(): string | null;+}++export interface PtyHostProbe {+ send(message: PtyHostIncomingMessage): void;+ streamOf(ptyId: string): PtyStream;+ dataOf(ptyId: string): string;+ exitOf(ptyId: string): { exitCode: number | undefined; signal: number | null } | null;+ errorOf(ptyId: string): string | null;+ killActive(): void;+}++export interface PtyHostProbeOptions {+ spawn: SpawnPty;+ env: Record<string, string | undefined>;+ platform?: NodeJS.Platform;+ shellExists?: (path: string) => boolean;+}++export function createPtyHostProbe(options: PtyHostProbeOptions): PtyHostProbe {+ let handler: ((event: { data: unknown }) => void) | null = null;+ const data = new Map<string, string>();+ const exits = new Map<string, { exitCode: number | undefined; signal: number | null }>();+ const errors = new Map<string, string>();+ const handle = setupPtyHost({+ parentPort: {+ on(_event, h) {+ handler = h;+ },+ postMessage(msg: PtyHostOutgoingMessage) {+ if (msg.type === 'data') data.set(msg.ptyId, (data.get(msg.ptyId) ?? '') + msg.data);+ else if (msg.type === 'exit')+ exits.set(msg.ptyId, { exitCode: msg.exitCode, signal: msg.signal });+ else if (msg.type === 'spawn-error') errors.set(msg.ptyId, msg.message);+ },+ },+ spawn: options.spawn,+ env: options.env,+ ...(options.platform === undefined ? {} : { platform: options.platform }),+ shellExists: options.shellExists,+ });+ const dataOf = (ptyId: string): string => data.get(ptyId) ?? '';+ const exitOf = (ptyId: string): { exitCode: number | undefined; signal: number | null } | null =>+ exits.get(ptyId) ?? null;+ const errorOf = (ptyId: string): string | null => errors.get(ptyId) ?? null;+ return {+ send: (msg) => handler?.({ data: msg }),+ dataOf,+ exitOf,+ errorOf,+ killActive: () => handle.killActive(),+ streamOf: (ptyId) => ({+ read: () => dataOf(ptyId),+ failure: () => {+ const error = errorOf(ptyId);+ if (error !== null) return `spawn-error: ${error}`;+ const exit = exitOf(ptyId);+ if (exit === null) return null;+ return `exited (code ${exit.exitCode ?? 'none'}, signal ${exit.signal ?? 'none'})`;+ },+ }),+ };+}++export interface WaitOptions {+ /** Budget before the awaited condition is declared unreachable. */+ timeoutMs?: number;+ /** Gap between samples. */+ intervalMs?: number;+}++export interface ShellReadyOptions extends WaitOptions {+ /** Consecutive unchanged samples required to call startup finished. */+ quietSamples?: number;+}++const DEFAULT_INTERVAL_MS = 15;+const DEFAULT_TIMEOUT_MS = 8_000;+const DEFAULT_READY_INTERVAL_MS = 50;+/** 20 samples x 50ms: a quiet window wide enough to span a cold shell's+ * intra-startup stalls (profile load, module JIT) without reading one as the+ * prompt. */+const DEFAULT_QUIET_SAMPLES = 20;+const DEFAULT_READY_TIMEOUT_MS = 12_000;+const RECEIVED_TAIL_CHARS = 400;++const sleep = (ms: number): Promise<void> => new Promise((resolve) => setTimeout(resolve, ms));++/** The tail of what a PTY emitted, so a timeout says what it saw instead of+ * discarding the only evidence that separates a dropped write from a dead+ * shell. */+function describeReceived(text: string): string {+ if (text.length === 0) return 'nothing';+ const tail = text.length > RECEIVED_TAIL_CHARS ? text.slice(-RECEIVED_TAIL_CHARS) : text;+ return `${text.length > RECEIVED_TAIL_CHARS ? '...' : ''}${JSON.stringify(tail)}`;+}++export async function waitForCondition(+ stream: PtyStream,+ predicate: () => boolean,+ label: string,+ options: WaitOptions = {},+): Promise<void> {+ const intervalMs = options.intervalMs ?? DEFAULT_INTERVAL_MS;+ const deadline = Date.now() + (options.timeoutMs ?? DEFAULT_TIMEOUT_MS);+ for (;;) {+ // Predicate before failure: a scenario that awaits an exit is satisfied by+ // the very event the failure channel reports, and must read it as success.+ if (predicate()) return;+ const failure = stream.failure();+ if (failure !== null) {+ throw new Error(`shell failed before ${label}: ${failure}`);+ }+ if (Date.now() >= deadline) {+ throw new Error(+ `timeout waiting for: ${label} (received ${describeReceived(stream.read())})`,+ );+ }+ await sleep(intervalMs);+ }+}++export async function waitForShellReady(+ stream: PtyStream,+ label: string,+ options: ShellReadyOptions = {},+): Promise<void> {+ const quietSamples = options.quietSamples ?? DEFAULT_QUIET_SAMPLES;+ let previous: string | null = null;+ let stable = 0;+ await waitForCondition(+ stream,+ () => {+ const current = stream.read();+ stable = current.length > 0 && current === previous ? stable + 1 : 0;+ previous = current;+ return stable >= quietSamples;+ },+ label,+ {+ timeoutMs: options.timeoutMs ?? DEFAULT_READY_TIMEOUT_MS,+ intervalMs: options.intervalMs ?? DEFAULT_READY_INTERVAL_MS,+ },+ );+}++/** Build a command whose relative file read proves the shell accepted the+ * requested cwd without relying on Windows path spelling or casing. */+export function buildCwdFileProofCommand(platform: NodeJS.Platform, fileName: string): string {+ if (!/^[A-Za-z0-9._-]+$/u.test(fileName) || fileName === '.' || fileName === '..') {+ throw new Error(`invalid cwd proof file name: ${fileName}`);+ }+ if (platform === 'win32') {+ return `Write-Output "CWD_PROOF=$(Get-Content -Raw -LiteralPath './${fileName}')"`;+ }+ return `printf 'CWD_PROOF=%s\\n' "$(cat './${fileName}')"`;+}diff --git a/packages/desktop/tests/support/temp-dir-cleanup.test-helper.ts b/packages/desktop/tests/support/temp-dir-cleanup.test-helper.tsnew file mode 100644index 000000000..e2f5cf4b1--- /dev/null+++ b/packages/desktop/tests/support/temp-dir-cleanup.test-helper.ts@@ -0,0 +1,24 @@+import { rmSync } from 'node:fs';++/**+ * Removes a test-owned OS temp directory without ever throwing.+ *+ * `rmSync`'s `force: true` suppresses only `ENOENT` — a permission error, or a+ * handle the OS still holds, still throws. Directories that hosted a real child+ * process (a node-pty shell, a packaged Electron app) hit that routinely on+ * Windows, which reports `EPERM` for a short window after the child exits+ * because the handle is not released synchronously with process exit.+ *+ * Teardown of such a directory is housekeeping, never a verdict: a throw here+ * would overturn assertions that already passed. Ride out the transient window+ * with bounded retries (`rmSync` retries EBUSY/EMFILE/ENFILE/ENOTEMPTY/EPERM),+ * then give up silently — the path is an OS temp directory and the OS reclaims+ * it.+ */+export function removeTempDirBestEffort(path: string): void {+ try {+ rmSync(path, { recursive: true, force: true, maxRetries: 3, retryDelay: 50 });+ } catch {+ // Best-effort by contract: the caller's verdict must not depend on this.+ }+}diff --git a/packages/desktop/tests/unit/electron-builder-node-pty-deps.test.ts b/packages/desktop/tests/unit/electron-builder-node-pty-deps.test.tsindex f2f195892..a6404ee1e 100644--- a/packages/desktop/tests/unit/electron-builder-node-pty-deps.test.ts+++ b/packages/desktop/tests/unit/electron-builder-node-pty-deps.test.ts@@ -32,6 +32,12 @@ import { parse } from 'yaml';* pins that the call site still exists alongside the unpack rule.* 4. Linux packages retain both ELF addons while excluding foreign-platform* prebuilds and Windows debug symbols.+ * 5. Windows packages retain BOTH win32 PE prebuilds (runtime selects by+ * process.arch) while excluding POSIX prebuilds, .pdb debug symbols, and+ * the build/ + third_party/ source trees; node-pty's lib/ and package.json+ * are asar-unpacked (the ConPTY conout worker runs on a worker thread,+ * which cannot load JS from inside an asar); and the Microsoft-signed+ * conpty.dll + OpenConsole.exe pair is excluded from our signing pass.** The build also stays arm64-only (no universal target) — node-pty would add a* second per-arch native into any universal lipo-merge.@@ -46,6 +52,7 @@ const afterPack = resolve(desktopRoot, 'scripts', 'afterPack.mjs');function readBuilderConfig(): {asarUnpack?: string[];linux?: { files?: string[] };+ win?: { files?: string[]; signExts?: string[] };mac?: { target?: Array<{ target?: string; arch?: string[] }> };} {return parse(readFileSync(builderYml, 'utf8'));@@ -124,6 +131,89 @@ describe('node-pty desktop packaging config', () => {expect(patterns).toContain('!**/node_modules/node-pty/prebuilds/win32-*/**');});+ test('win packages node-pty but excludes foreign prebuilds, debug symbols, and source trees', () => {+ const patterns = readBuilderConfig().win?.files ?? [];+ expect(+ patterns,+ 'The blanket node-pty exclusion is gone for good: the Windows terminal runs on the ' ++ 'win32 ConPTY prebuilds, so the win package must ship node-pty.',+ ).not.toContain('!**/node_modules/node-pty/**');+ expect(patterns).toContain('!**/node_modules/node-pty/prebuilds/**/*.pdb');+ expect(patterns).toContain('!**/node_modules/node-pty/prebuilds/darwin-*/**');+ expect(patterns).toContain('!**/node_modules/node-pty/prebuilds/linux-*/**');+ expect(+ patterns,+ "mac/win builds keep @electron/rebuild enabled and node-pty's node-gyp output under " ++ 'build/ shadows the prebuilds at require() time — without this prune a cross-arch ' ++ 'build ships builder-host binaries.',+ ).toContain('!**/node_modules/node-pty/build/**');+ expect(patterns).toContain('!**/node_modules/node-pty/third_party/**');+ const win32Excludes = patterns.filter(+ (pattern) => pattern.includes('node-pty') && pattern.includes('win32'),+ );+ expect(+ win32Excludes,+ 'BOTH win32 arch prebuilds must ship in BOTH per-arch installers — the addon selects ' ++ 'prebuilds/win32-<process.arch> at runtime, which keeps x64-under-emulation working ' ++ 'on arm64 hosts.',+ ).toEqual([]);+ });++ test.each([+ ['win32-x64', 0x8664],+ ['win32-arm64', 0xaa64],+ ])('%s ships PE conpty addons with the Microsoft ConPTY pair beside them', (platformArch, peMachine) => {+ for (const name of [+ 'conpty.node',+ 'conpty_console_list.node',+ 'conpty/conpty.dll',+ 'conpty/OpenConsole.exe',+ ]) {+ const file = resolve(+ desktopRoot,+ 'node_modules',+ 'node-pty',+ 'prebuilds',+ platformArch,+ name,+ );+ expect(existsSync(file), `node-pty must ship ${platformArch}/${name}`).toBe(true);+ const binary = readFileSync(file);+ expect(binary.readUInt16LE(0), `${platformArch}/${name}: MZ magic`).toBe(0x5a4d);+ const peOffset = binary.readUInt32LE(0x3c);+ expect(binary.readUInt32LE(peOffset), `${platformArch}/${name}: PE signature`).toBe(0x4550);+ expect(binary.readUInt16LE(peOffset + 4), `${platformArch}/${name}: PE machine word`).toBe(+ peMachine,+ );+ }+ });++ test('asarUnpack covers node-pty lib/ and package.json (conout worker runs off the real filesystem)', () => {+ const patterns = readBuilderConfig().asarUnpack ?? [];+ expect(+ patterns,+ "Add '**/node-pty/lib/**' to asarUnpack: node-pty reads ConPTY output on a worker thread " ++ '(lib/worker/conoutSocketWorker.js), and worker_threads cannot load JS from inside an asar.',+ ).toContain('**/node-pty/lib/**');+ expect(+ patterns,+ "Add '**/node-pty/package.json' to asarUnpack: the conout worker's CJS require() resolution " ++ "needs node-pty's package.json on the real filesystem beside the unpacked lib/.",+ ).toContain('**/node-pty/package.json');+ });++ test('win signing excludes the Microsoft-signed OpenConsole.exe (signExts intent)', () => {+ expect(+ readBuilderConfig().win?.signExts,+ 'win.signExts must stay ["!OpenConsole.exe"]: electron-builder signs every packaged .exe by ' ++ "default, and re-signing OpenConsole.exe would replace Microsoft's Authenticode signature " ++ "and split the ConPTY pair's provenance (conpty.dll is safe either way — only .exe files " ++ 'are in the default signing set). MIGRATION NOTE for the electron-builder v27 upgrade: v27 ' ++ 'replaces win.signtoolOptions/azureSignOptions with a win.sign union — re-express this ' ++ 'exclusion under the new win.sign surface when bumping past ^26.',+ ).toEqual(['!OpenConsole.exe']);+ });+test('afterPack makes the unpacked spawn-helper executable (unpack rule + chmod move together)', () => {const src = readFileSync(afterPack, 'utf8');expect(diff --git a/packages/desktop/tests/unit/temp-dir-cleanup.test.ts b/packages/desktop/tests/unit/temp-dir-cleanup.test.tsnew file mode 100644index 000000000..bef5debb1--- /dev/null+++ b/packages/desktop/tests/unit/temp-dir-cleanup.test.ts@@ -0,0 +1,47 @@+import { chmodSync, existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { describe, expect, test } from 'vitest';+import { removeTempDirBestEffort } from '../support/temp-dir-cleanup.test-helper.ts';++describe('removeTempDirBestEffort', () => {+ test('removes a directory and everything under it', () => {+ const dir = mkdtempSync(join(tmpdir(), 'ok-temp-cleanup-'));+ mkdirSync(join(dir, 'nested'));+ writeFileSync(join(dir, 'nested', 'file.txt'), 'content');++ removeTempDirBestEffort(dir);++ expect(existsSync(dir)).toBe(false);+ });++ test('no-ops on a path that is already gone', () => {+ const dir = mkdtempSync(join(tmpdir(), 'ok-temp-cleanup-gone-'));+ rmSync(dir, { recursive: true });++ expect(() => removeTempDirBestEffort(dir)).not.toThrow();+ });++ // The contract that keeps a teardown from overturning a passing verdict. A+ // read-only parent is the POSIX way to make the removal fail: `chmod` on+ // Windows only toggles a read-only attribute and would not block it, and root+ // is not subject to the permission check at all.+ test.skipIf(process.platform === 'win32' || process.getuid?.() === 0)(+ 'swallows a removal the OS refuses',+ () => {+ const root = mkdtempSync(join(tmpdir(), 'ok-temp-cleanup-locked-'));+ const child = join(root, 'child');+ mkdirSync(child);+ writeFileSync(join(child, 'file.txt'), 'content');+ chmodSync(root, 0o555);++ try {+ expect(() => removeTempDirBestEffort(child)).not.toThrow();+ expect(existsSync(child), 'the removal succeeded, so no refusal was exercised').toBe(true);+ } finally {+ chmodSync(root, 0o755);+ rmSync(root, { recursive: true, force: true });+ }+ },+ );+});diff --git a/packages/desktop/tests/unit/terminal-smoke-shell.test.ts b/packages/desktop/tests/unit/terminal-smoke-shell.test.tsnew file mode 100644index 000000000..73a2e8dfb--- /dev/null+++ b/packages/desktop/tests/unit/terminal-smoke-shell.test.ts@@ -0,0 +1,137 @@+import { existsSync, mkdtempSync, readFileSync, rmSync, statSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { afterEach, describe, expect, test } from 'vitest';+import {+ seedTerminalShellProfiles,+ terminalSmokeEnvironment,+ terminalSmokeShellCommands,+ writeFakeClaudeShim,+} from '../smoke/_helpers/terminal-smoke-shell.ts';++const cleanup: string[] = [];++function temporaryDirectory(prefix: string): string {+ const directory = mkdtempSync(join(tmpdir(), prefix));+ cleanup.push(directory);+ return directory;+}++afterEach(() => {+ for (const directory of cleanup.splice(0)) {+ rmSync(directory, { recursive: true, force: true });+ }+});++describe('terminal smoke shell commands', () => {+ test('composes PowerShell commands without POSIX syntax', () => {+ const commands = terminalSmokeShellCommands('win32');++ expect(commands.cwd).toBe('Get-Location');+ expect(commands.arithmetic('HARNESS', 6, 7, 'DONE')).toBe(+ 'Write-Output "HARNESS_$((6*7))_DONE"',+ );+ expect(commands.columns('COLS')).toBe('Write-Output "COLS=$($Host.UI.RawUI.WindowSize.Width)"');+ expect(commands.setEnvironment('OK_MARK', 'survived')).toBe("$env:OK_MARK='survived'");+ expect(commands.readEnvironment('OK_MARK', 'marker')).toBe(+ 'Write-Output "marker=[$env:OK_MARK]"',+ );+ expect(commands.processId('SHELLPID')).toBe('Write-Output "SHELLPID=$PID"');+ expect(commands.oscTitle('program', 'OSC_FED')).toBe(+ '[Console]::Write("$([char]27)]0;program$([char]7)"); Write-Output \'OSC_FED\'',+ );+ expect(commands.scroll('START', 'FIRST', 'ROW_', 3)).toBe(+ "Write-Output 'START','FIRST'; 1..3 | ForEach-Object { 'ROW_{0:D3}' -f $_ }",+ );+ });++ test('keeps the existing POSIX command contracts on macOS and Linux', () => {+ for (const platform of ['darwin', 'linux'] as const) {+ const commands = terminalSmokeShellCommands(platform);+ expect(commands.cwd).toBe('pwd');+ expect(commands.arithmetic('HARNESS', 6, 7, 'DONE')).toBe('echo HARNESS_$((6*7))_DONE');+ expect(commands.columns('COLS')).toBe('echo COLS=$(tput cols)');+ 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\' "$$"');+ }+ });+});++describe('terminal smoke shell fixtures', () => {+ test('uses a hermetic Windows system PATH without adding a POSIX SHELL', () => {+ expect(+ terminalSmokeEnvironment('C:\\fixture-home', {+ platform: 'win32',+ env: { Path: 'C:\\developer-bin', SystemRoot: 'D:\\Windows' },+ pathPrefix: 'C:\\fixture-bin',+ restrictPath: true,+ pinPosixZsh: true,+ }),+ ).toEqual({+ HOME: 'C:\\fixture-home',+ USERPROFILE: 'C:\\fixture-home',+ Path: [+ 'C:\\fixture-bin',+ 'D:\\Windows\\System32',+ 'D:\\Windows',+ 'D:\\Windows\\System32\\WindowsPowerShell\\v1.0',+ ].join(';'),+ });+ });++ test('keeps the POSIX login-shell fixture and delimiter', () => {+ expect(+ terminalSmokeEnvironment('/tmp/fixture-home', {+ platform: 'linux',+ env: { PATH: '/developer/bin' },+ pathPrefix: '/tmp/fixture-bin',+ restrictPath: true,+ pinPosixZsh: true,+ }),+ ).toEqual({+ HOME: '/tmp/fixture-home',+ PATH: '/tmp/fixture-bin:/usr/bin:/bin:/usr/sbin:/sbin',+ SHELL: '/bin/zsh',+ });+ });++ test('writes executable shims for POSIX and PATHEXT-visible shims for Windows', () => {+ const posixBin = temporaryDirectory('ok-terminal-posix-shim-');+ const windowsBin = temporaryDirectory('ok-terminal-windows-shim-');++ const posixPath = writeFakeClaudeShim(posixBin, 'interactive', 'darwin');+ const windowsPath = writeFakeClaudeShim(windowsBin, 'interactive', 'win32');++ expect(posixPath).toBe(join(posixBin, 'claude'));+ expect(statSync(posixPath).mode & 0o111).not.toBe(0);+ expect(readFileSync(posixPath, 'utf8')).toContain('exec cat');+ expect(windowsPath).toBe(join(windowsBin, 'claude.cmd'));+ expect(readFileSync(windowsPath, 'utf8')).toContain('more.com');+ });++ test('writes login profiles only for POSIX shells', () => {+ const posixHome = temporaryDirectory('ok-terminal-posix-home-');+ const windowsHome = temporaryDirectory('ok-terminal-windows-home-');++ seedTerminalShellProfiles(+ posixHome,+ { pathPrefix: '/tmp/fake-bin', restrictPath: true },+ 'linux',+ );+ seedTerminalShellProfiles(+ windowsHome,+ { pathPrefix: 'C:\\fake-bin', restrictPath: true },+ 'win32',+ );++ expect(readFileSync(join(posixHome, '.zprofile'), 'utf8')).toBe(+ 'export PATH="/tmp/fake-bin:/usr/bin:/bin:/usr/sbin:/sbin"\n',+ );+ expect(readFileSync(join(posixHome, '.zshrc'), 'utf8')).toBe(+ 'export PATH="/tmp/fake-bin:/usr/bin:/bin:/usr/sbin:/sbin"\n',+ );+ expect(existsSync(join(windowsHome, '.zprofile'))).toBe(false);+ expect(existsSync(join(windowsHome, '.zshrc'))).toBe(false);+ });+});diff --git a/packages/desktop/tests/unit/windows-package-native-guards.test.ts b/packages/desktop/tests/unit/windows-package-native-guards.test.tsnew file mode 100644index 000000000..292c0259a--- /dev/null+++ b/packages/desktop/tests/unit/windows-package-native-guards.test.ts@@ -0,0 +1,287 @@+import {+ existsSync,+ mkdirSync,+ mkdtempSync,+ readdirSync,+ readFileSync,+ rmSync,+ statSync,+ writeFileSync,+} from 'node:fs';+import { tmpdir } from 'node:os';+import { dirname, join, resolve } from 'node:path';+import { fileURLToPath } from 'node:url';+import { afterEach, describe, expect, test } from 'vitest';+import { MAX_ASAR_HEADER_BYTES, readAsarHeader } from '../../scripts/lib/asar-header.mjs';++/**+ * Two-lane guard for the packaged Windows node-pty payload.+ *+ * Helper lane (always on): unit-tests the PE / walker / asar-header helpers so+ * the assertive lane's oracles are themselves verified on every platform.+ *+ * Assertive lane (OK_WIN_PACKAGE_DIR): points at an electron-builder --win+ * output dir (e.g. dist-desktop/win-unpacked, relative to packages/desktop)+ * and asserts the shipped bytes: both win32 arch prebuilds present (the addon+ * selects prebuilds/win32-<process.arch> at runtime, so each installer must+ * carry both), PE machine words matching each arch dir (the rebuild pass on a+ * cross-arch builder is exactly what would ship wrong-arch binaries), the+ * Microsoft ConPTY pair beside the addons, the conout worker on the real+ * filesystem, and none of the pruned trees — checked in BOTH the unpacked tree+ * and the asar listing, because pruned-but-not-unpacked paths (third_party/,+ * most of build/) would ship invisibly inside the asar.+ *+ * The lane is host-agnostic by design: every assertion is over static file+ * bytes, so a cross-compiled --win output can be checked from any OS.+ */++const __dirname = dirname(fileURLToPath(import.meta.url));+const desktopRoot = resolve(__dirname, '../..');+const packageDirInput = process.env.OK_WIN_PACKAGE_DIR?.trim() ?? '';+const packageDir = packageDirInput === '' ? null : resolve(desktopRoot, packageDirInput);+const packageDirRequired = process.env.OK_WIN_PACKAGE_REQUIRED === '1';++const WIN32_ARCHES = ['win32-x64', 'win32-arm64'] as const;++const PE_MACHINE: Record<(typeof WIN32_ARCHES)[number], number> = {+ 'win32-x64': 0x8664,+ 'win32-arm64': 0xaa64,+};++const CONPTY_FILES = [+ 'conpty.node',+ 'conpty_console_list.node',+ 'conpty/conpty.dll',+ 'conpty/OpenConsole.exe',+] as const;++function peMachineType(binary: Buffer): number {+ if (binary.length < 0x40 || binary.readUInt16LE(0) !== 0x5a4d) {+ throw new Error('not a PE image: missing MZ magic');+ }+ const peOffset = binary.readUInt32LE(0x3c);+ if (peOffset + 6 > binary.length || binary.readUInt32LE(peOffset) !== 0x4550) {+ throw new Error('not a PE image: missing PE signature');+ }+ return binary.readUInt16LE(peOffset + 4);+}++function syntheticPe(machine: number): Buffer {+ const buffer = Buffer.alloc(0x90);+ buffer.writeUInt16LE(0x5a4d, 0);+ buffer.writeUInt32LE(0x80, 0x3c);+ buffer.writeUInt32LE(0x4550, 0x80);+ buffer.writeUInt16LE(machine, 0x84);+ return buffer;+}++/** Every file under root as a sorted, /-separated relative path. */+function walkFiles(root: string): string[] {+ const found: string[] = [];+ const visit = (dir: string, prefix: string): void => {+ for (const entry of readdirSync(dir, { withFileTypes: true })) {+ const path = join(dir, entry.name);+ const rel = prefix === '' ? entry.name : `${prefix}/${entry.name}`;+ if (entry.isDirectory()) visit(path, rel);+ else if (entry.isFile()) found.push(rel);+ }+ };+ visit(root, '');+ return found.sort();+}++type AsarDirNode = { files?: Record<string, unknown> };++/** Every entry (files AND directories) in an asar listing as a /-separated path. */+function asarEntryPaths(header: AsarDirNode): string[] {+ const paths: string[] = [];+ const visit = (node: AsarDirNode, prefix: string): void => {+ for (const [name, entry] of Object.entries(node.files ?? {})) {+ const path = prefix === '' ? name : `${prefix}/${name}`;+ paths.push(path);+ if (typeof entry === 'object' && entry !== null && 'files' in entry) {+ visit(entry as AsarDirNode, path);+ }+ }+ };+ visit(header, '');+ return paths.sort();+}++function writeSyntheticAsar(path: string, header: object): void {+ const json = Buffer.from(JSON.stringify(header), 'utf8');+ const prefix = Buffer.alloc(16);+ prefix.writeUInt32LE(4, 0);+ prefix.writeUInt32LE(json.length + 8, 4);+ prefix.writeUInt32LE(json.length + 4, 8);+ prefix.writeUInt32LE(json.length, 12);+ writeFileSync(path, Buffer.concat([prefix, json]));+}++const fixtureDirs: string[] = [];+afterEach(() => {+ for (const dir of fixtureDirs.splice(0)) rmSync(dir, { recursive: true, force: true });+});++describe('Windows package native guard helpers', () => {+ test('extracts the PE machine word for both shipped architectures', () => {+ expect(peMachineType(syntheticPe(0x8664))).toBe(0x8664);+ expect(peMachineType(syntheticPe(0xaa64))).toBe(0xaa64);+ });++ test('rejects non-PE bytes instead of returning a garbage machine word', () => {+ expect(() => peMachineType(Buffer.from('ELF-not-PE'))).toThrow(/MZ magic/);+ const mzOnly = Buffer.alloc(0x90);+ mzOnly.writeUInt16LE(0x5a4d, 0);+ mzOnly.writeUInt32LE(0x80, 0x3c);+ expect(() => peMachineType(mzOnly)).toThrow(/PE signature/);+ });++ test('walks nested package trees and reports files only, as relative paths', () => {+ const root = mkdtempSync(join(tmpdir(), 'ok-win-native-guard-'));+ fixtureDirs.push(root);+ const nested = join(root, 'prebuilds', 'win32-x64', 'conpty');+ mkdirSync(nested, { recursive: true });+ writeFileSync(join(nested, 'conpty.dll'), 'pe');+ writeFileSync(join(root, 'package.json'), '{}');+ expect(walkFiles(root)).toEqual(['package.json', 'prebuilds/win32-x64/conpty/conpty.dll']);+ });++ test('lists every entry of an asar header, including directories', () => {+ const root = mkdtempSync(join(tmpdir(), 'ok-win-native-guard-asar-'));+ fixtureDirs.push(root);+ const asar = join(root, 'app.asar');+ writeSyntheticAsar(asar, {+ files: {+ node_modules: {+ files: {+ 'node-pty': {+ files: {+ third_party: { files: { 'winpty.cc': { size: 1, offset: '0' } } },+ 'package.json': { size: 2, offset: '1' },+ },+ },+ },+ },+ },+ });+ expect(asarEntryPaths(readAsarHeader(asar) as AsarDirNode)).toEqual([+ 'node_modules',+ 'node_modules/node-pty',+ 'node_modules/node-pty/package.json',+ 'node_modules/node-pty/third_party',+ 'node_modules/node-pty/third_party/winpty.cc',+ ]);+ });++ test('rejects an asar header length above the shared allocation bound', () => {+ const root = mkdtempSync(join(tmpdir(), 'ok-win-native-guard-asar-bound-'));+ fixtureDirs.push(root);+ const asar = join(root, 'app.asar');+ const prefix = Buffer.alloc(16);+ prefix.writeUInt32LE(MAX_ASAR_HEADER_BYTES + 1, 12);+ writeFileSync(asar, prefix);++ expect(() => readAsarHeader(asar)).toThrow(/implausible asar header length/);+ });+});++describe('Windows package native guard lane visibility', () => {+ test('reports whether OK_WIN_PACKAGE_DIR enabled the assertive lane', () => {+ if (packageDir === null) {+ expect(packageDirRequired, 'OK_WIN_PACKAGE_DIR is required for this package lane').toBe(+ false,+ );+ console.log(+ '[windows-package-native-guards] OK_WIN_PACKAGE_DIR is unset — packaged-artifact assertions skipped',+ );+ return;+ }+ console.log(`[windows-package-native-guards] checking ${packageDir}`);+ expect(packageDirInput).not.toBe('');+ });+});++describe.skipIf(packageDir === null)('packaged Windows node-pty payload', () => {+ const nodePtyUnpackedRoot = join(+ packageDir ?? '',+ 'resources',+ 'app.asar.unpacked',+ 'node_modules',+ 'node-pty',+ );+ const appAsarPath = join(packageDir ?? '', 'resources', 'app.asar');++ test('control: package dir carries an unpacked node-pty tree and an app.asar (a wrong dir cannot pass vacuously)', () => {+ expect(existsSync(nodePtyUnpackedRoot), `no unpacked node-pty at ${nodePtyUnpackedRoot}`).toBe(+ true,+ );+ expect(existsSync(appAsarPath), `no app.asar at ${appAsarPath}`).toBe(true);+ expect(+ walkFiles(nodePtyUnpackedRoot).length,+ 'unpacked node-pty tree is empty',+ ).toBeGreaterThan(0);+ });++ test.each(+ WIN32_ARCHES,+ )('%s prebuild ships arch-correct PE addons with the ConPTY pair beside them', (arch) => {+ const archDir = join(nodePtyUnpackedRoot, 'prebuilds', arch);+ for (const name of CONPTY_FILES) {+ const file = join(archDir, name);+ expect(existsSync(file), `missing ${arch}/${name}`).toBe(true);+ expect(peMachineType(readFileSync(file)), `${arch}/${name}: PE machine word`).toBe(+ PE_MACHINE[arch],+ );+ }+ });++ test('unpacked tree carries no debug symbols, foreign prebuilds, or native-build output', () => {+ const offenders = walkFiles(nodePtyUnpackedRoot).filter(+ (file) =>+ file.endsWith('.pdb') ||+ /^(build|third_party)\//.test(file) ||+ (file.startsWith('prebuilds/') && !file.startsWith('prebuilds/win32-')),+ );+ expect(offenders, `pruned paths shipped: ${offenders.slice(0, 10).join(', ')}`).toEqual([]);+ });++ test('app.asar carries node-pty but none of the pruned trees', () => {+ const entries = asarEntryPaths(readAsarHeader(appAsarPath));+ const nodePtyEntries = entries.filter((entry) => entry.startsWith('node_modules/node-pty/'));+ expect(nodePtyEntries.length, 'node-pty absent from app.asar').toBeGreaterThan(0);+ const offenders = nodePtyEntries.filter(+ (entry) =>+ entry.endsWith('.pdb') ||+ /^node_modules\/node-pty\/(build|third_party)(\/|$)/.test(entry) ||+ /^node_modules\/node-pty\/prebuilds\/(?!win32-)/.test(entry),+ );+ expect(offenders, `pruned paths inside app.asar: ${offenders.slice(0, 10).join(', ')}`).toEqual(+ [],+ );+ });++ test('conout worker and its CJS resolution anchors are on the real filesystem', () => {+ for (const rel of [+ 'lib/worker/conoutSocketWorker.js',+ 'lib/shared/conout.js',+ 'package.json',+ ]) {+ expect(+ existsSync(join(nodePtyUnpackedRoot, rel)),+ `missing unpacked node-pty/${rel} — the ConPTY conout worker runs on a worker thread, which cannot load from inside an asar`,+ ).toBe(true);+ }+ });++ test('unpacked node-pty payload stays inside the size budget', () => {+ const bytes = walkFiles(nodePtyUnpackedRoot).reduce(+ (sum, rel) => sum + statSync(join(nodePtyUnpackedRoot, rel)).size,+ 0,+ );+ expect(+ bytes,+ 'unpacked node-pty exceeds the ~3.5 MB payload budget — a .pdb or foreign-prebuild regression adds tens of MB',+ ).toBeLessThanOrEqual(3.5 * 1024 * 1024);+ });+});diff --git a/packages/desktop/tests/utility/pty-flood.harness.ts b/packages/desktop/tests/utility/pty-flood.harness.tsindex 2de1f8665..e5d2b67f0 100644--- a/packages/desktop/tests/utility/pty-flood.harness.ts+++ b/packages/desktop/tests/utility/pty-flood.harness.ts@@ -25,7 +25,7 @@* proving the per-session isolation the single-PTY scenarios above cannot reach.*/-import { chmodSync, existsSync, mkdtempSync, realpathSync, rmSync, writeFileSync } from 'node:fs';+import { chmodSync, existsSync, mkdtempSync, realpathSync, writeFileSync } from 'node:fs';import { createRequire } from 'node:module';import { tmpdir } from 'node:os';import { dirname, join } from 'node:path';@@ -42,6 +42,7 @@ import {type SpawnPty,setupPtyHost,} from '../../src/utility/pty-host.ts';+import { removeTempDirBestEffort } from '../support/temp-dir-cleanup.test-helper.ts';const require = createRequire(import.meta.url);@@ -376,11 +377,7 @@ async function runFloodScenario(opts: FloodOptions): Promise<FloodMetrics> {// Best-effort: the shell may already be gone.}bridge.reap();- try {- rmSync(tmp, { recursive: true, force: true });- } catch {- // Best-effort tmpdir cleanup.- }+ removeTempDirBestEffort(tmp);}}@@ -575,11 +572,7 @@ function createMultiSessionRig(opts: {}bridge.reap();activeRigCleanups.delete(cleanup);- try {- rmSync(tmp, { recursive: true, force: true });- } catch {- // Best-effort tmpdir cleanup.- }+ removeTempDirBestEffort(tmp);};activeRigCleanups.add(cleanup);diff --git a/packages/desktop/tests/utility/pty-flood.test.ts b/packages/desktop/tests/utility/pty-flood.test.tsindex 2150147fb..6414ad87f 100644--- a/packages/desktop/tests/utility/pty-flood.test.ts+++ b/packages/desktop/tests/utility/pty-flood.test.ts@@ -16,18 +16,24 @@ import { describe, expect, test } from 'vitest';const NODE = Bun.which('node');const HARNESS = new URL('./pty-flood.harness.ts', import.meta.url).pathname;-describe('PTY flood — backpressure + UTF-8 integrity (Node runtime)', () => {- test('sustained multibyte floods stay responsive, bound in-flight via pause/resume, deliver bytes uncorrupted, and isolate concurrent sessions', () => {- if (!NODE) {- throw new Error(- 'node was not found on PATH but is required (package engines: >=24) to drive the real-PTY flood — node-pty produces no output under Bun',- );- }- const proc = Bun.spawnSync([NODE, HARNESS], { stdout: 'pipe', stderr: 'pipe' });- const output = `${proc.stdout.toString()}${proc.stderr.toString()}`;- if (proc.exitCode !== 0) {- throw new Error(`flood harness failed (exit ${proc.exitCode}):\n${output}`);- }- expect(output).toContain('HARNESS_RESULT ok=4 fail=0');- }, 120_000);-});+// This harness requires POSIX login shells and signal semantics. The required+// Windows terminal job covers the packaged interactive marker path; this+// sustained flood/backpressure matrix remains POSIX-only.+describe.skipIf(process.platform === 'win32')(+ 'PTY flood — backpressure + UTF-8 integrity (Node runtime)',+ () => {+ test('sustained multibyte floods stay responsive, bound in-flight via pause/resume, deliver bytes uncorrupted, and isolate concurrent sessions', () => {+ if (!NODE) {+ throw new Error(+ 'node was not found on PATH but is required (package engines: >=24) to drive the real-PTY flood — node-pty produces no output under Bun',+ );+ }+ const proc = Bun.spawnSync([NODE, HARNESS], { stdout: 'pipe', stderr: 'pipe' });+ const output = `${proc.stdout.toString()}${proc.stderr.toString()}`;+ if (proc.exitCode !== 0) {+ throw new Error(`flood harness failed (exit ${proc.exitCode}):\n${output}`);+ }+ expect(output).toContain('HARNESS_RESULT ok=4 fail=0');+ }, 120_000);+ },+);diff --git a/packages/desktop/tests/utility/pty-host-path-probe.test.ts b/packages/desktop/tests/utility/pty-host-path-probe.test.tsnew file mode 100644index 000000000..6d96ec542--- /dev/null+++ b/packages/desktop/tests/utility/pty-host-path-probe.test.ts@@ -0,0 +1,193 @@+import { execFileSync } from 'node:child_process';+import { win32 } from 'node:path';+import { beforeEach, describe, expect, test, vi } from 'vitest';+import { resolveShellWithDetails } from '../../src/utility/pty-host.ts';++/**+ * Coverage for the DEFAULT Windows `pwsh` PATH probe — the branch the+ * production host actually takes. `pty-host.test.ts` injects `pathProbe` in+ * every win32 case, so the real `execFileSync` body has no coverage there;+ * these tests deliberately omit the injection so the default runs.+ *+ * `execFileSync` is the seam: the probe's failure mode (a `PATH` entry on an+ * unreachable network location making `where.exe` block) cannot be synthesized+ * on a non-Windows host, and the probe is synchronous, so the bound it hands to+ * the child-process API is the only observable form of "this call is bounded".+ */+vi.mock('node:child_process', async (importOriginal) => ({+ ...(await importOriginal<typeof import('node:child_process')>()),+ execFileSync: vi.fn(),+}));++const execFileSyncMock = vi.mocked(execFileSync);++const WIN_ENV = {+ SystemRoot: 'C:\\Windows',+ ProgramFiles: 'C:\\Program Files',+} as const;++/** Options object handed to `execFileSync` by the probe on the Nth call. */+function probeOptions(call = 0): { timeout?: number } | undefined {+ return execFileSyncMock.mock.calls[call]?.[2] as { timeout?: number } | undefined;+}++beforeEach(() => {+ execFileSyncMock.mockReset();+});++describe('defaultWindowsPathProbe (via resolveShellWithDetails, no pathProbe injected)', () => {+ test("matches the readiness probe's five-second timeout", () => {+ execFileSyncMock.mockReturnValue('C:\\tools\\pwsh.exe\r\n');++ resolveShellWithDetails(WIN_ENV, {+ platform: 'win32',+ shellExists: (path) => path === 'C:\\tools\\pwsh.exe',+ });++ expect(execFileSyncMock).toHaveBeenCalledTimes(1);+ const timeout = probeOptions()?.timeout;+ // The probe runs synchronously on the PTY host's single message loop, so+ // an unbounded call freezes input/resize/kill for every tab in the window.+ expect(timeout).toBe(5_000);+ });++ test('a timed-out probe falls through to the next rung instead of throwing', () => {+ const warnings: Record<string, unknown>[] = [];+ execFileSyncMock.mockImplementation(() => {+ throw Object.assign(new Error('spawnSync where.exe ETIMEDOUT'), {+ code: 'ETIMEDOUT',+ signal: 'SIGTERM',+ });+ });++ const resolution = resolveShellWithDetails(WIN_ENV, {+ platform: 'win32',+ shellExists: (path) => path === 'C:\\Program Files\\PowerShell\\7\\pwsh.exe',+ logger: { warn: (entry) => warnings.push(entry) },+ });++ // Treating a timeout as "not found" is what lets the bound be added without+ // a new error path; a rethrow here would take down the create handler.+ expect(resolution.shell).toBe('C:\\Program Files\\PowerShell\\7\\pwsh.exe');+ expect(resolution.rung).toBe('pwsh-known-install');+ expect(warnings).toContainEqual({+ event: 'pty-host-shell-path-probe-timed-out',+ command: 'pwsh',+ timeoutMs: 5_000,+ });+ });++ test('a non-timeout probe failure is logged before the ladder falls through', () => {+ const warnings: Record<string, unknown>[] = [];+ execFileSyncMock.mockImplementation(() => {+ throw Object.assign(new Error('spawnSync where.exe EACCES'), { code: 'EACCES' });+ });++ const resolution = resolveShellWithDetails(WIN_ENV, {+ platform: 'win32',+ shellExists: (path) => path === 'C:\\Program Files\\PowerShell\\7\\pwsh.exe',+ logger: { warn: (entry) => warnings.push(entry) },+ });++ expect(resolution.rung).toBe('pwsh-known-install');+ expect(warnings).toContainEqual({+ event: 'pty-host-shell-path-probe-failed',+ command: 'pwsh',+ code: 'EACCES',+ });+ });++ test('still resolves the first absolute .exe line where.exe prints', () => {+ execFileSyncMock.mockReturnValue('pwsh\r\nC:\\tools\\pwsh.exe\r\nC:\\other\\pwsh.exe\r\n');++ const resolution = resolveShellWithDetails(WIN_ENV, {+ platform: 'win32',+ shellExists: (path) => path === 'C:\\tools\\pwsh.exe',+ });++ expect(execFileSyncMock.mock.calls[0]?.[0]).toBe('C:\\Windows\\System32\\where.exe');+ expect(execFileSyncMock.mock.calls[0]?.[1]).toEqual(['$PATH:pwsh']);+ expect(resolution.shell).toBe('C:\\tools\\pwsh.exe');+ expect(resolution.rung).toBe('pwsh-path');+ });+});++/**+ * Stand-in for `where.exe`, calibrated against its measured behaviour on+ * Windows 11 (build 26200) rather than assumed from its argv:+ *+ * - `where pwsh` run inside a directory holding `pwsh.exe` prints that+ * directory's copy, and when the name is also on `PATH` it prints the+ * working-directory copy FIRST.+ * - `where $PATH:pwsh` run in the same directory prints nothing and exits 1;+ * with the name on `PATH` it prints only the `PATH` copy.+ * - Both forms append `PATHEXT`'s `.exe` to an extension-less pattern.+ *+ * The real failure needs a Windows host and a working directory the test+ * cannot choose, so the seam is `execFileSync` and this fake supplies the+ * search semantics the probe's argv selects.+ */+function fakeWhereExe(options: {+ files: readonly string[];+ cwd: string;+ pathEntries: readonly string[];+}) {+ return (_file: string, args: readonly string[]): string => {+ const pattern = args[0] ?? '';+ const pathScoped = pattern.startsWith('$PATH:');+ const name = pathScoped ? pattern.slice('$PATH:'.length) : pattern;+ const filename = name.toLowerCase().endsWith('.exe') ? name : `${name}.exe`;+ const searchDirs = pathScoped ? options.pathEntries : [options.cwd, ...options.pathEntries];+ const hits = searchDirs+ .map((dir) => win32.join(dir, filename))+ .filter((candidate) => options.files.includes(candidate));+ if (hits.length === 0) {+ throw Object.assign(new Error('INFO: Could not find files for the given pattern(s).'), {+ status: 1,+ });+ }+ return `${hits.join('\r\n')}\r\n`;+ };+}++const PROJECT_DIR = 'C:\\Users\\ok\\projects\\untrusted';+const KNOWN_INSTALL_PWSH = 'C:\\Program Files\\PowerShell\\7\\pwsh.exe';++describe('the implicit pwsh probe is scoped to PATH', () => {+ test('a pwsh.exe in the working directory is not adopted as the shell', () => {+ const files = [win32.join(PROJECT_DIR, 'pwsh.exe'), KNOWN_INSTALL_PWSH];+ execFileSyncMock.mockImplementation(+ fakeWhereExe({ files, cwd: PROJECT_DIR, pathEntries: [] }) as never,+ );++ const resolution = resolveShellWithDetails(WIN_ENV, {+ platform: 'win32',+ shellExists: (path) => files.includes(path),+ });++ // The PTY host inherits the launcher's working directory, so a checkout+ // that happens to contain `pwsh.exe` must not be able to nominate the+ // shell the first terminal tab spawns without an explicit override.+ expect(resolution.shell).not.toBe(win32.join(PROJECT_DIR, 'pwsh.exe'));+ expect(resolution.shell).toBe(KNOWN_INSTALL_PWSH);+ expect(resolution.rung).toBe('pwsh-known-install');+ });++ test('an installed pwsh on PATH wins over a same-named file in the working directory', () => {+ const onPath = 'C:\\tools\\pwsh.exe';+ const files = [win32.join(PROJECT_DIR, 'pwsh.exe'), onPath];+ execFileSyncMock.mockImplementation(+ fakeWhereExe({ files, cwd: PROJECT_DIR, pathEntries: ['C:\\tools'] }) as never,+ );++ const resolution = resolveShellWithDetails(WIN_ENV, {+ platform: 'win32',+ shellExists: (path) => files.includes(path),+ });++ // `where.exe` lists the working-directory match ahead of the PATH match,+ // and the probe takes the first line, so an unscoped lookup loses here.+ expect(resolution.shell).toBe(onPath);+ expect(resolution.rung).toBe('pwsh-path');+ });+});diff --git a/packages/desktop/tests/utility/pty-host-real-io.test.ts b/packages/desktop/tests/utility/pty-host-real-io.test.tsindex c47222fc1..568dd64bc 100644--- a/packages/desktop/tests/utility/pty-host-real-io.test.ts+++ b/packages/desktop/tests/utility/pty-host-real-io.test.ts@@ -1,25 +1,118 @@-import { spawnSync } from 'node:child_process';+import { spawn } from 'node:child_process';+import { closeSync, mkdtempSync, openSync, readFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { fileURLToPath } from 'node:url';import { describe, expect, test } from 'vitest';import { isTerminalPlatform } from '../../src/shared/terminal-platform.ts';+import { removeTempDirBestEffort } from '../support/temp-dir-cleanup.test-helper.ts';/*** Gate wrapper for the real-shell-I/O seam. The actual PTY drive runs in an* isolated Node subprocess so native handles cannot leak into the Vitest worker.*/-const HARNESS = new URL('./pty-host.real-io-harness.ts', import.meta.url).pathname;+const HARNESS = fileURLToPath(new URL('./pty-host.real-io-harness.ts', import.meta.url));++const TERMINAL_PLATFORM = isTerminalPlatform(process.platform);+const SUCCESS_RESULT = `HARNESS_RESULT ok=${process.platform === 'win32' ? 5 : 4} fail=0`;++const sleep = (ms: number): Promise<void> => new Promise((resolve) => setTimeout(resolve, ms));++async function runHarness(outputDir: string): Promise<string> {+ const outputPath = join(outputDir, 'output.log');+ const outputFd = openSync(outputPath, 'w');+ const child = (() => {+ try {+ // A descendant can inherit a captured pipe on Windows and keep the+ // parent waiting for EOF after the harness itself has settled.+ return spawn(process.execPath, [HARNESS], {+ env: {+ ...process.env,+ TEMP: outputDir,+ TMP: outputDir,+ TMPDIR: outputDir,+ },+ stdio: ['ignore', outputFd, outputFd],+ windowsHide: true,+ });+ } finally {+ closeSync(outputFd);+ }+ })();++ let spawnError: Error | null = null;+ let exitResult: { code: number | null; signal: string | null } | null = null;+ let resolveExit: () => void = () => undefined;+ const exitPromise = new Promise<void>((resolve) => {+ resolveExit = resolve;+ });+ child.once('error', (error) => {+ spawnError = error;+ });+ child.once('exit', (code, signal) => {+ exitResult = { code, signal };+ resolveExit();+ });++ async function terminateChild(): Promise<void> {+ if (exitResult === null) {+ child.kill();+ await Promise.race([exitPromise, sleep(2_000)]);+ }+ child.unref();+ }++ try {+ const deadline = Date.now() + (process.platform === 'win32' ? 90_000 : 45_000);+ while (Date.now() < deadline) {+ const output = readFileSync(outputPath, 'utf8');+ if (spawnError !== null) {+ throw new Error(`real-PTY harness could not start: ${spawnError.message}\n${output}`);+ }++ const completeLines = output.split(/\r?\n/u);+ completeLines.pop();+ const resultLine = completeLines.find((line) => line.startsWith('HARNESS_RESULT '));+ if (resultLine !== undefined) {+ if (resultLine !== SUCCESS_RESULT) {+ throw new Error(`real-PTY harness reported failure:\n${output}`);+ }+ if (exitResult !== null && exitResult.code !== 0) {+ throw new Error(+ `real-PTY harness exited ${exitResult.code ?? exitResult.signal} after success:\n${output}`,+ );+ }+ return output;+ }++ if (exitResult !== null) {+ throw new Error(+ `real-PTY harness exited ${exitResult.code ?? exitResult.signal} without a verdict:\n${output}`,+ );+ }+ await sleep(25);+ }++ const output = readFileSync(outputPath, 'utf8');+ throw new Error(`real-PTY harness timed out without a verdict:\n${output}`);+ } finally {+ await terminateChild();+ }+}describe('PTY host — real shell I/O (Node runtime)', () => {- test.skipIf(!isTerminalPlatform(process.platform))(- 'real interactive shell round-trips a command, strips env markers, survives a kill, and reports a bad shell',- () => {- const proc = spawnSync(process.execPath, [HARNESS], { encoding: 'utf8' });- const output = `${proc.stdout}${proc.stderr}`;- if (proc.status !== 0) {- throw new Error(`real-PTY harness failed (exit ${proc.status}):\n${output}`);+ test.skipIf(!TERMINAL_PLATFORM)(+ 'real interactive shell round-trips commands, strips env markers, survives a kill, and reports a bad shell',+ async () => {+ const outputDir = mkdtempSync(join(tmpdir(), 'ok-real-pty-wrapper-'));+ try {+ const output = await runHarness(outputDir);+ expect(output).toContain(SUCCESS_RESULT);+ } finally {+ removeTempDirBestEffort(outputDir);}- expect(output).toContain('HARNESS_RESULT ok=4 fail=0');},- 60_000,+ process.platform === 'win32' ? 105_000 : 60_000,);});diff --git a/packages/desktop/tests/utility/pty-host-reap.test.ts b/packages/desktop/tests/utility/pty-host-reap.test.tsindex 77c0dfb01..a2c44ebc9 100644--- a/packages/desktop/tests/utility/pty-host-reap.test.ts+++ b/packages/desktop/tests/utility/pty-host-reap.test.ts@@ -83,12 +83,18 @@ async function assertNoOrphan(killSignal: 'SIGTERM' | 'SIGKILL'): Promise<void>}}-describe('PTY host — no orphan on host teardown (Node runtime)', () => {- test('a SIGTERM to the host leaves no orphan shell (graceful reap path)', async () => {- await assertNoOrphan('SIGTERM');- }, 60_000);+// This harness requires POSIX signals and master-fd SIGHUP behavior. Windows+// update-time cleanup has separate survivor-sweep coverage; real Windows+// forced-host-crash orphan behavior remains an external packaged-runtime gate.+describe.skipIf(process.platform === 'win32')(+ 'PTY host — no orphan on host teardown (Node runtime)',+ () => {+ test('a SIGTERM to the host leaves no orphan shell (graceful reap path)', async () => {+ await assertNoOrphan('SIGTERM');+ }, 60_000);- test('a SIGKILL to the host leaves no orphan shell (OS backstop, no handler runs)', async () => {- await assertNoOrphan('SIGKILL');- }, 60_000);-});+ test('a SIGKILL to the host leaves no orphan shell (OS backstop, no handler runs)', async () => {+ await assertNoOrphan('SIGKILL');+ }, 60_000);+ },+);diff --git a/packages/desktop/tests/utility/pty-host-support-file.test.ts b/packages/desktop/tests/utility/pty-host-support-file.test.tsnew file mode 100644index 000000000..1b856cd1f--- /dev/null+++ b/packages/desktop/tests/utility/pty-host-support-file.test.ts@@ -0,0 +1,282 @@+import {+ chmodSync,+ existsSync,+ lstatSync,+ mkdirSync,+ mkdtempSync,+ readFileSync,+ realpathSync,+ rmSync,+ symlinkSync,+ writeFileSync,+} from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { afterEach, beforeEach, describe, expect, test } from 'vitest';+import {+ type PtyHostOutgoingMessage,+ type PtyProcessLike,+ setupPtyHost,+} from '../../src/utility/pty-host.ts';++/**+ * Filesystem contract for the PRODUCTION support-file writer.+ *+ * The sibling suite (`pty-host.test.ts`) always injects `materializeSupportFile`,+ * so the default that ships — the one that actually calls `mkdir` and `write` —+ * is never exercised there. These tests deliberately leave the dep uninjected+ * and run against a real temp tree with real symlinks, because the property+ * under test (the resolved write location stays inside the project) is only+ * observable through the filesystem.+ *+ * `platform: 'win32'` is the logical launch platform the host is told to compose+ * for — the escape it must refuse is a Windows Git checkout with symlink support+ * — while the filesystem operations run natively on the host runner. Directory+ * junctions, which only exist on Windows, resolve through `realpath` exactly as+ * these directory symlinks do, so the segment walk covers them by construction.+ */++const SUPPORT_RELATIVE_PATH = '.ok/local/terminal/claude-settings-mcp-tools.json';+const REGISTRY_CONTENTS = '{"enabledMcpjsonServers":["open-knowledge"]}';++function makeInertPty(): PtyProcessLike {+ return {+ pid: 4242,+ onData() {},+ onExit() {},+ write() {},+ resize() {},+ kill() {},+ pause() {},+ resume() {},+ };+}++interface WriterHarness {+ spawnArgs: string[] | string | undefined;+ posted: PtyHostOutgoingMessage[];+ warnings: Record<string, unknown>[];+}++/** Drive one `create` through the host with the production writer in place. */+function materialize(cwd: string, relativePath = SUPPORT_RELATIVE_PATH): WriterHarness {+ let handler: ((event: { data: unknown }) => void) | null = null;+ const posted: PtyHostOutgoingMessage[] = [];+ const warnings: Record<string, unknown>[] = [];+ const spawnCalls: Array<string[] | string> = [];+ setupPtyHost({+ parentPort: {+ on(_event, h) {+ handler = h;+ },+ postMessage(value) {+ posted.push(value);+ },+ },+ spawn: (_file, args) => {+ spawnCalls.push(args);+ return makeInertPty();+ },+ env: { SystemRoot: 'C:\\Windows', ComSpec: 'C:\\Windows\\System32\\cmd.exe' },+ platform: 'win32',+ shellExists: () => false,+ pathProbe: () => null,+ listDirectory: () => [],+ logger: { warn: (o) => warnings.push(o), info: () => {} },+ // `materializeSupportFile` intentionally omitted — that is the subject.+ });+ handler?.({+ data: {+ type: 'create',+ ptyId: 'p1',+ cwd,+ cols: 80,+ rows: 24,+ launchCommand: {+ executable: 'claude',+ args: ['--settings', relativePath],+ supportFile: { kind: 'claude-settings', relativePath, contents: REGISTRY_CONTENTS },+ },+ },+ });+ return { spawnArgs: spawnCalls[0], posted, warnings };+}++let root: string;+let project: string;+let outside: string;++beforeEach(() => {+ // realpath the temp root: on macOS `/var` is a symlink to `/private/var`, so+ // an un-resolved root would make every containment assertion vacuous.+ root = realpathSync(mkdtempSync(join(tmpdir(), 'ok-support-file-')));+ project = join(root, 'project');+ outside = join(root, 'outside');+ mkdirSync(project, { recursive: true });+ mkdirSync(outside, { recursive: true });+});++afterEach(() => {+ rmSync(root, { recursive: true, force: true });+});++/** The degradation the writer must fall through to when it refuses. */+function expectBareClaudeLaunch(h: WriterHarness): void {+ expect(h.posted.filter((m) => m.type === 'spawn-error')).toHaveLength(0);+ expect(h.spawnArgs).toBe('/K claude');+ expect(h.warnings.some((w) => w.event === 'pty-host-support-file-materialize-failed')).toBe(true);+}++function expectContainmentRefusal(h: WriterHarness): void {+ expectBareClaudeLaunch(h);+ expect(h.warnings).toContainEqual(+ expect.objectContaining({+ event: 'pty-host-support-file-materialize-failed',+ code: 'ERR_TERMINAL_SUPPORT_FILE_ESCAPE',+ }),+ );+ expect(h.posted).toContainEqual({+ type: 'shell-notice',+ ptyId: 'p1',+ notice: 'support-file-degraded',+ reason: 'containment-refused',+ });+}++function expectWriteFailure(h: WriterHarness): void {+ expectBareClaudeLaunch(h);+ expect(h.posted).toContainEqual({+ type: 'shell-notice',+ ptyId: 'p1',+ notice: 'support-file-degraded',+ reason: 'write-failed',+ });+}++describe('production support-file writer', () => {+ test('creates the settings file when nothing exists yet', () => {+ const h = materialize(project);++ const target = join(project, '.ok', 'local', 'terminal', 'claude-settings-mcp-tools.json');+ expect(readFileSync(target, 'utf8')).toBe(REGISTRY_CONTENTS);+ expect(lstatSync(target).isSymbolicLink()).toBe(false);+ expect(h.spawnArgs).toBe(`/K claude --settings ${SUPPORT_RELATIVE_PATH}`);+ expect(h.warnings.some((w) => w.event === 'pty-host-support-file-materialize-failed')).toBe(+ false,+ );+ });++ test('overwrites an existing regular settings file in place', () => {+ const dir = join(project, '.ok', 'local', 'terminal');+ mkdirSync(dir, { recursive: true });+ writeFileSync(join(dir, 'claude-settings-mcp-tools.json'), '{"stale":true}');++ const h = materialize(project);++ expect(readFileSync(join(dir, 'claude-settings-mcp-tools.json'), 'utf8')).toBe(+ REGISTRY_CONTENTS,+ );+ expect(h.spawnArgs).toBe(`/K claude --settings ${SUPPORT_RELATIVE_PATH}`);+ });++ test('refuses when the terminal settings directory is a symlink out of the project', () => {+ const attackerDir = join(outside, 'attacker-dir');+ mkdirSync(attackerDir, { recursive: true });+ mkdirSync(join(project, '.ok', 'local'), { recursive: true });+ symlinkSync(attackerDir, join(project, '.ok', 'local', 'terminal'), 'dir');++ const h = materialize(project);++ expect(existsSync(join(attackerDir, 'claude-settings-mcp-tools.json'))).toBe(false);+ expectContainmentRefusal(h);+ });++ test('refuses when an ancestor segment is a symlink out of the project', () => {+ const attackerDir = join(outside, 'attacker-ok');+ mkdirSync(attackerDir, { recursive: true });+ symlinkSync(attackerDir, join(project, '.ok'), 'dir');++ const h = materialize(project);++ expect(existsSync(join(attackerDir, 'local'))).toBe(false);+ expectContainmentRefusal(h);+ });++ test('refuses to follow a leaf symlink onto an external file', () => {+ const victim = join(outside, 'victim.json');+ writeFileSync(victim, '{"user":"important"}');+ const dir = join(project, '.ok', 'local', 'terminal');+ mkdirSync(dir, { recursive: true });+ symlinkSync(victim, join(dir, 'claude-settings-mcp-tools.json'));++ const h = materialize(project);++ expect(readFileSync(victim, 'utf8')).toBe('{"user":"important"}');+ expectContainmentRefusal(h);+ });++ test('refuses a dangling leaf symlink rather than creating its target', () => {+ const victim = join(outside, 'not-yet-there.json');+ const dir = join(project, '.ok', 'local', 'terminal');+ mkdirSync(dir, { recursive: true });+ symlinkSync(victim, join(dir, 'claude-settings-mcp-tools.json'));++ const h = materialize(project);++ expect(existsSync(victim)).toBe(false);+ expectContainmentRefusal(h);+ });++ test('refuses a leaf symlink that stays inside the project', () => {+ // Even a contained symlink is refused: the writer owns this path outright,+ // so a link there is not a shape it authored and following it would let a+ // later re-point of the link redirect the next write.+ const inside = join(project, 'decoy.json');+ writeFileSync(inside, '{"inside":true}');+ const dir = join(project, '.ok', 'local', 'terminal');+ mkdirSync(dir, { recursive: true });+ symlinkSync(inside, join(dir, 'claude-settings-mcp-tools.json'));++ const h = materialize(project);++ expect(readFileSync(inside, 'utf8')).toBe('{"inside":true}');+ expectContainmentRefusal(h);+ });++ test('classifies a dangling directory symlink as a containment refusal', () => {+ mkdirSync(join(project, '.ok', 'local'), { recursive: true });+ symlinkSync(join(outside, 'missing'), join(project, '.ok', 'local', 'terminal'), 'dir');++ expectContainmentRefusal(materialize(project));+ });++ test('classifies a directory symlink cycle as a containment refusal', () => {+ mkdirSync(join(project, '.ok', 'local'), { recursive: true });+ const terminal = join(project, '.ok', 'local', 'terminal');+ symlinkSync(terminal, terminal, 'dir');++ expectContainmentRefusal(materialize(project));+ });++ test.skipIf(process.platform === 'win32')(+ 'keeps a permission failure distinct from a containment refusal',+ () => {+ const locked = join(outside, 'locked');+ const target = join(locked, 'target');+ mkdirSync(target, { recursive: true });+ symlinkSync(target, join(project, '.ok'), 'dir');+ chmodSync(locked, 0o000);+ try {+ expectWriteFailure(materialize(project));+ } finally {+ chmodSync(locked, 0o700);+ }+ },+ );++ test('refuses when the project cwd itself does not resolve', () => {+ const h = materialize(join(root, 'no-such-project'));++ expectBareClaudeLaunch(h);+ });+});diff --git a/packages/desktop/tests/utility/pty-host.real-io-harness.ts b/packages/desktop/tests/utility/pty-host.real-io-harness.tsindex ab9a3f351..88d4a2303 100644--- a/packages/desktop/tests/utility/pty-host.real-io-harness.ts+++ b/packages/desktop/tests/utility/pty-host.real-io-harness.ts@@ -7,19 +7,23 @@* on its exit code + result line.** Scenarios: real command round-trip, cwd binding + env-marker stripping,- * host-survives-PTY-death containment, bad-shell async exit.+ * Windows PowerShell launch composition, host-survives-PTY-death containment,+ * bad-shell async exit.*/-import { chmodSync, existsSync, mkdtempSync, realpathSync, rmSync } from 'node:fs';+import { randomUUID } from 'node:crypto';+import { chmodSync, existsSync, mkdtempSync, realpathSync, writeFileSync } from 'node:fs';import { createRequire } from 'node:module';import { tmpdir } from 'node:os';-import { basename, dirname, join } from 'node:path';+import { dirname, join } from 'node:path';+import type { SpawnPty } from '../../src/utility/pty-host.ts';+import { terminalSmokeShellCommands } from '../smoke/_helpers/terminal-smoke-shell.ts';import {- type PtyHostIncomingMessage,- type PtyHostOutgoingMessage,- type SpawnPty,- setupPtyHost,-} from '../../src/utility/pty-host.ts';+ buildCwdFileProofCommand,+ createPtyHostProbe,+ waitForCondition,+ waitForShellReady,+} from '../support/pty-readiness.test-helper.ts';const require = createRequire(import.meta.url);@@ -35,56 +39,15 @@ function ensureSpawnHelperExecutable(): void {const { spawn } = require('node-pty') as { spawn: SpawnPty };-interface Host {- send(msg: PtyHostIncomingMessage): void;- dataOf(ptyId: string): string;- exitOf(ptyId: string): { exitCode: number; signal: number | null } | null;- errorOf(ptyId: string): string | null;- killActive(): void;-}--function createHost(env: Record<string, string | undefined>): Host {- let handler: ((event: { data: unknown }) => void) | null = null;- const data = new Map<string, string>();- const exits = new Map<string, { exitCode: number; signal: number | null }>();- const errors = new Map<string, string>();- const handle = setupPtyHost({- parentPort: {- on(_event, h) {- handler = h;- },- postMessage(msg: PtyHostOutgoingMessage) {- if (msg.type === 'data') data.set(msg.ptyId, (data.get(msg.ptyId) ?? '') + msg.data);- else if (msg.type === 'exit')- exits.set(msg.ptyId, { exitCode: msg.exitCode, signal: msg.signal });- else if (msg.type === 'spawn-error') errors.set(msg.ptyId, msg.message);- },- },- spawn,- env,- });- return {- send: (msg) => handler?.({ data: msg }),- dataOf: (ptyId) => data.get(ptyId) ?? '',- exitOf: (ptyId) => exits.get(ptyId) ?? null,- errorOf: (ptyId) => errors.get(ptyId) ?? null,- killActive: () => handle.killActive(),- };-}--const sleep = (ms: number): Promise<void> => new Promise((r) => setTimeout(r, ms));--async function waitFor(predicate: () => boolean, label: string, timeoutMs = 8000): Promise<void> {- const deadline = Date.now() + timeoutMs;- while (Date.now() < deadline) {- if (predicate()) return;- await sleep(15);- }- throw new Error(`timeout waiting for: ${label}`);-}+const createHost = (+ env: Record<string, string | undefined>,+ shellExists?: (path: string) => boolean,+): ReturnType<typeof createPtyHostProbe> => createPtyHostProbe({ spawn, env, shellExists });const results: Array<{ name: string; ok: boolean; detail?: string }> = [];+let inFlight: string | null = null;async function scenario(name: string, fn: () => Promise<void>): Promise<void> {+ inFlight = name;try {await fn();results.push({ name, ok: true });@@ -92,29 +55,112 @@ async function scenario(name: string, fn: () => Promise<void>): Promise<void> {} catch (err) {results.push({ name, ok: false, detail: (err as Error).message });console.log(`FAIL ${name} :: ${(err as Error).message}`);+ } finally {+ inFlight = null;}}const BASE_ENV = { ...process.env };+const shellCommands = terminalSmokeShellCommands();+const CWD_PROOF_FILE = '.ok-pty-cwd-proof';+const WINDOWS_LAUNCH_WAIT = { timeoutMs: 20_000 } as const;++function createWindowsReadinessLaunch(): {+ marker: string;+ launchCommand: { executable: string; args: string[] };+} | null {+ if (process.platform !== 'win32') return null;+ // Never probe or retry with control characters before this marker: an early+ // Ctrl+C can be taken as process termination (NTSTATUS 0xC000013A) before the+ // shell's line editor owns the console. These scenarios pass no `shell:`, so+ // the ladder picks whatever the host resolves (pwsh 7 on `windows-latest`).+ // The structured command is the non-mutating startup gate; the real command+ // immediately after it proves interactive input.+ const marker = `OK_SHELL_READY_${randomUUID().replaceAll('-', '')}`;+ return {+ marker,+ launchCommand: { executable: 'cmd.exe', args: ['/d', '/c', 'echo', marker] },+ };+}++async function waitForInteractiveShellReady(+ host: ReturnType<typeof createHost>,+ ptyId: string,+ label: string,+ windowsLaunchMarker: string | null,+): Promise<void> {+ const stream = host.streamOf(ptyId);+ if (process.platform === 'win32') {+ if (windowsLaunchMarker === null) {+ throw new Error('Windows input-driven scenarios require a startup launch marker');+ }+ await waitForCondition(+ stream,+ () => stream.read().includes(windowsLaunchMarker),+ label,+ WINDOWS_LAUNCH_WAIT,+ );+ return;+ }+ await waitForShellReady(stream, label);+}async function main(): Promise<void> {ensureSpawnHelperExecutable();+ // The parent wrapper redirects the OS temp environment into its own+ // best-effort cleanup directory. Synchronous exit cleanup here can block on+ // Windows while a just-killed shell still holds this directory as its CWD.const tmp = realpathSync(mkdtempSync(join(tmpdir(), 'ok-pty-harness-')));// A real command runs and its evaluated output streams back,// and the prompt sits at the supplied project root.await scenario('real command round-trip at project root', async () => {+ const cwdToken = randomUUID();+ writeFileSync(join(tmp, CWD_PROOF_FILE), cwdToken, 'utf8');const host = createHost(BASE_ENV);- host.send({ type: 'create', ptyId: 'io', cwd: tmp, cols: 80, rows: 24 });- await waitFor(() => host.dataOf('io').length > 0, 'shell prompt');- // `$((6*7))` only resolves to 42 if the shell evaluated it — the echoed- // input line keeps the literal `$((6*7))`, so 42 proves execution.- host.send({ type: 'input', ptyId: 'io', data: 'echo HARNESS_$((6*7))_DONE\r' });- await waitFor(() => host.dataOf('io').includes('HARNESS_42_DONE'), 'evaluated command output');- host.send({ type: 'input', ptyId: 'io', data: 'pwd\r' });- await waitFor(() => host.dataOf('io').includes(basename(tmp)), 'pwd shows project root');- host.killActive();+ const io = host.streamOf('io');+ const readiness = createWindowsReadinessLaunch();+ try {+ host.send({+ type: 'create',+ ptyId: 'io',+ cwd: tmp,+ cols: 80,+ rows: 24,+ ...(readiness === null ? {} : { launchCommand: readiness.launchCommand }),+ });+ await waitForInteractiveShellReady(+ host,+ 'io',+ 'interactive shell ready at project root',+ readiness?.marker ?? null,+ );+ // The arithmetic expression only resolves to 42 if the shell evaluated+ // it; the echoed input line keeps the literal expression.+ host.send({+ type: 'input',+ ptyId: 'io',+ data: `${shellCommands.arithmetic('HARNESS', 6, 7, 'DONE')}\r`,+ });+ await waitForCondition(+ io,+ () => io.read().includes('HARNESS_42_DONE'),+ 'evaluated command output',+ );+ host.send({+ type: 'input',+ ptyId: 'io',+ data: `${buildCwdFileProofCommand(process.platform, CWD_PROOF_FILE)}\r`,+ });+ await waitForCondition(+ io,+ () => io.read().includes(`CWD_PROOF=${cwdToken}`),+ 'relative sentinel read at project root',+ );+ } finally {+ host.killActive();+ }});// Desktop-only markers are stripped from the user's shell.@@ -124,46 +170,156 @@ async function main(): Promise<void> {OK_ELECTRON_PROTOCOL_HOST: '1',OK_LOCK_KIND: 'interactive',});- host.send({ type: 'create', ptyId: 'env', cwd: tmp, cols: 80, rows: 24 });- await waitFor(() => host.dataOf('env').length > 0, 'shell prompt');- host.send({- type: 'input',- ptyId: 'env',- data: 'printf "MARKERS:[%s][%s]\\n" "$OK_LOCK_KIND" "$OK_ELECTRON_PROTOCOL_HOST"\r',- });- await waitFor(() => host.dataOf('env').includes('MARKERS:[][]'), 'empty markers in shell');- if (host.dataOf('env').includes('MARKERS:[interactive]')) {- throw new Error('OK_LOCK_KIND leaked into the shell');+ const env = host.streamOf('env');+ const readiness = createWindowsReadinessLaunch();+ try {+ host.send({+ type: 'create',+ ptyId: 'env',+ cwd: tmp,+ cols: 80,+ rows: 24,+ ...(readiness === null ? {} : { launchCommand: readiness.launchCommand }),+ });+ await waitForInteractiveShellReady(+ host,+ 'env',+ 'interactive shell ready with desktop markers stripped',+ readiness?.marker ?? null,+ );+ host.send({+ type: 'input',+ ptyId: 'env',+ data: `${shellCommands.readEnvironment('OK_LOCK_KIND', 'LOCK')}\r`,+ });+ host.send({+ type: 'input',+ ptyId: 'env',+ data: `${shellCommands.readEnvironment('OK_ELECTRON_PROTOCOL_HOST', 'HOST')}\r`,+ });+ await waitForCondition(+ env,+ () => env.read().includes('LOCK=[]') && env.read().includes('HOST=[]'),+ 'empty markers in shell',+ );+ if (env.read().includes('LOCK=[interactive]')) {+ throw new Error('OK_LOCK_KIND leaked into the shell');+ }+ } finally {+ host.killActive();}- host.killActive();});+ if (process.platform === 'win32') {+ // This is the only real-shell proof whose structured PowerShell launch+ // carries meaningful argv beyond the readiness marker. The explicit+ // Windows PowerShell override is load-bearing; the package smoke+ // intentionally pins ComSpec/cmd instead. The host-survival scenario below+ // separately exercises the plain empty-argv Windows spawn path twice.+ await scenario('PowerShell executes a structured launch command', async () => {+ const powershell = join(+ process.env.SystemRoot ?? 'C:\\Windows',+ 'System32',+ 'WindowsPowerShell',+ 'v1.0',+ 'powershell.exe',+ );+ if (!existsSync(powershell)) throw new Error(`Windows PowerShell is missing: ${powershell}`);++ const launchToken = randomUUID();+ const host = createHost({+ ...BASE_ENV,+ OK_HARNESS_LAUNCH_TOKEN: launchToken,+ });+ const launch = host.streamOf('launch');+ try {+ host.send({+ type: 'create',+ ptyId: 'launch',+ cwd: tmp,+ cols: 80,+ rows: 24,+ shell: powershell,+ launchCommand: {+ executable: 'cmd.exe',+ args: ['/d', '/c', 'echo', '%OK_HARNESS_LAUNCH_TOKEN%'],+ },+ });+ // The launch rides in as composed argv, so the output wait below needs+ // no pre-write gate. A distinct command typed afterward proves the shell+ // remains interactive after the EncodedCommand returns.+ await waitForCondition(+ launch,+ () => launch.read().includes(launchToken),+ 'PowerShell EncodedCommand output',+ WINDOWS_LAUNCH_WAIT,+ );+ const interactiveToken = `OK_INTERACTIVE_${randomUUID().replaceAll('-', '')}`;+ host.send({+ type: 'input',+ ptyId: 'launch',+ data: `${shellCommands.arithmetic(interactiveToken, 6, 7, 'READY')}\r`,+ });+ await waitForCondition(+ launch,+ () => launch.read().includes(`${interactiveToken}_42_READY`),+ 'PowerShell remains interactive after EncodedCommand',+ WINDOWS_LAUNCH_WAIT,+ );+ if (host.errorOf('launch') !== null) {+ throw new Error(`PowerShell launch failed: ${host.errorOf('launch')}`);+ }+ } finally {+ host.killActive();+ }+ });+ }+// Killing the shell (a crash) yields an exit event and the host stays// alive — a fresh PTY spawns in the same host.await scenario('host survives a PTY death and respawns', async () => {const host = createHost(BASE_ENV);+ const first = host.streamOf('c1');+ const second = host.streamOf('c2');host.send({ type: 'create', ptyId: 'c1', cwd: tmp, cols: 80, rows: 24 });- await waitFor(() => host.dataOf('c1').length > 0, 'first shell prompt');+ // Neither shell here is driven with input, so "the PTY produced bytes" is+ // the whole claim — spawn liveness, not read-loop readiness.+ await waitForCondition(first, () => first.read().length > 0, 'first shell prompt');host.send({ type: 'kill', ptyId: 'c1' });- await waitFor(() => host.exitOf('c1') !== null, 'exit after kill');+ await waitForCondition(first, () => host.exitOf('c1') !== null, 'exit after kill');host.send({ type: 'create', ptyId: 'c2', cwd: tmp, cols: 80, rows: 24 });- await waitFor(() => host.dataOf('c2').length > 0, 'second shell prompt (host survived)');+ await waitForCondition(+ second,+ () => second.read().length > 0,+ 'second shell prompt (host survived)',+ );host.killActive();});- // A shell that cannot launch surfaces as a non-zero exit- // (node-pty reports this async, NOT as a synchronous throw).- await scenario('bad shell surfaces as a non-zero exit', async () => {- const host = createHost(BASE_ENV);+ // A shell that cannot launch surfaces through the host's failure channel.+ await scenario('bad shell surfaces as a spawn failure', async () => {+ const badShell = join(+ tmp,+ process.platform === 'win32' ? 'no-such-shell-xyz.exe' : 'no-such-shell-xyz',+ );+ // Windows validates configured shell paths before spawning. Admit this+ // deliberate missing-path fixture through that gate so node-pty, rather+ // than the fallback ladder, remains the dependency under test.+ const host = createHost(BASE_ENV, (path) => path === badShell || existsSync(path));+ const bad = host.streamOf('bad');host.send({type: 'create',ptyId: 'bad',cwd: tmp,cols: 80,rows: 24,- shell: '/no/such/shell-xyz',+ shell: badShell,});- await waitFor(() => host.exitOf('bad') !== null, 'exit for unspawnable shell');+ await waitForCondition(+ bad,+ () => host.exitOf('bad') !== null || host.errorOf('bad') !== null,+ 'failure for unspawnable shell',+ );const exit = host.exitOf('bad');if (exit && exit.exitCode === 0 && exit.signal === null) {throw new Error('expected a non-zero/failed exit for a bad shell');@@ -171,18 +327,24 @@ async function main(): Promise<void> {host.killActive();});- rmSync(tmp, { recursive: true, force: true });-const failed = results.filter((r) => !r.ok).length;console.log(`HARNESS_RESULT ok=${results.length - failed} fail=${failed}`);process.exit(failed === 0 ? 0 : 1);}-// Hard ceiling so a wedged shell can never hang the parent Vitest worker.-const hardTimeout = setTimeout(() => {- console.log('HARNESS_RESULT ok=0 fail=1 :: hard timeout');- process.exit(1);-}, 30000);+// Wedge backstop below the parent wrapper's independent deadline. Scenario+// budgets remain the source of normal timeout failures and their diagnostics.+const hardTimeout = setTimeout(+ () => {+ const passed = results.filter((result) => result.ok).length;+ const failed = results.length - passed + 1;+ console.log(+ `HARNESS_RESULT ok=${passed} fail=${failed} :: hard timeout during ${inFlight ?? 'startup'}`,+ );+ process.exit(1);+ },+ process.platform === 'win32' ? 85_000 : 30_000,+);hardTimeout.unref();void main().catch((err) => {diff --git a/packages/desktop/tests/utility/pty-host.reap-harness.ts b/packages/desktop/tests/utility/pty-host.reap-harness.tsindex 63e2be045..c7ef3c756 100644--- a/packages/desktop/tests/utility/pty-host.reap-harness.ts+++ b/packages/desktop/tests/utility/pty-host.reap-harness.ts@@ -14,7 +14,7 @@* which is exactly the mechanism under test.*/-import { chmodSync, existsSync, mkdtempSync, realpathSync, rmSync } from 'node:fs';+import { chmodSync, existsSync, mkdtempSync, realpathSync } from 'node:fs';import { createRequire } from 'node:module';import { tmpdir } from 'node:os';import { dirname, join } from 'node:path';@@ -25,6 +25,7 @@ import {type SpawnPty,setupPtyHost,} from '../../src/utility/pty-host.ts';+import { removeTempDirBestEffort } from '../support/temp-dir-cleanup.test-helper.ts';const require = createRequire(import.meta.url);@@ -43,13 +44,7 @@ const sleep = (ms: number): Promise<void> => new Promise((r) => setTimeout(r, msasync function main(): Promise<void> {ensureSpawnHelperExecutable();const tmp = realpathSync(mkdtempSync(join(tmpdir(), 'ok-pty-reap-')));- process.on('exit', () => {- try {- rmSync(tmp, { recursive: true, force: true });- } catch {- // Best-effort tmpdir cleanup on the way out.- }- });+ process.on('exit', () => removeTempDirBestEffort(tmp));let data = '';let handler: ((event: { data: unknown }) => void) | null = null;diff --git a/packages/desktop/tests/utility/pty-host.test.ts b/packages/desktop/tests/utility/pty-host.test.tsindex ac0ae16f5..8e50a5c4c 100644--- a/packages/desktop/tests/utility/pty-host.test.ts+++ b/packages/desktop/tests/utility/pty-host.test.ts@@ -1,4 +1,5 @@import { OK_DESKTOP_TERMINAL_ENV } from '@inkeep/open-knowledge-core';+import { TERMINAL_SHELL_NOTICE_REASONS } from '@inkeep/open-knowledge-core/desktop-bridge';import { describe, expect, test } from 'vitest';import { isTerminalPlatform } from '../../src/shared/terminal-platform.ts';import {@@ -32,12 +33,12 @@ interface FakePty extends PtyProcessLike {pauseCount: number;resumeCount: number;emitData(data: string): void;- emitExit(event: { exitCode: number; signal?: number }): void;+ emitExit(event: { exitCode: number | undefined; signal?: number }): void;}function makeFakePty(): FakePty {let onData: ((data: string) => void) | null = null;- let onExit: ((event: { exitCode: number; signal?: number }) => void) | null = null;+ let onExit: ((event: { exitCode: number | undefined; signal?: number }) => void) | null = null;return {pid: 4242,writes: [],@@ -81,7 +82,11 @@ interface Harness {fire(message: PtyHostIncomingMessage): void;fireRaw(data: unknown): void;posted: PtyHostOutgoingMessage[];- spawnCalls: Array<{ file: string; args: string[]; options: PtySpawnOptions }>;+ spawnCalls: Array<{ file: string; args: string[] | string; options: PtySpawnOptions }>;+ materializedSupportFiles: Array<{+ cwd: string;+ file: NonNullable<import('@inkeep/open-knowledge-core').TerminalLaunchCommand['supportFile']>;+ }>;handle: ReturnType<typeof setupPtyHost>;}@@ -92,11 +97,25 @@ function makeHarness(opts?: {platform?: NodeJS.Platform;userInfoShell?: () => string | null;shellExists?: (path: string) => boolean;- logger?: { warn: (o: Record<string, unknown>) => void };+ pathProbe?: (command: string, env: Record<string, string | undefined>) => string | null;+ listDirectory?: (path: string) => readonly string[];+ cliBinDir?: string;+ logger?: {+ warn: (o: Record<string, unknown>) => void;+ info?: (o: Record<string, unknown>) => void;+ };+ exitHost?: (code: number) => void;+ flushLogger?: () => void;+ shutdownMs?: number;+ materializeSupportFile?: (+ cwd: string,+ file: NonNullable<import('@inkeep/open-knowledge-core').TerminalLaunchCommand['supportFile']>,+ ) => void;}): Harness {let handler: ((event: { data: unknown }) => void) | null = null;const posted: PtyHostOutgoingMessage[] = [];- const spawnCalls: Array<{ file: string; args: string[]; options: PtySpawnOptions }> = [];+ const spawnCalls: Array<{ file: string; args: string[] | string; options: PtySpawnOptions }> = [];+ const materializedSupportFiles: Harness['materializedSupportFiles'] = [];const pty = opts?.pty ?? makeFakePty();const spawn: SpawnPty =opts?.spawn ??@@ -114,10 +133,21 @@ function makeHarness(opts?: {},},spawn,+ exitHost: opts?.exitHost,+ flushLogger: opts?.flushLogger,+ shutdownMs: opts?.shutdownMs,env: opts?.env ?? { SHELL: '/bin/zsh', PATH: '/usr/bin' },platform: opts?.platform ?? 'darwin',userInfoShell: opts?.userInfoShell,shellExists: opts?.shellExists,+ pathProbe: opts?.pathProbe,+ listDirectory: opts?.listDirectory,+ cliBinDir: opts?.cliBinDir,+ materializeSupportFile:+ opts?.materializeSupportFile ??+ ((cwd, file) => {+ materializedSupportFiles.push({ cwd, file });+ }),logger: opts?.logger,});return {@@ -125,6 +155,7 @@ function makeHarness(opts?: {fireRaw: (data) => handler?.({ data }),posted,spawnCalls,+ materializedSupportFiles,handle,};}@@ -163,6 +194,60 @@ describe('setupPtyHost — create', () => {expect(h.spawnCalls[0]?.args).not.toContain('-l');});+ test('Windows prefers the bundled ConPTY dll on the first spawn', () => {+ const h = makeHarness({+ platform: 'win32',+ env: { SystemRoot: 'C:\\Windows' },+ shellExists: () => false,+ pathProbe: () => null,+ });+ h.fire(CREATE({ cwd: 'C:\\project' }));++ expect(h.spawnCalls).toHaveLength(1);+ expect(h.spawnCalls[0]?.options.useConptyDll).toBe(true);+ });++ test('Windows probes pwsh on PATH once per host instead of once per tab', () => {+ let probeCalls = 0;+ const h = makeHarness({+ platform: 'win32',+ env: { SystemRoot: 'C:\\Windows' },+ shellExists: (path) => path === 'C:\\tools\\pwsh.exe',+ pathProbe: () => {+ probeCalls += 1;+ return 'C:\\tools\\pwsh.exe';+ },+ });++ h.fire(CREATE({ ptyId: 'p1', cwd: 'C:\\project' }));+ h.fire(CREATE({ ptyId: 'p2', cwd: 'C:\\project' }));++ expect(probeCalls).toBe(1);+ expect(h.spawnCalls.map((call) => call.file)).toEqual([+ 'C:\\tools\\pwsh.exe',+ 'C:\\tools\\pwsh.exe',+ ]);+ });++ test('Windows retries a PATH probe that did not produce a verdict', () => {+ let probeCalls = 0;+ const h = makeHarness({+ platform: 'win32',+ env: { SystemRoot: 'C:\\Windows' },+ shellExists: () => false,+ pathProbe: () => {+ probeCalls += 1;+ return null;+ },+ listDirectory: () => [],+ });++ h.fire(CREATE({ ptyId: 'p1', cwd: 'C:\\project' }));+ h.fire(CREATE({ ptyId: 'p2', cwd: 'C:\\project' }));++ expect(probeCalls).toBe(2);+ });+test('bakes a launch command into a non-history `-c` spawn with an interactive exec tail', () => {// "Open in <Agent>": the command rides on `-c` (never typed through the line// editor → never written to the user's shell history), and the `exec` tail@@ -329,6 +414,20 @@ describe('setupPtyHost — exit', () => {expect(h.posted.at(-1)).toEqual({ type: 'exit', ptyId: 'e2', exitCode: 0, signal: 9 });});+ test('forwards an undefined native exitCode for main-side normalization', () => {+ const pty = makeFakePty();+ const h = makeHarness({ pty });+ h.fire(CREATE({ ptyId: 'race' }));+ pty.emitExit({ exitCode: undefined });++ expect(h.posted.at(-1)).toEqual({+ type: 'exit',+ ptyId: 'race',+ exitCode: undefined,+ signal: null,+ });+ });+test('a dead pty does not forward late data (active-id guard)', () => {const pty = makeFakePty();const h = makeHarness({ pty });@@ -341,6 +440,85 @@ describe('setupPtyHost — exit', () => {});describe('setupPtyHost — containment (AC5: host survives a PTY failure)', () => {+ test.each([+ 'Cannot find conpty.dll beside conpty.node',+ 'Failed to get conpty.node module handle: 126',+ 'Failed to get conpty.node module file name: 126',+ 'Failed to load conpty.dll: bad image',+ ])('retries deterministic loader failure %s once with the OS backend', (loaderError) => {+ const pty = makeFakePty();+ const calls: PtySpawnOptions[] = [];+ const warnings: Record<string, unknown>[] = [];+ const spawn: SpawnPty = (_file, _args, options) => {+ calls.push(options);+ if (calls.length === 1) throw new Error(loaderError);+ return pty;+ };+ const h = makeHarness({+ spawn,+ platform: 'win32',+ env: { SystemRoot: 'C:\\Windows' },+ shellExists: () => false,+ pathProbe: () => null,+ logger: { warn: (event) => warnings.push(event) },+ });+ h.fire(CREATE({ cwd: 'C:\\project' }));++ expect(calls.map((options) => options.useConptyDll)).toEqual([true, false]);+ expect(warnings).toContainEqual(+ expect.objectContaining({ event: 'pty-host-conpty-dll-fallback' }),+ );+ pty.emitData('fallback alive');+ expect(h.posted).toContainEqual({ type: 'data', ptyId: 'p1', data: 'fallback alive' });+ });++ test('does not retry a non-loader Windows spawn failure', () => {+ const calls: PtySpawnOptions[] = [];+ const spawn: SpawnPty = (_file, _args, options) => {+ calls.push(options);+ throw new Error('EMFILE: too many open files');+ };+ const h = makeHarness({+ spawn,+ platform: 'win32',+ env: { SystemRoot: 'C:\\Windows' },+ shellExists: () => false,+ pathProbe: () => null,+ });+ h.fire(CREATE({ cwd: 'C:\\project' }));++ expect(calls).toHaveLength(1);+ expect(h.posted.at(-1)).toEqual({+ type: 'spawn-error',+ ptyId: 'p1',+ message: 'EMFILE: too many open files',+ });+ });++ test('contains a failed OS-backend retry as the existing spawn-error contract', () => {+ let calls = 0;+ const spawn: SpawnPty = () => {+ calls += 1;+ if (calls === 1) throw new Error('Cannot find conpty.dll beside conpty.node');+ throw new Error('CreatePseudoConsole failed');+ };+ const h = makeHarness({+ spawn,+ platform: 'win32',+ env: { SystemRoot: 'C:\\Windows' },+ shellExists: () => false,+ pathProbe: () => null,+ });+ h.fire(CREATE({ cwd: 'C:\\project' }));++ expect(calls).toBe(2);+ expect(h.posted.at(-1)).toEqual({+ type: 'spawn-error',+ ptyId: 'p1',+ message: 'CreatePseudoConsole failed',+ });+ });+test('a synchronous spawn throw surfaces as spawn-error, not a crash', () => {const spawn: SpawnPty = () => {throw Object.assign(new Error('EMFILE: too many open files'), { code: 'EMFILE' });@@ -556,6 +734,61 @@ describe('setupPtyHost — concurrent sessions', () => {expect(a.killCount).toBe(1);expect(b.killCount).toBe(1);});++ test('an internal shutdown message reaps every session and exits once', () => {+ const a = makeFakePty();+ const b = makeFakePty();+ const ptys = [a, b];+ const exitCodes: number[] = [];+ let flushCount = 0;+ let n = 0;+ const h = makeHarness({+ spawn: () => ptys[n++] ?? makeFakePty(),+ exitHost: (code) => exitCodes.push(code),+ flushLogger: () => {+ flushCount += 1;+ },+ });+ h.fire(CREATE({ ptyId: 'a' }));+ h.fire(CREATE({ ptyId: 'b' }));++ h.fireRaw({ type: 'shutdown' });+ expect(a.killCount).toBe(1);+ expect(b.killCount).toBe(1);+ expect(exitCodes).toEqual([]);++ a.emitExit({ exitCode: 0 });+ expect(exitCodes).toEqual([]);+ b.emitExit({ exitCode: 0 });+ expect(exitCodes).toEqual([0]);+ expect(flushCount).toBe(1);++ h.fireRaw({ type: 'shutdown' });+ expect(a.killCount).toBe(1);+ expect(b.killCount).toBe(1);+ expect(exitCodes).toEqual([0]);+ expect(flushCount).toBe(1);+ });++ test('shutdown exits on the host-local deadline when a deferred Windows kill never exits', async () => {+ const pty = makeFakePty();+ const exitCodes: number[] = [];+ const warnings: Record<string, unknown>[] = [];+ const h = makeHarness({+ pty,+ shutdownMs: 1,+ exitHost: (code) => exitCodes.push(code),+ logger: { warn: (event) => warnings.push(event) },+ });+ h.fire(CREATE());++ h.fireRaw({ type: 'shutdown' });+ await new Promise((resolve) => setTimeout(resolve, 10));++ expect(pty.killCount).toBe(1);+ expect(exitCodes).toEqual([0]);+ expect(warnings).toContainEqual({ event: 'pty-host-shutdown-deadline', remaining: 1 });+ });});describe('setupPtyHost — incoming message validation (asIncomingMessage guard)', () => {@@ -602,7 +835,128 @@ describe('setupPtyHost — incoming message validation (asIncomingMessage guard)expect(h.spawnCalls[0]?.args).toEqual(['-l', '-i', '-c', "x 'y'; exec '/bin/zsh' -l -i"]);});- test('drops a create whose launchCommand is present but not a string', () => {+ test('accepts a structured Windows launch and composes it after shell resolution', () => {+ const h = makeHarness({+ platform: 'win32',+ env: { SystemRoot: 'C:\\Windows', ComSpec: 'C:\\Windows\\System32\\cmd.exe' },+ shellExists: () => false,+ pathProbe: () => null,+ listDirectory: () => [],+ });+ h.fireRaw({+ type: 'create',+ ptyId: 'p1',+ cwd: 'C:\\project',+ cols: 80,+ rows: 24,+ launchCommand: { executable: 'claude', args: [] },+ });+ expect(h.spawnCalls).toHaveLength(1);+ expect(h.spawnCalls[0]?.args).toBe('/K claude');+ });++ test('materializes Claude settings beneath the cwd before composing a cmd-safe launch', () => {+ const h = makeHarness({+ platform: 'win32',+ env: { SystemRoot: 'C:\\Windows', ComSpec: 'C:\\Windows\\System32\\cmd.exe' },+ shellExists: () => false,+ pathProbe: () => null,+ listDirectory: () => [],+ });+ const supportFile = {+ kind: 'claude-settings' as const,+ relativePath: '.ok/local/terminal/claude-settings-mcp-tools.json',+ contents: '{"enabledMcpjsonServers":["open-knowledge"]}',+ };+ h.fireRaw({+ type: 'create',+ ptyId: 'p1',+ cwd: 'C:\\project',+ cols: 80,+ rows: 24,+ launchCommand: {+ executable: 'claude',+ args: ['--settings', supportFile.relativePath],+ supportFile,+ },+ });++ expect(h.materializedSupportFiles).toEqual([{ cwd: 'C:\\project', file: supportFile }]);+ expect(h.spawnCalls[0]?.args).toBe(+ '/K claude --settings .ok/local/terminal/claude-settings-mcp-tools.json',+ );+ });++ test('opens a bare Claude launch when the settings support file cannot be written', () => {+ const logger = makeLogger();+ const h = makeHarness({+ platform: 'win32',+ env: { SystemRoot: 'C:\\Windows', ComSpec: 'C:\\Windows\\System32\\cmd.exe' },+ shellExists: () => false,+ pathProbe: () => null,+ listDirectory: () => [],+ logger,+ materializeSupportFile: () => {+ throw Object.assign(new Error('EROFS: read-only file system'), { code: 'EROFS' });+ },+ });+ h.fireRaw({+ type: 'create',+ ptyId: 'p1',+ cwd: 'C:\\project',+ cols: 80,+ rows: 24,+ launchCommand: {+ executable: 'claude',+ args: ['--settings', '.ok/local/terminal/claude-settings-mcp-tools.json'],+ supportFile: {+ kind: 'claude-settings',+ relativePath: '.ok/local/terminal/claude-settings-mcp-tools.json',+ contents: '{"enabledMcpjsonServers":["open-knowledge"]}',+ },+ },+ });++ expect(h.posted.filter((m) => m.type === 'spawn-error')).toHaveLength(0);+ expect(h.spawnCalls).toHaveLength(1);+ expect(h.spawnCalls[0]?.args).toBe('/K claude');+ expect(+ logger.warnings.some((w) => w.event === 'pty-host-support-file-materialize-failed'),+ ).toBe(true);+ expect(h.posted).toContainEqual({+ type: 'shell-notice',+ ptyId: 'p1',+ notice: 'support-file-degraded',+ reason: 'write-failed',+ });+ });++ test('rejects a support-file path outside the owned terminal settings directory', () => {+ const logger = makeLogger();+ const h = makeHarness({ logger });+ h.fireRaw({+ type: 'create',+ ptyId: 'p1',+ cwd: '/x',+ cols: 80,+ rows: 24,+ launchCommand: {+ executable: 'claude',+ args: ['--settings', '../../settings.json'],+ supportFile: {+ kind: 'claude-settings',+ relativePath: '../../settings.json',+ contents: '{}',+ },+ },+ });++ expect(h.spawnCalls).toHaveLength(0);+ expect(h.materializedSupportFiles).toHaveLength(0);+ expect(logger.warnings.length).toBeGreaterThan(0);+ });++ test('drops a create whose launchCommand has neither supported shape', () => {const logger = makeLogger();const h = makeHarness({ logger });h.fireRaw({ type: 'create', ptyId: 'p1', cwd: '/x', cols: 80, rows: 24, launchCommand: 123 });@@ -617,6 +971,54 @@ describe('setupPtyHost — incoming message validation (asIncomingMessage guard)expect(h.spawnCalls).toHaveLength(0);expect(logger.warnings.length).toBeGreaterThan(0);});++ // The guard's accepted set is built from the same vocabulary tuple the union+ // derives from, so a reason added to that vocabulary survives this hop+ // without a second edit here. A hand-mirrored literal chain would drop the+ // whole create instead, killing the spawn rather than just the notice.+ test.each([+ ...TERMINAL_SHELL_NOTICE_REASONS,+ ])('accepts a create carrying the shared reason %s and relays it verbatim', (reason) => {+ const h = makeHarness({+ platform: 'win32',+ env: { SystemRoot: 'C:\\Windows' },+ shellExists: () => false,+ pathProbe: () => null,+ listDirectory: () => [],+ });++ h.fireRaw({+ type: 'create',+ ptyId: 'p1',+ cwd: 'C:\\project',+ cols: 80,+ rows: 24,+ shellInvalidReason: reason,+ });++ expect(h.spawnCalls).toHaveLength(1);+ expect(h.posted).toContainEqual({+ type: 'shell-notice',+ ptyId: 'p1',+ notice: 'invalid-shell-override',+ reason,+ });+ });++ test('drops a create whose shellInvalidReason is outside the shared reason set', () => {+ const logger = makeLogger();+ const h = makeHarness({ logger });+ h.fireRaw({+ type: 'create',+ ptyId: 'p1',+ cwd: '/x',+ cols: 80,+ rows: 24,+ shellInvalidReason: 'config-unreadable-ish',+ });+ expect(h.spawnCalls).toHaveLength(0);+ expect(logger.warnings.length).toBeGreaterThan(0);+ });});describe('buildShellArgs', () => {@@ -683,6 +1085,22 @@ describe('buildShellEnv', () => {[OK_DESKTOP_TERMINAL_ENV]: '1',});});++ test('win32 prepends the packaged CLI bin using the inherited PATH key casing', () => {+ const env = buildShellEnv(+ {+ Path: 'C:\\Windows\\System32;C:\\Tools',+ HOME: 'C:\\Users\\alice',+ },+ { platform: 'win32', cliBinDir: 'C:\\Program Files\\Open Knowledge\\resources\\cli\\bin' },+ );++ expect(env.Path).toBe(+ 'C:\\Program Files\\Open Knowledge\\resources\\cli\\bin;C:\\Windows\\System32;C:\\Tools',+ );+ expect(env.PATH).toBeUndefined();+ expect(env.Path).not.toContain('.ok\\bin');+ });});describe('resolveShell', () => {@@ -797,6 +1215,408 @@ describe('resolveShell', () => {),).toBe('/bin/bash');});++ describe('win32 ladder', () => {+ const programFilesPwsh = 'C:\\Program Files\\PowerShell\\7\\pwsh.exe';+ const windowsPowerShell = 'C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe';+ const cmd = 'C:\\Windows\\System32\\cmd.exe';+ const baseEnv = {+ ProgramFiles: 'C:\\Program Files',+ SystemRoot: 'C:\\Windows',+ LOCALAPPDATA: 'C:\\Users\\alice\\AppData\\Local',+ PATH: 'C:\\Windows\\System32',+ PATHEXT: '.COM;.EXE;.BAT;.CMD',+ };++ test('honors an existing absolute override before probing PATH', () => {+ let probes = 0;+ expect(+ resolveShell(baseEnv, {+ platform: 'win32',+ override: 'D:\\Shells\\pwsh.exe',+ shellExists: shellExists(['D:\\Shells\\pwsh.exe']),+ pathProbe: () => {+ probes += 1;+ return 'C:\\PATH\\pwsh.exe';+ },+ }),+ ).toBe('D:\\Shells\\pwsh.exe');+ expect(probes).toBe(0);+ });++ test('uses the PATHEXT-aware PATH probe before known-install backstops', () => {+ expect(+ resolveShell(baseEnv, {+ platform: 'win32',+ pathProbe: (command, env) => {+ expect(command).toBe('pwsh');+ expect(env.PATHEXT).toBe('.COM;.EXE;.BAT;.CMD');+ return 'D:\\Portable\\pwsh.exe';+ },+ shellExists: shellExists(['D:\\Portable\\pwsh.exe', programFilesPwsh]),+ }),+ ).toBe('D:\\Portable\\pwsh.exe');+ });++ test('falls back to the Program Files PowerShell 7 install', () => {+ expect(+ resolveShell(baseEnv, {+ platform: 'win32',+ pathProbe: () => null,+ shellExists: shellExists([programFilesPwsh]),+ }),+ ).toBe(programFilesPwsh);+ });++ test('scans the WindowsApps PowerShell package aliases after Program Files', () => {+ const windowsApps = 'C:\\Users\\alice\\AppData\\Local\\Microsoft\\WindowsApps';+ const alias = `${windowsApps}\\Microsoft.PowerShell_8wekyb3d8bbwe\\pwsh.exe`;+ expect(+ resolveShell(baseEnv, {+ platform: 'win32',+ pathProbe: () => null,+ listDirectory: (path) =>+ path === windowsApps ? ['Other.App_123', 'Microsoft.PowerShell_8wekyb3d8bbwe'] : [],+ shellExists: shellExists([alias]),+ }),+ ).toBe(alias);+ });++ test('falls through to Windows PowerShell 5.1', () => {+ expect(+ resolveShell(baseEnv, {+ platform: 'win32',+ pathProbe: () => null,+ listDirectory: () => [],+ shellExists: shellExists([windowsPowerShell]),+ }),+ ).toBe(windowsPowerShell);+ });++ test('uses a case-insensitive ComSpec key before the cmd.exe floor', () => {+ expect(+ resolveShell(+ { ...baseEnv, ComSpec: undefined, cOmSpEc: 'D:\\Windows\\cmd.exe' },+ {+ platform: 'win32',+ pathProbe: () => null,+ listDirectory: () => [],+ shellExists: shellExists(['D:\\Windows\\cmd.exe']),+ },+ ),+ ).toBe('D:\\Windows\\cmd.exe');+ });++ test('uses the absolute cmd.exe floor and never consults SHELL', () => {+ expect(+ resolveShell(+ { ...baseEnv, SHELL: '/bin/zsh' },+ {+ platform: 'win32',+ pathProbe: () => null,+ listDirectory: () => [],+ shellExists: shellExists([]),+ },+ ),+ ).toBe(cmd);+ });++ test('empty and whitespace overrides are unset without an invalid-override notice', () => {+ for (const override of ['', ' ', '\t']) {+ const h = makeHarness({+ platform: 'win32',+ env: baseEnv,+ shellExists: shellExists([windowsPowerShell]),+ pathProbe: () => null,+ listDirectory: () => [],+ });+ h.fire(CREATE({ shell: override }));+ expect(h.spawnCalls[0]?.file).toBe(windowsPowerShell);+ expect(h.posted).not.toContainEqual(+ expect.objectContaining({+ type: 'shell-notice',+ ptyId: 'p1',+ notice: 'invalid-shell-override',+ reason: expect.any(String),+ }),+ );+ }+ });++ test('an invalid override logs, emits a notice, and continues down the ladder', () => {+ const warnings: Record<string, unknown>[] = [];+ const h = makeHarness({+ platform: 'win32',+ env: baseEnv,+ shellExists: shellExists([windowsPowerShell]),+ pathProbe: () => null,+ listDirectory: () => [],+ logger: { warn: (entry) => warnings.push(entry) },+ });++ h.fire(CREATE({ shell: 'C:\\Missing\\pwsh.exe' }));++ expect(h.spawnCalls[0]?.file).toBe(windowsPowerShell);+ expect(h.posted).toContainEqual({+ type: 'shell-notice',+ ptyId: 'p1',+ notice: 'invalid-shell-override',+ reason: 'not-found',+ });+ expect(warnings).toContainEqual(+ expect.objectContaining({+ event: 'pty-host-shell-override-invalid',+ platform: 'win32',+ reason: 'not-found',+ }),+ );+ });++ test('logs the selected bounded-cardinality ladder rung', () => {+ const entries: Record<string, unknown>[] = [];+ const h = makeHarness({+ platform: 'win32',+ env: baseEnv,+ shellExists: shellExists([programFilesPwsh]),+ pathProbe: () => null,+ logger: { warn: () => {}, info: (entry) => entries.push(entry) },+ });++ h.fire(CREATE());++ expect(entries).toContainEqual({+ event: 'pty-host-shell-resolved',+ platform: 'win32',+ rung: 'pwsh-known-install',+ });+ });+ });+});++test('buildShellArgs uses empty argv for every win32 shell rung', () => {+ expect(buildShellArgs('win32', 'C:\\Program Files\\PowerShell\\7\\pwsh.exe')).toEqual([]);+ expect(buildShellArgs('win32', 'C:\\Windows\\System32\\cmd.exe')).toEqual([]);+ expect(buildShellArgs('win32', 'C:\\Program Files\\Git\\bin\\bash.exe')).toEqual([]);+});++describe('buildShellArgs Windows launch composition', () => {+ test('PowerShell uses -NoExit + EncodedCommand and preserves structured JSON', () => {+ const args = buildShellArgs('win32', 'C:\\Program Files\\PowerShell\\7\\pwsh.exe', {+ executable: 'native.exe',+ args: ['--settings', '{"nested":"a\'b"}'],+ });+ expect(Array.isArray(args)).toBe(true);+ if (!Array.isArray(args)) throw new Error('expected PowerShell argv');+ expect(args.slice(0, 2)).toEqual(['-NoExit', '-EncodedCommand']);+ expect(Buffer.from(args[2] ?? '', 'base64').toString('utf16le')).toBe(+ "& 'native.exe' '--settings' '{\"nested\":\"a''b\"}'",+ );+ });++ test('cmd uses node-pty string mode so CRT quote remarshal is bypassed', () => {+ expect(+ buildShellArgs('win32', 'C:\\Windows\\System32\\cmd.exe', {+ executable: 'claude',+ args: [],+ }),+ ).toBe('/K claude');+ });++ test('Git Bash preserves the structured launch through parser-inert base64 arguments', () => {+ const shell = 'C:\\Program Files\\Git\\bin\\bash.exe';+ const launchTokens = [+ 'codex',+ '-c',+ 'mcp_servers.open-knowledge.default_tools_approval_mode=approve',+ "apostrophe'and space",+ ];+ const args = buildShellArgs('win32', shell, {+ executable: launchTokens[0] ?? '',+ args: launchTokens.slice(1),+ });+ expect(Array.isArray(args)).toBe(true);+ if (!Array.isArray(args)) throw new Error('expected Git Bash argv');++ expect(args.slice(0, 3)).toEqual(['--login', '-i', '-c']);+ expect(args[3]).toContain('base64 -d');+ expect(args[4]).toBe('bash');+ expect(+ Buffer.from(args[5] ?? '', 'base64')+ .toString('utf8')+ .split('\u0000'),+ ).toEqual([...launchTokens, '']);+ });++ test('the host reports the resolved Windows shell family before spawning', () => {+ const h = makeHarness({+ platform: 'win32',+ env: { SystemRoot: 'C:\\Windows', ProgramFiles: 'C:\\Program Files' },+ shellExists: (path) => path.endsWith('pwsh.exe'),+ });+ h.fire(CREATE());+ expect(h.posted).toContainEqual({+ type: 'shell-notice',+ ptyId: 'p1',+ notice: 'shell-resolved',+ shellFamily: 'powershell',+ });+ });++ test('an unsupported override degrades a structured launch to a plain interactive shell', () => {+ const warnings: Record<string, unknown>[] = [];+ const h = makeHarness({+ platform: 'win32',+ env: { SystemRoot: 'C:\\Windows', ProgramFiles: 'C:\\Program Files' },+ shellExists: (path) => ['C:\\Tools\\fish.exe', 'C:\\Tools\\pwsh.exe'].includes(path),+ logger: { warn: (entry) => warnings.push(entry) },+ });++ h.fire(+ CREATE({+ shell: 'C:\\Tools\\fish.exe',+ launchCommand: {+ executable: 'claude',+ args: ['--settings', '.ok/local/terminal/claude-settings-mcp-tools.json'],+ supportFile: {+ kind: 'claude-settings',+ relativePath: '.ok/local/terminal/claude-settings-mcp-tools.json',+ contents: '{"enabledMcpjsonServers":["open-knowledge"]}',+ },+ },+ }),+ );++ expect(h.spawnCalls).toHaveLength(1);+ expect(h.spawnCalls[0]?.file).toBe('C:\\Tools\\fish.exe');+ expect(h.spawnCalls[0]?.args).toEqual([]);+ expect(h.materializedSupportFiles).toHaveLength(0);+ expect(h.posted).toContainEqual({+ type: 'shell-notice',+ ptyId: 'p1',+ notice: 'invalid-shell-override',+ reason: 'unsupported-family',+ });+ expect(h.posted).not.toContainEqual(expect.objectContaining({ type: 'spawn-error' }));+ expect(warnings).toContainEqual(+ expect.objectContaining({+ event: 'pty-host-launch-degraded-unsupported-shell',+ platform: 'win32',+ rung: 'override',+ }),+ );++ h.fire(+ CREATE({+ ptyId: 'p2',+ shell: 'C:\\Tools\\pwsh.exe',+ launchCommand: { executable: 'claude', args: [] },+ }),+ );+ expect(h.spawnCalls).toHaveLength(2);+ expect(h.spawnCalls[1]?.file).toBe('C:\\Tools\\pwsh.exe');+ expect(h.spawnCalls[1]?.args).not.toEqual([]);+ });++ test('an unsupported override also degrades a managed command tab to a plain shell', () => {+ const h = makeHarness({+ platform: 'win32',+ env: { SystemRoot: 'C:\\Windows' },+ shellExists: (path) => ['C:\\Tools\\fish.exe', 'C:\\Tools\\pwsh.exe'].includes(path),+ });++ h.fire(+ CREATE({+ shell: 'C:\\Tools\\fish.exe',+ launchCommand: { executable: 'git', args: ['status'] },+ }),+ );++ expect(h.spawnCalls).toHaveLength(1);+ expect(h.spawnCalls[0]).toMatchObject({ file: 'C:\\Tools\\fish.exe', args: [] });+ expect(h.posted).toContainEqual({+ type: 'shell-notice',+ ptyId: 'p1',+ notice: 'invalid-shell-override',+ reason: 'unsupported-family',+ });+ expect(h.posted).not.toContainEqual(expect.objectContaining({ type: 'spawn-error' }));++ h.fire(+ CREATE({+ ptyId: 'p2',+ shell: 'C:\\Tools\\pwsh.exe',+ launchCommand: { executable: 'git', args: ['status'] },+ }),+ );+ expect(h.spawnCalls).toHaveLength(2);+ expect(h.spawnCalls[1]?.file).toBe('C:\\Tools\\pwsh.exe');+ expect(h.spawnCalls[1]?.args).not.toEqual([]);+ });++ test('a structured launch composition failure aborts only that create request', () => {+ const warnings: Record<string, unknown>[] = [];+ const h = makeHarness({+ platform: 'win32',+ env: { SystemRoot: 'C:\\Windows' },+ shellExists: (path) => path === 'C:\\Tools\\pwsh.exe',+ logger: { warn: (entry) => warnings.push(entry) },+ });++ h.fire(+ CREATE({+ shell: 'C:\\Tools\\pwsh.exe',+ launchCommand: { executable: 'agent.cmd', args: ['safe', '" & calc & "'] },+ }),+ );++ expect(h.spawnCalls).toHaveLength(0);+ expect(h.posted).toContainEqual(+ expect.objectContaining({+ type: 'spawn-error',+ ptyId: 'p1',+ message: expect.stringMatching(/unsafe batch argument/),+ }),+ );+ expect(warnings).toContainEqual(+ expect.objectContaining({+ event: 'pty-host-launch-compose-failed',+ platform: 'win32',+ rung: 'override',+ }),+ );++ h.fire(CREATE({ ptyId: 'p2', shell: 'C:\\Tools\\pwsh.exe' }));+ expect(h.spawnCalls).toHaveLength(1);+ expect(h.spawnCalls[0]?.file).toBe('C:\\Tools\\pwsh.exe');+ });++ test('an unsupported override keeps plain tabs usable with a capability notice', () => {+ const warnings: Record<string, unknown>[] = [];+ const h = makeHarness({+ platform: 'win32',+ env: { SystemRoot: 'C:\\Windows' },+ shellExists: (path) => path === 'C:\\Tools\\fish.exe',+ logger: { warn: (entry) => warnings.push(entry) },+ });++ h.fire(CREATE({ shell: 'C:\\Tools\\fish.exe' }));++ expect(h.spawnCalls[0]?.file).toBe('C:\\Tools\\fish.exe');+ expect(h.posted).toContainEqual({+ type: 'shell-notice',+ ptyId: 'p1',+ notice: 'invalid-shell-override',+ reason: 'unsupported-family',+ });+ expect(h.posted).not.toContainEqual(+ expect.objectContaining({ type: 'shell-notice', notice: 'shell-resolved' }),+ );+ expect(warnings).toContainEqual({+ event: 'pty-host-shell-override-capability-limited',+ platform: 'win32',+ reason: 'unsupported-family',+ });+ });});describe('node-pty import failure', () => {diff --git a/packages/desktop/tests/utility/pty-readiness.test.ts b/packages/desktop/tests/utility/pty-readiness.test.tsnew file mode 100644index 000000000..6f8c4ece6--- /dev/null+++ b/packages/desktop/tests/utility/pty-readiness.test.ts@@ -0,0 +1,304 @@+import { describe, expect, test } from 'vitest';+import type { PtyProcessLike, PtySpawnOptions, SpawnPty } from '../../src/utility/pty-host.ts';+import {+ buildCwdFileProofCommand,+ createPtyHostProbe,+ type PtyStream,+ waitForCondition,+ waitForShellReady,+} from '../support/pty-readiness.test-helper.ts';++/**+ * Contract for the real-shell harness's readiness gate and its failure channel.+ * Platform timing rationale lives on the helper; these tests pin that a+ * still-starting shell is not ready and a dead shell fails diagnostically.+ */++interface FakeStream extends PtyStream {+ emit(chunk: string): void;+ fail(reason: string): void;+}++function createFakeStream(): FakeStream {+ let text = '';+ let failure: string | null = null;+ return {+ read: () => text,+ failure: () => failure,+ emit(chunk) {+ text += chunk;+ },+ fail(reason) {+ failure = reason;+ },+ };+}++/** Sample every 5ms and require 100ms of quiet — long enough to span the gaps below. */+const FAST_READY = { intervalMs: 5, quietSamples: 20, timeoutMs: 5_000 } as const;++describe('shell readiness gate', () => {+ test('does not report ready while the shell is still producing startup output', async () => {+ const stream = createFakeStream();+ // ConPTY shape: the setup paint lands first, the shell's own startup output+ // follows in bursts, and the prompt is last.+ stream.emit('\u001b[2J\u001b[H');+ const chunks = ['loading profile\r\n', 'startup notice\r\n', 'PS C:\\project> '];+ const timers = chunks.map((chunk, index) =>+ setTimeout(() => stream.emit(chunk), (index + 1) * 40),+ );+ try {+ await waitForShellReady(stream, 'shell ready', FAST_READY);+ expect(stream.read()).toContain('PS C:\\project> ');+ } finally {+ for (const timer of timers) clearTimeout(timer);+ }+ });++ test('reports ready once the stream settles instead of waiting out the budget', async () => {+ const stream = createFakeStream();+ stream.emit('PS C:\\project> ');+ const started = Date.now();+ await waitForShellReady(stream, 'shell ready', FAST_READY);+ expect(Date.now() - started).toBeLessThan(1_000);+ });++ test('never reports a silent shell ready', async () => {+ const stream = createFakeStream();+ await expect(+ waitForShellReady(stream, 'shell ready', { intervalMs: 5, quietSamples: 3, timeoutMs: 120 }),+ ).rejects.toThrow(/shell ready/u);+ });++ test('surfaces a spawn failure that lands during startup', async () => {+ const stream = createFakeStream();+ stream.emit('\u001b[2J');+ const timer = setTimeout(() => stream.fail('spawn-error: File not found'), 20);+ try {+ await expect(waitForShellReady(stream, 'shell ready', FAST_READY)).rejects.toThrow(+ /File not found/u,+ );+ } finally {+ clearTimeout(timer);+ }+ });+});++describe('cwd file proof command', () => {+ test('reads a relative sentinel without embedding its random contents', () => {+ expect(buildCwdFileProofCommand('win32', '.ok-cwd-proof')).toBe(+ `Write-Output "CWD_PROOF=$(Get-Content -Raw -LiteralPath './.ok-cwd-proof')"`,+ );+ expect(buildCwdFileProofCommand('linux', '.ok-cwd-proof')).toBe(+ `printf 'CWD_PROOF=%s\\n' "$(cat './.ok-cwd-proof')"`,+ );+ });++ test('rejects a sentinel name that could inject shell syntax', () => {+ expect(() => buildCwdFileProofCommand('win32', "proof'; exit 1")).toThrow(+ /invalid cwd proof file name/u,+ );+ });+});++describe('condition waits', () => {+ test('surfaces a spawn failure instead of expiring as a timeout', async () => {+ const stream = createFakeStream();+ const timer = setTimeout(() => stream.fail('spawn-error: posix_spawnp failed'), 20);+ const started = Date.now();+ try {+ await expect(+ waitForCondition(stream, () => false, 'evaluated command output', {+ intervalMs: 5,+ timeoutMs: 3_000,+ }),+ ).rejects.toThrow(/posix_spawnp failed/u);+ expect(Date.now() - started).toBeLessThan(1_000);+ } finally {+ clearTimeout(timer);+ }+ });++ test('surfaces an early exit instead of expiring as a timeout', async () => {+ const stream = createFakeStream();+ const timer = setTimeout(() => stream.fail('exited (code 1, signal none)'), 20);+ try {+ await expect(+ waitForCondition(stream, () => false, 'evaluated command output', {+ intervalMs: 5,+ timeoutMs: 3_000,+ }),+ ).rejects.toThrow(/exited \(code 1/u);+ } finally {+ clearTimeout(timer);+ }+ });++ test('reads an awaited exit as success rather than as a failure', async () => {+ const stream = createFakeStream();+ stream.fail('exited (code 1, signal none)');+ await expect(+ waitForCondition(stream, () => true, 'failure for unspawnable shell', {+ intervalMs: 5,+ timeoutMs: 200,+ }),+ ).resolves.toBeUndefined();+ });++ test('names what did arrive when a condition times out', async () => {+ const stream = createFakeStream();+ stream.emit('PS C:\\project> Write-Output "HARNESS_$((6*7))_DONE"');+ await expect(+ waitForCondition(stream, () => false, 'evaluated command output', {+ intervalMs: 5,+ timeoutMs: 60,+ }),+ ).rejects.toThrow(/HARNESS_/u);+ });+});++/**+ * A shell whose console input reader attaches some time after its first bytes,+ * dropping anything written before then — the ConPTY behavior the Windows+ * failure came from, reproduced deterministically on any platform.+ */+function evaluateFakePowerShellCommand(command: string): string | null {+ const arithmetic = /^Write-Output "([^"]*)_\$\(\((\d+)\*(\d+)\)\)_([^"]*)"$/u.exec(command);+ if (arithmetic !== null) {+ return `${arithmetic[1]}_${Number(arithmetic[2]) * Number(arithmetic[3])}_${arithmetic[4]}`;+ }+ return /^Write-Output "([^"]*)"$/u.exec(command)?.[1] ?? null;+}++function createStartupRaceSpawn(readyAfterMs: number): SpawnPty {+ return (_file: string, _args: string[] | string, _options: PtySpawnOptions): PtyProcessLike => {+ let emit: (data: string) => void = () => undefined;+ let accepting = false;+ const timers = [+ setTimeout(() => emit('loading profile\r\n'), readyAfterMs / 2),+ setTimeout(() => {+ accepting = true;+ emit('PS C:\\project> ');+ }, readyAfterMs),+ ];+ queueMicrotask(() => emit('\u001b[2J\u001b[H'));+ return {+ pid: 4242,+ onData(listener) {+ emit = listener;+ },+ onExit() {+ // The fake shell never exits on its own.+ },+ write(data) {+ if (!accepting) return;+ const typed = data.replace(/\r$/u, '');+ emit(`${typed}\r\n`);+ const output = evaluateFakePowerShellCommand(typed);+ if (output === null) return;+ timers.push(setTimeout(() => emit(`${output}\r\n`), 0));+ },+ resize() {+ // No geometry to track.+ },+ kill() {+ for (const timer of timers) clearTimeout(timer);+ },+ pause() {+ // No backpressure to model.+ },+ resume() {+ // No backpressure to model.+ },+ };+ };+}++describe('driving a real host through a shell that starts slowly', () => {+ test('the command lands because the drive waits for the read loop', async () => {+ const host = createPtyHostProbe({+ spawn: createStartupRaceSpawn(60),+ env: { PATH: '/usr/bin', SHELL: '/bin/sh' },+ platform: 'linux',+ shellExists: () => true,+ });+ const io = host.streamOf('io');+ try {+ host.send({ type: 'create', ptyId: 'io', cwd: '/tmp', cols: 80, rows: 24 });+ await waitForShellReady(io, 'interactive shell ready', FAST_READY);+ host.send({+ type: 'input',+ ptyId: 'io',+ data: 'Write-Output "HARNESS_$((6*7))_DONE"\r',+ });+ await waitForCondition(io, () => io.read().includes('HARNESS_42_DONE'), 'command output', {+ intervalMs: 5,+ timeoutMs: 2_000,+ });+ } finally {+ host.killActive();+ }+ });++ test('maps a real host spawn failure into the readiness failure channel', async () => {+ const host = createPtyHostProbe({+ spawn: () => {+ throw new Error('EMFILE: too many open files');+ },+ env: { PATH: '/usr/bin', SHELL: '/bin/sh' },+ platform: 'linux',+ shellExists: () => true,+ });+ const io = host.streamOf('io');+ try {+ host.send({ type: 'create', ptyId: 'io', cwd: '/tmp', cols: 80, rows: 24 });+ await expect(+ waitForCondition(io, () => false, 'shell ready', { intervalMs: 5, timeoutMs: 100 }),+ ).rejects.toThrow(/shell failed before shell ready: spawn-error: EMFILE/u);+ } finally {+ host.killActive();+ }+ });++ test('maps a real host exit into the readiness failure channel', async () => {+ const spawn: SpawnPty = () => ({+ pid: 4243,+ onData() {+ // This shell exits before producing output.+ },+ onExit(listener) {+ queueMicrotask(() => listener({ exitCode: 3, signal: undefined }));+ },+ write() {+ // The shell exits before accepting input.+ },+ resize() {+ // No geometry to track.+ },+ kill() {+ // Already exited.+ },+ pause() {+ // No backpressure to model.+ },+ resume() {+ // No backpressure to model.+ },+ });+ const host = createPtyHostProbe({+ spawn,+ env: { PATH: '/usr/bin', SHELL: '/bin/sh' },+ platform: 'linux',+ shellExists: () => true,+ });+ const io = host.streamOf('io');+ try {+ host.send({ type: 'create', ptyId: 'io', cwd: '/tmp', cols: 80, rows: 24 });+ await expect(+ waitForCondition(io, () => false, 'shell ready', { intervalMs: 5, timeoutMs: 100 }),+ ).rejects.toThrow(/shell failed before shell ready: exited \(code 3, signal none\)/u);+ } finally {+ host.killActive();+ }+ });+});diff --git a/packages/server/src/lint-plugins/require-windowshide-on-spawn.test.ts b/packages/server/src/lint-plugins/require-windowshide-on-spawn.test.tsindex 220170766..7f42243ff 100644--- a/packages/server/src/lint-plugins/require-windowshide-on-spawn.test.ts+++ b/packages/server/src/lint-plugins/require-windowshide-on-spawn.test.ts@@ -64,11 +64,10 @@ describe('require-windowshide-on-spawn GritQL plugin', () => {expect(matchingOverride).toBeDefined();const includes = matchingOverride?.includes ?? [];- // Scoped to server + cli runtime spawns; desktop has separate launch- // wrappers and coverage. Tests are excluded.+ // Scoped to every package with runtime Windows spawns. Tests are excluded.expect(includes).toContain('packages/server/src/**/*.ts');expect(includes).toContain('packages/cli/src/**/*.ts');- expect(includes).not.toContain('packages/desktop/src/**/*.ts');+ expect(includes).toContain('packages/desktop/src/**/*.ts');expect(includes).toContain('!**/*.test.ts');// Fixture self-include so this test's positive cases still trigger.expect(includes).toContain(diff --git a/packages/server/src/spawn-cursor-api.ts b/packages/server/src/spawn-cursor-api.tsindex 107d6bde2..4ecc011ac 100644--- a/packages/server/src/spawn-cursor-api.ts+++ b/packages/server/src/spawn-cursor-api.ts@@ -394,7 +394,7 @@ export function resolveCursorSpawnInvocation(* platform. Lexical comparison only (no symlink resolution); a symlink inside* `contentDir` that targets outside (`<dir>/notes -> /etc`) passes here, and* the OS will follow it at use time. Same constraint as- * `isPathWithinProject` in `packages/desktop/src/main/path-containment.ts`.+ * `isPathWithinProject` in `packages/desktop/src/shared/path-containment.ts`.*/export function isPathWithinDir(userPath: string,