From 7c377ce4649aa1f48da9d2b591277373f0a29fcf Mon Sep 17 00:00:00 2001 From: aamott <54421854+aamott@users.noreply.github.com> Date: Sat, 17 Oct 2026 15:24:35 -0600 Subject: [PATCH] refactor(settings): separate registry and consolidate tests --- .../src/extensions/builtins/journal.test.tsx | 3 +- .../extensions/desktopExtensionHost.test.ts | 7 +- .../src/extensions/desktopExtensionHost.ts | 6 +- apps/desktop/src/lib/useUiScale.test.tsx | 3 +- apps/desktop/src/lib/useUiScale.ts | 3 +- apps/desktop/src/native/documentChain.test.ts | 214 +++++++ .../src/settings/SettingsContent.test.tsx | 3 +- apps/desktop/src/settings/SettingsContent.tsx | 3 +- .../src/settings/SettingsHeaderBar.test.tsx | 18 + .../src/settings/SettingsHeaderBar.tsx | 7 +- .../src/settings/SettingsImportExport.test.ts | 33 +- apps/desktop/src/settings/SettingsNav.tsx | 3 +- .../src/settings/SettingsSearch.test.tsx | 3 +- .../desktop/src/settings/SettingsTab.test.tsx | 3 +- .../settings/ThemeSectionControls.test.tsx | 25 +- .../src/settings/ThemeSectionControls.tsx | 4 +- .../src/settings/appSettingsFile.test.ts | 165 ++---- apps/desktop/src/settings/settingsHelpers.ts | 2 +- .../src/settings/settingsImportExport.ts | 27 +- apps/desktop/src/settings/settingsRegistry.ts | 92 +++ .../settings/settingsStore.extensions.test.ts | 411 ++++++++++++++ .../src/settings/settingsStore.test.ts | 523 +----------------- apps/desktop/src/settings/settingsStore.ts | 196 +------ .../src/settings/settingsStoreTestHelpers.ts | 75 +++ .../src/settings/settingsStoreTypes.ts | 107 ++++ .../src/settings/settingsTestHelpers.ts | 3 +- .../src/settings/themeImportExport.test.ts | 43 +- .../desktop/src/settings/themeImportExport.ts | 31 +- .../src/settings/useEffectiveValue.test.ts | 75 ++- .../desktop/src/settings/useEffectiveValue.ts | 3 +- .../src/shell/useShellShortcuts.test.tsx | 3 +- .../useWorkspaceLifecycle.session.test.tsx | 4 +- .../src/shell/useWorkspaceLifecycle.test.tsx | 4 +- apps/desktop/src/tabs/tabRestore.test.tsx | 4 +- .../workspace/workspaceSettingsFile.test.ts | 173 ++---- docs/reviews/2026-10-10/README.md | 4 +- .../settings-source-audit-med-med.md | 45 +- .../done-settings_source_cleanup-low-med.md | 11 + ...pending-settings_source_cleanup-low-med.md | 9 - 39 files changed, 1173 insertions(+), 1175 deletions(-) create mode 100644 apps/desktop/src/native/documentChain.test.ts create mode 100644 apps/desktop/src/settings/settingsRegistry.ts create mode 100644 apps/desktop/src/settings/settingsStore.extensions.test.ts create mode 100644 apps/desktop/src/settings/settingsStoreTestHelpers.ts create mode 100644 apps/desktop/src/settings/settingsStoreTypes.ts create mode 100644 plans/other_tasks/done-settings_source_cleanup-low-med.md delete mode 100644 plans/other_tasks/pending-settings_source_cleanup-low-med.md diff --git a/apps/desktop/src/extensions/builtins/journal.test.tsx b/apps/desktop/src/extensions/builtins/journal.test.tsx index a8e90231..64d5cd75 100644 --- a/apps/desktop/src/extensions/builtins/journal.test.tsx +++ b/apps/desktop/src/extensions/builtins/journal.test.tsx @@ -23,7 +23,8 @@ import { } from "../../commands/commandRegistry"; import { desktopPanelRegistry } from "../../panels/panelRegistryModel"; import { desktopEditorHeaderRegistry } from "../../tabs/editorHeaderRegistry.ts"; -import { appSettingsRegistry, useSettingsStore } from "../../settings/settingsStore"; +import { useSettingsStore } from "../../settings/settingsStore"; +import { appSettingsRegistry } from "../../settings/settingsRegistry"; let host: ReturnType | null = null; let root: Root | null = null; diff --git a/apps/desktop/src/extensions/desktopExtensionHost.test.ts b/apps/desktop/src/extensions/desktopExtensionHost.test.ts index 8b7f17f6..29e7b0a2 100644 --- a/apps/desktop/src/extensions/desktopExtensionHost.test.ts +++ b/apps/desktop/src/extensions/desktopExtensionHost.test.ts @@ -6,11 +6,8 @@ import { type Disposable } from "@thinkbrain/core"; -import { - appSettingsRegistry, - createSettingsStore, - useSettingsStore -} from "../settings/settingsStore"; +import { createSettingsStore, useSettingsStore } from "../settings/settingsStore"; +import { appSettingsRegistry } from "../settings/settingsRegistry"; import { appEvents } from "../events/appEvents"; import { desktopCommandRegistry } from "../commands/commandRegistry"; import { createDesktopTabRegistry } from "../tabs/tabRegistry"; diff --git a/apps/desktop/src/extensions/desktopExtensionHost.ts b/apps/desktop/src/extensions/desktopExtensionHost.ts index aa616132..10499688 100644 --- a/apps/desktop/src/extensions/desktopExtensionHost.ts +++ b/apps/desktop/src/extensions/desktopExtensionHost.ts @@ -38,10 +38,8 @@ import { workspaceDocumentApi } from "../workspace/workspaceDocumentAdapter"; import { createExtensionWorkspace, type DesktopExtensionWorkspace } from "./extensionWorkspace"; import { getWorkspaceBridge, subscribeWorkspaceBridge } from "./workspaceBridge"; import type { DesktopEditorHookContribution } from "../tabs/editorHookRegistry"; -import { - appSettingsRegistry, - useSettingsStore -} from "../settings/settingsStore"; +import { useSettingsStore } from "../settings/settingsStore"; +import { appSettingsRegistry } from "../settings/settingsRegistry"; import { effectiveSettingValue } from "../settings/settingsHelpers"; /** A command definition whose identifier is relative to the owning extension. */ diff --git a/apps/desktop/src/lib/useUiScale.test.tsx b/apps/desktop/src/lib/useUiScale.test.tsx index 40ccaa4f..c39971a7 100644 --- a/apps/desktop/src/lib/useUiScale.test.tsx +++ b/apps/desktop/src/lib/useUiScale.test.tsx @@ -10,7 +10,8 @@ import { UI_SCALE_KEY, useUiScale } from "./useUiScale"; -import { useSettingsStore, appSettingsRegistry } from "../settings/settingsStore"; +import { useSettingsStore } from "../settings/settingsStore"; +import { appSettingsRegistry } from "../settings/settingsRegistry"; import { installStageChangeSpy, seedSettingsStore } from "../settings/settingsTestHelpers"; import { clearScrollAnchorSnapshots, diff --git a/apps/desktop/src/lib/useUiScale.ts b/apps/desktop/src/lib/useUiScale.ts index f534233c..f3bf3732 100644 --- a/apps/desktop/src/lib/useUiScale.ts +++ b/apps/desktop/src/lib/useUiScale.ts @@ -21,7 +21,8 @@ import { captureRegisteredScrollAnchors, restoreRegisteredScrollAnchors } from "./scrollAnchors"; -import { appSettingsRegistry, useSettingsStore } from "../settings/settingsStore"; +import { useSettingsStore } from "../settings/settingsStore"; +import { appSettingsRegistry } from "../settings/settingsRegistry"; import { resolveEffectiveValue } from "../settings/settingsHelpers"; import { useEffectiveValue } from "../settings/useEffectiveValue"; diff --git a/apps/desktop/src/native/documentChain.test.ts b/apps/desktop/src/native/documentChain.test.ts new file mode 100644 index 00000000..cef93d96 --- /dev/null +++ b/apps/desktop/src/native/documentChain.test.ts @@ -0,0 +1,214 @@ +import { describe, expect, it, vi } from "vitest"; + +import { createDocumentChain } from "./documentChain"; +import { NativeCommandError } from "./commands"; + +const CONFLICT = "settings.test_conflict"; + +const parse = (raw: string | null): Record => + raw === null ? {} : (JSON.parse(raw) as Record); + +const patch = (key: string, value: unknown) => (raw: string | null) => + JSON.stringify({ ...parse(raw), [key]: value }); + +/** + * A typed stand-in for the host's document: `read` returns what `write` + * stored, and `write` can be re-programmed per test (conflicts, holds). + */ +function createDisk() { + const contents = new Map(); + const reads = vi.fn(async (key: string) => contents.get(key) ?? null); + const writes = vi.fn(async (key: string, next: string) => { + contents.set(key, next); + }); + return { contents, reads, writes }; +} + +function chainOf(disk: ReturnType) { + return createDocumentChain({ + conflictCode: CONFLICT, + read: disk.reads, + write: disk.writes + }); +} + +describe("createDocumentChain", () => { + it("reads through to the document", async () => { + const disk = createDisk(); + disk.contents.set("k", "raw-doc"); + + await expect(chainOf(disk).read("k")).resolves.toBe("raw-doc"); + expect(disk.reads).toHaveBeenCalledWith("k"); + }); + + /** + * Two writers on the same key each read, merge, and write. Serialized by the + * chain, the second writer revises the first's result instead of clobbering + * it — the lost-update bug this module exists to prevent. + */ + it("serializes same-key writes so both fields survive and the final doc returns", async () => { + const disk = createDisk(); + const chain = chainOf(disk); + + const written = await Promise.all([ + chain.update("k", patch("a", 1)), + chain.update("k", patch("b", 2)) + ]); + + expect(parse(disk.contents.get("k") ?? null)).toEqual({ a: 1, b: 2 }); + // Each caller gets back the document it wrote. + expect(written.map(parse)).toEqual([{ a: 1 }, { a: 1, b: 2 }]); + }); + + /** One writer's failure must not strand every writer queued behind it. */ + it("rejects the failed caller but still runs the queued next writer", async () => { + const disk = createDisk(); + const chain = chainOf(disk); + + const failed = chain.update("k", () => { + throw new Error("nope"); + }); + const after = chain.update("k", patch("ok", true)); + + await expect(failed).rejects.toThrow("nope"); + await expect(after).resolves.toContain("ok"); + expect(parse(disk.contents.get("k") ?? null)).toEqual({ ok: true }); + }); + + it("rejects a failing write the same way and still runs the next writer", async () => { + const disk = createDisk(); + let failOnce = true; + disk.writes.mockImplementation(async (key, next) => { + if (failOnce) { + failOnce = false; + throw new Error("write blew up"); + } + disk.contents.set(key, next); + }); + const chain = chainOf(disk); + + const failed = chain.update("k", patch("a", 1)); + const after = chain.update("k", patch("b", 2)); + + await expect(failed).rejects.toThrow("write blew up"); + await expect(after).resolves.toContain("b"); + expect(parse(disk.contents.get("k") ?? null)).toEqual({ b: 2 }); + }); + + it("rejects a failing read the same way and still runs the next writer", async () => { + const disk = createDisk(); + let failOnce = true; + disk.reads.mockImplementation(async (key) => { + if (failOnce) { + failOnce = false; + throw new Error("read blew up"); + } + return disk.contents.get(key) ?? null; + }); + const chain = chainOf(disk); + + const failed = chain.update("k", patch("a", 1)); + const after = chain.update("k", patch("b", 2)); + + await expect(failed).rejects.toThrow("read blew up"); + await expect(after).resolves.toContain("b"); + }); + + /** + * Another writer can land between this chain's read and its write. The host + * refuses the stale write under the configured conflict code, so the + * revision is recomputed against what is actually on disk now. + */ + it("recomputes the revision against the changed disk after a conflict", async () => { + const disk = createDisk(); + disk.contents.set("k", JSON.stringify({ other: 1 })); + let interfered = false; + disk.writes.mockImplementation(async (key, next) => { + if (!interfered) { + interfered = true; + // The other writer's write lands, so this attempt's `expected` is stale. + disk.contents.set(key, JSON.stringify({ other: 2 })); + throw new NativeCommandError({ code: CONFLICT, message: "conflict" }); + } + disk.contents.set(key, next); + }); + const chain = chainOf(disk); + + await chain.update("k", patch("mine", true)); + + expect(parse(disk.contents.get("k") ?? null)).toEqual({ other: 2, mine: true }); + expect(disk.writes).toHaveBeenCalledTimes(2); + }); + + it("sends exactly what it read as the write's precondition, including null", async () => { + const disk = createDisk(); + const chain = chainOf(disk); + + await chain.update("k", patch("a", 1)); + expect(disk.writes).toHaveBeenLastCalledWith("k", JSON.stringify({ a: 1 }), null); + + await chain.update("k", patch("b", 2)); + expect(disk.writes).toHaveBeenLastCalledWith( + "k", + JSON.stringify({ a: 1, b: 2 }), + JSON.stringify({ a: 1 }) + ); + }); + + it("gives up after exactly four conflicted attempts", async () => { + const disk = createDisk(); + disk.writes.mockRejectedValue(new NativeCommandError({ code: CONFLICT, message: "conflict" })); + const chain = chainOf(disk); + + await expect(chain.update("k", patch("a", 1))).rejects.toThrow("conflict"); + expect(disk.writes).toHaveBeenCalledTimes(4); + }); + + it("does not retry a NativeCommandError with a different code", async () => { + const disk = createDisk(); + disk.writes.mockRejectedValue( + new NativeCommandError({ code: "settings.other_code", message: "different failure" }) + ); + const chain = chainOf(disk); + + await expect(chain.update("k", patch("a", 1))).rejects.toThrow("different failure"); + expect(disk.writes).toHaveBeenCalledTimes(1); + }); + + it("does not retry a plain Error", async () => { + const disk = createDisk(); + disk.writes.mockRejectedValue(new Error("conflict-looking message")); + const chain = chainOf(disk); + + await expect(chain.update("k", patch("a", 1))).rejects.toThrow("conflict-looking message"); + expect(disk.writes).toHaveBeenCalledTimes(1); + }); + + /** + * Chains are keyed so unrelated documents never queue behind each other. + * Holding one key's write open proves the second key's write completes + * without it — a Promise.all pass alone could hide a shared tail. + */ + it("lets another key's write complete while one key's write is held", async () => { + const disk = createDisk(); + let release!: () => void; + const held = new Promise((resolve) => { + release = resolve; + }); + disk.writes.mockImplementation(async (key, next) => { + if (key === "held-key") await held; + disk.contents.set(key, next); + }); + const chain = chainOf(disk); + + const heldUpdate = chain.update("held-key", patch("a", 1)); + // Give the held update a tick to enter its (blocked) write. + await Promise.resolve(); + + await expect(chain.update("free-key", patch("b", 2))).resolves.toContain("b"); + expect(disk.contents.get("free-key")).toBe(JSON.stringify({ b: 2 })); + + release(); + await expect(heldUpdate).resolves.toContain("a"); + }); +}); diff --git a/apps/desktop/src/settings/SettingsContent.test.tsx b/apps/desktop/src/settings/SettingsContent.test.tsx index 63d2e1f1..86733364 100644 --- a/apps/desktop/src/settings/SettingsContent.test.tsx +++ b/apps/desktop/src/settings/SettingsContent.test.tsx @@ -6,7 +6,8 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { SettingsContent } from "./SettingsContent"; import { createScrollSpyHarness, intersectSection } from "./scrollSpyTestUtils"; import { requestSettingHighlight } from "./settingHighlight"; -import { appSettingsRegistry, useSettingsStore } from "./settingsStore"; +import { useSettingsStore } from "./settingsStore"; +import { appSettingsRegistry } from "./settingsRegistry"; import { createSettingsTestHarness, seedSettingsStore diff --git a/apps/desktop/src/settings/SettingsContent.tsx b/apps/desktop/src/settings/SettingsContent.tsx index 18d1e89d..88485c05 100644 --- a/apps/desktop/src/settings/SettingsContent.tsx +++ b/apps/desktop/src/settings/SettingsContent.tsx @@ -30,7 +30,8 @@ import type { } from "@thinkbrain/core"; import { cn } from "../lib/utils"; import { SCROLL_ANCHOR_ATTR, useScrollAnchor } from "../lib/scrollAnchors"; -import { appSettingsRegistry, useSettingsModules, useSettingsStore } from "./settingsStore"; +import { useSettingsStore } from "./settingsStore"; +import { appSettingsRegistry, useSettingsModules } from "./settingsRegistry"; import { getControlForDefinition } from "./controlRegistry"; import { subscribeSettingHighlight } from "./settingHighlight"; import { resolveEffectiveValue } from "./settingsHelpers"; diff --git a/apps/desktop/src/settings/SettingsHeaderBar.test.tsx b/apps/desktop/src/settings/SettingsHeaderBar.test.tsx index 27245018..bdb14595 100644 --- a/apps/desktop/src/settings/SettingsHeaderBar.test.tsx +++ b/apps/desktop/src/settings/SettingsHeaderBar.test.tsx @@ -302,6 +302,24 @@ describe("SettingsHeaderBar export/import outcomes", () => { await flushPromises(); }; + it("writes the export payload to the chosen path and says so", async () => { + vi.mocked(saveAndWriteTextFile).mockResolvedValue(true); + const host = await harness.render(); + + await clickExport(host); + + expect(saveAndWriteTextFile).toHaveBeenCalledWith( + "Export settings", + "thinkbrain-settings.json", + expect.any(String) + ); + const contents = vi.mocked(saveAndWriteTextFile).mock.calls[0]![2]; + expect(JSON.parse(contents)).toEqual( + expect.objectContaining({ version: expect.any(Number), settings: expect.any(Object) }) + ); + expect(statusOf(host)).toBe("Settings exported."); + }); + it("says so when the settings file cannot be written", async () => { vi.mocked(saveAndWriteTextFile).mockRejectedValue( new Error("The chosen file could not be written.") diff --git a/apps/desktop/src/settings/SettingsHeaderBar.tsx b/apps/desktop/src/settings/SettingsHeaderBar.tsx index 7da2e121..f4668e89 100644 --- a/apps/desktop/src/settings/SettingsHeaderBar.tsx +++ b/apps/desktop/src/settings/SettingsHeaderBar.tsx @@ -11,13 +11,14 @@ import { Download, MoreVertical, RotateCcw, Upload } from "lucide-react"; import type { SettingsModule } from "@thinkbrain/core"; import { cn } from "../lib/utils"; import { Menu, MenuButton, MenuCheckbox, MenuSeparator } from "../shell/Menu"; -import { selectDirtyCount, selectIsDirty, useAllSettingsModules, useSettingsStore } from "./settingsStore"; +import { selectDirtyCount, selectIsDirty, useSettingsStore } from "./settingsStore"; +import { useAllSettingsModules } from "./settingsRegistry"; import { buildExportPayload, importSettings, - writeExportFile, type ImportResult } from "./settingsImportExport"; +import { saveAndWriteTextFile } from "../native/fs"; import { findSectionLabelPath, parseQualifiedSectionId } from "./sectionUtils"; import { useEffectiveValue } from "./useEffectiveValue"; import { useTransientStatus } from "./useTransientStatus"; @@ -112,7 +113,7 @@ export function SettingsHeaderBar({ if (!proceed) return; } - void writeExportFile(json) + void saveAndWriteTextFile("Export settings", "thinkbrain-settings.json", json) .then((written) => { if (written) status.show("Settings exported."); }) diff --git a/apps/desktop/src/settings/SettingsImportExport.test.ts b/apps/desktop/src/settings/SettingsImportExport.test.ts index 95fcb51e..8cfb641e 100644 --- a/apps/desktop/src/settings/SettingsImportExport.test.ts +++ b/apps/desktop/src/settings/SettingsImportExport.test.ts @@ -4,7 +4,6 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { buildExportPayload, - writeExportFile, importSettings } from "./settingsImportExport"; import { useSettingsStore } from "./settingsStore"; @@ -18,16 +17,12 @@ import { * Settings import/export logic tests. * * The native fs module is mocked via `vi.mock` so tests can control the file - * paths and contents returned by `saveAndWriteTextFile` and - * `pickAndReadTextFile`. The real module-scoped + * paths and contents returned by `pickAndReadTextFile`. The real module-scoped * `useSettingsStore` singleton is seeded directly via `setState`. */ // Mock the native fs module so we can control dialog+read/write results. vi.mock("../native/fs", () => ({ - saveAndWriteTextFile: vi.fn< - (title: string, defaultName: string, contents: string) => Promise - >(), pickAndReadTextFile: vi.fn< ( title: string, @@ -37,7 +32,7 @@ vi.mock("../native/fs", () => ({ })); // Import the mocked functions AFTER vi.mock so we get the mock implementations. -import { saveAndWriteTextFile, pickAndReadTextFile } from "../native/fs"; +import { pickAndReadTextFile } from "../native/fs"; /** * Default app values seeded into the store for most tests. Extends the shared @@ -67,7 +62,6 @@ beforeEach(() => { seedSettingsStore({ appValues: SEEDED_APP_VALUES }); // Reset mock call counts and default implementations. - vi.mocked(saveAndWriteTextFile).mockReset(); vi.mocked(pickAndReadTextFile).mockReset(); }); @@ -149,29 +143,6 @@ describe("buildExportPayload", () => { }); }); -describe("writeExportFile", () => { - it("writes the file when the user selects a path", async () => { - vi.mocked(saveAndWriteTextFile).mockResolvedValue(true); - - const result = await writeExportFile('{"version":1}'); - - expect(result).toBe(true); - expect(saveAndWriteTextFile).toHaveBeenCalledWith( - "Export settings", - "thinkbrain-settings.json", - '{"version":1}' - ); - }); - - it("returns false when the user cancels the save dialog", async () => { - vi.mocked(saveAndWriteTextFile).mockResolvedValue(false); - - const result = await writeExportFile('{"version":1}'); - - expect(result).toBe(false); - }); -}); - describe("importSettings", () => { it("stages known valid keys and returns correct counts", async () => { const importJson = JSON.stringify({ diff --git a/apps/desktop/src/settings/SettingsNav.tsx b/apps/desktop/src/settings/SettingsNav.tsx index a59b36d2..8413fde9 100644 --- a/apps/desktop/src/settings/SettingsNav.tsx +++ b/apps/desktop/src/settings/SettingsNav.tsx @@ -23,7 +23,8 @@ import { useDismissable } from "@thinkbrain/ui"; import { cn } from "../lib/utils"; import { createDebounced } from "../lib/debounce"; import { useNarrowViewport } from "../shell/useNarrowViewport"; -import { appSettingsRegistry, useSettingDefinitions, useSettingsModules, useSettingsStore } from "./settingsStore"; +import { useSettingsStore } from "./settingsStore"; +import { appSettingsRegistry, useSettingDefinitions, useSettingsModules } from "./settingsRegistry"; import { fuzzySearch, type FuzzySearchField } from "./fuzzyMatch"; import { requestSettingHighlight } from "./settingHighlight"; import { findSectionLabelPath, qualifiedSectionId, sectionAnchorId } from "./sectionUtils"; diff --git a/apps/desktop/src/settings/SettingsSearch.test.tsx b/apps/desktop/src/settings/SettingsSearch.test.tsx index 1855a5fb..b1caa5a0 100644 --- a/apps/desktop/src/settings/SettingsSearch.test.tsx +++ b/apps/desktop/src/settings/SettingsSearch.test.tsx @@ -4,7 +4,8 @@ import { act } from "react"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { SettingsTab } from "./SettingsTab"; -import { appSettingsRegistry, useSettingsStore } from "./settingsStore"; +import { useSettingsStore } from "./settingsStore"; +import { appSettingsRegistry } from "./settingsRegistry"; import { createSettingsTestHarness, seedSettingsStore diff --git a/apps/desktop/src/settings/SettingsTab.test.tsx b/apps/desktop/src/settings/SettingsTab.test.tsx index afc80c4c..ab889328 100644 --- a/apps/desktop/src/settings/SettingsTab.test.tsx +++ b/apps/desktop/src/settings/SettingsTab.test.tsx @@ -29,7 +29,8 @@ import { isTauri } from "@tauri-apps/api/core"; import { workspaceDesktopApi } from "../workspace/workspaceAdapter"; import { invokeNativeCommand } from "../native/commands"; import { SettingsTab } from "./SettingsTab"; -import { useSettingsStore, appSettingsRegistry, selectIsDirty } from "./settingsStore"; +import { useSettingsStore, selectIsDirty } from "./settingsStore"; +import { appSettingsRegistry } from "./settingsRegistry"; import { setExtensionBootstrap } from "../extensions/bootstrapRef"; import { setWorkspaceBridge } from "../extensions/workspaceBridge"; import { registerControl, type ControlProps } from "./controlRegistry"; diff --git a/apps/desktop/src/settings/ThemeSectionControls.test.tsx b/apps/desktop/src/settings/ThemeSectionControls.test.tsx index 92067639..56de315a 100644 --- a/apps/desktop/src/settings/ThemeSectionControls.test.tsx +++ b/apps/desktop/src/settings/ThemeSectionControls.test.tsx @@ -30,10 +30,17 @@ import { // bridges. Each test customizes the mock implementations as needed. vi.mock("./themeImportExport", () => ({ buildThemeExport: vi.fn<() => Promise>(), - writeThemeExportFile: vi.fn<(json: string) => Promise>(), importTheme: vi.fn<() => Promise>() })); +// The toolbar writes exports through the native fs adapter directly; mock it +// so each test controls the save-dialog outcome. +vi.mock("../native/fs", () => ({ + saveAndWriteTextFile: vi.fn< + (title: string, defaultName: string, contents: string) => Promise + >() +})); + // Mock the themeAdapter so the picker's listThemes() call is deterministic and // never touches the native bridge. Each test customizes the resolved value. vi.mock("./themeAdapter", () => ({ @@ -43,9 +50,9 @@ vi.mock("./themeAdapter", () => ({ // Import the mocked functions AFTER vi.mock so we get the mock implementations. import { buildThemeExport, - writeThemeExportFile, importTheme } from "./themeImportExport"; +import { saveAndWriteTextFile } from "../native/fs"; import { listThemes } from "./themeAdapter"; const harness = createSettingsTestHarness(); @@ -56,7 +63,7 @@ beforeEach(() => { // Reset mock call counts and default implementations. vi.mocked(buildThemeExport).mockReset(); - vi.mocked(writeThemeExportFile).mockReset(); + vi.mocked(saveAndWriteTextFile).mockReset(); vi.mocked(importTheme).mockReset(); vi.mocked(listThemes).mockReset(); @@ -206,7 +213,7 @@ describe("ThemeToolbar", () => { describe("handleExport", () => { it("shows 'Theme exported.' on a successful write", async () => { - vi.mocked(writeThemeExportFile).mockResolvedValue(true); + vi.mocked(saveAndWriteTextFile).mockResolvedValue(true); const el = await harness.render(); const exportBtn = el.querySelector( @@ -214,13 +221,17 @@ describe("ThemeToolbar", () => { )!; await harness.click(exportBtn); - expect(writeThemeExportFile).toHaveBeenCalledWith('{"name":"x"}'); + expect(saveAndWriteTextFile).toHaveBeenCalledWith( + "Export theme", + "theme.tbtheme.json", + '{"name":"x"}' + ); expect(getStatus(el)).toBe("Theme exported."); }); it("shows no status message when the user cancels the save dialog", async () => { // Cancel resolves false — a non-event the toolbar ignores. - vi.mocked(writeThemeExportFile).mockResolvedValue(false); + vi.mocked(saveAndWriteTextFile).mockResolvedValue(false); const el = await harness.render(); const exportBtn = el.querySelector( @@ -233,7 +244,7 @@ describe("ThemeToolbar", () => { it("shows an 'Export failed' status message when the write throws", async () => { // Write failures now throw (fail-loudly) and are surfaced via .catch(). - vi.mocked(writeThemeExportFile).mockRejectedValue( + vi.mocked(saveAndWriteTextFile).mockRejectedValue( new Error("disk full") ); const el = await harness.render(); diff --git a/apps/desktop/src/settings/ThemeSectionControls.tsx b/apps/desktop/src/settings/ThemeSectionControls.tsx index 321e4900..63448536 100644 --- a/apps/desktop/src/settings/ThemeSectionControls.tsx +++ b/apps/desktop/src/settings/ThemeSectionControls.tsx @@ -16,10 +16,10 @@ import { useSettingsStore } from "./settingsStore"; import { listThemes, type ThemeEntry } from "./themeAdapter"; import { buildThemeExport, - writeThemeExportFile, importTheme, type ImportThemeResult } from "./themeImportExport"; +import { saveAndWriteTextFile } from "../native/fs"; import { useTransientStatus } from "./useTransientStatus"; import { useEffectiveValue } from "./useEffectiveValue"; @@ -204,7 +204,7 @@ export function ThemeToolbar() { */ const handleExport = useCallback((): void => { void buildThemeExport() - .then((json) => writeThemeExportFile(json)) + .then((json) => saveAndWriteTextFile("Export theme", "theme.tbtheme.json", json)) .then((written) => { if (written) { status.show("Theme exported."); diff --git a/apps/desktop/src/settings/appSettingsFile.test.ts b/apps/desktop/src/settings/appSettingsFile.test.ts index a61726c8..28b5703f 100644 --- a/apps/desktop/src/settings/appSettingsFile.test.ts +++ b/apps/desktop/src/settings/appSettingsFile.test.ts @@ -1,137 +1,84 @@ import { beforeEach, describe, expect, it, vi } from "vitest"; +import type { DocumentChain, DocumentChainOptions } from "../native/documentChain"; + +/** + * Wiring tests only. The chain's ordering/conflict semantics are covered by + * native/documentChain.test.ts; here we prove this module forwards the right + * command names, contents, precondition, key, and conflict code — and that its + * exported functions reach the singleton chain. + */ + +const mocks = vi.hoisted(() => ({ + options: undefined as DocumentChainOptions | undefined, + chainRead: vi.fn(), + chainUpdate: vi.fn(), + invoke: vi.fn<(command: string, args?: Record) => Promise>() +})); + +vi.mock("../native/documentChain", () => ({ + createDocumentChain: vi.fn((options: DocumentChainOptions): DocumentChain => { + mocks.options = options; + return { read: mocks.chainRead, update: mocks.chainUpdate }; + }) +})); + vi.mock("../native/commands", async (importOriginal) => ({ ...(await importOriginal()), - invokeNativeCommand: vi.fn() + invokeNativeCommand: mocks.invoke })); -import { invokeNativeCommand, NativeCommandError } from "../native/commands"; import { readAppSettingsDocument, updateAppSettingsDocument } from "./appSettingsFile"; -const invoke = vi.mocked(invokeNativeCommand); - -/** A stand-in for the app-settings file on disk, so a write is visible to the next read. */ -let disk: string | null = null; +const options = mocks.options!; beforeEach(() => { - disk = null; - invoke.mockReset(); - invoke.mockImplementation((async (command: string, args?: Record) => { - if (command === "read_app_settings") return disk; - if (command === "write_app_settings") { - disk = args!.contents!; - return null; - } - throw new Error(`unexpected command ${command}`); - }) as unknown as typeof invokeNativeCommand); + // Clear call state without dropping the captured singleton options. + mocks.chainRead.mockReset(); + mocks.chainUpdate.mockReset(); + mocks.invoke.mockReset(); }); -const parse = (raw: string | null): Record => - raw === null ? {} : (JSON.parse(raw) as Record); - -const patch = (key: string, value: unknown) => (raw: string | null) => - JSON.stringify({ ...parse(raw), [key]: value }); - describe("the app settings document", () => { - it("reads what was written", async () => { - await updateAppSettingsDocument(patch("appearance.theme", "dark")); + it("reads through the singleton chain under the constant app key", async () => { + mocks.chainRead.mockResolvedValue("doc"); - expect(parse(await readAppSettingsDocument())).toEqual({ "appearance.theme": "dark" }); + await expect(readAppSettingsDocument()).resolves.toBe("doc"); + expect(mocks.chainRead).toHaveBeenCalledWith("app"); }); - /** - * The bug this exists to prevent: `update_desktop_state` lands (a tab opens) - * between the store's read and its write, so a save must not revise a copy - * that write has already superseded — that is how a save reverted every - * desktop-state change made since the app started. - */ - it("shows each writer the previous writer's result", async () => { - await Promise.all([ - updateAppSettingsDocument(patch("appearance.theme", "dark")), - updateAppSettingsDocument(patch("desktopState", { openTabs: ["a"] })) - ]); - - expect(parse(disk)).toEqual({ - "appearance.theme": "dark", - desktopState: { openTabs: ["a"] } - }); - }); + it("updates through the singleton chain and forwards the revise callback unchanged", async () => { + mocks.chainUpdate.mockResolvedValue("written-doc"); + const revise = (current: string | null): string => current ?? ""; - /** One writer's failure must not strand every writer behind it. */ - it("carries on after an update fails", async () => { - const failed = updateAppSettingsDocument(() => { - throw new Error("nope"); - }); - const after = updateAppSettingsDocument(patch("appearance.theme", "dark")); - - await expect(failed).rejects.toThrow("nope"); - await expect(after).resolves.toContain("appearance.theme"); - expect(parse(disk)).toEqual({ "appearance.theme": "dark" }); + await expect(updateAppSettingsDocument(revise)).resolves.toBe("written-doc"); + expect(mocks.chainUpdate).toHaveBeenCalledWith("app", revise); }); - /** - * Another writer — `update_desktop_state` or another window's save — can - * land between this write's read and its own write. The - * host rejects the stale write rather than letting it through, so the - * revision has to be recomputed against what is actually there now. - */ - it("recomputes the revision when another writer landed first", async () => { - disk = JSON.stringify({ desktopState: { openTabs: ["a"] } }); - let interfered = false; - invoke.mockImplementation((async (command: string, args?: Record) => { - if (command === "read_app_settings") return disk; - if (command === "write_app_settings") { - if (!interfered) { - interfered = true; - // `update_desktop_state` lands, so this write's `expected` is stale. - disk = JSON.stringify({ desktopState: { openTabs: ["a", "b"] } }); - throw new NativeCommandError({ - code: "settings.app_conflict", - message: "The application settings changed while this one was being saved." - }); - } - disk = args!.contents!; - return null; - } - throw new Error(`unexpected command ${command}`); - }) as unknown as typeof invokeNativeCommand); - - await updateAppSettingsDocument(patch("appearance.theme", "dark")); - - expect(parse(disk)).toEqual({ - desktopState: { openTabs: ["a", "b"] }, - "appearance.theme": "dark" - }); + it("configures the app settings conflict code", () => { + expect(options.conflictCode).toBe("settings.app_conflict"); }); - it("sends what it read as the write's precondition", async () => { - disk = JSON.stringify({ "appearance.theme": "light" }); - - await updateAppSettingsDocument(patch("appearance.theme", "dark")); + it("reads through read_app_settings", async () => { + mocks.invoke.mockResolvedValue("doc"); - expect(invoke).toHaveBeenCalledWith("write_app_settings", { - contents: JSON.stringify({ "appearance.theme": "dark" }), - expected: JSON.stringify({ "appearance.theme": "light" }) - }); + await expect(options.read("app")).resolves.toBe("doc"); + expect(mocks.invoke).toHaveBeenCalledWith("read_app_settings"); }); - it("gives up rather than retrying a conflict for ever", async () => { - invoke.mockImplementation((async (command: string) => { - if (command === "read_app_settings") return disk; - throw new NativeCommandError({ - code: "settings.app_conflict", - message: "The application settings changed while this one was being saved." - }); - }) as unknown as typeof invokeNativeCommand); - - await expect( - updateAppSettingsDocument(patch("appearance.theme", "dark")) - ).rejects.toThrow("changed while this one was being saved"); + it("writes through write_app_settings with contents and precondition", async () => { + await options.write("app", "next-doc", "current-doc"); + expect(mocks.invoke).toHaveBeenCalledWith("write_app_settings", { + contents: "next-doc", + expected: "current-doc" + }); }); - it("returns the document it wrote", async () => { - const written = await updateAppSettingsDocument(patch("appearance.theme", "dark")); - - expect(written).toBe(disk); + it("passes a null precondition through", async () => { + await options.write("app", "next-doc", null); + expect(mocks.invoke).toHaveBeenCalledWith("write_app_settings", { + contents: "next-doc", + expected: null + }); }); }); diff --git a/apps/desktop/src/settings/settingsHelpers.ts b/apps/desktop/src/settings/settingsHelpers.ts index b22e6cfc..bddeec18 100644 --- a/apps/desktop/src/settings/settingsHelpers.ts +++ b/apps/desktop/src/settings/settingsHelpers.ts @@ -3,7 +3,7 @@ import type { SettingsRegistry, SettingScope } from "@thinkbrain/core"; -import type { SettingsStoreState } from "./settingsStore"; +import type { SettingsStoreState } from "./settingsStoreTypes"; /** * The single source of truth for effective-value precedence. diff --git a/apps/desktop/src/settings/settingsImportExport.ts b/apps/desktop/src/settings/settingsImportExport.ts index 45e09d92..8a77a8d4 100644 --- a/apps/desktop/src/settings/settingsImportExport.ts +++ b/apps/desktop/src/settings/settingsImportExport.ts @@ -9,8 +9,8 @@ * Returns the pretty-printed JSON string plus a list of non-portable * settings whose current values differ from their defaults (so the UI can * show a warning dialog before writing the file). - * 2. `writeExportFile(json)` — opens a native save dialog and writes the JSON - * to the chosen path. Returns `true` if written, `false` if cancelled. + * 2. The caller writes the JSON via `saveAndWriteTextFile` in `native/fs` — + * there is no per-module wrapper for a one-line save-dialog call. * * Import flow: * `importSettings()` — opens a native open dialog, reads the JSON file, @@ -29,8 +29,9 @@ import { validateSettings } from "@thinkbrain/core"; -import { appSettingsRegistry, useSettingsStore } from "./settingsStore"; -import { pickAndReadTextFile, saveAndWriteTextFile } from "../native/fs"; +import { useSettingsStore } from "./settingsStore"; +import { appSettingsRegistry } from "./settingsRegistry"; +import { pickAndReadTextFile } from "../native/fs"; // --------------------------------------------------------------------------- // Export. @@ -51,7 +52,7 @@ interface ExportPayload { * the registry, then returns the JSON string and a list of non-portable * settings whose current values differ from their defaults. The caller decides * whether to proceed (after showing a warning) and writes the file via - * `writeExportFile`. + * `saveAndWriteTextFile`. * * Only app-scoped settings are included (per epic design decision #6). * @@ -91,22 +92,6 @@ export function buildExportPayload(): ExportPayload { }; } -/** - * Opens a native save dialog and writes the export JSON to the chosen path. - * - * Args: - * json: The JSON string to write (from `buildExportPayload`). - * - * Returns: - * `true` if the file was written, `false` if the user cancelled the dialog. - * - * Throws: - * Error if a path was chosen and the write failed, so the caller can say so. - */ -export async function writeExportFile(json: string): Promise { - return await saveAndWriteTextFile("Export settings", "thinkbrain-settings.json", json); -} - // --------------------------------------------------------------------------- // Import. // --------------------------------------------------------------------------- diff --git a/apps/desktop/src/settings/settingsRegistry.ts b/apps/desktop/src/settings/settingsRegistry.ts new file mode 100644 index 00000000..98775dc7 --- /dev/null +++ b/apps/desktop/src/settings/settingsRegistry.ts @@ -0,0 +1,92 @@ +/** + * The application settings module registry and its live React snapshots. + * + * Kept separate from `settingsStore.ts`: the registry owns which settings + * exist, their defaults, and their scope, while the store owns loaded/staged + * values. UI components subscribe here rather than to the store so a schema + * registered by a lazily-activated extension is visible the moment it lands — + * no dependency on the store's lifecycle, and no import cycle (this module + * must not import the store). + */ + +import { useSyncExternalStore } from "react"; +import { + appearanceModule, + createSettingsRegistry, + editorModule, + settingsModule, + syncModule, + type SettingDefinition, + type SettingScope, + type SettingsModule, + type SettingsRegistry +} from "@thinkbrain/core"; +import { uiModuleForFormFactor } from "./uiModuleDefaults"; + +/** + * Module-scoped registry with the built-in Appearance, Editor, Settings, Sync, + * and UI modules. + * + * Exported so UI components (Story 3+) can look up definitions, sections, and + * modules for rendering. Extensions register additional modules here on + * activation. + */ +export const appSettingsRegistry: SettingsRegistry = createSettingsRegistry(); +appSettingsRegistry.register(appearanceModule); +appSettingsRegistry.register(editorModule); +appSettingsRegistry.register(settingsModule); +appSettingsRegistry.register(syncModule); +appSettingsRegistry.register(uiModuleForFormFactor()); + +/** + * Module-level subscribe for `useSyncExternalStore`: a stable reference so + * React does not resubscribe on every render. + */ +const subscribeToSettingsRegistry = (listener: () => void): (() => void) => + appSettingsRegistry.subscribe(listener); + +/** + * Live snapshot of the settings modules contributing to one scope. + * + * Subscribing is required, not optional: extension schemas register on + * activation, which routinely happens while the settings tab is open — a + * one-shot read during render would leave the nav and content showing a + * module that was never registered (or was already disposed). The registry + * keeps the returned array referentially stable between changes, so it can + * serve as the `useSyncExternalStore` snapshot directly. + */ +export function useSettingsModules(scope: SettingScope): readonly SettingsModule[] { + return useSyncExternalStore( + subscribeToSettingsRegistry, + () => appSettingsRegistry.getModulesByScope(scope), + () => appSettingsRegistry.getModulesByScope(scope) + ); +} + +/** + * Live snapshot of every registered settings module, unprojected. + * + * Used by the header-bar breadcrumbs, which resolve a section id across all + * modules rather than one scope's projection. + */ +export function useAllSettingsModules(): readonly SettingsModule[] { + return useSyncExternalStore( + subscribeToSettingsRegistry, + () => appSettingsRegistry.getAllModules(), + () => appSettingsRegistry.getAllModules() + ); +} + +/** + * Live snapshot of every resolved setting definition. + * + * Used by nav search so a schema registered while settings is open is + * searchable immediately rather than after the next unrelated re-render. + */ +export function useSettingDefinitions(): readonly SettingDefinition[] { + return useSyncExternalStore( + subscribeToSettingsRegistry, + () => appSettingsRegistry.getAllDefinitions(), + () => appSettingsRegistry.getAllDefinitions() + ); +} diff --git a/apps/desktop/src/settings/settingsStore.extensions.test.ts b/apps/desktop/src/settings/settingsStore.extensions.test.ts new file mode 100644 index 00000000..4f89b7da --- /dev/null +++ b/apps/desktop/src/settings/settingsStore.extensions.test.ts @@ -0,0 +1,411 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; + +import { createSettingsStore, selectIsDirty } from "./settingsStore"; +import { appSettingsRegistry } from "./settingsRegistry"; +import { createMockGateway, APP_JSON_WITH_DESKTOP_STATE } from "./settingsStoreTestHelpers"; +import type { SettingsModule } from "@thinkbrain/core"; + +/** + * Extension-facing store behavior: mixed-scope modules, the scoped + * `settings.set` write, and late-registered schema merging. + */ + +/** + * D45: an extension module holds settings of both scopes — the journal's folder + * is per workspace while its calendar defaults are global (D64). Scope is a + * property of each setting, not of the module it arrived in. + */ +describe("mixed-scope modules (D45)", () => { + const MODULE_ID = "extension-scope-fixture"; + const ROOT = `${MODULE_ID}.root`; + const VIEW = `${MODULE_ID}.view`; + + let registration: { dispose: () => void } | null = null; + + beforeEach(() => { + registration = appSettingsRegistry.register({ + id: MODULE_ID, + label: "Scope fixture", + scope: "app", + sections: [ + { + id: `${MODULE_ID}.main`, + label: "Main", + settings: [ + { + key: "root", + type: "path", + label: "Folder", + description: "Per workspace.", + default: "journal", + scope: "workspace", + section: `${MODULE_ID}.main` + }, + { + key: "view", + type: "string", + label: "View", + description: "Global.", + default: "month", + scope: "app", + section: `${MODULE_ID}.main` + } + ] + } + ] + }); + }); + + afterEach(() => { + registration?.dispose(); + registration = null; + }); + + it("reads a workspace override for a workspace-scoped setting", async () => { + const store = createSettingsStore( + createMockGateway(null, JSON.stringify({ version: 1, [ROOT]: "diary" })) + ); + + await store.getState().loadSettings("/notes/work"); + + expect(store.getState().getEffectiveValue(ROOT)).toBe("diary"); + }); + + it("falls back to the default when the workspace has no override", async () => { + const store = createSettingsStore(createMockGateway(null, JSON.stringify({ version: 1 }))); + + await store.getState().loadSettings("/notes/work"); + + expect(store.getState().getEffectiveValue(ROOT)).toBe("journal"); + }); + + it("falls back to the default when no workspace is open", async () => { + const store = createSettingsStore(createMockGateway(null, null)); + + await store.getState().loadSettings(null); + + expect(store.getState().getEffectiveValue(ROOT)).toBe("journal"); + }); + + it("persists a workspace-scoped edit to the workspace file", async () => { + // The bug this covers loses the edit outright: it is routed to the workspace + // payload and then dropped by the serializer. + const gateway = createMockGateway(null, JSON.stringify({ version: 1 })); + const store = createSettingsStore(gateway); + await store.getState().loadSettings("/notes/work"); + + store.getState().stageChange(ROOT, "diary"); + const result = await store.getState().saveSettings(); + + expect(result.success).toBe(true); + const written = gateway.writtenWorkspaceSettings.at(-1); + expect(written?.rootPath).toBe("/notes/work"); + expect(JSON.parse(written?.contents ?? "{}")[ROOT]).toBe("diary"); + expect(store.getState().getEffectiveValue(ROOT)).toBe("diary"); + }); + + it("reports failure rather than success when nothing could be written", async () => { + // Reporting success while the value never left memory is how a Save button + // ends up doing nothing, twice, with no explanation. + const store = createSettingsStore(createMockGateway(null, null)); + await store.getState().loadSettings(null); + + store.getState().stageChange(ROOT, "diary"); + const result = await store.getState().saveSettings(); + + expect(result.success).toBe(false); + expect(store.getState().saveError).toMatch(/workspace/i); + }); + + it("keeps a workspace-scoped edit staged when there is no workspace to write it to", async () => { + // Nothing can persist it yet, so dropping it from `stagedChanges` would lose + // the edit outright and report success while doing so. + const gateway = createMockGateway(null, null); + const store = createSettingsStore(gateway); + await store.getState().loadSettings(null); + + store.getState().stageChange(ROOT, "diary"); + await store.getState().saveSettings(); + + expect(gateway.writtenWorkspaceSettings).toHaveLength(0); + expect(store.getState().stagedChanges[ROOT]).toBe("diary"); + expect(selectIsDirty(store.getState())).toBe(true); + expect(store.getState().getEffectiveValue(ROOT)).toBe("diary"); + }); + + it("keeps a workspace override out of the app settings file", async () => { + const gateway = createMockGateway(null, JSON.stringify({ version: 1 })); + const store = createSettingsStore(gateway); + await store.getState().loadSettings("/notes/work"); + + store.getState().stageChange(ROOT, "diary"); + await store.getState().saveSettings(); + + for (const contents of gateway.writtenAppSettings) { + expect(Object.keys(JSON.parse(contents))).not.toContain(ROOT); + } + }); + + it("leaves an app-scoped setting in the same module global", async () => { + const gateway = createMockGateway(null, JSON.stringify({ version: 1 })); + const store = createSettingsStore(gateway); + await store.getState().loadSettings("/notes/work"); + + store.getState().stageChange(VIEW, "week"); + await store.getState().saveSettings(); + + const appWritten = gateway.writtenAppSettings.at(-1); + expect(JSON.parse(appWritten ?? "{}")[VIEW]).toBe("week"); + const workspaceWritten = gateway.writtenWorkspaceSettings.at(-1); + expect(Object.keys(JSON.parse(workspaceWritten?.contents ?? "{}"))).not.toContain(VIEW); + }); + + it("ignores a workspace file that tries to override an app-scoped setting", async () => { + // Workspace files travel with a vault; one must not reach across scopes. + const store = createSettingsStore( + createMockGateway(null, JSON.stringify({ version: 1, [VIEW]: "week" })) + ); + + await store.getState().loadSettings("/notes/work"); + + expect(store.getState().getEffectiveValue(VIEW)).toBe("month"); + }); + + it("re-reads workspace values when the active workspace changes", async () => { + const gateway = createMockGateway(null, JSON.stringify({ version: 1, [ROOT]: "diary" })); + const store = createSettingsStore(gateway); + await store.getState().loadSettings("/notes/work"); + + gateway.readWorkspaceSettings = vi.fn(async () => + JSON.stringify({ version: 1, [ROOT]: "personal-journal" }) + ); + await store.getState().loadSettings("/notes/home"); + + expect(store.getState().getEffectiveValue(ROOT)).toBe("personal-journal"); + }); +}); + +/** + * The scoped write behind extension `settings.set` (D81): only the one key is + * persisted, so an extension's write neither flushes unrelated staged edits + * nor gets stranded by them. + */ +describe("setSingleSettingImmediately (scoped write)", () => { + it("persists only its own key, leaving other staged changes pending", async () => { + const gateway = createMockGateway(APP_JSON_WITH_DESKTOP_STATE); + const store = createSettingsStore(gateway); + await store.getState().loadSettings(null); + + store.getState().stageChange("appearance.theme", "light"); + await store.getState().setSingleSettingImmediately("editor.fontSize", 20); + + const written = JSON.parse(gateway.writtenAppSettings.at(-1) as string); + expect(written["editor.fontSize"]).toBe(20); + // The unrelated staged edit was not flushed: the document keeps the + // value it had, and the edit stays pending for the user's own save. + expect(written["appearance.theme"]).toBe("dark"); + expect(store.getState().stagedChanges).toEqual({ "appearance.theme": "light" }); + expect(store.getState().appValues["editor.fontSize"]).toBe(20); + }); + + it("persists even when an unrelated staged value would fail validation", async () => { + // The bug this pins: a full save validates every effective value, so one + // bad staged key used to strand the extension's write as phantom-dirty. + const gateway = createMockGateway(null); + const store = createSettingsStore(gateway); + await store.getState().loadSettings(null); + store.getState().stageChange("editor.fontSize", 999); + + await store.getState().setSingleSettingImmediately("appearance.theme", "dark"); + + expect(gateway.writeAppSettings).toHaveBeenCalledTimes(1); + expect(store.getState().stagedChanges).toEqual({ "editor.fontSize": 999 }); + expect(store.getState().appValues["appearance.theme"]).toBe("dark"); + }); + + it("keeps the value staged when the write fails, so the session honours it", async () => { + const gateway = createMockGateway(null); + const store = createSettingsStore(gateway); + await store.getState().loadSettings(null); + gateway.writeAppSettings = vi.fn(async () => { + throw new Error("disk is full"); + }); + const errors = vi.spyOn(console, "error").mockImplementation(() => undefined); + + await store.getState().setSingleSettingImmediately("appearance.theme", "dark"); + + expect(store.getState().stagedChanges["appearance.theme"]).toBe("dark"); + expect(store.getState().getEffectiveValue("appearance.theme")).toBe("dark"); + errors.mockRestore(); + }); + + it("keeps a workspace-scoped write staged when no workspace is open", async () => { + const gateway = createMockGateway(null); + const store = createSettingsStore(gateway); + await store.getState().loadSettings(null); + + await store.getState().setSingleSettingImmediately("sync.destination", "nas"); + + expect(gateway.writeWorkspaceSettings).not.toHaveBeenCalled(); + expect(store.getState().stagedChanges["sync.destination"]).toBe("nas"); + expect(store.getState().getEffectiveValue("sync.destination")).toBe("nas"); + }); + + it("rejects an invalid value for its own key without touching other keys", async () => { + const gateway = createMockGateway(null); + const store = createSettingsStore(gateway); + await store.getState().loadSettings(null); + const errors = vi.spyOn(console, "error").mockImplementation(() => undefined); + + await store.getState().setSingleSettingImmediately("editor.fontSize", 999); + + expect(gateway.writeAppSettings).not.toHaveBeenCalled(); + expect(store.getState().stagedChanges["editor.fontSize"]).toBe(999); + expect(store.getState().validationDiagnostics.map((d) => d.path)).toContain( + "editor.fontSize" + ); + errors.mockRestore(); + }); +}); + +/** + * Late-registered schemas: `loadSettings` drops keys with no registered + * definition, so an extension schema that registers after load has to pull + * its persisted values out of the last-read document — which is exactly what + * the store's registry subscription does. + */ +describe("late-registered schema values", () => { + const LATE_FLAG = "late-module.flag"; + const lateModule: SettingsModule = { + id: "late-module", + label: "Late", + scope: "app", + sections: [ + { + id: "late-module.section", + label: "Late", + settings: [ + { + key: "flag", + type: "boolean", + label: "Flag", + description: "A late-registered flag.", + default: false, + scope: "app", + section: "late-module.section" + } + ] + } + ] + }; + const LATE_ROOT = "late-ws.root"; + const lateWorkspaceModule: SettingsModule = { + id: "late-ws", + label: "Late workspace", + scope: "app", + sections: [ + { + id: "late-ws.section", + label: "Late workspace", + settings: [ + { + key: "root", + type: "path", + label: "Root", + description: "A late-registered per-workspace folder.", + default: "journal", + scope: "workspace", + section: "late-ws.section" + } + ] + } + ] + }; + + it("merges a persisted extension value when its schema registers after load", async () => { + const gateway = createMockGateway( + JSON.stringify({ version: 1, [LATE_FLAG]: true }) + ); + const store = createSettingsStore(gateway); + await store.getState().loadSettings(null); + // Unknown at load: the key was dropped, not even a default held. + expect(store.getState().appValues[LATE_FLAG]).toBeUndefined(); + + const registration = appSettingsRegistry.register(lateModule); + try { + expect(store.getState().appValues[LATE_FLAG]).toBe(true); + expect(store.getState().getEffectiveValue(LATE_FLAG)).toBe(true); + } finally { + registration.dispose(); + } + }); + + it("merges a workspace-scoped persisted value for the open workspace", async () => { + const gateway = createMockGateway( + null, + JSON.stringify({ version: 1, [LATE_ROOT]: "diary" }) + ); + const store = createSettingsStore(gateway); + await store.getState().loadSettings("/notes/work"); + expect(store.getState().workspaceValues?.[LATE_ROOT]).toBeUndefined(); + + const registration = appSettingsRegistry.register(lateWorkspaceModule); + try { + expect(store.getState().workspaceValues?.[LATE_ROOT]).toBe("diary"); + expect(store.getState().getEffectiveValue(LATE_ROOT)).toBe("diary"); + } finally { + registration.dispose(); + } + }); + + it("keeps a staged user edit effective when the schema registers late", async () => { + const gateway = createMockGateway( + JSON.stringify({ version: 1, [LATE_FLAG]: false }) + ); + const store = createSettingsStore(gateway); + await store.getState().loadSettings(null); + // A pending edit for the not-yet-registered key — the merge must fill the + // loaded layer without overwriting the user's unsaved choice. + store.setState({ stagedChanges: { [LATE_FLAG]: true } }); + + const registration = appSettingsRegistry.register(lateModule); + try { + expect(store.getState().stagedChanges[LATE_FLAG]).toBe(true); + expect(store.getState().getEffectiveValue(LATE_FLAG)).toBe(true); + } finally { + registration.dispose(); + } + }); + + it("does not roll back a value written in-session when the module re-registers", async () => { + const registration = appSettingsRegistry.register(lateModule); + const gateway = createMockGateway( + JSON.stringify({ version: 1, [LATE_FLAG]: false }) + ); + const store = createSettingsStore(gateway); + await store.getState().loadSettings(null); + // An in-session write (e.g. the extension's own settings.set). + await store.getState().setSingleSettingImmediately(LATE_FLAG, true); + + // Deactivate + reactivate must not roll the session value back to the + // document's stale copy. + registration.dispose(); + const second = appSettingsRegistry.register(lateModule); + try { + expect(store.getState().appValues[LATE_FLAG]).toBe(true); + } finally { + second.dispose(); + } + }); + + it("does nothing before the first successful load", () => { + const store = createSettingsStore(createMockGateway(null)); + + const registration = appSettingsRegistry.register(lateModule); + try { + expect(store.getState().appValues[LATE_FLAG]).toBeUndefined(); + } finally { + registration.dispose(); + } + }); +}); diff --git a/apps/desktop/src/settings/settingsStore.test.ts b/apps/desktop/src/settings/settingsStore.test.ts index 3769106a..5dea46ce 100644 --- a/apps/desktop/src/settings/settingsStore.test.ts +++ b/apps/desktop/src/settings/settingsStore.test.ts @@ -1,81 +1,14 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { beforeEach, describe, expect, it, vi } from "vitest"; import { createSettingsStore, selectDirtyCount, - selectIsDirty, - type SettingsStoreGateway + selectIsDirty } from "./settingsStore"; -import { appSettingsRegistry } from "./settingsStore"; +import { appSettingsRegistry } from "./settingsRegistry"; +import { createMockGateway, APP_JSON_WITH_DESKTOP_STATE } from "./settingsStoreTestHelpers"; import { resolveEffectiveValue } from "./settingsHelpers"; -import { extractDefaults, type SettingDefinition, type SettingsModule } from "@thinkbrain/core"; - -/** - * Creates a mock gateway with controllable app/workspace settings payloads. - * - * The `writeAppSettings` / `writeWorkspaceSettings` mocks capture the serialized - * content so tests can assert what was persisted. Defaults to returning null - * (no settings file) unless overridden. - */ -function createMockGateway( - appSettings: string | null = null, - workspaceSettings: string | null = null -): SettingsStoreGateway & { - writtenAppSettings: string[]; - writtenWorkspaceSettings: { rootPath: string; contents: string }[]; - /** - * Simulates another writer — `update_desktop_state` or another window's - * save — landing on the app-settings document outside this - * store's knowledge, the way a tab open or panel resize does in production. - */ - setAppDocument(contents: string | null): void; -} { - const writtenAppSettings: string[] = []; - const writtenWorkspaceSettings: { rootPath: string; contents: string }[] = []; - // Stand-ins for the files, so `revise` sees what the last write left there. - let appDocument = appSettings; - let workspaceDocument = workspaceSettings; - - return { - readAppSettings: vi.fn(async () => appDocument), - writeAppSettings: vi.fn(async (revise: (current: string | null) => string) => { - const contents = revise(appDocument); - appDocument = contents; - writtenAppSettings.push(contents); - return contents; - }), - readWorkspaceSettings: vi.fn(async () => workspaceDocument), - writeWorkspaceSettings: vi.fn( - async (rootPath: string, revise: (current: string | null) => string) => { - const contents = revise(workspaceDocument); - workspaceDocument = contents; - writtenWorkspaceSettings.push({ rootPath, contents }); - return contents; - } - ), - setAppDocument: (contents: string | null) => { - appDocument = contents; - }, - writtenAppSettings, - writtenWorkspaceSettings - }; -} - -/** App settings JSON with a desktopState nested key (must be preserved). */ -const APP_JSON_WITH_DESKTOP_STATE = JSON.stringify({ - version: 1, - "appearance.theme": "dark", - "editor.fontSize": 20, - "editor.lineWrapping": false, - desktopState: { - version: 3, - lastWorkspacePath: "/notes/test", - explorerOpen: true, - leftPanelWidth: 288, - rightPanelWidth: 320, - bottomPanelOpen: false - } -}); +import { extractDefaults, type SettingDefinition } from "@thinkbrain/core"; describe("settingsStore", () => { beforeEach(() => { @@ -476,6 +409,9 @@ describe("settingsStore", () => { }); describe("getEffectiveValue", () => { + // One smoke test through the store action; the full precedence matrix + // (including falsy handling) lives in the canonical resolveEffectiveValue + // table below, and the wiring test there proves delegation. it("returns staged > loaded > default", async () => { const gateway = createMockGateway( JSON.stringify({ version: 1, "appearance.theme": "light" }) @@ -494,49 +430,6 @@ describe("settingsStore", () => { expect(store.getState().getEffectiveValue("editor.fontSize")).toBe(16); }); - // Falsy values must NOT be replaced by a lower-precedence layer. Each layer - // is checked by key presence (`in`), not truthiness, so a staged `false` is - // not silently dropped in favor of a saved `true`. These tests pin that - // behavior through the store action (which delegates to the shared - // `resolveEffectiveValue` helper). - it("keeps a staged falsy value over a saved truthy one", async () => { - const gateway = createMockGateway( - JSON.stringify({ - version: 1, - "editor.lineWrapping": true, - "editor.fontSize": 24, - "appearance.theme": "dark" - }) - ); - const store = createSettingsStore(gateway); - await store.getState().loadSettings(null); - - store.getState().stageChange("editor.lineWrapping", false); - expect(store.getState().getEffectiveValue("editor.lineWrapping")).toBe(false); - - store.getState().stageChange("editor.fontSize", 0); - expect(store.getState().getEffectiveValue("editor.fontSize")).toBe(0); - - store.getState().stageChange("appearance.theme", ""); - expect(store.getState().getEffectiveValue("appearance.theme")).toBe(""); - }); - - it("keeps a loaded falsy value over the default", async () => { - // The app settings file explicitly stores falsy values; they must win - // over the registry default rather than being treated as "missing". - const gateway = createMockGateway( - JSON.stringify({ - version: 1, - "editor.lineWrapping": false, - "editor.fontSize": 0 - }) - ); - const store = createSettingsStore(gateway); - await store.getState().loadSettings(null); - - expect(store.getState().getEffectiveValue("editor.lineWrapping")).toBe(false); - expect(store.getState().getEffectiveValue("editor.fontSize")).toBe(0); - }); }); }); @@ -847,403 +740,3 @@ describe("saveSettings concurrency", () => { expect(selectIsDirty(store.getState())).toBe(false); }); }); - -/** - * D45: an extension module holds settings of both scopes — the journal's folder - * is per workspace while its calendar defaults are global (D64). Scope is a - * property of each setting, not of the module it arrived in. - */ -describe("mixed-scope modules (D45)", () => { - const MODULE_ID = "extension-scope-fixture"; - const ROOT = `${MODULE_ID}.root`; - const VIEW = `${MODULE_ID}.view`; - - let registration: { dispose: () => void } | null = null; - - beforeEach(() => { - registration = appSettingsRegistry.register({ - id: MODULE_ID, - label: "Scope fixture", - scope: "app", - sections: [ - { - id: `${MODULE_ID}.main`, - label: "Main", - settings: [ - { - key: "root", - type: "path", - label: "Folder", - description: "Per workspace.", - default: "journal", - scope: "workspace", - section: `${MODULE_ID}.main` - }, - { - key: "view", - type: "string", - label: "View", - description: "Global.", - default: "month", - scope: "app", - section: `${MODULE_ID}.main` - } - ] - } - ] - }); - }); - - afterEach(() => { - registration?.dispose(); - registration = null; - }); - - it("reads a workspace override for a workspace-scoped setting", async () => { - const store = createSettingsStore( - createMockGateway(null, JSON.stringify({ version: 1, [ROOT]: "diary" })) - ); - - await store.getState().loadSettings("/notes/work"); - - expect(store.getState().getEffectiveValue(ROOT)).toBe("diary"); - }); - - it("falls back to the default when the workspace has no override", async () => { - const store = createSettingsStore(createMockGateway(null, JSON.stringify({ version: 1 }))); - - await store.getState().loadSettings("/notes/work"); - - expect(store.getState().getEffectiveValue(ROOT)).toBe("journal"); - }); - - it("falls back to the default when no workspace is open", async () => { - const store = createSettingsStore(createMockGateway(null, null)); - - await store.getState().loadSettings(null); - - expect(store.getState().getEffectiveValue(ROOT)).toBe("journal"); - }); - - it("persists a workspace-scoped edit to the workspace file", async () => { - // The bug this covers loses the edit outright: it is routed to the workspace - // payload and then dropped by the serializer. - const gateway = createMockGateway(null, JSON.stringify({ version: 1 })); - const store = createSettingsStore(gateway); - await store.getState().loadSettings("/notes/work"); - - store.getState().stageChange(ROOT, "diary"); - const result = await store.getState().saveSettings(); - - expect(result.success).toBe(true); - const written = gateway.writtenWorkspaceSettings.at(-1); - expect(written?.rootPath).toBe("/notes/work"); - expect(JSON.parse(written?.contents ?? "{}")[ROOT]).toBe("diary"); - expect(store.getState().getEffectiveValue(ROOT)).toBe("diary"); - }); - - it("reports failure rather than success when nothing could be written", async () => { - // Reporting success while the value never left memory is how a Save button - // ends up doing nothing, twice, with no explanation. - const store = createSettingsStore(createMockGateway(null, null)); - await store.getState().loadSettings(null); - - store.getState().stageChange(ROOT, "diary"); - const result = await store.getState().saveSettings(); - - expect(result.success).toBe(false); - expect(store.getState().saveError).toMatch(/workspace/i); - }); - - it("keeps a workspace-scoped edit staged when there is no workspace to write it to", async () => { - // Nothing can persist it yet, so dropping it from `stagedChanges` would lose - // the edit outright and report success while doing so. - const gateway = createMockGateway(null, null); - const store = createSettingsStore(gateway); - await store.getState().loadSettings(null); - - store.getState().stageChange(ROOT, "diary"); - await store.getState().saveSettings(); - - expect(gateway.writtenWorkspaceSettings).toHaveLength(0); - expect(store.getState().stagedChanges[ROOT]).toBe("diary"); - expect(selectIsDirty(store.getState())).toBe(true); - expect(store.getState().getEffectiveValue(ROOT)).toBe("diary"); - }); - - it("keeps a workspace override out of the app settings file", async () => { - const gateway = createMockGateway(null, JSON.stringify({ version: 1 })); - const store = createSettingsStore(gateway); - await store.getState().loadSettings("/notes/work"); - - store.getState().stageChange(ROOT, "diary"); - await store.getState().saveSettings(); - - for (const contents of gateway.writtenAppSettings) { - expect(Object.keys(JSON.parse(contents))).not.toContain(ROOT); - } - }); - - it("leaves an app-scoped setting in the same module global", async () => { - const gateway = createMockGateway(null, JSON.stringify({ version: 1 })); - const store = createSettingsStore(gateway); - await store.getState().loadSettings("/notes/work"); - - store.getState().stageChange(VIEW, "week"); - await store.getState().saveSettings(); - - const appWritten = gateway.writtenAppSettings.at(-1); - expect(JSON.parse(appWritten ?? "{}")[VIEW]).toBe("week"); - const workspaceWritten = gateway.writtenWorkspaceSettings.at(-1); - expect(Object.keys(JSON.parse(workspaceWritten?.contents ?? "{}"))).not.toContain(VIEW); - }); - - it("ignores a workspace file that tries to override an app-scoped setting", async () => { - // Workspace files travel with a vault; one must not reach across scopes. - const store = createSettingsStore( - createMockGateway(null, JSON.stringify({ version: 1, [VIEW]: "week" })) - ); - - await store.getState().loadSettings("/notes/work"); - - expect(store.getState().getEffectiveValue(VIEW)).toBe("month"); - }); - - it("re-reads workspace values when the active workspace changes", async () => { - const gateway = createMockGateway(null, JSON.stringify({ version: 1, [ROOT]: "diary" })); - const store = createSettingsStore(gateway); - await store.getState().loadSettings("/notes/work"); - - gateway.readWorkspaceSettings = vi.fn(async () => - JSON.stringify({ version: 1, [ROOT]: "personal-journal" }) - ); - await store.getState().loadSettings("/notes/home"); - - expect(store.getState().getEffectiveValue(ROOT)).toBe("personal-journal"); - }); -}); - -/** - * The scoped write behind extension `settings.set` (D81): only the one key is - * persisted, so an extension's write neither flushes unrelated staged edits - * nor gets stranded by them. - */ -describe("setSingleSettingImmediately (scoped write)", () => { - it("persists only its own key, leaving other staged changes pending", async () => { - const gateway = createMockGateway(APP_JSON_WITH_DESKTOP_STATE); - const store = createSettingsStore(gateway); - await store.getState().loadSettings(null); - - store.getState().stageChange("appearance.theme", "light"); - await store.getState().setSingleSettingImmediately("editor.fontSize", 20); - - const written = JSON.parse(gateway.writtenAppSettings.at(-1) as string); - expect(written["editor.fontSize"]).toBe(20); - // The unrelated staged edit was not flushed: the document keeps the - // value it had, and the edit stays pending for the user's own save. - expect(written["appearance.theme"]).toBe("dark"); - expect(store.getState().stagedChanges).toEqual({ "appearance.theme": "light" }); - expect(store.getState().appValues["editor.fontSize"]).toBe(20); - }); - - it("persists even when an unrelated staged value would fail validation", async () => { - // The bug this pins: a full save validates every effective value, so one - // bad staged key used to strand the extension's write as phantom-dirty. - const gateway = createMockGateway(null); - const store = createSettingsStore(gateway); - await store.getState().loadSettings(null); - store.getState().stageChange("editor.fontSize", 999); - - await store.getState().setSingleSettingImmediately("appearance.theme", "dark"); - - expect(gateway.writeAppSettings).toHaveBeenCalledTimes(1); - expect(store.getState().stagedChanges).toEqual({ "editor.fontSize": 999 }); - expect(store.getState().appValues["appearance.theme"]).toBe("dark"); - }); - - it("keeps the value staged when the write fails, so the session honours it", async () => { - const gateway = createMockGateway(null); - const store = createSettingsStore(gateway); - await store.getState().loadSettings(null); - gateway.writeAppSettings = vi.fn(async () => { - throw new Error("disk is full"); - }); - const errors = vi.spyOn(console, "error").mockImplementation(() => undefined); - - await store.getState().setSingleSettingImmediately("appearance.theme", "dark"); - - expect(store.getState().stagedChanges["appearance.theme"]).toBe("dark"); - expect(store.getState().getEffectiveValue("appearance.theme")).toBe("dark"); - errors.mockRestore(); - }); - - it("keeps a workspace-scoped write staged when no workspace is open", async () => { - const gateway = createMockGateway(null); - const store = createSettingsStore(gateway); - await store.getState().loadSettings(null); - - await store.getState().setSingleSettingImmediately("sync.destination", "nas"); - - expect(gateway.writeWorkspaceSettings).not.toHaveBeenCalled(); - expect(store.getState().stagedChanges["sync.destination"]).toBe("nas"); - expect(store.getState().getEffectiveValue("sync.destination")).toBe("nas"); - }); - - it("rejects an invalid value for its own key without touching other keys", async () => { - const gateway = createMockGateway(null); - const store = createSettingsStore(gateway); - await store.getState().loadSettings(null); - const errors = vi.spyOn(console, "error").mockImplementation(() => undefined); - - await store.getState().setSingleSettingImmediately("editor.fontSize", 999); - - expect(gateway.writeAppSettings).not.toHaveBeenCalled(); - expect(store.getState().stagedChanges["editor.fontSize"]).toBe(999); - expect(store.getState().validationDiagnostics.map((d) => d.path)).toContain( - "editor.fontSize" - ); - errors.mockRestore(); - }); -}); - -/** - * Late-registered schemas: `loadSettings` drops keys with no registered - * definition, so an extension schema that registers after load has to pull - * its persisted values out of the last-read document — which is exactly what - * the store's registry subscription does. - */ -describe("late-registered schema values", () => { - const LATE_FLAG = "late-module.flag"; - const lateModule: SettingsModule = { - id: "late-module", - label: "Late", - scope: "app", - sections: [ - { - id: "late-module.section", - label: "Late", - settings: [ - { - key: "flag", - type: "boolean", - label: "Flag", - description: "A late-registered flag.", - default: false, - scope: "app", - section: "late-module.section" - } - ] - } - ] - }; - const LATE_ROOT = "late-ws.root"; - const lateWorkspaceModule: SettingsModule = { - id: "late-ws", - label: "Late workspace", - scope: "app", - sections: [ - { - id: "late-ws.section", - label: "Late workspace", - settings: [ - { - key: "root", - type: "path", - label: "Root", - description: "A late-registered per-workspace folder.", - default: "journal", - scope: "workspace", - section: "late-ws.section" - } - ] - } - ] - }; - - it("merges a persisted extension value when its schema registers after load", async () => { - const gateway = createMockGateway( - JSON.stringify({ version: 1, [LATE_FLAG]: true }) - ); - const store = createSettingsStore(gateway); - await store.getState().loadSettings(null); - // Unknown at load: the key was dropped, not even a default held. - expect(store.getState().appValues[LATE_FLAG]).toBeUndefined(); - - const registration = appSettingsRegistry.register(lateModule); - try { - expect(store.getState().appValues[LATE_FLAG]).toBe(true); - expect(store.getState().getEffectiveValue(LATE_FLAG)).toBe(true); - } finally { - registration.dispose(); - } - }); - - it("merges a workspace-scoped persisted value for the open workspace", async () => { - const gateway = createMockGateway( - null, - JSON.stringify({ version: 1, [LATE_ROOT]: "diary" }) - ); - const store = createSettingsStore(gateway); - await store.getState().loadSettings("/notes/work"); - expect(store.getState().workspaceValues?.[LATE_ROOT]).toBeUndefined(); - - const registration = appSettingsRegistry.register(lateWorkspaceModule); - try { - expect(store.getState().workspaceValues?.[LATE_ROOT]).toBe("diary"); - expect(store.getState().getEffectiveValue(LATE_ROOT)).toBe("diary"); - } finally { - registration.dispose(); - } - }); - - it("keeps a staged user edit effective when the schema registers late", async () => { - const gateway = createMockGateway( - JSON.stringify({ version: 1, [LATE_FLAG]: false }) - ); - const store = createSettingsStore(gateway); - await store.getState().loadSettings(null); - // A pending edit for the not-yet-registered key — the merge must fill the - // loaded layer without overwriting the user's unsaved choice. - store.setState({ stagedChanges: { [LATE_FLAG]: true } }); - - const registration = appSettingsRegistry.register(lateModule); - try { - expect(store.getState().stagedChanges[LATE_FLAG]).toBe(true); - expect(store.getState().getEffectiveValue(LATE_FLAG)).toBe(true); - } finally { - registration.dispose(); - } - }); - - it("does not roll back a value written in-session when the module re-registers", async () => { - const registration = appSettingsRegistry.register(lateModule); - const gateway = createMockGateway( - JSON.stringify({ version: 1, [LATE_FLAG]: false }) - ); - const store = createSettingsStore(gateway); - await store.getState().loadSettings(null); - // An in-session write (e.g. the extension's own settings.set). - await store.getState().setSingleSettingImmediately(LATE_FLAG, true); - - // Deactivate + reactivate must not roll the session value back to the - // document's stale copy. - registration.dispose(); - const second = appSettingsRegistry.register(lateModule); - try { - expect(store.getState().appValues[LATE_FLAG]).toBe(true); - } finally { - second.dispose(); - } - }); - - it("does nothing before the first successful load", () => { - const store = createSettingsStore(createMockGateway(null)); - - const registration = appSettingsRegistry.register(lateModule); - try { - expect(store.getState().appValues[LATE_FLAG]).toBeUndefined(); - } finally { - registration.dispose(); - } - }); -}); diff --git a/apps/desktop/src/settings/settingsStore.ts b/apps/desktop/src/settings/settingsStore.ts index 53e52c53..8bc903bb 100644 --- a/apps/desktop/src/settings/settingsStore.ts +++ b/apps/desktop/src/settings/settingsStore.ts @@ -13,22 +13,11 @@ */ import { create } from "zustand"; -import { useSyncExternalStore } from "react"; import { readAppSettingsDocument, updateAppSettingsDocument } from "./appSettingsFile"; import { readWorkspaceSettingsDocument, updateWorkspaceSettingsDocument } from "../workspace/workspaceSettingsFile"; -import { - appearanceModule, - createSettingsRegistry, - editorModule, - settingsModule, - syncModule, - validateSettings, - type SettingsDiagnostic, - type SettingsRegistry -} from "@thinkbrain/core"; import { getErrorMessage, isRecord, @@ -36,73 +25,26 @@ import { parseDynamicWorkspaceSettings, serializeDynamicAppSettings, serializeDynamicWorkspaceSettings, - type SettingDefinition, + validateSettings, type SettingScope, - type SettingsModule + type SettingsRegistry } from "@thinkbrain/core"; import { scheduleAutosave } from "./autosaveScheduler"; -import { uiModuleForFormFactor } from "./uiModuleDefaults"; +import { appSettingsRegistry } from "./settingsRegistry"; import { effectiveSettingValue, partitionByScope } from "./settingsHelpers"; - -// --------------------------------------------------------------------------- -// Registry instance with built-in modules registered. -// --------------------------------------------------------------------------- - -/** - * Module-scoped registry with the built-in Appearance, Editor, Settings, Sync, - * and UI modules. - * - * Exported so UI components (Story 3+) can look up definitions, sections, and - * modules for rendering. Extensions will register additional modules here in a - * follow-up story. - */ -export const appSettingsRegistry: SettingsRegistry = createSettingsRegistry(); -appSettingsRegistry.register(appearanceModule); -appSettingsRegistry.register(editorModule); -appSettingsRegistry.register(settingsModule); -appSettingsRegistry.register(syncModule); -appSettingsRegistry.register(uiModuleForFormFactor()); +import type { + SaveSettingsResult, + SettingsStoreGateway, + SettingsStoreState +} from "./settingsStoreTypes"; // --------------------------------------------------------------------------- // Gateway: abstraction over native settings I/O (for testability). // --------------------------------------------------------------------------- -/** - * Gateway interface for reading/writing app and workspace settings. - * - * Mirrors the `DesktopStateGateway` pattern from `desktopState.ts`. The default - * implementation calls native Tauri commands; tests inject a mock. - */ -export interface SettingsStoreGateway { - readAppSettings(): Promise; - /** - * Revises the app-settings document and returns what was written. - * - * A document rather than a payload: `update_desktop_state` writes to the - * same file on every tab open or panel resize, so this store has to - * serialize against the document as it - * is at the moment of writing rather than the copy it read at load. `revise` - * runs inside the document's own update chain (see `appSettingsFile.ts`). - */ - writeAppSettings(revise: (current: string | null) => string): Promise; - readWorkspaceSettings(rootPath: string): Promise; - /** - * Revises the workspace document and returns what was written. - * - * A document rather than a payload: this store is one of two writers to the - * file, so it has to serialize against the document as it is at the moment of - * writing rather than the copy it read when the workspace opened. `revise` - * runs inside the file's own update chain (see `workspaceSettingsFile.ts`). - */ - writeWorkspaceSettings( - rootPath: string, - revise: (current: string | null) => string - ): Promise; -} - /** Default gateway backed by native Tauri commands. */ const nativeSettingsGateway: SettingsStoreGateway = { readAppSettings: () => readAppSettingsDocument(), @@ -112,75 +54,6 @@ const nativeSettingsGateway: SettingsStoreGateway = { updateWorkspaceSettingsDocument(rootPath, revise) }; -// --------------------------------------------------------------------------- -// Store types. -// --------------------------------------------------------------------------- - -/** Result of a save attempt: either success or validation diagnostics. */ -export interface SaveSettingsResult { - readonly success: boolean; - readonly diagnostics: SettingsDiagnostic[]; -} - -/** The full Zustand store state shape (state + actions). */ -export interface SettingsStoreState { - // --- Loaded values --- - /** App-scoped settings keyed by full setting key (defaults merged). */ - appValues: Record; - /** Workspace-scoped settings, or null when no workspace is open. */ - workspaceValues: Record | null; - /** The root path of the currently loaded workspace, if any. */ - workspaceRootPath: string | null; - - // --- Staged changes --- - /** Pending changes keyed by full setting key, not yet persisted. */ - stagedChanges: Record; - - // --- UI state --- - activeSection: string | null; - searchQuery: string; - - // --- Errors / validation --- - loadError: string | null; - saveError: string | null; - validationDiagnostics: SettingsDiagnostic[]; - /** True after the first successful or failed load. */ - loaded: boolean; - - // --- Actions --- - loadSettings(rootPath: string | null): Promise; - stageChange(key: string, value: unknown): void; - saveSettings(): Promise; - resetStaged(): void; - resetSection(sectionId: string): void; - setActiveSection(id: string | null): void; - setSearchQuery(query: string): void; - getEffectiveValue(key: string): unknown; - /** - * Stages a single setting and saves immediately. - * - * Used by palette commands, where there is no Save bar to press. Any other - * staged edits are persisted alongside it — acceptable because the Settings - * tab and the palette are not usually driven at the same time. Extensions - * use {@link setSingleSettingImmediately} instead: a timer- or event-driven - * write must not silently flush user edits. - */ - setSettingImmediately(key: string, value: unknown): Promise; - /** - * Stages a single setting and persists only that key. - * - * The scoped counterpart to {@link setSettingImmediately}, used by extension - * `settings.set` (D81). Unlike the palette path it does not co-persist - * unrelated staged edits, and an unrelated staged key that fails validation - * cannot strand the write as a phantom-dirty entry. - * - * On failure — a rejected write, an invalid value, or a workspace-scoped key - * with no workspace open — the value stays staged: the session still honours - * it and a later `saveSettings()` retries the write. - */ - setSingleSettingImmediately(key: string, value: unknown): Promise; -} - // --------------------------------------------------------------------------- // Store factory + default hook. // --------------------------------------------------------------------------- @@ -633,59 +506,6 @@ export function createSettingsStore( */ export const useSettingsStore = createSettingsStore(); -/** - * Module-level subscribe for `useSyncExternalStore`: a stable reference so - * React does not resubscribe on every render. - */ -const subscribeToSettingsRegistry = (listener: () => void): (() => void) => - appSettingsRegistry.subscribe(listener); - -/** - * Live snapshot of the settings modules contributing to one scope. - * - * Subscribing is required, not optional: extension schemas register on - * activation, which routinely happens while the settings tab is open — a - * one-shot read during render would leave the nav and content showing a - * module that was never registered (or was already disposed). The registry - * keeps the returned array referentially stable between changes, so it can - * serve as the `useSyncExternalStore` snapshot directly. - */ -export function useSettingsModules(scope: SettingScope): readonly SettingsModule[] { - return useSyncExternalStore( - subscribeToSettingsRegistry, - () => appSettingsRegistry.getModulesByScope(scope), - () => appSettingsRegistry.getModulesByScope(scope) - ); -} - -/** - * Live snapshot of every registered settings module, unprojected. - * - * Used by the header-bar breadcrumbs, which resolve a section id across all - * modules rather than one scope's projection. - */ -export function useAllSettingsModules(): readonly SettingsModule[] { - return useSyncExternalStore( - subscribeToSettingsRegistry, - () => appSettingsRegistry.getAllModules(), - () => appSettingsRegistry.getAllModules() - ); -} - -/** - * Live snapshot of every resolved setting definition. - * - * Used by nav search so a schema registered while settings is open is - * searchable immediately rather than after the next unrelated re-render. - */ -export function useSettingDefinitions(): readonly SettingDefinition[] { - return useSyncExternalStore( - subscribeToSettingsRegistry, - () => appSettingsRegistry.getAllDefinitions(), - () => appSettingsRegistry.getAllDefinitions() - ); -} - /** True when there are any staged (unsaved) changes. */ export const selectIsDirty = (state: SettingsStoreState): boolean => Object.keys(state.stagedChanges).length > 0; diff --git a/apps/desktop/src/settings/settingsStoreTestHelpers.ts b/apps/desktop/src/settings/settingsStoreTestHelpers.ts new file mode 100644 index 00000000..d15fc90d --- /dev/null +++ b/apps/desktop/src/settings/settingsStoreTestHelpers.ts @@ -0,0 +1,75 @@ +import { vi } from "vitest"; + +import type { SettingsStoreGateway } from "./settingsStoreTypes"; + +/** + * Shared mock gateway for the settings store test suites + * (`settingsStore.test.ts` and `settingsStore.extensions.test.ts`). + */ + +/** + * Creates a mock gateway with controllable app/workspace settings payloads. + * + * The `writeAppSettings` / `writeWorkspaceSettings` mocks capture the serialized + * content so tests can assert what was persisted. Defaults to returning null + * (no settings file) unless overridden. + */ +export function createMockGateway( + appSettings: string | null = null, + workspaceSettings: string | null = null +): SettingsStoreGateway & { + writtenAppSettings: string[]; + writtenWorkspaceSettings: { rootPath: string; contents: string }[]; + /** + * Simulates another writer — `update_desktop_state` or another window's + * save — landing on the app-settings document outside this + * store's knowledge, the way a tab open or panel resize does in production. + */ + setAppDocument(contents: string | null): void; +} { + const writtenAppSettings: string[] = []; + const writtenWorkspaceSettings: { rootPath: string; contents: string }[] = []; + // Stand-ins for the files, so `revise` sees what the last write left there. + let appDocument = appSettings; + let workspaceDocument = workspaceSettings; + + return { + readAppSettings: vi.fn(async () => appDocument), + writeAppSettings: vi.fn(async (revise: (current: string | null) => string) => { + const contents = revise(appDocument); + appDocument = contents; + writtenAppSettings.push(contents); + return contents; + }), + readWorkspaceSettings: vi.fn(async () => workspaceDocument), + writeWorkspaceSettings: vi.fn( + async (rootPath: string, revise: (current: string | null) => string) => { + const contents = revise(workspaceDocument); + workspaceDocument = contents; + writtenWorkspaceSettings.push({ rootPath, contents }); + return contents; + } + ), + setAppDocument: (contents: string | null) => { + appDocument = contents; + }, + writtenAppSettings, + writtenWorkspaceSettings + }; +} + +/** App settings JSON with a desktopState nested key (must be preserved). */ +export const APP_JSON_WITH_DESKTOP_STATE = JSON.stringify({ + version: 1, + "appearance.theme": "dark", + "editor.fontSize": 20, + "editor.lineWrapping": false, + desktopState: { + version: 3, + lastWorkspacePath: "/notes/test", + explorerOpen: true, + leftPanelWidth: 288, + rightPanelWidth: 320, + bottomPanelOpen: false + } +}); diff --git a/apps/desktop/src/settings/settingsStoreTypes.ts b/apps/desktop/src/settings/settingsStoreTypes.ts new file mode 100644 index 00000000..ad08bd1f --- /dev/null +++ b/apps/desktop/src/settings/settingsStoreTypes.ts @@ -0,0 +1,107 @@ +/** + * The settings store's public type surface: the gateway it persists through, + * the result a save reports, and the full store state shape. + * + * Separated from `settingsStore.ts` so the persistence/state contracts live + * apart from the store implementation; nothing here is a runtime value. + */ + +import type { SettingsDiagnostic } from "@thinkbrain/core"; + +/** + * Gateway interface for reading/writing app and workspace settings. + * + * Mirrors the `DesktopStateGateway` pattern from `desktopState.ts`. The default + * implementation calls native Tauri commands; tests inject a mock. + */ +export interface SettingsStoreGateway { + readAppSettings(): Promise; + /** + * Revises the app-settings document and returns what was written. + * + * A document rather than a payload: `update_desktop_state` writes to the + * same file on every tab open or panel resize, so this store has to + * serialize against the document as it + * is at the moment of writing rather than the copy it read at load. `revise` + * runs inside the document's own update chain (see `appSettingsFile.ts`). + */ + writeAppSettings(revise: (current: string | null) => string): Promise; + readWorkspaceSettings(rootPath: string): Promise; + /** + * Revises the workspace document and returns what was written. + * + * A document rather than a payload: this store is one of two writers to the + * file, so it has to serialize against the document as it is at the moment of + * writing rather than the copy it read when the workspace opened. `revise` + * runs inside the file's own update chain (see `workspaceSettingsFile.ts`). + */ + writeWorkspaceSettings( + rootPath: string, + revise: (current: string | null) => string + ): Promise; +} + +/** Result of a save attempt: either success or validation diagnostics. */ +export interface SaveSettingsResult { + readonly success: boolean; + readonly diagnostics: SettingsDiagnostic[]; +} + +/** The full Zustand store state shape (state + actions). */ +export interface SettingsStoreState { + // --- Loaded values --- + /** App-scoped settings keyed by full setting key (defaults merged). */ + appValues: Record; + /** Workspace-scoped settings, or null when no workspace is open. */ + workspaceValues: Record | null; + /** The root path of the currently loaded workspace, if any. */ + workspaceRootPath: string | null; + + // --- Staged changes --- + /** Pending changes keyed by full setting key, not yet persisted. */ + stagedChanges: Record; + + // --- UI state --- + activeSection: string | null; + searchQuery: string; + + // --- Errors / validation --- + loadError: string | null; + saveError: string | null; + validationDiagnostics: SettingsDiagnostic[]; + /** True after the first successful or failed load. */ + loaded: boolean; + + // --- Actions --- + loadSettings(rootPath: string | null): Promise; + stageChange(key: string, value: unknown): void; + saveSettings(): Promise; + resetStaged(): void; + resetSection(sectionId: string): void; + setActiveSection(id: string | null): void; + setSearchQuery(query: string): void; + getEffectiveValue(key: string): unknown; + /** + * Stages a single setting and saves immediately. + * + * Used by palette commands, where there is no Save bar to press. Any other + * staged edits are persisted alongside it — acceptable because the Settings + * tab and the palette are not usually driven at the same time. Extensions + * use {@link setSingleSettingImmediately} instead: a timer- or event-driven + * write must not silently flush user edits. + */ + setSettingImmediately(key: string, value: unknown): Promise; + /** + * Stages a single setting and persists only that key. + * + * The scoped counterpart to {@link setSettingImmediately}, used by extension + * `settings.set` (D81). Unlike the palette path it does not co-persist + * unrelated staged edits, and an unrelated staged key that fails validation + * cannot strand the write as a phantom-dirty entry. + * + * On failure — a rejected write, an invalid value, or a workspace-scoped key + * with no workspace open — the value stays staged: the session still honours + * it and a later `saveSettings()` retries the write. + */ + setSingleSettingImmediately(key: string, value: unknown): Promise; +} diff --git a/apps/desktop/src/settings/settingsTestHelpers.ts b/apps/desktop/src/settings/settingsTestHelpers.ts index 4ed44b20..50655180 100644 --- a/apps/desktop/src/settings/settingsTestHelpers.ts +++ b/apps/desktop/src/settings/settingsTestHelpers.ts @@ -2,7 +2,8 @@ import { act } from "react"; import { createRoot, type Root } from "react-dom/client"; import { vi } from "vitest"; -import { useSettingsStore, type SettingsStoreState } from "./settingsStore"; +import { useSettingsStore } from "./settingsStore"; +import type { SettingsStoreState } from "./settingsStoreTypes"; /** * Shared test helpers for settings component and logic tests — extracted from diff --git a/apps/desktop/src/settings/themeImportExport.test.ts b/apps/desktop/src/settings/themeImportExport.test.ts index d57b0d1c..529b3f2a 100644 --- a/apps/desktop/src/settings/themeImportExport.test.ts +++ b/apps/desktop/src/settings/themeImportExport.test.ts @@ -6,8 +6,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; * Theme import/export logic tests. * * The native fs module is mocked via `vi.mock` so tests can control the file - * paths and contents returned by `saveAndWriteTextFile` and - * `pickAndReadTextFile`. The DOM-reading helpers + * paths and contents returned by `pickAndReadTextFile`. The DOM-reading helpers * (`readCurrentTokenValues`, `readCurrentThemeBase`) read from * `document.documentElement` and `getComputedStyle`, so tests stub * `getComputedStyle` and set the `data-thinkbrain-theme` attribute directly to @@ -17,9 +16,6 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; // Mock the native fs module so we can control dialog+read/write results. vi.mock("../native/fs", () => ({ - saveAndWriteTextFile: vi.fn< - (title: string, defaultName: string, contents: string) => Promise - >(), pickAndReadTextFile: vi.fn< ( title: string, @@ -34,11 +30,10 @@ vi.mock("./themeAdapter", () => ({ })); import { readThemeFile } from "./themeAdapter"; -import { saveAndWriteTextFile, pickAndReadTextFile } from "../native/fs"; +import { pickAndReadTextFile } from "../native/fs"; import { buildThemeExport, buildThemeExportPayload, - writeThemeExportFile, importTheme, readCurrentTokenValues, readCurrentThemeBase @@ -70,7 +65,6 @@ beforeEach(() => { seedSettingsStore(); // Reset mock call counts and default implementations. - vi.mocked(saveAndWriteTextFile).mockReset(); vi.mocked(pickAndReadTextFile).mockReset(); // Default DOM state: light theme with the mock tokens. @@ -193,39 +187,6 @@ describe("buildThemeExportPayload", () => { }); }); -describe("writeThemeExportFile", () => { - it("writes the file when the user selects a path", async () => { - vi.mocked(saveAndWriteTextFile).mockResolvedValue(true); - - const result = await writeThemeExportFile('{"name":"x"}'); - - expect(result).toBe(true); - expect(saveAndWriteTextFile).toHaveBeenCalledWith( - "Export theme", - "theme.tbtheme.json", - '{"name":"x"}' - ); - }); - - it("returns false when the user cancels the save dialog", async () => { - vi.mocked(saveAndWriteTextFile).mockResolvedValue(false); - - const result = await writeThemeExportFile('{"name":"x"}'); - - expect(result).toBe(false); - }); - - it("throws when the write fails (fail-loud)", async () => { - vi.mocked(saveAndWriteTextFile).mockRejectedValue( - new Error("The chosen file could not be written.") - ); - - // Write failures now throw instead of returning false, so the caller can - // surface a destructive status message. Cancel (above) still returns false. - await expect(writeThemeExportFile('{"name":"x"}')).rejects.toThrow(); - }); -}); - describe("importTheme", () => { it("stages appearance.themeFile when parsing succeeds and returns the theme name", async () => { const themeJson = JSON.stringify({ diff --git a/apps/desktop/src/settings/themeImportExport.ts b/apps/desktop/src/settings/themeImportExport.ts index fe047833..a2d145b2 100644 --- a/apps/desktop/src/settings/themeImportExport.ts +++ b/apps/desktop/src/settings/themeImportExport.ts @@ -15,10 +15,10 @@ * the computed values already include its overrides, so the exported file * captures exactly what the user sees — a useful starting point for * customization. - * 2. `writeThemeExportFile(json)` — opens a native save dialog and writes the - * JSON to the chosen path. Returns `true` if written, `false` if the user - * cancelled the dialog, and throws on write failure (disk full, permission - * denied, etc.) so the caller can surface a status message. + * 2. The caller writes the JSON via `saveAndWriteTextFile` in `native/fs` — + * there is no per-module wrapper for a one-line save-dialog call. The + * resolved `false` on cancel is a non-event; a rejection is a real write + * failure (disk full, permission denied) the caller surfaces. * * Import flow: * `importTheme()` — opens a native open dialog, reads the file, parses it with @@ -41,11 +41,12 @@ import { type ThemeFile } from "@thinkbrain/core"; -import { appSettingsRegistry, useSettingsStore } from "./settingsStore"; +import { useSettingsStore } from "./settingsStore"; +import { appSettingsRegistry } from "./settingsRegistry"; import { resolveEffectiveValue } from "./settingsHelpers"; import { readThemeFile } from "./themeAdapter"; import { resolveThemeBase } from "./themeResolution"; -import { pickAndReadTextFile, saveAndWriteTextFile } from "../native/fs"; +import { pickAndReadTextFile } from "../native/fs"; // --------------------------------------------------------------------------- // DOM access (split out for testability). @@ -175,24 +176,6 @@ export async function buildThemeExport(): Promise { return buildThemeExportPayload(); } -/** - * Opens a native save dialog and writes the theme JSON to the chosen path. - * - * Args: - * json: The `.tbtheme.json` string to write (from `buildThemeExportPayload`). - * - * Returns: - * `true` if the file was written, `false` if the user cancelled the dialog. - * - * Throws: - * Error if the write itself failed (disk full, permission denied, etc.) so - * the caller can surface a status message. Cancel (above) returns `false` — - * a non-event the caller can ignore. - */ -export async function writeThemeExportFile(json: string): Promise { - return await saveAndWriteTextFile("Export theme", "theme.tbtheme.json", json); -} - // --------------------------------------------------------------------------- // Import. // --------------------------------------------------------------------------- diff --git a/apps/desktop/src/settings/useEffectiveValue.test.ts b/apps/desktop/src/settings/useEffectiveValue.test.ts index 5d1c2abf..e4496bd2 100644 --- a/apps/desktop/src/settings/useEffectiveValue.test.ts +++ b/apps/desktop/src/settings/useEffectiveValue.test.ts @@ -9,7 +9,9 @@ import { createSettingsTestHarness } from "./settingsTestHelpers"; /** * Exercises the hook through a small React component because its contract - * includes reactivity, not just value resolution. + * includes reactivity, not just value resolution. The pure precedence table + * itself is pinned in `settingsStore.test.ts` under `resolveEffectiveValue`; + * this suite only proves the hook re-renders as each store layer changes. */ function Probe({ settingKey }: { settingKey: string }) { const value = useEffectiveValue(settingKey); @@ -37,66 +39,53 @@ afterEach(async () => { container = null; }); -/** Renders the probe and flushes its initial render. */ -async function renderProbe(settingKey: string): Promise { - container = await harness.render(createElement(Probe, { settingKey })); -} - /** Reads the value currently rendered by the probe. */ function renderedValue(): string { return container?.querySelector("[data-testid='effective-value']")?.textContent ?? ""; } describe("useEffectiveValue", () => { - it("returns the staged value when present", async () => { - useSettingsStore.setState({ - appValues: { "appearance.theme": "light" }, - stagedChanges: { "appearance.theme": "dark" } - }); - - await renderProbe("appearance.theme"); + it("re-renders as each layer changes, including staged fallback and falsy", async () => { + // A loaded app value shows on mount. + useSettingsStore.setState({ appValues: { "appearance.theme": "light" } }); + container = await harness.render(createElement(Probe, { settingKey: "appearance.theme" })); + expect(renderedValue()).toBe("light"); + // With nothing staged, a loaded app update re-renders immediately — this + // is what pins the appValues subscription rather than any later fallback. + await act(async () => { + useSettingsStore.setState({ appValues: { "appearance.theme": "dark" } }); + }); expect(renderedValue()).toBe("dark"); - }); - it("falls back to appValues when no staged value is present", async () => { - useSettingsStore.setState({ - appValues: { "appearance.theme": "light" } + // A staged value masks the loaded layer. + await act(async () => { + useSettingsStore.getState().stageChange("appearance.theme", "system"); }); + expect(renderedValue()).toBe("system"); - await renderProbe("appearance.theme"); - - expect(renderedValue()).toBe("light"); - }); - - it("falls back to workspaceValues for workspace-scoped settings", async () => { - useSettingsStore.setState({ - appValues: { "sync.destination": "app-value" }, - workspaceValues: { "sync.destination": "workspace-value" } + // A loaded app change underneath a staged value stays hidden until the + // staged layer resets, and the hook then falls back to the newer value. + await act(async () => { + useSettingsStore.setState({ appValues: { "appearance.theme": "light" } }); }); - - await renderProbe("sync.destination"); - - expect(renderedValue()).toBe("workspace-value"); - }); - - it("falls back to the registry default when no stored value is present", async () => { - await renderProbe("appearance.theme"); - expect(renderedValue()).toBe("system"); - }); - - it("updates when the staged value changes", async () => { - useSettingsStore.setState({ - appValues: { "appearance.theme": "light" } + await act(async () => { + useSettingsStore.getState().resetStaged(); }); - await renderProbe("appearance.theme"); expect(renderedValue()).toBe("light"); + // Workspace values drive workspace-scoped keys reactively too — and a + // falsy workspace value must surface, not fall through to the default. await act(async () => { - useSettingsStore.getState().stageChange("appearance.theme", "dark"); + useSettingsStore.setState({ workspaceValues: { "sync.destination": "nas" } }); }); + container = await harness.render(createElement(Probe, { settingKey: "sync.destination" })); + expect(renderedValue()).toBe("nas"); - expect(renderedValue()).toBe("dark"); + await act(async () => { + useSettingsStore.setState({ workspaceValues: { "sync.destination": "" } }); + }); + expect(renderedValue()).toBe(""); }); }); diff --git a/apps/desktop/src/settings/useEffectiveValue.ts b/apps/desktop/src/settings/useEffectiveValue.ts index b86c0b12..4d052566 100644 --- a/apps/desktop/src/settings/useEffectiveValue.ts +++ b/apps/desktop/src/settings/useEffectiveValue.ts @@ -1,4 +1,5 @@ -import { appSettingsRegistry, useSettingsStore } from "./settingsStore"; +import { useSettingsStore } from "./settingsStore"; +import { appSettingsRegistry } from "./settingsRegistry"; import { resolveEffectiveValue } from "./settingsHelpers"; /** diff --git a/apps/desktop/src/shell/useShellShortcuts.test.tsx b/apps/desktop/src/shell/useShellShortcuts.test.tsx index fb0c2b60..de66da07 100644 --- a/apps/desktop/src/shell/useShellShortcuts.test.tsx +++ b/apps/desktop/src/shell/useShellShortcuts.test.tsx @@ -5,7 +5,8 @@ import { afterEach, describe, expect, it, vi } from "vitest"; import type { DesktopCommandContext } from "../commands/commandRegistry"; import { createEditorTab, initialDesktopTabState, type DesktopTabAction } from "../tabs/tabModel"; -import { appSettingsRegistry, useSettingsStore } from "../settings/settingsStore"; +import { useSettingsStore } from "../settings/settingsStore"; +import { appSettingsRegistry } from "../settings/settingsRegistry"; import { useCommandSurface } from "./useShellCommands"; import { useShellShortcuts, type ShellShortcutsProps } from "./useShellShortcuts"; diff --git a/apps/desktop/src/shell/useWorkspaceLifecycle.session.test.tsx b/apps/desktop/src/shell/useWorkspaceLifecycle.session.test.tsx index 37d91819..288a3e00 100644 --- a/apps/desktop/src/shell/useWorkspaceLifecycle.session.test.tsx +++ b/apps/desktop/src/shell/useWorkspaceLifecycle.session.test.tsx @@ -59,7 +59,9 @@ vi.mock("../wikiLinks/wikiLinkIndexStore", () => ({ useWikiLinkIndexStore: index vi.mock("../settings/settingsStore", () => ({ useSettingsStore: Object.assign(() => false, { getState: () => ({ loaded: true, workspaceRootPath: null, loadSettings: () => Promise.resolve() }) - }), + }) +})); +vi.mock("../settings/settingsRegistry", () => ({ appSettingsRegistry: { register: () => ({ dispose: () => {} }), getDefinition: () => undefined } })); diff --git a/apps/desktop/src/shell/useWorkspaceLifecycle.test.tsx b/apps/desktop/src/shell/useWorkspaceLifecycle.test.tsx index 4ef1059d..81b593ee 100644 --- a/apps/desktop/src/shell/useWorkspaceLifecycle.test.tsx +++ b/apps/desktop/src/shell/useWorkspaceLifecycle.test.tsx @@ -92,7 +92,9 @@ vi.mock("../settings/settingsStore", () => ({ workspaceRootPath: null, loadSettings: () => Promise.resolve() }) - }), + }) +})); +vi.mock("../settings/settingsRegistry", () => ({ // Read transitively at `desktopExtensionHost` module load; never exercised // under these tests. appSettingsRegistry: { diff --git a/apps/desktop/src/tabs/tabRestore.test.tsx b/apps/desktop/src/tabs/tabRestore.test.tsx index eb3c0c7f..f7a16e80 100644 --- a/apps/desktop/src/tabs/tabRestore.test.tsx +++ b/apps/desktop/src/tabs/tabRestore.test.tsx @@ -75,7 +75,9 @@ vi.mock("../settings/settingsStore", () => ({ workspaceRootPath: null, loadSettings: () => Promise.resolve() }) - }), + }) +})); +vi.mock("../settings/settingsRegistry", () => ({ // Read transitively at `desktopExtensionHost` module load; never exercised // under these tests. appSettingsRegistry: { diff --git a/apps/desktop/src/workspace/workspaceSettingsFile.test.ts b/apps/desktop/src/workspace/workspaceSettingsFile.test.ts index 5948a35a..54d43372 100644 --- a/apps/desktop/src/workspace/workspaceSettingsFile.test.ts +++ b/apps/desktop/src/workspace/workspaceSettingsFile.test.ts @@ -1,150 +1,87 @@ import { beforeEach, describe, expect, it, vi } from "vitest"; +import type { DocumentChain, DocumentChainOptions } from "../native/documentChain"; + +/** + * Wiring tests only. The chain's ordering/conflict semantics are covered by + * native/documentChain.test.ts; here we prove this module forwards the right + * command names, rootPath, contents, precondition, and conflict code — and that + * its exported functions reach the singleton chain. + */ + +const mocks = vi.hoisted(() => ({ + options: undefined as DocumentChainOptions | undefined, + chainRead: vi.fn(), + chainUpdate: vi.fn(), + invoke: vi.fn<(command: string, args?: Record) => Promise>() +})); + +vi.mock("../native/documentChain", () => ({ + createDocumentChain: vi.fn((options: DocumentChainOptions): DocumentChain => { + mocks.options = options; + return { read: mocks.chainRead, update: mocks.chainUpdate }; + }) +})); + vi.mock("../native/commands", async (importOriginal) => ({ ...(await importOriginal()), - invokeNativeCommand: vi.fn() + invokeNativeCommand: mocks.invoke })); -import { invokeNativeCommand, NativeCommandError } from "../native/commands"; import { readWorkspaceSettingsDocument, updateWorkspaceSettingsDocument } from "./workspaceSettingsFile"; -const invoke = vi.mocked(invokeNativeCommand); - -/** A stand-in for the file on disk, so a write is visible to the next read. */ -let disk = new Map(); +const options = mocks.options!; beforeEach(() => { - disk = new Map(); - invoke.mockReset(); - invoke.mockImplementation((async (command: string, args: Record) => { - if (command === "read_workspace_settings") return disk.get(args.rootPath!) ?? null; - if (command === "write_workspace_settings") { - disk.set(args.rootPath!, args.contents!); - return null; - } - throw new Error(`unexpected command ${command}`); - }) as unknown as typeof invokeNativeCommand); + // Clear call state without dropping the captured singleton options. + mocks.chainRead.mockReset(); + mocks.chainUpdate.mockReset(); + mocks.invoke.mockReset(); }); -const parse = (raw: string | null): Record => - raw === null ? {} : (JSON.parse(raw) as Record); - -const patch = (key: string, value: unknown) => (raw: string | null) => - JSON.stringify({ ...parse(raw), [key]: value }); - describe("the workspace settings document", () => { - it("reads what was written", async () => { - await updateWorkspaceSettingsDocument("/vault", patch("showHidden", true)); + it("reads through the singleton chain under the exact workspace rootPath", async () => { + mocks.chainRead.mockResolvedValue("doc"); - expect(parse(await readWorkspaceSettingsDocument("/vault"))).toEqual({ showHidden: true }); - }); + await expect(readWorkspaceSettingsDocument("/vault-a")).resolves.toBe("doc"); + await readWorkspaceSettingsDocument("/vault-b"); - /** - * The bug this exists to prevent: two writers each read, merge their own key - * and write back. Interleaved, the second revises a document the first has - * already replaced, and the first writer's key is gone — which is how the - * journal's field definitions disappeared on restart. - */ - it("shows each writer the previous writer's result", async () => { - await Promise.all([ - updateWorkspaceSettingsDocument("/vault", patch("showHidden", true)), - updateWorkspaceSettingsDocument("/vault", patch("fieldDefinitions", ["mood"])) - ]); - - expect(parse(disk.get("/vault") ?? null)).toEqual({ - showHidden: true, - fieldDefinitions: ["mood"] - }); + expect(mocks.chainRead).toHaveBeenNthCalledWith(1, "/vault-a"); + expect(mocks.chainRead).toHaveBeenNthCalledWith(2, "/vault-b"); }); - it("keeps one workspace's writes from waiting on another's", async () => { - await Promise.all([ - updateWorkspaceSettingsDocument("/one", patch("showHidden", true)), - updateWorkspaceSettingsDocument("/two", patch("showHidden", false)) - ]); + it("updates through the singleton chain and forwards the revise callback unchanged", async () => { + mocks.chainUpdate.mockResolvedValue("written-doc"); + const revise = (current: string | null): string => current ?? ""; - expect(parse(disk.get("/one") ?? null)).toEqual({ showHidden: true }); - expect(parse(disk.get("/two") ?? null)).toEqual({ showHidden: false }); + await expect(updateWorkspaceSettingsDocument("/vault-a", revise)).resolves.toBe( + "written-doc" + ); + expect(mocks.chainUpdate).toHaveBeenCalledWith("/vault-a", revise); }); - /** One writer's failure must not strand every writer behind it. */ - it("carries on after an update fails", async () => { - const failed = updateWorkspaceSettingsDocument("/vault", () => { - throw new Error("nope"); - }); - const after = updateWorkspaceSettingsDocument("/vault", patch("showHidden", true)); - - await expect(failed).rejects.toThrow("nope"); - await expect(after).resolves.toContain("showHidden"); - expect(parse(disk.get("/vault") ?? null)).toEqual({ showHidden: true }); + it("configures the workspace settings conflict code", () => { + expect(options.conflictCode).toBe("settings.workspace_conflict"); }); - /** - * Another window can land a write between this window's read and its own - * write. The host rejects the stale write rather than letting it through, so - * the revision has to be recomputed against what is actually there now. - */ - it("recomputes the revision when another window wrote first", async () => { - disk.set("/vault", JSON.stringify({ fieldDefinitions: ["mood"] })); - let interfered = false; - invoke.mockImplementation((async (command: string, args: Record) => { - if (command === "read_workspace_settings") return disk.get(args.rootPath!) ?? null; - if (command === "write_workspace_settings") { - if (!interfered) { - interfered = true; - // The other window's write lands, so this one's `expected` is stale. - disk.set(args.rootPath!, JSON.stringify({ fieldDefinitions: ["mood", "sleep"] })); - throw new NativeCommandError({ - code: "settings.workspace_conflict", - message: "The workspace settings changed while this one was being saved." - }); - } - disk.set(args.rootPath!, args.contents!); - return null; - } - throw new Error(`unexpected command ${command}`); - }) as unknown as typeof invokeNativeCommand); - - await updateWorkspaceSettingsDocument("/vault", patch("showHidden", true)); - - expect(parse(disk.get("/vault") ?? null)).toEqual({ - fieldDefinitions: ["mood", "sleep"], - showHidden: true + it("reads through read_workspace_settings with the workspace rootPath", async () => { + mocks.invoke.mockResolvedValue("doc"); + + await expect(options.read("/vault")).resolves.toBe("doc"); + expect(mocks.invoke).toHaveBeenCalledWith("read_workspace_settings", { + rootPath: "/vault" }); }); - it("sends what it read as the write's precondition", async () => { - disk.set("/vault", JSON.stringify({ showHidden: false })); - - await updateWorkspaceSettingsDocument("/vault", patch("showHidden", true)); - - expect(invoke).toHaveBeenCalledWith("write_workspace_settings", { + it("writes through write_workspace_settings with rootPath, contents, and precondition", async () => { + await options.write("/vault", "next-doc", "current-doc"); + expect(mocks.invoke).toHaveBeenCalledWith("write_workspace_settings", { rootPath: "/vault", - contents: JSON.stringify({ showHidden: true }), - expected: JSON.stringify({ showHidden: false }) + contents: "next-doc", + expected: "current-doc" }); }); - - it("gives up rather than retrying a conflict for ever", async () => { - invoke.mockImplementation((async (command: string, args: Record) => { - if (command === "read_workspace_settings") return disk.get(args.rootPath!) ?? null; - throw new NativeCommandError({ - code: "settings.workspace_conflict", - message: "The workspace settings changed while this one was being saved." - }); - }) as unknown as typeof invokeNativeCommand); - - await expect( - updateWorkspaceSettingsDocument("/vault", patch("showHidden", true)) - ).rejects.toThrow("changed while this one was being saved"); - }); - - it("returns the document it wrote", async () => { - const written = await updateWorkspaceSettingsDocument("/vault", patch("showHidden", true)); - - expect(written).toBe(disk.get("/vault")); - }); }); diff --git a/docs/reviews/2026-10-10/README.md b/docs/reviews/2026-10-10/README.md index e3757dc4..3507b920 100644 --- a/docs/reviews/2026-10-10/README.md +++ b/docs/reviews/2026-10-10/README.md @@ -10,8 +10,8 @@ line-level bug hunts; every report ends with a "keep as-is" list. - `journal-source-audit-med-med.md` — top item: `JournalPanel`'s hand-rolled delete dialog should be `ModalDialog` (a11y regression); duplicated listing machinery wants a shared hook. -- `settings-source-audit-med-med.md` — duplicated test scaffolding, a - pass-through module, `settingsStore.ts` split. +- `settings-source-audit-med-med.md` — remaining export/test-surface and + theme/highlight simplification suggestions; initial source cleanup complete. - `architecture-shell-state-med-hard.md` — top item: one workspace-session owner above both chromes; the explorer should consume the session, not load it. Then: split the `ShellState` mega-bag, deduplicate chrome diff --git a/docs/reviews/2026-10-10/settings-source-audit-med-med.md b/docs/reviews/2026-10-10/settings-source-audit-med-med.md index 5d06db58..82ec5484 100644 --- a/docs/reviews/2026-10-10/settings-source-audit-med-med.md +++ b/docs/reviews/2026-10-10/settings-source-audit-med-med.md @@ -1,55 +1,28 @@ # Audit: `apps/desktop/src/settings/` — bloat, over-testing, consolidation -Task: `audit_settings_source` (done — see `plans/other_tasks/done-summary.md`). Read-only audit; no source changes. +Task: `audit_settings_source` (done — see `plans/other_tasks/done-summary.md`). Remaining findings after the `settings_source_cleanup` follow-up. ## Summary -- **Source**: 5,262 lines across 38 files (excl. tests + 262 lines of test helpers). -- **Tests**: 6,749 lines across 24 files → **1.28×** test-to-source ratio (highest in app). -- Largest gaps: `settingsStore.test.ts` 1,243 vs 693 src; `useEffectiveValue.test.ts` 102 vs 24 (4.3×); `appSettingsFile.test.ts` 137 vs 39 (3.5×); `SettingsTab.test.tsx` 413 vs 133 (3.1×); `useTransientStatus.test.tsx` 198 vs 74 (2.7×); `ThemeProvider.test.tsx` 601 vs 240 (2.5×, mostly justified — real async races). -- `settingsStore.ts` (693) exceeds the 500-line preferred limit despite prior splits. +Findings 1, 2, 3, and 5 are addressed: precedence/chain tests are consolidated, +export-write wrappers are removed (`importExportFiles.ts` was already absent), +and registry/hooks plus public types are separated from the store. The store is +515 lines; it was not further fragmented just to meet the preferred 500-line +limit. Original line-saving estimates were approximate, not acceptance targets. -**Top 3 recommendations** -1. Deduplicate effective-value precedence tests and document-chain wrapper tests → **~250 test lines** removed, zero coverage loss. -2. Delete `importExportFiles.ts` and the one-line `write*File` wrappers → **~70 lines**, removes a 3-deep pass-through chain. -3. Unexport test-only symbols/constants (`promoteRecentWorkspace`, `fuzzyScore`, `buildThemeExportPayload`, `parseDesktopState`, `DESKTOP_STATE_*` constants, etc.) and split the registry/live-hooks block out of `settingsStore.ts` → **~90 source lines** moved, file back under 500. +The remaining suggestions below were not part of that behavior-preserving cleanup. ## Findings | # | Finding | Files | Est. savings | Risk | |---|---------|-------|--------------|------| -| 1 | Effective-value precedence tested 3× | settingsStore.test.ts, useEffectiveValue.test.ts | ~130 test lines | Low | -| 2 | documentChain tested twice via thin wrappers | appSettingsFile.test.ts, workspace/workspaceSettingsFile.test.ts | ~120 test lines | Low | -| 3 | 3-layer pass-through on import/export file I/O | importExportFiles.ts, settingsImportExport.ts, themeImportExport.ts | ~70 lines | Low | | 4 | Dead / test-only exports | desktopState.ts, fuzzyMatch.ts, themeImportExport.ts, +6 files | ~15 symbols | Low | -| 5 | settingsStore.ts >500 lines; registry+hooks block separable | settingsStore.ts | ~90 lines moved | Low | | 6 | SettingsTab.test re-covers SettingsContent/Nav internals | SettingsTab.test.tsx | ~150 test lines | Med | | 7 | settingHighlight.ts over-built for a 1.2s row flash | settingHighlight.ts (+145-line test) | ~90 lines | Med | | 8 | Triplicated "parse JSON → isRecord" helpers | desktopState.ts, settingsStore.ts, settingsImportExport.ts | ~15 lines | Low | | 9 | Merge tiny theme modules | themeAdapter.ts, themeResolution.ts, themeInjection.ts | ~25 lines + plumbing | Low | | 10 | Minor: `describeError` duplicates `getErrorMessage` | desktopStatePersistence.ts:102-105 | ~4 lines | Trivial | -### 1. Effective-value precedence tested three times (over-testing) - -`resolveEffectiveValue` is an 18-line pure function (`settingsHelpers.ts:38-55`). It is pinned by a 14-case table at `settingsStore.test.ts:546-742` plus a store-delegation wiring test at `:744-798`. On top of that: - -- `settingsStore.test.ts:472-545` (`describe("getEffectiveValue")`, ~73 lines) re-tests staged>loaded>default and falsy handling through the store — all cases already in the table, and the wiring test already proves delegation. -- `useEffectiveValue.test.ts:51-87` re-runs 4 of the same precedence cases through React. Only `"updates when the staged value changes"` (:89-101) tests something the others can't (reactivity). - -**Action**: delete the `getEffectiveValue` describe except 1 smoke test; keep only the reactivity test in `useEffectiveValue.test.ts`. **~130 lines**, low risk. - -### 2. documentChain behavior tested twice through two thin wrappers - -`appSettingsFile.test.ts` (137) and `workspace/workspaceSettingsFile.test.ts` (150) run near-identical scenarios against `createDocumentChain` (`native/documentChain.ts`, itself untested): "reads what was written", "previous writer's result", "carries on after failure", "recomputes revision on conflict", "precondition", "gives up", "returns written doc". 7 of 8 `appSettingsFile` tests are mirrored in the workspace file; only "one workspace's writes don't wait on another's" is unique. - -**Action**: move chain semantics to a single `native/documentChain.test.ts` (~170 lines) and reduce each wrapper test to a thin wiring smoke test (~25 lines). **~120 lines net**, low risk — also fixes the real gap that `documentChain` has no direct tests. - -### 3. Three-layer pass-through on import/export file I/O - -`writeExportFile` (`settingsImportExport.ts:106-108`) → `writeJsonViaSaveDialog` (`importExportFiles.ts:25-31`) → `saveAndWriteTextFile` (`native/fs.ts:34`), and the same for `writeThemeExportFile`/`readPickedFile`. `importExportFiles.ts` adds zero behavior — `native/fs.ts` already documents the identical "false/null = cancel, failures throw" contract. - -**Action**: call `native/fs` directly from `settingsImportExport.ts`/`themeImportExport.ts`; delete `importExportFiles.ts` (54) and the two `write*File` wrappers (~14), folding the default filenames into callers. **~70 lines + a whole file**, low risk. Keep `PickedFile` only if a signature needs a named type (it doesn't — `NativePickedTextFile` exists). - ### 4. Dead / test-only exports (grep-verified) Used only inside their own file, or only by their own test (dead-ish): @@ -70,10 +43,6 @@ Also: `createSettingsStore` (`settingsStore.ts:204`) is called in production onl **Action**: unexport the function/constant cases (keep types — they cost nothing and document shapes); where a test needs the seam, test through the public path instead (`buildThemeExport` covers `buildThemeExportPayload`). **~15 symbols**, low risk. -### 5. settingsStore.ts over the 500-line guideline - -`settingsStore.ts` is 693 lines. The clean split: the registry singleton + three `useSyncExternalStore` hooks (`appSettingsRegistry`, `useSettingsModules`, `useAllSettingsModules`, `useSettingDefinitions`, lines 50-68 and 634-685, ~90 lines) move to a `settingsRegistry.ts`. `useEffectiveValue.ts` (24) could fold in there too — it is one 12-line function. **~115 lines moved**, settingsStore back near 500. Low risk; imports change in ~10 files. - ### 6. SettingsTab.test re-covers SettingsContent/SettingsNav internals `SettingsTab.test.tsx` (413 on a 133-line component) mounts the whole tab to test things owned by children: "renders all sections and their controls" (:215-237) duplicates `SettingsContent.test.tsx:114-136`; "highlights the active section with aria-current after scroll-spy" (:197-214) duplicates `SettingsContent.test.tsx:189-196` plus nav rendering; "calls stageChange when a control is interacted with" (:249-261) is a `SettingsContent` row concern. **~150 lines** could move to the dedicated files or be cut. Medium risk — keep the genuinely tab-level tests (drawer/scrim, load orchestration, remount-preservation). diff --git a/plans/other_tasks/done-settings_source_cleanup-low-med.md b/plans/other_tasks/done-settings_source_cleanup-low-med.md new file mode 100644 index 00000000..0f22aa06 --- /dev/null +++ b/plans/other_tasks/done-settings_source_cleanup-low-med.md @@ -0,0 +1,11 @@ +# Story: Settings source cleanup (from 2026-10-10 audit) + +Scope: findings 1, 2, 3, and 5 of the settings-source audit. Other findings remain separate follow-ups. + +## Acceptance + +- [x] Duplicated precedence and document-chain tests consolidated; shared gateway setup extracted. +- [x] Pass-through module already absent; remaining export-write wrappers removed. +- [x] `settingsStore.ts` split into registry/hooks, public types, and store implementation (693 to 515 lines). + +Validation: `pnpm qa` passes; focused tests, lint, and desktop typecheck pass after test-review fixes. Save/conflict/autosave and late-schema behavior remain unchanged. diff --git a/plans/other_tasks/pending-settings_source_cleanup-low-med.md b/plans/other_tasks/pending-settings_source_cleanup-low-med.md deleted file mode 100644 index 90bdac5d..00000000 --- a/plans/other_tasks/pending-settings_source_cleanup-low-med.md +++ /dev/null @@ -1,9 +0,0 @@ -# Story: Settings source cleanup (from 2026-10-10 audit) - -`docs/reviews/2026-10-10/settings-source-audit-med-med.md`. - -## Acceptance - -- [ ] ~250 lines of duplicated test scaffolding consolidated. -- [ ] The pass-through module removed (see audit for which). -- [ ] `settingsStore.ts` (693 lines) split by responsibility.