From 88c52e9565a45492f3686630802c0b15f5f4f1c9 Mon Sep 17 00:00:00 2001 From: aamott <54421854+aamott@users.noreply.github.com> Date: Sat, 17 Oct 2026 15:37:21 -0600 Subject: [PATCH] refactor(native): centralize events and runtime probes --- apps/desktop/src/main.tsx | 4 +- apps/desktop/src/native/clipboard.ts | 4 +- apps/desktop/src/native/commands.test.ts | 3 +- apps/desktop/src/native/commands.ts | 6 +- apps/desktop/src/native/dialogs.ts | 6 +- apps/desktop/src/native/events.test.ts | 140 ++++++++++++++++++ apps/desktop/src/native/events.ts | 74 +++++++++ apps/desktop/src/native/fs.ts | 6 +- .../src/native/nativeImportBoundary.test.ts | 120 +++++++++++++++ apps/desktop/src/native/runtime.test.ts | 63 ++++++++ apps/desktop/src/native/runtime.ts | 31 ++++ apps/desktop/src/panels/Popout.inset.test.tsx | 5 +- .../desktop/src/settings/SettingsTab.test.tsx | 21 +-- apps/desktop/src/settings/SettingsTab.tsx | 4 +- .../src/settings/ThemeProvider.test.tsx | 13 +- apps/desktop/src/settings/ThemeProvider.tsx | 4 +- .../src/settings/controls/PathControl.tsx | 4 +- .../settings/desktopStatePersistence.test.ts | 9 +- .../src/settings/desktopStatePersistence.ts | 6 +- .../desktop/src/settings/themeAdapter.test.ts | 21 +-- apps/desktop/src/settings/themeAdapter.ts | 6 +- .../src/shell/DesktopShell.dirtySync.test.tsx | 13 +- .../shell/DesktopShell.onboarding.test.tsx | 5 +- .../shell/DesktopShell.rightPanel.test.tsx | 5 +- .../DesktopShell.workspaceSelector.test.tsx | 5 +- apps/desktop/src/shell/ShellRoot.test.tsx | 5 +- apps/desktop/src/shell/WorkspaceHeaderBar.tsx | 3 +- apps/desktop/src/shell/appUpdater.ts | 8 +- .../shell/phone/PhoneShell.testHarness.tsx | 7 +- apps/desktop/src/shell/useShellState.test.tsx | 5 +- apps/desktop/src/shell/useWorkspaceIndexes.ts | 4 +- .../useWorkspaceLifecycle.session.test.tsx | 7 +- .../src/shell/useWorkspaceLifecycle.test.tsx | 7 +- .../src/shell/useWorkspaceLifecycle.ts | 10 +- apps/desktop/src/sync/syncEvents.test.ts | 47 ++++++ apps/desktop/src/sync/syncEvents.ts | 6 +- apps/desktop/src/tabs/tabRestore.test.tsx | 7 +- .../workspace/GitLinkImportDialog.test.tsx | 25 ++++ .../src/workspace/gitLinkImport.test.ts | 40 +++++ apps/desktop/src/workspace/gitLinkImport.ts | 7 +- .../workspace/useWorkspaceSwitching.test.tsx | 5 +- .../src/workspace/workspaceAdapter.test.ts | 6 +- .../desktop/src/workspace/workspaceAdapter.ts | 4 +- .../desktop/src/workspace/workspaceWatcher.ts | 35 ++--- .../workspaceWatcherLifecycle.test.ts | 25 ++-- docs/reviews/2026-10-10/README.md | 9 +- ...tecture-core-extensions-editor-med-hard.md | 6 +- .../architecture-shell-state-med-hard.md | 14 +- eslint.config.js | 36 +++++ .../done-finish_native_boundary-med-med.md | 18 +++ .../pending-finish_native_boundary-med-med.md | 19 --- 51 files changed, 751 insertions(+), 192 deletions(-) create mode 100644 apps/desktop/src/native/events.test.ts create mode 100644 apps/desktop/src/native/events.ts create mode 100644 apps/desktop/src/native/nativeImportBoundary.test.ts create mode 100644 apps/desktop/src/native/runtime.test.ts create mode 100644 apps/desktop/src/native/runtime.ts create mode 100644 apps/desktop/src/sync/syncEvents.test.ts create mode 100644 apps/desktop/src/workspace/gitLinkImport.test.ts create mode 100644 plans/other_tasks/done-finish_native_boundary-med-med.md delete mode 100644 plans/other_tasks/pending-finish_native_boundary-med-med.md diff --git a/apps/desktop/src/main.tsx b/apps/desktop/src/main.tsx index b89fc7c9..4ea23600 100644 --- a/apps/desktop/src/main.tsx +++ b/apps/desktop/src/main.tsx @@ -1,6 +1,6 @@ import { StrictMode } from "react"; import { createRoot } from "react-dom/client"; -import { isTauri } from "@tauri-apps/api/core"; +import { isNativeHost } from "./native/runtime"; import "@thinkbrain/ui/styles.css"; import "./index.css"; import App from "./App"; @@ -18,7 +18,7 @@ const bootstrap = bootstrapExtensions(); const localExtensions = createLocalExtensions({ loader: createDesktopLocalDirectoryLoader(), bootstrap, - ...(isTauri() ? { directories: createDesktopExtensionDirectoryStore() } : {}) + ...(isNativeHost() ? { directories: createDesktopExtensionDirectoryStore() } : {}) }); setLocalExtensions(localExtensions); diff --git a/apps/desktop/src/native/clipboard.ts b/apps/desktop/src/native/clipboard.ts index 6eacc82b..b7002a19 100644 --- a/apps/desktop/src/native/clipboard.ts +++ b/apps/desktop/src/native/clipboard.ts @@ -14,7 +14,7 @@ * (tests, web preview). */ -import { isTauri } from "@tauri-apps/api/core"; +import { isNativeHost } from "./runtime"; import { invokeNativeCommand } from "./commands"; @@ -31,7 +31,7 @@ import { invokeNativeCommand } from "./commands"; export async function copyFilesToClipboard( paths: readonly string[] ): Promise { - if (!isTauri() || paths.length === 0) return false; + if (!isNativeHost() || paths.length === 0) return false; try { await invokeNativeCommand("copy_files_to_clipboard", { paths }); return true; diff --git a/apps/desktop/src/native/commands.test.ts b/apps/desktop/src/native/commands.test.ts index 58d94712..ab8b14d7 100644 --- a/apps/desktop/src/native/commands.test.ts +++ b/apps/desktop/src/native/commands.test.ts @@ -1,7 +1,8 @@ import { afterEach, describe, expect, it, vi } from "vitest"; const { invoke } = vi.hoisted(() => ({ invoke: vi.fn() })); -vi.mock("@tauri-apps/api/core", () => ({ invoke })); +// `isTauri` rides along because commands.ts probes it through native/runtime. +vi.mock("@tauri-apps/api/core", () => ({ invoke, isTauri: () => true })); import { invokeNativeCommand, diff --git a/apps/desktop/src/native/commands.ts b/apps/desktop/src/native/commands.ts index d5d57577..02f8fa50 100644 --- a/apps/desktop/src/native/commands.ts +++ b/apps/desktop/src/native/commands.ts @@ -1,4 +1,6 @@ -import { invoke, isTauri } from "@tauri-apps/api/core"; +import { invoke } from "@tauri-apps/api/core"; + +import { isNativeHost } from "./runtime"; import type { DesktopStateUpdate } from "../settings/desktopState"; import type { @@ -743,7 +745,7 @@ interface NativeAppUpdate { * a build where the plugin is not wired in. */ export async function checkForAppUpdate(): Promise { - if (!isTauri()) return null; + if (!isNativeHost()) return null; const { check } = await import("@tauri-apps/plugin-updater"); return await check(); } diff --git a/apps/desktop/src/native/dialogs.ts b/apps/desktop/src/native/dialogs.ts index 883021d7..9ac98b2a 100644 --- a/apps/desktop/src/native/dialogs.ts +++ b/apps/desktop/src/native/dialogs.ts @@ -8,7 +8,7 @@ * are guarded so the helpers resolve to `null` instead of crashing. */ -import { isTauri } from "@tauri-apps/api/core"; +import { isNativeHost } from "./runtime"; import { open } from "@tauri-apps/plugin-dialog"; /** @@ -20,7 +20,7 @@ import { open } from "@tauri-apps/plugin-dialog"; */ export async function pickFilePath(): Promise { // Guard non-Tauri contexts (tests, web-only dev) so callers don't crash. - if (!isTauri()) return null; + if (!isNativeHost()) return null; const selection = await open({ title: "Select file", @@ -44,7 +44,7 @@ export async function pickFilePath(): Promise { */ export async function pickDirectoryPath(title: string): Promise { // Guard non-Tauri contexts (tests, web-only dev) so callers don't crash. - if (!isTauri()) return null; + if (!isNativeHost()) return null; const selection = await open({ title, directory: true, multiple: false }); return typeof selection === "string" ? selection : null; diff --git a/apps/desktop/src/native/events.test.ts b/apps/desktop/src/native/events.test.ts new file mode 100644 index 00000000..e1ebf140 --- /dev/null +++ b/apps/desktop/src/native/events.test.ts @@ -0,0 +1,140 @@ +import { beforeEach, describe, expect, expectTypeOf, it, vi } from "vitest"; + +import { listen } from "@tauri-apps/api/event"; + +import { + subscribeToNativeEvent, + type NativeEventMap, + type NativeWorkspaceChangedPayload +} from "./events"; +import type { NativeImportProgress } from "./commands"; + +vi.mock("@tauri-apps/api/event", () => ({ + listen: vi.fn<(event: string, handler: (envelope: { payload: unknown }) => void) => Promise<() => void>>() +})); + +const listenMock = vi.mocked(listen); +const unlisten = vi.fn(); + +/** The handler `subscribeToNativeEvent` wrapped around `listen`. */ +function registeredHandler(): (envelope: { payload: unknown }) => void { + return listenMock.mock.calls[0]![1] as unknown as (envelope: { payload: unknown }) => void; +} + +beforeEach(() => { + listenMock.mockReset(); + unlisten.mockReset(); + listenMock.mockResolvedValue(unlisten); +}); + +describe("subscribeToNativeEvent", () => { + it("subscribes to workspace://changed and forwards the payload, renames included", async () => { + const onEvent = vi.fn(); + const stop = await subscribeToNativeEvent("workspace://changed", onEvent); + const payload: NativeWorkspaceChangedPayload = { + rootPath: "/vault", + changes: [ + { kind: "renamed", path: "b.md", oldPath: "a.md" }, + { kind: "deleted", path: "c.md" } + ] + }; + + registeredHandler()({ payload }); + + expect(listenMock).toHaveBeenCalledWith("workspace://changed", expect.any(Function)); + expect(onEvent).toHaveBeenCalledWith(payload); + expect(stop).toBe(unlisten); + }); + + it("subscribes to sync://import and forwards the NativeImportProgress payload", async () => { + const onEvent = vi.fn(); + await subscribeToNativeEvent("sync://import", onEvent); + const payload: NativeImportProgress = { + requestId: "imp-1", + state: "ok", + phase: "sending", + targetPath: "/vault", + notSent: "no credentials" + }; + + registeredHandler()({ payload }); + + expect(listenMock).toHaveBeenCalledWith("sync://import", expect.any(Function)); + expect(onEvent).toHaveBeenCalledWith(payload); + }); + + it.each(["sync://status", "sync://setup", "sync://conflicts"] as const)( + "subscribes to %s and forwards the named-workspace payload", + async (event) => { + const onEvent = vi.fn(); + await subscribeToNativeEvent(event, onEvent); + const payload = { rootPath: "/vault" }; + + registeredHandler()({ payload }); + + expect(listenMock).toHaveBeenCalledWith(event, expect.any(Function)); + expect(onEvent).toHaveBeenCalledWith(payload); + } + ); + + it("returns the unlisten function listen resolves to", async () => { + const stop = await subscribeToNativeEvent("sync://status", vi.fn()); + + stop(); + expect(unlisten).toHaveBeenCalledTimes(1); + }); + + it("stays pending until listen resolves the registration", async () => { + let resolveListen!: (unlisten: () => void) => void; + listenMock.mockReturnValue( + new Promise<() => void>((resolve) => { + resolveListen = resolve; + }) + ); + + let settled = false; + const pending = subscribeToNativeEvent("sync://status", vi.fn()).then((stop) => { + settled = true; + return stop; + }); + + await Promise.resolve(); + expect(settled).toBe(false); + + resolveListen(unlisten); + expect(await pending).toBe(unlisten); + expect(settled).toBe(true); + }); + + it("propagates a rejected registration unchanged", async () => { + const failure = new Error("event registration refused"); + listenMock.mockRejectedValue(failure); + + await expect(subscribeToNativeEvent("sync://status", vi.fn())).rejects.toBe(failure); + }); + + it("maps each event name to its payload type and no other", () => { + // Never invoked: these assertions exist for `tsc`, which fails the build + // if the map stops pairing names and payloads correctly. + const neverInvoked = () => { + subscribeToNativeEvent("workspace://changed", (payload) => { + expectTypeOf(payload).toEqualTypeOf(); + }); + subscribeToNativeEvent("sync://import", (payload) => { + expectTypeOf(payload).toEqualTypeOf(); + expectTypeOf().toEqualTypeOf(); + }); + subscribeToNativeEvent("sync://conflicts", (payload) => { + expectTypeOf(payload).toEqualTypeOf<{ readonly rootPath: string }>(); + }); + // @ts-expect-error — not a native event name. + subscribeToNativeEvent("sync://nope", () => undefined); + subscribeToNativeEvent("workspace://changed", (payload) => { + // @ts-expect-error — the changed payload carries changes, not a requestId. + void payload.requestId; + }); + void (0 as unknown as NativeEventMap); + }; + void neverInvoked; + }); +}); diff --git a/apps/desktop/src/native/events.ts b/apps/desktop/src/native/events.ts new file mode 100644 index 00000000..455fd47d --- /dev/null +++ b/apps/desktop/src/native/events.ts @@ -0,0 +1,74 @@ +/** + * Typed seam over the Tauri event channel. + * + * Feature code subscribes through `subscribeToNativeEvent` and never touches + * `@tauri-apps/api/event` or the envelope shape; the name→payload mapping is + * declared once in `NativeEventMap` so an event name cannot be paired with the + * wrong payload type. Registration keeps Tauri's contract: the returned + * promise resolves to the unlisten function and rejects when the native side + * refuses the subscription — no guard, no swallow. + */ + +import { listen } from "@tauri-apps/api/event"; + +import type { NativeImportProgress } from "./commands"; + +/** + * One reportable change, mirroring the native `WorkspaceChange`. The native + * classifier always pairs a rename with its origin — an unresolvable end + * becomes a rescan instead — so `oldPath` is a required field here. + */ +export type NativeWorkspaceChange = + | { + readonly kind: "created" | "modified" | "deleted" | "rescan"; + /** Workspace-relative, forward slashes. Empty for a rescan. */ + readonly path: string; + } + | { + readonly kind: "renamed"; + readonly path: string; + /** Where a renamed note came from. */ + readonly oldPath: string; + }; + +/** Payload of `workspace://changed`: a settled batch tagged with its root. */ +export interface NativeWorkspaceChangedPayload { + readonly rootPath: string; + readonly changes: readonly NativeWorkspaceChange[]; +} + +/** Payload of the sync events that only name their workspace. */ +interface NativeWorkspaceNamedPayload { + readonly rootPath: string; +} + +/** + * Every native event this app subscribes to, mapped to its payload. + * + * Keys are the exact channel names the Rust side emits on; field names are + * camelCase because serde serializes them that way. + */ +export interface NativeEventMap { + "workspace://changed": NativeWorkspaceChangedPayload; + "sync://import": NativeImportProgress; + "sync://status": NativeWorkspaceNamedPayload; + "sync://setup": NativeWorkspaceNamedPayload; + "sync://conflicts": NativeWorkspaceNamedPayload; +} + +/** The sync events whose payload is only a workspace name. */ +export type NativeSyncEventName = "sync://status" | "sync://setup" | "sync://conflicts"; + +/** + * Subscribes `onEvent` to a native event, unwrapping the Tauri envelope. + * + * Returns the promise Tauri's `listen` returns: it resolves once the native + * side has registered the listener — yielding the unlisten function — and + * rejects when registration fails. + */ +export function subscribeToNativeEvent( + event: K, + onEvent: (payload: NativeEventMap[K]) => void +): Promise<() => void> { + return listen(event, (envelope) => onEvent(envelope.payload)); +} diff --git a/apps/desktop/src/native/fs.ts b/apps/desktop/src/native/fs.ts index b494717e..b93e8036 100644 --- a/apps/desktop/src/native/fs.ts +++ b/apps/desktop/src/native/fs.ts @@ -15,7 +15,7 @@ * real failures arrive as `NativeCommandError` rejections. */ -import { isTauri } from "@tauri-apps/api/core"; +import { isNativeHost } from "./runtime"; import { invokeNativeCommand, type NativePickedTextFile } from "./commands"; /** @@ -37,7 +37,7 @@ export async function saveAndWriteTextFile( contents: string ): Promise { // Guard non-Tauri contexts (tests, web-only dev) so callers don't crash. - if (!isTauri()) return false; + if (!isNativeHost()) return false; return await invokeNativeCommand("save_and_write_text_file", { title, @@ -63,7 +63,7 @@ export async function pickAndReadTextFile( extensions?: readonly string[] ): Promise { // Guard non-Tauri contexts (tests, web-only dev) so callers don't crash. - if (!isTauri()) return null; + if (!isNativeHost()) return null; return await invokeNativeCommand("pick_and_read_text_file", { title, diff --git a/apps/desktop/src/native/nativeImportBoundary.test.ts b/apps/desktop/src/native/nativeImportBoundary.test.ts new file mode 100644 index 00000000..2d41ea66 --- /dev/null +++ b/apps/desktop/src/native/nativeImportBoundary.test.ts @@ -0,0 +1,120 @@ +import { fileURLToPath } from "node:url"; + +import { describe, expect, it } from "vitest"; +import { ESLint, type Linter } from "eslint"; + +/** + * Guards the renderer's Tauri boundary with the real ESLint config rather + * than a regex the config could drift away from: these fixtures run through + * `eslint.config.js` exactly as `pnpm lint` runs them. + */ + +const repoRoot = fileURLToPath(new URL("../../../../", import.meta.url)); +const eslint = new ESLint({ cwd: repoRoot }); + +const BOUNDARY_RULES = new Set(["no-restricted-imports", "no-restricted-syntax"]); + +async function boundaryMessages( + filePath: string, + code: string +): Promise { + expect(await eslint.isPathIgnored(filePath)).toBe(false); + const [result] = await eslint.lintText(code, { filePath }); + return result!.messages.filter( + (message) => message.ruleId !== null && BOUNDARY_RULES.has(message.ruleId) + ); +} + +const featureTs = `${repoRoot}apps/desktop/src/feature/fixture.ts`; +const featureTsx = `${repoRoot}apps/desktop/src/feature/fixture.tsx`; +const nativeTs = `${repoRoot}apps/desktop/src/native/fixture.ts`; + +describe("the native import boundary", () => { + it("denies a static scoped-package import in feature code", async () => { + const messages = await boundaryMessages( + featureTs, + 'import { invoke } from "@tauri-apps/api/core";\nvoid invoke;\n' + ); + expect(messages.map((m) => m.ruleId)).toEqual(["no-restricted-imports"]); + }); + + it("denies a scoped subpath import in .tsx feature code", async () => { + const messages = await boundaryMessages( + featureTsx, + 'import { listen } from "@tauri-apps/api/event";\nvoid listen;\nexport {};\n' + ); + expect(messages).toHaveLength(1); + }); + + it("denies a Tauri plugin import", async () => { + const messages = await boundaryMessages( + featureTs, + 'import { open } from "@tauri-apps/plugin-dialog";\nvoid open;\n' + ); + expect(messages).toHaveLength(1); + }); + + it("denies a type-only import", async () => { + const messages = await boundaryMessages( + featureTs, + 'import type { UnlistenFn } from "@tauri-apps/api/event";\nconst f: UnlistenFn | null = null;\nvoid f;\n' + ); + expect(messages).toHaveLength(1); + }); + + it("denies a re-export", async () => { + const messages = await boundaryMessages( + featureTs, + 'export { invoke } from "@tauri-apps/api/core";\n' + ); + expect(messages).toHaveLength(1); + }); + + it("denies a dynamic import", async () => { + const messages = await boundaryMessages( + featureTs, + 'export const load = () => import("@tauri-apps/api/core");\n' + ); + expect(messages.map((m) => m.ruleId)).toEqual(["no-restricted-syntax"]); + }); + + it("denies require()", async () => { + const messages = await boundaryMessages( + featureTs, + 'const api = require("@tauri-apps/api/core");\nvoid api;\nexport {};\n' + ); + expect(messages.map((m) => m.ruleId)).toEqual(["no-restricted-syntax"]); + }); + + it("denies Tauri in main.tsx — the composition root is not exempt", async () => { + const messages = await boundaryMessages( + `${repoRoot}apps/desktop/src/main.tsx`, + 'import { isTauri } from "@tauri-apps/api/core";\nvoid isTauri;\n' + ); + expect(messages).toHaveLength(1); + }); + + it("allows the same import inside native/", async () => { + const messages = await boundaryMessages( + nativeTs, + 'import { invoke } from "@tauri-apps/api/core";\nvoid invoke;\n' + ); + expect(messages).toEqual([]); + }); + + it("allows a dynamic Tauri import inside native/", async () => { + const messages = await boundaryMessages( + nativeTs, + 'export const load = () => import("@tauri-apps/plugin-updater");\n' + ); + expect(messages).toEqual([]); + }); + + it("allows feature code to reach the native adapter", async () => { + const messages = await boundaryMessages( + featureTs, + 'import { invokeNativeCommand } from "../native/commands";\nvoid invokeNativeCommand;\n' + ); + expect(messages).toEqual([]); + }); +}); diff --git a/apps/desktop/src/native/runtime.test.ts b/apps/desktop/src/native/runtime.test.ts new file mode 100644 index 00000000..b10566d4 --- /dev/null +++ b/apps/desktop/src/native/runtime.test.ts @@ -0,0 +1,63 @@ +import { afterEach, describe, expect, it, vi } from "vitest"; + +import { isTauri } from "@tauri-apps/api/core"; + +import { isApplePlatform, isNativeHost } from "./runtime"; + +vi.mock("@tauri-apps/api/core", () => ({ + isTauri: vi.fn<() => boolean>() +})); + +/** Stubs `navigator` for one call, restoring whatever was there before. */ +const realNavigator = globalThis.navigator; + +function stubNavigator(ua?: string, platform?: string): void { + vi.stubGlobal( + "navigator", + ua === undefined + ? undefined + : { userAgent: ua, platform: platform ?? ua } + ); +} + +afterEach(() => { + vi.unstubAllGlobals(); + vi.stubGlobal("navigator", realNavigator); +}); + +describe("isNativeHost", () => { + it("delegates to Tauri's probe on every call", () => { + vi.mocked(isTauri).mockReturnValueOnce(false).mockReturnValueOnce(true); + + expect(isNativeHost()).toBe(false); + expect(isNativeHost()).toBe(true); + expect(vi.mocked(isTauri)).toHaveBeenCalledTimes(2); + }); +}); + +describe("isApplePlatform", () => { + it.each(["Mac", "iPhone", "iPad", "iPod"])("is true on %s user agents", (token) => { + stubNavigator(`Mozilla/5.0 (${token}; CPU OS 17_0 like Mac OS X)`); + expect(isApplePlatform()).toBe(true); + }); + + it.each(["Windows NT 10.0", "X11; Linux x86_64", "Linux; Android 14"])( + "is false on %s user agents", + (ua) => { + stubNavigator(`Mozilla/5.0 (${ua})`); + expect(isApplePlatform()).toBe(false); + } + ); + + it("is false when navigator does not exist", () => { + stubNavigator(undefined); + expect(isApplePlatform()).toBe(false); + }); + + it("falls back to navigator.platform when the user agent is empty", () => { + stubNavigator("", "MacIntel"); + expect(isApplePlatform()).toBe(true); + stubNavigator("", "Win32"); + expect(isApplePlatform()).toBe(false); + }); +}); diff --git a/apps/desktop/src/native/runtime.ts b/apps/desktop/src/native/runtime.ts new file mode 100644 index 00000000..1638a475 --- /dev/null +++ b/apps/desktop/src/native/runtime.ts @@ -0,0 +1,31 @@ +/** + * Runtime environment probes for the native host. + * + * Every "are we inside Tauri" question answers through `isNativeHost`, so + * feature code never imports `@tauri-apps/api` just to detect its own + * environment. The check delegates to Tauri's `isTauri` on each call rather + * than caching: tests stub the global and expect later calls to see the new + * answer, and there is no startup ordering worth protecting. + */ + +import { isTauri } from "@tauri-apps/api/core"; + +/** True when running inside the Tauri native host (not a plain browser). */ +export function isNativeHost(): boolean { + return isTauri(); +} + +/** + * True on Apple platforms (macOS, iOS), where the shortcut modifier reads ⌘. + * + * Matches the historical `navigator.userAgent`/`navigator.platform` check — + * it predates `userAgentData` support and still has to work in WebKitGTK, so + * it stays a string sniff rather than an API capability check. Evaluated per + * call so tests can restub `navigator`. + */ +export function isApplePlatform(): boolean { + return ( + typeof navigator !== "undefined" && + /Mac|iPhone|iPad|iPod/i.test(navigator.userAgent || navigator.platform || "") + ); +} diff --git a/apps/desktop/src/panels/Popout.inset.test.tsx b/apps/desktop/src/panels/Popout.inset.test.tsx index cc071721..df2ccb19 100644 --- a/apps/desktop/src/panels/Popout.inset.test.tsx +++ b/apps/desktop/src/panels/Popout.inset.test.tsx @@ -13,7 +13,10 @@ import { DesktopShell } from "../shell/DesktopShell"; import { PhoneShell } from "../shell/phone/PhoneShell"; import { useShellState, type ShellState } from "../shell/useShellState"; -vi.mock("@tauri-apps/api/core", () => ({ isTauri: vi.fn(() => false) })); +vi.mock("../native/runtime", async (importOriginal) => ({ + ...(await importOriginal()), + isNativeHost: vi.fn(() => false) +})); vi.mock("../native/commands", () => ({ invokeNativeCommand: vi.fn(() => Promise.resolve(null)) })); diff --git a/apps/desktop/src/settings/SettingsTab.test.tsx b/apps/desktop/src/settings/SettingsTab.test.tsx index ab889328..e2ab7b28 100644 --- a/apps/desktop/src/settings/SettingsTab.test.tsx +++ b/apps/desktop/src/settings/SettingsTab.test.tsx @@ -3,9 +3,10 @@ import { act, useState } from "react"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; -// Mock the Tauri core `isTauri` check so we can toggle the mount-load branch. -vi.mock("@tauri-apps/api/core", () => ({ - isTauri: vi.fn<() => boolean>() +// Mock the native runtime check so we can toggle the mount-load branch. +vi.mock("../native/runtime", async (importOriginal) => ({ + ...(await importOriginal()), + isNativeHost: vi.fn<() => boolean>() })); // Mock the workspace adapter so `windowWorkspaceRoot` is controllable. @@ -25,7 +26,7 @@ vi.mock("../native/commands", async (importOriginal) => { }; }); -import { isTauri } from "@tauri-apps/api/core"; +import { isNativeHost } from "../native/runtime"; import { workspaceDesktopApi } from "../workspace/workspaceAdapter"; import { invokeNativeCommand } from "../native/commands"; import { SettingsTab } from "./SettingsTab"; @@ -67,9 +68,9 @@ beforeEach(() => { })) ); - // `isTauri` is false by default so the mount effect is a no-op for existing + // `isNativeHost` is false by default so the mount effect is a no-op for existing // tests. The remount-persistence test overrides this to true. - vi.mocked(isTauri).mockReturnValue(false); + vi.mocked(isNativeHost).mockReturnValue(false); vi.mocked(workspaceDesktopApi.windowWorkspaceRoot).mockResolvedValue(null); vi.mocked(invokeNativeCommand).mockImplementation(async (command) => command === "list_themes" ? [] : null @@ -83,7 +84,7 @@ afterEach(async () => { await harness.unmount(); clearScrollAnchorSnapshots(); vi.unstubAllGlobals(); - vi.mocked(isTauri).mockReset(); + vi.mocked(isNativeHost).mockReset(); vi.mocked(workspaceDesktopApi.windowWorkspaceRoot).mockReset(); vi.mocked(invokeNativeCommand).mockReset(); scrollSpy.restore(); @@ -405,7 +406,7 @@ describe("SettingsTab", () => { it("preserves staged changes across unmount/remount (Tauri)", async () => { // Simulate the native mount-load path. - vi.mocked(isTauri).mockReturnValue(true); + vi.mocked(isNativeHost).mockReturnValue(true); const WORKSPACE_ROOT = "/test/workspace"; vi.mocked(workspaceDesktopApi.windowWorkspaceRoot).mockResolvedValue(WORKSPACE_ROOT); vi.mocked(invokeNativeCommand).mockImplementation(async (command) => @@ -462,7 +463,7 @@ describe("SettingsTab and lazy extensions", () => { describe("finding the workspace a setting belongs to", () => { /** The main window falls back to the shell bridge when no native root exists. */ it("falls back to the shell's open workspace", async () => { - vi.mocked(isTauri).mockReturnValue(true); + vi.mocked(isNativeHost).mockReturnValue(true); vi.mocked(workspaceDesktopApi.windowWorkspaceRoot).mockResolvedValue(null); useSettingsStore.setState({ loaded: false, workspaceRootPath: null }); setWorkspaceBridge({ @@ -479,7 +480,7 @@ describe("finding the workspace a setting belongs to", () => { }); it("prefers the window's own root when it has one", async () => { - vi.mocked(isTauri).mockReturnValue(true); + vi.mocked(isNativeHost).mockReturnValue(true); vi.mocked(workspaceDesktopApi.windowWorkspaceRoot).mockResolvedValue("/window-vault"); useSettingsStore.setState({ loaded: false, workspaceRootPath: null }); setWorkspaceBridge({ diff --git a/apps/desktop/src/settings/SettingsTab.tsx b/apps/desktop/src/settings/SettingsTab.tsx index e12736ad..663dc9eb 100644 --- a/apps/desktop/src/settings/SettingsTab.tsx +++ b/apps/desktop/src/settings/SettingsTab.tsx @@ -11,7 +11,7 @@ import { useCallback, useEffect, useRef, useState } from "react"; import { Menu } from "lucide-react"; -import { isTauri } from "@tauri-apps/api/core"; +import { isNativeHost } from "../native/runtime"; import { workspaceDesktopApi } from "../workspace/workspaceAdapter"; import { getExtensionBootstrap } from "../extensions/bootstrapRef"; import { getWorkspaceBridge } from "../extensions/workspaceBridge"; @@ -58,7 +58,7 @@ export function SettingsTab({ active = true }: { readonly active?: boolean }) { useEffect(() => { // Non-Tauri contexts (tests, web preview) skip the native load. - if (!isTauri()) return; + if (!isNativeHost()) return; if (loadedRef.current) return; loadedRef.current = true; diff --git a/apps/desktop/src/settings/ThemeProvider.test.tsx b/apps/desktop/src/settings/ThemeProvider.test.tsx index 670d69a3..87cddb33 100644 --- a/apps/desktop/src/settings/ThemeProvider.test.tsx +++ b/apps/desktop/src/settings/ThemeProvider.test.tsx @@ -11,17 +11,18 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; * to the user's selection, and a toggle while a file is active doesn't flap. * * Uses `createRoot` + `act` (no @testing-library/react). Mocks `themeAdapter` - * for controllable file reads and `isTauri` to skip the mount-time load. + * for controllable file reads and `isNativeHost` to skip the mount-time load. */ vi.mock("./themeAdapter", () => ({ readThemeFile: vi.fn<(path: string) => Promise>() })); -vi.mock("@tauri-apps/api/core", () => ({ - isTauri: vi.fn<() => boolean>() +vi.mock("../native/runtime", async (importOriginal) => ({ + ...(await importOriginal()), + isNativeHost: vi.fn<() => boolean>() })); -import { isTauri } from "@tauri-apps/api/core"; +import { isNativeHost } from "../native/runtime"; import { readThemeFile } from "./themeAdapter"; import { ThemeProvider } from "./ThemeProvider"; import { useSettingsStore } from "./settingsStore"; @@ -40,7 +41,7 @@ let root: Root | null = null; let container: HTMLDivElement | null = null; beforeEach(() => { - vi.mocked(isTauri).mockReturnValue(false); + vi.mocked(isNativeHost).mockReturnValue(false); vi.mocked(readThemeFile).mockResolvedValue(null); // Reset to a clean, unloaded state. Tests seed fields via `setState`. @@ -70,7 +71,7 @@ afterEach(async () => { document.documentElement.removeAttribute("data-thinkbrain-theme"); vi.unstubAllGlobals(); vi.mocked(readThemeFile).mockReset(); - vi.mocked(isTauri).mockReset(); + vi.mocked(isNativeHost).mockReset(); }); /** Renders the ThemeProvider into a fresh container and flushes effects. */ diff --git a/apps/desktop/src/settings/ThemeProvider.tsx b/apps/desktop/src/settings/ThemeProvider.tsx index 457fb731..9fa1ad23 100644 --- a/apps/desktop/src/settings/ThemeProvider.tsx +++ b/apps/desktop/src/settings/ThemeProvider.tsx @@ -1,6 +1,6 @@ import { createContext, useContext, useEffect, useRef, useState } from "react"; import type { ReactNode } from "react"; -import { isTauri } from "@tauri-apps/api/core"; +import { isNativeHost } from "../native/runtime"; import { parseThemeFile, type AppThemeSetting, type ThemeBase } from "@thinkbrain/core"; import { useSettingsStore } from "./settingsStore"; import { readThemeFile } from "./themeAdapter"; @@ -142,7 +142,7 @@ export function ThemeProvider({ children }: ThemeProviderProps) { // prevents double-load in StrictMode or fast re-mounts. const loadStartedRef = useRef(false); useEffect(() => { - if (!isTauri()) return; + if (!isNativeHost()) return; if (loadStartedRef.current) return; loadStartedRef.current = true; loadSettings(null).catch((error: unknown) => { diff --git a/apps/desktop/src/settings/controls/PathControl.tsx b/apps/desktop/src/settings/controls/PathControl.tsx index 9f11bdfb..5adbc3f6 100644 --- a/apps/desktop/src/settings/controls/PathControl.tsx +++ b/apps/desktop/src/settings/controls/PathControl.tsx @@ -8,7 +8,7 @@ */ import { useState } from "react"; -import { isTauri } from "@tauri-apps/api/core"; +import { isNativeHost } from "../../native/runtime"; import { FolderOpen } from "lucide-react"; import { pickFilePath } from "../../native/dialogs"; import { inputClassName, type ControlProps } from "../controlRegistry"; @@ -23,7 +23,7 @@ import { inputClassName, type ControlProps } from "../controlRegistry"; */ export function PathControl({ definition, value, onChange }: ControlProps) { // Cache the Tauri check once; it never changes during a session. - const [nativeAvailable] = useState(() => isTauri()); + const [nativeAvailable] = useState(() => isNativeHost()); const pathValue = typeof value === "string" ? value : String(value ?? ""); async function handleBrowse() { diff --git a/apps/desktop/src/settings/desktopStatePersistence.test.ts b/apps/desktop/src/settings/desktopStatePersistence.test.ts index b6a5581f..36938168 100644 --- a/apps/desktop/src/settings/desktopStatePersistence.test.ts +++ b/apps/desktop/src/settings/desktopStatePersistence.test.ts @@ -11,11 +11,10 @@ import { DEFAULT_DESKTOP_STATE } from "./desktopState"; * underlying gateway logic `desktopState.test.ts` already covers. */ -// `isTauri` is mocked to true so the abstraction exercises its IPC path. -vi.mock("@tauri-apps/api/core", () => ({ - isTauri: () => true, - invoke: () => Promise.resolve(null), - convertFileSrc: (path: string) => path +// `isNativeHost` is mocked to true so the abstraction exercises its IPC path. +vi.mock("../native/runtime", async (importOriginal) => ({ + ...(await importOriginal()), + isNativeHost: () => true })); let saveShouldFail = false; diff --git a/apps/desktop/src/settings/desktopStatePersistence.ts b/apps/desktop/src/settings/desktopStatePersistence.ts index 42a4f947..572850c8 100644 --- a/apps/desktop/src/settings/desktopStatePersistence.ts +++ b/apps/desktop/src/settings/desktopStatePersistence.ts @@ -12,7 +12,7 @@ * read or write, so attempting the IPC would only produce noise. */ -import { isTauri } from "@tauri-apps/api/core"; +import { isNativeHost } from "../native/runtime"; import { getErrorMessage } from "@thinkbrain/core"; import { useNotificationStore } from "../notifications/notificationStore"; @@ -39,7 +39,7 @@ const LOAD_FAILURE_DEDUP_KEY = `${DESKTOP_STATE_SOURCE}:load-failed`; * Non-Tauri sessions are a no-op. */ export function persistDesktopState(update: DesktopStateUpdate): void { - if (!isTauri()) return; + if (!isNativeHost()) return; void saveDesktopState(update).catch(reportSaveFailure); } @@ -54,7 +54,7 @@ export function persistDesktopState(update: DesktopStateUpdate): void { * {@link reportDesktopStateReadFailure} in their own `.catch`. */ export function readDesktopState(): Promise { - if (!isTauri()) return Promise.resolve(DEFAULT_DESKTOP_STATE); + if (!isNativeHost()) return Promise.resolve(DEFAULT_DESKTOP_STATE); return loadDesktopState().catch((error: unknown) => { reportDesktopStateReadFailure(error); return DEFAULT_DESKTOP_STATE; diff --git a/apps/desktop/src/settings/themeAdapter.test.ts b/apps/desktop/src/settings/themeAdapter.test.ts index 3d7eaf0f..7154f96e 100644 --- a/apps/desktop/src/settings/themeAdapter.test.ts +++ b/apps/desktop/src/settings/themeAdapter.test.ts @@ -7,14 +7,15 @@ import { beforeEach, describe, expect, it, vi } from "vitest"; * * The adapter has two branches: a Tauri branch that delegates to * `invokeNativeCommand("list_themes")`, and a non-Tauri branch that returns an - * empty array. `isTauri()` from `@tauri-apps/api/core` is mocked per-test to + * empty array. `isNativeHost()` from `../native/runtime` is mocked per-test to * exercise each branch, and `invokeNativeCommand` is mocked so no real IPC * call is made. */ -// Mock the Tauri core `isTauri` check so we can toggle the branch under test. -vi.mock("@tauri-apps/api/core", () => ({ - isTauri: vi.fn<() => boolean>() +// Mock the native runtime check so we can toggle the branch under test. +vi.mock("../native/runtime", async (importOriginal) => ({ + ...(await importOriginal()), + isNativeHost: vi.fn<() => boolean>() })); // Mock the native bridge so no real IPC invocation happens. The mock @@ -23,18 +24,18 @@ vi.mock("../native/commands", () => ({ invokeNativeCommand: vi.fn() })); -import { isTauri } from "@tauri-apps/api/core"; +import { isNativeHost } from "../native/runtime"; import { invokeNativeCommand } from "../native/commands"; import { listThemes, type ThemeEntry } from "./themeAdapter"; beforeEach(() => { - vi.mocked(isTauri).mockReset(); + vi.mocked(isNativeHost).mockReset(); vi.mocked(invokeNativeCommand).mockReset(); }); describe("listThemes", () => { it("returns an empty array in non-Tauri contexts (no native bridge)", async () => { - vi.mocked(isTauri).mockReturnValue(false); + vi.mocked(isNativeHost).mockReturnValue(false); const result = await listThemes(); @@ -44,7 +45,7 @@ describe("listThemes", () => { }); it("delegates to invokeNativeCommand('list_themes') in Tauri contexts", async () => { - vi.mocked(isTauri).mockReturnValue(true); + vi.mocked(isNativeHost).mockReturnValue(true); const nativeEntries: readonly ThemeEntry[] = [ { name: "Forest Dark", path: "/app-data/themes/forest-dark.tbtheme.json" }, { name: "Solarized Light", path: "/app-data/themes/solarized-light.tbtheme.json" } @@ -59,7 +60,7 @@ describe("listThemes", () => { }); it("returns the native result unchanged (no per-entry copy)", async () => { - vi.mocked(isTauri).mockReturnValue(true); + vi.mocked(isNativeHost).mockReturnValue(true); const nativeEntries: readonly ThemeEntry[] = [ { name: "One Dark Pro", path: "/app-data/themes/one-dark-pro.tbtheme.json" } ]; @@ -74,7 +75,7 @@ describe("listThemes", () => { }); it("propagates native command errors (fail-loud)", async () => { - vi.mocked(isTauri).mockReturnValue(true); + vi.mocked(isNativeHost).mockReturnValue(true); const error = new Error("native bridge down"); vi.mocked(invokeNativeCommand).mockRejectedValue(error); diff --git a/apps/desktop/src/settings/themeAdapter.ts b/apps/desktop/src/settings/themeAdapter.ts index 1956ba99..b44005b5 100644 --- a/apps/desktop/src/settings/themeAdapter.ts +++ b/apps/desktop/src/settings/themeAdapter.ts @@ -8,7 +8,7 @@ * theme picker renders without errors outside the desktop shell. */ -import { isTauri } from "@tauri-apps/api/core"; +import { isNativeHost } from "../native/runtime"; import { invokeNativeCommand } from "../native/commands"; /** @@ -41,7 +41,7 @@ export async function listThemes(): Promise { // Non-Tauri contexts (vitest, web preview) have no native bridge. Return an // empty list so the picker renders with just the "None" option rather than // throwing an unhandled rejection. - if (!isTauri()) { + if (!isNativeHost()) { return []; } @@ -71,6 +71,6 @@ export async function listThemes(): Promise { * handler can surface "broken" distinctly from "missing" or "non-Tauri". */ export async function readThemeFile(path: string): Promise { - if (!isTauri()) return null; + if (!isNativeHost()) return null; return invokeNativeCommand("read_theme_file", { path }); } diff --git a/apps/desktop/src/shell/DesktopShell.dirtySync.test.tsx b/apps/desktop/src/shell/DesktopShell.dirtySync.test.tsx index 6a2d8f7f..a8a207fa 100644 --- a/apps/desktop/src/shell/DesktopShell.dirtySync.test.tsx +++ b/apps/desktop/src/shell/DesktopShell.dirtySync.test.tsx @@ -15,11 +15,12 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; * tabs produces a new array reference but should not re-trigger the sync). */ -// Mock Tauri's isTauri so the shell's restore/persistence effects are no-ops -// under the test environment. This keeps the render focused on the dirty-sync +// Mock the native runtime so restore/persistence effects are no-ops under +// the test environment. This keeps the render focused on the dirty-sync // effect without booting the native workspace-restore lifecycle. -vi.mock("@tauri-apps/api/core", () => ({ - isTauri: vi.fn(() => false) +vi.mock("../native/runtime", async (importOriginal) => ({ + ...(await importOriginal()), + isNativeHost: vi.fn(() => false) })); // Mock native commands so any transitive gateway call returns null instead of @@ -73,7 +74,7 @@ vi.mock("../tabs/tabModel", async () => { }; }); -import { isTauri } from "@tauri-apps/api/core"; +import { isNativeHost } from "../native/runtime"; import { desktopTabReducer } from "../tabs/tabModel"; import { getWorkspaceBridge } from "../extensions/workspaceBridge"; import { selectIsDirty, useSettingsStore } from "../settings/settingsStore"; @@ -85,7 +86,7 @@ let root: Root | null = null; let container: HTMLDivElement | null = null; beforeEach(() => { - vi.mocked(isTauri).mockReturnValue(false); + vi.mocked(isNativeHost).mockReturnValue(false); // Reset the singleton settings store to a clean, non-dirty state so tests // start from a known baseline (other describe blocks in the same file run // would otherwise leak stagedChanges). diff --git a/apps/desktop/src/shell/DesktopShell.onboarding.test.tsx b/apps/desktop/src/shell/DesktopShell.onboarding.test.tsx index f5e71a22..05966c57 100644 --- a/apps/desktop/src/shell/DesktopShell.onboarding.test.tsx +++ b/apps/desktop/src/shell/DesktopShell.onboarding.test.tsx @@ -7,7 +7,10 @@ import { ThemeProvider } from "../settings/ThemeProvider"; import { DesktopShell } from "./DesktopShell"; import { useShellState, type ShellState } from "./useShellState"; -vi.mock("@tauri-apps/api/core", () => ({ isTauri: vi.fn(() => false) })); +vi.mock("../native/runtime", async (importOriginal) => ({ + ...(await importOriginal()), + isNativeHost: vi.fn(() => false) +})); vi.mock("../native/commands", () => ({ // Desktop-shaped capabilities so the keepMounted explorer publishes its // onboarding actions; every other command keeps the null default. diff --git a/apps/desktop/src/shell/DesktopShell.rightPanel.test.tsx b/apps/desktop/src/shell/DesktopShell.rightPanel.test.tsx index 381ca367..06320530 100644 --- a/apps/desktop/src/shell/DesktopShell.rightPanel.test.tsx +++ b/apps/desktop/src/shell/DesktopShell.rightPanel.test.tsx @@ -8,7 +8,10 @@ import { createVersionDiffTab } from "../tabs/tabModel"; import { DesktopShell } from "./DesktopShell"; import { useShellState, type ShellState } from "./useShellState"; -vi.mock("@tauri-apps/api/core", () => ({ isTauri: vi.fn(() => false) })); +vi.mock("../native/runtime", async (importOriginal) => ({ + ...(await importOriginal()), + isNativeHost: vi.fn(() => false) +})); vi.mock("../native/commands", () => ({ // Commands a mounted tab actually issues need real-shaped answers: a null // document crashes the view-state reader, and a null version diff crashes diff --git a/apps/desktop/src/shell/DesktopShell.workspaceSelector.test.tsx b/apps/desktop/src/shell/DesktopShell.workspaceSelector.test.tsx index 9ff9f7a1..bce07092 100644 --- a/apps/desktop/src/shell/DesktopShell.workspaceSelector.test.tsx +++ b/apps/desktop/src/shell/DesktopShell.workspaceSelector.test.tsx @@ -4,8 +4,9 @@ import { act } from "react"; import { createRoot, type Root } from "react-dom/client"; import { afterEach, describe, expect, it, vi } from "vitest"; -vi.mock("@tauri-apps/api/core", () => ({ - isTauri: vi.fn(() => false) +vi.mock("../native/runtime", async (importOriginal) => ({ + ...(await importOriginal()), + isNativeHost: vi.fn(() => false) })); vi.mock("../native/commands", () => ({ diff --git a/apps/desktop/src/shell/ShellRoot.test.tsx b/apps/desktop/src/shell/ShellRoot.test.tsx index e11d8016..14c4ad9f 100644 --- a/apps/desktop/src/shell/ShellRoot.test.tsx +++ b/apps/desktop/src/shell/ShellRoot.test.tsx @@ -28,8 +28,9 @@ vi.mock("../lib/useMediaQuery", async (importOriginal) => { // `ShellRoot` mounts the real shell state, which boots the workspace lifecycle // and reaches for Tauri IPC when it believes it is running under Tauri. Mock // both so the restore path is a no-op, matching `useShellState.test.tsx`. -vi.mock("@tauri-apps/api/core", () => ({ - isTauri: vi.fn(() => false) +vi.mock("../native/runtime", async (importOriginal) => ({ + ...(await importOriginal()), + isNativeHost: vi.fn(() => false) })); vi.mock("../native/commands", () => ({ diff --git a/apps/desktop/src/shell/WorkspaceHeaderBar.tsx b/apps/desktop/src/shell/WorkspaceHeaderBar.tsx index ff4c5d5d..ddb6bec3 100644 --- a/apps/desktop/src/shell/WorkspaceHeaderBar.tsx +++ b/apps/desktop/src/shell/WorkspaceHeaderBar.tsx @@ -5,6 +5,7 @@ import { useEditorCommands } from "../tabs/editorCommands"; import { desktopTabRegistry } from "../tabs/tabRegistry"; import { isWorkspaceGitLinked } from "../workspace/workspaceSettings"; import { cn } from "../lib/utils"; +import { isApplePlatform } from "../native/runtime"; export interface WorkspaceHeaderBarProps { /** Display name of the active workspace, or null if none. */ @@ -21,7 +22,7 @@ export interface WorkspaceHeaderBarProps { readonly onSave?: () => void; } -const IS_APPLE = typeof navigator !== "undefined" && /Mac|iPhone|iPad|iPod/i.test(navigator.userAgent || navigator.platform || ""); +const IS_APPLE = isApplePlatform(); const SAVE_SHORTCUT = IS_APPLE ? "⌘S" : "Ctrl+S"; const UNDO_SHORTCUT = IS_APPLE ? "⌘Z" : "Ctrl+Z"; const REDO_SHORTCUT = IS_APPLE ? "⇧⌘Z" : "Ctrl+Y"; diff --git a/apps/desktop/src/shell/appUpdater.ts b/apps/desktop/src/shell/appUpdater.ts index 3e11b05a..bab477ea 100644 --- a/apps/desktop/src/shell/appUpdater.ts +++ b/apps/desktop/src/shell/appUpdater.ts @@ -1,6 +1,5 @@ -import { isTauri } from "@tauri-apps/api/core"; - import { checkForAppUpdate } from "../native/commands"; +import { isNativeHost } from "../native/runtime"; import type { AvailableUpdate } from "./useAppUpdate"; /** @@ -8,13 +7,12 @@ import type { AvailableUpdate } from "./useAppUpdate"; * the hook and its tests never import a plugin that only exists inside the * app. The Tauri IPC itself lives in `native/commands.ts` (`checkForAppUpdate`, * `relaunchApp`) — all plugin calls route through `native/` per the app - * boundary rule; the `isTauri` probe here is the documented environment-check - * exception, kept so the hook can cheaply tell "no updater" from "no update". + * boundary rule. * * `null` where there is no updater to talk to — a browser dev run, or a mobile * build, which is gated out natively as well. */ -export const checkForUpdate: (() => Promise) | null = isTauri() +export const checkForUpdate: (() => Promise) | null = isNativeHost() ? checkForAppUpdate : null; diff --git a/apps/desktop/src/shell/phone/PhoneShell.testHarness.tsx b/apps/desktop/src/shell/phone/PhoneShell.testHarness.tsx index ff74cf26..3515ab92 100644 --- a/apps/desktop/src/shell/phone/PhoneShell.testHarness.tsx +++ b/apps/desktop/src/shell/phone/PhoneShell.testHarness.tsx @@ -13,8 +13,9 @@ import { PhoneShell } from "./PhoneShell"; // `useShellState` boots the workspace lifecycle and reaches for Tauri IPC when // it believes it is running under Tauri. Mock both so the restore path is a // no-op, matching `ShellRoot.test.tsx` and `useShellState.test.tsx`. -vi.mock("@tauri-apps/api/core", () => ({ - isTauri: vi.fn(() => false) +vi.mock("../../native/runtime", async (importOriginal) => ({ + ...(await importOriginal()), + isNativeHost: vi.fn(() => false) })); // The load path dereferences what the adapter returns, and the native-command @@ -61,7 +62,7 @@ const nativeCommands = () => /** * Answers `workspace_access_capabilities` the way a managed-vault-only host * (Android) does. The workspace list needs no answer: `listKnownWorkspaces` - * short-circuits to `[]` when `isTauri()` is false, which this harness + * short-circuits to `[]` when `isNativeHost()` is false, which this harness * already fakes. Call before `render`/`renderWithShell`. */ export const mockManagedWorkspaceAccess = (): void => { diff --git a/apps/desktop/src/shell/useShellState.test.tsx b/apps/desktop/src/shell/useShellState.test.tsx index 065e0d7d..dd3e7981 100644 --- a/apps/desktop/src/shell/useShellState.test.tsx +++ b/apps/desktop/src/shell/useShellState.test.tsx @@ -13,8 +13,9 @@ import { useShellState, type ShellState } from "./useShellState"; // The shell state boots the workspace lifecycle, which reaches for Tauri IPC // when it believes it is running under Tauri. Under happy-dom it is not, but // mock it explicitly so the restore path is a no-op regardless of environment. -vi.mock("@tauri-apps/api/core", () => ({ - isTauri: vi.fn(() => false) +vi.mock("../native/runtime", async (importOriginal) => ({ + ...(await importOriginal()), + isNativeHost: vi.fn(() => false) })); vi.mock("../native/commands", async (importOriginal) => { diff --git a/apps/desktop/src/shell/useWorkspaceIndexes.ts b/apps/desktop/src/shell/useWorkspaceIndexes.ts index 1b40835f..016ae90a 100644 --- a/apps/desktop/src/shell/useWorkspaceIndexes.ts +++ b/apps/desktop/src/shell/useWorkspaceIndexes.ts @@ -7,7 +7,7 @@ * they did before the split. */ -import { isTauri } from "@tauri-apps/api/core"; +import { isNativeHost } from "../native/runtime"; import { useEffect, type Dispatch, type SetStateAction } from "react"; import { subscribeToNoteChanges } from "../events/noteChangeSubscription"; import type { NativeMarkdownFileEntry } from "../native/commands"; @@ -38,7 +38,7 @@ export function useWorkspaceIndexes({ // outside changes as the same `note.*` events an in-app edit produces, so // every consumer stays as it was. useEffect(() => { - if (!isTauri() || !restoredWorkspacePath) return; + if (!isNativeHost() || !restoredWorkspacePath) return; const rootPath = restoredWorkspacePath; let cancelled = false; let stop: (() => void) | null = null; diff --git a/apps/desktop/src/shell/useWorkspaceLifecycle.session.test.tsx b/apps/desktop/src/shell/useWorkspaceLifecycle.session.test.tsx index 288a3e00..2c41edc1 100644 --- a/apps/desktop/src/shell/useWorkspaceLifecycle.session.test.tsx +++ b/apps/desktop/src/shell/useWorkspaceLifecycle.session.test.tsx @@ -22,10 +22,9 @@ let savedUpdates: Record[] = []; let snapshots: Record> = {}; const indexed: string[] = []; -vi.mock("@tauri-apps/api/core", () => ({ - isTauri: () => true, - invoke: () => Promise.resolve(null), - convertFileSrc: (path: string) => path +vi.mock("../native/runtime", async (importOriginal) => ({ + ...(await importOriginal()), + isNativeHost: () => true })); vi.mock("../settings/desktopState", async (importOriginal) => ({ ...(await importOriginal()), diff --git a/apps/desktop/src/shell/useWorkspaceLifecycle.test.tsx b/apps/desktop/src/shell/useWorkspaceLifecycle.test.tsx index 81b593ee..bbfe8b49 100644 --- a/apps/desktop/src/shell/useWorkspaceLifecycle.test.tsx +++ b/apps/desktop/src/shell/useWorkspaceLifecycle.test.tsx @@ -34,10 +34,9 @@ let savedTabs: WorkspaceTabsUpdate[] = []; /** Every desktop-state update the hook persisted. */ let savedUpdates: Record[] = []; -vi.mock("@tauri-apps/api/core", () => ({ - isTauri: () => true, - invoke: () => Promise.resolve(null), - convertFileSrc: (path: string) => path +vi.mock("../native/runtime", async (importOriginal) => ({ + ...(await importOriginal()), + isNativeHost: () => true })); vi.mock("../settings/desktopState", async (importOriginal) => { diff --git a/apps/desktop/src/shell/useWorkspaceLifecycle.ts b/apps/desktop/src/shell/useWorkspaceLifecycle.ts index 91beb65b..b5a14462 100644 --- a/apps/desktop/src/shell/useWorkspaceLifecycle.ts +++ b/apps/desktop/src/shell/useWorkspaceLifecycle.ts @@ -1,4 +1,4 @@ -import { isTauri } from "@tauri-apps/api/core"; +import { isNativeHost } from "../native/runtime"; import { useCallback, useEffect, useMemo, useRef, useState, type Dispatch } from "react"; import { getExtensionBootstrap } from "../extensions/bootstrapRef"; import { splitContributionId } from "../extensions/desktopExtensionHost"; @@ -95,13 +95,13 @@ export function useWorkspaceLifecycle({ const workspaceName = workspaceSession.snapshot?.workspace.name ?? null; const workspaceFiles = workspaceSession.files; const [newNoteFocusRequest, setNewNoteFocusRequest] = useState(0); - const [stateRestored, setStateRestored] = useState(!isTauri()); + const [stateRestored, setStateRestored] = useState(!isNativeHost()); const tabsRestoredRef = useRef(false); // Restore the persisted desktop state (last workspace, recents, explorer // visibility) plus the workspace root the native window was launched with. useEffect(() => { - if (!isTauri()) return; + if (!isNativeHost()) return; let active = true; void Promise.allSettled([readDesktopState(), workspaceDesktopApi.windowWorkspaceRoot()]).then(([desktopResult, rootResult]) => { @@ -184,7 +184,7 @@ export function useWorkspaceLifecycle({ [] ); useEffect(() => { - if (!stateRestored || !isTauri()) return; + if (!stateRestored || !isNativeHost()) return; saveTabs({ tabs: tabState, workspacePath: restoredWorkspacePath }); }, [saveTabs, stateRestored, tabState, restoredWorkspacePath]); @@ -232,7 +232,7 @@ export function useWorkspaceLifecycle({ // workspace-scoped write in `stagedChanges` without persisting anything. // SettingsTab has its own guard that skips the reload if the root matches. useEffect(() => { - if (!isTauri()) return; + if (!isNativeHost()) return; const { loaded, workspaceRootPath } = useSettingsStore.getState(); if (loaded && workspaceRootPath === restoredWorkspacePath) return; void useSettingsStore.getState().loadSettings(restoredWorkspacePath); diff --git a/apps/desktop/src/sync/syncEvents.test.ts b/apps/desktop/src/sync/syncEvents.test.ts new file mode 100644 index 00000000..6ec873e6 --- /dev/null +++ b/apps/desktop/src/sync/syncEvents.test.ts @@ -0,0 +1,47 @@ +import { beforeEach, describe, expect, it, vi } from "vitest"; + +import { subscribeToNativeEvent } from "../native/events"; + +import { subscribeToSyncEvent } from "./syncEvents"; + +vi.mock("../native/events", () => ({ + subscribeToNativeEvent: vi.fn() +})); + +const subscribe = vi.mocked(subscribeToNativeEvent); +const unlisten = vi.fn(); + +beforeEach(() => { + subscribe.mockReset(); + unlisten.mockReset(); + subscribe.mockResolvedValue(unlisten); +}); + +describe("subscribeToSyncEvent", () => { + it.each(["sync://status", "sync://setup", "sync://conflicts"] as const)( + "forwards %s to the native event seam and calls onChange without filtering", + async (event) => { + const onChange = vi.fn(); + const stop = await subscribeToSyncEvent(event, onChange); + + expect(subscribe).toHaveBeenCalledWith(event, expect.any(Function)); + + // The seam's wrapped callback fires whatever payload arrived — the + // workspace name is deliberately never compared here (see the module + // doc): even another workspace's event prompts a cheap re-read. + const wrapped = subscribe.mock.calls[0]![1]; + wrapped({ rootPath: "/other-vault" }); + expect(onChange).toHaveBeenCalledTimes(1); + + stop(); + expect(unlisten).toHaveBeenCalledTimes(1); + } + ); + + it("does not swallow a rejected registration", async () => { + const failure = new Error("no channel"); + subscribe.mockRejectedValue(failure); + + await expect(subscribeToSyncEvent("sync://status", vi.fn())).rejects.toBe(failure); + }); +}); diff --git a/apps/desktop/src/sync/syncEvents.ts b/apps/desktop/src/sync/syncEvents.ts index f613b547..5a1c9b7e 100644 --- a/apps/desktop/src/sync/syncEvents.ts +++ b/apps/desktop/src/sync/syncEvents.ts @@ -7,7 +7,7 @@ * of the truth. The answer is always one command away. */ -import { listen } from "@tauri-apps/api/event"; +import { subscribeToNativeEvent, type NativeSyncEventName } from "../native/events"; /** * Calls `onChange` whenever the native side raises `event`. @@ -20,10 +20,10 @@ import { listen } from "@tauri-apps/api/event"; * workspace costs one call and cannot be wrong. */ export async function subscribeToSyncEvent( - event: string, + event: NativeSyncEventName, onChange: () => void ): Promise<() => void> { - return listen(event, () => { + return subscribeToNativeEvent(event, () => { onChange(); }); } diff --git a/apps/desktop/src/tabs/tabRestore.test.tsx b/apps/desktop/src/tabs/tabRestore.test.tsx index f7a16e80..ef72062b 100644 --- a/apps/desktop/src/tabs/tabRestore.test.tsx +++ b/apps/desktop/src/tabs/tabRestore.test.tsx @@ -23,10 +23,9 @@ import { documentTabId, fileTabId, initialDesktopTabState } from "./tabModel"; let storedState: DesktopState; let windowRoot: string | null = null; -vi.mock("@tauri-apps/api/core", () => ({ - isTauri: () => true, - invoke: () => Promise.resolve(null), - convertFileSrc: (path: string) => path +vi.mock("../native/runtime", async (importOriginal) => ({ + ...(await importOriginal()), + isNativeHost: () => true })); vi.mock("../settings/desktopState", async (importOriginal) => { diff --git a/apps/desktop/src/workspace/GitLinkImportDialog.test.tsx b/apps/desktop/src/workspace/GitLinkImportDialog.test.tsx index c415576c..6f2462f5 100644 --- a/apps/desktop/src/workspace/GitLinkImportDialog.test.tsx +++ b/apps/desktop/src/workspace/GitLinkImportDialog.test.tsx @@ -506,5 +506,30 @@ describe("GitLinkImportDialog", () => { await act(async () => undefined); expect(document.body.textContent).toContain("The keychain is locked."); }); + + /** + * The subscription promise is async: if the dialog is gone by the time the + * native side answers, the resolved unlisten must still run — exactly once — + * or every dismissed dialog would leak a listener. + */ + it("releases a subscription that only resolves after the dialog unmounts", async () => { + const stop = vi.fn(); + let resolveSubscribe!: (unlisten: () => void) => void; + subscribeToWorkspaceImport.mockReset().mockImplementation( + () => + new Promise<() => void>((resolve) => { + resolveSubscribe = resolve; + }) + ); + await renderDialog(); + await act(async () => root?.unmount()); + root = null; + + await act(async () => { + resolveSubscribe(stop); + }); + + expect(stop).toHaveBeenCalledTimes(1); + }); }); diff --git a/apps/desktop/src/workspace/gitLinkImport.test.ts b/apps/desktop/src/workspace/gitLinkImport.test.ts new file mode 100644 index 00000000..cb60c5c1 --- /dev/null +++ b/apps/desktop/src/workspace/gitLinkImport.test.ts @@ -0,0 +1,40 @@ +import { beforeEach, describe, expect, it, vi } from "vitest"; + +import { subscribeToNativeEvent } from "../native/events"; + +import { subscribeToWorkspaceImport } from "./gitLinkImport"; + +vi.mock("../native/events", () => ({ + subscribeToNativeEvent: vi.fn() +})); + +const subscribe = vi.mocked(subscribeToNativeEvent); +const unlisten = vi.fn(); + +beforeEach(() => { + subscribe.mockReset(); + unlisten.mockReset(); + subscribe.mockResolvedValue(unlisten); +}); + +describe("subscribeToWorkspaceImport", () => { + it("subscribes to sync://import and forwards the payload callback unchanged", async () => { + const onEvent = vi.fn(); + const stop = await subscribeToWorkspaceImport(onEvent); + + expect(subscribe).toHaveBeenCalledWith("sync://import", onEvent); + + const payload = { requestId: "imp-1", state: "ok", targetPath: "/vault" }; + subscribe.mock.calls[0]![1](payload); + expect(onEvent).toHaveBeenCalledWith(payload); + + expect(stop).toBe(unlisten); + }); + + it("propagates a rejected registration unchanged", async () => { + const failure = new Error("no channel"); + subscribe.mockRejectedValue(failure); + + await expect(subscribeToWorkspaceImport(vi.fn())).rejects.toBe(failure); + }); +}); diff --git a/apps/desktop/src/workspace/gitLinkImport.ts b/apps/desktop/src/workspace/gitLinkImport.ts index de4f9527..be383156 100644 --- a/apps/desktop/src/workspace/gitLinkImport.ts +++ b/apps/desktop/src/workspace/gitLinkImport.ts @@ -5,14 +5,13 @@ * closing this one cannot lose a finished import. */ -import { listen } from "@tauri-apps/api/event"; - import { invokeNativeCommand, type NativeGitLinkPreview, type NativeImportProgress, type NativeImportStarted } from "../native/commands"; +import { subscribeToNativeEvent } from "../native/events"; const WORKSPACE_IMPORT_EVENT = "sync://import"; @@ -58,7 +57,5 @@ export function importManagedWorkspaceFromGitLink( export async function subscribeToWorkspaceImport( onEvent: (payload: WorkspaceImportProgress) => void ): Promise<() => void> { - return listen(WORKSPACE_IMPORT_EVENT, (event) => { - onEvent(event.payload); - }); + return subscribeToNativeEvent(WORKSPACE_IMPORT_EVENT, onEvent); } diff --git a/apps/desktop/src/workspace/useWorkspaceSwitching.test.tsx b/apps/desktop/src/workspace/useWorkspaceSwitching.test.tsx index e9b34a11..7302fe56 100644 --- a/apps/desktop/src/workspace/useWorkspaceSwitching.test.tsx +++ b/apps/desktop/src/workspace/useWorkspaceSwitching.test.tsx @@ -9,8 +9,9 @@ import { forgetWorkspace, saveDesktopState } from "../settings/desktopState"; import { useWorkspaceSwitching, type WorkspaceSwitchingController } from "./useWorkspaceSwitching"; import { workspaceDesktopApi, type WorkspaceDesktopApi } from "./workspaceAdapter"; -vi.mock("@tauri-apps/api/core", () => ({ - isTauri: () => true +vi.mock("../native/runtime", async (importOriginal) => ({ + ...(await importOriginal()), + isNativeHost: () => true })); vi.mock("../settings/desktopState", () => ({ diff --git a/apps/desktop/src/workspace/workspaceAdapter.test.ts b/apps/desktop/src/workspace/workspaceAdapter.test.ts index da842f2e..0f4dcddb 100644 --- a/apps/desktop/src/workspace/workspaceAdapter.test.ts +++ b/apps/desktop/src/workspace/workspaceAdapter.test.ts @@ -10,9 +10,9 @@ vi.mock("../native/commands", async (importOriginal) => ({ vi.mock("../native/dialogs", () => ({ pickDirectoryPath: vi.fn(async () => null) })); -vi.mock("@tauri-apps/api/core", async (importOriginal) => ({ - ...(await importOriginal()), - isTauri: () => true +vi.mock("../native/runtime", async (importOriginal) => ({ + ...(await importOriginal()), + isNativeHost: () => true })); import { invokeNativeCommand } from "../native/commands"; diff --git a/apps/desktop/src/workspace/workspaceAdapter.ts b/apps/desktop/src/workspace/workspaceAdapter.ts index 9d9fd277..60716390 100644 --- a/apps/desktop/src/workspace/workspaceAdapter.ts +++ b/apps/desktop/src/workspace/workspaceAdapter.ts @@ -1,4 +1,4 @@ -import { isTauri } from "@tauri-apps/api/core"; +import { isNativeHost } from "../native/runtime"; import { invokeNativeCommand, NativeCommandError, @@ -60,7 +60,7 @@ export const workspaceDesktopApi: WorkspaceDesktopApi = { // Guard non-Tauri contexts (tests, web-only dev): a workspace list does // not exist there and the rejected invoke would only be noise. Called on // every window focus, so this matters. - if (!isTauri()) return Promise.resolve([]); + if (!isNativeHost()) return Promise.resolve([]); return invokeNativeCommand("list_known_workspaces"); }, deleteManagedWorkspace(rootPath) { diff --git a/apps/desktop/src/workspace/workspaceWatcher.ts b/apps/desktop/src/workspace/workspaceWatcher.ts index 592831ab..d10634b1 100644 --- a/apps/desktop/src/workspace/workspaceWatcher.ts +++ b/apps/desktop/src/workspace/workspaceWatcher.ts @@ -1,7 +1,9 @@ -import { listen } from "@tauri-apps/api/event"; - import { appEvents } from "../events/appEvents"; import { invokeNativeCommand } from "../native/commands"; +import { + subscribeToNativeEvent, + type NativeWorkspaceChange +} from "../native/events"; /** * Turns edits made outside the app into the events the app already understands. @@ -28,27 +30,10 @@ const WORKSPACE_CHANGED_EVENT = "workspace://changed"; const MAX_INDIVIDUAL_CHANGES = 50; /** - * One reportable change, mirroring the native `WorkspaceChange`. The native - * classifier always pairs a rename with its origin — an unresolvable end - * becomes a rescan instead — so `oldPath` is a required field here. + * The public domain alias for the native change union — kept so this module's + * API stays in workspace vocabulary while the wire shape lives in `native/`. */ -export type WorkspaceChange = - | { - readonly kind: "created" | "modified" | "deleted" | "rescan"; - /** Workspace-relative, forward slashes. Empty for a rescan. */ - readonly path: string; - } - | { - readonly kind: "renamed"; - readonly path: string; - /** Where a renamed note came from. */ - readonly oldPath: string; - }; - -interface WorkspaceChangedPayload { - readonly rootPath: string; - readonly changes: readonly WorkspaceChange[]; -} +export type WorkspaceChange = NativeWorkspaceChange; /** * Emits the note events describing `changes`. @@ -127,10 +112,10 @@ export async function watchWorkspace( // every event. const canonicalRoot = await invokeNativeCommand("watch_workspace", { rootPath }); - const unlisten = await listen(WORKSPACE_CHANGED_EVENT, (event) => { + const unlisten = await subscribeToNativeEvent(WORKSPACE_CHANGED_EVENT, (payload) => { // Every window hears every workspace; only this one's changes are ours. - if (event.payload.rootPath !== canonicalRoot) return; - applyWorkspaceChanges(rootPath, event.payload.changes, onRescan); + if (payload.rootPath !== canonicalRoot) return; + applyWorkspaceChanges(rootPath, payload.changes, onRescan); }); return () => { diff --git a/apps/desktop/src/workspace/workspaceWatcherLifecycle.test.ts b/apps/desktop/src/workspace/workspaceWatcherLifecycle.test.ts index df59966b..f8f88c17 100644 --- a/apps/desktop/src/workspace/workspaceWatcherLifecycle.test.ts +++ b/apps/desktop/src/workspace/workspaceWatcherLifecycle.test.ts @@ -1,28 +1,31 @@ import { beforeEach, describe, expect, it, vi } from "vitest"; import { appEvents } from "../events/appEvents"; +import type { NativeWorkspaceChangedPayload } from "../native/events"; -const listen = vi.fn(); +const subscribeToNativeEvent = vi.fn(); const invokeNativeCommand = vi.fn(); -vi.mock("@tauri-apps/api/event", () => ({ listen: (...args: unknown[]) => listen(...args) })); +vi.mock("../native/events", () => ({ + subscribeToNativeEvent: (...args: unknown[]) => subscribeToNativeEvent(...args) +})); vi.mock("../native/commands", () => ({ invokeNativeCommand: (...args: unknown[]) => invokeNativeCommand(...args) })); const { watchWorkspace } = await import("./workspaceWatcher"); -/** Captures the handler the watcher registers so tests can drive it. */ -type Handler = (event: { payload: unknown }) => void; +/** Captures the payload handler the watcher registers so tests can drive it. */ +type Handler = (payload: NativeWorkspaceChangedPayload) => void; const unlisten = vi.fn(); let handler: Handler = () => undefined; beforeEach(() => { - listen.mockReset(); + subscribeToNativeEvent.mockReset(); invokeNativeCommand.mockReset(); unlisten.mockReset(); - listen.mockImplementation((_event: string, given: Handler) => { + subscribeToNativeEvent.mockImplementation((_event: string, given: Handler) => { handler = given; return Promise.resolve(unlisten); }); @@ -48,9 +51,7 @@ describe("the workspace watcher's lifecycle", () => { const subscription = appEvents.on("note.saved", (payload) => seen.push(payload)); await watchWorkspace("/link/vault", vi.fn()); - handler({ - payload: { rootPath: "/real/vault", changes: [{ kind: "modified", path: "a.md" }] } - }); + handler({ rootPath: "/real/vault", changes: [{ kind: "modified", path: "a.md" }] }); // Heard, and re-announced under the root the stores are keyed by. expect(seen).toEqual([ @@ -65,9 +66,7 @@ describe("the workspace watcher's lifecycle", () => { const subscription = appEvents.on("note.saved", (payload) => seen.push(payload)); await watchWorkspace("/vault", vi.fn()); - handler({ - payload: { rootPath: "/other-vault", changes: [{ kind: "modified", path: "a.md" }] } - }); + handler({ rootPath: "/other-vault", changes: [{ kind: "modified", path: "a.md" }] }); expect(seen).toEqual([]); void subscription.dispose(); @@ -89,7 +88,7 @@ describe("the workspace watcher's lifecycle", () => { const onRescan = vi.fn(); await watchWorkspace("/vault", onRescan); - handler({ payload: { rootPath: "/vault", changes: [{ kind: "rescan", path: "" }] } }); + handler({ rootPath: "/vault", changes: [{ kind: "rescan", path: "" }] }); expect(onRescan).toHaveBeenCalledTimes(1); }); diff --git a/docs/reviews/2026-10-10/README.md b/docs/reviews/2026-10-10/README.md index 3507b920..a4900887 100644 --- a/docs/reviews/2026-10-10/README.md +++ b/docs/reviews/2026-10-10/README.md @@ -38,11 +38,10 @@ Three reviewers independently circled the same two seams: search-pool lifetime keyed by canonical root. The `detach_engine_on_delete` story is the first concrete leak from this gap; a `WorkspaceSession` abstraction is the structural fix. Worth one epic, not two. -- **The `native/` boundary is documented but incomplete.** Both sides flag - `@tauri-apps/*` imports escaping into feature folders (events, `isTauri`, - platform checks) and the hand-mirrored `NativeCommandMap`. A lint rule + - typed event/capability adapters closes most of it; ts-rs/tauri-specta is - the heavier answer for contract drift. +- **The `native/` transport boundary is now enforced.** Typed event/runtime + adapters and lint checks cover escaped Tauri imports. Command-name parity + is checked separately; argument/result type drift and application-port + placement remain distinct follow-ups. ## Disagreements / judgment calls diff --git a/docs/reviews/2026-10-10/architecture-core-extensions-editor-med-hard.md b/docs/reviews/2026-10-10/architecture-core-extensions-editor-med-hard.md index 2eddf332..04644827 100644 --- a/docs/reviews/2026-10-10/architecture-core-extensions-editor-med-hard.md +++ b/docs/reviews/2026-10-10/architecture-core-extensions-editor-med-hard.md @@ -76,11 +76,11 @@ Overall: `packages/core` is genuinely runtime-platform-neutral, and settings/reg ## 6. Make the core/adapters contract honest and enforceable -**Current decision and evidence.** Core itself obeys the no-React/DOM/Tauri rule, and desktop heavily reuses its note, settings, layout, and registry models. The vision, however, says app adapters implement interfaces defined in core (`plans/app-vision.md:66-71`); the workspace port is defined in the app beside its Tauri implementation (`apps/desktop/src/workspace/workspaceAdapter.ts:1-15,49-75`). Platform detection also leaks into shell/settings components (`apps/desktop/src/shell/useWorkspaceLifecycle.ts:1-8`; `apps/desktop/src/settings/ThemeProvider.tsx:1-7`; `apps/desktop/src/settings/SettingsTab.tsx:12-19`) despite the documented native-adapter boundary. +**Current decision and evidence.** Core itself obeys the no-React/DOM/Tauri rule, and desktop heavily reuses its note, settings, layout, and registry models. The vision, however, says app adapters implement interfaces defined in core (`plans/app-vision.md:66-71`); the workspace port is defined in the app beside its Tauri implementation (`apps/desktop/src/workspace/workspaceAdapter.ts`). The native-import/runtime portion is now addressed by `native/events`, `native/runtime`, and the import-boundary lint rule; port placement remains separate work. -**Cost.** `packages/core` is currently a good pure utility/domain package, not the promised application hub. UI orchestration decides which environment exists, tests mock Tauri in feature modules, and alternative adapters cannot be assembled from a clear port set. Moving every reducer into core would overcorrect and make core a dumping ground. +**Cost.** `packages/core` is currently a good pure utility/domain package, not the promised application hub. Alternative adapters cannot be assembled from a clear port set. Moving every reducer into core would overcorrect and make core a dumping ground. -**Alternative.** Choose explicitly: (a) revise the vision to “pure shared domain library” and keep ports in app feature modules; or (b), preferred for extension isolation and testability, define narrow workspace/document/search/settings ports and domain DTOs in core (or a new platform-neutral `application` package), with all Tauri/environment detection under `native/`. Add an import-boundary lint rule: outside `native/` and startup composition, no `@tauri-apps/*` imports. +**Alternative.** Choose explicitly: (a) revise the vision to “pure shared domain library” and keep ports in app feature modules; or (b), preferred for extension isolation and testability, define narrow workspace/document/search/settings ports and domain DTOs in core (or a new platform-neutral `application` package). Retain the enforced Tauri/environment boundary under `native/`. **Effort/risk/payoff.** Medium; low-medium runtime risk, mostly dependency movement and test seams; medium-high payoff in architectural honesty, web/test adapters, and a future out-of-process extension host. diff --git a/docs/reviews/2026-10-10/architecture-shell-state-med-hard.md b/docs/reviews/2026-10-10/architecture-shell-state-med-hard.md index 005c9ecd..2076ba69 100644 --- a/docs/reviews/2026-10-10/architecture-shell-state-med-hard.md +++ b/docs/reviews/2026-10-10/architecture-shell-state-med-hard.md @@ -4,12 +4,11 @@ Reviewed the renderer application architecture around `shell/`, `tabs/`, `panels/`, `events/`, `notifications/`, `workspace/`, and the renderer-facing `native/` boundary. I first mapped production/test file sizes and cross-feature imports, then traced workspace restoration/switching, tab/document state, command execution, panel/tab/editor registries, notifications, and native event subscriptions. This is an architecture judgment, not only a bug audit. -## Summary: top 5 recommendations +## Summary: remaining recommendations 2. **Replace the flat `ShellState` mega-bag with explicit domain facets.** Prefer memoized `tabs`, `workspace`, `panels`, `commands`, and `documents` view models over either the current unstable object or a wholesale move to Zustand. 3. **Extract shared shell composition from DesktopShell and PhoneShell.** In particular, build landing-tab actions and workspace switching once; keep only routing/layout differences in each chrome. 4. **Remove the module-global command-surface override.** Inject the active chrome's command target explicitly so commands are deterministic, instance-scoped, and testable. -5. **Finish the native boundary.** Tauri event listening and runtime detection should be adapters under `native/`, not imports spread through shell/workspace/sync/settings. ## Findings ranked by value @@ -18,7 +17,6 @@ Reviewed the renderer application architecture around `shell/`, `tabs/`, `panels | 2 | Split the unstable `ShellState` mega-bag into domain facets | med | hard | high | | 3 | Deduplicate cross-chrome application composition | med | med | high | | 4 | Inject command surfaces; remove the global mutable slot | med | med | high | -| 5 | Enforce the renderer/native bridge for events and capability checks | med | med | high | | 6 | Restore dependency direction between shell, workspace, panels, and tabs | med | med | medium-high | | 7 | Split the largest production renderer files by responsibility | low | med | medium | | 8 | Keep the existing contribution-registry primitive; do not invent one universal registry | low | low | medium | @@ -53,16 +51,6 @@ Reviewed the renderer application architecture around `shell/`, `tabs/`, `panels **Effort/risk/payoff.** Medium (2–3 days). Risk is medium because keyboard/palette/phone routes all execute commands. Payoff is high: deterministic behavior and much easier command tests. -## 5. Enforce the renderer/native bridge for events and capability checks - -**Current decision.** Command invocation is mostly centralized, which is good, but Tauri imports escape `native/`: watcher, git import, and sync subscribe directly to `@tauri-apps/api/event` (`apps/desktop/src/workspace/workspaceWatcher.ts:1-4`, `:118-138`; `apps/desktop/src/workspace/gitLinkImport.ts:8-15`, `:58-64`; `apps/desktop/src/sync/syncEvents.ts:10-29`). `isTauri` is also imported by shell/workspace code (`apps/desktop/src/shell/useWorkspaceLifecycle.ts:1`, `:81-97`; `apps/desktop/src/workspace/workspaceAdapter.ts:1`, `:56-61`). This conflicts with the documented “all native communication through `native/`” boundary. - -**Cost.** Tests must mock Tauri package modules throughout feature folders, event payload typing/cleanup conventions are repeated, and a future web/native transport change crosses unrelated features. Runtime detection also becomes policy embedded in consumers. - -**Change.** Add typed `native/events` subscriptions and a `native/runtime` capability (`isNativeHost`) or, preferably, put fallback behavior inside injected adapters. Workspace watcher and sync modules should depend on those interfaces. Do not hide domain event translation: `workspaceWatcher` should still translate native changes to `appEvents`; only transport belongs in `native/`. - -**Effort/risk/payoff.** Medium (3–5 days). Risk is medium around listener cleanup and Tauri event payloads. Payoff is high for compliance, tests, and Android/web portability. - ## 6. Restore dependency direction between feature folders **Current decision.** Shell imports workspace orchestration and workspace imports shell primitives (`apps/desktop/src/shell/DesktopShell.tsx:33-37`; `apps/desktop/src/workspace/WorkspaceSwitching.tsx:2`; `apps/desktop/src/workspace/WorkspaceExplorerView.tsx:6`). Panels import shell `Unavailable`, while shell imports panel models/renderers (`apps/desktop/src/panels/Popout.tsx:3-13`; `apps/desktop/src/shell/DesktopShell.tsx:13-16`). Shell types also derive selectable panel types from the panel registry (`apps/desktop/src/shell/shellTypes.ts:13-28`). Tabs are cleaner, but `MediaViewers` imports shell `Unavailable` (`apps/desktop/src/tabs/MediaViewers.tsx:5-7`). diff --git a/eslint.config.js b/eslint.config.js index 0d7ce7e9..3968545d 100644 --- a/eslint.config.js +++ b/eslint.config.js @@ -103,6 +103,42 @@ export default tseslint.config( ] } }, + { + // The renderer's Tauri boundary: feature code reaches the host only + // through `native/` adapters, so nothing outside that directory may touch + // the SDK — statically, as a type import, via re-export, dynamically, or + // through `require`. Ordinary Web APIs and feature imports stay allowed. + files: ["apps/desktop/src/**/*.{ts,tsx}"], + ignores: ["apps/desktop/src/native/**"], + rules: { + "no-restricted-imports": [ + "error", + { + patterns: [ + { + regex: "^@tauri-apps/", + message: + "Use apps/desktop/src/native adapters instead of importing Tauri in feature code." + } + ] + } + ], + "no-restricted-syntax": [ + "error", + { + selector: "ImportExpression[source.value=/^@tauri-apps\\//]", + message: + "Use apps/desktop/src/native adapters instead of importing Tauri in feature code." + }, + { + selector: + "CallExpression[callee.name='require'] > Literal[value=/^@tauri-apps\\//]", + message: + "Use apps/desktop/src/native adapters instead of importing Tauri in feature code." + } + ] + } + }, { // Tailwind CSS class-conflict detection — mirrors the `cssConflict` // warnings shown by the Tailwind IntelliSense extension, but runnable diff --git a/plans/other_tasks/done-finish_native_boundary-med-med.md b/plans/other_tasks/done-finish_native_boundary-med-med.md new file mode 100644 index 00000000..cf6df67e --- /dev/null +++ b/plans/other_tasks/done-finish_native_boundary-med-med.md @@ -0,0 +1,18 @@ +# Story: Finish the native/ boundary + +Tauri events and runtime/platform probes now pass through +`apps/desktop/src/native/`. Workspace event translation and sync refresh policy +remain in their feature modules. + +## Acceptance + +- [x] Typed `native/events` subscriptions (workspace-changed, sync, + git-import payloads) replacing direct event imports. +- [x] `native/runtime` probes (`isNativeHost`, `isApplePlatform`); + `isTauri()` not imported outside `native/`. +- [x] Import-boundary lint rule: no static/type/re-export, dynamic, or + literal `require` of `@tauri-apps/*` outside `native/`, including startup. + +Validation: `pnpm qa` passes. Focused tests cover event payloads, rejection and +async cleanup, canonical-root filtering, runtime probes, and the real lint rule. +Stacked on `settings_source_cleanup` to avoid overlapping-import conflicts. diff --git a/plans/other_tasks/pending-finish_native_boundary-med-med.md b/plans/other_tasks/pending-finish_native_boundary-med-med.md deleted file mode 100644 index bb1a91ad..00000000 --- a/plans/other_tasks/pending-finish_native_boundary-med-med.md +++ /dev/null @@ -1,19 +0,0 @@ -# Story: Finish the native/ boundary - -The documented rule — all Tauri IPC through `apps/desktop/src/native/` — is -only half-true (`docs/reviews/2026-10-10/architecture-shell-state-med-hard.md` -#5, `architecture-native-backend-med-hard.md` #4, and -`architecture-core-extensions-editor-med-hard.md` #6 all flag it). - -Escapes today: `@tauri-apps/api/event` imported directly by -`workspaceWatcher.ts`, `gitLinkImport.ts`, `syncEvents.ts`; `isTauri()` and -platform checks imported into shell/settings/workspace feature code. - -## Acceptance - -- [ ] Typed `native/events` subscribe helpers (workspace-changed, sync, - git-import payloads) replacing direct event imports. -- [ ] `native/runtime` capability (`isNativeHost`) or fallback-in-adapter - pattern; `isTauri()` not imported outside `native/`. -- [ ] Import-boundary lint rule: no `@tauri-apps/*` outside `native/` and - composition roots.