Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go

feat(views): block draft-fixing actions while attachments upload (#5465)

Naiyuan Qing3b08456264d1
diff --git a/packages/core/hooks/use-file-upload.ts b/packages/core/hooks/use-file-upload.ts
index ee723f2dd4..8338ef9d0b 100644
--- a/packages/core/hooks/use-file-upload.ts
+++ b/packages/core/hooks/use-file-upload.ts
@@ -82,7 +82,12 @@ function pickMarkdownLink(att: Attachment): string {
export function useFileUpload(
api: ApiClient,
- onError?: (error: Error) => void,
+ // Receives the failing `file` alongside the error so hosts can name it in
+ // the failure toast. `uploadWithToast` swallows the rejection after this
+ // fires, so a host that passes nothing reports nothing — the upload
+ // placeholder still disappears, which on its own reads as "my file
+ // silently vanished" (MUL-4808).
+ onError?: (error: Error, file: File) => void,
) {
// In-flight counter, NOT a single boolean. Callers fire multiple uploads
// concurrently (drag-drop of N files, paste with multiple images) and the
@@ -125,7 +130,7 @@ export function useFileUpload(
try {
return await upload(file, ctx);
} catch (err) {
- onError?.(err instanceof Error ? err : new Error("Upload failed"));
+ onError?.(err instanceof Error ? err : new Error("Upload failed"), file);
return null;
}
},
diff --git a/packages/ui/components/common/submit-button.tsx b/packages/ui/components/common/submit-button.tsx
index ba9089ab83..2212a87de1 100644
--- a/packages/ui/components/common/submit-button.tsx
+++ b/packages/ui/components/common/submit-button.tsx
@@ -13,6 +13,15 @@ interface SubmitButtonProps {
onClick: () => void;
disabled?: boolean;
loading?: boolean;
+ /**
+ * Blocked on background work the user started (an attachment still
+ * uploading) rather than on a missing precondition. Disables the button and
+ * marks it `aria-busy`, so a screen reader reaching it with a virtual cursor
+ * reads "busy" rather than an unexplained dead control. It is NOT tab
+ * reachable while disabled, so callers should also carry the reason in
+ * `ariaLabel` / `tooltip` and in the visible label where there is one.
+ */
+ busy?: boolean;
running?: boolean;
onStop?: () => void;
/**
@@ -34,6 +43,7 @@ function SubmitButton({
onClick,
disabled,
loading,
+ busy,
running,
onStop,
tooltip,
@@ -65,7 +75,9 @@ function SubmitButton({
<Button
size="icon-sm"
className="rounded-full"
- disabled={disabled || loading}
+ disabled={disabled || loading || busy}
+ aria-disabled={busy || undefined}
+ aria-busy={busy || undefined}
onClick={onClick}
aria-label={ariaLabel}
>
diff --git a/packages/views/chat/components/chat-input.test.tsx b/packages/views/chat/components/chat-input.test.tsx
index 70143dd9b2..721f6161f9 100644
--- a/packages/views/chat/components/chat-input.test.tsx
+++ b/packages/views/chat/components/chat-input.test.tsx
@@ -43,7 +43,12 @@ const editorProps = vi.hoisted(() => ({
// scrubbed the editor (clearEditor) or left it intact (fire-and-forget).
const editorState = vi.hoisted(() => ({ cleared: 0, blurred: 0, focused: 0 }));
-vi.mock("../../editor", () => ({
+vi.mock("../../editor", async () => ({
+ // Real submit gate (pure React) driven by the mock editor's
+ // `hasActiveUploads` / `onUploadingChange`.
+ ...(await vi.importActual<typeof import("../../editor/use-upload-gate")>(
+ "../../editor/use-upload-gate",
+ )),
useFileDropZone: ({ onDrop }: { onDrop: (files: File[]) => void }) => {
dropHandlers.onDrop = onDrop;
return { isDragOver: false, dropZoneProps: { "data-testid": "drop-zone" } };
@@ -55,6 +60,7 @@ vi.mock("../../editor", () => ({
onUpdate?: (md: string) => void;
placeholder?: string;
onUploadFile?: (file: File) => Promise<UploadResult | null>;
+ onUploadingChange?: (uploading: boolean) => void;
mentionMode?: string;
mentionContextItems?: unknown[];
},
@@ -65,6 +71,7 @@ vi.mock("../../editor", () => ({
onUpdate,
placeholder,
onUploadFile,
+ onUploadingChange,
} = props;
editorProps.last = props as unknown as Record<string, unknown>;
const valueRef = useRef<string>(defaultValue ?? "");
@@ -83,6 +90,9 @@ vi.mock("../../editor", () => ({
},
uploadFile: async (file: File) => {
uploadingRef.current += 1;
+ // Mirror the real editor: the pending node lands before the await, and
+ // the host learns about it through onUploadingChange, not by polling.
+ if (uploadingRef.current === 1) onUploadingChange?.(true);
try {
const result = await onUploadFile?.(file);
if (result) {
@@ -100,6 +110,7 @@ vi.mock("../../editor", () => ({
}
} finally {
uploadingRef.current = Math.max(0, uploadingRef.current - 1);
+ if (uploadingRef.current === 0) onUploadingChange?.(false);
}
},
hasActiveUploads: () => uploadingRef.current > 0,
diff --git a/packages/views/chat/components/chat-input.tsx b/packages/views/chat/components/chat-input.tsx
index 799b0baeb2..0914c31727 100644
--- a/packages/views/chat/components/chat-input.tsx
+++ b/packages/views/chat/components/chat-input.tsx
@@ -8,6 +8,7 @@ import {
type ContentEditorRef,
useFileDropZone,
FileDropOverlay,
+ useUploadGate,
} from "../../editor";
import { SubmitButton } from "@multica/ui/components/common/submit-button";
import { ChatAddMenu } from "./chat-add-menu";
@@ -124,6 +125,7 @@ export function ChatInput({
editorKeyOverride,
}: ChatInputProps) {
const { t } = useT("chat");
+ const { t: tEditor } = useT("editor");
const sendShortcut = useShortcut("send");
const editorRef = useRef<ContentEditorRef>(null);
const activeSessionId = useChatStore((s) => s.activeSessionId);
@@ -180,13 +182,13 @@ export function ChatInput({
const hasNothingToSend = isEmpty && !inputDraft.trim();
const appliedRestoreIdRef = useRef<string | null>(null);
const editorKey = editorKeyOverride ?? selectedAgentId ?? "no-agent";
- // Number of in-flight uploads. We track this explicitly (rather than
- // peeking at the editor on every render) so the SubmitButton visibly
- // disables the instant an upload starts and re-enables the instant it
- // finishes. handleSend ALSO checks `hasActiveUploads()` for paths that
- // bypass the button (Mod+Enter while paste is mid-stream, drag-drop
- // racing the keyboard) — defense in depth.
- const [pendingUploads, setPendingUploads] = useState(0);
+ // Submit gate. `uploading` disables the SubmitButton the instant an upload
+ // starts; `isBlocked()` is re-read inside handleSend for the paths that skip
+ // the button entirely (Mod+Enter mid-paste, drag-drop racing the keyboard).
+ // Both read the editor document, which is the actual upload queue — this
+ // used to be a local in-flight counter that a manual delete of the pending
+ // image would leave stuck (MUL-4808).
+ const uploadGate = useUploadGate(editorRef);
// Maps "URL inserted into the editor" → "attachment row id" so that
// on send we can ask the server to bind only the attachments still
@@ -256,18 +258,13 @@ export function ChatInput({
const handleUpload = useCallback(
async (file: File): Promise<UploadResult | null> => {
if (!onUploadFile) return null;
- setPendingUploads((n) => n + 1);
- try {
- const result = await onUploadFile(file);
- if (result) {
- const persistedURL = result.markdownLink || result.link;
- uploadMapRef.current.set(persistedURL, result.id);
- if (result.id) addInputDraftAttachment(draftKey, result);
- }
- return result;
- } finally {
- setPendingUploads((n) => Math.max(0, n - 1));
+ const result = await onUploadFile(file);
+ if (result) {
+ const persistedURL = result.markdownLink || result.link;
+ uploadMapRef.current.set(persistedURL, result.id);
+ if (result.id) addInputDraftAttachment(draftKey, result);
}
+ return result;
},
[addInputDraftAttachment, draftKey, onUploadFile],
);
@@ -298,7 +295,7 @@ export function ChatInput({
// 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 (editorRef.current?.hasActiveUploads()) {
+ if (uploadGate.isBlocked()) {
logger.debug("input.send skipped: uploads in flight");
return;
}
@@ -432,6 +429,7 @@ export function ChatInput({
}}
onSubmit={handleSend}
onUploadFile={uploadEnabled ? handleUpload : undefined}
+ onUploadingChange={uploadGate.onUploadingChange}
attachments={draftAttachments}
debounceMs={100}
mentionMode={contextItems ? "context" : "default"}
@@ -455,14 +453,19 @@ export function ChatInput({
<div className="absolute bottom-1 right-1.5 flex items-center gap-1">
<SubmitButton
onClick={handleSend}
- disabled={hasNothingToSend || isSubmitting || !!disabled || !!noAgent || pendingUploads > 0}
+ disabled={hasNothingToSend || isSubmitting || !!disabled || !!noAgent}
loading={isSubmitting}
+ busy={uploadGate.uploading}
running={isRunning}
onStop={onStop}
- tooltip={sendShortcut
- ? `${t(($) => $.input.send_tooltip)} · ${formatShortcut(sendShortcut)}`
+ tooltip={uploadGate.uploading
+ ? tEditor(($) => $.upload.in_progress)
+ : sendShortcut
+ ? `${t(($) => $.input.send_tooltip)} · ${formatShortcut(sendShortcut)}`
+ : t(($) => $.input.send_tooltip)}
+ ariaLabel={uploadGate.uploading
+ ? tEditor(($) => $.upload.in_progress)
: t(($) => $.input.send_tooltip)}
- ariaLabel={t(($) => $.input.send_tooltip)}
stopTooltip={t(($) => $.input.stop_tooltip)}
stopAriaLabel={t(($) => $.input.stop_tooltip)}
/>
diff --git a/packages/views/chat/components/chat-window.tsx b/packages/views/chat/components/chat-window.tsx
index 4eac31a61f..ad8114bda2 100644
--- a/packages/views/chat/components/chat-window.tsx
+++ b/packages/views/chat/components/chat-window.tsx
@@ -19,7 +19,7 @@ import { agentListOptions, memberListOptions } from "@multica/core/workspace/que
import { canAssignAgent } from "@multica/views/issues/components";
import { api } from "@multica/core/api";
import { useAgentPresenceDetail, useWorkspaceAgentAvailability } from "@multica/core/agents";
-import { useFileUpload } from "@multica/core/hooks/use-file-upload";
+import { useEditorUpload } from "../../editor";
import { ActorAvatar } from "../../common/actor-avatar";
import { useAppForeground } from "../../common/use-app-foreground";
import {
@@ -318,7 +318,7 @@ export function ChatWindow() {
// eslint-disable-next-line react-hooks/exhaustive-deps -- markRead ref stable
}, [isOpen, appForeground, activeSessionId, currentHasUnread]);
- const { uploadWithToast } = useFileUpload(api);
+ 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
diff --git a/packages/views/chat/components/use-chat-controller.ts b/packages/views/chat/components/use-chat-controller.ts
index 90eedaac5c..fdd5ec279e 100644
--- a/packages/views/chat/components/use-chat-controller.ts
+++ b/packages/views/chat/components/use-chat-controller.ts
@@ -14,7 +14,9 @@ import { agentListOptions, memberListOptions } from "@multica/core/workspace/que
import { canAssignAgent } from "@multica/views/issues/components";
import { api, dispatchReasonCode } from "@multica/core/api";
import { useAgentPresenceDetail, useWorkspaceAgentAvailability } from "@multica/core/agents";
-import { useFileUpload } from "@multica/core/hooks/use-file-upload";
+// 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,
@@ -313,7 +315,7 @@ export function useChatController(opts?: { isActive?: boolean }) {
// eslint-disable-next-line react-hooks/exhaustive-deps -- markRead ref stable
}, [isActive, appForeground, activeSessionId, currentHasUnread]);
- const { uploadWithToast } = useFileUpload(api);
+ const { uploadWithToast } = useEditorUpload();
const sessionPromiseRef = useRef<Promise<string | null> | null>(null);
const ensureSession = useCallback(
diff --git a/packages/views/editor/content-editor.test.tsx b/packages/views/editor/content-editor.test.tsx
index dd74b312e8..b8342d27dc 100644
--- a/packages/views/editor/content-editor.test.tsx
+++ b/packages/views/editor/content-editor.test.tsx
@@ -81,6 +81,13 @@ vi.mock("./attachment-download-context", () => ({
const editorRef = vi.hoisted<{ current: unknown }>(() => ({ current: null }));
const onCreateFired = vi.hoisted(() => ({ value: false }));
+// Transaction listeners registered via `editor.on("transaction", …)`. The
+// upload-state publisher subscribes here; `emitTransaction` stands in for
+// ProseMirror dispatching a doc change.
+const transactionListeners = vi.hoisted(() => ({ current: [] as Array<() => void> }));
+const emitTransaction = () => {
+ for (const listener of [...transactionListeners.current]) listener();
+};
const latestEditorOptions = vi.hoisted<{
current?: { onUpdate?: (args: { editor: unknown }) => void };
}>(() => ({}));
@@ -106,6 +113,15 @@ vi.mock("@tiptap/react", () => ({
setTextSelection: mockSetTextSelection,
},
getMarkdown: () => editorState.markdown,
+ on: (event: string, cb: () => void) => {
+ if (event === "transaction") transactionListeners.current.push(cb);
+ },
+ off: (event: string, cb: () => void) => {
+ if (event !== "transaction") return;
+ transactionListeners.current = transactionListeners.current.filter(
+ (listener) => listener !== cb,
+ );
+ },
view: { dispatch: mockDispatch },
state: {
get tr() {
@@ -146,6 +162,7 @@ describe("ContentEditor", () => {
editorState.markdown = "";
editorState.uploadingNodes = [];
editorRef.current = null;
+ transactionListeners.current = [];
onCreateFired.value = false;
latestEditorOptions.current = undefined;
providerProps.attachments = undefined;
@@ -461,6 +478,121 @@ function asUploadResult(att: Attachment): UploadResult {
return { ...att, link: att.url, markdownLink: `/api/attachments/${att.id}/download` };
}
+// MUL-4808 — the document IS the upload queue, so hosts gate submit off it
+// instead of each keeping a counter. These pin the publisher's contract.
+describe("ContentEditor — onUploadingChange (MUL-4808)", () => {
+ const uploadingNode = { attrs: { uploading: true } };
+ const settledNode = { attrs: { uploading: false } };
+
+ it("publishes true when a node starts uploading and false once it settles", () => {
+ const onUploadingChange = vi.fn();
+ render(<ContentEditor onUploadingChange={onUploadingChange} />);
+ // Mount publishes the current answer so the host can't be left holding a
+ // stale one from a previous editor instance (see the remount case below).
+ expect(onUploadingChange).toHaveBeenLastCalledWith(false);
+
+ editorState.uploadingNodes = [uploadingNode];
+ act(() => emitTransaction());
+ expect(onUploadingChange).toHaveBeenLastCalledWith(true);
+
+ editorState.uploadingNodes = [settledNode];
+ act(() => emitTransaction());
+ expect(onUploadingChange).toHaveBeenLastCalledWith(false);
+ });
+
+ it("keeps publishing true until the LAST concurrent upload settles", () => {
+ const onUploadingChange = vi.fn();
+ render(<ContentEditor onUploadingChange={onUploadingChange} />);
+
+ editorState.uploadingNodes = [{ attrs: { uploading: true } }, { attrs: { uploading: true } }];
+ act(() => emitTransaction());
+ expect(onUploadingChange).toHaveBeenLastCalledWith(true);
+
+ // First of two finishes — submit must STAY gated.
+ editorState.uploadingNodes = [settledNode, { attrs: { uploading: true } }];
+ act(() => emitTransaction());
+ expect(onUploadingChange).toHaveBeenLastCalledWith(true);
+
+ editorState.uploadingNodes = [settledNode, settledNode];
+ act(() => emitTransaction());
+ expect(onUploadingChange).toHaveBeenLastCalledWith(false);
+ });
+
+ // The regression that rules out driving this off `onUpdate`: a failed upload
+ // removes its placeholder, and since the blob URL was stripped from
+ // serialized markdown all along, the markdown is byte-identical before and
+ // after. onUpdate is debounced AND skips no-change emissions, so the host
+ // would stay gated forever with no pending upload left to un-gate it.
+ it("publishes false when a failed upload's placeholder is removed, even though the markdown never changed", () => {
+ const onUploadingChange = vi.fn();
+ const onUpdate = vi.fn();
+ editorState.markdown = "same body";
+ render(<ContentEditor onUploadingChange={onUploadingChange} onUpdate={onUpdate} />);
+
+ editorState.uploadingNodes = [uploadingNode];
+ act(() => emitTransaction());
+ expect(onUploadingChange).toHaveBeenLastCalledWith(true);
+
+ // Upload fails → node removed. Markdown is unchanged throughout.
+ editorState.uploadingNodes = [];
+ act(() => emitTransaction());
+ expect(onUploadingChange).toHaveBeenLastCalledWith(false);
+ expect(editorState.markdown).toBe("same body");
+ });
+
+ it("publishes only on flips, not on every transaction", () => {
+ const onUploadingChange = vi.fn();
+ render(<ContentEditor onUploadingChange={onUploadingChange} />);
+ onUploadingChange.mockClear(); // drop the mount publish
+
+ editorState.uploadingNodes = [uploadingNode];
+ act(() => emitTransaction());
+ // Typing while the upload is still in flight: same answer, no re-publish.
+ act(() => emitTransaction());
+ act(() => emitTransaction());
+ expect(onUploadingChange).toHaveBeenCalledTimes(1);
+ });
+
+ // An editor torn down mid-upload takes its pending node with it, but the
+ // host's gate state survives. Hosts that remount the editor under a living
+ // parent — comment edit (cancel → re-enter) and chat (agent switch rebuilds
+ // it by `key`) — would otherwise be stuck disabled forever, with no pending
+ // upload left in the document to ever flip them back.
+ it("republishes on remount so a host can't stay gated by a dead editor's upload", () => {
+ const onUploadingChange = vi.fn();
+ const { unmount } = render(<ContentEditor onUploadingChange={onUploadingChange} />);
+
+ editorState.uploadingNodes = [uploadingNode];
+ act(() => emitTransaction());
+ expect(onUploadingChange).toHaveBeenLastCalledWith(true);
+
+ // Editor dies while the upload is still pending; the host stays mounted
+ // holding `uploading: true`.
+ unmount();
+ editorRef.current = null;
+ onCreateFired.value = false;
+ editorState.uploadingNodes = [];
+
+ onUploadingChange.mockClear();
+ render(<ContentEditor onUploadingChange={onUploadingChange} />);
+ expect(onUploadingChange).toHaveBeenCalledWith(false);
+ });
+
+ it("does not subscribe at all when the host omits onUploadingChange", () => {
+ render(<ContentEditor />);
+ // Non-gating hosts (the autosaved description editor) must not pay for a
+ // doc scan on every keystroke.
+ expect(transactionListeners.current).toHaveLength(0);
+ });
+
+ it("unsubscribes on unmount", () => {
+ const { unmount } = render(<ContentEditor onUploadingChange={vi.fn()} />);
+ expect(transactionListeners.current).toHaveLength(1);
+ unmount();
+ expect(transactionListeners.current).toHaveLength(0);
+ });
+});
+
// MUL-3192 — surfaces like the quick-create modal upload images through the
// editor without a server-supplied `attachments` prop. Without in-session
// tracking, the AttachmentDownloadProvider had nothing to resolve the
diff --git a/packages/views/editor/content-editor.tsx b/packages/views/editor/content-editor.tsx
index 9c408bf870..35c3b10a4f 100644
--- a/packages/views/editor/content-editor.tsx
+++ b/packages/views/editor/content-editor.tsx
@@ -119,6 +119,22 @@ interface ContentEditorProps {
onSubmit?: () => void;
onBlur?: () => void;
onUploadFile?: (file: File) => Promise<UploadResult | null>;
+ /**
+ * Fired whenever this editor's "any attachment still uploading" answer
+ * flips. The document IS the upload queue — every path (paste, drop, the
+ * upload button, the imperative `uploadFile`) inserts a node with
+ * `attrs.uploading` before awaiting, and clears or removes it on settle —
+ * so hosts can drive a submit gate off one source of truth instead of a
+ * counter of their own that a manual node delete would desync.
+ *
+ * Pair it with the submit-time `hasActiveUploads()` second check: this
+ * callback drives the rendered button state, and the ref read is what a
+ * keyboard submit racing the last upload's settle must consult.
+ *
+ * Hosts that don't gate (the autosaved description editor) omit it and
+ * pay nothing — the scan below is skipped entirely when it's absent.
+ */
+ onUploadingChange?: (uploading: boolean) => void;
/** Show the floating formatting toolbar on text selection. Defaults true. */
showBubbleMenu?: boolean;
/**
@@ -221,6 +237,7 @@ const ContentEditor = forwardRef<ContentEditorRef, ContentEditorProps>(
onSubmit,
onBlur,
onUploadFile,
+ onUploadingChange,
showBubbleMenu = true,
currentIssueId,
disableMentions = false,
@@ -244,6 +261,7 @@ const ContentEditor = forwardRef<ContentEditorRef, ContentEditorProps>(
const onSubmitRef = useRef(onSubmit);
const onBlurRef = useRef(onBlur);
const onReadyRef = useRef(onReady);
+ const onUploadingChangeRef = useRef(onUploadingChange);
const onUploadFileRef = useRef<
((file: File) => Promise<UploadResult | null>) | undefined
>(undefined);
@@ -333,6 +351,7 @@ const ContentEditor = forwardRef<ContentEditorRef, ContentEditorProps>(
onSubmitRef.current = onSubmit;
onBlurRef.current = onBlur;
onReadyRef.current = onReady;
+ onUploadingChangeRef.current = onUploadingChange;
onUploadFileRef.current = wrappedOnUploadFile;
mentionContextItemsRef.current = mentionContextItems ?? [];
flushPendingOnUnmountRef.current = flushPendingOnUnmount;
@@ -479,6 +498,44 @@ const ContentEditor = forwardRef<ContentEditorRef, ContentEditorProps>(
onReadyRef.current?.();
}, [editor]);
+ // Publish upload-queue transitions to the host so it can gate submit.
+ //
+ // Deliberately NOT derived from `onUpdate`: that path is debounced and
+ // drops emissions whose markdown matches the last one — and a FAILED
+ // upload removes its placeholder to leave byte-identical markdown (the
+ // blob URL was stripped from it all along), so the un-gate would never
+ // fire. Transactions carry the attr flip regardless of what serializes.
+ useEffect(() => {
+ if (!editor || !onUploadingChange) return;
+ // Publish the current answer UNCONDITIONALLY on subscribe, then only on
+ // flips. The host's state outlives any one editor instance — comment
+ // edit unmounts the editor on cancel and mounts a fresh one on re-entry,
+ // and chat swaps the editor by `key` when the agent changes. An editor
+ // torn down mid-upload takes its pending node with it, so a host left
+ // holding `uploading: true` has nothing left to un-gate it: skipping
+ // this first emission because the new instance also reads "not
+ // uploading" is exactly how submit gets wedged shut for good.
+ //
+ // `last` is per-subscription rather than a ref for the same reason: flip
+ // tracking must not survive the instance it describes.
+ let last = hasUploadingNode(editor);
+ onUploadingChangeRef.current?.(last);
+ const check = () => {
+ if (editor.isDestroyed) return;
+ const uploading = hasUploadingNode(editor);
+ if (uploading === last) return;
+ last = uploading;
+ onUploadingChangeRef.current?.(uploading);
+ };
+ editor.on("transaction", check);
+ return () => {
+ editor.off("transaction", check);
+ };
+ // `onUploadingChange` is read for presence only; the ref carries the
+ // live callback, so a host passing an inline arrow doesn't rebind.
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [editor, !!onUploadingChange]);
+
// Cleanup on unmount. A pending debounced update is DROPPED by default,
// not flushed — see the `flushPendingOnUnmount` prop doc for why. When the
// owner opted in, emit the markdown cached at `onUpdate` time so a long
diff --git a/packages/views/editor/index.ts b/packages/views/editor/index.ts
index 263f0992f2..cc2c228203 100644
--- a/packages/views/editor/index.ts
+++ b/packages/views/editor/index.ts
@@ -10,6 +10,8 @@ export {
} from "./title-editor";
export { ReadonlyContent } from "./readonly-content";
export { useFileDropZone } from "./use-file-drop-zone";
+export { useUploadGate, type UploadGate } from "./use-upload-gate";
+export { useEditorUpload } from "./use-editor-upload";
export { FileDropOverlay } from "./file-drop-overlay";
export { useLazyEditor, type LazyEditorHandle, type LazyFocusTarget } from "./use-lazy-editor";
export { anchorFromPoint, type TextAnchor } from "./text-anchor";
diff --git a/packages/views/editor/use-editor-upload.test.tsx b/packages/views/editor/use-editor-upload.test.tsx
new file mode 100644
index 0000000000..a3eef793cc
--- /dev/null
+++ b/packages/views/editor/use-editor-upload.test.tsx
@@ -0,0 +1,87 @@
+import { describe, it, expect, vi, beforeEach } from "vitest";
+import { renderHook, act } from "@testing-library/react";
+import type { ReactNode } from "react";
+import { I18nProvider } from "@multica/core/i18n/react";
+import enEditor from "../locales/en/editor.json";
+
+const mockToastError = vi.hoisted(() => vi.fn());
+const mockUploadFile = vi.hoisted(() => vi.fn());
+
+vi.mock("sonner", () => ({
+ toast: { error: mockToastError },
+}));
+
+vi.mock("@multica/core/api", () => ({
+ api: { uploadFile: mockUploadFile },
+}));
+
+import { useEditorUpload } from "./use-editor-upload";
+
+function wrapper({ children }: { children: ReactNode }) {
+ return (
+ <I18nProvider locale="en" resources={{ en: { editor: enEditor } }}>
+ {children}
+ </I18nProvider>
+ );
+}
+
+// MUL-4808 — `uploadWithToast` only ever toasted if its caller passed
+// `onError`, and no composer did. So a failed upload silently removed its
+// placeholder and the file simply vanished with no explanation. The gate's
+// minimum failure fallback ("drop the placeholder, SAY SO, allow submit
+// again") depends on this hook supplying that missing toast.
+describe("useEditorUpload", () => {
+ beforeEach(() => {
+ mockToastError.mockReset();
+ mockUploadFile.mockReset();
+ });
+
+ it("toasts the filename and reason when an upload fails", async () => {
+ mockUploadFile.mockRejectedValue(new Error("Network unreachable"));
+ const { result } = renderHook(() => useEditorUpload(), { wrapper });
+
+ let returned: unknown;
+ await act(async () => {
+ returned = await result.current.uploadWithToast(
+ new File(["x"], "diagram.png", { type: "image/png" }),
+ );
+ });
+
+ // Null is what tells the editor extension to drop the placeholder.
+ expect(returned).toBeNull();
+ expect(mockToastError).toHaveBeenCalledWith(
+ "Couldn't upload diagram.png: Network unreachable",
+ );
+ });
+
+ it("surfaces the size-limit rejection by name too", async () => {
+ const { result } = renderHook(() => useEditorUpload(), { wrapper });
+ // The 100 MB guard throws before any request goes out.
+ const huge = new File(["x"], "huge.mov", { type: "video/quicktime" });
+ Object.defineProperty(huge, "size", { value: 200 * 1024 * 1024 });
+
+ await act(async () => {
+ await result.current.uploadWithToast(huge);
+ });
+
+ expect(mockToastError).toHaveBeenCalledWith(
+ "Couldn't upload huge.mov: File exceeds 100 MB limit",
+ );
+ });
+
+ it("does not toast on a successful upload", async () => {
+ mockUploadFile.mockResolvedValue({
+ id: "att-1",
+ url: "https://cdn.example/att-1.png",
+ markdown_url: "https://api.example/api/attachments/att-1/download",
+ filename: "ok.png",
+ });
+ const { result } = renderHook(() => useEditorUpload(), { wrapper });
+
+ await act(async () => {
+ await result.current.uploadWithToast(new File(["x"], "ok.png", { type: "image/png" }));
+ });
+
+ expect(mockToastError).not.toHaveBeenCalled();
+ });
+});
diff --git a/packages/views/editor/use-editor-upload.ts b/packages/views/editor/use-editor-upload.ts
new file mode 100644
index 0000000000..301af20450
--- /dev/null
+++ b/packages/views/editor/use-editor-upload.ts
@@ -0,0 +1,34 @@
+"use client";
+
+import { useCallback } from "react";
+import { toast } from "sonner";
+import { api } from "@multica/core/api";
+import { useFileUpload } from "@multica/core/hooks/use-file-upload";
+import { useT } from "../i18n";
+
+/**
+ * `useFileUpload` wired to the failure toast the upload gate depends on.
+ *
+ * The gate's failure fallback is "drop the placeholder, say so, let them
+ * submit again". Dropping the placeholder is handled in the upload extension,
+ * but without the toast the file just vanishes mid-upload with no explanation
+ * — which is what every composer did, since `uploadWithToast` only toasts if
+ * the caller supplies `onError` and no caller ever did (MUL-4808).
+ *
+ * `useFileUpload` lives in `@multica/core`, which may not import a UI library,
+ * so the toast is supplied here — once, rather than per composer.
+ */
+function useEditorUpload() {
+ const { t } = useT("editor");
+ const onError = useCallback(
+ (error: Error, file: File) => {
+ toast.error(
+ t(($) => $.upload.failed, { filename: file.name, reason: error.message }),
+ );
+ },
+ [t],
+ );
+ return useFileUpload(api, onError);
+}
+
+export { useEditorUpload };
diff --git a/packages/views/editor/use-upload-gate.ts b/packages/views/editor/use-upload-gate.ts
new file mode 100644
index 0000000000..07bbe20847
--- /dev/null
+++ b/packages/views/editor/use-upload-gate.ts
@@ -0,0 +1,60 @@
+"use client";
+
+/**
+ * The submit gate for composers that accept attachments (MUL-4808).
+ *
+ * While a file is still uploading, the editor holds a `blob:` placeholder and
+ * the attachment's id does not exist yet. Serializing at that moment strips
+ * the blob (see ContentEditor's stripBlobUrls) and binds no id, so the send
+ * succeeds while the file silently disappears from what the recipient gets.
+ * Every action that FIXES a draft — send, create, save, and the mode switch
+ * that re-serializes a draft into another form — must therefore wait.
+ *
+ * Two signals, because they answer different questions:
+ *
+ * `uploading` — reactive, drives the rendered button (disabled / "Uploading…"
+ * / aria-busy). Sourced from the editor document via
+ * `onUploadingChange`, which is the actual upload queue.
+ *
+ * `isBlocked()` — imperative, read INSIDE the submit handler. A rendered
+ * disabled state is a frame behind: Cmd+Enter and Enter-on-title
+ * bypass the button entirely, and a click can land in the same
+ * tick an upload starts. This reads the document at invocation
+ * time, which is the only answer that can't be stale.
+ *
+ * Hosts must use both. Gating the button alone leaves the shortcut paths open;
+ * gating the handler alone leaves a live-looking button that silently no-ops.
+ *
+ * Kept free of `api` / i18n / toast imports on purpose — the failure toast
+ * lives in `use-editor-upload` — so host tests can run the real gate against a
+ * mocked editor without pulling the API singleton into the module graph.
+ */
+
+import { useCallback, useState, type RefObject } from "react";
+import type { ContentEditorRef } from "./content-editor";
+
+interface UploadGate {
+ /** True while any attachment in this editor is mid-upload. Render state. */
+ uploading: boolean;
+ /** Pass to `<ContentEditor onUploadingChange={...} />`. */
+ onUploadingChange: (uploading: boolean) => void;
+ /** Submit-time truth. Call at the top of every submit/save/switch handler. */
+ isBlocked: () => boolean;
+}
+
+/**
+ * Reactive + submit-time upload state for one editor.
+ *
+ * The returned `isBlocked` reads the editor ref rather than `uploading` on
+ * purpose — see the module docstring.
+ */
+function useUploadGate(editorRef: RefObject<ContentEditorRef | null>): UploadGate {
+ const [uploading, setUploading] = useState(false);
+ const isBlocked = useCallback(
+ () => editorRef.current?.hasActiveUploads() === true,
+ [editorRef],
+ );
+ return { uploading, onUploadingChange: setUploading, isBlocked };
+}
+
+export { useUploadGate, type UploadGate };
diff --git a/packages/views/issues/components/comment-card-edit-gate.test.tsx b/packages/views/issues/components/comment-card-edit-gate.test.tsx
new file mode 100644
index 0000000000..37cf6470e7
--- /dev/null
+++ b/packages/views/issues/components/comment-card-edit-gate.test.tsx
@@ -0,0 +1,246 @@
+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 { UploadResult } from "@multica/core/hooks/use-file-upload";
+import { useCommentDraftStore } from "@multica/core/issues/stores";
+import { renderWithI18n } from "../../test/i18n";
+
+const uploadWithToast = vi.hoisted(() => vi.fn());
+
+vi.mock("@multica/core/api", () => ({
+ api: {},
+ dispatchReasonCode: () => undefined,
+}));
+
+vi.mock("../../navigation", () => ({
+ useNavigation: () => ({
+ push: vi.fn(),
+ pathname: "/acme/issues",
+ getShareableUrl: (p: string) => `https://app.example${p}`,
+ }),
+}));
+
+vi.mock("@multica/core/workspace/hooks", () => ({
+ useActorName: () => ({ getActorName: () => "Ada" }),
+}));
+
+vi.mock("../../common/actor-avatar", () => ({
+ ActorAvatar: () => null,
+}));
+
+// The trigger-preview chips have their own suite; inert here so this file
+// stays about the edit gate.
+vi.mock("../hooks/use-comment-trigger-preview", () => ({
+ useCommentTriggerPreview: () => ({ agents: [], blocked: [] }),
+}));
+
+vi.mock("../../editor", async () => ({
+ // Real submit gate (pure React) driven by the mock editor below.
+ ...(await vi.importActual<typeof import("../../editor/use-upload-gate")>(
+ "../../editor/use-upload-gate",
+ )),
+ // The card nests a ReplyInput, which is readonly-first — real controller.
+ ...(await vi.importActual<typeof import("../../editor/use-lazy-editor")>(
+ "../../editor/use-lazy-editor",
+ )),
+ useEditorUpload: () => ({ uploadWithToast, upload: vi.fn(), uploading: false }),
+ useFileDropZone: () => ({ isDragOver: false, dropZoneProps: {} }),
+ FileDropOverlay: () => null,
+ ReadonlyContent: ({ content }: { content: string }) => <div>{content}</div>,
+ Attachment: () => null,
+ AttachmentDownloadProvider: ({ children }: { children: ReactNode }) => <>{children}</>,
+ ContentEditor: forwardRef(function MockContentEditor(
+ {
+ defaultValue,
+ onUpdate,
+ onUploadFile,
+ onUploadingChange,
+ onSubmit,
+ placeholder,
+ }: {
+ defaultValue?: string;
+ onUpdate?: (markdown: string) => void;
+ onUploadFile?: (file: File) => Promise<UploadResult | null>;
+ onUploadingChange?: (uploading: boolean) => void;
+ onSubmit?: () => void;
+ placeholder?: string;
+ },
+ ref: Ref<unknown>,
+ ) {
+ const valueRef = useRef(defaultValue ?? "");
+ // Mirrors the real editor's `uploading` node attrs — see the sibling
+ // composer suite for the same stand-in.
+ const inFlightRef = useRef(0);
+ // Mirrors the real editor publishing its current answer on subscribe: a
+ // fresh instance owns no pending upload, so it reports "not uploading".
+ useEffect(() => {
+ onUploadingChange?.(inFlightRef.current > 0);
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, []);
+ useImperativeHandle(ref, () => ({
+ getMarkdown: () => valueRef.current,
+ clearContent: () => { valueRef.current = ""; },
+ focus: () => {},
+ blur: () => {},
+ uploadFile: async (file: File) => {
+ inFlightRef.current += 1;
+ if (inFlightRef.current === 1) onUploadingChange?.(true);
+ try {
+ const result = await onUploadFile?.(file);
+ if (!result) return;
+ valueRef.current = `${valueRef.current}\n${result.url}`.trim();
+ onUpdate?.(valueRef.current);
+ } finally {
+ inFlightRef.current -= 1;
+ if (inFlightRef.current === 0) onUploadingChange?.(false);
+ }
+ },
+ hasActiveUploads: () => inFlightRef.current > 0,
+ }));
+ return (
+ <textarea
+ data-testid="editor"
+ defaultValue={defaultValue}
+ placeholder={placeholder}
+ onChange={(e) => {
+ valueRef.current = e.target.value;
+ onUpdate?.(e.target.value);
+ }}
+ onKeyDown={(e) => {
+ if ((e.metaKey || e.ctrlKey) && e.key === "Enter") onSubmit?.();
+ }}
+ />
+ );
+ }),
+}));
+
+import { CommentCard } from "./comment-card";
+
+const entry: TimelineEntry = {
+ id: "comment-1",
+ issue_id: "issue-1",
+ parent_id: null,
+ // `actor_*` is what the own-comment / can-edit rule reads.
+ actor_type: "member",
+ actor_id: "user-1",
+ content: "Original body",
+ type: "comment",
+ created_at: "2026-07-01T00:00:00Z",
+ updated_at: "2026-07-01T00:00:00Z",
+ attachments: [],
+ reactions: [],
+} as unknown as TimelineEntry;
+
+function renderCard(onEdit = vi.fn().mockResolvedValue(undefined)) {
+ const qc = new QueryClient({ defaultOptions: { queries: { retry: false } } });
+ const view = renderWithI18n(
+ <QueryClientProvider client={qc}>
+ <CommentCard
+ issueId="issue-1"
+ entry={entry}
+ replies={[]}
+ currentUserId="user-1"
+ onReply={vi.fn().mockResolvedValue(true)}
+ onEdit={onEdit}
+ onDelete={vi.fn()}
+ onToggleReaction={vi.fn()}
+ />
+ </QueryClientProvider>,
+ );
+ return { ...view, onEdit };
+}
+
+/** Open the row's ⋯ menu and click Edit. The trigger is icon-only with no
+ * accessible name, so it is addressed by its menu popup role. */
+async function startEditing() {
+ const trigger = document.querySelector('button[aria-haspopup="menu"]');
+ if (!trigger) throw new Error("Expected the comment actions menu trigger");
+ fireEvent.click(trigger);
+ fireEvent.click(await screen.findByText("Edit"));
+ await screen.findByTestId("editor");
+}
+
+function getSaveButton() {
+ return screen.getByRole("button", { name: /Save|Uploading…/ });
+}
+
+beforeEach(() => {
+ uploadWithToast.mockReset();
+ useCommentDraftStore.setState({ drafts: {} });
+});
+
+// MUL-4808 — comment edit had no upload gate: saving mid-upload persisted the
+// 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; }),
+ );
+ 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) };
+ }
+
+ it("disables Save while an upload is in flight and re-enables once it settles", async () => {
+ const { container } = renderCard();
+ await startEditing();
+ fireEvent.change(screen.getByTestId("editor"), { target: { value: "Edited body" } });
+
+ const pending = startPendingUpload(container);
+
+ await waitFor(() => expect(getSaveButton()).toBeDisabled());
+ expect(getSaveButton()).toHaveAttribute("aria-busy", "true");
+
+ await act(async () => {
+ pending.release({
+ id: "att-1",
+ 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);
+ });
+
+ await waitFor(() => expect(getSaveButton()).not.toBeDisabled());
+ });
+
+ // The editor unmounts on Cancel, taking the pending upload's node with it,
+ // while the gate state lives on the surviving card. Re-entering edit must
+ // come back usable — not stuck on the dead editor's last answer.
+ it("does not stay gated after cancelling edit mid-upload and re-entering", async () => {
+ const { container } = renderCard();
+ await startEditing();
+ fireEvent.change(screen.getByTestId("editor"), { target: { value: "Edited body" } });
+
+ startPendingUpload(container);
+ await waitFor(() => expect(getSaveButton()).toBeDisabled());
+
+ // Cancel stays available during an upload, so this is reachable.
+ fireEvent.click(screen.getByRole("button", { name: "Cancel" }));
+ await waitFor(() => expect(screen.queryByTestId("editor")).toBeNull());
+
+ await startEditing();
+ await waitFor(() => expect(getSaveButton()).not.toBeDisabled());
+ expect(getSaveButton()).not.toHaveAttribute("aria-busy");
+ });
+
+ it("blocks the Cmd+Enter save path while an upload is in flight", async () => {
+ const { container, onEdit } = renderCard();
+ await startEditing();
+ const editor = screen.getByTestId("editor");
+ fireEvent.change(editor, { target: { value: "Edited body" } });
+
+ startPendingUpload(container);
+
+ // Cmd+Enter reaches saveEdit without ever consulting the Save button.
+ fireEvent.keyDown(editor, { key: "Enter", metaKey: true });
+ await Promise.resolve();
+ expect(onEdit).not.toHaveBeenCalled();
+ });
+});
diff --git a/packages/views/issues/components/comment-card.tsx b/packages/views/issues/components/comment-card.tsx
index 2f8dbe60ef..896b6fbf35 100644
--- a/packages/views/issues/components/comment-card.tsx
+++ b/packages/views/issues/components/comment-card.tsx
@@ -29,9 +29,8 @@ 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 } from "../../editor";
+import { ContentEditor, type ContentEditorRef, ReadonlyContent, useFileDropZone, FileDropOverlay, Attachment as AttachmentRenderer, AttachmentDownloadProvider, useUploadGate, useEditorUpload } from "../../editor";
import { FileUploadButton } from "@multica/ui/components/common/file-upload-button";
-import { useFileUpload } from "@multica/core/hooks/use-file-upload";
import { api, dispatchReasonCode } from "@multica/core/api";
import { ReplyInput } from "./reply-input";
import { CommentTriggerChips } from "./comment-trigger-chips";
@@ -322,10 +321,14 @@ function useEditAttachmentState(
onEdit: (commentId: string, content: string, attachmentIds: string[], suppressAgentIds?: string[]) => Promise<void>,
) {
const { t } = useT("issues");
- const { uploadWithToast } = useFileUpload(api);
+ const { t: tEditor } = useT("editor");
+ const { uploadWithToast } = useEditorUpload();
const [editing, setEditing] = useState(false);
const [saving, setSaving] = useState(false);
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 ?? "");
@@ -411,6 +414,8 @@ function useEditAttachmentState(
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*)+$/, "")
@@ -454,6 +459,9 @@ function useEditAttachmentState(
return {
editing,
saving,
+ uploading: uploadGate.uploading,
+ onUploadingChange: uploadGate.onUploadingChange,
+ uploadingLabel: tEditor(($) => $.upload.in_progress),
editorRef,
editorAttachments,
handleUpload,
@@ -633,6 +641,7 @@ function CommentRow({
}}
onSubmit={edit.saveEdit}
onUploadFile={edit.handleUpload}
+ onUploadingChange={edit.onUploadingChange}
debounceMs={100}
currentIssueId={issueId}
attachments={edit.editorAttachments}
@@ -668,9 +677,16 @@ function CommentRow({
onSelect={(file) => edit.editorRef.current?.uploadFile(file)}
/>
<Button size="sm" variant="ghost" onClick={edit.cancelEdit} disabled={edit.saving}>{t(($) => $.comment.cancel_edit)}</Button>
- <Button size="sm" variant="outline" onClick={edit.saveEdit} disabled={edit.saving}>
+ <Button
+ size="sm"
+ variant="outline"
+ onClick={edit.saveEdit}
+ disabled={edit.saving || edit.uploading}
+ aria-disabled={edit.uploading || undefined}
+ aria-busy={edit.uploading || undefined}
+ >
{edit.saving && <Loader2 className="h-3.5 w-3.5 animate-spin" />}
- {t(($) => $.comment.save_action)}
+ {edit.uploading ? edit.uploadingLabel : t(($) => $.comment.save_action)}
</Button>
</div>
</div>
@@ -934,6 +950,7 @@ function CommentCardImpl({
}}
onSubmit={edit.saveEdit}
onUploadFile={edit.handleUpload}
+ onUploadingChange={edit.onUploadingChange}
debounceMs={100}
currentIssueId={issueId}
attachments={edit.editorAttachments}
@@ -969,9 +986,16 @@ function CommentCardImpl({
</div>
<div className="flex items-center gap-2">
<Button size="sm" variant="ghost" onClick={edit.cancelEdit} disabled={edit.saving}>{t(($) => $.comment.cancel_edit)}</Button>
- <Button size="sm" variant="outline" onClick={edit.saveEdit} disabled={edit.saving}>
+ <Button
+ size="sm"
+ variant="outline"
+ onClick={edit.saveEdit}
+ disabled={edit.saving || edit.uploading}
+ aria-disabled={edit.uploading || undefined}
+ aria-busy={edit.uploading || undefined}
+ >
{edit.saving && <Loader2 className="h-3.5 w-3.5 animate-spin" />}
- {t(($) => $.comment.save_action)}
+ {edit.uploading ? edit.uploadingLabel : t(($) => $.comment.save_action)}
</Button>
</div>
</div>
diff --git a/packages/views/issues/components/comment-composers.test.tsx b/packages/views/issues/components/comment-composers.test.tsx
index a82204f0df..0bc189104d 100644
--- a/packages/views/issues/components/comment-composers.test.tsx
+++ b/packages/views/issues/components/comment-composers.test.tsx
@@ -1,7 +1,7 @@
import { forwardRef, useEffect, useImperativeHandle, useRef, type ReactNode, type Ref } from "react";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { describe, it, expect, vi, beforeEach } from "vitest";
-import { fireEvent, screen, waitFor } from "@testing-library/react";
+import { act, fireEvent, screen, waitFor } from "@testing-library/react";
import type { UploadResult } from "@multica/core/hooks/use-file-upload";
import { useCommentComposerStore, useCommentDraftStore } from "@multica/core/issues/stores";
import { renderWithI18n } from "../../test/i18n";
@@ -32,6 +32,12 @@ vi.mock("../../editor", async () => ({
...(await vi.importActual<typeof import("../../editor/use-lazy-editor")>(
"../../editor/use-lazy-editor",
)),
+ // Real submit gate (pure React) driven by the mock editor's
+ // `hasActiveUploads` / `onUploadingChange` below.
+ ...(await vi.importActual<typeof import("../../editor/use-upload-gate")>(
+ "../../editor/use-upload-gate",
+ )),
+ useEditorUpload: () => ({ uploadWithToast, upload: vi.fn(), uploading: false }),
useFileDropZone: () => ({
isDragOver: false,
dropZoneProps: { "data-testid": "drop-zone" },
@@ -43,17 +49,25 @@ vi.mock("../../editor", async () => ({
onUpdate,
placeholder,
onUploadFile,
+ onUploadingChange,
+ onSubmit,
onReady,
}: {
defaultValue?: string;
onUpdate?: (markdown: string) => void;
placeholder?: string;
onUploadFile?: (file: File) => Promise<UploadResult | null>;
+ onUploadingChange?: (uploading: boolean) => void;
+ onSubmit?: () => void;
onReady?: () => void;
},
ref: Ref<unknown>,
) {
const valueRef = useRef(defaultValue ?? "");
+ // Mirrors the real editor's `uploading` node attrs: the placeholder exists
+ // from before the await until the upload settles, `hasActiveUploads` reads
+ // it synchronously, and the host is told through onUploadingChange.
+ const inFlightRef = useRef(0);
useEffect(() => {
onReady?.();
@@ -69,12 +83,19 @@ vi.mock("../../editor", async () => ({
focusAtCoords: () => {},
blur: () => {},
uploadFile: async (file: File) => {
- const result = await onUploadFile?.(file);
- if (!result) return;
- valueRef.current = `${valueRef.current}\n${result.url}`.trim();
- onUpdate?.(valueRef.current);
+ inFlightRef.current += 1;
+ if (inFlightRef.current === 1) onUploadingChange?.(true);
+ try {
+ const result = await onUploadFile?.(file);
+ if (!result) return;
+ valueRef.current = `${valueRef.current}\n${result.url}`.trim();
+ onUpdate?.(valueRef.current);
+ } finally {
+ inFlightRef.current -= 1;
+ if (inFlightRef.current === 0) onUploadingChange?.(false);
+ }
},
- hasActiveUploads: () => false,
+ hasActiveUploads: () => inFlightRef.current > 0,
}));
return (
@@ -86,6 +107,11 @@ vi.mock("../../editor", async () => ({
valueRef.current = event.target.value;
onUpdate?.(event.target.value);
}}
+ onKeyDown={(event) => {
+ // The editor's Mod+Enter submit shortcut — the path that skips the
+ // send button entirely.
+ if ((event.metaKey || event.ctrlKey) && event.key === "Enter") onSubmit?.();
+ }}
/>
);
}),
@@ -263,6 +289,156 @@ 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. */
+ function startPendingUpload(container: HTMLElement, filename = "slow.png") {
+ let release!: (result: UploadResult | null) => void;
+ uploadWithToast.mockImplementationOnce(
+ () => new Promise<UploadResult | null>((resolve) => { release = resolve; }),
+ );
+ // FileUploadButton's visible control is a button that clicks a hidden
+ // input; the input is what carries the selection.
+ 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"], filename, { type: "image/png" })] },
+ });
+ return { release: (result: UploadResult | null) => release(result) };
+ }
+
+ 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");
+ fireEvent.change(screen.getByTestId("editor"), { target: { value: "look at this" } });
+
+ const pending = startPendingUpload(container);
+
+ await waitFor(() => expect(getSubmitButton(container)).toBeDisabled());
+ // Screen readers must hear "busy", not just a dead control.
+ expect(getSubmitButton(container)).toHaveAttribute("aria-busy", "true");
+
+ await act(async () => {
+ pending.release(uploadResult("att-1", "https://cdn.example/att-1.png"));
+ });
+
+ await waitFor(() => expect(getSubmitButton(container)).not.toBeDisabled());
+ expect(getSubmitButton(container)).not.toHaveAttribute("aria-busy");
+ });
+
+ it("blocks the Cmd+Enter path while an upload is in flight", async () => {
+ const { container, onSubmit } = renderCommentInput();
+ activateComposer("comment-composer-shell");
+ const editor = screen.getByTestId("editor");
+ fireEvent.change(editor, { target: { value: "look at this" } });
+
+ const pending = startPendingUpload(container);
+
+ // The shortcut never touches the disabled button — the handler's own
+ // re-read of the queue is the only thing standing between this keystroke
+ // and a comment posted without its attachment.
+ fireEvent.keyDown(editor, { key: "Enter", metaKey: true });
+ await Promise.resolve();
+ expect(onSubmit).not.toHaveBeenCalled();
+
+ await act(async () => {
+ pending.release(uploadResult("att-1", "https://cdn.example/att-1.png"));
+ });
+
+ 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");
+ fireEvent.change(screen.getByTestId("editor"), { target: { value: "two files" } });
+
+ const first = startPendingUpload(container, "a.png");
+ const second = startPendingUpload(container, "b.png");
+
+ await waitFor(() => expect(getSubmitButton(container)).toBeDisabled());
+
+ // 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"));
+ });
+ expect(getSubmitButton(container)).toBeDisabled();
+
+ await act(async () => {
+ second.release(uploadResult("att-b", "https://cdn.example/att-b.png"));
+ });
+ await waitFor(() => expect(getSubmitButton(container)).not.toBeDisabled());
+ });
+
+ it("re-enables send after a FAILED upload so the draft isn't stuck", async () => {
+ const { container } = renderCommentInput();
+ activateComposer("comment-composer-shell");
+ fireEvent.change(screen.getByTestId("editor"), { target: { value: "will fail" } });
+
+ const pending = startPendingUpload(container);
+ await waitFor(() => expect(getSubmitButton(container)).toBeDisabled());
+
+ // 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);
+ });
+ await waitFor(() => expect(getSubmitButton(container)).not.toBeDisabled());
+ });
+
+ it("sends the attachment id once the upload completes", async () => {
+ const { container, onSubmit } = renderCommentInput();
+ activateComposer("comment-composer-shell");
+ fireEvent.change(screen.getByTestId("editor"), { target: { value: "shipping it" } });
+
+ const pending = startPendingUpload(container);
+ await act(async () => {
+ pending.release(uploadResult("att-9", "https://cdn.example/att-9.png"));
+ });
+
+ await waitFor(() => expect(getSubmitButton(container)).not.toBeDisabled());
+ fireEvent.click(getSubmitButton(container));
+
+ await waitFor(() =>
+ expect(onSubmit).toHaveBeenCalledWith(
+ expect.stringContaining("https://cdn.example/att-9.png"),
+ ["att-9"],
+ undefined,
+ ),
+ );
+ });
+
+ it("gates the reply composer's send button too", async () => {
+ const { container } = renderReplyInput();
+ activateComposer("reply-composer-shell");
+ fireEvent.change(screen.getByTestId("editor"), { target: { value: "replying" } });
+
+ startPendingUpload(container);
+
+ await waitFor(() => expect(getSubmitButton(container)).toBeDisabled());
+ expect(getSubmitButton(container)).toHaveAttribute("aria-busy", "true");
+ });
+
+ it("blocks the reply composer's Cmd+Enter path", async () => {
+ const onSubmit = vi.fn().mockResolvedValue(true);
+ const { container } = renderReplyInput({ onSubmit });
+ activateComposer("reply-composer-shell");
+ const editor = screen.getByTestId("editor");
+ fireEvent.change(editor, { target: { value: "replying" } });
+
+ startPendingUpload(container);
+
+ fireEvent.keyDown(editor, { key: "Enter", metaKey: true });
+ await Promise.resolve();
+ expect(onSubmit).not.toHaveBeenCalled();
+ });
+});
+
describe("sticky composer preference", () => {
it("caps the editor height while the sticky preference is on (default)", () => {
renderCommentInput();
diff --git a/packages/views/issues/components/comment-input.tsx b/packages/views/issues/components/comment-input.tsx
index b59df228b6..907d5bd0ef 100644
--- a/packages/views/issues/components/comment-input.tsx
+++ b/packages/views/issues/components/comment-input.tsx
@@ -2,11 +2,9 @@
import { useRef, useState, useCallback, useEffect } from "react";
import { cn } from "@multica/ui/lib/utils";
-import { ContentEditor, type ContentEditorRef, useFileDropZone, FileDropOverlay, useLazyEditor } from "../../editor";
+import { ContentEditor, type ContentEditorRef, useFileDropZone, FileDropOverlay, useLazyEditor, useUploadGate, useEditorUpload } from "../../editor";
import { FileUploadButton } from "@multica/ui/components/common/file-upload-button";
import { SubmitButton } from "@multica/ui/components/common/submit-button";
-import { useFileUpload } from "@multica/core/hooks/use-file-upload";
-import { api } from "@multica/core/api";
import type { Attachment } from "@multica/core/types";
import { contentReferencesAttachment } from "@multica/core/types";
import { formatShortcut, useShortcut } from "@multica/core/shortcuts";
@@ -25,8 +23,12 @@ interface CommentInputProps {
function CommentInput({ issueId, onSubmit }: CommentInputProps) {
const { t } = useT("issues");
+ const { t: tEditor } = useT("editor");
const sendShortcut = useShortcut("send");
const editorRef = useRef<ContentEditorRef>(null);
+ // Sending mid-upload would strip the pending image's blob URL out of the
+ // markdown and bind no attachment id — the comment posts without the file.
+ const uploadGate = useUploadGate(editorRef);
// Read the persisted draft once on mount. ContentEditor only honors
// `defaultValue` at mount time, so this snapshot drives both the editor's
// initial content and the submit-button enable state — without this the
@@ -43,7 +45,7 @@ function CommentInput({ issueId, onSubmit }: CommentInputProps) {
// - 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 } = useFileUpload(api);
+ const { uploadWithToast } = useEditorUpload();
// 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
@@ -111,6 +113,10 @@ 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 —
@@ -183,6 +189,7 @@ function CommentInput({ issueId, onSubmit }: CommentInputProps) {
}}
onSubmit={handleSubmit}
onUploadFile={handleUpload}
+ onUploadingChange={uploadGate.onUploadingChange}
debounceMs={100}
currentIssueId={issueId}
attachments={pendingAttachments}
@@ -236,8 +243,14 @@ function CommentInput({ issueId, onSubmit }: CommentInputProps) {
onClick={handleSubmit}
disabled={isEmpty}
loading={submitting}
- tooltip={sendShortcut
- ? `${t(($) => $.comment.send_tooltip)} · ${formatShortcut(sendShortcut)}`
+ busy={uploadGate.uploading}
+ tooltip={uploadGate.uploading
+ ? tEditor(($) => $.upload.in_progress)
+ : sendShortcut
+ ? `${t(($) => $.comment.send_tooltip)} · ${formatShortcut(sendShortcut)}`
+ : t(($) => $.comment.send_tooltip)}
+ ariaLabel={uploadGate.uploading
+ ? tEditor(($) => $.upload.in_progress)
: t(($) => $.comment.send_tooltip)}
/>
</div>
diff --git a/packages/views/issues/components/issue-detail.test.tsx b/packages/views/issues/components/issue-detail.test.tsx
index a57eaaf813..494a17db0c 100644
--- a/packages/views/issues/components/issue-detail.test.tsx
+++ b/packages/views/issues/components/issue-detail.test.tsx
@@ -121,6 +121,15 @@ vi.mock("../../editor", async () => ({
...(await vi.importActual<typeof import("../../editor/use-lazy-editor")>(
"../../editor/use-lazy-editor",
)),
+ // Real submit gate (pure React) — see comment-composers.test.tsx.
+ ...(await vi.importActual<typeof import("../../editor/use-upload-gate")>(
+ "../../editor/use-upload-gate",
+ )),
+ useEditorUpload: () => ({
+ uploadWithToast: vi.fn(),
+ upload: vi.fn(),
+ uploading: false,
+ }),
useFileDropZone: () => ({ isDragOver: false, dropZoneProps: {} }),
FileDropOverlay: () => null,
// No-op so comment-card's AttachmentList can render without hitting the
diff --git a/packages/views/issues/components/issue-detail.tsx b/packages/views/issues/components/issue-detail.tsx
index 9348182d14..6e584e1e74 100644
--- a/packages/views/issues/components/issue-detail.tsx
+++ b/packages/views/issues/components/issue-detail.tsx
@@ -31,7 +31,7 @@ import { Button } from "@multica/ui/components/ui/button";
import { ResizablePanelGroup, ResizablePanel, ResizableHandle } from "@multica/ui/components/ui/resizable";
import { Sheet, SheetContent } from "@multica/ui/components/ui/sheet";
import { useIsMobile } from "@multica/ui/hooks/use-mobile";
-import { ContentEditor, type ContentEditorRef, TitleEditor, type TitleEditorRef, useFileDropZone, FileDropOverlay, useLazyEditor } from "../../editor";
+import { ContentEditor, type ContentEditorRef, TitleEditor, type TitleEditorRef, useFileDropZone, FileDropOverlay, useLazyEditor, useEditorUpload } from "../../editor";
import { FileUploadButton } from "@multica/ui/components/common/file-upload-button";
import {
Tooltip,
@@ -91,8 +91,6 @@ import { useIssueTimeline } from "../hooks/use-issue-timeline";
import { useIssueReactions } from "../hooks/use-issue-reactions";
import { useIssueSubscribers } from "../hooks/use-issue-subscribers";
import { ReactionBar } from "@multica/ui/components/common/reaction-bar";
-import { useFileUpload } from "@multica/core/hooks/use-file-upload";
-import { api } from "@multica/core/api";
import { useTimeAgo } from "../../i18n";
import { useRestoredScrollOffset, useRestoredScrollRef } from "../../platform";
import { cn } from "@multica/ui/lib/utils";
@@ -729,7 +727,11 @@ export function IssueDetail({ issueId, onDelete, onDone, defaultSidebarOpen = tr
currentUserRole === "owner" || currentUserRole === "admin";
const { data: allIssues = [] } = useQuery(issueListOptions(wsId));
const { getActorName } = useActorName();
- const { uploadWithToast } = useFileUpload(api);
+ // Description autosave is deliberately NOT gated (no explicit submit; the
+ // editor already strips `blob:` before serializing and binds ids on the
+ // later save). It still needs the failure toast, or a failed upload just
+ // erases its own placeholder and the file disappears unexplained.
+ const { uploadWithToast } = useEditorUpload();
const { defaultLayout, onLayoutChanged } = useDefaultLayout({
id: layoutId,
});
diff --git a/packages/views/issues/components/reply-input.tsx b/packages/views/issues/components/reply-input.tsx
index ceee8366a0..c0d85c56a6 100644
--- a/packages/views/issues/components/reply-input.tsx
+++ b/packages/views/issues/components/reply-input.tsx
@@ -1,12 +1,10 @@
"use client";
import { useRef, useState, useCallback, useEffect } from "react";
-import { ContentEditor, type ContentEditorRef, useFileDropZone, FileDropOverlay, useLazyEditor } from "../../editor";
+import { ContentEditor, type ContentEditorRef, useFileDropZone, FileDropOverlay, useLazyEditor, useUploadGate, useEditorUpload } 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 { useFileUpload } from "@multica/core/hooks/use-file-upload";
-import { api } from "@multica/core/api";
import type { Attachment } from "@multica/core/types";
import { contentReferencesAttachment } from "@multica/core/types";
import { formatShortcut, useShortcut } from "@multica/core/shortcuts";
@@ -52,9 +50,12 @@ function ReplyInput({
draftKey,
}: ReplyInputProps) {
const { t } = useT("issues");
+ const { t: tEditor } = useT("editor");
const sendShortcut = useShortcut("send");
const placeholderText = placeholder ?? t(($) => $.reply.placeholder);
const editorRef = useRef<ContentEditorRef>(null);
+ // See CommentInput — replying mid-upload posts without the file.
+ const uploadGate = useUploadGate(editorRef);
// If a draft key is provided, hydrate from store on mount (defaultValue is
// the only injection point on ContentEditorRef) and flush on every onUpdate.
const initialDraft = draftKey
@@ -70,7 +71,7 @@ function ReplyInput({
// 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 } = useFileUpload(api);
+ const { uploadWithToast } = useEditorUpload();
// Readonly-first: static shell until intent; an unsent draft mounts the
// real editor immediately (see CommentInput). This is also what keeps the
// reply box working across Virtuoso scroll-out — a typed draft rehydrates
@@ -132,6 +133,8 @@ 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.
@@ -205,6 +208,7 @@ function ReplyInput({
}}
onSubmit={handleSubmit}
onUploadFile={handleUpload}
+ onUploadingChange={uploadGate.onUploadingChange}
debounceMs={100}
currentIssueId={issueId}
attachments={pendingAttachments}
@@ -254,8 +258,14 @@ function ReplyInput({
onClick={handleSubmit}
disabled={isEmpty}
loading={submitting}
- tooltip={sendShortcut
- ? `${t(($) => $.comment.send_tooltip)} · ${formatShortcut(sendShortcut)}`
+ busy={uploadGate.uploading}
+ tooltip={uploadGate.uploading
+ ? tEditor(($) => $.upload.in_progress)
+ : sendShortcut
+ ? `${t(($) => $.comment.send_tooltip)} · ${formatShortcut(sendShortcut)}`
+ : t(($) => $.comment.send_tooltip)}
+ ariaLabel={uploadGate.uploading
+ ? tEditor(($) => $.upload.in_progress)
: t(($) => $.comment.send_tooltip)}
/>
</div>
diff --git a/packages/views/locales/en/editor.json b/packages/views/locales/en/editor.json
index 814a387e6a..e25d82e24e 100644
--- a/packages/views/locales/en/editor.json
+++ b/packages/views/locales/en/editor.json
@@ -79,6 +79,10 @@
"file_card": {
"uploading": "Uploading {{filename}}"
},
+ "upload": {
+ "failed": "Couldn't upload {{filename}}: {{reason}}",
+ "in_progress": "Uploading…"
+ },
"title_editor": {
"title_aria_label": "Title"
},
diff --git a/packages/views/locales/ja/editor.json b/packages/views/locales/ja/editor.json
index 54068f692a..1ae355a7a3 100644
--- a/packages/views/locales/ja/editor.json
+++ b/packages/views/locales/ja/editor.json
@@ -72,6 +72,10 @@
"file_card": {
"uploading": "{{filename}} をアップロード中"
},
+ "upload": {
+ "failed": "{{filename}} をアップロードできませんでした: {{reason}}",
+ "in_progress": "アップロード中…"
+ },
"title_editor": {
"title_aria_label": "タイトル"
},
diff --git a/packages/views/locales/ko/editor.json b/packages/views/locales/ko/editor.json
index f474a51a0b..8a41f65bc1 100644
--- a/packages/views/locales/ko/editor.json
+++ b/packages/views/locales/ko/editor.json
@@ -72,6 +72,10 @@
"file_card": {
"uploading": "{{filename}} 업로드 중"
},
+ "upload": {
+ "failed": "{{filename}}을(를) 업로드하지 못했어요: {{reason}}",
+ "in_progress": "업로드 중…"
+ },
"title_editor": {
"title_aria_label": "제목"
},
diff --git a/packages/views/locales/zh-Hans/editor.json b/packages/views/locales/zh-Hans/editor.json
index 7f52892f7e..7c6c8ca7a6 100644
--- a/packages/views/locales/zh-Hans/editor.json
+++ b/packages/views/locales/zh-Hans/editor.json
@@ -79,6 +79,10 @@
"file_card": {
"uploading": "正在上传 {{filename}}"
},
+ "upload": {
+ "failed": "{{filename}} 上传失败:{{reason}}",
+ "in_progress": "上传中…"
+ },
"title_editor": {
"title_aria_label": "标题"
},
diff --git a/packages/views/modals/create-issue.test.tsx b/packages/views/modals/create-issue.test.tsx
index 4fab911c6b..41713af81b 100644
--- a/packages/views/modals/create-issue.test.tsx
+++ b/packages/views/modals/create-issue.test.tsx
@@ -1,14 +1,16 @@
import { forwardRef, useImperativeHandle, useRef, useState, type ReactNode } from "react";
import { describe, it, expect, vi, beforeEach } from "vitest";
-import { fireEvent, render, screen, waitFor } from "@testing-library/react";
+import { act, fireEvent, render, screen, waitFor } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
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";
const TEST_RESOURCES = {
- en: { common: enCommon, modals: enModals },
+ // `editor` carries the shared upload-gate copy ("Uploading…").
+ en: { common: enCommon, modals: enModals, editor: enEditor },
};
function I18nWrapper({ children }: { children: ReactNode }) {
@@ -182,17 +184,36 @@ vi.mock("@multica/core/api", async () => {
};
});
-vi.mock("../editor", () => {
- const ContentEditor = forwardRef(({ defaultValue, onUpdate, onUploadFile, placeholder, attachments }: any, ref: any) => {
+vi.mock("../editor", async () => {
+ // Real submit gate (pure React) driven by the mock editor's
+ // `hasActiveUploads` / `onUploadingChange`.
+ const uploadGate = await vi.importActual<typeof import("../editor/use-upload-gate")>(
+ "../editor/use-upload-gate",
+ );
+ const ContentEditor = forwardRef(({ defaultValue, onUpdate, onUploadFile, onUploadingChange, placeholder, attachments }: any, ref: any) => {
const valueRef = useRef(defaultValue || "");
const [value, setValue] = useState(defaultValue || "");
+ // Mirrors the real editor's `uploading` node attrs: the placeholder is in
+ // the doc from before the await until the upload settles, and the host
+ // hears about it through onUploadingChange.
+ const inFlightRef = useRef(0);
useImperativeHandle(ref, () => ({
getMarkdown: () => valueRef.current,
clearContent: () => {
valueRef.current = "";
setValue("");
},
- uploadFile: (file: File) => onUploadFile?.(file),
+ uploadFile: async (file: File) => {
+ inFlightRef.current += 1;
+ if (inFlightRef.current === 1) onUploadingChange?.(true);
+ try {
+ return await onUploadFile?.(file);
+ } finally {
+ inFlightRef.current -= 1;
+ if (inFlightRef.current === 0) onUploadingChange?.(false);
+ }
+ },
+ hasActiveUploads: () => inFlightRef.current > 0,
}));
return (
<>
@@ -212,6 +233,12 @@ vi.mock("../editor", () => {
ContentEditor.displayName = "ContentEditor";
return {
+ ...uploadGate,
+ useEditorUpload: () => ({
+ uploadWithToast: mockUploadWithToast,
+ upload: vi.fn(),
+ uploading: false,
+ }),
useFileDropZone: () => ({ isDragOver: false, dropZoneProps: {} }),
FileDropOverlay: () => null,
ContentEditor,
@@ -302,13 +329,17 @@ vi.mock("@multica/ui/components/ui/button", () => ({
disabled,
onClick,
type = "button",
+ ...rest
}: {
children: React.ReactNode;
disabled?: boolean;
onClick?: () => void;
type?: "button" | "submit" | "reset";
+ // The real Button spreads the rest onto the element; forwarding them keeps
+ // accessibility props (aria-busy / aria-disabled) assertable here.
+ [key: string]: unknown;
}) => (
- <button type={type} disabled={disabled} onClick={onClick}>
+ <button type={type} disabled={disabled} onClick={onClick} {...rest}>
{children}
</button>
),
@@ -885,4 +916,79 @@ describe("CreateIssueModal", () => {
expect(mockSetDraft).toHaveBeenCalledWith({ title: "", 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.
+ describe("upload submit gate", () => {
+ /** Attach a file whose upload stays in flight until the caller releases it. */
+ function startPendingUpload() {
+ let release!: (result: unknown) => void;
+ mockUploadWithToast.mockImplementationOnce(
+ () => new Promise((resolve) => { release = resolve; }),
+ );
+ fireEvent.click(screen.getByRole("button", { name: "Upload file" }));
+ return { release: (result: unknown) => release(result) };
+ }
+
+ function renderManual(onSwitchMode = vi.fn()) {
+ const view = renderModal(
+ <ManualCreatePanel
+ onClose={vi.fn()}
+ onSwitchMode={onSwitchMode}
+ isExpanded={false}
+ setIsExpanded={vi.fn()}
+ />,
+ );
+ return { ...view, onSwitchMode };
+ }
+
+ it("disables Create and shows Uploading… while an upload is in flight", async () => {
+ const user = userEvent.setup();
+ renderManual();
+ await user.type(screen.getByPlaceholderText("Issue title"), "Has a screenshot");
+
+ const pending = startPendingUpload();
+
+ const createButton = await screen.findByRole("button", { name: "Uploading…" });
+ 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 waitFor(() =>
+ expect(screen.getByRole("button", { name: "Create Issue" })).not.toBeDisabled(),
+ );
+ });
+
+ it("blocks Enter on the title while an upload is in flight", async () => {
+ const user = userEvent.setup();
+ renderManual();
+ const title = screen.getByPlaceholderText("Issue title");
+ await user.type(title, "Has a screenshot");
+
+ startPendingUpload();
+
+ // Title Enter routes to the same handler as the Create button but never
+ // consults its disabled state — the handler's own check is the gate.
+ fireEvent.keyDown(title, { key: "Enter" });
+ await Promise.resolve();
+ expect(mockCreateIssue).not.toHaveBeenCalled();
+ });
+
+ it("blocks Switch to Agent while an upload is in flight", async () => {
+ const user = userEvent.setup();
+ const onSwitchMode = vi.fn();
+ renderManual(onSwitchMode);
+ await user.type(screen.getByPlaceholderText("Issue title"), "Has a screenshot");
+
+ startPendingUpload();
+
+ // The switch packs the description into an agent prompt and clears the
+ // manual draft — doing that mid-upload loses the image for good.
+ const switchButton = screen.getByRole("button", { name: /Switch to Agent/i });
+ await waitFor(() => expect(switchButton).toBeDisabled());
+ fireEvent.click(switchButton);
+ expect(onSwitchMode).not.toHaveBeenCalled();
+ });
+ });
});
diff --git a/packages/views/modals/create-issue.tsx b/packages/views/modals/create-issue.tsx
index e631922746..d89255a25d 100644
--- a/packages/views/modals/create-issue.tsx
+++ b/packages/views/modals/create-issue.tsx
@@ -35,7 +35,7 @@ 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, useFileDropZone, FileDropOverlay } from "../editor";
+import { ContentEditor, type ContentEditorRef, TitleEditor, useFileDropZone, FileDropOverlay, useUploadGate, useEditorUpload } from "../editor";
import { StatusIcon, StatusPicker, PriorityPicker, StagePicker, AssigneePicker, StartDatePicker, DueDatePicker, LabelPicker } from "../issues/components";
import { maxSiblingStage } from "../issues/components/pickers/stage-picker";
import { ProjectPicker } from "../projects/components/project-picker";
@@ -49,9 +49,7 @@ import { useQuickCreateStore } from "@multica/core/issues/stores/quick-create-st
import { issueDetailOptions, childIssuesOptions } from "@multica/core/issues/queries";
import { useCreateIssue, useUpdateIssue } from "@multica/core/issues/mutations";
import { useAttachLabelToIssue } from "@multica/core/labels";
-import { useFileUpload } from "@multica/core/hooks/use-file-upload";
import {
- api,
ApiError,
DuplicateIssueErrorBodySchema,
type DuplicateIssueErrorBody,
@@ -190,6 +188,7 @@ export function ManualCreatePanel({
setIsExpanded: (v: boolean) => void;
}) {
const { t } = useT("modals");
+ const { t: tEditor } = useT("editor");
const router = useNavigation();
const p = useWorkspacePaths();
const workspaceName = useCurrentWorkspace()?.name;
@@ -283,7 +282,11 @@ export function ManualCreatePanel({
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
- const { uploadWithToast } = useFileUpload(api);
+ const { uploadWithToast } = useEditorUpload();
+ // Gate every action that fixes this draft: Create, Enter on the title, and
+ // the switch to agent mode (which re-serializes the description into a
+ // prompt and would carry a stripped body across).
+ const uploadGate = useUploadGate(descEditorRef);
const handleUpload = async (file: File) => {
const result = await uploadWithToast(file);
if (result) {
@@ -341,6 +344,8 @@ export function ManualCreatePanel({
const handleSubmit = async () => {
if (!title.trim() || submitting) return;
+ // Covers both the Create button and TitleEditor's Enter, which route here.
+ if (uploadGate.isBlocked()) return;
setSubmitting(true);
try {
const description = descEditorRef.current?.getMarkdown()?.trim() || undefined;
@@ -527,6 +532,10 @@ export function ManualCreatePanel({
// needs it so the new issue is still created as a sub-issue when the user
// flips from "Add sub issue" → "Create with agent".
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
@@ -624,6 +633,7 @@ export function ManualCreatePanel({
placeholder={t(($) => $.create_issue.description_placeholder)}
onUpdate={(md) => setDraft({ description: md })}
onUploadFile={handleUpload}
+ onUploadingChange={uploadGate.onUploadingChange}
debounceMs={500}
attachments={draftAttachments}
/>
@@ -872,8 +882,11 @@ export function ManualCreatePanel({
<button
type="button"
onClick={switchToAgent}
+ disabled={uploadGate.uploading}
+ aria-disabled={uploadGate.uploading || undefined}
+ aria-busy={uploadGate.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"
+ 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"
>
<ArrowLeftRight className="size-3.5 text-brand/80 transition-transform duration-300 group-hover:rotate-180" />
{t(($) => $.create_issue.switch_to_agent)}
@@ -894,8 +907,18 @@ export function ManualCreatePanel({
</Tooltip>
</TooltipProvider>
) : (
- <Button size="sm" onClick={handleSubmit} disabled={submitting}>
- {submitting ? t(($) => $.create_issue.submitting) : t(($) => $.create_issue.submit)}
+ <Button
+ size="sm"
+ onClick={handleSubmit}
+ disabled={submitting || uploadGate.uploading}
+ aria-disabled={uploadGate.uploading || undefined}
+ aria-busy={uploadGate.uploading || undefined}
+ >
+ {submitting
+ ? t(($) => $.create_issue.submitting)
+ : uploadGate.uploading
+ ? tEditor(($) => $.upload.in_progress)
+ : t(($) => $.create_issue.submit)}
</Button>
)}
</div>
diff --git a/packages/views/modals/feedback.test.tsx b/packages/views/modals/feedback.test.tsx
index f65638d046..94cb436aa7 100644
--- a/packages/views/modals/feedback.test.tsx
+++ b/packages/views/modals/feedback.test.tsx
@@ -1,10 +1,24 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
-import { fireEvent, render, screen, waitFor } from "@testing-library/react";
-import { forwardRef, useImperativeHandle } from "react";
+import { act, fireEvent, render, screen, waitFor } from "@testing-library/react";
+import { forwardRef, useImperativeHandle, useRef } from "react";
let storedDraftMessage = "saved draft";
let liveEditorMarkdown = "";
const feedbackMocks = vi.hoisted(() => ({ mutateAsync: vi.fn() }));
+// Deferred controlling the mock editor's in-flight upload: `reset` arms a new
+// pending upload, `resolve` lands it so a test can watch the gate re-open.
+const pendingUpload = vi.hoisted(() => {
+ const deferred = {
+ promise: Promise.resolve() as Promise<void>,
+ resolve: () => {},
+ reset() {
+ deferred.promise = new Promise<void>((res) => {
+ deferred.resolve = res;
+ });
+ },
+ };
+ return deferred;
+});
vi.mock("react-i18next", () => ({
useTranslation: () => ({ t: (key: string) => key, i18n: { changeLanguage: vi.fn() } }),
@@ -28,6 +42,11 @@ vi.mock("../i18n", () => ({
sending: "Sending",
send: "Send",
},
+ // The `editor` namespace's shared upload-gate copy. This mock ignores
+ // the namespace argument, so both bundles live in one object.
+ upload: {
+ in_progress: "Uploading…",
+ },
}),
}),
}));
@@ -44,13 +63,31 @@ vi.mock("@multica/core/feedback", () => ({
useFeedbackDraftStore: (selector: any) =>
selector({ draft: { message: storedDraftMessage }, setDraft: vi.fn(), clearDraft: vi.fn() }),
}));
-vi.mock("../editor", () => {
- const ContentEditor = forwardRef(({ defaultValue, onSubmit }: any, ref) => {
+vi.mock("../editor", async () => {
+ // Real submit gate (pure React) driven by the mock editor's
+ // `hasActiveUploads` / `onUploadingChange`.
+ const uploadGate = await vi.importActual<typeof import("../editor/use-upload-gate")>(
+ "../editor/use-upload-gate",
+ );
+ const ContentEditor = forwardRef(({ defaultValue, onSubmit, onUploadingChange }: any, ref) => {
liveEditorMarkdown = defaultValue;
+ // Mirrors the real editor: the placeholder node is in the doc from before
+ // the await until the upload settles, and the host hears about it through
+ // onUploadingChange rather than polling.
+ const inFlightRef = useRef(0);
useImperativeHandle(ref, () => ({
- hasActiveUploads: () => false,
+ hasActiveUploads: () => inFlightRef.current > 0,
getMarkdown: () => liveEditorMarkdown,
- uploadFile: vi.fn(),
+ uploadFile: async () => {
+ inFlightRef.current += 1;
+ if (inFlightRef.current === 1) onUploadingChange?.(true);
+ try {
+ await pendingUpload.promise;
+ } finally {
+ inFlightRef.current -= 1;
+ if (inFlightRef.current === 0) onUploadingChange?.(false);
+ }
+ },
}));
return (
<textarea
@@ -65,6 +102,12 @@ vi.mock("../editor", () => {
});
ContentEditor.displayName = "MockContentEditor";
return {
+ ...uploadGate,
+ useEditorUpload: () => ({
+ uploadWithToast: vi.fn(),
+ upload: vi.fn(),
+ uploading: false,
+ }),
ContentEditor,
useFileDropZone: () => ({ isDragOver: false, dropZoneProps: {} }),
FileDropOverlay: () => null,
@@ -116,4 +159,55 @@ describe("FeedbackModal", () => {
);
});
});
+
+ // MUL-4808 — Feedback refused to submit mid-upload inside the handler, but
+ // the Send button stayed enabled, so the only signal was a toast fired after
+ // a click that looked like it should have worked.
+ describe("upload submit gate", () => {
+ function startPendingUpload() {
+ pendingUpload.reset();
+ // The modal renders through a portal, so its file input lives on
+ // document.body rather than under render()'s container.
+ const input = document.body.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" })] },
+ });
+ }
+
+ it("disables Send and shows Uploading… while an upload is in flight", async () => {
+ // Seeded through the draft so `message` is non-empty on mount — that
+ // isolates the disabled state to the upload gate rather than the
+ // empty-content check.
+ storedDraftMessage = "here's a screenshot";
+ render(<FeedbackModal onClose={vi.fn()} />);
+
+ startPendingUpload();
+
+ const send = await screen.findByRole("button", { name: "Uploading…" });
+ await waitFor(() => expect(send).toBeDisabled());
+ expect(send).toHaveAttribute("aria-busy", "true");
+
+ await act(async () => { pendingUpload.resolve(); });
+ await waitFor(() =>
+ expect(screen.getByRole("button", { name: "Send" })).not.toBeDisabled(),
+ );
+ });
+
+ it("blocks the Cmd+Enter path while an upload is in flight", async () => {
+ storedDraftMessage = "here's a screenshot";
+ render(<FeedbackModal onClose={vi.fn()} />);
+ const editor = screen.getByLabelText("feedback editor");
+
+ startPendingUpload();
+
+ fireEvent.keyDown(editor, { key: "Enter", metaKey: true });
+ await Promise.resolve();
+ expect(feedbackMocks.mutateAsync).not.toHaveBeenCalled();
+
+ await act(async () => { pendingUpload.resolve(); });
+ fireEvent.keyDown(editor, { key: "Enter", metaKey: true });
+ await waitFor(() => expect(feedbackMocks.mutateAsync).toHaveBeenCalled());
+ });
+ });
});
diff --git a/packages/views/modals/feedback.tsx b/packages/views/modals/feedback.tsx
index 714b1f3a5b..264d9bf668 100644
--- a/packages/views/modals/feedback.tsx
+++ b/packages/views/modals/feedback.tsx
@@ -15,6 +15,8 @@ import {
type ContentEditorRef,
useFileDropZone,
FileDropOverlay,
+ useUploadGate,
+ useEditorUpload,
} from "../editor";
import {
useCreateFeedback,
@@ -23,8 +25,6 @@ import {
type FeedbackKind,
} from "@multica/core/feedback";
import { useCurrentWorkspace } from "@multica/core/paths";
-import { useFileUpload } from "@multica/core/hooks/use-file-upload";
-import { api } from "@multica/core/api";
import { useT } from "../i18n";
import { useShortcut } from "@multica/core/shortcuts";
import { ShortcutKeycaps } from "../common/shortcut-keycaps";
@@ -57,6 +57,7 @@ export function FeedbackModal({
}) {
const sendShortcut = useShortcut("send");
const { t } = useT("modals");
+ const { t: tEditor } = useT("editor");
const workspace = useCurrentWorkspace();
const draft = useFeedbackDraftStore((s) => s.draft);
const setDraft = useFeedbackDraftStore((s) => s.setDraft);
@@ -73,20 +74,26 @@ export function FeedbackModal({
const { isDragOver, dropZoneProps } = useFileDropZone({
onDrop: (files) => files.forEach((f) => editorRef.current?.uploadFile(f)),
});
- const { uploadWithToast } = useFileUpload(api);
+ const { uploadWithToast } = useEditorUpload();
+ // The handler already refused to submit mid-upload, but the button stayed
+ // clickable — so the only feedback was a toast fired after the click.
+ const uploadGate = useUploadGate(editorRef);
const mutation = useCreateFeedback();
const canSubmit =
message.trim().length > 0 &&
message.length <= MAX_MESSAGE_LEN &&
- !mutation.isPending;
+ !mutation.isPending &&
+ !uploadGate.uploading;
const handleSubmit = async () => {
// The button can use debounced `message` state, but the keyboard shortcut
// must not: Command+Enter can arrive before ContentEditor's 150ms onUpdate
// fires. The editor ref below is the submit-time source of truth.
if (mutation.isPending) return;
- if (editorRef.current?.hasActiveUploads()) {
+ // Keep the toast on this path: the shortcut can fire while the button is
+ // disabled and off-screen, so a silent no-op would read as a dead ⌘+Enter.
+ if (uploadGate.isBlocked()) {
toast.info(t(($) => $.feedback.toast_uploading));
return;
}
@@ -147,6 +154,7 @@ export function FeedbackModal({
placeholder={t(($) => $.feedback.placeholder)}
onUpdate={(md) => { setMessage(md); setDraft({ message: md }); }}
onUploadFile={uploadWithToast}
+ onUploadingChange={uploadGate.onUploadingChange}
onSubmit={handleSubmit}
debounceMs={150}
showBubbleMenu={false}
@@ -162,8 +170,18 @@ export function FeedbackModal({
multiple
onSelect={(file) => editorRef.current?.uploadFile(file)}
/>
- <Button size="sm" onClick={handleSubmit} disabled={!canSubmit}>
- {mutation.isPending ? t(($) => $.feedback.sending) : t(($) => $.feedback.send)}
+ <Button
+ size="sm"
+ onClick={handleSubmit}
+ disabled={!canSubmit}
+ aria-disabled={uploadGate.uploading || undefined}
+ aria-busy={uploadGate.uploading || undefined}
+ >
+ {mutation.isPending
+ ? t(($) => $.feedback.sending)
+ : uploadGate.uploading
+ ? tEditor(($) => $.upload.in_progress)
+ : t(($) => $.feedback.send)}
{sendShortcut ? (
<ShortcutKeycaps
shortcut={sendShortcut}
diff --git a/packages/views/modals/quick-create-issue.test.tsx b/packages/views/modals/quick-create-issue.test.tsx
index 7e982029ff..91c52546b2 100644
--- a/packages/views/modals/quick-create-issue.test.tsx
+++ b/packages/views/modals/quick-create-issue.test.tsx
@@ -141,10 +141,29 @@ vi.mock("../common/pill-button", () => ({
PillButton: () => <div data-testid="pill-button" />,
}));
-vi.mock("../editor", () => {
- const ContentEditor = forwardRef(({ defaultValue, onUpdate, onSubmit, onUploadFile, placeholder }: any, ref: any) => {
+vi.mock("../editor", async () => {
+ // Real submit gate (pure React) driven by the mock editor's
+ // `hasActiveUploads` / `onUploadingChange`.
+ const uploadGate = await vi.importActual<typeof import("../editor/use-upload-gate")>(
+ "../editor/use-upload-gate",
+ );
+ const ContentEditor = forwardRef(({ defaultValue, onUpdate, onSubmit, onUploadFile, onUploadingChange, placeholder }: any, ref: any) => {
const valueRef = useRef(defaultValue || "");
const [value, setValue] = useState(defaultValue || "");
+ // Mirrors the real editor's `uploading` node attrs: the placeholder sits
+ // in the doc from before the await until the upload settles, which is what
+ // `hasActiveUploads` reports and `onUploadingChange` publishes.
+ const inFlightRef = useRef(0);
+ const runUpload = async (file: File) => {
+ inFlightRef.current += 1;
+ if (inFlightRef.current === 1) onUploadingChange?.(true);
+ try {
+ return await onUploadFile?.(file);
+ } finally {
+ inFlightRef.current -= 1;
+ if (inFlightRef.current === 0) onUploadingChange?.(false);
+ }
+ };
useImperativeHandle(ref, () => ({
getMarkdown: () => valueRef.current,
@@ -152,13 +171,9 @@ vi.mock("../editor", () => {
valueRef.current = "";
setValue("");
},
- uploadFile: vi.fn(),
+ uploadFile: runUpload,
focus: vi.fn(),
- // Real ContentEditor checks ProseMirror node attrs for any `uploading:
- // true` marker. The mock returns false because none of these tests drive
- // a real in-flight upload through the editor — the multi-upload race is
- // covered as a unit test against useFileUpload directly (MUL-3339).
- hasActiveUploads: () => false,
+ hasActiveUploads: () => inFlightRef.current > 0,
}));
return (
@@ -179,7 +194,7 @@ vi.mock("../editor", () => {
/>
<button
type="button"
- onClick={() => onUploadFile?.(new File(["image"], "shot.png", { type: "image/png" }))}
+ onClick={() => runUpload(new File(["image"], "shot.png", { type: "image/png" }))}
>
Mock editor upload
</button>
@@ -189,6 +204,12 @@ vi.mock("../editor", () => {
ContentEditor.displayName = "ContentEditor";
return {
+ ...uploadGate,
+ useEditorUpload: () => ({
+ uploadWithToast: mockUploadWithToast,
+ upload: vi.fn(),
+ uploading: false,
+ }),
ContentEditor,
useFileDropZone: () => ({ isDragOver: false, dropZoneProps: {} }),
FileDropOverlay: () => null,
@@ -265,7 +286,11 @@ vi.mock("@multica/ui/components/ui/switch", () => ({
}));
vi.mock("@multica/ui/components/common/file-upload-button", () => ({
- FileUploadButton: () => <button type="button">Upload file</button>,
+ // `disabled` is forwarded so the "can still queue another file mid-upload"
+ // guarantee is actually assertable here (MUL-4808).
+ FileUploadButton: ({ disabled }: { disabled?: boolean }) => (
+ <button type="button" disabled={disabled}>Upload file</button>
+ ),
}));
vi.mock("sonner", () => ({
@@ -526,4 +551,45 @@ describe("AgentCreatePanel", () => {
renderPanel({ onClose: vi.fn(), isExpanded: false, setIsExpanded: vi.fn() });
expect(screen.queryByTestId("agent-sub-issue-chip")).toBeNull();
});
+
+ // MUL-4808 — Quick Create already gated Create; these pin the two gaps:
+ // the mode switch (which re-serializes the prompt into the manual draft)
+ // and the file button that used to lock during an upload for no reason.
+ describe("upload submit gate", () => {
+ function startPendingUpload() {
+ let release!: (result: unknown) => void;
+ mockUploadWithToast.mockImplementationOnce(
+ () => new Promise((resolve) => { release = resolve; }),
+ );
+ fireEvent.click(screen.getByRole("button", { name: "Mock editor upload" }));
+ return { release: (result: unknown) => release(result) };
+ }
+
+ it("blocks Switch to Manual while an upload is in flight", async () => {
+ const onSwitchMode = vi.fn();
+ renderPanel({ onClose: vi.fn(), onSwitchMode, isExpanded: false, setIsExpanded: vi.fn() });
+
+ startPendingUpload();
+
+ // The switch hands the serialized prompt to the manual panel — mid-upload
+ // that prompt has already lost the pending image.
+ const switchButton = screen.getByRole("button", { name: /Switch to Manual/i });
+ await waitFor(() => expect(switchButton).toBeDisabled());
+ fireEvent.click(switchButton);
+ expect(onSwitchMode).not.toHaveBeenCalled();
+ });
+
+ it("keeps the attach-file button usable during an upload so files can queue", async () => {
+ renderPanel({ onClose: vi.fn(), isExpanded: false, setIsExpanded: vi.fn() });
+
+ startPendingUpload();
+
+ // Each file is its own queue entry — making users wait for the first to
+ // land before picking the second was a restriction with no race behind
+ // it, and this issue explicitly removed it.
+ const submit = await screen.findByRole("button", { name: "Uploading…" });
+ expect(submit).toBeDisabled();
+ expect(screen.getByRole("button", { name: "Upload file" })).not.toBeDisabled();
+ });
+ });
});
diff --git a/packages/views/modals/quick-create-issue.tsx b/packages/views/modals/quick-create-issue.tsx
index 12fb900e28..c076f57a23 100644
--- a/packages/views/modals/quick-create-issue.tsx
+++ b/packages/views/modals/quick-create-issue.tsx
@@ -24,7 +24,6 @@ import {
readRuntimeCliVersion,
MIN_QUICK_CREATE_CLI_VERSION,
} from "@multica/core/runtimes";
-import { useFileUpload } from "@multica/core/hooks/use-file-upload";
import { useShortcut } from "@multica/core/shortcuts";
import { ShortcutKeycaps } from "../common/shortcut-keycaps";
import { contentReferencesAttachment, type Agent, type Attachment, type Squad } from "@multica/core/types";
@@ -45,6 +44,8 @@ import {
type ContentEditorRef,
useFileDropZone,
FileDropOverlay,
+ useUploadGate,
+ useEditorUpload,
} from "../editor";
import { FileUploadButton } from "@multica/ui/components/common/file-upload-button";
import { useT } from "../i18n";
@@ -264,7 +265,11 @@ export function AgentCreatePanel({
// 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, uploading } = useFileUpload(api);
+ 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) {
@@ -288,15 +293,12 @@ export function AgentCreatePanel({
const submit = async () => {
const md = editorRef.current?.getMarkdown()?.trim() ?? "";
- if (!md || !actor || submitting || versionBlocked || uploading) return;
- // Belt-and-suspenders against the multi-file upload race fixed in
- // useFileUpload (MUL-3339): `uploading` already tracks an in-flight
- // counter now, but the editor's per-node `uploading` attr is the most
- // direct truth — if any image node is still mid-upload, blocking submit
- // here guarantees `getMarkdown()`'s blob-url strip never erases a
- // pasted/dropped image whose attachment id hasn't reached
- // `pendingAttachments` yet.
- if (editorRef.current?.hasActiveUploads()) return;
+ if (!md || !actor || submitting || 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);
@@ -382,6 +384,9 @@ export function AgentCreatePanel({
// store directly because the manual panel reads its initial values from
// there. Persist the mode flip so the next `c` lands in manual.
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,
@@ -490,6 +495,7 @@ export function AgentCreatePanel({
setPrompt(md);
}}
onUploadFile={handleUploadFile}
+ onUploadingChange={uploadGate.onUploadingChange}
attachments={pendingAttachments}
onSubmit={submit}
debounceMs={150}
@@ -539,10 +545,12 @@ export function AgentCreatePanel({
{/* Footer */}
<div className="flex flex-col gap-2 border-t px-4 py-3 shrink-0 sm:flex-row sm:items-center sm:justify-between">
<div className="flex min-h-7 items-center gap-2">
+ {/* Deliberately NOT disabled while uploading: each file is its
+ own queue entry, so queueing a second one is safe and waiting
+ for the first to land just to attach the next is busywork. */}
<FileUploadButton
size="sm"
multiple
- disabled={uploading}
onSelect={(file) => editorRef.current?.uploadFile(file)}
/>
{keepOpen && sentCount > 0 && (
@@ -555,8 +563,11 @@ export function AgentCreatePanel({
<button
type="button"
onClick={switchToManual}
+ disabled={uploadGate.uploading}
+ aria-disabled={uploadGate.uploading || undefined}
+ aria-busy={uploadGate.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"
+ 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"
>
<ArrowLeftRight className="size-3.5" />
{t(($) => $.create_issue.switch_to_manual)}
@@ -572,7 +583,9 @@ export function AgentCreatePanel({
<Button
size="sm"
onClick={submit}
- disabled={!hasContent || !actor || submitting || versionBlocked || uploading}
+ disabled={!hasContent || !actor || submitting || versionBlocked || uploadGate.uploading}
+ aria-disabled={uploadGate.uploading || undefined}
+ aria-busy={uploadGate.uploading || undefined}
title={
versionBlocked
? t(($) => $.create_issue.agent.version_blocked_tooltip, { min: versionCheck.min })
@@ -580,7 +593,7 @@ export function AgentCreatePanel({
}
className={justSent ? "min-w-28 !bg-emerald-600 !text-white" : "min-w-28"}
>
- {submitting ? t(($) => $.create_issue.agent.sending) : uploading ? t(($) => $.create_issue.agent.uploading) : justSent ? (
+ {submitting ? t(($) => $.create_issue.agent.sending) : uploadGate.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>
) : (
<>