Voice-to-text dictation app with local (Nvidia Parakeet/Whisper) and cloud models (BYOK). Privacy-first and available cross-platform.
JavaScript aianthropiccross-platformgeminigroqlinuxmacosnvidiaopen-sourceopenaiparakeetspeech-to-texttranscribewhisperwindows
fix: seat count, LWW guard, sync and container load race
Chadpihac706fcf2b939
diff --git a/preload.js b/preload.jsindex 4a2376d24..fab8f1934 100644--- a/preload.js+++ b/preload.js@@ -145,7 +145,6 @@ contextBridge.exposeInMainWorld("electronAPI", {// Space functionsgetSpaces: () => ipcRenderer.invoke("db-get-spaces"),- createSpace: (space) => ipcRenderer.invoke("db-create-space", space),updateSpace: (id, updates) => ipcRenderer.invoke("db-update-space", id, updates),purgeSpace: (id) => ipcRenderer.invoke("db-purge-space", id),getSpaceByCloudSpaceId: (cloudSpaceId) =>diff --git a/src/components/InviteTeammateDialog.tsx b/src/components/InviteTeammateDialog.tsxindex 49de4b549..041cb5d65 100644--- a/src/components/InviteTeammateDialog.tsx+++ b/src/components/InviteTeammateDialog.tsx@@ -61,7 +61,7 @@ export default function InviteTeammateDialog({let cancelled = false;WorkspacesService.previewSeats(workspaceId, 1).then((preview) => {- if (!cancelled) setSeatsUsed(preview.next_quantity - 1);+ if (!cancelled) setSeatsUsed(preview.seats_used);}).catch(async () => {// No subscription yet — fall back to the member count so the seatdiff --git a/src/helpers/cloudSyncGuards.js b/src/helpers/cloudSyncGuards.jsindex 8dc5564ee..8f1459a8f 100644--- a/src/helpers/cloudSyncGuards.js+++ b/src/helpers/cloudSyncGuards.js@@ -18,13 +18,14 @@ export function isCloudEntryNewer(cloudUpdatedAt, localUpdatedAt) {return normalizeTimestamp(cloudUpdatedAt) > normalizeTimestamp(localUpdatedAt);}-// Full-content PATCH payload for an existing cloud note — a content-less-// PATCH still bumps the cloud row's updated_at, so the next pull elects a-// copy that never received the local edit (#1290). No client_note_id here:-// legacy cloud notes carry a different backfilled UUID per device, so-// PATCHing it on every push would fork duplicate notes; only the one-shot-// migration branch sends it.-export function buildNoteUpdatePayload(note, folderMap) {+// Full-content payload for note pushes — a content-less PATCH still bumps+// the cloud row's updated_at, so the next pull elects a copy that never+// received the local edit (#1290). No client_note_id here: legacy cloud+// notes carry a different backfilled UUID per device, so PATCHing it on+// every push would fork duplicate notes; only the one-shot migration branch+// sends it. `cloudFolderId` is the note's folder already mapped to its cloud+// id (null when folderless or unmapped).+export function buildNoteUpdatePayload(note, cloudFolderId) {return {title: note.title,content: note.content,@@ -39,7 +40,7 @@ export function buildNoteUpdatePayload(note, folderMap) {calendar_event_id: note.calendar_event_id,diarization_enabled: note.diarization_enabled,expected_speaker_count: note.expected_speaker_count,- folder_id: note.folder_id ? (folderMap.get(note.folder_id) ?? null) : null,+ folder_id: cloudFolderId ?? null,updated_at: note.updated_at,};}diff --git a/src/helpers/database.js b/src/helpers/database.jsindex a1c485aa2..6a6ce57f9 100644--- a/src/helpers/database.js+++ b/src/helpers/database.js@@ -2007,6 +2007,7 @@ class DatabaseManager {this.db.transaction(() => {this._deleteSpeakerRowsForNotes("SELECT id FROM notes WHERE folder_id = ?", id);hardDeleteNotes.run(id);+ this._retireConversationsWhere("folder_id = ?", [id]);if (folder.cloud_id) tombstoneFolder.run(id);else hardDeleteFolder.run(id);})();@@ -2204,10 +2205,6 @@ class DatabaseManager {}}- renameSpace(id, name) {- return this.updateSpace(id, { name });- }-setSpaceSyncStatus(id, status) {try {if (!this.db) throw new Error("Database not initialized");@@ -2315,6 +2312,29 @@ class DatabaseManager {.run(param);}+ // Container-scoped agent conversations die with their container — a+ // surviving row would dangle and resurface if SQLite ever reuses the+ // container's rowid. Synced rows tombstone (like deleteAgentConversation)+ // so the next push retires the cloud copy; a hard local delete would let+ // the next pull resurrect the conversation as a global one. Never-synced+ // rows hard-delete: there is no server row to retire, and a bare tombstone+ // would linger forever (getPendingConversationDeletes requires a cloud_id).+ _retireConversationsWhere(containerFilter, params) {+ this.db+ .prepare(+ `DELETE FROM agent_messages WHERE conversation_id IN (SELECT id FROM agent_conversations WHERE cloud_id IS NULL AND (${containerFilter}))`+ )+ .run(...params);+ this.db+ .prepare(`DELETE FROM agent_conversations WHERE cloud_id IS NULL AND (${containerFilter})`)+ .run(...params);+ this.db+ .prepare(+ `UPDATE agent_conversations SET deleted_at = datetime('now'), sync_status = 'pending', updated_at = datetime('now') WHERE cloud_id IS NOT NULL AND deleted_at IS NULL AND (${containerFilter})`+ )+ .run(...params);+ }+purgeSpace(localSpaceId) {try {if (!this.db) throw new Error("Database not initialized");@@ -2366,6 +2386,10 @@ class DatabaseManager {"UPDATE notes SET folder_id = NULL WHERE space_id != ? AND folder_id IN (SELECT id FROM folders WHERE space_id = ?)").run(localSpaceId, localSpaceId);+ this._retireConversationsWhere(+ "space_id = ? OR folder_id IN (SELECT id FROM folders WHERE space_id = ?)",+ [localSpaceId, localSpaceId]+ );this.db.prepare("DELETE FROM folders WHERE space_id = ?").run(localSpaceId);this.db.prepare("DELETE FROM spaces WHERE id = ?").run(localSpaceId);return { noteIds: ids, folderNames: names, relocatedNotes: relocated };@@ -3739,6 +3763,7 @@ class DatabaseManager {const result = this.db.transaction(() => {this._deleteSpeakerRowsForNotes("SELECT id FROM notes WHERE folder_id = ?", id);this.db.prepare("DELETE FROM notes WHERE folder_id = ?").run(id);+ this._retireConversationsWhere("folder_id = ?", [id]);return this.db.prepare("DELETE FROM folders WHERE id = ?").run(id);})();return { success: result.changes > 0, id, noteIds, name: folder?.name ?? null };@@ -3798,7 +3823,13 @@ class DatabaseManager {).run(privateSpaceId, name, randomUUID(), id);preservedFolder = this.db.prepare("SELECT * FROM folders WHERE id = ?").get(id);+ // Folder-scoped chats follow the preserved folder into the private+ // space so their space ref doesn't dangle on the revoked space.+ this.db+ .prepare("UPDATE agent_conversations SET space_id = ? WHERE folder_id = ?")+ .run(privateSpaceId, id);} else {+ this._retireConversationsWhere("folder_id = ?", [id]);this.db.prepare("DELETE FROM folders WHERE id = ?").run(id);}const getNote = this.db.prepare("SELECT * FROM notes WHERE id = ?");diff --git a/src/helpers/ipcHandlers.js b/src/helpers/ipcHandlers.jsindex d4978b9d1..ccdd59c57 100644--- a/src/helpers/ipcHandlers.js+++ b/src/helpers/ipcHandlers.js@@ -1519,10 +1519,6 @@ class IPCHandlers {return this.databaseManager.getSpaces();});- ipcMain.handle("db-create-space", async (event, space) => {- return this.databaseManager.createSpace(space);- });-ipcMain.handle("db-update-space", async (event, id, updates) => {return this.databaseManager.updateSpace(id, updates);});diff --git a/src/services/SyncService.ts b/src/services/SyncService.tsindex e3fe38a1c..29ee3673e 100644--- a/src/services/SyncService.ts+++ b/src/services/SyncService.ts@@ -16,7 +16,16 @@ import { CloudApiError } from "./cloudApi.js";import { notifyTeamSpacesCapabilityChanged } from "../lib/teamSpacesCapability";import { subscribeIsSubscribed } from "../lib/subscriptionFlag";import { readNoteConflictIds } from "../lib/noteConflictRegistry";-import { normalizeTimestamp } from "../helpers/cloudSyncGuards.js";+import {+ buildNoteUpdatePayload,+ isCloudEntryNewer,+ normalizeTimestamp,+} from "../helpers/cloudSyncGuards.js";+import {+ prunePurgedSpaceEntries,+ resolvePullCursorAdvance,+ revokedNoteForkUpdate,+} from "./syncPassPolicy";function isHttpStatus(err: unknown, status: number): boolean {return err instanceof CloudApiError && err.status === status;@@ -84,14 +93,11 @@ const PURGED_SPACE_GUARD_TTL_MS = 15 * 60 * 1000;// entry.const PURGED_SPACE_GUARD_LOCK = "openwhispr-purged-spaces";-export function readPurgedSpaceIds(): Record<string, number> {+function readPurgedSpaceIds(): Record<string, number> {try {const raw = localStorage.getItem(PURGED_SPACE_GUARD_KEY);const parsed = raw ? (JSON.parse(raw) as Record<string, number>) : {};- const now = Date.now();- return Object.fromEntries(- Object.entries(parsed).filter(([, at]) => now - at < PURGED_SPACE_GUARD_TTL_MS)- );+ return prunePurgedSpaceEntries(parsed, Date.now(), PURGED_SPACE_GUARD_TTL_MS);} catch {return {};}@@ -117,6 +123,29 @@ async function prunePurgedSpaceIds(liveCloudSpaceIds: Set<string>): Promise<void});}+// Upserts cloud spaces into local rows, skipping recently purged ones — a+// purge racing this pass (delete just clicked, or the server hasn't processed+// it yet) must not resurrect the space. Returns local ids of spaces that+// still need a content backfill: brand new, or left 'pending' by a backfill+// that never finished. Shared with spaceActions' post-mutation mirror+// refresh so the purge-race guard lives in exactly one place.+export async function upsertCloudSpaces(cloudSpaces: MySpace[]): Promise<number[]> {+ const purged = readPurgedSpaceIds();+ const backfillIds: number[] = [];+ for (const cloudSpace of cloudSpaces) {+ if (purged[cloudSpace.id]) continue;+ const space = await window.electronAPI.upsertSpaceFromCloud?.(+ cloudSpace as unknown as Record<string, unknown>+ );+ // New spaces insert as 'pending' and stay that way until their content+ // backfill completes, so an interruption anywhere re-runs it.+ if (space?.sync_status === "pending") {+ backfillIds.push(space.id);+ }+ }+ return backfillIds;+}+class SyncService {private syncing = false;private syncAllPending = false;@@ -467,8 +496,15 @@ class SyncService {folder.updated_at);} catch (err) {- if (!isFolderNameTakenError(err)) throw err;- this.dispatchFolderNameTaken(folder.name);+ if (isFolderNameTakenError(err)) {+ this.dispatchFolderNameTaken(folder.name);+ } else if (isTeamAccessError(err)) {+ // Recover like the batch path — otherwise a revoked folder edited+ // via the debounce just logs errors until the next full pass.+ await this.handleRevokedFolderPush(folder, ctx);+ } else {+ throw err;+ }}} else {const cloud = await FoldersService.create({@@ -494,27 +530,12 @@ class SyncService {}}- // Full note payload for pushes. Scope fields ride along so local moves- // between spaces propagate; the server no-ops them when unchanged.+ // Full note payload for pushes, built on the tested #1290 guard (a+ // content-less PATCH would still bump the cloud row's updated_at and hand+ // the next pull a stale copy to elect). Scope fields ride along so local+ // moves between spaces propagate; the server no-ops them when unchanged.private notePushPayload(note: NoteItem, cloudFolderId: string | null, scope: PushScopeFields) {- return {- title: note.title,- content: note.content,- enhanced_content: note.enhanced_content,- enhancement_prompt: note.enhancement_prompt,- enhanced_at_content_hash: note.enhanced_at_content_hash,- note_type: note.note_type,- source_file: note.source_file,- audio_duration_seconds: note.audio_duration_seconds,- transcript: note.transcript,- participants: note.participants,- calendar_event_id: note.calendar_event_id,- diarization_enabled: note.diarization_enabled,- expected_speaker_count: note.expected_speaker_count,- folder_id: cloudFolderId,- updated_at: note.updated_at,- ...scope,- };+ return { ...buildNoteUpdatePayload(note, cloudFolderId), ...scope };}private async pushNote(id: number): Promise<void> {@@ -654,7 +675,7 @@ class SyncService {await prunePurgedSpaceIds(cloudIds);const prior = (await window.electronAPI.getSpaces?.()) ?? [];- const backfillIds = await this.upsertCloudSpaces(cloudSpaces);+ const backfillIds = await upsertCloudSpaces(cloudSpaces);for (const space of prior) {if (space.kind !== "team" || !space.cloud_space_id || cloudIds.has(space.cloud_space_id)) {@@ -689,28 +710,6 @@ class SyncService {return true;}- // Upserts cloud spaces into local rows. Returns local ids of spaces that- // still need a content backfill: brand new, or left 'pending' by a backfill- // that never finished.- private async upsertCloudSpaces(cloudSpaces: MySpace[]): Promise<number[]> {- const purged = readPurgedSpaceIds();- const backfillIds: number[] = [];- for (const cloudSpace of cloudSpaces) {- // A purge racing this pass (delete just clicked, or the server hasn't- // processed it yet) must not resurrect the space.- if (purged[cloudSpace.id]) continue;- const space = await window.electronAPI.upsertSpaceFromCloud?.(- cloudSpace as unknown as Record<string, unknown>- );- // New spaces insert as 'pending' and stay that way until their content- // backfill completes, so an interruption anywhere re-runs it.- if (space?.sync_status === "pending") {- backfillIds.push(space.id);- }- }- return backfillIds;- }-private async buildSpaceContext(): Promise<SpaceSyncContext> {const spaces = (await window.electronAPI.getSpaces?.()) ?? [];return {@@ -743,7 +742,7 @@ class SyncService {const cloudSpaces = await SpacesService.mySpaces();// New spaces stay 'pending' so the next spaces pass backfills their// pre-existing content (this delta pull only sees rows past the cursor).- await this.upsertCloudSpaces(cloudSpaces);+ await upsertCloudSpaces(cloudSpaces);} catch (err) {console.error("Mid-pass spaces refresh failed:", err);return null;@@ -783,15 +782,30 @@ class SyncService {}return;}- // left_team rows already sit in the private space — fork in place.- const alreadyPrivate = note.space_id === ctx.privateSpace.id;- await window.electronAPI.updateNote(note.id, {- ...(alreadyPrivate ? {} : { space_id: ctx.privateSpace.id, folder_id: null }),- ...(note.cloud_id ? { client_note_id: crypto.randomUUID() } : {}),- cloud_id: null,- left_team: 0,- });- if (!alreadyPrivate) this.dispatchNoteRelocated(note.title, spaceName);+ await this.forkNoteToPrivate(note, ctx.privateSpace, "push", spaceName);+ }++ // Applies the plan §7.2 fork (see revokedNoteForkUpdate) and surfaces the+ // relocation toast when the note actually moved.+ private async forkNoteToPrivate(+ note: NoteItem,+ privateSpace: SpaceItem,+ source: "push" | "pull",+ spaceName: string | null | undefined+ ): Promise<void> {+ const { update, relocated } = revokedNoteForkUpdate(note, privateSpace.id, source);+ await window.electronAPI.updateNote(note.id, update);+ if (relocated) this.dispatchNoteRelocated(note.title, spaceName);+ }++ // A folder PATCH was rejected because its team is gone or access was+ // revoked: the server row moved to a scope we can't write, so retrying+ // would fail forever. Preserve the dirty folder in Personal with a forked+ // identity so the next push re-creates it as personal (plan §7.2).+ private async handleRevokedFolderPush(folder: FolderItem, ctx: SpaceSyncContext): Promise<void> {+ if (!ctx.privateSpace) return;+ await window.electronAPI.relocateRevokedFolder?.(folder.id, ctx.privateSpace.id, true);+ this.dispatchNoteRelocated(folder.name, ctx.byId.get(folder.space_id)?.name);}// Sync passes run in whichever window holds the web lock (often the always-@@ -932,13 +946,7 @@ class SyncService {// Leave the row pending; retried on the next pass.this.dispatchFolderNameTaken(folder.name);} else if (isTeamAccessError(err)) {- // The server row moved to a scope we can't write; PATCHing it would- // fail forever. Preserve the dirty folder in Personal with a forked- // identity so the next push re-creates it as personal (plan §7.2).- if (ctx.privateSpace) {- await window.electronAPI.relocateRevokedFolder?.(folder.id, ctx.privateSpace.id, true);- this.dispatchNoteRelocated(folder.name, ctx.byId.get(folder.space_id)?.name);- }+ await this.handleRevokedFolderPush(folder, ctx);} else {console.error("Folder migration sync failed:", err);}@@ -1053,7 +1061,7 @@ class SyncService {} else if (// Pending rows are never overwritten by pull (D2), here too.local.sync_status !== "pending" &&- normalizeTimestamp(cloudFolder.updated_at) > normalizeTimestamp(local.updated_at)+ isCloudEntryNewer(cloudFolder.updated_at, local.updated_at)) {await window.electronAPI.upsertFolderFromCloud?.(cloudFolder as unknown as Record<string, unknown>,@@ -1115,7 +1123,7 @@ class SyncService {if (!local ||(local.sync_status !== "pending" &&- normalizeTimestamp(cloudFolder.updated_at) > normalizeTimestamp(local.updated_at))+ isCloudEntryNewer(cloudFolder.updated_at, local.updated_at))) {await window.electronAPI.upsertFolderFromCloud?.(cloudFolder as unknown as Record<string, unknown>,@@ -1128,23 +1136,15 @@ class SyncService {}}- // A backfill snapshot never sees tombstones or stubs, and a dirty pass- // must re-see its parked/failed rows, so neither advances the cursors.- if (!snapshot && dirtyRows === 0) {- const hasTeamSpaces = [...ctx.byId.values()].some((s) => s.kind === "team");- if (teamCapable || !hasTeamSpaces) {- localStorage.setItem(cursorKey, syncStartedAt);- // Full pulls cover team rows too; keep the team cursor current so a- // later backup-off pass doesn't re-pull from the distant past.- if (!teamOnly) localStorage.setItem("lastSyncedAt.folders.team", syncStartedAt);- } else if (!teamOnly) {- // Degraded (own-rows-only) full pull: personal rows were fully- // covered, so the personal cursor may advance; the untouched .team- // cursor lets syncFolders' recovery pull catch up on teammate- // edits made during the outage.- localStorage.setItem(cursorKey, syncStartedAt);- }- }+ const { advanceCursor, advanceTeamCursor } = resolvePullCursorAdvance({+ snapshot,+ dirty: dirtyRows > 0,+ teamOnly,+ teamCapable,+ hasTeamSpaces: [...ctx.byId.values()].some((s) => s.kind === "team"),+ });+ if (advanceCursor) localStorage.setItem(cursorKey, syncStartedAt);+ if (advanceTeamCursor) localStorage.setItem("lastSyncedAt.folders.team", syncStartedAt);return dirtyRows === 0;} catch (err) {console.error("Folder pull failed:", err);@@ -1326,23 +1326,12 @@ class SyncService {if (cloudNote.access_removed) {if (!local) continue;if (local.sync_status !== "synced" && !local.deleted_at && ctx.privateSpace) {- // Already-private rows were just relocated by their folder's- // stub — keep their folder link, only fork identity: the server- // row now belongs to a scope we can't write, so pushing under- // the old ids would be rejected (or hard-deleted) forever. The- // next push creates the note as a new personal one.- const alreadyPrivate = local.space_id === ctx.privateSpace.id;- await window.electronAPI.updateNote(local.id, {- ...(alreadyPrivate ? {} : { space_id: ctx.privateSpace.id, folder_id: null }),- client_note_id: crypto.randomUUID(),- cloud_id: null,- });- if (!alreadyPrivate) {- this.dispatchNoteRelocated(- local.title,- ctx.byCloudSpaceId.get(cloudNote.previous_space_id ?? "")?.name- );- }+ await this.forkNoteToPrivate(+ local,+ ctx.privateSpace,+ "pull",+ ctx.byCloudSpaceId.get(cloudNote.previous_space_id ?? "")?.name+ );} else {await window.electronAPI.hardDeleteNote?.(local.id);}@@ -1356,9 +1345,7 @@ class SyncService {if (local && !local.deleted_at && ctx.byId.get(local.space_id)?.kind === "team") {if (cloudNote.deleted_at) {await window.electronAPI.hardDeleteNote?.(local.id);- } else if (- normalizeTimestamp(cloudNote.updated_at) > normalizeTimestamp(local.updated_at)- ) {+ } else if (isCloudEntryNewer(cloudNote.updated_at, local.updated_at)) {// 'error' rows carry unpushed work just like 'pending' ones.if (local.sync_status !== "synced") {await this.surfaceNoteConflict(local.client_note_id, cloudNote);@@ -1398,10 +1385,7 @@ class SyncService {continue;}- if (- !local ||- normalizeTimestamp(cloudNote.updated_at) > normalizeTimestamp(local.updated_at)- ) {+ if (!local || isCloudEntryNewer(cloudNote.updated_at, local.updated_at)) {if (local && local.sync_status !== "synced") {// A newer cloud copy over unpushed local edits ('pending' or// 'error'): surface the conflict to the editor banner instead@@ -1441,23 +1425,15 @@ class SyncService {cursorId = last.id;}- // A backfill snapshot never sees tombstones or stubs, so it must not- // advance the delta cursors.- if (!snapshot && dirtyRows === 0) {- const hasTeamSpaces = [...ctx.byId.values()].some((s) => s.kind === "team");- if (teamCapable || !hasTeamSpaces) {- localStorage.setItem(cursorKey, syncStartedAt);- // Full pulls cover team rows too; keep the team cursor current so a- // later backup-off pass doesn't re-pull from the distant past.- if (!teamOnly) localStorage.setItem("lastSyncedAt.notes.team", syncStartedAt);- } else if (!teamOnly) {- // Degraded (own-rows-only) full pull: personal rows were fully- // covered, so the personal cursor may advance; the untouched .team- // cursor lets syncNotes' recovery pull catch up on teammate edits- // made during the outage.- localStorage.setItem(cursorKey, syncStartedAt);- }- }+ const { advanceCursor, advanceTeamCursor } = resolvePullCursorAdvance({+ snapshot,+ dirty: dirtyRows > 0,+ teamOnly,+ teamCapable,+ hasTeamSpaces: [...ctx.byId.values()].some((s) => s.kind === "team"),+ });+ if (advanceCursor) localStorage.setItem(cursorKey, syncStartedAt);+ if (advanceTeamCursor) localStorage.setItem("lastSyncedAt.notes.team", syncStartedAt);return dirtyRows === 0;} catch (err) {console.error("Note pull failed:", err);@@ -1547,10 +1523,7 @@ class SyncService {continue;}- if (- !local ||- normalizeTimestamp(cloudConv.updated_at) > normalizeTimestamp(local.updated_at)- ) {+ if (!local || isCloudEntryNewer(cloudConv.updated_at, local.updated_at)) {await window.electronAPI.upsertConversationFromCloud?.(cloudConv as unknown as Record<string, unknown>,(cloudConv.messages ?? []) as unknown as Array<Record<string, unknown>>diff --git a/src/services/spaceActions.ts b/src/services/spaceActions.tsindex 7029353e7..b5f74d521 100644--- a/src/services/spaceActions.ts+++ b/src/services/spaceActions.ts@@ -1,6 +1,6 @@import { TeamsService } from "./TeamsService";import { SpacesService } from "./SpacesService";-import { markSpacePurged, readPurgedSpaceIds, syncService } from "./SyncService";+import { markSpacePurged, syncService, upsertCloudSpaces } from "./SyncService";import { loadSpaces, purgeSpace, updateSpaceMeta } from "../stores/noteStore";import type { SpaceItem, TeamRole } from "../types/electron";@@ -29,15 +29,7 @@ async function settleAddMembers(teamId: string, userIds: string[]): Promise<unkn}async function refreshSpaceMirror(): Promise<void> {- const cloudSpaces = await SpacesService.mySpaces();- const purged = readPurgedSpaceIds();- for (const cloudSpace of cloudSpaces) {- // A purge racing this refresh must not resurrect the space.- if (purged[cloudSpace.id]) continue;- await window.electronAPI.upsertSpaceFromCloud?.(- cloudSpace as unknown as Record<string, unknown>- );- }+ await upsertCloudSpaces(await SpacesService.mySpaces());await loadSpaces();}@@ -86,9 +78,7 @@ export async function renameSpace(}}-export async function deleteSpace(- space: SpaceItem-): Promise<{ success: boolean; error?: string }> {+export async function deleteSpace(space: SpaceItem): Promise<{ success: boolean; error?: string }> {if (space.cloud_space_id) {try {// Server archives the space; its teams survive as workspace entities anddiff --git a/src/services/syncPassPolicy.ts b/src/services/syncPassPolicy.tsnew file mode 100644index 000000000..79112df30--- /dev/null+++ b/src/services/syncPassPolicy.ts@@ -0,0 +1,80 @@+// Pure decision logic for sync passes, kept out of SyncService so the+// node --test suite can cover it (the cloudSyncGuards.js precedent, #1290).++export interface PullCursorAdvance {+ // The pass's own cursor ("lastSyncedAt.<kind>", or ".<kind>.team" on a+ // team-only pass).+ advanceCursor: boolean;+ // The ".<kind>.team" cursor a full pull also covers.+ advanceTeamCursor: boolean;+}++// A backfill snapshot never sees tombstones or stubs, and a dirty pass must+// re-see its parked/failed rows, so neither advances any cursor. A+// team-capable pass (or one with no team spaces at all) fully covered its+// scope: advance its own cursor, and after a full pull keep the team cursor+// current too so a later backup-off pass doesn't re-pull from the distant+// past. A degraded (own-rows-only) full pull still fully covered personal+// rows, so its cursor may advance; the untouched team cursor lets the+// recovery pull catch up on teammate edits made during the outage.+export function resolvePullCursorAdvance(pass: {+ snapshot: boolean;+ dirty: boolean;+ teamOnly: boolean;+ teamCapable: boolean;+ hasTeamSpaces: boolean;+}): PullCursorAdvance {+ if (pass.snapshot || pass.dirty) {+ return { advanceCursor: false, advanceTeamCursor: false };+ }+ if (pass.teamCapable || !pass.hasTeamSpaces) {+ return { advanceCursor: true, advanceTeamCursor: !pass.teamOnly };+ }+ return { advanceCursor: !pass.teamOnly, advanceTeamCursor: false };+}++// Entries older than the TTL are dropped so a failed space delete cannot hide+// a still-live space forever.+export function prunePurgedSpaceEntries(+ entries: Record<string, number>,+ now: number,+ ttlMs: number+): Record<string, number> {+ return Object.fromEntries(Object.entries(entries).filter(([, at]) => now - at < ttlMs));+}++export interface RevokedNoteFork {+ update: {+ space_id?: number;+ folder_id?: null;+ client_note_id?: string;+ cloud_id: null;+ left_team?: 0;+ };+ relocated: boolean;+}++// Update applied to a team note whose access was revoked (plan §7.2): move it+// to the private space (unless it already sits there, e.g. a left_team row or+// one just relocated by its folder's stub — those keep their folder link),+// drop the cloud link, and fork the client identity so the next push+// re-creates it as a new personal note. Push-side rejections fork the+// identity only when a server row exists (cloud_id) and clear the pending+// left_team retraction the server will never accept; the pull-side+// access_removed stub always forks — the server row exists by construction.+export function revokedNoteForkUpdate(+ note: { space_id: number; cloud_id?: string | null },+ privateSpaceId: number,+ source: "push" | "pull"+): RevokedNoteFork {+ const relocated = note.space_id !== privateSpaceId;+ return {+ relocated,+ update: {+ ...(relocated ? { space_id: privateSpaceId, folder_id: null } : {}),+ ...(source === "pull" || note.cloud_id ? { client_note_id: crypto.randomUUID() } : {}),+ cloud_id: null,+ ...(source === "push" ? { left_team: 0 as const } : {}),+ },+ };+}diff --git a/src/stores/noteStore.ts b/src/stores/noteStore.tsindex c059f919a..421d5aec6 100644--- a/src/stores/noteStore.ts+++ b/src/stores/noteStore.ts@@ -341,21 +341,37 @@ export async function loadFolders(): Promise<FolderItem[]> {return items;}+const containerLoadGenerations = new Map<string, number>();+const containerLoadsInFlight = new Map<string, Promise<NoteItem[]>>();+export async function loadContainerNotes(key: string): Promise<NoteItem[]> {- const [kind, idStr] = key.split(":");- const id = Number(idStr);- const items =- kind === "f"- ? ((await window.electronAPI?.getNotes(null, DEFAULT_LIMIT, id)) ?? [])- : ((await window.electronAPI?.getNotes(null, DEFAULT_LIMIT, null, id)) ?? []);- applyContainers({ ...useNoteStore.getState().notesByContainer, [key]: items });- return items;+ const gen = (containerLoadGenerations.get(key) ?? 0) + 1;+ containerLoadGenerations.set(key, gen);+ const load = (async (): Promise<NoteItem[]> => {+ const [kind, idStr] = key.split(":");+ const id = Number(idStr);+ const items =+ kind === "f"+ ? ((await window.electronAPI?.getNotes(null, DEFAULT_LIMIT, id)) ?? [])+ : ((await window.electronAPI?.getNotes(null, DEFAULT_LIMIT, null, id)) ?? []);+ // A newer load for this container may have resolved first.+ if (containerLoadGenerations.get(key) === gen) {+ applyContainers({ ...useNoteStore.getState().notesByContainer, [key]: items });+ }+ return items;+ })();+ containerLoadsInFlight.set(key, load);+ try {+ return await load;+ } finally {+ if (containerLoadsInFlight.get(key) === load) containerLoadsInFlight.delete(key);+ }}export async function ensureContainerLoaded(key: string): Promise<NoteItem[]> {const cached = useNoteStore.getState().notesByContainer[key];if (cached) return cached;- return loadContainerNotes(key);+ return containerLoadsInFlight.get(key) ?? loadContainerNotes(key);}export function setContainerExpanded(key: string, expanded: boolean): void {@@ -430,7 +446,10 @@ export async function initializeNotesTree(): Promise<void> {revealContainer(context.spaceId, context.folderId);useNoteStore.setState({ activeContext: context });- const notes = await loadContainerNotes(contextContainerKey(context));+ // The store stays IPC-maintained across mounts, so an existing container+ // entry is current — reuse it (or revealContainer's in-flight load)+ // instead of fetching the same container twice on every init.+ const notes = await ensureContainerLoaded(contextContainerKey(context));if (gen !== treeLoadGeneration) return;// Containers restored as expanded from a previous session must load their// notes too, or they render expanded-but-empty until re-toggled.diff --git a/src/types/electron.ts b/src/types/electron.tsindex 783bee5e3..b5b6c52d5 100644--- a/src/types/electron.ts+++ b/src/types/electron.ts@@ -838,10 +838,6 @@ declare global {// Space operationsgetSpaces?: () => Promise<SpaceItem[]>;- createSpace?: (space: {- name: string;- emoji?: string | null;- }) => Promise<{ success: boolean; space?: SpaceItem; error?: string }>;updateSpace?: (id: number,updates: { name?: string; emoji?: string | null }diff --git a/test/helpers/cloudSyncGuards.test.js b/test/helpers/cloudSyncGuards.test.jsindex e05b80f3d..aee2b7408 100644--- a/test/helpers/cloudSyncGuards.test.js+++ b/test/helpers/cloudSyncGuards.test.js@@ -76,7 +76,7 @@ const localNote = {test("the note update payload carries the full content, not just identifiers", async () => {const { buildNoteUpdatePayload } = await load();- const payload = buildNoteUpdatePayload(localNote, new Map([[3, "cloud-folder-3"]]));+ const payload = buildNoteUpdatePayload(localNote, "cloud-folder-3");// Only the one-shot migration branch may send client_note_id// (see buildNoteUpdatePayload):@@ -96,14 +96,10 @@ test("the note update payload carries the full content, not just identifiers", aassert.equal(payload.updated_at, "2026-07-22 08:47:00");});-test("the note update payload maps the local folder to its cloud id", async () => {+test("the note update payload carries the pre-mapped cloud folder id", async () => {const { buildNoteUpdatePayload } = await load();- const mapped = buildNoteUpdatePayload(localNote, new Map([[3, "cloud-folder-3"]]));- assert.equal(mapped.folder_id, "cloud-folder-3");-- const unmapped = buildNoteUpdatePayload(localNote, new Map());- assert.equal(unmapped.folder_id, null);-- const folderless = buildNoteUpdatePayload({ ...localNote, folder_id: null }, new Map());- assert.equal(folderless.folder_id, null);+ assert.equal(buildNoteUpdatePayload(localNote, "cloud-folder-3").folder_id, "cloud-folder-3");+ // Unmapped or folderless notes push an explicit null, never undefined.+ assert.equal(buildNoteUpdatePayload(localNote, null).folder_id, null);+ assert.equal(buildNoteUpdatePayload(localNote, undefined).folder_id, null);});diff --git a/test/helpers/containerConversationsDatabase.test.js b/test/helpers/containerConversationsDatabase.test.jsindex 3c2fc137c..70242e857 100644--- a/test/helpers/containerConversationsDatabase.test.js+++ b/test/helpers/containerConversationsDatabase.test.js@@ -220,3 +220,92 @@ test("upsertNoteFromCloud round-trips updated_by_user_id", (t) => {);assert.equal(unchanged.updated_by_user_id, "user-b");});++// Container conversations die with their container (space purge, folder+// delete, revocation): synced rows tombstone so the next push retires the+// cloud copy — a hard local delete would let the next pull resurrect the+// conversation as a global one — while never-synced rows hard-delete+// outright (no server row to retire).++test("purgeSpace retires the space's container conversations", (t) => {+ const db = createDb(t);+ if (!db) return;+ const space = db.createSpace({ name: "Eng" }).space;+ const folder = db.createFolder("Docs", space.id).folder;++ const syncedConv = db.createAgentConversation("Synced", null, space.id);+ db.markConversationSynced(syncedConv.id, "cloud-conv-1");+ const localConv = db.createAgentConversation("Local only", null, space.id, folder.id);+ db.addAgentMessage(localConv.id, "user", "hello");+ const globalConv = db.createAgentConversation("Global");++ assert.equal(db.purgeSpace(space.id).success, true);++ const tombstoned = db.db+ .prepare("SELECT * FROM agent_conversations WHERE id = ?")+ .get(syncedConv.id);+ assert.ok(tombstoned.deleted_at, "synced conversation must tombstone for the delete push");+ assert.equal(tombstoned.sync_status, "pending");++ assert.equal(+ db.db.prepare("SELECT COUNT(*) AS n FROM agent_conversations WHERE id = ?").get(localConv.id).n,+ 0+ );+ assert.equal(+ db.db+ .prepare("SELECT COUNT(*) AS n FROM agent_messages WHERE conversation_id = ?")+ .get(localConv.id).n,+ 0+ );++ const global = db.db.prepare("SELECT * FROM agent_conversations WHERE id = ?").get(globalConv.id);+ assert.equal(global.deleted_at, null, "unscoped conversations are untouched");+});++test("deleteFolder and hardDeleteFolder retire the folder's conversations", (t) => {+ const db = createDb(t);+ if (!db) return;+ const space = db.createSpace({ name: "Eng" }).space;+ const folder = db.createFolder("Docs", space.id).folder;+ const folderConv = db.createAgentConversation("Folder chat", null, space.id, folder.id);+ const spaceConv = db.createAgentConversation("Space chat", null, space.id);++ assert.equal(db.deleteFolder(folder.id).success, true);+ assert.equal(+ db.db.prepare("SELECT COUNT(*) AS n FROM agent_conversations WHERE id = ?").get(folderConv.id)+ .n,+ 0+ );+ assert.equal(db.getConversationsForContainer(space.id, null)[0].id, spaceConv.id);++ const folder2 = db.createFolder("Specs", space.id).folder;+ const conv2 = db.createAgentConversation("Specs chat", null, space.id, folder2.id);+ db.markConversationSynced(conv2.id, "cloud-conv-2");+ db.hardDeleteFolder(folder2.id);+ const tombstoned = db.db.prepare("SELECT * FROM agent_conversations WHERE id = ?").get(conv2.id);+ assert.ok(tombstoned.deleted_at);+ assert.equal(tombstoned.sync_status, "pending");+});++test("relocateRevokedFolder moves or retires the folder's conversations", (t) => {+ const db = createDb(t);+ if (!db) return;+ const privateId = db.getPrivateSpaceId();+ const space = db.createSpace({ name: "Eng" }).space;++ const kept = db.createFolder("Kept", space.id).folder;+ const keptConv = db.createAgentConversation("Kept chat", null, space.id, kept.id);+ assert.equal(db.relocateRevokedFolder(kept.id, privateId, true).success, true);+ const moved = db.db.prepare("SELECT * FROM agent_conversations WHERE id = ?").get(keptConv.id);+ assert.equal(moved.space_id, privateId, "chat follows the preserved folder");+ assert.equal(moved.deleted_at, null);++ const dropped = db.createFolder("Dropped", space.id).folder;+ const droppedConv = db.createAgentConversation("Dropped chat", null, space.id, dropped.id);+ assert.equal(db.relocateRevokedFolder(dropped.id, privateId, false).success, true);+ assert.equal(+ db.db.prepare("SELECT COUNT(*) AS n FROM agent_conversations WHERE id = ?").get(droppedConv.id)+ .n,+ 0+ );+});diff --git a/test/lib/workspaceSelection.test.js b/test/lib/workspaceSelection.test.jsindex 97f69b4cb..ff0c22565 100644--- a/test/lib/workspaceSelection.test.js+++ b/test/lib/workspaceSelection.test.js@@ -2,12 +2,21 @@ const test = require("node:test");const assert = require("node:assert/strict");const {groupTeamSpacesByWorkspace,+ manageableWorkspaces,selectWorkspaceForSpaceCreation,} = require("../../src/lib/workspaceSelection.ts");const workspace = (id, role) => ({ id, name: `Workspace ${id}`, role });const space = (id, workspaceId) => ({ id, workspace_id: workspaceId });+test("manageableWorkspaces: keeps only owner/admin workspaces, in order", () => {+ const member = workspace("m", "member");+ const admin = workspace("a", "admin");+ const owner = workspace("o", "owner");+ assert.deepEqual(manageableWorkspaces([member, admin, owner]), [admin, owner]);+ assert.deepEqual(manageableWorkspaces([member]), []);+});+test("groupTeamSpacesByWorkspace: groups spaces under their workspace", () => {const workspaces = [workspace("a", "owner"), workspace("b", "member")];const spaces = [space(1, "a"), space(2, "b"), space(3, "a")];diff --git a/test/services/migrationFlows.test.js b/test/services/migrationFlows.test.jsdeleted file mode 100644index a354d88aa..000000000--- a/test/services/migrationFlows.test.js+++ /dev/null@@ -1,53 +0,0 @@-const test = require("node:test");-const assert = require("node:assert/strict");--test("note snapshot pagination includes an id tie-breaker", async () => {- const { buildNotesListPath } = await import("../../src/services/noteListQuery.ts");- const path = buildNotesListPath({- limit: 50,- before: "2026-07-22T12:00:00.000Z",- scope: "all",- cursorId: "note-50",- });-- assert.equal(- path,- "/api/notes/list?limit=50&before=2026-07-22T12%3A00%3A00.000Z&scope=all&before_id=note-50"- );-});--test("note delta pagination includes an id tie-breaker", async () => {- const { buildNotesListPath } = await import("../../src/services/noteListQuery.ts");- const path = buildNotesListPath({- limit: 50,- since: "2026-07-22T12:00:00.000Z",- scope: "all",- cursorId: "note-50",- });-- assert.equal(- path,- "/api/notes/list?limit=50&since=2026-07-22T12%3A00%3A00.000Z&scope=all&since_id=note-50"- );-});--test("space creation ignores a persisted member-only workspace", async () => {- const { manageableWorkspaces, selectWorkspaceForSpaceCreation } =- await import("../../src/lib/workspaceSelection.ts");- const memberWorkspace = { id: "member", role: "member", name: "Member workspace" };- const adminWorkspace = { id: "admin", role: "admin", name: "Admin workspace" };- const manageable = manageableWorkspaces([memberWorkspace, adminWorkspace]);-- assert.deepEqual(manageable, [adminWorkspace]);- assert.equal(selectWorkspaceForSpaceCreation(manageable, memberWorkspace, null), adminWorkspace);-});--test("space creation honors an explicit manageable workspace selection", async () => {- const { manageableWorkspaces, selectWorkspaceForSpaceCreation } =- await import("../../src/lib/workspaceSelection.ts");- const first = { id: "first", role: "owner", name: "First" };- const second = { id: "second", role: "admin", name: "Second" };- const manageable = manageableWorkspaces([first, second]);-- assert.equal(selectWorkspaceForSpaceCreation(manageable, first, second.id), second);-});diff --git a/test/services/noteListQuery.test.js b/test/services/noteListQuery.test.jsnew file mode 100644index 000000000..cae0b819b--- /dev/null+++ b/test/services/noteListQuery.test.js@@ -0,0 +1,32 @@+const test = require("node:test");+const assert = require("node:assert/strict");++test("note snapshot pagination includes an id tie-breaker", async () => {+ const { buildNotesListPath } = await import("../../src/services/noteListQuery.ts");+ const path = buildNotesListPath({+ limit: 50,+ before: "2026-07-22T12:00:00.000Z",+ scope: "all",+ cursorId: "note-50",+ });++ assert.equal(+ path,+ "/api/notes/list?limit=50&before=2026-07-22T12%3A00%3A00.000Z&scope=all&before_id=note-50"+ );+});++test("note delta pagination includes an id tie-breaker", async () => {+ const { buildNotesListPath } = await import("../../src/services/noteListQuery.ts");+ const path = buildNotesListPath({+ limit: 50,+ since: "2026-07-22T12:00:00.000Z",+ scope: "all",+ cursorId: "note-50",+ });++ assert.equal(+ path,+ "/api/notes/list?limit=50&since=2026-07-22T12%3A00%3A00.000Z&scope=all&since_id=note-50"+ );+});diff --git a/test/services/syncPassPolicy.test.js b/test/services/syncPassPolicy.test.jsnew file mode 100644index 000000000..d70a1afeb--- /dev/null+++ b/test/services/syncPassPolicy.test.js@@ -0,0 +1,131 @@+const test = require("node:test");+const assert = require("node:assert/strict");++const load = () => import("../../src/services/syncPassPolicy.ts");++// --- resolvePullCursorAdvance ----------------------------------------------+// The matrix mirrors SyncService's pullFolders/pullNotes cursor semantics: a+// wrongly advanced cursor silently drops teammate edits from the delta pulls.++const base = {+ snapshot: false,+ dirty: false,+ teamOnly: false,+ teamCapable: true,+ hasTeamSpaces: true,+};++test("cursor policy: snapshots and dirty passes never advance", async () => {+ const { resolvePullCursorAdvance } = await load();+ for (const pass of [+ { ...base, snapshot: true },+ { ...base, dirty: true },+ { ...base, snapshot: true, dirty: true, teamOnly: true },+ ]) {+ assert.deepEqual(resolvePullCursorAdvance(pass), {+ advanceCursor: false,+ advanceTeamCursor: false,+ });+ }+});++test("cursor policy: a team-capable full pull advances both cursors", async () => {+ const { resolvePullCursorAdvance } = await load();+ assert.deepEqual(resolvePullCursorAdvance(base), {+ advanceCursor: true,+ advanceTeamCursor: true,+ });+});++test("cursor policy: a team-only pass advances only its own (team) cursor", async () => {+ const { resolvePullCursorAdvance } = await load();+ assert.deepEqual(resolvePullCursorAdvance({ ...base, teamOnly: true }), {+ advanceCursor: true,+ advanceTeamCursor: false,+ });+});++test("cursor policy: with no team spaces a degraded pull still advances fully", async () => {+ const { resolvePullCursorAdvance } = await load();+ assert.deepEqual(+ resolvePullCursorAdvance({ ...base, teamCapable: false, hasTeamSpaces: false }),+ { advanceCursor: true, advanceTeamCursor: true }+ );+});++test("cursor policy: a degraded full pull parks the team cursor for recovery", async () => {+ const { resolvePullCursorAdvance } = await load();+ // The gap this leaves between the cursors is exactly what teamCursorLagging+ // detects to schedule the recovery pull after a capability outage.+ assert.deepEqual(resolvePullCursorAdvance({ ...base, teamCapable: false }), {+ advanceCursor: true,+ advanceTeamCursor: false,+ });+});++test("cursor policy: a degraded team-only pass advances nothing", async () => {+ const { resolvePullCursorAdvance } = await load();+ assert.deepEqual(resolvePullCursorAdvance({ ...base, teamOnly: true, teamCapable: false }), {+ advanceCursor: false,+ advanceTeamCursor: false,+ });+});++// --- prunePurgedSpaceEntries ------------------------------------------------++test("purge guard: entries expire strictly at the TTL", async () => {+ const { prunePurgedSpaceEntries } = await load();+ const now = 1_000_000_000;+ const ttl = 900_000;+ const pruned = prunePurgedSpaceEntries(+ { fresh: now - 1, edge: now - ttl, stale: now - ttl - 1 },+ now,+ ttl+ );+ assert.deepEqual(pruned, { fresh: now - 1 });+ assert.deepEqual(prunePurgedSpaceEntries({}, now, ttl), {});+});++// --- revokedNoteForkUpdate --------------------------------------------------++test("revoked fork: a push rejection moves, forks and clears the retraction", async () => {+ const { revokedNoteForkUpdate } = await load();+ const { update, relocated } = revokedNoteForkUpdate(+ { space_id: 7, cloud_id: "cloud-1" },+ 1,+ "push"+ );+ assert.equal(relocated, true);+ assert.equal(update.space_id, 1);+ assert.equal(update.folder_id, null);+ assert.equal(update.cloud_id, null);+ assert.equal(update.left_team, 0);+ assert.equal(typeof update.client_note_id, "string");+});++test("revoked fork: a never-synced push rejection keeps its client identity", async () => {+ const { revokedNoteForkUpdate } = await load();+ const { update } = revokedNoteForkUpdate({ space_id: 7, cloud_id: null }, 1, "push");+ assert.equal("client_note_id" in update, false);+ assert.equal(update.cloud_id, null);+});++test("revoked fork: the pull-side stub always forks and leaves left_team alone", async () => {+ const { revokedNoteForkUpdate } = await load();+ const { update } = revokedNoteForkUpdate({ space_id: 7, cloud_id: null }, 1, "pull");+ assert.equal(typeof update.client_note_id, "string");+ assert.equal("left_team" in update, false);+});++test("revoked fork: an already-private row forks in place without moving", async () => {+ const { revokedNoteForkUpdate } = await load();+ const { update, relocated } = revokedNoteForkUpdate(+ { space_id: 1, cloud_id: "cloud-1" },+ 1,+ "pull"+ );+ assert.equal(relocated, false);+ assert.equal("space_id" in update, false);+ assert.equal("folder_id" in update, false);+ assert.equal(update.cloud_id, null);+});