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(notes): harden team spaces — relaunch corruption, sync wedges, purge residue, live pull updates
Gabriel Stein90611692280e
diff --git a/main.js b/main.jsindex 49d9c4174..b4f8070fb 100644--- a/main.js+++ b/main.js@@ -1041,9 +1041,14 @@ async function startApp() {if (qdrantManager.isReady()) {const vectorIndex = require("./src/helpers/vectorIndex");vectorIndex.init(qdrantManager.getPort());- vectorIndex.ensureCollection().catch((err) => {- debugLogger.debug("Qdrant collection setup error (non-fatal)", { error: err.message });- });+ vectorIndex+ .ensureCollection()+ .then(() => ipcHandlers?.drainPendingVectorPurges())+ .catch((err) => {+ debugLogger.debug("Qdrant collection setup error (non-fatal)", {+ error: err.message,+ });+ });}}).catch((err) => {diff --git a/preload.js b/preload.jsindex 21eb69e5a..a75a24af8 100644--- a/preload.js+++ b/preload.js@@ -194,6 +194,27 @@ contextBridge.exposeInMainWorld("electronAPI", {ipcRenderer.on("note-deleted", listener);return () => ipcRenderer.removeListener("note-deleted", listener);},+ onNoteSynced: (callback) => {+ const listener = (_event, note) => callback?.(note);+ ipcRenderer.on("note-synced", listener);+ return () => ipcRenderer.removeListener("note-synced", listener);+ },+ onFolderSynced: (callback) => {+ const listener = (_event, folder) => callback?.(folder);+ ipcRenderer.on("folder-synced", listener);+ return () => ipcRenderer.removeListener("folder-synced", listener);+ },+ onFolderDeleted: (callback) => {+ const listener = (_event, data) => callback?.(data);+ ipcRenderer.on("folder-deleted", listener);+ return () => ipcRenderer.removeListener("folder-deleted", listener);+ },+ emitSyncEvent: (name, payload) => ipcRenderer.invoke("broadcast-sync-event", name, payload),+ onSyncEvent: (callback) => {+ const listener = (_event, data) => callback?.(data);+ ipcRenderer.on("sync-event", listener);+ return () => ipcRenderer.removeListener("sync-event", listener);+ },onActionCreated: (callback) => {const listener = (_event, action) => callback?.(action);@@ -846,6 +867,8 @@ contextBridge.exposeInMainWorld("electronAPI", {upsertNoteFromCloud: (cloudNote, localFolderId, localSpaceId) =>ipcRenderer.invoke("db-upsert-note-from-cloud", cloudNote, localFolderId, localSpaceId),markNoteSynced: (id, cloudId) => ipcRenderer.invoke("db-mark-note-synced", id, cloudId),+ markNoteSyncedIfUnchanged: (id, cloudId, snapshotUpdatedAt) =>+ ipcRenderer.invoke("db-mark-note-synced-if-unchanged", id, cloudId, snapshotUpdatedAt),markNoteSyncError: (id) => ipcRenderer.invoke("db-mark-note-sync-error", id),hardDeleteNote: (id) => ipcRenderer.invoke("db-hard-delete-note", id),@@ -855,12 +878,16 @@ contextBridge.exposeInMainWorld("electronAPI", {upsertFolderFromCloud: (cloudFolder, localSpaceId) =>ipcRenderer.invoke("db-upsert-folder-from-cloud", cloudFolder, localSpaceId),markFolderSynced: (id, cloudId) => ipcRenderer.invoke("db-mark-folder-synced", id, cloudId),+ markFolderSyncedIfUnchanged: (id, cloudId, snapshotUpdatedAt) =>+ ipcRenderer.invoke("db-mark-folder-synced-if-unchanged", id, cloudId, snapshotUpdatedAt),adoptFolderIdentity: (id, clientFolderId, cloudId, updatedAt) =>ipcRenderer.invoke("db-adopt-folder-identity", id, clientFolderId, cloudId, updatedAt),forkFolderIdentity: (id) => ipcRenderer.invoke("db-fork-folder-identity", id),getFolderIdMap: () => ipcRenderer.invoke("db-get-folder-id-map"),getPendingFolderDeletes: () => ipcRenderer.invoke("db-get-pending-folder-deletes"),hardDeleteFolder: (id) => ipcRenderer.invoke("db-hard-delete-folder", id),+ relocateRevokedFolder: (id, privateSpaceId, preserveFolder) =>+ ipcRenderer.invoke("db-relocate-revoked-folder", id, privateSpaceId, preserveFolder),getPendingConversations: () => ipcRenderer.invoke("db-get-pending-conversations"),getPendingConversationDeletes: () => ipcRenderer.invoke("db-get-pending-conversation-deletes"),diff --git a/src/components/notes/NoteEditor.tsx b/src/components/notes/NoteEditor.tsxindex 70ab6a822..506fa9ae9 100644--- a/src/components/notes/NoteEditor.tsx+++ b/src/components/notes/NoteEditor.tsx@@ -120,6 +120,8 @@ interface NoteEditorProps {folders?: FolderItem[];onMoveToFolder?: (noteId: number, folderId: number) => void;onCreateFolderAndMove?: (noteId: number, folderName: string) => void;+ /** Cancels the owner's debounced autosaves before an external copy is applied. */+ onCancelPendingSaves?: () => void;}export default function NoteEditor({@@ -156,6 +158,7 @@ export default function NoteEditor({folders,onMoveToFolder,onCreateFolderAndMove,+ onCancelPendingSaves,}: NoteEditorProps) {const { t } = useTranslation();const [viewMode, setViewMode] = useState<MeetingViewMode>("raw");@@ -623,14 +626,20 @@ export default function NoteEditor({// current local placement.const handleConflictRefresh = useCallback(async () => {if (!conflict) return;+ // Cancel any queued autosave FIRST: a pending debounced save holds the+ // pre-refresh buffer and would both block the editor resync and clobber+ // the cloud copy in SQLite a second later.+ onCancelPendingSaves?.();const fresh = await window.electronAPI.upsertNoteFromCloud?.(conflict as unknown as Record<string, unknown>,note.folder_id,note.space_id);clearNoteConflict(note.client_note_id);+ // With no save pending, the owner's external-update resync applies the+ // fresh copy to the visible editor buffer.if (fresh) updateNoteInStore(fresh);- }, [conflict, note.client_note_id, note.folder_id, note.space_id]);+ }, [conflict, note.client_note_id, note.folder_id, note.space_id, onCancelPendingSaves]);// Keep the local edits; the next push wins last-write.const handleConflictKeep = useCallback(() => {diff --git a/src/components/notes/PersonalNotesView.tsx b/src/components/notes/PersonalNotesView.tsxindex 7e629e037..8a42fe930 100644--- a/src/components/notes/PersonalNotesView.tsx+++ b/src/components/notes/PersonalNotesView.tsx@@ -252,6 +252,21 @@ export default function PersonalNotesView({}}, [activeNote]);+ // Conflict-banner Refresh applies an external cloud copy: a queued+ // debounced save would clobber it with the pre-refresh buffer, so the+ // editor cancels pending saves before the copy is applied. With the timers+ // cleared, the external-update resync effect above picks up the fresh note.+ const cancelPendingSaves = useCallback(() => {+ if (saveTimeoutRef.current) {+ clearTimeout(saveTimeoutRef.current);+ saveTimeoutRef.current = null;+ }+ if (enhancedSaveTimeoutRef.current) {+ clearTimeout(enhancedSaveTimeoutRef.current);+ enhancedSaveTimeoutRef.current = null;+ }+ }, []);+const debouncedSave = useCallback((noteId: number, title: string, content: string) => {if (saveTimeoutRef.current) clearTimeout(saveTimeoutRef.current);saveTimeoutRef.current = setTimeout(async () => {@@ -658,6 +673,7 @@ export default function PersonalNotesView({folders={editorFolders}onMoveToFolder={handleMoveToFolder}onCreateFolderAndMove={handleCreateFolderAndMove}+ onCancelPendingSaves={cancelPendingSaves}actionProcessingState={actionProcessingState}actionName={actionName}actionPicker={@@ -832,12 +848,16 @@ export default function PersonalNotesView({<Plus size={11} />{t("notes.empty.createNote")}</button>- <button- onClick={() => setShowAddNotesDialog(true)}- className="flex items-center gap-1.5 px-4 h-7 rounded-md border border-foreground/8 dark:border-white/8 text-xs text-foreground/40 hover:text-foreground/60 hover:border-foreground/15 hover:bg-foreground/3 dark:hover:bg-white/3 transition-colors"- >- {t("notes.addToFolder.addExisting")}- </button>+ {/* AddNotesToFolderDialog only mounts for folder contexts —+ space-root empty states offer just "Create note". */}+ {activeFolderId != null && (+ <button+ onClick={() => setShowAddNotesDialog(true)}+ className="flex items-center gap-1.5 px-4 h-7 rounded-md border border-foreground/8 dark:border-white/8 text-xs text-foreground/40 hover:text-foreground/60 hover:border-foreground/15 hover:bg-foreground/3 dark:hover:bg-white/3 transition-colors"+ >+ {t("notes.addToFolder.addExisting")}+ </button>+ )}</div></>) : (diff --git a/src/components/notes/SpaceMembersDialog.tsx b/src/components/notes/SpaceMembersDialog.tsxindex 73288d4be..1ccecc3e2 100644--- a/src/components/notes/SpaceMembersDialog.tsx+++ b/src/components/notes/SpaceMembersDialog.tsx@@ -11,6 +11,7 @@ import { useDelayedFlag } from "../../hooks/useDelayedFlag";import { cn } from "../lib/utils";import InviteTeammateDialog from "../InviteTeammateDialog";import { TeamsService } from "../../services/TeamsService";+import { markTeamSpacePurged } from "../../services/SyncService";import { useWorkspaceStore } from "../../stores/workspaceStore";import { loadSpaces, purgeSpace } from "../../stores/noteStore";import { canManageSpace } from "../../lib/spacePermissions";@@ -42,6 +43,13 @@ export default function SpaceMembersDialog({ space, open, onOpenChange }: SpaceMconst teamId = space.cloud_team_id;const canManage = canManageSpace(space, workspace?.role ?? null);const canInviteToWorkspace = workspace?.role === "owner" || workspace?.role === "admin";+ // Workspace owners/admins access every team implicitly (no team_members+ // row): the server's member DELETE no-ops (or leaves implicit access+ // intact), so the space would resurrect on the next sync pass right after+ // a local purge — Leave is n/a for them (plan §4).+ const isImplicitAdmin = workspace?.role === "owner" || workspace?.role === "admin";+ const isExplicitMember = members.some((m) => m.user_id === user?.id);+ const canLeave = isExplicitMember && !isImplicitAdmin;const loadRoster = useCallback(async () => {if (!teamId) return;@@ -135,6 +143,7 @@ export default function SpaceMembersDialog({ space, open, onOpenChange }: SpaceM};const confirmLeave = () => {+ if (!canLeave) return;showConfirmDialog({title: t("notes.spaces.members.leaveConfirm", { space: space.name }),description: t("notes.spaces.members.leaveConfirmDescription"),@@ -145,11 +154,12 @@ export default function SpaceMembersDialog({ space, open, onOpenChange }: SpaceMsetIsLeaving(true);try {await TeamsService.removeMember(teamId, user.id);+ markTeamSpacePurged(teamId);onOpenChange(false);// Local cleanup rides on the space-purged broadcast.await purgeSpace(space.id);} catch (err) {- // Server rejects e.g. a last-admin leave — surface its message.+ // Server rejected the leave — surface its message.toast({title: t("common.error"),description: err instanceof Error ? err.message : t("common.unknownError"),@@ -354,7 +364,8 @@ export default function SpaceMembersDialog({ space, open, onOpenChange }: SpaceM<buttontype="button"onClick={confirmLeave}- disabled={isLeaving}+ disabled={isLeaving || !canLeave}+ title={!canLeave ? t("notes.spaces.members.implicitAdminCannotLeave") : undefined}className={cn("flex items-center gap-2 w-full px-4 h-10 rounded-lg","border border-border/50 dark:border-border-subtle/70",diff --git a/src/components/notes/SpaceSyncToastListener.tsx b/src/components/notes/SpaceSyncToastListener.tsxindex a0956dd39..4c8e49d77 100644--- a/src/components/notes/SpaceSyncToastListener.tsx+++ b/src/components/notes/SpaceSyncToastListener.tsx@@ -7,6 +7,9 @@ const DEDUPE_MS = 15_000;/*** Headless. Mount once inside ToastProvider so team-space access changes* raised by sync surface even when the user is outside the notes view.+ * Sync passes run in whichever window holds the web lock (often the always-on+ * dictation overlay), so the signals arrive via the main-process 'sync-event'+ * rebroadcast rather than window-local CustomEvents.* A rejected push and the following spaces-pass purge can both announce the* same space, so access-revoked toasts dedupe by space name; folder name* conflicts recur every sync pass while unresolved, so they dedupe too.@@ -19,50 +22,43 @@ export default function SpaceSyncToastListener() {const lastRevokedAt = new Map<string, number>();const lastFolderConflictAt = new Map<string, number>();- const onSpaceRevoked = (event: Event) => {- const { spaceName } = (event as CustomEvent<{ spaceName: string | null }>).detail;- if (!spaceName) return;- const now = Date.now();- if (now - (lastRevokedAt.get(spaceName) ?? 0) < DEDUPE_MS) return;- lastRevokedAt.set(spaceName, now);- toast({- title: t("notes.spaces.accessRevoked", { space: spaceName }),- variant: "destructive",- });- };+ const dispose = window.electronAPI?.onSyncEvent?.(({ name, payload }) => {+ if (name === "space-revoked") {+ const { spaceName } = (payload ?? {}) as { spaceName?: string | null };+ if (!spaceName) return;+ const now = Date.now();+ if (now - (lastRevokedAt.get(spaceName) ?? 0) < DEDUPE_MS) return;+ lastRevokedAt.set(spaceName, now);+ toast({+ title: t("notes.spaces.accessRevoked", { space: spaceName }),+ variant: "destructive",+ });+ } else if (name === "folder-name-taken") {+ const { name: folderName } = (payload ?? {}) as { name?: string };+ if (!folderName) return;+ const now = Date.now();+ if (now - (lastFolderConflictAt.get(folderName) ?? 0) < DEDUPE_MS) return;+ lastFolderConflictAt.set(folderName, now);+ toast({+ title: t("notes.spaces.folderNameTaken", { name: folderName }),+ variant: "destructive",+ });+ } else if (name === "note-relocated") {+ const { title, spaceName } = (payload ?? {}) as {+ title?: string | null;+ spaceName?: string | null;+ };+ if (!spaceName) return;+ toast({+ title: t("notes.spaces.movedToPersonal", {+ space: spaceName,+ title: title || t("notes.list.untitled"),+ }),+ });+ }+ });- const onFolderNameTaken = (event: Event) => {- const { name } = (event as CustomEvent<{ name: string }>).detail;- const now = Date.now();- if (now - (lastFolderConflictAt.get(name) ?? 0) < DEDUPE_MS) return;- lastFolderConflictAt.set(name, now);- toast({- title: t("notes.spaces.folderNameTaken", { name }),- variant: "destructive",- });- };-- const onNoteRelocated = (event: Event) => {- const { title, spaceName } = (- event as CustomEvent<{ title: string | null; spaceName: string | null }>- ).detail;- if (!spaceName) return;- toast({- title: t("notes.spaces.movedToPersonal", {- space: spaceName,- title: title || t("notes.list.untitled"),- }),- });- };-- window.addEventListener("openwhispr:space-revoked", onSpaceRevoked);- window.addEventListener("openwhispr:note-relocated", onNoteRelocated);- window.addEventListener("openwhispr:folder-name-taken", onFolderNameTaken);- return () => {- window.removeEventListener("openwhispr:space-revoked", onSpaceRevoked);- window.removeEventListener("openwhispr:note-relocated", onNoteRelocated);- window.removeEventListener("openwhispr:folder-name-taken", onFolderNameTaken);- };+ return () => dispose?.();}, [toast, t]);return null;diff --git a/src/components/notes/SpacesTree.tsx b/src/components/notes/SpacesTree.tsxindex bfe5e681c..b9cf0c939 100644--- a/src/components/notes/SpacesTree.tsx+++ b/src/components/notes/SpacesTree.tsx@@ -44,6 +44,8 @@ import { useAuth } from "../../hooks/useAuth";import { useWorkspace } from "../../hooks/useWorkspace";import { canManageSpace } from "../../lib/spacePermissions";import { TeamsService } from "../../services/TeamsService";+import { NoteSharingService } from "../../services/NoteSharingService";+import { markTeamSpacePurged } from "../../services/SyncService";import { useSettingsStore } from "../../stores/settingsStore";import { cn } from "../lib/utils";import { formatRelativeTime } from "../../utils/dateFormatting";@@ -56,6 +58,7 @@ import {useSpaces,useFolders,useFolderCounts,+ useSpaceRootCounts,useNotesByContainer,useExpandedContainers,useActiveContext,@@ -73,6 +76,10 @@ import {updateSpaceMeta,purgeSpace,getNoteFromStore,+ getFoldersValue,+ getSpacesValue,+ updateShareCache,+ persistNoteShareState,} from "../../stores/noteStore";const FOLDER_INPUT_CLASS =@@ -216,6 +223,7 @@ function SpaceRow({isDropSuccess,dropHandlers,canManage,+ canLeave,onActivate,onToggle,onNewFolder,@@ -235,6 +243,7 @@ function SpaceRow({isDropSuccess: boolean;dropHandlers: DropHandlers;canManage: boolean;+ canLeave: boolean;onActivate: () => void;onToggle: () => void;onNewFolder: () => void;@@ -387,7 +396,7 @@ function SpaceRow({</DropdownMenuItem></>)}- {space.cloud_team_id && (+ {space.cloud_team_id && canLeave && (<DropdownMenuItemonClick={(e) => {e.stopPropagation();@@ -1022,6 +1031,7 @@ export default function SpacesTree({const spaces = useSpaces();const folders = useFolders();const folderCounts = useFolderCounts();+ const spaceRootCounts = useSpaceRootCounts();const notesByContainer = useNotesByContainer();const expanded = useExpandedContainers();const activeContext = useActiveContext();@@ -1060,6 +1070,14 @@ export default function SpacesTree({!space.cloud_team_id ||canManageSpace(space, workspaces.find((w) => w.id === space.workspace_id)?.role ?? null);+ // Workspace owners/admins access every team implicitly (no team_members+ // row), so a "leave" is a server no-op and the space would resurrect on the+ // next sync pass — Leave is n/a for them (plan §4).+ const hasImplicitSpaceAccess = (space: SpaceItem): boolean => {+ const role = workspaces.find((w) => w.id === space.workspace_id)?.role;+ return role === "owner" || role === "admin";+ };+const targetLabel = (target: NoteMoveTarget): string => {if (target.folderId != null) {return folders.find((f) => f.id === target.folderId)?.name ?? "";@@ -1094,20 +1112,25 @@ export default function SpacesTree({fromSpaceId: number,toSpaceId: number,isFolder: boolean,- onConfirm: () => void+ onConfirm: () => void,+ willDisableShare = false) => {const intoSpace = spaces.find((s) => s.id === toSpaceId);const fromSpace = spaces.find((s) => s.id === fromSpaceId);if (!intoSpace || !fromSpace) return;const movingIntoTeam = intoSpace.kind === "team";+ const moveInDescription = t(+ isFolder ? "notes.spaces.confirmMoveInFolder" : "notes.spaces.confirmMoveIn",+ { space: intoSpace.name }+ );showConfirmDialog({title: movingIntoTeam? t("notes.spaces.confirmMoveInTitle", { space: intoSpace.name }): t("notes.spaces.confirmMoveOutTitle", { space: fromSpace.name }),description: movingIntoTeam- ? t(isFolder ? "notes.spaces.confirmMoveInFolder" : "notes.spaces.confirmMoveIn", {- space: intoSpace.name,- })+ ? willDisableShare+ ? `${moveInDescription} ${t("notes.spaces.confirmMoveInShared")}`+ : moveInDescription: t(isFolder ? "notes.spaces.confirmMoveOutFolder" : "notes.spaces.confirmMoveOut", {space: fromSpace.name,}),@@ -1116,6 +1139,33 @@ export default function SpacesTree({});};+ // D8: team notes never carry a public web link — moving a web-shared note+ // into a team space revokes its share (the confirm dialog announces it).+ const willRevokeShare = (note: NoteItem, toSpaceId: number): boolean =>+ Boolean(note.is_shared && note.cloud_id) &&+ note.space_id !== toSpaceId &&+ spaces.find((s) => s.id === toSpaceId)?.kind === "team";++ const revokePublicShare = async (note: NoteItem) => {+ const cloudId = note.cloud_id;+ if (!cloudId) return;+ try {+ const res = await NoteSharingService.clearShare(cloudId);+ updateShareCache(cloudId, (entry) => ({+ share: res.share,+ invitations: entry?.invitations ?? [],+ rawToken: null,+ }));+ void persistNoteShareState(note.id, { is_shared: 0, share_token: null }).catch(+ (err: unknown) => console.error("Share flag persist failed:", err)+ );+ } catch {+ // Best effort — the move proceeds; the link stays revocable by moving+ // the note back to Personal.+ toast({ title: t("notes.spaces.shareRevokeFailed"), variant: "destructive" });+ }+ };+const moveNoteSafely = async (noteId: number, target: NoteMoveTarget): Promise<boolean> => {try {await onMoveNote(noteId, target);@@ -1126,16 +1176,37 @@ export default function SpacesTree({}};+ // The 8s undo window outlives the tree snapshot: the restore target may+ // have been deleted (folder) or purged (space) meanwhile. Never restore a+ // note into a container nothing renders — degrade to the space root.+ const undoMoveNote = async (noteId: number, title: string, prev: NoteMoveTarget) => {+ const prevSpace = getSpacesValue().find((s) => s.id === prev.spaceId);+ if (!prevSpace) {+ toast({ title: t("notes.spaces.couldNotMoveNote"), variant: "destructive" });+ return;+ }+ const folderGone =+ prev.folderId != null && !getFoldersValue().some((f) => f.id === prev.folderId);+ const restore = folderGone ? { spaceId: prev.spaceId, folderId: null } : prev;+ const moved = await moveNoteSafely(noteId, restore);+ if (moved && folderGone) {+ toast({ title: t("notes.spaces.moved", { title, target: spaceDisplayName(prevSpace, t) }) });+ }+ };+const commitMoveNote = async (noteId: number, target: NoteMoveTarget) => {const note = getNoteFromStore(noteId);const prev: NoteMoveTarget | null = note? { spaceId: note.space_id, folderId: note.folder_id }: null;+ if (note && willRevokeShare(note, target.spaceId)) {+ await revokePublicShare(note);+ }const moved = await moveNoteSafely(noteId, target);if (moved && prev) {const title = note?.title || t("notes.list.untitled");// Undo silently restores the previous space/folder — no confirm, no new toast.- showUndoToast(title, targetLabel(target), () => void moveNoteSafely(noteId, prev));+ showUndoToast(title, targetLabel(target), () => void undoMoveNote(noteId, title, prev));}};@@ -1147,7 +1218,8 @@ export default function SpacesTree({note.space_id,target.spaceId,false,- () => void commitMoveNote(noteId, target)+ () => void commitMoveNote(noteId, target),+ willRevokeShare(note, target.spaceId));} else {void commitMoveNote(noteId, target);@@ -1196,8 +1268,16 @@ export default function SpacesTree({const { dragState, noteDragHandlers, dropTargetHandlers } = useNoteDragAndDrop({onMoveToTarget: commitMoveNote,- onCrossSpaceDrop: (note: DraggedNoteInfo, target, commit) =>- confirmCrossSpaceMove(note.spaceId, target.spaceId, false, commit),+ onCrossSpaceDrop: (note: DraggedNoteInfo, target, commit) => {+ const full = getNoteFromStore(note.id);+ confirmCrossSpaceMove(+ note.spaceId,+ target.spaceId,+ false,+ commit,+ full ? willRevokeShare(full, target.spaceId) : false+ );+ },onHoverTarget: (key) => setContainerExpanded(key, true),});@@ -1320,6 +1400,8 @@ export default function SpacesTree({});return;}+ // Park the team id so an in-flight pull can't resurrect purged rows.+ markTeamSpacePurged(space.cloud_team_id);}const result = await purgeSpace(space.id);if (!result.success && result.error) {@@ -1344,10 +1426,19 @@ export default function SpacesTree({variant: "destructive",onConfirm: async () => {try {+ // The member DELETE succeeds even when no roster row exists, so an+ // implicit workspace owner/admin "leave" would purge locally only to+ // resurrect on the next pass — never purge for a server no-op.+ const roster = await TeamsService.listMembers(teamId);+ if (hasImplicitSpaceAccess(space) || !roster.some((m) => m.user_id === userId)) {+ toast({ title: t("notes.spaces.members.implicitAdminCannotLeave") });+ return;+ }await TeamsService.removeMember(teamId, userId);+ markTeamSpacePurged(teamId);await purgeSpace(space.id);} catch (err) {- // Server rejects e.g. a last-admin leave — surface its message.+ // Server rejected the leave — surface its message.toast({title: t("common.error"),description: err instanceof Error ? err.message : t("common.unknownError"),@@ -1618,9 +1709,11 @@ export default function SpacesTree({const spaceFolders = folders.filter((f) => f.space_id === space.id);const rootNotes = notesByContainer[spaceKey];const displayName = spaceDisplayName(space, t);+ // DB-backed counts: space-root notes count before their container loads,+ // and the root contribution isn't capped at the container's page size.const noteCount =spaceFolders.reduce((sum, f) => sum + (folderCounts[f.id] ?? 0), 0) +- (rootNotes?.length ?? 0);+ (spaceRootCounts[space.id] ?? 0);const showSkeletons =space.kind === "team" &&space.sync_status === "pending" &&@@ -1679,6 +1772,7 @@ export default function SpacesTree({isDropSuccess={dragState.dropSuccessKey === spaceKey}dropHandlers={dropTargetHandlers({ spaceId: space.id, folderId: null })}canManage={canManageTeamSpace(space)}+ canLeave={!hasImplicitSpaceAccess(space)}onActivate={() => activateRow({ type: "space", key: spaceKey, space })}onToggle={() => toggleContainerExpanded(spaceKey)}onNewFolder={() => startCreateFolder(space)}diff --git a/src/helpers/database.js b/src/helpers/database.jsindex 1d3db54b7..dec52544b 100644--- a/src/helpers/database.js+++ b/src/helpers/database.js@@ -197,19 +197,26 @@ class DatabaseManager {seedFolder.run("Meetings", 1);}+ // Backfill folder_id only when the column is first added: on later+ // launches a NULL folder_id is a legitimate space-root note, not a+ // pre-folders row.+ let folderColumnAdded = true;try {this.db.exec("ALTER TABLE notes ADD COLUMN folder_id INTEGER REFERENCES folders(id)");} catch (err) {if (!err.message.includes("duplicate column")) throw err;+ folderColumnAdded = false;}- const personalFolder = this.db- .prepare("SELECT id FROM folders WHERE name = 'Personal' AND is_default = 1")- .get();- if (personalFolder) {- this.db- .prepare("UPDATE notes SET folder_id = ? WHERE folder_id IS NULL")- .run(personalFolder.id);+ if (folderColumnAdded) {+ const personalFolder = this.db+ .prepare("SELECT id FROM folders WHERE name = 'Personal' AND is_default = 1")+ .get();+ if (personalFolder) {+ this.db+ .prepare("UPDATE notes SET folder_id = ? WHERE folder_id IS NULL")+ .run(personalFolder.id);+ }}this.db.exec(`@@ -738,6 +745,29 @@ class DatabaseManager {"CREATE INDEX IF NOT EXISTS idx_folders_space_sort ON folders(space_id, sort_order)");+ // Cloud-backed rows that just LEFT a team must keep pushing their scope+ // retraction (D6) even in the backup-off team-only pass, where the+ // pending queues otherwise filter on the row's CURRENT space kind.+ try {+ this.db.exec("ALTER TABLE notes ADD COLUMN left_team INTEGER NOT NULL DEFAULT 0");+ } catch (err) {+ if (!err.message.includes("duplicate column")) throw err;+ }+ try {+ this.db.exec("ALTER TABLE folders ADD COLUMN left_team INTEGER NOT NULL DEFAULT 0");+ } catch (err) {+ if (!err.message.includes("duplicate column")) throw err;+ }++ // Space vector purges owed to Qdrant while the sidecar was down/booting;+ // drained once the vector index is ready.+ this.db.exec(`+ CREATE TABLE IF NOT EXISTS pending_vector_purges (+ space_id INTEGER PRIMARY KEY,+ created_at DATETIME DEFAULT CURRENT_TIMESTAMP+ )+ `);+return true;} catch (error) {debugLogger.error("Database initialization failed", { error: error.message }, "database");@@ -1599,6 +1629,29 @@ class DatabaseManager {.get(updates.folder_id);if (folder) updates = { ...updates, space_id: folder.space_id };}+ if (updates.space_id !== undefined) {+ // D6: a cloud-backed note leaving a team must keep pushing until the+ // scope retraction lands, even when cloud backup is off (left_team+ // keeps it in the team-only pending queue). Identity forks null the+ // cloud_id — nothing to retract, so they never set the flag.+ const current = this.db+ .prepare(+ "SELECT n.space_id, n.cloud_id, s.kind AS space_kind FROM notes n LEFT JOIN spaces s ON s.id = n.space_id WHERE n.id = ?"+ )+ .get(id);+ if (current && current.space_id !== updates.space_id) {+ const newKind = this.db+ .prepare("SELECT kind FROM spaces WHERE id = ?")+ .get(updates.space_id)?.kind;+ const keepsCloudId =+ updates.cloud_id === undefined ? current.cloud_id != null : updates.cloud_id != null;+ if (current.space_kind === "team" && newKind === "private" && keepsCloudId) {+ updates = { ...updates, left_team: 1 };+ } else if (newKind === "team") {+ updates = { ...updates, left_team: 0 };+ }+ }+ }const allowedFields = ["title","content",@@ -1616,6 +1669,7 @@ class DatabaseManager {"deleted_at","client_note_id","cloud_id",+ "left_team",];const fields = [];const values = [];@@ -1711,6 +1765,7 @@ class DatabaseManager {);const hardDeleteFolder = this.db.prepare("DELETE FROM folders WHERE id = ?");this.db.transaction(() => {+ this._deleteSpeakerRowsForNotes("SELECT id FROM notes WHERE folder_id = ?", id);hardDeleteNotes.run(id);if (folder.cloud_id) tombstoneFolder.run(id);else hardDeleteFolder.run(id);@@ -1756,7 +1811,7 @@ class DatabaseManager {if (!folder) return { success: false, error: "Folder not found" };if (folder.is_default) return { success: false, error: "Cannot move default folders" };const space = this.db- .prepare("SELECT id FROM spaces WHERE id = ? AND deleted_at IS NULL")+ .prepare("SELECT id, kind FROM spaces WHERE id = ? AND deleted_at IS NULL").get(spaceId);if (!space) return { success: false, error: "Space not found" };if (folder.space_id === spaceId) return { success: true, folder, notes: [] };@@ -1766,17 +1821,23 @@ class DatabaseManager {).get(folder.name, spaceId, id);if (existing) return { success: false, error: "A folder with that name already exists" };+ // D6: cloud-backed rows leaving a team must keep pushing their scope+ // retraction even in the backup-off team-only pass (left_team).+ const oldKind = this.db+ .prepare("SELECT kind FROM spaces WHERE id = ?")+ .get(folder.space_id)?.kind;+ const leftTeam = oldKind === "team" && space.kind === "private" ? 1 : 0;const notes = this.db.transaction(() => {this.db.prepare(- "UPDATE folders SET space_id = ?, sync_status = 'pending', updated_at = datetime('now') WHERE id = ?"+ "UPDATE folders SET space_id = ?, sync_status = 'pending', updated_at = datetime('now'), left_team = ? WHERE id = ?")- .run(spaceId, id);+ .run(spaceId, leftTeam && folder.cloud_id ? 1 : 0, id);this.db.prepare(- "UPDATE notes SET space_id = ?, sync_status = 'pending', updated_at = datetime('now') WHERE folder_id = ? AND deleted_at IS NULL"+ "UPDATE notes SET space_id = ?, sync_status = 'pending', updated_at = datetime('now'), left_team = (CASE WHEN ? = 1 AND cloud_id IS NOT NULL THEN 1 ELSE 0 END) WHERE folder_id = ? AND deleted_at IS NULL")- .run(spaceId, id);+ .run(spaceId, leftTeam, id);return this.db.prepare("SELECT * FROM notes WHERE folder_id = ? AND deleted_at IS NULL").all(id);@@ -1792,9 +1853,11 @@ class DatabaseManager {getFolderNoteCounts() {try {if (!this.db) throw new Error("Database not initialized");+ // folder_id NULL rows are space-root notes; grouping by space_id too+ // attributes them per space so the tree shows true space totals.return this.db.prepare(- "SELECT folder_id, COUNT(*) as count FROM notes WHERE deleted_at IS NULL GROUP BY folder_id"+ "SELECT space_id, folder_id, COUNT(*) as count FROM notes WHERE deleted_at IS NULL GROUP BY space_id, folder_id").all();} catch (error) {@@ -1958,6 +2021,14 @@ class DatabaseManager {}}+ // FKs are not enforced in this DB — clean speaker rows explicitly.+ _deleteSpeakerRowsForNotes(noteIdSubquery, param) {+ this.db.prepare(`DELETE FROM speaker_mappings WHERE note_id IN (${noteIdSubquery})`).run(param);+ this.db+ .prepare(`DELETE FROM note_speaker_embeddings WHERE note_id IN (${noteIdSubquery})`)+ .run(param);+ }+purgeSpace(localSpaceId) {try {if (!this.db) throw new Error("Database not initialized");@@ -1966,7 +2037,28 @@ class DatabaseManager {if (space.kind === "private") {return { success: false, error: "Cannot purge the private space" };}- const { noteIds, folderNames } = this.db.transaction(() => {+ const privateSpaceId = this.getPrivateSpaceId();+ const { noteIds, folderNames, relocatedNotes } = this.db.transaction(() => {+ // Never-synced notes exist nowhere else — move them to the private+ // space root instead of destroying them with the space.+ let relocated = [];+ if (privateSpaceId != null) {+ const neverSynced = this.db+ .prepare(+ "SELECT id FROM notes WHERE space_id = ? AND cloud_id IS NULL AND deleted_at IS NULL"+ )+ .all(localSpaceId)+ .map((row) => row.id);+ if (neverSynced.length > 0) {+ this.db+ .prepare(+ "UPDATE notes SET space_id = ?, folder_id = NULL, sync_status = 'pending', updated_at = datetime('now') WHERE space_id = ? AND cloud_id IS NULL AND deleted_at IS NULL"+ )+ .run(privateSpaceId, localSpaceId);+ const getNote = this.db.prepare("SELECT * FROM notes WHERE id = ?");+ relocated = neverSynced.map((id) => getNote.get(id));+ }+ }const ids = this.db.prepare("SELECT id FROM notes WHERE space_id = ?").all(localSpaceId)@@ -1975,29 +2067,61 @@ class DatabaseManager {.prepare("SELECT name FROM folders WHERE space_id = ?").all(localSpaceId).map((row) => row.name);- // FKs are not enforced in this DB — clean speaker rows explicitly.- this.db- .prepare(- "DELETE FROM speaker_mappings WHERE note_id IN (SELECT id FROM notes WHERE space_id = ?)"- )- .run(localSpaceId);- this.db- .prepare(- "DELETE FROM note_speaker_embeddings WHERE note_id IN (SELECT id FROM notes WHERE space_id = ?)"- )- .run(localSpaceId);+ this._deleteSpeakerRowsForNotes("SELECT id FROM notes WHERE space_id = ?", localSpaceId);this.db.prepare("DELETE FROM notes WHERE space_id = ?").run(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 };+ return { noteIds: ids, folderNames: names, relocatedNotes: relocated };})();- return { success: true, noteIds, folderNames, spaceId: localSpaceId };+ return {+ success: true,+ noteIds,+ folderNames,+ spaceId: localSpaceId,+ relocatedNotes,+ relocatedCount: relocatedNotes.length,+ relocatedTitles: relocatedNotes.slice(0, 3).map((note) => note.title),+ };} catch (error) {debugLogger.error("Error purging space", { error: error.message }, "spaces");throw error;}}+ addPendingVectorPurge(spaceId) {+ try {+ if (!this.db) throw new Error("Database not initialized");+ this.db+ .prepare("INSERT OR IGNORE INTO pending_vector_purges (space_id) VALUES (?)")+ .run(spaceId);+ return { success: true };+ } catch (error) {+ debugLogger.error("Error adding pending vector purge", { error: error.message }, "spaces");+ throw error;+ }+ }++ getPendingVectorPurges() {+ try {+ if (!this.db) throw new Error("Database not initialized");+ return this.db.prepare("SELECT space_id FROM pending_vector_purges").all();+ } catch (error) {+ debugLogger.error("Error getting pending vector purges", { error: error.message }, "spaces");+ throw error;+ }+ }++ clearPendingVectorPurge(spaceId) {+ try {+ if (!this.db) throw new Error("Database not initialized");+ this.db.prepare("DELETE FROM pending_vector_purges WHERE space_id = ?").run(spaceId);+ return { success: true };+ } catch (error) {+ debugLogger.error("Error clearing pending vector purge", { error: error.message }, "spaces");+ throw error;+ }+ }+getActions() {try {if (!this.db) throw new Error("Database not initialized");@@ -3051,9 +3175,13 @@ class DatabaseManager {try {if (!this.db) throw new Error("Database not initialized");if (spaceKind != null) {+ // 'team' also returns cloud-backed rows that just LEFT a team: their+ // scope retraction must push even when cloud backup is off (D6).+ const leftTeam =+ spaceKind === "team" ? " OR (n.left_team = 1 AND n.cloud_id IS NOT NULL)" : "";return this.db.prepare(- "SELECT n.* FROM notes n JOIN spaces s ON s.id = n.space_id WHERE n.sync_status = 'pending' AND n.deleted_at IS NULL AND s.kind = ?"+ `SELECT n.* FROM notes n JOIN spaces s ON s.id = n.space_id WHERE n.sync_status = 'pending' AND n.deleted_at IS NULL AND (s.kind = ?${leftTeam})`).all(spaceKind);}@@ -3116,6 +3244,7 @@ class DatabaseManager {diarization_enabled = COALESCE(excluded.diarization_enabled, diarization_enabled),expected_speaker_count = COALESCE(excluded.expected_speaker_count, expected_speaker_count),sync_status = 'synced',+ left_team = 0,updated_at = excluded.updated_at`);stmt.run(@@ -3152,7 +3281,9 @@ class DatabaseManager {try {if (!this.db) throw new Error("Database not initialized");this.db- .prepare("UPDATE notes SET sync_status = 'synced', cloud_id = ? WHERE id = ?")+ .prepare(+ "UPDATE notes SET sync_status = 'synced', cloud_id = ?, left_team = 0 WHERE id = ?"+ ).run(cloudId, id);return { success: true };} catch (error) {@@ -3161,6 +3292,29 @@ class DatabaseManager {}}+ // Settles a row after an async push, but only if it wasn't edited while the+ // PATCH was in flight — a mid-flight edit must stay pending so its content+ // still pushes (a blind settle would let the next pass re-PATCH the stale+ // snapshot over a teammate's newer server copy).+ markNoteSyncedIfUnchanged(id, cloudId, snapshotUpdatedAt) {+ try {+ if (!this.db) throw new Error("Database not initialized");+ const result = this.db+ .prepare(+ "UPDATE notes SET sync_status = 'synced', cloud_id = ?, left_team = 0 WHERE id = ? AND updated_at = ?"+ )+ .run(cloudId, id, snapshotUpdatedAt);+ return { success: true, changes: result.changes };+ } catch (error) {+ debugLogger.error(+ "Error marking note synced if unchanged",+ { error: error.message },+ "database"+ );+ throw error;+ }+ }+markNoteSyncError(id) {try {if (!this.db) throw new Error("Database not initialized");@@ -3175,7 +3329,10 @@ class DatabaseManager {hardDeleteNote(id) {try {if (!this.db) throw new Error("Database not initialized");- const result = this.db.prepare("DELETE FROM notes WHERE id = ?").run(id);+ const result = this.db.transaction(() => {+ this._deleteSpeakerRowsForNotes("SELECT id FROM notes WHERE id = ?", id);+ return this.db.prepare("DELETE FROM notes WHERE id = ?").run(id);+ })();return { success: result.changes > 0, id };} catch (error) {debugLogger.error("Error hard deleting note", { error: error.message }, "database");@@ -3187,9 +3344,13 @@ class DatabaseManager {try {if (!this.db) throw new Error("Database not initialized");if (spaceKind != null) {+ // 'team' also returns cloud-backed rows that just LEFT a team: their+ // scope retraction must push even when cloud backup is off (D6).+ const leftTeam =+ spaceKind === "team" ? " OR (f.left_team = 1 AND f.cloud_id IS NOT NULL)" : "";return this.db.prepare(- "SELECT f.* FROM folders f JOIN spaces s ON s.id = f.space_id WHERE f.sync_status = 'pending' AND f.deleted_at IS NULL AND s.kind = ?"+ `SELECT f.* FROM folders f JOIN spaces s ON s.id = f.space_id WHERE f.sync_status = 'pending' AND f.deleted_at IS NULL AND (s.kind = ?${leftTeam})`).all(spaceKind);}@@ -3229,6 +3390,7 @@ class DatabaseManager {.all(id).map((row) => row.id);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);return this.db.prepare("DELETE FROM folders WHERE id = ?").run(id);})();@@ -3239,6 +3401,73 @@ class DatabaseManager {}}+ // The folder's server row moved into a team this user can't access+ // (access_removed stub or a team_access_revoked push rejection). Clean+ // server-owned child notes are no longer ours to keep — the server retains+ // them; dirty or never-synced children are the only surviving content+ // (plan §7.2): they relocate to the private space with forked identities so+ // the next push re-creates them as personal rows. The folder row itself+ // survives in the private space only when it carries unpushed changes+ // (preserveFolder), renamed "name (2)" on a collision; otherwise it is+ // deleted.+ relocateRevokedFolder(id, privateSpaceId, preserveFolder = false) {+ try {+ if (!this.db) throw new Error("Database not initialized");+ const folder = this.db.prepare("SELECT * FROM folders WHERE id = ?").get(id);+ if (!folder) return { success: false, error: "Folder not found" };+ const serverOwnedChildren =+ "SELECT id FROM notes WHERE folder_id = ? AND (deleted_at IS NOT NULL OR (sync_status = 'synced' AND cloud_id IS NOT NULL))";+ const result = this.db.transaction(() => {+ const preservedIds = this.db+ .prepare(+ "SELECT id FROM notes WHERE folder_id = ? AND deleted_at IS NULL AND (sync_status != 'synced' OR cloud_id IS NULL)"+ )+ .all(id)+ .map((row) => row.id);+ const deletedNoteIds = this.db+ .prepare(serverOwnedChildren)+ .all(id)+ .map((row) => row.id);+ this._deleteSpeakerRowsForNotes(serverOwnedChildren, id);+ this.db.prepare(`DELETE FROM notes WHERE id IN (${serverOwnedChildren})`).run(id);+ const relocateNote = this.db.prepare(+ "UPDATE notes SET space_id = ?, folder_id = ?, client_note_id = ?, cloud_id = NULL, sync_status = 'pending', left_team = 0, updated_at = datetime('now') WHERE id = ?"+ );+ for (const noteId of preservedIds) {+ relocateNote.run(privateSpaceId, preserveFolder ? id : null, randomUUID(), noteId);+ }+ let preservedFolder = null;+ if (preserveFolder) {+ let name = folder.name;+ const taken = this.db.prepare(+ "SELECT 1 FROM folders WHERE name = ? AND space_id = ? AND deleted_at IS NULL AND id != ?"+ );+ for (let n = 2; taken.get(name, privateSpaceId, id); n++) {+ name = `${folder.name} (${n})`;+ }+ this.db+ .prepare(+ "UPDATE folders SET space_id = ?, name = ?, client_folder_id = ?, cloud_id = NULL, sync_status = 'pending', left_team = 0, updated_at = datetime('now') WHERE id = ?"+ )+ .run(privateSpaceId, name, randomUUID(), id);+ preservedFolder = this.db.prepare("SELECT * FROM folders WHERE id = ?").get(id);+ } else {+ this.db.prepare("DELETE FROM folders WHERE id = ?").run(id);+ }+ const getNote = this.db.prepare("SELECT * FROM notes WHERE id = ?");+ return {+ folder: preservedFolder,+ relocatedNotes: preservedIds.map((noteId) => getNote.get(noteId)),+ deletedNoteIds,+ };+ })();+ return { success: true, folderName: folder.name, ...result };+ } catch (error) {+ debugLogger.error("Error relocating revoked folder", { error: error.message }, "database");+ throw error;+ }+ }+getFolderByClientId(clientFolderId) {try {if (!this.db) throw new Error("Database not initialized");@@ -3255,6 +3484,8 @@ class DatabaseManager {upsertFolderFromCloud(cloudFolder, localSpaceId = null) {try {if (!this.db) throw new Error("Database not initialized");+ const spaceId = localSpaceId ?? this.getPrivateSpaceId();+ const updatedAt = cloudFolder.updated_at || cloudFolder.created_at;const stmt = this.db.prepare(`INSERT INTO folders (client_folder_id, cloud_id, name, is_default, sort_order, space_id, sync_status, created_at, updated_at)VALUES (?, ?, ?, ?, ?, ?, 'synced', ?, ?)@@ -3264,18 +3495,51 @@ class DatabaseManager {sort_order = excluded.sort_order,space_id = excluded.space_id,sync_status = 'synced',+ left_team = 0,updated_at = excluded.updated_at`);- stmt.run(- cloudFolder.client_folder_id,- cloudFolder.id,- cloudFolder.name,- cloudFolder.is_default ? 1 : 0,- cloudFolder.sort_order || 0,- localSpaceId ?? this.getPrivateSpaceId(),- cloudFolder.created_at,- cloudFolder.updated_at || cloudFolder.created_at- );+ try {+ stmt.run(+ cloudFolder.client_folder_id,+ cloudFolder.id,+ cloudFolder.name,+ cloudFolder.is_default ? 1 : 0,+ cloudFolder.sort_order || 0,+ spaceId,+ cloudFolder.created_at,+ updatedAt+ );+ } catch (err) {+ // A live same-named folder already exists in this space (partial unique+ // index idx_folders_space_name is a different conflict target than the+ // client_folder_id upsert). Converge on the existing folder by adopting+ // the cloud row's identity instead of wedging the pull.+ if (!err.message.includes("folders.space_id, folders.name")) throw err;+ const existing = this.db+ .prepare("SELECT id FROM folders WHERE space_id = ? AND name = ? AND deleted_at IS NULL")+ .get(spaceId, cloudFolder.name);+ if (!existing) throw err;+ this.db.transaction(() => {+ const holder = this.db+ .prepare("SELECT id FROM folders WHERE client_folder_id = ? AND id != ?")+ .get(cloudFolder.client_folder_id, existing.id);+ // A different local row already tracked this cloud folder (rename+ // collision via the DO UPDATE branch) — fork it so the winner can+ // take the cloud identity without violating the client id index.+ if (holder) this.forkFolderIdentity(holder.id);+ this.db+ .prepare(+ "UPDATE folders SET client_folder_id = ?, cloud_id = ?, sort_order = ?, sync_status = 'synced', left_team = 0, updated_at = ? WHERE id = ?"+ )+ .run(+ cloudFolder.client_folder_id,+ cloudFolder.id,+ cloudFolder.sort_order || 0,+ updatedAt,+ existing.id+ );+ })();+ }return this.db.prepare("SELECT * FROM folders WHERE client_folder_id = ?").get(cloudFolder.client_folder_id);@@ -3289,7 +3553,9 @@ class DatabaseManager {try {if (!this.db) throw new Error("Database not initialized");this.db- .prepare("UPDATE folders SET sync_status = 'synced', cloud_id = ? WHERE id = ?")+ .prepare(+ "UPDATE folders SET sync_status = 'synced', cloud_id = ?, left_team = 0 WHERE id = ?"+ ).run(cloudId, id);return { success: true };} catch (error) {@@ -3298,6 +3564,29 @@ class DatabaseManager {}}+ // Folder twin of markNoteSyncedIfUnchanged: settles a row after an async+ // PATCH only if it wasn't edited while the PATCH was in flight — a blind+ // settle would mark a newer local rename 'synced', letting the next pull's+ // LWW (server timestamps run later) silently revert it.+ markFolderSyncedIfUnchanged(id, cloudId, snapshotUpdatedAt) {+ try {+ if (!this.db) throw new Error("Database not initialized");+ const result = this.db+ .prepare(+ "UPDATE folders SET sync_status = 'synced', cloud_id = ?, left_team = 0 WHERE id = ? AND updated_at = ?"+ )+ .run(cloudId, id, snapshotUpdatedAt);+ return { success: true, changes: result.changes };+ } catch (error) {+ debugLogger.error(+ "Error marking folder synced if unchanged",+ { error: error.message },+ "database"+ );+ throw error;+ }+ }+// A folder whose server row moved into a scope this user can no longer// write gets a fresh identity, so the next push creates it as a new// personal folder instead of PATCHing the inaccessible row forever.@@ -3306,7 +3595,7 @@ class DatabaseManager {if (!this.db) throw new Error("Database not initialized");const result = this.db.prepare(- "UPDATE folders SET client_folder_id = ?, cloud_id = NULL, sync_status = 'pending' WHERE id = ?"+ "UPDATE folders SET client_folder_id = ?, cloud_id = NULL, sync_status = 'pending', left_team = 0 WHERE id = ?").run(randomUUID(), id);return { success: result.changes > 0 };@@ -3321,7 +3610,7 @@ class DatabaseManager {if (!this.db) throw new Error("Database not initialized");this.db.prepare(- "UPDATE folders SET client_folder_id = ?, cloud_id = ?, sync_status = 'synced', updated_at = COALESCE(?, updated_at) WHERE id = ?"+ "UPDATE folders SET client_folder_id = ?, cloud_id = ?, sync_status = 'synced', left_team = 0, updated_at = COALESCE(?, updated_at) WHERE id = ?").run(clientFolderId, cloudId, updatedAt ?? null, id);return { success: true };diff --git a/src/helpers/ipcHandlers.js b/src/helpers/ipcHandlers.jsindex 172cea108..226fbf0fe 100644--- a/src/helpers/ipcHandlers.js+++ b/src/helpers/ipcHandlers.js@@ -451,6 +451,32 @@ class IPCHandlers {});}+ // Space vector purges are persisted (pending_vector_purges) so a purge that+ // lands while Qdrant is booting or down is retried once the index is ready.+ drainPendingVectorPurges() {+ setImmediate(async () => {+ const vectorIndex = require("./vectorIndex");+ if (!vectorIndex.isReady()) return;+ for (const { space_id } of this.databaseManager.getPendingVectorPurges()) {+ if (await vectorIndex.deleteBySpace(space_id)) {+ this.databaseManager.clearPendingVectorPurge(space_id);+ }+ }+ });+ }++ _mirrorDeleteFolderIfUnshared(folderName) {+ if (!this._noteFilesEnabled) return;+ // Folder names are only unique per space — a live same-named folder in+ // another space shares the mirror directory, so leave it on disk.+ const stillLive = this.databaseManager.db+ .prepare("SELECT 1 FROM folders WHERE name = ? AND deleted_at IS NULL")+ .get(folderName);+ if (stillLive) return;+ const markdownMirror = require("./markdownMirror");+ markdownMirror.deleteFolder(folderName);+ }+_asyncMirrorWrite(note) {if (!this._noteFilesEnabled) {debugLogger.debug(@@ -1206,11 +1232,12 @@ class IPCHandlers {const notes = this.databaseManager.getNotes(null, 100000);let done = 0;- await vectorIndex.reindexAll(notes, (completed, total) => {+ const { failed } = await vectorIndex.reindexAll(notes, (completed, total) => {done = completed;this.broadcastToWindows("semantic-reindex-progress", { done: completed, total });});- return { success: true, indexed: done };+ // Report failed batches so callers only latch their done-flag on a clean pass.+ return { success: failed === 0, indexed: done - failed };});ipcMain.handle("db-update-note-cloud-id", async (event, id, cloudId) => {@@ -1252,10 +1279,7 @@ class IPCHandlers {}setImmediate(() => {this.broadcastToWindows("folder-deleted", { id });- if (this._noteFilesEnabled && folderName) {- const markdownMirror = require("./markdownMirror");- markdownMirror.deleteFolder(folderName);- }+ if (folderName) this._mirrorDeleteFolderIfUnshared(folderName);});}return result;@@ -1316,21 +1340,19 @@ class IPCHandlers {ipcMain.handle("db-purge-space", async (event, id) => {const result = this.databaseManager.purgeSpace(id);if (result?.success) {- setImmediate(() => {- const vectorIndex = require("./vectorIndex");- if (!vectorIndex.isReady()) return;- vectorIndex.deleteBySpace(result.spaceId).catch(() => {});- });+ this.databaseManager.addPendingVectorPurge(result.spaceId);+ this.drainPendingVectorPurges();+ for (const note of result.relocatedNotes ?? []) {+ this._asyncVectorUpsert(note);+ this._asyncMirrorWrite(note);+ }for (const noteId of result.noteIds ?? []) {this._asyncMirrorDelete(noteId);}setImmediate(() => {this.broadcastToWindows("space-purged", { spaceId: result.spaceId });- if (this._noteFilesEnabled) {- const markdownMirror = require("./markdownMirror");- for (const folderName of result.folderNames ?? []) {- markdownMirror.deleteFolder(folderName);- }+ for (const folderName of result.folderNames ?? []) {+ this._mirrorDeleteFolderIfUnshared(folderName);}});}@@ -1489,12 +1511,17 @@ class IPCHandlers {ipcMain.handle("db-get-note-by-client-id", (_, clientNoteId) =>this.databaseManager.getNoteByClientId(clientNoteId));- ipcMain.handle("db-upsert-note-from-cloud", (_, cloudNote, localFolderId, localSpaceId) =>- this.databaseManager.upsertNoteFromCloud(cloudNote, localFolderId, localSpaceId)- );+ ipcMain.handle("db-upsert-note-from-cloud", (_, cloudNote, localFolderId, localSpaceId) => {+ const note = this.databaseManager.upsertNoteFromCloud(cloudNote, localFolderId, localSpaceId);+ if (note) setImmediate(() => this.broadcastToWindows("note-synced", note));+ return note;+ });ipcMain.handle("db-mark-note-synced", (_, id, cloudId) =>this.databaseManager.markNoteSynced(id, cloudId));+ ipcMain.handle("db-mark-note-synced-if-unchanged", (_, id, cloudId, snapshotUpdatedAt) =>+ this.databaseManager.markNoteSyncedIfUnchanged(id, cloudId, snapshotUpdatedAt)+ );ipcMain.handle("db-mark-note-sync-error", (_, id) =>this.databaseManager.markNoteSyncError(id));@@ -1515,12 +1542,17 @@ class IPCHandlers {ipcMain.handle("db-get-folder-by-client-id", (_, clientFolderId) =>this.databaseManager.getFolderByClientId(clientFolderId));- ipcMain.handle("db-upsert-folder-from-cloud", (_, cloudFolder, localSpaceId) =>- this.databaseManager.upsertFolderFromCloud(cloudFolder, localSpaceId)- );+ ipcMain.handle("db-upsert-folder-from-cloud", (_, cloudFolder, localSpaceId) => {+ const folder = this.databaseManager.upsertFolderFromCloud(cloudFolder, localSpaceId);+ if (folder) setImmediate(() => this.broadcastToWindows("folder-synced", folder));+ return folder;+ });ipcMain.handle("db-mark-folder-synced", (_, id, cloudId) =>this.databaseManager.markFolderSynced(id, cloudId));+ ipcMain.handle("db-mark-folder-synced-if-unchanged", (_, id, cloudId, snapshotUpdatedAt) =>+ this.databaseManager.markFolderSyncedIfUnchanged(id, cloudId, snapshotUpdatedAt)+ );ipcMain.handle("db-adopt-folder-identity", (_, id, clientFolderId, cloudId, updatedAt) =>this.databaseManager.adoptFolderIdentity(id, clientFolderId, cloudId, updatedAt));@@ -1539,15 +1571,49 @@ class IPCHandlers {}setImmediate(() => {this.broadcastToWindows("folder-deleted", { id });- if (this._noteFilesEnabled && result.name) {- const markdownMirror = require("./markdownMirror");- markdownMirror.deleteFolder(result.name);+ if (result.name) this._mirrorDeleteFolderIfUnshared(result.name);+ });+ }+ return result;+ });+ ipcMain.handle("db-relocate-revoked-folder", (_, id, privateSpaceId, preserveFolder) => {+ const result = this.databaseManager.relocateRevokedFolder(id, privateSpaceId, preserveFolder);+ if (result?.success) {+ // Qdrant payloads carry space_id and the markdown mirror files by+ // folder — refresh relocated notes, drop the server-owned ones.+ for (const note of result.relocatedNotes ?? []) {+ this._asyncVectorUpsert(note);+ this._asyncMirrorWrite(note);+ }+ for (const noteId of result.deletedNoteIds ?? []) {+ this._asyncVectorDelete(noteId);+ this._asyncMirrorDelete(noteId);+ }+ setImmediate(() => {+ if (result.folder) this.broadcastToWindows("folder-synced", result.folder);+ else this.broadcastToWindows("folder-deleted", { id });+ for (const note of result.relocatedNotes ?? []) {+ this.broadcastToWindows("note-updated", note);+ }+ for (const noteId of result.deletedNoteIds ?? []) {+ this.broadcastToWindows("note-deleted", { id: noteId });+ }+ const folderGone = !result.folder || result.folder.name !== result.folderName;+ if (result.folderName && folderGone) {+ this._mirrorDeleteFolderIfUnshared(result.folderName);}});}return result;});+ // Renderer-side sync events (conflicts, revocation toasts, …) happen in+ // whichever window ran the pass — rebroadcast them to ALL windows.+ ipcMain.handle("broadcast-sync-event", (_, name, payload) => {+ this.broadcastToWindows("sync-event", { name, payload });+ return { success: true };+ });+// Spaces syncipcMain.handle("db-get-space-by-cloud-team-id", (_, cloudTeamId) =>this.databaseManager.getSpaceByCloudTeamId(cloudTeamId)diff --git a/src/helpers/vectorIndex.js b/src/helpers/vectorIndex.jsindex 1f26242f2..e24e7de04 100644--- a/src/helpers/vectorIndex.js+++ b/src/helpers/vectorIndex.js@@ -52,13 +52,15 @@ class VectorIndex {}async deleteBySpace(spaceId) {- if (!this.client) return;+ if (!this.client) return false;try {await this.client.delete(this.collectionName, {filter: { must: [{ key: "space_id", match: { value: spaceId } }] },});+ return true;} catch (err) {debugLogger.debug("Vector index space delete failed", { spaceId, error: err.message });+ return false;}}@@ -79,8 +81,9 @@ class VectorIndex {}async reindexAll(notes, onProgress) {- if (!this.client) return;+ if (!this.client) return { failed: notes.length };const BATCH_SIZE = 50;+ let failed = 0;for (let i = 0; i < notes.length; i += BATCH_SIZE) {const batch = notes.slice(i, i + BATCH_SIZE);const texts = batch.map((n) =>@@ -95,10 +98,12 @@ class VectorIndex {}));await this.client.upsert(this.collectionName, { points });} catch (err) {+ failed += batch.length;debugLogger.debug("Vector reindex batch failed", { offset: i, error: err.message });}if (onProgress) onProgress(Math.min(i + BATCH_SIZE, notes.length), notes.length);}+ return { failed };}async ensureConversationChunksCollection() {diff --git a/src/locales/de/translation.json b/src/locales/de/translation.jsonindex b33138f69..80c2045af 100644--- a/src/locales/de/translation.json+++ b/src/locales/de/translation.json@@ -2397,12 +2397,14 @@"confirmMoveInTitle": "Nach {{space}} verschieben?","confirmMoveIn": "Alle in {{space}} können diese Notiz sehen und bearbeiten.","confirmMoveInFolder": "Alle in {{space}} können diesen Ordner und seine Notizen sehen und bearbeiten.",+ "confirmMoveInShared": "Der öffentliche Link wird deaktiviert.","confirmMoveOutTitle": "Aus {{space}} verschieben?","confirmMoveOut": "Mitglieder von {{space}} verlieren den Zugriff auf diese Notiz.","confirmMoveOutFolder": "Mitglieder von {{space}} verlieren den Zugriff auf diesen Ordner und seine Notizen.","moved": "„{{title}}“ nach {{target}} verschoben","couldNotMove": "Ordner konnte nicht verschoben werden","couldNotMoveNote": "Notiz konnte nicht verschoben werden",+ "shareRevokeFailed": "Öffentlicher Link konnte nicht deaktiviert werden","folderNameTaken": "„{{name}}“ konnte nicht verschoben werden – dort existiert bereits ein Ordner mit diesem Namen","undo": "Rückgängig","emptySpace": "Noch keine Notizen. Notizen hier sind für alle in {{space}} sichtbar.",@@ -2427,6 +2429,7 @@"leave": "Bereich verlassen","leaveConfirm": "{{space}} verlassen?","leaveConfirmDescription": "Sie verlieren den Zugriff auf alle Notizen in diesem Bereich.",+ "implicitAdminCannotLeave": "Workspace-Inhaber und -Administratoren haben Zugriff auf alle Team-Bereiche und können sie nicht verlassen.","inviteFooter": "{{email}} in den Workspace einladen…","empty": "Noch niemand hinzugefügt"},diff --git a/src/locales/en/translation.json b/src/locales/en/translation.jsonindex f9b1eeb73..a2c542305 100644--- a/src/locales/en/translation.json+++ b/src/locales/en/translation.json@@ -2397,12 +2397,14 @@"confirmMoveInTitle": "Move to {{space}}?","confirmMoveIn": "Everyone in {{space}} will be able to view and edit this note.","confirmMoveInFolder": "Everyone in {{space}} will be able to view and edit this folder and its notes.",+ "confirmMoveInShared": "Its public link will be disabled.","confirmMoveOutTitle": "Move out of {{space}}?","confirmMoveOut": "Members of {{space}} will lose access to this note.","confirmMoveOutFolder": "Members of {{space}} will lose access to this folder and its notes.","moved": "Moved “{{title}}” to {{target}}","couldNotMove": "Couldn't move folder","couldNotMoveNote": "Couldn't move note",+ "shareRevokeFailed": "Couldn't disable the public link","folderNameTaken": "Couldn't move “{{name}}” — a folder with that name already exists there","undo": "Undo","emptySpace": "No notes yet. Notes here are visible to everyone in {{space}}.",@@ -2427,6 +2429,7 @@"leave": "Leave space","leaveConfirm": "Leave {{space}}?","leaveConfirmDescription": "You'll lose access to all notes in this space.",+ "implicitAdminCannotLeave": "Workspace owners and admins have access to every team space and can't leave it.","inviteFooter": "Invite {{email}} to workspace…","empty": "No one has been added yet"},diff --git a/src/locales/es/translation.json b/src/locales/es/translation.jsonindex 053a1cd2d..bf6f734f0 100644--- a/src/locales/es/translation.json+++ b/src/locales/es/translation.json@@ -2239,12 +2239,14 @@"confirmMoveInTitle": "¿Mover a {{space}}?","confirmMoveIn": "Todos en {{space}} podrán ver y editar esta nota.","confirmMoveInFolder": "Todos en {{space}} podrán ver y editar esta carpeta y sus notas.",+ "confirmMoveInShared": "Su enlace público se desactivará.","confirmMoveOutTitle": "¿Sacar de {{space}}?","confirmMoveOut": "Los miembros de {{space}} perderán el acceso a esta nota.","confirmMoveOutFolder": "Los miembros de {{space}} perderán el acceso a esta carpeta y sus notas.","moved": "«{{title}}» se movió a {{target}}","couldNotMove": "No se pudo mover la carpeta","couldNotMoveNote": "No se pudo mover la nota",+ "shareRevokeFailed": "No se pudo desactivar el enlace público","folderNameTaken": "No se pudo mover «{{name}}»: ya existe una carpeta con ese nombre allí","undo": "Deshacer","emptySpace": "Aún no hay notas. Las notas aquí son visibles para todos en {{space}}.",@@ -2269,6 +2271,7 @@"leave": "Salir del espacio","leaveConfirm": "¿Salir de {{space}}?","leaveConfirmDescription": "Perderás el acceso a todas las notas de este espacio.",+ "implicitAdminCannotLeave": "Los propietarios y administradores del espacio de trabajo tienen acceso a todos los espacios de equipo y no pueden salir de ellos.","inviteFooter": "Invitar a {{email}} al espacio de trabajo…","empty": "Aún no se ha añadido a nadie"},diff --git a/src/locales/fr/translation.json b/src/locales/fr/translation.jsonindex f4d046d13..629981ffe 100644--- a/src/locales/fr/translation.json+++ b/src/locales/fr/translation.json@@ -2397,12 +2397,14 @@"confirmMoveInTitle": "Déplacer vers {{space}} ?","confirmMoveIn": "Tous les membres de {{space}} pourront voir et modifier cette note.","confirmMoveInFolder": "Tous les membres de {{space}} pourront voir et modifier ce dossier et ses notes.",+ "confirmMoveInShared": "Son lien public sera désactivé.","confirmMoveOutTitle": "Retirer de {{space}} ?","confirmMoveOut": "Les membres de {{space}} perdront l'accès à cette note.","confirmMoveOutFolder": "Les membres de {{space}} perdront l'accès à ce dossier et à ses notes.","moved": "« {{title}} » déplacée vers {{target}}","couldNotMove": "Impossible de déplacer le dossier","couldNotMoveNote": "Impossible de déplacer la note",+ "shareRevokeFailed": "Impossible de désactiver le lien public","folderNameTaken": "Impossible de déplacer « {{name}} » : un dossier portant ce nom existe déjà à cet emplacement","undo": "Annuler","emptySpace": "Aucune note pour le moment. Les notes ici sont visibles par tous les membres de {{space}}.",@@ -2427,6 +2429,7 @@"leave": "Quitter l'espace","leaveConfirm": "Quitter {{space}} ?","leaveConfirmDescription": "Vous perdrez l'accès à toutes les notes de cet espace.",+ "implicitAdminCannotLeave": "Les propriétaires et administrateurs de l'espace de travail ont accès à tous les espaces d'équipe et ne peuvent pas les quitter.","inviteFooter": "Inviter {{email}} dans l'espace de travail…","empty": "Personne n'a encore été ajouté"},diff --git a/src/locales/it/translation.json b/src/locales/it/translation.jsonindex 37758bee1..ed3838e04 100644--- a/src/locales/it/translation.json+++ b/src/locales/it/translation.json@@ -2191,12 +2191,14 @@"confirmMoveInTitle": "Spostare in {{space}}?","confirmMoveIn": "Tutti in {{space}} potranno vedere e modificare questa nota.","confirmMoveInFolder": "Tutti in {{space}} potranno vedere e modificare questa cartella e le sue note.",+ "confirmMoveInShared": "Il suo link pubblico verrà disattivato.","confirmMoveOutTitle": "Spostare fuori da {{space}}?","confirmMoveOut": "I membri di {{space}} perderanno l'accesso a questa nota.","confirmMoveOutFolder": "I membri di {{space}} perderanno l'accesso a questa cartella e alle sue note.","moved": "“{{title}}” spostata in {{target}}","couldNotMove": "Impossibile spostare la cartella","couldNotMoveNote": "Impossibile spostare la nota",+ "shareRevokeFailed": "Impossibile disattivare il link pubblico","folderNameTaken": "Impossibile spostare “{{name}}”: esiste già una cartella con questo nome in quella posizione","undo": "Annulla","emptySpace": "Ancora nessuna nota. Le note qui sono visibili a tutti in {{space}}.",@@ -2221,6 +2223,7 @@"leave": "Abbandona lo spazio","leaveConfirm": "Abbandonare {{space}}?","leaveConfirmDescription": "Perderai l'accesso a tutte le note di questo spazio.",+ "implicitAdminCannotLeave": "I proprietari e gli amministratori dell'area di lavoro hanno accesso a tutti gli spazi del team e non possono abbandonarli.","inviteFooter": "Invita {{email}} nell'area di lavoro…","empty": "Nessuno è stato ancora aggiunto"},diff --git a/src/locales/ja/translation.json b/src/locales/ja/translation.jsonindex b2dc7f64b..622843534 100644--- a/src/locales/ja/translation.json+++ b/src/locales/ja/translation.json@@ -2119,12 +2119,14 @@"confirmMoveInTitle": "{{space}}に移動しますか?","confirmMoveIn": "{{space}}の全員がこのノートを表示・編集できるようになります。","confirmMoveInFolder": "{{space}}の全員がこのフォルダとそのノートを表示・編集できるようになります。",+ "confirmMoveInShared": "公開リンクは無効になります。","confirmMoveOutTitle": "{{space}}から移動しますか?","confirmMoveOut": "{{space}}のメンバーはこのノートにアクセスできなくなります。","confirmMoveOutFolder": "{{space}}のメンバーはこのフォルダとそのノートにアクセスできなくなります。","moved": "「{{title}}」を{{target}}に移動しました","couldNotMove": "フォルダを移動できませんでした","couldNotMoveNote": "ノートを移動できませんでした",+ "shareRevokeFailed": "公開リンクを無効にできませんでした","folderNameTaken": "「{{name}}」を移動できませんでした。同じ名前のフォルダが既に存在します","undo": "元に戻す","emptySpace": "まだノートがありません。ここのノートは{{space}}の全員に表示されます。",@@ -2149,6 +2151,7 @@"leave": "スペースから退出","leaveConfirm": "{{space}} から退出しますか?","leaveConfirmDescription": "このスペースのすべてのノートにアクセスできなくなります。",+ "implicitAdminCannotLeave": "ワークスペースのオーナーと管理者はすべてのチームスペースにアクセスできるため、退出できません。","inviteFooter": "{{email}} をワークスペースに招待…","empty": "まだ誰も追加されていません"},diff --git a/src/locales/pt/translation.json b/src/locales/pt/translation.jsonindex a053433a4..9d69e721e 100644--- a/src/locales/pt/translation.json+++ b/src/locales/pt/translation.json@@ -2191,12 +2191,14 @@"confirmMoveInTitle": "Mover para {{space}}?","confirmMoveIn": "Todos em {{space}} poderão ver e editar esta nota.","confirmMoveInFolder": "Todos em {{space}} poderão ver e editar esta pasta e suas notas.",+ "confirmMoveInShared": "O link público será desativado.","confirmMoveOutTitle": "Mover para fora de {{space}}?","confirmMoveOut": "Os membros de {{space}} perderão o acesso a esta nota.","confirmMoveOutFolder": "Os membros de {{space}} perderão o acesso a esta pasta e suas notas.","moved": "“{{title}}” movida para {{target}}","couldNotMove": "Não foi possível mover a pasta","couldNotMoveNote": "Não foi possível mover a nota",+ "shareRevokeFailed": "Não foi possível desativar o link público","folderNameTaken": "Não foi possível mover “{{name}}”: já existe uma pasta com esse nome nesse local","undo": "Desfazer","emptySpace": "Nenhuma nota ainda. As notas aqui são visíveis para todos em {{space}}.",@@ -2221,6 +2223,7 @@"leave": "Sair do espaço","leaveConfirm": "Sair de {{space}}?","leaveConfirmDescription": "Você perderá o acesso a todas as notas deste espaço.",+ "implicitAdminCannotLeave": "Proprietários e administradores do espaço de trabalho têm acesso a todos os espaços de equipe e não podem sair deles.","inviteFooter": "Convidar {{email}} para o espaço de trabalho…","empty": "Ninguém foi adicionado ainda"},diff --git a/src/locales/ru/translation.json b/src/locales/ru/translation.jsonindex 58239655d..5bd52bade 100644--- a/src/locales/ru/translation.json+++ b/src/locales/ru/translation.json@@ -2193,12 +2193,14 @@"confirmMoveInTitle": "Переместить в {{space}}?","confirmMoveIn": "Все в {{space}} смогут просматривать и редактировать эту заметку.","confirmMoveInFolder": "Все в {{space}} смогут просматривать и редактировать эту папку и её заметки.",+ "confirmMoveInShared": "Публичная ссылка будет отключена.","confirmMoveOutTitle": "Переместить из {{space}}?","confirmMoveOut": "Участники {{space}} потеряют доступ к этой заметке.","confirmMoveOutFolder": "Участники {{space}} потеряют доступ к этой папке и её заметкам.","moved": "«{{title}}» перемещено в {{target}}","couldNotMove": "Не удалось переместить папку","couldNotMoveNote": "Не удалось переместить заметку",+ "shareRevokeFailed": "Не удалось отключить публичную ссылку","folderNameTaken": "Не удалось переместить «{{name}}» — там уже есть папка с таким именем","undo": "Отменить","emptySpace": "Пока нет заметок. Заметки здесь видны всем в {{space}}.",@@ -2225,6 +2227,7 @@"leave": "Покинуть пространство","leaveConfirm": "Покинуть {{space}}?","leaveConfirmDescription": "Вы потеряете доступ ко всем заметкам этого пространства.",+ "implicitAdminCannotLeave": "Владельцы и администраторы рабочего пространства имеют доступ ко всем командным пространствам и не могут их покинуть.","inviteFooter": "Пригласить {{email}} в рабочее пространство…","empty": "Пока никто не добавлен"},diff --git a/src/locales/zh-CN/translation.json b/src/locales/zh-CN/translation.jsonindex 59fe09488..c1307b683 100644--- a/src/locales/zh-CN/translation.json+++ b/src/locales/zh-CN/translation.json@@ -1209,7 +1209,12 @@"annualEquivalent": "$16.67","includesPrefix": "所有 Pro 功能 +","badge": "最受欢迎",- "features": ["无限会议录制", "代理模式", "与您的数据对话", "优先支持"],+ "features": [+ "无限会议录制",+ "代理模式",+ "与您的数据对话",+ "优先支持"+ ],"cta": "开始使用","switchToAnnual": "切换为年付"},@@ -2186,12 +2191,14 @@"confirmMoveInTitle": "移动到 {{space}}?","confirmMoveIn": "{{space}} 中的所有人都将能查看和编辑此笔记。","confirmMoveInFolder": "{{space}} 中的所有人都将能查看和编辑此文件夹及其笔记。",+ "confirmMoveInShared": "其公开链接将被停用。","confirmMoveOutTitle": "移出 {{space}}?","confirmMoveOut": "{{space}} 的成员将无法再访问此笔记。","confirmMoveOutFolder": "{{space}} 的成员将无法再访问此文件夹及其笔记。","moved": "已将“{{title}}”移动到 {{target}}","couldNotMove": "无法移动文件夹","couldNotMoveNote": "无法移动笔记",+ "shareRevokeFailed": "无法停用公开链接","folderNameTaken": "无法移动“{{name}}”:该位置已存在同名文件夹","undo": "撤销","emptySpace": "还没有笔记。这里的笔记对 {{space}} 中的所有人可见。",@@ -2216,6 +2223,7 @@"leave": "退出空间","leaveConfirm": "退出 {{space}}?","leaveConfirmDescription": "你将无法再访问此空间的所有笔记。",+ "implicitAdminCannotLeave": "工作区所有者和管理员可以访问所有团队空间,无法退出。","inviteFooter": "邀请 {{email}} 加入工作区…","empty": "尚未添加任何成员"},diff --git a/src/locales/zh-TW/translation.json b/src/locales/zh-TW/translation.jsonindex 134a264b3..9fa2f256f 100644--- a/src/locales/zh-TW/translation.json+++ b/src/locales/zh-TW/translation.json@@ -1209,7 +1209,12 @@"annualEquivalent": "$16.67","includesPrefix": "所有 Pro 功能 +","badge": "最熱門",- "features": ["無限會議錄製", "代理模式", "與您的資料對話", "優先支援"],+ "features": [+ "無限會議錄製",+ "代理模式",+ "與您的資料對話",+ "優先支援"+ ],"cta": "開始使用","switchToAnnual": "切換為年付"},@@ -2186,12 +2191,14 @@"confirmMoveInTitle": "移動到 {{space}}?","confirmMoveIn": "{{space}} 中的所有人都將能檢視和編輯這則筆記。","confirmMoveInFolder": "{{space}} 中的所有人都將能檢視和編輯這個資料夾及其筆記。",+ "confirmMoveInShared": "其公開連結將被停用。","confirmMoveOutTitle": "移出 {{space}}?","confirmMoveOut": "{{space}} 的成員將無法再存取這則筆記。","confirmMoveOutFolder": "{{space}} 的成員將無法再存取這個資料夾及其筆記。","moved": "已將「{{title}}」移動到 {{target}}","couldNotMove": "無法移動資料夾","couldNotMoveNote": "無法移動筆記",+ "shareRevokeFailed": "無法停用公開連結","folderNameTaken": "無法移動「{{name}}」:該位置已存在同名資料夾","undo": "復原","emptySpace": "還沒有筆記。這裡的筆記對 {{space}} 中的所有人可見。",@@ -2216,6 +2223,7 @@"leave": "退出空間","leaveConfirm": "要退出 {{space}} 嗎?","leaveConfirmDescription": "你將無法再存取此空間的所有筆記。",+ "implicitAdminCannotLeave": "工作區擁有者和管理員可以存取所有團隊空間,無法退出。","inviteFooter": "邀請 {{email}} 加入工作區…","empty": "尚未新增任何成員"},diff --git a/src/services/SyncService.ts b/src/services/SyncService.tsindex 0967ba53a..b28b73566 100644--- a/src/services/SyncService.ts+++ b/src/services/SyncService.ts@@ -5,7 +5,7 @@ import type {TranscriptionItem,ConversationPreview,} from "../types/electron";-import { NotesService } from "./NotesService.js";+import { NotesService, type CloudNote } from "./NotesService.js";import { ConversationsService } from "./ConversationsService.js";import { FoldersService } from "./FoldersService.js";import { TeamsService, type MyTeam } from "./TeamsService.js";@@ -75,6 +75,44 @@ function normalizeTimestamp(value: string | null | undefined): string {return (/\.\d+$/.test(iso) ? iso : `${iso}.000`) + "Z";}+// Cross-window guard against a space purge racing an in-flight pull: every+// purge initiator records the cloud team id here, and pull/upsert paths park+// rows for recently purged teams instead of resurrecting them as orphaned+// local rows nothing can ever clean up. Entries are pruned once a spaces pass+// confirms the team is gone from /api/me/teams, or after a TTL so a failed+// leave cannot hide a still-live team forever.+const PURGED_TEAM_GUARD_KEY = "purgedTeamIds";+const PURGED_TEAM_GUARD_TTL_MS = 15 * 60 * 1000;++function readPurgedTeamIds(): Record<string, number> {+ try {+ const raw = localStorage.getItem(PURGED_TEAM_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_TEAM_GUARD_TTL_MS)+ );+ } catch {+ return {};+ }+}++// Call BEFORE purgeSpace, from every purge path (sync revocation, sign-out,+// and the UI's leave/delete-space flows).+export function markTeamSpacePurged(cloudTeamId: string): void {+ localStorage.setItem(+ PURGED_TEAM_GUARD_KEY,+ JSON.stringify({ ...readPurgedTeamIds(), [cloudTeamId]: Date.now() })+ );+}++function prunePurgedTeamIds(liveCloudTeamIds: Set<string>): void {+ const kept = Object.fromEntries(+ Object.entries(readPurgedTeamIds()).filter(([id]) => liveCloudTeamIds.has(id))+ );+ localStorage.setItem(PURGED_TEAM_GUARD_KEY, JSON.stringify(kept));+}+class SyncService {private syncing = false;private syncAllPending = false;@@ -127,6 +165,7 @@ class SyncService {for (const space of spaces) {if (space.kind !== "team") continue;try {+ if (space.cloud_team_id) markTeamSpacePurged(space.cloud_team_id);await window.electronAPI.purgeSpace?.(space.id);} catch (err) {console.error(`Purging space ${space.id} on sign-out failed:`, err);@@ -139,6 +178,9 @@ class SyncService {localStorage.removeItem("teamSpacesCapability.probedAt");localStorage.removeItem("lastSyncedAt.notes.team");localStorage.removeItem("lastSyncedAt.folders.team");+ // The guard protected any pass still in flight during the purge; drop it+ // so the next account (possibly a member of the same teams) starts clean.+ localStorage.removeItem(PURGED_TEAM_GUARD_KEY);}// lastSyncedAt is written only when a syncAll() pass completes, and@@ -298,7 +340,10 @@ class SyncService {if (!note) return;if (!note.is_shared) {const ctx = await this.buildSpaceContext();- if (ctx.byId.get(note.space_id)?.kind !== "team") return;+ // A note that just left a team still owes its scope retraction (D6):+ // the server row stays visible to teammates until the PATCH lands.+ const leftTeam = !!note.left_team && !!note.cloud_id;+ if (ctx.byId.get(note.space_id)?.kind !== "team" && !leftTeam) return;}return this.pushNote(entityId);}@@ -318,6 +363,11 @@ class SyncService {const folders = (await window.electronAPI.getFolders?.()) ?? [];const folder = folders.find((f) => f.id === id);if (!folder) return;+ if (folder.left_team && folder.cloud_id && !this.hasTeamSpacesCapability()) {+ // The retraction PATCH needs team-scope support; without it the push+ // would settle the row and erase the pending scope change.+ return;+ }const ctx = await this.buildSpaceContext();const scope = this.pushScopeFields(ctx.byId.get(folder.space_id));@@ -333,6 +383,16 @@ class SyncService {sort_order: folder.sort_order,...scope,});+ // Settle like the batch path: a delivered row left pending would both+ // block its notes' pushes (blockedFolderIds) and re-PATCH stale state+ // over a teammate's newer rename on the next pass. Guarded settle: a+ // rename landing mid-flight stays pending so it still pushes (a blind+ // settle would let the next pull's LWW revert it).+ await window.electronAPI.markFolderSyncedIfUnchanged?.(+ folder.id,+ folder.cloud_id,+ folder.updated_at+ );} catch (err) {if (!isFolderNameTakenError(err)) throw err;this.dispatchFolderNameTaken(folder.name);@@ -345,7 +405,19 @@ class SyncService {sort_order: folder.sort_order,...scope,});- await window.electronAPI.markFolderSynced?.(folder.id, cloud.id);+ // On a same-name collision the API returns the WINNER's existing row;+ // adopt its identity (as the batch path does) so later pulls of that+ // row match this folder instead of inserting a colliding duplicate.+ if (cloud.client_folder_id && cloud.client_folder_id !== folder.client_folder_id) {+ await window.electronAPI.adoptFolderIdentity?.(+ folder.id,+ cloud.client_folder_id,+ cloud.id,+ cloud.updated_at+ );+ } else {+ await window.electronAPI.markFolderSynced?.(folder.id, cloud.id);+ }}}@@ -376,18 +448,39 @@ class SyncService {const note = await window.electronAPI.getNote?.(id);if (!note) return;- const folderMap = await this.buildLocalToCloudFolderMap();+ const { localToCloud, blockedFolderIds } = await this.buildLocalToCloudFolderMap();+ if (note.folder_id && blockedFolderIds.has(note.folder_id)) {+ // The folder's own changes haven't landed (e.g. a cross-space move that+ // 409'd on a name conflict): the server would reject this note's+ // folder_id as out of scope. Stay pending; the note retries after the+ // folder settles.+ return;+ }+ if (note.left_team && note.cloud_id && !this.hasTeamSpacesCapability()) {+ // The retraction PATCH needs team-scope support; without it the push+ // would settle the row and erase the pending scope change. Defer until+ // the capability probe recovers.+ return;+ }const ctx = await this.buildSpaceContext();const scope = this.pushScopeFields(ctx.byId.get(note.space_id));if (!scope) {console.warn(`Skipping note ${note.id} push: its team space has no cloud team yet`);return;}- const cloudFolderId = note.folder_id ? (folderMap.get(note.folder_id) ?? null) : null;+ const cloudFolderId = note.folder_id ? (localToCloud.get(note.folder_id) ?? null) : null;try {if (note.cloud_id) {await NotesService.update(note.cloud_id, this.notePushPayload(note, cloudFolderId, scope));+ // Settle only if the row wasn't edited while the PATCH was in flight;+ // a blind settle would leave the delivered snapshot pending and let a+ // later pass re-PATCH it over a teammate's newer edit.+ await window.electronAPI.markNoteSyncedIfUnchanged?.(+ note.id,+ note.cloud_id,+ note.updated_at+ );} else {const cloud = await NotesService.create({client_note_id: note.client_note_id,@@ -478,16 +571,26 @@ class SyncService {}this.cacheTeamSpacesCapability(true);+ const cloudIds = new Set(teams.map((t) => t.id));+ // Teams confirmed gone can no longer resurrect through pulls — their+ // purge-race guard entries are done.+ prunePurgedTeamIds(cloudIds);+const prior = (await window.electronAPI.getSpaces?.()) ?? [];const backfillIds = await this.upsertTeamSpaces(teams, prior);- const cloudIds = new Set(teams.map((t) => t.id));for (const space of prior) {if (space.kind !== "team" || !space.cloud_team_id || cloudIds.has(space.cloud_team_id)) {continue;}- await window.electronAPI.purgeSpace?.(space.id);+ markTeamSpacePurged(space.cloud_team_id);+ const purged = await window.electronAPI.purgeSpace?.(space.id);this.dispatchSpaceRevoked(space.name);+ // Never-synced notes survive the purge in Personal (plan §10.6) —+ // surface them, never silently.+ for (const title of purged?.relocatedTitles ?? []) {+ this.dispatchNoteRelocated(title, space.name);+ }}if (backfillIds.length > 0) {@@ -513,8 +616,12 @@ class SyncService {const priorByCloudId = new Map(prior.filter((s) => s.cloud_team_id).map((s) => [s.cloud_team_id!, s]));+ const purged = readPurgedTeamIds();const backfillIds: number[] = [];for (const team of teams) {+ // A purge racing this pass (leave/delete just clicked, or the server+ // hasn't processed it yet) must not resurrect the space.+ if (purged[team.id]) continue;const existing = priorByCloudId.get(team.id);const space = await window.electronAPI.upsertSpaceFromCloud?.(team as unknown as Record<string, unknown>@@ -549,6 +656,9 @@ class SyncService {ctx: SpaceSyncContext): Promise<SpaceItem | null> {if (!teamId) return ctx.privateSpace;+ // Live read on every row: a purge can land mid-pass (this ctx would still+ // hold the deleted space), and writing the row would orphan it forever.+ if (readPurgedTeamIds()[teamId]) return null;const known = ctx.byCloudTeamId.get(teamId);if (known) return known;if (ctx.refreshedSpaces) return null;@@ -603,20 +713,38 @@ class SyncService {}}+ // Sync passes run in whichever window holds the web lock (often the always-+ // on dictation overlay), so pass-raised UI signals rebroadcast to every+ // window through the main process instead of window-local CustomEvents.+ private emitSyncUiEvent(name: string, payload: Record<string, unknown>): void {+ void window.electronAPI.emitSyncEvent?.(name, payload)?.catch(console.error);+ }+private dispatchSpaceRevoked(spaceName: string | null): void {- window.dispatchEvent(new CustomEvent("openwhispr:space-revoked", { detail: { spaceName } }));+ this.emitSyncUiEvent("space-revoked", { spaceName });}private dispatchNoteRelocated(title: string | null, spaceName: string | null | undefined): void {- window.dispatchEvent(- new CustomEvent("openwhispr:note-relocated", {- detail: { title, spaceName: spaceName ?? null },- })- );+ this.emitSyncUiEvent("note-relocated", { title, spaceName: spaceName ?? null });}private dispatchFolderNameTaken(name: string): void {- window.dispatchEvent(new CustomEvent("openwhispr:folder-name-taken", { detail: { name } }));+ this.emitSyncUiEvent("folder-name-taken", { name });+ }++ // Conflicts land in this window's store (the pull may run here) AND+ // rebroadcast, so the editor window's banner shows no matter which window+ // detected them.+ private async surfaceNoteConflict(clientNoteId: string, cloudNote: CloudNote): Promise<void> {+ const { setNoteConflict } = await import("../stores/noteStore.js");+ setNoteConflict(clientNoteId, cloudNote);+ this.emitSyncUiEvent("note-conflict", { clientNoteId, cloudNote });+ }++ private async settleNoteConflict(clientNoteId: string): Promise<void> {+ const { clearNoteConflict } = await import("../stores/noteStore.js");+ clearNoteConflict(clientNoteId);+ this.emitSyncUiEvent("note-conflict-clear", { clientNoteId });}private async syncFolders(teamOnly = false): Promise<void> {@@ -687,10 +815,15 @@ class SyncService {(await window.electronAPI.getPendingFolders?.(teamOnly ? "team" : undefined)) ?? [];if (pending.length === 0) return;- const { byId } = await this.buildSpaceContext();+ const ctx = await this.buildSpaceContext();const pushable: Array<{ folder: FolderItem; scope: PushScopeFields }> = [];for (const folder of pending) {- const scope = this.pushScopeFields(byId.get(folder.space_id));+ if (folder.left_team && folder.cloud_id && !this.hasTeamSpacesCapability()) {+ // The retraction PATCH needs team-scope support; without it the push+ // would settle the row and erase the pending scope change.+ continue;+ }+ const scope = this.pushScopeFields(ctx.byId.get(folder.space_id));if (!scope) {console.warn(`Skipping folder ${folder.id} push: its team space has no cloud team yet`);continue;@@ -704,11 +837,24 @@ class SyncService {for (const { folder, scope } of migration) {try {await FoldersService.update(folder.cloud_id!, { name: folder.name, ...scope });- await window.electronAPI.markFolderSynced?.(folder.id, folder.cloud_id!);+ // Settle only if the row wasn't edited while the PATCH was in flight.+ await window.electronAPI.markFolderSyncedIfUnchanged?.(+ folder.id,+ folder.cloud_id!,+ folder.updated_at+ );} catch (err) {if (isFolderNameTakenError(err)) {// 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);+ }} else {console.error("Folder migration sync failed:", err);}@@ -762,97 +908,146 @@ class SyncService {const cursorKey = teamOnly ? "lastSyncedAt.folders.team" : "lastSyncedAt.folders";const since = snapshot ? undefined : (localStorage.getItem(cursorKey) ?? undefined);const syncStartedAt = new Date().toISOString();- const scope = this.canSyncTeamSpaces() && this.hasTeamSpacesCapability() ? "all" : undefined;+ const teamCapable = this.canSyncTeamSpaces() && this.hasTeamSpacesCapability();+ const scope = teamCapable ? "all" : undefined;const { folders: cloudFolders } = await FoldersService.list(since, scope);const ctx = await this.buildSpaceContext();+ // Parked or failed rows must retry: they hold the cursor back (and fail+ // a backfill) so one bad row never drops the rest of the delta.+ let dirtyRows = 0;for (const cloudFolder of cloudFolders) {- const local = await window.electronAPI.getFolderByClientId?.(- cloudFolder.client_folder_id ?? ""- );+ try {+ const local = await window.electronAPI.getFolderByClientId?.(+ cloudFolder.client_folder_id ?? ""+ );- // Redacted stub: the folder moved out of one of our teams. Clean local- // copies are no longer ours to keep; dirty ones move to the private- // space so unpushed work survives (plan §7.2).- if (cloudFolder.access_removed) {- if (!local) continue;- if (local.sync_status === "pending" && !local.deleted_at && ctx.privateSpace) {- const moved = await window.electronAPI.moveFolderToSpace?.(- local.id,- ctx.privateSpace.id- );- if (moved?.success) {- // Fork identity: the server row now belongs to a scope we can't- // write, so pushing under the old ids would be rejected forever.- // The next push creates the folder as a new personal one.- await window.electronAPI.forkFolderIdentity?.(local.id);- this.dispatchNoteRelocated(- local.name,- ctx.byCloudTeamId.get(cloudFolder.previous_team_id ?? "")?.name+ // Redacted stub: the folder moved out of one of our teams. Clean+ // local copies (folder and child notes) are no longer ours to keep;+ // dirty ones move to the private space with forked identities so+ // unpushed work survives (plan §7.2).+ if (cloudFolder.access_removed) {+ if (!local) continue;+ if (ctx.privateSpace) {+ const preserveFolder = local.sync_status === "pending" && !local.deleted_at;+ const result = await window.electronAPI.relocateRevokedFolder?.(+ local.id,+ ctx.privateSpace.id,+ preserveFolder);+ if (result?.success) {+ const teamName = ctx.byCloudTeamId.get(cloudFolder.previous_team_id ?? "")?.name;+ if (result.folder) {+ this.dispatchNoteRelocated(result.folder.name, teamName);+ } else {+ for (const note of result.relocatedNotes ?? []) {+ this.dispatchNoteRelocated(note.title, teamName);+ }+ }+ } else {+ dirtyRows++;+ console.warn(`Could not relocate revoked folder ${local.id}:`, result?.error);+ }} else {- console.warn(`Could not relocate revoked folder ${local.id}:`, moved?.error);+ await window.electronAPI.hardDeleteFolder?.(local.id);}- } else {- await window.electronAPI.hardDeleteFolder?.(local.id);+ continue;}- continue;- }- if (teamOnly && !cloudFolder.team_id) continue;+ if (teamOnly && !cloudFolder.team_id) {+ // A personal row whose local copy still sits in a team space+ // announces a team→personal transition — apply it, or a later+ // edit's push would re-team the privatized folder.+ if (+ local &&+ !local.deleted_at &&+ ctx.byId.get(local.space_id)?.kind === "team" &&+ ctx.privateSpace+ ) {+ if (cloudFolder.deleted_at) {+ await window.electronAPI.hardDeleteFolder?.(local.id);+ } else if (+ normalizeTimestamp(cloudFolder.updated_at) > normalizeTimestamp(local.updated_at)+ ) {+ await window.electronAPI.upsertFolderFromCloud?.(+ cloudFolder as unknown as Record<string, unknown>,+ ctx.privateSpace.id+ );+ }+ }+ continue;+ }- if (cloudFolder.deleted_at) {- if (local) await window.electronAPI.hardDeleteFolder?.(local.id);- continue;- }+ if (cloudFolder.deleted_at) {+ if (local) await window.electronAPI.hardDeleteFolder?.(local.id);+ continue;+ }- const space = await this.resolveSpaceForCloudRow(cloudFolder.team_id, ctx);- if (!space) {- console.warn(`Parking folder ${cloudFolder.id}: unknown team ${cloudFolder.team_id}`);- continue;- }+ const space = await this.resolveSpaceForCloudRow(cloudFolder.team_id, ctx);+ if (!space) {+ dirtyRows++;+ console.warn(`Parking folder ${cloudFolder.id}: unknown team ${cloudFolder.team_id}`);+ continue;+ }- // A default folder created on another platform arrives with an- // unknown client_folder_id; inserting it would violate the per-space- // unique folder name. Match it by name within the private space and- // adopt its identity (team folders never adopt by name).- if (!local && cloudFolder.is_default && !cloudFolder.team_id) {- const allFolders = (await window.electronAPI.getFolderIdMap?.()) ?? [];- const nameMatch = allFolders.find(- (f) =>- f.is_default &&- f.space_id === space.id &&- f.name.toLowerCase() === cloudFolder.name.toLowerCase()- );- if (nameMatch) {- await window.electronAPI.adoptFolderIdentity?.(- nameMatch.id,- cloudFolder.client_folder_id ?? nameMatch.client_folder_id,- cloudFolder.id,- cloudFolder.updated_at+ // A default folder created on another platform arrives with an+ // unknown client_folder_id; inserting it would violate the per-space+ // unique folder name. Match it by name within the private space and+ // adopt its identity (team folders never adopt by name).+ if (!local && cloudFolder.is_default && !cloudFolder.team_id) {+ const allFolders = (await window.electronAPI.getFolderIdMap?.()) ?? [];+ const nameMatch = allFolders.find(+ (f) =>+ f.is_default &&+ f.space_id === space.id &&+ f.name.toLowerCase() === cloudFolder.name.toLowerCase());- continue;+ if (nameMatch) {+ await window.electronAPI.adoptFolderIdentity?.(+ nameMatch.id,+ cloudFolder.client_folder_id ?? nameMatch.client_folder_id,+ cloudFolder.id,+ cloudFolder.updated_at+ );+ continue;+ }}- }- if (local?.deleted_at) continue;- if (!local || cloudFolder.updated_at > local.updated_at) {- await window.electronAPI.upsertFolderFromCloud?.(- cloudFolder as unknown as Record<string, unknown>,- space.id- );+ if (local?.deleted_at) continue;+ // Pending rows are never overwritten by pull: an unpushed change+ // (e.g. a team→private move awaiting its scope PATCH) must win over+ // a teammate's rename, or the move silently snaps back (D2).+ if (+ !local ||+ (local.sync_status !== "pending" &&+ normalizeTimestamp(cloudFolder.updated_at) > normalizeTimestamp(local.updated_at))+ ) {+ await window.electronAPI.upsertFolderFromCloud?.(+ cloudFolder as unknown as Record<string, unknown>,+ space.id+ );+ }+ } catch (err) {+ dirtyRows++;+ console.error(`Folder pull failed for cloud folder ${cloudFolder.id}:`, err);}}- // A backfill snapshot never sees tombstones or stubs, so it must not- // advance the delta cursors.- if (!snapshot) {- 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);+ // 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) {+ // A degraded (own-rows-only) pull never saw team rows; advancing+ // would permanently skip teammate edits once the capability probe+ // recovers.+ 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);+ }}- return true;+ return dirtyRows === 0;} catch (err) {console.error("Folder pull failed:", err);return false;@@ -870,10 +1065,22 @@ class SyncService {(await window.electronAPI.getPendingNotes?.(teamOnly ? "team" : undefined)) ?? [];if (pending.length === 0) return;- const folderMap = await this.buildLocalToCloudFolderMap();+ const { localToCloud, blockedFolderIds } = await this.buildLocalToCloudFolderMap();const ctx = await this.buildSpaceContext();const pushable: Array<{ note: NoteItem; scope: PushScopeFields }> = [];for (const note of pending) {+ if (note.folder_id && blockedFolderIds.has(note.folder_id)) {+ // The folder's own changes haven't landed (e.g. a cross-space move+ // that 409'd on a name conflict): the server would reject the note's+ // folder_id as out of scope, stranding it in 'error'. Stay pending;+ // folder and notes push together once the conflict resolves.+ continue;+ }+ if (note.left_team && note.cloud_id && !this.hasTeamSpacesCapability()) {+ // The retraction PATCH needs team-scope support; without it the push+ // would settle the row and erase the pending scope change.+ continue;+ }const scope = this.pushScopeFields(ctx.byId.get(note.space_id));if (!scope) {console.warn(`Skipping note ${note.id} push: its team space has no cloud team yet`);@@ -892,12 +1099,17 @@ class SyncService {// this PATCH marks the row synced — settling it without content// would strand the edit locally and hand the next pull a stale-but-// newer cloud copy to overwrite it with.- const cloudFolderId = note.folder_id ? (folderMap.get(note.folder_id) ?? null) : null;+ const cloudFolderId = note.folder_id ? (localToCloud.get(note.folder_id) ?? null) : null;await NotesService.update(note.cloud_id!, {client_note_id: note.client_note_id,...this.notePushPayload(note, cloudFolderId, scope),});- await window.electronAPI.markNoteSynced?.(note.id, note.cloud_id!);+ // Settle only if the row wasn't edited while the PATCH was in flight.+ await window.electronAPI.markNoteSyncedIfUnchanged?.(+ note.id,+ note.cloud_id!,+ note.updated_at+ );} catch (err) {if (isTeamAccessError(err)) {await this.handleRevokedNotePush(note, ctx);@@ -922,7 +1134,7 @@ class SyncService {source_file: n.source_file,audio_duration_seconds: n.audio_duration_seconds,transcript: n.transcript,- folder_id: n.folder_id ? (folderMap.get(n.folder_id) ?? undefined) : undefined,+ folder_id: n.folder_id ? (localToCloud.get(n.folder_id) ?? undefined) : undefined,created_at: n.created_at,updated_at: n.updated_at,...scope,@@ -970,7 +1182,8 @@ class SyncService {const { cloudToLocal, defaultFolderId } = await this.buildCloudToLocalFolderMap(ctx.privateSpace?.id ?? null);- const scope = this.canSyncTeamSpaces() && this.hasTeamSpacesCapability() ? "all" : undefined;+ const teamCapable = this.canSyncTeamSpaces() && this.hasTeamSpacesCapability();+ const scope = teamCapable ? "all" : undefined;let cursor: string | undefined = since;while (true) {@@ -1013,7 +1226,34 @@ class SyncService {continue;}- if (teamOnly && !cloudNote.team_id) continue;+ if (teamOnly && !cloudNote.team_id) {+ // A personal row whose local copy still sits in a team space+ // announces a team→personal transition — apply it, or a later+ // edit's push would re-team the privatized note.+ 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)+ ) {+ if (local.sync_status === "pending") {+ await this.surfaceNoteConflict(local.client_note_id, cloudNote);+ } else if (ctx.privateSpace) {+ await window.electronAPI.upsertNoteFromCloud?.(+ cloudNote as unknown as Record<string, unknown>,+ this.resolveLocalFolderId(+ cloudNote,+ ctx.privateSpace,+ cloudToLocal,+ defaultFolderId+ ),+ ctx.privateSpace.id+ );+ }+ }+ }+ continue;+ }if (cloudNote.deleted_at) {if (local) await window.electronAPI.hardDeleteNote?.(local.id);@@ -1026,30 +1266,25 @@ class SyncService {continue;}- if (!local || cloudNote.updated_at > local.updated_at) {+ if (+ !local ||+ normalizeTimestamp(cloudNote.updated_at) > normalizeTimestamp(local.updated_at)+ ) {if (local?.sync_status === "pending") {// A newer cloud copy over unpushed local edits: surface the// conflict to the editor banner instead of silently dropping// the local edit (plan §7.3).- const { setNoteConflict } = await import("../stores/noteStore.js");- setNoteConflict(local.client_note_id, cloudNote);+ await this.surfaceNoteConflict(local.client_note_id, cloudNote);continue;}- // Unmapped folders fall back to the space root for team rows and- // to the default folder for personal rows — never across spaces.- const fallbackFolderId = cloudNote.team_id ? null : defaultFolderId;- const localFolderId = cloudNote.folder_id- ? (cloudToLocal.get(cloudNote.folder_id) ?? fallbackFolderId)- : fallbackFolderId;await window.electronAPI.upsertNoteFromCloud?.(cloudNote as unknown as Record<string, unknown>,- localFolderId,+ this.resolveLocalFolderId(cloudNote, space, cloudToLocal, defaultFolderId),space.id);if (local) {// Applying cloud over a clean row settles any stale conflict.- const { clearNoteConflict } = await import("../stores/noteStore.js");- clearNoteConflict(local.client_note_id);+ await this.settleNoteConflict(local.client_note_id);}}}@@ -1064,10 +1299,16 @@ class SyncService {// A backfill snapshot never sees tombstones or stubs, so it must not// advance the delta cursors.if (!snapshot) {- 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);+ // A degraded (own-rows-only) pull never saw team rows; advancing+ // would permanently skip teammate edits once the capability probe+ // recovers.+ 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);+ }}return true;} catch (err) {@@ -1158,7 +1399,10 @@ class SyncService {continue;}- if (!local || cloudConv.updated_at > local.updated_at) {+ if (+ !local ||+ normalizeTimestamp(cloudConv.updated_at) > normalizeTimestamp(local.updated_at)+ ) {await window.electronAPI.upsertConversationFromCloud?.(cloudConv as unknown as Record<string, unknown>,(cloudConv.messages ?? []) as unknown as Array<Record<string, unknown>>@@ -1656,22 +1900,53 @@ class SyncService {}}- private async buildLocalToCloudFolderMap(): Promise<Map<number, string>> {+ private async buildLocalToCloudFolderMap(): Promise<{+ localToCloud: Map<number, string>;+ // Cloud-backed folders with unpushed changes: their migration PATCH+ // failed or hasn't run yet (folders push before notes in a pass), so+ // pushing a child note's folder_id + scope now could be rejected as out+ // of scope. Those notes defer and stay pending.+ blockedFolderIds: Set<number>;+ }> {const folders = (await window.electronAPI.getFolderIdMap?.()) ?? [];- return new Map(folders.filter((f) => f.cloud_id).map((f) => [f.id, f.cloud_id!]));+ return {+ localToCloud: new Map(folders.filter((f) => f.cloud_id).map((f) => [f.id, f.cloud_id!])),+ blockedFolderIds: new Set(+ folders.filter((f) => f.cloud_id && f.sync_status === "pending").map((f) => f.id)+ ),+ };}private async buildCloudToLocalFolderMap(privateSpaceId: number | null): Promise<{- cloudToLocal: Map<string, number>;+ cloudToLocal: Map<string, { id: number; space_id: number }>;defaultFolderId: number | null;}> {const folders = (await window.electronAPI.getFolderIdMap?.()) ?? [];- const cloudToLocal = new Map(folders.filter((f) => f.cloud_id).map((f) => [f.cloud_id!, f.id]));+ const cloudToLocal = new Map(+ folders+ .filter((f) => f.cloud_id)+ .map((f) => [f.cloud_id!, { id: f.id, space_id: f.space_id }])+ );const personalFolder = folders.find((f) => f.is_default && f.name === "Personal" && f.space_id === privateSpaceId);return { cloudToLocal, defaultFolderId: personalFolder?.id ?? null };}++ // Unmapped folders fall back to the space root for team rows and to the+ // default folder for personal rows; a mapped folder sitting in ANOTHER+ // local space (e.g. mid-move after a 409) falls back the same way — a note+ // never files across spaces (D2).+ private resolveLocalFolderId(+ cloudNote: CloudNote,+ space: SpaceItem,+ cloudToLocal: Map<string, { id: number; space_id: number }>,+ defaultFolderId: number | null+ ): number | null {+ const fallback = cloudNote.team_id ? null : defaultFolderId;+ const mapped = cloudNote.folder_id ? cloudToLocal.get(cloudNote.folder_id) : undefined;+ return mapped && mapped.space_id === space.id ? mapped.id : fallback;+ }}export const syncService = new SyncService();diff --git a/src/services/tools/createNoteTool.ts b/src/services/tools/createNoteTool.tsindex a16d89cd2..dc30413b3 100644--- a/src/services/tools/createNoteTool.ts+++ b/src/services/tools/createNoteTool.ts@@ -5,7 +5,7 @@ import { syncService } from "../SyncService.js";export const createNoteTool: ToolDefinition = {name: "create_note",description:- "Always call list_folders first. Reuse an existing folder whenever one is a reasonable semantic fit for the note's topic (e.g. a story goes into an existing 'Stories' folder), even if the user didn't name it. Only pass a new folder name when nothing existing fits. Creates a note with title, content, optional folder (auto-created if missing), and optional space.",+ "Always call list_folders first. Reuse an existing folder whenever one is a reasonable semantic fit for the note's topic (e.g. a story goes into an existing 'Stories' folder), even if the user didn't name it. Only pass a new folder name when nothing existing fits. Creates a note with title, content, optional folder (auto-created if missing), and optional space. When space is omitted, the note AND its folder always stay in the user's private space — folder names never match team folders. To file a note into a team space (visible to its members), you must pass space explicitly.",parameters: {type: "object",properties: {@@ -19,11 +19,13 @@ export const createNoteTool: ToolDefinition = {},folder: {type: "string",- description: "Folder name for the note. Created automatically if it does not exist.",+ description:+ "Folder name for the note, resolved within the target space. Created automatically if it does not exist.",},space: {type: "string",- description: "Space name to create the note in. Omit for the user's personal space.",+ description:+ "Space name to create the note in. Omit for the user's personal space — required when filing into a team space.",},},required: ["title", "content"],@@ -39,13 +41,18 @@ export const createNoteTool: ToolDefinition = {try {let spaceId: number | null = null;+ const spaces = (await window.electronAPI.getSpaces?.()) ?? [];if (spaceName) {- const spaces = (await window.electronAPI.getSpaces?.()) ?? [];const resolved = resolveSpace(spaces, spaceName);if (resolved.error) {return { success: false, data: null, displayText: resolved.error };}spaceId = resolved.space.id;+ } else {+ // No space argument means the user's private space: folder resolution+ // must never match a team folder, or the note would silently inherit+ // the team audience (D2 derives space from folder).+ spaceId = spaces.find((s) => s.kind === "private")?.id ?? null;}let folderId: number | null = null;diff --git a/src/stores/noteStore.ts b/src/stores/noteStore.tsindex 23ee41acd..98aa0df68 100644--- a/src/stores/noteStore.ts+++ b/src/stores/noteStore.ts@@ -28,6 +28,9 @@ interface NoteState {spaces: SpaceItem[];folders: FolderItem[];folderCounts: Record<number, number>;+ // Notes sitting at a space root (folder_id NULL), keyed by space id — the+ // tree's space rows show true totals without loading containers.+ spaceRootCounts: Record<number, number>;notesByContainer: Record<string, NoteItem[]>;expandedContainers: Set<string>;activeContext: ActiveContext | null;@@ -65,6 +68,7 @@ const useNoteStore = create<NoteState>()(() => ({spaces: [],folders: [],folderCounts: {},+ spaceRootCounts: {},notesByContainer: {},expandedContainers: readExpandedContainers(),activeContext: null,@@ -158,9 +162,11 @@ function ensureIpcListeners() {}// Sharing is per-note consent, and so is team-space membership: edits// to a shared or team note must reach the cloud promptly even when- // the global backup toggle is off (teammates poll for them).+ // the global backup toggle is off (teammates poll for them). A note+ // that just LEFT a team also pushes promptly — the server row stays+ // visible to teammates until its scope retraction lands (D6).const spaceKind = useNoteStore.getState().spaces.find((s) => s.id === note.space_id)?.kind;- if (note.is_shared || spaceKind === "team") {+ if (note.is_shared || spaceKind === "team" || (note.left_team && note.cloud_id)) {syncService.debouncedPush("note", note.id);}}@@ -183,6 +189,101 @@ function ensureIpcListeners() {}}+ // Cloud-origin rows applied by a sync pull. Unlike onNoteUpdated, these+ // must NEVER trigger debouncedPush — they were just pulled from the cloud.+ // Routing through updateNoteInStore also refreshes an open clean editor+ // (PersonalNotesView's external-update resync); a dirty editor keeps its+ // buffer and the conflict-banner path covers it.+ if (window.electronAPI?.onNoteSynced) {+ const dispose = window.electronAPI.onNoteSynced((note) => {+ if (!note) return;+ const state = useNoteStore.getState();+ // Backfilled team content can reference a space the store hasn't seen.+ if (!state.spaces.some((s) => s.id === note.space_id)) void loadSpaces();+ const previous = findNoteInState(state, note.id);+ if (previous) {+ updateNoteInStore(note);+ if (noteContainerKey(previous) !== noteContainerKey(note)) void loadFolders();+ } else {+ addNote(note);+ void loadFolders();+ }+ });+ if (typeof dispose === "function") {+ disposers.push(dispose);+ }+ }++ if (window.electronAPI?.onFolderSynced) {+ const dispose = window.electronAPI.onFolderSynced((folder) => {+ if (!folder) return;+ void loadFolders();+ void loadSpaces();+ // A pulled folder change (rename, space move, revocation relocation)+ // can invalidate its cached container — re-read it if loaded.+ const key = folderContainerKey(folder.id);+ if (useNoteStore.getState().notesByContainer[key]) void loadContainerNotes(key);+ });+ if (typeof dispose === "function") {+ disposers.push(dispose);+ }+ }++ // Folder hard-deletes (pulled tombstones, revocation cascades, and the+ // echo of local deletes) — drop the container and refresh counts. The+ // UI-originated deleteFolder already cleaned up by the time the echo+ // arrives, so every step here is idempotent.+ if (window.electronAPI?.onFolderDeleted) {+ const dispose = window.electronAPI.onFolderDeleted(({ id }) => {+ if (id == null) return;+ const state = useNoteStore.getState();+ const key = folderContainerKey(id);+ const removedNotes = state.notesByContainer[key];+ const notesByContainer = { ...state.notesByContainer };+ delete notesByContainer[key];+ const expanded = new Set(state.expandedContainers);+ if (expanded.delete(key)) persistExpandedContainers(expanded);+ const extra: Partial<NoteState> = { expandedContainers: expanded };+ if (state.activeNoteId != null && removedNotes?.some((n) => n.id === state.activeNoteId)) {+ extra.activeNoteId = null;+ }+ let fallbackContext: ActiveContext | null = null;+ if (state.activeContext?.folderId === id) {+ // The active folder vanished under us — degrade to its space root.+ fallbackContext = { spaceId: state.activeContext.spaceId, folderId: null };+ extra.activeContext = fallbackContext;+ extra.activeFolderId = null;+ extra.notes = notesByContainer[contextContainerKey(fallbackContext)] ?? [];+ }+ useNoteStore.setState({ notesByContainer, ...extra });+ if (fallbackContext) void ensureContainerLoaded(contextContainerKey(fallbackContext));+ void loadFolders();+ });+ if (typeof dispose === "function") {+ disposers.push(dispose);+ }+ }++ // Conflict signals rebroadcast through the main process because the sync+ // pull usually runs in the overlay window, not the one showing the editor.+ // Broadcasts echo to the emitting window; both setters are idempotent.+ if (window.electronAPI?.onSyncEvent) {+ const dispose = window.electronAPI.onSyncEvent(({ name, payload }) => {+ if (name === "note-conflict") {+ const data = payload as { clientNoteId?: string; cloudNote?: CloudNote } | undefined;+ if (data?.clientNoteId && data.cloudNote) {+ setNoteConflict(data.clientNoteId, data.cloudNote);+ }+ } else if (name === "note-conflict-clear") {+ const data = payload as { clientNoteId?: string } | undefined;+ if (data?.clientNoteId) clearNoteConflict(data.clientNoteId);+ }+ });+ if (typeof dispose === "function") {+ disposers.push(dispose);+ }+ }+if (window.electronAPI?.onSpacePurged) {const dispose = window.electronAPI.onSpacePurged(({ spaceId }) => {handleSpacePurged(spaceId);@@ -211,10 +312,12 @@ export async function loadFolders(): Promise<FolderItem[]> {window.electronAPI.getFolderNoteCounts(),]);const folderCounts: Record<number, number> = {};+ const spaceRootCounts: Record<number, number> = {};counts.forEach((c) => {if (c.folder_id != null) folderCounts[c.folder_id] = c.count;+ else if (c.space_id != null) spaceRootCounts[c.space_id] = c.count;});- useNoteStore.setState({ folders: items, folderCounts });+ useNoteStore.setState({ folders: items, folderCounts, spaceRootCounts });return items;}@@ -414,6 +517,7 @@ export function removeNote(id: number): void {function handleSpacePurged(spaceId: number): void {const state = useNoteStore.getState();+ const purgedTeamId = state.spaces.find((s) => s.id === spaceId)?.cloud_team_id ?? null;const removedKeys = new Set<string>([spaceContainerKey(spaceId)]);state.folders.forEach((f) => {if (f.space_id === spaceId) removedKeys.add(folderContainerKey(f.id));@@ -427,14 +531,42 @@ function handleSpacePurged(spaceId: number): void {state.folders.forEach((f) => {if (f.space_id === spaceId) delete folderCounts[f.id];});+ const spaceRootCounts = { ...state.spaceRootCounts };+ delete spaceRootCounts[spaceId];const expanded = new Set([...state.expandedContainers].filter((key) => !removedKeys.has(key)));persistExpandedContainers(expanded);+ // Purge completeness (plan §5.4): purged notes' share-cache entries (which+ // can hold raw link tokens) and conflict banners (which hold full cloud+ // copies) must not outlive the space in renderer memory. Conflicts are+ // matched by the team's cloud id too, since their notes' containers may+ // never have been loaded.+ const purgedCloudIds = new Set<string>();+ const purgedClientIds = new Set<string>();+ removedKeys.forEach((key) => {+ (state.notesByContainer[key] ?? []).forEach((n) => {+ if (n.cloud_id) purgedCloudIds.add(n.cloud_id);+ purgedClientIds.add(n.client_note_id);+ });+ });+ const shareByCloudId = new Map(state.shareByCloudId);+ purgedCloudIds.forEach((id) => shareByCloudId.delete(id));+ const noteConflicts = Object.fromEntries(+ Object.entries(state.noteConflicts).filter(+ ([clientId, cloudNote]) =>+ !purgedClientIds.has(clientId) &&+ (purgedTeamId == null || cloudNote.team_id !== purgedTeamId)+ )+ );+const extra: Partial<NoteState> = {spaces: state.spaces.filter((s) => s.id !== spaceId),folders: state.folders.filter((f) => f.space_id !== spaceId),folderCounts,+ spaceRootCounts,expandedContainers: expanded,+ shareByCloudId,+ noteConflicts,};const activeNote = state.activeNoteId != null ? findNoteInState(state, state.activeNoteId) : null;if (activeNote?.space_id === spaceId) {@@ -455,6 +587,16 @@ function handleSpacePurged(spaceId: number): void {}useNoteStore.setState({ notesByContainer, ...extra });if (fallbackContext) void ensureContainerLoaded(contextContainerKey(fallbackContext));+ // The purge relocates never-synced notes to the private space root —+ // refresh counts, and the root container when it's already cached.+ void loadFolders();+ const privateSpace = state.spaces.find((s) => s.kind === "private" && s.id !== spaceId);+ if (privateSpace) {+ const privateRootKey = spaceContainerKey(privateSpace.id);+ if (useNoteStore.getState().notesByContainer[privateRootKey]) {+ void loadContainerNotes(privateRootKey);+ }+ }}export async function createFolder(@@ -600,6 +742,15 @@ export function getActiveFolderIdValue(): number | null {return useNoteStore.getState().activeFolderId;}+/** Live (non-hook) reads for deferred callbacks like undo toasts. */+export function getFoldersValue(): FolderItem[] {+ return useNoteStore.getState().folders;+}++export function getSpacesValue(): SpaceItem[] {+ return useNoteStore.getState().spaces;+}+export function useNotes(): NoteItem[] {return useNoteStore((state) => state.notes);}@@ -616,6 +767,10 @@ export function useFolderCounts(): Record<number, number> {return useNoteStore((state) => state.folderCounts);}+export function useSpaceRootCounts(): Record<number, number> {+ return useNoteStore((state) => state.spaceRootCounts);+}+export function useNotesByContainer(): Record<string, NoteItem[]> {return useNoteStore((state) => state.notesByContainer);}diff --git a/src/types/electron.ts b/src/types/electron.tsindex 0610b6da2..824508872 100644--- a/src/types/electron.ts+++ b/src/types/electron.ts@@ -68,6 +68,9 @@ export interface NoteItem {deleted_at: string | null;workspace_id?: string | null;team_id?: string | null;+ // 1 while a cloud-backed row that left a team still owes its scope+ // retraction push (D6); cleared when the row settles.+ left_team?: number;}export type ShareVisibility = "private" | "link" | "domain" | "invited";@@ -104,6 +107,9 @@ export interface FolderItem {deleted_at: string | null;workspace_id?: string | null;team_id?: string | null;+ // 1 while a cloud-backed row that left a team still owes its scope+ // retraction push (D6); cleared when the row settles.+ left_team?: number;}export interface SpaceItem {@@ -697,7 +703,9 @@ declare global {id: number,spaceId: number) => Promise<{ success: boolean; folder?: FolderItem; notes?: NoteItem[]; error?: string }>;- getFolderNoteCounts: () => Promise<Array<{ folder_id: number; count: number }>>;+ getFolderNoteCounts: () => Promise<+ Array<{ space_id: number; folder_id: number | null; count: number }>+ >;// Space operationsgetSpaces?: () => Promise<SpaceItem[]>;@@ -715,6 +723,9 @@ declare global {noteIds?: number[];folderNames?: string[];spaceId?: number;+ relocatedNotes?: NoteItem[];+ relocatedCount?: number;+ relocatedTitles?: string[];error?: string;}>;getSpaceByCloudTeamId?: (cloudTeamId: string) => Promise<SpaceItem | null>;@@ -780,6 +791,13 @@ declare global {onNoteAdded?: (callback: (note: NoteItem) => void) => () => void;onNoteUpdated?: (callback: (note: NoteItem) => void) => () => void;onNoteDeleted?: (callback: (payload: { id: number }) => void) => () => void;+ onNoteSynced?: (callback: (note: NoteItem) => void) => () => void;+ onFolderSynced?: (callback: (folder: FolderItem) => void) => () => void;+ onFolderDeleted?: (callback: (payload: { id: number }) => void) => () => void;++ // Cross-window sync events+ emitSyncEvent?: (name: string, payload?: unknown) => Promise<{ success: boolean }>;+ onSyncEvent?: (callback: (event: { name: string; payload?: unknown }) => void) => () => void;// Database event listenersonTranscriptionAdded?: (callback: (item: TranscriptionItem) => void) => () => void;@@ -1998,6 +2016,11 @@ declare global {localSpaceId?: number | null) => Promise<NoteItem>;markNoteSynced?: (id: number, cloudId: string) => Promise<void>;+ markNoteSyncedIfUnchanged?: (+ id: number,+ cloudId: string,+ snapshotUpdatedAt: string+ ) => Promise<{ success: boolean; changes: number }>;markNoteSyncError?: (id: number) => Promise<void>;hardDeleteNote?: (id: number) => Promise<void>;@@ -2008,6 +2031,11 @@ declare global {localSpaceId?: number | null) => Promise<FolderItem>;markFolderSynced?: (id: number, cloudId: string) => Promise<void>;+ markFolderSyncedIfUnchanged?: (+ id: number,+ cloudId: string,+ snapshotUpdatedAt: string+ ) => Promise<{ success: boolean; changes: number }>;adoptFolderIdentity?: (id: number,clientFolderId: string,@@ -2018,6 +2046,18 @@ declare global {getFolderIdMap?: () => Promise<FolderItem[]>;getPendingFolderDeletes?: () => Promise<FolderItem[]>;hardDeleteFolder?: (id: number) => Promise<{ success: boolean; id: number }>;+ relocateRevokedFolder?: (+ id: number,+ privateSpaceId: number,+ preserveFolder?: boolean+ ) => Promise<{+ success: boolean;+ folder?: FolderItem | null;+ folderName?: string;+ relocatedNotes?: NoteItem[];+ deletedNoteIds?: number[];+ error?: string;+ }>;getPendingConversations?: () => Promise<ConversationPreview[]>;getPendingConversationDeletes?: () => Promise<ConversationPreview[]>;diff --git a/test/helpers/spacesDatabase.test.js b/test/helpers/spacesDatabase.test.jsindex c203a6afc..8a9c4fb2f 100644--- a/test/helpers/spacesDatabase.test.js+++ b/test/helpers/spacesDatabase.test.js@@ -192,6 +192,15 @@ test("purgeSpace leaves zero residue for the space and spares the private space"teamFolder.id).note;assert.equal(teamNote.space_id, team.id);+ db.markNoteSynced(teamNote.id, "cloud-team-note");+ const draft = db.saveNote(+ "Draft",+ "unsent yeti prose",+ "personal",+ null,+ null,+ teamFolder.id+ ).note;const privateNote = db.saveNote("Mine", "private groundhog data").note;const seedMapping = db.db.prepare(@@ -211,6 +220,18 @@ test("purgeSpace leaves zero residue for the space and spares the private space"assert.deepEqual(result.folderNames, ["Vault"]);assert.equal(result.spaceId, team.id);+ // Never-synced notes exist nowhere else — relocated, not destroyed.+ assert.equal(result.relocatedCount, 1);+ assert.deepEqual(result.relocatedTitles, ["Draft"]);+ assert.deepEqual(+ result.relocatedNotes.map((n) => n.id),+ [draft.id]+ );+ const relocated = db.getNote(draft.id);+ assert.equal(relocated.space_id, privateId);+ assert.equal(relocated.folder_id, null);+ assert.equal(relocated.sync_status, "pending");+const count = (sql, ...args) => db.db.prepare(sql).get(...args).count;assert.equal(count("SELECT COUNT(*) as count FROM notes WHERE space_id = ?", team.id), 0);assert.equal(count("SELECT COUNT(*) as count FROM folders WHERE space_id = ?", team.id), 0);@@ -227,8 +248,9 @@ test("purgeSpace leaves zero residue for the space and spares the private space"count("SELECT COUNT(*) as count FROM notes_fts WHERE notes_fts MATCH 'zebracorn'"),0);+ assert.equal(count("SELECT COUNT(*) as count FROM notes_fts WHERE notes_fts MATCH 'yeti'"), 1);- assert.equal(count("SELECT COUNT(*) as count FROM notes WHERE space_id = ?", privateId), 1);+ assert.equal(count("SELECT COUNT(*) as count FROM notes WHERE space_id = ?", privateId), 2);assert.equal(count("SELECT COUNT(*) as count FROM speaker_mappings WHERE note_id = ?", privateNote.id),1@@ -359,6 +381,145 @@ test("pending queues split by space kind", (t) => {);});+test("space-root notes keep folder_id NULL across relaunches", (t) => {+ const db = createDb(t);+ if (!db) return;+ const privateId = db.getPrivateSpaceId();+ const team = db.createSpace({ name: "Team" }).space;+ const teamRoot = db.saveNote("Team root", "body", "personal", null, null, null, team.id).note;+ assert.equal(teamRoot.folder_id, null);+ const privateRoot = db.saveNote("Mine", "body").note;+ db.updateNote(privateRoot.id, { folder_id: null, space_id: privateId });+ db.db+ .prepare("UPDATE notes SET sync_status = 'synced' WHERE id IN (?, ?)")+ .run(teamRoot.id, privateRoot.id);+ const snapshot = db.db+ .prepare(+ "SELECT id, folder_id, space_id, sync_status, updated_at FROM notes WHERE id IN (?, ?) ORDER BY id"+ )+ .all(teamRoot.id, privateRoot.id);+ db.db.close();++ const db2 = new DatabaseManager();+ const relaunched = db2.db+ .prepare(+ "SELECT id, folder_id, space_id, sync_status, updated_at FROM notes WHERE id IN (?, ?) ORDER BY id"+ )+ .all(teamRoot.id, privateRoot.id);+ assert.deepEqual(+ relaunched,+ snapshot,+ "relaunch must not backfill space-root notes into a folder"+ );+ for (const note of relaunched) {+ assert.equal(note.folder_id, null);+ }+});++test("hard deletes clean speaker rows", (t) => {+ const db = createDb(t);+ if (!db) return;+ const seedSpeakerRows = (noteId) => {+ db.db+ .prepare(+ "INSERT INTO speaker_mappings (note_id, speaker_id, display_name) VALUES (?, 'spk_0', 'Alice')"+ )+ .run(noteId);+ db.db+ .prepare(+ "INSERT INTO note_speaker_embeddings (note_id, speaker_id, embedding) VALUES (?, 'spk_0', ?)"+ )+ .run(noteId, Buffer.from(new Float32Array([0.1, 0.2]).buffer));+ };+ const residue = (noteId) =>+ db.db+ .prepare(+ "SELECT (SELECT COUNT(*) FROM speaker_mappings WHERE note_id = ?) + (SELECT COUNT(*) FROM note_speaker_embeddings WHERE note_id = ?) as count"+ )+ .get(noteId, noteId).count;++ const solo = db.saveNote("Solo", "body").note;+ seedSpeakerRows(solo.id);+ assert.ok(db.hardDeleteNote(solo.id).success);+ assert.equal(residue(solo.id), 0);++ const hardFolder = db.createFolder("Hard").folder;+ const hardNote = db.saveNote("Filed", "body", "personal", null, null, hardFolder.id).note;+ seedSpeakerRows(hardNote.id);+ assert.ok(db.hardDeleteFolder(hardFolder.id).success);+ assert.equal(residue(hardNote.id), 0);++ const softFolder = db.createFolder("Soft").folder;+ const softNote = db.saveNote("Filed too", "body", "personal", null, null, softFolder.id).note;+ seedSpeakerRows(softNote.id);+ assert.ok(db.deleteFolder(softFolder.id).success);+ assert.equal(residue(softNote.id), 0);+});++test("upsertFolderFromCloud converges on a same-space name collision", (t) => {+ const db = createDb(t);+ if (!db) return;+ const team = db.createSpace({ name: "Shared" }).space;+ const local = db.createFolder("Projects", team.id).folder;++ const cloud = {+ client_folder_id: "cf-remote",+ id: "cloud-folder-1",+ name: "Projects",+ sort_order: 7,+ created_at: "2026-07-01T00:00:00.000Z",+ updated_at: "2026-07-02T00:00:00.000Z",+ };+ const converged = db.upsertFolderFromCloud(cloud, team.id);+ assert.equal(converged.id, local.id, "must adopt the existing live folder, not insert");+ assert.equal(converged.client_folder_id, "cf-remote");+ assert.equal(converged.cloud_id, "cloud-folder-1");+ assert.equal(converged.sort_order, 7);+ assert.equal(converged.name, "Projects");+ assert.equal(converged.sync_status, "synced");+ assert.equal(db.getFolders(team.id).filter((f) => f.name === "Projects").length, 1);++ // DO UPDATE branch: the cloud folder is renamed to a name held by another+ // live local folder in the same space — the holder adopts the identity and+ // the stale tracker is forked instead of wedging the pull.+ const other = db.createFolder("Roadmap", team.id).folder;+ const renamed = db.upsertFolderFromCloud(+ { ...cloud, name: "Roadmap", updated_at: "2026-07-03T00:00:00.000Z" },+ team.id+ );+ assert.equal(renamed.id, other.id);+ assert.equal(renamed.client_folder_id, "cf-remote");+ assert.equal(renamed.cloud_id, "cloud-folder-1");+ const forked = db.db.prepare("SELECT * FROM folders WHERE id = ?").get(local.id);+ assert.notEqual(forked.client_folder_id, "cf-remote");+ assert.equal(forked.cloud_id, null);+ assert.equal(forked.sync_status, "pending");+});++test("pending vector purges persist across relaunches until cleared", (t) => {+ const db = createDb(t);+ if (!db) return;+ db.addPendingVectorPurge(42);+ db.addPendingVectorPurge(42);+ db.addPendingVectorPurge(7);+ assert.deepEqual(+ db+ .getPendingVectorPurges()+ .map((row) => row.space_id)+ .sort((a, b) => a - b),+ [7, 42]+ );+ db.db.close();++ const db2 = new DatabaseManager();+ assert.equal(db2.getPendingVectorPurges().length, 2, "queue must survive a relaunch");+ db2.clearPendingVectorPurge(42);+ assert.deepEqual(+ db2.getPendingVectorPurges().map((row) => row.space_id),+ [7]+ );+});+test("setSpaceSyncStatus flips a space's sync_status", (t) => {const db = createDb(t);if (!db) return;@@ -372,3 +533,210 @@ test("setSpaceSyncStatus flips a space's sync_status", (t) => {assert.equal(db.setSpaceSyncStatus(99999, "synced").success, false);});++test("team→private moves set left_team so retractions stay in the team queue", (t) => {+ const db = createDb(t);+ if (!db) return;+ const privateId = db.getPrivateSpaceId();+ const team = db.createSpace({ name: "Sales" }).space;++ const note = db.saveNote("Comp review", "body", "personal", null, null, null, team.id).note;+ db.markNoteSynced(note.id, "cloud-note-1");+ db.updateNote(note.id, { space_id: privateId, folder_id: null });++ const moved = db.getNote(note.id);+ assert.equal(moved.space_id, privateId);+ assert.equal(moved.left_team, 1);+ assert.equal(moved.sync_status, "pending");+ assert.ok(+ db.getPendingNotes("team").some((n) => n.id === note.id),+ "the retraction must push even in the backup-off team-only pass"+ );++ db.markNoteSynced(note.id, "cloud-note-1");+ assert.equal(db.getNote(note.id).left_team, 0, "settling clears the flag");++ // Identity forks null the cloud_id — nothing to retract, no flag.+ const forked = db.saveNote("Stub", "body", "personal", null, null, null, team.id).note;+ db.markNoteSynced(forked.id, "cloud-note-2");+ db.updateNote(forked.id, {+ space_id: privateId,+ folder_id: null,+ client_note_id: "forked-client-id",+ cloud_id: null,+ });+ assert.equal(db.getNote(forked.id).left_team, 0);++ // Never-synced rows have no server copy to retract.+ const local = db.saveNote("Local", "body", "personal", null, null, null, team.id).note;+ db.updateNote(local.id, { space_id: privateId, folder_id: null });+ assert.equal(db.getNote(local.id).left_team, 0);+ assert.ok(!db.getPendingNotes("team").some((n) => n.id === local.id));+});++test("moveFolderToSpace team→private flags the folder and its cloud-backed notes", (t) => {+ const db = createDb(t);+ if (!db) return;+ const privateId = db.getPrivateSpaceId();+ const team = db.createSpace({ name: "Growth" }).space;+ const folder = db.createFolder("Campaigns", team.id).folder;+ db.markFolderSynced(folder.id, "cloud-folder-1");+ const cloudNote = db.saveNote("Plan", "body", "personal", null, null, folder.id).note;+ db.markNoteSynced(cloudNote.id, "cloud-note-1");+ const localNote = db.saveNote("Draft", "body", "personal", null, null, folder.id).note;++ assert.ok(db.moveFolderToSpace(folder.id, privateId).success);+ const movedFolder = db.db.prepare("SELECT * FROM folders WHERE id = ?").get(folder.id);+ assert.equal(movedFolder.left_team, 1);+ assert.equal(db.getNote(cloudNote.id).left_team, 1);+ assert.equal(db.getNote(localNote.id).left_team, 0);+ assert.ok(db.getPendingFolders("team").some((f) => f.id === folder.id));+ assert.ok(db.getPendingNotes("team").some((n) => n.id === cloudNote.id));+ assert.ok(!db.getPendingNotes("team").some((n) => n.id === localNote.id));++ // Moving back into a team clears the flags: the team queue covers the rows+ // by their space kind again.+ assert.ok(db.moveFolderToSpace(folder.id, team.id).success);+ assert.equal(+ db.db.prepare("SELECT left_team FROM folders WHERE id = ?").get(folder.id).left_team,+ 0+ );+ assert.equal(db.getNote(cloudNote.id).left_team, 0);+});++test("markNoteSyncedIfUnchanged settles only rows untouched since the push snapshot", (t) => {+ const db = createDb(t);+ if (!db) return;+ const note = db.saveNote("Doc", "v1").note;+ const snapshot = db.getNote(note.id);++ const settled = db.markNoteSyncedIfUnchanged(note.id, "cloud-1", snapshot.updated_at);+ assert.equal(settled.changes, 1);+ assert.equal(db.getNote(note.id).sync_status, "synced");+ assert.equal(db.getNote(note.id).cloud_id, "cloud-1");++ // Simulate an edit landing while the PATCH was in flight.+ db.db+ .prepare(+ "UPDATE notes SET content = 'v2', sync_status = 'pending', updated_at = datetime('now', '+1 hour') WHERE id = ?"+ )+ .run(note.id);+ const stale = db.markNoteSyncedIfUnchanged(note.id, "cloud-1", snapshot.updated_at);+ assert.equal(stale.changes, 0);+ assert.equal(db.getNote(note.id).sync_status, "pending", "the mid-flight edit must still push");+});++test("markFolderSyncedIfUnchanged settles only rows untouched since the push snapshot", (t) => {+ const db = createDb(t);+ if (!db) return;+ const folder = db.createFolder("Design").folder;+ const readFolder = () => db.db.prepare("SELECT * FROM folders WHERE id = ?").get(folder.id);+ const snapshot = readFolder();++ const settled = db.markFolderSyncedIfUnchanged(folder.id, "cloud-folder-1", snapshot.updated_at);+ assert.equal(settled.changes, 1);+ assert.equal(readFolder().sync_status, "synced");+ assert.equal(readFolder().cloud_id, "cloud-folder-1");++ // Simulate a rename landing while the PATCH was in flight.+ db.db+ .prepare(+ "UPDATE folders SET name = 'Design v2', sync_status = 'pending', updated_at = datetime('now', '+1 hour') WHERE id = ?"+ )+ .run(folder.id);+ const stale = db.markFolderSyncedIfUnchanged(folder.id, "cloud-folder-1", snapshot.updated_at);+ assert.equal(stale.changes, 0);+ assert.equal(readFolder().sync_status, "pending", "the mid-flight rename must still push");+});++test("relocateRevokedFolder preserves dirty children and hard-deletes server-owned ones", (t) => {+ const db = createDb(t);+ if (!db) return;+ const privateId = db.getPrivateSpaceId();+ const team = db.createSpace({ name: "Ops" }).space;+ const folder = db.createFolder("Q3 calls", team.id).folder;+ db.markFolderSynced(folder.id, "cloud-folder-1");++ const clean = db.saveNote("Recap", "server copy", "personal", null, null, folder.id).note;+ db.markNoteSynced(clean.id, "cloud-note-1");+ const dirty = db.saveNote("Edits", "unpushed work", "personal", null, null, folder.id).note;+ db.markNoteSynced(dirty.id, "cloud-note-2");+ db.updateNote(dirty.id, { content: "unpushed work v2" });+ const draft = db.saveNote("Draft", "never synced", "personal", null, null, folder.id).note;+ db.db+ .prepare(+ "INSERT INTO speaker_mappings (note_id, speaker_id, display_name) VALUES (?, 'spk_0', 'Alice')"+ )+ .run(clean.id);++ // Clean folder: the row is deleted, only dirty/never-synced children survive.+ const result = db.relocateRevokedFolder(folder.id, privateId, false);+ assert.ok(result.success);+ assert.equal(result.folder, null);+ assert.equal(result.folderName, "Q3 calls");+ assert.deepEqual(result.deletedNoteIds, [clean.id]);+ assert.deepEqual(+ result.relocatedNotes.map((n) => n.id).sort((a, b) => a - b),+ [dirty.id, draft.id]+ );+ assert.equal(db.getNote(clean.id), null);+ assert.equal(+ db.db.prepare("SELECT COUNT(*) as count FROM speaker_mappings WHERE note_id = ?").get(clean.id)+ .count,+ 0+ );+ assert.equal(db.db.prepare("SELECT * FROM folders WHERE id = ?").get(folder.id), undefined);+ for (const survivor of [db.getNote(dirty.id), db.getNote(draft.id)]) {+ assert.equal(survivor.space_id, privateId);+ assert.equal(survivor.folder_id, null);+ assert.equal(survivor.cloud_id, null);+ assert.equal(survivor.sync_status, "pending");+ }+ assert.notEqual(db.getNote(dirty.id).client_note_id, dirty.client_note_id, "identity forked");++ // Dirty folder: preserved in Personal with a forked identity, children keep+ // their folder link, and a name collision falls back to a suffixed rename.+ db.createFolder("Projects");+ const team2 = db.createSpace({ name: "Design" }).space;+ const dirtyFolder = db.createFolder("Projects", team2.id).folder;+ db.markFolderSynced(dirtyFolder.id, "cloud-folder-2");+ db.renameFolder(dirtyFolder.id, "Projects");+ const child = db.saveNote("Spec", "body", "personal", null, null, dirtyFolder.id).note;++ const preserved = db.relocateRevokedFolder(dirtyFolder.id, privateId, true);+ assert.ok(preserved.success);+ assert.equal(preserved.folder.name, "Projects (2)");+ assert.equal(preserved.folder.space_id, privateId);+ assert.equal(preserved.folder.cloud_id, null);+ assert.equal(preserved.folder.sync_status, "pending");+ assert.notEqual(preserved.folder.client_folder_id, dirtyFolder.client_folder_id);+ const movedChild = db.getNote(child.id);+ assert.equal(movedChild.space_id, privateId);+ assert.equal(movedChild.folder_id, dirtyFolder.id, "children keep the preserved folder link");+ assert.equal(movedChild.cloud_id, null);+});++test("getFolderNoteCounts attributes space-root notes per space", (t) => {+ const db = createDb(t);+ if (!db) return;+ const privateId = db.getPrivateSpaceId();+ const team = db.createSpace({ name: "Ops" }).space;+ const folder = db.createFolder("Docs", team.id).folder;+ db.saveNote("Filed", "body", "personal", null, null, folder.id);+ db.saveNote("Root A", "body", "personal", null, null, null, team.id);+ db.saveNote("Root B", "body", "personal", null, null, null, team.id);+ const tombstoned = db.saveNote("Gone", "body", "personal", null, null, null, team.id).note;+ db.deleteNote(tombstoned.id);++ const counts = db.getFolderNoteCounts();+ const folderRow = counts.find((c) => c.folder_id === folder.id);+ assert.equal(folderRow.space_id, team.id);+ assert.equal(folderRow.count, 1);++ const teamRootRow = counts.find((c) => c.folder_id === null && c.space_id === team.id);+ assert.equal(teamRootRow.count, 2, "space-root notes count per space, excluding tombstones");+ assert.ok(+ !counts.some((c) => c.folder_id === null && c.space_id === privateId),+ "no root row for spaces without root notes"+ );+});