Skip to content

Build your personal knowledge base with Trilium Notes

feat(desktop): native subtree export streaming straight to a file

Elian Doranf7dd2a82d4df
diff --git a/apps/client/src/widgets/dialogs/export.tsx b/apps/client/src/widgets/dialogs/export.tsx
index 1a2f17e1b0..9b373f277e 100644
--- a/apps/client/src/widgets/dialogs/export.tsx
+++ b/apps/client/src/widgets/dialogs/export.tsx
@@ -69,7 +69,7 @@ export default function ExportDialog() {
return;
}
- exportBranch(opts.branchId, exportType, selectedFormat);
+ exportBranch(opts.branchId, exportType, selectedFormat, opts.noteTitle || "export");
setShown(false);
}}
onHidden={() => setShown(false)}
@@ -136,8 +136,18 @@ function exportResultText(exportType: "subtree" | "single", format: string) {
return format === "markdown" ? t("export.result_subtree_markdown") : t("export.result_subtree_html");
}
-function exportBranch(branchId: string, type: string, format: string) {
+async function exportBranch(branchId: string, type: string, format: string, title: string) {
const taskId = utils.randomString(10);
+
+ // Desktop: stream subtree zip exports straight to a user-chosen file, bypassing
+ // the in-memory download path. Electron's download manager buffers the whole
+ // response in memory, which spikes badly for large (multi-GB) exports. OPML is
+ // a single non-zip file handled by the regular download route.
+ if (utils.isElectron() && type === "subtree" && format !== "opml") {
+ await window.electronApi?.nativeExport.exportSubtreeToFile({ branchId, format, title, taskId });
+ return;
+ }
+
const url = open.getUrlForDownload(`api/branches/${branchId}/export/${type}/${format}/${taskId}`);
open.download(url);
}
diff --git a/apps/desktop/src/main.ts b/apps/desktop/src/main.ts
index 2738d26dbb..e48f9359b8 100644
--- a/apps/desktop/src/main.ts
+++ b/apps/desktop/src/main.ts
@@ -27,6 +27,7 @@ import DesktopPlatformProvider from "./platform_provider";
import { registerTriliumAppScheme, setupTriliumAppProtocol } from "./protocol";
import { applyLaunchOnStartup, setupAutoLaunch, wasLaunchedHidden } from "./services/auto_launch";
import { setupCustomDictionary } from "./services/custom_dictionary";
+import { setupExportHandlers } from "./services/export";
import { setupOneNoteHandlers } from "./services/onenote";
import { setupPrintingHandlers } from "./services/printing";
import { getSecuritySettings, registerSecurityIpcHandlers } from "./services/security_settings";
@@ -128,6 +129,7 @@ export async function main() {
setupShellHandlers();
setupOneNoteHandlers();
setupPrintingHandlers();
+ setupExportHandlers();
registerSecurityIpcHandlers();
setupStartupMetricsIpc();
diff --git a/apps/desktop/src/preload.spec.ts b/apps/desktop/src/preload.spec.ts
index 367809eb81..a6f05b1d14 100644
--- a/apps/desktop/src/preload.spec.ts
+++ b/apps/desktop/src/preload.spec.ts
@@ -613,4 +613,14 @@ describe("preload script", () => {
expect(ipcRendererInvoked).toContainEqual({ channel: "onenote-login", args: [] });
});
});
+
+ describe("nativeExport", () => {
+ const nativeExport = () => getGroup("nativeExport");
+
+ it("exportSubtreeToFile invokes the corresponding IPC channel with the options", async () => {
+ const opts = { branchId: "branch123", format: "html", title: "My Note", taskId: "task1" };
+ await nativeExport().exportSubtreeToFile(opts);
+ expect(ipcRendererInvoked).toContainEqual({ channel: "export-subtree-to-file", args: [opts] });
+ });
+ });
});
diff --git a/apps/desktop/src/preload.ts b/apps/desktop/src/preload.ts
index 6c928f4f52..02c3238f6a 100644
--- a/apps/desktop/src/preload.ts
+++ b/apps/desktop/src/preload.ts
@@ -204,6 +204,12 @@ contextBridge.exposeInMainWorld("electronApi", {
}
},
+ nativeExport: {
+ exportSubtreeToFile(opts: { branchId: string; format: string; title: string; taskId: string }) {
+ return ipcRenderer.invoke("export-subtree-to-file", opts);
+ }
+ },
+
ws: {
// Renderer → main process. Mirror channel name with the server-side
// IpcMessagingProvider constants.
diff --git a/apps/desktop/src/services/export.ts b/apps/desktop/src/services/export.ts
new file mode 100644
index 0000000000..05ab13e30d
--- /dev/null
+++ b/apps/desktop/src/services/export.ts
@@ -0,0 +1,46 @@
+import type { ExportFormat } from "@triliumnext/core";
+import { getLog, utils as coreUtils, zipExportService } from "@triliumnext/core";
+import type { NativeExportResult } from "@triliumnext/commons";
+import { default as electron } from "electron";
+import fs from "fs/promises";
+import { t } from "i18next";
+
+interface ExportSubtreeOpts {
+ branchId: string;
+ format: string;
+ title: string;
+ taskId: string;
+}
+
+/**
+ * Registers the desktop-native subtree export IPC handler. Instead of streaming a
+ * (potentially multi-GB) archive through an in-memory HTTP response — which
+ * Electron's download manager buffers whole — this prompts a save dialog and
+ * streams the export straight to the chosen file with bounded memory.
+ */
+export function setupExportHandlers() {
+ electron.ipcMain.handle("export-subtree-to-file", async (_e, { branchId, format, title, taskId }: ExportSubtreeOpts): Promise<NativeExportResult> => {
+ const focusedWindow = electron.BrowserWindow.getFocusedWindow();
+ if (!focusedWindow) {
+ return { status: "cancelled" };
+ }
+
+ const filePath = electron.dialog.showSaveDialogSync(focusedWindow, {
+ defaultPath: coreUtils.formatDownloadTitle(title, "file", "application/zip"),
+ filters: [{ name: t("export.zip_filter"), extensions: ["zip"] }]
+ });
+ if (!filePath) {
+ return { status: "cancelled" };
+ }
+
+ try {
+ await zipExportService.exportBranchToZipFile(branchId, format as ExportFormat, filePath, taskId);
+ return { status: "saved", filePath };
+ } catch (e) {
+ // Remove the partial/incomplete archive left at the destination.
+ await fs.rm(filePath, { force: true });
+ getLog().error(`Native subtree export failed: ${coreUtils.safeExtractMessageAndStackFromError(e)}`);
+ return { status: "error", message: e instanceof Error ? e.message : String(e) };
+ }
+ });
+}
diff --git a/apps/server/src/assets/translations/en/server.json b/apps/server/src/assets/translations/en/server.json
index 2747e5678d..c7e00adc60 100644
--- a/apps/server/src/assets/translations/en/server.json
+++ b/apps/server/src/assets/translations/en/server.json
@@ -335,6 +335,9 @@
"obsidian_import": {
"root-title": "Obsidian import"
},
+ "export": {
+ "zip_filter": "ZIP archive (*.zip)"
+ },
"pdf": {
"export_filter": "PDF Document (*.pdf)",
"unable-to-export-message": "The current note could not be exported as a PDF.",
diff --git a/packages/commons/src/lib/electron_api_interface.ts b/packages/commons/src/lib/electron_api_interface.ts
index 6a992375bb..f21d75701d 100644
--- a/packages/commons/src/lib/electron_api_interface.ts
+++ b/packages/commons/src/lib/electron_api_interface.ts
@@ -511,6 +511,27 @@ export interface ElectronOneNoteApi {
login(): Promise<OneNoteLoginResult>;
}
+/** Outcome of a {@link ElectronNativeExportApi.exportSubtreeToFile} request. */
+export interface NativeExportResult {
+ status: "saved" | "cancelled" | "error";
+ /** Absolute path the archive was written to (when `status === "saved"`). */
+ filePath?: string;
+ /** Failure detail (when `status === "error"`). */
+ message?: string;
+}
+
+/** Desktop-native subtree export that streams a `.zip` straight to a file. */
+export interface ElectronNativeExportApi {
+ /**
+ * Prompts a native "save as" dialog, then streams a subtree (branch) export
+ * to the chosen path on disk. This bypasses the in-memory download path, so
+ * memory stays bounded regardless of archive size. Progress/success/error
+ * are reported over the WebSocket via `taskId`. Resolves once the dialog is
+ * dismissed (`cancelled`) or the export finishes (`saved` / `error`).
+ */
+ exportSubtreeToFile(opts: { branchId: string; format: string; title: string; taskId: string }): Promise<NativeExportResult>;
+}
+
/**
* The complete surface exposed to the renderer as `window.electronApi` via
* `contextBridge`. The renderer must access Electron-only functionality through
@@ -545,4 +566,6 @@ export interface ElectronApi {
security: ElectronSecurityApi;
/** OneNote importer sign-in via a loopback OAuth redirect (desktop only). */
onenote: ElectronOneNoteApi;
+ /** Desktop-native subtree export that streams a `.zip` straight to a file. */
+ nativeExport: ElectronNativeExportApi;
}
diff --git a/packages/trilium-core/src/services/export/zip.spec.ts b/packages/trilium-core/src/services/export/zip.spec.ts
index d97eb76392..b9ae6edbfc 100644
--- a/packages/trilium-core/src/services/export/zip.spec.ts
+++ b/packages/trilium-core/src/services/export/zip.spec.ts
@@ -484,4 +484,39 @@ describe.skipIf(isBrowserRuntime)("zip export (real DB)", () => {
).rejects.toThrow(/not found/);
});
});
+
+ describe("exportBranchToZipFile", () => {
+ let tempDir: string;
+
+ beforeAll(() => {
+ tempDir = mkdtempSync(join(tmpdir(), "trilium-zip-branch-export-"));
+ });
+
+ it("streams a subtree export for the given branch to a file path", async () => {
+ const { note, branch } = createNote("root", { title: "BranchFileExport", content: "<p>branch to file</p>" });
+ const zipPath = join(tempDir, `branch-export-${note.noteId}.zip`);
+
+ await getContext().init(() =>
+ zip.exportBranchToZipFile(branch.branchId, "html", zipPath, "no-progress-reporting")
+ );
+
+ const buffer = readFileSync(zipPath);
+ const entries = await readArchive(buffer);
+ const rootMeta = parseMeta(entries).files[0];
+
+ expect(rootMeta.noteId).toBe(note.noteId);
+ const dataFileName = rootMeta.dataFileName ?? "";
+ expect(entries[dataFileName].toString("utf-8")).toContain("branch to file");
+
+ rmSync(zipPath, { force: true });
+ });
+
+ it("throws a ValidationError for a non-existent branch", async () => {
+ await expect(
+ getContext().init(() =>
+ zip.exportBranchToZipFile("missingBranch123", "html", join(tempDir, "never.zip"), "no-progress-reporting")
+ )
+ ).rejects.toThrow(/not found/);
+ });
+ });
});
diff --git a/packages/trilium-core/src/services/export/zip.ts b/packages/trilium-core/src/services/export/zip.ts
index 745fd47e24..1f7762e95a 100644
--- a/packages/trilium-core/src/services/export/zip.ts
+++ b/packages/trilium-core/src/services/export/zip.ts
@@ -488,7 +488,34 @@ async function exportToZipFile(noteId: string, format: ExportFormat, zipFilePath
getLog().info(`Exported '${noteId}' with format '${format}' to '${zipFilePath}'`);
}
+/**
+ * Streams a subtree (branch) export straight to a file on disk, reporting
+ * progress/success/failure over the WebSocket via `taskId`. Used by the desktop
+ * "native export" flow, which writes directly to a user-chosen path instead of
+ * routing a potentially multi-GB archive through an in-memory HTTP response.
+ */
+async function exportBranchToZipFile(branchId: string, format: ExportFormat, zipFilePath: string, taskId: string) {
+ const branch = becca.getBranch(branchId);
+ if (!branch) {
+ throw new ValidationError(`Branch ${branchId} not found.`);
+ }
+
+ const taskContext = new TaskContext(taskId, "export", null);
+ const { destination, waitForFinish } = getZipProvider().createFileStream(zipFilePath);
+
+ try {
+ await exportToZip(taskContext, branch, format, destination as Record<string, any>, false);
+ await waitForFinish();
+ } catch (e: unknown) {
+ taskContext.reportError(`Export failed with error: ${e instanceof Error ? e.message : String(e)}`);
+ throw e;
+ }
+
+ getLog().info(`Exported branch '${branchId}' with format '${format}' to '${zipFilePath}'`);
+}
+
export default {
exportToZip,
- exportToZipFile
+ exportToZipFile,
+ exportBranchToZipFile
};