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
core/setup: add a method to boot again to the setup screen
Adorian Doran08fedd0ee369
diff --git a/apps/client/src/services/setup_mode.spec.ts b/apps/client/src/services/setup_mode.spec.tsnew file mode 100644index 0000000000..b4f2e5f00f--- /dev/null+++ b/apps/client/src/services/setup_mode.spec.ts@@ -0,0 +1,71 @@+import { beforeEach, describe, expect, it, vi } from "vitest";++const mocks = vi.hoisted(() => ({+ post: vi.fn(),+ restartDesktopApp: vi.fn(),+ isElectron: vi.fn(() => false),+ isStandalone: false+}));++vi.mock("./server", () => ({ default: { post: mocks.post } }));+vi.mock("./utils", () => ({+ restartDesktopApp: mocks.restartDesktopApp,+ isElectron: mocks.isElectron,+ get isStandalone() { return mocks.isStandalone; }+}));++async function freshModule() {+ vi.resetModules();+ return import("./setup_mode.js");+}++beforeEach(() => {+ mocks.post.mockReset().mockResolvedValue(undefined);+ mocks.restartDesktopApp.mockReset();+ mocks.isElectron.mockReset().mockReturnValue(false);+ mocks.isStandalone = false;+});++describe("asking the next start to be the setup wizard", () => {+ it("writes down what was asked for, then starts the app again", async () => {+ mocks.isElectron.mockReturnValue(true);+ const { bootToSetup } = await freshModule();++ await bootToSetup({ targetScreen: "restore-backup" });++ expect(mocks.post).toHaveBeenCalledWith("setup/boot", { targetScreen: "restore-backup" });+ // In that order: a restart before the marker is written comes back to the app.+ expect(mocks.restartDesktopApp).toHaveBeenCalled();+ expect(mocks.post.mock.invocationCallOrder[0])+ .toBeLessThan(mocks.restartDesktopApp.mock.invocationCallOrder[0]);+ });++ it("may be asked for without a screen, which is where a first run starts", async () => {+ mocks.isStandalone = true;+ const { bootToSetup } = await freshModule();++ await bootToSetup();++ expect(mocks.post).toHaveBeenCalledWith("setup/boot", { targetScreen: undefined });+ });++ it("refuses where the app cannot start itself again, rather than leaving a marker behind", async () => {+ // A browser talking to a server reloads only itself: the server keeps the database open and+ // would find the marker at some unrelated restart, days later.+ const { bootToSetup, canBootToSetup } = await freshModule();++ expect(canBootToSetup()).toBe(false);+ await expect(bootToSetup({ targetScreen: "restore-backup" })).rejects.toThrow(/cannot restart/);+ expect(mocks.post).not.toHaveBeenCalled();+ expect(mocks.restartDesktopApp).not.toHaveBeenCalled();+ });++ it("is offered on the two builds that come back to a real start", async () => {+ mocks.isElectron.mockReturnValue(true);+ expect((await freshModule()).canBootToSetup()).toBe(true);++ mocks.isElectron.mockReturnValue(false);+ mocks.isStandalone = true;+ expect((await freshModule()).canBootToSetup()).toBe(true);+ });+});diff --git a/apps/client/src/services/setup_mode.ts b/apps/client/src/services/setup_mode.tsnew file mode 100644index 0000000000..bcb4f154b7--- /dev/null+++ b/apps/client/src/services/setup_mode.ts@@ -0,0 +1,43 @@+import type { SetupTargetScreen } from "@triliumnext/commons";++import server from "./server";+import { isElectron, isStandalone, restartDesktopApp } from "./utils";++/**+ * Sends the instance into the setup wizard, from inside the running app.+ *+ * Some things a user can ask for need the setup screen and need the database closed while they+ * happen: restoring a backup is the first of them. Rather than doing that underneath a running app,+ * the instance writes down what was asked for and starts again, and the start that follows finds the+ * marker and comes up as the wizard. See `setup_mode` in core for the other half.+ *+ * The language is not passed from here. It is filled in on the way out from the instance's own+ * option, because it has to be the language of the database that is about to be left closed.+ *+ * @param options where the wizard should open, and nothing else yet.+ * @throws Error where this build cannot start again, so no marker is left to be found much later.+ */+export async function bootToSetup(options: { targetScreen?: SetupTargetScreen } = {}): Promise<void> {+ if (!canBootToSetup()) {+ throw new Error("This build cannot restart itself, so it cannot boot into setup.");+ }++ await server.post("setup/boot", { targetScreen: options.targetScreen });++ // Electron relaunches, which is a real start with nothing attached. Everywhere else reloads,+ // which for the browser-only build tears down the worker holding the database and amounts to+ // the same thing.+ restartDesktopApp();+}++/**+ * Whether this build can act on a marker at all.+ *+ * The desktop relaunches and the browser-only build reloads its worker, so both come back to a start+ * that reads the marker. A browser talking to a server reloads only itself, leaving the server+ * running with the database open and the marker unread until it is next restarted, which could be+ * days later and would be the last thing the user expected. So it is not offered there yet.+ */+export function canBootToSetup(): boolean {+ return isElectron() || isStandalone;+}diff --git a/apps/client/src/setup.spec.tsx b/apps/client/src/setup.spec.tsxindex a74dc27347..6372b7e9e1 100644--- a/apps/client/src/setup.spec.tsx+++ b/apps/client/src/setup.spec.tsx@@ -22,7 +22,7 @@ const serverMock = vi.hoisted(() => ({}));vi.mock("./services/server", () => ({ default: serverMock }));-import { renderState, SyncFailed, SyncFromServer, SyncInProgress } from "./setup";+import { initialState, renderState, SyncFailed, SyncFromServer, SyncInProgress } from "./setup";type Stats = { outstandingPullCount: number; totalPullCount: number | null; initialized: boolean; lastSyncError?: string | null };@@ -196,3 +196,24 @@ describe("SyncFromServer", () => {expect(host?.value).toBe("");});});++describe("where the wizard opens", () => {+ it("starts at the language step on a first run", () => {+ expect(initialState({})).toBe("selectLanguage");+ });++ it("goes where a setup marker asked, which is how the app sends a user here", () => {+ expect(initialState({ setupTargetScreen: "restore-backup" })).toBe("restoreFromBackup");+ });++ 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");+ });++ it("ignores a screen it does not know rather than guessing at one", () => {+ expect(initialState({ setupTargetScreen: "createNewDocumentEmpty" as never }))+ .toBe("selectLanguage");+ });+});diff --git a/apps/client/src/setup.tsx b/apps/client/src/setup.tsxindex aab1fa416a..49d3711e4a 100644--- a/apps/client/src/setup.tsx+++ b/apps/client/src/setup.tsx@@ -1,6 +1,6 @@import "./setup.css";-import { LOCALES, MOBILE_SYNC_MAX_BLOB_CONTENT_SIZE, NetworkAddressesResponse, SetupSyncFromServerResponse } from "@triliumnext/commons";+import { LOCALES, MOBILE_SYNC_MAX_BLOB_CONTENT_SIZE, NetworkAddressesResponse, SetupSyncFromServerResponse, type SetupTargetScreen } from "@triliumnext/commons";import clsx from "clsx";import { render } from "preact";import { useEffect, useMemo, useRef, useState } from "preact/hooks";@@ -65,7 +65,7 @@ function App() {// A sync that already created the schema but was interrupted before finishing// resumes straight on the progress screen instead of restarting the wizard.const resuming = window.glob.syncInProgress === true;- const [state, setState] = useState<State>(resuming ? "syncFromServerInProgress" : "selectLanguage");+ const [state, setState] = useState<State>(initialState(window.glob));useEffect(() => {if (!resuming) {@@ -90,6 +90,27 @@ function App() {);}+/**+ * 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.+ */+export function initialState(glob: { syncInProgress?: boolean; setupTargetScreen?: SetupTargetScreen }): State {+ if (glob.syncInProgress) {+ return "syncFromServerInProgress";+ }++ switch (glob.setupTargetScreen) {+ case "restore-backup": return "restoreFromBackup";+ // Deliberately not a lookup table: two of the states below create a document the moment they+ // are shown, and nothing outside this file should be able to name one.+ default: return "selectLanguage";+ }+}+function SelectLanguage({ setState }: { setState: (state: State) => void }) {const { t, i18n } = useTranslation();const [ currentLocale, setCurrentLocale ] = useState(i18n.language);diff --git a/apps/desktop/src/main.ts b/apps/desktop/src/main.tsindex a0bf60fdde..a0e2fd5eb0 100644--- a/apps/desktop/src/main.ts+++ b/apps/desktop/src/main.ts@@ -9,6 +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 { 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";@@ -278,6 +279,10 @@ export async function main() {),image: (await import("@triliumnext/server/src/services/image_provider.js")).serverImageProvider,config,+ // 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,extraAppInfo: {nodeVersion: process.version,dataDirectory: path.resolve(dataDirs.TRILIUM_DATA_DIR)diff --git a/apps/server/src/main.ts b/apps/server/src/main.tsindex 4e98d14538..93fc39c723 100644--- a/apps/server/src/main.ts+++ b/apps/server/src/main.ts@@ -19,6 +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 WebSocketMessagingProvider from "./services/ws_messaging_provider.js";import BetterSqlite3Provider from "./sql_provider.js";import NodejsZipProvider from "./zip_provider.js";@@ -88,6 +89,9 @@ async function startApplication() {backup: new ServerBackupService(options),image: (await import("./services/image_provider.js")).serverImageProvider,config,+ // Read before core exists, because what it says is whether to open the database at all.+ setupMarker: consumeSetupMarker(),+ setupMarkerStore,extraAppInfo: {nodeVersion: process.version,dataDirectory: path.resolve(dataDirs.TRILIUM_DATA_DIR)diff --git a/apps/server/src/services/database_restore.ts b/apps/server/src/services/database_restore.tsindex b4a4bdbfd3..56de889552 100644--- a/apps/server/src/services/database_restore.ts+++ b/apps/server/src/services/database_restore.ts@@ -12,6 +12,7 @@ import {events as eventService,getLog,getSql,+ leaveSetupMode,sql_init as sqlInit,utils as coreUtils} from "@triliumnext/core";@@ -533,6 +534,10 @@ async function openRestoredDatabase(needsMigration: boolean): Promise<void> {? "opening the restored database, which is being migrated first and may take a while": "opening the restored database");+ // Whatever asked this instance into setup has had its answer, and until this is said the+ // instance keeps reporting that it has nothing to open, which is what `initDbConnection` checks.+ leaveSetupMode();+try {await sqlInit.initDbConnection();} catch (e) {diff --git a/apps/server/src/services/setup_marker.spec.ts b/apps/server/src/services/setup_marker.spec.tsnew file mode 100644index 0000000000..a6a6d53fc2--- /dev/null+++ b/apps/server/src/services/setup_marker.spec.ts@@ -0,0 +1,54 @@+import { SETUP_MARKER_FILE_NAME } from "@triliumnext/commons";+import fs from "fs";+import path from "path";+import { afterEach, describe, expect, it } from "vitest";++import dataDirs from "./data_dir.js";+import { consumeSetupMarker, setupMarkerStore } from "./setup_marker.js";++const MARKER_PATH = path.join(dataDirs.TRILIUM_DATA_DIR, SETUP_MARKER_FILE_NAME);++function writeMarkerFile(contents: string) {+ fs.writeFileSync(MARKER_PATH, contents, "utf8");+}++afterEach(() => fs.rmSync(MARKER_PATH, { force: true }));++describe("the marker a start finds", () => {+ it("is nothing at all on an ordinary start", () => {+ expect(consumeSetupMarker()).toBeNull();+ });++ it("is read and then gone, so the start after this one is an ordinary one", () => {+ writeMarkerFile(JSON.stringify({ lang: "ro", targetScreen: "restore-backup" }));++ expect(consumeSetupMarker()).toEqual({ lang: "ro", targetScreen: "restore-backup" });+ expect(fs.existsSync(MARKER_PATH)).toBe(false);+ expect(consumeSetupMarker()).toBeNull();+ });++ it("is removed even when it could not be read, so a bad one cannot trap the instance", () => {+ writeMarkerFile("half a file, written by a start that was interrupted");++ expect(consumeSetupMarker()).toBeNull();+ expect(fs.existsSync(MARKER_PATH)).toBe(false);+ });+});++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" });++ 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();+ 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();+ });+});diff --git a/apps/server/src/services/setup_marker.ts b/apps/server/src/services/setup_marker.tsnew file mode 100644index 0000000000..2f18dd83df--- /dev/null+++ b/apps/server/src/services/setup_marker.ts@@ -0,0 +1,67 @@+import { SETUP_MARKER_FILE_NAME, type SetupMarker } from "@triliumnext/commons";+import { getLog, parseSetupMarker, type SetupMarkerStore } from "@triliumnext/core";+import fs from "fs";+import path from "path";++import dataDirs from "./data_dir.js";++/**+ * The `setup.json` marker on a filesystem, for the server and the desktop.+ *+ * Reading it is separate from everything else here because of when it happens: before the database+ * is opened and before core exists, since what it says is whether to open the database at all. See+ * `setup_mode` in core for what it is for.+ *+ * @module+ */++function markerPath(): string {+ return path.join(dataDirs.TRILIUM_DATA_DIR, SETUP_MARKER_FILE_NAME);+}++/**+ * Reads the marker this start was left, and deletes it.+ *+ * Deleted on read rather than when the wizard is done with it: a marker that outlives its purpose+ * puts the instance in setup with no way out, which is worse than the reload it protects against.+ * What it asked for lives on in memory for this process, so a page reloaded mid-wizard still comes+ * back to the same screen, while a genuine restart comes back to the app.+ *+ * Never throws. A marker that cannot be read is one the instance is better off without.+ */+export function consumeSetupMarker(): SetupMarker | null {+ const filePath = markerPath();++ let raw: string;+ try {+ raw = fs.readFileSync(filePath, "utf8");+ } catch {+ // Overwhelmingly: there is no marker, which is what an ordinary start looks like.+ return null;+ }++ try {+ fs.rmSync(filePath, { force: true });+ } catch (e) {+ // Left behind, it would send the next start into setup as well. Worth saying out loud.+ getLog().error(`Could not remove the setup marker: ${e instanceof Error ? e.message : String(e)}`);+ }++ const marker = parseSetupMarker(raw);+ if (!marker) {+ getLog().error("The setup marker could not be read and was ignored.");+ }++ 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) {+ fs.writeFileSync(markerPath(), JSON.stringify(marker, null, 4), "utf8");+ },++ async remove() {+ fs.rmSync(markerPath(), { force: true });+ }+};diff --git a/apps/standalone/src/lightweight/setup_marker.spec.ts b/apps/standalone/src/lightweight/setup_marker.spec.tsnew file mode 100644index 0000000000..d80d37db40--- /dev/null+++ b/apps/standalone/src/lightweight/setup_marker.spec.ts@@ -0,0 +1,78 @@+import { SETUP_MARKER_FILE_NAME } from "@triliumnext/commons";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++import { consumeSetupMarker, setupMarkerStore } from "./setup_marker.js";++/** Stands in for the origin's private filesystem, which is where the marker lives here. */+let files: Map<string, string>;++beforeEach(() => {+ files = new Map();+ vi.stubGlobal("navigator", {+ storage: {+ getDirectory: async () => ({+ getFileHandle: async (name: string, opts?: { create?: boolean }) => {+ if (!files.has(name)) {+ if (!opts?.create) {+ throw new Error("NotFoundError");+ }+ files.set(name, "");+ }++ return {+ getFile: async () => ({ text: async () => files.get(name) ?? "" }),+ createWritable: async () => ({+ write: async (text: string) => { files.set(name, text); },+ close: async () => {}+ })+ };+ },+ removeEntry: async (name: string) => {+ if (!files.delete(name)) {+ throw new Error("NotFoundError");+ }+ }+ })+ }+ });+});++afterEach(() => vi.unstubAllGlobals());++describe("the marker a start finds", () => {+ it("is nothing at all on an ordinary start", async () => {+ await expect(consumeSetupMarker()).resolves.toBeNull();+ });++ it("is read and then gone, so the start after this one is an ordinary one", async () => {+ files.set(SETUP_MARKER_FILE_NAME, JSON.stringify({ lang: "ro", targetScreen: "restore-backup" }));++ await expect(consumeSetupMarker()).resolves.toEqual({ lang: "ro", targetScreen: "restore-backup" });+ expect(files.has(SETUP_MARKER_FILE_NAME)).toBe(false);+ await expect(consumeSetupMarker()).resolves.toBeNull();+ });++ it("is removed even when it could not be read, so a bad one cannot trap the instance", async () => {+ files.set(SETUP_MARKER_FILE_NAME, "half a file, written by a start that was interrupted");++ await expect(consumeSetupMarker()).resolves.toBeNull();+ expect(files.has(SETUP_MARKER_FILE_NAME)).toBe(false);+ });+});++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 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();+ 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();+ });+});diff --git a/apps/standalone/src/lightweight/setup_marker.ts b/apps/standalone/src/lightweight/setup_marker.tsnew file mode 100644index 0000000000..1cec5772e8--- /dev/null+++ b/apps/standalone/src/lightweight/setup_marker.ts@@ -0,0 +1,66 @@+import { SETUP_MARKER_FILE_NAME, type SetupMarker } from "@triliumnext/commons";+import { parseSetupMarker, type SetupMarkerStore } from "@triliumnext/core";++/**+ * The `setup.json` marker in the browser's own storage.+ *+ * The same file the server and the desktop keep in the data directory, kept here in the origin's+ * private filesystem beside the database pointer, for the same reason and read at the same moment:+ * before the database is opened, since what it says is whether to open it at all. See `setup_mode`+ * in core.+ *+ * Reloading the page is what a restart is here, since it tears down the worker that holds the+ * database and starts another one, so this platform gets the same boot-into-setup that a relaunch+ * gives the desktop.+ *+ * @module+ */++/**+ * Reads the marker this start was left, and deletes it.+ *+ * Deleted on read for the reason the other platforms delete it: a marker that outlives its purpose+ * puts the instance in setup with no way out. What it asked for lives on in memory for as long as+ * this worker does.+ *+ * Never throws. A marker that cannot be read is one the instance is better off without.+ */+export async function consumeSetupMarker(): Promise<SetupMarker | null> {+ let raw: string;++ try {+ const root = await navigator.storage.getDirectory();+ const handle = await root.getFileHandle(SETUP_MARKER_FILE_NAME);+ raw = await (await handle.getFile()).text();+ await root.removeEntry(SETUP_MARKER_FILE_NAME);+ } catch {+ // Overwhelmingly: there is no marker, which is what an ordinary start looks like.+ return 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();++ 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.+ }+ }+};diff --git a/apps/standalone/src/local-server-worker.ts b/apps/standalone/src/local-server-worker.tsindex abc2434916..bde9bf6597 100644--- a/apps/standalone/src/local-server-worker.ts+++ b/apps/standalone/src/local-server-worker.ts@@ -50,6 +50,7 @@ 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';// Build-time constant injected by Vite (see `define` in vite.config.mts).declare const __TRILIUM_INTEGRATION_TEST__: string;@@ -272,6 +273,10 @@ async function initialize(): Promise<void> {},inAppHelp: new StandaloneInAppHelpProvider(),image: (await import("./services/image_provider.js")).standaloneImageProvider,+ // 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,dbConfig: {provider: sqlProvider!,isReadOnly: false,@@ -411,6 +416,10 @@ async function handleRestoreBackup(id: string, backup: File, passphrase?: string{ passphrase, report: ({ stage, fraction }) => report({ stage, fraction }) });+ // Whatever asked this instance into setup has had its answer, and until this is said the+ // instance keeps reporting that it has nothing to open, which is what the next line checks.+ core.leaveSetupMode();+// What the "create new document" path announces for the same reason: everything that waits// on a database being there starts from here.await core.sql_init.initDbConnection();diff --git a/packages/commons/src/index.ts b/packages/commons/src/index.tsindex 98e0a3ac55..585285668a 100644--- a/packages/commons/src/index.ts+++ b/packages/commons/src/index.ts@@ -28,6 +28,7 @@ export { default as BUILTIN_ATTRIBUTES } from "./lib/builtin_attributes.js";// barrel is imported by virtually every client module. Import them via their subpath instead,// e.g. "@triliumnext/commons/src/lib/spreadsheet/render_to_html".export * from "./lib/electron_api_interface.js";+export * from "./lib/setup_marker.js";export * from "./lib/standalone_api_interface.js";export * from "./lib/favicon_contrast.js";export * from "./lib/link_embed.js";diff --git a/packages/commons/src/lib/server_api.ts b/packages/commons/src/lib/server_api.tsindex 4a9027b6a1..17ada60b6f 100644--- a/packages/commons/src/lib/server_api.ts+++ b/packages/commons/src/lib/server_api.ts@@ -1,5 +1,6 @@import type { Locale } from "./i18n.js";import { AttachmentRow, AttributeRow, BranchRow, NoteRow, NoteType, OptionRow, RevisionSource } from "./rows.js";+import type { SetupTargetScreen } from "./setup_marker.js";type Response = {success: true,@@ -843,6 +844,19 @@ export type BootstrapDefinition = {* jump straight back to the sync-in-progress step and resume the sync on restart.*/syncInProgress?: boolean;+ /**+ * Whether this is the instance's first run, with no database behind the setup screen.+ *+ * Only meaningful while `dbInitialized` is `false`. It is `false` when setup was asked for by a+ * running instance through a `setup.json` marker, which means there is a database to go back to+ * and the wizard may offer to leave without doing anything.+ */+ initialSetup?: boolean;+ /**+ * The screen the wizard should open on, from the marker that asked for setup. Only meaningful+ * while `dbInitialized` is `false`, and absent for a first run, which starts at the language step.+ */+ setupTargetScreen?: SetupTargetScreen;/*** Whether a password has been set yet. `false` only in the pre-auth window* after the database is initialized but before the user has set a password,diff --git a/packages/commons/src/lib/setup_marker.ts b/packages/commons/src/lib/setup_marker.tsnew file mode 100644index 0000000000..a9ca774abf--- /dev/null+++ b/packages/commons/src/lib/setup_marker.ts@@ -0,0 +1,33 @@+/**+ * The file a running instance leaves behind to ask the next start to come up in setup.+ *+ * Setup is normally where an instance goes because it has no database. This is the other way in: an+ * instance that has one, and wants to be somewhere in the wizard anyway, writes this file and+ * restarts. The start that follows reads it, deliberately leaves the database closed, and opens the+ * screen it names.+ *+ * Everything the wizard needs from the database has to be in here, because by then the database is+ * not open. That is what {@link SetupMarker.lang} is for: without it the wizard would come up in+ * English and ask a user who has already answered that question.+ *+ * @module+ */++/** Where the marker is kept: the data directory, beside the database it is asking to bypass. */+export const SETUP_MARKER_FILE_NAME = "setup.json";++/**+ * The screen the wizard should open on.+ *+ * 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";++/** 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. */+ lang: string;+ /** Where to go. Absent leaves the wizard where a first run starts, at the language step. */+ targetScreen?: SetupTargetScreen;+}diff --git a/packages/trilium-core/src/index.ts b/packages/trilium-core/src/index.tsindex 16d562257e..03751c3bc5 100644--- a/packages/trilium-core/src/index.ts+++ b/packages/trilium-core/src/index.ts@@ -1,3 +1,5 @@+import type { SetupMarker } from "@triliumnext/commons";+import { ExecutionContext, initContext } from "./services/context";import { CryptoProvider, initCrypto } from "./services/encryption/crypto";import LogService, { getLog, initLog } from "./services/log";@@ -6,7 +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 { initTranslations, TranslationProvider } from "./services/i18n";+import { changeLanguage, initTranslations, TranslationProvider } from "./services/i18n";+import { enterSetupMode, initSetupMarkerStore, type SetupMarkerStore } from "./services/setup_mode";import { initSchema, initDemoArchive } from "./services/sql_init";import appInfo from "./services/app_info";import { type PlatformProvider, initPlatform } from "./services/platform";@@ -23,6 +26,15 @@ export type * from "./services/sql/types";export * from "./services/sql/index";export { default as sql_init } from "./services/sql_init";export { getRunningSetupOperation, holdSetup, withSetupLock } from "./services/setup_lock";+export {+ getSetupLanguage,+ getSetupTargetScreen,+ isInitialSetup,+ isSetupRequested,+ leaveSetupMode,+ parseSetupMarker,+ type SetupMarkerStore+} from "./services/setup_mode";export {type CandidateDatabase,type DatabaseRejection,@@ -150,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 }: {+export async function initializeCore({ dbConfig, executionContext, crypto, zip, zipExportProviderFactory, translations, messaging, request, schema, extraAppInfo, platform, getDemoArchive, inAppHelp, log, backup, image, config, setupMarker, setupMarkerStore }: {dbConfig: SqlServiceParams,executionContext: ExecutionContext,crypto: CryptoProvider,@@ -171,6 +183,13 @@ export async function initializeCore({ dbConfig, executionContext, crypto, zip,backup: BackupService;image: ImageProvider;config?: CoreConfig;+ /**+ * The `setup.json` a running instance left behind for this start, already read and deleted by+ * the platform. Its presence keeps the database closed and sends the client to the setup screen.+ */+ setupMarker?: SetupMarker | null;+ /** How this platform writes that file, for the route that asks for the next start to be setup. */+ setupMarkerStore?: SetupMarkerStore;}) {if (config) {initConfig(config);@@ -178,7 +197,19 @@ export async function initializeCore({ dbConfig, executionContext, crypto, zip,initPlatform(platform);initLog(log);initBackup(backup);+ // 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);+ }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 f59b49765d..800e664294 100644--- a/packages/trilium-core/src/routes/api/setup.ts+++ b/packages/trilium-core/src/routes/api/setup.ts@@ -1,6 +1,7 @@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 { getLog } from "../../services/log.js";import appInfo from "../../services/app_info.js";import optionService from "../../services/options.js";@@ -31,6 +32,24 @@ function getStatus() {};}+/**+ * Asks the next start of this instance to come up in the setup wizard rather than in the app.+ *+ * Writes the marker and answers; restarting is the caller's half, since only the client knows how+ * this platform restarts. The language is filled in here from the instance's own option rather than+ * taken from the request: it has to be the language whose database is about to be left closed.+ */+async function bootToSetup(req: Request) {+ const targetScreen = asSetupTargetScreen(req.body?.targetScreen);++ await getSetupMarkerStore().write({+ lang: optionService.getOptionOrNull("locale") ?? "en",+ ...(targetScreen ? { targetScreen } : {})+ });++ getLog().info(`Boot to setup requested${targetScreen ? ` for "${targetScreen}"` : ""}.`);+}+async function setupNewDocument(req: Request) {const { skipDemoDb } = req.query;const locale = req.body?.locale;@@ -115,6 +134,7 @@ function getSyncSeed() {export default {getStatus,+ bootToSetup,setupNewDocument,setupSyncFromServer,getSyncSeed,diff --git a/packages/trilium-core/src/routes/index.ts b/packages/trilium-core/src/routes/index.tsindex 9f2374fa6d..5e4af1fe0f 100644--- a/packages/trilium-core/src/routes/index.ts+++ b/packages/trilium-core/src/routes/index.ts@@ -150,6 +150,9 @@ export function buildSharedApiRoutes({ route, asyncRoute, apiRoute, asyncApiRoutasyncRoute(PST, "/api/setup/sync-from-server", [checkAppNotInitialized], setupApiRoute.setupSyncFromServer, apiResultHandler);route(GET, "/api/setup/sync-seed", [loginRateLimiter, checkCredentials], setupApiRoute.getSyncSeed, apiResultHandler);asyncRoute(PST, "/api/setup/sync-seed", [checkAppNotInitialized], setupApiRoute.saveSyncSeed, apiResultHandler);+ // The one setup route that belongs to a running instance rather than to one without a database:+ // it is how the app asks the next start to be the wizard.+ asyncApiRoute(PST, "/api/setup/boot", setupApiRoute.bootToSetup);asyncApiRoute(PST, "/api/sync/test", syncApiRoute.testSync);asyncApiRoute(PST, "/api/sync/now", syncApiRoute.syncNow);diff --git a/packages/trilium-core/src/services/bootstrap_utils.spec.ts b/packages/trilium-core/src/services/bootstrap_utils.spec.tsindex cff47d56f9..766254ebc3 100644--- a/packages/trilium-core/src/services/bootstrap_utils.spec.ts+++ b/packages/trilium-core/src/services/bootstrap_utils.spec.ts@@ -5,6 +5,7 @@ import getSharedBootstrapItems, { getIconConfig } from "./bootstrap_utils.js";import * as cls from "./context.js";import notes from "./notes.js";import options from "./options.js";+import { enterSetupMode, leaveSetupMode } from "./setup_mode.js";import sqlInit from "./sql_init.js";const ASSET_PATH = "assets-x";@@ -59,6 +60,27 @@ describe("bootstrap_utils (real DB)", () => {}});+ it("tells the wizard where to open, and that it has a database to go back to", () => {+ const schemaSpy = vi.spyOn(sqlInit, "schemaExists").mockReturnValue(true);+ try {+ // A first run: nowhere in particular to go, and nothing behind the wizard.+ expect(getSharedBootstrapItems(ASSET_PATH, false)).toMatchObject({+ initialSetup: true, setupTargetScreen: undefined+ });++ enterSetupMode({ lang: "ro", targetScreen: "restore-backup" });+ const items = getSharedBootstrapItems(ASSET_PATH, false);++ expect(items).toMatchObject({ initialSetup: false, setupTargetScreen: "restore-backup" });+ // The schema of a finished database says nothing about an interrupted sync, so the+ // wizard must not be sent to the sync-progress screen instead of the one asked for.+ expect(items.syncInProgress).toBe(false);+ } finally {+ leaveSetupMode();+ schemaSpy.mockRestore();+ }+ });+it("returns the full payload once the DB is initialized, including app CSS note ids", () => {const appCssNoteId = cls.init(() => {const { note } = notes.createNewNote({diff --git a/packages/trilium-core/src/services/bootstrap_utils.ts b/packages/trilium-core/src/services/bootstrap_utils.tsindex 2537c3142c..df36be0c30 100644--- a/packages/trilium-core/src/services/bootstrap_utils.ts+++ b/packages/trilium-core/src/services/bootstrap_utils.ts@@ -8,6 +8,7 @@ import { getCurrentLocale } from "./i18n";import attributes from "./attributes";import BNote from "../becca/entities/bnote";import { getPlatform } from "./platform";+import { getSetupTargetScreen, isInitialSetup, isSetupRequested } from "./setup_mode";import sqlInit from "./sql_init";export default function getSharedBootstrapItems(assetPath: string, dbInitialized: boolean) {@@ -25,8 +26,13 @@ export default function getSharedBootstrapItems(assetPath: string, dbInitializedcomponentId: "",// Schema present but not yet initialized means a sync was started and interrupted, so the// setup screen resumes it instead of starting over. A fully initialized DB is never mid-sync.- // Kept in the common items so both payload shapes carry the flag uniformly.- syncInProgress: !dbInitialized && sqlInit.schemaExists(),+ // Kept in the common items so both payload shapes carry the flag uniformly. An instance that+ // was asked into setup has a finished database behind it, so its schema says nothing here.+ syncInProgress: !dbInitialized && !isSetupRequested() && sqlInit.schemaExists(),+ // Where the wizard should open, and whether it has anywhere to go back to. Only a marker+ // says otherwise; a first run leaves both at their first-run answers.+ initialSetup: isInitialSetup(),+ setupTargetScreen: getSetupTargetScreen(),...getIconConfig(assetPath)};diff --git a/packages/trilium-core/src/services/setup_mode.spec.ts b/packages/trilium-core/src/services/setup_mode.spec.tsnew file mode 100644index 0000000000..82be66669c--- /dev/null+++ b/packages/trilium-core/src/services/setup_mode.spec.ts@@ -0,0 +1,100 @@+import { afterEach, describe, expect, it, vi } from "vitest";++import {+ asSetupTargetScreen,+ enterSetupMode,+ getSetupLanguage,+ getSetupMarkerStore,+ getSetupTargetScreen,+ initSetupMarkerStore,+ isInitialSetup,+ isSetupRequested,+ leaveSetupMode,+ parseSetupMarker+} from "./setup_mode.js";++afterEach(() => leaveSetupMode());++describe("reading a marker", () => {+ it("takes the language and the screen it names", () => {+ expect(parseSetupMarker(`{ "lang": "ro", "targetScreen": "restore-backup" }`))+ .toEqual({ lang: "ro", targetScreen: "restore-backup" });+ });++ it("takes a marker that only says which language, which is the whole of what is required", () => {+ expect(parseSetupMarker(`{ "lang": "en" }`)).toEqual({ lang: "en" });+ });++ it("drops a screen it does not know, rather than carrying it", () => {+ // The wizard has states that create a document the moment they are shown. A file in the data+ // directory must not be able to name one, whoever wrote it.+ expect(parseSetupMarker(`{ "lang": "en", "targetScreen": "createNewDocumentEmpty" }`))+ .toEqual({ lang: "en" });+ expect(asSetupTargetScreen("createNewDocumentEmpty")).toBeUndefined();+ expect(asSetupTargetScreen("restore-backup")).toBe("restore-backup");+ });++ it("refuses anything that is not a marker", () => {+ // Read at the one moment when a wrong answer sends the instance somewhere nobody asked for.+ expect(parseSetupMarker("not json at all")).toBeNull();+ expect(parseSetupMarker(`{ "targetScreen": "restore-backup" }`)).toBeNull();+ expect(parseSetupMarker(`{ "lang": "" }`)).toBeNull();+ expect(parseSetupMarker(`{ "lang": 42 }`)).toBeNull();+ expect(parseSetupMarker(`[ "lang" ]`)).toBeNull();+ expect(parseSetupMarker("null")).toBeNull();+ });+});++describe("being in setup because it was asked for", () => {+ it("starts as neither, since an ordinary start has no marker", () => {+ expect(isSetupRequested()).toBe(false);+ expect(isInitialSetup()).toBe(true);+ expect(getSetupTargetScreen()).toBeUndefined();+ expect(getSetupLanguage()).toBeUndefined();+ });++ it("remembers what the marker asked for, and says this is not a first run", () => {+ enterSetupMode({ lang: "de", targetScreen: "restore-backup" });++ expect(isSetupRequested()).toBe(true);+ // Which is what lets a screen offer to leave: there is a database to go back to.+ expect(isInitialSetup()).toBe(false);+ expect(getSetupTargetScreen()).toBe("restore-backup");+ expect(getSetupLanguage()).toBe("de");+ });++ it("is left the moment a database is brought up", () => {+ enterSetupMode({ lang: "de" });+ leaveSetupMode();++ expect(isSetupRequested()).toBe(false);+ expect(isInitialSetup()).toBe(true);+ });++ it("treats a start without a marker as the ordinary one", () => {+ enterSetupMode(null);++ expect(isSetupRequested()).toBe(false);+ expect(isInitialSetup()).toBe(true);+ });+});++describe("the marker store", () => {+ it("carries what a route writes to whichever platform registered itself", async () => {+ const written: unknown[] = [];+ initSetupMarkerStore({+ write: async (marker) => { written.push(marker); },+ remove: async () => {}+ });++ await getSetupMarkerStore().write({ lang: "en", targetScreen: "restore-backup" });+ expect(written).toEqual([ { lang: "en", targetScreen: "restore-backup" } ]);+ });++ it("says so rather than failing quietly where no platform registered one", async () => {+ vi.resetModules();+ const fresh = await import("./setup_mode.js");++ expect(() => fresh.getSetupMarkerStore()).toThrow(/not initialized/);+ });+});diff --git a/packages/trilium-core/src/services/setup_mode.ts b/packages/trilium-core/src/services/setup_mode.tsnew file mode 100644index 0000000000..3a5a7f05bc--- /dev/null+++ b/packages/trilium-core/src/services/setup_mode.ts@@ -0,0 +1,140 @@+import { type SetupMarker, type SetupTargetScreen } from "@triliumnext/commons";++/**+ * Setup asked for by an instance that already has a database.+ *+ * An instance normally reaches the setup screen because there is nothing to open. Some things the+ * user can ask for, restoring a backup among them, need the same screen and the same closed+ * database, so a running instance writes a `setup.json` marker and restarts. The start that follows+ * reads it, hands it to this module, and from then on the instance answers "not initialized" to+ * everything that asks: the database is never migrated, becca is never loaded, the desktop opens its+ * setup window, and every guard that exists to protect an uninitialized instance keeps working+ * unchanged.+ *+ * The state lives for the process, not for the file, which is read once and deleted. A page reloaded+ * halfway through the wizard therefore comes back to the same screen, while a genuine restart comes+ * back to the app.+ *+ * @module+ */++/** The screens a marker is allowed to name, which is not every screen the wizard has. */+const TARGET_SCREENS: readonly SetupTargetScreen[] = [ "restore-backup" ];++let requested: SetupMarker | null = null;++/**+ * Puts the instance into setup for the rest of this process.+ *+ * Called by the platform at start, before the database is opened, with whatever its marker file+ * held. A `null` marker is the ordinary case and leaves everything alone.+ */+export function enterSetupMode(marker: SetupMarker | null): void {+ requested = marker;+}++/**+ * Takes the instance back out, which is what bringing a database up means.+ *+ * Called by every path that opens one: finishing a restore, creating a document, converging a sync.+ * Until it is called, {@link isSetupRequested} keeps the instance answering as uninitialized, and+ * the database that was just opened would go unnoticed.+ */+export function leaveSetupMode(): void {+ requested = null;+}++/** Whether this instance was asked to be in setup rather than being there for want of a database. */+export function isSetupRequested(): boolean {+ return requested !== null;+}++/**+ * Whether the setup screen is the instance's first run.+ *+ * `false` says there is a database behind the wizard, which is what lets a screen offer to leave+ * without doing anything: the instance has somewhere to go back to.+ */+export function isInitialSetup(): boolean {+ return requested === null;+}++/** The screen the marker asked for, if it asked for one. */+export function getSetupTargetScreen(): SetupTargetScreen | undefined {+ return requested?.targetScreen;+}++/** The language the marker carried, which is the instance's own, from before the database closed. */+export function getSetupLanguage(): string | undefined {+ return requested?.lang;+}++/**+ * Reads a marker's contents, or answers `null` for anything that is not one.+ *+ * The file is written by this application and read by the next start of it, but it is also a plain+ * file in the data directory that anything could have left behind, and it is read at the one moment+ * when a bad answer sends the instance somewhere the user did not ask to go. So it is parsed+ * defensively: unknown screens are dropped rather than carried, and a marker without a language is+ * not a marker.+ */+export function parseSetupMarker(raw: string): SetupMarker | null {+ let parsed: unknown;+ try {+ parsed = JSON.parse(raw);+ } catch {+ return null;+ }++ if (typeof parsed !== "object" || parsed === null) {+ return null;+ }++ const { lang, targetScreen } = parsed as Record<string, unknown>;+ if (typeof lang !== "string" || !lang) {+ return null;+ }++ const screen = asSetupTargetScreen(targetScreen);++ return {+ lang,+ ...(screen ? { targetScreen: screen } : {})+ };+}++/**+ * Narrows a value to a screen the wizard may be sent to, or to nothing.+ *+ * The list is deliberately not every state the wizard has: two of them create a document the moment+ * they are shown, and nothing outside the wizard should be able to name those.+ */+export function asSetupTargetScreen(value: unknown): SetupTargetScreen | undefined {+ return TARGET_SCREENS.find((screen) => screen === value);+}++/**+ * Where the marker is kept, which is somewhere only the platform knows.+ *+ * 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.+ */+export interface SetupMarkerStore {+ write(marker: SetupMarker): Promise<void>;+ remove(): Promise<void>;+}++let store: SetupMarkerStore | null = null;++export function initSetupMarkerStore(instance: SetupMarkerStore): void {+ store = instance;+}++export function getSetupMarkerStore(): SetupMarkerStore {+ if (!store) {+ throw new Error("Setup marker store not initialized.");+ }++ return store;+}diff --git a/packages/trilium-core/src/services/sql_init.ts b/packages/trilium-core/src/services/sql_init.tsindex d081e08c80..ccbfe5c120 100644--- a/packages/trilium-core/src/services/sql_init.ts+++ b/packages/trilium-core/src/services/sql_init.ts@@ -14,6 +14,7 @@ import TaskContext from "./task_context";import BOption from "../becca/entities/boption";import migrationService from "./migration";import passwordService from "./encryption/password";+import { isSetupRequested, leaveSetupMode } from "./setup_mode";export const dbReady = deferred<void>();@@ -34,6 +35,12 @@ function schemaExists() {}function isDbInitialized() {+ // An instance asked to boot into setup answers as one that has nothing to open, which is what+ // keeps the database closed and every uninitialized-only guard in force. See setup_mode.+ if (isSetupRequested()) {+ return false;+ }+try {if (!schemaExists()) {return false;@@ -75,6 +82,9 @@ async function initDbConnection() {}function setDbAsInitialized() {+ // A database is being brought up, so whatever asked for setup has had its answer.+ leaveSetupMode();+if (!isDbInitialized()) {optionService.setOption("initialized", "true");