Beautiful, AI-native markdown IDE and LLM wiki
TypeScript 2nd-brainagent-skillsclaudecodexcompany-braindocsknowledge-knowledge-baseknowledge-managementllmllm-wikillm-wiki-karpathymarkdownmarkdown-editormdmdxnotespkmsecond-brainskills
feat(open-knowledge): New Terminal Window — standalone terminal in its own window (#2018)
serafin-garcia11efc0a60d21
diff --git a/.changeset/new-terminal-window.md b/.changeset/new-terminal-window.mdnew file mode 100644index 000000000..fa2a21fb2--- /dev/null+++ b/.changeset/new-terminal-window.md@@ -0,0 +1,12 @@+---+"@inkeep/open-knowledge": minor+---++A new **Terminal → New Terminal Window** command opens a terminal in its own dedicated window, so you can keep a full-height shell alongside the editor instead of sharing the docked panel's vertical space.++- The window reuses the docked terminal's multi-session tabs: open more shells with the `+` affordance, switch with ⌘-number, and each tab is its own login shell. The ⌘-number chord is always active here since the whole window is the terminal.+- Launched from a project, the window inherits that project's cwd and config (its shells start at the project root); launched with no project focused, it opens a shell at your home directory.+- Open it as many times as you like — each invocation is an independent window with its own terminal host, including multiple windows for the same project.+- Closing the last tab closes the window, and closing a window reaps all of its shells (no orphaned processes).++The command matches VS Code's "New Terminal Window" and ships without a keyboard shortcut; ⌘J stays the docked Show/Hide Terminal toggle. The docked terminal is unchanged, and the security posture is the same: terminals remain human-only and default-on, with no new IPC surface.diff --git a/packages/app/src/components/TerminalDock.dom.test.tsx b/packages/app/src/components/TerminalDock.dom.test.tsxindex ac2bf9684..164e2cb51 100644--- a/packages/app/src/components/TerminalDock.dom.test.tsx+++ b/packages/app/src/components/TerminalDock.dom.test.tsx@@ -729,6 +729,20 @@ describe('TerminalDock multi-session', () => {expect(screen.getAllByTestId('terminal-session')).toHaveLength(1);});+ test('⌘W (close-active-tab-or-window) is NOT handled by the dock — the editor owns it', async () => {+ const user = userEvent.setup();+ const view = renderDock(true);+ await addTerminalTab(user);+ expect(screen.getAllByTestId('terminal-session')).toHaveLength(2);++ act(() => view.dispatchMenuAction('close-active-tab-or-window'));++ // In the editor window ⌘W closes the active DOC tab (DocumentContext); the+ // docked terminal must not also close a session, or one keystroke would+ // close two things. Only the standalone terminal window handles this action.+ expect(screen.getAllByTestId('terminal-session')).toHaveLength(2);+ });+test('Cmd+number jumps to the matching tab while the terminal is focused', async () => {const user = userEvent.setup();renderDock(true);@@ -1020,3 +1034,95 @@ describe('TerminalSessionsHost focus-return gating across a dock move', () => {expect(onEditorFocus).toHaveBeenCalled();});});++// The behavior-preservation contract for the terminal session model+// (TerminalSessionsHost, shared by the dock and the standalone terminal+// window): these five behaviors (close-last collapse, seed-on-reveal,+// single-tab-per-launch-nonce, Cmd+number tab switch, close-active-neighbor+// focus) are the ones most easily broken when the dock's container wiring and+// the shared session core drift out of lockstep. Kept as a discrete, minimal+// block — distinct from the broader suite above — so the dock and the window+// share one stable, referenceable set to validate against.+describe('TerminalDock extraction pins', () => {+ beforeEach(() => {+ terminalPanelProps = null;+ panelHandle.collapse.mockClear();+ panelHandle.resize.mockClear();+ panelHandle.expand.mockClear();+ sharedPanelRef.current = panelHandle;+ });+ afterEach(() => {+ cleanup();+ });++ test('pin: closing the last tab collapses the dock and returns focus to the editor', async () => {+ const user = userEvent.setup();+ const view = renderDock(true);+ act(() => screen.getByTestId('terminal-session').focus());++ await user.click(screen.getByRole('button', { name: 'Close Terminal 1' }));++ expect(screen.queryAllByTestId('terminal-session')).toHaveLength(0);+ expect(view.onVisibleChange).toHaveBeenCalledWith(false);+ expect(document.activeElement).toBe(editorRegion());+ });++ test('pin: the dock seeds exactly one session when it becomes visible', () => {+ const view = renderDock(false);+ expect(screen.queryAllByTestId('terminal-session')).toHaveLength(0);++ act(() => view.rerender(true));++ expect(screen.getAllByTestId('terminal-session')).toHaveLength(1);+ expect(view.create).toHaveBeenCalledTimes(1);+ });++ test('pin: a repeated launch nonce does not open a second tab', () => {+ const view = renderDock(true);++ act(() => view.rerender(true, { prompt: 'work', nonce: 1 }));+ expect(screen.getAllByTestId('terminal-session')).toHaveLength(2);++ // An unrelated re-render carrying the already-handled nonce must not spawn+ // another tab — one launch click means exactly one new tab.+ act(() => view.rerender(true, { prompt: 'work', nonce: 1 }));+ expect(screen.getAllByTestId('terminal-session')).toHaveLength(2);+ });++ test('pin: Cmd+number switches the active tab while the terminal is focused', async () => {+ const user = userEvent.setup();+ renderDock(true);+ await addTerminalTab(user);+ const panels = sessionPanels();+ act(() => panels[1]?.querySelector<HTMLElement>('.xterm-helper-textarea')?.focus());++ const event = new KeyboardEvent('keydown', {+ key: '1',+ metaKey: true,+ cancelable: true,+ bubbles: true,+ });+ act(() => {+ window.dispatchEvent(event);+ });++ expect(event.defaultPrevented).toBe(true);+ expect(activePanelId()).toBe(panels[0]?.getAttribute('data-terminal-session'));+ });++ test('pin: closing the active tab moves focus to a surviving neighbor', async () => {+ const user = userEvent.setup();+ renderDock(true);+ await addTerminalTab(user);+ await addTerminalTab(user);+ await user.click(screen.getByRole('tab', { name: 'Terminal 2' }));++ await user.click(screen.getByRole('button', { name: 'Close Terminal 2' }));++ const nowActive = activePanelId();+ const focusSink = document.querySelector<HTMLElement>(+ `[data-terminal-session="${nowActive}"] .xterm-helper-textarea`,+ );+ await waitFor(() => expect(document.activeElement).toBe(focusSink));+ });+});diff --git a/packages/app/src/components/TerminalSessionsHost.tsx b/packages/app/src/components/TerminalSessionsHost.tsxindex cea832431..0acb282a2 100644--- a/packages/app/src/components/TerminalSessionsHost.tsx+++ b/packages/app/src/components/TerminalSessionsHost.tsx@@ -11,6 +11,7 @@ import {writePreferBareTerminal,} from '@/lib/terminal-new-tab-store';import { loadStickyAgent, saveStickyAgent, terminalCliId } from '@/lib/unified-agent-store';+import { cn } from '@/lib/utils';import { emitOpenAskAiComposer } from './ask-ai-composer-events';import type { TerminalLaunchIntent } from './EditorPane';import { subscribeToActiveTerminalInput } from './handoff/terminal-input-events';@@ -49,8 +50,21 @@ function focusTerminalSession(id: string) {interface TerminalSessionsHostProps {/** Desktop bridge — the host renders only on the Electron surface. */readonly bridge: OkDesktopBridge;+ /**+ * Which surface hosts the sessions. `'dock'` (default) is the editor's+ * docked terminal: visibility-driven seeding, dock-toggle + collapse controls,+ * ⌘1–9 scoped to focus inside the host. `'window'` is the standalone terminal+ * window: always visible, seeds its first tab on mount, the tab row doubles as+ * the macOS title bar, no dock/collapse controls (window management is the+ * OS's), and ⌘1–9 is scope-free (the whole window is the terminal). Everything+ * else — the new-chat split button, OSC tab titles, menu actions, liveness,+ * reload rehydration — is identical by construction: one session model, two+ * placements.+ */+ readonly variant?: 'dock' | 'window';/** Controlled visibility. The host reflects this and reports close-last back- * through {@link onVisibleChange}; it never owns it. */+ * through {@link onVisibleChange}; it never owns it. The window variant pins+ * it `true` and maps the close-last report to `window.close()`. */readonly visible: boolean;readonly onVisibleChange: (visible: boolean) => void;/** "Open in terminal" launch intent — each new intent opens its own tab. */@@ -73,10 +87,12 @@ interface TerminalSessionsHostProps {/** Return focus to the editor when the terminal hides or the last tab closes. */readonly onRequestEditorFocus: () => void;/** Current dock position — passed to the tab strip's dock-toggle + collapse- * controls so their icons/labels reflect where the terminal lives. */- readonly dockPosition: TerminalDockPosition;- /** Flip the dock between bottom and right (the tab strip's dock-toggle button). */- readonly onToggleDock: () => void;+ * controls so their icons/labels reflect where the terminal lives. Dock+ * variant only. */+ readonly dockPosition?: TerminalDockPosition;+ /** Flip the dock between bottom and right (the tab strip's dock-toggle button).+ * Dock variant only — the strip renders no toggle without it. */+ readonly onToggleDock?: () => void;/** Reports whether any PTY session is currently open. The header's New chat* button reads this to decide between spawning a first chat and merely* revealing the existing dock. */@@ -93,6 +109,7 @@ interface TerminalSessionsHostProps {*/export function TerminalSessionsHost({bridge,+ variant = 'dock',visible,onVisibleChange,launch = null,@@ -166,8 +183,11 @@ export function TerminalSessionsHost({// intent across re-renders.const lastHandledLaunchNonceRef = useRef<number | null>(visible && launch ? launch.nonce : null);// Tracks the prior `visible` so the open-from-hidden transition (false→true) is- // distinguishable from "still visible".- const prevVisibleRef = useRef(visible);+ // distinguishable from "still visible". The window variant mounts already+ // visible, so its mount IS the open transition — starting the ref false routes+ // the first-tab seed through the same open path the dock uses (after any+ // rehydration settles, so adopted reload survivors still win over a fresh seed).+ const prevVisibleRef = useRef(variant === 'window' ? false : visible);// Live PTY id per session, reported up from each panel (null on teardown). Lets// the selection-bubble "Ask AI" input (requestActiveTerminalInput) write into an// already-open terminal's live shell (reuse) instead of the caret going to the@@ -395,21 +415,32 @@ export function TerminalSessionsHost({// The Terminal application menu's per-session items act on the tab collection:// "New Terminal" opens a fresh tab, "Kill Terminal" closes the active one —// reusing the strip's own open/close paths so menu and strip stay identical.+ // ⌘W (`close-active-tab-or-window`) closes the active tab in the WINDOW+ // variant only — every BrowserWindow type must subscribe to it (menu.ts+ // contract), and in the terminal window this host is the only subscriber+ // (close-last then closes the window via the close-last report). In the+ // editor window the doc tree owns ⌘W (DocumentContext closes the active doc+ // tab); handling it here too would double-close.useEffect(() => {return bridge.onMenuAction((action) => {if (action === 'new-terminal') openSessionRef.current(null);else if (action === 'kill-terminal') closeActiveRef.current();+ else if (action === 'close-active-tab-or-window' && variant === 'window')+ closeActiveRef.current();});- }, [bridge]);+ }, [bridge, variant]);// ⌘1–⌘9 jump straight to the Nth tab. Capture phase so a focused xterm can't// swallow the chord; scoped to focus inside the stable host div (which follows// the terminal to whichever dock) so the digit chord stays free everywhere else.+ // The window variant skips the scope gate — the whole window is the terminal,+ // so there is nothing else the digit chord could mean there.useEffect(() => {function onKeyDown(event: KeyboardEvent) {if (!event.metaKey || event.ctrlKey || event.altKey || event.shiftKey) return;if (!/^[1-9]$/.test(event.key)) return;- if (hostEl == null || !hostEl.contains(document.activeElement)) return;+ if (variant !== 'window' && (hostEl == null || !hostEl.contains(document.activeElement)))+ return;const target = sessionsRef.current[Number(event.key) - 1];if (target == null) return;event.preventDefault();@@ -419,7 +450,7 @@ export function TerminalSessionsHost({}window.addEventListener('keydown', onKeyDown, { capture: true });return () => window.removeEventListener('keydown', onKeyDown, { capture: true });- }, [hostEl]);+ }, [hostEl, variant]);// Reflect PTY liveness to main so the Terminal menu's "Kill Terminal" item// enables only while at least one session is live. A collapsed-but-alive@@ -480,7 +511,10 @@ export function TerminalSessionsHost({onToggleDock={onToggleDock}// Collapse hides the terminal but keeps every session alive (hide is not// kill), exactly like the ⌘J toggle — the next reveal restores the tabs.- onCollapse={() => onVisibleChange(false)}+ // The window has no collapse (closing the window is the OS affordance).+ onCollapse={variant === 'window' ? undefined : () => onVisibleChange(false)}+ // Window mode: the tab row doubles as the frameless window's title bar.+ draggable={variant === 'window'}className="h-full">{sessions.map((session) => (@@ -492,7 +526,14 @@ export function TerminalSessionsHost({value={session.id}forceMountdata-terminal-session={session.id}- className="m-0 flex min-h-0 flex-1 flex-col overflow-hidden data-[state=inactive]:hidden"+ // Window mode insets the terminal content by the traffic-light gutter+ // (22px, = trafficLightPosition.x) so its left edge lines up with the+ // bubbles and it isn't glued to the window's edges; the padding shows+ // the window background, framing the xterm. The dock sits flush.+ className={cn(+ 'm-0 flex min-h-0 flex-1 flex-col overflow-hidden data-[state=inactive]:hidden',+ variant === 'window' && 'px-[22px] pb-[22px]',+ )}><TerminalGatebridge={bridge}diff --git a/packages/app/src/components/TerminalTabStrip.dom.test.tsx b/packages/app/src/components/TerminalTabStrip.dom.test.tsxindex c41dd870b..adc43a032 100644--- a/packages/app/src/components/TerminalTabStrip.dom.test.tsx+++ b/packages/app/src/components/TerminalTabStrip.dom.test.tsx@@ -15,6 +15,7 @@ function renderStrip(props?: {activeSessionId?: string;dockPosition?: 'bottom' | 'right';newChatSelected?: 'claude' | 'codex' | 'opencode' | 'cursor' | 'terminal';+ draggable?: boolean;}) {const onSelect = mock((_id: string) => {});const onTabActivate = mock((_id: string) => {});@@ -27,6 +28,8 @@ function renderStrip(props?: {render(// The app mounts a root TooltipProvider (main.tsx); the strip's control// tooltips need that context, so the isolated render supplies its own.+ // `draggable` mirrors the standalone terminal window's prop shape (same+ // new-chat model, no dock/collapse controls); the default mirrors the dock.<TooltipProvider><TerminalTabStripsessions={props?.sessions ?? SESSIONS}@@ -38,9 +41,10 @@ function renderStrip(props?: {onNewChatPickCli={onNewChatPickCli}onNewChatPickTerminal={onNewChatPickTerminal}onClose={onClose}- dockPosition={props?.dockPosition ?? 'bottom'}- onToggleDock={onToggleDock}- onCollapse={onCollapse}+ dockPosition={props?.draggable ? undefined : (props?.dockPosition ?? 'bottom')}+ onToggleDock={props?.draggable ? undefined : onToggleDock}+ onCollapse={props?.draggable ? undefined : onCollapse}+ draggable={props?.draggable}/></TooltipProvider>,);@@ -244,4 +248,31 @@ describe('TerminalTabStrip', () => {expect(screen.getByRole('button', { name: `Close ${label}` })).toBeDefined();}});++ // The standalone terminal window is frameless (titleBarStyle:'hiddenInset'),+ // so its tab row doubles as the macOS title bar. The dock (default) must NOT —+ // it sits at the bottom of the editor, clear of the traffic lights.+ test('window mode marks the bar as the draggable macOS title region; dock mode does not', () => {+ renderStrip({ draggable: true });+ expect(document.querySelector('[data-electron-drag]')).not.toBeNull();+ // The window has no dock-toggle/collapse — window management is the OS+ // title bar's job — but keeps the full new-chat affordance (feature parity).+ expect(screen.queryByRole('button', { name: /Dock terminal/ })).toBeNull();+ expect(screen.queryByRole('button', { name: 'Collapse terminal' })).toBeNull();+ expect(screen.getByRole('button', { name: 'New Claude chat' })).toBeDefined();+ cleanup();+ renderStrip();+ expect(document.querySelector('[data-electron-drag]')).toBeNull();+ });++ test('window mode keeps the tab controls interactive (no-drag opt-out works)', async () => {+ const user = userEvent.setup();+ const { onNewChatLaunch, onClose } = renderStrip({ activeSessionId: 's1', draggable: true });++ await user.click(screen.getByRole('button', { name: 'New Claude chat' }));+ await user.click(screen.getByRole('button', { name: 'Close Terminal 1' }));++ expect(onNewChatLaunch).toHaveBeenCalledTimes(1);+ expect(onClose).toHaveBeenCalledWith('s1');+ });});diff --git a/packages/app/src/components/TerminalTabStrip.tsx b/packages/app/src/components/TerminalTabStrip.tsxindex 55bbadfeb..8b4d003fd 100644--- a/packages/app/src/components/TerminalTabStrip.tsx+++ b/packages/app/src/components/TerminalTabStrip.tsx@@ -48,12 +48,15 @@ interface TerminalTabStripProps {/** Fires with the session id when the user closes a tab. */readonly onClose: (id: string) => void;/** Where the terminal is currently docked — drives the dock-toggle + collapse- * button icons/labels. */- readonly dockPosition: TerminalDockPosition;- /** Fires when the user flips the dock between bottom and right. */- readonly onToggleDock: () => void;- /** Fires when the user collapses (hides) the terminal — sessions stay alive. */- readonly onCollapse: () => void;+ * button icons/labels. Absent on the standalone terminal window (nothing to+ * dock or collapse — the window is the terminal). */+ readonly dockPosition?: TerminalDockPosition;+ /** Fires when the user flips the dock between bottom and right. The toggle+ * button renders only when provided. */+ readonly onToggleDock?: () => void;+ /** Fires when the user collapses (hides) the terminal — sessions stay alive.+ * The collapse button renders only when provided. */+ readonly onCollapse?: () => void;/*** Tab panels, one per session. Rendered inside this component's `Tabs` root so* Radix can wire each trigger's `aria-controls` to its panel's `aria-labelledby`@@ -63,10 +66,20 @@ interface TerminalTabStripProps {*/readonly children?: ReactNode;readonly className?: string;+ /**+ * Standalone-terminal-window mode (macOS): the tab row doubles as the window+ * title bar. Tall enough (`h-[62px]`) to vertically center the tabs against the+ * traffic lights (taller than `EditorHeader`'s `h-12` — see the height note at+ * the row below), reserves the light footprint+ * (`--ok-titlebar-reserve-left`) so the first tab clears them, and makes the+ * empty bar area the `-webkit-app-region: drag` handle (controls opt out via+ * `no-drag`). The docked strip omits this (it sits at the editor's bottom).+ */+ readonly draggable?: boolean;}/**- * Controlled tab widget for the docked terminal's concurrent sessions. Holds no+ * Controlled tab widget for the terminal's concurrent sessions. Holds no* state of its own: the consumer owns the session list and active id and reacts* to the callbacks below (tab select/activate, new-chat launch/pick, close, dock,* collapse).@@ -85,6 +98,10 @@ interface TerminalTabStripProps {* the terminal (sessions stay alive). The consumer owns dock position +* visibility; this strip only fires the callbacks.*+ * The standalone terminal window is the second placement (via the session+ * host's window variant): it passes `draggable` (the row doubles as the macOS+ * title bar) and no dock/collapse handlers (the window is the terminal).+ ** The tablist is a thin bar; `children` (the consumer's tab panels) render below* it under the same `Tabs` root so the trigger↔panel a11y relationship resolves.*/@@ -103,6 +120,7 @@ export function TerminalTabStrip({onCollapse,children,className,+ draggable,}: TerminalTabStripProps) {const { t } = useLingui();const rightDocked = dockPosition === 'right';@@ -112,7 +130,31 @@ export function TerminalTabStrip({onValueChange={onSelect}className={cn('flex min-h-0 min-w-0 flex-1 flex-col', className)}>- <div className="flex shrink-0 flex-row items-center gap-1 px-1.5 py-1">+ <div+ // Window mode: this row is the macOS title bar — h-[62px] to center the+ // tabs against the traffic lights, traffic-light reserve so the first tab+ // clears them, and a drag handle on the empty area (controls opt out via+ // no-drag below). The dock omits all of this.+ data-electron-drag={draggable ? '' : undefined}+ className={cn(+ 'flex shrink-0 flex-row items-center gap-1 px-1.5 py-1',+ // h-[62px] centers the tab on the traffic-light row: the lights sit at+ // trafficLightPosition.y=24 with ~14px height (center ~y31), so an+ // items-center row must be ~62px tall (center 31) for the tab to line+ // up with the bubbles rather than floating above them.+ //+ // Left padding = the shared traffic-light reserve PLUS an extra 0.75rem:+ // the reserve (78px) is tuned for the editor's icon content, but a tab+ // is a background pill, so the bare reserve leaves its left edge touching+ // the green light. The extra gutter clears the bubbles cleanly.+ // pr-[22px] matches the traffic lights' own inset from the left edge+ // (trafficLightPosition.x=22) so the trailing "+" sits the same distance+ // from the right edge as the bubbles are from the left — a consistent+ // window gutter.+ draggable &&+ 'h-[62px] [-webkit-app-region:drag] pr-[22px] pl-[calc(var(--ok-titlebar-reserve-left,1rem)+0.75rem)]',+ )}+ ><TabsListvariant="line"aria-label={t`Terminal sessions`}@@ -143,7 +185,10 @@ export function TerminalTabStrip({// terminal on a deliberate select without stealing focus while// the user arrows across tabs.onClick={() => onTabActivate?.(session.id)}- className="h-7 flex-none rounded-md px-2 text-xs"+ className={cn(+ 'h-7 flex-none rounded-md px-2 text-xs',+ draggable && '[-webkit-app-region:no-drag]',+ )}><span className="max-w-40 truncate">{session.label}</span></TabsTrigger>@@ -169,6 +214,7 @@ export function TerminalTabStrip({className={cn('text-muted-foreground opacity-0 transition-opacity hover:text-foreground group-hover:opacity-100 group-focus-within:opacity-100',isActive && 'opacity-100',+ draggable && '[-webkit-app-region:no-drag]',)}onClick={(event) => {event.stopPropagation();@@ -189,62 +235,66 @@ export function TerminalTabStrip({onLaunchSelected={onNewChatLaunch}onPickCli={onNewChatPickCli}onPickTerminal={onNewChatPickTerminal}- className="shrink-0"+ className={cn('shrink-0', draggable && '[-webkit-app-region:no-drag]')}/>{/* Spacer pushes the trailing controls to the far right. */}<div className="flex-1" />- <Tooltip>- <TooltipTrigger asChild>- <Button- type="button"- variant="ghost"- size="icon-xs"- // Label names the resulting position, not the current one, so the- // action reads as "move it there" to a screen-reader user.- aria-label={- rightDocked ? t`Dock terminal to the bottom` : t`Dock terminal to the right`- }- className="shrink-0 cursor-pointer text-muted-foreground hover:text-foreground"- onClick={onToggleDock}- >- {rightDocked ? (- <PanelBottomIcon aria-hidden="true" />- ) : (- <PanelRightIcon aria-hidden="true" />- )}- </Button>- </TooltipTrigger>- <TooltipContent side="bottom" sideOffset={8}>- {rightDocked ? (- <Trans>Dock terminal to the bottom</Trans>- ) : (- <Trans>Dock terminal to the right</Trans>- )}- </TooltipContent>- </Tooltip>- <Tooltip>- <TooltipTrigger asChild>- <Button- type="button"- variant="ghost"- size="icon-xs"- aria-label={t`Collapse terminal`}- className="shrink-0 cursor-pointer text-muted-foreground hover:text-foreground"- onClick={onCollapse}- >- {/* Chevron points the way the panel slides shut: down for the bottom- dock, right for the right column. */}+ {onToggleDock != null ? (+ <Tooltip>+ <TooltipTrigger asChild>+ <Button+ type="button"+ variant="ghost"+ size="icon-xs"+ // Label names the resulting position, not the current one, so the+ // action reads as "move it there" to a screen-reader user.+ aria-label={+ rightDocked ? t`Dock terminal to the bottom` : t`Dock terminal to the right`+ }+ className="shrink-0 cursor-pointer text-muted-foreground hover:text-foreground"+ onClick={onToggleDock}+ >+ {rightDocked ? (+ <PanelBottomIcon aria-hidden="true" />+ ) : (+ <PanelRightIcon aria-hidden="true" />+ )}+ </Button>+ </TooltipTrigger>+ <TooltipContent side="bottom" sideOffset={8}>{rightDocked ? (- <ChevronRightIcon aria-hidden="true" />+ <Trans>Dock terminal to the bottom</Trans>) : (- <ChevronDownIcon aria-hidden="true" />+ <Trans>Dock terminal to the right</Trans>)}- </Button>- </TooltipTrigger>- <TooltipContent side="bottom" sideOffset={8}>- <Trans>Collapse terminal</Trans>- </TooltipContent>- </Tooltip>+ </TooltipContent>+ </Tooltip>+ ) : null}+ {onCollapse != null ? (+ <Tooltip>+ <TooltipTrigger asChild>+ <Button+ type="button"+ variant="ghost"+ size="icon-xs"+ aria-label={t`Collapse terminal`}+ className="shrink-0 cursor-pointer text-muted-foreground hover:text-foreground"+ onClick={onCollapse}+ >+ {/* Chevron points the way the panel slides shut: down for the bottom+ dock, right for the right column. */}+ {rightDocked ? (+ <ChevronRightIcon aria-hidden="true" />+ ) : (+ <ChevronDownIcon aria-hidden="true" />+ )}+ </Button>+ </TooltipTrigger>+ <TooltipContent side="bottom" sideOffset={8}>+ <Trans>Collapse terminal</Trans>+ </TooltipContent>+ </Tooltip>+ ) : null}</div>{children}</Tabs>diff --git a/packages/app/src/components/TerminalWindowApp.config-provider.dom.test.tsx b/packages/app/src/components/TerminalWindowApp.config-provider.dom.test.tsxnew file mode 100644index 000000000..da6c8c1fb--- /dev/null+++ b/packages/app/src/components/TerminalWindowApp.config-provider.dom.test.tsx@@ -0,0 +1,69 @@+/**+ * The standalone terminal window must establish its own ConfigProvider: the+ * terminal-consent hooks under TerminalGate (`useTerminalConsentState` /+ * `useTerminalEnabledWriter` → `useConfigContext`) read the project-local+ * ConfigBinding, and this window has no editor/document tree to inherit the+ * provider from. Without it `useConfigContext` throws "must be used within+ * <ConfigProvider />", blanking the whole React root and leaving the window empty.+ *+ * Unlike the sibling behavioral test, TerminalGate is stubbed with a component+ * that ACTUALLY consumes `useConfigContext` — the same context the real consent+ * hooks read — so the test exercises the missing-provider crash. With the+ * provider wrapping removed, this render throws; with it, the child mounts.+ */++import { afterEach, describe, expect, mock, test } from 'bun:test';+import { cleanup, render, screen } from '@testing-library/react';+import { TooltipProvider } from '@/components/ui/tooltip';+import { useConfigContext } from '@/lib/config-provider';+import type { OkDesktopBridge } from '@/lib/desktop-bridge-types';++// Stand in for the real TerminalGate: read the same context the terminal-consent+// hooks read. Throws (and blanks the root) if no ConfigProvider is above it.+mock.module('./TerminalGate', () => ({+ TerminalGate: () => {+ const { projectLocalSynced } = useConfigContext();+ return (+ <span data-testid="config-consumer" data-synced={projectLocalSynced ? 'true' : 'false'} />+ );+ },+}));++const { TerminalWindowApp } = await import('./TerminalWindowApp');++function bridgeWithCollabUrl(collabUrl: string): OkDesktopBridge {+ return {+ config: { mode: 'terminal', collabUrl },+ onMenuAction: () => () => {},+ editor: { notifyViewMenuStateChanged: () => {} },+ terminal: { create: async () => ({ ok: true, ptyId: 'pty-1' }), kill: async () => {} },+ } as unknown as OkDesktopBridge;+}++describe('TerminalWindowApp ConfigProvider wiring', () => {+ afterEach(() => {+ cleanup();+ });++ test('provides ConfigProvider context to its terminal subtree (project-less / empty collabUrl)', () => {+ // Empty collabUrl is the project-less terminal window. The consent hooks+ // must fail-open: the context resolves (no throw) with an unsynced binding.+ render(+ <TooltipProvider>+ <TerminalWindowApp bridge={bridgeWithCollabUrl('')} />+ </TooltipProvider>,+ );+ const consumer = screen.getByTestId('config-consumer');+ expect(consumer).toBeTruthy();+ expect(consumer.getAttribute('data-synced')).toBe('false');+ });++ test('provides ConfigProvider context for a project-bound terminal window', () => {+ render(+ <TooltipProvider>+ <TerminalWindowApp bridge={bridgeWithCollabUrl('ws://localhost:5200/collab')} />+ </TooltipProvider>,+ );+ expect(screen.getByTestId('config-consumer')).toBeTruthy();+ });+});diff --git a/packages/app/src/components/TerminalWindowApp.dom.test.tsx b/packages/app/src/components/TerminalWindowApp.dom.test.tsxnew file mode 100644index 000000000..0c16d9469--- /dev/null+++ b/packages/app/src/components/TerminalWindowApp.dom.test.tsx@@ -0,0 +1,326 @@+/**+ * Behavioral tests for the standalone terminal window surface + the renderer+ * mode routing that selects it.+ *+ * TerminalGate (the heavy consent + xterm session) is stubbed with a session+ * stand-in that spawns a PTY on mount and reaps it on unmount — the same+ * pattern as TerminalDock.dom.test.tsx — so the assertions pin what the window+ * owns: one shell on mount, the new-tab affordance, ⌘1–9 switching with no+ * scope gate, and close-last → window.close(). The window mounts the shared+ * TerminalSessionsHost (window variant), so the session model — including the+ * New-chat split button — is the dock's. The sibling root surfaces are+ * stubbed so the routing helper resolves without pulling the editor / navigator+ * trees.+ */++import { afterEach, beforeEach, describe, expect, mock, spyOn, test } from 'bun:test';+import { act, cleanup, render, screen } from '@testing-library/react';+import userEvent from '@testing-library/user-event';+import { useEffect, useRef } from 'react';+import { TooltipProvider } from '@/components/ui/tooltip';+import type { OkDesktopBridge } from '@/lib/desktop-bridge-types';++mock.module('./TerminalGate', () => ({+ // biome-ignore lint/suspicious/noExplicitAny: test stub+ TerminalGate: ({ bridge }: any) => {+ const ptyIdRef = useRef<string | null>(null);+ const cancelledRef = useRef(false);+ useEffect(() => {+ cancelledRef.current = false;+ void Promise.resolve(bridge?.terminal?.create?.({ cols: 80, rows: 24 })).then(+ (result: { ok?: boolean; ptyId?: string } | undefined) => {+ if (!result?.ok || result.ptyId == null) return;+ if (cancelledRef.current) bridge?.terminal?.kill?.(result.ptyId);+ else ptyIdRef.current = result.ptyId;+ },+ );+ return () => {+ cancelledRef.current = true;+ if (ptyIdRef.current != null) bridge?.terminal?.kill?.(ptyIdRef.current);+ };+ }, [bridge]);+ return <span data-testid="terminal-session" className="xterm-helper-textarea" tabIndex={-1} />;+ },+}));++mock.module('@/App', () => ({ App: () => <div data-testid="editor-app" /> }));+mock.module('@/components/NavigatorApp', () => ({+ NavigatorApp: () => <div data-testid="navigator-app" />,+}));++const { TerminalWindowApp } = await import('./TerminalWindowApp');+const { selectDesktopRootApp } = await import('./desktop-root-app');++function makeBridge() {+ const menuHandlers: Array<(action: string) => void> = [];+ const viewMenuPushes: Array<{ terminalLive?: boolean }> = [];+ let ptyCounter = 0;+ const create = mock(async () => {+ ptyCounter += 1;+ return { ok: true as const, ptyId: `pty-${ptyCounter}` };+ });+ const kill = mock(async (_id: string) => {});+ const bridge = {+ config: { mode: 'terminal' },+ onMenuAction(cb: (action: string) => void) {+ menuHandlers.push(cb);+ return () => {+ const index = menuHandlers.indexOf(cb);+ if (index >= 0) menuHandlers.splice(index, 1);+ };+ },+ editor: {+ notifyViewMenuStateChanged(state: { terminalLive?: boolean }) {+ viewMenuPushes.push(state);+ },+ },+ terminal: { create, kill },+ } as unknown as OkDesktopBridge;+ return {+ bridge,+ create,+ kill,+ viewMenuPushes,+ dispatchMenuAction(action: string) {+ for (const cb of menuHandlers) cb(action);+ },+ };+}++function bridgeWithMode(mode: string): OkDesktopBridge {+ return { config: { mode } } as unknown as OkDesktopBridge;+}++// Adds a plain-shell tab via the New-chat split button's "Terminal" option —+// the same affordance the dock has (the window holds feature parity; only the+// placement differs).+async function addTerminalTab(user: ReturnType<typeof userEvent.setup>) {+ await user.click(screen.getByRole('button', { name: 'Choose CLI for new chat' }));+ await user.click(await screen.findByRole('menuitem', { name: 'Terminal' }));+}++function sessionPanels(): HTMLElement[] {+ return Array.from(document.querySelectorAll<HTMLElement>('[data-terminal-session]'));+}++function activePanelId(): string | null {+ return (+ document+ .querySelector<HTMLElement>('[data-terminal-session][data-state="active"]')+ ?.getAttribute('data-terminal-session') ?? null+ );+}++describe('TerminalWindowApp', () => {+ afterEach(() => {+ cleanup();+ });++ test('opens with exactly one shell tab on mount', () => {+ const { bridge, create } = makeBridge();+ render(+ <TooltipProvider>+ <TerminalWindowApp bridge={bridge} />+ </TooltipProvider>,+ );+ expect(screen.getAllByTestId('terminal-session')).toHaveLength(1);+ expect(create).toHaveBeenCalledTimes(1);+ });++ test('the new-chat control opens an additional independent tab', async () => {+ const user = userEvent.setup();+ const { bridge, create } = makeBridge();+ render(+ <TooltipProvider>+ <TerminalWindowApp bridge={bridge} />+ </TooltipProvider>,+ );++ await addTerminalTab(user);++ expect(screen.getAllByTestId('terminal-session')).toHaveLength(2);+ expect(create).toHaveBeenCalledTimes(2);+ });++ test('Cmd+number switches tabs with no focus-scope gate (the whole window is the terminal)', async () => {+ const user = userEvent.setup();+ const { bridge } = makeBridge();+ render(+ <TooltipProvider>+ <TerminalWindowApp bridge={bridge} />+ </TooltipProvider>,+ );+ await addTerminalTab(user);+ // Deliberately do NOT focus inside a terminal panel: unlike the dock, the+ // window has no scope gate, so the chord works regardless of focus.+ const event = new KeyboardEvent('keydown', {+ key: '1',+ metaKey: true,+ cancelable: true,+ bubbles: true,+ });+ act(() => {+ window.dispatchEvent(event);+ });++ expect(event.defaultPrevented).toBe(true);+ expect(screen.getByRole('tab', { name: 'Terminal 1' }).getAttribute('aria-selected')).toBe(+ 'true',+ );+ expect(activePanelId()).toBe(sessionPanels()[0]?.getAttribute('data-terminal-session'));+ });++ test('Cmd+number with a co-modifier (Ctrl) falls through to the shell, not a tab switch', async () => {+ const user = userEvent.setup();+ const { bridge } = makeBridge();+ render(+ <TooltipProvider>+ <TerminalWindowApp bridge={bridge} />+ </TooltipProvider>,+ );+ await addTerminalTab(user);+ const activeBefore = activePanelId();++ // Ctrl+Cmd+1 (and other co-modified chords) belong to the running program,+ // not the tab strip — the switch handler must ignore them entirely so the+ // keystroke reaches the shell.+ const event = new KeyboardEvent('keydown', {+ key: '1',+ metaKey: true,+ ctrlKey: true,+ cancelable: true,+ bubbles: true,+ });+ act(() => {+ window.dispatchEvent(event);+ });++ expect(event.defaultPrevented).toBe(false);+ expect(activePanelId()).toBe(activeBefore);+ });++ test('closing the last tab closes the window instead of leaving an empty surface', async () => {+ const user = userEvent.setup();+ const closeSpy = spyOn(window, 'close').mockImplementation(() => {});+ try {+ const { bridge } = makeBridge();+ render(+ <TooltipProvider>+ <TerminalWindowApp bridge={bridge} />+ </TooltipProvider>,+ );+ expect(screen.getAllByTestId('terminal-session')).toHaveLength(1);++ await user.click(screen.getByRole('button', { name: 'Close Terminal 1' }));++ expect(screen.queryAllByTestId('terminal-session')).toHaveLength(0);+ expect(closeSpy).toHaveBeenCalledTimes(1);+ } finally {+ closeSpy.mockRestore();+ }+ });++ test('the Terminal menu "New Terminal" action opens an additional tab in the focused window', () => {+ const view = makeBridge();+ render(+ <TooltipProvider>+ <TerminalWindowApp bridge={view.bridge} />+ </TooltipProvider>,+ );+ expect(screen.getAllByTestId('terminal-session')).toHaveLength(1);++ act(() => view.dispatchMenuAction('new-terminal'));++ // The window handles the menu action itself — without the onMenuAction+ // wiring the action is delivered to a renderer with no listener and is inert.+ expect(screen.getAllByTestId('terminal-session')).toHaveLength(2);+ expect(view.create).toHaveBeenCalledTimes(2);+ });++ test('the Terminal menu "Kill Terminal" action closes the active tab in the focused window', async () => {+ const user = userEvent.setup();+ const view = makeBridge();+ render(+ <TooltipProvider>+ <TerminalWindowApp bridge={view.bridge} />+ </TooltipProvider>,+ );+ await addTerminalTab(user);+ expect(screen.getAllByTestId('terminal-session')).toHaveLength(2);++ act(() => view.dispatchMenuAction('kill-terminal'));++ expect(screen.getAllByTestId('terminal-session')).toHaveLength(1);+ });++ test('⌘W (close-active-tab-or-window) closes the active tab; the last tab closes the window', async () => {+ const user = userEvent.setup();+ const closeSpy = spyOn(window, 'close').mockImplementation(() => {});+ try {+ const view = makeBridge();+ render(+ <TooltipProvider>+ <TerminalWindowApp bridge={view.bridge} />+ </TooltipProvider>,+ );+ await addTerminalTab(user);+ expect(screen.getAllByTestId('terminal-session')).toHaveLength(2);++ // ⌘W closes the innermost unit first: the active tab.+ act(() => view.dispatchMenuAction('close-active-tab-or-window'));+ expect(screen.getAllByTestId('terminal-session')).toHaveLength(1);+ expect(closeSpy).not.toHaveBeenCalled();++ // With one tab left, ⌘W cascades to closing the window itself.+ act(() => view.dispatchMenuAction('close-active-tab-or-window'));+ expect(screen.queryAllByTestId('terminal-session')).toHaveLength(0);+ expect(closeSpy).toHaveBeenCalledTimes(1);+ } finally {+ closeSpy.mockRestore();+ }+ });++ test('reports terminal liveness to main so "Kill Terminal" enables while the window is focused', () => {+ const view = makeBridge();+ render(+ <TooltipProvider>+ <TerminalWindowApp bridge={view.bridge} />+ </TooltipProvider>,+ );+ // The window opens with one shell, so the menu must read its liveness from+ // the focused window rather than a stale editor-dock singleton.+ expect(view.viewMenuPushes.at(-1)).toEqual({ terminalLive: true });+ });+});++describe('selectDesktopRootApp routing', () => {+ beforeEach(() => {+ cleanup();+ });+ afterEach(() => {+ cleanup();+ });++ test('mode=terminal selects the terminal window app', () => {+ expect(selectDesktopRootApp(bridgeWithMode('terminal')).type).toBe(TerminalWindowApp);+ });++ test('mounting the terminal-mode selection renders the full-window terminal', () => {+ const { bridge } = makeBridge();+ render(<TooltipProvider>{selectDesktopRootApp(bridge)}</TooltipProvider>);+ expect(screen.getByRole('tablist', { name: 'Terminal sessions' })).toBeTruthy();+ expect(screen.getAllByTestId('terminal-session')).toHaveLength(1);+ });++ test('mode=navigator does not select the terminal window app', () => {+ expect(selectDesktopRootApp(bridgeWithMode('navigator')).type).not.toBe(TerminalWindowApp);+ });++ test('mode=editor does not select the terminal window app', () => {+ expect(selectDesktopRootApp(bridgeWithMode('editor')).type).not.toBe(TerminalWindowApp);+ });++ test('no bridge (web / CLI) does not select the terminal window app', () => {+ expect(selectDesktopRootApp(undefined).type).not.toBe(TerminalWindowApp);+ });+});diff --git a/packages/app/src/components/TerminalWindowApp.tsx b/packages/app/src/components/TerminalWindowApp.tsxnew file mode 100644index 000000000..37359a87a--- /dev/null+++ b/packages/app/src/components/TerminalWindowApp.tsx@@ -0,0 +1,77 @@+import { useTheme } from 'next-themes';+import { useState } from 'react';+import { useInstalledClis } from '@/hooks/use-installed-clis';+import { ConfigProvider } from '@/lib/config-provider';+import type { OkDesktopBridge } from '@/lib/desktop-bridge-types';+import { TerminalSessionsHost } from './TerminalSessionsHost';+import { xtermThemeForMode } from './terminal-theme';++interface TerminalWindowAppProps {+ /** Desktop bridge — the terminal window renders only on the Electron host. */+ readonly bridge: OkDesktopBridge;+}++/**+ * Full-window multi-session terminal — the renderer for a `--ok-mode=terminal`+ * window. Mounts the SAME {@link TerminalSessionsHost} the docked terminal uses+ * (window variant), so the window is purely a placement: new-chat split button,+ * OSC tab titles, menu actions, ⌘1–9, liveness reporting, and reload+ * rehydration are the dock's, by construction. The window-shaped differences+ * live in the host's `variant: 'window'`: closing the last tab closes the+ * window instead of collapsing a panel, the tab row doubles as the macOS title+ * bar, there are no dock/collapse controls, and ⌘1–9 needs no focus-scope gate.+ *+ * Establishes its own {@link ConfigProvider} — the terminal-consent hooks under+ * TerminalGate (`useTerminalConsentState` / `useTerminalEnabledWriter`) read+ * the project-local ConfigBinding via `useConfigContext`, and this window has+ * no editor/document tree to inherit the provider from (unlike `App.tsx`).+ * The collab URL is the project's, surfaced through the bridge (attach-mode).+ * A project-less terminal window carries an empty `collabUrl`; normalize it to+ * `null` so `ConfigProvider` skips binding creation and the consent hooks+ * fail-open (terminal allowed unless `terminal.enabled: false`).+ */+export function TerminalWindowApp({ bridge }: TerminalWindowAppProps) {+ const collabUrl = bridge.config.collabUrl ? bridge.config.collabUrl : null;+ return (+ <ConfigProvider collabUrl={collabUrl}>+ <TerminalWindowBody bridge={bridge} />+ </ConfigProvider>+ );+}++function TerminalWindowBody({ bridge }: TerminalWindowAppProps) {+ const { resolvedTheme } = useTheme();+ const installedClis = useInstalledClis();+ // The host portals its session subtree into this container (a callback-ref+ // state so the host re-renders once the div mounts).+ const [container, setContainer] = useState<HTMLDivElement | null>(null);++ return (+ <>+ {/* Paint the full window with the xterm canvas color so the tab strip and+ canvas read as one continuous surface (mirrors the dock). */}+ <div+ ref={setContainer}+ className="flex h-screen min-h-0 flex-col"+ style={{ backgroundColor: xtermThemeForMode(resolvedTheme).background }}+ />+ <TerminalSessionsHost+ bridge={bridge}+ variant="window"+ // The window is its own always-on terminal surface: visibility never+ // toggles, and the host's close-last "hide" report means the surface is+ // done — close the window (the dock collapses a panel instead).+ visible+ onVisibleChange={(nextVisible) => {+ if (!nextVisible) window.close();+ }}+ installedClis={installedClis}+ container={container}+ isShowing+ // No editor to return focus to — the window IS the terminal, and after+ // close-last it is closing anyway.+ onRequestEditorFocus={() => {}}+ />+ </>+ );+}diff --git a/packages/app/src/components/desktop-root-app.tsx b/packages/app/src/components/desktop-root-app.tsxnew file mode 100644index 000000000..cfb8a88e9--- /dev/null+++ b/packages/app/src/components/desktop-root-app.tsx@@ -0,0 +1,17 @@+import type { ReactElement } from 'react';+import { App } from '@/App';+import { NavigatorApp } from '@/components/NavigatorApp';+import { TerminalWindowApp } from '@/components/TerminalWindowApp';+import type { OkDesktopBridge } from '@/lib/desktop-bridge-types';++/**+ * Pick the root surface for the current window from the desktop bridge's mode.+ * `terminal` and `navigator` are dedicated Electron window types; everything+ * else — editor windows, and the web / CLI distribution where `bridge` is+ * undefined — renders the full editor shell.+ */+export function selectDesktopRootApp(bridge: OkDesktopBridge | undefined): ReactElement {+ if (bridge?.config.mode === 'terminal') return <TerminalWindowApp bridge={bridge} />;+ if (bridge?.config.mode === 'navigator') return <NavigatorApp bridge={bridge} />;+ return <App />;+}diff --git a/packages/app/src/lib/desktop-bridge-types.ts b/packages/app/src/lib/desktop-bridge-types.tsindex 8c0f42f37..22ebe7f9d 100644--- a/packages/app/src/lib/desktop-bridge-types.ts+++ b/packages/app/src/lib/desktop-bridge-types.ts@@ -135,7 +135,7 @@ export interface OkFindEnclosingGitRootResult {readonly distance: number;}-type OkDesktopMode = 'editor' | 'navigator';+type OkDesktopMode = 'editor' | 'navigator' | 'terminal';export interface OkDesktopConfig {readonly collabUrl: string;diff --git a/packages/app/src/main.tsx b/packages/app/src/main.tsxindex 267adc277..96d71f4be 100644--- a/packages/app/src/main.tsx+++ b/packages/app/src/main.tsx@@ -25,7 +25,7 @@ import { QueryClient, QueryClientProvider } from '@tanstack/react-query';import { ThemeProvider } from 'next-themes';import { StrictMode } from 'react';import { createRoot } from 'react-dom/client';-import { NavigatorApp } from '@/components/NavigatorApp';+import { selectDesktopRootApp } from '@/components/desktop-root-app';import { Toaster } from '@/components/ui/sonner';import { TooltipProvider } from '@/components/ui/tooltip';// Side-effect import to load the `Window.okDesktop?` global augmentation.@@ -50,7 +50,6 @@ import { installShareReceivedListener } from '@/lib/share/receive-store';import { seedInitialDocHashFromWindow } from '@/lib/single-file-initial-doc';import { installSubscribeCardStore } from '@/lib/subscribe-card-store';import { installUpdateNoticesBridge } from '@/lib/update-notices-store';-import { App } from './App';import '@fontsource-variable/inter';import '@fontsource-variable/jetbrains-mono';// react-medium-image-zoom ships structural CSS (modal positioning, dialog@@ -192,11 +191,12 @@ const queryClient = new QueryClient({const root = document.getElementById('root');if (!root) throw new Error('Root element not found');-// Electron Navigator-mode branch: when the desktop preload has-// flagged `mode: 'navigator'`, render the lightweight launcher UI instead of-// the full editor shell. CLI / web distribution: window.okDesktop is undefined,-// so this is always the editor (`App`) path.-const isNavigator = typeof window !== 'undefined' && window.okDesktop?.config.mode === 'navigator';+// Electron window-mode branch: the desktop preload flags `mode` per window so+// the renderer mounts the matching surface — `terminal` → the standalone+// terminal window, `navigator` → the launcher, everything else → the editor+// shell. CLI / web distribution: window.okDesktop is undefined, so this is+// always the editor (`App`) path.+const desktopBridge = typeof window === 'undefined' ? undefined : window.okDesktop;createRoot(root).render(<StrictMode>@@ -209,9 +209,7 @@ createRoot(root).render(disableTransitionOnChangestorageKey="ok-theme-v1">- <TooltipProvider>- {isNavigator && window.okDesktop ? <NavigatorApp bridge={window.okDesktop} /> : <App />}- </TooltipProvider>+ <TooltipProvider>{selectDesktopRootApp(desktopBridge)}</TooltipProvider>{/** Sonner toaster for ad-hoc status/error toasts (clone dialog, file* tree, etc.). Auto-update notices are NOT routed here — they livediff --git a/packages/core/src/desktop-bridge.ts b/packages/core/src/desktop-bridge.tsindex 3b9376190..63cd19916 100644--- a/packages/core/src/desktop-bridge.ts+++ b/packages/core/src/desktop-bridge.ts@@ -26,7 +26,7 @@ import type {import type { RecentProjectEntry } from './sharing/index.ts';/** Render mode picked by the main process when creating a BrowserWindow. */-type OkDesktopMode = 'editor' | 'navigator';+type OkDesktopMode = 'editor' | 'navigator' | 'terminal';/*** Config values injected at preload-exposure time. A frozen snapshot, not a@@ -44,7 +44,7 @@ interface OkDesktopConfig {readonly projectPath: string;/** Display name for the project (usually basename of projectPath). */readonly projectName: string;- /** Render mode — `navigator` renders the Project Navigator, `editor` renders the doc editor. */+ /** Render mode — `navigator` renders the Project Navigator, `editor` renders the doc editor, `terminal` renders the standalone terminal window. */readonly mode: OkDesktopMode;}diff --git a/packages/desktop/src/main/index.ts b/packages/desktop/src/main/index.tsindex 5eab3c310..bfcfe9297 100644--- a/packages/desktop/src/main/index.ts+++ b/packages/desktop/src/main/index.ts@@ -277,7 +277,14 @@ import {recordConcurrentSessions,recordShellExit,recordTerminalSession,+ recordTerminalWindowOpened,} from './terminal-telemetry.ts';+import {+ createTerminalWindow,+ resolveTerminalWindowProject,+ type TerminalBrowserWindow,+} from './terminal-window.ts';+import { getTerminalWindowContext, resolvePtyProjectRoot } from './terminal-window-registry.ts';import { applyThemeApplied } from './theme-applied-handler.ts';import { applyThemeSource, isOkThemeSource } from './theme-handler.ts';import {@@ -2059,6 +2066,7 @@ async function runApplicationMenuRefresh(): Promise<void> {onToggleTerminal: () => sendMenuActionToFocused('toggle-terminal'),onNewTerminal: () => sendMenuActionToFocused('new-terminal'),onKillTerminal: () => sendMenuActionToFocused('kill-terminal'),+ onNewTerminalWindow: () => openTerminalWindow(),onExpandAll: () => sendMenuActionToFocused('expand-all-tree'),onCollapseAll: () => sendMenuActionToFocused('collapse-all-tree'),// Edit -> "Check Spelling While Typing": the checkbox reflects the@@ -2084,6 +2092,57 @@ function sendMenuActionToFocused(action: OkMenuAction): void {sendToRenderer(target.webContents, 'ok:menu-action', action);}+/**+ * Terminal → "New Terminal Window": open a dedicated terminal window inheriting+ * the focused window's project (the editor window's `windowsByPath` context, or+ * a focused terminal window's registry context for chaining; project-less from+ * the Navigator or with no focused project). Opens directly in main — like+ * `openNavigator` — rather than round-tripping the renderer.+ */+function openTerminalWindow(): void {+ if (terminalReaper == null) return; // PTY manager not yet wired (pre-boot) — unreachable from a menu click.+ const focused = BrowserWindow.getFocusedWindow();+ const editorCtx =+ focused && wm ? wm.getContextForBrowserWindow(focused as unknown as BrowserWindowLike) : null;+ const project = resolveTerminalWindowProject({+ editor: editorCtx ?? null,+ terminal: focused ? getTerminalWindowContext(focused.id) : undefined,+ });+ const rendererEntryPath = app.isPackaged+ ? join(process.resourcesPath, 'app', 'index.html')+ : join(__dirname, '../renderer/index.html');+ createTerminalWindow({+ createWindow: (opts) => {+ const win = new BrowserWindow({+ ...DEFAULT_WIN_OPTS,+ minWidth: WINDOW_MIN_SIZE.EDITOR.width,+ minHeight: WINDOW_MIN_SIZE.EDITOR.height,+ title: opts.title,+ webPreferences: {+ ...DEFAULT_WIN_OPTS.webPreferences,+ additionalArguments: withDebugFlagIfAllowed(opts.additionalArguments),+ preload: join(__dirname, '../preload/index.js'),+ },+ });+ // Keep our per-window title against the renderer's static <title> (same as+ // editor windows). The per-window PTY reap is wired by the factory.+ win.on('page-title-updated', (e) => {+ e.preventDefault();+ });+ applyCascadePosition(win);+ attachSpellcheckMenuToWindow(win);+ return win as unknown as TerminalBrowserWindow;+ },+ rendererEntryPath,+ rendererDevUrl,+ appVersion: app.getVersion(),+ showGate,+ terminalReaper,+ project,+ });+ recordTerminalWindowOpened();+}+/*** Arm first-launch MCP consent. Extracted as a helper so both the* `app.whenReady()` path (once-per-boot marker-respecting) AND the@@ -2495,12 +2554,21 @@ function registerIpcHandlers() {handle('ok:pty:create', async (event, opts) => {const win = BrowserWindow.fromWebContents(event.sender);- const ctx =+ const editorCtx =win && wm ? wm.getContextForBrowserWindow(win as unknown as BrowserWindowLike) : null;- const projectPath = ctx?.projectPath ?? null;- // A window with no resolved ProjectContext (e.g. the Navigator) has no- // cwd to anchor a shell in — refuse rather than spawn at an arbitrary dir.- if (!win || !wm || !projectPath) {+ // A standalone terminal window is not in `windowsByPath` (one-per-project,+ // focus-existing), so `getContextForBrowserWindow` returns nothing for it.+ // Editor windows keep their existing per-project resolution; a terminal+ // window resolves its cwd from the windowId-keyed terminalWindows registry,+ // falling back to homedir() when project-less (never null — create() refuses+ // null). A window in neither map (e.g. the Navigator) resolves to null and+ // is refused below rather than spawning a shell at an arbitrary dir.+ const projectPath = resolvePtyProjectRoot({+ editorProjectPath: editorCtx?.projectPath ?? null,+ terminalWindow: win ? getTerminalWindowContext(win.id) : undefined,+ homedir: osHomedir(),+ });+ if (!win || !projectPath) {logIpcError({event: 'ipc.error',channel: 'ok:pty:create',diff --git a/packages/desktop/src/main/menu.ts b/packages/desktop/src/main/menu.tsindex 467425f51..2cd6646bd 100644--- a/packages/desktop/src/main/menu.ts+++ b/packages/desktop/src/main/menu.ts@@ -247,6 +247,13 @@ export interface MenuDeps {*/onNewTerminal?(): void;onKillTerminal?(): void;+ /**+ * Opens a new dedicated terminal WINDOW (distinct from `onNewTerminal`, which+ * opens a tab in the docked panel). Main resolves the focused window's project+ * and opens the window directly — no renderer round-trip. Optional for the+ * deps-unwired unit-test contexts.+ */+ onNewTerminalWindow?(): void;/*** Whether a terminal session is live (mounted). Gates "Kill Terminal" — a* collapsed-but-alive terminal still counts as live, so this tracks the dock@@ -657,6 +664,14 @@ export function buildMenuTemplate(deps: MenuDeps): MenuItemConstructorOptions[]enabled: deps.onNewTerminal !== undefined,click: () => deps.onNewTerminal?.(),},+ {+ // Opens a dedicated terminal window (1:1 with VS Code's "New Terminal+ // Window"). No accelerator — VS Code ships the command unbound, and+ // ⌘J stays the docked Show/Hide Terminal toggle.+ label: 'New Terminal Window',+ enabled: deps.onNewTerminalWindow !== undefined,+ click: () => deps.onNewTerminalWindow?.(),+ },{// Closes the active tab — kills its shell (not just hide). Enabled// only when at least one session is live; a collapsed-but-alivediff --git a/packages/desktop/src/main/show-gate.ts b/packages/desktop/src/main/show-gate.tsindex 60c8cebda..d844f33f3 100644--- a/packages/desktop/src/main/show-gate.ts+++ b/packages/desktop/src/main/show-gate.ts@@ -71,7 +71,7 @@ export interface ShowGateRegistry {* window destroyed before either signal arrives doesn't hold stale state.** @param window - The window to register.- * @param opts.kind - Kind of window for diagnostic warns. 'editor' or 'navigator'.+ * @param opts.kind - Kind of window for diagnostic warns. 'editor', 'navigator', or 'terminal'.*/register(window: BrowserWindowLike, opts?: { kind?: WindowKind }): () => void;/**@@ -83,7 +83,7 @@ export interface ShowGateRegistry {fireThemeApplied(window: BrowserWindowLike): void;}-type WindowKind = 'editor' | 'navigator';+type WindowKind = 'editor' | 'navigator' | 'terminal';interface PerWindowGateState {readyToShow: boolean;diff --git a/packages/desktop/tests/main/terminal-telemetry.test.ts b/packages/desktop/src/main/terminal-telemetry.test.tssimilarity index 83%rename from packages/desktop/tests/main/terminal-telemetry.test.tsrename to packages/desktop/src/main/terminal-telemetry.test.tsindex b514a0088..0c7b40ac7 100644--- a/packages/desktop/tests/main/terminal-telemetry.test.ts+++ b/packages/desktop/src/main/terminal-telemetry.test.ts@@ -26,9 +26,12 @@ mock.module('@inkeep/open-knowledge-server', () => ({},}));-const { recordConcurrentSessions, recordShellExit, recordTerminalSession } = await import(- '../../src/main/terminal-telemetry.ts'-);+const {+ recordConcurrentSessions,+ recordShellExit,+ recordTerminalSession,+ recordTerminalWindowOpened,+} = await import('../../src/main/terminal-telemetry.ts');describe('recordShellExit — span name + crashed attribute', () => {beforeEach(() => {@@ -86,3 +89,16 @@ describe('recordConcurrentSessions — count-only concurrency signal', () => {expect(Object.keys(attrs)).toEqual(['ok.desktop.concurrent_sessions']);});});++describe('recordTerminalWindowOpened — count-only adoption marker', () => {+ beforeEach(() => {+ capturedCalls.length = 0;+ });++ test('emits ok.desktop.terminalWindowOpened with no attributes (the span is the count)', () => {+ recordTerminalWindowOpened();+ expect(capturedCalls).toHaveLength(1);+ expect(capturedCalls[0]?.name).toBe('ok.desktop.terminalWindowOpened');+ expect(capturedCalls[0]?.options?.attributes ?? {}).toEqual({});+ });+});diff --git a/packages/desktop/src/main/terminal-telemetry.ts b/packages/desktop/src/main/terminal-telemetry.tsindex 96ca51ab2..79d939672 100644--- a/packages/desktop/src/main/terminal-telemetry.ts+++ b/packages/desktop/src/main/terminal-telemetry.ts@@ -59,3 +59,13 @@ export function recordConcurrentSessions(info: { count: number }): void {() => undefined,);}++/**+ * Emit one `ok.desktop.terminalWindowOpened` span — the count-only adoption+ * marker for the "New Terminal Window" command. The span itself is the count;+ * it carries no attributes (no project path, no command contents), mirroring+ * `recordTerminalSession`. SDK disabled → no-op.+ */+export function recordTerminalWindowOpened(): void {+ withSpanSync('ok.desktop.terminalWindowOpened', {}, () => undefined);+}diff --git a/packages/desktop/src/main/terminal-window-registry.test.ts b/packages/desktop/src/main/terminal-window-registry.test.tsnew file mode 100644index 000000000..b38babe10--- /dev/null+++ b/packages/desktop/src/main/terminal-window-registry.test.ts@@ -0,0 +1,80 @@+import { afterEach, describe, expect, test } from 'bun:test';+import {+ getTerminalWindowContext,+ registerTerminalWindow,+ resolvePtyProjectRoot,+ unregisterTerminalWindow,+} from './terminal-window-registry.ts';++// Unique windowIds per test + explicit cleanup so the module-global Map does not+// leak across cases.+const WIN_A = 90_001;+const WIN_B = 90_002;++afterEach(() => {+ unregisterTerminalWindow(WIN_A);+ unregisterTerminalWindow(WIN_B);+});++describe('terminal-window registry', () => {+ test('round-trips a registered window context by windowId', () => {+ registerTerminalWindow(WIN_A, {+ projectRoot: '/Users/me/project',+ collabUrl: 'ws://localhost:5200/collab',+ apiOrigin: 'http://localhost:5200',+ });+ expect(getTerminalWindowContext(WIN_A)).toEqual({+ projectRoot: '/Users/me/project',+ collabUrl: 'ws://localhost:5200/collab',+ apiOrigin: 'http://localhost:5200',+ });+ });++ test('returns undefined for an unregistered window', () => {+ expect(getTerminalWindowContext(WIN_B)).toBeUndefined();+ });++ test('unregister removes the entry', () => {+ registerTerminalWindow(WIN_A, { projectRoot: '/Users/me/project' });+ unregisterTerminalWindow(WIN_A);+ expect(getTerminalWindowContext(WIN_A)).toBeUndefined();+ });+});++describe('resolvePtyProjectRoot', () => {+ test('an editor window keeps its windowsByPath-resolved project path', () => {+ const root = resolvePtyProjectRoot({+ editorProjectPath: '/Users/me/editor-project',+ terminalWindow: { projectRoot: '/Users/me/other' },+ homedir: '/Users/me',+ });+ expect(root).toBe('/Users/me/editor-project');+ });++ test('a project-bound terminal window resolves to its registered project root', () => {+ const root = resolvePtyProjectRoot({+ editorProjectPath: null,+ terminalWindow: { projectRoot: '/Users/me/project' },+ homedir: '/Users/me',+ });+ expect(root).toBe('/Users/me/project');+ });++ test('a project-less terminal window resolves to the home directory (never null)', () => {+ const root = resolvePtyProjectRoot({+ editorProjectPath: null,+ terminalWindow: { projectRoot: null },+ homedir: '/Users/me',+ });+ expect(root).toBe('/Users/me');+ });++ test('a window in neither map (e.g. the Navigator) resolves to null so the handler refuses', () => {+ const root = resolvePtyProjectRoot({+ editorProjectPath: null,+ terminalWindow: undefined,+ homedir: '/Users/me',+ });+ expect(root).toBeNull();+ });+});diff --git a/packages/desktop/src/main/terminal-window-registry.ts b/packages/desktop/src/main/terminal-window-registry.tsnew file mode 100644index 000000000..ad35495b0--- /dev/null+++ b/packages/desktop/src/main/terminal-window-registry.ts@@ -0,0 +1,53 @@+/**+ * windowId-keyed registry of standalone terminal windows.+ *+ * Terminal windows are deliberately NOT tracked in the window manager's+ * per-project `windowsByPath` map (which is one-per-project, focus-existing) so+ * multiple terminal windows for the same project can coexist. Because they are+ * absent from `windowsByPath`, `getContextForBrowserWindow` returns nothing for+ * them, so the `ok:pty:create` handler resolves a terminal window's cwd ++ * consent path from this registry instead.+ */++export interface TerminalWindowContext {+ /** Inherited project root, or null when the window was launched project-less. */+ readonly projectRoot: string | null;+ /** Inherited collab server URL (attach-mode) when the project's server is running. */+ readonly collabUrl?: string;+ /** Inherited API origin (attach-mode). */+ readonly apiOrigin?: string;+}++const terminalWindows = new Map<number, TerminalWindowContext>();++export function registerTerminalWindow(windowId: number, context: TerminalWindowContext): void {+ terminalWindows.set(windowId, context);+}++export function getTerminalWindowContext(windowId: number): TerminalWindowContext | undefined {+ return terminalWindows.get(windowId);+}++export function unregisterTerminalWindow(windowId: number): void {+ terminalWindows.delete(windowId);+}++/**+ * Resolve the cwd for an `ok:pty:create` call.+ *+ * Editor windows keep their existing per-project resolution (the project path+ * the window manager already resolved via `windowsByPath`). Terminal windows+ * resolve from the registry, falling back to `homedir` when project-less —+ * never null, because the PTY manager refuses a null root. Returns null only+ * when the window is neither (e.g. the Navigator), so the handler refuses with+ * `no-project`.+ */+export function resolvePtyProjectRoot(args: {+ readonly editorProjectPath: string | null;+ readonly terminalWindow: TerminalWindowContext | undefined;+ readonly homedir: string;+}): string | null {+ if (args.editorProjectPath) return args.editorProjectPath;+ if (args.terminalWindow) return args.terminalWindow.projectRoot ?? args.homedir;+ return null;+}diff --git a/packages/desktop/src/main/terminal-window.test.ts b/packages/desktop/src/main/terminal-window.test.tsnew file mode 100644index 000000000..7d2919159--- /dev/null+++ b/packages/desktop/src/main/terminal-window.test.ts@@ -0,0 +1,266 @@+import { afterEach, describe, expect, mock, spyOn, test } from 'bun:test';+import type { ShowGateRegistry } from './show-gate.ts';+import type { TerminalReaper } from './terminal-lifecycle.ts';+import {+ createTerminalWindow,+ resolveTerminalWindowProject,+ type TerminalBrowserWindow,+ type TerminalWindowProject,+} from './terminal-window.ts';+import { getTerminalWindowContext, unregisterTerminalWindow } from './terminal-window-registry.ts';++const PROJECT: TerminalWindowProject = {+ projectPath: '/Users/me/project',+ projectName: 'project',+ collabUrl: 'ws://localhost:5200/collab',+ apiOrigin: 'http://localhost:5200',+};++/** A fake window exposing only what the factory touches; `closed` handlers are+ * captured so a test can fire the lifecycle event. */+function makeFakeWindow(id: number) {+ const closedHandlers: Array<() => void> = [];+ const window = {+ id,+ on: (event: string, cb: () => void) => {+ if (event === 'closed') closedHandlers.push(cb);+ },+ once: () => {},+ loadFile: mock(async () => {}),+ loadURL: mock(async () => {}),+ webContents: { send: () => {}, once: () => {} },+ } as unknown as TerminalBrowserWindow;+ return {+ window,+ fireClosed: () => {+ for (const cb of closedHandlers) cb();+ },+ };+}++function makeDeps(opts: {+ id: number;+ project: TerminalWindowProject | null;+ rendererDevUrl?: string | null;+}) {+ const fake = makeFakeWindow(opts.id);+ const createWindow = mock((_o: { additionalArguments: string[]; title: string }) => fake.window);+ const disposeShowGate = mock(() => {});+ const register = mock((_window: unknown, _opts?: { kind?: string }) => disposeShowGate);+ const showGate = { register, fireThemeApplied: () => {} } as unknown as ShowGateRegistry;+ const killForWindow = mock((_id: number) => {});+ const terminalReaper = { killForWindow, killAll: () => {} } as unknown as TerminalReaper;+ return {+ fake,+ createWindow,+ disposeShowGate,+ register,+ killForWindow,+ deps: {+ createWindow,+ rendererEntryPath: '/app/index.html',+ rendererDevUrl: opts.rendererDevUrl ?? null,+ appVersion: '1.2.3',+ showGate,+ terminalReaper,+ project: opts.project,+ },+ };+}++const CREATED_IDS = [70_001, 70_002, 70_003];++afterEach(() => {+ // The registry is a module-global Map — drop anything a test registered (most+ // tests fire `closed` which unregisters; this covers the ones that do not).+ for (const id of CREATED_IDS) unregisterTerminalWindow(id);+});++describe('createTerminalWindow', () => {+ test('opens a --ok-mode=terminal window inheriting the project collab/api argv', () => {+ const h = makeDeps({ id: 70_001, project: PROJECT });+ createTerminalWindow(h.deps);++ expect(h.createWindow).toHaveBeenCalledTimes(1);+ const args = h.createWindow.mock.calls[0]?.[0];+ expect(args?.additionalArguments).toContain('--ok-mode=terminal');+ expect(args?.additionalArguments).toContain('--ok-collab-url=ws://localhost:5200/collab');+ expect(args?.additionalArguments).toContain('--ok-api-origin=http://localhost:5200');+ expect(args?.additionalArguments).toContain('--ok-project-path=/Users/me/project');+ expect(args?.additionalArguments).toContain('--ok-app-version=1.2.3');+ });++ test('titles the window with the project name when a project is present', () => {+ const h = makeDeps({ id: 70_001, project: PROJECT });+ createTerminalWindow(h.deps);+ expect(h.createWindow.mock.calls[0]?.[0]?.title).toBe('Open Knowledge Terminal — project');+ });++ test('records the window in the terminalWindows registry with its project root', () => {+ const h = makeDeps({ id: 70_001, project: PROJECT });+ createTerminalWindow(h.deps);+ expect(getTerminalWindowContext(70_001)).toEqual({+ projectRoot: '/Users/me/project',+ collabUrl: 'ws://localhost:5200/collab',+ apiOrigin: 'http://localhost:5200',+ });+ });++ test('registers the show gate with kind terminal', () => {+ const h = makeDeps({ id: 70_001, project: PROJECT });+ createTerminalWindow(h.deps);+ expect(h.register).toHaveBeenCalledTimes(1);+ expect(h.register.mock.calls[0]?.[1]).toEqual({ kind: 'terminal' });+ });++ test('a project-less window carries empty collab/api argv, a generic title, and a null project root', () => {+ const h = makeDeps({ id: 70_002, project: null });+ createTerminalWindow(h.deps);++ const args = h.createWindow.mock.calls[0]?.[0];+ expect(args?.additionalArguments).toContain('--ok-collab-url=');+ expect(args?.additionalArguments).toContain('--ok-api-origin=');+ expect(args?.additionalArguments).toContain('--ok-project-path=');+ expect(args?.title).toBe('Open Knowledge Terminal');+ expect(getTerminalWindowContext(70_002)?.projectRoot).toBeNull();+ });++ test('closing the window reaps its PTYs, disposes the show gate, and clears the registry', () => {+ const h = makeDeps({ id: 70_001, project: PROJECT });+ createTerminalWindow(h.deps);+ expect(getTerminalWindowContext(70_001)).not.toBeUndefined();++ h.fake.fireClosed();++ expect(h.killForWindow).toHaveBeenCalledWith(70_001);+ expect(h.disposeShowGate).toHaveBeenCalledTimes(1);+ expect(getTerminalWindowContext(70_001)).toBeUndefined();+ });++ test('opening twice for the same project yields two independent windows (no focus-existing)', () => {+ const a = makeDeps({ id: 70_001, project: PROJECT });+ createTerminalWindow(a.deps);+ const b = makeDeps({ id: 70_003, project: PROJECT });+ createTerminalWindow(b.deps);++ // Each call created its own window + registry entry — terminal windows are+ // not deduped by project the way windowsByPath editor windows are.+ expect(a.createWindow).toHaveBeenCalledTimes(1);+ expect(b.createWindow).toHaveBeenCalledTimes(1);+ expect(getTerminalWindowContext(70_001)).not.toBeUndefined();+ expect(getTerminalWindowContext(70_003)).not.toBeUndefined();++ a.fake.fireClosed();+ b.fake.fireClosed();+ });++ test('uses loadURL with the dev URL when provided, else loadFile', () => {+ const dev = makeDeps({ id: 70_001, project: PROJECT, rendererDevUrl: 'http://localhost:5173' });+ createTerminalWindow(dev.deps);+ expect(dev.fake.window.loadURL).toHaveBeenCalledWith('http://localhost:5173');+ expect(dev.fake.window.loadFile).not.toHaveBeenCalled();+ dev.fake.fireClosed();++ const prod = makeDeps({ id: 70_002, project: PROJECT });+ createTerminalWindow(prod.deps);+ expect(prod.fake.window.loadFile).toHaveBeenCalledWith('/app/index.html');+ expect(prod.fake.window.loadURL).not.toHaveBeenCalled();+ prod.fake.fireClosed();+ });++ test('a renderer load rejection surfaces a structured terminal-load-failed warn (not an unhandled rejection)', async () => {+ const h = makeDeps({ id: 70_001, project: PROJECT, rendererDevUrl: 'http://localhost:5173' });+ const failing = mock(async () => {+ throw new Error('renderer boom');+ });+ // Override the happy-path loadURL with one that rejects, exercising the+ // factory's `.catch` handler rather than the resolve path the tests above hit.+ (h.fake.window as unknown as { loadURL: typeof failing }).loadURL = failing;+ const warnSpy = spyOn(console, 'warn').mockImplementation(() => {});++ createTerminalWindow(h.deps);+ // The factory attaches its `.catch` synchronously; the rejected promise queues+ // that handler as a microtask. Flush the microtask queue so it has run before+ // asserting — deterministic, no timer wait.+ await Promise.resolve();+ await Promise.resolve();++ expect(warnSpy).toHaveBeenCalledTimes(1);+ const payload = JSON.parse(warnSpy.mock.calls[0]?.[0] as string);+ expect(payload).toMatchObject({+ event: 'terminal-load-failed',+ windowId: 70_001,+ target: 'http://localhost:5173',+ message: 'renderer boom',+ });++ warnSpy.mockRestore();+ h.fake.fireClosed();+ });+});++describe('resolveTerminalWindowProject', () => {+ test('an editor window context wins, deriving the collab URL from its port', () => {+ expect(+ resolveTerminalWindowProject({+ editor: {+ projectPath: '/Users/me/proj',+ projectName: 'proj',+ port: 5200,+ apiOrigin: 'http://localhost:5200',+ },+ terminal: { projectRoot: '/Users/me/other' },+ }),+ ).toEqual({+ projectPath: '/Users/me/proj',+ projectName: 'proj',+ collabUrl: 'ws://localhost:5200/collab',+ apiOrigin: 'http://localhost:5200',+ });+ });++ test('a focused terminal window inherits its registry context (chaining)', () => {+ expect(+ resolveTerminalWindowProject({+ editor: null,+ terminal: {+ projectRoot: '/Users/me/proj',+ collabUrl: 'ws://localhost:5300/collab',+ apiOrigin: 'http://localhost:5300',+ },+ }),+ ).toEqual({+ projectPath: '/Users/me/proj',+ projectName: 'proj',+ collabUrl: 'ws://localhost:5300/collab',+ apiOrigin: 'http://localhost:5300',+ });+ });++ test('chaining from a terminal window with no collab/api fields falls back to empty strings', () => {+ // The registry's collabUrl/apiOrigin are optional; the resolver's `?? ''`+ // fallbacks must keep argv as `--ok-collab-url=` (empty) rather than letting+ // `undefined` through and producing `--ok-collab-url=undefined`.+ expect(+ resolveTerminalWindowProject({+ editor: null,+ terminal: { projectRoot: '/Users/me/proj' },+ }),+ ).toEqual({+ projectPath: '/Users/me/proj',+ projectName: 'proj',+ collabUrl: '',+ apiOrigin: '',+ });+ });++ test('a project-less focused terminal window resolves to null (project-less)', () => {+ expect(+ resolveTerminalWindowProject({ editor: null, terminal: { projectRoot: null } }),+ ).toBeNull();+ });++ test('no focused project (Navigator / no window) resolves to null', () => {+ expect(resolveTerminalWindowProject({ editor: null, terminal: undefined })).toBeNull();+ });+});diff --git a/packages/desktop/src/main/terminal-window.ts b/packages/desktop/src/main/terminal-window.tsnew file mode 100644index 000000000..941721663--- /dev/null+++ b/packages/desktop/src/main/terminal-window.ts@@ -0,0 +1,162 @@+/**+ * Standalone terminal window — a dedicated `--ok-mode=terminal` window whose+ * content is the multi-session terminal (tab strip + sessions) full-window.+ *+ * Modeled on `navigator-window.ts`: same renderer bundle, a distinct window+ * mode, and the dual-signal show gate. Differs in two ways that make the+ * terminal a first-class peer rather than a launcher:+ * - It records itself in the windowId-keyed `terminalWindows` registry (and+ * never in `windowsByPath`), so `ok:pty:create` can resolve its cwd ++ * consent path and multiple terminal windows for the same project coexist+ * instead of focusing an existing one.+ * - It wires the per-window PTY reap so closing the window kills its shells.+ *+ * When launched from a project it inherits that project's collab/api server+ * (attach-mode); launched project-less it carries empty collab/api argv and a+ * home-cwd shell (resolved in the create handler).+ */++import { basename } from 'node:path';+import type { ShowGateRegistry } from './show-gate.ts';+import { type TerminalReaper, wireWindowTerminalReap } from './terminal-lifecycle.ts';+import {+ registerTerminalWindow,+ type TerminalWindowContext,+ unregisterTerminalWindow,+} from './terminal-window-registry.ts';+import type { BrowserWindowLike } from './window-manager.ts';++/** A created window exposing the numeric `id` the reap + registry wiring needs.+ * The real Electron `BrowserWindow` always has `id`; `BrowserWindowLike` omits+ * it because most window plumbing keys off the window object, not its id. */+export type TerminalBrowserWindow = BrowserWindowLike & { readonly id: number };++/** Project context a terminal window inherits (attach-mode). Null = project-less. */+export interface TerminalWindowProject {+ readonly projectPath: string;+ readonly projectName: string;+ readonly collabUrl: string;+ readonly apiOrigin: string;+}++interface CreateTerminalWindowDeps {+ /** Creates the real BrowserWindow (with `show: false`); the show gate reveals it. */+ createWindow(opts: { additionalArguments: string[]; title: string }): TerminalBrowserWindow;+ /** Path to the built renderer HTML (packaged/prod). */+ rendererEntryPath: string;+ /** electron-vite dev-server URL for HMR; when set, `loadURL` is used over `loadFile`. */+ rendererDevUrl?: string | null;+ /** App version, passed to the preload via additionalArguments. */+ appVersion: string;+ /** Dual-signal show coordinator — terminal windows get `kind: 'terminal'`. */+ showGate: ShowGateRegistry;+ /** PTY reap surface so a closed terminal window never leaks its shells. */+ terminalReaper: TerminalReaper;+ /** Inherited project context (attach-mode), or null for a home-cwd window. */+ project: TerminalWindowProject | null;+}++const GENERIC_TITLE = 'Open Knowledge Terminal';++export function createTerminalWindow(deps: CreateTerminalWindowDeps): TerminalBrowserWindow {+ const { project } = deps;+ const title = project ? `${GENERIC_TITLE} — ${project.projectName}` : GENERIC_TITLE;+ const window = deps.createWindow({+ additionalArguments: [+ '--ok-mode=terminal',+ `--ok-app-version=${deps.appVersion}`,+ // Attach-mode: inherit the launching project's collab + api server so the+ // window shares its config / consent / MCP. A project-less window omits+ // them (the renderer's useCollabUrl short-circuit returns empty) and runs+ // a home-cwd shell.+ `--ok-collab-url=${project?.collabUrl ?? ''}`,+ `--ok-api-origin=${project?.apiOrigin ?? ''}`,+ `--ok-project-path=${project?.projectPath ?? ''}`,+ `--ok-project-name=${project?.projectName ?? GENERIC_TITLE}`,+ ],+ title,+ });++ // Record the window's cwd + attach context BEFORE the renderer loads, so the+ // first `ok:pty:create` resolves a shell. Terminal windows are deliberately+ // absent from `windowsByPath` (one-per-project, focus-existing), so this is+ // their only cwd/consent source. projectRoot is null when project-less; the+ // create handler falls back to homedir().+ registerTerminalWindow(window.id, {+ projectRoot: project?.projectPath ?? null,+ collabUrl: project?.collabUrl,+ apiOrigin: project?.apiOrigin,+ });++ // Closing the window reaps its PTY host (no orphan shells) and drops its+ // registry entry. The reap wiring captures the id eagerly (the window is+ // destroyed by the time `closed` fires).+ wireWindowTerminalReap(window, deps.terminalReaper);+ const disposeShowGate = deps.showGate.register(window, { kind: 'terminal' });+ window.on('closed', () => {+ disposeShowGate();+ unregisterTerminalWindow(window.id);+ });++ // Surface load failures with a grep-able structured warn (mirrors the+ // Navigator factory) rather than discarding the rejection — the show gate's+ // 5 s safety timeout still reveals the (blank) window so failure is visible.+ const loadPromise = deps.rendererDevUrl+ ? window.loadURL(deps.rendererDevUrl)+ : window.loadFile(deps.rendererEntryPath);+ loadPromise.catch((err: unknown) => {+ console.warn(+ JSON.stringify({+ event: 'terminal-load-failed',+ // Terminal windows are multi-instance (unlike the single Navigator), so+ // attribute the failure to the specific window.+ windowId: window.id,+ target: deps.rendererDevUrl ?? deps.rendererEntryPath,+ message: err instanceof Error ? err.message : String(err),+ }),+ );+ });++ return window;+}++/** The editor-window project fields the resolver reads. The full `ProjectContext`+ * (window-manager.ts) is structurally assignable to this. */+interface EditorProjectContext {+ readonly projectPath: string;+ readonly projectName: string;+ readonly port: number;+ readonly apiOrigin: string;+}++/**+ * Resolve the project a new terminal window inherits from the focused window.+ * An editor window's context (from `windowsByPath`) wins — its collab URL is+ * derived from the port the same way editor windows build their `--ok-collab-url`+ * argv. Otherwise a focused terminal window's registry context lets "New+ * Terminal Window" chain within the same project. Returns null when neither+ * resolves (the Navigator, no focused window, or a project-less terminal window)+ * so the new window opens project-less (home cwd).+ */+export function resolveTerminalWindowProject(args: {+ readonly editor: EditorProjectContext | null;+ readonly terminal: TerminalWindowContext | undefined;+}): TerminalWindowProject | null {+ if (args.editor) {+ return {+ projectPath: args.editor.projectPath,+ projectName: args.editor.projectName,+ collabUrl: `ws://localhost:${args.editor.port}/collab`,+ apiOrigin: args.editor.apiOrigin,+ };+ }+ if (args.terminal?.projectRoot) {+ return {+ projectPath: args.terminal.projectRoot,+ projectName: basename(args.terminal.projectRoot),+ collabUrl: args.terminal.collabUrl ?? '',+ apiOrigin: args.terminal.apiOrigin ?? '',+ };+ }+ return null;+}diff --git a/packages/desktop/src/preload/index.ts b/packages/desktop/src/preload/index.tsindex b55100344..4c386c5c9 100644--- a/packages/desktop/src/preload/index.ts+++ b/packages/desktop/src/preload/index.ts@@ -50,6 +50,7 @@ import type {OkWhatsNewInfo,} from '../shared/bridge-contract.ts';import { createInvoker } from '../shared/ipc-invoke.ts';+import { resolveOkDesktopMode } from '../shared/ok-desktop-mode.ts';const invoke = createInvoker(ipcRenderer);@@ -202,8 +203,7 @@ function readConfigFromArgv(): OkDesktopConfig {const apiOrigin = parseArg('api-origin') ?? '';const projectPath = parseArg('project-path') ?? '';const projectName = parseArg('project-name') ?? '';- const modeRaw = parseArg('mode') ?? 'editor';- const mode: OkDesktopConfig['mode'] = modeRaw === 'navigator' ? 'navigator' : 'editor';+ const mode = resolveOkDesktopMode(parseArg('mode'));// Present only on ephemeral single-file windows (`ok <file>`); every normal// project window omits the flag and coerces to `false`.const singleFile = parseArg('single-file') === '1';diff --git a/packages/desktop/src/shared/bridge-contract.ts b/packages/desktop/src/shared/bridge-contract.tsindex 19288a656..20a80c1f8 100644--- a/packages/desktop/src/shared/bridge-contract.ts+++ b/packages/desktop/src/shared/bridge-contract.ts@@ -113,7 +113,7 @@ export type OkSeedListPacksResult =| { ok: false; error: { kind: 'internal'; message: string } };/** Render mode picked by the main process when creating a BrowserWindow. */-type OkDesktopMode = 'editor' | 'navigator';+type OkDesktopMode = 'editor' | 'navigator' | 'terminal';/** Frozen snapshot of window-level config injected at preload-exposure time. */export interface OkDesktopConfig {diff --git a/packages/desktop/src/shared/ok-desktop-mode.test.ts b/packages/desktop/src/shared/ok-desktop-mode.test.tsnew file mode 100644index 000000000..005d754fe--- /dev/null+++ b/packages/desktop/src/shared/ok-desktop-mode.test.ts@@ -0,0 +1,24 @@+import { describe, expect, test } from 'bun:test';+import { resolveOkDesktopMode } from './ok-desktop-mode.ts';++describe('resolveOkDesktopMode', () => {+ test('maps the terminal flag to the terminal window mode', () => {+ expect(resolveOkDesktopMode('terminal')).toBe('terminal');+ });++ test('maps the navigator flag to the navigator window mode', () => {+ expect(resolveOkDesktopMode('navigator')).toBe('navigator');+ });++ test('maps the editor flag to the editor window mode', () => {+ expect(resolveOkDesktopMode('editor')).toBe('editor');+ });++ test('falls back to editor when the flag is absent', () => {+ expect(resolveOkDesktopMode(undefined)).toBe('editor');+ });++ test('falls back to editor for an unrecognized flag value', () => {+ expect(resolveOkDesktopMode('totally-unknown')).toBe('editor');+ });+});diff --git a/packages/desktop/src/shared/ok-desktop-mode.ts b/packages/desktop/src/shared/ok-desktop-mode.tsnew file mode 100644index 000000000..adec5d33e--- /dev/null+++ b/packages/desktop/src/shared/ok-desktop-mode.ts@@ -0,0 +1,13 @@+import type { OkDesktopConfig } from './bridge-contract.ts';++/**+ * Resolve the `--ok-mode=<value>` argv flag the main process injects into a+ * window's preload into a render mode. Unknown or absent values fall back to+ * `editor` so a malformed launch still yields a usable editor window rather+ * than a blank one.+ */+export function resolveOkDesktopMode(raw: string | undefined): OkDesktopConfig['mode'] {+ if (raw === 'navigator') return 'navigator';+ if (raw === 'terminal') return 'terminal';+ return 'editor';+}diff --git a/packages/desktop/tests/main/menu.test.ts b/packages/desktop/tests/main/menu.test.tsindex 98227fb75..4d954398d 100644--- a/packages/desktop/tests/main/menu.test.ts+++ b/packages/desktop/tests/main/menu.test.ts@@ -1017,14 +1017,22 @@ describe('buildMenuTemplate — top-level Terminal menu (New / Kill)', () => {expect(windowIdx).toBeGreaterThan(terminalIdx);});- test('contains exactly New Terminal then Kill Terminal; New Terminal is click-only (no ⌘J)', () => {+ test('contains New Terminal, New Terminal Window, then Kill Terminal; New Terminal is click-only (no ⌘J)', () => {const template = buildMenuTemplate(- makeDeps({ onNewTerminal: mock(() => {}), onKillTerminal: mock(() => {}) }),+ makeDeps({+ onNewTerminal: mock(() => {}),+ onNewTerminalWindow: mock(() => {}),+ onKillTerminal: mock(() => {}),+ }),);const sub = findByLabel(template, 'Terminal')?.submenu as| MenuItemConstructorOptions[]| undefined;- expect(sub?.map((i) => i.label)).toEqual(['New Terminal', 'Kill Terminal']);+ expect(sub?.map((i) => i.label)).toEqual([+ 'New Terminal',+ 'New Terminal Window',+ 'Kill Terminal',+ ]);// No accelerator: ⌘J belongs to the View → Show/Hide Terminal toggle, so// advertising it here too would only mislabel this item.expect(findByLabel(template, 'New Terminal')?.accelerator).toBeUndefined();@@ -1135,3 +1143,43 @@ describe('buildMenuTemplate — Edit → Check spelling while typing', () => {expect(spellIdx).toBeGreaterThan(selectAllIdx);});});++describe('Terminal menu — New Terminal Window', () => {+ test('appears in the Terminal submenu beside New Terminal', () => {+ const template = buildMenuTemplate(makeDeps({ onNewTerminalWindow: mock(() => {}) }));+ const terminalMenu = template.find((i) => i.label === 'Terminal');+ const sub = terminalMenu?.submenu as MenuItemConstructorOptions[] | undefined;+ if (!sub) throw new Error('Terminal submenu missing');+ const labels = sub.map((i) => i.label);+ expect(labels).toContain('New Terminal');+ expect(labels).toContain('New Terminal Window');+ });++ test('renders with no keyboard accelerator', () => {+ const item = findByLabel(+ buildMenuTemplate(makeDeps({ onNewTerminalWindow: mock(() => {}) })),+ 'New Terminal Window',+ );+ expect(item).toBeDefined();+ expect(item?.accelerator).toBeUndefined();+ });++ test('click invokes onNewTerminalWindow', () => {+ const onNewTerminalWindow = mock(() => {});+ const item = findByLabel(+ buildMenuTemplate(makeDeps({ onNewTerminalWindow })),+ 'New Terminal Window',+ );+ (item?.click as (() => void) | undefined)?.();+ expect(onNewTerminalWindow).toHaveBeenCalledTimes(1);+ });++ test('disabled when the dep is omitted, enabled when wired', () => {+ expect(findByLabel(buildMenuTemplate(makeDeps()), 'New Terminal Window')?.enabled).toBe(false);+ const wired = findByLabel(+ buildMenuTemplate(makeDeps({ onNewTerminalWindow: mock(() => {}) })),+ 'New Terminal Window',+ );+ expect(wired?.enabled).toBe(true);+ });+});diff --git a/packages/desktop/tests/main/terminal-window-attach-survival.test.ts b/packages/desktop/tests/main/terminal-window-attach-survival.test.tsnew file mode 100644index 000000000..033da9f05--- /dev/null+++ b/packages/desktop/tests/main/terminal-window-attach-survival.test.ts@@ -0,0 +1,277 @@+/**+ * Seam 6 integration: a terminal window launched from a project+ * attaches to that project's already-running server (`ownsServer:false`), and+ * its PTY SURVIVES when the owning editor window's server is torn down. The PTY+ * host is server-independent by construction — `terminalManager` forks a+ * per-`windowId` utilityProcess and never holds a reference to the collab/api+ * server, so server teardown cannot reap it.+ *+ * Composes the real pieces at the seam-7 gate-run rung (fake pty-host + fake+ * BrowserWindow/utility, real everything else):+ * - real `WindowManager` attach path (the owner editor window, `ownsServer:false`)+ * - real `terminalWindow` registry + `resolvePtyProjectRoot` (the terminal+ * window's cwd/consent source)+ * - real `terminalManager` (the per-window PTY host)+ * It exercises the genuine survival path: the owner window closes and its+ * server is torn down (no cross-window ref-counting), then a command typed into+ * the terminal window's shell still routes to its live host and host output+ * still reaches the terminal renderer. Full real-shell fidelity is the+ * `_electron` smoke (seam 4); this is the gate-run rung, matching+ * terminal-window-pty.test.ts.+ */++import { afterEach, describe, expect, test } from 'bun:test';+import { createTerminalManager, type PtyUtilityLike } from '../../src/main/terminal-manager.ts';+import {+ getTerminalWindowContext,+ registerTerminalWindow,+ resolvePtyProjectRoot,+ unregisterTerminalWindow,+} from '../../src/main/terminal-window-registry.ts';+import {+ type BrowserWindowLike,+ type ServerLockMetadataLike,+ type UtilityProcessLike,+ WindowManager,+ type WindowManagerDeps,+} from '../../src/main/window-manager.ts';+import type { SendableWebContents } from '../../src/shared/ipc-send.ts';++const HOME = '/Users/test-home';+const PROJECT = '/tmp/attach-survival-project';++/** Per-window fake pty-host. Captures every message the manager posts so a test+ * can assert input routing, and lets a test drive host->renderer `data`. */+class FakeHost {+ posted: Array<Record<string, unknown>> = [];+ private messageCb: ((m: unknown) => void) | null = null;+ killed = false;+ postMessage(m: Record<string, unknown>): void {+ this.posted.push(m);+ }+ on(event: 'message' | 'exit', cb: (m: unknown) => void): void {+ if (event === 'message') this.messageCb = cb;+ }+ /** Simulate the utilityProcess emitting output for a session. */+ emit(m: Record<string, unknown>): void {+ this.messageCb?.(m);+ }+ kill(): boolean {+ this.killed = true;+ return true;+ }+}++function makeWebContents(): SendableWebContents & { destroyed: boolean } {+ const wc = {+ destroyed: false,+ send() {},+ isDestroyed() {+ return wc.destroyed;+ },+ };+ return wc;+}++/** Real terminalManager over fake hosts, with captured data/exit sinks so we can+ * prove the terminal renderer still receives output after server teardown. */+function makeTerminalManager() {+ const forked: FakeHost[] = [];+ const dataPushes: Array<{ ptyId: string; data: string }> = [];+ let idn = 0;+ const mgr = createTerminalManager({+ forkPtyHost: () => {+ const h = new FakeHost();+ forked.push(h);+ return h as unknown as PtyUtilityLike;+ },+ sendData: (_wc, payload) => dataPushes.push(payload),+ sendExit: () => {},+ newPtyId: () => `pty-${++idn}`,+ // Fire the coalesce flush synchronously so a host->renderer `data` push is+ // observable within the test without real timers.+ setTimer: (cb: () => void) => {+ cb();+ return 0;+ },+ clearTimer: () => {},+ logger: { warn: () => {} },+ });+ return { mgr, forked, dataPushes };+}++// --- WindowManager attach harness (owner editor window owns the server) ------++function makeOwnerWindow() {+ const closedHandlers: Array<() => void> = [];+ let destroyed = false;+ const window = {+ focus: () => {},+ show: () => {},+ restore: () => {},+ isMinimized: () => false,+ isDestroyed: () => destroyed,+ isVisible: () => true,+ on: (_event: 'closed', cb: () => void) => {+ closedHandlers.push(cb);+ },+ once: () => {},+ close: () => {+ destroyed = true;+ for (const h of closedHandlers) h();+ },+ destroy: () => {+ destroyed = true;+ for (const h of closedHandlers) h();+ },+ webContents: { send: () => {}, once: () => {} },+ loadFile: () => Promise.resolve(),+ loadURL: () => Promise.resolve(),+ } as unknown as BrowserWindowLike;+ return window;+}++/**+ * A WindowManager wired for the attach path, with a server "torn down" hook the+ * test drives. The lock disappears once the owner is torn down so any later+ * attach attempt would correctly fall through — modeling the real "owner closed,+ * server gone" topology.+ */+function makeOwnerWindowManager() {+ let serverAlive = true;+ const liveLock: ServerLockMetadataLike = {+ pid: 90_111,+ hostname: 'my-host',+ port: 59_900,+ startedAt: '2026-06-22T00:00:00.000Z',+ worktreeRoot: PROJECT,+ kind: 'interactive',+ capabilities: ['http', 'ws'],+ };+ const killed: number[] = [];+ const deps: WindowManagerDeps = {+ createWindow: () => makeOwnerWindow(),+ // The attach path never forks a utility (it reuses the live lock); this is+ // wired only to satisfy the deps contract.+ forkUtility: (): UtilityProcessLike => ({+ pid: 90_222,+ postMessage: () => {},+ on: () => {},+ once: () => {},+ removeListener: () => {},+ kill: () => true,+ }),+ utilityEntryPath: '/fake/utility-entry.js',+ rendererEntryPath: '/fake/renderer/index.html',+ appVersion: '9.9.9-test',+ setTimeout: () => null,+ killProbe: (pid: number, signal: string | number) => {+ if (signal === 'SIGTERM') killed.push(pid);+ },+ showGate: {+ register: () => () => {},+ fireThemeApplied: () => {},+ },+ // Attach-mode probe: a live same-host server holds the lock until teardown.+ readServerLock: () => (serverAlive ? liveLock : null),+ isProcessAlive: () => serverAlive,+ hostname: () => 'my-host',+ probeWsUpgrade: () => Promise.resolve(true),+ };+ return {+ wm: new WindowManager(deps),+ liveLock,+ killed,+ tearDownServer: () => {+ serverAlive = false;+ },+ };+}++const TERM_WIN_ID = 90_500;++afterEach(() => {+ unregisterTerminalWindow(TERM_WIN_ID);+});++describe('terminal window PTY survives owner-server teardown (seam 6 / FR4 / D2)', () => {+ test('attach-mode terminal window: PTY keeps routing after the owner editor window closes and its server is torn down', async () => {+ const owner = makeOwnerWindowManager();++ // 1) The owning editor window attaches to the project's running server.+ const ownerCtx = await owner.wm.createProjectWindow({ projectPath: PROJECT });+ expect(ownerCtx.ownsServer).toBe(false); // attached, not owned+ expect(ownerCtx.port).toBe(59_900);++ // 2) A terminal window is launched from that project (attach-mode: it+ // inherits the collab/api argv). It is registered in the terminalWindows+ // registry — deliberately absent from windowsByPath — so ok:pty:create+ // resolves its cwd from the registry.+ registerTerminalWindow(TERM_WIN_ID, {+ projectRoot: PROJECT,+ collabUrl: `ws://localhost:${ownerCtx.port}/collab`,+ apiOrigin: ownerCtx.apiOrigin,+ });+ const cwd = resolvePtyProjectRoot({+ editorProjectPath: null,+ terminalWindow: getTerminalWindowContext(TERM_WIN_ID),+ homedir: HOME,+ });+ expect(cwd).toBe(PROJECT);++ // 3) The terminal window spawns a live PTY at the inherited cwd.+ const { mgr, forked, dataPushes } = makeTerminalManager();+ const termWc = makeWebContents();+ const created = mgr.create({+ windowId: TERM_WIN_ID,+ webContents: termWc,+ projectRoot: cwd,+ cols: 80,+ rows: 24,+ });+ expect(created.ok).toBe(true);+ if (!created.ok) throw new Error('expected a live PTY');+ const host = forked[0];+ if (!host) throw new Error('expected a forked PTY host');+ expect(host.posted).toContainEqual({+ type: 'create',+ ptyId: created.ptyId,+ cwd: PROJECT,+ cols: 80,+ rows: 24,+ });++ // 4) THE TEARDOWN: the owning editor window closes and its server is torn+ // down (no cross-window ref-counting). This is the event the PTY must+ // survive.+ owner.tearDownServer();+ ownerCtx.window.close();+ expect(owner.wm.getWindowFor(PROJECT)).toBeUndefined(); // owner gone+ expect(owner.wm.windowCount()).toBe(0); // its server context is reaped++ // 5) SURVIVAL PROOF — the terminal window's PTY host was NEVER touched by+ // the server teardown (it is a separate per-windowId utilityProcess).+ expect(host.killed).toBe(false);++ // a) Input still routes to the live host: typing a command after teardown+ // reaches the host's postMessage (the shell still accepts input).+ const beforeInput = host.posted.length;+ mgr.input({ windowId: TERM_WIN_ID, ptyId: created.ptyId, data: 'echo alive\r' });+ expect(host.posted.length).toBe(beforeInput + 1);+ expect(host.posted.at(-1)).toEqual({+ type: 'input',+ ptyId: created.ptyId,+ data: 'echo alive\r',+ });++ // b) Host output still flows to the terminal renderer after teardown+ // (the data path is intact — the window is not destroyed).+ host.emit({ type: 'data', ptyId: created.ptyId, data: 'alive\r\n' });+ expect(dataPushes).toContainEqual({ ptyId: created.ptyId, data: 'alive\r\n' });++ // Sanity: reaping the TERMINAL window (its own close) is what kills its PTY+ // — proving step 5 was not a no-op because nothing reaps anything.+ mgr.killForWindow(TERM_WIN_ID);+ expect(host.killed).toBe(true);+ });+});diff --git a/packages/desktop/tests/main/terminal-window-pty.test.ts b/packages/desktop/tests/main/terminal-window-pty.test.tsnew file mode 100644index 000000000..dd36fa584--- /dev/null+++ b/packages/desktop/tests/main/terminal-window-pty.test.ts@@ -0,0 +1,154 @@+/**+ * Seam 7 integration: a standalone terminal window — deliberately absent+ * from `windowsByPath` — resolves its PTY cwd from the windowId-keyed+ * terminalWindows registry (or homedir() when project-less) and yields a live+ * PTY. Composes the real registry + the real `resolvePtyProjectRoot` + a real+ * `terminalManager` over a fake pty-host, so the cwd that reaches `create()` is+ * the one the registry/resolver produced. The full real-shell fidelity is the+ * `_electron` smoke (terminal-window.e2e.ts); this is the gate-run rung.+ */++import { afterEach, describe, expect, test } from 'bun:test';+import { createTerminalManager, type PtyUtilityLike } from '../../src/main/terminal-manager.ts';+import {+ getTerminalWindowContext,+ registerTerminalWindow,+ resolvePtyProjectRoot,+ unregisterTerminalWindow,+} from '../../src/main/terminal-window-registry.ts';+import type { SendableWebContents } from '../../src/shared/ipc-send.ts';++const HOME = '/Users/test-home';+const PROJECT = '/Users/me/proj';++class FakeHost {+ posted: Array<Record<string, unknown>> = [];+ postMessage(m: Record<string, unknown>): void {+ this.posted.push(m);+ }+ on(): void {}+ kill(): boolean {+ return true;+ }+}++function makeWebContents(): SendableWebContents {+ return { send() {}, isDestroyed: () => false };+}++function makeManager() {+ const forked: FakeHost[] = [];+ let idn = 0;+ const mgr = createTerminalManager({+ forkPtyHost: () => {+ const h = new FakeHost();+ forked.push(h);+ return h as unknown as PtyUtilityLike;+ },+ sendData: () => {},+ sendExit: () => {},+ newPtyId: () => `pty-${++idn}`,+ setTimer: () => 0,+ clearTimer: () => {},+ logger: { warn: () => {} },+ });+ return { mgr, forked };+}++/** The create handler's terminal-window cwd resolution: a terminal window is+ * absent from windowsByPath, so cwd comes from the registry (or homedir). */+function resolveTerminalWindowCwd(windowId: number): string | null {+ return resolvePtyProjectRoot({+ editorProjectPath: null,+ terminalWindow: getTerminalWindowContext(windowId),+ homedir: HOME,+ });+}++const WIN_BOUND = 80_001;+const WIN_LESS = 80_002;+const WIN_A = 80_003;+const WIN_B = 80_004;++afterEach(() => {+ for (const id of [WIN_BOUND, WIN_LESS, WIN_A, WIN_B]) unregisterTerminalWindow(id);+});++describe('terminal window ok:pty:create cwd resolution (seam 7 / D10)', () => {+ test('a project-bound terminal window spawns a live PTY at its registered project root', () => {+ registerTerminalWindow(WIN_BOUND, { projectRoot: PROJECT });+ const cwd = resolveTerminalWindowCwd(WIN_BOUND);+ expect(cwd).toBe(PROJECT);++ const { mgr, forked } = makeManager();+ const result = mgr.create({+ windowId: WIN_BOUND,+ webContents: makeWebContents(),+ projectRoot: cwd,+ cols: 80,+ rows: 24,+ });++ expect(result.ok).toBe(true);+ if (!result.ok) throw new Error('expected a live PTY');+ expect(forked).toHaveLength(1);+ expect(forked[0]?.posted).toContainEqual({+ type: 'create',+ ptyId: result.ptyId,+ cwd: PROJECT,+ cols: 80,+ rows: 24,+ });+ });++ test('a project-less terminal window spawns a live PTY at the home directory (never null)', () => {+ registerTerminalWindow(WIN_LESS, { projectRoot: null });+ const cwd = resolveTerminalWindowCwd(WIN_LESS);+ expect(cwd).toBe(HOME);++ const { mgr, forked } = makeManager();+ const result = mgr.create({+ windowId: WIN_LESS,+ webContents: makeWebContents(),+ projectRoot: cwd,+ cols: 80,+ rows: 24,+ });++ expect(result.ok).toBe(true);+ if (!result.ok) throw new Error('expected a live PTY');+ expect(forked[0]?.posted).toContainEqual({+ type: 'create',+ ptyId: result.ptyId,+ cwd: HOME,+ cols: 80,+ rows: 24,+ });+ });++ test('multiple terminal windows for the same project each fork their own PTY host', () => {+ registerTerminalWindow(WIN_A, { projectRoot: PROJECT });+ registerTerminalWindow(WIN_B, { projectRoot: PROJECT });+ const { mgr, forked } = makeManager();++ const a = mgr.create({+ windowId: WIN_A,+ webContents: makeWebContents(),+ projectRoot: resolveTerminalWindowCwd(WIN_A),+ cols: 80,+ rows: 24,+ });+ const b = mgr.create({+ windowId: WIN_B,+ webContents: makeWebContents(),+ projectRoot: resolveTerminalWindowCwd(WIN_B),+ cols: 80,+ rows: 24,+ });++ expect(a.ok).toBe(true);+ expect(b.ok).toBe(true);+ // Independent hosts (per-window), so closing one never reaps the other.+ expect(forked).toHaveLength(2);+ });+});diff --git a/packages/desktop/tests/smoke/terminal-window.e2e.ts b/packages/desktop/tests/smoke/terminal-window.e2e.tsnew file mode 100644index 000000000..dada1c853--- /dev/null+++ b/packages/desktop/tests/smoke/terminal-window.e2e.ts@@ -0,0 +1,210 @@+/**+ * Standalone terminal-window live-Electron smoke (SPEC §9 seam 4). Drives the+ * real menu → main `createTerminalWindow` → a dedicated `--ok-mode=terminal`+ * BrowserWindow → the renderer's TerminalWindowApp → a per-window utilityProcess+ * hosting node-pty. Asserts the surfaces the mocked dom tests cannot reach: the+ * Terminal → New Terminal Window menu command opens a real window, a live shell+ * spawns at the inherited project cwd, multiple windows coexist, and closing the+ * last tab closes the window (D7). Per-window PTY reap on close is unit-covered+ * (terminal-window.test.ts asserts killForWindow on 'closed'; terminal-manager+ * kills the host); this asserts the observable window-close.+ *+ * Skip gates mirror terminal-dock.e2e.ts: opt-in via OK_DESKTOP_E2E_SMOKE=1,+ * darwin-only, the electron-vite build must exist, and CI-skipped (the+ * live-Electron terminal surface is not yet validated on the CI runner — same+ * caveat as the docked-terminal smoke). Runs in local dev to keep the seam+ * covered. Not part of `bun run check`; run via `bunx playwright test` or+ * `bun run check:full:parallel`.+ */++import { existsSync, mkdirSync, mkdtempSync, 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 Seed {+ tmpHome: string;+ userDataDir: string;+ projectDir: string;+}++/** Seed a consented project (so the shell spawns without the JIT consent dialog). */+function seed(prefix: string): Seed {+ const tmpHome = realpathSync(mkdtempSync(join(tmpdir(), `ok-termwin-${prefix}-home-`)));+ const projectDir = realpathSync(mkdtempSync(join(tmpdir(), `ok-termwin-${prefix}-proj-`)));+ mkdirSync(join(projectDir, '.ok', 'local'), { recursive: true });+ writeFileSync(join(projectDir, '.ok', 'config.yml'), "content:\n dir: '.'\n");+ writeFileSync(join(projectDir, '.ok', 'local', 'config.yml'), 'terminal:\n enabled: true\n');+ writeFileSync(join(projectDir, 'start.md'), '# Start\n\nSeed document.\n');++ 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 Window Smoke', lastOpenedAt: new Date().toISOString() },+ ],+ lastOpenedProject: projectDir,+ versionPendingInstall: null,+ lastSeenVersion: null,+ lastSuccessfulCheckAt: null,+ stuckHintShown: false,+ }),+ );+ return { tmpHome, userDataDir, projectDir };+}++async function launchApp(s: Seed): Promise<ElectronApplication> {+ const deepLink = `openknowledge://open?project=${encodeURIComponent(s.projectDir)}&doc=start`;+ return electron.launch({+ args: [MAIN_ENTRY, `--user-data-dir=${s.userDataDir}`, deepLink],+ timeout: 30_000,+ env: {+ ...process.env,+ HOME: s.tmpHome,+ PATH: '/usr/bin:/bin:/usr/sbin:/sbin',+ OK_DESKTOP_E2E_SMOKE: '1',+ OK_RECLAIM_DISABLE: '1',+ },+ });+}++async function findWindowByMode(+ app: ElectronApplication,+ mode: 'editor' | 'terminal',+ timeoutMs = 25_000,+): Promise<Page> {+ let page: Page | undefined;+ await expect(async () => {+ for (const p of app.windows()) {+ const m = await p.evaluate(() => window.okDesktop?.config?.mode).catch(() => undefined);+ if (m === mode) {+ page = p;+ return;+ }+ }+ throw new Error(`no ${mode} window yet`);+ }).toPass({ timeout: timeoutMs });+ if (!page) throw new Error(`${mode} window vanished after readiness poll`);+ return page;+}++async function clickNewTerminalWindow(app: ElectronApplication): Promise<boolean> {+ return app.evaluate(async ({ Menu }) => {+ const menu = Menu.getApplicationMenu();+ const terminal = menu?.items.find((i) => i.label === 'Terminal');+ const item = terminal?.submenu?.items.find((i) => i.label === 'New Terminal Window');+ if (!item) return false;+ item.click();+ return true;+ });+}++async function terminalWindowCount(app: ElectronApplication): Promise<number> {+ let count = 0;+ for (const p of app.windows()) {+ const mode = await p.evaluate(() => window.okDesktop?.config?.mode).catch(() => undefined);+ if (mode === 'terminal') count += 1;+ }+ return count;+}++const cleanup: string[] = [];+function track(...paths: string[]): void {+ cleanup.push(...paths);+}++test.describe('Standalone terminal window — live Electron', () => {+ test.skip(!SMOKE_ENABLED, 'Set OK_DESKTOP_E2E_SMOKE=1 to run Electron smoke tests.');+ test.skip(!DARWIN, 'Desktop is darwin-only.');+ test.skip(!BUILD_EXISTS, `Main build missing at ${MAIN_ENTRY} — run "bun run build:desktop".`);+ test.skip(+ IS_CI,+ 'Quarantined on CI: constrained-runner degradation on the live-Electron terminal surface, same class as terminal-dock (inkeep/agents-private#2187). Runs in local dev.',+ );++ test.afterEach(() => {+ for (const target of cleanup.splice(0)) {+ try {+ rmSync(target, { recursive: true, force: true });+ } catch {+ // best-effort+ }+ }+ });++ test('New Terminal Window opens a window with a live shell at the project root; close-last closes it', async ({+ captureStderrFor,+ }) => {+ const s = seed('open-close');+ track(s.tmpHome, s.projectDir);+ const app = await launchApp(s);+ captureStderrFor(app, { cleanupDirs: [s.tmpHome, s.projectDir] });+ // The editor window must be focused so the command inherits its project.+ await findWindowByMode(app, 'editor');++ expect(await clickNewTerminalWindow(app)).toBe(true);+ const term = await findWindowByMode(app, 'terminal');++ // A live shell tab spawned in the new window.+ await expect(term.locator('[data-terminal-status]').first()).toHaveAttribute(+ 'data-terminal-status',+ 'running',+ { timeout: 25_000 },+ );+ await expect(term.getByRole('tab', { name: 'Terminal 1' })).toBeVisible();++ // The shell's cwd is the inherited project root (the registry resolution+ // reaching a real shell).+ await term.locator('section[aria-label="Terminal"] .xterm').first().click();+ await term.keyboard.type('pwd\r');+ const tail = s.projectDir.split('/').slice(-1)[0] ?? '';+ await expect+ .poll(+ () =>+ term.evaluate(() => {+ const sec = document.querySelector('section[aria-label="Terminal"]');+ const a11y = sec?.querySelector('.xterm-accessibility')?.textContent ?? '';+ const rows = sec?.querySelector('.xterm-rows')?.textContent ?? '';+ return `${a11y}\n${rows}`;+ }),+ { timeout: 15_000 },+ )+ .toContain(tail);++ // Closing the last tab closes the window (it does not collapse a panel).+ await term.getByRole('button', { name: 'Close Terminal 1' }).click();+ await expect.poll(() => terminalWindowCount(app), { timeout: 15_000 }).toBe(0);+ });++ test('opening New Terminal Window twice yields two independent terminal windows', async ({+ captureStderrFor,+ }) => {+ const s = seed('multi');+ track(s.tmpHome, s.projectDir);+ const app = await launchApp(s);+ captureStderrFor(app, { cleanupDirs: [s.tmpHome, s.projectDir] });+ await findWindowByMode(app, 'editor');++ expect(await clickNewTerminalWindow(app)).toBe(true);+ await findWindowByMode(app, 'terminal');+ expect(await clickNewTerminalWindow(app)).toBe(true);++ // Both windows coexist — terminal windows are not deduped per project the+ // way editor windows are (windowsByPath focus-existing).+ await expect.poll(() => terminalWindowCount(app), { timeout: 20_000 }).toBe(2);+ });+});