Skip to content

Build your personal knowledge base with Trilium Notes

standalone/backup: move the manual backup creation in the setup stage, where the database can stay locked for changes

Adorian Doran6765a8defb1c
diff --git a/apps/client/src/setup.spec.tsx b/apps/client/src/setup.spec.tsx
index 86626373d1..9435f42cea 100644
--- a/apps/client/src/setup.spec.tsx
+++ b/apps/client/src/setup.spec.tsx
@@ -212,10 +212,22 @@ describe("where the wizard opens", () => {
.toBe("existingData");
});
+ it("goes straight to the backup screen, which is the one that replaces nothing", () => {
+ // Unlike a restore, a backup leaves the knowledge base exactly as it is, so the question
+ // about what to do with it would be asking about something that is not happening.
+ expect(initialState({ initialSetup: false, setupTargetScreen: "backup-database" }))
+ .toBe("backupDatabase");
+
+ // Except where there is nothing to back up, which is not a state the app can ask for.
+ expect(initialState({ setupTargetScreen: "backup-database" })).toBe("selectLanguage");
+ });
+
it("resumes an interrupted sync before anything else, since that one cannot wait", () => {
expect(initialState({ syncInProgress: true })).toBe("syncFromServerInProgress");
expect(initialState({ syncInProgress: true, setupTargetScreen: "restore-backup" }))
.toBe("syncFromServerInProgress");
+ expect(initialState({ syncInProgress: true, initialSetup: false, setupTargetScreen: "backup-database" }))
+ .toBe("syncFromServerInProgress");
});
it("ignores a screen it does not know rather than guessing at one", () => {
diff --git a/apps/client/src/setup.tsx b/apps/client/src/setup.tsx
index d4fb7adb4a..3a794b3d6d 100644
--- a/apps/client/src/setup.tsx
+++ b/apps/client/src/setup.tsx
@@ -10,7 +10,8 @@ import logo from "./assets/icon-color.svg?url";
import { getCurrentLanguage, initLocale, t } from "./services/i18n";
import server from "./services/server";
import { isElectron, isMobileApp } from "./services/utils";
-import ExistingData from "./setup_existing";
+import SetupBackupDatabase from "./setup_backup";
+import ExistingData, { keepExistingData } from "./setup_existing";
import RestoreFromBackup from "./setup_restore";
import Admonition, { ExtendedAdmonition } from "./widgets/react/Admonition";
import Button from "./widgets/react/Button";
@@ -41,12 +42,15 @@ async function main() {
document.body.replaceChildren(bodyWrapper);
}
-type State = "existingData" | "selectLanguage" | "firstOptions" | "createNewDocumentOptions" | "createNewDocumentWithDemo" | "createNewDocumentEmpty" | "restoreFromBackup" | "syncFromDesktop" | "syncFromServer" | "syncFromServerInProgress" | "syncFromDesktopInProgress" | "syncFailed";
+type State = "backupDatabase" | "existingData" | "selectLanguage" | "firstOptions" | "createNewDocumentOptions" | "createNewDocumentWithDemo" | "createNewDocumentEmpty" | "restoreFromBackup" | "syncFromDesktop" | "syncFromServer" | "syncFromServerInProgress" | "syncFromDesktopInProgress" | "syncFailed";
-const STATE_ORDER: State[] = ["existingData", "selectLanguage", "firstOptions", "createNewDocumentOptions", "createNewDocumentWithDemo", "createNewDocumentEmpty", "restoreFromBackup", "syncFromDesktop", "syncFromServer", "syncFromServerInProgress", "syncFromDesktopInProgress", "syncFailed"];
+const STATE_ORDER: State[] = ["backupDatabase", "existingData", "selectLanguage", "firstOptions", "createNewDocumentOptions", "createNewDocumentWithDemo", "createNewDocumentEmpty", "restoreFromBackup", "syncFromDesktop", "syncFromServer", "syncFromServerInProgress", "syncFromDesktopInProgress", "syncFailed"];
export function renderState(state: State, setState: (state: State) => void) {
switch (state) {
+ // Leads nowhere by design: the wizard was opened to take a backup of the database it is
+ // sitting on, so the only way out of it is back into that database.
+ case "backupDatabase": return <SetupBackupDatabase onDone={() => void onExistingDataKept()} />;
case "existingData": return (
<ExistingData
onProceed={() => setState(afterExistingData(window.glob))}
@@ -117,6 +121,13 @@ export function initialState(glob: SetupGlob): State {
return "syncFromServerInProgress";
}
+ // Asked for by a running instance that wants its database held still long enough to be copied.
+ // It skips the question below because it answers it: nothing here is being replaced or erased,
+ // and the instance goes back to the same database when the screen is done with.
+ if (glob.setupTargetScreen === "backup-database" && glob.initialSetup === false) {
+ return "backupDatabase";
+ }
+
// Before the language, before the menu: everything past this point replaces or erases what is
// already here, and the user has not been asked about that yet.
if (glob.initialSetup === false) {
@@ -707,6 +718,24 @@ async function allowLanAccessAndRestart() {
}
}
+/**
+ * Leaves setup and opens the database that was behind it all along.
+ *
+ * The way out of the backup screen, which is the one screen that changes nothing: the instance
+ * comes back up on the same database it was asked to hold still. A failure here still ends in a
+ * reload, because the marker that sent the instance to the wizard is consumed at start — so the
+ * next start comes back to the application whatever this call did.
+ */
+async function onExistingDataKept() {
+ try {
+ await keepExistingData();
+ } catch (e) {
+ console.error("Could not leave setup cleanly; restarting anyway.", e);
+ }
+
+ onSetupFinished();
+}
+
function onSetupFinished() {
if (isElectron()) {
// On Electron we need to use the setup route because it handles the closing of the setup window and opening the main app window.
diff --git a/apps/client/src/setup_backup.css b/apps/client/src/setup_backup.css
new file mode 100644
index 0000000000..0bec6fa519
--- /dev/null
+++ b/apps/client/src/setup_backup.css
@@ -0,0 +1,18 @@
+/* The download action with its state under it, centred like the other setup waits. */
+.backup-download {
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ gap: 1em;
+ margin-block: 3em;
+
+ .backup-download-message {
+ display: flex;
+ align-items: center;
+ gap: 0.75em;
+ }
+}
+
+.page.setup-backup-database .setup-backup-note {
+ margin-top: 16px;
+}
diff --git a/apps/client/src/setup_backup.spec.tsx b/apps/client/src/setup_backup.spec.tsx
new file mode 100644
index 0000000000..e9602ed664
--- /dev/null
+++ b/apps/client/src/setup_backup.spec.tsx
@@ -0,0 +1,106 @@
+import { render } from "preact";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+// t() returns the key so assertions are deterministic and not tied to English text.
+vi.mock("./services/i18n", () => ({ t: (key: string) => key }));
+
+const mocks = vi.hoisted(() => ({
+ startBackupDownload: vi.fn(async () => ({ status: "done" }) as { status: string; message?: string })
+}));
+
+vi.mock("./services/backup_download", () => ({
+ backupDownloadFileName: () => "Backup 2026-08-08 10-00-00.tnbackup",
+ isBackupDownloadSupported: () => true,
+ startBackupDownload: mocks.startBackupDownload
+}));
+
+import SetupBackupDatabase from "./setup_backup";
+
+let container: HTMLDivElement;
+const onDone = vi.fn();
+
+/** Preact flushes effects and state through the microtask queue plus a frame. */
+const settle = () => vi.advanceTimersByTimeAsync(50);
+
+function renderScreen() {
+ container = document.createElement("div");
+ document.body.appendChild(container);
+ render(<SetupBackupDatabase onDone={onDone} />, container);
+
+ return container;
+}
+
+function button(label: string): HTMLButtonElement | undefined {
+ return [ ...container.querySelectorAll("button") ]
+ .find((element) => element.textContent?.includes(label));
+}
+
+beforeEach(() => {
+ vi.useFakeTimers();
+ onDone.mockReset();
+ mocks.startBackupDownload.mockReset().mockResolvedValue({ status: "done" });
+});
+
+afterEach(() => {
+ render(null, container);
+ container.remove();
+ vi.useRealTimers();
+});
+
+describe("backing up from the setup screen", () => {
+ it("names the file up front and downloads nothing until asked", async () => {
+ renderScreen();
+ await settle();
+
+ expect(container.textContent).toContain("setup.backup-database");
+ expect(mocks.startBackupDownload).not.toHaveBeenCalled();
+ // Nothing here is destructive, so leaving is available from the start.
+ expect(button("setup.continue")?.disabled).toBe(false);
+ });
+
+ it("downloads on request, and says so while it runs and once it is done", async () => {
+ let finish: (result: { status: string }) => void = () => {};
+ mocks.startBackupDownload.mockImplementation(() => new Promise((resolve) => {
+ finish = resolve;
+ }));
+ renderScreen();
+ await settle();
+
+ button("setup.existing-data-download")?.click();
+ await settle();
+
+ expect(mocks.startBackupDownload).toHaveBeenCalledWith("Backup 2026-08-08 10-00-00.tnbackup");
+ expect(container.textContent).toContain("setup.existing-data-downloading-in-progress");
+ // Leaving mid-stream would abandon the download, so that one moment is held.
+ expect(button("setup.continue")?.disabled).toBe(true);
+
+ finish({ status: "done" });
+ await settle();
+ expect(container.textContent).toContain("setup.existing-data-downloading-done");
+ expect(button("setup.backup-database-finish")?.disabled).toBe(false);
+ });
+
+ it("shows what stopped a failed download, and offers another go", async () => {
+ mocks.startBackupDownload.mockResolvedValue({ status: "failed", message: "the stream broke" });
+ renderScreen();
+ await settle();
+
+ button("setup.existing-data-download")?.click();
+ await settle();
+
+ expect(container.textContent).toContain("the stream broke");
+ expect(button("setup.existing-data-download")?.disabled).toBe(false);
+ // Still not trapped: the way back to the notes stays open through a failure.
+ expect(button("setup.continue")?.disabled).toBe(false);
+ });
+
+ it("hands back to the application when it is done with", async () => {
+ renderScreen();
+ await settle();
+
+ button("setup.continue")?.click();
+ await settle();
+
+ expect(onDone).toHaveBeenCalled();
+ });
+});
diff --git a/apps/client/src/setup_backup.tsx b/apps/client/src/setup_backup.tsx
new file mode 100644
index 0000000000..5fc28846f7
--- /dev/null
+++ b/apps/client/src/setup_backup.tsx
@@ -0,0 +1,126 @@
+import "./setup_backup.css";
+
+import { useMemo, useState } from "preact/hooks";
+
+import { backupDownloadFileName, startBackupDownload } from "./services/backup_download";
+import { t } from "./services/i18n";
+import Admonition from "./widgets/react/Admonition";
+import Button from "./widgets/react/Button";
+import Icon from "./widgets/react/Icon";
+import SetupPage from "./widgets/react/SetupPage";
+
+/**
+ * Backing up by download, which on the standalone platform happens here rather than while the
+ * application runs.
+ *
+ * A backup is streamed off the database page by page and takes minutes on a large one. Nothing may
+ * write to the database in between, or the pages would come from two different versions of it — and
+ * a running Trilium writes constantly. So the application restarts into setup, where the database is
+ * open but nothing is loaded against it: no becca, no sync, no migration. This screen is what it
+ * restarts into, and leaving it puts the application back the way it was.
+ *
+ * @module
+ */
+
+/** Where the download stands, and the one thing that can be done about it. */
+export interface BackupDownload {
+ fileName: string;
+ state: "idle" | "running" | "done" | "failed";
+ /** What stopped it, once `failed`. */
+ error?: string;
+ start: () => void;
+}
+
+/**
+ * Owns a download and the file it is named after, which is fixed when the screen appears rather
+ * than when the button is pressed: the name is shown before the download starts.
+ */
+export function useBackupDownload(): BackupDownload {
+ const fileName = useMemo(() => backupDownloadFileName(new Date()), []);
+ const [ state, setState ] = useState<BackupDownload["state"]>("idle");
+ const [ error, setError ] = useState<string>();
+
+ return {
+ fileName,
+ state,
+ error,
+ start: () => {
+ setState("running");
+ setError(undefined);
+ void startBackupDownload(fileName).then((result) => {
+ setState(result.status === "done" ? "done" : "failed");
+ setError(result.status === "done" ? undefined : result.message);
+ });
+ }
+ };
+}
+
+/**
+ * The download itself: the button that starts it and what became of it.
+ *
+ * Shared by the two screens that offer one, so a backup taken before a restore and a backup taken
+ * for its own sake are the same thing to a user.
+ */
+export function BackupDownloadPanel({ download }: { download: BackupDownload }) {
+ return (
+ <div class="backup-download">
+ <Button
+ text={t("setup.existing-data-download")}
+ icon="bx bx-download"
+ kind="primary"
+ disabled={download.state === "running"}
+ onClick={download.start}
+ />
+
+ {download.state === "running" && (
+ <div class="backup-download-message">
+ <span class="spinner-border" role="status" aria-hidden="true" />
+ <span>{t("setup.existing-data-downloading-in-progress")}</span>
+ </div>
+ )}
+ {download.state === "done" && <span>{t("setup.existing-data-downloading-done")}</span>}
+ {download.state === "failed" && (
+ <Admonition type="warning" className="backup-download-error">
+ {download.error ?? t("setup.existing-data-download-failed")}
+ </Admonition>
+ )}
+ </div>
+ );
+}
+
+/**
+ * The whole of the wizard, when the wizard was opened to take a backup and nothing else.
+ *
+ * Unlike every other screen here, this one leads nowhere: there is no next step, because the
+ * database it was opened over is the one the application is going back to. Continue is available
+ * from the start, so a user who changes their mind is not trapped on a screen that only exists to
+ * offer them something.
+ *
+ * @param onDone leave setup and open the database that was there all along.
+ */
+export default function SetupBackupDatabase({ onDone }: { onDone: () => void }) {
+ const download = useBackupDownload();
+
+ return (
+ <SetupPage
+ className="setup-backup-database top-aligned"
+ title={t("setup.backup-database")}
+ description={t("setup.backup-database-description", { fileName: download.fileName })}
+ illustration={<Icon icon="bx bx-archive-out" className="illustration-icon" />}
+ footer={
+ <Button
+ text={download.state === "done" ? t("setup.backup-database-finish") : t("setup.continue")}
+ kind="primary"
+ disabled={download.state === "running"}
+ onClick={onDone}
+ />
+ }
+ >
+ <BackupDownloadPanel download={download} />
+
+ <Admonition type="note" className="setup-backup-note">
+ {t("setup.backup-database-note")}
+ </Admonition>
+ </SetupPage>
+ );
+}
diff --git a/apps/client/src/setup_existing.css b/apps/client/src/setup_existing.css
index 4a62fa29b8..06ea27c71d 100644
--- a/apps/client/src/setup_existing.css
+++ b/apps/client/src/setup_existing.css
@@ -6,21 +6,6 @@
}
}
-/* The download step: one action with its state under it, centred like the backing-up wait. */
-.page.existing-data-downloading .existing-data-download {
- display: flex;
- flex-direction: column;
- align-items: center;
- gap: 1em;
- margin-block: 3em;
-
- .existing-data-progress-message {
- display: flex;
- align-items: center;
- gap: 0.75em;
- }
-}
-
.page.existing-data .existing-data-choices .tn-card-section {
padding-block: 12px;
}
diff --git a/apps/client/src/setup_existing.tsx b/apps/client/src/setup_existing.tsx
index 5a1d5045f8..ade1dc188f 100644
--- a/apps/client/src/setup_existing.tsx
+++ b/apps/client/src/setup_existing.tsx
@@ -3,11 +3,7 @@ import "./setup_existing.css";
import type { SetupExistingBackup, SetupExistingBackupStatus } from "@triliumnext/commons";
import { useEffect, useState } from "preact/hooks";
-import {
- backupDownloadFileName,
- isBackupDownloadSupported,
- startBackupDownload
-} from "./services/backup_download";
+import { isBackupDownloadSupported } from "./services/backup_download";
import { t } from "./services/i18n";
import open from "./services/open";
import server from "./services/server";
@@ -19,6 +15,7 @@ import FormRadioGroup from "./widgets/react/FormRadioGroup";
import Icon from "./widgets/react/Icon";
import SetupPage from "./widgets/react/SetupPage";
import SlidePages from "./widgets/react/SlidePages";
+import { type BackupDownload, BackupDownloadPanel, useBackupDownload } from "./setup_backup";
/**
* What happens to the knowledge base that was already here.
@@ -46,14 +43,6 @@ const CHOICES: { value: Choice; label: string }[] = [
type Step = "choice" | "backing-up" | "downloading" | "backed-up";
const STEP_ORDER: Step[] = [ "choice", "backing-up", "downloading", "backed-up" ];
-/** Where the standalone platform's backup download stands, as its screen shows it. */
-interface DownloadStatus {
- fileName: string;
- state: "idle" | "running" | "done" | "failed";
- /** What stopped it, shown when `state` is `failed`. */
- error?: string;
-}
-
/**
* The whole question, as one step of the wizard.
*
@@ -67,7 +56,7 @@ interface DownloadStatus {
export default function ExistingData({ onProceed, onKept }: { onProceed: () => void; onKept: () => void }) {
const [ step, setStep ] = useState<Step>("choice");
const [ backup, setBackup ] = useState<SetupExistingBackup | null>(null);
- const [ download, setDownload ] = useState<DownloadStatus | null>(null);
+ const download = useBackupDownload();
const [ error, setError ] = useState<string>();
const [ errorId, setErrorId ] = useState(0);
@@ -93,7 +82,6 @@ export default function ExistingData({ onProceed, onKept }: { onProceed: () => v
// screen comes first and the download starts from its own button, so nothing lands in
// the downloads bar unannounced.
if (isBackupDownloadSupported()) {
- setDownload({ fileName: backupDownloadFileName(new Date()), state: "idle" });
setStep("downloading");
return;
}
@@ -111,18 +99,6 @@ export default function ExistingData({ onProceed, onKept }: { onProceed: () => v
}
}
- async function startDownload() {
- if (!download) {
- return;
- }
-
- setDownload({ ...download, state: "running", error: undefined });
- const result = await startBackupDownload(download.fileName);
- setDownload((current) => current && (result.status === "done"
- ? { ...current, state: "done", error: undefined }
- : { ...current, state: "failed", error: result.message }));
- }
-
async function keep() {
try {
await keepExistingData();
@@ -147,12 +123,9 @@ export default function ExistingData({ onProceed, onKept }: { onProceed: () => v
/>
)}
{shown === "backing-up" && <ExistingDataBackingUp />}
- {shown === "downloading" && download && (
+ {shown === "downloading" && (
<ExistingDataDownloading
- fileName={download.fileName}
- state={download.state}
- error={download.error}
- onDownload={() => void startDownload()}
+ download={download}
onContinue={() => void erase()}
onCancel={() => void keep()}
/>
@@ -323,11 +296,8 @@ const PROGRESS_INTERVAL_MS = 1000;
* been fully produced — the closest thing to "finished" the application can see, with the
* browser's own download UI carrying the transfer itself.
*/
-export function ExistingDataDownloading({ fileName, state, error, onDownload, onContinue, onCancel }: {
- fileName: string;
- state: DownloadStatus["state"];
- error?: string;
- onDownload: () => void;
+export function ExistingDataDownloading({ download, onContinue, onCancel }: {
+ download: BackupDownload;
onContinue: () => void;
onCancel: () => void;
}) {
@@ -335,7 +305,7 @@ export function ExistingDataDownloading({ fileName, state, error, onDownload, on
<SetupPage
className="existing-data-downloading top-aligned"
title={t("setup.existing-data-downloading")}
- description={t("setup.existing-data-downloading-description", { fileName })}
+ description={t("setup.existing-data-downloading-description", { fileName: download.fileName })}
illustration={<Icon icon="bx bx-download" className="illustration-icon" />}
footer={
<>
@@ -343,34 +313,13 @@ export function ExistingDataDownloading({ fileName, state, error, onDownload, on
<Button
text={t("setup.continue")}
kind="primary"
- disabled={state !== "done"}
+ disabled={download.state !== "done"}
onClick={onContinue}
/>
</>
}
>
- <div class="existing-data-download">
- <Button
- text={t("setup.existing-data-download")}
- icon="bx bx-download"
- kind="primary"
- disabled={state === "running"}
- onClick={onDownload}
- />
-
- {state === "running" && (
- <div class="existing-data-progress-message">
- <span class="spinner-border" role="status" aria-hidden="true" />
- <span>{t("setup.existing-data-downloading-in-progress")}</span>
- </div>
- )}
- {state === "done" && <span>{t("setup.existing-data-downloading-done")}</span>}
- {state === "failed" && (
- <Admonition type="warning" className="existing-data-download-error">
- {error ?? t("setup.existing-data-download-failed")}
- </Admonition>
- )}
- </div>
+ <BackupDownloadPanel download={download} />
<Admonition type="caution" className="existing-data-warning">
{t("setup.existing-data-downloading-warning")}
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.json
index d1c5353687..69338f57c2 100644
--- a/apps/client/src/translations/en/translation.json
+++ b/apps/client/src/translations/en/translation.json
@@ -2078,8 +2078,7 @@
"path": "Path",
"database_backed_up_to": "Database has been backed up to {{- backupFilePath}}",
"download_only_summary": "Backups are downloaded straight to your device; nothing is stored in the browser.",
- "download_finished": "The backup was downloaded as {{- fileName}}.",
- "download_failed": "The backup download did not finish.",
+ "restart_for_backup": "Trilium needs to restart to back up your notes. You can go back to them as soon as it's done.\n\nRestart now?",
"no_backup_yet": "no backup yet",
"download": "Download",
"options_title": "Backup options",
@@ -3710,6 +3709,10 @@
"existing-data-downloading-done": "The download has finished.",
"existing-data-download-failed": "The download did not finish.",
"existing-data-downloading-warning": "Once the download has finished and you press Continue, the knowledge base it was taken from is permanently erased. Keep the downloaded file somewhere safe.",
+ "backup-database": "Back up your knowledge base",
+ "backup-database-description": "Your knowledge base will be saved as a download named {{- fileName}}. Your browser shows its progress among your downloads.",
+ "backup-database-note": "Trilium waits here while your backup is saved. When the download has finished, press Continue to go back to your notes.",
+ "backup-database-finish": "Back to my notes",
"existing-data-delete-failed": "The existing knowledge base could not be deleted.",
"existing-data-keep-failed": "The existing knowledge base could not be reopened.",
"restore-from-backup": "Restore from backup",
diff --git a/apps/client/src/widgets/type_widgets/options/backup.status.spec.tsx b/apps/client/src/widgets/type_widgets/options/backup.status.spec.tsx
index 89824e07bb..dc62d798ac 100644
--- a/apps/client/src/widgets/type_widgets/options/backup.status.spec.tsx
+++ b/apps/client/src/widgets/type_widgets/options/backup.status.spec.tsx
@@ -3,7 +3,8 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
const mocks = vi.hoisted(() => ({
bootToSetup: vi.fn(),
- canBootToSetup: vi.fn(() => true)
+ canBootToSetup: vi.fn(() => true),
+ confirm: vi.fn(async () => true)
}));
vi.mock("../../../services/setup_mode", () => ({
@@ -11,6 +12,8 @@ vi.mock("../../../services/setup_mode", () => ({
canBootToSetup: () => mocks.canBootToSetup()
}));
+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")>()),
@@ -18,7 +21,7 @@ vi.mock("../../../services/i18n", async (importOriginal) => ({
}));
// Import AFTER the mocks (vi.mock is hoisted, but the component import must resolve the mocked deps).
-import { BackupStatus } from "./backup";
+import { BackupStatus, StandaloneBackupStatus } from "./backup";
let container: HTMLDivElement | undefined;
@@ -37,6 +40,7 @@ function restoreButton(): HTMLButtonElement | null {
beforeEach(() => {
mocks.bootToSetup.mockReset().mockResolvedValue(undefined);
mocks.canBootToSetup.mockReset().mockReturnValue(true);
+ mocks.confirm.mockReset().mockResolvedValue(true);
});
afterEach(() => {
@@ -66,3 +70,42 @@ describe("restoring a backup from the options", () => {
expect(container?.querySelector("button[name='backup-database-now-button']")).not.toBeNull();
});
});
+
+describe("backing up where a backup is a download (standalone)", () => {
+ function backupNowButton(): HTMLButtonElement | null {
+ return container?.querySelector<HTMLButtonElement>("button[name='backup-database-now-button']") ?? null;
+ }
+
+ /** Lets the click's own promise chain settle, since confirming is asynchronous. */
+ const settle = () => new Promise((resolve) => setTimeout(resolve, 0));
+
+ it("asks before restarting, then goes to the setup screen's backup step", async () => {
+ renderInto(<StandaloneBackupStatus />);
+
+ backupNowButton()?.click();
+ await settle();
+
+ // Asked first: the restart is the surprising part, not the backup.
+ expect(mocks.confirm).toHaveBeenCalledWith("backup.restart_for_backup");
+ expect(mocks.bootToSetup).toHaveBeenCalledWith({ targetScreen: "backup-database" });
+ });
+
+ it("does nothing at all when the restart is declined", async () => {
+ mocks.confirm.mockResolvedValue(false);
+ renderInto(<StandaloneBackupStatus />);
+
+ backupNowButton()?.click();
+ await settle();
+
+ expect(mocks.bootToSetup).not.toHaveBeenCalled();
+ });
+
+ it("offers neither action where the app cannot start itself again", () => {
+ // Both of them restart the application, so neither can be honoured without that.
+ mocks.canBootToSetup.mockReturnValue(false);
+ renderInto(<StandaloneBackupStatus />);
+
+ expect(backupNowButton()).toBeNull();
+ expect(restoreButton()).toBeNull();
+ });
+});
diff --git a/apps/client/src/widgets/type_widgets/options/backup.tsx b/apps/client/src/widgets/type_widgets/options/backup.tsx
index 89004e64b6..412d162280 100644
--- a/apps/client/src/widgets/type_widgets/options/backup.tsx
+++ b/apps/client/src/widgets/type_widgets/options/backup.tsx
@@ -9,11 +9,7 @@ import {
} from "@triliumnext/commons";
import { useCallback, useEffect, useRef, useState } from "preact/hooks";
-import {
- backupDownloadFileName,
- isBackupDownloadSupported,
- startBackupDownload
-} from "../../../services/backup_download";
+import { isBackupDownloadSupported } from "../../../services/backup_download";
import { describeDatabaseFormat } from "../../../services/database_files";
import dialogService from "../../../services/dialog";
import { t } from "../../../services/i18n";
@@ -76,50 +72,52 @@ function StoredBackupSettings() {
* schedule or format to configure, because nothing is ever stored.
*/
function StandaloneBackupSettings() {
- const [downloading, setDownloading] = useState(false);
-
- async function download() {
- setDownloading(true);
- try {
- const fileName = backupDownloadFileName(new Date());
- const result = await startBackupDownload(fileName);
-
- if (result.status === "done") {
- toast.showMessage(t("backup.download_finished", { fileName }), 10000);
- } else if (result.status === "failed") {
- toast.showError(result.message ?? t("backup.download_failed"));
- }
- // A cancelled download needs no telling: the user did it themselves, in the browser.
- } finally {
- setDownloading(false);
+ return <OptionsPageHeader below={<StandaloneBackupStatus />} />;
+}
+
+/**
+ * The whole of what the standalone platform offers: back up, and restore. Both leave this screen
+ * behind, because both need the database held still, which only the setup screen provides.
+ */
+export function StandaloneBackupStatus() {
+ /**
+ * Restarts into the setup screen, where the backup is actually taken.
+ *
+ * A backup is streamed off the live database over minutes, and a page of it read after a write
+ * would not match the pages read before: the copy has to come from a database nothing is
+ * touching. Only setup mode gives that — the database is open, but becca, sync and migrations
+ * are all held back — so the backup is taken there and the instance comes straight back here.
+ */
+ async function backUp() {
+ if (!await dialogService.confirm(t("backup.restart_for_backup"))) {
+ return;
}
+
+ await bootToSetup({ targetScreen: "backup-database" });
}
return (
- <OptionsPageHeader
- below={
- <div className="backup-status">
- <span className="backup-status-summary">{t("backup.download_only_summary")}</span>
+ <div className="backup-status">
+ <span className="backup-status-summary">{t("backup.download_only_summary")}</span>
- {canBootToSetup() && (
- <Button
- name="restore-backup-button"
- text={t("backup.restore_backup")}
- size="micro"
- onClick={() => bootToSetup({ targetScreen: "restore-backup" })}
- />
- )}
+ {canBootToSetup() && (
+ <>
+ <Button
+ name="restore-backup-button"
+ text={t("backup.restore_backup")}
+ size="micro"
+ onClick={() => bootToSetup({ targetScreen: "restore-backup" })}
+ />
<Button
name="backup-database-now-button"
text={t("backup.backup_now")}
size="micro"
- disabled={downloading}
- onClick={() => void download()}
+ onClick={() => void backUp()}
/>
- </div>
- }
- />
+ </>
+ )}
+ </div>
);
}
diff --git a/packages/commons/src/lib/setup_marker.ts b/packages/commons/src/lib/setup_marker.ts
index 4e78b745d6..342feeb819 100644
--- a/packages/commons/src/lib/setup_marker.ts
+++ b/packages/commons/src/lib/setup_marker.ts
@@ -22,7 +22,7 @@ export const SETUP_MARKER_FILE_NAME = "setup.json";
* Named for what the user asked for rather than for the wizard's own state, so the file format does
* not follow the client's internals around. Screens are listed here as they gain a way in.
*/
-export type SetupTargetScreen = "restore-backup";
+export type SetupTargetScreen = "restore-backup" | "backup-database";
/** A backup the setup screen took of the database it is about to replace. */
export interface SetupExistingBackup {
diff --git a/packages/trilium-core/src/services/setup_mode.ts b/packages/trilium-core/src/services/setup_mode.ts
index 476510b613..b1b24c62f1 100644
--- a/packages/trilium-core/src/services/setup_mode.ts
+++ b/packages/trilium-core/src/services/setup_mode.ts
@@ -19,7 +19,7 @@ import { type SetupMarker, type SetupTargetScreen } from "@triliumnext/commons";
*/
/** The screens a marker is allowed to name, which is not every screen the wizard has. */
-const TARGET_SCREENS: readonly SetupTargetScreen[] = [ "restore-backup" ];
+const TARGET_SCREENS: readonly SetupTargetScreen[] = [ "restore-backup", "backup-database" ];
let requested: SetupMarker | null = null;