Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions apps/desktop/src/main.tsx
Original file line number Diff line number Diff line change
@@ -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";
Expand All @@ -18,7 +18,7 @@ const bootstrap = bootstrapExtensions();
const localExtensions = createLocalExtensions({
loader: createDesktopLocalDirectoryLoader(),
bootstrap,
...(isTauri() ? { directories: createDesktopExtensionDirectoryStore() } : {})
...(isNativeHost() ? { directories: createDesktopExtensionDirectoryStore() } : {})
});
setLocalExtensions(localExtensions);

Expand Down
4 changes: 2 additions & 2 deletions apps/desktop/src/native/clipboard.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
* (tests, web preview).
*/

import { isTauri } from "@tauri-apps/api/core";
import { isNativeHost } from "./runtime";

import { invokeNativeCommand } from "./commands";

Expand All @@ -31,7 +31,7 @@ import { invokeNativeCommand } from "./commands";
export async function copyFilesToClipboard(
paths: readonly string[]
): Promise<boolean> {
if (!isTauri() || paths.length === 0) return false;
if (!isNativeHost() || paths.length === 0) return false;
try {
await invokeNativeCommand("copy_files_to_clipboard", { paths });
return true;
Expand Down
3 changes: 2 additions & 1 deletion apps/desktop/src/native/commands.test.ts
Original file line number Diff line number Diff line change
@@ -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,
Expand Down
6 changes: 4 additions & 2 deletions apps/desktop/src/native/commands.ts
Original file line number Diff line number Diff line change
@@ -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 {
Expand Down Expand Up @@ -743,7 +745,7 @@ interface NativeAppUpdate {
* a build where the plugin is not wired in.
*/
export async function checkForAppUpdate(): Promise<NativeAppUpdate | null> {
if (!isTauri()) return null;
if (!isNativeHost()) return null;
const { check } = await import("@tauri-apps/plugin-updater");
return await check();
}
Expand Down
6 changes: 3 additions & 3 deletions apps/desktop/src/native/dialogs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";

/**
Expand All @@ -20,7 +20,7 @@ import { open } from "@tauri-apps/plugin-dialog";
*/
export async function pickFilePath(): Promise<string | null> {
// 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",
Expand All @@ -44,7 +44,7 @@ export async function pickFilePath(): Promise<string | null> {
*/
export async function pickDirectoryPath(title: string): Promise<string | null> {
// 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;
Expand Down
140 changes: 140 additions & 0 deletions apps/desktop/src/native/events.test.ts
Original file line number Diff line number Diff line change
@@ -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<NativeWorkspaceChangedPayload>();
});
subscribeToNativeEvent("sync://import", (payload) => {
expectTypeOf(payload).toEqualTypeOf<NativeImportProgress>();
expectTypeOf<NativeEventMap["sync://import"]>().toEqualTypeOf<NativeImportProgress>();
});
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;
});
});
74 changes: 74 additions & 0 deletions apps/desktop/src/native/events.ts
Original file line number Diff line number Diff line change
@@ -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<K extends keyof NativeEventMap>(
event: K,
onEvent: (payload: NativeEventMap[K]) => void
): Promise<() => void> {
return listen<NativeEventMap[K]>(event, (envelope) => onEvent(envelope.payload));
}
6 changes: 3 additions & 3 deletions apps/desktop/src/native/fs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";

/**
Expand All @@ -37,7 +37,7 @@ export async function saveAndWriteTextFile(
contents: string
): Promise<boolean> {
// 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,
Expand All @@ -63,7 +63,7 @@ export async function pickAndReadTextFile(
extensions?: readonly string[]
): Promise<NativePickedTextFile | null> {
// 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,
Expand Down
Loading
Loading