Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
MUL-4864 fix(chat): use a single New Chat draft, keyed by session not agent (#5519)
Naiyuan Qingc52ebeaa0fbf
diff --git a/packages/core/chat/index.ts b/packages/core/chat/index.tsindex 1f66e56250..09789fa2cd 100644--- a/packages/core/chat/index.ts+++ b/packages/core/chat/index.ts@@ -1,4 +1,4 @@-export { createChatStore, CHAT_MIN_W, CHAT_MIN_H, CHAT_DEFAULT_W, CHAT_DEFAULT_H, DRAFT_NEW_SESSION, newSessionDraftKey } from "./store";+export { createChatStore, CHAT_MIN_W, CHAT_MIN_H, CHAT_DEFAULT_W, CHAT_DEFAULT_H, DRAFT_NEW_SESSION } from "./store";export type { ChatStoreOptions, ChatState, ChatTimelineItem } from "./store";export { useRecentContextStore, selectRecentContexts } from "./recent-context-store";export type { RecentContextEntry, RecentContextType } from "./recent-context-store";diff --git a/packages/core/chat/store.test.ts b/packages/core/chat/store.test.tsindex 762977eaf1..3e11ef04e2 100644--- a/packages/core/chat/store.test.ts+++ b/packages/core/chat/store.test.ts@@ -1,5 +1,5 @@import { beforeEach, describe, expect, it } from "vitest";-import { createChatStore, newSessionDraftKey } from "./store";+import { createChatStore, DRAFT_NEW_SESSION } from "./store";import type { StorageAdapter } from "../types";import type { Attachment } from "../types";@@ -36,10 +36,112 @@ function makeAttachment(id: string): Attachment {};}-describe("newSessionDraftKey", () => {- it("derives a stable per-agent slot for an uncreated chat", () => {- expect(newSessionDraftKey("agent-1")).toBe("__new__:agent-1");- expect(newSessionDraftKey(null)).toBe("__new__:");+// The pre-MUL-4864 scheme kept one new-chat draft per agent, in `__new__:<id>`+// slots. Those slots have no timestamp, so on upgrade only one can survive:+// the one for the agent the workspace has selected — the draft the user would+// have been shown. The rest were the invisible multi-draft state, and go.+describe("chat store — legacy per-agent new-chat draft migration", () => {+ const DRAFTS_KEY = "multica:chat:drafts";+ const ATTACHMENTS_KEY = "multica:chat:draft-attachments";+ const AGENT_KEY = "multica:chat:selectedAgentId";++ it("adopts the selected agent's legacy draft into the single new-chat slot", () => {+ const storage = memStorage();+ storage.setItem(AGENT_KEY, "agent-1");+ storage.setItem(+ DRAFTS_KEY,+ JSON.stringify({ "__new__:agent-1": "mine", "__new__:agent-2": "other" }),+ );++ const store = createChatStore({ storage });++ expect(store.getState().inputDrafts).toEqual({ [DRAFT_NEW_SESSION]: "mine" });+ });++ it("migrates the matching attachments with the text, not another agent's", () => {+ const storage = memStorage();+ storage.setItem(AGENT_KEY, "agent-1");+ storage.setItem(DRAFTS_KEY, JSON.stringify({ "__new__:agent-1": "mine" }));+ storage.setItem(+ ATTACHMENTS_KEY,+ JSON.stringify({+ "__new__:agent-1": [makeAttachment("att-mine")],+ "__new__:agent-2": [makeAttachment("att-other")],+ }),+ );++ const store = createChatStore({ storage });++ expect(store.getState().inputDraftAttachments[DRAFT_NEW_SESSION]?.map((a) => a.id)).toEqual([+ "att-mine",+ ]);+ expect(store.getState().inputDraftAttachments["__new__:agent-2"]).toBeUndefined();+ });++ it("persists the migration so the legacy slots do not come back on reload", () => {+ const storage = memStorage();+ storage.setItem(AGENT_KEY, "agent-1");+ storage.setItem(+ DRAFTS_KEY,+ JSON.stringify({ "__new__:agent-1": "mine", "__new__:agent-2": "other" }),+ );++ createChatStore({ storage });+ // A second store reads what the first one wrote — this is the reload.+ const reloaded = createChatStore({ storage });++ expect(JSON.parse(storage.getItem(DRAFTS_KEY) ?? "{}")).toEqual({ [DRAFT_NEW_SESSION]: "mine" });+ expect(reloaded.getState().inputDrafts).toEqual({ [DRAFT_NEW_SESSION]: "mine" });+ });++ it("drops every legacy slot when no agent is selected", () => {+ const storage = memStorage();+ storage.setItem(DRAFTS_KEY, JSON.stringify({ "__new__:agent-1": "a", "__new__:agent-2": "b" }));++ const store = createChatStore({ storage });++ expect(store.getState().inputDrafts).toEqual({});+ expect(storage.getItem(DRAFTS_KEY)).toBeNull();+ });++ it("leaves real session drafts untouched", () => {+ const storage = memStorage();+ storage.setItem(AGENT_KEY, "agent-1");+ storage.setItem(+ DRAFTS_KEY,+ JSON.stringify({ "session-a": "draft A", "session-b": "draft B", "__new__:agent-1": "mine" }),+ );++ const store = createChatStore({ storage });++ expect(store.getState().inputDrafts).toEqual({+ "session-a": "draft A",+ "session-b": "draft B",+ [DRAFT_NEW_SESSION]: "mine",+ });+ });++ it("keeps a current-scheme draft rather than overwriting it with a legacy one", () => {+ const storage = memStorage();+ storage.setItem(AGENT_KEY, "agent-1");+ storage.setItem(+ DRAFTS_KEY,+ JSON.stringify({ [DRAFT_NEW_SESSION]: "current", "__new__:agent-1": "stale" }),+ );++ const store = createChatStore({ storage });++ expect(store.getState().inputDrafts).toEqual({ [DRAFT_NEW_SESSION]: "current" });+ });++ it("does not touch storage when there is nothing to migrate", () => {+ const storage = memStorage();+ storage.setItem(DRAFTS_KEY, JSON.stringify({ [DRAFT_NEW_SESSION]: "typed" }));+ const before = storage.getItem(DRAFTS_KEY);++ createChatStore({ storage });++ expect(storage.getItem(DRAFTS_KEY)).toBe(before);});});diff --git a/packages/core/chat/store.ts b/packages/core/chat/store.tsindex 127c197af2..5bdea3dfb6 100644--- a/packages/core/chat/store.ts+++ b/packages/core/chat/store.ts@@ -35,18 +35,17 @@ const APPLIED_RESTORES_KEY = "multica:chat:applied-draft-restores";* they are refetchable, so dropping one loses nothing.*/const PENDING_SEND_RESTORES_KEY = "multica:chat:pending-send-restores";-/** Placeholder sessionId for a chat that hasn't been created yet. */-export const DRAFT_NEW_SESSION = "__new__";-/**- * Draft storage key for an as-yet-uncreated chat with the given agent.- * Shared by ChatInput (which writes the draft) and ensureSession (which- * migrates it onto the real session id the moment the session is created),- * so the two never disagree on the slot name.+ * Draft slot for a chat that hasn't been created yet. There is exactly one per+ * workspace: the new-chat composer's identity is "the chat I have not created",+ * not "the chat I have not created with agent X". `selectedAgentId` is the send+ * target, not draft ownership, so switching agent mid-compose keeps the text+ * (MUL-4864). Created sessions keep their own slot, keyed by session id.*/-export function newSessionDraftKey(selectedAgentId: string | null): string {- return `${DRAFT_NEW_SESSION}:${selectedAgentId ?? ""}`;-}+export const DRAFT_NEW_SESSION = "__new__";++/** Pre-MUL-4864 per-agent new-chat slots, shaped `__new__:<agentId>`. */+const LEGACY_NEW_SESSION_PREFIX = `${DRAFT_NEW_SESSION}:`;const CHAT_WIDTH_KEY = "multica:chat:width";const CHAT_HEIGHT_KEY = "multica:chat:height";const CHAT_EXPANDED_KEY = "multica:chat:expanded";@@ -197,6 +196,64 @@ function writeDraftAttachments(}}+/**+ * Fold the legacy per-agent new-chat slots into the single DRAFT_NEW_SESSION+ * slot, then drop them.+ *+ * The legacy slots carry no timestamp, so when several exist there is no way to+ * tell which one the user typed last — and "keep them all" has nowhere to put+ * the losers now that there is one composer. Adopt the slot belonging to the+ * persisted `selectedAgentId` (the draft this workspace would have shown on+ * open, so the only one the user can be expecting) and discard the rest: those+ * extra slots ARE the invisible multi-draft state this change removes.+ *+ * Both write paths prune empty values, so key presence means content.+ * Idempotent: once the legacy keys are gone this is an allocation-free no-op.+ */+function migrateLegacyNewChatSlots<T>(+ slots: Record<string, T>,+ selectedAgentId: string | null,+): { slots: Record<string, T>; changed: boolean } {+ const legacyKeys = Object.keys(slots).filter((k) => k.startsWith(LEGACY_NEW_SESSION_PREFIX));+ if (legacyKeys.length === 0) return { slots, changed: false };+ const next = { ...slots };+ const adopted = next[`${LEGACY_NEW_SESSION_PREFIX}${selectedAgentId ?? ""}`];+ // Never clobber the unified slot: whatever is in it was written under the+ // current scheme and is therefore newer than any legacy leftover.+ if (!(DRAFT_NEW_SESSION in next) && adopted !== undefined) {+ next[DRAFT_NEW_SESSION] = adopted;+ }+ for (const key of legacyKeys) delete next[key];+ logger.info("migrating legacy per-agent new-chat drafts", {+ legacyCount: legacyKeys.length,+ selectedAgentId,+ adopted: DRAFT_NEW_SESSION in next,+ });+ return { slots: next, changed: true };+}++/**+ * Read both draft maps and migrate them together, against the same+ * `selectedAgentId` — text and attachments must never disagree on which legacy+ * new-chat draft survived, or the user gets agent A's words with agent B's+ * files.+ */+function loadDraftSlots(+ storage: StorageAdapter,+ draftsKey: string,+ attachmentsKey: string,+ selectedAgentId: string | null,+): { inputDrafts: Record<string, string>; inputDraftAttachments: Record<string, Attachment[]> } {+ const drafts = migrateLegacyNewChatSlots(readDrafts(storage, draftsKey), selectedAgentId);+ const attachments = migrateLegacyNewChatSlots(+ readDraftAttachments(storage, attachmentsKey),+ selectedAgentId,+ );+ if (drafts.changed) writeDrafts(storage, draftsKey, drafts.slots);+ if (attachments.changed) writeDraftAttachments(storage, attachmentsKey, attachments.slots);+ return { inputDrafts: drafts.slots, inputDraftAttachments: attachments.slots };+}+export const CHAT_MIN_W = 360;export const CHAT_MIN_H = 480;export const CHAT_DEFAULT_W = 380;@@ -294,13 +351,21 @@ export function createChatStore(options: ChatStoreOptions) {// (new user) resolves to enabled.const initialFloatingEnabled = storage.getItem(FLOATING_KEY) !== "false";+ const initialAgentId = storage.getItem(wsKey(AGENT_STORAGE_KEY));+ const initialDraftSlots = loadDraftSlots(+ storage,+ wsKey(DRAFTS_KEY),+ wsKey(DRAFT_ATTACHMENTS_KEY),+ initialAgentId,+ );+const store = create<ChatState>((set, get) => ({isOpen: initialIsOpen,floatingChatEnabled: initialFloatingEnabled,activeSessionId: storage.getItem(wsKey(SESSION_STORAGE_KEY)),- selectedAgentId: storage.getItem(wsKey(AGENT_STORAGE_KEY)),- inputDrafts: readDrafts(storage, wsKey(DRAFTS_KEY)),- inputDraftAttachments: readDraftAttachments(storage, wsKey(DRAFT_ATTACHMENTS_KEY)),+ selectedAgentId: initialAgentId,+ inputDrafts: initialDraftSlots.inputDrafts,+ inputDraftAttachments: initialDraftSlots.inputDraftAttachments,appliedDraftRestoreIds: readAppliedRestores(storage, wsKey(APPLIED_RESTORES_KEY)),pendingSendRestores: readPendingSendRestores(storage, wsKey(PENDING_SEND_RESTORES_KEY)),chatWidth: Number(storage.getItem(CHAT_WIDTH_KEY)) || CHAT_DEFAULT_W,@@ -456,8 +521,15 @@ export function createChatStore(options: ChatStoreOptions) {registerForWorkspaceRehydration(() => {const nextSession = storage.getItem(wsKey(SESSION_STORAGE_KEY));const nextAgent = storage.getItem(wsKey(AGENT_STORAGE_KEY));- const nextDrafts = readDrafts(storage, wsKey(DRAFTS_KEY));- const nextDraftAttachments = readDraftAttachments(storage, wsKey(DRAFT_ATTACHMENTS_KEY));+ // Drafts are namespaced per workspace, so the workspace being switched TO+ // has its own legacy slots to fold — migrate against that workspace's own+ // persisted agent, not the one we are leaving.+ const { inputDrafts: nextDrafts, inputDraftAttachments: nextDraftAttachments } = loadDraftSlots(+ storage,+ wsKey(DRAFTS_KEY),+ wsKey(DRAFT_ATTACHMENTS_KEY),+ nextAgent,+ );logger.info("workspace rehydration", {prevSession: store.getState().activeSessionId,nextSession,diff --git a/packages/views/chat/components/chat-input-draft-isolation.test.tsx b/packages/views/chat/components/chat-input-draft-isolation.test.tsxnew file mode 100644index 0000000000..93f47eabc4--- /dev/null+++ b/packages/views/chat/components/chat-input-draft-isolation.test.tsx@@ -0,0 +1,462 @@+import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";+import { act, fireEvent, render, screen } from "@testing-library/react";+import { I18nProvider } from "@multica/core/i18n/react";+import type { UploadResult } from "@multica/core/hooks/use-file-upload";+import enCommon from "../../locales/en/common.json";+import enChat from "../../locales/en/chat.json";++/**+ * Draft isolation across a composer switch, driven through the REAL+ * ContentEditor — its real 100ms `onUpdate` debounce, its real dirty guard,+ * and its real `onUpdateRef`-resolves-to-latest-render behavior.+ *+ * chat-input.test.tsx mocks ContentEditor with an instant `onUpdate`, which+ * cannot see this class of bug at all: the hazard only exists in the window+ * between a keystroke and its debounce firing. So only Tiptap's primitive is+ * mocked here (as in editor/content-editor.test.tsx); everything from+ * ContentEditor upward is the real component.+ *+ * The bug being pinned (MUL-4864 review): one editor instance serves every+ * chat draft. Typing in session A arms a debounce; switching to session B+ * before it fires means the timer runs with B's `draftKey` in scope, filing+ * A's document into B's draft — breaking "existing sessions keep independent+ * drafts" and risking A's context being sent to B's agent.+ */++const editorState = vi.hoisted(() => ({+ isFocused: false,+ isDestroyed: false,+ markdown: "",+ uploadingNodes: [] as Array<{ attrs: { uploading?: boolean } }>,+}));+const editorInstance = vi.hoisted<{ current: unknown }>(() => ({ current: null }));+const onCreateFired = vi.hoisted(() => ({ value: false }));+const transactionListeners = vi.hoisted(() => ({ current: [] as Array<() => void> }));+const latestEditorOptions = vi.hoisted<{+ current?: { onUpdate?: (args: { editor: unknown }) => void };+}>(() => ({}));+const mockSetContent = vi.hoisted(() => vi.fn());++vi.mock("@tanstack/react-query", () => ({+ useQueryClient: () => ({}),+}));+// Captures what ContentEditor wires into its extensions. `onSubmitRef` is the+// Mod+Enter path — it bypasses the SubmitButton entirely, which is why the+// send guards live inside the handler and not only in the button's disabled+// state.+const capturedExtOptions = vi.hoisted<{+ current?: { onSubmitRef?: { current?: () => void } };+}>(() => ({}));+vi.mock("../../editor/extensions", () => ({+ createEditorExtensions: (options: { onSubmitRef?: { current?: () => void } }) => {+ capturedExtOptions.current = options;+ return [];+ },+}));+// Mirrors the real contract that matters here: `handler` is captured at CALL+// time (content-editor passes `onUploadFileRef.current` when the upload+// starts), and on completion the real implementation dispatches into the SAME+// editor instance — which is what fires onUpdate. Tests drive that dispatch+// explicitly via `finishUpload()`.+vi.mock("../../editor/extensions/file-upload", () => ({+ uploadAndInsertFile: async (+ _editor: unknown,+ file: File,+ handler: (f: File) => Promise<unknown>,+ ) => {+ await handler(file);+ },+}));+vi.mock("../../editor/utils/preprocess", () => ({+ preprocessMarkdown: (value: string) => value,+}));+vi.mock("../../editor/utils/repair-list-items", () => ({+ repairEmptyListItems: vi.fn(() => false),+}));+vi.mock("../../editor/bubble-menu", () => ({+ EditorBubbleMenu: () => null,+}));+vi.mock("../../editor/attachment-download-context", () => ({+ AttachmentDownloadProvider: ({ children }: { children: React.ReactNode }) => <>{children}</>,+}));++vi.mock("@tiptap/react", () => ({+ useEditor: (options: {+ onCreate?: (args: { editor: unknown }) => void;+ onUpdate?: (args: { editor: unknown }) => void;+ }) => {+ latestEditorOptions.current = options;+ if (!editorInstance.current) {+ editorInstance.current = {+ get isFocused() {+ return editorState.isFocused;+ },+ get isDestroyed() {+ return editorState.isDestroyed;+ },+ commands: {+ focus: vi.fn(),+ blur: vi.fn(),+ clearContent: vi.fn(() => {+ editorState.markdown = "";+ }),+ setContent: mockSetContent,+ setTextSelection: vi.fn(),+ },+ getMarkdown: () => editorState.markdown,+ on: (event: string, cb: () => void) => {+ if (event === "transaction") transactionListeners.current.push(cb);+ },+ off: (event: string, cb: () => void) => {+ if (event !== "transaction") return;+ transactionListeners.current = transactionListeners.current.filter((l) => l !== cb);+ },+ view: { dispatch: vi.fn() },+ state: {+ get tr() {+ return { __emptyTransaction: true };+ },+ doc: {+ content: { size: 0 },+ descendants: (cb: (node: { attrs: { uploading?: boolean } }) => boolean | void) => {+ for (const node of editorState.uploadingNodes) {+ if (cb(node) === false) break;+ }+ },+ },+ selection: { empty: true, from: 0, to: 0 },+ },+ };+ }+ if (!onCreateFired.value) {+ onCreateFired.value = true;+ options?.onCreate?.({ editor: editorInstance.current });+ }+ return editorInstance.current;+ },+ EditorContent: ({ className }: { className?: string }) => (+ <div className={className} data-testid="editor-content" />+ ),+}));++vi.mock("@multica/core/chat", () => {+ const state = {+ activeSessionId: null as string | null,+ selectedAgentId: "agent-1",+ inputDrafts: {} as Record<string, string>,+ inputDraftAttachments: {} as Record<string, unknown[]>,+ setInputDraft: vi.fn((key: string, value: string) => {+ state.inputDrafts[key] = value;+ }),+ setInputDraftAttachments: vi.fn(),+ addInputDraftAttachment: vi.fn(),+ clearInputDraft: vi.fn(),+ };+ return {+ DRAFT_NEW_SESSION: "__new__",+ useChatStore: Object.assign(+ (selector?: (s: typeof state) => unknown) => (selector ? selector(state) : state),+ { getState: () => state },+ ),+ };+});++import { ChatInput } from "./chat-input";+import { useChatStore } from "@multica/core/chat";++const TEST_RESOURCES = { en: { common: enCommon, chat: enChat } };++function makeUpload(id: string, filename: string): UploadResult {+ const link = `/api/attachments/${id}/download`;+ return {+ id,+ filename,+ workspace_id: "ws-1",+ issue_id: null,+ comment_id: null,+ chat_session_id: null,+ chat_message_id: null,+ uploader_type: "member",+ uploader_id: "user-1",+ url: link,+ download_url: link,+ markdown_url: link,+ content_type: "image/png",+ size_bytes: 1,+ created_at: new Date(0).toISOString(),+ markdownLink: link,+ link,+ };+}++function store() {+ return useChatStore.getState() as unknown as {+ activeSessionId: string | null;+ selectedAgentId: string;+ inputDrafts: Record<string, string>;+ inputDraftAttachments: Record<string, unknown[]>;+ };+}++function element(props: Partial<React.ComponentProps<typeof ChatInput>> = {}) {+ return (+ <I18nProvider locale="en" resources={TEST_RESOURCES}>+ <ChatInput onSend={vi.fn()} agentName="Multica" {...props} />+ </I18nProvider>+ );+}++/** ContentEditor publishes upload-queue flips off `editor.on("transaction")`,+ * not off onUpdate — every insert/dispatch below is a transaction in the real+ * editor, so the tests emit one too. */+function emitTransaction() {+ act(() => {+ for (const listener of [...transactionListeners.current]) listener();+ });+}++/** Put the editor in the state a live upload leaves it in: file-upload.ts+ * inserts a blob placeholder node (attrs.uploading = true) via a transaction,+ * so `hasUploadingNode` — and therefore Guard 0, `hasActiveUploads`, and the+ * host's upload gate — all report an upload in flight. */+function beginUpload(markdown: string) {+ editorState.uploadingNodes = [{ attrs: { uploading: true } }];+ type(markdown);+ emitTransaction();+}++/** What file-upload.ts does on completion: swap the blob for the CDN URL and+ * clear the uploading flag, then dispatch into the SAME editor instance. That+ * dispatch both fires onUpdate and, as a transaction, is how ContentEditor+ * publishes the flip that un-gates the host. */+function finishUpload(markdown: string) {+ editorState.uploadingNodes = [];+ type(markdown);+ emitTransaction();+}++/** Simulate real typing: move the document, then fire the editor's own+ * (debounced) onUpdate exactly as Tiptap would. */+function type(markdown: string) {+ editorState.markdown = markdown;+ act(() => {+ latestEditorOptions.current?.onUpdate?.({ editor: editorInstance.current });+ });+}++describe("ChatInput draft isolation across a composer switch (real debounce)", () => {+ beforeEach(() => {+ vi.useFakeTimers();+ editorState.isFocused = true;+ editorState.isDestroyed = false;+ editorState.markdown = "";+ editorState.uploadingNodes = [];+ editorInstance.current = null;+ onCreateFired.value = false;+ latestEditorOptions.current = undefined;+ mockSetContent.mockClear();+ const s = store();+ s.activeSessionId = null;+ s.selectedAgentId = "agent-1";+ s.inputDrafts = {};+ s.inputDraftAttachments = {};+ });++ afterEach(() => {+ vi.useRealTimers();+ });++ it("files unflushed keystrokes under the session they were typed in, never the one switched to", () => {+ store().activeSessionId = "session-a";+ const { rerender } = render(element());++ // Typed in A. The debounce is armed but has NOT fired — this is the whole+ // hazard window.+ type("secret plan for agent A");+ expect(store().inputDrafts).toEqual({});++ // User clicks session B inside that window.+ store().activeSessionId = "session-b";+ rerender(element());++ // A's words belong to A.+ expect(store().inputDrafts["session-a"]).toBe("secret plan for agent A");+ // …and must never have reached B.+ expect(store().inputDrafts["session-b"]).toBeUndefined();++ // The armed timer must not resurrect the cross-write after the fact.+ act(() => {+ vi.advanceTimersByTime(1000);+ });+ expect(store().inputDrafts["session-b"]).toBeUndefined();+ expect(store().inputDrafts["session-a"]).toBe("secret plan for agent A");+ });++ it("loads the incoming session's own draft instead of leaving the old document on screen", () => {+ store().activeSessionId = "session-a";+ store().inputDrafts["session-b"] = "B's own words";+ const { rerender } = render(element());++ type("A's unflushed words");+ store().activeSessionId = "session-b";+ rerender(element());++ // The dirty guard would have suppressed this sync; flushing clears the+ // dirt, so B's draft actually loads.+ expect(mockSetContent).toHaveBeenCalled();+ });++ it("keeps a New Chat draft intact when only the agent changes", () => {+ // The MUL-4864 headline behavior, verified through the real debounce:+ // switching agent does not move draftKey, so there is nothing to flush and+ // nothing to lose.+ const { rerender } = render(element());+ type("half a thought");++ store().selectedAgentId = "agent-2";+ rerender(element());++ act(() => {+ vi.advanceTimersByTime(1000);+ });+ // One slot, holding the text, still the New Chat slot.+ expect(store().inputDrafts).toEqual({ __new__: "half a thought" });+ });++ // An in-flight upload PINS the editor to the source document: Guard 0 in+ // ContentEditor refuses to setContent over an `uploading` node (doing so+ // strands the upload's finalize and the file vanishes). So while the upload+ // runs, the instance still holds A's document even though the user is on B —+ // and the upload's own completion dispatch fires onUpdate on that instance.+ // Every write it produces belongs to A, not to wherever the user navigated.+ //+ // `useUploadGate` does NOT protect this: it gates submit, not session/agent+ // navigation (use-chat-controller.ts handleSelectSession has no upload check).+ describe("with an upload in flight", () => {+ it("keeps the completing upload's markdown in the source draft, never the one switched to", () => {+ store().activeSessionId = "session-a";+ store().inputDrafts["session-b"] = "B's own words";+ const { rerender } = render(element());++ beginUpload("look at this ");++ // User clicks session B while the upload is still running.+ store().activeSessionId = "session-b";+ rerender(element());++ // Upload lands: blob → CDN URL, uploading flag cleared, dispatched into+ // the same instance.+ finishUpload("look at this ");+ act(() => {+ vi.advanceTimersByTime(1000);+ });++ // B must never receive A's body or its attachment URL.+ expect(store().inputDrafts["session-b"]).toBe("B's own words");+ // The upload result belongs to the draft it was started in.+ expect(store().inputDrafts["session-a"]).toBe(+ "look at this ",+ );+ });++ it("binds an attachment dropped while the editor is still pinned to the source draft", async () => {+ store().activeSessionId = "session-a";+ const onUploadFile = vi.fn(async (_file: File) => makeUpload("att-2", "second.png"));+ const { rerender } = render(element({ onUploadFile }));++ // An upload is already in flight, so Guard 0 pins the editor to A's+ // document.+ beginUpload("first ");+ store().activeSessionId = "session-b";+ rerender(element({ onUploadFile }));++ // The composer still shows A's document, so a file dropped now lands in+ // A's body — its attachment row has to bind to A, or the body and the+ // staged attachment end up in different drafts.+ await act(async () => {+ fireEvent.drop(screen.getByTestId("editor-content"), {+ dataTransfer: { files: [new File(["x"], "second.png", { type: "image/png" })] },+ });+ await Promise.resolve();+ });++ const addAttachment = (+ useChatStore.getState() as unknown as {+ addInputDraftAttachment: ReturnType<typeof vi.fn>;+ }+ ).addInputDraftAttachment;+ expect(addAttachment).toHaveBeenCalledWith(+ "session-a",+ expect.objectContaining({ id: "att-2" }),+ );+ expect(addAttachment).not.toHaveBeenCalledWith("session-b", expect.anything());+ });++ it("refuses to send while the composer still holds the source draft's document", () => {+ // The upload gate covers most of the pinned window, but not the sliver+ // between the upload's final dispatch (uploading node gone, so+ // `hasActiveUploads()` is already false) and the re-render that adopts —+ // React flushes that update on a scheduler task, so a click can land+ // first. Sending then would post A's text into B's session.+ store().activeSessionId = "session-a";+ const onSend = vi.fn();+ const { rerender } = render(element({ onSend }));++ beginUpload("A's words ");+ store().activeSessionId = "session-b";+ rerender(element({ onSend }));++ // Upload's node is gone, but no transaction has re-rendered us yet, so+ // the adopt has not run: the editor still holds A.+ editorState.uploadingNodes = [];+ act(() => {+ latestEditorOptions.current?.onUpdate?.({ editor: editorInstance.current });+ });++ // Mod+Enter, which skips the SubmitButton (and its disabled state)+ // entirely — the only way to actually reach handleSend in this window.+ act(() => {+ capturedExtOptions.current?.onSubmitRef?.current?.();+ });++ expect(onSend).not.toHaveBeenCalled();+ });++ it("loads the target draft once the upload guard clears", () => {+ store().activeSessionId = "session-a";+ store().inputDrafts["session-b"] = "B's own words";+ const { rerender } = render(element());++ beginUpload("uploading ");+ store().activeSessionId = "session-b";+ rerender(element());++ // Guard 0 blocks the sync while the upload runs — and it CONSUMES the+ // defaultValue change (lastDefaultValueRef advances before the guard), so+ // nothing re-applies it later on its own.+ mockSetContent.mockClear();++ finishUpload("uploaded ");+ act(() => {+ vi.advanceTimersByTime(1000);+ });++ // The composer must end up showing B's draft, not A's document.+ expect(mockSetContent).toHaveBeenCalled();+ });+ });++ it("does not strand the last keystrokes when a lazy session create re-keys the draft mid-compose", () => {+ // First send / first upload in a New Chat flips activeSessionId null → uuid+ // under a live editor. Those bytes were typed in the New Chat slot, so they+ // must land there, not be dropped or filed under the new session.+ const { rerender } = render(element());+ type("creating a session with this");++ store().activeSessionId = "session-new";+ rerender(element());++ expect(store().inputDrafts["__new__"]).toBe("creating a session with this");+ expect(store().inputDrafts["session-new"]).toBeUndefined();+ });+});diff --git a/packages/views/chat/components/chat-input.test.tsx b/packages/views/chat/components/chat-input.test.tsxindex 721f6161f9..b97074378e 100644--- a/packages/views/chat/components/chat-input.test.tsx+++ b/packages/views/chat/components/chat-input.test.tsx@@ -114,6 +114,16 @@ vi.mock("../../editor", async () => ({}},hasActiveUploads: () => uploadingRef.current > 0,+ // This mock emits onUpdate synchronously, so a pending debounced update+ // never exists and there is nothing to hand back. The real debounce (and+ // the draft-switch flush that depends on it) is covered against the real+ // ContentEditor in chat-input-draft-isolation.test.tsx.+ flushPendingUpdate: () => null,+ // Same file: the upload-pinned adopt path needs the real Guard 0, which+ // this mock has no concept of. Kept so the ref honours the full contract.+ adoptContent: (markdown: string) => {+ valueRef.current = markdown;+ },}));return (<textarea@@ -143,7 +153,6 @@ vi.mock("@multica/core/chat", () => {};return {DRAFT_NEW_SESSION: "__draft_new__",- newSessionDraftKey: (agentId: string | null) => `__draft_new__:${agentId ?? ""}`,useChatStore: Object.assign((selector?: (s: typeof state) => unknown) =>selector ? selector(state) : state,@@ -224,6 +233,93 @@ function element(props: Partial<React.ComponentProps<typeof ChatInput>>) {);}+// MUL-4864: an uncreated chat has ONE draft per workspace. `selectedAgentId`+// picks where the first send goes; it does not own the draft. Switching agent+// mid-compose must therefore change nothing the user can see.+describe("ChatInput new-chat draft identity", () => {+ function switchAgentTo(agentId: string, rerender: (ui: React.ReactElement) => void) {+ const state = useChatStore.getState() as unknown as { selectedAgentId: string };+ state.selectedAgentId = agentId;+ // The mock store is not reactive; a real store switch re-renders the tree.+ rerender(element({ agentName: agentId }));+ }++ it("writes to the single new-chat slot regardless of the selected agent", () => {+ const { rerender } = render(element({ agentName: "agent-1" }));++ fireEvent.change(screen.getByTestId("editor"), { target: { value: "half a thought" } });+ switchAgentTo("agent-2", rerender);+ fireEvent.change(screen.getByTestId("editor"), { target: { value: "half a thought, finished" } });++ const state = useChatStore.getState() as unknown as { inputDrafts: Record<string, string> };+ // One slot, not one per agent — the hidden multi-draft state is gone.+ expect(Object.keys(state.inputDrafts)).toEqual(["__draft_new__"]);+ expect(state.inputDrafts["__draft_new__"]).toBe("half a thought, finished");+ });++ it("keeps the live editor instance across an agent switch", () => {+ const { rerender } = render(element({ agentName: "agent-1" }));+ const before = screen.getByTestId("editor");++ switchAgentTo("agent-2", rerender);++ // Identity, not just content: a remount would silently drop whatever the+ // 100ms draft debounce had not yet persisted — the last thing typed.+ expect(screen.getByTestId("editor")).toBe(before);+ });++ it("keeps text the draft debounce has not persisted yet across an agent switch", () => {+ const { rerender } = render(element({ agentName: "agent-1" }));+ // The uncontrolled textarea models the live editor document: text lives in+ // the instance, and only a remount can lose it.+ const editor = screen.getByTestId("editor") as HTMLTextAreaElement;+ fireEvent.change(editor, { target: { value: "unsaved words" } });++ switchAgentTo("agent-2", rerender);++ expect((screen.getByTestId("editor") as HTMLTextAreaElement).value).toBe("unsaved words");+ });++ it("keeps staged attachments across an agent switch", async () => {+ const onUploadFile = vi.fn(async (_file: File) =>+ makeUpload({ id: "att-kept", link: "/api/attachments/att-kept/download", filename: "a.png" }),+ );+ const { rerender } = render(element({ agentName: "agent-1", onUploadFile }));++ await act(async () => {+ dropHandlers.onDrop?.([new File(["x"], "a.png", { type: "image/png" })]);+ await Promise.resolve();+ });+ switchAgentTo("agent-2", rerender);++ const state = useChatStore.getState() as unknown as {+ inputDraftAttachments: Record<string, UploadResult[]>;+ };+ // Body and attachments share one attribution rule, so the files follow the+ // text across the switch instead of stranding in the old agent's slot.+ expect(state.inputDraftAttachments["__draft_new__"]?.map((a) => a.id)).toEqual(["att-kept"]);+ expect(Object.keys(state.inputDraftAttachments)).toEqual(["__draft_new__"]);+ });++ it("still gives each created session its own draft slot", () => {+ const state = useChatStore.getState() as unknown as {+ activeSessionId: string | null;+ inputDrafts: Record<string, string>;+ };+ state.activeSessionId = "session-a";+ const { rerender } = render(element({ agentName: "agent-1" }));+ fireEvent.change(screen.getByTestId("editor"), { target: { value: "for A" } });++ state.activeSessionId = "session-b";+ rerender(element({ agentName: "agent-1" }));+ fireEvent.change(screen.getByTestId("editor"), { target: { value: "for B" } });++ // Real sessions stay isolated — unifying the NEW-chat draft must not bleed+ // one conversation's context into another.+ expect(state.inputDrafts).toEqual({ "session-a": "for A", "session-b": "for B" });+ });+});+describe("ChatInput focusRequest", () => {it("focuses the editor when focusRequest becomes a non-zero value (new chat)", () => {const { rerender } = render(@@ -317,7 +413,7 @@ describe("ChatInput attachment wiring", () => {const [, ids] = onSend.mock.calls[0]!;expect(ids).toEqual(["att-42"]);expect(useChatStore.getState().addInputDraftAttachment).toHaveBeenCalledWith(- "__draft_new__:agent-1",+ "__draft_new__",expect.objectContaining({ id: "att-42" }),);});@@ -443,7 +539,7 @@ describe("ChatInput async send", () => {await waitFor(() => {expect(useChatStore.getState().setInputDraft).toHaveBeenCalledWith(- "__draft_new__:agent-1",+ "__draft_new__","bring this back",);expect(editorProps.last?.defaultValue).toBe("bring this back");@@ -461,7 +557,7 @@ describe("ChatInput async send", () => {inputDrafts: Record<string, string>;setInputDraft: ReturnType<typeof vi.fn>;};- state.inputDrafts["__draft_new__:agent-1"] = "already typing";+ state.inputDrafts["__draft_new__"] = "already typing";const onRestoreDraftApplied = vi.fn();const { rerender } = render(@@ -476,13 +572,13 @@ describe("ChatInput async send", () => {});expect(onRestoreDraftApplied).not.toHaveBeenCalled();expect(state.setInputDraft).not.toHaveBeenCalledWith(- "__draft_new__:agent-1",+ "__draft_new__","bring this back",);// The user sends/clears what they were typing: the same restore, still// pending, now lands.- state.inputDrafts["__draft_new__:agent-1"] = "";+ state.inputDrafts["__draft_new__"] = "";rerender(element({restoreDraftRequest: { id: "msg-restored", content: "bring this back" },@@ -492,7 +588,7 @@ describe("ChatInput async send", () => {await waitFor(() => {expect(state.setInputDraft).toHaveBeenCalledWith(- "__draft_new__:agent-1",+ "__draft_new__","bring this back",);expect(onRestoreDraftApplied).toHaveBeenCalledTimes(1);@@ -505,7 +601,7 @@ describe("ChatInput async send", () => {setInputDraft: ReturnType<typeof vi.fn>;setInputDraftAttachments: ReturnType<typeof vi.fn>;};- state.inputDraftAttachments["__draft_new__:agent-1"] = [{ id: "att-staged" }];+ state.inputDraftAttachments["__draft_new__"] = [{ id: "att-staged" }];const onRestoreDraftApplied = vi.fn();renderInput({@@ -523,7 +619,7 @@ describe("ChatInput async send", () => {// The staged attachment list must never be replaced by the restore.expect(state.setInputDraftAttachments).not.toHaveBeenCalled();expect(state.setInputDraft).not.toHaveBeenCalledWith(- "__draft_new__:agent-1",+ "__draft_new__","bring this back",);});@@ -561,7 +657,7 @@ describe("ChatInput async send", () => {commitInput({ extraDraftKeys: ["session-1"] });});- expect(useChatStore.getState().clearInputDraft).toHaveBeenCalledWith("__draft_new__:agent-1");+ expect(useChatStore.getState().clearInputDraft).toHaveBeenCalledWith("__draft_new__");expect(useChatStore.getState().clearInputDraft).toHaveBeenCalledWith("session-1");await act(async () => {@@ -604,8 +700,8 @@ describe("ChatInput async send", () => {link: "/api/attachments/att-persisted/download",filename: "persisted.png",});- state.inputDrafts["__draft_new__:agent-1"] = "see ";- state.inputDraftAttachments["__draft_new__:agent-1"] = [attachment];+ state.inputDrafts["__draft_new__"] = "see ";+ state.inputDraftAttachments["__draft_new__"] = [attachment];const onSend = vi.fn<ChatInputOnSend>((_content, _ids, commitInput) => {commitInput();@@ -781,7 +877,7 @@ describe("ChatInput commit handoff", () => {expect(editorState.cleared).toBeGreaterThan(0);expect(editorState.blurred).toBeGreaterThan(0);- expect(useChatStore.getState().clearInputDraft).toHaveBeenCalledWith("__draft_new__:agent-1");+ expect(useChatStore.getState().clearInputDraft).toHaveBeenCalledWith("__draft_new__");});it("leaves the editor intact on a fire-and-forget commit but still clears the sent draft", async () => {@@ -795,6 +891,6 @@ describe("ChatInput commit handoff", () => {expect(editorState.cleared).toBe(0);expect(editorState.blurred).toBe(0);// …but the sent session's persisted draft is cleared regardless.- expect(useChatStore.getState().clearInputDraft).toHaveBeenCalledWith("__draft_new__:agent-1");+ expect(useChatStore.getState().clearInputDraft).toHaveBeenCalledWith("__draft_new__");});});diff --git a/packages/views/chat/components/chat-input.tsx b/packages/views/chat/components/chat-input.tsxindex 0914c31727..cf3d4bb1ec 100644--- a/packages/views/chat/components/chat-input.tsx+++ b/packages/views/chat/components/chat-input.tsx@@ -1,7 +1,7 @@"use client";import type { ReactNode } from "react";-import { useCallback, useEffect, useRef, useState } from "react";+import { useCallback, useEffect, useLayoutEffect, useRef, useState } from "react";import { cn } from "@multica/ui/lib/utils";import {ContentEditor,@@ -12,7 +12,7 @@ import {} from "../../editor";import { SubmitButton } from "@multica/ui/components/common/submit-button";import { ChatAddMenu } from "./chat-add-menu";-import { useChatStore, newSessionDraftKey } from "@multica/core/chat";+import { useChatStore, DRAFT_NEW_SESSION } from "@multica/core/chat";import { createLogger } from "@multica/core/logger";import { formatShortcut, useShortcut } from "@multica/core/shortcuts";import type { UploadResult } from "@multica/core/hooks/use-file-upload";@@ -22,6 +22,8 @@ import { useT } from "../../i18n";const logger = createLogger("chat.ui");const EMPTY_ATTACHMENTS: Attachment[] = [];+/** Editor identity for the chat composer — see the editorKey note below. */+const CHAT_COMPOSER_EDITOR_KEY = "chat-composer";function attachmentReferenceUrls(attachment: Attachment): string[] {const withUploadFields = attachment as Attachment & {@@ -129,36 +131,35 @@ export function ChatInput({const sendShortcut = useShortcut("send");const editorRef = useRef<ContentEditorRef>(null);const activeSessionId = useChatStore((s) => s.activeSessionId);- const selectedAgentId = useChatStore((s) => s.selectedAgentId);// Two keys with deliberately different concerns://- // `draftKey` — zustand storage key. Scopes the in-progress draft per- // session so different sessions don't bleed text into each other; for- // brand-new chats it falls back to a per-agent slot so switching agents- // mid-compose gives each agent its own draft. This is a STORAGE key, not- // a React identity.+ // `draftKey` — zustand storage key. Scopes the in-progress draft per session+ // so different sessions don't bleed text into each other. An uncreated chat+ // uses ONE slot per workspace, deliberately NOT keyed by agent: the composer+ // is "the chat I have not created yet", and `selectedAgentId` only decides+ // where the first send goes (MUL-4864). This is a STORAGE key, not a React+ // identity.//- // `editorKey` — React `key` on the ContentEditor. Forces a fresh editor- // instance when the user explicitly switches agent. Placeholder text itself- // no longer depends on this: ContentEditor's placeholder-sync effect- // refreshes it live (e.g. across archived ↔ active sessions of the SAME- // agent, where this key does not change). A cancelled-run draft restore- // does NOT bump this key either: it just writes- // the restored text into `inputDraft`, and the editor's own- // defaultValue-sync effect (content-editor.tsx) pushes it into the live- // instance. There is no second copy of the draft to drift or resurface.- // Crucially this does NOT include `activeSessionId`: when the user- // uploads a file in a brand-new chat, `handleUploadFile` first awaits- // `ensureSession` which lazily creates the session and flips- // `activeSessionId` from null → uuid mid-upload. If the editor key- // depended on session id, that flip would unmount the editor right as- // the blob preview was inserted, dropping the in-progress upload's- // image node before file-upload.ts could swap it for the CDN URL — the- // user would see the image flash on then disappear. Keeping editor- // identity stable across the lazy-create event is what makes- // first-upload-creates-session work the same as second-upload.- const draftKey =- draftKeyOverride ?? activeSessionId ?? newSessionDraftKey(selectedAgentId);+ // `editorKey` — React `key` on the ContentEditor, i.e. editor identity. It is+ // constant for the chat composer, because nothing about switching what you+ // are composing to should throw away the instance you are typing in:+ // - Agent switch: same draft slot now, so a remount would only serve to+ // drop the last <100ms of typing the draft debounce has not persisted.+ // - Placeholder: ContentEditor's placeholder-sync effect refreshes it live,+ // so it never needed a remount.+ // - Draft restore (a cancelled run, a failed send): writes into+ // `inputDraft`, and the editor's defaultValue-sync effect pushes it into+ // the live instance. There is no second copy to drift or resurface.+ // - Session switch / lazy create: when the user uploads a file in a+ // brand-new chat, `handleUploadFile` awaits `ensureSession`, which flips+ // `activeSessionId` from null → uuid mid-upload. A session-keyed editor+ // would unmount right as the blob preview landed, dropping the image node+ // before file-upload.ts could swap in the CDN URL — the user would watch+ // the image flash on and vanish. Stable identity is what makes+ // first-upload-creates-session behave like every later upload.+ // Embedded surfaces (Agent Builder) still pass `editorKeyOverride` to isolate+ // their own composer.+ const draftKey = draftKeyOverride ?? activeSessionId ?? DRAFT_NEW_SESSION;// Select a primitive — empty-string fallback keeps referential stability.const inputDraft = useChatStore((s) => s.inputDrafts[draftKey] ?? "");const draftAttachments = useChatStore(@@ -181,7 +182,44 @@ export function ChatInput({// reads the live editor and bails when it is empty.const hasNothingToSend = isEmpty && !inputDraft.trim();const appliedRestoreIdRef = useRef<string | null>(null);- const editorKey = editorKeyOverride ?? selectedAgentId ?? "no-agent";+ const editorKey = editorKeyOverride ?? CHAT_COMPOSER_EDITOR_KEY;++ // The draft whose document the editor instance is currently HOLDING.+ //+ // Normally identical to `draftKey`. The two diverge only while an in-flight+ // upload pins the instance to the source document: ContentEditor's Guard 0+ // refuses to `setContent` over an `uploading` node, because wiping that node+ // strands the upload's finalize and the file silently disappears. Until the+ // upload settles the composer still shows — and still edits — the source+ // draft, so every byte the instance produces belongs to THIS key, not to+ // wherever the user has since navigated.+ //+ // `draftKey` answers "what is selected"; this answers "what is loaded". Every+ // write the editor drives must use the latter.+ const editorDraftKeyRef = useRef(draftKey);++ // Write a document into a draft slot: text, plus a prune of the attachments+ // its body no longer references (deleting an image's markdown drops the+ // staged upload with it). Shared by the live `onUpdate` and the draft-switch+ // flush below, so a document can never be filed under one rule by one path+ // and a different rule by the other. Attachments are read live for `key`+ // rather than passed in — during a divergence the rendered `draftAttachments`+ // belongs to the selected draft, not the loaded one.+ const commitDraft = useCallback(+ (key: string, markdown: string) => {+ setInputDraft(key, markdown);+ const attachments =+ useChatStore.getState().inputDraftAttachments[key] ?? EMPTY_ATTACHMENTS;+ if (attachments.length === 0) return;+ const referenced = attachments.filter((attachment) =>+ isAttachmentReferenced(markdown, attachment),+ );+ if (referenced.length !== attachments.length) {+ setInputDraftAttachments(key, referenced);+ }+ },+ [setInputDraft, setInputDraftAttachments],+ );// Submit gate. `uploading` disables the SubmitButton the instant an upload// starts; `isBlocked()` is re-read inside handleSend for the paths that skip// the button entirely (Mod+Enter mid-paste, drag-drop racing the keyboard).@@ -190,6 +228,56 @@ export function ChatInput({// image would leave stuck (MUL-4808).const uploadGate = useUploadGate(editorRef);+ // Move the editor from the draft it holds to the draft that is selected.+ //+ // Two hazards make this more than "let the defaultValue sync handle it":+ //+ // 1. Unflushed keystrokes. `onUpdate` is debounced, and by the time a+ // debounce armed under draft A fires, `onUpdate` resolves to the latest+ // render's closure — it would file A's document under B. Flushing takes+ // those bytes back and commits them to the key they were typed in.+ // 2. An in-flight upload. Guard 0 pins the document (see editorDraftKeyRef),+ // so the switch cannot happen yet at all: we leave BOTH the document and+ // its writes on the source key and retry when the gate clears+ // (`uploadGate.uploading` is a dep). Blocking navigation instead would be+ // a worse trade — the user waits on a network round-trip to change tabs.+ //+ // Case 2 also has to force the adopt afterwards: ContentEditor's sync effect+ // CONSUMED the defaultValue change while Guard 0 was up (lastDefaultValueRef+ // advances before the guard), so it will never re-run for that value and the+ // target draft would never load on its own.+ //+ // useLayoutEffect, not useEffect, for two ordering reasons: passive effects+ // run child-first, so a passive flush here would land AFTER ContentEditor's+ // sync effect had already skipped on a dirty editor; and a layout effect is+ // part of the commit, so no pending debounce timer can fire ahead of it.+ const deferredAdoptRef = useRef(false);+ useLayoutEffect(() => {+ const loadedKey = editorDraftKeyRef.current;+ if (loadedKey === draftKey) return;+ if (editorRef.current?.hasActiveUploads() === true) {+ // Pinned. Stay bound to the source draft until the upload settles.+ deferredAdoptRef.current = true;+ logger.debug("input.draft switch deferred by in-flight upload", {+ from: loadedKey,+ to: draftKey,+ });+ return;+ }+ const pending = editorRef.current?.flushPendingUpdate() ?? null;+ if (pending !== null) {+ logger.debug("input.draft flush on key change", { from: loadedKey, to: draftKey });+ commitDraft(loadedKey, pending);+ }+ editorDraftKeyRef.current = draftKey;+ if (!deferredAdoptRef.current) return;+ deferredAdoptRef.current = false;+ const incoming = useChatStore.getState().inputDrafts[draftKey] ?? "";+ logger.debug("input.draft adopting after upload settled", { key: draftKey });+ editorRef.current?.adoptContent(incoming);+ setIsEmpty(!incoming.trim());+ }, [draftKey, uploadGate.uploading, commitDraft]);+// Maps "URL inserted into the editor" → "attachment row id" so that// on send we can ask the server to bind only the attachments still// referenced in the message body. Cleared after every send. Mirrors@@ -262,11 +350,16 @@ export function ChatInput({if (result) {const persistedURL = result.markdownLink || result.link;uploadMapRef.current.set(persistedURL, result.id);- if (result.id) addInputDraftAttachment(draftKey, result);+ // Bind to the draft this file is landing IN. The editor inserts the+ // node into whatever document it currently holds, so while an earlier+ // upload pins it to the source draft, that — not the selected draft —+ // is where the body lives. Filing the row anywhere else splits a+ // message from its own attachment.+ if (result.id) addInputDraftAttachment(editorDraftKeyRef.current, result);}return result;},- [addInputDraftAttachment, draftKey, onUploadFile],+ [addInputDraftAttachment, onUploadFile],);// Drop zone wraps the rounded card so a drop anywhere on the input@@ -299,6 +392,20 @@ export function ChatInput({logger.debug("input.send skipped: uploads in flight");return;}+ // The editor is still holding a DIFFERENT draft's document than the one+ // selected — an upload pinned it and the adopt below has not run yet. The+ // upload gate above covers most of that window, but not the sliver between+ // the upload's final dispatch (node gone) and the re-render that adopts:+ // React flushes that state update on a scheduler task, so a click can land+ // first. Sending here would post the source draft's text into the selected+ // session and then clear the wrong draft.+ if (editorDraftKeyRef.current !== draftKey) {+ logger.debug("input.send skipped: composer still holds another draft", {+ loaded: editorDraftKeyRef.current,+ selected: draftKey,+ });+ return;+ }// Only send attachment IDs for uploads still present in the content.// Edits / deletions that remove the markdown URL also drop the binding.const activeIds: string[] = [];@@ -409,23 +516,18 @@ export function ChatInput({><div className="flex-1 min-h-0 overflow-y-auto px-3 py-2"><ContentEditor- // See the editorKey / draftKey split note above — editorKey- // intentionally does not depend on activeSessionId.+ // See the editorKey / draftKey split note above — editor identity+ // intentionally tracks neither the session nor the agent.key={editorKey}ref={editorRef}defaultValue={inputDraft}placeholder={placeholder}onUpdate={(md) => {setIsEmpty(!md.trim());- setInputDraft(draftKey, md);- if (draftAttachments.length > 0) {- const referenced = draftAttachments.filter((attachment) =>- isAttachmentReferenced(md, attachment),- );- if (referenced.length !== draftAttachments.length) {- setInputDraftAttachments(draftKey, referenced);- }- }+ // The LOADED key, not the selected one: while an upload pins the+ // document this fires for the source draft's body — including the+ // upload's own completion dispatch.+ commitDraft(editorDraftKeyRef.current, md);}}onSubmit={handleSend}onUploadFile={uploadEnabled ? handleUpload : undefined}diff --git a/packages/views/chat/components/chat-window.tsx b/packages/views/chat/components/chat-window.tsxindex ad8114bda2..133fa2ddef 100644--- a/packages/views/chat/components/chat-window.tsx+++ b/packages/views/chat/components/chat-window.tsx@@ -54,7 +54,7 @@ import { ChatInput } from "./chat-input";import { ChatResizeHandles } from "./chat-resize-handles";import { useChatContextItems } from "./use-chat-context-items";import { useChatResize } from "./use-chat-resize";-import { hasOptimisticInFlight } from "./use-chat-controller";+import { hasOptimisticInFlight, isStillOnComposeTarget } from "./use-chat-controller";import { createLogger } from "@multica/core/logger";import type { Agent, Attachment, ChatMessage, ChatMessagesPage, ChatPendingTask, ChatSession, PendingChatTasksResponse } from "@multica/core/types";import { useT } from "../../i18n";@@ -523,18 +523,12 @@ export function ChatWindow() {status: "queued",created_at: sentAt,});- // Cache primed → safe to publish the new active session. But only steal- // focus if the user is STILL on the compose target they sent from — if- // they navigated away mid-send, this is fire-and-forget: the reply- // surfaces via the unread dot on the sent session, we don't yank the- // view back. Compare the live store against the closure-captured target.- // For a brand-new chat (activeSessionId === null) the target is keyed by- // the selected agent, so switching agents to start a different new chat- // must also count as "navigated away" even though both sides are null.+ // Cache primed → safe to publish the new active session, but only if the+ // user hasn't navigated away mid-send. Compare the live store against the+ // closure-captured target; see isStillOnComposeTarget for the rule, which+ // this floating window shares with the chat tab's controller.const live = useChatStore.getState();- const stillOnSourceSession =- live.activeSessionId === activeSessionId &&- (activeSessionId !== null || live.selectedAgentId === selectedAgentId);+ const stillOnSourceSession = isStillOnComposeTarget(live.activeSessionId, activeSessionId);if (stillOnSourceSession) {setActiveSession(sessionId);}@@ -606,7 +600,6 @@ export function ChatWindow() {},[activeSessionId,- selectedAgentId,activeAgent,isAgentArchived,ensureSession,diff --git a/packages/views/chat/components/use-chat-controller.test.ts b/packages/views/chat/components/use-chat-controller.test.tsindex 0874ce751c..96fa59b2d6 100644--- a/packages/views/chat/components/use-chat-controller.test.ts+++ b/packages/views/chat/components/use-chat-controller.test.ts@@ -2,7 +2,7 @@ import { describe, it, expect } from "vitest";import { QueryClient, type InfiniteData } from "@tanstack/react-query";import { chatKeys } from "@multica/core/chat/queries";import type { ChatMessage, ChatMessagesPage, ChatPendingTask } from "@multica/core/types";-import { hasOptimisticInFlight } from "./use-chat-controller";+import { hasOptimisticInFlight, isStillOnComposeTarget } from "./use-chat-controller";// hasOptimisticInFlight is the discriminator the stale-session self-heal uses// to EXEMPT a just-created session (awaiting the list refetch) from being@@ -65,3 +65,27 @@ describe("hasOptimisticInFlight", () => {expect(hasOptimisticInFlight(qc, sid)).toBe(true);});});++// The post-send "scrub the composer?" rule, shared by BOTH send chains (the+// chat tab's controller and the floating ChatWindow) so they cannot drift.+// MUL-4864: the new-chat composer is one box per workspace, so the selected+// agent is NOT part of compose-target identity — only the session is.+describe("isStillOnComposeTarget", () => {+ it("is true when the user never left the session they sent from", () => {+ expect(isStillOnComposeTarget(sid, sid)).toBe(true);+ });++ it("is true for a new chat the user is still sitting in", () => {+ // Both null: ensureSession creates the row but does not publish it as+ // active, so a user who stayed put is still looking at the new-chat box.+ expect(isStillOnComposeTarget(null, null)).toBe(true);+ });++ it("is false once the user opens a different session mid-send", () => {+ expect(isStillOnComposeTarget("session-2", sid)).toBe(false);+ });++ it("is false when the user starts a new chat mid-send from a session", () => {+ expect(isStillOnComposeTarget(null, sid)).toBe(false);+ });+});diff --git a/packages/views/chat/components/use-chat-controller.test.tsx b/packages/views/chat/components/use-chat-controller.test.tsxindex e6daf6a846..b471e62fcd 100644--- a/packages/views/chat/components/use-chat-controller.test.tsx+++ b/packages/views/chat/components/use-chat-controller.test.tsx@@ -53,6 +53,9 @@ const h = vi.hoisted(() => {store,archivedMutate: vi.fn(),markReadMutate: vi.fn(),+ // Stable across renders so tests can assert on it; lazy-creates the session+ // a new chat's first send needs.+ createSessionMutate: vi.fn(async () => ({ id: "new-session" })),// Foreground gate for the auto mark-read effect; tests flip it.appForeground: { value: true },consumeRestoreMutate: vi.fn(),@@ -78,6 +81,9 @@ vi.mock("@multica/core/workspace/queries", () => ({vi.mock("@multica/views/issues/components", () => ({ canAssignAgent: () => true }));vi.mock("@multica/core/api", () => ({api: { sendChatMessage: vi.fn(), cancelTaskById: vi.fn() },+ // Names the 403 that a revoked invoke permission raises (MUL-4525); plain+ // failures have no reason code.+ dispatchReasonCode: () => undefined,}));vi.mock("@multica/core/agents", () => ({useAgentPresenceDetail: () => ({ availability: "online" }),@@ -87,7 +93,7 @@ vi.mock("@multica/core/hooks/use-file-upload", () => ({useFileUpload: () => ({ uploadWithToast: vi.fn() }),}));vi.mock("@multica/core/chat/mutations", () => ({- useCreateChatSession: () => ({ mutateAsync: vi.fn() }),+ useCreateChatSession: () => ({ mutateAsync: h.createSessionMutate }),useMarkChatSessionRead: () => ({ mutate: h.markReadMutate }),useSetChatSessionArchived: () => ({ mutate: h.archivedMutate }),useConsumeChatDraftRestore: () => ({ mutate: h.consumeRestoreMutate }),@@ -140,6 +146,7 @@ vi.mock("@tanstack/react-query", async (importOriginal) => {});import { useChatController } from "./use-chat-controller";+import { api } from "@multica/core/api";// --- Fixtures ---------------------------------------------------------------function makeSession(@@ -466,3 +473,105 @@ describe("useChatController durable draft restores (#5219)", () => {expect(result.current.restoreDraftRequest?.serverRestoreId).toBe("msg-1");});});++// After a send, the composer is scrubbed only if the user is still on the+// session they sent from — otherwise the shared editor is showing a different+// draft and clearing it would wipe visible input. MUL-4864 changes what+// "still here" means: with ONE new-chat draft, the composer no longer belongs+// to an agent, so only `activeSessionId` can answer it.+describe("useChatController.handleSend — compose target tracking", () => {+ beforeEach(() => {+ h.store.setActiveSession.mockClear();+ h.createSessionMutate.mockClear();+ h.createSessionMutate.mockResolvedValue({ id: "new-session" });+ vi.mocked(api.sendChatMessage).mockResolvedValue({+ message_id: "msg-1",+ task_id: "task-1",+ created_at: new Date(0).toISOString(),+ } as unknown as Awaited<ReturnType<typeof api.sendChatMessage>>);+ });++ function sendFrom(activeSessionId: string | null, whileSending?: () => void) {+ h.store.activeSessionId = activeSessionId;+ h.store.selectedAgentId = "agent-a";+ h.sessions = [sA];+ h.agents = [agentA];+ const { result } = renderHook(() => useChatController());+ h.store.setActiveSession.mockClear();+ const commitInput = vi.fn();+ return {+ commitInput,+ send: () =>+ act(async () => {+ const pending = result.current.handleSend("hello", undefined, commitInput);+ // Runs between ensureSession and the commit — the window the user+ // actually races with when they touch the picker after hitting send.+ whileSending?.();+ await pending;+ }),+ };+ }++ it("scrubs the composer after a new chat's first send", async () => {+ const { commitInput, send } = sendFrom(null);+ await send();++ expect(commitInput).toHaveBeenCalledWith(+ expect.objectContaining({ clearEditor: true, extraDraftKeys: ["new-session"] }),+ );+ expect(h.store.setActiveSession).toHaveBeenCalledWith("new-session");+ });++ it("scrubs the composer even if the agent picker moved mid-send", async () => {+ // The sent text is still sitting in the one shared composer. Leaving it+ // there would arm a second, unintended send to the agent just picked.+ const { commitInput, send } = sendFrom(null, () => {+ h.store.selectedAgentId = "agent-b";+ });+ await send();++ expect(commitInput).toHaveBeenCalledWith(+ expect.objectContaining({ clearEditor: true, extraDraftKeys: ["new-session"] }),+ );+ // The message goes to the agent selected when Send was pressed — a later+ // flick of the picker does not re-route work already on its way.+ expect(h.createSessionMutate).toHaveBeenCalledWith(+ expect.objectContaining({ agent_id: "agent-a" }),+ );+ // …and that session is what opens, so the user sees the reply they asked for.+ expect(h.store.setActiveSession).toHaveBeenCalledWith("new-session");+ });++ it("keeps the input when session create fails, and opens nothing", async () => {+ h.createSessionMutate.mockRejectedValue(new Error("create failed"));+ const { commitInput, send } = sendFrom(null);+ await send();++ // No commit = the draft is never cleared, so the user's words survive.+ expect(commitInput).not.toHaveBeenCalled();+ expect(h.store.setActiveSession).not.toHaveBeenCalled();+ });++ it("leaves the composer alone when the user navigated to another session mid-send", async () => {+ // Genuine navigation: the editor now shows sB's draft, which this send has+ // no business clearing. Fire-and-forget — the reply surfaces as unread.+ const { commitInput, send } = sendFrom(null, () => {+ h.store.activeSessionId = "sB";+ });+ await send();++ expect(commitInput).toHaveBeenCalledWith(+ expect.objectContaining({ clearEditor: false, extraDraftKeys: ["new-session"] }),+ );+ expect(h.store.setActiveSession).not.toHaveBeenCalled();+ });++ it("still clears the sent draft when sending from an existing session", async () => {+ const { commitInput, send } = sendFrom("sA");+ await send();++ expect(commitInput).toHaveBeenCalledWith(+ expect.objectContaining({ clearEditor: true, extraDraftKeys: ["sA"] }),+ );+ });+});diff --git a/packages/views/chat/components/use-chat-controller.ts b/packages/views/chat/components/use-chat-controller.tsindex fdd5ec279e..76520ce4ed 100644--- a/packages/views/chat/components/use-chat-controller.ts+++ b/packages/views/chat/components/use-chat-controller.ts@@ -64,6 +64,28 @@ export function deriveChatTitle(content: string): string {return cleaned.slice(0, CHAT_TITLE_MAX - 1).trimEnd() + "…";}+/**+ * After a send resolves: is the user still composing to the target they sent+ * from? Decides whether to scrub the composer and open the sent session, or+ * treat the send as fire-and-forget (the reply surfaces as unread instead).+ *+ * The active session answers this on its own, deliberately. The new-chat+ * composer is ONE box per workspace (see DRAFT_NEW_SESSION), so moving the+ * agent picker re-points where the next send goes without moving the view or+ * the draft slot — that is not "navigating away" (MUL-4864). Counting it as+ * such would leave a completed send's text sitting in the composer, primed to+ * be sent a second time to the agent just picked.+ *+ * Shared by both send chains — the chat tab's controller and the floating+ * ChatWindow — so the rule cannot drift between the two surfaces.+ */+export function isStillOnComposeTarget(+ liveActiveSessionId: string | null,+ sentFromSessionId: string | null,+): boolean {+ return liveActiveSessionId === sentFromSessionId;+}+// True when a session has an in-flight optimistic write — an `optimistic-`// message or a pending task in the cache. That is the signal of a just-created// (or actively-sending) session still awaiting server confirmation, before the@@ -497,10 +519,10 @@ export function useChatController(opts?: { isActive?: boolean }) {status: "queued",created_at: sentAt,});+ // Cache primed → safe to publish the new active session, but only if the+ // user hasn't navigated away mid-send. See isStillOnComposeTarget.const live = useChatStore.getState();- const stillOnSourceSession =- live.activeSessionId === activeSessionId &&- (activeSessionId !== null || live.selectedAgentId === selectedAgentId);+ const stillOnSourceSession = isStillOnComposeTarget(live.activeSessionId, activeSessionId);if (stillOnSourceSession) {setActiveSession(sessionId);}@@ -569,7 +591,6 @@ export function useChatController(opts?: { isActive?: boolean }) {},[activeSessionId,- selectedAgentId,activeAgent,isAgentArchived,ensureSession,diff --git a/packages/views/editor/content-editor.test.tsx b/packages/views/editor/content-editor.test.tsxindex b8342d27dc..302c9a968e 100644--- a/packages/views/editor/content-editor.test.tsx+++ b/packages/views/editor/content-editor.test.tsx@@ -297,6 +297,89 @@ describe("ContentEditor", () => {expect(mockSetContent).not.toHaveBeenCalled();});+ // flushPendingUpdate exists for hosts that re-point ONE editor instance at a+ // different destination mid-debounce (chat swapping draftKey between+ // sessions). Without it the armed debounce fires after the switch and, since+ // onUpdate always resolves to the latest render's closure, files the old+ // document under the new destination (MUL-4864).+ describe("flushPendingUpdate", () => {+ it("hands back the pending markdown and cancels the debounce so it cannot fire later", () => {+ vi.useFakeTimers();+ const onUpdate = vi.fn();+ const ref = createRef<ContentEditorRef>();+ editorState.markdown = "old content";+ render(+ <ContentEditor ref={ref} defaultValue="old content" onUpdate={onUpdate} debounceMs={100} />,+ );++ editorState.markdown = "typed but not yet flushed";+ act(() => {+ latestEditorOptions.current?.onUpdate?.({ editor: editorRef.current });+ });++ // Taken back, not emitted — the host routes it to the source draft.+ expect(ref.current?.flushPendingUpdate()).toBe("typed but not yet flushed");+ expect(onUpdate).not.toHaveBeenCalled();++ // The armed timer must be dead: firing now would write these bytes into+ // whatever destination the host has since switched to.+ act(() => {+ vi.advanceTimersByTime(500);+ });+ expect(onUpdate).not.toHaveBeenCalled();+ });++ it("returns null when nothing is pending", () => {+ const ref = createRef<ContentEditorRef>();+ editorState.markdown = "settled";+ render(<ContentEditor ref={ref} defaultValue="settled" onUpdate={vi.fn()} />);++ expect(ref.current?.flushPendingUpdate()).toBeNull();+ });++ it("leaves the editor clean so the next defaultValue sync is no longer blocked by the dirty guard", () => {+ vi.useFakeTimers();+ const ref = createRef<ContentEditorRef>();+ editorState.markdown = "draft A text";+ const { rerender } = render(+ <ContentEditor ref={ref} defaultValue="draft A text" onUpdate={vi.fn()} debounceMs={100} />,+ );++ // Unflushed local edits — this is what makes the editor dirty.+ editorState.markdown = "draft A text, still typing";+ act(() => {+ latestEditorOptions.current?.onUpdate?.({ editor: editorRef.current });+ });+ act(() => {+ ref.current?.flushPendingUpdate();+ });++ // Host has taken the bytes, so switching destination must now load the+ // incoming draft rather than leaving the old document on screen.+ rerender(+ <ContentEditor ref={ref} defaultValue="draft B text" onUpdate={vi.fn()} debounceMs={100} />,+ );+ expect(mockSetContent).toHaveBeenCalled();+ });++ it("still blocks the sync when the pending update was NOT flushed (guard intact)", () => {+ vi.useFakeTimers();+ editorState.markdown = "draft A text";+ const { rerender } = render(+ <ContentEditor defaultValue="draft A text" onUpdate={vi.fn()} debounceMs={100} />,+ );++ editorState.markdown = "draft A text, still typing";+ act(() => {+ latestEditorOptions.current?.onUpdate?.({ editor: editorRef.current });+ });++ // No flush → dirty → the guard must still protect the unsaved bytes.+ rerender(<ContentEditor defaultValue="draft B text" onUpdate={vi.fn()} debounceMs={100} />);+ expect(mockSetContent).not.toHaveBeenCalled();+ });+ });+it("does not sync when defaultValue normalizes to the current editor markdown", () => {editorState.markdown = "same content";const { rerender } = render(<ContentEditor defaultValue="same content" />);diff --git a/packages/views/editor/content-editor.tsx b/packages/views/editor/content-editor.tsxindex 35c3b10a4f..a666462cce 100644--- a/packages/views/editor/content-editor.tsx+++ b/packages/views/editor/content-editor.tsx@@ -32,6 +32,7 @@import {forwardRef,+ useCallback,useEffect,useImperativeHandle,useMemo,@@ -220,6 +221,38 @@ interface ContentEditorRef {uploadFile: (file: File) => void;/** True when file uploads are still in progress. */hasActiveUploads: () => boolean;+ /**+ * Cancel the pending debounced `onUpdate` and hand its markdown back to the+ * caller instead of firing it. Returns null when nothing is pending.+ *+ * For hosts that re-point ONE editor instance at a different destination+ * (chat swaps `draftKey` between sessions). A debounce armed under the old+ * destination would otherwise fire after the switch and, because `onUpdate`+ * always resolves to the latest render's closure, write the old document+ * into the NEW destination. Taking the markdown back lets the host commit it+ * where it was actually typed. Flushing also marks the editor clean, so the+ * dirty guard stops suppressing the incoming `defaultValue` sync.+ *+ * Distinct from `flushPendingOnUnmount`: this is for a LIVE editor changing+ * targets, so it reads the current document rather than a cached copy.+ */+ flushPendingUpdate: () => string | null;+ /**+ * Force `markdown` into the document, bypassing the `defaultValue` sync+ * guards.+ *+ * Those guards SKIP permanently rather than defer: `lastDefaultValueRef`+ * advances before they run, so a `defaultValue` they refuse is never+ * re-applied. That is correct for their usual case (the cache will send+ * another value), but not for a host that re-points ONE instance at a+ * different document and must land it exactly once — chat's draft switch,+ * where an in-flight upload makes Guard 0 refuse the swap.+ *+ * The caller owns the safety the guards normally provide: only call once the+ * reason for the block is gone (upload settled) and any pending edits have+ * been flushed, or this destroys them.+ */+ adoptContent: (markdown: string) => void;}// ---------------------------------------------------------------------------@@ -554,6 +587,58 @@ const ContentEditor = forwardRef<ContentEditorRef, ContentEditorProps>(};}, []);+ // Replace the live document with external markdown. Shared by the+ // `defaultValue` sync effect below and the imperative `adoptContent`, so+ // both land content identically — chunked parse for large docs, no+ // onUpdate echo, caret preserved. Callers own the decision to apply;+ // the guards live in the effect, not here.+ const applyExternalContent = useCallback(+ (markdown: string) => {+ if (!editor || editor.isDestroyed) return;+ const incoming = markdown ? preprocessMarkdown(markdown) : "";+ const incomingNormalized = normalizeMarkdown(incoming);+ // Normalized-equal short-circuit. Avoids a no-op transaction when the+ // cache reflects a write this same editor just emitted.+ if (incomingNormalized === normalizeEditorMarkdown(editor)) return;++ // `emitUpdate: false`. Tiptap v3's setContent defaults to+ // `emitUpdate: true`; without this we would re-trigger onUpdate →+ // server save → self-write loop.+ const { from, to } = editor.state.selection;+ // Same chunked path on WS-driven re-parse of a large description.+ const manager =+ incoming.length > MARKDOWN_CHUNK_THRESHOLD+ ? (editor.storage as { markdown?: { manager?: MarkdownManagerLike } })+ .markdown?.manager+ : undefined;+ if (manager) {+ editor.commands.setContent(parseMarkdownChunked(manager, incoming), {+ emitUpdate: false,+ });+ } else {+ editor.commands.setContent(incoming, {+ emitUpdate: false,+ contentType: "markdown",+ });+ }++ // An empty list item in the incoming markdown parses into a caretless,+ // schema-invalid node; repair it and let it own the caret. Otherwise clamp+ // the prior selection to the new doc size so the caret doesn't snap to+ // position 0 after ProseMirror replaces the document.+ if (!repairEmptyListItems(editor, { from, to })) {+ const docSize = editor.state.doc.content.size;+ editor.commands.setTextSelection({+ from: Math.min(from, docSize),+ to: Math.min(to, docSize),+ });+ }++ lastEmittedRef.current = normalizeEditorMarkdown(editor);+ },+ [editor],+ );+// Sync external `defaultValue` changes into the editor.// Tiptap v3 `useEditor` reads `content` only at mount (ueberdosis/tiptap#5831);// without this effect, a WS-driven description update keeps the editor@@ -579,6 +664,11 @@ const ContentEditor = forwardRef<ContentEditorRef, ContentEditorProps>(// finalize can no longer find it (the file vanishes, leaving an empty// `!file[name]()`). Like the dirty guards below, an uploading node is// local state that an external sync must not overwrite.+ //+ // NOTE: this (like every guard here) SKIPS the sync permanently for this+ // value — `lastDefaultValueRef` has already advanced, so the effect will+ // not re-run for it. A host that must still land this content once the+ // block clears has to say so explicitly, via `adoptContent`.if (hasUploadingNode(editor)) return;const current = normalizeEditorMarkdown(editor);@@ -601,47 +691,8 @@ const ContentEditor = forwardRef<ContentEditorRef, ContentEditorProps>(// here avoids overwriting unsaved local edits.if (isDirty) return;- const incoming = defaultValue ? preprocessMarkdown(defaultValue) : "";- const incomingNormalized = normalizeMarkdown(incoming);- // Guard 3: normalized-equal short-circuit. Avoids a no-op transaction- // when the cache reflects a write this same editor just emitted.- if (incomingNormalized === current) return;-- // Guard 4: `emitUpdate: false`. Tiptap v3's setContent defaults to- // `emitUpdate: true`; without this we would re-trigger onUpdate →- // server save → self-write loop.- const { from, to } = editor.state.selection;- // Same chunked path on WS-driven re-parse of a large description.- const manager =- incoming.length > MARKDOWN_CHUNK_THRESHOLD- ? (editor.storage as { markdown?: { manager?: MarkdownManagerLike } })- .markdown?.manager- : undefined;- if (manager) {- editor.commands.setContent(parseMarkdownChunked(manager, incoming), {- emitUpdate: false,- });- } else {- editor.commands.setContent(incoming, {- emitUpdate: false,- contentType: "markdown",- });- }-- // An empty list item in the incoming markdown parses into a caretless,- // schema-invalid node; repair it and let it own the caret. Otherwise clamp- // the prior selection to the new doc size so the caret doesn't snap to- // position 0 after ProseMirror replaces the document.- if (!repairEmptyListItems(editor, { from, to })) {- const docSize = editor.state.doc.content.size;- editor.commands.setTextSelection({- from: Math.min(from, docSize),- to: Math.min(to, docSize),- });- }-- lastEmittedRef.current = normalizeEditorMarkdown(editor);- }, [defaultValue, editor]);+ applyExternalContent(defaultValue);+ }, [defaultValue, editor, applyExternalContent]);// Sync external `placeholder` changes into the mounted editor.// The Placeholder extension is configured with a getter over `placeholderRef`@@ -700,6 +751,25 @@ const ContentEditor = forwardRef<ContentEditorRef, ContentEditorProps>(uploadAndInsertFile(editor, file, onUploadFileRef.current, endPos);},hasActiveUploads: () => (editor ? hasUploadingNode(editor) : false),+ flushPendingUpdate: () => {+ // No armed timer = nothing typed since the last emit. The editor is+ // already clean, so the host has nothing to re-route.+ if (!debounceRef.current) return null;+ clearTimeout(debounceRef.current);+ debounceRef.current = undefined;+ pendingFlushRef.current = null;+ if (!editor || editor.isDestroyed) return null;+ // Read the live document: unlike the unmount flush, the instance is+ // still alive here, so this is the freshest possible copy.+ const md = normalizeEditorMarkdown(editor);+ if (md === lastEmittedRef.current) return null;+ // Advance the emit watermark so the editor reads as clean — the host+ // is taking responsibility for these bytes, and the dirty guard must+ // now let the incoming defaultValue through.+ lastEmittedRef.current = md;+ return md;+ },+ adoptContent: (markdown: string) => applyExternalContent(markdown),}));// Link hover card — disabled when BubbleMenu is active (has selection)