Beautiful, AI-native markdown IDE and LLM wiki
TypeScript 2nd-brainagent-skillsclaudecodexcompany-braindocsknowledge-knowledge-baseknowledge-managementllmllm-wikillm-wiki-karpathymarkdownmarkdown-editormdmdxnotespkmsecond-brainskills
feat(ok): open the @ picker on the doc you are editing (PRD-8029) (#4797)
Abrahamb5a49d414b30
diff --git a/.changeset/prd-8029-mention-picker-recency.md b/.changeset/prd-8029-mention-picker-recency.mdnew file mode 100644index 000000000..4565919b8--- /dev/null+++ b/.changeset/prd-8029-mention-picker-recency.md@@ -0,0 +1,5 @@+---+"@inkeep/open-knowledge": patch+---++`@` pickers now open with the document you are on first, ahead of the rest of the workspace. In an agent conversation the picker also lists what you already attached earlier in that chat.diff --git a/docs/content/features/editor.mdx b/docs/content/features/editor.mdxindex 826301c7b..3696000fd 100644--- a/docs/content/features/editor.mdx+++ b/docs/content/features/editor.mdx@@ -122,7 +122,7 @@ Surfaces with their own specialized right-click menus — asset and wiki-link ch## Ask AI-An **Ask AI** composer is docked at the bottom of the editor — in the desktop app and in a regular browser — whenever a doc or folder view is open. It's a slim, single-line entry field that expands as you type to accept a fuller prompt (and `@`-mentions); in the desktop app, `Cmd+L` opens and focuses it. Type an instruction — "condense this doc", "research X", "make a spec from this user story" — and press Enter to hand it to an agent. `Shift+Enter` inserts a newline; the field clears once the prompt is sent.+An **Ask AI** composer is docked at the bottom of the editor — in the desktop app and in a regular browser — whenever a doc or folder view is open. It's a slim, single-line entry field that expands as you type to accept a fuller prompt (and `@`-mentions); in the desktop app, `Cmd+L` opens and focuses it. Its `@` picker opens with the document you're on first, ahead of the rest of the workspace. The Agents panel's own composer goes one step further and also lists what you've already attached earlier in that conversation. Type an instruction — "condense this doc", "research X", "make a spec from this user story" — and press Enter to hand it to an agent. `Shift+Enter` inserts a newline; the field clears once the prompt is sent.It's the primary in-editor way to hand work to an agent, and the freetext companion to the menu-driven [Open with AI](#open-with-ai) (whole file / folder / project). Submitting dispatches the typed prompt to your **default agent**, scoped to the current doc (or, in a folder view, the folder), which the agent receives as an `@`-mention. Until you pick something else, that default is an **In app** agent, so the conversation stays inside OpenKnowledge; it falls back to a **Terminal** CLI — preferring one detected on this machine — and then to an **External app**, when no higher option is available here. The agent picker beside the field overrides the default per send, listing In app agents first, then the [Terminal](#open-with-ai) CLIs available on this machine, then the external agent apps detected here. Whatever you pick is remembered on that machine and stays your default until you change it or turn it off in **Agent connections**. Success and failure use the same handoff toast as Open with AI.diff --git a/packages/app/src/comments/CommentSelectionAffordance.tsx b/packages/app/src/comments/CommentSelectionAffordance.tsxindex edda035a9..0786175a7 100644--- a/packages/app/src/comments/CommentSelectionAffordance.tsx+++ b/packages/app/src/comments/CommentSelectionAffordance.tsx@@ -179,6 +179,7 @@ export function CommentSelectionAffordance({<ComposerMentionInputref={inputRef}ariaLabel={t`Add a comment`}+ mentionRecency={{ currentDocName: docName, recentPaths: [] }}placeholder={t`Add a comment`}attachmentDrop={{ kind: 'refuse' }}onEmptyChange={setEmpty}diff --git a/packages/app/src/comments/ThreadCard.tsx b/packages/app/src/comments/ThreadCard.tsxindex cf09eedc7..699d2e442 100644--- a/packages/app/src/comments/ThreadCard.tsx+++ b/packages/app/src/comments/ThreadCard.tsx@@ -320,6 +320,7 @@ export function ThreadCard({<div className="flex flex-col gap-1.5"><ComposerMentionInputref={editFieldRef}+ mentionRecency={{ currentDocName: thread.docName, recentPaths: [] }}ariaLabel={t`Edit this comment`}placeholder={t`Edit this comment`}attachmentDrop={{ kind: 'refuse' }}diff --git a/packages/app/src/comments/comment-composer-submit.dom.test.tsx b/packages/app/src/comments/comment-composer-submit.dom.test.tsxindex f06b60a76..2cdc172a0 100644--- a/packages/app/src/comments/comment-composer-submit.dom.test.tsx+++ b/packages/app/src/comments/comment-composer-submit.dom.test.tsx@@ -2,6 +2,7 @@ import * as actualLinguiMacro from '@lingui/react/macro';import { act, cleanup, fireEvent, render, screen } from '@testing-library/react';import type { ReactNode } from 'react';import { afterEach, describe, expect, test, vi } from 'vitest';+import { mentionRecencyAttribute } from '@/components/acp/composer-mention-input.test-helper';vi.doMock('@lingui/react/macro', () => ({...actualLinguiMacro,@@ -39,16 +40,19 @@ vi.doMock('@/editor/ComposerMentionInput', () => ({onEmptyChange,onSubmit,onEscape,+ mentionRecency,}: {ref?: { current: unknown };placeholder?: string;onEmptyChange: (empty: boolean) => void;onSubmit: () => void;onEscape?: () => void;+ mentionRecency?: { currentDocName: string | null; recentPaths: readonly string[] };}) => {return (<textareaplaceholder={placeholder}+ data-mention-recency={mentionRecencyAttribute(mentionRecency)}ref={(el) => {if (ref === undefined || ref === null || el === null) return;ref.current = {@@ -248,3 +252,15 @@ describe('the comment composer', () => {popup.remove();});});++describe('what the comment @ picker is told to list first', () => {+ test('the affordance pins the doc it is anchored to', async () => {+ const field = await openComposer();++ const handed = field.getAttribute('data-mention-recency');+ expect(JSON.parse(handed ?? 'null')).toEqual({+ currentDocName: 'recipes/stir-fry',+ recentPaths: [],+ });+ });+});diff --git a/packages/app/src/comments/thread-edit-save.dom.test.tsx b/packages/app/src/comments/thread-edit-save.dom.test.tsxindex a3ebff33a..d863e0113 100644--- a/packages/app/src/comments/thread-edit-save.dom.test.tsx+++ b/packages/app/src/comments/thread-edit-save.dom.test.tsx@@ -147,3 +147,17 @@ describe('the click-away commit', () => {expect(editComment).not.toHaveBeenCalled();});});++describe('what the comment edit @ picker is told to list first', () => {+ test('the card pins the doc its thread belongs to', () => {+ renderEditing();++ const handed = document+ .querySelector('textarea[data-mention-recency]')+ ?.getAttribute('data-mention-recency');+ expect(JSON.parse(handed ?? 'null')).toEqual({+ currentDocName: 'recipes/stir-fry',+ recentPaths: [],+ });+ });+});diff --git a/packages/app/src/components/BottomComposer.dom.test.tsx b/packages/app/src/components/BottomComposer.dom.test.tsxindex f123f670d..7d72c9626 100644--- a/packages/app/src/components/BottomComposer.dom.test.tsx+++ b/packages/app/src/components/BottomComposer.dom.test.tsx@@ -5,6 +5,7 @@ import userEvent from '@testing-library/user-event';import type { Editor } from '@tiptap/core';import { type ReactNode, type Ref, useEffect, useImperativeHandle, useRef } from 'react';import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';+import { mentionRecencyAttribute } from '@/components/acp/composer-mention-input.test-helper';import type { ComposerMentionInputHandle } from '@/editor/ComposerMentionInput';import { FULL_PAGE_CM_HOST_SELECTORS, type FullPageCmHost } from '@/editor/document-scrollports';import type { EditorSurface } from '@/editor/selection-stats';@@ -80,6 +81,7 @@ vi.doMock('@/editor/ComposerMentionInput', () => ({onMentionsChange,onSubmit,className,+ mentionRecency,}: {ref?: Ref<ComposerMentionInputHandle>;ariaLabel: string;@@ -87,6 +89,7 @@ vi.doMock('@/editor/ComposerMentionInput', () => ({onMentionsChange?: (mentions: string[]) => void;onSubmit: () => void;className?: string;+ mentionRecency?: { currentDocName: string | null; recentPaths: readonly string[] };}) => {const localRef = useRef<HTMLTextAreaElement>(null);useEffect(() => {@@ -111,6 +114,7 @@ vi.doMock('@/editor/ComposerMentionInput', () => ({ref={localRef}aria-label={ariaLabel}className={className}+ data-mention-recency={mentionRecencyAttribute(mentionRecency)}onChange={(event) => onEmptyChange(event.target.value.trim() === '')}onKeyDown={(event) => {if (event.key === 'Escape') {@@ -2068,3 +2072,25 @@ describe('BottomComposer (end-of-document scroll compensation)', () => {).toBe(afterBackstop);});});++describe('what the Ask AI @ picker is told to list first', () => {+ test('a doc view hands the picker the open doc and no chat attachments', async () => {+ await renderComposer('foo');++ const handed = screen+ .getByRole('textbox', { name: 'Ask AI' })+ .getAttribute('data-mention-recency');+ expect(JSON.parse(handed ?? 'null')).toEqual({ currentDocName: 'foo', recentPaths: [] });+ });++ test('a folder view has no doc to pin', async () => {+ const { BottomComposer } = await import('./BottomComposer');+ const { TooltipProvider } = await import('@/components/ui/tooltip');+ render(<BottomComposer folderPath="specs" />, { wrapper: TooltipProvider });++ const handed = screen+ .getByRole('textbox', { name: 'Ask AI' })+ .getAttribute('data-mention-recency');+ expect(JSON.parse(handed ?? 'null')).toEqual({ currentDocName: null, recentPaths: [] });+ });+});diff --git a/packages/app/src/components/BottomComposer.tsx b/packages/app/src/components/BottomComposer.tsxindex a94b4dc7d..93f96d2f7 100644--- a/packages/app/src/components/BottomComposer.tsx+++ b/packages/app/src/components/BottomComposer.tsx@@ -841,6 +841,7 @@ export function BottomComposer({<ComposerMentionInputref={inputRef}ariaLabel={t`Ask AI`}+ mentionRecency={{ currentDocName: activeDocOrNull, recentPaths: [] }}attachmentDrop={attachmentDrop}onEmptyChange={setIsEmpty}onContentChange={(doc) => {diff --git a/packages/app/src/components/acp/ThreadView.dom.test.tsx b/packages/app/src/components/acp/ThreadView.dom.test.tsxindex e3808aa49..e450b75c2 100644--- a/packages/app/src/components/acp/ThreadView.dom.test.tsx+++ b/packages/app/src/components/acp/ThreadView.dom.test.tsx@@ -106,8 +106,9 @@ vi.doMock('sonner', () => ({toast: { error: toastError, success: vi.fn(), info: vi.fn() },}));+let activeDocName: string | null = null;vi.doMock('@/editor/DocumentContext', () => ({- useDocumentContext: () => ({ systemProvider: null }),+ useDocumentContext: () => ({ systemProvider: null, activeDocName }),}));vi.doMock('@/lib/use-workspace', () => ({@@ -5187,3 +5188,44 @@ describe('ThreadView context window', () => {expect(screen.queryByTestId('agent-thread-context-window-872000')).toBeNull();});});++describe('ThreadView hands the composer what to list first', () => {+ test('the open doc and the paths this chat attached, newest first', () => {+ activeDocName = 'notes/today';+ try {+ model = makeModel({+ turnActive: false,+ items: [+ {+ kind: 'message',+ role: 'user',+ text: 'first',+ messageId: 'm1',+ attachments: [{ kind: 'file', path: 'specs/a.md', name: 'a' }],+ },+ {+ kind: 'message',+ role: 'user',+ text: 'second',+ messageId: 'm2',+ attachments: [+ { kind: 'folder', path: 'plans', name: 'plans' },+ { kind: 'image', data: 'AAAA', mimeType: 'image/png', name: 'shot.png' },+ ],+ },+ ],+ });+ render(<ThreadView info={makeInfo({ status: 'ready' })} />);++ const handed = screen+ .getByTestId('agent-thread-composer')+ .getAttribute('data-mention-recency');+ expect(JSON.parse(handed ?? 'null')).toEqual({+ currentDocName: 'notes/today',+ recentPaths: ['plans', 'specs/a.md'],+ });+ } finally {+ activeDocName = null;+ }+ });+});diff --git a/packages/app/src/components/acp/ThreadView.tsx b/packages/app/src/components/acp/ThreadView.tsxindex 9951de9de..a580d4e20 100644--- a/packages/app/src/components/acp/ThreadView.tsx+++ b/packages/app/src/components/acp/ThreadView.tsx@@ -106,6 +106,7 @@ import {ComposerMentionInput,type ComposerMentionInputHandle,} from '@/editor/ComposerMentionInput';+import type { MentionRecency } from '@/editor/composer-mention/composer-mention';import { useDocumentContext } from '@/editor/DocumentContext';import { agentDisplayName } from '@/lib/acp/agent-display';import {@@ -132,6 +133,7 @@ import { contextChoicesForModel, useModelCandidates } from '@/lib/acp/model-candimport { formatShellCommand, revealHiddenCharacters } from '@/lib/acp/shell-command-format';import { parseSignInOutput, shortenUrl } from '@/lib/acp/sign-in-output';import { renderTerminalText } from '@/lib/acp/terminal-text';+import { threadAttachmentPaths } from '@/lib/acp/thread-attachment-paths';import {getAgentThreadClient,ThreadContextWindowError,@@ -176,6 +178,7 @@ import {loadFollowFilePref,saveFollowFilePref,} from './follow-file';+import { MentionRecencyContext } from './mention-recency-context';import { type ImagePreview, ImagePreviewContext, PendingImageStrip } from './PendingImageStrip';import { PlanChecklist } from './PlanChecklist';import { appendPresenceWrite, latestAgentWrite, type PresenceWrite } from './presence-follow';@@ -525,7 +528,7 @@ export function ThreadView({const resolverReady = docPathResolver !== null;const transcriptFollowTarget = model !== null ? latestFollowTarget(model.items, workspace) : null;- const { systemProvider } = useDocumentContext();+ const { systemProvider, activeDocName } = useDocumentContext();const [presenceWrites, setPresenceWrites] = useState<ReadonlyArray<PresenceWrite>>([]);useEffect(() => {if (!turnActive) {@@ -966,6 +969,10 @@ export function ThreadView({: '';const items = visibleItems;+ const mentionRecency: MentionRecency = {+ currentDocName: activeDocName,+ recentPaths: threadAttachmentPaths(items),+ };let authPrompt: ThreadFailureDetail | null = null;if (awaitingSignIn && !archived) {for (let index = items.length - 1; index >= 0; index -= 1) {@@ -978,356 +985,359 @@ export function ThreadView({}return (- <ImagePreviewContext.Provider value={openImagePreview}>- <ImagePreviewDialog- preview={imagePreview}- onOpenChange={(open) => !open && setImagePreview(null)}- />- {/* biome-ignore lint/a11y/noStaticElementInteractions: drop-target — keyboard/AT users have the + picker button in the composer; drop is a pointer-only affordance. */}- <div- className="relative flex min-h-0 flex-1 flex-col text-gray-800 dark:text-gray-200"- data-agent-thread-root=""- onDragEnter={(event) => {- if (isExternalFileDrag(event)) {- event.preventDefault();- setDragActive(true);- }- }}- onDragOver={(event) => {- if (isExternalFileDrag(event)) {+ <MentionRecencyContext value={mentionRecency}>+ <ImagePreviewContext.Provider value={openImagePreview}>+ <ImagePreviewDialog+ preview={imagePreview}+ onOpenChange={(open) => !open && setImagePreview(null)}+ />+ {/* biome-ignore lint/a11y/noStaticElementInteractions: drop-target — keyboard/AT users have the + picker button in the composer; drop is a pointer-only affordance. */}+ <div+ className="relative flex min-h-0 flex-1 flex-col text-gray-800 dark:text-gray-200"+ data-agent-thread-root=""+ onDragEnter={(event) => {+ if (isExternalFileDrag(event)) {+ event.preventDefault();+ setDragActive(true);+ }+ }}+ onDragOver={(event) => {+ if (isExternalFileDrag(event)) {+ event.preventDefault();+ event.dataTransfer.dropEffect = 'copy';+ setDragActive(true);+ }+ }}+ onDragLeave={(event) => {+ const next = event.relatedTarget;+ if (next instanceof Node && event.currentTarget.contains(next)) return;+ setDragActive(false);+ }}+ onDrop={(event) => {+ if (!isExternalFileDrag(event)) return;event.preventDefault();- event.dataTransfer.dropEffect = 'copy';- setDragActive(true);- }- }}- onDragLeave={(event) => {- const next = event.relatedTarget;- if (next instanceof Node && event.currentTarget.contains(next)) return;- setDragActive(false);- }}- onDrop={(event) => {- if (!isExternalFileDrag(event)) return;- event.preventDefault();- setDragActive(false);- const files = collectAllFiles(event.dataTransfer);- if (files.length === 0) {- dropNoticeIdRef.current += 1;- setDropNotice({- text: t`Folders and empty files can't be attached — drop the files themselves.`,- id: dropNoticeIdRef.current,- });- return;- }- void ingestFiles(files);- }}- >- <DocPathResolverReadyContext value={resolverReady}>- <ThreadHeader info={info} followFile={followFile} onToggleFollow={toggleFollow} />- {}- <AgentNoticeAnnouncer- notices={agentNotices}- agentName={agentName}- replayThroughSeq={state?.replayThroughSeq ?? Number.POSITIVE_INFINITY}- />- {model !== null && model.plan.length > 0 ? (- <PlanChecklist- plan={model.plan}- approval={- canPrompt && !archived && !planApprovalPending- ? {- onApprove: () => {- setPlanApprovalPending(true);- void sendText('Approve. Please proceed with the plan.');- },- onAskChanges: () => {- const prefix = t`In the plan above, please `;- const composer = composerRef.current;- if (- composer !== null &&- !composer.getContent().instruction.endsWith(prefix)- ) {- composer.appendText(prefix);- }- composer?.focusEnd();- },- onReject: () => {- setPlanApprovalPending(true);- void sendText('Reject. Please stop and do not proceed with this plan.');- },- }- : undefined- }+ setDragActive(false);+ const files = collectAllFiles(event.dataTransfer);+ if (files.length === 0) {+ dropNoticeIdRef.current += 1;+ setDropNotice({+ text: t`Folders and empty files can't be attached — drop the files themselves.`,+ id: dropNoticeIdRef.current,+ });+ return;+ }+ void ingestFiles(files);+ }}+ >+ <DocPathResolverReadyContext value={resolverReady}>+ <ThreadHeader info={info} followFile={followFile} onToggleFollow={toggleFollow} />+ {}+ <AgentNoticeAnnouncer+ notices={agentNotices}+ agentName={agentName}+ replayThroughSeq={state?.replayThroughSeq ?? Number.POSITIVE_INFINITY}/>- ) : null}- {authPrompt !== null || model === null || visibleItems.length === 0 ? (- <div- className="min-h-0 flex-1 overflow-y-auto px-3 py-2 subtle-scrollbar scroll-fade-mask"- data-testid="agent-thread-transcript"- >- {authPrompt !== null ? (- <div className="flex min-h-full items-center justify-center">- <ThreadAuthPrompt- failure={authPrompt}- offer={threadAuthOffer({- authMethods: authPrompt.authMethods ?? [],- agentName,- terminalCli,- })}+ {model !== null && model.plan.length > 0 ? (+ <PlanChecklist+ plan={model.plan}+ approval={+ canPrompt && !archived && !planApprovalPending+ ? {+ onApprove: () => {+ setPlanApprovalPending(true);+ void sendText('Approve. Please proceed with the plan.');+ },+ onAskChanges: () => {+ const prefix = t`In the plan above, please `;+ const composer = composerRef.current;+ if (+ composer !== null &&+ !composer.getContent().instruction.endsWith(prefix)+ ) {+ composer.appendText(prefix);+ }+ composer?.focusEnd();+ },+ onReject: () => {+ setPlanApprovalPending(true);+ void sendText('Reject. Please stop and do not proceed with this plan.');+ },+ }+ : undefined+ }+ />+ ) : null}+ {authPrompt !== null || model === null || visibleItems.length === 0 ? (+ <div+ className="min-h-0 flex-1 overflow-y-auto px-3 py-2 subtle-scrollbar scroll-fade-mask"+ data-testid="agent-thread-transcript"+ >+ {authPrompt !== null ? (+ <div className="flex min-h-full items-center justify-center">+ <ThreadAuthPrompt+ failure={authPrompt}+ offer={threadAuthOffer({+ authMethods: authPrompt.authMethods ?? [],+ agentName,+ terminalCli,+ })}+ agent={info.agent}+ agentName={agentName}+ signingIn={signingIn}+ signInOutput={info.signInOutput}+ showRetry={canRetry}+ retryPending={retryPending}+ onRetry={retryThread}+ onAuthAction={runAuthAction}+ runningAuthAction={runningAuthAction}+ onAuthenticate={authenticateThread}+ />+ </div>+ ) : (+ <ThreadEmptyState+ status={status}+ displayedStartStatus={displayedStartStatus}+ archived={archived}agent={info.agent}- agentName={agentName}- signingIn={signingIn}- signInOutput={info.signInOutput}- showRetry={canRetry}- retryPending={retryPending}- onRetry={retryThread}+ authOffer={authOffer}onAuthAction={runAuthAction}runningAuthAction={runningAuthAction}- onAuthenticate={authenticateThread}/>- </div>- ) : (- <ThreadEmptyState- status={status}- displayedStartStatus={displayedStartStatus}- archived={archived}- agent={info.agent}- authOffer={authOffer}- onAuthAction={runAuthAction}- runningAuthAction={runningAuthAction}- />- )}- </div>- ) : (- <MessageScrollerProvider autoScroll defaultScrollPosition="last-anchor">- <ScrollToEndBridge apiRef={scrollApiRef} />- <MessageScroller className="min-h-0 flex-1">- <MessageScrollerViewport- aria-label={t`Agent transcript`}- className="px-3 py-2 subtle-scrollbar scroll-fade-mask"- data-testid="agent-thread-transcript"- >- <MessageScrollerContent className="gap-2 [&>[data-tool-call]+[data-tool-call]]:-mt-1">- {visibleEntries.map(({ item, modelIndex }, index) => {- const id = transcriptItemId(item, modelIndex);- const group = toolRunByIndex.get(index);- const collapsed = group !== undefined && !expandedToolRuns.has(group.runId);- if (collapsed && !group.isHead) return null;- if (collapsed && group.isHead) {- const runId = group.runId;+ )}+ </div>+ ) : (+ <MessageScrollerProvider autoScroll defaultScrollPosition="last-anchor">+ <ScrollToEndBridge apiRef={scrollApiRef} />+ <MessageScroller className="min-h-0 flex-1">+ <MessageScrollerViewport+ aria-label={t`Agent transcript`}+ className="px-3 py-2 subtle-scrollbar scroll-fade-mask"+ data-testid="agent-thread-transcript"+ >+ <MessageScrollerContent className="gap-2 [&>[data-tool-call]+[data-tool-call]]:-mt-1">+ {visibleEntries.map(({ item, modelIndex }, index) => {+ const id = transcriptItemId(item, modelIndex);+ const group = toolRunByIndex.get(index);+ const collapsed = group !== undefined && !expandedToolRuns.has(group.runId);+ if (collapsed && !group.isHead) return null;+ if (collapsed && group.isHead) {+ const runId = group.runId;+ return (+ <MessageScrollerItem+ key={id}+ messageId={id}+ className="flex flex-col"+ data-tool-call=""+ >+ <ToolCallGroupRow+ calls={visibleItems+ .slice(group.run.start, group.run.start + group.run.size)+ .filter(+ (candidate): candidate is RenderedToolCall =>+ candidate.kind === 'tool_call',+ )}+ onExpand={() =>+ setExpandedToolRuns((previous) => new Set(previous).add(runId))+ }+ />+ </MessageScrollerItem>+ );+ }return (<MessageScrollerItemkey={id}messageId={id}className="flex flex-col"- data-tool-call=""+ scrollAnchor={item.kind === 'message' && item.role === 'user'}+ data-tool-call={item.kind === 'tool_call' ? '' : undefined}>- <ToolCallGroupRow- calls={visibleItems- .slice(group.run.start, group.run.start + group.run.size)- .filter(- (candidate): candidate is RenderedToolCall =>- candidate.kind === 'tool_call',- )}- onExpand={() =>- setExpandedToolRuns((previous) => new Set(previous).add(runId))+ <ThreadItem+ item={item}+ threadId={info.threadId}+ agent={info.agent}+ actionable={!archived && status !== 'exited' && status !== 'error'}+ streaming={turnActive && index === visibleItems.length - 1}+ terminals={model.terminals}+ permissionsByToolCall={model.permissionsByToolCall}+ showRetry={index === retryNoticeIndex}+ retryPending={retryPending}+ onRetry={retryThread}+ showRestore={index === restoreNoticeIndex}+ onRestore={() => restoreFailedPromptToComposer(index)}+ authOffer={+ index === authOfferNoticeIndex ? authOffer : authHistoryOffer}+ onAuthAction={runAuthAction}+ runningAuthAction={runningAuthAction}+ onResend={resendMessage}+ canSendHere={canPrompt || canQueue}+ isLatestUserTurn={index === lastUserTurnIndex}/></MessageScrollerItem>);- }- return (- <MessageScrollerItem- key={id}- messageId={id}- className="flex flex-col"- scrollAnchor={item.kind === 'message' && item.role === 'user'}- data-tool-call={item.kind === 'tool_call' ? '' : undefined}- >- <ThreadItem- item={item}- threadId={info.threadId}- agent={info.agent}- actionable={!archived && status !== 'exited' && status !== 'error'}- streaming={turnActive && index === visibleItems.length - 1}- terminals={model.terminals}- permissionsByToolCall={model.permissionsByToolCall}- showRetry={index === retryNoticeIndex}- retryPending={retryPending}- onRetry={retryThread}- showRestore={index === restoreNoticeIndex}- onRestore={() => restoreFailedPromptToComposer(index)}- authOffer={- index === authOfferNoticeIndex ? authOffer : authHistoryOffer- }- onAuthAction={runAuthAction}- runningAuthAction={runningAuthAction}- onResend={resendMessage}- canSendHere={canPrompt || canQueue}- isLatestUserTurn={index === lastUserTurnIndex}+ })}+ {turnActive ? (+ status === 'awaiting_permission' ? (+ <div+ className="flex items-center gap-2 px-1 py-1 text-muted-foreground text-sm shimmer"+ data-testid="agent-thread-awaiting-permission"+ >+ <span>{t`Waiting for your approval`}</span>+ </div>+ ) : (+ <WorkingAvatar+ status={workingStatusText(activeToolKind(model.items), thinkingLine)}+ className="px-1 py-1"+ testId="agent-thread-working"/>- </MessageScrollerItem>- );- })}- {turnActive ? (- status === 'awaiting_permission' ? (+ )+ ) : status === 'installing' || status === 'spawning' ? (<div- className="flex items-center gap-2 px-1 py-1 text-muted-foreground text-sm shimmer"- data-testid="agent-thread-awaiting-permission"+ className="flex items-center gap-2 px-1 py-1 text-muted-foreground text-sm"+ data-testid="agent-thread-starting">- <span>{t`Waiting for your approval`}</span>+ <Spinner className="size-3.5" aria-hidden="true" />+ <span className="shimmer">{startStatusMessage}</span></div>- ) : (- <WorkingAvatar- status={workingStatusText(activeToolKind(model.items), thinkingLine)}- className="px-1 py-1"- testId="agent-thread-working"- />- )- ) : status === 'installing' || status === 'spawning' ? (- <div- className="flex items-center gap-2 px-1 py-1 text-muted-foreground text-sm"- data-testid="agent-thread-starting"- >- <Spinner className="size-3.5" aria-hidden="true" />- <span className="shimmer">{startStatusMessage}</span>- </div>- ) : null}- </MessageScrollerContent>- </MessageScrollerViewport>- <MessageScrollerButton direction="end" />- </MessageScroller>- </MessageScrollerProvider>- )}- <div role="status" aria-live="polite" data-testid="agent-thread-drop-notice">- {dropNotice !== null ? (+ ) : null}+ </MessageScrollerContent>+ </MessageScrollerViewport>+ <MessageScrollerButton direction="end" />+ </MessageScroller>+ </MessageScrollerProvider>+ )}+ <div role="status" aria-live="polite" data-testid="agent-thread-drop-notice">+ {dropNotice !== null ? (+ <div+ key={dropNotice.id}+ className="border-t bg-muted/40 px-3 py-1.5 text-muted-foreground text-xs"+ >+ {dropNotice.text}+ </div>+ ) : uploadsPending ? (+ <p className="sr-only">+ <Plural+ value={pendingUploads.length}+ one="Uploading # attachment"+ other="Uploading # attachments"+ />+ </p>+ ) : null}+ </div>+ {info.steer !== undefined && !archived ? (+ <div+ className="flex items-center gap-2 border-t bg-muted/40 px-3 py-1.5 text-muted-foreground text-xs"+ data-testid="agent-thread-steer-pending"+ >+ <Spinner className="size-3.5 shrink-0" aria-hidden="true" />+ <span className="shrink-0">{t`Steering — waiting for the current run to stop…`}</span>+ <span className="min-w-0 flex-1 truncate text-foreground/80">+ {info.steer.content}+ </span>+ </div>+ ) : null}+ {cancelStalled && turnActive ? (<div- key={dropNotice.id}- className="border-t bg-muted/40 px-3 py-1.5 text-muted-foreground text-xs"+ className="flex items-center gap-2 border-amber-500/30 border-t bg-amber-500/5 px-3 py-1.5 text-amber-700 text-xs dark:text-amber-400"+ data-testid="agent-thread-cancel-stalled">- {dropNotice.text}+ <span className="flex-1">+ {t`The agent isn't stopping. Force stop closes this chat and quits the agent.`}+ </span>+ <Button+ type="button"+ size="sm"+ variant="destructive"+ className="h-6 text-xs"+ onClick={() => client.closeThread(info.threadId)}+ data-testid="agent-thread-force-stop"+ >+ {t`Force stop`}+ </Button></div>- ) : uploadsPending ? (- <p className="sr-only">- <Plural- value={pendingUploads.length}- one="Uploading # attachment"- other="Uploading # attachments"- />- </p>) : null}- </div>- {info.steer !== undefined && !archived ? (- <div- className="flex items-center gap-2 border-t bg-muted/40 px-3 py-1.5 text-muted-foreground text-xs"- data-testid="agent-thread-steer-pending"+ <span+ className="sr-only"+ role="status"+ aria-live="polite"+ data-testid="agent-thread-auth-status">- <Spinner className="size-3.5 shrink-0" aria-hidden="true" />- <span className="shrink-0">{t`Steering — waiting for the current run to stop…`}</span>- <span className="min-w-0 flex-1 truncate text-foreground/80">- {info.steer.content}- </span>- </div>- ) : null}- {cancelStalled && turnActive ? (- <div- className="flex items-center gap-2 border-amber-500/30 border-t bg-amber-500/5 px-3 py-1.5 text-amber-700 text-xs dark:text-amber-400"- data-testid="agent-thread-cancel-stalled"+ {runningAuthAction === null ? '' : authActionAnnouncement(runningAuthAction)}+ </span>+ <span+ className="sr-only"+ role="status"+ aria-live="polite"+ data-testid="agent-thread-resume-status">- <span className="flex-1">- {t`The agent isn't stopping. Force stop closes this chat and quits the agent.`}- </span>- <Button- type="button"- size="sm"- variant="destructive"- className="h-6 text-xs"- onClick={() => client.closeThread(info.threadId)}- data-testid="agent-thread-force-stop"- >- {t`Force stop`}- </Button>- </div>- ) : null}- <span- className="sr-only"- role="status"- aria-live="polite"- data-testid="agent-thread-auth-status"- >- {runningAuthAction === null ? '' : authActionAnnouncement(runningAuthAction)}- </span>- <span- className="sr-only"- role="status"- aria-live="polite"- data-testid="agent-thread-resume-status"- >- {resumeFailureMessage}- </span>- <span- className="sr-only"- role="status"- aria-live="polite"- aria-atomic="true"- data-testid="agent-thread-start-status"- >- {announcedStartStatus}- </span>- {resumeFailureMessage !== '' ? (- <div- className="flex items-center gap-2 border-amber-500/30 border-t bg-amber-500/5 px-3 py-1.5 text-amber-700 text-xs dark:text-amber-400"- data-testid="agent-thread-resume-failed"+ {resumeFailureMessage}+ </span>+ <span+ className="sr-only"+ role="status"+ aria-live="polite"+ aria-atomic="true"+ data-testid="agent-thread-start-status">- <span className="flex-1">{resumeFailureMessage}</span>- <Button- type="button"- size="sm"- variant="outline"- className="h-6 shrink-0 text-xs"- disabled={runningAuthAction !== null}- aria-busy={runningAuthAction === 'new-chat'}- onClick={startFreshThread}- data-testid="agent-thread-resume-fallback-new"+ {announcedStartStatus}+ </span>+ {resumeFailureMessage !== '' ? (+ <div+ className="flex items-center gap-2 border-amber-500/30 border-t bg-amber-500/5 px-3 py-1.5 text-amber-700 text-xs dark:text-amber-400"+ data-testid="agent-thread-resume-failed">- {runningAuthAction === 'new-chat' ? (- <Spinner className="size-3" aria-hidden="true" />- ) : null}- {t`New chat with ${agentName}`}- </Button>- </div>- ) : null}- <ThreadComposer- info={info}- hasStartedWork={items.some((item) => item.kind === 'message' && item.role === 'user')}- onNewChat={startFreshThread}- composerRef={composerRef}- onSubmit={submit}- canPrompt={canPrompt}- canQueue={canQueue}- turnActive={turnActive}- cancelPending={cancelPending}- onCancel={requestCancel}- onSteer={requestSteer}- status={status}- archived={archived}- resumePending={resumePending}- usage={model?.tokenUsage ?? null}- selectedCommentCount={selectedCommentCount}- selectedCommentDocs={selectedCommentDocs}- hasQueuedComments={hasQueuedComments}- onAttachComments={() => setCommentsAttached(true)}- onDismissComments={() => setCommentsAttached(false)}- pendingAttachments={pendingAttachments}- pendingUploads={pendingUploads}- imagesAccepted={imagesAccepted}- onIngestImageFiles={ingestFiles}- onIngestAllFiles={ingestFiles}- onRemovePendingAttachment={removePendingAttachment}- />- {dragActive ? <ChatPanelDropOverlay onDismiss={() => setDragActive(false)} /> : null}- </DocPathResolverReadyContext>- </div>- </ImagePreviewContext.Provider>+ <span className="flex-1">{resumeFailureMessage}</span>+ <Button+ type="button"+ size="sm"+ variant="outline"+ className="h-6 shrink-0 text-xs"+ disabled={runningAuthAction !== null}+ aria-busy={runningAuthAction === 'new-chat'}+ onClick={startFreshThread}+ data-testid="agent-thread-resume-fallback-new"+ >+ {runningAuthAction === 'new-chat' ? (+ <Spinner className="size-3" aria-hidden="true" />+ ) : null}+ {t`New chat with ${agentName}`}+ </Button>+ </div>+ ) : null}+ <ThreadComposer+ info={info}+ hasStartedWork={items.some((item) => item.kind === 'message' && item.role === 'user')}+ onNewChat={startFreshThread}+ composerRef={composerRef}+ mentionRecency={mentionRecency}+ onSubmit={submit}+ canPrompt={canPrompt}+ canQueue={canQueue}+ turnActive={turnActive}+ cancelPending={cancelPending}+ onCancel={requestCancel}+ onSteer={requestSteer}+ status={status}+ archived={archived}+ resumePending={resumePending}+ usage={model?.tokenUsage ?? null}+ selectedCommentCount={selectedCommentCount}+ selectedCommentDocs={selectedCommentDocs}+ hasQueuedComments={hasQueuedComments}+ onAttachComments={() => setCommentsAttached(true)}+ onDismissComments={() => setCommentsAttached(false)}+ pendingAttachments={pendingAttachments}+ pendingUploads={pendingUploads}+ imagesAccepted={imagesAccepted}+ onIngestImageFiles={ingestFiles}+ onIngestAllFiles={ingestFiles}+ onRemovePendingAttachment={removePendingAttachment}+ />+ {dragActive ? <ChatPanelDropOverlay onDismiss={() => setDragActive(false)} /> : null}+ </DocPathResolverReadyContext>+ </div>+ </ImagePreviewContext.Provider>+ </MentionRecencyContext>);}@@ -3825,6 +3835,7 @@ function ThreadComposer({hasStartedWork,onNewChat,composerRef,+ mentionRecency,onSubmit,canPrompt,canQueue,@@ -3852,6 +3863,7 @@ function ThreadComposer({hasStartedWork: boolean;onNewChat: () => void;composerRef: RefObject<ComposerMentionInputHandle | null>;+ mentionRecency: MentionRecency;onSubmit: () => void;canPrompt: boolean;canQueue: boolean;@@ -3990,6 +4002,7 @@ function ThreadComposer({}}disabled={composerDisabled}slashCommands={info.availableCommands ?? null}+ mentionRecency={mentionRecency}className={cn('max-h-40 overflow-y-auto px-2.5 pt-1 text-base md:text-sm',composerDisabled && 'opacity-50',diff --git a/packages/app/src/components/acp/ThreadView.user-message-actions.dom.test.tsx b/packages/app/src/components/acp/ThreadView.user-message-actions.dom.test.tsxindex b29b5b9a7..0d86326fb 100644--- a/packages/app/src/components/acp/ThreadView.user-message-actions.dom.test.tsx+++ b/packages/app/src/components/acp/ThreadView.user-message-actions.dom.test.tsx@@ -94,7 +94,7 @@ vi.doMock('sonner', () => ({}));vi.doMock('@/editor/DocumentContext', () => ({- useDocumentContext: () => ({ systemProvider: null }),+ useDocumentContext: () => ({ systemProvider: null, activeDocName: 'notes/today' }),}));let workspace: Workspace | null = null;@@ -669,3 +669,25 @@ describe('a sent attachment chip', () => {expect(within(attachmentRow()).queryByRole('link')).toBeNull();});});++describe('what the edit-and-resend @ picker is told to list first', () => {+ test('the same open doc and attachments the main composer gets', async () => {+ mountWith([+ userMessage({+ attachments: [+ { kind: 'file', path: 'specs/a.md', name: 'a' },+ { kind: 'image', data: 'AAAA', mimeType: 'image/png', name: 'shot.png' },+ ],+ }),+ ]);+ await startEditing();++ const handed = screen+ .getByTestId('agent-thread-user-message-edit-field')+ .getAttribute('data-mention-recency');+ expect(JSON.parse(handed ?? 'null')).toEqual({+ currentDocName: 'notes/today',+ recentPaths: ['specs/a.md'],+ });+ });+});diff --git a/packages/app/src/components/acp/UserMessageActions.tsx b/packages/app/src/components/acp/UserMessageActions.tsxindex 187e743f4..516e48f75 100644--- a/packages/app/src/components/acp/UserMessageActions.tsx+++ b/packages/app/src/components/acp/UserMessageActions.tsx@@ -1,7 +1,7 @@import type { AttachmentPart } from '@inkeep/open-knowledge-core/acp/thread-protocol';import { Trans, useLingui } from '@lingui/react/macro';import { ChevronDown, Pencil } from 'lucide-react';-import { type ReactNode, useEffect, useRef, useState } from 'react';+import { type ReactNode, use, useEffect, useRef, useState } from 'react';import { useCalendarDayNow } from '@/components/acp/calendar-day-store';import { RegisteredAgentIcon } from '@/components/acp/RegisteredAgentIcon';import { formatSentAt } from '@/components/acp/sent-at';@@ -28,6 +28,7 @@ import { enabledThreadAgents } from '@/lib/acp/launcher-selection';import { type RegisteredAgent, useRegisteredAgents } from '@/lib/acp/registered-agents';import { scheduleClipboardWrite } from '@/lib/share/clipboard-adapter';import { cn } from '@/lib/utils';+import { MentionRecencyContext } from './mention-recency-context';export type ResendTarget =| { kind: 'this-thread' }@@ -117,6 +118,8 @@ export function UserMessageEditor({onSend: (text: string, target: ResendTarget, chips: readonly AttachmentPart[]) => Promise<void>;}): ReactNode {const { t } = useLingui();+ const mentionRecency = use(MentionRecencyContext);+ if (mentionRecency === null) throw new Error('UserMessageEditor requires MentionRecencyContext');const fieldRef = useRef<ComposerMentionInputHandle>(null);const [draftEmpty, setDraftEmpty] = useState(initialText.trim() === '');const [sending, setSending] = useState(false);@@ -153,6 +156,7 @@ export function UserMessageEditor({onEscape={onCancel}className="max-h-60 overflow-y-auto text-sm"testId="agent-thread-user-message-edit-field"+ mentionRecency={mentionRecency}/><div className="flex items-center justify-end gap-1.5"><Buttondiff --git a/packages/app/src/components/acp/UserMessageEditor.dom.test.tsx b/packages/app/src/components/acp/UserMessageEditor.dom.test.tsxnew file mode 100644index 000000000..a39daa0ea--- /dev/null+++ b/packages/app/src/components/acp/UserMessageEditor.dom.test.tsx@@ -0,0 +1,40 @@+import { cleanup, render } from '@testing-library/react';+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';+import { EMPTY_MENTION_RECENCY } from '@/editor/composer-mention/composer-mention';+import { MentionRecencyContext } from './mention-recency-context';+import { UserMessageEditor } from './UserMessageActions';++let consoleErrorSpy: ReturnType<typeof vi.spyOn>;++beforeEach(() => {+ consoleErrorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});+});++afterEach(() => {+ cleanup();+ consoleErrorSpy.mockRestore();+});++function editor() {+ return (+ <UserMessageEditor+ initialText="try again"+ currentAgent={{ source: 'registry', id: 'claude', name: 'Claude Agent' }}+ canSendHere+ onCancel={() => {}}+ onSend={() => Promise.resolve()}+ />+ );+}++describe('UserMessageEditor and its recency provider', () => {+ test('rendered with no provider above it, it fails loud rather than quietly losing the @ order', () => {+ expect(() => render(editor())).toThrow(/requires MentionRecencyContext/);+ });++ test('under an explicit provider the real, unmocked editor mounts without a single console error', () => {+ render(<MentionRecencyContext value={EMPTY_MENTION_RECENCY}>{editor()}</MentionRecencyContext>);++ expect(consoleErrorSpy).not.toHaveBeenCalled();+ });+});diff --git a/packages/app/src/components/acp/composer-mention-input.test-helper.tsx b/packages/app/src/components/acp/composer-mention-input.test-helper.tsxindex 6b3835f07..13e1ba11d 100644--- a/packages/app/src/components/acp/composer-mention-input.test-helper.tsx+++ b/packages/app/src/components/acp/composer-mention-input.test-helper.tsx@@ -1,6 +1,11 @@import type { JSONContent } from '@tiptap/core';import { type Ref, useImperativeHandle, useRef } from 'react';import type { ComposerMentionInputHandle } from '@/editor/ComposerMentionInput';+import type { MentionRecency } from '@/editor/composer-mention/composer-mention';++export function mentionRecencyAttribute(recency: MentionRecency | undefined): string | undefined {+ return recency === undefined ? undefined : JSON.stringify(recency);+}export function MockComposerMentionInput({ref,@@ -14,6 +19,7 @@ export function MockComposerMentionInput({placeholder,disabled,testId,+ mentionRecency,}: {ref?: Ref<ComposerMentionInputHandle>;ariaLabel: string;@@ -26,6 +32,7 @@ export function MockComposerMentionInput({placeholder?: string;disabled?: boolean;testId?: string;+ mentionRecency?: MentionRecency;}) {const localRef = useRef<HTMLTextAreaElement>(null);const notify = () => {@@ -79,6 +86,7 @@ export function MockComposerMentionInput({placeholder={placeholder}disabled={disabled}data-testid={testId}+ data-mention-recency={mentionRecencyAttribute(mentionRecency)}className={className}onChange={notify}onKeyDown={(event) => {diff --git a/packages/app/src/components/acp/mention-recency-context.ts b/packages/app/src/components/acp/mention-recency-context.tsnew file mode 100644index 000000000..1bdf7c9d6--- /dev/null+++ b/packages/app/src/components/acp/mention-recency-context.ts@@ -0,0 +1,4 @@+import { createContext } from 'react';+import type { MentionRecency } from '@/editor/composer-mention/composer-mention';++export const MentionRecencyContext = createContext<MentionRecency | null>(null);diff --git a/packages/app/src/editor/ComposerMentionInput.dom.test.tsx b/packages/app/src/editor/ComposerMentionInput.dom.test.tsxindex 3ca48e44f..a89d68a36 100644--- a/packages/app/src/editor/ComposerMentionInput.dom.test.tsx+++ b/packages/app/src/editor/ComposerMentionInput.dom.test.tsx@@ -30,6 +30,14 @@ function getComposerEditor(box: HTMLElement): Editor {return (box as unknown as { editor: Editor }).editor;}+async function waitForSelectableItem(editor: Editor): Promise<void> {+ for (let i = 0; i < 50; i++) {+ if (suggestionHasSelectableItem(editor.view)) return;+ await new Promise((resolve) => setTimeout(resolve, 0));+ }+ throw new Error('mention popup never produced a selectable item');+}+let consoleErrorSpy: ReturnType<typeof vi.spyOn>;beforeEach(() => {@@ -504,14 +512,6 @@ describe('ComposerMentionInput — Enter defers to the @-mention popup', () => {return state?.active ?? false;}- async function waitForSelectableItem(editor: Editor): Promise<void> {- for (let i = 0; i < 50; i++) {- if (suggestionHasSelectableItem(editor.view)) return;- await new Promise((resolve) => setTimeout(resolve, 0));- }- throw new Error('mention popup never produced a selectable item');- }-test('Enter submits while the popup is closed', () => {const onSubmit = vi.fn(() => {});render(@@ -693,3 +693,57 @@ describe('ComposerMentionInput — setText round-trips the text it was given', (expect(onEmptyChange).toHaveBeenCalledWith(true);});});++describe('ComposerMentionInput — what the @ popup lists first', () => {+ let fetchSpy: ReturnType<typeof vi.spyOn>;++ beforeEach(() => {+ const page = (docName: string, title: string) => ({+ docName,+ title,+ docExt: '.md',+ size: 1,+ modified: '2026-01-01T00:00:00.000Z',+ });+ fetchSpy = vi+ .spyOn(globalThis, 'fetch')+ .mockImplementation(+ async () =>+ new Response(+ JSON.stringify({ pages: [page('foo', 'Foo'), page('bar', 'Bar'), page('baz', 'Baz')] }),+ { status: 200, headers: { 'content-type': 'application/json' } },+ ),+ );+ });++ afterEach(() => {+ fetchSpy.mockRestore();+ });++ test('the open doc leads, then what the chat attached, then the rest', async () => {+ render(+ <ComposerMentionInput+ attachmentDrop={{ kind: 'host' }}+ ariaLabel="Ask AI"+ onEmptyChange={() => {}}+ onSubmit={() => {}}+ mentionRecency={{ currentDocName: 'bar', recentPaths: ['baz.md'] }}+ />,+ );+ const box = screen.getByRole('textbox', { name: 'Ask AI' });+ const editor = getComposerEditor(box);++ await act(async () => {+ editor.commands.insertContent('@');+ });+ await waitForSelectableItem(editor);++ const rows = [...document.querySelectorAll('[role="option"]')].map(+ (row) => row.textContent ?? '',+ );+ expect(rows).toHaveLength(3);+ expect(rows[0]).toContain('bar.md');+ expect(rows[1]).toContain('baz.md');+ expect(rows[2]).toContain('foo.md');+ });+});diff --git a/packages/app/src/editor/ComposerMentionInput.tsx b/packages/app/src/editor/ComposerMentionInput.tsxindex f4d65bc54..0e186bf43 100644--- a/packages/app/src/editor/ComposerMentionInput.tsx+++ b/packages/app/src/editor/ComposerMentionInput.tsx@@ -8,8 +8,11 @@ import {type ComposerAttachmentPart,composerMentionExtensions,composerMentionSuggestionKey,+ EMPTY_MENTION_RECENCY,isComposerEmpty,+ type MentionRecency,serializeComposerContent,+ setMentionRecency,} from '@/editor/composer-mention/composer-mention';import {composerFirstLineText,@@ -78,6 +81,7 @@ export function ComposerMentionInput({disabled = false,testId,slashCommands,+ mentionRecency,attachmentDrop,}: {ref?: Ref<ComposerMentionInputHandle>;@@ -94,6 +98,7 @@ export function ComposerMentionInput({disabled?: boolean;testId?: string;slashCommands?: SlashCommandItem[] | null;+ mentionRecency?: MentionRecency;attachmentDrop: ComposerAttachmentDropPolicy;}) {const { t } = useLingui();@@ -204,6 +209,11 @@ export function ComposerMentionInput({setSlashHint(resolveSlashTokenHint(composerFirstLineText(editor), getSlashCommands(editor)));}, [editor, slashCommands]);+ useEffect(() => {+ if (!editor || editor.isDestroyed) return;+ setMentionRecency(editor, mentionRecency ?? EMPTY_MENTION_RECENCY);+ }, [editor, mentionRecency]);+// biome-ignore lint/correctness/useExhaustiveDependencies: mount-once seed-integrity check; initialDoc is the one-time draft seed and must not re-trigger this effect.useEffect(() => {if (!editor) return;diff --git a/packages/app/src/editor/composer-drop-parity.dom.test.tsx b/packages/app/src/editor/composer-drop-parity.dom.test.tsxindex c09463cc3..6d3c9d328 100644--- a/packages/app/src/editor/composer-drop-parity.dom.test.tsx+++ b/packages/app/src/editor/composer-drop-parity.dom.test.tsx@@ -2,6 +2,7 @@ import * as actualLinguiMacro from '@lingui/react/macro';import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';import type { ReactNode } from 'react';import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';+import { MentionRecencyContext } from '@/components/acp/mention-recency-context';import { setComposerDraftDoc } from '@/components/composer-draft-store';import {type AgentThreadLaunchDetail,@@ -18,6 +19,7 @@ import {expectDragOverIsCancelled,makeImageFile,} from '@/editor/composer-drop.test-helper';+import { EMPTY_MENTION_RECENCY } from '@/editor/composer-mention/composer-mention';import { reloadEnabledAgentsFromStorage } from '@/lib/acp/enabled-agents';import { registerAgent, reloadRegisteredAgentsFromStorage } from '@/lib/acp/registered-agents';import { saveStickyAgent } from '@/lib/unified-agent-store';@@ -276,13 +278,15 @@ describe('every ComposerMentionInput surface either refuses the drop with a reashostDrops.push(...Array.from(event.dataTransfer.files).map((file) => file.name));}}>- <UserMessageEditor- initialText="try again with the screenshot"- currentAgent={{ source: 'registry', id: 'claude-acp', name: 'Claude Agent' }}- canSendHere- onCancel={() => {}}- onSend={() => Promise.resolve()}- />+ <MentionRecencyContext value={EMPTY_MENTION_RECENCY}>+ <UserMessageEditor+ initialText="try again with the screenshot"+ currentAgent={{ source: 'registry', id: 'claude-acp', name: 'Claude Agent' }}+ canSendHere+ onCancel={() => {}}+ onSend={() => Promise.resolve()}+ />+ </MentionRecencyContext></div></TooltipProvider>,);diff --git a/packages/app/src/editor/composer-mention/composer-mention.test.ts b/packages/app/src/editor/composer-mention/composer-mention.test.tsindex 97ff93778..3a49dc707 100644--- a/packages/app/src/editor/composer-mention/composer-mention.test.ts+++ b/packages/app/src/editor/composer-mention/composer-mention.test.ts@@ -136,3 +136,105 @@ describe('createMentionCorpus — fetch retry contract', () => {expect(calls).toBe(2);});});++describe('createMentionCorpus — what the empty picker shows first', () => {+ const pages: PageItem[] = [+ { docName: 'changesets/a', title: 'A' },+ { docName: 'changesets/b', title: 'B' },+ { docName: 'plan', title: 'Plan' },+ { docName: 'notes/today', title: 'Today' },+ { docName: 'specs/api', title: 'API' },+ ];+ const corpus = () => createMentionCorpus(async () => pages);++ test('the document being edited comes first, then what the chat already attached', async () => {+ const items = await corpus().getItems('', {+ currentDocName: 'notes/today',+ recentPaths: ['specs/api.md', 'plan.md'],+ });++ expect(items.map((item) => item.path)).toEqual([+ 'notes/today.md',+ 'specs/api.md',+ 'plan.md',+ 'changesets/a.md',+ 'changesets/b.md',+ ]);+ });++ test('with nothing to go on, the order is the workspace order as before', async () => {+ const items = await corpus().getItems('');++ expect(items.map((item) => item.path)).toEqual([+ 'changesets/a.md',+ 'changesets/b.md',+ 'plan.md',+ 'notes/today.md',+ 'specs/api.md',+ ]);+ });++ test('a typed query searches as it always did and ignores recency', async () => {+ const items = await corpus().getItems('changesets', {+ currentDocName: 'notes/today',+ recentPaths: ['plan.md'],+ });++ expect(items.map((item) => item.path)).toEqual(['changesets/a.md', 'changesets/b.md']);+ });++ test('an attached path that is no longer in the workspace is simply skipped', async () => {+ const items = await corpus().getItems('', {+ currentDocName: null,+ recentPaths: ['gone.md', 'plan.md'],+ });++ expect(items[0]?.path).toBe('plan.md');+ expect(items).toHaveLength(5);+ });++ test('a folder the chat attached is pinned like a file', async () => {+ const withFolder: PageItem[] = [...pages, { kind: 'folder', docName: 'specs', title: 'specs' }];+ const items = await createMentionCorpus(async () => withFolder).getItems('', {+ currentDocName: null,+ recentPaths: ['specs'],+ });++ expect(items[0]).toMatchObject({ path: 'specs', kind: 'folder' });+ });++ test('an extension-qualified open doc still pins its page', async () => {+ const items = await corpus().getItems('', {+ currentDocName: 'notes/today.md',+ recentPaths: [],+ });++ expect(items[0]?.path).toBe('notes/today.md');+ });++ test('a long chat cannot push the workspace out of the default list', async () => {+ const many: PageItem[] = Array.from({ length: 12 }, (_, i) => ({+ docName: `a/${i}`,+ title: `A${i}`,+ }));+ const attached = many+ .slice(3)+ .reverse()+ .map((page) => `${page.docName}.md`);+ const items = await createMentionCorpus(async () => many).getItems('', {+ currentDocName: null,+ recentPaths: attached,+ });++ expect(items.map((i) => i.path)).toEqual([+ 'a/11.md',+ 'a/10.md',+ 'a/9.md',+ 'a/8.md',+ 'a/0.md',+ 'a/1.md',+ 'a/2.md',+ 'a/3.md',+ ]);+ });+});diff --git a/packages/app/src/editor/composer-mention/composer-mention.ts b/packages/app/src/editor/composer-mention/composer-mention.tsindex 954291d2c..dcc1ded59 100644--- a/packages/app/src/editor/composer-mention/composer-mention.ts+++ b/packages/app/src/editor/composer-mention/composer-mention.ts@@ -9,6 +9,7 @@ import { ReactRenderer } from '@tiptap/react';import Suggestion, { type SuggestionKeyDownProps, type SuggestionProps } from '@tiptap/suggestion';import { X } from 'lucide-react';import { fileEntryPathIconToSvgString } from '@/components/file-entry-icon';+import { normalizeDocNameInput } from '@/lib/doc-paths';import { docNameToRelativePath } from '@/lib/workspace-paths';import {clearSuggestionSelectableCount,@@ -34,6 +35,58 @@ export interface MentionItem {}const MAX_MENTION_ITEMS = 8;+const MAX_PINNED_ITEMS = 4;+const EXTENSION_NAME = 'composerMention';++export interface MentionRecency {+ readonly currentDocName: string | null;+ readonly recentPaths: readonly string[];+}++export const EMPTY_MENTION_RECENCY: MentionRecency = { currentDocName: null, recentPaths: [] };++interface MentionStorage {+ recency: MentionRecency;+}++function mentionStorage(editor: Editor): MentionStorage | undefined {+ return (editor.storage as unknown as Partial<Record<string, MentionStorage>>)[EXTENSION_NAME];+}++function getMentionRecency(editor: Editor): MentionRecency {+ return mentionStorage(editor)?.recency ?? EMPTY_MENTION_RECENCY;+}++export function setMentionRecency(editor: Editor, recency: MentionRecency): void {+ const storage = mentionStorage(editor);+ if (storage !== undefined) storage.recency = recency;+}++function rankByRecency(pages: PageItem[], recency: MentionRecency): PageItem[] {+ const current =+ recency.currentDocName === null ? null : normalizeDocNameInput(recency.currentDocName);+ const order = new Map<string, number>();+ for (const [index, path] of recency.recentPaths.entries()) order.set(path, index + 1);+ const pinned: { page: PageItem; order: number }[] = [];+ for (const page of pages) {+ if (current !== null && page.docName === current) {+ pinned.push({ page, order: 0 });+ continue;+ }+ const position = order.get(pageItemToPath(page));+ if (position !== undefined) pinned.push({ page, order: position });+ }+ pinned.sort((a, b) => a.order - b.order);+ const kept = pinned.slice(0, MAX_PINNED_ITEMS).map((entry) => entry.page);+ const keptSet = new Set(kept);+ return [+ ...kept,+ ...filterPages(+ pages.filter((page) => !keptSet.has(page)),+ '',+ ),+ ];+}export const composerMentionSuggestionKey = new PluginKey('composerMentionSuggestion');@@ -85,7 +138,7 @@ const ComposerHistory = Extension.create({});const ComposerMention = Node.create({- name: 'composerMention',+ name: EXTENSION_NAME,group: 'inline',inline: true,atom: true,@@ -168,6 +221,9 @@ const ComposerMention = Node.create({};},+ addStorage() {+ return { recency: EMPTY_MENTION_RECENCY };+ },addProseMirrorPlugins() {return [configureComposerMentionSuggestion(this.editor)];},@@ -217,7 +273,10 @@ export function createMentionCorpus(return { loaded: pagesLoaded, error: fetchError };},- async getItems(query: string): Promise<MentionItem[]> {+ async getItems(+ query: string,+ recency: MentionRecency = EMPTY_MENTION_RECENCY,+ ): Promise<MentionItem[]> {if (!pagesLoaded) {pagesPromise ||= fetch();try {@@ -232,7 +291,10 @@ export function createMentionCorpus(pagesPromise = null;}}- return filterPages(cachedPages, query)+ const ordered = (+ query === '' ? rankByRecency(cachedPages, recency) : filterPages(cachedPages, query)+ ).slice(0, MAX_MENTION_ITEMS);+ return ordered.map((page) => ({docName: page.docName,title: page.title,@@ -259,7 +321,7 @@ function configureComposerMentionSuggestion(editor: Editor) {pluginKey: composerMentionSuggestionKey,char: '@',- items: ({ query }) => corpus.getItems(query),+ items: ({ query }) => corpus.getItems(query, getMentionRecency(editor)),command: ({ editor, range, props: item }) => {try {diff --git a/packages/app/src/lib/acp/thread-attachment-paths.test.ts b/packages/app/src/lib/acp/thread-attachment-paths.test.tsnew file mode 100644index 000000000..3dcb2002a--- /dev/null+++ b/packages/app/src/lib/acp/thread-attachment-paths.test.ts@@ -0,0 +1,44 @@+import { describe, expect, test } from 'vitest';+import { threadAttachmentPaths } from './thread-attachment-paths';+import type { RenderedItem } from './thread-event-model';++const user = (messageId: string, paths: readonly string[]): RenderedItem => ({+ kind: 'message',+ role: 'user',+ text: 'hi',+ messageId,+ attachments: paths.map((path) => ({ kind: 'file' as const, path, name: path })),+});++describe('threadAttachmentPaths', () => {+ test('lists what the user attached, most recent message first, without repeats', () => {+ const items: RenderedItem[] = [+ user('m1', ['notes.md', 'specs/a.md']),+ { kind: 'message', role: 'agent', text: 'ok' } as RenderedItem,+ user('m2', ['specs/a.md', 'plan.md']),+ ];++ expect(threadAttachmentPaths(items)).toEqual(['specs/a.md', 'plan.md', 'notes.md']);+ });++ test('a thread with no attachments yields nothing', () => {+ expect(threadAttachmentPaths([user('m1', [])])).toEqual([]);+ });++ test('only file and folder attachments carry a path; images and blobs are skipped', () => {+ const item: RenderedItem = {+ kind: 'message',+ role: 'user',+ text: 'hi',+ messageId: 'm1',+ attachments: [+ { kind: 'image', data: 'AAAA', mimeType: 'image/png', name: 'shot.png' },+ { kind: 'folder', path: 'specs', name: 'specs' },+ { kind: 'blob', data: 'AAAA', textPayload: true, mimeType: 'text/plain', name: 'x.txt' },+ { kind: 'file', path: 'plan.md', name: 'plan.md' },+ ],+ };++ expect(threadAttachmentPaths([item])).toEqual(['specs', 'plan.md']);+ });+});diff --git a/packages/app/src/lib/acp/thread-attachment-paths.ts b/packages/app/src/lib/acp/thread-attachment-paths.tsnew file mode 100644index 000000000..e79d316e9--- /dev/null+++ b/packages/app/src/lib/acp/thread-attachment-paths.ts@@ -0,0 +1,17 @@+import type { RenderedItem } from '@/lib/acp/thread-event-model';++export function threadAttachmentPaths(items: readonly RenderedItem[]): string[] {+ const seen = new Set<string>();+ const paths: string[] = [];+ for (let index = items.length - 1; index >= 0; index -= 1) {+ const item = items[index];+ if (item?.kind !== 'message' || item.role !== 'user') continue;+ for (const attachment of item.attachments ?? []) {+ if (attachment.kind !== 'file' && attachment.kind !== 'folder') continue;+ if (seen.has(attachment.path)) continue;+ seen.add(attachment.path);+ paths.push(attachment.path);+ }+ }+ return paths;+}