Skip to content

Build your personal knowledge base with Trilium Notes

fix(import/export): address automated review findings

Elian Doran1afab8ab5779
diff --git a/apps/desktop/src/services/export.ts b/apps/desktop/src/services/export.ts
index 05ab13e30d..80ac927848 100644
--- a/apps/desktop/src/services/export.ts
+++ b/apps/desktop/src/services/export.ts
@@ -25,11 +25,13 @@ export function setupExportHandlers() {
return { status: "cancelled" };
}
- const filePath = electron.dialog.showSaveDialogSync(focusedWindow, {
+ // Async dialog: showSaveDialogSync blocks the main process event loop (freezing the UI, WebSockets
+ // and background tasks) for as long as the dialog is open.
+ const { canceled, filePath } = await electron.dialog.showSaveDialog(focusedWindow, {
defaultPath: coreUtils.formatDownloadTitle(title, "file", "application/zip"),
filters: [{ name: t("export.zip_filter"), extensions: ["zip"] }]
});
- if (!filePath) {
+ if (canceled || !filePath) {
return { status: "cancelled" };
}
diff --git a/apps/desktop/src/services/import.spec.ts b/apps/desktop/src/services/import.spec.ts
index ae7a77c400..83b378ae7c 100644
--- a/apps/desktop/src/services/import.spec.ts
+++ b/apps/desktop/src/services/import.spec.ts
@@ -4,18 +4,25 @@ import { beforeEach, describe, expect, it, vi } from "vitest";
const electronMock = vi.hoisted(() => ({
handlers: new Map<string, (...args: unknown[]) => unknown>(),
handle: vi.fn((channel: string, handler: (...args: unknown[]) => unknown) => electronMock.handlers.set(channel, handler)),
- showOpenDialogSync: vi.fn<(...args: unknown[]) => string[] | undefined>(),
+ showOpenDialog: vi.fn<(...args: unknown[]) => Promise<{ canceled: boolean; filePaths: string[] }>>(),
getFocusedWindow: vi.fn<() => object | null>(() => ({}))
}));
vi.mock("electron", () => ({
default: {
ipcMain: { handle: electronMock.handle },
- dialog: { showOpenDialogSync: electronMock.showOpenDialogSync },
+ dialog: { showOpenDialog: electronMock.showOpenDialog },
BrowserWindow: { getFocusedWindow: electronMock.getFocusedWindow }
}
}));
+/** Resolves the open-dialog mock to a user selection (or a cancel) the way Electron's async dialog does. */
+function dialogReturns(filePaths: string[] | undefined) {
+ electronMock.showOpenDialog.mockResolvedValue(
+ filePaths && filePaths.length ? { canceled: false, filePaths } : { canceled: true, filePaths: [] }
+ );
+}
+
vi.mock("i18next", () => ({ t: (key: string) => key }));
// --- fs mock: the handler reads non-zip files into a buffer; zips are read in place (no readFile) ---
@@ -75,7 +82,7 @@ describe("desktop native import — capability token", () => {
});
it("pick returns tokens + filenames (never paths) for the user-chosen files", async () => {
- electronMock.showOpenDialogSync.mockReturnValue(["C:/Users/me/big vault.zip", "C:/Users/me/notes.md"]);
+ dialogReturns(["C:/Users/me/big vault.zip", "C:/Users/me/notes.md"]);
const result = await pick();
@@ -88,7 +95,7 @@ describe("desktop native import — capability token", () => {
});
it("a cancelled dialog mints no token and imports nothing", async () => {
- electronMock.showOpenDialogSync.mockReturnValue(undefined);
+ dialogReturns(undefined);
expect(await pick()).toEqual({ status: "cancelled" });
expect(coreMock.dispatch).not.toHaveBeenCalled();
@@ -97,7 +104,7 @@ describe("desktop native import — capability token", () => {
it("imports a granted zip in place (dispatch receives a { path } file, never read into a buffer)", async () => {
vi.useFakeTimers();
try {
- electronMock.showOpenDialogSync.mockReturnValue(["/data/big.zip"]);
+ dialogReturns(["/data/big.zip"]);
const { files } = await pick();
const token = files?.[0].token;
@@ -121,7 +128,7 @@ describe("desktop native import — capability token", () => {
});
it("reads a granted non-zip file into a buffer before dispatching", async () => {
- electronMock.showOpenDialogSync.mockReturnValue(["/data/note.md"]);
+ dialogReturns(["/data/note.md"]);
fsMock.readFile.mockResolvedValue(Buffer.from("# hello"));
const { files } = await pick();
@@ -136,7 +143,7 @@ describe("desktop native import — capability token", () => {
it("fires the success toast only on the last file of a batch", async () => {
vi.useFakeTimers();
try {
- electronMock.showOpenDialogSync.mockReturnValue(["/data/a.md", "/data/b.md"]);
+ dialogReturns(["/data/a.md", "/data/b.md"]);
const { files } = await pick();
await importFromToken({ token: files?.[0].token, parentNoteId: "p", taskId: "t", options: OPTIONS, last: false });
@@ -152,7 +159,7 @@ describe("desktop native import — capability token", () => {
});
it("forwards a provider format and still streams the tagged zip from path (not read into a buffer)", async () => {
- electronMock.showOpenDialogSync.mockReturnValue(["/data/vault.zip"]);
+ dialogReturns(["/data/vault.zip"]);
const { files } = await pick();
await importFromToken({ token: files?.[0].token, parentNoteId: "p", taskId: "t", options: OPTIONS, last: true, format: "obsidian" });
@@ -173,7 +180,7 @@ describe("desktop native import — capability token", () => {
});
it("consumes the token: the same token cannot be redeemed twice (no replay)", async () => {
- electronMock.showOpenDialogSync.mockReturnValue(["/data/once.zip"]);
+ dialogReturns(["/data/once.zip"]);
const { files } = await pick();
const token = files?.[0].token;
@@ -186,7 +193,7 @@ describe("desktop native import — capability token", () => {
});
it("reports a failed import as an error and surfaces it on the task channel", async () => {
- electronMock.showOpenDialogSync.mockReturnValue(["/data/bad.zip"]);
+ dialogReturns(["/data/bad.zip"]);
coreMock.dispatch.mockRejectedValue(new Error("corrupt archive"));
const { files } = await pick();
@@ -197,7 +204,7 @@ describe("desktop native import — capability token", () => {
});
it("surfaces an OPML structured failure (the [status, message] tuple) as an error", async () => {
- electronMock.showOpenDialogSync.mockReturnValue(["/data/bad.opml"]);
+ dialogReturns(["/data/bad.opml"]);
coreMock.dispatch.mockResolvedValue([400, "Unsupported OPML version"]);
const { files } = await pick();
diff --git a/apps/desktop/src/services/import.ts b/apps/desktop/src/services/import.ts
index bceb06527b..05497ce46c 100644
--- a/apps/desktop/src/services/import.ts
+++ b/apps/desktop/src/services/import.ts
@@ -36,16 +36,18 @@ export function setupImportHandlers() {
return { status: "cancelled" };
}
- const selection = electron.dialog.showOpenDialogSync(focusedWindow, {
+ // Async dialog: showOpenDialogSync blocks the main process event loop (freezing the UI, WebSockets
+ // and background tasks) for as long as the picker is open.
+ const { canceled, filePaths } = await electron.dialog.showOpenDialog(focusedWindow, {
properties: ["openFile", "multiSelections"]
});
- if (!selection || selection.length === 0) {
+ if (canceled || filePaths.length === 0) {
return { status: "cancelled" };
}
return {
status: "selected",
- files: selection.map((path) => ({ token: grantFileAccess(path), fileName: basename(path) }))
+ files: filePaths.map((path) => ({ token: grantFileAccess(path), fileName: basename(path) }))
};
});
@@ -72,8 +74,16 @@ const GRANT_TTL_MS = 5 * 60 * 1000;
/** Mints a single-use, time-limited token for a path the *user* picked in the OS dialog. */
function grantFileAccess(path: string): string {
+ // Drop any grants the user never redeemed so the map can't grow unbounded across repeated dialogs.
+ const now = Date.now();
+ for (const [existingToken, grant] of fileGrants) {
+ if (grant.expiresAt < now) {
+ fileGrants.delete(existingToken);
+ }
+ }
+
const token = coreUtils.randomString(32);
- fileGrants.set(token, { path, expiresAt: Date.now() + GRANT_TTL_MS });
+ fileGrants.set(token, { path, expiresAt: now + GRANT_TTL_MS });
return token;
}
@@ -93,23 +103,26 @@ async function runNativeImport(path: string, opts: ImportFromTokenOpts): Promise
const taskContext = TaskContext.getInstance(opts.taskId, "importNotes", opts.options);
const options = opts.options satisfies ImportOptions;
+ const file = await buildImportFile(path, options.explodeArchives, opts.format);
+
const note = await cls.init(async () => {
// Match the HTTP import route: skip per-entity events and change-id tracking during the bulk import.
cls.disableEntityEvents();
cls.ignoreEntityChangeIds();
- const file = await buildImportFile(path, options.explodeArchives, opts.format);
- const result = await importDispatchService(taskContext, file, parentNote, options, opts.format);
-
- // Import ran with entity events disabled, so becca wasn't updated incrementally — force a reload.
- // Must run inside the CLS context: becca_loader.load() toggles slow-query logging via the namespace.
- becca_loader.load();
-
- if (Array.isArray(result)) {
- // OPML reports a structured failure as a `[httpStatus, message]` array.
- throw new Error(String(result[1]));
+ try {
+ const result = await importDispatchService(taskContext, file, parentNote, options, opts.format);
+ if (Array.isArray(result)) {
+ // OPML reports a structured failure as a `[httpStatus, message]` array.
+ throw new Error(String(result[1]));
+ }
+ return result;
+ } finally {
+ // Import ran with entity events disabled, so becca wasn't updated incrementally — reload it to
+ // resync the cache even if the import threw partway (some notes may already be written). Must run
+ // inside the CLS context: becca_loader.load() toggles slow-query logging via the namespace.
+ becca_loader.load();
}
- return result;
});
// Small delay mirrors the route: let the transaction commit before the client reacts to success. Only
diff --git a/apps/server/src/zip_provider.ts b/apps/server/src/zip_provider.ts
index 7e7d349e4f..2e6c943d31 100644
--- a/apps/server/src/zip_provider.ts
+++ b/apps/server/src/zip_provider.ts
@@ -11,7 +11,9 @@ class NodejsZipArchive implements ZipArchive {
// exactly one "entry" event per append, so this stays aligned with it.
readonly #pendingSizes: number[] = [];
#queuedBytes = 0;
- #capacityWaiter: (() => void) | null = null;
+ #capacityWaiter: { resolve: () => void; reject: (err: Error) => void } | null = null;
+ // First error emitted by archiver (disk full, zlib failure, …); surfaced through append/waitForCapacity.
+ #error: Error | null = null;
// Cap how much appended-but-unwritten data archiver holds in its internal
// queue. The export walk appends the whole note tree synchronously; without
@@ -26,18 +28,33 @@ class NodejsZipArchive implements ZipArchive {
zlib: { level: 6 }
});
+ // An EventEmitter with no "error" listener throws as an *unhandled* exception when it errors, which
+ // crashes the process. Capture archiver's error and re-surface it through append/waitForCapacity/
+ // finalize so the export fails cleanly instead.
+ this.#archive.on("error", (err: Error) => {
+ this.#error = err;
+ if (this.#capacityWaiter) {
+ const waiter = this.#capacityWaiter;
+ this.#capacityWaiter = null;
+ waiter.reject(err);
+ }
+ });
+
// Fires as each queued entry finishes being written to the output.
this.#archive.on("entry", () => {
this.#queuedBytes -= this.#pendingSizes.shift() ?? 0;
if (this.#capacityWaiter && this.#queuedBytes < NodejsZipArchive.#HIGH_WATER_MARK) {
- const resolve = this.#capacityWaiter;
+ const waiter = this.#capacityWaiter;
this.#capacityWaiter = null;
- resolve();
+ waiter.resolve();
}
});
}
append(content: string | Uint8Array, options: ZipArchiveEntryOptions) {
+ if (this.#error) {
+ throw this.#error;
+ }
// Wrap the Uint8Array in a Buffer view sharing the same memory rather
// than copying it (Buffer.from(uint8array) would allocate a full copy).
// byteOffset/byteLength keep the view scoped to this slice, never the
@@ -52,11 +69,14 @@ class NodejsZipArchive implements ZipArchive {
}
waitForCapacity(): Promise<void> {
+ if (this.#error) {
+ return Promise.reject(this.#error);
+ }
if (this.#queuedBytes < NodejsZipArchive.#HIGH_WATER_MARK) {
return Promise.resolve();
}
// At most one waiter: the export loop awaits this before the next append.
- return new Promise((resolve) => { this.#capacityWaiter = resolve; });
+ return new Promise((resolve, reject) => { this.#capacityWaiter = { resolve, reject }; });
}
pipe(destination: unknown) {
diff --git a/packages/trilium-core/src/services/export/zip.ts b/packages/trilium-core/src/services/export/zip.ts
index a7b6fc3bba..6913c31d48 100644
--- a/packages/trilium-core/src/services/export/zip.ts
+++ b/packages/trilium-core/src/services/export/zip.ts
@@ -474,7 +474,13 @@ async function exportToZip(taskContext: TaskContext<"export">, branch: BBranch,
await archive.finalize();
- taskContext.taskSucceeded(null);
+ // Report success here only for an HTTP response, whose bytes are on the wire once finalize() resolves.
+ // A file (or other) stream isn't durably written until its "finish" event — which the caller awaits via
+ // waitForFinish() — so for those the caller emits taskSucceeded after the flush, not here, to avoid
+ // reporting success before a late write error (e.g. a full disk) leaves a truncated archive.
+ if ("setHeader" in res) {
+ taskContext.taskSucceeded(null);
+ }
}
/** Counts the notes in a metadata tree — i.e. the number of `saveNote()` calls the content-writing pass will make. */
@@ -520,6 +526,9 @@ async function exportBranchToZipFile(branchId: string, format: ExportFormat, zip
try {
await exportToZip(taskContext, branch, format, destination as Record<string, any>, false);
await waitForFinish();
+ // exportToZip defers success for non-HTTP destinations: only now, with the file fully flushed to
+ // disk, is the export genuinely complete — so report it here rather than before the final write.
+ taskContext.taskSucceeded(null);
} catch (e: unknown) {
taskContext.reportError(`Export failed with error: ${e instanceof Error ? e.message : String(e)}`);
throw e;