Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
feat(drafts): unified draft lifecycle + upload ownership inversion (MUL-5181) (#5900)
Naiyuan Qing77b309a5ac1d
diff --git a/packages/core/api/client.test.ts b/packages/core/api/client.test.tsindex ea159ef4c5..0a0d545766 100644--- a/packages/core/api/client.test.ts+++ b/packages/core/api/client.test.ts@@ -1421,6 +1421,45 @@ describe("ApiClient", () => {expect(body.get("comment_id")).toBeNull();});+ it("threads an AbortSignal into fetch so the coordinator can cancel it (MUL-5181)", async () => {+ const fetchMock = vi.fn().mockResolvedValue(+ new Response(JSON.stringify({ id: "att-1", url: "https://cdn/x" }), {+ status: 200,+ headers: { "Content-Type": "application/json" },+ }),+ );+ vi.stubGlobal("fetch", fetchMock);++ const client = new ApiClient("https://api.example.test");+ const controller = new AbortController();+ const file = new File(["hi"], "hi.png", { type: "image/png" });+ await client.uploadFile(file, { issueId: "issue-1" }, controller.signal);++ const [, init] = fetchMock.mock.calls[0]!;+ expect(init?.signal).toBe(controller.signal);+ });++ it("rejects with the fetch AbortError when the signal is already aborted", async () => {+ const fetchMock = vi.fn().mockImplementation((_url, init?: RequestInit) => {+ if (init?.signal?.aborted) {+ const err = new Error("The operation was aborted");+ err.name = "AbortError";+ return Promise.reject(err);+ }+ return Promise.resolve(new Response("{}", { status: 200 }));+ });+ vi.stubGlobal("fetch", fetchMock);++ const client = new ApiClient("https://api.example.test");+ const controller = new AbortController();+ controller.abort();+ const file = new File(["hi"], "hi.png", { type: "image/png" });++ await expect(+ client.uploadFile(file, undefined, controller.signal),+ ).rejects.toMatchObject({ name: "AbortError" });+ });+it("sendChatMessage serialises attachment_ids onto the JSON body when present", async () => {const fetchMock = vi.fn().mockResolvedValue(new Response(JSON.stringify({ message_id: "m1", task_id: "t1", created_at: "" }), {diff --git a/packages/core/api/client.ts b/packages/core/api/client.tsindex e358e73b9c..21d24667d1 100644--- a/packages/core/api/client.ts+++ b/packages/core/api/client.ts@@ -2085,6 +2085,11 @@ export class ApiClient {async uploadFile(file: File,opts?: { issueId?: string; commentId?: string; chatSessionId?: string },+ // Optional abort signal so a module-level upload coordinator (MUL-5181)+ // can cancel an in-flight upload on logout. When aborted, `fetch` rejects+ // with an AbortError, which the coordinator distinguishes from a real+ // failure via `signal.aborted` / `err.name === "AbortError"`.+ signal?: AbortSignal,): Promise<Attachment> {const formData = new FormData();formData.append("file", file);@@ -2101,6 +2106,7 @@ export class ApiClient {headers: this.authHeaders(),body: formData,credentials: "include",+ signal,});if (!res.ok) {diff --git a/packages/core/chat/store.test.ts b/packages/core/chat/store.test.tsindex aa39e28421..cacb1c9b81 100644--- a/packages/core/chat/store.test.ts+++ b/packages/core/chat/store.test.ts@@ -72,9 +72,14 @@ describe("chat store — legacy per-agent new-chat draft migration", () => {const store = createChatStore({ storage });- expect(store.getState().inputDraftAttachments[DRAFT_NEW_SESSION]?.map((a) => a.id)).toEqual([- "att-mine",- ]);+ // Legacy bare Attachment rows load as `uploaded` entries (MUL-5181 L2).+ expect(+ store+ .getState()+ .inputDraftAttachments[DRAFT_NEW_SESSION]?.map((u) =>+ u.status === "uploaded" ? u.attachment.id : u.clientUploadId,+ ),+ ).toEqual(["att-mine"]);expect(store.getState().inputDraftAttachments["__new__:agent-2"]).toBeUndefined();});@@ -302,3 +307,99 @@ describe("chat store — applied draft-restore ledger", () => {expect(store.getState().appliedDraftRestoreIds[0]).toBe("r-1");});});++// Coordinator-owned upload lifecycle in the draft slots (MUL-5181 L2).+describe("chat store — draft upload ops", () => {+ const ATTACHMENTS_KEY = "multica:chat:draft-attachments";++ function freshStore() {+ const storage = memStorage();+ return { storage, store: createChatStore({ storage }) };+ }++ it("add → settle keeps the clientUploadId and strips the signed download_url", () => {+ const { storage, store } = freshStore();+ const s = store.getState();+ s.addInputDraftUpload("session-1", {+ clientUploadId: "c1",+ status: "uploading",+ filename: "shot.png",+ size: 9,+ });+ expect(store.getState().inputDraftAttachments["session-1"]?.[0]?.status).toBe("uploading");++ s.settleInputDraftUpload("session-1", "c1", {+ ...makeAttachment("att-1"),+ download_url: "/uploads/att-1.png?Signature=short-lived",+ });++ const settled = store.getState().inputDraftAttachments["session-1"]?.[0];+ expect(settled).toMatchObject({ clientUploadId: "c1", status: "uploaded" });+ expect(settled?.status === "uploaded" && settled.attachment.id).toBe("att-1");+ // Drafts survive restarts; a response-scoped signed URL must not.+ expect(settled?.status === "uploaded" && settled.attachment.download_url).toBe("");+ // And the persisted blob agrees with memory.+ expect(storage.getItem(ATTACHMENTS_KEY)).toContain('"c1"');+ expect(storage.getItem(ATTACHMENTS_KEY)).not.toContain("Signature=");+ });++ it("addInputDraftUpload dedupes by clientUploadId", () => {+ const { store } = freshStore();+ const s = store.getState();+ const placeholder = {+ clientUploadId: "c1",+ status: "uploading" as const,+ filename: "a.png",+ size: 1,+ };+ s.addInputDraftUpload("session-1", placeholder);+ s.addInputDraftUpload("session-1", placeholder);+ expect(store.getState().inputDraftAttachments["session-1"]).toHaveLength(1);+ });++ it("failInputDraftUpload marks the placeholder failed with its reason", () => {+ const { store } = freshStore();+ const s = store.getState();+ s.addInputDraftUpload("session-1", {+ clientUploadId: "c1",+ status: "uploading",+ filename: "a.png",+ size: 1,+ });+ s.failInputDraftUpload("session-1", "c1", "network down");+ expect(store.getState().inputDraftAttachments["session-1"]?.[0]).toMatchObject({+ status: "failed",+ error: "network down",+ filename: "a.png",+ });+ });++ it("removeInputDraftUpload drops the entry and prunes an empty slot", () => {+ const { storage, store } = freshStore();+ const s = store.getState();+ s.addInputDraftUpload("session-1", {+ clientUploadId: "c1",+ status: "uploading",+ filename: "a.png",+ size: 1,+ });+ s.removeInputDraftUpload("session-1", "c1");+ expect(store.getState().inputDraftAttachments["session-1"]).toBeUndefined();+ expect(storage.getItem(ATTACHMENTS_KEY)).toBeNull();+ });++ it("appendToInputDraft lands after trimmed text, or bare on an empty slot", () => {+ const { store } = freshStore();+ const s = store.getState();+ s.setInputDraft("session-1", "wip text \n");+ s.appendToInputDraft("session-1", "");+ expect(store.getState().inputDrafts["session-1"]).toBe(+ "wip text\n\n",+ );++ s.appendToInputDraft("session-2", "[doc.pdf](/api/attachments/att-2/download)");+ expect(store.getState().inputDrafts["session-2"]).toBe(+ "[doc.pdf](/api/attachments/att-2/download)",+ );+ });+});diff --git a/packages/core/chat/store.ts b/packages/core/chat/store.tsindex b706917f2b..20903c3abb 100644--- a/packages/core/chat/store.ts+++ b/packages/core/chat/store.ts@@ -2,6 +2,13 @@ import { create } from "zustand";import type { StorageAdapter } from "../types";import type { Attachment } from "../types/attachment";import { getCurrentSlug, registerForWorkspaceRehydration } from "../platform/workspace-storage";+import { registerDraftCleanup } from "../drafts/cleanup-registry";+import {+ normalizeStoredUploads,+ attachmentToDraftUpload,+ type DraftUpload,+ type PendingDraftUpload,+} from "../drafts/draft-upload";import { createLogger } from "../logger";const logger = createLogger("chat.store");@@ -92,6 +99,7 @@ function writeDrafts(storage: StorageAdapter, key: string, drafts: Record<string}}+/** Shape check for server Attachment rows inside persisted restores. */function isAttachmentDraft(value: unknown): value is Attachment {return (typeof value === "object" &&@@ -101,17 +109,20 @@ function isAttachmentDraft(value: unknown): value is Attachment {);}-function readDraftAttachments(storage: StorageAdapter, key: string): Record<string, Attachment[]> {+function readDraftAttachments(storage: StorageAdapter, key: string): Record<string, DraftUpload[]> {const raw = storage.getItem(key);if (!raw) return {};try {const parsed = JSON.parse(raw);if (typeof parsed !== "object" || parsed === null) return {};- const out: Record<string, Attachment[]> = {};+ const out: Record<string, DraftUpload[]> = {};for (const [draftKey, value] of Object.entries(parsed)) {if (!Array.isArray(value)) continue;- const attachments = value.filter(isAttachmentDraft);- if (attachments.length > 0) out[draftKey] = attachments;+ // Normalize on every load (MUL-5181 L2): bare Attachment rows persisted+ // by pre-L2 builds become `uploaded` placeholders, and an upload still+ // `uploading` at load time is coerced to `interrupted` (bytes are gone).+ const uploads = normalizeStoredUploads(value);+ if (uploads.length > 0) out[draftKey] = uploads;}return out;} catch {@@ -184,9 +195,9 @@ function writePendingSendRestores(function writeDraftAttachments(storage: StorageAdapter,key: string,- drafts: Record<string, Attachment[]>,+ drafts: Record<string, DraftUpload[]>,) {- const pruned: Record<string, Attachment[]> = {};+ const pruned: Record<string, DraftUpload[]> = {};for (const [k, v] of Object.entries(drafts)) {if (v.length > 0) pruned[k] = v;}@@ -244,7 +255,7 @@ function loadDraftSlots(draftsKey: string,attachmentsKey: string,selectedAgentId: string | null,-): { inputDrafts: Record<string, string>; inputDraftAttachments: Record<string, Attachment[]> } {+): { inputDrafts: Record<string, string>; inputDraftAttachments: Record<string, DraftUpload[]> } {const drafts = migrateLegacyNewChatSlots(readDrafts(storage, draftsKey), selectedAgentId);const attachments = migrateLegacyNewChatSlots(readDraftAttachments(storage, attachmentsKey),@@ -300,7 +311,8 @@ export interface ChatState {/** Drafts per session: sessionId (or DRAFT_NEW_SESSION) → markdown text. */inputDrafts: Record<string, string>;/** Attachment rows referenced by each input draft. */- inputDraftAttachments: Record<string, Attachment[]>;+ /** Coordinator-owned uploads per draft slot (placeholders + completed). */+ inputDraftAttachments: Record<string, DraftUpload[]>;/** Durable draft restores already written into a composer (#5219). */appliedDraftRestoreIds: string[];/** Server-less restores waiting for their session's composer, per session (#5219). */@@ -317,8 +329,19 @@ export interface ChatState {setSelectedProjectId: (id: string | null) => void;/** sessionId accepts a real session UUID or DRAFT_NEW_SESSION. */setInputDraft: (sessionId: string, draft: string) => void;- setInputDraftAttachments: (sessionId: string, attachments: Attachment[]) => void;+ /** Append a markdown fragment to a draft slot's text (upload write-back). */+ appendToInputDraft: (sessionId: string, markdown: string) => void;+ setInputDraftAttachments: (sessionId: string, uploads: DraftUpload[]) => void;+ /** Record a completed server row as an uploaded entry (restore paths). */addInputDraftAttachment: (sessionId: string, attachment: Attachment) => void;+ /** Record a placeholder the moment a file is picked (coordinator-owned). */+ addInputDraftUpload: (sessionId: string, upload: DraftUpload) => void;+ /** Swap a placeholder for its completed attachment. No-op if it's gone. */+ settleInputDraftUpload: (sessionId: string, clientUploadId: string, attachment: Attachment) => void;+ /** Mark a placeholder failed. No-op if it's gone. */+ failInputDraftUpload: (sessionId: string, clientUploadId: string, error?: string) => void;+ /** Drop a placeholder (dismiss a failure / interrupted). */+ removeInputDraftUpload: (sessionId: string, clientUploadId: string) => void;clearInputDraft: (sessionId: string) => void;/** Record that a durable restore reached the composer; survives a reload. */markDraftRestoreApplied: (restoreId: string) => void;@@ -476,10 +499,20 @@ export function createChatStore(options: ChatStoreOptions) {writeDrafts(storage, wsKey(DRAFTS_KEY), next);set({ inputDrafts: next });},- setInputDraftAttachments: (sessionId, attachments) => {- logger.debug("setInputDraftAttachments", { sessionId, count: attachments.length });+ appendToInputDraft: (sessionId, markdown) => {+ const existing = get().inputDrafts[sessionId] ?? "";+ const draft = existing.trim()+ ? `${existing.replace(/\s+$/, "")}\n\n${markdown}`+ : markdown;+ logger.debug("appendToInputDraft", { sessionId, length: draft.length });+ const next = { ...get().inputDrafts, [sessionId]: draft };+ writeDrafts(storage, wsKey(DRAFTS_KEY), next);+ set({ inputDrafts: next });+ },+ setInputDraftAttachments: (sessionId, uploads) => {+ logger.debug("setInputDraftAttachments", { sessionId, count: uploads.length });const next = { ...get().inputDraftAttachments };- if (attachments.length > 0) next[sessionId] = attachments;+ if (uploads.length > 0) next[sessionId] = uploads;else delete next[sessionId];writeDraftAttachments(storage, wsKey(DRAFT_ATTACHMENTS_KEY), next);set({ inputDraftAttachments: next });@@ -488,13 +521,68 @@ export function createChatStore(options: ChatStoreOptions) {if (!attachment.id) return;const current = get().inputDraftAttachments;const existing = current[sessionId] ?? [];- const nextForKey = existing.some((a) => a.id === attachment.id)- ? existing.map((a) => (a.id === attachment.id ? attachment : a))- : [...existing, attachment];+ const wrapped = attachmentToDraftUpload(attachment);+ const nextForKey = existing.some(+ (u) => u.status === "uploaded" && u.attachment.id === attachment.id,+ )+ ? existing.map((u) =>+ u.status === "uploaded" && u.attachment.id === attachment.id ? wrapped : u,+ )+ : [...existing, wrapped];+ const next = { ...current, [sessionId]: nextForKey };+ writeDraftAttachments(storage, wsKey(DRAFT_ATTACHMENTS_KEY), next);+ set({ inputDraftAttachments: next });+ },+ addInputDraftUpload: (sessionId, upload) => {+ const current = get().inputDraftAttachments;+ const existing = current[sessionId] ?? [];+ if (existing.some((u) => u.clientUploadId === upload.clientUploadId)) return;+ const next = { ...current, [sessionId]: [...existing, upload] };+ writeDraftAttachments(storage, wsKey(DRAFT_ATTACHMENTS_KEY), next);+ set({ inputDraftAttachments: next });+ },+ settleInputDraftUpload: (sessionId, clientUploadId, attachment) => {+ const current = get().inputDraftAttachments;+ const existing = current[sessionId] ?? [];+ if (!existing.some((u) => u.clientUploadId === clientUploadId)) return;+ const nextForKey = existing.map((u) =>+ u.clientUploadId === clientUploadId+ ? { ...attachmentToDraftUpload(attachment), clientUploadId }+ : u,+ );+ const next = { ...current, [sessionId]: nextForKey };+ writeDraftAttachments(storage, wsKey(DRAFT_ATTACHMENTS_KEY), next);+ set({ inputDraftAttachments: next });+ },+ failInputDraftUpload: (sessionId, clientUploadId, error) => {+ const current = get().inputDraftAttachments;+ const existing = current[sessionId] ?? [];+ const target = existing.find((u) => u.clientUploadId === clientUploadId);+ if (!target) return;+ const failed: PendingDraftUpload = {+ clientUploadId,+ status: "failed",+ filename: target.filename,+ size: target.size,+ contentType: target.contentType,+ error,+ };+ const nextForKey = existing.map((u) => (u.clientUploadId === clientUploadId ? failed : u));const next = { ...current, [sessionId]: nextForKey };writeDraftAttachments(storage, wsKey(DRAFT_ATTACHMENTS_KEY), next);set({ inputDraftAttachments: next });},+ removeInputDraftUpload: (sessionId, clientUploadId) => {+ const current = get().inputDraftAttachments;+ const existing = current[sessionId] ?? [];+ if (!existing.some((u) => u.clientUploadId === clientUploadId)) return;+ const remaining = existing.filter((u) => u.clientUploadId !== clientUploadId);+ const next = { ...current };+ if (remaining.length > 0) next[sessionId] = remaining;+ else delete next[sessionId];+ writeDraftAttachments(storage, wsKey(DRAFT_ATTACHMENTS_KEY), next);+ set({ inputDraftAttachments: next });+ },clearInputDraft: (sessionId) => {const currentDrafts = get().inputDrafts;const currentAttachments = get().inputDraftAttachments;@@ -530,6 +618,34 @@ export function createChatStore(options: ChatStoreOptions) {},}));+ // Self-register the chat draft persist keys so logout / workspace-delete+ // clear them like every other draft store (previously leaked — the chat+ // drafts, their attachments, and the applied-restore ledger survived a+ // client-side logout into the next login on the same tab). All are+ // workspace-scoped (persisted through `wsKey`, i.e. `${base}:${slug}`), and+ // each entry resets only its own in-memory slice. The server-less restore+ // queue is registered too so its recoverable text does not outlive the user.+ registerDraftCleanup({+ storageKey: DRAFTS_KEY,+ workspaceScoped: true,+ resetInMemory: () => store.setState({ inputDrafts: {} }),+ });+ registerDraftCleanup({+ storageKey: DRAFT_ATTACHMENTS_KEY,+ workspaceScoped: true,+ resetInMemory: () => store.setState({ inputDraftAttachments: {} }),+ });+ registerDraftCleanup({+ storageKey: APPLIED_RESTORES_KEY,+ workspaceScoped: true,+ resetInMemory: () => store.setState({ appliedDraftRestoreIds: [] }),+ });+ registerDraftCleanup({+ storageKey: PENDING_SEND_RESTORES_KEY,+ workspaceScoped: true,+ resetInMemory: () => store.setState({ pendingSendRestores: {} }),+ });+registerForWorkspaceRehydration(() => {const nextSession = storage.getItem(wsKey(SESSION_STORAGE_KEY));const nextAgent = storage.getItem(wsKey(AGENT_STORAGE_KEY));diff --git a/packages/core/drafts/cleanup-registry.test.ts b/packages/core/drafts/cleanup-registry.test.tsnew file mode 100644index 0000000000..6a0d317c84--- /dev/null+++ b/packages/core/drafts/cleanup-registry.test.ts@@ -0,0 +1,45 @@+import { describe, it, expect, vi, beforeEach } from "vitest";+import {+ registerDraftCleanup,+ clearRegisteredWorkspaceDrafts,+ resetAllRegisteredDrafts,+ __clearDraftCleanupRegistryForTest,+ __getRegisteredDraftKeysForTest,+} from "./cleanup-registry";++beforeEach(() => {+ __clearDraftCleanupRegistryForTest();+});++describe("draft cleanup registry", () => {+ it("clears workspace-scoped keys with the slug suffix and global keys bare", () => {+ const adapter = { getItem: vi.fn(), setItem: vi.fn(), removeItem: vi.fn() };+ registerDraftCleanup({ storageKey: "scoped_a", workspaceScoped: true, resetInMemory: vi.fn() });+ registerDraftCleanup({ storageKey: "global_b", workspaceScoped: false, resetInMemory: vi.fn() });++ clearRegisteredWorkspaceDrafts(adapter, "acme");++ expect(adapter.removeItem).toHaveBeenCalledWith("scoped_a:acme");+ expect(adapter.removeItem).toHaveBeenCalledWith("global_b");+ expect(adapter.removeItem).toHaveBeenCalledTimes(2);+ });++ it("resets every registered store's in-memory state", () => {+ const resetA = vi.fn();+ const resetB = vi.fn();+ registerDraftCleanup({ storageKey: "a", workspaceScoped: true, resetInMemory: resetA });+ registerDraftCleanup({ storageKey: "b", workspaceScoped: true, resetInMemory: resetB });++ resetAllRegisteredDrafts();++ expect(resetA).toHaveBeenCalledTimes(1);+ expect(resetB).toHaveBeenCalledTimes(1);+ });++ it("is idempotent per key — re-registering overwrites, never duplicates", () => {+ registerDraftCleanup({ storageKey: "dupe", workspaceScoped: true, resetInMemory: vi.fn() });+ registerDraftCleanup({ storageKey: "dupe", workspaceScoped: true, resetInMemory: vi.fn() });++ expect(__getRegisteredDraftKeysForTest()).toEqual(["dupe"]);+ });+});diff --git a/packages/core/drafts/cleanup-registry.ts b/packages/core/drafts/cleanup-registry.tsnew file mode 100644index 0000000000..dad86cb812--- /dev/null+++ b/packages/core/drafts/cleanup-registry.ts@@ -0,0 +1,88 @@+import type { StorageAdapter } from "../types/storage";+import { abortAll as abortAllUploads } from "./upload-coordinator";++/**+ * Self-registration registry for draft stores, replacing the hand-maintained+ * `WORKSPACE_SCOPED_KEYS` array in `platform/storage-cleanup.ts`.+ *+ * The old model required every new draft store to remember to append its+ * persist key to a list living in a different file; that list drifted and+ * left `multica_comment_drafts`, `multica_quick_create`, `multica_project_draft`,+ * `multica_feedback_draft`, and the chat draft-attachment / restore keys+ * uncleared on logout and workspace deletion (persistence-layer leak), while+ * the in-memory Zustand singletons kept a previous user's draft after a+ * client-side logout navigation (memory-layer leak, cross-user on a shared+ * profile).+ *+ * A store registers ONCE at module load via `registerDraftCleanup`. Cleanup+ * then iterates the registry, so adding a draft store can never again silently+ * skip cleanup.+ */+export interface DraftCleanupEntry {+ /**+ * Base persist key, before any workspace-slug suffix. For workspace-scoped+ * stores the real localStorage key is `${storageKey}:${slug}`.+ */+ storageKey: string;+ /**+ * True when persisted through `createWorkspaceAwareStorage` (key suffixed+ * with the active slug). False for globally-namespaced keys.+ */+ workspaceScoped: boolean;+ /**+ * Reset this store's in-memory state to empty. Called on logout so the+ * Zustand singleton cannot surface a previous user's draft after a+ * client-side navigation (no full page reload clears module singletons).+ */+ resetInMemory: () => void;+}++const entries = new Map<string, DraftCleanupEntry>();++/** Register a draft store for workspace/logout cleanup. Idempotent per key. */+export function registerDraftCleanup(entry: DraftCleanupEntry): void {+ entries.set(entry.storageKey, entry);+}++/**+ * Remove every registered draft's persisted storage for one workspace slug.+ * Called on workspace delete/leave (per slug) and logout (per workspace the+ * user belonged to). Globally-namespaced draft keys are removed regardless of+ * slug — passing any slug clears them once.+ */+export function clearRegisteredWorkspaceDrafts(+ adapter: StorageAdapter,+ slug: string,+): void {+ for (const entry of entries.values()) {+ if (entry.workspaceScoped) {+ adapter.removeItem(`${entry.storageKey}:${slug}`);+ } else {+ adapter.removeItem(entry.storageKey);+ }+ }+}++/**+ * Reset all registered draft stores' in-memory state. Called on logout before+ * auth is cleared, so no draft survives into the next login on the same tab.+ */+export function resetAllRegisteredDrafts(): void {+ // Abort in-flight uploads BEFORE clearing drafts: an upload that settles+ // after the draft is wiped must not resurrect a placeholder, and its bytes+ // must never bind an attachment under the next session (MUL-5181).+ abortAllUploads();+ for (const entry of entries.values()) {+ entry.resetInMemory();+ }+}++/** Test-only: drop all registrations. */+export function __clearDraftCleanupRegistryForTest(): void {+ entries.clear();+}++/** Test-only: inspect registered keys. */+export function __getRegisteredDraftKeysForTest(): string[] {+ return [...entries.keys()];+}diff --git a/packages/core/drafts/create-draft-store.test.ts b/packages/core/drafts/create-draft-store.test.tsnew file mode 100644index 0000000000..5699351701--- /dev/null+++ b/packages/core/drafts/create-draft-store.test.ts@@ -0,0 +1,68 @@+import { describe, it, expect, beforeEach } from "vitest";+import { createDraftStore } from "./create-draft-store";+import {+ resetAllRegisteredDrafts,+ __clearDraftCleanupRegistryForTest,+ __getRegisteredDraftKeysForTest,+} from "./cleanup-registry";++interface Sample {+ title: string;+ tags: string[];+}++const EMPTY: Sample = { title: "", tags: [] };++beforeEach(() => {+ __clearDraftCleanupRegistryForTest();+});++describe("createDraftStore", () => {+ it("merges patches and reports meaningful drafts via hasMeaningful", () => {+ const useStore = createDraftStore<Sample>({+ storageKey: "t_merge",+ emptyData: EMPTY,+ hasMeaningful: (d) => !!d.title || d.tags.length > 0,+ workspaceScoped: false,+ });++ expect(useStore.getState().hasDraft()).toBe(false);+ useStore.getState().setDraft({ title: "hi" });+ expect(useStore.getState().draft).toEqual({ title: "hi", tags: [] });+ expect(useStore.getState().hasDraft()).toBe(true);+ });++ it("clearDraft resets to a fresh empty draft that does not share nested references", () => {+ const useStore = createDraftStore<Sample>({+ storageKey: "t_clear",+ emptyData: EMPTY,+ hasMeaningful: (d) => d.tags.length > 0,+ workspaceScoped: false,+ });++ useStore.getState().setDraft({ tags: ["a"] });+ useStore.getState().clearDraft();+ expect(useStore.getState().draft.tags).toEqual([]);++ // Mutating the cleared array must not corrupt EMPTY for the next clear.+ useStore.getState().draft.tags.push("leak");+ useStore.getState().setDraft({ tags: ["b"] });+ useStore.getState().clearDraft();+ expect(useStore.getState().draft.tags).toEqual([]);+ });++ it("self-registers for cleanup and reset wipes in-memory state", () => {+ const useStore = createDraftStore<Sample>({+ storageKey: "t_register",+ emptyData: EMPTY,+ hasMeaningful: (d) => !!d.title,+ workspaceScoped: false,+ });++ expect(__getRegisteredDraftKeysForTest()).toContain("t_register");++ useStore.getState().setDraft({ title: "leaky" });+ resetAllRegisteredDrafts();+ expect(useStore.getState().draft.title).toBe("");+ });+});diff --git a/packages/core/drafts/create-draft-store.ts b/packages/core/drafts/create-draft-store.tsnew file mode 100644index 0000000000..966a9d22be--- /dev/null+++ b/packages/core/drafts/create-draft-store.ts@@ -0,0 +1,113 @@+import { create, type StoreApi, type UseBoundStore } from "zustand";+import { createJSONStorage, persist } from "zustand/middleware";+import {+ createWorkspaceAwareStorage,+ registerForWorkspaceRehydration,+} from "../platform/workspace-storage";+import { defaultStorage } from "../platform/storage";+import { registerDraftCleanup } from "./cleanup-registry";++/**+ * Factory for singleton draft stores. Before this existed, every simple draft+ * store (`projects/draft-store`, `feedback/draft-store`, and structurally the+ * issue draft store) hand-copied the identical shape: a `draft` object,+ * `setDraft(patch)`, `clearDraft()`, `hasDraft()`, a `persist` config wired to+ * `createWorkspaceAwareStorage`, and a `registerForWorkspaceRehydration` call.+ * The only per-store differences are the data shape, the persist key, and the+ * "is this draft meaningful" predicate — exactly the {@link DraftStoreConfig}+ * fields below.+ *+ * The factory additionally wires two things the copies kept getting wrong:+ * 1. `registerDraftCleanup` — self-registers the persist key so workspace+ * delete and logout clean it up without a hand-maintained key list.+ * 2. an in-memory `resetInMemory` — logout resets the Zustand singleton so a+ * previous user's draft cannot survive into the next login on the same tab.+ */+export interface DraftStoreConfig<TData> {+ /** Persist key, before the workspace-slug suffix. Must be globally unique. */+ storageKey: string;+ /** The empty/initial draft. Cleared drafts and fresh stores start here. */+ emptyData: TData;+ /**+ * Whether the draft holds recoverable user intent. Must consider every+ * signal the surface treats as "unsaved work" — text, meaningful field+ * selections, attachments — not just the primary text field.+ */+ hasMeaningful: (data: TData) => boolean;+ /** Persist per workspace slug via `createWorkspaceAwareStorage`. Default true. */+ workspaceScoped?: boolean;+ /**+ * Backfill defaults onto drafts persisted by older builds that predate a+ * later-added field, so read sites can rely on the declared shape. Receives+ * the raw persisted `data` and returns the fields to overlay onto emptyData.+ */+ migrateData?: (persistedData: unknown) => Partial<TData>;+}++export interface DraftStore<TData> {+ draft: TData;+ setDraft: (patch: Partial<TData>) => void;+ clearDraft: () => void;+ hasDraft: () => boolean;+}++export function createDraftStore<TData extends object>(+ config: DraftStoreConfig<TData>,+): UseBoundStore<StoreApi<DraftStore<TData>>> {+ const workspaceScoped = config.workspaceScoped ?? true;+ const empty = () => structuredCloneData(config.emptyData);++ const useStore = create<DraftStore<TData>>()(+ persist(+ (set, get) => ({+ draft: empty(),+ setDraft: (patch) => set((s) => ({ draft: { ...s.draft, ...patch } })),+ clearDraft: () => set({ draft: empty() }),+ hasDraft: () => config.hasMeaningful(get().draft),+ }),+ {+ name: config.storageKey,+ storage: createJSONStorage(() =>+ workspaceScoped+ ? createWorkspaceAwareStorage(defaultStorage)+ : defaultStorage,+ ),+ merge: (persistedState, currentState) => {+ const persisted = (persistedState ?? {}) as Partial<DraftStore<TData>>;+ const persistedData = persisted.draft as unknown;+ const overlay = config.migrateData+ ? config.migrateData(persistedData)+ : (persistedData as Partial<TData> | undefined);+ return {+ ...currentState,+ ...persisted,+ // Clone emptyData so a persisted draft missing a nested field does+ // not alias the module-level constant's array/object references.+ draft: { ...structuredCloneData(config.emptyData), ...overlay },+ };+ },+ },+ ),+ );++ if (workspaceScoped) {+ registerForWorkspaceRehydration(() => useStore.persist.rehydrate());+ }++ registerDraftCleanup({+ storageKey: config.storageKey,+ workspaceScoped,+ resetInMemory: () => useStore.getState().clearDraft(),+ });++ return useStore;+}++// Structured clone kept local and defensive: the empty draft may contain+// nested arrays/objects (labelIds, propertyValues, attachments) that must not+// be shared by reference between the initial state and later `clearDraft`.+function structuredCloneData<T>(value: T): T {+ return typeof structuredClone === "function"+ ? structuredClone(value)+ : (JSON.parse(JSON.stringify(value)) as T);+}diff --git a/packages/core/drafts/draft-upload.test.ts b/packages/core/drafts/draft-upload.test.tsnew file mode 100644index 0000000000..ffcca38a3e--- /dev/null+++ b/packages/core/drafts/draft-upload.test.ts@@ -0,0 +1,93 @@+import { describe, expect, it } from "vitest";+import type { Attachment } from "../types";+import {+ type DraftUpload,+ attachmentToDraftUpload,+ hasUploadingDraft,+ normalizeStoredUploads,+ uploadedAttachments,+} from "./draft-upload";++function makeAttachment(id: string): Attachment {+ return {+ id,+ workspace_id: "ws-1",+ issue_id: "issue-1",+ comment_id: null,+ chat_session_id: null,+ chat_message_id: null,+ uploader_type: "member",+ uploader_id: "alice",+ filename: `${id}.png`,+ url: `https://cdn.example.test/${id}.png`,+ download_url: `https://cdn.example.test/${id}.png`,+ markdown_url: `https://app.example.test/api/attachments/${id}/download`,+ content_type: "image/png",+ size_bytes: 10,+ created_at: "2026-06-12T00:00:00Z",+ };+}++const pending = (id: string): DraftUpload => ({+ clientUploadId: id,+ status: "uploading",+ filename: `${id}.png`,+ size: 5,+ contentType: "image/png",+});++describe("draft-upload helpers", () => {+ it("uploadedAttachments returns only completed rows, in order", () => {+ const uploads: DraftUpload[] = [+ pending("a"),+ attachmentToDraftUpload(makeAttachment("att-1")),+ { clientUploadId: "c", status: "failed", filename: "x", size: 1 },+ attachmentToDraftUpload(makeAttachment("att-2")),+ ];+ expect(uploadedAttachments(uploads).map((a) => a.id)).toEqual(["att-1", "att-2"]);+ });++ it("hasUploadingDraft is true only while a placeholder is in flight", () => {+ expect(hasUploadingDraft([pending("a")])).toBe(true);+ expect(+ hasUploadingDraft([+ attachmentToDraftUpload(makeAttachment("att-1")),+ { clientUploadId: "c", status: "failed", filename: "x", size: 1 },+ ]),+ ).toBe(false);+ });++ it("wraps a bare persisted Attachment as an uploaded placeholder (pre-L2 migration)", () => {+ const normalized = normalizeStoredUploads([makeAttachment("att-1")]);+ expect(normalized).toHaveLength(1);+ expect(normalized[0]?.status).toBe("uploaded");+ expect(uploadedAttachments(normalized).map((a) => a.id)).toEqual(["att-1"]);+ });++ it("coerces an `uploading` placeholder to `interrupted` on load", () => {+ const normalized = normalizeStoredUploads([pending("a")]);+ expect(normalized).toHaveLength(1);+ expect(normalized[0]?.status).toBe("interrupted");+ // The bytes are gone, so it is NOT a bindable attachment.+ expect(uploadedAttachments(normalized)).toEqual([]);+ });++ it("keeps failed/interrupted/uploaded placeholders across load", () => {+ const stored: DraftUpload[] = [+ { clientUploadId: "f", status: "failed", filename: "f", size: 1 },+ { clientUploadId: "i", status: "interrupted", filename: "i", size: 1 },+ attachmentToDraftUpload(makeAttachment("att-1")),+ ];+ const normalized = normalizeStoredUploads(stored);+ expect(normalized.map((u) => u.status)).toEqual(["failed", "interrupted", "uploaded"]);+ });++ it("drops junk entries and non-arrays", () => {+ expect(normalizeStoredUploads(undefined)).toEqual([]);+ expect(normalizeStoredUploads([null, 42, { foo: "bar" }])).toEqual([]);+ // An `uploaded` entry with a broken attachment is not trusted.+ expect(+ normalizeStoredUploads([{ clientUploadId: "x", status: "uploaded", filename: "x", size: 1 }]),+ ).toEqual([]);+ });+});diff --git a/packages/core/drafts/draft-upload.ts b/packages/core/drafts/draft-upload.tsnew file mode 100644index 0000000000..2c83eacbd8--- /dev/null+++ b/packages/core/drafts/draft-upload.ts@@ -0,0 +1,138 @@+import type { Attachment } from "../types";++/**+ * Persistable upload placeholder + result (MUL-5181, L2).+ *+ * Before this, a composer draft stored only COMPLETED `Attachment` rows, so an+ * upload that was still mid-flight when the composer closed had no persisted+ * representation: reopening showed nothing, and a reload/app-restart left no+ * trace that a file had ever been dropped. Modelled on Linear's local store+ * (a first-class `uploads` record carrying `uploadId` + `uploadState`, linked+ * to the draft), a `DraftUpload` lives in the persisted draft from the moment+ * the file is picked, so the upload's lifecycle survives the component that+ * started it.+ *+ * The `clientUploadId` is a client-minted id that ties the placeholder to the+ * module-level {@link UploadCoordinator} running the actual request. It is NOT+ * the server attachment id (which does not exist until the upload completes).+ */+export type UploadStatus = "uploading" | "uploaded" | "failed" | "interrupted";++interface DraftUploadBase {+ /** Client-minted id, stable across the placeholder's whole lifecycle. */+ clientUploadId: string;+ filename: string;+ /** Byte size, mirrored so a placeholder can render without the File. */+ size: number;+ contentType?: string;+}++/**+ * A placeholder whose bytes are not (or no longer) resolvable to an attachment:+ * - `uploading`: request in flight (owned by the coordinator).+ * - `failed`: the request errored; keep it so the user sees the failure.+ * - `interrupted`: was `uploading` when the app was reloaded/restarted; the+ * bytes were never persisted so the request cannot be resumed.+ */+export interface PendingDraftUpload extends DraftUploadBase {+ status: "uploading" | "failed" | "interrupted";+ /** Present for `failed`; the surfaced error message. */+ error?: string;+}++/** A completed upload carrying the full server attachment row. */+export interface UploadedDraftUpload extends DraftUploadBase {+ status: "uploaded";+ attachment: Attachment;+}++export type DraftUpload = PendingDraftUpload | UploadedDraftUpload;++/** True for a completed upload (narrows to {@link UploadedDraftUpload}). */+export function isUploaded(u: DraftUpload): u is UploadedDraftUpload {+ return u.status === "uploaded";+}++/** The completed attachment rows, in order. The submit-bindable set. */+export function uploadedAttachments(uploads: readonly DraftUpload[]): Attachment[] {+ const out: Attachment[] = [];+ for (const u of uploads) {+ if (u.status === "uploaded") out.push(u.attachment);+ }+ return out;+}++/** True while any upload is still in flight — the submit gate reads this. */+export function hasUploadingDraft(uploads: readonly DraftUpload[]): boolean {+ return uploads.some((u) => u.status === "uploading");+}++/** Wrap a completed attachment as an uploaded placeholder. */+export function attachmentToDraftUpload(attachment: Attachment): UploadedDraftUpload {+ return {+ clientUploadId: attachment.id || attachment.url,+ status: "uploaded",+ filename: attachment.filename,+ size: attachment.size_bytes,+ contentType: attachment.content_type || undefined,+ // `download_url` is minted for the current API response and may be a+ // short-lived signed URL; draft uploads survive dialog closes and app+ // restarts, so it is stripped here. `url`/`markdown_url` stay as the+ // durable render/download paths, and content-editor's session merge+ // backfills an empty download_url from the live upload result.+ attachment: { ...attachment, download_url: "" },+ };+}++function looksLikeAttachment(value: unknown): value is Attachment {+ return (+ typeof value === "object" &&+ value !== null &&+ typeof (value as { id?: unknown }).id === "string" &&+ typeof (value as { filename?: unknown }).filename === "string" &&+ typeof (value as { url?: unknown }).url === "string"+ );+}++function isDraftUploadShape(value: unknown): value is DraftUpload {+ return (+ typeof value === "object" &&+ value !== null &&+ typeof (value as { clientUploadId?: unknown }).clientUploadId === "string" &&+ typeof (value as { status?: unknown }).status === "string"+ );+}++/**+ * Normalize a raw persisted array into `DraftUpload[]`:+ * - already-`DraftUpload` entries are kept, EXCEPT any still in `uploading`,+ * which become `interrupted` — a reload/restart cannot resume the bytes.+ * - bare `Attachment` rows (persisted by pre-L2 builds that stored only+ * completed attachments) are wrapped as `uploaded`.+ * - anything else is dropped.+ *+ * Runs on every load/rehydrate and on `set` writes, so the in-memory shape is+ * always canonical regardless of which build wrote the persisted blob.+ */+export function normalizeStoredUploads(raw: unknown): DraftUpload[] {+ if (!Array.isArray(raw)) return [];+ const out: DraftUpload[] = [];+ for (const item of raw) {+ if (isDraftUploadShape(item)) {+ if (item.status === "uploading") {+ const { clientUploadId, filename, size, contentType } = item;+ out.push({ clientUploadId, status: "interrupted", filename, size, contentType });+ } else if (item.status === "uploaded") {+ // Trust the persisted attachment only if it still looks like one.+ if (looksLikeAttachment((item as UploadedDraftUpload).attachment)) {+ out.push(item);+ }+ } else {+ out.push(item);+ }+ } else if (looksLikeAttachment(item)) {+ out.push(attachmentToDraftUpload(item));+ }+ }+ return out;+}diff --git a/packages/core/drafts/index.ts b/packages/core/drafts/index.tsnew file mode 100644index 0000000000..3d5518a85d--- /dev/null+++ b/packages/core/drafts/index.ts@@ -0,0 +1,30 @@+export {+ createDraftStore,+ type DraftStore,+ type DraftStoreConfig,+} from "./create-draft-store";+export {+ registerDraftCleanup,+ clearRegisteredWorkspaceDrafts,+ resetAllRegisteredDrafts,+ type DraftCleanupEntry,+} from "./cleanup-registry";+export {+ startUpload,+ abortUpload,+ abortAll,+ type StartUploadArgs,+ type UploadOutcome,+ type UploadCoordinatorContext,+} from "./upload-coordinator";+export {+ type DraftUpload,+ type PendingDraftUpload,+ type UploadedDraftUpload,+ type UploadStatus,+ isUploaded,+ uploadedAttachments,+ hasUploadingDraft,+ attachmentToDraftUpload,+ normalizeStoredUploads,+} from "./draft-upload";diff --git a/packages/core/drafts/register-all-drafts.ts b/packages/core/drafts/register-all-drafts.tsnew file mode 100644index 0000000000..6762d731a7--- /dev/null+++ b/packages/core/drafts/register-all-drafts.ts@@ -0,0 +1,21 @@+/**+ * Side-effect module that imports every module-level draft store so their+ * `registerDraftCleanup` calls have run before any cleanup path executes.+ *+ * Self-registration (see cleanup-registry) only knows about stores that have+ * been imported. A cleanup caller that imports only its own module would+ * otherwise see an empty registry and skip persisted draft keys whose store+ * happened not to be loaded yet — a narrower version of the very leak this+ * system exists to fix. Importing this module from `storage-cleanup` guarantees+ * the registry is complete wherever cleanup runs.+ *+ * Chat is intentionally absent: its keys are registered inside `createChatStore`+ * (the store is instance-scoped, created by the chat provider), so its keys+ * only exist once that instance does, and registration is tied to the same+ * lifecycle. There is nothing to import here that would register them earlier.+ */+import "../issues/stores/draft-store";+import "../issues/stores/quick-create-store";+import "../issues/stores/comment-draft-store";+import "../projects/draft-store";+import "../feedback/draft-store";diff --git a/packages/core/drafts/upload-coordinator.test.ts b/packages/core/drafts/upload-coordinator.test.tsnew file mode 100644index 0000000000..645146cad8--- /dev/null+++ b/packages/core/drafts/upload-coordinator.test.ts@@ -0,0 +1,155 @@+import { afterEach, describe, expect, it, vi } from "vitest";+import type { ApiClient } from "../api/client";+import type { Attachment } from "../types";+import {+ startUpload,+ abortAll,+ abortUpload,+ __trackedUploadCountForTest,+ type UploadOutcome,+} from "./upload-coordinator";++function makeAttachment(id: string): Attachment {+ return {+ id,+ workspace_id: "ws-1",+ issue_id: "issue-1",+ comment_id: null,+ chat_session_id: null,+ chat_message_id: null,+ uploader_type: "member",+ uploader_id: "alice",+ filename: `${id}.png`,+ url: `https://cdn.example.test/${id}.png`,+ download_url: `https://cdn.example.test/${id}.png`,+ markdown_url: `https://app.example.test/api/attachments/${id}/download`,+ content_type: "image/png",+ size_bytes: 10,+ created_at: "2026-06-12T00:00:00Z",+ };+}++const file = () => new File(["x"], "shot.png", { type: "image/png" });+const tick = () => new Promise((r) => setTimeout(r, 0));++/** An api whose uploadFile resolves/rejects/aborts under the test's control. */+function abortableApi(): {+ api: Pick<ApiClient, "uploadFile">;+ resolve: (att: Attachment) => void;+ reject: (err: Error) => void;+ sawSignal: () => AbortSignal | undefined;+} {+ let resolveFn: (att: Attachment) => void = () => {};+ let rejectFn: (err: Error) => void = () => {};+ let captured: AbortSignal | undefined;+ const uploadFile = vi.fn(+ (_f: File, _opts?: unknown, signal?: AbortSignal): Promise<Attachment> => {+ captured = signal;+ return new Promise<Attachment>((resolve, reject) => {+ resolveFn = resolve;+ // Reject with an AbortError the moment the signal fires — this is what+ // the real `fetch` does on abort.+ signal?.addEventListener("abort", () => {+ const err = new Error("aborted");+ err.name = "AbortError";+ reject(err);+ });+ rejectFn = reject;+ });+ },+ );+ return {+ api: { uploadFile } as unknown as Pick<ApiClient, "uploadFile">,+ resolve: (att) => resolveFn(att),+ reject: (err) => rejectFn(err),+ sawSignal: () => captured,+ };+}++afterEach(() => {+ abortAll();+});++describe("upload coordinator", () => {+ it("delivers the attachment on success and stops tracking", async () => {+ const { api, resolve } = abortableApi();+ const settled: UploadOutcome[] = [];++ startUpload({+ clientUploadId: "c1",+ file: file(),+ api,+ ctx: { issueId: "issue-1" },+ onSettled: (o) => settled.push(o),+ });+ expect(__trackedUploadCountForTest()).toBe(1);++ resolve(makeAttachment("att-1"));+ await tick();++ expect(settled).toHaveLength(1);+ expect(settled[0]).toMatchObject({ clientUploadId: "c1", status: "uploaded" });+ expect(settled[0]).toHaveProperty("attachment.id", "att-1");+ expect(__trackedUploadCountForTest()).toBe(0);+ });++ it("forwards the upload context to api.uploadFile", async () => {+ const { api } = abortableApi();+ startUpload({+ clientUploadId: "c1",+ file: file(),+ api,+ ctx: { commentId: "cmt-9", chatSessionId: "sess-3" },+ onSettled: () => {},+ });+ expect(api.uploadFile).toHaveBeenCalledWith(+ expect.any(File),+ { issueId: undefined, commentId: "cmt-9", chatSessionId: "sess-3" },+ expect.any(AbortSignal),+ );+ });++ it("reports a non-abort error as failed", async () => {+ const { api, reject } = abortableApi();+ const settled: UploadOutcome[] = [];++ startUpload({ clientUploadId: "c1", file: file(), api, onSettled: (o) => settled.push(o) });+ reject(new Error("boom"));+ await tick();++ expect(settled).toHaveLength(1);+ expect(settled[0]).toMatchObject({ clientUploadId: "c1", status: "failed" });+ expect((settled[0] as { error: Error }).error.message).toBe("boom");+ expect(__trackedUploadCountForTest()).toBe(0);+ });++ it("does NOT call onSettled when aborted", async () => {+ const { api } = abortableApi();+ const settled: UploadOutcome[] = [];++ startUpload({ clientUploadId: "c1", file: file(), api, onSettled: (o) => settled.push(o) });+ abortUpload("c1");+ await tick();++ expect(settled).toHaveLength(0);+ expect(__trackedUploadCountForTest()).toBe(0);+ });++ it("aborts every tracked upload on abortAll and settles none", async () => {+ const a = abortableApi();+ const b = abortableApi();+ const settled: UploadOutcome[] = [];++ startUpload({ clientUploadId: "c1", file: file(), api: a.api, onSettled: (o) => settled.push(o) });+ startUpload({ clientUploadId: "c2", file: file(), api: b.api, onSettled: (o) => settled.push(o) });+ expect(__trackedUploadCountForTest()).toBe(2);++ abortAll();+ await tick();++ expect(settled).toHaveLength(0);+ expect(__trackedUploadCountForTest()).toBe(0);+ expect(a.sawSignal()?.aborted).toBe(true);+ expect(b.sawSignal()?.aborted).toBe(true);+ });+});diff --git a/packages/core/drafts/upload-coordinator.ts b/packages/core/drafts/upload-coordinator.tsnew file mode 100644index 0000000000..52eb7af31e--- /dev/null+++ b/packages/core/drafts/upload-coordinator.ts@@ -0,0 +1,131 @@+import type { ApiClient } from "../api/client";+import type { Attachment } from "../types";+import { createLogger } from "../logger";++/**+ * Module-level file-upload coordinator (MUL-5181, L2).+ *+ * Ownership inversion: an upload is owned here, NOT by the React component that+ * started it. The composer only records a persisted placeholder (a+ * `DraftUpload`) in its draft and hands the file to `startUpload`; the request+ * then outlives the composer's mount. Closing the editor/modal no longer aborts+ * the upload — its result lands in the persisted draft through `onSettled`, so+ * reopening the composer shows the attachment.+ *+ * The coordinator itself knows nothing about drafts. `onSettled` fires with the+ * outcome and the CALLER is responsible for the generation guard: it must check+ * that its draft still tracks `clientUploadId` before writing (the draft may+ * have been cleared/submitted, or the placeholder removed, while the request+ * was in flight).+ *+ * Abort (`abortAll`) is the one thing a plain fire-and-forget promise cannot do:+ * on logout, every tracked request is cancelled so the previous user's bytes+ * never bind to an attachment under the next session.+ */++const logger = createLogger("drafts.upload-coordinator");++export interface UploadCoordinatorContext {+ issueId?: string;+ commentId?: string;+ chatSessionId?: string;+}++export type UploadOutcome =+ | { clientUploadId: string; status: "uploaded"; attachment: Attachment }+ | { clientUploadId: string; status: "failed"; error: Error };++export interface StartUploadArgs {+ /** Client-minted id tying this request to its persisted `DraftUpload`. */+ clientUploadId: string;+ file: File;+ /** Injected so the coordinator is framework-agnostic and unit-testable. */+ api: Pick<ApiClient, "uploadFile">;+ ctx?: UploadCoordinatorContext;+ /**+ * Settled outcome. NOT called on abort — an aborted upload leaves its+ * placeholder in `uploading`, which the store coerces to `interrupted` only+ * on the next load (aborts happen on logout, where the placeholder is cleared+ * anyway). The caller MUST re-check its draft still tracks `clientUploadId`+ * before writing the result.+ */+ onSettled: (outcome: UploadOutcome) => void;+}++const controllers = new Map<string, AbortController>();++/**+ * Start an upload owned by this module. Returns immediately; the outcome is+ * delivered through `onSettled`. Safe to call for a `clientUploadId` already in+ * flight (the newer controller replaces the map entry — callers mint unique+ * ids, so this is a defensive no-op in practice).+ */+export function startUpload({+ clientUploadId,+ file,+ api,+ ctx,+ onSettled,+}: StartUploadArgs): void {+ const controller = new AbortController();+ controllers.set(clientUploadId, controller);++ void (async () => {+ try {+ const attachment = await api.uploadFile(+ file,+ {+ issueId: ctx?.issueId,+ commentId: ctx?.commentId,+ chatSessionId: ctx?.chatSessionId,+ },+ controller.signal,+ );+ onSettled({ clientUploadId, status: "uploaded", attachment });+ } catch (err) {+ // An abort is not a failure: leave the placeholder untouched so it reads+ // as "interrupted" on the next load. Every other error surfaces.+ if (controller.signal.aborted || (err instanceof Error && err.name === "AbortError")) {+ logger.info("upload aborted", { clientUploadId });+ return;+ }+ onSettled({+ clientUploadId,+ status: "failed",+ error: err instanceof Error ? err : new Error("Upload failed"),+ });+ } finally {+ // Only drop the entry if it is still ours — a racing re-start under the+ // same id must not have its controller evicted by our finally.+ if (controllers.get(clientUploadId) === controller) {+ controllers.delete(clientUploadId);+ }+ }+ })();+}++/** Abort a single tracked upload, if present. */+export function abortUpload(clientUploadId: string): void {+ const controller = controllers.get(clientUploadId);+ if (!controller) return;+ controllers.delete(clientUploadId);+ controller.abort();+}++/**+ * Abort every tracked upload. Called on logout (before drafts are cleared) so+ * no in-flight upload can bind an attachment under the next session.+ */+export function abortAll(): void {+ if (controllers.size === 0) return;+ logger.info("aborting all uploads", { count: controllers.size });+ for (const controller of controllers.values()) {+ controller.abort();+ }+ controllers.clear();+}++/** Test-only: number of uploads currently tracked. */+export function __trackedUploadCountForTest(): number {+ return controllers.size;+}diff --git a/packages/core/feedback/draft-store.ts b/packages/core/feedback/draft-store.tsindex 91587b37bb..ae6eb7d4c6 100644--- a/packages/core/feedback/draft-store.ts+++ b/packages/core/feedback/draft-store.ts@@ -1,41 +1,11 @@-import { create } from "zustand";-import { createJSONStorage, persist } from "zustand/middleware";-import { createWorkspaceAwareStorage, registerForWorkspaceRehydration } from "../platform/workspace-storage";-import { defaultStorage } from "../platform/storage";+import { createDraftStore } from "../drafts/create-draft-store";interface FeedbackDraft {message: string;}-const EMPTY_DRAFT: FeedbackDraft = {- message: "",-};--interface FeedbackDraftStore {- draft: FeedbackDraft;- setDraft: (patch: Partial<FeedbackDraft>) => void;- clearDraft: () => void;- hasDraft: () => boolean;-}--export const useFeedbackDraftStore = create<FeedbackDraftStore>()(- persist(- (set, get) => ({- draft: { ...EMPTY_DRAFT },- setDraft: (patch) =>- set((s) => ({ draft: { ...s.draft, ...patch } })),- clearDraft: () =>- set({ draft: { ...EMPTY_DRAFT } }),- hasDraft: () => {- const { draft } = get();- return !!draft.message;- },- }),- {- name: "multica_feedback_draft",- storage: createJSONStorage(() => createWorkspaceAwareStorage(defaultStorage)),- },- ),-);--registerForWorkspaceRehydration(() => useFeedbackDraftStore.persist.rehydrate());+export const useFeedbackDraftStore = createDraftStore<FeedbackDraft>({+ storageKey: "multica_feedback_draft",+ emptyData: { message: "" },+ hasMeaningful: (d) => !!d.message,+});diff --git a/packages/core/hooks/use-file-upload.ts b/packages/core/hooks/use-file-upload.tsindex 8338ef9d0b..68e92916df 100644--- a/packages/core/hooks/use-file-upload.ts+++ b/packages/core/hooks/use-file-upload.ts@@ -80,6 +80,15 @@ function pickMarkdownLink(att: Attachment): string {return att.url;}+// Adapt a completed server `Attachment` into the editor's `UploadResult` (the+// two URL fields the editor writes into markdown / persists). Exported so the+// coordinated-upload path (MUL-5181), which runs the request through the+// module-level upload coordinator rather than this hook, can hand the editor+// the exact same shape for its inline preview swap.+export function toUploadResult(att: Attachment): UploadResult {+ return { ...att, link: att.url, markdownLink: pickMarkdownLink(att) };+}+export function useFileUpload(api: ApiClient,// Receives the failing `file` alongside the error so hosts can name it in@@ -117,7 +126,7 @@ export function useFileUpload(commentId: ctx?.commentId,chatSessionId: ctx?.chatSessionId,});- return { ...att, link: att.url, markdownLink: pickMarkdownLink(att) };+ return toUploadResult(att);} finally {setInFlight((n) => n - 1);}diff --git a/packages/core/issues/stores/comment-draft-store.test.ts b/packages/core/issues/stores/comment-draft-store.test.tsnew file mode 100644index 0000000000..341dc8ca2e--- /dev/null+++ b/packages/core/issues/stores/comment-draft-store.test.ts@@ -0,0 +1,329 @@+// @vitest-environment jsdom+import { afterEach, beforeAll, beforeEach, describe, expect, it } from "vitest";+import { useCommentDraftStore } from "./comment-draft-store";+import { setCurrentWorkspace } from "../../platform/workspace-storage";+import type { Attachment } from "../../types";++const flush = () => new Promise((resolve) => queueMicrotask(() => resolve(null)));++// Node 25 ships a partial `localStorage` shim under jsdom that's missing+// `clear`/`removeItem`; replace it with a real in-memory Storage so persist+// can round-trip values.+beforeAll(() => {+ if (typeof globalThis.localStorage?.clear !== "function") {+ const values = new Map<string, string>();+ const storage: Storage = {+ get length() { return values.size; },+ clear: () => values.clear(),+ getItem: (k) => values.get(k) ?? null,+ key: (i) => Array.from(values.keys())[i] ?? null,+ removeItem: (k) => { values.delete(k); },+ setItem: (k, v) => { values.set(k, v); },+ };+ Object.defineProperty(globalThis, "localStorage", { configurable: true, value: storage });+ Object.defineProperty(window, "localStorage", { configurable: true, value: storage });+ }+});++function makeAttachment(id: string): Attachment {+ return {+ id,+ workspace_id: "ws-1",+ issue_id: "issue-1",+ comment_id: null,+ chat_session_id: null,+ chat_message_id: null,+ uploader_type: "member",+ uploader_id: "alice",+ filename: `${id}.png`,+ url: `https://cdn.example.test/${id}.png`,+ download_url: `https://cdn.example.test/${id}.png`,+ markdown_url: `https://app.example.test/api/attachments/${id}/download`,+ content_type: "image/png",+ size_bytes: 123,+ created_at: "2026-06-12T00:00:00Z",+ };+}++const DAY_MS = 24 * 60 * 60 * 1000;++describe("comment draft store — attachments in the draft", () => {+ beforeEach(() => {+ useCommentDraftStore.setState({ drafts: {} });+ });++ it("persists attachments alongside content under the same key", () => {+ const { setDraft, setAttachments, getDraft, getAttachments } =+ useCommentDraftStore.getState();++ setDraft("new:issue-1", "look at this");+ setAttachments("new:issue-1", [makeAttachment("att-1")]);++ expect(getDraft("new:issue-1")).toBe("look at this");+ expect(getAttachments("new:issue-1").map((a) => a.id)).toEqual(["att-1"]);+ });++ it("setDraft preserves already-uploaded attachments", () => {+ const { setAttachments, setDraft, getAttachments } =+ useCommentDraftStore.getState();++ setAttachments("new:issue-1", [makeAttachment("att-1")]);+ setDraft("new:issue-1", "typed after uploading");++ expect(getAttachments("new:issue-1").map((a) => a.id)).toEqual(["att-1"]);+ });++ it("setAttachments preserves the in-progress text", () => {+ const { setDraft, setAttachments, getDraft } = useCommentDraftStore.getState();++ setDraft("new:issue-1", "half a sentence");+ setAttachments("new:issue-1", [makeAttachment("att-1")]);++ expect(getDraft("new:issue-1")).toBe("half a sentence");+ });++ it("returns a stable empty-attachments reference for a missing draft", () => {+ const { getAttachments } = useCommentDraftStore.getState();+ // A fresh allocation on each read would re-render every subscribing editor.+ expect(getAttachments("new:issue-1")).toBe(getAttachments("reply:issue-1:c-1"));+ });++ it("keeps an attachment-only draft (empty text) instead of dropping it", () => {+ const { setAttachments, setDraft, getAttachments, getDraft } =+ useCommentDraftStore.getState();++ setAttachments("new:issue-1", [makeAttachment("att-1")]);+ // The user clears all text but the uploaded file must survive.+ setDraft("new:issue-1", "");++ expect(getDraft("new:issue-1")).toBe("");+ expect(getAttachments("new:issue-1").map((a) => a.id)).toEqual(["att-1"]);+ });++ it("drops the entry once text AND attachments are both empty", () => {+ const { setDraft, setAttachments } = useCommentDraftStore.getState();++ setDraft("new:issue-1", "something");+ setAttachments("new:issue-1", [makeAttachment("att-1")]);++ setDraft("new:issue-1", "");+ setAttachments("new:issue-1", []);++ expect("new:issue-1" in useCommentDraftStore.getState().drafts).toBe(false);+ });++ it("clearDraft removes both content and attachments", () => {+ const { setDraft, setAttachments, clearDraft } = useCommentDraftStore.getState();++ setDraft("new:issue-1", "draft body");+ setAttachments("new:issue-1", [makeAttachment("att-1")]);+ clearDraft("new:issue-1");++ expect("new:issue-1" in useCommentDraftStore.getState().drafts).toBe(false);+ expect(useCommentDraftStore.getState().getAttachments("new:issue-1")).toEqual([]);+ });+});++describe("comment draft store — prune on rehydrate", () => {+ const KEY = "multica_comment_drafts:acme";++ beforeEach(() => {+ localStorage.clear();+ setCurrentWorkspace(null, null);+ useCommentDraftStore.setState({ drafts: {} });+ });++ afterEach(() => {+ setCurrentWorkspace(null, null);+ });++ function seed(drafts: Record<string, unknown>) {+ localStorage.setItem(KEY, JSON.stringify({ state: { drafts }, version: 0 }));+ }++ it("keeps a recent attachment-only draft through the TTL prune", async () => {+ seed({+ "new:issue-1": {+ content: "",+ attachments: [makeAttachment("att-1")],+ updatedAt: Date.now(),+ },+ });++ setCurrentWorkspace("acme", "ws_a");+ await flush();+ await flush();++ const state = useCommentDraftStore.getState();+ expect(state.getDraft("new:issue-1")).toBe("");+ expect(state.getAttachments("new:issue-1").map((a) => a.id)).toEqual(["att-1"]);+ });++ it("drops a draft with neither text nor attachments", async () => {+ seed({+ "new:issue-1": { content: " ", attachments: [], updatedAt: Date.now() },+ });++ setCurrentWorkspace("acme", "ws_a");+ await flush();+ await flush();++ expect("new:issue-1" in useCommentDraftStore.getState().drafts).toBe(false);+ });++ it("drops a stale draft even when it still carries attachments", async () => {+ seed({+ "new:issue-1": {+ content: "old",+ attachments: [makeAttachment("att-1")],+ updatedAt: Date.now() - 31 * DAY_MS,+ },+ });++ setCurrentWorkspace("acme", "ws_a");+ await flush();+ await flush();++ expect("new:issue-1" in useCommentDraftStore.getState().drafts).toBe(false);+ });++ it("backfills an empty attachments array for legacy drafts written before the field", async () => {+ seed({+ // No `attachments` — persisted by a build that predated the field.+ "new:issue-1": { content: "legacy body", updatedAt: Date.now() },+ });++ setCurrentWorkspace("acme", "ws_a");+ await flush();+ await flush();++ const state = useCommentDraftStore.getState();+ expect(state.getDraft("new:issue-1")).toBe("legacy body");+ expect(state.getAttachments("new:issue-1")).toEqual([]);+ });++ it("coerces an upload that was in flight at reload into an interrupted placeholder", async () => {+ seed({+ "new:issue-1": {+ content: "",+ attachments: [+ { clientUploadId: "c1", status: "uploading", filename: "shot.png", size: 9 },+ ],+ updatedAt: Date.now(),+ },+ });++ setCurrentWorkspace("acme", "ws_a");+ await flush();+ await flush();++ const state = useCommentDraftStore.getState();+ // The placeholder survives (so the UI can show "interrupted"), but its+ // bytes are gone — it is NOT a bindable attachment.+ const uploads = state.getUploads("new:issue-1");+ expect(uploads.map((u) => u.status)).toEqual(["interrupted"]);+ expect(state.getAttachments("new:issue-1")).toEqual([]);+ });+});++describe("comment draft store — upload lifecycle", () => {+ beforeEach(() => {+ useCommentDraftStore.setState({ drafts: {} });+ });++ const KEY = "new:issue-1" as const;++ it("addUpload records an uploading placeholder that blocks the bindable set", () => {+ const s = useCommentDraftStore.getState();+ s.addUpload(KEY, { clientUploadId: "c1", status: "uploading", filename: "shot.png", size: 9 });++ expect(s.getUploads(KEY).map((u) => u.status)).toEqual(["uploading"]);+ // A placeholder is not yet bindable.+ expect(s.getAttachments(KEY)).toEqual([]);+ });++ it("settleUpload swaps the placeholder for its attachment", () => {+ const s = useCommentDraftStore.getState();+ s.addUpload(KEY, { clientUploadId: "c1", status: "uploading", filename: "shot.png", size: 9 });+ s.settleUpload(KEY, "c1", makeAttachment("att-1"));++ expect(s.getUploads(KEY).map((u) => u.status)).toEqual(["uploaded"]);+ expect(s.getAttachments(KEY).map((a) => a.id)).toEqual(["att-1"]);+ });++ it("an identical setDraft is a no-op that preserves entry identity", () => {+ // The stale-submit guard compares entry identity; the composers' tab-switch+ // flush re-writes identical content mid-flight and must not mint a new+ // entry (that would read as an edit and keep a submitted draft alive).+ const s = useCommentDraftStore.getState();+ s.setDraft(KEY, "same words");+ const before = useCommentDraftStore.getState().drafts[KEY];+ s.setDraft(KEY, "same words");+ expect(useCommentDraftStore.getState().drafts[KEY]).toBe(before);++ s.setDraft(KEY, "different words");+ expect(useCommentDraftStore.getState().drafts[KEY]).not.toBe(before);+ });++ it("appendToDraftContent lands a fragment after existing text, keeping uploads", () => {+ const s = useCommentDraftStore.getState();+ s.setDraft(KEY, "wip text");+ s.addUpload(KEY, { clientUploadId: "c1", status: "uploading", filename: "shot.png", size: 9 });++ s.appendToDraftContent(KEY, "");++ expect(useCommentDraftStore.getState().getDraft(KEY)).toBe(+ "wip text\n\n",+ );+ expect(useCommentDraftStore.getState().getUploads(KEY)).toHaveLength(1);+ });++ it("appendToDraftContent on an empty draft is just the fragment", () => {+ const s = useCommentDraftStore.getState();+ s.appendToDraftContent(KEY, "[doc.pdf](https://cdn.example/doc.pdf)");++ expect(useCommentDraftStore.getState().getDraft(KEY)).toBe(+ "[doc.pdf](https://cdn.example/doc.pdf)",+ );+ });++ it("settleUpload is a no-op once the placeholder is gone (generation guard)", () => {+ const s = useCommentDraftStore.getState();+ s.addUpload(KEY, { clientUploadId: "c1", status: "uploading", filename: "shot.png", size: 9 });+ s.clearDraft(KEY);+ // Late settle after the draft was submitted/cleared must not resurrect it.+ s.settleUpload(KEY, "c1", makeAttachment("att-1"));++ expect(KEY in useCommentDraftStore.getState().drafts).toBe(false);+ });++ it("failUpload marks the placeholder failed but keeps it", () => {+ const s = useCommentDraftStore.getState();+ s.addUpload(KEY, { clientUploadId: "c1", status: "uploading", filename: "shot.png", size: 9 });+ s.failUpload(KEY, "c1", "network down");++ const uploads = s.getUploads(KEY);+ expect(uploads.map((u) => u.status)).toEqual(["failed"]);+ expect(uploads[0]).toMatchObject({ error: "network down" });+ expect(s.getAttachments(KEY)).toEqual([]);+ });++ it("removeUpload drops a placeholder and clears the draft when nothing is left", () => {+ const s = useCommentDraftStore.getState();+ s.addUpload(KEY, { clientUploadId: "c1", status: "uploading", filename: "shot.png", size: 9 });+ s.removeUpload(KEY, "c1");++ expect(KEY in useCommentDraftStore.getState().drafts).toBe(false);+ });++ it("keeps getAttachments referentially stable across unrelated touches", () => {+ const s = useCommentDraftStore.getState();+ s.addUpload(KEY, { clientUploadId: "c1", status: "uploading", filename: "shot.png", size: 9 });+ s.settleUpload(KEY, "c1", makeAttachment("att-1"));++ const first = useCommentDraftStore.getState().getAttachments(KEY);+ // A read again without a mutation must return the identical array.+ const second = useCommentDraftStore.getState().getAttachments(KEY);+ expect(first).toBe(second);+ });+});diff --git a/packages/core/issues/stores/comment-draft-store.ts b/packages/core/issues/stores/comment-draft-store.tsindex cf30a3bcd3..0088239f71 100644--- a/packages/core/issues/stores/comment-draft-store.ts+++ b/packages/core/issues/stores/comment-draft-store.ts@@ -2,6 +2,15 @@ import { create } from "zustand";import { createJSONStorage, persist } from "zustand/middleware";import { createWorkspaceAwareStorage, registerForWorkspaceRehydration } from "../../platform/workspace-storage";import { defaultStorage } from "../../platform/storage";+import { registerDraftCleanup } from "../../drafts/cleanup-registry";+import {+ type DraftUpload,+ type PendingDraftUpload,+ attachmentToDraftUpload,+ normalizeStoredUploads,+ uploadedAttachments,+} from "../../drafts/draft-upload";+import type { Attachment } from "../../types";/*** Per-comment draft persistence — survives:@@ -10,6 +19,15 @@ import { defaultStorage } from "../../platform/storage";* - tab close / accidental Cmd-W* - reload*+ * A draft holds both the in-progress text AND the uploads started in the same+ * composer session (MUL-5181). Uploads used to live in component `useState`,+ * so closing or scrolling the composer away dropped in-flight and already-+ * uploaded files; persisting them here keeps them recoverable exactly like the+ * text. Each upload is a {@link DraftUpload} that carries its status — an+ * in-flight placeholder (owned by the upload coordinator) becomes the full+ * attachment once it settles, and a placeholder still `uploading` at load time+ * is coerced to `interrupted` because the bytes were never persisted.+ ** Keys are issue-scoped because createWorkspaceAwareStorage only partitions* by workspace, not by issue. Without issueId in the key, two issues with* thread replies open in adjacent desktop tabs would collide.@@ -22,13 +40,36 @@ export type CommentDraftKey =interface CommentDraft {content: string;+ /** Uploads (placeholders + completed) for this composer session. */+ attachments: DraftUpload[];updatedAt: number;}interface CommentDraftStore {drafts: Record<string, CommentDraft>;getDraft: (key: CommentDraftKey) => string | undefined;+ /** Completed attachment rows only — the submit-bindable / preview set. */+ getAttachments: (key: CommentDraftKey) => Attachment[];+ /** Every upload for this draft (placeholders included) — for status chips. */+ getUploads: (key: CommentDraftKey) => DraftUpload[];setDraft: (key: CommentDraftKey, content: string) => void;+ /**+ * Append a markdown fragment to the draft body (upload write-back,+ * MUL-5181): an upload that finished after its composer unmounted has no+ * live editor to insert its link, so the settle handler lands it here —+ * the draft body stays the single source of truth for what gets bound.+ */+ appendToDraftContent: (key: CommentDraftKey, markdown: string) => void;+ /** Replace the upload list with completed attachments (legacy/compat path). */+ setAttachments: (key: CommentDraftKey, attachments: Attachment[]) => void;+ /** Record a placeholder the moment a file is picked (coordinator-owned). */+ addUpload: (key: CommentDraftKey, upload: DraftUpload) => void;+ /** Swap a placeholder for its completed attachment. No-op if it's gone. */+ settleUpload: (key: CommentDraftKey, clientUploadId: string, attachment: Attachment) => void;+ /** Mark a placeholder failed. No-op if it's gone. */+ failUpload: (key: CommentDraftKey, clientUploadId: string, error?: string) => void;+ /** Drop a placeholder (e.g. a dismissed failure). */+ removeUpload: (key: CommentDraftKey, clientUploadId: string) => void;clearDraft: (key: CommentDraftKey) => void;}@@ -37,12 +78,75 @@ interface CommentDraftStore {// slowly leak localStorage quota.const TTL_MS = 30 * 24 * 60 * 60 * 1000;+// Stable empty references so reads on a missing/empty draft return the same+// array every call — reading through a Zustand selector must not allocate, or+// every store touch would re-render the composer.+const EMPTY_UPLOADS: DraftUpload[] = [];+const EMPTY_ATTACHMENTS: Attachment[] = [];++// Derived completed-attachment lists, memoized by the uploads-array reference.+// Every mutation replaces the uploads array, so a stable ref means the derived+// list is unchanged — this keeps the `getAttachments` selector referentially+// stable across unrelated store touches.+const derivedCache = new WeakMap<DraftUpload[], Attachment[]>();+function deriveUploaded(uploads: DraftUpload[]): Attachment[] {+ const cached = derivedCache.get(uploads);+ if (cached) return cached;+ const derived = uploadedAttachments(uploads);+ const result = derived.length === 0 ? EMPTY_ATTACHMENTS : derived;+ derivedCache.set(uploads, result);+ return result;+}++// A draft carries recoverable intent when it has non-blank text OR at least one+// upload (in any state). Upload-only drafts (text deleted, a file still pending+// or failed) are meaningful — pruning or dropping them would silently discard+// the upload the whole persistence exists to protect.+function isMeaningful(content: string, uploads: DraftUpload[]): boolean {+ return content.trim().length > 0 || uploads.length > 0;+}++// Shared writer for setDraft/setAttachments/upload mutations: an entry with+// neither text nor uploads carries nothing to recover, so drop it instead of+// leaving a blank record behind (parity with the old onUpdate "clear on empty+// text").+function writeDraft(+ drafts: Record<string, CommentDraft>,+ key: string,+ content: string,+ uploads: DraftUpload[],+): Record<string, CommentDraft> {+ if (!isMeaningful(content, uploads)) {+ if (!(key in drafts)) return drafts;+ const next = { ...drafts };+ delete next[key];+ return next;+ }+ // Idempotent on identical writes: the composers' visibilitychange/pagehide+ // flush re-writes the same content on every tab switch, and the stale-submit+ // guard compares entry identity — a fresh-but-equal entry would read as "the+ // user edited during the request" and wrongly keep a submitted draft alive.+ const existing = drafts[key];+ if (existing && existing.content === content && existing.attachments === uploads) {+ return drafts;+ }+ return { ...drafts, [key]: { content, attachments: uploads, updatedAt: Date.now() } };+}++function uploadsOf(drafts: Record<string, CommentDraft>, key: string): DraftUpload[] {+ return drafts[key]?.attachments ?? EMPTY_UPLOADS;+}+function pruneStaleDrafts(drafts: Record<string, CommentDraft>): Record<string, CommentDraft> {const cutoff = Date.now() - TTL_MS;const out: Record<string, CommentDraft> = {};for (const [k, v] of Object.entries(drafts)) {- if (v.updatedAt >= cutoff && v.content.trim().length > 0) {- out[k] = v;+ // Normalize every persisted draft: legacy `Attachment[]` becomes uploaded+ // placeholders, and any placeholder still `uploading` becomes `interrupted`+ // (the bytes were never persisted, so the upload cannot resume).+ const uploads = normalizeStoredUploads(v.attachments);+ if (v.updatedAt >= cutoff && isMeaningful(v.content, uploads)) {+ out[k] = { ...v, attachments: uploads };}}return out;@@ -53,10 +157,77 @@ export const useCommentDraftStore = create<CommentDraftStore>()((set, get) => ({drafts: {},getDraft: (key) => get().drafts[key]?.content,+ getAttachments: (key) => deriveUploaded(uploadsOf(get().drafts, key)),+ getUploads: (key) => uploadsOf(get().drafts, key),setDraft: (key, content) =>set((s) => ({- drafts: { ...s.drafts, [key]: { content, updatedAt: Date.now() } },+ drafts: writeDraft(s.drafts, key, content, uploadsOf(s.drafts, key)),})),+ appendToDraftContent: (key, markdown) =>+ set((s) => {+ const existing = s.drafts[key]?.content ?? "";+ const next = existing.trim() ? `${existing.replace(/\s+$/, "")}\n\n${markdown}` : markdown;+ return {+ drafts: writeDraft(s.drafts, key, next, uploadsOf(s.drafts, key)),+ };+ }),+ setAttachments: (key, attachments) =>+ set((s) => ({+ drafts: writeDraft(+ s.drafts,+ key,+ s.drafts[key]?.content ?? "",+ attachments.map(attachmentToDraftUpload),+ ),+ })),+ addUpload: (key, upload) =>+ set((s) => {+ const current = uploadsOf(s.drafts, key);+ if (current.some((u) => u.clientUploadId === upload.clientUploadId)) return s;+ return {+ drafts: writeDraft(s.drafts, key, s.drafts[key]?.content ?? "", [...current, upload]),+ };+ }),+ settleUpload: (key, clientUploadId, attachment) =>+ set((s) => {+ const current = uploadsOf(s.drafts, key);+ if (!current.some((u) => u.clientUploadId === clientUploadId)) return s;+ const next = current.map((u) =>+ u.clientUploadId === clientUploadId+ ? { ...attachmentToDraftUpload(attachment), clientUploadId }+ : u,+ );+ return {+ drafts: writeDraft(s.drafts, key, s.drafts[key]?.content ?? "", next),+ };+ }),+ failUpload: (key, clientUploadId, error) =>+ set((s) => {+ const current = uploadsOf(s.drafts, key);+ const target = current.find((u) => u.clientUploadId === clientUploadId);+ if (!target) return s;+ const failed: PendingDraftUpload = {+ clientUploadId,+ status: "failed",+ filename: target.filename,+ size: target.size,+ contentType: target.contentType,+ error,+ };+ const next = current.map((u) => (u.clientUploadId === clientUploadId ? failed : u));+ return {+ drafts: writeDraft(s.drafts, key, s.drafts[key]?.content ?? "", next),+ };+ }),+ removeUpload: (key, clientUploadId) =>+ set((s) => {+ const current = uploadsOf(s.drafts, key);+ if (!current.some((u) => u.clientUploadId === clientUploadId)) return s;+ const next = current.filter((u) => u.clientUploadId !== clientUploadId);+ return {+ drafts: writeDraft(s.drafts, key, s.drafts[key]?.content ?? "", next),+ };+ }),clearDraft: (key) =>set((s) => {if (!(key in s.drafts)) return s;@@ -78,3 +249,9 @@ export const useCommentDraftStore = create<CommentDraftStore>()();registerForWorkspaceRehydration(() => useCommentDraftStore.persist.rehydrate());++registerDraftCleanup({+ storageKey: "multica_comment_drafts",+ workspaceScoped: true,+ resetInMemory: () => useCommentDraftStore.setState({ drafts: {} }),+});diff --git a/packages/core/issues/stores/draft-store.test.ts b/packages/core/issues/stores/draft-store.test.tsindex 995292c48c..cb011f8bc8 100644--- a/packages/core/issues/stores/draft-store.test.ts+++ b/packages/core/issues/stores/draft-store.test.ts@@ -2,6 +2,9 @@import { afterEach, beforeAll, beforeEach, describe, expect, it } from "vitest";import { useIssueDraftStore } from "./draft-store";import { setCurrentWorkspace } from "../../platform/workspace-storage";+import { resetAllRegisteredDrafts } from "../../drafts/cleanup-registry";+import { clearWorkspaceStorage } from "../../platform/storage-cleanup";+import { defaultStorage } from "../../platform/storage";const flush = () => new Promise((resolve) => queueMicrotask(() => resolve(null)));@@ -26,18 +29,28 @@ beforeAll(() => {const RESET_STATE = {draft: {- title: "",- description: "",- status: "todo" as const,- priority: "none" as const,- assigneeType: undefined,- assigneeId: undefined,- projectId: undefined,- startDate: null,- dueDate: null,- labelIds: [],- propertyValues: {},- attachments: [],+ shared: {+ projectId: undefined,+ priority: "none" as const,+ dueDate: null,+ attachments: [],+ },+ manual: {+ title: "",+ description: "",+ status: "todo" as const,+ startDate: null,+ assigneeType: undefined,+ assigneeId: undefined,+ labelIds: [],+ propertyValues: {},+ },+ agent: {+ prompt: "",+ actorType: undefined,+ actorId: undefined,+ },+ activeMode: "manual" as const,},lastAssigneeType: undefined,lastAssigneeId: undefined,@@ -48,77 +61,92 @@ describe("issue draft store — last assignee", () => {useIssueDraftStore.setState(RESET_STATE);});- it("clearDraft prefills the next draft with the remembered assignee", () => {- const { setDraft, setLastAssignee, clearDraft } =+ it("clearDraft prefills the next manual draft with the remembered assignee", () => {+ const { setManual, setLastAssignee, clearDraft } =useIssueDraftStore.getState();- setDraft({ title: "first", assigneeType: "member", assigneeId: "alice" });+ setManual({ title: "first", assigneeType: "member", assigneeId: "alice" });setLastAssignee("member", "alice");clearDraft();const { draft } = useIssueDraftStore.getState();- expect(draft.title).toBe("");- expect(draft.assigneeType).toBe("member");- expect(draft.assigneeId).toBe("alice");+ expect(draft.manual.title).toBe("");+ expect(draft.manual.assigneeType).toBe("member");+ expect(draft.manual.assigneeId).toBe("alice");});it("clearDraft yields an empty assignee when none has ever been remembered", () => {- const { setDraft, clearDraft } = useIssueDraftStore.getState();+ const { setManual, clearDraft } = useIssueDraftStore.getState();- setDraft({ title: "first" });+ setManual({ title: "first" });clearDraft();const { draft } = useIssueDraftStore.getState();- expect(draft.assigneeType).toBeUndefined();- expect(draft.assigneeId).toBeUndefined();+ expect(draft.manual.assigneeType).toBeUndefined();+ expect(draft.manual.assigneeId).toBeUndefined();});- it("clearDraft removes persisted draft attachments", () => {- const { setDraft, clearDraft } = useIssueDraftStore.getState();+ it("clearDraft removes persisted shared attachments", () => {+ const { setShared, clearDraft } = useIssueDraftStore.getState();- setDraft({- title: "first",+ setShared({attachments: [{- id: "11111111-2222-3333-4444-555555555555",- workspace_id: "ws-1",- issue_id: null,- comment_id: null,- chat_session_id: null,- chat_message_id: null,- uploader_type: "member",- uploader_id: "alice",+ clientUploadId: "11111111-2222-3333-4444-555555555555",+ status: "uploaded",filename: "shot.png",- url: "https://cdn.example.test/shot.png",- download_url: "https://cdn.example.test/shot.png",- markdown_url: "https://app.example.test/api/attachments/11111111-2222-3333-4444-555555555555/download",- content_type: "image/png",- size_bytes: 123,- created_at: "2026-06-12T00:00:00Z",+ size: 123,+ contentType: "image/png",+ attachment: {+ id: "11111111-2222-3333-4444-555555555555",+ workspace_id: "ws-1",+ issue_id: null,+ comment_id: null,+ chat_session_id: null,+ chat_message_id: null,+ uploader_type: "member",+ uploader_id: "alice",+ filename: "shot.png",+ url: "https://cdn.example.test/shot.png",+ download_url: "https://cdn.example.test/shot.png",+ markdown_url: "https://app.example.test/api/attachments/11111111-2222-3333-4444-555555555555/download",+ content_type: "image/png",+ size_bytes: 123,+ created_at: "2026-06-12T00:00:00Z",+ },},],});clearDraft();- expect(useIssueDraftStore.getState().draft.attachments).toEqual([]);+ expect(useIssueDraftStore.getState().draft.shared.attachments).toEqual([]);});it("clearDraft removes persisted custom property values", () => {- const { setDraft, clearDraft } = useIssueDraftStore.getState();+ const { setManual, clearDraft } = useIssueDraftStore.getState();- setDraft({ propertyValues: { "property-1": "option-1" } });+ setManual({ propertyValues: { "property-1": "option-1" } });clearDraft();- expect(useIssueDraftStore.getState().draft.propertyValues).toEqual({});+ expect(useIssueDraftStore.getState().draft.manual.propertyValues).toEqual({});});it("clearDraft removes the persisted project selection", () => {- const { setDraft, clearDraft } = useIssueDraftStore.getState();+ const { setShared, clearDraft } = useIssueDraftStore.getState();++ setShared({ projectId: "project-1" });+ clearDraft();++ expect(useIssueDraftStore.getState().draft.shared.projectId).toBeUndefined();+ });++ it("clearDraft removes the persisted agent prompt", () => {+ const { setAgent, clearDraft } = useIssueDraftStore.getState();- setDraft({ projectId: "project-1" });+ setAgent({ prompt: "Investigate the regression" });clearDraft();- expect(useIssueDraftStore.getState().draft.projectId).toBeUndefined();+ expect(useIssueDraftStore.getState().draft.agent.prompt).toBe("");});it("setLastAssignee(undefined) lets the user opt back out of a default", () => {@@ -126,12 +154,36 @@ describe("issue draft store — last assignee", () => {setLastAssignee("member", "alice");clearDraft();- expect(useIssueDraftStore.getState().draft.assigneeId).toBe("alice");+ expect(useIssueDraftStore.getState().draft.manual.assigneeId).toBe("alice");setLastAssignee(undefined, undefined);clearDraft();- expect(useIssueDraftStore.getState().draft.assigneeId).toBeUndefined();- expect(useIssueDraftStore.getState().draft.assigneeType).toBeUndefined();+ expect(useIssueDraftStore.getState().draft.manual.assigneeId).toBeUndefined();+ expect(useIssueDraftStore.getState().draft.manual.assigneeType).toBeUndefined();+ });+});++describe("issue draft store — mode switch preserves both sides", () => {+ beforeEach(() => {+ useIssueDraftStore.setState(RESET_STATE);+ });++ it("keeps the manual slot untouched when the agent slot is filled and vice versa", () => {+ const { setManual, setAgent, setShared } = useIssueDraftStore.getState();++ setManual({ title: "Manual title", description: "Manual body" });+ setShared({ projectId: "project-1", priority: "high" });+ // Switching to agent seeds the agent slot but must not clear manual.+ setAgent({ prompt: "Agent prompt", actorType: "agent", actorId: "agent-1" });++ const { draft } = useIssueDraftStore.getState();+ expect(draft.manual.title).toBe("Manual title");+ expect(draft.manual.description).toBe("Manual body");+ expect(draft.agent.prompt).toBe("Agent prompt");+ expect(draft.agent.actorId).toBe("agent-1");+ // Shared fields are visible to both sides.+ expect(draft.shared.projectId).toBe("project-1");+ expect(draft.shared.priority).toBe("high");});});@@ -145,7 +197,7 @@ describe("issue draft store — legacy rehydrate", () => {setCurrentWorkspace(null, null);});- it("backfills attachments and custom properties for legacy drafts", async () => {+ it("migrates a pre-MUL-5181 flat draft into the shared/manual slots", async () => {localStorage.setItem("multica_issue_draft:acme",JSON.stringify({@@ -154,9 +206,12 @@ describe("issue draft store — legacy rehydrate", () => {title: "legacy",description: "body",status: "todo",- priority: "none",+ priority: "high",+ projectId: "project-1",startDate: null,- dueDate: null,+ dueDate: "2026-08-01",+ labelIds: ["label-1"],+ propertyValues: { "property-1": "option-1" },// no `attachments` — written by a build that predates the field},},@@ -169,9 +224,180 @@ describe("issue draft store — legacy rehydrate", () => {await flush();const { draft } = useIssueDraftStore.getState();- expect(draft.title).toBe("legacy");- expect(draft.projectId).toBeUndefined();- expect(draft.attachments).toEqual([]);- expect(draft.propertyValues).toEqual({});+ // Manual-only fields land in the manual slot.+ expect(draft.manual.title).toBe("legacy");+ expect(draft.manual.description).toBe("body");+ expect(draft.manual.status).toBe("todo");+ expect(draft.manual.labelIds).toEqual(["label-1"]);+ expect(draft.manual.propertyValues).toEqual({ "property-1": "option-1" });+ // Shared fields land in the shared slot, with attachments backfilled.+ expect(draft.shared.projectId).toBe("project-1");+ expect(draft.shared.priority).toBe("high");+ expect(draft.shared.dueDate).toBe("2026-08-01");+ expect(draft.shared.attachments).toEqual([]);+ // A legacy draft had no agent prompt (it lived in a separate store).+ expect(draft.agent.prompt).toBe("");+ expect(draft.activeMode).toBe("manual");+ });++ it("backfills missing sub-fields on an already-nested persisted draft", async () => {+ localStorage.setItem(+ "multica_issue_draft:beta",+ JSON.stringify({+ state: {+ draft: {+ // A build that shipped the nested shape but predated a later field.+ shared: { projectId: "project-2", priority: "urgent" },+ manual: { title: "kept" },+ agent: { prompt: "keep me" },+ activeMode: "agent",+ },+ },+ version: 0,+ }),+ );++ setCurrentWorkspace("beta", "ws_b");+ await flush();+ await flush();++ const { draft } = useIssueDraftStore.getState();+ expect(draft.shared.projectId).toBe("project-2");+ expect(draft.shared.priority).toBe("urgent");+ expect(draft.shared.dueDate).toBeNull();+ expect(draft.shared.attachments).toEqual([]);+ expect(draft.manual.title).toBe("kept");+ expect(draft.manual.status).toBe("todo");+ expect(draft.agent.prompt).toBe("keep me");+ expect(draft.activeMode).toBe("agent");+ });++ it("normalizes pre-L2 shared attachments and coerces stale uploading placeholders", async () => {+ localStorage.setItem(+ "multica_issue_draft:gamma",+ JSON.stringify({+ state: {+ draft: {+ shared: {+ attachments: [+ // Pre-L2 build persisted a bare Attachment row.+ {+ id: "att-1",+ filename: "old.png",+ url: "https://cdn.example.test/old.png",+ size_bytes: 7,+ content_type: "image/png",+ },+ // An upload that was still in flight when the app closed.+ {+ clientUploadId: "c-flight",+ status: "uploading",+ filename: "mid.png",+ size: 9,+ },+ ],+ },+ manual: {},+ agent: {},+ activeMode: "manual",+ },+ },+ version: 0,+ }),+ );++ setCurrentWorkspace("gamma", "ws_c");+ await flush();+ await flush();++ const { attachments } = useIssueDraftStore.getState().draft.shared;+ expect(attachments.map((u) => u.status)).toEqual(["uploaded", "interrupted"]);+ expect(attachments[0]?.filename).toBe("old.png");+ expect(attachments[1]?.filename).toBe("mid.png");+ });+});++describe("issue draft store — hasDraft upload semantics", () => {+ beforeEach(() => {+ useIssueDraftStore.setState(RESET_STATE);+ });++ const placeholder = (status: "uploading" | "uploaded" | "failed" | "interrupted") =>+ ({+ clientUploadId: `c-${status}`,+ status,+ filename: "f.png",+ size: 1,+ ...(status === "uploaded"+ ? {+ attachment: {+ id: "att-1",+ filename: "f.png",+ url: "https://cdn.example.test/f.png",+ },+ }+ : {}),+ }) as never;++ it("counts uploaded and uploading entries as recoverable draft intent", () => {+ const { setShared, hasDraft } = useIssueDraftStore.getState();+ setShared({ attachments: [placeholder("uploading")] });+ expect(hasDraft()).toBe(true);+ setShared({ attachments: [placeholder("uploaded")] });+ expect(hasDraft()).toBe(true);+ });++ it("ignores failed/interrupted remnants so they cannot pin the sidebar dot", () => {+ const { setShared, hasDraft } = useIssueDraftStore.getState();+ setShared({ attachments: [placeholder("failed"), placeholder("interrupted")] });+ expect(hasDraft()).toBe(false);+ });+});++describe("issue draft store — logout cleanup", () => {+ beforeEach(() => {+ localStorage.clear();+ setCurrentWorkspace(null, null);+ useIssueDraftStore.setState(RESET_STATE);+ });++ afterEach(() => {+ setCurrentWorkspace(null, null);+ });++ it("registered reset wipes the last-assignee preference, not just the draft", () => {+ const { setManual, setLastAssignee } = useIssueDraftStore.getState();+ setManual({ title: "wip", assigneeType: "member", assigneeId: "alice" });+ setLastAssignee("member", "alice");++ resetAllRegisteredDrafts();++ const state = useIssueDraftStore.getState();+ expect(state.lastAssigneeType).toBeUndefined();+ expect(state.lastAssigneeId).toBeUndefined();+ // clearDraft() would have re-seeded the manual slot from lastAssignee —+ // the logout reset must not hand the next login a previous user's pick.+ expect(state.draft.manual.assigneeType).toBeUndefined();+ expect(state.draft.manual.assigneeId).toBeUndefined();+ });++ it("logout sequence (reset in-memory, then clear storage) leaves no persisted key", async () => {+ setCurrentWorkspace("acme", "ws_a");+ await flush();+ await flush();++ const { setManual, setLastAssignee } = useIssueDraftStore.getState();+ setManual({ title: "secret wip" });+ setLastAssignee("member", "alice");+ expect(localStorage.getItem("multica_issue_draft:acme")).not.toBeNull();++ // use-logout's order: reset first (each reset is a setState, and persist+ // writes the new state back to storage under the still-active slug), THEN+ // remove the keys. The reverse order resurrects the key with the previous+ // user's lastAssignee inside.+ resetAllRegisteredDrafts();+ clearWorkspaceStorage(defaultStorage, "acme");++ expect(localStorage.getItem("multica_issue_draft:acme")).toBeNull();});});diff --git a/packages/core/issues/stores/draft-store.ts b/packages/core/issues/stores/draft-store.tsindex 8266a07fa9..6f74707d0f 100644--- a/packages/core/issues/stores/draft-store.ts+++ b/packages/core/issues/stores/draft-store.ts@@ -5,97 +5,226 @@ import type {IssuePriority,IssueAssigneeType,IssuePropertyValues,- Attachment,} from "../../types";+import type { CreateMode } from "./create-mode-store";+import type { QuickCreateActorType } from "./quick-create-store";import { createWorkspaceAwareStorage, registerForWorkspaceRehydration } from "../../platform/workspace-storage";import { defaultStorage } from "../../platform/storage";+import { registerDraftCleanup } from "../../drafts/cleanup-registry";+import { normalizeStoredUploads, type DraftUpload } from "../../drafts/draft-upload";-interface IssueDraft {+// One logical Issue-Create draft (MUL-5181), split so switching between the+// manual form and the agent form never destroys the other side's content.+//+// shared — belongs to the issue no matter how it is filed: project,+// priority, due date, attachments.+// manual — the manual form's own state: title, description, status, start+// date, assignee, labels, custom properties.+// agent — the agent form's own state: the free-text prompt and the picked+// actor (agent or squad).+// activeMode — which form the draft is currently being edited in.+//+// Before this split, `switchToAgent` concatenated title + description into the+// prompt and then CLEARED the manual fields, and `switchToManual` copied the+// prompt into the description but left the old prompt behind — so a round-trip+// both lost manual content and resurfaced a stale prompt. With separate slots+// a switch is a no-op on the other side's data; the only cross-write is a+// one-time assist-init the panels perform when the target slot is still empty.++export interface IssueCreateShared {+ projectId?: string;+ priority: IssuePriority;+ dueDate: string | null;+ /** Uploads for the dialog (placeholders + completed), referenced by the+ * manual description OR the agent prompt markdown. A single pool so an+ * image survives a mode switch from either side; each submit path sends+ * only the ids its own content references. Coordinator-owned (MUL-5181 L2):+ * a placeholder written at pick time survives dialog close, and one still+ * `uploading` at load time is coerced to `interrupted` on rehydrate. */+ attachments: DraftUpload[];+}++export interface IssueCreateManual {title: string;description: string;status: IssueStatus;- priority: IssuePriority;+ startDate: string | null;assigneeType?: IssueAssigneeType;assigneeId?: string;- projectId?: string;- startDate: string | null;- dueDate: string | null;- /** Label IDs chosen in the create dialog. Attached to the issue right- * after it is created (the create endpoint takes no labels), so they are- * kept as a plain id list rather than full Label objects. */+ /** Label IDs chosen in the create dialog. Attached to the issue right after+ * it is created (the create endpoint takes no labels), so they are kept as+ * a plain id list rather than full Label objects. */labelIds: string[];propertyValues: IssuePropertyValues;- attachments: Attachment[];}-const EMPTY_DRAFT: IssueDraft = {+export interface IssueCreateAgent {+ prompt: string;+ actorType?: QuickCreateActorType;+ actorId?: string;+}++export interface IssueCreateDraft {+ shared: IssueCreateShared;+ manual: IssueCreateManual;+ agent: IssueCreateAgent;+ activeMode: CreateMode;+}++const emptyShared = (): IssueCreateShared => ({+ projectId: undefined,+ priority: "none",+ dueDate: null,+ attachments: [],+});++const emptyManual = (): IssueCreateManual => ({title: "",description: "",status: "todo",- priority: "none",+ startDate: null,assigneeType: undefined,assigneeId: undefined,- projectId: undefined,- startDate: null,- dueDate: null,labelIds: [],propertyValues: {},- attachments: [],-};+});++const emptyAgent = (): IssueCreateAgent => ({+ prompt: "",+ actorType: undefined,+ actorId: undefined,+});interface IssueDraftStore {- draft: IssueDraft;+ draft: IssueCreateDraft;// Last assignee picked at submit time. Persisted across drafts so the// create-issue modal can prefill the picker with the user's most recent// choice instead of always opening with no assignee.lastAssigneeType?: IssueAssigneeType;lastAssigneeId?: string;- setDraft: (patch: Partial<IssueDraft>) => void;+ setShared: (patch: Partial<IssueCreateShared>) => void;+ setManual: (patch: Partial<IssueCreateManual>) => void;+ setAgent: (patch: Partial<IssueCreateAgent>) => void;+ setActiveMode: (mode: CreateMode) => void;clearDraft: () => void;setLastAssignee: (type?: IssueAssigneeType, id?: string) => void;hasDraft: () => boolean;}+function isLegacyFlatDraft(d: Record<string, unknown>): boolean {+ return (+ !("manual" in d) &&+ !("shared" in d) &&+ ("title" in d || "status" in d || "labelIds" in d || "description" in d)+ );+}++// Drafts persisted by older builds either predate a later-added sub-field or+// use the pre-MUL-5181 flat shape. Backfill defaults so every read site can+// rely on the declared IssueCreateDraft shape instead of re-defending, and lift+// a legacy flat draft into the manual/shared slots (there was no agent prompt+// in that store — it lived in `multica_quick_create` and is not carried over).+function migrateDraft(raw: unknown): IssueCreateDraft {+ const d = (raw && typeof raw === "object" ? raw : {}) as Record<string, unknown>;++ if (isLegacyFlatDraft(d)) {+ return {+ shared: {+ ...emptyShared(),+ projectId: d.projectId as string | undefined,+ priority: (d.priority as IssuePriority) ?? "none",+ dueDate: (d.dueDate as string | null) ?? null,+ // Legacy builds persisted bare Attachment rows; normalize wraps them+ // as `uploaded` placeholders (and coerces stale `uploading` ones).+ attachments: normalizeStoredUploads(d.attachments),+ },+ manual: {+ ...emptyManual(),+ title: (d.title as string) ?? "",+ description: (d.description as string) ?? "",+ status: (d.status as IssueStatus) ?? "todo",+ startDate: (d.startDate as string | null) ?? null,+ assigneeType: d.assigneeType as IssueAssigneeType | undefined,+ assigneeId: d.assigneeId as string | undefined,+ labelIds: Array.isArray(d.labelIds) ? (d.labelIds as string[]) : [],+ propertyValues:+ d.propertyValues && typeof d.propertyValues === "object"+ ? (d.propertyValues as IssuePropertyValues)+ : {},+ },+ agent: emptyAgent(),+ activeMode: "manual",+ };+ }++ const sharedRaw = (d.shared as Partial<IssueCreateShared> & { attachments?: unknown }) ?? {};+ return {+ shared: {+ ...emptyShared(),+ ...sharedRaw,+ // Pre-L2 nested drafts stored bare Attachment rows; every load also+ // coerces `uploading` placeholders to `interrupted` (bytes are gone).+ attachments: normalizeStoredUploads(sharedRaw.attachments),+ },+ manual: { ...emptyManual(), ...((d.manual as Partial<IssueCreateManual>) ?? {}) },+ agent: { ...emptyAgent(), ...((d.agent as Partial<IssueCreateAgent>) ?? {}) },+ activeMode: d.activeMode === "agent" ? "agent" : "manual",+ };+}+export const useIssueDraftStore = create<IssueDraftStore>()(persist((set, get) => ({- draft: { ...EMPTY_DRAFT },+ draft: migrateDraft(undefined),lastAssigneeType: undefined,lastAssigneeId: undefined,- setDraft: (patch) =>- set((s) => ({ draft: { ...s.draft, ...patch } })),+ setShared: (patch) =>+ set((s) => ({ draft: { ...s.draft, shared: { ...s.draft.shared, ...patch } } })),+ setManual: (patch) =>+ set((s) => ({ draft: { ...s.draft, manual: { ...s.draft.manual, ...patch } } })),+ setAgent: (patch) =>+ set((s) => ({ draft: { ...s.draft, agent: { ...s.draft.agent, ...patch } } })),+ setActiveMode: (mode) =>+ set((s) => ({ draft: { ...s.draft, activeMode: mode } })),clearDraft: () =>set((s) => ({draft: {- ...EMPTY_DRAFT,- assigneeType: s.lastAssigneeType,- assigneeId: s.lastAssigneeId,+ shared: emptyShared(),+ manual: {+ ...emptyManual(),+ assigneeType: s.lastAssigneeType,+ assigneeId: s.lastAssigneeId,+ },+ agent: emptyAgent(),+ activeMode: s.draft.activeMode,},})),setLastAssignee: (type, id) =>set({ lastAssigneeType: type, lastAssigneeId: id }),hasDraft: () => {- const { draft } = get();+ const { manual, agent, shared } = get().draft;return !!(- draft.title ||- draft.description ||- Object.keys(draft.propertyValues).length > 0+ manual.title ||+ manual.description ||+ agent.prompt ||+ Object.keys(manual.propertyValues).length > 0 ||+ // Recoverable uploads only: a failed/interrupted remnant the user+ // never dismissed must not pin the sidebar's draft dot forever.+ shared.attachments.some((u) => u.status === "uploaded" || u.status === "uploading"));},}),{name: "multica_issue_draft",storage: createJSONStorage(() => createWorkspaceAwareStorage(defaultStorage)),- // Drafts persisted by older builds predate fields added later (e.g.- // `attachments`). Backfill EMPTY_DRAFT defaults on rehydrate so every- // read site can rely on the declared IssueDraft shape instead of- // re-defending with `?? fallback`.merge: (persistedState, currentState) => {- const persisted = (persistedState ?? {}) as Partial<IssueDraftStore>;+ const persisted = (persistedState ?? {}) as Partial<IssueDraftStore> & {+ draft?: unknown;+ };return {...currentState,...persisted,- draft: { ...EMPTY_DRAFT, ...persisted.draft },+ draft: migrateDraft(persisted.draft),};},},@@ -103,3 +232,18 @@ export const useIssueDraftStore = create<IssueDraftStore>()();registerForWorkspaceRehydration(() => useIssueDraftStore.persist.rehydrate());++registerDraftCleanup({+ storageKey: "multica_issue_draft",+ workspaceScoped: true,+ // Full reset, NOT clearDraft(): clearDraft deliberately keeps the+ // last-assignee preference and re-seeds it into the fresh draft's manual+ // slot — correct between drafts of one user, but on logout it would hand+ // the previous user's last-picked assignee to the next login on this tab.+ resetInMemory: () =>+ useIssueDraftStore.setState({+ draft: migrateDraft(undefined),+ lastAssigneeType: undefined,+ lastAssigneeId: undefined,+ }),+});diff --git a/packages/core/issues/stores/quick-create-store.test.ts b/packages/core/issues/stores/quick-create-store.test.tsindex 30668bd536..c3ef0f76e6 100644--- a/packages/core/issues/stores/quick-create-store.test.ts+++ b/packages/core/issues/stores/quick-create-store.test.ts@@ -5,7 +5,6 @@ const RESET_STATE = {lastActorType: null,lastActorId: null,lastProjectId: null,- prompt: "",keepOpen: false,};@@ -14,18 +13,6 @@ describe("quick create store", () => {useQuickCreateStore.setState(RESET_STATE);});- it("persists the agent prompt draft until explicitly cleared", () => {- const { setPrompt, clearPrompt } = useQuickCreateStore.getState();-- setPrompt("Investigate the inbox loading regression");- expect(useQuickCreateStore.getState().prompt).toBe(- "Investigate the inbox loading regression",- );-- clearPrompt();- expect(useQuickCreateStore.getState().prompt).toBe("");- });-it("remembers the last project picked so frequent users skip the picker", () => {const { setLastProjectId } = useQuickCreateStore.getState();diff --git a/packages/core/issues/stores/quick-create-store.ts b/packages/core/issues/stores/quick-create-store.tsindex 93dae2922d..2d2519d48f 100644--- a/packages/core/issues/stores/quick-create-store.ts+++ b/packages/core/issues/stores/quick-create-store.ts@@ -4,6 +4,7 @@ import { create } from "zustand";import { createJSONStorage, persist } from "zustand/middleware";import { createWorkspaceAwareStorage, registerForWorkspaceRehydration } from "../../platform/workspace-storage";import { defaultStorage } from "../../platform/storage";+import { registerDraftCleanup } from "../../drafts/cleanup-registry";export type QuickCreateActorType = "agent" | "squad";@@ -21,15 +22,17 @@ export type QuickCreateActorType = "agent" | "squad";// squads became selectable. Users who had a persisted agent preference// land back on whatever the picker shows first; a one-time re-pick is// preferable to the type-tag ambiguity of overloading a single UUID.+//+// The in-progress agent prompt no longer lives here — it moved into the+// unified issue-create draft's `agent` slot (draft-store) so it shares one+// lifecycle with the manual draft (MUL-5181). This store keeps only the+// last-successful preferences (actor, project) and the shared keep-open toggle.interface QuickCreateState {lastActorType: QuickCreateActorType | null;lastActorId: string | null;setLastActor: (type: QuickCreateActorType | null, id: string | null) => void;lastProjectId: string | null;setLastProjectId: (id: string | null) => void;- prompt: string;- setPrompt: (prompt: string) => void;- clearPrompt: () => void;keepOpen: boolean;setKeepOpen: (v: boolean) => void;}@@ -42,9 +45,6 @@ export const useQuickCreateStore = create<QuickCreateState>()(setLastActor: (type, id) => set({ lastActorType: type, lastActorId: id }),lastProjectId: null,setLastProjectId: (id) => set({ lastProjectId: id }),- prompt: "",- setPrompt: (prompt) => set({ prompt }),- clearPrompt: () => set({ prompt: "" }),keepOpen: false,setKeepOpen: (v) => set({ keepOpen: v }),}),@@ -56,3 +56,17 @@ export const useQuickCreateStore = create<QuickCreateState>()();registerForWorkspaceRehydration(() => useQuickCreateStore.persist.rehydrate());++registerDraftCleanup({+ storageKey: "multica_quick_create",+ workspaceScoped: true,+ // Reset the per-user picker memory so it does not survive into the next+ // login on the same tab. (The prompt draft lives in draft-store now.)+ resetInMemory: () =>+ useQuickCreateStore.setState({+ lastActorType: null,+ lastActorId: null,+ lastProjectId: null,+ keepOpen: false,+ }),+});diff --git a/packages/core/package.json b/packages/core/package.jsonindex 55de94551a..90a0bafdbf 100644--- a/packages/core/package.json+++ b/packages/core/package.json@@ -113,6 +113,8 @@"./constants/*": "./constants/*.ts","./feature-flags": "./feature-flags/index.ts","./platform": "./platform/index.ts",+ "./drafts": "./drafts/index.ts",+ "./drafts/*": "./drafts/*.ts","./shortcuts": "./shortcuts/index.ts","./analytics": "./analytics/index.ts","./diagnostics": "./diagnostics/index.ts",diff --git a/packages/core/platform/storage-cleanup.test.ts b/packages/core/platform/storage-cleanup.test.tsindex 2f52b25b60..2b5ced8e50 100644--- a/packages/core/platform/storage-cleanup.test.ts+++ b/packages/core/platform/storage-cleanup.test.ts@@ -1,8 +1,16 @@-import { describe, it, expect, vi } from "vitest";+import { describe, it, expect, vi, beforeEach } from "vitest";import { clearWorkspaceStorage } from "./storage-cleanup";+import {+ registerDraftCleanup,+ __clearDraftCleanupRegistryForTest,+} from "../drafts/cleanup-registry";++beforeEach(() => {+ __clearDraftCleanupRegistryForTest();+});describe("clearWorkspaceStorage", () => {- it("removes all workspace-scoped keys for given wsId", () => {+ it("removes all non-draft workspace-scoped keys for the given slug", () => {const adapter = {getItem: vi.fn(),setItem: vi.fn(),@@ -11,16 +19,42 @@ describe("clearWorkspaceStorage", () => {clearWorkspaceStorage(adapter, "ws_123");- expect(adapter.removeItem).toHaveBeenCalledWith("multica_issue_draft:ws_123");expect(adapter.removeItem).toHaveBeenCalledWith("multica_issue_surface_views:ws_123");expect(adapter.removeItem).toHaveBeenCalledWith("multica_issues_view:ws_123");expect(adapter.removeItem).toHaveBeenCalledWith("multica_issues_scope:ws_123");expect(adapter.removeItem).toHaveBeenCalledWith("multica_my_issues_view:ws_123");expect(adapter.removeItem).toHaveBeenCalledWith("multica:chat:selectedAgentId:ws_123");+ expect(adapter.removeItem).toHaveBeenCalledWith("multica:chat:selectedProjectId:ws_123");expect(adapter.removeItem).toHaveBeenCalledWith("multica:chat:activeSessionId:ws_123");- expect(adapter.removeItem).toHaveBeenCalledWith("multica:chat:drafts:ws_123");expect(adapter.removeItem).toHaveBeenCalledWith("multica:chat:expanded:ws_123");expect(adapter.removeItem).toHaveBeenCalledWith("multica_navigation:ws_123");- expect(adapter.removeItem).toHaveBeenCalledTimes(10);+ // 8 non-draft keys, and no registered drafts in this test.+ expect(adapter.removeItem).toHaveBeenCalledTimes(9);+ });++ it("also clears registered draft keys via the registry", () => {+ const adapter = {+ getItem: vi.fn(),+ setItem: vi.fn(),+ removeItem: vi.fn(),+ };+ registerDraftCleanup({+ storageKey: "multica_test_draft",+ workspaceScoped: true,+ resetInMemory: vi.fn(),+ });+ registerDraftCleanup({+ storageKey: "multica_test_global_draft",+ workspaceScoped: false,+ resetInMemory: vi.fn(),+ });++ clearWorkspaceStorage(adapter, "ws_123");++ expect(adapter.removeItem).toHaveBeenCalledWith("multica_test_draft:ws_123");+ // Globally-namespaced draft keys are removed without the slug suffix.+ expect(adapter.removeItem).toHaveBeenCalledWith("multica_test_global_draft");+ // 8 non-draft keys + 2 registered draft keys.+ expect(adapter.removeItem).toHaveBeenCalledTimes(11);});});diff --git a/packages/core/platform/storage-cleanup.ts b/packages/core/platform/storage-cleanup.tsindex 3b043d5d4d..1a08b179bb 100644--- a/packages/core/platform/storage-cleanup.ts+++ b/packages/core/platform/storage-cleanup.ts@@ -1,21 +1,29 @@import type { StorageAdapter } from "../types/storage";+import { clearRegisteredWorkspaceDrafts } from "../drafts/cleanup-registry";+// Ensure every module-level draft store has registered its key before cleanup+// runs, so the registry is never partially populated at logout/delete time.+import "../drafts/register-all-drafts";/**- * Keys that are namespaced per workspace (stored as `${key}:${slug}`).+ * Non-draft workspace-scoped keys (stored as `${key}:${slug}`).*- * IMPORTANT: When adding a new workspace-scoped persist store or storage key,- * add its key here so that workspace deletion and logout properly clean it up.- * Also ensure the store uses `createWorkspaceAwareStorage` for its persist config.+ * Draft stores no longer live here: they self-register via+ * `registerDraftCleanup` (see `drafts/cleanup-registry`) and are cleared by+ * `clearRegisteredWorkspaceDrafts` below. This list is only for the remaining+ * view/navigation keys that are not drafts.+ *+ * IMPORTANT: When adding a new non-draft workspace-scoped persist store, add+ * its key here; for draft stores, prefer `createDraftStore` (auto-registers)+ * or call `registerDraftCleanup` directly.*/const WORKSPACE_SCOPED_KEYS = [- "multica_issue_draft","multica_issue_surface_views","multica_issues_view","multica_issues_scope","multica_my_issues_view","multica:chat:selectedAgentId",+ "multica:chat:selectedProjectId","multica:chat:activeSessionId",- "multica:chat:drafts","multica:chat:expanded","multica_navigation",];@@ -28,4 +36,7 @@ export function clearWorkspaceStorage(for (const key of WORKSPACE_SCOPED_KEYS) {adapter.removeItem(`${key}:${slug}`);}+ // Draft stores self-register their keys; clear them from the registry so a+ // new draft store can never be silently skipped by an out-of-date list.+ clearRegisteredWorkspaceDrafts(adapter, slug);}diff --git a/packages/core/projects/draft-store.ts b/packages/core/projects/draft-store.tsindex 29d6bbebef..56fcbe0ec9 100644--- a/packages/core/projects/draft-store.ts+++ b/packages/core/projects/draft-store.ts@@ -1,8 +1,5 @@-import { create } from "zustand";-import { createJSONStorage, persist } from "zustand/middleware";import type { ProjectStatus, ProjectPriority } from "../types";-import { createWorkspaceAwareStorage, registerForWorkspaceRehydration } from "../platform/workspace-storage";-import { defaultStorage } from "../platform/storage";+import { createDraftStore } from "../drafts/create-draft-store";interface ProjectDraft {title: string;@@ -29,31 +26,8 @@ const EMPTY_DRAFT: ProjectDraft = {dueDate: undefined,};-interface ProjectDraftStore {- draft: ProjectDraft;- setDraft: (patch: Partial<ProjectDraft>) => void;- clearDraft: () => void;- hasDraft: () => boolean;-}--export const useProjectDraftStore = create<ProjectDraftStore>()(- persist(- (set, get) => ({- draft: { ...EMPTY_DRAFT },- setDraft: (patch) =>- set((s) => ({ draft: { ...s.draft, ...patch } })),- clearDraft: () =>- set({ draft: { ...EMPTY_DRAFT } }),- hasDraft: () => {- const { draft } = get();- return !!(draft.title || draft.description);- },- }),- {- name: "multica_project_draft",- storage: createJSONStorage(() => createWorkspaceAwareStorage(defaultStorage)),- },- ),-);--registerForWorkspaceRehydration(() => useProjectDraftStore.persist.rehydrate());+export const useProjectDraftStore = createDraftStore<ProjectDraft>({+ storageKey: "multica_project_draft",+ emptyData: EMPTY_DRAFT,+ hasMeaningful: (d) => !!(d.title || d.description),+});diff --git a/packages/core/realtime/use-realtime-sync-comment.test.tsx b/packages/core/realtime/use-realtime-sync-comment.test.tsxindex 56e4489edc..85fb26c453 100644--- a/packages/core/realtime/use-realtime-sync-comment.test.tsx+++ b/packages/core/realtime/use-realtime-sync-comment.test.tsx@@ -13,6 +13,10 @@ import { useRealtimeSync, type RealtimeSyncStores } from "./use-realtime-sync";vi.mock("../platform/workspace-storage", () => ({getCurrentWsId: () => "ws-1",getCurrentSlug: () => "test-ws",+ // Draft stores are now loaded transitively (storage-cleanup → register-all-drafts)+ // so their persist wiring must resolve against this mock.+ createWorkspaceAwareStorage: (adapter: unknown) => adapter,+ registerForWorkspaceRehydration: () => {},}));vi.mock("../paths", () => ({diff --git a/packages/core/realtime/use-realtime-sync-ws-instance.test.tsx b/packages/core/realtime/use-realtime-sync-ws-instance.test.tsxindex 27b1beb9ce..4735730a1a 100644--- a/packages/core/realtime/use-realtime-sync-ws-instance.test.tsx+++ b/packages/core/realtime/use-realtime-sync-ws-instance.test.tsx@@ -19,6 +19,10 @@ import { useRealtimeSync, type RealtimeSyncStores } from "./use-realtime-sync";vi.mock("../platform/workspace-storage", () => ({getCurrentWsId: () => "ws-1",getCurrentSlug: () => "test-ws",+ // Draft stores are now loaded transitively (storage-cleanup → register-all-drafts)+ // so their persist wiring must resolve against this mock.+ createWorkspaceAwareStorage: (adapter: unknown) => adapter,+ registerForWorkspaceRehydration: () => {},}));vi.mock("../paths", () => ({diff --git a/packages/views/auth/use-logout.test.ts b/packages/views/auth/use-logout.test.tsnew file mode 100644index 0000000000..be5b74f39f--- /dev/null+++ b/packages/views/auth/use-logout.test.ts@@ -0,0 +1,84 @@+// @vitest-environment jsdom+import { describe, expect, it, vi, beforeEach } from "vitest";+import { renderHook } from "@testing-library/react";+import { useLogout } from "./use-logout";++// Order of the destructive calls is the contract under test: each in-memory+// reset is a Zustand setState, and persist middleware writes the reset state+// straight back to storage under the still-active workspace slug. Resetting+// AFTER the per-slug key removal therefore resurrects the just-deleted keys+// (for the issue draft store: with the previous user's lastAssignee inside).+const calls = vi.hoisted(() => [] as string[]);+const mockReset = vi.hoisted(() => vi.fn());+const mockClearWorkspaceStorage = vi.hoisted(() => vi.fn());+const mockAuthLogout = vi.hoisted(() => vi.fn());+const mockPush = vi.hoisted(() => vi.fn());+const mockQueryClientClear = vi.hoisted(() => vi.fn());++vi.mock("@tanstack/react-query", () => ({+ useQueryClient: () => ({+ getQueryData: () => [+ { slug: "acme" },+ { slug: "beta" },+ ],+ clear: mockQueryClientClear,+ }),+}));++vi.mock("@multica/core/auth", () => ({+ useAuthStore: Object.assign(+ (selector?: (s: unknown) => unknown) => {+ const state = { logout: mockAuthLogout };+ return selector ? selector(state) : state;+ },+ { getState: () => ({ logout: mockAuthLogout }) },+ ),+}));++vi.mock("@multica/core/workspace/queries", () => ({+ workspaceKeys: { list: () => ["workspaces", "list"] },+}));++vi.mock("@multica/core/platform", () => ({+ clearWorkspaceStorage: mockClearWorkspaceStorage,+ defaultStorage: { getItem: () => null, setItem: () => {}, removeItem: () => {} },+}));++vi.mock("@multica/core/drafts/cleanup-registry", () => ({+ resetAllRegisteredDrafts: mockReset,+}));++vi.mock("@multica/core/paths", () => ({+ paths: { login: () => "/login" },+}));++vi.mock("../navigation", () => ({+ useNavigation: () => ({ push: mockPush }),+}));++describe("useLogout", () => {+ beforeEach(() => {+ calls.length = 0;+ vi.clearAllMocks();+ mockReset.mockImplementation(() => calls.push("reset"));+ mockClearWorkspaceStorage.mockImplementation((_a: unknown, slug: string) =>+ calls.push(`clear:${slug}`),+ );+ });++ it("resets in-memory drafts BEFORE removing their persisted keys", () => {+ const { result } = renderHook(() => useLogout());+ result.current();++ expect(calls).toEqual(["reset", "clear:acme", "clear:beta"]);+ });++ it("still ends by clearing the query cache, auth, and navigating to /login", () => {+ const { result } = renderHook(() => useLogout());+ result.current();++ expect(mockQueryClientClear).toHaveBeenCalledTimes(1);+ expect(mockAuthLogout).toHaveBeenCalledTimes(1);+ expect(mockPush).toHaveBeenCalledWith("/login");+ });+});diff --git a/packages/views/auth/use-logout.ts b/packages/views/auth/use-logout.tsindex fdc19ebde7..2e4494df63 100644--- a/packages/views/auth/use-logout.ts+++ b/packages/views/auth/use-logout.ts@@ -5,6 +5,7 @@ import { useQueryClient } from "@tanstack/react-query";import { useAuthStore } from "@multica/core/auth";import { workspaceKeys } from "@multica/core/workspace/queries";import { clearWorkspaceStorage, defaultStorage } from "@multica/core/platform";+import { resetAllRegisteredDrafts } from "@multica/core/drafts/cleanup-registry";import { paths } from "@multica/core/paths";import type { Workspace } from "@multica/core/types";import { useNavigation } from "../navigation";@@ -28,7 +29,17 @@ export function useLogout() {const { push } = useNavigation();return useCallback(() => {- // Clear workspace-scoped storage for every workspace this user has+ // Reset draft stores' in-memory state FIRST, before removing persisted+ // keys. Each reset is a Zustand setState, and persist middleware writes+ // the new (empty) state straight back to storage under the still-active+ // workspace slug — so resetting after removal would resurrect the very+ // keys just deleted, with whatever the reset state still carries. Memory+ // must be wiped regardless of the workspace list below: a client-side+ // navigation to /login does not reload the page, so the singletons would+ // otherwise surface the previous user's draft after the next login.+ resetAllRegisteredDrafts();++ // Then clear workspace-scoped storage for every workspace this user has// access to, BEFORE clearing the React Query cache (which holds the// workspace list). Otherwise per-workspace drafts/chat/etc would leak// to the next user on this device.diff --git a/packages/views/chat/chat-page.tsx b/packages/views/chat/chat-page.tsxindex 29dcc950a5..6a4d93b1c8 100644--- a/packages/views/chat/chat-page.tsx+++ b/packages/views/chat/chat-page.tsx@@ -261,7 +261,7 @@ export function ChatPage() {onSend={c.handleSend}restoreDraftRequest={c.restoreDraftRequest}onRestoreDraftApplied={c.handleRestoreDraftApplied}- onUploadFile={c.handleUploadFile}+ uploadEnabled={c.uploadEnabled}onStop={c.handleStop}isRunning={!!c.pendingTaskId}disabled={c.isSessionArchived || c.isAgentArchived}diff --git a/packages/views/chat/components/chat-input-draft-isolation.test.tsx b/packages/views/chat/components/chat-input-draft-isolation.test.tsxindex 93f47eabc4..af3d64309e 100644--- a/packages/views/chat/components/chat-input-draft-isolation.test.tsx+++ b/packages/views/chat/components/chat-input-draft-isolation.test.tsx@@ -4,6 +4,15 @@ 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";+import enEditor from "../../locales/en/editor.json";++// Uploads flow through the module-level coordinator, which calls+// `api.uploadFile(file, ctx, signal)` (MUL-5181 L2).+const mockApiUploadFile = vi.hoisted(() => vi.fn());++vi.mock("@multica/core/api", () => ({+ api: { uploadFile: mockApiUploadFile },+}));/*** Draft isolation across a composer switch, driven through the REAL@@ -150,6 +159,14 @@ vi.mock("@multica/core/chat", () => {}),setInputDraftAttachments: vi.fn(),addInputDraftAttachment: vi.fn(),+ appendToInputDraft: vi.fn(),+ addInputDraftUpload: vi.fn((key: string, upload: { clientUploadId: string }) => {+ const existing = state.inputDraftAttachments[key] ?? [];+ state.inputDraftAttachments[key] = [...existing, upload];+ }),+ settleInputDraftUpload: vi.fn(),+ failInputDraftUpload: vi.fn(),+ removeInputDraftUpload: vi.fn(),clearInputDraft: vi.fn(),};return {@@ -164,7 +181,7 @@ vi.mock("@multica/core/chat", () => {import { ChatInput } from "./chat-input";import { useChatStore } from "@multica/core/chat";-const TEST_RESOURCES = { en: { common: enCommon, chat: enChat } };+const TEST_RESOURCES = { en: { common: enCommon, chat: enChat, editor: enEditor } };function makeUpload(id: string, filename: string): UploadResult {const link = `/api/attachments/${id}/download`;@@ -361,14 +378,14 @@ describe("ChatInput draft isolation across a composer switch (real debounce)", (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 }));+ mockApiUploadFile.mockImplementation(async () => makeUpload("att-2", "second.png"));+ const { rerender } = render(element({ uploadEnabled: true }));// 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 }));+ rerender(element({ uploadEnabled: true }));// 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@@ -380,16 +397,18 @@ describe("ChatInput draft isolation across a composer switch (real debounce)", (await Promise.resolve();});- const addAttachment = (+ // The engine snapshots the LOADED draft as the upload target at pick+ // time — the placeholder (and its settle) file under A, never B.+ const addUpload = (useChatStore.getState() as unknown as {- addInputDraftAttachment: ReturnType<typeof vi.fn>;+ addInputDraftUpload: ReturnType<typeof vi.fn>;}- ).addInputDraftAttachment;- expect(addAttachment).toHaveBeenCalledWith(+ ).addInputDraftUpload;+ expect(addUpload).toHaveBeenCalledWith("session-a",- expect.objectContaining({ id: "att-2" }),+ expect.objectContaining({ status: "uploading", filename: "second.png" }),);- expect(addAttachment).not.toHaveBeenCalledWith("session-b", expect.anything());+ expect(addUpload).not.toHaveBeenCalledWith("session-b", expect.anything());});it("refuses to send while the composer still holds the source draft's document", () => {diff --git a/packages/views/chat/components/chat-input.test.tsx b/packages/views/chat/components/chat-input.test.tsxindex 16a6aff8de..ad58730ec5 100644--- a/packages/views/chat/components/chat-input.test.tsx+++ b/packages/views/chat/components/chat-input.test.tsx@@ -3,8 +3,23 @@ import { beforeEach, describe, it, expect, vi } from "vitest";import { act, render, screen, fireEvent, waitFor } from "@testing-library/react";import { I18nProvider } from "@multica/core/i18n/react";import type { UploadResult } from "@multica/core/hooks/use-file-upload";+import type { DraftUpload } from "@multica/core/drafts";import enCommon from "../../locales/en/common.json";import enChat from "../../locales/en/chat.json";+import enEditor from "../../locales/en/editor.json";++// Uploads flow through the module-level coordinator, which calls+// `api.uploadFile(file, ctx, signal)` (MUL-5181 L2). Tests drive uploads by+// mocking that call; it resolves a server Attachment row (makeUpload's extra+// link/markdownLink fields are ignored by the engine, which re-derives them).+const mockApiUploadFile = vi.hoisted(() => vi.fn());+// Observability for the write-back insert path: a settle whose mount died+// delivers into the live editor through this method.+const insertMarkdownSpy = vi.hoisted(() => vi.fn());++vi.mock("@multica/core/api", () => ({+ api: { uploadFile: mockApiUploadFile },+}));function makeUpload(overrides: Partial<UploadResult> & { id: string; link: string; filename: string }): UploadResult {return {@@ -30,7 +45,7 @@ function makeUpload(overrides: Partial<UploadResult> & { id: string; link: strin};}-const TEST_RESOURCES = { en: { common: enCommon, chat: enChat } };+const TEST_RESOURCES = { en: { common: enCommon, chat: enChat, editor: enEditor } };// Track drop-zone callbacks so the test can simulate a real drop.const dropHandlers = vi.hoisted(() => ({@@ -49,6 +64,11 @@ vi.mock("../../editor", async () => ({...(await vi.importActual<typeof import("../../editor/use-upload-gate")>("../../editor/use-upload-gate",)),+ // Real await-then-render submit contract (pure React) — it only imports+ // types from ContentEditor / the upload gate, so it pulls in no Tiptap tree.+ ...(await vi.importActual<typeof import("../../editor/use-composer-submit")>(+ "../../editor/use-composer-submit",+ )),useFileDropZone: ({ onDrop }: { onDrop: (files: File[]) => void }) => {dropHandlers.onDrop = onDrop;return { isDragOver: false, dropZoneProps: { "data-testid": "drop-zone" } };@@ -119,6 +139,12 @@ vi.mock("../../editor", async () => ({}},hasActiveUploads: () => uploadingRef.current > 0,+ insertMarkdownAtEnd: (md: string) => {+ insertMarkdownSpy(md);+ valueRef.current = `${valueRef.current}\n\n${md}`.trim();+ onUpdate?.(valueRef.current);+ return true;+ },// 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@@ -172,16 +198,22 @@ vi.mock("../../projects/components/project-picker", () => ({}));// Mock chat store with an in-memory implementation that supports both-// (selector) calls and getState().+// (selector) calls and getState(). Draft attachments hold coordinator-owned+// DraftUpload entries (MUL-5181 L2).vi.mock("@multica/core/chat", () => {const state = {activeSessionId: null as string | null,selectedAgentId: "agent-1",inputDrafts: {} as Record<string, string>,- inputDraftAttachments: {} as Record<string, UploadResult[]>,+ inputDraftAttachments: {} as Record<string, unknown[]>,setInputDraft: vi.fn(),+ appendToInputDraft: vi.fn(),setInputDraftAttachments: vi.fn(),addInputDraftAttachment: vi.fn(),+ addInputDraftUpload: vi.fn(),+ settleInputDraftUpload: vi.fn(),+ failInputDraftUpload: vi.fn(),+ removeInputDraftUpload: vi.fn(),clearInputDraft: vi.fn(),};return {@@ -211,10 +243,15 @@ beforeEach(() => {selectedAgentId: string;inputDrafts: Record<string, string>;setInputDraft: ReturnType<typeof vi.fn>;+ appendToInputDraft: ReturnType<typeof vi.fn>;clearInputDraft: ReturnType<typeof vi.fn>;- inputDraftAttachments: Record<string, UploadResult[]>;+ inputDraftAttachments: Record<string, DraftUpload[]>;setInputDraftAttachments: ReturnType<typeof vi.fn>;addInputDraftAttachment: ReturnType<typeof vi.fn>;+ addInputDraftUpload: ReturnType<typeof vi.fn>;+ settleInputDraftUpload: ReturnType<typeof vi.fn>;+ failInputDraftUpload: ReturnType<typeof vi.fn>;+ removeInputDraftUpload: ReturnType<typeof vi.fn>;};state.activeSessionId = null;state.selectedAgentId = "agent-1";@@ -224,44 +261,101 @@ beforeEach(() => {state.setInputDraft.mockImplementation((key: string, value: string) => {state.inputDrafts[key] = value;});+ state.appendToInputDraft.mockClear();+ // Mirrors the real store: trailing whitespace trimmed before the separator.+ state.appendToInputDraft.mockImplementation((key: string, markdown: string) => {+ const existing = state.inputDrafts[key] ?? "";+ state.inputDrafts[key] = existing.trim()+ ? `${existing.replace(/\s+$/, "")}\n\n${markdown}`+ : markdown;+ });state.setInputDraftAttachments.mockClear();- state.setInputDraftAttachments.mockImplementation((key: string, attachments: UploadResult[]) => {- if (attachments.length > 0) state.inputDraftAttachments[key] = attachments;+ state.setInputDraftAttachments.mockImplementation((key: string, uploads: DraftUpload[]) => {+ if (uploads.length > 0) state.inputDraftAttachments[key] = uploads;else delete state.inputDraftAttachments[key];});state.addInputDraftAttachment.mockClear();state.addInputDraftAttachment.mockImplementation((key: string, attachment: UploadResult) => {const existing = state.inputDraftAttachments[key] ?? [];- state.inputDraftAttachments[key] = existing.some((a) => a.id === attachment.id)- ? existing.map((a) => (a.id === attachment.id ? attachment : a))- : [...existing, attachment];+ state.inputDraftAttachments[key] = [+ ...existing,+ {+ clientUploadId: attachment.id,+ status: "uploaded",+ filename: attachment.filename,+ size: attachment.size_bytes,+ attachment,+ } as DraftUpload,+ ];+ });+ state.addInputDraftUpload.mockClear();+ state.addInputDraftUpload.mockImplementation((key: string, upload: DraftUpload) => {+ const existing = state.inputDraftAttachments[key] ?? [];+ if (existing.some((u) => u.clientUploadId === upload.clientUploadId)) return;+ state.inputDraftAttachments[key] = [...existing, upload];+ });+ state.settleInputDraftUpload.mockClear();+ state.settleInputDraftUpload.mockImplementation(+ (key: string, clientUploadId: string, attachment: UploadResult) => {+ const existing = state.inputDraftAttachments[key] ?? [];+ state.inputDraftAttachments[key] = existing.map((u) =>+ u.clientUploadId === clientUploadId+ ? ({+ clientUploadId,+ status: "uploaded",+ filename: attachment.filename,+ size: attachment.size_bytes,+ attachment,+ } as DraftUpload)+ : u,+ );+ },+ );+ state.failInputDraftUpload.mockClear();+ state.failInputDraftUpload.mockImplementation(+ (key: string, clientUploadId: string, error?: string) => {+ const existing = state.inputDraftAttachments[key] ?? [];+ state.inputDraftAttachments[key] = existing.map((u) =>+ u.clientUploadId === clientUploadId+ ? ({ ...u, status: "failed", error } as DraftUpload)+ : u,+ );+ },+ );+ state.removeInputDraftUpload.mockClear();+ state.removeInputDraftUpload.mockImplementation((key: string, clientUploadId: string) => {+ const remaining = (state.inputDraftAttachments[key] ?? []).filter(+ (u) => u.clientUploadId !== clientUploadId,+ );+ if (remaining.length > 0) state.inputDraftAttachments[key] = remaining;+ else delete state.inputDraftAttachments[key];});state.clearInputDraft.mockClear();state.clearInputDraft.mockImplementation((key: string) => {delete state.inputDrafts[key];delete state.inputDraftAttachments[key];});+ mockApiUploadFile.mockReset();+ mockApiUploadFile.mockImplementation(async () =>+ makeUpload({ id: "att-1", link: "https://cdn.example/att-1.png", filename: "img.png" }),+ );+ insertMarkdownSpy.mockReset();});function renderInput(props: Partial<React.ComponentProps<typeof ChatInput>> = {}) {const onSend = props.onSend ?? vi.fn();- const onUploadFile =- props.onUploadFile ??- vi.fn(async (_file: File) =>- makeUpload({ id: "att-1", link: "https://cdn.example/att-1.png", filename: "img.png" }),- );render(<I18nProvider locale="en" resources={TEST_RESOURCES}>- <ChatInput onSend={onSend} onUploadFile={onUploadFile} agentName="Multica" {...props} />+ <ChatInput onSend={onSend} uploadEnabled agentName="Multica" {...props} /></I18nProvider>,);- return { onSend, onUploadFile };+ return { onSend };}function element(props: Partial<React.ComponentProps<typeof ChatInput>>) {return (<I18nProvider locale="en" resources={TEST_RESOURCES}>- <ChatInput onSend={vi.fn()} onUploadFile={vi.fn()} agentName="Multica" {...props} />+ <ChatInput onSend={vi.fn()} uploadEnabled agentName="Multica" {...props} /></I18nProvider>);}@@ -314,10 +408,10 @@ describe("ChatInput new-chat draft identity", () => {});it("keeps staged attachments across an agent switch", async () => {- const onUploadFile = vi.fn(async (_file: File) =>+ mockApiUploadFile.mockImplementation(async () =>makeUpload({ id: "att-kept", link: "/api/attachments/att-kept/download", filename: "a.png" }),);- const { rerender } = render(element({ agentName: "agent-1", onUploadFile }));+ const { rerender } = render(element({ agentName: "agent-1" }));await act(async () => {dropHandlers.onDrop?.([new File(["x"], "a.png", { type: "image/png" })]);@@ -326,11 +420,15 @@ describe("ChatInput new-chat draft identity", () => {switchAgentTo("agent-2", rerender);const state = useChatStore.getState() as unknown as {- inputDraftAttachments: Record<string, UploadResult[]>;+ inputDraftAttachments: Record<string, DraftUpload[]>;};// 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(+ state.inputDraftAttachments["__draft_new__"]?.map((u) =>+ u.status === "uploaded" ? u.attachment.id : u.status,+ ),+ ).toEqual(["att-kept"]);expect(Object.keys(state.inputDraftAttachments)).toEqual(["__draft_new__"]);});@@ -548,8 +646,8 @@ describe("ChatInput project context", () => {});describe("ChatInput attachment wiring", () => {- it("routes dropped files through the editor's upload handler", async () => {- const { onUploadFile } = renderInput();+ it("routes dropped files through the coordinator upload", async () => {+ renderInput();expect(dropHandlers.onDrop).not.toBeNull();const file = new File(["x"], "drop.png", { type: "image/png" });await act(async () => {@@ -558,15 +656,16 @@ describe("ChatInput attachment wiring", () => {await Promise.resolve();await Promise.resolve();});- expect(onUploadFile).toHaveBeenCalledWith(file);+ expect(mockApiUploadFile).toHaveBeenCalledTimes(1);+ expect(mockApiUploadFile.mock.calls[0]?.[0]).toBe(file);});it("passes attachment_ids to onSend for uploads still referenced in the content", async () => {const onSend = vi.fn();- const onUploadFile = vi.fn(async (_file: File) =>+ mockApiUploadFile.mockImplementation(async () =>makeUpload({ id: "att-42", link: "https://cdn.example/att-42.png", filename: "x.png" }),);- renderInput({ onSend, onUploadFile });+ renderInput({ onSend });// Simulate the drop → editor.uploadFile → onUploadFile happy path. The// mock editor appends the markdown link into its value and calls@@ -593,9 +692,11 @@ describe("ChatInput attachment wiring", () => {expect(onSend).toHaveBeenCalledTimes(1);const [, ids] = onSend.mock.calls[0]!;expect(ids).toEqual(["att-42"]);- expect(useChatStore.getState().addInputDraftAttachment).toHaveBeenCalledWith(+ // The placeholder was staged in the LOADED draft slot at pick time and+ // settled into the uploaded entry the send just bound.+ expect(useChatStore.getState().addInputDraftUpload).toHaveBeenCalledWith("__draft_new__",- expect.objectContaining({ id: "att-42" }),+ expect.objectContaining({ status: "uploading", filename: "drop.png" }),);});@@ -611,15 +712,17 @@ describe("ChatInput attachment wiring", () => {const onSend = vi.fn();const SHORT_LIVED_LINK = "/uploads/workspaces/ws-1/foo.png?exp=42&sig=stale";const STABLE_MARKDOWN_LINK = "/api/attachments/att-99/download";- const onUploadFile = vi.fn(async (_file: File) =>+ mockApiUploadFile.mockImplementation(async () =>makeUpload({id: "att-99",link: SHORT_LIVED_LINK,+ // The engine derives markdownLink from the row's markdown_url.+ markdown_url: STABLE_MARKDOWN_LINK,markdownLink: STABLE_MARKDOWN_LINK,filename: "foo.png",}),);- renderInput({ onSend, onUploadFile });+ renderInput({ onSend });const file = new File(["x"], "foo.png", { type: "image/png" });await act(async () => {@@ -654,8 +757,8 @@ describe("ChatInput attachment wiring", () => {resolveUpload = res;});const onSend = vi.fn();- const onUploadFile = vi.fn(() => uploadPromise);- renderInput({ onSend, onUploadFile });+ mockApiUploadFile.mockImplementation(() => uploadPromise);+ renderInput({ onSend });// Give the editor some text so isEmpty=false — this isolates the// disabled state to the pending-upload condition (otherwise both@@ -694,8 +797,129 @@ describe("ChatInput attachment wiring", () => {expect(ids).toEqual(["att-slow"]);});- it("does not render the file upload button when onUploadFile is omitted", () => {- renderInput({ onUploadFile: undefined });+ it("delivers a dead mount's settle into the editor still HOLDING that draft, not the selected one", async () => {+ const state = useChatStore.getState() as unknown as {+ activeSessionId: string | null;+ inputDrafts: Record<string, string>;+ inputDraftAttachments: Record<string, DraftUpload[]>;+ };++ // Mount #1 composes to session-a and starts an upload that outlives it.+ state.activeSessionId = "session-a";+ let resolveA!: (v: UploadResult) => void;+ mockApiUploadFile.mockImplementationOnce(+ () => new Promise<UploadResult>((r) => (resolveA = r)),+ );+ const first = render(element({}));+ await act(async () => {+ dropHandlers.onDrop?.([new File(["x"], "a.png", { type: "image/png" })]);+ await Promise.resolve();+ });+ first.unmount();++ // Mount #2 also loads session-a, then gets PINNED to it by its own upload+ // while the user switches selection to session-b: loaded=A, selected=B.+ let resolveB!: (v: UploadResult) => void;+ mockApiUploadFile.mockImplementationOnce(+ () => new Promise<UploadResult>((r) => (resolveB = r)),+ );+ const second = render(element({}));+ await act(async () => {+ dropHandlers.onDrop?.([new File(["y"], "b.png", { type: "image/png" })]);+ await Promise.resolve();+ });+ state.activeSessionId = "session-b";+ second.rerender(element({}));++ // Mount #1's upload settles. Its target draft is session-a — which mount+ // #2's editor is HOLDING (not showing as selected). The registry must be+ // keyed by the LOADED draft, so the insert reaches that document; keying+ // by selection would misroute or drop it.+ await act(async () => {+ resolveA(+ makeUpload({+ id: "att-pinned",+ link: "/api/attachments/att-pinned/download",+ filename: "a.png",+ }),+ );+ await Promise.resolve();+ await Promise.resolve();+ });++ expect(insertMarkdownSpy).toHaveBeenCalledWith(+ expect.stringContaining("/api/attachments/att-pinned/download"),+ );+ expect(state.inputDrafts["session-a"] ?? "").toContain(+ "/api/attachments/att-pinned/download",+ );+ // The selected-but-not-loaded draft must not receive the link.+ expect(state.inputDrafts["session-b"] ?? "").not.toContain("att-pinned");++ await act(async () => {+ resolveB(makeUpload({ id: "att-b", link: "/api/attachments/att-b/download", filename: "b.png" }));+ await Promise.resolve();+ });+ });++ it("text typed while a chat send is in flight survives the success", async () => {+ const state = useChatStore.getState() as unknown as {+ inputDrafts: Record<string, string>;+ };+ let resolveSend!: (v: boolean) => void;+ const onSend = vi.fn(+ (+ _content: string,+ _ids: string[] | undefined,+ _commit: (o?: { extraDraftKeys?: string[]; clearEditor?: boolean }) => void,+ ) => new Promise<boolean>((r) => { resolveSend = r; }),+ );+ renderInput({ onSend: onSend as never });++ const editor = screen.getByTestId("editor");+ fireEvent.change(editor, { target: { value: "draft A" } });+ const buttons = screen.getAllByRole("button");+ fireEvent.click(buttons[buttons.length - 1]!);+ await waitFor(() => expect(onSend).toHaveBeenCalled());++ // The editor stays interactive during the send; the debounced commit files+ // the newer text under the same slot mid-flight.+ fireEvent.change(editor, { target: { value: "draft B typed during send" } });++ await act(async () => {+ resolveSend(true);+ await Promise.resolve();+ });++ // Success may only clear what it sent — the newer draft survives, and the+ // editor was not scrubbed over it.+ expect(state.inputDrafts["__draft_new__"]).toBe("draft B typed during send");+ expect(editorState.cleared).toBe(0);+ });++ it("keeps an in-flight placeholder while the user keeps typing", () => {+ // commitDraft prunes uploaded rows the body no longer references; a+ // placeholder has no body reference yet, so a keystroke must never prune+ // it — that would drop the chip and strand the settle on the guard.+ const state = useChatStore.getState() as unknown as {+ inputDraftAttachments: Record<string, DraftUpload[]>;+ };+ state.inputDraftAttachments["__draft_new__"] = [+ { clientUploadId: "c-flight", status: "uploading", filename: "up.png", size: 1 },+ ];+ renderInput();++ fireEvent.change(screen.getByTestId("editor"), { target: { value: "still typing" } });++ expect(state.inputDraftAttachments["__draft_new__"]).toHaveLength(1);+ expect(state.inputDraftAttachments["__draft_new__"]?.[0]).toMatchObject({+ status: "uploading",+ clientUploadId: "c-flight",+ });+ });++ it("does not render the file upload button when uploads are disabled", () => {+ renderInput({ uploadEnabled: false });// The ChatAddMenu "+" (which hosts file upload) only mounts when upload// wiring is present — without it the chat input falls back to "submit +// extras" only. Probe by counting buttons: with no upload, only the@@ -874,7 +1098,7 @@ describe("ChatInput async send", () => {it("sends attachment ids restored from persisted draft attachments", async () => {const state = useChatStore.getState() as unknown as {inputDrafts: Record<string, string>;- inputDraftAttachments: Record<string, UploadResult[]>;+ inputDraftAttachments: Record<string, DraftUpload[]>;};const attachment = makeUpload({id: "att-persisted",@@ -882,7 +1106,17 @@ describe("ChatInput async send", () => {filename: "persisted.png",});state.inputDrafts["__draft_new__"] = "see ";- state.inputDraftAttachments["__draft_new__"] = [attachment];+ // Persisted drafts hold DraftUpload entries (the real store normalizes+ // legacy bare rows into this shape on load).+ state.inputDraftAttachments["__draft_new__"] = [+ {+ clientUploadId: "att-persisted",+ status: "uploaded",+ filename: attachment.filename,+ size: attachment.size_bytes,+ attachment,+ },+ ];const onSend = vi.fn<ChatInputOnSend>((_content, _ids, commitInput) => {commitInput();diff --git a/packages/views/chat/components/chat-input.tsx b/packages/views/chat/components/chat-input.tsxindex 68385694a0..4015c37335 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, useLayoutEffect, useRef, useState } from "react";+import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";import { TriangleAlert } from "lucide-react";import { cn } from "@multica/ui/lib/utils";import {@@ -10,20 +10,26 @@ import {useFileDropZone,FileDropOverlay,useUploadGate,+ useComposerSubmit,} from "../../editor";+import {+ useCoordinatedUploads,+ type UploadDraftBinding,+} from "../../editor/use-coordinated-uploads";+import { ComposerUploadChips } from "../../issues/components/composer-upload-chips";import { SubmitButton } from "@multica/ui/components/common/submit-button";import { ChatAddMenu } from "./chat-add-menu";import { useChatStore, DRAFT_NEW_SESSION } from "@multica/core/chat";+import { attachmentToDraftUpload, type DraftUpload } from "@multica/core/drafts";import { createLogger } from "@multica/core/logger";import { formatShortcut, useShortcut } from "@multica/core/shortcuts";-import type { UploadResult } from "@multica/core/hooks/use-file-upload";import type { MentionItem } from "../../editor/extensions/mention-suggestion";import type { Attachment, Project } from "@multica/core/types";import { ProjectPicker } from "../../projects/components/project-picker";import { useT } from "../../i18n";const logger = createLogger("chat.ui");-const EMPTY_ATTACHMENTS: Attachment[] = [];+const EMPTY_UPLOADS: DraftUpload[] = [];/** Editor identity for the chat composer — see the editorKey note below. */const CHAT_COMPOSER_EDITOR_KEY = "chat-composer";@@ -73,13 +79,11 @@ interface ChatInputProps {* therefore treat this as the single terminal transition and consume the row.*/onRestoreDraftApplied?: () => void;- /** Receives a File and returns the attachment row (with id + CDN link).- * The wrapper owner (ChatWindow) lazy-creates a chat_session if needed- * and forwards `chatSessionId` to the upload — chat-input only cares- * about the upload result so it can map URL → id for back-fill on send.- * When unset, paste/drag/button still type into the editor but no upload- * fires (the editor's file-upload extension is a no-op without a handler). */- onUploadFile?: (file: File) => Promise<UploadResult | null>;+ /** True when uploads are available for this composer (an agent is selected).+ * The transport itself is the coordinated-upload engine (MUL-5181 L2) —+ * the owner only says whether the affordance exists. When false,+ * paste/drag/button still type into the editor but no upload fires. */+ uploadEnabled?: boolean;onStop?: () => void;isRunning?: boolean;disabled?: boolean;@@ -125,7 +129,7 @@ export function ChatInput({onSend,restoreDraftRequest,onRestoreDraftApplied,- onUploadFile,+ uploadEnabled: uploadAllowed,onStop,isRunning,disabled,@@ -167,27 +171,25 @@ export function ChatInput({// - Draft restore (a cancelled run, a failed send): writes into// `inputDraft`, and the editor's synchronized-value 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.+ // - Session switch / lazy create: sending from a brand-new chat flips+ // `activeSessionId` from null → uuid while an upload's blob preview may+ // still be in the document. A session-keyed editor would unmount right+ // then, 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(- (s) => s.inputDraftAttachments[draftKey] ?? EMPTY_ATTACHMENTS,+ const storeUploads = useChatStore(+ (s) => s.inputDraftAttachments[draftKey] ?? EMPTY_UPLOADS,);const setInputDraft = useChatStore((s) => s.setInputDraft);const setInputDraftAttachments = useChatStore((s) => s.setInputDraftAttachments);- const addInputDraftAttachment = useChatStore((s) => s.addInputDraftAttachment);const clearInputDraft = useChatStore((s) => s.clearInputDraft);const [isEmpty, setIsEmpty] = useState(!inputDraft.trim());- const [isSubmitting, setIsSubmitting] = useState(false);// `isEmpty` tracks the LIVE editor, which the persisted draft lags by a// debounce, so the send affordance cannot be derived from `inputDraft` alone.// But `isEmpty` is never re-derived when the composer switches draft slots@@ -225,13 +227,17 @@ export function ChatInput({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),+ const uploads =+ useChatStore.getState().inputDraftAttachments[key] ?? EMPTY_UPLOADS;+ if (uploads.length === 0) return;+ // Prune only COMPLETED uploads the body no longer references — deleting+ // an image's markdown drops the staged upload with it. Placeholders+ // (uploading / failed / interrupted) have no body reference yet; the+ // status chips are their only UI, so they must survive every keystroke.+ const referenced = uploads.filter(+ (u) => u.status !== "uploaded" || isAttachmentReferenced(markdown, u.attachment),);- if (referenced.length !== attachments.length) {+ if (referenced.length !== uploads.length) {setInputDraftAttachments(key, referenced);}},@@ -245,6 +251,45 @@ export function ChatInput({// image would leave stuck (MUL-4808).const uploadGate = useUploadGate(editorRef);+ // Reactive mirror of `editorDraftKeyRef` for the live-editor registry: a+ // write-back may insert into this editor only while its DOCUMENT belongs to+ // the settling draft, and a ref advance alone re-runs no effect. Updated by+ // the adopt layout effect below, alongside the ref.+ const [loadedDraftKey, setLoadedDraftKey] = useState(draftKey);++ // Store-backed accessors for one draft slot, buildable for ANY key: the+ // engine snapshots `resolveUploadTarget()` at pick time so an upload lands+ // in — and settles against — the draft the editor was HOLDING, even if the+ // user has since switched sessions.+ const makeUploadBinding = useCallback((key: string): UploadDraftBinding => ({+ registryKey: `chat:${key}`,+ getUploads: () => useChatStore.getState().inputDraftAttachments[key] ?? EMPTY_UPLOADS,+ addUpload: (u) => useChatStore.getState().addInputDraftUpload(key, u),+ settleUpload: (id, att) => useChatStore.getState().settleInputDraftUpload(key, id, att),+ failUpload: (id, err) => useChatStore.getState().failInputDraftUpload(key, id, err),+ removeUpload: (id) => useChatStore.getState().removeInputDraftUpload(key, id),+ getBody: () => useChatStore.getState().inputDrafts[key] ?? "",+ appendToBody: (md) => useChatStore.getState().appendToInputDraft(key, md),+ }), []);+ const uploadBinding = useMemo(+ () => makeUploadBinding(draftKey),+ [makeUploadBinding, draftKey],+ );+ // Coordinator-owned uploads (MUL-5181 L2): survive window close, abort on+ // logout, read `interrupted` after a reload. `gate` widens the editor gate+ // with the draft's placeholders so a REOPENED composer over a still-running+ // upload cannot send past it.+ const {+ uploads: draftUploads,+ attachments: draftAttachments,+ handleUpload,+ removeUpload,+ gate,+ } = useCoordinatedUploads(uploadBinding, storeUploads, {}, uploadGate, editorRef, {+ resolveUploadTarget: () => makeUploadBinding(editorDraftKeyRef.current),+ liveRegistryKey: `chat:${loadedDraftKey}`,+ });+// Move the editor from the draft it holds to the draft that is selected.//// Two hazards make this more than "let the value sync handle it":@@ -287,6 +332,7 @@ export function ChatInput({commitDraft(loadedKey, pending);}editorDraftKeyRef.current = draftKey;+ setLoadedDraftKey(draftKey);if (!deferredAdoptRef.current) return;deferredAdoptRef.current = false;const incoming = useChatStore.getState().inputDrafts[draftKey] ?? "";@@ -295,20 +341,6 @@ export function ChatInput({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- // the comment-input flow exactly. The map key MUST match what the- // editor actually wrote into the markdown — that's `markdownLink`- // (the stable per-attachment URL) for normal post-MUL-3130 uploads- // and `link` (= att.url) for the no-workspace upload branch where- // there's no attachment-row id to address. Storing only `link` here- // would cause `content.includes(url)` to miss every new chat upload- // because the editor persists `markdownLink` instead, and the- // `onSend` call would silently drop `attachment_ids` so the- // attachment never binds to the chat message.- const uploadMapRef = useRef<Map<string, string>>(new Map());-// Grab keyboard focus when the owner bumps `focusRequest` (a new chat was// started) so the user can type immediately. The editor's `focus()` latches// through to `onCreate` when it isn't mounted yet, so this works even on the@@ -338,7 +370,7 @@ export function ChatInput({// pending and this effect re-runs on every draft change, so the restore// lands as soon as the user sends or clears what they were typing. Marking// it done here would strand it for the rest of this composer's life.- if (inputDraft.trim() || draftAttachments.length > 0) {+ if (inputDraft.trim() || draftUploads.length > 0) {logger.debug("input.restore waiting: draft has content", {draftKey,restoreId: restoreDraftRequest.id,@@ -347,38 +379,23 @@ export function ChatInput({}appliedRestoreIdRef.current = restoreDraftRequest.id;setInputDraft(draftKey, restoreDraftRequest.content);- setInputDraftAttachments(draftKey, restoreDraftRequest.attachments ?? []);+ // Restores carry completed server rows — stage them as uploaded entries.+ setInputDraftAttachments(+ draftKey,+ (restoreDraftRequest.attachments ?? []).map(attachmentToDraftUpload),+ );setIsEmpty(!restoreDraftRequest.content.trim());onRestoreDraftApplied?.();}, [draftKey,inputDraft,- draftAttachments,+ draftUploads,onRestoreDraftApplied,restoreDraftRequest,setInputDraft,setInputDraftAttachments,]);- const handleUpload = useCallback(- async (file: File): Promise<UploadResult | null> => {- if (!onUploadFile) return null;- const result = await onUploadFile(file);- if (result) {- const persistedURL = result.markdownLink || result.link;- uploadMapRef.current.set(persistedURL, result.id);- // 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, onUploadFile],- );-// Drop zone wraps the rounded card so a drop anywhere on the input// surface routes the file through the editor's upload extension (same// handler as the in-editor paste path).@@ -386,113 +403,112 @@ export function ChatInput({onDrop: (files) => files.forEach((f) => editorRef.current?.uploadFile(f)),});- const handleSend = async () => {- const content = editorRef.current?.getMarkdown()?.replace(/(\n\s*)+$/, "").trim();- if (!content || isRunning || isSubmitting || disabled || noAgent) {- logger.debug("input.send skipped", {- emptyContent: !content,- isRunning,- isSubmitting,- disabled,- noAgent,- });- return;- }- // Block the send while any file is still uploading. If we let it- // through the attachment id is not yet in uploadMapRef (the upload- // resolves later) and the attachment would only end up bound to the- // session, not the message — the agent then can't `multica attachment- // download <id>` the file. The SubmitButton is also disabled in this- // state via `uploading`, but Mod+Enter bypasses the button so we- // still gate here.- if (uploadGate.isBlocked()) {- 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[] = [];- for (const [url, id] of uploadMapRef.current) {- if (content.includes(url)) activeIds.push(id);- }- for (const attachment of draftAttachments) {- if (isAttachmentReferenced(content, attachment)) activeIds.push(attachment.id);- }- const uniqueActiveIds = Array.from(new Set(activeIds));- // Capture draft key BEFORE onSend — creating a new session mutates- // activeSessionId synchronously, so reading it after onSend would point- // at the new session and leave the old draft orphaned.- const keyAtSend = draftKey;- let committed = false;- const commitInput = (options?: { extraDraftKeys?: string[]; clearEditor?: boolean }) => {- if (committed) return;- committed = true;- // `clearEditor === false` means the owner sent fire-and-forget while the- // user had already navigated to another session. The editor instance is- // shared across sessions, so it now shows (and the user may be typing- // into) a DIFFERENT draft — clearing it or blurring would wipe that- // visible input. Only scrub the editor when the user is still on the- // session they sent from.- if (options?.clearEditor !== false) {- editorRef.current?.clearContent();- // Drop focus so the caret doesn't keep blinking under the StatusPill /- // streaming reply that's about to take over the user's attention. The- // input is also `disabled` once isRunning flips, and a focused-but-- // disabled editor reads as a stale cursor. We deliberately don't auto-- // refocus on completion — that would interrupt the user if they're- // selecting text from the assistant reply; one click to refocus is- // a fair price for not stealing focus mid-action.- editorRef.current?.blur();- setIsEmpty(true);+ // The unified await-then-render send contract (MUL-5181). `useComposerSubmit`+ // owns the six-step pessimistic submit — empty-guard, synchronous single-flight+ // (a ref, so a double Mod+Enter in one tick cannot slip past a render-behind+ // state boolean and double-send), the submit-time upload re-check, and the+ // `submitting` lock/spinner. The chat-specific work — the loaded-draft guard,+ // attachment-id resolution, and the owner-driven `commitInput` handoff — stays+ // here in `onSubmit`, which receives the already-normalized content.+ const { submitting, submit } = useComposerSubmit({+ editorRef,+ uploadGate: gate,+ onSubmit: async (content: string): Promise<boolean> => {+ // These states disable the SubmitButton, but Mod+Enter bypasses it — so a+ // read-only or busy composer must still refuse the keyboard path.+ if (isRunning || disabled || noAgent) {+ logger.debug("input.send skipped", { isRunning, disabled, noAgent });+ return false;}- // The sent draft's data is cleared regardless — the message is on its- // way, so its persisted draft must not resurface.- clearInputDraft(keyAtSend);- for (const key of options?.extraDraftKeys ?? []) {- if (key !== keyAtSend) clearInputDraft(key);+ // 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 (re-checked inside useComposerSubmit) 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 submit 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 false;}- uploadMapRef.current.clear();- setIsSubmitting(false);- };- logger.info("input.send", {- contentLength: content.length,- draftKey: keyAtSend,- attachmentCount: uniqueActiveIds.length,- });- setIsSubmitting(true);- let accepted: void | boolean;- try {- accepted = await onSend(+ // 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[] = [];+ for (const attachment of draftAttachments) {+ if (isAttachmentReferenced(content, attachment)) activeIds.push(attachment.id);+ }+ const uniqueActiveIds = Array.from(new Set(activeIds));+ // Capture draft key BEFORE onSend — creating a new session mutates+ // activeSessionId synchronously, so reading it after onSend would point+ // at the new session and leave the old draft orphaned.+ const keyAtSend = draftKey;+ // Stale-submit guard (MUL-5181 P0): snapshot the sent draft's persisted+ // value, flushing the editor's pending debounce first so pre-submit+ // typing is inside the snapshot. A late success may only clear what it+ // actually sent — text typed DURING the send (or by a reopened composer+ // after this one unmounted) survives in both the editor and the store.+ const pendingFlush = editorRef.current?.flushPendingUpdate?.();+ if (pendingFlush != null) commitDraft(editorDraftKeyRef.current, pendingFlush);+ const draftValueAtSend = useChatStore.getState().inputDrafts[keyAtSend];+ let committed = false;+ const commitInput = (options?: { extraDraftKeys?: string[]; clearEditor?: boolean }) => {+ if (committed) return;+ committed = true;+ // `clearEditor === false` means the owner sent fire-and-forget while the+ // user had already navigated to another session. The editor instance is+ // shared across sessions, so it now shows (and the user may be typing+ // into) a DIFFERENT draft — clearing it or blurring would wipe that+ // visible input. Only scrub the editor when the user is still on the+ // session they sent from.+ // Flush typing still inside the debounce window before judging: it+ // belongs to the LOADED document and must count as a mid-flight edit.+ const lateMd = editorRef.current?.flushPendingUpdate?.();+ if (lateMd != null) commitDraft(editorDraftKeyRef.current, lateMd);+ const liveDraft = useChatStore.getState().inputDrafts[keyAtSend];+ const untouched = liveDraft === undefined || liveDraft === draftValueAtSend;+ if (options?.clearEditor !== false && untouched) {+ editorRef.current?.clearContent();+ // Drop focus so the caret doesn't keep blinking under the StatusPill /+ // streaming reply that's about to take over the user's attention. The+ // input is also `disabled` once isRunning flips, and a focused-but-+ // disabled editor reads as a stale cursor. We deliberately don't auto-+ // refocus on completion — that would interrupt the user if they're+ // selecting text from the assistant reply; one click to refocus is+ // a fair price for not stealing focus mid-action.+ editorRef.current?.blur();+ setIsEmpty(true);+ }+ // The sent draft's data is cleared only when untouched — the message+ // is on its way, but a draft replaced since the snapshot is NEWER work+ // and must not resurface as collateral.+ if (untouched) clearInputDraft(keyAtSend);+ for (const key of options?.extraDraftKeys ?? []) {+ if (key !== keyAtSend) clearInputDraft(key);+ }+ };+ logger.info("input.send", {+ contentLength: content.length,+ draftKey: keyAtSend,+ attachmentCount: uniqueActiveIds.length,+ });+ const accepted = await onSend(content,uniqueActiveIds.length > 0 ? uniqueActiveIds : undefined,commitInput,draftAttachments.filter((attachment) => uniqueActiveIds.includes(attachment.id)),);- } catch (err) {- logger.warn("input.send failed", err);- if (!committed) setIsSubmitting(false);- return;- }- if (accepted === false) {- if (!committed) setIsSubmitting(false);- return;- }- if (!committed) commitInput();- };+ // Owner rejected the send (or threw, which useComposerSubmit also treats+ // as a rejection): the draft was never committed, so it stays put for+ // retry. Only a commit — here or by the owner — clears it.+ if (accepted === false) return false;+ if (!committed) commitInput();+ return true;+ },+ });const placeholder = noAgent? t(($) => $.input.placeholder_no_agent)@@ -504,7 +520,7 @@ export function ChatInput({? t(($) => $.input.placeholder_named, { name: agentName }): t(($) => $.input.placeholder_default);- const uploadEnabled = !!onUploadFile && !disabled && !noAgent;+ const uploadEnabled = !!uploadAllowed && !disabled && !noAgent;// Lock only while the send request itself is creating/resolving the target// session. Once accepted, its project can still be detached while agent work// continues: changing session metadata does not cancel or move that task.@@ -512,7 +528,7 @@ export function ChatInput({!!onProjectChange &&!disabled &&!noAgent &&- !isSubmitting &&+ !submitting &&!isProjectUpdating;const selectedProject = projects.find((project) => project.id === projectId);@@ -600,7 +616,7 @@ export function ChatInput({// upload's own completion dispatch.commitDraft(editorDraftKeyRef.current, md);}}- onSubmit={handleSend}+ onSubmit={submit}onUploadFile={uploadEnabled ? handleUpload : undefined}onUploadingChange={uploadGate.onUploadingChange}attachments={draftAttachments}@@ -617,6 +633,13 @@ export function ChatInput({showBubbleMenu/></div>+ {draftUploads.some((u) => u.status !== "uploaded") && (+ <ComposerUploadChips+ uploads={draftUploads}+ onRemove={removeUpload}+ className="px-3 pb-1"+ />+ )}{(uploadEnabled || projectSelectionEnabled || leftAdornment) && (<div className="absolute bottom-1.5 left-1.5 flex items-center gap-1">{(uploadEnabled || projectSelectionEnabled) && (@@ -635,18 +658,18 @@ export function ChatInput({)}<div className="absolute bottom-1 right-1.5 flex items-center gap-1"><SubmitButton- onClick={handleSend}- disabled={hasNothingToSend || isSubmitting || !!disabled || !!noAgent}- loading={isSubmitting}- busy={uploadGate.uploading}+ onClick={submit}+ disabled={hasNothingToSend || submitting || !!disabled || !!noAgent}+ loading={submitting}+ busy={gate.uploading}running={isRunning}onStop={onStop}- tooltip={uploadGate.uploading+ tooltip={gate.uploading? tEditor(($) => $.upload.in_progress): sendShortcut? `${t(($) => $.input.send_tooltip)} · ${formatShortcut(sendShortcut)}`: t(($) => $.input.send_tooltip)}- ariaLabel={uploadGate.uploading+ ariaLabel={gate.uploading? tEditor(($) => $.upload.in_progress): t(($) => $.input.send_tooltip)}stopTooltip={t(($) => $.input.stop_tooltip)}diff --git a/packages/views/chat/components/chat-window.tsx b/packages/views/chat/components/chat-window.tsxindex e32455d1af..2425b9d5fe 100644--- a/packages/views/chat/components/chat-window.tsx+++ b/packages/views/chat/components/chat-window.tsx@@ -20,7 +20,6 @@ import { projectListOptions } from "@multica/core/projects/queries";import { canAssignAgent } from "@multica/views/issues/components";import { api } from "@multica/core/api";import { useAgentPresenceDetail, useWorkspaceAgentAvailability } from "@multica/core/agents";-import { useEditorUpload } from "../../editor";import { ActorAvatar } from "../../common/actor-avatar";import { useAppForeground } from "../../common/use-app-foreground";import {@@ -57,7 +56,7 @@ import { ChatResizeHandles } from "./chat-resize-handles";import { useChatContextItems } from "./use-chat-context-items";import { useChatResize } from "./use-chat-resize";import {- hasOptimisticInFlight,+ hasInFlightPendingTask,isStillOnComposeTarget,planProjectContextChange,} from "./use-chat-controller";@@ -102,42 +101,6 @@ function appendChatMessageToLatestPageCache();}-function replaceOptimisticChatMessageId(- qc: ReturnType<typeof useQueryClient>,- sessionId: string,- optimisticId: string,- messageId: string,- taskId: string,-) {- const replace = (messages: ChatMessage[] | undefined) => {- if (!messages) return messages;- if (messages.some((m) => m.id === messageId)) {- return messages.filter((m) => m.id !== optimisticId);- }- return messages.map((m) =>- m.id === optimisticId ? { ...m, id: messageId, task_id: taskId } : m,- );- };-- qc.setQueryData<ChatMessage[]>(- chatKeys.messages(sessionId),- replace,- );- qc.setQueryData<InfiniteData<ChatMessagesPage> | undefined>(- chatKeys.messagesPage(sessionId),- (old) => {- if (!old) return old;- return {- ...old,- pages: old.pages.map((page) => ({- ...page,- messages: replace(page.messages) ?? page.messages,- })),- };- },- );-}-export function ChatWindow() {const { t } = useT("chat");const wsId = useWorkspaceId();@@ -309,18 +272,18 @@ export function ChatWindow() {// Self-heal a dangling `activeSessionId` (persisted / restored from storage)// that points at a session which was deleted or lost access: once the// sessions list has loaded and doesn't contain it — with no in-flight- // optimistic write exempting a just-created session — clear it so the+ // pending task exempting a just-created session — clear it so the// floating window shows the new-chat state instead of an editable empty chat// whose send would POST into a nonexistent session. Same fix the shared- // controller applies for the tab (kept in sync via `hasOptimisticInFlight`).+ // controller applies for the tab (kept in sync via `hasInFlightPendingTask`).// The earlier "no self-heal" note was about a naive version keyed on stale- // `allSessions`; the optimistic-write signal here exempts the freshly-created- // session (handleSend seeds its optimistic message + pending task BEFORE- // setActiveSession), so it is never mistaken for stale.+ // `allSessions`; the in-flight-pending-task signal here exempts the+ // freshly-created session (handleSend seeds its pending task from the send+ // response BEFORE setActiveSession), so it is never mistaken for stale.useEffect(() => {if (!activeSessionId || !sessionsLoaded) return;if (sessions.some((s) => s.id === activeSessionId)) return;- if (hasOptimisticInFlight(qc, activeSessionId)) return;+ if (hasInFlightPendingTask(qc, activeSessionId)) return;uiLogger.info("clearing dangling activeSessionId (floating)", { sessionId: activeSessionId });setActiveSession(null);}, [activeSessionId, sessionsLoaded, sessions, qc, setActiveSession]);@@ -346,8 +309,6 @@ export function ChatWindow() {// eslint-disable-next-line react-hooks/exhaustive-deps -- markRead ref stable}, [isOpen, appForeground, activeSessionId, currentHasUnread]);- const { uploadWithToast } = useEditorUpload();-// Lazy-creates a chat_session the first time the user needs an id —// either to send a message or to attach an uploaded file. Pulled out of// handleSend so the upload path (which fires before any text exists) can@@ -383,7 +344,7 @@ export function ChatWindow() {activeSessionId &&(!sessionsLoaded ||sessions.some((s) => s.id === activeSessionId) ||- hasOptimisticInFlight(qc, activeSessionId))+ hasInFlightPendingTask(qc, activeSessionId))) {return activeSessionId;}@@ -416,17 +377,10 @@ export function ChatWindow() {],);- const handleUploadFile = useCallback(- async (file: File) => {- if (!activeAgent) return null;- // Uploads are workspace-scoped drafts. Sending the message is the point- // where we create a chat session (if needed) and bind attachment_ids to- // the persisted chat_message row. This keeps a paste/drop from creating- // an empty chat session the user never sends.- return uploadWithToast(file);- },- [activeAgent, uploadWithToast],- );+ // Upload transport moved into the coordinated-upload engine inside ChatInput+ // (MUL-5181 L2); the host only says whether the affordance exists. Uploads+ // remain workspace-scoped drafts — sending is still the point where a+ // session is created (if needed) and attachment_ids bind to the message.const cancelChatTask = useCallback(async (@@ -524,89 +478,68 @@ export function ChatWindow() {return false;}- // Optimistic burst — everything that gives the user "I sent a message- // and the agent is now working" feedback fires BEFORE the HTTP roundtrip.- // Pre-#status-pill the pending-task seed lived after `await- // sendChatMessage` and the pill blinked in a few hundred ms after the- // user's message — small but visible "did it actually send?" gap.- const sentAt = new Date().toISOString();- const optimistic: ChatMessage = {- id: `optimistic-${Date.now()}`,+ // Await-then-render: the composer keeps the user's text and attachments+ // in place (editor locked, button spinning via `submitting`) until the+ // server accepts the send. Nothing is written into the caches, and the+ // draft is never cleared, before the roundtrip settles — a slow send never+ // reads as "posted but the box is still full", and a rejected one keeps+ // the draft for retry (ChatInput never cleared it).+ let result;+ try {+ result = await api.sendChatMessage(sessionId, finalContent, attachmentIds);+ } catch (err) {+ apiLogger.error("sendChatMessage.error", { sessionId, err });+ toast.error(t(($) => $.input.send_failed_toast));+ return false;+ }+ apiLogger.info("sendChatMessage.success", {+ sessionId,+ messageId: result.message_id,+ taskId: result.task_id,+ });++ // Render the accepted message from the server response. Seed the message+ // caches BEFORE flipping activeSessionId: if we set the active session+ // first, useQuery's first subscription to the new key sees no cached data+ // and renders ChatMessageSkeleton for one frame — the "new-chat+ // first-message" white flash. Priming the cache first means the very first+ // read after activeSessionId flips hits data synchronously and+ // ChatMessageList mounts directly. Seed the pending-task from the server's+ // real id + created_at so the StatusPill mounts anchored to the true clock+ // (no local-clock drift, no backwards snap) and the stale-session self-heal+ // exempts this just-created session until the sessions-list refetch lands.+ const sent: ChatMessage = {+ id: result.message_id,chat_session_id: sessionId,role: "user",content: finalContent,- task_id: null,- created_at: sentAt,+ task_id: result.task_id,+ created_at: result.created_at,attachments: draftAttachments,};- // Seed cache BEFORE flipping activeSessionId. If we set the active- // session first, useQuery's first subscription to the new key sees no- // cached data and renders ChatMessageSkeleton for one frame — the- // "new-chat first-message" white flash. Priming the cache first means- // the very first read after activeSessionId flips hits data- // synchronously and ChatMessageList mounts directly.- appendChatMessageToLatestPageCache(qc, sessionId, optimistic);+ appendChatMessageToLatestPageCache(qc, sessionId, sent);qc.setQueryData<ChatMessage[]>(chatKeys.messages(sessionId),- (old) => (old ? [...old, optimistic] : [optimistic]),+ (old) => (old ? [...old, sent] : [sent]),);- // Seed the pending-task with a temporary id so the StatusPill mounts- // and starts ticking the instant the user clicks send. Real task_id- // and server-authoritative created_at land below; until then the pill- // is anchored to the local clock (drift is the request RTT, ~50–200ms,- // which doesn't change the rendered "Ns" value).qc.setQueryData<ChatPendingTask>(chatKeys.pendingTask(sessionId), {- task_id: `optimistic-${optimistic.id}`,+ task_id: result.task_id,status: "queued",- created_at: sentAt,+ created_at: result.created_at,});- // 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+ // Cache primed → 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.+ // this floating window shares with the chat tab's controller. commitInput+ // clears the sent draft, and scrubs the shared editor only when the user+ // is still on the session they sent from.const live = useChatStore.getState();const stillOnSourceSession = isStillOnComposeTarget(live.activeSessionId, activeSessionId);if (stillOnSourceSession) {setActiveSession(sessionId);}commitInput?.({ extraDraftKeys: [sessionId], clearEditor: stillOnSourceSession });- apiLogger.debug("sendChatMessage.optimistic", { sessionId, optimisticId: optimistic.id });- let result;- try {- result = await api.sendChatMessage(sessionId, finalContent, attachmentIds);- } catch (err) {- apiLogger.error("sendChatMessage.error.rollback", { sessionId, optimisticId: optimistic.id, err });- stopRequestedBeforeTaskRef.current = false;- removeChatMessageFromCaches(qc, sessionId, optimistic.id);- qc.setQueryData(chatKeys.pendingTask(sessionId), {});- enqueueLocalRestore({- id: `send-failed-${optimistic.id}`,- content: finalContent,- attachments: draftAttachments,- // Restore into the session this was sent from. If the user navigated- // away (fire-and-forget) the request waits in that session's persisted- // queue until they return, rather than dumping content into another- // session or dying with this component.- sessionId,- });- toast.error(t(($) => $.input.send_failed_toast));- return false;- }- apiLogger.info("sendChatMessage.success", {- sessionId,- messageId: result.message_id,- taskId: result.task_id,- });- replaceOptimisticChatMessageId(qc, sessionId, optimistic.id, result.message_id, result.task_id);- // Replace the temporary task_id with the server's real one (so the WS- // task: handlers can match against it) and snap the anchor to the- // server's created_at — keeping the elapsed-seconds reading stable.- qc.setQueryData<ChatPendingTask>(chatKeys.pendingTask(sessionId), {- task_id: result.task_id,- status: "queued",- created_at: result.created_at,- });if (stopRequestedBeforeTaskRef.current) {stopRequestedBeforeTaskRef.current = false;await cancelChatTask(result.task_id, sessionId, {@@ -643,7 +576,6 @@ export function ChatWindow() {cancelChatTask,qc,setActiveSession,- enqueueLocalRestore,t,],);@@ -931,7 +863,7 @@ export function ChatWindow() {onSend={handleSend}restoreDraftRequest={restoreDraftRequest}onRestoreDraftApplied={handleRestoreDraftApplied}- onUploadFile={handleUploadFile}+ uploadEnabled={!!activeAgent}onStop={handleStop}isRunning={!!pendingTaskId}disabled={isSessionArchived || isAgentArchived}diff --git a/packages/views/chat/components/use-chat-controller.test.ts b/packages/views/chat/components/use-chat-controller.test.tsindex 86c6bfc40f..4dafb8d42d 100644--- a/packages/views/chat/components/use-chat-controller.test.ts+++ b/packages/views/chat/components/use-chat-controller.test.ts@@ -3,17 +3,17 @@ 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,+ hasInFlightPendingTask,isStillOnComposeTarget,planProjectContextChange,} from "./use-chat-controller";-// hasOptimisticInFlight is the discriminator the stale-session self-heal uses+// hasInFlightPendingTask is the discriminator the stale-session self-heal uses// to EXEMPT a just-created session (awaiting the list refetch) from being-// dropped as dangling. The critical property (MUL-4171 review): it must key-// off OPTIMISTIC in-flight writes, NOT merely "has cached messages" — a session-// deleted elsewhere can still hold real cached history and must remain eligible-// for self-heal.+// dropped as dangling. Post-MUL-5181 the send is await-then-render, so the+// exemption keys purely on the pending task `handleSend` seeds from the send+// response — NOT on "has cached messages": a session deleted elsewhere can still+// hold real cached history and must remain eligible for self-heal.const sid = "session-1";function msg(id: string): ChatMessage {@@ -27,46 +27,32 @@ function msg(id: string): ChatMessage {};}-describe("hasOptimisticInFlight", () => {+describe("hasInFlightPendingTask", () => {it("is false with an empty cache", () => {- expect(hasOptimisticInFlight(new QueryClient(), sid)).toBe(false);+ expect(hasInFlightPendingTask(new QueryClient(), sid)).toBe(false);});- it("is false when only real (non-optimistic) cached history exists", () => {+ it("is false when only real cached history exists (no in-flight task)", () => {const qc = new QueryClient();qc.setQueryData<ChatMessage[]>(chatKeys.messages(sid), [msg("real-1"), msg("real-2")]);qc.setQueryData<InfiniteData<ChatMessagesPage>>(chatKeys.messagesPage(sid), {pages: [{ messages: [msg("real-1")], limit: 50, has_more: false, next_cursor: null }],pageParams: [null],});- // A completed session sets pendingTask to {} (no task_id).+ // A completed session sets pendingTask to {} (no task_id) — cached history+ // alone must not exempt it from the self-heal.qc.setQueryData<ChatPendingTask>(chatKeys.pendingTask(sid), {} as ChatPendingTask);- expect(hasOptimisticInFlight(qc, sid)).toBe(false);+ expect(hasInFlightPendingTask(qc, sid)).toBe(false);});it("is true while a pending task is in flight (task_id set)", () => {const qc = new QueryClient();qc.setQueryData<ChatPendingTask>(chatKeys.pendingTask(sid), {- task_id: "optimistic-abc",+ task_id: "11111111-1111-4111-8111-111111111111",status: "queued",created_at: "2026-07-08T00:00:00Z",});- expect(hasOptimisticInFlight(qc, sid)).toBe(true);- });-- it("is true when an optimistic- message sits in the flat cache", () => {- const qc = new QueryClient();- qc.setQueryData<ChatMessage[]>(chatKeys.messages(sid), [msg("optimistic-123")]);- expect(hasOptimisticInFlight(qc, sid)).toBe(true);- });-- it("is true when an optimistic- message sits in the paged cache", () => {- const qc = new QueryClient();- qc.setQueryData<InfiniteData<ChatMessagesPage>>(chatKeys.messagesPage(sid), {- pages: [{ messages: [msg("optimistic-xyz")], limit: 50, has_more: false, next_cursor: null }],- pageParams: [null],- });- expect(hasOptimisticInFlight(qc, sid)).toBe(true);+ expect(hasInFlightPendingTask(qc, sid)).toBe(true);});});diff --git a/packages/views/chat/components/use-chat-controller.ts b/packages/views/chat/components/use-chat-controller.tsindex debe532fe6..87530ad580 100644--- a/packages/views/chat/components/use-chat-controller.ts+++ b/packages/views/chat/components/use-chat-controller.ts@@ -15,9 +15,6 @@ import { projectListOptions } from "@multica/core/projects/queries";import { canAssignAgent } from "@multica/views/issues/components";import { api, dispatchReasonCode } from "@multica/core/api";import { useAgentPresenceDetail, useWorkspaceAgentAvailability } from "@multica/core/agents";-// Direct module path, not the `../../editor` barrel: this controller is-// headless, and the barrel would pull the whole Tiptap tree in behind it.-import { useEditorUpload } from "../../editor/use-editor-upload";import {chatSessionsOptions,chatMessagesPageOptions,@@ -134,28 +131,20 @@ export function planProjectContextChange(input: {return { kind: "setDraftProject", projectId: input.targetProjectId };}-// 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-// sessions-list refetch includes it. Deliberately NOT "has cached messages": a-// session deleted elsewhere can still have real cached history, which must not-// exempt it from the stale-session self-heal.-export function hasOptimisticInFlight(+// True when a session has an in-flight pending task in the cache — the signal+// of a just-created (or actively-sending) session still awaiting server+// confirmation, before the sessions-list refetch includes it. `handleSend`+// seeds this task from the server response the instant the send is accepted, so+// it is populated before `setActiveSession` publishes the new session.+// Deliberately NOT "has cached messages": a session deleted elsewhere can still+// have real cached history, which must not exempt it from the stale-session+// self-heal.+export function hasInFlightPendingTask(qc: ReturnType<typeof useQueryClient>,sessionId: string,): boolean {const pending = qc.getQueryData<ChatPendingTask>(chatKeys.pendingTask(sessionId));- if (pending?.task_id) return true;- const flat = qc.getQueryData<ChatMessage[]>(chatKeys.messages(sessionId));- if (flat?.some((m) => m.id.startsWith("optimistic-"))) return true;- const paged = qc.getQueryData<InfiniteData<ChatMessagesPage>>(- chatKeys.messagesPage(sessionId),- );- return Boolean(- paged?.pages.some((page) =>- page.messages.some((m) => m.id.startsWith("optimistic-")),- ),- );+ return Boolean(pending?.task_id);}const CHAT_VIRTUOSO_INITIAL_FIRST_ITEM_INDEX = 1_000_000;@@ -191,43 +180,10 @@ function appendChatMessageToLatestPageCache();}-function replaceOptimisticChatMessageId(- qc: ReturnType<typeof useQueryClient>,- sessionId: string,- optimisticId: string,- messageId: string,- taskId: string,-) {- const replace = (messages: ChatMessage[] | undefined) => {- if (!messages) return messages;- if (messages.some((m) => m.id === messageId)) {- return messages.filter((m) => m.id !== optimisticId);- }- return messages.map((m) =>- m.id === optimisticId ? { ...m, id: messageId, task_id: taskId } : m,- );- };-- qc.setQueryData<ChatMessage[]>(chatKeys.messages(sessionId), replace);- qc.setQueryData<InfiniteData<ChatMessagesPage> | undefined>(- chatKeys.messagesPage(sessionId),- (old) => {- if (!old) return old;- return {- ...old,- pages: old.pages.map((page) => ({- ...page,- messages: replace(page.messages) ?? page.messages,- })),- };- },- );-}-/*** Layout-agnostic chat controller. Holds every piece of chat conversation- * state and behavior — agent resolution, session lookup, the optimistic- * send/stop/cancel burst, message pagination, and auto-mark-read — so that+ * state and behavior — agent resolution, session lookup, the await-then-render+ * send/stop/cancel flow, message pagination, and auto-mark-read — so that* both surfaces render the same conversation logic:** - ChatWindow: the floating FAB overlay (adds resize / expand / minimize).@@ -410,8 +366,6 @@ export function useChatController(opts?: { isActive?: boolean }) {// eslint-disable-next-line react-hooks/exhaustive-deps -- markRead ref stable}, [isActive, appForeground, activeSessionId, currentHasUnread]);- const { uploadWithToast } = useEditorUpload();-const sessionPromiseRef = useRef<Promise<string | null> | null>(null);const ensureSession = useCallback(async (titleSeed: string): Promise<string | null> => {@@ -424,7 +378,7 @@ export function useChatController(opts?: { isActive?: boolean }) {activeSessionId &&(!sessionsLoaded ||sessions.some((s) => s.id === activeSessionId) ||- hasOptimisticInFlight(qc, activeSessionId))+ hasInFlightPendingTask(qc, activeSessionId))) {return activeSessionId;}@@ -467,18 +421,14 @@ export function useChatController(opts?: { isActive?: boolean }) {useEffect(() => {if (!activeSessionId || !sessionsLoaded) return;if (sessions.some((s) => s.id === activeSessionId)) return;- if (hasOptimisticInFlight(qc, activeSessionId)) return;+ if (hasInFlightPendingTask(qc, activeSessionId)) return;uiLogger.info("clearing dangling activeSessionId", { sessionId: activeSessionId });setActiveSession(null);}, [activeSessionId, sessionsLoaded, sessions, qc, setActiveSession]);- const handleUploadFile = useCallback(- async (file: File) => {- if (!activeAgent) return null;- return uploadWithToast(file);- },- [activeAgent, uploadWithToast],- );+ // Upload transport moved into the coordinated-upload engine inside ChatInput+ // (MUL-5181 L2); surfaces only forward whether the affordance exists.+ const uploadEnabled = !!activeAgent;const cancelChatTask = useCallback(async (@@ -581,50 +531,17 @@ export function useChatController(opts?: { isActive?: boolean }) {return false;}- const sentAt = new Date().toISOString();- const optimistic: ChatMessage = {- id: `optimistic-${Date.now()}`,- chat_session_id: sessionId,- role: "user",- content: finalContent,- task_id: null,- created_at: sentAt,- attachments: draftAttachments,- };- appendChatMessageToLatestPageCache(qc, sessionId, optimistic);- qc.setQueryData<ChatMessage[]>(- chatKeys.messages(sessionId),- (old) => (old ? [...old, optimistic] : [optimistic]),- );- qc.setQueryData<ChatPendingTask>(chatKeys.pendingTask(sessionId), {- task_id: `optimistic-${optimistic.id}`,- 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 = isStillOnComposeTarget(live.activeSessionId, activeSessionId);- if (stillOnSourceSession) {- setActiveSession(sessionId);- }- commitInput?.({ extraDraftKeys: [sessionId], clearEditor: stillOnSourceSession });- apiLogger.debug("sendChatMessage.optimistic", { sessionId, optimisticId: optimistic.id });-+ // Await-then-render: the composer keeps the user's text and attachments+ // in place (editor locked, button spinning via `submitting`) until the+ // server accepts the send. Nothing is written into the caches, and the+ // draft is never cleared, before the roundtrip settles — a slow send never+ // reads as "posted but the box is still full", and a rejected one keeps+ // the draft for retry (ChatInput never cleared it).let result;try {result = await api.sendChatMessage(sessionId, finalContent, attachmentIds);} catch (err) {- apiLogger.error("sendChatMessage.error.rollback", { sessionId, optimisticId: optimistic.id, err });- stopRequestedBeforeTaskRef.current = false;- removeChatMessageFromCaches(qc, sessionId, optimistic.id);- qc.setQueryData(chatKeys.pendingTask(sessionId), {});- enqueueLocalRestore({- id: `send-failed-${optimistic.id}`,- content: finalContent,- attachments: draftAttachments,- sessionId,- });+ apiLogger.error("sendChatMessage.error", { sessionId, err });// Invoke permission can be revoked mid-session; the send is refused with// a structured 403 before anything persists (MUL-4525). Surface the// specific cause so the user knows it is a permission change, not a@@ -641,12 +558,44 @@ export function useChatController(opts?: { isActive?: boolean }) {messageId: result.message_id,taskId: result.task_id,});- replaceOptimisticChatMessageId(qc, sessionId, optimistic.id, result.message_id, result.task_id);++ // Render the accepted message from the server response. Prime the message+ // caches BEFORE publishing the session so the first useQuery read after+ // activeSessionId flips hits data synchronously (no new-chat skeleton+ // flash), and seed the pending task with the server's real id and+ // created_at so the StatusPill mounts anchored to the true clock and the+ // stale-session self-heal exempts this just-created session until the+ // sessions-list refetch includes it.+ const sent: ChatMessage = {+ id: result.message_id,+ chat_session_id: sessionId,+ role: "user",+ content: finalContent,+ task_id: result.task_id,+ created_at: result.created_at,+ attachments: draftAttachments,+ };+ appendChatMessageToLatestPageCache(qc, sessionId, sent);+ qc.setQueryData<ChatMessage[]>(+ chatKeys.messages(sessionId),+ (old) => (old ? [...old, sent] : [sent]),+ );qc.setQueryData<ChatPendingTask>(chatKeys.pendingTask(sessionId), {task_id: result.task_id,status: "queued",created_at: result.created_at,});+ // Cache primed → publish the new active session, but only if the user+ // hasn't navigated away mid-send. See isStillOnComposeTarget. commitInput+ // clears the sent draft, and scrubs the shared editor only when the user+ // is still on the session they sent from.+ const live = useChatStore.getState();+ const stillOnSourceSession = isStillOnComposeTarget(live.activeSessionId, activeSessionId);+ if (stillOnSourceSession) {+ setActiveSession(sessionId);+ }+ commitInput?.({ extraDraftKeys: [sessionId], clearEditor: stillOnSourceSession });+if (stopRequestedBeforeTaskRef.current) {stopRequestedBeforeTaskRef.current = false;await cancelChatTask(result.task_id, sessionId, {@@ -679,7 +628,6 @@ export function useChatController(opts?: { isActive?: boolean }) {cancelChatTask,qc,setActiveSession,- enqueueLocalRestore,t,],);@@ -872,7 +820,7 @@ export function useChatController(opts?: { isActive?: boolean }) {// actionshandleSend,handleStop,- handleUploadFile,+ uploadEnabled,handleNewChat,handleStartNewChat,handleSelectSession,diff --git a/packages/views/editor/content-editor.tsx b/packages/views/editor/content-editor.tsxindex 97568a9737..c63d464a94 100644--- a/packages/views/editor/content-editor.tsx+++ b/packages/views/editor/content-editor.tsx@@ -240,6 +240,21 @@ interface ContentEditorRef {uploadFile: (file: File) => void;/** True when file uploads are still in progress. */hasActiveUploads: () => boolean;+ /**+ * Append a markdown fragment to the end of the document (parsed, not raw+ * text), firing the normal `onUpdate` pipeline. For the upload write-back+ * path (MUL-5181): an upload that outlived the mount that started it settles+ * while a NEW editor instance is showing the same draft — that editor never+ * owned the upload's promise, so this is how the finished attachment's link+ * lands in the visible document instead of only in the persisted draft.+ *+ * Returns whether the insert actually landed. The imperative handle exists+ * from the component's first commit, but the Tiptap instance is created in a+ * passive effect — in that window (and after destroy) this is a no-op and+ * returns false so the caller can fall back or retry instead of silently+ * losing the fragment.+ */+ insertMarkdownAtEnd: (markdown: string) => boolean;/*** Cancel the pending debounced `onUpdate` and hand its markdown back to the* caller instead of firing it. Returns null when nothing is pending.@@ -801,6 +816,13 @@ const ContentEditor = forwardRef<ContentEditorRef, ContentEditorProps>(uploadAndInsertFile(editor, file, onUploadFileRef.current, endPos);},hasActiveUploads: () => (editor ? hasUploadingNode(editor) : false),+ insertMarkdownAtEnd: (markdown: string) => {+ if (!editor || editor.isDestroyed) return false;+ editor.commands.insertContentAt(editor.state.doc.content.size, markdown, {+ contentType: "markdown",+ });+ return true;+ },flushPendingUpdate: () => {// No armed timer = nothing typed since the last emit. The editor is// already clean, so the host has nothing to re-route.diff --git a/packages/views/editor/extensions/file-upload.ts b/packages/views/editor/extensions/file-upload.tsindex 6fd1df43de..be8cc7e271 100644--- a/packages/views/editor/extensions/file-upload.ts+++ b/packages/views/editor/extensions/file-upload.ts@@ -158,6 +158,11 @@ export async function uploadAndInsertFile(try {const result = await handler(file);+ // The upload outlives the mount (coordinator-owned, MUL-5181): by the+ // time it settles this editor may be destroyed. Dispatching against a+ // destroyed EditorView throws, and the catch would dispatch again —+ // the write-back path owns delivery for dead editors, not this swap.+ if (editor.isDestroyed) return;if (result) {const imagePos = findImagePosBySrc(editor, blobUrl);const imageNode = imagePos === null ? null : editor.state.doc.nodeAt(imagePos);@@ -181,7 +186,7 @@ export async function uploadAndInsertFile(removeImageBySrc(editor, blobUrl);}} catch {- removeImageBySrc(editor, blobUrl);+ if (!editor.isDestroyed) removeImageBySrc(editor, blobUrl);} finally {URL.revokeObjectURL(blobUrl);}@@ -198,13 +203,16 @@ export async function uploadAndInsertFile(try {const result = await handler(file);+ // See the image branch: a settle after this editor's destroy must not+ // dispatch against the dead EditorView.+ if (editor.isDestroyed) return;if (result) {finalizeFileCard(editor, uploadId, result.markdownLink || result.link);} else {removeUploadingFileCard(editor, uploadId);}} catch {- removeUploadingFileCard(editor, uploadId);+ if (!editor.isDestroyed) removeUploadingFileCard(editor, uploadId);}}}diff --git a/packages/views/editor/index.ts b/packages/views/editor/index.tsindex cc2c228203..9d15ea278d 100644--- a/packages/views/editor/index.ts+++ b/packages/views/editor/index.ts@@ -11,6 +11,11 @@ export {export { ReadonlyContent } from "./readonly-content";export { useFileDropZone } from "./use-file-drop-zone";export { useUploadGate, type UploadGate } from "./use-upload-gate";+export {+ useComposerSubmit,+ type ComposerSubmit,+ type ComposerSubmitOptions,+} from "./use-composer-submit";export { useEditorUpload } from "./use-editor-upload";export { FileDropOverlay } from "./file-drop-overlay";export { useLazyEditor, type LazyEditorHandle, type LazyFocusTarget } from "./use-lazy-editor";diff --git a/packages/views/editor/use-composer-submit.test.tsx b/packages/views/editor/use-composer-submit.test.tsxnew file mode 100644index 0000000000..c74cbf1683--- /dev/null+++ b/packages/views/editor/use-composer-submit.test.tsx@@ -0,0 +1,96 @@+import { describe, it, expect, vi } from "vitest";+import { renderHook, act } from "@testing-library/react";+import { useComposerSubmit } from "./use-composer-submit";+import type { ContentEditorRef } from "./content-editor";+import type { UploadGate } from "./use-upload-gate";++function editorWith(markdown: string) {+ return {+ current: { getMarkdown: () => markdown } as unknown as ContentEditorRef,+ };+}++const openGate: UploadGate = {+ uploading: false,+ onUploadingChange: () => {},+ isBlocked: () => false,+};++const blockedGate: UploadGate = { ...openGate, isBlocked: () => true };++describe("useComposerSubmit", () => {+ it("does not submit empty content", async () => {+ const onSubmit = vi.fn().mockResolvedValue(true);+ const { result } = renderHook(() =>+ useComposerSubmit({ editorRef: editorWith(" \n"), uploadGate: openGate, onSubmit }),+ );+ await act(async () => { await result.current.submit(); });+ expect(onSubmit).not.toHaveBeenCalled();+ });++ it("clears (onAccepted) only when the server accepts", async () => {+ const onAccepted = vi.fn();+ const { result } = renderHook(() =>+ useComposerSubmit({+ editorRef: editorWith("hello"),+ uploadGate: openGate,+ onSubmit: vi.fn().mockResolvedValue(true),+ onAccepted,+ }),+ );+ await act(async () => { await result.current.submit(); });+ expect(onAccepted).toHaveBeenCalledTimes(1);+ });++ it("keeps the draft when the server rejects", async () => {+ const onAccepted = vi.fn();+ const { result } = renderHook(() =>+ useComposerSubmit({+ editorRef: editorWith("hello"),+ uploadGate: openGate,+ onSubmit: vi.fn().mockResolvedValue(false),+ onAccepted,+ }),+ );+ await act(async () => { await result.current.submit(); });+ expect(onAccepted).not.toHaveBeenCalled();+ });++ it("keeps the draft when the send throws", async () => {+ const onAccepted = vi.fn();+ const { result } = renderHook(() =>+ useComposerSubmit({+ editorRef: editorWith("hello"),+ uploadGate: openGate,+ onSubmit: vi.fn().mockRejectedValue(new Error("network")),+ onAccepted,+ }),+ );+ await act(async () => { await result.current.submit(); });+ expect(onAccepted).not.toHaveBeenCalled();+ });++ it("blocks while an upload is in flight", async () => {+ const onSubmit = vi.fn().mockResolvedValue(true);+ const { result } = renderHook(() =>+ useComposerSubmit({ editorRef: editorWith("hello"), uploadGate: blockedGate, onSubmit }),+ );+ await act(async () => { await result.current.submit(); });+ expect(onSubmit).not.toHaveBeenCalled();+ });++ it("single-flights concurrent submits", async () => {+ let resolve!: (v: boolean) => void;+ const onSubmit = vi.fn().mockImplementation(() => new Promise<boolean>((r) => { resolve = r; }));+ const { result } = renderHook(() =>+ useComposerSubmit({ editorRef: editorWith("hello"), uploadGate: openGate, onSubmit }),+ );+ await act(async () => {+ const a = result.current.submit();+ const b = result.current.submit();+ resolve(true);+ await Promise.all([a, b]);+ });+ expect(onSubmit).toHaveBeenCalledTimes(1);+ });+});diff --git a/packages/views/editor/use-composer-submit.ts b/packages/views/editor/use-composer-submit.tsnew file mode 100644index 0000000000..6190305c52--- /dev/null+++ b/packages/views/editor/use-composer-submit.ts@@ -0,0 +1,88 @@+"use client";++/**+ * The unified await-then-render send contract for every composer (MUL-5181).+ *+ * Before this hook, comment-input, reply-input, comment-card (edit),+ * create-issue, and quick-create each hand-copied the same six-step+ * "pessimistic submit": read markdown, guard empty/in-flight, re-read+ * the upload gate, lock + spin, await the server, and clear only on success+ * (keep the draft on failure). The copies drifted — some guarded single-flight+ * with a ref, some with a state boolean a render behind; some re-checked the+ * upload gate at submit time, some trusted the disabled button. This+ * centralizes the contract so every surface behaves identically.+ *+ * It is deliberately await-then-render, NOT optimistic: the composer keeps the+ * user's text and attachments in place (send affordance locked and spinning)+ * until the server accepts the submission, then clears. A slow send never+ * looks like "posted but the box is still full", and a rejected send keeps the+ * draft for retry instead of silently dropping it. The editor itself stays+ * interactive (Tiptap cannot toggle editable post-mount), so callers' accepted+ * handlers guard on a submit-time snapshot: success clears ONLY the draft it+ * submitted, and anything typed during the request survives.+ */++import { useCallback, useRef, useState, type RefObject } from "react";+import type { ContentEditorRef } from "./content-editor";+import type { UploadGate } from "./use-upload-gate";++export interface ComposerSubmitOptions {+ editorRef: RefObject<ContentEditorRef | null>;+ uploadGate: UploadGate;+ /**+ * Perform the send. Resolve `true` when the server accepted the submission+ * (the composer then clears via `onAccepted`); resolve `false` to keep the+ * draft in place for retry. Throwing is treated as `false`.+ */+ onSubmit: (content: string) => Promise<boolean>;+ /**+ * Run once after an accepted submit: clear the editor, attachments, and the+ * persisted draft. Not run on rejection.+ */+ onAccepted?: () => void;+ /** Normalize the raw markdown before the empty-guard and `onSubmit`. */+ normalize?: (raw: string) => string;+}++export interface ComposerSubmit {+ /** True from submit start until the server settles. Drives lock + spinner. */+ submitting: boolean;+ /** Invoke from the send button and the Cmd/Ctrl+Enter shortcut. */+ submit: () => Promise<void>;+}++const defaultNormalize = (raw: string) => raw.replace(/(\n\s*)+$/, "").trim();++export function useComposerSubmit(opts: ComposerSubmitOptions): ComposerSubmit {+ const [submitting, setSubmitting] = useState(false);+ // Synchronous single-flight. `submitting` is a render behind, so a second+ // Enter in the same tick would slip past a state-only guard and double-send.+ const inFlight = useRef(false);+ const optsRef = useRef(opts);+ optsRef.current = opts;++ const submit = useCallback(async () => {+ const o = optsRef.current;+ const raw = o.editorRef.current?.getMarkdown() ?? "";+ const content = (o.normalize ?? defaultNormalize)(raw);+ if (!content || inFlight.current) return;+ // Submit-time upload re-check: the disabled button is a frame behind, and+ // Cmd+Enter / Enter-on-title bypass the button entirely.+ if (o.uploadGate.isBlocked()) return;++ inFlight.current = true;+ setSubmitting(true);+ try {+ const accepted = await o.onSubmit(content);+ if (accepted) o.onAccepted?.();+ } catch {+ // A thrown send is a rejection: keep the draft, let the caller's+ // onSubmit surface its own error toast.+ } finally {+ inFlight.current = false;+ setSubmitting(false);+ }+ }, []);++ return { submitting, submit };+}diff --git a/packages/views/editor/use-coordinated-uploads.test.tsx b/packages/views/editor/use-coordinated-uploads.test.tsxnew file mode 100644index 0000000000..9ac61e63a6--- /dev/null+++ b/packages/views/editor/use-coordinated-uploads.test.tsx@@ -0,0 +1,96 @@+// @vitest-environment jsdom+import { useLayoutEffect, useMemo, useRef, type ReactNode } from "react";+import { describe, expect, it } from "vitest";+import { render } from "@testing-library/react";+import { I18nProvider } from "@multica/core/i18n/react";+import enCommon from "../locales/en/common.json";+import enEditor from "../locales/en/editor.json";+import type { ContentEditorRef } from "./content-editor";+import type { UploadGate } from "./use-upload-gate";+import {+ useCoordinatedUploads,+ __liveEditorRegistryKeysForTest,+ type UploadDraftBinding,+} from "./use-coordinated-uploads";++const TEST_RESOURCES = { en: { common: enCommon, editor: enEditor } };++const inertGate: UploadGate = {+ uploading: false,+ onUploadingChange: () => {},+ isBlocked: () => false,+};++function makeBinding(key: string): UploadDraftBinding {+ return {+ registryKey: key,+ getUploads: () => [],+ addUpload: () => {},+ settleUpload: () => {},+ failUpload: () => {},+ removeUpload: () => {},+ getBody: () => "",+ appendToBody: () => {},+ };+}++function HookHost({ registryKey }: { registryKey: string }) {+ const editorRef = useRef<ContentEditorRef | null>(null);+ const binding = useMemo(() => makeBinding(registryKey), [registryKey]);+ useCoordinatedUploads(binding, [], {}, inertGate, editorRef);+ return null;+}++/**+ * Captures the registry from a PARENT layout effect: layout effects run+ * child-first within a commit, so at capture time the hook's registration for+ * this commit must already be visible. A passive registration would not be —+ * it flushes a task later, which is exactly the settle window where a+ * write-back for the old key can insert into an editor already holding the+ * new draft's document (chat's pinned-switch adopts in layout).+ */+function CaptureAfterCommit({+ registryKey,+ capture,+ children,+}: {+ registryKey: string;+ capture: (keys: string[]) => void;+ children: ReactNode;+}) {+ useLayoutEffect(() => {+ capture(__liveEditorRegistryKeysForTest());+ }, [registryKey, capture]);+ return <>{children}</>;+}++function Probe({ registryKey, capture }: { registryKey: string; capture: (keys: string[]) => void }) {+ return (+ <I18nProvider locale="en" resources={TEST_RESOURCES}>+ <CaptureAfterCommit registryKey={registryKey} capture={capture}>+ <HookHost registryKey={registryKey} />+ </CaptureAfterCommit>+ </I18nProvider>+ );+}++describe("useCoordinatedUploads live-editor registry timing", () => {+ it("registers within the commit (layout), so a key switch is visible before any task runs", () => {+ const captures: string[][] = [];+ const capture = (keys: string[]) => captures.push(keys);++ const view = render(<Probe registryKey="probe:a" capture={capture} />);+ expect(captures.at(-1)).toContain("probe:a");++ view.rerender(<Probe registryKey="probe:b" capture={capture} />);++ // At the parent's layout effect of the SWITCH commit, the registry must+ // already point at the new key and no longer at the old one. A passive+ // registration fails both assertions here.+ expect(captures.at(-1)).toContain("probe:b");+ expect(captures.at(-1)).not.toContain("probe:a");++ view.unmount();+ expect(__liveEditorRegistryKeysForTest()).not.toContain("probe:b");+ });+});diff --git a/packages/views/editor/use-coordinated-uploads.ts b/packages/views/editor/use-coordinated-uploads.tsnew file mode 100644index 0000000000..eeefc88c40--- /dev/null+++ b/packages/views/editor/use-coordinated-uploads.ts@@ -0,0 +1,391 @@+"use client";++/**+ * The coordinated-upload engine shared by every composer surface (MUL-5181, L2).+ *+ * Ownership inversion: an upload is owned by the module-level upload+ * coordinator (`@multica/core/drafts`), not by the React component that+ * started it. On file pick the engine writes a persisted placeholder into the+ * surface's draft IMMEDIATELY (through the {@link UploadDraftBinding}), then+ * hands the file to the coordinator. Closing or scrolling the composer away no+ * longer aborts the upload; logout aborts every tracked request; a placeholder+ * still `uploading` at load time is coerced to `interrupted` by the store.+ *+ * `onSettled` is generation-guarded: it re-reads the draft and only writes if+ * the placeholder is still tracked (the draft may have been submitted or+ * cleared while the request was in flight). The coordinator never calls+ * `onSettled` on abort, so logout — abort first, then clear drafts — cannot+ * resurrect a placeholder into a wiped draft.+ *+ * The SOURCE OF TRUTH for what a submit binds is the draft BODY+ * (reference-filtered): an upload that settles after its mount died gets its+ * markdown link delivered back into the body — into the reopened composer's+ * live editor when one exists (confirmed, with retry while the Tiptap instance+ * is still warming up), else appended to the persisted draft — so the file is+ * visible, deletable, and deleting it really unbinds it.+ *+ * A surface plugs in with a {@link UploadDraftBinding}: imperative, store-backed+ * accessors that must remain callable after the component unmounts. Bindings+ * MUST be referentially stable per target (memoize on the draft key).+ */++import {+ useCallback,+ useLayoutEffect,+ useMemo,+ useRef,+ useState,+ type RefObject,+} from "react";+import { toast } from "sonner";+import { api } from "@multica/core/api";+import {+ startUpload,+ abortUpload,+ hasUploadingDraft,+ attachmentToDraftUpload,+ type DraftUpload,+} from "@multica/core/drafts";+import { createSafeId } from "@multica/core/utils";+import { contentReferencesAttachment, type Attachment } from "@multica/core/types";+import {+ toUploadResult,+ type UploadContext,+ type UploadResult,+} from "@multica/core/hooks/use-file-upload";+import { MAX_FILE_SIZE } from "@multica/core/constants/upload";+import { useT } from "../i18n";+import type { UploadGate } from "./use-upload-gate";+import type { ContentEditorRef } from "./content-editor";++const EMPTY_ATTACHMENTS: Attachment[] = [];++/**+ * Store-backed accessors for one composer target's uploads and body. Every+ * method must go through the store's `getState()` (never captured React+ * state): settle handlers call them after the owning component is gone.+ */+export interface UploadDraftBinding {+ /**+ * Identity for the live-editor registry — unique per composer target+ * (e.g. `comment:new:{issueId}`, `issue-create:manual`). A reopened+ * composer for the same target registers its editor under the same key,+ * which is how a settle handler finds it.+ */+ registryKey: string;+ getUploads: () => DraftUpload[];+ addUpload: (upload: DraftUpload) => void;+ settleUpload: (clientUploadId: string, attachment: Attachment) => void;+ failUpload: (clientUploadId: string, error?: string) => void;+ removeUpload: (clientUploadId: string) => void;+ /** The draft body reference-filtering binds against at submit time. */+ getBody: () => string;+ /** Append a markdown fragment to the persisted body. */+ appendToBody: (markdown: string) => void;+}++// The editor currently showing each registry key. Lets a settle handler whose+// own mount is gone (the upload outlived the composer) hand the finished link+// to the editor a REOPENED composer mounted for the same target.+const liveEditors = new Map<string, RefObject<ContentEditorRef | null>>();++/** Test-only: registry keys currently registered. Lets timing tests assert+ * registration is part of the COMMIT (layout), not a passive task later. */+export function __liveEditorRegistryKeysForTest(): string[] {+ return [...liveEditors.keys()];+}++/** Markdown for a finished upload. Mirrors the shape the in-editor swap+ * produces (`extensions/file-upload.ts`: image node for images, fileCard link+ * for everything else) — keep the two in sync. */+export function attachmentMarkdown(att: Attachment): string {+ const link = toUploadResult(att).markdownLink;+ return (att.content_type ?? "").startsWith("image/")+ ? ``+ : `[${att.filename}](${link})`;+}++const DELIVER_RETRY_MS = 50;+const DELIVER_MAX_TRIES = 100; // ~5s — editor init is a passive effect away++/**+ * Land a finished upload's markdown link in the draft BODY after the mount+ * that owned the upload died. Delivery must be CONFIRMED, not assumed:+ *+ * - live editor for the key, insert landed → also persist the same body via+ * `appendToBody` as insurance — the editor's debounced emit is dropped on a+ * quick unmount, and it converges to identical content anyway.+ * - no composer mounted for the key → append to the persisted draft; the next+ * mount reads it as `defaultValue`.+ * - composer mounted but its Tiptap instance not created yet (the handle+ * exists from first commit; the instance arrives in a passive effect) →+ * RETRY. Appending to the store here would be erased by the mounted+ * editor's first emit, which snapshots a body without the link.+ *+ * Every attempt re-checks the generation guard (draft may be cleared or+ * submitted while waiting) and the body (the link may have landed some other+ * way) before writing.+ */+function deliverFinishedUpload(+ binding: UploadDraftBinding,+ clientUploadId: string,+ attachment: Attachment,+ tries = 0,+): void {+ if (!binding.getUploads().some((u) => u.clientUploadId === clientUploadId)) return;+ if (contentReferencesAttachment(binding.getBody(), attachment)) return;++ const md = attachmentMarkdown(attachment);+ const live = liveEditors.get(binding.registryKey);+ if (live?.current?.insertMarkdownAtEnd(md) === true) {+ binding.appendToBody(md);+ return;+ }+ if (!live) {+ binding.appendToBody(md);+ return;+ }+ if (tries >= DELIVER_MAX_TRIES) {+ // Editor never initialized — persist to the store as the least-bad option.+ binding.appendToBody(md);+ return;+ }+ setTimeout(+ () => deliverFinishedUpload(binding, clientUploadId, attachment, tries + 1),+ DELIVER_RETRY_MS,+ );+}++export interface CoordinatedUploads {+ /** Every upload for this composer (placeholders included) — for status chips. */+ uploads: DraftUpload[];+ /** Completed attachment rows — the editor preview set; submit binds the+ * subset whose link the body still references. */+ attachments: Attachment[];+ /** Wire to `<ContentEditor onUploadFile={...} />`. */+ handleUpload: (file: File) => Promise<UploadResult | null>;+ /** Drop a placeholder (dismiss a failure / interrupted). */+ removeUpload: (clientUploadId: string) => void;+ /**+ * The submit gate for this composer. Combines the editor gate (this mount's+ * in-document uploads) with the coordinator-owned placeholders in the draft:+ * a composer reopened while a previous mount's upload is still in flight has+ * a clean editor document, so the editor gate alone would let a send clear+ * the draft out from under the settling upload — silently dropping the file+ * whose "uploading" chip is on screen.+ */+ gate: UploadGate;+}++/**+ * @param binding Store-backed accessors for the persisted target. When+ * absent (a composer with no persistence context) uploads+ * fall back to component-local state and die with the+ * mount, matching pre-L2 behavior.+ * @param boundUploads The binding's uploads as a REACTIVE value (the caller's+ * store subscription). Ignored when `binding` is absent.+ */+export function useCoordinatedUploads(+ binding: UploadDraftBinding | undefined,+ boundUploads: DraftUpload[],+ ctx: UploadContext,+ editorGate: UploadGate,+ editorRef: RefObject<ContentEditorRef | null>,+ opts?: {+ /**+ * Resolve the binding a NEW upload should target, snapshotted at pick+ * time. For composers whose single editor instance can hold a DIFFERENT+ * draft than the selected one (chat pins the document while an upload is+ * in flight): the file lands in the document the editor is HOLDING, so+ * its placeholder/settle/write-back must follow that draft, not whatever+ * is selected by the time the request finishes. Defaults to `binding`.+ */+ resolveUploadTarget?: () => UploadDraftBinding;+ /**+ * Registry key to register this mount's editor under, when it differs+ * from `binding.registryKey`. Same divergence as above: a write-back must+ * insert into the editor only if its DOCUMENT belongs to the settling+ * draft, so composers with a pinnable editor register the LOADED key.+ */+ liveRegistryKey?: string;+ },+): CoordinatedUploads {+ const { t } = useT("editor");+ const [localUploads, setLocalUploads] = useState<DraftUpload[]>([]);+ // Latest-value ref: handleUpload snapshots the target at invocation time.+ const resolveUploadTargetRef = useRef(opts?.resolveUploadTarget);+ resolveUploadTargetRef.current = opts?.resolveUploadTarget;++ // Liveness of THIS mount, read by settle closures it created: while true,+ // the editor that started the upload will do the inline swap itself; once+ // false, the write-back is the only path that lands the link. Layout effect+ // on purpose: React nulls the child editor's ref during the unmount commit,+ // but a passive cleanup flips this a task later — a settle landing in that+ // gap would see "mounted" with no editor left to swap.+ const mountedRef = useRef(true);+ useLayoutEffect(() => {+ mountedRef.current = true;+ return () => {+ mountedRef.current = false;+ };+ }, []);++ // Registration only exists for a persisted target; a liveRegistryKey with+ // no binding would register an editor nothing can ever look up.+ const registryKey = binding ? (opts?.liveRegistryKey ?? binding.registryKey) : undefined;+ // Layout effect for the same reason as mountedRef: chat's adopt swaps the+ // editor's document (and its loaded key) synchronously during commit, and a+ // passive re-registration one task later leaves a settle window where the+ // old key still maps to an editor now holding another draft's document.+ useLayoutEffect(() => {+ if (!registryKey) return;+ liveEditors.set(registryKey, editorRef);+ return () => {+ if (liveEditors.get(registryKey) === editorRef) liveEditors.delete(registryKey);+ };+ }, [registryKey, editorRef]);++ const uploads = binding ? boundUploads : localUploads;+ const attachments = useMemo(() => {+ const done: Attachment[] = [];+ for (const u of uploads) {+ if (u.status === "uploaded") done.push(u.attachment);+ }+ return done.length === 0 ? EMPTY_ATTACHMENTS : done;+ }, [uploads]);++ const issueId = ctx.issueId;+ const commentId = ctx.commentId;+ const chatSessionId = ctx.chatSessionId;++ const handleUpload = useCallback(+ (file: File): Promise<UploadResult | null> => {+ const clientUploadId = createSafeId();+ // Snapshot the target NOW: settle handlers must keep addressing the+ // draft the file landed in, no matter what is selected when they fire.+ const target = binding ? (resolveUploadTargetRef.current?.() ?? binding) : undefined;+ const placeholder: DraftUpload = {+ clientUploadId,+ status: "uploading",+ filename: file.name,+ size: file.size,+ contentType: file.type || undefined,+ };++ if (file.size > MAX_FILE_SIZE) {+ // Never enters the coordinator — surface it as a failed placeholder so+ // the composer shows the reason instead of silently dropping the file.+ const reason = "File exceeds 100 MB limit";+ if (target) {+ target.addUpload(placeholder);+ target.failUpload(clientUploadId, reason);+ } else {+ setLocalUploads((prev) => [+ ...prev,+ { clientUploadId, status: "failed", filename: file.name, size: file.size, error: reason },+ ]);+ }+ toast.error(t(($) => $.upload.failed, { filename: file.name, reason }));+ return Promise.resolve(null);+ }++ if (target) {+ target.addUpload(placeholder);+ } else {+ setLocalUploads((prev) => [...prev, placeholder]);+ }++ return new Promise<UploadResult | null>((resolve) => {+ startUpload({+ clientUploadId,+ file,+ api,+ ctx: { issueId, commentId, chatSessionId },+ onSettled: (outcome) => {+ if (outcome.status === "uploaded") {+ if (target) {+ // Generation guard: only write if the draft still tracks it.+ if (target.getUploads().some((u) => u.clientUploadId === clientUploadId)) {+ target.settleUpload(clientUploadId, outcome.attachment);+ // Write-back (MUL-5181): the mount that started this upload+ // is gone, so no editor swap will put the finished link into+ // the document — deliver it into the BODY instead (that is+ // what submit binds, reference-filtered). Skipped while this+ // mount is alive: resolving the promise below drives the+ // normal inline blob→URL swap, and a placeholder the user+ // deleted mid-upload must stay deleted.+ if (!mountedRef.current) {+ deliverFinishedUpload(target, clientUploadId, outcome.attachment);+ }+ }+ } else {+ setLocalUploads((prev) =>+ prev.map((u) =>+ u.clientUploadId === clientUploadId+ ? { ...attachmentToDraftUpload(outcome.attachment), clientUploadId }+ : u,+ ),+ );+ }+ resolve(toUploadResult(outcome.attachment));+ } else {+ const reason = outcome.error.message;+ if (target) {+ if (target.getUploads().some((u) => u.clientUploadId === clientUploadId)) {+ target.failUpload(clientUploadId, reason);+ }+ } else {+ setLocalUploads((prev) =>+ prev.map((u) =>+ u.clientUploadId === clientUploadId+ ? { clientUploadId, status: "failed", filename: file.name, size: file.size, error: reason }+ : u,+ ),+ );+ }+ toast.error(t(($) => $.upload.failed, { filename: file.name, reason }));+ resolve(null);+ }+ },+ });+ });+ },+ [binding, issueId, commentId, chatSessionId, t],+ );++ const removeUpload = useCallback(+ (clientUploadId: string) => {+ // Defensive cancel for a placeholder removed while still in flight: its+ // request has no destination left, so don't let it run to completion.+ // Today's chips expose ✕ only for failed/interrupted entries, so this+ // fires only if a future caller removes an `uploading` one. Guarded on+ // OUR tracking so a stray id can never abort another surface's upload.+ const tracked = binding ? binding.getUploads() : localUploadsRef.current;+ if (tracked.some((u) => u.clientUploadId === clientUploadId && u.status === "uploading")) {+ abortUpload(clientUploadId);+ }+ if (binding) binding.removeUpload(clientUploadId);+ else setLocalUploads((prev) => prev.filter((u) => u.clientUploadId !== clientUploadId));+ },+ [binding],+ );++ // Submit-time truth for the local (non-persisted) path: a deliberate+ // latest-value ref written during render, because `isBlocked` must read the+ // value at invocation time, not at the render the callback captured. The+ // persisted path reads the store through the binding.+ const localUploadsRef = useRef(localUploads);+ localUploadsRef.current = localUploads;++ // Rebuilt every render on purpose (editorGate itself is a fresh object per+ // render): consumers read it through refs/props, never by identity.+ const gate: UploadGate = {+ uploading: editorGate.uploading || hasUploadingDraft(uploads),+ onUploadingChange: editorGate.onUploadingChange,+ isBlocked: () =>+ editorGate.isBlocked() ||+ hasUploadingDraft(binding ? binding.getUploads() : localUploadsRef.current),+ };++ return { uploads, attachments, handleUpload, removeUpload, gate };+}diff --git a/packages/views/inbox/components/inbox-page.tsx b/packages/views/inbox/components/inbox-page.tsxindex 081d0df048..6921f2cac6 100644--- a/packages/views/inbox/components/inbox-page.tsx+++ b/packages/views/inbox/components/inbox-page.tsx@@ -481,7 +481,7 @@ export function InboxPage() {// candidate (still editable).const prompt = selected.details?.original_prompt ?? "";const agentId = selected.details?.agent_id;- useIssueDraftStore.getState().setDraft({+ useIssueDraftStore.getState().setManual({description: prompt,...(agentId? { assigneeType: "agent" as const, assigneeId: agentId }diff --git a/packages/views/issues/components/comment-card-edit-gate.test.tsx b/packages/views/issues/components/comment-card-edit-gate.test.tsxindex cbe7b2a868..fd612f6b98 100644--- a/packages/views/issues/components/comment-card-edit-gate.test.tsx+++ b/packages/views/issues/components/comment-card-edit-gate.test.tsx@@ -2,18 +2,20 @@ import { describe, it, expect, vi, beforeEach } from "vitest";import { act, fireEvent, screen, waitFor } from "@testing-library/react";import { forwardRef, useEffect, useImperativeHandle, useRef, type ReactNode, type Ref } from "react";import { QueryClient, QueryClientProvider } from "@tanstack/react-query";-import type { TimelineEntry } from "@multica/core/types";+import type { Attachment, TimelineEntry } from "@multica/core/types";import type { UploadResult } from "@multica/core/hooks/use-file-upload";import { useCommentDraftStore } from "@multica/core/issues/stores";import { renderWithI18n } from "../../test/i18n";+const apiUploadFile = vi.hoisted(() => vi.fn());const uploadWithToast = vi.hoisted(() => vi.fn());const editorDefaultValues = vi.hoisted(() => ({values: [] as Array<string | undefined>,}));vi.mock("@multica/core/api", () => ({- api: {},+ // Uploads flow through the coordinator, which calls api.uploadFile (MUL-5181).+ api: { uploadFile: apiUploadFile },dispatchReasonCode: () => undefined,}));@@ -48,6 +50,11 @@ vi.mock("../../editor", async () => ({...(await vi.importActual<typeof import("../../editor/use-lazy-editor")>("../../editor/use-lazy-editor",)),+ // Real await-then-render submit contract (pure React) — the edit save path+ // now delegates to it.+ ...(await vi.importActual<typeof import("../../editor/use-composer-submit")>(+ "../../editor/use-composer-submit",+ )),useEditorUpload: () => ({ uploadWithToast, upload: vi.fn(), uploading: false }),useFileDropZone: () => ({ isDragOver: false, dropZoneProps: {} }),FileDropOverlay: () => null,@@ -172,6 +179,7 @@ function getSaveButton() {beforeEach(() => {uploadWithToast.mockReset();+ apiUploadFile.mockReset();useCommentDraftStore.setState({ drafts: {} });editorDefaultValues.values = [];});@@ -198,16 +206,16 @@ describe("comment edit — draft snapshot", () => {// edit with the pending image stripped out of the body and its id unbound.describe("comment edit — upload submit gate", () => {function startPendingUpload(container: HTMLElement) {- let release!: (result: UploadResult | null) => void;- uploadWithToast.mockImplementationOnce(- () => new Promise<UploadResult | null>((resolve) => { release = resolve; }),+ let resolveUpload!: (att: Attachment) => void;+ apiUploadFile.mockImplementationOnce(+ () => new Promise<Attachment>((resolve) => { resolveUpload = resolve; }),);const input = container.querySelector('input[type="file"]');if (!input) throw new Error("Expected a file input to render");fireEvent.change(input, {target: { files: [new File(["x"], "shot.png", { type: "image/png" })] },});- return { release: (result: UploadResult | null) => release(result) };+ return { resolve: (att: Attachment) => resolveUpload(att) };}it("disables Save while an upload is in flight and re-enables once it settles", async () => {@@ -221,13 +229,15 @@ describe("comment edit — upload submit gate", () => {expect(getSaveButton()).toHaveAttribute("aria-busy", "true");await act(async () => {- pending.release({+ pending.resolve({id: "att-1",url: "https://cdn.example/att-1.png",+ download_url: "https://cdn.example/att-1.png",+ markdown_url: "https://cdn.example/att-1.png",filename: "shot.png",- link: "https://cdn.example/att-1.png",- markdownLink: "https://cdn.example/att-1.png",- } as unknown as UploadResult);+ content_type: "image/png",+ size_bytes: 1,+ } as unknown as Attachment);});await waitFor(() => expect(getSaveButton()).not.toBeDisabled());diff --git a/packages/views/issues/components/comment-card.tsx b/packages/views/issues/components/comment-card.tsxindex e2d0419120..8e2306c5b5 100644--- a/packages/views/issues/components/comment-card.tsx+++ b/packages/views/issues/components/comment-card.tsx@@ -29,7 +29,9 @@ import { cn } from "@multica/ui/lib/utils";import { copyText } from "@multica/ui/lib/clipboard";import { useActorName } from "@multica/core/workspace/hooks";import { useTimeAgo } from "../../i18n";-import { ContentEditor, type ContentEditorRef, ReadonlyContent, useFileDropZone, FileDropOverlay, Attachment as AttachmentRenderer, AttachmentDownloadProvider, useUploadGate, useEditorUpload } from "../../editor";+import { ContentEditor, type ContentEditorRef, ReadonlyContent, useFileDropZone, FileDropOverlay, Attachment as AttachmentRenderer, AttachmentDownloadProvider, useUploadGate, useComposerSubmit } from "../../editor";+import { useCommentUploads } from "./use-comment-uploads";+import { ComposerUploadChips } from "./composer-upload-chips";import { FileUploadButton } from "@multica/ui/components/common/file-upload-button";import { api, dispatchReasonCode } from "@multica/core/api";import { ReplyInput } from "./reply-input";@@ -322,19 +324,23 @@ function useEditAttachmentState() {const { t } = useT("issues");const { t: tEditor } = useT("editor");- const { uploadWithToast } = useEditorUpload();const [editing, setEditing] = useState(false);- const [saving, setSaving] = useState(false);const [initialValue, setInitialValue] = useState(entry.content ?? "");const editorRef = useRef<ContentEditorRef>(null);// Saving mid-upload would persist the edit without the file the user just// pasted in — same failure as posting a new comment.const uploadGate = useUploadGate(editorRef);const cancelledRef = useRef(false);- const savingRef = useRef(false);const [content, setContent] = useState(entry.content ?? "");const [suppressedAgentIds, setSuppressedAgentIds] = useState<Set<string>>(() => new Set());- const [pendingAttachments, setPendingAttachments] = useState<Attachment[]>([]);+ // Uploads for this edit session (MUL-5181) — coordinator-owned, persisted in+ // the draft store keyed by the edit draft so scroll-out/close no longer drops+ // an in-flight upload.+ const draftKey = `edit:${issueId}:${entry.id}` as const;+ // `gate` widens the editor gate with coordinator-owned placeholders — see+ // CommentInput.+ const { uploads, attachments: pendingAttachments, handleUpload, removeUpload, gate } =+ useCommentUploads(draftKey, { issueId }, uploadGate, editorRef);const [retainedStandaloneIds, setRetainedStandaloneIds] = useState<Set<string> | null>(null);const triggerPreview = useCommentTriggerPreview({issueId,@@ -347,12 +353,6 @@ function useEditAttachmentState(? [...(entry.attachments ?? []), ...pendingAttachments]: entry.attachments;- const handleUpload = useCallback(async (file: File) => {- const result = await uploadWithToast(file, { issueId });- if (result) setPendingAttachments((prev) => [...prev, result]);- return result;- }, [uploadWithToast, issueId]);-useEffect(() => {setSuppressedAgentIds(new Set());}, [issueId, entry.id, entry.parent_id]);@@ -362,7 +362,6 @@ function useEditAttachmentState(enabled: editing,});- const draftKey = `edit:${issueId}:${entry.id}` as const;const getDraft = useCommentDraftStore.getState().getDraft;const setDraft = useCommentDraftStore((s) => s.setDraft);const clearDraft = useCommentDraftStore((s) => s.clearDraft);@@ -392,8 +391,8 @@ function useEditAttachmentState(setEditing(false);setContent(entry.content ?? "");setSuppressedAgentIds(new Set());- setPendingAttachments([]);setRetainedStandaloneIds(null);+ // clearDraft drops both the edit text and its pending attachments.clearDraft(draftKey);};@@ -411,59 +410,93 @@ function useEditAttachmentState(resetState();};- const saveEdit = async () => {- if (cancelledRef.current || savingRef.current) return;- // Submit-time re-read — Cmd+Enter bypasses the Save button entirely.- if (uploadGate.isBlocked()) return;- const trimmed = editorRef.current- ?.getMarkdown()- ?.replace(/(\n\s*)+$/, "")- .trim();- if (!trimmed) return;- const activeIds = collectActiveAttachmentIds(- trimmed,- [...(entry.attachments ?? []), ...pendingAttachments],- retainedStandaloneIds,- );- const attachmentsChanged = !sameIdSet(activeIds, (entry.attachments ?? []).map((a) => a.id));- if (trimmed === (entry.content ?? "").trim() && !attachmentsChanged) {- resetState();- return;- }- const suppressAgentIds = triggerPreview.agents- .filter((agent) => suppressedAgentIds.has(agent.id))- .map((agent) => agent.id);- savingRef.current = true;- setSaving(true);- try {- await onEdit(- entry.id,+ // Await-then-render save (MUL-5181): shared submit contract, with the edit-+ // only concerns folded into onSubmit — the cancel-race guard, the no-op+ // short-circuit, and the failure toast. The hook owns the empty guard,+ // upload re-check, single-flight, and lock/spin via `submitting`.+ // Stale-submit guard (MUL-5181 P0) — see CommentInput. The edit hook lives+ // in CommentRow, so "unmounted" here means the issue detail closed.+ const editMountedRef = useRef(true);+ useEffect(() => {+ editMountedRef.current = true;+ return () => {+ editMountedRef.current = false;+ };+ }, []);+ const submittedEntryRef = useRef<unknown>(null);++ const { submitting: saving, submit: saveEdit } = useComposerSubmit({+ editorRef,+ uploadGate: gate,+ onSubmit: async (trimmed) => {+ // A save racing a just-pressed Cancel must never reach the server.+ if (cancelledRef.current) return false;+ // Flush pending debounce before snapshotting — see CommentInput.+ const pendingMd = editorRef.current?.flushPendingUpdate?.();+ if (pendingMd != null) setDraft(draftKey, pendingMd);+ submittedEntryRef.current = useCommentDraftStore.getState().drafts[draftKey];+ const activeIds = collectActiveAttachmentIds(trimmed,- activeIds,- suppressAgentIds.length > 0 ? suppressAgentIds : undefined,+ [...(entry.attachments ?? []), ...pendingAttachments],+ // Body-referenced + retained-standalone only (MUL-5181): an upload the+ // user removed from the body is really unbound. Close-surviving+ // uploads are written back into the body by the settle handler.+ retainedStandaloneIds,);+ const attachmentsChanged = !sameIdSet(activeIds, (entry.attachments ?? []).map((a) => a.id));+ // Nothing changed — close the editor without a write. Accepted, so+ // onAccepted resets the edit state.+ if (trimmed === (entry.content ?? "").trim() && !attachmentsChanged) {+ return true;+ }+ const suppressAgentIds = triggerPreview.agents+ .filter((agent) => suppressedAgentIds.has(agent.id))+ .map((agent) => agent.id);+ try {+ await onEdit(+ entry.id,+ trimmed,+ activeIds,+ suppressAgentIds.length > 0 ? suppressAgentIds : undefined,+ );+ return true;+ } catch (err) {+ toast.error(+ err instanceof Error && err.message+ ? err.message+ : t(($) => $.comment.update_failed),+ );+ return false;+ }+ },+ onAccepted: () => {+ // Success may only consume the entry it submitted: edits made during the+ // save survive, and the editor then STAYS in edit mode on them.+ const lateMd = editorRef.current?.flushPendingUpdate?.();+ if (lateMd != null) setDraft(draftKey, lateMd);+ const store = useCommentDraftStore.getState();+ const live = store.drafts[draftKey];+ const untouched = live === undefined || live === submittedEntryRef.current;+ if (!editMountedRef.current) {+ if (untouched) store.clearDraft(draftKey);+ return;+ }+ if (!untouched) return;resetState();- } catch (err) {- toast.error(- err instanceof Error && err.message- ? err.message- : t(($) => $.comment.update_failed),- );- } finally {- savingRef.current = false;- setSaving(false);- }- };+ },+ });return {editing,saving,- uploading: uploadGate.uploading,- onUploadingChange: uploadGate.onUploadingChange,+ uploading: gate.uploading,+ onUploadingChange: gate.onUploadingChange,uploadingLabel: tEditor(($) => $.upload.in_progress),editorRef,editorAttachments,handleUpload,+ uploads,+ removeUpload,isDragOver,dropZoneProps,triggerPreview,@@ -659,6 +692,9 @@ function CommentRow({}/>)}+ {edit.uploads.some((u) => u.status !== "uploaded") && (+ <ComposerUploadChips uploads={edit.uploads} onRemove={edit.removeUpload} className="mt-2 max-w-full" />+ )}<div className="flex items-center justify-between gap-2 mt-2"><div className="min-w-0 flex-1"><CommentTriggerChips@@ -970,6 +1006,9 @@ function CommentCardImpl({}/>)}+ {edit.uploads.some((u) => u.status !== "uploaded") && (+ <ComposerUploadChips uploads={edit.uploads} onRemove={edit.removeUpload} className="max-w-full" />+ )}<CommentTriggerChipsagents={edit.triggerPreview.agents}blocked={edit.triggerPreview.blocked}diff --git a/packages/views/issues/components/comment-composers.test.tsx b/packages/views/issues/components/comment-composers.test.tsxindex d74ed2a97c..682d127d4b 100644--- a/packages/views/issues/components/comment-composers.test.tsx+++ b/packages/views/issues/components/comment-composers.test.tsx@@ -3,21 +3,34 @@ import { QueryClient, QueryClientProvider } from "@tanstack/react-query";import { describe, it, expect, vi, beforeEach } from "vitest";import { act, fireEvent, screen, waitFor } from "@testing-library/react";import type { UploadResult } from "@multica/core/hooks/use-file-upload";+import type { Attachment } from "@multica/core/types";import { useCommentComposerStore, useCommentDraftStore } from "@multica/core/issues/stores";import { renderWithI18n } from "../../test/i18n";import { CommentInput } from "./comment-input";import { ReplyInput } from "./reply-input";+// Uploads now flow through the module-level coordinator, which calls+// `api.uploadFile(file, ctx, signal)` (MUL-5181). Tests drive uploads by+// mocking that call directly rather than the old `uploadWithToast` hook.+const apiUploadFile = vi.hoisted(() => vi.fn());const uploadWithToast = vi.hoisted(() => vi.fn());const editorDefaultValues = vi.hoisted(() => ({values: [] as Array<string | undefined>,}));+// Observability + failure control for the write-back insert path (MUL-5181):+// `insertMarkdownAtEnd` returns false while the (simulated) Tiptap instance+// doesn't exist yet, exactly like the real handle.+const insertMarkdownSpy = vi.hoisted(() => vi.fn());+const insertMarkdownBehavior = vi.hoisted(() => ({ succeed: true }));vi.mock("@multica/core/api", () => ({- api: {},+ api: { uploadFile: apiUploadFile },}));-vi.mock("@multica/core/hooks/use-file-upload", () => ({+vi.mock("@multica/core/hooks/use-file-upload", async () => ({+ ...(await vi.importActual<typeof import("@multica/core/hooks/use-file-upload")>(+ "@multica/core/hooks/use-file-upload",+ )),useFileUpload: () => ({ uploadWithToast }),}));@@ -40,6 +53,11 @@ vi.mock("../../editor", async () => ({...(await vi.importActual<typeof import("../../editor/use-upload-gate")>("../../editor/use-upload-gate",)),+ // Real await-then-render submit contract (pure React) — the composers now+ // delegate their send handler to it.+ ...(await vi.importActual<typeof import("../../editor/use-composer-submit")>(+ "../../editor/use-composer-submit",+ )),useEditorUpload: () => ({ uploadWithToast, upload: vi.fn(), uploading: false }),useFileDropZone: () => ({isDragOver: false,@@ -72,9 +90,16 @@ vi.mock("../../editor", async () => ({// from before the await until the upload settles, `hasActiveUploads` reads// it synchronously, and the host is told through onUploadingChange.const inFlightRef = useRef(0);+ // Mirrors `editor.isDestroyed`: a settle continuation after unmount must+ // not write the document or emit onUpdate (uploadAndInsertFile guards on+ // isDestroyed in production).+ const destroyedRef = useRef(false);useEffect(() => {onReady?.();+ return () => {+ destroyedRef.current = true;+ };// eslint-disable-next-line react-hooks/exhaustive-deps}, []);@@ -91,15 +116,22 @@ vi.mock("../../editor", async () => ({if (inFlightRef.current === 1) onUploadingChange?.(true);try {const result = await onUploadFile?.(file);- if (!result) return;+ if (!result || destroyedRef.current) return;valueRef.current = `${valueRef.current}\n${result.url}`.trim();onUpdate?.(valueRef.current);} finally {inFlightRef.current -= 1;- if (inFlightRef.current === 0) onUploadingChange?.(false);+ if (inFlightRef.current === 0 && !destroyedRef.current) onUploadingChange?.(false);}},hasActiveUploads: () => inFlightRef.current > 0,+ insertMarkdownAtEnd: (md: string) => {+ insertMarkdownSpy(md);+ if (destroyedRef.current || !insertMarkdownBehavior.succeed) return false;+ valueRef.current = `${valueRef.current}\n\n${md}`.trim();+ onUpdate?.(valueRef.current);+ return true;+ },}));return (@@ -177,6 +209,9 @@ function getSubmitButton(container: HTMLElement): HTMLButtonElement {beforeEach(() => {uploadWithToast.mockReset();+ apiUploadFile.mockReset();+ insertMarkdownSpy.mockReset();+ insertMarkdownBehavior.succeed = true;localStorage.clear();useCommentComposerStore.setState({ sticky: true });// The draft store is a module singleton — a draft left by a previous test@@ -311,6 +346,102 @@ describe("comment composers", () => {expect(screen.getByTestId("editor").closest("[aria-busy]")).toBeNull();});+ // Regression: the tab-switch flush re-writes IDENTICAL content mid-flight;+ // that must not read as "edited during the request" — the posted comment's+ // draft still clears (it previously resurrected with Send re-enabled).+ it("a tab switch during the send does not resurrect the posted draft", async () => {+ let resolveSubmit!: (v: boolean) => void;+ const onSubmit = vi.fn(() => new Promise<boolean>((r) => { resolveSubmit = r; }));+ renderCommentInput(onSubmit);+ activateComposer("comment-composer-shell");+ fireEvent.change(screen.getByTestId("editor"), { target: { value: "draft A" } });+ fireEvent.keyDown(screen.getByTestId("editor"), { key: "Enter", metaKey: true });+ await waitFor(() => expect(onSubmit).toHaveBeenCalled());++ // Backgrounding the tab fires the visibility flush with unchanged content.+ Object.defineProperty(document, "visibilityState", {+ configurable: true,+ get: () => "hidden",+ });+ fireEvent(document, new Event("visibilitychange"));++ await act(async () => {+ resolveSubmit(true);+ await Promise.resolve();+ });++ expect(useCommentDraftStore.getState().getDraft("new:issue-1")).toBeUndefined();++ Object.defineProperty(document, "visibilityState", {+ configurable: true,+ get: () => "visible",+ });+ });++ // MUL-5181 P0: the editor stays interactive during a send — text typed+ // while draft A is in flight must survive A's success, in store AND editor.+ it("text typed while a comment send is in flight survives the success", async () => {+ let resolveSubmit!: (v: boolean) => void;+ const onSubmit = vi.fn(() => new Promise<boolean>((r) => { resolveSubmit = r; }));+ renderCommentInput(onSubmit);+ activateComposer("comment-composer-shell");+ const editor = screen.getByTestId("editor");+ fireEvent.change(editor, { target: { value: "draft A" } });+ fireEvent.keyDown(editor, { key: "Enter", metaKey: true });+ await waitFor(() => expect(onSubmit).toHaveBeenCalled());++ // Still mounted, still typing while the request is in flight.+ fireEvent.change(editor, { target: { value: "draft A plus more" } });++ await act(async () => {+ resolveSubmit(true);+ await Promise.resolve();+ });++ expect(useCommentDraftStore.getState().getDraft("new:issue-1")).toBe("draft A plus more");+ });++ // MUL-5181 P0: a submit that outlives its composer may only clear the draft+ // it submitted — never one typed after the composer unmounted and reopened.+ it("a late comment success does NOT clear a draft typed after unmount", async () => {+ let resolveSubmit!: (v: boolean) => void;+ const onSubmit = vi.fn(() => new Promise<boolean>((r) => { resolveSubmit = r; }));+ const view = renderCommentInput(onSubmit);+ activateComposer("comment-composer-shell");+ fireEvent.change(screen.getByTestId("editor"), { target: { value: "draft A" } });+ fireEvent.keyDown(screen.getByTestId("editor"), { key: "Enter", metaKey: true });+ await waitFor(() => expect(onSubmit).toHaveBeenCalled());++ view.unmount();+ // A reopened composer typed draft B under the same key.+ useCommentDraftStore.getState().setDraft("new:issue-1", "draft B");++ await act(async () => {+ resolveSubmit(true);+ await Promise.resolve();+ });++ expect(useCommentDraftStore.getState().getDraft("new:issue-1")).toBe("draft B");+ });++ it("a late comment success still clears an untouched draft", async () => {+ let resolveSubmit!: (v: boolean) => void;+ const onSubmit = vi.fn(() => new Promise<boolean>((r) => { resolveSubmit = r; }));+ const view = renderCommentInput(onSubmit);+ activateComposer("comment-composer-shell");+ fireEvent.change(screen.getByTestId("editor"), { target: { value: "draft A" } });+ fireEvent.keyDown(screen.getByTestId("editor"), { key: "Enter", metaKey: true });+ await waitFor(() => expect(onSubmit).toHaveBeenCalled());++ view.unmount();+ await act(async () => {+ resolveSubmit(true);+ await Promise.resolve();+ });++ expect(useCommentDraftStore.getState().getDraft("new:issue-1")).toBeUndefined();+ });+it("keeps the draft when the send fails (no optimistic clear)", async () => {const onSubmit = vi.fn().mockResolvedValue(false);const { container } = renderCommentInput(onSubmit);@@ -328,11 +459,31 @@ describe("comment composers", () => {// MUL-4808 — posting mid-upload strips the pending image's blob URL out of the// body and binds no attachment id, so the comment lands without the file.describe("comment composers — upload submit gate", () => {- /** Start an upload that stays in flight until the returned resolver runs. */+ const uploadAttachment = (id: string, url: string) =>+ ({+ id,+ url,+ download_url: url,+ markdown_url: url,+ filename: `${id}.png`,+ content_type: "image/png",+ size_bytes: 1,+ }) as unknown as Attachment;++ /**+ * Start an upload that stays in flight until the returned resolver runs. The+ * coordinator calls `api.uploadFile`, so this controls THAT promise: resolve+ * it with an attachment (success) or reject it (failure).+ */function startPendingUpload(container: HTMLElement, filename = "slow.png") {- let release!: (result: UploadResult | null) => void;- uploadWithToast.mockImplementationOnce(- () => new Promise<UploadResult | null>((resolve) => { release = resolve; }),+ let resolveUpload!: (att: Attachment) => void;+ let rejectUpload!: (err: Error) => void;+ apiUploadFile.mockImplementationOnce(+ () =>+ new Promise<Attachment>((resolve, reject) => {+ resolveUpload = resolve;+ rejectUpload = reject;+ }),);// FileUploadButton's visible control is a button that clicks a hidden// input; the input is what carries the selection.@@ -341,12 +492,12 @@ describe("comment composers — upload submit gate", () => {fireEvent.change(input, {target: { files: [new File(["x"], filename, { type: "image/png" })] },});- return { release: (result: UploadResult | null) => release(result) };+ return {+ resolve: (att: Attachment) => resolveUpload(att),+ fail: () => rejectUpload(new Error("upload failed")),+ };}- const uploadResult = (id: string, url: string) =>- ({ id, url, filename: `${id}.png`, link: url, markdownLink: url }) as unknown as UploadResult;-it("disables send while an upload is in flight and re-enables once it settles", async () => {const { container } = renderCommentInput();activateComposer("comment-composer-shell");@@ -359,7 +510,7 @@ describe("comment composers — upload submit gate", () => {expect(getSubmitButton(container)).toHaveAttribute("aria-busy", "true");await act(async () => {- pending.release(uploadResult("att-1", "https://cdn.example/att-1.png"));+ pending.resolve(uploadAttachment("att-1", "https://cdn.example/att-1.png"));});await waitFor(() => expect(getSubmitButton(container)).not.toBeDisabled());@@ -382,13 +533,55 @@ describe("comment composers — upload submit gate", () => {expect(onSubmit).not.toHaveBeenCalled();await act(async () => {- pending.release(uploadResult("att-1", "https://cdn.example/att-1.png"));+ pending.resolve(uploadAttachment("att-1", "https://cdn.example/att-1.png"));});fireEvent.keyDown(editor, { key: "Enter", metaKey: true });await waitFor(() => expect(onSubmit).toHaveBeenCalled());});+ it("blocks send while a coordinator upload from a PREVIOUS mount is still in flight", async () => {+ // Reopened-composer scenario: the upload placeholder lives in the draft+ // store (coordinator-owned), but this mount's editor is clean — the editor+ // gate alone sees no active uploads. Sending here would clear the draft+ // out from under the settling upload and silently drop the file.+ useCommentDraftStore.getState().setDraft("new:issue-1", "recovered draft");+ useCommentDraftStore.getState().addUpload("new:issue-1", {+ clientUploadId: "prev-mount-upload",+ status: "uploading",+ filename: "shot.png",+ size: 10,+ });++ const { container, onSubmit } = renderCommentInput();+ // Draft + pending upload mount the editor directly (no shell).+ const editor = await screen.findByTestId("editor");++ expect(getSubmitButton(container)).toBeDisabled();+ expect(getSubmitButton(container)).toHaveAttribute("aria-busy", "true");++ // The shortcut path bypasses the button — the submit-time re-read of the+ // DRAFT's uploads is the only guard.+ fireEvent.keyDown(editor, { key: "Enter", metaKey: true });+ await Promise.resolve();+ expect(onSubmit).not.toHaveBeenCalled();++ // The old upload settles (coordinator onSettled → store.settleUpload) —+ // the gate opens and the send goes through.+ await act(async () => {+ useCommentDraftStore+ .getState()+ .settleUpload(+ "new:issue-1",+ "prev-mount-upload",+ uploadAttachment("att-prev", "https://cdn.example/att-prev.png"),+ );+ });+ await waitFor(() => expect(getSubmitButton(container)).not.toBeDisabled());+ fireEvent.keyDown(editor, { key: "Enter", metaKey: true });+ await waitFor(() => expect(onSubmit).toHaveBeenCalled());+ });+it("stays gated until the LAST of two concurrent uploads settles", async () => {const { container } = renderCommentInput();activateComposer("comment-composer-shell");@@ -401,12 +594,12 @@ describe("comment composers — upload submit gate", () => {// First one lands — the second is still in flight, so send must stay shut.await act(async () => {- first.release(uploadResult("att-a", "https://cdn.example/att-a.png"));+ first.resolve(uploadAttachment("att-a", "https://cdn.example/att-a.png"));});expect(getSubmitButton(container)).toBeDisabled();await act(async () => {- second.release(uploadResult("att-b", "https://cdn.example/att-b.png"));+ second.resolve(uploadAttachment("att-b", "https://cdn.example/att-b.png"));});await waitFor(() => expect(getSubmitButton(container)).not.toBeDisabled());});@@ -422,7 +615,7 @@ describe("comment composers — upload submit gate", () => {// uploadWithToast reports the failure and resolves null — the placeholder// is dropped and the body never referenced it, so submit must come back.await act(async () => {- pending.release(null);+ pending.fail();});await waitFor(() => expect(getSubmitButton(container)).not.toBeDisabled());});@@ -434,7 +627,7 @@ describe("comment composers — upload submit gate", () => {const pending = startPendingUpload(container);await act(async () => {- pending.release(uploadResult("att-9", "https://cdn.example/att-9.png"));+ pending.resolve(uploadAttachment("att-9", "https://cdn.example/att-9.png"));});await waitFor(() => expect(getSubmitButton(container)).not.toBeDisabled());@@ -449,6 +642,112 @@ describe("comment composers — upload submit gate", () => {);});+ it("does NOT bind an upload the user deleted from the body", async () => {+ const { container, onSubmit } = renderCommentInput();+ activateComposer("comment-composer-shell");+ const editor = screen.getByTestId("editor");+ fireEvent.change(editor, { target: { value: "keep this" } });++ const pending = startPendingUpload(container);+ await act(async () => {+ pending.resolve(uploadAttachment("att-del", "https://cdn.example/att-del.png"));+ });++ // The completed upload's link is in the body; the user deletes it. What+ // is not referenced must not ship — deleting really unbinds (MUL-5181).+ fireEvent.change(editor, { target: { value: "keep this, dropped the image" } });+ fireEvent.keyDown(editor, { key: "Enter", metaKey: true });++ await waitFor(() => expect(onSubmit).toHaveBeenCalled());+ expect(onSubmit).toHaveBeenCalledWith("keep this, dropped the image", undefined, undefined);+ });++ it("writes the finished upload's link into the persisted draft after the composer unmounts", async () => {+ const { container, unmount } = renderCommentInput();+ activateComposer("comment-composer-shell");+ fireEvent.change(screen.getByTestId("editor"), { target: { value: "wip text" } });++ const pending = startPendingUpload(container);+ unmount();++ await act(async () => {+ pending.resolve(uploadAttachment("att-wb", "https://cdn.example/att-wb.png"));+ });++ // The upload outlived the composer; its link must land in the draft BODY —+ // that's what a future submit binds, and what a reopen renders.+ const draft = useCommentDraftStore.getState().getDraft("new:issue-1");+ expect(draft).toContain("wip text");+ expect(draft).toContain("https://cdn.example/att-wb.png");+ const uploads = useCommentDraftStore.getState().getUploads("new:issue-1");+ expect(uploads).toHaveLength(1);+ expect(uploads[0]?.status).toBe("uploaded");+ });++ it("hands the finished upload's link to a REOPENED composer's live editor", async () => {+ const first = renderCommentInput();+ activateComposer("comment-composer-shell");+ fireEvent.change(screen.getByTestId("editor"), { target: { value: "draft body" } });++ const pending = startPendingUpload(first.container);+ first.unmount();++ // Reopen: the draft + pending upload mount the editor directly (no shell).+ renderCommentInput();+ await screen.findByTestId("editor");++ await act(async () => {+ pending.resolve(uploadAttachment("att-live", "https://cdn.example/att-live.png"));+ });++ // The LIVE EDITOR received the insert (not just the store — an append the+ // mounted editor never saw would be erased by its next emit)…+ expect(insertMarkdownSpy).toHaveBeenCalledWith(+ expect.stringContaining("https://cdn.example/att-live.png"),+ );+ // …and the draft body converged through the normal onUpdate pipeline.+ await waitFor(() =>+ expect(useCommentDraftStore.getState().getDraft("new:issue-1")).toContain(+ "https://cdn.example/att-live.png",+ ),+ );+ });++ it("retries the insert while the reopened editor's instance is still warming up", async () => {+ const first = renderCommentInput();+ activateComposer("comment-composer-shell");+ fireEvent.change(screen.getByTestId("editor"), { target: { value: "draft body" } });++ const pending = startPendingUpload(first.container);+ first.unmount();++ renderCommentInput();+ await screen.findByTestId("editor");++ // Simulate the real handle's window where the component committed but the+ // Tiptap instance hasn't been created yet: insert reports failure.+ insertMarkdownBehavior.succeed = false;+ await act(async () => {+ pending.resolve(uploadAttachment("att-retry", "https://cdn.example/att-retry.png"));+ });++ // Nothing may land in the store while a mounted editor can't show it —+ // that append would be silently erased by the editor's first emit.+ expect(useCommentDraftStore.getState().getDraft("new:issue-1") ?? "").not.toContain(+ "att-retry.png",+ );++ // Instance comes up → the retry delivers into the editor.+ insertMarkdownBehavior.succeed = true;+ await waitFor(+ () =>+ expect(useCommentDraftStore.getState().getDraft("new:issue-1")).toContain(+ "https://cdn.example/att-retry.png",+ ),+ { timeout: 3000 },+ );+ });+it("gates the reply composer's send button too", async () => {const { container } = renderReplyInput();activateComposer("reply-composer-shell");diff --git a/packages/views/issues/components/comment-input.tsx b/packages/views/issues/components/comment-input.tsxindex 1f9f36b6a0..b09a559398 100644--- a/packages/views/issues/components/comment-input.tsx+++ b/packages/views/issues/components/comment-input.tsx@@ -2,16 +2,17 @@import { useRef, useState, useCallback, useEffect } from "react";import { cn } from "@multica/ui/lib/utils";-import { ContentEditor, type ContentEditorRef, useFileDropZone, FileDropOverlay, useLazyEditor, useUploadGate, useEditorUpload } from "../../editor";+import { ContentEditor, type ContentEditorRef, useFileDropZone, FileDropOverlay, useLazyEditor, useUploadGate, useComposerSubmit } from "../../editor";import { FileUploadButton } from "@multica/ui/components/common/file-upload-button";import { SubmitButton } from "@multica/ui/components/common/submit-button";-import type { Attachment } from "@multica/core/types";import { contentReferencesAttachment } from "@multica/core/types";import { formatShortcut, useShortcut } from "@multica/core/shortcuts";import { useCommentComposerStore, useCommentDraftStore } from "@multica/core/issues/stores";import { useT } from "../../i18n";import { CommentTriggerChips } from "./comment-trigger-chips";import { useCommentTriggerPreview } from "../hooks/use-comment-trigger-preview";+import { useCommentUploads } from "./use-comment-uploads";+import { ComposerUploadChips } from "./composer-upload-chips";interface CommentInputProps {issueId: string;@@ -39,22 +40,27 @@ function CommentInput({ issueId, onSubmit }: CommentInputProps) {);const [content, setContent] = useState(initialDraft ?? "");const [isEmpty, setIsEmpty] = useState(() => !initialDraft?.trim());- const [submitting, setSubmitting] = useState(false);const [suppressedAgentIds, setSuppressedAgentIds] = useState<Set<string>>(() => new Set());const triggerPreview = useCommentTriggerPreview({ issueId, content });- // Attachments uploaded in this composer session. Drives both:- // - submit-time `attachment_ids` payload (filtered to URLs still in markdown)- // - the editor's AttachmentDownloadProvider, so file-card Eye buttons can- // resolve text/code/markdown previews that require the attachment id.- const [pendingAttachments, setPendingAttachments] = useState<Attachment[]>([]);- const { uploadWithToast } = useEditorUpload();+ // Uploads for this composer session (MUL-5181). Owned by the module-level+ // coordinator and persisted in the draft store, so closing/scrolling the+ // composer away no longer drops an in-flight upload — its result lands in the+ // draft. `attachments` (completed rows) drives both the submit `attachment_ids`+ // payload and the editor's AttachmentDownloadProvider; `uploads` drives the+ // status chips (uploading / failed / interrupted).+ // `gate` widens the editor gate with coordinator-owned placeholders, so a+ // composer reopened over a still-in-flight upload cannot send past it.+ const { uploads, attachments: pendingAttachments, handleUpload, removeUpload, gate } =+ useCommentUploads(draftKey, { issueId }, uploadGate, editorRef);// Readonly-first: the composer renders as a same-looking static shell until// the user shows intent (click / keyboard / file drop). An unsent draft is// standing intent — mount the real editor immediately so the draft is// visible and editable, exactly like the pre-lazy behavior.const lazy = useLazyEditor({- initialActive: !!initialDraft?.trim(),+ initialActive:+ !!initialDraft?.trim() ||+ useCommentDraftStore.getState().getUploads(draftKey).length > 0,editorRef,});const { isDragOver, dropZoneProps } = useFileDropZone({@@ -69,7 +75,6 @@ function CommentInput({ issueId, onSubmit }: CommentInputProps) {// Flush on every onUpdate (debounced upstream) + visibilitychange/pagehide// so tab close / mobile background doesn't lose work. Cleared on submit.const setDraft = useCommentDraftStore((s) => s.setDraft);- const clearDraft = useCommentDraftStore((s) => s.clearDraft);useEffect(() => {const flush = () => {const md = editorRef.current?.getMarkdown();@@ -84,14 +89,6 @@ function CommentInput({ issueId, onSubmit }: CommentInputProps) {};}, [draftKey, setDraft]);- const handleUpload = useCallback(async (file: File) => {- const result = await uploadWithToast(file, { issueId });- if (result) {- setPendingAttachments((prev) => [...prev, result]);- }- return result;- }, [uploadWithToast, issueId]);-useEffect(() => {setSuppressedAgentIds(new Set());}, [issueId]);@@ -113,47 +110,66 @@ function CommentInput({ issueId, onSubmit }: CommentInputProps) {});}, []);- const handleSubmit = async () => {- const content = editorRef.current?.getMarkdown()?.replace(/(\n\s*)+$/, "").trim();- if (!content || submitting) return;- // Re-read the queue here rather than trusting the button's disabled prop:- // Cmd+Enter never touches the button, and a click can land in the same- // tick an upload starts.- if (uploadGate.isBlocked()) return;- // Track every attachment whose stable download URL OR legacy- // storage URL is referenced in the markdown body. Both shapes- // can appear in the same comment during the MUL-3130 rollout —- // see contentReferencesAttachment for the rationale.- const activeIds = pendingAttachments- .filter((a) => contentReferencesAttachment(content, a))- .map((a) => a.id);- const suppressAgentIds = triggerPreview.agents- .filter((agent) => suppressedAgentIds.has(agent.id))- .map((agent) => agent.id);- // Pessimistic submit: keep the text in place (the editor is locked and the- // button spins via `submitting`) until the server actually accepts it, then- // clear. Clearing only on success means a slow send no longer looks like- // "comment posted but the box is still full", and a failed send keeps the- // draft instead of silently dropping it.- setSubmitting(true);- try {- const ok = await onSubmit(+ // Await-then-render send (MUL-5181): the shared hook reads the markdown,+ // guards empty/in-flight, re-checks the upload gate, locks + spins via+ // `submitting`, and clears only once the server accepts — a failed send keeps+ // the draft instead of silently dropping it.+ // Stale-submit guard (MUL-5181 P0): if this composer unmounts mid-submit+ // (issue detail closed) and the user reopens and types a new draft under the+ // same key, the late success may only clear the draft it submitted.+ const mountedRef = useRef(true);+ useEffect(() => {+ mountedRef.current = true;+ return () => {+ mountedRef.current = false;+ };+ }, []);+ const submittedEntryRef = useRef<unknown>(null);++ const { submitting, submit } = useComposerSubmit({+ editorRef,+ uploadGate: gate,+ onSubmit: (content) => {+ // Flush the editor's pending debounce before snapshotting — a late flush+ // of pre-submit typing must not read as an edit made during the request.+ const pending = editorRef.current?.flushPendingUpdate?.();+ if (pending != null) setDraft(draftKey, pending);+ submittedEntryRef.current = useCommentDraftStore.getState().drafts[draftKey];+ // Bind only uploads the BODY still references (MUL-5181): deleting an+ // inline image really unbinds it. Uploads that finished after a close+ // are written back into the body by the settle handler, so surviving+ // files are referenced too — never silently attached.+ const activeIds = pendingAttachments+ .filter((a) => contentReferencesAttachment(content, a))+ .map((a) => a.id);+ const suppressAgentIds = triggerPreview.agents+ .filter((agent) => suppressedAgentIds.has(agent.id))+ .map((agent) => agent.id);+ return onSubmit(content,activeIds.length > 0 ? activeIds : undefined,suppressAgentIds.length > 0 ? suppressAgentIds : undefined,);- if (ok) {- editorRef.current?.clearContent();- setContent("");- setIsEmpty(true);- setSuppressedAgentIds(new Set());- setPendingAttachments([]);- clearDraft(draftKey);- }- } finally {- setSubmitting(false);- }- };+ },+ onAccepted: () => {+ // Success may only consume the entry it submitted (MUL-5181 P0): edits+ // made while the request was in flight — or by a reopened composer after+ // this one unmounted — survive both in the store and in the editor.+ // Flush the pending debounce first so typing still inside the window is+ // judged correctly (a no-op flush preserves entry identity).+ const lateMd = editorRef.current?.flushPendingUpdate?.();+ if (lateMd != null) setDraft(draftKey, lateMd);+ const store = useCommentDraftStore.getState();+ const live = store.drafts[draftKey];+ const untouched = live === undefined || live === submittedEntryRef.current;+ if (untouched) store.clearDraft(draftKey);+ if (!mountedRef.current || !untouched) return;+ editorRef.current?.clearContent();+ setContent("");+ setIsEmpty(true);+ setSuppressedAgentIds(new Set());+ },+ });return (<div@@ -187,10 +203,11 @@ function CommentInput({ issueId, onSubmit }: CommentInputProps) {setIsEmpty(!md.trim());// Debounced upstream (debounceMs=100). Persist on every tick so a// reload or scroll-out-of-viewport restores work to the keystroke.- if (md.trim().length > 0) setDraft(draftKey, md);- else clearDraft(draftKey);+ // setDraft keeps any pending attachments and drops the entry only+ // when text AND attachments are both empty.+ setDraft(draftKey, md);}}- onSubmit={handleSubmit}+ onSubmit={submit}onUploadFile={handleUpload}onUploadingChange={uploadGate.onUploadingChange}debounceMs={100}@@ -201,6 +218,9 @@ function CommentInput({ issueId, onSubmit }: CommentInputProps) {/></div>)}+ {uploads.some((u) => u.status !== "uploaded") && (+ <ComposerUploadChips uploads={uploads} onRemove={removeUpload} className="px-3 pb-1" />+ )}{/* Static shell — visually clones the empty single-line composer.Real editor mounts (hidden) on first intent; shell stays visibleuntil it's ready so the card never blanks or shifts. */}@@ -243,16 +263,16 @@ function CommentInput({ issueId, onSubmit }: CommentInputProps) {onSelect={(file) => lazy.uploadOrQueue([file])}/><SubmitButton- onClick={handleSubmit}+ onClick={submit}disabled={isEmpty}loading={submitting}- busy={uploadGate.uploading}- tooltip={uploadGate.uploading+ busy={gate.uploading}+ tooltip={gate.uploading? tEditor(($) => $.upload.in_progress): sendShortcut? `${t(($) => $.comment.send_tooltip)} · ${formatShortcut(sendShortcut)}`: t(($) => $.comment.send_tooltip)}- ariaLabel={uploadGate.uploading+ ariaLabel={gate.uploading? tEditor(($) => $.upload.in_progress): t(($) => $.comment.send_tooltip)}/>diff --git a/packages/views/issues/components/composer-upload-chips.tsx b/packages/views/issues/components/composer-upload-chips.tsxnew file mode 100644index 0000000000..619d056b84--- /dev/null+++ b/packages/views/issues/components/composer-upload-chips.tsx@@ -0,0 +1,83 @@+"use client";++import { AlertCircle, Loader2, X } from "lucide-react";+import { Button } from "@multica/ui/components/ui/button";+import { cn } from "@multica/ui/lib/utils";+import type { DraftUpload } from "@multica/core/drafts";+import { useT } from "../../i18n";++/**+ * Status chips for uploads that are NOT yet a completed attachment (MUL-5181).+ *+ * Completed uploads render through the editor's inline preview / the standalone+ * AttachmentList; this strip covers the states those cannot show:+ * - `uploading` — a spinner, so a reopened composer proves the upload is still+ * running (it is owned by the coordinator, not this component).+ * - `interrupted` — a reload/restart killed an in-flight upload; the bytes are+ * gone, so the user must re-attach.+ * - `failed` — the request errored.+ *+ * Interrupted/failed chips are dismissable; there is no retry because the file+ * bytes are not persisted.+ */+export function ComposerUploadChips({+ uploads,+ onRemove,+ className,+}: {+ uploads: DraftUpload[];+ onRemove: (clientUploadId: string) => void;+ className?: string;+}) {+ const { t } = useT("editor");+ const pending = uploads.filter((u) => u.status !== "uploaded");+ if (pending.length === 0) return null;++ return (+ <div className={cn("flex flex-col gap-1", className)}>+ {pending.map((u) => {+ const isUploading = u.status === "uploading";+ const isFailed = u.status === "failed";+ return (+ <div+ key={u.clientUploadId}+ className={cn(+ "flex items-center gap-2 rounded-md border px-2 py-1 text-xs",+ isUploading+ ? "border-border bg-muted/50 text-muted-foreground"+ : "border-destructive/40 bg-destructive/5 text-destructive",+ )}+ >+ {isUploading ? (+ <Loader2 className="h-3.5 w-3.5 shrink-0 animate-spin" aria-hidden />+ ) : (+ <AlertCircle className="h-3.5 w-3.5 shrink-0" aria-hidden />+ )}+ <span className="min-w-0 flex-1 truncate">+ {isUploading+ ? t(($) => $.upload.uploading_label, { filename: u.filename })+ : isFailed+ ? t(($) => $.upload.failed, {+ filename: u.filename,+ reason: u.error ?? "",+ })+ : `${t(($) => $.upload.failed_label, { filename: u.filename })} — ${t(($) => $.upload.interrupted)}`}+ </span>+ {!isUploading && (+ <Button+ type="button"+ size="icon-sm"+ variant="ghost"+ className="h-5 w-5 shrink-0"+ aria-label={t(($) => $.upload.remove)}+ onClick={() => onRemove(u.clientUploadId)}+ >+ <X className="h-3 w-3" />+ </Button>+ )}+ </div>+ );+ })}+ </div>+ );+}diff --git a/packages/views/issues/components/issue-detail.test.tsx b/packages/views/issues/components/issue-detail.test.tsxindex 6c962c9994..25dd6a151d 100644--- a/packages/views/issues/components/issue-detail.test.tsx+++ b/packages/views/issues/components/issue-detail.test.tsx@@ -19,6 +19,10 @@ const mockViewport = vi.hoisted(() => ({ isMobile: false }));// Counts MockContentEditor mounts. This pins the description to exactly one// eager editor per issue and catches stale editor reuse across issue switches.const contentEditorMounts = vi.hoisted(() => ({ count: 0 }));+// Stable empty-attachments reference: the real store returns a shared constant+// so the `useCommentDraftStore(s => s.getAttachments(key))` selector keeps a+// stable identity. A fresh `[]` per call would loop useSyncExternalStore.+const emptyDraftAttachments = vi.hoisted(() => [] as unknown[]);vi.mock("@multica/ui/hooks/use-mobile", () => ({useIsMobile: () => mockViewport.isMobile,@@ -130,6 +134,11 @@ vi.mock("../../editor", async () => ({...(await vi.importActual<typeof import("../../editor/use-upload-gate")>("../../editor/use-upload-gate",)),+ // Real await-then-render submit hook (pure React) so comment/reply/edit+ // composers run the production submit path.+ ...(await vi.importActual<typeof import("../../editor/use-composer-submit")>(+ "../../editor/use-composer-submit",+ )),useEditorUpload: () => ({uploadWithToast: vi.fn(),upload: vi.fn(),@@ -344,18 +353,32 @@ vi.mock("@multica/core/issues/stores", async () => ({useCommentDraftStore: Object.assign((selector?: any) => {const state = {- drafts: {} as Record<string, { content: string; updatedAt: number }>,+ drafts: {} as Record<string, { content: string; attachments: unknown[]; updatedAt: number }>,getDraft: () => undefined,+ getAttachments: () => emptyDraftAttachments,+ getUploads: () => emptyDraftAttachments,setDraft: () => {},+ setAttachments: () => {},+ addUpload: () => {},+ settleUpload: () => {},+ failUpload: () => {},+ removeUpload: () => {},clearDraft: () => {},};return selector ? selector(state) : state;},{getState: () => ({- drafts: {} as Record<string, { content: string; updatedAt: number }>,+ drafts: {} as Record<string, { content: string; attachments: unknown[]; updatedAt: number }>,getDraft: () => undefined,+ getAttachments: () => emptyDraftAttachments,+ getUploads: () => emptyDraftAttachments,setDraft: () => {},+ setAttachments: () => {},+ addUpload: () => {},+ settleUpload: () => {},+ failUpload: () => {},+ removeUpload: () => {},clearDraft: () => {},}),},diff --git a/packages/views/issues/components/reply-input.tsx b/packages/views/issues/components/reply-input.tsxindex 199b685fdd..faeb954c88 100644--- a/packages/views/issues/components/reply-input.tsx+++ b/packages/views/issues/components/reply-input.tsx@@ -1,11 +1,10 @@"use client";import { useRef, useState, useCallback, useEffect } from "react";-import { ContentEditor, type ContentEditorRef, useFileDropZone, FileDropOverlay, useLazyEditor, useUploadGate, useEditorUpload } from "../../editor";+import { ContentEditor, type ContentEditorRef, useFileDropZone, FileDropOverlay, useLazyEditor, useUploadGate, useComposerSubmit } from "../../editor";import { FileUploadButton } from "@multica/ui/components/common/file-upload-button";import { SubmitButton } from "@multica/ui/components/common/submit-button";import { ActorAvatar } from "../../common/actor-avatar";-import type { Attachment } from "@multica/core/types";import { contentReferencesAttachment } from "@multica/core/types";import { formatShortcut, useShortcut } from "@multica/core/shortcuts";import { useCommentDraftStore, type CommentDraftKey } from "@multica/core/issues/stores";@@ -14,6 +13,8 @@ import type { AvatarSize } from "@multica/ui/lib/avatar-size";import { useT } from "../../i18n";import { CommentTriggerChips } from "./comment-trigger-chips";import { useCommentTriggerPreview } from "../hooks/use-comment-trigger-preview";+import { useCommentUploads } from "./use-comment-uploads";+import { ComposerUploadChips } from "./composer-upload-chips";// ---------------------------------------------------------------------------// Types@@ -63,15 +64,17 @@ function ReplyInput({);const [content, setContent] = useState(initialDraft ?? "");const setDraft = useCommentDraftStore((s) => s.setDraft);- const clearDraft = useCommentDraftStore((s) => s.clearDraft);const [isEmpty, setIsEmpty] = useState(!initialDraft?.trim());- const [submitting, setSubmitting] = useState(false);const [suppressedAgentIds, setSuppressedAgentIds] = useState<Set<string>>(() => new Set());const triggerPreview = useCommentTriggerPreview({ issueId, parentId, content });- // Attachments uploaded in this composer session — see CommentInput for the- // rationale (drives both submit-time attachment_ids and editor previews).- const [pendingAttachments, setPendingAttachments] = useState<Attachment[]>([]);- const { uploadWithToast } = useEditorUpload();+ // Uploads for this reply session (MUL-5181) — owned by the coordinator. With+ // a draftKey they persist in the draft store so scroll-out/close no longer+ // drops an in-flight upload; without one (no persistence context) they fall+ // back to session-local state inside the hook.+ // `gate` widens the editor gate with coordinator-owned placeholders — see+ // CommentInput.+ const { uploads, attachments: pendingAttachments, handleUpload, removeUpload, gate } =+ useCommentUploads(draftKey, { issueId }, uploadGate, editorRef);// Readonly-first: static shell until intent; an unsent draft mounts the// real editor immediately (see CommentInput). This is also what keeps the@@ -79,7 +82,9 @@ function ReplyInput({// into a live editor when the card remounts, an untouched box folds back// to the shell.const lazy = useLazyEditor({- initialActive: !!initialDraft?.trim(),+ initialActive:+ !!initialDraft?.trim() ||+ (draftKey ? useCommentDraftStore.getState().getUploads(draftKey).length > 0 : false),editorRef,});const { isDragOver, dropZoneProps } = useFileDropZone({@@ -102,14 +107,6 @@ function ReplyInput({};}, [draftKey, setDraft]);- const handleUpload = useCallback(async (file: File) => {- const result = await uploadWithToast(file, { issueId });- if (result) {- setPendingAttachments((prev) => [...prev, result]);- }- return result;- }, [uploadWithToast, issueId]);-useEffect(() => {setSuppressedAgentIds(new Set());}, [issueId, parentId]);@@ -131,41 +128,63 @@ function ReplyInput({});}, []);- const handleSubmit = async () => {- const content = editorRef.current?.getMarkdown()?.replace(/(\n\s*)+$/, "").trim();- if (!content || submitting) return;- // Submit-time re-read — the shortcut path never sees the disabled button.- if (uploadGate.isBlocked()) return;- // Track every attachment whose stable download URL OR legacy- // storage URL is referenced in the markdown body. Both shapes- // can appear in the same comment during the MUL-3130 rollout.- const activeIds = pendingAttachments- .filter((a) => contentReferencesAttachment(content, a))- .map((a) => a.id);- const suppressAgentIds = triggerPreview.agents- .filter((agent) => suppressedAgentIds.has(agent.id))- .map((agent) => agent.id);- // Pessimistic submit (see CommentInput): keep the text, lock + spin, clear- // only once the server accepts it.- setSubmitting(true);- try {- const ok = await onSubmit(+ // Await-then-render send (see CommentInput): the shared hook keeps the text,+ // locks + spins, and clears only once the server accepts it.+ // Stale-submit guard — see CommentInput.+ const mountedRef = useRef(true);+ useEffect(() => {+ mountedRef.current = true;+ return () => {+ mountedRef.current = false;+ };+ }, []);+ const submittedEntryRef = useRef<unknown>(null);++ const { submitting, submit } = useComposerSubmit({+ editorRef,+ uploadGate: gate,+ onSubmit: (content) => {+ if (draftKey) {+ // Flush pending debounce before snapshotting — see CommentInput.+ const pending = editorRef.current?.flushPendingUpdate?.();+ if (pending != null) setDraft(draftKey, pending);+ submittedEntryRef.current = useCommentDraftStore.getState().drafts[draftKey];+ }+ // Bind only uploads the body still references (see CommentInput):+ // deleting an inline image really unbinds it; close-surviving uploads+ // are written back into the body by the settle handler.+ const activeIds = pendingAttachments+ .filter((a) => contentReferencesAttachment(content, a))+ .map((a) => a.id);+ const suppressAgentIds = triggerPreview.agents+ .filter((agent) => suppressedAgentIds.has(agent.id))+ .map((agent) => agent.id);+ return onSubmit(content,activeIds.length > 0 ? activeIds : undefined,suppressAgentIds.length > 0 ? suppressAgentIds : undefined,);- if (ok) {- editorRef.current?.clearContent();- setContent("");- setIsEmpty(true);- setSuppressedAgentIds(new Set());- setPendingAttachments([]);- if (draftKey) clearDraft(draftKey);+ },+ onAccepted: () => {+ // Success may only consume the entry it submitted — see CommentInput.+ if (draftKey) {+ const lateMd = editorRef.current?.flushPendingUpdate?.();+ if (lateMd != null) setDraft(draftKey, lateMd);+ const store = useCommentDraftStore.getState();+ const live = store.drafts[draftKey];+ const untouched = live === undefined || live === submittedEntryRef.current;+ if (untouched) store.clearDraft(draftKey);+ if (!mountedRef.current || !untouched) return;+ } else {+ if (!mountedRef.current) return;+ uploads.forEach((u) => removeUpload(u.clientUploadId));}- } finally {- setSubmitting(false);- }- };+ editorRef.current?.clearContent();+ setContent("");+ setIsEmpty(true);+ setSuppressedAgentIds(new Set());+ },+ });const avatarSize: AvatarSize = size === "sm" ? "sm" : "md";@@ -202,12 +221,11 @@ function ReplyInput({onUpdate={(md) => {setContent(md);setIsEmpty(!md.trim());- if (draftKey) {- if (md.trim().length > 0) setDraft(draftKey, md);- else clearDraft(draftKey);- }+ // setDraft keeps any pending attachments and drops the entry only+ // when text AND attachments are both empty.+ if (draftKey) setDraft(draftKey, md);}}- onSubmit={handleSubmit}+ onSubmit={submit}onUploadFile={handleUpload}onUploadingChange={uploadGate.onUploadingChange}debounceMs={100}@@ -218,6 +236,9 @@ function ReplyInput({/></div>)}+ {uploads.some((u) => u.status !== "uploaded") && (+ <ComposerUploadChips uploads={uploads} onRemove={removeUpload} className="mt-1" />+ )}{/* Static shell — clones the empty single-line reply box (seeCommentInput for the pattern). */}{!lazy.ready && (@@ -256,16 +277,16 @@ function ReplyInput({onSelect={(file) => lazy.uploadOrQueue([file])}/><SubmitButton- onClick={handleSubmit}+ onClick={submit}disabled={isEmpty}loading={submitting}- busy={uploadGate.uploading}- tooltip={uploadGate.uploading+ busy={gate.uploading}+ tooltip={gate.uploading? tEditor(($) => $.upload.in_progress): sendShortcut? `${t(($) => $.comment.send_tooltip)} · ${formatShortcut(sendShortcut)}`: t(($) => $.comment.send_tooltip)}- ariaLabel={uploadGate.uploading+ ariaLabel={gate.uploading? tEditor(($) => $.upload.in_progress): t(($) => $.comment.send_tooltip)}/>diff --git a/packages/views/issues/components/use-comment-uploads.ts b/packages/views/issues/components/use-comment-uploads.tsnew file mode 100644index 0000000000..e152a40101--- /dev/null+++ b/packages/views/issues/components/use-comment-uploads.ts@@ -0,0 +1,59 @@+"use client";++/**+ * Comment-composer binding for the coordinated-upload engine (MUL-5181, L2).+ *+ * All upload mechanics — coordinator ownership, generation guards, the+ * confirmed write-back of a finished upload's link into the draft body, the+ * combined submit gate — live in `editor/use-coordinated-uploads`. This file+ * only maps the engine onto the comment draft store, keyed by+ * {@link CommentDraftKey}. Without a key (a reply box with no persistence+ * context) the engine falls back to component-local uploads that die with the+ * mount, matching pre-L2 behavior.+ */++import { useMemo, type RefObject } from "react";+import type { DraftUpload } from "@multica/core/drafts";+import type { UploadContext } from "@multica/core/hooks/use-file-upload";+import { useCommentDraftStore, type CommentDraftKey } from "@multica/core/issues/stores";+import type { UploadGate } from "../../editor/use-upload-gate";+import type { ContentEditorRef } from "../../editor/content-editor";+import {+ useCoordinatedUploads,+ type CoordinatedUploads,+ type UploadDraftBinding,+} from "../../editor/use-coordinated-uploads";++const EMPTY_UPLOADS: DraftUpload[] = [];++export type CommentUploads = CoordinatedUploads;++export function useCommentUploads(+ draftKey: CommentDraftKey | undefined,+ ctx: UploadContext,+ editorGate: UploadGate,+ editorRef: RefObject<ContentEditorRef | null>,+): CommentUploads {+ const storeUploads = useCommentDraftStore((s) =>+ draftKey ? s.getUploads(draftKey) : EMPTY_UPLOADS,+ );++ // Referentially stable per key — settle closures capture it and must keep+ // working after this component unmounts, so every accessor goes through+ // getState().+ const binding = useMemo<UploadDraftBinding | undefined>(() => {+ if (!draftKey) return undefined;+ return {+ registryKey: `comment:${draftKey}`,+ getUploads: () => useCommentDraftStore.getState().getUploads(draftKey),+ addUpload: (u) => useCommentDraftStore.getState().addUpload(draftKey, u),+ settleUpload: (id, att) => useCommentDraftStore.getState().settleUpload(draftKey, id, att),+ failUpload: (id, err) => useCommentDraftStore.getState().failUpload(draftKey, id, err),+ removeUpload: (id) => useCommentDraftStore.getState().removeUpload(draftKey, id),+ getBody: () => useCommentDraftStore.getState().getDraft(draftKey) ?? "",+ appendToBody: (md) => useCommentDraftStore.getState().appendToDraftContent(draftKey, md),+ };+ }, [draftKey]);++ return useCoordinatedUploads(binding, storeUploads, ctx, editorGate, editorRef);+}diff --git a/packages/views/layout/app-sidebar.tsx b/packages/views/layout/app-sidebar.tsxindex c3bb84a818..a431dcf9fc 100644--- a/packages/views/layout/app-sidebar.tsx+++ b/packages/views/layout/app-sidebar.tsx@@ -159,7 +159,7 @@ const configureNav: { key: NavKey; labelKey: NavLabelKey }[] = [];function DraftDot() {- const hasDraft = useIssueDraftStore((s) => !!(s.draft.title || s.draft.description));+ const hasDraft = useIssueDraftStore((s) => s.hasDraft());if (!hasDraft) return null;return <span className="absolute top-0 right-0 size-1.5 rounded-full bg-brand" />;}diff --git a/packages/views/locales/en/editor.json b/packages/views/locales/en/editor.jsonindex 86c91ac344..81bb022e32 100644--- a/packages/views/locales/en/editor.json+++ b/packages/views/locales/en/editor.json@@ -88,7 +88,11 @@},"upload": {"failed": "Couldn't upload {{filename}}: {{reason}}",- "in_progress": "Uploading…"+ "in_progress": "Uploading…",+ "interrupted": "Upload interrupted — the file wasn’t saved. Attach it again.",+ "remove": "Remove",+ "uploading_label": "Uploading {{filename}}…",+ "failed_label": "Couldn’t upload {{filename}}"},"title_editor": {"title_aria_label": "Title"diff --git a/packages/views/locales/ja/editor.json b/packages/views/locales/ja/editor.jsonindex ec56605a4c..a109d45e93 100644--- a/packages/views/locales/ja/editor.json+++ b/packages/views/locales/ja/editor.json@@ -81,7 +81,11 @@},"upload": {"failed": "{{filename}} をアップロードできませんでした: {{reason}}",- "in_progress": "アップロード中…"+ "in_progress": "アップロード中…",+ "interrupted": "アップロードが中断されました—ファイルは保存されていません。もう一度添付してください。",+ "remove": "削除",+ "uploading_label": "{{filename}} をアップロード中…",+ "failed_label": "{{filename}} をアップロードできませんでした"},"title_editor": {"title_aria_label": "タイトル"diff --git a/packages/views/locales/ko/editor.json b/packages/views/locales/ko/editor.jsonindex 477f385cf6..cf3af900cf 100644--- a/packages/views/locales/ko/editor.json+++ b/packages/views/locales/ko/editor.json@@ -81,7 +81,11 @@},"upload": {"failed": "{{filename}}을(를) 업로드하지 못했어요: {{reason}}",- "in_progress": "업로드 중…"+ "in_progress": "업로드 중…",+ "interrupted": "업로드가 중단되었어요 — 파일이 저장되지 않았어요. 다시 첨부해 주세요.",+ "remove": "제거",+ "uploading_label": "{{filename}} 업로드 중…",+ "failed_label": "{{filename}}을(를) 업로드하지 못했어요"},"title_editor": {"title_aria_label": "제목"diff --git a/packages/views/locales/zh-Hans/editor.json b/packages/views/locales/zh-Hans/editor.jsonindex f0bd2bff70..ed8de7747b 100644--- a/packages/views/locales/zh-Hans/editor.json+++ b/packages/views/locales/zh-Hans/editor.json@@ -88,7 +88,11 @@},"upload": {"failed": "{{filename}} 上传失败:{{reason}}",- "in_progress": "上传中…"+ "in_progress": "上传中…",+ "interrupted": "上传已中断——文件未保存。请重新添加。",+ "remove": "移除",+ "uploading_label": "正在上传 {{filename}}…",+ "failed_label": "{{filename}} 上传失败"},"title_editor": {"title_aria_label": "标题"diff --git a/packages/views/modals/create-issue.test.tsx b/packages/views/modals/create-issue.test.tsxindex c5c43c587e..a69a8ac890 100644--- a/packages/views/modals/create-issue.test.tsx+++ b/packages/views/modals/create-issue.test.tsx@@ -26,51 +26,86 @@ const mockCreateIssue = vi.hoisted(() => vi.fn());const mockAttachLabel = vi.hoisted(() => vi.fn());const mockListProperties = vi.hoisted(() => vi.fn());const mockSetIssueProperty = vi.hoisted(() => vi.fn());-const mockSetDraft = vi.hoisted(() => vi.fn());+const mockSetShared = vi.hoisted(() => vi.fn());+const mockSetManual = vi.hoisted(() => vi.fn());+const mockSetAgent = vi.hoisted(() => vi.fn());+const mockSetActiveMode = vi.hoisted(() => vi.fn());const mockClearDraft = vi.hoisted(() => vi.fn());const mockSetLastAssignee = vi.hoisted(() => vi.fn());const mockSetKeepOpen = vi.hoisted(() => vi.fn());const mockToastCustom = vi.hoisted(() => vi.fn());const mockToastDismiss = vi.hoisted(() => vi.fn());const mockToastError = vi.hoisted(() => vi.fn());-const mockUploadWithToast = vi.hoisted(() => vi.fn());+// Uploads flow through the module-level coordinator, which calls+// `api.uploadFile(file, ctx, signal)` (MUL-5181 L2). Tests drive uploads by+// mocking that call; it resolves a plain server Attachment row.+const mockApiUploadFile = vi.hoisted(() => vi.fn());++type DraftAttachment = {+ id: string;+ workspace_id: string;+ issue_id: string | null;+ comment_id: string | null;+ chat_session_id: string | null;+ chat_message_id: string | null;+ uploader_type: string;+ uploader_id: string;+ filename: string;+ url: string;+ download_url: string;+ markdown_url: string;+ content_type: string;+ size_bytes: number;+ created_at: string;+};-const mockDraftStore = {- draft: {+// Coordinator-owned upload entry persisted in the shared pool (MUL-5181 L2).+type DraftUploadEntry = {+ clientUploadId: string;+ status: "uploading" | "uploaded" | "failed" | "interrupted";+ filename: string;+ size: number;+ contentType?: string;+ attachment?: DraftAttachment;+ error?: string;+};++const emptyIssueDraft = () => ({+ shared: {+ projectId: undefined as string | undefined,+ priority: "none" as "none" | "low" | "medium" | "high" | "urgent",+ dueDate: null as string | null,+ attachments: [] as DraftUploadEntry[],+ },+ manual: {title: "",description: "",status: "todo" as const,- priority: "none" as const,+ startDate: null as string | null,assigneeType: undefined as "agent" | "squad" | "member" | undefined,assigneeId: undefined as string | undefined,- projectId: undefined as string | undefined,- startDate: null,- dueDate: null,labelIds: [] as string[],propertyValues: {} as Record<string, string | number | boolean | string[]>,- attachments: [] as Array<{- id: string;- workspace_id: string;- issue_id: string | null;- comment_id: string | null;- chat_session_id: string | null;- chat_message_id: string | null;- uploader_type: string;- uploader_id: string;- filename: string;- url: string;- download_url: string;- markdown_url: string;- content_type: string;- size_bytes: number;- created_at: string;- }>,},- lastAssigneeType: undefined,- lastAssigneeId: undefined,- setDraft: mockSetDraft,+ agent: {+ prompt: "",+ actorType: undefined as "agent" | "squad" | undefined,+ actorId: undefined as string | undefined,+ },+ activeMode: "manual" as "manual" | "agent",+});++const mockDraftStore = {+ draft: emptyIssueDraft(),+ lastAssigneeType: undefined as "agent" | "squad" | "member" | undefined,+ lastAssigneeId: undefined as string | undefined,+ setShared: mockSetShared,+ setManual: mockSetManual,+ setAgent: mockSetAgent,+ setActiveMode: mockSetActiveMode,clearDraft: mockClearDraft,setLastAssignee: mockSetLastAssignee,+ hasDraft: () => false,};const mockQuickCreateStore = {@@ -191,9 +226,6 @@ vi.mock("@multica/core/properties", async (importOriginal) => {};});-vi.mock("@multica/core/hooks/use-file-upload", () => ({- useFileUpload: () => ({ uploadWithToast: mockUploadWithToast }),-}));// Hoisted ApiError class so both the vi.mock factory and the tests below// can construct/instanceof-check the same identity. vi.mock is hoisted, so@@ -231,6 +263,7 @@ vi.mock("@multica/core/api", async () => {api: {listProperties: mockListProperties,setIssueProperty: mockSetIssueProperty,+ uploadFile: mockApiUploadFile,},ApiError,parseWithFallback,@@ -244,6 +277,9 @@ vi.mock("../editor", async () => {const uploadGate = await vi.importActual<typeof import("../editor/use-upload-gate")>("../editor/use-upload-gate",);+ const composer = await vi.importActual<typeof import("../editor/use-composer-submit")>(+ "../editor/use-composer-submit",+ );const ContentEditor = forwardRef(({ defaultValue, onUpdate, onSubmit, onUploadFile, onUploadingChange, placeholder, attachments }: any, ref: any) => {const valueRef = useRef(defaultValue || "");const [value, setValue] = useState(defaultValue || "");@@ -325,11 +361,7 @@ vi.mock("../editor", async () => {return {...uploadGate,- useEditorUpload: () => ({- uploadWithToast: mockUploadWithToast,- upload: vi.fn(),- uploading: false,- }),+ ...composer,useFileDropZone: () => ({ isDragOver: false, dropZoneProps: {} }),FileDropOverlay: () => null,ContentEditor,@@ -512,40 +544,25 @@ describe("CreateIssueModal", () => {mockSetKeepOpen.mockImplementation((v: boolean) => {mockQuickCreateStore.keepOpen = v;});- mockDraftStore.draft.title = "";- mockDraftStore.draft.description = "";- mockDraftStore.draft.status = "todo";- mockDraftStore.draft.priority = "none";- // Reset the shared draft mock so per-test assignee seeding (squad / agent)+ // Reset the unified draft mock so per-test seeding (assignee, project, …)// doesn't leak into the next test in the suite.- mockDraftStore.draft.assigneeType = undefined;- mockDraftStore.draft.assigneeId = undefined;- mockDraftStore.draft.projectId = undefined;- mockDraftStore.draft.startDate = null;- mockDraftStore.draft.dueDate = null;- mockDraftStore.draft.labelIds = [];- mockDraftStore.draft.propertyValues = {};- mockDraftStore.draft.attachments = [];- mockSetDraft.mockImplementation((patch: Partial<typeof mockDraftStore.draft>) => {- mockDraftStore.draft = { ...mockDraftStore.draft, ...patch };+ mockDraftStore.draft = emptyIssueDraft();+ mockSetShared.mockImplementation((patch: Partial<typeof mockDraftStore.draft.shared>) => {+ mockDraftStore.draft.shared = { ...mockDraftStore.draft.shared, ...patch };+ });+ mockSetManual.mockImplementation((patch: Partial<typeof mockDraftStore.draft.manual>) => {+ mockDraftStore.draft.manual = { ...mockDraftStore.draft.manual, ...patch };+ });+ mockSetAgent.mockImplementation((patch: Partial<typeof mockDraftStore.draft.agent>) => {+ mockDraftStore.draft.agent = { ...mockDraftStore.draft.agent, ...patch };});mockClearDraft.mockImplementation(() => {- mockDraftStore.draft = {- title: "",- description: "",- status: "todo",- priority: "none",- assigneeType: mockDraftStore.lastAssigneeType,- assigneeId: mockDraftStore.lastAssigneeId,- projectId: undefined,- startDate: null,- dueDate: null,- labelIds: [],- propertyValues: {},- attachments: [],- };+ const next = emptyIssueDraft();+ next.manual.assigneeType = mockDraftStore.lastAssigneeType;+ next.manual.assigneeId = mockDraftStore.lastAssigneeId;+ mockDraftStore.draft = next;});- mockUploadWithToast.mockResolvedValue({+ mockApiUploadFile.mockResolvedValue({id: "11111111-2222-3333-4444-555555555555",workspace_id: "ws-test",issue_id: null,@@ -561,8 +578,6 @@ describe("CreateIssueModal", () => {content_type: "image/png",size_bytes: 123,created_at: "2026-06-12T00:00:00Z",- link: "https://cdn.example.test/shot.png",- markdownLink: "https://multica-api.copilothub.ai/api/attachments/11111111-2222-3333-4444-555555555555/download",});mockCreateIssue.mockResolvedValue({id: "issue-123",@@ -649,7 +664,7 @@ describe("CreateIssueModal", () => {it("forwards selected labels in the create payload so they attach in the same transaction", async () => {const user = userEvent.setup();- mockDraftStore.draft.labelIds = [+ mockDraftStore.draft.manual.labelIds = ["aaaaaaaa-1111-2222-3333-444444444444","bbbbbbbb-1111-2222-3333-444444444444",];@@ -687,7 +702,7 @@ describe("CreateIssueModal", () => {title: "Labeled issue",status: "todo",});- mockDraftStore.draft.labelIds = [+ mockDraftStore.draft.manual.labelIds = ["aaaaaaaa-1111-2222-3333-444444444444","bbbbbbbb-1111-2222-3333-444444444444",];@@ -742,17 +757,20 @@ describe("CreateIssueModal", () => {expect(onClose).not.toHaveBeenCalled();expect(screen.getByPlaceholderText("Issue title")).toHaveValue("");expect(screen.getByPlaceholderText("Add description...")).toHaveValue("");- expect(mockSetDraft).toHaveBeenCalledWith({+ expect(mockSetManual).toHaveBeenCalledWith({title: "",description: "",status: "todo",- priority: "none",assigneeType: undefined,assigneeId: undefined,startDate: null,- dueDate: null,labelIds: [],propertyValues: {},+ });+ expect(mockSetShared).toHaveBeenCalledWith({+ priority: "none",+ projectId: undefined,+ dueDate: null,attachments: [],});});@@ -785,23 +803,18 @@ describe("CreateIssueModal", () => {await user.click(screen.getByRole("button", { name: "Upload file" }));+ // Coordinator flow (MUL-5181 L2): a placeholder is written at pick time,+ // then settles into an `uploaded` entry carrying the server row.await waitFor(() => {- expect(mockSetDraft).toHaveBeenCalledWith({- attachments: [- expect.objectContaining({- id: "11111111-2222-3333-4444-555555555555",- filename: "shot.png",- download_url: "",- }),- ],- });+ const uploads = mockDraftStore.draft.shared.attachments;+ expect(uploads).toHaveLength(1);+ expect(uploads[0]).toMatchObject({ status: "uploaded", filename: "shot.png" });+ expect(uploads[0]?.attachment?.id).toBe("11111111-2222-3333-4444-555555555555");});- const draftAttachmentsCall = mockSetDraft.mock.calls.find(- ([patch]) => Array.isArray(patch.attachments),- )?.[0] as { attachments?: Array<{ download_url: string }> } | undefined;- expect(draftAttachmentsCall?.attachments?.[0]?.download_url).not.toContain(- "Signature=",- );+ // The response-scoped signed download_url must never be persisted — the+ // draft survives dialog closes, and a stale signature would 403 the+ // preview on reopen. Durable render paths re-resolve via markdown_url.+ expect(mockDraftStore.draft.shared.attachments[0]?.attachment?.download_url).toBe("");});it("reuses draft attachments after reopening manual create so pasted images can render and bind", async () => {@@ -823,9 +836,18 @@ describe("CreateIssueModal", () => {size_bytes: 123,created_at: "2026-06-12T00:00:00Z",};- mockDraftStore.draft.title = "Image draft";- mockDraftStore.draft.description = ``;- mockDraftStore.draft.attachments = [attachment];+ mockDraftStore.draft.manual.title = "Image draft";+ mockDraftStore.draft.manual.description = ``;+ mockDraftStore.draft.shared.attachments = [+ {+ clientUploadId: attachment.id,+ status: "uploaded",+ filename: attachment.filename,+ size: attachment.size_bytes,+ contentType: attachment.content_type,+ attachment,+ },+ ];renderModal(<CreateIssueModal onClose={vi.fn()} />);@@ -871,23 +893,76 @@ describe("CreateIssueModal", () => {url: "https://cdn.example.test/deleted.png",markdown_url: "https://multica-api.copilothub.ai/api/attachments/99999999-8888-7777-6666-555555555555/download",};- mockDraftStore.draft.title = "Image draft";- mockDraftStore.draft.description = ``;- mockDraftStore.draft.attachments = [referenced, deleted];+ const wrap = (att: typeof referenced): DraftUploadEntry => ({+ clientUploadId: att.id,+ status: "uploaded",+ filename: att.filename,+ size: att.size_bytes,+ contentType: att.content_type,+ attachment: att,+ });+ mockDraftStore.draft.manual.title = "Image draft";+ mockDraftStore.draft.manual.description = ``;+ mockDraftStore.draft.shared.attachments = [wrap(referenced), wrap(deleted)];renderModal(<CreateIssueModal onClose={vi.fn()} />);await waitFor(() => {- expect(mockSetDraft).toHaveBeenCalledWith({ attachments: [referenced] });+ expect(mockSetShared).toHaveBeenCalledWith({+ attachments: [expect.objectContaining({ clientUploadId: referenced.id })],+ });});});- // Manual → agent must also forward the picked squad. Without this branch- // the agent panel silently falls back to the persisted actor / first+ it("mount prune keeps in-flight placeholders while dropping unreferenced uploaded rows", async () => {+ // Reopen-while-uploading: the placeholder has no body reference yet (the+ // chips are its only UI), so the mount prune must never touch it —+ // dropping it here would let the settle hit the generation guard and+ // silently discard the file.+ const orphanRow = {+ id: "99999999-8888-7777-6666-555555555555",+ workspace_id: "ws-test",+ issue_id: null,+ comment_id: null,+ chat_session_id: null,+ chat_message_id: null,+ uploader_type: "member",+ uploader_id: "user-1",+ filename: "orphan.png",+ url: "https://cdn.example.test/orphan.png",+ download_url: "",+ markdown_url: "https://multica-api.copilothub.ai/api/attachments/99999999-8888-7777-6666-555555555555/download",+ content_type: "image/png",+ size_bytes: 5,+ created_at: "2026-06-12T00:00:00Z",+ };+ mockDraftStore.draft.manual.title = "Reopened";+ mockDraftStore.draft.shared.attachments = [+ { clientUploadId: "c-flight", status: "uploading", filename: "mid.png", size: 9 },+ {+ clientUploadId: orphanRow.id,+ status: "uploaded",+ filename: orphanRow.filename,+ size: orphanRow.size_bytes,+ attachment: orphanRow,+ },+ ];++ renderModal(<CreateIssueModal onClose={vi.fn()} />);++ await waitFor(() => {+ expect(mockSetShared).toHaveBeenCalledWith({+ attachments: [expect.objectContaining({ clientUploadId: "c-flight" })],+ });+ });+ });++ // Manual → agent must seed the agent actor from the picked squad. Without+ // this the agent panel silently falls back to the persisted actor / first// visible agent and the user loses the squad they just chose in manual.- it("forwards the picked squad when switching to agent mode", async () => {- mockDraftStore.draft.assigneeType = "squad";- mockDraftStore.draft.assigneeId = "squad-1";+ it("seeds the agent actor from the picked squad when switching to agent mode", async () => {+ mockDraftStore.draft.manual.assigneeType = "squad";+ mockDraftStore.draft.manual.assigneeId = "squad-1";const user = userEvent.setup();const onSwitchMode = vi.fn();@@ -904,11 +979,14 @@ describe("CreateIssueModal", () => {await user.click(screen.getByRole("button", { name: /Switch to Agent/i }));expect(onSwitchMode).toHaveBeenCalledTimes(1);- const carry = onSwitchMode.mock.calls[0]?.[0];- expect(carry).toEqual(- expect.objectContaining({ prompt: "Refactor auth", squad_id: "squad-1" }),- );- expect(carry).not.toHaveProperty("agent_id");+ // Prompt assist-init + squad actor land in the unified agent draft.+ expect(mockSetAgent).toHaveBeenCalledWith({ prompt: "Refactor auth" });+ expect(mockSetAgent).toHaveBeenCalledWith({+ actorType: "squad",+ actorId: "squad-1",+ });+ // Actor rides the store, not the carry; no parent here → carry is null.+ expect(onSwitchMode.mock.calls[0]?.[0]).toBeNull();});// Manual → agent must forward the picked project so the new modal pins to@@ -1002,7 +1080,10 @@ describe("CreateIssueModal", () => {expect(mockToastError).toHaveBeenCalledWith("Failed to create issue");});- it("forwards the picked project when switching to agent mode", async () => {+ // Manual → agent must preserve the picked project. It now rides the shared+ // draft slot rather than the carry: the switch commits the (data-seeded)+ // project into `shared` so the agent panel reads it from there.+ it("commits the picked project to the shared draft when switching to agent mode", async () => {const user = userEvent.setup();const onSwitchMode = vi.fn();@@ -1021,12 +1102,10 @@ describe("CreateIssueModal", () => {await user.click(screen.getByRole("button", { name: /Switch to Agent/i }));expect(onSwitchMode).toHaveBeenCalledTimes(1);- expect(onSwitchMode.mock.calls[0]?.[0]).toEqual(- expect.objectContaining({- prompt: "Refactor auth",- project_id: "proj-1",- }),+ expect(mockSetShared).toHaveBeenCalledWith(+ expect.objectContaining({ projectId: "proj-1" }),);+ expect(mockSetAgent).toHaveBeenCalledWith({ prompt: "Refactor auth" });});it("restores an unfinished project selection after manual create remounts", async () => {@@ -1036,7 +1115,7 @@ describe("CreateIssueModal", () => {expect(screen.getByTestId("project-picker")).toHaveAttribute("data-project-id", "none");await user.click(screen.getByTestId("project-picker"));- expect(mockSetDraft).toHaveBeenCalledWith({ projectId: "proj-1" });+ expect(mockSetShared).toHaveBeenCalledWith({ projectId: "proj-1" });firstOpen.unmount();renderModal(<CreateIssueModal onClose={vi.fn()} />);@@ -1077,13 +1156,13 @@ describe("CreateIssueModal", () => {await user.click(screen.getByRole("button", { name: /Switch to Agent/i }));expect(onSwitchMode).toHaveBeenCalledTimes(1);- expect(onSwitchMode.mock.calls[0]?.[0]).toEqual(- expect.objectContaining({- prompt: "Refactor auth",- parent_issue_id: "parent-uuid-1",- parent_issue_identifier: "MUL-2534",- }),- );+ // The parent context is not persisted (a per-invocation intent), so it+ // still rides the carry channel. The prompt rides the store now.+ expect(onSwitchMode.mock.calls[0]?.[0]).toEqual({+ parent_issue_id: "parent-uuid-1",+ parent_issue_identifier: "MUL-2534",+ });+ expect(mockSetAgent).toHaveBeenCalledWith({ prompt: "Refactor auth" });});// Start date is a low-frequency field — by default it lives behind the@@ -1156,7 +1235,7 @@ describe("CreateIssueModal", () => {it("keeps a hidden field on the toolbar while it holds a value", () => {mockCreateSettingsStore.manualCreateFields = ["status", "priority", "assignee", "project"];- mockDraftStore.draft.labelIds = ["label-1"];+ mockDraftStore.draft.manual.labelIds = ["label-1"];renderModal(<CreateIssueModal onClose={vi.fn()} />);@@ -1185,11 +1264,12 @@ describe("CreateIssueModal", () => {expect(mockPush).toHaveBeenCalledWith("/ws-test/settings?tab=issue");});- // Title + description are packed into the agent prompt on switch; if we- // leave them in the shared draft store, the next agent→manual switch- // surfaces the stale manual draft on top of the prompt-as-description,- // duplicating the user's text on every round-trip.- it("clears the manual draft when packing title and description into the agent prompt", async () => {+ // MUL-5181: switching to agent must PRESERVE the manual draft. The agent+ // prompt is assist-init'd from title + description (a one-time convenience+ // when the agent slot is empty), but the manual title/description are left+ // untouched so a later agent→manual switch restores them verbatim — no+ // concatenate-then-clear, no duplication on round-trips.+ it("assist-inits the agent prompt from title and description without clearing the manual draft", async () => {const user = userEvent.setup();renderModal(@@ -1204,20 +1284,124 @@ describe("CreateIssueModal", () => {await user.type(screen.getByPlaceholderText("Issue title"), "Update");await user.type(screen.getByPlaceholderText("Add description..."), "Some body");- mockSetDraft.mockClear();+ mockSetManual.mockClear();+ mockSetAgent.mockClear();await user.click(screen.getByRole("button", { name: /Switch to Agent/i }));- expect(mockSetDraft).toHaveBeenCalledWith({ title: "", description: "" });+ // Agent prompt seeded from the manual content...+ expect(mockSetAgent).toHaveBeenCalledWith({ prompt: "Update\n\nSome body" });+ // ...and the manual slot is never cleared.+ expect(mockSetManual).not.toHaveBeenCalledWith(+ expect.objectContaining({ title: "" }),+ );+ expect(mockSetManual).not.toHaveBeenCalledWith(+ expect.objectContaining({ description: "" }),+ );});// MUL-4808 — manual create had no upload gate at all: Create, Enter on the// title, and Switch to Agent would each fix the draft while an image was// still uploading, dropping it from the description with no warning.+ // MUL-5181 P0: the issue draft is a SINGLETON store. A submit that outlives+ // its dialog may only consume the draft it submitted — never one the user+ // typed after closing and reopening.+ describe("stale-submit draft guard", () => {+ function renderManualPanel(onClose = vi.fn()) {+ return renderModal(+ <ManualCreatePanel+ onClose={onClose}+ onSwitchMode={vi.fn()}+ isExpanded={false}+ setIsExpanded={vi.fn()}+ />,+ );+ }++ async function startPendingCreate() {+ let resolveCreate!: (v: unknown) => void;+ mockCreateIssue.mockImplementationOnce(+ () => new Promise((resolve) => { resolveCreate = resolve; }),+ );+ const user = userEvent.setup();+ const onClose = vi.fn();+ const view = renderManualPanel(onClose);+ await user.type(screen.getByPlaceholderText("Issue title"), "Draft A");+ fireEvent.keyDown(screen.getByPlaceholderText("Issue title"), {+ key: "Enter",+ metaKey: true,+ });+ await waitFor(() => expect(mockCreateIssue).toHaveBeenCalled());+ return {+ view,+ onClose,+ finish: () =>+ act(async () => {+ resolveCreate({ id: "issue-9", identifier: "TES-9", title: "Draft A", status: "todo", labels: [] });+ await Promise.resolve();+ }),+ };+ }++ it("typing draft B while draft A's submit is pending survives the success (mounted)", async () => {+ const { onClose, finish } = await startPendingCreate();++ // The editor stays interactive during the request; a store write during+ // the flight replaces the singleton draft's object identity.+ mockDraftStore.draft = {+ ...emptyIssueDraft(),+ manual: { ...emptyIssueDraft().manual, title: "Draft B" },+ };++ await finish();++ expect(mockClearDraft).not.toHaveBeenCalled();+ // The dialog must not close/reset over the newer draft either.+ expect(onClose).not.toHaveBeenCalled();+ expect(mockDraftStore.draft.manual.title).toBe("Draft B");+ });++ it("an untouched mounted submit still clears and closes", async () => {+ const { onClose, finish } = await startPendingCreate();++ await finish();++ expect(mockClearDraft).toHaveBeenCalled();+ expect(onClose).toHaveBeenCalled();+ });++ it("a late success does NOT clear a draft replaced after the dialog closed", async () => {+ const { view, finish } = await startPendingCreate();++ view.unmount();+ // The user reopened the dialog and typed draft B — the singleton store+ // now holds a different draft object than the submit snapshot.+ mockDraftStore.draft = {+ ...emptyIssueDraft(),+ manual: { ...emptyIssueDraft().manual, title: "Draft B" },+ };++ await finish();++ expect(mockClearDraft).not.toHaveBeenCalled();+ expect(mockDraftStore.draft.manual.title).toBe("Draft B");+ });++ it("a late success still clears an untouched draft", async () => {+ const { view, finish } = await startPendingCreate();++ view.unmount();+ await finish();++ expect(mockClearDraft).toHaveBeenCalled();+ });+ });+describe("upload submit gate", () => {- /** Attach a file whose upload stays in flight until the caller releases it. */+ /** Attach a file whose upload stays in flight until the caller releases it.+ * Controls the coordinator's `api.uploadFile` promise (MUL-5181 L2). */function startPendingUpload() {let release!: (result: unknown) => void;- mockUploadWithToast.mockImplementationOnce(+ mockApiUploadFile.mockImplementationOnce(() => new Promise((resolve) => { release = resolve; }),);fireEvent.click(screen.getByRole("button", { name: "Upload file" }));@@ -1247,7 +1431,15 @@ describe("CreateIssueModal", () => {await waitFor(() => expect(createButton).toBeDisabled());expect(createButton).toHaveAttribute("aria-busy", "true");- await act(async () => { pending.release({ id: "att-1", url: "https://cdn/x.png" }); });+ await act(async () => {+ pending.release({+ id: "att-1",+ url: "https://cdn/x.png",+ filename: "x.png",+ size_bytes: 1,+ content_type: "image/png",+ });+ });await waitFor(() =>expect(screen.getByRole("button", { name: "Create Issue" })).not.toBeDisabled(),);diff --git a/packages/views/modals/create-issue.tsx b/packages/views/modals/create-issue.tsxindex 71d4d466de..fa0213dde6 100644--- a/packages/views/modals/create-issue.tsx+++ b/packages/views/modals/create-issue.tsx@@ -1,6 +1,6 @@"use client";-import { useState, useRef, useEffect } from "react";+import { useState, useRef, useEffect, useLayoutEffect } from "react";import { useQuery } from "@tanstack/react-query";import { useNavigation } from "../navigation";import {@@ -30,7 +30,6 @@ import type {IssuePriority,IssueAssigneeType,IssuePropertyValue,- Attachment,} from "@multica/core/types";import { contentReferencesAttachment } from "@multica/core/types";import {@@ -50,7 +49,9 @@ import {import { Tooltip, TooltipTrigger, TooltipContent, TooltipProvider } from "@multica/ui/components/ui/tooltip";import { Button } from "@multica/ui/components/ui/button";import { Switch } from "@multica/ui/components/ui/switch";-import { ContentEditor, type ContentEditorRef, TitleEditor, type TitleEditorRef, useFileDropZone, FileDropOverlay, useUploadGate, useEditorUpload } from "../editor";+import { ContentEditor, type ContentEditorRef, TitleEditor, type TitleEditorRef, useFileDropZone, FileDropOverlay, useUploadGate, useComposerSubmit } from "../editor";+import { useIssueCreateUploads } from "./use-issue-create-uploads";+import { ComposerUploadChips } from "../issues/components/composer-upload-chips";import { useShortcut } from "@multica/core/shortcuts";import { ShortcutKeycaps } from "../common/shortcut-keycaps";import { StatusIcon, StatusPicker, PriorityIcon, PriorityPicker, StagePicker, AssigneePicker, StartDatePicker, DueDatePicker, LabelPicker } from "../issues/components";@@ -60,7 +61,7 @@ import { useIssueTriggerPreview } from "../issues/hooks/use-issue-trigger-previeimport { useActorName } from "@multica/core/workspace/hooks";import { useCurrentWorkspace, useWorkspacePaths } from "@multica/core/paths";import { useWorkspaceId } from "@multica/core/hooks";-import { useIssueDraftStore } from "@multica/core/issues/stores/draft-store";+import { useIssueDraftStore, type IssueCreateDraft } from "@multica/core/issues/stores/draft-store";import { useCreateModeStore } from "@multica/core/issues/stores/create-mode-store";import { useQuickCreateStore } from "@multica/core/issues/stores/quick-create-store";import {@@ -91,17 +92,6 @@ import {import { IssuePickerModal } from "./issue-picker-modal";import { useT } from "../i18n";-function toDraftAttachment(attachment: Attachment): Attachment {- return {- ...attachment,- // `download_url` is minted for the current API response and may be a- // short-lived signed URL. Drafts survive across dialog closes and app- // restarts, so persist only durable fields and let render/download paths- // re-resolve through id/markdown_url when needed.- download_url: "",- };-}-// ---------------------------------------------------------------------------// ManualCreatePanel — manual-mode body of the create-issue dialog. Renders// DialogContent + everything inside; the surrounding `<Dialog>` is owned by@@ -224,7 +214,10 @@ export function ManualCreatePanel({const workspaceName = useCurrentWorkspace()?.name;const draft = useIssueDraftStore((s) => s.draft);- const setDraft = useIssueDraftStore((s) => s.setDraft);+ const setManual = useIssueDraftStore((s) => s.setManual);+ const setShared = useIssueDraftStore((s) => s.setShared);+ const setAgent = useIssueDraftStore((s) => s.setAgent);+ const setActiveMode = useIssueDraftStore((s) => s.setActiveMode);const clearDraft = useIssueDraftStore((s) => s.clearDraft);const setLastAssignee = useIssueDraftStore((s) => s.setLastAssignee);const setLastMode = useCreateModeStore((s) => s.setLastMode);@@ -233,43 +226,41 @@ export function ManualCreatePanel({const manualFields = useIssueCreateSettingsStore((s) => s.manualCreateFields);const sendShortcut = useShortcut("send");- const [title, setTitle] = useState(draft.title);+ const [title, setTitle] = useState(draft.manual.title);const [formResetKey, setFormResetKey] = useState(0);const titleEditorRef = useRef<TitleEditorRef>(null);const descEditorRef = useRef<ContentEditorRef>(null);const { isDragOver: descDragOver, dropZoneProps: descDropZoneProps } = useFileDropZone({onDrop: (files) => files.forEach((f) => descEditorRef.current?.uploadFile(f)),});- const [status, setStatus] = useState<IssueStatus>((data?.status as IssueStatus) || draft.status);+ const [status, setStatus] = useState<IssueStatus>((data?.status as IssueStatus) || draft.manual.status);const [priority, setPriority] = useState<IssuePriority>(- (data?.priority as IssuePriority | undefined) ?? draft.priority,+ (data?.priority as IssuePriority | undefined) ?? draft.shared.priority,);- const [submitting, setSubmitting] = useState(false);- const submittingRef = useRef(false);const [assigneeType, setAssigneeType] = useState<IssueAssigneeType | undefined>(() => {if (data && "assignee_type" in data) {return (data.assignee_type as IssueAssigneeType | null) ?? undefined;}- return draft.assigneeType;+ return draft.manual.assigneeType;});const [assigneeId, setAssigneeId] = useState<string | undefined>(() => {if (data && "assignee_id" in data) {return (data.assignee_id as string | null) ?? undefined;}- return draft.assigneeId;+ return draft.manual.assigneeId;});- const [startDate, setStartDate] = useState<string | null>(draft.startDate);+ const [startDate, setStartDate] = useState<string | null>(draft.manual.startDate);const [dueDate, setDueDate] = useState<string | null>(- (data?.due_date as string | undefined) ?? draft.dueDate,+ (data?.due_date as string | undefined) ?? draft.shared.dueDate,);- const [labelIds, setLabelIds] = useState<string[]>(draft.labelIds);- const [propertyValues, setPropertyValues] = useState(draft.propertyValues ?? {});+ const [labelIds, setLabelIds] = useState<string[]>(draft.manual.labelIds);+ const [propertyValues, setPropertyValues] = useState(draft.manual.propertyValues ?? {});const [customPropertyPickerId, setCustomPropertyPickerId] = useState<string | null>(null);const [projectId, setProjectId] = useState<string | undefined>(() => {if (data && "project_id" in data) {return (data.project_id as string | null) ?? undefined;}- return draft.projectId;+ return draft.shared.projectId;});const [parentIssueId, setParentIssueId] = useState<string | undefined>((data?.parent_issue_id as string) || undefined,@@ -317,60 +308,68 @@ export function ManualCreatePanel({enabled: !!parentIssueId,});- const draftAttachments = draft.attachments ?? [];+ // Set the persisted draft's active mode so a later reopen (and any reader of+ // the unified draft) knows which form the user is editing in.+ useEffect(() => {+ setActiveMode("manual");+ }, [setActiveMode]);- // Prune draft attachments whose markdown reference was deleted in an+ // Prune completed uploads whose markdown reference was deleted in an// earlier editing session. Runs once on mount: at that point the persisted- // description IS the draft body (no editor edits have happened yet), so- // dropping unreferenced records is safe. Don't prune on description updates- // — an onUpdate flush can race a just-finished upload whose markdown link- // hasn't been inserted yet, and pruning there would drop a live attachment.+ // manual description / agent prompt ARE the draft bodies (no editor edits+ // have happened yet), so dropping `uploaded` records referenced by neither+ // is safe. Placeholders (uploading / failed / interrupted) are always kept —+ // they have no body reference yet and the status chips are their only UI.+ // Don't prune on description updates — an onUpdate flush can race a+ // just-finished upload whose markdown link hasn't been inserted yet, and+ // pruning there would drop a live attachment.useEffect(() => {const { draft: current } = useIssueDraftStore.getState();- const attachments = current.attachments ?? [];- const kept = attachments.filter((a) =>- contentReferencesAttachment(current.description, a),+ const uploads = current.shared.attachments ?? [];+ const kept = uploads.filter(+ (u) =>+ u.status !== "uploaded" ||+ contentReferencesAttachment(current.manual.description, u.attachment) ||+ contentReferencesAttachment(current.agent.prompt, u.attachment),);- if (kept.length !== attachments.length) setDraft({ attachments: kept });+ if (kept.length !== uploads.length) setShared({ attachments: kept });// eslint-disable-next-line react-hooks/exhaustive-deps}, []);- const { uploadWithToast } = useEditorUpload();// Gate every action that fixes this draft: Create and the switch to agent- // mode (which re-serializes the description into a- // prompt and would carry a stripped body across).+ // mode (which assist-inits the agent prompt from the description and would+ // carry a stripped body across).const uploadGate = useUploadGate(descEditorRef);- const handleUpload = async (file: File) => {- const result = await uploadWithToast(file);- if (result) {- const currentAttachments =- useIssueDraftStore.getState().draft.attachments ?? [];- const attachments = currentAttachments.some((a) => a.id === result.id)- ? currentAttachments- : [...currentAttachments, toDraftAttachment(result)];- setDraft({ attachments });- }- return result;- };+ // Coordinator-owned uploads in the shared pool (MUL-5181, L2): a file picked+ // here survives dialog close, aborts on logout, and reads `interrupted`+ // after a reload. `gate` widens the editor gate with the pool's placeholders.+ const {+ uploads: draftUploads,+ attachments: draftAttachments,+ handleUpload,+ removeUpload,+ gate,+ } = useIssueCreateUploads("manual", uploadGate, descEditorRef);- // Sync field changes to draft store- const updateTitle = (v: string) => { setTitle(v); setDraft({ title: v }); };- const updateStatus = (v: IssueStatus) => { setStatus(v); setDraft({ status: v }); };- const updatePriority = (v: IssuePriority) => { setPriority(v); setDraft({ priority: v }); };+ // Sync field changes to the draft store — manual-only fields to the manual+ // slot, project / priority / due date to the shared slot.+ const updateTitle = (v: string) => { setTitle(v); setManual({ title: v }); };+ const updateStatus = (v: IssueStatus) => { setStatus(v); setManual({ status: v }); };+ const updatePriority = (v: IssuePriority) => { setPriority(v); setShared({ priority: v }); };const updateAssignee = (type?: IssueAssigneeType, id?: string) => {setAssigneeType(type); setAssigneeId(id);- setDraft({ assigneeType: type, assigneeId: id });+ setManual({ assigneeType: type, assigneeId: id });};- const updateProject = (id?: string) => { setProjectId(id); setDraft({ projectId: id }); };- const updateStartDate = (v: string | null) => { setStartDate(v); setDraft({ startDate: v }); };- const updateDueDate = (v: string | null) => { setDueDate(v); setDraft({ dueDate: v }); };- const updateLabelIds = (ids: string[]) => { setLabelIds(ids); setDraft({ labelIds: ids }); };+ const updateProject = (id?: string) => { setProjectId(id); setShared({ projectId: id }); };+ const updateStartDate = (v: string | null) => { setStartDate(v); setManual({ startDate: v }); };+ const updateDueDate = (v: string | null) => { setDueDate(v); setShared({ dueDate: v }); };+ const updateLabelIds = (ids: string[]) => { setLabelIds(ids); setManual({ labelIds: ids }); };const updatePropertyValue = (propertyId: string, value: IssuePropertyValue | undefined) => {const next = { ...propertyValues };if (value === undefined) delete next[propertyId];else next[propertyId] = value;setPropertyValues(next);- setDraft({ propertyValues: next });+ setManual({ propertyValues: next });};// Inline pill reveal per toolbar field: kept by Settings → Issue, holding a@@ -412,40 +411,59 @@ export function ManualCreatePanel({setParentIssueId(undefined);setStage(null);setChildIssues([]);- setDraft({+ // Keep the just-used assignee for the next issue in the batch; reset+ // everything else across the manual + shared slots.+ setManual({title: "",description: "",status: "todo",- priority: "none",assigneeType,assigneeId,- projectId: undefined,startDate: null,- dueDate: null,labelIds: [],propertyValues: {},+ });+ setShared({+ priority: "none",+ projectId: undefined,+ dueDate: null,attachments: [],});descEditorRef.current?.clearContent();setFormResetKey((key) => key + 1);};- const handleSubmit = async () => {- // Single-flight on a ref, not `submitting`: two shortcut presses in one- // tick both read the pre-update state and would each fire a create. The- // ref flips synchronously, so the second press loses the race.- if (submittingRef.current) return;- if (!title.trim()) {- // The shortcut paths bypass the button entirely, so an empty title would- // otherwise be a silent no-op. Put the caret where the fix is; the- // button's tooltip says the rest.- titleEditorRef.current?.focus();- return;- }- if (uploadGate.isBlocked()) return;- submittingRef.current = true;- setSubmitting(true);- try {+ // Manual create runs through the shared await-then-render composer contract+ // (single-flight ref, submit-time upload re-check, lock+spin, await→boolean,+ // clear only on acceptance). Manual is gated on the TITLE rather than the+ // editor body — a title-only issue is valid — so `normalize` ignores the+ // description markdown and feeds the title through as the empty-guard/content;+ // the body is read separately inside onSubmit.+ // Stale-submit guard (MUL-5181 P0): the issue draft is a SINGLETON store+ // and the editors stay interactive during a request. Snapshot the draft's+ // object identity at submit; success clears ONLY an untouched draft —+ // whether the edit came mid-flight or from a reopened dialog.+ const mountedRef = useRef(true);+ useLayoutEffect(() => {+ mountedRef.current = true;+ return () => {+ mountedRef.current = false;+ };+ }, []);+ const submittedDraftRef = useRef<IssueCreateDraft | null>(null);++ const composer = useComposerSubmit({+ editorRef: descEditorRef,+ uploadGate: gate,+ normalize: () => title.trim(),+ onSubmit: async (): Promise<boolean> => {+ // Flush the description editor's pending debounce into the store BEFORE+ // snapshotting, so a late flush of pre-submit typing cannot masquerade+ // as an edit made during the request.+ const pendingDesc = descEditorRef.current?.flushPendingUpdate?.();+ if (pendingDesc != null) setManual({ description: pendingDesc });+ submittedDraftRef.current = useIssueDraftStore.getState().draft;+ try {const description = descEditorRef.current?.getMarkdown()?.trim() || undefined;const activeAttachmentIds = draftAttachments.filter((a) => contentReferencesAttachment(description ?? "", a))@@ -560,18 +578,9 @@ export function ManualCreatePanel({}}- setLastAssignee(assigneeType, assigneeId);- setLastMode("manual");- clearDraft();// The old post-create "agent paused in Backlog" blocking panel is gone —- // a passive inline hint now warns before submit (MUL-3375). Just close or- // reset and confirm the create.- if (keepOpen) {- resetForNextIssue();- } else {- onClose();- }-+ // a passive inline hint now warns before submit (MUL-3375). The draft+ // reset + close/keep-open happens in onAccepted once we report success.{toast.custom((toastId) => (<div className="bg-popover text-popover-foreground border rounded-lg shadow-lg p-4 w-[360px]">@@ -598,6 +607,7 @@ export function ManualCreatePanel({</div>), { duration: 5000 });}+ return true;} catch (err) {// Duplicate-issue is the only structured 409 the create endpoint// returns. We schema-guard the body (ApiError.body is `unknown`) so a@@ -639,7 +649,7 @@ export function ManualCreatePanel({),{ duration: 5000 },);- return;+ return false;}}toast.error(@@ -647,40 +657,82 @@ export function ManualCreatePanel({? err.message: t(($) => $.create_issue.toast_failed),);- } finally {- submittingRef.current = false;- setSubmitting(false);+ return false;+ }+ },+ onAccepted: () => {+ // These preferences derive from the SUBMITTED values, not the live+ // draft — an issue was created, so record them regardless of the guard.+ setLastAssignee(assigneeType, assigneeId);+ setLastMode("manual");+ // Success may only consume the draft it submitted (MUL-5181 P0): any+ // edit after the submit snapshot — typing while the request is in+ // flight, or a reopened dialog — survives, and the dialog then stays+ // open on the newer draft instead of closing/resetting over it. Flush+ // the editor's pending debounce first so mid-flight typing still inside+ // the debounce window is judged correctly.+ const lateDesc = descEditorRef.current?.flushPendingUpdate?.();+ if (lateDesc != null) setManual({ description: lateDesc });+ const untouched =+ useIssueDraftStore.getState().draft === submittedDraftRef.current;+ if (untouched) clearDraft();+ if (!mountedRef.current || !untouched) return;+ if (keepOpen) {+ resetForNextIssue();+ } else {+ onClose();+ }+ },+ });++ // Button + shortcut entry point. The title-empty case can't rely on the+ // button tooltip (shortcuts bypass the button), so focus the title to point+ // at the fix; otherwise hand off to the composer (single-flight + gate live+ // there).+ const handleSubmit = () => {+ if (!title.trim()) {+ titleEditorRef.current?.focus();+ return;}+ void composer.submit();};+ const submitting = composer.submitting;- // Switch to agent mode. Hand the typed text up to the shell as the carry- // payload; the shell stores it as the next panel's `data` so the agent- // panel reads `data.prompt` on mount. Concatenate title + description so- // nothing the user typed is lost — the agent derives a fresh title from- // the combined text. Persist the mode flip so the next `c` lands in agent.- // Also forward the picked project so the agent panel pins the new issue- // to it; without this the agent panel would fall back to its persisted- // `lastProjectId`, silently routing the issue to the wrong project.- // Forward squad picks alongside agent picks so the agent panel honors- // the actor the user already chose — otherwise a squad selection silently- // falls back to the persisted actor / first visible agent on flip.- // parent_issue_id rides through the same carry channel: the modal opener- // (openCreateSubIssue) seeded it on the manual panel, and the agent panel- // needs it so the new issue is still created as a sub-issue when the user- // flips from "Add sub issue" → "Create with agent".+ // Switch to agent mode WITHOUT destroying the manual draft. The manual slot+ // (title, description, …) is left untouched so a later agent→manual flip+ // restores it verbatim. Project / priority / due date already live in the+ // shared slot, so they carry across for free. Only two things are handed to+ // the agent panel:+ // 1. A one-time assist-init of the agent prompt / actor: when the agent+ // draft is still empty, seed the prompt from title + description and the+ // actor from the manual assignee (if agent-like). An existing agent+ // draft is preserved — no repeated concatenate-then-clobber.+ // 2. The parent-issue context, which is not persisted in the draft (it is a+ // per-invocation intent from "Add sub issue"), so it rides the carry.const switchToAgent = () => {// Serializing mid-upload packs a description that has already lost the- // pending image into the agent prompt, and the draft it came from is- // cleared below — the file would be unrecoverable.- if (uploadGate.isBlocked()) return;- const desc = descEditorRef.current?.getMarkdown()?.trim() ?? "";- const prompt = [title.trim(), desc].filter(Boolean).join("\n\n");- // Title + description have been packed into the agent prompt — clear them- // from the shared draft so a later agent→manual switch doesn't surface- // stale manual state on top of the prompt-as-description, which would- // duplicate content on every round-trip.- setDraft({ title: "", description: "" });+ // pending image into the agent prompt, so gate the switch too.+ if (gate.isBlocked()) return;+ // Commit the shared fields to the draft so the agent panel reads them from+ // there. Local state can hold a value seeded from `data` (e.g. an opener's+ // project) that was never written through a picker, so a plain flip would+ // otherwise drop it.+ setShared({ projectId, priority, dueDate });+ const existingPrompt = draft.agent.prompt;+ if (!existingPrompt.trim()) {+ const desc = descEditorRef.current?.getMarkdown()?.trim() ?? "";+ const seeded = [title.trim(), desc].filter(Boolean).join("\n\n");+ if (seeded) setAgent({ prompt: seeded });+ }+ if (+ !draft.agent.actorId &&+ assigneeId &&+ (assigneeType === "agent" || assigneeType === "squad")+ ) {+ setAgent({ actorType: assigneeType, actorId: assigneeId });+ }setLastMode("agent");+ setActiveMode("agent");// Prefer the hydrated identifier from `parentIssue`, but fall back to the// identifier the modal opener seeded on `data`. Without the fallback, a// flip that happens before the issue detail query resolves drops the@@ -689,19 +741,10 @@ export function ManualCreatePanel({// this only affects the display affordance.const carryParentIdentifier =parentIssue?.identifier ?? (data?.parent_issue_identifier as string | undefined);- onSwitchMode?.({- prompt,- ...(assigneeId && assigneeType === "agent"- ? { agent_id: assigneeId }- : assigneeId && assigneeType === "squad"- ? { squad_id: assigneeId }- : {}),- ...(projectId ? { project_id: projectId } : {}),- ...(priority !== "none" ? { priority } : {}),- ...(dueDate ? { due_date: dueDate } : {}),- ...(parentIssueId ? { parent_issue_id: parentIssueId } : {}),- ...(carryParentIdentifier ? { parent_issue_identifier: carryParentIdentifier } : {}),- });+ const carry: Record<string, unknown> = {};+ if (parentIssueId) carry.parent_issue_id = parentIssueId;+ if (carryParentIdentifier) carry.parent_issue_identifier = carryParentIdentifier;+ onSwitchMode?.(Object.keys(carry).length > 0 ? carry : null);};// One state for the button and the keyboard paths, so a rendered affordance@@ -709,7 +752,7 @@ export function ManualCreatePanel({const submitState: "submitting" | "uploading" | "missing_title" | "ready" =submitting? "submitting"- : uploadGate.uploading+ : gate.uploading? "uploading": !title.trim()? "missing_title"@@ -810,7 +853,7 @@ export function ManualCreatePanel({key={formResetKey}ref={titleEditorRef}autoFocus- defaultValue={draft.title}+ defaultValue={draft.manual.title}placeholder={t(($) => $.create_issue.title_placeholder)}className="text-lg font-semibold"onChange={(v) => updateTitle(v)}@@ -823,9 +866,9 @@ export function ManualCreatePanel({<div {...descDropZoneProps} className="relative flex flex-1 min-h-0 overflow-y-auto px-5"><ContentEditorref={descEditorRef}- defaultValue={draft.description}+ defaultValue={draft.manual.description}placeholder={t(($) => $.create_issue.description_placeholder)}- onUpdate={(md) => setDraft({ description: md })}+ onUpdate={(md) => setManual({ description: md })}onSubmit={handleSubmit}onUploadFile={handleUpload}onUploadingChange={uploadGate.onUploadingChange}@@ -835,6 +878,14 @@ export function ManualCreatePanel({{descDragOver && <FileDropOverlay />}</div>+ {draftUploads.some((u) => u.status !== "uploaded") && (+ <ComposerUploadChips+ uploads={draftUploads}+ onRemove={removeUpload}+ className="px-5 pb-1"+ />+ )}+{/* Pre-trigger preview — a passive caption above the toolbar; revealswhen an agent assignee will pick the issue up. */}<CreateRunHint assigneeType={assigneeType} assigneeId={assigneeId} status={status} />@@ -1199,9 +1250,9 @@ export function ManualCreatePanel({<buttontype="button"onClick={switchToAgent}- disabled={uploadGate.uploading}- aria-disabled={uploadGate.uploading || undefined}- aria-busy={uploadGate.uploading || undefined}+ disabled={gate.uploading}+ aria-disabled={gate.uploading || undefined}+ aria-busy={gate.uploading || undefined}title={t(($) => $.create_issue.switch_to_agent_tooltip)}className="border-beam group flex shrink-0 items-center gap-1.5 text-xs px-2 py-1 rounded-sm text-muted-foreground bg-brand/5 hover:bg-brand/10 hover:text-foreground transition-colors cursor-pointer disabled:cursor-not-allowed disabled:opacity-50">diff --git a/packages/views/modals/quick-create-issue.test.tsx b/packages/views/modals/quick-create-issue.test.tsxindex bcd7e43b58..671499739b 100644--- a/packages/views/modals/quick-create-issue.test.tsx+++ b/packages/views/modals/quick-create-issue.test.tsx@@ -7,31 +7,51 @@ const mockQuickCreateIssue = vi.hoisted(() => vi.fn());const mockSetLastActor = vi.hoisted(() => vi.fn());const mockSetLastProjectId = vi.hoisted(() => vi.fn());const mockSetQuickCreateFieldVisible = vi.hoisted(() => vi.fn());-const mockSetPrompt = vi.hoisted(() => vi.fn());-const mockClearPrompt = vi.hoisted(() => vi.fn());const mockSetKeepOpen = vi.hoisted(() => vi.fn());const mockSetLastMode = vi.hoisted(() => vi.fn());const mockToastSuccess = vi.hoisted(() => vi.fn());-const mockUploadWithToast = vi.hoisted(() => vi.fn());+// Uploads flow through the module-level coordinator, which calls+// `api.uploadFile(file, ctx, signal)` (MUL-5181 L2).+const mockApiUploadFile = vi.hoisted(() => vi.fn());const mockNavigationPush = vi.hoisted(() => vi.fn());-const mockSetIssueDraft = vi.hoisted(() => vi.fn());--const mockIssueDraftStore = {- draft: {+const mockSetShared = vi.hoisted(() => vi.fn());+const mockSetManual = vi.hoisted(() => vi.fn());+const mockSetAgent = vi.hoisted(() => vi.fn());+const mockSetActiveMode = vi.hoisted(() => vi.fn());+const mockClearDraft = vi.hoisted(() => vi.fn());++const emptyIssueDraft = () => ({+ shared: {+ projectId: undefined as string | undefined,+ priority: "none" as "none" | "low" | "medium" | "high" | "urgent",+ dueDate: null as string | null,+ attachments: [] as Array<{ id: string }>,+ },+ manual: {title: "",description: "",status: "todo" as const,- priority: "none" as const,+ startDate: null as string | null,assigneeType: undefined as "agent" | "squad" | "member" | undefined,assigneeId: undefined as string | undefined,- projectId: undefined as string | undefined,- startDate: null as string | null,- dueDate: null as string | null,labelIds: [] as string[],propertyValues: {} as Record<string, string | number | boolean | string[]>,- attachments: [],},- setDraft: mockSetIssueDraft,+ agent: {+ prompt: "",+ actorType: undefined as "agent" | "squad" | undefined,+ actorId: undefined as string | undefined,+ },+ activeMode: "agent" as "agent" | "manual",+});++const mockIssueDraftStore = {+ draft: emptyIssueDraft(),+ setShared: mockSetShared,+ setManual: mockSetManual,+ setAgent: mockSetAgent,+ setActiveMode: mockSetActiveMode,+ clearDraft: mockClearDraft,};const mockQuickCreateStore = {@@ -40,9 +60,6 @@ const mockQuickCreateStore = {setLastActor: mockSetLastActor,lastProjectId: null as string | null,setLastProjectId: mockSetLastProjectId,- prompt: "Persisted draft prompt",- setPrompt: mockSetPrompt,- clearPrompt: mockClearPrompt,keepOpen: false,setKeepOpen: mockSetKeepOpen,};@@ -94,6 +111,7 @@ vi.mock("@tanstack/react-query", () => ({vi.mock("@multica/core/api", () => ({api: {quickCreateIssue: mockQuickCreateIssue,+ uploadFile: mockApiUploadFile,},ApiError: class ApiError extends Error {body?: unknown;@@ -164,9 +182,6 @@ vi.mock("@multica/core/runtimes", () => ({MIN_QUICK_CREATE_CLI_VERSION: "1.0.0",}));-vi.mock("@multica/core/hooks/use-file-upload", () => ({- useFileUpload: () => ({ uploadWithToast: mockUploadWithToast, uploading: false }),-}));vi.mock("../issues/components/pickers/assignee-picker", () => ({canAssignAgent: () => true,@@ -222,6 +237,11 @@ vi.mock("../editor", async () => {const uploadGate = await vi.importActual<typeof import("../editor/use-upload-gate")>("../editor/use-upload-gate",);+ // Real composer submit contract — pure React, no network. Drives the+ // single-flight + upload-gate semantics against the mocked editor/api.+ const composer = await vi.importActual<typeof import("../editor/use-composer-submit")>(+ "../editor/use-composer-submit",+ );const ContentEditor = forwardRef(({ defaultValue, onUpdate, onSubmit, onUploadFile, onUploadingChange, placeholder }: any, ref: any) => {const valueRef = useRef(defaultValue || "");const [value, setValue] = useState(defaultValue || "");@@ -280,11 +300,7 @@ vi.mock("../editor", async () => {return {...uploadGate,- useEditorUpload: () => ({- uploadWithToast: mockUploadWithToast,- upload: vi.fn(),- uploading: false,- }),+ ...composer,ContentEditor,useFileDropZone: () => ({ isDragOver: false, dropZoneProps: {} }),FileDropOverlay: () => null,@@ -376,9 +392,10 @@ vi.mock("sonner", () => ({import { I18nProvider } from "@multica/core/i18n/react";import enCommon from "../locales/en/common.json";import enModals from "../locales/en/modals.json";+import enEditor from "../locales/en/editor.json";import { AgentCreatePanel } from "./quick-create-issue";-const TEST_RESOURCES = { en: { common: enCommon, modals: enModals } };+const TEST_RESOURCES = { en: { common: enCommon, modals: enModals, editor: enEditor } };function renderPanel(props: React.ComponentProps<typeof AgentCreatePanel>) {return render(@@ -395,30 +412,27 @@ describe("AgentCreatePanel", () => {mockQuickCreateStore.lastActorId = null;mockQuickCreateStore.lastProjectId = null;mockCreateSettingsStore.quickCreateFields = ["project"];- mockQuickCreateStore.prompt = "Persisted draft prompt";mockQuickCreateStore.keepOpen = false;- mockIssueDraftStore.draft = {- title: "",- description: "",- status: "todo",- priority: "none",- assigneeType: undefined,- assigneeId: undefined,- projectId: undefined,- startDate: null,- dueDate: null,- labelIds: [],- propertyValues: {},- attachments: [],- };- mockSetIssueDraft.mockImplementation((patch: Partial<typeof mockIssueDraftStore.draft>) => {- mockIssueDraftStore.draft = { ...mockIssueDraftStore.draft, ...patch };+ mockIssueDraftStore.draft = emptyIssueDraft();+ // The prompt now lives in the unified draft's agent slot.+ mockIssueDraftStore.draft.agent.prompt = "Persisted draft prompt";+ mockSetShared.mockImplementation((patch: Partial<typeof mockIssueDraftStore.draft.shared>) => {+ mockIssueDraftStore.draft.shared = { ...mockIssueDraftStore.draft.shared, ...patch };+ });+ mockSetManual.mockImplementation((patch: Partial<typeof mockIssueDraftStore.draft.manual>) => {+ mockIssueDraftStore.draft.manual = { ...mockIssueDraftStore.draft.manual, ...patch };+ });+ mockSetAgent.mockImplementation((patch: Partial<typeof mockIssueDraftStore.draft.agent>) => {+ mockIssueDraftStore.draft.agent = { ...mockIssueDraftStore.draft.agent, ...patch };+ });+ mockClearDraft.mockImplementation(() => {+ mockIssueDraftStore.draft = emptyIssueDraft();});mockProjectsQuery.data = [];mockProjectsQuery.isSuccess = true;mockSquadsData.list = [];mockQuickCreateIssue.mockResolvedValue(undefined);- mockUploadWithToast.mockResolvedValue({+ mockApiUploadFile.mockResolvedValue({id: "019ec09d-6222-722b-bdfa-427b105d80be",workspace_id: "ws-test",issue_id: null,@@ -469,10 +483,11 @@ describe("AgentCreatePanel", () => {await user.click(screen.getByTestId("priority-picker"));await user.click(screen.getByTestId("due-date-picker"));- expect(mockIssueDraftStore.draft).toEqual(+ expect(mockIssueDraftStore.draft.agent).toEqual(+ expect.objectContaining({ actorType: "squad", actorId: "squad-1" }),+ );+ expect(mockIssueDraftStore.draft.shared).toEqual(expect.objectContaining({- assigneeType: "squad",- assigneeId: "squad-1",projectId: "proj-1",priority: "high",dueDate: "2026-08-01",@@ -503,7 +518,7 @@ describe("AgentCreatePanel", () => {await user.clear(editor);await user.type(editor, "New agent prompt");- expect(mockSetPrompt).toHaveBeenLastCalledWith("New agent prompt");+ expect(mockSetAgent).toHaveBeenLastCalledWith({ prompt: "New agent prompt" });await user.click(screen.getByRole("button", { name: /^Create$/i }));@@ -519,14 +534,8 @@ describe("AgentCreatePanel", () => {// No project picked → persisted project preference is cleared so the// store stays in sync with the actual outgoing request.expect(mockSetLastProjectId).toHaveBeenCalledWith(null);- expect(mockSetIssueDraft).toHaveBeenLastCalledWith({- assigneeType: undefined,- assigneeId: undefined,- projectId: undefined,- priority: "none",- dueDate: null,- });- expect(mockClearPrompt).toHaveBeenCalled();+ // A successful create ends the whole unified draft.+ expect(mockClearDraft).toHaveBeenCalled();expect(mockSetLastMode).toHaveBeenCalledWith("agent");expect(onClose).toHaveBeenCalled();});@@ -563,7 +572,7 @@ describe("AgentCreatePanel", () => {fireEvent.change(editor, { target: { value: "Half-typed request" } });await user.click(screen.getByRole("button", { name: "Customize fields..." }));- expect(mockSetPrompt).toHaveBeenLastCalledWith("Half-typed request");+ expect(mockSetAgent).toHaveBeenLastCalledWith({ prompt: "Half-typed request" });expect(onClose).toHaveBeenCalled();expect(mockNavigationPush).toHaveBeenCalledWith("/ws-test/settings?tab=issue");});@@ -600,6 +609,90 @@ describe("AgentCreatePanel", () => {});});+ // MUL-5181 P0: success may only consume the draft it submitted — the editor+ // stays interactive during the request, so mid-flight edits must survive.+ it("typing draft B while draft A's quick-create is pending survives the success (mounted)", async () => {+ let resolveCreate!: (v: unknown) => void;+ mockQuickCreateIssue.mockImplementationOnce(+ () => new Promise((resolve) => { resolveCreate = resolve; }),+ );+ const onClose = vi.fn();+ renderPanel({ onClose, isExpanded: false, setIsExpanded: vi.fn() });+ const editor = screen.getByPlaceholderText(+ 'Tell the agent what to do, e.g. "let Bohan fix the inbox loading slowness in the Web project"',+ );+ fireEvent.change(editor, { target: { value: "Draft A prompt" } });+ fireEvent.click(screen.getByRole("button", { name: /^Create$/i }));+ await waitFor(() => expect(mockQuickCreateIssue).toHaveBeenCalled());++ // Mid-flight edit replaces the singleton draft's object identity.+ mockIssueDraftStore.draft = {+ ...emptyIssueDraft(),+ agent: { ...emptyIssueDraft().agent, prompt: "Draft B prompt" },+ };++ await act(async () => {+ resolveCreate(undefined);+ await Promise.resolve();+ });++ expect(mockClearDraft).not.toHaveBeenCalled();+ expect(onClose).not.toHaveBeenCalled();+ expect(mockIssueDraftStore.draft.agent.prompt).toBe("Draft B prompt");+ });++ // MUL-5181 P0: a submit that outlives its dialog may only consume the draft+ // it submitted — never one typed after closing and reopening.+ it("a late quick-create success does NOT clear a draft replaced after close", async () => {+ let resolveCreate!: (v: unknown) => void;+ mockQuickCreateIssue.mockImplementationOnce(+ () => new Promise((resolve) => { resolveCreate = resolve; }),+ );+ const view = renderPanel({ onClose: vi.fn(), isExpanded: false, setIsExpanded: vi.fn() });+ const editor = screen.getByPlaceholderText(+ 'Tell the agent what to do, e.g. "let Bohan fix the inbox loading slowness in the Web project"',+ );+ fireEvent.change(editor, { target: { value: "Draft A prompt" } });+ fireEvent.click(screen.getByRole("button", { name: /^Create$/i }));+ await waitFor(() => expect(mockQuickCreateIssue).toHaveBeenCalled());++ view.unmount();+ mockIssueDraftStore.draft = {+ ...emptyIssueDraft(),+ agent: { ...emptyIssueDraft().agent, prompt: "Draft B prompt" },+ };++ await act(async () => {+ resolveCreate(undefined);+ await Promise.resolve();+ });++ expect(mockClearDraft).not.toHaveBeenCalled();+ expect(mockIssueDraftStore.draft.agent.prompt).toBe("Draft B prompt");+ });++ it("a late quick-create success still clears an untouched draft", async () => {+ let resolveCreate!: (v: unknown) => void;+ mockQuickCreateIssue.mockImplementationOnce(+ () => new Promise((resolve) => { resolveCreate = resolve; }),+ );+ const view = renderPanel({ onClose: vi.fn(), isExpanded: false, setIsExpanded: vi.fn() });+ const editor = screen.getByPlaceholderText(+ 'Tell the agent what to do, e.g. "let Bohan fix the inbox loading slowness in the Web project"',+ );+ fireEvent.change(editor, { target: { value: "Draft A prompt" } });+ fireEvent.click(screen.getByRole("button", { name: /^Create$/i }));+ await waitFor(() => expect(mockQuickCreateIssue).toHaveBeenCalled());++ view.unmount();+ await act(async () => {+ resolveCreate(undefined);+ await Promise.resolve();+ });++ expect(mockClearDraft).toHaveBeenCalled();+ });+it("passes referenced upload attachment ids to quick-create", async () => {const user = userEvent.setup();const onClose = vi.fn();@@ -607,7 +700,7 @@ describe("AgentCreatePanel", () => {renderPanel({ onClose, isExpanded: false, setIsExpanded: vi.fn() });await user.click(screen.getByRole("button", { name: "Mock editor upload" }));- await waitFor(() => expect(mockUploadWithToast).toHaveBeenCalled());+ await waitFor(() => expect(mockApiUploadFile).toHaveBeenCalled());const editor = screen.getByPlaceholderText('Tell the agent what to do, e.g. "let Bohan fix the inbox loading slowness in the Web project"',@@ -767,7 +860,7 @@ describe("AgentCreatePanel", () => {describe("upload submit gate", () => {function startPendingUpload() {let release!: (result: unknown) => void;- mockUploadWithToast.mockImplementationOnce(+ mockApiUploadFile.mockImplementationOnce(() => new Promise((resolve) => { release = resolve; }),);fireEvent.click(screen.getByRole("button", { name: "Mock editor upload" }));diff --git a/packages/views/modals/quick-create-issue.tsx b/packages/views/modals/quick-create-issue.tsxindex 0856dad66b..0e4721fa36 100644--- a/packages/views/modals/quick-create-issue.tsx+++ b/packages/views/modals/quick-create-issue.tsx@@ -1,6 +1,6 @@"use client";-import { useCallback, useEffect, useMemo, useRef, useState } from "react";+import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";import {ArrowLeftRight,CalendarDays,@@ -39,7 +39,7 @@ import {useIssueCreateSettingsStore,type QuickCreateField,} from "@multica/core/issues/stores/issue-create-settings-store";-import { useIssueDraftStore } from "@multica/core/issues/stores/draft-store";+import { useIssueDraftStore, type IssueCreateDraft } from "@multica/core/issues/stores/draft-store";import { useCreateModeStore } from "@multica/core/issues/stores/create-mode-store";import {runtimeListOptions,@@ -52,7 +52,6 @@ import { ShortcutKeycaps } from "../common/shortcut-keycaps";import {contentReferencesAttachment,type Agent,- type Attachment,type IssuePriority,type Squad,} from "@multica/core/types";@@ -75,8 +74,10 @@ import {useFileDropZone,FileDropOverlay,useUploadGate,- useEditorUpload,+ useComposerSubmit,} from "../editor";+import { useIssueCreateUploads } from "./use-issue-create-uploads";+import { ComposerUploadChips } from "../issues/components/composer-upload-chips";import { FileUploadButton } from "@multica/ui/components/common/file-upload-button";import { useT } from "../i18n";import { matchesPinyin } from "../editor/extensions/pinyin-match";@@ -164,14 +165,18 @@ export function AgentCreatePanel({const lastProjectId = useQuickCreateStore((s) => s.lastProjectId);const setLastProjectId = useQuickCreateStore((s) => s.setLastProjectId);const visibleFields = useIssueCreateSettingsStore((s) => s.quickCreateFields);- const promptDraft = useQuickCreateStore((s) => s.prompt);- const setPrompt = useQuickCreateStore((s) => s.setPrompt);- const clearPrompt = useQuickCreateStore((s) => s.clearPrompt);const keepOpen = useQuickCreateStore((s) => s.keepOpen);const setKeepOpen = useQuickCreateStore((s) => s.setKeepOpen);const setLastMode = useCreateModeStore((s) => s.setLastMode);- const selectionDraft = useIssueDraftStore((s) => s.draft);- const setSelectionDraft = useIssueDraftStore((s) => s.setDraft);+ // The agent draft (prompt + actor) and the shared fields (project, priority,+ // due date, attachments) live in the unified issue-create draft, so a switch+ // to/from the manual form preserves them.+ const draft = useIssueDraftStore((s) => s.draft);+ const setShared = useIssueDraftStore((s) => s.setShared);+ const setManual = useIssueDraftStore((s) => s.setManual);+ const setAgent = useIssueDraftStore((s) => s.setAgent);+ const setActiveMode = useIssueDraftStore((s) => s.setActiveMode);+ const clearDraft = useIssueDraftStore((s) => s.clearDraft);// Resolve a candidate actor against the currently-visible agents / squads.// Returns null when the candidate doesn't exist in this workspace right@@ -196,20 +201,14 @@ export function AgentCreatePanel({const seedActor = useCallback((): ActorSelection | null => {// Caller-provided seed wins (e.g. shell pre-seeds with `agent_id` /- // `squad_id`), then the unfinished draft, the last successful pick, and- // finally the first visible agent.+ // `squad_id`), then the persisted agent draft, the last successful pick,+ // and finally the first visible agent.const dataAgent = data?.agent_id as string | undefined;const dataSquad = data?.squad_id as string | undefined;return (resolveActor("agent", dataAgent) ||resolveActor("squad", dataSquad) ||- resolveActor(- selectionDraft.assigneeType === "agent" ||- selectionDraft.assigneeType === "squad"- ? selectionDraft.assigneeType- : null,- selectionDraft.assigneeId,- ) ||+ resolveActor(draft.agent.actorType, draft.agent.actorId) ||resolveActor(lastActorType, lastActorId) ||(visibleAgents[0]? ({ type: "agent", id: visibleAgents[0].id } as const)@@ -219,8 +218,8 @@ export function AgentCreatePanel({resolveActor,data?.agent_id,data?.squad_id,- selectionDraft.assigneeType,- selectionDraft.assigneeId,+ draft.agent.actorType,+ draft.agent.actorId,lastActorType,lastActorId,visibleAgents,@@ -247,21 +246,21 @@ export function AgentCreatePanel({return visibleSquads.find((s) => s.id === actor.id);}, [actor, visibleSquads]);- // Unfinished selections live in the shared issue draft. Last-successful+ // Unfinished selections live in the shared issue-create draft. Last-successful// actor/project values remain separate fallbacks, so closing a draft never// overwrites the defaults established by an actual create.const [projectId, setProjectId] = useState<string | null>(() => {const seed =(data?.project_id as string | undefined) ??- selectionDraft.projectId ??+ draft.shared.projectId ??lastProjectId;return seed ?? null;});const [priority, setPriority] = useState<IssuePriority>(- (data?.priority as IssuePriority | undefined) ?? selectionDraft.priority,+ (data?.priority as IssuePriority | undefined) ?? draft.shared.priority,);const [dueDate, setDueDate] = useState<string | null>(- (data?.due_date as string | undefined) ?? selectionDraft.dueDate,+ (data?.due_date as string | undefined) ?? draft.shared.dueDate,);const [fieldPickerOpen, setFieldPickerOpen] = useState<QuickCreateField | null>(null);@@ -285,20 +284,26 @@ export function AgentCreatePanel({if (!projectsLoaded || projectId === null) return;if (projects.some((p) => p.id === projectId)) return;setProjectId(null);- if (selectionDraft.projectId === projectId) {- setSelectionDraft({ projectId: undefined });+ if (draft.shared.projectId === projectId) {+ setShared({ projectId: undefined });}if (lastProjectId === projectId) setLastProjectId(null);}, [projectsLoaded,projects,projectId,- selectionDraft.projectId,+ draft.shared.projectId,lastProjectId,- setSelectionDraft,+ setShared,setLastProjectId,]);+ // Mark the persisted draft's active mode so a later reopen and any reader of+ // the unified draft know which form is being edited.+ useEffect(() => {+ setActiveMode("agent");+ }, [setActiveMode]);+// Daemon CLI version gate. The agent-create flow needs the runtime's// bundled multica CLI to be ≥ MIN_QUICK_CREATE_CLI_VERSION; older// daemons handle attachments and partial-failure retries incorrectly@@ -331,38 +336,27 @@ export function AgentCreatePanel({baseVersionCheck.state !== "ok" ||(usesExplicitFields && fieldVersionCheck.state !== "ok");- const initialPrompt = (data?.prompt as string) || promptDraft;+ const initialPrompt = draft.agent.prompt || (data?.prompt as string) || "";// The editor is uncontrolled — we read the latest markdown via the ref at// submit/switch time. `hasContent` mirrors emptiness so the Create button// can disable correctly without a controlled-input rerender on every keystroke.const editorRef = useRef<ContentEditorRef>(null);const [hasContent, setHasContent] = useState(initialPrompt.trim().length > 0);- const [submitting, setSubmitting] = useState(false);- // See create-issue's handleSubmit: `submitting` state can't gate two presses- // landing in the same tick, and ⌘+Enter makes that trivial to hit.- const submittingRef = useRef(false);const [justSent, setJustSent] = useState(false);const [sentCount, setSentCount] = useState(0);const [error, setError] = useState<string | null>(null);- const [pendingAttachments, setPendingAttachments] = useState<Attachment[]>([]);-- // Image paste/drop support: route uploads through the same helper Advanced- // uses, so users can paste screenshots straight into the prompt and the- // agent receives them as embedded markdown image URLs in the prompt.- const { uploadWithToast } = useEditorUpload();- // Was two parallel truths — useFileUpload's request counter for the button- // and the editor's node scan for the handler. The editor document is the- // queue, so one source drives both now.const uploadGate = useUploadGate(editorRef);- const handleUploadFile = useCallback(async (file: File) => {- const result = await uploadWithToast(file);- if (result) {- setPendingAttachments((prev) =>- prev.some((a) => a.id === result.id) ? prev : [...prev, result],- );- }- return result;- }, [uploadWithToast]);+ // Coordinator-owned uploads in the shared draft pool (MUL-5181, L2): a file+ // pasted into the prompt survives dialog close and mode switches, aborts on+ // logout, and reads `interrupted` after a reload. `gate` widens the editor+ // gate with the pool's placeholders.+ const {+ uploads: draftUploads,+ attachments: pendingAttachments,+ handleUpload: handleUploadFile,+ removeUpload,+ gate,+ } = useIssueCreateUploads("agent", uploadGate, editorRef);const { isDragOver, dropZoneProps } = useFileDropZone({onDrop: (files) => files.forEach((f) => editorRef.current?.uploadFile(f)),});@@ -375,54 +369,113 @@ export function AgentCreatePanel({return () => cancelAnimationFrame(id);}, []);- const submit = async () => {- const md = editorRef.current?.getMarkdown()?.trim() ?? "";- if (!md || !actor || submittingRef.current || versionBlocked) return;- // Submit-time re-read of the queue. Blocking here is what guarantees- // `getMarkdown()`'s blob-url strip never erases a pasted/dropped image- // whose attachment id hasn't reached `pendingAttachments` yet — the- // rendered button state is a frame behind and ⌘+Enter skips it anyway.- if (uploadGate.isBlocked()) return;- const activeAttachmentIds = pendingAttachments- .filter((a) => contentReferencesAttachment(md, a))- .map((a) => a.id);- submittingRef.current = true;- setSubmitting(true);- setError(null);- try {- await api.quickCreateIssue({- ...(actor.type === "agent"- ? { agent_id: actor.id }- : { squad_id: actor.id }),- prompt: md,- project_id: projectId ?? undefined,- ...(priority !== "none" ? { priority } : {}),- ...(dueDate ? { due_date: dueDate } : {}),- parent_issue_id: parentIssueId,- ...(activeAttachmentIds.length > 0 ? { attachment_ids: activeAttachmentIds } : {}),- });- setLastActor(actor.type, actor.id);- setLastProjectId(projectId);- // A successful create ends this draft. Keep last-successful actor and- // project preferences above, but clear the unfinished selections so a- // future draft does not inherit priority or due date accidentally.- setSelectionDraft({- assigneeType: undefined,- assigneeId: undefined,- projectId: undefined,- priority: "none",- dueDate: null,- });- clearPrompt();- setLastMode("agent");- toast.success(t(($) => $.create_issue.agent.toast_sent), {- duration: 4000,- });+ // Agent create runs through the shared await-then-render composer contract+ // (single-flight ref, submit-time upload re-check, lock+spin, await→boolean,+ // clear only on acceptance). The prompt IS the editor content, so this maps+ // onto the hook directly.+ // Stale-submit guard (MUL-5181 P0): the issue draft is a SINGLETON store.+ // A late success from a dialog the user closed mid-submit must not clear a+ // newer draft typed after reopening — see ManualCreatePanel for the rule.+ const mountedRef = useRef(true);+ useLayoutEffect(() => {+ mountedRef.current = true;+ return () => {+ mountedRef.current = false;+ };+ }, []);+ const submittedDraftRef = useRef<IssueCreateDraft | null>(null);++ const composer = useComposerSubmit({+ editorRef,+ uploadGate: gate,+ onSubmit: async (md): Promise<boolean> => {+ // The button already disables on !actor / versionBlocked, but the+ // ⌘+Enter path bypasses it — re-guard here and keep the draft in place.+ if (!actor || versionBlocked) return false;+ // Flush the prompt editor's pending debounce before snapshotting — see+ // ManualCreatePanel.+ const pendingPrompt = editorRef.current?.flushPendingUpdate?.();+ if (pendingPrompt != null) setAgent({ prompt: pendingPrompt });+ submittedDraftRef.current = useIssueDraftStore.getState().draft;+ const activeAttachmentIds = pendingAttachments+ .filter((a) => contentReferencesAttachment(md, a))+ .map((a) => a.id);+ setError(null);+ try {+ await api.quickCreateIssue({+ ...(actor.type === "agent"+ ? { agent_id: actor.id }+ : { squad_id: actor.id }),+ prompt: md,+ project_id: projectId ?? undefined,+ ...(priority !== "none" ? { priority } : {}),+ ...(dueDate ? { due_date: dueDate } : {}),+ parent_issue_id: parentIssueId,+ ...(activeAttachmentIds.length > 0 ? { attachment_ids: activeAttachmentIds } : {}),+ });+ setLastActor(actor.type, actor.id);+ setLastProjectId(projectId);+ setLastMode("agent");+ toast.success(t(($) => $.create_issue.agent.toast_sent), {+ duration: 4000,+ });+ return true;+ } catch (e) {+ // Server returns 422 with { code, ... } for the structured rejection+ // paths the modal cares about. Surface the reason in-modal so the+ // user can switch to a live agent / upgrade their daemon without+ // leaving the flow.+ if (e instanceof ApiError && e.body && typeof e.body === "object") {+ const body = e.body as {+ code?: string;+ reason?: string;+ current_version?: string;+ min_version?: string;+ };+ if (body.code === "agent_unavailable") {+ setError(body.reason || t(($) => $.create_issue.agent.error_agent_unavailable_fallback));+ return false;+ }+ if (body.code === "daemon_version_unsupported") {+ // Race fallback: the picker pre-check should normally catch this,+ // but a runtime can silently re-register with an older CLI between+ // pre-check and submit. Same wording as the inline notice for+ // consistency.+ const cur = body.current_version || "unknown";+ setError(+ t(($) => $.create_issue.agent.error_daemon_version, {+ current: cur,+ min: body.min_version || versionCheck.min,+ }),+ );+ return false;+ }+ }+ setError(+ e instanceof Error && e.message+ ? e.message+ : t(($) => $.create_issue.agent.error_unknown),+ );+ return false;+ }+ },+ onAccepted: () => {+ // A successful create ends this whole draft (shared + manual + agent);+ // last-successful actor/project preferences were saved in onSubmit.+ // Success may only consume the draft it submitted: flush the editor's+ // pending debounce first, then clear only an untouched draft — edits+ // made mid-flight or by a reopened dialog survive.+ const latePrompt = editorRef.current?.flushPendingUpdate?.();+ if (latePrompt != null) setAgent({ prompt: latePrompt });+ const untouched =+ useIssueDraftStore.getState().draft === submittedDraftRef.current;+ if (untouched) clearDraft();+ // An edit made during the request survives; the panel stays open on it.+ if (!mountedRef.current || !untouched) return;if (keepOpen) {- // Stay open for continuous creation — clear the editor so the- // user can immediately type the next prompt.+ // Stay open for continuous creation — clear the editor so the user can+ // immediately type the next prompt.editorRef.current?.clearContent();- setPendingAttachments([]);setHasContent(false);setSentCount((c) => c + 1);setJustSent(true);@@ -431,78 +484,38 @@ export function AgentCreatePanel({} else {onClose();}- } catch (e) {- // Server returns 422 with { code, ... } for the structured rejection- // paths the modal cares about. Surface the reason in-modal so the- // user can switch to a live agent / upgrade their daemon without- // leaving the flow.- if (e instanceof ApiError && e.body && typeof e.body === "object") {- const body = e.body as {- code?: string;- reason?: string;- current_version?: string;- min_version?: string;- };- if (body.code === "agent_unavailable") {- setError(body.reason || t(($) => $.create_issue.agent.error_agent_unavailable_fallback));- setSubmitting(false);- return;- }- if (body.code === "daemon_version_unsupported") {- // Race fallback: the picker pre-check should normally catch this,- // but a runtime can silently re-register with an older CLI between- // pre-check and submit. Same wording as the inline notice for- // consistency.- const cur = body.current_version || "unknown";- setError(- t(($) => $.create_issue.agent.error_daemon_version, {- current: cur,- min: body.min_version || versionCheck.min,- }),- );- setSubmitting(false);- return;- }- }- setError(- e instanceof Error && e.message- ? e.message- : t(($) => $.create_issue.agent.error_unknown),- );- } finally {- submittingRef.current = false;- setSubmitting(false);- }+ },+ });+ const submit = () => {+ void composer.submit();};-- // Switch to the manual form, carrying what the user typed over as the- // description (markdown, including any pasted images) so they don't lose- // their work. The picked actor (agent or squad) becomes the default- // assignee candidate (still editable). We seed the shared issue-draft- // store directly because the manual panel reads its initial values from- // there. Persist the mode flip so the next `c` lands in manual.+ const submitting = composer.submitting;++ // Switch to the manual form WITHOUT destroying the agent draft. The agent+ // slot (prompt + actor) is left untouched so a later manual→agent flip+ // restores it verbatim. Project / priority / due date already live in the+ // shared slot and carry across for free. Two one-time assist-inits run only+ // when the manual slot is still empty: seed the description from the prompt+ // and the assignee from the picked actor. The parent-issue context is not+ // persisted (a per-invocation intent) so it rides the carry channel.const switchToManual = () => {- // The prompt is serialized into the manual draft here; mid-upload that- // body has already lost the pending image (see switchToAgent).- if (uploadGate.isBlocked()) return;- const md = editorRef.current?.getMarkdown() ?? "";- useIssueDraftStore.getState().setDraft({- description: md,- ...(actor- ? { assigneeType: actor.type, assigneeId: actor.id }- : {}),- });+ // The prompt is copied into the manual description on assist-init; mid-upload+ // that body has already lost the pending image (see switchToAgent).+ if (gate.isBlocked()) return;+ // Commit the shared fields to the draft so the manual panel reads them from+ // there — local state can hold a value seeded from `data` that was never+ // written through a picker.+ setShared({ projectId: projectId ?? undefined, priority, dueDate });+ if (!draft.manual.description.trim()) {+ const md = editorRef.current?.getMarkdown() ?? "";+ if (md) setManual({ description: md });+ }+ if (!draft.manual.assigneeId && actor) {+ setManual({ assigneeType: actor.type, assigneeId: actor.id });+ }setLastMode("manual");- // Hand the picked project and the parent-issue context to the manual- // panel through the same `data` channel that already carries agent_id /- // parent_issue_id. The manual panel reads these on mount; this preserves- // the user's selection (and the sub-issue intent seeded by- // openCreateSubIssue) across the mode flip without piping a third store- // through.+ setActiveMode("manual");const carry: Record<string, unknown> = {};- if (projectId) carry.project_id = projectId;- if (priority !== "none") carry.priority = priority;- if (dueDate) carry.due_date = dueDate;if (parentIssueId) carry.parent_issue_id = parentIssueId;if (parentIssueIdentifier) carry.parent_issue_identifier = parentIssueIdentifier;onSwitchMode?.(Object.keys(carry).length > 0 ? carry : null);@@ -512,7 +525,7 @@ export function AgentCreatePanel({// before leaving so what the user typed survives the round-trip, then// close — the dialog would otherwise linger over the settings page.const openFieldSettings = () => {- setPrompt(editorRef.current?.getMarkdown() ?? "");+ setAgent({ prompt: editorRef.current?.getMarkdown() ?? "" });onClose();navigation.push(`${workspacePaths.settings()}?tab=issue`);};@@ -567,7 +580,7 @@ export function AgentCreatePanel({selectedSquad={selectedSquad}onPick={(next) => {setActor(next);- setSelectionDraft({ assigneeType: next.type, assigneeId: next.id });+ setAgent({ actorType: next.type, actorId: next.id });setError(null);}}t={t}@@ -602,7 +615,7 @@ export function AgentCreatePanel({placeholder={t(($) => $.create_issue.agent.prompt_placeholder)}onUpdate={(md) => {setHasContent(md.trim().length > 0);- setPrompt(md);+ setAgent({ prompt: md });}}onUploadFile={handleUploadFile}onUploadingChange={uploadGate.onUploadingChange}@@ -613,6 +626,14 @@ export function AgentCreatePanel({{isDragOver && <FileDropOverlay />}</div>+ {draftUploads.some((u) => u.status !== "uploaded") && (+ <ComposerUploadChips+ uploads={draftUploads}+ onRemove={removeUpload}+ className="px-5 pb-1"+ />+ )}+{error && (<div className="px-5 pb-2 text-xs text-destructive">{error}</div>)}@@ -636,7 +657,7 @@ export function AgentCreatePanel({onUpdate={(u) => {const next = u.project_id ?? null;setProjectId(next);- setSelectionDraft({ projectId: next ?? undefined });+ setShared({ projectId: next ?? undefined });}}triggerRender={<PillButton />}align="start"@@ -652,7 +673,7 @@ export function AgentCreatePanel({onUpdate={(updates) => {if (updates.priority) {setPriority(updates.priority);- setSelectionDraft({ priority: updates.priority });+ setShared({ priority: updates.priority });}}}triggerRender={<PillButton />}@@ -669,7 +690,7 @@ export function AgentCreatePanel({onUpdate={(updates) => {const next = updates.due_date ?? null;setDueDate(next);- setSelectionDraft({ dueDate: next });+ setShared({ dueDate: next });}}triggerRender={<PillButton />}align="start"@@ -750,9 +771,9 @@ export function AgentCreatePanel({<buttontype="button"onClick={switchToManual}- disabled={uploadGate.uploading}- aria-disabled={uploadGate.uploading || undefined}- aria-busy={uploadGate.uploading || undefined}+ disabled={gate.uploading}+ aria-disabled={gate.uploading || undefined}+ aria-busy={gate.uploading || undefined}title={t(($) => $.create_issue.switch_to_manual_tooltip)}className="flex shrink-0 items-center gap-1.5 text-xs px-2 py-1 rounded-sm text-muted-foreground hover:text-foreground hover:bg-accent/60 transition-colors cursor-pointer disabled:cursor-not-allowed disabled:opacity-50">@@ -770,10 +791,10 @@ export function AgentCreatePanel({<Buttonsize="sm"onClick={submit}- disabled={!hasContent || !actor || submitting || versionBlocked || uploadGate.uploading}- aria-disabled={uploadGate.uploading || undefined}+ disabled={!hasContent || !actor || submitting || versionBlocked || gate.uploading}+ aria-disabled={gate.uploading || undefined}// Sending is a busy state too, not just uploading.- aria-busy={uploadGate.uploading || submitting || undefined}+ aria-busy={gate.uploading || submitting || undefined}title={versionBlocked? t(($) => $.create_issue.agent.version_blocked_tooltip, { min: versionCheck.min })@@ -781,7 +802,7 @@ export function AgentCreatePanel({}className={justSent ? "min-w-28 !bg-emerald-600 !text-white" : "min-w-28"}>- {submitting ? t(($) => $.create_issue.agent.sending) : uploadGate.uploading ? t(($) => $.create_issue.agent.uploading) : justSent ? (+ {submitting ? t(($) => $.create_issue.agent.sending) : gate.uploading ? t(($) => $.create_issue.agent.uploading) : justSent ? (<span className="flex items-center gap-1"><Check className="size-3.5" />{t(($) => $.create_issue.agent.sent_label)}</span>) : (<>diff --git a/packages/views/modals/use-issue-create-uploads.ts b/packages/views/modals/use-issue-create-uploads.tsnew file mode 100644index 0000000000..4fdd9dc2d7--- /dev/null+++ b/packages/views/modals/use-issue-create-uploads.ts@@ -0,0 +1,110 @@+"use client";++/**+ * Issue-create binding for the coordinated-upload engine (MUL-5181, L2).+ *+ * Both create panels (manual form and agent prompt) share ONE upload pool —+ * `draft.shared.attachments` — so a file survives a mode switch from either+ * side. What differs per mode is the BODY the upload's link belongs to: the+ * manual description or the agent prompt. The binding captures the mode that+ * started the upload, so a settle that arrives after the dialog closed (or+ * after the user flipped modes) writes the link back into the body it was+ * pasted into, never the other side's.+ *+ * Uploads here carry no issue/comment context — the issue does not exist yet;+ * the server binds attachments at create time from `attachment_ids`.+ */++import { useMemo, type RefObject } from "react";+import { attachmentToDraftUpload, type DraftUpload } from "@multica/core/drafts";+import { useIssueDraftStore } from "@multica/core/issues/stores";+import type { CreateMode } from "@multica/core/issues/stores";+import type { UploadGate } from "../editor/use-upload-gate";+import type { ContentEditorRef } from "../editor/content-editor";+import {+ useCoordinatedUploads,+ type CoordinatedUploads,+ type UploadDraftBinding,+} from "../editor/use-coordinated-uploads";++function appendMarkdown(existing: string, markdown: string): string {+ return existing.trim() ? `${existing.replace(/\s+$/, "")}\n\n${markdown}` : markdown;+}++function sharedUploads(): DraftUpload[] {+ return useIssueDraftStore.getState().draft.shared.attachments ?? [];+}++function setSharedUploads(next: DraftUpload[]): void {+ useIssueDraftStore.getState().setShared({ attachments: next });+}++export function useIssueCreateUploads(+ mode: CreateMode,+ editorGate: UploadGate,+ editorRef: RefObject<ContentEditorRef | null>,+): CoordinatedUploads {+ const uploads = useIssueDraftStore((s) => s.draft.shared.attachments);++ const binding = useMemo<UploadDraftBinding>(+ () => ({+ registryKey: `issue-create:${mode}`,+ getUploads: sharedUploads,+ addUpload: (u) => {+ const cur = sharedUploads();+ if (cur.some((x) => x.clientUploadId === u.clientUploadId)) return;+ setSharedUploads([...cur, u]);+ },+ settleUpload: (id, att) => {+ const cur = sharedUploads();+ if (!cur.some((u) => u.clientUploadId === id)) return;+ // attachmentToDraftUpload strips the response-scoped signed+ // download_url before the row is persisted.+ setSharedUploads(+ cur.map((u) =>+ u.clientUploadId === id ? { ...attachmentToDraftUpload(att), clientUploadId: id } : u,+ ),+ );+ },+ failUpload: (id, error) => {+ const cur = sharedUploads();+ const target = cur.find((u) => u.clientUploadId === id);+ if (!target) return;+ setSharedUploads(+ cur.map((u) =>+ u.clientUploadId === id+ ? {+ clientUploadId: id,+ status: "failed",+ filename: target.filename,+ size: target.size,+ contentType: target.contentType,+ error,+ }+ : u,+ ),+ );+ },+ removeUpload: (id) => {+ const cur = sharedUploads();+ if (!cur.some((u) => u.clientUploadId === id)) return;+ setSharedUploads(cur.filter((u) => u.clientUploadId !== id));+ },+ getBody: () => {+ const { draft } = useIssueDraftStore.getState();+ return mode === "agent" ? draft.agent.prompt : draft.manual.description;+ },+ appendToBody: (md) => {+ const state = useIssueDraftStore.getState();+ if (mode === "agent") {+ state.setAgent({ prompt: appendMarkdown(state.draft.agent.prompt, md) });+ } else {+ state.setManual({ description: appendMarkdown(state.draft.manual.description, md) });+ }+ },+ }),+ [mode],+ );++ return useCoordinatedUploads(binding, uploads, {}, editorGate, editorRef);+}