Build your personal knowledge base with Trilium Notes
TypeScript electronelectron-appknowledge-baseknowledge-graphknowledge-managementknowledge-management-graphlocal-firstnote-managmentnote-takernote-takingnotebooknotesnotes-apppersonal-knowledge-basepersonal-wikiscriptableself-hostedself-hostingwiki
client/options: relocate some options from the "Advanced" section to "Database"
Adorian Doran6ff80fb20fc1
diff --git a/apps/client/src/stylesheets/theme-next/pages.css b/apps/client/src/stylesheets/theme-next/pages.cssindex b283053303..bdf0f51316 100644--- a/apps/client/src/stylesheets/theme-next/pages.css+++ b/apps/client/src/stylesheets/theme-next/pages.css@@ -232,8 +232,7 @@ body.desktop .options-section:not(.tn-no-card) {color: var(--root-background);}-.options-section-card p:last-of-type:not(:first-of-type),-.options-section-card .existing-anonymized-databases {+.options-section-card p:last-of-type:not(:first-of-type) {margin-bottom: 0;}diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.jsonindex 0a7ccf0293..b6270fa782 100644--- a/apps/client/src/translations/en/translation.json+++ b/apps/client/src/translations/en/translation.json@@ -1748,6 +1748,7 @@},"database": {"title": "Database",+ "maintenance": "Maintenance","start_over_description": "Switch to a new blank database, start again syncing with a new server or restore a backup. You will be prompted to backup your data before discarding the existing data.","start_over": "Start over","start_over_confirm": "Trilium will go back to the setup screen, where you can start a new knowledge base, restore a backup or sync from another device. You will be offered a backup of your current data first, and nothing is deleted until you choose one of those. Continue?",diff --git a/apps/client/src/widgets/type_widgets/options/advanced.tsx b/apps/client/src/widgets/type_widgets/options/advanced.tsxindex 89a869d755..fcc50f180c 100644--- a/apps/client/src/widgets/type_widgets/options/advanced.tsx+++ b/apps/client/src/widgets/type_widgets/options/advanced.tsx@@ -1,5 +1,4 @@-import { AnonymizedDbResponse, DatabaseAnonymizeResponse, DatabaseCheckIntegrityResponse, ExistingAnonymizedDatabasesResponse } from "@triliumnext/commons";-import { useCallback, useEffect, useMemo, useState } from "preact/hooks";+import { useCallback, useMemo } from "preact/hooks";import { type ExperimentalFeatureId, getAvailableExperimentalFeatures } from "../../../services/experimental_features";import { t } from "../../../services/i18n";@@ -7,7 +6,6 @@ import server from "../../../services/server";import toast from "../../../services/toast";import FormText from "../../react/FormText";import { useTriliumOptionJson } from "../../react/hooks";-import DatabaseFileList from "./components/DatabaseFileList";import OptionsPageHeader from "./components/OptionsPageHeader";import { OptionsRowWithButton, OptionsRowWithToggle } from "./components/OptionsRow";import OptionsSection from "./components/OptionsSection";@@ -15,174 +13,11 @@ import OptionsSection from "./components/OptionsSection";export default function AdvancedSettings() {return <><OptionsPageHeader />- <DatabaseOptions />- <DatabaseAnonymizationOptions /><ExperimentalOptions /><AdvancedSyncOptions /></>;}-function AdvancedSyncOptions() {- return (- <OptionsSection title={t("sync.title")}>- <OptionsRowWithButton- label={t("sync.force_full_sync_label")}- description={t("sync.force_full_sync_description")}- buttonText={t("sync.force_full_sync_button")}- onClick={async () => {- await server.post("sync/force-full-sync");- toast.showMessage(t("sync.full_sync_triggered"));- }}- />-- <OptionsRowWithButton- label={t("sync.fill_entity_changes_label")}- description={t("sync.fill_entity_changes_description")}- buttonText={t("sync.fill_entity_changes_button")}- onClick={async () => {- toast.showMessage(t("sync.filling_entity_changes"));- await server.post("sync/fill-entity-changes");- toast.showMessage(t("sync.sync_rows_filled_successfully"));- }}- />- </OptionsSection>- );-}--function DatabaseOptions() {- return (- <OptionsSection title={t("database.title")}>- <OptionsRowWithButton- label={t("database_integrity_check.check_integrity_label")}- description={t("database_integrity_check.check_integrity_description")}- buttonText={t("database_integrity_check.check_button")}- onClick={async () => {- toast.showMessage(t("database_integrity_check.checking_integrity"));-- const { results } = await server.get<DatabaseCheckIntegrityResponse>("database/check-integrity");-- if (results.length === 1 && results[0].integrity_check === "ok") {- toast.showMessage(t("database_integrity_check.integrity_check_succeeded"));- } else {- toast.showMessage(t("database_integrity_check.integrity_check_failed", { results: JSON.stringify(results, null, 2) }), 15000);- }- }}- />-- <OptionsRowWithButton- label={t("consistency_checks.find_and_fix_label")}- description={t("consistency_checks.find_and_fix_description")}- buttonText={t("consistency_checks.find_and_fix_button")}- onClick={async () => {- toast.showMessage(t("consistency_checks.finding_and_fixing_message"));- await server.post("database/find-and-fix-consistency-issues");- toast.showMessage(t("consistency_checks.issues_fixed_message"));- }}- />-- <OptionsRowWithButton- label={t("vacuum_database.vacuum_label")}- description={t("vacuum_database.vacuum_description")}- buttonText={t("vacuum_database.button_text")}- onClick={async () => {- toast.showMessage(t("vacuum_database.vacuuming_database"));- // A rebuild runs in minutes on a large database — half an hour on 36 GiB — so- // the default minute would report a failure for something still succeeding.- await server.postWithTimeout("database/vacuum-database", VACUUM_TIMEOUT_MS);- toast.showMessage(t("vacuum_database.database_vacuumed"));- }}- />- </OptionsSection>- );-}--/** Rebuilding runs in minutes on a large database, and the client must not give up before it ends. */-const VACUUM_TIMEOUT_MS = 60 * 60 * 1000;--function DatabaseAnonymizationOptions() {- const [databases, setDatabases] = useState<AnonymizedDbResponse[]>([]);- const [anonymizedFolderPath, setAnonymizedFolderPath] = useState<string | null>(null);- const [anonymizationInProgress, setAnonymizationInProgress] = useState(false);-- const refreshAnonymizedDatabases = useCallback(() => {- server.get<ExistingAnonymizedDatabasesResponse>("database/anonymized-databases").then((response) => {- setDatabases(response.databases);- setAnonymizedFolderPath(response.anonymizedFolderPath);- });- }, []);-- useEffect(refreshAnonymizedDatabases, []);-- const anonymize = async (type: "full" | "light") => {- setAnonymizationInProgress(true);- try {- toast.showMessage(type === "full"- ? t("database_anonymization.creating_fully_anonymized_database")- : t("database_anonymization.creating_lightly_anonymized_database"));- const resp = await server.post<DatabaseAnonymizeResponse>(`database/anonymize/${type}`);-- if (!resp.success) {- toast.showError(t("database_anonymization.error_creating_anonymized_database"));- } else {- toast.showMessage(type === "full"- ? t("database_anonymization.successfully_created_fully_anonymized_database", { anonymizedFilePath: resp.anonymizedFilePath })- : t("database_anonymization.successfully_created_lightly_anonymized_database", { anonymizedFilePath: resp.anonymizedFilePath }), 10000);- refreshAnonymizedDatabases();- }- } finally {- setAnonymizationInProgress(false);- }- };-- return (- <>- <OptionsSection- title={t("database_anonymization.title")}- description={t("database_anonymization.description")}- >- <OptionsRowWithButton- label={t("database_anonymization.full_anonymization")}- description={t("database_anonymization.full_anonymization_description")}- buttonText={t("database_anonymization.save_fully_anonymized_database")}- disabled={anonymizationInProgress}- onClick={() => anonymize("full")}- />-- <OptionsRowWithButton- label={t("database_anonymization.light_anonymization")}- description={t("database_anonymization.light_anonymization_description")}- buttonText={t("database_anonymization.save_lightly_anonymized_database")}- disabled={anonymizationInProgress}- onClick={() => anonymize("light")}- />- </OptionsSection>-- <ExistingAnonymizedDatabases databases={databases} anonymizedFolderPath={anonymizedFolderPath} />- </>- );-}--function ExistingAnonymizedDatabases({ databases, anonymizedFolderPath }: { databases: AnonymizedDbResponse[]; anonymizedFolderPath: string | null }) {- return (- <DatabaseFileList- title={t("database_anonymization.existing_anonymized_databases")}- description={anonymizedFolderPath && (- <span className="selectable-text">- {t("database_anonymization.anonymized_databases_location", {- anonymizedFolder: anonymizedFolderPath- })}- </span>- )}- files={databases}- downloadEndpoint="api/database/anonymized/download"- downloadText={t("database_anonymization.download")}- emptyIcon="bx bx-glasses"- emptyText={t("database_anonymization.no_anonymized_database_yet")}- />- );-}--function ExperimentalOptions() {const [enabledFeatures, setEnabledFeatures] = useTriliumOptionJson<ExperimentalFeatureId[]>("experimentalFeatures", true);// Features with dedicated controls elsewhere (appearance settings and the AI/LLM page, respectively).@@ -218,3 +53,30 @@ function ExperimentalOptions() {</OptionsSection>);}++function AdvancedSyncOptions() {+ return (+ <OptionsSection title={t("sync.title")}>+ <OptionsRowWithButton+ label={t("sync.force_full_sync_label")}+ description={t("sync.force_full_sync_description")}+ buttonText={t("sync.force_full_sync_button")}+ onClick={async () => {+ await server.post("sync/force-full-sync");+ toast.showMessage(t("sync.full_sync_triggered"));+ }}+ />++ <OptionsRowWithButton+ label={t("sync.fill_entity_changes_label")}+ description={t("sync.fill_entity_changes_description")}+ buttonText={t("sync.fill_entity_changes_button")}+ onClick={async () => {+ toast.showMessage(t("sync.filling_entity_changes"));+ await server.post("sync/fill-entity-changes");+ toast.showMessage(t("sync.sync_rows_filled_successfully"));+ }}+ />+ </OptionsSection>+ );+}diff --git a/apps/client/src/widgets/type_widgets/options/database.css b/apps/client/src/widgets/type_widgets/options/database.cssindex ef4ead2fd8..a44b60b20c 100644--- a/apps/client/src/widgets/type_widgets/options/database.css+++ b/apps/client/src/widgets/type_widgets/options/database.css@@ -1,4 +1,4 @@-/* The notice sits above the card it is about, so the gap belongs under it. */+/* The notice sits above the cards it precedes, so the gap belongs under it. */.admonition.start-over-pending {margin-bottom: 16px;diff --git a/apps/client/src/widgets/type_widgets/options/database.spec.tsx b/apps/client/src/widgets/type_widgets/options/database.spec.tsxindex a87d82d805..35cf5c8447 100644--- a/apps/client/src/widgets/type_widgets/options/database.spec.tsx+++ b/apps/client/src/widgets/type_widgets/options/database.spec.tsx@@ -12,6 +12,30 @@ const setupMode = vi.hoisted(() => ({}));vi.mock("../../../services/setup_mode", () => setupMode);+// The maintenance and anonymization cards call the backend as they render and as they are used.+const server = vi.hoisted(() => ({+ get: vi.fn(async (url: string) => {+ switch (url) {+ case "database/check-integrity":+ return { results: [{ integrity_check: "ok" }] };+ case "database/anonymized-databases":+ return { databases: [], anonymizedFolderPath: "/data/anonymized" };+ // Whatever the page's own imports ask for while they load, e.g. keyboard actions.+ default:+ return [];+ }+ }),+ post: vi.fn(async () => ({ success: true, anonymizedFilePath: "/data/anonymized/copy.db" })),+ postWithTimeout: vi.fn(async () => ({}))+}));+vi.mock("../../../services/server", () => ({ default: server }));++const toast = vi.hoisted(() => ({+ showMessage: vi.fn(),+ showError: vi.fn()+}));+vi.mock("../../../services/toast", () => ({ default: toast }));+// The page header renders the note's own title, which needs a note context this spec has no use for.vi.mock("./components/OptionsPageHeader", () => ({ default: () => null }));@@ -41,6 +65,11 @@ beforeEach(() => {setupMode.startOver.mockReset().mockResolvedValue("restarting");setupMode.isStartOverPending.mockReset().mockResolvedValue(false);setupMode.cancelStartOver.mockReset().mockResolvedValue(undefined);+ server.get.mockClear();+ server.post.mockClear();+ server.postWithTimeout.mockClear();+ toast.showMessage.mockClear();+ toast.showError.mockClear();});afterEach(() => {@@ -49,6 +78,52 @@ afterEach(() => {vi.useRealTimers();});+describe("database maintenance", () => {+ it("runs each check against its own endpoint, and says how it went", async () => {+ renderPage();+ await settle();++ button("check-integrity-button")?.click();+ button("fix-consistency-issues-button")?.click();+ button("vacuum-database-button")?.click();+ await settle();++ expect(server.get).toHaveBeenCalledWith("database/check-integrity");+ expect(server.post).toHaveBeenCalledWith("database/find-and-fix-consistency-issues");+ // With a timeout of its own: a rebuild outlives the default one on a large database.+ expect(server.postWithTimeout).toHaveBeenCalledWith("database/vacuum-database", expect.any(Number));+ expect(toast.showMessage).toHaveBeenCalledWith("database_integrity_check.integrity_check_succeeded");+ });+});++describe("anonymized copies", () => {+ it("reads the existing copies on arrival, and lists the new one it makes", async () => {+ renderPage();+ await settle();++ expect(server.get).toHaveBeenCalledWith("database/anonymized-databases");++ button("light-anonymization-button")?.click();+ await settle();++ expect(server.post).toHaveBeenCalledWith("database/anonymize/light");+ // The copy is a file beside the database, so the list is the only way back to it.+ expect(server.get.mock.calls.filter(([url]) => url === "database/anonymized-databases")).toHaveLength(2);+ });++ it("says so when the copy could not be made, and asks the list for nothing", async () => {+ server.post.mockResolvedValueOnce({ success: false, anonymizedFilePath: "" });+ renderPage();+ await settle();++ button("full-anonymization-button")?.click();+ await settle();++ expect(toast.showError).toHaveBeenCalledWith("database_anonymization.error_creating_anonymized_database");+ expect(server.get.mock.calls.filter(([url]) => url === "database/anonymized-databases")).toHaveLength(1);+ });+});+describe("starting over from Options", () => {it("offers the button, and asks nothing of its own before handing over", async () => {renderPage();diff --git a/apps/client/src/widgets/type_widgets/options/database.tsx b/apps/client/src/widgets/type_widgets/options/database.tsxindex 7b5543f9fc..c0204aee6c 100644--- a/apps/client/src/widgets/type_widgets/options/database.tsx+++ b/apps/client/src/widgets/type_widgets/options/database.tsx@@ -1,24 +1,34 @@import "./database.css";-import { useEffect, useState } from "preact/hooks";+import {+ AnonymizedDbResponse,+ DatabaseAnonymizeResponse,+ DatabaseCheckIntegrityResponse,+ ExistingAnonymizedDatabasesResponse+} from "@triliumnext/commons";+import { useCallback, useEffect, useState } from "preact/hooks";import { t } from "../../../services/i18n";+import server from "../../../services/server";import {canBootToSetup,cancelStartOver,isStartOverPending,startOver} from "../../../services/setup_mode";+import toast from "../../../services/toast";import Admonition from "../../react/Admonition";import Button from "../../react/Button";import { Card, CardOption } from "../../react/Card";+import DatabaseFileList from "./components/DatabaseFileList";import OptionsPageHeader from "./components/OptionsPageHeader";/**- * What can be done to the knowledge base as a whole, rather than to anything inside it.+ * What can be done to the knowledge base as a whole, rather than to anything inside it: keeping the+ * database sound, handing a copy of it to someone else with the contents taken out, and replacing+ * it altogether.*- * One entry for now, and the one that needed a page of its own: starting over is neither a backup- * nor a setting, and it is the only thing in Options that leaves the application entirely.+ * Starting over comes last, being the only thing in Options that leaves the application.*/export default function DatabaseSettings() {const startOverState = useStartOver();@@ -27,7 +37,7 @@ export default function DatabaseSettings() {<><OptionsPageHeader />- {/* Above the card rather than under the button that caused it: a request left standing+ {/* Above the cards rather than under the button that caused it: a request left standingis the state of the whole page from here on, and the first thing its owner needs toknow when they open this page again. */}{startOverState.pending && (@@ -44,29 +54,208 @@ export default function DatabaseSettings() {</Admonition>)}- {/* Headingless: the row names the feature itself, and this card is to be folded into- another one later. */}- <div className="options-section start-over">- <Card>+ <MaintenanceOptions />+ <AnonymizationOptions />+ <StartOverOption state={startOverState} />+ </>+ );+}++/** Checks and repairs that act on the database file itself, rather than on what is kept in it. */+function MaintenanceOptions() {+ return (+ <div className="options-section database-maintenance">+ <Card heading={t("database.maintenance")}>+ <CardOption+ label={t("database_integrity_check.check_integrity_label")}+ description={t("database_integrity_check.check_integrity_description")}+ >+ <Button+ name="check-integrity-button"+ text={t("database_integrity_check.check_button")}+ size="micro"+ onClick={checkIntegrity}+ />+ </CardOption>++ <CardOption+ label={t("consistency_checks.find_and_fix_label")}+ description={t("consistency_checks.find_and_fix_description")}+ >+ <Button+ name="fix-consistency-issues-button"+ text={t("consistency_checks.find_and_fix_button")}+ size="micro"+ onClick={fixConsistencyIssues}+ />+ </CardOption>++ <CardOption+ label={t("vacuum_database.vacuum_label")}+ description={t("vacuum_database.vacuum_description")}+ >+ <Button+ name="vacuum-database-button"+ text={t("vacuum_database.button_text")}+ size="micro"+ onClick={vacuumDatabase}+ />+ </CardOption>+ </Card>+ </div>+ );+}++/** Reports back either a clean bill of health, or whatever SQLite found, which is worth reading. */+async function checkIntegrity() {+ toast.showMessage(t("database_integrity_check.checking_integrity"));++ const { results } = await server.get<DatabaseCheckIntegrityResponse>("database/check-integrity");++ if (results.length === 1 && results[0].integrity_check === "ok") {+ toast.showMessage(t("database_integrity_check.integrity_check_succeeded"));+ } else {+ toast.showMessage(t("database_integrity_check.integrity_check_failed", { results: JSON.stringify(results, null, 2) }), 15000);+ }+}++async function fixConsistencyIssues() {+ toast.showMessage(t("consistency_checks.finding_and_fixing_message"));+ await server.post("database/find-and-fix-consistency-issues");+ toast.showMessage(t("consistency_checks.issues_fixed_message"));+}++async function vacuumDatabase() {+ toast.showMessage(t("vacuum_database.vacuuming_database"));+ // A rebuild runs in minutes on a large database — half an hour on 36 GiB — so the default+ // minute would report a failure for something still succeeding.+ await server.postWithTimeout("database/vacuum-database", VACUUM_TIMEOUT_MS);+ toast.showMessage(t("vacuum_database.database_vacuumed"));+}++/** Rebuilding runs in minutes on a large database, and the client must not give up before it ends. */+const VACUUM_TIMEOUT_MS = 60 * 60 * 1000;++/**+ * Copies of the database made to be handed out: the contents are taken out, so that what is left+ * says how the knowledge base is put together without saying what is in it.+ *+ * The copies are kept as files beside the database, so the list below the actions is the only place+ * they can be reached from once the toast that announced them is gone.+ */+function AnonymizationOptions() {+ const [databases, setDatabases] = useState<AnonymizedDbResponse[]>([]);+ const [anonymizedFolderPath, setAnonymizedFolderPath] = useState<string | null>(null);+ const [anonymizationInProgress, setAnonymizationInProgress] = useState(false);++ const refreshAnonymizedDatabases = useCallback(() => {+ server.get<ExistingAnonymizedDatabasesResponse>("database/anonymized-databases").then((response) => {+ setDatabases(response.databases);+ setAnonymizedFolderPath(response.anonymizedFolderPath);+ });+ }, []);++ useEffect(refreshAnonymizedDatabases, []);++ async function anonymize(type: "full" | "light") {+ setAnonymizationInProgress(true);+ try {+ toast.showMessage(type === "full"+ ? t("database_anonymization.creating_fully_anonymized_database")+ : t("database_anonymization.creating_lightly_anonymized_database"));+ const resp = await server.post<DatabaseAnonymizeResponse>(`database/anonymize/${type}`);++ if (!resp.success) {+ toast.showError(t("database_anonymization.error_creating_anonymized_database"));+ return;+ }++ toast.showMessage(type === "full"+ ? t("database_anonymization.successfully_created_fully_anonymized_database", { anonymizedFilePath: resp.anonymizedFilePath })+ : t("database_anonymization.successfully_created_lightly_anonymized_database", { anonymizedFilePath: resp.anonymizedFilePath }), 10000);+ refreshAnonymizedDatabases();+ } finally {+ setAnonymizationInProgress(false);+ }+ }++ return (+ <>+ <div className="options-section database-anonymization">+ <Card+ heading={t("database_anonymization.title")}+ description={t("database_anonymization.description")}+ ><CardOption- label={t("database.start_over")}- description={t("database.start_over_description")}+ label={t("database_anonymization.full_anonymization")}+ description={t("database_anonymization.full_anonymization_description")}><Button- name="start-over-button"- text={t("database.start_over")}- icon="bx-reset"+ name="full-anonymization-button"+ text={t("database_anonymization.save_fully_anonymized_database")}size="micro"- disabled={startOverState.busy || startOverState.pending}- onClick={() => void startOverState.begin()}+ disabled={anonymizationInProgress}+ onClick={() => void anonymize("full")}+ />+ </CardOption>++ <CardOption+ label={t("database_anonymization.light_anonymization")}+ description={t("database_anonymization.light_anonymization_description")}+ >+ <Button+ name="light-anonymization-button"+ text={t("database_anonymization.save_lightly_anonymized_database")}+ size="micro"+ disabled={anonymizationInProgress}+ onClick={() => void anonymize("light")}/></CardOption></Card></div>++ <DatabaseFileList+ title={t("database_anonymization.existing_anonymized_databases")}+ description={anonymizedFolderPath && (+ <span className="selectable-text">+ {t("database_anonymization.anonymized_databases_location", {+ anonymizedFolder: anonymizedFolderPath+ })}+ </span>+ )}+ files={databases}+ downloadEndpoint="api/database/anonymized/download"+ downloadText={t("database_anonymization.download")}+ emptyIcon="bx bx-glasses"+ emptyText={t("database_anonymization.no_anonymized_database_yet")}+ /></>);}+/** Headingless: the row names the feature itself, and nothing else belongs beside it. */+function StartOverOption({ state }: { state: ReturnType<typeof useStartOver> }) {+ return (+ <div className="options-section start-over">+ <Card>+ <CardOption+ label={t("database.start_over")}+ description={t("database.start_over_description")}+ >+ <Button+ name="start-over-button"+ text={t("database.start_over")}+ icon="bx-reset"+ size="micro"+ disabled={state.busy || state.pending}+ onClick={() => void state.begin()}+ />+ </CardOption>+ </Card>+ </div>+ );+}+/*** Going back to the setup screen, from where the knowledge base can be replaced.*@@ -74,6 +263,9 @@ export default function DatabaseSettings() {* build go there and then, so pressing the button is the whole of it. A server is restarted by* whoever runs it, so the request outlives the page that made it, and the page has to say that a* start-over is waiting and offer to call it off.+ *+ * Held by the page rather than by the row it belongs to, since the notice about a standing request+ * is the state of the whole page and sits at the top of it.*/function useStartOver() {const [ pending, setPending ] = useState(false);