Skip to content

Beautiful, AI-native markdown IDE and LLM wiki

feat(open-knowledge): docked terminal panel with in-app shell (#1895)

serafin-garciabb5380fa3bd2
diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.md
index 020906ae3..e618c7262 100644
--- a/THIRD_PARTY_NOTICES.md
+++ b/THIRD_PARTY_NOTICES.md
@@ -2569,6 +2569,31 @@ Homepage: https://github.com/vimeo/player.js
Copyright (c) 2016 [Vimeo](https://vimeo.com)
+### `@xterm/[email protected]`
+Homepage: https://github.com/xtermjs/xterm.js/tree/master/addons/addon-fit
+
+Copyright (c) 2019, The xterm.js authors (https://github.com/xtermjs/xterm.js)
+
+### `@xterm/[email protected]`
+Homepage: https://github.com/xtermjs/xterm.js/tree/master/addons/addon-unicode11
+
+Copyright (c) 2019, The xterm.js authors (https://github.com/xtermjs/xterm.js)
+
+### `@xterm/[email protected]`
+Homepage: https://github.com/xtermjs/xterm.js/tree/master/addons/addon-web-links
+
+Copyright (c) 2017, The xterm.js authors (https://github.com/xtermjs/xterm.js)
+
+### `@xterm/[email protected]`
+Homepage: https://github.com/xtermjs/xterm.js/tree/master/addons/addon-webgl
+
+Copyright (c) 2018, The xterm.js authors (https://github.com/xtermjs/xterm.js)
+
+### `@xterm/[email protected]`
+Homepage: https://github.com/xtermjs/xterm.js
+
+Copyright (c) 2017-2019, The xterm.js authors (https://github.com/xtermjs/xterm.js) Copyright (c) 2014-2016, SourceLair Private Company (https://www.sourcelair.com) Copyright (c) 2012-2013, Christopher Jeffrey (https://github.com/chjj/)
+
Homepage: https://github.com/jshttp/accepts
@@ -4390,6 +4415,13 @@ Homepage: https://github.com/prebuild/node-gyp-build
Copyright (c) 2017 Mathias Buus
+Homepage: https://github.com/microsoft/node-pty
+
+Copyright (c) 2012-2015, Christopher Jeffrey (https://github.com/chjj/)
+Copyright (c) 2016, Daniel Imms (http://www.growingwiththeweb.com)
+Copyright (c) 2018 - present Microsoft Corporation
+
Homepage: https://github.com/chicoxyzzy/node-releases
diff --git a/bun.lock b/bun.lock
index d506e9be9..6a69517e2 100644
--- a/bun.lock
+++ b/bun.lock
@@ -107,6 +107,11 @@
"@tiptap/y-tiptap": "^3.0.3",
"@u-wave/react-vimeo": "^0.9.12",
"@uiw/codemirror-theme-basic": "^4.25.9",
+ "@xterm/addon-fit": "0.11.0",
+ "@xterm/addon-unicode11": "0.9.0",
+ "@xterm/addon-web-links": "0.12.0",
+ "@xterm/addon-webgl": "0.19.0",
+ "@xterm/xterm": "6.0.0",
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
"cmdk": "^1.1.1",
@@ -316,6 +321,7 @@
"@inkeep/open-knowledge-server": "workspace:*",
"@napi-rs/keyring": "^1.3.0",
"electron-updater": "6.8.4",
+ "node-pty": "1.1.0",
"pino": "^10.3.1",
"semver": "^7.7.4",
"yaml": "^2.8.3",
@@ -1809,6 +1815,16 @@
"@xmldom/xmldom": ["@xmldom/[email protected]", "", {}, "sha512-KRYzxepc14G/CEpEGc3Yn+JKaAeT63smlDr+vjB8jRfgTBBI9wRj/nkQEO+ucV8p8I9bfKLWp37uHgFrbntPvw=="],
+ "@xterm/addon-fit": ["@xterm/[email protected]", "", {}, "sha512-jYcgT6xtVYhnhgxh3QgYDnnNMYTcf8ElbxxFzX0IZo+vabQqSPAjC3c1wJrKB5E19VwQei89QCiZZP86DCPF7g=="],
+
+ "@xterm/addon-unicode11": ["@xterm/[email protected]", "", {}, "sha512-FxDnYcyuXhNl+XSqGZL/t0U9eiNb/q3EWT5rYkQT/zuig8Gz/VagnQANKHdDWFM2lTMk9ly0EFQxxxtZUoRetw=="],
+
+ "@xterm/addon-web-links": ["@xterm/[email protected]", "", {}, "sha512-4Smom3RPyVp7ZMYOYDoC/9eGJJJqYhnPLGGqJ6wOBfB8VxPViJNSKdgRYb8NpaM6YSelEKbA2SStD7lGyqaobw=="],
+
+ "@xterm/addon-webgl": ["@xterm/[email protected]", "", {}, "sha512-b3fMOsyLVuCeNJWxolACEUED0vm7qC0cy4wRvf3oURSzDTYVQiGPhTnhWZwIHdvC48Y+oLhvYXnY4XDXPoJo6A=="],
+
+ "@xterm/xterm": ["@xterm/[email protected]", "", {}, "sha512-TQwDdQGtwwDt+2cgKDLn0IRaSxYu1tSUjgKarSDkUM0ZNiSRXFpjxEsvc/Zgc5kq5omJ+V0a8/kIM2WD3sMOYg=="],
+
"@zag-js/anatomy": ["@zag-js/[email protected]", "", {}, "sha512-wBQVpl8TC9O5AjeJrnmNdJWEUYorTi7iklOcySeXIeaz6D7Y0YY0YbEOSFNsRTpn/NQHwkPejf3i5qkKavNHXw=="],
"@zag-js/collection": ["@zag-js/[email protected]", "", { "dependencies": { "@zag-js/utils": "1.41.1" } }, "sha512-6Kun1lmkp3k+JHkcwCscrKNmPLAZNIeswpGvbbd3T5Qj7WX7b5A2Z926ZHUMicrXQinAtT90B9zrTurDdJZ4EQ=="],
@@ -3227,6 +3243,8 @@
"node-liblzma": ["[email protected]", "", { "dependencies": { "node-addon-api": "^8.5.0", "node-gyp-build": "^4.8.4" }, "bin": { "nxz": "lib/cli/nxz.js" } }, "sha512-s0KzNOWwOJJgPG6wxg6cKohnAl9Wk/oW1KrQaVzJBjQwVcUGPQCzpR46Ximygjqj/3KhOrtJXnYMp/xYAXp75g=="],
+ "node-pty": ["[email protected]", "", { "dependencies": { "node-addon-api": "^7.1.0" } }, "sha512-20JqtutY6JPXTUnL0ij1uad7Qe1baT46lyolh2sSENDd4sTzKZ4nmAFkeAARDKwmlLjPx6XKRlwRUxwjOy+lUg=="],
+
"node-releases": ["[email protected]", "", {}, "sha512-1h5gKZCF+pO/o3Iqt5Jp7wc9rH3eJJ0+nh/CIoiRwjRxde/hAHyLPXYN4V3CqKAbiZPSeJFSWHmJsbkicta0Eg=="],
"nopt": ["[email protected]", "", { "dependencies": { "abbrev": "^3.0.0" }, "bin": { "nopt": "bin/nopt.js" } }, "sha512-ieGu42u/Qsa4TFktmaKEwM6MQH0pOWnaB3htzh0JRtx84+Mebc0cbZYN5bC+6WTZ4+77xrL9Pn5m7CV6VIkV7A=="],
diff --git a/knip.config.ts b/knip.config.ts
index e9378d5c3..ff401a923 100644
--- a/knip.config.ts
+++ b/knip.config.ts
@@ -115,12 +115,14 @@ export default {
'src/main/index.ts',
'src/preload/index.ts',
'src/utility/server-entry.ts',
+ 'src/utility/pty-host.ts',
'src/**/*.test.ts',
'electron.vite.config.ts',
'scripts/*.mjs',
'tests/**/*.test.ts',
'tests/**/*.test.mjs',
],
+ ignoreUnresolved: [/utility\/pty-host\.js$/],
project: 'src/**',
},
},
diff --git a/packages/app/package.json b/packages/app/package.json
index 0ab45586b..6b42cf1a8 100644
--- a/packages/app/package.json
+++ b/packages/app/package.json
@@ -43,14 +43,14 @@
{
"name": "main app bundle (gzipped)",
"path": "dist/assets/index-*.js",
- "limit": "407 kB",
+ "limit": "415 kB",
"gzip": true,
"running": false
},
{
"name": "all JS chunks combined (gzipped)",
"path": "dist/assets/*.js",
- "limit": "2.85 MB",
+ "limit": "3 MB",
"gzip": true,
"running": false
},
@@ -115,6 +115,11 @@
"@tiptap/y-tiptap": "^3.0.3",
"@u-wave/react-vimeo": "^0.9.12",
"@uiw/codemirror-theme-basic": "^4.25.9",
+ "@xterm/addon-fit": "0.11.0",
+ "@xterm/addon-unicode11": "0.9.0",
+ "@xterm/addon-web-links": "0.12.0",
+ "@xterm/addon-webgl": "0.19.0",
+ "@xterm/xterm": "6.0.0",
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
"cmdk": "^1.1.1",
diff --git a/packages/app/src/App.dom.test.tsx b/packages/app/src/App.dom.test.tsx
index b28407949..0c68ae9fd 100644
--- a/packages/app/src/App.dom.test.tsx
+++ b/packages/app/src/App.dom.test.tsx
@@ -91,6 +91,10 @@ mock.module('@/lib/config-provider', () => ({
),
}));
+mock.module('@/lib/config-context', () => ({
+ useConfigContext: () => ({ merged: null }),
+}));
+
mock.module('@/lib/api-config', () => ({
fetchApiConfig: (...args: Parameters<typeof fetchApiConfigMock>) => fetchApiConfigMock(...args),
}));
diff --git a/packages/app/src/App.tsx b/packages/app/src/App.tsx
index eb373bc9f..55d219ddf 100644
--- a/packages/app/src/App.tsx
+++ b/packages/app/src/App.tsx
@@ -6,6 +6,12 @@ import { CreateProjectMenuTrigger } from '@/components/CreateProjectMenuTrigger'
import { EditorPane } from '@/components/EditorPane';
import { FileSidebar } from '@/components/FileSidebar';
import { defaultInitialDir } from '@/components/file-tree-utils';
+import {
+ type TerminalLaunchContextValue,
+ TerminalLaunchProvider,
+} from '@/components/handoff/TerminalLaunchContext';
+import { requestTerminalLaunch } from '@/components/handoff/terminal-launch-events';
+import { selectScopedPrompt } from '@/components/handoff/useHandoffDispatch';
import { InstallInClaudeDesktopDialog } from '@/components/InstallInClaudeDesktopDialog';
import { McpConsentDialog } from '@/components/McpConsentDialog';
import { isNewItemShortcut, NewItemDialog } from '@/components/NewItemDialog';
@@ -24,6 +30,7 @@ import {
useDocumentTransition,
} from '@/editor/DocumentContext';
import { fetchApiConfig } from '@/lib/api-config';
+import { useConfigContext } from '@/lib/config-context';
import { ConfigProvider } from '@/lib/config-provider';
import { assetPathFromHash, docNameFromHash, isContentRootHash } from '@/lib/doc-hash';
import { mark, ProfilerBoundary } from '@/lib/perf';
@@ -316,6 +323,16 @@ function AppBody() {
const isElectronHost = typeof window !== 'undefined' && window.okDesktop != null;
const [commandPaletteOpen, setCommandPaletteOpen] = useState(false);
const singleFile = useSingleFileMode();
+ const { merged } = useConfigContext();
+ const autoOpen = merged?.appearance?.preview?.autoOpen ?? true;
+
+ const terminalLaunch: TerminalLaunchContextValue | null = desktopBridge
+ ? {
+ launchInTerminal: (input) => {
+ requestTerminalLaunch(selectScopedPrompt(input, 'claude-code', autoOpen));
+ },
+ }
+ : null;
return (
<>
@@ -363,14 +380,20 @@ function AppBody() {
className="pointer-events-none fixed inset-x-0 top-0 z-50 h-2 [-webkit-app-region:drag]"
/>
)}
- <SidebarProvider className="h-screen overflow-hidden">
- {/* No-project single-file mode drops the file sidebar (file tree +
- project switcher); the editor inset takes the full width. */}
- {!singleFile && <FileSidebar onOpenSearch={() => setCommandPaletteOpen(true)} />}
- <SidebarInset className="overflow-hidden h-[calc(100vh-var(--layout-inset-offset))]">
- <EditorPane onOpenSearch={() => setCommandPaletteOpen(true)} />
- </SidebarInset>
- </SidebarProvider>
+ {/* The "Open in terminal" entry point spans both the FileSidebar
+ menus and the EditorHeader/EditorPane, which are siblings here —
+ so the provider wraps both. Its value is desktop-gated; the docked
+ terminal that consumes the launch lives in EditorPane. */}
+ <TerminalLaunchProvider value={terminalLaunch}>
+ <SidebarProvider className="h-screen overflow-hidden">
+ {/* No-project single-file mode drops the file sidebar (file tree +
+ project switcher); the editor inset takes the full width. */}
+ {!singleFile && <FileSidebar onOpenSearch={() => setCommandPaletteOpen(true)} />}
+ <SidebarInset className="overflow-hidden h-[calc(100vh-var(--layout-inset-offset))]">
+ <EditorPane onOpenSearch={() => setCommandPaletteOpen(true)} />
+ </SidebarInset>
+ </SidebarProvider>
+ </TerminalLaunchProvider>
</PageListProvider>
</>
);
diff --git a/packages/app/src/components/ClaudeReadinessBanner.dom.test.tsx b/packages/app/src/components/ClaudeReadinessBanner.dom.test.tsx
new file mode 100644
index 000000000..daa5874b8
--- /dev/null
+++ b/packages/app/src/components/ClaudeReadinessBanner.dom.test.tsx
@@ -0,0 +1,128 @@
+import { afterEach, beforeEach, describe, expect, mock, test } from 'bun:test';
+import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
+import type { ClaudeReadiness, OkDesktopBridge } from '@/lib/desktop-bridge-types';
+
+const toastErrors: string[] = [];
+mock.module('sonner', () => ({
+ toast: { error: (message: string) => toastErrors.push(message) },
+}));
+
+const { ClaudeReadinessBanner } = await import('./ClaudeReadinessBanner');
+
+function makeBridge(rewireResult: ClaudeReadiness = { claude: 'present', mcp: 'wired' }) {
+ const openExternal = mock(async (_url: string) => {});
+ const rewireClaudeMcp = mock(async () => rewireResult);
+ const bridge = {
+ shell: { openExternal },
+ terminal: { rewireClaudeMcp },
+ } as unknown as OkDesktopBridge;
+ return { bridge, openExternal, rewireClaudeMcp };
+}
+
+beforeEach(() => {
+ toastErrors.length = 0;
+});
+afterEach(() => cleanup());
+
+describe('ClaudeReadinessBanner', () => {
+ test('not-found: offers a help affordance that opens the Claude Code docs', () => {
+ const { bridge, openExternal, rewireClaudeMcp } = makeBridge();
+ render(
+ <ClaudeReadinessBanner
+ readiness={{ claude: 'not-found', mcp: 'needs-rewire' }}
+ bridge={bridge}
+ onDismiss={() => {}}
+ />,
+ );
+
+ expect(screen.getByText(/isn't installed or on your PATH/)).toBeTruthy();
+ fireEvent.click(screen.getByRole('button', { name: 'Get Claude Code' }));
+ expect(openExternal).toHaveBeenCalledTimes(1);
+ expect(openExternal.mock.calls[0]?.[0]).toContain('claude-code');
+ expect(rewireClaudeMcp).not.toHaveBeenCalled();
+ expect(screen.queryByRole('button', { name: 'Connect tools' })).toBeNull();
+ });
+
+ test('present + needs-rewire: offers a re-wire affordance and dismisses on success', async () => {
+ const onDismiss = mock(() => {});
+ const { bridge, rewireClaudeMcp, openExternal } = makeBridge();
+ render(
+ <ClaudeReadinessBanner
+ readiness={{ claude: 'present', mcp: 'needs-rewire' }}
+ bridge={bridge}
+ onDismiss={onDismiss}
+ />,
+ );
+
+ expect(screen.getByText(/aren't connected to it yet/)).toBeTruthy();
+ fireEvent.click(screen.getByRole('button', { name: 'Connect tools' }));
+ expect(rewireClaudeMcp).toHaveBeenCalledTimes(1);
+ await waitFor(() => expect(onDismiss).toHaveBeenCalledTimes(1));
+ expect(openExternal).not.toHaveBeenCalled();
+ });
+
+ test('present + needs-rewire: a rewire that reports an error surfaces a toast and keeps the banner', async () => {
+ const onDismiss = mock(() => {});
+ const { bridge } = makeBridge({
+ claude: 'present',
+ mcp: 'needs-rewire',
+ rewireError: 'consent dialog failed to arm',
+ });
+ render(
+ <ClaudeReadinessBanner
+ readiness={{ claude: 'present', mcp: 'needs-rewire' }}
+ bridge={bridge}
+ onDismiss={onDismiss}
+ />,
+ );
+
+ await act(async () => {
+ fireEvent.click(screen.getByRole('button', { name: 'Connect tools' }));
+ await Promise.resolve();
+ });
+ await waitFor(() => expect(toastErrors.length).toBe(1));
+ expect(onDismiss).not.toHaveBeenCalled();
+ });
+
+ test('present + wired: renders nothing', () => {
+ const { bridge } = makeBridge();
+ const { container } = render(
+ <ClaudeReadinessBanner
+ readiness={{ claude: 'present', mcp: 'wired' }}
+ bridge={bridge}
+ onDismiss={() => {}}
+ />,
+ );
+ expect(container.firstChild).toBeNull();
+ expect(screen.queryByRole('status')).toBeNull();
+ });
+
+ test('unknown probe verdict renders nothing (no false "not installed")', () => {
+ const { bridge } = makeBridge();
+ const { container } = render(
+ <ClaudeReadinessBanner
+ readiness={{ claude: 'unknown', mcp: 'needs-rewire' }}
+ bridge={bridge}
+ onDismiss={() => {}}
+ />,
+ );
+ expect(container.firstChild).toBeNull();
+ });
+
+ test('exposes a status live region and an accessible dismiss control', () => {
+ const onDismiss = mock(() => {});
+ const { bridge } = makeBridge();
+ render(
+ <ClaudeReadinessBanner
+ readiness={{ claude: 'not-found', mcp: 'needs-rewire' }}
+ bridge={bridge}
+ onDismiss={onDismiss}
+ />,
+ );
+
+ expect(screen.getByRole('status')).toBeTruthy();
+ const dismiss = screen.getByRole('button', { name: 'Dismiss' });
+ fireEvent.click(dismiss);
+ expect(onDismiss).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/packages/app/src/components/ClaudeReadinessBanner.tsx b/packages/app/src/components/ClaudeReadinessBanner.tsx
new file mode 100644
index 000000000..a81b4a21c
--- /dev/null
+++ b/packages/app/src/components/ClaudeReadinessBanner.tsx
@@ -0,0 +1,80 @@
+import { useLingui } from '@lingui/react/macro';
+import { X } from 'lucide-react';
+import { toast } from 'sonner';
+import { Button } from '@/components/ui/button';
+import type { ClaudeReadiness, OkDesktopBridge } from '@/lib/desktop-bridge-types';
+
+const CLAUDE_CODE_DOCS_URL = 'https://docs.claude.com/en/docs/claude-code';
+
+interface ClaudeReadinessBannerProps {
+ readonly readiness: ClaudeReadiness;
+ readonly bridge: OkDesktopBridge;
+ readonly onDismiss: () => void;
+}
+
+type BannerKind = 'claude-missing' | 'mcp-needs-rewire';
+
+function bannerKind(readiness: ClaudeReadiness): BannerKind | null {
+ if (readiness.claude === 'not-found') return 'claude-missing';
+ if (readiness.claude === 'present' && readiness.mcp === 'needs-rewire') {
+ return 'mcp-needs-rewire';
+ }
+ return null;
+}
+
+export function ClaudeReadinessBanner({
+ readiness,
+ bridge,
+ onDismiss,
+}: ClaudeReadinessBannerProps) {
+ const { t } = useLingui();
+ const kind = bannerKind(readiness);
+ if (kind === null) return null;
+
+ const isClaudeMissing = kind === 'claude-missing';
+ const message = isClaudeMissing
+ ? t`Claude Code (claude) isn't installed or on your PATH.`
+ : t`Claude Code is installed, but Open Knowledge tools aren't connected to it yet.`;
+ const actionLabel = isClaudeMissing ? t`Get Claude Code` : t`Connect tools`;
+
+ function handleAction() {
+ if (isClaudeMissing) {
+ void bridge.shell.openExternal(CLAUDE_CODE_DOCS_URL);
+ return;
+ }
+ bridge.terminal
+ .rewireClaudeMcp()
+ .then((result) => {
+ if (result.rewireError != null) {
+ toast.error(t`Couldn't connect Open Knowledge tools to Claude Code. Please try again.`);
+ return;
+ }
+ onDismiss();
+ })
+ .catch((err) => {
+ console.warn('[terminal] rewireClaudeMcp failed:', err);
+ toast.error(t`Couldn't connect Open Knowledge tools to Claude Code. Please try again.`);
+ });
+ }
+
+ return (
+ <div
+ role="status"
+ className="flex shrink-0 items-center gap-3 border-[#3c3c3c] border-b bg-[#252526] px-3 py-2 text-[#d4d4d4] text-xs"
+ >
+ <p className="min-w-0 flex-1">{message}</p>
+ <Button size="sm" variant="secondary" className="shrink-0" onClick={handleAction}>
+ {actionLabel}
+ </Button>
+ <Button
+ size="icon"
+ variant="ghost"
+ aria-label={t`Dismiss`}
+ className="size-6 shrink-0"
+ onClick={onDismiss}
+ >
+ <X aria-hidden="true" className="size-4" />
+ </Button>
+ </div>
+ );
+}
diff --git a/packages/app/src/components/EditorArea.tsx b/packages/app/src/components/EditorArea.tsx
index d9bddf51e..2c7f57f2f 100644
--- a/packages/app/src/components/EditorArea.tsx
+++ b/packages/app/src/components/EditorArea.tsx
@@ -31,6 +31,7 @@ import { syncPromiseHasResolved } from '@/editor/sync-promise';
import { useDocumentStats } from '@/hooks/use-document-stats';
import { useLifecycleStatus } from '@/hooks/use-lifecycle-status';
import { useSelectionStats } from '@/hooks/use-selection-stats';
+import type { OkDesktopBridge } from '@/lib/desktop-bridge-types';
import { docNameFromHash, hashFromDocName } from '@/lib/doc-hash';
import { getInitialDocPanelWidth, writeDocPanelWidth } from '@/lib/doc-panel-width-store';
import { matchesKeyboardShortcut } from '@/lib/keyboard-shortcuts';
@@ -42,9 +43,10 @@ import { cn } from '@/lib/utils';
import { useSyncStatus } from '@/presence/use-sync-status';
import { EditorActivityPool } from './EditorActivityPool';
import { EditorFooter } from './EditorFooter';
-import type { EditorMode } from './EditorPane';
+import type { EditorMode, TerminalLaunchIntent } from './EditorPane';
import { EditorToolbar } from './EditorToolbar';
import { shouldPaintOverlay } from './editor-area-overlay';
+import { TerminalDock } from './TerminalDock';
const LazyActivityModeContent = lazy(async () => {
const mod = await import('@/components/ActivityModeContent');
@@ -56,6 +58,12 @@ interface EditorAreaProps {
onModeChange: (mode: EditorMode) => void;
activeTab: PanelTab;
onActiveTabChange: (tab: PanelTab) => void;
+ terminalBridge?: OkDesktopBridge | null;
+ terminalVisible?: boolean;
+ onTerminalVisibleChange?: (visible: boolean) => void;
+ /** "Open in terminal" launch intent — carried to the terminal session, which
+ * writes the `claude` launch once per nonce. Null until a UI click. */
+ terminalLaunch?: TerminalLaunchIntent | null;
}
export function EditorArea(props: EditorAreaProps) {
@@ -92,6 +100,10 @@ function EditorAreaInner({
onModeChange,
activeTab,
onActiveTabChange,
+ terminalBridge,
+ terminalVisible = false,
+ onTerminalVisibleChange,
+ terminalLaunch = null,
}: EditorAreaProps) {
const { t } = useLingui();
const {
@@ -460,6 +472,20 @@ function EditorAreaInner({
</div>
);
+ const editorColumn =
+ terminalBridge != null ? (
+ <TerminalDock
+ bridge={terminalBridge}
+ visible={terminalVisible}
+ onVisibleChange={onTerminalVisibleChange ?? (() => {})}
+ launch={terminalLaunch}
+ >
+ {editorContent}
+ </TerminalDock>
+ ) : (
+ editorContent
+ );
+
return (
<div className="flex min-h-0 flex-1" ref={setGroupContainerEl}>
<ResizablePanelGroup
@@ -475,7 +501,7 @@ function EditorAreaInner({
: 'transition-[flex-grow] duration-200 ease-out motion-reduce:transition-none motion-reduce:duration-0'
}
>
- {editorContent}
+ {editorColumn}
</ResizablePanel>
<ResizableHandle
withHandle
diff --git a/packages/app/src/components/EditorPane.dom.test.tsx b/packages/app/src/components/EditorPane.dom.test.tsx
index dd388f56a..0b7ce2b6f 100644
--- a/packages/app/src/components/EditorPane.dom.test.tsx
+++ b/packages/app/src/components/EditorPane.dom.test.tsx
@@ -1,6 +1,7 @@
import { afterEach, describe, expect, mock, test } from 'bun:test';
-import { cleanup, render, screen } from '@testing-library/react';
+import { act, cleanup, render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
+import { isMacOS } from '@tiptap/core';
import type { ReactNode } from 'react';
mock.module('@lingui/react/macro', () => ({
@@ -43,7 +44,25 @@ mock.module('./EditorHeader', () => ({
}));
mock.module('./EditorArea', () => ({
- EditorArea: () => <div data-testid="editor-area" />,
+ EditorArea: ({
+ terminalBridge,
+ terminalVisible,
+ }: {
+ terminalBridge?: unknown;
+ terminalVisible?: boolean;
+ }) => (
+ <div data-testid="editor-area">
+ {terminalBridge != null ? (
+ <div data-testid="terminal-dock" data-visible={String(terminalVisible)} />
+ ) : null}
+ </div>
+ ),
+}));
+
+const terminalOpenedCalls: true[] = [];
+mock.module('@/lib/terminal-telemetry', () => ({
+ recordTerminalOpened: () => terminalOpenedCalls.push(true),
+ recordShellConsentGranted: () => undefined,
}));
mock.module('./AuthModal', () => ({
@@ -126,3 +145,123 @@ describe('EditorPane auto-sync onboarding gate', () => {
expect(screen.getByTestId('auto-sync-onboarding').getAttribute('data-open')).toBe('false');
});
});
+
+function makeOkDesktopStub() {
+ const menuHandlers: Array<(action: string) => void> = [];
+ const viewMenuPushes: Array<{ terminalVisible?: boolean }> = [];
+ return {
+ viewMenuPushes,
+ dispatchMenuAction(action: string) {
+ for (const cb of menuHandlers) cb(action);
+ },
+ stub: {
+ onMenuAction(cb: (action: string) => void) {
+ menuHandlers.push(cb);
+ return () => {
+ const index = menuHandlers.indexOf(cb);
+ if (index >= 0) menuHandlers.splice(index, 1);
+ };
+ },
+ editor: {
+ notifyViewMenuStateChanged(state: { terminalVisible?: boolean }) {
+ viewMenuPushes.push(state);
+ },
+ },
+ },
+ };
+}
+
+describe('EditorPane terminal dock wiring', () => {
+ afterEach(() => {
+ cleanup();
+ delete (window as { okDesktop?: unknown }).okDesktop;
+ terminalOpenedCalls.length = 0;
+ });
+
+ test('web host renders the editor chrome without a terminal dock', async () => {
+ await renderEditorPane();
+
+ expect(screen.queryByTestId('terminal-dock')).toBeNull();
+ expect(screen.getByTestId('editor-header')).toBeTruthy();
+ expect(screen.getByTestId('editor-area')).toBeTruthy();
+ });
+
+ test('desktop host renders the editor chrome with the terminal dock under the editor area', async () => {
+ (window as { okDesktop?: unknown }).okDesktop = makeOkDesktopStub().stub;
+ await renderEditorPane();
+
+ expect(screen.getByTestId('editor-header')).toBeTruthy();
+ const area = screen.getByTestId('editor-area');
+ expect(area.querySelector('[data-testid="terminal-dock"]')).not.toBeNull();
+ });
+
+ test('desktop: toggle-terminal menu action flips dock visibility and pushes the view-menu state', async () => {
+ const desk = makeOkDesktopStub();
+ (window as { okDesktop?: unknown }).okDesktop = desk.stub;
+ await renderEditorPane();
+
+ expect(screen.getByTestId('terminal-dock').getAttribute('data-visible')).toBe('false');
+ expect(desk.viewMenuPushes.at(-1)).toEqual({ terminalVisible: false });
+
+ act(() => desk.dispatchMenuAction('toggle-terminal'));
+ expect(screen.getByTestId('terminal-dock').getAttribute('data-visible')).toBe('true');
+ expect(desk.viewMenuPushes.at(-1)).toEqual({ terminalVisible: true });
+
+ act(() => desk.dispatchMenuAction('toggle-terminal'));
+ expect(screen.getByTestId('terminal-dock').getAttribute('data-visible')).toBe('false');
+ expect(desk.viewMenuPushes.at(-1)).toEqual({ terminalVisible: false });
+ });
+
+ test('desktop: an unrelated menu action does not toggle the terminal', async () => {
+ const desk = makeOkDesktopStub();
+ (window as { okDesktop?: unknown }).okDesktop = desk.stub;
+ await renderEditorPane();
+
+ act(() => desk.dispatchMenuAction('toggle-doc-panel'));
+ expect(screen.getByTestId('terminal-dock').getAttribute('data-visible')).toBe('false');
+ });
+
+ test('desktop: each open records terminal-opened; mount (hidden) and close do not', async () => {
+ const desk = makeOkDesktopStub();
+ (window as { okDesktop?: unknown }).okDesktop = desk.stub;
+ await renderEditorPane();
+
+ expect(terminalOpenedCalls).toHaveLength(0);
+
+ act(() => desk.dispatchMenuAction('toggle-terminal')); // hidden → open
+ expect(terminalOpenedCalls).toHaveLength(1);
+
+ act(() => desk.dispatchMenuAction('toggle-terminal')); // open → hidden (no record)
+ expect(terminalOpenedCalls).toHaveLength(1);
+
+ act(() => desk.dispatchMenuAction('toggle-terminal')); // hidden → open again
+ expect(terminalOpenedCalls).toHaveLength(2);
+ });
+
+ test('web host: a Cmd/Ctrl+J keydown is intercepted (the toggle handler is wired)', async () => {
+ await renderEditorPane();
+
+ const init: KeyboardEventInit = { key: 'j', cancelable: true, bubbles: true };
+ if (isMacOS()) init.metaKey = true;
+ else init.ctrlKey = true;
+ const event = new KeyboardEvent('keydown', init);
+ window.dispatchEvent(event);
+
+ expect(event.defaultPrevented).toBe(true);
+ });
+
+ test('web host: an unrelated keydown is not intercepted', async () => {
+ await renderEditorPane();
+
+ const event = new KeyboardEvent('keydown', {
+ key: 'g',
+ metaKey: true,
+ ctrlKey: true,
+ cancelable: true,
+ bubbles: true,
+ });
+ window.dispatchEvent(event);
+
+ expect(event.defaultPrevented).toBe(false);
+ });
+});
diff --git a/packages/app/src/components/EditorPane.tsx b/packages/app/src/components/EditorPane.tsx
index 49e570b89..03048d5c1 100644
--- a/packages/app/src/components/EditorPane.tsx
+++ b/packages/app/src/components/EditorPane.tsx
@@ -9,6 +9,8 @@ import { type EditorModeValue, useEditorMode } from '@/editor/use-editor-mode';
import { useGitSyncStatus } from '@/hooks/use-git-sync-status';
import { useNoPushPermissionToast } from '@/hooks/use-no-push-permission-toast';
import { useConfigContext } from '@/lib/config-provider';
+import { matchesKeyboardShortcut } from '@/lib/keyboard-shortcuts';
+import { recordTerminalOpened } from '@/lib/terminal-telemetry';
import { useWorkspace } from '@/lib/use-workspace';
import { AuthModal } from './AuthModal';
import { AutoSyncOnboardingDialog } from './AutoSyncOnboardingDialog';
@@ -17,11 +19,17 @@ import { type PanelTab, TABS } from './DocPanel';
import { EditorArea } from './EditorArea';
import { EditorHeader } from './EditorHeader';
import { OpenInAgentMenuRequestProvider } from './handoff/OpenInAgentMenuRequestContext';
+import { subscribeToTerminalLaunchRequests } from './handoff/terminal-launch-events';
import {
buildSelectionOrDocHandoffInput,
type HandoffDispatchInput,
} from './handoff/useHandoffDispatch';
+export interface TerminalLaunchIntent {
+ readonly prompt: string;
+ readonly nonce: number;
+}
+
export type EditorMode = EditorModeValue;
interface EditorPaneProps {
@@ -40,6 +48,9 @@ export function EditorPane({ onOpenSearch }: EditorPaneProps = {}) {
const [openInAgentMenuInput, setOpenInAgentMenuInput] = useState<HandoffDispatchInput | null>(
null,
);
+ const desktopBridge = typeof window !== 'undefined' ? (window.okDesktop ?? null) : null;
+ const [terminalVisible, setTerminalVisible] = useState(false);
+ const [terminalLaunch, setTerminalLaunch] = useState<TerminalLaunchIntent | null>(null);
const syncStatus = useGitSyncStatus();
const { projectLocalConfig, projectLocalSynced } = useConfigContext();
@@ -67,6 +78,45 @@ export function EditorPane({ onOpenSearch }: EditorPaneProps = {}) {
return () => window.removeEventListener(RAW_MDX_NAV_EVENT, onRawMdxNav);
}, [activeDocName]);
+ useEffect(() => {
+ const bridge = window.okDesktop;
+ if (bridge == null) return;
+ return bridge.onMenuAction((action) => {
+ if (action === 'toggle-terminal') {
+ setTerminalVisible((visible) => !visible);
+ }
+ });
+ }, []);
+
+ useEffect(() => {
+ if (window.okDesktop != null) return;
+ function handleKeyDown(event: KeyboardEvent) {
+ if (matchesKeyboardShortcut(event, 'toggle-terminal-panel')) {
+ event.preventDefault();
+ setTerminalVisible((visible) => !visible);
+ }
+ }
+ window.addEventListener('keydown', handleKeyDown, { capture: true });
+ return () => window.removeEventListener('keydown', handleKeyDown, { capture: true });
+ }, []);
+
+ useEffect(() => {
+ return subscribeToTerminalLaunchRequests((prompt) => {
+ setTerminalVisible(true);
+ setTerminalLaunch((prev) => ({ prompt, nonce: (prev?.nonce ?? 0) + 1 }));
+ });
+ }, []);
+
+ useEffect(() => {
+ if (window.okDesktop == null) return;
+ window.okDesktop.editor.notifyViewMenuStateChanged({ terminalVisible });
+ }, [terminalVisible]);
+
+ useEffect(() => {
+ if (window.okDesktop == null) return;
+ if (terminalVisible) recordTerminalOpened();
+ }, [terminalVisible]);
+
useNoPushPermissionToast(syncStatus?.pausedReason);
function handleModeChange(mode: EditorModeValue) {
@@ -114,11 +164,19 @@ export function EditorPane({ onOpenSearch }: EditorPaneProps = {}) {
openInAgentMenuInput={openInAgentMenuInput}
onOpenInAgentMenuOpenChange={handleOpenInAgentMenuOpenChange}
/>
+ {/* The terminal docks under the editor/file column only — EditorArea
+ nests the vertical split inside its horizontal editor↔doc-panel
+ split so the doc panel stays full-height beside the terminal. The
+ ⌘J/menu/telemetry state stays owned here and is threaded down. */}
<EditorArea
editorMode={editorMode}
onModeChange={handleModeChange}
activeTab={activeTab}
onActiveTabChange={setActiveTab}
+ terminalBridge={desktopBridge}
+ terminalVisible={terminalVisible}
+ onTerminalVisibleChange={setTerminalVisible}
+ terminalLaunch={terminalLaunch}
/>
</OpenInAgentMenuRequestProvider>
<AuthModal
diff --git a/packages/app/src/components/FileSidebar.dom.test.tsx b/packages/app/src/components/FileSidebar.dom.test.tsx
index c16e3fe60..4b4d4a117 100644
--- a/packages/app/src/components/FileSidebar.dom.test.tsx
+++ b/packages/app/src/components/FileSidebar.dom.test.tsx
@@ -95,7 +95,6 @@ const treeCalls = {
uploadFiles: mock((_parentDir: string) => {}),
};
const projectLocalPatch = mock((_patch: unknown) => projectPatchResult);
-const dispatchOpenInTerminalMock = mock((_bridge: unknown, _path: string) => Promise.resolve());
const showItemInFolderMock = mock((_path: string) => Promise.resolve());
const notifyViewMenuStateChangedMock = mock((_snapshot: unknown) => {});
const onOpenSearch = mock(() => {});
@@ -276,6 +275,7 @@ mock.module('@/components/ui/dropdown-menu', () => ({
<div data-testid="tree-options-menu">{children}</div>
),
DropdownMenuItem: Button,
+ DropdownMenuSeparator: () => null,
DropdownMenuTrigger: PassThrough,
}));
@@ -363,10 +363,6 @@ mock.module('@/lib/config-provider', () => ({
}),
}));
-mock.module('@/lib/dispatch-open-in-terminal', () => ({
- dispatchOpenInTerminal: dispatchOpenInTerminalMock,
-}));
-
mock.module('@/lib/use-workspace', () => ({
useWorkspace: () => workspace,
}));
@@ -408,7 +404,6 @@ describe('FileSidebar runtime behavior', () => {
treeCalls.startCreatingFromTemplate,
treeCalls.uploadFiles,
projectLocalPatch,
- dispatchOpenInTerminalMock,
showItemInFolderMock,
notifyViewMenuStateChangedMock,
onOpenSearch,
@@ -528,7 +523,6 @@ describe('FileSidebar runtime behavior', () => {
'empty-space-menu-upload-file',
'empty-space-menu-reveal-in-finder',
'open-in-agent-empty-space-submenu',
- 'empty-space-menu-open-in-terminal',
'empty-space-menu-copy-full-path',
'empty-space-menu-show-hidden-files',
'empty-space-menu-show-all-files',
@@ -554,12 +548,6 @@ describe('FileSidebar runtime behavior', () => {
fireEvent.click(screen.getByTestId('empty-space-menu-reveal-in-finder'));
expect(showItemInFolderMock).toHaveBeenCalledWith('/tmp/open-knowledge');
- fireEvent.click(screen.getByTestId('empty-space-menu-open-in-terminal'));
- expect(dispatchOpenInTerminalMock).toHaveBeenCalledWith(
- window.okDesktop,
- '/tmp/open-knowledge',
- );
-
fireEvent.click(screen.getByTestId('empty-space-menu-copy-full-path'));
await waitFor(() =>
expect(navigator.clipboard.writeText).toHaveBeenCalledWith('/tmp/open-knowledge'),
diff --git a/packages/app/src/components/FileSidebar.menu-action.dom.test.tsx b/packages/app/src/components/FileSidebar.menu-action.dom.test.tsx
index b19ea026f..d81b1b4e0 100644
--- a/packages/app/src/components/FileSidebar.menu-action.dom.test.tsx
+++ b/packages/app/src/components/FileSidebar.menu-action.dom.test.tsx
@@ -57,7 +57,6 @@ const ACTIVE_TARGET = {
const notifyViewMenuStateChangedMock = mock(() => {});
const toggleSidebarMock = mock(() => {});
const showItemInFolderMock = mock((_path: string) => Promise.resolve());
-const dispatchOpenInTerminalMock = mock((_bridge: unknown, _path: string) => Promise.resolve());
const handoffDispatchMock = mock((_target: string, _input: unknown) =>
Promise.resolve({ ok: true }),
);
@@ -130,6 +129,7 @@ mock.module('@/components/ui/dropdown-menu', () => ({
DropdownMenu: PassThrough,
DropdownMenuContent: ElementPassThrough,
DropdownMenuItem: Button,
+ DropdownMenuSeparator: () => null,
DropdownMenuTrigger: PassThrough,
}));
@@ -198,10 +198,6 @@ mock.module('@/lib/config-provider', () => ({
}),
}));
-mock.module('@/lib/dispatch-open-in-terminal', () => ({
- dispatchOpenInTerminal: dispatchOpenInTerminalMock,
-}));
-
mock.module('@/lib/use-workspace', () => ({
useWorkspace: () => ({
contentDir: '/tmp/open-knowledge',
@@ -230,7 +226,6 @@ describe('FileSidebar menu-action runtime routing', () => {
notifyViewMenuStateChangedMock,
toggleSidebarMock,
showItemInFolderMock,
- dispatchOpenInTerminalMock,
handoffDispatchMock,
projectLocalPatch,
treeCalls.collapseAll,
@@ -347,12 +342,6 @@ describe('FileSidebar menu-action runtime routing', () => {
menuActionCallback?.('reveal-in-finder' as MenuAction);
expect(showItemInFolderMock).toHaveBeenCalledWith('/tmp/open-knowledge/notes/source.md');
- menuActionCallback?.('open-in-terminal' as MenuAction);
- expect(dispatchOpenInTerminalMock).toHaveBeenCalledWith(
- window.okDesktop,
- '/tmp/open-knowledge/notes',
- );
-
menuActionCallback?.('send-to-ai' as MenuAction);
expect(handoffDispatchMock).toHaveBeenCalledWith(
'codex',
diff --git a/packages/app/src/components/FileSidebar.tsx b/packages/app/src/components/FileSidebar.tsx
index 7c821ddec..777cfd66e 100644
--- a/packages/app/src/components/FileSidebar.tsx
+++ b/packages/app/src/components/FileSidebar.tsx
@@ -8,7 +8,6 @@ import {
FoldVertical,
ListCollapse,
SquarePen,
- Terminal,
UnfoldVertical,
Upload,
} from 'lucide-react';
@@ -62,11 +61,9 @@ import { useFolderConfig } from '@/hooks/use-folder-config';
import { useIsEmbedded } from '@/hooks/use-is-embedded';
import { useConfigContext } from '@/lib/config-provider';
import { subscribeToCreateTopLevelFile } from '@/lib/create-file-events';
-import { dispatchOpenInTerminal } from '@/lib/dispatch-open-in-terminal';
import {
buildSendToAiInputForActiveTarget,
resolveActiveTargetAbsPath,
- resolveActiveTargetParentDirAbsPath,
resolveActiveTargetRelativePath,
} from '@/lib/file-menu-target-resolvers';
import {
@@ -219,10 +216,6 @@ function FileSidebarInner({ onOpenSearch }: FileSidebarProps) {
if (!workspace || !bridge) return;
void bridge.shell.showItemInFolder(workspace.contentDir);
};
- const handleEmptySpaceOpenInTerminal = () => {
- if (!workspace || !bridge) return;
- void dispatchOpenInTerminal(bridge, workspace.contentDir);
- };
const handleEmptySpaceCopyFullPath = async () => {
if (!workspace) return;
try {
@@ -322,16 +315,6 @@ function FileSidebarInner({ onOpenSearch }: FileSidebarProps) {
void bridge.shell.showItemInFolder(absPath);
return;
}
- case 'open-in-terminal': {
- if (!bridge || !workspace) return;
- const dirAbsPath = resolveActiveTargetParentDirAbsPath(
- activeTarget,
- activeDocName,
- workspace,
- );
- void dispatchOpenInTerminal(bridge, dirAbsPath);
- return;
- }
case 'send-to-ai': {
const installedTargets = VISIBLE_TARGETS.filter(
(target) => handoffInstallStates[target.id]?.installed === true,
@@ -686,8 +669,8 @@ function FileSidebarInner({ onOpenSearch }: FileSidebarProps) {
* (parentDir = '' → contentDir). Upload opens the project-root file
* picker. Disabled when workspace hasn't resolved.
*
- * Section 2: Act-on-project. Reveal in Finder + Open in Terminal
- * are Electron-only (`if (!bridge) return null`); Open with AI submenu
+ * Section 2: Act-on-project. Reveal in Finder
+ * is Electron-only (`if (!bridge) return null`); Open with AI submenu
* is cross-host (filtered via useInstalledAgents); Copy full path
* is cross-host.
*
@@ -769,24 +752,6 @@ function FileSidebarInner({ onOpenSearch }: FileSidebarProps) {
dispatch={dispatchHandoff}
webFallbackVisible={false}
/>
- {bridge ? (
- <ContextMenuItem
- disabled={!workspace}
- onSelect={handleEmptySpaceOpenInTerminal}
- data-testid="empty-space-menu-open-in-terminal"
- aria-label={workspace ? t`Open in Terminal` : t`Open in Terminal, No workspace`}
- >
- <Terminal aria-hidden="true" />
- <span className="flex-1">
- <Trans>Open in Terminal</Trans>
- </span>
- {!workspace ? (
- <span aria-hidden="true" className="ml-2 text-muted-foreground text-xs">
- <Trans>No workspace</Trans>
- </span>
- ) : null}
- </ContextMenuItem>
- ) : null}
<ContextMenuItem
disabled={!workspace}
onSelect={handleEmptySpaceCopyFullPath}
diff --git a/packages/app/src/components/FileTree.tsx b/packages/app/src/components/FileTree.tsx
index ccf551434..ac2ea7dda 100644
--- a/packages/app/src/components/FileTree.tsx
+++ b/packages/app/src/components/FileTree.tsx
@@ -40,7 +40,6 @@ import {
Info,
Pencil,
SquarePen,
- Terminal,
Trash2,
TriangleAlert,
UnfoldVertical,
@@ -167,7 +166,6 @@ import { assetTabId, docTabId, folderTabId, remapPathForFolderRenames } from '@/
import { useConflicts } from '@/hooks/use-conflicts';
import { useFolderConfig } from '@/hooks/use-folder-config';
import { useConfigContext } from '@/lib/config-provider';
-import { dispatchOpenInTerminal } from '@/lib/dispatch-open-in-terminal';
import {
hashFromAssetPath,
hashFromDocName,
@@ -487,40 +485,6 @@ function RevealInFileManagerMenuItem({
);
}
-function OpenInTerminalMenuItem({
- dirAbsPath,
- onClose,
-}: {
- dirAbsPath: string | null;
- onClose: () => void;
-}) {
- const { t } = useLingui();
- const bridge = typeof window !== 'undefined' ? window.okDesktop : undefined;
- if (!bridge) return null;
- const hint = dirAbsPath === null ? t`No workspace` : null;
- return (
- <DropdownMenuItem
- disabled={dirAbsPath === null}
- onSelect={() => {
- if (dirAbsPath === null) return;
- onClose();
- void dispatchOpenInTerminal(bridge, dirAbsPath);
- }}
- aria-label={hint ? t`Open in Terminal, ${hint}` : t`Open in Terminal`}
- >
- <Terminal aria-hidden="true" />
- <span className="flex-1">
- <Trans>Open in Terminal</Trans>
- </span>
- {hint ? (
- <span aria-hidden="true" className="ml-2 text-muted-foreground text-xs">
- {hint}
- </span>
- ) : null}
- </DropdownMenuItem>
- );
-}
-
interface FileTreeMenuProps {
item: ContextMenuItem;
context: ContextMenuOpenContext;
@@ -722,21 +686,6 @@ function FileTreeMenu({
const deleteTargets = selectedDeleteTargets.length > 1 ? selectedDeleteTargets : [target];
const deleteCount = deleteTargets.length;
const deleteLabel = plural(deleteCount, { one: 'Delete', other: 'Delete # items' });
- const folderAbsPath =
- isFolder && workspace
- ? joinWorkspacePath(
- workspace.contentDir,
- relativePathForTreeItem(item),
- workspace.pathSeparator,
- )
- : null;
- const parentDirAbsPath: string | null = (() => {
- if (!workspace || isFolder) return null;
- const rel = relativePathForTreeItem(item);
- const lastSep = rel.lastIndexOf('/');
- if (lastSep === -1) return workspace.contentDir;
- return joinWorkspacePath(workspace.contentDir, rel.slice(0, lastSep), workspace.pathSeparator);
- })();
const handoffInput: HandoffDispatchInput | null = isAsset
? null
: isFolder
@@ -873,7 +822,6 @@ function FileTreeMenu({
dispatch={handoff.dispatch}
webFallbackVisible={false}
/>
- <OpenInTerminalMenuItem dirAbsPath={folderAbsPath} onClose={close} />
<DropdownMenuSub>
<DropdownMenuSubTrigger>
<Copy aria-hidden="true" />
@@ -1023,7 +971,6 @@ function FileTreeMenu({
webFallbackVisible={true}
/>
)}
- <OpenInTerminalMenuItem dirAbsPath={parentDirAbsPath} onClose={close} />
<DropdownMenuSub>
<DropdownMenuSubTrigger>
<Copy aria-hidden="true" />
diff --git a/packages/app/src/components/TerminalConsentDialog.dom.test.tsx b/packages/app/src/components/TerminalConsentDialog.dom.test.tsx
new file mode 100644
index 000000000..62b97369a
--- /dev/null
+++ b/packages/app/src/components/TerminalConsentDialog.dom.test.tsx
@@ -0,0 +1,97 @@
+import { afterEach, describe, expect, mock, test } from 'bun:test';
+import { cleanup, render, screen } from '@testing-library/react';
+import userEvent from '@testing-library/user-event';
+import type { ReactNode } from 'react';
+
+mock.module('@lingui/react/macro', () => ({
+ Trans: ({ children }: { children: ReactNode }) => <>{children}</>,
+ useLingui: () => ({
+ t: (strings: TemplateStringsArray, ...values: unknown[]) =>
+ strings.reduce((out, part, index) => `${out}${part}${values[index] ?? ''}`, ''),
+ }),
+}));
+
+const { TerminalConsentDialog } = await import('./TerminalConsentDialog');
+
+const EXPECTED = {
+ title: 'Enable a terminal for this project?',
+ para1:
+ "This runs a real terminal inside Open Knowledge — the same as opening Terminal on your Mac — starting in this project's folder.",
+ para2:
+ "Commands you run have the full access of your macOS user account: they can read, change, or delete your files, install software, and use the network. Open Knowledge doesn't limit or sandbox what the terminal can do.",
+ para3:
+ "This stays on only for this project on this Mac. It's never included when you sync, clone, or share the project, and you can turn it off anytime in Settings.",
+ enable: 'Enable terminal',
+ notNow: 'Not now',
+};
+
+describe('TerminalConsentDialog', () => {
+ afterEach(() => cleanup());
+
+ test('renders the HUMAN-APPROVED copy verbatim inside an accessible dialog', () => {
+ render(<TerminalConsentDialog open={true} onAccept={() => {}} onDecline={() => {}} />);
+
+ const dialog = screen.getByRole('dialog');
+ expect(dialog.textContent).toContain(EXPECTED.title);
+ expect(screen.getByText(EXPECTED.title)).toBeTruthy();
+ expect(screen.getByText(EXPECTED.para1)).toBeTruthy();
+ expect(screen.getByText(EXPECTED.para2)).toBeTruthy();
+ expect(screen.getByText(EXPECTED.para3)).toBeTruthy();
+ expect(screen.getByRole('button', { name: EXPECTED.enable })).toBeTruthy();
+ expect(screen.getByRole('button', { name: EXPECTED.notNow })).toBeTruthy();
+ });
+
+ test('does not render any content when closed', () => {
+ render(<TerminalConsentDialog open={false} onAccept={() => {}} onDecline={() => {}} />);
+ expect(screen.queryByRole('dialog')).toBeNull();
+ expect(screen.queryByText(EXPECTED.title)).toBeNull();
+ });
+
+ test('"Enable terminal" fires onAccept; never onDecline', async () => {
+ const accepts: string[] = [];
+ const declines: string[] = [];
+ render(
+ <TerminalConsentDialog
+ open={true}
+ onAccept={() => accepts.push('accept')}
+ onDecline={() => declines.push('decline')}
+ />,
+ );
+
+ await userEvent.click(screen.getByRole('button', { name: EXPECTED.enable }));
+ expect(accepts).toEqual(['accept']);
+ expect(declines).toEqual([]);
+ });
+
+ test('"Not now" fires onDecline', async () => {
+ const accepts: string[] = [];
+ const declines: string[] = [];
+ render(
+ <TerminalConsentDialog
+ open={true}
+ onAccept={() => accepts.push('accept')}
+ onDecline={() => declines.push('decline')}
+ />,
+ );
+
+ await userEvent.click(screen.getByRole('button', { name: EXPECTED.notNow }));
+ expect(declines).toEqual(['decline']);
+ expect(accepts).toEqual([]);
+ });
+
+ test('Escape resolves to the safe choice (decline), never an implicit grant', async () => {
+ const accepts: string[] = [];
+ const declines: string[] = [];
+ render(
+ <TerminalConsentDialog
+ open={true}
+ onAccept={() => accepts.push('accept')}
+ onDecline={() => declines.push('decline')}
+ />,
+ );
+
+ await userEvent.keyboard('{Escape}');
+ expect(declines).toEqual(['decline']);
+ expect(accepts).toEqual([]);
+ });
+});
diff --git a/packages/app/src/components/TerminalConsentDialog.tsx b/packages/app/src/components/TerminalConsentDialog.tsx
new file mode 100644
index 000000000..036b2bdac
--- /dev/null
+++ b/packages/app/src/components/TerminalConsentDialog.tsx
@@ -0,0 +1,61 @@
+import { Button } from '@/components/ui/button';
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+} from '@/components/ui/dialog';
+
+const TERMINAL_CONSENT_COPY = {
+ title: 'Enable a terminal for this project?',
+ body: [
+ "This runs a real terminal inside Open Knowledge — the same as opening Terminal on your Mac — starting in this project's folder.",
+ "Commands you run have the full access of your macOS user account: they can read, change, or delete your files, install software, and use the network. Open Knowledge doesn't limit or sandbox what the terminal can do.",
+ "This stays on only for this project on this Mac. It's never included when you sync, clone, or share the project, and you can turn it off anytime in Settings.",
+ ],
+ enable: 'Enable terminal',
+ notNow: 'Not now',
+} as const;
+
+interface TerminalConsentDialogProps {
+ readonly open: boolean;
+ readonly onAccept: () => void;
+ readonly onDecline: () => void;
+}
+
+export function TerminalConsentDialog({ open, onAccept, onDecline }: TerminalConsentDialogProps) {
+ return (
+ <Dialog
+ open={open}
+ onOpenChange={(next) => {
+ if (!next) onDecline();
+ }}
+ >
+ <DialogContent className="sm:max-w-lg" showCloseButton={false}>
+ <DialogHeader>
+ <DialogTitle>{TERMINAL_CONSENT_COPY.title}</DialogTitle>
+ {/* All three paragraphs live in the description (Radix wires it to
+ `aria-describedby`) so a screen reader announces the actual risk —
+ "full access… no sandbox" — on open, not just the first line.
+ `asChild` makes the description a <div> so multiple <p> children
+ are valid markup. */}
+ <DialogDescription asChild>
+ <div className="space-y-3">
+ <p>{TERMINAL_CONSENT_COPY.body[0]}</p>
+ <p className="text-1sm">{TERMINAL_CONSENT_COPY.body[1]}</p>
+ <p className="text-1sm">{TERMINAL_CONSENT_COPY.body[2]}</p>
+ </div>
+ </DialogDescription>
+ </DialogHeader>
+ <DialogFooter>
+ <Button variant="outline" onClick={onDecline}>
+ {TERMINAL_CONSENT_COPY.notNow}
+ </Button>
+ <Button onClick={onAccept}>{TERMINAL_CONSENT_COPY.enable}</Button>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+ );
+}
diff --git a/packages/app/src/components/TerminalDock.dom.test.tsx b/packages/app/src/components/TerminalDock.dom.test.tsx
new file mode 100644
index 000000000..38f900db1
--- /dev/null
+++ b/packages/app/src/components/TerminalDock.dom.test.tsx
@@ -0,0 +1,203 @@
+import { afterEach, beforeEach, describe, expect, mock, test } from 'bun:test';
+import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
+import type { OkDesktopBridge } from '@/lib/desktop-bridge-types';
+
+const TERMINAL_PANEL_ID = 'terminal-dock-panel';
+
+type Size = { asPercentage: number; inPixels: number };
+// biome-ignore lint/suspicious/noExplicitAny: captured mock-component props, asserted structurally
+let terminalPanelProps: Record<string, any> | null = null;
+// biome-ignore lint/suspicious/noExplicitAny: captured TerminalGate props (onClose), asserted structurally
+let lastTerminalPanelProps: Record<string, any> | null = null;
+let written: number[] = [];
+
+const panelHandle = {
+ collapse: mock(() => terminalPanelProps?.onResize?.({ asPercentage: 0, inPixels: 0 })),
+ expand: mock(() => terminalPanelProps?.onResize?.({ asPercentage: 40, inPixels: 240 })),
+ resize: mock((s: string) => {
+ const px = Number.parseInt(s, 10) || 0;
+ terminalPanelProps?.onResize?.({ asPercentage: px > 0 ? 30 : 0, inPixels: px });
+ }),
+};
+const sharedPanelRef: { current: unknown } = { current: panelHandle };
+
+mock.module('react-resizable-panels', () => ({
+ usePanelRef: () => sharedPanelRef,
+}));
+
+mock.module('@/components/ui/resizable', () => ({
+ // biome-ignore lint/suspicious/noExplicitAny: test stub
+ ResizablePanelGroup: ({ children, orientation }: any) => (
+ <div data-testid="rrp-group" data-orientation={orientation}>
+ {children}
+ </div>
+ ),
+ // biome-ignore lint/suspicious/noExplicitAny: test stub
+ ResizablePanel: (props: any) => {
+ if (props.id === TERMINAL_PANEL_ID) terminalPanelProps = props;
+ return (
+ <div
+ id={props.id}
+ data-panel={props.id ?? 'editor'}
+ data-inert={props.inert ? 'true' : undefined}
+ >
+ {props.children}
+ </div>
+ );
+ },
+ // biome-ignore lint/suspicious/noExplicitAny: test stub
+ ResizableHandle: ({ onPointerDown }: any) => (
+ <div data-testid="terminal-resize-handle" onPointerDown={onPointerDown} />
+ ),
+}));
+
+mock.module('./TerminalGate', () => ({
+ // biome-ignore lint/suspicious/noExplicitAny: test stub
+ TerminalGate: (props: any) => {
+ lastTerminalPanelProps = props;
+ return <span data-testid="terminal-panel" tabIndex={-1} />;
+ },
+}));
+
+mock.module('@/lib/terminal-height-store', () => ({
+ getInitialTerminalHeight: () => 240,
+ writeTerminalHeight: (px: number) => {
+ written.push(px);
+ },
+}));
+
+const { TerminalDock } = await import('./TerminalDock');
+
+const bridge = {} as OkDesktopBridge;
+
+function renderDock(visible: boolean) {
+ const onVisibleChange = mock((_v: boolean) => {});
+ const ui = (v: boolean) => (
+ <TerminalDock bridge={bridge} visible={v} onVisibleChange={onVisibleChange}>
+ <div data-testid="editor-child" />
+ </TerminalDock>
+ );
+ const utils = render(ui(visible));
+ return {
+ ...utils,
+ onVisibleChange,
+ rerender: (v: boolean) => utils.rerender(ui(v)),
+ };
+}
+
+function editorRegion(): HTMLElement {
+ const region = screen.getByTestId('editor-child').parentElement;
+ if (region == null) throw new Error('editor region not found');
+ return region;
+}
+
+describe('TerminalDock', () => {
+ beforeEach(() => {
+ terminalPanelProps = null;
+ lastTerminalPanelProps = null;
+ written = [];
+ panelHandle.collapse.mockClear();
+ panelHandle.resize.mockClear();
+ panelHandle.expand.mockClear();
+ sharedPanelRef.current = panelHandle;
+ });
+ afterEach(() => {
+ cleanup();
+ });
+
+ test('wraps the editor in a vertical group with a collapsible bottom terminal panel', () => {
+ renderDock(false);
+
+ expect(screen.getByTestId('editor-child')).toBeTruthy();
+ expect(screen.getByTestId('rrp-group').getAttribute('data-orientation')).toBe('vertical');
+ expect(screen.getByTestId('terminal-resize-handle')).toBeTruthy();
+
+ expect(terminalPanelProps?.collapsible).toBe(true);
+ expect(terminalPanelProps?.collapsedSize).toBe(0);
+ expect(terminalPanelProps?.minSize).toBe('120px');
+ expect(terminalPanelProps?.maxSize).toBe('50%');
+ expect(terminalPanelProps?.defaultSize).toBe(0);
+ expect(terminalPanelProps?.inert).toBe(true);
+ });
+
+ test('does not mount the terminal (no PTY) until first opened, then keeps it mounted on hide', () => {
+ const view = renderDock(false);
+ expect(screen.queryByTestId('terminal-panel')).toBeNull();
+
+ act(() => view.rerender(true));
+ expect(screen.getByTestId('terminal-panel')).toBeTruthy();
+
+ act(() => view.rerender(false));
+ expect(screen.getByTestId('terminal-panel')).toBeTruthy();
+ });
+
+ test('opening restores the persisted height; hiding collapses the panel', () => {
+ const view = renderDock(false);
+ panelHandle.resize.mockClear();
+ panelHandle.collapse.mockClear();
+
+ act(() => view.rerender(true));
+ expect(panelHandle.resize).toHaveBeenCalledWith('240px');
+
+ act(() => view.rerender(false));
+ expect(panelHandle.collapse).toHaveBeenCalledTimes(1);
+ });
+
+ test('reflects collapsed state via inert as the panel opens and closes', () => {
+ const view = renderDock(true);
+ expect(terminalPanelProps?.inert).toBeFalsy();
+
+ act(() => view.rerender(false));
+ expect(terminalPanelProps?.inert).toBe(true);
+ });
+
+ test('persists height only on user drag, never on an imperative open', async () => {
+ const view = renderDock(false);
+
+ act(() => view.rerender(true));
+ expect(written).toEqual([]);
+
+ fireEvent.pointerDown(screen.getByTestId('terminal-resize-handle'));
+ act(() => terminalPanelProps?.onResize?.({ asPercentage: 35, inPixels: 300 } as Size));
+ await waitFor(() => expect(written).toContain(300));
+ fireEvent.pointerUp(window);
+ });
+
+ test('drag-collapsing the panel reports the hidden state to the parent', () => {
+ const view = renderDock(true);
+
+ fireEvent.pointerDown(screen.getByTestId('terminal-resize-handle'));
+ act(() => terminalPanelProps?.onResize?.({ asPercentage: 0, inPixels: 0 } as Size));
+
+ expect(view.onVisibleChange).toHaveBeenCalledWith(false);
+ fireEvent.pointerUp(window);
+ });
+
+ test('returns focus to the editor when the terminal collapses (no keyboard strand)', () => {
+ const view = renderDock(true);
+ const term = screen.getByTestId('terminal-panel');
+ act(() => term.focus());
+ expect(document.getElementById(TERMINAL_PANEL_ID)?.contains(document.activeElement)).toBe(true);
+
+ act(() => view.rerender(false));
+
+ expect(document.activeElement).toBe(editorRegion());
+ });
+
+ test('does not pass an Escape handler to the gate — Escape reaches the shell, ⌘J is the exit', () => {
+ renderDock(true);
+ screen.getByTestId('terminal-panel'); // mounted
+
+ expect(lastTerminalPanelProps?.onEscape).toBeUndefined();
+ });
+
+ test('the "Close terminal" affordance collapses the dock and returns focus to the editor', () => {
+ const view = renderDock(true);
+ act(() => screen.getByTestId('terminal-panel').focus());
+
+ act(() => lastTerminalPanelProps?.onClose?.());
+
+ expect(view.onVisibleChange).toHaveBeenCalledWith(false);
+ expect(document.activeElement).toBe(editorRegion());
+ });
+});
diff --git a/packages/app/src/components/TerminalDock.tsx b/packages/app/src/components/TerminalDock.tsx
new file mode 100644
index 000000000..e691e5952
--- /dev/null
+++ b/packages/app/src/components/TerminalDock.tsx
@@ -0,0 +1,152 @@
+import { type ReactNode, useEffect, useLayoutEffect, useRef, useState } from 'react';
+import { usePanelRef } from 'react-resizable-panels';
+import { ResizableHandle, ResizablePanel, ResizablePanelGroup } from '@/components/ui/resizable';
+import type { OkDesktopBridge } from '@/lib/desktop-bridge-types';
+import { getInitialTerminalHeight, writeTerminalHeight } from '@/lib/terminal-height-store';
+import { cn } from '@/lib/utils';
+import type { TerminalLaunchIntent } from './EditorPane';
+import { TerminalGate } from './TerminalGate';
+
+const TERMINAL_PANEL_ID = 'terminal-dock-panel';
+
+interface TerminalDockProps {
+ readonly bridge: OkDesktopBridge;
+ readonly children: ReactNode;
+ readonly visible: boolean;
+ readonly onVisibleChange: (visible: boolean) => void;
+ readonly launch?: TerminalLaunchIntent | null;
+}
+
+export function TerminalDock({
+ bridge,
+ children,
+ visible,
+ onVisibleChange,
+ launch = null,
+}: TerminalDockProps) {
+ const panelRef = usePanelRef();
+ const editorRegionRef = useRef<HTMLDivElement | null>(null);
+ const [isCollapsed, setIsCollapsed] = useState(!visible);
+ const [mounted, setMounted] = useState(visible);
+
+ const [initialHeightPx] = useState(() => getInitialTerminalHeight());
+ const heightPxRef = useRef(initialHeightPx);
+
+ const [isDragging, setIsDragging] = useState(false);
+ const isDraggingRef = useRef(false);
+
+ const writeTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
+ function debouncedWriteHeight(px: number) {
+ if (writeTimerRef.current != null) clearTimeout(writeTimerRef.current);
+ writeTimerRef.current = setTimeout(() => {
+ writeTerminalHeight(px);
+ writeTimerRef.current = null;
+ }, 100);
+ }
+ const dragUpHandlerRef = useRef<(() => void) | null>(null);
+ useEffect(
+ () => () => {
+ if (writeTimerRef.current != null) clearTimeout(writeTimerRef.current);
+ if (dragUpHandlerRef.current != null) {
+ window.removeEventListener('pointerup', dragUpHandlerRef.current);
+ dragUpHandlerRef.current = null;
+ }
+ },
+ [],
+ );
+
+ useEffect(() => {
+ if (visible) setMounted(true);
+ }, [visible]);
+
+ useEffect(() => {
+ const panel = panelRef.current;
+ if (panel == null) return;
+ if (visible) {
+ panel.resize(`${heightPxRef.current}px`);
+ } else {
+ panel.collapse();
+ }
+ }, [visible, panelRef]);
+
+ useLayoutEffect(() => {
+ if (!isCollapsed) return;
+ const panelEl = document.getElementById(TERMINAL_PANEL_ID);
+ if (!panelEl?.contains(document.activeElement)) return;
+ editorRegionRef.current?.focus();
+ }, [isCollapsed]);
+
+ return (
+ <ResizablePanelGroup
+ orientation="vertical"
+ className="min-h-0 flex-1"
+ data-dragging={isDragging || undefined}
+ >
+ <ResizablePanel minSize="20%" className="flex min-h-0 flex-col">
+ {/* tabIndex -1 makes this a programmatic focus target for focus-return
+ on collapse without adding it to the tab order. */}
+ <div
+ ref={editorRegionRef}
+ tabIndex={-1}
+ className="flex h-full min-h-0 flex-col outline-none"
+ >
+ {children}
+ </div>
+ </ResizablePanel>
+ <ResizableHandle
+ withHandle
+ onPointerDown={() => {
+ setIsDragging(true);
+ isDraggingRef.current = true;
+ const handleUp = () => {
+ setIsDragging(false);
+ isDraggingRef.current = false;
+ window.removeEventListener('pointerup', handleUp);
+ dragUpHandlerRef.current = null;
+ };
+ dragUpHandlerRef.current = handleUp;
+ window.addEventListener('pointerup', handleUp);
+ }}
+ />
+ <ResizablePanel
+ id={TERMINAL_PANEL_ID}
+ panelRef={panelRef}
+ defaultSize={visible ? `${initialHeightPx}px` : 0}
+ minSize="120px"
+ maxSize="50%"
+ collapsible
+ collapsedSize={0}
+ onResize={(size) => {
+ const collapsed = size.asPercentage === 0;
+ setIsCollapsed(collapsed);
+ if (isDraggingRef.current) {
+ if (collapsed && visible) onVisibleChange(false);
+ else if (!collapsed && !visible) onVisibleChange(true);
+ if (size.inPixels > 0) {
+ heightPxRef.current = size.inPixels;
+ debouncedWriteHeight(size.inPixels);
+ }
+ }
+ }}
+ inert={isCollapsed}
+ className={cn(
+ 'flex flex-col',
+ !isDragging &&
+ 'transition-[flex-grow] duration-150 ease-out motion-reduce:transition-none motion-reduce:duration-0',
+ )}
+ >
+ {mounted ? (
+ <TerminalGate
+ bridge={bridge}
+ visible={visible}
+ launch={launch}
+ onClose={() => {
+ onVisibleChange(false);
+ editorRegionRef.current?.focus();
+ }}
+ />
+ ) : null}
+ </ResizablePanel>
+ </ResizablePanelGroup>
+ );
+}
diff --git a/packages/app/src/components/TerminalExitNotice.dom.test.tsx b/packages/app/src/components/TerminalExitNotice.dom.test.tsx
new file mode 100644
index 000000000..011f6034a
--- /dev/null
+++ b/packages/app/src/components/TerminalExitNotice.dom.test.tsx
@@ -0,0 +1,44 @@
+import { afterEach, describe, expect, mock, test } from 'bun:test';
+import { cleanup, fireEvent, render, screen } from '@testing-library/react';
+import { TerminalExitNotice } from './TerminalExitNotice';
+
+afterEach(() => cleanup());
+
+describe('TerminalExitNotice', () => {
+ test('a clean exit shows the ended state inside an alert live region', () => {
+ render(<TerminalExitNotice info={{ exitCode: 0, signal: null }} onRestart={() => {}} />);
+
+ expect(screen.getByRole('alert')).toBeTruthy();
+ expect(screen.getByText(/terminal session ended/i)).toBeTruthy();
+ });
+
+ test('a non-zero exit code is conveyed so the state is actionable', () => {
+ render(<TerminalExitNotice info={{ exitCode: 1, signal: null }} onRestart={() => {}} />);
+ expect(screen.getByText(/exit code 1/)).toBeTruthy();
+ });
+
+ test('a signal termination is conveyed and takes precedence over the exit code', () => {
+ render(<TerminalExitNotice info={{ exitCode: 0, signal: 9 }} onRestart={() => {}} />);
+ expect(screen.getByText(/signal 9/)).toBeTruthy();
+ });
+
+ test('a crash is distinguished from a clean exit', () => {
+ render(
+ <TerminalExitNotice
+ info={{ exitCode: 1, signal: null, error: 'host crashed' }}
+ onRestart={() => {}}
+ />,
+ );
+ expect(screen.getByText(/stopped unexpectedly/i)).toBeTruthy();
+ expect(screen.queryByText(/host crashed/)).toBeNull();
+ });
+
+ test('the restart control is an accessible button that spawns a fresh session', () => {
+ const onRestart = mock(() => {});
+ render(<TerminalExitNotice info={{ exitCode: 0, signal: null }} onRestart={onRestart} />);
+
+ const restart = screen.getByRole('button', { name: 'Restart terminal' });
+ fireEvent.click(restart);
+ expect(onRestart).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/packages/app/src/components/TerminalExitNotice.tsx b/packages/app/src/components/TerminalExitNotice.tsx
new file mode 100644
index 000000000..2da052965
--- /dev/null
+++ b/packages/app/src/components/TerminalExitNotice.tsx
@@ -0,0 +1,40 @@
+import { useLingui } from '@lingui/react/macro';
+import { Button } from '@/components/ui/button';
+
+export interface TerminalExitInfo {
+ readonly exitCode: number;
+ readonly signal: number | null;
+ readonly error?: string;
+}
+
+interface TerminalExitNoticeProps {
+ readonly info: TerminalExitInfo;
+ readonly onRestart: () => void;
+}
+
+export function TerminalExitNotice({ info, onRestart }: TerminalExitNoticeProps) {
+ const { t } = useLingui();
+
+ let message: string;
+ if (info.error != null) {
+ message = t`The terminal stopped unexpectedly.`;
+ } else if (info.signal != null && info.signal !== 0) {
+ message = t`The terminal session ended (signal ${info.signal}).`;
+ } else if (info.exitCode !== 0) {
+ message = t`The terminal session ended (exit code ${info.exitCode}).`;
+ } else {
+ message = t`The terminal session ended.`;
+ }
+
+ return (
+ <div
+ role="alert"
+ className="absolute inset-0 z-20 flex flex-col items-center justify-center gap-3 bg-[#1e1e1e]/90 p-6 text-center text-[#d4d4d4]"
+ >
+ <p className="max-w-sm text-sm">{message}</p>
+ <Button size="sm" variant="secondary" onClick={onRestart}>
+ {t`Restart terminal`}
+ </Button>
+ </div>
+ );
+}
diff --git a/packages/app/src/components/TerminalGate.dom.test.tsx b/packages/app/src/components/TerminalGate.dom.test.tsx
new file mode 100644
index 000000000..618f7c5a0
--- /dev/null
+++ b/packages/app/src/components/TerminalGate.dom.test.tsx
@@ -0,0 +1,149 @@
+import { afterEach, beforeEach, describe, expect, mock, test } from 'bun:test';
+import { act, cleanup, render, screen } from '@testing-library/react';
+import type { ReactNode } from 'react';
+import type { OkDesktopBridge } from '@/lib/desktop-bridge-types';
+
+type ConsentState = { enabled: boolean | null; synced: boolean };
+type Writer = ((enabled: boolean) => { ok: true } | { ok: false; error: string }) | null;
+
+let consentState: ConsentState = { enabled: null, synced: true };
+let writerImpl: Writer = null;
+const writerCalls: boolean[] = [];
+const toastErrors: string[] = [];
+// biome-ignore lint/suspicious/noExplicitAny: captured mock-component props
+let consentDialogProps: Record<string, any> | null = null;
+
+mock.module('@lingui/react/macro', () => ({
+ Trans: ({ children }: { children: ReactNode }) => <>{children}</>,
+ useLingui: () => ({
+ t: (strings: TemplateStringsArray, ...values: unknown[]) =>
+ strings.reduce((out, part, index) => `${out}${part}${values[index] ?? ''}`, ''),
+ }),
+}));
+
+mock.module('sonner', () => ({
+ toast: { error: (message: string) => toastErrors.push(message) },
+}));
+
+mock.module('@/hooks/use-terminal-enabled', () => ({
+ useTerminalConsentState: () => consentState,
+ useTerminalEnabledWriter: () => writerImpl,
+}));
+
+mock.module('./TerminalPanel', () => ({
+ TerminalPanel: () => <span data-testid="terminal-panel" />,
+}));
+
+mock.module('./TerminalConsentDialog', () => ({
+ // biome-ignore lint/suspicious/noExplicitAny: test stub
+ TerminalConsentDialog: (props: any) => {
+ consentDialogProps = props;
+ return props.open ? <div data-testid="consent-dialog" /> : null;
+ },
+}));
+
+const { TerminalGate } = await import('./TerminalGate');
+
+const bridge = {} as OkDesktopBridge;
+
+function renderGate(visible = true) {
+ return render(<TerminalGate bridge={bridge} visible={visible} />);
+}
+
+describe('TerminalGate', () => {
+ beforeEach(() => {
+ consentState = { enabled: null, synced: true };
+ writerImpl = (enabled) => {
+ writerCalls.push(enabled);
+ return { ok: true };
+ };
+ writerCalls.length = 0;
+ toastErrors.length = 0;
+ consentDialogProps = null;
+ });
+ afterEach(() => cleanup());
+
+ test('enabled === true mounts the terminal (shell spawns); no consent dialog', async () => {
+ consentState = { enabled: true, synced: true };
+ renderGate();
+ expect(await screen.findByTestId('terminal-panel')).toBeTruthy();
+ expect(screen.queryByTestId('consent-dialog')).toBeNull();
+ expect(screen.queryByRole('region', { name: 'Terminal disabled' })).toBeNull();
+ });
+
+ test('enabled === null on first open shows the JIT consent dialog; no shell', () => {
+ consentState = { enabled: null, synced: true };
+ renderGate(true);
+ expect(screen.queryByTestId('terminal-panel')).toBeNull();
+ expect(consentDialogProps?.open).toBe(true);
+ });
+
+ test('null but not yet synced does not flash the dialog (cold start)', () => {
+ consentState = { enabled: null, synced: false };
+ renderGate(true);
+ expect(consentDialogProps?.open).toBe(false);
+ });
+
+ test('null while hidden does not open the dialog', () => {
+ consentState = { enabled: null, synced: true };
+ renderGate(false);
+ expect(consentDialogProps?.open).toBe(false);
+ });
+
+ test('accepting consent grants via the writer (terminal.enabled := true)', () => {
+ consentState = { enabled: null, synced: true };
+ renderGate(true);
+ act(() => consentDialogProps?.onAccept());
+ expect(writerCalls).toEqual([true]);
+ });
+
+ test('declining shows the not-enabled state and never spawns', () => {
+ consentState = { enabled: null, synced: true };
+ renderGate(true);
+ act(() => consentDialogProps?.onDecline());
+
+ expect(screen.getByRole('region', { name: 'Terminal disabled' })).toBeTruthy();
+ expect(screen.queryByTestId('terminal-panel')).toBeNull();
+ expect(consentDialogProps?.open).toBe(false);
+ expect(writerCalls).toEqual([]);
+ });
+
+ test('enabled === false shows the not-enabled notice; no shell, no auto-dialog', () => {
+ consentState = { enabled: false, synced: true };
+ renderGate(true);
+ expect(screen.getByRole('region', { name: 'Terminal disabled' })).toBeTruthy();
+ expect(screen.queryByTestId('terminal-panel')).toBeNull();
+ expect(consentDialogProps?.open).toBe(false);
+ });
+
+ test('re-enabling from a revoked notice reopens consent (re-consent on re-enable)', () => {
+ consentState = { enabled: false, synced: true };
+ renderGate(true);
+ act(() => screen.getByRole('button', { name: 'Enable terminal' }).click());
+ expect(consentDialogProps?.open).toBe(true);
+ });
+
+ test('accept with no writer yet surfaces an actionable toast, no crash', () => {
+ consentState = { enabled: null, synced: true };
+ writerImpl = null;
+ renderGate(true);
+ act(() => consentDialogProps?.onAccept());
+ expect(writerCalls).toEqual([]);
+ expect(toastErrors.length).toBe(1);
+ });
+
+ test('a writer that fails to persist consent surfaces a toast and never mounts the shell', () => {
+ consentState = { enabled: null, synced: true };
+ writerImpl = (enabled) => {
+ writerCalls.push(enabled);
+ return { ok: false, error: 'ENOSPC: no space left on device' };
+ };
+ renderGate(true);
+ act(() => consentDialogProps?.onAccept());
+
+ expect(writerCalls).toEqual([true]);
+ expect(toastErrors.length).toBe(1);
+ expect(toastErrors[0]).toContain('ENOSPC');
+ expect(screen.queryByTestId('terminal-panel')).toBeNull();
+ });
+});
diff --git a/packages/app/src/components/TerminalGate.tsx b/packages/app/src/components/TerminalGate.tsx
new file mode 100644
index 000000000..cd55417d9
--- /dev/null
+++ b/packages/app/src/components/TerminalGate.tsx
@@ -0,0 +1,98 @@
+import { useLingui } from '@lingui/react/macro';
+import { lazy, Suspense, useState } from 'react';
+import { toast } from 'sonner';
+import { Button } from '@/components/ui/button';
+import { useTerminalConsentState, useTerminalEnabledWriter } from '@/hooks/use-terminal-enabled';
+import type { OkDesktopBridge } from '@/lib/desktop-bridge-types';
+import type { TerminalLaunchIntent } from './EditorPane';
+import { TerminalConsentDialog } from './TerminalConsentDialog';
+
+const TerminalPanel = lazy(() =>
+ import('./TerminalPanel').then((m) => ({ default: m.TerminalPanel })),
+);
+
+interface TerminalGateProps {
+ readonly bridge: OkDesktopBridge;
+ readonly visible: boolean;
+ readonly onClose?: () => void;
+ /** "Open in terminal" launch intent. Only reaches the session once consent
+ * is granted (the enabled-true branch) — so consent still gates the launch. */
+ readonly launch?: TerminalLaunchIntent | null;
+}
+
+export function TerminalGate({ bridge, visible, onClose, launch = null }: TerminalGateProps) {
+ const { enabled, synced } = useTerminalConsentState();
+ const writer = useTerminalEnabledWriter();
+ const { t } = useLingui();
+ const [declined, setDeclined] = useState(false);
+ const [forceConsent, setForceConsent] = useState(false);
+
+ const consentOpen = forceConsent || (visible && synced && enabled === null && !declined);
+ const showNotice = !consentOpen && (enabled === false || (enabled === null && declined));
+
+ function handleAccept() {
+ if (writer === null) {
+ toast.error(t`Terminal settings not loaded yet — try again in a moment.`);
+ return;
+ }
+ const result = writer(true);
+ if (!result.ok) {
+ toast.error(t`Could not enable the terminal: ${result.error}`);
+ return;
+ }
+ setForceConsent(false);
+ setDeclined(false);
+ }
+
+ function handleDecline() {
+ setForceConsent(false);
+ setDeclined(true);
+ }
+
+ if (enabled === true) {
+ return (
+ <Suspense fallback={<div className="h-full w-full bg-[#1e1e1e]" aria-hidden="true" />}>
+ <TerminalPanel bridge={bridge} className="h-full" onClose={onClose} launch={launch} />
+ </Suspense>
+ );
+ }
+
+ return (
+ <>
+ {showNotice ? (
+ <TerminalNotEnabledNotice
+ revoked={enabled === false}
+ onEnable={() => setForceConsent(true)}
+ />
+ ) : (
+ <div className="h-full w-full bg-[#1e1e1e]" aria-hidden="true" />
+ )}
+ <TerminalConsentDialog open={consentOpen} onAccept={handleAccept} onDecline={handleDecline} />
+ </>
+ );
+}
+
+interface TerminalNotEnabledNoticeProps {
+ readonly revoked: boolean;
+ readonly onEnable: () => void;
+}
+
+function TerminalNotEnabledNotice({ revoked, onEnable }: TerminalNotEnabledNoticeProps) {
+ const { t } = useLingui();
+ return (
+ <section
+ aria-label={t`Terminal disabled`}
+ className="flex h-full w-full flex-col items-center justify-center gap-3 bg-[#1e1e1e] p-6 text-center"
+ >
+ <p className="max-w-sm text-sm text-[#d4d4d4]">
+ {revoked
+ ? t`The terminal is turned off for this project. Turn it back on to run commands here.`
+ : t`The terminal is not enabled for this project.`}
+ </p>
+ <Button onClick={onEnable}>{t`Enable terminal`}</Button>
+ {revoked ? (
+ <p className="text-xs text-[#b3b3b3]">{t`You can also manage this in Settings.`}</p>
+ ) : null}
+ </section>
+ );
+}
diff --git a/packages/app/src/components/TerminalPanel.dom.test.tsx b/packages/app/src/components/TerminalPanel.dom.test.tsx
new file mode 100644
index 000000000..9363277ed
--- /dev/null
+++ b/packages/app/src/components/TerminalPanel.dom.test.tsx
@@ -0,0 +1,437 @@
+import { afterEach, beforeEach, describe, expect, mock, test } from 'bun:test';
+import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
+import type {
+ ClaudeReadiness,
+ OkDesktopBridge,
+ OkPtyData,
+ OkPtyExit,
+} from '@/lib/desktop-bridge-types';
+
+class MockFitAddon {
+ fit = mock(() => {});
+ constructor() {
+ lastFit = this;
+ }
+}
+class MockWebglAddon {}
+class MockWebLinksAddon {}
+class MockUnicode11Addon {}
+
+class MockTerminal {
+ cols = 80;
+ rows = 24;
+ unicode = { activeVersion: '6' };
+ onDataCb: ((d: string) => void) | null = null;
+ keyHandler: ((e: KeyboardEvent) => boolean) | null = null;
+ options: Record<string, unknown>;
+ open = mock(() => {});
+ focus = mock(() => {});
+ dispose = mock(() => {});
+ write = mock((_data: string, cb?: () => void) => {
+ cb?.();
+ });
+ loadAddon = mock((addon: unknown) => {
+ if (webglThrows && addon instanceof MockWebglAddon) throw new Error('no webgl2 context');
+ });
+ onData = mock((cb: (d: string) => void) => {
+ this.onDataCb = cb;
+ return { dispose() {} };
+ });
+ attachCustomKeyEventHandler = mock((h: (e: KeyboardEvent) => boolean) => {
+ this.keyHandler = h;
+ });
+ constructor(options: Record<string, unknown>) {
+ this.options = options;
+ lastTerm = this;
+ }
+}
+
+let lastTerm: MockTerminal | null = null;
+let lastFit: MockFitAddon | null = null;
+let webglThrows = false;
+
+let roCallback: (() => void) | null = null;
+let lastRO: MockResizeObserver | null = null;
+class MockResizeObserver {
+ observe = mock(() => {});
+ unobserve = mock(() => {});
+ disconnect = mock(() => {});
+ constructor(cb: () => void) {
+ roCallback = cb;
+ lastRO = this;
+ }
+}
+
+mock.module('@xterm/xterm', () => ({ Terminal: MockTerminal }));
+mock.module('@xterm/addon-fit', () => ({ FitAddon: MockFitAddon }));
+mock.module('@xterm/addon-webgl', () => ({ WebglAddon: MockWebglAddon }));
+mock.module('@xterm/addon-web-links', () => ({ WebLinksAddon: MockWebLinksAddon }));
+mock.module('@xterm/addon-unicode11', () => ({ Unicode11Addon: MockUnicode11Addon }));
+mock.module('@xterm/xterm/css/xterm.css', () => ({}));
+
+type CreateResult =
+ | { ok: true; ptyId: string }
+ | { ok: false; reason: 'no-project' | 'not-consented' };
+
+const WIRED: ClaudeReadiness = { claude: 'present', mcp: 'wired' };
+
+function makeBridge(createResult: CreateResult, preflight: ClaudeReadiness = WIRED) {
+ const dataSubs: Array<(m: OkPtyData) => void> = [];
+ const exitSubs: Array<(m: OkPtyExit) => void> = [];
+ const unsubData = mock(() => {});
+ const unsubExit = mock(() => {});
+ const openExternal = mock(async (_url: string) => {});
+ const rewireClaudeMcp = mock(async () => preflight);
+ const terminal = {
+ create: mock(async () => createResult),
+ input: mock((_id: string, _d: string) => {}),
+ resize: mock((_id: string, _c: number, _r: number) => {}),
+ kill: mock(async (_id: string) => {}),
+ drain: mock((_id: string, _bytes: number) => {}),
+ onData: mock((cb: (m: OkPtyData) => void) => {
+ dataSubs.push(cb);
+ return unsubData;
+ }),
+ onExit: mock((cb: (m: OkPtyExit) => void) => {
+ exitSubs.push(cb);
+ return unsubExit;
+ }),
+ claudePreflight: mock(async () => preflight),
+ rewireClaudeMcp,
+ };
+ return {
+ bridge: { terminal, shell: { openExternal } } as unknown as OkDesktopBridge,
+ terminal,
+ openExternal,
+ rewireClaudeMcp,
+ unsubData,
+ unsubExit,
+ pushData: (m: OkPtyData) => {
+ for (const f of dataSubs) f(m);
+ },
+ pushExit: (m: OkPtyExit) => {
+ for (const f of exitSubs) f(m);
+ },
+ };
+}
+
+const { TerminalPanel } = await import('./TerminalPanel');
+
+describe('TerminalPanel', () => {
+ beforeEach(() => {
+ lastTerm = null;
+ lastFit = null;
+ lastRO = null;
+ roCallback = null;
+ webglThrows = false;
+ (globalThis as { ResizeObserver: unknown }).ResizeObserver = MockResizeObserver;
+ });
+ afterEach(() => {
+ cleanup();
+ });
+
+ test('mounts an accessible region, configures xterm for a11y, and creates a PTY sized to the fitted terminal', async () => {
+ const { bridge, terminal } = makeBridge({ ok: true, ptyId: 'pty-1' });
+ render(<TerminalPanel bridge={bridge} />);
+
+ const region = screen.getByRole('region', { name: 'Terminal' });
+ expect(region).toBeTruthy();
+
+ expect(lastTerm?.options.screenReaderMode).toBe(true);
+ expect(lastTerm?.options.minimumContrastRatio).toBe(4.5);
+ expect(lastTerm?.unicode.activeVersion).toBe('11');
+
+ await waitFor(() => expect(terminal.create).toHaveBeenCalledTimes(1));
+ expect(terminal.create).toHaveBeenCalledWith({ cols: 80, rows: 24 });
+ });
+
+ test('writes shell output to the terminal and drains the consumed code-unit count for backpressure', async () => {
+ const { bridge, terminal, pushData } = makeBridge({ ok: true, ptyId: 'pty-1' });
+ render(<TerminalPanel bridge={bridge} />);
+ await waitFor(() => expect(terminal.onData).toHaveBeenCalledTimes(1));
+
+ const payload = 'hi🎉';
+ expect(payload.length).toBe(4);
+ act(() => pushData({ ptyId: 'pty-1', data: payload }));
+
+ expect(lastTerm?.write).toHaveBeenCalledTimes(1);
+ expect(lastTerm?.write.mock.calls[0]?.[0]).toBe(payload);
+ expect(terminal.drain).toHaveBeenCalledWith('pty-1', payload.length);
+ });
+
+ test('forwards user keystrokes to the PTY via input', async () => {
+ const { bridge, terminal } = makeBridge({ ok: true, ptyId: 'pty-1' });
+ render(<TerminalPanel bridge={bridge} />);
+ await waitFor(() => expect(lastTerm?.onDataCb).toBeTruthy());
+
+ act(() => lastTerm?.onDataCb?.('ls\r'));
+ expect(terminal.input).toHaveBeenCalledWith('pty-1', 'ls\r');
+ });
+
+ test('re-fits and resizes the PTY when the container resizes', async () => {
+ const { bridge, terminal } = makeBridge({ ok: true, ptyId: 'pty-1' });
+ render(<TerminalPanel bridge={bridge} />);
+ await waitFor(() => expect(roCallback).toBeTruthy());
+
+ const fitsBefore = lastFit?.fit.mock.calls.length ?? 0;
+ act(() => roCallback?.());
+
+ expect(lastFit?.fit.mock.calls.length ?? 0).toBeGreaterThan(fitsBefore);
+ expect(terminal.resize).toHaveBeenCalledWith('pty-1', 80, 24);
+ });
+
+ test('does not intercept keys — Escape and all keystrokes reach the PTY', async () => {
+ const { bridge, terminal } = makeBridge({ ok: true, ptyId: 'pty-1' });
+ render(<TerminalPanel bridge={bridge} />);
+ await waitFor(() => expect(lastTerm?.onDataCb).toBeTruthy());
+
+ expect(lastTerm?.attachCustomKeyEventHandler).not.toHaveBeenCalled();
+ expect(lastTerm?.keyHandler).toBeNull();
+
+ act(() => lastTerm?.onDataCb?.('\x1b'));
+ expect(terminal.input).toHaveBeenCalledWith('pty-1', '\x1b');
+ });
+
+ test('disposes the terminal, kills the PTY, and unsubscribes on unmount', async () => {
+ const { bridge, terminal, unsubData, unsubExit } = makeBridge({ ok: true, ptyId: 'pty-1' });
+ const { unmount } = render(<TerminalPanel bridge={bridge} />);
+ await waitFor(() => expect(roCallback).toBeTruthy());
+
+ const term = lastTerm;
+ const ro = lastRO;
+ act(() => unmount());
+
+ expect(term?.dispose).toHaveBeenCalledTimes(1);
+ expect(terminal.kill).toHaveBeenCalledWith('pty-1');
+ expect(unsubData).toHaveBeenCalledTimes(1);
+ expect(unsubExit).toHaveBeenCalledTimes(1);
+ expect(ro?.disconnect).toHaveBeenCalledTimes(1);
+ });
+
+ test('degrades to the DOM renderer when WebGL is unavailable instead of failing the mount', async () => {
+ webglThrows = true;
+ const { bridge, terminal, pushData } = makeBridge({ ok: true, ptyId: 'pty-1' });
+ render(<TerminalPanel bridge={bridge} />);
+
+ await waitFor(() => expect(terminal.onData).toHaveBeenCalledTimes(1));
+ act(() => pushData({ ptyId: 'pty-1', data: 'ok' }));
+ expect(lastTerm?.write).toHaveBeenCalledTimes(1);
+ });
+
+ test('ignores data addressed to a different PTY', async () => {
+ const { bridge, terminal, pushData } = makeBridge({ ok: true, ptyId: 'pty-1' });
+ render(<TerminalPanel bridge={bridge} />);
+ await waitFor(() => expect(terminal.onData).toHaveBeenCalledTimes(1));
+
+ act(() => pushData({ ptyId: 'someone-else', data: 'leak' }));
+ expect(lastTerm?.write).not.toHaveBeenCalled();
+ expect(terminal.drain).not.toHaveBeenCalled();
+
+ act(() => pushData({ ptyId: 'pty-1', data: 'mine' }));
+ expect(lastTerm?.write).toHaveBeenCalledTimes(1);
+ expect(lastTerm?.write.mock.calls[0]?.[0]).toBe('mine');
+ });
+
+ test('reports the no-project state and wires no data stream when the window has no project', async () => {
+ const { bridge, terminal } = makeBridge({ ok: false, reason: 'no-project' });
+ render(<TerminalPanel bridge={bridge} />);
+
+ await waitFor(() =>
+ expect(document.querySelector('[data-terminal-status="no-project"]')).not.toBeNull(),
+ );
+ expect(terminal.onData).not.toHaveBeenCalled();
+ expect(terminal.drain).not.toHaveBeenCalled();
+ expect(screen.getByRole('region', { name: 'Terminal' })).toBeTruthy();
+ const alert = await screen.findByRole('alert');
+ expect(alert.textContent).toMatch(/no project folder/i);
+ expect(lastTerm?.focus).not.toHaveBeenCalled();
+ });
+
+ test('renders a refusal notice (not a blank canvas) when main refuses with not-consented', async () => {
+ const onClose = mock(() => {});
+ const { bridge, terminal } = makeBridge({ ok: false, reason: 'not-consented' });
+ render(<TerminalPanel bridge={bridge} onClose={onClose} />);
+
+ await waitFor(() =>
+ expect(document.querySelector('[data-terminal-status="not-consented"]')).not.toBeNull(),
+ );
+ const alert = await screen.findByRole('alert');
+ expect(alert.textContent).toMatch(/isn't enabled for this project/i);
+ expect(lastTerm?.focus).not.toHaveBeenCalled();
+ expect(terminal.onData).not.toHaveBeenCalled();
+ const closeButton = screen.getByRole('button', { name: 'Close terminal' });
+ fireEvent.click(closeButton);
+ expect(onClose).toHaveBeenCalledTimes(1);
+ });
+
+ test('omits the "Close terminal" button when no onClose is provided', async () => {
+ const { bridge } = makeBridge({ ok: false, reason: 'not-consented' });
+ render(<TerminalPanel bridge={bridge} />);
+
+ await waitFor(() =>
+ expect(document.querySelector('[data-terminal-status="not-consented"]')).not.toBeNull(),
+ );
+ await screen.findByRole('alert');
+ expect(screen.queryByRole('button', { name: 'Close terminal' })).toBeNull();
+ });
+
+ test('reaps a PTY that finishes spawning after the panel has already unmounted', async () => {
+ let resolveCreate: ((r: CreateResult) => void) | undefined;
+ const createPromise = new Promise<CreateResult>((res) => {
+ resolveCreate = res;
+ });
+ const kill = mock(async (_id: string) => {});
+ const terminal = {
+ create: mock(() => createPromise),
+ input: mock(() => {}),
+ resize: mock(() => {}),
+ kill,
+ drain: mock(() => {}),
+ onData: mock(() => mock(() => {})),
+ onExit: mock(() => mock(() => {})),
+ };
+ const bridge = { terminal } as unknown as OkDesktopBridge;
+
+ const { unmount } = render(<TerminalPanel bridge={bridge} />);
+ await waitFor(() => expect(terminal.create).toHaveBeenCalledTimes(1));
+
+ act(() => unmount());
+ await act(async () => {
+ resolveCreate?.({ ok: true, ptyId: 'pty-late' });
+ await createPromise;
+ });
+
+ expect(kill).toHaveBeenCalledWith('pty-late');
+ expect(terminal.onData).not.toHaveBeenCalled();
+ });
+
+ test('probes Claude readiness once the shell is live and shows a help affordance when claude is not on PATH', async () => {
+ const { bridge, terminal, openExternal } = makeBridge(
+ { ok: true, ptyId: 'pty-1' },
+ { claude: 'not-found', mcp: 'needs-rewire' },
+ );
+ render(<TerminalPanel bridge={bridge} />);
+
+ await waitFor(() => expect(terminal.claudePreflight).toHaveBeenCalledTimes(1));
+ expect(await screen.findByText(/isn't installed or on your PATH/)).toBeTruthy();
+
+ fireEvent.click(screen.getByRole('button', { name: 'Get Claude Code' }));
+ expect(openExternal).toHaveBeenCalledTimes(1);
+ expect(openExternal.mock.calls[0]?.[0]).toContain('claude-code');
+ });
+
+ test('shows a re-wire affordance when claude is present but OK tools are not wired', async () => {
+ const { bridge, rewireClaudeMcp } = makeBridge(
+ { ok: true, ptyId: 'pty-1' },
+ { claude: 'present', mcp: 'needs-rewire' },
+ );
+ render(<TerminalPanel bridge={bridge} />);
+
+ expect(await screen.findByText(/aren't connected to it yet/)).toBeTruthy();
+ fireEvent.click(screen.getByRole('button', { name: 'Connect tools' }));
+ expect(rewireClaudeMcp).toHaveBeenCalledTimes(1);
+ await waitFor(() => expect(screen.queryByRole('status')).toBeNull());
+ });
+
+ test('shows no readiness banner when claude is present and OK tools are wired', async () => {
+ const { bridge, terminal } = makeBridge({ ok: true, ptyId: 'pty-1' }, WIRED);
+ render(<TerminalPanel bridge={bridge} />);
+
+ await waitFor(() => expect(terminal.claudePreflight).toHaveBeenCalledTimes(1));
+ await act(async () => {
+ await Promise.resolve();
+ });
+ expect(screen.queryByRole('status')).toBeNull();
+ });
+
+ test('the readiness banner is dismissible', async () => {
+ const { bridge } = makeBridge(
+ { ok: true, ptyId: 'pty-1' },
+ { claude: 'not-found', mcp: 'needs-rewire' },
+ );
+ render(<TerminalPanel bridge={bridge} />);
+
+ await screen.findByText(/isn't installed or on your PATH/);
+ fireEvent.click(screen.getByRole('button', { name: 'Dismiss' }));
+ await waitFor(() => expect(screen.queryByText(/isn't installed or on your PATH/)).toBeNull());
+ });
+
+ test('surfaces a restartable error state when create() rejects (startup failure, no silent dead-end)', async () => {
+ let resolveCreate: (() => void) | undefined;
+ let createCalls = 0;
+ const createGate = new Promise<void>((res) => {
+ resolveCreate = res;
+ });
+ const terminal = {
+ create: mock(async () => {
+ createCalls += 1;
+ if (createCalls === 1) throw new Error('fork EMFILE');
+ await createGate;
+ return { ok: true, ptyId: 'pty-restarted' } as const;
+ }),
+ input: mock(() => {}),
+ resize: mock(() => {}),
+ kill: mock(async () => {}),
+ drain: mock(() => {}),
+ onData: mock(() => mock(() => {})),
+ onExit: mock(() => mock(() => {})),
+ claudePreflight: mock(async () => WIRED),
+ rewireClaudeMcp: mock(async () => WIRED),
+ };
+ const bridge = {
+ terminal,
+ shell: { openExternal: mock(async () => {}) },
+ } as unknown as OkDesktopBridge;
+
+ render(<TerminalPanel bridge={bridge} />);
+
+ expect(await screen.findByRole('alert')).toBeTruthy();
+ const restart = screen.getByRole('button', { name: 'Restart terminal' });
+
+ fireEvent.click(restart);
+ await waitFor(() => expect(terminal.create).toHaveBeenCalledTimes(2));
+ await act(async () => {
+ resolveCreate?.();
+ await Promise.resolve();
+ });
+ await waitFor(() => expect(screen.queryByRole('alert')).toBeNull());
+ });
+
+ test('renders a visible exit state with a restart affordance when the shell exits', async () => {
+ const { bridge, terminal, pushExit } = makeBridge({ ok: true, ptyId: 'pty-1' });
+ render(<TerminalPanel bridge={bridge} />);
+ await waitFor(() => expect(terminal.onExit).toHaveBeenCalledTimes(1));
+
+ act(() => pushExit({ ptyId: 'pty-1', exitCode: 1, signal: null }));
+
+ expect(screen.getByRole('alert')).toBeTruthy();
+ expect(screen.getByText(/exit code 1/)).toBeTruthy();
+ expect(screen.getByRole('button', { name: 'Restart terminal' })).toBeTruthy();
+ });
+
+ test('Restart spawns a fresh PTY in the same window and clears the exit state', async () => {
+ const { bridge, terminal, pushExit } = makeBridge({ ok: true, ptyId: 'pty-1' });
+ render(<TerminalPanel bridge={bridge} />);
+ await waitFor(() => expect(terminal.create).toHaveBeenCalledTimes(1));
+
+ act(() => pushExit({ ptyId: 'pty-1', exitCode: 0, signal: null }));
+ fireEvent.click(screen.getByRole('button', { name: 'Restart terminal' }));
+
+ await waitFor(() => expect(terminal.create).toHaveBeenCalledTimes(2));
+ await waitFor(() => expect(screen.queryByRole('alert')).toBeNull());
+ });
+
+ test('hides the Claude readiness banner once the shell has exited', async () => {
+ const { bridge, pushExit } = makeBridge(
+ { ok: true, ptyId: 'pty-1' },
+ { claude: 'not-found', mcp: 'needs-rewire' },
+ );
+ render(<TerminalPanel bridge={bridge} />);
+
+ await screen.findByText(/isn't installed or on your PATH/);
+
+ act(() => pushExit({ ptyId: 'pty-1', exitCode: 0, signal: null }));
+ await waitFor(() => expect(screen.queryByText(/isn't installed or on your PATH/)).toBeNull());
+ expect(screen.getByRole('alert')).toBeTruthy();
+ });
+});
diff --git a/packages/app/src/components/TerminalPanel.launch.dom.test.tsx b/packages/app/src/components/TerminalPanel.launch.dom.test.tsx
new file mode 100644
index 000000000..a361bafb4
--- /dev/null
+++ b/packages/app/src/components/TerminalPanel.launch.dom.test.tsx
@@ -0,0 +1,191 @@
+import { afterEach, beforeEach, describe, expect, mock, test } from 'bun:test';
+import { act, cleanup, render, waitFor } from '@testing-library/react';
+import type { ClaudeReadiness, OkDesktopBridge, OkPtyData } from '@/lib/desktop-bridge-types';
+
+class MockFitAddon {
+ fit = mock(() => {});
+}
+class MockWebglAddon {}
+class MockWebLinksAddon {}
+class MockUnicode11Addon {}
+
+class MockTerminal {
+ cols = 80;
+ rows = 24;
+ unicode = { activeVersion: '6' };
+ onDataCb: ((d: string) => void) | null = null;
+ keyHandler: ((e: KeyboardEvent) => boolean) | null = null;
+ options: Record<string, unknown>;
+ open = mock(() => {});
+ focus = mock(() => {});
+ dispose = mock(() => {});
+ write = mock((_data: string, cb?: () => void) => {
+ cb?.();
+ });
+ loadAddon = mock(() => {});
+ onData = mock((cb: (d: string) => void) => {
+ this.onDataCb = cb;
+ return { dispose() {} };
+ });
+ attachCustomKeyEventHandler = mock((h: (e: KeyboardEvent) => boolean) => {
+ this.keyHandler = h;
+ });
+ constructor(options: Record<string, unknown>) {
+ this.options = options;
+ }
+}
+
+class MockResizeObserver {
+ observe = mock(() => {});
+ unobserve = mock(() => {});
+ disconnect = mock(() => {});
+}
+
+mock.module('@xterm/xterm', () => ({ Terminal: MockTerminal }));
+mock.module('@xterm/addon-fit', () => ({ FitAddon: MockFitAddon }));
+mock.module('@xterm/addon-webgl', () => ({ WebglAddon: MockWebglAddon }));
+mock.module('@xterm/addon-web-links', () => ({ WebLinksAddon: MockWebLinksAddon }));
+mock.module('@xterm/addon-unicode11', () => ({ Unicode11Addon: MockUnicode11Addon }));
+mock.module('@xterm/xterm/css/xterm.css', () => ({}));
+
+const WIRED: ClaudeReadiness = { claude: 'present', mcp: 'wired' };
+
+function makeBridge(preflight: ClaudeReadiness = WIRED) {
+ const dataSubs: Array<(m: OkPtyData) => void> = [];
+ const terminal = {
+ create: mock(async () => ({ ok: true as const, ptyId: 'pty-1' })),
+ input: mock((_id: string, _d: string) => {}),
+ resize: mock(() => {}),
+ kill: mock(async () => {}),
+ drain: mock(() => {}),
+ onData: mock((cb: (m: OkPtyData) => void) => {
+ dataSubs.push(cb);
+ return mock(() => {});
+ }),
+ onExit: mock(() => mock(() => {})),
+ claudePreflight: mock(async () => preflight),
+ rewireClaudeMcp: mock(async () => preflight),
+ };
+ return {
+ bridge: {
+ terminal,
+ shell: { openExternal: mock(async () => {}) },
+ } as unknown as OkDesktopBridge,
+ terminal,
+ pushData: (m: OkPtyData) => {
+ for (const f of dataSubs) f(m);
+ },
+ };
+}
+
+const { TerminalPanel } = await import('./TerminalPanel');
+
+/** Inputs the user typed are forwarded verbatim; the launch is the only call
+ * that goes through `buildClaudeLaunchCommand`. Filter to the launch shape. */
+function launchWrites(inputMock: ReturnType<typeof mock>): string[] {
+ return inputMock.mock.calls
+ .map((c) => c[1] as string)
+ .filter((d) => typeof d === 'string' && d.startsWith('claude '));
+}
+
+describe('TerminalPanel "Open in terminal" launch', () => {
+ beforeEach(() => {
+ (globalThis as { ResizeObserver: unknown }).ResizeObserver = MockResizeObserver;
+ });
+ afterEach(() => {
+ cleanup();
+ });
+
+ test("writes `claude '<escaped prompt>'` exactly once on running, after first output", async () => {
+ const { bridge, terminal, pushData } = makeBridge(WIRED);
+ const prompt = "Let's work on `foo.md` using Open Knowledge.";
+ const { rerender } = render(<TerminalPanel bridge={bridge} launch={{ prompt, nonce: 1 }} />);
+
+ await waitFor(() => expect(terminal.onData).toHaveBeenCalledTimes(1));
+ act(() => pushData({ ptyId: 'pty-1', data: '$ ' }));
+ await waitFor(() => expect(terminal.claudePreflight).toHaveBeenCalledTimes(1));
+
+ await waitFor(() => expect(launchWrites(terminal.input).length).toBe(1));
+ expect(launchWrites(terminal.input)[0]).toBe(
+ "claude 'Let'\\''s work on `foo.md` using Open Knowledge.'\r",
+ );
+
+ rerender(<TerminalPanel bridge={bridge} launch={{ prompt, nonce: 1 }} />);
+ await act(async () => {
+ await Promise.resolve();
+ });
+ expect(launchWrites(terminal.input).length).toBe(1);
+ });
+
+ test('does NOT write a launch before the shell is running', async () => {
+ const terminal = {
+ create: mock(() => new Promise(() => {})),
+ input: mock(() => {}),
+ resize: mock(() => {}),
+ kill: mock(async () => {}),
+ drain: mock(() => {}),
+ onData: mock(() => mock(() => {})),
+ onExit: mock(() => mock(() => {})),
+ claudePreflight: mock(async () => WIRED),
+ rewireClaudeMcp: mock(async () => WIRED),
+ };
+ const bridge = {
+ terminal,
+ shell: { openExternal: mock(async () => {}) },
+ } as unknown as OkDesktopBridge;
+
+ render(<TerminalPanel bridge={bridge} launch={{ prompt: 'hi', nonce: 1 }} />);
+ await waitFor(() => expect(terminal.create).toHaveBeenCalledTimes(1));
+ await act(async () => {
+ await Promise.resolve();
+ });
+ expect(launchWrites(terminal.input).length).toBe(0);
+ });
+
+ test('does NOT write the command when claude is not found (the banner handles remediation)', async () => {
+ const { bridge, terminal, pushData } = makeBridge({
+ claude: 'not-found',
+ mcp: 'needs-rewire',
+ });
+ render(<TerminalPanel bridge={bridge} launch={{ prompt: 'hi', nonce: 1 }} />);
+
+ await waitFor(() => expect(terminal.onData).toHaveBeenCalledTimes(1));
+ act(() => pushData({ ptyId: 'pty-1', data: '$ ' }));
+ await waitFor(() => expect(terminal.claudePreflight).toHaveBeenCalledTimes(1));
+ await act(async () => {
+ await Promise.resolve();
+ });
+
+ expect(launchWrites(terminal.input).length).toBe(0);
+ });
+
+ test('launches when claude is present even if OK tools need a rewire (claude still runs)', async () => {
+ const { bridge, terminal, pushData } = makeBridge({
+ claude: 'present',
+ mcp: 'needs-rewire',
+ });
+ render(<TerminalPanel bridge={bridge} launch={{ prompt: 'hi', nonce: 1 }} />);
+
+ await waitFor(() => expect(terminal.onData).toHaveBeenCalledTimes(1));
+ act(() => pushData({ ptyId: 'pty-1', data: '$ ' }));
+ await waitFor(() => expect(terminal.claudePreflight).toHaveBeenCalledTimes(1));
+
+ await waitFor(() => expect(launchWrites(terminal.input).length).toBe(1));
+ expect(launchWrites(terminal.input)[0]).toBe("claude 'hi'\r");
+ });
+
+ test('a new nonce fires a second launch (repeat "Open in terminal" while running)', async () => {
+ const { bridge, terminal, pushData } = makeBridge(WIRED);
+ const { rerender } = render(
+ <TerminalPanel bridge={bridge} launch={{ prompt: 'first', nonce: 1 }} />,
+ );
+
+ await waitFor(() => expect(terminal.onData).toHaveBeenCalledTimes(1));
+ act(() => pushData({ ptyId: 'pty-1', data: '$ ' }));
+ await waitFor(() => expect(launchWrites(terminal.input).length).toBe(1));
+
+ rerender(<TerminalPanel bridge={bridge} launch={{ prompt: 'second', nonce: 2 }} />);
+ await waitFor(() => expect(launchWrites(terminal.input).length).toBe(2));
+ expect(launchWrites(terminal.input)[1]).toBe("claude 'second'\r");
+ });
+});
diff --git a/packages/app/src/components/TerminalPanel.tsx b/packages/app/src/components/TerminalPanel.tsx
new file mode 100644
index 000000000..9d5a34879
--- /dev/null
+++ b/packages/app/src/components/TerminalPanel.tsx
@@ -0,0 +1,233 @@
+import '@xterm/xterm/css/xterm.css';
+
+import { buildClaudeLaunchCommand } from '@inkeep/open-knowledge-core';
+import { useLingui } from '@lingui/react/macro';
+import { FitAddon } from '@xterm/addon-fit';
+import { Unicode11Addon } from '@xterm/addon-unicode11';
+import { WebLinksAddon } from '@xterm/addon-web-links';
+import { WebglAddon } from '@xterm/addon-webgl';
+import { Terminal } from '@xterm/xterm';
+import { useEffect, useRef, useState } from 'react';
+import type { ClaudeReadiness, OkDesktopBridge } from '@/lib/desktop-bridge-types';
+import { cn } from '@/lib/utils';
+import { ClaudeReadinessBanner } from './ClaudeReadinessBanner';
+import type { TerminalLaunchIntent } from './EditorPane';
+import { type TerminalExitInfo, TerminalExitNotice } from './TerminalExitNotice';
+import { TerminalRefusalNotice } from './TerminalRefusalNotice';
+
+interface TerminalPanelProps {
+ /** Desktop bridge — the panel is rendered only on the Electron host, where
+ * `window.okDesktop` is present. */
+ readonly bridge: OkDesktopBridge;
+ readonly className?: string;
+ readonly onClose?: () => void;
+ readonly onExit?: (info: { readonly exitCode: number; readonly signal: number | null }) => void;
+ readonly launch?: TerminalLaunchIntent | null;
+}
+
+export function TerminalPanel({
+ bridge,
+ className,
+ onClose,
+ onExit,
+ launch = null,
+}: TerminalPanelProps) {
+ const { t } = useLingui();
+ const [restartKey, setRestartKey] = useState(0);
+ return (
+ <section
+ aria-label={t`Terminal`}
+ className={cn('relative h-full w-full overflow-hidden bg-[#1e1e1e]', className)}
+ >
+ <TerminalSession
+ key={restartKey}
+ bridge={bridge}
+ onClose={onClose}
+ onExit={onExit}
+ onRestart={() => setRestartKey((k) => k + 1)}
+ launch={launch}
+ />
+ </section>
+ );
+}
+
+type SessionStatus = 'starting' | 'running' | 'no-project' | 'not-consented' | 'exited';
+
+interface TerminalSessionProps {
+ readonly bridge: OkDesktopBridge;
+ readonly onClose?: () => void;
+ readonly onExit?: (info: { readonly exitCode: number; readonly signal: number | null }) => void;
+ readonly onRestart: () => void;
+ readonly launch?: TerminalLaunchIntent | null;
+}
+
+function TerminalSession({
+ bridge,
+ onClose,
+ onExit,
+ onRestart,
+ launch = null,
+}: TerminalSessionProps) {
+ const containerRef = useRef<HTMLDivElement | null>(null);
+ const onExitRef = useRef(onExit);
+ const [status, setStatus] = useState<SessionStatus>('starting');
+ const [readiness, setReadiness] = useState<ClaudeReadiness | null>(null);
+ const [preflightDone, setPreflightDone] = useState(false);
+ const [exitInfo, setExitInfo] = useState<TerminalExitInfo | null>(null);
+ const ptyIdRef = useRef<string | null>(null);
+ const [firstOutputSeen, setFirstOutputSeen] = useState(false);
+ const lastLaunchedNonceRef = useRef<number | null>(null);
+
+ useEffect(() => {
+ onExitRef.current = onExit;
+ });
+
+ useEffect(() => {
+ const container = containerRef.current;
+ if (!container) return;
+
+ let cancelled = false;
+ let ptyId: string | null = null;
+ let unsubData: (() => void) | undefined;
+ let unsubExit: (() => void) | undefined;
+ let observer: ResizeObserver | undefined;
+
+ const term = new Terminal({
+ screenReaderMode: true,
+ minimumContrastRatio: 4.5,
+ allowProposedApi: true,
+ cursorBlink: true,
+ fontFamily: 'ui-monospace, SFMono-Regular, Menlo, Monaco, monospace',
+ fontSize: 13,
+ theme: { background: '#1e1e1e', foreground: '#d4d4d4' },
+ });
+ const fit = new FitAddon();
+ term.loadAddon(fit);
+ term.loadAddon(new Unicode11Addon());
+ term.unicode.activeVersion = '11';
+ term.loadAddon(new WebLinksAddon());
+
+ term.open(container);
+
+ try {
+ term.loadAddon(new WebglAddon());
+ } catch (err) {
+ console.warn('[terminal] WebGL addon failed, using DOM renderer:', err);
+ }
+
+ fit.fit();
+
+ void (async () => {
+ let result: Awaited<ReturnType<typeof bridge.terminal.create>>;
+ try {
+ result = await bridge.terminal.create({ cols: term.cols, rows: term.rows });
+ } catch (err) {
+ if (cancelled) return;
+ setExitInfo({ exitCode: 1, signal: null, error: (err as Error).message });
+ setStatus('exited');
+ return;
+ }
+
+ if (cancelled) {
+ if (result.ok)
+ void bridge.terminal
+ .kill(result.ptyId)
+ .catch((err) => console.warn('[terminal] kill after cancelled mount failed:', err));
+ return;
+ }
+ if (!result.ok) {
+ setStatus(result.reason === 'not-consented' ? 'not-consented' : 'no-project');
+ return;
+ }
+
+ ptyId = result.ptyId;
+ ptyIdRef.current = result.ptyId;
+ setStatus('running');
+
+ term.onData((data) => {
+ if (ptyId) bridge.terminal.input(ptyId, data);
+ });
+
+ unsubData = bridge.terminal.onData((msg) => {
+ if (msg.ptyId !== ptyId) return;
+ if (!cancelled) setFirstOutputSeen(true);
+ term.write(msg.data, () => bridge.terminal.drain(msg.ptyId, msg.data.length));
+ });
+
+ unsubExit = bridge.terminal.onExit((msg) => {
+ if (msg.ptyId !== ptyId) return;
+ setExitInfo({ exitCode: msg.exitCode, signal: msg.signal, error: msg.error });
+ setStatus('exited');
+ onExitRef.current?.({ exitCode: msg.exitCode, signal: msg.signal });
+ });
+
+ observer = new ResizeObserver(() => {
+ fit.fit();
+ if (ptyId) bridge.terminal.resize(ptyId, term.cols, term.rows);
+ });
+ observer.observe(container);
+
+ term.focus();
+
+ bridge.terminal
+ .claudePreflight()
+ .then((readinessResult) => {
+ if (!cancelled) setReadiness(readinessResult);
+ })
+ .catch((err) => {
+ console.warn('[terminal] claude readiness preflight failed', err);
+ })
+ .finally(() => {
+ if (!cancelled) setPreflightDone(true);
+ });
+ })();
+
+ return () => {
+ cancelled = true;
+ ptyIdRef.current = null;
+ observer?.disconnect();
+ unsubData?.();
+ unsubExit?.();
+ term.dispose();
+ if (ptyId)
+ void bridge.terminal
+ .kill(ptyId)
+ .catch((err) => console.warn('[terminal] kill on unmount failed:', err));
+ };
+ }, [bridge]);
+
+ useEffect(() => {
+ if (launch === null) return;
+ if (status !== 'running') return;
+ if (!firstOutputSeen) return;
+ if (!preflightDone) return;
+ if (lastLaunchedNonceRef.current === launch.nonce) return;
+ const ptyId = ptyIdRef.current;
+ if (ptyId === null) return;
+ if (readiness?.claude === 'not-found') {
+ lastLaunchedNonceRef.current = launch.nonce;
+ return;
+ }
+ lastLaunchedNonceRef.current = launch.nonce;
+ bridge.terminal.input(ptyId, buildClaudeLaunchCommand(launch.prompt));
+ }, [bridge, launch, status, firstOutputSeen, preflightDone, readiness]);
+
+ return (
+ <div className="flex h-full w-full flex-col">
+ {status === 'running' && readiness ? (
+ <ClaudeReadinessBanner
+ readiness={readiness}
+ bridge={bridge}
+ onDismiss={() => setReadiness(null)}
+ />
+ ) : null}
+ <div ref={containerRef} data-terminal-status={status} className="min-h-0 flex-1" />
+ {status === 'exited' && exitInfo ? (
+ <TerminalExitNotice info={exitInfo} onRestart={onRestart} />
+ ) : null}
+ {status === 'no-project' || status === 'not-consented' ? (
+ <TerminalRefusalNotice reason={status} onClose={onClose} />
+ ) : null}
+ </div>
+ );
+}
diff --git a/packages/app/src/components/TerminalRefusalNotice.tsx b/packages/app/src/components/TerminalRefusalNotice.tsx
new file mode 100644
index 000000000..a8d033251
--- /dev/null
+++ b/packages/app/src/components/TerminalRefusalNotice.tsx
@@ -0,0 +1,30 @@
+import { useLingui } from '@lingui/react/macro';
+import { Button } from '@/components/ui/button';
+
+interface TerminalRefusalNoticeProps {
+ readonly reason: 'no-project' | 'not-consented';
+ readonly onClose?: () => void;
+}
+
+export function TerminalRefusalNotice({ reason, onClose }: TerminalRefusalNoticeProps) {
+ const { t } = useLingui();
+
+ const message =
+ reason === 'not-consented'
+ ? t`Terminal access isn't enabled for this project.`
+ : t`There's no project folder for this window, so a terminal can't start here.`;
+
+ return (
+ <div
+ role="alert"
+ className="absolute inset-0 z-20 flex flex-col items-center justify-center gap-3 bg-[#1e1e1e]/90 p-6 text-center text-[#d4d4d4]"
+ >
+ <p className="max-w-sm text-sm">{message}</p>
+ {onClose ? (
+ <Button size="sm" variant="secondary" onClick={onClose}>
+ {t`Close terminal`}
+ </Button>
+ ) : null}
+ </div>
+ );
+}
diff --git a/packages/app/src/components/handoff/OpenInAgentContextSubmenu.tsx b/packages/app/src/components/handoff/OpenInAgentContextSubmenu.tsx
index 720bdb3d3..a2cd8f44f 100644
--- a/packages/app/src/components/handoff/OpenInAgentContextSubmenu.tsx
+++ b/packages/app/src/components/handoff/OpenInAgentContextSubmenu.tsx
@@ -6,10 +6,11 @@ import {
} from '@inkeep/open-knowledge-core';
import { t } from '@lingui/core/macro';
import { Trans, useLingui } from '@lingui/react/macro';
-import { ExternalLink, Sparkles } from 'lucide-react';
+import { ExternalLink, Sparkles, SquareTerminal } from 'lucide-react';
import type { ReactNode } from 'react';
import {
DropdownMenuItem,
+ DropdownMenuSeparator,
DropdownMenuSub,
DropdownMenuSubContent,
DropdownMenuSubTrigger,
@@ -18,6 +19,7 @@ import { useIsEmbedded } from '@/hooks/use-is-embedded';
import { useConfigContext } from '@/lib/config-context';
import { VISIBLE_TARGETS } from '@/lib/handoff/targets';
import { dispatchClaudeWebFallback, TargetIcon } from './OpenInAgentMenuItem';
+import { useTerminalLaunch } from './TerminalLaunchContext';
import type { HandoffDispatchInput } from './useHandoffDispatch';
export function contextRowHint(inputMissing: boolean): string | null {
@@ -56,6 +58,7 @@ export function OpenInAgentContextSubmenu(props: OpenInAgentContextSubmenuProps)
const { t } = useLingui();
const isEmbedded = useIsEmbedded();
const { merged } = useConfigContext();
+ const terminalLaunch = useTerminalLaunch();
const autoOpen = merged?.appearance?.preview?.autoOpen ?? true;
if (isEmbedded) return null;
const { input, installStates, dispatch, webFallbackVisible = true } = props;
@@ -128,6 +131,30 @@ export function OpenInAgentContextSubmenu(props: OpenInAgentContextSubmenuProps)
</span>
</DropdownMenuItem>
) : null}
+ {terminalLaunch !== null ? (
+ <>
+ <DropdownMenuSeparator />
+ <DropdownMenuItem
+ onSelect={() => {
+ if (input === null) return;
+ terminalLaunch.launchInTerminal(input);
+ }}
+ disabled={inputMissing}
+ data-testid="file-tree-open-in-terminal"
+ aria-label={hint ? t`Claude CLI, ${hint}` : t`Claude CLI`}
+ >
+ <SquareTerminal className="size-4" aria-hidden="true" />
+ <span className="flex-1">
+ <Trans>Claude CLI</Trans>
+ </span>
+ {hint ? (
+ <span aria-hidden="true" className="ml-2 text-muted-foreground text-xs">
+ {hint}
+ </span>
+ ) : null}
+ </DropdownMenuItem>
+ </>
+ ) : null}
</DropdownMenuSubContent>
</DropdownMenuSub>
);
diff --git a/packages/app/src/components/handoff/OpenInAgentEmptySpaceSubmenu.tsx b/packages/app/src/components/handoff/OpenInAgentEmptySpaceSubmenu.tsx
index fed29e060..2816d4a8a 100644
--- a/packages/app/src/components/handoff/OpenInAgentEmptySpaceSubmenu.tsx
+++ b/packages/app/src/components/handoff/OpenInAgentEmptySpaceSubmenu.tsx
@@ -6,10 +6,11 @@ import {
} from '@inkeep/open-knowledge-core';
import { t } from '@lingui/core/macro';
import { Trans, useLingui } from '@lingui/react/macro';
-import { ExternalLink, Sparkles } from 'lucide-react';
+import { ExternalLink, Sparkles, SquareTerminal } from 'lucide-react';
import type { ReactNode } from 'react';
import {
ContextMenuItem,
+ ContextMenuSeparator,
ContextMenuSub,
ContextMenuSubContent,
ContextMenuSubTrigger,
@@ -18,6 +19,7 @@ import { useIsEmbedded } from '@/hooks/use-is-embedded';
import { useConfigContext } from '@/lib/config-context';
import { VISIBLE_TARGETS } from '@/lib/handoff/targets';
import { dispatchClaudeWebFallback, TargetIcon } from './OpenInAgentMenuItem';
+import { useTerminalLaunch } from './TerminalLaunchContext';
import type { HandoffDispatchInput } from './useHandoffDispatch';
/** Status hint shown alongside per-target rows when the input is not ready
@@ -52,6 +54,7 @@ export function OpenInAgentEmptySpaceSubmenu(props: OpenInAgentEmptySpaceSubmenu
const { t } = useLingui();
const isEmbedded = useIsEmbedded();
const { merged } = useConfigContext();
+ const terminalLaunch = useTerminalLaunch();
const autoOpen = merged?.appearance?.preview?.autoOpen ?? true;
if (isEmbedded) return null;
const { input, installStates, dispatch, webFallbackVisible = true } = props;
@@ -75,7 +78,8 @@ export function OpenInAgentEmptySpaceSubmenu(props: OpenInAgentEmptySpaceSubmenu
};
const fallbackRowVisible = webFallbackVisible && !claudeInstalled;
- if (installedTargets.length === 0 && !fallbackRowVisible) {
+ const terminalRowVisible = terminalLaunch !== null;
+ if (installedTargets.length === 0 && !fallbackRowVisible && !terminalRowVisible) {
return null;
}
@@ -129,6 +133,30 @@ export function OpenInAgentEmptySpaceSubmenu(props: OpenInAgentEmptySpaceSubmenu
</span>
</ContextMenuItem>
) : null}
+ {terminalLaunch !== null ? (
+ <>
+ <ContextMenuSeparator />
+ <ContextMenuItem
+ onSelect={() => {
+ if (input === null) return;
+ terminalLaunch.launchInTerminal(input);
+ }}
+ disabled={inputMissing}
+ data-testid="empty-space-open-in-terminal"
+ aria-label={hint ? t`Claude CLI, ${hint}` : t`Claude CLI`}
+ >
+ <SquareTerminal className="size-4" aria-hidden="true" />
+ <span className="flex-1">
+ <Trans>Claude CLI</Trans>
+ </span>
+ {hint ? (
+ <span aria-hidden="true" className="ml-2 text-muted-foreground text-xs">
+ {hint}
+ </span>
+ ) : null}
+ </ContextMenuItem>
+ </>
+ ) : null}
</ContextMenuSubContent>
</ContextMenuSub>
);
diff --git a/packages/app/src/components/handoff/OpenInAgentMenu.tsx b/packages/app/src/components/handoff/OpenInAgentMenu.tsx
index b31b526b5..39a71186e 100644
--- a/packages/app/src/components/handoff/OpenInAgentMenu.tsx
+++ b/packages/app/src/components/handoff/OpenInAgentMenu.tsx
@@ -6,7 +6,7 @@ import {
type TargetData,
} from '@inkeep/open-knowledge-core';
import { Trans, useLingui } from '@lingui/react/macro';
-import { ExternalLink, Sparkles } from 'lucide-react';
+import { ExternalLink, Sparkles, SquareTerminal } from 'lucide-react';
import type { ComponentProps, ReactNode } from 'react';
import { useRef, useState } from 'react';
import { Button } from '@/components/ui/button';
@@ -14,6 +14,7 @@ import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
+ DropdownMenuSeparator,
DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
import { useIsEmbedded } from '@/hooks/use-is-embedded';
@@ -24,6 +25,7 @@ import {
OpenInAgentMenuItem,
successToastForWebFallback,
} from './OpenInAgentMenuItem';
+import { useTerminalLaunch } from './TerminalLaunchContext';
import { type HandoffDispatchInput, useHandoffDispatch } from './useHandoffDispatch';
import { useInstalledAgents } from './useInstalledAgents';
@@ -60,6 +62,7 @@ function OpenInAgentMenuContent({
className = 'min-w-[220px]',
}: OpenInAgentMenuContentProps): ReactNode {
const { t } = useLingui();
+ const terminalLaunch = useTerminalLaunch();
const isSelectionScope = Boolean(input?.selection);
const prompt =
input !== null && input.docContext !== null
@@ -123,6 +126,25 @@ function OpenInAgentMenuContent({
</span>
</DropdownMenuItem>
) : null}
+ {terminalLaunch !== null ? (
+ <>
+ <DropdownMenuSeparator />
+ <DropdownMenuItem
+ onSelect={() => {
+ if (input === null) return;
+ terminalLaunch.launchInTerminal(input);
+ }}
+ disabled={input === null}
+ data-testid="open-in-agent-terminal"
+ aria-label={t`Claude CLI`}
+ >
+ <SquareTerminal className="size-4" aria-hidden="true" />
+ <span className="flex-1">
+ <Trans>Claude CLI</Trans>
+ </span>
+ </DropdownMenuItem>
+ </>
+ ) : null}
</DropdownMenuContent>
);
}
diff --git a/packages/app/src/components/handoff/OpenInAgentTerminalRow.dom.test.tsx b/packages/app/src/components/handoff/OpenInAgentTerminalRow.dom.test.tsx
new file mode 100644
index 000000000..cd4c00d5c
--- /dev/null
+++ b/packages/app/src/components/handoff/OpenInAgentTerminalRow.dom.test.tsx
@@ -0,0 +1,85 @@
+import { afterEach, describe, expect, mock, test } from 'bun:test';
+import type { HandoffTarget, InstallState } from '@inkeep/open-knowledge-core';
+import { cleanup, render, screen } from '@testing-library/react';
+import userEvent from '@testing-library/user-event';
+import type { ReactNode } from 'react';
+import { DropdownMenu } from '@/components/ui/dropdown-menu';
+import type { HandoffDispatchInput } from './useHandoffDispatch';
+
+mock.module('@lingui/react/macro', () => ({
+ Trans: ({ children }: { children: ReactNode }) => <>{children}</>,
+ useLingui: () => ({
+ t: (strings: TemplateStringsArray, ...values: unknown[]) =>
+ strings.reduce((acc, part, index) => `${acc}${part}${values[index] ?? ''}`, ''),
+ }),
+}));
+
+mock.module('@/hooks/use-is-embedded', () => ({ useIsEmbedded: () => false }));
+
+const SKIP_IN_CI = process.env.CI === 'true' || process.env.GITHUB_ACTIONS === 'true';
+
+const input: HandoffDispatchInput = {
+ docContext: { relativePath: 'docs/notes.md' },
+ projectDir: '/tmp/project',
+ docPath: '/tmp/project/docs/notes.md',
+};
+
+const installedStates = {
+ 'claude-cowork': { installed: true },
+ 'claude-code': { installed: true },
+ codex: { installed: true },
+ cursor: { installed: true },
+} as unknown as Record<HandoffTarget, InstallState>;
+
+const { OpenInAgentMenuContent } = await import('./OpenInAgentMenu');
+const { TerminalLaunchProvider } = await import('./TerminalLaunchContext');
+
+async function renderContent(opts: {
+ launcher: ((input: HandoffDispatchInput) => void) | null;
+ menuInput?: HandoffDispatchInput | null;
+}) {
+ const menuInput = 'menuInput' in opts ? opts.menuInput : input;
+ render(
+ <TerminalLaunchProvider value={opts.launcher ? { launchInTerminal: opts.launcher } : null}>
+ <DropdownMenu open>
+ <OpenInAgentMenuContent
+ input={menuInput ?? null}
+ states={installedStates}
+ dispatch={() => Promise.resolve({ ok: true as const })}
+ isElectronHost
+ autoOpen
+ />
+ </DropdownMenu>
+ </TerminalLaunchProvider>,
+ );
+}
+
+describe.skipIf(SKIP_IN_CI)('Open-in-Agent "Claude CLI" row', () => {
+ afterEach(() => {
+ cleanup();
+ });
+
+ test('renders the terminal row when the launcher is available (desktop)', async () => {
+ await renderContent({ launcher: () => {} });
+ expect(screen.getByTestId('open-in-agent-terminal')).toBeTruthy();
+ });
+
+ test('hides the terminal row when no launcher is available (web host)', async () => {
+ await renderContent({ launcher: null });
+ expect(screen.queryByTestId('open-in-agent-terminal')).toBeNull();
+ });
+
+ test('clicking the row hands the handoff input to the launcher', async () => {
+ const calls: HandoffDispatchInput[] = [];
+ await renderContent({ launcher: (i) => calls.push(i) });
+ await userEvent.click(screen.getByTestId('open-in-agent-terminal'));
+ expect(calls).toEqual([input]);
+ });
+
+ test('the row does not launch when there is no handoff input', async () => {
+ const calls: HandoffDispatchInput[] = [];
+ await renderContent({ launcher: (i) => calls.push(i), menuInput: null });
+ await userEvent.click(screen.getByTestId('open-in-agent-terminal'));
+ expect(calls).toEqual([]);
+ });
+});
diff --git a/packages/app/src/components/handoff/TerminalLaunchContext.tsx b/packages/app/src/components/handoff/TerminalLaunchContext.tsx
new file mode 100644
index 000000000..8ee5dfcc9
--- /dev/null
+++ b/packages/app/src/components/handoff/TerminalLaunchContext.tsx
@@ -0,0 +1,22 @@
+import { createContext, type ReactNode, use } from 'react';
+import type { HandoffDispatchInput } from './useHandoffDispatch';
+
+export interface TerminalLaunchContextValue {
+ readonly launchInTerminal: (input: HandoffDispatchInput) => void;
+}
+
+const TerminalLaunchContext = createContext<TerminalLaunchContextValue | null>(null);
+
+export function TerminalLaunchProvider({
+ value,
+ children,
+}: {
+ readonly value: TerminalLaunchContextValue | null;
+ readonly children: ReactNode;
+}): ReactNode {
+ return <TerminalLaunchContext value={value}>{children}</TerminalLaunchContext>;
+}
+
+export function useTerminalLaunch(): TerminalLaunchContextValue | null {
+ return use(TerminalLaunchContext);
+}
diff --git a/packages/app/src/components/handoff/terminal-launch-events.test.ts b/packages/app/src/components/handoff/terminal-launch-events.test.ts
new file mode 100644
index 000000000..6c7ec8597
--- /dev/null
+++ b/packages/app/src/components/handoff/terminal-launch-events.test.ts
@@ -0,0 +1,17 @@
+import { describe, expect, test } from 'bun:test';
+import { requestTerminalLaunch, subscribeToTerminalLaunchRequests } from './terminal-launch-events';
+
+describe('terminal-launch-events', () => {
+ test('delivers the composed prompt from request to subscriber', () => {
+ const target = new EventTarget();
+ const received: string[] = [];
+ const unsub = subscribeToTerminalLaunchRequests((p) => received.push(p), target);
+
+ requestTerminalLaunch("Let's work on `foo.md` using Open Knowledge.", target);
+ expect(received).toEqual(["Let's work on `foo.md` using Open Knowledge."]);
+
+ unsub();
+ requestTerminalLaunch('after unsubscribe', target);
+ expect(received).toHaveLength(1);
+ });
+});
diff --git a/packages/app/src/components/handoff/terminal-launch-events.ts b/packages/app/src/components/handoff/terminal-launch-events.ts
new file mode 100644
index 000000000..f55eca3ec
--- /dev/null
+++ b/packages/app/src/components/handoff/terminal-launch-events.ts
@@ -0,0 +1,34 @@
+const TERMINAL_LAUNCH_EVENT = 'open-knowledge:terminal-launch';
+
+interface TerminalLaunchDetail {
+ readonly prompt: string;
+}
+
+export function requestTerminalLaunch(
+ prompt: string,
+ target: Pick<Window, 'dispatchEvent'> | EventTarget = typeof window === 'undefined'
+ ? new EventTarget()
+ : window,
+): void {
+ target.dispatchEvent(
+ new CustomEvent<TerminalLaunchDetail>(TERMINAL_LAUNCH_EVENT, { detail: { prompt } }),
+ );
+}
+
+export function subscribeToTerminalLaunchRequests(
+ onRequest: (prompt: string) => void,
+ target: Pick<Window, 'addEventListener' | 'removeEventListener'> | EventTarget = typeof window ===
+ 'undefined'
+ ? new EventTarget()
+ : window,
+): () => void {
+ const listener = (event: Event) => {
+ const prompt =
+ event instanceof CustomEvent
+ ? (event as CustomEvent<TerminalLaunchDetail>).detail?.prompt
+ : undefined;
+ if (typeof prompt === 'string') onRequest(prompt);
+ };
+ target.addEventListener(TERMINAL_LAUNCH_EVENT, listener as EventListener);
+ return () => target.removeEventListener(TERMINAL_LAUNCH_EVENT, listener as EventListener);
+}
diff --git a/packages/app/src/components/settings/SettingsDialogBody.sections.dom.test.tsx b/packages/app/src/components/settings/SettingsDialogBody.sections.dom.test.tsx
index 80087c84b..ac3411b3d 100644
--- a/packages/app/src/components/settings/SettingsDialogBody.sections.dom.test.tsx
+++ b/packages/app/src/components/settings/SettingsDialogBody.sections.dom.test.tsx
@@ -266,6 +266,10 @@ describe('SettingsDialogBody section runtime dispatch', () => {
await renderBody({ activeId: 'project-templates' });
expect(screen.getByTestId('project-templates-section')).not.toBeNull();
expect(screen.queryByRole('dialog')).toBeNull();
+
+ cleanup();
+ await renderBody({ activeId: 'terminal' });
+ expect(screen.getByTestId('settings-terminal-body')).not.toBeNull();
});
test('hotkeys section renders from the shared shortcut registry', async () => {
diff --git a/packages/app/src/components/settings/SettingsDialogBody.tsx b/packages/app/src/components/settings/SettingsDialogBody.tsx
index 6f714491f..82a171b14 100644
--- a/packages/app/src/components/settings/SettingsDialogBody.tsx
+++ b/packages/app/src/components/settings/SettingsDialogBody.tsx
@@ -77,6 +77,7 @@ import {
resolveLeafSchema,
} from './schema-walker';
import type { SlotForwardedProps } from './slot-forwarded-props';
+import { TerminalSection } from './TerminalSection';
import { pickFirstIssueForPath, useConfigForm } from './use-config-form';
type Scope = 'user' | 'project';
@@ -151,6 +152,9 @@ export function SettingsDialogBody({
if (activeId === 'search') {
return <SearchSection />;
}
+ if (activeId === 'terminal') {
+ return <TerminalSection />;
+ }
if (activeId === 'project-templates') {
return <ProjectTemplatesSection />;
}
diff --git a/packages/app/src/components/settings/SettingsDialogShell.terminal.dom.test.tsx b/packages/app/src/components/settings/SettingsDialogShell.terminal.dom.test.tsx
new file mode 100644
index 000000000..dfe0a37ac
--- /dev/null
+++ b/packages/app/src/components/settings/SettingsDialogShell.terminal.dom.test.tsx
@@ -0,0 +1,88 @@
+import { afterEach, beforeEach, describe, expect, mock, test } from 'bun:test';
+import { cleanup, render, screen } from '@testing-library/react';
+import type { ReactNode } from 'react';
+
+mock.module('@inkeep/open-knowledge-core', () => ({
+ SHOW_INSTALL_SKILL: false,
+}));
+
+mock.module('@lingui/react/macro', () => ({
+ Trans: ({ children }: { children?: ReactNode }) => <>{children}</>,
+ useLingui: () => ({
+ t: (strings: TemplateStringsArray | string, ...values: unknown[]) => {
+ if (typeof strings === 'string') return strings;
+ return strings.reduce(
+ (text, chunk, index) =>
+ `${text}${chunk}${index < values.length ? String(values[index]) : ''}`,
+ '',
+ );
+ },
+ }),
+}));
+
+mock.module('@/components/settings/SettingsDialogBodyLazy', () => ({
+ SettingsDialogBodyLazy: () => <div data-testid="settings-body-probe" />,
+}));
+
+mock.module('@/components/ui/dialog', () => ({
+ Dialog: ({ children, open }: { children?: ReactNode; open?: boolean }) =>
+ open ? <div role="dialog">{children}</div> : null,
+ DialogContent: ({ children, ...props }: { children?: ReactNode; [key: string]: unknown }) => (
+ <div {...props}>{children}</div>
+ ),
+ DialogDescription: ({ children }: { children?: ReactNode }) => <p>{children}</p>,
+ DialogTitle: ({ children, id }: { children?: ReactNode; id?: string }) => (
+ <h2 id={id}>{children}</h2>
+ ),
+}));
+
+mock.module('@/components/ui/skeleton', () => ({
+ Skeleton: ({ className }: { className?: string }) => <div className={className} />,
+}));
+
+mock.module('@/editor/DocumentContext', () => ({
+ useDocumentContext: () => ({ collabUrl: 'ws://test.invalid' }),
+}));
+
+mock.module('@/lib/config-provider', () => ({
+ useConfigContext: () => ({
+ userBinding: null,
+ userSynced: false,
+ okignoreBinding: null,
+ okignoreSynced: false,
+ }),
+}));
+
+mock.module('@/lib/handoff/use-claude-desktop-integration', () => ({
+ useClaudeDesktopIntegration: () => ({ desktopPresent: false }),
+}));
+
+const { SettingsDialogShell } = await import('./SettingsDialogShell');
+
+function setDesktopHost(present: boolean) {
+ const w = window as unknown as { okDesktop?: unknown };
+ if (present) w.okDesktop = {};
+ else {
+ w.okDesktop = undefined;
+ }
+}
+
+describe('SettingsDialogShell terminal nav item (desktop-only)', () => {
+ beforeEach(() => setDesktopHost(false));
+ afterEach(() => {
+ cleanup();
+ setDesktopHost(false);
+ });
+
+ test('shows the Terminal section under the Electron host', () => {
+ setDesktopHost(true);
+ render(<SettingsDialogShell open={true} onOpenChange={() => {}} />);
+ expect(screen.getByTestId('settings-sidebar-item-terminal')).not.toBeNull();
+ });
+
+ test('hides the Terminal section on the web host (no okDesktop bridge)', () => {
+ setDesktopHost(false);
+ render(<SettingsDialogShell open={true} onOpenChange={() => {}} />);
+ expect(screen.queryByTestId('settings-sidebar-item-terminal')).toBeNull();
+ });
+});
diff --git a/packages/app/src/components/settings/SettingsDialogShell.tsx b/packages/app/src/components/settings/SettingsDialogShell.tsx
index 715e563b3..bb3828574 100644
--- a/packages/app/src/components/settings/SettingsDialogShell.tsx
+++ b/packages/app/src/components/settings/SettingsDialogShell.tsx
@@ -48,6 +48,8 @@ export function SettingsDialogShell({ open, onOpenChange }: SettingsDialogShellP
const hasProject = collabUrl !== null;
+ const isOkDesktopHost = typeof window !== 'undefined' && window.okDesktop != null;
+
const groups: SidebarGroup[] = [
{
id: 'user',
@@ -66,6 +68,7 @@ export function SettingsDialogShell({ open, onOpenChange }: SettingsDialogShellP
items: [
{ id: 'sync', label: t`Sync` },
{ id: 'search', label: t`Search` },
+ ...(isOkDesktopHost ? [{ id: 'terminal', label: t`Terminal` }] : []),
{ id: 'project-templates', label: t`Templates` },
{ id: 'okignore', label: t`Ignore patterns` },
{ id: 'sharing', label: t`Config sharing` },
diff --git a/packages/app/src/components/settings/TerminalSection.dom.test.tsx b/packages/app/src/components/settings/TerminalSection.dom.test.tsx
new file mode 100644
index 000000000..a6f922354
--- /dev/null
+++ b/packages/app/src/components/settings/TerminalSection.dom.test.tsx
@@ -0,0 +1,98 @@
+import { afterEach, beforeEach, describe, expect, mock, test } from 'bun:test';
+import { act, cleanup, render, screen } from '@testing-library/react';
+import userEvent from '@testing-library/user-event';
+import type { ReactNode } from 'react';
+
+type ConsentState = { enabled: boolean | null; synced: boolean };
+type Writer = ((enabled: boolean) => { ok: true } | { ok: false; error: string }) | null;
+
+let consentState: ConsentState = { enabled: false, synced: true };
+let writerImpl: Writer = null;
+const writerCalls: boolean[] = [];
+// biome-ignore lint/suspicious/noExplicitAny: captured mock-component props
+let consentDialogProps: Record<string, any> | null = null;
+
+mock.module('@lingui/react/macro', () => ({
+ Trans: ({ children }: { children: ReactNode }) => <>{children}</>,
+ useLingui: () => ({
+ t: (strings: TemplateStringsArray, ...values: unknown[]) =>
+ strings.reduce((out, part, index) => `${out}${part}${values[index] ?? ''}`, ''),
+ }),
+}));
+
+mock.module('sonner', () => ({
+ toast: { error: () => {} },
+}));
+
+mock.module('@/hooks/use-terminal-enabled', () => ({
+ useTerminalConsentState: () => consentState,
+ useTerminalEnabledWriter: () => writerImpl,
+}));
+
+mock.module('@/components/TerminalConsentDialog', () => ({
+ // biome-ignore lint/suspicious/noExplicitAny: test stub
+ TerminalConsentDialog: (props: any) => {
+ consentDialogProps = props;
+ return props.open ? <div data-testid="consent-dialog" /> : null;
+ },
+}));
+
+const { TerminalSection } = await import('./TerminalSection');
+
+describe('TerminalSection (Settings revoke toggle)', () => {
+ beforeEach(() => {
+ consentState = { enabled: false, synced: true };
+ writerImpl = (enabled) => {
+ writerCalls.push(enabled);
+ return { ok: true };
+ };
+ writerCalls.length = 0;
+ consentDialogProps = null;
+ });
+ afterEach(() => cleanup());
+
+ test('reflects the granted state as a checked switch', () => {
+ consentState = { enabled: true, synced: true };
+ render(<TerminalSection />);
+ expect((screen.getByRole('switch') as HTMLButtonElement).getAttribute('aria-checked')).toBe(
+ 'true',
+ );
+ });
+
+ test('on → off revokes immediately via writer(false), no dialog', async () => {
+ consentState = { enabled: true, synced: true };
+ render(<TerminalSection />);
+ await userEvent.click(screen.getByRole('switch'));
+ expect(writerCalls).toEqual([false]);
+ expect(screen.queryByTestId('consent-dialog')).toBeNull();
+ });
+
+ test('off → on opens the consent dialog and does not write until accepted', async () => {
+ consentState = { enabled: false, synced: true };
+ render(<TerminalSection />);
+ await userEvent.click(screen.getByRole('switch'));
+
+ expect(consentDialogProps?.open).toBe(true);
+ expect(writerCalls).toEqual([]);
+
+ act(() => consentDialogProps?.onAccept());
+ expect(writerCalls).toEqual([true]);
+ });
+
+ test('off → on then decline leaves the shell off (no write)', async () => {
+ consentState = { enabled: false, synced: true };
+ render(<TerminalSection />);
+ await userEvent.click(screen.getByRole('switch'));
+ act(() => consentDialogProps?.onDecline());
+
+ expect(writerCalls).toEqual([]);
+ expect(consentDialogProps?.open).toBe(false);
+ });
+
+ test('the toggle is disabled until the project-local binding is ready', () => {
+ consentState = { enabled: null, synced: false };
+ writerImpl = null;
+ render(<TerminalSection />);
+ expect((screen.getByRole('switch') as HTMLButtonElement).disabled).toBe(true);
+ });
+});
diff --git a/packages/app/src/components/settings/TerminalSection.tsx b/packages/app/src/components/settings/TerminalSection.tsx
new file mode 100644
index 000000000..18891d4a3
--- /dev/null
+++ b/packages/app/src/components/settings/TerminalSection.tsx
@@ -0,0 +1,83 @@
+import { useLingui } from '@lingui/react/macro';
+import { useState } from 'react';
+import { toast } from 'sonner';
+import { TerminalConsentDialog } from '@/components/TerminalConsentDialog';
+import { Switch } from '@/components/ui/switch';
+import { useTerminalConsentState, useTerminalEnabledWriter } from '@/hooks/use-terminal-enabled';
+
+export function TerminalSection() {
+ const { t } = useLingui();
+ const { enabled, synced } = useTerminalConsentState();
+ const writer = useTerminalEnabledWriter();
+ const [confirmOpen, setConfirmOpen] = useState(false);
+ const isOn = enabled === true;
+
+ function applyEnabled(next: boolean): boolean {
+ if (writer === null) {
+ toast.error(t`Terminal settings not loaded yet — try again in a moment.`);
+ return false;
+ }
+ const result = writer(next);
+ if (!result.ok) {
+ toast.error(
+ next
+ ? t`Could not enable the terminal: ${result.error}`
+ : t`Could not turn off the terminal: ${result.error}`,
+ );
+ return false;
+ }
+ return true;
+ }
+
+ function onToggle(next: boolean) {
+ if (next) {
+ setConfirmOpen(true);
+ return;
+ }
+ applyEnabled(false);
+ }
+
+ function onConfirmEnable() {
+ if (applyEnabled(true)) setConfirmOpen(false);
+ }
+
+ return (
+ <section aria-labelledby="settings-terminal-title" className="space-y-3">
+ <div className="space-y-1">
+ <h3 id="settings-terminal-title" className="text-base font-semibold">
+ {t`Terminal`}
+ </h3>
+ <p className="text-sm text-muted-foreground">
+ {t`Run a real terminal docked inside Open Knowledge, starting in this project's folder.`}
+ </p>
+ </div>
+
+ <div className="flex items-center justify-between gap-3 rounded-md border p-3">
+ <div className="space-y-0.5">
+ <label htmlFor="settings-terminal-toggle" className="text-sm font-medium">
+ {t`Enable terminal for this project`}
+ </label>
+ <p className="text-1sm text-muted-foreground" data-testid="settings-terminal-body">
+ {isOn
+ ? t`Commands run with the full access of your macOS user account on this machine. Turn this off to disable the shell.`
+ : t`A real shell is off for this project. Turning it on runs commands with the full access of your macOS user account.`}
+ </p>
+ </div>
+ <Switch
+ id="settings-terminal-toggle"
+ checked={isOn}
+ onCheckedChange={onToggle}
+ disabled={!synced || writer === null}
+ aria-label={t`Enable terminal for this project`}
+ data-testid="settings-terminal-toggle"
+ />
+ </div>
+
+ <TerminalConsentDialog
+ open={confirmOpen}
+ onAccept={onConfirmEnable}
+ onDecline={() => setConfirmOpen(false)}
+ />
+ </section>
+ );
+}
diff --git a/packages/app/src/hooks/use-terminal-enabled.dom.test.tsx b/packages/app/src/hooks/use-terminal-enabled.dom.test.tsx
new file mode 100644
index 000000000..bf194acd3
--- /dev/null
+++ b/packages/app/src/hooks/use-terminal-enabled.dom.test.tsx
@@ -0,0 +1,174 @@
+import { afterEach, beforeAll, describe, expect, mock, test } from 'bun:test';
+import type { Config, ConfigBinding, ConfigPatch } from '@inkeep/open-knowledge-core';
+import { cleanup, render } from '@testing-library/react';
+import { ConfigContext, type ConfigContextValue } from '@/lib/config-context';
+import type { TerminalConsentState, TerminalEnabledWriter } from './use-terminal-enabled';
+
+const consentGrants: true[] = [];
+mock.module('@/lib/terminal-telemetry', () => ({
+ recordShellConsentGranted: () => consentGrants.push(true),
+ recordTerminalOpened: () => undefined,
+}));
+
+let useTerminalConsentState: typeof import('./use-terminal-enabled').useTerminalConsentState;
+let useTerminalEnabledWriter: typeof import('./use-terminal-enabled').useTerminalEnabledWriter;
+beforeAll(async () => {
+ const mod = await import('./use-terminal-enabled');
+ useTerminalConsentState = mod.useTerminalConsentState;
+ useTerminalEnabledWriter = mod.useTerminalEnabledWriter;
+});
+
+const emptyContext: ConfigContextValue = {
+ userBinding: null,
+ userSynced: false,
+ projectBinding: null,
+ projectLocalBinding: null,
+ okignoreBinding: null,
+ okignoreSynced: false,
+ userConfig: null,
+ projectConfig: null,
+ projectLocalConfig: null,
+ projectLocalSynced: false,
+ merged: null,
+};
+
+type FakePatchResult = { ok: true } | { ok: false; error: { code: 'WRITE_ERROR'; detail: string } };
+
+function makeFakeBinding(result: FakePatchResult): {
+ binding: ConfigBinding;
+ patches: ConfigPatch[];
+} {
+ const patches: ConfigPatch[] = [];
+ const binding = {
+ patch: (patch: ConfigPatch) => {
+ patches.push(patch);
+ return result;
+ },
+ } as unknown as ConfigBinding;
+ return { binding, patches };
+}
+
+let captured: { state: TerminalConsentState; writer: TerminalEnabledWriter | null } | null = null;
+
+function Probe() {
+ const state = useTerminalConsentState();
+ const writer = useTerminalEnabledWriter();
+ captured = { state, writer };
+ return null;
+}
+
+function renderWith(value: ConfigContextValue) {
+ render(
+ <ConfigContext value={value}>
+ <Probe />
+ </ConfigContext>,
+ );
+}
+
+describe('useTerminalConsentState', () => {
+ afterEach(() => {
+ cleanup();
+ captured = null;
+ });
+
+ test('reads the project-local terminal.enabled tri-state', () => {
+ renderWith({
+ ...emptyContext,
+ projectLocalConfig: { terminal: { enabled: true } } as unknown as Config,
+ projectLocalSynced: true,
+ });
+ expect(captured?.state).toEqual({ enabled: true, synced: true });
+
+ cleanup();
+ renderWith({
+ ...emptyContext,
+ projectLocalConfig: { terminal: { enabled: false } } as unknown as Config,
+ projectLocalSynced: true,
+ });
+ expect(captured?.state).toEqual({ enabled: false, synced: true });
+ });
+
+ test('coalesces an absent terminal leaf to null (unanswered)', () => {
+ renderWith({
+ ...emptyContext,
+ projectLocalConfig: {} as unknown as Config,
+ projectLocalSynced: true,
+ });
+ expect(captured?.state).toEqual({ enabled: null, synced: true });
+ });
+
+ test('reports synced:false during cold start so null is not mistaken for unanswered', () => {
+ renderWith({ ...emptyContext, projectLocalConfig: null, projectLocalSynced: false });
+ expect(captured?.state).toEqual({ enabled: null, synced: false });
+ });
+});
+
+describe('useTerminalEnabledWriter', () => {
+ afterEach(() => {
+ cleanup();
+ captured = null;
+ consentGrants.length = 0;
+ });
+
+ test('is null until the project-local binding mounts', () => {
+ renderWith(emptyContext);
+ expect(captured?.writer).toBeNull();
+ });
+
+ test('grant patches terminal.enabled true on the project-local binding', () => {
+ const { binding, patches } = makeFakeBinding({ ok: true });
+ renderWith({ ...emptyContext, projectLocalBinding: binding });
+
+ const result = captured?.writer?.(true);
+ expect(result).toEqual({ ok: true });
+ expect(patches).toEqual([{ terminal: { enabled: true } }]);
+ });
+
+ test('revoke patches terminal.enabled false on the project-local binding', () => {
+ const { binding, patches } = makeFakeBinding({ ok: true });
+ renderWith({ ...emptyContext, projectLocalBinding: binding });
+
+ const result = captured?.writer?.(false);
+ expect(result).toEqual({ ok: true });
+ expect(patches).toEqual([{ terminal: { enabled: false } }]);
+ });
+
+ test('maps a binding write failure to a tagged error result', () => {
+ const { binding } = makeFakeBinding({
+ ok: false,
+ error: { code: 'WRITE_ERROR', detail: 'disk full' },
+ });
+ renderWith({ ...emptyContext, projectLocalBinding: binding });
+
+ const result = captured?.writer?.(true);
+ expect(result?.ok).toBe(false);
+ if (result && !result.ok) expect(typeof result.error).toBe('string');
+ });
+
+ test('a successful grant records the shell-consent-granted event once', () => {
+ const { binding } = makeFakeBinding({ ok: true });
+ renderWith({ ...emptyContext, projectLocalBinding: binding });
+
+ captured?.writer?.(true);
+ expect(consentGrants).toHaveLength(1);
+ });
+
+ test('a revoke does not record a consent grant', () => {
+ const { binding } = makeFakeBinding({ ok: true });
+ renderWith({ ...emptyContext, projectLocalBinding: binding });
+
+ captured?.writer?.(false);
+ expect(consentGrants).toEqual([]);
+ });
+
+ test('a failed grant write does not record a consent grant', () => {
+ const { binding } = makeFakeBinding({
+ ok: false,
+ error: { code: 'WRITE_ERROR', detail: 'disk full' },
+ });
+ renderWith({ ...emptyContext, projectLocalBinding: binding });
+
+ captured?.writer?.(true);
+ expect(consentGrants).toEqual([]);
+ });
+});
diff --git a/packages/app/src/hooks/use-terminal-enabled.ts b/packages/app/src/hooks/use-terminal-enabled.ts
new file mode 100644
index 000000000..6925bcb24
--- /dev/null
+++ b/packages/app/src/hooks/use-terminal-enabled.ts
@@ -0,0 +1,30 @@
+import { humanFormat } from '@inkeep/open-knowledge-core';
+import { useConfigContext } from '@/lib/config-provider';
+import { recordShellConsentGranted } from '@/lib/terminal-telemetry';
+
+export type TerminalEnabledWriter = (
+ enabled: boolean,
+) => { ok: true } | { ok: false; error: string };
+
+export interface TerminalConsentState {
+ enabled: boolean | null;
+ synced: boolean;
+}
+
+export function useTerminalConsentState(): TerminalConsentState {
+ const { projectLocalConfig, projectLocalSynced } = useConfigContext();
+ return {
+ enabled: projectLocalConfig?.terminal?.enabled ?? null,
+ synced: projectLocalSynced,
+ };
+}
+
+export function useTerminalEnabledWriter(): TerminalEnabledWriter | null {
+ const { projectLocalBinding } = useConfigContext();
+ if (projectLocalBinding === null) return null;
+ return (enabled: boolean) => {
+ const result = projectLocalBinding.patch({ terminal: { enabled } });
+ if (result.ok && enabled) recordShellConsentGranted();
+ return result.ok ? { ok: true } : { ok: false, error: humanFormat(result.error) };
+ };
+}
diff --git a/packages/app/src/lib/desktop-bridge-types.ts b/packages/app/src/lib/desktop-bridge-types.ts
index 335c44bde..ca2aa8515 100644
--- a/packages/app/src/lib/desktop-bridge-types.ts
+++ b/packages/app/src/lib/desktop-bridge-types.ts
@@ -134,7 +134,6 @@ type OkMenuAction =
| 'duplicate'
| 'move-to-trash'
| 'reveal-in-finder'
- | 'open-in-terminal'
| 'send-to-ai'
| 'copy-full-path'
| 'copy-relative-path'
@@ -142,7 +141,8 @@ type OkMenuAction =
| 'toggle-show-all-files'
| 'expand-all-tree'
| 'collapse-all-tree'
- | 'toggle-doc-panel';
+ | 'toggle-doc-panel'
+ | 'toggle-terminal';
type OkUnsubscribe = () => void;
@@ -386,6 +386,7 @@ interface OkEditorViewMenuStateSnapshot {
readonly canCollapseAll: boolean;
readonly sidebarVisible: boolean;
readonly docPanelVisible?: boolean;
+ readonly terminalVisible?: boolean;
}
interface OkKeyringSmokeResult {
@@ -426,6 +427,30 @@ export type OkServerRestartOutcome =
| { readonly ok: true }
| { readonly ok: false; readonly reason: 'eperm' | 'other' };
+export type OkPtyCreateResult =
+ | { readonly ok: true; readonly ptyId: string }
+ | { readonly ok: false; readonly reason: 'no-project' | 'not-consented' };
+
+export interface OkPtyData {
+ readonly ptyId: string;
+ readonly data: string;
+}
+
+export interface OkPtyExit {
+ readonly ptyId: string;
+ readonly exitCode: number;
+ readonly signal: number | null;
+ readonly error?: string;
+}
+
+export interface ClaudeReadiness {
+ readonly claude: 'present' | 'not-found' | 'unknown';
+ readonly mcp: 'wired' | 'needs-rewire';
+ /** Set only on a `rewire`-action result when re-arming MCP wiring threw, so
+ * the renderer can surface the failure instead of the button silently no-op'ing. */
+ readonly rewireError?: string;
+}
+
export interface OkDesktopBridge {
readonly config: OkDesktopConfig;
onProjectSwitched(cb: (next: OkDesktopConfig) => void): OkUnsubscribe;
@@ -504,11 +529,6 @@ export interface OkDesktopBridge {
detail?: string;
}
>;
- openInTerminal(
- dirAbsPath: string,
- ): Promise<
- { ok: true } | { ok: false; reason: 'not-found' | 'spawn-error' | 'timeout' | 'path-escape' }
- >;
};
clipboard: {
writeText(text: string): Promise<void>;
@@ -679,6 +699,19 @@ export interface OkDesktopBridge {
expandAll(cb: () => void): OkUnsubscribe;
collapseAll(cb: () => void): OkUnsubscribe;
};
+
+ terminal: {
+ create(opts: { cols: number; rows: number }): Promise<OkPtyCreateResult>;
+ input(ptyId: string, data: string): void;
+ resize(ptyId: string, cols: number, rows: number): void;
+ kill(ptyId: string): Promise<void>;
+ drain(ptyId: string, bytes: number): void;
+ onData(cb: (msg: OkPtyData) => void): OkUnsubscribe;
+ onExit(cb: (msg: OkPtyExit) => void): OkUnsubscribe;
+ claudePreflight(): Promise<ClaudeReadiness>;
+ rewireClaudeMcp(): Promise<ClaudeReadiness>;
+ };
+
readonly platform: 'darwin' | 'win32' | 'linux';
readonly appVersion: string;
debug?: {
diff --git a/packages/app/src/lib/dispatch-open-in-terminal.test.ts b/packages/app/src/lib/dispatch-open-in-terminal.test.ts
deleted file mode 100644
index ea25edaf0..000000000
--- a/packages/app/src/lib/dispatch-open-in-terminal.test.ts
+++ /dev/null
@@ -1,69 +0,0 @@
-import { afterEach, beforeEach, expect, mock, test } from 'bun:test';
-import * as actualSonner from 'sonner';
-import { dispatchOpenInTerminal } from './dispatch-open-in-terminal.ts';
-
-type ToastCall = { kind: 'error' | 'success'; message: string; description?: string };
-
-const toastCalls: ToastCall[] = [];
-const toastErrorMock = mock((message: string, opts?: { description?: string }) => {
- toastCalls.push({ kind: 'error', message, description: opts?.description });
-});
-
-mock.module('sonner', () => ({
- ...actualSonner,
- toast: { error: toastErrorMock },
-}));
-
-beforeEach(() => {
- toastCalls.length = 0;
- toastErrorMock.mockClear();
-});
-
-afterEach(() => {
- toastErrorMock.mockClear();
-});
-
-type Bridge = Parameters<typeof dispatchOpenInTerminal>[0];
-
-function fakeBridge(openInTerminal: Bridge['shell']['openInTerminal']): Bridge {
- return { shell: { openInTerminal } } as unknown as Bridge;
-}
-
-test('dispatchOpenInTerminal: ok outcome emits no toast', async () => {
- const bridge = fakeBridge(async () => ({ ok: true }) as never);
- await dispatchOpenInTerminal(bridge, '/abs/path/folder');
- expect(toastCalls).toHaveLength(0);
-});
-
-test('dispatchOpenInTerminal: typed {ok:false} outcome emits reason-mapped toast', async () => {
- const bridge = fakeBridge(async () => ({ ok: false, reason: 'not-found' }) as never);
- await dispatchOpenInTerminal(bridge, '/abs/path/folder');
- expect(toastCalls).toHaveLength(1);
- expect(toastCalls[0]).toEqual({
- kind: 'error',
- message: 'Could not open Terminal',
- description: 'Terminal.app not found',
- });
-});
-
-test('dispatchOpenInTerminal: IPC rejection surfaces the ipc-error toast instead of silently swallowing', async () => {
- const bridge = fakeBridge(async () => {
- throw new Error('IPC channel destroyed');
- });
- await dispatchOpenInTerminal(bridge, '/abs/path/folder');
- expect(toastCalls).toHaveLength(1);
- expect(toastCalls[0]).toEqual({
- kind: 'error',
- message: 'Could not open Terminal',
- description: 'Lost connection to the main process',
- });
-});
-
-test('dispatchOpenInTerminal: synchronous throw is also caught', async () => {
- const bridge = fakeBridge((() => {
- throw new Error('IPC unavailable');
- }) as never);
- await dispatchOpenInTerminal(bridge, '/abs/path/folder');
- expect(toastCalls).toHaveLength(1);
- expect(toastCalls[0]?.description).toBe('Lost connection to the main process');
-});
diff --git a/packages/app/src/lib/dispatch-open-in-terminal.ts b/packages/app/src/lib/dispatch-open-in-terminal.ts
deleted file mode 100644
index e007f87c9..000000000
--- a/packages/app/src/lib/dispatch-open-in-terminal.ts
+++ /dev/null
@@ -1,30 +0,0 @@
-import { t } from '@lingui/core/macro';
-import { toast } from 'sonner';
-
-type Bridge = NonNullable<typeof window.okDesktop>;
-
-type OpenInTerminalOutcome = Awaited<ReturnType<Bridge['shell']['openInTerminal']>>;
-
-type OpenInTerminalFailureReason = Extract<OpenInTerminalOutcome, { ok: false }>['reason'];
-
-export async function dispatchOpenInTerminal(bridge: Bridge, dirAbsPath: string): Promise<void> {
- const reasonLabel: Record<OpenInTerminalFailureReason | 'ipc-error', string> = {
- 'not-found': t`Terminal.app not found`,
- 'spawn-error': t`Could not launch Terminal`,
- timeout: t`Terminal took too long to respond`,
- 'path-escape': t`Path resolves outside the project`,
- 'ipc-error': t`Lost connection to the main process`,
- };
- let result: OpenInTerminalOutcome;
- try {
- result = await bridge.shell.openInTerminal(dirAbsPath);
- } catch (err) {
- console.warn('[shell] openInTerminal IPC threw', { dirAbsPath, err });
- toast.error(t`Could not open Terminal`, { description: reasonLabel['ipc-error'] });
- return;
- }
- if (!result.ok) {
- console.warn('[shell] openInTerminal failed', { reason: result.reason, dirAbsPath });
- toast.error(t`Could not open Terminal`, { description: reasonLabel[result.reason] });
- }
-}
diff --git a/packages/app/src/lib/file-menu-target-resolvers.test.ts b/packages/app/src/lib/file-menu-target-resolvers.test.ts
index 3b3d18be9..a6db41447 100644
--- a/packages/app/src/lib/file-menu-target-resolvers.test.ts
+++ b/packages/app/src/lib/file-menu-target-resolvers.test.ts
@@ -2,7 +2,6 @@ import { describe, expect, test } from 'bun:test';
import {
buildSendToAiInputForActiveTarget,
resolveActiveTargetAbsPath,
- resolveActiveTargetParentDirAbsPath,
resolveActiveTargetRelativePath,
} from './file-menu-target-resolvers';
import type { Workspace } from './workspace-paths';
@@ -70,62 +69,6 @@ describe('resolveActiveTargetAbsPath', () => {
});
});
-describe('resolveActiveTargetParentDirAbsPath', () => {
- test('doc scope at nested depth returns parent dir', () => {
- expect(
- resolveActiveTargetParentDirAbsPath(
- { kind: 'doc', target: 'specs/foo/SPEC', docName: 'specs/foo/SPEC' },
- 'specs/foo/SPEC',
- WORKSPACE,
- ),
- ).toBe('/Users/test/project/specs/foo');
- });
-
- test('doc scope at root returns contentDir (no leading slash artifact)', () => {
- expect(
- resolveActiveTargetParentDirAbsPath(
- { kind: 'doc', target: 'README', docName: 'README' },
- 'README',
- WORKSPACE,
- ),
- ).toBe('/Users/test/project');
- });
-
- test('folder scope returns the folder itself (not its parent)', () => {
- expect(
- resolveActiveTargetParentDirAbsPath(
- { kind: 'folder', target: 'reports', folderPath: 'reports' },
- null,
- WORKSPACE,
- ),
- ).toBe('/Users/test/project/reports');
- });
-
- test('null + missing scopes return contentDir', () => {
- expect(resolveActiveTargetParentDirAbsPath(null, null, WORKSPACE)).toBe('/Users/test/project');
- expect(
- resolveActiveTargetParentDirAbsPath({ kind: 'missing', target: 'gone' }, null, WORKSPACE),
- ).toBe('/Users/test/project');
- });
-
- test('asset scope returns the asset parent dir', () => {
- expect(
- resolveActiveTargetParentDirAbsPath(
- { kind: 'asset', target: 'media/x.png', assetPath: 'media/x.png', mediaKind: null },
- null,
- WORKSPACE,
- ),
- ).toBe('/Users/test/project/media');
- expect(
- resolveActiveTargetParentDirAbsPath(
- { kind: 'asset', target: 'x.png', assetPath: 'x.png', mediaKind: null },
- null,
- WORKSPACE,
- ),
- ).toBe('/Users/test/project');
- });
-});
-
describe('resolveActiveTargetRelativePath', () => {
test('doc scope returns .md-suffixed relative path', () => {
expect(
diff --git a/packages/app/src/lib/file-menu-target-resolvers.ts b/packages/app/src/lib/file-menu-target-resolvers.ts
index 63a6f6af3..8b362bc56 100644
--- a/packages/app/src/lib/file-menu-target-resolvers.ts
+++ b/packages/app/src/lib/file-menu-target-resolvers.ts
@@ -39,39 +39,6 @@ export function resolveActiveTargetAbsPath(
return workspace.contentDir;
}
-export function resolveActiveTargetParentDirAbsPath(
- activeTarget: ResolvedNavigationTarget | null,
- activeDocName: string | null,
- workspace: Workspace,
-): string {
- if ((activeTarget?.kind === 'doc' || activeTarget?.kind === 'folder-index') && activeDocName) {
- const lastSep = activeDocName.lastIndexOf('/');
- if (lastSep < 0) return workspace.contentDir;
- return joinWorkspacePath(
- workspace.contentDir,
- activeDocName.slice(0, lastSep),
- workspace.pathSeparator,
- );
- }
- if (activeTarget?.kind === 'folder') {
- return joinWorkspacePath(
- workspace.contentDir,
- activeTarget.folderPath,
- workspace.pathSeparator,
- );
- }
- if (activeTarget?.kind === 'asset') {
- const lastSep = activeTarget.assetPath.lastIndexOf('/');
- if (lastSep < 0) return workspace.contentDir;
- return joinWorkspacePath(
- workspace.contentDir,
- activeTarget.assetPath.slice(0, lastSep),
- workspace.pathSeparator,
- );
- }
- return workspace.contentDir;
-}
-
export function resolveActiveTargetRelativePath(
activeTarget: ResolvedNavigationTarget | null,
activeDocName: string | null,
diff --git a/packages/app/src/lib/keyboard-shortcuts.test.ts b/packages/app/src/lib/keyboard-shortcuts.test.ts
index 2dd277240..21a8366f8 100644
--- a/packages/app/src/lib/keyboard-shortcuts.test.ts
+++ b/packages/app/src/lib/keyboard-shortcuts.test.ts
@@ -125,6 +125,56 @@ describe('keyboard shortcut registry', () => {
).toBe(false);
});
+ test('formats the terminal-panel shortcut as Cmd/Ctrl + J', () => {
+ expect(formatShortcut('toggle-terminal-panel', 'mac')).toBe('⌘ J');
+ expect(formatShortcut('toggle-terminal-panel', 'windowsLinux')).toBe('Ctrl J');
+ });
+
+ test('matches the terminal-panel shortcut on Cmd+J / Ctrl+J and excludes extra modifiers', () => {
+ expect(
+ matchesKeyboardShortcut(
+ { metaKey: true, ctrlKey: false, altKey: false, key: 'j' },
+ 'toggle-terminal-panel',
+ 'mac',
+ ),
+ ).toBe(true);
+ expect(
+ matchesKeyboardShortcut(
+ { metaKey: false, ctrlKey: true, altKey: false, key: 'j' },
+ 'toggle-terminal-panel',
+ 'windowsLinux',
+ ),
+ ).toBe(true);
+ expect(
+ matchesKeyboardShortcut(
+ { metaKey: false, ctrlKey: true, altKey: false, key: 'j' },
+ 'toggle-terminal-panel',
+ 'mac',
+ ),
+ ).toBe(false);
+ expect(
+ matchesKeyboardShortcut(
+ { metaKey: true, ctrlKey: false, altKey: true, key: 'j' },
+ 'toggle-terminal-panel',
+ 'mac',
+ ),
+ ).toBe(false);
+ expect(
+ matchesKeyboardShortcut(
+ { metaKey: true, ctrlKey: false, altKey: false, shiftKey: true, key: 'j' },
+ 'toggle-terminal-panel',
+ 'mac',
+ ),
+ ).toBe(false);
+ expect(
+ matchesKeyboardShortcut(
+ { metaKey: false, ctrlKey: false, altKey: false, key: 'j' },
+ 'toggle-terminal-panel',
+ 'mac',
+ ),
+ ).toBe(false);
+ });
+
test('matches command palette with allowed extra modifiers and rejects missing mod', () => {
expect(
matchesKeyboardShortcut(
diff --git a/packages/app/src/lib/keyboard-shortcuts.ts b/packages/app/src/lib/keyboard-shortcuts.ts
index 18282cfa3..f2ff249ad 100644
--- a/packages/app/src/lib/keyboard-shortcuts.ts
+++ b/packages/app/src/lib/keyboard-shortcuts.ts
@@ -152,6 +152,20 @@ const KEYBOARD_SHORTCUT_DEFINITIONS = [
},
],
},
+ {
+ id: 'toggle-terminal-panel',
+ category: 'general',
+ title: msg`Show or hide terminal`,
+ description: msg`Toggle the bottom terminal panel.`,
+ scope: msg`OK Desktop`,
+ bindings: [
+ {
+ mac: '⌘ J',
+ windowsLinux: 'Ctrl J',
+ match: { key: 'j', mod: true },
+ },
+ ],
+ },
{
id: 'open-folder',
category: 'workspace',
diff --git a/packages/app/src/lib/terminal-height-store.test.ts b/packages/app/src/lib/terminal-height-store.test.ts
new file mode 100644
index 000000000..961db3f81
--- /dev/null
+++ b/packages/app/src/lib/terminal-height-store.test.ts
@@ -0,0 +1,103 @@
+import { describe, expect, test } from 'bun:test';
+import {
+ DEFAULT_TERMINAL_HEIGHT,
+ type HeightStorage,
+ MIN_TERMINAL_HEIGHT,
+ readTerminalHeight,
+ TERMINAL_HEIGHT_KEY,
+ writeTerminalHeight,
+} from './terminal-height-store.ts';
+
+function memoryStorage(initial: Record<string, string> = {}): HeightStorage {
+ const data = new Map(Object.entries(initial));
+ return {
+ getItem(key) {
+ return data.get(key) ?? null;
+ },
+ setItem(key, value) {
+ data.set(key, value);
+ },
+ };
+}
+
+const TALL = 1000;
+
+describe('readTerminalHeight', () => {
+ test('absent key returns default', () => {
+ expect(readTerminalHeight(memoryStorage(), TALL)).toBe(DEFAULT_TERMINAL_HEIGHT);
+ });
+
+ test('valid stored height is returned', () => {
+ const s = memoryStorage({ [TERMINAL_HEIGHT_KEY]: '300' });
+ expect(readTerminalHeight(s, TALL)).toBe(300);
+ });
+
+ test('height below floor is clamped to MIN', () => {
+ const s = memoryStorage({ [TERMINAL_HEIGHT_KEY]: '80' });
+ expect(readTerminalHeight(s, TALL)).toBe(MIN_TERMINAL_HEIGHT);
+ });
+
+ test('height above the 50vh ceiling is clamped to half the viewport', () => {
+ const s = memoryStorage({ [TERMINAL_HEIGHT_KEY]: '9999' });
+ expect(readTerminalHeight(s, TALL)).toBe(500);
+ });
+
+ test('ceiling tracks the viewport (50vh), not a fixed pixel cap', () => {
+ const s = memoryStorage({ [TERMINAL_HEIGHT_KEY]: '400' });
+ expect(readTerminalHeight(s, 1000)).toBe(400);
+ expect(readTerminalHeight(s, 600)).toBe(300);
+ });
+
+ test('non-numeric value falls back to default', () => {
+ const s = memoryStorage({ [TERMINAL_HEIGHT_KEY]: 'not a number' });
+ expect(readTerminalHeight(s, TALL)).toBe(DEFAULT_TERMINAL_HEIGHT);
+ });
+
+ test('empty string falls back to default', () => {
+ const s = memoryStorage({ [TERMINAL_HEIGHT_KEY]: '' });
+ expect(readTerminalHeight(s, TALL)).toBe(DEFAULT_TERMINAL_HEIGHT);
+ });
+
+ test('floating-point value is rounded', () => {
+ const s = memoryStorage({ [TERMINAL_HEIGHT_KEY]: '240.6' });
+ expect(readTerminalHeight(s, TALL)).toBe(240);
+ });
+});
+
+describe('writeTerminalHeight', () => {
+ test('writes a clamped integer to storage', () => {
+ const s = memoryStorage();
+ writeTerminalHeight(300, s, TALL);
+ expect(s.getItem(TERMINAL_HEIGHT_KEY)).toBe('300');
+ });
+
+ test('clamps to MIN on write below floor', () => {
+ const s = memoryStorage();
+ writeTerminalHeight(80, s, TALL);
+ expect(s.getItem(TERMINAL_HEIGHT_KEY)).toBe(String(MIN_TERMINAL_HEIGHT));
+ });
+
+ test('clamps to the 50vh ceiling on write above it', () => {
+ const s = memoryStorage();
+ writeTerminalHeight(9999, s, 600);
+ expect(s.getItem(TERMINAL_HEIGHT_KEY)).toBe('300');
+ });
+
+ test('rounds floating-point input before write', () => {
+ const s = memoryStorage();
+ writeTerminalHeight(240.7, s, TALL);
+ expect(s.getItem(TERMINAL_HEIGHT_KEY)).toBe('241');
+ });
+
+ test('quota-exceeded throw is swallowed (in-memory only)', () => {
+ const throwing: HeightStorage = {
+ getItem() {
+ return null;
+ },
+ setItem() {
+ throw new Error('QuotaExceededError');
+ },
+ };
+ expect(() => writeTerminalHeight(240, throwing, TALL)).not.toThrow();
+ });
+});
diff --git a/packages/app/src/lib/terminal-height-store.ts b/packages/app/src/lib/terminal-height-store.ts
new file mode 100644
index 000000000..71ffe5316
--- /dev/null
+++ b/packages/app/src/lib/terminal-height-store.ts
@@ -0,0 +1,63 @@
+export const TERMINAL_HEIGHT_KEY = 'ok-terminal-height-v1';
+
+export const DEFAULT_TERMINAL_HEIGHT = 240;
+export const MIN_TERMINAL_HEIGHT = 120;
+const MAX_TERMINAL_HEIGHT_FRACTION = 0.5;
+
+export interface HeightStorage {
+ getItem(key: string): string | null;
+ setItem(key: string, value: string): void;
+}
+
+function maxHeight(viewportHeight: number): number {
+ const vh = Number.isFinite(viewportHeight) ? viewportHeight : 0;
+ return Math.max(MIN_TERMINAL_HEIGHT, Math.round(vh * MAX_TERMINAL_HEIGHT_FRACTION));
+}
+
+function clamp(px: number, viewportHeight: number): number {
+ const max = maxHeight(viewportHeight);
+ if (!Number.isFinite(px)) return Math.min(DEFAULT_TERMINAL_HEIGHT, max);
+ if (px < MIN_TERMINAL_HEIGHT) return MIN_TERMINAL_HEIGHT;
+ if (px > max) return max;
+ return Math.round(px);
+}
+
+function currentViewportHeight(): number {
+ if (typeof window === 'undefined') return 0;
+ return window.innerHeight;
+}
+
+export function readTerminalHeight(storage?: HeightStorage, viewportHeight?: number): number {
+ try {
+ const s = storage ?? localStorage;
+ const vh = viewportHeight ?? currentViewportHeight();
+ const raw = s.getItem(TERMINAL_HEIGHT_KEY);
+ if (raw == null) return clamp(DEFAULT_TERMINAL_HEIGHT, vh);
+ const parsed = Number.parseInt(raw, 10);
+ if (!Number.isFinite(parsed)) return clamp(DEFAULT_TERMINAL_HEIGHT, vh);
+ return clamp(parsed, vh);
+ } catch {
+ return DEFAULT_TERMINAL_HEIGHT;
+ }
+}
+
+export function writeTerminalHeight(
+ px: number,
+ storage?: HeightStorage,
+ viewportHeight?: number,
+): void {
+ try {
+ const s = storage ?? localStorage;
+ const vh = viewportHeight ?? currentViewportHeight();
+ s.setItem(TERMINAL_HEIGHT_KEY, String(clamp(px, vh)));
+ } catch {}
+}
+
+export function getInitialTerminalHeight(): number {
+ try {
+ if (typeof localStorage === 'undefined') return DEFAULT_TERMINAL_HEIGHT;
+ return readTerminalHeight();
+ } catch {
+ return DEFAULT_TERMINAL_HEIGHT;
+ }
+}
diff --git a/packages/app/src/lib/terminal-telemetry.test.ts b/packages/app/src/lib/terminal-telemetry.test.ts
new file mode 100644
index 000000000..720162812
--- /dev/null
+++ b/packages/app/src/lib/terminal-telemetry.test.ts
@@ -0,0 +1,50 @@
+import { afterEach, beforeEach, describe, expect, type Mock, spyOn, test } from 'bun:test';
+import { type Tracer, trace } from '@opentelemetry/api';
+import { recordShellConsentGranted, recordTerminalOpened } from './terminal-telemetry';
+
+const spanNames: string[] = [];
+let startSpanThrows = false;
+let getTracerSpy: Mock<typeof trace.getTracer>;
+
+beforeEach(() => {
+ spanNames.length = 0;
+ startSpanThrows = false;
+ getTracerSpy = spyOn(trace, 'getTracer').mockImplementation(
+ () =>
+ ({
+ startSpan: (name: string) => {
+ if (startSpanThrows) throw new Error('otel provider fault');
+ spanNames.push(name);
+ return { end: () => undefined };
+ },
+ }) as unknown as Tracer,
+ );
+});
+
+afterEach(() => {
+ getTracerSpy.mockRestore();
+});
+
+describe('renderer terminal telemetry — span names', () => {
+ test('recordTerminalOpened starts ok.desktop.terminalOpened', () => {
+ recordTerminalOpened();
+ expect(spanNames).toEqual(['ok.desktop.terminalOpened']);
+ });
+
+ test('recordShellConsentGranted starts ok.desktop.shellConsentGranted', () => {
+ recordShellConsentGranted();
+ expect(spanNames).toEqual(['ok.desktop.shellConsentGranted']);
+ });
+});
+
+describe('renderer terminal telemetry — SDK fault isolation', () => {
+ test('a startSpan throw does not escape recordTerminalOpened', () => {
+ startSpanThrows = true;
+ expect(() => recordTerminalOpened()).not.toThrow();
+ });
+
+ test('a startSpan throw does not escape recordShellConsentGranted', () => {
+ startSpanThrows = true;
+ expect(() => recordShellConsentGranted()).not.toThrow();
+ });
+});
diff --git a/packages/app/src/lib/terminal-telemetry.ts b/packages/app/src/lib/terminal-telemetry.ts
new file mode 100644
index 000000000..6230efe8a
--- /dev/null
+++ b/packages/app/src/lib/terminal-telemetry.ts
@@ -0,0 +1,22 @@
+import { trace } from '@opentelemetry/api';
+
+const TRACER_NAME = 'open-knowledge-app';
+
+function emitMarker(name: string): void {
+ try {
+ trace.getTracer(TRACER_NAME).startSpan(name).end();
+ } catch (err) {
+ console.warn(
+ '[terminal-telemetry] span emit failed:',
+ err instanceof Error ? err : String(err),
+ );
+ }
+}
+
+export function recordTerminalOpened(): void {
+ emitMarker('ok.desktop.terminalOpened');
+}
+
+export function recordShellConsentGranted(): void {
+ emitMarker('ok.desktop.shellConsentGranted');
+}
diff --git a/packages/app/src/locales/en/messages.json b/packages/app/src/locales/en/messages.json
index 3b2ceba1e..185410f3e 100644
--- a/packages/app/src/locales/en/messages.json
+++ b/packages/app/src/locales/en/messages.json
@@ -365,15 +365,21 @@
"AAlr5Y": [
"No collab server for this worktree — run <0>ok start</0> here, or reopen the project."
],
+ "AE7BY3": ["The terminal session ended."],
+ "ALhMYW": ["Terminal"],
"AMyJts": [
"This path is on an external volume (/Volumes/...). Open Knowledge will lose track of files when the drive ejects."
],
"AQ-Lfg": ["Couldn't load templates"],
+ "AQGtjK": [
+ "Commands run with the full access of your macOS user account on this machine. Turn this off to disable the shell."
+ ],
"AThCb_": [
"Open Knowledge manages the <0>open-knowledge</0> MCP server name, the <1>open-knowledge-ui</1> launch config, and <2>ok</2> / <3>open-knowledge</3> on PATH (including OK-owned symlinks). Using a custom wrapper? Register it under a different name."
],
"AVW-K9": ["Failed to load orphan pages"],
"AWOSPo": ["Zoom in"],
+ "AcK_r0": ["Claude CLI"],
"AdcGcG": ["Applying your change"],
"AddR83": ["Could not create project. Try again or pick a different location."],
"AeHuzT": ["# One pattern per line.\n# Examples:\n# drafts/\n# *.draft.md\n# !keep.md"],
@@ -409,7 +415,7 @@
],
"BGHHtQ": ["Single page"],
"BH56dn": ["Custom display text"],
- "BJpGCq": ["Open in Terminal"],
+ "BQKHuL": ["Restart terminal"],
"BQu9Pg": ["Symlink"],
"BY-g4_": ["Add pattern"],
"Bdha5y": ["Publishing..."],
@@ -448,7 +454,6 @@
"DId6MT": ["Project-level pages with no outgoing graph edges."],
"DPfwMq": ["Done"],
"DVh_Tb": ["Failed to clean up after trash"],
- "DYwdxG": ["Could not open Terminal"],
"D_WKe_": ["Click an agent's avatar in the presence bar to view their session."],
"DeDYLr": ["Unrecognized wiki link"],
"DhLHEb": ["Failed to load activity"],
@@ -461,7 +466,9 @@
],
"Dw1T_W": ["Rename ", ["label"]],
"E1_c72": ["Task list"],
+ "E1tG2u": ["Get Claude Code"],
"E2Mv-X": ["Copy source"],
+ "E4XYYH": ["Enable terminal for this project"],
"E7BhZn": ["Blank note"],
"E9bKSA": ["Creating"],
"EBVbtP": ["Could not duplicate item"],
@@ -582,6 +589,7 @@
"I5AfhE": ["Sync status unavailable — server unreachable."],
"IA1wNb": ["The Claude Desktop App didn't open the file. Is it installed? (", ["msg"], ")"],
"IA6JW2": ["Detecting"],
+ "ICoNYz": ["You can also manage this in Settings."],
"IInnZo": ["Conflict"],
"IKoTAC": ["Keep disabled"],
"IN4UX8": ["Search (", ["searchShortcut"], ")"],
@@ -595,6 +603,7 @@
"If0crP": ["Open with AI ", ["targetDisplayName"], ", ", ["hint"]],
"IgTwLt": ["Open this document in the editor and collapse the graph."],
"Ik-gP0": ["Heading H", ["level"], ": ", ["text"]],
+ "Iq8zdU": ["Close terminal"],
"IrB5AK": [
"Server-side cleanup failed for ",
["failedCount", "plural", { "one": ["#", " item"], "other": ["#", " items"] }]
@@ -654,6 +663,7 @@
["componentName"],
"> isn't a known component. Copy the source to use it elsewhere, or delete the block."
],
+ "Khxcyu": ["Terminal access isn't enabled for this project."],
"KkEAud": ["Create a file from the current document or folder context."],
"KmydK6": ["Bold"],
"KnoB--": ["Will be saved as <0>", ["sanitized"], "</0>."],
@@ -691,6 +701,7 @@
"LpB85N": ["Plain"],
"LtI9AS": ["Owner"],
"LtSYdi": ["Reveal in Finder"],
+ "LtVw4J": ["Claude CLI, ", ["hint"]],
"M1OfV9": ["Next source diagnostic"],
"M3ytY_": [
"This looks like a drive root (e.g., C:\\). Scaffolding here will scan an entire drive."
@@ -835,6 +846,9 @@
],
"R0jJzV": ["Paste URL, owner/repo, or search your repos"],
"R3y75Z": ["Edit source"],
+ "R65q-K": [
+ "A real shell is off for this project. Turning it on runs commands with the full access of your macOS user account."
+ ],
"RDrXh4": ["Configure user, project, and integration settings."],
"RGCCrg": ["Copy share link"],
"RGkNeJ": ["Initialize a starter pack"],
@@ -901,6 +915,9 @@
"U3IvM5": ["Full guide"],
"U5Spo9": ["Content directory must be inside the project"],
"U8CD-l": ["Copy full path, No workspace"],
+ "UA171M": [
+ "Run a real terminal docked inside Open Knowledge, starting in this project's folder."
+ ],
"UBv8UK": ["Delete Permanently"],
"UDFrWm": ["Checking GitHub connection..."],
"UL8A9w": ["Tag"],
@@ -940,6 +957,7 @@
"VYd_YA": ["Open an existing project folder from disk."],
"VZGh8G": ["Fold, unfold, fold all, or unfold all source ranges."],
"VZSBXL": ["Semantic ranking activates the first time an agent runs a search."],
+ "V_6bJ4": ["Terminal settings not loaded yet — try again in a moment."],
"VbqhBI": ["Already at ", ["assetContentPath"], " — reusing."],
"VcqWBy": ["Upload may have succeeded but the sidebar is out of date — refresh to resync"],
"VdXv4D": ["Clone from GitHub"],
@@ -1080,7 +1098,6 @@
"Zul8Ry": ["never"],
"ZxXhLY": ["Hide Files (", ["sidebarShortcut"], ")"],
"Zz25kq": ["Show Files (", ["sidebarShortcut"], ")"],
- "_6IEmc": ["Open in Terminal, No workspace"],
"_7UQ7y": ["Whole word"],
"_8quCH": ["From template"],
"_902BE": [
@@ -1109,6 +1126,7 @@
"_TF8ep": ["Failed to render PDF"],
"_VRtd7": ["Couldn't send the selection — please try again."],
"_W-elG": ["(inline)"],
+ "_XWY2J": ["Terminal disabled"],
"_gkGSK": ["deleted template"],
"_pY_Vq": ["The repository was moved, renamed, or deleted."],
"_qD6mn": ["Pick the folder where you've cloned it."],
@@ -1205,8 +1223,10 @@
"dN20LW": [
"Semantic search is on, but no API key is set — search falls back to keyword matching. Add one in <0>Settings → Account</0> (it's stored once for your whole machine)."
],
+ "dNM58w": ["Claude Code (claude) isn't installed or on your PATH."],
"dOHMA0": ["Failed to move"],
"dOxPd4": ["Footnote"],
+ "dPOFid": ["Show or hide terminal"],
"dTaauv": ["Reason: ", ["reason"]],
"dUQ7_J": [
"Add meaning-based ranking to search so conceptually-related pages surface even when they share no keywords. This setting applies only to this computer."
@@ -1237,7 +1257,7 @@
"Writes a project-MCP config for each selected tool; Claude also gets <0>.claude/launch.json</0>."
],
"eVPynQ": ["Open <0><1>", ["verificationUri"], "</1><2/></0> and enter this code:"],
- "ehLu5O": ["Open in Terminal, ", ["hint"]],
+ "eiG6_3": ["The terminal is not enabled for this project."],
"emgiet": ["Authoritative content; mirrored verbatim everywhere it's referenced."],
"ensWZc": ["or start from scratch <0/>"],
"euc6Ns": ["Duplicate"],
@@ -1245,6 +1265,8 @@
"f1XQyZ": ["Move block"],
"f65AOQ": ["Start from"],
"f8jU-L": [["0"], "/", ["1"], " — ", ["2"]],
+ "fBHvBn": ["There's no project folder for this window, so a terminal can't start here."],
+ "fBaTkM": ["Toggle the bottom terminal panel."],
"fG0X0e": ["Install ", ["brand"], " →"],
"fIgqfQ": ["Reinstalling"],
"fJgQHX": ["Failed to create file"],
@@ -1284,6 +1306,7 @@
"gYz2ep": ["Expires in ", ["timeLabel"]],
"gbHcbI": ["Failed to delete property"],
"gcV0dI": ["The folders and templates are in place; there's nothing left to scaffold."],
+ "gfohmY": ["Connect tools"],
"ggm6JX": [
"This page doesn't exist yet. Open it to create the page in the editor and collapse the graph."
],
@@ -1374,6 +1397,7 @@
"j9Vqvc": ["inherited"],
"jEdF24": ["Missing page: ", ["linkTitle"], ". Click to create."],
"jGJy-9": ["Downloads ", ["shareOwner"], "/", ["shareRepo"], " from GitHub."],
+ "jKd3AP": ["Could not enable the terminal: ", ["0"]],
"jPUPvG": ["Couldn't resolve the conflict for ", ["filePath"], "."],
"jRHdCz": ["Failed to load PDF"],
"jSO1X5": ["Inherited templates can't be renamed here — rename it in the folder that owns it."],
@@ -1384,7 +1408,6 @@
"jdGUeI": ["Couldn't create template: ", ["error"]],
"jerqF0": ["Loading branch state"],
"jhtG3I": [" Your selection has been restored."],
- "jjmuxV": ["Lost connection to the main process"],
"jjtmV_": ["First file name"],
"jol95m": ["Failed to open Project Navigator."],
"ju38ms": [
@@ -1403,7 +1426,6 @@
" ready. Results may be incomplete."
],
"kCqCyf": ["Open CodeMirror's lint diagnostics panel."],
- "kDuh1E": ["Path resolves outside the project"],
"kFLlsI": ["Insert a footnote reference + matching definition stub."],
"kFgMHe": ["Local only on this machine"],
"kNqMMd": ["Folder"],
@@ -1420,7 +1442,6 @@
"kmKqZg": ["Clusters"],
"knjOzA": ["Tag value"],
"kolRU1": ["Do you want to permanently delete instead?"],
- "ktATCe": ["Could not launch Terminal"],
"ku0yLQ": ["Pages are embedded the first time a search needs them."],
"ky9Tuc": ["Edit ", ["0"], " source"],
"l17ab4": ["Could not write project files. Try a different location."],
@@ -1433,6 +1454,7 @@
"lGs_bQ": ["Page <0>*</0>"],
"lHwYMr": ["Server error: ", ["status"], " ", ["statusText"]],
"lIn9L9": ["Disable sync"],
+ "lLGJG6": ["Couldn't connect Open Knowledge tools to Claude Code. Please try again."],
"lPzyrU": ["All hunks resolved"],
"lVWEIL": ["Indexed ", ["embedded"], " of ", ["total"], " pages."],
"lWNpNB": ["Add cursors or select matching occurrences through CodeMirror."],
@@ -1515,6 +1537,7 @@
"nCzR-G": ["Copy code ", ["userCode"]],
"nDT8qt": ["Initialized ", ["0"], " but could not open it."],
"nNYV3Y": ["and ", ["remaining"], " more"],
+ "nPhvQ_": ["Claude Code is installed, but Open Knowledge tools aren't connected to it yet."],
"nTwL53": ["Open a doc to share its URL."],
"nWv1ja": ["Manage hidden files in Settings → Ignore patterns."],
"nYKerc": ["(user-level only)"],
@@ -1550,6 +1573,9 @@
"oQA-cA": ["Full path"],
"oS1YpJ": ["Open the Project Navigator."],
"oXKEsy": ["Delete an adjacent wiki-link or tag chip."],
+ "oYepHb": [
+ "The terminal is turned off for this project. Turn it back on to run commands here."
+ ],
"ogAuyr": ["Back to document view"],
"omXJcU": ["Close others"],
"optX0N": [["0"], "h ago"],
@@ -1575,6 +1601,7 @@
"pWT04I": ["Checking..."],
"pWbsW6": ["Loading docs"],
"pZAs1T": ["Failed to load outgoing links"],
+ "pajIrl": ["Could not turn off the terminal: ", ["0"]],
"pbwTg6": [["seconds"], "s ago"],
"pcfY8r": ["opens in browser"],
"pckX1A": [["0", "plural", { "one": ["#", " use"], "other": ["#", " uses"] }]],
@@ -1589,6 +1616,7 @@
"prHfed": ["Each selected tool gets an Open Knowledge MCP entry."],
"pzutoc": ["Italic"],
"q2kXMG": ["Inline Math"],
+ "q4YJl_": ["The terminal session ended (exit code ", ["0"], ")."],
"q6-JVU": ["Loading pages"],
"qAQVSD": ["Page headings response was not JSON"],
"qAhFeg": [
@@ -1720,6 +1748,7 @@
"uF9ruK": ["Saving"],
"uH_S-u": [["loadErrorTitle"], ": ", ["message"]],
"uKRYiW": ["Sync status unavailable — server error."],
+ "uL_Wx8": ["The terminal stopped unexpectedly."],
"uM6jnS": ["Restore failed"],
"uO9WLl": ["Push"],
"uQNW00": ["Detached HEAD — checkout a branch to resume"],
@@ -1731,6 +1760,7 @@
],
"uWx2ZP": ["Last sync"],
"u_lS4C": ["Clone complete — opening project"],
+ "ubMwcO": ["The terminal session ended (signal ", ["0"], ")."],
"ugoTXs": ["folder"],
"uhJEA2": [
[
@@ -1745,6 +1775,7 @@
"uuoHOU": ["Command failed."],
"uynXup": [["tokens", "plural", { "one": ["token"], "other": ["tokens"] }]],
"v-h2hx": ["Delete ", ["targetGitPath"]],
+ "v2ZW0K": ["Enable terminal"],
"v41fCm": ["File not found"],
"v75Em9": [
[
@@ -1761,7 +1792,6 @@
"vPYaz3": ["Scaffold directly under this project."],
"vQIVHc": ["Folder properties"],
"vWc9a0": ["Type to edit; <0>⌘ Enter</0> saves, <1>Esc</1> cancels."],
- "vY54W_": ["Terminal.app not found"],
"vZVeFG": ["Upload failed — please try again"],
"vbK_ZG": ["Files sidebar"],
"ve8vEM": ["Code expired — please try again"],
@@ -1788,7 +1818,6 @@
"You picked ~/Downloads. Files there are usually transient — consider a stable folder instead."
],
"wndeIl": ["Project-level pages with neither incoming nor outgoing graph edges."],
- "wrzAcD": ["Terminal took too long to respond"],
"wt8OSk": ["Requires a git repository — pick a different folder or enable git init."],
"wvbc1r": ["Couldn't open document"],
"x2fr_j": ["Graph"],
diff --git a/packages/app/src/locales/en/messages.po b/packages/app/src/locales/en/messages.po
index 230ac7d55..e4ee945cc 100644
--- a/packages/app/src/locales/en/messages.po
+++ b/packages/app/src/locales/en/messages.po
@@ -460,6 +460,10 @@ msgstr "A project already exists at this location. Pick a different parent folde
msgid "A pull quote stands out from the surrounding text."
msgstr "A pull quote stands out from the surrounding text."
+#: src/components/settings/TerminalSection.tsx
+msgid "A real shell is off for this project. Turning it on runs commands with the full access of your macOS user account."
+msgstr "A real shell is off for this project. Turning it on runs commands with the full access of your macOS user account."
+
#: src/components/NewTemplateDialog.tsx
msgid "A reusable starting point for new documents in this folder."
msgstr "A reusable starting point for new documents in this folder."
@@ -957,6 +961,25 @@ msgstr "Checklist with checkboxes."
msgid "Choose whether to commit <0>.ok/</0>, <1>.mcp.json</1> (and per-editor variants), project skills, and <2>.claude/launch.json</2> alongside content — or keep them on this machine only via <3>.git/info/exclude</3>."
msgstr "Choose whether to commit <0>.ok/</0>, <1>.mcp.json</1> (and per-editor variants), project skills, and <2>.claude/launch.json</2> alongside content — or keep them on this machine only via <3>.git/info/exclude</3>."
+#: src/components/handoff/OpenInAgentContextSubmenu.tsx
+#: src/components/handoff/OpenInAgentEmptySpaceSubmenu.tsx
+#: src/components/handoff/OpenInAgentMenu.tsx
+msgid "Claude CLI"
+msgstr "Claude CLI"
+
+#: src/components/handoff/OpenInAgentContextSubmenu.tsx
+#: src/components/handoff/OpenInAgentEmptySpaceSubmenu.tsx
+msgid "Claude CLI, {hint}"
+msgstr "Claude CLI, {hint}"
+
+#: src/components/ClaudeReadinessBanner.tsx
+msgid "Claude Code (claude) isn't installed or on your PATH."
+msgstr "Claude Code (claude) isn't installed or on your PATH."
+
+#: src/components/ClaudeReadinessBanner.tsx
+msgid "Claude Code is installed, but Open Knowledge tools aren't connected to it yet."
+msgstr "Claude Code is installed, but Open Knowledge tools aren't connected to it yet."
+
#: src/components/settings/SettingsDialogShell.tsx
msgid "Claude Desktop"
msgstr "Claude Desktop"
@@ -1075,6 +1098,10 @@ msgstr "Close new tab"
msgid "Close others"
msgstr "Close others"
+#: src/components/TerminalRefusalNotice.tsx
+msgid "Close terminal"
+msgstr "Close terminal"
+
#: src/components/GraphLegend.tsx
msgid "Clusters"
msgstr "Clusters"
@@ -1149,6 +1176,10 @@ msgstr "Command palette"
msgid "Commands"
msgstr "Commands"
+#: src/components/settings/TerminalSection.tsx
+msgid "Commands run with the full access of your macOS user account on this machine. Turn this off to disable the shell."
+msgstr "Commands run with the full access of your macOS user account on this machine. Turn this off to disable the shell."
+
#: src/components/ShareBranchSwitchDialog.tsx
msgid "Commit or stash changes to switch:"
msgstr "Commit or stash changes to switch:"
@@ -1240,6 +1271,10 @@ msgstr "Connect to AI tools"
msgid "Connect to GitHub"
msgstr "Connect to GitHub"
+#: src/components/ClaudeReadinessBanner.tsx
+msgid "Connect tools"
+msgstr "Connect tools"
+
#: src/components/AuthModal.tsx
#: src/components/settings/AccountSection.tsx
msgid "Connected as @{login}"
@@ -1378,6 +1413,12 @@ msgstr "Could not duplicate item"
msgid "Could not enable sync: {detail}"
msgstr "Could not enable sync: {detail}"
+#. placeholder {0}: result.error
+#: src/components/settings/TerminalSection.tsx
+#: src/components/TerminalGate.tsx
+msgid "Could not enable the terminal: {0}"
+msgstr "Could not enable the terminal: {0}"
+
#: src/components/ShareBranchSwitchDialog.tsx
msgid "Could not fetch branch. Check your connection."
msgstr "Could not fetch branch. Check your connection."
@@ -1391,10 +1432,6 @@ msgstr "Could not finalize project setup. Try again."
msgid "Could not initialize {0}."
msgstr "Could not initialize {0}."
-#: src/lib/dispatch-open-in-terminal.ts
-msgid "Could not launch Terminal"
-msgstr "Could not launch Terminal"
-
#: src/components/NewItemDialog.tsx
msgid "Could not load templates: {templatesError}. You can still create a blank note."
msgstr "Could not load templates: {templatesError}. You can still create a blank note."
@@ -1419,10 +1456,6 @@ msgstr "Could not open folder picker"
msgid "Could not open GitHub sign-in. Please try again."
msgstr "Could not open GitHub sign-in. Please try again."
-#: src/lib/dispatch-open-in-terminal.ts
-msgid "Could not open Terminal"
-msgstr "Could not open Terminal"
-
#: src/components/FileTree.tsx
msgid "Could not reach server"
msgstr "Could not reach server"
@@ -1443,6 +1476,11 @@ msgstr "Could not start creating a new item"
msgid "Could not switch to {shareBranch}. Try switching manually."
msgstr "Could not switch to {shareBranch}. Try switching manually."
+#. placeholder {0}: result.error
+#: src/components/settings/TerminalSection.tsx
+msgid "Could not turn off the terminal: {0}"
+msgstr "Could not turn off the terminal: {0}"
+
#: src/components/FileSidebar.tsx
#: src/components/FileTree.tsx
msgid "Could not update sidebar settings"
@@ -1464,6 +1502,10 @@ msgstr "Couldn't auto-copy"
msgid "Couldn't clear the key — please try again."
msgstr "Couldn't clear the key — please try again."
+#: src/components/ClaudeReadinessBanner.tsx
+msgid "Couldn't connect Open Knowledge tools to Claude Code. Please try again."
+msgstr "Couldn't connect Open Knowledge tools to Claude Code. Please try again."
+
#: src/components/PublishToGitHubDialog.tsx
msgid "Couldn't construct the share URL. Try Done and re-share."
msgstr "Couldn't construct the share URL. Try Done and re-share."
@@ -1793,6 +1835,7 @@ msgstr "Disconnect"
msgid "Disconnecting"
msgstr "Disconnecting"
+#: src/components/ClaudeReadinessBanner.tsx
#: src/components/NavigatorApp.tsx
#: src/components/settings/SharingSection.tsx
msgid "Dismiss"
@@ -2051,6 +2094,14 @@ msgstr "Enable semantic search"
msgid "Enable sync"
msgstr "Enable sync"
+#: src/components/TerminalGate.tsx
+msgid "Enable terminal"
+msgstr "Enable terminal"
+
+#: src/components/settings/TerminalSection.tsx
+msgid "Enable terminal for this project"
+msgstr "Enable terminal for this project"
+
#: src/components/ActivityModeContent.tsx
msgid "Ended"
msgstr "Ended"
@@ -2513,6 +2564,10 @@ msgstr "Full path"
msgid "General"
msgstr "General"
+#: src/components/ClaudeReadinessBanner.tsx
+msgid "Get Claude Code"
+msgstr "Get Claude Code"
+
#: src/components/settings/SettingsDialogBody.tsx
msgid "Git auto-sync"
msgstr "Git auto-sync"
@@ -3147,10 +3202,6 @@ msgstr "Looking for <0>{lookingForUrl}</0>."
msgid "Lost connection to \"{docName}\"."
msgstr "Lost connection to \"{docName}\"."
-#: src/lib/dispatch-open-in-terminal.ts
-msgid "Lost connection to the main process"
-msgstr "Lost connection to the main process"
-
#: src/components/settings/SettingsDialogBody.tsx
msgid "Make this knowledge base available as a Claude Skill."
msgstr "Make this knowledge base available as a Claude Skill."
@@ -3851,19 +3902,6 @@ msgstr "Open in claude.ai, opens in browser with prompt pre-filled"
msgid "Open in current branch"
msgstr "Open in current branch"
-#: src/components/FileSidebar.tsx
-#: src/components/FileTree.tsx
-msgid "Open in Terminal"
-msgstr "Open in Terminal"
-
-#: src/components/FileTree.tsx
-msgid "Open in Terminal, {hint}"
-msgstr "Open in Terminal, {hint}"
-
-#: src/components/FileSidebar.tsx
-msgid "Open in Terminal, No workspace"
-msgstr "Open in Terminal, No workspace"
-
#: src/components/ConsentDialogBody.tsx
msgid "Open Knowledge initializes at <0>{projectDir}</0> — the parent of <1>{pickedRelative}</1> because it contains a <2>.git</2> folder (one .ok/ per git repo). <3>Content directory</3> defaults to <4>.</4> (the whole repo); type a sub-folder to narrow it."
msgstr "Open Knowledge initializes at <0>{projectDir}</0> — the parent of <1>{pickedRelative}</1> because it contains a <2>.git</2> folder (one .ok/ per git repo). <3>Content directory</3> defaults to <4>.</4> (the whole repo); type a sub-folder to narrow it."
@@ -4177,10 +4215,6 @@ msgstr "Path cannot start with \"/\""
msgid "Path resolves outside project"
msgstr "Path resolves outside project"
-#: src/lib/dispatch-open-in-terminal.ts
-msgid "Path resolves outside the project"
-msgstr "Path resolves outside the project"
-
#: src/editor/link-path-suggestions.tsx
msgid "Path suggestions"
msgstr "Path suggestions"
@@ -4612,6 +4646,10 @@ msgstr "Resolving deltas"
msgid "Resources"
msgstr "Resources"
+#: src/components/TerminalExitNotice.tsx
+msgid "Restart terminal"
+msgstr "Restart terminal"
+
#: src/lib/install-server-drift-listener.ts
msgid "Restart with this app's version"
msgstr "Restart with this app's version"
@@ -4705,6 +4743,10 @@ msgstr "Role"
msgid "root"
msgstr "root"
+#: src/components/settings/TerminalSection.tsx
+msgid "Run a real terminal docked inside Open Knowledge, starting in this project's folder."
+msgstr "Run a real terminal docked inside Open Knowledge, starting in this project's folder."
+
#: src/components/InstallInClaudeDesktopDialog.tsx
msgid "Run this in your terminal"
msgstr "Run this in your terminal"
@@ -5056,6 +5098,10 @@ msgstr "Show or hide document panel"
msgid "Show or hide Files"
msgstr "Show or hide Files"
+#: src/lib/keyboard-shortcuts.ts
+msgid "Show or hide terminal"
+msgstr "Show or hide terminal"
+
#: src/components/EditorToolbar.tsx
msgid "Show panel ({panelShortcut})"
msgstr "Show panel ({panelShortcut})"
@@ -5419,13 +5465,24 @@ msgstr "Templates"
msgid "Templates available"
msgstr "Templates available"
-#: src/lib/dispatch-open-in-terminal.ts
-msgid "Terminal took too long to respond"
-msgstr "Terminal took too long to respond"
+#: src/components/settings/SettingsDialogShell.tsx
+#: src/components/settings/TerminalSection.tsx
+#: src/components/TerminalPanel.tsx
+msgid "Terminal"
+msgstr "Terminal"
+
+#: src/components/TerminalRefusalNotice.tsx
+msgid "Terminal access isn't enabled for this project."
+msgstr "Terminal access isn't enabled for this project."
-#: src/lib/dispatch-open-in-terminal.ts
-msgid "Terminal.app not found"
-msgstr "Terminal.app not found"
+#: src/components/TerminalGate.tsx
+msgid "Terminal disabled"
+msgstr "Terminal disabled"
+
+#: src/components/settings/TerminalSection.tsx
+#: src/components/TerminalGate.tsx
+msgid "Terminal settings not loaded yet — try again in a moment."
+msgstr "Terminal settings not loaded yet — try again in a moment."
#: src/components/PropertyWidgets.tsx
msgid "Text"
@@ -5487,10 +5544,40 @@ msgstr "The repository is private and your GitHub account doesn't have access to
msgid "The repository was moved, renamed, or deleted."
msgstr "The repository was moved, renamed, or deleted."
+#: src/components/TerminalGate.tsx
+msgid "The terminal is not enabled for this project."
+msgstr "The terminal is not enabled for this project."
+
+#: src/components/TerminalGate.tsx
+msgid "The terminal is turned off for this project. Turn it back on to run commands here."
+msgstr "The terminal is turned off for this project. Turn it back on to run commands here."
+
+#. placeholder {0}: info.exitCode
+#: src/components/TerminalExitNotice.tsx
+msgid "The terminal session ended (exit code {0})."
+msgstr "The terminal session ended (exit code {0})."
+
+#. placeholder {0}: info.signal
+#: src/components/TerminalExitNotice.tsx
+msgid "The terminal session ended (signal {0})."
+msgstr "The terminal session ended (signal {0})."
+
+#: src/components/TerminalExitNotice.tsx
+msgid "The terminal session ended."
+msgstr "The terminal session ended."
+
+#: src/components/TerminalExitNotice.tsx
+msgid "The terminal stopped unexpectedly."
+msgstr "The terminal stopped unexpectedly."
+
#: src/components/settings/SettingsDialogBody.tsx
msgid "Theme"
msgstr "Theme"
+#: src/components/TerminalRefusalNotice.tsx
+msgid "There's no project folder for this window, so a terminal can't start here."
+msgstr "There's no project folder for this window, so a terminal can't start here."
+
#: src/components/ShareBranchSwitchDialog.tsx
msgid "This {targetNoun} only exists on branch <0>{shareBranch}</0>. You have uncommitted changes that prevent switching. Commit or stash your changes, then open the share link again."
msgstr "This {targetNoun} only exists on branch <0>{shareBranch}</0>. You have uncommitted changes that prevent switching. Commit or stash your changes, then open the share link again."
@@ -5681,6 +5768,10 @@ msgstr "Toggle source tab focus mode"
msgid "Toggle strikethrough formatting."
msgstr "Toggle strikethrough formatting."
+#: src/lib/keyboard-shortcuts.ts
+msgid "Toggle the bottom terminal panel."
+msgstr "Toggle the bottom terminal panel."
+
#: src/lib/keyboard-shortcuts.ts
msgid "Toggle the left file sidebar."
msgstr "Toggle the left file sidebar."
@@ -6059,6 +6150,10 @@ msgstr "yesterday"
msgid "you"
msgstr "you"
+#: src/components/TerminalGate.tsx
+msgid "You can also manage this in Settings."
+msgstr "You can also manage this in Settings."
+
#: src/components/AutoSyncOnboardingDialog.tsx
msgid "You can turn this on later in <0>Settings → Sync</0>."
msgstr "You can turn this on later in <0>Settings → Sync</0>."
diff --git a/packages/app/src/locales/pseudo/messages.json b/packages/app/src/locales/pseudo/messages.json
index 8639fb935..66a242269 100644
--- a/packages/app/src/locales/pseudo/messages.json
+++ b/packages/app/src/locales/pseudo/messages.json
@@ -365,15 +365,21 @@
"AAlr5Y": [
"Ńō ćōĺĺàƀ śēŕvēŕ ƒōŕ ţĥĩś ŵōŕķţŕēē — ŕũń <0>ōķ śţàŕţ</0> ĥēŕē, ōŕ ŕēōƥēń ţĥē ƥŕōĴēćţ."
],
+ "AE7BY3": ["Ţĥē ţēŕḿĩńàĺ śēśśĩōń ēńďēď."],
+ "ALhMYW": ["Ţēŕḿĩńàĺ"],
"AMyJts": [
"Ţĥĩś ƥàţĥ ĩś ōń àń ēxţēŕńàĺ vōĺũḿē (/Vōĺũḿēś/...). Ōƥēń Ķńōŵĺēďĝē ŵĩĺĺ ĺōśē ţŕàćķ ōƒ ƒĩĺēś ŵĥēń ţĥē ďŕĩvē ēĴēćţś."
],
"AQ-Lfg": ["Ćōũĺďń'ţ ĺōàď ţēḿƥĺàţēś"],
+ "AQGtjK": [
+ "Ćōḿḿàńďś ŕũń ŵĩţĥ ţĥē ƒũĺĺ àććēśś ōƒ ŷōũŕ ḿàćŌŚ ũśēŕ àććōũńţ ōń ţĥĩś ḿàćĥĩńē. Ţũŕń ţĥĩś ōƒƒ ţō ďĩśàƀĺē ţĥē śĥēĺĺ."
+ ],
"AThCb_": [
"Ōƥēń Ķńōŵĺēďĝē ḿàńàĝēś ţĥē <0>ōƥēń-ķńōŵĺēďĝē</0> ḾĆƤ śēŕvēŕ ńàḿē, ţĥē <1>ōƥēń-ķńōŵĺēďĝē-ũĩ</1> ĺàũńćĥ ćōńƒĩĝ, àńď <2>ōķ</2> / <3>ōƥēń-ķńōŵĺēďĝē</3> ōń ƤÀŢĤ (ĩńćĺũďĩńĝ ŌĶ-ōŵńēď śŷḿĺĩńķś). Ũśĩńĝ à ćũśţōḿ ŵŕàƥƥēŕ? Ŕēĝĩśţēŕ ĩţ ũńďēŕ à ďĩƒƒēŕēńţ ńàḿē."
],
"AVW-K9": ["Ƒàĩĺēď ţō ĺōàď ōŕƥĥàń ƥàĝēś"],
"AWOSPo": ["Źōōḿ ĩń"],
+ "AcK_r0": ["Ćĺàũďē ĆĹĨ"],
"AdcGcG": ["Àƥƥĺŷĩńĝ ŷōũŕ ćĥàńĝē"],
"AddR83": ["Ćōũĺď ńōţ ćŕēàţē ƥŕōĴēćţ. Ţŕŷ àĝàĩń ōŕ ƥĩćķ à ďĩƒƒēŕēńţ ĺōćàţĩōń."],
"AeHuzT": ["# Ōńē ƥàţţēŕń ƥēŕ ĺĩńē.\n# Ēxàḿƥĺēś:\n# ďŕàƒţś/\n# *.ďŕàƒţ.ḿď\n# !ķēēƥ.ḿď"],
@@ -409,7 +415,7 @@
],
"BGHHtQ": ["Śĩńĝĺē ƥàĝē"],
"BH56dn": ["Ćũśţōḿ ďĩśƥĺàŷ ţēxţ"],
- "BJpGCq": ["Ōƥēń ĩń Ţēŕḿĩńàĺ"],
+ "BQKHuL": ["Ŕēśţàŕţ ţēŕḿĩńàĺ"],
"BQu9Pg": ["Śŷḿĺĩńķ"],
"BY-g4_": ["Àďď ƥàţţēŕń"],
"Bdha5y": ["Ƥũƀĺĩśĥĩńĝ..."],
@@ -448,7 +454,6 @@
"DId6MT": ["ƤŕōĴēćţ-ĺēvēĺ ƥàĝēś ŵĩţĥ ńō ōũţĝōĩńĝ ĝŕàƥĥ ēďĝēś."],
"DPfwMq": ["Ďōńē"],
"DVh_Tb": ["Ƒàĩĺēď ţō ćĺēàń ũƥ àƒţēŕ ţŕàśĥ"],
- "DYwdxG": ["Ćōũĺď ńōţ ōƥēń Ţēŕḿĩńàĺ"],
"D_WKe_": ["Ćĺĩćķ àń àĝēńţ'ś àvàţàŕ ĩń ţĥē ƥŕēśēńćē ƀàŕ ţō vĩēŵ ţĥēĩŕ śēśśĩōń."],
"DeDYLr": ["Ũńŕēćōĝńĩźēď ŵĩķĩ ĺĩńķ"],
"DhLHEb": ["Ƒàĩĺēď ţō ĺōàď àćţĩvĩţŷ"],
@@ -461,7 +466,9 @@
],
"Dw1T_W": ["Ŕēńàḿē ", ["label"]],
"E1_c72": ["Ţàśķ ĺĩśţ"],
+ "E1tG2u": ["Ĝēţ Ćĺàũďē Ćōďē"],
"E2Mv-X": ["Ćōƥŷ śōũŕćē"],
+ "E4XYYH": ["Ēńàƀĺē ţēŕḿĩńàĺ ƒōŕ ţĥĩś ƥŕōĴēćţ"],
"E7BhZn": ["ßĺàńķ ńōţē"],
"E9bKSA": ["Ćŕēàţĩńĝ"],
"EBVbtP": ["Ćōũĺď ńōţ ďũƥĺĩćàţē ĩţēḿ"],
@@ -582,6 +589,7 @@
"I5AfhE": ["Śŷńć śţàţũś ũńàvàĩĺàƀĺē — śēŕvēŕ ũńŕēàćĥàƀĺē."],
"IA1wNb": ["Ţĥē Ćĺàũďē Ďēśķţōƥ Àƥƥ ďĩďń'ţ ōƥēń ţĥē ƒĩĺē. Ĩś ĩţ ĩńśţàĺĺēď? (", ["msg"], ")"],
"IA6JW2": ["Ďēţēćţĩńĝ"],
+ "ICoNYz": ["Ŷōũ ćàń àĺśō ḿàńàĝē ţĥĩś ĩń Śēţţĩńĝś."],
"IInnZo": ["Ćōńƒĺĩćţ"],
"IKoTAC": ["Ķēēƥ ďĩśàƀĺēď"],
"IN4UX8": ["Śēàŕćĥ (", ["searchShortcut"], ")"],
@@ -595,6 +603,7 @@
"If0crP": ["Ōƥēń ŵĩţĥ ÀĨ ", ["targetDisplayName"], ", ", ["hint"]],
"IgTwLt": ["Ōƥēń ţĥĩś ďōćũḿēńţ ĩń ţĥē ēďĩţōŕ àńď ćōĺĺàƥśē ţĥē ĝŕàƥĥ."],
"Ik-gP0": ["Ĥēàďĩńĝ Ĥ", ["level"], ": ", ["text"]],
+ "Iq8zdU": ["Ćĺōśē ţēŕḿĩńàĺ"],
"IrB5AK": [
"Śēŕvēŕ-śĩďē ćĺēàńũƥ ƒàĩĺēď ƒōŕ ",
["failedCount", "plural", { "one": ["#", " ĩţēḿ"], "other": ["#", " ĩţēḿś"] }]
@@ -654,6 +663,7 @@
["componentName"],
"> ĩśń'ţ à ķńōŵń ćōḿƥōńēńţ. Ćōƥŷ ţĥē śōũŕćē ţō ũśē ĩţ ēĺśēŵĥēŕē, ōŕ ďēĺēţē ţĥē ƀĺōćķ."
],
+ "Khxcyu": ["Ţēŕḿĩńàĺ àććēśś ĩśń'ţ ēńàƀĺēď ƒōŕ ţĥĩś ƥŕōĴēćţ."],
"KkEAud": ["Ćŕēàţē à ƒĩĺē ƒŕōḿ ţĥē ćũŕŕēńţ ďōćũḿēńţ ōŕ ƒōĺďēŕ ćōńţēxţ."],
"KmydK6": ["ßōĺď"],
"KnoB--": ["Ŵĩĺĺ ƀē śàvēď àś <0>", ["sanitized"], "</0>."],
@@ -691,6 +701,7 @@
"LpB85N": ["Ƥĺàĩń"],
"LtI9AS": ["Ōŵńēŕ"],
"LtSYdi": ["Ŕēvēàĺ ĩń Ƒĩńďēŕ"],
+ "LtVw4J": ["Ćĺàũďē ĆĹĨ, ", ["hint"]],
"M1OfV9": ["Ńēxţ śōũŕćē ďĩàĝńōśţĩć"],
"M3ytY_": [
"Ţĥĩś ĺōōķś ĺĩķē à ďŕĩvē ŕōōţ (ē.ĝ., Ć:\\). Śćàƒƒōĺďĩńĝ ĥēŕē ŵĩĺĺ śćàń àń ēńţĩŕē ďŕĩvē."
@@ -835,6 +846,9 @@
],
"R0jJzV": ["Ƥàśţē ŨŔĹ, ōŵńēŕ/ŕēƥō, ōŕ śēàŕćĥ ŷōũŕ ŕēƥōś"],
"R3y75Z": ["Ēďĩţ śōũŕćē"],
+ "R65q-K": [
+ "À ŕēàĺ śĥēĺĺ ĩś ōƒƒ ƒōŕ ţĥĩś ƥŕōĴēćţ. Ţũŕńĩńĝ ĩţ ōń ŕũńś ćōḿḿàńďś ŵĩţĥ ţĥē ƒũĺĺ àććēśś ōƒ ŷōũŕ ḿàćŌŚ ũśēŕ àććōũńţ."
+ ],
"RDrXh4": ["Ćōńƒĩĝũŕē ũśēŕ, ƥŕōĴēćţ, àńď ĩńţēĝŕàţĩōń śēţţĩńĝś."],
"RGCCrg": ["Ćōƥŷ śĥàŕē ĺĩńķ"],
"RGkNeJ": ["Ĩńĩţĩàĺĩźē à śţàŕţēŕ ƥàćķ"],
@@ -901,6 +915,9 @@
"U3IvM5": ["Ƒũĺĺ ĝũĩďē"],
"U5Spo9": ["Ćōńţēńţ ďĩŕēćţōŕŷ ḿũśţ ƀē ĩńśĩďē ţĥē ƥŕōĴēćţ"],
"U8CD-l": ["Ćōƥŷ ƒũĺĺ ƥàţĥ, Ńō ŵōŕķśƥàćē"],
+ "UA171M": [
+ "Ŕũń à ŕēàĺ ţēŕḿĩńàĺ ďōćķēď ĩńśĩďē Ōƥēń Ķńōŵĺēďĝē, śţàŕţĩńĝ ĩń ţĥĩś ƥŕōĴēćţ'ś ƒōĺďēŕ."
+ ],
"UBv8UK": ["Ďēĺēţē Ƥēŕḿàńēńţĺŷ"],
"UDFrWm": ["Ćĥēćķĩńĝ ĜĩţĤũƀ ćōńńēćţĩōń..."],
"UL8A9w": ["Ţàĝ"],
@@ -940,6 +957,7 @@
"VYd_YA": ["Ōƥēń àń ēxĩśţĩńĝ ƥŕōĴēćţ ƒōĺďēŕ ƒŕōḿ ďĩśķ."],
"VZGh8G": ["Ƒōĺď, ũńƒōĺď, ƒōĺď àĺĺ, ōŕ ũńƒōĺď àĺĺ śōũŕćē ŕàńĝēś."],
"VZSBXL": ["Śēḿàńţĩć ŕàńķĩńĝ àćţĩvàţēś ţĥē ƒĩŕśţ ţĩḿē àń àĝēńţ ŕũńś à śēàŕćĥ."],
+ "V_6bJ4": ["Ţēŕḿĩńàĺ śēţţĩńĝś ńōţ ĺōàďēď ŷēţ — ţŕŷ àĝàĩń ĩń à ḿōḿēńţ."],
"VbqhBI": ["Àĺŕēàďŷ àţ ", ["assetContentPath"], " — ŕēũśĩńĝ."],
"VcqWBy": ["Ũƥĺōàď ḿàŷ ĥàvē śũććēēďēď ƀũţ ţĥē śĩďēƀàŕ ĩś ōũţ ōƒ ďàţē — ŕēƒŕēśĥ ţō ŕēśŷńć"],
"VdXv4D": ["Ćĺōńē ƒŕōḿ ĜĩţĤũƀ"],
@@ -1080,7 +1098,6 @@
"Zul8Ry": ["ńēvēŕ"],
"ZxXhLY": ["Ĥĩďē Ƒĩĺēś (", ["sidebarShortcut"], ")"],
"Zz25kq": ["Śĥōŵ Ƒĩĺēś (", ["sidebarShortcut"], ")"],
- "_6IEmc": ["Ōƥēń ĩń Ţēŕḿĩńàĺ, Ńō ŵōŕķśƥàćē"],
"_7UQ7y": ["Ŵĥōĺē ŵōŕď"],
"_8quCH": ["Ƒŕōḿ ţēḿƥĺàţē"],
"_902BE": [
@@ -1109,6 +1126,7 @@
"_TF8ep": ["Ƒàĩĺēď ţō ŕēńďēŕ ƤĎƑ"],
"_VRtd7": ["Ćōũĺďń'ţ śēńď ţĥē śēĺēćţĩōń — ƥĺēàśē ţŕŷ àĝàĩń."],
"_W-elG": ["(ĩńĺĩńē)"],
+ "_XWY2J": ["Ţēŕḿĩńàĺ ďĩśàƀĺēď"],
"_gkGSK": ["ďēĺēţēď ţēḿƥĺàţē"],
"_pY_Vq": ["Ţĥē ŕēƥōśĩţōŕŷ ŵàś ḿōvēď, ŕēńàḿēď, ōŕ ďēĺēţēď."],
"_qD6mn": ["Ƥĩćķ ţĥē ƒōĺďēŕ ŵĥēŕē ŷōũ'vē ćĺōńēď ĩţ."],
@@ -1205,8 +1223,10 @@
"dN20LW": [
"Śēḿàńţĩć śēàŕćĥ ĩś ōń, ƀũţ ńō ÀƤĨ ķēŷ ĩś śēţ — śēàŕćĥ ƒàĺĺś ƀàćķ ţō ķēŷŵōŕď ḿàţćĥĩńĝ. Àďď ōńē ĩń <0>Śēţţĩńĝś → Àććōũńţ</0> (ĩţ'ś śţōŕēď ōńćē ƒōŕ ŷōũŕ ŵĥōĺē ḿàćĥĩńē)."
],
+ "dNM58w": ["Ćĺàũďē Ćōďē (ćĺàũďē) ĩśń'ţ ĩńśţàĺĺēď ōŕ ōń ŷōũŕ ƤÀŢĤ."],
"dOHMA0": ["Ƒàĩĺēď ţō ḿōvē"],
"dOxPd4": ["Ƒōōţńōţē"],
+ "dPOFid": ["Śĥōŵ ōŕ ĥĩďē ţēŕḿĩńàĺ"],
"dTaauv": ["Ŕēàśōń: ", ["reason"]],
"dUQ7_J": [
"Àďď ḿēàńĩńĝ-ƀàśēď ŕàńķĩńĝ ţō śēàŕćĥ śō ćōńćēƥţũàĺĺŷ-ŕēĺàţēď ƥàĝēś śũŕƒàćē ēvēń ŵĥēń ţĥēŷ śĥàŕē ńō ķēŷŵōŕďś. Ţĥĩś śēţţĩńĝ àƥƥĺĩēś ōńĺŷ ţō ţĥĩś ćōḿƥũţēŕ."
@@ -1237,7 +1257,7 @@
"Ŵŕĩţēś à ƥŕōĴēćţ-ḾĆƤ ćōńƒĩĝ ƒōŕ ēàćĥ śēĺēćţēď ţōōĺ; Ćĺàũďē àĺśō ĝēţś <0>.ćĺàũďē/ĺàũńćĥ.Ĵśōń</0>."
],
"eVPynQ": ["Ōƥēń <0><1>", ["verificationUri"], "</1><2/></0> àńď ēńţēŕ ţĥĩś ćōďē:"],
- "ehLu5O": ["Ōƥēń ĩń Ţēŕḿĩńàĺ, ", ["hint"]],
+ "eiG6_3": ["Ţĥē ţēŕḿĩńàĺ ĩś ńōţ ēńàƀĺēď ƒōŕ ţĥĩś ƥŕōĴēćţ."],
"emgiet": ["Àũţĥōŕĩţàţĩvē ćōńţēńţ; ḿĩŕŕōŕēď vēŕƀàţĩḿ ēvēŕŷŵĥēŕē ĩţ'ś ŕēƒēŕēńćēď."],
"ensWZc": ["ōŕ śţàŕţ ƒŕōḿ śćŕàţćĥ <0/>"],
"euc6Ns": ["Ďũƥĺĩćàţē"],
@@ -1245,6 +1265,8 @@
"f1XQyZ": ["Ḿōvē ƀĺōćķ"],
"f65AOQ": ["Śţàŕţ ƒŕōḿ"],
"f8jU-L": [["0"], "/", ["1"], " — ", ["2"]],
+ "fBHvBn": ["Ţĥēŕē'ś ńō ƥŕōĴēćţ ƒōĺďēŕ ƒōŕ ţĥĩś ŵĩńďōŵ, śō à ţēŕḿĩńàĺ ćàń'ţ śţàŕţ ĥēŕē."],
+ "fBaTkM": ["Ţōĝĝĺē ţĥē ƀōţţōḿ ţēŕḿĩńàĺ ƥàńēĺ."],
"fG0X0e": ["Ĩńśţàĺĺ ", ["brand"], " →"],
"fIgqfQ": ["Ŕēĩńśţàĺĺĩńĝ"],
"fJgQHX": ["Ƒàĩĺēď ţō ćŕēàţē ƒĩĺē"],
@@ -1284,6 +1306,7 @@
"gYz2ep": ["Ēxƥĩŕēś ĩń ", ["timeLabel"]],
"gbHcbI": ["Ƒàĩĺēď ţō ďēĺēţē ƥŕōƥēŕţŷ"],
"gcV0dI": ["Ţĥē ƒōĺďēŕś àńď ţēḿƥĺàţēś àŕē ĩń ƥĺàćē; ţĥēŕē'ś ńōţĥĩńĝ ĺēƒţ ţō śćàƒƒōĺď."],
+ "gfohmY": ["Ćōńńēćţ ţōōĺś"],
"ggm6JX": [
"Ţĥĩś ƥàĝē ďōēśń'ţ ēxĩśţ ŷēţ. Ōƥēń ĩţ ţō ćŕēàţē ţĥē ƥàĝē ĩń ţĥē ēďĩţōŕ àńď ćōĺĺàƥśē ţĥē ĝŕàƥĥ."
],
@@ -1374,6 +1397,7 @@
"j9Vqvc": ["ĩńĥēŕĩţēď"],
"jEdF24": ["Ḿĩśśĩńĝ ƥàĝē: ", ["linkTitle"], ". Ćĺĩćķ ţō ćŕēàţē."],
"jGJy-9": ["Ďōŵńĺōàďś ", ["shareOwner"], "/", ["shareRepo"], " ƒŕōḿ ĜĩţĤũƀ."],
+ "jKd3AP": ["Ćōũĺď ńōţ ēńàƀĺē ţĥē ţēŕḿĩńàĺ: ", ["0"]],
"jPUPvG": ["Ćōũĺďń'ţ ŕēśōĺvē ţĥē ćōńƒĺĩćţ ƒōŕ ", ["filePath"], "."],
"jRHdCz": ["Ƒàĩĺēď ţō ĺōàď ƤĎƑ"],
"jSO1X5": ["Ĩńĥēŕĩţēď ţēḿƥĺàţēś ćàń'ţ ƀē ŕēńàḿēď ĥēŕē — ŕēńàḿē ĩţ ĩń ţĥē ƒōĺďēŕ ţĥàţ ōŵńś ĩţ."],
@@ -1384,7 +1408,6 @@
"jdGUeI": ["Ćōũĺďń'ţ ćŕēàţē ţēḿƥĺàţē: ", ["error"]],
"jerqF0": ["Ĺōàďĩńĝ ƀŕàńćĥ śţàţē"],
"jhtG3I": [" Ŷōũŕ śēĺēćţĩōń ĥàś ƀēēń ŕēśţōŕēď."],
- "jjmuxV": ["Ĺōśţ ćōńńēćţĩōń ţō ţĥē ḿàĩń ƥŕōćēśś"],
"jjtmV_": ["Ƒĩŕśţ ƒĩĺē ńàḿē"],
"jol95m": ["Ƒàĩĺēď ţō ōƥēń ƤŕōĴēćţ Ńàvĩĝàţōŕ."],
"ju38ms": [
@@ -1403,7 +1426,6 @@
" ŕēàďŷ. Ŕēśũĺţś ḿàŷ ƀē ĩńćōḿƥĺēţē."
],
"kCqCyf": ["Ōƥēń ĆōďēḾĩŕŕōŕ'ś ĺĩńţ ďĩàĝńōśţĩćś ƥàńēĺ."],
- "kDuh1E": ["Ƥàţĥ ŕēśōĺvēś ōũţśĩďē ţĥē ƥŕōĴēćţ"],
"kFLlsI": ["Ĩńśēŕţ à ƒōōţńōţē ŕēƒēŕēńćē + ḿàţćĥĩńĝ ďēƒĩńĩţĩōń śţũƀ."],
"kFgMHe": ["Ĺōćàĺ ōńĺŷ ōń ţĥĩś ḿàćĥĩńē"],
"kNqMMd": ["Ƒōĺďēŕ"],
@@ -1420,7 +1442,6 @@
"kmKqZg": ["Ćĺũśţēŕś"],
"knjOzA": ["Ţàĝ vàĺũē"],
"kolRU1": ["Ďō ŷōũ ŵàńţ ţō ƥēŕḿàńēńţĺŷ ďēĺēţē ĩńśţēàď?"],
- "ktATCe": ["Ćōũĺď ńōţ ĺàũńćĥ Ţēŕḿĩńàĺ"],
"ku0yLQ": ["Ƥàĝēś àŕē ēḿƀēďďēď ţĥē ƒĩŕśţ ţĩḿē à śēàŕćĥ ńēēďś ţĥēḿ."],
"ky9Tuc": ["Ēďĩţ ", ["0"], " śōũŕćē"],
"l17ab4": ["Ćōũĺď ńōţ ŵŕĩţē ƥŕōĴēćţ ƒĩĺēś. Ţŕŷ à ďĩƒƒēŕēńţ ĺōćàţĩōń."],
@@ -1433,6 +1454,7 @@
"lGs_bQ": ["Ƥàĝē <0>*</0>"],
"lHwYMr": ["Śēŕvēŕ ēŕŕōŕ: ", ["status"], " ", ["statusText"]],
"lIn9L9": ["Ďĩśàƀĺē śŷńć"],
+ "lLGJG6": ["Ćōũĺďń'ţ ćōńńēćţ Ōƥēń Ķńōŵĺēďĝē ţōōĺś ţō Ćĺàũďē Ćōďē. Ƥĺēàśē ţŕŷ àĝàĩń."],
"lPzyrU": ["Àĺĺ ĥũńķś ŕēśōĺvēď"],
"lVWEIL": ["Ĩńďēxēď ", ["embedded"], " ōƒ ", ["total"], " ƥàĝēś."],
"lWNpNB": ["Àďď ćũŕśōŕś ōŕ śēĺēćţ ḿàţćĥĩńĝ ōććũŕŕēńćēś ţĥŕōũĝĥ ĆōďēḾĩŕŕōŕ."],
@@ -1515,6 +1537,7 @@
"nCzR-G": ["Ćōƥŷ ćōďē ", ["userCode"]],
"nDT8qt": ["Ĩńĩţĩàĺĩźēď ", ["0"], " ƀũţ ćōũĺď ńōţ ōƥēń ĩţ."],
"nNYV3Y": ["àńď ", ["remaining"], " ḿōŕē"],
+ "nPhvQ_": ["Ćĺàũďē Ćōďē ĩś ĩńśţàĺĺēď, ƀũţ Ōƥēń Ķńōŵĺēďĝē ţōōĺś àŕēń'ţ ćōńńēćţēď ţō ĩţ ŷēţ."],
"nTwL53": ["Ōƥēń à ďōć ţō śĥàŕē ĩţś ŨŔĹ."],
"nWv1ja": ["Ḿàńàĝē ĥĩďďēń ƒĩĺēś ĩń Śēţţĩńĝś → Ĩĝńōŕē ƥàţţēŕńś."],
"nYKerc": ["(ũśēŕ-ĺēvēĺ ōńĺŷ)"],
@@ -1550,6 +1573,9 @@
"oQA-cA": ["Ƒũĺĺ ƥàţĥ"],
"oS1YpJ": ["Ōƥēń ţĥē ƤŕōĴēćţ Ńàvĩĝàţōŕ."],
"oXKEsy": ["Ďēĺēţē àń àďĴàćēńţ ŵĩķĩ-ĺĩńķ ōŕ ţàĝ ćĥĩƥ."],
+ "oYepHb": [
+ "Ţĥē ţēŕḿĩńàĺ ĩś ţũŕńēď ōƒƒ ƒōŕ ţĥĩś ƥŕōĴēćţ. Ţũŕń ĩţ ƀàćķ ōń ţō ŕũń ćōḿḿàńďś ĥēŕē."
+ ],
"ogAuyr": ["ßàćķ ţō ďōćũḿēńţ vĩēŵ"],
"omXJcU": ["Ćĺōśē ōţĥēŕś"],
"optX0N": [["0"], "ĥ àĝō"],
@@ -1575,6 +1601,7 @@
"pWT04I": ["Ćĥēćķĩńĝ..."],
"pWbsW6": ["Ĺōàďĩńĝ ďōćś"],
"pZAs1T": ["Ƒàĩĺēď ţō ĺōàď ōũţĝōĩńĝ ĺĩńķś"],
+ "pajIrl": ["Ćōũĺď ńōţ ţũŕń ōƒƒ ţĥē ţēŕḿĩńàĺ: ", ["0"]],
"pbwTg6": [["seconds"], "ś àĝō"],
"pcfY8r": ["ōƥēńś ĩń ƀŕōŵśēŕ"],
"pckX1A": [["0", "plural", { "one": ["#", " ũśē"], "other": ["#", " ũśēś"] }]],
@@ -1589,6 +1616,7 @@
"prHfed": ["Ēàćĥ śēĺēćţēď ţōōĺ ĝēţś àń Ōƥēń Ķńōŵĺēďĝē ḾĆƤ ēńţŕŷ."],
"pzutoc": ["Ĩţàĺĩć"],
"q2kXMG": ["Ĩńĺĩńē Ḿàţĥ"],
+ "q4YJl_": ["Ţĥē ţēŕḿĩńàĺ śēśśĩōń ēńďēď (ēxĩţ ćōďē ", ["0"], ")."],
"q6-JVU": ["Ĺōàďĩńĝ ƥàĝēś"],
"qAQVSD": ["Ƥàĝē ĥēàďĩńĝś ŕēśƥōńśē ŵàś ńōţ ĵŚŌŃ"],
"qAhFeg": [
@@ -1720,6 +1748,7 @@
"uF9ruK": ["Śàvĩńĝ"],
"uH_S-u": [["loadErrorTitle"], ": ", ["message"]],
"uKRYiW": ["Śŷńć śţàţũś ũńàvàĩĺàƀĺē — śēŕvēŕ ēŕŕōŕ."],
+ "uL_Wx8": ["Ţĥē ţēŕḿĩńàĺ śţōƥƥēď ũńēxƥēćţēďĺŷ."],
"uM6jnS": ["Ŕēśţōŕē ƒàĩĺēď"],
"uO9WLl": ["Ƥũśĥ"],
"uQNW00": ["Ďēţàćĥēď ĤĒÀĎ — ćĥēćķōũţ à ƀŕàńćĥ ţō ŕēśũḿē"],
@@ -1731,6 +1760,7 @@
],
"uWx2ZP": ["Ĺàśţ śŷńć"],
"u_lS4C": ["Ćĺōńē ćōḿƥĺēţē — ōƥēńĩńĝ ƥŕōĴēćţ"],
+ "ubMwcO": ["Ţĥē ţēŕḿĩńàĺ śēśśĩōń ēńďēď (śĩĝńàĺ ", ["0"], ")."],
"ugoTXs": ["ƒōĺďēŕ"],
"uhJEA2": [
[
@@ -1745,6 +1775,7 @@
"uuoHOU": ["Ćōḿḿàńď ƒàĩĺēď."],
"uynXup": [["tokens", "plural", { "one": ["ţōķēń"], "other": ["ţōķēńś"] }]],
"v-h2hx": ["Ďēĺēţē ", ["targetGitPath"]],
+ "v2ZW0K": ["Ēńàƀĺē ţēŕḿĩńàĺ"],
"v41fCm": ["Ƒĩĺē ńōţ ƒōũńď"],
"v75Em9": [
[
@@ -1761,7 +1792,6 @@
"vPYaz3": ["Śćàƒƒōĺď ďĩŕēćţĺŷ ũńďēŕ ţĥĩś ƥŕōĴēćţ."],
"vQIVHc": ["Ƒōĺďēŕ ƥŕōƥēŕţĩēś"],
"vWc9a0": ["Ţŷƥē ţō ēďĩţ; <0>⌘ Ēńţēŕ</0> śàvēś, <1>Ēść</1> ćàńćēĺś."],
- "vY54W_": ["Ţēŕḿĩńàĺ.àƥƥ ńōţ ƒōũńď"],
"vZVeFG": ["Ũƥĺōàď ƒàĩĺēď — ƥĺēàśē ţŕŷ àĝàĩń"],
"vbK_ZG": ["Ƒĩĺēś śĩďēƀàŕ"],
"ve8vEM": ["Ćōďē ēxƥĩŕēď — ƥĺēàśē ţŕŷ àĝàĩń"],
@@ -1788,7 +1818,6 @@
"Ŷōũ ƥĩćķēď ~/Ďōŵńĺōàďś. Ƒĩĺēś ţĥēŕē àŕē ũśũàĺĺŷ ţŕàńśĩēńţ — ćōńśĩďēŕ à śţàƀĺē ƒōĺďēŕ ĩńśţēàď."
],
"wndeIl": ["ƤŕōĴēćţ-ĺēvēĺ ƥàĝēś ŵĩţĥ ńēĩţĥēŕ ĩńćōḿĩńĝ ńōŕ ōũţĝōĩńĝ ĝŕàƥĥ ēďĝēś."],
- "wrzAcD": ["Ţēŕḿĩńàĺ ţōōķ ţōō ĺōńĝ ţō ŕēśƥōńď"],
"wt8OSk": ["Ŕēǫũĩŕēś à ĝĩţ ŕēƥōśĩţōŕŷ — ƥĩćķ à ďĩƒƒēŕēńţ ƒōĺďēŕ ōŕ ēńàƀĺē ĝĩţ ĩńĩţ."],
"wvbc1r": ["Ćōũĺďń'ţ ōƥēń ďōćũḿēńţ"],
"x2fr_j": ["Ĝŕàƥĥ"],
diff --git a/packages/app/src/locales/pseudo/messages.po b/packages/app/src/locales/pseudo/messages.po
index 7f00a5e02..200f60b5e 100644
--- a/packages/app/src/locales/pseudo/messages.po
+++ b/packages/app/src/locales/pseudo/messages.po
@@ -455,6 +455,10 @@ msgstr ""
msgid "A pull quote stands out from the surrounding text."
msgstr ""
+#: src/components/settings/TerminalSection.tsx
+msgid "A real shell is off for this project. Turning it on runs commands with the full access of your macOS user account."
+msgstr ""
+
#: src/components/NewTemplateDialog.tsx
msgid "A reusable starting point for new documents in this folder."
msgstr ""
@@ -952,6 +956,25 @@ msgstr ""
msgid "Choose whether to commit <0>.ok/</0>, <1>.mcp.json</1> (and per-editor variants), project skills, and <2>.claude/launch.json</2> alongside content — or keep them on this machine only via <3>.git/info/exclude</3>."
msgstr ""
+#: src/components/handoff/OpenInAgentContextSubmenu.tsx
+#: src/components/handoff/OpenInAgentEmptySpaceSubmenu.tsx
+#: src/components/handoff/OpenInAgentMenu.tsx
+msgid "Claude CLI"
+msgstr ""
+
+#: src/components/handoff/OpenInAgentContextSubmenu.tsx
+#: src/components/handoff/OpenInAgentEmptySpaceSubmenu.tsx
+msgid "Claude CLI, {hint}"
+msgstr ""
+
+#: src/components/ClaudeReadinessBanner.tsx
+msgid "Claude Code (claude) isn't installed or on your PATH."
+msgstr ""
+
+#: src/components/ClaudeReadinessBanner.tsx
+msgid "Claude Code is installed, but Open Knowledge tools aren't connected to it yet."
+msgstr ""
+
#: src/components/settings/SettingsDialogShell.tsx
msgid "Claude Desktop"
msgstr ""
@@ -1070,6 +1093,10 @@ msgstr ""
msgid "Close others"
msgstr ""
+#: src/components/TerminalRefusalNotice.tsx
+msgid "Close terminal"
+msgstr ""
+
#: src/components/GraphLegend.tsx
msgid "Clusters"
msgstr ""
@@ -1144,6 +1171,10 @@ msgstr ""
msgid "Commands"
msgstr ""
+#: src/components/settings/TerminalSection.tsx
+msgid "Commands run with the full access of your macOS user account on this machine. Turn this off to disable the shell."
+msgstr ""
+
#: src/components/ShareBranchSwitchDialog.tsx
msgid "Commit or stash changes to switch:"
msgstr ""
@@ -1235,6 +1266,10 @@ msgstr ""
msgid "Connect to GitHub"
msgstr ""
+#: src/components/ClaudeReadinessBanner.tsx
+msgid "Connect tools"
+msgstr ""
+
#: src/components/AuthModal.tsx
#: src/components/settings/AccountSection.tsx
msgid "Connected as @{login}"
@@ -1373,6 +1408,12 @@ msgstr ""
msgid "Could not enable sync: {detail}"
msgstr ""
+#. placeholder {0}: result.error
+#: src/components/settings/TerminalSection.tsx
+#: src/components/TerminalGate.tsx
+msgid "Could not enable the terminal: {0}"
+msgstr ""
+
#: src/components/ShareBranchSwitchDialog.tsx
msgid "Could not fetch branch. Check your connection."
msgstr ""
@@ -1386,10 +1427,6 @@ msgstr ""
msgid "Could not initialize {0}."
msgstr ""
-#: src/lib/dispatch-open-in-terminal.ts
-msgid "Could not launch Terminal"
-msgstr ""
-
#: src/components/NewItemDialog.tsx
msgid "Could not load templates: {templatesError}. You can still create a blank note."
msgstr ""
@@ -1414,10 +1451,6 @@ msgstr ""
msgid "Could not open GitHub sign-in. Please try again."
msgstr ""
-#: src/lib/dispatch-open-in-terminal.ts
-msgid "Could not open Terminal"
-msgstr ""
-
#: src/components/FileTree.tsx
msgid "Could not reach server"
msgstr ""
@@ -1438,6 +1471,11 @@ msgstr ""
msgid "Could not switch to {shareBranch}. Try switching manually."
msgstr ""
+#. placeholder {0}: result.error
+#: src/components/settings/TerminalSection.tsx
+msgid "Could not turn off the terminal: {0}"
+msgstr ""
+
#: src/components/FileSidebar.tsx
#: src/components/FileTree.tsx
msgid "Could not update sidebar settings"
@@ -1459,6 +1497,10 @@ msgstr ""
msgid "Couldn't clear the key — please try again."
msgstr ""
+#: src/components/ClaudeReadinessBanner.tsx
+msgid "Couldn't connect Open Knowledge tools to Claude Code. Please try again."
+msgstr ""
+
#: src/components/PublishToGitHubDialog.tsx
msgid "Couldn't construct the share URL. Try Done and re-share."
msgstr ""
@@ -1788,6 +1830,7 @@ msgstr ""
msgid "Disconnecting"
msgstr ""
+#: src/components/ClaudeReadinessBanner.tsx
#: src/components/NavigatorApp.tsx
#: src/components/settings/SharingSection.tsx
msgid "Dismiss"
@@ -2046,6 +2089,14 @@ msgstr ""
msgid "Enable sync"
msgstr ""
+#: src/components/TerminalGate.tsx
+msgid "Enable terminal"
+msgstr ""
+
+#: src/components/settings/TerminalSection.tsx
+msgid "Enable terminal for this project"
+msgstr ""
+
#: src/components/ActivityModeContent.tsx
msgid "Ended"
msgstr ""
@@ -2508,6 +2559,10 @@ msgstr ""
msgid "General"
msgstr ""
+#: src/components/ClaudeReadinessBanner.tsx
+msgid "Get Claude Code"
+msgstr ""
+
#: src/components/settings/SettingsDialogBody.tsx
msgid "Git auto-sync"
msgstr ""
@@ -3142,10 +3197,6 @@ msgstr ""
msgid "Lost connection to \"{docName}\"."
msgstr ""
-#: src/lib/dispatch-open-in-terminal.ts
-msgid "Lost connection to the main process"
-msgstr ""
-
#: src/components/settings/SettingsDialogBody.tsx
msgid "Make this knowledge base available as a Claude Skill."
msgstr ""
@@ -3846,19 +3897,6 @@ msgstr ""
msgid "Open in current branch"
msgstr ""
-#: src/components/FileSidebar.tsx
-#: src/components/FileTree.tsx
-msgid "Open in Terminal"
-msgstr ""
-
-#: src/components/FileTree.tsx
-msgid "Open in Terminal, {hint}"
-msgstr ""
-
-#: src/components/FileSidebar.tsx
-msgid "Open in Terminal, No workspace"
-msgstr ""
-
#: src/components/ConsentDialogBody.tsx
msgid "Open Knowledge initializes at <0>{projectDir}</0> — the parent of <1>{pickedRelative}</1> because it contains a <2>.git</2> folder (one .ok/ per git repo). <3>Content directory</3> defaults to <4>.</4> (the whole repo); type a sub-folder to narrow it."
msgstr ""
@@ -4172,10 +4210,6 @@ msgstr ""
msgid "Path resolves outside project"
msgstr ""
-#: src/lib/dispatch-open-in-terminal.ts
-msgid "Path resolves outside the project"
-msgstr ""
-
#: src/editor/link-path-suggestions.tsx
msgid "Path suggestions"
msgstr ""
@@ -4607,6 +4641,10 @@ msgstr ""
msgid "Resources"
msgstr ""
+#: src/components/TerminalExitNotice.tsx
+msgid "Restart terminal"
+msgstr ""
+
#: src/lib/install-server-drift-listener.ts
msgid "Restart with this app's version"
msgstr ""
@@ -4700,6 +4738,10 @@ msgstr ""
msgid "root"
msgstr ""
+#: src/components/settings/TerminalSection.tsx
+msgid "Run a real terminal docked inside Open Knowledge, starting in this project's folder."
+msgstr ""
+
#: src/components/InstallInClaudeDesktopDialog.tsx
msgid "Run this in your terminal"
msgstr ""
@@ -5051,6 +5093,10 @@ msgstr ""
msgid "Show or hide Files"
msgstr ""
+#: src/lib/keyboard-shortcuts.ts
+msgid "Show or hide terminal"
+msgstr ""
+
#: src/components/EditorToolbar.tsx
msgid "Show panel ({panelShortcut})"
msgstr ""
@@ -5414,12 +5460,23 @@ msgstr ""
msgid "Templates available"
msgstr ""
-#: src/lib/dispatch-open-in-terminal.ts
-msgid "Terminal took too long to respond"
+#: src/components/settings/SettingsDialogShell.tsx
+#: src/components/settings/TerminalSection.tsx
+#: src/components/TerminalPanel.tsx
+msgid "Terminal"
msgstr ""
-#: src/lib/dispatch-open-in-terminal.ts
-msgid "Terminal.app not found"
+#: src/components/TerminalRefusalNotice.tsx
+msgid "Terminal access isn't enabled for this project."
+msgstr ""
+
+#: src/components/TerminalGate.tsx
+msgid "Terminal disabled"
+msgstr ""
+
+#: src/components/settings/TerminalSection.tsx
+#: src/components/TerminalGate.tsx
+msgid "Terminal settings not loaded yet — try again in a moment."
msgstr ""
#: src/components/PropertyWidgets.tsx
@@ -5482,10 +5539,40 @@ msgstr ""
msgid "The repository was moved, renamed, or deleted."
msgstr ""
+#: src/components/TerminalGate.tsx
+msgid "The terminal is not enabled for this project."
+msgstr ""
+
+#: src/components/TerminalGate.tsx
+msgid "The terminal is turned off for this project. Turn it back on to run commands here."
+msgstr ""
+
+#. placeholder {0}: info.exitCode
+#: src/components/TerminalExitNotice.tsx
+msgid "The terminal session ended (exit code {0})."
+msgstr ""
+
+#. placeholder {0}: info.signal
+#: src/components/TerminalExitNotice.tsx
+msgid "The terminal session ended (signal {0})."
+msgstr ""
+
+#: src/components/TerminalExitNotice.tsx
+msgid "The terminal session ended."
+msgstr ""
+
+#: src/components/TerminalExitNotice.tsx
+msgid "The terminal stopped unexpectedly."
+msgstr ""
+
#: src/components/settings/SettingsDialogBody.tsx
msgid "Theme"
msgstr ""
+#: src/components/TerminalRefusalNotice.tsx
+msgid "There's no project folder for this window, so a terminal can't start here."
+msgstr ""
+
#: src/components/ShareBranchSwitchDialog.tsx
msgid "This {targetNoun} only exists on branch <0>{shareBranch}</0>. You have uncommitted changes that prevent switching. Commit or stash your changes, then open the share link again."
msgstr ""
@@ -5676,6 +5763,10 @@ msgstr ""
msgid "Toggle strikethrough formatting."
msgstr ""
+#: src/lib/keyboard-shortcuts.ts
+msgid "Toggle the bottom terminal panel."
+msgstr ""
+
#: src/lib/keyboard-shortcuts.ts
msgid "Toggle the left file sidebar."
msgstr ""
@@ -6054,6 +6145,10 @@ msgstr ""
msgid "you"
msgstr ""
+#: src/components/TerminalGate.tsx
+msgid "You can also manage this in Settings."
+msgstr ""
+
#: src/components/AutoSyncOnboardingDialog.tsx
msgid "You can turn this on later in <0>Settings → Sync</0>."
msgstr ""
diff --git a/packages/app/tests/stress/file-tree-create.e2e.ts b/packages/app/tests/stress/file-tree-create.e2e.ts
index c46d2057c..892a0fcbe 100644
--- a/packages/app/tests/stress/file-tree-create.e2e.ts
+++ b/packages/app/tests/stress/file-tree-create.e2e.ts
@@ -211,7 +211,6 @@ async function installDelayedDesktopSessionBridge(
showAssetMenu: async () => {},
showItemInFolder: async () => {},
trashItem: async () => ({ ok: true as const }),
- openInTerminal: async () => ({ ok: true as const }),
},
editor: {
notifyActiveTargetChanged: () => {},
diff --git a/packages/app/tests/stress/fixtures/handoff-mocks.ts b/packages/app/tests/stress/fixtures/handoff-mocks.ts
index 25cda9eb0..5abba65dd 100644
--- a/packages/app/tests/stress/fixtures/handoff-mocks.ts
+++ b/packages/app/tests/stress/fixtures/handoff-mocks.ts
@@ -200,7 +200,6 @@ export async function installHandoffMocks(page: Page, cfg: HandoffMockConfig): P
showAssetMenu: async (): Promise<void> => {},
showItemInFolder: async (): Promise<void> => {},
trashItem: async (): Promise<{ ok: true }> => ({ ok: true }),
- openInTerminal: async (): Promise<{ ok: true }> => ({ ok: true }),
};
const bridge = {
@@ -352,6 +351,17 @@ export async function installHandoffMocks(page: Page, cfg: HandoffMockConfig): P
expandAll: (_cb: () => void) => () => {},
collapseAll: (_cb: () => void) => () => {},
},
+ terminal: {
+ create: async () => ({ ok: true as const, ptyId: 'mock-pty' }),
+ input: () => {},
+ resize: () => {},
+ kill: async () => {},
+ drain: () => {},
+ onData: () => () => {},
+ onExit: () => () => {},
+ claudePreflight: async () => ({ claude: 'present' as const, mcp: 'wired' as const }),
+ rewireClaudeMcp: async () => ({ claude: 'present' as const, mcp: 'wired' as const }),
+ },
platform: 'darwin' as const,
appVersion: 'test-0.0.0',
} satisfies OkDesktopBridge;
diff --git a/packages/cli/src/config/schema.test.ts b/packages/cli/src/config/schema.test.ts
index 31cf7feed..4543efba6 100644
--- a/packages/cli/src/config/schema.test.ts
+++ b/packages/cli/src/config/schema.test.ts
@@ -8,6 +8,7 @@ describe('ConfigSchema', () => {
expect(config.appearance.theme).toBeUndefined();
expect(config.editor.wordWrap).toBe(true);
expect(config.autoSync.enabled).toBeNull();
+ expect(config.terminal.enabled).toBeNull();
});
test('stale dropped fields pass loose-mode without throwing', () => {
@@ -43,6 +44,21 @@ describe('ConfigSchema', () => {
}
});
+ test('terminal.enabled accepts boolean true / false / null', () => {
+ for (const enabled of [true, false, null] as const) {
+ const config = ConfigSchema.parse({ terminal: { enabled } });
+ expect(config.terminal.enabled).toBe(enabled);
+ }
+ });
+
+ test('terminal.enabled rejects non-boolean values', () => {
+ const result = ConfigSchema.safeParse({ terminal: { enabled: 'true' } });
+ expect(result.success).toBe(false);
+ if (!result.success) {
+ expect(result.error.issues[0].path).toContain('enabled');
+ }
+ });
+
test('appearance.theme accepts the enum values', () => {
for (const theme of ['light', 'dark', 'system'] as const) {
const config = ConfigSchema.parse({ appearance: { theme } });
diff --git a/packages/core/src/config/field-registry.test.ts b/packages/core/src/config/field-registry.test.ts
index 91104d217..fcd04f15f 100644
--- a/packages/core/src/config/field-registry.test.ts
+++ b/packages/core/src/config/field-registry.test.ts
@@ -152,7 +152,7 @@ describe('ConfigSchema coverage (NR3 — every leaf has fieldRegistry metadata)'
]);
});
- test('project-local-strict fields cover autoSync.enabled + appearance.sidebar.* + search.semantic.*', () => {
+ test('project-local-strict fields cover autoSync.enabled + appearance.sidebar.* + search.semantic.* + terminal.enabled', () => {
const leaves: { path: string[]; schema: unknown }[] = [];
walkLeaves(ConfigSchema, [], leaves);
const projectLocalStrict = leaves
@@ -168,6 +168,7 @@ describe('ConfigSchema coverage (NR3 — every leaf has fieldRegistry metadata)'
'search.semantic.enabled',
'search.semantic.model',
'search.semantic.similarityFloor',
+ 'terminal.enabled',
]);
});
});
diff --git a/packages/core/src/config/merge-layered.test.ts b/packages/core/src/config/merge-layered.test.ts
index d2205fdb8..b6b741efc 100644
--- a/packages/core/src/config/merge-layered.test.ts
+++ b/packages/core/src/config/merge-layered.test.ts
@@ -146,6 +146,23 @@ describe('mergeLayered — scope-aware leaf short-circuits', () => {
const merged = mergeLayered(user, project, projectLocal);
expect(merged.autoSync?.enabled).toBe(true);
});
+
+ test("scope: 'project-local' (terminal.enabled) returns the project-local grant, ignoring project + user", () => {
+ const user = makeConfig({});
+ const project = makeConfig({});
+ const projectLocal = makeConfig({ terminal: { enabled: true } });
+
+ const merged = mergeLayered(user, project, projectLocal);
+ expect(merged.terminal?.enabled).toBe(true);
+ });
+
+ test('a clone without the project-local layer resolves terminal.enabled to null (grant never inherited)', () => {
+ const user = makeConfig({});
+ const project = makeConfig({});
+
+ const merged = mergeLayered(user, project);
+ expect(merged.terminal?.enabled).toBeNull();
+ });
});
describe('mergeLayered — backward compat for two-layer call sites', () => {
diff --git a/packages/core/src/config/schema.ts b/packages/core/src/config/schema.ts
index acc2158d0..81901b391 100644
--- a/packages/core/src/config/schema.ts
+++ b/packages/core/src/config/schema.ts
@@ -116,6 +116,21 @@ export const ConfigSchema = z.looseObject({
.default(null),
})
.default({ enabled: null }),
+ terminal: z
+ .looseObject({
+ enabled: z
+ .boolean()
+ .register(fieldRegistry, {
+ scope: 'project-local',
+ agentSettable: false,
+ defaultScope: 'project-local',
+ description:
+ 'Whether the in-app terminal (a real OS shell at full user privilege) is enabled for this project on this machine. null = not chosen yet (the first shell-open asks). Per-machine (project-local) — never shared via git, clone, or sync.',
+ })
+ .nullable()
+ .default(null),
+ })
+ .default({ enabled: null }),
telemetry: z
.looseObject({
localSink: z
diff --git a/packages/core/src/config/write-config-patch.test.ts b/packages/core/src/config/write-config-patch.test.ts
index 590b06cc4..e22b6bf65 100644
--- a/packages/core/src/config/write-config-patch.test.ts
+++ b/packages/core/src/config/write-config-patch.test.ts
@@ -180,6 +180,44 @@ describe('writeConfigPatch — project-local scope', () => {
});
expect(existsSync(join(testDir, '.ok', 'config.yml'))).toBe(false);
});
+
+ test('persists terminal.enabled to .ok/local/config.yml and round-trips across reads', async () => {
+ const granted = await writeConfigPatch({
+ cwd: testDir,
+ scope: 'project-local',
+ patch: { terminal: { enabled: true } },
+ });
+ expect(granted.ok).toBe(true);
+ if (!granted.ok) throw new Error('expected success');
+ expect(granted.path).toBe(projectLocalConfigPath());
+ expect(granted.appliedPaths).toContain('terminal.enabled');
+
+ const onDisk = readFileSync(projectLocalConfigPath(), 'utf-8');
+ expect(onDisk).toContain('terminal:');
+ expect(onDisk).toContain('enabled: true');
+
+ const revoked = await writeConfigPatch({
+ cwd: testDir,
+ scope: 'project-local',
+ patch: { terminal: { enabled: false } },
+ });
+ expect(revoked.ok).toBe(true);
+ if (!revoked.ok) throw new Error('expected success');
+ expect(revoked.effective.terminal.enabled).toBe(false);
+ const after = readFileSync(projectLocalConfigPath(), 'utf-8');
+ expect(after).toContain('enabled: false');
+ expect(after).not.toContain('enabled: true');
+ });
+
+ test('terminal.enabled grant lands ONLY in the gitignored .ok/local/ file, never the committed project file', async () => {
+ await writeConfigPatch({
+ cwd: testDir,
+ scope: 'project-local',
+ patch: { terminal: { enabled: true } },
+ });
+ expect(existsSync(projectLocalConfigPath())).toBe(true);
+ expect(existsSync(join(testDir, '.ok', 'config.yml'))).toBe(false);
+ });
});
describe('writeConfigPatch — user scope', () => {
@@ -427,6 +465,40 @@ describe('writeConfigPatch — scope-violation gate', () => {
if (result.error.code !== 'SCOPE_VIOLATION') throw new Error('wrong code');
expect(result.error.expectedScope).toBe('user');
});
+
+ test('project writer rejects terminal.enabled with SCOPE_VIOLATION; no fs write', async () => {
+ const result = await writeConfigPatch({
+ cwd: testDir,
+ scope: 'project',
+ patch: { terminal: { enabled: true } },
+ });
+ expect(result.ok).toBe(false);
+ if (result.ok) throw new Error('expected SCOPE_VIOLATION');
+ if (!isKnownConfigError(result.error)) throw new Error('expected known error');
+ expect(result.error.code).toBe('SCOPE_VIOLATION');
+ if (result.error.code !== 'SCOPE_VIOLATION') throw new Error('wrong code');
+ expect(result.error.path).toEqual(['terminal', 'enabled']);
+ expect(result.error.expectedScope).toBe('project-local');
+ expect(result.error.actualScope).toBe('project');
+ expect(existsSync(projectConfigPath())).toBe(false);
+ });
+
+ test('user writer rejects terminal.enabled with SCOPE_VIOLATION; no fs write', async () => {
+ const result = await writeConfigPatch({
+ cwd: testDir,
+ scope: 'user',
+ homedirOverride: testDir,
+ patch: { terminal: { enabled: false } },
+ });
+ expect(result.ok).toBe(false);
+ if (result.ok) throw new Error('expected SCOPE_VIOLATION');
+ if (!isKnownConfigError(result.error)) throw new Error('expected known error');
+ expect(result.error.code).toBe('SCOPE_VIOLATION');
+ if (result.error.code !== 'SCOPE_VIOLATION') throw new Error('wrong code');
+ expect(result.error.expectedScope).toBe('project-local');
+ expect(result.error.actualScope).toBe('user');
+ expect(existsSync(userConfigPath(testDir))).toBe(false);
+ });
});
describe('writeConfigPatch — concurrent writes (file lock)', () => {
diff --git a/packages/core/src/constants/menu-labels.ts b/packages/core/src/constants/menu-labels.ts
index 08c6f372e..c4d37e64e 100644
--- a/packages/core/src/constants/menu-labels.ts
+++ b/packages/core/src/constants/menu-labels.ts
@@ -5,7 +5,6 @@ export const MENU_LABELS = {
duplicate: 'Duplicate',
rename: 'Rename',
revealInFinder: 'Reveal in Finder',
- openInTerminal: 'Open in Terminal',
openWithAi: 'Open with AI',
copyPath: 'Copy path',
fullPath: 'Full path',
diff --git a/packages/core/src/desktop-bridge.ts b/packages/core/src/desktop-bridge.ts
index dc5b22573..7e57116bd 100644
--- a/packages/core/src/desktop-bridge.ts
+++ b/packages/core/src/desktop-bridge.ts
@@ -32,7 +32,6 @@ type OkMenuAction =
| 'duplicate'
| 'move-to-trash'
| 'reveal-in-finder'
- | 'open-in-terminal'
| 'send-to-ai'
| 'copy-full-path'
| 'copy-relative-path'
@@ -40,7 +39,8 @@ type OkMenuAction =
| 'toggle-show-all-files'
| 'expand-all-tree'
| 'collapse-all-tree'
- | 'toggle-doc-panel';
+ | 'toggle-doc-panel'
+ | 'toggle-terminal';
type OkUnsubscribe = () => void;
@@ -379,6 +379,7 @@ interface OkEditorViewMenuStateSnapshot {
readonly canCollapseAll: boolean;
readonly sidebarVisible: boolean;
readonly docPanelVisible?: boolean;
+ readonly terminalVisible?: boolean;
}
export interface OkSharingStatusResult {
@@ -419,6 +420,30 @@ export type OkServerRestartOutcome =
| { readonly ok: true }
| { readonly ok: false; readonly reason: 'eperm' | 'other' };
+export type OkPtyCreateResult =
+ | { readonly ok: true; readonly ptyId: string }
+ | { readonly ok: false; readonly reason: 'no-project' | 'not-consented' };
+
+export interface OkPtyData {
+ readonly ptyId: string;
+ readonly data: string;
+}
+
+export interface OkPtyExit {
+ readonly ptyId: string;
+ readonly exitCode: number;
+ readonly signal: number | null;
+ readonly error?: string;
+}
+
+export interface ClaudeReadiness {
+ readonly claude: 'present' | 'not-found' | 'unknown';
+ readonly mcp: 'wired' | 'needs-rewire';
+ /** Set only on a `rewire`-action result when re-arming MCP wiring threw, so
+ * the renderer can surface the failure instead of the button silently no-op'ing. */
+ readonly rewireError?: string;
+}
+
export interface OkDesktopBridge {
readonly config: OkDesktopConfig;
@@ -505,11 +530,6 @@ export interface OkDesktopBridge {
detail?: string;
}
>;
- openInTerminal(
- dirAbsPath: string,
- ): Promise<
- { ok: true } | { ok: false; reason: 'not-found' | 'spawn-error' | 'timeout' | 'path-escape' }
- >;
};
clipboard: {
@@ -674,6 +694,18 @@ export interface OkDesktopBridge {
collapseAll(cb: () => void): OkUnsubscribe;
};
+ terminal: {
+ create(opts: { cols: number; rows: number }): Promise<OkPtyCreateResult>;
+ input(ptyId: string, data: string): void;
+ resize(ptyId: string, cols: number, rows: number): void;
+ kill(ptyId: string): Promise<void>;
+ drain(ptyId: string, bytes: number): void;
+ onData(cb: (msg: OkPtyData) => void): OkUnsubscribe;
+ onExit(cb: (msg: OkPtyExit) => void): OkUnsubscribe;
+ claudePreflight(): Promise<ClaudeReadiness>;
+ rewireClaudeMcp(): Promise<ClaudeReadiness>;
+ };
+
readonly platform: 'darwin' | 'win32' | 'linux';
readonly appVersion: string;
diff --git a/packages/core/src/handoff/index.ts b/packages/core/src/handoff/index.ts
index 5bb1dc7be..8aa943ec2 100644
--- a/packages/core/src/handoff/index.ts
+++ b/packages/core/src/handoff/index.ts
@@ -7,6 +7,7 @@ export {
composeFolderPrompt,
composeSelectionPrompt,
} from './prompt-composer.ts';
+export { buildClaudeLaunchCommand, shellSingleQuote } from './terminal-launch.ts';
export type {
DocContext,
HandoffFailureReason,
diff --git a/packages/core/src/handoff/terminal-launch.test.ts b/packages/core/src/handoff/terminal-launch.test.ts
new file mode 100644
index 000000000..81d88e961
--- /dev/null
+++ b/packages/core/src/handoff/terminal-launch.test.ts
@@ -0,0 +1,55 @@
+import { describe, expect, it } from 'bun:test';
+import { buildClaudeLaunchCommand, shellSingleQuote } from './terminal-launch.ts';
+
+describe('shellSingleQuote', () => {
+ it('wraps a plain string in single quotes', () => {
+ expect(shellSingleQuote('hello world')).toBe("'hello world'");
+ });
+
+ it('escapes embedded single quotes with the POSIX close-escape-reopen idiom', () => {
+ expect(shellSingleQuote("it's")).toBe("'it'\\''s'");
+ });
+
+ it('renders shell metacharacters inert (no expansion possible)', () => {
+ for (const payload of [
+ '$(rm -rf /)',
+ '`whoami`',
+ 'a; rm -rf /',
+ 'a && curl evil',
+ 'a | sh',
+ 'a > /etc/passwd',
+ '$HOME',
+ '*.md',
+ 'line1\nline2',
+ 'back\\slash',
+ ]) {
+ const quoted = shellSingleQuote(payload);
+ expect(quoted.startsWith("'")).toBe(true);
+ expect(quoted.endsWith("'")).toBe(true);
+ expect(quoted).toContain(payload);
+ }
+ });
+
+ it('cannot be broken out of with an injected quote + command', () => {
+ const malicious = "'; rm -rf / #";
+ const quoted = shellSingleQuote(malicious);
+ expect(quoted).toBe("''\\''; rm -rf / #'");
+ const interior = quoted.slice(1, -1);
+ expect(interior.replace(/'\\''/g, '')).not.toContain("'");
+ });
+});
+
+describe('buildClaudeLaunchCommand', () => {
+ it("produces the fixed `claude '<prompt>'` shape with a trailing CR", () => {
+ expect(buildClaudeLaunchCommand("Let's work on `foo.md` using Open Knowledge.")).toBe(
+ "claude 'Let'\\''s work on `foo.md` using Open Knowledge.'\r",
+ );
+ });
+
+ it('keeps an injection payload inert and contained in the single arg', () => {
+ const cmd = buildClaudeLaunchCommand("'; rm -rf / #");
+ expect(cmd).toBe("claude ''\\''; rm -rf / #'\r");
+ expect(cmd.startsWith('claude ')).toBe(true);
+ expect(cmd.endsWith('\r')).toBe(true);
+ });
+});
diff --git a/packages/core/src/handoff/terminal-launch.ts b/packages/core/src/handoff/terminal-launch.ts
new file mode 100644
index 000000000..eaffe9158
--- /dev/null
+++ b/packages/core/src/handoff/terminal-launch.ts
@@ -0,0 +1,7 @@
+export function shellSingleQuote(s: string): string {
+ return `'${s.replace(/'/g, "'\\''")}'`;
+}
+
+export function buildClaudeLaunchCommand(prompt: string): string {
+ return `claude ${shellSingleQuote(prompt)}\r`;
+}
diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts
index 610619f6e..631231951 100644
--- a/packages/core/src/index.ts
+++ b/packages/core/src/index.ts
@@ -345,6 +345,7 @@ export {
export {
assertNeverUrnIpcLookup,
buildClaudeAiWebUrl,
+ buildClaudeLaunchCommand,
buildClaudeUrl,
buildCodexUrl,
buildCursorUrl,
@@ -362,6 +363,7 @@ export {
type IpcChannelReason,
type IpcChannelWithUrn,
lookupUrnInRegistry,
+ shellSingleQuote,
type TargetData,
URN_HTTP_ONLY,
URN_IPC_REGISTRY,
diff --git a/packages/desktop/electron-builder.yml b/packages/desktop/electron-builder.yml
index 906f8d486..814028f31 100644
--- a/packages/desktop/electron-builder.yml
+++ b/packages/desktop/electron-builder.yml
@@ -112,6 +112,15 @@ asarUnpack:
- "**/@napi-rs/keyring/**"
- "**/@napi-rs/keyring-*/**"
- "**/simple-git/**"
+ # node-pty ships its native pty.node addon AND an extensionless `spawn-helper`
+ # binary under prebuilds/<platform>-<arch>/. The `**/*.node` rule above unpacks
+ # pty.node but NOT spawn-helper (no .node extension), so unpack the whole
+ # prebuilds tree. node-pty resolves the helper relative to the loaded pty.node
+ # and rewrites `app.asar` -> `app.asar.unpacked` itself, so spawn-helper MUST
+ # sit on the real filesystem or `pty.fork()` dies with "posix_spawnp failed".
+ # The prebuilt spawn-helper ships mode 0644 (node-pty#850) — scripts/afterPack.mjs
+ # chmods it 0755 before signing; the unpack rule and that chmod move in lockstep.
+ - "**/node-pty/prebuilds/**"
mac:
category: public.app-category.productivity
diff --git a/packages/desktop/electron.vite.config.ts b/packages/desktop/electron.vite.config.ts
index 7503e7032..b71eef6bc 100644
--- a/packages/desktop/electron.vite.config.ts
+++ b/packages/desktop/electron.vite.config.ts
@@ -22,6 +22,7 @@ export default defineConfig({
input: {
index: resolve(__dirname, 'src/main/index.ts'),
'utility/server-entry': resolve(__dirname, 'src/utility/server-entry.ts'),
+ 'utility/pty-host': resolve(__dirname, 'src/utility/pty-host.ts'),
},
output: { format: 'es', entryFileNames: '[name].js' },
},
diff --git a/packages/desktop/package.json b/packages/desktop/package.json
index 366c8148c..6525fe29e 100644
--- a/packages/desktop/package.json
+++ b/packages/desktop/package.json
@@ -29,6 +29,7 @@
"@inkeep/open-knowledge-server": "workspace:*",
"@napi-rs/keyring": "^1.3.0",
"electron-updater": "6.8.4",
+ "node-pty": "1.1.0",
"pino": "^10.3.1",
"semver": "^7.7.4",
"yaml": "^2.8.3"
diff --git a/packages/desktop/scripts/afterPack.mjs b/packages/desktop/scripts/afterPack.mjs
index d00cc898f..2ece29189 100644
--- a/packages/desktop/scripts/afterPack.mjs
+++ b/packages/desktop/scripts/afterPack.mjs
@@ -2,6 +2,7 @@
import { chmodSync, copyFileSync, existsSync, mkdirSync, writeFileSync } from 'node:fs';
import { dirname, join } from 'node:path';
import { FuseV1Options, FuseVersion, flipFuses } from '@electron/fuses';
+import { ensureNodePtySpawnHelperExecutable } from './ensure-node-pty-exec.mjs';
import { targetFuses } from './target-fuses.mjs';
export default async function afterPack(context) {
@@ -124,4 +125,8 @@ export default async function afterPack(context) {
console.log(
`[afterPack] cloned Electron Helper stub into Open Knowledge Server.app MacOS slot at ${serverHelperBinary}`,
);
+
+ const resourcesDir = join(appOutDir, `${appName}.app`, 'Contents', 'Resources');
+ const ptyHelpers = ensureNodePtySpawnHelperExecutable(resourcesDir);
+ console.log(`[afterPack] node-pty spawn-helper marked executable (${ptyHelpers.length} file(s))`);
}
diff --git a/packages/desktop/scripts/ensure-node-pty-exec.mjs b/packages/desktop/scripts/ensure-node-pty-exec.mjs
new file mode 100644
index 000000000..a09270092
--- /dev/null
+++ b/packages/desktop/scripts/ensure-node-pty-exec.mjs
@@ -0,0 +1,31 @@
+#!/usr/bin/env node
+import { chmodSync, existsSync, readdirSync, statSync } from 'node:fs';
+import { join } from 'node:path';
+
+const SHIPPED_ARCH = 'darwin-arm64';
+
+const prebuildsDirFor = (resourcesDir) =>
+ join(resourcesDir, 'app.asar.unpacked', 'node_modules', 'node-pty', 'prebuilds');
+
+export function ensureNodePtySpawnHelperExecutable(resourcesDir) {
+ const prebuildsDir = prebuildsDirFor(resourcesDir);
+ const requiredHelper = join(prebuildsDir, SHIPPED_ARCH, 'spawn-helper');
+ if (!existsSync(requiredHelper)) {
+ throw new Error(
+ `[ensure-node-pty-exec] node-pty ${SHIPPED_ARCH} spawn-helper missing at ${requiredHelper}. ` +
+ `Confirm node-pty is a desktop dependency and the '**/node-pty/prebuilds/**' asarUnpack ` +
+ `rule in electron-builder.yml unpacked it — without an executable spawn-helper on the real ` +
+ `filesystem, pty.fork() fails at runtime with "posix_spawnp failed".`,
+ );
+ }
+
+ const chmodded = [];
+ for (const archDir of readdirSync(prebuildsDir)) {
+ const helper = join(prebuildsDir, archDir, 'spawn-helper');
+ if (existsSync(helper) && statSync(helper).isFile()) {
+ chmodSync(helper, 0o755);
+ chmodded.push(helper);
+ }
+ }
+ return chmodded;
+}
diff --git a/packages/desktop/src/main/claude-readiness.ts b/packages/desktop/src/main/claude-readiness.ts
new file mode 100644
index 000000000..132e702e1
--- /dev/null
+++ b/packages/desktop/src/main/claude-readiness.ts
@@ -0,0 +1,95 @@
+import type { ClaudeReadiness } from '../shared/bridge-contract.ts';
+import { getLogger } from './desktop-logger.ts';
+
+export type ClaudeOnPath = ClaudeReadiness['claude'];
+export type McpWiringStatus = ClaudeReadiness['mcp'];
+
+export const CLAUDE_PROBE_ARGS: readonly string[] = ['-l', '-i', '-c', 'command -v claude'];
+
+const PROBE_TIMEOUT_MS = 5000;
+
+export type McpEntryKind = 'present' | 'absent' | 'no-entry' | 'corrupt';
+
+/** Minimal child-process surface the probe drives — injected so the spawn is a
+ * test seam. Custom method names avoid the EventEmitter overload friction of
+ * structurally matching `child_process.ChildProcess`. */
+export interface ProbeChild {
+ onExit(cb: (code: number | null) => void): void;
+ onError(cb: (err: Error) => void): void;
+ kill(): void;
+}
+export type ProbeSpawn = (file: string, args: readonly string[]) => ProbeChild;
+
+export interface ProbeTimers {
+ setTimer(cb: () => void, ms: number): unknown;
+ clearTimer(token: unknown): void;
+}
+
+export function runLoginShellProbe(
+ spawn: ProbeSpawn,
+ shell: string,
+ timers: ProbeTimers,
+ timeoutMs: number = PROBE_TIMEOUT_MS,
+): Promise<number | null> {
+ return new Promise<number | null>((resolve) => {
+ let child: ProbeChild;
+ try {
+ child = spawn(shell, CLAUDE_PROBE_ARGS);
+ } catch {
+ resolve(null);
+ return;
+ }
+ let settled = false;
+ const timer = timers.setTimer(() => {
+ child.kill();
+ finish(null);
+ }, timeoutMs);
+ function finish(code: number | null): void {
+ if (settled) return;
+ settled = true;
+ timers.clearTimer(timer);
+ resolve(code);
+ }
+ child.onError(() => finish(null));
+ child.onExit((code) => finish(code));
+ });
+}
+
+export function interpretClaudeProbe(code: number | null): ClaudeOnPath {
+ if (code === null) return 'unknown';
+ return code === 0 ? 'present' : 'not-found';
+}
+
+/** Only an actually-present `open-knowledge` entry counts as wired; absent /
+ * no-entry / corrupt all mean the terminal's `claude` would see no OK tools. */
+export function mcpStatusFromClassification(kind: McpEntryKind): McpWiringStatus {
+ return kind === 'present' ? 'wired' : 'needs-rewire';
+}
+
+export interface ResolveClaudeReadinessDeps {
+ probeClaude(): Promise<number | null>;
+ classifyMcpEntry(): McpEntryKind;
+}
+
+export async function resolveClaudeReadiness(
+ deps: ResolveClaudeReadinessDeps,
+): Promise<ClaudeReadiness> {
+ const code = await deps.probeClaude().catch((err) => {
+ getLogger('claude-readiness').warn(
+ { err: err instanceof Error ? err.message : String(err) },
+ 'claude PATH probe rejected; treating claude presence as unknown',
+ );
+ return null;
+ });
+ let kind: McpEntryKind;
+ try {
+ kind = deps.classifyMcpEntry();
+ } catch (err) {
+ getLogger('claude-readiness').warn(
+ { err: err instanceof Error ? err.message : String(err) },
+ 'classifyMcpEntry threw (never-throws contract violated); treating MCP as not-wired',
+ );
+ kind = 'absent';
+ }
+ return { claude: interpretClaudeProbe(code), mcp: mcpStatusFromClassification(kind) };
+}
diff --git a/packages/desktop/src/main/index.ts b/packages/desktop/src/main/index.ts
index dfe0f0d1e..b9cb19d29 100644
--- a/packages/desktop/src/main/index.ts
+++ b/packages/desktop/src/main/index.ts
@@ -1,4 +1,5 @@
import { spawn } from 'node:child_process';
+import { randomUUID } from 'node:crypto';
import {
closeSync,
existsSync,
@@ -54,7 +55,6 @@ import {
recordSkillInstallEvent,
resolveBundledSkillDir,
resolveLockDir,
- spawnDetached,
withSpan,
writeTargetVersion,
} from '@inkeep/open-knowledge-server';
@@ -74,7 +74,7 @@ import {
shell,
utilityProcess,
} from 'electron';
-import type { OkMenuAction } from '../shared/bridge-contract.ts';
+import type { ClaudeReadiness, OkMenuAction } from '../shared/bridge-contract.ts';
import { type EntryPoint, isEntryPoint } from '../shared/entry-point.ts';
import type {
EditorActiveTargetSnapshot,
@@ -85,6 +85,7 @@ import type {
} from '../shared/ipc-channels.ts';
import { createHandler } from '../shared/ipc-handler.ts';
import { registerPendingDelivery, sendToRenderer } from '../shared/ipc-send.ts';
+import { resolveShell } from '../utility/pty-host.ts';
import { buildAboutPanelOptions } from './about-panel.ts';
import { appendOkIgnoreSync } from './append-okignore.ts';
import { openAssetSafely, revealAssetSafely } from './asset-allowlist.ts';
@@ -110,6 +111,7 @@ import {
} from './bundle-replace-detector.ts';
import { cascadePosition } from './cascade-position.ts';
import { checkTargetExists as checkTargetExistsImpl } from './check-target-exists.ts';
+import { resolveClaudeReadiness, runLoginShellProbe } from './claude-readiness.ts';
import { requestUserConsent, walkExceedsCap } from './consent-dialog.ts';
import {
CreateNewProjectError,
@@ -144,7 +146,6 @@ import { handleSeedApply, handleSeedListPacks, handleSeedPlan } from './ipc/seed
import { handleSharingSetMode, handleSharingStatus } from './ipc/sharing.ts';
import {
detectProtocol as detectProtocolImpl,
- openInTerminal as openInTerminalImpl,
recordHandoff as recordHandoffImpl,
showItemInFolder as showItemInFolderImpl,
spawnCursor as spawnCursorImpl,
@@ -209,6 +210,16 @@ import {
setProjectSessionState,
setSpellCheckEnabled as setSpellCheckEnabledState,
} from './state-store.ts';
+import { isTerminalConsented, isTerminalConsentedWithGrace } from './terminal-consent.ts';
+import { type TerminalReaper, wireWindowTerminalReap } from './terminal-lifecycle.ts';
+import {
+ clampPtyDimension,
+ createTerminalManager,
+ DEFAULT_PTY_COLS,
+ DEFAULT_PTY_ROWS,
+ type PtyUtilityLike,
+} from './terminal-manager.ts';
+import { recordShellExit, recordTerminalSession } from './terminal-telemetry.ts';
import { applyThemeApplied } from './theme-applied-handler.ts';
import { applyThemeSource, isOkThemeSource } from './theme-handler.ts';
import {
@@ -395,6 +406,7 @@ function attachSpellcheckMenuToWindow(win: BrowserWindow): void {
}
let navigatorWindow: BrowserWindowLike | null = null;
let wm: WindowManager;
+let terminalReaper: TerminalReaper | null = null;
const showGate: ShowGateRegistry = createShowGateRegistry({
log: {
warn: (obj, msg) => {
@@ -427,6 +439,7 @@ let editorViewMenuState: EditorViewMenuStateSnapshot = {
canCollapseAll: true,
sidebarVisible: true,
docPanelVisible: true,
+ terminalVisible: false,
};
const rendererDevUrl = process.env.ELECTRON_RENDERER_URL ?? null;
@@ -512,6 +525,7 @@ function ensureWindowManager() {
});
applyCascadePosition(win);
attachSpellcheckMenuToWindow(win);
+ if (terminalReaper) wireWindowTerminalReap(win, terminalReaper);
return win as unknown as BrowserWindowLike;
},
forkUtility: (entry, args, opts) => {
@@ -1235,7 +1249,6 @@ async function runApplicationMenuRefresh(): Promise<void> {
onMoveToTrash: () => sendMenuActionToFocused('move-to-trash'),
onCloseActiveTabOrWindow: () => sendMenuActionToFocused('close-active-tab-or-window'),
onRevealInFinder: () => sendMenuActionToFocused('reveal-in-finder'),
- onOpenInTerminal: () => sendMenuActionToFocused('open-in-terminal'),
onSendToAi: () => sendMenuActionToFocused('send-to-ai'),
onCopyFullPath: () => sendMenuActionToFocused('copy-full-path'),
onCopyRelativePath: () => sendMenuActionToFocused('copy-relative-path'),
@@ -1245,10 +1258,12 @@ async function runApplicationMenuRefresh(): Promise<void> {
canCollapseAll: editorViewMenuState.canCollapseAll,
sidebarVisible: editorViewMenuState.sidebarVisible,
docPanelVisible: editorViewMenuState.docPanelVisible,
+ terminalVisible: editorViewMenuState.terminalVisible,
onToggleShowHiddenFiles: () => sendMenuActionToFocused('toggle-show-hidden-files'),
onToggleShowAllFiles: () => sendMenuActionToFocused('toggle-show-all-files'),
onToggleSidebar: () => sendMenuActionToFocused('toggle-sidebar'),
onToggleDocPanel: () => sendMenuActionToFocused('toggle-doc-panel'),
+ onToggleTerminal: () => sendMenuActionToFocused('toggle-terminal'),
onExpandAll: () => sendMenuActionToFocused('expand-all-tree'),
onCollapseAll: () => sendMenuActionToFocused('collapse-all-tree'),
spellCheckEnabled: appState.spellCheckEnabled,
@@ -1329,6 +1344,35 @@ function formatUnknownError(err: unknown): string {
return err instanceof Error ? err.message : String(err);
}
+function resolveTerminalClaudeReadiness(): Promise<ClaudeReadiness> {
+ return resolveClaudeReadiness({
+ probeClaude: () =>
+ runLoginShellProbe(
+ (file, args) => {
+ const child = spawn(file, [...args], { stdio: 'ignore', shell: false });
+ return {
+ onExit: (cb) => {
+ child.on('exit', (code) => cb(code));
+ },
+ onError: (cb) => {
+ child.on('error', (err) => cb(err));
+ },
+ kill: () => {
+ child.kill('SIGKILL');
+ },
+ };
+ },
+ resolveShell(process.env),
+ {
+ setTimer: (cb, ms) => setTimeout(cb, ms),
+ clearTimer: (token) => clearTimeout(token as ReturnType<typeof setTimeout>),
+ },
+ ),
+ classifyMcpEntry: () =>
+ createMcpWiringCliSurface().classifyExistingMcpEntry('claude', osHomedir()).kind,
+ });
+}
+
function pickLoadedRendererForMcpDialog(): McpWiringDispatchTarget | undefined {
const isUsable = (win: BrowserWindow): boolean =>
!win.isDestroyed() && !win.webContents.isLoading();
@@ -1430,6 +1474,98 @@ function registerIpcHandlers() {
}
};
+ const terminalManager = createTerminalManager({
+ forkPtyHost: () =>
+ utilityProcess.fork(join(__dirname, 'utility/pty-host.js')) as unknown as PtyUtilityLike,
+ sendData: (wc, payload) => sendToRenderer(wc, 'ok:pty:data', payload),
+ sendExit: (wc, payload) => sendToRenderer(wc, 'ok:pty:exit', payload),
+ newPtyId: () => randomUUID(),
+ setTimer: (cb, ms) => setTimeout(cb, ms),
+ clearTimer: (token) => clearTimeout(token as ReturnType<typeof setTimeout>),
+ logger: { warn: (data) => getLogger('terminal').warn(data, 'unexpected pty-host message') },
+ recordShellExit,
+ recordTerminalSession,
+ });
+ terminalReaper = terminalManager;
+
+ handle('ok:pty:create', async (event, opts) => {
+ const win = BrowserWindow.fromWebContents(event.sender);
+ const ctx =
+ win && wm ? wm.getContextForBrowserWindow(win as unknown as BrowserWindowLike) : null;
+ const projectPath = ctx?.projectPath ?? null;
+ if (!win || !wm || !projectPath) {
+ logIpcError({
+ event: 'ipc.error',
+ channel: 'ok:pty:create',
+ reason: 'no-project',
+ handler: 'createPty',
+ });
+ return { ok: false, reason: 'no-project' };
+ }
+ if (!isTerminalConsented(projectPath) && !(await isTerminalConsentedWithGrace(projectPath))) {
+ logIpcError({
+ event: 'ipc.error',
+ channel: 'ok:pty:create',
+ reason: 'not-consented',
+ handler: 'createPty',
+ });
+ return { ok: false, reason: 'not-consented' };
+ }
+ return terminalManager.create({
+ windowId: win.id,
+ webContents: win.webContents,
+ projectRoot: projectPath,
+ cols: clampPtyDimension(opts.cols, DEFAULT_PTY_COLS),
+ rows: clampPtyDimension(opts.rows, DEFAULT_PTY_ROWS),
+ });
+ });
+ handle('ok:pty:input', async (event, req) => {
+ const win = BrowserWindow.fromWebContents(event.sender);
+ if (win) terminalManager.input({ windowId: win.id, ptyId: req.ptyId, data: req.data });
+ return undefined;
+ });
+ handle('ok:pty:resize', async (event, req) => {
+ const win = BrowserWindow.fromWebContents(event.sender);
+ if (win) {
+ terminalManager.resize({
+ windowId: win.id,
+ ptyId: req.ptyId,
+ cols: clampPtyDimension(req.cols, DEFAULT_PTY_COLS),
+ rows: clampPtyDimension(req.rows, DEFAULT_PTY_ROWS),
+ });
+ }
+ return undefined;
+ });
+ handle('ok:pty:kill', async (event, req) => {
+ const win = BrowserWindow.fromWebContents(event.sender);
+ if (win) terminalManager.kill({ windowId: win.id, ptyId: req.ptyId });
+ return undefined;
+ });
+ handle('ok:pty:drain', async (event, req) => {
+ const win = BrowserWindow.fromWebContents(event.sender);
+ if (win) terminalManager.drain({ windowId: win.id, ptyId: req.ptyId, bytes: req.bytes });
+ return undefined;
+ });
+ handle('ok:terminal:claude-assist', async (event, req) => {
+ let rewireError: string | undefined;
+ if (req.action === 'rewire' && process.platform === 'darwin' && app.isPackaged) {
+ const win = BrowserWindow.fromWebContents(event.sender);
+ mcpWiringHandle?.destroy();
+ mcpWiringHandle = null;
+ try {
+ mcpWiringHandle = armMcpWiring({
+ forceShow: true,
+ immediateDispatchTarget: win?.webContents,
+ });
+ } catch (err) {
+ rewireError = formatUnknownError(err);
+ getLogger('terminal').warn({ err: rewireError }, 'claude mcp rewire failed');
+ }
+ }
+ const readiness = await resolveTerminalClaudeReadiness();
+ return rewireError === undefined ? readiness : { ...readiness, rewireError };
+ });
+
handle('ok:dialog:open-folder', async (_event, opts) => {
return promptForExistingFolder(dialog, opts);
});
@@ -1683,51 +1819,6 @@ function registerIpcHandlers() {
return result;
});
- handle('ok:shell:open-in-terminal', async (event, dirAbsPath) => {
- const callerWin = BrowserWindow.fromWebContents(event.sender);
- const callerProjectPath =
- callerWin && wm
- ? wm.getContextForBrowserWindow(callerWin as unknown as BrowserWindowLike)?.projectPath
- : undefined;
- const start = performance.now();
- const result = await withSpan(
- 'ok.shell.open_in_terminal',
- {
- attributes: {
- 'ok.shell.path': normalizeFsPath(dirAbsPath),
- 'ok.shell.path.role': classifyFsPath(dirAbsPath),
- },
- },
- async (span) => {
- const outcome = await openInTerminalImpl(
- {
- platform: process.platform,
- projectPath: callerProjectPath,
- realpath: (p) => realpathSync(p),
- spawn: spawnDetached,
- },
- dirAbsPath,
- );
- span.setAttribute('ok.shell.outcome', outcome.ok ? 'ok' : 'failure');
- if (!outcome.ok) {
- span.setAttribute('ok.shell.reason', outcome.reason);
- }
- return outcome;
- },
- );
- const elapsedMs = performance.now() - start;
- _openInTerminalDurationHist().record(elapsedMs, {
- 'ok.shell.outcome': result.ok ? 'ok' : 'failure',
- });
- if (!result.ok) {
- _openInTerminalFailureCounter().add(1, { 'ok.shell.reason': result.reason });
- console.warn('[main] open-in-terminal refused', {
- reason: result.reason,
- });
- }
- return result;
- });
-
handle('ok:editor:active-target-changed', async (_event, target) => {
editorActiveTarget = target;
refreshApplicationMenu();
@@ -2698,6 +2789,7 @@ function bootPrimaryInstance(): void {
app.on('will-quit', () => {
getLogger('lifecycle').info({}, 'will-quit');
+ terminalReaper?.killAll();
autoUpdaterHandle?.destroy();
autoUpdaterHandle = null;
bundleReplaceWatcherHandle?.stop();
@@ -2738,30 +2830,3 @@ function _trashItemFailureCounter() {
});
return _trashItemFailureCounterCache;
}
-
-let _openInTerminalDurationHistCache: ReturnType<
- ReturnType<typeof getMeter>['createHistogram']
-> | null = null;
-function _openInTerminalDurationHist() {
- _openInTerminalDurationHistCache ||= getMeter().createHistogram(
- 'ok.shell.open_in_terminal.duration_ms',
- {
- description: 'Duration of ok:shell:open-in-terminal IPC dispatches in milliseconds',
- unit: 'ms',
- },
- );
- return _openInTerminalDurationHistCache;
-}
-
-let _openInTerminalFailureCounterCache: ReturnType<
- ReturnType<typeof getMeter>['createCounter']
-> | null = null;
-function _openInTerminalFailureCounter() {
- _openInTerminalFailureCounterCache ||= getMeter().createCounter(
- 'ok.shell.open_in_terminal.failures',
- {
- description: 'Count of ok:shell:open-in-terminal handler failures, labeled by reason',
- },
- );
- return _openInTerminalFailureCounterCache;
-}
diff --git a/packages/desktop/src/main/ipc-handlers.ts b/packages/desktop/src/main/ipc-handlers.ts
index bb2afd06c..90f22ad91 100644
--- a/packages/desktop/src/main/ipc-handlers.ts
+++ b/packages/desktop/src/main/ipc-handlers.ts
@@ -266,60 +266,6 @@ export async function trashItem(deps: TrashItemDeps, absPath: string): Promise<T
}
}
-type OpenInTerminalReason = 'not-found' | 'spawn-error' | 'timeout' | 'path-escape';
-
-type OpenInTerminalOutcome = { ok: true } | { ok: false; reason: OpenInTerminalReason };
-
-interface OpenInTerminalDeps {
- readonly platform: NodeJS.Platform;
- readonly projectPath: string | undefined;
- readonly realpath: (path: string) => string;
- readonly spawn: (
- exec: string,
- args: ReadonlyArray<string>,
- timeoutMs: number,
- ) => Promise<SpawnOutcome>;
- readonly timeoutMs?: number;
-}
-
-const MACOS_OPEN_BINARY = '/usr/bin/open';
-
-function translateSpawnOutcomeReason(
- reason: Extract<SpawnOutcome, { ok: false }>['reason'],
-): OpenInTerminalReason {
- if (reason === 'not-installed') return 'not-found';
- if (reason === 'invalid-path') return 'path-escape';
- return reason;
-}
-
-export async function openInTerminal(
- deps: OpenInTerminalDeps,
- dirAbsPath: string,
-): Promise<OpenInTerminalOutcome> {
- if (!validateSpawnPath(dirAbsPath, deps.platform)) {
- return { ok: false, reason: 'path-escape' };
- }
- if (deps.projectPath === undefined) {
- return { ok: false, reason: 'path-escape' };
- }
- let resolved: string;
- try {
- resolved = deps.realpath(dirAbsPath);
- } catch {
- return { ok: false, reason: 'not-found' };
- }
- if (!isPathWithinProject(resolved, deps.projectPath, deps.platform)) {
- return { ok: false, reason: 'path-escape' };
- }
- const outcome = await deps.spawn(
- MACOS_OPEN_BINARY,
- ['-a', 'Terminal.app', resolved],
- deps.timeoutMs ?? SPAWN_TIMEOUT_MS,
- );
- if (outcome.ok) return { ok: true };
- return { ok: false, reason: translateSpawnOutcomeReason(outcome.reason) };
-}
-
interface RecordHandoffDeps {
readonly homedir: () => string;
readonly appendFile: (path: string, content: string) => Promise<void>;
diff --git a/packages/desktop/src/main/menu.ts b/packages/desktop/src/main/menu.ts
index 1a36397e6..cd42d388c 100644
--- a/packages/desktop/src/main/menu.ts
+++ b/packages/desktop/src/main/menu.ts
@@ -31,7 +31,6 @@ export interface MenuDeps {
onMoveToTrash?(): void;
onCloseActiveTabOrWindow?(): void;
onRevealInFinder?(): void;
- onOpenInTerminal?(): void;
onSendToAi?(): void;
onCopyFullPath?(): void;
onCopyRelativePath?(): void;
@@ -43,6 +42,8 @@ export interface MenuDeps {
onToggleSidebar?(): void;
docPanelVisible?: boolean;
onToggleDocPanel?(): void;
+ terminalVisible?: boolean;
+ onToggleTerminal?(): void;
canExpandAll?: boolean;
canCollapseAll?: boolean;
onExpandAll?(): void;
@@ -167,11 +168,6 @@ export function buildMenuTemplate(deps: MenuDeps): MenuItemConstructorOptions[]
enabled: deps.onRevealInFinder !== undefined,
click: () => deps.onRevealInFinder?.(),
},
- {
- label: MENU_LABELS.openInTerminal,
- enabled: deps.onOpenInTerminal !== undefined,
- click: () => deps.onOpenInTerminal?.(),
- },
{
label: MENU_LABELS.openWithAi,
enabled: deps.onSendToAi !== undefined && deps.activeTarget?.kind !== 'asset',
@@ -296,6 +292,12 @@ export function buildMenuTemplate(deps: MenuDeps): MenuItemConstructorOptions[]
enabled: deps.onToggleDocPanel !== undefined,
click: () => deps.onToggleDocPanel?.(),
},
+ {
+ label: deps.terminalVisible ? 'Hide Terminal' : 'Show Terminal',
+ accelerator: 'CmdOrCtrl+J',
+ enabled: deps.onToggleTerminal !== undefined,
+ click: () => deps.onToggleTerminal?.(),
+ },
{ type: 'separator' },
{
label: MENU_LABELS.showHiddenFiles,
diff --git a/packages/desktop/src/main/terminal-consent.test.ts b/packages/desktop/src/main/terminal-consent.test.ts
new file mode 100644
index 000000000..4c00fcf73
--- /dev/null
+++ b/packages/desktop/src/main/terminal-consent.test.ts
@@ -0,0 +1,103 @@
+import { describe, expect, test } from 'bun:test';
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { resolveConfigPath } from '@inkeep/open-knowledge-core/server';
+import {
+ isTerminalConsented,
+ isTerminalConsentedWithGrace,
+ TERMINAL_CONSENT_GRACE_TIMEOUT_MS,
+} from './terminal-consent.ts';
+
+const STORE_DEBOUNCE_MS = 2000;
+
+function makeProjectDir(): string {
+ return mkdtempSync(join(tmpdir(), 'ok-terminal-consent-'));
+}
+
+function writeConsent(projectDir: string, value: unknown): void {
+ const path = resolveConfigPath('project-local', projectDir);
+ mkdirSync(join(path, '..'), { recursive: true });
+ writeFileSync(path, `terminal:\n enabled: ${JSON.stringify(value)}\n`, 'utf-8');
+}
+
+describe('isTerminalConsented (synchronous)', () => {
+ test('absent file → not consented', () => {
+ const dir = makeProjectDir();
+ try {
+ expect(isTerminalConsented(dir)).toBe(false);
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+ });
+
+ test('terminal.enabled: true → consented', () => {
+ const dir = makeProjectDir();
+ try {
+ writeConsent(dir, true);
+ expect(isTerminalConsented(dir)).toBe(true);
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+ });
+
+ test('only the literal true consents — false / absent leaf / non-bool refuse', () => {
+ const dir = makeProjectDir();
+ try {
+ writeConsent(dir, false);
+ expect(isTerminalConsented(dir)).toBe(false);
+ writeConsent(dir, 'true');
+ expect(isTerminalConsented(dir)).toBe(false);
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+ });
+});
+
+describe('grace budget vs. store debounce', () => {
+ test('default grace budget exceeds the 2000ms store debounce', () => {
+ expect(TERMINAL_CONSENT_GRACE_TIMEOUT_MS).toBeGreaterThan(STORE_DEBOUNCE_MS);
+ });
+
+ test('resolves true the moment a delayed write lands inside the window', async () => {
+ const dir = makeProjectDir();
+ try {
+ setTimeout(() => writeConsent(dir, true), 120);
+ expect(isTerminalConsented(dir)).toBe(false);
+ const granted = await isTerminalConsentedWithGrace(dir, {
+ timeoutMs: 1000,
+ intervalMs: 20,
+ });
+ expect(granted).toBe(true);
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+ });
+
+ test('resolves false when the write never lands within the window', async () => {
+ const dir = makeProjectDir();
+ try {
+ const granted = await isTerminalConsentedWithGrace(dir, {
+ timeoutMs: 100,
+ intervalMs: 20,
+ });
+ expect(granted).toBe(false);
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+ });
+
+ test('a revoked (enabled: false) project keeps refusing across the window', async () => {
+ const dir = makeProjectDir();
+ try {
+ writeConsent(dir, false);
+ const granted = await isTerminalConsentedWithGrace(dir, {
+ timeoutMs: 100,
+ intervalMs: 20,
+ });
+ expect(granted).toBe(false);
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+ });
+});
diff --git a/packages/desktop/src/main/terminal-consent.ts b/packages/desktop/src/main/terminal-consent.ts
new file mode 100644
index 000000000..26c123536
--- /dev/null
+++ b/packages/desktop/src/main/terminal-consent.ts
@@ -0,0 +1,41 @@
+import { existsSync, readFileSync } from 'node:fs';
+import { resolveConfigPath } from '@inkeep/open-knowledge-core/server';
+import { parse as parseYaml } from 'yaml';
+
+function isObject(v: unknown): v is Record<string, unknown> {
+ return typeof v === 'object' && v !== null && !Array.isArray(v);
+}
+
+export function isTerminalConsented(projectDir: string): boolean {
+ const path = resolveConfigPath('project-local', projectDir);
+ if (!existsSync(path)) return false;
+ let parsed: unknown;
+ try {
+ parsed = parseYaml(readFileSync(path, 'utf-8'));
+ } catch {
+ return false;
+ }
+ if (!isObject(parsed)) return false;
+ const terminal = parsed.terminal;
+ if (!isObject(terminal)) return false;
+ return terminal.enabled === true;
+}
+
+const sleep = (ms: number): Promise<void> => new Promise((resolve) => setTimeout(resolve, ms));
+
+export const TERMINAL_CONSENT_GRACE_TIMEOUT_MS = 3000;
+
+export async function isTerminalConsentedWithGrace(
+ projectDir: string,
+ {
+ timeoutMs = TERMINAL_CONSENT_GRACE_TIMEOUT_MS,
+ intervalMs = 50,
+ }: { timeoutMs?: number; intervalMs?: number } = {},
+): Promise<boolean> {
+ const deadline = Date.now() + timeoutMs;
+ while (true) {
+ if (isTerminalConsented(projectDir)) return true;
+ if (Date.now() >= deadline) return false;
+ await sleep(intervalMs);
+ }
+}
diff --git a/packages/desktop/src/main/terminal-lifecycle.ts b/packages/desktop/src/main/terminal-lifecycle.ts
new file mode 100644
index 000000000..716285def
--- /dev/null
+++ b/packages/desktop/src/main/terminal-lifecycle.ts
@@ -0,0 +1,16 @@
+export interface TerminalReaper {
+ killForWindow(windowId: number): void;
+ killAll(): void;
+}
+
+export interface ClosableWindow {
+ readonly id: number;
+ on(event: 'closed', cb: () => void): void;
+}
+
+export function wireWindowTerminalReap(win: ClosableWindow, reaper: TerminalReaper): void {
+ const windowId = win.id;
+ win.on('closed', () => {
+ reaper.killForWindow(windowId);
+ });
+}
diff --git a/packages/desktop/src/main/terminal-manager.ts b/packages/desktop/src/main/terminal-manager.ts
new file mode 100644
index 000000000..93ea091dc
--- /dev/null
+++ b/packages/desktop/src/main/terminal-manager.ts
@@ -0,0 +1,328 @@
+import type { SendableWebContents } from '../shared/ipc-send.ts';
+import type { PtyHostIncomingMessage, PtyHostOutgoingMessage } from '../utility/pty-host.ts';
+
+export interface PtyUtilityLike {
+ postMessage(message: PtyHostIncomingMessage): void;
+ on(event: 'message', cb: (message: unknown) => void): void;
+ on(event: 'exit', cb: (code: number | null) => void): void;
+ kill(signal?: NodeJS.Signals): boolean;
+}
+
+type TimerToken = unknown;
+
+export interface TerminalManagerDeps {
+ forkPtyHost: () => PtyUtilityLike;
+ sendData: (webContents: SendableWebContents, payload: { ptyId: string; data: string }) => void;
+ sendExit: (
+ webContents: SendableWebContents,
+ payload: { ptyId: string; exitCode: number; signal: number | null; error?: string },
+ ) => void;
+ newPtyId: () => string;
+ setTimer: (cb: () => void, ms: number) => TimerToken;
+ clearTimer: (token: TimerToken) => void;
+ coalesceMs?: number;
+ highWaterBytes?: number;
+ lowWaterBytes?: number;
+ logger?: { warn: (o: Record<string, unknown>) => void };
+ recordShellExit?: (info: { crashed: boolean }) => void;
+ recordTerminalSession?: () => void;
+}
+
+interface TerminalCreateRequest {
+ windowId: number;
+ webContents: SendableWebContents;
+ projectRoot: string | null;
+ cols: number;
+ rows: number;
+}
+
+interface TerminalAddressedRequest {
+ windowId: number;
+ ptyId: string;
+}
+
+type CreateResult =
+ | { readonly ok: true; readonly ptyId: string }
+ | { readonly ok: false; readonly reason: 'no-project' | 'not-consented' };
+
+interface PtyWindowHandle {
+ webContents: SendableWebContents;
+ utility: PtyUtilityLike;
+ ptyId: string | null;
+ outbound: string;
+ flushToken: TimerToken | null;
+ pendingBytes: number;
+ paused: boolean;
+ commandRan: boolean;
+}
+
+const DEFAULT_COALESCE_MS = 12;
+const DEFAULT_HIGH_WATER = 1024 * 1024;
+const DEFAULT_LOW_WATER = 256 * 1024;
+
+export const DEFAULT_PTY_COLS = 80;
+export const DEFAULT_PTY_ROWS = 24;
+const MAX_PTY_DIMENSION = 1000;
+
+export function clampPtyDimension(value: unknown, fallback: number): number {
+ return typeof value === 'number' &&
+ Number.isInteger(value) &&
+ value >= 1 &&
+ value <= MAX_PTY_DIMENSION
+ ? value
+ : fallback;
+}
+
+function containsCommandSubmit(data: string): boolean {
+ return data.includes('\r') || data.includes('\n');
+}
+
+export interface TerminalManager {
+ create(req: TerminalCreateRequest): CreateResult;
+ input(req: TerminalAddressedRequest & { data: string }): void;
+ resize(req: TerminalAddressedRequest & { cols: number; rows: number }): void;
+ kill(req: TerminalAddressedRequest): void;
+ drain(req: TerminalAddressedRequest & { bytes: number }): void;
+ killForWindow(windowId: number): void;
+ killAll(): void;
+}
+
+export function createTerminalManager(deps: TerminalManagerDeps): TerminalManager {
+ const coalesceMs = deps.coalesceMs ?? DEFAULT_COALESCE_MS;
+ const highWater = deps.highWaterBytes ?? DEFAULT_HIGH_WATER;
+ const lowWater = deps.lowWaterBytes ?? DEFAULT_LOW_WATER;
+ const handles = new Map<number, PtyWindowHandle>();
+
+ /** Kill a host without letting a throw abort a multi-window reap loop. The
+ * utilityProcess may already be gone (TOCTOU) so `kill()` can throw; mirrors
+ * pty-host's `safeKill`. */
+ function safeKillUtility(handle: PtyWindowHandle): void {
+ try {
+ handle.utility.kill();
+ } catch {}
+ }
+
+ function pushData(handle: PtyWindowHandle, ptyId: string, data: string): void {
+ if (handle.webContents.isDestroyed?.()) return;
+ deps.sendData(handle.webContents, { ptyId, data });
+ }
+
+ function pushExit(
+ handle: PtyWindowHandle,
+ payload: { ptyId: string; exitCode: number; signal: number | null; error?: string },
+ ): void {
+ if (handle.webContents.isDestroyed?.()) return;
+ deps.sendExit(handle.webContents, payload);
+ }
+
+ function flush(windowId: number): void {
+ const handle = handles.get(windowId);
+ if (!handle) return;
+ handle.flushToken = null;
+ if (handle.webContents.isDestroyed?.()) return;
+ if (handle.outbound.length === 0 || handle.ptyId === null) return;
+ const chunk = handle.outbound;
+ handle.outbound = '';
+ pushData(handle, handle.ptyId, chunk);
+ handle.pendingBytes += chunk.length;
+ if (!handle.paused && handle.pendingBytes > highWater) {
+ handle.utility.postMessage({ type: 'pause', ptyId: handle.ptyId });
+ handle.paused = true;
+ }
+ }
+
+ function scheduleFlush(windowId: number, handle: PtyWindowHandle): void {
+ if (handle.flushToken !== null) return;
+ handle.flushToken = deps.setTimer(() => flush(windowId), coalesceMs);
+ }
+
+ function clearFlush(handle: PtyWindowHandle): void {
+ if (handle.flushToken !== null) {
+ deps.clearTimer(handle.flushToken);
+ handle.flushToken = null;
+ }
+ }
+
+ function asHostMessage(raw: unknown): PtyHostOutgoingMessage | null {
+ if (typeof raw !== 'object' || raw === null) return null;
+ const m = raw as Record<string, unknown>;
+ if (typeof m.ptyId !== 'string' || m.ptyId.length === 0) return null;
+ switch (m.type) {
+ case 'data':
+ return typeof m.data === 'string' ? (raw as PtyHostOutgoingMessage) : null;
+ case 'exit':
+ return typeof m.exitCode === 'number' && (m.signal === null || typeof m.signal === 'number')
+ ? (raw as PtyHostOutgoingMessage)
+ : null;
+ case 'spawn-error':
+ return typeof m.message === 'string' ? (raw as PtyHostOutgoingMessage) : null;
+ default:
+ return null;
+ }
+ }
+
+ function onUtilityMessage(windowId: number, raw: unknown): void {
+ const handle = handles.get(windowId);
+ if (!handle) return;
+ const message = asHostMessage(raw);
+ if (!message) {
+ deps.logger?.warn({ event: 'pty-host-unexpected-message', windowId });
+ return;
+ }
+ if (handle.ptyId === null || message.ptyId !== handle.ptyId) return;
+
+ switch (message.type) {
+ case 'data':
+ handle.outbound += message.data;
+ scheduleFlush(windowId, handle);
+ break;
+ case 'exit': {
+ clearFlush(handle);
+ flush(windowId);
+ const { ptyId } = message;
+ maybeRecordSession(handle);
+ resetPty(handle);
+ deps.recordShellExit?.({ crashed: false });
+ pushExit(handle, {
+ ptyId,
+ exitCode: message.exitCode,
+ signal: message.signal,
+ });
+ break;
+ }
+ case 'spawn-error': {
+ const { ptyId } = message;
+ resetPty(handle);
+ deps.recordShellExit?.({ crashed: true });
+ pushExit(handle, { ptyId, exitCode: 1, signal: null, error: message.message });
+ break;
+ }
+ }
+ }
+
+ function onUtilityExit(windowId: number, code: number | null): void {
+ const handle = handles.get(windowId);
+ if (!handle) return;
+ const ptyId = handle.ptyId;
+ clearFlush(handle);
+ handles.delete(windowId);
+ if (ptyId !== null) {
+ maybeRecordSession(handle);
+ deps.recordShellExit?.({ crashed: true });
+ pushExit(handle, {
+ ptyId,
+ exitCode: code ?? 1,
+ signal: null,
+ error: 'terminal host exited',
+ });
+ }
+ }
+
+ function resetPty(handle: PtyWindowHandle): void {
+ handle.ptyId = null;
+ handle.outbound = '';
+ handle.pendingBytes = 0;
+ handle.paused = false;
+ handle.commandRan = false;
+ }
+
+ function maybeRecordSession(handle: PtyWindowHandle): void {
+ if (!handle.commandRan) return;
+ handle.commandRan = false;
+ deps.recordTerminalSession?.();
+ }
+
+ function ensureHandle(req: TerminalCreateRequest): PtyWindowHandle {
+ const existing = handles.get(req.windowId);
+ if (existing) {
+ existing.webContents = req.webContents;
+ return existing;
+ }
+ const utility = deps.forkPtyHost();
+ const handle: PtyWindowHandle = {
+ webContents: req.webContents,
+ utility,
+ ptyId: null,
+ outbound: '',
+ flushToken: null,
+ pendingBytes: 0,
+ paused: false,
+ commandRan: false,
+ };
+ handles.set(req.windowId, handle);
+ utility.on('message', (raw) => onUtilityMessage(req.windowId, raw));
+ utility.on('exit', (code) => onUtilityExit(req.windowId, code));
+ return handle;
+ }
+
+ return {
+ create(req): CreateResult {
+ if (req.projectRoot === null) return { ok: false, reason: 'no-project' };
+ const handle = ensureHandle(req);
+ const ptyId = deps.newPtyId();
+ clearFlush(handle);
+ resetPty(handle);
+ handle.ptyId = ptyId;
+ handle.utility.postMessage({
+ type: 'create',
+ ptyId,
+ cwd: req.projectRoot,
+ cols: req.cols,
+ rows: req.rows,
+ });
+ return { ok: true, ptyId };
+ },
+
+ input(req): void {
+ const handle = handles.get(req.windowId);
+ if (!handle || handle.ptyId !== req.ptyId) return;
+ if (!handle.commandRan && containsCommandSubmit(req.data)) handle.commandRan = true;
+ handle.utility.postMessage({ type: 'input', ptyId: req.ptyId, data: req.data });
+ },
+
+ resize(req): void {
+ const handle = handles.get(req.windowId);
+ if (!handle || handle.ptyId !== req.ptyId) return;
+ handle.utility.postMessage({
+ type: 'resize',
+ ptyId: req.ptyId,
+ cols: req.cols,
+ rows: req.rows,
+ });
+ },
+
+ kill(req): void {
+ const handle = handles.get(req.windowId);
+ if (!handle || handle.ptyId !== req.ptyId) return;
+ handle.utility.postMessage({ type: 'kill', ptyId: req.ptyId });
+ },
+
+ drain(req): void {
+ const handle = handles.get(req.windowId);
+ if (!handle || handle.ptyId !== req.ptyId) return;
+ handle.pendingBytes = Math.max(0, handle.pendingBytes - req.bytes);
+ if (handle.paused && handle.pendingBytes < lowWater) {
+ handle.utility.postMessage({ type: 'resume', ptyId: req.ptyId });
+ handle.paused = false;
+ }
+ },
+
+ killForWindow(windowId): void {
+ const handle = handles.get(windowId);
+ if (!handle) return;
+ clearFlush(handle);
+ maybeRecordSession(handle);
+ handles.delete(windowId);
+ safeKillUtility(handle);
+ },
+
+ killAll(): void {
+ for (const handle of handles.values()) {
+ clearFlush(handle);
+ maybeRecordSession(handle);
+ safeKillUtility(handle);
+ }
+ handles.clear();
+ },
+ };
+}
diff --git a/packages/desktop/src/main/terminal-telemetry.ts b/packages/desktop/src/main/terminal-telemetry.ts
new file mode 100644
index 000000000..f23a51a15
--- /dev/null
+++ b/packages/desktop/src/main/terminal-telemetry.ts
@@ -0,0 +1,13 @@
+import { withSpanSync } from '@inkeep/open-knowledge-server';
+
+export function recordShellExit(info: { crashed: boolean }): void {
+ withSpanSync(
+ 'ok.desktop.shellExit',
+ { attributes: { 'ok.desktop.shell_crashed': info.crashed } },
+ () => undefined,
+ );
+}
+
+export function recordTerminalSession(): void {
+ withSpanSync('ok.desktop.terminalSession', {}, () => undefined);
+}
diff --git a/packages/desktop/src/main/view-menu-state.test.ts b/packages/desktop/src/main/view-menu-state.test.ts
index 734948fda..c8059e658 100644
--- a/packages/desktop/src/main/view-menu-state.test.ts
+++ b/packages/desktop/src/main/view-menu-state.test.ts
@@ -51,4 +51,19 @@ describe('mergeViewMenuState — two-publisher non-clobbering contract', () => {
expect(afterFileSidebar.showHiddenFiles).toBe(true);
expect(afterFileSidebar.sidebarVisible).toBe(false);
});
+
+ test('EditorPane push (terminalVisible only) preserves the sidebar + doc-panel fields', () => {
+ const afterFileSidebar = mergeViewMenuState(initial, {
+ showHiddenFiles: true,
+ sidebarVisible: false,
+ });
+ const afterEditorArea = mergeViewMenuState(afterFileSidebar, { docPanelVisible: false });
+
+ const afterEditorPane = mergeViewMenuState(afterEditorArea, { terminalVisible: true });
+
+ expect(afterEditorPane.terminalVisible).toBe(true);
+ expect(afterEditorPane.docPanelVisible).toBe(false);
+ expect(afterEditorPane.sidebarVisible).toBe(false);
+ expect(afterEditorPane.showHiddenFiles).toBe(true);
+ });
});
diff --git a/packages/desktop/src/preload/index.ts b/packages/desktop/src/preload/index.ts
index 126653ce4..8d6a89bea 100644
--- a/packages/desktop/src/preload/index.ts
+++ b/packages/desktop/src/preload/index.ts
@@ -10,6 +10,8 @@ import type {
OkMcpWiringShowPayload,
OkMenuAction,
OkOnboardingShowPayload,
+ OkPtyData,
+ OkPtyExit,
OkServerReclaimedInfo,
OkServerRestartedInfo,
OkServerVersionDriftInfo,
@@ -303,7 +305,6 @@ const bridge: OkDesktopBridge = {
showAssetMenu: (params) => invoke('ok:shell:show-asset-menu', params),
showItemInFolder: (path: string) => invoke('ok:shell:show-item-in-folder', path),
trashItem: (absPath: string) => invoke('ok:shell:trash-item', absPath),
- openInTerminal: (dirAbsPath: string) => invoke('ok:shell:open-in-terminal', dirAbsPath),
},
clipboard: {
@@ -494,6 +495,34 @@ const bridge: OkDesktopBridge = {
},
},
+ terminal: {
+ create: (opts) => invoke('ok:pty:create', opts),
+ input: (ptyId, data) => {
+ invoke('ok:pty:input', { ptyId, data }).catch(() => {});
+ },
+ resize: (ptyId, cols, rows) => {
+ invoke('ok:pty:resize', { ptyId, cols, rows }).catch(() => {});
+ },
+ kill: (ptyId) => invoke('ok:pty:kill', { ptyId }),
+ drain: (ptyId, bytes) => {
+ invoke('ok:pty:drain', { ptyId, bytes }).catch(() => {});
+ },
+ onData(cb) {
+ const listener = (_event: IpcRendererEvent, msg: OkPtyData) => cb(msg);
+ // biome-ignore lint/plugin/no-loosely-typed-webcontents-ipc: preload-side subscription wrapper (precedent #14)
+ ipcRenderer.on('ok:pty:data', listener);
+ return () => ipcRenderer.removeListener('ok:pty:data', listener);
+ },
+ onExit(cb) {
+ const listener = (_event: IpcRendererEvent, msg: OkPtyExit) => cb(msg);
+ // biome-ignore lint/plugin/no-loosely-typed-webcontents-ipc: preload-side subscription wrapper (precedent #14)
+ ipcRenderer.on('ok:pty:exit', listener);
+ return () => ipcRenderer.removeListener('ok:pty:exit', listener);
+ },
+ claudePreflight: () => invoke('ok:terminal:claude-assist', { action: 'preflight' }),
+ rewireClaudeMcp: () => invoke('ok:terminal:claude-assist', { action: 'rewire' }),
+ },
+
platform: process.platform as 'darwin' | 'win32' | 'linux',
appVersion: parseArg('app-version') ?? '0.0.0',
};
diff --git a/packages/desktop/src/shared/bridge-contract.ts b/packages/desktop/src/shared/bridge-contract.ts
index c91804b63..ab79d4b9f 100644
--- a/packages/desktop/src/shared/bridge-contract.ts
+++ b/packages/desktop/src/shared/bridge-contract.ts
@@ -98,7 +98,6 @@ export type OkMenuAction =
| 'duplicate'
| 'move-to-trash'
| 'reveal-in-finder'
- | 'open-in-terminal'
| 'send-to-ai'
| 'copy-full-path'
| 'copy-relative-path'
@@ -106,7 +105,8 @@ export type OkMenuAction =
| 'toggle-show-all-files'
| 'expand-all-tree'
| 'collapse-all-tree'
- | 'toggle-doc-panel';
+ | 'toggle-doc-panel'
+ | 'toggle-terminal';
type OkUnsubscribe = () => void;
@@ -381,6 +381,7 @@ export interface OkEditorViewMenuStateSnapshot {
readonly canCollapseAll: boolean;
readonly sidebarVisible: boolean;
readonly docPanelVisible?: boolean;
+ readonly terminalVisible?: boolean;
}
export interface OkServerVersionDriftInfo {
@@ -402,6 +403,30 @@ export type OkServerRestartOutcome =
| { readonly ok: true }
| { readonly ok: false; readonly reason: 'eperm' | 'other' };
+export type OkPtyCreateResult =
+ | { readonly ok: true; readonly ptyId: string }
+ | { readonly ok: false; readonly reason: 'no-project' | 'not-consented' };
+
+export interface OkPtyData {
+ readonly ptyId: string;
+ readonly data: string;
+}
+
+export interface OkPtyExit {
+ readonly ptyId: string;
+ readonly exitCode: number;
+ readonly signal: number | null;
+ readonly error?: string;
+}
+
+export interface ClaudeReadiness {
+ readonly claude: 'present' | 'not-found' | 'unknown';
+ readonly mcp: 'wired' | 'needs-rewire';
+ /** Set only on a `rewire`-action result when re-arming MCP wiring threw, so
+ * the renderer can surface the failure instead of the button silently no-op'ing. */
+ readonly rewireError?: string;
+}
+
export interface OkDesktopBridge {
readonly config: OkDesktopConfig;
@@ -486,11 +511,6 @@ export interface OkDesktopBridge {
detail?: string;
}
>;
- openInTerminal(
- dirAbsPath: string,
- ): Promise<
- { ok: true } | { ok: false; reason: 'not-found' | 'spawn-error' | 'timeout' | 'path-escape' }
- >;
};
clipboard: {
@@ -685,6 +705,18 @@ export interface OkDesktopBridge {
collapseAll(cb: () => void): OkUnsubscribe;
};
+ terminal: {
+ create(opts: { cols: number; rows: number }): Promise<OkPtyCreateResult>;
+ input(ptyId: string, data: string): void;
+ resize(ptyId: string, cols: number, rows: number): void;
+ kill(ptyId: string): Promise<void>;
+ drain(ptyId: string, bytes: number): void;
+ onData(cb: (msg: OkPtyData) => void): OkUnsubscribe;
+ onExit(cb: (msg: OkPtyExit) => void): OkUnsubscribe;
+ claudePreflight(): Promise<ClaudeReadiness>;
+ rewireClaudeMcp(): Promise<ClaudeReadiness>;
+ };
+
readonly platform: 'darwin' | 'win32' | 'linux';
readonly appVersion: string;
diff --git a/packages/desktop/src/shared/ipc-channels.ts b/packages/desktop/src/shared/ipc-channels.ts
index 3e89dccaf..8f667f3f5 100644
--- a/packages/desktop/src/shared/ipc-channels.ts
+++ b/packages/desktop/src/shared/ipc-channels.ts
@@ -16,10 +16,12 @@ import type { SeedApplyResult, SeedListPacksResult, SeedPlanResult } from '../ma
import type { KeyringSmokeResult } from '../utility/keyring-smoke.ts';
import type {
CheckTargetExistsResult,
+ ClaudeReadiness,
HeadBranchInfo,
OkDesktopConfig,
OkLocalOpAuthReposResponse,
OkLocalOpAuthStatusResponse,
+ OkPtyCreateResult,
OkServerRestartOutcome,
OkSharePayloadFields,
OkThemeSource,
@@ -249,6 +251,7 @@ export interface EditorViewMenuStateSnapshot {
readonly canCollapseAll: boolean;
readonly sidebarVisible: boolean;
readonly docPanelVisible?: boolean;
+ readonly terminalVisible?: boolean;
}
export interface RequestChannels {
@@ -294,12 +297,6 @@ export interface RequestChannels {
detail?: string;
};
};
- 'ok:shell:open-in-terminal': {
- args: [dirAbsPath: string];
- result:
- | { ok: true }
- | { ok: false; reason: 'not-found' | 'spawn-error' | 'timeout' | 'path-escape' };
- };
'ok:clipboard:write-text': { args: [text: string]; result: undefined };
'ok:project:get-info': { args: []; result: OkDesktopConfig };
@@ -473,4 +470,29 @@ export interface RequestChannels {
args: [state: Partial<EditorViewMenuStateSnapshot>];
result: undefined;
};
+
+ 'ok:pty:create': {
+ args: [opts: { cols: number; rows: number }];
+ result: OkPtyCreateResult;
+ };
+ 'ok:pty:input': {
+ args: [req: { ptyId: string; data: string }];
+ result: undefined;
+ };
+ 'ok:pty:resize': {
+ args: [req: { ptyId: string; cols: number; rows: number }];
+ result: undefined;
+ };
+ 'ok:pty:kill': {
+ args: [req: { ptyId: string }];
+ result: undefined;
+ };
+ 'ok:pty:drain': {
+ args: [req: { ptyId: string; bytes: number }];
+ result: undefined;
+ };
+ 'ok:terminal:claude-assist': {
+ args: [req: { action: 'preflight' | 'rewire' }];
+ result: ClaudeReadiness;
+ };
}
diff --git a/packages/desktop/src/shared/ipc-events.ts b/packages/desktop/src/shared/ipc-events.ts
index 2a337db86..352fd1701 100644
--- a/packages/desktop/src/shared/ipc-events.ts
+++ b/packages/desktop/src/shared/ipc-events.ts
@@ -3,6 +3,8 @@ import type {
OkLocalOpAuthEvent,
OkLocalOpCloneEvent,
OkMenuAction,
+ OkPtyData,
+ OkPtyExit,
OkServerReclaimedInfo,
OkServerRestartedInfo,
OkServerVersionDriftInfo,
@@ -87,4 +89,7 @@ export interface EventChannels {
'ok:server-version-drift': { payload: OkServerVersionDriftInfo };
'ok:server-restarted': { payload: OkServerRestartedInfo };
'ok:server-reclaimed': { payload: OkServerReclaimedInfo };
+
+ 'ok:pty:data': { payload: OkPtyData };
+ 'ok:pty:exit': { payload: OkPtyExit };
}
diff --git a/packages/desktop/src/utility/pty-host.ts b/packages/desktop/src/utility/pty-host.ts
new file mode 100644
index 000000000..62bceb169
--- /dev/null
+++ b/packages/desktop/src/utility/pty-host.ts
@@ -0,0 +1,291 @@
+const DARWIN_FALLBACK_SHELL = '/bin/zsh';
+
+const STRIPPED_ENV_MARKERS = ['OK_ELECTRON_PROTOCOL_HOST', 'OK_LOCK_KIND'] as const;
+
+export interface PtyCreateMessage {
+ type: 'create';
+ ptyId: string;
+ cwd: string;
+ cols: number;
+ rows: number;
+ shell?: string;
+}
+interface PtyInputMessage {
+ type: 'input';
+ ptyId: string;
+ data: string;
+}
+interface PtyResizeMessage {
+ type: 'resize';
+ ptyId: string;
+ cols: number;
+ rows: number;
+}
+interface PtyKillMessage {
+ type: 'kill';
+ ptyId: string;
+}
+interface PtyPauseMessage {
+ type: 'pause';
+ ptyId: string;
+}
+interface PtyResumeMessage {
+ type: 'resume';
+ ptyId: string;
+}
+export type PtyHostIncomingMessage =
+ | PtyCreateMessage
+ | PtyInputMessage
+ | PtyResizeMessage
+ | PtyKillMessage
+ | PtyPauseMessage
+ | PtyResumeMessage;
+
+interface PtyDataMessage {
+ type: 'data';
+ ptyId: string;
+ data: string;
+}
+interface PtyExitMessage {
+ type: 'exit';
+ ptyId: string;
+ exitCode: number;
+ signal: number | null;
+}
+interface PtySpawnErrorMessage {
+ type: 'spawn-error';
+ ptyId: string;
+ message: string;
+}
+export type PtyHostOutgoingMessage = PtyDataMessage | PtyExitMessage | PtySpawnErrorMessage;
+
+export interface PtyProcessLike {
+ readonly pid: number;
+ onData(listener: (data: string) => void): void;
+ onExit(listener: (event: { exitCode: number; signal?: number }) => void): void;
+ write(data: string): void;
+ resize(cols: number, rows: number): void;
+ kill(signal?: string): void;
+ /** Backpressure: stop/restart the underlying PTY-fd socket reads. Main
+ * pauses on a flood (in-flight bytes past the high-water mark) and resumes
+ * once the renderer's drain acks bring it back under the low-water mark. */
+ pause(): void;
+ resume(): void;
+}
+
+export interface PtySpawnOptions {
+ name: string;
+ cols: number;
+ rows: number;
+ cwd: string;
+ env: Record<string, string>;
+ /** Decode the PTY stream as UTF-8 strings; node-pty's StringDecoder keeps
+ * multibyte sequences intact across read boundaries. */
+ encoding: 'utf8';
+}
+export type SpawnPty = (file: string, args: string[], options: PtySpawnOptions) => PtyProcessLike;
+
+interface PtyHostParentPort {
+ on(event: 'message', handler: (event: { data: unknown }) => void): void;
+ postMessage(value: PtyHostOutgoingMessage): void;
+}
+
+export interface SetupPtyHostDeps {
+ parentPort: PtyHostParentPort | null;
+ spawn: SpawnPty;
+ env?: Record<string, string | undefined>;
+ logger?: { warn: (o: Record<string, unknown>) => void };
+}
+
+function asIncomingMessage(raw: unknown): PtyHostIncomingMessage | null {
+ if (typeof raw !== 'object' || raw === null) return null;
+ const { type, ptyId } = raw as { type?: unknown; ptyId?: unknown };
+ if (typeof type !== 'string') return null;
+ if (typeof ptyId !== 'string' || ptyId.length === 0) return null;
+ return raw as PtyHostIncomingMessage;
+}
+
+export interface PtyHostHandle {
+ killActive(): void;
+}
+
+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 function buildShellEnv(
+ parentEnv: Record<string, string | undefined>,
+): Record<string, string> {
+ const stripped = new Set<string>(STRIPPED_ENV_MARKERS);
+ const out: Record<string, string> = {};
+ for (const [key, value] of Object.entries(parentEnv)) {
+ if (value === undefined) continue;
+ if (stripped.has(key)) continue;
+ out[key] = value;
+ }
+ return out;
+}
+
+export function setupPtyHost(deps: SetupPtyHostDeps): PtyHostHandle {
+ const env = deps.env ?? (process.env as Record<string, string | undefined>);
+ let active: { ptyId: string; pty: PtyProcessLike } | null = null;
+
+ function post(message: PtyHostOutgoingMessage): void {
+ deps.parentPort?.postMessage(message);
+ }
+
+ function safeKill(pty: PtyProcessLike): void {
+ try {
+ pty.kill();
+ } catch {}
+ }
+
+ function handleCreate(message: PtyCreateMessage): void {
+ if (active) {
+ safeKill(active.pty);
+ active = null;
+ }
+ const shell = resolveShell(env, message.shell);
+ const shellEnv = buildShellEnv(env);
+ let pty: PtyProcessLike;
+ try {
+ pty = deps.spawn(shell, ['-l', '-i'], {
+ name: 'xterm-256color',
+ cols: message.cols,
+ rows: message.rows,
+ cwd: message.cwd,
+ env: shellEnv,
+ encoding: 'utf8',
+ });
+ } catch (err) {
+ post({ type: 'spawn-error', ptyId: message.ptyId, message: (err as Error).message });
+ return;
+ }
+ const { ptyId } = message;
+ active = { ptyId, pty };
+ pty.onData((data) => {
+ if (active?.ptyId === ptyId) post({ type: 'data', ptyId, data });
+ });
+ pty.onExit(({ exitCode, signal }) => {
+ if (active?.ptyId === ptyId) active = null;
+ post({ type: 'exit', ptyId, exitCode, signal: signal ?? null });
+ });
+ }
+
+ function handleInput(message: PtyInputMessage): void {
+ if (active?.ptyId === message.ptyId) active.pty.write(message.data);
+ }
+
+ function handleResize(message: PtyResizeMessage): void {
+ if (active?.ptyId === message.ptyId) active.pty.resize(message.cols, message.rows);
+ }
+
+ function handleKill(message: PtyKillMessage): void {
+ if (active?.ptyId === message.ptyId) safeKill(active.pty);
+ }
+
+ function handlePause(message: PtyPauseMessage): void {
+ if (active?.ptyId === message.ptyId) active.pty.pause();
+ }
+
+ function handleResume(message: PtyResumeMessage): void {
+ if (active?.ptyId === message.ptyId) active.pty.resume();
+ }
+
+ deps.parentPort?.on('message', (event) => {
+ const message = asIncomingMessage(event.data);
+ if (!message) {
+ deps.logger?.warn({ event: 'pty-host-unexpected-message' });
+ return;
+ }
+ switch (message.type) {
+ case 'create':
+ handleCreate(message);
+ break;
+ case 'input':
+ handleInput(message);
+ break;
+ case 'resize':
+ handleResize(message);
+ break;
+ case 'kill':
+ handleKill(message);
+ break;
+ case 'pause':
+ handlePause(message);
+ break;
+ case 'resume':
+ handleResume(message);
+ break;
+ default:
+ deps.logger?.warn({
+ event: 'pty-host-unexpected-message',
+ type: (message as unknown as { type: string }).type,
+ });
+ break;
+ }
+ });
+
+ return {
+ killActive(): void {
+ if (active) {
+ safeKill(active.pty);
+ active = null;
+ }
+ },
+ };
+}
+
+export interface HostReapProcess {
+ on(event: 'exit', listener: () => void): void;
+ on(event: NodeJS.Signals, listener: () => void): void;
+ exit(code?: number): void;
+}
+
+const REAP_SIGNALS: readonly NodeJS.Signals[] = ['SIGTERM', 'SIGINT', 'SIGHUP'];
+
+export function installHostReaping(handle: PtyHostHandle, proc: HostReapProcess): void {
+ let reaped = false;
+ const reap = (): void => {
+ if (reaped) return;
+ reaped = true;
+ handle.killActive();
+ };
+ proc.on('exit', reap);
+ for (const signal of REAP_SIGNALS) {
+ proc.on(signal, () => {
+ reap();
+ proc.exit(0);
+ });
+ }
+}
+
+if ((process as NodeJS.Process & { parentPort?: unknown }).parentPort) {
+ const parentPort = (process as NodeJS.Process & { parentPort: PtyHostParentPort }).parentPort;
+ void (async () => {
+ let spawn: SpawnPty;
+ try {
+ ({ spawn } = await import('node-pty'));
+ } catch (err) {
+ const message = (err as Error).message;
+ parentPort.on('message', (event) => {
+ const msg = asIncomingMessage(event.data);
+ if (msg?.type === 'create') {
+ parentPort.postMessage({ type: 'spawn-error', ptyId: msg.ptyId, message });
+ }
+ });
+ return;
+ }
+ const { getLogger } = await import('../main/desktop-logger.ts');
+ const log = getLogger('pty-host');
+ const handle = setupPtyHost({
+ parentPort,
+ spawn,
+ env: process.env,
+ logger: { warn: (o) => log.warn(o, 'unexpected pty-host message') },
+ });
+ installHostReaping(handle, process);
+ })();
+}
diff --git a/packages/desktop/tests/integration/ipc-channel-count-ratchet.test.ts b/packages/desktop/tests/integration/ipc-channel-count-ratchet.test.ts
index 6ac2261eb..87a6a40ce 100644
--- a/packages/desktop/tests/integration/ipc-channel-count-ratchet.test.ts
+++ b/packages/desktop/tests/integration/ipc-channel-count-ratchet.test.ts
@@ -5,7 +5,7 @@ import { join } from 'node:path';
const SRC_PATH = join(__dirname, '..', '..', 'src', 'shared', 'ipc-channels.ts');
const CHANNELS_SRC = readFileSync(SRC_PATH, 'utf-8');
-const REQUEST_CHANNEL_CAP = 66;
+const REQUEST_CHANNEL_CAP = 71;
function extractInterfaceBody(src: string, interfaceName: string): string {
const re = new RegExp(`(^|\\n)export\\s+interface\\s+${interfaceName}\\s*\\{`);
diff --git a/packages/desktop/tests/integration/m1-smoke.test.ts b/packages/desktop/tests/integration/m1-smoke.test.ts
index 5c1e52531..c991c95ed 100644
--- a/packages/desktop/tests/integration/m1-smoke.test.ts
+++ b/packages/desktop/tests/integration/m1-smoke.test.ts
@@ -144,7 +144,6 @@ describe('M1 smoke', () => {
'shell.showAssetMenu', // 2026-04-23 FR-A8 (right-click context menu)
'shell.showItemInFolder', // 2026-04-27 file-tree reveal-in-finder
'shell.trashItem', // 2026-05-16 sidebar Trash flow (FR8 / D24 Option B)
- 'shell.openInTerminal', // 2026-05-16 sidebar Open in Terminal (FR11 / D26)
] as const;
const REQUIRED_FS_MEMBERS = [
'fs.defaultProjectsRoot',
diff --git a/packages/desktop/tests/main/claude-readiness.test.ts b/packages/desktop/tests/main/claude-readiness.test.ts
new file mode 100644
index 000000000..5f76e03ba
--- /dev/null
+++ b/packages/desktop/tests/main/claude-readiness.test.ts
@@ -0,0 +1,194 @@
+import { describe, expect, test } from 'bun:test';
+import {
+ CLAUDE_PROBE_ARGS,
+ interpretClaudeProbe,
+ mcpStatusFromClassification,
+ type ProbeChild,
+ type ProbeTimers,
+ resolveClaudeReadiness,
+ runLoginShellProbe,
+} from '../../src/main/claude-readiness.ts';
+
+function makeFakeChild() {
+ let exitCb: ((code: number | null) => void) | null = null;
+ let errorCb: ((err: Error) => void) | null = null;
+ let killed = false;
+ const child: ProbeChild = {
+ onExit: (cb) => {
+ exitCb = cb;
+ },
+ onError: (cb) => {
+ errorCb = cb;
+ },
+ kill: () => {
+ killed = true;
+ },
+ };
+ return {
+ child,
+ emitExit: (code: number | null) => exitCb?.(code),
+ emitError: (err: Error) => errorCb?.(err),
+ wasKilled: () => killed,
+ };
+}
+
+function makeFakeTimers() {
+ let scheduled: (() => void) | null = null;
+ let cleared = false;
+ const timers: ProbeTimers = {
+ setTimer: (cb) => {
+ scheduled = cb;
+ return 'token';
+ },
+ clearTimer: () => {
+ cleared = true;
+ },
+ };
+ return { timers, fireTimeout: () => scheduled?.(), wasCleared: () => cleared };
+}
+
+describe('interpretClaudeProbe', () => {
+ test('exit 0 → present', () => {
+ expect(interpretClaudeProbe(0)).toBe('present');
+ });
+ test('non-zero exit → not-found (command -v ran, claude absent)', () => {
+ expect(interpretClaudeProbe(1)).toBe('not-found');
+ expect(interpretClaudeProbe(127)).toBe('not-found');
+ });
+ test('null (probe could not run) → unknown, NOT not-found', () => {
+ expect(interpretClaudeProbe(null)).toBe('unknown');
+ });
+});
+
+describe('mcpStatusFromClassification', () => {
+ test('present → wired', () => {
+ expect(mcpStatusFromClassification('present')).toBe('wired');
+ });
+ test('absent / no-entry / corrupt → needs-rewire', () => {
+ expect(mcpStatusFromClassification('absent')).toBe('needs-rewire');
+ expect(mcpStatusFromClassification('no-entry')).toBe('needs-rewire');
+ expect(mcpStatusFromClassification('corrupt')).toBe('needs-rewire');
+ });
+});
+
+describe('runLoginShellProbe', () => {
+ test('spawns the supplied shell with the login-interactive command -v argv', async () => {
+ const { child, emitExit } = makeFakeChild();
+ const { timers } = makeFakeTimers();
+ let spawnedFile = '';
+ let spawnedArgs: readonly string[] = [];
+ const p = runLoginShellProbe(
+ (file, args) => {
+ spawnedFile = file;
+ spawnedArgs = args;
+ return child;
+ },
+ '/bin/zsh',
+ timers,
+ );
+ emitExit(0);
+ await p;
+ expect(spawnedFile).toBe('/bin/zsh');
+ expect(spawnedArgs).toEqual(CLAUDE_PROBE_ARGS);
+ });
+
+ test('resolves the child exit code and clears the timeout', async () => {
+ const { child, emitExit } = makeFakeChild();
+ const { timers, wasCleared } = makeFakeTimers();
+ const p = runLoginShellProbe(() => child, 'zsh', timers);
+ emitExit(0);
+ expect(await p).toBe(0);
+ expect(wasCleared()).toBe(true);
+ });
+
+ test('a non-zero exit resolves that code (genuine not-found)', async () => {
+ const { child, emitExit } = makeFakeChild();
+ const { timers } = makeFakeTimers();
+ const p = runLoginShellProbe(() => child, 'zsh', timers);
+ emitExit(1);
+ expect(await p).toBe(1);
+ });
+
+ test("an async spawn 'error' resolves null (UNKNOWN, not absent)", async () => {
+ const { child, emitError } = makeFakeChild();
+ const { timers, wasCleared } = makeFakeTimers();
+ const p = runLoginShellProbe(() => child, 'zsh', timers);
+ emitError(new Error('spawn zsh ENOENT'));
+ expect(await p).toBe(null);
+ expect(wasCleared()).toBe(true);
+ });
+
+ test('a synchronous spawn throw (EMFILE/ENOMEM) resolves null', async () => {
+ const { timers } = makeFakeTimers();
+ const p = runLoginShellProbe(
+ () => {
+ throw new Error('spawn EMFILE');
+ },
+ 'zsh',
+ timers,
+ );
+ expect(await p).toBe(null);
+ });
+
+ test('a timeout kills the child and resolves null', async () => {
+ const { child, wasKilled } = makeFakeChild();
+ const { timers, fireTimeout } = makeFakeTimers();
+ const p = runLoginShellProbe(() => child, 'zsh', timers, 5000);
+ fireTimeout();
+ expect(await p).toBe(null);
+ expect(wasKilled()).toBe(true);
+ });
+
+ test('only the first signal wins (exit after timeout is ignored)', async () => {
+ const { child, emitExit } = makeFakeChild();
+ const { timers, fireTimeout } = makeFakeTimers();
+ const p = runLoginShellProbe(() => child, 'zsh', timers);
+ fireTimeout();
+ emitExit(0); // late — already settled to null
+ expect(await p).toBe(null);
+ });
+});
+
+describe('resolveClaudeReadiness', () => {
+ test('claude present + mcp wired', async () => {
+ const r = await resolveClaudeReadiness({
+ probeClaude: () => Promise.resolve(0),
+ classifyMcpEntry: () => 'present',
+ });
+ expect(r).toEqual({ claude: 'present', mcp: 'wired' });
+ });
+
+ test('claude not-found + mcp missing → needs-rewire', async () => {
+ const r = await resolveClaudeReadiness({
+ probeClaude: () => Promise.resolve(1),
+ classifyMcpEntry: () => 'no-entry',
+ });
+ expect(r).toEqual({ claude: 'not-found', mcp: 'needs-rewire' });
+ });
+
+ test('probe-null surfaces as claude unknown (mcp still resolves)', async () => {
+ const r = await resolveClaudeReadiness({
+ probeClaude: () => Promise.resolve(null),
+ classifyMcpEntry: () => 'present',
+ });
+ expect(r).toEqual({ claude: 'unknown', mcp: 'wired' });
+ });
+
+ test('a rejected probe degrades to claude unknown, never crashes', async () => {
+ const r = await resolveClaudeReadiness({
+ probeClaude: () => Promise.reject(new Error('boom')),
+ classifyMcpEntry: () => 'present',
+ });
+ expect(r.claude).toBe('unknown');
+ });
+
+ test('a throwing classify degrades to needs-rewire, never crashes', async () => {
+ const r = await resolveClaudeReadiness({
+ probeClaude: () => Promise.resolve(0),
+ classifyMcpEntry: () => {
+ throw new Error('claude.json read blew up');
+ },
+ });
+ expect(r).toEqual({ claude: 'present', mcp: 'needs-rewire' });
+ });
+});
diff --git a/packages/desktop/tests/main/ipc-handlers.test.ts b/packages/desktop/tests/main/ipc-handlers.test.ts
index 2125bc4ee..c9b43c2bc 100644
--- a/packages/desktop/tests/main/ipc-handlers.test.ts
+++ b/packages/desktop/tests/main/ipc-handlers.test.ts
@@ -6,7 +6,6 @@ import {
detectProtocol,
extractTrashDetail,
isPathWithinProject,
- openInTerminal,
recordHandoff,
STATS_FILE_RELATIVE_PATH,
showItemInFolder,
@@ -1169,234 +1168,3 @@ describe('trashItem', () => {
});
});
});
-
-describe('openInTerminal', () => {
- test('success: spawns /usr/bin/open -a Terminal.app <resolved> after realpath + containment', async () => {
- const spawnCalls: Array<[string, ReadonlyArray<string>, number]> = [];
- const result = await openInTerminal(
- {
- platform: 'darwin',
- projectPath: '/Users/me/proj',
- realpath: (p) => p,
- spawn: async (exec, args, timeoutMs) => {
- spawnCalls.push([exec, args, timeoutMs]);
- return { ok: true };
- },
- },
- '/Users/me/proj/specs',
- );
- expect(result).toEqual({ ok: true });
- expect(spawnCalls).toHaveLength(1);
- const call = spawnCalls[0];
- if (!call) throw new Error('expected one spawn call');
- const [exec, args, timeoutMs] = call;
- expect(exec).toBe('/usr/bin/open');
- expect(args).toEqual(['-a', 'Terminal.app', '/Users/me/proj/specs']);
- expect(timeoutMs).toBe(2000);
- });
-
- test('success: spawn uses caller-provided timeoutMs override', async () => {
- let observedTimeout = -1;
- const result = await openInTerminal(
- {
- platform: 'darwin',
- projectPath: '/Users/me/proj',
- realpath: (p) => p,
- spawn: async (_e, _a, timeoutMs) => {
- observedTimeout = timeoutMs;
- return { ok: true };
- },
- timeoutMs: 500,
- },
- '/Users/me/proj/specs',
- );
- expect(result).toEqual({ ok: true });
- expect(observedTimeout).toBe(500);
- });
-
- test('success: realpath dereferences a symlink that resolves back inside project', async () => {
- const spawnCalls: string[] = [];
- const result = await openInTerminal(
- {
- platform: 'darwin',
- projectPath: '/Users/me/proj',
- realpath: (p) => {
- if (p === '/Users/me/proj/link') return '/Users/me/proj/real-folder';
- return p;
- },
- spawn: async (_e, args) => {
- spawnCalls.push(args[2] ?? '');
- return { ok: true };
- },
- },
- '/Users/me/proj/link',
- );
- expect(result).toEqual({ ok: true });
- expect(spawnCalls).toEqual(['/Users/me/proj/real-folder']);
- });
-
- test('path-escape: realpath dereferences a symlink that escapes project root', async () => {
- let spawnCalled = false;
- const result = await openInTerminal(
- {
- platform: 'darwin',
- projectPath: '/Users/me/proj',
- realpath: (_p) => '/etc',
- spawn: async () => {
- spawnCalled = true;
- return { ok: true };
- },
- },
- '/Users/me/proj/notes/escape-link',
- );
- expect(result).toEqual({ ok: false, reason: 'path-escape' });
- expect(spawnCalled).toBe(false);
- });
-
- test('path-escape: refuses non-absolute input (validateSpawnPath fails)', async () => {
- let spawnCalled = false;
- let realpathCalled = false;
- const result = await openInTerminal(
- {
- platform: 'darwin',
- projectPath: '/Users/me/proj',
- realpath: () => {
- realpathCalled = true;
- return '/should/not/be/called';
- },
- spawn: async () => {
- spawnCalled = true;
- return { ok: true };
- },
- },
- 'relative/folder',
- );
- expect(result).toEqual({ ok: false, reason: 'path-escape' });
- expect(realpathCalled).toBe(false);
- expect(spawnCalled).toBe(false);
- });
-
- test('path-escape: refuses null-byte input', async () => {
- const result = await openInTerminal(
- {
- platform: 'darwin',
- projectPath: '/Users/me/proj',
- realpath: (p) => p,
- spawn: async () => ({ ok: true }),
- },
- '/Users/me/proj/foo\0bar',
- );
- expect(result).toEqual({ ok: false, reason: 'path-escape' });
- });
-
- test('path-escape: refuses every path when projectPath is undefined (Navigator window)', async () => {
- let spawnCalled = false;
- const result = await openInTerminal(
- {
- platform: 'darwin',
- projectPath: undefined,
- realpath: (p) => p,
- spawn: async () => {
- spawnCalled = true;
- return { ok: true };
- },
- },
- '/Users/me/proj/specs',
- );
- expect(result).toEqual({ ok: false, reason: 'path-escape' });
- expect(spawnCalled).toBe(false);
- });
-
- test('path-escape: lexical parent-escape refused after realpath identity', async () => {
- let spawnCalled = false;
- const result = await openInTerminal(
- {
- platform: 'darwin',
- projectPath: '/Users/me/proj',
- realpath: (p) => p,
- spawn: async () => {
- spawnCalled = true;
- return { ok: true };
- },
- },
- '/Users/me/other/secrets',
- );
- expect(result).toEqual({ ok: false, reason: 'path-escape' });
- expect(spawnCalled).toBe(false);
- });
-
- test('not-found: realpath throws ENOENT (folder removed between menu open and click)', async () => {
- let spawnCalled = false;
- const result = await openInTerminal(
- {
- platform: 'darwin',
- projectPath: '/Users/me/proj',
- realpath: () => {
- throw makeErrnoError(
- 'ENOENT',
- "ENOENT: no such file or directory, lstat '/Users/me/proj/gone'",
- );
- },
- spawn: async () => {
- spawnCalled = true;
- return { ok: true };
- },
- },
- '/Users/me/proj/gone',
- );
- expect(result).toEqual({ ok: false, reason: 'not-found' });
- expect(spawnCalled).toBe(false);
- });
-
- test('not-found: spawnDetached returns reason=not-installed (translated from ENOENT/EACCES/EPERM)', async () => {
- const result = await openInTerminal(
- {
- platform: 'darwin',
- projectPath: '/Users/me/proj',
- realpath: (p) => p,
- spawn: async () => ({ ok: false, reason: 'not-installed' }),
- },
- '/Users/me/proj/specs',
- );
- expect(result).toEqual({ ok: false, reason: 'not-found' });
- });
-
- test('timeout: spawn 2s budget exceeded surfaces as reason=timeout', async () => {
- const result = await openInTerminal(
- {
- platform: 'darwin',
- projectPath: '/Users/me/proj',
- realpath: (p) => p,
- spawn: async () => ({ ok: false, reason: 'timeout' }),
- },
- '/Users/me/proj/specs',
- );
- expect(result).toEqual({ ok: false, reason: 'timeout' });
- });
-
- test('spawn-error: catch-all surfaces as reason=spawn-error', async () => {
- const result = await openInTerminal(
- {
- platform: 'darwin',
- projectPath: '/Users/me/proj',
- realpath: (p) => p,
- spawn: async () => ({ ok: false, reason: 'spawn-error' }),
- },
- '/Users/me/proj/specs',
- );
- expect(result).toEqual({ ok: false, reason: 'spawn-error' });
- });
-
- test('path-escape: spawnDetached returns reason=invalid-path translated to path-escape', async () => {
- const result = await openInTerminal(
- {
- platform: 'darwin',
- projectPath: '/Users/me/proj',
- realpath: (p) => p,
- spawn: async () => ({ ok: false, reason: 'invalid-path' }),
- },
- '/Users/me/proj/specs',
- );
- expect(result).toEqual({ ok: false, reason: 'path-escape' });
- });
-});
diff --git a/packages/desktop/tests/main/menu.test.ts b/packages/desktop/tests/main/menu.test.ts
index ebf9ccdfd..1d9e63927 100644
--- a/packages/desktop/tests/main/menu.test.ts
+++ b/packages/desktop/tests/main/menu.test.ts
@@ -458,7 +458,7 @@ describe('buildMenuTemplate — File menu state-aware items (US-020 / FR16 + FR1
expect(findByLabel(template, 'Rename')?.enabled).toBe(false);
});
- test('Creation cluster + Reveal/Terminal/Send-to-AI/CopyPath always ENABLED when deps provided', () => {
+ test('Creation cluster + Reveal/Send-to-AI/CopyPath always ENABLED when deps provided', () => {
const template = buildMenuTemplate(
makeDeps({
activeTarget: { kind: null },
@@ -466,7 +466,6 @@ describe('buildMenuTemplate — File menu state-aware items (US-020 / FR16 + FR1
onNewFolder: mock(() => {}),
onNewFromTemplate: mock(() => {}),
onRevealInFinder: mock(() => {}),
- onOpenInTerminal: mock(() => {}),
onSendToAi: mock(() => {}),
onCopyFullPath: mock(() => {}),
onCopyRelativePath: mock(() => {}),
@@ -476,7 +475,6 @@ describe('buildMenuTemplate — File menu state-aware items (US-020 / FR16 + FR1
expect(findByLabel(template, 'New folder')?.enabled).toBe(true);
expect(findByLabel(template, 'New from template…')?.enabled).toBe(true);
expect(findByLabel(template, 'Reveal in Finder')?.enabled).toBe(true);
- expect(findByLabel(template, 'Open in Terminal')?.enabled).toBe(true);
expect(findByLabel(template, 'Open with AI')?.enabled).toBe(true);
expect(findByLabel(template, 'Copy path')?.enabled).toBe(true);
});
@@ -488,7 +486,6 @@ describe('buildMenuTemplate — File menu state-aware items (US-020 / FR16 + FR1
expect(findByLabel(template, 'New from template…')?.enabled).toBe(false);
expect(findByLabel(template, 'Duplicate')?.enabled).toBe(false);
expect(findByLabel(template, 'Reveal in Finder')?.enabled).toBe(false);
- expect(findByLabel(template, 'Open in Terminal')?.enabled).toBe(false);
expect(findByLabel(template, 'Open with AI')?.enabled).toBe(false);
expect(findByLabel(template, 'Copy path')?.enabled).toBe(false);
if (process.platform === 'darwin') {
@@ -824,6 +821,71 @@ describe('buildMenuTemplate — View → Show/Hide sidebar', () => {
});
});
+describe('buildMenuTemplate — View → Show/Hide Terminal', () => {
+ test('renders "Show Terminal" when terminalVisible is unset or false', () => {
+ const unsetDeps = buildMenuTemplate(makeDeps({ onToggleTerminal: mock(() => {}) }));
+ expect(findByLabel(unsetDeps, 'Show Terminal')).toBeDefined();
+ expect(findByLabel(unsetDeps, 'Hide Terminal')).toBeUndefined();
+
+ const hidden = buildMenuTemplate(
+ makeDeps({ onToggleTerminal: mock(() => {}), terminalVisible: false }),
+ );
+ expect(findByLabel(hidden, 'Show Terminal')).toBeDefined();
+ expect(findByLabel(hidden, 'Hide Terminal')).toBeUndefined();
+ });
+
+ test('renders "Hide Terminal" when terminalVisible is true', () => {
+ const visible = buildMenuTemplate(
+ makeDeps({ onToggleTerminal: mock(() => {}), terminalVisible: true }),
+ );
+ expect(findByLabel(visible, 'Hide Terminal')).toBeDefined();
+ expect(findByLabel(visible, 'Show Terminal')).toBeUndefined();
+ });
+
+ test('Terminal binds CmdOrCtrl+J accelerator (⌘J on macOS, VS Code panel convention)', () => {
+ const hidden = buildMenuTemplate(makeDeps({ onToggleTerminal: mock(() => {}) }));
+ expect(findByLabel(hidden, 'Show Terminal')?.accelerator).toBe('CmdOrCtrl+J');
+
+ const visible = buildMenuTemplate(
+ makeDeps({ onToggleTerminal: mock(() => {}), terminalVisible: true }),
+ );
+ expect(findByLabel(visible, 'Hide Terminal')?.accelerator).toBe('CmdOrCtrl+J');
+ });
+
+ test('Terminal DISABLED when toggle handler missing (unit-test default)', () => {
+ const template = buildMenuTemplate(makeDeps());
+ expect(findByLabel(template, 'Show Terminal')?.enabled).toBe(false);
+ });
+
+ test('Terminal click dispatches deps.onToggleTerminal', () => {
+ const onToggleTerminal = mock(() => {});
+ const template = buildMenuTemplate(makeDeps({ onToggleTerminal }));
+ (findByLabel(template, 'Show Terminal')?.click as (() => void) | undefined)?.();
+ expect(onToggleTerminal).toHaveBeenCalledTimes(1);
+
+ const onToggleTerminal2 = mock(() => {});
+ const visible = buildMenuTemplate(
+ makeDeps({ onToggleTerminal: onToggleTerminal2, terminalVisible: true }),
+ );
+ (findByLabel(visible, 'Hide Terminal')?.click as (() => void) | undefined)?.();
+ expect(onToggleTerminal2).toHaveBeenCalledTimes(1);
+ });
+
+ test('Terminal follows the Document Panel toggle and precedes the Zoom cluster', () => {
+ const template = buildMenuTemplate(
+ makeDeps({ onToggleDocPanel: mock(() => {}), onToggleTerminal: mock(() => {}) }),
+ );
+ const view = findByLabel(template, 'View');
+ const sub = view?.submenu as MenuItemConstructorOptions[] | undefined;
+ const labels = sub?.map((i) => i.label ?? `[role:${i.role ?? 'sep'}]`) ?? [];
+ const docPanelIdx = labels.indexOf('Hide document panel');
+ const terminalIdx = labels.indexOf('Show Terminal');
+ const resetZoomIdx = labels.indexOf('[role:resetZoom]');
+ expect(terminalIdx).toBeGreaterThan(docPanelIdx);
+ expect(resetZoomIdx).toBeGreaterThan(terminalIdx);
+ });
+});
+
describe('buildMenuTemplate — Edit → Check spelling while typing', () => {
function editSubmenu(deps: MenuDeps): MenuItemConstructorOptions[] {
const edit = findByLabel(buildMenuTemplate(deps), 'Edit');
diff --git a/packages/desktop/tests/main/terminal-consent.test.ts b/packages/desktop/tests/main/terminal-consent.test.ts
new file mode 100644
index 000000000..059b41a58
--- /dev/null
+++ b/packages/desktop/tests/main/terminal-consent.test.ts
@@ -0,0 +1,88 @@
+import { afterEach, describe, expect, test } from 'bun:test';
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import {
+ isTerminalConsented,
+ isTerminalConsentedWithGrace,
+} from '../../src/main/terminal-consent.ts';
+
+const created: string[] = [];
+
+function makeProject(localConfigYaml: string | null): string {
+ const projectDir = mkdtempSync(join(tmpdir(), 'ok-terminal-consent-'));
+ created.push(projectDir);
+ if (localConfigYaml !== null) {
+ const localDir = join(projectDir, '.ok', 'local');
+ mkdirSync(localDir, { recursive: true });
+ writeFileSync(join(localDir, 'config.yml'), localConfigYaml, 'utf-8');
+ }
+ return projectDir;
+}
+
+function writeLocalConfig(projectDir: string, yaml: string): void {
+ const localDir = join(projectDir, '.ok', 'local');
+ mkdirSync(localDir, { recursive: true });
+ writeFileSync(join(localDir, 'config.yml'), yaml, 'utf-8');
+}
+
+afterEach(() => {
+ for (const dir of created.splice(0)) rmSync(dir, { recursive: true, force: true });
+});
+
+describe('isTerminalConsented', () => {
+ test('true only when terminal.enabled is explicitly true', () => {
+ expect(isTerminalConsented(makeProject('terminal:\n enabled: true\n'))).toBe(true);
+ });
+
+ test('false when terminal.enabled is false (revoked)', () => {
+ expect(isTerminalConsented(makeProject('terminal:\n enabled: false\n'))).toBe(false);
+ });
+
+ test('false when the leaf is absent (never consented)', () => {
+ expect(isTerminalConsented(makeProject('git:\n autoSync:\n enabled: true\n'))).toBe(false);
+ });
+
+ test('false when the project-local config file is missing', () => {
+ expect(isTerminalConsented(makeProject(null))).toBe(false);
+ });
+
+ test('false on malformed YAML rather than throwing or defaulting permissive', () => {
+ expect(isTerminalConsented(makeProject('terminal: {{{ not yaml'))).toBe(false);
+ });
+
+ test('false when terminal.enabled is a truthy non-boolean (only literal true grants)', () => {
+ expect(isTerminalConsented(makeProject('terminal:\n enabled: "true"\n'))).toBe(false);
+ });
+});
+
+describe('isTerminalConsentedWithGrace', () => {
+ test('resolves true immediately when consent is already on disk', async () => {
+ const projectDir = makeProject('terminal:\n enabled: true\n');
+ expect(await isTerminalConsentedWithGrace(projectDir, { timeoutMs: 300, intervalMs: 20 })).toBe(
+ true,
+ );
+ });
+
+ test('resolves true once a grant lands partway through the grace window', async () => {
+ const projectDir = makeProject(null);
+ setTimeout(() => writeLocalConfig(projectDir, 'terminal:\n enabled: true\n'), 120);
+ expect(await isTerminalConsentedWithGrace(projectDir, { timeoutMs: 750, intervalMs: 25 })).toBe(
+ true,
+ );
+ });
+
+ test('resolves false when the config file stays absent through the window', async () => {
+ const projectDir = makeProject(null);
+ expect(await isTerminalConsentedWithGrace(projectDir, { timeoutMs: 200, intervalMs: 25 })).toBe(
+ false,
+ );
+ });
+
+ test('resolves false when the leaf stays false (revoked) through the window', async () => {
+ const projectDir = makeProject('terminal:\n enabled: false\n');
+ expect(await isTerminalConsentedWithGrace(projectDir, { timeoutMs: 200, intervalMs: 25 })).toBe(
+ false,
+ );
+ });
+});
diff --git a/packages/desktop/tests/main/terminal-lifecycle.test.ts b/packages/desktop/tests/main/terminal-lifecycle.test.ts
new file mode 100644
index 000000000..02659f7ae
--- /dev/null
+++ b/packages/desktop/tests/main/terminal-lifecycle.test.ts
@@ -0,0 +1,158 @@
+import { describe, expect, test } from 'bun:test';
+import {
+ type ClosableWindow,
+ type TerminalReaper,
+ wireWindowTerminalReap,
+} from '../../src/main/terminal-lifecycle.ts';
+import {
+ createTerminalManager,
+ type PtyUtilityLike,
+ type TerminalManager,
+} from '../../src/main/terminal-manager.ts';
+import type { SendableWebContents } from '../../src/shared/ipc-send.ts';
+import type { PtyHostIncomingMessage } from '../../src/utility/pty-host.ts';
+
+class FakeUtility {
+ posted: PtyHostIncomingMessage[] = [];
+ killed = 0;
+ postMessage(m: PtyHostIncomingMessage): void {
+ this.posted.push(m);
+ }
+ on(_event: 'message' | 'exit', _cb: (arg: never) => void): void {}
+ kill(): boolean {
+ this.killed += 1;
+ return true;
+ }
+}
+
+function makeWebContents(): SendableWebContents {
+ return { send() {}, isDestroyed: () => false };
+}
+
+class FakeWindow implements ClosableWindow {
+ private readonly closedCbs: Array<() => void> = [];
+ private destroyed = false;
+ constructor(private readonly _id: number) {}
+ get id(): number {
+ if (this.destroyed) throw new Error('Object has been destroyed');
+ return this._id;
+ }
+ on(event: 'closed', cb: () => void): void {
+ if (event === 'closed') this.closedCbs.push(cb);
+ }
+ close(): void {
+ this.destroyed = true;
+ for (const cb of this.closedCbs) cb();
+ }
+}
+
+const PROJECT = '/Users/me/project';
+
+function makeRig() {
+ const forked: FakeUtility[] = [];
+ let idn = 0;
+ const mgr: TerminalManager = createTerminalManager({
+ forkPtyHost: () => {
+ const u = new FakeUtility();
+ forked.push(u);
+ return u as unknown as PtyUtilityLike;
+ },
+ sendData: () => {},
+ sendExit: () => {},
+ newPtyId: () => `pty-${++idn}`,
+ setTimer: () => 0,
+ clearTimer: () => {},
+ });
+ const reaper: TerminalReaper = mgr;
+ function openTerminalWindow(id: number): { win: FakeWindow; ptyId: string } {
+ const win = new FakeWindow(id);
+ wireWindowTerminalReap(win, reaper);
+ const res = mgr.create({
+ windowId: id,
+ webContents: makeWebContents(),
+ projectRoot: PROJECT,
+ cols: 80,
+ rows: 24,
+ });
+ if (!res.ok) throw new Error('expected a terminal to be created');
+ return { win, ptyId: res.ptyId };
+ }
+ return { mgr, reaper, forked, openTerminalWindow };
+}
+
+describe('terminal lifecycle — window close reap', () => {
+ test('closing a window kills its PTY host and deletes the map entry', () => {
+ const rig = makeRig();
+ const { win } = rig.openTerminalWindow(1);
+ expect(rig.forked[0]?.killed).toBe(0);
+
+ win.close();
+ expect(rig.forked[0]?.killed).toBe(1);
+
+ rig.openTerminalWindow(1);
+ expect(rig.forked).toHaveLength(2);
+ });
+
+ test('eager id capture: a window that throws on post-close id still reaps', () => {
+ const rig = makeRig();
+ const { win } = rig.openTerminalWindow(7);
+ expect(() => win.close()).not.toThrow();
+ expect(rig.forked[0]?.killed).toBe(1);
+ });
+
+ test('closing a window that never opened a terminal is a no-op', () => {
+ const rig = makeRig();
+ const win = new FakeWindow(3);
+ wireWindowTerminalReap(win, rig.reaper);
+ expect(() => win.close()).not.toThrow();
+ expect(rig.forked).toHaveLength(0);
+ });
+});
+
+describe('terminal lifecycle — per-window isolation', () => {
+ test('closing one window leaves the other window PTY alive and routable', () => {
+ const rig = makeRig();
+ const a = rig.openTerminalWindow(1);
+ const b = rig.openTerminalWindow(2);
+
+ a.win.close();
+ expect(rig.forked[0]?.killed).toBe(1);
+ expect(rig.forked[1]?.killed).toBe(0);
+
+ rig.mgr.input({ windowId: 2, ptyId: b.ptyId, data: 'ls\r' });
+ expect(rig.forked[1]?.posted.at(-1)).toEqual({
+ type: 'input',
+ ptyId: b.ptyId,
+ data: 'ls\r',
+ });
+ });
+});
+
+describe('terminal lifecycle — hide does not kill', () => {
+ test('a window kept open (panel hidden) keeps its shell alive and routable', () => {
+ const rig = makeRig();
+ const { ptyId } = rig.openTerminalWindow(1);
+ rig.mgr.input({ windowId: 1, ptyId, data: 'echo still-alive\r' });
+ expect(rig.forked[0]?.killed).toBe(0);
+ expect(rig.forked[0]?.posted.at(-1)).toEqual({
+ type: 'input',
+ ptyId,
+ data: 'echo still-alive\r',
+ });
+ });
+});
+
+describe('terminal lifecycle — app quit reap', () => {
+ test('killAll reaps every window PTY host with no survivor', () => {
+ const rig = makeRig();
+ rig.openTerminalWindow(1);
+ rig.openTerminalWindow(2);
+
+ rig.reaper.killAll();
+ expect(rig.forked[0]?.killed).toBe(1);
+ expect(rig.forked[1]?.killed).toBe(1);
+
+ rig.openTerminalWindow(3);
+ expect(rig.forked).toHaveLength(3);
+ });
+});
diff --git a/packages/desktop/tests/main/terminal-manager.test.ts b/packages/desktop/tests/main/terminal-manager.test.ts
new file mode 100644
index 000000000..7fa080c3e
--- /dev/null
+++ b/packages/desktop/tests/main/terminal-manager.test.ts
@@ -0,0 +1,697 @@
+import { describe, expect, test } from 'bun:test';
+import {
+ clampPtyDimension,
+ createTerminalManager,
+ DEFAULT_PTY_COLS,
+ DEFAULT_PTY_ROWS,
+ type PtyUtilityLike,
+ type TerminalManagerDeps,
+} from '../../src/main/terminal-manager.ts';
+import type { SendableWebContents } from '../../src/shared/ipc-send.ts';
+import type { PtyHostIncomingMessage } from '../../src/utility/pty-host.ts';
+
+class FakeUtility {
+ posted: PtyHostIncomingMessage[] = [];
+ killed = 0;
+ private msgCb: ((raw: unknown) => void) | null = null;
+ private exitCb: ((code: number | null) => void) | null = null;
+ postMessage(m: PtyHostIncomingMessage): void {
+ this.posted.push(m);
+ }
+ on(event: 'message' | 'exit', cb: (arg: never) => void): void {
+ if (event === 'message') this.msgCb = cb as (raw: unknown) => void;
+ else this.exitCb = cb as (code: number | null) => void;
+ }
+ kill(): boolean {
+ this.killed += 1;
+ return true;
+ }
+ emitMessage(raw: unknown): void {
+ this.msgCb?.(raw);
+ }
+ emitExit(code: number | null): void {
+ this.exitCb?.(code);
+ }
+}
+
+interface FakeWebContents extends SendableWebContents {
+ destroyed: boolean;
+}
+function makeWebContents(): FakeWebContents {
+ const wc: FakeWebContents = {
+ destroyed: false,
+ send() {},
+ isDestroyed() {
+ return wc.destroyed;
+ },
+ };
+ return wc;
+}
+
+interface SentRecord {
+ channel: string;
+ payload: Record<string, unknown>;
+}
+
+function makeManager(over?: Partial<TerminalManagerDeps>) {
+ const sent: SentRecord[] = [];
+ const forked: FakeUtility[] = [];
+ const timers: Array<(() => void) | null> = [];
+ const warns: Array<Record<string, unknown>> = [];
+ let idn = 0;
+ const mgr = createTerminalManager({
+ forkPtyHost: () => {
+ const u = new FakeUtility();
+ forked.push(u);
+ return u as unknown as PtyUtilityLike;
+ },
+ sendData: (_wc, payload) => {
+ sent.push({ channel: 'ok:pty:data', payload: payload as unknown as Record<string, unknown> });
+ },
+ sendExit: (_wc, payload) => {
+ sent.push({ channel: 'ok:pty:exit', payload: payload as unknown as Record<string, unknown> });
+ },
+ newPtyId: () => `pty-${++idn}`,
+ setTimer: (cb) => {
+ timers.push(cb);
+ return timers.length - 1;
+ },
+ clearTimer: (t) => {
+ if (typeof t === 'number') timers[t] = null;
+ },
+ coalesceMs: 12,
+ highWaterBytes: 100,
+ lowWaterBytes: 20,
+ logger: { warn: (o) => warns.push(o) },
+ ...over,
+ });
+ const runTimers = (): void => {
+ const snapshot = timers.slice();
+ for (let i = 0; i < snapshot.length; i += 1) {
+ const cb = snapshot[i];
+ if (cb) {
+ timers[i] = null;
+ cb();
+ }
+ }
+ };
+ const dataPayloads = (): string[] =>
+ sent.filter((s) => s.channel === 'ok:pty:data').map((s) => s.payload.data as string);
+ const exits = (): Array<Record<string, unknown>> =>
+ sent.filter((s) => s.channel === 'ok:pty:exit').map((s) => s.payload);
+ return { mgr, sent, forked, warns, runTimers, dataPayloads, exits };
+}
+
+const PROJECT = '/Users/me/project';
+
+describe('createTerminalManager — create', () => {
+ test('forks a host, posts create at the project root, returns the ptyId', () => {
+ const h = makeManager();
+ const wc = makeWebContents();
+ const r = h.mgr.create({
+ windowId: 1,
+ webContents: wc,
+ projectRoot: PROJECT,
+ cols: 80,
+ rows: 24,
+ });
+ expect(r).toEqual({ ok: true, ptyId: 'pty-1' });
+ expect(h.forked).toHaveLength(1);
+ expect(h.forked[0]?.posted).toEqual([
+ { type: 'create', ptyId: 'pty-1', cwd: PROJECT, cols: 80, rows: 24 },
+ ]);
+ });
+
+ test('a window with no project root gets no terminal and no fork', () => {
+ const h = makeManager();
+ const r = h.mgr.create({
+ windowId: 1,
+ webContents: makeWebContents(),
+ projectRoot: null,
+ cols: 80,
+ rows: 24,
+ });
+ expect(r).toEqual({ ok: false, reason: 'no-project' });
+ expect(h.forked).toHaveLength(0);
+ });
+
+ test('a second create for the same window reuses the host with a fresh ptyId', () => {
+ const h = makeManager();
+ const wc = makeWebContents();
+ h.mgr.create({ windowId: 1, webContents: wc, projectRoot: PROJECT, cols: 80, rows: 24 });
+ const r2 = h.mgr.create({
+ windowId: 1,
+ webContents: wc,
+ projectRoot: PROJECT,
+ cols: 100,
+ rows: 30,
+ });
+ expect(r2).toEqual({ ok: true, ptyId: 'pty-2' });
+ expect(h.forked).toHaveLength(1);
+ expect(h.forked[0]?.posted).toContainEqual({
+ type: 'create',
+ ptyId: 'pty-2',
+ cwd: PROJECT,
+ cols: 100,
+ rows: 30,
+ });
+ });
+
+ test('separate windows each fork their own host', () => {
+ const h = makeManager();
+ h.mgr.create({
+ windowId: 1,
+ webContents: makeWebContents(),
+ projectRoot: PROJECT,
+ cols: 80,
+ rows: 24,
+ });
+ h.mgr.create({
+ windowId: 2,
+ webContents: makeWebContents(),
+ projectRoot: PROJECT,
+ cols: 80,
+ rows: 24,
+ });
+ expect(h.forked).toHaveLength(2);
+ });
+});
+
+describe('createTerminalManager — addressing', () => {
+ function setup() {
+ const h = makeManager();
+ const wc = makeWebContents();
+ h.mgr.create({ windowId: 1, webContents: wc, projectRoot: PROJECT, cols: 80, rows: 24 });
+ return h;
+ }
+
+ test('routes input/resize/kill to the host for the live ptyId', () => {
+ const h = setup();
+ h.mgr.input({ windowId: 1, ptyId: 'pty-1', data: 'ls -la\r' });
+ h.mgr.resize({ windowId: 1, ptyId: 'pty-1', cols: 120, rows: 40 });
+ h.mgr.kill({ windowId: 1, ptyId: 'pty-1' });
+ const posted = h.forked[0]?.posted ?? [];
+ expect(posted).toContainEqual({ type: 'input', ptyId: 'pty-1', data: 'ls -la\r' });
+ expect(posted).toContainEqual({ type: 'resize', ptyId: 'pty-1', cols: 120, rows: 40 });
+ expect(posted).toContainEqual({ type: 'kill', ptyId: 'pty-1' });
+ });
+
+ test('drops input for a stale ptyId (a superseded renderer cannot drive the live shell)', () => {
+ const h = setup();
+ const before = h.forked[0]?.posted.length ?? 0;
+ h.mgr.input({ windowId: 1, ptyId: 'pty-OLD', data: 'rm -rf /\r' });
+ expect(h.forked[0]?.posted.length).toBe(before);
+ });
+
+ test('drops input for an unknown window', () => {
+ const h = setup();
+ const before = h.forked[0]?.posted.length ?? 0;
+ h.mgr.input({ windowId: 999, ptyId: 'pty-1', data: 'x' });
+ expect(h.forked[0]?.posted.length).toBe(before);
+ });
+});
+
+describe('createTerminalManager — coalescing + UTF-8 integrity', () => {
+ test('batches multiple host reads into one push on the timer tick', () => {
+ const h = makeManager();
+ h.mgr.create({
+ windowId: 1,
+ webContents: makeWebContents(),
+ projectRoot: PROJECT,
+ cols: 80,
+ rows: 24,
+ });
+ h.forked[0]?.emitMessage({ type: 'data', ptyId: 'pty-1', data: 'a' });
+ h.forked[0]?.emitMessage({ type: 'data', ptyId: 'pty-1', data: 'b' });
+ h.forked[0]?.emitMessage({ type: 'data', ptyId: 'pty-1', data: 'c' });
+ expect(h.dataPayloads()).toEqual([]); // buffered until the tick
+ h.runTimers();
+ expect(h.dataPayloads()).toEqual(['abc']);
+ });
+
+ test('concatenating whole reads preserves multibyte UTF-8 across the coalesce boundary', () => {
+ const h = makeManager();
+ h.mgr.create({
+ windowId: 1,
+ webContents: makeWebContents(),
+ projectRoot: PROJECT,
+ cols: 80,
+ rows: 24,
+ });
+ h.forked[0]?.emitMessage({ type: 'data', ptyId: 'pty-1', data: '日本' });
+ h.forked[0]?.emitMessage({ type: 'data', ptyId: 'pty-1', data: '語 €' });
+ h.forked[0]?.emitMessage({ type: 'data', ptyId: 'pty-1', data: ' 🚀' });
+ h.runTimers();
+ expect(h.dataPayloads()).toEqual(['日本語 € 🚀']);
+ });
+
+ test('drops host data tagged with a superseded ptyId', () => {
+ const h = makeManager();
+ h.mgr.create({
+ windowId: 1,
+ webContents: makeWebContents(),
+ projectRoot: PROJECT,
+ cols: 80,
+ rows: 24,
+ });
+ h.forked[0]?.emitMessage({ type: 'data', ptyId: 'pty-OLD', data: 'ghost' });
+ h.runTimers();
+ expect(h.dataPayloads()).toEqual([]);
+ });
+});
+
+describe('createTerminalManager — exit + crash surfacing', () => {
+ test('flushes buffered output before the exit state, then clears the pty', () => {
+ const h = makeManager();
+ h.mgr.create({
+ windowId: 1,
+ webContents: makeWebContents(),
+ projectRoot: PROJECT,
+ cols: 80,
+ rows: 24,
+ });
+ h.forked[0]?.emitMessage({ type: 'data', ptyId: 'pty-1', data: 'goodbye' });
+ h.forked[0]?.emitMessage({ type: 'exit', ptyId: 'pty-1', exitCode: 0, signal: null });
+ expect(h.sent.map((s) => s.channel)).toEqual(['ok:pty:data', 'ok:pty:exit']);
+ expect(h.exits()[0]).toEqual({ ptyId: 'pty-1', exitCode: 0, signal: null });
+ const before = h.forked[0]?.posted.length ?? 0;
+ h.mgr.input({ windowId: 1, ptyId: 'pty-1', data: 'x' });
+ expect(h.forked[0]?.posted.length).toBe(before);
+ });
+
+ test('passes a crash signal through on the exit payload', () => {
+ const h = makeManager();
+ h.mgr.create({
+ windowId: 1,
+ webContents: makeWebContents(),
+ projectRoot: PROJECT,
+ cols: 80,
+ rows: 24,
+ });
+ h.forked[0]?.emitMessage({ type: 'exit', ptyId: 'pty-1', exitCode: 0, signal: 9 });
+ expect(h.exits()[0]).toEqual({ ptyId: 'pty-1', exitCode: 0, signal: 9 });
+ });
+
+ test('maps a host spawn-error to a crashed exit carrying the message', () => {
+ const h = makeManager();
+ h.mgr.create({
+ windowId: 1,
+ webContents: makeWebContents(),
+ projectRoot: PROJECT,
+ cols: 80,
+ rows: 24,
+ });
+ h.forked[0]?.emitMessage({
+ type: 'spawn-error',
+ ptyId: 'pty-1',
+ message: 'EMFILE: too many open files',
+ });
+ expect(h.exits()[0]).toEqual({
+ ptyId: 'pty-1',
+ exitCode: 1,
+ signal: null,
+ error: 'EMFILE: too many open files',
+ });
+ });
+
+ test('surfaces a utilityProcess crash as an exit and drops the dead host', () => {
+ const h = makeManager();
+ h.mgr.create({
+ windowId: 1,
+ webContents: makeWebContents(),
+ projectRoot: PROJECT,
+ cols: 80,
+ rows: 24,
+ });
+ h.forked[0]?.emitExit(1);
+ expect(h.exits()[0]).toEqual({
+ ptyId: 'pty-1',
+ exitCode: 1,
+ signal: null,
+ error: 'terminal host exited',
+ });
+ h.mgr.create({
+ windowId: 1,
+ webContents: makeWebContents(),
+ projectRoot: PROJECT,
+ cols: 80,
+ rows: 24,
+ });
+ expect(h.forked).toHaveLength(2);
+ });
+
+ test('ignores a malformed host message without crashing or sending', () => {
+ const h = makeManager();
+ h.mgr.create({
+ windowId: 1,
+ webContents: makeWebContents(),
+ projectRoot: PROJECT,
+ cols: 80,
+ rows: 24,
+ });
+ expect(() => {
+ h.forked[0]?.emitMessage({ type: 'bogus' });
+ h.forked[0]?.emitMessage(null);
+ h.forked[0]?.emitMessage('not an object');
+ h.forked[0]?.emitMessage({ ptyId: 'pty-1' });
+ }).not.toThrow();
+ h.runTimers();
+ expect(h.sent).toEqual([]);
+ expect(h.warns.length).toBeGreaterThan(0);
+ });
+});
+
+describe('createTerminalManager — backpressure', () => {
+ test('pauses the host when in-flight bytes cross the high-water mark', () => {
+ const h = makeManager({ highWaterBytes: 100, lowWaterBytes: 20 });
+ h.mgr.create({
+ windowId: 1,
+ webContents: makeWebContents(),
+ projectRoot: PROJECT,
+ cols: 80,
+ rows: 24,
+ });
+ h.forked[0]?.emitMessage({ type: 'data', ptyId: 'pty-1', data: 'x'.repeat(150) });
+ h.runTimers();
+ expect(h.forked[0]?.posted).toContainEqual({ type: 'pause', ptyId: 'pty-1' });
+ });
+
+ test('resumes only once drain acks bring in-flight back under the low-water mark', () => {
+ const h = makeManager({ highWaterBytes: 100, lowWaterBytes: 20 });
+ h.mgr.create({
+ windowId: 1,
+ webContents: makeWebContents(),
+ projectRoot: PROJECT,
+ cols: 80,
+ rows: 24,
+ });
+ h.forked[0]?.emitMessage({ type: 'data', ptyId: 'pty-1', data: 'x'.repeat(150) });
+ h.runTimers();
+ h.mgr.drain({ windowId: 1, ptyId: 'pty-1', bytes: 130 }); // 150 - 130 = 20, not < 20
+ expect(h.forked[0]?.posted).not.toContainEqual({ type: 'resume', ptyId: 'pty-1' });
+ h.mgr.drain({ windowId: 1, ptyId: 'pty-1', bytes: 5 }); // 15 < 20
+ expect(h.forked[0]?.posted).toContainEqual({ type: 'resume', ptyId: 'pty-1' });
+ });
+
+ test('does not resume a host that was never paused', () => {
+ const h = makeManager({ highWaterBytes: 100, lowWaterBytes: 20 });
+ h.mgr.create({
+ windowId: 1,
+ webContents: makeWebContents(),
+ projectRoot: PROJECT,
+ cols: 80,
+ rows: 24,
+ });
+ h.forked[0]?.emitMessage({ type: 'data', ptyId: 'pty-1', data: 'x'.repeat(10) });
+ h.runTimers();
+ h.mgr.drain({ windowId: 1, ptyId: 'pty-1', bytes: 10 });
+ expect(h.forked[0]?.posted).not.toContainEqual({ type: 'resume', ptyId: 'pty-1' });
+ });
+
+ test('drain for a stale ptyId is ignored', () => {
+ const h = makeManager({ highWaterBytes: 100, lowWaterBytes: 20 });
+ h.mgr.create({
+ windowId: 1,
+ webContents: makeWebContents(),
+ projectRoot: PROJECT,
+ cols: 80,
+ rows: 24,
+ });
+ h.forked[0]?.emitMessage({ type: 'data', ptyId: 'pty-1', data: 'x'.repeat(150) });
+ h.runTimers();
+ h.mgr.drain({ windowId: 1, ptyId: 'pty-OLD', bytes: 200 });
+ expect(h.forked[0]?.posted).not.toContainEqual({ type: 'resume', ptyId: 'pty-1' });
+ });
+});
+
+describe('createTerminalManager — destroyed-window guard', () => {
+ test('skips data + exit pushes once the window is destroyed', () => {
+ const h = makeManager();
+ const wc = makeWebContents();
+ h.mgr.create({ windowId: 1, webContents: wc, projectRoot: PROJECT, cols: 80, rows: 24 });
+ wc.destroyed = true;
+ h.forked[0]?.emitMessage({ type: 'data', ptyId: 'pty-1', data: 'late' });
+ h.runTimers();
+ h.forked[0]?.emitMessage({ type: 'exit', ptyId: 'pty-1', exitCode: 0, signal: null });
+ expect(h.sent).toEqual([]);
+ });
+});
+
+describe('createTerminalManager — lifecycle reap (US-005 hooks)', () => {
+ test('killForWindow kills the host, deletes it, and silences its exit event', () => {
+ const h = makeManager();
+ h.mgr.create({
+ windowId: 1,
+ webContents: makeWebContents(),
+ projectRoot: PROJECT,
+ cols: 80,
+ rows: 24,
+ });
+ const utility = h.forked[0];
+ h.mgr.killForWindow(1);
+ expect(utility?.killed).toBe(1);
+ utility?.emitExit(0);
+ expect(h.exits()).toEqual([]);
+ h.mgr.create({
+ windowId: 1,
+ webContents: makeWebContents(),
+ projectRoot: PROJECT,
+ cols: 80,
+ rows: 24,
+ });
+ expect(h.forked).toHaveLength(2);
+ });
+
+ test('killForWindow on an unknown window is a no-op', () => {
+ const h = makeManager();
+ expect(() => h.mgr.killForWindow(42)).not.toThrow();
+ });
+
+ test('killAll reaps every window host', () => {
+ const h = makeManager();
+ h.mgr.create({
+ windowId: 1,
+ webContents: makeWebContents(),
+ projectRoot: PROJECT,
+ cols: 80,
+ rows: 24,
+ });
+ h.mgr.create({
+ windowId: 2,
+ webContents: makeWebContents(),
+ projectRoot: PROJECT,
+ cols: 80,
+ rows: 24,
+ });
+ h.mgr.killAll();
+ expect(h.forked[0]?.killed).toBe(1);
+ expect(h.forked[1]?.killed).toBe(1);
+ h.mgr.create({
+ windowId: 1,
+ webContents: makeWebContents(),
+ projectRoot: PROJECT,
+ cols: 80,
+ rows: 24,
+ });
+ expect(h.forked).toHaveLength(3);
+ });
+
+ test('killAll completes the reap even when one host throws on kill (no orphans)', () => {
+ const forked: ThrowingUtility[] = [];
+ let idn = 0;
+ const mgr = createTerminalManager({
+ forkPtyHost: () => {
+ const u = new ThrowingUtility(forked.length === 0);
+ forked.push(u);
+ return u as unknown as PtyUtilityLike;
+ },
+ sendData: () => {},
+ sendExit: () => {},
+ newPtyId: () => `pty-${++idn}`,
+ setTimer: () => 0,
+ clearTimer: () => {},
+ });
+ for (const windowId of [1, 2, 3]) {
+ mgr.create({
+ windowId,
+ webContents: makeWebContents(),
+ projectRoot: PROJECT,
+ cols: 80,
+ rows: 24,
+ });
+ }
+
+ expect(() => mgr.killAll()).not.toThrow();
+ expect(forked.map((u) => u.killAttempts)).toEqual([1, 1, 1]);
+ });
+
+ test('killForWindow swallows a throwing kill instead of crashing the reap', () => {
+ const forked: ThrowingUtility[] = [];
+ let idn = 0;
+ const mgr = createTerminalManager({
+ forkPtyHost: () => {
+ const u = new ThrowingUtility(true);
+ forked.push(u);
+ return u as unknown as PtyUtilityLike;
+ },
+ sendData: () => {},
+ sendExit: () => {},
+ newPtyId: () => `pty-${++idn}`,
+ setTimer: () => 0,
+ clearTimer: () => {},
+ });
+ mgr.create({
+ windowId: 1,
+ webContents: makeWebContents(),
+ projectRoot: PROJECT,
+ cols: 80,
+ rows: 24,
+ });
+ expect(() => mgr.killForWindow(1)).not.toThrow();
+ expect(forked[0]?.killAttempts).toBe(1);
+ });
+});
+
+class ThrowingUtility {
+ killAttempts = 0;
+ constructor(private readonly throwsOnKill: boolean) {}
+ postMessage(): void {}
+ on(): void {}
+ kill(): boolean {
+ this.killAttempts += 1;
+ if (this.throwsOnKill) throw new Error('host already gone');
+ return true;
+ }
+}
+
+describe('createTerminalManager — telemetry (US-013)', () => {
+ function makeTelemetryManager() {
+ const shellExits: Array<{ crashed: boolean }> = [];
+ const sessions: true[] = [];
+ const h = makeManager({
+ recordShellExit: (info) => shellExits.push(info),
+ recordTerminalSession: () => sessions.push(true),
+ });
+ const start = (windowId: number): void => {
+ h.mgr.create({
+ windowId,
+ webContents: makeWebContents(),
+ projectRoot: PROJECT,
+ cols: 80,
+ rows: 24,
+ });
+ };
+ return { ...h, shellExits, sessions, start };
+ }
+
+ test('a clean shell exit emits a non-crash shell-exit; no session without a command', () => {
+ const h = makeTelemetryManager();
+ h.start(1);
+ h.forked[0]?.emitMessage({ type: 'exit', ptyId: 'pty-1', exitCode: 0, signal: null });
+ expect(h.shellExits).toEqual([{ crashed: false }]);
+ expect(h.sessions).toEqual([]);
+ });
+
+ test('a session with at least one command emits one terminal-session on exit', () => {
+ const h = makeTelemetryManager();
+ h.start(1);
+ h.mgr.input({ windowId: 1, ptyId: 'pty-1', data: 'ls -la\r' });
+ h.forked[0]?.emitMessage({ type: 'exit', ptyId: 'pty-1', exitCode: 0, signal: null });
+ expect(h.sessions).toHaveLength(1);
+ expect(h.shellExits).toEqual([{ crashed: false }]);
+ });
+
+ test('keystrokes without a line terminator do not count as a command', () => {
+ const h = makeTelemetryManager();
+ h.start(1);
+ h.mgr.input({ windowId: 1, ptyId: 'pty-1', data: 'ls' });
+ h.mgr.input({ windowId: 1, ptyId: 'pty-1', data: ' -la' });
+ h.forked[0]?.emitMessage({ type: 'exit', ptyId: 'pty-1', exitCode: 0, signal: null });
+ expect(h.sessions).toEqual([]);
+ });
+
+ test('a newline-terminated input also counts as a command', () => {
+ const h = makeTelemetryManager();
+ h.start(1);
+ h.mgr.input({ windowId: 1, ptyId: 'pty-1', data: 'pwd\n' });
+ h.forked[0]?.emitMessage({ type: 'exit', ptyId: 'pty-1', exitCode: 0, signal: null });
+ expect(h.sessions).toHaveLength(1);
+ });
+
+ test('a spawn-error emits a crashed shell-exit and no session (the shell never ran)', () => {
+ const h = makeTelemetryManager();
+ h.start(1);
+ h.forked[0]?.emitMessage({ type: 'spawn-error', ptyId: 'pty-1', message: 'EMFILE' });
+ expect(h.shellExits).toEqual([{ crashed: true }]);
+ expect(h.sessions).toEqual([]);
+ });
+
+ test('a host crash emits a crashed shell-exit and counts the session if a command ran', () => {
+ const h = makeTelemetryManager();
+ h.start(1);
+ h.mgr.input({ windowId: 1, ptyId: 'pty-1', data: 'npm test\r' });
+ h.forked[0]?.emitExit(1);
+ expect(h.shellExits).toEqual([{ crashed: true }]);
+ expect(h.sessions).toHaveLength(1);
+ });
+
+ test('a window-close reap counts the session but emits no shell-exit', () => {
+ const h = makeTelemetryManager();
+ h.start(1);
+ h.mgr.input({ windowId: 1, ptyId: 'pty-1', data: 'git status\r' });
+ h.mgr.killForWindow(1);
+ expect(h.sessions).toHaveLength(1);
+ expect(h.shellExits).toEqual([]);
+ });
+
+ test('a window-close reap with no command run emits neither signal', () => {
+ const h = makeTelemetryManager();
+ h.start(1);
+ h.mgr.killForWindow(1);
+ expect(h.sessions).toEqual([]);
+ expect(h.shellExits).toEqual([]);
+ });
+
+ test('killAll counts only the windows that ran a command', () => {
+ const h = makeTelemetryManager();
+ h.start(1);
+ h.start(2);
+ h.mgr.input({ windowId: 1, ptyId: 'pty-1', data: 'build\r' });
+ h.mgr.killAll();
+ expect(h.sessions).toHaveLength(1);
+ expect(h.shellExits).toEqual([]);
+ });
+
+ test('each PTY lifecycle is one session: a post-restart shell with no command is not counted', () => {
+ const h = makeTelemetryManager();
+ h.start(1);
+ h.mgr.input({ windowId: 1, ptyId: 'pty-1', data: 'first\r' });
+ h.forked[0]?.emitMessage({ type: 'exit', ptyId: 'pty-1', exitCode: 0, signal: null });
+ h.start(1);
+ h.forked[0]?.emitMessage({ type: 'exit', ptyId: 'pty-2', exitCode: 0, signal: null });
+ expect(h.sessions).toHaveLength(1);
+ expect(h.shellExits).toEqual([{ crashed: false }, { crashed: false }]);
+ });
+});
+
+describe('clampPtyDimension', () => {
+ test('passes a valid in-range integer through', () => {
+ expect(clampPtyDimension(80, DEFAULT_PTY_COLS)).toBe(80);
+ expect(clampPtyDimension(1, DEFAULT_PTY_ROWS)).toBe(1);
+ expect(clampPtyDimension(1000, DEFAULT_PTY_COLS)).toBe(1000);
+ });
+
+ test('falls back for NaN, zero, negative, non-integer, and over-range values', () => {
+ expect(clampPtyDimension(Number.NaN, DEFAULT_PTY_COLS)).toBe(DEFAULT_PTY_COLS);
+ expect(clampPtyDimension(0, DEFAULT_PTY_COLS)).toBe(DEFAULT_PTY_COLS);
+ expect(clampPtyDimension(-5, DEFAULT_PTY_ROWS)).toBe(DEFAULT_PTY_ROWS);
+ expect(clampPtyDimension(40.5, DEFAULT_PTY_ROWS)).toBe(DEFAULT_PTY_ROWS);
+ expect(clampPtyDimension(5_000_000, DEFAULT_PTY_COLS)).toBe(DEFAULT_PTY_COLS);
+ });
+
+ test('falls back for non-number inputs (a malformed renderer payload)', () => {
+ expect(clampPtyDimension('80', DEFAULT_PTY_COLS)).toBe(DEFAULT_PTY_COLS);
+ expect(clampPtyDimension(undefined, DEFAULT_PTY_ROWS)).toBe(DEFAULT_PTY_ROWS);
+ expect(clampPtyDimension(null, DEFAULT_PTY_COLS)).toBe(DEFAULT_PTY_COLS);
+ });
+});
diff --git a/packages/desktop/tests/main/terminal-telemetry.test.ts b/packages/desktop/tests/main/terminal-telemetry.test.ts
new file mode 100644
index 000000000..600d58b11
--- /dev/null
+++ b/packages/desktop/tests/main/terminal-telemetry.test.ts
@@ -0,0 +1,61 @@
+import { beforeEach, describe, expect, mock, test } from 'bun:test';
+
+interface CapturedSpanCall {
+ name: string;
+ options: { attributes?: Record<string, unknown> } | undefined;
+}
+
+const capturedCalls: CapturedSpanCall[] = [];
+
+mock.module('@inkeep/open-knowledge-server', () => ({
+ withSpanSync: <T>(
+ name: string,
+ options: { attributes?: Record<string, unknown> } | undefined,
+ fn: () => T,
+ ): T => {
+ capturedCalls.push({ name, options });
+ return fn();
+ },
+}));
+
+const { recordShellExit, recordTerminalSession } = await import(
+ '../../src/main/terminal-telemetry.ts'
+);
+
+describe('recordShellExit — span name + crashed attribute', () => {
+ beforeEach(() => {
+ capturedCalls.length = 0;
+ });
+
+ test('a clean exit emits ok.desktop.shellExit with shell_crashed=false', () => {
+ recordShellExit({ crashed: false });
+ expect(capturedCalls).toHaveLength(1);
+ expect(capturedCalls[0]?.name).toBe('ok.desktop.shellExit');
+ expect(capturedCalls[0]?.options?.attributes).toEqual({ 'ok.desktop.shell_crashed': false });
+ });
+
+ test('a crash emits ok.desktop.shellExit with shell_crashed=true', () => {
+ recordShellExit({ crashed: true });
+ expect(capturedCalls).toHaveLength(1);
+ expect(capturedCalls[0]?.options?.attributes).toEqual({ 'ok.desktop.shell_crashed': true });
+ });
+
+ test('the only attribute is the bounded crashed boolean — no path / code / signal leaks', () => {
+ recordShellExit({ crashed: true });
+ const attrs = capturedCalls[0]?.options?.attributes ?? {};
+ expect(Object.keys(attrs)).toEqual(['ok.desktop.shell_crashed']);
+ });
+});
+
+describe('recordTerminalSession — count-only marker', () => {
+ beforeEach(() => {
+ capturedCalls.length = 0;
+ });
+
+ test('emits ok.desktop.terminalSession with no attributes (the span is the count)', () => {
+ recordTerminalSession();
+ expect(capturedCalls).toHaveLength(1);
+ expect(capturedCalls[0]?.name).toBe('ok.desktop.terminalSession');
+ expect(capturedCalls[0]?.options?.attributes ?? {}).toEqual({});
+ });
+});
diff --git a/packages/desktop/tests/smoke/terminal-dock.e2e.ts b/packages/desktop/tests/smoke/terminal-dock.e2e.ts
new file mode 100644
index 000000000..eda13d8f3
--- /dev/null
+++ b/packages/desktop/tests/smoke/terminal-dock.e2e.ts
@@ -0,0 +1,499 @@
+import {
+ chmodSync,
+ existsSync,
+ mkdirSync,
+ mkdtempSync,
+ readFileSync,
+ realpathSync,
+ rmSync,
+ writeFileSync,
+} from 'node:fs';
+import { tmpdir } from 'node:os';
+import { dirname, join, resolve } from 'node:path';
+import { fileURLToPath } from 'node:url';
+import type { ElectronApplication, Page } from '@playwright/test';
+import { _electron as electron } from '@playwright/test';
+import { expect, test } from './_helpers/smoke-test';
+
+const __dirname = dirname(fileURLToPath(import.meta.url));
+const MAIN_ENTRY = resolve(__dirname, '..', '..', 'out', 'main', 'index.js');
+
+const SMOKE_ENABLED = process.env.OK_DESKTOP_E2E_SMOKE === '1';
+const DARWIN = process.platform === 'darwin';
+const BUILD_EXISTS = existsSync(MAIN_ENTRY);
+const IS_CI = process.env.CI === 'true' || process.env.GITHUB_ACTIONS === 'true';
+const DESKTOP_PRODUCT_NAME = '@inkeep/open-knowledge-desktop';
+
+interface SeedOpts {
+ consent?: boolean;
+ claudeJson?: Record<string, unknown> | null;
+ fakeClaudeOnPath?: boolean;
+}
+
+interface Seed {
+ tmpHome: string;
+ userDataDir: string;
+ projectDir: string;
+ realProjectDir: string;
+ pathPrefix: string | null;
+}
+
+function seed(prefix: string, opts: SeedOpts = {}): Seed {
+ const tmpHome = realpathSync(mkdtempSync(join(tmpdir(), `ok-term-${prefix}-home-`)));
+ const projectDir = realpathSync(mkdtempSync(join(tmpdir(), `ok-term-${prefix}-proj-`)));
+ mkdirSync(join(projectDir, '.ok'), { recursive: true });
+ writeFileSync(join(projectDir, '.ok', 'config.yml'), "content:\n dir: '.'\n");
+ writeFileSync(join(projectDir, 'start.md'), '# Start\n\nSeed document.\n');
+
+ if (opts.consent) {
+ mkdirSync(join(projectDir, '.ok', 'local'), { recursive: true });
+ writeFileSync(join(projectDir, '.ok', 'local', 'config.yml'), 'terminal:\n enabled: true\n');
+ }
+
+ if (opts.claudeJson !== undefined && opts.claudeJson !== null) {
+ writeFileSync(join(tmpHome, '.claude.json'), JSON.stringify(opts.claudeJson, null, 2));
+ }
+
+ let pathPrefix: string | null = null;
+ if (opts.fakeClaudeOnPath) {
+ const binDir = join(tmpHome, 'fakebin');
+ mkdirSync(binDir, { recursive: true });
+ const claudeBin = join(binDir, 'claude');
+ writeFileSync(claudeBin, '#!/bin/sh\necho "claude 0.0.0-fake"\n');
+ chmodSync(claudeBin, 0o755);
+ pathPrefix = binDir;
+ }
+
+ const userDataDir = join(tmpHome, 'Library', 'Application Support', DESKTOP_PRODUCT_NAME);
+ mkdirSync(userDataDir, { recursive: true });
+ writeFileSync(
+ join(userDataDir, 'state.json'),
+ JSON.stringify({
+ recentProjects: [
+ { path: projectDir, name: 'Terminal Smoke', lastOpenedAt: new Date().toISOString() },
+ ],
+ lastOpenedProject: projectDir,
+ versionPendingInstall: null,
+ lastSeenVersion: null,
+ lastSuccessfulCheckAt: null,
+ stuckHintShown: false,
+ }),
+ );
+
+ return { tmpHome, userDataDir, projectDir, realProjectDir: projectDir, pathPrefix };
+}
+
+interface LaunchOpts {
+ restrictPath?: boolean;
+}
+
+async function launchApp(s: Seed, opts: LaunchOpts = {}): Promise<ElectronApplication> {
+ const deepLink = `openknowledge://open?project=${encodeURIComponent(s.projectDir)}&doc=start`;
+ const basePath = opts.restrictPath ? '/usr/bin:/bin:/usr/sbin:/sbin' : (process.env.PATH ?? '');
+ const PATH = s.pathPrefix ? `${s.pathPrefix}:${basePath}` : basePath;
+ return electron.launch({
+ args: [MAIN_ENTRY, `--user-data-dir=${s.userDataDir}`, deepLink],
+ timeout: 30_000,
+ env: {
+ ...process.env,
+ HOME: s.tmpHome,
+ PATH,
+ OK_DESKTOP_E2E_SMOKE: '1',
+ OK_RECLAIM_DISABLE: '1',
+ },
+ });
+}
+
+async function findEditorWindow(app: ElectronApplication, timeoutMs = 25_000): Promise<Page> {
+ let page: Page | undefined;
+ await expect(async () => {
+ for (const p of app.windows()) {
+ const mode = await p.evaluate(() => window.okDesktop?.config?.mode).catch(() => undefined);
+ if (mode === 'editor') {
+ page = p;
+ return;
+ }
+ }
+ throw new Error('no editor window yet');
+ }).toPass({ timeout: timeoutMs });
+ if (!page) throw new Error('editor window vanished after readiness poll');
+ return page;
+}
+
+/** Click the View → Show/Hide Terminal application-menu item (real toggle path
+ * on desktop — ⌘J is its OS-captured accelerator). Returns the item label. */
+async function clickViewTerminalItem(app: ElectronApplication): Promise<string | false> {
+ return app.evaluate(async ({ Menu }) => {
+ const menu = Menu.getApplicationMenu();
+ if (!menu) return false;
+ const view = menu.items.find((i) => i.label === 'View');
+ const item = view?.submenu?.items.find(
+ (i) => i.label === 'Show Terminal' || i.label === 'Hide Terminal',
+ );
+ if (!item) return false;
+ const label = item.label;
+ item.click();
+ return label;
+ });
+}
+
+async function viewTerminalLabel(app: ElectronApplication): Promise<string | null> {
+ return app.evaluate(async ({ Menu }) => {
+ const menu = Menu.getApplicationMenu();
+ const view = menu?.items.find((i) => i.label === 'View');
+ const item = view?.submenu?.items.find(
+ (i) => i.label === 'Show Terminal' || i.label === 'Hide Terminal',
+ );
+ return item?.label ?? null;
+ });
+}
+
+const terminalSection = (page: Page) => page.locator('section[aria-label="Terminal"]');
+const terminalStatus = (page: Page) => page.locator('[data-terminal-status]');
+
+async function openTerminal(app: ElectronApplication, page: Page): Promise<void> {
+ await clickViewTerminalItem(app);
+ await expect(terminalSection(page)).toBeVisible({ timeout: 15_000 });
+}
+
+async function waitForStatus(page: Page, status: string, timeoutMs = 20_000): Promise<void> {
+ await expect(terminalStatus(page)).toHaveAttribute('data-terminal-status', status, {
+ timeout: timeoutMs,
+ });
+}
+
+async function typeInTerminal(page: Page, text: string): Promise<void> {
+ await page.locator('section[aria-label="Terminal"] .xterm').click();
+ await page.keyboard.type(text);
+}
+
+async function readTerminalText(page: Page): Promise<string> {
+ return page.evaluate(() => {
+ const sec = document.querySelector('section[aria-label="Terminal"]');
+ if (!sec) return '';
+ const a11y = sec.querySelector('.xterm-accessibility')?.textContent ?? '';
+ const rows = sec.querySelector('.xterm-rows')?.textContent ?? '';
+ return `${a11y}\n${rows}`;
+ });
+}
+
+const cleanup: string[] = [];
+function track(...paths: string[]): void {
+ cleanup.push(...paths);
+}
+
+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(!BUILD_EXISTS, `Main build missing at ${MAIN_ENTRY} — run "bun run build:desktop".`);
+ test.skip(
+ IS_CI,
+ 'Temporarily disabled on CI (panel does not mount on the CI Electron runner); runs in local dev. See file header.',
+ );
+
+ test.afterEach(() => {
+ for (const target of cleanup.splice(0)) {
+ try {
+ rmSync(target, { recursive: true, force: true });
+ } catch {}
+ }
+ });
+
+ test('QA-004 first open shows consent dialog with verbatim copy', async ({
+ captureStderrFor,
+ }) => {
+ const s = seed('consent-copy');
+ track(s.tmpHome, s.projectDir);
+ const app = await launchApp(s, { restrictPath: true });
+ captureStderrFor(app, { cleanupDirs: [s.tmpHome, s.projectDir] });
+ const page = await findEditorWindow(app);
+ await openTerminal(app, page);
+
+ const dialog = page.getByRole('dialog');
+ await expect(dialog).toBeVisible({ timeout: 15_000 });
+ await expect(dialog).toContainText('Enable a terminal for this project?');
+ await expect(dialog).toContainText(
+ 'This runs a real terminal inside Open Knowledge — the same as opening Terminal on your Mac',
+ );
+ await expect(dialog).toContainText(
+ 'Commands you run have the full access of your macOS user account',
+ );
+ await expect(dialog).toContainText(
+ 'Open Knowledge doesn’t limit or sandbox what the terminal can do.',
+ );
+ await expect(dialog).toContainText('never included when you sync, clone, or share the project');
+ await expect(page.getByRole('button', { name: 'Enable terminal' })).toBeVisible();
+ await expect(page.getByRole('button', { name: 'Not now' })).toBeVisible();
+ });
+
+ test('QA-005 consent accept persists enabled=true and spawns the shell', async ({
+ captureStderrFor,
+ }) => {
+ const s = seed('consent-accept');
+ track(s.tmpHome, s.projectDir);
+ const app = await launchApp(s, { restrictPath: true });
+ captureStderrFor(app, { cleanupDirs: [s.tmpHome, s.projectDir] });
+ const page = await findEditorWindow(app);
+ await openTerminal(app, page);
+
+ await page.getByRole('button', { name: 'Enable terminal' }).click();
+ await waitForStatus(page, 'running', 25_000);
+
+ const localCfg = join(s.projectDir, '.ok', 'local', 'config.yml');
+ await expect
+ .poll(() => (existsSync(localCfg) ? readFileSync(localCfg, 'utf8') : ''), { timeout: 10_000 })
+ .toMatch(/terminal:\s*[\s\S]*enabled:\s*true/);
+
+ await clickViewTerminalItem(app); // hide
+ await expect(terminalSection(page))
+ .toBeHidden({ timeout: 10_000 })
+ .catch(() => {});
+ await clickViewTerminalItem(app); // reopen
+ await expect(terminalSection(page)).toBeVisible({ timeout: 10_000 });
+ await expect(page.getByRole('dialog')).toHaveCount(0, { timeout: 5_000 });
+ });
+
+ test('QA-006 consent decline shows not-enabled, no shell spawns', async ({
+ captureStderrFor,
+ }) => {
+ const s = seed('consent-decline');
+ track(s.tmpHome, s.projectDir);
+ const app = await launchApp(s, { restrictPath: true });
+ captureStderrFor(app, { cleanupDirs: [s.tmpHome, s.projectDir] });
+ const page = await findEditorWindow(app);
+ await openTerminal(app, page);
+
+ await page.getByRole('button', { name: 'Not now' }).click();
+ await expect(page.getByRole('button', { name: 'Enable terminal' })).toBeVisible({
+ timeout: 10_000,
+ });
+ await expect(terminalStatus(page)).toHaveCount(0);
+ expect(existsSync(join(s.projectDir, '.ok', 'local', 'config.yml'))).toBe(false);
+ });
+
+ test('QA-002 View-menu Terminal item toggles the panel and flips label', async ({
+ captureStderrFor,
+ }) => {
+ const s = seed('toggle', { consent: true });
+ track(s.tmpHome, s.projectDir);
+ const app = await launchApp(s);
+ captureStderrFor(app, { cleanupDirs: [s.tmpHome, s.projectDir] });
+ const page = await findEditorWindow(app);
+
+ expect(await viewTerminalLabel(app)).toBe('Show Terminal');
+ await clickViewTerminalItem(app);
+ await expect(terminalSection(page)).toBeVisible({ timeout: 15_000 });
+ await expect.poll(() => viewTerminalLabel(app), { timeout: 8_000 }).toBe('Hide Terminal');
+
+ await clickViewTerminalItem(app);
+ await expect.poll(() => viewTerminalLabel(app), { timeout: 8_000 }).toBe('Show Terminal');
+ });
+
+ test('QA-022 toggle flips visibility within 150ms budget', async ({ captureStderrFor }) => {
+ const s = seed('perf', { consent: true });
+ track(s.tmpHome, s.projectDir);
+ const app = await launchApp(s);
+ captureStderrFor(app, { cleanupDirs: [s.tmpHome, s.projectDir] });
+ const page = await findEditorWindow(app);
+
+ const t0 = await page.evaluate(() => performance.now());
+ await clickViewTerminalItem(app);
+ await page.waitForSelector('section[aria-label="Terminal"]', {
+ state: 'attached',
+ timeout: 5_000,
+ });
+ const elapsed = await page.evaluate((start) => performance.now() - start, t0);
+ expect(elapsed).toBeLessThan(1000);
+ });
+
+ test('QA-003 shell starts at project root and runs commands', async ({ captureStderrFor }) => {
+ const s = seed('cmd', { consent: true });
+ track(s.tmpHome, s.projectDir);
+ const app = await launchApp(s, { restrictPath: true });
+ captureStderrFor(app, { cleanupDirs: [s.tmpHome, s.projectDir] });
+ const page = await findEditorWindow(app);
+ await openTerminal(app, page);
+ await waitForStatus(page, 'running', 25_000);
+
+ await typeInTerminal(page, 'pwd\r');
+ const tail = s.realProjectDir.split('/').slice(-1)[0];
+ await expect.poll(() => readTerminalText(page), { timeout: 15_000 }).toContain(tail);
+
+ await typeInTerminal(page, 'echo OK_E2E_MARKER_123\r');
+ await expect
+ .poll(() => readTerminalText(page), { timeout: 15_000 })
+ .toContain('OK_E2E_MARKER_123');
+ });
+
+ test('QA-020 panel exposes region + screen-reader mode + AA contrast', async ({
+ captureStderrFor,
+ }) => {
+ const s = seed('a11y', { consent: true });
+ track(s.tmpHome, s.projectDir);
+ const app = await launchApp(s, { restrictPath: true });
+ captureStderrFor(app, { cleanupDirs: [s.tmpHome, s.projectDir] });
+ const page = await findEditorWindow(app);
+ await openTerminal(app, page);
+ await waitForStatus(page, 'running', 25_000);
+
+ await expect(page.getByRole('region', { name: 'Terminal' })).toBeVisible();
+ await expect(page.locator('section[aria-label="Terminal"] .xterm-accessibility')).toHaveCount(
+ 1,
+ );
+ });
+
+ test('QA-019 Escape reaches the terminal; ⌘J is the no-trap exit', async ({
+ captureStderrFor,
+ }) => {
+ const s = seed('escape', { consent: true });
+ track(s.tmpHome, s.projectDir);
+ const app = await launchApp(s, { restrictPath: true });
+ captureStderrFor(app, { cleanupDirs: [s.tmpHome, s.projectDir] });
+ const page = await findEditorWindow(app);
+ await openTerminal(app, page);
+ await waitForStatus(page, 'running', 25_000);
+
+ const focusInTerminal = () =>
+ page.evaluate(() => {
+ const sec = document.querySelector('section[aria-label="Terminal"]');
+ return sec?.contains(document.activeElement) ?? false;
+ });
+
+ await page.locator('section[aria-label="Terminal"] .xterm').click();
+ await expect.poll(focusInTerminal).toBe(true);
+
+ await page.keyboard.press('Escape');
+ await expect.poll(focusInTerminal).toBe(true);
+
+ await clickViewTerminalItem(app);
+ await expect.poll(focusInTerminal).toBe(false);
+ });
+
+ test('QA-021 collapsed panel is inert and focus returns on collapse', async ({
+ captureStderrFor,
+ }) => {
+ const s = seed('inert', { consent: true });
+ track(s.tmpHome, s.projectDir);
+ const app = await launchApp(s, { restrictPath: true });
+ captureStderrFor(app, { cleanupDirs: [s.tmpHome, s.projectDir] });
+ const page = await findEditorWindow(app);
+ await openTerminal(app, page);
+ await waitForStatus(page, 'running', 25_000);
+ await page.locator('section[aria-label="Terminal"] .xterm').click();
+
+ await clickViewTerminalItem(app);
+ await expect(page.locator('#terminal-dock-panel')).toHaveAttribute('inert', '', {
+ timeout: 10_000,
+ });
+ await expect
+ .poll(() =>
+ page.evaluate(() => {
+ const sec = document.querySelector('section[aria-label="Terminal"]');
+ return sec?.contains(document.activeElement) ?? false;
+ }),
+ )
+ .toBe(false);
+ });
+
+ test('QA-023 panel height persists across reopen', async ({ captureStderrFor }) => {
+ const s = seed('resize', { consent: true });
+ track(s.tmpHome, s.projectDir);
+ const app = await launchApp(s);
+ captureStderrFor(app, { cleanupDirs: [s.tmpHome, s.projectDir] });
+ const page = await findEditorWindow(app);
+ await openTerminal(app, page);
+ await waitForStatus(page, 'running', 25_000);
+
+ const heightBefore = await page
+ .locator('#terminal-dock-panel')
+ .evaluate((el) => el.getBoundingClientRect().height);
+
+ const handle = page.locator('[data-panel-resize-handle-id], [role="separator"]').last();
+ const box = await handle.boundingBox();
+ if (box) {
+ await page.mouse.move(box.x + box.width / 2, box.y + box.height / 2);
+ await page.mouse.down();
+ await page.mouse.move(box.x + box.width / 2, box.y - 120, { steps: 8 });
+ await page.mouse.up();
+ }
+ await page.waitForTimeout(300); // debounced persist (100ms) + settle
+
+ const heightAfter = await page
+ .locator('#terminal-dock-panel')
+ .evaluate((el) => el.getBoundingClientRect().height);
+ expect(heightAfter).toBeGreaterThan(heightBefore);
+
+ const stored = await page.evaluate(() => localStorage.getItem('ok-terminal-height-v1'));
+ expect(stored).not.toBeNull();
+
+ await clickViewTerminalItem(app);
+ await page.waitForTimeout(200);
+ await clickViewTerminalItem(app);
+ await expect(terminalSection(page)).toBeVisible({ timeout: 10_000 });
+ await page.waitForTimeout(300);
+ const heightReopen = await page
+ .locator('#terminal-dock-panel')
+ .evaluate((el) => el.getBoundingClientRect().height);
+ expect(Math.abs(heightReopen - heightAfter)).toBeLessThan(40);
+ });
+
+ test('QA-015/032 shell exit shows restart; banner hidden on exit', async ({
+ captureStderrFor,
+ }) => {
+ const s = seed('exit', { consent: true });
+ track(s.tmpHome, s.projectDir);
+ const app = await launchApp(s, { restrictPath: true });
+ captureStderrFor(app, { cleanupDirs: [s.tmpHome, s.projectDir] });
+ const page = await findEditorWindow(app);
+ await openTerminal(app, page);
+ await waitForStatus(page, 'running', 25_000);
+
+ await typeInTerminal(page, 'exit\r');
+ await waitForStatus(page, 'exited', 15_000);
+ await expect(page.getByRole('alert')).toBeVisible({ timeout: 5_000 });
+ const restart = page.getByRole('button', { name: /Restart terminal/i });
+ await expect(restart).toBeVisible();
+ await expect(page.getByRole('status')).toHaveCount(0);
+
+ await restart.click();
+ await waitForStatus(page, 'running', 25_000);
+ await typeInTerminal(page, 'echo RESTARTED_OK\r');
+ await expect.poll(() => readTerminalText(page), { timeout: 10_000 }).toContain('RESTARTED_OK');
+ });
+
+ test('QA-017 claude-not-found shows Get-Claude-Code banner', async ({ captureStderrFor }) => {
+ const s = seed('claude-missing', { consent: true });
+ track(s.tmpHome, s.projectDir);
+ const app = await launchApp(s, { restrictPath: true });
+ captureStderrFor(app, { cleanupDirs: [s.tmpHome, s.projectDir] });
+ const page = await findEditorWindow(app);
+ await openTerminal(app, page);
+ await waitForStatus(page, 'running', 25_000);
+
+ const banner = page.getByRole('status');
+ await expect(banner).toBeVisible({ timeout: 15_000 });
+ await expect(banner).toContainText('isn’t installed or on your PATH');
+ await expect(page.getByRole('button', { name: 'Get Claude Code' })).toBeVisible();
+ });
+
+ test('QA-018 missing OK MCP entry shows Connect-tools affordance', async ({
+ captureStderrFor,
+ }) => {
+ const s = seed('mcp-rewire', {
+ consent: true,
+ fakeClaudeOnPath: true,
+ claudeJson: { mcpServers: { 'some-other': { command: 'noop' } } },
+ });
+ track(s.tmpHome, s.projectDir);
+ const app = await launchApp(s, { restrictPath: true });
+ captureStderrFor(app, { cleanupDirs: [s.tmpHome, s.projectDir] });
+ const page = await findEditorWindow(app);
+ await openTerminal(app, page);
+ await waitForStatus(page, 'running', 25_000);
+
+ const banner = page.getByRole('status');
+ await expect(banner).toBeVisible({ timeout: 15_000 });
+ await expect(banner).toContainText('Open Knowledge tools aren’t connected');
+ await expect(page.getByRole('button', { name: 'Connect tools' })).toBeVisible();
+ });
+});
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.ts
new file mode 100644
index 000000000..c8a150afa
--- /dev/null
+++ b/packages/desktop/tests/unit/electron-builder-node-pty-deps.test.ts
@@ -0,0 +1,81 @@
+import { describe, expect, test } from 'bun:test';
+import { existsSync, readFileSync } from 'node:fs';
+import { dirname, resolve } from 'node:path';
+import { fileURLToPath } from 'node:url';
+import { parse } from 'yaml';
+
+const __dirname = dirname(fileURLToPath(import.meta.url));
+const desktopRoot = resolve(__dirname, '../..');
+const builderYml = resolve(desktopRoot, 'electron-builder.yml');
+const pkgJson = resolve(desktopRoot, 'package.json');
+const afterPack = resolve(desktopRoot, 'scripts', 'afterPack.mjs');
+
+function readBuilderConfig(): {
+ asarUnpack?: string[];
+ mac?: { target?: Array<{ target?: string; arch?: string[] }> };
+} {
+ return parse(readFileSync(builderYml, 'utf8'));
+}
+
+function readPkg(): {
+ dependencies?: Record<string, string>;
+ devDependencies?: Record<string, string>;
+} {
+ return JSON.parse(readFileSync(pkgJson, 'utf8'));
+}
+
+describe('node-pty desktop packaging config', () => {
+ test('source files exist (premise check)', () => {
+ expect(existsSync(builderYml)).toBe(true);
+ expect(existsSync(pkgJson)).toBe(true);
+ expect(existsSync(afterPack)).toBe(true);
+ });
+
+ test('node-pty is an upstream dependency and @lydell/node-pty is not used', () => {
+ const pkg = readPkg();
+ const deps = { ...pkg.dependencies, ...pkg.devDependencies };
+ expect(
+ pkg.dependencies?.['node-pty'],
+ 'node-pty must be a runtime dependency so electron-builder packs it into the app.',
+ ).toBe('1.1.0');
+ expect(
+ '@lydell/node-pty' in deps,
+ '@lydell/node-pty recreates the keyring per-arch universal-merge hazard — use upstream node-pty.',
+ ).toBe(false);
+ });
+
+ test('asarUnpack unpacks the node-pty prebuilds tree (covers extensionless spawn-helper)', () => {
+ const patterns = readBuilderConfig().asarUnpack ?? [];
+ expect(
+ patterns.includes('**/node-pty/prebuilds/**'),
+ "Add '**/node-pty/prebuilds/**' to electron-builder.yml asarUnpack. The generic '**/*.node' " +
+ 'rule does NOT cover node-pty/prebuilds/<arch>/spawn-helper (extensionless), and node-pty ' +
+ 'resolves that helper from app.asar.unpacked at runtime — packed-in-asar means ' +
+ 'pty.fork() fails with "posix_spawnp failed".',
+ ).toBe(true);
+ });
+
+ test('afterPack makes the unpacked spawn-helper executable (unpack rule + chmod move together)', () => {
+ const src = readFileSync(afterPack, 'utf8');
+ expect(
+ src.includes('ensureNodePtySpawnHelperExecutable'),
+ 'afterPack.mjs must call ensureNodePtySpawnHelperExecutable so the unpacked-but-0644 ' +
+ 'spawn-helper (node-pty#850) is chmod 0755 before signing. Unpacking it without chmod ' +
+ 'still ships a non-executable helper and the terminal dies at runtime.',
+ ).toBe(true);
+ });
+
+ test('mac build stays arm64-only — no universal/x64 target (node-pty native would split the lipo merge)', () => {
+ const targets = readBuilderConfig().mac?.target ?? [];
+ expect(targets.length).toBeGreaterThan(0);
+ for (const t of targets) {
+ const arches = t.arch ?? [];
+ expect(
+ arches,
+ `mac.target "${t.target}" must ship arm64 only; got [${arches.join(', ')}]. A universal ` +
+ 'or x64 slice pulls node-pty (and keyring) per-arch natives into the @electron/universal ' +
+ 'merge, the hazard that forced this build arm64-only.',
+ ).toEqual(['arm64']);
+ }
+ });
+});
diff --git a/packages/desktop/tests/unit/ensure-node-pty-exec.test.ts b/packages/desktop/tests/unit/ensure-node-pty-exec.test.ts
new file mode 100644
index 000000000..2ffad50cc
--- /dev/null
+++ b/packages/desktop/tests/unit/ensure-node-pty-exec.test.ts
@@ -0,0 +1,69 @@
+import { afterEach, describe, expect, test } from 'bun:test';
+import { chmodSync, mkdirSync, mkdtempSync, rmSync, statSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { ensureNodePtySpawnHelperExecutable } from '../../scripts/ensure-node-pty-exec.mjs';
+
+const tmpRoots: string[] = [];
+
+function helperPath(resourcesDir: string, arch: string): string {
+ return join(
+ resourcesDir,
+ 'app.asar.unpacked',
+ 'node_modules',
+ 'node-pty',
+ 'prebuilds',
+ arch,
+ 'spawn-helper',
+ );
+}
+
+function makeResourcesFixture(archDirs: string[]): string {
+ const root = mkdtempSync(join(tmpdir(), 'ok-nodepty-exec-'));
+ tmpRoots.push(root);
+ for (const arch of archDirs) {
+ const helper = helperPath(root, arch);
+ mkdirSync(join(helper, '..'), { recursive: true });
+ writeFileSync(helper, 'fake-mach-o');
+ chmodSync(helper, 0o644);
+ }
+ return root;
+}
+
+afterEach(() => {
+ while (tmpRoots.length > 0) {
+ const dir = tmpRoots.pop();
+ if (dir) rmSync(dir, { recursive: true, force: true });
+ }
+});
+
+describe('ensureNodePtySpawnHelperExecutable', () => {
+ test('promotes the shipped darwin-arm64 spawn-helper from 0644 to executable 0755', () => {
+ const resourcesDir = makeResourcesFixture(['darwin-arm64']);
+ const helper = helperPath(resourcesDir, 'darwin-arm64');
+ expect(statSync(helper).mode & 0o111).toBe(0); // no execute bits to start
+
+ const chmodded = ensureNodePtySpawnHelperExecutable(resourcesDir);
+
+ expect(chmodded).toContain(helper);
+ expect(statSync(helper).mode & 0o777).toBe(0o755);
+ });
+
+ test('chmods every prebuild arch the unpack rule extracted, not just the shipped one', () => {
+ const resourcesDir = makeResourcesFixture(['darwin-arm64', 'darwin-x64']);
+
+ const chmodded = ensureNodePtySpawnHelperExecutable(resourcesDir);
+
+ expect(chmodded.length).toBe(2);
+ for (const arch of ['darwin-arm64', 'darwin-x64']) {
+ expect(statSync(helperPath(resourcesDir, arch)).mode & 0o777).toBe(0o755);
+ }
+ });
+
+ test('throws when the shipped darwin-arm64 spawn-helper is absent (broken packaging is a hard build error)', () => {
+ const resourcesDir = makeResourcesFixture(['darwin-x64']); // arm64 helper missing
+ expect(() => ensureNodePtySpawnHelperExecutable(resourcesDir)).toThrow(
+ /darwin-arm64 spawn-helper missing/,
+ );
+ });
+});
diff --git a/packages/desktop/tests/utility/pty-flood.harness.ts b/packages/desktop/tests/utility/pty-flood.harness.ts
new file mode 100644
index 000000000..6403f30b1
--- /dev/null
+++ b/packages/desktop/tests/utility/pty-flood.harness.ts
@@ -0,0 +1,344 @@
+import { chmodSync, existsSync, mkdtempSync, realpathSync, rmSync, writeFileSync } from 'node:fs';
+import { createRequire } from 'node:module';
+import { tmpdir } from 'node:os';
+import { dirname, join } from 'node:path';
+import {
+ createTerminalManager,
+ type PtyUtilityLike,
+ type TerminalManager,
+} from '../../src/main/terminal-manager.ts';
+import type { SendableWebContents } from '../../src/shared/ipc-send.ts';
+import {
+ type PtyHostHandle,
+ type PtyHostIncomingMessage,
+ type PtyHostOutgoingMessage,
+ type SpawnPty,
+ setupPtyHost,
+} from '../../src/utility/pty-host.ts';
+
+const require = createRequire(import.meta.url);
+
+function ensureSpawnHelperExecutable(): void {
+ const pkgDir = dirname(dirname(require.resolve('node-pty')));
+ const helper = join(pkgDir, 'prebuilds', `${process.platform}-${process.arch}`, 'spawn-helper');
+ if (existsSync(helper)) chmodSync(helper, 0o755);
+}
+
+const { spawn } = require('node-pty') as { spawn: SpawnPty };
+
+const UNIT = '日本語🎉αβγ';
+const SENTINEL = '__OKFLOOD_42__';
+const SENTINEL_CMD = '__OKFLOOD_$((6*7))__';
+const PTY_ID = 'flood-pty';
+const COALESCE_MS = 12;
+
+const sleep = (ms: number): Promise<void> => new Promise((r) => setTimeout(r, ms));
+
+async function waitFor(predicate: () => boolean, label: string, timeoutMs: number): Promise<void> {
+ const deadline = Date.now() + timeoutMs;
+ while (Date.now() < deadline) {
+ if (predicate()) return;
+ await sleep(10);
+ }
+ throw new Error(`timeout waiting for: ${label}`);
+}
+
+function countOccurrences(haystack: string, needle: string): number {
+ let count = 0;
+ let idx = haystack.indexOf(needle);
+ while (idx !== -1) {
+ count += 1;
+ idx = haystack.indexOf(needle, idx + needle.length);
+ }
+ return count;
+}
+
+function assert(condition: boolean, message: string): void {
+ if (!condition) throw new Error(message);
+}
+
+class InProcessBridge implements PtyUtilityLike {
+ pauseCount = 0;
+ resumeCount = 0;
+ private hostHandler: ((event: { data: unknown }) => void) | null = null;
+ private readonly msgSubs: Array<(message: unknown) => void> = [];
+ private readonly exitSubs: Array<(code: number | null) => void> = [];
+ private readonly hostHandle: PtyHostHandle;
+
+ constructor(spawnPty: SpawnPty, env: Record<string, string | undefined>) {
+ this.hostHandle = setupPtyHost({
+ parentPort: {
+ on: (_event, handler) => {
+ this.hostHandler = handler;
+ },
+ postMessage: (value: PtyHostOutgoingMessage) => {
+ for (const sub of this.msgSubs) sub(value);
+ },
+ },
+ spawn: spawnPty,
+ env,
+ });
+ }
+
+ postMessage(message: PtyHostIncomingMessage): void {
+ if (message.type === 'pause') this.pauseCount += 1;
+ else if (message.type === 'resume') this.resumeCount += 1;
+ this.hostHandler?.({ data: message });
+ }
+
+ on(event: 'message', cb: (message: unknown) => void): void;
+ on(event: 'exit', cb: (code: number | null) => void): void;
+ on(event: 'message' | 'exit', cb: (arg: never) => void): void {
+ if (event === 'message') this.msgSubs.push(cb as (message: unknown) => void);
+ else this.exitSubs.push(cb as (code: number | null) => void);
+ }
+
+ kill(): boolean {
+ this.reap();
+ for (const sub of this.exitSubs) sub(0);
+ return true;
+ }
+
+ reap(): void {
+ this.hostHandle.killActive();
+ }
+}
+
+interface FloodOptions {
+ units: number;
+ highWaterBytes: number;
+ lowWaterBytes: number;
+ drain: 'immediate' | 'metered';
+ stallUntilPaused?: boolean;
+ meterUnitsPerTick?: number;
+ meterTickMs?: number;
+ heartbeat?: boolean;
+}
+
+interface FloodMetrics {
+ units: number;
+ receivedUnitCount: number;
+ hasReplacementChar: boolean;
+ totalPushedCodeUnits: number;
+ pushCount: number;
+ maxInFlight: number;
+ pauseCount: number;
+ resumeCount: number;
+ maxHeartbeatGapMs: number;
+ heartbeats: number;
+ floodMs: number;
+}
+
+async function runFloodScenario(opts: FloodOptions): Promise<FloodMetrics> {
+ const tmp = realpathSync(mkdtempSync(join(tmpdir(), 'ok-pty-flood-')));
+ const file = join(tmp, 'flood.txt');
+ writeFileSync(file, UNIT.repeat(opts.units), 'utf8');
+
+ const bridge = new InProcessBridge(spawn, { ...process.env });
+
+ const chunks: string[] = [];
+ let totalPushed = 0;
+ let totalAcked = 0;
+ let pushCount = 0;
+ let maxInFlight = 0;
+ let tail = '';
+ let sawSentinel = false;
+ let drainEnabled = opts.drain === 'immediate';
+
+ const webContents: SendableWebContents = { send: () => {}, isDestroyed: () => false };
+
+ let manager!: TerminalManager;
+ const ackBytes = (n: number): void => {
+ totalAcked += n;
+ manager.drain({ windowId: 1, ptyId: PTY_ID, bytes: n });
+ };
+
+ manager = createTerminalManager({
+ forkPtyHost: () => bridge,
+ sendData: (_wc, payload) => {
+ chunks.push(payload.data);
+ totalPushed += payload.data.length;
+ pushCount += 1;
+ const inFlight = totalPushed - totalAcked;
+ if (inFlight > maxInFlight) maxInFlight = inFlight;
+ tail = (tail + payload.data).slice(-256);
+ if (!sawSentinel && tail.includes(SENTINEL)) sawSentinel = true;
+ if (opts.drain === 'immediate' && drainEnabled) {
+ const n = payload.data.length;
+ queueMicrotask(() => ackBytes(n));
+ }
+ },
+ sendExit: () => {},
+ newPtyId: () => PTY_ID,
+ setTimer: (cb, ms) => setTimeout(cb, ms),
+ clearTimer: (t) => clearTimeout(t as ReturnType<typeof setTimeout>),
+ coalesceMs: COALESCE_MS,
+ highWaterBytes: opts.highWaterBytes,
+ lowWaterBytes: opts.lowWaterBytes,
+ });
+
+ let lastBeat = 0;
+ let maxGap = 0;
+ let beats = 0;
+ let measuring = false;
+ const heartbeat = opts.heartbeat
+ ? setInterval(() => {
+ const now = Date.now();
+ if (measuring && lastBeat > 0) {
+ const gap = now - lastBeat;
+ if (gap > maxGap) maxGap = gap;
+ beats += 1;
+ }
+ lastBeat = now;
+ }, 10)
+ : null;
+
+ const meterUnits = opts.meterUnitsPerTick ?? 262144;
+ const meterMs = opts.meterTickMs ?? 20;
+ const pump =
+ opts.drain === 'metered'
+ ? setInterval(() => {
+ if (!drainEnabled) return;
+ const available = totalPushed - totalAcked;
+ if (available <= 0) return;
+ ackBytes(Math.min(meterUnits, available));
+ }, meterMs)
+ : null;
+
+ try {
+ manager.create({ windowId: 1, webContents, projectRoot: tmp, cols: 80, rows: 24 });
+ await waitFor(() => totalPushed > 0, 'shell prompt', 15000);
+
+ const floodStart = Date.now();
+ measuring = true;
+ manager.input({ windowId: 1, ptyId: PTY_ID, data: `cat '${file}'; echo ${SENTINEL_CMD}\r` });
+
+ if (opts.stallUntilPaused) {
+ await waitFor(() => bridge.pauseCount > 0, 'backpressure pause to engage', 20000);
+ drainEnabled = true;
+ }
+
+ await waitFor(() => sawSentinel, 'flood completion sentinel', 60000);
+ const floodMs = Date.now() - floodStart;
+ measuring = false;
+
+ const all = chunks.join('');
+ return {
+ units: opts.units,
+ receivedUnitCount: countOccurrences(all, UNIT),
+ hasReplacementChar: all.includes('�'),
+ totalPushedCodeUnits: totalPushed,
+ pushCount,
+ maxInFlight,
+ pauseCount: bridge.pauseCount,
+ resumeCount: bridge.resumeCount,
+ maxHeartbeatGapMs: maxGap,
+ heartbeats: beats,
+ floodMs,
+ };
+ } finally {
+ if (heartbeat) clearInterval(heartbeat);
+ if (pump) clearInterval(pump);
+ try {
+ manager.kill({ windowId: 1, ptyId: PTY_ID });
+ } catch {}
+ bridge.reap();
+ try {
+ rmSync(tmp, { recursive: true, force: true });
+ } catch {}
+ }
+}
+
+const results: Array<{ name: string; ok: boolean }> = [];
+async function scenario(name: string, fn: () => Promise<void>): Promise<void> {
+ try {
+ await fn();
+ results.push({ name, ok: true });
+ console.log(`PASS ${name}`);
+ } catch (err) {
+ results.push({ name, ok: false });
+ console.log(`FAIL ${name} :: ${(err as Error).message}`);
+ }
+}
+
+const FLOOD_UNITS_RESPONSIVE = 1_500_000; // ~28.5 MB UTF-8 / 12M UTF-16 code units
+const FLOOD_UNITS_BACKPRESSURE = 300_000; // ~5.7 MB UTF-8 / 2.4M UTF-16 code units
+const MAX_HEARTBEAT_GAP_MS = (() => {
+ const override = Number(process.env.OK_FLOOD_MAX_GAP_MS);
+ return Number.isFinite(override) && override > 0 ? override : 500;
+})();
+
+async function main(): Promise<void> {
+ ensureSpawnHelperExecutable();
+
+ await scenario('flood stays responsive and byte-exact under a fast consumer', async () => {
+ const m = await runFloodScenario({
+ units: FLOOD_UNITS_RESPONSIVE,
+ highWaterBytes: Number.MAX_SAFE_INTEGER,
+ lowWaterBytes: 0,
+ drain: 'immediate',
+ heartbeat: true,
+ });
+ assert(
+ m.receivedUnitCount === m.units,
+ `byte corruption: ${m.receivedUnitCount} units delivered, expected ${m.units}`,
+ );
+ assert(!m.hasReplacementChar, 'U+FFFD replacement char in stream (split multibyte sequence)');
+ assert(m.heartbeats > 0, 'event loop frozen: no heartbeats fired during the flood');
+ assert(
+ m.maxHeartbeatGapMs < MAX_HEARTBEAT_GAP_MS,
+ `event loop starved: max heartbeat gap ${m.maxHeartbeatGapMs}ms >= ${MAX_HEARTBEAT_GAP_MS}ms`,
+ );
+ const maxExpectedPushes = Math.ceil(m.floodMs / COALESCE_MS) + 8;
+ assert(
+ m.pushCount <= maxExpectedPushes,
+ `coalescing ineffective: ${m.pushCount} pushes for a ${m.floodMs}ms flood (tick-bound ${maxExpectedPushes})`,
+ );
+ const avgPushUnits = m.totalPushedCodeUnits / Math.max(1, m.pushCount);
+ console.log(
+ ` units=${m.units} pushes=${m.pushCount} avgPush=${avgPushUnits.toFixed(0)} maxGap=${m.maxHeartbeatGapMs}ms beats=${m.heartbeats} floodMs=${m.floodMs}`,
+ );
+ });
+
+ await scenario('flood backpressure bounds in-flight under a slow consumer', async () => {
+ const highWater = 256 * 1024;
+ const m = await runFloodScenario({
+ units: FLOOD_UNITS_BACKPRESSURE,
+ highWaterBytes: highWater,
+ lowWaterBytes: 64 * 1024,
+ drain: 'metered',
+ stallUntilPaused: true,
+ meterUnitsPerTick: 131072,
+ meterTickMs: 20,
+ });
+ assert(
+ m.receivedUnitCount === m.units,
+ `byte corruption: ${m.receivedUnitCount} units delivered, expected ${m.units}`,
+ );
+ assert(!m.hasReplacementChar, 'U+FFFD replacement char in stream (split multibyte sequence)');
+ assert(m.pauseCount >= 1, 'backpressure never paused the source under sustained flood');
+ assert(m.resumeCount >= 1, 'backpressure never resumed the source after draining');
+ assert(
+ m.maxInFlight < m.totalPushedCodeUnits * 0.6,
+ `in-flight not bounded: peak ${m.maxInFlight} vs ${m.totalPushedCodeUnits} total code units`,
+ );
+ console.log(
+ ` units=${m.units} maxInFlight=${m.maxInFlight} highWater=${highWater} pauses=${m.pauseCount} resumes=${m.resumeCount} floodMs=${m.floodMs}`,
+ );
+ });
+
+ const failed = results.filter((r) => !r.ok).length;
+ console.log(`HARNESS_RESULT ok=${results.length - failed} fail=${failed}`);
+ process.exit(failed === 0 ? 0 : 1);
+}
+
+const hardTimeout = setTimeout(() => {
+ console.log('HARNESS_RESULT ok=0 fail=1 :: hard timeout');
+ process.exit(1);
+}, 120000);
+hardTimeout.unref();
+
+void main().catch((err) => {
+ console.log(`HARNESS_RESULT ok=0 fail=1 :: ${(err as Error).message}`);
+ process.exit(1);
+});
diff --git a/packages/desktop/tests/utility/pty-flood.test.ts b/packages/desktop/tests/utility/pty-flood.test.ts
new file mode 100644
index 000000000..f8a19a3ba
--- /dev/null
+++ b/packages/desktop/tests/utility/pty-flood.test.ts
@@ -0,0 +1,20 @@
+import { describe, expect, test } from 'bun:test';
+
+const NODE = Bun.which('node');
+const HARNESS = new URL('./pty-flood.harness.ts', import.meta.url).pathname;
+
+describe('PTY flood — backpressure + UTF-8 integrity (Node runtime)', () => {
+ test('a sustained multibyte flood stays responsive, bounds in-flight via pause/resume, and delivers bytes uncorrupted', () => {
+ if (!NODE) {
+ throw new Error(
+ 'node was not found on PATH but is required (package engines: >=24) to drive the real-PTY flood — node-pty produces no output under Bun',
+ );
+ }
+ const proc = Bun.spawnSync([NODE, HARNESS], { stdout: 'pipe', stderr: 'pipe' });
+ const output = `${proc.stdout.toString()}${proc.stderr.toString()}`;
+ if (proc.exitCode !== 0) {
+ throw new Error(`flood harness failed (exit ${proc.exitCode}):\n${output}`);
+ }
+ expect(output).toContain('HARNESS_RESULT ok=2 fail=0');
+ }, 120_000);
+});
diff --git a/packages/desktop/tests/utility/pty-host-real-io.test.ts b/packages/desktop/tests/utility/pty-host-real-io.test.ts
new file mode 100644
index 000000000..0aeb2ed32
--- /dev/null
+++ b/packages/desktop/tests/utility/pty-host-real-io.test.ts
@@ -0,0 +1,26 @@
+import { describe, expect, test } from 'bun:test';
+
+const NODE = Bun.which('node');
+const HARNESS = new URL('./pty-host.real-io-harness.ts', import.meta.url).pathname;
+
+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',
+ () => {
+ 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}`);
+ }
+ expect(output).toContain('HARNESS_RESULT ok=4 fail=0');
+ },
+ 60_000,
+ );
+});
diff --git a/packages/desktop/tests/utility/pty-host-reap.test.ts b/packages/desktop/tests/utility/pty-host-reap.test.ts
new file mode 100644
index 000000000..a0fc8dd32
--- /dev/null
+++ b/packages/desktop/tests/utility/pty-host-reap.test.ts
@@ -0,0 +1,75 @@
+import { describe, expect, test } from 'bun:test';
+import { isProcessAlive } from '@inkeep/open-knowledge-server';
+
+const NODE = Bun.which('node');
+const HARNESS = new URL('./pty-host.reap-harness.ts', import.meta.url).pathname;
+
+async function readShellPid(
+ stream: ReadableStream<Uint8Array>,
+ timeoutMs: number,
+): Promise<number> {
+ const reader = stream.getReader();
+ const decoder = new TextDecoder();
+ let buf = '';
+ const deadline = Date.now() + timeoutMs;
+ try {
+ while (Date.now() < deadline) {
+ const { value, done } = await reader.read();
+ if (done) break;
+ buf += decoder.decode(value, { stream: true });
+ const match = buf.match(/SHELLPID=(\d+)/);
+ if (match) return Number(match[1]);
+ }
+ } finally {
+ reader.releaseLock();
+ }
+ throw new Error(`harness never reported SHELLPID; output so far:\n${buf}`);
+}
+
+async function waitForReaped(pid: number, timeoutMs: number): Promise<boolean> {
+ const deadline = Date.now() + timeoutMs;
+ while (Date.now() < deadline) {
+ if (!isProcessAlive(pid)) return true;
+ await new Promise((r) => setTimeout(r, 50));
+ }
+ return false;
+}
+
+async function assertNoOrphan(killSignal: 'SIGTERM' | 'SIGKILL'): Promise<void> {
+ const proc = Bun.spawn([NODE as string, HARNESS], { stdout: 'pipe', stderr: 'pipe' });
+ let shellPid: number | null = null;
+ try {
+ shellPid = await readShellPid(proc.stdout, 20_000);
+ expect(isProcessAlive(shellPid)).toBe(true);
+ proc.kill(killSignal);
+ expect(await waitForReaped(shellPid, 10_000)).toBe(true);
+ } finally {
+ if (shellPid !== null && isProcessAlive(shellPid)) {
+ try {
+ process.kill(shellPid, 'SIGKILL');
+ } catch {}
+ }
+ proc.kill('SIGKILL');
+ await proc.exited;
+ }
+}
+
+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.ts
new file mode 100644
index 000000000..0855076c0
--- /dev/null
+++ b/packages/desktop/tests/utility/pty-host.real-io-harness.ts
@@ -0,0 +1,165 @@
+import { chmodSync, existsSync, mkdtempSync, realpathSync, rmSync } from 'node:fs';
+import { createRequire } from 'node:module';
+import { tmpdir } from 'node:os';
+import { basename, dirname, join } from 'node:path';
+import {
+ type PtyHostIncomingMessage,
+ type PtyHostOutgoingMessage,
+ type SpawnPty,
+ setupPtyHost,
+} from '../../src/utility/pty-host.ts';
+
+const require = createRequire(import.meta.url);
+
+function ensureSpawnHelperExecutable(): void {
+ const pkgDir = dirname(dirname(require.resolve('node-pty')));
+ const helper = join(pkgDir, 'prebuilds', `${process.platform}-${process.arch}`, 'spawn-helper');
+ if (existsSync(helper)) chmodSync(helper, 0o755);
+}
+
+const { spawn } = require('node-pty') as { spawn: SpawnPty };
+
+interface Host {
+ send(msg: PtyHostIncomingMessage): void;
+ dataOf(ptyId: string): string;
+ exitOf(ptyId: string): { exitCode: number; signal: number | null } | null;
+ errorOf(ptyId: string): string | null;
+ killActive(): void;
+}
+
+function createHost(env: Record<string, string | undefined>): Host {
+ let handler: ((event: { data: unknown }) => void) | null = null;
+ const data = new Map<string, string>();
+ const exits = new Map<string, { exitCode: number; signal: number | null }>();
+ const errors = new Map<string, string>();
+ const handle = setupPtyHost({
+ parentPort: {
+ on(_event, h) {
+ handler = h;
+ },
+ postMessage(msg: PtyHostOutgoingMessage) {
+ if (msg.type === 'data') data.set(msg.ptyId, (data.get(msg.ptyId) ?? '') + msg.data);
+ else if (msg.type === 'exit')
+ exits.set(msg.ptyId, { exitCode: msg.exitCode, signal: msg.signal });
+ else if (msg.type === 'spawn-error') errors.set(msg.ptyId, msg.message);
+ },
+ },
+ spawn,
+ env,
+ });
+ return {
+ send: (msg) => handler?.({ data: msg }),
+ dataOf: (ptyId) => data.get(ptyId) ?? '',
+ exitOf: (ptyId) => exits.get(ptyId) ?? null,
+ errorOf: (ptyId) => errors.get(ptyId) ?? null,
+ killActive: () => handle.killActive(),
+ };
+}
+
+const sleep = (ms: number): Promise<void> => new Promise((r) => setTimeout(r, ms));
+
+async function waitFor(predicate: () => boolean, label: string, timeoutMs = 8000): Promise<void> {
+ const deadline = Date.now() + timeoutMs;
+ while (Date.now() < deadline) {
+ if (predicate()) return;
+ await sleep(15);
+ }
+ throw new Error(`timeout waiting for: ${label}`);
+}
+
+const results: Array<{ name: string; ok: boolean; detail?: string }> = [];
+async function scenario(name: string, fn: () => Promise<void>): Promise<void> {
+ try {
+ await fn();
+ results.push({ name, ok: true });
+ console.log(`PASS ${name}`);
+ } catch (err) {
+ results.push({ name, ok: false, detail: (err as Error).message });
+ console.log(`FAIL ${name} :: ${(err as Error).message}`);
+ }
+}
+
+const BASE_ENV = { ...process.env };
+
+async function main(): Promise<void> {
+ ensureSpawnHelperExecutable();
+
+ const tmp = realpathSync(mkdtempSync(join(tmpdir(), 'ok-pty-harness-')));
+
+ await scenario('real command round-trip at project root', async () => {
+ const host = createHost(BASE_ENV);
+ host.send({ type: 'create', ptyId: 'io', cwd: tmp, cols: 80, rows: 24 });
+ await waitFor(() => host.dataOf('io').length > 0, 'shell prompt');
+ host.send({ type: 'input', ptyId: 'io', data: 'echo HARNESS_$((6*7))_DONE\r' });
+ await waitFor(() => host.dataOf('io').includes('HARNESS_42_DONE'), 'evaluated command output');
+ host.send({ type: 'input', ptyId: 'io', data: 'pwd\r' });
+ await waitFor(() => host.dataOf('io').includes(basename(tmp)), 'pwd shows project root');
+ host.killActive();
+ });
+
+ await scenario('strips desktop env markers from the shell', async () => {
+ const host = createHost({
+ ...BASE_ENV,
+ OK_ELECTRON_PROTOCOL_HOST: '1',
+ OK_LOCK_KIND: 'interactive',
+ });
+ host.send({ type: 'create', ptyId: 'env', cwd: tmp, cols: 80, rows: 24 });
+ await waitFor(() => host.dataOf('env').length > 0, 'shell prompt');
+ host.send({
+ type: 'input',
+ ptyId: 'env',
+ data: 'printf "MARKERS:[%s][%s]\\n" "$OK_LOCK_KIND" "$OK_ELECTRON_PROTOCOL_HOST"\r',
+ });
+ await waitFor(() => host.dataOf('env').includes('MARKERS:[][]'), 'empty markers in shell');
+ if (host.dataOf('env').includes('MARKERS:[interactive]')) {
+ throw new Error('OK_LOCK_KIND leaked into the shell');
+ }
+ host.killActive();
+ });
+
+ await scenario('host survives a PTY death and respawns', async () => {
+ const host = createHost(BASE_ENV);
+ host.send({ type: 'create', ptyId: 'c1', cwd: tmp, cols: 80, rows: 24 });
+ await waitFor(() => host.dataOf('c1').length > 0, 'first shell prompt');
+ host.send({ type: 'kill', ptyId: 'c1' });
+ await waitFor(() => host.exitOf('c1') !== null, 'exit after kill');
+ host.send({ type: 'create', ptyId: 'c2', cwd: tmp, cols: 80, rows: 24 });
+ await waitFor(() => host.dataOf('c2').length > 0, 'second shell prompt (host survived)');
+ host.killActive();
+ });
+
+ await scenario('bad shell surfaces as a non-zero exit', async () => {
+ const host = createHost(BASE_ENV);
+ host.send({
+ type: 'create',
+ ptyId: 'bad',
+ cwd: tmp,
+ cols: 80,
+ rows: 24,
+ shell: '/no/such/shell-xyz',
+ });
+ await waitFor(() => host.exitOf('bad') !== null, 'exit for unspawnable shell');
+ const exit = host.exitOf('bad');
+ if (exit && exit.exitCode === 0 && exit.signal === null) {
+ throw new Error('expected a non-zero/failed exit for a bad shell');
+ }
+ host.killActive();
+ });
+
+ rmSync(tmp, { recursive: true, force: true });
+
+ const failed = results.filter((r) => !r.ok).length;
+ console.log(`HARNESS_RESULT ok=${results.length - failed} fail=${failed}`);
+ process.exit(failed === 0 ? 0 : 1);
+}
+
+const hardTimeout = setTimeout(() => {
+ console.log('HARNESS_RESULT ok=0 fail=1 :: hard timeout');
+ process.exit(1);
+}, 30000);
+hardTimeout.unref();
+
+void main().catch((err) => {
+ console.log(`HARNESS_RESULT ok=0 fail=1 :: ${(err as Error).message}`);
+ process.exit(1);
+});
diff --git a/packages/desktop/tests/utility/pty-host.reap-harness.ts b/packages/desktop/tests/utility/pty-host.reap-harness.ts
new file mode 100644
index 000000000..ad2283343
--- /dev/null
+++ b/packages/desktop/tests/utility/pty-host.reap-harness.ts
@@ -0,0 +1,76 @@
+import { chmodSync, existsSync, mkdtempSync, realpathSync, rmSync } from 'node:fs';
+import { createRequire } from 'node:module';
+import { tmpdir } from 'node:os';
+import { dirname, join } from 'node:path';
+import {
+ installHostReaping,
+ type PtyHostIncomingMessage,
+ type PtyHostOutgoingMessage,
+ type SpawnPty,
+ setupPtyHost,
+} from '../../src/utility/pty-host.ts';
+
+const require = createRequire(import.meta.url);
+
+function ensureSpawnHelperExecutable(): void {
+ const pkgDir = dirname(dirname(require.resolve('node-pty')));
+ const helper = join(pkgDir, 'prebuilds', `${process.platform}-${process.arch}`, 'spawn-helper');
+ if (existsSync(helper)) chmodSync(helper, 0o755);
+}
+
+const { spawn } = require('node-pty') as { spawn: SpawnPty };
+const sleep = (ms: number): Promise<void> => new Promise((r) => setTimeout(r, ms));
+
+async function main(): Promise<void> {
+ ensureSpawnHelperExecutable();
+ const tmp = realpathSync(mkdtempSync(join(tmpdir(), 'ok-pty-reap-')));
+ process.on('exit', () => {
+ try {
+ rmSync(tmp, { recursive: true, force: true });
+ } catch {}
+ });
+
+ let data = '';
+ let handler: ((event: { data: unknown }) => void) | null = null;
+ const handle = setupPtyHost({
+ parentPort: {
+ on(_event, h) {
+ handler = h;
+ },
+ postMessage(msg: PtyHostOutgoingMessage) {
+ if (msg.type === 'data') data += msg.data;
+ },
+ },
+ spawn,
+ env: process.env,
+ });
+ installHostReaping(handle, process);
+ const send = (msg: PtyHostIncomingMessage): void => handler?.({ data: msg });
+
+ send({ type: 'create', ptyId: 'reap', cwd: tmp, cols: 80, rows: 24 });
+
+ const deadline = Date.now() + 15000;
+ while (data.length === 0 && Date.now() < deadline) await sleep(15);
+ send({ type: 'input', ptyId: 'reap', data: 'echo SHELLPID=$$\r' });
+ let pid: number | null = null;
+ while (pid === null && Date.now() < deadline) {
+ const match = data.match(/SHELLPID=(\d+)/);
+ if (match) pid = Number(match[1]);
+ else await sleep(15);
+ }
+ if (pid === null) {
+ console.error('reap-harness: shell never reported its pid');
+ process.exit(1);
+ }
+
+ process.stdout.write(`SHELLPID=${pid}\n`);
+
+ await sleep(30000);
+ handle.killActive();
+ process.exit(2);
+}
+
+void main().catch((err) => {
+ console.error(`reap-harness fatal: ${(err as Error).message}`);
+ process.exit(1);
+});
diff --git a/packages/desktop/tests/utility/pty-host.test.ts b/packages/desktop/tests/utility/pty-host.test.ts
new file mode 100644
index 000000000..b66c32bf4
--- /dev/null
+++ b/packages/desktop/tests/utility/pty-host.test.ts
@@ -0,0 +1,457 @@
+import { describe, expect, test } from 'bun:test';
+import {
+ buildShellEnv,
+ type HostReapProcess,
+ installHostReaping,
+ type PtyCreateMessage,
+ type PtyHostHandle,
+ type PtyHostIncomingMessage,
+ type PtyHostOutgoingMessage,
+ type PtyProcessLike,
+ type PtySpawnOptions,
+ resolveShell,
+ type SpawnPty,
+ setupPtyHost,
+} from '../../src/utility/pty-host.ts';
+
+interface FakePty extends PtyProcessLike {
+ writes: string[];
+ resizes: Array<[number, number]>;
+ killCount: number;
+ killThrows: boolean;
+ pauseCount: number;
+ resumeCount: number;
+ emitData(data: string): void;
+ emitExit(event: { exitCode: number; signal?: number }): void;
+}
+
+function makeFakePty(): FakePty {
+ let onData: ((data: string) => void) | null = null;
+ let onExit: ((event: { exitCode: number; signal?: number }) => void) | null = null;
+ return {
+ pid: 4242,
+ writes: [],
+ resizes: [],
+ killCount: 0,
+ killThrows: false,
+ pauseCount: 0,
+ resumeCount: 0,
+ onData(listener) {
+ onData = listener;
+ },
+ onExit(listener) {
+ onExit = listener;
+ },
+ write(data) {
+ this.writes.push(data);
+ },
+ resize(cols, rows) {
+ this.resizes.push([cols, rows]);
+ },
+ kill() {
+ this.killCount += 1;
+ if (this.killThrows) throw Object.assign(new Error('kill ESRCH'), { code: 'ESRCH' });
+ },
+ pause() {
+ this.pauseCount += 1;
+ },
+ resume() {
+ this.resumeCount += 1;
+ },
+ emitData(data) {
+ onData?.(data);
+ },
+ emitExit(event) {
+ onExit?.(event);
+ },
+ };
+}
+
+interface Harness {
+ fire(message: PtyHostIncomingMessage): void;
+ fireRaw(data: unknown): void;
+ posted: PtyHostOutgoingMessage[];
+ spawnCalls: Array<{ file: string; args: string[]; options: PtySpawnOptions }>;
+ handle: ReturnType<typeof setupPtyHost>;
+}
+
+function makeHarness(opts?: {
+ pty?: FakePty;
+ spawn?: SpawnPty;
+ env?: Record<string, string | undefined>;
+ logger?: { warn: (o: Record<string, unknown>) => void };
+}): Harness {
+ let handler: ((event: { data: unknown }) => void) | null = null;
+ const posted: PtyHostOutgoingMessage[] = [];
+ const spawnCalls: Array<{ file: string; args: string[]; options: PtySpawnOptions }> = [];
+ const pty = opts?.pty ?? makeFakePty();
+ const spawn: SpawnPty =
+ opts?.spawn ??
+ ((file, args, options) => {
+ spawnCalls.push({ file, args, options });
+ return pty;
+ });
+ const handle = setupPtyHost({
+ parentPort: {
+ on(_event, h) {
+ handler = h;
+ },
+ postMessage(value) {
+ posted.push(value);
+ },
+ },
+ spawn,
+ env: opts?.env ?? { SHELL: '/bin/zsh', PATH: '/usr/bin' },
+ logger: opts?.logger,
+ });
+ return {
+ fire: (message) => handler?.({ data: message }),
+ fireRaw: (data) => handler?.({ data }),
+ posted,
+ spawnCalls,
+ handle,
+ };
+}
+
+const CREATE = (over?: Partial<PtyCreateMessage>): PtyCreateMessage => ({
+ type: 'create',
+ ptyId: 'p1',
+ cwd: '/project/root',
+ cols: 80,
+ rows: 24,
+ ...over,
+});
+
+describe('setupPtyHost — create', () => {
+ test('spawns the login interactive shell at the project root', () => {
+ const h = makeHarness({ env: { SHELL: '/bin/bash', PATH: '/usr/bin' } });
+ h.fire(CREATE());
+ expect(h.spawnCalls).toHaveLength(1);
+ expect(h.spawnCalls[0]?.file).toBe('/bin/bash');
+ expect(h.spawnCalls[0]?.args).toEqual(['-l', '-i']);
+ expect(h.spawnCalls[0]?.options.cwd).toBe('/project/root');
+ expect(h.spawnCalls[0]?.options.cols).toBe(80);
+ expect(h.spawnCalls[0]?.options.rows).toBe(24);
+ });
+
+ test('falls back to /bin/zsh when SHELL is unset', () => {
+ const h = makeHarness({ env: { PATH: '/usr/bin' } });
+ h.fire(CREATE());
+ expect(h.spawnCalls[0]?.file).toBe('/bin/zsh');
+ });
+
+ test('honors an explicit shell override', () => {
+ const h = makeHarness({ env: { SHELL: '/bin/bash' } });
+ h.fire(CREATE({ cwd: '/x', cols: 10, rows: 10, shell: '/usr/bin/fish' }));
+ expect(h.spawnCalls[0]?.file).toBe('/usr/bin/fish');
+ });
+
+ test('strips desktop-only env markers from the child shell env', () => {
+ const h = makeHarness({
+ env: {
+ SHELL: '/bin/zsh',
+ PATH: '/usr/bin',
+ OK_ELECTRON_PROTOCOL_HOST: '1',
+ OK_LOCK_KIND: 'interactive',
+ },
+ });
+ h.fire(CREATE());
+ const env = h.spawnCalls[0]?.options.env ?? {};
+ expect(env.OK_ELECTRON_PROTOCOL_HOST).toBeUndefined();
+ expect(env.OK_LOCK_KIND).toBeUndefined();
+ expect(env.PATH).toBe('/usr/bin');
+ });
+});
+
+describe('setupPtyHost — streaming', () => {
+ test('forwards shell output as data messages tagged with the ptyId', () => {
+ const pty = makeFakePty();
+ const h = makeHarness({ pty });
+ h.fire(CREATE({ ptyId: 'abc' }));
+ pty.emitData('hello ');
+ pty.emitData('world');
+ expect(h.posted).toEqual([
+ { type: 'data', ptyId: 'abc', data: 'hello ' },
+ { type: 'data', ptyId: 'abc', data: 'world' },
+ ]);
+ });
+
+ test('writes renderer input to the pty', () => {
+ const pty = makeFakePty();
+ const h = makeHarness({ pty });
+ h.fire(CREATE());
+ h.fire({ type: 'input', ptyId: 'p1', data: 'ls -la\r' });
+ expect(pty.writes).toEqual(['ls -la\r']);
+ });
+
+ test('resizes the pty', () => {
+ const pty = makeFakePty();
+ const h = makeHarness({ pty });
+ h.fire(CREATE());
+ h.fire({ type: 'resize', ptyId: 'p1', cols: 120, rows: 40 });
+ expect(pty.resizes).toEqual([[120, 40]]);
+ });
+
+ test('kills the pty on a kill message', () => {
+ const pty = makeFakePty();
+ const h = makeHarness({ pty });
+ h.fire(CREATE());
+ h.fire({ type: 'kill', ptyId: 'p1' });
+ expect(pty.killCount).toBe(1);
+ });
+
+ test('routes pause/resume backpressure to the active pty', () => {
+ const pty = makeFakePty();
+ const h = makeHarness({ pty });
+ h.fire(CREATE());
+ h.fire({ type: 'pause', ptyId: 'p1' });
+ h.fire({ type: 'resume', ptyId: 'p1' });
+ expect(pty.pauseCount).toBe(1);
+ expect(pty.resumeCount).toBe(1);
+ });
+});
+
+describe('setupPtyHost — exit', () => {
+ test('emits an exit message with exitCode and a null signal when none', () => {
+ const pty = makeFakePty();
+ const h = makeHarness({ pty });
+ h.fire(CREATE({ ptyId: 'e1' }));
+ pty.emitExit({ exitCode: 0, signal: undefined });
+ expect(h.posted.at(-1)).toEqual({ type: 'exit', ptyId: 'e1', exitCode: 0, signal: null });
+ });
+
+ test('passes the signal through on a signal-killed exit (crash)', () => {
+ const pty = makeFakePty();
+ const h = makeHarness({ pty });
+ h.fire(CREATE({ ptyId: 'e2' }));
+ pty.emitExit({ exitCode: 0, signal: 9 });
+ expect(h.posted.at(-1)).toEqual({ type: 'exit', ptyId: 'e2', exitCode: 0, signal: 9 });
+ });
+
+ test('a dead pty does not forward late data (active-id guard)', () => {
+ const pty = makeFakePty();
+ const h = makeHarness({ pty });
+ h.fire(CREATE({ ptyId: 'g1' }));
+ pty.emitExit({ exitCode: 0 });
+ const before = h.posted.length;
+ pty.emitData('straggler bytes');
+ expect(h.posted.length).toBe(before);
+ });
+});
+
+describe('setupPtyHost — containment (AC5: host survives a PTY failure)', () => {
+ test('a synchronous spawn throw surfaces as spawn-error, not a crash', () => {
+ const spawn: SpawnPty = () => {
+ throw Object.assign(new Error('EMFILE: too many open files'), { code: 'EMFILE' });
+ };
+ const h = makeHarness({ spawn });
+ expect(() => h.fire(CREATE())).not.toThrow();
+ expect(h.posted).toEqual([
+ { type: 'spawn-error', ptyId: 'p1', message: 'EMFILE: too many open files' },
+ ]);
+ });
+
+ test('the host keeps routing after a spawn failure', () => {
+ const goodPty = makeFakePty();
+ let calls = 0;
+ const spawn: SpawnPty = () => {
+ calls += 1;
+ if (calls === 1) throw new Error('spawn blew up');
+ return goodPty;
+ };
+ const h = makeHarness({ spawn });
+ h.fire(CREATE({ ptyId: 'bad' }));
+ h.fire(CREATE({ ptyId: 'good' }));
+ goodPty.emitData('alive');
+ expect(h.posted).toContainEqual({ type: 'data', ptyId: 'good', data: 'alive' });
+ });
+
+ test('swallows an ESRCH from killing an already-exited pty', () => {
+ const pty = makeFakePty();
+ pty.killThrows = true;
+ const h = makeHarness({ pty });
+ h.fire(CREATE());
+ expect(() => h.fire({ type: 'kill', ptyId: 'p1' })).not.toThrow();
+ expect(pty.killCount).toBe(1);
+ });
+});
+
+describe('setupPtyHost — addressing', () => {
+ test('ignores input/resize/kill/pause/resume for an unknown ptyId', () => {
+ const pty = makeFakePty();
+ const h = makeHarness({ pty });
+ h.fire(CREATE({ ptyId: 'real' }));
+ h.fire({ type: 'input', ptyId: 'ghost', data: 'x' });
+ h.fire({ type: 'resize', ptyId: 'ghost', cols: 1, rows: 1 });
+ h.fire({ type: 'kill', ptyId: 'ghost' });
+ h.fire({ type: 'pause', ptyId: 'ghost' });
+ h.fire({ type: 'resume', ptyId: 'ghost' });
+ expect(pty.writes).toEqual([]);
+ expect(pty.resizes).toEqual([]);
+ expect(pty.killCount).toBe(0);
+ expect(pty.pauseCount).toBe(0);
+ expect(pty.resumeCount).toBe(0);
+ });
+
+ test('killActive reaps the live pty (window-close / quit)', () => {
+ const pty = makeFakePty();
+ const h = makeHarness({ pty });
+ h.fire(CREATE());
+ h.handle.killActive();
+ expect(pty.killCount).toBe(1);
+ h.handle.killActive();
+ expect(pty.killCount).toBe(1);
+ });
+
+ test('a second create kills the prior live pty before spawning (supersede/reap)', () => {
+ const first = makeFakePty();
+ const second = makeFakePty();
+ const ptys = [first, second];
+ let n = 0;
+ const spawn: SpawnPty = () => ptys[n++] ?? makeFakePty();
+ const h = makeHarness({ spawn });
+
+ h.fire(CREATE({ ptyId: 'first' }));
+ expect(first.killCount).toBe(0);
+
+ h.fire(CREATE({ ptyId: 'second' }));
+ expect(first.killCount).toBe(1);
+
+ second.emitData('alive');
+ expect(h.posted).toContainEqual({ type: 'data', ptyId: 'second', data: 'alive' });
+ const before = h.posted.length;
+ first.emitData('orphan');
+ expect(h.posted.length).toBe(before);
+ });
+});
+
+describe('setupPtyHost — incoming message validation (asIncomingMessage guard)', () => {
+ function makeLogger() {
+ const warnings: Array<Record<string, unknown>> = [];
+ return { warn: (o: Record<string, unknown>) => warnings.push(o), warnings };
+ }
+
+ test('drops a message with a missing ptyId (no spawn, warns) so it cannot defeat the active-id guard', () => {
+ const logger = makeLogger();
+ const h = makeHarness({ logger });
+ h.fireRaw({ type: 'create', cwd: '/x', cols: 80, rows: 24 });
+ expect(h.spawnCalls).toHaveLength(0);
+ expect(logger.warnings.length).toBeGreaterThan(0);
+ });
+
+ test('drops a message with an empty-string ptyId', () => {
+ const logger = makeLogger();
+ const h = makeHarness({ logger });
+ h.fireRaw({ type: 'input', ptyId: '', data: 'x' });
+ expect(logger.warnings.length).toBeGreaterThan(0);
+ });
+
+ test('a null or non-object message does not throw and is dropped', () => {
+ const logger = makeLogger();
+ const h = makeHarness({ logger });
+ expect(() => h.fireRaw(null)).not.toThrow();
+ expect(() => h.fireRaw('garbage')).not.toThrow();
+ expect(h.spawnCalls).toHaveLength(0);
+ expect(logger.warnings.length).toBeGreaterThan(0);
+ });
+
+ test('an unknown message type lands in the default warn branch (forward-compat)', () => {
+ const logger = makeLogger();
+ const h = makeHarness({ logger });
+ h.fireRaw({ type: 'bogus-future-type', ptyId: 'p1' });
+ expect(h.spawnCalls).toHaveLength(0);
+ expect(logger.warnings.length).toBeGreaterThan(0);
+ });
+});
+
+describe('buildShellEnv', () => {
+ test('strips markers, drops undefined, preserves the rest', () => {
+ const env = buildShellEnv({
+ PATH: '/usr/bin',
+ HOME: '/Users/x',
+ OK_ELECTRON_PROTOCOL_HOST: '1',
+ OK_LOCK_KIND: 'interactive',
+ MAYBE: undefined,
+ });
+ expect(env).toEqual({ PATH: '/usr/bin', HOME: '/Users/x' });
+ });
+});
+
+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');
+ });
+});
+
+class FakeReapProcess implements HostReapProcess {
+ exitCodes: number[] = [];
+ private readonly listeners = new Map<string, Array<() => void>>();
+ on(event: 'exit' | NodeJS.Signals, listener: () => void): void {
+ const arr = this.listeners.get(event) ?? [];
+ arr.push(listener);
+ this.listeners.set(event, arr);
+ }
+ exit(code?: number): void {
+ this.exitCodes.push(code ?? 0);
+ }
+ emit(event: 'exit' | NodeJS.Signals): void {
+ for (const listener of this.listeners.get(event) ?? []) listener();
+ }
+}
+
+function makeReapHandle(): { handle: PtyHostHandle; killCount: () => number } {
+ let count = 0;
+ return {
+ handle: {
+ killActive() {
+ count += 1;
+ },
+ },
+ killCount: () => count,
+ };
+}
+
+describe('installHostReaping', () => {
+ test('SIGTERM reaps the active pty and exits the host', () => {
+ const { handle, killCount } = makeReapHandle();
+ const proc = new FakeReapProcess();
+ installHostReaping(handle, proc);
+ proc.emit('SIGTERM');
+ expect(killCount()).toBe(1);
+ expect(proc.exitCodes).toEqual([0]);
+ });
+
+ test('SIGINT and SIGHUP also reap + exit', () => {
+ for (const signal of ['SIGINT', 'SIGHUP'] as const) {
+ const { handle, killCount } = makeReapHandle();
+ const proc = new FakeReapProcess();
+ installHostReaping(handle, proc);
+ proc.emit(signal);
+ expect(killCount()).toBe(1);
+ expect(proc.exitCodes).toEqual([0]);
+ }
+ });
+
+ test('a plain exit reaps without re-triggering exit (sync backstop)', () => {
+ const { handle, killCount } = makeReapHandle();
+ const proc = new FakeReapProcess();
+ installHostReaping(handle, proc);
+ proc.emit('exit');
+ expect(killCount()).toBe(1);
+ expect(proc.exitCodes).toEqual([]);
+ });
+
+ test('reaping is idempotent across multiple teardown events', () => {
+ const { handle, killCount } = makeReapHandle();
+ const proc = new FakeReapProcess();
+ installHostReaping(handle, proc);
+ proc.emit('SIGTERM');
+ proc.emit('exit');
+ proc.emit('SIGINT');
+ expect(killCount()).toBe(1);
+ expect(proc.exitCodes).toEqual([0, 0]);
+ });
+});
diff --git a/packages/server/src/config/schema.test.ts b/packages/server/src/config/schema.test.ts
index b890edb1d..c2c513c77 100644
--- a/packages/server/src/config/schema.test.ts
+++ b/packages/server/src/config/schema.test.ts
@@ -8,6 +8,7 @@ describe('ConfigSchema', () => {
expect(config.appearance.theme).toBeUndefined();
expect(config.editor.wordWrap).toBe(true);
expect(config.autoSync.enabled).toBeNull();
+ expect(config.terminal.enabled).toBeNull();
});
test('stale dropped fields pass loose-mode without throwing', () => {