Beautiful, AI-native markdown IDE and LLM wiki
TypeScript 2nd-brainagent-skillsclaudecodexcompany-braindocsknowledge-knowledge-baseknowledge-managementllmllm-wikillm-wiki-karpathymarkdownmarkdown-editormdmdxnotespkmsecond-brainskills
feat(open-knowledge): ⌘J/⇧⌘J stage editor selection into an AI CLI in the terminal (PRD-7328) (#2579)
serafin-garciaf2834c237639
diff --git a/.changeset/launch-ai-terminal-shortcut.md b/.changeset/launch-ai-terminal-shortcut.mdnew file mode 100644index 000000000..0e09df774--- /dev/null+++ b/.changeset/launch-ai-terminal-shortcut.md@@ -0,0 +1,10 @@+---+"@inkeep/open-knowledge": patch+---++Keyboard shortcuts for staging a selection into an AI CLI in the terminal, plus new terminal tabs:++- **⌘J** (Show/Hide Terminal): with text selected in the editor, ⌘J stages that selection into an AI CLI's input in the terminal — **not** submitted, so you can add context and press Enter yourself. If the active tab is already running a CLI (claude/codex/…), the passage goes into its prompt (no screen wipe); otherwise a new CLI tab opens and the passage is staged into it. With no selection, ⌘J toggles the terminal as before.+- **⇧⌘J**: opens a new terminal tab. With text selected, it opens a new CLI tab with the passage staged into its input; with no selection, it starts a new chat with your preferred CLI.++The passage is grounded the same way the "Ask AI" selection button does (doc reference + text). Nothing is auto-run — the selection is staged for you to review, extend, and send. Brings AI-in-terminal keyboard parity with Cursor/Zed/VS Code.diff --git a/docs/content/features/editor.mdx b/docs/content/features/editor.mdxindex 6d4989455..5d77d5c7c 100644--- a/docs/content/features/editor.mdx+++ b/docs/content/features/editor.mdx@@ -81,7 +81,7 @@ Select text in the WYSIWYG editor and the selection bubble menu shows an **Ask AThe desktop app has a built-in terminal: real login shells, docked in the editor window. Toggle it with `Cmd+J`, **View ▸ Show / Hide Terminal**, or the edge **Show terminal** tab that sits where you last closed it. It opens as a right-side column by default; buttons in its tab strip move it between the right column and the bottom dock or collapse it (sessions keep running), and the dock position is remembered.-The terminal is also the editor's AI-chat surface: the **Show terminal** tab starts your default CLI when no session is open, and the tab strip's **New chat** split button opens another CLI tab — its dropdown switches CLI (the pick sticks, shared with the Ask AI composer) or opens a plain shell tab. **Terminal ▸ New Terminal Window** (see [Terminal menu](#terminal-menu)) opens a dedicated window with the same multi-session tabs, `Cmd+<number>` tab switching, and shells starting at the project root.+The terminal is also the editor's AI-chat surface: the **Show terminal** tab starts your default CLI when no session is open, and the tab strip's **New chat** split button opens another CLI tab — its dropdown switches CLI (the pick sticks, shared with the Ask AI composer) or opens a plain shell tab. With text selected in the editor, `Cmd+J` stages the passage into the active CLI's input (or opens a new CLI tab when none is running) instead of toggling, and `Cmd+Shift+J` always stages it into a new CLI tab — the passage sits in the input for you to add to, and nothing is submitted until you press Enter. **Terminal ▸ New Terminal Window** (see [Terminal menu](#terminal-menu)) opens a dedicated window with the same multi-session tabs, `Cmd+<number>` tab switching, and shells starting at the project root.The shells run at full user privilege. To turn the terminal off for a project on this machine, use **Settings ▸ Terminal** or set `terminal.enabled: false` in `.ok/local/config.yml` (see the [configuration reference](/docs/reference/configuration)); the setting is project-local, never shared via git or sync, and not agent-settable — only a human can flip it.@@ -203,7 +203,8 @@ Keyboard shortcuts (use `Ctrl` on Windows / Linux in place of `Cmd`, unless the| `Cmd+K` | Command palette — or, with text selected in the visual editor, add a link (cursor inside a link edits it). || `Cmd+Option+S` | Show / Hide the file sidebar (left). Matches Apple's standard sidebar accelerator. || `Cmd+Option+B` | Show / Hide the document panel (right). Matches VS Code's Secondary Side Bar accelerator. |-| `Cmd+J` | Show / Hide the docked terminal (desktop app). |+| `Cmd+J` | Show / Hide the docked terminal (desktop app). With text selected, stages the passage into the AI CLI's input instead — nothing runs until you press Enter. |+| `Cmd+Shift+J` | Open an additional terminal tab (desktop app). With text selected, stages the passage into the new tab's AI CLI input. || `Cmd+K` | Open the [command palette](#command-palette). || `Cmd+L` | Open and focus the [Ask AI](#ask-ai) composer (desktop app). || `Cmd+F` | Find in the visual editor. |@@ -250,7 +251,7 @@ Before the existing Zoom and Toggle Fullscreen items, the View menu gets:| --- | --- | --- || **Show / Hide Sidebar** | `Cmd+Option+S` | Toggles the file sidebar (left). Label flips between Show and Hide based on current state, matching Finder. || **Show / Hide Document Panel** | `Cmd+Option+B` | Toggles the document panel (right). |-| **Show / Hide Terminal** | `Cmd+J` | Toggles the docked terminal. |+| **Show / Hide Terminal** | `Cmd+J` | Toggles the docked terminal. With editor text selected, stages the selection into the AI CLI's input instead of toggling. || **Show Hidden Files** | `Cmd+Shift+.` | `appearance.sidebar.showHiddenFiles`; same toggle as the sidebar's right-click menu. || **Expand All** | (none) | Expands every folder in the tree. Hidden when nothing is collapsed. || **Collapse All** | (none) | Collapses every folder in the tree. Hidden when nothing is expanded. |diff --git a/packages/app/src/components/EditorPane.dom.test.tsx b/packages/app/src/components/EditorPane.dom.test.tsxindex cb678f787..b6a014ba1 100644--- a/packages/app/src/components/EditorPane.dom.test.tsx+++ b/packages/app/src/components/EditorPane.dom.test.tsx@@ -2,7 +2,52 @@ import { afterEach, describe, expect, mock, test } from 'bun:test';import { act, cleanup, render, screen } from '@testing-library/react';import userEvent from '@testing-library/user-event';import { isMacOS } from '@tiptap/core';-import type { ReactNode } from 'react';+import { type ReactNode, useEffect } from 'react';+import { publishSelectionContext } from '@/editor/selection-context';+import type { EditorSurface } from '@/editor/selection-stats';+import { subscribeToActiveTerminalInput } from './handoff/terminal-input-events';++// The doc the mocked DocumentContext reports (see the useDocumentContext mock).+const TEST_DOC = 'docs/notes';++// Controls what the mocked TerminalSessionsHost reports via+// `onActiveSessionCliChange` — i.e. whether the active terminal tab is a running+// AI CLI (drives EditorPane's ⌘J inject-vs-launch decision).+let mockActiveIsCli = false;++// Seed / clear the shared selection snapshot registry EditorPane reads for the+// ⌘J / ⇧⌘J selection-paste path. Seed both body surfaces so the test is+// independent of the default editor mode.+function seedSelection(markdown: string): void {+ for (const surface of ['wysiwyg', 'source'] as EditorSurface[]) {+ publishSelectionContext(TEST_DOC, surface, {+ surface,+ docName: TEST_DOC,+ markdown,+ charLen: markdown.length,+ lineCount: 1,+ });+ }+}+function clearSelection(): void {+ publishSelectionContext(TEST_DOC, 'wysiwyg', null);+ publishSelectionContext(TEST_DOC, 'source', null);+}++// Collect the raw-inject requests EditorPane dispatches to a running CLI (the+// host that consumes them is mocked here).+function captureActiveTerminalInput(): { texts: string[]; stop: () => void } {+ const texts: string[] = [];+ const stop = subscribeToActiveTerminalInput((text) => texts.push(text));+ return { texts, stop };+}++function shiftJKeydownInit(): KeyboardEventInit {+ const init: KeyboardEventInit = { key: 'j', shiftKey: true, cancelable: true, bubbles: true };+ if (isMacOS()) init.metaKey = true;+ else init.ctrlKey = true;+ return init;+}mock.module('@lingui/react/macro', () => ({Trans: ({ children }: { children: ReactNode }) => <>{children}</>,@@ -63,16 +108,26 @@ mock.module('./TerminalSessionsHost', () => ({TerminalSessionsHost: ({visible,launch,+ onActiveSessionCliChange,}: {visible?: boolean;- launch?: { nonce: number } | null;- }) => (- <div- data-testid="terminal-dock"- data-visible={String(visible)}- data-launch-nonce={launch ? String(launch.nonce) : 'none'}- />- ),+ launch?: { nonce: number; stagePaste?: string } | null;+ onActiveSessionCliChange?: (isCli: boolean) => void;+ }) => {+ // Report the test-controlled CLI-active state up, as the real host does from+ // its active session's launch descriptor.+ useEffect(() => {+ onActiveSessionCliChange?.(mockActiveIsCli);+ }, [onActiveSessionCliChange]);+ return (+ <div+ data-testid="terminal-dock"+ data-visible={String(visible)}+ data-launch-nonce={launch ? String(launch.nonce) : 'none'}+ data-launch-stage={launch?.stagePaste ?? 'none'}+ />+ );+ },}));const terminalOpenedCalls: true[] = [];@@ -283,6 +338,8 @@ describe('EditorPane terminal dock wiring', () => {cleanup();delete (window as { okDesktop?: unknown }).okDesktop;terminalOpenedCalls.length = 0;+ clearSelection();+ mockActiveIsCli = false;});test('web host renders the editor chrome without a terminal dock', async () => {@@ -489,4 +546,119 @@ describe('EditorPane terminal dock wiring', () => {expect(event.defaultPrevented).toBe(false);});++ test('desktop: ⇧⌘J with no selection opens a new chat (launch intent, no staged text)', async () => {+ (window as { okDesktop?: unknown }).okDesktop = makeOkDesktopStub().stub;+ await renderEditorPane();+ const input = captureActiveTerminalInput();++ act(() => {+ window.dispatchEvent(new KeyboardEvent('keydown', shiftJKeydownInit()));+ });+ input.stop();++ // launchNewChat: the dock reveals + a promptless launch intent, nothing staged.+ const dock = screen.getByTestId('terminal-dock');+ expect(dock.getAttribute('data-visible')).toBe('true');+ expect(dock.getAttribute('data-launch-nonce')).toBe('1');+ expect(dock.getAttribute('data-launch-stage')).toBe('none');+ expect(input.texts).toEqual([]);+ });++ test('desktop: ⇧⌘J with a selection launches a NEW CLI tab with the passage STAGED (not sent)', async () => {+ (window as { okDesktop?: unknown }).okDesktop = makeOkDesktopStub().stub;+ await renderEditorPane();+ seedSelection('some highlighted text');+ const input = captureActiveTerminalInput();++ act(() => {+ window.dispatchEvent(new KeyboardEvent('keydown', shiftJKeydownInit()));+ });+ input.stop();++ // A launch intent that STAGES the passage (no raw inject, nothing auto-run).+ const dock = screen.getByTestId('terminal-dock');+ expect(dock.getAttribute('data-visible')).toBe('true');+ expect(dock.getAttribute('data-launch-nonce')).toBe('1');+ expect(dock.getAttribute('data-launch-stage')).toContain('some highlighted text');+ // Trailing soft newlines land the CLI caret on a blank line below the passage.+ expect(dock.getAttribute('data-launch-stage')?.endsWith('\n\n')).toBe(true);+ expect(input.texts).toEqual([]);+ });++ test('desktop: ⇧⌘J claims the event (preventDefault)', async () => {+ (window as { okDesktop?: unknown }).okDesktop = makeOkDesktopStub().stub;+ await renderEditorPane();+ const event = new KeyboardEvent('keydown', shiftJKeydownInit());+ act(() => {+ window.dispatchEvent(event);+ });+ expect(event.defaultPrevented).toBe(true);+ });++ test('web host: ⇧⌘J is a no-op (no terminal to open)', async () => {+ await renderEditorPane();+ const event = new KeyboardEvent('keydown', shiftJKeydownInit());+ window.dispatchEvent(event);+ expect(event.defaultPrevented).toBe(false);+ expect(screen.queryByTestId('terminal-dock')).toBeNull();+ });++ test('desktop: ⌘J with a selection injects into the ACTIVE running CLI (no toggle, no launch)', async () => {+ mockActiveIsCli = true;+ const desk = makeOkDesktopStub();+ (window as { okDesktop?: unknown }).okDesktop = desk.stub;+ await renderEditorPane();+ seedSelection('run the build');+ const input = captureActiveTerminalInput();++ // ⌘J arrives via the OS-captured menu accelerator → the toggle-terminal action.+ act(() => desk.dispatchMenuAction('toggle-terminal'));+ input.stop();++ // Active tab is a running CLI → write the passage into it (reuse), reveal, no+ // launch intent.+ const dock = screen.getByTestId('terminal-dock');+ expect(input.texts).toHaveLength(1);+ expect(input.texts[0]).toContain('run the build');+ // Trailing soft newlines land the CLI caret on a blank line below the passage.+ expect(input.texts[0]?.endsWith('\n\n')).toBe(true);+ expect(dock.getAttribute('data-launch-nonce')).toBe('none');+ expect(dock.getAttribute('data-visible')).toBe('true');+ });++ test('desktop: ⌘J with a selection but a bare-shell active tab STAGES into a new CLI instead', async () => {+ mockActiveIsCli = false;+ const desk = makeOkDesktopStub();+ (window as { okDesktop?: unknown }).okDesktop = desk.stub;+ await renderEditorPane();+ seedSelection('run the build');+ const input = captureActiveTerminalInput();++ act(() => desk.dispatchMenuAction('toggle-terminal'));+ input.stop();++ // No running CLI in the active tab → launch a new CLI and STAGE the passage+ // into it, rather than typing a multi-line prompt into a bare shell.+ const dock = screen.getByTestId('terminal-dock');+ expect(input.texts).toEqual([]);+ expect(dock.getAttribute('data-launch-nonce')).toBe('1');+ expect(dock.getAttribute('data-launch-stage')).toContain('run the build');+ expect(dock.getAttribute('data-launch-stage')?.endsWith('\n\n')).toBe(true);+ });++ test('desktop: ⌘J with no selection still toggles and stages nothing', async () => {+ const desk = makeOkDesktopStub();+ (window as { okDesktop?: unknown }).okDesktop = desk.stub;+ await renderEditorPane();+ const input = captureActiveTerminalInput();++ act(() => desk.dispatchMenuAction('toggle-terminal'));+ input.stop();++ const dock = screen.getByTestId('terminal-dock');+ expect(dock.getAttribute('data-visible')).toBe('true');+ expect(dock.getAttribute('data-launch-nonce')).toBe('none');+ expect(input.texts).toEqual([]);+ });});diff --git a/packages/app/src/components/EditorPane.tsx b/packages/app/src/components/EditorPane.tsxindex 10d00daf2..1c61df6e0 100644--- a/packages/app/src/components/EditorPane.tsx+++ b/packages/app/src/components/EditorPane.tsx@@ -1,8 +1,9 @@import type { TerminalCli } from '@inkeep/open-knowledge-core';-import { useEffect, useRef, useState } from 'react';+import { useEffect, useEffectEvent, useRef, useState } from 'react';import { TagDialog } from '@/editor/components/TagDialog';import { useDocumentContext } from '@/editor/DocumentContext';import { RAW_MDX_NAV_EVENT, type RawMdxNavDetail } from '@/editor/extensions/raw-mdx-nav-event';+import { getSelectionContext } from '@/editor/selection-context';import { rememberPendingSourceNavigation } from '@/editor/source-editor-navigation';import { type EditorModeValue, useEditorMode } from '@/editor/use-editor-mode';import { useGitSyncStatus } from '@/hooks/use-git-sync-status';@@ -26,6 +27,8 @@ import { shouldShowAutoSyncOnboarding } from './auto-sync-onboarding-gate';import { type PanelTab, TABS } from './DocPanel';import { EditorArea, type TerminalPlacement } from './EditorArea';import { EditorHeader } from './EditorHeader';+import { composeTerminalSelectionPaste } from './handoff/compose-terminal-selection';+import { requestActiveTerminalInput } from './handoff/terminal-input-events';import { subscribeToTerminalLaunchRequests } from './handoff/terminal-launch-events';import { TerminalSessionsHost } from './TerminalSessionsHost';@@ -41,6 +44,13 @@ export interface TerminalLaunchIntent {readonly prompt: string | null;readonly cli: TerminalCli;readonly nonce: number;+ /** Text to write into the launched CLI's input once it is up — NOT submitted.+ * Used by the ⌘J/⇧⌘J selection-send so the passage is staged for the user to+ * add to and send themselves. `prompt` stays null so nothing auto-runs.+ * Consumed by TerminalPanel, gated on the CLI bake actually happening: a+ * preflight-suppressed launch (bare-shell fallback) drops it, because staged+ * text in a raw shell would execute line by line. */+ readonly stagePaste?: string;}export type EditorMode = EditorModeValue;@@ -132,12 +142,20 @@ export function EditorPane({ onOpenSearch }: EditorPaneProps = {}) {// one, reveal the dock, and thread a promptless one-shot intent through the// same nonce-dedup + hide-clear path as "Open in terminal". Distinct from the// prompt-composing `subscribeToTerminalLaunchRequests` path below — New chat- // needs no doc scope.- function launchNewChat(cli?: TerminalCli) {+ // needs no doc scope. `stagePaste` (the ⌘J/⇧⌘J selection-send) rides the+ // intent so the session panel writes it into the freshly-launched CLI's input+ // once its TUI settles — never submitted, and `prompt` stays null so nothing+ // auto-runs (see the TerminalLaunchIntent JSDoc for the bake gate).+ function launchNewChat(cli?: TerminalCli, stagePaste?: string) {const resolvedCli = cli ?? resolveDefaultCli(loadStickyAgent(), installedClis);setTerminalVisible(true);launchNonceRef.current += 1;- setTerminalLaunch({ prompt: null, cli: resolvedCli, nonce: launchNonceRef.current });+ setTerminalLaunch({+ prompt: null,+ cli: resolvedCli,+ nonce: launchNonceRef.current,+ stagePaste,+ });}// Reveal the docked terminal and, if no session exists yet, seed a first one.@@ -185,14 +203,58 @@ export function EditorPane({ onOpenSearch }: EditorPaneProps = {}) {return () => window.removeEventListener(RAW_MDX_NAV_EVENT, onRawMdxNav);}, [activeDocName]);+ // Whether the ACTIVE terminal tab is a running AI CLI (reported up by the host).+ // The ⌘J selection-send reads this to inject-into-running-CLI vs launch-new-CLI.+ const activeSessionIsCliRef = useRef(false);++ // ⌘J / ⇧⌘J with an editor selection STAGE that selection into an AI CLI's input+ // in the terminal instead of toggling — never submitted, so the user can add+ // context and send it themselves. Reads the debounced selection snapshot for the+ // active doc + current mode (the same registry BottomComposer reads — no editor+ // instance needed, so it works even from the OS-captured ⌘J menu accelerator)+ // and composes the same grounded prompt the Ask-AI selection button sends.+ // - ⌘J into a tab that is ALREADY running a CLI → write the passage straight+ // into its input (no screen wipe) via the reuse channel, and focus it.+ // - otherwise (⇧⌘J, or ⌘J into a bare shell / closed terminal) → launch a NEW+ // promptless CLI tab and stage the passage into its input once it is up.+ // (Baking the prompt as a CLI arg would auto-run it; a raw write into a bare+ // shell would mangle a multi-line prompt — staging into a live CLI avoids+ // both.)+ // Returns true when a selection was staged (caller skips the toggle / new-tab+ // fallback). No-ops on the web host (no terminal).+ function sendSelectionToTerminal(newTab: boolean): boolean {+ if (!terminalAvailable || activeDocName == null) return false;+ const snapshot = getSelectionContext(activeDocName, editorMode);+ const selectionMarkdown = snapshot?.markdown ?? '';+ if (selectionMarkdown.trim() === '') return false;+ // Trailing soft newlines (\n, not \r — no submit) drop the CLI input caret+ // onto a blank line below the staged passage.+ const staged = `${composeTerminalSelectionPaste(activeDocName, selectionMarkdown)}\n\n`;+ if (!newTab && activeSessionIsCliRef.current) {+ setTerminalVisible(true);+ requestActiveTerminalInput(staged);+ } else {+ launchNewChat(undefined, staged);+ }+ return true;+ }+ // Effect Events so the once-bound key/menu listeners below read the current+ // closures (fresh activeDocName / editorMode / installedClis) without+ // re-subscribing.+ const sendSelectionToTerminalEvent = useEffectEvent(sendSelectionToTerminal);+ const launchNewChatEvent = useEffectEvent(() => launchNewChat());+// Bottom-terminal toggle, dual-wired like the DocPanel: on desktop the// View → Terminal item's ⌘J/Ctrl+J accelerator is OS-captured and dispatches// `toggle-terminal`; the web host has no menu, so a window keydown stands in.+ // With a selection, ⌘J sends it to the terminal (reusing the active tab)+ // instead of toggling.useEffect(() => {const bridge = window.okDesktop;if (bridge == null) return;return bridge.onMenuAction((action) => {if (action === 'toggle-terminal') {+ if (sendSelectionToTerminalEvent(false)) return;setTerminalVisible((visible) => !visible);} else if (action === 'new-terminal') {// Terminal menu "New Terminal": reveal the dock (it never hides, unlike@@ -208,6 +270,7 @@ export function EditorPane({ onOpenSearch }: EditorPaneProps = {}) {function handleKeyDown(event: KeyboardEvent) {if (matchesKeyboardShortcut(event, 'toggle-terminal-panel')) {event.preventDefault();+ if (sendSelectionToTerminalEvent(false)) return;setTerminalVisible((visible) => !visible);}}@@ -216,6 +279,22 @@ export function EditorPane({ onOpenSearch }: EditorPaneProps = {}) {return () => window.removeEventListener('keydown', handleKeyDown, { capture: true });}, []);+ // ⇧⌘J / Ctrl+Shift+J: open an ADDITIONAL terminal tab. With a selection, send it+ // to a NEW CLI tab (always new, never reusing the active one); otherwise open a+ // new chat with the preferred CLI (the "+ New chat" default). Renderer-owned on+ // both hosts (no menu item claims ⇧⌘J), capture-phase so a focused xterm can't+ // swallow it. No-ops on the web host (no terminal surface).+ useEffect(() => {+ if (!terminalAvailable) return;+ function handleKeyDown(event: KeyboardEvent) {+ if (!matchesKeyboardShortcut(event, 'new-terminal-tab')) return;+ event.preventDefault();+ if (!sendSelectionToTerminalEvent(true)) launchNewChatEvent();+ }+ window.addEventListener('keydown', handleKeyDown, { capture: true });+ return () => window.removeEventListener('keydown', handleKeyDown, { capture: true });+ }, [terminalAvailable]);+// "Open in terminal" launch — a handoff-menu click fires a window event with// the composed prompt. Open the dock (the terminal is allowed by default; the// gate only blocks a project explicitly opted out) AND carry the prompt to the@@ -376,6 +455,9 @@ export function EditorPane({ onOpenSearch }: EditorPaneProps = {}) {dockPosition={terminalDock}onToggleDock={toggleTerminalDock}onHasSessionsChange={setHasSessions}+ onActiveSessionCliChange={(isCli) => {+ activeSessionIsCliRef.current = isCli;+ }}/>) : null}<AuthModaldiff --git a/packages/app/src/components/TerminalDock.dom.test.tsx b/packages/app/src/components/TerminalDock.dom.test.tsxindex 942774bae..8afacfd72 100644--- a/packages/app/src/components/TerminalDock.dom.test.tsx+++ b/packages/app/src/components/TerminalDock.dom.test.tsx@@ -16,6 +16,7 @@*/import { afterEach, beforeEach, describe, expect, mock, test } from 'bun:test';+import type { TerminalCli } from '@inkeep/open-knowledge-core';import { act, cleanup, render, screen, waitFor, within } from '@testing-library/react';import userEvent from '@testing-library/user-event';import { useEffect, useRef, useState } from 'react';@@ -151,6 +152,8 @@ mock.module('@/lib/terminal-height-store', () => ({const { TerminalDock } = await import('./TerminalDock');const { TerminalSessionsHost } = await import('./TerminalSessionsHost');+// After the mock.module block (a static import would load the real xterm).+const { STAGE_PASTE_SETTLE_MS } = await import('./TerminalPanel');function makeBridge() {const menuHandlers: Array<(action: string) => void> = [];@@ -200,8 +203,25 @@ function makeBridge() {// invariant EditorArea enforces). Session behavior is bottom-dock only —// right-dock placement is covered by EditorArea + the live-Electron smoke; the// `dock` knob here exercises only the shell's handle gating across positions.-// biome-ignore lint/suspicious/noExplicitAny: test harness props-function DockHarness({ v, l, onVisibleChange, bridge, onReveal, dock = 'bottom' }: any) {+// Structural mirror of TerminalLaunchIntent (EditorPane) so tests can express+// promptless / staged launches without casts.+type TestLaunch = {+ prompt: string | null;+ nonce: number;+ cli?: TerminalCli;+ stagePaste?: string;+};++function DockHarness({+ v,+ l,+ onVisibleChange,+ bridge,+ onReveal,+ dock = 'bottom',+ onActiveSessionCliChange,+ // biome-ignore lint/suspicious/noExplicitAny: test harness props+}: any) {const [bottomContainer, setBottomContainer] = useState<HTMLDivElement | null>(null);const [editorRegionEl, setEditorRegionEl] = useState<HTMLDivElement | null>(null);return (@@ -226,6 +246,7 @@ function DockHarness({ v, l, onVisibleChange, bridge, onReveal, dock = 'bottom'onRequestEditorFocus={() => editorRegionEl?.focus()}dockPosition={dock}onToggleDock={() => {}}+ onActiveSessionCliChange={onActiveSessionCliChange}/></TooltipProvider>);@@ -233,16 +254,13 @@ function DockHarness({ v, l, onVisibleChange, bridge, onReveal, dock = 'bottom'function renderDock(visible: boolean,- launch?: { prompt: string; nonce: number; cli?: string } | null,+ launch?: TestLaunch | null,onReveal?: () => void,+ onActiveSessionCliChange?: (isCli: boolean) => void,) {const onVisibleChange = mock((_v: boolean) => {});const { bridge, create, kill, input, viewMenuPushes, dispatchMenuAction } = makeBridge();- const ui = (- v: boolean,- l?: { prompt: string; nonce: number; cli?: string } | null,- dock?: TerminalDockPosition,- ) => (+ const ui = (v: boolean, l?: TestLaunch | null, dock?: TerminalDockPosition) => (<DockHarnessv={v}l={l ?? null}@@ -250,6 +268,7 @@ function renderDock(bridge={bridge}onReveal={onReveal}dock={dock ?? 'bottom'}+ onActiveSessionCliChange={onActiveSessionCliChange}/>);const utils = render(ui(visible, launch));@@ -261,11 +280,8 @@ function renderDock(input,viewMenuPushes,dispatchMenuAction,- rerender: (- v: boolean,- l?: { prompt: string; nonce: number; cli?: string } | null,- dock?: TerminalDockPosition,- ) => utils.rerender(ui(v, l, dock)),+ rerender: (v: boolean, l?: TestLaunch | null, dock?: TerminalDockPosition) =>+ utils.rerender(ui(v, l, dock)),};}@@ -850,6 +866,69 @@ describe('TerminalDock multi-session', () => {expect(activePanelId()).toBe(runningId);});+ test('reports whether the active tab is a CLI session (drives ⌘J inject-vs-launch)', () => {+ // Seeded from a CLI launch → active tab is a CLI session.+ const cliReports: boolean[] = [];+ const { unmount } = renderDock(+ true,+ { prompt: 'work', cli: 'claude', nonce: 1 },+ undefined,+ (isCli) => cliReports.push(isCli),+ );+ expect(cliReports.at(-1)).toBe(true);+ unmount();+ cliReports.length = 0;++ // A bare-shell seed (no launch) → active tab is NOT a CLI session.+ renderDock(true, null, undefined, (isCli) => cliReports.push(isCli));+ expect(cliReports.at(-1)).toBe(false);+ });++ test('CLI-active report tracks tab SWITCHES (CLI tab ↔ bare-shell tab)', async () => {+ // The transition is the load-bearing case: a stale `true` after switching+ // to a bare-shell tab would route the next ⌘J selection-send through the+ // raw-inject path into that bare shell — the mangling the inject-vs-launch+ // decision exists to avoid.+ const user = userEvent.setup();+ const cliReports: boolean[] = [];+ renderDock(true, { prompt: 'work', cli: 'claude', nonce: 1 }, undefined, (isCli) =>+ cliReports.push(isCli),+ );+ expect(cliReports.at(-1)).toBe(true);++ // Add a bare-shell tab (becomes active) → report flips false.+ await addTerminalTab(user);+ expect(cliReports.at(-1)).toBe(false);++ // Switch back to the CLI tab → report flips true again.+ await user.click(screen.getByRole('tab', { name: 'Terminal 1' }));+ expect(cliReports.at(-1)).toBe(true);+ });++ test('a stagePaste launch opens its own tab; the HOST never types the passage (staging is TerminalPanel-owned, bake-gated)', async () => {+ const view = renderDock(false);+ // Open a promptless CLI session carrying a staged selection (the ⌘J/⇧⌘J+ // launch-with-selection path). prompt:null so nothing is baked/auto-run.+ act(() =>+ view.rerender(true, {+ prompt: null,+ cli: 'claude',+ nonce: 1,+ stagePaste: 'work on @notes.md — the selected passage',+ }),+ );++ // The intent routes to a session tab; the staged write itself happens inside+ // TerminalPanel AFTER its CLI bake succeeds (TerminalPanel.launch.dom.test),+ // never from the host — a host-side write couldn't know whether the bake was+ // suppressed into a bare shell, where staged `\n`s would execute.+ expect(screen.getAllByTestId('terminal-session')).toHaveLength(1);+ // Waited past the panel's settle window (derived from the production+ // constant so a grown window can't turn this into a vacuous pass).+ await new Promise((resolve) => setTimeout(resolve, STAGE_PASTE_SETTLE_MS + 200));+ expect(view.input).not.toHaveBeenCalled();+ });+test('a launch before the seed terminal PTY is live also opens its own tab', () => {const view = renderDock(true);expect(screen.getAllByTestId('terminal-session')).toHaveLength(1);diff --git a/packages/app/src/components/TerminalPanel.launch.dom.test.tsx b/packages/app/src/components/TerminalPanel.launch.dom.test.tsxindex 3db3c8d49..e7bc96cc9 100644--- a/packages/app/src/components/TerminalPanel.launch.dom.test.tsx+++ b/packages/app/src/components/TerminalPanel.launch.dom.test.tsx@@ -133,7 +133,7 @@ function makeBridge(preflight: ClaudeReadiness = WIRED, cliReadiness: CliReadine};}-const { TerminalPanel } = await import('./TerminalPanel');+const { TerminalPanel, STAGE_PASTE_SETTLE_MS } = await import('./TerminalPanel');/** The `launchCommand` baked into the (single) `create` call, or undefined when* none was passed (plain shell). The launch's only sanctioned transport. */@@ -220,6 +220,46 @@ describe('TerminalPanel "Open in terminal" launch (baked into the PTY spawn)', (expect(launchInputWrites(terminal.input)).toEqual([]);});+ test('a launch carrying stagePaste writes it into the CLI input after the TUI settles — no submit', async () => {+ const { bridge, terminal } = makeBridge(WIRED);+ const staged = 'work on @notes.md — the selected passage\n\n';+ render(+ <TerminalPanel+ bridge={bridge}+ launch={{ prompt: null, cli: 'claude', nonce: 1, stagePaste: staged }}+ />,+ );++ await waitFor(() => expect(terminal.create).toHaveBeenCalledTimes(1));+ // Promptless bake: bare `claude` (+ pre-approval), nothing auto-runs.+ expect(bakedLaunch(terminal.create)).toBe(`claude ${CLAUDE_PRE}`);+ // The staged passage lands via `input` after the settle beat — soft trailing+ // newlines intact, no `\r` anywhere (nothing submitted).+ await waitFor(() => expect(terminal.input).toHaveBeenCalledWith('pty-1', staged), {+ timeout: 2_000,+ });+ expect(terminal.input.mock.calls.every((c) => !(c[1] as string).includes('\r'))).toBe(true);+ });++ test('stagePaste is DROPPED when the bake was suppressed — staged text in the bare-shell fallback would execute', async () => {+ const { bridge, terminal } = makeBridge({ claude: 'not-found', mcp: 'needs-rewire' });+ render(+ <TerminalPanel+ bridge={bridge}+ launch={{ prompt: null, cli: 'claude', nonce: 1, stagePaste: 'echo pwned\n\n' }}+ />,+ );++ await waitFor(() => expect(terminal.create).toHaveBeenCalledTimes(1));+ // No bake — this PTY is a plain shell (the readiness banner explains why).+ expect(bakedLaunch(terminal.create)).toBeUndefined();+ // Wait past the settle window (derived from the production constant so this+ // can't rot into a vacuous pass if the window grows): nothing may be typed+ // into the bare shell, where each staged `\n` would execute as a command.+ await new Promise((resolve) => setTimeout(resolve, STAGE_PASTE_SETTLE_MS + 200));+ expect(terminal.input).not.toHaveBeenCalled();+ });+test('spawns a plain shell (no launchCommand) when claude is not found, and surfaces the banner', async () => {const { bridge, terminal } = makeBridge({ claude: 'not-found', mcp: 'needs-rewire' });render(<TerminalPanel bridge={bridge} launch={{ prompt: 'hi', cli: 'claude', nonce: 1 }} />);diff --git a/packages/app/src/components/TerminalPanel.tsx b/packages/app/src/components/TerminalPanel.tsxindex 71a6f093e..9590e2476 100644--- a/packages/app/src/components/TerminalPanel.tsx+++ b/packages/app/src/components/TerminalPanel.tsx@@ -37,6 +37,13 @@ import { nextWheelReports, sgrWheelReport, wheelReportPosition } from './termina*/const PTY_RESIZE_THROTTLE_MS = 100;+/** Settle beat between a staged-selection launch's PTY going live and the+ * `stagePaste` write — long enough for the CLI TUI's stdin reader to attach (a+ * write at raw PTY-live can race it). Exported so the dom tests derive their+ * waited-past-the-window negative assertions from the same value instead of a+ * hardcoded sibling that silently rots when this changes. */+export const STAGE_PASTE_SETTLE_MS = 500;+interface TerminalPanelProps {/** Desktop bridge — the panel is rendered only on the Electron host, where* `window.okDesktop` is present. */@@ -615,6 +622,8 @@ function TerminalSession({return undefined;};+ let stagePasteTimer: ReturnType<typeof setTimeout> | undefined;+void (async () => {// Reload rehydration: a tab restored from a surviving session carries its// ptyId. Adopt it (reconnect the live shell) rather than spawning a fresh@@ -700,10 +709,38 @@ function TerminalSession({}attachSession(result.ptyId);++ // Stage the ⌘J/⇧⌘J selection into the freshly-launched CLI's input — once,+ // and NOT submitted. Gated on the bake actually happening: when the+ // preflight suppressed `launchCommand`, this PTY is a BARE shell where+ // every staged `\n` would EXECUTE as a command — the exact mangling the+ // staging design exists to avoid — so the passage is dropped and the+ // missing-CLI / readiness banner explains why nothing arrived. The short+ // beat lets the TUI's stdin reader attach (a write at raw PTY-live can+ // race it); unmount cancels the timer.+ const staged = launch?.stagePaste;+ if (launch != null && launch.prompt != null && staged != null) {+ // `prompt` and `stagePaste` are mutually exclusive by the intent's+ // contract (the type doesn't forbid it — single producer today). A+ // future producer setting both would double-dispatch: the prompt+ // auto-runs at spawn AND the paste lands in the input. The baked+ // prompt wins; surface the contract violation instead of silently+ // double-writing.+ console.warn(+ '[terminal] TerminalLaunchIntent carried both prompt and stagePaste; dropping stagePaste',+ );+ } else if (launchCommand !== undefined && staged != null && staged !== '') {+ stagePasteTimer = setTimeout(() => {+ if (cancelled || ptyIdRef.current === null) return;+ bridge.terminal.input(ptyIdRef.current, staged);+ term.focus();+ }, STAGE_PASTE_SETTLE_MS);+ }})();return () => {cancelled = true;+ if (stagePasteTimer !== undefined) clearTimeout(stagePasteTimer);ptyIdRef.current = null;// This session no longer has a live PTY — clear it from the host's reuse// map so an "Ask AI" launch never writes into a torn-down shell.diff --git a/packages/app/src/components/TerminalSessionsHost.tsx b/packages/app/src/components/TerminalSessionsHost.tsxindex c18977d69..fdf6a6ff2 100644--- a/packages/app/src/components/TerminalSessionsHost.tsx+++ b/packages/app/src/components/TerminalSessionsHost.tsx@@ -119,6 +119,13 @@ interface TerminalSessionsHostProps {* button reads this to decide between spawning a first chat and merely* revealing the existing dock. */readonly onHasSessionsChange?: (hasSessions: boolean) => void;+ /** Reports whether the ACTIVE tab is an AI-CLI session (was launched with a+ * `cli`, e.g. a "New chat" / "Open with AI" tab) rather than a bare shell.+ * The ⌘J selection-send reads this to decide inject-into-running-CLI vs+ * launch-a-new-CLI (a raw prompt typed into a bare shell mangles). Proxy: the+ * session's launch descriptor — a bare shell the user manually `claude`'d into+ * reads as non-CLI, which is fine (it just starts a fresh CLI tab). */+ readonly onActiveSessionCliChange?: (isCli: boolean) => void;}/**@@ -142,6 +149,7 @@ export function TerminalSessionsHost({dockPosition,onToggleDock,onHasSessionsChange,+ onActiveSessionCliChange,}: TerminalSessionsHostProps) {const { t } = useLingui();@@ -648,6 +656,14 @@ export function TerminalSessionsHost({onHasSessionsChange?.(sessions.length > 0);}, [onHasSessionsChange, sessions.length]);+ // Report whether the active tab is a CLI session (see the prop doc). Derived in+ // render so the effect fires only on actual transitions, not on every session-+ // list mutation. EditorPane's ⌘J read decides inject-vs-launch off this.+ const activeSessionIsCli = sessions.find((s) => s.id === activeSessionId)?.launch?.cli != null;+ useEffect(() => {+ onActiveSessionCliChange?.(activeSessionIsCli);+ }, [onActiveSessionCliChange, activeSessionIsCli]);+// Return focus out of the hidden terminal so a keyboard user is never stranded.// Only acts when focus is actually inside the terminal.//diff --git a/packages/app/src/components/handoff/compose-terminal-selection.ts b/packages/app/src/components/handoff/compose-terminal-selection.tsnew file mode 100644index 000000000..242da63d9--- /dev/null+++ b/packages/app/src/components/handoff/compose-terminal-selection.ts@@ -0,0 +1,26 @@+import { composeSelectionPrompt } from '@inkeep/open-knowledge-core';+import { docNameToRelativePath } from '@/lib/workspace-paths';++/**+ * Grounded selection paste for a terminal CLI: the doc named as an `@`-mention+ * plus the passage, via the same `composeSelectionPrompt` the bottom composer+ * uses — never raw text a running agent can't place. Shared by every+ * selection→terminal entry point (Ask-AI bubble button, ⌘J/⇧⌘J selection-send)+ * so they stay byte-identical.+ *+ * NOTE: there's no URL to budget in a terminal paste, so `target` only tunes+ * composeSelectionPrompt's inline-vs-locus threshold — and only Cursor+ * double-encodes, so every non-Cursor target (claude-code among them) shares+ * the same widest threshold: inline unless huge. Any target is correct here; it+ * does NOT assume the running CLI. Derive it from the live terminal CLI only if+ * that threshold ever matters (e.g. composeSelectionPrompt gains per-target+ * content).+ */+export function composeTerminalSelectionPaste(docName: string, selectionMarkdown: string): string {+ return composeSelectionPrompt({+ relativePath: docNameToRelativePath(docName),+ instruction: '',+ selectionMarkdown,+ target: 'claude-code',+ });+}diff --git a/packages/app/src/editor/bubble-menu/EditWithAiBubbleButton.tsx b/packages/app/src/editor/bubble-menu/EditWithAiBubbleButton.tsxindex 2a4fbf5b1..e70e88b29 100644--- a/packages/app/src/editor/bubble-menu/EditWithAiBubbleButton.tsx+++ b/packages/app/src/editor/bubble-menu/EditWithAiBubbleButton.tsx@@ -26,19 +26,18 @@* share exactly one open+focus implementation rather than duplicating it.*/-import { composeSelectionPrompt } from '@inkeep/open-knowledge-core';import { Trans } from '@lingui/react/macro';import { isMacOS } from '@tiptap/core';import type { Editor } from '@tiptap/react';import { Sparkles } from 'lucide-react';import { type ReactNode, useEffect } from 'react';import { emitOpenAskAiComposer } from '@/components/ask-ai-composer-events';+import { composeTerminalSelectionPaste } from '@/components/handoff/compose-terminal-selection';import { requestActiveTerminalInput } from '@/components/handoff/terminal-input-events';import { Button } from '@/components/ui/button';import { Separator } from '@/components/ui/separator';import { useIsEmbedded } from '@/hooks/use-is-embedded';import { matchesKeyboardShortcut } from '@/lib/keyboard-shortcuts';-import { docNameToRelativePath } from '@/lib/workspace-paths';import { serializeWysiwygSelection } from '../edit-with-ai-selection';import { getEditorDocName } from '../extensions/doc-context';@@ -106,11 +105,10 @@ function EditWithAiBubbleMenu({data-testid="edit-with-ai-bubble-button"className="gap-1 px-2 text-sm font-medium text-accent-foreground/80"// With a terminal open, send the selected passage into the active shell- // (the host decides reuse vs. composer-fallback) as a GROUNDED prompt:- // the doc named as an `@`-mention plus the passage, via the same- // `composeSelectionPrompt` the bottom composer uses — never raw text a- // running agent can't place. Caret-only / empty selection (or no active- // doc to ground against) has nothing to send, so open the composer.+ // (the host decides reuse vs. composer-fallback) as a GROUNDED prompt+ // (see `composeTerminalSelectionPaste`). Caret-only / empty selection+ // (or no active doc to ground against) has nothing to send, so open the+ // composer.//// Deferred a frame: the composer-fallback focus (and a terminal focus)// fires synchronously inside this click, before ProseMirror's own focus@@ -118,14 +116,6 @@ function EditWithAiBubbleMenu({// the doc and leave the composer unfocused. Reading the selection first// keeps the passage from the click moment even though the write runs// later. Mirrors LinkEditPopover's rAF focus.- //- // NOTE: there's no URL to budget in a terminal paste, so `target`- // only tunes composeSelectionPrompt's inline-vs-locus threshold — and- // only Cursor double-encodes, so every non-Cursor target (claude-code- // among them) shares the same widest threshold: inline unless huge. Any- // target is correct here; it does NOT assume the running CLI. Derive it- // from the live terminal CLI only if that threshold ever matters (e.g.- // composeSelectionPrompt gains per-target content).onClick={() => {const docName = getEditorDocName(editor);const selectionMarkdown = serializeWysiwygSelection(editor);@@ -134,14 +124,7 @@ function EditWithAiBubbleMenu({emitOpenAskAiComposer();return;}- requestActiveTerminalInput(- composeSelectionPrompt({- relativePath: docNameToRelativePath(docName),- instruction: '',- selectionMarkdown,- target: 'claude-code',- }),- );+ requestActiveTerminalInput(composeTerminalSelectionPaste(docName, selectionMarkdown));});}}>diff --git a/packages/app/src/lib/keyboard-shortcuts.test.ts b/packages/app/src/lib/keyboard-shortcuts.test.tsindex 2387dfc22..acbe2b187 100644--- a/packages/app/src/lib/keyboard-shortcuts.test.ts+++ b/packages/app/src/lib/keyboard-shortcuts.test.ts@@ -257,6 +257,54 @@ describe('keyboard shortcut registry', () => {).toBe(false);});+ test('formats the new-terminal-tab shortcut as Shift+Cmd/Ctrl + J', () => {+ expect(formatShortcut('new-terminal-tab', 'mac')).toBe('⇧⌘ J');+ expect(formatShortcut('new-terminal-tab', 'windowsLinux')).toBe('Ctrl Shift J');+ });++ test('matches new-terminal-tab on Shift+Cmd+J / Ctrl+Shift+J and stays clear of the ⌘J toggle', () => {+ // The chord fires with shift held, on each platform's mod key.+ expect(+ matchesKeyboardShortcut(+ { metaKey: true, ctrlKey: false, altKey: false, shiftKey: true, key: 'j' },+ 'new-terminal-tab',+ 'mac',+ ),+ ).toBe(true);+ expect(+ matchesKeyboardShortcut(+ { metaKey: false, ctrlKey: true, altKey: false, shiftKey: true, key: 'j' },+ 'new-terminal-tab',+ 'windowsLinux',+ ),+ ).toBe(true);+ // Without shift it is NOT the launch chord (that is the ⌘J toggle).+ expect(+ matchesKeyboardShortcut(+ { metaKey: true, ctrlKey: false, altKey: false, shiftKey: false, key: 'j' },+ 'new-terminal-tab',+ 'mac',+ ),+ ).toBe(false);+ // Wrong platform modifier: Ctrl+Shift+J on macOS must NOT match (mod is exact).+ expect(+ matchesKeyboardShortcut(+ { metaKey: false, ctrlKey: true, altKey: false, shiftKey: true, key: 'j' },+ 'new-terminal-tab',+ 'mac',+ ),+ ).toBe(false);+ // The reverse direction of mutual exclusion: Shift+⌘J does not trip the+ // toggle (plain-⌘J-vs-launch is the "Without shift" case above).+ expect(+ matchesKeyboardShortcut(+ { metaKey: true, ctrlKey: false, altKey: false, shiftKey: true, key: 'j' },+ 'toggle-terminal-panel',+ 'mac',+ ),+ ).toBe(false);+ });+test('matches tab shortcuts with strict modifiers', () => {expect(matchesKeyboardShortcut(diff --git a/packages/app/src/lib/keyboard-shortcuts.ts b/packages/app/src/lib/keyboard-shortcuts.tsindex d4e2682e1..d3de7d64f 100644--- a/packages/app/src/lib/keyboard-shortcuts.ts+++ b/packages/app/src/lib/keyboard-shortcuts.ts@@ -177,7 +177,7 @@ const KEYBOARD_SHORTCUT_DEFINITIONS = [id: 'toggle-terminal-panel',category: 'general',title: msg`Show or hide terminal`,- description: msg`Toggle the bottom terminal panel.`,+ description: msg`Toggle the bottom terminal panel. With text selected, stage it in the terminal's AI input instead.`,scope: msg`OK Desktop`,bindings: [{@@ -201,6 +201,23 @@ const KEYBOARD_SHORTCUT_DEFINITIONS = [},],},+ {+ // Sibling of ⌘J: opens an additional terminal tab. With text selected, that+ // selection is staged into the new tab. The shift matcher keeps this clear+ // of the ⌘J toggle, whose matcher rejects shift.+ id: 'new-terminal-tab',+ category: 'general',+ title: msg`New terminal tab`,+ description: msg`Open an additional terminal tab. With text selected, stage it in the new tab's AI input.`,+ scope: msg`OK Desktop`,+ bindings: [+ {+ mac: '⇧⌘ J',+ windowsLinux: 'Ctrl Shift J',+ match: { key: 'j', mod: true, shiftKey: true },+ },+ ],+ },{id: 'tab-new',category: 'navigation',@@ -813,8 +830,14 @@ export type KeyboardShortcutId = (typeof KEYBOARD_SHORTCUT_DEFINITIONS)[number][export const KEYBOARD_SHORTCUTS: readonly KeyboardShortcutDefinition[] =KEYBOARD_SHORTCUT_DEFINITIONS;+// Map lookup, not Array.find: `matchesKeyboardShortcut` callers include+// capture-phase window keydown listeners that run on every keypress.+const SHORTCUTS_BY_ID = new Map<KeyboardShortcutId, KeyboardShortcutDefinition>(+ KEYBOARD_SHORTCUT_DEFINITIONS.map((item) => [item.id, item]),+);+function getShortcut(id: KeyboardShortcutId): KeyboardShortcutDefinition {- const shortcut = KEYBOARD_SHORTCUTS.find((item) => item.id === id);+ const shortcut = SHORTCUTS_BY_ID.get(id);if (!shortcut) throw new Error(`Unknown keyboard shortcut: ${id}`);return shortcut;}diff --git a/packages/app/src/locales/en/messages.json b/packages/app/src/locales/en/messages.jsonindex ffe024b16..cbc7201dd 100644--- a/packages/app/src/locales/en/messages.json+++ b/packages/app/src/locales/en/messages.json@@ -1656,7 +1656,6 @@"f8jU-L": [["0"], "/", ["1"], " — ", ["2"]],"f9lQNJ": ["Adds a managed block to"],"fBHvBn": ["There's no project folder for this window, so a terminal can't start here."],- "fBaTkM": ["Toggle the bottom terminal panel."],"fG0X0e": ["Install ", ["brand"], " →"],"fIgqfQ": ["Reinstalling"],"fJgQHX": ["Failed to create file"],@@ -1858,6 +1857,7 @@["trimmedSlug"],"</0> already exists here. Saving creates a local copy that overrides it for this folder."],+ "k0vc0N": ["New terminal tab"],"k4CuuV": ["Ready-made folders and templates to get you started quickly. Select a pack to preview what gets created, then add it to your project."],@@ -2060,6 +2060,9 @@],"oBXkm2": ["Delete code block"],"oCHfGC": ["Level"],+ "oCNLN8": [+ "Toggle the bottom terminal panel. With text selected, stage it in the terminal's AI input instead."+ ],"oCZkaG": ["Copy path"],"oJl7eO": ["Unknown component: ", ["componentName"], " — source editable below"],"oKBnk5": ["More requests were blocked."],@@ -2216,6 +2219,9 @@"saYiIO": ["Path cannot contain null bytes"],"seeS6l": ["Setup OpenKnowledge in this folder?"],"shNd9t": ["Slash command menu"],+ "si3L24": [+ "Open an additional terminal tab. With text selected, stage it in the new tab's AI input."+ ],"skf5Ix": ["Indent or outdent source editor lines."],"snrVQ7": ["probe failed"],"ssuwjF": ["Branch"],diff --git a/packages/app/src/locales/en/messages.po b/packages/app/src/locales/en/messages.poindex b9b344f12..d8542c1fc 100644--- a/packages/app/src/locales/en/messages.po+++ b/packages/app/src/locales/en/messages.po@@ -4451,6 +4451,10 @@ msgstr "New template"msgid "New terminal"msgstr "New terminal"+#: src/lib/keyboard-shortcuts.ts+msgid "New terminal tab"+msgstr "New terminal tab"+#: src/components/NewWorktreeDialog.tsx#: src/components/ProjectSwitcher.tsxmsgid "New worktree"@@ -4862,6 +4866,10 @@ msgstr "Open activity panel for {tooltipName}"msgid "Open activity panel for {tooltipName}, editing {realCurrentDoc}"msgstr "Open activity panel for {tooltipName}, editing {realCurrentDoc}"+#: src/lib/keyboard-shortcuts.ts+msgid "Open an additional terminal tab. With text selected, stage it in the new tab's AI input."+msgstr "Open an additional terminal tab. With text selected, stage it in the new tab's AI input."+#: src/lib/keyboard-shortcuts.tsmsgid "Open an existing project folder from disk."msgstr "Open an existing project folder from disk."@@ -7322,8 +7330,8 @@ msgid "Toggle strikethrough formatting."msgstr "Toggle strikethrough formatting."#: src/lib/keyboard-shortcuts.ts-msgid "Toggle the bottom terminal panel."-msgstr "Toggle the bottom terminal panel."+msgid "Toggle the bottom terminal panel. With text selected, stage it in the terminal's AI input instead."+msgstr "Toggle the bottom terminal panel. With text selected, stage it in the terminal's AI input instead."#: src/lib/keyboard-shortcuts.tsmsgid "Toggle the left file sidebar."diff --git a/packages/app/src/locales/pseudo/messages.json b/packages/app/src/locales/pseudo/messages.jsonindex 0e29e4904..3f1a3d573 100644--- a/packages/app/src/locales/pseudo/messages.json+++ b/packages/app/src/locales/pseudo/messages.json@@ -1656,7 +1656,6 @@"f8jU-L": [["0"], "/", ["1"], " — ", ["2"]],"f9lQNJ": ["Àďďś à ḿàńàĝēď ƀĺōćķ ţō"],"fBHvBn": ["Ţĥēŕē'ś ńō ƥŕōĴēćţ ƒōĺďēŕ ƒōŕ ţĥĩś ŵĩńďōŵ, śō à ţēŕḿĩńàĺ ćàń'ţ śţàŕţ ĥēŕē."],- "fBaTkM": ["Ţōĝĝĺē ţĥē ƀōţţōḿ ţēŕḿĩńàĺ ƥàńēĺ."],"fG0X0e": ["Ĩńśţàĺĺ ", ["brand"], " →"],"fIgqfQ": ["Ŕēĩńśţàĺĺĩńĝ"],"fJgQHX": ["Ƒàĩĺēď ţō ćŕēàţē ƒĩĺē"],@@ -1858,6 +1857,7 @@["trimmedSlug"],"</0> àĺŕēàďŷ ēxĩśţś ĥēŕē. Śàvĩńĝ ćŕēàţēś à ĺōćàĺ ćōƥŷ ţĥàţ ōvēŕŕĩďēś ĩţ ƒōŕ ţĥĩś ƒōĺďēŕ."],+ "k0vc0N": ["Ńēŵ ţēŕḿĩńàĺ ţàƀ"],"k4CuuV": ["Ŕēàďŷ-ḿàďē ƒōĺďēŕś àńď ţēḿƥĺàţēś ţō ĝēţ ŷōũ śţàŕţēď ǫũĩćķĺŷ. Śēĺēćţ à ƥàćķ ţō ƥŕēvĩēŵ ŵĥàţ ĝēţś ćŕēàţēď, ţĥēń àďď ĩţ ţō ŷōũŕ ƥŕōĴēćţ."],@@ -2060,6 +2060,9 @@],"oBXkm2": ["Ďēĺēţē ćōďē ƀĺōćķ"],"oCHfGC": ["Ĺēvēĺ"],+ "oCNLN8": [+ "Ţōĝĝĺē ţĥē ƀōţţōḿ ţēŕḿĩńàĺ ƥàńēĺ. Ŵĩţĥ ţēxţ śēĺēćţēď, śţàĝē ĩţ ĩń ţĥē ţēŕḿĩńàĺ'ś ÀĨ ĩńƥũţ ĩńśţēàď."+ ],"oCZkaG": ["Ćōƥŷ ƥàţĥ"],"oJl7eO": ["Ũńķńōŵń ćōḿƥōńēńţ: ", ["componentName"], " — śōũŕćē ēďĩţàƀĺē ƀēĺōŵ"],"oKBnk5": ["Ḿōŕē ŕēǫũēśţś ŵēŕē ƀĺōćķēď."],@@ -2216,6 +2219,9 @@"saYiIO": ["Ƥàţĥ ćàńńōţ ćōńţàĩń ńũĺĺ ƀŷţēś"],"seeS6l": ["Śēţũƥ ŌƥēńĶńōŵĺēďĝē ĩń ţĥĩś ƒōĺďēŕ?"],"shNd9t": ["Śĺàśĥ ćōḿḿàńď ḿēńũ"],+ "si3L24": [+ "Ōƥēń àń àďďĩţĩōńàĺ ţēŕḿĩńàĺ ţàƀ. Ŵĩţĥ ţēxţ śēĺēćţēď, śţàĝē ĩţ ĩń ţĥē ńēŵ ţàƀ'ś ÀĨ ĩńƥũţ."+ ],"skf5Ix": ["Ĩńďēńţ ōŕ ōũţďēńţ śōũŕćē ēďĩţōŕ ĺĩńēś."],"snrVQ7": ["ƥŕōƀē ƒàĩĺēď"],"ssuwjF": ["ßŕàńćĥ"],diff --git a/packages/app/src/locales/pseudo/messages.po b/packages/app/src/locales/pseudo/messages.poindex bda56d974..9c077caa5 100644--- a/packages/app/src/locales/pseudo/messages.po+++ b/packages/app/src/locales/pseudo/messages.po@@ -4446,6 +4446,10 @@ msgstr ""msgid "New terminal"msgstr ""+#: src/lib/keyboard-shortcuts.ts+msgid "New terminal tab"+msgstr ""+#: src/components/NewWorktreeDialog.tsx#: src/components/ProjectSwitcher.tsxmsgid "New worktree"@@ -4857,6 +4861,10 @@ msgstr ""msgid "Open activity panel for {tooltipName}, editing {realCurrentDoc}"msgstr ""+#: src/lib/keyboard-shortcuts.ts+msgid "Open an additional terminal tab. With text selected, stage it in the new tab's AI input."+msgstr ""+#: src/lib/keyboard-shortcuts.tsmsgid "Open an existing project folder from disk."msgstr ""@@ -7317,7 +7325,7 @@ msgid "Toggle strikethrough formatting."msgstr ""#: src/lib/keyboard-shortcuts.ts-msgid "Toggle the bottom terminal panel."+msgid "Toggle the bottom terminal panel. With text selected, stage it in the terminal's AI input instead."msgstr ""#: src/lib/keyboard-shortcuts.tsdiff --git a/packages/desktop/tests/smoke/terminal-dock.e2e.ts b/packages/desktop/tests/smoke/terminal-dock.e2e.tsindex 8927fde73..c0022f018 100644--- a/packages/desktop/tests/smoke/terminal-dock.e2e.ts+++ b/packages/desktop/tests/smoke/terminal-dock.e2e.ts@@ -58,6 +58,21 @@ interface SeedOpts {claudeJson?: Record<string, unknown> | null;/** Put a fake executable `claude` on PATH (so the readiness probe resolves it). */fakeClaudeOnPath?: boolean;+ /** Like `fakeClaudeOnPath`, but the fake is a TUI stand-in that stays open+ * reading stdin (`exec cat`), so bytes staged into the launched CLI's PTY are+ * observable in xterm instead of landing in a post-exit shell. */+ fakeClaudeTui?: boolean;+ /** Skip the state.json last-project restore. A cold start then opens the+ * window from the argv deep-link alone, routed to its `doc=` — the restore+ * window otherwise wins the race and lands on the empty state with the+ * deep-link's doc dropped. Needed by tests that drive the DOC EDITOR. */+ skipRestoreState?: boolean;+ /** Pin the login-shell PATH to the bare system dirs via the test HOME's rc+ * files. `launchApp({ restrictPath })` alone is NOT enough for a+ * "claude absent" premise: /etc/zprofile's `path_helper` re-adds+ * /etc/paths.d dirs (incl. /opt/homebrew/bin, where a real `claude` cask+ * may live) ahead of the restricted env PATH. */+ pinRestrictedPath?: boolean;}interface Seed {@@ -91,30 +106,53 @@ function seed(prefix: string, opts: SeedOpts = {}): Seed {}let pathPrefix: string | null = null;- if (opts.fakeClaudeOnPath) {+ if (opts.fakeClaudeOnPath || opts.fakeClaudeTui) {const binDir = join(tmpHome, 'fakebin');mkdirSync(binDir, { recursive: true });const claudeBin = join(binDir, 'claude');- writeFileSync(claudeBin, '#!/bin/sh\necho "claude 0.0.0-fake"\n');+ // The TUI variant still answers `--version` and exits (keeps any probe that+ // executes the binary from hanging on `cat`).+ writeFileSync(+ claudeBin,+ opts.fakeClaudeTui+ ? '#!/bin/sh\nif [ "$1" = "--version" ]; then echo "claude 0.0.0-fake"; exit 0; fi\necho FAKE_CLAUDE_TUI_READY\nexec cat\n'+ : '#!/bin/sh\necho "claude 0.0.0-fake"\n',+ );chmodSync(claudeBin, 0o755);pathPrefix = binDir;+ // The PTY runs `$SHELL -l -i`, whose /etc/zprofile `path_helper` REORDERS+ // PATH: /etc/paths + /etc/paths.d dirs (incl. /opt/homebrew/bin, where a+ // real `claude` cask may live) jump AHEAD of the env's fakebin prefix.+ // Re-prepend fakebin from the test HOME's own rc files — they source after+ // path_helper, so the fake wins deterministically in probe and PTY alike.+ const prepend = `export PATH="${binDir}:$PATH"\n`;+ writeFileSync(join(tmpHome, '.zprofile'), prepend);+ writeFileSync(join(tmpHome, '.zshrc'), prepend);+ } else if (opts.pinRestrictedPath) {+ // No fakebin: pin the bare system PATH after path_helper so a host-machine+ // claude (e.g. the /opt/homebrew/bin cask) cannot leak into the probe.+ const pin = 'export PATH="/usr/bin:/bin:/usr/sbin:/sbin"\n';+ writeFileSync(join(tmpHome, '.zprofile'), pin);+ writeFileSync(join(tmpHome, '.zshrc'), pin);}const userDataDir = join(tmpHome, 'Library', 'Application Support', DESKTOP_PRODUCT_NAME);mkdirSync(userDataDir, { recursive: true });- writeFileSync(- join(userDataDir, 'state.json'),- JSON.stringify({- recentProjects: [- { path: projectDir, name: 'Terminal Smoke', lastOpenedAt: new Date().toISOString() },- ],- lastOpenedProject: projectDir,- versionPendingInstall: null,- lastSeenVersion: null,- lastSuccessfulCheckAt: null,- stuckHintShown: false,- }),- );+ if (!opts.skipRestoreState) {+ writeFileSync(+ join(userDataDir, 'state.json'),+ JSON.stringify({+ recentProjects: [+ { path: projectDir, name: 'Terminal Smoke', lastOpenedAt: new Date().toISOString() },+ ],+ lastOpenedProject: projectDir,+ versionPendingInstall: null,+ lastSeenVersion: null,+ lastSuccessfulCheckAt: null,+ stuckHintShown: false,+ }),+ );+ }return { tmpHome, userDataDir, projectDir, realProjectDir: projectDir, pathPrefix };}@@ -701,8 +739,9 @@ test.describe('Docked terminal — live Electron', () => {// Claude not on PATH surfaces the actionable not-found banner.test('QA-017 claude-not-found shows Get-Claude-Code banner', async ({ captureStderrFor }) => {- // No fake claude, restricted PATH → probe resolves not-found.- const s = seed('claude-missing', { consent: true });+ // No fake claude, restricted PATH pinned past path_helper → probe resolves+ // not-found even when the host machine has a real claude cask.+ const s = seed('claude-missing', { consent: true, pinRestrictedPath: true });track(s.tmpHome, s.projectDir);const app = await launchApp(s, { restrictPath: true });captureStderrFor(app, { cleanupDirs: [s.tmpHome, s.projectDir] });@@ -793,4 +832,82 @@ test.describe('Docked terminal — live Electron', () => {.poll(() => readTerminalText(page), { timeout: 15_000 }).toContain('marker=[OKRELOAD_SURVIVED_351]');});++ // ⌘J/⇧⌘J selection-send at the live-Electron rung: a REAL editor+ // selection is staged into a REAL CLI PTY — the composed flow the dom tests+ // pin only in slices (EditorPane decides against a mocked host; the host+ // stages against a mocked TerminalGate; here every layer between the keydown+ // and the PTY bytes is real). The fake `claude` is a TUI stand-in (`exec cat`)+ // that holds the PTY open reading stdin, so the staged bytes stay observable+ // in xterm. Residual only a live-claude run can pin: the real TUI treating+ // the trailing soft newlines as caret-move, not submit.+ test('⇧⌘J stages the editor selection into a new CLI tab; ⌘J (menu route) reuses it', async ({+ captureStderrFor,+ }) => {+ // Two-phase scenario (stage into a NEW CLI tab, then reuse the running one+ // via the menu route) walks doc-load + launch + two staged writes, so its+ // cumulative inner timeouts (~170s) exceed the suite's 150s CI outer budget+ // — opt into a per-test budget per the calibration invariant's mechanism.+ test.setTimeout(200_000);+ // skipRestoreState: with a state.json restore the cold-start window wins and+ // lands on the empty state, dropping the deep-link's `doc=` (and its collab+ // connection never recovers for a later hash-route). A restore-free cold+ // start opens the window from the deep link, routed to the doc.+ const s = seed('stage', { consent: true, fakeClaudeTui: true, skipRestoreState: true });+ track(s.tmpHome, s.projectDir);+ const app = await launchApp(s, { restrictPath: true });+ captureStderrFor(app, { cleanupDirs: [s.tmpHome, s.projectDir] });+ const page = await findEditorWindow(app);++ // Select the seeded doc's body in the real editor (ProseMirror select-all).+ // The selection-context registry publishes on a 120ms debounce+ // (SELECTION_STATS_DEBOUNCE_MS) — wait it out before firing the chord, or+ // the send reads an empty snapshot and degrades to a plain new-chat launch.+ // NOT `.ProseMirror.first()` — the Ask-AI composer is its own (empty)+ // ProseMirror; the doc editor is the non-composer one (sibling-smoke idiom).+ const editor = page.locator('.ProseMirror[contenteditable="true"]:not(.composer-prosemirror)');+ // The editor mounts before the CRDT doc body arrives — select-all on the+ // empty doc publishes an empty snapshot, so wait for the seeded text first.+ await expect(editor).toContainText('Seed document', { timeout: 30_000 });+ await editor.click();+ await page.keyboard.press('Meta+a');+ await expect+ .poll(() => page.evaluate(() => String(window.getSelection() ?? '')))+ .toContain('Seed document');+ await page.waitForTimeout(500);++ // ⇧⌘J: the renderer-owned chord (capture-phase window keydown — no menu item+ // claims it) opens a NEW CLI tab with the grounded passage staged into its+ // input once the PTY is live.+ await page.keyboard.press('Meta+Shift+j');+ await expect(terminalSection(page)).toBeVisible({ timeout: 15_000 });+ await waitForStatus(page, 'running', 25_000);+ // The staged bytes reached the CLI's PTY: the composed prompt names the doc+ // and carries the selected passage verbatim (short selections inline).+ await expect.poll(() => readTerminalText(page), { timeout: 20_000 }).toContain('start.md');+ await expect.poll(() => readTerminalText(page), { timeout: 15_000 }).toContain('Seed document');+ const terminalTabs = () => terminalSection(page).getByRole('tab');+ const tabsAfterLaunch = await terminalTabs().count();++ // Grow the doc with a distinguishing marker and re-select, then take the ⌘J+ // route via its View-menu accelerator item (the real menu→IPC→renderer+ // chain; the raw OS key capture itself is not synthesizable from Playwright,+ // same class as the deep-link Apple-Event limitation). With a selection and+ // the active tab a running CLI, the passage is written INTO that CLI —+ // the dock must not toggle away and no second tab may open.+ await editor.click();+ await page.keyboard.press('Meta+a');+ await page.keyboard.type('Reuse marker OKSTAGE_REUSE_742 body');+ await page.keyboard.press('Meta+a');+ await expect+ .poll(() => page.evaluate(() => String(window.getSelection() ?? '')))+ .toContain('OKSTAGE_REUSE_742');+ await page.waitForTimeout(500);+ await clickViewTerminalItem(app);+ await expect+ .poll(() => readTerminalText(page), { timeout: 15_000 })+ .toContain('OKSTAGE_REUSE_742');+ await expect(terminalSection(page)).toBeVisible();+ expect(await terminalTabs().count()).toBe(tabsAfterLaunch);+ });});