Beautiful, AI-native markdown IDE and LLM wiki
TypeScript 2nd-brainagent-skillsclaudecodexcompany-braindocsknowledge-knowledge-baseknowledge-managementllmllm-wikillm-wiki-karpathymarkdownmarkdown-editormdmdxnotespkmsecond-brainskills
feat(ok): shared AI prompt composer — migrate ACP thread composer onto ComposerMentionInput (PRD-7880) (#3375)
mike-inkeep8df829ff1ea4
diff --git a/.changeset/acp-shared-prompt-composer.md b/.changeset/acp-shared-prompt-composer.mdnew file mode 100644index 000000000..cfb9abfe4--- /dev/null+++ b/.changeset/acp-shared-prompt-composer.md@@ -0,0 +1,5 @@+---+"@inkeep/open-knowledge": patch+---++The agent-thread composer now uses the same rich prompt field as every other AI composer in the app. Typing `@` in the sidebar chat picks files, folders, and assets from the workspace and inserts them as removable chips, exactly as it does in the bottom Ask AI, New Tab, and comment composers — the agent receives them as `@path` references it can open. The migration also fixes a live input bug: the thread composer had no IME-composition guard, so committing CJK text with Enter could fire a premature send; the shared field guards every surface uniformly. Composer drafts still behave the same — staged selection passages append to what you typed, and stopping a turn folds its queued messages back into the field. With all four prompt surfaces on one component, upcoming composer capabilities (attachments, slash commands) land once and reach every surface.diff --git a/biome-plugins/README.md b/biome-plugins/README.mdindex e58a874ca..58e08beb7 100644--- a/biome-plugins/README.md+++ b/biome-plugins/README.md@@ -44,7 +44,7 @@ UI primitives discipline. Forbids raw JSX `<button>`, `<input>`, `<textarea>`, `- `!packages/app/src/editor/**` — ProseMirror NodeViews + editor chrome legitimately render raw HTML for measurement / PM-managed DOM. The exemption matches the existing `a11y/useSemanticElements` suppressions scattered through the editor subtree.- `!packages/app/src/components/ui/**` — these files ARE the shadcn primitive wrappers; they MUST render raw HTML by definition.-- `!**/*.test.tsx` + `!**/*.dom.test.tsx` — test fixtures aren't user-facing UI.+- `!**/*.test.tsx` + `!**/*.dom.test.tsx` + `!**/*.test-helper.tsx` — test fixtures and shared test doubles aren't user-facing UI.**Pre-rule backlog (ratchet pattern).** Files that pre-date the rule and use raw `<button>` / `<input>` / `<textarea>` carry a file-level `// biome-ignore-all lint/plugin/no-raw-html-interactive-element: pre-rule backlog — ...` comment at the top of the file. The comment list across the codebase IS the visible migration backlog — review treats each `biome-ignore-all` header as a backlog marker, not a free pass. Drain by migrating the file to shadcn primitives, then deleting the suppression header (the rule starts firing again immediately, so a partial migration that misses a raw `<button>` fails the gate). Reference migration: `packages/app/src/components/NavigatorApp.tsx` (three raw `<button>` → shadcn `<Button variant="ghost|outline|link">`).diff --git a/biome.jsonc b/biome.jsoncindex 0510dcaf0..974f53331 100644--- a/biome.jsonc+++ b/biome.jsonc@@ -187,7 +187,8 @@// a11y/useSemanticElements suppressions in editor/*).// - packages/app/src/components/ui/** — these ARE the shadcn primitive// wrappers; they must render raw HTML by definition.- // - *.test.tsx / *.dom.test.tsx — test fixtures aren't user-facing UI.+ // - *.test.tsx / *.dom.test.tsx / *.test-helper.tsx — test fixtures and+ // shared test doubles aren't user-facing UI.// Pre-rule backlog (files outside the exemptions that pre-date the rule)// is annotated via `// biome-ignore-all lint/plugin/no-raw-html-interactive-element:`// at the top of each offender file — the comment list is the visible@@ -201,6 +202,7 @@"!packages/app/src/components/ui/**","!**/*.test.tsx","!**/*.dom.test.tsx",+ "!**/*.test-helper.tsx","biome-plugins/__fixtures__/no-raw-html-interactive-element.fixture.tsx"],"plugins": ["./biome-plugins/no-raw-html-interactive-element.grit"]diff --git a/packages/app/src/components/acp/ThreadView.comments.dom.test.tsx b/packages/app/src/components/acp/ThreadView.comments.dom.test.tsxindex c799257e6..375bb1687 100644--- a/packages/app/src/components/acp/ThreadView.comments.dom.test.tsx+++ b/packages/app/src/components/acp/ThreadView.comments.dom.test.tsx@@ -17,6 +17,7 @@ import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';import type { CommentThread } from '@/comments/types';import { TooltipProvider } from '@/components/ui/tooltip';import type { ThreadRenderModel } from '@/lib/acp/thread-event-model';+import { MockComposerMentionInput } from './composer-mention-input.test-helper';const render = (ui: Parameters<typeof rtlRender>[0]) => rtlRender(ui, { wrapper: TooltipProvider });@@ -63,6 +64,12 @@ vi.doMock('@/components/acp/AgentMarkdown', () => ({AgentMarkdown: ({ text }: { text: string }) => <div>{text}</div>,}));+// The composer's rich input, doubled as a textarea (jsdom can't type into a+// ProseMirror contentEditable) — see the helper's header for contract parity.+vi.doMock('@/editor/ComposerMentionInput', () => ({+ ComposerMentionInput: MockComposerMentionInput,+}));+/*** The comment store, doubled: a fixed queue with everything checked. The real* one talks to the server on every read, and the dispatch path's server-sidediff --git a/packages/app/src/components/acp/ThreadView.dom.test.tsx b/packages/app/src/components/acp/ThreadView.dom.test.tsxindex f606140f7..87fb009b8 100644--- a/packages/app/src/components/acp/ThreadView.dom.test.tsx+++ b/packages/app/src/components/acp/ThreadView.dom.test.tsx@@ -24,6 +24,7 @@ import type {RenderedTerminal,ThreadRenderModel,} from '@/lib/acp/thread-event-model';+import { MockComposerMentionInput } from './composer-mention-input.test-helper';// ThreadView renders Radix Tooltips (the context-usage ring, the follow// toggle). The app installs the single TooltipProvider at its root (main.tsx),@@ -104,6 +105,12 @@ vi.doMock('@/components/acp/AgentMarkdown', () => ({AgentMarkdown: ({ text }: { text: string }) => <div>{text}</div>,}));+// The composer's rich input, doubled as a textarea (jsdom can't type into a+// ProseMirror contentEditable) — see the helper's header for contract parity.+vi.doMock('@/editor/ComposerMentionInput', () => ({+ ComposerMentionInput: MockComposerMentionInput,+}));+const { ThreadView } = await import('./ThreadView');// Not mocked — the settings popover writes real remembered picks through it.const { agentSettingsKey, getRememberedAgentConfig, getRememberedAgentMode } = await import(diff --git a/packages/app/src/components/acp/ThreadView.tsx b/packages/app/src/components/acp/ThreadView.tsxindex bedcdc055..3035e57df 100644--- a/packages/app/src/components/acp/ThreadView.tsx+++ b/packages/app/src/components/acp/ThreadView.tsx@@ -104,6 +104,10 @@ import { Switch } from '@/components/ui/switch';import { Textarea } from '@/components/ui/textarea';import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip';import { WorkingAvatar } from '@/components/WorkingAvatar';+import {+ ComposerMentionInput,+ type ComposerMentionInputHandle,+} from '@/editor/ComposerMentionInput';import { useDocumentContext } from '@/editor/DocumentContext';import {agentSettingsKey,@@ -227,7 +231,13 @@ export function ThreadView({const state = useAgentThread(info.threadId);const client = getAgentThreadClient();const workspace = useWorkspace();- const [draft, setDraft] = useState('');+ // The composer input (the shared rich `@`-mention field) owns the draft; this+ // component reads it at each send via the imperative handle and seeds it via+ // `appendText` — there is no draft string in React state anymore.+ const composerRef = useRef<ComposerMentionInputHandle>(null);+ // The current serialized draft: typed prose with chips inline as `@path`.+ // Called from event handlers only (a render must not read the ref).+ const composerText = (): string => composerRef.current?.getContent().instruction.trim() ?? '';const [followFile, setFollowFile] = useState(loadFollowFilePref);// Captured by ScrollToEndBridge (a child of the scroller Provider) so send/// resume can imperatively jump to the live edge; null until the bridge mounts.@@ -245,10 +255,12 @@ export function ThreadView({// seeds the composer instead of auto-sending, so the user reviews and extends// the passage before spending a turn — the same stage-don't-submit contract the// terminal CLI path honors. Appends rather than overwrites so a staged value- // arriving after the user started typing can't eat their words.+ // arriving after the user started typing can't eat their words. The handle is+ // populated before this subscribes: the composer child's ref commits before+ // the parent's effects run, so a value staged before mount is not dropped.useEffect(() => {return subscribeStagedThreadDraft(info.threadId, (text) => {- setDraft((prev) => (prev.trim() === '' ? text : `${prev.replace(/\s+$/, '')}\n\n${text}`));+ composerRef.current?.appendText(text);});}, [info.threadId]);@@ -349,8 +361,7 @@ export function ThreadView({...(info.queue ?? []).map((message) => message.content),];if (rescued.length > 0) {- const text = rescued.join('\n\n');- setDraft((prev) => (prev.trim() === '' ? text : `${prev.replace(/\s+$/, '')}\n\n${text}`));+ composerRef.current?.appendText(rescued.join('\n\n'));}client.cancel(info.threadId);setCancelPending(true);@@ -362,10 +373,10 @@ export function ThreadView({* interrupting a run is not something a habit keystroke should do.*/const requestSteer = (): void => {- const text = draft.trim();+ const text = composerText();if (text === '') return;client.steer(info.threadId, text);- setDraft('');+ composerRef.current?.clear();scrollApiRef.current?.scrollToEnd();};@@ -504,7 +515,7 @@ export function ThreadView({};const submit = (): void => {- const text = draft.trim();+ const text = composerText();// `canQueue` rides alongside `canPrompt`: a busy thread accepts a queued// message rather than refusing the send.if (!(canPrompt || canQueue)) return;@@ -523,7 +534,7 @@ export function ThreadView({}if (text === '') return;void sendText(text);- setDraft('');+ composerRef.current?.clear();};/**@@ -573,7 +584,7 @@ export function ThreadView({t`Your comments are waiting behind the running turn — they stay queued until the agent picks the message up.`,);}- setDraft('');+ composerRef.current?.clear();// The batch detaches with the rest of the draft. Left on, the next message// would silently carry whatever had been queued since.setCommentsAttached(false);@@ -597,7 +608,7 @@ export function ThreadView({// The composer's own guard: a busy thread accepts a queued message, a dead// one accepts nothing.if (!(canPrompt || canQueue)) return;- submitQueuedComments(draft.trim(), threadIds).catch((err) => {+ submitQueuedComments(composerText(), threadIds).catch((err) => {console.warn('[acp] panel comment send rejected unexpectedly', err);});});@@ -629,7 +640,8 @@ export function ThreadView({};const startFreshThread = (): void => {- const prompt = failedPrompt ?? (draft.trim() === '' ? undefined : draft.trim());+ const draftText = composerText();+ const prompt = failedPrompt ?? (draftText === '' ? undefined : draftText);setResumeError(null);setFailedPrompt(null);void client@@ -825,8 +837,7 @@ export function ThreadView({) : null}<ThreadComposerinfo={info}- draft={draft}- onDraftChange={setDraft}+ composerRef={composerRef}onSubmit={submit}canPrompt={canPrompt}canQueue={canQueue}@@ -2732,8 +2743,7 @@ function ContextUsageRing({function ThreadComposer({info,- draft,- onDraftChange,+ composerRef,onSubmit,canPrompt,canQueue,@@ -2754,8 +2764,10 @@ function ThreadComposer({onDismissComments,}: {info: ThreadInfo;- draft: string;- onDraftChange: (value: string) => void;+ /** The parent's handle to the shared composer input — ThreadView reads the+ * draft through it at send time and seeds it (staged passages, a cancelled+ * turn's rescued queue) via `appendText`. */+ composerRef: RefObject<ComposerMentionInputHandle | null>;onSubmit: () => void;canPrompt: boolean;/** A turn is running — sends queue behind it instead of dispatching. */@@ -2790,21 +2802,22 @@ function ThreadComposer({onDismissComments: () => void;}): ReactNode {const { t } = useLingui();- const ref = useRef<HTMLTextAreaElement>(null);// Naming the agent in the placeholder ("Message Claude") beats a generic// "Message the agent"; strip the "Agent" suffix so it reads as the brand.const agentName = agentDisplayName(info.agent.name);- // Grow with content up to a cap. `draft` is the trigger, not read in the- // body (the element's own scrollHeight is), so the analyzer sees it as- // redundant — but it is exactly what should re-run the resize.- // biome-ignore lint/correctness/useExhaustiveDependencies: draft is the resize trigger, not a body dependency- useEffect(() => {- const el = ref.current;- if (el === null) return;- el.style.height = 'auto';- el.style.height = `${Math.min(el.scrollHeight, 160)}px`;- }, [draft]);+ // The input owns the draft; this host tracks only emptiness (pushed up via+ // `onEmptyChange`) to drive the send-enabled state and the Stop/Send/Steer+ // action slot. Content is read at send time through `composerRef`.+ const [isEmpty, setIsEmpty] = useState(true);++ // Typable in every live state, including the ones that are only waiting on+ // something: signing in takes a detour through a browser (and flips the+ // status to `installing` while it does), a failed start is a Retry away from+ // running, and a draft written across any of that must survive. Only a+ // thread whose agent is gone for good has nothing left to say. Sending is+ // still gated by canPrompt / canQueue.+ const composerDisabled = archived ? resumePending : status === 'exited';const usagePercent =usage !== null && usage.used !== undefined && usage.size !== undefined && usage.size > 0@@ -2818,7 +2831,7 @@ function ThreadComposer({// What the action slot keys off. Both the Stop/Send choice and Send's disabled// state read this, or the two disagree. An attached batch counts as content:// the comments are the ask, so a send with nothing typed is a real send.- const hasSendableContent = draft.trim() !== '' || hasQueuedComments;+ const hasSendableContent = !isEmpty || hasQueuedComments;// Mid-turn the same control queues rather than sends, so it stops wearing the// send arrow — an aria-label the sighted user never reads was the only thing@@ -2846,15 +2859,15 @@ function ThreadComposer({{queue.length > 0 && !archived ? (<QueuedMessageList threadId={info.threadId} queue={queue} />) : null}- {/* Two-row field: the textarea fills the full width on top; a bottom bar+ {/* Two-row field: the input fills the full width on top; a bottom barholds the model/agent settings (left) and the context ring + send/stop(right). The wrapper owns the border + focus ring so the whole box lightsup on focus. Every control is a real in-flow sibling (natural Tab order,own focus ring) and the send button lives on its own row, so there's noreserved text gutter narrowing the input on multi-line drafts. */}- {/* biome-ignore lint/a11y/noStaticElementInteractions: pointer-only affordance — pressing the card's whitespace focuses the textarea; keyboard/AT users reach it via Tab. See focus-composer-on-card-pointer.ts. */}+ {/* biome-ignore lint/a11y/noStaticElementInteractions: pointer-only affordance — pressing the card's whitespace focuses the composer input; keyboard/AT users reach it via Tab. See focus-composer-on-card-pointer.ts. */}<div- onMouseDown={(event) => focusComposerInputOnCardPointer(event, ref)}+ onMouseDown={(event) => focusComposerInputOnCardPointer(event, composerRef)}className="cursor-text rounded-lg border border-input bg-transparent transition-colors focus-within:border-ring focus-within:ring-3 focus-within:ring-ring/50 dark:bg-input/30">{/* Queued comments as a context chip above the field, the same control@@ -2883,30 +2896,27 @@ function ThreadComposer({) : null}</ComposerContextChips>) : null}- <Textarea- ref={ref}- value={draft}- onChange={(event) => onDraftChange(event.target.value)}- onKeyDown={(event) => {- if (event.key === 'Enter' && !event.shiftKey) {- event.preventDefault();- onSubmit();- } else if (event.key === 'Escape' && turnActive && !cancelPending) {- // Deliberately field-scoped, not panel-wide. Sendable content hides- // Stop, so Escape is the cancel path while composing — but Escape- // is a dismiss-shaped key, and binding it panel-wide would let a- // stray press kill a running turn with no undo. The accepted cost:- // leave content in the composer, click away, and neither Stop nor- // Escape is reachable until you click back or clear it. Judged rare- // enough to accept over a broader binding or a second Stop.- event.preventDefault();- onCancel();- }- }}- rows={1}+ <ComposerMentionInput+ ref={composerRef}// Stable accessible name — the placeholder is situational (and a// placeholder alone isn't a reliable label for screen readers).- aria-label={t`Message ${agentName}`}+ ariaLabel={t`Message ${agentName}`}+ onEmptyChange={setIsEmpty}+ // Enter with the `@`-popup closed (IME-composition guarded inside the+ // shared input, so a CJK commit-Enter never sends).+ onSubmit={onSubmit}+ onEscape={() => {+ // Deliberately field-scoped, not panel-wide. Sendable content hides+ // Stop, so Escape is the cancel path while composing — but Escape+ // is a dismiss-shaped key, and binding it panel-wide would let a+ // stray press kill a running turn with no undo. The accepted cost:+ // leave content in the composer, click away, and neither Stop nor+ // Escape is reachable until you click back or clear it. Judged rare+ // enough to accept over a broader binding or a second Stop. With no+ // turn running Escape is a no-op (never a blur), matching the+ // textarea this field replaced.+ if (turnActive && !cancelPending) onCancel();+ }}placeholder={archived? resumePending@@ -2916,23 +2926,17 @@ function ThreadComposer({? t`Sign in to ${agentName} first`: t`Message ${agentName}`}- disabled={- archived- ? resumePending- : // Typable in every live state, including the ones that are only- // waiting on something: signing in takes a detour through a- // browser (and flips the status to `installing` while it does),- // a failed start is a Retry away from running, and a draft- // written across any of that must survive. Only a thread whose- // agent is gone for good has nothing left to say. Sending is- // still gated by canPrompt / canQueue.- status === 'exited'- }- // Borderless + transparent so the wrapper alone renders the field chrome- // and focus ring (no doubled border/ring). Full width — the action bar- // sits on its own row below, so no right-padding gutter is reserved.- className="max-h-40 min-h-9 resize-none border-0 bg-transparent pb-0 shadow-none focus-visible:border-0 focus-visible:ring-0 disabled:bg-transparent dark:bg-transparent dark:disabled:bg-transparent placeholder:text-muted-foreground/60"- data-testid="agent-thread-composer"+ disabled={composerDisabled}+ // The wrapper alone renders the field chrome and focus ring; this is a+ // bare scrolling text region sized to the old textarea (single slim+ // line at rest, capped growth). Full width — the action bar sits on+ // its own row below, so no right-padding gutter is reserved. Disabled+ // dims like the native textarea it replaced.+ className={cn(+ 'max-h-40 overflow-y-auto px-2.5 pt-1 text-base md:text-sm',+ composerDisabled && 'opacity-50',+ )}+ testId="agent-thread-composer"/>{/* Action bar: model/agent settings on the left, context ring + send/stopon the right. The send cluster uses `ml-auto` (not the row's@@ -2980,7 +2984,7 @@ function ThreadComposer({are some — an attached comment batch has its own deliveryrules (it stays queued until a turn actually runs it) andmust not be interrupted onto a run being cancelled. */}- {draft.trim() !== '' ? (+ {!isEmpty ? (<Tooltip><TooltipTrigger asChild><Buttondiff --git a/packages/app/src/components/acp/ThreadView.working-loop.dom.test.tsx b/packages/app/src/components/acp/ThreadView.working-loop.dom.test.tsxindex a338185b6..0f562ba6a 100644--- a/packages/app/src/components/acp/ThreadView.working-loop.dom.test.tsx+++ b/packages/app/src/components/acp/ThreadView.working-loop.dom.test.tsx@@ -10,6 +10,7 @@ import { act, cleanup, render as rtlRender } from '@testing-library/react';import { afterEach, describe, expect, test, vi } from 'vitest';import { TooltipProvider } from '@/components/ui/tooltip';import type { RenderedItem, ThreadRenderModel } from '@/lib/acp/thread-event-model';+import { MockComposerMentionInput } from './composer-mention-input.test-helper';const render = (ui: Parameters<typeof rtlRender>[0]) => rtlRender(ui, { wrapper: TooltipProvider });@@ -51,6 +52,12 @@ vi.doMock('@/lib/use-workspace', () => ({ useWorkspace: () => null }));vi.doMock('@/components/acp/AgentMarkdown', () => ({AgentMarkdown: ({ text }: { text: string }) => <div>{text}</div>,}));+// The composer's rich input, doubled as a textarea — a real TipTap instance in+// jsdom schedules deferred scroll work that can crash the run after the suite+// passes, and this suite only needs the composer to mount.+vi.doMock('@/editor/ComposerMentionInput', () => ({+ ComposerMentionInput: MockComposerMentionInput,+}));// The comments store is deliberately NOT mocked here. It is the one dependency// in this component with a documented history of the runaway-update failure// (an unstable `useSyncExternalStore` snapshot — see comments/store.ts), anddiff --git a/packages/app/src/components/acp/composer-mention-input.test-helper.tsx b/packages/app/src/components/acp/composer-mention-input.test-helper.tsxnew file mode 100644index 000000000..6b80773e5--- /dev/null+++ b/packages/app/src/components/acp/composer-mention-input.test-helper.tsx@@ -0,0 +1,87 @@+/**+ * Textarea double for the shared `ComposerMentionInput`, for the ThreadView+ * DOM suites' `vi.doMock('@/editor/ComposerMentionInput', ...)`.+ *+ * The real field is a ProseMirror contentEditable, which jsdom cannot type+ * into (`fireEvent.change` is inert and `user.keyboard` needs a real editing+ * host), and whose deferred scroll work is a known source of post-suite+ * crashes under the DOM runner — so ThreadView suites drive this double and+ * the editor's own behavior (chips, `@`-typeahead, IME guard, key handling)+ * is covered against the real TipTap instance in+ * `ComposerMentionInput.dom.test.tsx`.+ *+ * Contract parity, because ThreadView's logic is what these suites test:+ * the full imperative handle (focus / blur / clear / setText / appendText /+ * getContent), `onEmptyChange` on every edit, Enter-submits with the IME+ * guard, Escape → `onEscape` (else blur), and placeholder / disabled /+ * testId as plain DOM attributes. `appendText` reproduces the blank-line+ * join (`existing\n\nappended`) the rescue/staged-draft tests assert.+ */++import { type Ref, useImperativeHandle, useRef } from 'react';+import type { ComposerMentionInputHandle } from '@/editor/ComposerMentionInput';++export function MockComposerMentionInput({+ ref,+ ariaLabel,+ onEmptyChange,+ onSubmit,+ onEscape,+ className,+ placeholder,+ disabled,+ testId,+}: {+ ref?: Ref<ComposerMentionInputHandle>;+ ariaLabel: string;+ onEmptyChange: (isEmpty: boolean) => void;+ onSubmit: () => void;+ onEscape?: () => void;+ className?: string;+ placeholder?: string;+ disabled?: boolean;+ testId?: string;+}) {+ const localRef = useRef<HTMLTextAreaElement>(null);+ const notify = () => onEmptyChange((localRef.current?.value.trim() ?? '') === '');+ useImperativeHandle(ref, () => ({+ focus: () => localRef.current?.focus(),+ blur: () => localRef.current?.blur(),+ clear: () => {+ if (localRef.current) localRef.current.value = '';+ onEmptyChange(true);+ },+ setText: (text: string) => {+ if (localRef.current) localRef.current.value = text;+ notify();+ },+ appendText: (text: string) => {+ const el = localRef.current;+ if (!el || text === '') return;+ el.value = el.value.trim() === '' ? text : `${el.value.replace(/\s+$/, '')}\n\n${text}`;+ notify();+ },+ getContent: () => ({ instruction: localRef.current?.value ?? '', mentions: [] }),+ }));+ return (+ <textarea+ ref={localRef}+ aria-label={ariaLabel}+ placeholder={placeholder}+ disabled={disabled}+ data-testid={testId}+ className={className}+ onChange={notify}+ onKeyDown={(event) => {+ if (event.key === 'Enter' && !event.shiftKey && !event.nativeEvent.isComposing) {+ event.preventDefault();+ onSubmit();+ } else if (event.key === 'Escape') {+ event.preventDefault();+ if (onEscape !== undefined) onEscape();+ else localRef.current?.blur();+ }+ }}+ />+ );+}diff --git a/packages/app/src/components/focus-composer-on-card-pointer.ts b/packages/app/src/components/focus-composer-on-card-pointer.tsindex e243af8b6..42c817ab4 100644--- a/packages/app/src/components/focus-composer-on-card-pointer.ts+++ b/packages/app/src/components/focus-composer-on-card-pointer.ts@@ -1,15 +1,14 @@/*** Shared "click the card, focus the field" affordance for the composer cards:- * the two Ask AI composers (ProseMirror `ComposerMentionInput` contentEditable)- * and the agent-thread composer (native `<textarea>`).+ * the two Ask AI composers and the agent-thread composer (all ProseMirror+ * `ComposerMentionInput` contentEditables).** A contentEditable focuses on click only within its OWN box, and — unlike a* labelable form control — a wrapping `<label>` cannot forward a click into it,* so the standard chat-composer affordance (ChatGPT / Claude / Cursor: click- * anywhere in the field's card to focus the input) needs this pointer handler.- * The agent-thread composer's chrome (wrapper padding, the whitespace in the- * action bar between the settings menu and the send button) isn't wrapped in a- * label either, so it reuses the same handler against its textarea ref.+ * anywhere in the field's card to focus the input) needs this pointer handler+ * for the card's chrome (wrapper padding, the whitespace in an action bar+ * between the settings menu and the send button).** a11y: this is a pointer-only progressive enhancement. The card keeps passive* semantics (no `role`/`tabindex`) — the real control is the inner textbox,@@ -40,9 +39,9 @@ export function focusComposerInputOnCardPointer(currentTarget: EventTarget | null;preventDefault: () => void;},- // Any focusable input handle — the ProseMirror `ComposerMentionInputHandle`- // (Ask AI composers) or a native `HTMLTextAreaElement` (the agent-thread- // composer). Both expose `focus()`.+ // Any focusable input handle — in practice the ProseMirror+ // `ComposerMentionInputHandle`; typed structurally so any `focus()`-bearing+ // handle works.inputRef: RefObject<{ focus: () => void } | null>,): void {if (!(event.target instanceof HTMLElement)) return;diff --git a/packages/app/src/editor/ComposerMentionInput.dom.test.tsx b/packages/app/src/editor/ComposerMentionInput.dom.test.tsxindex 1f1f2b181..1b93822b3 100644--- a/packages/app/src/editor/ComposerMentionInput.dom.test.tsx+++ b/packages/app/src/editor/ComposerMentionInput.dom.test.tsx@@ -39,6 +39,12 @@ function mentionNode(path: string, label = path): Content {return { type: 'composerMention', attrs: { path, label } };}+/** Reach the live editor from the rendered textbox — TipTap's EditorContent+ * tags the contenteditable host node with the instance. */+function getComposerEditor(box: HTMLElement): Editor {+ return (box as unknown as { editor: Editor }).editor;+}+let consoleErrorSpy: ReturnType<typeof vi.spyOn>;beforeEach(() => {@@ -154,6 +160,105 @@ describe('ComposerMentionInput (component)', () => {expect(ref.current?.getContent()).toEqual({ instruction: 'a research wiki', mentions: [] });});+ test('appendText fills an empty field, mapping newlines to paragraphs', () => {+ const ref = createRef<ComposerMentionInputHandle>();+ const onEmptyChange = vi.fn((_isEmpty: boolean) => {});+ render(+ <ComposerMentionInput+ ref={ref}+ ariaLabel="Message Claude"+ onEmptyChange={onEmptyChange}+ onSubmit={() => {}}+ />,+ );+ ref.current?.appendText('line one\nline two');+ expect(ref.current?.getContent().instruction).toBe('line one\nline two');+ // The send-enabled state must flip — `setContent` alone won't announce it.+ expect(onEmptyChange).toHaveBeenLastCalledWith(false);+ });++ test('appendText joins after existing content with a blank line, chips intact', () => {+ const ref = createRef<ComposerMentionInputHandle>();+ render(+ <ComposerMentionInput+ ref={ref}+ ariaLabel="Message Claude"+ onEmptyChange={() => {}}+ onSubmit={() => {}}+ initialDoc={+ paragraph(+ { type: 'text', text: 'look at ' },+ mentionNode('notes.md', 'Notes'),+ ) as JSONContent+ }+ />,+ );+ ref.current?.appendText('rescued queue text');+ const { instruction, mentions } = ref.current?.getContent() ?? {+ instruction: '',+ mentions: [],+ };+ // The chip survives as a chip (still on the mentions list), not flattened+ // prose — the property that makes append safe mid-draft.+ expect(instruction).toBe('look at @notes.md\n\nrescued queue text');+ expect(mentions).toEqual(['notes.md']);+ });++ test('disabled turns off editing but keeps content, placeholder, and the handle', () => {+ const ref = createRef<ComposerMentionInputHandle>();+ const { rerender } = render(+ <ComposerMentionInput+ ref={ref}+ ariaLabel="Message Claude"+ placeholder="Resuming the chat"+ onEmptyChange={() => {}}+ onSubmit={() => {}}+ disabled+ />,+ );+ const box = screen.getByRole('textbox', { name: 'Message Claude' });+ expect(box.getAttribute('contenteditable')).toBe('false');+ // `contenteditable=false` is invisible to AT on a role="textbox" element —+ // the disabled state must be announced, as the native `<textarea disabled>`+ // this replaces did natively.+ expect(box.getAttribute('aria-disabled')).toBe('true');+ // A disabled native textarea still shows its placeholder; so must this.+ expect(box.querySelector('[data-placeholder="Resuming the chat"]')).not.toBeNull();+ // The handle still writes (the host seeds drafts regardless of state).+ ref.current?.appendText('kept');+ expect(ref.current?.getContent().instruction).toBe('kept');++ rerender(+ <ComposerMentionInput+ ref={ref}+ ariaLabel="Message Claude"+ placeholder="Resuming the chat"+ onEmptyChange={() => {}}+ onSubmit={() => {}}+ />,+ );+ expect(box.getAttribute('contenteditable')).toBe('true');+ expect(box.getAttribute('aria-disabled')).toBeNull();+ expect(ref.current?.getContent().instruction).toBe('kept');+ });++ test('mounting emits no onContentChange — only an edit mirrors into the draft', () => {+ // The editable-sync effect must not push a synthetic update on mount:+ // every composer runs it, and the Ask AI hosts mirror onContentChange into+ // the persisted draft store — a mount-time emission is a redundant write on+ // every doc navigation.+ const onContentChange = vi.fn(() => {});+ render(+ <ComposerMentionInput+ ariaLabel="Ask AI"+ onEmptyChange={() => {}}+ onContentChange={onContentChange}+ onSubmit={() => {}}+ />,+ );+ expect(onContentChange).not.toHaveBeenCalled();+ });+test('a placeholder adds the data-placeholder hint while the field is empty', () => {render(<ComposerMentionInput@@ -334,12 +439,6 @@ describe('ComposerMentionInput — Enter defers to the @-mention popup', () => {fetchSpy.mockRestore();});- function getComposerEditor(box: HTMLElement): Editor {- // TipTap's EditorContent tags the contenteditable host node with the live- // editor instance; the textbox role resolves to that same node.- return (box as unknown as { editor: Editor }).editor;- }-function isSuggestionActive(editor: Editor): boolean {const state = composerMentionSuggestionKey.getState(editor.state) as| { active: boolean }@@ -395,4 +494,69 @@ describe('ComposerMentionInput — Enter defers to the @-mention popup', () => {fireEvent.keyDown(box, { key: 'Enter' });expect(onSubmit).toHaveBeenCalledTimes(1);});++ test('Escape defers to the open @-popup and does not fire onEscape', () => {+ // Load-bearing since the agent-thread composer wired onEscape to+ // turn-cancellation: while the popup is open, Escape closes IT (the+ // suggestion plugin owns the key) — the host must not hear the press, or+ // dismissing the picker would stop a running agent turn.+ const onEscape = vi.fn(() => {});+ render(+ <ComposerMentionInput+ ariaLabel="Ask AI"+ onEmptyChange={() => {}}+ onSubmit={() => {}}+ onEscape={onEscape}+ />,+ );+ const box = screen.getByRole('textbox', { name: 'Ask AI' });+ const editor = getComposerEditor(box);++ editor.commands.insertContent('@foo');+ expect(isSuggestionActive(editor)).toBe(true);+ fireEvent.keyDown(box, { key: 'Escape' });+ expect(onEscape).toHaveBeenCalledTimes(0);++ // Popup gone → Escape is the host's again.+ editor.commands.clearContent(true);+ expect(isSuggestionActive(editor)).toBe(false);+ fireEvent.keyDown(box, { key: 'Escape' });+ expect(onEscape).toHaveBeenCalledTimes(1);+ });+});++/**+ * The IME-composition guard, against the real editor: Enter mid-composition is+ * the input method committing characters, never a send. Both halves of the+ * guard are exercised — the event's own `isComposing` flag and ProseMirror's+ * `view.composing` (they can disagree; the keydown that ends a composition+ * clears the event flag while the view still reports composing). The+ * ThreadView suites' textarea double reimplements only the event half, so this+ * is the coverage that pins production.+ */+describe('ComposerMentionInput — Enter during IME composition', () => {+ test('neither guard half lets a composition Enter submit; a plain Enter does', () => {+ const onSubmit = vi.fn(() => {});+ render(+ <ComposerMentionInput ariaLabel="Ask AI" onEmptyChange={() => {}} onSubmit={onSubmit} />,+ );+ const box = screen.getByRole('textbox', { name: 'Ask AI' });+ const editor = getComposerEditor(box);++ fireEvent.keyDown(box, { key: 'Enter', isComposing: true });+ expect(onSubmit).toHaveBeenCalledTimes(0);++ // Same public-getter override the gfm-autolink suite uses — the view's+ // `composing` is a getter, so define over it rather than assign.+ Object.defineProperty(editor.view, 'composing', { get: () => true, configurable: true });+ try {+ fireEvent.keyDown(box, { key: 'Enter' });+ expect(onSubmit).toHaveBeenCalledTimes(0);+ } finally {+ Reflect.deleteProperty(editor.view, 'composing');+ }++ fireEvent.keyDown(box, { key: 'Enter' });+ expect(onSubmit).toHaveBeenCalledTimes(1);+ });});diff --git a/packages/app/src/editor/ComposerMentionInput.tsx b/packages/app/src/editor/ComposerMentionInput.tsxindex 840aea610..5d4a1b8ab 100644--- a/packages/app/src/editor/ComposerMentionInput.tsx+++ b/packages/app/src/editor/ComposerMentionInput.tsx@@ -1,14 +1,20 @@/**- * The bottom "Ask AI" composer's rich text input: a lightweight TipTap editor- * with `@`-mention chips. It is deliberately NOT the document editor — it never- * registers in the active-editor registry (that registry stays owned by the- * real per-doc editors, so `getEditorForDoc` keeps returning the document the- * user is editing, which the selection-passage feature reads from).+ * THE shared AI prompt-composer input — one rich text field (a lightweight+ * TipTap editor with `@`-mention chips) rendered by every prompt surface: the+ * bottom "Ask AI" composer, the empty-state create composer, the inline comment+ * composer, and the agent-thread composer. New composer-wide capabilities+ * (attachment paste/drop, `/` slash commands) land HERE, once, gated per host —+ * never as a per-surface fork. It is deliberately NOT the document editor — it+ * never registers in the active-editor registry (that registry stays owned by+ * the real per-doc editors, so `getEditorForDoc` keeps returning the document+ * the user is editing, which the selection-passage feature reads from).** The host owns submit/clear/focus via an imperative handle; this component owns* only the editor lifecycle and the Enter-submits / Shift+Enter-newline /- * Escape-blurs key handling. Emptiness (no prose, no chips) is pushed up via- * `onEmptyChange` so the host can drive the placeholder + send-enabled state.+ * Escape-blurs key handling. The Enter path guards IME composition, so a CJK+ * commit-Enter never fires a premature submit on any surface. Emptiness (no+ * prose, no chips) is pushed up via `onEmptyChange` so the host can drive the+ * placeholder + send-enabled state.*/import type { JSONContent } from '@tiptap/core';@@ -52,11 +58,27 @@ export interface ComposerMentionInputHandle {* starter brief the user can then edit. Mirrors the resulting doc into the* shared draft via `onContentChange`. */setText: (text: string) => void;+ /** Append plain text after the existing content, separated by a blank line+ * (an empty field just takes the text). Newlines in `text` become paragraph+ * breaks. Existing content — chips included — is left untouched, which is+ * why hosts that seed a composer mid-draft (a staged selection passage, a+ * cancelled turn's rescued queue) use this rather than read-modify-`setText`,+ * which would flatten chips to literal `@path` text. */+ appendText: (text: string) => void;/** The dispatch payload: instruction prose (chips inline as `@path`) + the* ordered, de-duplicated `@path` mention list. */getContent: () => { instruction: string; mentions: string[] };}+/** Map plain text onto the composer schema: one paragraph per line, blank+ * lines as empty paragraphs (both serialize back to `\n`). */+function textToParagraphs(text: string): JSONContent[] {+ return text.split('\n').map((line) => ({+ type: 'paragraph',+ content: line === '' ? [] : [{ type: 'text', text: line }],+ }));+}+export function ComposerMentionInput({ref,ariaLabel,@@ -68,6 +90,8 @@ export function ComposerMentionInput({className,placeholder,initialDoc,+ disabled = false,+ testId,}: {ref?: Ref<ComposerMentionInputHandle>;ariaLabel: string;@@ -110,6 +134,15 @@ export function ComposerMentionInput({* not literal `@path` text. Applied once at editor creation; later draft* changes flow through the store, not this prop. */initialDoc?: JSONContent;+ /** Make the field read-only (the agent-thread composer while an archived+ * thread resumes, or once its agent is gone for good). Content — a draft+ * written before the flip — is kept, the placeholder stays visible, and the+ * imperative handle still works; only user editing is off. */+ disabled?: boolean;+ /** `data-testid` for the contenteditable element itself, so tests and the+ * sessions dock's focus routing address the real textbox. Applied once at+ * editor creation (it never changes). */+ testId?: string;}) {// Refs carry the latest callbacks into the editor's once-created handlers so// they never go stale, without re-creating the editor (and writing the refs in@@ -131,11 +164,13 @@ export function ComposerMentionInput({extensions: composerMentionExtensions({ placeholder }),content: initialDoc ?? undefined,immediatelyRender: true,+ editable: !disabled,editorProps: {attributes: {role: 'textbox','aria-label': ariaLabel,'aria-multiline': 'true',+ ...(testId !== undefined ? { 'data-testid': testId } : {}),// `composer-prosemirror` resets the document-editor `.ProseMirror`// sizing (200px min-height, the drag-handle margin/padding) so the// composer rests at a single slim line — see globals.css.@@ -210,6 +245,27 @@ export function ComposerMentionInput({view.dispatch(editor.state.tr.setMeta('addToHistory', false));}, [editor, placeholder, ariaLabel]);+ // `useEditor`'s `editable` option only seeds creation — later flips (an+ // archived thread's resume settling, its agent exiting) have to reach the+ // live instance.+ useEffect(() => {+ if (!editor || editor.isDestroyed) return;+ const editable = !disabled;+ // Guarded + no `emitUpdate`: editability is not content. Unguarded,+ // `setEditable` defaults to emitting `update`, which pushed a synthetic+ // onUpdate through every composer on mount — a redundant draft-store write+ // for the hosts that mirror content out.+ if (editor.isEditable !== editable) editor.setEditable(editable, false);+ // `contenteditable=false` alone tells assistive tech nothing — the element+ // keeps `role="textbox"`, so without this a disabled field still reads as+ // editable (the native `<textarea disabled>` it replaces carried the state+ // natively). Same non-throwing `editorView` reach as the locale repaint.+ const view = (editor as unknown as { editorView?: ComposerEditorView }).editorView;+ if (!view) return;+ if (disabled) view.dom.setAttribute('aria-disabled', 'true');+ else view.dom.removeAttribute('aria-disabled');+ }, [editor, disabled]);+// Seed the host's empty-state from the initial draft text. `useEditor` does// not fire `onUpdate` for the `content` seed, so without this a restored draft// would leave the placeholder showing + Send disabled until the first@@ -247,6 +303,25 @@ export function ComposerMentionInput({onContentChangeRef.current?.(editor.getJSON());onMentionsChangeRef.current?.(serializeComposerContent(editor).mentions);},+ appendText: (text: string) => {+ if (!editor || text === '') return;+ if (isComposerEmpty(editor)) {+ editor.commands.setContent(textToParagraphs(text));+ } else {+ // A blank-line separator between what was there and what arrived —+ // the serialized instruction reads `existing\n\nappended`.+ editor.commands.insertContentAt(editor.state.doc.content.size, [+ { type: 'paragraph', content: [] },+ ...textToParagraphs(text),+ ]);+ }+ // Same mirroring rationale as `setText`; `onEmptyChange` too, because+ // an append into an empty field flips the host's send-enabled state+ // and `setContent` won't reliably announce it.+ onEmptyChangeRef.current(isComposerEmpty(editor));+ onContentChangeRef.current?.(editor.getJSON());+ onMentionsChangeRef.current?.(serializeComposerContent(editor).mentions);+ },getContent: () =>editor ? serializeComposerContent(editor) : { instruction: '', mentions: [] },}),diff --git a/packages/app/src/editor/composer-mention/composer-mention.ts b/packages/app/src/editor/composer-mention/composer-mention.tsindex c5aeda222..634a8aa07 100644--- a/packages/app/src/editor/composer-mention/composer-mention.ts+++ b/packages/app/src/editor/composer-mention/composer-mention.ts@@ -243,8 +243,19 @@ export function composerMentionExtensions(options?: { placeholder?: string }) {ComposerMention,// Seeds the mount-time value only. Extensions are built once, so the host// re-points `options.placeholder` on this instance when the interface- // language changes — see `ComposerMentionInput`.- ...(options?.placeholder ? [Placeholder.configure({ placeholder: options.placeholder })] : []),+ // language changes — see `ComposerMentionInput`. `showOnlyWhenEditable:+ // false` because a disabled composer keeps its placeholder (the agent-thread+ // composer disables while an archived thread resumes, and the placeholder is+ // what says "Resuming the chat" — matching a native textarea, which shows its+ // placeholder while disabled).+ ...(options?.placeholder+ ? [+ Placeholder.configure({+ placeholder: options.placeholder,+ showOnlyWhenEditable: false,+ }),+ ]+ : []),];}