Skip to content

Voice-to-text dictation app with local (Nvidia Parakeet/Whisper) and cloud models (BYOK). Privacy-first and available cross-platform.

fix: viewer note access, scope chats, stuck sync conflicts

Chadpiha5716782a18f8
diff --git a/src/components/notes/NoteEditor.tsx b/src/components/notes/NoteEditor.tsx
index 9ae46d0d0..46d6b0b9b 100644
--- a/src/components/notes/NoteEditor.tsx
+++ b/src/components/notes/NoteEditor.tsx
@@ -25,7 +25,7 @@ import {
Users,
} from "lucide-react";
import ShareNoteDialog from "./ShareNoteDialog";
-import { noteCapabilities } from "../../lib/notePermissions";
+import { noteCapabilities, resolveNotePermission } from "../../lib/notePermissions";
import SpaceMembersDialog from "./SpaceMembersDialog";
import {
useShareCacheEntry,
@@ -33,8 +33,11 @@ import {
useSpaces,
clearNoteConflict,
navigateToContainer,
+ persistNoteShareState,
updateNoteInStore,
+ updateShareCache,
} from "../../stores/noteStore";
+import { NoteSharingService } from "../../services/NoteSharingService";
import { fetchSpaceRoster } from "../../hooks/useTeamRoster";
import { readIsSubscribed, subscribeIsSubscribed } from "../../lib/subscriptionFlag";
import { useAuth } from "../../hooks/useAuth";
@@ -252,16 +255,43 @@ export default function NoteEditor({
// Same gate as SyncService.canSyncSharedNotes: sharing needs a subscription.
// An already-shared note stays manageable (unshare/revoke) after a lapse.
const isSubscribed = useSyncExternalStore(subscribeIsSubscribed, readIsSubscribed);
- // Legacy servers do not return note ACLs. Their existing model gives every
- // team member edit access and personal notes to their owner, so those are
- // the safe compatibility defaults until `access.my_permission` is present.
const shareCapabilities = noteCapabilities(
- shareCache?.access?.my_permission ?? (isTeamNote ? "editor" : "owner")
+ resolveNotePermission({
+ cachedPermission: shareCache?.access?.my_permission,
+ shareStateLoaded: shareCache !== null,
+ isTeamNote,
+ hasCloudId: Boolean(note.cloud_id),
+ })
);
const canShare =
isSignedIn && shareCapabilities.canShare && (isSubscribed || Boolean(note.is_shared));
- // Sync doesn't carry permissions, so a viewer is only known once share state loads.
const canEditNote = shareCapabilities.canEdit;
+ useEffect(() => {
+ if (!isSignedIn || !note.cloud_id || shareCache) return;
+ const cloudId = note.cloud_id;
+ let cancelled = false;
+ NoteSharingService.getShareSettings(cloudId)
+ .then((res) => {
+ if (cancelled) return;
+ updateShareCache(cloudId, (entry) => ({
+ share: res.share,
+ invitations: res.invitations,
+ access: res.access ?? entry?.access,
+ rawToken: entry?.rawToken ?? null,
+ }));
+ const serverShared = res.share.visibility !== "private";
+ if (serverShared !== Boolean(note.is_shared)) {
+ void persistNoteShareState(
+ note.id,
+ serverShared ? { is_shared: 1 } : { is_shared: 0, share_token: null }
+ ).catch((err) => console.error("Share flag persist failed:", err));
+ }
+ })
+ .catch((err) => console.error("Failed to load note permissions:", err));
+ return () => {
+ cancelled = true;
+ };
+ }, [isSignedIn, note.cloud_id, note.id, note.is_shared, shareCache]);
// A newer cloud copy arrived while this note had unpushed edits (plan §7.3).
const conflict = useNoteConflict(note.client_note_id);
const [conflictEditorName, setConflictEditorName] = useState<string | null>(null);
diff --git a/src/helpers/database.js b/src/helpers/database.js
index bdf66000b..0507f6eb9 100644
--- a/src/helpers/database.js
+++ b/src/helpers/database.js
@@ -2629,7 +2629,7 @@ class DatabaseManager {
if (!this.db) throw new Error("Database not initialized");
return this.db
.prepare(
- "SELECT * FROM agent_conversations WHERE deleted_at IS NULL ORDER BY updated_at DESC LIMIT ?"
+ "SELECT * FROM agent_conversations WHERE deleted_at IS NULL AND space_id IS NULL AND folder_id IS NULL ORDER BY updated_at DESC LIMIT ?"
)
.all(limit);
} catch (error) {
@@ -3205,8 +3205,8 @@ class DatabaseManager {
try {
if (!this.db) throw new Error("Database not initialized");
const archiveFilter = includeArchived
- ? "WHERE c.archived_at IS NOT NULL AND c.deleted_at IS NULL"
- : "WHERE c.archived_at IS NULL AND c.deleted_at IS NULL";
+ ? "WHERE c.archived_at IS NOT NULL AND c.deleted_at IS NULL AND c.space_id IS NULL AND c.folder_id IS NULL"
+ : "WHERE c.archived_at IS NULL AND c.deleted_at IS NULL AND c.space_id IS NULL AND c.folder_id IS NULL";
return this.db
.prepare(
`SELECT c.id, c.title, c.created_at, c.updated_at, c.archived_at, c.cloud_id,
@@ -3245,6 +3245,7 @@ class DatabaseManager {
LEFT JOIN agent_messages m ON m.conversation_id = c.id
LEFT JOIN agent_messages ms ON ms.conversation_id = c.id
WHERE c.archived_at IS NULL AND c.deleted_at IS NULL
+ AND c.space_id IS NULL AND c.folder_id IS NULL
AND (c.title LIKE ? OR ms.content LIKE ?)
GROUP BY c.id
ORDER BY c.updated_at DESC
diff --git a/src/lib/noteConflictRegistry.ts b/src/lib/noteConflictRegistry.ts
index 8c3192aa3..e7836d320 100644
--- a/src/lib/noteConflictRegistry.ts
+++ b/src/lib/noteConflictRegistry.ts
@@ -1,27 +1,57 @@
-// Client ids of notes with an unresolved pull conflict, persisted so the push
-// engine keeps honoring a conflict across restarts and windows (the banner's
-// CloudNote payload stays in-memory; the first pull after launch re-surfaces
-// it). Written only via the noteStore conflict setters.
+import type { CloudNote } from "../services/NotesService";
+
+// Full cloud snapshots for unresolved conflicts. Persisting only client ids
+// kept the push gate active after relaunch but left the editor with no payload
+// to render or resolve.
const KEY = "noteConflicts.clientIds";
-export function readNoteConflictIds(): Set<string> {
+function readStoredConflicts(): Record<string, CloudNote> {
try {
const raw = localStorage.getItem(KEY);
- return new Set(raw ? (JSON.parse(raw) as string[]) : []);
+ if (!raw) return {};
+ const parsed = JSON.parse(raw) as unknown;
+ if (Array.isArray(parsed)) {
+ // Pre-payload versions stored only ids. They cannot restore a banner, so
+ // unblock them once: the guarded push will 409 again and persist the
+ // server's current snapshot in the new format.
+ localStorage.removeItem(KEY);
+ return {};
+ }
+ if (!parsed || typeof parsed !== "object") return {};
+ return Object.fromEntries(
+ Object.entries(parsed).filter(([, value]) => value && typeof value === "object")
+ ) as Record<string, CloudNote>;
} catch {
- return new Set();
+ return {};
}
}
-export function addNoteConflictId(clientNoteId: string): void {
- const ids = readNoteConflictIds();
- if (ids.has(clientNoteId)) return;
- ids.add(clientNoteId);
- localStorage.setItem(KEY, JSON.stringify([...ids]));
+export function readNoteConflicts(): Record<string, CloudNote> {
+ return readStoredConflicts();
+}
+
+export function readNoteConflictIds(): Set<string> {
+ return new Set(Object.keys(readStoredConflicts()));
+}
+
+export function addNoteConflict(clientNoteId: string, cloudNote: CloudNote): void {
+ try {
+ const conflicts = readStoredConflicts();
+ conflicts[clientNoteId] = cloudNote;
+ localStorage.setItem(KEY, JSON.stringify(conflicts));
+ } catch {
+ // The in-memory store still surfaces the conflict for this session.
+ }
}
export function removeNoteConflictId(clientNoteId: string): void {
- const ids = readNoteConflictIds();
- if (!ids.delete(clientNoteId)) return;
- localStorage.setItem(KEY, JSON.stringify([...ids]));
+ try {
+ const conflicts = readStoredConflicts();
+ if (!(clientNoteId in conflicts)) return;
+ delete conflicts[clientNoteId];
+ localStorage.setItem(KEY, JSON.stringify(conflicts));
+ } catch {
+ // A failed persistence cleanup is harmless; the next guarded push can
+ // surface the conflict again.
+ }
}
diff --git a/src/lib/notePermissions.ts b/src/lib/notePermissions.ts
index db1ff5ce1..697a4c7f7 100644
--- a/src/lib/notePermissions.ts
+++ b/src/lib/notePermissions.ts
@@ -52,3 +52,23 @@ export function noteCapabilities(
}
return { ...NO_ACCESS };
}
+
+export function resolveNotePermission({
+ cachedPermission,
+ shareStateLoaded,
+ isTeamNote,
+ hasCloudId,
+}: {
+ cachedPermission?: NotePermission;
+ shareStateLoaded: boolean;
+ isTeamNote: boolean;
+ hasCloudId: boolean;
+}): NotePermission | null {
+ if (cachedPermission) return cachedPermission;
+ // A personal cloud note may belong to this user or may be a view-only grant.
+ // Until its ACL loads, fail closed instead of temporarily granting owner
+ // controls. A loaded legacy response has no ACL, so retain the old ownership
+ // fallback for compatibility with servers that predate note permissions.
+ if (hasCloudId && !isTeamNote && !shareStateLoaded) return null;
+ return isTeamNote ? "editor" : "owner";
+}
diff --git a/src/services/SyncService.ts b/src/services/SyncService.ts
index a93f206e9..55a4f029f 100644
--- a/src/services/SyncService.ts
+++ b/src/services/SyncService.ts
@@ -1404,6 +1404,9 @@ class SyncService {
} else if (isCloudEntryNewer(cloudNote.updated_at, local.updated_at)) {
// 'error' rows carry unpushed work just like 'pending' ones.
if (local.sync_status !== "synced") {
+ // Snapshot pulls never advance cursors; don't let an existing
+ // conflict block an unrelated new-space backfill.
+ if (!snapshot) dirtyRows++;
await this.surfaceNoteConflict(local.client_note_id, cloudNote);
} else if (cloudNote.folder_id && !cloudToLocal.has(cloudNote.folder_id)) {
// Filing to the fallback would stick (the advanced cursor
@@ -1446,6 +1449,9 @@ class SyncService {
// A newer cloud copy over unpushed local edits ('pending' or
// 'error'): surface the conflict to the editor banner instead
// of silently dropping the local edit (plan §7.3).
+ // Snapshots already keep their cursors and may be backfilling a
+ // different space, so only regular pulls need the dirty marker.
+ if (!snapshot) dirtyRows++;
await this.surfaceNoteConflict(local.client_note_id, cloudNote);
continue;
}
diff --git a/src/services/spaceActions.ts b/src/services/spaceActions.ts
index 7b8195bc7..09a06d413 100644
--- a/src/services/spaceActions.ts
+++ b/src/services/spaceActions.ts
@@ -79,14 +79,33 @@ export async function renameSpace(
): Promise<{ success: boolean; error?: string }> {
const local = await updateSpaceMeta(space.id, updates);
if (!local.success) return local;
- if (!space.cloud_space_id) return { success: true };
- try {
- await SpacesService.update(space.cloud_space_id, updates);
+ if (!space.cloud_space_id) {
+ await window.electronAPI.setSpaceSyncStatus?.(space.id, "synced");
+ await loadSpaces();
return { success: true };
+ }
+ let cloudSpace;
+ try {
+ cloudSpace = await SpacesService.update(space.cloud_space_id, updates);
} catch (err) {
await updateSpaceMeta(space.id, { name: space.name, emoji: space.emoji ?? null });
+ await window.electronAPI.setSpaceSyncStatus?.(space.id, "synced");
+ await loadSpaces();
return { success: false, error: errorMessage(err) };
}
+ try {
+ await window.electronAPI.upsertSpaceFromCloud?.(
+ cloudSpace as unknown as Record<string, unknown>
+ );
+ await window.electronAPI.setSpaceSyncStatus?.(space.id, "synced");
+ await loadSpaces();
+ } catch (err) {
+ // The server rename succeeded. Keep the optimistic row pending and let the
+ // regular mirror pass reconcile it instead of rolling back to a false name.
+ console.error("Space rename mirror failed:", err);
+ syncService.requestSyncAll("manual");
+ }
+ return { success: true };
}
export async function deleteSpace(space: SpaceItem): Promise<{ success: boolean; error?: string }> {
diff --git a/src/services/tools/searchNotesTool.ts b/src/services/tools/searchNotesTool.ts
index 2a3166c93..8181d97b7 100644
--- a/src/services/tools/searchNotesTool.ts
+++ b/src/services/tools/searchNotesTool.ts
@@ -1,6 +1,6 @@
import type { SpaceItem } from "../../types/electron";
import type { ToolDefinition, ToolResult } from "./ToolRegistry";
-import { resolveSpace } from "./utils";
+import { resolveLocalNoteId, resolveSpace } from "./utils";
const MAX_CONTENT_LENGTH = 500;
@@ -76,7 +76,9 @@ export function createSearchNotesTool(options: SearchToolOptions): ToolDefinitio
if (useCloudSearch && cloudCanScope && folderId == null) {
strategies.push(() => executeCloudSearch(query, limit, space, spaces));
}
- strategies.push(() => executeLocalSearch(query, limit, true, space, spaces, spaceId, folderId));
+ strategies.push(() =>
+ executeLocalSearch(query, limit, true, space, spaces, spaceId, folderId)
+ );
strategies.push(() =>
executeLocalSearch(query, limit, false, space, spaces, spaceId, folderId)
);
@@ -158,15 +160,17 @@ async function executeCloudSearch(
spaces.filter((s) => s.cloud_space_id).map((s) => [s.cloud_space_id!, s.name])
);
const privateSpaceName = spaces.find((s) => s.kind === "private")?.name ?? null;
- const results = cloudNotes.map((cn) => ({
- id: cn.client_note_id ? parseInt(cn.client_note_id, 10) : null,
- title: cn.title,
- date: cn.created_at,
- type: cn.note_type,
- score: cn.score,
- space: cn.space_id ? (spaceNameByCloudId.get(cn.space_id) ?? null) : privateSpaceName,
- content: (cn.enhanced_content || cn.content).slice(0, MAX_CONTENT_LENGTH),
- }));
+ const results = await Promise.all(
+ cloudNotes.map(async (cn) => ({
+ id: await resolveLocalNoteId(cn.client_note_id),
+ title: cn.title,
+ date: cn.created_at,
+ type: cn.note_type,
+ score: cn.score,
+ space: cn.space_id ? (spaceNameByCloudId.get(cn.space_id) ?? null) : privateSpaceName,
+ content: (cn.enhanced_content || cn.content).slice(0, MAX_CONTENT_LENGTH),
+ }))
+ );
return {
success: true,
diff --git a/src/services/tools/utils.ts b/src/services/tools/utils.ts
index 4a7d37b19..089ee398b 100644
--- a/src/services/tools/utils.ts
+++ b/src/services/tools/utils.ts
@@ -39,3 +39,29 @@ export function resolveSpace(spaces: SpaceItem[], spaceName: string): ResolveSpa
const available = spaces.map((s) => s.name).join(", ");
return { error: `Space "${spaceName}" not found. Available spaces: ${available}` };
}
+
+type NoteByClientIdLookup = (
+ clientNoteId: string
+) => Promise<{ id: number; deleted_at?: string | null } | null>;
+
+export async function resolveLocalNoteId(
+ clientNoteId: string | null | undefined,
+ lookup?: NoteByClientIdLookup
+): Promise<number | null> {
+ const resolve =
+ lookup ??
+ (typeof window !== "undefined"
+ ? (window.electronAPI.getNoteByClientId as NoteByClientIdLookup | undefined)
+ : undefined);
+ if (!clientNoteId || !resolve) return null;
+ try {
+ const note = await resolve(clientNoteId);
+ return note && !note.deleted_at && Number.isSafeInteger(note.id) && note.id > 0
+ ? note.id
+ : null;
+ } catch {
+ // Cloud search results remain useful to the model even when their local
+ // rows cannot be resolved into clickable cards.
+ return null;
+ }
+}
diff --git a/src/stores/noteStore.ts b/src/stores/noteStore.ts
index 994fd380c..744eaac29 100644
--- a/src/stores/noteStore.ts
+++ b/src/stores/noteStore.ts
@@ -1,7 +1,11 @@
import { create } from "zustand";
import { syncService } from "../services/SyncService.js";
import { removeNoteFromLists } from "./noteListOps";
-import { addNoteConflictId, removeNoteConflictId } from "../lib/noteConflictRegistry";
+import {
+ addNoteConflict,
+ readNoteConflicts,
+ removeNoteConflictId,
+} from "../lib/noteConflictRegistry";
import { findDefaultFolder } from "../components/notes/shared";
import type { CloudNote } from "../services/NotesService.js";
import type {
@@ -79,7 +83,7 @@ const useNoteStore = create<NoteState>()(() => ({
isTreeLoading: true,
migration: null,
shareByCloudId: new Map<string, NoteShareCacheEntry>(),
- noteConflicts: {},
+ noteConflicts: readNoteConflicts(),
}));
let hasBoundIpcListeners = false;
@@ -911,7 +915,7 @@ export async function startMigration(): Promise<void> {
}
export function setNoteConflict(clientNoteId: string, cloudNote: CloudNote): void {
- addNoteConflictId(clientNoteId);
+ addNoteConflict(clientNoteId, cloudNote);
const { noteConflicts } = useNoteStore.getState();
useNoteStore.setState({ noteConflicts: { ...noteConflicts, [clientNoteId]: cloudNote } });
}
diff --git a/test/helpers/containerConversationsDatabase.test.js b/test/helpers/containerConversationsDatabase.test.js
index 70242e857..28f0b52c5 100644
--- a/test/helpers/containerConversationsDatabase.test.js
+++ b/test/helpers/containerConversationsDatabase.test.js
@@ -137,6 +137,43 @@ test("getConversationsForContainer excludes deleted conversations", (t) => {
assert.equal(db.getConversationsForContainer(space.id, null).length, 0);
});
+test("global conversation lists and search exclude space and folder chats", (t) => {
+ const db = createDb(t);
+ if (!db) return;
+ const space = db.createSpace({ name: "Eng" }).space;
+ const folder = db.createFolder("Docs", space.id).folder;
+
+ const global = db.createAgentConversation("Roadmap global");
+ const archivedGlobal = db.createAgentConversation("Roadmap archived");
+ const noteScoped = db.createAgentConversation("Roadmap note", 123);
+ const spaceScoped = db.createAgentConversation("Roadmap space", null, space.id);
+ const folderScoped = db.createAgentConversation("Roadmap folder", null, space.id, folder.id);
+ db.archiveAgentConversation(archivedGlobal.id);
+ db.addAgentMessage(global.id, "user", "roadmap");
+ db.addAgentMessage(noteScoped.id, "user", "roadmap");
+ db.addAgentMessage(spaceScoped.id, "user", "roadmap");
+ db.addAgentMessage(folderScoped.id, "user", "roadmap");
+
+ assert.deepEqual(
+ new Set(db.getAgentConversations().map((conversation) => conversation.id)),
+ new Set([global.id, archivedGlobal.id, noteScoped.id])
+ );
+ assert.deepEqual(
+ new Set(db.getAgentConversationsWithPreview().map((conversation) => conversation.id)),
+ new Set([noteScoped.id, global.id])
+ );
+ assert.deepEqual(
+ db.getAgentConversationsWithPreview(50, 0, true).map((conversation) => conversation.id),
+ [archivedGlobal.id]
+ );
+ assert.deepEqual(
+ new Set(db.searchAgentConversations("roadmap").map((conversation) => conversation.id)),
+ new Set([global.id, noteScoped.id])
+ );
+ assert.equal(db.getConversationsForContainer(space.id, null)[0].id, spaceScoped.id);
+ assert.equal(db.getConversationsForContainer(space.id, folder.id)[0].id, folderScoped.id);
+});
+
test("searchNotes filters by folder", (t) => {
const db = createDb(t);
if (!db) return;
diff --git a/test/helpers/notePermissions.test.js b/test/helpers/notePermissions.test.js
index 4cf83d94c..056c45825 100644
--- a/test/helpers/notePermissions.test.js
+++ b/test/helpers/notePermissions.test.js
@@ -51,3 +51,54 @@ test("owners and administrators retain all capabilities", async () => {
assert.equal(capabilities.canTransferOwnership, true);
}
});
+
+test("personal cloud notes fail closed until their share state loads", async () => {
+ const { resolveNotePermission } = await load();
+
+ assert.equal(
+ resolveNotePermission({
+ shareStateLoaded: false,
+ isTeamNote: false,
+ hasCloudId: true,
+ }),
+ null
+ );
+ assert.equal(
+ resolveNotePermission({
+ cachedPermission: "viewer",
+ shareStateLoaded: true,
+ isTeamNote: false,
+ hasCloudId: true,
+ }),
+ "viewer"
+ );
+});
+
+test("local, team, and legacy notes retain their compatibility defaults", async () => {
+ const { resolveNotePermission } = await load();
+
+ assert.equal(
+ resolveNotePermission({
+ shareStateLoaded: false,
+ isTeamNote: false,
+ hasCloudId: false,
+ }),
+ "owner"
+ );
+ assert.equal(
+ resolveNotePermission({
+ shareStateLoaded: false,
+ isTeamNote: true,
+ hasCloudId: true,
+ }),
+ "editor"
+ );
+ assert.equal(
+ resolveNotePermission({
+ shareStateLoaded: true,
+ isTeamNote: false,
+ hasCloudId: true,
+ }),
+ "owner"
+ );
+});
diff --git a/test/lib/noteConflictRegistry.test.js b/test/lib/noteConflictRegistry.test.js
new file mode 100644
index 000000000..cf0efbdce
--- /dev/null
+++ b/test/lib/noteConflictRegistry.test.js
@@ -0,0 +1,73 @@
+const test = require("node:test");
+const assert = require("node:assert/strict");
+const fs = require("node:fs");
+const path = require("node:path");
+const ts = require("typescript");
+
+const values = new Map();
+global.localStorage = {
+ getItem: (key) => values.get(key) ?? null,
+ setItem: (key, value) => values.set(key, String(value)),
+ removeItem: (key) => values.delete(key),
+};
+
+let loaded;
+const load = () => {
+ if (!loaded) {
+ const filename = path.join(__dirname, "../../src/lib/noteConflictRegistry.ts");
+ const source = fs.readFileSync(filename, "utf8");
+ const output = ts.transpileModule(source, {
+ compilerOptions: { module: ts.ModuleKind.ESNext, target: ts.ScriptTarget.ES2022 },
+ }).outputText;
+ loaded = import(`data:text/javascript;base64,${Buffer.from(output).toString("base64")}`);
+ }
+ return loaded;
+};
+
+const cloudNote = {
+ id: "cloud-note",
+ client_note_id: "client-note",
+ title: "Server title",
+ content: "Server body",
+ enhanced_content: null,
+ note_type: "personal",
+ enhancement_prompt: null,
+ source_file: null,
+ audio_duration_seconds: null,
+ folder_id: null,
+ transcript: null,
+ enhanced_at_content_hash: null,
+ participants: null,
+ calendar_event_id: null,
+ diarization_enabled: null,
+ expected_speaker_count: null,
+ workspace_id: null,
+ space_id: null,
+ updated_by_user_id: null,
+ deleted_at: null,
+ created_at: "2026-07-28T10:00:00.000Z",
+ updated_at: "2026-07-28T10:01:00.000Z",
+};
+
+test.beforeEach(() => values.clear());
+
+test("persists and restores the full conflict payload", async () => {
+ const { addNoteConflict, readNoteConflictIds, readNoteConflicts, removeNoteConflictId } =
+ await load();
+
+ addNoteConflict("client-note", cloudNote);
+ assert.deepEqual(readNoteConflicts(), { "client-note": cloudNote });
+ assert.deepEqual([...readNoteConflictIds()], ["client-note"]);
+
+ removeNoteConflictId("client-note");
+ assert.deepEqual(readNoteConflicts(), {});
+});
+
+test("drops legacy id-only storage so a guarded push can re-surface it", async () => {
+ const { readNoteConflictIds, readNoteConflicts } = await load();
+
+ localStorage.setItem("noteConflicts.clientIds", JSON.stringify(["legacy-client"]));
+ assert.deepEqual(readNoteConflicts(), {});
+ assert.equal(localStorage.getItem("noteConflicts.clientIds"), null);
+ assert.deepEqual([...readNoteConflictIds()], []);
+});
diff --git a/test/services/toolUtils.test.js b/test/services/toolUtils.test.js
new file mode 100644
index 000000000..249d24156
--- /dev/null
+++ b/test/services/toolUtils.test.js
@@ -0,0 +1,49 @@
+const test = require("node:test");
+const assert = require("node:assert/strict");
+const fs = require("node:fs");
+const path = require("node:path");
+const ts = require("typescript");
+
+let loaded;
+const load = () => {
+ if (!loaded) {
+ const filename = path.join(__dirname, "../../src/services/tools/utils.ts");
+ const source = fs.readFileSync(filename, "utf8");
+ const output = ts.transpileModule(source, {
+ compilerOptions: { module: ts.ModuleKind.ESNext, target: ts.ScriptTarget.ES2022 },
+ }).outputText;
+ loaded = import(`data:text/javascript;base64,${Buffer.from(output).toString("base64")}`);
+ }
+ return loaded;
+};
+
+test("cloud UUIDs resolve through the local client-id lookup without numeric parsing", async () => {
+ const { resolveLocalNoteId } = await load();
+ const seen = [];
+ const id = await resolveLocalNoteId("3a4f8b9c-uuid", async (clientNoteId) => {
+ seen.push(clientNoteId);
+ return { id: 42, deleted_at: null };
+ });
+
+ assert.equal(id, 42);
+ assert.deepEqual(seen, ["3a4f8b9c-uuid"]);
+});
+
+test("unavailable, deleted, invalid, and failed local rows produce no clickable id", async () => {
+ const { resolveLocalNoteId } = await load();
+
+ assert.equal(await resolveLocalNoteId(null, async () => ({ id: 1 })), null);
+ assert.equal(await resolveLocalNoteId("uuid", undefined), null);
+ assert.equal(await resolveLocalNoteId("uuid", async () => null), null);
+ assert.equal(
+ await resolveLocalNoteId("uuid", async () => ({ id: 7, deleted_at: "2026-07-28" })),
+ null
+ );
+ assert.equal(await resolveLocalNoteId("uuid", async () => ({ id: Number.NaN })), null);
+ assert.equal(
+ await resolveLocalNoteId("uuid", async () => {
+ throw new Error("database unavailable");
+ }),
+ null
+ );
+});