Skip to content

Beautiful, AI-native markdown IDE and LLM wiki

Revive the Edit with AI instruction prompt box (#1897)

Andrew Mikofalvy0ce7ecd55e8e
diff --git a/.changeset/edit-with-ai-instruction-prompt.md b/.changeset/edit-with-ai-instruction-prompt.md
new file mode 100644
index 000000000..e05c445e5
--- /dev/null
+++ b/.changeset/edit-with-ai-instruction-prompt.md
@@ -0,0 +1,5 @@
+---
+"@inkeep/open-knowledge": patch
+---
+
+Bring back the instruction prompt box on the editor's "Edit with AI" affordance. Selecting text and clicking "Edit with AI" (or pressing Cmd+Shift+I) now opens a popover with a "What should the AI do?" field above the installed-agent list, instead of jumping straight to an agent picker. Type an instruction and pick an agent to hand off the selected passage with your instruction attached; the field is optional, so you can still dispatch with no instruction. The passage is snapshotted when the popover opens, so changing your selection afterward does not alter what gets sent.
diff --git a/packages/app/src/components/handoff/EditWithAiPanel.dom.test.tsx b/packages/app/src/components/handoff/EditWithAiPanel.dom.test.tsx
new file mode 100644
index 000000000..85d142fd8
--- /dev/null
+++ b/packages/app/src/components/handoff/EditWithAiPanel.dom.test.tsx
@@ -0,0 +1,116 @@
+import { afterEach, describe, expect, test } from 'bun:test';
+import type { HandoffTarget, InstallState } from '@inkeep/open-knowledge-core';
+import { cleanup, render, screen } from '@testing-library/react';
+import userEvent from '@testing-library/user-event';
+import { EditWithAiPanel } from './EditWithAiPopover';
+
+afterEach(() => {
+ cleanup();
+});
+
+function installStates(
+ flags: Partial<Record<HandoffTarget, boolean | null>>,
+): Record<HandoffTarget, InstallState> {
+ const at = (id: HandoffTarget): InstallState => ({ installed: flags[id] ?? null });
+ return {
+ 'claude-cowork': at('claude-cowork'),
+ 'claude-code': at('claude-code'),
+ codex: at('codex'),
+ cursor: at('cursor'),
+ };
+}
+
+describe('EditWithAiPanel', () => {
+ test('renders the instruction input and one button per installed agent', () => {
+ render(
+ <EditWithAiPanel
+ installStates={installStates({ 'claude-code': true, codex: true })}
+ onPick={() => {}}
+ />,
+ );
+ expect(screen.getByTestId('edit-with-ai-instruction')).toBeTruthy();
+ expect(screen.getByTestId('edit-with-ai-target-claude-code')).toBeTruthy();
+ expect(screen.getByTestId('edit-with-ai-target-codex')).toBeTruthy();
+ });
+
+ test('hides agents that are not installed or still being probed', () => {
+ render(
+ <EditWithAiPanel
+ installStates={installStates({ 'claude-code': true, codex: false, cursor: null })}
+ onPick={() => {}}
+ />,
+ );
+ expect(screen.getByTestId('edit-with-ai-target-claude-code')).toBeTruthy();
+ expect(screen.queryByTestId('edit-with-ai-target-codex')).toBeNull();
+ expect(screen.queryByTestId('edit-with-ai-target-cursor')).toBeNull();
+ });
+
+ test('never renders the cowork target even when it is installed', () => {
+ render(
+ <EditWithAiPanel
+ installStates={installStates({ 'claude-cowork': true, codex: true })}
+ onPick={() => {}}
+ />,
+ );
+ expect(screen.queryByTestId('edit-with-ai-target-claude-cowork')).toBeNull();
+ });
+
+ test('renders no claude.ai web-fallback row', () => {
+ render(
+ <EditWithAiPanel
+ installStates={installStates({ 'claude-code': false, codex: false, cursor: false })}
+ onPick={() => {}}
+ />,
+ );
+ expect(screen.queryByText(/claude\.ai/i)).toBeNull();
+ });
+
+ test('picking an agent reports the target and the typed instruction', async () => {
+ const user = userEvent.setup();
+ const picks: Array<{ id: string; instruction: string }> = [];
+ render(
+ <EditWithAiPanel
+ installStates={installStates({ codex: true })}
+ onPick={(target, instruction) => picks.push({ id: target.id, instruction })}
+ />,
+ );
+ await user.type(screen.getByTestId('edit-with-ai-instruction'), 'tighten the prose');
+ await user.click(screen.getByTestId('edit-with-ai-target-codex'));
+ expect(picks).toEqual([{ id: 'codex', instruction: 'tighten the prose' }]);
+ });
+
+ test('allows a pick with an empty instruction', async () => {
+ const user = userEvent.setup();
+ const picks: Array<{ id: string; instruction: string }> = [];
+ render(
+ <EditWithAiPanel
+ installStates={installStates({ 'claude-code': true })}
+ onPick={(target, instruction) => picks.push({ id: target.id, instruction })}
+ />,
+ );
+ await user.click(screen.getByTestId('edit-with-ai-target-claude-code'));
+ expect(picks).toEqual([{ id: 'claude-code', instruction: '' }]);
+ });
+
+ test('shows an empty state when no agents are installed', () => {
+ render(
+ <EditWithAiPanel
+ installStates={installStates({ 'claude-code': false, codex: false, cursor: false })}
+ onPick={() => {}}
+ />,
+ );
+ const empty = screen.getByTestId('edit-with-ai-empty');
+ expect(empty).toBeTruthy();
+ expect(screen.queryByTestId('edit-with-ai-target-claude-code')).toBeNull();
+ });
+
+ test('the install-state region is an aria-live region so its async transition is announced', () => {
+ render(
+ <EditWithAiPanel
+ installStates={installStates({ 'claude-code': null, codex: null, cursor: null })}
+ onPick={() => {}}
+ />,
+ );
+ expect(screen.getByTestId('edit-with-ai-empty').getAttribute('aria-live')).toBe('polite');
+ });
+});
diff --git a/packages/app/src/components/handoff/EditWithAiPopover.dom.test.tsx b/packages/app/src/components/handoff/EditWithAiPopover.dom.test.tsx
new file mode 100644
index 000000000..a1c6a1304
--- /dev/null
+++ b/packages/app/src/components/handoff/EditWithAiPopover.dom.test.tsx
@@ -0,0 +1,167 @@
+import { afterEach, describe, expect, mock, test } from 'bun:test';
+import { cleanup, render, screen } from '@testing-library/react';
+import userEvent from '@testing-library/user-event';
+import { Button } from '@/components/ui/button';
+import type { EditWithAiSelectionSnapshot } from './EditWithAiPopover';
+
+type WindowGlobals = {
+ MutationObserver?: typeof MutationObserver;
+ NodeFilter?: typeof NodeFilter;
+};
+type GlobalWithDomShims = typeof globalThis &
+ WindowGlobals & {
+ window?: WindowGlobals;
+ ResizeObserver?: unknown;
+ };
+const globalWithDomShims = globalThis as GlobalWithDomShims;
+if (
+ globalWithDomShims.MutationObserver === undefined &&
+ globalWithDomShims.window?.MutationObserver !== undefined
+) {
+ globalWithDomShims.MutationObserver = globalWithDomShims.window.MutationObserver;
+}
+if (
+ globalWithDomShims.NodeFilter === undefined &&
+ globalWithDomShims.window?.NodeFilter !== undefined
+) {
+ globalWithDomShims.NodeFilter = globalWithDomShims.window.NodeFilter;
+}
+if (globalWithDomShims.ResizeObserver === undefined) {
+ class NoopResizeObserver {
+ observe() {}
+ unobserve() {}
+ disconnect() {}
+ }
+ globalWithDomShims.ResizeObserver = NoopResizeObserver;
+}
+
+const dispatchCalls: Array<{ target: string; input: unknown }> = [];
+const buildArgs: unknown[] = [];
+const toastErrors: string[] = [];
+let refreshCount = 0;
+
+mock.module('sonner', () => ({
+ toast: {
+ error: (message: string) => {
+ toastErrors.push(message);
+ },
+ success: () => {},
+ },
+}));
+
+mock.module('./useInstalledAgents', () => ({
+ useInstalledAgents: () => ({
+ states: {
+ 'claude-cowork': { installed: false },
+ 'claude-code': { installed: true },
+ codex: { installed: false },
+ cursor: { installed: false },
+ },
+ refresh: () => {
+ refreshCount += 1;
+ return Promise.resolve();
+ },
+ }),
+}));
+
+mock.module('./useHandoffDispatch', () => ({
+ useHandoffDispatch: () => ({
+ dispatch: (target: string, input: unknown) => {
+ dispatchCalls.push({ target, input });
+ return Promise.resolve({ ok: true });
+ },
+ reinstallCoworkSkill: () => Promise.resolve({ kind: 'already-installed' }),
+ }),
+ buildSelectionOrDocHandoffInput: (args: { selectionMarkdown: string }) => {
+ buildArgs.push(args);
+ return args.selectionMarkdown === '' ? null : { __built: true };
+ },
+}));
+
+const { EditWithAiPopover } = await import('./EditWithAiPopover');
+
+const SNAPSHOT: EditWithAiSelectionSnapshot = {
+ docName: 'specs/foo/SPEC',
+ workspace: { contentDir: '/Users/x/notes', pathSeparator: '/' },
+ selectionMarkdown: 'The selected passage.',
+};
+
+function renderPopover({
+ open,
+ onOpenChange = () => {},
+ snapshot,
+}: {
+ open: boolean;
+ onOpenChange?: (next: boolean) => void;
+ snapshot: EditWithAiSelectionSnapshot | null;
+}) {
+ return render(
+ <EditWithAiPopover open={open} onOpenChange={onOpenChange} snapshot={snapshot}>
+ <Button data-testid="trigger">Edit with AI</Button>
+ </EditWithAiPopover>,
+ );
+}
+
+afterEach(() => {
+ cleanup();
+ dispatchCalls.length = 0;
+ buildArgs.length = 0;
+ toastErrors.length = 0;
+ refreshCount = 0;
+});
+
+describe('EditWithAiPopover', () => {
+ test('renders the instruction panel and refreshes install state when open', () => {
+ renderPopover({ open: true, snapshot: SNAPSHOT });
+
+ expect(screen.getByTestId('edit-with-ai-instruction')).toBeTruthy();
+ expect(refreshCount).toBe(1);
+ });
+
+ test('stays closed and does not refresh when open is false', () => {
+ renderPopover({ open: false, snapshot: null });
+
+ expect(screen.queryByTestId('edit-with-ai-instruction')).toBeNull();
+ expect(refreshCount).toBe(0);
+ });
+
+ test('dispatches a selection-scoped handoff carrying the snapshot and typed instruction', async () => {
+ const user = userEvent.setup();
+ const onOpenChange = mock(() => {});
+ renderPopover({ open: true, onOpenChange, snapshot: SNAPSHOT });
+
+ await user.type(screen.getByTestId('edit-with-ai-instruction'), 'make it concise');
+ await user.click(screen.getByTestId('edit-with-ai-target-claude-code'));
+
+ expect(buildArgs).toEqual([
+ {
+ docName: 'specs/foo/SPEC',
+ workspace: { contentDir: '/Users/x/notes', pathSeparator: '/' },
+ instruction: 'make it concise',
+ selectionMarkdown: 'The selected passage.',
+ },
+ ]);
+ expect(dispatchCalls).toEqual([{ target: 'claude-code', input: { __built: true } }]);
+ expect(onOpenChange).toHaveBeenCalledWith(false);
+ });
+
+ test('allows a pick with an empty instruction', async () => {
+ const user = userEvent.setup();
+ renderPopover({ open: true, snapshot: SNAPSHOT });
+
+ await user.click(screen.getByTestId('edit-with-ai-target-claude-code'));
+
+ expect((buildArgs[0] as { instruction: string }).instruction).toBe('');
+ expect(dispatchCalls).toEqual([{ target: 'claude-code', input: { __built: true } }]);
+ });
+
+ test('null input from the builder surfaces a toast and skips dispatch', async () => {
+ const user = userEvent.setup();
+ renderPopover({ open: true, snapshot: { ...SNAPSHOT, selectionMarkdown: '' } });
+
+ await user.click(screen.getByTestId('edit-with-ai-target-claude-code'));
+
+ expect(dispatchCalls).toEqual([]);
+ expect(toastErrors).toHaveLength(1);
+ });
+});
diff --git a/packages/app/src/components/handoff/EditWithAiPopover.tsx b/packages/app/src/components/handoff/EditWithAiPopover.tsx
new file mode 100644
index 000000000..7527e0dee
--- /dev/null
+++ b/packages/app/src/components/handoff/EditWithAiPopover.tsx
@@ -0,0 +1,136 @@
+import type { HandoffTarget, InstallState, TargetData } from '@inkeep/open-knowledge-core';
+import { Trans, useLingui } from '@lingui/react/macro';
+import { type ReactNode, useEffect, useEffectEvent, useState } from 'react';
+import { toast } from 'sonner';
+import { Button } from '@/components/ui/button';
+import { Input } from '@/components/ui/input';
+import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';
+import { VISIBLE_TARGETS } from '@/lib/handoff/targets';
+import type { Workspace } from '@/lib/workspace-paths';
+import { TargetIcon } from './OpenInAgentMenuItem';
+import { buildSelectionOrDocHandoffInput, useHandoffDispatch } from './useHandoffDispatch';
+import { useInstalledAgents } from './useInstalledAgents';
+
+export interface EditWithAiSelectionSnapshot {
+ readonly docName: string | null;
+ readonly workspace: Workspace | null;
+ readonly selectionMarkdown: string;
+}
+
+interface EditWithAiPanelProps {
+ readonly installStates: Record<HandoffTarget, InstallState>;
+ /** Fired when the user picks a target; carries the typed instruction —
+ * the empty string when the user dispatched without typing one. */
+ readonly onPick: (target: TargetData, instruction: string) => void;
+}
+
+export function EditWithAiPanel({ installStates, onPick }: EditWithAiPanelProps): ReactNode {
+ const { t } = useLingui();
+ const [instruction, setInstruction] = useState('');
+
+ const installedTargets = VISIBLE_TARGETS.filter(
+ (target) => installStates[target.id]?.installed === true,
+ );
+ const probePending = VISIBLE_TARGETS.some(
+ (target) => installStates[target.id]?.installed == null,
+ );
+
+ return (
+ <div className="flex flex-col gap-3">
+ <div className="font-mono text-xs uppercase tracking-wide text-muted-foreground">
+ <Trans>Edit with AI</Trans>
+ </div>
+ <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="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>
+ ) : (
+ <p
+ className="text-sm text-muted-foreground"
+ data-testid="edit-with-ai-empty"
+ aria-live="polite"
+ >
+ {probePending ? (
+ <Trans>Checking for installed agents</Trans>
+ ) : (
+ <Trans>No installed agents found</Trans>
+ )}
+ </p>
+ )}
+ </div>
+ );
+}
+
+interface EditWithAiPopoverProps {
+ /** Controlled open state, owned by the bubble button so the Cmd+Shift+I
+ * shortcut and a trigger click share one popover. */
+ readonly open: boolean;
+ readonly onOpenChange: (open: boolean) => void;
+ /** Selection snapshot captured by the caller when the popover opened. Null
+ * while closed; a non-null snapshot is required to dispatch. */
+ readonly snapshot: EditWithAiSelectionSnapshot | null;
+ readonly children: ReactNode;
+}
+
+export function EditWithAiPopover({
+ open,
+ onOpenChange,
+ snapshot,
+ children,
+}: EditWithAiPopoverProps): ReactNode {
+ const { t } = useLingui();
+ const { states, refresh } = useInstalledAgents();
+ const { dispatch } = useHandoffDispatch();
+
+ const refreshOnOpen = useEffectEvent(() => {
+ void refresh();
+ });
+ useEffect(() => {
+ if (open) refreshOnOpen();
+ }, [open]);
+
+ const handlePick = (target: TargetData, instruction: string): void => {
+ if (snapshot !== null) {
+ const input = buildSelectionOrDocHandoffInput({
+ docName: snapshot.docName,
+ workspace: snapshot.workspace,
+ instruction,
+ selectionMarkdown: snapshot.selectionMarkdown,
+ });
+ if (input !== null) {
+ void dispatch(target.id, input);
+ } else {
+ toast.error(t`Couldn't send the selection — please try again.`);
+ }
+ }
+ onOpenChange(false);
+ };
+
+ return (
+ <Popover open={open} onOpenChange={onOpenChange}>
+ <PopoverTrigger asChild>{children}</PopoverTrigger>
+ <PopoverContent align="start" aria-label={t`Edit with AI`} data-testid="edit-with-ai-popover">
+ <EditWithAiPanel installStates={states} onPick={handlePick} />
+ </PopoverContent>
+ </Popover>
+ );
+}
diff --git a/packages/app/src/components/handoff/OpenInAgentMenu.tsx b/packages/app/src/components/handoff/OpenInAgentMenu.tsx
index 52b6b088b..b31b526b5 100644
--- a/packages/app/src/components/handoff/OpenInAgentMenu.tsx
+++ b/packages/app/src/components/handoff/OpenInAgentMenu.tsx
@@ -50,7 +50,7 @@ interface OpenInAgentMenuContentProps {
readonly className?: string;
}
-export function OpenInAgentMenuContent({
+function OpenInAgentMenuContent({
input,
states,
dispatch,
diff --git a/packages/app/src/editor/bubble-menu/EditWithAiBubbleButton.dom.test.tsx b/packages/app/src/editor/bubble-menu/EditWithAiBubbleButton.dom.test.tsx
index 6820ae3da..93f370e07 100644
--- a/packages/app/src/editor/bubble-menu/EditWithAiBubbleButton.dom.test.tsx
+++ b/packages/app/src/editor/bubble-menu/EditWithAiBubbleButton.dom.test.tsx
@@ -4,34 +4,54 @@ import userEvent from '@testing-library/user-event';
import { Schema } from '@tiptap/pm/model';
import type { Editor } from '@tiptap/react';
import type { ReactNode } from 'react';
-import { DropdownMenuContent } from '@/components/ui/dropdown-menu';
-import { ConfigContext, type ConfigContextValue } from '@/lib/config-context';
-import type { HandoffDispatchInput } from '../../components/handoff/useHandoffDispatch';
import { setEditorDocName } from '../extensions/doc-context.ts';
+type WindowGlobals = {
+ MutationObserver?: typeof MutationObserver;
+ NodeFilter?: typeof NodeFilter;
+};
+type GlobalWithDomShims = typeof globalThis &
+ WindowGlobals & {
+ window?: WindowGlobals;
+ ResizeObserver?: unknown;
+ };
+const globalWithDomShims = globalThis as GlobalWithDomShims;
+if (
+ globalWithDomShims.MutationObserver === undefined &&
+ globalWithDomShims.window?.MutationObserver !== undefined
+) {
+ globalWithDomShims.MutationObserver = globalWithDomShims.window.MutationObserver;
+}
+if (
+ globalWithDomShims.NodeFilter === undefined &&
+ globalWithDomShims.window?.NodeFilter !== undefined
+) {
+ globalWithDomShims.NodeFilter = globalWithDomShims.window.NodeFilter;
+}
+if (globalWithDomShims.ResizeObserver === undefined) {
+ class NoopResizeObserver {
+ observe() {}
+ unobserve() {}
+ disconnect() {}
+ }
+ globalWithDomShims.ResizeObserver = NoopResizeObserver;
+}
+
const toastError = mock(() => {});
const refreshInstalledAgents = mock(async () => {});
-let latestMenuInput: HandoffDispatchInput | null | undefined;
-let lastNonNullMenuInput: HandoffDispatchInput | null | undefined;
-
-mock.module('sonner', () => ({ toast: { error: toastError } }));
-
-mock.module('@/components/handoff/OpenInAgentMenu', () => ({
- OpenInAgentMenuContent: ({ input }: { input: HandoffDispatchInput | null }) => {
- latestMenuInput = input;
- if (input !== null) lastNonNullMenuInput = input;
- if (input === null) return null;
- return (
- <DropdownMenuContent data-testid="edit-with-ai-popover">
- {input.selection?.selectionMarkdown ?? 'file scope'}
- </DropdownMenuContent>
- );
- },
-}));
+const dispatchCalls: Array<{ target: string; input: unknown }> = [];
+const buildArgs: Array<{
+ docName: string | null;
+ instruction: string;
+ selectionMarkdown: string;
+}> = [];
+
+mock.module('sonner', () => ({ toast: { error: toastError, success: () => {} } }));
mock.module('@/components/handoff/useInstalledAgents', () => ({
useInstalledAgents: () => ({
states: {
+ 'claude-cowork': { installed: false, lastChecked: 1 },
'claude-code': { installed: true, lastChecked: 1 },
codex: { installed: true, lastChecked: 1 },
cursor: { installed: true, lastChecked: 1 },
@@ -40,6 +60,24 @@ mock.module('@/components/handoff/useInstalledAgents', () => ({
}),
}));
+mock.module('@/components/handoff/useHandoffDispatch', () => ({
+ useHandoffDispatch: () => ({
+ dispatch: (target: string, input: unknown) => {
+ dispatchCalls.push({ target, input });
+ return Promise.resolve({ ok: true });
+ },
+ reinstallCoworkSkill: () => Promise.resolve({ kind: 'already-installed' }),
+ }),
+ buildSelectionOrDocHandoffInput: (args: {
+ docName: string | null;
+ instruction: string;
+ selectionMarkdown: string;
+ }) => {
+ buildArgs.push(args);
+ return args.selectionMarkdown === '' ? null : { __built: true };
+ },
+}));
+
mock.module('@/lib/use-workspace', () => ({
useWorkspace: () => ({ contentDir: '/tmp/project', pathSeparator: '/' }),
}));
@@ -66,7 +104,6 @@ function makeEditor(docName: string, text: string) {
setEditorDocName(editor, docName);
return {
editor,
- selectionContent,
setSelectionText(next: string) {
doc = schema.node('doc', null, [schema.node('paragraph', null, [schema.text(next)])]);
},
@@ -104,19 +141,6 @@ function setUserAgent(userAgent: string): void {
const PLAIN_UA = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) Chrome/120 Safari/537.36';
const EMBEDDED_UA = `${PLAIN_UA} Cursor/1.2.3`;
-const configContextValue = {
- userBinding: null,
- userSynced: false,
- projectBinding: null,
- projectLocalBinding: null,
- okignoreBinding: null,
- okignoreSynced: false,
- userConfig: null,
- projectConfig: null,
- projectLocalConfig: null,
- projectLocalSynced: false,
- merged: { appearance: { preview: { autoOpen: true } } },
-} as ConfigContextValue;
function renderButton({
editor,
@@ -128,30 +152,45 @@ function renderButton({
before?: ReactNode;
}) {
return render(
- <ConfigContext value={configContextValue}>
+ <>
{before}
<EditWithAiBubbleButton editor={editor} shortcutEnabled={shortcutEnabled} />
- </ConfigContext>,
+ </>,
+ );
+}
+
+function dispatchEditWithAiShortcut(target: EventTarget): void {
+ target.dispatchEvent(
+ new KeyboardEvent('keydown', {
+ key: 'I',
+ code: 'KeyI',
+ metaKey: true,
+ shiftKey: true,
+ bubbles: true,
+ cancelable: true,
+ }),
);
}
+const instructionInput = () => screen.queryByTestId('edit-with-ai-instruction');
+
afterEach(() => {
cleanup();
- latestMenuInput = undefined;
- lastNonNullMenuInput = undefined;
toastError.mockClear();
refreshInstalledAgents.mockClear();
+ dispatchCalls.length = 0;
+ buildArgs.length = 0;
setUserAgent(PLAIN_UA);
});
describe('EditWithAiBubbleButton', () => {
- test('renders the Edit with AI trigger on a macOS host', () => {
+ test('renders the Edit with AI trigger on a macOS host with the popover closed', () => {
setPlatform('MacIntel');
const { editor } = makeEditor('specs/foo/SPEC', 'A passage.');
renderButton({ editor });
expect(screen.getByTestId('edit-with-ai-bubble-button')).toBeTruthy();
- expect(screen.queryByTestId('edit-with-ai-popover')).toBeNull();
+ expect(instructionInput()).toBeNull();
});
test('does not render anything on a non-macOS host', () => {
@@ -180,23 +219,13 @@ describe('EditWithAiBubbleButton', () => {
renderButton({ editor });
await act(async () => {
- window.dispatchEvent(
- new KeyboardEvent('keydown', {
- key: 'I',
- code: 'KeyI',
- metaKey: true,
- shiftKey: true,
- bubbles: true,
- cancelable: true,
- }),
- );
+ dispatchEditWithAiShortcut(window);
});
- expect(screen.queryByTestId('edit-with-ai-popover')).toBeNull();
- expect(latestMenuInput).toBeUndefined();
+ expect(instructionInput()).toBeNull();
});
- test('clicking the trigger opens the local Open with AI menu', async () => {
+ test('clicking the trigger opens the popover and refreshes install state', async () => {
setPlatform('MacIntel');
const user = userEvent.setup();
const { editor } = makeEditor('specs/foo/SPEC', 'A passage.');
@@ -204,99 +233,94 @@ describe('EditWithAiBubbleButton', () => {
await user.click(screen.getByTestId('edit-with-ai-bubble-button'));
- expect(screen.getByTestId('edit-with-ai-popover')).toBeTruthy();
- expect(latestMenuInput?.selection).toEqual({
- relativePath: 'specs/foo/SPEC.md',
- instruction: '',
- selectionMarkdown: 'A passage.',
- });
+ expect(instructionInput()).toBeTruthy();
expect(refreshInstalledAgents).toHaveBeenCalled();
});
- test('pressing Enter on the trigger opens the local Open with AI menu', async () => {
+ test('Cmd+Shift+I opens the popover', async () => {
setPlatform('MacIntel');
- const user = userEvent.setup();
const { editor } = makeEditor('specs/foo/SPEC', 'A passage.');
renderButton({ editor });
- screen.getByTestId('edit-with-ai-bubble-button').focus();
- await user.keyboard('{Enter}');
+ await act(async () => {
+ dispatchEditWithAiShortcut(window);
+ });
- expect(screen.getByTestId('edit-with-ai-popover')).toBeTruthy();
- expect(latestMenuInput?.selection?.selectionMarkdown).toBe('A passage.');
+ expect(instructionInput()).toBeTruthy();
});
- test('pressing Space on the trigger opens the local Open with AI menu', async () => {
+ test('Cmd+Shift+I ignores inactive mounted editors', async () => {
setPlatform('MacIntel');
const { editor } = makeEditor('specs/foo/SPEC', 'A passage.');
- renderButton({ editor });
+ renderButton({ editor, shortcutEnabled: false });
await act(async () => {
- screen.getByTestId('edit-with-ai-bubble-button').dispatchEvent(
- new KeyboardEvent('keydown', {
- key: ' ',
- code: 'Space',
- bubbles: true,
- cancelable: true,
- }),
- );
+ dispatchEditWithAiShortcut(window);
});
- expect(screen.getByTestId('edit-with-ai-popover')).toBeTruthy();
- expect(latestMenuInput?.selection?.selectionMarkdown).toBe('A passage.');
+ expect(instructionInput()).toBeNull();
});
- test('synthetic click activation opens the local Open with AI menu', async () => {
+ test('Cmd+Shift+I ignores native text inputs', async () => {
setPlatform('MacIntel');
const { editor } = makeEditor('specs/foo/SPEC', 'A passage.');
- renderButton({ editor });
+ renderButton({ editor, before: <input data-testid="native-input" /> });
await act(async () => {
- screen.getByTestId('edit-with-ai-bubble-button').click();
+ dispatchEditWithAiShortcut(screen.getByTestId('native-input'));
});
- expect(screen.getByTestId('edit-with-ai-popover')).toBeTruthy();
- expect(latestMenuInput?.selection).toMatchObject({
- selectionMarkdown: 'A passage.',
- });
+ expect(instructionInput()).toBeNull();
});
- test('clicking an already-open trigger does not replace the captured selection', async () => {
+ test('typing an instruction and picking an agent dispatches the selection with the instruction', async () => {
setPlatform('MacIntel');
const user = userEvent.setup();
- const { editor, setSelectionText } = makeEditor('specs/foo/SPEC', 'Original passage.');
+ const { editor } = makeEditor('specs/foo/SPEC', 'The selected passage.');
renderButton({ editor });
await user.click(screen.getByTestId('edit-with-ai-bubble-button'));
- expect(latestMenuInput?.selection?.selectionMarkdown).toBe('Original passage.');
+ await user.type(screen.getByTestId('edit-with-ai-instruction'), 'tighten the prose');
+ await user.click(screen.getByTestId('edit-with-ai-target-claude-code'));
+
+ expect(buildArgs).toEqual([
+ {
+ docName: 'specs/foo/SPEC',
+ workspace: { contentDir: '/tmp/project', pathSeparator: '/' },
+ instruction: 'tighten the prose',
+ selectionMarkdown: 'The selected passage.',
+ },
+ ]);
+ expect(dispatchCalls).toEqual([{ target: 'claude-code', input: { __built: true } }]);
+ });
+
+ test('picking an agent with no instruction still dispatches the selection', async () => {
+ setPlatform('MacIntel');
+ const user = userEvent.setup();
+ const { editor } = makeEditor('specs/foo/SPEC', 'A passage.');
+ renderButton({ editor });
- setSelectionText('Changed after open.');
await user.click(screen.getByTestId('edit-with-ai-bubble-button'));
+ await user.click(screen.getByTestId('edit-with-ai-target-codex'));
- expect(lastNonNullMenuInput?.selection?.selectionMarkdown).toBe('Original passage.');
+ expect(buildArgs[0]?.instruction).toBe('');
+ expect(dispatchCalls).toEqual([{ target: 'codex', input: { __built: true } }]);
});
- test('closing and reopening the trigger captures the current selection', async () => {
+ test('a selection change after the popover opens does not alter the dispatched passage', async () => {
setPlatform('MacIntel');
const user = userEvent.setup();
const { editor, setSelectionText } = makeEditor('specs/foo/SPEC', 'Original passage.');
renderButton({ editor });
await user.click(screen.getByTestId('edit-with-ai-bubble-button'));
- expect(latestMenuInput?.selection?.selectionMarkdown).toBe('Original passage.');
-
- await user.keyboard('{Escape}');
- expect(screen.queryByTestId('edit-with-ai-popover')).toBeNull();
- expect(latestMenuInput).toBeNull();
-
- setSelectionText('Changed after close.');
- await user.click(screen.getByTestId('edit-with-ai-bubble-button'));
+ setSelectionText('A different passage entirely.');
+ await user.click(screen.getByTestId('edit-with-ai-target-claude-code'));
- expect(screen.getByTestId('edit-with-ai-popover')).toBeTruthy();
- expect(latestMenuInput?.selection?.selectionMarkdown).toBe('Changed after close.');
+ expect(buildArgs[0]?.selectionMarkdown).toBe('Original passage.');
});
- test('selection serialization failure shows an error toast without opening the menu', async () => {
+ test('selection serialization failure shows an error toast without opening the popover', async () => {
setPlatform('MacIntel');
const user = userEvent.setup();
const editor = makeThrowingEditor('specs/foo/SPEC');
@@ -311,16 +335,14 @@ describe('EditWithAiBubbleButton', () => {
console.error = originalConsoleError;
}
- expect(screen.queryByTestId('edit-with-ai-popover')).toBeNull();
- expect(latestMenuInput).toBeNull();
+ expect(instructionInput()).toBeNull();
expect(consoleError).toHaveBeenCalledTimes(1);
expect(toastError).toHaveBeenCalledTimes(1);
expect(toastError.mock.calls[0]?.[0]).toBe("Couldn't read the selection — please try again.");
});
- test('keyboard selection serialization failure shows an error toast without opening the menu', async () => {
+ test('keyboard selection serialization failure shows an error toast without opening the popover', async () => {
setPlatform('MacIntel');
- const user = userEvent.setup();
const editor = makeThrowingEditor('specs/foo/SPEC');
const originalConsoleError = console.error;
const consoleError = mock(() => {});
@@ -328,115 +350,16 @@ describe('EditWithAiBubbleButton', () => {
console.error = consoleError as typeof console.error;
try {
- screen.getByTestId('edit-with-ai-bubble-button').focus();
- await user.keyboard('{Enter}');
+ await act(async () => {
+ dispatchEditWithAiShortcut(window);
+ });
} finally {
console.error = originalConsoleError;
}
- expect(screen.queryByTestId('edit-with-ai-popover')).toBeNull();
- expect(latestMenuInput).toBeNull();
+ expect(instructionInput()).toBeNull();
expect(consoleError).toHaveBeenCalledTimes(1);
expect(toastError).toHaveBeenCalledTimes(1);
expect(toastError.mock.calls[0]?.[0]).toBe("Couldn't read the selection — please try again.");
});
-
- test('Cmd+Shift+I opens the local Open with AI menu', async () => {
- setPlatform('MacIntel');
- const { editor } = makeEditor('specs/foo/SPEC', 'A passage.');
- renderButton({ editor });
-
- await act(async () => {
- window.dispatchEvent(
- new KeyboardEvent('keydown', {
- key: 'I',
- code: 'KeyI',
- metaKey: true,
- shiftKey: true,
- bubbles: true,
- cancelable: true,
- }),
- );
- });
-
- expect(screen.getByTestId('edit-with-ai-popover')).toBeTruthy();
- expect(latestMenuInput?.selection).toEqual({
- relativePath: 'specs/foo/SPEC.md',
- instruction: '',
- selectionMarkdown: 'A passage.',
- });
- });
-
- test('Cmd+Shift+I ignores inactive mounted editors', async () => {
- setPlatform('MacIntel');
- const { editor } = makeEditor('specs/foo/SPEC', 'A passage.');
- renderButton({ editor, shortcutEnabled: false });
-
- await act(async () => {
- window.dispatchEvent(
- new KeyboardEvent('keydown', {
- key: 'I',
- code: 'KeyI',
- metaKey: true,
- shiftKey: true,
- bubbles: true,
- cancelable: true,
- }),
- );
- });
-
- expect(screen.queryByTestId('edit-with-ai-popover')).toBeNull();
- expect(latestMenuInput).toBeNull();
- });
-
- test('Cmd+Shift+I ignores native text inputs', async () => {
- setPlatform('MacIntel');
- const { editor } = makeEditor('specs/foo/SPEC', 'A passage.');
- renderButton({ editor, before: <input data-testid="native-input" /> });
-
- await act(async () => {
- screen.getByTestId('native-input').dispatchEvent(
- new KeyboardEvent('keydown', {
- key: 'I',
- code: 'KeyI',
- metaKey: true,
- shiftKey: true,
- bubbles: true,
- cancelable: true,
- }),
- );
- });
-
- expect(screen.queryByTestId('edit-with-ai-popover')).toBeNull();
- expect(latestMenuInput).toBeNull();
- });
-
- test('request carries the editor doc name and serialized selection', async () => {
- setPlatform('MacIntel');
- const user = userEvent.setup();
- const { editor } = makeEditor('specs/foo/SPEC', 'The selected passage.');
- renderButton({ editor });
-
- await user.click(screen.getByTestId('edit-with-ai-bubble-button'));
-
- expect(latestMenuInput?.selection).toEqual({
- relativePath: 'specs/foo/SPEC.md',
- instruction: '',
- selectionMarkdown: 'The selected passage.',
- });
- });
-
- test('a selection change after the request does not alter the dispatched passage', async () => {
- setPlatform('MacIntel');
- const user = userEvent.setup();
- const { editor, setSelectionText } = makeEditor('specs/foo/SPEC', 'Original passage.');
- renderButton({ editor });
-
- await user.click(screen.getByTestId('edit-with-ai-bubble-button'));
- setSelectionText('A different passage entirely.');
-
- expect(latestMenuInput?.selection).toMatchObject({
- selectionMarkdown: 'Original passage.',
- });
- });
});
diff --git a/packages/app/src/editor/bubble-menu/EditWithAiBubbleButton.tsx b/packages/app/src/editor/bubble-menu/EditWithAiBubbleButton.tsx
index 84db3d5ec..0c3ccc7f8 100644
--- a/packages/app/src/editor/bubble-menu/EditWithAiBubbleButton.tsx
+++ b/packages/app/src/editor/bubble-menu/EditWithAiBubbleButton.tsx
@@ -2,28 +2,15 @@ import { Trans, useLingui } from '@lingui/react/macro';
import { isMacOS } from '@tiptap/core';
import type { Editor } from '@tiptap/react';
import { Sparkles } from 'lucide-react';
-import {
- type KeyboardEvent as ReactKeyboardEvent,
- type ReactNode,
- type PointerEvent as ReactPointerEvent,
- useEffect,
- useEffectEvent,
- useRef,
- useState,
-} from 'react';
+import { type ReactNode, useEffect, useEffectEvent, useState } from 'react';
import { toast } from 'sonner';
-import { OpenInAgentMenuContent } from '@/components/handoff/OpenInAgentMenu';
import {
- buildSelectionOrDocHandoffInput,
- type HandoffDispatchInput,
- useHandoffDispatch,
-} from '@/components/handoff/useHandoffDispatch';
-import { useInstalledAgents } from '@/components/handoff/useInstalledAgents';
+ EditWithAiPopover,
+ type EditWithAiSelectionSnapshot,
+} from '@/components/handoff/EditWithAiPopover';
import { Button } from '@/components/ui/button';
-import { DropdownMenu, DropdownMenuTrigger } from '@/components/ui/dropdown-menu';
import { Separator } from '@/components/ui/separator';
import { useIsEmbedded } from '@/hooks/use-is-embedded';
-import { useConfigContext } from '@/lib/config-context';
import { matchesKeyboardShortcut } from '@/lib/keyboard-shortcuts';
import { useWorkspace } from '@/lib/use-workspace';
import { serializeWysiwygSelection } from '../edit-with-ai-selection.ts';
@@ -57,101 +44,40 @@ function EditWithAiBubbleMenu({
shortcutEnabled: boolean;
}): ReactNode {
const { t } = useLingui();
- const { states, refresh } = useInstalledAgents();
- const { dispatch } = useHandoffDispatch();
- const { merged } = useConfigContext();
const workspace = useWorkspace();
- const [menuOpen, setMenuOpen] = useState(false);
- const [menuInput, setMenuInput] = useState<HandoffDispatchInput | null>(null);
- const menuInputRef = useRef<HandoffDispatchInput | null>(null);
- const suppressNextClickRef = useRef(false);
- const autoOpen = merged?.appearance?.preview?.autoOpen ?? true;
- const isElectronHost = typeof window !== 'undefined' && window.okDesktop != null;
- const selectionErrorMessage = t`Couldn't read the selection — please try again.`;
+ const [open, setOpen] = useState(false);
+ const [snapshot, setSnapshot] = useState<EditWithAiSelectionSnapshot | null>(null);
- const captureSelectionInput = (): HandoffDispatchInput | null => {
+ const captureSnapshot = (): EditWithAiSelectionSnapshot | null => {
let selectionMarkdown: string;
try {
selectionMarkdown = serializeWysiwygSelection(editor);
} catch (err) {
console.error('Edit with AI: could not read the selection', err);
- toast.error(selectionErrorMessage);
+ toast.error(t`Couldn't read the selection — please try again.`);
return null;
}
-
- const docName = getEditorDocName(editor);
- const input = buildSelectionOrDocHandoffInput({
- docName,
- workspace,
- instruction: '',
- selectionMarkdown,
- });
- if (input === null) {
- toast.error(selectionErrorMessage);
- return null;
- }
- return input;
- };
-
- const primeSelectionMenu = (): boolean => {
- const input = captureSelectionInput();
- if (input === null) return false;
- menuInputRef.current = input;
- setMenuInput(input);
- return true;
- };
-
- const openSelectionMenu = (): void => {
- if (!primeSelectionMenu()) return;
- setMenuOpen(true);
- void refresh();
- };
-
- const handleOpenChange = (open: boolean): void => {
- setMenuOpen(open);
- if (!open) {
- menuInputRef.current = null;
- setMenuInput(null);
- return;
- }
- void refresh();
+ return { docName: getEditorDocName(editor), workspace, selectionMarkdown };
};
- const handleTriggerPointerDownCapture = (event: ReactPointerEvent<HTMLButtonElement>): void => {
- if (menuInputRef.current !== null) {
- suppressNextClickRef.current = true;
- return;
- }
- if (event.button !== 0) return;
- suppressNextClickRef.current = true;
- if (primeSelectionMenu()) return;
- event.preventDefault();
- event.stopPropagation();
- };
-
- const handleTriggerKeyDownCapture = (event: ReactKeyboardEvent<HTMLButtonElement>): void => {
- if (menuInputRef.current !== null) {
- suppressNextClickRef.current = true;
- return;
- }
- if (event.key !== 'Enter' && event.key !== ' ') return;
- suppressNextClickRef.current = true;
- if (primeSelectionMenu()) return;
- event.preventDefault();
- event.stopPropagation();
+ const openPopover = (): void => {
+ const shot = captureSnapshot();
+ if (shot === null) return;
+ setSnapshot(shot);
+ setOpen(true);
};
- const handleTriggerClick = (): void => {
- if (suppressNextClickRef.current) {
- suppressNextClickRef.current = false;
+ const handleOpenChange = (next: boolean): void => {
+ if (next) {
+ openPopover();
return;
}
- if (menuInputRef.current !== null) return;
- openSelectionMenu();
+ setOpen(false);
+ setSnapshot(null);
};
- const openSelectionMenuEvent = useEffectEvent(() => {
- openSelectionMenu();
+ const openPopoverEvent = useEffectEvent(() => {
+ openPopover();
});
useEffect(() => {
@@ -163,7 +89,7 @@ function EditWithAiBubbleMenu({
event.preventDefault();
event.stopPropagation();
event.stopImmediatePropagation();
- openSelectionMenuEvent();
+ openPopoverEvent();
};
window.addEventListener('keydown', handleKeyDown, { capture: true });
@@ -173,32 +99,20 @@ function EditWithAiBubbleMenu({
return (
<>
<Separator orientation="vertical" className="mx-0.5 h-5 data-vertical:self-center" />
- <DropdownMenu open={menuOpen} onOpenChange={handleOpenChange} modal={false}>
- <DropdownMenuTrigger asChild>
- <Button
- type="button"
- variant="ghost"
- size="sm"
- data-testid="edit-with-ai-bubble-button"
- className="gap-1 px-2 text-sm font-medium text-accent-foreground/80"
- onPointerDownCapture={handleTriggerPointerDownCapture}
- onKeyDownCapture={handleTriggerKeyDownCapture}
- onClick={handleTriggerClick}
- >
- <Sparkles className="size-3.5" aria-hidden="true" />
- <span>
- <Trans>Edit with AI</Trans>
- </span>
- </Button>
- </DropdownMenuTrigger>
- <OpenInAgentMenuContent
- input={menuInput}
- states={states}
- dispatch={dispatch}
- isElectronHost={isElectronHost}
- autoOpen={autoOpen}
- />
- </DropdownMenu>
+ <EditWithAiPopover open={open} onOpenChange={handleOpenChange} snapshot={snapshot}>
+ <Button
+ type="button"
+ variant="ghost"
+ size="sm"
+ data-testid="edit-with-ai-bubble-button"
+ className="gap-1 px-2 text-sm font-medium text-accent-foreground/80"
+ >
+ <Sparkles className="size-3.5" aria-hidden="true" />
+ <span>
+ <Trans>Edit with AI</Trans>
+ </span>
+ </Button>
+ </EditWithAiPopover>
</>
);
}
diff --git a/packages/app/src/locales/en/messages.json b/packages/app/src/locales/en/messages.json
index 1dc05c7ac..3b2ceba1e 100644
--- a/packages/app/src/locales/en/messages.json
+++ b/packages/app/src/locales/en/messages.json
@@ -845,6 +845,7 @@
"RSqaSd": ["Project root"],
"RY6Bq1": ["Open shared ", ["targetNoun"]],
"RaPMZv": ["Keyboard shortcuts available in the editor and workspace."],
+ "Rah7yq": ["What should the AI do? (optional)"],
"RfHNf8": ["Open activity panel for ", ["tooltipName"]],
"RfaEio": ["Toggle source comment"],
"RgbKEe": ["You don't have access to this repository."],
@@ -1058,6 +1059,7 @@
["burstCount", "plural", { "one": ["#", " burst"], "other": ["#", " bursts"] }],
"). Other files and writers are unaffected."
],
+ "ZBt4rI": ["Instruction for the AI"],
"ZLQol-": ["You can turn this on later in <0>Settings → Sync</0>."],
"ZNK2Tq": ["root"],
"ZQLDTl": ["created folder"],
diff --git a/packages/app/src/locales/en/messages.po b/packages/app/src/locales/en/messages.po
index d363b3dc6..230ac7d55 100644
--- a/packages/app/src/locales/en/messages.po
+++ b/packages/app/src/locales/en/messages.po
@@ -924,6 +924,7 @@ msgstr "Cannot upload: no document is open"
msgid "Checkbox"
msgstr "Checkbox"
+#: src/components/handoff/EditWithAiPopover.tsx
#: src/components/handoff/OpenInAgentMenu.tsx
msgid "Checking for installed agents"
msgstr "Checking for installed agents"
@@ -1568,6 +1569,7 @@ msgid "Couldn't save the resolution for {filePath}."
msgstr "Couldn't save the resolution for {filePath}."
#: src/components/EditorPane.tsx
+#: src/components/handoff/EditWithAiPopover.tsx
msgid "Couldn't send the selection — please try again."
msgstr "Couldn't send the selection — please try again."
@@ -1953,6 +1955,7 @@ msgstr "Edit this HTML — the preview updates live."
msgid "Edit wiki link"
msgstr "Edit wiki link"
+#: src/components/handoff/EditWithAiPopover.tsx
#: src/editor/bubble-menu/EditWithAiBubbleButton.tsx
#: src/lib/keyboard-shortcuts.ts
msgid "Edit with AI"
@@ -2875,6 +2878,10 @@ msgstr "Install in Claude Desktop"
msgid "Installing"
msgstr "Installing"
+#: src/components/handoff/EditWithAiPopover.tsx
+msgid "Instruction for the AI"
+msgstr "Instruction for the AI"
+
#: src/components/settings/SettingsDialogBody.tsx
#: src/components/settings/SettingsDialogShell.tsx
msgid "Integrations"
@@ -3501,6 +3508,7 @@ msgstr "No hub pages yet. Hubs appear once pages accumulate inbound graph links.
msgid "No Incoming"
msgstr "No Incoming"
+#: src/components/handoff/EditWithAiPopover.tsx
#: src/components/handoff/OpenInAgentMenu.tsx
msgid "No installed agents found"
msgstr "No installed agents found"
@@ -5975,6 +5983,10 @@ msgstr "What gets created"
msgid "What is this knowledge base for?"
msgstr "What is this knowledge base for?"
+#: src/components/handoff/EditWithAiPopover.tsx
+msgid "What should the AI do? (optional)"
+msgstr "What should the AI do? (optional)"
+
#: src/components/settings/SettingsDialogBody.tsx
msgid "When enabled, the agent opens or refreshes the preview after each edit. Disable if you manage your own preview window (OK Desktop, a browser tab on another display, etc.)."
msgstr "When enabled, the agent opens or refreshes the preview after each edit. Disable if you manage your own preview window (OK Desktop, a browser tab on another display, etc.)."
diff --git a/packages/app/src/locales/pseudo/messages.json b/packages/app/src/locales/pseudo/messages.json
index 932c793cd..8639fb935 100644
--- a/packages/app/src/locales/pseudo/messages.json
+++ b/packages/app/src/locales/pseudo/messages.json
@@ -845,6 +845,7 @@
"RSqaSd": ["ƤŕōĴēćţ ŕōōţ"],
"RY6Bq1": ["Ōƥēń śĥàŕēď ", ["targetNoun"]],
"RaPMZv": ["Ķēŷƀōàŕď śĥōŕţćũţś àvàĩĺàƀĺē ĩń ţĥē ēďĩţōŕ àńď ŵōŕķśƥàćē."],
+ "Rah7yq": ["Ŵĥàţ śĥōũĺď ţĥē ÀĨ ďō? (ōƥţĩōńàĺ)"],
"RfHNf8": ["Ōƥēń àćţĩvĩţŷ ƥàńēĺ ƒōŕ ", ["tooltipName"]],
"RfaEio": ["Ţōĝĝĺē śōũŕćē ćōḿḿēńţ"],
"RgbKEe": ["Ŷōũ ďōń'ţ ĥàvē àććēśś ţō ţĥĩś ŕēƥōśĩţōŕŷ."],
@@ -1058,6 +1059,7 @@
["burstCount", "plural", { "one": ["#", " ƀũŕśţ"], "other": ["#", " ƀũŕśţś"] }],
"). Ōţĥēŕ ƒĩĺēś àńď ŵŕĩţēŕś àŕē ũńàƒƒēćţēď."
],
+ "ZBt4rI": ["Ĩńśţŕũćţĩōń ƒōŕ ţĥē ÀĨ"],
"ZLQol-": ["Ŷōũ ćàń ţũŕń ţĥĩś ōń ĺàţēŕ ĩń <0>Śēţţĩńĝś → Śŷńć</0>."],
"ZNK2Tq": ["ŕōōţ"],
"ZQLDTl": ["ćŕēàţēď ƒōĺďēŕ"],
diff --git a/packages/app/src/locales/pseudo/messages.po b/packages/app/src/locales/pseudo/messages.po
index 0e315d1dc..7f00a5e02 100644
--- a/packages/app/src/locales/pseudo/messages.po
+++ b/packages/app/src/locales/pseudo/messages.po
@@ -919,6 +919,7 @@ msgstr ""
msgid "Checkbox"
msgstr ""
+#: src/components/handoff/EditWithAiPopover.tsx
#: src/components/handoff/OpenInAgentMenu.tsx
msgid "Checking for installed agents"
msgstr ""
@@ -1563,6 +1564,7 @@ msgid "Couldn't save the resolution for {filePath}."
msgstr ""
#: src/components/EditorPane.tsx
+#: src/components/handoff/EditWithAiPopover.tsx
msgid "Couldn't send the selection — please try again."
msgstr ""
@@ -1948,6 +1950,7 @@ msgstr ""
msgid "Edit wiki link"
msgstr ""
+#: src/components/handoff/EditWithAiPopover.tsx
#: src/editor/bubble-menu/EditWithAiBubbleButton.tsx
#: src/lib/keyboard-shortcuts.ts
msgid "Edit with AI"
@@ -2870,6 +2873,10 @@ msgstr ""
msgid "Installing"
msgstr ""
+#: src/components/handoff/EditWithAiPopover.tsx
+msgid "Instruction for the AI"
+msgstr ""
+
#: src/components/settings/SettingsDialogBody.tsx
#: src/components/settings/SettingsDialogShell.tsx
msgid "Integrations"
@@ -3496,6 +3503,7 @@ msgstr ""
msgid "No Incoming"
msgstr ""
+#: src/components/handoff/EditWithAiPopover.tsx
#: src/components/handoff/OpenInAgentMenu.tsx
msgid "No installed agents found"
msgstr ""
@@ -5970,6 +5978,10 @@ msgstr ""
msgid "What is this knowledge base for?"
msgstr ""
+#: src/components/handoff/EditWithAiPopover.tsx
+msgid "What should the AI do? (optional)"
+msgstr ""
+
#: src/components/settings/SettingsDialogBody.tsx
msgid "When enabled, the agent opens or refreshes the preview after each edit. Disable if you manage your own preview window (OK Desktop, a browser tab on another display, etc.)."
msgstr ""
diff --git a/packages/app/tests/stress/edit-with-ai.e2e.ts b/packages/app/tests/stress/edit-with-ai.e2e.ts
index 9e76bb3fc..70848c1b9 100644
--- a/packages/app/tests/stress/edit-with-ai.e2e.ts
+++ b/packages/app/tests/stress/edit-with-ai.e2e.ts
@@ -47,9 +47,9 @@ async function selectFirstParagraph(page: Page): Promise<void> {
async function openSelectionAskAiMenu(page: Page) {
await page.getByTestId('edit-with-ai-bubble-button').click();
- const menu = page.getByTestId('open-in-agent-menu');
- await expect(menu).toBeVisible();
- return menu;
+ const popover = page.getByTestId('edit-with-ai-popover');
+ await expect(popover).toBeVisible();
+ return popover;
}
async function openSourceSelectionAskAiMenu(page: Page, shortcut: string) {
@@ -65,6 +65,10 @@ async function openSourceSelectionAskAiMenu(page: Page, shortcut: string) {
}
async function pickAskAiTarget(page: Page, target: 'claude-code' | 'codex' | 'cursor') {
+ await page.getByTestId(`edit-with-ai-target-${target}`).click();
+}
+
+async function pickSourceAskAiTarget(page: Page, target: 'claude-code' | 'codex' | 'cursor') {
await page.getByTestId(`open-in-agent-item-${target}`).click();
}
@@ -129,7 +133,7 @@ test.describe('Edit with AI — affordance + deep-link dispatch (live app)', ()
await seedAndOpenWysiwyg(page, api, 'qa-ewai-source-shortcut', `# Heading\n\n${PROSE}`);
await openSourceSelectionAskAiMenu(page, 'Meta+Shift+I');
- await pickAskAiTarget(page, 'claude-code');
+ await pickSourceAskAiTarget(page, 'claude-code');
await expect
.poll(async () => (await readCapturedHandoff(page)).handoffApiCalls.length, {
@@ -144,7 +148,7 @@ test.describe('Edit with AI — affordance + deep-link dispatch (live app)', ()
expect(q).toContain('quick brown fox');
});
- test('WYSIWYG Cmd+Shift+I opens the shared Ask AI menu for the selected passage', async ({
+ test('WYSIWYG Cmd+Shift+I opens the selection popover for the selected passage', async ({
page,
api,
workerServer,
@@ -154,7 +158,7 @@ test.describe('Edit with AI — affordance + deep-link dispatch (live app)', ()
await selectFirstParagraph(page);
await page.keyboard.press('ControlOrMeta+Shift+I');
- await expect(page.getByTestId('open-in-agent-menu')).toBeVisible();
+ await expect(page.getByTestId('edit-with-ai-popover')).toBeVisible();
await pickAskAiTarget(page, 'claude-code');
await expect
@@ -247,7 +251,7 @@ test.describe('Edit with AI — affordance + deep-link dispatch (live app)', ()
await expect(page.getByTestId('edit-with-ai-bubble-button')).toHaveCount(0);
});
- test('QA-012: shared Ask AI menu shows installed agents and no claude.ai/web fallback row', async ({
+ test('QA-012: selection popover shows installed agents and no claude.ai/web fallback row', async ({
page,
api,
workerServer,
@@ -255,18 +259,43 @@ test.describe('Edit with AI — affordance + deep-link dispatch (live app)', ()
await installHandoffMocks(page, webCfg(workerServer));
await seedAndOpenWysiwyg(page, api, 'qa-ewai-agents', `# H\n\n${PROSE}`);
await selectFirstParagraph(page);
- const menu = await openSelectionAskAiMenu(page);
-
- await expect(page.getByTestId('open-in-agent-item-claude-code')).toBeVisible();
- await expect(page.getByTestId('open-in-agent-item-codex')).toBeVisible();
- await expect(page.getByTestId('open-in-agent-item-cursor')).toBeVisible();
- await expect(page.getByTestId('open-in-agent-item-claude-cowork')).toHaveCount(0);
- await expect(page.getByTestId('open-in-agent-claude-web-fallback')).toHaveCount(0);
- const bodyText = await menu.innerText();
+ const popover = await openSelectionAskAiMenu(page);
+
+ await expect(page.getByTestId('edit-with-ai-target-claude-code')).toBeVisible();
+ await expect(page.getByTestId('edit-with-ai-target-codex')).toBeVisible();
+ await expect(page.getByTestId('edit-with-ai-target-cursor')).toBeVisible();
+ await expect(page.getByTestId('edit-with-ai-target-claude-cowork')).toHaveCount(0);
+ const bodyText = await popover.innerText();
expect(bodyText.toLowerCase()).not.toContain('claude.ai');
});
- test('QA-013: dispatch allowed with empty instruction (no instruction text in prompt)', async ({
+ test('QA-013: typed instruction appears in the dispatched prompt', async ({
+ page,
+ api,
+ workerServer,
+ }) => {
+ await installHandoffMocks(page, webCfg(workerServer));
+ await seedAndOpenWysiwyg(page, api, 'qa-ewai-instr', `# H\n\n${PROSE}`);
+ await selectFirstParagraph(page);
+ await openSelectionAskAiMenu(page);
+ await page.getByTestId('edit-with-ai-instruction').fill('tighten the prose');
+ await pickAskAiTarget(page, 'codex');
+
+ await expect
+ .poll(async () => (await readCapturedHandoff(page)).handoffApiCalls.length, {
+ timeout: 5_000,
+ })
+ .toBe(1);
+ const call = (await readCapturedHandoff(page)).handoffApiCalls[0];
+ expect(call?.target).toBe('codex');
+ const prompt = new URL(call?.url ?? '').searchParams.get('prompt') ?? '';
+ expect(prompt).toContain('@qa-ewai-instr.md');
+ expect(prompt).toContain('quick brown fox');
+ expect(prompt).toContain('Instruction:');
+ expect(prompt).toContain('tighten the prose');
+ });
+
+ test('QA-013b: dispatch allowed with empty instruction (no instruction text in prompt)', async ({
page,
api,
workerServer,
@@ -288,9 +317,10 @@ test.describe('Edit with AI — affordance + deep-link dispatch (live app)', ()
expect(prompt).toContain('@qa-ewai-noinstr.md');
expect(prompt).toContain('quick brown fox');
expect(prompt).toContain('Here is the passage:');
+ expect(prompt).not.toContain('Instruction:');
});
- test('QA-024: shared Ask AI menu shows pending then empty-install copy when no agents installed', async ({
+ test('QA-024: selection popover shows pending then empty-install copy when no agents installed', async ({
page,
api,
workerServer,
@@ -305,14 +335,14 @@ test.describe('Edit with AI — affordance + deep-link dispatch (live app)', ()
await seedAndOpenWysiwyg(page, api, 'qa-ewai-empty', `# H\n\n${PROSE}`);
await selectFirstParagraph(page);
await openSelectionAskAiMenu(page);
- const empty = page.getByTestId('open-in-agent-selection-empty');
+ const empty = page.getByTestId('edit-with-ai-empty');
await expect(empty).toBeVisible();
const txt = await empty.innerText();
expect(/Checking for installed agents|No installed agents found/.test(txt)).toBe(true);
- await expect(page.getByTestId('open-in-agent-item-claude-code')).toHaveCount(0);
+ await expect(page.getByTestId('edit-with-ai-target-claude-code')).toHaveCount(0);
});
- test('QA-027: shared Ask AI menu opens from keyboard activation', async ({
+ test('QA-027: selection popover opens from keyboard activation', async ({
page,
api,
workerServer,
@@ -324,11 +354,11 @@ test.describe('Edit with AI — affordance + deep-link dispatch (live app)', ()
await expect(btn).toBeVisible({ timeout: 10_000 });
await btn.focus();
await page.keyboard.press('Enter');
- await expect(page.getByTestId('open-in-agent-menu')).toBeVisible();
- await expect(page.getByTestId('open-in-agent-item-claude-code')).toBeVisible();
+ await expect(page.getByTestId('edit-with-ai-popover')).toBeVisible();
+ await expect(page.getByTestId('edit-with-ai-target-claude-code')).toBeVisible();
});
- test('QA-028: Escape closes the shared Ask AI menu without dispatching and with no error toast', async ({
+ test('QA-028: Escape closes the selection popover without dispatching and with no error toast', async ({
page,
api,
workerServer,
@@ -338,7 +368,7 @@ test.describe('Edit with AI — affordance + deep-link dispatch (live app)', ()
await selectFirstParagraph(page);
await openSelectionAskAiMenu(page);
await page.keyboard.press('Escape');
- await expect(page.getByTestId('open-in-agent-menu')).toHaveCount(0);
+ await expect(page.getByTestId('edit-with-ai-popover')).toHaveCount(0);
const captured = await readCapturedHandoff(page);
expect(captured.handoffApiCalls).toEqual([]);
await expect(page.getByText(/Couldn't reach/)).toHaveCount(0);