Beautiful, AI-native markdown IDE and LLM wiki
TypeScript 2nd-brainagent-skillsclaudecodexcompany-braindocsknowledge-knowledge-baseknowledge-managementllmllm-wikillm-wiki-karpathymarkdownmarkdown-editormdmdxnotespkmsecond-brainskills
Preserve Ask AI drafts across composer recreation (#7015)
Nick Gomez179c4ee9f380
diff --git a/.changeset/preserve-staged-thread-draft.md b/.changeset/preserve-staged-thread-draft.mdnew file mode 100644index 000000000..1ab6d2284--- /dev/null+++ b/.changeset/preserve-staged-thread-draft.md@@ -0,0 +1,5 @@+---+'@inkeep/open-knowledge': patch+---++Ask AI text added to an existing chat in the Agents panel no longer sometimes leaves the chat's message box empty.diff --git a/packages/app/src/components/BottomComposer.dom.test.tsx b/packages/app/src/components/BottomComposer.dom.test.tsxindex 6a15b6e1e..06db8760f 100644--- a/packages/app/src/components/BottomComposer.dom.test.tsx+++ b/packages/app/src/components/BottomComposer.dom.test.tsx@@ -85,7 +85,7 @@ vi.doMock('@/editor/ComposerMentionInput', () => ({if (localRef.current) localRef.current.value = text;onEmptyChange(text.trim() === '');},- appendText: () => {},+ appendText: () => true,openMentionPicker: () => {},openSlashCommandPicker: () => {},}));diff --git a/packages/app/src/components/SessionsHost.agents.dom.test.tsx b/packages/app/src/components/SessionsHost.agents.dom.test.tsxindex 99b545c51..7166dc18b 100644--- a/packages/app/src/components/SessionsHost.agents.dom.test.tsx+++ b/packages/app/src/components/SessionsHost.agents.dom.test.tsx@@ -1651,7 +1651,10 @@ describe('SessionsHost — agents panel (web / no bridge)', () => {const staged: string[] = [];const queued: Array<{ threadId: string; threadIds: readonly string[] | undefined }> = [];- const stopStaging = subscribeStagedThreadDraft('b', (text) => staged.push(text));+ const stopStaging = subscribeStagedThreadDraft('b', (text) => {+ staged.push(text);+ return true;+ });const stopQueued = subscribeSendInThread((threadId, threadIds) =>queued.push({ threadId, threadIds }),);@@ -2866,7 +2869,10 @@ describe('SessionsHost — agents panel (web / no bridge)', () => {await screen.findByTestId('thread-view');const staged: string[] = [];- const stopStaging = subscribeStagedThreadDraft('t1', (text) => staged.push(text));+ const stopStaging = subscribeStagedThreadDraft('t1', (text) => {+ staged.push(text);+ return true;+ });await act(async () => {requestActiveTerminalInput('fix this lint error', { submit });});@@ -2885,7 +2891,10 @@ describe('SessionsHost — agents panel (web / no bridge)', () => {expect(onVisibleChange).not.toHaveBeenCalled();const staged: string[] = [];- const stopStaging = subscribeStagedThreadDraft('t1', (text) => staged.push(text));+ const stopStaging = subscribeStagedThreadDraft('t1', (text) => {+ staged.push(text);+ return true;+ });await act(async () => {requestActiveTerminalInput('fix this lint error', { submit: false });});@@ -2902,7 +2911,10 @@ describe('SessionsHost — agents panel (web / no bridge)', () => {await screen.findByTestId('thread-view');const staged: string[] = [];- const stopStaging = subscribeStagedThreadDraft('t1', (text) => staged.push(text));+ const stopStaging = subscribeStagedThreadDraft('t1', (text) => {+ staged.push(text);+ return true;+ });await act(async () => {requestActiveTerminalInput('a fresh question', { newTab: true, submit: false });});@@ -2922,7 +2934,10 @@ describe('SessionsHost — agents panel (web / no bridge)', () => {await screen.findByTestId('thread-view');const staged: string[] = [];- const stopStaging = subscribeStagedThreadDraft('t1', (text) => staged.push(text));+ const stopStaging = subscribeStagedThreadDraft('t1', (text) => {+ staged.push(text);+ return true;+ });await act(async () => {requestActiveTerminalInput('fix this lint error', { newTab: true, submit: true });});diff --git a/packages/app/src/components/acp/ThreadView.comments.dom.test.tsx b/packages/app/src/components/acp/ThreadView.comments.dom.test.tsxindex 2f622d7a4..6c6c46043 100644--- a/packages/app/src/components/acp/ThreadView.comments.dom.test.tsx+++ b/packages/app/src/components/acp/ThreadView.comments.dom.test.tsx@@ -272,6 +272,7 @@ describe('ThreadView queued-comment chip', () => {let staged: string | null = null;const stopStaging = subscribeStagedThreadDraft('new', (text) => {staged = text;+ return true;});const field = screen.getByTestId('agent-thread-composer') as HTMLTextAreaElement;diff --git a/packages/app/src/components/acp/ThreadView.dom.test.tsx b/packages/app/src/components/acp/ThreadView.dom.test.tsxindex 6aafc160f..7476de5c8 100644--- a/packages/app/src/components/acp/ThreadView.dom.test.tsx+++ b/packages/app/src/components/acp/ThreadView.dom.test.tsx@@ -4407,6 +4407,7 @@ describe('ThreadView auth-required dead ends', () => {const seen = { text: null as string | null };stopStaging = subscribeStagedThreadDraft(threadId, (text) => {seen.text = text;+ return true;});return seen;}diff --git a/packages/app/src/components/acp/ThreadView.draft-delivery.dom.test.tsx b/packages/app/src/components/acp/ThreadView.draft-delivery.dom.test.tsxnew file mode 100644index 000000000..8cc26b1cc--- /dev/null+++ b/packages/app/src/components/acp/ThreadView.draft-delivery.dom.test.tsx@@ -0,0 +1,205 @@+import type { ThreadInfo } from '@inkeep/open-knowledge-core/acp/thread-protocol';+import { i18n } from '@lingui/core';+import { I18nProvider } from '@lingui/react';+import { QueryClient, QueryClientProvider } from '@tanstack/react-query';+import { act, cleanup, render, screen } from '@testing-library/react';+import { Editor } from '@tiptap/core';+import { StrictMode, useInsertionEffect } from 'react';+import { describe, expect, test, vi } from 'vitest';+import { TooltipProvider } from '@/components/ui/tooltip';+import {+ resetStagedThreadDrafts,+ stageThreadDraft,+ stageThreadDraftContent,+} from '@/lib/acp/thread-draft-staging';+import { ThreadView } from './ThreadView';++vi.mock('@/editor/DocumentContext', () => ({+ useDocumentContext: () => ({ systemProvider: null, activeDocName: null }),+}));+vi.mock('@/lib/use-workspace', () => ({ useWorkspace: () => null }));++function BeforeLayout({ run }: { run: () => void }) {+ useInsertionEffect(run, [run]);+ return null;+}++describe('ThreadView staged draft delivery', () => {+ test.for([+ { order: 'before provisional disposal', expire: false },+ { order: 'after provisional disposal', expire: true },+ ])('keeps the pending draft in the current composer $order', async ({ expire }, context) => {+ const query = new QueryClient({ defaultOptions: { queries: { retry: false } } });+ context.onTestFinished(() => {+ try {+ act(() => {+ cleanup();+ query.clear();+ vi.runOnlyPendingTimers();+ });+ expect(vi.getTimerCount()).toBe(0);+ } finally {+ vi.useRealTimers();+ resetStagedThreadDrafts();+ vi.restoreAllMocks();+ }+ });+ vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] });+ const errors = vi.spyOn(console, 'error');+ const warnings = vi.spyOn(console, 'warn');+ i18n.load('en', {});+ i18n.activate('en');+ const created: Editor[] = [];+ const mount = Editor.prototype.mount;+ vi.spyOn(Editor.prototype, 'mount').mockImplementation(function (...args) {+ const result = mount.apply(this, args);+ created.push(this);+ return result;+ });+ const observations: { liveBefore: number; destroyedAfter: number; timerCount: number }[] = [];+ const beforeLayout = () => {+ const provisional = created.filter((editor) => !editor.isDestroyed);+ const timerCount = vi.getTimerCount();+ if (expire) vi.runOnlyPendingTimers();+ observations.push({+ liveBefore: provisional.length,+ destroyedAfter: provisional.filter((editor) => editor.isDestroyed).length,+ timerCount,+ });+ };+ const info: ThreadInfo = {+ threadId: `draft-delivery-${expire}`,+ agent: { id: 'echo', source: 'custom', name: 'Echo' },+ title: 'Chat',+ status: 'ready',+ createdAt: 1,+ lastActivityAt: 1,+ lastSeq: -1,+ modes: null,+ configOptions: null,+ };+ stageThreadDraft(info.threadId, 'Review this document');++ await act(async () => {+ render(+ <StrictMode>+ <I18nProvider i18n={i18n}>+ <QueryClientProvider client={query}>+ <TooltipProvider>+ <BeforeLayout run={beforeLayout} />+ <ThreadView info={info} />+ </TooltipProvider>+ </QueryClientProvider>+ </I18nProvider>+ </StrictMode>,+ );+ });++ expect(observations).toHaveLength(1);+ await context.annotate(JSON.stringify(observations), 'pre-layout editor lifetime');+ const [lifetime] = observations;+ expect(lifetime.liveBefore).toBeGreaterThan(0);+ if (expire) expect(lifetime.timerCount).toBeGreaterThan(0);+ expect(lifetime.destroyedAfter).toBe(expire ? lifetime.liveBefore : 0);+ expect(errors).not.toHaveBeenCalled();+ expect(warnings).not.toHaveBeenCalled();+ expect(screen.getByRole('textbox', { name: 'Message Echo' }).textContent).toBe(+ 'Review this document',+ );+ });++ test.for([+ { order: 'before provisional disposal', expire: false },+ { order: 'after provisional disposal', expire: true },+ ])(+ 'keeps the pending draft content and its attachment in the current composer $order',+ async ({ expire }, context) => {+ const query = new QueryClient({ defaultOptions: { queries: { retry: false } } });+ context.onTestFinished(() => {+ try {+ act(() => {+ cleanup();+ query.clear();+ vi.runOnlyPendingTimers();+ });+ expect(vi.getTimerCount()).toBe(0);+ } finally {+ vi.useRealTimers();+ resetStagedThreadDrafts();+ vi.restoreAllMocks();+ }+ });+ vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] });+ const errors = vi.spyOn(console, 'error');+ const warnings = vi.spyOn(console, 'warn');+ i18n.load('en', {});+ i18n.activate('en');+ const created: Editor[] = [];+ const mount = Editor.prototype.mount;+ vi.spyOn(Editor.prototype, 'mount').mockImplementation(function (...args) {+ const result = mount.apply(this, args);+ created.push(this);+ return result;+ });+ const observations: { liveBefore: number; destroyedAfter: number; timerCount: number }[] = [];+ const beforeLayout = () => {+ const provisional = created.filter((editor) => !editor.isDestroyed);+ const timerCount = vi.getTimerCount();+ if (expire) vi.runOnlyPendingTimers();+ observations.push({+ liveBefore: provisional.length,+ destroyedAfter: provisional.filter((editor) => editor.isDestroyed).length,+ timerCount,+ });+ };+ const info: ThreadInfo = {+ threadId: `draft-content-delivery-${expire}`,+ agent: { id: 'echo', source: 'custom', name: 'Echo' },+ title: 'Chat',+ status: 'ready',+ createdAt: 1,+ lastActivityAt: 1,+ lastSeq: -1,+ modes: null,+ configOptions: null,+ };+ stageThreadDraftContent(info.threadId, {+ doc: {+ type: 'doc',+ content: [+ { type: 'paragraph', content: [{ type: 'text', text: 'Carry this brief over' }] },+ ],+ },+ attachments: [{ kind: 'file', path: '/notes/brief.md', name: 'brief.md' }],+ });++ await act(async () => {+ render(+ <StrictMode>+ <I18nProvider i18n={i18n}>+ <QueryClientProvider client={query}>+ <TooltipProvider>+ <BeforeLayout run={beforeLayout} />+ <ThreadView info={info} />+ </TooltipProvider>+ </QueryClientProvider>+ </I18nProvider>+ </StrictMode>,+ );+ });++ expect(observations).toHaveLength(1);+ await context.annotate(JSON.stringify(observations), 'pre-layout editor lifetime');+ const [lifetime] = observations;+ expect(lifetime.liveBefore).toBeGreaterThan(0);+ if (expire) expect(lifetime.timerCount).toBeGreaterThan(0);+ expect(lifetime.destroyedAfter).toBe(expire ? lifetime.liveBefore : 0);+ expect(screen.getByRole('textbox', { name: 'Message Echo' }).textContent).toBe(+ 'Carry this brief over',+ );+ expect(screen.getAllByRole('button', { name: 'Remove brief.md' })).toHaveLength(1);+ expect(errors).not.toHaveBeenCalled();+ expect(warnings).not.toHaveBeenCalled();+ },+ );+});diff --git a/packages/app/src/components/acp/ThreadView.registered-draft-delivery.dom.test.tsx b/packages/app/src/components/acp/ThreadView.registered-draft-delivery.dom.test.tsxnew file mode 100644index 000000000..ddc58fe8c--- /dev/null+++ b/packages/app/src/components/acp/ThreadView.registered-draft-delivery.dom.test.tsx@@ -0,0 +1,146 @@+import type { ThreadInfo } from '@inkeep/open-knowledge-core/acp/thread-protocol';+import { i18n } from '@lingui/core';+import { I18nProvider } from '@lingui/react';+import { QueryClient, QueryClientProvider } from '@tanstack/react-query';+import { act, cleanup, render, screen } from '@testing-library/react';+import { Editor } from '@tiptap/core';+import { StrictMode, useEffect, useInsertionEffect, useRef } from 'react';+import { describe, expect, test, vi } from 'vitest';+import { TooltipProvider } from '@/components/ui/tooltip';+import * as staging from '@/lib/acp/thread-draft-staging';+import { ThreadView } from './ThreadView';++vi.mock('@/editor/DocumentContext', () => ({+ useDocumentContext: () => ({ systemProvider: null, activeDocName: null }),+}));+vi.mock('@/lib/use-workspace', () => ({ useWorkspace: () => null }));++function BeforeLayout({ run }: { run: () => void }) {+ useInsertionEffect(run, [run]);+ return null;+}++function AfterSubscription({ stage }: { stage: () => void }) {+ const staged = useRef(false);+ useEffect(() => {+ if (staged.current) return;+ staged.current = true;+ stage();+ }, [stage]);+ return null;+}++describe('ThreadView registered staged draft delivery', () => {+ test('keeps a draft staged after subscription in the current composer after provisional disposal', async (context) => {+ const query = new QueryClient({ defaultOptions: { queries: { retry: false } } });+ context.onTestFinished(() => {+ try {+ act(() => {+ cleanup();+ query.clear();+ vi.runOnlyPendingTimers();+ });+ expect(vi.getTimerCount()).toBe(0);+ } finally {+ vi.useRealTimers();+ staging.resetStagedThreadDrafts();+ vi.restoreAllMocks();+ }+ });+ vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] });+ const errors = vi.spyOn(console, 'error');+ const warnings = vi.spyOn(console, 'warn');+ i18n.load('en', {});+ i18n.activate('en');+ const created: Editor[] = [];+ const mount = Editor.prototype.mount;+ vi.spyOn(Editor.prototype, 'mount').mockImplementation(function (...args) {+ const result = mount.apply(this, args);+ created.push(this);+ return result;+ });+ const lifecycle: { liveBefore: number; destroyedAfter: number; timerCount: number }[] = [];+ const beforeLayout = () => {+ const provisional = created.filter((editor) => !editor.isDestroyed);+ const timerCount = vi.getTimerCount();+ vi.runOnlyPendingTimers();+ lifecycle.push({+ liveBefore: provisional.length,+ destroyedAfter: provisional.filter((editor) => editor.isDestroyed).length,+ timerCount,+ });+ };+ const info: ThreadInfo = {+ threadId: 'registered-draft-delivery',+ agent: { id: 'echo', source: 'custom', name: 'Echo' },+ title: 'Chat',+ status: 'ready',+ createdAt: 1,+ lastActivityAt: 1,+ lastSeq: -1,+ modes: null,+ configOptions: null,+ };+ let stageInProgress = false;+ const deliveries: {+ threadId: string;+ text: string;+ duringStage: boolean;+ accepted: boolean;+ }[] = [];+ const subscribe = staging.subscribeStagedThreadDraft;+ vi.spyOn(staging, 'subscribeStagedThreadDraft').mockImplementation((threadId, listener) =>+ subscribe(threadId, (text) => {+ const duringStage = stageInProgress;+ const accepted = listener(text);+ deliveries.push({ threadId, text, duringStage, accepted });+ return accepted;+ }),+ );+ const stage = () => {+ stageInProgress = true;+ try {+ staging.stageThreadDraft(info.threadId, 'Review this document');+ } finally {+ stageInProgress = false;+ }+ };++ await act(async () => {+ render(+ <StrictMode>+ <I18nProvider i18n={i18n}>+ <QueryClientProvider client={query}>+ <TooltipProvider>+ <BeforeLayout run={beforeLayout} />+ <ThreadView info={info} />+ <AfterSubscription stage={stage} />+ </TooltipProvider>+ </QueryClientProvider>+ </I18nProvider>+ </StrictMode>,+ );+ });++ expect(lifecycle).toHaveLength(1);+ await context.annotate(JSON.stringify({ lifecycle, deliveries }), 'registered draft delivery');+ const [lifetime] = lifecycle;+ expect(lifetime.liveBefore).toBeGreaterThan(0);+ expect(lifetime.timerCount).toBeGreaterThan(0);+ expect(lifetime.destroyedAfter).toBe(lifetime.liveBefore);+ expect(deliveries.filter((delivery) => delivery.duringStage)).toEqual([+ { threadId: info.threadId, text: 'Review this document', duringStage: true, accepted: false },+ ]);+ expect(deliveries).toContainEqual({+ threadId: info.threadId,+ text: 'Review this document',+ duringStage: false,+ accepted: true,+ });+ expect(errors).not.toHaveBeenCalled();+ expect(warnings).not.toHaveBeenCalled();+ expect(screen.getByRole('textbox', { name: 'Message Echo' }).textContent).toBe(+ 'Review this document',+ );+ });+});diff --git a/packages/app/src/components/acp/ThreadView.tsx b/packages/app/src/components/acp/ThreadView.tsxindex b07003a0a..b51c3f120 100644--- a/packages/app/src/components/acp/ThreadView.tsx+++ b/packages/app/src/components/acp/ThreadView.tsx@@ -169,6 +169,8 @@ import {useAgentThreadModel,} from '@/lib/acp/thread-client';import {+ flushStagedThreadDraft,+ flushStagedThreadDraftContent,registerThreadDraftReader,subscribeStagedThreadDraft,subscribeStagedThreadDraftContent,@@ -599,14 +601,15 @@ export function ThreadView({useEffect(() => {const stopStaging = subscribeStagedThreadDraft(info.threadId, (text) => {- composerRef.current?.appendText(text);+ return composerRef.current?.appendText(text) ?? false;});const stopStagingContent = subscribeStagedThreadDraftContent(info.threadId, (content) => {- composerRef.current?.setDoc(content.doc);- if (content.attachments.length > 0) {+ const accepted = composerRef.current?.setDoc(content.doc) ?? false;+ if (accepted && content.attachments.length > 0) {attachmentsRef.current = [...attachmentsRef.current, ...content.attachments];setPendingAttachments(attachmentsRef.current);}+ return accepted;});return () => {stopStagingContent();@@ -1544,6 +1547,10 @@ export function ThreadView({hasStartedWork={threadHasUserMessage({ items })}onNewChat={startFreshThread}composerRef={composerRef}+ onComposerReady={() => {+ flushStagedThreadDraft(info.threadId);+ flushStagedThreadDraftContent(info.threadId);+ }}mentionRecency={mentionRecency}onSubmit={submit}canPrompt={canPrompt}@@ -4396,6 +4403,7 @@ function ThreadComposer({hasStartedWork,onNewChat,composerRef,+ onComposerReady,mentionRecency,onSubmit,canPrompt,@@ -4424,6 +4432,7 @@ function ThreadComposer({hasStartedWork: boolean;onNewChat: () => void;composerRef: RefObject<ComposerMentionInputHandle | null>;+ onComposerReady: () => void;mentionRecency: MentionRecency;onSubmit: () => void;canPrompt: boolean;@@ -4555,6 +4564,7 @@ function ThreadComposer({<div className="relative"><ComposerMentionInputref={composerRef}+ onReady={onComposerReady}ariaLabel={t`Message ${agentName}`}ariaDescribedBy={placeholderRotating ? composerHintId : undefined}onEmptyChange={setIsEmpty}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 a464be6b4..919ca9320 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@@ -85,9 +85,11 @@ export function MockComposerMentionInput({},appendText: (text: string) => {const el = localRef.current;- if (!el || text === '') return;+ if (text === '') return true;+ if (!el) return false;el.value = el.value.trim() === '' ? text : `${el.value.replace(/\s+$/, '')}\n\n${text}`;notify();+ return true;},getDoc: () => ({type: 'doc',@@ -100,8 +102,11 @@ export function MockComposerMentionInput({),}),setDoc: (doc) => {- if (localRef.current) localRef.current.value = docPlainText(doc);+ const el = localRef.current;+ if (!el) return false;+ el.value = docPlainText(doc);notify();+ return true;},getContent: () => ({instruction: localRef.current?.value ?? '',diff --git a/packages/app/src/editor/ComposerMentionInput.tsx b/packages/app/src/editor/ComposerMentionInput.tsxindex 6fa632dc7..008520252 100644--- a/packages/app/src/editor/ComposerMentionInput.tsx+++ b/packages/app/src/editor/ComposerMentionInput.tsx@@ -51,9 +51,9 @@ export interface ComposerMentionInputHandle {blur: () => void;clear: () => void;setText: (text: string) => void;- appendText: (text: string) => void;+ appendText: (text: string) => boolean;getDoc: () => JSONContent | null;- setDoc: (doc: JSONContent) => void;+ setDoc: (doc: JSONContent) => boolean;getContent: () => {instruction: string;mentions: string[];@@ -77,6 +77,7 @@ export function ComposerMentionInput({onEmptyChange,onContentChange,onMentionsChange,+ onReady,onSubmit,onEscape,className,@@ -94,6 +95,7 @@ export function ComposerMentionInput({onEmptyChange: (isEmpty: boolean) => void;onContentChange?: (doc: JSONContent) => void;onMentionsChange?: (mentions: string[]) => void;+ onReady?: () => void;onSubmit: () => void;onEscape?: () => void;className?: string;@@ -124,12 +126,14 @@ export function ComposerMentionInput({const onMentionsChangeRef = useRef(onMentionsChange);const onSubmitRef = useRef(onSubmit);const onEscapeRef = useRef(onEscape);+ const onReadyRef = useRef(onReady);useEffect(() => {onEmptyChangeRef.current = onEmptyChange;onContentChangeRef.current = onContentChange;onMentionsChangeRef.current = onMentionsChange;onSubmitRef.current = onSubmit;onEscapeRef.current = onEscape;+ onReadyRef.current = onReady;});const editor = useEditor({@@ -253,23 +257,26 @@ export function ComposerMentionInput({notifyContentMutation();},appendText: (text: string) => {- if (!editor || text === '') return;- if (isComposerEmpty(editor)) {- editor.commands.setContent(textToParagraphs(text));- } else {- editor.commands.insertContentAt(editor.state.doc.content.size, [- { type: 'paragraph', content: [] },- ...textToParagraphs(text),- ]);- }- notifyContentMutation();+ if (text === '') return true;+ if (!editor || editor.isDestroyed) return false;+ const inserted = isComposerEmpty(editor)+ ? editor.commands.setContent(textToParagraphs(text))+ : editor.commands.insertContentAt(editor.state.doc.content.size, [+ { type: 'paragraph', content: [] },+ ...textToParagraphs(text),+ ]);+ if (inserted) notifyContentMutation();+ return inserted;},getDoc: () => (editor ? editor.getJSON() : null),setDoc: (doc: JSONContent) => {- if (!editor) return;- editor.commands.setContent(doc);- reconcileCommandNodes(editor);- notifyContentMutation();+ if (!editor || editor.isDestroyed) return false;+ const applied = editor.commands.setContent(doc);+ if (applied) {+ reconcileCommandNodes(editor);+ notifyContentMutation();+ }+ return applied;},getContent: () =>editor@@ -287,6 +294,11 @@ export function ComposerMentionInput({};}, [editor]);+ useEffect(() => {+ if (!editor || editor.isDestroyed) return;+ onReadyRef.current?.();+ }, [editor]);+const dropPolicy = attachmentDrop;const dropSurfaceProps =dropPolicy.kind === 'host'diff --git a/packages/app/src/lib/acp/thread-draft-staging.test.ts b/packages/app/src/lib/acp/thread-draft-staging.test.tsindex 67a7488a4..d2328fcf6 100644--- a/packages/app/src/lib/acp/thread-draft-staging.test.ts+++ b/packages/app/src/lib/acp/thread-draft-staging.test.ts@@ -1,5 +1,6 @@import { afterEach, describe, expect, test, vi } from 'vitest';import {+ flushStagedThreadDraftContent,isEmptyThreadDraft,readThreadDraft,registerThreadDraftReader,@@ -18,13 +19,19 @@ describe('thread draft staging', () => {test('delivers to a subscriber that arrives AFTER the stage', () => {stageThreadDraft('thread-1', 'fix this lint error');const seen: string[] = [];- subscribeStagedThreadDraft('thread-1', (text) => seen.push(text));+ subscribeStagedThreadDraft('thread-1', (text) => {+ seen.push(text);+ return true;+ });expect(seen).toEqual(['fix this lint error']);});test('delivers to a subscriber that arrives BEFORE the stage', () => {const seen: string[] = [];- subscribeStagedThreadDraft('thread-1', (text) => seen.push(text));+ subscribeStagedThreadDraft('thread-1', (text) => {+ seen.push(text);+ return true;+ });stageThreadDraft('thread-1', 'fix this lint error');expect(seen).toEqual(['fix this lint error']);});@@ -32,10 +39,16 @@ describe('thread draft staging', () => {test('consumes exactly once', () => {stageThreadDraft('thread-1', 'first');const first: string[] = [];- const stop = subscribeStagedThreadDraft('thread-1', (text) => first.push(text));+ const stop = subscribeStagedThreadDraft('thread-1', (text) => {+ first.push(text);+ return true;+ });stop();const second: string[] = [];- subscribeStagedThreadDraft('thread-1', (text) => second.push(text));+ subscribeStagedThreadDraft('thread-1', (text) => {+ second.push(text);+ return true;+ });expect(first).toEqual(['first']);expect(second).toEqual([]);});@@ -45,30 +58,42 @@ describe('thread draft staging', () => {stageThreadDraft('thread-2', 'for two');const one: string[] = [];const two: string[] = [];- subscribeStagedThreadDraft('thread-1', (text) => one.push(text));- subscribeStagedThreadDraft('thread-2', (text) => two.push(text));+ subscribeStagedThreadDraft('thread-1', (text) => {+ one.push(text);+ return true;+ });+ subscribeStagedThreadDraft('thread-2', (text) => {+ two.push(text);+ return true;+ });expect(one).toEqual(['for one']);expect(two).toEqual(['for two']);});test.each([' ', '', '\n\t '])('ignores whitespace-only text (%j)', (text) => {const seen: string[] = [];- subscribeStagedThreadDraft('thread-1', (t) => seen.push(t));+ subscribeStagedThreadDraft('thread-1', (t) => {+ seen.push(t);+ return true;+ });stageThreadDraft('thread-1', text);expect(seen).toEqual([]);});test('unsubscribe stops delivery', () => {const seen: string[] = [];- const stop = subscribeStagedThreadDraft('thread-1', (text) => seen.push(text));+ const stop = subscribeStagedThreadDraft('thread-1', (text) => {+ seen.push(text);+ return true;+ });stop();stageThreadDraft('thread-1', 'too late');expect(seen).toEqual([]);});test('a stale unsubscribe does not evict a newer listener', () => {- const older = vi.fn();- const newer = vi.fn();+ const older = vi.fn(() => true);+ const newer = vi.fn(() => true);const stopOlder = subscribeStagedThreadDraft('thread-1', older);subscribeStagedThreadDraft('thread-1', newer);stopOlder();@@ -126,20 +151,61 @@ describe('thread draft content staging', () => {test('holds content until a subscriber arrives, then delivers it once', () => {stageThreadDraftContent('t3', content);const seen: unknown[] = [];- const stop = subscribeStagedThreadDraftContent('t3', (c) => seen.push(c));+ const stop = subscribeStagedThreadDraftContent('t3', (c) => {+ seen.push(c);+ return true;+ });expect(seen).toEqual([content]);stop();const later: unknown[] = [];- const stopLater = subscribeStagedThreadDraftContent('t3', (c) => later.push(c));+ const stopLater = subscribeStagedThreadDraftContent('t3', (c) => {+ later.push(c);+ return true;+ });expect(later).toEqual([]);stopLater();});test('delivers straight to a live subscriber', () => {const seen: unknown[] = [];- const stop = subscribeStagedThreadDraftContent('t4', (c) => seen.push(c));+ const stop = subscribeStagedThreadDraftContent('t4', (c) => {+ seen.push(c);+ return true;+ });stageThreadDraftContent('t4', content);expect(seen).toEqual([content]);stop();});++ test('keeps held content a subscriber rejects for the next subscriber, then delivers it once', () => {+ stageThreadDraftContent('t5', content);+ const rejected: unknown[] = [];+ subscribeStagedThreadDraftContent('t5', (c) => {+ rejected.push(c);+ return false;+ });+ const accepted: unknown[] = [];+ subscribeStagedThreadDraftContent('t5', (c) => {+ accepted.push(c);+ return true;+ });+ flushStagedThreadDraftContent('t5');+ expect(rejected).toEqual([content]);+ expect(accepted).toEqual([content]);+ });++ test('keeps content a live subscriber rejects until a later flush lands it', () => {+ let ready = false;+ const seen: unknown[] = [];+ subscribeStagedThreadDraftContent('t6', (c) => {+ seen.push(c);+ return ready;+ });+ stageThreadDraftContent('t6', content);+ expect(seen).toEqual([content]);+ ready = true;+ flushStagedThreadDraftContent('t6');+ flushStagedThreadDraftContent('t6');+ expect(seen).toEqual([content, content]);+ });});diff --git a/packages/app/src/lib/acp/thread-draft-staging.ts b/packages/app/src/lib/acp/thread-draft-staging.tsindex 0f5342059..f6e598fe3 100644--- a/packages/app/src/lib/acp/thread-draft-staging.ts+++ b/packages/app/src/lib/acp/thread-draft-staging.ts@@ -15,58 +15,56 @@ export interface ThreadDraftSnapshot {const pending = new Map<string, string>();-const listeners = new Map<string, (text: string) => void>();+const listeners = new Map<string, (text: string) => boolean>();const pendingContent = new Map<string, ThreadDraftContent>();-const contentListeners = new Map<string, (content: ThreadDraftContent) => void>();+const contentListeners = new Map<string, (content: ThreadDraftContent) => boolean>();const readers = new Map<string, () => ThreadDraftSnapshot>();export function stageThreadDraft(threadId: string, text: string): void {if (text.trim() === '') return;- const listener = listeners.get(threadId);- if (listener !== undefined) {- listener(text);- return;- }pending.set(threadId, text);+ flushStagedThreadDraft(threadId);+}++export function flushStagedThreadDraft(threadId: string): void {+ const text = pending.get(threadId);+ const listener = listeners.get(threadId);+ if (text === undefined || listener === undefined) return;+ if (listener(text) === true) pending.delete(threadId);}export function subscribeStagedThreadDraft(threadId: string,- onDraft: (text: string) => void,+ onDraft: (text: string) => boolean,): () => void {listeners.set(threadId, onDraft);- const held = pending.get(threadId);- if (held !== undefined) {- pending.delete(threadId);- onDraft(held);- }+ flushStagedThreadDraft(threadId);return () => {if (listeners.get(threadId) === onDraft) listeners.delete(threadId);};}export function stageThreadDraftContent(threadId: string, content: ThreadDraftContent): void {- const listener = contentListeners.get(threadId);- if (listener !== undefined) {- listener(content);- return;- }pendingContent.set(threadId, content);+ flushStagedThreadDraftContent(threadId);+}++export function flushStagedThreadDraftContent(threadId: string): void {+ const content = pendingContent.get(threadId);+ const listener = contentListeners.get(threadId);+ if (content === undefined || listener === undefined) return;+ if (listener(content) === true) pendingContent.delete(threadId);}export function subscribeStagedThreadDraftContent(threadId: string,- onContent: (content: ThreadDraftContent) => void,+ onContent: (content: ThreadDraftContent) => boolean,): () => void {contentListeners.set(threadId, onContent);- const held = pendingContent.get(threadId);- if (held !== undefined) {- pendingContent.delete(threadId);- onContent(held);- }+ flushStagedThreadDraftContent(threadId);return () => {if (contentListeners.get(threadId) === onContent) contentListeners.delete(threadId);};