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
feat(sync): space-scoped sync — spaces pass, revocation purge, conflict protection
Gabriel Steine697ba1e322c
diff --git a/preload.js b/preload.jsindex f3eff0c2e..21eb69e5a 100644--- a/preload.js+++ b/preload.js@@ -147,6 +147,7 @@ contextBridge.exposeInMainWorld("electronAPI", {getSpaceByCloudTeamId: (cloudTeamId) =>ipcRenderer.invoke("db-get-space-by-cloud-team-id", cloudTeamId),upsertSpaceFromCloud: (team) => ipcRenderer.invoke("db-upsert-space-from-cloud", team),+ setSpaceSyncStatus: (id, status) => ipcRenderer.invoke("db-set-space-sync-status", id, status),onSpacePurged: (callback) => {const listener = (_event, payload) => callback?.(payload);ipcRenderer.on("space-purged", listener);@@ -839,7 +840,7 @@ contextBridge.exposeInMainWorld("electronAPI", {ipcRenderer.invoke("db-semantic-search-conversations", query, limit),// Sync operations- getPendingNotes: () => ipcRenderer.invoke("db-get-pending-notes"),+ getPendingNotes: (spaceKind) => ipcRenderer.invoke("db-get-pending-notes", spaceKind),getPendingNoteDeletes: () => ipcRenderer.invoke("db-get-pending-note-deletes"),getNoteByClientId: (clientNoteId) => ipcRenderer.invoke("db-get-note-by-client-id", clientNoteId),upsertNoteFromCloud: (cloudNote, localFolderId, localSpaceId) =>@@ -848,7 +849,7 @@ contextBridge.exposeInMainWorld("electronAPI", {markNoteSyncError: (id) => ipcRenderer.invoke("db-mark-note-sync-error", id),hardDeleteNote: (id) => ipcRenderer.invoke("db-hard-delete-note", id),- getPendingFolders: () => ipcRenderer.invoke("db-get-pending-folders"),+ getPendingFolders: (spaceKind) => ipcRenderer.invoke("db-get-pending-folders", spaceKind),getFolderByClientId: (clientFolderId) =>ipcRenderer.invoke("db-get-folder-by-client-id", clientFolderId),upsertFolderFromCloud: (cloudFolder, localSpaceId) =>@@ -856,6 +857,7 @@ contextBridge.exposeInMainWorld("electronAPI", {markFolderSynced: (id, cloudId) => ipcRenderer.invoke("db-mark-folder-synced", id, cloudId),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),diff --git a/src/components/AcceptInvitationModal.tsx b/src/components/AcceptInvitationModal.tsxindex 00a3c5565..d27d3d42c 100644--- a/src/components/AcceptInvitationModal.tsx+++ b/src/components/AcceptInvitationModal.tsx@@ -18,6 +18,7 @@ import {import { useWorkspaceStore } from "../stores/workspaceStore";import { useAuth } from "../hooks/useAuth";import { signOut } from "../lib/auth";+import { syncService } from "../services/SyncService.js";import { useToast } from "./ui/useToast";import SignInDialog from "./SignInDialog";import type { InvitationPreview } from "../types/electron";@@ -91,9 +92,11 @@ export default function AcceptInvitationModal({ token, onClose }: Props) {}// Stored token survives the sign-out reload, so the modal resurfaces for- // the next account.+ // the next account. The old account's team content must not leak into the+ // new one (the purge never blocks the switch).async function handleSwitchAccount() {if (token) storePendingInvitationToken(token);+ await syncService.purgeTeamSpacesForSignOut();await signOut();}diff --git a/src/components/CommandSearch.tsx b/src/components/CommandSearch.tsxindex cf6233151..30fd4cf09 100644--- a/src/components/CommandSearch.tsx+++ b/src/components/CommandSearch.tsx@@ -4,7 +4,7 @@ import * as DialogPrimitive from "@radix-ui/react-dialog";import { Search, FileText, Mic, Folder, Lock, Users, Upload, MessageSquare } from "lucide-react";import { cn } from "./lib/utils";import type { NoteItem, FolderItem, SpaceItem, TranscriptionItem } from "../types/electron.js";-import { normalizeDbDate } from "../utils/dateFormatting";+import { formatRelativeTime } from "../utils/dateFormatting";interface ConversationResult {id: number;@@ -38,23 +38,6 @@ type FlatItem =| { kind: "transcript"; transcript: TranscriptionItem }| { kind: "conversation"; conversation: ConversationResult };-function relativeTime(- dateStr: string,- t: (key: string, opts?: Record<string, unknown>) => string-): string {- const date = normalizeDbDate(dateStr);- if (Number.isNaN(date.getTime())) return "";- const diff = Date.now() - date.getTime();- const minutes = Math.floor(diff / 60000);- const hours = Math.floor(diff / 3600000);- const days = Math.floor(diff / 86400000);- if (minutes < 1) return t("notes.list.timeNow");- if (minutes < 60) return t("notes.list.minutesAgo", { count: minutes });- if (hours < 24) return t("notes.list.hoursAgo", { count: hours });- if (days < 7) return t("notes.list.daysAgo", { count: days });- return date.toLocaleDateString(undefined, { month: "short", day: "numeric" });-}-function stripMarkdownPreview(text: string): string {return text.replace(/#{1,6}\s+/g, "")@@ -392,7 +375,7 @@ export default function CommandSearch({)}</div><span className="text-[10px] text-muted-foreground/35 tabular-nums shrink-0">- {relativeTime(conv.updated_at, t)}+ {formatRelativeTime(conv.updated_at, t)}</span></button>))@@ -615,7 +598,7 @@ function NoteRow({)}</div><span className="text-[10px] text-muted-foreground/35 tabular-nums shrink-0">- {relativeTime(note.updated_at, t)}+ {formatRelativeTime(note.updated_at, t)}</span></button>);@@ -658,7 +641,7 @@ function TranscriptRow({/><p className="flex-1 text-xs text-foreground/75 truncate min-w-0">{transcript.text}</p><span className="text-[10px] text-muted-foreground/35 tabular-nums shrink-0">- {relativeTime(transcript.created_at, t)}+ {formatRelativeTime(transcript.created_at, t)}</span></button>);diff --git a/src/components/ControlPanel.tsx b/src/components/ControlPanel.tsxindex c979ce20b..734413aa2 100644--- a/src/components/ControlPanel.tsx+++ b/src/components/ControlPanel.tsx@@ -43,6 +43,7 @@ import {import { fetchProviders as fetchStreamingProviders } from "../stores/streamingProvidersStore";import HistoryView from "./HistoryView";import BackgroundActionToastListener from "./notes/BackgroundActionToastListener";+import SpaceSyncToastListener from "./notes/SpaceSyncToastListener";import { syncService } from "../services/SyncService.js";import AcceptInvitationModal from "./AcceptInvitationModal";import {@@ -960,6 +961,7 @@ export default function ControlPanel({ initialSettingsSection }: ControlPanelPro</main></div><BackgroundActionToastListener />+ <SpaceSyncToastListener /></div>);}diff --git a/src/components/SettingsPage.tsx b/src/components/SettingsPage.tsxindex 56c72e85c..d0db48783 100644--- a/src/components/SettingsPage.tsx+++ b/src/components/SettingsPage.tsx@@ -1368,6 +1368,9 @@ export default function SettingsPage({const handleSignOut = useCallback(async () => {setIsSigningOut(true);try {+ // Team content is membership-scoped, not account data: drop it locally+ // before the session ends (never blocks sign-out).+ await syncService.purgeTeamSpacesForSignOut();await signOut();window.location.reload();} catch (error) {diff --git a/src/components/notes/NoteEditor.tsx b/src/components/notes/NoteEditor.tsxindex d35f06496..c1e415142 100644--- a/src/components/notes/NoteEditor.tsx+++ b/src/components/notes/NoteEditor.tsx@@ -16,7 +16,13 @@ import {Share2,} from "lucide-react";import ShareNoteDialog from "./ShareNoteDialog";-import { useShareCacheEntry } from "../../stores/noteStore";+import {+ useShareCacheEntry,+ useNoteConflict,+ clearNoteConflict,+ updateNoteInStore,+} from "../../stores/noteStore";+import { useWorkspaceStore } from "../../stores/workspaceStore";import { useAuth } from "../../hooks/useAuth";import { RichTextEditor } from "../ui/RichTextEditor";import type { Editor } from "@tiptap/react";@@ -36,7 +42,7 @@ import ActionProcessingOverlay from "./ActionProcessingOverlay";import NoteBottomBar from "./NoteBottomBar";import EmbeddedChat, { type EmbeddedChatMode } from "./EmbeddedChat";import { useEmbeddedChat } from "../../hooks/useEmbeddedChat";-import { normalizeDbDate } from "../../utils/dateFormatting";+import { normalizeDbDate, formatRelativeTime } from "../../utils/dateFormatting";import { parseTranscriptSegments } from "../../utils/parseTranscriptSegments";import {applyTranscriptSpeakerPatch,@@ -152,7 +158,7 @@ export default function NoteEditor({const [newFolderName, setNewFolderName] = useState("");const [isDiarizing, setIsDiarizing] = useState(false);const [shareDialogOpen, setShareDialogOpen] = useState(false);- const { isSignedIn } = useAuth();+ const { isSignedIn, user } = useAuth();const shareCache = useShareCacheEntry(note.cloud_id);// Persisted flag is the restart-safe truth; the live cache overlays it for// the current session (it reflects server state before the flag persists).@@ -161,6 +167,16 @@ export default function NoteEditor({// An already-shared note stays manageable (unshare/revoke) after a lapse.const canShare =isSignedIn && (localStorage.getItem("isSubscribed") === "true" || Boolean(note.is_shared));+ // A newer cloud copy arrived while this note had unpushed edits (plan §7.3).+ const conflict = useNoteConflict(note.client_note_id);+ const members = useWorkspaceStore((s) => s.members);+ const conflictEditorName = useMemo(() => {+ if (!conflict?.updated_by_user_id || !user?.id || conflict.updated_by_user_id === user.id) {+ return null;+ }+ const member = members.find((m) => m.user_id === conflict.updated_by_user_id);+ return member ? (member.name ?? member.email) : null;+ }, [conflict, members, user?.id]);const [diarizedSegments, setDiarizedSegments] = useState<TranscriptSegment[] | null>(null);const [speakerMappings, setSpeakerMappings] = useState<Record<string, string>>({});const [speakerProfiles, setSpeakerProfiles] = useState<@@ -586,6 +602,24 @@ export default function NoteEditor({}}, [chatMode]);+ // Apply the newer cloud copy over the local edits, keeping the note's+ // current local placement.+ const handleConflictRefresh = useCallback(async () => {+ if (!conflict) return;+ const fresh = await window.electronAPI.upsertNoteFromCloud?.(+ conflict as unknown as Record<string, unknown>,+ note.folder_id,+ note.space_id+ );+ clearNoteConflict(note.client_note_id);+ if (fresh) updateNoteInStore(fresh);+ }, [conflict, note.client_note_id, note.folder_id, note.space_id]);++ // Keep the local edits; the next push wins last-write.+ const handleConflictKeep = useCallback(() => {+ clearNoteConflict(note.client_note_id);+ }, [note.client_note_id]);+const noteDate = formatNoteDate(note.created_at);const shortDate = formatShortDate(note.created_at);@@ -884,6 +918,43 @@ export default function NoteEditor({</div></div>+ {conflict && (+ <div+ className={cn(+ "flex items-center gap-2 px-5 h-8 mt-2 shrink-0",+ "bg-amber-400/5 dark:bg-amber-400/[0.07]",+ "border-y border-amber-400/15 dark:border-amber-400/20",+ "animate-in slide-in-from-top-2 duration-300"+ )}+ >+ <span className="w-1 h-1 rounded-full bg-amber-400/60 shrink-0" />+ <p className="text-[11px] text-foreground/50 flex-1 truncate">+ {t("notes.spaces.conflictBanner")}+ {conflictEditorName && (+ <span className="text-foreground/30">+ {" "}+ {t("notes.spaces.editedBy", {+ name: conflictEditorName,+ time: formatRelativeTime(conflict.updated_at, t),+ })}+ </span>+ )}+ </p>+ <button+ onClick={handleConflictRefresh}+ className="text-[11px] font-medium text-foreground/50 hover:text-foreground/70 transition-colors shrink-0"+ >+ {t("notes.spaces.conflictRefresh")}+ </button>+ <button+ onClick={handleConflictKeep}+ className="text-[11px] font-medium text-foreground/35 hover:text-foreground/55 transition-colors shrink-0"+ >+ {t("notes.spaces.conflictKeep")}+ </button>+ </div>+ )}+<div className="flex-1 relative min-h-0"><div className="h-full overflow-y-auto">{viewMode === "transcript" && (hasChatSegments || isRecording) ? (diff --git a/src/components/notes/SpaceSyncToastListener.tsx b/src/components/notes/SpaceSyncToastListener.tsxnew file mode 100644index 000000000..05b6c7da9--- /dev/null+++ b/src/components/notes/SpaceSyncToastListener.tsx@@ -0,0 +1,54 @@+import { useEffect } from "react";+import { useTranslation } from "react-i18next";+import { useToast } from "../ui/useToast";++const REVOKED_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.+ * A rejected push and the following spaces-pass purge can both announce the+ * same space, so access-revoked toasts dedupe by space name.+ */+export default function SpaceSyncToastListener() {+ const { t } = useTranslation();+ const { toast } = useToast();++ useEffect(() => {+ const lastRevokedAt = 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) < REVOKED_DEDUPE_MS) return;+ lastRevokedAt.set(spaceName, now);+ toast({+ title: t("notes.spaces.accessRevoked", { space: spaceName }),+ 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);+ return () => {+ window.removeEventListener("openwhispr:space-revoked", onSpaceRevoked);+ window.removeEventListener("openwhispr:note-relocated", onNoteRelocated);+ };+ }, [toast, t]);++ return null;+}diff --git a/src/components/notes/SpacesTree.tsx b/src/components/notes/SpacesTree.tsxindex 1318d9448..4a4f70561 100644--- a/src/components/notes/SpacesTree.tsx+++ b/src/components/notes/SpacesTree.tsx@@ -43,7 +43,7 @@ import {} from "../../hooks/useTeamSpacesCapability";import { useSettingsStore } from "../../stores/settingsStore";import { cn } from "../lib/utils";-import { normalizeDbDate } from "../../utils/dateFormatting";+import { formatRelativeTime } from "../../utils/dateFormatting";import CreateSpaceDialog from "./CreateSpaceDialog";import type { FolderItem, NoteItem, SpaceItem } from "../../types/electron";import {@@ -121,22 +121,6 @@ function spaceDisplayName(space: SpaceItem, t: TFn): string {return space.kind === "private" ? t("notes.spaces.personal") : space.name;}-function relativeTime(dateStr: string, t: TFn): string {- const date = normalizeDbDate(dateStr);- if (Number.isNaN(date.getTime())) return dateStr;-- const diff = Date.now() - date.getTime();- const minutes = Math.floor(diff / 60000);- const hours = Math.floor(diff / 3600000);- const days = Math.floor(diff / 86400000);-- if (minutes < 1) return t("notes.list.timeNow");- if (minutes < 60) return t("notes.list.minutesAgo", { count: minutes });- if (hours < 24) return t("notes.list.hoursAgo", { count: hours });- if (days < 7) return t("notes.list.daysAgo", { count: days });- return date.toLocaleDateString(undefined, { month: "short", day: "numeric" });-}-function useFileManagerName(): string {return navigator.platform.startsWith("Mac")? "Finder"@@ -791,7 +775,7 @@ function NoteLeaf({aria-hidden="true"className="text-[10px] tabular-nums shrink-0 text-foreground/35 dark:text-foreground/15 transition-opacity group-hover:opacity-0">- {relativeTime(note.updated_at, t)}+ {formatRelativeTime(note.updated_at, t)}</span><DropdownMenuonOpenChange={(open) => {diff --git a/src/helpers/database.js b/src/helpers/database.jsindex b7a031619..1d3db54b7 100644--- a/src/helpers/database.js+++ b/src/helpers/database.js@@ -1885,6 +1885,19 @@ class DatabaseManager {return this.updateSpace(id, { name });}+ setSpaceSyncStatus(id, status) {+ try {+ if (!this.db) throw new Error("Database not initialized");+ const result = this.db+ .prepare("UPDATE spaces SET sync_status = ? WHERE id = ?")+ .run(status, id);+ return { success: result.changes > 0 };+ } catch (error) {+ debugLogger.error("Error setting space sync status", { error: error.message }, "spaces");+ throw error;+ }+ }+getSpaceByCloudTeamId(cloudTeamId) {try {if (!this.db) throw new Error("Database not initialized");@@ -3034,9 +3047,16 @@ class DatabaseManager {}}- getPendingNotes() {+ getPendingNotes(spaceKind = null) {try {if (!this.db) throw new Error("Database not initialized");+ if (spaceKind != 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 = ?"+ )+ .all(spaceKind);+ }return this.db.prepare("SELECT * FROM notes WHERE sync_status = 'pending' AND deleted_at IS NULL").all();@@ -3163,9 +3183,16 @@ class DatabaseManager {}}- getPendingFolders() {+ getPendingFolders(spaceKind = null) {try {if (!this.db) throw new Error("Database not initialized");+ if (spaceKind != 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 = ?"+ )+ .all(spaceKind);+ }return this.db.prepare("SELECT * FROM folders WHERE sync_status = 'pending' AND deleted_at IS NULL").all();@@ -3271,6 +3298,24 @@ class DatabaseManager {}}+ // 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.+ forkFolderIdentity(id) {+ try {+ 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 = ?"+ )+ .run(randomUUID(), id);+ return { success: result.changes > 0 };+ } catch (error) {+ debugLogger.error("Error forking folder identity", { error: error.message }, "database");+ throw error;+ }+ }+adoptFolderIdentity(id, clientFolderId, cloudId, updatedAt) {try {if (!this.db) throw new Error("Database not initialized");diff --git a/src/helpers/ipcHandlers.js b/src/helpers/ipcHandlers.jsindex 56d35ae24..172cea108 100644--- a/src/helpers/ipcHandlers.js+++ b/src/helpers/ipcHandlers.js@@ -1480,7 +1480,9 @@ class IPCHandlers {});// Notes sync- ipcMain.handle("db-get-pending-notes", () => this.databaseManager.getPendingNotes());+ ipcMain.handle("db-get-pending-notes", (_, spaceKind) =>+ this.databaseManager.getPendingNotes(spaceKind)+ );ipcMain.handle("db-get-pending-note-deletes", () =>this.databaseManager.getPendingNoteDeletes());@@ -1507,7 +1509,9 @@ class IPCHandlers {});// Folders sync- ipcMain.handle("db-get-pending-folders", () => this.databaseManager.getPendingFolders());+ ipcMain.handle("db-get-pending-folders", (_, spaceKind) =>+ this.databaseManager.getPendingFolders(spaceKind)+ );ipcMain.handle("db-get-folder-by-client-id", (_, clientFolderId) =>this.databaseManager.getFolderByClientId(clientFolderId));@@ -1520,6 +1524,9 @@ class IPCHandlers {ipcMain.handle("db-adopt-folder-identity", (_, id, clientFolderId, cloudId, updatedAt) =>this.databaseManager.adoptFolderIdentity(id, clientFolderId, cloudId, updatedAt));+ ipcMain.handle("db-fork-folder-identity", (_, id) =>+ this.databaseManager.forkFolderIdentity(id)+ );ipcMain.handle("db-get-folder-id-map", () => this.databaseManager.getFolderIdMap());ipcMain.handle("db-get-pending-folder-deletes", () =>this.databaseManager.getPendingFolderDeletes()@@ -1548,6 +1555,9 @@ class IPCHandlers {ipcMain.handle("db-upsert-space-from-cloud", (_, team) =>this.databaseManager.upsertSpaceFromCloud(team));+ ipcMain.handle("db-set-space-sync-status", (_, id, status) =>+ this.databaseManager.setSpaceSyncStatus(id, status)+ );// Conversations syncipcMain.handle("db-get-pending-conversations", () =>diff --git a/src/hooks/useTeamSpacesCapability.ts b/src/hooks/useTeamSpacesCapability.tsindex 340a068f9..6c7ff8403 100644--- a/src/hooks/useTeamSpacesCapability.ts+++ b/src/hooks/useTeamSpacesCapability.ts@@ -6,10 +6,15 @@ export function hasTeamSpacesDevOverride(): boolean {}/**- * Whether the TEAM SPACES section should render. Phase 2: dev override or- * locally known team spaces; Phase 3 swaps in the server capability probe.+ * Whether the TEAM SPACES section should render: the cached server capability+ * probe (written by the spaces sync pass), the dev override, or locally known+ * team spaces.*/export function useTeamSpacesCapability(): boolean {const spaces = useSpaces();- return hasTeamSpacesDevOverride() || spaces.some((space) => space.kind === "team");+ return (+ hasTeamSpacesDevOverride() ||+ localStorage.getItem("teamSpacesCapability") === "true" ||+ spaces.some((space) => space.kind === "team")+ );}diff --git a/src/locales/de/translation.json b/src/locales/de/translation.jsonindex 55911d1da..aea4dd554 100644--- a/src/locales/de/translation.json+++ b/src/locales/de/translation.json@@ -2403,7 +2403,13 @@"undo": "Rückgängig","emptySpace": "Noch keine Notizen. Notizen hier sind für alle in {{space}} sichtbar.","noteCount_one": "{{count}} Notiz",- "noteCount_other": "{{count}} Notizen"+ "noteCount_other": "{{count}} Notizen",+ "accessRevoked": "Du hast keinen Zugriff mehr auf {{space}}",+ "movedToPersonal": "Du hast keinen Zugriff mehr auf {{space}} — „{{title}}“ wurde in deinen persönlichen Bereich verschoben",+ "conflictBanner": "Es existiert eine neuere Version dieser Notiz.",+ "conflictRefresh": "Aktualisieren",+ "conflictKeep": "Weiter bearbeiten",+ "editedBy": "Bearbeitet von {{name}} · {{time}}"},"folders": {"title": "Ordner",diff --git a/src/locales/en/translation.json b/src/locales/en/translation.jsonindex e2ac95db7..94323ba98 100644--- a/src/locales/en/translation.json+++ b/src/locales/en/translation.json@@ -2403,7 +2403,13 @@"undo": "Undo","emptySpace": "No notes yet. Notes here are visible to everyone in {{space}}.","noteCount_one": "{{count}} note",- "noteCount_other": "{{count}} notes"+ "noteCount_other": "{{count}} notes",+ "accessRevoked": "You no longer have access to {{space}}",+ "movedToPersonal": "You no longer have access to {{space}} — “{{title}}” was moved to your Personal space",+ "conflictBanner": "A newer version of this note exists.",+ "conflictRefresh": "Refresh",+ "conflictKeep": "Keep editing",+ "editedBy": "Edited by {{name}} · {{time}}"},"folders": {"title": "Folders",diff --git a/src/locales/es/translation.json b/src/locales/es/translation.jsonindex d25e8b603..d1fc0e042 100644--- a/src/locales/es/translation.json+++ b/src/locales/es/translation.json@@ -2245,7 +2245,13 @@"undo": "Deshacer","emptySpace": "Aún no hay notas. Las notas aquí son visibles para todos en {{space}}.","noteCount_one": "{{count}} nota",- "noteCount_other": "{{count}} notas"+ "noteCount_other": "{{count}} notas",+ "accessRevoked": "Ya no tienes acceso a {{space}}",+ "movedToPersonal": "Ya no tienes acceso a {{space}} — “{{title}}” se movió a tu espacio personal",+ "conflictBanner": "Existe una versión más reciente de esta nota.",+ "conflictRefresh": "Actualizar",+ "conflictKeep": "Seguir editando",+ "editedBy": "Editado por {{name}} · {{time}}"},"folders": {"title": "Carpetas",diff --git a/src/locales/fr/translation.json b/src/locales/fr/translation.jsonindex 265550a4b..e4f94d203 100644--- a/src/locales/fr/translation.json+++ b/src/locales/fr/translation.json@@ -2403,7 +2403,13 @@"undo": "Annuler","emptySpace": "Aucune note pour le moment. Les notes ici sont visibles par tous les membres de {{space}}.","noteCount_one": "{{count}} note",- "noteCount_other": "{{count}} notes"+ "noteCount_other": "{{count}} notes",+ "accessRevoked": "Vous n'avez plus accès à {{space}}",+ "movedToPersonal": "Vous n'avez plus accès à {{space}} — « {{title}} » a été déplacée vers votre espace personnel",+ "conflictBanner": "Une version plus récente de cette note existe.",+ "conflictRefresh": "Actualiser",+ "conflictKeep": "Continuer à modifier",+ "editedBy": "Modifié par {{name}} · {{time}}"},"folders": {"title": "Dossiers",diff --git a/src/locales/it/translation.json b/src/locales/it/translation.jsonindex fd4f6f211..c3a40db8e 100644--- a/src/locales/it/translation.json+++ b/src/locales/it/translation.json@@ -2197,7 +2197,13 @@"undo": "Annulla","emptySpace": "Ancora nessuna nota. Le note qui sono visibili a tutti in {{space}}.","noteCount_one": "{{count}} nota",- "noteCount_other": "{{count}} note"+ "noteCount_other": "{{count}} note",+ "accessRevoked": "Non hai più accesso a {{space}}",+ "movedToPersonal": "Non hai più accesso a {{space}} — “{{title}}” è stata spostata nel tuo spazio personale",+ "conflictBanner": "Esiste una versione più recente di questa nota.",+ "conflictRefresh": "Aggiorna",+ "conflictKeep": "Continua a modificare",+ "editedBy": "Modificato da {{name}} · {{time}}"},"folders": {"title": "Cartelle",diff --git a/src/locales/ja/translation.json b/src/locales/ja/translation.jsonindex dfa5d7361..91ed4995d 100644--- a/src/locales/ja/translation.json+++ b/src/locales/ja/translation.json@@ -2125,7 +2125,13 @@"undo": "元に戻す","emptySpace": "まだノートがありません。ここのノートは{{space}}の全員に表示されます。","noteCount_one": "{{count}} 件のノート",- "noteCount_other": "{{count}} 件のノート"+ "noteCount_other": "{{count}} 件のノート",+ "accessRevoked": "{{space}} へのアクセス権がなくなりました",+ "movedToPersonal": "{{space}} へのアクセス権がなくなったため、「{{title}}」は個人スペースに移動されました",+ "conflictBanner": "このノートには新しいバージョンがあります。",+ "conflictRefresh": "更新",+ "conflictKeep": "編集を続ける",+ "editedBy": "{{name}} が編集 · {{time}}"},"editor": {"transcribe": "文字起こし",diff --git a/src/locales/pt/translation.json b/src/locales/pt/translation.jsonindex d1e476bbf..0783065b6 100644--- a/src/locales/pt/translation.json+++ b/src/locales/pt/translation.json@@ -2197,7 +2197,13 @@"undo": "Desfazer","emptySpace": "Nenhuma nota ainda. As notas aqui são visíveis para todos em {{space}}.","noteCount_one": "{{count}} nota",- "noteCount_other": "{{count}} notas"+ "noteCount_other": "{{count}} notas",+ "accessRevoked": "Você não tem mais acesso a {{space}}",+ "movedToPersonal": "Você não tem mais acesso a {{space}} — “{{title}}” foi movida para o seu espaço pessoal",+ "conflictBanner": "Existe uma versão mais recente desta nota.",+ "conflictRefresh": "Atualizar",+ "conflictKeep": "Continuar editando",+ "editedBy": "Editado por {{name}} · {{time}}"},"folders": {"title": "Pastas",diff --git a/src/locales/ru/translation.json b/src/locales/ru/translation.jsonindex e05dbf7ce..b36c5d871 100644--- a/src/locales/ru/translation.json+++ b/src/locales/ru/translation.json@@ -2201,7 +2201,13 @@"noteCount_one": "{{count}} заметка","noteCount_few": "{{count}} заметки","noteCount_many": "{{count}} заметок",- "noteCount_other": "{{count}} заметки"+ "noteCount_other": "{{count}} заметки",+ "accessRevoked": "У вас больше нет доступа к {{space}}",+ "movedToPersonal": "У вас больше нет доступа к {{space}} — «{{title}}» перемещена в ваше личное пространство",+ "conflictBanner": "Существует более новая версия этой заметки.",+ "conflictRefresh": "Обновить",+ "conflictKeep": "Продолжить редактирование",+ "editedBy": "Изменено: {{name}} · {{time}}"},"folders": {"title": "Папки",diff --git a/src/locales/zh-CN/translation.json b/src/locales/zh-CN/translation.jsonindex 4100f3376..eb5578a83 100644--- a/src/locales/zh-CN/translation.json+++ b/src/locales/zh-CN/translation.json@@ -2197,7 +2197,13 @@"undo": "撤销","emptySpace": "还没有笔记。这里的笔记对 {{space}} 中的所有人可见。","noteCount_one": "{{count}} 条笔记",- "noteCount_other": "{{count}} 条笔记"+ "noteCount_other": "{{count}} 条笔记",+ "accessRevoked": "你已无法访问 {{space}}",+ "movedToPersonal": "你已无法访问 {{space}},“{{title}}”已移至你的个人空间",+ "conflictBanner": "此笔记存在更新的版本。",+ "conflictRefresh": "刷新",+ "conflictKeep": "继续编辑",+ "editedBy": "由 {{name}} 编辑 · {{time}}"},"folders": {"title": "文件夹",diff --git a/src/locales/zh-TW/translation.json b/src/locales/zh-TW/translation.jsonindex e74bf88d0..46021a94b 100644--- a/src/locales/zh-TW/translation.json+++ b/src/locales/zh-TW/translation.json@@ -2197,7 +2197,13 @@"undo": "復原","emptySpace": "還沒有筆記。這裡的筆記對 {{space}} 中的所有人可見。","noteCount_one": "{{count}} 則筆記",- "noteCount_other": "{{count}} 則筆記"+ "noteCount_other": "{{count}} 則筆記",+ "accessRevoked": "你已無法存取 {{space}}",+ "movedToPersonal": "你已無法存取 {{space}},「{{title}}」已移至你的個人空間",+ "conflictBanner": "此筆記有更新的版本。",+ "conflictRefresh": "重新整理",+ "conflictKeep": "繼續編輯",+ "editedBy": "由 {{name}} 編輯 · {{time}}"},"folders": {"title": "資料夾",diff --git a/src/services/FoldersService.ts b/src/services/FoldersService.tsindex 11cb98b9c..6ccdd3041 100644--- a/src/services/FoldersService.ts+++ b/src/services/FoldersService.ts@@ -5,6 +5,8 @@ interface FolderInput {client_folder_id?: string;is_default?: boolean;sort_order?: number;+ workspace_id?: string | null;+ team_id?: string | null;}interface CloudFolder {@@ -13,6 +15,12 @@ interface CloudFolder {name: string;is_default: boolean;sort_order: number;+ workspace_id: string | null;+ team_id: string | null;+ previous_team_id?: string | null;+ // Redacted stub for a row that moved out of one of the caller's teams —+ // only id/client_folder_id/scope/updated_at are present.+ access_removed?: boolean;deleted_at: string | null;created_at: string;updated_at: string;@@ -34,9 +42,12 @@ async function deleteFolder(id: string): Promise<void> {await cloudDelete("/api/folders/delete", { id });}-async function list(since?: string): Promise<{ folders: CloudFolder[] }> {- const query = since ? `?since=${encodeURIComponent(since)}` : "";- return cloudGet<{ folders: CloudFolder[] }>(`/api/folders/list${query}`);+async function list(since?: string, scope?: "all"): Promise<{ folders: CloudFolder[] }> {+ const params = new URLSearchParams();+ if (since !== undefined) params.set("since", since);+ if (scope !== undefined) params.set("scope", scope);+ const query = params.toString();+ return cloudGet<{ folders: CloudFolder[] }>(`/api/folders/list${query ? `?${query}` : ""}`);}export { create, batchCreate, update, deleteFolder, list };diff --git a/src/services/NotesService.ts b/src/services/NotesService.tsindex eda977db5..575b0ce99 100644--- a/src/services/NotesService.ts+++ b/src/services/NotesService.ts@@ -2,6 +2,8 @@ import { cloudGet, cloudPost, cloudPatch, cloudDelete } from "./cloudApi.js";interface NoteInput {client_note_id?: string;+ workspace_id?: string | null;+ team_id?: string | null;title?: string | null;content?: string;enhanced_content?: string | null;@@ -20,7 +22,7 @@ interface NoteInput {updated_at?: string;}-interface CloudNote {+export interface CloudNote {id: string;client_note_id: string | null;title: string | null;@@ -37,6 +39,13 @@ interface CloudNote {calendar_event_id: string | null;diarization_enabled: number | null;expected_speaker_count: number | null;+ workspace_id: string | null;+ team_id: string | null;+ updated_by_user_id: string | null;+ previous_team_id?: string | null;+ // Redacted stub for a row that moved out of one of the caller's teams —+ // only id/client_note_id/scope/updated_at are present.+ access_removed?: boolean;deleted_at: string | null;created_at: string;updated_at: string;@@ -70,12 +79,14 @@ async function deleteNote(id: string): Promise<void> {async function list(limit?: number,before?: string,- since?: string+ since?: string,+ scope?: "all"): Promise<{ notes: CloudNote[] }> {const params = new URLSearchParams();if (limit !== undefined) params.set("limit", String(limit));if (before !== undefined) params.set("before", before);if (since !== undefined) params.set("since", since);+ if (scope !== undefined) params.set("scope", scope);const query = params.toString();return cloudGet<{ notes: CloudNote[] }>(`/api/notes/list${query ? `?${query}` : ""}`);}diff --git a/src/services/SyncService.ts b/src/services/SyncService.tsindex 318db1292..0542923b3 100644--- a/src/services/SyncService.ts+++ b/src/services/SyncService.ts@@ -1,12 +1,14 @@import type {NoteItem,FolderItem,+ SpaceItem,TranscriptionItem,ConversationPreview,} from "../types/electron";import { NotesService } from "./NotesService.js";import { ConversationsService } from "./ConversationsService.js";import { FoldersService } from "./FoldersService.js";+import { TeamsService, type MyTeam } from "./TeamsService.js";import { TranscriptionsService } from "./TranscriptionsService.js";import { DictionaryService } from "./DictionaryService.js";import { SnippetService, type CloudSnippetEntry } from "./SnippetService.js";@@ -16,6 +18,30 @@ function isHttpStatus(err: unknown, status: number): boolean {return err instanceof CloudApiError && err.status === status;}+// Typed errors from team write-access checks: membership revoked (403),+// team archived (410) or team gone (404).+function isTeamAccessError(err: unknown): boolean {+ return (+ err instanceof CloudApiError &&+ (err.code === "team_access_revoked" ||+ err.code === "team_archived" ||+ err.code === "team_not_found")+ );+}++// Extra fields pushed with note/folder payloads so the server files rows into+// the right team scope; `null` scope means the row must not push at all.+type PushScopeFields = { workspace_id?: string | null; team_id?: string | null };++// Per-pull-pass mapping of cloud teams to local spaces.+interface SpaceSyncContext {+ byId: Map<number, SpaceItem>;+ byCloudTeamId: Map<string, SpaceItem>;+ privateSpace: SpaceItem | null;+ // Guard: at most one mid-pass spaces re-pull per pass.+ refreshedSpaces: boolean;+}+const PUSH_DEBOUNCE_MS = 2000;const BATCH_SIZE = 50;const TRANSCRIPTION_BATCH_SIZE = 100;@@ -68,6 +94,47 @@ class SyncService {);}+ // Team-space membership, like sharing, is per-space consent: team content+ // syncs while signed in + subscribed even when cloud backup is off (D7).+ private canSyncTeamSpaces(): boolean {+ return this.canSyncSharedNotes();+ }++ // Whether the API supports team scope (GET /api/me/teams deployed); probed+ // by syncSpaces and cached for the UI gate (useTeamSpacesCapability).+ private hasTeamSpacesCapability(): boolean {+ return localStorage.getItem("teamSpacesCapability") === "true";+ }++ private cacheTeamSpacesCapability(available: boolean): void {+ localStorage.setItem("teamSpacesCapability", String(available));+ localStorage.setItem("teamSpacesCapability.probedAt", new Date().toISOString());+ }++ // Sign-out leaves no team content behind: purge every team space locally and+ // forget the capability probe + team cursors so the next account re-probes+ // and backfills from scratch. Never throws — a failed purge must not block+ // signing out.+ async purgeTeamSpacesForSignOut(): Promise<void> {+ try {+ const spaces = (await window.electronAPI.getSpaces?.()) ?? [];+ for (const space of spaces) {+ if (space.kind !== "team") continue;+ try {+ await window.electronAPI.purgeSpace?.(space.id);+ } catch (err) {+ console.error(`Purging space ${space.id} on sign-out failed:`, err);+ }+ }+ } catch (err) {+ console.error("Team space purge on sign-out failed:", err);+ }+ localStorage.removeItem("teamSpacesCapability");+ localStorage.removeItem("teamSpacesCapability.probedAt");+ localStorage.removeItem("lastSyncedAt.notes.team");+ localStorage.removeItem("lastSyncedAt.folders.team");+ }+// lastSyncedAt is written only when a syncAll() pass completes, and// localStorage is shared across windows, so it doubles as the global// "last completed sync" stamp for throttling.@@ -101,21 +168,8 @@ class SyncService {}async syncAll(waitForLock = false): Promise<void> {- if (!this.canSync()) {- // Backup is off, but deletes of cloud copies must still propagate so- // revoked/deleted notes stop being served (edits flow via debouncedPush).- if (this.canSyncSharedNotes() && !this.syncing) {- this.syncing = true;- try {- await this.pushNoteDeletes();- } catch (err) {- console.error("Shared note sync failed:", err);- } finally {- this.syncing = false;- }- }- return;- }+ const full = this.canSync();+ if (!full && !this.canSyncTeamSpaces()) return;// A pass already running may have synced past the data this request covers,// so flag a re-run instead of dropping it.if (this.syncing) {@@ -129,20 +183,29 @@ class SyncService {// Manual passes wait so a user action is never silently dropped.await navigator.locks.request(SYNC_ALL_LOCK, { ifAvailable: !waitForLock }, async (lock) => {if (!lock) return;- await this.syncFolders();- await this.syncNotes();- await this.syncConversations();- await this.syncTranscriptions();- // Edits during the awaits above set dictionaryDirty (syncing is already- // true), so re-run until clean rather than stalling until the next trigger.- do {- this.dictionaryDirty = false;- await this.syncDictionary();- } while (this.dictionaryDirty);- do {- this.snippetsDirty = false;- await this.syncSnippets();- } while (this.snippetsDirty);+ await this.syncSpaces();+ if (full) {+ await this.syncFolders();+ await this.syncNotes();+ await this.syncConversations();+ await this.syncTranscriptions();+ // Edits during the awaits above set dictionaryDirty (syncing is already+ // true), so re-run until clean rather than stalling until the next trigger.+ do {+ this.dictionaryDirty = false;+ await this.syncDictionary();+ } while (this.dictionaryDirty);+ do {+ this.snippetsDirty = false;+ await this.syncSnippets();+ } while (this.snippetsDirty);+ } else {+ // Backup is off: team-space content still syncs (membership is+ // consent, D7) and note deletes still propagate so revoked/deleted+ // shared notes stop being served (edits flow via debouncedPush).+ await this.syncFolders(true);+ await this.syncNotes(true);+ }localStorage.setItem("lastSyncedAt", new Date().toISOString());});} catch (err) {@@ -156,7 +219,9 @@ class SyncService {}}- requestSyncAll(reason: "start" | "focus" | "interval" | "online" | "manual"): void {+ requestSyncAll(+ reason: "start" | "focus" | "interval" | "online" | "manual" | "team-push"+ ): void {if (!this.canSync() && !this.canSyncSharedNotes()) return;if (reason !== "manual" &&@@ -223,10 +288,14 @@ class SyncService {private async pushEntity(entityType: string, entityId: number): Promise<void> {if (!this.canSync()) {- // Only shared notes may push without the global backup toggle.+ // Only shared notes and team-space notes push without the backup toggle.if (entityType !== "note" || !this.canSyncSharedNotes()) return;const note = await window.electronAPI.getNote?.(entityId);- if (!note?.is_shared) return;+ if (!note) return;+ if (!note.is_shared) {+ const ctx = await this.buildSpaceContext();+ if (ctx.byId.get(note.space_id)?.kind !== "team") return;+ }return this.pushNote(entityId);}switch (entityType) {@@ -252,63 +321,78 @@ class SyncService {sort_order: folder.sort_order,});} else {+ const ctx = await this.buildSpaceContext();+ 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`);+ return;+ }const cloud = await FoldersService.create({name: folder.name,client_folder_id: folder.client_folder_id,is_default: !!folder.is_default,sort_order: folder.sort_order,+ ...scope,});await window.electronAPI.markFolderSynced?.(folder.id, cloud.id);}}+ // Full note payload for pushes. Scope fields ride along so local moves+ // between spaces propagate; the server no-ops them when unchanged.+ private notePushPayload(note: NoteItem, cloudFolderId: string | null, scope: PushScopeFields) {+ return {+ title: note.title,+ content: note.content,+ enhanced_content: note.enhanced_content,+ enhancement_prompt: note.enhancement_prompt,+ enhanced_at_content_hash: note.enhanced_at_content_hash,+ note_type: note.note_type,+ source_file: note.source_file,+ audio_duration_seconds: note.audio_duration_seconds,+ transcript: note.transcript,+ participants: note.participants,+ calendar_event_id: note.calendar_event_id,+ diarization_enabled: note.diarization_enabled,+ expected_speaker_count: note.expected_speaker_count,+ folder_id: cloudFolderId,+ updated_at: note.updated_at,+ ...scope,+ };+ }+private async pushNote(id: number): Promise<void> {const note = await window.electronAPI.getNote?.(id);if (!note) return;const folderMap = await this.buildLocalToCloudFolderMap();+ 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;- if (note.cloud_id) {- await NotesService.update(note.cloud_id, {- title: note.title,- content: note.content,- enhanced_content: note.enhanced_content,- enhancement_prompt: note.enhancement_prompt,- enhanced_at_content_hash: note.enhanced_at_content_hash,- note_type: note.note_type,- source_file: note.source_file,- audio_duration_seconds: note.audio_duration_seconds,- transcript: note.transcript,- participants: note.participants,- calendar_event_id: note.calendar_event_id,- diarization_enabled: note.diarization_enabled,- expected_speaker_count: note.expected_speaker_count,- folder_id: cloudFolderId,- updated_at: note.updated_at,- });- } else {- const cloud = await NotesService.create({- client_note_id: note.client_note_id,- title: note.title,- content: note.content,- enhanced_content: note.enhanced_content,- enhancement_prompt: note.enhancement_prompt,- enhanced_at_content_hash: note.enhanced_at_content_hash,- note_type: note.note_type,- source_file: note.source_file,- audio_duration_seconds: note.audio_duration_seconds,- transcript: note.transcript,- participants: note.participants,- calendar_event_id: note.calendar_event_id,- diarization_enabled: note.diarization_enabled,- expected_speaker_count: note.expected_speaker_count,- folder_id: cloudFolderId,- created_at: note.created_at,- updated_at: note.updated_at,- });- await window.electronAPI.markNoteSynced?.(note.id, cloud.id);+ try {+ if (note.cloud_id) {+ await NotesService.update(note.cloud_id, this.notePushPayload(note, cloudFolderId, scope));+ } else {+ const cloud = await NotesService.create({+ client_note_id: note.client_note_id,+ ...this.notePushPayload(note, cloudFolderId, scope),+ created_at: note.created_at,+ });+ await window.electronAPI.markNoteSynced?.(note.id, cloud.id);+ }+ } catch (err) {+ if (!isTeamAccessError(err)) throw err;+ await this.handleRevokedNotePush(note, ctx);+ return;}+ // A push into a team must reach teammates fast; a pull may also carry+ // their concurrent edits back (throttled like other ambient triggers).+ if (scope.team_id) this.requestSyncAll("team-push");}// Sharing requires a cloud copy. Deliberate single-note push that does not@@ -366,11 +450,167 @@ class SyncService {await window.electronAPI.markTranscriptionSynced?.(t.id, cloud.id);}- private async syncFolders(): Promise<void> {- await this.adoptDefaultFolders();- await this.pushPendingFolders();- await this.pushFolderDeletes();- await this.pullFolders();+ // Runs first in every pass: probes team-spaces availability, mirrors the+ // caller's teams into local spaces, purges spaces whose teams vanished+ // (deleted, archived, or membership revoked) and backfills new ones.+ private async syncSpaces(): Promise<void> {+ if (!this.canSyncTeamSpaces()) return;+ let teams: MyTeam[];+ try {+ teams = await TeamsService.myTeams();+ } catch (err) {+ // 404 = endpoint not deployed yet (rollout probe): remember and skip+ // silently so pulls and pushes stay personal-only until a probe succeeds.+ if (isHttpStatus(err, 404)) this.cacheTeamSpacesCapability(false);+ else console.error("Teams fetch failed:", err);+ return;+ }+ this.cacheTeamSpacesCapability(true);++ 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);+ this.dispatchSpaceRevoked(space.name);+ }++ if (backfillIds.length > 0) {+ // scope=all returns pre-existing team rows only when `since` is unset,+ // so a full snapshot pull is the simplest correct backfill for a space+ // that just appeared (v1). Spaces stay 'pending' until it completes so+ // the tree shows skeletons — and so an interrupted backfill re-runs.+ const teamOnly = !this.canSync();+ const pulled =+ (await this.pullFolders(teamOnly, true)) && (await this.pullNotes(teamOnly, true));+ if (pulled) {+ for (const id of backfillIds) {+ await window.electronAPI.setSpaceSyncStatus?.(id, "synced");+ }+ }+ }+ }++ // Upserts cloud teams into local spaces. Returns local ids of spaces that+ // still need a content backfill: brand new, or left 'pending' by a backfill+ // that never finished.+ private async upsertTeamSpaces(teams: MyTeam[], prior: SpaceItem[]): Promise<number[]> {+ const priorByCloudId = new Map(+ prior.filter((s) => s.cloud_team_id).map((s) => [s.cloud_team_id!, s])+ );+ const backfillIds: number[] = [];+ for (const team of teams) {+ const existing = priorByCloudId.get(team.id);+ const space = await window.electronAPI.upsertSpaceFromCloud?.(+ team as unknown as Record<string, unknown>+ );+ if (space && (!existing || existing.sync_status === "pending")) {+ // The upsert marks rows synced; flag the space back to pending until+ // its content backfill completes.+ await window.electronAPI.setSpaceSyncStatus?.(space.id, "pending");+ backfillIds.push(space.id);+ }+ }+ return backfillIds;+ }++ private async buildSpaceContext(): Promise<SpaceSyncContext> {+ const spaces = (await window.electronAPI.getSpaces?.()) ?? [];+ return {+ byId: new Map(spaces.map((s) => [s.id, s])),+ byCloudTeamId: new Map(+ spaces.filter((s) => s.cloud_team_id).map((s) => [s.cloud_team_id!, s])+ ),+ privateSpace: spaces.find((s) => s.kind === "private") ?? null,+ refreshedSpaces: false,+ };+ }++ // Maps a cloud row's team to its local space (team_id null → private space).+ // An unknown team means we were added to it mid-pass: re-pull spaces once,+ // then park still-unmapped rows — team content never files into Personal.+ private async resolveSpaceForCloudRow(+ teamId: string | null | undefined,+ ctx: SpaceSyncContext+ ): Promise<SpaceItem | null> {+ if (!teamId) return ctx.privateSpace;+ const known = ctx.byCloudTeamId.get(teamId);+ if (known) return known;+ if (ctx.refreshedSpaces) return null;+ ctx.refreshedSpaces = true;+ try {+ const teams = await TeamsService.myTeams();+ const prior = (await window.electronAPI.getSpaces?.()) ?? [];+ // New spaces stay 'pending' so the next spaces pass backfills their+ // pre-existing content (this delta pull only sees rows past the cursor).+ await this.upsertTeamSpaces(teams, prior);+ } catch (err) {+ console.error("Mid-pass spaces refresh failed:", err);+ return null;+ }+ const fresh = await this.buildSpaceContext();+ ctx.byId = fresh.byId;+ ctx.byCloudTeamId = fresh.byCloudTeamId;+ ctx.privateSpace = fresh.privateSpace;+ return ctx.byCloudTeamId.get(teamId) ?? null;+ }++ // Scope fields for push payloads. Team rows carry their team identity; when+ // the server supports team scope, personal rows send explicit nulls so local+ // moves out of a team propagate (the server treats an absent team_id as+ // "keep the current scope"). Returns null for team rows that must not push:+ // spaces with no cloud team yet (local-only dev spaces), or a server that+ // no longer understands team scope and would file the row as personal.+ private pushScopeFields(space: SpaceItem | undefined): PushScopeFields | null {+ if (space?.kind === "team") {+ if (!space.cloud_team_id || !this.hasTeamSpacesCapability()) return null;+ return { workspace_id: space.workspace_id, team_id: space.cloud_team_id };+ }+ return this.hasTeamSpacesCapability() ? { workspace_id: null, team_id: null } : {};+ }++ // A push was rejected because the note's team is gone or access was revoked+ // (plan §7.2): a row already on the server stays the team's — drop the local+ // copy; a row that never reached the server is the only content the client+ // keeps — move it to the private space so the next push creates it as+ // personal.+ private async handleRevokedNotePush(note: NoteItem, ctx: SpaceSyncContext): Promise<void> {+ const spaceName = ctx.byId.get(note.space_id)?.name ?? null;+ if (note.cloud_id) {+ await window.electronAPI.hardDeleteNote?.(note.id);+ this.dispatchSpaceRevoked(spaceName);+ } else if (ctx.privateSpace) {+ await window.electronAPI.updateNote(note.id, {+ space_id: ctx.privateSpace.id,+ folder_id: null,+ });+ this.dispatchNoteRelocated(note.title, spaceName);+ }+ }++ private dispatchSpaceRevoked(spaceName: string | null): void {+ window.dispatchEvent(+ new CustomEvent("openwhispr:space-revoked", { detail: { spaceName } })+ );+ }++ private dispatchNoteRelocated(title: string | null, spaceName: string | null | undefined): void {+ window.dispatchEvent(+ new CustomEvent("openwhispr:note-relocated", {+ detail: { title, spaceName: spaceName ?? null },+ })+ );+ }++ private async syncFolders(teamOnly = false): Promise<void> {+ if (!teamOnly) await this.adoptDefaultFolders();+ await this.pushPendingFolders(teamOnly);+ await this.pushFolderDeletes(teamOnly);+ await this.pullFolders(teamOnly);}// Each platform seeds "Personal"/"Meetings" with its own random@@ -379,7 +619,8 @@ class SyncService {// Before the first push, adopt the cloud identity of any same-named// default folder so both platforms converge on a single folder.private async adoptDefaultFolders(): Promise<void> {- const pending = (await window.electronAPI.getPendingFolders?.()) ?? [];+ // Private space only — team folders never adopt by name.+ const pending = (await window.electronAPI.getPendingFolders?.("private")) ?? [];const unlinkedDefaults = pending.filter((f) => f.is_default && !f.cloud_id);if (unlinkedDefaults.length === 0) return;@@ -405,28 +646,52 @@ class SyncService {}}- private async pushFolderDeletes(): Promise<void> {- const deletes = (await window.electronAPI.getPendingFolderDeletes?.()) ?? [];+ private async pushFolderDeletes(teamOnly = false): Promise<void> {+ let deletes = (await window.electronAPI.getPendingFolderDeletes?.()) ?? [];+ if (teamOnly && deletes.length > 0) {+ const { byId } = await this.buildSpaceContext();+ deletes = deletes.filter((f) => byId.get(f.space_id)?.kind === "team");+ }for (const f of deletes) {if (!f.cloud_id) continue;try {await FoldersService.delete(f.cloud_id);await window.electronAPI.hardDeleteFolder?.(f.id);} catch (err) {- console.error("Folder delete sync failed:", err);+ // 404 means the row is already gone server-side — clear the tombstone+ // instead of retrying forever (matches the dictionary precedent).+ if (isHttpStatus(err, 404)) {+ await window.electronAPI.hardDeleteFolder?.(f.id);+ } else {+ console.error("Folder delete sync failed:", err);+ }}}}- private async pushPendingFolders(): Promise<void> {- const pending = (await window.electronAPI.getPendingFolders?.()) ?? [];+ private async pushPendingFolders(teamOnly = false): Promise<void> {+ const pending =+ (await window.electronAPI.getPendingFolders?.(teamOnly ? "team" : undefined)) ?? [];if (pending.length === 0) return;- const migration = pending.filter((f) => f.cloud_id);- const fresh = pending.filter((f) => !f.cloud_id);+ const { byId } = 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 (!scope) {+ console.warn(`Skipping folder ${folder.id} push: its team space has no cloud team yet`);+ continue;+ }+ pushable.push({ folder, scope });+ }++ const migration = pushable.filter(({ folder }) => folder.cloud_id);+ const fresh = pushable.filter(({ folder }) => !folder.cloud_id);- for (const folder of migration) {+ for (const { folder } of migration) {try {+ // The folders update endpoint carries no scope fields — folder moves+ // between spaces don't propagate through PATCH in v1.await FoldersService.update(folder.cloud_id!, { name: folder.name });await window.electronAPI.markFolderSynced?.(folder.id, folder.cloud_id!);} catch (err) {@@ -437,11 +702,12 @@ class SyncService {if (fresh.length > 0) {try {const { created } = await FoldersService.batchCreate(- fresh.map((f) => ({- name: f.name,- client_folder_id: f.client_folder_id,- is_default: !!f.is_default,- sort_order: f.sort_order,+ fresh.map(({ folder, scope }) => ({+ name: folder.name,+ client_folder_id: folder.client_folder_id,+ is_default: !!folder.is_default,+ sort_order: folder.sort_order,+ ...scope,})));// created preserves input order; the cloud may return an existing@@ -454,7 +720,7 @@ class SyncService {return;}for (const [i, cloudFolder] of created.entries()) {- const local = fresh[i];+ const local = fresh[i].folder;if (cloudFolder.client_folder_id &&cloudFolder.client_folder_id !== local.client_folder_id@@ -475,29 +741,72 @@ class SyncService {}}- private async pullFolders(): Promise<void> {+ private async pullFolders(teamOnly = false, snapshot = false): Promise<boolean> {try {- const since = localStorage.getItem("lastSyncedAt.folders") ?? undefined;+ const cursorKey = teamOnly ? "lastSyncedAt.folders.team" : "lastSyncedAt.folders";+ const since = snapshot ? undefined : (localStorage.getItem(cursorKey) ?? undefined);const syncStartedAt = new Date().toISOString();- const { folders: cloudFolders } = await FoldersService.list(since);+ const scope = this.canSyncTeamSpaces() && this.hasTeamSpacesCapability() ? "all" : undefined;+ const { folders: cloudFolders } = await FoldersService.list(since, scope);+ const ctx = await this.buildSpaceContext();for (const cloudFolder of cloudFolders) {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+ );+ } else {+ console.warn(`Could not relocate revoked folder ${local.id}:`, moved?.error);+ }+ } else {+ await window.electronAPI.hardDeleteFolder?.(local.id);+ }+ continue;+ }++ if (teamOnly && !cloudFolder.team_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;+ }+// A default folder created on another platform arrives with an- // unknown client_folder_id; inserting it would violate the local- // unique folder name. Match it by name and adopt its identity.- if (!local && cloudFolder.is_default) {+ // 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.name.toLowerCase() === cloudFolder.name.toLowerCase()+ (f) =>+ f.is_default &&+ f.space_id === space.id &&+ f.name.toLowerCase() === cloudFolder.name.toLowerCase());if (nameMatch) {await window.electronAPI.adoptFolderIdentity?.(@@ -513,37 +822,72 @@ class SyncService {if (local?.deleted_at) continue;if (!local || cloudFolder.updated_at > local.updated_at) {await window.electronAPI.upsertFolderFromCloud?.(- cloudFolder as unknown as Record<string, unknown>+ cloudFolder as unknown as Record<string, unknown>,+ space.id);}}- localStorage.setItem("lastSyncedAt.folders", syncStartedAt);+ // 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);+ }+ return true;} catch (err) {console.error("Folder pull failed:", err);+ return false;}}- private async syncNotes(): Promise<void> {- await this.pushPendingNotes();+ private async syncNotes(teamOnly = false): Promise<void> {+ await this.pushPendingNotes(teamOnly);await this.pushNoteDeletes();- await this.pullNotes();+ await this.pullNotes(teamOnly);}- private async pushPendingNotes(): Promise<void> {- const pending = (await window.electronAPI.getPendingNotes?.()) ?? [];+ private async pushPendingNotes(teamOnly = false): Promise<void> {+ const pending =+ (await window.electronAPI.getPendingNotes?.(teamOnly ? "team" : undefined)) ?? [];if (pending.length === 0) return;const folderMap = await this.buildLocalToCloudFolderMap();- const migration = pending.filter((n) => n.cloud_id);- const fresh = pending.filter((n) => !n.cloud_id);+ const ctx = await this.buildSpaceContext();+ const pushable: Array<{ note: NoteItem; scope: PushScopeFields }> = [];+ for (const note of pending) {+ 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`);+ continue;+ }+ pushable.push({ note, scope });+ }++ const migration = pushable.filter(({ note }) => note.cloud_id);+ const fresh = pushable.filter(({ note }) => !note.cloud_id);- for (const note of migration) {+ for (const { note, scope } of migration) {try {- await NotesService.update(note.cloud_id!, { client_note_id: note.client_note_id });+ // Carry the full content: a pending row may hold edits that never+ // reached the server (offline debounced pushes fail silently), and+ // 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;+ 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!);- } catch {- await window.electronAPI.markNoteSyncError?.(note.id);+ } catch (err) {+ if (isTeamAccessError(err)) {+ await this.handleRevokedNotePush(note, ctx);+ } else {+ await window.electronAPI.markNoteSyncError?.(note.id);+ }}}@@ -551,7 +895,7 @@ class SyncService {const chunk = fresh.slice(i, i + BATCH_SIZE);try {const { created } = await NotesService.batchCreate(- chunk.map((n) => ({+ chunk.map(({ note: n, scope }) => ({client_note_id: n.client_note_id,title: n.title,content: n.content,@@ -565,15 +909,16 @@ class SyncService {folder_id: n.folder_id ? (folderMap.get(n.folder_id) ?? undefined) : undefined,created_at: n.created_at,updated_at: n.updated_at,+ ...scope,})));for (const { client_note_id, id: cloudId } of created) {- const local = chunk.find((n) => n.client_note_id === client_note_id);- if (local) await window.electronAPI.markNoteSynced?.(local.id, cloudId);+ const local = chunk.find(({ note }) => note.client_note_id === client_note_id);+ if (local) await window.electronAPI.markNoteSynced?.(local.note.id, cloudId);}} catch {- for (const n of chunk) {- await window.electronAPI.markNoteSyncError?.(n.id);+ for (const { note } of chunk) {+ await window.electronAPI.markNoteSyncError?.(note.id);}}}@@ -589,22 +934,33 @@ class SyncService {await NotesService.delete(note.cloud_id!);await window.electronAPI.hardDeleteNote?.(note.id);} catch (err) {- console.error("Note delete sync failed:", err);+ // 404 means the row is already gone server-side — clear the tombstone+ // instead of retrying forever (matches the dictionary precedent).+ if (isHttpStatus(err, 404)) {+ await window.electronAPI.hardDeleteNote?.(note.id);+ } else {+ console.error("Note delete sync failed:", err);+ }}}}- private async pullNotes(): Promise<void> {+ private async pullNotes(teamOnly = false, snapshot = false): Promise<boolean> {try {- const since = localStorage.getItem("lastSyncedAt.notes") ?? undefined;+ const cursorKey = teamOnly ? "lastSyncedAt.notes.team" : "lastSyncedAt.notes";+ const since = snapshot ? undefined : (localStorage.getItem(cursorKey) ?? undefined);const syncStartedAt = new Date().toISOString();- const { cloudToLocal, defaultFolderId } = await this.buildCloudToLocalFolderMap();+ const ctx = await this.buildSpaceContext();+ const { cloudToLocal, defaultFolderId } = await this.buildCloudToLocalFolderMap(+ ctx.privateSpace?.id ?? null+ );+ const scope = this.canSyncTeamSpaces() && this.hasTeamSpacesCapability() ? "all" : undefined;let cursor: string | undefined = since;while (true) {const { notes: cloudNotes } = since- ? await NotesService.list(BATCH_SIZE, undefined, cursor)- : await NotesService.list(BATCH_SIZE, cursor);+ ? await NotesService.list(BATCH_SIZE, undefined, cursor, scope)+ : await NotesService.list(BATCH_SIZE, cursor, undefined, scope);if (cloudNotes.length === 0) break;for (const cloudNote of cloudNotes) {@@ -612,19 +968,73 @@ class SyncService {cloudNote.client_note_id ?? "");+ // Redacted stub: the note 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 (cloudNote.access_removed) {+ if (!local) continue;+ if (local.sync_status === "pending" && !local.deleted_at && ctx.privateSpace) {+ // Already-private rows were just relocated by their folder's+ // stub — keep their folder link, only fork identity: the server+ // row now belongs to a scope we can't write, so pushing under+ // the old ids would be rejected (or hard-deleted) forever. The+ // next push creates the note as a new personal one.+ const alreadyPrivate = local.space_id === ctx.privateSpace.id;+ await window.electronAPI.updateNote(local.id, {+ ...(alreadyPrivate ? {} : { space_id: ctx.privateSpace.id, folder_id: null }),+ client_note_id: crypto.randomUUID(),+ cloud_id: null,+ });+ if (!alreadyPrivate) {+ this.dispatchNoteRelocated(+ local.title,+ ctx.byCloudTeamId.get(cloudNote.previous_team_id ?? "")?.name+ );+ }+ } else {+ await window.electronAPI.hardDeleteNote?.(local.id);+ }+ continue;+ }++ if (teamOnly && !cloudNote.team_id) continue;+if (cloudNote.deleted_at) {if (local) await window.electronAPI.hardDeleteNote?.(local.id);continue;}+ const space = await this.resolveSpaceForCloudRow(cloudNote.team_id, ctx);+ if (!space) {+ console.warn(`Parking note ${cloudNote.id}: unknown team ${cloudNote.team_id}`);+ continue;+ }+if (!local || cloudNote.updated_at > 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);+ 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) ?? defaultFolderId)- : defaultFolderId;+ ? (cloudToLocal.get(cloudNote.folder_id) ?? fallbackFolderId)+ : fallbackFolderId;await window.electronAPI.upsertNoteFromCloud?.(cloudNote as unknown as Record<string, unknown>,- localFolderId+ localFolderId,+ 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);+ }}}@@ -635,9 +1045,18 @@ class SyncService {cursor = next;}- localStorage.setItem("lastSyncedAt.notes", syncStartedAt);+ // 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);+ }+ return true;} catch (err) {console.error("Note pull failed:", err);+ return false;}}@@ -1226,13 +1645,15 @@ class SyncService {return new Map(folders.filter((f) => f.cloud_id).map((f) => [f.id, f.cloud_id!]));}- private async buildCloudToLocalFolderMap(): Promise<{+ private async buildCloudToLocalFolderMap(privateSpaceId: number | null): Promise<{cloudToLocal: Map<string, 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 personalFolder = folders.find((f) => f.is_default && f.name === "Personal");+ const personalFolder = folders.find(+ (f) => f.is_default && f.name === "Personal" && f.space_id === privateSpaceId+ );return { cloudToLocal, defaultFolderId: personalFolder?.id ?? null };}}diff --git a/src/services/TeamsService.ts b/src/services/TeamsService.tsindex db0f3ef5f..666942f25 100644--- a/src/services/TeamsService.ts+++ b/src/services/TeamsService.ts@@ -5,6 +5,26 @@ interface DataWrap<T> {data: T;}+export interface MyTeam {+ id: string;+ workspace_id: string;+ name: string;+ slug: string;+ description: string | null;+ emoji: string | null;+ my_role: "admin" | "member";+ member_count: number;+ created_at: string;+ updated_at: string;+}++// Every team the caller can access across all their workspaces (explicit+// membership or implicit workspace owner/admin). Drives the spaces sync pass.+async function myTeams(): Promise<MyTeam[]> {+ const res = await cloudGet<DataWrap<MyTeam[]>>("/api/me/teams");+ return res.data;+}+async function list(workspaceId: string): Promise<Team[]> {const res = await cloudGet<DataWrap<Team[]>>(`/api/workspaces/${workspaceId}/teams`);return res.data;@@ -48,6 +68,7 @@ async function removeMember(teamId: string, userId: string): Promise<void> {}export const TeamsService = {+ myTeams,list,create,update,diff --git a/src/stores/noteStore.ts b/src/stores/noteStore.tsindex 87effbbb6..c24097362 100644--- a/src/stores/noteStore.ts+++ b/src/stores/noteStore.ts@@ -1,6 +1,7 @@import { create } from "zustand";import { syncService } from "../services/SyncService.js";import { findDefaultFolder } from "../components/notes/shared";+import type { CloudNote } from "../services/NotesService.js";import type {FolderItem,NoteItem,@@ -35,6 +36,9 @@ interface NoteState {isTreeLoading: boolean;migration: { total: number; done: number } | null;shareByCloudId: Map<string, NoteShareCacheEntry>;+ // Cloud versions that arrived while the local row had unpushed edits,+ // keyed by client_note_id. Consumed by the editor's conflict banner.+ noteConflicts: Record<string, CloudNote>;}const EXPANDED_STORAGE_KEY = "notesTree.expanded";@@ -69,6 +73,7 @@ const useNoteStore = create<NoteState>()(() => ({isTreeLoading: true,migration: null,shareByCloudId: new Map<string, NoteShareCacheEntry>(),+ noteConflicts: {},}));let hasBoundIpcListeners = false;@@ -151,9 +156,13 @@ function ensureIpcListeners() {if (previous && noteContainerKey(previous) !== noteContainerKey(note)) {loadFolders();}- // Sharing is per-note consent: edits to a shared note must reach the- // cloud even when the global backup toggle is off.- if (note.is_shared) {+ // 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).+ const spaceKind = useNoteStore+ .getState()+ .spaces.find((s) => s.id === note.space_id)?.kind;+ if (note.is_shared || spaceKind === "team") {syncService.debouncedPush("note", note.id);}}@@ -708,6 +717,25 @@ export async function startMigration(): Promise<void> {useNoteStore.setState({ migration: null });}+export function setNoteConflict(clientNoteId: string, cloudNote: CloudNote): void {+ const { noteConflicts } = useNoteStore.getState();+ useNoteStore.setState({ noteConflicts: { ...noteConflicts, [clientNoteId]: cloudNote } });+}++export function clearNoteConflict(clientNoteId: string): void {+ const { noteConflicts } = useNoteStore.getState();+ if (!(clientNoteId in noteConflicts)) return;+ const next = { ...noteConflicts };+ delete next[clientNoteId];+ useNoteStore.setState({ noteConflicts: next });+}++export function useNoteConflict(clientNoteId: string | null): CloudNote | null {+ return useNoteStore((state) =>+ clientNoteId ? (state.noteConflicts[clientNoteId] ?? null) : null+ );+}+export async function persistNoteShareState(noteId: number,updates: { is_shared: number; share_token?: string | null }diff --git a/src/types/electron.ts b/src/types/electron.tsindex 3b55e656e..5c75e3e47 100644--- a/src/types/electron.ts+++ b/src/types/electron.ts@@ -651,6 +651,8 @@ declare global {participants?: string | null;diarization_enabled?: number | null;expected_speaker_count?: number | null;+ client_note_id?: string;+ cloud_id?: string | null;}) => Promise<{ success: boolean; note?: NoteItem }>;deleteNote: (id: number) => Promise<{ success: boolean }>;@@ -716,6 +718,10 @@ declare global {}>;getSpaceByCloudTeamId?: (cloudTeamId: string) => Promise<SpaceItem | null>;upsertSpaceFromCloud?: (team: Record<string, unknown>) => Promise<SpaceItem>;+ setSpaceSyncStatus?: (+ id: number,+ status: SpaceItem["sync_status"]+ ) => Promise<{ success: boolean }>;onSpacePurged?: (callback: (payload: { spaceId: number }) => void) => () => void;// Note files (markdown mirror)@@ -1982,7 +1988,7 @@ declare global {sendDictationPreviewAudio?: (data: ArrayBuffer) => void;// Sync operations- getPendingNotes?: () => Promise<NoteItem[]>;+ getPendingNotes?: (spaceKind?: "private" | "team") => Promise<NoteItem[]>;getPendingNoteDeletes?: () => Promise<NoteItem[]>;getNoteByClientId?: (clientNoteId: string) => Promise<NoteItem | null>;upsertNoteFromCloud?: (@@ -1994,7 +2000,7 @@ declare global {markNoteSyncError?: (id: number) => Promise<void>;hardDeleteNote?: (id: number) => Promise<void>;- getPendingFolders?: () => Promise<FolderItem[]>;+ getPendingFolders?: (spaceKind?: "private" | "team") => Promise<FolderItem[]>;getFolderByClientId?: (clientFolderId: string) => Promise<FolderItem | null>;upsertFolderFromCloud?: (cloudFolder: Record<string, unknown>,@@ -2007,6 +2013,7 @@ declare global {cloudId: string,updatedAt?: string) => Promise<void>;+ forkFolderIdentity?: (id: number) => Promise<{ success: boolean }>;getFolderIdMap?: () => Promise<FolderItem[]>;getPendingFolderDeletes?: () => Promise<FolderItem[]>;hardDeleteFolder?: (id: number) => Promise<{ success: boolean; id: number }>;diff --git a/src/utils/dateFormatting.ts b/src/utils/dateFormatting.tsindex 1764877e1..d3a535a8f 100644--- a/src/utils/dateFormatting.ts+++ b/src/utils/dateFormatting.ts@@ -3,6 +3,23 @@ export function normalizeDbDate(dateStr: string): Date {return new Date(source);}+export function formatRelativeTime(+ dateStr: string,+ t: (key: string, options?: Record<string, unknown>) => string+): string {+ const date = normalizeDbDate(dateStr);+ if (Number.isNaN(date.getTime())) return "";+ const diff = Date.now() - date.getTime();+ const minutes = Math.floor(diff / 60000);+ const hours = Math.floor(diff / 3600000);+ const days = Math.floor(diff / 86400000);+ if (minutes < 1) return t("notes.list.timeNow");+ if (minutes < 60) return t("notes.list.minutesAgo", { count: minutes });+ if (hours < 24) return t("notes.list.hoursAgo", { count: hours });+ if (days < 7) return t("notes.list.daysAgo", { count: days });+ return date.toLocaleDateString(undefined, { month: "short", day: "numeric" });+}+export function formatUpcomingDateGroup(date: Date | string, t: (key: string) => string): string {const d = typeof date === "string" ? new Date(date) : date;const now = new Date();diff --git a/test/helpers/spacesDatabase.test.js b/test/helpers/spacesDatabase.test.jsindex d6f067d37..c203a6afc 100644--- a/test/helpers/spacesDatabase.test.js+++ b/test/helpers/spacesDatabase.test.js@@ -327,3 +327,48 @@ test("getNotes with spaceId and no folderId lists only the space's root notes",assert.equal(folderNotes.length, 1);assert.equal(folderNotes[0].title, "Filed");});++test("pending queues split by space kind", (t) => {+ const db = createDb(t);+ if (!db) return;+ const team = db.createSpace({ name: "Sales" }).space;+ const privateFolder = db.createFolder("Ideas").folder;+ const teamFolder = db.createFolder("Pipeline", team.id).folder;+ const privateNote = db.saveNote("Mine", "body").note;+ const teamNote = db.saveNote("Ours", "body", "personal", null, null, null, team.id).note;++ assert.deepEqual(+ db.getPendingNotes("team").map((n) => n.id),+ [teamNote.id]+ );+ assert.ok(db.getPendingNotes("private").some((n) => n.id === privateNote.id));+ assert.ok(!db.getPendingNotes("private").some((n) => n.id === teamNote.id));+ assert.equal(+ db.getPendingNotes().length,+ db.getPendingNotes("private").length + db.getPendingNotes("team").length+ );++ assert.deepEqual(+ db.getPendingFolders("team").map((f) => f.id),+ [teamFolder.id]+ );+ assert.ok(db.getPendingFolders("private").some((f) => f.id === privateFolder.id));+ assert.equal(+ db.getPendingFolders().length,+ db.getPendingFolders("private").length + db.getPendingFolders("team").length+ );+});++test("setSpaceSyncStatus flips a space's sync_status", (t) => {+ const db = createDb(t);+ if (!db) return;+ const team = db.createSpace({ name: "Docs" }).space;++ assert.ok(db.setSpaceSyncStatus(team.id, "synced").success);+ assert.equal(db.getSpaces().find((s) => s.id === team.id).sync_status, "synced");++ assert.ok(db.setSpaceSyncStatus(team.id, "pending").success);+ assert.equal(db.getSpaces().find((s) => s.id === team.id).sync_status, "pending");++ assert.equal(db.setSpaceSyncStatus(99999, "synced").success, false);+});