Beautiful, AI-native markdown IDE and LLM wiki
TypeScript 2nd-brainagent-skillsclaudecodexcompany-braindocsknowledge-knowledge-baseknowledge-managementllmllm-wikillm-wiki-karpathymarkdownmarkdown-editormdmdxnotespkmsecond-brainskills
fix(open-knowledge): honor preferred AI on every launch surface (#2921)
serafin-garcia6edbad6690c9
diff --git a/.changeset/preferred-ai-honored-by-every-surface.md b/.changeset/preferred-ai-honored-by-every-surface.mdnew file mode 100644index 000000000..37845b998--- /dev/null+++ b/.changeset/preferred-ai-honored-by-every-surface.md@@ -0,0 +1,13 @@+---+"@inkeep/open-knowledge": patch+---++Every surface that launches an AI now honors the preferred-AI setting. Choosing an in-app agent used to change the Ask composers and the sessions-dock New button and nothing else: revealing the dock, ⌘J, ⇧⌘J, the Problems panel's "Ask AI", the selection bubble, and the code-block Ask AI all opened a Claude terminal regardless.++The cause was one decision made in three places that could each only see part of the preference. The sessions host already resolved the whole space — in-app agent, terminal CLI, or bare shell, filtered by the Configure-agents toggles — but the editor pane resolved a CLI of its own before the host got a chance, and the Ask-AI channel ended in a hardcoded Claude launch. Resolution now happens only in the host: callers say what they want done, never which AI does it.++An agent now receives text exactly the way a terminal always has. Ask AI sends a finished instruction, so a fresh session runs it — the Problems panel's "Use AI", the selection bubble, and the code-block ask all fire on an agent just as they already did on a newly launched CLI. A ⌘J or ⇧⌘J selection send is raw material, so it is written and left unsent for you to extend. Reusing a session you already have open never submits on either side, matching what writing into a live CLI has always done.++That distinction also fixes a hazard on the terminal side: ⇧⌘J with a selection could auto-run the highlighted passage instead of staging it.++⌘J continues where you are, reusing a running CLI or an open agent thread; ⇧⌘J always opens a fresh session. With no in-app agent set up, behavior is unchanged.diff --git a/packages/app/src/components/BottomComposer.dom.test.tsx b/packages/app/src/components/BottomComposer.dom.test.tsxindex ada3a3cdf..6fadf6a43 100644--- a/packages/app/src/components/BottomComposer.dom.test.tsx+++ b/packages/app/src/components/BottomComposer.dom.test.tsx@@ -290,7 +290,7 @@ async function renderComposerWithTerminal(terminalLaunchCalls.push({ input, cli });},// The composer reads the install map from here (not its own probe), so it- // drives both the no-pick default (resolveDefaultCli) and row gating+ // drives both the no-pick default and row gating// (isTerminalCliEnabled). Default {} ⇒ probe unresolved ⇒ fail-open (all// CLIs), matching the ungated rows most tests were written against.installedClis,diff --git a/packages/app/src/components/DocPanel.tsx b/packages/app/src/components/DocPanel.tsxindex 808c86461..b4d356bc0 100644--- a/packages/app/src/components/DocPanel.tsx+++ b/packages/app/src/components/DocPanel.tsx@@ -132,16 +132,22 @@ export function DocPanel({applyLintFixes(lintProvider, collectFixes(lintDiagnostics));}};- // Hand one diagnostic to the docked terminal's agent as a grounded prompt- // (live TUI reuse or a fresh Claude launch — the host decides). Desktop-only:- // on web nothing subscribes to the terminal-input event, so the button is+ // Hand one diagnostic to the user's preferred AI as a grounded fix prompt (the+ // host resolves which AI, and reuses a live session or launches one). Desktop-+ // only: on web nothing subscribes to the terminal-input event, so the button is// withheld entirely by not passing `onAskAi`.+ //+ // `submit` because the composed text is a complete "fix this problem"+ // instruction, not material the user is expected to finish writing — so a fresh+ // session runs it, the same as a fresh CLI always has.const terminalLaunch = useTerminalLaunch();const handleAskAi = (diagnostic: DiagnosticLike) => {if (lintProvider === null) return;const source = lintProvider.document.getText('source').toString();const lineText = source.split('\n')[diagnostic.range.start.line];- requestActiveTerminalInput(composeLintFixTerminalPaste(docName, diagnostic, lineText));+ requestActiveTerminalInput(composeLintFixTerminalPaste(docName, diagnostic, lineText), {+ submit: true,+ });};// Single-file `ok <file>` keeps only the Outline + Problems tabs. Links/Graph// need a multi-doc knowledge base, and Timeline is git history — all empty ordiff --git a/packages/app/src/components/EditorPane.dom.test.tsx b/packages/app/src/components/EditorPane.dom.test.tsxindex ccc17f229..7bf9aa99c 100644--- a/packages/app/src/components/EditorPane.dom.test.tsx+++ b/packages/app/src/components/EditorPane.dom.test.tsx@@ -1,20 +1,16 @@import { act, cleanup, render, screen } from '@testing-library/react';import userEvent from '@testing-library/user-event';import { isMacOS } from '@tiptap/core';-import { type ReactNode, useEffect } from 'react';+import type { ReactNode } from 'react';import { afterEach, describe, expect, test, vi } from 'vitest';import { publishSelectionContext } from '@/editor/selection-context';import type { EditorSurface } from '@/editor/selection-stats';+import { subscribeToPreferredSessionRequests } from './handoff/preferred-session-events';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.@@ -34,12 +30,32 @@ function clearSelection(): void {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 } {+// Collect the Ask-AI passages EditorPane dispatches to the sessions host (which+// owns reuse-vs-launch and preferred-AI resolution; mocked here). `newTab` rides+// along so ⌘J (reuse when sensible) stays distinguishable from ⇧⌘J (always fresh).+function captureActiveTerminalInput(): {+ texts: string[];+ details: { text: string; newTab: boolean; submit: boolean }[];+ stop: () => void;+} {const texts: string[] = [];- const stop = subscribeToActiveTerminalInput((text) => texts.push(text));- return { texts, stop };+ const details: { text: string; newTab: boolean; submit: boolean }[] = [];+ const stop = subscribeToActiveTerminalInput((detail) => {+ texts.push(detail.text);+ details.push({ text: detail.text, newTab: detail.newTab, submit: detail.submit });+ });+ return { texts, details, stop };+}++// Count the promptless "open my preferred AI" requests EditorPane dispatches+// (⇧⌘J with no selection). The host resolves which AI that is.+function capturePreferredSessionRequests(): { readonly count: number; stop: () => void } {+ const state = { count: 0, stop: () => {} };+ const unsubscribe = subscribeToPreferredSessionRequests(() => {+ state.count += 1;+ });+ state.stop = unsubscribe;+ return state;}function shiftJKeydownInit(): KeyboardEventInit {@@ -125,18 +141,11 @@ vi.doMock('./TerminalSessionsHost', () => ({bridge,visible,launch,- onActiveSessionCliChange,}: {bridge?: unknown;visible?: boolean;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 (<divdata-testid="terminal-dock"@@ -407,7 +416,6 @@ describe('EditorPane terminal dock wiring', () => {delete (window as { okDesktop?: unknown }).okDesktop;terminalOpenedCalls.length = 0;clearSelection();- mockActiveIsCli = false;});test('web host mounts the sessions host (host-agnostic) with no desktop bridge', async () => {@@ -623,43 +631,58 @@ 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 () => {+ test('desktop: ⇧⌘J with no selection asks the host for a preferred-AI session', async () => {(window as { okDesktop?: unknown }).okDesktop = makeOkDesktopStub().stub;await renderEditorPane();const input = captureActiveTerminalInput();+ const preferred = capturePreferredSessionRequests();act(() => {window.dispatchEvent(new KeyboardEvent('keydown', shiftJKeydownInit()));});input.stop();+ preferred.stop();- // launchNewChat: the dock reveals + a promptless launch intent, nothing staged.+ // The dock reveals and the host is asked to open the user's preferred AI.+ // EditorPane deliberately names no CLI: resolving here could only ever yield+ // a CLI, which is what made ⇧⌘J ignore a preferred ACP agent.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(preferred.count).toBe(1);+ expect(dock.getAttribute('data-launch-nonce')).toBe('none');expect(input.texts).toEqual([]);});- test('desktop: ⇧⌘J with a selection launches a NEW CLI tab with the passage STAGED (not sent)', async () => {+ test('desktop: ⇧⌘J with a selection sends the passage to the host as a NEW session', async () => {(window as { okDesktop?: unknown }).okDesktop = makeOkDesktopStub().stub;await renderEditorPane();seedSelection('some highlighted text');const input = captureActiveTerminalInput();+ const preferred = capturePreferredSessionRequests();act(() => {window.dispatchEvent(new KeyboardEvent('keydown', shiftJKeydownInit()));});input.stop();+ preferred.stop();- // A launch intent that STAGES the passage (no raw inject, nothing auto-run).+ // The passage rides the Ask-AI channel with `newTab` set, so the host opens a+ // fresh session in whichever family the user prefers instead of reusing one.+ // Nothing is auto-run and no CLI is named here.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([]);+ expect(input.details).toHaveLength(1);+ expect(input.details[0]?.newTab).toBe(true);+ expect(input.details[0]?.text).toContain('some highlighted text');+ // Raw selected material, never an instruction: `submit` stays false so a+ // fresh session writes it and waits. A true here would auto-run a passage the+ // user only highlighted.+ expect(input.details[0]?.submit).toBe(false);+ // Trailing soft newlines land the caret on a blank line below the passage.+ expect(input.details[0]?.text.endsWith('\n\n')).toBe(true);+ // A selection send is not a promptless "new chat" request.+ expect(preferred.count).toBe(0);+ expect(dock.getAttribute('data-launch-nonce')).toBe('none');});test('desktop: ⇧⌘J claims the event (preventDefault)', async () => {@@ -682,8 +705,7 @@ describe('EditorPane terminal dock wiring', () => {expect(screen.getByTestId('terminal-dock').getAttribute('data-launch-nonce')).toBe('none');});- test('desktop: ⌘J with a selection injects into the ACTIVE running CLI (no toggle, no launch)', async () => {- mockActiveIsCli = true;+ test('desktop: ⌘J with a selection sends the passage to the host for reuse (no toggle, no launch)', async () => {const desk = makeOkDesktopStub();(window as { okDesktop?: unknown }).okDesktop = desk.stub;await renderEditorPane();@@ -694,37 +716,22 @@ describe('EditorPane terminal dock wiring', () => {act(() => desk.dispatchMenuAction('toggle-terminal'));input.stop();- // Active tab is a running CLI → write the passage into it (reuse), reveal, no- // launch intent.+ // ⌘J means "continue where I am when that makes sense", so `newTab` is unset+ // and the host decides: a running CLI or an open agent thread takes the+ // passage, otherwise it launches the preferred AI. EditorPane reveals the dock+ // and stages nothing itself — whether the active tab is a CLI, a bare shell, or+ // an agent thread is knowledge only the host has.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(input.details).toHaveLength(1);+ expect(input.details[0]?.newTab).toBe(false);+ expect(input.details[0]?.text).toContain('run the build');+ expect(input.details[0]?.submit).toBe(false);+ // Trailing soft newlines land the caret on a blank line below the passage.+ expect(input.details[0]?.text.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;diff --git a/packages/app/src/components/EditorPane.tsx b/packages/app/src/components/EditorPane.tsxindex a2296b535..d70f3e2fd 100644--- a/packages/app/src/components/EditorPane.tsx+++ b/packages/app/src/components/EditorPane.tsx@@ -11,7 +11,6 @@ import { useInstalledClis } from '@/hooks/use-installed-clis';import { useNoPushPermissionToast } from '@/hooks/use-no-push-permission-toast';import { useWorktreeAutoSyncNotice } from '@/hooks/use-worktree-autosync-notice';import { useConfigContext } from '@/lib/config-provider';-import { resolveDefaultCli } from '@/lib/default-cli-resolver';import { matchesKeyboardShortcut } from '@/lib/keyboard-shortcuts';import { subscribeLocalMenuAction } from '@/lib/local-menu-action-bus';import {@@ -19,9 +18,7 @@ import {type TerminalDockPosition,writeTerminalDock,} from '@/lib/terminal-dock-store';-import { readPreferBareTerminal } from '@/lib/terminal-new-tab-store';import { recordTerminalOpened } from '@/lib/terminal-telemetry';-import { loadStickyAgent } from '@/lib/unified-agent-store';import { setViewMenuState } from '@/lib/view-menu-state-store';import { AuthModal } from './AuthModal';import { AutoSyncOnboardingDialog } from './AutoSyncOnboardingDialog';@@ -30,6 +27,7 @@ import { type PanelTab, TABS } from './DocPanel';import { EditorArea, type TerminalPlacement } from './EditorArea';import { EditorHeader } from './EditorHeader';import { composeTerminalSelectionPaste } from './handoff/compose-terminal-selection';+import { requestPreferredSession } from './handoff/preferred-session-events';import { requestActiveTerminalInput } from './handoff/terminal-input-events';import { subscribeToTerminalLaunchRequests } from './handoff/terminal-launch-events';import {@@ -123,12 +121,12 @@ export function EditorPane({ onOpenSearch }: EditorPaneProps = {}) {desktopBridge.config.ptyAvailable === true;const [terminalVisible, setTerminalVisible] = useState(false);// Which launchable CLIs are on PATH (desktop probe, cached ~60s in main).- // Feeds the New-chat default-CLI auto-pick. Starts empty, so resolveDefaultCli- // degrades to claude until the probe resolves. Shared with the Ask-X bubble.+ // Handed to the sessions host, which folds it into its launcher resolution.+ // Shared with the Ask-X bubble.const installedClis = useInstalledClis();- // Whether the terminal currently holds any session (reported up by the host).- // The header's New chat button reads this to decide between bootstrapping a- // first chat and merely revealing an already-populated dock.+ // Whether the dock currently holds any session (reported up by the host).+ // Keeps the edge reveal tab available on a host with no terminal once threads+ // are open, so a hidden dock is still reachable there.const [hasSessions, setHasSessions] = useState(false);// Gates the View-menu visibility push (below) until the mount-time dock-state// restore has read main's retained per-window visibility. Without the gate the@@ -183,37 +181,27 @@ export function EditorPane({ onOpenSearch }: EditorPaneProps = {}) {// the dock would then dedup away as a repeat.const launchNonceRef = useRef(0);- // Header + tab-strip "New chat": launch a CLI with NO prompt (a blank session).- // Resolve the CLI from the sticky pick + installed set unless the caller names- // 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. `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);+ // "New chat" with the preferred AI: reveal the dock and let the host resolve+ // and open it. The host's `launchSelectedNewTab` spans all three families+ // (in-app agent / CLI / bare shell) and honors the Configure-agents toggles;+ // resolving a CLI here instead could only ever produce a CLI, never the in-app+ // agent a user may prefer.+ function launchNewChat() {setTerminalVisible(true);- launchNonceRef.current += 1;- setTerminalLaunch({- prompt: null,- cli: resolvedCli,- nonce: launchNonceRef.current,- stagePaste,- });+ requestPreferredSession();}- // Reveal the sessions dock and, if no session exists yet, seed a first one.- // Drives the edge "Show sessions" reveal tab; leaves the right doc-panel- // untouched (the two coexist). On a terminal surface the seed honors the sticky- // pick: for a CLI, launch a chat under the default CLI; when the last pick was a- // bare "Terminal", skip the CLI launch and let the host's reveal-from-empty- // fallback seed a bare shell. On the web host (no terminal) the host's- // reveal-from-empty seed handles the sticky agent instead.+ // Reveal the sessions dock; the host seeds it when it opens empty. Drives the+ // edge "Show sessions" reveal tab and the View → Show Terminal item; leaves the+ // right doc-panel untouched (the two coexist).+ //+ // Seeding is deliberately NOT done here. The host's `seedOnReveal` resolves the+ // whole preferred-AI space (in-app agent / CLI / bare shell, enablement-aware);+ // this pane can only see the CLI slice. Launching from here would set a launch+ // intent that PREEMPTS that seed, forcing a CLI on a user whose preferred AI is+ // an in-app agent.function revealTerminal() {setTerminalVisible(true);- if (terminalAvailable && !hasSessions && !readPreferBareTerminal()) launchNewChat();}const syncStatus = useGitSyncStatus();@@ -251,23 +239,19 @@ 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+ // ⌘J / ⇧⌘J with an editor selection STAGE that selection into the user's+ // preferred AI 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.)+ //+ // Where it lands is the HOST's call, not this pane's: it owns both the live+ // session state and the preferred-AI resolution, so ⌘J reuses a running CLI or+ // an open agent thread, and otherwise launches whichever AI the user prefers.+ // Resolving here instead would limit ⌘J to the CLI slice this pane can see,+ // ignoring a preferred in-app agent.+ //// 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 {@@ -278,17 +262,14 @@ export function EditorPane({ onOpenSearch }: EditorPaneProps = {}) {// 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);- }+ setTerminalVisible(true);+ // Raw selected material, not an instruction — written and left for the user+ // to extend and send, on a CLI and on an agent thread alike.+ requestActiveTerminalInput(staged, { newTab, submit: false });return true;}// Effect Events so the once-bound key/menu listeners below read the current- // closures (fresh activeDocName / editorMode / installedClis) without- // re-subscribing.+ // closures (fresh activeDocName / editorMode) without re-subscribing.const sendSelectionToTerminalEvent = useEffectEvent(sendSelectionToTerminal);const launchNewChatEvent = useEffectEvent(() => launchNewChat());@@ -325,11 +306,13 @@ 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).+ // ⇧⌘J / Ctrl+Shift+J: open a fresh session with the preferred AI. With a+ // selection, that selection is staged into the new session (always fresh, never+ // reusing the active tab); otherwise the host opens a promptless one. Both paths+ // resolve to whichever AI the user prefers (in-app agent / CLI / bare shell),+ // not a hardcoded CLI. 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) {@@ -341,18 +324,28 @@ export function EditorPane({ onOpenSearch }: EditorPaneProps = {}) {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- // session as a fresh one-shot intent. The nonce comes from the monotonic ref,- // so every click is a strictly increasing, never-reused intent: each one opens- // its own tab and the dock can dedup re-renders by nonce without dropping a- // genuinely new launch. Desktop-only; the web host never renders the entry point.+ // CLI launch — "Open in terminal" from a handoff menu, or the sessions host+ // resolving an Ask AI / selection send to a CLI. Open the dock (the terminal is+ // allowed by default; the gate only blocks a project explicitly opted out) AND+ // carry the text to the session as a fresh one-shot intent. The nonce comes from+ // the monotonic ref, so every click is a strictly increasing, never-reused+ // intent: each one opens its own tab and the dock can dedup re-renders by nonce+ // without dropping a genuinely new launch.+ //+ // `stage` picks which slot the text lands in, and the two are mutually+ // exclusive: `prompt` is baked as a CLI arg and RUNS, `stagePaste` is written+ // into the input and waits. A raw selection send must never auto-run, so it+ // stages.useEffect(() => {- return subscribeToTerminalLaunchRequests((prompt, cli) => {+ return subscribeToTerminalLaunchRequests((text, cli, { stage }) => {setTerminalVisible(true);launchNonceRef.current += 1;- setTerminalLaunch({ prompt, cli, nonce: launchNonceRef.current });+ setTerminalLaunch({+ prompt: stage ? null : text,+ cli,+ nonce: launchNonceRef.current,+ stagePaste: stage ? text : undefined,+ });});}, []);@@ -544,9 +537,6 @@ export function EditorPane({ onOpenSearch }: EditorPaneProps = {}) {dockPosition={terminalDock}onToggleDock={toggleTerminalDock}onHasSessionsChange={setHasSessions}- onActiveSessionCliChange={(isCli) => {- activeSessionIsCliRef.current = isCli;- }}/></Suspense><AuthModaldiff --git a/packages/app/src/components/TerminalDock.dom.test.tsx b/packages/app/src/components/TerminalDock.dom.test.tsxindex 9d0f1bbfc..5f651abbf 100644--- a/packages/app/src/components/TerminalDock.dom.test.tsx+++ b/packages/app/src/components/TerminalDock.dom.test.tsx@@ -30,6 +30,7 @@ import type { TerminalDockPosition } from '@/lib/terminal-dock-store';import { writePreferBareTerminal } from '@/lib/terminal-new-tab-store';import { saveStickyAgent, terminalCliId } from '@/lib/unified-agent-store';import { requestActiveTerminalInput } from './handoff/terminal-input-events';+import { subscribeToTerminalLaunchRequests } from './handoff/terminal-launch-events';const TERMINAL_PANEL_ID = 'terminal-dock-panel';@@ -229,7 +230,6 @@ function DockHarness({bridge,onReveal,dock = 'bottom',- onActiveSessionCliChange,// biome-ignore lint/suspicious/noExplicitAny: test harness props}: any) {const [bottomContainer, setBottomContainer] = useState<HTMLDivElement | null>(null);@@ -259,18 +259,12 @@ function DockHarness({onRequestEditorFocus={() => editorRegionEl?.focus()}dockPosition={dock}onToggleDock={() => {}}- onActiveSessionCliChange={onActiveSessionCliChange}/></TooltipProvider>);}-function renderDock(- visible: boolean,- launch?: TestLaunch | null,- onReveal?: () => void,- onActiveSessionCliChange?: (isCli: boolean) => void,-) {+function renderDock(visible: boolean, launch?: TestLaunch | null, onReveal?: () => void) {const onVisibleChange = vi.fn((_v: boolean) => {});const { bridge, create, kill, input, viewMenuPushes, dispatchMenuAction } = makeBridge();const ui = (v: boolean, l?: TestLaunch | null, dock?: TerminalDockPosition) => (@@ -281,7 +275,6 @@ function renderDock(bridge={bridge}onReveal={onReveal}dock={dock ?? 'bottom'}- onActiveSessionCliChange={onActiveSessionCliChange}/>);const utils = render(ui(visible, launch));@@ -870,14 +863,16 @@ describe('TerminalDock multi-session', () => {expect(view.input).not.toHaveBeenCalled();});- test('the selection input reuses the live terminal — raw PTY write, no new tab', async () => {+ test('the selection input reuses a live CLI tab — raw PTY write, no new tab', async () => {const view = renderDock(true);- // Wait until the seed session's PTY is live and reported up into the reuse map.+ // A bare-shell seed opens first (pty-1); a CLI launch then takes over as the+ // active tab (pty-2), so the reuse target is a running CLI's TUI (raw mode).await waitFor(() => expect(emitTitle('pty-1', 'zsh')).toBe(true));+ act(() => view.rerender(true, { prompt: null, cli: 'claude', nonce: 1 }));+ await waitFor(() => expect(emitTitle('pty-2', 'claude')).toBe(true));const runningId = activePanelId();- expect(screen.getAllByTestId('terminal-session')).toHaveLength(1);- // The selection-bubble channel fires while that shell is live (the other half+ // The selection-bubble channel fires while that CLI is live (the other half// of the design: launches open their own tab, the selection reuses the open// one).await act(async () => {@@ -885,50 +880,35 @@ describe('TerminalDock multi-session', () => {});// Reused, not respawned: the raw selection text goes straight into the live- // PTY (no `<bin> '<prompt>'` wrapping), no new tab, and the running shell- // stays active.- await waitFor(() => expect(view.input).toHaveBeenCalledWith('pty-1', 'explain this'));- expect(screen.getAllByTestId('terminal-session')).toHaveLength(1);+ // CLI PTY (no `<bin> '<prompt>'` wrapping), no new tab, and it stays active.+ await waitFor(() => expect(view.input).toHaveBeenCalledWith('pty-2', 'explain this'));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('a selection send into a bare shell is NEVER raw-written — it stages a fresh CLI instead', async () => {+ // Regression guard: `terminal.input` writes bytes straight to the PTY, and a+ // bare shell in canonical mode runs each `\n` in the passage as accept-line.+ // So the reuse write must be gated on the active tab being a CLI (raw-mode+ // TUI); a bare shell falls through to a fresh staged launch.+ const view = renderDock(true);+ await waitFor(() => expect(emitTitle('pty-1', 'zsh')).toBe(true));+ expect(screen.getAllByTestId('terminal-session')).toHaveLength(1);- 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),+ const launchRequests: Array<{ text: string; cli: string; stage: boolean }> = [];+ const stopLaunch = subscribeToTerminalLaunchRequests((text, cli, opts) =>+ launchRequests.push({ text, cli, stage: opts.stage }),);- 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);+ await act(async () => {+ requestActiveTerminalInput('explain this');+ });+ stopLaunch();- // 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);+ // Never a raw write into the bare shell's PTY.+ expect(view.input).not.toHaveBeenCalled();+ // The bare shell is not hijacked into a CLI in place; the fresh session is a+ // staged launch (consumed by EditorPane, not mounted in this host-only rig).+ expect(screen.getAllByTestId('terminal-session')).toHaveLength(1);+ expect(launchRequests).toEqual([{ text: 'explain this', cli: 'claude', stage: true }]);});test('a stagePaste launch opens its own tab; the HOST never types the passage (staging is TerminalPanel-owned, bake-gated)', async () => {diff --git a/packages/app/src/components/TerminalDock.reload-survival.dom.test.tsx b/packages/app/src/components/TerminalDock.reload-survival.dom.test.tsxindex e585b0330..644110833 100644--- a/packages/app/src/components/TerminalDock.reload-survival.dom.test.tsx+++ b/packages/app/src/components/TerminalDock.reload-survival.dom.test.tsx@@ -34,6 +34,7 @@ import { afterEach, describe, expect, test, vi } from 'vitest';import { TooltipProvider } from '@/components/ui/tooltip';import type { OkDesktopBridge } from '@/lib/desktop-bridge-types';import { requestActiveTerminalInput } from './handoff/terminal-input-events';+import { subscribeToTerminalLaunchRequests } from './handoff/terminal-launch-events';const TERMINAL_PANEL_ID = 'terminal-dock-panel';@@ -318,8 +319,20 @@ describe('issue #351 — the terminal dock rehydrates surviving sessions after a});});- test('an Ask-AI selection reuses a reload-rehydrated (adopted) session via a direct PTY write', async () => {+ test('an Ask-AI selection does NOT raw-write into a reload survivor (unknown shell type)', async () => {+ // A reload survivor comes back with no launch descriptor, so the host cannot+ // tell a surviving CLI TUI (safe to write) from a surviving bare shell (where a+ // raw write of a multi-line passage runs line-by-line as shell commands). It+ // therefore treats the survivor as non-CLI and falls the selection through to a+ // fresh staged launch — safety over reusing a PTY of unknown type.const { bridge, create, input } = makeSurvivingMainBridge([{ ptyId: 'pty-1' }]);+ // Capture `stage` too, not just the text: falling through to a launch is only+ // half the safety property. A fallthrough that ran the passage as the CLI's+ // prompt would auto-execute the very text this guard exists to hold back.+ const launchRequests: Array<{ text: string; cli: string; stage: boolean }> = [];+ const stopLaunch = subscribeToTerminalLaunchRequests((text, cli, opts) =>+ launchRequests.push({ text, cli, stage: opts.stage }),+ );render(dockUi(bridge, true));// Rehydration recovers exactly one adopted tab, which reports its adopted PTY@@ -329,17 +342,19 @@ describe('issue #351 — the terminal dock rehydrates surviving sessions after a});await act(async () => {}); // flush the onPtyId report into the host's reuse map- // The selection-bubble "Ask AI" fires while the recovered survivor is the- // active tab. Reuse is the selection-input path (verbatim text into the live- // shell), NOT a launch nonce — launches always open their own tab now.+ // The selection-bubble "Ask AI" fires while the recovered survivor is active.await act(async () => {requestActiveTerminalInput('explain');});+ stopLaunch();- // Reused, not respawned: the raw selection text is written straight into the- // adopted PTY (`pty-1`) — no `<bin> '<prompt>'` command wrapping, no new tab,- // no fresh create(). Covers reuse for reload survivors.- await waitFor(() => expect(input).toHaveBeenCalledWith('pty-1', 'explain'));+ // Never a raw write into the survivor's adopted PTY (the bare-shell hazard).+ expect(input).not.toHaveBeenCalled();+ // The selection falls through to a fresh STAGED launch instead — `stage: true`+ // is what keeps it written-and-waiting rather than run.+ expect(launchRequests).toEqual([{ text: 'explain', cli: 'claude', stage: true }]);+ // The survivor tab is not hijacked; the fresh launch is consumed by EditorPane+ // (not mounted in this host-only rig), so no create() fires here.expect(screen.getAllByTestId('terminal-session')).toHaveLength(1);expect(create).not.toHaveBeenCalled();});diff --git a/packages/app/src/components/TerminalSessionsHost.threads.dom.test.tsx b/packages/app/src/components/TerminalSessionsHost.threads.dom.test.tsxindex e4747fdf7..d34b57840 100644--- a/packages/app/src/components/TerminalSessionsHost.threads.dom.test.tsx+++ b/packages/app/src/components/TerminalSessionsHost.threads.dom.test.tsx@@ -8,12 +8,16 @@*/import type { ThreadInfo } from '@inkeep/open-knowledge-core/acp/thread-protocol';-import { cleanup, render, screen, waitFor } from '@testing-library/react';+import { act, cleanup, render, screen, waitFor } from '@testing-library/react';import userEvent from '@testing-library/user-event';import { useState, useSyncExternalStore } from 'react';import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';import { TooltipProvider } from '@/components/ui/tooltip';+import { subscribeStagedThreadDraft } from '@/lib/acp/thread-draft-staging';import type { OkDesktopBridge } from '@/lib/desktop-bridge-types';+import { requestPreferredSession } from './handoff/preferred-session-events';+import { requestActiveTerminalInput } from './handoff/terminal-input-events';+import { subscribeToTerminalLaunchRequests } from './handoff/terminal-launch-events';// A tiny controllable stand-in for the server-authoritative thread store.let openThreads: ThreadInfo[] = [];@@ -83,16 +87,23 @@ vi.doMock('@/components/acp/ThreadView', () => ({),}));+/**+ * The registered in-app agent, when a test wants one. Null (the default) models a+ * machine with no ACP agent set up, so the launcher falls through to the CLI /+ * bare-terminal families.+ */+let mockRegisteredAgent: { source: 'registry' | 'custom'; id: string; name: string } | null = null;+vi.doMock('@/lib/acp/registered-agents', () => ({- useRegisteredAgents: () => [],- useDefaultRegisteredAgent: () => null,- getDefaultRegisteredAgent: () => null,+ useRegisteredAgents: () => (mockRegisteredAgent === null ? [] : [mockRegisteredAgent]),+ useDefaultRegisteredAgent: () => mockRegisteredAgent,+ getDefaultRegisteredAgent: () => mockRegisteredAgent,registerAgent: () => {},// Real code loaded here imports these too (TerminalSessionsHost →// pickEffectiveDefaultAgent; catalog → hydrateRegisteredAgentMeta). A// mock.module replaces the whole module, so any omitted export becomes an// unresolved import that fails the file (and can cascade to siblings).- pickEffectiveDefaultAgent: () => null,+ pickEffectiveDefaultAgent: () => mockRegisteredAgent,hydrateRegisteredAgentMeta: () => {},}));@@ -120,6 +131,20 @@ function makeThread(overrides: Partial<ThreadInfo> & { threadId: string }): Thre};}+/** Minimal desktop bridge whose only job is to make `terminalAvailable` true, so+ * the CLI family is a candidate the launcher can resolve to. */+function makeTerminalBridge(): OkDesktopBridge {+ return {+ terminal: {+ create: vi.fn(async () => ({ ptyId: 'pty-1' })),+ kill: vi.fn(),+ input: vi.fn(),+ list: vi.fn(async () => []),+ },+ editor: { notifyViewMenuStateChanged: vi.fn() },+ } as unknown as OkDesktopBridge;+}+function Harness({bridge = null,initialVisible = true,@@ -162,6 +187,7 @@ describe('TerminalSessionsHost — agent-thread hosting (web / no bridge)', () =deleteThread.mockClear();launchAgentThread.mockClear();catalogData = undefined;+ mockRegisteredAgent = null;});afterEach(() => cleanup());@@ -318,6 +344,185 @@ describe('TerminalSessionsHost — agent-thread hosting (web / no bridge)', () =expect(screen.queryByRole('button', { name: 'Restore sessions' })).toBeNull();});+ // Every "Ask AI" surface (Problems panel, selection bubble, code block, ⌘J/⇧⌘J)+ // funnels through this one channel, and the host is the only place that knows+ // which AI the user prefers — so the preferred agent, CLI, or bare shell is what+ // each surface routes to, uniformly.+ describe('Ask AI honors the preferred AI', () => {+ test('an Ask AI instruction RUNS on a new thread (never a CLI)', async () => {+ mockRegisteredAgent = { source: 'registry', id: 'acme-agent', name: 'Acme' };+ const launches: unknown[] = [];+ const stopLaunch = subscribeToTerminalLaunchRequests((prompt, cli, opts) =>+ launches.push({ prompt, cli, ...opts }),+ );+ render(<Harness />);+ await screen.findByTestId('terminal-new-chat');++ await act(async () => {+ requestActiveTerminalInput('fix this lint error', { submit: true });+ });+ stopLaunch();++ // The passage lands as `prompt` (2nd arg), so the thread runs it on+ // creation — the thread twin of a fresh CLI baking the prompt as an arg.+ // Nothing is staged.+ expect(launchAgentThread).toHaveBeenCalledTimes(1);+ const [agent, prompt, , , stagedDraft] = launchAgentThread.mock.calls[0];+ expect(agent).toEqual({ source: 'registry', id: 'acme-agent' });+ expect(prompt).toBe('fix this lint error');+ expect(stagedDraft).toBeNull();+ // Crucially: no terminal launch at all. This is the assertion that fails+ // against the old hardcoded `requestTerminalLaunch(text, 'claude')`.+ expect(launches).toEqual([]);+ });++ test('a ⌘J selection send STAGES on a new thread instead of running', async () => {+ mockRegisteredAgent = { source: 'registry', id: 'acme-agent', name: 'Acme' };+ render(<Harness />);+ await screen.findByTestId('terminal-new-chat');++ await act(async () => {+ requestActiveTerminalInput('a selected passage', { submit: false });+ });++ // Raw material, so it waits on the user's send — mirroring the terminal,+ // where a selection send rides `stagePaste` and never auto-runs.+ expect(launchAgentThread).toHaveBeenCalledTimes(1);+ const [, prompt, , , stagedDraft] = launchAgentThread.mock.calls[0];+ expect(prompt).toBeNull();+ expect(stagedDraft).toBe('a selected passage');+ });++ // Reuse never submits on EITHER family. Not a choice made for threads: it is+ // what `terminal.input` has always done (write, don't press enter).+ test.each([true, false])('reusing an open thread always stages, submit=%s', async (submit) => {+ mockRegisteredAgent = { source: 'registry', id: 'acme-agent', name: 'Acme' };+ render(<Harness />);+ setOpenThreads([makeThread({ threadId: 't1', title: 'Work' })]);+ await screen.findByTestId('thread-view');++ const staged: string[] = [];+ const stopStaging = subscribeStagedThreadDraft('t1', (text) => staged.push(text));+ await act(async () => {+ requestActiveTerminalInput('fix this lint error', { submit });+ });+ stopStaging();++ expect(staged).toEqual(['fix this lint error']);+ expect(launchAgentThread).not.toHaveBeenCalled();+ });++ test('newTab forces a fresh thread even with one open (⇧⌘J)', async () => {+ mockRegisteredAgent = { source: 'registry', id: 'acme-agent', name: 'Acme' };+ render(<Harness />);+ setOpenThreads([makeThread({ threadId: 't1', title: 'Work' })]);+ await screen.findByTestId('thread-view');++ const staged: string[] = [];+ const stopStaging = subscribeStagedThreadDraft('t1', (text) => staged.push(text));+ await act(async () => {+ requestActiveTerminalInput('a fresh question', { newTab: true, submit: false });+ });+ stopStaging();++ expect(staged).toEqual([]);+ // Both positions, matching the sibling above: asserting the draft alone+ // would still pass if a caller set BOTH prompt and stageDraft, which would+ // auto-run the passage the user only highlighted.+ expect(launchAgentThread).toHaveBeenCalledTimes(1);+ const [, prompt, , , stagedDraft] = launchAgentThread.mock.calls[0];+ expect(prompt).toBeNull();+ expect(stagedDraft).toBe('a fresh question');+ });++ // The other half of the matrix: an Ask AI INSTRUCTION that forces a fresh+ // session (a Problems-panel ask dispatched while a thread is already open).+ // Skips reuse like the case above, but `submit` sends it to `prompt`.+ test('newTab with submit runs the instruction in a fresh thread', async () => {+ mockRegisteredAgent = { source: 'registry', id: 'acme-agent', name: 'Acme' };+ render(<Harness />);+ setOpenThreads([makeThread({ threadId: 't1', title: 'Work' })]);+ await screen.findByTestId('thread-view');++ const staged: string[] = [];+ const stopStaging = subscribeStagedThreadDraft('t1', (text) => staged.push(text));+ await act(async () => {+ requestActiveTerminalInput('fix this lint error', { newTab: true, submit: true });+ });+ stopStaging();++ expect(staged).toEqual([]);+ expect(launchAgentThread).toHaveBeenCalledTimes(1);+ const [, prompt, , , stagedDraft] = launchAgentThread.mock.calls[0];+ expect(prompt).toBe('fix this lint error');+ expect(stagedDraft).toBeNull();+ });++ // Closes the triangle: the channel and `launchSelectedNewTab` are each tested+ // alone, but nothing fired a request into a mounted host. A stale closure or an+ // event-name drift would slip past both endpoint tests.+ test('a promptless preferred-session request opens the preferred agent', async () => {+ mockRegisteredAgent = { source: 'registry', id: 'acme-agent', name: 'Acme' };+ render(<Harness />);+ await screen.findByTestId('terminal-new-chat');++ await act(async () => {+ requestPreferredSession();+ });++ expect(launchAgentThread).toHaveBeenCalledTimes(1);+ const [agent, prompt, , , stagedDraft] = launchAgentThread.mock.calls[0];+ expect(agent).toEqual({ source: 'registry', id: 'acme-agent' });+ // Promptless: ⇧⌘J with no selection carries nothing to run or stage.+ // Normalized because this path omits the optional 5th arg rather than+ // passing an explicit null — the invariant is "no staged draft", not which+ // of the two nullish encodings the call site happens to use.+ expect(prompt).toBeNull();+ expect(stagedDraft ?? null).toBeNull();+ });++ // The CLI family must carry the SAME distinction, or ⇧⌘J would auto-run a+ // raw passage the moment no agent is configured.+ test.each([+ { submit: true, stage: false, label: 'an Ask AI instruction runs' },+ { submit: false, stage: true, label: 'a selection send stages' },+ ])('with NO agent set up, $label on the CLI', async ({ submit, stage }) => {+ const launches: { prompt: string; cli: string; stage: boolean }[] = [];+ const stopLaunch = subscribeToTerminalLaunchRequests((prompt, cli, opts) =>+ launches.push({ prompt, cli, stage: opts.stage }),+ );+ render(<Harness bridge={makeTerminalBridge()} />);+ await screen.findByTestId('terminal-new-chat');++ await act(async () => {+ requestActiveTerminalInput('fix this lint error', { submit });+ });+ stopLaunch();++ // No in-app agent → the CLI family is next in the uniform precedence, so the+ // passage still reaches an AI. Claude here is the resolver's install-nudge+ // default, not a hardcoded sender-side choice.+ expect(launchAgentThread).not.toHaveBeenCalled();+ expect(launches).toEqual([{ prompt: 'fix this lint error', cli: 'claude', stage }]);+ });++ test('with nothing set up, an Ask AI send opens Configure agents (no silent shell)', async () => {+ // No registered agent and no terminal host → nothing to ask. The passage+ // routes to Settings rather than silently opening a bare shell or a+ // hardcoded CLI, matching the New primary's destination in this state.+ window.location.hash = '';+ render(<Harness />);+ await screen.findByTestId('terminal-new-chat');++ await act(async () => {+ requestActiveTerminalInput('fix this lint error', { submit: false });+ });++ expect(launchAgentThread).not.toHaveBeenCalled();+ expect(window.location.hash).toBe('#settings/configure-agents');+ });+ });+test('a dropped WS shows the reconnecting banner above the active thread', async () => {render(<Harness />);setOpenThreads([makeThread({ threadId: 't1', title: 'Work' })]);diff --git a/packages/app/src/components/TerminalSessionsHost.tsx b/packages/app/src/components/TerminalSessionsHost.tsxindex f11871ba3..e94b192de 100644--- a/packages/app/src/components/TerminalSessionsHost.tsx+++ b/packages/app/src/components/TerminalSessionsHost.tsx@@ -33,6 +33,7 @@ import {useArchivedAgentThreads,useOpenAgentThreadTabs,} from '@/lib/acp/thread-client';+import { stageThreadDraft } from '@/lib/acp/thread-draft-staging';import type { OkDesktopBridge } from '@/lib/desktop-bridge-types';import {type DockSessionOrder,@@ -66,7 +67,11 @@ const ThreadView = lazy(() =>import('@/components/acp/ThreadView').then((mod) => ({ default: mod.ThreadView })),);-import { subscribeToActiveTerminalInput } from './handoff/terminal-input-events';+import { subscribeToPreferredSessionRequests } from './handoff/preferred-session-events';+import {+ type ActiveTerminalInputDetail,+ subscribeToActiveTerminalInput,+} from './handoff/terminal-input-events';import { requestTerminalLaunch } from './handoff/terminal-launch-events';import { TerminalGate } from './TerminalGate';import { TerminalNewChatButton } from './TerminalNewChatButton';@@ -244,13 +249,6 @@ interface TerminalSessionsHostProps {/** Reports whether ANY session (terminal or thread) is open, so the placement* owner (EditorArea via EditorPane) can render the dock column/shell. */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;}/**@@ -280,7 +278,6 @@ export function TerminalSessionsHost({dockPosition,onToggleDock,onHasSessionsChange,- onActiveSessionCliChange,}: TerminalSessionsHostProps) {const { t } = useLingui();@@ -531,6 +528,96 @@ export function TerminalSessionsHost({// `choose` → reveal the empty dock without auto-opening the catalog.}+ /**+ * Which AI an "Ask AI" passage goes to. Same resolver as the New primary, but+ * with both bare-terminal knobs off: a composed passage needs an *AI*, and a+ * bare shell would just paste markdown into zsh. So a user whose last session+ * pick was "Terminal" still gets their preferred agent for Ask AI, and when+ * nothing is enabled this yields `none` (→ Configure agents) rather than+ * silently opening a shell.+ */+ const askAiSelection = resolveLauncherSelection({+ sticky: stickyAgentId,+ effectiveThreadAgent: effectiveDefaultAgent,+ enabledClis: enabledTerminalClis(enabledOverrides, installedClis ?? {}),+ enabledDesktopTargets: [],+ installedClis: installedClis ?? {},+ terminalAvailable,+ threadsAvailable: hostThreads,+ desktopSelectable: false,+ preferBareTerminal: false,+ bareTerminalFallback: false,+ });++ /**+ * Route an "Ask AI" passage (selection bubble, code block, Problems panel, the+ * ⌘J/⇧⌘J selection sends) to the user's preferred AI. This is the single place+ * the which-AI decision is made, so every surface honors the preferred agent+ * rather than a per-surface default.+ *+ * Reuse first, unless the caller asked for a fresh session (⇧⌘J): a live thread+ * takes the passage as a staged composer draft; a live CLI takes it as a+ * no-carriage-return write into its input. Reuse writes without submitting on+ * both families.+ *+ * The reuse write is gated on the terminal tab being a CLI session+ * (`launch.cli`), NOT merely any live PTY. `terminal.input` writes bytes+ * straight to the PTY, and a bare shell in canonical mode treats each `\n` in+ * the passage as accept-line, so a raw write there would run the passage as+ * shell commands; an interactive CLI's TUI is in raw mode and treats the same+ * bytes as input. A bare shell therefore falls through to the launch path+ * below (the fresh-CLI staging the ⌘J send has always used for a non-CLI tab)+ * instead of executing the passage.+ *+ * With nothing to reuse, launch whatever `askAiSelection` names, and let+ * `submit` decide how the text lands: an Ask AI surface sends a complete+ * instruction and runs it; a ⌘J selection send is raw material and waits.+ */+ function dispatchAskAi({ text, newTab, submit }: ActiveTerminalInputDetail) {+ const activeId = activeSessionIdRef.current;+ const active = sessionsRef.current.find((s) => s.id === activeId);+ if (!newTab && active != null) {+ if (active.kind === 'thread') {+ // Reuse ignores `submit` on purpose, so this is NOT an asymmetry to+ // "fix" by threading submit through: writing into a live CLI has never+ // pressed enter, and a thread the user is already in behaves the same.+ // `submit` only decides how a FRESH session receives the text.+ stageThreadDraft(active.threadId, text);+ queueMicrotask(() => focusSession(active));+ return;+ }+ const livePtyId = ptyIdBySessionRef.current.get(active.id);+ const terminal = bridge?.terminal;+ // Only a live CLI tab is reused. A bare shell — and a reload survivor, which+ // rehydrates as launch:null with its CLI-ness unrecoverable — falls through+ // to a fresh launch. Do NOT widen this to any live PTY to restore survivor+ // reuse: a rehydrated bare shell would then run the passage as commands+ // (see the `launch.cli` gate rationale above).+ if (livePtyId != null && terminal != null && active.launch?.cli != null) {+ terminal.input(livePtyId, text);+ queueMicrotask(() => focusTerminalSession(activeId));+ return;+ }+ }+ if (askAiSelection.kind === 'thread') {+ const agent = { source: askAiSelection.agent.source, id: askAiSelection.agent.id };+ // `prompt` runs on creation, `stageDraft` waits — the thread twins of the+ // launch intent's `prompt` / `stagePaste`.+ if (submit) launchAgentThread(agent, text, null, null, null);+ else launchAgentThread(agent, null, null, null, text);+ } else if (askAiSelection.kind === 'cli') {+ requestTerminalLaunch(text, askAiSelection.cli, { stage: !submit });+ } else {+ // Only `none` reaches here. `askAiSelection` is built with+ // `desktopSelectable: false` + `bareTerminalFallback/preferBareTerminal: false`,+ // so the resolver cannot yield `desktop` or `terminal` for this path — flip+ // either knob and a bare shell would land in this branch silently instead of+ // being refused. Nothing enabled to ask, so send the user where they can+ // enable something: the same destination the New primary uses in this state.+ openAgentSettings();+ }+ }+// Dropdown CLI pick: clear the bare-terminal preference, persist `cli`, open it.function pickNewChatCli(cli: TerminalCli) {setPreferBareTerminal(false);@@ -655,6 +742,8 @@ export function TerminalSessionsHost({const moveActiveSessionRef = useRef(moveActiveSession);const openSessionRef = useRef(openSession);const seedOnRevealRef = useRef(seedOnReveal);+ const dispatchAskAiRef = useRef(dispatchAskAi);+ const launchSelectedNewTabRef = useRef(launchSelectedNewTab);// Close a tab — kind-dispatched. A terminal is removed from the list (its panel// unmounts, killing the PTY); a thread is archived server-side (discarded if it@@ -689,6 +778,8 @@ export function TerminalSessionsHost({useEffect(() => {openSessionRef.current = openSession;seedOnRevealRef.current = seedOnReveal;+ dispatchAskAiRef.current = dispatchAskAi;+ launchSelectedNewTabRef.current = launchSelectedNewTab;moveActiveSessionRef.current = moveActiveSession;activeSessionIdRef.current = activeSessionId;sessionsRef.current = sessions;@@ -958,26 +1049,20 @@ export function TerminalSessionsHost({return () => window.clearTimeout(timer);}, [canRehydrate]);- // The editor's "Ask AI" selection affordance routes here. Live PTY → write the- // composed prompt into the active shell (e.g. a running claude TUI); no trailing- // newline so the user reviews/sends. No live PTY → launch a fresh Claude tab- // pre-loaded with the same prompt (mirrors the "Open in terminal" path).+ // Every editor "Ask AI" affordance routes here; `dispatchAskAi` owns the+ // reuse-vs-launch and which-AI decisions. Subscribed whenever EITHER family can+ // serve the passage — threads are server-hosted, so a host with no terminal can+ // still answer an Ask AI with the user's preferred agent.useEffect(() => {- if (!terminalAvailable || bridge?.terminal == null) return;- const terminal = bridge.terminal;- return subscribeToActiveTerminalInput((text) => {- const activeId = activeSessionIdRef.current;- const active = sessionsRef.current.find((s) => s.id === activeId);- const livePtyId =- active?.kind === 'terminal' ? ptyIdBySessionRef.current.get(active.id) : undefined;- if (livePtyId != null) {- terminal.input(livePtyId, text);- queueMicrotask(() => focusTerminalSession(activeId));- } else {- requestTerminalLaunch(text, 'claude');- }- });- }, [bridge, terminalAvailable]);+ if (!terminalAvailable && !hostThreads) return;+ return subscribeToActiveTerminalInput((detail) => dispatchAskAiRef.current(detail));+ }, [terminalAvailable, hostThreads]);++ // ⇧⌘J with no selection: open a new session with the preferred AI — the same+ // resolution the New split-button primary uses, so it is never hardcoded to a CLI.+ useEffect(() => {+ return subscribeToPreferredSessionRequests(() => launchSelectedNewTabRef.current());+ }, []);// Terminal application-menu actions act on the tab collection.useEffect(() => {@@ -1055,16 +1140,6 @@ 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 activeSession = sessions.find((s) => s.id === activeSessionId);- const activeSessionIsCli =- activeSession?.kind === 'terminal' && activeSession.launch?.cli != null;- useEffect(() => {- onActiveSessionCliChange?.(activeSessionIsCli);- }, [onActiveSessionCliChange, activeSessionIsCli]);-// Return focus out of the hidden dock so a keyboard user is never stranded.// Only acts when focus is actually inside the dock.//diff --git a/packages/app/src/components/acp/ThreadView.tsx b/packages/app/src/components/acp/ThreadView.tsxindex 39df472ea..2dc4af0f7 100644--- a/packages/app/src/components/acp/ThreadView.tsx+++ b/packages/app/src/components/acp/ThreadView.tsx@@ -72,6 +72,7 @@ import {useAgentThread,useAgentThreadModel,} from '@/lib/acp/thread-client';+import { subscribeStagedThreadDraft } from '@/lib/acp/thread-draft-staging';import {type PermissionOutcome,type RenderedItem,@@ -134,6 +135,17 @@ export function ThreadView({ info }: { info: ThreadInfo }): ReactNode {const initialSeqRef = useRef<number | null>(null);const lastFollowedRef = useRef<string | null>(null);+ // A selection send (⌘J) or Problems-panel "Ask AI" that resolved to this agent+ // seeds the composer instead of auto-sending, so the user reviews and extends+ // the passage before spending a turn — the same stage-don't-submit contract the+ // terminal CLI path honors. Appends rather than overwrites so a staged value+ // arriving after the user started typing can't eat their words.+ useEffect(() => {+ return subscribeStagedThreadDraft(info.threadId, (text) => {+ setDraft((prev) => (prev.trim() === '' ? text : `${prev.replace(/\s+$/, '')}\n\n${text}`));+ });+ }, [info.threadId]);+// Incrementally folded in the store — never re-fold `state.events` here;// the per-render full fold was O(transcript) per streamed chunk.const model = useAgentThreadModel(info.threadId);diff --git a/packages/app/src/components/handoff/preferred-session-events.test.ts b/packages/app/src/components/handoff/preferred-session-events.test.tsnew file mode 100644index 000000000..dc7e5c966--- /dev/null+++ b/packages/app/src/components/handoff/preferred-session-events.test.ts@@ -0,0 +1,39 @@+import { describe, expect, test } from 'vitest';+import {+ requestPreferredSession,+ subscribeToPreferredSessionRequests,+} from './preferred-session-events';++describe('preferred-session-events', () => {+ test('delivers a request to the subscriber and stops after unsubscribe', () => {+ const target = new EventTarget();+ let received = 0;+ const unsub = subscribeToPreferredSessionRequests(() => {+ received += 1;+ }, target);++ requestPreferredSession(target);+ expect(received).toBe(1);++ // Two presses are two sessions — the channel does not dedupe.+ requestPreferredSession(target);+ expect(received).toBe(2);++ unsub();+ requestPreferredSession(target);+ expect(received).toBe(2);+ });++ test('carries no payload, so callers cannot name an AI', () => {+ const target = new EventTarget();+ const args: unknown[][] = [];+ const unsub = subscribeToPreferredSessionRequests((...rest) => args.push(rest), target);++ requestPreferredSession(target);+ unsub();++ // A payload here would let a caller smuggle in an agent opinion, which is+ // what let the old CLI-only resolution ignore a preferred agent.+ expect(args).toEqual([[]]);+ });+});diff --git a/packages/app/src/components/handoff/preferred-session-events.ts b/packages/app/src/components/handoff/preferred-session-events.tsnew file mode 100644index 000000000..c5b95b7ae--- /dev/null+++ b/packages/app/src/components/handoff/preferred-session-events.ts@@ -0,0 +1,35 @@+/**+ * Window-scoped pub/sub for "open a new session with my preferred AI" — the+ * promptless sibling of `terminal-input-events`.+ *+ * ⇧⌘J with no selection fires this. It carries no payload on purpose: which AI+ * opens is `TerminalSessionsHost`'s call (the same `resolveLauncherSelection` its+ * New split-button primary uses), not the caller's. Resolving in the caller is+ * what made ⇧⌘J always open a Claude CLI — the pane could only see the CLI slice+ * of the preference.+ *+ * Distinct from the Terminal menu's `new-terminal` action, which is explicitly a+ * bare shell and stays that way.+ */++const PREFERRED_SESSION_EVENT = 'open-knowledge:new-preferred-session';++export function requestPreferredSession(+ target: Pick<Window, 'dispatchEvent'> | EventTarget = typeof window === 'undefined'+ ? new EventTarget()+ : window,+): void {+ target.dispatchEvent(new CustomEvent(PREFERRED_SESSION_EVENT));+}++export function subscribeToPreferredSessionRequests(+ onRequest: () => void,+ target: Pick<Window, 'addEventListener' | 'removeEventListener'> | EventTarget = typeof window ===+ 'undefined'+ ? new EventTarget()+ : window,+): () => void {+ const listener = () => onRequest();+ target.addEventListener(PREFERRED_SESSION_EVENT, listener);+ return () => target.removeEventListener(PREFERRED_SESSION_EVENT, listener);+}diff --git a/packages/app/src/components/handoff/terminal-input-events.ts b/packages/app/src/components/handoff/terminal-input-events.tsindex 725d08bed..e21228490 100644--- a/packages/app/src/components/handoff/terminal-input-events.ts+++ b/packages/app/src/components/handoff/terminal-input-events.ts@@ -1,37 +1,76 @@/**- * Window-scoped pub/sub carrying a raw text paste into the *already-open* docked- * terminal's active session. The editor's "Ask AI" selection affordance fires- * this so a selection lands directly in the live shell (e.g. a running `claude`- * TUI) when a terminal is open, skipping the bottom composer.+ * Window-scoped pub/sub carrying a raw text paste to the sessions dock's+ * preferred AI. The editor's "Ask AI" affordances (selection bubble, code block,+ * Problems panel) and the ⌘J / ⇧⌘J selection sends fire this so a passage lands+ * wherever the user's preferred AI actually is.** Mirrors the `terminal-launch-events` idiom, but the payload is verbatim text —* never a `<bin> '<prompt>'` command and never a `cli` discriminant. The host- * (`TerminalSessionsHost`) owns the PTY state, so it decides reuse-vs-fallback:- * a live PTY → write the text into it; no terminal open → defer to the Ask-AI- * composer (the same surface a caret-only Ask AI opens).+ * (`TerminalSessionsHost`) owns both the PTY state AND the preferred-AI+ * resolution, so it alone decides reuse-vs-launch and which family to launch+ * into: a live session → write into it; nothing open → launch whatever+ * `resolveLauncherSelection` names. Senders deliberately carry no agent opinion,+ * so the host's preferred-AI resolution is the single source of that decision.+ *+ * `newTab` distinguishes ⇧⌘J ("always a fresh session") from ⌘J ("continue where+ * I am when that makes sense"). It is a request, not a guarantee — the host still+ * degrades per what is enabled and available.*/const ACTIVE_TERMINAL_INPUT_EVENT = 'open-knowledge:active-terminal-input';+export interface ActiveTerminalInputDetail {+ readonly text: string;+ /** Force a fresh session rather than reusing the active one. */+ readonly newTab: boolean;+ /**+ * The text is a complete instruction, so RUN it when starting a fresh session+ * (the Ask AI surfaces). Unset means it is raw material to write and leave+ * unsent (the ⌘J/⇧⌘J selection sends).+ *+ * Only the fresh-session branch honors this — reusing a live session writes+ * without submitting, on both families: a launch intent's `prompt` runs while+ * its `stagePaste` waits, and the thread path mirrors that. The reuse write+ * goes in without a trailing carriage return; the host keeps it off a bare+ * shell (where each `\n` would submit a line) by reusing only a live CLI+ * session, never any live PTY.+ */+ readonly submit: boolean;+}+export function requestActiveTerminalInput(text: string,+ options?: { newTab?: boolean; submit?: boolean },target: Pick<Window, 'dispatchEvent'> | EventTarget = typeof window === 'undefined'? new EventTarget(): window,): void {- target.dispatchEvent(new CustomEvent<string>(ACTIVE_TERMINAL_INPUT_EVENT, { detail: text }));+ target.dispatchEvent(+ new CustomEvent<ActiveTerminalInputDetail>(ACTIVE_TERMINAL_INPUT_EVENT, {+ detail: { text, newTab: options?.newTab === true, submit: options?.submit === true },+ }),+ );}export function subscribeToActiveTerminalInput(- onRequest: (text: string) => void,+ onRequest: (detail: ActiveTerminalInputDetail) => void,target: Pick<Window, 'addEventListener' | 'removeEventListener'> | EventTarget = typeof window ==='undefined'? new EventTarget(): window,): () => void {const listener = (event: Event) => {- const text = event instanceof CustomEvent ? (event as CustomEvent<string>).detail : undefined;- if (typeof text === 'string') onRequest(text);+ const detail =+ event instanceof CustomEvent+ ? (event as CustomEvent<ActiveTerminalInputDetail>).detail+ : undefined;+ if (detail !== undefined && typeof detail.text === 'string') {+ onRequest({+ text: detail.text,+ newTab: detail.newTab === true,+ submit: detail.submit === true,+ });+ }};target.addEventListener(ACTIVE_TERMINAL_INPUT_EVENT, listener as EventListener);return () => target.removeEventListener(ACTIVE_TERMINAL_INPUT_EVENT, listener as EventListener);diff --git a/packages/app/src/components/handoff/terminal-launch-events.test.ts b/packages/app/src/components/handoff/terminal-launch-events.test.tsindex 29ef2eeb5..34b7324c4 100644--- a/packages/app/src/components/handoff/terminal-launch-events.test.ts+++ b/packages/app/src/components/handoff/terminal-launch-events.test.ts@@ -11,13 +11,40 @@ describe('terminal-launch-events', () => {target,);- requestTerminalLaunch("Let's work on `foo.md` using OpenKnowledge.", 'codex', target);+ requestTerminalLaunch(+ "Let's work on `foo.md` using OpenKnowledge.",+ 'codex',+ undefined,+ target,+ );expect(received).toEqual([{ prompt: "Let's work on `foo.md` using OpenKnowledge.", cli: 'codex' },]);unsub();- requestTerminalLaunch('after unsubscribe', 'cursor', target);+ requestTerminalLaunch('after unsubscribe', 'cursor', undefined, target);expect(received).toHaveLength(1);});++ // `stage` picks which slot the text lands in downstream: unset (the default,+ // used by "Open in terminal" and the Ask AI surfaces) bakes it as the CLI's+ // prompt so it RUNS; set (the ⌘J/⇧⌘J selection sends) routes it to `stagePaste`+ // so it is written and waits. Defaulting this the wrong way would auto-run a+ // passage the user merely highlighted.+ test.each([+ { options: undefined, expected: false, label: 'defaults to running the prompt' },+ { options: { stage: false }, expected: false, label: 'explicit stage:false runs' },+ { options: { stage: true }, expected: true, label: 'stage:true defers to the input' },+ ])('$label', ({ options, expected }) => {+ const target = new EventTarget();+ const received: boolean[] = [];+ const unsub = subscribeToTerminalLaunchRequests(+ (_p, _c, opts) => received.push(opts.stage),+ target,+ );++ requestTerminalLaunch('some text', 'claude', options, target);+ expect(received).toEqual([expected]);+ unsub();+ });});diff --git a/packages/app/src/components/handoff/terminal-launch-events.ts b/packages/app/src/components/handoff/terminal-launch-events.tsindex 75cfb6a47..7e1587674 100644--- a/packages/app/src/components/handoff/terminal-launch-events.ts+++ b/packages/app/src/components/handoff/terminal-launch-events.ts@@ -21,22 +21,38 @@ const TERMINAL_LAUNCH_EVENT = 'open-knowledge:terminal-launch';interface TerminalLaunchDetail {readonly prompt: string;readonly cli: TerminalCli;+ readonly stage: boolean;+}++/** How the launched CLI receives the text. */+export interface TerminalLaunchOptions {+ /**+ * Write the text into the CLI's input and STOP, instead of running it. Maps to+ * the launch intent's `stagePaste` rather than its `prompt` — the ⌘J/⇧⌘J+ * selection sends use this, because a raw passage is material the user extends+ * before sending. Composed instructions ("Open in terminal", the Ask AI+ * surfaces) leave it unset and run on launch.+ */+ readonly stage?: boolean;}export function requestTerminalLaunch(prompt: string,cli: TerminalCli,+ options?: TerminalLaunchOptions,target: Pick<Window, 'dispatchEvent'> | EventTarget = typeof window === 'undefined'? new EventTarget(): window,): void {target.dispatchEvent(- new CustomEvent<TerminalLaunchDetail>(TERMINAL_LAUNCH_EVENT, { detail: { prompt, cli } }),+ new CustomEvent<TerminalLaunchDetail>(TERMINAL_LAUNCH_EVENT, {+ detail: { prompt, cli, stage: options?.stage === true },+ }),);}export function subscribeToTerminalLaunchRequests(- onRequest: (prompt: string, cli: TerminalCli) => void,+ onRequest: (prompt: string, cli: TerminalCli, options: { stage: boolean }) => void,target: Pick<Window, 'addEventListener' | 'removeEventListener'> | EventTarget = typeof window ==='undefined'? new EventTarget()@@ -47,7 +63,9 @@ export function subscribeToTerminalLaunchRequests(event instanceof CustomEvent? (event as CustomEvent<TerminalLaunchDetail>).detail: undefined;- if (detail && typeof detail.prompt === 'string') onRequest(detail.prompt, detail.cli);+ if (detail && typeof detail.prompt === 'string') {+ onRequest(detail.prompt, detail.cli, { stage: detail.stage === true });+ }};target.addEventListener(TERMINAL_LAUNCH_EVENT, listener as EventListener);return () => target.removeEventListener(TERMINAL_LAUNCH_EVENT, listener as EventListener);diff --git a/packages/app/src/editor/bubble-menu/EditWithAiBubbleButton.dom.test.tsx b/packages/app/src/editor/bubble-menu/EditWithAiBubbleButton.dom.test.tsxindex a81e2defd..b39a276e4 100644--- a/packages/app/src/editor/bubble-menu/EditWithAiBubbleButton.dom.test.tsx+++ b/packages/app/src/editor/bubble-menu/EditWithAiBubbleButton.dom.test.tsx@@ -22,7 +22,10 @@ import type { Editor } from '@tiptap/react';import type { ReactNode } from 'react';import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';import { subscribeToOpenAskAiComposer } from '@/components/ask-ai-composer-events';-import { subscribeToActiveTerminalInput } from '@/components/handoff/terminal-input-events';+import {+ type ActiveTerminalInputDetail,+ subscribeToActiveTerminalInput,+} from '@/components/handoff/terminal-input-events';import { setEditorDocName } from '../extensions/doc-context.ts';vi.doMock('sonner', () => ({ toast: { error: () => {}, success: () => {} } }));@@ -92,7 +95,7 @@ let openRequests = 0;let unsubscribe: (() => void) | null = null;// Capture text routed to the active-terminal input channel (TerminalSessionsHost's// subscriber path in production).-let terminalInputs: string[] = [];+let terminalInputs: ActiveTerminalInputDetail[] = [];let unsubscribeTerminal: (() => void) | null = null;function renderButton({@@ -131,8 +134,8 @@ beforeEach(() => {unsubscribe = subscribeToOpenAskAiComposer(() => {openRequests += 1;});- unsubscribeTerminal = subscribeToActiveTerminalInput((text) => {- terminalInputs.push(text);+ unsubscribeTerminal = subscribeToActiveTerminalInput((detail) => {+ terminalInputs.push(detail);});});@@ -217,10 +220,13 @@ describe('EditWithAiBubbleButton', () => {// (tested in core); here we assert the grounding is present. Dispatch is// deferred a frame, so flush it before asserting.await waitFor(() => expect(terminalInputs).toHaveLength(1));- const [prompt] = terminalInputs;- expect(prompt).toContain('@specs/foo/SPEC.md');- expect(prompt).toContain('A passage.');- expect(prompt).not.toBe('A passage.');+ const [detail] = terminalInputs;+ expect(detail.text).toContain('@specs/foo/SPEC.md');+ expect(detail.text).toContain('A passage.');+ expect(detail.text).not.toBe('A passage.');+ // A composed, self-contained Ask AI instruction RUNS on a fresh session+ // (submit), unlike the ⌘J selection send which stages unsent.+ expect(detail.submit).toBe(true);expect(openRequests).toBe(0);});diff --git a/packages/app/src/editor/bubble-menu/EditWithAiBubbleButton.tsx b/packages/app/src/editor/bubble-menu/EditWithAiBubbleButton.tsxindex ff2b22135..9843052aa 100644--- a/packages/app/src/editor/bubble-menu/EditWithAiBubbleButton.tsx+++ b/packages/app/src/editor/bubble-menu/EditWithAiBubbleButton.tsx@@ -125,7 +125,11 @@ function EditWithAiBubbleMenu({emitOpenAskAiComposer();return;}- requestActiveTerminalInput(composeTerminalSelectionPaste(docName, selectionMarkdown));+ // A composed, self-contained ask — runs on a fresh session (what a+ // fresh CLI has always done), on a CLI and an agent thread alike.+ requestActiveTerminalInput(composeTerminalSelectionPaste(docName, selectionMarkdown), {+ submit: true,+ });});}}>diff --git a/packages/app/src/editor/extensions/CodeBlockView.dom.test.tsx b/packages/app/src/editor/extensions/CodeBlockView.dom.test.tsxindex b82f374f8..356141f4b 100644--- a/packages/app/src/editor/extensions/CodeBlockView.dom.test.tsx+++ b/packages/app/src/editor/extensions/CodeBlockView.dom.test.tsx@@ -14,7 +14,10 @@ import { act, cleanup, fireEvent, render, waitFor } from '@testing-library/reactimport type { NodeViewProps } from '@tiptap/core';import { afterEach, describe, expect, test, vi } from 'vitest';import { subscribeToOpenAskAiComposer } from '@/components/ask-ai-composer-events';-import { subscribeToActiveTerminalInput } from '@/components/handoff/terminal-input-events';+import {+ type ActiveTerminalInputDetail,+ subscribeToActiveTerminalInput,+} from '@/components/handoff/terminal-input-events';import { ConfigContext, type ConfigContextValue } from '@/lib/config-context';// The Ask AI click handler routes through `serializeWysiwygSelection`, which@@ -246,7 +249,7 @@ describe('CodeBlockView Ask AI dispatch', () => {}) as typeof globalThis.requestAnimationFrame;}- let terminalInputs: string[] = [];+ let terminalInputs: ActiveTerminalInputDetail[] = [];let composerOpens = 0;let unsubscribeTerminal: (() => void) | null = null;let unsubscribeComposer: (() => void) | null = null;@@ -262,8 +265,8 @@ describe('CodeBlockView Ask AI dispatch', () => {});function subscribeAll() {- unsubscribeTerminal = subscribeToActiveTerminalInput((text) => {- terminalInputs.push(text);+ unsubscribeTerminal = subscribeToActiveTerminalInput((detail) => {+ terminalInputs.push(detail);});unsubscribeComposer = subscribeToOpenAskAiComposer(() => {composerOpens += 1;@@ -335,12 +338,14 @@ describe('CodeBlockView Ask AI dispatch', () => {fireEvent.click(askBtn as HTMLButtonElement);await waitFor(() => expect(terminalInputs).toHaveLength(1));- const [prompt] = terminalInputs;+ const [detail] = terminalInputs;// Doc named as an @-mention (grounding contract from composeSelectionPrompt).- expect(prompt).toContain('@specs/foo/SPEC.md');+ expect(detail.text).toContain('@specs/foo/SPEC.md');// Stubbed fenced body survives verbatim into the composed prompt.- expect(prompt).toContain('```json');- expect(prompt).toContain('{ "name": "sample" }');+ expect(detail.text).toContain('```json');+ expect(detail.text).toContain('{ "name": "sample" }');+ // A composed Ask AI instruction RUNS on a fresh session (submit).+ expect(detail.submit).toBe(true);// Terminal-input branch does NOT open the composer.expect(composerOpens).toBe(0);});diff --git a/packages/app/src/editor/extensions/CodeBlockView.tsx b/packages/app/src/editor/extensions/CodeBlockView.tsxindex 63f2b7a8c..c8a308fd9 100644--- a/packages/app/src/editor/extensions/CodeBlockView.tsx+++ b/packages/app/src/editor/extensions/CodeBlockView.tsx@@ -667,6 +667,9 @@ export function CodeBlockView({ node, updateAttributes, editor, getPos, selectedselectionMarkdown,target: 'claude-code',}),+ // A composed ask, so a fresh session runs it — matching the+ // fresh-CLI behavior this surface has always had.+ { submit: true },);});}}diff --git a/packages/app/src/hooks/use-installed-clis.ts b/packages/app/src/hooks/use-installed-clis.tsindex a24cc9644..7229c2023 100644--- a/packages/app/src/hooks/use-installed-clis.ts+++ b/packages/app/src/hooks/use-installed-clis.ts@@ -10,7 +10,7 @@ import { useEffect, useState } from 'react';* Starts empty (unknown, not "none installed") until the async probe resolves.* A partial/older bridge, the web host with no `terminal` surface, or a probe* failure leaves keys `undefined` (unknown). Consumers must NOT read unknown as- * "absent": `resolveDefaultCli` treats it optimistically, and `isTerminalCliEnabled`+ * "absent": the default-CLI pick treats it optimistically, and `isTerminalCliEnabled`* fails open (an unknown CLI still renders), so a probe miss never silently drops* an installed CLI from the launch surfaces for the whole session.*diff --git a/packages/app/src/lib/acp/agent-visibility.ts b/packages/app/src/lib/acp/agent-visibility.tsindex d134e3729..857296184 100644--- a/packages/app/src/lib/acp/agent-visibility.ts+++ b/packages/app/src/lib/acp/agent-visibility.ts@@ -46,8 +46,8 @@ export function isInAppAgentEnabled(* (`undefined`, e.g. the cold-start window) still shows the row, so a probe miss* never silently drops an installed CLI. Claude is not special-cased visible: a* probed-absent Claude CLI hides like any other. The user can still re-enable it- * in Settings, and the install-nudge launch default in `resolveDefaultCli` is a- * separate last-resort path, not a visibility rule.+ * in Settings, and the install-nudge launch default is a separate last-resort+ * path, not a visibility rule.*/export function isTerminalCliEnabled(overrides: EnabledOverrides,diff --git a/packages/app/src/lib/acp/launch-agent-thread.ts b/packages/app/src/lib/acp/launch-agent-thread.tsindex 91fc9f387..93e7f1511 100644--- a/packages/app/src/lib/acp/launch-agent-thread.ts+++ b/packages/app/src/lib/acp/launch-agent-thread.ts@@ -11,6 +11,7 @@import { t } from '@lingui/core/macro';import { toast } from 'sonner';import { getAgentThreadClient, ThreadChannelUnavailableError } from '@/lib/acp/thread-client';+import { stageThreadDraft } from '@/lib/acp/thread-draft-staging';/*** One launch per agent may be in flight at a time: creation can take seconds@@ -25,12 +26,19 @@ const inflightLaunches = new Set<string>();* Create a thread for a concrete agent. Agent-level failures stream into the dock* as thread status events; the catch fires only when no thread was created at all,* so a toast is the sole feedback channel there.+ *+ * `stageDraft` seeds the new thread's composer with text the user is meant to+ * review before sending (a ⌘J selection send, a Problems-panel "Ask AI"). It is+ * deliberately separate from `prompt`: a prompt runs on creation, a staged draft+ * waits on the user's send. Passing both is legal but unusual — the prompt runs+ * and the draft sits under it as the follow-up.*/export function launchAgentThread(agent: { source: 'registry' | 'custom'; id: string },prompt: string | null,docName: string | null,titleHint: string | null,+ stageDraft?: string | null,): void {const launchKey = `${agent.source}:${agent.id}`;if (inflightLaunches.has(launchKey)) return;@@ -42,6 +50,19 @@ export function launchAgentThread(docName: docName ?? undefined,titleHint: titleHint ?? undefined,})+ .then((info) => {+ // Staged only once the server has minted the id the composer is keyed by.+ // Isolated from the shared catch below: by the time this runs the thread+ // EXISTS, so letting a staging failure fall through would log "launch+ // failed" and tell the user to retry a launch that actually succeeded.+ if (stageDraft != null) {+ try {+ stageThreadDraft(info.threadId, stageDraft);+ } catch (err) {+ console.error('[agent-threads] draft staging failed for', info.threadId, err);+ }+ }+ }).catch((err) => {console.error('[agent-threads] launch failed:', err);toast.error(diff --git a/packages/app/src/lib/acp/thread-draft-staging.test.ts b/packages/app/src/lib/acp/thread-draft-staging.test.tsnew file mode 100644index 000000000..e0a36017b--- /dev/null+++ b/packages/app/src/lib/acp/thread-draft-staging.test.ts@@ -0,0 +1,82 @@+import { afterEach, describe, expect, test, vi } from 'vitest';+import {+ resetStagedThreadDrafts,+ stageThreadDraft,+ subscribeStagedThreadDraft,+} from './thread-draft-staging';++afterEach(() => {+ resetStagedThreadDrafts();+});++describe('thread draft staging', () => {+ // The two ends genuinely race: `launchAgentThread` stages once `createThread`+ // resolves, while `ThreadView` subscribes when the dock mounts its tab. Both+ // orders have to deliver, or an Ask AI silently loses the user's passage.+ test('delivers to a subscriber that arrives AFTER the stage', () => {+ stageThreadDraft('thread-1', 'fix this lint error');+ const seen: string[] = [];+ subscribeStagedThreadDraft('thread-1', (text) => seen.push(text));+ expect(seen).toEqual(['fix this lint error']);+ });++ test('delivers to a subscriber that arrives BEFORE the stage', () => {+ const seen: string[] = [];+ subscribeStagedThreadDraft('thread-1', (text) => seen.push(text));+ stageThreadDraft('thread-1', 'fix this lint error');+ expect(seen).toEqual(['fix this lint error']);+ });++ // A remount must not re-seed a draft the user already cleared.+ test('consumes exactly once', () => {+ stageThreadDraft('thread-1', 'first');+ const first: string[] = [];+ const stop = subscribeStagedThreadDraft('thread-1', (text) => first.push(text));+ stop();+ const second: string[] = [];+ subscribeStagedThreadDraft('thread-1', (text) => second.push(text));+ expect(first).toEqual(['first']);+ expect(second).toEqual([]);+ });++ test('routes each thread its own draft', () => {+ stageThreadDraft('thread-1', 'for one');+ stageThreadDraft('thread-2', 'for two');+ const one: string[] = [];+ const two: string[] = [];+ subscribeStagedThreadDraft('thread-1', (text) => one.push(text));+ subscribeStagedThreadDraft('thread-2', (text) => two.push(text));+ expect(one).toEqual(['for one']);+ expect(two).toEqual(['for two']);+ });++ // Nothing to review — staging it would just flash an empty composer.+ test.each([' ', '', '\n\t '])('ignores whitespace-only text (%j)', (text) => {+ const seen: string[] = [];+ subscribeStagedThreadDraft('thread-1', (t) => seen.push(t));+ stageThreadDraft('thread-1', text);+ expect(seen).toEqual([]);+ });++ test('unsubscribe stops delivery', () => {+ const seen: string[] = [];+ const stop = subscribeStagedThreadDraft('thread-1', (text) => seen.push(text));+ stop();+ stageThreadDraft('thread-1', 'too late');+ expect(seen).toEqual([]);+ });++ // A remount can register its listener before the previous one's cleanup runs+ // (React StrictMode, fast tab flips). The stale cleanup must not evict the+ // newer listener, or the very next stage goes nowhere.+ test('a stale unsubscribe does not evict a newer listener', () => {+ const older = vi.fn();+ const newer = vi.fn();+ const stopOlder = subscribeStagedThreadDraft('thread-1', older);+ subscribeStagedThreadDraft('thread-1', newer);+ stopOlder();+ stageThreadDraft('thread-1', 'after remount');+ expect(newer).toHaveBeenCalledWith('after remount');+ expect(older).not.toHaveBeenCalled();+ });+});diff --git a/packages/app/src/lib/acp/thread-draft-staging.ts b/packages/app/src/lib/acp/thread-draft-staging.tsnew file mode 100644index 000000000..cc27ea6c8--- /dev/null+++ b/packages/app/src/lib/acp/thread-draft-staging.ts@@ -0,0 +1,82 @@+/**+ * One-shot staged composer text for a freshly-launched agent thread — the ACP+ * twin of the terminal launch intent's `stagePaste`.+ *+ * A selection send (⌘J / ⇧⌘J) and the Problems panel's "Ask AI" both hand the+ * user a composed passage they are meant to review and extend before sending.+ * On the terminal path that means writing into the CLI's input without a+ * trailing carriage return; on the thread path it means seeding the composer's+ * draft and leaving the send button to the user. Auto-submitting instead would+ * spend the customer's tokens on a keystroke the user may have mis-fired.+ *+ * Delivery is order-independent because the two ends race: `launchAgentThread`+ * stages once `createThread` resolves, while `ThreadView` subscribes when the+ * dock mounts its tab — and either can happen first. A value staged before+ * anyone subscribes is held until the first subscriber for that thread arrives;+ * a subscriber that arrives first is delivered to directly. Either way the value+ * is consumed exactly once, so a later remount of the same thread does not+ * re-seed a draft the user already cleared.+ */++/**+ * Staged text awaiting a subscriber, keyed by threadId.+ *+ * Module scope, so this is per-renderer and each window has its own map — the+ * same single-window assumption `inflightLaunches` makes in `launch-agent-thread`.+ *+ * An entry normally lives for microseconds: a docked thread force-mounts its+ * composer, so the subscriber arrives right after the stage. An entry only+ * lingers when the thread never mounts at all (closed before its lazy ThreadView+ * chunk resolves). Two consequences of not evicting: one short string per orphan+ * stays for the renderer's lifetime, and reopening that exact thread from archive+ * would hand its composer the old passage. Both are bounded and rare enough that+ * a TTL would add more moving parts than it removes.+ */+const pending = new Map<string, string>();++/** The live subscriber per threadId (a thread renders in at most one tab). */+const listeners = new Map<string, (text: string) => void>();++/**+ * Stage `text` as the opening draft for `threadId`. Delivered immediately when+ * that thread's composer is already listening, otherwise held for it. Empty /+ * whitespace-only text is ignored — there is nothing to review.+ */+export function stageThreadDraft(threadId: string, text: string): void {+ if (text.trim() === '') return;+ const listener = listeners.get(threadId);+ if (listener !== undefined) {+ listener(text);+ return;+ }+ pending.set(threadId, text);+}++/**+ * Subscribe `onDraft` to staged text for `threadId`, consuming anything already+ * staged. Returns the unsubscribe. The subscription is single-slot per thread:+ * a remount replaces the prior listener rather than fanning out, matching the+ * one-tab-per-thread invariant the dock maintains.+ */+export function subscribeStagedThreadDraft(+ threadId: string,+ onDraft: (text: string) => void,+): () => void {+ listeners.set(threadId, onDraft);+ const held = pending.get(threadId);+ if (held !== undefined) {+ pending.delete(threadId);+ onDraft(held);+ }+ return () => {+ // Only clear the slot when it is still ours — a remount that registered its+ // own listener before this cleanup ran must keep the newer one.+ if (listeners.get(threadId) === onDraft) listeners.delete(threadId);+ };+}++/** Test seam — drop all staged state between cases. */+export function resetStagedThreadDrafts(): void {+ pending.clear();+ listeners.clear();+}diff --git a/packages/app/src/lib/default-cli-resolver.test.ts b/packages/app/src/lib/default-cli-resolver.test.tsdeleted file mode 100644index d1f5b4920..000000000--- a/packages/app/src/lib/default-cli-resolver.test.ts+++ /dev/null@@ -1,121 +0,0 @@-/**- * Unit tests for the default-CLI resolver — the one deterministic function that- * both the header/tab-strip "New chat" launch and the "Ask X" bubble use to- * pick which CLI to start when the user has not (or has) set a sticky default.- *- * Resolution contract:- * 1. sticky parses to a CLI (via parseStickyCliId) → it, unconditionally- * (an explicit pick is honored even when the CLI is KNOWN-absent);- * 2. else the first KNOWN-installed CLI by priority (claude > codex > opencode > cursor > copilot > pi);- * 3. else 'claude'.- */--import { TERMINAL_CLI_IDS, type TerminalCli } from '@inkeep/open-knowledge-core';-import { describe, expect, test } from 'vitest';-import { resolveDefaultCli } from './default-cli-resolver';-import { TERMINAL_CLI_ID, terminalCliId } from './unified-agent-store';--/**- * Build a FULLY-RESOLVED installed map (every CLI keyed to true/false), matching- * what the desktop `resolveCliInstalledMap` probe returns — so an absent CLI is- * explicit `false` (known not-on-PATH), NOT `undefined` (which the resolver- * treats as still-unknown / cold-start). Pass `{}` for the cold-start case.- */-function installedMap(clis: readonly TerminalCli[]): Record<TerminalCli, boolean> {- return Object.fromEntries(TERMINAL_CLI_IDS.map((cli) => [cli, clis.includes(cli)])) as Record<- TerminalCli,- boolean- >;-}--describe('resolveDefaultCli', () => {- describe('sticky pick', () => {- test('a sticky CLI that is installed wins, even over a higher-priority installed CLI', () => {- // codex is sticky and installed; claude (higher priority) is also installed —- // the explicit pick must beat the priority auto-pick.- expect(resolveDefaultCli(terminalCliId('codex'), installedMap(['claude', 'codex']))).toBe(- 'codex',- );- });-- test('a sticky CLI that is NOT installed is still honored (respect the explicit pick)', () => {- // cursor is sticky but not on PATH; codex/opencode ARE installed. The- // explicit pick still wins — launching it surfaces the "Get Cursor" banner- // rather than silently substituting an installed CLI the user didn't pick.- expect(resolveDefaultCli(terminalCliId('cursor'), installedMap(['opencode', 'codex']))).toBe(- 'cursor',- );- });-- test('the legacy bare `terminal-cli` sentinel resolves to claude when installed', () => {- expect(resolveDefaultCli(TERMINAL_CLI_ID, installedMap(['claude', 'codex']))).toBe('claude');- });-- test('the legacy bare sentinel is honored (claude) even when claude is not installed', () => {- // The bare sentinel is a real prior terminal pick (claude-only era), so it- // is honored as an explicit claude pick rather than substituting opencode.- expect(resolveDefaultCli(TERMINAL_CLI_ID, installedMap(['opencode']))).toBe('claude');- });-- test('an app-target sticky (not a CLI sentinel) is ignored — New chat only launches CLIs', () => {- // 'claude-code' is a HandoffTarget id, not a terminal-cli:<cli> sentinel;- // parseStickyCliId returns null, so we fall through to first-installed.- expect(resolveDefaultCli('claude-code', installedMap(['codex']))).toBe('codex');- });- });-- describe('priority auto-pick (no usable sticky)', () => {- test('null sticky picks the highest-priority installed CLI', () => {- expect(resolveDefaultCli(null, installedMap(['codex', 'opencode', 'cursor']))).toBe('codex');- });-- test('respects the full priority order claude > codex > opencode > cursor > copilot > pi', () => {- expect(resolveDefaultCli(null, installedMap(['copilot', 'opencode']))).toBe('opencode');- expect(resolveDefaultCli(null, installedMap(['opencode', 'cursor']))).toBe('opencode');- expect(resolveDefaultCli(null, installedMap(['cursor', 'copilot']))).toBe('cursor');- expect(resolveDefaultCli(null, installedMap(['copilot', 'pi']))).toBe('copilot');- expect(resolveDefaultCli(null, installedMap(['pi']))).toBe('pi');- expect(resolveDefaultCli(null, installedMap(['claude', 'codex', 'opencode', 'cursor']))).toBe(- 'claude',- );- });- });-- describe('nothing installed', () => {- test('empty install map + no sticky → claude (the install-nudge default)', () => {- expect(resolveDefaultCli(null, {})).toBe('claude');- });-- test('all-false install map → claude', () => {- expect(- resolveDefaultCli(null, {- claude: false,- codex: false,- opencode: false,- cursor: false,- pi: false,- }),- ).toBe('claude');- });-- test('a KNOWN-absent sticky CLI with nothing installed is still honored', () => {- // Fully-resolved all-false map: codex is known not-on-PATH, but the explicit- // pick still wins over the (empty) priority auto-pick — the launch then- // surfaces the "Get Codex" missing-CLI banner.- expect(resolveDefaultCli(terminalCliId('codex'), installedMap([]))).toBe('codex');- });- });-- describe('cold start (probe not yet resolved → unknown, not known-absent)', () => {- test('a sticky CLI is honored against an empty/unknown map (not dropped to claude)', () => {- // The header/tab-strip New chat can fire before the async login-shell probe- // fills the map; the remembered pick must survive rather than silently- // becoming claude — matching the Ask-X bubble.- expect(resolveDefaultCli(terminalCliId('codex'), {})).toBe('codex');- });-- test('no sticky + unknown map → claude (priority auto-pick needs a positive install)', () => {- expect(resolveDefaultCli(null, {})).toBe('claude');- });- });-});diff --git a/packages/app/src/lib/default-cli-resolver.ts b/packages/app/src/lib/default-cli-resolver.tsdeleted file mode 100644index dd7b6a44b..000000000--- a/packages/app/src/lib/default-cli-resolver.ts+++ /dev/null@@ -1,43 +0,0 @@-/**- * The single deterministic rule for "which CLI does New chat launch?" — shared- * by the header + tab-strip New-chat buttons and the "Ask X" bubble default so- * every entry point agrees on the same CLI.- *- * A New chat only ever launches a terminal CLI, so an app-target sticky pick- * (a `HandoffTarget` id, e.g. `claude-code`) is intentionally ignored here —- * `parseStickyCliId` returns `null` for it and resolution falls through to the- * installed-priority auto-pick. Priority order is `TERMINAL_CLI_IDS` itself- * (claude > codex > opencode > cursor > copilot > pi); reusing it keeps the auto-pick order in- * lockstep with the visible launch-row order rather than duplicating a list.- */--import { TERMINAL_CLI_IDS, type TerminalCli } from '@inkeep/open-knowledge-core';-import { parseStickyCliId } from './unified-agent-store';--/**- * Resolve the default CLI from the raw sticky pick and the installed-CLI map:- *- * 1. sticky parses to a CLI ({@link parseStickyCliId}) → it, unconditionally.- * An explicit pick is honored even when the CLI is KNOWN-absent: the user- * chose it, so launching it (and surfacing the "Get <CLI>" missing-CLI- * banner) respects that choice rather than silently substituting whatever- * happens to be installed. The install state is irrelevant to this branch;- * it also means a click during the cold-start probe window keeps the- * remembered pick — matching the Ask-X bubble.- * 2. else the first known-installed CLI by `TERMINAL_CLI_IDS` priority;- * 3. else `'claude'` (the install-nudge default — launching it surfaces the- * existing "Get Claude" banner when nothing is on PATH).- *- * `installed` is a partial map: an unresolved probe leaves keys `undefined`- * (unknown), distinct from `false` (probed, not on PATH). It gates only the- * priority auto-pick (branch 2), which needs a positive `true` and so waits for- * the probe rather than guessing; the explicit sticky pick ignores it entirely.- */-export function resolveDefaultCli(- sticky: string | null,- installed: Partial<Record<TerminalCli, boolean>>,-): TerminalCli {- const stickyCli = parseStickyCliId(sticky);- if (stickyCli) return stickyCli;- return TERMINAL_CLI_IDS.find((cli) => installed[cli] === true) ?? 'claude';-}diff --git a/packages/app/src/lib/keyboard-shortcuts.ts b/packages/app/src/lib/keyboard-shortcuts.tsindex 06a2d5aa5..264cf60a9 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. With text selected, stage it in the terminal's AI input instead.`,+ description: msg`Toggle the bottom terminal panel. With text selected, stage it for your preferred AI instead.`,scope: msg`OK Desktop`,bindings: [{@@ -202,13 +202,13 @@ 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.+ // Sibling of ⌘J: opens a fresh session with the preferred AI. With text+ // selected, that selection is staged into the new session. 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.`,+ title: msg`New session`,+ description: msg`Open a new session with your preferred AI. With text selected, stage it there instead of running it.`,scope: msg`OK Desktop`,bindings: [{diff --git a/packages/app/src/lib/unified-agent-store.ts b/packages/app/src/lib/unified-agent-store.tsindex 272093675..523a90a24 100644--- a/packages/app/src/lib/unified-agent-store.ts+++ b/packages/app/src/lib/unified-agent-store.ts@@ -62,8 +62,8 @@ export function terminalCliId(cli: TerminalCli): string {* like a sticky agent choice. `parseStickyCliId` returns null for it and* `resolveStickyAgent` (app targets only) never returns it, so callers gate* thread mode explicitly (`id === IN_APP_THREAD_ID`) — the same shape the- * CLI sentinel uses. On terminal-only surfaces it degrades via- * `resolveDefaultCli` to the default CLI, harmlessly.+ * CLI sentinel uses. On terminal-only surfaces it degrades to the default CLI,+ * harmlessly.** Two forms coexist (additive parse, no key bump — see {@link parseStickyThreadAgent}):* - the bare `in-app-thread` sentinel — "in-app thread, whatever the defaultdiff --git a/packages/app/src/locales/en/messages.json b/packages/app/src/locales/en/messages.jsonindex 47706eff4..5baea6993 100644--- a/packages/app/src/locales/en/messages.json+++ b/packages/app/src/locales/en/messages.json@@ -1801,6 +1801,7 @@"Yi0VMG": ["Upload ", ["keyName"]],"YjMLg2": ["Off — external links show only their URL. No requests leave this computer."],"YjhKI5": ["Cloning..."],+ "YkvmF4": ["New session"],"YlDuro": ["Fit height"],"YsEYYS": [["behind", "plural", { "one": ["#", " commit behind"], "other": ["#", " commits behind"] }]@@ -2369,6 +2370,9 @@"iv452l": ["Documentation for ", ["0"], " (opens in browser)"],"iy64Li": ["Full sync — your edits are committed and pushed to your remote automatically."],"iycx_A": ["Pushing"],+ "j2kt1j": [+ "Open a new session with your preferred AI. With text selected, stage it there instead of running it."+ ],"j5CWO4": ["Up to date"],"j9Vqvc": ["inherited"],"j9tqwO": ["Not in sidebar"],@@ -2412,7 +2416,6 @@],"jxtXZI": ["Install the gh CLI"],"k0dL2I": ["Reconnecting to the agent service…"],- "k0vc0N": ["New terminal tab"],"k2fEi7": ["User plugins are personal to this device — turn them on or off here. The choice lives in your user config and is never committed to the project. Each enabled plugin gets its own page under Plugins in the settings sidebar."],@@ -2506,6 +2509,9 @@["4"],") that won't touch the rest of your system."],+ "l9HUtd": [+ "Toggle the bottom terminal panel. With text selected, stage it for your preferred AI instead."+ ],"lAiyU_": ["Only the current document uses <0>#", ["tag"], "</0>."],"lCC_D5": ["Subscribing..."],"lGs_bQ": ["Page <0>*</0>"],@@ -2683,9 +2689,6 @@"oBK5fD": ["Overlapping edits"],"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."],@@ -2885,9 +2888,6 @@"seeS6l": ["Setup OpenKnowledge in this folder?"],"sgmRY8": ["Skipped downloading ", ["0"], "."],"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."],"sn5BEU": [["sizeText"],diff --git a/packages/app/src/locales/en/messages.po b/packages/app/src/locales/en/messages.poindex c79985742..a46b42773 100644--- a/packages/app/src/locales/en/messages.po+++ b/packages/app/src/locales/en/messages.po@@ -5765,6 +5765,10 @@ msgstr "New property name"msgid "New schema"msgstr "New schema"+#: src/lib/keyboard-shortcuts.ts+msgid "New session"+msgstr "New session"+#: src/components/NewSkillDialog.tsx#: src/components/settings/SkillsManagerSection.tsx#: src/components/SkillsSidebarSection.tsx@@ -5790,10 +5794,6 @@ msgstr "New terminal"msgid "New Terminal"msgstr "New Terminal"-#: src/lib/keyboard-shortcuts.ts-msgid "New terminal tab"-msgstr "New terminal tab"-#. placeholder {0}: info.agent.name#: src/components/acp/ThreadView.tsxmsgid "New thread with {0}"@@ -6316,6 +6316,10 @@ msgstr "Open a blank editor tab."msgid "Open a doc to share its URL."msgstr "Open a doc to share its URL."+#: src/lib/keyboard-shortcuts.ts+msgid "Open a new session with your preferred AI. With text selected, stage it there instead of running it."+msgstr "Open a new session with your preferred AI. With text selected, stage it there instead of running it."+#: src/components/settings/SettingsDialogShell.tsxmsgid "Open a project to edit."msgstr "Open a project to edit."@@ -6340,10 +6344,6 @@ 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."@@ -9596,8 +9596,8 @@ msgid "Toggle strikethrough formatting."msgstr "Toggle strikethrough formatting."#: src/lib/keyboard-shortcuts.ts-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."+msgid "Toggle the bottom terminal panel. With text selected, stage it for your preferred AI instead."+msgstr "Toggle the bottom terminal panel. With text selected, stage it for your preferred AI 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 bb2a0b4a9..27b5694fa 100644--- a/packages/app/src/locales/pseudo/messages.json+++ b/packages/app/src/locales/pseudo/messages.json@@ -1801,6 +1801,7 @@"Yi0VMG": ["Ũƥĺōàď ", ["keyName"]],"YjMLg2": ["Ōƒƒ — ēxţēŕńàĺ ĺĩńķś śĥōŵ ōńĺŷ ţĥēĩŕ ŨŔĹ. Ńō ŕēǫũēśţś ĺēàvē ţĥĩś ćōḿƥũţēŕ."],"YjhKI5": ["Ćĺōńĩńĝ..."],+ "YkvmF4": ["Ńēŵ śēśśĩōń"],"YlDuro": ["Ƒĩţ ĥēĩĝĥţ"],"YsEYYS": [["behind", "plural", { "one": ["#", " ćōḿḿĩţ ƀēĥĩńď"], "other": ["#", " ćōḿḿĩţś ƀēĥĩńď"] }]@@ -2369,6 +2370,9 @@"iv452l": ["Ďōćũḿēńţàţĩōń ƒōŕ ", ["0"], " (ōƥēńś ĩń ƀŕōŵśēŕ)"],"iy64Li": ["Ƒũĺĺ śŷńć — ŷōũŕ ēďĩţś àŕē ćōḿḿĩţţēď àńď ƥũśĥēď ţō ŷōũŕ ŕēḿōţē àũţōḿàţĩćàĺĺŷ."],"iycx_A": ["Ƥũśĥĩńĝ"],+ "j2kt1j": [+ "Ōƥēń à ńēŵ śēśśĩōń ŵĩţĥ ŷōũŕ ƥŕēƒēŕŕēď ÀĨ. Ŵĩţĥ ţēxţ śēĺēćţēď, śţàĝē ĩţ ţĥēŕē ĩńśţēàď ōƒ ŕũńńĩńĝ ĩţ."+ ],"j5CWO4": ["Ũƥ ţō ďàţē"],"j9Vqvc": ["ĩńĥēŕĩţēď"],"j9tqwO": ["Ńōţ ĩń śĩďēƀàŕ"],@@ -2412,7 +2416,6 @@],"jxtXZI": ["Ĩńśţàĺĺ ţĥē ĝĥ ĆĹĨ"],"k0dL2I": ["Ŕēćōńńēćţĩńĝ ţō ţĥē àĝēńţ śēŕvĩćē…"],- "k0vc0N": ["Ńēŵ ţēŕḿĩńàĺ ţàƀ"],"k2fEi7": ["Ũśēŕ ƥĺũĝĩńś àŕē ƥēŕśōńàĺ ţō ţĥĩś ďēvĩćē — ţũŕń ţĥēḿ ōń ōŕ ōƒƒ ĥēŕē. Ţĥē ćĥōĩćē ĺĩvēś ĩń ŷōũŕ ũśēŕ ćōńƒĩĝ àńď ĩś ńēvēŕ ćōḿḿĩţţēď ţō ţĥē ƥŕōĴēćţ. Ēàćĥ ēńàƀĺēď ƥĺũĝĩń ĝēţś ĩţś ōŵń ƥàĝē ũńďēŕ Ƥĺũĝĩńś ĩń ţĥē śēţţĩńĝś śĩďēƀàŕ."],@@ -2506,6 +2509,9 @@["4"],") ţĥàţ ŵōń'ţ ţōũćĥ ţĥē ŕēśţ ōƒ ŷōũŕ śŷśţēḿ."],+ "l9HUtd": [+ "Ţōĝĝĺē ţĥē ƀōţţōḿ ţēŕḿĩńàĺ ƥàńēĺ. Ŵĩţĥ ţēxţ śēĺēćţēď, śţàĝē ĩţ ƒōŕ ŷōũŕ ƥŕēƒēŕŕēď ÀĨ ĩńśţēàď."+ ],"lAiyU_": ["Ōńĺŷ ţĥē ćũŕŕēńţ ďōćũḿēńţ ũśēś <0>#", ["tag"], "</0>."],"lCC_D5": ["Śũƀśćŕĩƀĩńĝ..."],"lGs_bQ": ["Ƥàĝē <0>*</0>"],@@ -2683,9 +2689,6 @@"oBK5fD": ["Ōvēŕĺàƥƥĩńĝ ēďĩţś"],"oBXkm2": ["Ďēĺēţē ćōďē ƀĺōćķ"],"oCHfGC": ["Ĺēvēĺ"],- "oCNLN8": [- "Ţōĝĝĺē ţĥē ƀōţţōḿ ţēŕḿĩńàĺ ƥàńēĺ. Ŵĩţĥ ţēxţ śēĺēćţēď, śţàĝē ĩţ ĩń ţĥē ţēŕḿĩńàĺ'ś ÀĨ ĩńƥũţ ĩńśţēàď."- ],"oCZkaG": ["Ćōƥŷ ƥàţĥ"],"oJl7eO": ["Ũńķńōŵń ćōḿƥōńēńţ: ", ["componentName"], " — śōũŕćē ēďĩţàƀĺē ƀēĺōŵ"],"oKBnk5": ["Ḿōŕē ŕēǫũēśţś ŵēŕē ƀĺōćķēď."],@@ -2885,9 +2888,6 @@"seeS6l": ["Śēţũƥ ŌƥēńĶńōŵĺēďĝē ĩń ţĥĩś ƒōĺďēŕ?"],"sgmRY8": ["Śķĩƥƥēď ďōŵńĺōàďĩńĝ ", ["0"], "."],"shNd9t": ["Śĺàśĥ ćōḿḿàńď ḿēńũ"],- "si3L24": [- "Ōƥēń àń àďďĩţĩōńàĺ ţēŕḿĩńàĺ ţàƀ. Ŵĩţĥ ţēxţ śēĺēćţēď, śţàĝē ĩţ ĩń ţĥē ńēŵ ţàƀ'ś ÀĨ ĩńƥũţ."- ],"skf5Ix": ["Ĩńďēńţ ōŕ ōũţďēńţ śōũŕćē ēďĩţōŕ ĺĩńēś."],"sn5BEU": [["sizeText"],diff --git a/packages/app/src/locales/pseudo/messages.po b/packages/app/src/locales/pseudo/messages.poindex 1c94f7d2c..a134cf0e0 100644--- a/packages/app/src/locales/pseudo/messages.po+++ b/packages/app/src/locales/pseudo/messages.po@@ -5761,6 +5761,10 @@ msgstr ""msgid "New schema"msgstr ""+#: src/lib/keyboard-shortcuts.ts+msgid "New session"+msgstr ""+#: src/components/NewSkillDialog.tsx#: src/components/settings/SkillsManagerSection.tsx#: src/components/SkillsSidebarSection.tsx@@ -5786,10 +5790,6 @@ msgstr ""msgid "New Terminal"msgstr ""-#: src/lib/keyboard-shortcuts.ts-msgid "New terminal tab"-msgstr ""-#. placeholder {0}: info.agent.name#: src/components/acp/ThreadView.tsxmsgid "New thread with {0}"@@ -6312,6 +6312,10 @@ msgstr ""msgid "Open a doc to share its URL."msgstr ""+#: src/lib/keyboard-shortcuts.ts+msgid "Open a new session with your preferred AI. With text selected, stage it there instead of running it."+msgstr ""+#: src/components/settings/SettingsDialogShell.tsxmsgid "Open a project to edit."msgstr ""@@ -6336,10 +6340,6 @@ 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 ""@@ -9592,7 +9592,7 @@ msgid "Toggle strikethrough formatting."msgstr ""#: src/lib/keyboard-shortcuts.ts-msgid "Toggle the bottom terminal panel. With text selected, stage it in the terminal's AI input instead."+msgid "Toggle the bottom terminal panel. With text selected, stage it for your preferred AI instead."msgstr ""#: src/lib/keyboard-shortcuts.ts