Skip to content

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

Go

feat(editor): 粘贴超长文本自动转为文本附件 (#6019)

Naiyuan Qing995ec8fcf21d
diff --git a/packages/views/chat/components/chat-input-draft-isolation.test.tsx b/packages/views/chat/components/chat-input-draft-isolation.test.tsx
index af3d64309e..ffb0da1387 100644
--- a/packages/views/chat/components/chat-input-draft-isolation.test.tsx
+++ b/packages/views/chat/components/chat-input-draft-isolation.test.tsx
@@ -67,7 +67,12 @@ vi.mock("../../editor/extensions", () => ({
// starts), and on completion the real implementation dispatches into the SAME
// editor instance — which is what fires onUpdate. Tests drive that dispatch
// explicitly via `finishUpload()`.
-vi.mock("../../editor/extensions/file-upload", () => ({
+vi.mock("../../editor/extensions/file-upload", async () => ({
+ // Only the insert flow is stubbed; the paste-as-file tagging helpers are
+ // plain module state the upload hook reads on every settle.
+ ...(await vi.importActual<typeof import("../../editor/extensions/file-upload")>(
+ "../../editor/extensions/file-upload",
+ )),
uploadAndInsertFile: async (
_editor: unknown,
file: File,
diff --git a/packages/views/chat/components/chat-input.tsx b/packages/views/chat/components/chat-input.tsx
index 9ef2c3790f..1265a9d58b 100644
--- a/packages/views/chat/components/chat-input.tsx
+++ b/packages/views/chat/components/chat-input.tsx
@@ -12,6 +12,7 @@ import {
useUploadGate,
useComposerSubmit,
} from "../../editor";
+import { PASTE_AS_FILE_THRESHOLD } from "../../editor/paste-as-file";
import {
useCoordinatedUploads,
type UploadDraftBinding,
@@ -631,6 +632,7 @@ export function ChatInput({
}}
onSubmit={submit}
onUploadFile={uploadEnabled ? handleUpload : undefined}
+ pasteAsFileThreshold={PASTE_AS_FILE_THRESHOLD}
onUploadingChange={uploadGate.onUploadingChange}
attachments={draftAttachments}
debounceMs={100}
diff --git a/packages/views/editor/content-editor.tsx b/packages/views/editor/content-editor.tsx
index a4587a0b33..be13c70333 100644
--- a/packages/views/editor/content-editor.tsx
+++ b/packages/views/editor/content-editor.tsx
@@ -121,6 +121,17 @@ interface ContentEditorBaseProps {
onSubmit?: () => void;
onBlur?: () => void;
onUploadFile?: (file: File) => Promise<UploadResult | null>;
+ /**
+ * Character count above which a plain-text paste is uploaded as a
+ * `pasted-text.txt` attachment instead of being inserted as body text.
+ * Requires `onUploadFile`; without an uploader the paste stays text.
+ *
+ * Opt-in ON PURPOSE. It belongs to turn-based composers (chat, comments),
+ * where a wall of pasted text is context for one message and reads better
+ * as an attachment. Document-style editors — issue and project descriptions
+ * — must never pass it: there, a long paste IS the content.
+ */
+ pasteAsFileThreshold?: number;
/**
* Fired whenever this editor's "any attachment still uploading" answer
* flips. The document IS the upload queue — every path (paste, drop, the
@@ -305,6 +316,7 @@ const ContentEditor = forwardRef<ContentEditorRef, ContentEditorProps>(
onSubmit,
onBlur,
onUploadFile,
+ pasteAsFileThreshold,
onUploadingChange,
showBubbleMenu = true,
currentIssueId,
@@ -333,6 +345,10 @@ const ContentEditor = forwardRef<ContentEditorRef, ContentEditorProps>(
const onUploadFileRef = useRef<
((file: File) => Promise<UploadResult | null>) | undefined
>(undefined);
+ // Same reasoning as placeholderRef below: the extension array is built once
+ // at mount, so the paste-as-file threshold is read through a ref to stay
+ // live without remounting the editor.
+ const pasteAsFileThresholdRef = useRef<number | undefined>(pasteAsFileThreshold);
const mentionContextItemsRef = useRef<MentionItem[]>(mentionContextItems ?? []);
const lastEmittedRef = useRef<string | null>(null);
// `content` already consumes the initial synchronized value when Tiptap
@@ -427,6 +443,7 @@ const ContentEditor = forwardRef<ContentEditorRef, ContentEditorProps>(
onReadyRef.current = onReady;
onUploadingChangeRef.current = onUploadingChange;
onUploadFileRef.current = wrappedOnUploadFile;
+ pasteAsFileThresholdRef.current = pasteAsFileThreshold;
mentionContextItemsRef.current = mentionContextItems ?? [];
flushPendingOnUnmountRef.current = flushPendingOnUnmount;
@@ -524,6 +541,7 @@ const ContentEditor = forwardRef<ContentEditorRef, ContentEditorProps>(
queryClient,
onSubmitRef,
onUploadFileRef,
+ pasteAsFileThresholdRef,
disableMentions,
mentionMode,
getMentionContextItems: () => mentionContextItemsRef.current,
diff --git a/packages/views/editor/extensions/file-upload.test.ts b/packages/views/editor/extensions/file-upload.test.ts
index c17388d068..93f32d9900 100644
--- a/packages/views/editor/extensions/file-upload.test.ts
+++ b/packages/views/editor/extensions/file-upload.test.ts
@@ -1,10 +1,17 @@
-import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
import { Editor } from "@tiptap/core";
import StarterKit from "@tiptap/starter-kit";
import { Markdown } from "@tiptap/markdown";
+import { Slice } from "@tiptap/pm/model";
import type { UploadResult } from "@multica/core/hooks/use-file-upload";
-import { ImageExtension } from "./index";
-import { uploadAndInsertFile } from "./file-upload";
+import { ImageExtension, createEditorExtensions } from "./index";
+import { FileCardExtension } from "./file-card";
+import {
+ createFileUploadExtension,
+ uploadAndInsertFile,
+ pastedTextSource,
+ PASTED_TEXT_FILENAME,
+} from "./file-upload";
const BLOB_URL = "blob:test-image";
const FINAL_URL = "https://cdn.example.com/photo.png";
@@ -68,6 +75,31 @@ function makeUpload(
};
}
+// jsdom lays nothing out, so ProseMirror's scrollToSelection (reached via the
+// `focus()` in the fileCard insert) throws on the missing rect APIs. Same stub
+// set as suggestion-popup.test.tsx.
+beforeAll(() => {
+ const rect = () => new DOMRect(0, 0, 0, 0);
+ const rectList = () =>
+ ({ length: 0, item: () => null, [Symbol.iterator]: function* () {} }) as DOMRectList;
+ Object.defineProperty(Range.prototype, "getBoundingClientRect", {
+ configurable: true,
+ value: rect,
+ });
+ Object.defineProperty(Range.prototype, "getClientRects", {
+ configurable: true,
+ value: rectList,
+ });
+ Object.defineProperty(HTMLElement.prototype, "getClientRects", {
+ configurable: true,
+ value: rectList,
+ });
+ Object.defineProperty(Text.prototype, "getClientRects", {
+ configurable: true,
+ value: rectList,
+ });
+});
+
beforeEach(() => {
originalCreateObjectURL = URL.createObjectURL;
originalRevokeObjectURL = URL.revokeObjectURL;
@@ -224,3 +256,188 @@ describe("uploadAndInsertFile", () => {
expect(editor.getMarkdown()).not.toContain("?sig=");
});
});
+
+describe("paste-as-file", () => {
+ const THRESHOLD = 20;
+
+ function makePasteEditor(opts: {
+ handler?: (file: File) => Promise<UploadResult | null>;
+ threshold?: number;
+ }) {
+ const onUploadFileRef = { current: opts.handler };
+ const thresholdRef = { current: opts.threshold };
+ const element = document.createElement("div");
+ document.body.appendChild(element);
+ const editor = new Editor({
+ element,
+ extensions: [
+ StarterKit,
+ ImageExtension,
+ FileCardExtension,
+ Markdown.configure({ indentation: { style: "space", size: 3 } }),
+ createFileUploadExtension(
+ onUploadFileRef as React.RefObject<
+ ((file: File) => Promise<UploadResult | null>) | undefined
+ >,
+ thresholdRef as React.RefObject<number | undefined>,
+ ),
+ ],
+ });
+ editors.push(editor);
+ return editor;
+ }
+
+ /** Drive the plugin's handlePaste the way ProseMirror does, and report
+ * whether any plugin claimed the event. */
+ function paste(editor: Editor, opts: { text?: string; files?: File[] }) {
+ const event = {
+ clipboardData: {
+ files: opts.files ?? [],
+ getData: (type: string) => (type === "text/plain" ? (opts.text ?? "") : ""),
+ },
+ } as unknown as ClipboardEvent;
+ let handled = false;
+ editor.view.someProp("handlePaste", (fn) => {
+ handled = fn(editor.view, event, Slice.empty) === true;
+ return handled;
+ });
+ return handled;
+ }
+
+ it("uploads an over-threshold plain-text paste as pasted-text.txt and keeps it out of the body", async () => {
+ const upload = deferred<UploadResult | null>();
+ const handler = vi.fn((_file: File) => upload.promise);
+ const editor = makePasteEditor({ handler, threshold: THRESHOLD });
+ const long = "x".repeat(THRESHOLD + 1);
+
+ expect(paste(editor, { text: long })).toBe(true);
+
+ await vi.waitFor(() => expect(handler).toHaveBeenCalled());
+ const file = handler.mock.calls[0]![0];
+ expect(file.name).toBe(PASTED_TEXT_FILENAME);
+ expect(file.type).toBe("text/plain");
+ await expect(file.text()).resolves.toBe(long);
+
+ // The text itself never lands in the document — only the upload card.
+ expect(editor.getMarkdown()).not.toContain(long);
+
+ upload.resolve(
+ makeUpload({
+ id: "attachment-9",
+ link: "/api/attachments/attachment-9/download",
+ filename: PASTED_TEXT_FILENAME,
+ }),
+ );
+ await vi.waitFor(() =>
+ expect(editor.getMarkdown()).toContain("/api/attachments/attachment-9/download"),
+ );
+ });
+
+ it("leaves a paste at or below the threshold as ordinary text", () => {
+ const handler = vi.fn(async () => null);
+ const editor = makePasteEditor({ handler, threshold: THRESHOLD });
+
+ expect(paste(editor, { text: "x".repeat(THRESHOLD) })).toBe(false);
+ expect(handler).not.toHaveBeenCalled();
+ });
+
+ it("does not convert when the host passes no threshold", () => {
+ const handler = vi.fn(async () => null);
+ const editor = makePasteEditor({ handler, threshold: undefined });
+
+ expect(paste(editor, { text: "x".repeat(10_000) })).toBe(false);
+ expect(handler).not.toHaveBeenCalled();
+ });
+
+ it("does not convert when the host wired no uploader", () => {
+ const editor = makePasteEditor({ handler: undefined, threshold: THRESHOLD });
+
+ // Degrades to a plain-text paste rather than swallowing the event.
+ expect(paste(editor, { text: "x".repeat(THRESHOLD + 1) })).toBe(false);
+ });
+
+ it("still takes the real-file path when the clipboard carries a file", async () => {
+ const handler = vi.fn(async (_file: File) => null);
+ const editor = makePasteEditor({ handler, threshold: THRESHOLD });
+ const real = new File(["image"], "photo.png", { type: "image/png" });
+
+ expect(paste(editor, { text: "x".repeat(THRESHOLD + 1), files: [real] })).toBe(true);
+
+ await vi.waitFor(() => expect(handler).toHaveBeenCalled());
+ expect(handler).toHaveBeenCalledTimes(1);
+ expect(handler.mock.calls[0]![0]).toBe(real);
+ });
+
+ it("tags the synthesised file with its source text so the draft owner can restore it", async () => {
+ const upload = deferred<UploadResult | null>();
+ const handler = vi.fn((_file: File) => upload.promise);
+ const editor = makePasteEditor({ handler, threshold: THRESHOLD });
+ const long = "x".repeat(THRESHOLD + 1);
+
+ paste(editor, { text: long });
+
+ await vi.waitFor(() => expect(handler).toHaveBeenCalled());
+ // The recovery path lives in useCoordinatedUploads (the only layer that
+ // outlives the mount and owns the draft); this is the channel it reads.
+ expect(pastedTextSource(handler.mock.calls[0]![0])).toBe(long);
+
+ upload.resolve(null);
+ });
+
+ it("does not tag a real dropped file", async () => {
+ const handler = vi.fn(async (_file: File) => null);
+ const editor = makePasteEditor({ handler, threshold: THRESHOLD });
+ const real = new File(["image"], "photo.png", { type: "image/png" });
+
+ paste(editor, { files: [real] });
+
+ await vi.waitFor(() => expect(handler).toHaveBeenCalled());
+ expect(pastedTextSource(real)).toBeUndefined();
+ });
+
+ it("wins the paste over markdownPaste in the REAL extension order", async () => {
+ // Both paste handlers are catch-alls, so which one ProseMirror consults
+ // first is the whole feature. Tiptap reverses the extension array before
+ // collecting plugins (@tiptap/core `get plugins()`), and neither extension
+ // sets a priority — so the ordering that decides this lives in
+ // createEditorExtensions, not in either file. Build the production array so
+ // a reorder there fails HERE instead of silently disabling the feature.
+ const upload = deferred<UploadResult | null>();
+ const handler = vi.fn((_file: File) => upload.promise);
+ const onUploadFileRef = { current: handler };
+ const thresholdRef = { current: THRESHOLD };
+ const element = document.createElement("div");
+ document.body.appendChild(element);
+ const editor = new Editor({
+ element,
+ extensions: createEditorExtensions({
+ onUploadFileRef: onUploadFileRef as React.RefObject<
+ ((file: File) => Promise<UploadResult | null>) | undefined
+ >,
+ pasteAsFileThresholdRef: thresholdRef as React.RefObject<number | undefined>,
+ disableMentions: true,
+ }),
+ });
+ editors.push(editor);
+
+ const long = "# heading\n\n" + "x".repeat(THRESHOLD + 1);
+ expect(paste(editor, { text: long })).toBe(true);
+
+ await vi.waitFor(() => expect(handler).toHaveBeenCalled());
+ expect(handler.mock.calls[0]![0].name).toBe(PASTED_TEXT_FILENAME);
+ // markdownPaste did NOT get to parse it into the body.
+ expect(editor.getMarkdown()).not.toContain("x".repeat(THRESHOLD + 1));
+
+ upload.resolve(null);
+ });
+
+ it("keeps a long paste inline inside a code block", () => {
+ const handler = vi.fn(async (_file: File) => null);
+ const editor = makePasteEditor({ handler, threshold: THRESHOLD });
+ editor.commands.setCodeBlock();
+
+ // Opening a fence IS the request to show the thing inline.
+ expect(paste(editor, { text: "x".repeat(THRESHOLD + 1) })).toBe(false);
+ expect(handler).not.toHaveBeenCalled();
+ });
+});
diff --git a/packages/views/editor/extensions/file-upload.ts b/packages/views/editor/extensions/file-upload.ts
index be8cc7e271..f911532496 100644
--- a/packages/views/editor/extensions/file-upload.ts
+++ b/packages/views/editor/extensions/file-upload.ts
@@ -133,7 +133,7 @@ function moveSelectionToParagraphAfterImage(editor: any, src: string) {
* Used by both paste/drop (at cursor) and button upload (at end of doc).
*/
export async function uploadAndInsertFile(
-
+
editor: any,
file: File,
handler: (file: File) => Promise<UploadResult | null>,
@@ -229,18 +229,54 @@ function dedupFiles(files: FileList): File[] {
});
}
+/** Filename given to the .txt synthesised from an over-threshold paste. */
+export const PASTED_TEXT_FILENAME = "pasted-text.txt";
+
+/**
+ * Source text of every file synthesised by the paste-as-file path, keyed by
+ * the File instance that carries it downstream.
+ *
+ * Unlike a dropped file, this one has no copy anywhere else: the text was
+ * never written into the document and its source may be a tab the user has
+ * already closed. So whoever owns the draft must be able to put it back when
+ * the upload fails. A WeakMap rather than a property on the File keeps the
+ * File exactly as the upload layer expects it, and lets the entry die with the
+ * upload. Read it with {@link pastedTextSource}; a File that came from disk
+ * returns undefined and needs no recovery.
+ */
+const pastedTextSources = new WeakMap<File, string>();
+
+/** Record the text a synthesised paste file was built from. */
+export function markPastedTextFile(file: File, text: string): File {
+ pastedTextSources.set(file, text);
+ return file;
+}
+
+/** The text an over-threshold paste was made from, or undefined for real files. */
+export function pastedTextSource(file: File): string | undefined {
+ return pastedTextSources.get(file);
+}
+
export function createFileUploadExtension(
onUploadFileRef: React.RefObject<((file: File) => Promise<UploadResult | null>) | undefined>,
+ /**
+ * Character count above which a plain-text paste is uploaded as a .txt
+ * attachment instead of being inserted into the document. A ref because the
+ * extension array is built once at mount while the prop that feeds it can
+ * change. Undefined / 0 keeps every paste as text — the default, so an
+ * editor that never opts in behaves exactly as before.
+ */
+ pasteAsFileThresholdRef?: React.RefObject<number | undefined>,
) {
return Extension.create({
name: "fileUpload",
addProseMirrorPlugins() {
const { editor } = this;
- const handleFiles = async (files: FileList) => {
+ const handleFiles = async (files: File[]) => {
const handler = onUploadFileRef.current;
if (!handler) return false;
- for (const file of dedupFiles(files)) {
+ for (const file of files) {
await uploadAndInsertFile(editor, file, handler);
}
return true;
@@ -252,9 +288,27 @@ export function createFileUploadExtension(
props: {
handlePaste(_view, event) {
const files = event.clipboardData?.files;
- if (!files?.length) return false;
+ if (!files?.length) {
+ // No file on the clipboard: this may still be a paste large
+ // enough that the host wants it as an attachment rather than
+ // thousands of characters of body text (turn-based composers
+ // only — document editors never pass a threshold).
+ const threshold = pasteAsFileThresholdRef?.current;
+ if (!threshold || threshold <= 0) return false;
+ const text = event.clipboardData?.getData("text/plain") ?? "";
+ if (text.length <= threshold) return false;
+ if (!onUploadFileRef.current) return false;
+ // A paste INTO a code block is the one long paste that is
+ // deliberately inline — the user opened a fence to show the
+ // thing. Converting it to an attachment would take away what
+ // they just asked for.
+ if (editor.isActive("codeBlock")) return false;
+ const file = new File([text], PASTED_TEXT_FILENAME, { type: "text/plain" });
+ handleFiles([markPastedTextFile(file, text)]);
+ return true;
+ }
if (!onUploadFileRef.current) return false;
- handleFiles(files);
+ handleFiles(dedupFiles(files));
return true;
},
handleDrop(view, event) {
diff --git a/packages/views/editor/extensions/index.ts b/packages/views/editor/extensions/index.ts
index 7bf3619275..9cc4757a05 100644
--- a/packages/views/editor/extensions/index.ts
+++ b/packages/views/editor/extensions/index.ts
@@ -133,6 +133,12 @@ export interface EditorExtensionsOptions {
onUploadFileRef?: RefObject<
((file: File) => Promise<UploadResult | null>) | undefined
>;
+ /**
+ * Character count above which a plain-text paste becomes a .txt attachment
+ * instead of document text. A ref so the value can change without
+ * recreating the editor. Omitted (the default) keeps every paste as text.
+ */
+ pasteAsFileThresholdRef?: RefObject<number | undefined>;
/**
* When true, the `@` suggestion picker is not attached. The mention node
* type is still registered in the schema so any mention pasted in from
@@ -260,6 +266,6 @@ export function createEditorExtensions(
return true;
}),
createBlurShortcutExtension(),
- createFileUploadExtension(options.onUploadFileRef!),
+ createFileUploadExtension(options.onUploadFileRef!, options.pasteAsFileThresholdRef),
];
}
diff --git a/packages/views/editor/paste-as-file.ts b/packages/views/editor/paste-as-file.ts
new file mode 100644
index 0000000000..7a1aa62089
--- /dev/null
+++ b/packages/views/editor/paste-as-file.ts
@@ -0,0 +1,21 @@
+/**
+ * Character count above which a plain-text paste is uploaded as a
+ * `pasted-text.txt` attachment instead of being inserted as body text.
+ *
+ * One shared value so every turn-based composer converts at the same point —
+ * a comment and its edit form disagreeing would let the same content be a file
+ * on the way in and text on the way back out.
+ *
+ * The number is a product judgement, not a technical limit: nothing in this
+ * stack caps message length (no client schema max, the server only rejects
+ * empty content, and every column is unbounded TEXT). Below ~4k a paste is
+ * still scrollable as text; above it the body stops being readable and the
+ * attachment is the better container. For reference, ChatGPT converts at
+ * 10,000 characters and Discord at its 2,000-character message ceiling.
+ *
+ * NOT the same thing as `LARGE_PASTE_TEXT_THRESHOLD` in
+ * `extensions/markdown-paste.ts` — that one (50,000) is a parser bail-out that
+ * keeps a huge paste from running the markdown pipeline, and applies to every
+ * editor including the ones that never convert to a file.
+ */
+export const PASTE_AS_FILE_THRESHOLD = 4000;
diff --git a/packages/views/editor/use-coordinated-uploads.ts b/packages/views/editor/use-coordinated-uploads.ts
index eeefc88c40..386be41bc4 100644
--- a/packages/views/editor/use-coordinated-uploads.ts
+++ b/packages/views/editor/use-coordinated-uploads.ts
@@ -57,6 +57,7 @@ import { MAX_FILE_SIZE } from "@multica/core/constants/upload";
import { useT } from "../i18n";
import type { UploadGate } from "./use-upload-gate";
import type { ContentEditorRef } from "./content-editor";
+import { pastedTextSource } from "./extensions/file-upload";
const EMPTY_ATTACHMENTS: Attachment[] = [];
@@ -156,6 +157,40 @@ function deliverFinishedUpload(
);
}
+/**
+ * Put a failed paste-as-file's source text back where the user can see it.
+ *
+ * The mirror image of {@link deliverFinishedUpload}, and it exists for the
+ * same reason: the upload outlives the mount, so the composer that swallowed
+ * the paste may be gone by the time the failure lands. Unlike a dropped file,
+ * this content has no other copy — it was never written into the document and
+ * the tab it came from may be closed — so "the editor is gone, drop it" would
+ * be silent data loss.
+ *
+ * Restored as markdown, not literal text: had the paste never been converted,
+ * `markdown-paste` is exactly what would have handled it, so this reproduces
+ * what the user would have gotten. Live editor first (it lands at the end of
+ * the document, never mid-sentence at a caret the user has since moved), the
+ * persisted body otherwise.
+ */
+function deliverPastedTextBack(
+ binding: UploadDraftBinding | undefined,
+ editorRef: RefObject<ContentEditorRef | null>,
+ text: string,
+): void {
+ if (!binding) {
+ // No persistence context (a reply composer opened without a draft key):
+ // the live editor is the only place left to put it.
+ editorRef.current?.insertMarkdownAtEnd(text);
+ return;
+ }
+ // Same insurance as deliverFinishedUpload: a landed editor insert can still
+ // lose its debounced emit to a quick unmount, and both writes converge on
+ // identical content.
+ liveEditors.get(binding.registryKey)?.current?.insertMarkdownAtEnd(text);
+ binding.appendToBody(text);
+}
+
export interface CoordinatedUploads {
/** Every upload for this composer (placeholders included) — for status chips. */
uploads: DraftUpload[];
@@ -272,11 +307,17 @@ export function useCoordinatedUploads(
contentType: file.type || undefined,
};
+ const pastedText = pastedTextSource(file);
+
if (file.size > MAX_FILE_SIZE) {
// Never enters the coordinator — surface it as a failed placeholder so
// the composer shows the reason instead of silently dropping the file.
const reason = "File exceeds 100 MB limit";
- if (target) {
+ if (pastedText !== undefined) {
+ // A paste has no on-disk copy to retry from: give the text back
+ // rather than leaving a failed chip standing in for lost content.
+ deliverPastedTextBack(target, editorRef, pastedText);
+ } else if (target) {
target.addUpload(placeholder);
target.failUpload(clientUploadId, reason);
} else {
@@ -330,7 +371,24 @@ export function useCoordinatedUploads(
resolve(toUploadResult(outcome.attachment));
} else {
const reason = outcome.error.message;
- if (target) {
+ if (pastedText !== undefined) {
+ // Paste-as-file: the text has no copy anywhere else, so it is
+ // restored instead of being represented by a failed chip. Runs
+ // whether or not this mount survived — deliverPastedTextBack
+ // owns that choice, and it is the ONLY responder so the live
+ // and dead cases can never both fire or both be skipped.
+ if (target) {
+ if (target.getUploads().some((u) => u.clientUploadId === clientUploadId)) {
+ target.removeUpload(clientUploadId);
+ deliverPastedTextBack(target, editorRef, pastedText);
+ }
+ } else {
+ setLocalUploads((prev) =>
+ prev.filter((u) => u.clientUploadId !== clientUploadId),
+ );
+ deliverPastedTextBack(undefined, editorRef, pastedText);
+ }
+ } else if (target) {
if (target.getUploads().some((u) => u.clientUploadId === clientUploadId)) {
target.failUpload(clientUploadId, reason);
}
@@ -350,7 +408,7 @@ export function useCoordinatedUploads(
});
});
},
- [binding, issueId, commentId, chatSessionId, t],
+ [binding, editorRef, issueId, commentId, chatSessionId, t],
);
const removeUpload = useCallback(
diff --git a/packages/views/issues/components/comment-card.tsx b/packages/views/issues/components/comment-card.tsx
index 8e2306c5b5..7d58333efe 100644
--- a/packages/views/issues/components/comment-card.tsx
+++ b/packages/views/issues/components/comment-card.tsx
@@ -30,6 +30,7 @@ import { copyText } from "@multica/ui/lib/clipboard";
import { useActorName } from "@multica/core/workspace/hooks";
import { useTimeAgo } from "../../i18n";
import { ContentEditor, type ContentEditorRef, ReadonlyContent, useFileDropZone, FileDropOverlay, Attachment as AttachmentRenderer, AttachmentDownloadProvider, useUploadGate, useComposerSubmit } from "../../editor";
+import { PASTE_AS_FILE_THRESHOLD } from "../../editor/paste-as-file";
import { useCommentUploads } from "./use-comment-uploads";
import { ComposerUploadChips } from "./composer-upload-chips";
import { FileUploadButton } from "@multica/ui/components/common/file-upload-button";
@@ -673,6 +674,7 @@ function CommentRow({
}}
onSubmit={edit.saveEdit}
onUploadFile={edit.handleUpload}
+ pasteAsFileThreshold={PASTE_AS_FILE_THRESHOLD}
onUploadingChange={edit.onUploadingChange}
debounceMs={100}
currentIssueId={issueId}
@@ -985,6 +987,7 @@ function CommentCardImpl({
}}
onSubmit={edit.saveEdit}
onUploadFile={edit.handleUpload}
+ pasteAsFileThreshold={PASTE_AS_FILE_THRESHOLD}
onUploadingChange={edit.onUploadingChange}
debounceMs={100}
currentIssueId={issueId}
diff --git a/packages/views/issues/components/comment-composers.test.tsx b/packages/views/issues/components/comment-composers.test.tsx
index ee96ab166b..182b582dc4 100644
--- a/packages/views/issues/components/comment-composers.test.tsx
+++ b/packages/views/issues/components/comment-composers.test.tsx
@@ -6,6 +6,10 @@ import type { UploadResult } from "@multica/core/hooks/use-file-upload";
import type { Attachment } from "@multica/core/types";
import { useCommentComposerStore, useCommentDraftStore } from "@multica/core/issues/stores";
import { renderWithI18n } from "../../test/i18n";
+import {
+ markPastedTextFile,
+ PASTED_TEXT_FILENAME,
+} from "../../editor/extensions/file-upload";
import { CommentInput } from "./comment-input";
import { ReplyInput } from "./reply-input";
@@ -556,7 +560,11 @@ describe("comment composers — upload submit gate", () => {
* coordinator calls `api.uploadFile`, so this controls THAT promise: resolve
* it with an attachment (success) or reject it (failure).
*/
- function startPendingUpload(container: HTMLElement, filename = "slow.png") {
+ function startPendingUpload(
+ container: HTMLElement,
+ filename = "slow.png",
+ file?: File,
+ ) {
let resolveUpload!: (att: Attachment) => void;
let rejectUpload!: (err: Error) => void;
apiUploadFile.mockImplementationOnce(
@@ -571,7 +579,7 @@ describe("comment composers — upload submit gate", () => {
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" })] },
+ target: { files: [file ?? new File(["x"], filename, { type: "image/png" })] },
});
return {
resolve: (att: Attachment) => resolveUpload(att),
@@ -765,6 +773,35 @@ describe("comment composers — upload submit gate", () => {
expect(uploads[0]?.status).toBe("uploaded");
});
+ it("restores a failed paste-as-file's text into the draft even after the composer unmounts", async () => {
+ const pastedText = "a long pasted wall of text that became an attachment";
+ const { container, unmount } = renderCommentInput();
+ activateComposer("comment-composer-shell");
+ fireEvent.change(screen.getByTestId("editor"), { target: { value: "wip text" } });
+
+ const pending = startPendingUpload(
+ container,
+ PASTED_TEXT_FILENAME,
+ markPastedTextFile(
+ new File([pastedText], PASTED_TEXT_FILENAME, { type: "text/plain" }),
+ pastedText,
+ ),
+ );
+ unmount();
+
+ await act(async () => {
+ pending.fail();
+ });
+
+ // A dropped file survives a failed upload on disk; this text does not
+ // exist anywhere else, so the draft must get it back rather than keep a
+ // failed chip standing in for content the user can never recover.
+ const draft = useCommentDraftStore.getState().getDraft("new:issue-1");
+ expect(draft).toContain("wip text");
+ expect(draft).toContain(pastedText);
+ expect(useCommentDraftStore.getState().getUploads("new:issue-1")).toHaveLength(0);
+ });
+
it("hands the finished upload's link to a REOPENED composer's live editor", async () => {
const first = renderCommentInput();
activateComposer("comment-composer-shell");
diff --git a/packages/views/issues/components/comment-input.tsx b/packages/views/issues/components/comment-input.tsx
index 6699ac30bc..1790782454 100644
--- a/packages/views/issues/components/comment-input.tsx
+++ b/packages/views/issues/components/comment-input.tsx
@@ -3,6 +3,7 @@
import { useRef, useState, useCallback, useEffect } from "react";
import { cn } from "@multica/ui/lib/utils";
import { ContentEditor, type ContentEditorRef, useFileDropZone, FileDropOverlay, useLazyEditor, useUploadGate, useComposerSubmit } from "../../editor";
+import { PASTE_AS_FILE_THRESHOLD } from "../../editor/paste-as-file";
import { FileUploadButton } from "@multica/ui/components/common/file-upload-button";
import { SubmitButton } from "@multica/ui/components/common/submit-button";
import { contentReferencesAttachment } from "@multica/core/types";
@@ -220,6 +221,7 @@ function CommentInput({ issueId, onSubmit }: CommentInputProps) {
}}
onSubmit={submit}
onUploadFile={handleUpload}
+ pasteAsFileThreshold={PASTE_AS_FILE_THRESHOLD}
onUploadingChange={uploadGate.onUploadingChange}
debounceMs={100}
currentIssueId={issueId}
diff --git a/packages/views/issues/components/reply-input.tsx b/packages/views/issues/components/reply-input.tsx
index 7733645a36..fb2479a61d 100644
--- a/packages/views/issues/components/reply-input.tsx
+++ b/packages/views/issues/components/reply-input.tsx
@@ -2,6 +2,7 @@
import { useRef, useState, useCallback, useEffect } from "react";
import { ContentEditor, type ContentEditorRef, useFileDropZone, FileDropOverlay, useLazyEditor, useUploadGate, useComposerSubmit } from "../../editor";
+import { PASTE_AS_FILE_THRESHOLD } from "../../editor/paste-as-file";
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";
@@ -241,6 +242,7 @@ function ReplyInput({
}}
onSubmit={submit}
onUploadFile={handleUpload}
+ pasteAsFileThreshold={PASTE_AS_FILE_THRESHOLD}
onUploadingChange={uploadGate.onUploadingChange}
debounceMs={100}
currentIssueId={issueId}