Build your personal knowledge base with Trilium Notes
TypeScript electronelectron-appknowledge-baseknowledge-graphknowledge-managementknowledge-management-graphlocal-firstnote-managmentnote-takernote-takingnotebooknotesnotes-apppersonal-knowledge-basepersonal-wikiscriptableself-hostedself-hostingwiki
fix(client): register import/export progress toasts eagerly so they survive a refresh
Elian Doran1d614c54fdd9
diff --git a/apps/client/src/components/main_tree_executors.ts b/apps/client/src/components/main_tree_executors.tsindex bfff930bbd..5c9c49d09c 100644--- a/apps/client/src/components/main_tree_executors.ts+++ b/apps/client/src/components/main_tree_executors.ts@@ -1,3 +1,9 @@+// Loaded for its side effect: this eagerly-instantiated executor owns the import/export commands, so+// importing the service here registers its task-progress toast subscriptions at startup. The import/export+// dialogs are lazy-loaded, so relying on them to register would mean an in-progress import/export toast+// never reappears after a page refresh.+import "../services/import.js";+import branchService from "../services/branches.js";import clipboard from "../services/clipboard.js";import froca from "../services/froca.js";diff --git a/apps/client/src/services/import.spec.ts b/apps/client/src/services/import.spec.tsindex e64182e624..ce76a443d1 100644--- a/apps/client/src/services/import.spec.ts+++ b/apps/client/src/services/import.spec.ts@@ -1,20 +1,28 @@+import type { WebSocketMessage } from "@triliumnext/commons";import { beforeAll, beforeEach, describe, expect, it, vi } from "vitest";-import type { WebSocketMessage } from "@triliumnext/commons";+// 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";-import ws from "./ws.js";--// Capture the message handlers that import.ts registers at module load. The-// global ws mock's subscribeToMessages is a no-op, so we replace it with a-// capturing variant BEFORE importing the module under test.-type MessageHandler = (message: WebSocketMessage) => void | Promise<void>;-const handlers: MessageHandler[] = [];-ws.subscribeToMessages = ((cb: MessageHandler) => {- handlers.push(cb);-}) as typeof ws.subscribeToMessages;let importService: typeof import("./import.js").default;let uploadFiles: typeof import("./import.js").uploadFiles;@@ -23,8 +31,9 @@ beforeAll(async () => {const mod = await import("./import.js");importService = mod.default;uploadFiles = mod.uploadFiles;- // Two handlers registered at load: importNotes + importAttachments.- expect(handlers.length).toBe(2);+ // 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.@@ -136,11 +145,11 @@ async function dispatch(message: any) {}describe("importNotes ws handler", () => {- const handler = () => handlers[0];+ const handler = () => dispatch;it("ignores messages without a matching taskType", async () => {await handler()({ type: "taskSucceeded" } as any); // no taskType- await handler()({ type: "taskSucceeded", taskType: "importAttachments" } as any); // wrong type+ await handler()({ type: "taskSucceeded", taskType: "unrelatedTask" } as any); // not addressed to any toast handlerexpect(toastService.showError).not.toHaveBeenCalled();expect(toastService.showPersistent).not.toHaveBeenCalled();});@@ -238,11 +247,11 @@ describe("importNotes ws handler", () => {});describe("importAttachments ws handler", () => {- const handler = () => handlers[1];+ const handler = () => dispatch;it("ignores messages without a matching taskType", async () => {await handler()({ type: "taskSucceeded" } as any); // no taskType- await handler()({ type: "taskSucceeded", taskType: "importNotes" } as any); // wrong type+ await handler()({ type: "taskSucceeded", taskType: "unrelatedTask" } as any); // not addressed to any toast handlerexpect(toastService.showError).not.toHaveBeenCalled();expect(toastService.showPersistent).not.toHaveBeenCalled();});@@ -316,6 +325,46 @@ describe("importAttachments ws handler", () => {});});+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);++ 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();+ });+});+describe("dispatch sanity", () => {it("delivers an unrelated message to both handlers without side effects", async () => {await dispatch({ type: "ping" });diff --git a/apps/client/src/services/import.ts b/apps/client/src/services/import.tsindex 60678fbb76..63eccfd834 100644--- a/apps/client/src/services/import.ts+++ b/apps/client/src/services/import.ts@@ -1,10 +1,11 @@-import toastService, { type ToastOptionsWithRequiredId } from "./toast.js";-import server from "./server.js";-import ws from "./ws.js";-import utils from "./utils.js";+import { ProgressPhase, WebSocketMessage } from "@triliumnext/commons";+import appContext from "../components/app_context.js";import { t } from "./i18n.js";-import { ProgressPhase, WebSocketMessage } from "@triliumnext/commons";+import server from "./server.js";+import toastService, { type ToastOptionsWithRequiredId } from "./toast.js";+import utils from "./utils.js";+import ws from "./ws.js";type BooleanLike = boolean | "true" | "false";@@ -51,7 +52,7 @@ export async function uploadFiles(entityType: string, parentNoteId: string, filedataType: "json",type: "POST",timeout: 60 * 60 * 1000,- error: function (xhr) {+ error (xhr) {// Fallback toast for failures that never produced a WebSocket `taskError` (e.g. transport or// auth errors raised before the importer runs). Deferred so the canonical WebSocket error —// emitted alongside this same 500 — can claim the taskId first and win.@@ -173,6 +174,57 @@ ws.subscribeToMessages(async (message: WebSocketMessage) => {}});+// The export progress toast subscription lives here too — in this eagerly-loaded service — rather than in+// the lazily-loaded export dialog (export.tsx). Registered at startup, it re-registers on every page load,+// so an in-progress export's toast resumes after a refresh; a subscription inside the dialog module would+// never re-register unless the dialog were reopened. Reuses this existing transfer service rather than+// adding a parallel export one.+ws.subscribeToMessages(async (message: WebSocketMessage) => {+ if (!("taskType" in message) || message.taskType !== "export") {+ return;+ }++ if (message.type === "taskError") {+ toastService.closePersistent(message.taskId);+ toastService.showError(message.message);+ } else if (message.type === "taskProgressCount") {+ toastService.showPersistent(makeExportProgressToast(message.taskId, message.progressCount, message.totalCount));+ } else if (message.type === "taskSucceeded") {+ const toast = makeExportToast(message.taskId, t("export.export_finished_successfully"));+ toast.timeout = 5000;++ toastService.showPersistent(toast);+ }+});++function makeExportToast(id: string, message: string): ToastOptionsWithRequiredId {+ return {+ id,+ message,+ icon: "export",+ // This toast replaces the in-progress one (same id), and showPersistent merges fields rather than+ // swapping the object — so clear the progress explicitly, otherwise the finished bar lingers at 100%.+ progress: undefined+ };+}++/**+ * Builds the persistent "export in progress" toast. The metadata-collection phase doesn't know the total+ * up front, so it shows an indeterminate "Preparing for export…" message; once the content-writing phase+ * sets a total, the message switches to "Exported X notes out of N" with a progress bar.+ */+function makeExportProgressToast(taskId: string, progressCount: number, totalCount?: number): ToastOptionsWithRequiredId {+ const hasTotal = typeof totalCount === "number" && totalCount > 0;+ return {+ id: taskId,+ icon: "bx bx-loader-circle bx-spin",+ message: hasTotal+ ? t("export.export_in_progress_with_total", { progressCount, totalCount })+ : t("export.preparing_export"),+ ...(hasTotal ? { progress: progressCount / totalCount } : {})+ };+}+export default {uploadFiles};diff --git a/apps/client/src/widgets/dialogs/export.tsx b/apps/client/src/widgets/dialogs/export.tsxindex 5ff4c7ec8f..a142ab9f2b 100644--- a/apps/client/src/widgets/dialogs/export.tsx+++ b/apps/client/src/widgets/dialogs/export.tsx@@ -5,10 +5,8 @@ import { useState } from "preact/hooks";import froca from "../../services/froca";import { t } from "../../services/i18n";import open from "../../services/open";-import toastService, { type ToastOptionsWithRequiredId } from "../../services/toast";import tree from "../../services/tree";import utils, { isStandalone } from "../../services/utils";-import ws from "../../services/ws";import { ExtendedAdmonition } from "../react/Admonition";import { Badge } from "../react/Badge";import Button, { ButtonGroup } from "../react/Button";@@ -151,50 +149,3 @@ async function exportBranch(branchId: string, type: string, format: string, titlconst url = open.getUrlForDownload(`api/branches/${branchId}/export/${type}/${format}/${taskId}`);open.download(url);}--ws.subscribeToMessages(async (message) => {- function makeToast(id: string, message: string): ToastOptionsWithRequiredId {- return {- id,- message,- icon: "export",- // This toast replaces the in-progress one (same id), and showPersistent merges fields rather- // than swapping the object — so clear the progress explicitly, otherwise the finished bar- // lingers at 100%.- progress: undefined- };- }-- if (!("taskType" in message) || message.taskType !== "export") {- return;- }-- if (message.type === "taskError") {- toastService.closePersistent(message.taskId);- toastService.showError(message.message);- } else if (message.type === "taskProgressCount") {- toastService.showPersistent(makeProgressToast(message.taskId, message.progressCount, message.totalCount));- } else if (message.type === "taskSucceeded") {- const toast = makeToast(message.taskId, t("export.export_finished_successfully"));- toast.timeout = 5000;-- toastService.showPersistent(toast);- }-});--/**- * Builds the persistent "export in progress" toast. The metadata-collection phase doesn't know the total- * up front, so it shows an indeterminate "Preparing for export…" message; once the content-writing phase- * sets a total, the message switches to "Exporting X of N" with a progress bar.- */-function makeProgressToast(taskId: string, progressCount: number, totalCount?: number): ToastOptionsWithRequiredId {- const hasTotal = typeof totalCount === "number" && totalCount > 0;- return {- id: taskId,- icon: "bx bx-loader-circle bx-spin",- message: hasTotal- ? t("export.export_in_progress_with_total", { progressCount, totalCount })- : t("export.preparing_export"),- ...(hasTotal ? { progress: progressCount / totalCount } : {})- };-}