Skip to content

Build your personal knowledge base with Trilium Notes

feat(import): split zip import progress into extraction and processing phases

Elian Doran223c3c948400
diff --git a/apps/client/src/services/import.spec.ts b/apps/client/src/services/import.spec.ts
index c0453d7395..e64182e624 100644
--- a/apps/client/src/services/import.spec.ts
+++ b/apps/client/src/services/import.spec.ts
@@ -174,6 +174,18 @@ describe("importNotes ws handler", () => {
expect(toast.progress).toBe(3 / 12);
});
+ 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 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);
diff --git a/apps/client/src/services/import.ts b/apps/client/src/services/import.ts
index f891d59548..60678fbb76 100644
--- a/apps/client/src/services/import.ts
+++ b/apps/client/src/services/import.ts
@@ -4,7 +4,7 @@ import ws from "./ws.js";
import utils from "./utils.js";
import appContext from "../components/app_context.js";
import { t } from "./i18n.js";
-import { WebSocketMessage } from "@triliumnext/commons";
+import { ProgressPhase, WebSocketMessage } from "@triliumnext/commons";
type BooleanLike = boolean | "true" | "false";
@@ -77,15 +77,21 @@ function makeToast(id: string, message: string): ToastOptionsWithRequiredId {
/**
* Builds the persistent "import in progress" toast:
- * - a total is known → "Importing X of N" with a progress bar;
+ * - a phase is known (zip import) → a phase-specific message: "Extracted X items of N" while extracting
+ * archive entries, "Processed X notes of N" while post-processing the created notes;
+ * - a total but no phase (single-format importers like Notion/Obsidian) → "Imported X notes of N";
* - some progress, no total → a bare running count;
* - nothing counted yet (count 0, no total) → a generic indeterminate message, since "in progress: 0"
* is meaningless while the importer is still working out how much there is to do.
*/
-function makeProgressToast(taskId: string, progressCount: number, totalCount?: number): ToastOptionsWithRequiredId {
+function makeProgressToast(taskId: string, progressCount: number, totalCount?: number, phase?: ProgressPhase): ToastOptionsWithRequiredId {
const hasTotal = typeof totalCount === "number" && totalCount > 0;
let message: string;
- if (hasTotal) {
+ if (hasTotal && phase === "extracting") {
+ message = t("import.extracting", { progress: progressCount, total: totalCount });
+ } else if (hasTotal && phase === "processing") {
+ message = t("import.processing", { progress: progressCount, total: totalCount });
+ } else if (hasTotal) {
message = t("import.in-progress-with-total", { progress: progressCount, total: totalCount });
} else if (progressCount > 0) {
message = t("import.in-progress", { progress: progressCount });
@@ -129,7 +135,7 @@ ws.subscribeToMessages(async (message) => {
if (message.type === "taskError") {
reportImportError(message.taskId, message.message);
} else if (message.type === "taskProgressCount") {
- toastService.showPersistent(makeProgressToast(message.taskId, message.progressCount, message.totalCount));
+ toastService.showPersistent(makeProgressToast(message.taskId, message.progressCount, message.totalCount, message.phase));
} else if (message.type === "taskSucceeded") {
const toast = makeToast(message.taskId, t("import.successful"));
toast.timeout = 5000;
@@ -150,7 +156,7 @@ ws.subscribeToMessages(async (message: WebSocketMessage) => {
if (message.type === "taskError") {
reportImportError(message.taskId, message.message);
} else if (message.type === "taskProgressCount") {
- toastService.showPersistent(makeProgressToast(message.taskId, message.progressCount, message.totalCount));
+ toastService.showPersistent(makeProgressToast(message.taskId, message.progressCount, message.totalCount, message.phase));
} else if (message.type === "taskSucceeded") {
const toast = makeToast(message.taskId, t("import.successful"));
toast.timeout = 5000;
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.json
index c07af30ef1..b30bdfd439 100644
--- a/apps/client/src/translations/en/translation.json
+++ b/apps/client/src/translations/en/translation.json
@@ -150,7 +150,7 @@
"export": "Export",
"choose_export_type": "Choose export type first please",
"preparing_export": "Preparing for export…",
- "export_in_progress_with_total": "Exporting {{progressCount}} of {{totalCount}} notes",
+ "export_in_progress_with_total": "Exported {{progressCount}} notes out of {{totalCount}}",
"export_finished_successfully": "Export finished successfully.",
"format_pdf": "PDF - for printing or sharing purposes."
},
@@ -239,8 +239,10 @@
"reset_button": "Reset to Default List"
},
"starting": "Importing…",
- "in-progress": "Import in progress: {{progress}}",
- "in-progress-with-total": "Importing {{progress}} of {{total}}",
+ "in-progress": "Imported {{progress}} notes",
+ "in-progress-with-total": "Imported {{progress}} notes out of {{total}}",
+ "extracting": "Extracted {{progress}} items out of {{total}}",
+ "processing": "Processed {{progress}} notes out of {{total}}",
"successful": "Import finished successfully."
},
"file_upload": {
diff --git a/packages/commons/src/lib/ws_api.ts b/packages/commons/src/lib/ws_api.ts
index b847b0e05b..6624df3f2c 100644
--- a/packages/commons/src/lib/ws_api.ts
+++ b/packages/commons/src/lib/ws_api.ts
@@ -65,6 +65,13 @@ export type TaskType = keyof TaskDataDefinitions | keyof TaskResultDefinitions;
export type TaskData<T extends TaskType> = TaskDataDefinitions[T];
export type TaskResult<T extends TaskType> = TaskResultDefinitions[T];
+/**
+ * Identifies which phase of a multi-phase task a progress message belongs to, so the client can label
+ * the bar accordingly (e.g. zip import counts archive entries while "extracting", then notes while
+ * "processing"). Single-phase tasks omit it and the client falls back to a generic message.
+ */
+export type ProgressPhase = "extracting" | "processing";
+
type TaskDefinition<T extends TaskType> = {
type: "taskProgressCount",
taskId: string;
@@ -73,6 +80,8 @@ type TaskDefinition<T extends TaskType> = {
progressCount: number;
/** Total expected units of work, when known up front; lets the client show a progress bar. */
totalCount?: number;
+ /** Which phase of a multi-phase task this count belongs to; lets the client pick a phase-specific label. */
+ phase?: ProgressPhase;
} | {
type: "taskError",
taskId: string;
diff --git a/packages/trilium-core/src/services/import/zip.spec.ts b/packages/trilium-core/src/services/import/zip.spec.ts
index f124663a27..a3fe7937de 100644
--- a/packages/trilium-core/src/services/import/zip.spec.ts
+++ b/packages/trilium-core/src/services/import/zip.spec.ts
@@ -224,11 +224,12 @@ describe("processNoteContent", () => {
expect(sheet.cellData[0][1].v).toBe(42);
});
- it("reports a progress total that the running count lands exactly on (bar reaches 100%)", async () => {
+ it("each phase's running count lands exactly on its total (the bar reaches 100% in both phases)", async () => {
// fresh task id -> a new TaskContext whose constructor increment happens before we spy
const taskContext = TaskContext.getInstance("import-progress-total", "importNotes", { textImportedAsText: true });
const setTotalSpy = vi.spyOn(taskContext, "setTotalCount");
const increaseSpy = vi.spyOn(taskContext, "increaseProgressCount");
+ const resetSpy = vi.spyOn(taskContext, "resetProgressCount");
const zipBuffer = await createZipBuffer({
"a.txt": "first",
@@ -248,21 +249,25 @@ describe("processNoteContent", () => {
});
});
- // the total is set twice: an initial estimate after the scan pass, then widened to the exact
- // value once the created-note count is known
+ // two labelled phases — extraction (archive entries) then processing (created notes) — each reset
+ // to zero and given its own total, so each drives an independent 0→100% bar
expect(setTotalSpy).toHaveBeenCalledTimes(2);
-
- const finalTotal = setTotalSpy.mock.calls.at(-1)?.[0];
- // the constructor's first increment isn't captured by the spy, but it brought progressCount from
- // -1 to 0, so the final progressCount equals the number of captured increments
- expect(finalTotal).toBe(increaseSpy.mock.calls.length);
+ expect(resetSpy).toHaveBeenCalledTimes(2);
+
+ const extractionTotal = setTotalSpy.mock.calls[0]?.[0] ?? 0;
+ const processingTotal = setTotalSpy.mock.calls[1]?.[0] ?? 0;
+ // the constructor's first increment ran before the spy; every later increment belongs to one of the
+ // two phases, so the captured increments equal the two phase totals combined — i.e. each phase counts
+ // up to exactly its own total
+ expect(increaseSpy.mock.calls.length).toBe(extractionTotal + processingTotal);
});
- it("sets the progress total up front so the denominator doesn't jump mid-import", async () => {
- const taskContext = TaskContext.getInstance("import-progress-no-jump", "importNotes", { textImportedAsText: true });
+ it("drives extraction and post-processing as two separate, labelled phases", async () => {
+ const taskContext = TaskContext.getInstance("import-progress-phases", "importNotes", { textImportedAsText: true });
const setTotalSpy = vi.spyOn(taskContext, "setTotalCount");
+ const setPhaseSpy = vi.spyOn(taskContext, "setPhase");
- // Flat files at the root: each becomes a note, no folder notes, no meta file.
+ // Flat files at the root: 3 entries, each becomes a note, no folder notes, no meta file.
const zipBuffer = await createZipBuffer({ "a.txt": "first", "b.txt": "second", "c.txt": "third" });
await new Promise<void>((resolve, reject) => {
@@ -277,12 +282,11 @@ describe("processNoteContent", () => {
});
});
- const firstTotal = setTotalSpy.mock.calls[0]?.[0] ?? 0;
- const finalTotal = setTotalSpy.mock.calls.at(-1)?.[0] ?? 0;
- // The first total already accounts for the post-processing phase (3 entries + 3 notes = 6), rather
- // than the bare entry count (3) — so the denominator never leaps from 3 to 6 partway through.
- expect(firstTotal).toBe(6);
- expect(finalTotal).toBe(firstTotal);
+ // extraction is announced first (counting archive entries), then processing (counting created notes)
+ expect(setPhaseSpy.mock.calls.map((call) => call[0])).toEqual(["extracting", "processing"]);
+ // 3 entries extracted, then the 3 created notes processed — the denominator deliberately switches
+ // between phases rather than being summed into one inflated total
+ expect(setTotalSpy.mock.calls.map((call) => call[0])).toEqual([3, 3]);
});
it("imports a CSV entry as a plain file note when the spreadsheet option is off", async () => {
diff --git a/packages/trilium-core/src/services/import/zip.ts b/packages/trilium-core/src/services/import/zip.ts
index d8ca7616ca..01a6d175e4 100644
--- a/packages/trilium-core/src/services/import/zip.ts
+++ b/packages/trilium-core/src/services/import/zip.ts
@@ -739,14 +739,14 @@ async function importZip(taskContext: TaskContext<"importNotes">, source: ZipSou
topLevelPath = (topLevelItems.size > 1 ? "" : topLevelItems.values().next().value ?? "");
- // The import is counted in two phases: extracting every entry, then post-processing each created note.
- // Set the total to cover *both* up front so the bar climbs monotonically — otherwise the denominator
- // jumps mid-import (e.g. "X of 32k" → "X of 60k") when post-processing starts. The post-process count
- // is taken from the meta file when present (exact for a Trilium export); without one, every entry
- // becomes a note, so the entry count is the right estimate. Any small mismatch is corrected exactly by
- // the setTotalCount below, which then barely moves instead of leaping.
- const estimatedNoteCount = countImportableNotes(metaFile) || entriesToProcess;
- taskContext.setTotalCount(entriesToProcess + estimatedNoteCount);
+ // The import runs in two labelled phases, each driving its own 0→100% bar: first "extracting" counts
+ // every archive entry (notes, attachments, folders, the meta file), then "processing" counts only the
+ // notes that were actually created. The denominator deliberately changes between phases — the client
+ // shows distinct messages ("Extracted X items" vs "Processed X notes") so the switch reads as progress
+ // rather than the bar jerking. Here we seed the extraction phase with the entry count from the scan.
+ taskContext.setPhase("extracting");
+ taskContext.resetProgressCount();
+ taskContext.setTotalCount(entriesToProcess);
// Notes are written in batches, each batch in a single synchronous transaction, instead of letting
// every entity save auto-commit on its own. The per-note BEGIN/COMMIT (and its WAL fsync) dominated
@@ -811,9 +811,11 @@ async function importZip(taskContext: TaskContext<"importNotes">, source: ZipSou
flushBatch();
- // post-processing increments progress once per created note (a subset of the entries, now known
- // exactly), so widen the total accordingly to keep the count accurate and let the bar reach 100%
- taskContext.setTotalCount(entriesToProcess + createdNoteIds.size);
+ // Post-processing phase: increments progress once per created note (now known exactly). Reset the count
+ // and re-seed the total with the note count so this phase renders its own clean 0→100% bar.
+ taskContext.setPhase("processing");
+ taskContext.resetProgressCount();
+ taskContext.setTotalCount(createdNoteIds.size);
for (const noteId of createdNoteIds) {
const note = becca.getNote(noteId);
@@ -931,22 +933,6 @@ export function removeTriliumTags(content: string) {
return content;
}
-/**
- * Estimates how many notes an import will create — the post-processing phase's unit count — from the meta
- * tree, so the progress total can be set once up front. Clones and explicitly non-imported notes don't
- * create a note, so they're not counted. Returns 0 when there's no meta file (the caller then falls back to
- * the entry count, since without meta every content entry becomes a note). `metaFile` is typed nullable
- * because control-flow analysis can't see it being assigned inside the read callback.
- */
-function countImportableNotes(metaFile: MetaFile | null): number {
- if (!metaFile) {
- return 0;
- }
- const count = (notes: NoteMeta[]): number =>
- notes.reduce((sum, note) => sum + (note.isClone || note.noImport ? 0 : 1) + count(note.children ?? []), 0);
- return count(metaFile.files);
-}
-
export default {
importZip
};
diff --git a/packages/trilium-core/src/services/task_context.spec.ts b/packages/trilium-core/src/services/task_context.spec.ts
index b17caba200..877eacbf4f 100644
--- a/packages/trilium-core/src/services/task_context.spec.ts
+++ b/packages/trilium-core/src/services/task_context.spec.ts
@@ -113,6 +113,28 @@ describe("TaskContext", () => {
});
});
+ describe("setPhase", () => {
+ it("tags subsequent progress messages with the phase and flushes the next one immediately", () => {
+ vi.useFakeTimers();
+ vi.setSystemTime(1_000);
+
+ const ctx = new TaskContext("phase-1", "importNotes", importData);
+ // The constructor's first message carries no phase.
+ expect(sendMessageToAllClients).toHaveBeenLastCalledWith(expect.not.objectContaining({ phase: expect.anything() }));
+
+ // setPhase resets the throttle, so the very next increment sends even within the 300ms window.
+ ctx.setPhase("extracting");
+ vi.setSystemTime(1_100);
+ ctx.increaseProgressCount();
+ expect(sendMessageToAllClients).toHaveBeenLastCalledWith(expect.objectContaining({ phase: "extracting" }));
+
+ ctx.setPhase("processing");
+ vi.setSystemTime(1_200);
+ ctx.increaseProgressCount();
+ expect(sendMessageToAllClients).toHaveBeenLastCalledWith(expect.objectContaining({ phase: "processing" }));
+ });
+ });
+
describe("reportError", () => {
it("broadcasts a taskError message with the failure text and task metadata", () => {
const ctx = new TaskContext("err-1", "importNotes", importData);
diff --git a/packages/trilium-core/src/services/task_context.ts b/packages/trilium-core/src/services/task_context.ts
index 1ef9f4c4e6..2483ecd23a 100644
--- a/packages/trilium-core/src/services/task_context.ts
+++ b/packages/trilium-core/src/services/task_context.ts
@@ -1,6 +1,6 @@
"use strict";
-import type { TaskData, TaskResult, TaskType, WebSocketMessage } from "@triliumnext/commons";
+import type { ProgressPhase, TaskData, TaskResult, TaskType, WebSocketMessage } from "@triliumnext/commons";
import ws from "./ws.js";
// taskId => TaskContext
@@ -11,6 +11,7 @@ class TaskContext<T extends TaskType> {
private taskType: TaskType;
private progressCount: number;
private totalCount: number | null;
+ private phase: ProgressPhase | null;
private lastSentCountTs: number;
data: TaskData<T>;
noteDeletionHandlerTriggered: boolean;
@@ -21,6 +22,7 @@ class TaskContext<T extends TaskType> {
this.data = data;
this.noteDeletionHandlerTriggered = false;
this.totalCount = null;
+ this.phase = null;
// progressCount is meant to represent just some progress - to indicate the task is not stuck
this.progressCount = -1; // we're incrementing immediately
@@ -50,6 +52,17 @@ class TaskContext<T extends TaskType> {
this.totalCount = totalCount;
}
+ /**
+ * Labels the phase the subsequent progress counts belong to, so the client can render a phase-specific
+ * message (e.g. "Extracted X items" vs "Processed X notes"). Typically paired with resetProgressCount()
+ * and setTotalCount() at a phase boundary so each phase drives its own 0→100% bar. Forces the next
+ * progress message to send immediately (bypassing the throttle) so the label switches without delay.
+ */
+ setPhase(phase: ProgressPhase) {
+ this.phase = phase;
+ this.lastSentCountTs = 0;
+ }
+
/**
* Resets the running progress count back to zero. Useful for multi-phase tasks (e.g. zip export,
* which first walks the tree to build metadata and then walks it again to write content) so a later
@@ -71,7 +84,8 @@ class TaskContext<T extends TaskType> {
taskType: this.taskType,
data: this.data,
progressCount: this.progressCount,
- ...(this.totalCount !== null ? { totalCount: this.totalCount } : {})
+ ...(this.totalCount !== null ? { totalCount: this.totalCount } : {}),
+ ...(this.phase !== null ? { phase: this.phase } : {})
} as WebSocketMessage);
}
}