Beautiful, AI-native markdown IDE and LLM wiki
TypeScript 2nd-brainagent-skillsclaudecodexcompany-braindocsknowledge-knowledge-baseknowledge-managementllmllm-wikillm-wiki-karpathymarkdownmarkdown-editormdmdxnotespkmsecond-brainskills
feat(ok): support Linux terminals (PRD-8002) (#3648)
serafin-garcia7d5af88068a2
diff --git a/.changeset/linux-terminal-support.md b/.changeset/linux-terminal-support.mdnew file mode 100644index 000000000..93eb392a7--- /dev/null+++ b/.changeset/linux-terminal-support.md@@ -0,0 +1,5 @@+---+"@inkeep/open-knowledge": minor+---++OpenKnowledge Desktop now supports the docked terminal on Linux deb and rpm installs. Linux packages include the upstream N-API `node-pty` prebuild for x64 and arm64, use Linux-native shell selection, expose the existing terminal controls, and preserve terminal copy and paste through Linux keyboard conventions.diff --git a/.github/workflows/desktop-build-win-linux.yml b/.github/workflows/desktop-build-win-linux.ymlindex d9b5293b7..6526c624b 100644--- a/.github/workflows/desktop-build-win-linux.yml+++ b/.github/workflows/desktop-build-win-linux.yml@@ -325,9 +325,11 @@ jobs:- runner: ubuntu-latestarch: x64targets: deb:x64 rpm:x64+ unpacked_dir: linux-unpacked- runner: ubuntu-24.04-armarch: arm64targets: deb:arm64 rpm:arm64+ unpacked_dir: linux-arm64-unpackedsteps:- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2@@ -409,6 +411,12 @@ jobs:pnpm exec electron-builder --linux ${{ matrix.targets }} --publish never \--config electron-builder.linux.yml+ - name: Assert Linux terminal native package compatibility+ working-directory: packages/desktop+ env:+ OK_LINUX_PACKAGE_DIR: dist-desktop/${{ matrix.unpacked_dir }}+ run: pnpm exec vitest run tests/unit/linux-package-native-guards.test.ts+# Fail before uploading an installer that cannot start (see the Windows# step for the full rationale). This is the control that would have caught# the 0.42.2 arm64 deb, which installed cleanly and then died ondiff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.mdindex 2d53bc026..71431ce2a 100644--- a/THIRD_PARTY_NOTICES.md+++ b/THIRD_PARTY_NOTICES.md@@ -4607,7 +4607,7 @@ Homepage: https://github.com/prebuild/node-gyp-buildCopyright (c) 2017 Mathias Buus-### `[email protected]`+### `[email protected]`Homepage: https://github.com/microsoft/node-ptyCopyright (c) 2012-2015, Christopher Jeffrey (https://github.com/chjj/)diff --git a/docs/content/features/editor.mdx b/docs/content/features/editor.mdxindex 875d244fc..7955eb694 100644--- a/docs/content/features/editor.mdx+++ b/docs/content/features/editor.mdx@@ -102,9 +102,9 @@ Select text in the WYSIWYG editor and the selection bubble menu shows a **Commen## Terminal-The desktop app on macOS has a built-in terminal with real login shells inside the editor window. (Not yet available in the Windows and Linux apps.) Toggle it with `Cmd+J` or `` Ctrl+` `` (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 and Linux has a built-in terminal with real interactive shells inside the editor window. On Linux, OpenKnowledge inherits Electron 41's supported distribution floor: the Ubuntu 20.04+ and Debian 11+ glibc generation. 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 terminal is also the editor's AI-chat surface: opening it starts your default CLI when no session is open, and the tab strip's **New chat** split button opens another CLI tab — its dropdown switches CLI (the pick sticks, shared with the Ask AI composer) or opens a plain shell tab. With text selected in the editor, `Cmd+J` and `` Ctrl+` `` both 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 — and `Cmd+Shift+J` 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 default CLI when no session is open, and the tab strip's **New chat** split button opens another CLI tab — its dropdown switches CLI (the pick sticks, shared with the Ask AI composer) or opens a plain shell tab. 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.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.@@ -192,7 +192,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 two sections. **Terminal** (macOS desktop app) leads: a row for each agent CLI — **Claude**, **Codex**, **OpenCode**, **Cursor**, and **Pi** — that runs the corresponding CLI (`claude`, `codex`, `opencode`, `pi`; Cursor's is `cursor-agent`) in OpenKnowledge's [docked terminal](#terminal) with the same scoped prompt. **Desktop** follows, listing the installed agent apps (Claude, Codex, Cursor); selecting one launches it via its deep link. Because both sections can list the same name, a Terminal **Claude** (the CLI) and a Desktop **Claude** (the app) can appear together; screen readers tell them apart by the Terminal row's "Claude CLI" accessible name. Each section renders only when it has something to launch, so on the web build and in the Windows and Linux apps — which have no docked terminal — the Terminal section is absent and a CLI pick falls back to the first installed Desktop app target.+The menu is organized into two sections. **Terminal** (macOS and Linux desktop apps) leads: a row for each agent CLI — **Claude**, **Codex**, **OpenCode**, **Cursor**, and **Pi** — that runs the corresponding CLI (`claude`, `codex`, `opencode`, `pi`; Cursor's is `cursor-agent`) in OpenKnowledge's [docked terminal](#terminal) with the same scoped prompt. **Desktop** follows, listing the installed agent apps (Claude, Codex, Cursor); selecting one launches it via its deep link. Because both sections can list the same name, a Terminal **Claude** (the CLI) and a Desktop **Claude** (the app) can appear together; screen readers tell them apart by the Terminal row's "Claude CLI" 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 CLI pick falls back to the first installed Desktop app target.The empty-state create composer on a fresh project carries the same Desktop / Terminal split: its Desktop rows pick the default agent the **Create** button uses, while its Terminal rows (desktop only, disabled until the workspace resolves) launch any of the five CLIs with the brief you typed.@@ -246,9 +246,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` | Show / Hide the Terminal in its current placement (macOS 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 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` | Open an additional terminal tab (macOS 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 / 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+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+M` | [Comment](/docs/features/comments) on the selected text (visual editor). |@@ -297,7 +297,7 @@ Before the existing Zoom and Toggle Fullscreen items, the View menu gets:| --- | --- | --- || **Show / Hide Sidebar** | `Cmd+Option+S` | Toggles the file sidebar (left). Label flips between Show and Hide based on current state, matching Finder. || **Show / Hide Document Panel** | `Cmd+Option+B` | Toggles the document panel (right). |-| **Show / Hide Terminal** | `Cmd+J` | Toggles the Terminal in its current placement. With editor text selected, stages the selection into the AI CLI's input instead of toggling. (`` Ctrl+` `` toggles it too, though that chord has no menu accelerator.) |+| **Show / Hide Terminal** | `Cmd+J` / `Ctrl+J` | Toggles the Terminal in its current placement. With editor text selected, stages the selection into the AI CLI's input instead of toggling. (`` Ctrl+` `` toggles it too, though that chord has no menu accelerator.) || **Show Hidden Files** | `Cmd+Shift+.` | `appearance.sidebar.showHiddenFiles`; same toggle as the sidebar's right-click menu. || **Expand All** | (none) | Expands every folder in the tree. Hidden when nothing is collapsed. || **Collapse All** | (none) | Collapses every folder in the tree. Hidden when nothing is expanded. |diff --git a/docs/content/get-started/overview.mdx b/docs/content/get-started/overview.mdxindex bdc606d58..6e26899e8 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 and a built-in **[TUI](../features/editor.mdx#terminal)** for editing your knowledge base with your favorite agent.+- **[Ask AI](../features/editor.mdx#ask-ai)** experience and a built-in **[TUI](../features/editor.mdx#terminal)** on the macOS and Linux desktop apps for editing your knowledge base with your favorite agent.- 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/integrations/antigravity.mdx b/docs/content/integrations/antigravity.mdxindex 82c1a6ca0..a40dd647c 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**, 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 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`).## Initialize a knowledge basediff --git a/docs/content/integrations/github-copilot-cli.mdx b/docs/content/integrations/github-copilot-cli.mdxindex 7e68f90cc..6d0bbcfc1 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, 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 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.## Verifydiff --git a/docs/content/reference/configuration.mdx b/docs/content/reference/configuration.mdxindex 85f80cefb..b21382bad 100644--- a/docs/content/reference/configuration.mdx+++ b/docs/content/reference/configuration.mdx@@ -59,9 +59,9 @@ 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 (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 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. || `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), 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) 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). || `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 fca23fb76..355662a98 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 is affected. The MCP server and "Open with AI" launches still work without it, as does the app's built-in terminal on macOS (the built-in terminal is not yet available in the Windows and Linux apps). 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 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.The managed block is clearly fenced so you can see and remove it:diff --git a/packages/app/src/App.dom.test.tsx b/packages/app/src/App.dom.test.tsxindex 686978f7a..4db9419fd 100644--- a/packages/app/src/App.dom.test.tsx+++ b/packages/app/src/App.dom.test.tsx@@ -144,6 +144,14 @@ vi.doMock('@/lib/config-context', () => ({useConfigContext: () => ({ merged: mergedConfig }),}));+vi.doMock('@/components/handoff/TerminalLaunchContext', () => ({+ TerminalLaunchProvider: ({ value, children }: { value: unknown; children: ReactNode }) => (+ <div data-testid="terminal-launch-provider" data-enabled={String(value !== null)}>+ {children}+ </div>+ ),+}));+vi.doMock('@/lib/api-config', () => ({fetchApiConfig: (...args: Parameters<typeof fetchApiConfigMock>) => fetchApiConfigMock(...args),}));@@ -275,17 +283,17 @@ vi.doMock('@/lib/transports/clone-transport', () => ({const { App } = await import('./App');-function createBridge() {+function createBridge({ ptyAvailable = true }: { ptyAvailable?: boolean } = {}) {return {editor: {notifyActiveTargetChanged: vi.fn(() => {}),},// The real preload always exposes `config`; App reads `config.ptyAvailable`- // to gate the terminal-launch provider (mac-only PTY). Mirror that shape so+ // to gate the terminal-launch provider. Mirror that shape so// the gate resolves instead of dereferencing undefined.config: {mode: 'editor' as const,- ptyAvailable: true,+ ptyAvailable,},};}@@ -401,6 +409,14 @@ describe('App runtime wiring', () => {expect(screen.getByTestId('editor-pane')).not.toBeNull();});+ test('a desktop host without PTY capability keeps terminal launching disabled', () => {+ renderApp({ bridge: createBridge({ ptyAvailable: false }) });++ expect(screen.getByTestId('terminal-launch-provider').getAttribute('data-enabled')).toBe(+ 'false',+ );+ });+test('promotes preview tabs when the setting changes from enabled to disabled', async () => {mergedConfig = { editor: { previewTabs: true } };const view = renderApp();diff --git a/packages/app/src/App.tsx b/packages/app/src/App.tsxindex 88aa6e377..e893fee73 100644--- a/packages/app/src/App.tsx+++ b/packages/app/src/App.tsx@@ -70,8 +70,8 @@ import {} from '@/lib/use-settings-route';// Cold-path receive surface: only mounts when main routes a-// 'project-branch-switch' payload. Lazy so its branch-info / checkout / variant-// code (and the target-status client it pulls in) splits out of the main bundle.+// 'project-branch-switch' payload. Lazy-loading keeps its branch-info, checkout,+// variant, and target-status code out of the main bundle.const ShareBranchSwitchDialog = lazy(() =>import('@/components/ShareBranchSwitchDialog').then((m) => ({default: m.ShareBranchSwitchDialog,@@ -79,9 +79,9 @@ const ShareBranchSwitchDialog = lazy(() =>);// Cold-path receive surface: the honest verdict modal for a share deep link-// whose target is absent on the receiver's branch. Self-gates on-// `missDialogStore`; lazy so its verdict-fetch code splits out of the main-// bundle until a miss actually occurs.+// whose target is absent on the receiver's branch. It self-gates on+// `missDialogStore`; lazy-loading keeps verdict-fetch code out of the main+// bundle until a miss occurs.const ShareReceiveMissDialog = lazy(() =>import('@/components/ShareReceiveMissDialog').then((m) => ({default: m.ShareReceiveMissDialog,@@ -730,8 +730,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/Linux — node-pty- // is excluded from those packages), so the menu rows that consume it render+ // 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// gated on the same `ptyAvailable` flag, so a Terminal row here would launch// into a surface that never mounts. Mirrors the gate in EditorPane / Settingsdiff --git a/packages/app/src/components/AppMenubar.dom.test.tsx b/packages/app/src/components/AppMenubar.dom.test.tsxindex 282df6209..08aa730ac 100644--- a/packages/app/src/components/AppMenubar.dom.test.tsx+++ b/packages/app/src/components/AppMenubar.dom.test.tsx@@ -23,13 +23,17 @@ vi.doMock('@lingui/react/macro', () => ({type DispatchMock = ReturnType<typeof vi.fn>;-function installBridge(platform: string, mode: 'editor' | 'note' = 'editor'): DispatchMock {- // `query` resolves null so the snapshot-gated rows stay hidden; the two- // rows under test are unconditional.- const dispatch = vi.fn(() => Promise.resolve(null));+function installBridge(+ platform: string,+ mode: 'editor' | 'note' = 'editor',+ options: { ptyAvailable?: boolean; queryResult?: unknown } = {},+): DispatchMock {+ const dispatch = vi.fn((request: { kind: string }) =>+ Promise.resolve(request.kind === 'query' ? (options.queryResult ?? null) : undefined),+ );(window as unknown as { okDesktop?: unknown }).okDesktop = {platform,- config: { mode },+ config: { mode, ptyAvailable: options.ptyAvailable ?? false },menu: { dispatch },};return dispatch;@@ -168,3 +172,74 @@ describe('AppMenubar View navigation history', () => {});});});++describe('AppMenubar View terminal toggle', () => {+ const snapshot = (terminalVisible: boolean) => ({+ recentProjects: [],+ spellCheckEnabled: true,+ showDevToolsMenu: false,+ canCheckForUpdates: false,+ canReconfigureMcpWiring: false,+ activeTarget: { kind: null },+ viewMenuState: {+ showHiddenFiles: false,+ showOkFolders: false,+ showOnlyMarkdownFiles: false,+ showSkillsSection: true,+ canExpandAll: true,+ canCollapseAll: true,+ sidebarVisible: true,+ docPanelVisible: true,+ terminalVisible,+ },+ });++ beforeEach(() => {+ vi.clearAllMocks();+ });++ afterEach(() => {+ cleanup();+ (window as unknown as { okDesktop?: unknown }).okDesktop = undefined;+ });++ test('Linux shows the terminal toggle and dispatches it through the shared menu action', async () => {+ const dispatch = installBridge('linux', 'editor', {+ ptyAvailable: true,+ queryResult: snapshot(false),+ });+ await openMenu('View');++ const item = await screen.findByRole('menuitem', { name: /Show Terminal/ });+ expect(item.textContent).toContain('Ctrl+J');+ dispatch.mockClear();++ await userEvent.click(item);+ expect(dispatch).toHaveBeenCalledWith({+ kind: 'menu-action',+ action: 'toggle-terminal',+ });+ });++ test('Linux labels a visible terminal with the inverse action', async () => {+ installBridge('linux', 'editor', {+ ptyAvailable: true,+ queryResult: snapshot(true),+ });+ await openMenu('View');++ expect(await screen.findByRole('menuitem', { name: /Hide Terminal/ })).not.toBeNull();+ expect(screen.queryByRole('menuitem', { name: /Show Terminal/ })).toBeNull();+ });++ test('Windows keeps the terminal toggle absent while PTYs are unavailable', async () => {+ installBridge('win32', 'editor', {+ ptyAvailable: false,+ queryResult: snapshot(false),+ });+ await openMenu('View');++ expect(screen.queryByRole('menuitem', { name: /Show Terminal/ })).toBeNull();+ expect(screen.queryByRole('menuitem', { name: /Hide Terminal/ })).toBeNull();+ });+});diff --git a/packages/app/src/components/AppMenubar.tsx b/packages/app/src/components/AppMenubar.tsxindex 3eb7da836..4cad6030e 100644--- a/packages/app/src/components/AppMenubar.tsx+++ b/packages/app/src/components/AppMenubar.tsx@@ -17,10 +17,8 @@* that drives the native menu's rendering — refreshed each time a menu* opens, so it is at most one open stale.*- * The Terminal menu is deliberately absent: the pty-backed dock is dark on- * Windows/Linux (`config.ptyAvailable`), and every Terminal item is- * pty-scoped. Re-add it from the native template if node-pty ever ships- * off-mac.+ * Terminal controls stay capability-gated: Linux exposes the View toggle,+ * while Windows keeps it absent until its PTY implementation ships.*/import { useLingui } from '@lingui/react/macro';@@ -291,6 +289,14 @@ export function AppMenubar() {{view?.docPanelVisible === false ? t`Show document panel` : t`Hide document panel`}<MenubarShortcut>Ctrl+Alt+B</MenubarShortcut></MenubarItem>+ {bridge.config.ptyAvailable && (+ <MenubarItem+ onSelect={() => dispatch({ kind: 'menu-action', action: 'toggle-terminal' })}+ >+ {view?.terminalVisible === true ? t`Hide Terminal` : t`Show Terminal`}+ <MenubarShortcut>Ctrl+J</MenubarShortcut>+ </MenubarItem>+ )}<MenubarSeparator /><MenubarCheckboxItemchecked={view?.showHiddenFiles ?? false}diff --git a/packages/app/src/components/EditorPane.dom.test.tsx b/packages/app/src/components/EditorPane.dom.test.tsxindex c1d7b1bf2..b0f9acd3a 100644--- a/packages/app/src/components/EditorPane.dom.test.tsx+++ b/packages/app/src/components/EditorPane.dom.test.tsx@@ -490,6 +490,7 @@ function makeOkDesktopStub(terminalVisible: false,agentPanelVisible: false,}),+ ptyAvailable = true,) {const menuHandlers: Array<(action: string) => void> = [];const viewMenuPushes: Array<{@@ -506,9 +507,8 @@ function makeOkDesktopStub(},stub: {// The terminal affordances gate on the host's pty capability- // (`config.ptyAvailable`, false on win/linux where node-pty isn't- // bundled) — these tests model the capable macOS host.- config: { ptyAvailable: true },+ // (`config.ptyAvailable`, false where node-pty is unavailable).+ config: { ptyAvailable },onMenuAction(cb: (action: string) => void) {menuHandlers.push(cb);return () => {@@ -585,6 +585,18 @@ describe('EditorPane session-panel wiring', () => {}});+ test('desktop host without PTY capability keeps the terminal dock unmounted', async () => {+ const desk = makeOkDesktopStub(undefined, false);+ (window as { okDesktop?: unknown }).okDesktop = desk.stub;+ await renderEditorPane();++ expect(screen.queryByTestId('terminal-dock')).toBeNull();+ expect(screen.getByTestId('agents-panel').getAttribute('data-terminal-capable')).toBe('false');++ act(() => desk.dispatchMenuAction('toggle-terminal'));+ expect(screen.queryByTestId('terminal-dock')).toBeNull();+ });+test('desktop: the two panels open and close independently', async () => {const desk = makeOkDesktopStub();(window as { okDesktop?: unknown }).okDesktop = desk.stub;diff --git a/packages/app/src/components/EditorPane.tsx b/packages/app/src/components/EditorPane.tsxindex 924f26a28..19d2044dd 100644--- a/packages/app/src/components/EditorPane.tsx+++ b/packages/app/src/components/EditorPane.tsx@@ -172,8 +172,7 @@ 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/Linux- // (node-pty is not bundled there; terminal dock dark off-mac), where a+ // actually spawn a PTY: `config.ptyAvailable` is false on Windows, 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@@ -647,7 +646,7 @@ export function EditorPane({ onOpenSearch }: EditorPaneProps = {}) {useNoPushPermissionToast(syncStatus?.pausedReason);// One-time notice when this window is a worktree that inherited the root- // project's auto-sync setting (fires + self-clears its seeded flag).+ // project's auto-sync setting; it fires once and clears its seeded flag.useWorktreeAutoSyncNotice();function handleModeChange(mode: EditorModeValue) {@@ -668,14 +667,14 @@ export function EditorPane({ onOpenSearch }: EditorPaneProps = {}) {requestPreviewTabPromotion(activeDocName);}setEditorMode(mode);- // User-initiated change — persist globally. Tool-driven flips (e.g.- // RAW_MDX_NAV_EVENT → source) are session-only and deliberately do NOT- // call setPersistedMode.+ // User-initiated change — persist globally. Tool-driven flips such as+ // RAW_MDX_NAV_EVENT → source are session-only and deliberately do not call+ // setPersistedMode.setPersistedMode(mode);}- // Effect Events so the once-bound keydown listener below reads the current- // closures (mode, active doc/provider) without re-subscribing on every change.+ // Effect Events let the once-bound keydown listener read current mode, doc,+ // and provider state without re-subscribing on every change.const toggleEditorModeEvent = useEffectEvent(() => {handleModeChange(editorMode === 'source' ? 'wysiwyg' : 'source');});diff --git a/packages/app/src/components/SessionsHost.tsx b/packages/app/src/components/SessionsHost.tsxindex 5256c8482..c7555631d 100644--- a/packages/app/src/components/SessionsHost.tsx+++ b/packages/app/src/components/SessionsHost.tsx@@ -54,6 +54,7 @@ import {readWebDockSessionOrder,writeDockSessionOrder,} from '@/lib/dock-session-persistence';+import { matchesPrimaryModifier, type ShortcutPlatform } from '@/lib/keyboard-shortcuts';import { subscribeLocalMenuAction } from '@/lib/local-menu-action-bus';import type { NewSessionChoice } from '@/lib/new-session-choice';import { isOverlayLayerOpen } from '@/lib/overlay-layers';@@ -177,7 +178,7 @@ function focusInsideHost(hostEl: HTMLElement | null): boolean {*/export type SessionSurface = 'terminal-dock' | 'agents-panel' | 'terminal-window';-/** Focus-gate for the host's capture-phase chords (⌘1–9, ⌘⇧←/→): always in the+/** Focus-gate for the host's primary-modifier chords (tab selection and reorder): always in the* standalone window (the whole window IS the terminal), in a docked panel only* while focus sits inside the host. */function chordTargetsHost(hostEl: HTMLElement | null, isWindow: boolean): boolean {@@ -375,6 +376,12 @@ export function SessionsHost({// into, so it does not persist at all.const persistSurface: DockSurface = hostThreads ? 'agents' : 'terminal';const persistsOrder = !isWindow;+ const shortcutPlatform: ShortcutPlatform | undefined =+ bridge?.platform === 'darwin'+ ? 'mac'+ : bridge?.platform === 'linux' || bridge?.platform === 'win32'+ ? 'windowsLinux'+ : undefined;// The single stable host div for the session subtree. Created once via a// useState lazy initializer (never a render-time ref write — React Compiler@@ -1534,10 +1541,11 @@ export function SessionsHost({});}, [isWindow, hostTerminals, terminalAvailable]);- // ⌘1–⌘9 jump straight to the Nth tab (capture phase, focus-scoped in the dock).+ // Primary modifier + 1–9 jumps straight to the Nth tab (capture phase, focus-scoped in the dock).useEffect(() => {function onKeyDown(event: KeyboardEvent) {- if (!event.metaKey || event.ctrlKey || event.altKey || event.shiftKey) return;+ if (!matchesPrimaryModifier(event, shortcutPlatform) || event.altKey || event.shiftKey)+ return;if (!/^[1-9]$/.test(event.key)) return;if (!chordTargetsHost(hostEl, isWindow)) return;// `chordTargetsHost` short-circuits to true in the dedicated terminal@@ -1552,12 +1560,14 @@ export function SessionsHost({}window.addEventListener('keydown', onKeyDown, { capture: true });return () => window.removeEventListener('keydown', onKeyDown, { capture: true });- }, [hostEl, isWindow]);+ }, [hostEl, isWindow, shortcutPlatform]);- // ⌘⇧← / ⌘⇧→ move the ACTIVE tab one slot (capture phase + focus-gate).+ // Primary modifier + Shift + Left/Right moves the active tab one slot.useEffect(() => {function onKeyDown(event: KeyboardEvent) {- if (!event.metaKey || !event.shiftKey || event.ctrlKey || event.altKey) return;+ if (!matchesPrimaryModifier(event, shortcutPlatform) || !event.shiftKey || event.altKey) {+ return;+ }const direction = event.key === 'ArrowLeft' ? -1 : event.key === 'ArrowRight' ? 1 : 0;if (direction === 0) return;if (!chordTargetsHost(hostEl, isWindow)) return;@@ -1587,7 +1597,7 @@ export function SessionsHost({announceTimerRef.current = null;}};- }, [hostEl, isWindow, t]);+ }, [hostEl, isWindow, shortcutPlatform, t]);// Reflect terminal liveness to main so the Terminal menu's "Kill Terminal"// enables only while at least one TERMINAL session is live.diff --git a/packages/app/src/components/TerminalDock.dom.test.tsx b/packages/app/src/components/TerminalDock.dom.test.tsxindex f9eae2d6b..63472bb65 100644--- a/packages/app/src/components/TerminalDock.dom.test.tsx+++ b/packages/app/src/components/TerminalDock.dom.test.tsx@@ -183,7 +183,7 @@ const { SessionsHost } = await import('./SessionsHost');// After the vi.doMock block (a static import would load the real xterm).const { STAGE_PASTE_SETTLE_MS } = await import('./TerminalPanel');-function makeBridge() {+function makeBridge(platform: OkDesktopBridge['platform'] = 'darwin') {const viewMenuPushes: Array<{ terminalLive?: boolean }> = [];// Hand each session a distinct PTY id (pty-1, pty-2, …) so a close can assert// exactly which session's PTY was reaped — the demux the dock owns.@@ -197,6 +197,7 @@ function makeBridge() {// existing PTY (it opens its own tab), so tests assert `input` stays unused.const input = vi.fn((_ptyId: string, _data: string) => {});const bridge = {+ platform,onMenuAction: () => () => {},editor: {notifyViewMenuStateChanged(state: { terminalLive?: boolean }) {@@ -277,9 +278,14 @@ function DockHarness({);}-function renderDock(visible: boolean, launch?: TestLaunch | null, placement = 'bottom') {+function renderDock(+ visible: boolean,+ launch?: TestLaunch | null,+ placement = 'bottom',+ platform: OkDesktopBridge['platform'] = 'darwin',+) {const onVisibleChange = vi.fn((_v: boolean) => {});- const { bridge, create, kill, input, viewMenuPushes, dispatchMenuAction } = makeBridge();+ const { bridge, create, kill, input, viewMenuPushes, dispatchMenuAction } = makeBridge(platform);const ui = (v: boolean, l?: TestLaunch | null, p = placement, targetAvailable = true) => (<DockHarnessv={v}@@ -703,10 +709,11 @@ describe('TerminalDock multi-session', () => {}function dispatchChord(key: string,- mods: { metaKey?: boolean; shiftKey?: boolean },+ mods: { ctrlKey?: boolean; metaKey?: boolean; shiftKey?: boolean },): KeyboardEvent {const event = new KeyboardEvent('keydown', {key,+ ctrlKey: mods.ctrlKey ?? false,metaKey: mods.metaKey ?? false,shiftKey: mods.shiftKey ?? false,cancelable: true,@@ -739,6 +746,19 @@ describe('TerminalDock multi-session', () => {);});+ test('Ctrl+Shift+Left moves the active tab on Linux', async () => {+ const user = userEvent.setup();+ renderDock(true, null, 'bottom', 'linux');+ await addTerminalTab(user);+ const panels = sessionPanels();+ act(() => panels[1]?.querySelector<HTMLElement>('.xterm-helper-textarea')?.focus());++ const event = dispatchChord('ArrowLeft', { ctrlKey: true, shiftKey: true });++ expect(event.defaultPrevented).toBe(true);+ expect(tabLabels()).toEqual(['Terminal 2', 'Terminal 1']);+ });+test('⌘⇧→ at the last slot is a no-op left for the shell', async () => {const user = userEvent.setup();renderDock(true);@@ -795,6 +815,21 @@ describe('TerminalDock multi-session', () => {);});+ test('Ctrl+1 selects the first terminal tab on Linux', async () => {+ const user = userEvent.setup();+ renderDock(true, null, 'bottom', 'linux');+ await addTerminalTab(user);+ const panels = sessionPanels();+ act(() => panels[1]?.querySelector<HTMLElement>('.xterm-helper-textarea')?.focus());++ const event = dispatchChord('1', { ctrlKey: true });++ expect(event.defaultPrevented).toBe(true);+ expect(screen.getByRole('tab', { name: 'Terminal 1' }).getAttribute('aria-selected')).toBe(+ 'true',+ );+ });+test('the reorder chord is left for native editing while a rename input is focused', async () => {const user = userEvent.setup();renderDock(true);diff --git a/packages/app/src/components/TerminalPanel.dom.test.tsx b/packages/app/src/components/TerminalPanel.dom.test.tsxindex 784362e03..69978ffe8 100644--- a/packages/app/src/components/TerminalPanel.dom.test.tsx+++ b/packages/app/src/components/TerminalPanel.dom.test.tsx@@ -54,6 +54,9 @@ class MockTerminal {// the flush the glyphs land one frame late — a visible blank flash).renderFlush = vi.fn(() => {});refresh = vi.fn((_start: number, _end: number) => {});+ selection = '';+ hasSelection = vi.fn(() => this.selection.length > 0);+ getSelection = vi.fn(() => this.selection);get _core() {return {coreMouseService: { activeEncoding: this.mouseEncoding },@@ -115,6 +118,7 @@ class MockTerminal {});focus = vi.fn(() => {});dispose = vi.fn(() => {});+ paste = vi.fn((_data: string) => {});write = vi.fn((_data: string, cb?: () => void) => {cb?.();});@@ -206,6 +210,7 @@ function makeBridge(ok: true,replay: '',}),+ platform: OkDesktopBridge['platform'] = 'darwin',) {const dataSubs: Array<(m: OkPtyData) => void> = [];const exitSubs: Array<(m: OkPtyExit) => void> = [];@@ -252,6 +257,7 @@ function makeBridge(shell: { openExternal, openAsset, revealAsset, revealExternal },project: { checkTargetExists },config: { e2eSmoke: false, projectPath: '/Users/me/project' },+ platform,// Stand in for Electron `webUtils.getPathForFile`: a dropped File resolves// to a deterministic on-disk path so the drop→input wiring is assertable.getPathForFile: (file: File) => `/dropped/${file.name}`,@@ -286,6 +292,13 @@ describe('TerminalPanel', () => {webglThrows = false;mockResolvedTheme = 'dark';(globalThis as { ResizeObserver: unknown }).ResizeObserver = MockResizeObserver;+ Object.defineProperty(globalThis.navigator, 'clipboard', {+ configurable: true,+ value: {+ readText: vi.fn(async () => 'clipboard paste'),+ writeText: vi.fn(async () => {}),+ },+ });});afterEach(() => {cleanup();@@ -790,6 +803,171 @@ describe('TerminalPanel', () => {expect(plainEnterPreventDefault).not.toHaveBeenCalled();});+ test('Linux Ctrl+C and Ctrl+V bypass menu accelerators and still reach the PTY', async () => {+ const { bridge, terminal } = makeBridge(+ { ok: true, ptyId: 'pty-1' },+ WIRED,+ undefined,+ 'linux',+ );+ render(<TerminalPanel bridge={bridge} />);+ await waitFor(() => expect(lastTerm?.onDataCb).toBeTruthy());+ const handler = lastTerm?.keyHandler;+ expect(handler).toBeTruthy();++ for (const [key, bytes] of [+ ['c', '\x03'],+ ['v', '\x16'],+ ] as const) {+ const preventDefault = vi.fn(() => {});+ expect(+ handler?.({+ type: 'keydown',+ key,+ ctrlKey: true,+ shiftKey: false,+ altKey: false,+ metaKey: false,+ preventDefault,+ } as unknown as KeyboardEvent),+ ).toBe(true);+ expect(preventDefault).toHaveBeenCalledTimes(1);+ act(() => lastTerm?.onDataCb?.(bytes));+ expect(terminal.input).toHaveBeenLastCalledWith('pty-1', bytes);+ }+ });++ test('Linux Ctrl+Shift+C copies the xterm selection and Ctrl+Shift+V pastes clipboard text', async () => {+ const { bridge, terminal } = makeBridge(+ { ok: true, ptyId: 'pty-1' },+ WIRED,+ undefined,+ 'linux',+ );+ render(<TerminalPanel bridge={bridge} />);+ await waitFor(() => expect(lastTerm?.onDataCb).toBeTruthy());+ const handler = lastTerm?.keyHandler;+ expect(handler).toBeTruthy();+ if (lastTerm) lastTerm.selection = 'selected output';++ const copyPreventDefault = vi.fn(() => {});+ expect(+ handler?.({+ type: 'keydown',+ key: 'C',+ ctrlKey: true,+ shiftKey: true,+ 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'),+ );++ const pastePreventDefault = vi.fn(() => {});+ expect(+ handler?.({+ type: 'keydown',+ key: 'V',+ ctrlKey: true,+ shiftKey: true,+ altKey: false,+ metaKey: false,+ preventDefault: pastePreventDefault,+ } as unknown as KeyboardEvent),+ ).toBe(false);+ expect(pastePreventDefault).toHaveBeenCalledTimes(1);+ await waitFor(() => expect(lastTerm?.paste).toHaveBeenCalledWith('clipboard paste'));+ expect(terminal.input).not.toHaveBeenCalledWith('pty-1', 'clipboard paste');+ });++ test('Linux Ctrl+Shift+C consumes the clipboard chord when xterm has no selection', async () => {+ const { bridge } = makeBridge({ ok: true, ptyId: 'pty-1' }, WIRED, undefined, 'linux');+ render(<TerminalPanel bridge={bridge} />);+ await waitFor(() => expect(lastTerm?.keyHandler).toBeTruthy());++ const preventDefault = vi.fn(() => {});+ expect(+ lastTerm?.keyHandler?.({+ type: 'keydown',+ key: 'C',+ ctrlKey: true,+ shiftKey: true,+ altKey: false,+ metaKey: false,+ preventDefault,+ } as unknown as KeyboardEvent),+ ).toBe(false);+ expect(preventDefault).toHaveBeenCalledTimes(1);+ expect(navigator.clipboard.writeText).not.toHaveBeenCalled();+ });++ 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', {+ configurable: true,+ value: {+ readText: vi.fn(+ () =>+ new Promise<string>((resolve) => {+ resolveClipboard = resolve;+ }),+ ),+ writeText: vi.fn(async () => {}),+ },+ });+ const { bridge } = makeBridge({ ok: true, ptyId: 'pty-1' }, WIRED, undefined, 'linux');+ const { unmount } = render(<TerminalPanel bridge={bridge} />);+ await waitFor(() => expect(lastTerm?.keyHandler).toBeTruthy());++ expect(+ lastTerm?.keyHandler?.({+ type: 'keydown',+ key: 'V',+ ctrlKey: true,+ shiftKey: true,+ altKey: false,+ metaKey: false,+ preventDefault: vi.fn(() => {}),+ } as unknown as KeyboardEvent),+ ).toBe(false);+ const term = lastTerm;+ unmount();+ await act(async () => resolveClipboard?.('late clipboard text'));++ expect(term?.paste).not.toHaveBeenCalled();+ });++ test('macOS leaves Ctrl+Shift+C and Ctrl+Shift+V on xterm’s existing path', async () => {+ const { bridge, terminal } = makeBridge({ ok: true, ptyId: 'pty-1' });+ render(<TerminalPanel bridge={bridge} />);+ await waitFor(() => expect(lastTerm?.onDataCb).toBeTruthy());+ const handler = lastTerm?.keyHandler;++ for (const key of ['C', 'V']) {+ const preventDefault = vi.fn(() => {});+ expect(+ handler?.({+ type: 'keydown',+ key,+ ctrlKey: true,+ shiftKey: true,+ altKey: false,+ metaKey: false,+ preventDefault,+ } as unknown as KeyboardEvent),+ ).toBe(true);+ expect(preventDefault).not.toHaveBeenCalled();+ }+ expect(navigator.clipboard.writeText).not.toHaveBeenCalled();+ expect(navigator.clipboard.readText).not.toHaveBeenCalled();+ expect(lastTerm?.paste).not.toHaveBeenCalled();+ expect(terminal.input).not.toHaveBeenCalledWith('pty-1', 'clipboard paste');+ });+test('wheel handler defers to xterm in normal scrollback, drives the PTY in mouse mode', async () => {const { bridge, terminal } = makeBridge({ ok: true, ptyId: 'pty-1' });render(<TerminalPanel bridge={bridge} />);diff --git a/packages/app/src/components/TerminalPanel.launch.dom.test.tsx b/packages/app/src/components/TerminalPanel.launch.dom.test.tsxindex 9aa02b83c..51d3dc218 100644--- a/packages/app/src/components/TerminalPanel.launch.dom.test.tsx+++ b/packages/app/src/components/TerminalPanel.launch.dom.test.tsx@@ -40,6 +40,8 @@ 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(() => '');open = vi.fn(() => {});focus = vi.fn(() => {});dispose = vi.fn(() => {});@@ -101,7 +103,11 @@ const ON_PATH: CliReadiness = { onPath: 'present' };* the gate that lets the launch add the `-c` tool-auto-approve override. */const CODEX_OK_CONFIGURED: CliReadiness = { onPath: 'present', okServerConfigured: true };-function makeBridge(preflight: ClaudeReadiness = WIRED, cliReadiness: CliReadiness = ON_PATH) {+function makeBridge(+ preflight: ClaudeReadiness = WIRED,+ cliReadiness: CliReadiness = ON_PATH,+ platform: OkDesktopBridge['platform'] = 'darwin',+) {const dataSubs: Array<(m: OkPtyData) => void> = [];const terminal = {create: vi.fn(async (_opts: { cols: number; rows: number; launchCommand?: string }) => ({@@ -132,6 +138,7 @@ function makeBridge(preflight: ClaudeReadiness = WIRED, cliReadiness: CliReadineterminal,shell: { openExternal: vi.fn(async () => {}) },config: { e2eSmoke: false },+ platform,} as unknown as OkDesktopBridge,terminal,pushData: (m: OkPtyData) => {diff --git a/packages/app/src/components/TerminalPanel.tsx b/packages/app/src/components/TerminalPanel.tsxindex 82b82eaed..a42de439d 100644--- a/packages/app/src/components/TerminalPanel.tsx+++ b/packages/app/src/components/TerminalPanel.tsx@@ -503,7 +503,10 @@ function TerminalSession({});// Every key (including Escape) goes to the PTY so terminal apps (vim, the- // `claude` TUI) work — the keyboard exit is ⌘J. Two Shift-chord patches:+ // `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://// - Shift+Tab: xterm emits the reverse-tab sequence (ESC [ Z) but, unlike// plain Tab, does NOT call preventDefault, so the browser's@@ -515,7 +518,44 @@ function TerminalSession({// rather than submitting — matching how Ghostty / Cursor map this chord.// Return false so xterm does NOT also emit its default \r.term.attachCustomKeyEventHandler((event) => {- if (event.type !== 'keydown' || !event.shiftKey) return true;+ if (event.type !== 'keydown') return true;++ const key = event.key.toLowerCase();+ const linuxClipboardKey =+ bridge.platform === 'linux' &&+ event.ctrlKey &&+ !event.altKey &&+ !event.metaKey &&+ (key === 'c' || key === 'v');+ if (linuxClipboardKey) {+ // 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.+ event.preventDefault();+ if (!event.shiftKey) return true;++ if (key === 'c') {+ if (term.hasSelection() && navigator.clipboard?.writeText) {+ void navigator.clipboard+ .writeText(term.getSelection())+ .catch((err) => console.warn('[terminal] clipboard copy failed', err));+ }+ return false;+ }++ if (navigator.clipboard?.readText) {+ void navigator.clipboard+ .readText()+ .then((text) => {+ const ptyId = ptyIdRef.current;+ if (!cancelled && ptyId !== null) term.paste(text);+ })+ .catch((err) => console.warn('[terminal] clipboard paste failed', err));+ }+ return false;+ }++ if (!event.shiftKey) return true;if (event.key === 'Tab') {event.preventDefault();return true;diff --git a/packages/app/src/components/TerminalTabStrip.tsx b/packages/app/src/components/TerminalTabStrip.tsxindex 6c8a76b26..7e74ce7df 100644--- a/packages/app/src/components/TerminalTabStrip.tsx+++ b/packages/app/src/components/TerminalTabStrip.tsx@@ -47,7 +47,7 @@ const TERMINAL_TAB_SORTABLE_SELECTOR = '[data-terminal-tab-sortable]';* One terminal tab as a `@dnd-kit/sortable` node. Only the pointer listeners +* transform are wired (no `attributes` spread and no `KeyboardSensor`): dnd-kit's* `attributes` would overwrite the Radix trigger's tab semantics, while keyboard- * reorder belongs to the host's dedicated ⌘⇧←/→ chord rather than dnd-kit's+ * reorder belongs to the host's dedicated primary-modifier chord rather than dnd-kit's* Space-lift model. The pointer listeners attach to the trigger, but without a* keyboard sensor they do not claim Radix arrow keys or F2. `disabled`* short-circuits sortable while any rename is open.@@ -185,7 +185,7 @@ interface TerminalTabStripProps {readonly onReorder?: (newOrderIds: readonly string[]) => void;/*** Reports whether a pointer drag is currently lifted, so the host can suppress- * the ⌘⇧←/→ keyboard-reorder chord while a drag is in flight.+ * the primary-modifier keyboard-reorder chord while a drag is in flight.*/readonly onDragActiveChange?: (active: boolean) => void;/** Which edge this panel occupies — drives the collapse chevron's direction.@@ -337,7 +337,7 @@ export function TerminalTabStrip({// Pointer-drag reorder. PointerSensor distance:8 keeps a plain click (activate// / double-click-to-rename) from starting a drag. No KeyboardSensor — keyboard- // reorder is the host's ⌘⇧←/→ chord, so arrow keys stay with Radix roving focus.+ // reorder is the host's primary-modifier chord, so arrow keys stay with Radix roving focus.// Drag is disabled entirely while a rename is open. The chrome module (shared// with editor tabs) supplies the horizontal clamp, edge-snap collision, and// width stabilization; bounds are measured against the row on drag start.diff --git a/packages/app/src/components/TerminalWindowApp.dom.test.tsx b/packages/app/src/components/TerminalWindowApp.dom.test.tsxindex 57e7cdaf6..187f6e693 100644--- a/packages/app/src/components/TerminalWindowApp.dom.test.tsx+++ b/packages/app/src/components/TerminalWindowApp.dom.test.tsx@@ -5,7 +5,7 @@* TerminalGate (the heavy consent + xterm session) is stubbed with a session* stand-in that spawns a PTY on mount and reaps it on unmount — the same* pattern as TerminalDock.dom.test.tsx — so the assertions pin what the window- * owns: one shell on mount, the new-tab affordance, ⌘1–9 switching with no+ * owns: one shell on mount, the new-tab affordance, primary-modifier tab switching with no* scope gate, and close-last → window.close(). The window mounts the shared* TerminalSessionsHost (window variant), so the session model — including the* New-chat split button — is the dock's. The sibling root surfaces are@@ -61,7 +61,7 @@ vi.doMock('@/components/NavigatorApp', () => ({const { TerminalWindowApp } = await import('./TerminalWindowApp');const { selectDesktopRootApp } = await import('./desktop-root-app');-function makeBridge() {+function makeBridge(platform: OkDesktopBridge['platform'] = 'darwin') {const viewMenuPushes: Array<{ terminalLive?: boolean }> = [];let ptyCounter = 0;const create = vi.fn(async () => {@@ -70,6 +70,7 @@ function makeBridge() {});const kill = vi.fn(async (_id: string) => {});const bridge = {+ platform,config: { mode: 'terminal' },onMenuAction: () => () => {},editor: {@@ -177,6 +178,33 @@ describe('TerminalWindowApp', () => {expect(activePanelId()).toBe(sessionPanels()[0]?.getAttribute('data-terminal-session'));});+ test('Ctrl+number switches tabs in a Linux terminal window', async () => {+ const user = userEvent.setup();+ const { bridge } = makeBridge('linux');+ render(+ <TooltipProvider>+ <TerminalWindowApp bridge={bridge} />+ </TooltipProvider>,+ );+ await addTerminalTab(user);++ const event = new KeyboardEvent('keydown', {+ key: '1',+ ctrlKey: true,+ cancelable: true,+ bubbles: true,+ });+ act(() => {+ window.dispatchEvent(event);+ });++ expect(event.defaultPrevented).toBe(true);+ expect(screen.getByRole('tab', { name: 'Terminal 1' }).getAttribute('aria-selected')).toBe(+ 'true',+ );+ expect(activePanelId()).toBe(sessionPanels()[0]?.getAttribute('data-terminal-session'));+ });+test('Cmd+number with a co-modifier (Ctrl) falls through to the shell, not a tab switch', async () => {const user = userEvent.setup();const { bridge } = makeBridge();diff --git a/packages/app/src/components/settings/SettingsDialogShell.terminal.dom.test.tsx b/packages/app/src/components/settings/SettingsDialogShell.terminal.dom.test.tsxindex 2b1bdd828..1f0af9b0f 100644--- a/packages/app/src/components/settings/SettingsDialogShell.terminal.dom.test.tsx+++ b/packages/app/src/components/settings/SettingsDialogShell.terminal.dom.test.tsx@@ -119,8 +119,7 @@ function setDesktopHost(present: boolean, opts: { ptyAvailable?: boolean } = {})const w = window as unknown as { okDesktop?: unknown };if (present) {// The Terminal subsection additionally gates on the host's pty capability- // (`config.ptyAvailable`, false on win/linux where node-pty isn't- // bundled) — model the capable macOS host by default.+ // (`config.ptyAvailable`, false where node-pty is unavailable).w.okDesktop = { config: { ptyAvailable: opts.ptyAvailable ?? true } };} else {w.okDesktop = undefined;@@ -203,7 +202,7 @@ describe('SettingsDialogShell terminal subsection (desktop-only)', () => {expect(screen.queryByTestId(SUBSECTION_RESULT_ID)).toBeNull();});- test('drops the Terminal search entry on a pty-less Electron host (win/linux)', async () => {+ test('drops the Terminal search entry on a PTY-less Electron host', async () => {setDesktopHost(true, { ptyAvailable: false });const user = userEvent.setup();render(<SettingsDialogShell open={true} onOpenChange={() => {}} />);diff --git a/packages/app/src/components/settings/SlidesPluginSection.dom.test.tsx b/packages/app/src/components/settings/SlidesPluginSection.dom.test.tsxindex dbc169634..ebb2b3e90 100644--- a/packages/app/src/components/settings/SlidesPluginSection.dom.test.tsx+++ b/packages/app/src/components/settings/SlidesPluginSection.dom.test.tsx@@ -212,9 +212,8 @@ describe('SlidesPluginSection — single source for the command', () => {});describe('SlidesPluginSection — terminal availability', () => {- test('hides Run in terminal where no PTY can be spawned (Windows / Linux)', async () => {- // node-pty is macOS-only, so the dock is dark off-mac and `ptyAvailable` is- // false. Rendering the button there would close Settings, fire the request,+ test('hides Run in terminal where no PTY can be spawned', async () => {+ // Rendering the button on a PTY-less host would close Settings, fire the request,// and produce no session — the click would look swallowed.installBridge(() => Promise.resolve({ kind: 'status', available: false }), {ptyAvailable: false,diff --git a/packages/app/src/components/settings/SlidesPluginSection.tsx b/packages/app/src/components/settings/SlidesPluginSection.tsxindex eb259b758..f18f24cc3 100644--- a/packages/app/src/components/settings/SlidesPluginSection.tsx+++ b/packages/app/src/components/settings/SlidesPluginSection.tsx@@ -56,15 +56,13 @@ type Availability =function useSlidevStatus(): Availability {const [availability, setAvailability] = useState<Availability>({ kind: 'checking' });- // `probe` is defined inside the effect (not the component body) so it shares- // the effect's `active` flag and keeps a single stable identity — the same- // function reference registers the focus listener below and removes it on- // cleanup, which a body-level callback (unmemoizable under the React Compiler)- // could not guarantee.+ // `probe` lives inside the effect so it shares the `active` flag and keeps+ // one identity for registering and removing the focus listener. A body-level+ // callback cannot guarantee that under the React Compiler.useEffect(() => {// Guards a late `status()` resolution from writing state into an unmounted- // panel — the round-trip outlives a quick open-and-close of Settings. The- // sibling probe in SlidesToolbarControls carries the same flag.+ // panel after Settings closes quickly. The sibling probe in+ // SlidesToolbarControls carries the same flag.let active = true;const probe = () => {const slides = window.okDesktop?.slides;@@ -81,20 +79,19 @@ function useSlidevStatus(): Availability {);})// Trust boundary: an IPC round-trip to a separate process. A rejected- // invoke means the probe could not run — reported as `check-failed`- // (neutral copy), NOT `missing`: telling the user to install Slidev when- // the bridge broke would send them after software that may be present.- // Logged so a broken bridge stays distinguishable in diagnostics.+ // invoke means the probe could not run, so report neutral `check-failed`+ // instead of `missing`. Otherwise a broken bridge could tell the user+ // to install software that is already present. Logging keeps those+ // failures distinguishable in diagnostics..catch((err: unknown) => {console.warn('[slides] settings availability probe failed:', err);if (active) setAvailability({ kind: 'check-failed' });});};probe();- // Re-probe when the user comes back to the window. The common first-run- // path is: see "not installed" → install in a terminal → switch back. That- // switch is the focus event, so the panel is correct by the time they look- // at it.+ // Re-probe when the user returns to the window. The common first-run path+ // is: see "not installed" → install in a terminal → switch back. That focus+ // event refreshes the panel before they look at it.window.addEventListener('focus', probe);return () => {active = false;@@ -108,8 +105,8 @@ function useSlidevStatus(): Availability {/*** Whether this host can actually open a terminal tab and run something in it.*- * The terminal dock is dark on Windows and Linux — node-pty ships macOS-only,- * so `config.ptyAvailable` is false there. Without this gate, "Run in terminal"+ * `config.ptyAvailable` is false where the packaged app cannot spawn a PTY.+ * Without this gate, "Run in terminal"* would close Settings, fire the request, and produce no session at all: the* dock never creates a PTY, so the click reads as the app swallowing it. Same* rule EditorPane states for every terminal affordance — a control that cannot@@ -192,9 +189,9 @@ function StatusRow({ availability }: { availability: Availability }) {variant="outline"data-testid="slides-run-install"onClick={() => {- // Close Settings first: the dialog is hash-routed and its close is a- // single `history.back()`, so leaving it open would put the terminal- // behind a modal the user then has to dismiss to watch the install.+ // Close Settings first. The hash-routed dialog closes through one+ // `history.back()`; leaving it open would hide the terminal behind+ // a modal while the install runs.if (typeof window !== 'undefined' && isSettingsHashOpen(window.location.hash)) {window.history.back();}@@ -211,8 +208,8 @@ function StatusRow({ availability }: { availability: Availability }) {rel="noopener noreferrer"onClick={(e) => dispatchExternalLinkClick(e, SLIDEV_INSTALL_DOCS)}onAuxClick={(e) => dispatchExternalLinkClick(e, SLIDEV_INSTALL_DOCS)}- // Names its destination for anyone listing links out of context, where- // a bare "Other ways to install" says less.+ // Name the destination for link lists where a bare “Other ways to+ // install” lacks context.aria-label={t`Other ways to install Slidev`}className="inline-flex items-center gap-0.5 text-xs text-muted-foreground underline-offset-2 hover:text-foreground hover:underline"data-testid="slides-install-docs-link"@@ -236,8 +233,8 @@ export function SlidesPluginSection() {><SettingsSectionHeadertitleId="settings-plugin-slides-title"- // A product name, not a translatable label — passed raw the way the- // markdownlint panel passes its own.+ // Product name, not a translatable label; the markdownlint panel passes+ // its name raw too.title="Slidev"scope="user"betadiff --git a/packages/app/src/lib/keyboard-shortcuts.ts b/packages/app/src/lib/keyboard-shortcuts.tsindex 31049046a..611efd56d 100644--- a/packages/app/src/lib/keyboard-shortcuts.ts+++ b/packages/app/src/lib/keyboard-shortcuts.ts@@ -1104,6 +1104,13 @@ export function isEditableShortcutTarget(target: ShortcutTargetLike): boolean {return tagName === 'INPUT' || tagName === 'TEXTAREA';}+export function matchesPrimaryModifier(+ event: Pick<ShortcutEventLike, 'ctrlKey' | 'metaKey'>,+ platform: ShortcutPlatform = currentShortcutPlatform(),+): boolean {+ return platform === 'mac' ? event.metaKey && !event.ctrlKey : event.ctrlKey && !event.metaKey;+}+export function matchesKeyboardShortcut(event: ShortcutEventLike,id: KeyboardShortcutId,diff --git a/packages/app/src/locales/ar/messages.po b/packages/app/src/locales/ar/messages.poindex ddd0a015a..e98d538c4 100644--- a/packages/app/src/locales/ar/messages.po+++ b/packages/app/src/locales/ar/messages.po@@ -6355,6 +6355,7 @@ msgstr "إخفاء الشريط الجانبي"msgid "Hide skill nodes"msgstr "إخفاء عقد المهارات"+#: src/components/AppMenubar.tsx#: src/components/command-palette-commands.tsmsgid "Hide Terminal"msgstr "إخفاء Terminal"@@ -11671,6 +11672,7 @@ msgstr "إظهار عقد المهارات"msgid "Show source"msgstr "إظهار المصدر"+#: src/components/AppMenubar.tsx#: src/components/command-palette-commands.tsmsgid "Show Terminal"msgstr "إظهار Terminal"diff --git a/packages/app/src/locales/bn/messages.po b/packages/app/src/locales/bn/messages.poindex 2dcf985bb..fc6b6add1 100644--- a/packages/app/src/locales/bn/messages.po+++ b/packages/app/src/locales/bn/messages.po@@ -6351,6 +6351,7 @@ msgstr "সাইডবার লুকান"msgid "Hide skill nodes"msgstr "স্কিল নোড লুকান"+#: src/components/AppMenubar.tsx#: src/components/command-palette-commands.tsmsgid "Hide Terminal"msgstr "Terminal লুকান"@@ -11667,6 +11668,7 @@ msgstr "স্কিল নোড দেখান"msgid "Show source"msgstr "সোর্স দেখান"+#: src/components/AppMenubar.tsx#: src/components/command-palette-commands.tsmsgid "Show Terminal"msgstr "Terminal দেখান"diff --git a/packages/app/src/locales/en/messages.po b/packages/app/src/locales/en/messages.poindex b5e3ca85d..6554fb583 100644--- a/packages/app/src/locales/en/messages.po+++ b/packages/app/src/locales/en/messages.po@@ -6355,6 +6355,7 @@ msgstr "Hide sidebar"msgid "Hide skill nodes"msgstr "Hide skill nodes"+#: src/components/AppMenubar.tsx#: src/components/command-palette-commands.tsmsgid "Hide Terminal"msgstr "Hide Terminal"@@ -11671,6 +11672,7 @@ msgstr "Show skill nodes"msgid "Show source"msgstr "Show source"+#: src/components/AppMenubar.tsx#: src/components/command-palette-commands.tsmsgid "Show Terminal"msgstr "Show Terminal"diff --git a/packages/app/src/locales/es/messages.po b/packages/app/src/locales/es/messages.poindex 0b5bdbc2d..866ef0c02 100644--- a/packages/app/src/locales/es/messages.po+++ b/packages/app/src/locales/es/messages.po@@ -6355,6 +6355,7 @@ msgstr "Ocultar la barra lateral"msgid "Hide skill nodes"msgstr "Ocultar los nodos de habilidades"+#: src/components/AppMenubar.tsx#: src/components/command-palette-commands.tsmsgid "Hide Terminal"msgstr "Ocultar Terminal"@@ -11671,6 +11672,7 @@ msgstr "Mostrar los nodos de habilidades"msgid "Show source"msgstr "Mostrar el código"+#: src/components/AppMenubar.tsx#: src/components/command-palette-commands.tsmsgid "Show Terminal"msgstr "Mostrar Terminal"diff --git a/packages/app/src/locales/fr/messages.po b/packages/app/src/locales/fr/messages.poindex be55d8579..8452598c7 100644--- a/packages/app/src/locales/fr/messages.po+++ b/packages/app/src/locales/fr/messages.po@@ -6355,6 +6355,7 @@ msgstr "Masquer la barre latérale"msgid "Hide skill nodes"msgstr "Masquer les nœuds de compétences"+#: src/components/AppMenubar.tsx#: src/components/command-palette-commands.tsmsgid "Hide Terminal"msgstr "Masquer Terminal"@@ -11671,6 +11672,7 @@ msgstr "Afficher les nœuds de compétences"msgid "Show source"msgstr "Afficher la source"+#: src/components/AppMenubar.tsx#: src/components/command-palette-commands.tsmsgid "Show Terminal"msgstr "Afficher Terminal"diff --git a/packages/app/src/locales/hi/messages.po b/packages/app/src/locales/hi/messages.poindex 991c75855..fa7194b39 100644--- a/packages/app/src/locales/hi/messages.po+++ b/packages/app/src/locales/hi/messages.po@@ -6351,6 +6351,7 @@ msgstr "साइडबार छिपाएँ"msgid "Hide skill nodes"msgstr "स्किल नोड छिपाएँ"+#: src/components/AppMenubar.tsx#: src/components/command-palette-commands.tsmsgid "Hide Terminal"msgstr "Terminal छिपाएँ"@@ -11667,6 +11668,7 @@ msgstr "स्किल नोड दिखाएँ"msgid "Show source"msgstr "स्रोत दिखाएँ"+#: src/components/AppMenubar.tsx#: src/components/command-palette-commands.tsmsgid "Show Terminal"msgstr "Terminal दिखाएँ"diff --git a/packages/app/src/locales/id/messages.po b/packages/app/src/locales/id/messages.poindex 89c2a03e7..a9a79db38 100644--- a/packages/app/src/locales/id/messages.po+++ b/packages/app/src/locales/id/messages.po@@ -6351,6 +6351,7 @@ msgstr "Sembunyikan bilah sisi"msgid "Hide skill nodes"msgstr "Sembunyikan simpul keterampilan"+#: src/components/AppMenubar.tsx#: src/components/command-palette-commands.tsmsgid "Hide Terminal"msgstr "Sembunyikan Terminal"@@ -11667,6 +11668,7 @@ msgstr "Tampilkan simpul keterampilan"msgid "Show source"msgstr "Tampilkan sumber"+#: src/components/AppMenubar.tsx#: src/components/command-palette-commands.tsmsgid "Show Terminal"msgstr "Tampilkan Terminal"diff --git a/packages/app/src/locales/ko/messages.po b/packages/app/src/locales/ko/messages.poindex 6931912b5..31ee98e25 100644--- a/packages/app/src/locales/ko/messages.po+++ b/packages/app/src/locales/ko/messages.po@@ -6355,6 +6355,7 @@ msgstr "사이드바 가리기"msgid "Hide skill nodes"msgstr "스킬 노드 숨기기"+#: src/components/AppMenubar.tsx#: src/components/command-palette-commands.tsmsgid "Hide Terminal"msgstr "터미널 가리기"@@ -11671,6 +11672,7 @@ msgstr "스킬 노드 보기"msgid "Show source"msgstr "소스 보기"+#: src/components/AppMenubar.tsx#: src/components/command-palette-commands.tsmsgid "Show Terminal"msgstr "터미널 표시"diff --git a/packages/app/src/locales/pseudo/messages.po b/packages/app/src/locales/pseudo/messages.poindex cc41c0bee..ae0657f4a 100644--- a/packages/app/src/locales/pseudo/messages.po+++ b/packages/app/src/locales/pseudo/messages.po@@ -6351,6 +6351,7 @@ msgstr ""msgid "Hide skill nodes"msgstr ""+#: src/components/AppMenubar.tsx#: src/components/command-palette-commands.tsmsgid "Hide Terminal"msgstr ""@@ -11667,6 +11668,7 @@ msgstr ""msgid "Show source"msgstr ""+#: src/components/AppMenubar.tsx#: src/components/command-palette-commands.tsmsgid "Show Terminal"msgstr ""diff --git a/packages/app/src/locales/pt-BR/messages.po b/packages/app/src/locales/pt-BR/messages.poindex 8d31c53f2..b72c98e6e 100644--- a/packages/app/src/locales/pt-BR/messages.po+++ b/packages/app/src/locales/pt-BR/messages.po@@ -6351,6 +6351,7 @@ msgstr "Ocultar a barra lateral"msgid "Hide skill nodes"msgstr "Ocultar os nós de habilidades"+#: src/components/AppMenubar.tsx#: src/components/command-palette-commands.tsmsgid "Hide Terminal"msgstr "Ocultar o Terminal"@@ -11667,6 +11668,7 @@ msgstr "Mostrar os nós de habilidades"msgid "Show source"msgstr "Mostrar o código"+#: src/components/AppMenubar.tsx#: src/components/command-palette-commands.tsmsgid "Show Terminal"msgstr "Mostrar o Terminal"diff --git a/packages/app/src/locales/ur/messages.po b/packages/app/src/locales/ur/messages.poindex 267061607..277788a4f 100644--- a/packages/app/src/locales/ur/messages.po+++ b/packages/app/src/locales/ur/messages.po@@ -6355,6 +6355,7 @@ msgstr "سائیڈ بار چھپائیں"msgid "Hide skill nodes"msgstr "مہارت نوڈز چھپائیں"+#: src/components/AppMenubar.tsx#: src/components/command-palette-commands.tsmsgid "Hide Terminal"msgstr "Terminal چھپائیں"@@ -11671,6 +11672,7 @@ msgstr "مہارت نوڈز دکھائیں"msgid "Show source"msgstr "سورس دکھائیں"+#: src/components/AppMenubar.tsx#: src/components/command-palette-commands.tsmsgid "Show Terminal"msgstr "Terminal دکھائیں"diff --git a/packages/app/src/locales/zh-Hans/messages.po b/packages/app/src/locales/zh-Hans/messages.poindex de6fbd3b0..f15c60fc0 100644--- a/packages/app/src/locales/zh-Hans/messages.po+++ b/packages/app/src/locales/zh-Hans/messages.po@@ -6355,6 +6355,7 @@ msgstr "隐藏侧边栏"msgid "Hide skill nodes"msgstr "隐藏技能节点"+#: src/components/AppMenubar.tsx#: src/components/command-palette-commands.tsmsgid "Hide Terminal"msgstr "隐藏 Terminal"@@ -11671,6 +11672,7 @@ msgstr "显示技能节点"msgid "Show source"msgstr "显示源码"+#: src/components/AppMenubar.tsx#: src/components/command-palette-commands.tsmsgid "Show Terminal"msgstr "显示 Terminal"diff --git a/packages/app/src/locales/zh-Hant/messages.po b/packages/app/src/locales/zh-Hant/messages.poindex 55d4e209e..61dd3c0f1 100644--- a/packages/app/src/locales/zh-Hant/messages.po+++ b/packages/app/src/locales/zh-Hant/messages.po@@ -6355,6 +6355,7 @@ msgstr "隱藏側邊欄"msgid "Hide skill nodes"msgstr "隱藏技能節點"+#: src/components/AppMenubar.tsx#: src/components/command-palette-commands.tsmsgid "Hide Terminal"msgstr "隱藏 Terminal"@@ -11671,6 +11672,7 @@ msgstr "顯示技能節點"msgid "Show source"msgstr "顯示原始碼"+#: src/components/AppMenubar.tsx#: src/components/command-palette-commands.tsmsgid "Show Terminal"msgstr "顯示 Terminal"diff --git a/packages/desktop/electron-builder.yml b/packages/desktop/electron-builder.ymlindex 60bfa35e5..299cce00b 100644--- a/packages/desktop/electron-builder.yml+++ b/packages/desktop/electron-builder.yml@@ -11,8 +11,9 @@ copyright: Copyright © 2026 Inkeep# electron-rebuild / native-module ABI compilation cannot drift.electronVersion: "41.9.1"-# @electron/rebuild runs for mac and Windows from this config: mac needs-# node-pty's ABI rebuilt, Windows cross-builds its per-arch binaries.+# @electron/rebuild stays enabled for mac and Windows from this config because+# other native modules still use that pass. node-pty's N-API prebuilds do not+# require an Electron ABI rebuild.## Linux skips the pass instead, via the `electron-builder.linux.yml` overlay# (`npmRebuild: false`) — Linux builds MUST pass `--config@@ -396,7 +397,7 @@ win:# belong hardcoded here while unknown. Unsigned Windows artifacts are# never published (internal QA only).#- # The terminal dock is dark off-mac: node-pty and its+ # 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.#@@ -514,10 +515,15 @@ linux:# in builder-util rewrites `${arch}` per extension). deb and rpm therefore# never collide on a filename even where the arch word differs.artifactName: ${productName}-${arch}.${ext}- # Terminal dock dark off-mac — keep node-pty out, and keep native-config's- # darwin cargo `target/` tree out (see win.files for the rationale).+ # node-pty publishes every platform prebuild in one package. Drop+ # foreign-platform binaries and Windows debug symbols, but keep both Linux+ # prebuilds so each installer carries the correct ELF regardless of builder+ # architecture. native-config's darwin cargo `target/` tree stays excluded+ # (see win.files for the rationale).files:- - "!**/node_modules/node-pty/**"+ - "!**/node_modules/node-pty/prebuilds/**/*.pdb"+ - "!**/node_modules/node-pty/prebuilds/darwin-*/**"+ - "!**/node_modules/node-pty/prebuilds/win32-*/**"- "!**/node_modules/@inkeep/open-knowledge-native-config/target/**"extraResources:# Linux-layout wrapper ships under the same canonical destination asdiff --git a/packages/desktop/package.json b/packages/desktop/package.jsonindex 1617ca46f..a90bdecef 100644--- a/packages/desktop/package.json+++ b/packages/desktop/package.json@@ -48,7 +48,7 @@"yaml": "^2.8.3"},"optionalDependencies": {- "node-pty": "1.1.0"+ "node-pty": "1.2.0-beta.15"},"devDependencies": {"@electron/fuses": "^2.1.1",diff --git a/packages/desktop/scripts/afterPack.mjs b/packages/desktop/scripts/afterPack.mjsindex 4cd9dc42a..f748bf5b0 100644--- a/packages/desktop/scripts/afterPack.mjs+++ b/packages/desktop/scripts/afterPack.mjs@@ -99,9 +99,9 @@ export default async function afterPack(context) {// Everything below is darwin-only: the LSUIElement helper bundle exists to// suppress the macOS Dock "exec" placeholder (no Dock/LaunchServices// concept on win/linux — resolve-detached-spawn-args.ts uses- // parentExecPath directly there), and the node-pty spawn-helper chmod is- // moot off-mac (the terminal dock is dark on win/linux per D7; node-pty is- // excluded from those packages via win.files/linux.files).+ // parentExecPath directly there). The node-pty chmod is also mac-specific:+ // Linux prebuilds do not use a separate spawn-helper, while the Windows+ // package excludes node-pty.if (electronPlatformName !== 'darwin') {console.log(`[afterPack] fuses done; skipping darwin-only helper-bundle + node-pty steps on "${electronPlatformName}"`,diff --git a/packages/desktop/scripts/ensure-node-pty-exec.mjs b/packages/desktop/scripts/ensure-node-pty-exec.mjsindex ae91f3c7d..c57f62250 100644--- a/packages/desktop/scripts/ensure-node-pty-exec.mjs+++ b/packages/desktop/scripts/ensure-node-pty-exec.mjs@@ -9,7 +9,7 @@ import { dirname, join } from 'node:path';* node-pty ships prebuilt binaries under* `node-pty/prebuilds/<platform>-<arch>/{pty.node,spawn-helper}`, and the* prebuilt `spawn-helper` is mode 0644 — not executable (node-pty#850). Both- * producers that lay it on disk preserve that non-executable mode — `bun install`+ * producers that lay it on disk preserve that non-executable mode — `pnpm install`* for the dev tree, electron-builder's asarUnpack for the packed app — so* `pty.fork()` dies at runtime with "posix_spawnp failed" and the in-app terminal* never spawns a shell.@@ -20,7 +20,7 @@ import { dirname, join } from 'node:path';* electron-builder re-signs (the Developer ID signature covers the +x bit).* - DEV / CI (`ensureNodePtySpawnHelperExecutableInNodeModules`) — the desktop* postinstall, against the real `node_modules/node-pty/prebuilds` tree, so- * `bun run build:desktop` / `dev:electron` / smoke launches get a working+ * `pnpm run build:desktop` / `dev:electron` / smoke launches get a working* terminal without packaging.** We ship arm64-only (mac.target), so the darwin-arm64 helper is load-bearing and@@ -30,6 +30,11 @@ import { dirname, join } from 'node:path';const SHIPPED_ARCH = 'darwin-arm64';+/** The spawn-helper is a Darwin node-pty prebuild detail. */+export function shouldEnsureNodePtySpawnHelper(platform = process.platform) {+ return platform === 'darwin';+}+/*** chmod 0755 every `<arch>/spawn-helper` under a node-pty `prebuilds` directory.* Throws if the load-bearing SHIPPED_ARCH helper is absent.@@ -89,8 +94,8 @@ export function ensureNodePtySpawnHelperExecutable(resourcesDir) {/*** DEV / CI build+install path (desktop postinstall).*- * `bun install` leaves the prebuilt helper non-executable, and the dev build- * (`bun run build:desktop` / `dev:electron`, electron-vite, no afterPack) has no+ * `pnpm install` leaves the prebuilt helper non-executable, and the dev build+ * (`pnpm run build:desktop` / `dev:electron`, electron-vite, no afterPack) has no* step to fix it. Resolves the same node-pty the runtime loads; the `nodePtyDir`* parameter is for tests to point at a fixture.*@@ -100,7 +105,7 @@ export function ensureNodePtySpawnHelperExecutable(resourcesDir) {export function ensureNodePtySpawnHelperExecutableInNodeModules(nodePtyDir = resolveNodePtyDir()) {return chmodSpawnHelpersUnderPrebuilds(join(nodePtyDir, 'prebuilds'),- `Confirm node-pty is installed (it is a desktop dependency) and 'bun install' did not run ` ++ `Confirm node-pty is installed (it is a desktop dependency) and 'pnpm install' did not run ` +`with --ignore-scripts — without an executable spawn-helper, pty.fork() fails at runtime ` +`with "posix_spawnp failed" and the in-app terminal cannot spawn a shell.`,);@@ -112,7 +117,7 @@ export function ensureNodePtySpawnHelperExecutableInNodeModules(nodePtyDir = res/*** Non-throwing wrapper around {@link ensureNodePtySpawnHelperExecutableInNodeModules}- * for the desktop postinstall. The postinstall must NEVER fail `bun install` over a+ * for the desktop postinstall. The postinstall must NEVER fail `pnpm install` over a* pathological node-pty layout (a partially-broken install, an absent shipped-arch* prebuild) — that would gate the whole monorepo. This converts the throw into a* `{ ok: false, error }` result so the caller stays exit-0; the caller owns logging.diff --git a/packages/desktop/scripts/postinstall.mjs b/packages/desktop/scripts/postinstall.mjsindex 34e1e5a05..5538b4b75 100644--- a/packages/desktop/scripts/postinstall.mjs+++ b/packages/desktop/scripts/postinstall.mjs@@ -1,12 +1,12 @@#!/usr/bin/env node/*** Desktop postinstall — two install-producer fix-ups: (1) make node-pty's prebuilt- * `spawn-helper` executable for the dev/CI build (the afterPack analog; runs first,- * unconditionally), then (2) rebuild native modules (`@parcel/watcher`, etc.) against+ * Darwin `spawn-helper` executable for the dev/CI build (the afterPack analog; runs+ * first on macOS), then (2) rebuild native modules (`@parcel/watcher`, etc.) against* the pinned Electron Node ABI so packaged + dev loads can `dlopen` the binaries.** Agent-first default runs `electron-builder install-app-deps` on every- * `bun install`. Non-desktop contributors opt out via `ELECTRON_SKIP_REBUILD=1` in+ * `pnpm install`. Non-desktop contributors opt out via `ELECTRON_SKIP_REBUILD=1` in* their shell profile — saves ~150MB of Electron headers on first install and a* few seconds on subsequent ones.*@@ -14,27 +14,32 @@* runs cross-platform (macOS / Linux / Windows) without shell-syntax surprises.*/import { spawn } from 'node:child_process';-import { ensureNodePtySpawnHelperExecutableInNodeModulesSafe } from './ensure-node-pty-exec.mjs';+import {+ ensureNodePtySpawnHelperExecutableInNodeModulesSafe,+ shouldEnsureNodePtySpawnHelper,+} from './ensure-node-pty-exec.mjs';// node-pty ships its prebuilt `spawn-helper` non-executable (node-pty#850) and-// `bun install` preserves that mode, so the dev/CI build (`bun run build:desktop`+// `pnpm install` preserves that mode, so the dev/CI build (`pnpm run build:desktop`// / `dev:electron`, electron-vite, no afterPack) launches with a terminal that// dies "posix_spawnp failed". The packaged `.app` fixes this in afterPack; this is// the dev/CI analog at the install producer that strips the bit. It runs FIRST and-// UNCONDITIONALLY — before the ELECTRON_SKIP_REBUILD / CI early-exits below —-// because CI desktop-smoke is one of the affected environments and the +x bit is+// on Darwin before the ELECTRON_SKIP_REBUILD / CI early-exits below because macOS+// desktop-smoke is one of the affected environments and the +x bit is// independent of the electron-builder native rebuild those guards gate. The Safe// wrapper never throws so a pathological node-pty layout can't gate the whole-// monorepo's `bun install` (matching this script's install-app-deps stance below).-const spawnHelper = ensureNodePtySpawnHelperExecutableInNodeModulesSafe();-if (spawnHelper.ok) {- console.log(- `[desktop postinstall] node-pty spawn-helper marked executable (${spawnHelper.chmodded.length} file(s))`,- );-} else {- console.warn(- `[desktop postinstall] could not make node-pty spawn-helper executable: ${spawnHelper.error.message}`,- );+// workspace's `pnpm install` (matching this script's install-app-deps stance below).+if (shouldEnsureNodePtySpawnHelper()) {+ const spawnHelper = ensureNodePtySpawnHelperExecutableInNodeModulesSafe();+ if (spawnHelper.ok) {+ console.log(+ `[desktop postinstall] node-pty spawn-helper marked executable (${spawnHelper.chmodded.length} file(s))`,+ );+ } else {+ console.warn(+ `[desktop postinstall] could not make node-pty spawn-helper executable: ${spawnHelper.error.message}`,+ );+ }}if (process.env.ELECTRON_SKIP_REBUILD === '1') {@@ -49,7 +54,7 @@ if (process.env.ELECTRON_SKIP_REBUILD === '1') {// `install-app-deps` (electron's platform binary isn't guaranteed present,// and when it's missing electron-builder errors with "Cannot compute// electron version from installed node modules" — that cascades into every-// downstream typecheck/test/lint job failing at `bun install`). Desktop+// downstream typecheck/test/lint job failing at `pnpm install`). Desktop// contributors running CI manually can set ELECTRON_SKIP_REBUILD=0 to// opt back in — the opt-out is for machines that don't need it.if (process.env.CI && process.env.ELECTRON_SKIP_REBUILD !== '0') {@@ -61,7 +66,7 @@ if (process.env.CI && process.env.ELECTRON_SKIP_REBUILD !== '0') {}// Local desktop dev — run install-app-deps but soften failures to a warning.-// A broken install shouldn't gate the whole monorepo's `bun install`.+// A broken install shouldn't gate the whole workspace's `pnpm install`.const child = spawn('electron-builder', ['install-app-deps'], {stdio: 'inherit',shell: true,@@ -84,6 +89,6 @@ child.on('error', (err) => {err instanceof Error ? err.message : String(err)}`,);- console.warn('[desktop postinstall] Skipping — run `bun run rebuild:native` manually if needed');+ console.warn('[desktop postinstall] Skipping — run `pnpm run rebuild:native` manually if needed');process.exit(0);});diff --git a/packages/desktop/scripts/smoke-linux-terminal-package.py b/packages/desktop/scripts/smoke-linux-terminal-package.pynew file mode 100755index 000000000..21dc0da18--- /dev/null+++ b/packages/desktop/scripts/smoke-linux-terminal-package.py@@ -0,0 +1,117 @@+#!/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.shnew file mode 100755index 000000000..9798ad69e--- /dev/null+++ b/packages/desktop/scripts/smoke-linux-terminal-package.sh@@ -0,0 +1,267 @@+#!/usr/bin/env bash+set -euo pipefail++# One-time pre-ship verification for packaged Linux terminals. Run both Fedora+# rows on matching native hosts, then run one Debian 11 row to anchor the+# Electron-inherited glibc generation documented for Linux:+#+# ./scripts/smoke-linux-terminal-package.sh \+# --image fedora:41 --arch x86_64 --package dist-desktop/OpenKnowledge-x86_64.rpm+# ./scripts/smoke-linux-terminal-package.sh \+# --image fedora:41 --arch aarch64 --package dist-desktop/OpenKnowledge-aarch64.rpm+# ./scripts/smoke-linux-terminal-package.sh \+# --image debian:11 --arch x86_64 --package dist-desktop/OpenKnowledge-amd64.deb+#+# These are deliberate one-time package rows, not recurring CI. The recurring+# rpm metadata guard remains electron-builder-linux-depends-parity.test.ts.+#+# Chromium first launches with its normal sandbox. In containers where user+# namespaces prevent startup, OK_CONTAINER_SANDBOX=auto retries once with+# --no-sandbox. Set OK_CONTAINER_SANDBOX=require to prohibit that fallback, or+# 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"++usage() {+ printf '%s\n' \+ 'Usage:' \+ ' smoke-linux-terminal-package.sh --image IMAGE --arch ARCH --package PATH' \+ '' \+ 'Images: fedora:41 for rpm, debian:11 or ubuntu:20.04 for deb.' \+ 'Architectures: x86_64 or aarch64 (amd64 and arm64 aliases are accepted).'+}++fail() {+ printf 'ERROR: %s\n' "$*" >&2+ exit 1+}++normalize_arch() {+ case "$1" in+ x86_64 | amd64)+ printf 'x86_64\n'+ ;;+ aarch64 | arm64)+ printf 'aarch64\n'+ ;;+ *)+ fail "unsupported architecture '$1'; expected x86_64 or aarch64"+ ;;+ esac+}++docker_platform() {+ case "$1" in+ x86_64) printf 'linux/amd64\n' ;;+ aarch64) printf 'linux/arm64\n' ;;+ esac+}++resolve_package_path() {+ local input=$1+ [[ -f "$input" ]] || fail "package artifact not found: $input"+ [[ -s "$input" ]] || fail "package artifact is empty: $input"+ local directory+ directory=$(cd "$(dirname "$input")" && pwd -P)+ printf '%s/%s\n' "$directory" "$(basename "$input")"+}++wait_for_debugger() {+ local attempts_remaining=40+ while ((attempts_remaining > 0)); do+ if curl -fsS http://127.0.0.1:9222/json/version >/dev/null 2>&1; then+ return 0+ fi+ sleep 0.5+ attempts_remaining=$((attempts_remaining - 1))+ done+ return 1+}++stop_app() {+ pkill -TERM -u ok-smoke >/dev/null 2>&1 || true+ sleep 1+ pkill -KILL -u ok-smoke >/dev/null 2>&1 || true+}++launch_app() {+ local executable=$1+ local sandbox=$2+ local -a flags=(+ --disable-gpu+ --remote-debugging-address=127.0.0.1+ --remote-debugging-port=9222+ '--remote-allow-origins=*'+ --user-data-dir=/tmp/ok-smoke-user-data+ )+ if [[ "$sandbox" == disable ]]; then+ flags+=(--no-sandbox)+ fi++ runuser -u ok-smoke -- env \+ HOME=/home/ok-smoke \+ DISPLAY=:99 \+ OK_DESKTOP_E2E_SMOKE=1 \+ "$executable" \+ "${flags[@]}" \+ 'openknowledge://open?project=%2Ftmp%2Fok-smoke-project&doc=start' \+ >/tmp/openknowledge-smoke.log 2>&1 &+}++install_container_dependencies() {+ local image=$1+ local artifact=$2+ case "$image" in+ fedora:*)+ [[ "$artifact" == *.rpm ]] || fail "Fedora rows require an .rpm artifact"+ dnf install -y \+ "$artifact" \+ curl \+ procps-ng \+ python3-websocket-client \+ shadow-utils \+ util-linux \+ xorg-x11-server-Xvfb+ ;;+ debian:* | ubuntu:*)+ [[ "$artifact" == *.deb ]] || fail "Debian/Ubuntu rows require a .deb artifact"+ export DEBIAN_FRONTEND=noninteractive+ apt-get update+ apt-get install -y \+ "$artifact" \+ curl \+ passwd \+ procps \+ python3-websocket \+ util-linux \+ xvfb+ ;;+ *)+ fail "unsupported image '$image'; use fedora:41, debian:11, or ubuntu:20.04"+ ;;+ esac+}++inside_container() {+ local image=$1+ local requested_arch=$2+ local artifact=$3+ local sandbox_mode=${OK_CONTAINER_SANDBOX:-auto}++ case "$sandbox_mode" in+ auto | require | disable) ;;+ *) fail "OK_CONTAINER_SANDBOX must be auto, require, or disable" ;;+ esac++ local actual_arch+ actual_arch=$(normalize_arch "$(uname -m)")+ [[ "$actual_arch" == "$requested_arch" ]] ||+ fail "container architecture is $actual_arch, expected $requested_arch"++ install_container_dependencies "$image" "$artifact"+ command -v openknowledge >/dev/null 2>&1 ||+ fail "installed package did not provide the openknowledge executable"++ useradd --create-home --shell /bin/bash ok-smoke+ install -d -o ok-smoke -g ok-smoke \+ /tmp/ok-smoke-project/.ok/local \+ /tmp/ok-smoke-user-data+ printf "content:\n dir: '.'\n" >/tmp/ok-smoke-project/.ok/config.yml+ printf 'terminal:\n enabled: true\n' >/tmp/ok-smoke-project/.ok/local/config.yml+ printf '# Container terminal smoke\n' >/tmp/ok-smoke-project/start.md+ chown -R ok-smoke:ok-smoke /tmp/ok-smoke-project /tmp/ok-smoke-user-data++ Xvfb :99 -screen 0 1280x800x24 >/tmp/xvfb.log 2>&1 &+ local xvfb_pid=$!+ trap 'stop_app; kill "$xvfb_pid" >/dev/null 2>&1 || true' EXIT++ local launch_mode=$sandbox_mode+ if [[ "$launch_mode" == auto ]]; then+ launch_mode=require+ fi+ printf 'Launching installed app with sandbox mode: %s\n' "$launch_mode"+ launch_app "$(command -v openknowledge)" "$launch_mode"++ if ! wait_for_debugger; then+ if [[ "$sandbox_mode" != auto ]]; then+ tail -80 /tmp/openknowledge-smoke.log >&2 || true+ fail "installed app never exposed its debugging endpoint"+ fi+ printf '%s\n' 'Sandboxed launch did not start; retrying once with --no-sandbox.'+ stop_app+ launch_app "$(command -v openknowledge)" disable+ if ! wait_for_debugger; then+ tail -80 /tmp/openknowledge-smoke.log >&2 || true+ fail "installed app did not start even with --no-sandbox"+ fi+ fi++ runuser -u ok-smoke -- python3 /tmp/smoke-linux-terminal-package.py+ printf 'PASS: installed %s package launched and completed a packaged PTY echo round-trip\n' "$requested_arch"+}++host_main() {+ local image=''+ local arch=''+ local package=''+ while (($# > 0)); do+ case "$1" in+ --image)+ (($# >= 2)) || fail '--image requires a value'+ image=$2+ shift 2+ ;;+ --arch)+ (($# >= 2)) || fail '--arch requires a value'+ arch=$2+ shift 2+ ;;+ --package)+ (($# >= 2)) || fail '--package requires a value'+ package=$2+ shift 2+ ;;+ -h | --help)+ usage+ return 0+ ;;+ *) fail "unknown argument: $1" ;;+ esac+ done++ [[ -n "$image" ]] || fail '--image is required'+ [[ -n "$arch" ]] || fail '--arch is required'+ [[ -n "$package" ]] || fail '--package is required'+ local normalized_arch+ normalized_arch=$(normalize_arch "$arch")+ local absolute_package+ absolute_package=$(resolve_package_path "$package")+ command -v docker >/dev/null 2>&1 ||+ fail 'docker is unavailable; run these one-time package rows on a Docker host'+ [[ -f "$DRIVER_PATH" ]] || fail "PTY smoke driver not found: $DRIVER_PATH"++ local extension=${absolute_package##*.}+ local container_artifact="/tmp/OpenKnowledge.$extension"++ if ! docker pull --platform "$(docker_platform "$normalized_arch")" "$image"; then+ fail "container image unavailable: $image ($(docker_platform "$normalized_arch"))"+ fi++ docker run --rm \+ --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" \+ --env "OK_CONTAINER_SANDBOX=${OK_CONTAINER_SANDBOX:-auto}" \+ "$image" \+ bash /tmp/smoke-linux-terminal-package.sh \+ --inside "$image" "$normalized_arch" "$container_artifact"+}++if [[ "${1:-}" == --inside ]]; then+ (($# == 4)) || fail 'internal invocation requires image, architecture, and artifact'+ inside_container "$2" "$3" "$4"+else+ host_main "$@"+fidiff --git a/packages/desktop/src/main/claude-readiness.ts b/packages/desktop/src/main/claude-readiness.tsindex f0c6858ae..86fcdfad1 100644--- a/packages/desktop/src/main/claude-readiness.ts+++ b/packages/desktop/src/main/claude-readiness.ts@@ -2,47 +2,51 @@* Claude Code readiness for the docked terminal.** Two facts make typing `claude` "just work" inside the terminal:- * 1. `claude` resolves on the login shell's PATH (so the user gets a real+ * 1. `claude` resolves on the interactive shell's PATH (so the user gets a real* Claude Code, not "command not found").* 2. `~/.claude.json` carries the `open-knowledge` MCP server (so that* `claude` already sees OK tools — the once-per-Mac MCP consent may have* been skipped or raced, leaving a `claude` with no tools).*- * This module computes both. The PATH check is a one-shot login-shell probe- * (`$SHELL -l -i -c 'command -v claude'`, matching the PTY's own- * `$SHELL -l -i`), with the `spawn` and timer injected so the probe's+ * This module computes both. The PATH check is a one-shot interactive-shell+ * probe, matching the PTY's platform argv (`-l -i` on macOS, `-i` on Linux),+ * with the `spawn` and timer injected so the probe's* timeout/exit-code/error logic is unit-testable without a real subprocess.* The MCP check reuses the CLI's `classifyExistingMcpEntry` (passed in by the* caller as a thunk over `~/.claude.json`).** Electron-free by construction — no `electron` import, every effect injected —- * so the routing logic runs under `bun test`. The real subprocess + the real+ * so the routing logic runs under Vitest. The real subprocess + the real* `~/.claude.json` read are the runtime e2e rung (a built terminal).*/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 { getLogger } from './desktop-logger.ts';export type ClaudeOnPath = ClaudeReadiness['claude'];export type McpWiringStatus = ClaudeReadiness['mcp'];/**- * Probe argv for a given binary. Matches the PTY's `$SHELL -l -i` (pty-host.ts)- * plus `-c` so the probe resolves `<bin>` against exactly the PATH the- * interactive shell will have (login + interactive profiles sourced).+ * Probe argv for a given binary. Matches the PTY's interactive argv+ * (pty-host.ts) plus `-c` so the probe resolves `<bin>` against exactly the+ * PATH the terminal shell will have.* `command -v` is POSIX, exits 0 iff `<bin>` resolves. `<bin>` is a fixed* registry value (`TERMINAL_CLIS[*].bin`), never user input — no injection* surface.*/-export function cliProbeArgs(bin: string): readonly string[] {- return ['-l', '-i', '-c', `command -v ${bin}`];+export function cliProbeArgs(+ bin: string,+ platform: NodeJS.Platform = process.platform,+): readonly string[] {+ return [...interactiveShellArgs(platform), '-c', `command -v ${bin}`];}/** The `claude` probe argv — `cliProbeArgs('claude')`, named for the legacy* readiness path + its unit tests. */-export const CLAUDE_PROBE_ARGS: readonly string[] = cliProbeArgs('claude');+export const CLAUDE_PROBE_ARGS: readonly string[] = cliProbeArgs('claude', process.platform);const PROBE_TIMEOUT_MS = 5000;@@ -66,7 +70,7 @@ export interface ProbeTimers {}/**- * Run the login-shell `command -v claude` probe. Resolves the child's exit+ * 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`@@ -94,18 +98,18 @@ export function runLoginShellProbe(} catch (err) {// partial-failure boundary: spawn can throw synchronously on resource// exhaustion. Claude presence is UNKNOWN, not absent.- getLogger('login-shell-probe').warn(+ getLogger('interactive-shell-probe').warn({ shell, args, err },- 'login-shell PATH probe spawn threw; presence unknown',+ 'interactive-shell PATH probe spawn threw; presence unknown',);resolve(null);return;}let settled = false;const timer = timers.setTimer(() => {- getLogger('login-shell-probe').warn(+ getLogger('interactive-shell-probe').warn({ shell, args, timeoutMs },- 'login-shell PATH probe timed out; presence unknown',+ 'interactive-shell PATH probe timed out; presence unknown',);child.kill();finish(null);@@ -118,9 +122,9 @@ export function runLoginShellProbe(}child.onError((err) => {if (!settled) {- getLogger('login-shell-probe').warn(+ getLogger('interactive-shell-probe').warn({ shell, args, err },- 'login-shell PATH probe failed to run; presence unknown',+ 'interactive-shell PATH probe failed to run; presence unknown',);}finish(null);@@ -142,7 +146,7 @@ export function mcpStatusFromClassification(kind: McpEntryKind): McpWiringStatus}export interface ResolveClaudeReadinessDeps {- /** Runs the login-shell PATH probe; resolves the exit code or `null`. */+ /** Runs the interactive-shell PATH probe; resolves the exit code or `null`. */probeClaude(): Promise<number | null>;/** `classifyExistingMcpEntry('claude', home).kind` over `~/.claude.json`. */classifyMcpEntry(): McpEntryKind;@@ -200,7 +204,7 @@ export async function resolveClaudeReadiness(}export interface ResolveCliOnPathDeps {- /** Runs the login-shell PATH probe for the CLI's binary; resolves the exit+ /** Runs the interactive-shell PATH probe for the CLI's binary; resolves the exit* code or `null` (probe failed → UNKNOWN). */probe(): Promise<number | null>;/** Codex-only: whether OK's MCP server is already configured in the user's@@ -293,7 +297,7 @@ export function resolvePlatformCliInstalledMap(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));+ return deps.probePosix(cliProbeArgs(bin, deps.platform));},});}diff --git a/packages/desktop/src/main/index.ts b/packages/desktop/src/main/index.tsindex 646fdb58b..d0f253117 100644--- a/packages/desktop/src/main/index.ts+++ b/packages/desktop/src/main/index.ts@@ -166,6 +166,7 @@ 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 { resolveShell } from '../utility/pty-host.ts';import { buildAboutPanelOptions } from './about-panel.ts';@@ -322,6 +323,7 @@ import {runMcpWiringOnFirstLaunch,} from './mcp-wiring.ts';import { installApplicationMenu } from './menu.ts';+import { resolveMenuActionTarget } from './menu-action-target.ts';import type { MenuTranslator } from './menu-translator.ts';import { beginNavigatorHandoff, createNavigatorWindow } from './navigator-window.ts';import {@@ -3210,8 +3212,8 @@ async function runApplicationMenuRefresh(): Promise<void> {// Window torn down mid-dispatch — the click degrades to a no-op.});},- onReportBug: () => sendMenuActionToFocused('report-bug'),- onSendFeedback: () => sendMenuActionToFocused('send-feedback'),+ onReportBug: () => sendMenuAction('report-bug'),+ onSendFeedback: () => sendMenuAction('send-feedback'),// App-menu / Help-menu "Check for Updates…" entries fire this. Returns// void: the menu doesn't surface in-flight progress; the existing// `update-available` / `update-not-available` electron-updater events@@ -3235,8 +3237,8 @@ async function runApplicationMenuRefresh(): Promise<void> {}): undefined,// View menu history traversal uses the same focused-renderer action channel.- onNavigateBack: () => sendMenuActionToFocused('navigate-back'),- onNavigateForward: () => sendMenuActionToFocused('navigate-forward'),+ onNavigateBack: () => sendMenuAction('navigate-back'),+ onNavigateForward: () => sendMenuAction('navigate-forward'),noteWindow: focusedWindow !== null && getNoteWindowContext(focusedWindow.id) !== undefined,// File menu state-aware items. activeTarget drives enable/disable;// per-item handlers fire `ok:menu-action` to the focused renderer which@@ -3255,40 +3257,39 @@ async function runApplicationMenuRefresh(): Promise<void> {if (!docName) return;openNoteWindowForDoc({ origin: focused, docName, entryPoint: 'window-menu' });},- onNewFile: () => sendMenuActionToFocused('new-doc'),- onNewFolder: () => sendMenuActionToFocused('new-folder'),- onNewFromTemplate: () => sendMenuActionToFocused('new-from-template'),+ onNewFile: () => sendMenuAction('new-doc'),+ onNewFolder: () => sendMenuAction('new-folder'),+ onNewFromTemplate: () => sendMenuAction('new-from-template'),// New project… — opens the create-new-project dialog in the// focused window. Both window kinds (editor App, NavigatorApp) subscribe// to this action and mount CreateProjectDialog.- onNewProject: () => sendMenuActionToFocused('new-project'),+ onNewProject: () => sendMenuAction('new-project'),// Worktree selector (worktree = window). Both delegate to the// focused renderer's ProjectSwitcher surface: `new-worktree` opens the// create dialog, `switch-worktree` opens the sidebar switcher.- onNewWorktree: () => sendMenuActionToFocused('new-worktree'),- onSwitchWorktree: () => sendMenuActionToFocused('switch-worktree'),- onRename: () => sendMenuActionToFocused('rename'),- onDuplicate: () => sendMenuActionToFocused('duplicate'),- onMoveToTrash: () => sendMenuActionToFocused('move-to-trash'),- onCloseActiveTabOrWindow: () => sendMenuActionToFocused('close-active-tab-or-window'),- onRevealInFinder: () => sendMenuActionToFocused('reveal-in-finder'),- onSendToAi: () => sendMenuActionToFocused('send-to-ai'),- onCopyFullPath: () => sendMenuActionToFocused('copy-full-path'),- onCopyRelativePath: () => sendMenuActionToFocused('copy-relative-path'),+ onNewWorktree: () => sendMenuAction('new-worktree'),+ onSwitchWorktree: () => sendMenuAction('switch-worktree'),+ onRename: () => sendMenuAction('rename'),+ onDuplicate: () => sendMenuAction('duplicate'),+ onMoveToTrash: () => sendMenuAction('move-to-trash'),+ onCloseActiveTabOrWindow: () => sendMenuAction('close-active-tab-or-window'),+ onRevealInFinder: () => sendMenuAction('reveal-in-finder'),+ onSendToAi: () => sendMenuAction('send-to-ai'),+ onCopyFullPath: () => sendMenuAction('copy-full-path'),+ onCopyRelativePath: () => sendMenuAction('copy-relative-path'),// View menu items reflect the latest renderer-pushed snapshot via// `ok:editor:view-menu-state-changed`; `buildViewMenuStateDeps` owns the// field/action mapping. Toggling fires `ok:menu-action` which the// renderer routes through `projectLocalBinding.patch(...)`; the// resulting CRDT mutation triggers a sibling push back so the checkmark// snaps.- ...buildViewMenuStateDeps(editorViewMenuState, sendMenuActionToFocused),- // Terminal dock is dark off-mac (windows-linux-port terminal posture): node-pty- // is not bundled on win/linux, so strip every terminal handler there —- // the menu items render disabled instead of surfacing a spawn failure.+ ...buildViewMenuStateDeps(editorViewMenuState, sendMenuAction),+ // Unsupported platforms strip every PTY-backed terminal handler so their+ // menu items render disabled instead of surfacing a spawn failure.// 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.- ...(process.platform === 'darwin'+ ...(isTerminalPlatform(process.platform)? { onNewTerminalWindow: () => openTerminalWindow() }: {onToggleTerminal: undefined,@@ -4022,15 +4023,19 @@ async function runDesktopUninstallUiPreview(mode: DesktopUninstallFlowPreviewMod}/**- * Dispatch an `OkMenuAction` to the focused renderer window. Mirrors the- * `openInstallSkillDialog` / `openSettings` pattern — falls back to the first- * BrowserWindow when no window is focused (menu clicked from the Dock).+ * Dispatch an `OkMenuAction` to its originating renderer when available.+ * Native-menu callers have no sender and use the focused window, then the first+ * BrowserWindow (for a menu click from the Dock).* Silent no-op when no windows are open (e.g. last project closed but app* still running on macOS via the Dock).*/-function sendMenuActionToFocused(action: OkMenuAction): void {- const target = BrowserWindow.getFocusedWindow() ?? BrowserWindow.getAllWindows()[0];+function sendMenuAction(action: OkMenuAction, sender: WebContents | null = null): void {+ const target = resolveMenuActionTarget(sender, {+ fromWebContents: (contents) => BrowserWindow.fromWebContents(contents),+ getFocusedWindow: () => BrowserWindow.getFocusedWindow(),+ getAllWindows: () => BrowserWindow.getAllWindows(),+ });if (!target) return;sendToRenderer(target.webContents, 'ok:menu-action', action);}@@ -4630,7 +4635,7 @@ function formatUnknownError(err: unknown): string {}/**- * Run a login-shell `command -v <bin>` probe in the real shell (the same+ * 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@@ -4674,7 +4679,7 @@ function probeLoginShellOnPath(args?: readonly string[]): Promise<number | null>},};},- resolveShell(process.env),+ resolveShell(process.env, { platform: process.platform }),{setTimer: (cb, ms) => setTimeout(cb, ms),clearTimer: (token) => clearTimeout(token as ReturnType<typeof setTimeout>),@@ -4705,7 +4710,7 @@ function isProjectClaudeMcpOwn(projectRoot: string | undefined): boolean {/*** Resolve docked-terminal Claude Code readiness: probe `claude` on the- * login-shell PATH, classify the user-global `open-knowledge` entry in+ * terminal shell's PATH, classify the user-global `open-knowledge` entry in* `~/.claude.json`, and verify the PROJECT's `.mcp.json` `open-knowledge` entry* is OK's own (gates MCP pre-approval). The real subprocess + config reads are* the runtime e2e rung (a built terminal).@@ -4727,7 +4732,7 @@ function resolveTerminalClaudeReadiness(projectRoot: string | undefined): Promis*/function resolveTerminalCliOnPath(cli: TerminalCli): Promise<CliReadiness> {return resolveCliOnPath({- probe: () => probeLoginShellOnPath(cliProbeArgs(TERMINAL_CLIS[cli].bin)),+ probe: () => probeLoginShellOnPath(cliProbeArgs(TERMINAL_CLIS[cli].bin, process.platform)),// 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@@ -5664,7 +5669,8 @@ function registerIpcHandlers() {// Windows/Linux renderer-menubar dispatch (the windows-linux-port renderer-menubar decision).// The renderer-drawn menu bar routes every click here so menu semantics// stay single-sourced with the native template: `menu-action` relays- // through the exact `sendMenuActionToFocused` path the native items use,+ // through the same menu-action path the native items use while preferring+ // the dispatching renderer over focus state,// `role` maps onto what Electron menu roles do, `command` reuses the// same click handlers the native deps wire, and `query` returns the// aggregated state (`activeTarget` + view-menu snapshot + recents +@@ -5688,7 +5694,7 @@ function registerIpcHandlers() {})(),};case 'menu-action':- sendMenuActionToFocused(request.action);+ sendMenuAction(request.action, event.sender);return undefined;case 'open-recent-project':await openProjectOrFallbackToNavigator(request.path, 'recents');@@ -5733,10 +5739,9 @@ function registerIpcHandlers() {// Ephemeral single-file windows carry teardown state on `ctx.ephemeral`;// its presence IS the single-file signal for the renderer's chrome gate.singleFile: ctx.ephemeral !== undefined,- // Mirrors the preload's cold-start config: pty capability is a- // platform fact (node-pty ships on macOS only), identical for a- // re-queried live window.- ptyAvailable: process.platform === 'darwin',+ // Mirrors the preload's cold-start config: PTY capability is the same+ // platform fact for a re-queried live window.+ ptyAvailable: isTerminalPlatform(process.platform),// `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.@@ -5781,7 +5786,7 @@ function registerIpcHandlers() {: undefined;const probes = {isExecutableFile: realIsExecutableFile,- // The login-shell probe exists for the macOS/Linux GUI-PATH problem: a+ // The interactive-shell probe exists for the macOS/Linux GUI-PATH problem: a// desktop-launched process does not source the user's rc files, so a// globally-installed binary is invisible to `process.env.PATH`. Windows// has neither that problem (a GUI process inherits the user PATH from the@@ -5790,7 +5795,7 @@ function registerIpcHandlers() {isOnLoginPath: async (bin: string) =>process.platform === 'win32'? await probeWindowsPath(bin)- : (await probeLoginShellOnPath(cliProbeArgs(bin))) === 0,+ : (await probeLoginShellOnPath(cliProbeArgs(bin, process.platform))) === 0,};if (request.kind === 'status') {return handleSlidesStatus(projectRoot, probes);@@ -5844,7 +5849,10 @@ function registerIpcHandlers() {startDeps: {findFreePort,spawnSlidev: (port) => {- const base = { docPath: resolvedDocPath, shell: resolveShell(process.env) };+ const base = {+ docPath: resolvedDocPath,+ shell: resolveShell(process.env, { platform: process.platform }),+ };return realSpawnSlidev(resolution.source === 'project-local'? { ...base, source: 'project-local', projectRoot: containedRoot }diff --git a/packages/desktop/src/main/menu-action-target.test.ts b/packages/desktop/src/main/menu-action-target.test.tsnew file mode 100644index 000000000..16a6eeae0--- /dev/null+++ b/packages/desktop/src/main/menu-action-target.test.ts@@ -0,0 +1,38 @@+import { describe, expect, test, vi } from 'vitest';++import { resolveMenuActionTarget } from './menu-action-target';++describe('resolveMenuActionTarget', () => {+ test('renderer menu actions target the dispatching window before focus fallbacks', () => {+ const sender = {};+ const dispatchingWindow = { id: 2 };+ const focusedWindow = { id: 1 };+ const fromWebContents = vi.fn(() => dispatchingWindow);+ const getFocusedWindow = vi.fn((): { id: number } | null => focusedWindow);+ const getAllWindows = vi.fn(() => [focusedWindow]);++ expect(+ resolveMenuActionTarget(sender, { fromWebContents, getFocusedWindow, getAllWindows }),+ ).toBe(dispatchingWindow);+ expect(fromWebContents).toHaveBeenCalledWith(sender);+ expect(getFocusedWindow).not.toHaveBeenCalled();+ expect(getAllWindows).not.toHaveBeenCalled();+ });++ test('native menu actions retain focused-window then first-window fallback ordering', () => {+ const focusedWindow = { id: 1 };+ const fallbackWindow = { id: 2 };+ const deps = {+ fromWebContents: vi.fn(() => null),+ getFocusedWindow: vi.fn((): { id: number } | null => focusedWindow),+ getAllWindows: vi.fn(() => [fallbackWindow]),+ };++ expect(resolveMenuActionTarget(null, deps)).toBe(focusedWindow);+ expect(deps.fromWebContents).not.toHaveBeenCalled();+ expect(deps.getAllWindows).not.toHaveBeenCalled();++ deps.getFocusedWindow.mockReturnValueOnce(null);+ expect(resolveMenuActionTarget(null, deps)).toBe(fallbackWindow);+ });+});diff --git a/packages/desktop/src/main/menu-action-target.ts b/packages/desktop/src/main/menu-action-target.tsnew file mode 100644index 000000000..360daaf63--- /dev/null+++ b/packages/desktop/src/main/menu-action-target.ts@@ -0,0 +1,16 @@+interface MenuActionTargetDeps<TSender, TWindow> {+ fromWebContents: (sender: TSender) => TWindow | null;+ getFocusedWindow: () => TWindow | null;+ getAllWindows: () => readonly TWindow[];+}++export function resolveMenuActionTarget<TSender, TWindow>(+ sender: TSender | null,+ deps: MenuActionTargetDeps<TSender, TWindow>,+): TWindow | null {+ if (sender != null) {+ const senderWindow = deps.fromWebContents(sender);+ if (senderWindow != null) return senderWindow;+ }+ return deps.getFocusedWindow() ?? deps.getAllWindows()[0] ?? null;+}diff --git a/packages/desktop/src/main/menu.ts b/packages/desktop/src/main/menu.tsindex c96666a40..e20709368 100644--- a/packages/desktop/src/main/menu.ts+++ b/packages/desktop/src/main/menu.ts@@ -21,8 +21,8 @@* (Electron recommends full rebuild on state change).** Electron import discipline: `electron` named exports (Menu, app, dialog,- * shell) are only resolvable at runtime inside an Electron process. Bun's- * unit-test runner loads the `electron` npm package, which is just a string+ * shell) are only resolvable at runtime inside an Electron process. Vitest's+ * Node runtime loads the `electron` npm package, which is just a string* path to the binary — it has NO named exports. So this module uses* type-only imports for interface types (MenuItemConstructorOptions) and* pulls the one runtime value we need (`app.name`) + side-effecting APIs@@ -50,6 +50,7 @@ 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';@@ -66,7 +67,7 @@ export interface MenuDeps {showDevToolsMenu: boolean;/** `electron.dialog` — injected so the File → Open folder click handler* can call `promptForExistingFolder(dialog)` without importing `dialog`- * at module scope (breaks Bun-test module load). */+ * at module scope (breaks Vitest module load). */dialog: Dialog;/** Open the Project Navigator window (File → Switch project…). */openNavigator(): void;@@ -191,7 +192,7 @@ export interface MenuDeps {* File → New file click handler. Routes through the renderer-side* inline-rename flow at FileTree's startCreating helper — same path the* sidebar empty-space context menu uses. Optional because the menu is- * also built in contexts that don't wire it (Bun unit tests).+ * also built in contexts that don't wire it (Vitest unit tests).*/onNewFile?(): void;/** File → New folder click handler. Sibling of `onNewFile`. */@@ -204,7 +205,7 @@ export interface MenuDeps {* Project…, which lists/opens existing projects): this scaffolds a brand-new* project. Always enabled when wired (no `activeTarget` gate — creating a* project is project-scope-independent). Optional because the menu is also- * built in contexts that don't wire it (Bun unit tests).+ * built in contexts that don't wire it (Vitest unit tests).*/onNewProject?(): void;/**@@ -460,7 +461,7 @@ function roleLabelSource(role: string, isMac: boolean): string | undefined {/*** Install the template as the application menu. Dynamically imports- * `Menu` so the module-top scope stays Bun-test-loadable; callers must+ * `Menu` so the module-top scope stays Vitest-loadable; callers must* be in an async context (typically `app.whenReady().then(async () => ...)`).*/export async function installApplicationMenu(deps: MenuDeps): Promise<void> {@@ -699,7 +700,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: process.platform === 'darwin',+ terminalCapable: isTerminalPlatform(process.platform),terminalLive: deps.terminalLive === true,canExpandAll: deps.canExpandAll ?? true,canCollapseAll: deps.canCollapseAll ?? true,diff --git a/packages/desktop/src/preload/index.ts b/packages/desktop/src/preload/index.tsindex 3932f2bb8..d87a5565f 100644--- a/packages/desktop/src/preload/index.ts+++ b/packages/desktop/src/preload/index.ts@@ -71,6 +71,7 @@ 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';@@ -265,12 +266,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 (windows-linux-port terminal posture): node-pty is- // bundled on macOS only, so off-mac the renderer must hide the terminal- // affordances rather than let a spawn fail. Platform is the whole signal —- // a mac install with a broken node-pty still surfaces the existing+ // 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 = process.platform === 'darwin';+ const ptyAvailable = isTerminalPlatform(process.platform);return Object.freeze({collabUrl,apiOrigin,diff --git a/packages/desktop/src/shared/terminal-platform.test.ts b/packages/desktop/src/shared/terminal-platform.test.tsnew file mode 100644index 000000000..15d16c4be--- /dev/null+++ b/packages/desktop/src/shared/terminal-platform.test.ts@@ -0,0 +1,10 @@+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', () => {+ expect(isTerminalPlatform('darwin')).toBe(true);+ expect(isTerminalPlatform('linux')).toBe(true);+ expect(isTerminalPlatform('win32')).toBe(false);+ });+});diff --git a/packages/desktop/src/shared/terminal-platform.ts b/packages/desktop/src/shared/terminal-platform.tsnew file mode 100644index 000000000..5c73812f6--- /dev/null+++ b/packages/desktop/src/shared/terminal-platform.ts@@ -0,0 +1,3 @@+export function isTerminalPlatform(platform: NodeJS.Platform): boolean {+ return platform === 'darwin' || platform === 'linux';+}diff --git a/packages/desktop/src/shared/terminal-shell.ts b/packages/desktop/src/shared/terminal-shell.tsnew file mode 100644index 000000000..2e14001f6--- /dev/null+++ b/packages/desktop/src/shared/terminal-shell.ts@@ -0,0 +1,4 @@+/** Shell argv shared by the interactive PTY and its PATH-readiness probes. */+export function interactiveShellArgs(platform: NodeJS.Platform): readonly string[] {+ return platform === 'linux' ? ['-i'] : ['-l', '-i'];+}diff --git a/packages/desktop/src/utility/pty-host.ts b/packages/desktop/src/utility/pty-host.tsindex 43ece3879..8dff40a19 100644--- a/packages/desktop/src/utility/pty-host.ts+++ b/packages/desktop/src/utility/pty-host.ts@@ -4,19 +4,25 @@* process over `parentPort`.** `setupPtyHost` is a pure factory with an injected `spawn`, so the- * message-routing logic is unit-testable under Bun without a real PTY; the+ * message-routing logic is unit-testable under Vitest without a real PTY; the* production bootstrap at the bottom wires real `process.parentPort` +- * `node-pty`. node-pty's PTY-fd reads do not pump under Bun's event loop, so- * the real-shell-I/O path is exercised by a Node-runtime harness rather than- * `bun test` (see `tests/utility/pty-host.real-io-harness.ts`).+ * `node-pty`. The real-shell-I/O path is exercised by a Node-runtime harness+ * (see `tests/utility/pty-host.real-io-harness.ts`).*/-import { delimiter, join } from 'node:path';+import { existsSync } 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 { interactiveShellArgs } from '../shared/terminal-shell.ts';const DARWIN_FALLBACK_SHELL = '/bin/zsh';-const STRIPPED_ENV_MARKERS = ['OK_ELECTRON_PROTOCOL_HOST', 'OK_LOCK_KIND'] as const;+const STRIPPED_ENV_MARKERS = [+ 'OK_ELECTRON_PROTOCOL_HOST',+ 'OK_LOCK_KIND',+ 'ELECTRON_RUN_AS_NODE',+] as const;export interface PtyCreateMessage {type: 'create';@@ -24,16 +30,16 @@ export interface PtyCreateMessage {cwd: string;cols: number;rows: number;- /** Test-only shell override. Production omits → `$SHELL` or the darwin fallback. */+ /** Test-only shell override. Production uses the platform shell resolver. */shell?: string;/*** "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 as `$SHELL -l -i -c '<launchCommand>; exec $SHELL -l -i'`+ * 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 (`~/.zsh_history`). The+ * 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 (spawned as the bare `$SHELL -l -i`).+ * exits. Omitted for a plain terminal tab.*/launchCommand?: string;}@@ -118,6 +124,21 @@ interface PtyHostParentPort {postMessage(value: PtyHostOutgoingMessage): void;}+export function installPtyImportFailureReply(+ parentPort: PtyHostParentPort,+ error: unknown,+ logger?: { warn(data: Record<string, unknown>, message: string): void },+): void {+ const message = error instanceof Error ? error.message : String(error);+ logger?.warn({ event: 'pty-host-import-failed', error: message }, 'node-pty import failed');+ parentPort.on('message', (event) => {+ const msg = asIncomingMessage(event.data);+ if (msg?.type === 'create') {+ parentPort.postMessage({ type: 'spawn-error', ptyId: msg.ptyId, message });+ }+ });+}+export interface SetupPtyHostDeps {/** `process.parentPort` in the utility runtime; a fake in tests. */parentPort: PtyHostParentPort | null;@@ -125,6 +146,12 @@ export interface SetupPtyHostDeps {spawn: SpawnPty;/** Defaults to `process.env`. Injected so env-stripping is unit-testable. */env?: Record<string, string | undefined>;+ /** Defaults to `process.platform`. */+ platform?: NodeJS.Platform;+ /** Defaults to `os.userInfo().shell`. */+ userInfoShell?: () => string | null;+ /** Defaults to `existsSync`. */+ shellExists?: (path: string) => boolean;/** Optional structured warn sink for unrecognized/malformed messages. */logger?: { warn: (o: Record<string, unknown>) => void };}@@ -177,38 +204,98 @@ export interface PtyHostHandle {killActive(): void;}-/** Login interactive shell: sources profiles so `claude`/git/npm resolve on PATH. */-export function resolveShell(env: Record<string, string | undefined>, override?: string): string {- if (override && override.length > 0) return override;- const shell = env.SHELL;- return typeof shell === 'string' && shell.length > 0 ? shell : DARWIN_FALLBACK_SHELL;+export interface ResolveShellOptions {+ platform: NodeJS.Platform;+ override?: string;+ userInfoShell?: () => string | null;+ shellExists?: (path: string) => boolean;+ logger?: { warn: (o: Record<string, unknown>) => void };+}++function isFalseStyleShell(shell: string): boolean {+ const command = basename(shell);+ return command === 'false' || command === 'nologin';+}++function isUsableShell(+ shell: string | null | undefined,+ shellExists: (path: string) => boolean,+): shell is string {+ return (+ typeof shell === 'string' && shell.length > 0 && !isFalseStyleShell(shell) && shellExists(shell)+ );+}++/** Resolve the user's interactive shell with platform-native fallbacks. */+export function resolveShell(+ env: Record<string, string | undefined>,+ options: ResolveShellOptions,+): string {+ if (options.override && options.override.length > 0) return options.override;++ const configuredShell = env.SHELL;+ if (options.platform === 'darwin') {+ return typeof configuredShell === 'string' && configuredShell.length > 0+ ? configuredShell+ : DARWIN_FALLBACK_SHELL;+ }+ if (options.platform !== 'linux') {+ return typeof configuredShell === 'string' && configuredShell.length > 0+ ? configuredShell+ : '/bin/sh';+ }++ const shellExists = options.shellExists ?? existsSync;+ if (isUsableShell(configuredShell, shellExists)) return configuredShell;++ let passwdShell: string | null = null;+ try {+ passwdShell = (options.userInfoShell ?? (() => userInfo().shell))();+ } catch (err) {+ const code = (err as { code?: unknown } | null)?.code;+ options.logger?.warn({+ event: 'pty-host-user-info-shell-failed',+ code: typeof code === 'string' ? code : 'unknown',+ });+ passwdShell = null;+ }+ if (isUsableShell(passwdShell, shellExists)) return passwdShell;+ return shellExists('/bin/bash') ? '/bin/bash' : '/bin/sh';}/*** Compute the shell argv for a PTY.*- * - Plain tab → `['-l', '-i']`: a login interactive shell (sources profiles for- * PATH; interactive for the user's normal prompt + history).- * - "Open in <Agent>" launch → `['-l', '-i', '-c', '<launchCommand>; exec <shell> -l -i']`:- * the SAME login-interactive shell (so `.zshrc`-sourced PATH is byte-identical- * to the plain tab), but the agent command rides on `-c`. A `-c` command is run+ * 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`.+ * A `-c` command is run* directly rather than entered through the shell's line editor, so it is NOT* written to the user's persistent history — fixing both the launch-line* clutter and the doc-content-on-disk leak (the prompt would otherwise be saved- * in plaintext to `~/.zsh_history`, outside `.ok/`). The `exec <shell> -l -i`- * tail replaces the launcher with a fresh interactive shell once the agent+ * in plaintext to the shell's history file, outside `.ok/`). The `exec` tail+ * replaces the launcher with a fresh interactive shell once the agent* exits, so the user keeps working in the same tab and THEIR commands record* normally — only OK's machine-generated launch line is suppressed.** The agent still gets a real PTY (node-pty allocates the tty), so its TUI runs* interactively regardless of the shell being driven by `-c`.*/-export function buildShellArgs(shell: string, launchCommand?: string): string[] {- if (launchCommand === undefined || launchCommand.length === 0) return ['-l', '-i'];+export function buildShellArgs(+ platform: NodeJS.Platform,+ shell: string,+ launchCommand?: string,+): string[] {+ const interactiveArgs = [...interactiveShellArgs(platform)];+ if (launchCommand === undefined || 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, "'\\''")}'`;- return ['-l', '-i', '-c', `${launchCommand}; exec ${quotedShell} -l -i`];+ return [+ ...interactiveArgs,+ '-c',+ `${launchCommand}; exec ${quotedShell} ${interactiveArgs.join(' ')}`,+ ];}/**@@ -224,15 +311,14 @@ export function buildShellEnv(const out: Record<string, string> = {};for (const [key, value] of Object.entries(parentEnv)) {if (value === undefined) continue;- if (stripped.has(key)) continue;+ if (stripped.has(key) || key.startsWith('GDK_PIXBUF_')) continue;out[key] = value;}// `ok` must resolve in OK's own terminal regardless of the shell-PATH// rc-consent decision: OK spawns this process, so prepending `~/.ok/bin`// 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 (never the case on a macOS GUI launch)- // just skips the injection.+ // re-prepend it. A missing HOME just skips the injection.const home = out.HOME;if (home) {const okBin = join(home, '.ok', 'bin');@@ -252,6 +338,7 @@ export function buildShellEnv(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>();@@ -287,11 +374,17 @@ export function setupPtyHost(deps: SetupPtyHostDeps): PtyHostHandle {safeKill(stale);sessions.delete(ptyId);}- const shell = resolveShell(env, message.shell);+ const shell = resolveShell(env, {+ platform,+ override: message.shell,+ userInfoShell: deps.userInfoShell,+ shellExists: deps.shellExists,+ logger: deps.logger,+ });const shellEnv = buildShellEnv(env);let pty: PtyProcessLike;try {- pty = deps.spawn(shell, buildShellArgs(shell, message.launchCommand), {+ pty = deps.spawn(shell, buildShellArgs(platform, shell, message.launchCommand), {name: 'xterm-256color',cols: message.cols,rows: message.rows,@@ -439,12 +532,26 @@ export function installHostReaping(handle: PtyHostHandle, proc: HostReapProcess)}// Production entry — auto-runs when imported by `utilityProcess.fork(<this-file>)`.-// `process.parentPort` is non-null only in the utility runtime; under Bun/Node-// unit tests and the Node harness it is undefined, so this branch stays dormant+// `process.parentPort` is non-null only in the utility runtime; under Vitest/Node+// and the Node harness it is undefined, so this branch stays dormant// and node-pty is never imported there.if ((process as NodeJS.Process & { parentPort?: unknown }).parentPort) {const parentPort = (process as NodeJS.Process & { parentPort: PtyHostParentPort }).parentPort;void (async () => {+ let log: {+ warn(data: Record<string, unknown>, message?: string): void;+ } = {+ warn: (data, message) => console.warn(message ?? '[pty-host] warning', data),+ };+ try {+ const { getLogger } = await import('../main/desktop-logger.ts');+ log = getLogger('pty-host');+ } catch (err) {+ const code = (err as { code?: unknown } | null)?.code;+ console.warn('[pty-host] logger unavailable; using console fallback', {+ code: typeof code === 'string' ? code : 'unknown',+ });+ }let spawn: SpawnPty;try {({ spawn } = await import('node-pty'));@@ -454,17 +561,9 @@ if ((process as NodeJS.Process & { parentPort?: unknown }).parentPort) {// the unhandled rejection leaves the renderer in `'running'` with no// output and no signal. Reply to any `create` with a spawn-error so the// panel shows its error/restart state instead of hanging.- const message = err instanceof Error ? err.message : String(err);- parentPort.on('message', (event) => {- const msg = asIncomingMessage(event.data);- if (msg?.type === 'create') {- parentPort.postMessage({ type: 'spawn-error', ptyId: msg.ptyId, message });- }- });+ installPtyImportFailureReply(parentPort, err, log);return;}- const { getLogger } = await import('../main/desktop-logger.ts');- const log = getLogger('pty-host');const handle = setupPtyHost({parentPort,spawn,diff --git a/packages/desktop/tests/main/claude-readiness.test.ts b/packages/desktop/tests/main/claude-readiness.test.tsindex 398d94388..9f6b75801 100644--- a/packages/desktop/tests/main/claude-readiness.test.ts+++ b/packages/desktop/tests/main/claude-readiness.test.ts@@ -105,16 +105,22 @@ describe('mcpStatusFromClassification', () => {});describe('cliProbeArgs', () => {- test('builds the login-interactive `command -v <bin>` argv for any binary', () => {- expect(cliProbeArgs('codex')).toEqual(['-l', '-i', '-c', 'command -v codex']);- expect(cliProbeArgs('cursor-agent')).toEqual(['-l', '-i', '-c', 'command -v cursor-agent']);+ test('matches each platform’s interactive PTY argv for any binary', () => {+ expect(cliProbeArgs('codex', 'darwin')).toEqual(['-l', '-i', '-c', 'command -v codex']);+ expect(cliProbeArgs('codex', 'linux')).toEqual(['-i', '-c', 'command -v codex']);+ expect(cliProbeArgs('cursor-agent', 'darwin')).toEqual([+ '-l',+ '-i',+ '-c',+ 'command -v cursor-agent',+ ]);// The claude argv is just the generic builder applied to `claude`.- expect(CLAUDE_PROBE_ARGS).toEqual(cliProbeArgs('claude'));+ expect(CLAUDE_PROBE_ARGS).toEqual(cliProbeArgs('claude', process.platform));});});describe('runLoginShellProbe', () => {- test('spawns the supplied shell with the login-interactive command -v argv', async () => {+ test('spawns the supplied shell with the platform command-v argv', async () => {const { child, emitExit } = makeFakeChild();const { timers } = makeFakeTimers();let spawnedFile = '';@@ -146,7 +152,7 @@ describe('runLoginShellProbe', () => {'zsh',timers,undefined,- cliProbeArgs('cursor-agent'),+ cliProbeArgs('cursor-agent', 'darwin'),);emitExit(0);await p;@@ -464,7 +470,7 @@ describe('resolvePlatformCliInstalledMap', () => {expect(probeWindows).toHaveBeenCalledWith('cursor-agent');});- test('POSIX hosts keep using the login-shell probe', async () => {+ 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,);@@ -479,6 +485,23 @@ describe('resolvePlatformCliInstalledMap', () => {expect(map.cursor).toBe(true);expect(map.codex).toBe(false);expect(probeWindows).not.toHaveBeenCalled();- expect(probePosix).toHaveBeenCalledWith(cliProbeArgs('cursor-agent'));+ expect(probePosix).toHaveBeenCalledWith(cliProbeArgs('cursor-agent', 'darwin'));+ });++ test('Linux probes with the same non-login interactive argv as its PTY', async () => {+ const probed: readonly string[][] = [];+ const probePosix = vi.fn(async (args: readonly string[]) => {+ (probed as string[][]).push([...args]);+ return 127;+ });++ await resolvePlatformCliInstalledMap({+ platform: 'linux',+ probePosix,+ probeWindows: vi.fn(async () => false),+ });++ expect(probed).toContainEqual(['-i', '-c', 'command -v claude']);+ expect(probed).toContainEqual(['-i', '-c', 'command -v cursor-agent']);});});diff --git a/packages/desktop/tests/main/menu.test.ts b/packages/desktop/tests/main/menu.test.tsindex 81d904983..b68420726 100644--- a/packages/desktop/tests/main/menu.test.ts+++ b/packages/desktop/tests/main/menu.test.ts@@ -1355,9 +1355,9 @@ describe('buildMenuTemplate — View → Show/Hide Agents', () => {});// The panel is server-hosted, not pty-backed, so its toggle must survive the- // off-mac strip that darkens every terminal handler (index.ts's darwin gate).- // A regression that folded it into that branch would kill agents on win/linux.- test('Agents stays wired when every terminal handler is stripped (off-mac shape)', () => {+ // unsupported-platform strip that darkens every PTY-backed terminal handler.+ // A regression that folded it into that branch would kill agents there too.+ test('Agents stays wired when every terminal handler is stripped', () => {const template = buildMenuTemplate(makeDeps({onToggleAgentPanel: vi.fn(() => {}),@@ -1478,8 +1478,8 @@ describe('buildMenuTemplate — top-level Terminal menu', () => {expect(onKillTerminal).toHaveBeenCalledTimes(1);});- test('PTY-backed commands stay disabled off macOS even when handlers are wired', () => {- const template = buildMenuTemplateForPlatform(+ test('PTY-backed commands are enabled on Linux when handlers are wired', () => {+ const linux = buildMenuTemplateForPlatform('linux',makeDeps({onToggleTerminal: vi.fn(() => {}),@@ -1491,11 +1491,31 @@ describe('buildMenuTemplate — top-level Terminal menu', () => {}),);- expect(findByLabel(template, 'Show Terminal')?.enabled).toBe(false);- expect(findByLabel(template, 'Move Terminal to right')?.enabled).toBe(false);- expect(findByLabel(template, 'New Terminal')?.enabled).toBe(false);- expect(findByLabel(template, 'New Terminal Window')?.enabled).toBe(false);- expect(findByLabel(template, 'Kill Terminal')?.enabled).toBe(false);+ expect(findByLabel(linux, 'Show Terminal')?.enabled).toBe(true);+ expect(findByLabel(linux, 'Move Terminal to right')?.enabled).toBe(true);+ expect(findByLabel(linux, 'New Terminal')?.enabled).toBe(true);+ expect(findByLabel(linux, 'New Terminal Window')?.enabled).toBe(true);+ expect(findByLabel(linux, 'Kill Terminal')?.enabled).toBe(true);+ });++ test('PTY-backed commands stay disabled on unsupported platforms', () => {+ const windows = buildMenuTemplateForPlatform(+ 'win32',+ makeDeps({+ 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);+ expect(findByLabel(windows, 'New Terminal Window')?.enabled).toBe(false);+ expect(findByLabel(windows, 'Kill Terminal')?.enabled).toBe(false);});test('the View → Show/Hide Terminal toggle is preserved alongside the Terminal menu', () => {diff --git a/packages/desktop/tests/smoke/_helpers/platform-gate.ts b/packages/desktop/tests/smoke/_helpers/platform-gate.tsindex 80d399c45..c44daaf42 100644--- a/packages/desktop/tests/smoke/_helpers/platform-gate.ts+++ b/packages/desktop/tests/smoke/_helpers/platform-gate.ts@@ -9,22 +9,25 @@* first place — they launch Electron, poke the renderer, and read main-process* state.*- * Two categories now exist, and the distinction is deliberate:+ * Three categories now exist, and the distinction is deliberate:** - 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.* - 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, the node-pty terminal dock (excluded from the- * Windows/Linux packages by `electron-builder.yml`'s per-platform `files`),- * or the darwin chrome stack (vibrancy / hiddenInset traffic lights).+ * Event URL delivery or the darwin chrome stack (vibrancy / hiddenInset+ * traffic lights).** Moving a spec between categories is a one-line change; prefer growing the* cross-platform set over adding platform branches inside a spec.*/import { join } from 'node:path';+import { isTerminalPlatform } from '../../../src/shared/terminal-platform.ts';/** Opt-in gate shared by every smoke spec. */export const SMOKE_ENABLED = process.env.OK_DESKTOP_E2E_SMOKE === '1';@@ -41,6 +44,11 @@ export const PLATFORM_SUPPORTED = SUPPORTED_PLATFORMS.has(process.platform);export const PLATFORM_SKIP_REASON = `Smoke harness does not support platform "${process.platform}".`;+/** True on every platform that ships the desktop PTY capability. */+export const PTY_PLATFORM_SUPPORTED = isTerminalPlatform(process.platform);++export const PTY_PLATFORM_SKIP_REASON = `Desktop terminal does not support platform "${process.platform}".`;+/*** Environment overrides that actually redirect the app's home directory on* every OS.diff --git a/packages/desktop/tests/smoke/share-receive-miss-terminal.e2e.ts b/packages/desktop/tests/smoke/share-receive-miss-terminal.e2e.tsindex 0e14a8c17..362182ac2 100644--- a/packages/desktop/tests/smoke/share-receive-miss-terminal.e2e.ts+++ b/packages/desktop/tests/smoke/share-receive-miss-terminal.e2e.ts@@ -36,12 +36,12 @@ import { tmpdir } from 'node:os';import { dirname, join } from 'node:path';import { _electron as electron } from '@playwright/test';import { desktopLaunchOptions, resolveDesktopTarget } from './_helpers/launch-desktop';+import { PLATFORM_SKIP_REASON, PLATFORM_SUPPORTED } from './_helpers/platform-gate';import { expect, type SmokeFixtures, test } from './_helpers/smoke-test';const TARGET = resolveDesktopTarget();const SMOKE_ENABLED = process.env.OK_DESKTOP_E2E_SMOKE === '1';-const DARWIN = process.platform === 'darwin';function git(cwd: string, ...args: string[]): void {execFileSync('git', args, {@@ -241,7 +241,7 @@ async function expectDeletedTargetMiss(test.describe('share-receive miss terminal smoke', () => {test.skip(!SMOKE_ENABLED, 'Set OK_DESKTOP_E2E_SMOKE=1 to run Electron smoke tests.');- test.skip(!DARWIN, 'Deep-link URL scheme is macOS-only in v0.');+ test.skip(!PLATFORM_SUPPORTED, PLATFORM_SKIP_REASON);test.skip(!TARGET.exists, TARGET.missingReason);test('a deleted share target lands the receiver on the miss dialog, never create-mode', async ({diff --git a/packages/desktop/tests/smoke/terminal-dock-state.e2e.ts b/packages/desktop/tests/smoke/terminal-dock-state.e2e.tsindex f0edb972d..77086e30b 100644--- a/packages/desktop/tests/smoke/terminal-dock-state.e2e.ts+++ b/packages/desktop/tests/smoke/terminal-dock-state.e2e.ts@@ -4,6 +4,7 @@ import { join } from 'node:path';import type { 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 { expect, test } from './_helpers/smoke-test';const TARGET = resolveDesktopTarget();@@ -11,6 +12,7 @@ const SMOKE_ENABLED = process.env.OK_DESKTOP_E2E_SMOKE === '1';test.describe('terminal dock-state IPC', () => {test.skip(!SMOKE_ENABLED, 'Set OK_DESKTOP_E2E_SMOKE=1 to run Electron smoke tests.');+ test.skip(!PTY_PLATFORM_SUPPORTED, PTY_PLATFORM_SKIP_REASON);test.skip(!TARGET.exists, TARGET.missingReason);test('terminal tab snapshot survives renderer reload together', async ({ captureStderrFor }) => {diff --git a/packages/desktop/tests/smoke/terminal-dock.e2e.ts b/packages/desktop/tests/smoke/terminal-dock.e2e.tsindex b3076af3b..e3f0dacd3 100644--- a/packages/desktop/tests/smoke/terminal-dock.e2e.ts+++ b/packages/desktop/tests/smoke/terminal-dock.e2e.ts@@ -9,7 +9,8 @@* banner.** Skip gates mirror the sibling smokes: opt-in via OK_DESKTOP_E2E_SMOKE=1,- * darwin-only, and the electron-vite build must exist (out/main/index.js).+ * a PTY-capable platform, and the electron-vite build must exist+ * (out/main/index.js).*/import {@@ -24,17 +25,18 @@ import {} 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 { expect, test } from './_helpers/smoke-test';import { waitForShellReady } from './_helpers/terminal-ready';const TARGET = resolveDesktopTarget();const SMOKE_ENABLED = process.env.OK_DESKTOP_E2E_SMOKE === '1';-const DARWIN = process.platform === 'darwin';const DESKTOP_PRODUCT_NAME = '@inkeep/open-knowledge-desktop';+const PRIMARY_MODIFIER = process.platform === 'darwin' ? 'Meta' : 'Control';interface SeedOpts {/** Pre-grant consent by seeding .ok/local/config.yml terminal.enabled: true. */@@ -193,10 +195,22 @@ async function findEditorWindow(app: ElectronApplication, timeoutMs = 25_000): Preturn page;}+async function dispatchRendererMenuAction(+ app: ElectronApplication,+ action: 'move-terminal' | 'toggle-agent-panel' | 'toggle-terminal',+): Promise<void> {+ const page = await findEditorWindow(app);+ await page.evaluate(async (menuAction) => {+ const menu = window.okDesktop?.menu;+ if (!menu) throw new Error('renderer menu bridge is unavailable');+ await menu.dispatch({ kind: 'menu-action', action: menuAction });+ }, action);+}+/** Click the View → Show/Hide Terminal application-menu item (real toggle path- * on desktop — ⌘J is its OS-captured accelerator). Returns the item label. */+ * on desktop — CmdOrCtrl+J is its OS-captured accelerator). Returns the item label. */async function clickViewTerminalItem(app: ElectronApplication): Promise<string> {- return app.evaluate(async ({ Menu }) => {+ const label = await app.evaluate(async ({ Menu }) => {const menu = Menu.getApplicationMenu();if (!menu) throw new Error('application menu is unavailable');const view = menu.items.find((i) => i.label === 'View');@@ -205,9 +219,11 @@ async function clickViewTerminalItem(app: ElectronApplication): Promise<string>);if (!item) throw new Error('View menu is missing the required Terminal visibility item');const label = item.label;- item.click();+ if (process.platform === 'darwin') item.click();return label;});+ if (process.platform !== 'darwin') await dispatchRendererMenuAction(app, 'toggle-terminal');+ return label;}async function viewTerminalLabel(app: ElectronApplication): Promise<string> {@@ -223,6 +239,19 @@ async function viewTerminalLabel(app: ElectronApplication): Promise<string> {});}+async function waitForMenuSelectionState(page: Page, expected: boolean): Promise<void> {+ await expect+ .poll(() =>+ page.evaluate(async () => {+ const menu = window.okDesktop?.menu;+ if (!menu) return undefined;+ const snapshot = await menu.dispatch({ kind: 'query' });+ return snapshot?.viewMenuState.hasEditorSelection;+ }),+ )+ .toBe(expected);+}+async function terminalPlacementLabel(app: ElectronApplication): Promise<string> {return app.evaluate(async ({ Menu }) => {const menu = Menu.getApplicationMenu();@@ -237,6 +266,10 @@ async function terminalPlacementLabel(app: ElectronApplication): Promise<string>}async function clickTerminalPlacementItem(app: ElectronApplication): Promise<void> {+ if (process.platform !== 'darwin') {+ await dispatchRendererMenuAction(app, 'move-terminal');+ return;+ }await app.evaluate(async ({ Menu }) => {const terminal = Menu.getApplicationMenu()?.items.find((i) => i.label === 'Terminal');const item = terminal?.submenu?.items.find(@@ -248,6 +281,10 @@ async function clickTerminalPlacementItem(app: ElectronApplication): Promise<voi}async function clickViewAgentsItem(app: ElectronApplication): Promise<void> {+ if (process.platform !== 'darwin') {+ await dispatchRendererMenuAction(app, 'toggle-agent-panel');+ return;+ }await app.evaluate(async ({ Menu }) => {const view = Menu.getApplicationMenu()?.items.find((item) => item.label === 'View');const item = view?.submenu?.items.find(@@ -265,6 +302,15 @@ const terminalStatus = (page: Page) => page.locator('[data-terminal-status]');// strict mode. Scope the claude-readiness banner by its stable test seam instead.const readinessBanner = (page: Page) => page.getByTestId('terminal-readiness-banner');+async function revealTerminalSurface(app: ElectronApplication, target: Locator): Promise<void> {+ await expect(async () => {+ // A prior dispatch can land between attempts; observe first so a retry cannot hide it again.+ if (await target.isVisible()) return;+ await clickViewTerminalItem(app);+ await expect(target).toBeVisible({ timeout: 1_000 });+ }).toPass({ timeout: 15_000 });+}+async function expectCollapsedRailColumn(page: Page, selector: string): Promise<void> {const column = page.locator(selector);await expect(column).toHaveCount(1);@@ -275,8 +321,7 @@ async function expectCollapsedRailColumn(page: Page, selector: string): Promise</** Open the dock (via the real menu toggle) and wait for the panel to mount. */async function openTerminal(app: ElectronApplication, page: Page): Promise<void> {- await clickViewTerminalItem(app);- await expect(terminalSection(page)).toBeVisible({ timeout: 15_000 });+ await revealTerminalSurface(app, terminalSection(page));}async function waitForStatus(page: Page, status: string, timeoutMs = 20_000): Promise<void> {@@ -318,7 +363,7 @@ function track(...paths: string[]): void {test.describe('Docked terminal — live Electron', () => {test.skip(!SMOKE_ENABLED, 'Set OK_DESKTOP_E2E_SMOKE=1 to run Electron smoke tests.');- test.skip(!DARWIN, 'Desktop is darwin-only.');+ test.skip(!PTY_PLATFORM_SUPPORTED, PTY_PLATFORM_SKIP_REASON);test.skip(!TARGET.exists, TARGET.missingReason);test.afterEach(() => {for (const target of cleanup.splice(0)) {@@ -383,10 +428,7 @@ test.describe('Docked terminal — live Electron', () => {// The opted-out gate renders the "Terminal disabled" region, NOT the panel// section — so openTerminal() (which waits on the panel) would never resolve.- await clickViewTerminalItem(app);- await expect(page.getByRole('region', { name: 'Terminal disabled' })).toBeVisible({- timeout: 15_000,- });+ await revealTerminalSurface(app, page.getByRole('region', { name: 'Terminal disabled' }));await expect(page.getByRole('button', { name: 'Enable terminal' })).toBeVisible();// No PTY/panel in the opted-out state.await expect(terminalStatus(page)).toHaveCount(0);@@ -408,8 +450,7 @@ test.describe('Docked terminal — live Electron', () => {const page = await findEditorWindow(app);expect(await viewTerminalLabel(app)).toBe('Show Terminal');- await clickViewTerminalItem(app);- await expect(terminalSection(page)).toBeVisible({ timeout: 15_000 });+ await revealTerminalSurface(app, terminalSection(page));await expect.poll(() => viewTerminalLabel(app), { timeout: 8_000 }).toBe('Hide Terminal');await clickViewTerminalItem(app);@@ -581,8 +622,9 @@ test.describe('Docked terminal — live Electron', () => {// but coalesces the PTY resize (leading + trailing throttle), so a storm// must (1) never wedge the shell and (2) always settle the PTY at the final// fitted grid — a dropped trailing resize would leave the shell's winsize at- // a mid-drag width. The storm returns the window to its starting size, so- // `tput cols` before and after must agree.+ // a mid-drag width. Chromium may reclaim a scrollbar-width sliver when the+ // window returns to its starting size, so the fitted grid can legitimately+ // differ by a couple of columns.test('a window-resize storm keeps the shell responsive and settles the PTY at the fitted grid', async ({captureStderrFor,}) => {@@ -618,10 +660,17 @@ test.describe('Docked terminal — live Electron', () => {// the last step, but the storm's queued SIGWINCH redraws drain async.await typeInTerminal(page, 'echo AFTER_COLS=$(tput cols)\r');await expect.poll(() => readTerminalText(page), { timeout: 15_000 }).toMatch(/AFTER_COLS=\d+/);- expect(before).toBeTruthy();+ const beforeColumns = Number(before);+ expect(beforeColumns).toBeGreaterThan(0);await expect- .poll(() => readTerminalText(page), { timeout: 10_000 })- .toContain(`AFTER_COLS=${before}`);+ .poll(+ async () => {+ const after = (await readTerminalText(page)).match(/AFTER_COLS=(\d+)/)?.[1];+ return after == null ? Number.POSITIVE_INFINITY : Math.abs(Number(after) - beforeColumns);+ },+ { timeout: 10_000 },+ )+ .toBeLessThanOrEqual(2);});// Dock controls in the live build keep the explicit Terminal collapse name.@@ -686,9 +735,9 @@ test.describe('Docked terminal — live Electron', () => {// Escape is delivered to the terminal (NOT swallowed): terminal apps// (vim, the `claude` TUI) need it. The no-keyboard-trap exit (WCAG 2.1.2) is- // ⌘J — the View → Hide Terminal toggle — which collapses the dock and returns- // focus to the editor.- test('QA-019 Escape reaches the terminal; ⌘J is the no-trap exit', async ({+ // CmdOrCtrl+J — the View → Hide Terminal toggle — which collapses the dock+ // and returns focus to the editor.+ test('QA-019 Escape reaches the terminal; CmdOrCtrl+J is the no-trap exit', async ({captureStderrFor,}) => {const s = seed('escape', { consent: true });@@ -715,16 +764,16 @@ test.describe('Docked terminal — live Electron', () => {await page.keyboard.press('Escape');await expect.poll(focusInTerminal).toBe(true);- // The documented keyboard exit is ⌘J (here via its View-menu accelerator):- // it collapses the dock and returns focus to the editor — satisfying WCAG- // 2.1.2 without consuming Escape.+ // The documented keyboard exit is CmdOrCtrl+J (here via its View-menu+ // accelerator): it collapses the dock and returns focus to the editor —+ // satisfying WCAG 2.1.2 without consuming Escape.await clickViewTerminalItem(app);await expect.poll(focusInTerminal).toBe(false);});// ⌃` is the dock's second chord and the only one the RENDERER delivers on- // desktop — ⌘J is an OS-captured menu accelerator, and a menu item may hold- // only one. That makes this the case no unit test can stand in for: the+ // desktop — CmdOrCtrl+J is an OS-captured menu accelerator, and a menu item+ // may hold only one. That makes this the case no unit test can stand in for: the// listener is capture-phase on `window` precisely so a focused xterm's hidden// textarea cannot consume the chord first. If it ever regressed to bubble// phase, or the listener went back to skipping the desktop host, the dock@@ -940,8 +989,8 @@ test.describe('Docked terminal — live Electron', () => {await expect(page.getByRole('button', { name: 'Connect tools' })).toBeVisible();});- // A renderer reload (View → Reload, or the window reload macOS sleep/wake- // forces) must NOT lose the open terminal. The PTY survives in the main+ // A renderer reload (View → Reload, or an OS resume-triggered reload) must+ // NOT lose the open terminal. The PTY survives in the main// process; the reloaded renderer must rehydrate the dock from it — same shell,// not a fresh spawn. This is the canonical reload-survival contract. It// RED-fails on origin/main, where the dock comes back collapsed/empty: the@@ -949,8 +998,8 @@ test.describe('Docked terminal — live Electron', () => {// orphaned and the dock seeds nothing.//// Desktop-only — the dock renders only on the Electron host (it needs the real- // preload bridge + the per-window PTY host), so this runs on a real macOS- // desktop (OK_DESKTOP_E2E_SMOKE=1), never headless. It is intentionally the+ // preload bridge + the per-window PTY host), so this runs in a real desktop+ // Electron process (OK_DESKTOP_E2E_SMOKE=1), never headless. It is intentionally the// highest-fidelity rung for this fix; the renderer + main-process halves are// pinned headless in the reload-survival dom test and main-process test.test('a renderer reload preserves the open terminal and its live session', async ({@@ -991,12 +1040,13 @@ test.describe('Docked terminal — live Electron', () => {.toContain('marker=[OKRELOAD_SURVIVED_351]');});- // Shortcut behavior at the live-Electron rung: ⇧⌘J stages a REAL editor- // selection into a REAL CLI PTY, then the View-menu route proves ⌘J remains a- // pure visibility toggle even while another selection is live. The fake+ // Shortcut behavior at the live-Electron rung: the platform's primary+ // modifier + Shift+J stages a REAL editor selection into a REAL CLI PTY,+ // then the View-menu route proves primary-modifier+J remains a pure+ // visibility toggle even while another selection is live. The fake// `claude` is a TUI stand-in (`exec cat`) that holds the PTY open reading// stdin, so staged bytes and session survival stay observable in xterm.- test('⇧⌘J stages into a new CLI tab; ⌘J stays a pure visibility toggle', async ({+ test('the primary-modifier J shortcuts stage a new CLI tab and toggle visibility', async ({captureStderrFor,}) => {// This composed flow walks doc-load + launch + staged write + menu delivery,@@ -1031,16 +1081,16 @@ test.describe('Docked terminal — live Electron', () => {// 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();- await page.keyboard.press('Meta+a');+ await page.keyboard.press(`${PRIMARY_MODIFIER}+a`);await expect.poll(() => page.evaluate(() => String(window.getSelection() ?? ''))).toContain('Seed document');- await page.waitForTimeout(500);+ await waitForMenuSelectionState(page, true);- // ⇧⌘J: the renderer-owned chord (capture-phase window keydown — no menu item+ // The renderer-owned chord (capture-phase window keydown — no menu item// claims it) opens a NEW CLI tab with the grounded passage staged into its// input once the PTY is live.- await page.keyboard.press('Meta+Shift+j');+ await page.keyboard.press(`${PRIMARY_MODIFIER}+Shift+j`);await expect(terminalSection(page)).toBeVisible({ timeout: 15_000 });await waitForStatus(page, 'running', 25_000);// The staged bytes reached the CLI's PTY: the composed prompt names the doc@@ -1050,18 +1100,19 @@ test.describe('Docked terminal — live Electron', () => {const terminalTabs = () => terminalSection(page).getByRole('tab');const tabsAfterLaunch = await terminalTabs().count();- // Grow the doc with a distinguishing marker and re-select, then take the ⌘J- // route via its View-menu accelerator item (the real menu→IPC→renderer+ // Grow the doc with a distinguishing marker and re-select, then take the+ // 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();- await page.keyboard.press('Meta+a');+ await page.keyboard.press(`${PRIMARY_MODIFIER}+a`);await page.keyboard.type('Reuse marker OKSTAGE_REUSE_742 body');- await page.keyboard.press('Meta+a');+ await waitForMenuSelectionState(page, false);+ await page.keyboard.press(`${PRIMARY_MODIFIER}+a`);await expect.poll(() => page.evaluate(() => String(window.getSelection() ?? ''))).toContain('OKSTAGE_REUSE_742');- await page.waitForTimeout(500);+ await waitForMenuSelectionState(page, true);expect(await clickViewTerminalItem(app)).toBe('Hide Terminal');await expect(terminalSection(page)).toBeHidden();diff --git a/packages/desktop/tests/smoke/terminal-links.e2e.ts b/packages/desktop/tests/smoke/terminal-links.e2e.tsindex 0ba280fb8..3db6357b7 100644--- a/packages/desktop/tests/smoke/terminal-links.e2e.ts+++ b/packages/desktop/tests/smoke/terminal-links.e2e.ts@@ -12,7 +12,8 @@* navigates to that doc (hash route).** Skip gates mirror the sibling terminal smokes: opt-in via OK_DESKTOP_E2E_SMOKE=1,- * darwin-only, and the electron-vite build must exist (out/main/index.js).+ * a PTY-capable platform, and the electron-vite build must exist+ * (out/main/index.js).*/import { chmodSync, mkdirSync, mkdtempSync, realpathSync, rmSync, writeFileSync } from 'node:fs';@@ -21,13 +22,13 @@ 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 { expect, test } from './_helpers/smoke-test';import { waitForShellReady } from './_helpers/terminal-ready';const TARGET = resolveDesktopTarget();const SMOKE_ENABLED = process.env.OK_DESKTOP_E2E_SMOKE === '1';-const DARWIN = process.platform === 'darwin';const DESKTOP_PRODUCT_NAME = '@inkeep/open-knowledge-desktop';interface Seed {@@ -199,10 +200,9 @@ function track(...paths: string[]): void {}test.describe('Terminal clickable links — live Electron', () => {- test.skip(- !SMOKE_ENABLED || !DARWIN || !TARGET.exists,- `Live-Electron smoke: set OK_DESKTOP_E2E_SMOKE=1 on darwin. ${TARGET.missingReason}`,- );+ test.skip(!SMOKE_ENABLED, 'Set OK_DESKTOP_E2E_SMOKE=1 to run Electron smoke tests.');+ 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 });});diff --git a/packages/desktop/tests/smoke/terminal-movement.e2e.ts b/packages/desktop/tests/smoke/terminal-movement.e2e.tsindex 35b9a4e87..488080ce7 100644--- a/packages/desktop/tests/smoke/terminal-movement.e2e.ts+++ b/packages/desktop/tests/smoke/terminal-movement.e2e.ts@@ -5,13 +5,14 @@ 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 { expect, test } from './_helpers/smoke-test';import { waitForShellReady } from './_helpers/terminal-ready';const TARGET = resolveDesktopTarget();const SMOKE_ENABLED = process.env.OK_DESKTOP_E2E_SMOKE === '1';-const DARWIN = process.platform === 'darwin';const DESKTOP_PRODUCT_NAME = '@inkeep/open-knowledge-desktop';+const PRIMARY_MODIFIER = process.platform === 'darwin' ? 'Meta' : 'Control';type TerminalHome = 'bottom' | 'right';@@ -93,7 +94,23 @@ async function findEditorWindow(app: ElectronApplication, timeoutMs = 25_000): Preturn page;}+async function dispatchRendererMenuAction(+ app: ElectronApplication,+ action: 'move-terminal' | 'toggle-agent-panel' | 'toggle-terminal',+): Promise<void> {+ const page = await findEditorWindow(app);+ await page.evaluate(async (menuAction) => {+ const menu = window.okDesktop?.menu;+ if (!menu) throw new Error('renderer menu bridge is unavailable');+ await menu.dispatch({ kind: 'menu-action', action: menuAction });+ }, action);+}+async function clickViewTerminalItem(app: ElectronApplication): Promise<void> {+ if (process.platform !== 'darwin') {+ await dispatchRendererMenuAction(app, 'toggle-terminal');+ return;+ }await app.evaluate(async ({ Menu }) => {const view = Menu.getApplicationMenu()?.items.find((item) => item.label === 'View');const terminal = view?.submenu?.items.find(@@ -105,6 +122,10 @@ async function clickViewTerminalItem(app: ElectronApplication): Promise<void> {}async function clickViewAgentsItem(app: ElectronApplication): Promise<void> {+ if (process.platform !== 'darwin') {+ await dispatchRendererMenuAction(app, 'toggle-agent-panel');+ return;+ }await app.evaluate(async ({ Menu }) => {const view = Menu.getApplicationMenu()?.items.find((item) => item.label === 'View');const item = view?.submenu?.items.find(@@ -116,6 +137,10 @@ async function clickViewAgentsItem(app: ElectronApplication): Promise<void> {}async function clickTerminalPlacementItem(app: ElectronApplication): Promise<void> {+ if (process.platform !== 'darwin') {+ await dispatchRendererMenuAction(app, 'move-terminal');+ return;+ }await app.evaluate(async ({ Menu }) => {const terminal = Menu.getApplicationMenu()?.items.find((item) => item.label === 'Terminal');const placement = terminal?.submenu?.items.find(@@ -130,6 +155,12 @@ async function clickTerminalPlacementItemRapidly(app: ElectronApplication,count: number,): Promise<void> {+ if (process.platform !== 'darwin') {+ for (let index = 0; index < count; index += 1) {+ await dispatchRendererMenuAction(app, 'move-terminal');+ }+ return;+ }await app.evaluate(async ({ Menu }, clickCount) => {const terminal = Menu.getApplicationMenu()?.items.find((item) => item.label === 'Terminal');const placement = terminal?.submenu?.items.find(@@ -145,9 +176,14 @@ const terminalTabs = (page: Page) =>page.getByRole('tablist', { name: 'Terminal sessions' }).getByRole('tab');async function openTerminal(app: ElectronApplication, page: Page): Promise<void> {- await clickViewTerminalItem(app);- await expect(visibleTerminal(page)).toBeVisible({ timeout: 15_000 });- await expect(visibleTerminal(page).locator('[data-terminal-status]')).toHaveAttribute(+ const terminal = visibleTerminal(page);+ await expect(async () => {+ // A prior dispatch can land between attempts; observe first so a retry cannot hide it again.+ if (await terminal.isVisible()) return;+ await clickViewTerminalItem(app);+ await expect(terminal).toBeVisible({ timeout: 1_000 });+ }).toPass({ timeout: 15_000 });+ await expect(terminal.locator('[data-terminal-status]')).toHaveAttribute('data-terminal-status','running',{ timeout: 25_000 },@@ -189,7 +225,10 @@ async function readScrollbackContaining(page: Page, marker: string): Promise<strfor (let pageIndex = 0; pageIndex < 20; pageIndex += 1) {const text = await readActiveTerminal(page);if (text.includes(marker)) return text;- await page.mouse.wheel(0, -10_000);+ await page.mouse.wheel(0, -1_000);+ await page.evaluate(+ () => new Promise<void>((resolve) => requestAnimationFrame(() => resolve())),+ );}const text = await readActiveTerminal(page);if (text.includes(marker)) return text;@@ -291,7 +330,7 @@ async function expectCollapsedRailColumn(page: Page, selector: string): Promise<test.describe('Terminal placement continuity — live Electron', () => {test.skip(!SMOKE_ENABLED, 'Set OK_DESKTOP_E2E_SMOKE=1 to run Electron smoke tests.');- test.skip(!DARWIN, 'Desktop is darwin-only.');+ test.skip(!PTY_PLATFORM_SUPPORTED, PTY_PLATFORM_SKIP_REASON);test.skip(!TARGET.exists, TARGET.missingReason);test('moving a populated terminal preserves every live session', async ({ captureStderrFor }) => {@@ -413,7 +452,7 @@ test.describe('Terminal placement continuity — live Electron', () => {// owns pointer-drag behavior. Reordering in the bottom dock keeps this// setup independent of right-column overlay geometry.await visibleTerminal(page).locator('.xterm').click();- await page.keyboard.press('Meta+Shift+ArrowLeft');+ 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',diff --git a/packages/desktop/tests/smoke/terminal-process-restart.e2e.ts b/packages/desktop/tests/smoke/terminal-process-restart.e2e.tsindex cf1229fb1..5ccac2585 100644--- a/packages/desktop/tests/smoke/terminal-process-restart.e2e.ts+++ b/packages/desktop/tests/smoke/terminal-process-restart.e2e.ts@@ -5,11 +5,13 @@ 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 { expect, test } from './_helpers/smoke-test';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 {tmpHome: string;@@ -102,32 +104,28 @@ async function setWindowSize(.toBeGreaterThanOrEqual(width - 100);}-async function clickMenuItem(- app: ElectronApplication,- topLabel: string,- labels: string[],+async function dispatchRendererMenuAction(+ page: Page,+ action: 'move-terminal' | 'toggle-terminal',): Promise<void> {- await app.evaluate(- ({ Menu }, payload) => {- const top = Menu.getApplicationMenu()?.items.find((item) => item.label === payload.topLabel);- const item = top?.submenu?.items.find((candidate) =>- payload.labels.includes(candidate.label),- );- if (!item)- throw new Error(`missing ${payload.topLabel} menu item: ${payload.labels.join(' / ')}`);- item.click();- },- { topLabel, labels },- );+ await page.evaluate(async (menuAction) => {+ const menu = window.okDesktop?.menu;+ if (!menu) throw new Error('renderer menu bridge is unavailable');+ await menu.dispatch({ kind: 'menu-action', action: menuAction });+ }, action);}const terminalTabs = (page: Page) =>page.getByRole('tablist', { name: 'Terminal sessions' }).getByRole('tab');-async function openTerminal(app: ElectronApplication, page: Page): Promise<void> {- await clickMenuItem(app, 'View', ['Show Terminal']);+async function openTerminal(page: Page): Promise<void> {const terminal = page.locator('section[aria-label="Terminal"]:visible');- await expect(terminal).toBeVisible({ timeout: 15_000 });+ await expect(async () => {+ // A prior dispatch can land between attempts; observe first so a retry cannot hide it again.+ if (await terminal.isVisible()) return;+ await dispatchRendererMenuAction(page, 'toggle-terminal');+ await expect(terminal).toBeVisible({ timeout: 1_000 });+ }).toPass({ timeout: 15_000 });await expect(terminal.locator('[data-terminal-status]')).toHaveAttribute('data-terminal-status','running',@@ -141,21 +139,21 @@ async function openBareTab(page: Page): Promise<void> {await expect(terminalTabs(page)).toHaveCount(2, { timeout: 25_000 });}-async function growRightTerminal(page: Page, deltaPx: number): Promise<number> {+async function applyPersistedRightTerminalWidth(page: Page, width: number): Promise<number> {+ await page.evaluate((nextWidth) => {+ localStorage.setItem('ok-terminal-right-width-v1', String(nextWidth));+ }, width);+ await page.reload({ waitUntil: 'domcontentloaded' });const column = page.locator('#terminal-column');- const before = await column.evaluate((element) => element.getBoundingClientRect().width);- const handle = await column.evaluate((element) => {- const rect = element.previousElementSibling?.getBoundingClientRect();- return rect == null ? null : { x: rect.x, y: rect.y, width: rect.width, height: rect.height };- });- if (!handle) throw new Error('right Terminal resize handle unavailable');- await page.mouse.move(handle.x + handle.width / 2, handle.y + handle.height / 2);- await page.mouse.down();- await page.mouse.move(handle.x - deltaPx, handle.y + handle.height / 2, { steps: 12 });- await page.mouse.up();+ await expect(column).toBeVisible({ timeout: 20_000 });await expect- .poll(() => column.evaluate((element) => element.getBoundingClientRect().width))- .toBeGreaterThan(before + deltaPx / 2);+ .poll(async () => {+ const renderedWidth = await column.evaluate(+ (element) => element.getBoundingClientRect().width,+ );+ return Math.abs(renderedWidth - width);+ })+ .toBeLessThan(20);return column.evaluate((element) => element.getBoundingClientRect().width);}@@ -177,7 +175,7 @@ async function quitAndWait(app: ElectronApplication, child: ChildProcess): Promitest.describe('terminal process restart', () => {test.skip(!ENABLED, 'Set OK_DESKTOP_E2E_SMOKE=1');- test.skip(process.platform !== 'darwin', 'Desktop is darwin-only');+ test.skip(!PTY_PLATFORM_SUPPORTED, PTY_PLATFORM_SKIP_REASON);test.skip(!TARGET.exists, TARGET.missingReason);test('restores placement, width, tab order, and active tab in a separate Electron process', async ({@@ -191,21 +189,28 @@ test.describe('terminal process restart', () => {const firstProcess = firstApp.process();const firstPage = await findEditorWindow(firstApp);await setWindowSize(firstApp, firstPage, 1900, 900);- await openTerminal(firstApp, firstPage);+ await openTerminal(firstPage);await openBareTab(firstPage);// 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('Meta+Shift+ArrowLeft');+ 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('aria-selected','true',);- await clickMenuItem(firstApp, 'Terminal', ['Move Terminal to right']);+ await dispatchRendererMenuAction(firstPage, 'move-terminal');await expect(firstPage.locator('#terminal-column')).toBeVisible({ timeout: 10_000 });- const retainedWidth = await growRightTerminal(firstPage, 120);+ // 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(+ 'aria-selected',+ 'true',+ );await quitAndWait(firstApp, firstProcess);const secondApp = await launchRestartProfile(seed);diff --git a/packages/desktop/tests/smoke/terminal-tabs.e2e.ts b/packages/desktop/tests/smoke/terminal-tabs.e2e.tsindex 189aec6da..e93e7e480 100644--- a/packages/desktop/tests/smoke/terminal-tabs.e2e.ts+++ b/packages/desktop/tests/smoke/terminal-tabs.e2e.ts@@ -7,8 +7,8 @@* - closing a tab reaps only that tab's shell — the survivor stays interactive;* - a manual rename pins over the program's OSC 0/2 title (the running shell* sets a title; the user's custom name wins);- * - keyboard reorder (⌘⇧←/→) changes tab order, keeps each session's sticky- * number, and PRESERVES the moved tab's live shell + scrollback — the+ * - keyboard reorder (CmdOrCtrl+Shift+Left/Right) changes tab order, keeps+ * each session's sticky number, and PRESERVES the moved tab's live shell + scrollback — the* regression that shipped ("reorder resets my terminal"): reordering moved* the panel's xterm container in the DOM, disrupting the running program.*@@ -19,8 +19,9 @@* reorder); this pins the live-session outcome.** Skip gates mirror the sibling terminal smokes: opt-in via OK_DESKTOP_E2E_SMOKE=1,- * darwin-only, and the electron-vite build must exist (out/main/index.js). Runs- * in local dev / the release gate. Not part of `pnpm check`.+ * a PTY-capable platform, and the electron-vite build must exist+ * (out/main/index.js). Runs in local dev / the release gate. Not part of+ * `pnpm check`.*/import { mkdirSync, mkdtempSync, realpathSync, rmSync, writeFileSync } from 'node:fs';@@ -29,14 +30,15 @@ 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 { expect, test } from './_helpers/smoke-test';import { waitForShellReady } from './_helpers/terminal-ready';const TARGET = resolveDesktopTarget();const SMOKE_ENABLED = process.env.OK_DESKTOP_E2E_SMOKE === '1';-const DARWIN = process.platform === 'darwin';const DESKTOP_PRODUCT_NAME = '@inkeep/open-knowledge-desktop';+const PRIMARY_MODIFIER = process.platform === 'darwin' ? 'Meta' : 'Control';interface Seed {tmpHome: string;@@ -224,7 +226,7 @@ function track(...paths: string[]): void {test.describe('Terminal tabs — live Electron', () => {test.skip(!SMOKE_ENABLED, 'Set OK_DESKTOP_E2E_SMOKE=1 to run Electron smoke tests.');- test.skip(!DARWIN, 'Desktop is darwin-only.');+ test.skip(!PTY_PLATFORM_SUPPORTED, PTY_PLATFORM_SKIP_REASON);test.skip(!TARGET.exists, TARGET.missingReason);test.afterEach(() => {for (const target of cleanup.splice(0)) {@@ -334,8 +336,8 @@ test.describe('Terminal tabs — live Electron', () => {await activateTab(page, 'Terminal 1');await visibleSection(page).locator('.xterm').click();- // ⌘⇧→ moves the active tab (Terminal 1) one slot right.- await page.keyboard.press('Meta+Shift+ArrowRight');+ // CmdOrCtrl+Shift+Right moves the active tab (Terminal 1) one slot right.+ await page.keyboard.press(`${PRIMARY_MODIFIER}+Shift+ArrowRight`);// Order changed; the sticky numbers rode with their sessions (NOT renumbered// by position).diff --git a/packages/desktop/tests/smoke/terminal-window.e2e.ts b/packages/desktop/tests/smoke/terminal-window.e2e.tsindex 0934f9ccd..b4712227c 100644--- a/packages/desktop/tests/smoke/terminal-window.e2e.ts+++ b/packages/desktop/tests/smoke/terminal-window.e2e.ts@@ -10,8 +10,9 @@* kills the host); this asserts the observable window-close.** Skip gates mirror terminal-dock.e2e.ts: opt-in via OK_DESKTOP_E2E_SMOKE=1,- * darwin-only, and the electron-vite build must exist. Not part of `pnpm check`;- * run via `pnpm exec playwright test` or `pnpm run check:full:parallel`.+ * a PTY-capable platform, and the electron-vite build must exist. Not part of+ * `pnpm check`; run via `pnpm exec playwright test` or+ * `pnpm run check:full:parallel`.*/import { mkdirSync, mkdtempSync, realpathSync, rmSync, writeFileSync } from 'node:fs';@@ -20,12 +21,12 @@ 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 { expect, test } from './_helpers/smoke-test';const TARGET = resolveDesktopTarget();const SMOKE_ENABLED = process.env.OK_DESKTOP_E2E_SMOKE === '1';-const DARWIN = process.platform === 'darwin';const DESKTOP_PRODUCT_NAME = '@inkeep/open-knowledge-desktop';interface Seed {@@ -147,7 +148,7 @@ function track(...paths: string[]): void {test.describe('Standalone terminal window — live Electron', () => {test.skip(!SMOKE_ENABLED, 'Set OK_DESKTOP_E2E_SMOKE=1 to run Electron smoke tests.');- test.skip(!DARWIN, 'Desktop is darwin-only.');+ test.skip(!PTY_PLATFORM_SUPPORTED, PTY_PLATFORM_SKIP_REASON);test.skip(!TARGET.exists, TARGET.missingReason);test.afterEach(() => {for (const target of cleanup.splice(0)) {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 481b85644..f2f195892 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@@ -5,22 +5,22 @@ import { describe, expect, test } from 'vitest';import { parse } from 'yaml';/**- * Regression guard for node-pty packaging on the arm64 desktop build.+ * Regression guard for node-pty packaging on the desktop builds.*- * node-pty ships its native addon and an extensionless `spawn-helper` binary- * under `prebuilds/<platform>-<arch>/`. Three things must hold together or the- * in-app terminal is dead on arrival in the packaged `.app`:+ * node-pty ships its native addons under `prebuilds/<platform>-<arch>/`;+ * Darwin also carries an extensionless `spawn-helper`. These invariants must+ * hold together or the in-app terminal is dead on arrival in the packaged app:** 1. node-pty is the upstream package, pinned in optionalDependencies — NOT* `@lydell/node-pty`, whose per-arch optionalDependency layout recreates* the keyring universal-merge hazard that forced this build arm64-only.* optionalDependencies placement is itself load-bearing in the other* direction: node-pty's node-gyp build needs a C toolchain, and a failed- * optional install is dropped by bun instead of failing the whole repo's- * install (the built-in terminal is macOS-only).+ * optional install is dropped by pnpm instead of failing the whole+ * workspace install when a host has no native toolchain.* electron-builder packs installed optional production deps the same as* regular ones, so the packaged app is unaffected on the macOS build- * host, where the native build always runs.+ * host.* 2. `**\/node-pty/prebuilds/**` is in asarUnpack. The generic `**\/*.node`* rule unpacks `pty.node` but NOT `spawn-helper` (no `.node` extension);* node-pty resolves the helper from `app.asar.unpacked` at runtime, so it@@ -30,6 +30,8 @@ import { parse } from 'yaml';* it 0644 (node-pty#850) and asarUnpack preserves that mode. Behavior of* that chmod is covered by ensure-node-pty-exec.test.ts; this guard only* 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.** The build also stays arm64-only (no universal target) — node-pty would add a* second per-arch native into any universal lipo-merge.@@ -43,6 +45,7 @@ const afterPack = resolve(desktopRoot, 'scripts', 'afterPack.mjs');function readBuilderConfig(): {asarUnpack?: string[];+ linux?: { files?: string[] };mac?: { target?: Array<{ target?: string; arch?: string[] }> };} {return parse(readFileSync(builderYml, 'utf8'));@@ -70,12 +73,12 @@ describe('node-pty desktop packaging config', () => {pkg.optionalDependencies?.['node-pty'],'node-pty must be a pinned optionalDependency: electron-builder still packs installed ' +'optional production deps into the app, and optional placement keeps a failed node-gyp ' +- 'build (Linux contributor without a C toolchain) from failing the whole repo bun install.',- ).toBe('1.1.0');+ 'build from failing the whole workspace install.',+ ).toBe('1.2.0-beta.15');expect(pkg.dependencies?.['node-pty'],'node-pty must not also appear in dependencies — that placement makes its native build ' +- 'failure fatal to bun install on machines without a C toolchain.',+ 'failure fatal to pnpm install on machines without a C toolchain.',).toBeUndefined();expect('@lydell/node-pty' in deps,@@ -94,6 +97,33 @@ describe('node-pty desktop packaging config', () => {).toBe(true);});+ test.each([+ ['linux-x64', 62],+ ['linux-arm64', 183],+ ])('%s ships an ELF pty.node for the declared architecture', (platformArch, elfMachine) => {+ const addon = resolve(+ desktopRoot,+ 'node_modules',+ 'node-pty',+ 'prebuilds',+ platformArch,+ 'pty.node',+ );+ expect(existsSync(addon), `node-pty must ship ${platformArch}/pty.node`).toBe(true);++ const binary = readFileSync(addon);+ expect([...binary.subarray(0, 4)]).toEqual([0x7f, 0x45, 0x4c, 0x46]);+ expect(binary.readUInt16LE(18)).toBe(elfMachine);+ });++ test('linux packages node-pty but excludes foreign prebuilds and debug symbols', () => {+ const patterns = readBuilderConfig().linux?.files ?? [];+ expect(patterns).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/win32-*/**');+ });+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/ensure-node-pty-exec.test.ts b/packages/desktop/tests/unit/ensure-node-pty-exec.test.tsindex 3dbfd509f..cf9a9bee7 100644--- a/packages/desktop/tests/unit/ensure-node-pty-exec.test.ts+++ b/packages/desktop/tests/unit/ensure-node-pty-exec.test.ts@@ -6,6 +6,7 @@ import {ensureNodePtySpawnHelperExecutable,ensureNodePtySpawnHelperExecutableInNodeModules,ensureNodePtySpawnHelperExecutableInNodeModulesSafe,+ shouldEnsureNodePtySpawnHelper,} from '../../scripts/ensure-node-pty-exec.mjs';/**@@ -83,9 +84,9 @@ describe('ensureNodePtySpawnHelperExecutable', () => {/*** Behavioral coverage for the dev/CI build+install path — the analog of the- * afterPack chmod above. `bun install` lands node-pty's prebuilt spawn-helper+ * afterPack chmod above. `pnpm install` lands node-pty's prebuilt spawn-helper* non-executable under the real `node_modules/node-pty/prebuilds/...` tree, and- * the dev build (`bun run build:desktop`, electron-vite, no afterPack) has no+ * the dev build (`pnpm run build:desktop`, electron-vite, no afterPack) has no* step to fix it, so the in-app terminal dies with "posix_spawnp failed". The* desktop postinstall runs this against the real `node_modules` layout; we* exercise the real mode bits against a fixture mirroring it — no mocks.@@ -103,7 +104,7 @@ function makeNodeModulesFixture(archDirs: string[]): string {const helper = nodeModulesHelperPath(nodePtyDir, arch);mkdirSync(join(helper, '..'), { recursive: true });writeFileSync(helper, 'fake-mach-o');- // Mirror the non-executable mode bun install leaves behind.+ // Mirror the non-executable mode pnpm install leaves behind.chmodSync(helper, 0o644);}return nodePtyDir;@@ -142,7 +143,7 @@ describe('ensureNodePtySpawnHelperExecutableInNodeModules', () => {/*** The postinstall's non-throwing contract: a pathological node-pty layout must NEVER- * fail `bun install` (that would gate the whole monorepo). The Safe wrapper converts+ * fail `pnpm install` (that would gate the whole monorepo). The Safe wrapper converts* the hard-error throw above into an `{ ok: false, error }` result so the postinstall* caller stays exit-0. Pinned here so a refactor that drops the swallowing regresses.*/@@ -168,3 +169,11 @@ describe('ensureNodePtySpawnHelperExecutableInNodeModulesSafe', () => {}});});++describe('shouldEnsureNodePtySpawnHelper', () => {+ test('runs the spawn-helper chmod only on Darwin', () => {+ expect(shouldEnsureNodePtySpawnHelper('darwin')).toBe(true);+ expect(shouldEnsureNodePtySpawnHelper('linux')).toBe(false);+ expect(shouldEnsureNodePtySpawnHelper('win32')).toBe(false);+ });+});diff --git a/packages/desktop/tests/unit/linux-package-native-guards.test.ts b/packages/desktop/tests/unit/linux-package-native-guards.test.tsnew file mode 100644index 000000000..05d8926ef--- /dev/null+++ b/packages/desktop/tests/unit/linux-package-native-guards.test.ts@@ -0,0 +1,144 @@+import {+ mkdirSync,+ mkdtempSync,+ readdirSync,+ readFileSync,+ rmSync,+ statSync,+ writeFileSync,+} from 'node:fs';+import { tmpdir } from 'node:os';+import { dirname, join, relative, resolve } from 'node:path';+import { fileURLToPath } from 'node:url';+import { afterEach, describe, expect, test } from 'vitest';++const __dirname = dirname(fileURLToPath(import.meta.url));+const desktopRoot = resolve(__dirname, '../..');+const packageDirInput = process.env.OK_LINUX_PACKAGE_DIR?.trim() ?? '';+const packageDir = packageDirInput === '' ? null : resolve(desktopRoot, packageDirInput);++const MAX_NATIVE_VERSIONS = {+ GLIBC: '2.31',+ GLIBCXX: '3.4.28',+} as const;++type NativeVersionFamily = keyof typeof MAX_NATIVE_VERSIONS;++function compareVersions(left: string, right: string): number {+ const a = left.split('.').map(Number);+ const b = right.split('.').map(Number);+ const width = Math.max(a.length, b.length);+ for (let index = 0; index < width; index += 1) {+ const difference = (a[index] ?? 0) - (b[index] ?? 0);+ if (difference !== 0) return difference;+ }+ return 0;+}++function requiredNativeVersions(binary: Buffer): Map<NativeVersionFamily, string> {+ const required = new Map<NativeVersionFamily, string>();+ const text = binary.toString('latin1');+ for (const match of text.matchAll(/\b(GLIBCXX|GLIBC)_(\d+\.\d+(?:\.\d+)?)\b/g)) {+ const family = match[1] as NativeVersionFamily;+ const version = match[2];+ const current = required.get(family);+ if (current === undefined || compareVersions(version, current) > 0) {+ required.set(family, version);+ }+ }+ return required;+}++function findNativeAddons(root: string): string[] {+ const found: string[] = [];+ const visit = (dir: string): void => {+ for (const entry of readdirSync(dir, { withFileTypes: true })) {+ const path = join(dir, entry.name);+ if (entry.isDirectory()) visit(path);+ else if (entry.isFile() && entry.name.endsWith('.node')) found.push(path);+ }+ };+ visit(root);+ return found.sort();+}++const fixtureDirs: string[] = [];+afterEach(() => {+ for (const dir of fixtureDirs.splice(0)) rmSync(dir, { recursive: true, force: true });+});++describe('Linux package native-version guard helpers', () => {+ test('extracts the highest GLIBC and GLIBCXX version tags numerically', () => {+ const versions = requiredNativeVersions(+ Buffer.from('GLIBC_2.9\0GLIBC_2.31\0GLIBC_2.28\0GLIBCXX_3.4.9\0GLIBCXX_3.4.28'),+ );+ expect(Object.fromEntries(versions)).toEqual({ GLIBC: '2.31', GLIBCXX: '3.4.28' });+ });++ test('walks nested package resources without treating non-.node files as addons', () => {+ const root = mkdtempSync(join(tmpdir(), 'ok-linux-native-guard-'));+ fixtureDirs.push(root);+ const nested = join(root, 'resources', 'app.asar.unpacked');+ const addon = join(nested, 'pty.node');+ const sibling = join(nested, 'helper.txt');+ mkdirSync(nested, { recursive: true });+ writeFileSync(addon, 'ELF');+ writeFileSync(sibling, 'not native');+ expect(findNativeAddons(root)).toEqual([addon]);+ });+});++describe('Linux package native guard lane visibility', () => {+ test('reports whether OK_LINUX_PACKAGE_DIR enabled the assertive lane', () => {+ if (packageDir === null) {+ console.log(+ '[linux-package-native-guards] OK_LINUX_PACKAGE_DIR is unset — packaged-artifact assertions skipped',+ );+ return;+ }+ console.log(`[linux-package-native-guards] checking ${packageDir}`);+ expect(packageDirInput).not.toBe('');+ });+});++describe.skipIf(packageDir === null)('packaged Linux native modules', () => {+ test('carries node-pty for the packaged architecture', () => {+ expect(+ process.platform,+ 'OK_LINUX_PACKAGE_DIR must only be set in a Linux packaging lane',+ ).toBe('linux');+ const ptyNode = join(+ packageDir as string,+ 'resources',+ 'app.asar.unpacked',+ 'node_modules',+ 'node-pty',+ 'prebuilds',+ `linux-${process.arch}`,+ 'pty.node',+ );+ expect(+ statSync(ptyNode).isFile(),+ `packaged node-pty prebuild missing at ${relative(packageDir as string, ptyNode)}`,+ ).toBe(true);+ });++ test('keeps every shipped native addon within Electron’s Debian 11 ABI floor', () => {+ const addons = findNativeAddons(packageDir as string);+ expect(addons.length, `no .node binaries found under ${packageDir}`).toBeGreaterThan(0);++ for (const addon of addons) {+ const versions = requiredNativeVersions(readFileSync(addon));+ for (const [family, maximum] of Object.entries(MAX_NATIVE_VERSIONS) as Array<+ [NativeVersionFamily, string]+ >) {+ const required = versions.get(family);+ if (required === undefined) continue;+ expect(+ compareVersions(required, maximum),+ `${relative(packageDir as string, addon)} requires ${family}_${required}, above the recorded ${family}_${maximum} Electron floor`,+ ).toBeLessThanOrEqual(0);+ }+ }+ });+});diff --git a/packages/desktop/tests/utility/pty-host-real-io.test.ts b/packages/desktop/tests/utility/pty-host-real-io.test.tsindex bf96bbcd5..c47222fc1 100644--- a/packages/desktop/tests/utility/pty-host-real-io.test.ts+++ b/packages/desktop/tests/utility/pty-host-real-io.test.ts@@ -1,37 +1,22 @@+import { spawnSync } from 'node:child_process';import { describe, expect, test } from 'vitest';+import { isTerminalPlatform } from '../../src/shared/terminal-platform.ts';/**- * Gate wrapper for the real-shell-I/O seam. node-pty does not pump under Bun,- * so the actual PTY drive runs in `pty-host.real-io-harness.ts` under Node- * (a hard package engine, >=24); this test runs that harness as a subprocess- * and fails if it does not report all scenarios green.+ * 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 NODE = Bun.which('node');const HARNESS = new URL('./pty-host.real-io-harness.ts', import.meta.url).pathname;-// macOS-only: the docked terminal ships on macOS, and the real login-shell-// round-trip is environment-sensitive on the Linux CI runner (node-pty's-// PTY-fd reads are libuv-driven and the interactive-shell echo timing differs),-// which made it fail deterministically there while passing on macOS. The seam's-// CI coverage lives on the macOS `preflight` cell instead (see-// .github/workflows/public-open-knowledge-validation.yml). Runs unconditionally-// in local macOS dev.-const IS_DARWIN = process.platform === 'darwin';-describe('PTY host — real shell I/O (Node runtime)', () => {- test.skipIf(!IS_DARWIN)(- 'real login shell round-trips a command, strips env markers, survives a kill, and reports a bad shell',+ test.skipIf(!isTerminalPlatform(process.platform))(+ 'real interactive shell round-trips a command, strips env markers, survives a kill, and reports a bad shell',() => {- if (!NODE) {- throw new Error(- 'node was not found on PATH but is required (package engines: >=24) to exercise the real-PTY seam — 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(`real-PTY harness failed (exit ${proc.exitCode}):\n${output}`);+ 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}`);}expect(output).toContain('HARNESS_RESULT ok=4 fail=0');},diff --git a/packages/desktop/tests/utility/pty-host-reap.test.ts b/packages/desktop/tests/utility/pty-host-reap.test.tsindex e047014fc..77c0dfb01 100644--- a/packages/desktop/tests/utility/pty-host-reap.test.ts+++ b/packages/desktop/tests/utility/pty-host-reap.test.ts@@ -7,8 +7,8 @@ import { describe, expect, test } from 'vitest';/*** No-orphan OUTCOME seam. Verifies the system property the feature requires:* killing a PTY host process leaves no surviving shell. Real shell +- * real signal are required, and node-pty does not pump under Bun, so the drive- * runs in `pty-host.reap-harness.ts` under Node; this test spawns it, reads the+ * real signal are required, so the drive runs in an isolated Node subprocess;+ * this test spawns it, reads the* shell pid it spawned, kills the host, and asserts the shell pid is gone.** No-orphan is defense-in-depth — the explicit `installHostReaping` `pty.kill()`@@ -19,7 +19,6 @@ import { describe, expect, test } from 'vitest';* alone — both must leave no orphan, including under a forced host crash.*/-const NODE = Bun.which('node');const HARNESS = new URL('./pty-host.reap-harness.ts', import.meta.url).pathname;async function readShellPid(@@ -54,7 +53,7 @@ async function waitForReaped(pid: number, timeoutMs: number): Promise<boolean> {}async function assertNoOrphan(killSignal: 'SIGTERM' | 'SIGKILL'): Promise<void> {- const child = nodeSpawn(NODE as string, [HARNESS], { stdio: ['ignore', 'pipe', 'inherit'] });+ const child = nodeSpawn(process.execPath, [HARNESS], { stdio: ['ignore', 'pipe', 'inherit'] });const childStdout = child.stdout;if (!childStdout) throw new Error('spawned harness has no stdout pipe');const proc = {@@ -86,20 +85,10 @@ 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 () => {- if (!NODE) {- throw new Error(- 'node was not found on PATH but is required (package engines: >=24) to spawn a real PTY — node-pty is silent under Bun',- );- }await assertNoOrphan('SIGTERM');}, 60_000);test('a SIGKILL to the host leaves no orphan shell (OS backstop, no handler runs)', async () => {- if (!NODE) {- throw new Error(- 'node was not found on PATH but is required (package engines: >=24) to spawn a real PTY — node-pty is silent under Bun',- );- }await assertNoOrphan('SIGKILL');}, 60_000);});diff --git a/packages/desktop/tests/utility/pty-host.real-io-harness.ts b/packages/desktop/tests/utility/pty-host.real-io-harness.tsindex 5987f60ba..ab9a3f351 100644--- a/packages/desktop/tests/utility/pty-host.real-io-harness.ts+++ b/packages/desktop/tests/utility/pty-host.real-io-harness.ts@@ -1,12 +1,10 @@/**- * Real-shell-I/O harness for the PTY host — RUN UNDER NODE, not Bun.+ * Real-shell-I/O harness for the PTY host.*- * node-pty's PTY-fd reads are driven by libuv and do not pump under Bun's- * event loop (a spawned shell produces zero bytes), so `bun test` cannot- * exercise the real shell. This harness drives the actual `setupPtyHost`- * factory with a real `node-pty` spawn under the Node runtime and asserts the- * real-I/O contract end to end. `pty-host-real-io.test.ts` invokes it as a- * Node subprocess from Bun and asserts on its exit code + result line.+ * This harness drives the actual `setupPtyHost` factory with a real `node-pty`+ * spawn under Node and asserts the real-I/O contract end to end.+ * `pty-host-real-io.test.ts` invokes it as an isolated subprocess and asserts+ * 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.@@ -180,7 +178,7 @@ async function main(): Promise<void> {process.exit(failed === 0 ? 0 : 1);}-// Hard ceiling so a wedged shell can never hang the parent `bun test`.+// 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);diff --git a/packages/desktop/tests/utility/pty-host.reap-harness.ts b/packages/desktop/tests/utility/pty-host.reap-harness.tsindex 023d9ad9d..63e2be045 100644--- a/packages/desktop/tests/utility/pty-host.reap-harness.ts+++ b/packages/desktop/tests/utility/pty-host.reap-harness.ts@@ -1,10 +1,10 @@/**- * No-orphan reap harness — RUN UNDER NODE, not Bun.+ * No-orphan reap harness.** Proves the OS-level no-orphan guarantee: a host that is SIGTERM'd (what* Electron's `utilityProcess.kill()` delivers) reaps its real node-pty shell- * instead of orphaning it. node-pty's PTY-fd reads do not pump under Bun, so- * this runs under Node; `pty-host-reap.test.ts` spawns it, reads the shell pid+ * instead of orphaning it. `pty-host-reap.test.ts` spawns this under Node,+ * reads the shell pid* it prints, SIGTERMs it, and asserts that pid is gone.** Shape: spawn a real login shell, print `SHELLPID=<pid>` (the shell's owndiff --git a/packages/desktop/tests/utility/pty-host.test.ts b/packages/desktop/tests/utility/pty-host.test.tsindex 3d4f71574..ac0ae16f5 100644--- a/packages/desktop/tests/utility/pty-host.test.ts+++ b/packages/desktop/tests/utility/pty-host.test.ts@@ -1,10 +1,12 @@import { OK_DESKTOP_TERMINAL_ENV } from '@inkeep/open-knowledge-core';import { describe, expect, test } from 'vitest';+import { isTerminalPlatform } from '../../src/shared/terminal-platform.ts';import {buildShellArgs,buildShellEnv,type HostReapProcess,installHostReaping,+ installPtyImportFailureReply,type PtyCreateMessage,type PtyHostHandle,type PtyHostIncomingMessage,@@ -19,7 +21,7 @@ import {/*** Unit tests for the PTY host message-routing contract. node-pty is injected* as a controllable fake — the real-shell-I/O path runs under Node via- * `pty-host.real-io-harness.ts` (node-pty's reads don't pump under Bun).+ * `pty-host.real-io-harness.ts` in an isolated Node subprocess.*/interface FakePty extends PtyProcessLike {@@ -87,6 +89,9 @@ function makeHarness(opts?: {pty?: FakePty;spawn?: SpawnPty;env?: Record<string, string | undefined>;+ platform?: NodeJS.Platform;+ userInfoShell?: () => string | null;+ shellExists?: (path: string) => boolean;logger?: { warn: (o: Record<string, unknown>) => void };}): Harness {let handler: ((event: { data: unknown }) => void) | null = null;@@ -110,6 +115,9 @@ function makeHarness(opts?: {},spawn,env: opts?.env ?? { SHELL: '/bin/zsh', PATH: '/usr/bin' },+ platform: opts?.platform ?? 'darwin',+ userInfoShell: opts?.userInfoShell,+ shellExists: opts?.shellExists,logger: opts?.logger,});return {@@ -142,6 +150,19 @@ describe('setupPtyHost — create', () => {expect(h.spawnCalls[0]?.options.rows).toBe(24);});+ test('Linux creates the PTY with interactive non-login argv', () => {+ const h = makeHarness({+ platform: 'linux',+ env: { SHELL: '/bin/bash', PATH: '/usr/bin' },+ shellExists: (path) => path === '/bin/bash',+ });+ h.fire(CREATE());++ expect(h.spawnCalls[0]?.file).toBe('/bin/bash');+ expect(h.spawnCalls[0]?.args).toEqual(['-i']);+ expect(h.spawnCalls[0]?.args).not.toContain('-l');+ });+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@@ -599,13 +620,15 @@ describe('setupPtyHost — incoming message validation (asIncomingMessage guard)});describe('buildShellArgs', () => {- test('a plain tab is the bare login interactive shell', () => {- expect(buildShellArgs('/bin/zsh')).toEqual(['-l', '-i']);- expect(buildShellArgs('/bin/zsh', '')).toEqual(['-l', '-i']);+ test('a plain tab follows the platform interactive-shell convention', () => {+ expect(buildShellArgs('darwin', '/bin/zsh')).toEqual(['-l', '-i']);+ expect(buildShellArgs('darwin', '/bin/zsh', '')).toEqual(['-l', '-i']);+ expect(buildShellArgs('linux', '/bin/bash')).toEqual(['-i']);+ expect(buildShellArgs('linux', '/bin/bash', '')).toEqual(['-i']);});- test('a launch bakes the command on `-c` and execs into a fresh interactive shell', () => {- expect(buildShellArgs('/bin/zsh', "codex 'hi'")).toEqual([+ test('a macOS launch keeps login flags in the launcher and exec tail', () => {+ expect(buildShellArgs('darwin', '/bin/zsh', "codex 'hi'")).toEqual(['-l','-i','-c',@@ -613,8 +636,21 @@ describe('buildShellArgs', () => {]);});+ test('a Linux launch is interactive without forcing login semantics', () => {+ expect(buildShellArgs('linux', '/bin/bash', "codex 'hi'")).toEqual([+ '-i',+ '-c',+ "codex 'hi'; exec '/bin/bash' -i",+ ]);+ });+test('single-quotes the shell path in the exec tail (space/quote-safe)', () => {- expect(buildShellArgs("/odd path/o'sh", "claude 'x'")).toEqual([+ expect(buildShellArgs('linux', "/odd path/o'sh", "claude 'x'")).toEqual([+ '-i',+ '-c',+ "claude 'x'; exec '/odd path/o'\\''sh' -i",+ ]);+ expect(buildShellArgs('darwin', "/odd path/o'sh", "claude 'x'")).toEqual(['-l','-i','-c',@@ -630,6 +666,11 @@ describe('buildShellEnv', () => {HOME: '/Users/x',OK_ELECTRON_PROTOCOL_HOST: '1',OK_LOCK_KIND: 'interactive',+ ELECTRON_RUN_AS_NODE: '1',+ GDK_PIXBUF_MODULEDIR: '/app/lib/gdk-pixbuf',+ GDK_PIXBUF_MODULE_FILE: '/app/lib/loaders.cache',+ ELECTRON_TRASH: 'gio',+ GDK_THEME: 'Adwaita',MAYBE: undefined,});// `~/.ok/bin` rides in front of the inherited PATH — OK's own spawned@@ -637,17 +678,177 @@ describe('buildShellEnv', () => {expect(env).toEqual({PATH: '/Users/x/.ok/bin:/usr/bin',HOME: '/Users/x',+ ELECTRON_TRASH: 'gio',+ GDK_THEME: 'Adwaita',[OK_DESKTOP_TERMINAL_ENV]: '1',});});});describe('resolveShell', () => {- test('prefers an override, then $SHELL, then the darwin fallback', () => {- expect(resolveShell({ SHELL: '/bin/bash' }, '/usr/bin/fish')).toBe('/usr/bin/fish');- expect(resolveShell({ SHELL: '/bin/bash' })).toBe('/bin/bash');- expect(resolveShell({})).toBe('/bin/zsh');- expect(resolveShell({ SHELL: '' })).toBe('/bin/zsh');+ const shellExists = (paths: string[]) => (path: string) => paths.includes(path);++ test('macOS preserves override, $SHELL, and zsh fallback behavior', () => {+ expect(+ resolveShell({ SHELL: '/bin/bash' }, { platform: 'darwin', override: '/usr/bin/fish' }),+ ).toBe('/usr/bin/fish');+ expect(resolveShell({ SHELL: '/bin/bash' }, { platform: 'darwin' })).toBe('/bin/bash');+ expect(resolveShell({}, { platform: 'darwin' })).toBe('/bin/zsh');+ expect(resolveShell({ SHELL: '' }, { platform: 'darwin' })).toBe('/bin/zsh');+ });++ test('Linux prefers $SHELL, then the passwd shell', () => {+ expect(+ resolveShell(+ { SHELL: '/usr/bin/fish' },+ {+ platform: 'linux',+ userInfoShell: () => '/bin/zsh',+ shellExists: shellExists(['/usr/bin/fish', '/bin/zsh']),+ },+ ),+ ).toBe('/usr/bin/fish');+ expect(+ resolveShell(+ { SHELL: '' },+ {+ platform: 'linux',+ userInfoShell: () => '/bin/zsh',+ shellExists: shellExists(['/bin/zsh']),+ },+ ),+ ).toBe('/bin/zsh');+ });++ test('Linux treats false-style and nonexistent configured shells as unset', () => {+ for (const configuredShell of [+ '/bin/false',+ '/usr/bin/false',+ '/usr/sbin/nologin',+ '/missing',+ ]) {+ expect(+ resolveShell(+ { SHELL: configuredShell },+ {+ platform: 'linux',+ userInfoShell: () => '/bin/fish',+ shellExists: shellExists(['/bin/fish']),+ },+ ),+ ).toBe('/bin/fish');+ }+ });++ test('Linux falls back through bash to sh when passwd lookup is absent', () => {+ expect(+ resolveShell(+ {},+ {+ platform: 'linux',+ userInfoShell: () => null,+ shellExists: shellExists(['/bin/bash', '/bin/sh']),+ },+ ),+ ).toBe('/bin/bash');+ expect(+ resolveShell(+ {},+ {+ platform: 'linux',+ userInfoShell: () => null,+ shellExists: shellExists(['/bin/sh']),+ },+ ),+ ).toBe('/bin/sh');+ });++ test('Linux logs and falls back when passwd lookup throws', () => {+ const warnings: Record<string, unknown>[] = [];++ expect(+ resolveShell(+ {},+ {+ platform: 'linux',+ userInfoShell: () => {+ throw Object.assign(new Error('no passwd entry'), { code: 'ENOENT' });+ },+ shellExists: shellExists(['/bin/bash', '/bin/sh']),+ logger: { warn: (data) => warnings.push(data) },+ },+ ),+ ).toBe('/bin/bash');+ expect(warnings).toContainEqual({+ event: 'pty-host-user-info-shell-failed',+ code: 'ENOENT',+ });+ });++ test('Linux ignores a false-style passwd shell before falling back', () => {+ expect(+ resolveShell(+ {},+ {+ platform: 'linux',+ userInfoShell: () => '/bin/false',+ shellExists: shellExists(['/bin/false', '/bin/bash', '/bin/sh']),+ },+ ),+ ).toBe('/bin/bash');+ });+});++describe('node-pty import failure', () => {+ test('a Linux-capable host replies to create with the existing spawn-error contract', () => {+ expect(isTerminalPlatform('linux')).toBe(true);++ let handler: ((event: { data: unknown }) => void) | null = null;+ const posted: PtyHostOutgoingMessage[] = [];+ const warnings: Array<{ data: Record<string, unknown>; message: string }> = [];+ installPtyImportFailureReply(+ {+ on(_event, nextHandler) {+ handler = nextHandler;+ },+ postMessage(message) {+ posted.push(message);+ },+ },+ new Error('node-pty Linux prebuild could not be loaded'),+ {+ warn(data, message) {+ warnings.push({ data, message });+ },+ },+ );++ handler?.({+ data: {+ type: 'create',+ ptyId: 'linux-pty',+ cwd: '/project',+ cols: 80,+ rows: 24,+ },+ });++ expect(posted).toEqual([+ {+ type: 'spawn-error',+ ptyId: 'linux-pty',+ message: 'node-pty Linux prebuild could not be loaded',+ },+ ]);+ expect(warnings).toEqual([+ {+ data: {+ event: 'pty-host-import-failed',+ error: 'node-pty Linux prebuild could not be loaded',+ },+ message: 'node-pty import failed',+ },+ ]);});});diff --git a/packages/native-config/package.json b/packages/native-config/package.jsonindex a70aee7c6..41e61653a 100644--- a/packages/native-config/package.json+++ b/packages/native-config/package.json@@ -25,9 +25,9 @@"*.node"],"scripts": {- "build": "napi build --platform --release",- "build:debug": "napi build --platform",- "test": "cargo test"+ "build": "node scripts/build.mjs --release",+ "build:debug": "node scripts/build.mjs",+ "test": "cargo test && node --test scripts/build.test.mjs"},"devDependencies": {"@napi-rs/cli": "^3.7.2"diff --git a/packages/native-config/scripts/build.mjs b/packages/native-config/scripts/build.mjsnew file mode 100644index 000000000..d6c3fd461--- /dev/null+++ b/packages/native-config/scripts/build.mjs@@ -0,0 +1,44 @@+#!/usr/bin/env node++import { spawnSync } from 'node:child_process';+import { createRequire } from 'node:module';+import { dirname, join } from 'node:path';+import { pathToFileURL } from 'node:url';++const LINUX_GNU_TARGETS = {+ arm64: 'aarch64-unknown-linux-gnu',+ x64: 'x86_64-unknown-linux-gnu',+};++export function resolveBuildArgs({ platform, arch, release }) {+ const args = ['build', '--platform'];+ if (release) args.push('--release');++ if (platform !== 'linux') return args;++ const target = LINUX_GNU_TARGETS[arch];+ if (target == null) throw new Error(`Unsupported Linux architecture: ${arch}`);++ // Linux package builds run on newer CI hosts than the distributions we+ // support. napi-rs's pinned cross toolchain keeps the addon's glibc floor+ // independent of the host runner.+ args.push('--target', target, '--use-napi-cross');+ return args;+}++function run() {+ const require = createRequire(import.meta.url);+ const cliPath = join(dirname(require.resolve('@napi-rs/cli/package.json')), 'dist', 'cli.js');+ const args = resolveBuildArgs({+ platform: process.platform,+ arch: process.arch,+ release: process.argv.includes('--release'),+ });+ const result = spawnSync(process.execPath, [cliPath, ...args], { stdio: 'inherit' });++ if (result.error != null) throw result.error;+ if (result.signal != null) throw new Error(`napi build terminated by ${result.signal}`);+ process.exitCode = result.status ?? 1;+}++if (process.argv[1] != null && import.meta.url === pathToFileURL(process.argv[1]).href) run();diff --git a/packages/native-config/scripts/build.test.mjs b/packages/native-config/scripts/build.test.mjsnew file mode 100644index 000000000..4daeee08b--- /dev/null+++ b/packages/native-config/scripts/build.test.mjs@@ -0,0 +1,46 @@+import assert from 'node:assert/strict';+import { describe, test } from 'node:test';+import { resolveBuildArgs } from './build.mjs';++// This package has no Vitest dependency, so the plain-JS harness uses Node's built-in runner.+describe('resolveBuildArgs', () => {+ test('uses the napi cross toolchain for Linux x64 release builds', () => {+ assert.deepEqual(resolveBuildArgs({ platform: 'linux', arch: 'x64', release: true }), [+ 'build',+ '--platform',+ '--release',+ '--target',+ 'x86_64-unknown-linux-gnu',+ '--use-napi-cross',+ ]);+ });++ test('uses the napi cross toolchain for Linux arm64 debug builds', () => {+ assert.deepEqual(resolveBuildArgs({ platform: 'linux', arch: 'arm64', release: false }), [+ 'build',+ '--platform',+ '--target',+ 'aarch64-unknown-linux-gnu',+ '--use-napi-cross',+ ]);+ });++ test('keeps the existing native build on macOS and Windows', () => {+ assert.deepEqual(resolveBuildArgs({ platform: 'darwin', arch: 'arm64', release: true }), [+ 'build',+ '--platform',+ '--release',+ ]);+ assert.deepEqual(resolveBuildArgs({ platform: 'win32', arch: 'x64', release: false }), [+ 'build',+ '--platform',+ ]);+ });++ test('fails explicitly for an unsupported Linux architecture', () => {+ assert.throws(+ () => resolveBuildArgs({ platform: 'linux', arch: 'riscv64', release: true }),+ /Unsupported Linux architecture: riscv64/,+ );+ });+});diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex e874d7dad..1c33eea5a 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -1182,8 +1182,8 @@ importers:version: 8.0.8(@types/[email protected])([email protected])([email protected])([email protected])([email protected])optionalDependencies:node-pty:- specifier: 1.1.0- version: 1.1.0+ specifier: 1.2.0-beta.15+ version: 1.2.0-beta.15packages/native-config:devDependencies:@@ -9661,8 +9661,8 @@ packages:engines: {node: '>=16.0.0'}hasBin: true- resolution: {integrity: sha512-20JqtutY6JPXTUnL0ij1uad7Qe1baT46lyolh2sSENDd4sTzKZ4nmAFkeAARDKwmlLjPx6XKRlwRUxwjOy+lUg==}+ resolution: {integrity: sha512-vORSzHXi4Ofl7HemVWpuudLqCPdaQb4LfpRCUpE5HPxhp4JYscl8zZwxh11p26v2wvW24WMwnMfLjhRLixrfxA==}resolution: {integrity: sha512-wRNIrw4DmVLKQlbgOMdkMx27Wrpzes2hh5Jtbi2bjPd+4wJstWIqP5A+lscnqbm0xxmT5Bpg8Lec5ItEBwx6BQ==}@@ -20849,7 +20849,7 @@ snapshots:node-gyp-build: 4.8.4optional: truedependencies:node-addon-api: 7.1.1optional: truediff --git a/pnpm-workspace.yaml b/pnpm-workspace.yamlindex d346677e9..58f1a470b 100644--- a/pnpm-workspace.yaml+++ b/pnpm-workspace.yaml@@ -20,10 +20,10 @@ minimumReleaseAgeExclude:# Dependency build scripts are blocked by default under pnpm; only these run.# electron downloads its platform binary in a postinstall. The napi native addon# (@inkeep/open-knowledge-native-config) builds via its own turbo `napi build`-# task, not a dependency install script, so it needs no entry here. node-pty ships-# prebuilds for darwin + win32 only — no Linux prebuild — so on Linux its install-# script must run to compile pty.node from source, or the Node-runtime pty tests-# can't load the native module (darwin/win32 resolve the shipped prebuild, no build).+# task, not a dependency install script, so it needs no entry here. node-pty+# publishes N-API prebuilds for the supported desktop platforms; its install+# script remains allowlisted as a source-build fallback when no matching+# prebuild is present.onlyBuiltDependencies:- electron- node-pty