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
client/options: add a UI to customize the database backup location
Adorian Dorandc58223d16c8
diff --git a/apps/client/src/services/open.spec.ts b/apps/client/src/services/open.spec.tsindex a2d5fbbbc9..99c5404c66 100644--- a/apps/client/src/services/open.spec.ts+++ b/apps/client/src/services/open.spec.ts@@ -4,6 +4,7 @@ import { buildNote } from "../test/easy-froca";import open, { checkType, downloadFileNote, getUrlForDownload, openNoteExternally } from "./open.js";import options from "./options.js";import server from "./server.js";+import toast from "./toast.js";import utils from "./utils.js";const realWindow = window as any;@@ -242,22 +243,30 @@ describe("open service", () => {expect(errSpy).not.toHaveBeenCalled();});- it("logs an error under Electron when openPath returns an error string", async () => {+ it("reports to the user, not only the console, when openPath returns an error string", async () => {const shell = installElectronApi();vi.spyOn(utils, "isElectron").mockReturnValue(true);shell.openPath.mockResolvedValue("ENOENT"); // failureconst errSpy = vi.spyOn(console, "error").mockImplementation(() => {});+ const toastSpy = vi.spyOn(toast, "showError").mockImplementation(() => {});+await open.openDirectory("/bad/dir");- expect(errSpy).toHaveBeenCalledWith("Failed to open directory:", "ENOENT");++ expect(errSpy).toHaveBeenCalledWith("Failed to open directory:", "/bad/dir", "ENOENT");+ expect(toastSpy).toHaveBeenCalled();});- it("catches and logs filesystem errors thrown by openPath", async () => {+ it("reports filesystem errors thrown by openPath the same way", async () => {const shell = installElectronApi();vi.spyOn(utils, "isElectron").mockReturnValue(true);shell.openPath.mockRejectedValue(new Error("boom"));const errSpy = vi.spyOn(console, "error").mockImplementation(() => {});+ const toastSpy = vi.spyOn(toast, "showError").mockImplementation(() => {});+await open.openDirectory("/throws");- expect(errSpy).toHaveBeenCalledWith("Error:", "boom");++ expect(errSpy).toHaveBeenCalledWith("Failed to open directory:", "/throws", "boom");+ expect(toastSpy).toHaveBeenCalled();});});});diff --git a/apps/client/src/services/open.ts b/apps/client/src/services/open.tsindex 3dcaa4aa57..07891052d8 100644--- a/apps/client/src/services/open.ts+++ b/apps/client/src/services/open.ts@@ -1,7 +1,9 @@import Component from "../components/component.js";import FNote from "../entities/fnote.js";+import { t } from "./i18n.js";import options from "./options.js";import server from "./server.js";+import toast from "./toast.js";import utils from "./utils.js";@@ -137,21 +139,29 @@ async function openNoteOnServer(noteId: string) {}async function openDirectory(directory: string) {+ if (!utils.isElectron()) {+ console.error("Not running in an Electron environment.");+ return;+ }+try {- if (utils.isElectron()) {- const res = await window.electronApi?.shell.openPath(directory);- if (res) {- console.error("Failed to open directory:", res);- }- } else {- console.error("Not running in an Electron environment.");+ // Resolves to an empty string once the file manager is up, or to the reason it is not.+ const failure = await window.electronApi?.shell.openPath(directory);+ if (failure) {+ reportDirectoryFailure(directory, failure);}- } catch (err: any) {- // Handle file system errors (e.g. path does not exist or is inaccessible)- console.error("Error:", err.message);+ } catch (e) {+ // File system errors, e.g. the path no longer exists or is inaccessible.+ reportDirectoryFailure(directory, e instanceof Error ? e.message : String(e));}}+/** Reported to the user, not only the console: a silent failure reads as the link doing nothing at all. */+function reportDirectoryFailure(directory: string, reason: string) {+ console.error("Failed to open directory:", directory, reason);+ toast.showError(t("open.directory_failed", { directory, reason }));+}+export default {download,downloadFileNote,diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.jsonindex ea72b8e197..f32f848a6a 100644--- a/apps/client/src/translations/en/translation.json+++ b/apps/client/src/translations/en/translation.json@@ -1990,17 +1990,26 @@"enable_daily_backup": "Daily backup","enable_weekly_backup": "Weekly backup","enable_monthly_backup": "Monthly backup",+ "location_title": "Backup location",+ "saved_in": "Backups are saved in",+ "select_location": "Select location",+ "select_location_desktop_only": "Choosing a backup location is available only in the desktop application.",+ "reset_location": "Reset to default",+ "reset_location_confirmation": "Would you like to reset the database backup location to default?",+ "default_location": "Default location","backup_recommendation": "It's recommended to keep the backup turned on, but this can make application startup slow with large databases and/or slow storage devices.","backup_now": "Backup now","backup_database_now": "Backup database now","existing_backups": "Existing backups",- "backup_location_description": "Backups are stored in {{- backupFolder}}.","date-and-time": "Date & time","path": "Path","database_backed_up_to": "Database has been backed up to {{- backupFilePath}}","no_backup_yet": "no backup yet","download": "Download"},+ "open": {+ "directory_failed": "Could not open {{- directory}}: {{- reason}}"+ },"etapi": {"description": "ETAPI is a REST API used to access Trilium instance programmatically, without UI.","create_token": "Create new ETAPI token",diff --git a/apps/client/src/widgets/dialogs/about.tsx b/apps/client/src/widgets/dialogs/about.tsxindex f9591a5999..e5e9891729 100644--- a/apps/client/src/widgets/dialogs/about.tsx+++ b/apps/client/src/widgets/dialogs/about.tsx@@ -11,10 +11,10 @@ import { Trans } from "react-i18next";import contributors from "../../../../../contributors.json";import { t } from "../../services/i18n.js";-import openService from "../../services/open.js";import server from "../../services/server.js";-import utils, { isStandalone } from "../../services/utils.js";+import { isStandalone } from "../../services/utils.js";import { formatDateTime } from "../../utils/formatters.js";+import DirectoryLink from "../react/DirectoryLink.js";import { useTooltip, useTriliumEvent } from "../react/hooks.jsx";import Modal from "../react/Modal.js";import { PropertySheet, PropertySheetItem } from "../react/PropertySheet.js";@@ -225,14 +225,3 @@ function ContributorListItem({data, onHover}: {data: Contributor, onHover?: Hove</>;}-function DirectoryLink({ directory }: { directory: string}) {- if (utils.isElectron()) {- const onClick = (e: MouseEvent) => {- e.preventDefault();- openService.openDirectory(directory);- };-- return <a className="tn-link selectable-text" href="#" onClick={onClick}>{directory}</a>;- }- return <span className="selectable-text">{directory}</span>;-}diff --git a/apps/client/src/widgets/react/Button.css b/apps/client/src/widgets/react/Button.cssnew file mode 100644index 0000000000..cd8b38bde9--- /dev/null+++ b/apps/client/src/widgets/react/Button.css@@ -0,0 +1,5 @@+/* Takes the button's place in the layout rather than adding a box of its own, but still has one for+ the pointer to reach — a disabled button emits no events for the tooltip to hang off. */+.tn-disabled-reason {+ display: inline-flex;+}diff --git a/apps/client/src/widgets/react/Button.tsx b/apps/client/src/widgets/react/Button.tsxindex 2c7bf45724..04302bd6ae 100644--- a/apps/client/src/widgets/react/Button.tsx+++ b/apps/client/src/widgets/react/Button.tsx@@ -1,9 +1,13 @@+import "./Button.css";++import type { Tooltip } from "bootstrap";import type { ComponentChildren, CSSProperties, RefObject } from "preact";-import { useMemo } from "preact/hooks";+import { useMemo, useRef } from "preact/hooks";import { CommandNames } from "../../components/app_context";import { isDesktop, isMobile } from "../../services/utils";import ActionButton from "./ActionButton";+import { useStaticTooltip } from "./hooks";import Icon from "./Icon";import { renderShortcutKbds } from "./shortcut_kbd";@@ -25,9 +29,11 @@ export interface ButtonProps {style?: CSSProperties;triggerCommand?: CommandNames;title?: string;+ /** Why the button is off, shown on hover while `disabled`. Ignored otherwise. */+ disabledTooltip?: string;}-function Button({ name, buttonRef, className, text, onClick, keyboardShortcut, icon, kind, disabled, size, style, triggerCommand, ...restProps }: ButtonProps) {+function Button({ name, buttonRef, className, text, onClick, keyboardShortcut, icon, kind, disabled, disabledTooltip, size, style, triggerCommand, ...restProps }: ButtonProps) {// Memoize classes array to prevent recreationconst classes = useMemo(() => {const classList: string[] = ["btn"];@@ -67,7 +73,7 @@ function Button({ name, buttonRef, className, text, onClick, keyboardShortcut, ireturn renderShortcutKbds(keyboardShortcut);}, [keyboardShortcut]);- return (+ const button = (<buttonname={name}className={classes}@@ -83,6 +89,27 @@ function Button({ name, buttonRef, className, text, onClick, keyboardShortcut, i{text} {shortcutElements}</button>);++ if (disabled && disabledTooltip) {+ return <DisabledReason reason={disabledTooltip}>{button}</DisabledReason>;+ }++ return button;+}++/**+ * Carries the tooltip for a disabled control. A disabled `<button>` emits no pointer events, so the+ * explanation for why it is off has to hang off a wrapper the pointer can still reach.+ */+function DisabledReason({ reason, children }: { reason: string; children: ComponentChildren }) {+ const ref = useRef<HTMLSpanElement>(null);++ useStaticTooltip(ref, useMemo<Partial<Tooltip.Options>>(() => ({+ title: reason,+ placement: "top"+ }), [reason]));++ return <span ref={ref} class="tn-disabled-reason">{children}</span>;}export function ButtonGroup({ size, className, children }: { size?: "sm" | "lg"; className?: string; children: ComponentChildren }) {diff --git a/apps/client/src/widgets/react/DirectoryLink.tsx b/apps/client/src/widgets/react/DirectoryLink.tsxnew file mode 100644index 0000000000..3ed223e61a--- /dev/null+++ b/apps/client/src/widgets/react/DirectoryLink.tsx@@ -0,0 +1,18 @@+import openService from "../../services/open.js";+import { isElectron } from "../../services/utils.js";++/**+ * A filesystem location, opened in the OS file manager on click. Only the desktop application can+ * open anything, so everywhere else the path is shown as plain (selectable) text.+ */+export default function DirectoryLink({ directory }: { directory: string }) {+ if (isElectron()) {+ const onClick = (e: MouseEvent) => {+ e.preventDefault();+ openService.openDirectory(directory);+ };++ return <a className="tn-link selectable-text" href="#" onClick={onClick}>{directory}</a>;+ }+ return <span className="selectable-text">{directory}</span>;+}diff --git a/apps/client/src/widgets/type_widgets/options/backup.css b/apps/client/src/widgets/type_widgets/options/backup.cssnew file mode 100644index 0000000000..3e39baa2c2--- /dev/null+++ b/apps/client/src/widgets/type_widgets/options/backup.css@@ -0,0 +1,35 @@+.backup-location .tn-card-section {+ display: grid;+ grid-template-columns: auto 1fr auto;+ grid-template-rows: auto auto;+ align-items: center;+ column-gap: 16px;++ .backup-location-icon {+ grid-row: 1 / span 2;+ font-size: 2.2em;+ opacity: .6;+ }++ .backup-location-label {+ grid-column: 2;+ font-size: .85em;+ opacity: .7;+ }++ .backup-location-path {+ grid-column: 2;+ overflow-wrap: anywhere;+ }++ .backup-location-actions {+ display: flex;+ grid-column: 3;+ grid-row: 1 / span 2;+ gap: 8px;++ .btn {+ white-space: nowrap;+ }+ }+}diff --git a/apps/client/src/widgets/type_widgets/options/backup.location.spec.tsx b/apps/client/src/widgets/type_widgets/options/backup.location.spec.tsxnew file mode 100644index 0000000000..efe25f3870--- /dev/null+++ b/apps/client/src/widgets/type_widgets/options/backup.location.spec.tsx@@ -0,0 +1,190 @@+import { render, VNode } from "preact";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++const mocks = vi.hoisted(() => ({+ setCustomDir: vi.fn(),+ confirm: vi.fn<() => Promise<boolean>>(),+ isElectron: vi.fn(() => true),+ customDir: ""+}));++// Partial-mock so sibling components (e.g. `useUniqueName` in OptionsRow) keep their real implementation.+vi.mock("../../react/hooks", async (importOriginal) => ({+ ...(await importOriginal<typeof import("../../react/hooks")>()),+ useTriliumOption: () => [mocks.customDir, mocks.setCustomDir]+}));++vi.mock("../../../services/utils", async (importActual) => ({+ ...(await importActual<typeof import("../../../services/utils")>()),+ isElectron: () => mocks.isElectron()+}));++vi.mock("../../../services/dialog", () => ({ default: { confirm: mocks.confirm } }));++// i18next is never initialized in the client tests, so its `t` returns undefined; echo the key instead.+vi.mock("../../../services/i18n", async (importOriginal) => ({+ ...(await importOriginal<typeof import("../../../services/i18n")>()),+ t: (key: string) => key+}));++// Import AFTER the mocks (vi.mock is hoisted, but the component import must resolve the mocked deps).+import { BackupList, BackupLocation } from "./backup";++const DEFAULT_DIR = "/data/backup";+const CUSTOM_DIR = "/mnt/usb/trilium";++let container: HTMLDivElement | undefined;+const refreshCallback = vi.fn();++function renderInto(vnode: VNode) {+ container = document.createElement("div");+ document.body.appendChild(container);+ render(vnode, container);+ return container;+}++function renderLocation(folderPath = DEFAULT_DIR) {+ return renderInto(<BackupLocation backupFolderPath={folderPath} refreshCallback={refreshCallback} />);+}++function button(name: string) {+ return container?.querySelector<HTMLButtonElement>(`button[name="${name}"]`);+}++function setPickDirectory(pickDirectory: unknown) {+ (window as unknown as { electronApi?: unknown }).electronApi = pickDirectory ? { dialog: { pickDirectory } } : undefined;+}++beforeEach(() => {+ vi.clearAllMocks();+ mocks.customDir = "";+ mocks.isElectron.mockReturnValue(true);+ setPickDirectory(vi.fn(async () => ({ status: "selected", path: CUSTOM_DIR })));+});++function cleanup() {+ if (container) {+ render(null, container);+ container.remove();+ container = undefined;+ }+}++/** Lets the click handler's awaited continuation run, so "nothing happened" is a real assertion. */+function settle() {+ return new Promise((resolve) => setTimeout(resolve, 0));+}++afterEach(cleanup);++describe("BackupLocation", () => {+ it("shows the effective location, offering a reset only once a custom one is in use", () => {+ renderLocation();+ expect(container?.querySelector(".backup-location-path")?.textContent).toBe(DEFAULT_DIR);+ // On the desktop the location opens in the OS file manager, as in the About dialog.+ expect(container?.querySelector(".backup-location-path a.tn-link")).not.toBeNull();+ expect(button("select-backup-location-button")?.disabled).toBe(false);+ expect(button("reset-backup-location-button")).toBeNull();++ cleanup();+ mocks.customDir = CUSTOM_DIR;+ renderLocation(CUSTOM_DIR);+ expect(container?.querySelector(".backup-location-path")?.textContent).toBe(CUSTOM_DIR);+ expect(button("reset-backup-location-button")).not.toBeNull();+ });++ it("disables the picker outside Electron, explaining why", () => {+ mocks.isElectron.mockReturnValue(false);++ renderLocation();++ expect(button("select-backup-location-button")?.disabled).toBe(true);+ // The explanation hangs off a wrapper, since a disabled button emits no pointer events.+ expect(container?.querySelector(".tn-disabled-reason button")).not.toBeNull();+ // Nothing can open a file manager here, so the location stays plain text.+ expect(container?.querySelector(".backup-location-path a")).toBeNull();+ expect(container?.querySelector(".backup-location-path")?.textContent).toBe(DEFAULT_DIR);+ });++ it("stores the chosen directory and refreshes, opening the picker at the current location", async () => {+ const pickDirectory = vi.fn(async () => ({ status: "selected", path: CUSTOM_DIR }));+ setPickDirectory(pickDirectory);++ renderLocation();+ button("select-backup-location-button")?.click();++ expect(pickDirectory).toHaveBeenCalledWith({ defaultPath: DEFAULT_DIR });+ await vi.waitFor(() => expect(mocks.setCustomDir).toHaveBeenCalledWith(CUSTOM_DIR));+ await vi.waitFor(() => expect(refreshCallback).toHaveBeenCalled());+ });++ it("leaves the option alone when the picker is dismissed", async () => {+ const pickDirectory = vi.fn(async () => ({ status: "cancelled" }));+ setPickDirectory(pickDirectory);++ renderLocation();+ button("select-backup-location-button")?.click();+ await settle();++ expect(pickDirectory).toHaveBeenCalled();+ expect(mocks.setCustomDir).not.toHaveBeenCalled();+ expect(refreshCallback).not.toHaveBeenCalled();+ });++ it("clears the option on a confirmed reset, and only then", async () => {+ mocks.customDir = CUSTOM_DIR;+ mocks.confirm.mockResolvedValue(false);++ renderLocation(CUSTOM_DIR);+ button("reset-backup-location-button")?.click();+ await settle();++ expect(mocks.confirm).toHaveBeenCalled();+ expect(mocks.setCustomDir).not.toHaveBeenCalled();++ mocks.confirm.mockResolvedValue(true);+ button("reset-backup-location-button")?.click();+ await vi.waitFor(() => expect(mocks.setCustomDir).toHaveBeenCalledWith(""));+ await vi.waitFor(() => expect(refreshCallback).toHaveBeenCalled());+ });+});++describe("BackupList: telling the two locations apart", () => {+ const backup = (filePath: string) => ({ fileName: filePath.split(/[/\\]/).pop() ?? "", filePath, mtime: new Date(0), fileSize: 1 });++ function renderList(folderPath: string, files: string[]) {+ return renderInto(+ <BackupList+ backups={files.map(backup)}+ backupFolderPath={folderPath}+ refreshCallback={refreshCallback}+ />+ );+ }++ function badges() {+ return [...(container?.querySelectorAll(".database-file-badge") ?? [])].map((el) => el.textContent);+ }++ it("badges only the backups left outside a custom location", () => {+ mocks.customDir = CUSTOM_DIR;++ renderList(CUSTOM_DIR, [`${CUSTOM_DIR}/backup-daily.db`, `${DEFAULT_DIR}/backup-weekly.db`]);++ expect(badges()).toEqual(["backup.default_location"]);+ });++ it("badges nothing while the default location is the one in use", () => {+ renderList(DEFAULT_DIR, [`${DEFAULT_DIR}/backup-daily.db`, `${DEFAULT_DIR}/backup-weekly.db`]);++ expect(badges()).toEqual([]);+ });++ it("does not mistake a sibling directory sharing the location's name for the location itself", () => {+ mocks.customDir = CUSTOM_DIR;++ renderList(CUSTOM_DIR, [`${CUSTOM_DIR}-old/backup-daily.db`]);++ expect(badges()).toEqual(["backup.default_location"]);+ });+});diff --git a/apps/client/src/widgets/type_widgets/options/backup.tsx b/apps/client/src/widgets/type_widgets/options/backup.tsxindex 53a99030ba..f6af73f91e 100644--- a/apps/client/src/widgets/type_widgets/options/backup.tsx+++ b/apps/client/src/widgets/type_widgets/options/backup.tsx@@ -1,12 +1,19 @@+import "./backup.css";+import { BackupDatabaseNowResponse, DatabaseBackup, ExistingBackupsResponse } from "@triliumnext/commons";import { useCallback, useEffect, useState } from "preact/hooks";+import dialogService from "../../../services/dialog";import { t } from "../../../services/i18n";import server from "../../../services/server";import toast from "../../../services/toast";+import { isElectron } from "../../../services/utils";import Button from "../../react/Button";-import { useTriliumOptionBool } from "../../react/hooks";-import DatabaseFileList from "./components/DatabaseFileList";+import { Card, CardSection } from "../../react/Card";+import DirectoryLink from "../../react/DirectoryLink";+import { useTriliumOption, useTriliumOptionBool } from "../../react/hooks";+import Icon from "../../react/Icon";+import DatabaseFileList, { type DatabaseFile } from "./components/DatabaseFileList";import OptionsPageHeader from "./components/OptionsPageHeader";import OptionsRow, { OptionsRowWithToggle } from "./components/OptionsRow";import OptionsSection from "./components/OptionsSection";@@ -28,6 +35,8 @@ export default function BackupSettings() {<><OptionsPageHeader /><BackupConfiguration />+ {/* Absent where there is no user-accessible location at all, e.g. backups kept in OPFS. */}+ {backupFolderPath && <BackupLocation backupFolderPath={backupFolderPath} refreshCallback={refreshBackups} />}<BackupList backups={backups} backupFolderPath={backupFolderPath} refreshCallback={refreshBackups} /></>);@@ -67,14 +76,85 @@ export function BackupConfiguration() {);}+/**+ * Where the backups go. The location can only be moved on the desktop application, which is the only+ * one with a directory picker to offer; a server is pointed elsewhere through `TRILIUM_BACKUP_DIR`.+ */+export function BackupLocation({ backupFolderPath, refreshCallback }: { backupFolderPath: string; refreshCallback: () => void }) {+ const [customDir, setCustomDir] = useTriliumOption("customDbBackupDir");+ const canSelect = isElectron();++ async function selectLocation() {+ const result = await window.electronApi?.dialog.pickDirectory({ defaultPath: backupFolderPath });+ if (result?.status !== "selected" || !result.path) {+ return;+ }++ await setCustomDir(result.path);+ refreshCallback();+ }++ async function resetToDefault() {+ if (!await dialogService.confirm(t("backup.reset_location_confirmation"))) {+ return;+ }++ await setCustomDir("");+ refreshCallback();+ }++ return (+ <div className="options-section backup-location">+ <Card heading={t("backup.location_title")}>+ <CardSection>+ <Icon icon="bx bx-folder" className="backup-location-icon" />++ <div className="backup-location-label">{t("backup.saved_in")}</div>+ <div className="backup-location-path"><DirectoryLink directory={backupFolderPath} /></div>++ <div className="backup-location-actions">+ <Button+ name="select-backup-location-button"+ text={t("backup.select_location")}+ size="micro"+ disabled={!canSelect}+ disabledTooltip={t("backup.select_location_desktop_only")}+ onClick={selectLocation}+ />++ {customDir && (+ <Button+ name="reset-backup-location-button"+ text={t("backup.reset_location")}+ size="micro"+ onClick={resetToDefault}+ />+ )}+ </div>+ </CardSection>+ </Card>+ </div>+ );+}+export function BackupList({ backups, backupFolderPath, refreshCallback }: { backups: DatabaseBackup[]; backupFolderPath: string | null; refreshCallback: () => void }) {const [backupInProgress, setBackupInProgress] = useState(false);+ const [customDir] = useTriliumOption("customDbBackupDir");++ // With a custom location in use the list also carries whatever stayed in — or was redirected to —+ // the default one, and a row shows only a file name, so those need telling apart.+ const fileBadge = useCallback((file: DatabaseFile) => (+ customDir && backupFolderPath && !isInsideDirectory(backupFolderPath, file.filePath)+ ? t("backup.default_location")+ : undefined+ ), [customDir, backupFolderPath]);return (+ // Where the backups live is stated by the "Backup location" card above, not repeated here.<DatabaseFileListtitle={t("backup.existing_backups")}- locationDescription={backupFolderPath && t("backup.backup_location_description", { backupFolder: backupFolderPath })}files={backups}+ fileBadge={fileBadge}downloadEndpoint="api/database/backup/download"rowName="existing-backup"downloadText={t("backup.download")}@@ -102,3 +182,10 @@ export function BackupList({ backups, backupFolderPath, refreshCallback }: { bac</DatabaseFileList>);}++/** Both paths come already resolved from the server, so a prefix test settles containment on either platform. */+function isInsideDirectory(directory: string, filePath: string) {+ const rest = filePath.slice(directory.length);++ return filePath.startsWith(directory) && (rest.startsWith("/") || rest.startsWith("\\"));+}diff --git a/apps/client/src/widgets/type_widgets/options/components/DatabaseFileList.css b/apps/client/src/widgets/type_widgets/options/components/DatabaseFileList.cssnew file mode 100644index 0000000000..b7578d15d5--- /dev/null+++ b/apps/client/src/widgets/type_widgets/options/components/DatabaseFileList.css@@ -0,0 +1,10 @@+.database-file-label {+ display: flex;+ align-items: center;+ gap: 8px;+}++.database-file-badge {+ --color: var(--muted-text-color);+ flex-shrink: 0;+}diff --git a/apps/client/src/widgets/type_widgets/options/components/DatabaseFileList.tsx b/apps/client/src/widgets/type_widgets/options/components/DatabaseFileList.tsxindex 1e7236c266..c34acbb146 100644--- a/apps/client/src/widgets/type_widgets/options/components/DatabaseFileList.tsx+++ b/apps/client/src/widgets/type_widgets/options/components/DatabaseFileList.tsx@@ -1,3 +1,5 @@+import "./DatabaseFileList.css";+import { ComponentChildren } from "preact";import { useMemo } from "preact/hooks";@@ -5,6 +7,7 @@ import open from "../../../../services/open";import { formatSize } from "../../../../services/utils";import { formatDateTime } from "../../../../utils/formatters";import ActionButton from "../../../react/ActionButton";+import { Badge } from "../../../react/Badge";import NoItems from "../../../react/NoItems";import OptionsRow from "./OptionsRow";import OptionsSection from "./OptionsSection";@@ -29,11 +32,13 @@ interface DatabaseFileListProps {downloadText: string;emptyIcon: string;emptyText: string;+ /** Labels individual files, for the ones that need telling apart — e.g. one kept somewhere else. */+ fileBadge?: (file: DatabaseFile) => string | undefined;/** Extra content rendered below the list (e.g. an action button). */children?: ComponentChildren;}-export default function DatabaseFileList({ title, locationDescription, files, downloadEndpoint, rowName, downloadText, emptyIcon, emptyText, children }: DatabaseFileListProps) {+export default function DatabaseFileList({ title, locationDescription, files, downloadEndpoint, rowName, downloadText, emptyIcon, emptyText, fileBadge, children }: DatabaseFileListProps) {const sortedFiles = useMemo(() => [...files].sort((a, b) => {if (a.mtime < b.mtime) return 1;if (a.mtime > b.mtime) return -1;@@ -48,17 +53,22 @@ export default function DatabaseFileList({ title, locationDescription, files, do)}>{sortedFiles.length > 0 ? (- sortedFiles.map(({ fileName, filePath, mtime, fileSize }) => (+ sortedFiles.map((file) => (<OptionsRow- key={filePath}+ key={file.filePath}name={rowName}- label={<span className="selectable-text">{fileName}</span>}- description={`${mtime ? formatDateTime(mtime) : "-"} • ${formatSize(fileSize)}`}+ label={+ <span className="database-file-label">+ <span className="selectable-text">{file.fileName}</span>+ {fileBadge?.(file) && <Badge className="database-file-badge" text={fileBadge(file)} outline />}+ </span>+ }+ description={`${file.mtime ? formatDateTime(file.mtime) : "-"} • ${formatSize(file.fileSize)}`}><ActionButtonicon="bx bx-download"text={downloadText}- onClick={() => open.download(open.getUrlForDownload(`${downloadEndpoint}?filePath=${encodeURIComponent(filePath)}`))}+ onClick={() => open.download(open.getUrlForDownload(`${downloadEndpoint}?filePath=${encodeURIComponent(file.filePath)}`))}/></OptionsRow>))diff --git a/apps/desktop/src/main.ts b/apps/desktop/src/main.tsindex e7a22e583e..eeaa222a2b 100644--- a/apps/desktop/src/main.ts+++ b/apps/desktop/src/main.ts@@ -29,6 +29,7 @@ import { registerTriliumAppScheme, setupTriliumAppProtocol } from "./protocol";import { applyLaunchOnStartup, setupAutoLaunch, wasLaunchedHidden } from "./services/auto_launch";import { setupCustomDictionary } from "./services/custom_dictionary";import { setupReferer } from "./services/referer";+import { setupDialogHandlers } from "./services/dialog";import { setupExportHandlers } from "./services/export";import { setupImportHandlers } from "./services/import";import { setupOneNoteHandlers } from "./services/onenote";@@ -129,6 +130,7 @@ export async function main() {setupPrintingHandlers();setupExportHandlers();setupImportHandlers();+ setupDialogHandlers();registerSecurityIpcHandlers();setupStartupMetricsIpc();diff --git a/apps/desktop/src/preload.spec.ts b/apps/desktop/src/preload.spec.tsindex ffe0651443..4d6f305f2a 100644--- a/apps/desktop/src/preload.spec.ts+++ b/apps/desktop/src/preload.spec.ts@@ -651,4 +651,18 @@ describe("preload script", () => {expect(ipcRendererInvoked).toContainEqual({ channel: "import-grant-dropped", args: [["/data/a.zip"]] });});});++ describe("dialog", () => {+ const dialog = () => getGroup("dialog");++ it("pickDirectory forwards the starting location to its IPC channel", async () => {+ await dialog().pickDirectory({ defaultPath: "/data/backup" });+ expect(ipcRendererInvoked).toContainEqual({ channel: "dialog-pick-directory", args: [{ defaultPath: "/data/backup" }] });+ });++ it("pickDirectory may be called without a starting location", async () => {+ await dialog().pickDirectory();+ expect(ipcRendererInvoked).toContainEqual({ channel: "dialog-pick-directory", args: [undefined] });+ });+ });});diff --git a/apps/desktop/src/preload.ts b/apps/desktop/src/preload.tsindex d82a0d7ef7..d668e1ffbe 100644--- a/apps/desktop/src/preload.ts+++ b/apps/desktop/src/preload.ts@@ -227,6 +227,12 @@ contextBridge.exposeInMainWorld("electronApi", {}},+ dialog: {+ pickDirectory(opts?: { defaultPath?: string }) {+ return ipcRenderer.invoke("dialog-pick-directory", opts);+ }+ },+ws: {// Renderer → main process. Mirror channel name with the server-side// IpcMessagingProvider constants.diff --git a/apps/desktop/src/services/dialog.spec.ts b/apps/desktop/src/services/dialog.spec.tsnew file mode 100644index 0000000000..3f13be8da9--- /dev/null+++ b/apps/desktop/src/services/dialog.spec.ts@@ -0,0 +1,67 @@+import { beforeEach, describe, expect, it, vi } from "vitest";++// --- electron mock: capture the IPC handlers and drive the dialog/window from the test ---+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)),+ showOpenDialog: vi.fn<(...args: unknown[]) => Promise<{ canceled: boolean; filePaths: string[] }>>(),+ getFocusedWindow: vi.fn<() => object | null>(() => ({}))+}));++vi.mock("electron", () => ({+ default: {+ ipcMain: { handle: electronMock.handle },+ dialog: { showOpenDialog: electronMock.showOpenDialog },+ BrowserWindow: { getFocusedWindow: electronMock.getFocusedWindow }+ }+}));++vi.mock("i18next", () => ({ t: (key: string) => key }));++const { setupDialogHandlers } = await import("./dialog.js");++function pickDirectory(opts?: { defaultPath?: string }) {+ return electronMock.handlers.get("dialog-pick-directory")?.({}, opts) as Promise<{ status: string; path?: string }>;+}++describe("desktop native directory picker", () => {+ beforeEach(() => {+ electronMock.handlers.clear();+ vi.clearAllMocks();+ electronMock.getFocusedWindow.mockReturnValue({});+ electronMock.showOpenDialog.mockResolvedValue({ canceled: false, filePaths: ["/data/backup"] });+ setupDialogHandlers();+ });++ it("returns the chosen directory, opening the picker at the given location", async () => {+ expect(await pickDirectory({ defaultPath: "/data/old" })).toEqual({ status: "selected", path: "/data/backup" });++ const [, options] = electronMock.showOpenDialog.mock.calls[0] as [unknown, { defaultPath?: string; properties: string[] }];+ expect(options.defaultPath).toBe("/data/old");+ expect(options.properties).toEqual(["openDirectory", "createDirectory"]);+ });++ it("works without a starting location", async () => {+ expect(await pickDirectory()).toEqual({ status: "selected", path: "/data/backup" });++ const [, options] = electronMock.showOpenDialog.mock.calls[0] as [unknown, { defaultPath?: string }];+ expect(options.defaultPath).toBeUndefined();+ });++ it("reports a cancelled dialog", async () => {+ electronMock.showOpenDialog.mockResolvedValue({ canceled: true, filePaths: [] });+ expect(await pickDirectory()).toEqual({ status: "cancelled" });+ });++ it("reports a cancel when the dialog comes back empty despite not being cancelled", async () => {+ electronMock.showOpenDialog.mockResolvedValue({ canceled: false, filePaths: [] });+ expect(await pickDirectory()).toEqual({ status: "cancelled" });+ });++ it("does not open a picker when there is no window to own it", async () => {+ electronMock.getFocusedWindow.mockReturnValue(null);++ expect(await pickDirectory()).toEqual({ status: "cancelled" });+ expect(electronMock.showOpenDialog).not.toHaveBeenCalled();+ });+});diff --git a/apps/desktop/src/services/dialog.ts b/apps/desktop/src/services/dialog.tsnew file mode 100644index 0000000000..ac6d192011--- /dev/null+++ b/apps/desktop/src/services/dialog.ts@@ -0,0 +1,32 @@+import type { NativeDirectoryPickResult } from "@triliumnext/commons";+import { default as electron } from "electron";+import { t } from "i18next";++/**+ * Registers the native picker IPC handlers.+ *+ * The renderer never supplies the answer: the OS dialog runs here in the main process and a path+ * only comes back once the user has accepted it, so a note script can at most pop the dialog.+ */+export function setupDialogHandlers() {+ electron.ipcMain.handle("dialog-pick-directory", async (_e, opts?: { defaultPath?: string }): Promise<NativeDirectoryPickResult> => {+ const focusedWindow = electron.BrowserWindow.getFocusedWindow();+ if (!focusedWindow) {+ return { status: "cancelled" };+ }++ // 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, {+ title: t("dialog.select_directory"),+ defaultPath: opts?.defaultPath,+ properties: ["openDirectory", "createDirectory"]+ });++ if (canceled || filePaths.length === 0) {+ return { status: "cancelled" };+ }++ return { status: "selected", path: filePaths[0] };+ });+}diff --git a/apps/desktop/src/services/shell.spec.ts b/apps/desktop/src/services/shell.spec.tsindex 00bcb2243e..e567a64152 100644--- a/apps/desktop/src/services/shell.spec.ts+++ b/apps/desktop/src/services/shell.spec.ts@@ -178,6 +178,33 @@ describe("validateOpenPath", () => {expect(validateOpenPath(dataDir, dataDir, tmpDir)).toBe(path.resolve(dataDir));});+ describe("backup directory root", () => {+ let backupDir: string;++ beforeAll(() => {+ backupDir = fs.mkdtempSync(path.join(os.tmpdir(), "trilium-open-path-backup-"));+ fs.writeFileSync(path.join(backupDir, "backup-daily.db"), "");+ });++ afterAll(() => fs.rmSync(backupDir, { recursive: true, force: true }));++ it("accepts a backup directory outside the data directory, and what it holds", () => {+ expect(validateOpenPath(backupDir, dataDir, tmpDir, backupDir)).toBe(path.resolve(backupDir));+ expect(validateOpenPath(path.join(backupDir, "backup-daily.db"), dataDir, tmpDir, backupDir))+ .toBe(path.resolve(backupDir, "backup-daily.db"));+ });++ it("rejects that same directory when it is not the configured one", () => {+ expect(() => validateOpenPath(backupDir, dataDir, tmpDir)).toThrow(/outside data dir/);+ expect(() => validateOpenPath(backupDir, dataDir, tmpDir, null)).toThrow(/outside data dir/);+ });++ it("does not widen the sandbox beyond the backup directory", () => {+ const outside = path.join(backupDir, "..", "elsewhere.txt");+ expect(() => validateOpenPath(outside, dataDir, tmpDir, backupDir)).toThrow(/outside data dir/);+ });+ });+it("accepts files under the data directory", () => {expect(validateOpenPath(dataFile, dataDir, tmpDir)).toBe(path.resolve(dataFile));});diff --git a/apps/desktop/src/services/shell.ts b/apps/desktop/src/services/shell.tsindex 0e702cdc2d..6a7ef23ec4 100644--- a/apps/desktop/src/services/shell.ts+++ b/apps/desktop/src/services/shell.ts@@ -1,5 +1,5 @@import { SHELL_OPEN_EXTERNAL_PROTOCOLS } from "@triliumnext/commons";-import { getLog, utils as coreUtils } from "@triliumnext/core";+import { getBackup, getLog, utils as coreUtils } from "@triliumnext/core";import dataDirs from "@triliumnext/server/src/services/data_dir.js";import { execFile } from "child_process";import electron from "electron";@@ -63,25 +63,31 @@ export function validateOpenCustomPath(filePath: unknown, tmpDir: string): strin//#endregion-//#region open-path — sandbox to Trilium's data dir ∪ tmp dir + existence check+//#region open-path — sandbox to Trilium's data dir ∪ tmp dir ∪ backup dir + existence check/*** Validates a path for the "open-path" IPC channel (Open Note Externally,- * Open Attachment Externally, and the "open data directory" link in the- * About dialog). The legit callers only ever pass server-generated paths- * either inside the tmp dir or equal to the data dir itself.+ * Open Attachment Externally, and the "open data directory" / "open backup+ * directory" links in the About dialog and the backup settings). The legit+ * callers only ever pass server-generated paths either inside the tmp dir or+ * equal to one of the directories themselves.+ *+ * `backupDir` is a root of its own because the user may have moved backups+ * outside the data directory. It is resolved from the app's own configuration+ * rather than taken from the renderer, so the sandbox still bounds the caller.** UNC paths are blocked implicitly — they cannot normalise to a descendant- * of the data/tmp dirs, so the sandbox check rejects them. This closes the+ * of those roots, so the sandbox check rejects them. This closes the* NTLM-hash-leak vector that affects file:// and smb:// URLs.*/-export function validateOpenPath(input: unknown, dataDir: string, tmpDir: string): string {+export function validateOpenPath(input: unknown, dataDir: string, tmpDir: string, backupDir?: string | null): string {if (typeof input !== "string" || input.length === 0 || input.includes("\0")) {throw new Error("open-path: invalid filePath");}+ const roots = backupDir ? [dataDir, tmpDir, backupDir] : [dataDir, tmpDir];const resolved = path.resolve(input);- if (!isUnderOrEquals(resolved, dataDir) && !isUnderOrEquals(resolved, tmpDir)) {+ if (!roots.some((root) => isUnderOrEquals(resolved, root))) {throw new Error(`open-path: refusing path outside data dir: ${resolved}`);}@@ -242,7 +248,7 @@ export function setupShellHandlers() {electron.ipcMain.handle("open-path", (_event, filePath: string) => {try {- const resolved = validateOpenPath(filePath, dataDirs.TRILIUM_DATA_DIR, dataDirs.TMP_DIR);+ const resolved = validateOpenPath(filePath, dataDirs.TRILIUM_DATA_DIR, dataDirs.TMP_DIR, getConfiguredBackupDir());return electron.shell.openPath(resolved);} catch (e) {getLog().error(`open-path failed: ${coreUtils.safeExtractMessageAndStackFromError(e)}`);@@ -327,4 +333,17 @@ export function setupShellHandlers() {});}+/**+ * The directory backups currently go to, which the user may have moved outside the data directory.+ * Read from the backup service rather than accepted from the renderer, so it stays the app's own+ * notion of where backups live. Null before core is initialized, leaving the other roots to apply.+ */+function getConfiguredBackupDir(): string | null {+ try {+ return getBackup().getBackupFolderPath();+ } catch {+ return null;+ }+}+//#endregiondiff --git a/apps/server/src/assets/translations/en/server.json b/apps/server/src/assets/translations/en/server.jsonindex c8280d66ec..d3bacd8508 100644--- a/apps/server/src/assets/translations/en/server.json+++ b/apps/server/src/assets/translations/en/server.json@@ -403,6 +403,9 @@"backup": {"custom_directory_unwritable": "Database backup failed: unable to write to {{- location}}. Backing up to the default location instead."},+ "dialog": {+ "select_directory": "Select folder"+ },"migration": {"old_version": "Direct migration from your current version is not supported. Please upgrade to the latest v0.60.4 first and only then to this version.","error_message": "Error during migration to version {{version}}: {{stack}}",diff --git a/packages/commons/src/lib/electron_api_interface.ts b/packages/commons/src/lib/electron_api_interface.tsindex 770af504f6..613b9e8005 100644--- a/packages/commons/src/lib/electron_api_interface.ts+++ b/packages/commons/src/lib/electron_api_interface.ts@@ -596,6 +596,23 @@ export interface ElectronNativeImportApi {importFromToken(opts: { token: string; parentNoteId: string; taskId: string; options: NativeImportOptions; last: boolean; format?: string }): Promise<NativeImportResult>;}+/** Outcome of {@link ElectronDialogApi.pickDirectory}. */+export interface NativeDirectoryPickResult {+ status: "selected" | "cancelled";+ /** Absolute path of the chosen directory (when `status === "selected"`). */+ path?: string;+}++/** Native OS pickers that hand the renderer a location the user chose themselves. */+export interface ElectronDialogApi {+ /**+ * Prompts a native "select folder" dialog, starting at `defaultPath` when it is given. The renderer+ * cannot supply the answer: a script can at most pop the dialog, which the user still has to accept+ * before any path comes back.+ */+ pickDirectory(opts?: { defaultPath?: string }): Promise<NativeDirectoryPickResult>;+}+/*** The complete surface exposed to the renderer as `window.electronApi` via* `contextBridge`. The renderer must access Electron-only functionality through@@ -634,4 +651,6 @@ export interface ElectronApi {nativeExport: ElectronNativeExportApi;/** Desktop-native large-`.zip` import that reads the user's file in place via a capability token. */nativeImport: ElectronNativeImportApi;+ /** Native OS pickers that hand the renderer a location the user chose themselves. */+ dialog: ElectronDialogApi;}