Skip to content

armgit / kaneo

Public Imported from GitHub
0

⚡ Project management that doesn't become the project. Boards, Gantt charts, and GitHub integration. Self-host it or use Kaneo Cloud.

fix(web): preserve image uploads across editor recreation (#1738)

Adam Boulila07d36e237349
diff --git a/apps/web/src/components/activity/comment-editor-image-upload.test.tsx b/apps/web/src/components/activity/comment-editor-image-upload.test.tsx
new file mode 100644
index 000000000..fc487c966
--- /dev/null
+++ b/apps/web/src/components/activity/comment-editor-image-upload.test.tsx
@@ -0,0 +1,283 @@
+import { act, fireEvent, render, waitFor } from "@testing-library/react";
+import { Extension } from "@tiptap/core";
+import TaskItem from "@tiptap/extension-task-item";
+import { EditorView } from "@tiptap/pm/view";
+import type { Editor } from "@tiptap/react";
+import { beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
+import { toast } from "@/lib/toast";
+import { uploadTaskImage } from "@/lib/upload-task-image";
+import CommentEditor from "./comment-editor";
+
+const mocks = vi.hoisted(() => ({
+ t: (key: string) => key,
+ editors: [] as unknown[],
+}));
+
+vi.mock("@tiptap/react", async (importOriginal) => {
+ const actual = await importOriginal<typeof import("@tiptap/react")>();
+ return {
+ ...actual,
+ useEditor: (...args: Parameters<typeof actual.useEditor>) => {
+ const editor = actual.useEditor(...args);
+ if (editor && !mocks.editors.includes(editor)) mocks.editors.push(editor);
+ return editor;
+ },
+ };
+});
+
+function inert(name: string) {
+ return Extension.create({ name });
+}
+
+vi.mock("@/components/task/extensions/shiki-code-block", () => ({
+ ShikiCodeBlock: inert("shikiCodeBlockStub"),
+}));
+vi.mock("@/components/task/extensions/mermaid-block", () => ({
+ MermaidBlock: inert("mermaidBlockStub"),
+}));
+vi.mock("@/components/task/extensions/embed-block", () => ({
+ EmbedBlock: inert("embedBlockStub"),
+}));
+vi.mock("@/components/task/extensions/attachment-card", () => ({
+ AttachmentCard: inert("attachmentCardStub"),
+}));
+vi.mock("@/components/task/extensions/kaneo-issue-link", () => ({
+ KaneoIssueLink: inert("kaneoIssueLinkStub"),
+}));
+vi.mock("@/components/task/extensions/kaneo-mention", () => ({
+ KaneoMention: inert("kaneoMentionStub"),
+}));
+vi.mock("@/components/task/extensions/mention-suggestion", () => ({
+ MentionSuggestion: inert("mentionSuggestionStub"),
+}));
+vi.mock("@/components/task/extensions/task-item-with-checkbox", () => ({
+ TaskItemWithCheckbox: TaskItem,
+}));
+
+vi.mock("react-i18next", () => ({
+ useTranslation: () => ({ t: mocks.t }),
+ initReactI18next: { type: "3rdParty", init: () => {} },
+}));
+vi.mock("@/hooks/queries/workspace/use-active-workspace", () => ({
+ default: () => ({ data: undefined }),
+}));
+vi.mock(
+ "@/hooks/queries/workspace-users/use-get-active-workspace-users",
+ () => ({
+ useGetActiveWorkspaceUsers: () => ({ data: undefined }),
+ }),
+);
+vi.mock("@/lib/toast", () => ({
+ toast: {
+ error: vi.fn(),
+ success: vi.fn(),
+ loading: vi.fn(),
+ dismiss: vi.fn(),
+ },
+}));
+vi.mock("@/lib/upload-task-image", () => ({ uploadTaskImage: vi.fn() }));
+vi.mock("@/lib/shiki-highlighter", () => ({
+ getSharedShikiHighlighter: () => new Promise(() => {}),
+}));
+
+const uploadMock = vi.mocked(uploadTaskImage);
+const toastError = vi.mocked(toast.error);
+
+const asset = {
+ url: "/api/asset/asset-9",
+ alt: "paste",
+ filename: "paste.png",
+ kind: "image" as const,
+ mimeType: "image/png",
+ size: 18,
+};
+
+function latestEditor() {
+ return mocks.editors[mocks.editors.length - 1] as Editor;
+}
+
+function pasteFile(editor: Editor) {
+ const file = new File(["fake-image-bytes"], "paste.png", {
+ type: "image/png",
+ });
+ fireEvent.paste(editor.view.dom, {
+ clipboardData: { files: [file], getData: () => "" },
+ });
+}
+
+function deferredUpload() {
+ let resolveUpload!: (value: typeof asset) => void;
+ uploadMock.mockImplementation(
+ () =>
+ new Promise<typeof asset>((resolve) => {
+ resolveUpload = resolve;
+ }),
+ );
+ return () => resolveUpload(asset);
+}
+
+// jsdom has no layout, so ProseMirror cannot compute coordinates when a
+// command scrolls the selection into view. Browsers are unaffected.
+beforeAll(() => {
+ vi.spyOn(EditorView.prototype, "coordsAtPos").mockReturnValue({
+ left: 0,
+ right: 0,
+ top: 0,
+ bottom: 0,
+ });
+});
+
+beforeEach(() => {
+ mocks.editors.length = 0;
+ vi.mocked(toast.error).mockClear();
+ vi.mocked(toast.success).mockClear();
+ vi.mocked(toast.dismiss).mockClear();
+ uploadMock.mockReset();
+});
+
+describe("CommentEditor image upload insertion", () => {
+ it("inserts into the current editor when it is recreated mid-upload", async () => {
+ const resolveUpload = deferredUpload();
+ const onChange = vi.fn();
+
+ const editorProps = {
+ value: "",
+ onChange,
+ taskId: "task-1",
+ placeholder: "first",
+ };
+ const { rerender } = render(<CommentEditor {...editorProps} />);
+ await waitFor(() => expect(latestEditor()).toBeDefined());
+
+ const firstEditor = latestEditor();
+ pasteFile(firstEditor);
+ await act(async () => {});
+ expect(uploadMock).toHaveBeenCalledTimes(1);
+
+ // Simulate the editor being recreated while the upload is in flight: a
+ // changed placeholder flows into the useEditor dependencies.
+ rerender(<CommentEditor {...editorProps} placeholder="second" />);
+ const currentEditor = latestEditor();
+ expect(currentEditor).not.toBe(firstEditor);
+ expect(firstEditor.isDestroyed).toBe(true);
+
+ await act(async () => {
+ resolveUpload();
+ });
+
+ expect(currentEditor.getHTML()).toContain("/api/asset/asset-9");
+ expect(onChange).toHaveBeenCalledWith(
+ expect.stringContaining("/api/asset/asset-9"),
+ );
+ });
+
+ it("does not insert into a replacement editor for another task", async () => {
+ const resolveUpload = deferredUpload();
+ const props = {
+ value: "",
+ onChange: () => {},
+ taskId: "task-1",
+ placeholder: "first",
+ };
+ const { rerender } = render(<CommentEditor {...props} />);
+ await waitFor(() => expect(latestEditor()).toBeDefined());
+
+ const firstEditor = latestEditor();
+ pasteFile(firstEditor);
+ await act(async () => {});
+
+ rerender(<CommentEditor {...props} taskId="task-2" placeholder="second" />);
+ const currentEditor = latestEditor();
+ expect(currentEditor).not.toBe(firstEditor);
+
+ await act(async () => resolveUpload());
+
+ expect(currentEditor.getHTML()).not.toContain("/api/asset/asset-9");
+ expect(toastError).not.toHaveBeenCalled();
+ expect(toast.success).not.toHaveBeenCalled();
+ });
+
+ it("does not insert an ensured draft upload into another task", async () => {
+ const resolveUpload = deferredUpload();
+ const props = {
+ value: "",
+ onChange: () => {},
+ ensureTaskId: () => Promise.resolve("task-1"),
+ placeholder: "first",
+ };
+ const { rerender } = render(<CommentEditor {...props} />);
+ await waitFor(() => expect(latestEditor()).toBeDefined());
+
+ const firstEditor = latestEditor();
+ pasteFile(firstEditor);
+ await waitFor(() => expect(uploadMock).toHaveBeenCalled());
+
+ rerender(<CommentEditor {...props} taskId="task-2" placeholder="second" />);
+ const currentEditor = latestEditor();
+ expect(currentEditor).not.toBe(firstEditor);
+
+ await act(async () => resolveUpload());
+
+ expect(currentEditor.getHTML()).not.toContain("/api/asset/asset-9");
+ expect(toastError).not.toHaveBeenCalled();
+ expect(toast.success).not.toHaveBeenCalled();
+ });
+
+ it("reports an error when no live editor remains on the active task", async () => {
+ const resolveUpload = deferredUpload();
+ render(<CommentEditor value="" onChange={() => {}} taskId="task-1" />);
+ await waitFor(() => expect(latestEditor()).toBeDefined());
+
+ const editor = latestEditor();
+ pasteFile(editor);
+ await waitFor(() => expect(uploadMock).toHaveBeenCalledOnce());
+ // The upload finishes before a replacement editor is available.
+ act(() => editor.destroy());
+ await act(async () => resolveUpload());
+
+ expect(toastError).toHaveBeenCalledWith(
+ "activity:comment.editor.failedToUploadFile",
+ );
+ expect(toast.dismiss).toHaveBeenCalled();
+ expect(toast.success).not.toHaveBeenCalled();
+ });
+
+ it("quietly cancels an upload after the editor surface unmounts", async () => {
+ const resolveUpload = deferredUpload();
+ const onChange = vi.fn();
+ const { unmount } = render(
+ <CommentEditor value="" onChange={onChange} taskId="task-1" />,
+ );
+ await waitFor(() => expect(latestEditor()).toBeDefined());
+ pasteFile(latestEditor());
+ await waitFor(() => expect(uploadMock).toHaveBeenCalledOnce());
+ onChange.mockClear();
+
+ unmount();
+ await act(async () => resolveUpload());
+
+ expect(toast.dismiss).toHaveBeenCalled();
+ expect(toastError).not.toHaveBeenCalled();
+ expect(toast.success).not.toHaveBeenCalled();
+ expect(onChange).not.toHaveBeenCalled();
+ });
+
+ it("reports an error when the insert command does not execute", async () => {
+ const resolveUpload = deferredUpload();
+ render(<CommentEditor value="" onChange={() => {}} taskId="task-1" />);
+ await waitFor(() => expect(latestEditor()).toBeDefined());
+
+ const editor = latestEditor();
+ const chain = editor.chain();
+ vi.spyOn(chain, "run").mockReturnValue(false);
+ vi.spyOn(editor, "chain").mockReturnValue(chain);
+
+ pasteFile(editor);
+ await act(async () => {});
+ await act(async () => resolveUpload());
+
+ expect(toastError).toHaveBeenCalledWith(
+ "activity:comment.editor.failedToUploadFile",
+ );
+ });
+});
diff --git a/apps/web/src/components/activity/comment-editor.tsx b/apps/web/src/components/activity/comment-editor.tsx
index 06b5a4c11..c2792b226 100644
--- a/apps/web/src/components/activity/comment-editor.tsx
+++ b/apps/web/src/components/activity/comment-editor.tsx
@@ -204,6 +204,13 @@ export default function CommentEditor({
const hasHydratedRef = useRef(false);
const latestValueRef = useRef(normalizeCommentMarkdown(value || ""));
const lastEditorRef = useRef<Editor | null>(null);
+ const isMountedRef = useRef(false);
+ useEffect(() => {
+ isMountedRef.current = true;
+ return () => {
+ isMountedRef.current = false;
+ };
+ }, []);
const taskIdRef = useRef(taskId);
const ensureTaskIdRef = useRef(ensureTaskId);
const uploadSurfaceRef = useRef(uploadSurface);
@@ -301,16 +308,21 @@ export default function CommentEditor({
}
if (asset.kind === "image") {
- chain
+ const ran = chain
.setImage({
src: asset.url,
alt: asset.alt,
})
.run();
+ // Chain commands report silent failure via false rather than
+ // throwing; convert it so the caller's catch reports it.
+ if (!ran) {
+ throw new Error(t("activity:comment.editor.failedToUploadFile"));
+ }
return;
}
- chain
+ const ran = chain
.insertContent({
type: "attachmentCard",
attrs: {
@@ -321,15 +333,19 @@ export default function CommentEditor({
},
})
.run();
+ if (!ran) {
+ throw new Error(t("activity:comment.editor.failedToUploadFile"));
+ }
},
- [],
+ [t],
);
const handleAssetFileUpload = useCallback(
async (file: File, targetEditor?: Editor | null, range?: SlashRange) => {
const activeEditor = targetEditor || lastEditorRef.current;
+ const initialTaskId = taskIdRef.current;
const resolvedTaskId =
- taskIdRef.current ?? (await ensureTaskIdRef.current?.());
+ initialTaskId ?? (await ensureTaskIdRef.current?.());
if (!activeEditor || !resolvedTaskId) {
toast.error(t("activity:comment.editor.uploadsOnlyOnSavedTasks"));
@@ -346,7 +362,28 @@ export default function CommentEditor({
surface: uploadSurfaceRef.current,
file,
});
- insertUploadedAsset(activeEditor, uploadedAsset, range);
+
+ // Reuse a replacement editor only while it still belongs to the task
+ // that owns the uploaded asset.
+ const currentEditor = !activeEditor.isDestroyed
+ ? activeEditor
+ : lastEditorRef.current;
+ const taskChanged =
+ initialTaskId === undefined
+ ? taskIdRef.current !== undefined &&
+ taskIdRef.current !== resolvedTaskId
+ : taskIdRef.current !== initialTaskId;
+ if (!isMountedRef.current || taskChanged) {
+ toast.dismiss(loadingToast);
+ return;
+ }
+ if (!currentEditor || currentEditor.isDestroyed) {
+ throw new Error(t("activity:comment.editor.failedToUploadFile"));
+ }
+
+ // Only report success when the image actually landed in the document;
+ // insertUploadedAsset throws otherwise and the catch below reports it.
+ insertUploadedAsset(currentEditor, uploadedAsset, range);
toast.dismiss(loadingToast);
toast.success(
@@ -953,7 +990,10 @@ export default function CommentEditor({
}, [editor]);
useEffect(() => {
- if (!editor) return;
+ // The editor instance can be destroyed and replaced while effects are
+ // flushing (e.g. Shiki resolving recreates it via useEditor deps). The
+ // next run attaches to the replacement instance.
+ if (!editor || editor.isDestroyed) return;
const handleImagePreviewClick = (event: MouseEvent) => {
const target = event.target as HTMLElement | null;
diff --git a/apps/web/src/components/task/task-description-save.test.tsx b/apps/web/src/components/task/task-description-save.test.tsx
index f04d5aea8..a883a31a9 100644
--- a/apps/web/src/components/task/task-description-save.test.tsx
+++ b/apps/web/src/components/task/task-description-save.test.tsx
@@ -1,8 +1,19 @@
-import { act, render, waitFor } from "@testing-library/react";
+import { act, fireEvent, render, waitFor } from "@testing-library/react";
import { Extension } from "@tiptap/core";
import TaskItem from "@tiptap/extension-task-item";
+import { EditorView } from "@tiptap/pm/view";
import type { Editor } from "@tiptap/react";
-import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import {
+ afterEach,
+ beforeAll,
+ beforeEach,
+ describe,
+ expect,
+ it,
+ vi,
+} from "vitest";
+import { toast } from "@/lib/toast";
+import { uploadTaskImage } from "@/lib/upload-task-image";
import TaskDescription from "./task-description";
const mocks = vi.hoisted(() => ({
@@ -77,6 +88,15 @@ vi.mock("@/lib/shiki-highlighter", () => ({
}));
const DEBOUNCE_MS = 700;
+const uploadMock = vi.mocked(uploadTaskImage);
+const asset = {
+ url: "/api/asset/asset-1",
+ alt: "paste",
+ filename: "paste.png",
+ kind: "image" as const,
+ mimeType: "image/png",
+ size: 18,
+};
function latestEditor() {
return mocks.editors[mocks.editors.length - 1] as Editor;
@@ -98,10 +118,44 @@ function savedTaskIds() {
return mocks.mutateAsync.mock.calls.map((call) => call[0].id);
}
+function pasteFile(editor: Editor) {
+ fireEvent.paste(editor.view.dom, {
+ clipboardData: {
+ files: [new File(["image"], "paste.png", { type: "image/png" })],
+ getData: () => "",
+ },
+ });
+}
+
+function deferredUpload() {
+ let resolveUpload!: (value: typeof asset) => void;
+ uploadMock.mockImplementation(
+ () =>
+ new Promise<typeof asset>((resolve) => {
+ resolveUpload = resolve;
+ }),
+ );
+ return () => resolveUpload(asset);
+}
+
+beforeAll(() => {
+ vi.spyOn(EditorView.prototype, "coordsAtPos").mockReturnValue({
+ left: 0,
+ right: 0,
+ top: 0,
+ bottom: 0,
+ });
+});
+
beforeEach(() => {
mocks.mutateAsync.mockReset();
mocks.mutateAsync.mockResolvedValue({});
mocks.editors.length = 0;
+ mocks.t = (key: string) => key;
+ uploadMock.mockReset();
+ vi.mocked(toast.error).mockClear();
+ vi.mocked(toast.success).mockClear();
+ vi.mocked(toast.dismiss).mockClear();
mocks.tasks.set("task-a", {
id: "task-a",
projectId: "project-1",
@@ -119,6 +173,95 @@ afterEach(() => {
});
describe("TaskDescription pending saves", () => {
+ it("inserts an uploaded image into a replacement editor and saves it", async () => {
+ const resolveUpload = deferredUpload();
+ const { container, rerender } = render(<TaskDescription taskId="task-a" />);
+ await waitFor(() => expect(container.textContent).toContain("alpha"));
+ await settle();
+
+ const firstEditor = latestEditor();
+ pasteFile(firstEditor);
+ await act(async () => {});
+ expect(uploadMock).toHaveBeenCalledTimes(1);
+
+ mocks.t = (key: string) => key;
+ rerender(<TaskDescription taskId="task-a" />);
+ const currentEditor = latestEditor();
+ expect(currentEditor).not.toBe(firstEditor);
+ expect(firstEditor.isDestroyed).toBe(true);
+ await settle();
+
+ await act(async () => resolveUpload());
+
+ expect(currentEditor.getHTML()).toContain(asset.url);
+ await vi.waitFor(
+ () =>
+ expect(
+ mocks.mutateAsync.mock.calls.some(([saved]) =>
+ saved.description.includes(asset.url),
+ ),
+ ).toBe(true),
+ { timeout: DEBOUNCE_MS * 4 },
+ );
+ });
+
+ it("reports an error when no live editor remains on the active task", async () => {
+ const resolveUpload = deferredUpload();
+ const { container } = render(<TaskDescription taskId="task-a" />);
+ await waitFor(() => expect(container.textContent).toContain("alpha"));
+ await settle();
+
+ const editor = latestEditor();
+ pasteFile(editor);
+ await waitFor(() => expect(uploadMock).toHaveBeenCalledOnce());
+ act(() => editor.destroy());
+ await act(async () => resolveUpload());
+
+ expect(toast.error).toHaveBeenCalledWith(
+ "tasks:detail.editor.upload.failed",
+ );
+ expect(toast.dismiss).toHaveBeenCalled();
+ expect(toast.success).not.toHaveBeenCalled();
+ expect(mocks.mutateAsync).not.toHaveBeenCalled();
+ });
+
+ it("quietly cancels an upload after the description unmounts", async () => {
+ const resolveUpload = deferredUpload();
+ const { container, unmount } = render(<TaskDescription taskId="task-a" />);
+ await waitFor(() => expect(container.textContent).toContain("alpha"));
+ await settle();
+ pasteFile(latestEditor());
+ await waitFor(() => expect(uploadMock).toHaveBeenCalledOnce());
+
+ unmount();
+ await act(async () => resolveUpload());
+
+ expect(toast.dismiss).toHaveBeenCalled();
+ expect(toast.error).not.toHaveBeenCalled();
+ expect(toast.success).not.toHaveBeenCalled();
+ expect(mocks.mutateAsync).not.toHaveBeenCalled();
+ });
+
+ it("quietly cancels an upload after navigating to another task", async () => {
+ const resolveUpload = deferredUpload();
+ const { container, rerender } = render(<TaskDescription taskId="task-a" />);
+ await waitFor(() => expect(container.textContent).toContain("alpha"));
+ await settle();
+ pasteFile(latestEditor());
+ await waitFor(() => expect(uploadMock).toHaveBeenCalledOnce());
+
+ rerender(<TaskDescription taskId="task-b" />);
+ await waitFor(() => expect(container.textContent).toContain("bravo"));
+ await settle();
+ await act(async () => resolveUpload());
+
+ expect(latestEditor().getHTML()).not.toContain(asset.url);
+ expect(toast.dismiss).toHaveBeenCalled();
+ expect(toast.error).not.toHaveBeenCalled();
+ expect(toast.success).not.toHaveBeenCalled();
+ expect(mocks.mutateAsync).not.toHaveBeenCalled();
+ });
+
it("saves an edit to the task it was typed in, not the one navigated to", async () => {
const { container, rerender } = render(<TaskDescription taskId="task-a" />);
await waitFor(() => expect(container.textContent).toContain("alpha"));
diff --git a/apps/web/src/components/task/task-description.tsx b/apps/web/src/components/task/task-description.tsx
index a34fb2bef..b4dc2f49f 100644
--- a/apps/web/src/components/task/task-description.tsx
+++ b/apps/web/src/components/task/task-description.tsx
@@ -312,6 +312,13 @@ export default function TaskDescription({ taskId }: TaskDescriptionProps) {
const updateTaskRef = useRef(updateTaskDescription);
const activeTaskIdRef = useRef<string | null>(null);
const lastEditorRef = useRef<Editor | null>(null);
+ const isMountedRef = useRef(false);
+ useEffect(() => {
+ isMountedRef.current = true;
+ return () => {
+ isMountedRef.current = false;
+ };
+ }, []);
const pendingImageInsertRef = useRef<{
editor: Editor;
range?: SlashRange;
@@ -402,16 +409,21 @@ export default function TaskDescription({ taskId }: TaskDescriptionProps) {
}
if (asset.kind === "image") {
- chain
+ const ran = chain
.setImage({
src: asset.url,
alt: asset.alt,
})
.run();
+ // Chain commands report silent failure via false rather than
+ // throwing; convert it so the caller's catch reports it.
+ if (!ran) {
+ throw new Error(t("tasks:detail.editor.upload.failed"));
+ }
return;
}
- chain
+ const ran = chain
.insertContent({
type: "attachmentCard",
attrs: {
@@ -422,8 +434,11 @@ export default function TaskDescription({ taskId }: TaskDescriptionProps) {
},
})
.run();
+ if (!ran) {
+ throw new Error(t("tasks:detail.editor.upload.failed"));
+ }
},
- [],
+ [t],
);
const handleAssetFileUpload = useCallback(
@@ -448,12 +463,22 @@ export default function TaskDescription({ taskId }: TaskDescriptionProps) {
file,
});
- if (activeEditor.isDestroyed || taskIdRef.current !== uploadTaskId) {
+ // The captured editor can be destroyed and replaced while the upload
+ // is in flight; fall back to the current instance for the same task.
+ const currentEditor = !activeEditor.isDestroyed
+ ? activeEditor
+ : lastEditorRef.current;
+ if (!isMountedRef.current || taskIdRef.current !== uploadTaskId) {
toast.dismiss(loadingToast);
return;
}
+ if (!currentEditor || currentEditor.isDestroyed) {
+ throw new Error(t("tasks:detail.editor.upload.failed"));
+ }
- insertUploadedAsset(activeEditor, uploadedAsset, range);
+ // insertUploadedAsset throws on failure and the catch below reports
+ // it, so reaching the toast means the image is in the document.
+ insertUploadedAsset(currentEditor, uploadedAsset, range);
toast.dismiss(loadingToast);
toast.success(
@@ -874,7 +899,10 @@ export default function TaskDescription({ taskId }: TaskDescriptionProps) {
}, [editor]);
useEffect(() => {
- if (!editor) return;
+ // The editor instance can be destroyed and replaced while effects are
+ // flushing (e.g. a language change recreates it via useEditor deps). The
+ // next run attaches to the replacement instance.
+ if (!editor || editor.isDestroyed) return;
const handleImagePreviewClick = (event: MouseEvent) => {
const target = event.target as HTMLElement | null;