Skip to content

Build your personal knowledge base with Trilium Notes

feat(desktop): integrate native import into the drop zone

Elian Doran6a8d5dd8448f
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.json
index 28d2b222d9..c07af30ef1 100644
--- a/apps/client/src/translations/en/translation.json
+++ b/apps/client/src/translations/en/translation.json
@@ -218,8 +218,6 @@
"cardDescription": "ZIP, ENEX, OPML, Markdown, HTML, images and more",
"chooseImportFile": "Choose import file",
"importZipRecommendation": "When importing a ZIP file, the note hierarchy will reflect the subdirectory structure within the archive.",
- "largeZipHint": "Importing a large ZIP? Choose it directly for best performance:",
- "largeZipButton": "Choose .zip…",
"options": "Options",
"safeImportTooltip": "Trilium <code>.zip</code> exports can contain executable scripts. Safe import disables them; uncheck only if the archive is meant to run scripts and you trust its contents.",
"safeImport": "Safe import",
diff --git a/apps/client/src/widgets/dialogs/import/files.tsx b/apps/client/src/widgets/dialogs/import/files.tsx
index abe15ae3f7..187d289288 100644
--- a/apps/client/src/widgets/dialogs/import/files.tsx
+++ b/apps/client/src/widgets/dialogs/import/files.tsx
@@ -1,4 +1,4 @@
-import type { NativeImportOptions } from "@triliumnext/commons";
+import type { NativeImportOptions, NativeImportPickedFile } from "@triliumnext/commons";
import { useCallback, useEffect, useRef, useState } from "preact/hooks";
import { t } from "../../../services/i18n.js";
@@ -15,6 +15,9 @@ import type { ImportProvider, ImportProviderPanelProps } from "./types.js";
function FilesPanel({ parentNoteId, closeDialog, setFooter }: ImportProviderPanelProps) {
const [compressImages] = useTriliumOptionBool("compressImages");
const [files, setFiles] = useState<FileList | null>(null);
+ // Desktop only: files picked via the native OS dialog, identified by capability tokens (not paths) so
+ // they can be imported in place. Mutually exclusive with `files` — picking clears one, the other clears it.
+ const [nativeFiles, setNativeFiles] = useState<NativeImportPickedFile[] | null>(null);
const [safeImport, setSafeImport] = useState(true);
const [explodeArchives, setExplodeArchives] = useState(true);
const [shrinkImages, setShrinkImages] = useState(compressImages);
@@ -25,6 +28,26 @@ function FilesPanel({ parentNoteId, closeDialog, setFooter }: ImportProviderPane
const [optionsShown, setOptionsShown] = useState(false);
const doImport = useCallback(async () => {
+ // Close immediately and let the shared import toasts (registered in import.ts) report progress,
+ // completion and any error over the WebSocket. Rejections are swallowed so these void-ed calls
+ // don't raise an unhandled rejection.
+ if (nativeFiles?.length) {
+ const options: NativeImportOptions = {
+ safeImport, shrinkImages, textImportedAsText, codeImportedAsCode,
+ spreadsheetImportedAsSpreadsheet, explodeArchives, replaceUnderscoresWithSpaces
+ };
+ // One taskId for the whole batch so the toast tracks all files together; `last` on the final
+ // file fires the success toast once, mirroring the upload route.
+ const taskId = utils.randomString(10);
+ closeDialog();
+ for (let i = 0; i < nativeFiles.length; i++) {
+ await window.electronApi?.nativeImport.importFromToken({
+ token: nativeFiles[i].token, parentNoteId, taskId, options, last: i === nativeFiles.length - 1
+ }).catch(() => {});
+ }
+ return;
+ }
+
if (!files) {
return;
}
@@ -39,33 +62,30 @@ function FilesPanel({ parentNoteId, closeDialog, setFooter }: ImportProviderPane
replaceUnderscoresWithSpaces: boolToString(replaceUnderscoresWithSpaces)
};
- // Close immediately and let the shared import toasts (registered in import.ts) report progress,
- // completion and any error. Swallow the rejection so this void-ed call doesn't raise an unhandled
- // rejection.
closeDialog();
await importService.uploadFiles("notes", parentNoteId, Array.from(files), options).catch(() => {});
- }, [files, safeImport, shrinkImages, textImportedAsText, codeImportedAsCode, spreadsheetImportedAsSpreadsheet, explodeArchives, replaceUnderscoresWithSpaces, parentNoteId, closeDialog]);
+ }, [files, nativeFiles, safeImport, shrinkImages, textImportedAsText, codeImportedAsCode, spreadsheetImportedAsSpreadsheet, explodeArchives, replaceUnderscoresWithSpaces, parentNoteId, closeDialog]);
- // Desktop only: import a large .zip straight from disk. The OS dialog (in the main process) is the
- // sole source of the path — it returns a single-use capability token, never a path — and the archive
- // is read in place, so a multi-GB import stays memory-bounded (no upload, no temp copy). Other files
- // and drag-drop keep the normal upload route above.
- const doNativeZipImport = useCallback(async () => {
- const pick = await window.electronApi?.nativeImport.pickZipFile();
- if (pick?.status !== "selected" || !pick.token) {
+ // Desktop only: browse via the native OS dialog. The dialog (in the main process) is the sole source of
+ // the path — it returns single-use capability tokens, never paths — and the files are read in place, so
+ // a multi-GB archive stays memory-bounded (no upload, no temp copy). Picking clears any dropped files.
+ const doNativeBrowse = useCallback(async () => {
+ const pick = await window.electronApi?.nativeImport.pickFiles();
+ if (pick?.status !== "selected" || !pick.files?.length) {
return;
}
+ setFiles(null);
+ setNativeFiles(pick.files);
+ }, []);
- const options: NativeImportOptions = {
- safeImport, shrinkImages, textImportedAsText, codeImportedAsCode,
- spreadsheetImportedAsSpreadsheet, explodeArchives, replaceUnderscoresWithSpaces
- };
-
- // Close immediately and let the shared import toasts (registered in import.ts) report progress,
- // completion and any error over the WebSocket, exactly like the upload route.
- closeDialog();
- await window.electronApi?.nativeImport.importFromToken({ token: pick.token, parentNoteId, taskId: utils.randomString(10), options });
- }, [safeImport, shrinkImages, textImportedAsText, codeImportedAsCode, spreadsheetImportedAsSpreadsheet, explodeArchives, replaceUnderscoresWithSpaces, parentNoteId, closeDialog]);
+ // Drag-and-drop (or, off desktop, the in-page picker) goes through the normal upload route; a fresh
+ // selection there clears any native pick so the two never coexist.
+ const onFilesChange = useCallback((list: FileList | null) => {
+ setFiles(list);
+ if (list?.length) {
+ setNativeFiles(null);
+ }
+ }, []);
// Keep the latest import handler in a ref so the footer effect depends only on whether files are
// selected, never on doImport's identity — otherwise re-pushing the footer on every option toggle
@@ -73,24 +93,26 @@ function FilesPanel({ parentNoteId, closeDialog, setFooter }: ImportProviderPane
const doImportRef = useRef(doImport);
doImportRef.current = doImport;
+ const hasSelection = !!files || !!nativeFiles?.length;
useEffect(() => {
setFooter(
- <Button text={t("import.import")} kind="primary" disabled={!files} onClick={() => void doImportRef.current()} />
+ <Button text={t("import.import")} kind="primary" disabled={!hasSelection} onClick={() => void doImportRef.current()} />
);
- }, [files, setFooter]);
+ }, [hasSelection, setFooter]);
return (
<>
<Card heading={t("import.chooseImportFile")}>
<CardSection>
<p className="import-files-description">{t("import.importZipRecommendation")}</p>
- <FileDropZone multiple onChange={setFiles} />
- {utils.isElectron() && (
- <div className="import-native-zip">
- <span className="import-native-zip-hint">{t("import.largeZipHint")}</span>
- <Button text={t("import.largeZipButton")} onClick={() => void doNativeZipImport()} />
- </div>
- )}
+ <FileDropZone
+ multiple
+ onChange={onFilesChange}
+ // On desktop, browsing opens the native dialog so the chosen files (zips especially)
+ // are read in place. Drag-and-drop still uses the upload route via onChange.
+ onBrowse={utils.isElectron() ? () => void doNativeBrowse() : undefined}
+ displayNames={nativeFiles?.map((file) => file.fileName)}
+ />
</CardSection>
</Card>
diff --git a/apps/client/src/widgets/dialogs/import/import_dialog.css b/apps/client/src/widgets/dialogs/import/import_dialog.css
index f69aeade7d..3ffbdf50d6 100644
--- a/apps/client/src/widgets/dialogs/import/import_dialog.css
+++ b/apps/client/src/widgets/dialogs/import/import_dialog.css
@@ -23,22 +23,6 @@
color: var(--muted-text-color);
}
- /* Desktop-only fast path for large .zip imports, shown beneath the drop zone. */
- .import-native-zip {
- display: flex;
- align-items: center;
- justify-content: space-between;
- gap: 1em;
- margin-top: 0.75em;
- padding-top: 0.75em;
- border-top: 1px solid var(--main-border-color);
- }
-
- .import-native-zip-hint {
- color: var(--muted-text-color);
- font-size: 0.9em;
- }
-
/* Collapsed-by-default options: the section header toggles the option rows below. */
.import-options-toggle {
display: flex;
diff --git a/apps/client/src/widgets/react/FileDropZone.tsx b/apps/client/src/widgets/react/FileDropZone.tsx
index eab8bd2241..ad4c9e308c 100644
--- a/apps/client/src/widgets/react/FileDropZone.tsx
+++ b/apps/client/src/widgets/react/FileDropZone.tsx
@@ -11,6 +11,16 @@ export interface FileDropZoneProps {
multiple?: boolean;
/** Optional `accept` attribute forwarded to the underlying file input (e.g. `".zip"`). */
accept?: string;
+ /**
+ * Overrides the click-to-browse action (e.g. open a native OS dialog on desktop instead of the
+ * in-page file input). Drag-and-drop still goes through `onChange`.
+ */
+ onBrowse?: () => void;
+ /**
+ * Externally-controlled selection to display in place of the internal one — e.g. native picks whose
+ * filenames are known but which aren't `File` objects. When non-empty it wins; dropping files clears it.
+ */
+ displayNames?: string[];
}
/**
@@ -18,7 +28,7 @@ export interface FileDropZoneProps {
* picker. Selected files are listed inside. Drop-in replacement for {@link FormFileUpload} — same
* `onChange(files)` / `multiple` contract.
*/
-export default function FileDropZone({ name, onChange, multiple, accept }: FileDropZoneProps) {
+export default function FileDropZone({ name, onChange, multiple, accept, onBrowse, displayNames }: FileDropZoneProps) {
const inputRef = useRef<HTMLInputElement>(null);
const [files, setFiles] = useState<File[]>([]);
const [dragging, setDragging] = useState(false);
@@ -29,6 +39,13 @@ export default function FileDropZone({ name, onChange, multiple, accept }: FileD
// Reset any stale selection carried over from a previous mount of this widget.
useEffect(() => { onChange(null); }, []);
+ // An external selection wins, so drop the internal list to keep it from lingering underneath.
+ useEffect(() => {
+ if (displayNames?.length) {
+ setFiles([]);
+ }
+ }, [displayNames]);
+
const update = useCallback((list: FileList | null) => {
const selected = list && list.length ? (multiple ? Array.from(list) : [list[0]]) : [];
setFiles(selected);
@@ -58,9 +75,15 @@ export default function FileDropZone({ name, onChange, multiple, accept }: FileD
}
}, [update]);
+ // An external (native) selection takes precedence over whatever the in-page input/drop produced.
+ const selectedNames = displayNames?.length ? displayNames : files.map((file) => file.name);
+
return (
<label
- className={`file-drop-zone ${dragging ? "dragging" : ""} ${files.length ? "has-files" : ""}`}
+ className={`file-drop-zone ${dragging ? "dragging" : ""} ${selectedNames.length ? "has-files" : ""}`}
+ // When the caller overrides browsing (desktop native dialog), stop the label from opening the
+ // in-page file input and call the override instead. Drag-and-drop is unaffected.
+ onClick={onBrowse ? (e) => { e.preventDefault(); onBrowse(); } : undefined}
onDragEnter={onDragEnter}
onDragOver={(e) => e.preventDefault()}
onDragLeave={onDragLeave}
@@ -75,12 +98,12 @@ export default function FileDropZone({ name, onChange, multiple, accept }: FileD
accept={accept}
onChange={(e) => update((e.target as HTMLInputElement).files)}
/>
- {files.length ? (
+ {selectedNames.length ? (
<div className="file-drop-zone-selection">
- {files.length > 1 && <div className="file-drop-zone-count">{t("file_upload.selected", { count: files.length })}</div>}
+ {selectedNames.length > 1 && <div className="file-drop-zone-count">{t("file_upload.selected", { count: selectedNames.length })}</div>}
<ul className="file-drop-zone-files">
- {files.map((file, index) => (
- <li key={index}><span className="bx bx-file-blank" /> <span className="file-drop-zone-filename">{file.name}</span></li>
+ {selectedNames.map((fileName, index) => (
+ <li key={index}><span className="bx bx-file-blank" /> <span className="file-drop-zone-filename">{fileName}</span></li>
))}
</ul>
</div>
diff --git a/apps/desktop/src/preload.spec.ts b/apps/desktop/src/preload.spec.ts
index 0680de930f..b2d0af6ea1 100644
--- a/apps/desktop/src/preload.spec.ts
+++ b/apps/desktop/src/preload.spec.ts
@@ -627,13 +627,13 @@ describe("preload script", () => {
describe("nativeImport", () => {
const nativeImport = () => getGroup("nativeImport");
- it("pickZipFile invokes the open-dialog IPC channel with no path argument", async () => {
- await nativeImport().pickZipFile();
- expect(ipcRendererInvoked).toContainEqual({ channel: "import-pick-zip", args: [] });
+ it("pickFiles invokes the open-dialog IPC channel with no path argument", async () => {
+ await nativeImport().pickFiles();
+ expect(ipcRendererInvoked).toContainEqual({ channel: "import-pick-files", args: [] });
});
it("importFromToken forwards the token + options (never a path) to its IPC channel", async () => {
- const opts = { token: "tok-1", parentNoteId: "p1", taskId: "task1", options: { explodeArchives: true } };
+ const opts = { token: "tok-1", parentNoteId: "p1", taskId: "task1", options: { explodeArchives: true }, last: true };
await nativeImport().importFromToken(opts);
expect(ipcRendererInvoked).toContainEqual({ channel: "import-from-token", args: [opts] });
});
diff --git a/apps/desktop/src/preload.ts b/apps/desktop/src/preload.ts
index a8a4087def..ed4260de3c 100644
--- a/apps/desktop/src/preload.ts
+++ b/apps/desktop/src/preload.ts
@@ -211,10 +211,10 @@ contextBridge.exposeInMainWorld("electronApi", {
},
nativeImport: {
- pickZipFile() {
- return ipcRenderer.invoke("import-pick-zip");
+ pickFiles() {
+ return ipcRenderer.invoke("import-pick-files");
},
- importFromToken(opts: { token: string; parentNoteId: string; taskId: string; options: NativeImportOptions }) {
+ importFromToken(opts: { token: string; parentNoteId: string; taskId: string; options: NativeImportOptions; last: boolean }) {
return ipcRenderer.invoke("import-from-token", opts);
}
},
diff --git a/apps/desktop/src/services/import.spec.ts b/apps/desktop/src/services/import.spec.ts
index 006484aa10..991d0b8e98 100644
--- a/apps/desktop/src/services/import.spec.ts
+++ b/apps/desktop/src/services/import.spec.ts
@@ -18,9 +18,13 @@ vi.mock("electron", () => ({
vi.mock("i18next", () => ({ t: (key: string) => key }));
-// --- core mock: stub the import pipeline so we can assert what the handler calls ---
+// --- fs mock: the handler reads non-zip files into a buffer; zips are read in place (no readFile) ---
+const fsMock = vi.hoisted(() => ({ readFile: vi.fn<(...args: unknown[]) => Promise<Buffer>>(async () => Buffer.from("data")) }));
+vi.mock("fs/promises", () => ({ readFile: fsMock.readFile }));
+
+// --- core mock: stub the dispatch pipeline so we can assert what the handler calls ---
const coreMock = vi.hoisted(() => ({
- importZip: vi.fn<(...args: unknown[]) => Promise<{ noteId: string }>>(),
+ dispatch: vi.fn<(...args: unknown[]) => Promise<unknown>>(),
getNoteOrThrow: vi.fn((id: string) => ({ noteId: id })),
taskSucceeded: vi.fn(),
reportError: vi.fn(),
@@ -42,7 +46,7 @@ vi.mock("@triliumnext/core", () => ({
randomString: () => `tok-${coreMock.tokenCounter++}`,
safeExtractMessageAndStackFromError: (e: unknown) => String(e)
},
- zipImportService: { importZip: coreMock.importZip }
+ importDispatchService: coreMock.dispatch
}));
const { setupImportHandlers } = await import("./import.js");
@@ -53,7 +57,7 @@ const OPTIONS = {
};
function pick() {
- return electronMock.handlers.get("import-pick-zip")?.() as Promise<{ status: string; token?: string; fileName?: string }>;
+ return electronMock.handlers.get("import-pick-files")?.() as Promise<{ status: string; files?: { token: string; fileName: string }[] }>;
}
function importFromToken(opts: object) {
return electronMock.handlers.get("import-from-token")?.({}, opts) as Promise<{ status: string; importedNoteId?: string; message?: string }>;
@@ -64,20 +68,22 @@ describe("desktop native import — capability token", () => {
electronMock.handlers.clear();
vi.clearAllMocks();
coreMock.tokenCounter = 0;
- coreMock.importZip.mockResolvedValue({ noteId: "imported1" });
+ coreMock.dispatch.mockResolvedValue({ noteId: "imported1" });
+ fsMock.readFile.mockResolvedValue(Buffer.from("data"));
electronMock.getFocusedWindow.mockReturnValue({});
setupImportHandlers();
});
- it("pick-zip returns a token + filename (never a path) for the user-chosen file", async () => {
- electronMock.showOpenDialogSync.mockReturnValue(["C:/Users/me/big vault.zip"]);
+ 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"]);
const result = await pick();
expect(result.status).toBe("selected");
- expect(result.token).toBeTruthy();
- expect(result.fileName).toBe("big vault.zip");
- // The renderer is handed a token, not the absolute path.
+ expect(result.files).toHaveLength(2);
+ expect(result.files?.map((f) => f.fileName)).toEqual(["big vault.zip", "notes.md"]);
+ expect(result.files?.every((f) => !!f.token)).toBe(true);
+ // The renderer is handed tokens, not absolute paths.
expect(JSON.stringify(result)).not.toContain("C:/Users/me");
});
@@ -85,50 +91,105 @@ describe("desktop native import — capability token", () => {
electronMock.showOpenDialogSync.mockReturnValue(undefined);
expect(await pick()).toEqual({ status: "cancelled" });
- expect(coreMock.importZip).not.toHaveBeenCalled();
+ expect(coreMock.dispatch).not.toHaveBeenCalled();
+ });
+
+ 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"]);
+ const { files } = await pick();
+ const token = files?.[0].token;
+
+ const result = await importFromToken({ token, parentNoteId: "parent1", taskId: "task1", options: OPTIONS, last: true });
+
+ expect(result).toEqual({ status: "imported", importedNoteId: "imported1" });
+ expect(coreMock.getNoteOrThrow).toHaveBeenCalledWith("parent1");
+ // A zip is streamed from disk: the file carries its path, an empty buffer, and isn't read here.
+ const [, file, parentNote] = coreMock.dispatch.mock.calls[0];
+ expect(file).toMatchObject({ originalname: "big.zip", path: "/data/big.zip" });
+ expect((file as { buffer: Buffer }).buffer.length).toBe(0);
+ expect(fsMock.readFile).not.toHaveBeenCalled();
+ expect(parentNote).toEqual({ noteId: "parent1" });
+ expect(coreMock.load).toHaveBeenCalled();
+ // Success is reported on a short delay (lets the transaction commit first).
+ await vi.advanceTimersByTimeAsync(1000);
+ expect(coreMock.taskSucceeded).toHaveBeenCalledTimes(1);
+ } finally {
+ vi.useRealTimers();
+ }
});
- it("imports the granted file in place (importZip receives { path }, not bytes)", async () => {
- electronMock.showOpenDialogSync.mockReturnValue(["/data/big.zip"]);
- const { token } = await pick();
+ it("reads a granted non-zip file into a buffer before dispatching", async () => {
+ electronMock.showOpenDialogSync.mockReturnValue(["/data/note.md"]);
+ fsMock.readFile.mockResolvedValue(Buffer.from("# hello"));
+ const { files } = await pick();
- const result = await importFromToken({ token, parentNoteId: "parent1", taskId: "task1", options: OPTIONS });
+ await importFromToken({ token: files?.[0].token, parentNoteId: "p", taskId: "t", options: OPTIONS, last: true });
+
+ expect(fsMock.readFile).toHaveBeenCalledWith("/data/note.md");
+ const [, file] = coreMock.dispatch.mock.calls[0];
+ expect(file).toMatchObject({ originalname: "note.md", path: "/data/note.md" });
+ expect((file as { buffer: Buffer }).buffer.toString()).toBe("# hello");
+ });
- expect(result).toEqual({ status: "imported", importedNoteId: "imported1" });
- expect(coreMock.getNoteOrThrow).toHaveBeenCalledWith("parent1");
- const [, source, parentNote] = coreMock.importZip.mock.calls[0];
- expect(source).toEqual({ path: "/data/big.zip" });
- expect(parentNote).toEqual({ noteId: "parent1" });
- expect(coreMock.load).toHaveBeenCalled();
+ 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"]);
+ const { files } = await pick();
+
+ await importFromToken({ token: files?.[0].token, parentNoteId: "p", taskId: "t", options: OPTIONS, last: false });
+ await vi.advanceTimersByTimeAsync(1000);
+ expect(coreMock.taskSucceeded).not.toHaveBeenCalled();
+
+ await importFromToken({ token: files?.[1].token, parentNoteId: "p", taskId: "t", options: OPTIONS, last: true });
+ await vi.advanceTimersByTimeAsync(1000);
+ expect(coreMock.taskSucceeded).toHaveBeenCalledTimes(1);
+ } finally {
+ vi.useRealTimers();
+ }
});
it("rejects an unknown/forged token without importing (a script can't supply a path or guess a token)", async () => {
- const result = await importFromToken({ token: "forged-token", parentNoteId: "parent1", taskId: "t", options: OPTIONS });
+ const result = await importFromToken({ token: "forged-token", parentNoteId: "parent1", taskId: "t", options: OPTIONS, last: true });
expect(result.status).toBe("error");
- expect(coreMock.importZip).not.toHaveBeenCalled();
+ expect(coreMock.dispatch).not.toHaveBeenCalled();
});
it("consumes the token: the same token cannot be redeemed twice (no replay)", async () => {
electronMock.showOpenDialogSync.mockReturnValue(["/data/once.zip"]);
- const { token } = await pick();
+ const { files } = await pick();
+ const token = files?.[0].token;
- const first = await importFromToken({ token, parentNoteId: "p", taskId: "t", options: OPTIONS });
- const second = await importFromToken({ token, parentNoteId: "p", taskId: "t", options: OPTIONS });
+ const first = await importFromToken({ token, parentNoteId: "p", taskId: "t", options: OPTIONS, last: true });
+ const second = await importFromToken({ token, parentNoteId: "p", taskId: "t", options: OPTIONS, last: true });
expect(first.status).toBe("imported");
expect(second.status).toBe("error");
- expect(coreMock.importZip).toHaveBeenCalledTimes(1);
+ expect(coreMock.dispatch).toHaveBeenCalledTimes(1);
});
it("reports a failed import as an error and surfaces it on the task channel", async () => {
electronMock.showOpenDialogSync.mockReturnValue(["/data/bad.zip"]);
- coreMock.importZip.mockRejectedValue(new Error("corrupt archive"));
- const { token } = await pick();
+ coreMock.dispatch.mockRejectedValue(new Error("corrupt archive"));
+ const { files } = await pick();
- const result = await importFromToken({ token, parentNoteId: "p", taskId: "t", options: OPTIONS });
+ const result = await importFromToken({ token: files?.[0].token, parentNoteId: "p", taskId: "t", options: OPTIONS, last: true });
expect(result).toEqual({ status: "error", message: "corrupt archive" });
expect(coreMock.reportError).toHaveBeenCalledWith("corrupt archive");
});
+
+ it("surfaces an OPML structured failure (the [status, message] tuple) as an error", async () => {
+ electronMock.showOpenDialogSync.mockReturnValue(["/data/bad.opml"]);
+ coreMock.dispatch.mockResolvedValue([400, "Unsupported OPML version"]);
+ const { files } = await pick();
+
+ const result = await importFromToken({ token: files?.[0].token, parentNoteId: "p", taskId: "t", options: OPTIONS, last: true });
+
+ expect(result).toEqual({ status: "error", message: "Unsupported OPML version" });
+ expect(coreMock.reportError).toHaveBeenCalledWith("Unsupported OPML version");
+ });
});
diff --git a/apps/desktop/src/services/import.ts b/apps/desktop/src/services/import.ts
index d9b687c517..6ab498efd5 100644
--- a/apps/desktop/src/services/import.ts
+++ b/apps/desktop/src/services/import.ts
@@ -1,45 +1,50 @@
import type { NativeImportOptions, NativeImportPickResult, NativeImportResult } from "@triliumnext/commons";
-import { becca, becca_loader, cls, getLog, TaskContext, utils as coreUtils, zipImportService } from "@triliumnext/core";
+import { becca, becca_loader, cls, type File, getLog, importDispatchService, type ImportOptions, TaskContext, utils as coreUtils } from "@triliumnext/core";
import { default as electron } from "electron";
-import { basename } from "path";
+import { readFile } from "fs/promises";
import { t } from "i18next";
+import { basename, extname } from "path";
interface ImportFromTokenOpts {
token: string;
parentNoteId: string;
taskId: string;
options: NativeImportOptions;
+ /** Set only on the final file of a batch, so the success toast fires once everything is imported. */
+ last: boolean;
}
/**
- * Registers the desktop-native large-`.zip` import IPC handlers.
+ * Registers the desktop-native import IPC handlers (reachable only from the import dialog's "browse" action).
*
* Security model: the renderer **never** supplies a path. The OS dialog runs here in the main process and
- * is the *only* thing that mints an access grant; `import-pick-zip` returns a single-use, short-lived
- * **token** (plus the display filename), and `import-from-token` accepts that token — not a path. So a
- * note script can at most pop the dialog (the user still has to pick a file) and can never read an
- * arbitrary file: it can't forge a valid token, and there's no path parameter to abuse.
+ * is the *only* thing that mints an access grant; `import-pick-files` returns single-use, short-lived
+ * **tokens** (plus display filenames), and `import-from-token` accepts a token — not a path. So a note
+ * script can at most pop the dialog (the user still has to pick a file) and can never read an arbitrary
+ * file: it can't forge a valid token, and there's no path parameter to abuse.
*
- * The chosen file is read **in place** (`zipImportService.importZip({ path })`, streamed per entry), so a
- * multi-GB archive is never copied to a temp file or held in memory — the reason this path exists.
+ * Any importable file is accepted, but the reason this path exists is large `.zip` archives: a zip is read
+ * **in place** (`{ path }`, streamed per entry) so a multi-GB import is never copied to a temp file or held
+ * in memory. Smaller single files are read into a buffer and dispatched exactly like an HTTP upload.
*/
export function setupImportHandlers() {
- electron.ipcMain.handle("import-pick-zip", async (): Promise<NativeImportPickResult> => {
+ electron.ipcMain.handle("import-pick-files", async (): Promise<NativeImportPickResult> => {
const focusedWindow = electron.BrowserWindow.getFocusedWindow();
if (!focusedWindow) {
return { status: "cancelled" };
}
const selection = electron.dialog.showOpenDialogSync(focusedWindow, {
- properties: ["openFile"],
- filters: [{ name: t("import.zip_filter"), extensions: ["zip"] }]
+ properties: ["openFile", "multiSelections"]
});
if (!selection || selection.length === 0) {
return { status: "cancelled" };
}
- const path = selection[0];
- return { status: "selected", token: grantFileAccess(path), fileName: basename(path) };
+ return {
+ status: "selected",
+ files: selection.map((path) => ({ token: grantFileAccess(path), fileName: basename(path) }))
+ };
});
electron.ipcMain.handle("import-from-token", async (_e, opts: ImportFromTokenOpts): Promise<NativeImportResult> => {
@@ -49,11 +54,11 @@ export function setupImportHandlers() {
}
try {
- return { status: "imported", importedNoteId: await runZipImport(path, opts) };
+ return { status: "imported", importedNoteId: await runNativeImport(path, opts) };
} catch (e) {
const message = e instanceof Error ? e.message : String(e);
TaskContext.getInstance(opts.taskId, "importNotes", opts.options).reportError(message);
- getLog().error(`Native zip import failed: ${coreUtils.safeExtractMessageAndStackFromError(e)}`);
+ getLog().error(`Native import failed: ${coreUtils.safeExtractMessageAndStackFromError(e)}`);
return { status: "error", message };
}
});
@@ -80,25 +85,52 @@ function redeemFileAccess(token: string): string | null {
return grant.path;
}
-/** Imports the zip at `path` in place, reporting progress/success over the WebSocket like the HTTP route. */
-async function runZipImport(path: string, opts: ImportFromTokenOpts): Promise<string | undefined> {
+/** Imports the file at `path` in place, reporting progress/success over the WebSocket like the HTTP route. */
+async function runNativeImport(path: string, opts: ImportFromTokenOpts): Promise<string | undefined> {
const parentNote = becca.getNoteOrThrow(opts.parentNoteId);
const taskContext = TaskContext.getInstance(opts.taskId, "importNotes", opts.options);
+ const options = opts.options satisfies ImportOptions;
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 importedNote = await zipImportService.importZip(taskContext, { path }, parentNote);
+
+ const file = await buildImportFile(path, options.explodeArchives);
+ const result = await importDispatchService(taskContext, file, parentNote, options);
// 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();
- return importedNote;
+
+ if (Array.isArray(result)) {
+ // OPML reports a structured failure as a `[httpStatus, message]` array.
+ throw new Error(String(result[1]));
+ }
+ return result;
});
- // Small delay mirrors the route: let the transaction commit before the client reacts to success.
- setTimeout(() => taskContext.taskSucceeded({ parentNoteId: opts.parentNoteId, importedNoteId: note?.noteId }), 1000);
+ // Small delay mirrors the route: let the transaction commit before the client reacts to success. Only
+ // the last file of a batch fires the success toast so it doesn't flash once per file.
+ if (opts.last) {
+ setTimeout(() => taskContext.taskSucceeded({ parentNoteId: opts.parentNoteId, importedNoteId: note?.noteId }), 1000);
+ }
return note?.noteId;
}
+
+/**
+ * Builds the {@link File} the importer expects from a path on disk. A zip that will be exploded is left
+ * unbuffered (an empty buffer + the `path`) so it streams per entry; every other file is small enough to
+ * read into memory here. The MIME is resolved by the importer from the filename, so it's left blank.
+ */
+async function buildImportFile(path: string, explodeArchives: boolean): Promise<File> {
+ const fileName = basename(path);
+ const isExplodableZip = extname(fileName).toLowerCase() === ".zip" && explodeArchives;
+ return {
+ originalname: fileName,
+ mimetype: "",
+ buffer: isExplodableZip ? Buffer.alloc(0) : await readFile(path),
+ path
+ };
+}
diff --git a/apps/server/src/assets/translations/en/server.json b/apps/server/src/assets/translations/en/server.json
index 76e8ed0d9d..0df9671fa5 100644
--- a/apps/server/src/assets/translations/en/server.json
+++ b/apps/server/src/assets/translations/en/server.json
@@ -339,7 +339,6 @@
"zip_filter": "ZIP archive (*.zip)"
},
"import": {
- "zip_filter": "ZIP archive (*.zip)",
"invalid_file_grant": "The file selection has expired or is invalid. Please choose the file again."
},
"pdf": {
diff --git a/packages/commons/src/lib/electron_api_interface.ts b/packages/commons/src/lib/electron_api_interface.ts
index fd67d42659..6dfcd09ab4 100644
--- a/packages/commons/src/lib/electron_api_interface.ts
+++ b/packages/commons/src/lib/electron_api_interface.ts
@@ -543,13 +543,19 @@ export interface NativeImportOptions {
replaceUnderscoresWithSpaces: boolean;
}
-/** Outcome of {@link ElectronNativeImportApi.pickZipFile}: a capability token, never a path. */
+/** A single user-chosen file: a capability token (redeemed to import it) and its display name — never a path. */
+export interface NativeImportPickedFile {
+ /** Single-use, short-lived grant for the chosen file. */
+ token: string;
+ /** Display name of the chosen file. */
+ fileName: string;
+}
+
+/** Outcome of {@link ElectronNativeImportApi.pickFiles}: capability tokens, never paths. */
export interface NativeImportPickResult {
status: "selected" | "cancelled";
- /** Single-use, short-lived grant for the user-chosen file (when `status === "selected"`). */
- token?: string;
- /** Display name of the chosen file (when `status === "selected"`). */
- fileName?: string;
+ /** The user-chosen files (when `status === "selected"`); one or more, since the dialog allows multi-select. */
+ files?: NativeImportPickedFile[];
}
/** Outcome of {@link ElectronNativeImportApi.importFromToken}. */
@@ -562,19 +568,21 @@ export interface NativeImportResult {
}
/**
- * Desktop-native large-`.zip` import that reads the user's file **in place** (bounded memory, no temp
- * copy). The renderer never handles a filesystem path: {@link pickZipFile} runs the OS dialog in the main
- * process and returns an opaque capability token, which {@link importFromToken} redeems. A script can't
- * forge a token or pass a path, so it can never read an arbitrary file.
+ * Desktop-native import that reads the user's file **in place** (bounded memory, no temp copy) — the whole
+ * point being multi-GB `.zip` archives, though any importable file is accepted. The renderer never handles
+ * a filesystem path: {@link pickFiles} runs the OS dialog in the main process and returns opaque capability
+ * tokens, which {@link importFromToken} redeems. A script can't forge a token or pass a path, so it can
+ * never read an arbitrary file.
*/
export interface ElectronNativeImportApi {
- /** Prompts a native "open file" dialog (`.zip`) and returns a single-use token for the chosen file. */
- pickZipFile(): Promise<NativeImportPickResult>;
+ /** Prompts a native "open file" dialog (multi-select, any type) and returns single-use tokens for the chosen files. */
+ pickFiles(): Promise<NativeImportPickResult>;
/**
* Imports the file behind `token` into `parentNoteId`. Progress/success/error are reported over the
- * WebSocket via `taskId`, matching the HTTP import path.
+ * WebSocket via `taskId`, matching the HTTP import path. When importing several files in one batch, set
+ * `last` only on the final call so the success toast fires once, after everything is in.
*/
- importFromToken(opts: { token: string; parentNoteId: string; taskId: string; options: NativeImportOptions }): Promise<NativeImportResult>;
+ importFromToken(opts: { token: string; parentNoteId: string; taskId: string; options: NativeImportOptions; last: boolean }): Promise<NativeImportResult>;
}
/**
diff --git a/packages/trilium-core/src/index.ts b/packages/trilium-core/src/index.ts
index a2a4b3d933..91459f4938 100644
--- a/packages/trilium-core/src/index.ts
+++ b/packages/trilium-core/src/index.ts
@@ -117,6 +117,8 @@ export * as routeHelpers from "./routes/helpers";
export { getZipProvider, type ZipArchive, type ZipProvider } from "./services/zip_provider";
export { default as zipImportService } from "./services/import/zip";
+export { default as importDispatchService, type ImportOptions } from "./services/import/dispatch";
+export type { File } from "./services/import/common";
export { default as zipExportService } from "./services/export/zip";
export { type AdvancedExportOptions, type ZipExportProviderData } from "./services/export/zip/abstract_provider";
export { ZipExportProvider } from "./services/export/zip/abstract_provider";
diff --git a/packages/trilium-core/src/routes/api/import.ts b/packages/trilium-core/src/routes/api/import.ts
index 0e56a8e0d7..5b54f431ca 100644
--- a/packages/trilium-core/src/routes/api/import.ts
+++ b/packages/trilium-core/src/routes/api/import.ts
@@ -9,18 +9,11 @@ import becca_loader from "../../becca/becca_loader.js";
import type BNote from "../../becca/entities/bnote.js";
import { ValidationError } from "../../errors.js";
import * as cls from "../../services/context.js";
-import anytypeImportService from "../../services/import/anytype/importer.js";
-import enexImportService from "../../services/import/enex.js";
-import keepImportService from "../../services/import/keep/importer.js";
-import notionImportService from "../../services/import/notion/importer.js";
-import obsidianImportService from "../../services/import/obsidian/importer.js";
-import opmlImportService from "../../services/import/opml.js";
+import importFile from "../../services/import/dispatch.js";
import singleImportService from "../../services/import/single.js";
-import zipImportService from "../../services/import/zip.js";
import { getLog } from "../../services/log.js";
import TaskContext from "../../services/task_context.js";
import { safeExtractMessageAndStackFromError } from "../../services/utils/index.js";
-import { extname } from "../../services/utils/path.js";
async function importNotesToBranch(req: ImportRequest<{ parentNoteId: string }>) {
const { parentNoteId } = req.params;
@@ -44,8 +37,6 @@ async function importNotesToBranch(req: ImportRequest<{ parentNoteId: string }>)
const parentNote = becca.getNoteOrThrow(parentNoteId);
- const extension = extname(file.originalname).toLowerCase();
-
// running all the event handlers on imported notes (and attributes) is slow
// and may produce unintended consequences
cls.disableEntityEvents();
@@ -58,46 +49,12 @@ async function importNotesToBranch(req: ImportRequest<{ parentNoteId: string }>)
const taskContext = TaskContext.getInstance(taskId, "importNotes", options);
try {
- if (format === "notion" && typeof file.buffer !== "string") {
- // An explicit format always wins over extension sniffing: a Notion export is just a `.zip`,
- // indistinguishable from a Trilium export without inspecting its contents. The Notion import
- // dialog tags the upload, so we route it to the Notion importer rather than the generic zip.
- note = await notionImportService.importNotion(taskContext, file.buffer, parentNote);
- } else if (format === "keep" && typeof file.buffer !== "string") {
- // Like Notion, a Google Keep (Takeout) export is just a `.zip` indistinguishable from a Trilium
- // export by extension alone, so the Keep import dialog tags the upload to route it here.
- note = await keepImportService.importKeep(taskContext, file.buffer, parentNote);
- } else if (format === "anytype" && typeof file.buffer !== "string") {
- // An Anytype JSON export is likewise a plain `.zip`; the Anytype import dialog tags the upload so
- // it routes to the Anytype importer rather than the generic zip importer.
- note = await anytypeImportService.importAnytype(taskContext, file.buffer, parentNote, file.originalname);
- } else if (format === "obsidian" && typeof file.buffer !== "string") {
- // An Obsidian vault is exported as a plain `.zip` of Markdown files, indistinguishable from a
- // Trilium export by extension alone; the Obsidian import dialog tags the upload to route it here.
- note = await obsidianImportService.importObsidian(taskContext, file.buffer, parentNote, file.originalname);
- } else if (extension === ".zip" && options.explodeArchives && typeof file.buffer !== "string") {
- // Prefer reading the archive straight from the uploaded temp file (server disk storage) so a
- // multi-GB zip is streamed per entry — never held in one buffer, and free of fs.readFile's
- // ~2 GiB ceiling. Falls back to the buffer when there's no path (the browser/WASM upload).
- const zipSource = file.path ? { path: file.path } : file.buffer;
- note = await zipImportService.importZip(taskContext, zipSource, parentNote);
- } else if (extension === ".opml" && options.explodeArchives) {
- const importResult = await opmlImportService.importOpml(taskContext, file.buffer, parentNote);
- if (!Array.isArray(importResult)) {
- note = importResult;
- } else {
- return importResult;
- }
- } else if (extension === ".enex" && options.explodeArchives) {
- const importResult = await enexImportService.importEnex(taskContext, file, parentNote);
- if (!Array.isArray(importResult)) {
- note = importResult;
- } else {
- return importResult;
- }
- } else {
- note = await singleImportService.importSingleFile(taskContext, file, parentNote);
+ const importResult = await importFile(taskContext, file, parentNote, options, format);
+ if (Array.isArray(importResult)) {
+ // OPML reports a structured failure as a `[httpStatus, message]` tuple — pass it straight through.
+ return importResult;
}
+ note = importResult;
} catch (e: unknown) {
const [errMessage, errStack] = safeExtractMessageAndStackFromError(e);
console.warn(e);
diff --git a/packages/trilium-core/src/services/import/dispatch.ts b/packages/trilium-core/src/services/import/dispatch.ts
new file mode 100644
index 0000000000..c68391d51b
--- /dev/null
+++ b/packages/trilium-core/src/services/import/dispatch.ts
@@ -0,0 +1,69 @@
+import type BNote from "../../becca/entities/bnote.js";
+import type TaskContext from "../task_context.js";
+import { extname } from "../utils/path.js";
+import anytypeImportService from "./anytype/importer.js";
+import type { File } from "./common.js";
+import enexImportService from "./enex.js";
+import keepImportService from "./keep/importer.js";
+import notionImportService from "./notion/importer.js";
+import obsidianImportService from "./obsidian/importer.js";
+import opmlImportService from "./opml.js";
+import singleImportService from "./single.js";
+import zipImportService from "./zip.js";
+
+export interface ImportOptions {
+ safeImport: boolean;
+ shrinkImages: boolean;
+ textImportedAsText: boolean;
+ codeImportedAsCode: boolean;
+ spreadsheetImportedAsSpreadsheet: boolean;
+ explodeArchives: boolean;
+ replaceUnderscoresWithSpaces: boolean;
+}
+
+/**
+ * Routes a single uploaded or natively-picked file to the appropriate importer, returning the root note
+ * of the import (the note the client activates afterwards). OPML reports a structured failure as a
+ * `[httpStatus, message]` array instead of throwing.
+ *
+ * Shared by the HTTP import route and the desktop native import handler so both resolve a file to an
+ * importer identically. The caller owns the surrounding CLS setup (`disableEntityEvents`,
+ * `ignoreEntityChangeIds`) and the `becca_loader.load()` afterwards.
+ *
+ * A `.zip` is read from `file.path` in place (streamed per entry) when present, falling back to
+ * `file.buffer` for the browser/WASM upload that has no temp file.
+ */
+export default async function importFile(taskContext: TaskContext<"importNotes">, file: File, parentNote: BNote, options: ImportOptions, format?: string): Promise<BNote | (string | number)[] | null> {
+ const extension = extname(file.originalname).toLowerCase();
+
+ if (format === "notion" && typeof file.buffer !== "string") {
+ // An explicit format always wins over extension sniffing: a Notion export is just a `.zip`,
+ // indistinguishable from a Trilium export without inspecting its contents. The Notion import
+ // dialog tags the upload, so we route it to the Notion importer rather than the generic zip.
+ return await notionImportService.importNotion(taskContext, file.buffer, parentNote);
+ } else if (format === "keep" && typeof file.buffer !== "string") {
+ // Like Notion, a Google Keep (Takeout) export is just a `.zip` indistinguishable from a Trilium
+ // export by extension alone, so the Keep import dialog tags the upload to route it here.
+ return await keepImportService.importKeep(taskContext, file.buffer, parentNote);
+ } else if (format === "anytype" && typeof file.buffer !== "string") {
+ // An Anytype JSON export is likewise a plain `.zip`; the Anytype import dialog tags the upload so
+ // it routes to the Anytype importer rather than the generic zip importer.
+ return await anytypeImportService.importAnytype(taskContext, file.buffer, parentNote, file.originalname);
+ } else if (format === "obsidian" && typeof file.buffer !== "string") {
+ // An Obsidian vault is exported as a plain `.zip` of Markdown files, indistinguishable from a
+ // Trilium export by extension alone; the Obsidian import dialog tags the upload to route it here.
+ return await obsidianImportService.importObsidian(taskContext, file.buffer, parentNote, file.originalname);
+ } else if (extension === ".zip" && options.explodeArchives && typeof file.buffer !== "string") {
+ // Prefer reading the archive straight from the temp file (server disk storage / native pick) so a
+ // multi-GB zip is streamed per entry — never held in one buffer, and free of fs.readFile's
+ // ~2 GiB ceiling. Falls back to the buffer when there's no path (the browser/WASM upload).
+ const zipSource = file.path ? { path: file.path } : file.buffer;
+ return await zipImportService.importZip(taskContext, zipSource, parentNote);
+ } else if (extension === ".opml" && options.explodeArchives) {
+ return await opmlImportService.importOpml(taskContext, file.buffer, parentNote);
+ } else if (extension === ".enex" && options.explodeArchives) {
+ return await enexImportService.importEnex(taskContext, file, parentNote);
+ } else {
+ return await singleImportService.importSingleFile(taskContext, file, parentNote);
+ }
+}