Skip to content

Build your personal knowledge base with Trilium Notes

19.0 KB
Raw Blame
import type { WebSocketMessage } from "@triliumnext/commons";
import { beforeAll, beforeEach, describe, expect, it, vi } from "vitest";

// import.ts registers its task-progress ws.subscribeToMessages handlers at module load, and it is now loaded
// eagerly (pulled into app_context's graph via main_tree_executors) so its toasts survive a page refresh.
// That means it evaluates the moment this spec imports app_context — before any in-body override could run —
// so we mock ws.js here (hoisted above all imports) to CAPTURE handlers as they register. The captured list
// also holds handlers from other eagerly-loaded services, so tests dispatch to ALL of them and rely on each
// handler self-filtering by taskType, mirroring protected_session.spec.
type MessageHandler = (message: WebSocketMessage) => void | Promise<void>;
const { handlers } = vi.hoisted(() => ({ handlers: [] as MessageHandler[] }));

vi.mock("./ws.js", () => ({
    default: {
        subscribeToMessages(cb: MessageHandler) {
            handlers.push(cb);
        },
        waitForMaxKnownEntityChangeId: async () => {}
    }
}));

import appContext from "../components/app_context.js";
import * as i18n from "./i18n.js";
import server from "./server.js";
import toastService from "./toast.js";

let importService: typeof import("./import.js").default;
let uploadFiles: typeof import("./import.js").uploadFiles;

beforeAll(async () => {
    const mod = await import("./import.js");
    importService = mod.default;
    uploadFiles = mod.uploadFiles;
    // import.ts contributes three handlers (importNotes + importAttachments + export); the rest of the eager
    // graph adds more, so just assert ours were captured.
    expect(handlers.length).toBeGreaterThanOrEqual(3);
});

// Toast service spies.
toastService.showError = vi.fn();
toastService.showPersistent = vi.fn();
toastService.closePersistent = vi.fn();

// A fake active note context whose setNote we can assert against.
const setNote = vi.fn(async () => {});
const getActiveContext = vi.fn(() => ({ setNote }) as any);
(appContext as any).tabManager = { getActiveContext };

beforeEach(() => {
    vi.clearAllMocks();
    getActiveContext.mockReturnValue({ setNote } as any);
});

describe("uploadFiles", () => {
    const fileA = new File([ "a" ], "a.md");
    const fileB = new File([ "b" ], "b.md");
    let uploadForm: ReturnType<typeof vi.fn>;

    beforeEach(() => {
        uploadForm = vi.fn(async () => ({}));
        server.uploadForm = uploadForm as typeof server.uploadForm;
        server.getHeaders = vi.fn(async () => ({ "x-h": "1" })) as typeof server.getHeaders;
    });

    it("throws on an unrecognized entity type", async () => {
        await expect(uploadFiles("bogus", "p1", [ fileA ], { shrinkImages: false })).rejects.toThrow(
            "Unrecognized import entity type 'bogus'."
        );
        expect(uploadForm).not.toHaveBeenCalled();
    });

    it("returns early without uploading when there are no files", async () => {
        const result = await uploadFiles("notes", "p1", [], { shrinkImages: false });
        expect(result).toBeUndefined();
        expect(uploadForm).not.toHaveBeenCalled();
    });

    it("posts one form per file, flagging the last, and forwards options + headers", async () => {
        await uploadFiles("notes", "parent1", [ fileA, fileB ], {
            shrinkImages: true,
            safeImport: "true"
        });

        expect(uploadForm).toHaveBeenCalledTimes(2);

        const [ firstUrl, first ] = uploadForm.mock.calls[0];
        expect(firstUrl).toBe("notes/parent1/notes-import");
        expect(first).toMatchObject({ method: "POST", headers: { "x-h": "1" }, file: fileA, dataType: "json" });
        expect(first.fields).toMatchObject({ last: "false", shrinkImages: "true", safeImport: "true" });
        // taskId is shared across files in the same upload batch.
        expect(typeof first.fields.taskId).toBe("string");

        const [ , second ] = uploadForm.mock.calls[1];
        expect(second.file).toBe(fileB);
        expect(second.fields).toMatchObject({ last: "true", taskId: first.fields.taskId });
    });

    it("uses the attachments endpoint for the attachments entity type", async () => {
        await uploadFiles("attachments", "host1", [ fileA ], { shrinkImages: false });
        expect(uploadForm.mock.calls[0][0]).toBe("notes/host1/attachments-import");
    });

    it("surfaces an upload error through the toast service and rejects", async () => {
        // Spy on the i18n binding so we can verify responseText is forwarded
        // without depending on i18next interpolation (i18next is uninitialised in
        // the test env, so t() returns the key and never interpolates). We assert
        // the call args/structure rather than a human-readable translated string.
        const tSpy = vi.spyOn(i18n, "t");
        vi.useFakeTimers();
        try {
            const failure = { status: 500, responseText: "boom" };
            uploadForm.mockRejectedValue(failure);
            await expect(uploadFiles("notes", "p1", [ fileA, fileB ], { shrinkImages: false })).rejects.toBe(failure);
            // The first failure ends the batch.
            expect(uploadForm).toHaveBeenCalledTimes(1);
            // The error toast is deferred (so a WebSocket taskError can claim the taskId first and
            // win), so the fallback only fires after IMPORT_ERROR_FALLBACK_DELAY — flush it first.
            vi.runOnlyPendingTimers();
            expect(toastService.showError).toHaveBeenCalledTimes(1);
            // The responseText ("boom") must be forwarded into the message
            // interpolation, not dropped or replaced with the whole error object.
            expect(tSpy).toHaveBeenCalledWith("import.failed", { message: "boom" });
        } finally {
            tSpy.mockRestore();
            vi.useRealTimers();
        }
    });

    it("is also reachable through the default export", async () => {
        await importService.uploadFiles("notes", "p1", [ fileA ], { shrinkImages: false });
        expect(uploadForm).toHaveBeenCalledTimes(1);
    });
});

// Convenience: invoke both subscribed handlers with a message.
async function dispatch(message: any) {
    for (const handler of handlers) {
        await handler(message);
    }
}

describe("importNotes ws handler", () => {
    const handler = () => dispatch;

    it("ignores messages without a matching taskType", async () => {
        await handler()({ type: "taskSucceeded" } as any); // no taskType
        await handler()({ type: "taskSucceeded", taskType: "unrelatedTask" } as any); // not addressed to any toast handler
        expect(toastService.showError).not.toHaveBeenCalled();
        expect(toastService.showPersistent).not.toHaveBeenCalled();
    });

    it("closes the toast and shows an error on taskError", async () => {
        await handler()({ type: "taskError", taskType: "importNotes", taskId: "t1", message: "nope" } as any);
        expect(toastService.closePersistent).toHaveBeenCalledWith("t1");
        expect(toastService.showError).toHaveBeenCalledWith("nope");
    });

    it("shows the error only once when the same task reports it twice (the WebSocket + fallback dedup)", async () => {
        // A fresh taskId — the dedup guard is module-level state that survives clearAllMocks.
        await handler()({ type: "taskError", taskType: "importNotes", taskId: "dedupT", message: "boom" } as any);
        await handler()({ type: "taskError", taskType: "importNotes", taskId: "dedupT", message: "boom again" } as any);
        // The second report for the same taskId is suppressed, so only the first toast shows.
        expect(toastService.showError).toHaveBeenCalledTimes(1);
        expect(toastService.showError).toHaveBeenCalledWith("boom");
    });

    it("shows a persistent count-only progress toast when no total is reported", async () => {
        await handler()({ type: "taskProgressCount", taskType: "importNotes", taskId: "t2", progressCount: 3 } as any);
        expect(toastService.showPersistent).toHaveBeenCalledTimes(1);
        const toast = (toastService.showPersistent as any).mock.calls[0][0];
        expect(toast.id).toBe("t2");
        expect(toast.progress).toBeUndefined();
    });

    it("shows a progress-bar toast when a total is reported", async () => {
        await handler()({ type: "taskProgressCount", taskType: "importNotes", taskId: "t2", progressCount: 3, totalCount: 12 } as any);
        const toast = (toastService.showPersistent as any).mock.calls[0][0];
        expect(toast.progress).toBe(3 / 12);
        // The in-progress toast can't be dismissed — the import runs regardless, so a × would read as "cancel".
        expect(toast.dismissible).toBe(false);
    });

    it("uses phase-specific messages for the zip extraction and processing phases", async () => {
        const tSpy = vi.spyOn(i18n, "t").mockImplementation(((key: string) => key) as typeof i18n.t);

        await handler()({ type: "taskProgressCount", taskType: "importNotes", taskId: "t2", progressCount: 3, totalCount: 12, phase: "extracting" } as any);
        expect((toastService.showPersistent as any).mock.calls.at(-1)[0].message).toBe("import.extracting");

        await handler()({ type: "taskProgressCount", taskType: "importNotes", taskId: "t2", progressCount: 7, totalCount: 9, phase: "processing" } as any);
        expect((toastService.showPersistent as any).mock.calls.at(-1)[0].message).toBe("import.processing");

        tSpy.mockRestore();
    });

    it("shows the explicit throttled message while Graph rate-limits, with and without a total", async () => {
        const tSpy = vi.spyOn(i18n, "t").mockImplementation(((key: string) => key) as typeof i18n.t);

        // The count can legitimately sit still for a long time, so the throttled phase overrides the
        // usual count message — but the bar stays, since the counted progress is still real.
        await handler()({ type: "taskProgressCount", taskType: "importNotes", taskId: "t2", progressCount: 3, totalCount: 12, phase: "throttled" } as any);
        let toast = (toastService.showPersistent as any).mock.calls.at(-1)[0];
        expect(toast.message).toBe("import.throttled-with-total");
        expect(toast.progress).toBe(3 / 12);

        // Throttled before any total is known: no count to show, no bar.
        await handler()({ type: "taskProgressCount", taskType: "importNotes", taskId: "t2", progressCount: 0, phase: "throttled" } as any);
        toast = (toastService.showPersistent as any).mock.calls.at(-1)[0];
        expect(toast.message).toBe("import.throttled");
        expect(toast.progress).toBeUndefined();

        tSpy.mockRestore();
    });

    it("shows a generic 'starting' message (no bar) before anything is counted", async () => {
        const tSpy = vi.spyOn(i18n, "t").mockImplementation(((key: string) => key) as typeof i18n.t);
        await handler()({ type: "taskProgressCount", taskType: "importNotes", taskId: "t2", progressCount: 0 } as any);
        const toast = (toastService.showPersistent as any).mock.calls[0][0];
        expect(toast.progress).toBeUndefined();
        expect(toast.message).toBe("import.starting");
        tSpy.mockRestore();
    });

    it("shows a success toast and navigates to the imported note when one is returned", async () => {
        await handler()({
            type: "taskSucceeded",
            taskType: "importNotes",
            taskId: "t3",
            result: { importedNoteId: "imp1" }
        } as any);
        const toast = (toastService.showPersistent as any).mock.calls[0][0];
        expect(toast.timeout).toBe(5000);
        expect(setNote).toHaveBeenCalledWith("imp1");
        // The terminal toast re-enables dismissal, overriding the progress toast's value via the merge.
        expect(toast.dismissible).toBe(true);
    });

    it("shows a success toast but does not navigate when there is no imported note id", async () => {
        await handler()({
            type: "taskSucceeded",
            taskType: "importNotes",
            taskId: "t4",
            result: {}
        } as any);
        expect(toastService.showPersistent).toHaveBeenCalledTimes(1);
        expect(setNote).not.toHaveBeenCalled();
    });

    it("tolerates a missing active context on success navigation", async () => {
        getActiveContext.mockReturnValue(undefined as any);
        await handler()({
            type: "taskSucceeded",
            taskType: "importNotes",
            taskId: "t5",
            result: { importedNoteId: "imp2" }
        } as any);
        expect(setNote).not.toHaveBeenCalled();
    });

    it("does nothing for a matching task with an unhandled message type", async () => {
        await handler()({ type: "ping", taskType: "importNotes", taskId: "t6" } as any);
        expect(toastService.showError).not.toHaveBeenCalled();
        expect(toastService.showPersistent).not.toHaveBeenCalled();
        expect(toastService.closePersistent).not.toHaveBeenCalled();
    });
});

describe("importAttachments ws handler", () => {
    const handler = () => dispatch;

    it("ignores messages without a matching taskType", async () => {
        await handler()({ type: "taskSucceeded" } as any); // no taskType
        await handler()({ type: "taskSucceeded", taskType: "unrelatedTask" } as any); // not addressed to any toast handler
        expect(toastService.showError).not.toHaveBeenCalled();
        expect(toastService.showPersistent).not.toHaveBeenCalled();
    });

    it("closes the toast and shows an error on taskError", async () => {
        await handler()({ type: "taskError", taskType: "importAttachments", taskId: "a1", message: "bad" } as any);
        expect(toastService.closePersistent).toHaveBeenCalledWith("a1");
        expect(toastService.showError).toHaveBeenCalledWith("bad");
    });

    it("shows a persistent progress toast on taskProgressCount", async () => {
        await handler()({ type: "taskProgressCount", taskType: "importAttachments", taskId: "a2", progressCount: 1 } as any);
        expect(toastService.showPersistent).toHaveBeenCalledTimes(1);
        expect((toastService.showPersistent as any).mock.calls[0][0].id).toBe("a2");
    });

    it("navigates to the attachments view on success when a parent note id is present", async () => {
        await handler()({
            type: "taskSucceeded",
            taskType: "importAttachments",
            taskId: "a3",
            result: { parentNoteId: "par1", importedNoteId: "imp3" }
        } as any);
        const toast = (toastService.showPersistent as any).mock.calls[0][0];
        expect(toast.timeout).toBe(5000);
        expect(setNote).toHaveBeenCalledWith("imp3", { viewScope: { viewMode: "attachments" } });
    });

    it("shows a success toast but does not navigate when there is no parent note id", async () => {
        await handler()({
            type: "taskSucceeded",
            taskType: "importAttachments",
            taskId: "a4",
            result: {}
        } as any);
        expect(toastService.showPersistent).toHaveBeenCalledTimes(1);
        expect(setNote).not.toHaveBeenCalled();
    });

    it("navigates with an undefined note id when the parent gates but the imported note id is missing", async () => {
        // The source gates navigation on result.parentNoteId but passes
        // result.importedNoteId to setNote. With a parent present and no
        // imported id, setNote is still called with the (undefined) id.
        await handler()({
            type: "taskSucceeded",
            taskType: "importAttachments",
            taskId: "a4b",
            result: { parentNoteId: "par2" }
        } as any);
        expect(toastService.showPersistent).toHaveBeenCalledTimes(1);
        expect(setNote).toHaveBeenCalledTimes(1);
        expect(setNote).toHaveBeenCalledWith(undefined, { viewScope: { viewMode: "attachments" } });
    });

    it("tolerates a missing active context on success navigation", async () => {
        getActiveContext.mockReturnValue(undefined as any);
        await handler()({
            type: "taskSucceeded",
            taskType: "importAttachments",
            taskId: "a5",
            result: { parentNoteId: "par2", importedNoteId: "imp4" }
        } as any);
        expect(setNote).not.toHaveBeenCalled();
    });

    it("does nothing for a matching task with an unhandled message type", async () => {
        await handler()({ type: "ping", taskType: "importAttachments", taskId: "a6" } as any);
        expect(toastService.showError).not.toHaveBeenCalled();
        expect(toastService.showPersistent).not.toHaveBeenCalled();
        expect(toastService.closePersistent).not.toHaveBeenCalled();
    });
});

describe("export ws handler", () => {
    const handler = () => dispatch;

    it("ignores messages without a matching taskType", async () => {
        await handler()({ type: "taskSucceeded" } as any); // no taskType
        await handler()({ type: "taskSucceeded", taskType: "unrelatedTask" } as any); // not addressed to any toast handler
        expect(toastService.showPersistent).not.toHaveBeenCalled();
    });

    it("closes the toast and shows an error on taskError", async () => {
        await handler()({ type: "taskError", taskType: "export", taskId: "e1", message: "boom" } as any);
        expect(toastService.closePersistent).toHaveBeenCalledWith("e1");
        expect(toastService.showError).toHaveBeenCalledWith("boom");
    });

    it("shows an indeterminate toast (no bar) before a total is known, and a progress bar once it is", async () => {
        const tSpy = vi.spyOn(i18n, "t").mockImplementation(((key: string) => key) as typeof i18n.t);

        await handler()({ type: "taskProgressCount", taskType: "export", taskId: "e2", progressCount: 4 } as any);
        let toast = (toastService.showPersistent as any).mock.calls.at(-1)[0];
        expect(toast.message).toBe("export.preparing_export");
        expect(toast.progress).toBeUndefined();

        await handler()({ type: "taskProgressCount", taskType: "export", taskId: "e2", progressCount: 4, totalCount: 8 } as any);
        toast = (toastService.showPersistent as any).mock.calls.at(-1)[0];
        expect(toast.message).toBe("export.export_in_progress_with_total");
        expect(toast.progress).toBe(4 / 8);
        // The in-progress toast can't be dismissed — the export runs regardless of the toast.
        expect(toast.dismissible).toBe(false);

        tSpy.mockRestore();
    });

    it("shows a timed success toast that clears the progress bar on taskSucceeded", async () => {
        await handler()({ type: "taskSucceeded", taskType: "export", taskId: "e3", result: null } as any);
        const toast = (toastService.showPersistent as any).mock.calls.at(-1)[0];
        expect(toast.id).toBe("e3");
        expect(toast.timeout).toBe(5000);
        expect(toast.progress).toBeUndefined();
        // The terminal toast re-enables dismissal, overriding the progress toast's value via the merge.
        expect(toast.dismissible).toBe(true);
    });
});

describe("dispatch sanity", () => {
    it("delivers an unrelated message to both handlers without side effects", async () => {
        await dispatch({ type: "ping" });
        expect(toastService.showError).not.toHaveBeenCalled();
    });
});