Beautiful, AI-native markdown IDE and LLM wiki
TypeScript 2nd-brainagent-skillsclaudecodexcompany-braindocsknowledge-knowledge-baseknowledge-managementllmllm-wikillm-wiki-karpathymarkdownmarkdown-editormdmdxnotespkmsecond-brainskills
Add instruction prompt box to toolbar Open with AI menu (#1975)
Andrew Mikofalvy903822b546c9
diff --git a/.changeset/open-with-ai-instruction-box.md b/.changeset/open-with-ai-instruction-box.mdnew file mode 100644index 000000000..2220dfb4f--- /dev/null+++ b/.changeset/open-with-ai-instruction-box.md@@ -0,0 +1,5 @@+---+"@inkeep/open-knowledge": patch+---++Add an instruction prompt box to the toolbar "Open with AI" menu. The menu is now a popover with a "What should the AI do? (optional)" field above the installed-agent list; the typed instruction rides along into the launched agent's first-turn prompt (both the deep-link dispatch and the docked-terminal "Claude CLI" launch), mirroring the editor's "Edit with AI" affordance. Leaving the box empty preserves the previous one-click behavior.diff --git a/docs/content/features/editor.mdx b/docs/content/features/editor.mdxindex 3467ad570..99ab63ae5 100644--- a/docs/content/features/editor.mdx+++ b/docs/content/features/editor.mdx@@ -124,7 +124,17 @@ When both are on, **Show all files** supersedes.The trailing `Open the OK editor in web view.` directive is dropped when the [`appearance.preview.autoOpen`](/docs/reference/configuration) preference is off, so the receiving agent honors the same "leave my preview alone" choice on its first turn; only the `Let's work on … using Open Knowledge.` opener is sent.-The same submenu is mounted on the **sparkle icon** in the editor header; it picks the scope to dispatch from whichever target is currently active in the editor.+The **sparkle icon** in the editor header opens the same handoff as a popover, picking the scope from whichever target is currently active in the editor. Unlike the right-click submenus — which dispatch in one click — this header popover adds an optional **instruction field** ("What should the AI do?"). When you type one, it's appended to the directive above as a quoted block, so the agent opens the target *and* gets your specific ask in the same prompt:++```text+Let's work on `<path>` using Open Knowledge. Open the OK editor in web view.++Instruction:++> <your instruction>+```++The directive line itself varies by scope (file, folder, or whole project); the example shows the file form, and the openers described above list the others. Leaving the field empty dispatches the bare directive unchanged.**Install detection** filters the submenu to just the agents you have. When the server and your browser are on the same machine (`localhost`), the filter is accurate. When you're running the server elsewhere (a hosted preview, SSH tunnel, remote dev), the submenu lists every supported agent and lets your browser's OS protocol-dispatch dialog be the truth signal.diff --git a/packages/app/src/components/handoff/EditWithAiPopover.tsx b/packages/app/src/components/handoff/EditWithAiPopover.tsxindex 7527e0dee..c309cf494 100644--- a/packages/app/src/components/handoff/EditWithAiPopover.tsx+++ b/packages/app/src/components/handoff/EditWithAiPopover.tsx@@ -48,21 +48,26 @@ export function EditWithAiPanel({ installStates, onPick }: EditWithAiPanelProps)data-testid="edit-with-ai-instruction"/>{installedTargets.length > 0 ? (- <div className="flex flex-col gap-0.5">- {installedTargets.map((target) => (- <Button- key={target.id}- type="button"- variant="ghost"- className="w-full justify-start gap-2"- data-testid={`edit-with-ai-target-${target.id}`}- onClick={() => onPick(target, instruction)}- >- <TargetIcon id={target.id} aria-hidden="true" />- <span>{target.displayName}</span>- </Button>- ))}- </div>+ <>+ <div className="text-muted-foreground text-xs" data-testid="edit-with-ai-send-label">+ <Trans>Send to</Trans>+ </div>+ <div className="flex flex-col gap-0.5">+ {installedTargets.map((target) => (+ <Button+ key={target.id}+ type="button"+ variant="ghost"+ className="w-full justify-start gap-2"+ data-testid={`edit-with-ai-target-${target.id}`}+ onClick={() => onPick(target, instruction)}+ >+ <TargetIcon id={target.id} aria-hidden="true" />+ <span>{target.displayName}</span>+ </Button>+ ))}+ </div>+ </>) : (<pclassName="text-sm text-muted-foreground"diff --git a/packages/app/src/components/handoff/OpenInAgentMenu.dom.test.tsx b/packages/app/src/components/handoff/OpenInAgentMenu.dom.test.tsxindex 30050e50b..9c6ecb4e2 100644--- a/packages/app/src/components/handoff/OpenInAgentMenu.dom.test.tsx+++ b/packages/app/src/components/handoff/OpenInAgentMenu.dom.test.tsx@@ -1,5 +1,4 @@import { afterEach, describe, expect, mock, test } from 'bun:test';-import type { TargetData } from '@inkeep/open-knowledge-core';import { cleanup, render, screen, waitFor } from '@testing-library/react';import userEvent from '@testing-library/user-event';import type { ReactNode } from 'react';@@ -48,11 +47,7 @@ mock.module('@/hooks/use-is-embedded', () => ({}));mock.module('./OpenInAgentMenuItem', () => ({- OpenInAgentMenuItem: ({ target, onSelect }: { target: TargetData; onSelect: () => void }) => (- <button type="button" data-testid={`open-in-agent-row-${target.id}`} onClick={onSelect}>- {target.displayName}- </button>- ),+ TargetIcon: () => null,}));const input: HandoffDispatchInput = {@@ -118,13 +113,67 @@ describe('OpenInAgentMenu runtime behavior', () => {await openMenu();expect(refreshCalls).toEqual(['refresh']);- expect(screen.getByTestId('open-in-agent-row-claude-code')).toBeTruthy();- expect(screen.getByTestId('open-in-agent-row-codex')).toBeTruthy();- expect(screen.getByTestId('open-in-agent-row-cursor')).toBeTruthy();- expect(screen.queryByTestId('open-in-agent-row-claude-cowork')).toBeNull();+ expect(screen.getByTestId('open-in-agent-item-claude-code')).toBeTruthy();+ expect(screen.getByTestId('open-in-agent-item-codex')).toBeTruthy();+ expect(screen.getByTestId('open-in-agent-item-cursor')).toBeTruthy();+ expect(screen.queryByTestId('open-in-agent-item-claude-cowork')).toBeNull();- await userEvent.click(screen.getByTestId('open-in-agent-row-codex'));- expect(dispatchCalls).toEqual([{ target: 'codex', input }]);+ expect(screen.getByTestId('open-in-agent-send-label').textContent).toContain('Send to');++ await userEvent.click(screen.getByTestId('open-in-agent-item-codex'));+ expect(dispatchCalls).toStrictEqual([{ target: 'codex', input }]);+ });++ test('typing an instruction threads it onto the dispatched input', async () => {+ states = {+ 'claude-cowork': { installed: true, lastChecked: 1 },+ 'claude-code': { installed: true, lastChecked: 1 },+ codex: { installed: true, lastChecked: 1 },+ cursor: { installed: true, lastChecked: 1 },+ };+ await renderMenu();+ await openMenu();++ await userEvent.type(screen.getByTestId('open-in-agent-instruction'), 'Tighten the intro');+ await userEvent.click(screen.getByTestId('open-in-agent-item-cursor'));++ expect(dispatchCalls).toStrictEqual([+ { target: 'cursor', input: { ...input, instruction: 'Tighten the intro' } },+ ]);+ });++ test('instruction input resets to empty when the popover is reopened', async () => {+ states = {+ 'claude-cowork': { installed: true, lastChecked: 1 },+ 'claude-code': { installed: true, lastChecked: 1 },+ codex: { installed: true, lastChecked: 1 },+ cursor: { installed: true, lastChecked: 1 },+ };+ await renderMenu();+ await openMenu();+ await userEvent.type(screen.getByTestId('open-in-agent-instruction'), 'Tighten the intro');+ await userEvent.click(screen.getByTestId('open-in-agent-item-codex'));++ await userEvent.click(screen.getByTestId('open-in-agent-trigger'));+ await waitFor(() => {+ expect(screen.getByTestId('open-in-agent-menu')).toBeTruthy();+ });+ expect((screen.getByTestId('open-in-agent-instruction') as HTMLInputElement).value).toBe('');+ });++ test('a whitespace-only instruction is treated as empty (no instruction key)', async () => {+ states = {+ 'claude-cowork': { installed: true, lastChecked: 1 },+ 'claude-code': { installed: true, lastChecked: 1 },+ codex: { installed: true, lastChecked: 1 },+ cursor: { installed: true, lastChecked: 1 },+ };+ await renderMenu();+ await openMenu();++ await userEvent.type(screen.getByTestId('open-in-agent-instruction'), ' ');+ await userEvent.click(screen.getByTestId('open-in-agent-item-codex'));+ expect(dispatchCalls).toStrictEqual([{ target: 'codex', input }]);});test('shows the empty hint (no claude.ai fallback) when nothing is installed', async () => {diff --git a/packages/app/src/components/handoff/OpenInAgentMenu.tsx b/packages/app/src/components/handoff/OpenInAgentMenu.tsxindex 4a3da53cd..1b7304f83 100644--- a/packages/app/src/components/handoff/OpenInAgentMenu.tsx+++ b/packages/app/src/components/handoff/OpenInAgentMenu.tsx@@ -1,25 +1,15 @@-import type {- HandoffOutcome,- HandoffTarget,- InstallState,- TargetData,-} from '@inkeep/open-knowledge-core';+import type { HandoffTarget, InstallState, TargetData } from '@inkeep/open-knowledge-core';import { Trans, useLingui } from '@lingui/react/macro';import { Sparkles, SquareTerminal } from 'lucide-react';-import type { ComponentProps, ReactNode } from 'react';-import { useRef, useState } from 'react';+import { type ReactNode, useEffect, useEffectEvent, useRef, useState } from 'react';import { Button } from '@/components/ui/button';-import {- DropdownMenu,- DropdownMenuContent,- DropdownMenuItem,- DropdownMenuSeparator,- DropdownMenuTrigger,-} from '@/components/ui/dropdown-menu';+import { Input } from '@/components/ui/input';+import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';+import { Separator } from '@/components/ui/separator';import { useIsEmbedded } from '@/hooks/use-is-embedded';import { VISIBLE_TARGETS } from '@/lib/handoff/targets';-import { OpenInAgentMenuItem } from './OpenInAgentMenuItem';-import { useTerminalLaunch } from './TerminalLaunchContext';+import { TargetIcon } from './OpenInAgentMenuItem';+import { type TerminalLaunchContextValue, useTerminalLaunch } from './TerminalLaunchContext';import { type HandoffDispatchInput, useHandoffDispatch } from './useHandoffDispatch';import { useInstalledAgents } from './useInstalledAgents';@@ -31,109 +21,161 @@ interface OpenInAgentMenuProps {readonly onOpenChange?: (open: boolean) => void;}-interface OpenInAgentMenuContentProps {- readonly input: HandoffDispatchInput | null;- readonly states: Record<HandoffTarget, InstallState>;- readonly dispatch: (- target: HandoffTarget,- input: HandoffDispatchInput,- ) => Promise<HandoffOutcome>;- readonly isElectronHost: boolean;- readonly align?: ComponentProps<typeof DropdownMenuContent>['align'];- readonly className?: string;+interface OpenWithAiPanelProps {+ readonly installStates: Record<HandoffTarget, InstallState>;+ readonly terminalLaunch: TerminalLaunchContextValue | null;+ /** Disable every dispatch row — set when there is nothing to dispatch+ * (no active doc / workspace not loaded). The trigger is also disabled in+ * that state, so this is a defensive guard for the controlled-open path. */+ readonly disabled: boolean;+ /** Fired when the user picks an agent; carries the typed instruction — the+ * empty string when the user dispatched without typing one. */+ readonly onPick: (target: TargetData, instruction: string) => void;+ readonly onLaunchTerminal: (instruction: string) => void;}-function OpenInAgentMenuContent({- input,- states,- dispatch,- isElectronHost,- align = 'end',- className = 'min-w-[220px]',-}: OpenInAgentMenuContentProps): ReactNode {+function OpenWithAiPanel({+ installStates,+ terminalLaunch,+ disabled,+ onPick,+ onLaunchTerminal,+}: OpenWithAiPanelProps): ReactNode {const { t } = useLingui();- const terminalLaunch = useTerminalLaunch();-- const handleSelect = (target: TargetData): void => {- if (input === null) return;- void dispatch(target.id, input);- };+ const [instruction, setInstruction] = useState('');const installedTargets = VISIBLE_TARGETS.filter(- (target) => states[target.id]?.installed === true,+ (target) => installStates[target.id]?.installed === true,+ );+ const probePending = VISIBLE_TARGETS.some(+ (target) => installStates[target.id]?.installed == null,);- const probePending = VISIBLE_TARGETS.some((target) => states[target.id]?.installed == null);- const showEmptyHint = installedTargets.length === 0 && terminalLaunch === null;+ const hasRows = installedTargets.length > 0 || terminalLaunch !== null;return (- <DropdownMenuContent align={align} className={className} data-testid="open-in-agent-menu">- {installedTargets.map((target) => {- const installState = states[target.id];- return (- <OpenInAgentMenuItem- key={target.id}- target={target}- installState={installState}- isElectronHost={isElectronHost}- onSelect={() => handleSelect(target)}- />- );- })}- {showEmptyHint ? (- <DropdownMenuItem disabled data-testid="open-in-agent-empty">+ <div className="flex flex-col gap-3">+ <Input+ value={instruction}+ onChange={(event) => setInstruction(event.target.value)}+ placeholder={t`What should the AI do? (optional)`}+ aria-label={t`Instruction for the AI`}+ data-testid="open-in-agent-instruction"+ />+ {hasRows ? (+ <>+ <div className="text-muted-foreground text-xs" data-testid="open-in-agent-send-label">+ <Trans>Send to</Trans>+ </div>+ <div className="flex flex-col gap-0.5">+ {installedTargets.map((target) => {+ const { displayName } = target;+ return (+ <Button+ key={target.id}+ type="button"+ variant="ghost"+ className="w-full justify-start gap-2"+ disabled={disabled}+ data-testid={`open-in-agent-item-${target.id}`}+ aria-label={t`Open with AI ${displayName}`}+ onClick={() => onPick(target, instruction)}+ >+ <TargetIcon id={target.id} aria-hidden="true" />+ <span>{displayName}</span>+ </Button>+ );+ })}+ {terminalLaunch !== null ? (+ <>+ {installedTargets.length > 0 ? <Separator className="my-1" /> : null}+ <Button+ type="button"+ variant="ghost"+ className="w-full justify-start gap-2"+ disabled={disabled}+ data-testid="open-in-agent-terminal"+ aria-label={t`Claude CLI`}+ onClick={() => onLaunchTerminal(instruction)}+ >+ <SquareTerminal className="size-4" aria-hidden="true" />+ <span>+ <Trans>Claude CLI</Trans>+ </span>+ </Button>+ </>+ ) : null}+ </div>+ </>+ ) : (+ <p+ className="text-muted-foreground text-sm"+ data-testid="open-in-agent-empty"+ aria-live="polite"+ >{probePending ? (<Trans>Checking for installed agents</Trans>) : (<Trans>No installed agents found</Trans>)}- </DropdownMenuItem>- ) : null}- {terminalLaunch !== null ? (- <>- <DropdownMenuSeparator />- <DropdownMenuItem- onSelect={() => {- if (input === null) return;- terminalLaunch.launchInTerminal(input);- }}- disabled={input === null}- data-testid="open-in-agent-terminal"- aria-label={t`Claude CLI`}- >- <SquareTerminal className="size-4" aria-hidden="true" />- <span className="flex-1">- <Trans>Claude CLI</Trans>- </span>- </DropdownMenuItem>- </>- ) : null}- </DropdownMenuContent>+ </p>+ )}+ </div>);}export function OpenInAgentMenu({ input, open, onOpenChange }: OpenInAgentMenuProps): ReactNode {+ const { t } = useLingui();const { states, refresh } = useInstalledAgents();const { dispatch } = useHandoffDispatch();+ const terminalLaunch = useTerminalLaunch();const [internalOpen, setInternalOpen] = useState(false);const sawPointerDownRef = useRef(false);const isEmbedded = useIsEmbedded();++ const menuOpen = open ?? internalOpen;++ const refreshOnOpen = useEffectEvent(() => {+ void refresh();+ });+ useEffect(() => {+ if (menuOpen) refreshOnOpen();+ }, [menuOpen]);+if (isEmbedded) return null;const isElectronHost = typeof window !== 'undefined' && window.okDesktop != null;- const menuOpen = open ?? internalOpen;const handleOpenChange = (next: boolean): void => {if (open === undefined) setInternalOpen(next);onOpenChange?.(next);- if (next) void refresh();};const triggerDisabled = input === null;+ const inputWith = (instruction: string): HandoffDispatchInput | null => {+ if (input === null) return null;+ const trimmed = instruction.trim();+ return trimmed ? { ...input, instruction: trimmed } : input;+ };++ const handlePick = (target: TargetData, instruction: string): void => {+ const next = inputWith(instruction);+ if (next === null) return;+ void dispatch(target.id, next);+ handleOpenChange(false);+ };++ const handleLaunchTerminal = (instruction: string): void => {+ const next = inputWith(instruction);+ if (next === null || terminalLaunch === null) return;+ terminalLaunch.launchInTerminal(next);+ handleOpenChange(false);+ };+return (- <DropdownMenu open={menuOpen} onOpenChange={handleOpenChange} modal={false}>- <DropdownMenuTrigger asChild>+ <Popover open={menuOpen} onOpenChange={handleOpenChange}>+ <PopoverTrigger asChild><Buttonvariant="ghost"size="sm"@@ -162,13 +204,16 @@ export function OpenInAgentMenu({ input, open, onOpenChange }: OpenInAgentMenuPr<Sparkles className="size-3.5" aria-hidden="true" /><Trans>Open with AI</Trans></Button>- </DropdownMenuTrigger>- <OpenInAgentMenuContent- input={input}- states={states}- dispatch={dispatch}- isElectronHost={isElectronHost}- />- </DropdownMenu>+ </PopoverTrigger>+ <PopoverContent align="end" aria-label={t`Open with AI`} data-testid="open-in-agent-menu">+ <OpenWithAiPanel+ installStates={states}+ terminalLaunch={terminalLaunch}+ disabled={input === null}+ onPick={handlePick}+ onLaunchTerminal={handleLaunchTerminal}+ />+ </PopoverContent>+ </Popover>);}diff --git a/packages/app/src/components/handoff/OpenInAgentTerminalRow.dom.test.tsx b/packages/app/src/components/handoff/OpenInAgentTerminalRow.dom.test.tsxindex cd4c00d5c..4118772cc 100644--- a/packages/app/src/components/handoff/OpenInAgentTerminalRow.dom.test.tsx+++ b/packages/app/src/components/handoff/OpenInAgentTerminalRow.dom.test.tsx@@ -1,11 +1,22 @@import { afterEach, describe, expect, mock, test } from 'bun:test';-import type { HandoffTarget, InstallState } from '@inkeep/open-knowledge-core';-import { cleanup, render, screen } from '@testing-library/react';+import { cleanup, render, screen, waitFor } from '@testing-library/react';import userEvent from '@testing-library/user-event';import type { ReactNode } from 'react';-import { DropdownMenu } from '@/components/ui/dropdown-menu';import type { HandoffDispatchInput } from './useHandoffDispatch';+const input: HandoffDispatchInput = {+ docContext: { relativePath: 'docs/notes.md' },+ projectDir: '/tmp/project',+ docPath: '/tmp/project/docs/notes.md',+};++const installedStates = {+ 'claude-cowork': { installed: true, lastChecked: 1 },+ 'claude-code': { installed: true, lastChecked: 1 },+ codex: { installed: true, lastChecked: 1 },+ cursor: { installed: true, lastChecked: 1 },+};+mock.module('@lingui/react/macro', () => ({Trans: ({ children }: { children: ReactNode }) => <>{children}</>,useLingui: () => ({@@ -14,72 +25,81 @@ mock.module('@lingui/react/macro', () => ({}),}));-mock.module('@/hooks/use-is-embedded', () => ({ useIsEmbedded: () => false }));+mock.module('./useInstalledAgents', () => ({+ useInstalledAgents: () => ({ states: installedStates, refresh: () => Promise.resolve() }),+}));-const SKIP_IN_CI = process.env.CI === 'true' || process.env.GITHUB_ACTIONS === 'true';+mock.module('./useHandoffDispatch', () => ({+ useHandoffDispatch: () => ({ dispatch: () => Promise.resolve({ ok: true as const }) }),+}));-const input: HandoffDispatchInput = {- docContext: { relativePath: 'docs/notes.md' },- projectDir: '/tmp/project',- docPath: '/tmp/project/docs/notes.md',-};+mock.module('@/lib/config-context', () => ({+ useConfigContext: () => ({ merged: { appearance: { preview: { autoOpen: true } } } }),+}));-const installedStates = {- 'claude-cowork': { installed: true },- 'claude-code': { installed: true },- codex: { installed: true },- cursor: { installed: true },-} as unknown as Record<HandoffTarget, InstallState>;+mock.module('@/hooks/use-is-embedded', () => ({ useIsEmbedded: () => false }));-const { OpenInAgentMenuContent } = await import('./OpenInAgentMenu');+mock.module('./OpenInAgentMenuItem', () => ({ TargetIcon: () => null }));++const { OpenInAgentMenu } = await import('./OpenInAgentMenu');const { TerminalLaunchProvider } = await import('./TerminalLaunchContext');-async function renderContent(opts: {+async function renderMenu(opts: {launcher: ((input: HandoffDispatchInput) => void) | null;menuInput?: HandoffDispatchInput | null;}) {const menuInput = 'menuInput' in opts ? opts.menuInput : input;render(<TerminalLaunchProvider value={opts.launcher ? { launchInTerminal: opts.launcher } : null}>- <DropdownMenu open>- <OpenInAgentMenuContent- input={menuInput ?? null}- states={installedStates}- dispatch={() => Promise.resolve({ ok: true as const })}- isElectronHost- autoOpen- />- </DropdownMenu>+ <OpenInAgentMenu input={menuInput ?? null} /></TerminalLaunchProvider>,);}-describe.skipIf(SKIP_IN_CI)('Open-in-Agent "Claude CLI" row', () => {+async function openMenu() {+ await userEvent.click(screen.getByTestId('open-in-agent-trigger'));+ await waitFor(() => {+ expect(screen.getByTestId('open-in-agent-menu')).toBeTruthy();+ });+}++describe('Open-with-AI "Claude CLI" row', () => {afterEach(() => {cleanup();});test('renders the terminal row when the launcher is available (desktop)', async () => {- await renderContent({ launcher: () => {} });+ await renderMenu({ launcher: () => {} });+ await openMenu();expect(screen.getByTestId('open-in-agent-terminal')).toBeTruthy();});test('hides the terminal row when no launcher is available (web host)', async () => {- await renderContent({ launcher: null });+ await renderMenu({ launcher: null });+ await openMenu();expect(screen.queryByTestId('open-in-agent-terminal')).toBeNull();});- test('clicking the row hands the handoff input to the launcher', async () => {+ test('clicking the row hands the bare handoff input to the launcher', async () => {const calls: HandoffDispatchInput[] = [];- await renderContent({ launcher: (i) => calls.push(i) });+ await renderMenu({ launcher: (i) => calls.push(i) });+ await openMenu();await userEvent.click(screen.getByTestId('open-in-agent-terminal'));- expect(calls).toEqual([input]);+ expect(calls).toStrictEqual([input]);});- test('the row does not launch when there is no handoff input', async () => {+ test('typing an instruction threads it onto the launched input', async () => {const calls: HandoffDispatchInput[] = [];- await renderContent({ launcher: (i) => calls.push(i), menuInput: null });+ await renderMenu({ launcher: (i) => calls.push(i) });+ await openMenu();+ await userEvent.type(screen.getByTestId('open-in-agent-instruction'), 'Add error handling');await userEvent.click(screen.getByTestId('open-in-agent-terminal'));- expect(calls).toEqual([]);+ expect(calls).toStrictEqual([{ ...input, instruction: 'Add error handling' }]);+ });++ test('the trigger is disabled when there is no handoff input', async () => {+ await renderMenu({ launcher: () => {}, menuInput: null });+ const trigger = screen.getByTestId('open-in-agent-trigger') as HTMLButtonElement;+ expect(trigger.disabled).toBe(true);});});diff --git a/packages/app/src/components/handoff/useHandoffDispatch.test.ts b/packages/app/src/components/handoff/useHandoffDispatch.test.tsindex 0e3786181..9f6045f68 100644--- a/packages/app/src/components/handoff/useHandoffDispatch.test.ts+++ b/packages/app/src/components/handoff/useHandoffDispatch.test.ts@@ -869,6 +869,111 @@ describe('selectScopedPrompt — template selection across autoOpen modes', () =expect(out).toBe("Let's work on this project using Open Knowledge.");});+ test('file scope threads the toolbar instruction into the directive prompt', async () => {+ const { selectScopedPrompt } = await import('./useHandoffDispatch');+ const { composeFilePrompt } = await import('@inkeep/open-knowledge-core');+ const out = selectScopedPrompt(+ {+ docContext: { relativePath: 'notes/today.md' },+ instruction: 'Tighten the intro',+ projectDir: '/proj',+ docPath: '/proj/notes/today.md',+ },+ 'claude-code',+ true,+ );+ expect(out).toBe(composeFilePrompt('notes/today.md', true, 'Tighten the intro'));+ expect(out).toContain('Instruction:\n\n> Tighten the intro');+ });++ test('folder scope threads the toolbar instruction', async () => {+ const { selectScopedPrompt } = await import('./useHandoffDispatch');+ const out = selectScopedPrompt(+ {+ docContext: null,+ folderRelativePath: 'notes',+ instruction: 'Review the structure',+ projectDir: '/proj',+ docPath: '',+ },+ 'claude-code',+ true,+ );+ expect(out).toContain("Let's work on the `notes` folder using Open Knowledge.");+ expect(out).toContain('> Review the structure');+ });++ test('empty-space scope threads the toolbar instruction', async () => {+ const { selectScopedPrompt } = await import('./useHandoffDispatch');+ const out = selectScopedPrompt(+ {+ docContext: null,+ instruction: 'Scaffold the wiki',+ projectDir: '/proj',+ docPath: '',+ },+ 'claude-code',+ true,+ );+ expect(out).toContain("Let's work on this project using Open Knowledge.");+ expect(out).toContain('> Scaffold the wiki');+ });++ test('selection scope ignores the top-level instruction — selection.instruction wins', async () => {+ const { selectScopedPrompt } = await import('./useHandoffDispatch');+ const out = selectScopedPrompt(+ {+ docContext: null,+ instruction: 'top-level directive instruction',+ selection: {+ relativePath: 'notes/today.md',+ instruction: 'selection instruction',+ selectionMarkdown: 'the passage',+ },+ projectDir: '/proj',+ docPath: '/proj/notes/today.md',+ },+ 'claude-code',+ true,+ );+ expect(out).toContain('> selection instruction');+ expect(out).not.toContain('top-level directive instruction');+ });++ test('create scope ignores the top-level instruction — createDescription is the only free-text', async () => {+ const { selectScopedPrompt } = await import('./useHandoffDispatch');+ const out = selectScopedPrompt(+ {+ docContext: null,+ instruction: 'top-level directive instruction',+ createDescription: 'a worldbuilding wiki',+ createScenario: 'new-project',+ projectDir: '/proj',+ docPath: '',+ },+ 'claude-code',+ true,+ );+ expect(out).toContain('> a worldbuilding wiki');+ expect(out).not.toContain('top-level directive instruction');+ });++ test('file scope threads the instruction even when autoOpen=false (trailer dropped, instruction kept)', async () => {+ const { selectScopedPrompt } = await import('./useHandoffDispatch');+ const out = selectScopedPrompt(+ {+ docContext: { relativePath: 'notes/today.md' },+ instruction: 'Fix the intro',+ projectDir: '/proj',+ docPath: '/proj/notes/today.md',+ },+ 'claude-code',+ false,+ );+ expect(out).toContain('> Fix the intro');+ expect(out).not.toContain('Open the OK editor');+ });+test('create scope (createDescription set) returns composeCreatePrompt with the scenario', async () => {const { selectScopedPrompt } = await import('./useHandoffDispatch');const { composeCreatePrompt } = await import('@inkeep/open-knowledge-core');diff --git a/packages/app/src/components/handoff/useHandoffDispatch.ts b/packages/app/src/components/handoff/useHandoffDispatch.tsindex 91e2a223d..38bf136c1 100644--- a/packages/app/src/components/handoff/useHandoffDispatch.ts+++ b/packages/app/src/components/handoff/useHandoffDispatch.ts@@ -58,6 +58,15 @@ export interface HandoffDispatchInput {* project isn't described as a brand-new one. Set alongside* `createDescription`; defaults to `new-project` if absent. */readonly createScenario?: CreateScenario;+ /** Optional free-text instruction the user typed in the toolbar "Open with+ * AI" popover. Orthogonal to scope: it applies to file / folder / project+ * (empty-space) dispatch — the three directive composers append it as a+ * quoted `Instruction:` block. Unset for the right-click submenus and+ * CommandPalette (which dispatch instantly with no prompt box), and for+ * selection / create scope (which carry their own free-text via+ * `selection.instruction` / `createDescription`). Set at the popover call+ * site, not by the shared `build*HandoffInput` helpers. */+ readonly instruction?: string;readonly projectDir: string;readonly docPath: string;}@@ -216,10 +225,10 @@ export function selectScopedPrompt(return composeSelectionPrompt({ ...input.selection, target });}if (input.docContext !== null) {- return composeFilePrompt(input.docContext.relativePath, autoOpen);+ return composeFilePrompt(input.docContext.relativePath, autoOpen, input.instruction);}if (input.folderRelativePath) {- return composeFolderPrompt(input.folderRelativePath, autoOpen);+ return composeFolderPrompt(input.folderRelativePath, autoOpen, input.instruction);}if (input.createDescription !== undefined) {return composeCreatePrompt(@@ -228,7 +237,7 @@ export function selectScopedPrompt(input.createScenario ?? 'new-project',);}- return composeEmptySpacePrompt(autoOpen);+ return composeEmptySpacePrompt(autoOpen, input.instruction);}export function composeTerminalLaunchPrompt(input: HandoffDispatchInput): string {diff --git a/packages/app/src/locales/en/messages.json b/packages/app/src/locales/en/messages.jsonindex 817df6466..e63113205 100644--- a/packages/app/src/locales/en/messages.json+++ b/packages/app/src/locales/en/messages.json@@ -443,6 +443,7 @@"By-7Pn": ["Toggle a bullet list."],"BymzO4": ["Document outline"],"C0NPNd": ["Add Open Knowledge to your AI tools"],+ "C37Zkt": ["Send to"],"C62P6b": ["Editor selection"],"C9TBvF": ["No Outgoing"],"CCTop_": ["Recent"],diff --git a/packages/app/src/locales/en/messages.po b/packages/app/src/locales/en/messages.poindex 559bf3935..450d24b58 100644--- a/packages/app/src/locales/en/messages.po+++ b/packages/app/src/locales/en/messages.po@@ -2982,6 +2982,7 @@ msgid "Installing"msgstr "Installing"#: src/components/handoff/EditWithAiPopover.tsx+#: src/components/handoff/OpenInAgentMenu.tsxmsgid "Instruction for the AI"msgstr "Instruction for the AI"@@ -4048,6 +4049,7 @@ msgstr "Open with AI"#: src/components/CommandPalette.tsx#: src/components/handoff/OpenInAgentContextSubmenu.tsx#: src/components/handoff/OpenInAgentEmptySpaceSubmenu.tsx+#: src/components/handoff/OpenInAgentMenu.tsxmsgid "Open with AI {displayName}"msgstr "Open with AI {displayName}"@@ -4986,6 +4988,11 @@ msgstr "Semantic search adds meaning-based ranking to the search tool so conceptmsgid "Semantic search is on, but no API key is set — search falls back to keyword matching. Add one in <0>Settings → Account</0> (it's stored once for your whole machine)."msgstr "Semantic search is on, but no API key is set — search falls back to keyword matching. Add one in <0>Settings → Account</0> (it's stored once for your whole machine)."+#: src/components/handoff/EditWithAiPopover.tsx+#: src/components/handoff/OpenInAgentMenu.tsx+msgid "Send to"+msgstr "Send to"+#: src/editor/slash-command/items.tsxmsgid "Separator"msgstr "Separator"@@ -6127,6 +6134,7 @@ msgid "What is this knowledge base for?"msgstr "What is this knowledge base for?"#: src/components/handoff/EditWithAiPopover.tsx+#: src/components/handoff/OpenInAgentMenu.tsxmsgid "What should the AI do? (optional)"msgstr "What should the AI do? (optional)"diff --git a/packages/app/src/locales/pseudo/messages.json b/packages/app/src/locales/pseudo/messages.jsonindex 9df072bc5..613b38a21 100644--- a/packages/app/src/locales/pseudo/messages.json+++ b/packages/app/src/locales/pseudo/messages.json@@ -443,6 +443,7 @@"By-7Pn": ["Ţōĝĝĺē à ƀũĺĺēţ ĺĩśţ."],"BymzO4": ["Ďōćũḿēńţ ōũţĺĩńē"],"C0NPNd": ["Àďď Ōƥēń Ķńōŵĺēďĝē ţō ŷōũŕ ÀĨ ţōōĺś"],+ "C37Zkt": ["Śēńď ţō"],"C62P6b": ["Ēďĩţōŕ śēĺēćţĩōń"],"C9TBvF": ["Ńō Ōũţĝōĩńĝ"],"CCTop_": ["Ŕēćēńţ"],diff --git a/packages/app/src/locales/pseudo/messages.po b/packages/app/src/locales/pseudo/messages.poindex dc6e163ba..5b76283b2 100644--- a/packages/app/src/locales/pseudo/messages.po+++ b/packages/app/src/locales/pseudo/messages.po@@ -2977,6 +2977,7 @@ msgid "Installing"msgstr ""#: src/components/handoff/EditWithAiPopover.tsx+#: src/components/handoff/OpenInAgentMenu.tsxmsgid "Instruction for the AI"msgstr ""@@ -4043,6 +4044,7 @@ msgstr ""#: src/components/CommandPalette.tsx#: src/components/handoff/OpenInAgentContextSubmenu.tsx#: src/components/handoff/OpenInAgentEmptySpaceSubmenu.tsx+#: src/components/handoff/OpenInAgentMenu.tsxmsgid "Open with AI {displayName}"msgstr ""@@ -4981,6 +4983,11 @@ msgstr ""msgid "Semantic search is on, but no API key is set — search falls back to keyword matching. Add one in <0>Settings → Account</0> (it's stored once for your whole machine)."msgstr ""+#: src/components/handoff/EditWithAiPopover.tsx+#: src/components/handoff/OpenInAgentMenu.tsx+msgid "Send to"+msgstr ""+#: src/editor/slash-command/items.tsxmsgid "Separator"msgstr ""@@ -6122,6 +6129,7 @@ msgid "What is this knowledge base for?"msgstr ""#: src/components/handoff/EditWithAiPopover.tsx+#: src/components/handoff/OpenInAgentMenu.tsxmsgid "What should the AI do? (optional)"msgstr ""diff --git a/packages/core/src/handoff/prompt-composer.test.ts b/packages/core/src/handoff/prompt-composer.test.tsindex d8a60a0b2..aa8542fc0 100644--- a/packages/core/src/handoff/prompt-composer.test.ts+++ b/packages/core/src/handoff/prompt-composer.test.ts@@ -140,6 +140,102 @@ test('composeEmptySpacePrompt is deterministic across calls', () => {expect(composeEmptySpacePrompt(false)).toBe(composeEmptySpacePrompt(false));});+test('composeFilePrompt appends a quoted Instruction block after the directive trailer', () => {+ expect(composeFilePrompt('foo.md', true, 'Tighten the intro')).toBe(+ "Let's work on `foo.md` using Open Knowledge. Open the OK editor in web view." ++ '\n\nInstruction:\n\n> Tighten the intro',+ );+});++test('composeFilePrompt with autoOpen=false places the instruction after the bare directive', () => {+ expect(composeFilePrompt('foo.md', false, 'Tighten the intro')).toBe(+ "Let's work on `foo.md` using Open Knowledge.\n\nInstruction:\n\n> Tighten the intro",+ );+});++test('composeFilePrompt blockquotes every line of a multi-line instruction', () => {+ expect(composeFilePrompt('foo.md', false, 'line one\nline two')).toBe(+ "Let's work on `foo.md` using Open Knowledge.\n\nInstruction:\n\n> line one\n> line two",+ );+});++test('composeFilePrompt with an empty / whitespace / absent instruction is byte-identical to the path-only form', () => {+ const bare = composeFilePrompt('foo.md', true);+ expect(composeFilePrompt('foo.md', true, '')).toBe(bare);+ expect(composeFilePrompt('foo.md', true, ' ')).toBe(bare);+ expect(composeFilePrompt('foo.md', true, undefined)).toBe(bare);+ expect(composeFilePrompt('foo.md', false, '')).toBe(composeFilePrompt('foo.md', false));+});++test('composeFolderPrompt appends a quoted Instruction block', () => {+ expect(composeFolderPrompt('specs', true, 'Review the structure')).toBe(+ "Let's work on the `specs` folder using Open Knowledge. Open the OK editor in web view." ++ '\n\nInstruction:\n\n> Review the structure',+ );+ expect(composeFolderPrompt('specs', true, ' ')).toBe(composeFolderPrompt('specs', true));+});++test('composeEmptySpacePrompt appends a quoted Instruction block', () => {+ expect(composeEmptySpacePrompt(true, 'Scaffold the wiki')).toBe(+ "Let's work on this project using Open Knowledge. Open the OK editor in web view." ++ '\n\nInstruction:\n\n> Scaffold the wiki',+ );+ expect(composeEmptySpacePrompt(true, '')).toBe(composeEmptySpacePrompt(true));+});++test('composeFolderPrompt blockquotes every line of a multi-line instruction', () => {+ expect(composeFolderPrompt('specs', false, 'line one\nline two')).toBe(+ "Let's work on the `specs` folder using Open Knowledge.\n\nInstruction:\n\n> line one\n> line two",+ );+});++test('composeEmptySpacePrompt blockquotes every line of a multi-line instruction', () => {+ expect(composeEmptySpacePrompt(false, 'line one\nline two')).toBe(+ "Let's work on this project using Open Knowledge.\n\nInstruction:\n\n> line one\n> line two",+ );+});++test('directive composers keep the dispatched URL within 4096 chars for an oversized instruction (every target)', () => {+ const hugeInstruction = 'please tighten this prose for clarity and concision '.repeat(200);+ const composed = [+ composeFilePrompt('specs/deep/nested/SPEC.md', true, hugeInstruction),+ composeFolderPrompt('specs/deep/nested', true, hugeInstruction),+ composeEmptySpacePrompt(true, hugeInstruction),+ ];+ for (const target of ALL_TARGETS) {+ for (const prompt of composed) {+ expect(urlForTarget(target, prompt).length).toBeLessThanOrEqual(4096);+ }+ }+});++test('an oversized directive instruction is shortened with the truncation marker, not dropped whole', () => {+ const hugeInstruction = 'rewrite this section thoroughly '.repeat(200);+ const prompt = composeFilePrompt('foo.md', true, hugeInstruction);+ expect(prompt).toContain('…');+ expect(prompt).not.toContain(hugeInstruction);+ expect(prompt).toContain("Let's work on `foo.md` using Open Knowledge.");+});++test('a normal-length directive instruction is never truncated', () => {+ const instruction =+ 'Tighten the introduction, then add a short summary section at the end. Keep the existing headings.';+ const prompt = composeFilePrompt('foo.md', true, instruction);+ expect(prompt).toContain(`> ${instruction}`);+ expect(prompt).not.toContain('…');+});++test('shortening an oversized emoji-heavy instruction never splits a surrogate pair', () => {+ const hugeEmoji = '🎉'.repeat(3000);+ for (const target of ALL_TARGETS) {+ let url = '';+ expect(() => {+ url = urlForTarget(target, composeFilePrompt('foo.md', true, hugeEmoji));+ }).not.toThrow();+ expect(url.length).toBeLessThanOrEqual(4096);+ }+});+test('composeCreatePrompt new-project blockquotes the brief + appends the scaffold directive (autoOpen=true)', () => {expect(composeCreatePrompt('a wiki for my D&D campaign', true, 'new-project')).toBe("I'm setting up a new Open Knowledge project. Here's what I want to create:\n" +@@ -399,6 +495,26 @@ test('composeSelectionPrompt shortens an oversized instruction so the locus URL}});+test('shortening an oversized emoji-heavy instruction never splits a surrogate pair in locus mode', () => {+ const hugeEmoji = '🎉'.repeat(3000);+ const hugeSelection = 'lorem ipsum dolor sit amet '.repeat(2000);+ for (const target of ALL_TARGETS) {+ let url = '';+ expect(() => {+ url = urlForTarget(+ target,+ composeSelectionPrompt({+ relativePath: 'specs/deep/nested/SPEC.md',+ instruction: hugeEmoji,+ selectionMarkdown: hugeSelection,+ target,+ }),+ );+ }).not.toThrow();+ expect(url.length).toBeLessThanOrEqual(4096);+ }+});+test('composeSelectionPrompt drops the instruction whole — never a lone marker — when no prefix fits the locus budget', () => {const longPath = `deep/${'x'.repeat(2000)}.md`;const prompt = composeSelectionPrompt({diff --git a/packages/core/src/handoff/prompt-composer.ts b/packages/core/src/handoff/prompt-composer.tsindex d60294f28..74ccf6a10 100644--- a/packages/core/src/handoff/prompt-composer.ts+++ b/packages/core/src/handoff/prompt-composer.ts@@ -34,21 +34,32 @@ function sanitizePathForAtMention(path: string): string {return path.replace(AT_MENTION_PATH_INJECTION_SANITIZE_RE, '_');}-export function composeFilePrompt(relativePath: string, autoOpen: boolean): string {+export function composeFilePrompt(+ relativePath: string,+ autoOpen: boolean,+ instruction?: string,+): string {const safe = sanitizePathForPrompt(relativePath);const base = `Let's work on \`${safe}\` using Open Knowledge.`;- return autoOpen ? `${base} Open the OK editor in web view.` : base;+ const directive = autoOpen ? `${base} Open the OK editor in web view.` : base;+ return appendInstruction(directive, instruction);}-export function composeFolderPrompt(relativeFolderPath: string, autoOpen: boolean): string {+export function composeFolderPrompt(+ relativeFolderPath: string,+ autoOpen: boolean,+ instruction?: string,+): string {const safe = sanitizePathForPrompt(relativeFolderPath);const base = `Let's work on the \`${safe}\` folder using Open Knowledge.`;- return autoOpen ? `${base} Open the OK editor in web view.` : base;+ const directive = autoOpen ? `${base} Open the OK editor in web view.` : base;+ return appendInstruction(directive, instruction);}-export function composeEmptySpacePrompt(autoOpen: boolean): string {+export function composeEmptySpacePrompt(autoOpen: boolean, instruction?: string): string {const base = `Let's work on this project using Open Knowledge.`;- return autoOpen ? `${base} Open the OK editor in web view.` : base;+ const directive = autoOpen ? `${base} Open the OK editor in web view.` : base;+ return appendInstruction(directive, instruction);}export type CreateScenario = 'new-project' | 'existing-repo';@@ -164,6 +175,47 @@ function instructionLines(instruction: string): readonly string[] {return ['Instruction:', '', quoted, ''];}+function directiveWithInstruction(directive: string, instruction: string): string {+ const lines = instructionLines(instruction);+ return lines.length === 0 ? directive : [directive, '', ...lines].join('\n').trimEnd();+}++function fitInstruction(+ compose: (instruction: string) => string,+ instruction: string,+ target: HandoffTarget,+): string {+ const fits = (instr: string): boolean =>+ encodedPromptLength(compose(instr), target) <= INLINE_PROMPT_ENCODED_BUDGET;+ if (fits(instruction)) return instruction;+ const codePoints = Array.from(instruction);+ let lo = 0;+ let hi = codePoints.length;+ while (lo < hi) {+ const mid = Math.ceil((lo + hi) / 2);+ const candidate = codePoints.slice(0, mid).join('').trimEnd() + INSTRUCTION_TRUNCATION_MARKER;+ if (fits(candidate)) lo = mid;+ else hi = mid - 1;+ }+ const kept = codePoints.slice(0, lo).join('').trimEnd();+ return kept === '' ? '' : kept + INSTRUCTION_TRUNCATION_MARKER;+}++function fitInstructionForDirective(directive: string, instruction: string): string {+ return fitInstruction(+ (instr) => directiveWithInstruction(directive, instr),+ instruction,+ 'cursor',+ );+}++function appendInstruction(directive: string, instruction: string | undefined): string {+ return directiveWithInstruction(+ directive,+ fitInstructionForDirective(directive, instruction ?? ''),+ );+}+function composeInline(safePath: string, instruction: string, selectionMarkdown: string): string {const fence = fenceFor(selectionMarkdown);return [@@ -201,20 +253,11 @@ function fitInstructionForLocus(selectionMarkdown: string,target: HandoffTarget,): string {- const fits = (instr: string): boolean =>- encodedPromptLength(composeLocus(safePath, instr, selectionMarkdown), target) <=- INLINE_PROMPT_ENCODED_BUDGET;- if (fits(instruction)) return instruction;- let lo = 0;- let hi = instruction.length;- while (lo < hi) {- const mid = Math.ceil((lo + hi) / 2);- const candidate = instruction.slice(0, mid).trimEnd() + INSTRUCTION_TRUNCATION_MARKER;- if (fits(candidate)) lo = mid;- else hi = mid - 1;- }- const kept = instruction.slice(0, lo).trimEnd();- return kept === '' ? '' : kept + INSTRUCTION_TRUNCATION_MARKER;+ return fitInstruction(+ (instr) => composeLocus(safePath, instr, selectionMarkdown),+ instruction,+ target,+ );}export function composeSelectionPrompt(input: SelectionPromptInput): string {