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
backup import: allow the user to create a backup of the existing data straight from the setup screen before restoring a backup
Adorian Doranb8541ca9554c
diff --git a/apps/client/src/setup.spec.tsx b/apps/client/src/setup.spec.tsxindex 6372b7e9e1..86626373d1 100644--- a/apps/client/src/setup.spec.tsx+++ b/apps/client/src/setup.spec.tsx@@ -206,6 +206,12 @@ describe("where the wizard opens", () => {expect(initialState({ setupTargetScreen: "restore-backup" })).toBe("restoreFromBackup");});+ it("asks about the existing knowledge base before anything else, wherever it was headed", () => {+ expect(initialState({ initialSetup: false })).toBe("existingData");+ expect(initialState({ initialSetup: false, setupTargetScreen: "restore-backup" }))+ .toBe("existingData");+ });+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" }))diff --git a/apps/client/src/setup.tsx b/apps/client/src/setup.tsxindex 49d3711e4a..d4fb7adb4a 100644--- a/apps/client/src/setup.tsx+++ b/apps/client/src/setup.tsx@@ -10,6 +10,7 @@ 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 RestoreFromBackup from "./setup_restore";import Admonition, { ExtendedAdmonition } from "./widgets/react/Admonition";import Button from "./widgets/react/Button";@@ -40,12 +41,18 @@ async function main() {document.body.replaceChildren(bodyWrapper);}-type State = "selectLanguage" | "firstOptions" | "createNewDocumentOptions" | "createNewDocumentWithDemo" | "createNewDocumentEmpty" | "restoreFromBackup" | "syncFromDesktop" | "syncFromServer" | "syncFromServerInProgress" | "syncFromDesktopInProgress" | "syncFailed";+type State = "existingData" | "selectLanguage" | "firstOptions" | "createNewDocumentOptions" | "createNewDocumentWithDemo" | "createNewDocumentEmpty" | "restoreFromBackup" | "syncFromDesktop" | "syncFromServer" | "syncFromServerInProgress" | "syncFromDesktopInProgress" | "syncFailed";-const STATE_ORDER: State[] = ["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"];export function renderState(state: State, setState: (state: State) => void) {switch (state) {+ case "existingData": return (+ <ExistingData+ onProceed={() => setState(afterExistingData(window.glob))}+ onKept={onSetupFinished}+ />+ );case "selectLanguage": return <SelectLanguage setState={setState} />;case "firstOptions": return <SetupOptions setState={setState} />;case "createNewDocumentOptions": return <CreateNewDocumentOptions setState={setState} />;@@ -90,19 +97,43 @@ function App() {);}+/** What the wizard needs to know from the bootstrap to decide where it opens and where it goes next. */+interface SetupGlob {+ syncInProgress?: boolean;+ initialSetup?: boolean;+ setupTargetScreen?: SetupTargetScreen;+}+/*** Where the wizard opens.*- * A first run starts at the language step and works forward. The two exceptions both arrive already- * knowing where they belong: a sync interrupted after it created the schema, and an instance that- * asked to be here through a `setup.json` marker, which is how the app sends a user to a screen that- * needs the database closed.+ * A first run starts at the language step and works forward. Three things come in already knowing+ * better: a sync interrupted after it created the schema, an instance with a knowledge base still+ * behind the wizard, which has to answer for that before anything else, and an instance sent to a+ * particular screen through a `setup.json` marker.*/-export function initialState(glob: { syncInProgress?: boolean; setupTargetScreen?: SetupTargetScreen }): State {+export function initialState(glob: SetupGlob): State {if (glob.syncInProgress) {return "syncFromServerInProgress";}+ // 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) {+ return "existingData";+ }++ return afterExistingData(glob);+}++/**+ * Where the wizard goes once there is nothing left to lose.+ *+ * The same answer a first run gets, which is the point: by the time this is reached the instance has+ * no database, so it is being set up exactly as a new one would be, except that it may have been+ * told which screen the user was heading for.+ */+function afterExistingData(glob: SetupGlob): State {switch (glob.setupTargetScreen) {case "restore-backup": return "restoreFromBackup";// Deliberately not a lookup table: two of the states below create a document the moment theydiff --git a/apps/client/src/setup_existing.css b/apps/client/src/setup_existing.cssnew file mode 100644index 0000000000..f7199d9d2a--- /dev/null+++ b/apps/client/src/setup_existing.css@@ -0,0 +1,62 @@+.page.existing-data,+.page.existing-data-backed-up {+ .existing-data-warning {+ margin-top: 16px;+ }+}++/* The wait while a backup is written, centred under the icon like the restore's own steps. */+.page.existing-data-backing-up .existing-data-progress {+ 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;+ }++ .existing-data-progress-bar {+ display: flex;+ align-items: center;+ gap: 0.75em;+ /* Wide enough to read as a measure of the whole write, never wider than the page. */+ width: min(100%, 27.5em);++ progress {+ flex: 1;+ }++ span {+ min-width: 3em;+ font-variant-numeric: tabular-nums;+ text-align: right;+ opacity: 0.7;+ }+ }+}++.page.existing-data-backed-up .existing-data-facts {+ display: grid;+ grid-template-columns: auto 1fr;+ gap: 8px 16px;+ margin: 0;++ dt {+ color: var(--muted-text-color);+ font-weight: normal;+ }++ dd {+ margin: 0;+ }++ /* A path has no spaces to break at and is shown in full, since it may not be readable anywhere+ else once the database holding the custom backup directory is gone. */+ .existing-data-path {+ overflow-wrap: anywhere;+ }+}diff --git a/apps/client/src/setup_existing.spec.tsx b/apps/client/src/setup_existing.spec.tsxnew file mode 100644index 0000000000..4522454e06--- /dev/null+++ b/apps/client/src/setup_existing.spec.tsx@@ -0,0 +1,197 @@+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 serverMock = vi.hoisted(() => ({+ get: vi.fn(async (url: string): Promise<unknown> =>+ (url === "setup/existing/status" ? { fraction: null } : url === "keyboard-actions" ? [] : {})),+ post: vi.fn(async (_url: string): Promise<unknown> => ({})),+ // The backup runs for minutes, so it asks for a timeout of its own rather than the default one.+ postWithTimeout: vi.fn(async (_url: string, _timeoutMs: number): Promise<unknown> => ({}))+}));+vi.mock("./services/server", () => ({ default: serverMock }));++import ExistingData from "./setup_existing";++const BACKUP = {+ fileName: "Backup 2026-08-07 10-32-21.tnbackup",+ filePath: "/mnt/usb/trilium/Backup 2026-08-07 10-32-21.tnbackup",+ fileSize: 209715200,+ encrypted: false+};++let container: HTMLDivElement;+const onProceed = vi.fn();+const onKept = vi.fn();++function renderScreens() {+ container = document.createElement("div");+ document.body.appendChild(container);+ render(<ExistingData onProceed={onProceed} onKept={onKept} />, container);++ return container;+}++/** Preact flushes effects and state through the microtask queue plus a frame. */+const settle = () => vi.advanceTimersByTimeAsync(50);++function choose(value: string) {+ const radio = container.querySelector<HTMLInputElement>(`input[type=radio][value='${value}']`);+ radio?.click();+ radio?.dispatchEvent(new Event("change", { bubbles: true }));+}++function button(label: string): HTMLButtonElement | undefined {+ return [ ...container.querySelectorAll("button") ]+ .find((element) => element.textContent?.includes(label));+}++beforeEach(() => {+ vi.useFakeTimers();+ onProceed.mockReset();+ onKept.mockReset();+ serverMock.post.mockReset().mockResolvedValue(undefined);+ serverMock.postWithTimeout.mockReset().mockResolvedValue(undefined);+ serverMock.get.mockClear();+});++afterEach(() => {+ render(null, container);+ container.remove();+ vi.useRealTimers();+});++describe("choosing what happens to the existing knowledge base", () => {+ it("will not continue until one of the two has been chosen", async () => {+ renderScreens();+ await settle();++ expect(button("setup.continue")?.disabled).toBe(true);++ choose("back-up");+ await settle();+ expect(button("setup.continue")?.disabled).toBe(false);+ });++ it("warns about erasure only once erasure is what was chosen", async () => {+ renderScreens();+ await settle();++ expect(container.querySelector(".existing-data-warning")).toBeNull();++ choose("delete");+ await settle();+ expect(container.querySelector(".existing-data-warning")?.textContent)+ .toContain("setup.existing-data-delete-warning");++ // Changing one's mind takes the warning away with it.+ choose("back-up");+ await settle();+ expect(container.querySelector(".existing-data-warning")).toBeNull();+ });++ it("erases and moves on when that is the answer", async () => {+ renderScreens();+ await settle();++ choose("delete");+ await settle();+ button("setup.continue")?.click();+ await settle();++ expect(serverMock.post).toHaveBeenCalledWith("setup/existing/delete");+ expect(onProceed).toHaveBeenCalled();+ // Nothing was backed up, since nothing was asked to be.+ expect(serverMock.postWithTimeout).not.toHaveBeenCalled();+ });++ it("leaves everything alone and reopens the database on cancel", async () => {+ renderScreens();+ await settle();++ button("setup.existing-data-cancel")?.click();+ await settle();++ expect(serverMock.post).toHaveBeenCalledWith("setup/existing/keep");+ expect(onKept).toHaveBeenCalled();+ });+});++describe("backing it up first", () => {+ it("says what was written, and erases nothing until that is confirmed", async () => {+ serverMock.postWithTimeout.mockResolvedValue(BACKUP);+ renderScreens();+ await settle();++ choose("back-up");+ await settle();+ button("setup.continue")?.click();+ await settle();++ expect(serverMock.postWithTimeout).toHaveBeenCalledWith("setup/existing/backup", 3600000);+ // The path in full: the option holding a custom backup directory is in the database that is+ // about to go, so this may be the last chance to read it.+ expect(container.textContent).toContain(BACKUP.fileName);+ expect(container.textContent).toContain(BACKUP.filePath);+ expect(container.textContent).toContain("200 MiB");+ expect(serverMock.post).not.toHaveBeenCalledWith("setup/existing/delete");++ button("setup.continue")?.click();+ await settle();+ expect(serverMock.post).toHaveBeenCalledWith("setup/existing/delete");+ expect(onProceed).toHaveBeenCalled();+ });++ it("shows how far along the write is, once the writer has said anything", async () => {+ // The backup answers only when it is finished, so this screen would otherwise show a spinner+ // and nothing else for the minutes a large knowledge base takes.+ let resolveBackup: (value: unknown) => void = () => {};+ serverMock.postWithTimeout.mockImplementation(() => new Promise((resolve) => { resolveBackup = resolve; }));+ serverMock.get.mockResolvedValue({ fraction: 0.42 });+ renderScreens();+ await settle();++ choose("back-up");+ await settle();+ button("setup.continue")?.click();+ await settle();++ await vi.advanceTimersByTimeAsync(1000);+ expect(container.querySelector("progress")?.value).toBeCloseTo(0.42);+ expect(container.textContent).toContain("42%");++ resolveBackup(BACKUP);+ });++ it("says to keep the backup password where the backup needs one", async () => {+ serverMock.postWithTimeout.mockResolvedValue({ ...BACKUP, encrypted: true });+ renderScreens();+ await settle();++ choose("back-up");+ await settle();+ button("setup.continue")?.click();+ await settle();++ expect(container.querySelector(".existing-data-warning")?.textContent)+ .toContain("setup.existing-data-encrypted-warning");+ });++ it("goes back to the question when the backup fails, having erased nothing", async () => {+ // Rejected the way the client's request layer rejects: the response body, not an Error.+ serverMock.postWithTimeout.mockRejectedValue('{"message":"the disk is full"}');+ renderScreens();+ await settle();++ choose("back-up");+ await settle();+ button("setup.continue")?.click();+ await settle();++ expect(container.querySelector(".page-error")?.textContent).toContain("the disk is full");+ expect(container.querySelector("input[type=radio]")).not.toBeNull();+ expect(onProceed).not.toHaveBeenCalled();+ });+});diff --git a/apps/client/src/setup_existing.tsx b/apps/client/src/setup_existing.tsxnew file mode 100644index 0000000000..a6c9d2e92c--- /dev/null+++ b/apps/client/src/setup_existing.tsx@@ -0,0 +1,334 @@+import "./setup_existing.css";++import type { SetupExistingBackup } from "@triliumnext/commons";+import { useEffect, useState } from "preact/hooks";++import { formatSize } from "./services/utils";+import { t } from "./services/i18n";+import server from "./services/server";+import Admonition from "./widgets/react/Admonition";+import Button from "./widgets/react/Button";+import { Card, CardSection } from "./widgets/react/Card";+import FormRadioGroup from "./widgets/react/FormRadioGroup";+import Icon from "./widgets/react/Icon";+import SetupPage from "./widgets/react/SetupPage";+import SlidePages from "./widgets/react/SlidePages";++/**+ * What happens to the knowledge base that was already here.+ *+ * The wizard is normally the first thing an instance ever shows. When the app asks for it instead,+ * there is a database behind it, and every path onwards from here replaces or erases that database.+ * So this is the first screen, before the menu, and nothing else can be reached until it is answered.+ *+ * Three screens, one question. The choice, the wait while a backup is written, and what was written.+ * Every one of them can be left through Cancel, which puts the instance back the way it was: nothing+ * is touched until the last Continue.+ *+ * @module+ */++/** What the user decided to do with the database that is already here. */+type Choice = "back-up" | "delete";++/** The three screens, in the order they can be reached, which is also the order they slide in. */+type Step = "choice" | "backing-up" | "backed-up";+const STEP_ORDER: Step[] = [ "choice", "backing-up", "backed-up" ];++/**+ * The whole question, as one step of the wizard.+ *+ * Owns its screens the way the restore flow owns its own: the wizard has one state for all of this,+ * and what the user has answered so far lives here rather than being spread through the wizard's own+ * state machine.+ *+ * @param onProceed the database is gone; carry on with the rest of setup.+ * @param onKept nothing was touched; the app is coming back.+ */+export default function ExistingData({ onProceed, onKept }: { onProceed: () => void; onKept: () => void }) {+ const [ step, setStep ] = useState<Step>("choice");+ const [ backup, setBackup ] = useState<SetupExistingBackup | null>(null);+ const [ error, setError ] = useState<string>();+ const [ errorId, setErrorId ] = useState(0);++ function raiseError(message: string) {+ setError(message);+ setErrorId((previous) => previous + 1);+ }++ /** Erases the database and moves on, which is the one irreversible thing these screens do. */+ async function erase() {+ try {+ await deleteExistingData();+ onProceed();+ } catch (e) {+ setStep("choice");+ raiseError(messageOf(e) ?? t("setup.existing-data-delete-failed"));+ }+ }++ async function backUp() {+ setStep("backing-up");++ try {+ setBackup(await backUpExistingData());+ setStep("backed-up");+ } catch (e) {+ // Back to the question with nothing done: there is no continuing past a backup that was+ // asked for and did not happen.+ setStep("choice");+ raiseError(messageOf(e) ?? t("setup.existing-data-backup-failed"));+ }+ }++ async function keep() {+ try {+ await keepExistingData();+ onKept();+ } catch (e) {+ setStep("choice");+ raiseError(messageOf(e) ?? t("setup.existing-data-keep-failed"));+ }+ }++ return (+ <SlidePages current={step} order={STEP_ORDER}>+ {(shown) => (+ <>+ {shown === "choice" && (+ <ExistingDataChoice+ error={error}+ errorId={errorId}+ onBackUp={() => void backUp()}+ onDelete={() => void erase()}+ onCancel={() => void keep()}+ />+ )}+ {shown === "backing-up" && <ExistingDataBackingUp />}+ {shown === "backed-up" && backup && (+ <ExistingDataBackedUp+ backup={backup}+ onContinue={() => void erase()}+ onCancel={() => void keep()}+ />+ )}+ </>+ )}+ </SlidePages>+ );+}++/**+ * Whatever the failure has to say for itself.+ *+ * A rejected request is not an `Error`: the client's own layer rejects with the response body as a+ * string, or with a bare word when the browser dropped the request. Taking only `Error` here left+ * every server-side failure showing the generic sentence and nothing else.+ */+function messageOf(e: unknown): string | undefined {+ if (e instanceof Error) {+ return e.message;+ }+ if (typeof e === "string" && e) {+ return messageOfBody(e);+ }+ if (typeof e === "object" && e !== null && "message" in e && typeof e.message === "string") {+ return e.message;+ }++ return undefined;+}++/** The sentence out of a JSON error body, or the body itself where it is not one. */+function messageOfBody(body: string): string {+ try {+ const parsed: unknown = JSON.parse(body);+ if (typeof parsed === "object" && parsed !== null && "message" in parsed+ && typeof parsed.message === "string") {+ return parsed.message;+ }+ } catch {+ // Not JSON, so it is already whatever the server had to say.+ }++ return body;+}++export function ExistingDataChoice({ error, errorId, onBackUp, onDelete, onCancel }: {+ error?: string;+ errorId?: number;+ onBackUp: () => void;+ onDelete: () => void;+ onCancel: () => void;+}) {+ const [ choice, setChoice ] = useState<Choice | null>(null);++ return (+ <SetupPage+ className="existing-data"+ title={t("setup.existing-data")}+ description={t("setup.existing-data-description")}+ illustration={<Icon icon="bx bx-data" className="illustration-icon" />}+ error={error}+ errorId={errorId}+ footer={+ <>+ <Button text={t("setup.existing-data-cancel")} onClick={onCancel} />+ <Button+ text={t("setup.continue")}+ kind="primary"+ // Neither is chosen to begin with: one of them erases a knowledge base, and a+ // default would make that the answer of anyone who pressed on without reading.+ disabled={choice === null}+ onClick={() => (choice === "back-up" ? onBackUp() : onDelete())}+ />+ </>+ }+ >+ <Card>+ <CardSection>+ <FormRadioGroup+ name="existing-data-choice"+ currentValue={choice ?? ""}+ onChange={(value) => setChoice(value as Choice)}+ values={[+ { value: "back-up", label: t("setup.existing-data-back-up") },+ { value: "delete", label: t("setup.existing-data-delete") }+ ]}+ />+ </CardSection>+ </Card>++ {choice === "delete" && (+ <Admonition type="caution" className="existing-data-warning">+ {t("setup.existing-data-delete-warning")}+ </Admonition>+ )}+ </SetupPage>+ );+}++/**+ * The wait while the backup is written, which for a large knowledge base is minutes.+ *+ * Asks how far along it is rather than only spinning: most of that time is spent inside a single+ * write, and a screen that says nothing for six minutes is indistinguishable from one that has+ * stopped. The number is polled because the answer is one number and this is the only thing asking.+ */+export function ExistingDataBackingUp() {+ const [ fraction, setFraction ] = useState<number | null>(null);++ useEffect(() => {+ const interval = setInterval(async () => {+ try {+ const { fraction } = await server.get<{ fraction: number | null }>("setup/existing/status");+ setFraction(fraction);+ } catch {+ // The backup is what matters here; a missed reading is worth nothing being said about.+ }+ }, PROGRESS_INTERVAL_MS);++ return () => clearInterval(interval);+ }, []);++ return (+ <SetupPage+ className="existing-data-backing-up top-aligned"+ title={t("setup.existing-data-backing-up")}+ illustration={<Icon icon="bx bx-archive-out" className="illustration-icon" />}+ >+ <div class="existing-data-progress">+ <div class="existing-data-progress-message">+ <span class="spinner-border" role="status" aria-hidden="true" />+ <span>{t("setup.existing-data-backing-up-message")}</span>+ </div>++ {/* Only once the writer has said something. Until then there is nothing to draw, and+ an empty bar that never moves says less than no bar at all. */}+ {fraction !== null && (+ <div class="existing-data-progress-bar">+ <progress value={fraction} max={1} />+ <span>{Math.floor(fraction * 100)}%</span>+ </div>+ )}+ </div>+ </SetupPage>+ );+}++/** How often the screen asks how far along the backup is. */+const PROGRESS_INTERVAL_MS = 1000;++/**+ * What was written, before the database it was written from is erased.+ *+ * The path is shown in full and not abbreviated: a custom backup directory is an option in a+ * database that is about to stop existing, so this may be the last time the user can see where their+ * backup actually went.+ */+export function ExistingDataBackedUp({ backup, onContinue, onCancel }: {+ backup: SetupExistingBackup;+ onContinue: () => void;+ onCancel: () => void;+}) {+ return (+ <SetupPage+ className="existing-data-backed-up top-aligned"+ title={t("setup.existing-data-backed-up")}+ description={t("setup.existing-data-backed-up-description")}+ illustration={<Icon icon="bx bx-check-circle" className="illustration-icon" />}+ footer={+ <>+ <Button text={t("setup.existing-data-cancel")} onClick={onCancel} />+ <Button text={t("setup.continue")} kind="primary" onClick={onContinue} />+ </>+ }+ >+ <Card>+ <CardSection>+ <dl class="existing-data-facts">+ <dt>{t("setup.existing-data-file-name")}</dt>+ <dd>{backup.fileName}</dd>++ <dt>{t("setup.existing-data-file-path")}</dt>+ <dd class="existing-data-path">{backup.filePath}</dd>++ <dt>{t("setup.existing-data-file-size")}</dt>+ <dd>{formatSize(backup.fileSize)}</dd>+ </dl>+ </CardSection>+ </Card>++ {backup.encrypted && (+ <Admonition type="warning" className="existing-data-warning">+ {t("setup.existing-data-encrypted-warning")}+ </Admonition>+ )}+ </SetupPage>+ );+}++/**+ * How long the backup is given before the client stops waiting for its answer.+ *+ * The default minute is nothing next to what this takes: a large knowledge base is copied, and+ * compressed and encrypted where the instance is set up for that, which runs into minutes. Giving up+ * early would not stop any of it, only lose the answer and report a failure for something that was+ * still succeeding.+ */+const BACKUP_TIMEOUT_MS = 60 * 60 * 1000;++/** Backs the existing database up, answering with what was written. */+export function backUpExistingData(): Promise<SetupExistingBackup> {+ return server.postWithTimeout<SetupExistingBackup>("setup/existing/backup", BACKUP_TIMEOUT_MS);+}++/** Erases it, which is the point of no return. */+export function deleteExistingData(): Promise<void> {+ return server.post("setup/existing/delete");+}++/** Leaves it alone and opens it, which is what every Cancel on these screens does. */+export function keepExistingData(): Promise<void> {+ return server.post("setup/existing/keep");+}diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.jsonindex 04fa98190e..557e9c3b8b 100644--- a/apps/client/src/translations/en/translation.json+++ b/apps/client/src/translations/en/translation.json@@ -3684,6 +3684,23 @@"language": "Language","continue": "Continue","your-ip-addresses": "Addresses for this device",+ "existing-data": "You already have a knowledge base",+ "existing-data-description": "Setting up again will replace it. Would you like to save a copy first?",+ "existing-data-back-up": "Yes, back it up",+ "existing-data-delete": "No, delete the existing data",+ "existing-data-delete-warning": "Once you press Continue, the existing knowledge base is permanently erased. There is no way to recover it afterwards.",+ "existing-data-cancel": "Cancel",+ "existing-data-backing-up": "Backing up",+ "existing-data-backing-up-message": "Creating a backup...",+ "existing-data-backed-up": "Backup created",+ "existing-data-backed-up-description": "Your existing knowledge base has been saved to a backup file.",+ "existing-data-file-name": "Backup file name",+ "existing-data-file-path": "File path",+ "existing-data-file-size": "Size",+ "existing-data-encrypted-warning": "This backup is encrypted with the backup password you set in the options, which is not your Trilium password. If you no longer have that password, press Cancel now: nothing has been deleted yet, and you can change the password before trying again. Without it the backup cannot be restored.",+ "existing-data-backup-failed": "The backup could not be created.",+ "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","restore-from-backup-description": "Continue using an existing knowledge base, restored from a backup file.","restore-from-backup-page-description": "Choose the backup to restore from.",diff --git a/apps/desktop/src/main.ts b/apps/desktop/src/main.tsindex a0e2fd5eb0..93223a3130 100644--- a/apps/desktop/src/main.ts+++ b/apps/desktop/src/main.ts@@ -9,7 +9,7 @@ import config from "@triliumnext/server/src/services/config.js";import { recoverInterruptedRestore } from "@triliumnext/server/src/services/database_restore.js";import dataDirs from "@triliumnext/server/src/services/data_dir.js";import port from "@triliumnext/server/src/services/port.js";-import { consumeSetupMarker, setupMarkerStore } from "@triliumnext/server/src/services/setup_marker.js";+import { consumeSetupMarker, setupPlatform } from "@triliumnext/server/src/services/setup_marker.js";import { RESOURCE_DIR } from "@triliumnext/server/src/services/resource_dir.js";import WebSocketMessagingProvider from "@triliumnext/server/src/services/ws_messaging_provider.js";import BetterSqlite3Provider from "@triliumnext/server/src/sql_provider.js";@@ -282,7 +282,7 @@ export async function main() {// Read before core exists, because what it says is whether to open the database at all: a// relaunch asked for by the app itself comes back here and goes to the setup window instead.setupMarker: consumeSetupMarker(),- setupMarkerStore,+ setupPlatform,extraAppInfo: {nodeVersion: process.version,dataDirectory: path.resolve(dataDirs.TRILIUM_DATA_DIR)diff --git a/apps/server/src/backup_provider.ts b/apps/server/src/backup_provider.tsindex 1a9936533a..46c599e6ff 100644--- a/apps/server/src/backup_provider.ts+++ b/apps/server/src/backup_provider.ts@@ -3,7 +3,7 @@ import {peekBackupContainer,writeBackupContainer} from "@triliumnext/backup-container";-import type { DatabaseBackup } from "@triliumnext/commons";+import type { DatabaseBackup, SetupExistingBackup } from "@triliumnext/commons";import { BackupOptionsService, BackupService, getLog, sync_mutex as syncMutexService, utils as coreUtils, ws } from "@triliumnext/core";import fs from "fs";import fsp from "fs/promises";@@ -103,6 +103,40 @@ export default class ServerBackupService extends BackupService {});}+ /**+ * Writes a backup under the given name, and says what was written.+ *+ * The name is used as it stands, spaces and all, because the setup screen shows it to the user+ * and the user then goes looking for it in a file manager. It never reaches a shell, and the+ * directory is this instance's own, so the sanitising `backupNow` does for names that arrive+ * from a schedule would only make this one harder to read.+ */+ override async backupAs(+ baseName: string,+ onProgress?: (fraction: number) => void+ ): Promise<SetupExistingBackup> {+ const written = await syncMutexService.doExclusively(async () => {+ const format = await this.resolveFormat();+ const directory = (format.keepLocal ? null : this.getCustomBackupDir()) ?? getDefaultBackupDir();++ return {+ filePath: await writeBackup(directory, baseName, format, "default", onProgress),+ // What was actually written, not what was asked for: encryption falls back to an+ // unencrypted local copy where the passphrase cannot be read, and the screen that+ // tells the user to keep their password safe must not appear over one of those.+ encrypted: format.passphrase !== null+ };+ });+ const stat = fs.statSync(written.filePath);++ return {+ fileName: path.basename(written.filePath),+ filePath: written.filePath,+ fileSize: stat.size,+ encrypted: written.encrypted+ };+ }+override async getBackupContent(filePath: string): Promise<Uint8Array | null> {const resolvedPath = this.resolveBackupPath(filePath);@@ -211,7 +245,9 @@ function listBackupsIn(directory: string): DatabaseBackup[] {return fileNames// The extension check excludes intermediate files (e.g. *.db-journal, *.part) created while// a backup is in progress.- .filter((fileName) => fileName.includes("backup")+ // Case-insensitively: the backup the setup screen takes before replacing a database is named+ // for a person reading a directory listing, and starts with a capital.+ .filter((fileName) => fileName.toLowerCase().includes("backup")&& (fileName.endsWith(DATABASE_EXTENSION) || fileName.endsWith(CONTAINER_EXTENSION))).flatMap((fileName) => {const filePath = path.resolve(directory, fileName);@@ -272,7 +308,8 @@ async function writeBackup(directory: string,baseName: string,format: BackupFormat,- location: "default" | "custom"+ location: "default" | "custom",+ onProgress?: (fraction: number) => void): Promise<string> {const isContainer = format.compress || format.passphrase !== null;const fileName = `${baseName}${isContainer ? CONTAINER_EXTENSION : DATABASE_EXTENSION}`;@@ -283,10 +320,12 @@ async function writeBackup(getLog().info("Creating backup...");try {if (isContainer) {- await writeContainer(backupFile, baseName, format);+ await writeContainer(backupFile, baseName, format, onProgress);} else {+ // A plain copy has nothing to report along the way, only that it is over.await sql.copyDatabase(backupFile);}+ onProgress?.(1);} catch (e) {// Whatever was written before the failure is not a usable backup, and would otherwise be// listed and offered for download as if it were one.@@ -314,7 +353,8 @@ async function writeBackup(async function writeContainer(backupFile: string,baseName: string,- format: BackupFormat+ format: BackupFormat,+ onProgress?: (fraction: number) => void): Promise<void> {const snapshot = path.resolve(dataDir.TMP_DIR, `${baseName}.snapshot.db`);const partial = `${backupFile}.part`;@@ -326,6 +366,7 @@ async function writeContainer(compress: format.compress,passphrase: format.passphrase ?? undefined,plaintextSize: fs.statSync(snapshot).size,+ onProgress,// The digest is only known once the payload is written, so it is patched in afterwards.patchHeader: async (offset, data) => {const handle = await fsp.open(partial, "r+");diff --git a/apps/server/src/main.ts b/apps/server/src/main.tsindex 93fc39c723..aabff3fe91 100644--- a/apps/server/src/main.ts+++ b/apps/server/src/main.ts@@ -19,7 +19,7 @@ import dataDirs from "./services/data_dir.js";import port from "./services/port.js";import NodeRequestProvider from "./services/request.js";import { RESOURCE_DIR } from "./services/resource_dir.js";-import { consumeSetupMarker, setupMarkerStore } from "./services/setup_marker.js";+import { consumeSetupMarker, setupPlatform } from "./services/setup_marker.js";import WebSocketMessagingProvider from "./services/ws_messaging_provider.js";import BetterSqlite3Provider from "./sql_provider.js";import NodejsZipProvider from "./zip_provider.js";@@ -91,7 +91,7 @@ async function startApplication() {config,// Read before core exists, because what it says is whether to open the database at all.setupMarker: consumeSetupMarker(),- setupMarkerStore,+ setupPlatform,extraAppInfo: {nodeVersion: process.version,dataDirectory: path.resolve(dataDirs.TRILIUM_DATA_DIR)diff --git a/apps/server/src/services/database_restore.spec.ts b/apps/server/src/services/database_restore.spec.tsindex fd5e614519..1c1a6651d2 100644--- a/apps/server/src/services/database_restore.spec.ts+++ b/apps/server/src/services/database_restore.spec.ts@@ -202,6 +202,18 @@ describe("what the log is told", () => {expect(said[1]).toContain("<temporary files>");});+ it("leaves ordinary words alone, however the data directory happens to be configured", () => {+ const said: string[] = [];+ vi.spyOn(getLog(), "info").mockImplementation((message) => said.push(String(message)));++ // A relatively configured data directory ("TRILIUM_DATA_DIR=data", which the development+ // scripts use) was replaced as a bare substring, turning every "database" into+ // "<data directory>base" and making the log read as nonsense.+ logRestore("detaching the database being replaced");++ expect(said[0]).toContain("detaching the database being replaced");+ });+it("names every step it enters and where it stopped, without naming the backup", async () => {const said: string[] = [];vi.spyOn(getLog(), "info").mockImplementation((message) => said.push(String(message)));diff --git a/apps/server/src/services/database_restore.ts b/apps/server/src/services/database_restore.tsindex 56de889552..b2cceeba87 100644--- a/apps/server/src/services/database_restore.ts+++ b/apps/server/src/services/database_restore.ts@@ -75,19 +75,39 @@ function withoutPaths(text: string): string {let scrubbed = text;// Longest first, so a path inside the data directory is not reduced to the data directory and a- // leftover fragment of itself.+ // leftover fragment of itself. Each is scrubbed both as configured and as resolved, since an+ // error quotes back whichever form the call that failed was given.for (const [ directory, name ] of [[ dataDir.DOCUMENT_PATH, "<database>" ],[ dataDir.TMP_DIR, "<temporary files>" ],[ dataDir.BACKUP_DIR, "<backup location>" ],[ dataDir.TRILIUM_DATA_DIR, "<data directory>" ]] as const) {- scrubbed = coreUtils.replaceAll(scrubbed, directory, name);+ for (const form of pathForms(directory)) {+ scrubbed = coreUtils.replaceAll(scrubbed, form, name);+ }}return scrubbed;}+/**+ * The spellings of a configured location that could turn up in an error, longest first.+ *+ * A data directory may be configured relatively — `TRILIUM_DATA_DIR=data` is what the development+ * scripts use — so the resolved form is what a filesystem error names, while our own calls pass the+ * configured one. A bare word is dropped: replacing "data" as a substring turns every "database" in+ * a sentence into "<data directory>base".+ */+function pathForms(directory: string): string[] {+ const resolved = path.resolve(directory);+ const looksLikePath = directory.includes(path.sep) || directory.includes("/");++ return resolved === directory || !looksLikePath+ ? [ resolved ]+ : [ resolved, directory ].sort((a, b) => b.length - a.length);+}+/*** How much of the way through a step has to pass before it is worth another line.*diff --git a/apps/server/src/services/setup_marker.spec.ts b/apps/server/src/services/setup_marker.spec.tsindex a6a6d53fc2..8f88c76102 100644--- a/apps/server/src/services/setup_marker.spec.ts+++ b/apps/server/src/services/setup_marker.spec.ts@@ -4,7 +4,7 @@ import path from "path";import { afterEach, describe, expect, it } from "vitest";import dataDirs from "./data_dir.js";-import { consumeSetupMarker, setupMarkerStore } from "./setup_marker.js";+import { consumeSetupMarker, setupPlatform } from "./setup_marker.js";const MARKER_PATH = path.join(dataDirs.TRILIUM_DATA_DIR, SETUP_MARKER_FILE_NAME);@@ -37,18 +37,18 @@ describe("the marker a start finds", () => {describe("writing the marker", () => {it("leaves something the next start reads back as what was asked for", async () => {- await setupMarkerStore.write({ lang: "de", targetScreen: "restore-backup" });+ await setupPlatform.writeMarker({ lang: "de", targetScreen: "restore-backup" });expect(fs.existsSync(MARKER_PATH)).toBe(true);expect(consumeSetupMarker()).toEqual({ lang: "de", targetScreen: "restore-backup" });});it("can be taken back, whether or not there was one", async () => {- await setupMarkerStore.write({ lang: "en" });- await setupMarkerStore.remove();+ await setupPlatform.writeMarker({ lang: "en" });+ await setupPlatform.removeMarker();expect(fs.existsSync(MARKER_PATH)).toBe(false);// Removing what is not there is how a cancelled request ends, and is not a failure.- await expect(setupMarkerStore.remove()).resolves.toBeUndefined();+ await expect(setupPlatform.removeMarker()).resolves.toBeUndefined();});});diff --git a/apps/server/src/services/setup_marker.ts b/apps/server/src/services/setup_marker.tsindex 2f18dd83df..c0dd264a17 100644--- a/apps/server/src/services/setup_marker.ts+++ b/apps/server/src/services/setup_marker.ts@@ -1,5 +1,5 @@import { SETUP_MARKER_FILE_NAME, type SetupMarker } from "@triliumnext/commons";-import { getLog, parseSetupMarker, type SetupMarkerStore } from "@triliumnext/core";+import { getLog, getSql, parseSetupMarker, type SetupPlatform } from "@triliumnext/core";import fs from "fs";import path from "path";@@ -55,13 +55,24 @@ export function consumeSetupMarker(): SetupMarker | null {return marker;}-/** How this platform writes the marker, for the route that asks the next start to be the wizard. */-export const setupMarkerStore: SetupMarkerStore = {- async write(marker: SetupMarker) {+/** What setup reaches for on this platform: the marker file, and the database beside it. */+export const setupPlatform: SetupPlatform = {+ async writeMarker(marker: SetupMarker) {fs.writeFileSync(markerPath(), JSON.stringify(marker, null, 4), "utf8");},- async remove() {+ async removeMarker() {fs.rmSync(markerPath(), { force: true });+ },++ async removeDatabase() {+ // Detached first: on Windows an open handle is enough to make the file undeletable, and+ // leaving the connection attached to a file that is gone is worse than either.+ getSql().detachConnection();++ const document = dataDirs.DOCUMENT_PATH;+ for (const file of [ document, `${document}-wal`, `${document}-shm` ]) {+ fs.rmSync(file, { force: true });+ }}};diff --git a/apps/server/src/sql_provider.ts b/apps/server/src/sql_provider.tsindex 5495c2ffad..f76bc04895 100644--- a/apps/server/src/sql_provider.ts+++ b/apps/server/src/sql_provider.ts@@ -52,6 +52,10 @@ export default class BetterSqlite3Provider implements DatabaseProvider {this.dbConnection = undefined;}+ isAttached() {+ return this.dbConnection !== undefined;+ }+async backup(destinationFile: string) {try {unlinkSync(destinationFile);diff --git a/apps/standalone/src/lightweight/database_restore.ts b/apps/standalone/src/lightweight/database_restore.tsindex b52add06d9..e6a45b6d6e 100644--- a/apps/standalone/src/lightweight/database_restore.ts+++ b/apps/standalone/src/lightweight/database_restore.ts@@ -243,7 +243,8 @@ async function swapIn(target: RestoreTarget, previous: string, candidate: stringawait removeQuietly(target.pool, previous);}-async function writeCurrentDatabaseName(dbName: string): Promise<void> {+/** Points the next start at `dbName`, which is the whole of what makes a database the live one. */+export async function writeCurrentDatabaseName(dbName: string): Promise<void> {const root = await navigator.storage.getDirectory();const handle = await root.getFileHandle(POINTER_FILE, { create: true });const writable = await handle.createWritable();diff --git a/apps/standalone/src/lightweight/setup_marker.spec.ts b/apps/standalone/src/lightweight/setup_marker.spec.tsindex d80d37db40..970d6aeab3 100644--- a/apps/standalone/src/lightweight/setup_marker.spec.ts+++ b/apps/standalone/src/lightweight/setup_marker.spec.ts@@ -1,7 +1,7 @@import { SETUP_MARKER_FILE_NAME } from "@triliumnext/commons";import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";-import { consumeSetupMarker, setupMarkerStore } from "./setup_marker.js";+import { consumeSetupMarker, removeSetupMarker, writeSetupMarker } from "./setup_marker.js";/** Stands in for the origin's private filesystem, which is where the marker lives here. */let files: Map<string, string>;@@ -62,17 +62,17 @@ describe("the marker a start finds", () => {describe("writing the marker", () => {it("leaves something the next start reads back as what was asked for", async () => {- await setupMarkerStore.write({ lang: "de", targetScreen: "restore-backup" });+ await writeSetupMarker({ lang: "de", targetScreen: "restore-backup" });await expect(consumeSetupMarker()).resolves.toEqual({ lang: "de", targetScreen: "restore-backup" });});it("can be taken back, whether or not there was one", async () => {- await setupMarkerStore.write({ lang: "en" });- await setupMarkerStore.remove();+ await writeSetupMarker({ lang: "en" });+ await removeSetupMarker();expect(files.has(SETUP_MARKER_FILE_NAME)).toBe(false);// Removing what is not there is how a cancelled request ends, and is not a failure.- await expect(setupMarkerStore.remove()).resolves.toBeUndefined();+ await expect(removeSetupMarker()).resolves.toBeUndefined();});});diff --git a/apps/standalone/src/lightweight/setup_marker.ts b/apps/standalone/src/lightweight/setup_marker.tsindex 1cec5772e8..e380a9f402 100644--- a/apps/standalone/src/lightweight/setup_marker.ts+++ b/apps/standalone/src/lightweight/setup_marker.ts@@ -1,5 +1,5 @@import { SETUP_MARKER_FILE_NAME, type SetupMarker } from "@triliumnext/commons";-import { parseSetupMarker, type SetupMarkerStore } from "@triliumnext/core";+import { parseSetupMarker } from "@triliumnext/core";/*** The `setup.json` marker in the browser's own storage.@@ -41,26 +41,25 @@ export async function consumeSetupMarker(): Promise<SetupMarker | null> {return parseSetupMarker(raw);}-/** How this platform writes the marker, for the route that asks the next start to be the wizard. */-export const setupMarkerStore: SetupMarkerStore = {- async write(marker: SetupMarker) {- const root = await navigator.storage.getDirectory();- const handle = await root.getFileHandle(SETUP_MARKER_FILE_NAME, { create: true });- const writable = await handle.createWritable();+/** Leaves the marker that makes the next start the wizard. */+export async function writeSetupMarker(marker: SetupMarker): Promise<void> {+ const root = await navigator.storage.getDirectory();+ const handle = await root.getFileHandle(SETUP_MARKER_FILE_NAME, { create: true });+ const writable = await handle.createWritable();- try {- await writable.write(JSON.stringify(marker, null, 4));- } finally {- await writable.close();- }- },+ try {+ await writable.write(JSON.stringify(marker, null, 4));+ } finally {+ await writable.close();+ }+}- async remove() {- try {- const root = await navigator.storage.getDirectory();- await root.removeEntry(SETUP_MARKER_FILE_NAME);- } catch {- // Nothing to remove, which is the state the caller wanted anyway.- }+/** Takes it back, for a request that was made and then abandoned. */+export async function removeSetupMarker(): Promise<void> {+ try {+ const root = await navigator.storage.getDirectory();+ await root.removeEntry(SETUP_MARKER_FILE_NAME);+ } catch {+ // Nothing to remove, which is the state the caller wanted anyway.}-};+}diff --git a/apps/standalone/src/local-server-worker.ts b/apps/standalone/src/local-server-worker.tsindex bde9bf6597..a8b4fc5769 100644--- a/apps/standalone/src/local-server-worker.ts+++ b/apps/standalone/src/local-server-worker.ts@@ -49,8 +49,14 @@ console.log("[Worker] Error handlers installed, loading modules...");import type { BrowserRouter } from './lightweight/browser_router';import type { StandaloneRestoreProgress, StandaloneRestoreResult } from "@triliumnext/commons";-import { readCurrentDatabaseName, RestoreFailure, restoreDatabase } from './lightweight/database_restore';-import { consumeSetupMarker, setupMarkerStore } from './lightweight/setup_marker';+import {+ DEFAULT_DATABASE_NAME,+ readCurrentDatabaseName,+ RestoreFailure,+ restoreDatabase,+ writeCurrentDatabaseName+} from './lightweight/database_restore';+import { consumeSetupMarker, removeSetupMarker, writeSetupMarker } from './lightweight/setup_marker';// Build-time constant injected by Vite (see `define` in vite.config.mts).declare const __TRILIUM_INTEGRATION_TEST__: string;@@ -276,7 +282,11 @@ async function initialize(): Promise<void> {// Read before core opens anything, because what it says is whether to open the// database at all: a page reloaded by the app itself comes back to the wizard.setupMarker: await consumeSetupMarker(),- setupMarkerStore,+ setupPlatform: {+ writeMarker: writeSetupMarker,+ removeMarker: removeSetupMarker,+ removeDatabase: removeStandaloneDatabase+ },dbConfig: {provider: sqlProvider!,isReadOnly: false,@@ -369,6 +379,32 @@ async function dispatch(request: LocalRequest) {return appRouter.dispatch(request.method, request.url, request.body, request.headers);}+/**+ * Erases the database the wizard was booted away from, and leaves an empty one in its place.+ *+ * The pool has no notion of "no database", and everything after this point in the wizard writes to+ * one: creating a document, converging a sync. So the entry is unlinked and a fresh one opened under+ * the name a first run uses, which is exactly the state a browser that had never run Trilium is in.+ */+async function removeStandaloneDatabase(): Promise<void> {+ const pool = sqlProvider?.sahPool;+ if (!sqlProvider || !pool) {+ throw new Error("The database is not open, so there is nothing to erase.");+ }++ const live = await readCurrentDatabaseName();+ sqlProvider.close();++ try {+ pool.unlink(live);+ } catch {+ // Already gone, which is the state the caller asked for.+ }++ await writeCurrentDatabaseName(DEFAULT_DATABASE_NAME);+ sqlProvider.loadFromSahPool(DEFAULT_DATABASE_NAME);+}+/*** Restores the database from a backup handed straight to this worker.*diff --git a/packages/commons/src/lib/setup_marker.ts b/packages/commons/src/lib/setup_marker.tsindex a9ca774abf..fa4976075f 100644--- a/packages/commons/src/lib/setup_marker.ts+++ b/packages/commons/src/lib/setup_marker.ts@@ -24,6 +24,16 @@ export const SETUP_MARKER_FILE_NAME = "setup.json";*/export type SetupTargetScreen = "restore-backup";+/** A backup the setup screen took of the database it is about to replace. */+export interface SetupExistingBackup {+ fileName: string;+ /** Shown in full, because the user may lose sight of a custom backup directory afterwards. */+ filePath: string;+ fileSize: number;+ /** Whether it is encrypted, which decides whether the user needs their backup password to use it. */+ encrypted: boolean;+}+/** What a start reads out of {@link SETUP_MARKER_FILE_NAME}. */export interface SetupMarker {/** The language the instance was using, so the wizard is in it rather than asking again. */diff --git a/packages/trilium-core/src/index.ts b/packages/trilium-core/src/index.tsindex 03751c3bc5..9e4f44974b 100644--- a/packages/trilium-core/src/index.ts+++ b/packages/trilium-core/src/index.ts@@ -8,8 +8,8 @@ import { initSql } from "./services/sql/index";import { SqlService, SqlServiceParams } from "./services/sql/sql";import { initMessaging, MessagingProvider } from "./services/messaging/index";import { initRequest, RequestProvider } from "./services/request";-import { changeLanguage, initTranslations, TranslationProvider } from "./services/i18n";-import { enterSetupMode, initSetupMarkerStore, type SetupMarkerStore } from "./services/setup_mode";+import { initTranslations, TranslationProvider } from "./services/i18n";+import { enterSetupMode, initSetupPlatform, type SetupPlatform } from "./services/setup_mode";import { initSchema, initDemoArchive } from "./services/sql_init";import appInfo from "./services/app_info";import { type PlatformProvider, initPlatform } from "./services/platform";@@ -33,7 +33,7 @@ export {isSetupRequested,leaveSetupMode,parseSetupMarker,- type SetupMarkerStore+ type SetupPlatform} from "./services/setup_mode";export {type CandidateDatabase,@@ -162,7 +162,7 @@ export { default as scriptService } from "./services/script";export { default as BackendScriptApi, type Api as BackendScriptApiInterface } from "./services/backend_script_api";export * as scheduler from "./services/scheduler";-export async function initializeCore({ dbConfig, executionContext, crypto, zip, zipExportProviderFactory, translations, messaging, request, schema, extraAppInfo, platform, getDemoArchive, inAppHelp, log, backup, image, config, setupMarker, setupMarkerStore }: {+export async function initializeCore({ dbConfig, executionContext, crypto, zip, zipExportProviderFactory, translations, messaging, request, schema, extraAppInfo, platform, getDemoArchive, inAppHelp, log, backup, image, config, setupMarker, setupPlatform }: {dbConfig: SqlServiceParams,executionContext: ExecutionContext,crypto: CryptoProvider,@@ -189,7 +189,7 @@ export async function initializeCore({ dbConfig, executionContext, crypto, zip,*/setupMarker?: SetupMarker | null;/** How this platform writes that file, for the route that asks for the next start to be setup. */- setupMarkerStore?: SetupMarkerStore;+ setupPlatform?: SetupPlatform;}) {if (config) {initConfig(config);@@ -200,16 +200,13 @@ export async function initializeCore({ dbConfig, executionContext, crypto, zip,// Before anything reads the database: from here on this instance answers as one with nothing to// open, which is what `initSql` below relies on to leave the existing database alone.enterSetupMode(setupMarker ?? null);- if (setupMarkerStore) {- initSetupMarkerStore(setupMarkerStore);- }- await initTranslations(translations);- // The wizard is for a user who has already chosen a language, so it opens in theirs. Applied- // here because the place that language is normally read from is the database this start is- // deliberately not opening.- if (setupMarker?.lang) {- await changeLanguage(setupMarker.lang);+ if (setupPlatform) {+ initSetupPlatform(setupPlatform);}+ // The wizard is for a user who has already chosen a language, so it opens in theirs. Passed in+ // here, where the resources for a language are actually loaded, because the place that language+ // is normally read from is the database this start is deliberately not opening.+ await initTranslations(translations, setupMarker?.lang);initCrypto(crypto);initZipProvider(zip);initZipExportProviderFactory(zipExportProviderFactory);diff --git a/packages/trilium-core/src/routes/api/setup.ts b/packages/trilium-core/src/routes/api/setup.tsindex 800e664294..7b2f3aed82 100644--- a/packages/trilium-core/src/routes/api/setup.ts+++ b/packages/trilium-core/src/routes/api/setup.ts@@ -1,7 +1,13 @@import sqlInit from "../../services/sql_init.js";import setupService from "../../services/setup.js";import { getRunningSetupOperation, withSetupLock } from "../../services/setup_lock.js";-import { asSetupTargetScreen, getSetupMarkerStore } from "../../services/setup_mode.js";+import {+ backUpExistingData,+ deleteExistingData,+ getExistingBackupProgress,+ keepExistingData+} from "../../services/setup_existing.js";+import { asSetupTargetScreen, getSetupPlatform } from "../../services/setup_mode.js";import { getLog } from "../../services/log.js";import appInfo from "../../services/app_info.js";import optionService from "../../services/options.js";@@ -42,7 +48,7 @@ function getStatus() {async function bootToSetup(req: Request) {const targetScreen = asSetupTargetScreen(req.body?.targetScreen);- await getSetupMarkerStore().write({+ await getSetupPlatform().writeMarker({lang: optionService.getOptionOrNull("locale") ?? "en",...(targetScreen ? { targetScreen } : {})});@@ -50,6 +56,36 @@ async function bootToSetup(req: Request) {getLog().info(`Boot to setup requested${targetScreen ? ` for "${targetScreen}"` : ""}.`);}+/**+ * Backs up the database the wizard was booted away from, and says where it went.+ *+ * Answers only once the file is written, which for a large database is minutes: the screen that+ * calls this shows a spinner for exactly that long, and has nothing useful to say in between.+ */+async function backUpExisting() {+ return await backUpExistingData(new Date());+}++/**+ * How far through the backup is, for the screen waiting on it.+ *+ * Polled rather than pushed: the answer is one number, the screen is the only thing asking, and a+ * push would need a channel that setup does not otherwise have.+ */+function existingBackupStatus() {+ return { fraction: getExistingBackupProgress() };+}++/** Erases that database. Everything else in the data directory, backups included, stays. */+async function deleteExisting() {+ await deleteExistingData();+}++/** Abandons setup and opens the database that was there all along. */+async function keepExisting() {+ await keepExistingData();+}+async function setupNewDocument(req: Request) {const { skipDemoDb } = req.query;const locale = req.body?.locale;@@ -135,6 +171,10 @@ function getSyncSeed() {export default {getStatus,bootToSetup,+ backUpExisting,+ existingBackupStatus,+ deleteExisting,+ keepExisting,setupNewDocument,setupSyncFromServer,getSyncSeed,diff --git a/packages/trilium-core/src/routes/index.ts b/packages/trilium-core/src/routes/index.tsindex 5e4af1fe0f..67d55a040f 100644--- a/packages/trilium-core/src/routes/index.ts+++ b/packages/trilium-core/src/routes/index.ts@@ -154,6 +154,14 @@ export function buildSharedApiRoutes({ route, asyncRoute, apiRoute, asyncApiRout// it is how the app asks the next start to be the wizard.asyncApiRoute(PST, "/api/setup/boot", setupApiRoute.bootToSetup);+ // What becomes of the database the wizard was booted away from. Guarded like the rest of setup,+ // and refused again inside on an instance that has no such database. Not transactional: the+ // backup runs for minutes, and keeping the database reopens it.+ asyncRoute(PST, "/api/setup/existing/backup", [checkAppNotInitialized], setupApiRoute.backUpExisting, apiResultHandler);+ asyncRoute(GET, "/api/setup/existing/status", [checkAppNotInitialized], setupApiRoute.existingBackupStatus, apiResultHandler);+ asyncRoute(PST, "/api/setup/existing/delete", [checkAppNotInitialized], setupApiRoute.deleteExisting, apiResultHandler);+ asyncRoute(PST, "/api/setup/existing/keep", [checkAppNotInitialized], setupApiRoute.keepExisting, apiResultHandler);+asyncApiRoute(PST, "/api/sync/test", syncApiRoute.testSync);asyncApiRoute(PST, "/api/sync/now", syncApiRoute.syncNow);apiRoute(PST, "/api/sync/fill-entity-changes", syncApiRoute.fillEntityChanges);diff --git a/packages/trilium-core/src/services/backup.ts b/packages/trilium-core/src/services/backup.tsindex ad554a21bb..1a038de247 100644--- a/packages/trilium-core/src/services/backup.ts+++ b/packages/trilium-core/src/services/backup.ts@@ -1,4 +1,4 @@-import type { DatabaseBackup, FilterOptionsByType, OptionNames } from "@triliumnext/commons";+import type { DatabaseBackup, FilterOptionsByType, OptionNames, SetupExistingBackup } from "@triliumnext/commons";import { getContext } from "./context.js";import dateUtils from "./utils/date.js";@@ -28,6 +28,19 @@ export default abstract class BackupService {*/abstract backupNow(name: string): Promise<string>;+ /**+ * Create a backup under a name of the caller's choosing, reporting what was written.+ *+ * For the setup screen's offer to save the existing database before replacing it, where the user+ * is shown the file afterwards and so has to be told its name, its path and its size. Left out by+ * platforms with nowhere to write a file the user could then find.+ *+ * @param onProgress how far through the write it is, from 0 to 1. A backup of a large knowledge+ * base runs for minutes, and a screen with nothing to show for that long is+ * indistinguishable from one that has stopped.+ */+ backupAs?(baseName: string, onProgress?: (fraction: number) => void): Promise<SetupExistingBackup>;+/*** Perform regular scheduled backups (daily, weekly, monthly).* Called periodically by the scheduler.diff --git a/packages/trilium-core/src/services/i18n.spec.ts b/packages/trilium-core/src/services/i18n.spec.tsindex 2eaa4b9999..c488ed8e2a 100644--- a/packages/trilium-core/src/services/i18n.spec.ts+++ b/packages/trilium-core/src/services/i18n.spec.ts@@ -106,6 +106,25 @@ describe("i18n service (core)", () => {});});+ it("initTranslations loads the language it is handed, for a start with no database to read one from", async () => {+ const asked: string[] = [];+ const load = async (_i18next: unknown, locale: string) => { asked.push(locale); };+ const previous = options.getOption("locale");++ try {+ cls.init(() => options.setOption("locale", "en"));++ await initTranslations(load, "ro");+ // Anything that is not a language this application displays leaves the document's own.+ await initTranslations(load, "kl");+ await initTranslations(load);++ expect(asked).toEqual([ "ro", "en", "en" ]);+ } finally {+ cls.init(() => options.setOption("locale", previous));+ }+ });+it("initTranslations logs a fallback when the locale option is empty", async () => {const infoSpy = vi.spyOn(console, "info").mockImplementation(() => {});const previous = options.getOption("locale");diff --git a/packages/trilium-core/src/services/i18n.ts b/packages/trilium-core/src/services/i18n.tsindex 2673728ea5..61c4035b2f 100644--- a/packages/trilium-core/src/services/i18n.ts+++ b/packages/trilium-core/src/services/i18n.ts@@ -6,8 +6,13 @@ import hidden_subtree from "./hidden_subtree";export type TranslationProvider = (i18nextInstance: typeof i18next, locale: LOCALE_IDS) => Promise<void>;-export async function initTranslations(translationProvider: TranslationProvider) {- const locale = getCurrentLanguage();+/**+ * @param preferredLocale the language to load instead of the document's own, for a start that has a+ * language but no open database to read it from — see `setup_mode`. Ignored+ * where it is not a language this application displays.+ */+export async function initTranslations(translationProvider: TranslationProvider, preferredLocale?: string) {+ const locale = isDisplayableLocale(preferredLocale) ? preferredLocale : getCurrentLanguage();await translationProvider(i18next, locale);diff --git a/packages/trilium-core/src/services/setup_existing.spec.ts b/packages/trilium-core/src/services/setup_existing.spec.tsnew file mode 100644index 0000000000..f3fb1999bd--- /dev/null+++ b/packages/trilium-core/src/services/setup_existing.spec.ts@@ -0,0 +1,101 @@+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++import { getBackup } from "./backup.js";+import {+ backUpExistingData,+ backupNameFor,+ deleteExistingData,+ getExistingBackupProgress,+ keepExistingData+} from "./setup_existing.js";+import { enterSetupMode, initSetupPlatform, leaveSetupMode } from "./setup_mode.js";++const platform = {+ writeMarker: vi.fn(async () => {}),+ removeMarker: vi.fn(async () => {}),+ removeDatabase: vi.fn(async () => {})+};++beforeEach(() => {+ Object.values(platform).forEach((fn) => fn.mockClear());+ initSetupPlatform(platform);+ // An instance the app asked into setup, which is the only state these operations belong to.+ enterSetupMode({ lang: "en" });+});++afterEach(() => {+ leaveSetupMode();+ vi.restoreAllMocks();+});++describe("naming the backup", () => {+ it("is dated and readable, and is a filename on every platform", () => {+ expect(backupNameFor(new Date(2026, 7, 7, 10, 32, 21))).toBe("Backup 2026-08-07 10-32-21");+ // Padded, so a directory listing sorts by name and gets chronological order for free.+ expect(backupNameFor(new Date(2026, 0, 2, 3, 4, 5))).toBe("Backup 2026-01-02 03-04-05");+ // A colon is not a filename on Windows, and this one is written to a directory the user opens.+ expect(backupNameFor(new Date())).not.toContain(":");+ });+});++describe("what becomes of the existing database", () => {+ it("backs it up through the platform's own backup service", async () => {+ const written = { fileName: "Backup.tnbackup", filePath: "/b/Backup.tnbackup", fileSize: 12, encrypted: true };+ const backupAs = vi.fn(async (_name: string, _onProgress?: (fraction: number) => void) => written);+ // Assigned rather than spied: the method is optional, and a platform without one is exactly+ // what the service checks for.+ const backup = getBackup() as { backupAs?: typeof backupAs };+ const previous = backup.backupAs;+ backup.backupAs = backupAs;++ await expect(backUpExistingData(new Date(2026, 7, 7, 10, 32, 21))).resolves.toEqual(written);+ expect(backupAs).toHaveBeenCalledWith("Backup 2026-08-07 10-32-21", expect.any(Function));+ // Nothing is erased by taking a copy of it.+ expect(platform.removeDatabase).not.toHaveBeenCalled();++ backup.backupAs = previous;+ });++ it("says how far along the write is while it runs, and nothing once it is over", async () => {+ const seen: (number | null)[] = [];+ const backup = getBackup() as { backupAs?: unknown };+ const previous = backup.backupAs;+ backup.backupAs = async (_name: string, onProgress?: (fraction: number) => void) => {+ seen.push(getExistingBackupProgress());+ onProgress?.(0.5);+ seen.push(getExistingBackupProgress());+ return { fileName: "b", filePath: "/b", fileSize: 1, encrypted: false };+ };++ await backUpExistingData(new Date());++ expect(seen).toEqual([ 0, 0.5 ]);+ // Nothing is running any more, which is what the screen needs to stop drawing a bar.+ expect(getExistingBackupProgress()).toBeNull();++ backup.backupAs = previous;+ });++ it("erases it, and nothing else", async () => {+ await deleteExistingData();++ expect(platform.removeDatabase).toHaveBeenCalled();+ });++ it("puts the instance back as it was when the answer is to keep it", async () => {+ await keepExistingData();++ // The marker goes first: a start that finds one comes up as the wizard all over again.+ expect(platform.removeMarker).toHaveBeenCalled();+ expect(platform.removeDatabase).not.toHaveBeenCalled();+ });++ it("refuses every one of them where there is no existing database to act on", async () => {+ leaveSetupMode();++ await expect(backUpExistingData(new Date())).rejects.toThrow(/first time/);+ await expect(deleteExistingData()).rejects.toThrow(/first time/);+ await expect(keepExistingData()).rejects.toThrow(/first time/);+ expect(platform.removeDatabase).not.toHaveBeenCalled();+ });+});diff --git a/packages/trilium-core/src/services/setup_existing.ts b/packages/trilium-core/src/services/setup_existing.tsnew file mode 100644index 0000000000..31c281afdf--- /dev/null+++ b/packages/trilium-core/src/services/setup_existing.ts@@ -0,0 +1,146 @@+import type { SetupExistingBackup } from "@triliumnext/commons";++import { getBackup } from "./backup.js";+import eventService from "./events.js";+import { getLog } from "./log.js";+import { getSetupPlatform, isInitialSetup, leaveSetupMode } from "./setup_mode.js";+import sqlInit from "./sql_init.js";++/**+ * What becomes of the database an instance was booted away from.+ *+ * Setup normally runs where there is nothing to lose. When the app itself asks for setup there is a+ * whole knowledge base sitting behind the wizard, and the user is asked, before anything else, what+ * should happen to it. That question has exactly three answers, and they are the three functions+ * here: keep it and go back, back it up, or erase it.+ *+ * All three run against a database that is attached but not initialized, which is what setup mode+ * means. That is enough for a backup: options are read straight from the table when becca is not+ * loaded, and the backup itself copies a file. It is deliberately not enough for anything to be+ * written to the database, which nothing here does.+ *+ * @module+ */++/** How the backup is named, since a user reading a directory listing is who has to recognise it. */+const BACKUP_NAME_PREFIX = "Backup";++/**+ * Backs the existing database up, and says where it went.+ *+ * The format is the one the instance is already configured for: compressed or not, encrypted or not,+ * in the chosen directory or the default one. Nothing is asked again here, because the answer is in+ * the options the user already gave, and this is not the moment to be asking about formats.+ *+ * @param now the moment to name the backup after; passed in so the name is the caller's to decide.+ * @throws Error where the platform cannot write a backup, or the write itself failed.+ */+export async function backUpExistingData(now: Date): Promise<SetupExistingBackup> {+ requireExistingData();++ const backup = getBackup();+ if (!backup.backupAs) {+ throw new Error("This platform cannot write a backup of the existing database.");+ }++ getLog().info("Setup: backing up the existing database before it is replaced.");+ progress = 0;++ try {+ const written = await backup.backupAs(backupNameFor(now), reportProgress);+ getLog().info(`Setup: the existing database was backed up (${written.fileSize} bytes).`);++ return written;+ } finally {+ progress = null;+ }+}++/**+ * How far through the backup is, from 0 to 1, or `null` when none is running.+ *+ * Read by the screen that is waiting on it. A backup of a large knowledge base runs for minutes,+ * most of it inside one write that says nothing, and a screen with nothing to show for that long is+ * indistinguishable from one that has stopped.+ */+export function getExistingBackupProgress(): number | null {+ return progress;+}++let progress: number | null = null;+/** The last tenth that was logged, so a long write leaves a trail without flooding the log. */+let loggedTenth = -1;++function reportProgress(fraction: number): void {+ progress = fraction;++ const tenth = Math.floor(fraction * 10);+ if (tenth > loggedTenth) {+ loggedTenth = tenth;+ getLog().info(`Setup: backing up the existing database [${Math.round(fraction * 100)}%]`);+ }+ if (fraction >= 1) {+ loggedTenth = -1;+ }+}++/**+ * Erases the existing database, which is the point of no return.+ *+ * Only ever reached from a screen that has said as much, and only after the user has either taken a+ * backup or refused one. What follows is the rest of the wizard, on an instance that now genuinely+ * has nothing.+ */+export async function deleteExistingData(): Promise<void> {+ requireExistingData();++ getLog().info("Setup: erasing the existing database at the user's request.");+ await getSetupPlatform().removeDatabase();+ getLog().info("Setup: the existing database is gone.");+}++/**+ * Abandons setup and opens the database that was there all along.+ *+ * The way out of every screen in this part of the wizard, including the one that warns about+ * erasure. Nothing has been touched up to this point, so there is nothing to undo: the instance+ * stops answering as uninitialized and comes up as it would have.+ */+export async function keepExistingData(): Promise<void> {+ requireExistingData();++ getLog().info("Setup: leaving the existing database as it was.");+ await getSetupPlatform().removeMarker();+ leaveSetupMode();++ await sqlInit.initDbConnection();+ eventService.emit(eventService.DB_INITIALIZED);+}++/**+ * The name a backup taken here is written under.+ *+ * Spaced and dated rather than slugged, because it is read in a file manager next to backups named+ * after the schedule that took them, and this one wants to be recognisable as the one from the day+ * everything was replaced. The time is dashed: a colon is not a filename on Windows.+ */+export function backupNameFor(now: Date): string {+ const stamp = (value: number) => String(value).padStart(2, "0");+ const date = [ now.getFullYear(), stamp(now.getMonth() + 1), stamp(now.getDate()) ].join("-");+ const time = [ stamp(now.getHours()), stamp(now.getMinutes()), stamp(now.getSeconds()) ].join("-");++ return `${BACKUP_NAME_PREFIX} ${date} ${time}`;+}++/**+ * Refuses everything here on an instance that has nothing to lose.+ *+ * These operations only make sense between an app asking for setup and the wizard getting past the+ * question, and each of them is destructive or irreversible in its own way. A first run reaching+ * them means something is wrong, not that there is an empty database to erase.+ */+function requireExistingData(): void {+ if (isInitialSetup()) {+ throw new Error("There is no existing database: this instance is being set up for the first time.");+ }+}diff --git a/packages/trilium-core/src/services/setup_mode.spec.ts b/packages/trilium-core/src/services/setup_mode.spec.tsindex 82be66669c..158cc896da 100644--- a/packages/trilium-core/src/services/setup_mode.spec.ts+++ b/packages/trilium-core/src/services/setup_mode.spec.ts@@ -4,9 +4,9 @@ import {asSetupTargetScreen,enterSetupMode,getSetupLanguage,- getSetupMarkerStore,+ getSetupPlatform,getSetupTargetScreen,- initSetupMarkerStore,+ initSetupPlatform,isInitialSetup,isSetupRequested,leaveSetupMode,@@ -79,15 +79,16 @@ describe("being in setup because it was asked for", () => {});});-describe("the marker store", () => {+describe("what setup reaches for on its platform", () => {it("carries what a route writes to whichever platform registered itself", async () => {const written: unknown[] = [];- initSetupMarkerStore({- write: async (marker) => { written.push(marker); },- remove: async () => {}+ initSetupPlatform({+ writeMarker: async (marker) => { written.push(marker); },+ removeMarker: async () => {},+ removeDatabase: async () => {}});- await getSetupMarkerStore().write({ lang: "en", targetScreen: "restore-backup" });+ await getSetupPlatform().writeMarker({ lang: "en", targetScreen: "restore-backup" });expect(written).toEqual([ { lang: "en", targetScreen: "restore-backup" } ]);});@@ -95,6 +96,6 @@ describe("the marker store", () => {vi.resetModules();const fresh = await import("./setup_mode.js");- expect(() => fresh.getSetupMarkerStore()).toThrow(/not initialized/);+ expect(() => fresh.getSetupPlatform()).toThrow(/not initialized/);});});diff --git a/packages/trilium-core/src/services/setup_mode.ts b/packages/trilium-core/src/services/setup_mode.tsindex 3a5a7f05bc..476510b613 100644--- a/packages/trilium-core/src/services/setup_mode.ts+++ b/packages/trilium-core/src/services/setup_mode.ts@@ -114,27 +114,34 @@ export function asSetupTargetScreen(value: unknown): SetupTargetScreen | undefin}/**- * Where the marker is kept, which is somewhere only the platform knows.+ * What setup needs of the platform it is running on.*- * Reading it is the platform's business too, and happens before any of this exists, so only the- * writing side is registered here: a route shared by every platform has to be able to ask for setup- * without knowing whether it is writing to a disk or to the browser's own storage.+ * The marker and the database both live somewhere only the platform knows: a data directory on a+ * disk, or the origin's private filesystem in a browser. Reading the marker is the platform's own+ * business and happens before any of this exists, so only what a shared route has to reach is here.*/-export interface SetupMarkerStore {- write(marker: SetupMarker): Promise<void>;- remove(): Promise<void>;+export interface SetupPlatform {+ /** Leaves the marker that makes the next start the wizard. */+ writeMarker(marker: SetupMarker): Promise<void>;+ /** Takes it back, for a request that was made and then abandoned. */+ removeMarker(): Promise<void>;+ /**+ * Erases the database this instance was booted away from, and only that: backups, configuration+ * and the stored passphrase are what a user who deletes by mistake has left, and they stay.+ */+ removeDatabase(): Promise<void>;}-let store: SetupMarkerStore | null = null;+let platform: SetupPlatform | null = null;-export function initSetupMarkerStore(instance: SetupMarkerStore): void {- store = instance;+export function initSetupPlatform(instance: SetupPlatform): void {+ platform = instance;}-export function getSetupMarkerStore(): SetupMarkerStore {- if (!store) {- throw new Error("Setup marker store not initialized.");+export function getSetupPlatform(): SetupPlatform {+ if (!platform) {+ throw new Error("Setup platform not initialized.");}- return store;+ return platform;}diff --git a/packages/trilium-core/src/services/sql/sql.spec.ts b/packages/trilium-core/src/services/sql/sql.spec.tsindex fe29bf4d3a..6bf5a22016 100644--- a/packages/trilium-core/src/services/sql/sql.spec.ts+++ b/packages/trilium-core/src/services/sql/sql.spec.ts@@ -1,7 +1,9 @@import { beforeAll, describe, expect, it } from "vitest";import { getContext } from "../context.js";+import { getLog } from "../log.js";import { getSql } from "./index.js";+import { SqlService, type SqlServiceParams } from "./sql.js";// happy-dom (standalone/WASM) exposes `window`; the Node server suite does not.const isBrowserRuntime = typeof window !== "undefined";@@ -350,6 +352,28 @@ describe("SqlService (real DB)", () => {});});+ describe("detaching", () => {+ it("lets go once, and says nothing the second time", () => {+ // The setup screen erases the database, which detaches it; a restore started straight+ // afterwards detaches again on its way to swapping the files in. That second one has+ // nothing to do, and used to fail on a connection that was already gone.+ let attached = true;+ const provider = {+ detach: () => { attached = false; },+ isAttached: () => attached,+ get inTransaction(): boolean {+ if (!attached) throw new Error("DB not open.");+ return false;+ }+ };+ const sql = new SqlService({ provider } as unknown as SqlServiceParams, getLog());++ sql.detachConnection();+ expect(attached).toBe(false);+ expect(() => sql.detachConnection()).not.toThrow();+ });+ });+describe("serialize", () => {it("either throws (provider unsupported) or returns the serialized bytes", () => {// Capability-aware: the server's better-sqlite3 provider has nodiff --git a/packages/trilium-core/src/services/sql/sql.ts b/packages/trilium-core/src/services/sql/sql.tsindex 11c2e9579b..95c1d5d153 100644--- a/packages/trilium-core/src/services/sql/sql.ts+++ b/packages/trilium-core/src/services/sql/sql.ts@@ -55,6 +55,12 @@ export class SqlService {if (!this.dbConnection.detach) {throw new Error("Database provider does not support detaching.");}+ // Nothing to let go of: the database was erased before this, which is what the setup screen+ // does when the user asks for it, and a restore that follows would otherwise fail here on a+ // connection that is already gone.+ if (this.dbConnection.isAttached?.() === false) {+ return;+ }if (this.dbConnection.inTransaction) {throw new Error("Cannot detach the database in the middle of a transaction.");}diff --git a/packages/trilium-core/src/services/sql/types.ts b/packages/trilium-core/src/services/sql/types.tsindex 7927696bb5..633768b89e 100644--- a/packages/trilium-core/src/services/sql/types.ts+++ b/packages/trilium-core/src/services/sql/types.ts@@ -37,6 +37,14 @@ export interface DatabaseProvider {* Optional - only implemented where the database is a file that can be replaced underneath.*/detach?(): void;+ /**+ * Whether there is a connection at all. Answers `false` between a {@link detach} and the+ * `loadFrom*` that follows it, which is a window a restore runs inside and an erased database+ * never leaves.+ *+ * Optional, and treated as "attached" where a provider does not answer.+ */+ isAttached?(): boolean;prepare(query: string): Statement;transaction<T>(func: (statement: Statement) => T): Transaction;get inTransaction(): boolean;