Skip to content

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

feat: Added localized mutation error mapping and improved test coverage

Chadpihaa00d37a8e124
diff --git a/preload.js b/preload.js
index 2305e1cbb..efa84be27 100644
--- a/preload.js
+++ b/preload.js
@@ -147,8 +147,6 @@ contextBridge.exposeInMainWorld("electronAPI", {
getSpaces: () => ipcRenderer.invoke("db-get-spaces"),
updateSpace: (id, updates) => ipcRenderer.invoke("db-update-space", id, updates),
purgeSpace: (id) => ipcRenderer.invoke("db-purge-space", id),
- getSpaceByCloudSpaceId: (cloudSpaceId) =>
- ipcRenderer.invoke("db-get-space-by-cloud-space-id", cloudSpaceId),
upsertSpaceFromCloud: (space) => ipcRenderer.invoke("db-upsert-space-from-cloud", space),
setSpaceSyncStatus: (id, status) => ipcRenderer.invoke("db-set-space-sync-status", id, status),
onSpacePurged: (callback) => {
@@ -932,7 +930,6 @@ contextBridge.exposeInMainWorld("electronAPI", {
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),
diff --git a/src/components/notes/SpacesTree.tsx b/src/components/notes/SpacesTree.tsx
index 65b2a2210..503545b23 100644
--- a/src/components/notes/SpacesTree.tsx
+++ b/src/components/notes/SpacesTree.tsx
@@ -45,6 +45,7 @@ import { useWorkspace } from "../../hooks/useWorkspace";
import { EmojiPickerInput } from "./EmojiPickerInput";
import { canManageSpace, canMoveBetweenSpaces } from "../../lib/spacePermissions";
import { groupTeamSpacesByWorkspace } from "../../lib/workspaceSelection";
+import { localMutationErrorKey } from "../../lib/localMutationError";
import { readIsSubscribed, subscribeIsSubscribed } from "../../lib/subscriptionFlag";
import { deleteSpace, renameSpace } from "../../services/spaceActions";
import { useSettingsStore } from "../../stores/settingsStore";
@@ -1301,7 +1302,7 @@ export default function SpacesTree({
if (!result.success) {
toast({
title: t("notes.spaces.couldNotMove"),
- description: result.error,
+ description: t(localMutationErrorKey(result.error)),
variant: "destructive",
});
}
@@ -1456,7 +1457,7 @@ export default function SpacesTree({
if (!result.success && result.error) {
toast({
title: t("notes.folders.couldNotDelete"),
- description: result.error,
+ description: t(localMutationErrorKey(result.error)),
variant: "destructive",
});
}
@@ -1473,7 +1474,7 @@ export default function SpacesTree({
if (!result.success) {
toast({
title: t("notes.spaces.couldNotDelete"),
- description: result.error ?? t("common.unknownError"),
+ description: t(localMutationErrorKey(result.error)),
variant: "destructive",
});
return;
@@ -1586,7 +1587,7 @@ export default function SpacesTree({
if (result.error) {
toast({
title: t("notes.folders.couldNotCreate"),
- description: result.error,
+ description: t(localMutationErrorKey(result.error)),
variant: "destructive",
});
}
@@ -1603,7 +1604,7 @@ export default function SpacesTree({
if (!result.success && result.error) {
toast({
title: t("notes.folders.couldNotRename"),
- description: result.error,
+ description: t(localMutationErrorKey(result.error)),
variant: "destructive",
});
}
@@ -1622,7 +1623,7 @@ export default function SpacesTree({
if (!result.success) {
toast({
title: t("notes.spaces.couldNotRename"),
- description: result.error ?? t("common.unknownError"),
+ description: t(localMutationErrorKey(result.error)),
variant: "destructive",
});
return;
diff --git a/src/helpers/ipcHandlers.js b/src/helpers/ipcHandlers.js
index 05646d264..b8eb36bed 100644
--- a/src/helpers/ipcHandlers.js
+++ b/src/helpers/ipcHandlers.js
@@ -1760,9 +1760,6 @@ 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()
@@ -1819,9 +1816,6 @@ class IPCHandlers {
});
// Spaces sync
- ipcMain.handle("db-get-space-by-cloud-space-id", (_, cloudSpaceId) =>
- this.databaseManager.getSpaceByCloudSpaceId(cloudSpaceId)
- );
ipcMain.handle("db-upsert-space-from-cloud", (_, cloudSpace) => {
const space = this.databaseManager.upsertSpaceFromCloud(cloudSpace);
if (space) setImmediate(() => this.broadcastToWindows("space-synced", space));
diff --git a/src/lib/localMutationError.ts b/src/lib/localMutationError.ts
new file mode 100644
index 000000000..74191e6bf
--- /dev/null
+++ b/src/lib/localMutationError.ts
@@ -0,0 +1,31 @@
+export type LocalMutationErrorKey =
+ | "notes.mutationErrors.folderNameRequired"
+ | "notes.mutationErrors.folderAlreadyExists"
+ | "notes.mutationErrors.folderNotFound"
+ | "notes.mutationErrors.defaultFolderImmutable"
+ | "notes.mutationErrors.spaceNameRequired"
+ | "notes.mutationErrors.spaceNotFound"
+ | "notes.mutationErrors.privateSpaceImmutable"
+ | "notes.mutationErrors.generic";
+
+const ERROR_KEYS: Record<string, LocalMutationErrorKey> = {
+ "Folder name is required": "notes.mutationErrors.folderNameRequired",
+ "A folder with that name already exists": "notes.mutationErrors.folderAlreadyExists",
+ "Folder not found": "notes.mutationErrors.folderNotFound",
+ "Cannot delete default folders": "notes.mutationErrors.defaultFolderImmutable",
+ "Cannot rename default folders": "notes.mutationErrors.defaultFolderImmutable",
+ "Cannot move default folders": "notes.mutationErrors.defaultFolderImmutable",
+ "Space name is required": "notes.mutationErrors.spaceNameRequired",
+ "Space not found": "notes.mutationErrors.spaceNotFound",
+ "Cannot rename the private space": "notes.mutationErrors.privateSpaceImmutable",
+ "Cannot purge the private space": "notes.mutationErrors.privateSpaceImmutable",
+};
+
+/**
+ * Main-process/database messages are internal protocol details, not UI copy.
+ * Known validation failures get a specific translation; network and unknown
+ * errors deliberately collapse to a localized generic description.
+ */
+export function localMutationErrorKey(error: string | null | undefined): LocalMutationErrorKey {
+ return (error && ERROR_KEYS[error]) || "notes.mutationErrors.generic";
+}
diff --git a/src/locales/de/translation.json b/src/locales/de/translation.json
index 3c4a3c780..10a043e52 100644
--- a/src/locales/de/translation.json
+++ b/src/locales/de/translation.json
@@ -2446,6 +2446,16 @@
"upgradeUnlimited": "Auf Pro upgraden – unbegrenzte Transkriptionen"
},
"notes": {
+ "mutationErrors": {
+ "folderNameRequired": "Gib einen Ordnernamen ein.",
+ "folderAlreadyExists": "Ein Ordner mit diesem Namen existiert bereits.",
+ "folderNotFound": "Dieser Ordner wurde nicht gefunden.",
+ "defaultFolderImmutable": "Standardordner können nicht geändert werden.",
+ "spaceNameRequired": "Gib einen Bereichsnamen ein.",
+ "spaceNotFound": "Dieser Bereich wurde nicht gefunden.",
+ "privateSpaceImmutable": "Dein persönlicher Bereich kann nicht geändert werden.",
+ "generic": "Die Änderung konnte nicht abgeschlossen werden. Bitte versuche es erneut."
+ },
"sidebar": {
"newNote": "Neue Notiz",
"searchNotes": "Notizen suchen",
diff --git a/src/locales/en/translation.json b/src/locales/en/translation.json
index 6a14ed92c..70dffd18f 100644
--- a/src/locales/en/translation.json
+++ b/src/locales/en/translation.json
@@ -2446,6 +2446,16 @@
"upgradeUnlimited": "Upgrade to Pro — unlimited transcriptions"
},
"notes": {
+ "mutationErrors": {
+ "folderNameRequired": "Enter a folder name.",
+ "folderAlreadyExists": "A folder with that name already exists.",
+ "folderNotFound": "That folder could not be found.",
+ "defaultFolderImmutable": "Default folders cannot be changed.",
+ "spaceNameRequired": "Enter a space name.",
+ "spaceNotFound": "That space could not be found.",
+ "privateSpaceImmutable": "Your Personal space cannot be changed.",
+ "generic": "The change could not be completed. Please try again."
+ },
"sidebar": {
"newNote": "New note",
"searchNotes": "Search notes",
diff --git a/src/locales/es/translation.json b/src/locales/es/translation.json
index 498870f7d..99242d1ab 100644
--- a/src/locales/es/translation.json
+++ b/src/locales/es/translation.json
@@ -2283,6 +2283,16 @@
}
},
"notes": {
+ "mutationErrors": {
+ "folderNameRequired": "Introduce un nombre para la carpeta.",
+ "folderAlreadyExists": "Ya existe una carpeta con ese nombre.",
+ "folderNotFound": "No se pudo encontrar esa carpeta.",
+ "defaultFolderImmutable": "Las carpetas predeterminadas no se pueden modificar.",
+ "spaceNameRequired": "Introduce un nombre para el espacio.",
+ "spaceNotFound": "No se pudo encontrar ese espacio.",
+ "privateSpaceImmutable": "Tu espacio Personal no se puede modificar.",
+ "generic": "No se pudo completar el cambio. Inténtalo de nuevo."
+ },
"sidebar": {
"newNote": "Nueva nota",
"searchNotes": "Buscar notas",
diff --git a/src/locales/fr/translation.json b/src/locales/fr/translation.json
index b5759d068..ed9f7c587 100644
--- a/src/locales/fr/translation.json
+++ b/src/locales/fr/translation.json
@@ -2446,6 +2446,16 @@
"upgradeUnlimited": "Passer à Pro — transcriptions illimitées"
},
"notes": {
+ "mutationErrors": {
+ "folderNameRequired": "Saisissez un nom de dossier.",
+ "folderAlreadyExists": "Un dossier portant ce nom existe déjà.",
+ "folderNotFound": "Ce dossier est introuvable.",
+ "defaultFolderImmutable": "Les dossiers par défaut ne peuvent pas être modifiés.",
+ "spaceNameRequired": "Saisissez un nom d’espace.",
+ "spaceNotFound": "Cet espace est introuvable.",
+ "privateSpaceImmutable": "Votre espace Personnel ne peut pas être modifié.",
+ "generic": "La modification n’a pas pu être effectuée. Réessayez."
+ },
"sidebar": {
"newNote": "Nouvelle note",
"searchNotes": "Rechercher des notes",
diff --git a/src/locales/it/translation.json b/src/locales/it/translation.json
index acf0d187a..f1df54f30 100644
--- a/src/locales/it/translation.json
+++ b/src/locales/it/translation.json
@@ -2235,6 +2235,16 @@
}
},
"notes": {
+ "mutationErrors": {
+ "folderNameRequired": "Inserisci un nome per la cartella.",
+ "folderAlreadyExists": "Esiste già una cartella con questo nome.",
+ "folderNotFound": "Impossibile trovare questa cartella.",
+ "defaultFolderImmutable": "Le cartelle predefinite non possono essere modificate.",
+ "spaceNameRequired": "Inserisci un nome per lo spazio.",
+ "spaceNotFound": "Impossibile trovare questo spazio.",
+ "privateSpaceImmutable": "Il tuo spazio Personale non può essere modificato.",
+ "generic": "Impossibile completare la modifica. Riprova."
+ },
"sidebar": {
"newNote": "Nuova nota",
"searchNotes": "Cerca note",
diff --git a/src/locales/ja/translation.json b/src/locales/ja/translation.json
index fbef83948..612e733e6 100644
--- a/src/locales/ja/translation.json
+++ b/src/locales/ja/translation.json
@@ -2163,6 +2163,16 @@
}
},
"notes": {
+ "mutationErrors": {
+ "folderNameRequired": "フォルダ名を入力してください。",
+ "folderAlreadyExists": "同じ名前のフォルダが既に存在します。",
+ "folderNotFound": "そのフォルダが見つかりませんでした。",
+ "defaultFolderImmutable": "デフォルトフォルダは変更できません。",
+ "spaceNameRequired": "スペース名を入力してください。",
+ "spaceNotFound": "そのスペースが見つかりませんでした。",
+ "privateSpaceImmutable": "個人用スペースは変更できません。",
+ "generic": "変更を完了できませんでした。もう一度お試しください。"
+ },
"sidebar": {
"newNote": "新しいノート",
"searchNotes": "ノートを検索",
diff --git a/src/locales/pt/translation.json b/src/locales/pt/translation.json
index c533d393d..a6304cfac 100644
--- a/src/locales/pt/translation.json
+++ b/src/locales/pt/translation.json
@@ -2235,6 +2235,16 @@
}
},
"notes": {
+ "mutationErrors": {
+ "folderNameRequired": "Insira um nome para a pasta.",
+ "folderAlreadyExists": "Já existe uma pasta com esse nome.",
+ "folderNotFound": "Não foi possível encontrar essa pasta.",
+ "defaultFolderImmutable": "As pastas padrão não podem ser alteradas.",
+ "spaceNameRequired": "Insira um nome para o espaço.",
+ "spaceNotFound": "Não foi possível encontrar esse espaço.",
+ "privateSpaceImmutable": "Seu espaço Pessoal não pode ser alterado.",
+ "generic": "Não foi possível concluir a alteração. Tente novamente."
+ },
"sidebar": {
"newNote": "Nova nota",
"searchNotes": "Pesquisar notas",
diff --git a/src/locales/ru/translation.json b/src/locales/ru/translation.json
index e82eadc93..c7708d986 100644
--- a/src/locales/ru/translation.json
+++ b/src/locales/ru/translation.json
@@ -2251,6 +2251,16 @@
}
},
"notes": {
+ "mutationErrors": {
+ "folderNameRequired": "Введите название папки.",
+ "folderAlreadyExists": "Папка с таким названием уже существует.",
+ "folderNotFound": "Эта папка не найдена.",
+ "defaultFolderImmutable": "Папки по умолчанию нельзя изменять.",
+ "spaceNameRequired": "Введите название пространства.",
+ "spaceNotFound": "Это пространство не найдено.",
+ "privateSpaceImmutable": "Личное пространство нельзя изменять.",
+ "generic": "Не удалось выполнить изменение. Попробуйте снова."
+ },
"sidebar": {
"newNote": "Новая заметка",
"searchNotes": "Поиск заметок",
diff --git a/src/locales/zh-CN/translation.json b/src/locales/zh-CN/translation.json
index a813fadc0..1f9372921 100644
--- a/src/locales/zh-CN/translation.json
+++ b/src/locales/zh-CN/translation.json
@@ -2235,6 +2235,16 @@
}
},
"notes": {
+ "mutationErrors": {
+ "folderNameRequired": "请输入文件夹名称。",
+ "folderAlreadyExists": "已存在同名文件夹。",
+ "folderNotFound": "找不到该文件夹。",
+ "defaultFolderImmutable": "无法更改默认文件夹。",
+ "spaceNameRequired": "请输入空间名称。",
+ "spaceNotFound": "找不到该空间。",
+ "privateSpaceImmutable": "无法更改你的个人空间。",
+ "generic": "无法完成更改,请重试。"
+ },
"sidebar": {
"newNote": "新建笔记",
"searchNotes": "搜索笔记",
diff --git a/src/locales/zh-TW/translation.json b/src/locales/zh-TW/translation.json
index fea950553..fb0ee9045 100644
--- a/src/locales/zh-TW/translation.json
+++ b/src/locales/zh-TW/translation.json
@@ -2235,6 +2235,16 @@
}
},
"notes": {
+ "mutationErrors": {
+ "folderNameRequired": "請輸入資料夾名稱。",
+ "folderAlreadyExists": "已存在同名資料夾。",
+ "folderNotFound": "找不到該資料夾。",
+ "defaultFolderImmutable": "無法變更預設資料夾。",
+ "spaceNameRequired": "請輸入空間名稱。",
+ "spaceNotFound": "找不到該空間。",
+ "privateSpaceImmutable": "無法變更你的個人空間。",
+ "generic": "無法完成變更,請再試一次。"
+ },
"sidebar": {
"newNote": "新增筆記",
"searchNotes": "搜尋筆記",
diff --git a/src/services/SyncService.ts b/src/services/SyncService.ts
index 60f22a0e8..a286d7404 100644
--- a/src/services/SyncService.ts
+++ b/src/services/SyncService.ts
@@ -29,6 +29,7 @@ import {
keepPurgedSpaceEntry,
normalizePurgedSpaceEntries,
prunePurgedSpaceEntries,
+ resolvePulledNoteFolderId,
resolvePullCursorAdvance,
revokedNoteForkUpdate,
type PurgedSpaceEntry,
@@ -1400,9 +1401,9 @@ class SyncService {
} else if (ctx.privateSpace) {
await window.electronAPI.upsertNoteFromCloud?.(
cloudNote as unknown as Record<string, unknown>,
- this.resolveLocalFolderId(
+ resolvePulledNoteFolderId(
cloudNote,
- ctx.privateSpace,
+ ctx.privateSpace.id,
cloudToLocal,
defaultFolderId
),
@@ -1448,7 +1449,7 @@ class SyncService {
}
await window.electronAPI.upsertNoteFromCloud?.(
cloudNote as unknown as Record<string, unknown>,
- this.resolveLocalFolderId(cloudNote, space, cloudToLocal, defaultFolderId),
+ resolvePulledNoteFolderId(cloudNote, space.id, cloudToLocal, defaultFolderId),
space.id
);
if (local) {
@@ -2097,21 +2098,6 @@ class SyncService {
);
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.space_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/spaceActions.ts b/src/services/spaceActions.ts
index e745f2376..068282a35 100644
--- a/src/services/spaceActions.ts
+++ b/src/services/spaceActions.ts
@@ -3,204 +3,42 @@ import { SpacesService } from "./SpacesService";
import { markSpacePurged, syncService, upsertCloudSpaces } from "./SyncService";
import { loadSpaces, purgeSpace, updateSpaceMeta } from "../stores/noteStore";
import { invalidateSpaceRoster } from "../lib/spaceRosterCache";
-import type { SpaceItem, TeamRole } from "../types/electron";
-
-// Single mutation path for spaces and their assigned teams: server call → local
-// SQLite mirror → store refresh. Roster and team mutations are space-agnostic
-// (a team can be assigned to many spaces), so they re-mirror every cloud space
-// rather than patching one row — my_role, member_count (deduped union) and the
-// teams list are always server-computed.
-
-function requireCloudSpaceId(space: SpaceItem): string {
- if (!space.cloud_space_id) throw new Error("Not a cloud space");
- return space.cloud_space_id;
-}
-
-function errorMessage(err: unknown): string | undefined {
- return err instanceof Error ? err.message : undefined;
-}
-
-async function settleAddMembers(teamId: string, userIds: string[]): Promise<unknown[]> {
- const results = await Promise.allSettled(
- userIds.map((userId) => TeamsService.addMember(teamId, userId))
- );
- return results
- .filter((r): r is PromiseRejectedResult => r.status === "rejected")
- .map((r) => r.reason);
-}
-
-async function refreshSpaceMirror(): Promise<void> {
- // Team membership and assignments affect the deduplicated union roster for
- // every space that team reaches. Invalidate before the mirror fetch so a
- // failed refresh cannot leave stale member attribution cached indefinitely.
- invalidateSpaceRoster();
- await upsertCloudSpaces(await SpacesService.mySpaces());
- await loadSpaces();
-}
-
-export async function createSpace(
- workspaceId: string,
- input: { name: string; emoji?: string | null },
- teams: { existingTeamIds: string[]; newTeam?: { name: string; memberIds: string[] } }
-): Promise<{ space: SpaceItem | null; failedMembers: number }> {
- const teamIds = [...teams.existingTeamIds];
- let failedMembers = 0;
- let createdTeamId: string | null = null;
- if (teams.newTeam) {
- const team = await TeamsService.create(workspaceId, { name: teams.newTeam.name });
- createdTeamId = team.id;
- failedMembers = (await settleAddMembers(team.id, teams.newTeam.memberIds)).length;
- teamIds.push(team.id);
- }
- let cloudSpace;
- try {
- cloudSpace = await SpacesService.create(workspaceId, {
- name: input.name,
- emoji: input.emoji,
- team_ids: teamIds,
- });
- } catch (err) {
- // The space create failed after the inline team was created (plan limit,
- // network) — best-effort delete so a retry doesn't duplicate the team.
- // The team is server-only at this point; nothing local to clean up.
- if (createdTeamId) await TeamsService.remove(createdTeamId).catch(() => {});
- throw err;
- }
- const space =
- (await window.electronAPI.upsertSpaceFromCloud?.(
- cloudSpace as unknown as Record<string, unknown>
- )) ?? null;
- // Cloud upserts insert as 'pending' (backfill marker); a space created this
- // second has no pre-existing content, so settle it — no skeletons.
- if (space) await window.electronAPI.setSpaceSyncStatus?.(space.id, "synced");
- await loadSpaces();
- syncService.requestSyncAll("manual");
- return { space, failedMembers };
-}
-
-export async function renameSpace(
- space: SpaceItem,
- updates: { name: string; emoji: string | null }
-): Promise<{ success: boolean; error?: string }> {
- const local = await updateSpaceMeta(space.id, updates);
- if (!local.success) return local;
- if (!space.cloud_space_id) {
- await window.electronAPI.setSpaceSyncStatus?.(space.id, "synced");
- await loadSpaces();
- return { success: true };
- }
- let cloudSpace;
- try {
- cloudSpace = await SpacesService.update(space.cloud_space_id, updates);
- } catch (err) {
- await updateSpaceMeta(space.id, { name: space.name, emoji: space.emoji ?? null });
- await window.electronAPI.setSpaceSyncStatus?.(space.id, "synced");
- await loadSpaces();
- return { success: false, error: errorMessage(err) };
- }
- try {
- await window.electronAPI.upsertSpaceFromCloud?.(
- cloudSpace as unknown as Record<string, unknown>
- );
- await window.electronAPI.setSpaceSyncStatus?.(space.id, "synced");
- await loadSpaces();
- } catch (err) {
- // The server rename succeeded. Keep the optimistic row pending and let the
- // regular mirror pass reconcile it instead of rolling back to a false name.
- console.error("Space rename mirror failed:", err);
- syncService.requestSyncAll("manual");
- }
- return { success: true };
-}
-
-export async function deleteSpace(space: SpaceItem): Promise<{ success: boolean; error?: string }> {
- if (space.cloud_space_id) {
- try {
- // Server archives the space; its teams survive as workspace entities and
- // members purge on their next spaces pass.
- await SpacesService.remove(space.cloud_space_id);
- } catch (err) {
- return { success: false, error: errorMessage(err) };
- }
- invalidateSpaceRoster(space.cloud_space_id);
- // Park the space id so an in-flight pull can't resurrect purged rows.
- await markSpacePurged(space.cloud_space_id, "deleted");
- }
- // Store cleanup rides on the space-purged broadcast.
- return purgeSpace(space.id);
-}
-
-// Fresh assignments get the server-side 'member' default; promotion to admin
-// is a separate, explicit act via setSpaceTeamAccess.
-export async function assignTeamToSpace(space: SpaceItem, teamId: string): Promise<void> {
- await SpacesService.assignTeam(requireCloudSpaceId(space), teamId);
- await refreshSpaceMirror();
-}
-
-// Changes an assignment's access cap via the upserting teams POST. May change
-// the caller's own my_role — including dropping their admin on this space —
-// which the mirror refresh picks up. Membership presence is untouched, so no
-// content re-sync is needed.
-export async function setSpaceTeamAccess(
- space: SpaceItem,
- teamId: string,
- access: "admin" | "member"
-): Promise<void> {
- await SpacesService.assignTeam(requireCloudSpaceId(space), teamId, access);
- await refreshSpaceMirror();
-}
-
-// Unassigning may cost the caller their own access (last of their teams on the
-// space): the follow-up sync pass purges the space locally in that case.
-export async function unassignTeamFromSpace(space: SpaceItem, teamId: string): Promise<void> {
- await SpacesService.unassignTeam(requireCloudSpaceId(space), teamId);
- await refreshSpaceMirror();
- syncService.requestSyncAll("manual");
-}
-
-export async function addTeamMembers(
- teamId: string,
- userIds: string[]
-): Promise<{ failures: unknown[] }> {
- const failures = await settleAddMembers(teamId, userIds);
- await refreshSpaceMirror();
- return { failures };
-}
-
-export async function removeTeamMember(teamId: string, userId: string): Promise<void> {
- await TeamsService.removeMember(teamId, userId);
- await refreshSpaceMirror();
-}
-
-export async function setTeamMemberRole(
- teamId: string,
- userId: string,
- role: TeamRole
-): Promise<void> {
- // The members POST upserts (ON CONFLICT DO UPDATE): role change via add.
- await TeamsService.addMember(teamId, userId, role);
- await refreshSpaceMirror();
-}
-
-// Spaces accessible only through this team disappear on the follow-up sync
-// pass (never purged here: other teams may still grant access).
-export async function leaveTeam(teamId: string, userId: string): Promise<void> {
- await TeamsService.removeMember(teamId, userId);
- await refreshSpaceMirror();
- syncService.requestSyncAll("manual");
-}
-
-export async function renameTeam(teamId: string, name: string): Promise<void> {
- await TeamsService.update(teamId, { name });
- // Team names are mirrored inside each space's teams list.
- await refreshSpaceMirror();
-}
-
-// Archives the team. Never marks the purge guard: spaces it granted access to
-// may survive via other teams — the follow-up sync pass decides what
-// disappears.
-export async function deleteTeam(teamId: string): Promise<void> {
- await TeamsService.remove(teamId);
- await refreshSpaceMirror();
- syncService.requestSyncAll("manual");
-}
+import { createSpaceActions } from "./spaceActionsCore";
+
+// Single mutation path for spaces and their assigned teams: server call →
+// local SQLite mirror → store refresh. The orchestration lives in an
+// injectable core so ordering, rollback, and partial-failure behavior stay
+// testable without a renderer or cloud server.
+const actions = createSpaceActions({
+ teams: TeamsService,
+ spaces: SpacesService,
+ local: {
+ upsertSpaceFromCloud: async (space) =>
+ (await window.electronAPI.upsertSpaceFromCloud?.(space)) ?? null,
+ setSpaceSyncStatus: async (id, status) => {
+ await window.electronAPI.setSpaceSyncStatus?.(id, status);
+ },
+ updateSpaceMeta,
+ purgeSpace,
+ loadSpaces,
+ },
+ mirror: { upsertCloudSpaces },
+ sync: syncService,
+ markSpacePurged,
+ invalidateSpaceRoster,
+});
+
+export const {
+ createSpace,
+ renameSpace,
+ deleteSpace,
+ assignTeamToSpace,
+ setSpaceTeamAccess,
+ unassignTeamFromSpace,
+ addTeamMembers,
+ removeTeamMember,
+ setTeamMemberRole,
+ leaveTeam,
+ renameTeam,
+ deleteTeam,
+} = actions;
diff --git a/src/services/spaceActionsCore.ts b/src/services/spaceActionsCore.ts
new file mode 100644
index 000000000..988d32b72
--- /dev/null
+++ b/src/services/spaceActionsCore.ts
@@ -0,0 +1,237 @@
+import type { SpaceItem, TeamRole } from "../types/electron";
+import type { MySpace } from "./SpacesService";
+
+interface CloudTeam {
+ id: string;
+}
+
+interface MutationResult {
+ success: boolean;
+ error?: string;
+}
+
+export interface SpaceActionsDependencies {
+ teams: {
+ create: (workspaceId: string, input: { name: string }) => Promise<CloudTeam>;
+ update: (teamId: string, input: { name: string }) => Promise<unknown>;
+ remove: (teamId: string) => Promise<void>;
+ addMember: (teamId: string, userId: string, role?: TeamRole) => Promise<void>;
+ removeMember: (teamId: string, userId: string) => Promise<void>;
+ };
+ spaces: {
+ mySpaces: () => Promise<MySpace[]>;
+ create: (
+ workspaceId: string,
+ input: { name: string; emoji?: string | null; team_ids: string[] }
+ ) => Promise<MySpace>;
+ update: (spaceId: string, updates: { name: string; emoji: string | null }) => Promise<MySpace>;
+ remove: (spaceId: string) => Promise<void>;
+ assignTeam: (spaceId: string, teamId: string, access?: "admin" | "member") => Promise<void>;
+ unassignTeam: (spaceId: string, teamId: string) => Promise<void>;
+ };
+ local: {
+ upsertSpaceFromCloud: (space: Record<string, unknown>) => Promise<SpaceItem | null>;
+ setSpaceSyncStatus: (id: number, status: SpaceItem["sync_status"]) => Promise<void>;
+ updateSpaceMeta: (
+ id: number,
+ updates: { name: string; emoji: string | null }
+ ) => Promise<MutationResult>;
+ purgeSpace: (id: number) => Promise<MutationResult>;
+ loadSpaces: () => Promise<unknown>;
+ };
+ mirror: {
+ upsertCloudSpaces: (spaces: MySpace[]) => Promise<unknown>;
+ };
+ sync: {
+ requestSyncAll: (reason: string) => void;
+ };
+ markSpacePurged: (cloudSpaceId: string, reason: "deleted") => Promise<void>;
+ invalidateSpaceRoster: (cloudSpaceId?: string) => void;
+}
+
+function requireCloudSpaceId(space: SpaceItem): string {
+ if (!space.cloud_space_id) throw new Error("Not a cloud space");
+ return space.cloud_space_id;
+}
+
+function errorMessage(err: unknown): string | undefined {
+ return err instanceof Error ? err.message : undefined;
+}
+
+export function createSpaceActions(deps: SpaceActionsDependencies) {
+ async function settleAddMembers(teamId: string, userIds: string[]): Promise<unknown[]> {
+ const results = await Promise.allSettled(
+ userIds.map((userId) => deps.teams.addMember(teamId, userId))
+ );
+ return results
+ .filter((result): result is PromiseRejectedResult => result.status === "rejected")
+ .map((result) => result.reason);
+ }
+
+ async function refreshSpaceMirror(): Promise<void> {
+ // Invalidate before fetching: a failed refresh must not preserve stale
+ // member attribution in the roster cache.
+ deps.invalidateSpaceRoster();
+ const cloudSpaces = await deps.spaces.mySpaces();
+ await deps.mirror.upsertCloudSpaces(cloudSpaces);
+ await deps.local.loadSpaces();
+ }
+
+ async function createSpace(
+ workspaceId: string,
+ input: { name: string; emoji?: string | null },
+ teams: { existingTeamIds: string[]; newTeam?: { name: string; memberIds: string[] } }
+ ): Promise<{ space: SpaceItem | null; failedMembers: number }> {
+ const teamIds = [...teams.existingTeamIds];
+ let failedMembers = 0;
+ let createdTeamId: string | null = null;
+ if (teams.newTeam) {
+ const team = await deps.teams.create(workspaceId, { name: teams.newTeam.name });
+ createdTeamId = team.id;
+ failedMembers = (await settleAddMembers(team.id, teams.newTeam.memberIds)).length;
+ teamIds.push(team.id);
+ }
+
+ let cloudSpace: MySpace;
+ try {
+ cloudSpace = await deps.spaces.create(workspaceId, {
+ name: input.name,
+ emoji: input.emoji,
+ team_ids: teamIds,
+ });
+ } catch (err) {
+ if (createdTeamId) await deps.teams.remove(createdTeamId).catch(() => {});
+ throw err;
+ }
+
+ const space = await deps.local.upsertSpaceFromCloud(
+ cloudSpace as unknown as Record<string, unknown>
+ );
+ if (space) await deps.local.setSpaceSyncStatus(space.id, "synced");
+ await deps.local.loadSpaces();
+ deps.sync.requestSyncAll("manual");
+ return { space, failedMembers };
+ }
+
+ async function renameSpace(
+ space: SpaceItem,
+ updates: { name: string; emoji: string | null }
+ ): Promise<{ success: boolean; error?: string }> {
+ const local = await deps.local.updateSpaceMeta(space.id, updates);
+ if (!local.success) return local;
+ if (!space.cloud_space_id) {
+ await deps.local.setSpaceSyncStatus(space.id, "synced");
+ await deps.local.loadSpaces();
+ return { success: true };
+ }
+
+ let cloudSpace: MySpace;
+ try {
+ cloudSpace = await deps.spaces.update(space.cloud_space_id, updates);
+ } catch (err) {
+ await deps.local.updateSpaceMeta(space.id, {
+ name: space.name,
+ emoji: space.emoji ?? null,
+ });
+ await deps.local.setSpaceSyncStatus(space.id, "synced");
+ await deps.local.loadSpaces();
+ return { success: false, error: errorMessage(err) };
+ }
+
+ try {
+ await deps.local.upsertSpaceFromCloud(cloudSpace as unknown as Record<string, unknown>);
+ await deps.local.setSpaceSyncStatus(space.id, "synced");
+ await deps.local.loadSpaces();
+ } catch (err) {
+ // The server won. Leave the optimistic row pending for the regular
+ // mirror instead of rolling it back to a name that is now false.
+ console.error("Space rename mirror failed:", err);
+ deps.sync.requestSyncAll("manual");
+ }
+ return { success: true };
+ }
+
+ async function deleteSpace(space: SpaceItem): Promise<{ success: boolean; error?: string }> {
+ if (space.cloud_space_id) {
+ try {
+ await deps.spaces.remove(space.cloud_space_id);
+ } catch (err) {
+ return { success: false, error: errorMessage(err) };
+ }
+ deps.invalidateSpaceRoster(space.cloud_space_id);
+ await deps.markSpacePurged(space.cloud_space_id, "deleted");
+ }
+ return deps.local.purgeSpace(space.id);
+ }
+
+ async function assignTeamToSpace(space: SpaceItem, teamId: string): Promise<void> {
+ await deps.spaces.assignTeam(requireCloudSpaceId(space), teamId);
+ await refreshSpaceMirror();
+ }
+
+ async function setSpaceTeamAccess(
+ space: SpaceItem,
+ teamId: string,
+ access: "admin" | "member"
+ ): Promise<void> {
+ await deps.spaces.assignTeam(requireCloudSpaceId(space), teamId, access);
+ await refreshSpaceMirror();
+ }
+
+ async function unassignTeamFromSpace(space: SpaceItem, teamId: string): Promise<void> {
+ await deps.spaces.unassignTeam(requireCloudSpaceId(space), teamId);
+ await refreshSpaceMirror();
+ deps.sync.requestSyncAll("manual");
+ }
+
+ async function addTeamMembers(
+ teamId: string,
+ userIds: string[]
+ ): Promise<{ failures: unknown[] }> {
+ const failures = await settleAddMembers(teamId, userIds);
+ await refreshSpaceMirror();
+ return { failures };
+ }
+
+ async function removeTeamMember(teamId: string, userId: string): Promise<void> {
+ await deps.teams.removeMember(teamId, userId);
+ await refreshSpaceMirror();
+ }
+
+ async function setTeamMemberRole(teamId: string, userId: string, role: TeamRole): Promise<void> {
+ await deps.teams.addMember(teamId, userId, role);
+ await refreshSpaceMirror();
+ }
+
+ async function leaveTeam(teamId: string, userId: string): Promise<void> {
+ await deps.teams.removeMember(teamId, userId);
+ await refreshSpaceMirror();
+ deps.sync.requestSyncAll("manual");
+ }
+
+ async function renameTeam(teamId: string, name: string): Promise<void> {
+ await deps.teams.update(teamId, { name });
+ await refreshSpaceMirror();
+ }
+
+ async function deleteTeam(teamId: string): Promise<void> {
+ await deps.teams.remove(teamId);
+ await refreshSpaceMirror();
+ deps.sync.requestSyncAll("manual");
+ }
+
+ return {
+ createSpace,
+ renameSpace,
+ deleteSpace,
+ assignTeamToSpace,
+ setSpaceTeamAccess,
+ unassignTeamFromSpace,
+ addTeamMembers,
+ removeTeamMember,
+ setTeamMemberRole,
+ leaveTeam,
+ renameTeam,
+ deleteTeam,
+ };
+}
diff --git a/src/services/syncPassPolicy.ts b/src/services/syncPassPolicy.ts
index 911d67ab6..5c12b6292 100644
--- a/src/services/syncPassPolicy.ts
+++ b/src/services/syncPassPolicy.ts
@@ -77,6 +77,22 @@ export function keepPurgedSpaceEntry(entry: PurgedSpaceEntry, isLive: boolean):
return isLive && entry.reason === "deleted";
}
+/**
+ * Resolve a pulled note's cloud folder without ever crossing local space
+ * boundaries. Team notes fall back to their space root; personal notes retain
+ * the legacy default-folder fallback.
+ */
+export function resolvePulledNoteFolderId(
+ cloudNote: { space_id?: string | null; folder_id?: string | null },
+ localSpaceId: number,
+ cloudToLocal: Map<string, { id: number; space_id: number }>,
+ defaultFolderId: number | null
+): number | null {
+ const fallback = cloudNote.space_id ? null : defaultFolderId;
+ const mapped = cloudNote.folder_id ? cloudToLocal.get(cloudNote.folder_id) : undefined;
+ return mapped && mapped.space_id === localSpaceId ? mapped.id : fallback;
+}
+
export interface RevokedNoteFork {
update: {
space_id?: number;
diff --git a/src/types/electron.ts b/src/types/electron.ts
index fada42546..a9d99fe46 100644
--- a/src/types/electron.ts
+++ b/src/types/electron.ts
@@ -855,7 +855,6 @@ declare global {
relocatedTitles?: string[];
error?: string;
}>;
- getSpaceByCloudSpaceId?: (cloudSpaceId: string) => Promise<SpaceItem | null>;
upsertSpaceFromCloud?: (space: Record<string, unknown>) => Promise<SpaceItem>;
setSpaceSyncStatus?: (
id: number,
@@ -2268,7 +2267,6 @@ 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/test/helpers/spacesDatabase.test.js b/test/helpers/spacesDatabase.test.js
index 2a60b8435..f316f278d 100644
--- a/test/helpers/spacesDatabase.test.js
+++ b/test/helpers/spacesDatabase.test.js
@@ -626,6 +626,80 @@ test("markNoteSyncedIfUnchanged settles only rows untouched since the push snaps
assert.equal(db.getNote(note.id).sync_status, "pending", "the mid-flight edit must still push");
});
+test("cloud_updated_at follows the pull, edit, push, and conflict lifecycle", (t) => {
+ const db = createDb(t);
+ if (!db) return;
+ const privateId = db.getPrivateSpaceId();
+ const firstCloudRevision = "2026-07-20T10:00:00.000Z";
+ const pushedCloudRevision = "2026-07-20T11:00:00.000Z";
+ const conflictCloudRevision = "2026-07-20T12:00:00.000Z";
+
+ const pulled = db.upsertNoteFromCloud(
+ {
+ id: "cloud-lifecycle-1",
+ client_note_id: "client-lifecycle-1",
+ title: "Lifecycle",
+ content: "cloud v1",
+ created_at: firstCloudRevision,
+ updated_at: firstCloudRevision,
+ },
+ null,
+ privateId
+ );
+ assert.equal(pulled.cloud_updated_at, firstCloudRevision, "pull establishes the PATCH base");
+
+ db.updateNote(pulled.id, { content: "local v2" });
+ const pushSnapshot = db.getNote(pulled.id);
+ assert.equal(pushSnapshot.sync_status, "pending");
+ assert.equal(
+ pushSnapshot.cloud_updated_at,
+ firstCloudRevision,
+ "local edits preserve the last observed server revision"
+ );
+
+ const settled = db.markNoteSyncedIfUnchanged(
+ pulled.id,
+ pulled.cloud_id,
+ pushSnapshot.updated_at,
+ pushedCloudRevision
+ );
+ assert.equal(settled.changes, 1);
+ assert.equal(db.getNote(pulled.id).sync_status, "synced");
+ assert.equal(db.getNote(pulled.id).cloud_updated_at, pushedCloudRevision);
+
+ db.updateNote(pulled.id, { content: "local v3" });
+ const racingSnapshot = db.getNote(pulled.id);
+ db.db
+ .prepare(
+ "UPDATE notes SET content = 'local v4', sync_status = 'pending', updated_at = datetime('now', '+1 hour') WHERE id = ?"
+ )
+ .run(pulled.id);
+ const raced = db.markNoteSyncedIfUnchanged(
+ pulled.id,
+ pulled.cloud_id,
+ racingSnapshot.updated_at,
+ conflictCloudRevision
+ );
+ assert.equal(raced.changes, 0);
+ assert.equal(db.getNote(pulled.id).sync_status, "pending");
+ assert.equal(
+ db.getNote(pulled.id).cloud_updated_at,
+ conflictCloudRevision,
+ "a delivered PATCH advances the base even when a newer local edit stays pending"
+ );
+
+ db.setNoteCloudBase(pulled.id, "2026-07-20T13:00:00.000Z");
+ assert.equal(db.getNote(pulled.id).sync_status, "pending");
+ assert.equal(db.getNote(pulled.id).cloud_updated_at, "2026-07-20T13:00:00.000Z");
+
+ db.markNoteSynced(pulled.id, "forked-cloud-id", null);
+ assert.equal(
+ db.getNote(pulled.id).cloud_updated_at,
+ null,
+ "a fork recreated under a new cloud id cannot retain the old row's base"
+ );
+});
+
test("markFolderSyncedIfUnchanged settles only rows untouched since the push snapshot", (t) => {
const db = createDb(t);
if (!db) return;
@@ -996,7 +1070,10 @@ test("upsertSpaceFromCloud adopts a pre-spaces row via its single backfilled tea
teams: [{ id: "team-1", name: "Legacy team", my_role: "member" }],
});
assert.equal(again.id, legacyId);
- assert.equal(db.db.prepare("SELECT COUNT(*) as count FROM spaces WHERE kind = 'team'").get().count, 1);
+ assert.equal(
+ db.db.prepare("SELECT COUNT(*) as count FROM spaces WHERE kind = 'team'").get().count,
+ 1
+ );
});
test("upsertSpaceFromCloud never adopts by team for multi-team spaces", (t) => {
diff --git a/test/lib/localMutationError.test.js b/test/lib/localMutationError.test.js
new file mode 100644
index 000000000..78772499b
--- /dev/null
+++ b/test/lib/localMutationError.test.js
@@ -0,0 +1,31 @@
+const test = require("node:test");
+const assert = require("node:assert/strict");
+
+const load = () => import("../../src/lib/localMutationError.ts");
+
+test("maps database validation messages to translation keys", async () => {
+ const { localMutationErrorKey } = await load();
+
+ assert.equal(
+ localMutationErrorKey("A folder with that name already exists"),
+ "notes.mutationErrors.folderAlreadyExists"
+ );
+ assert.equal(
+ localMutationErrorKey("Cannot move default folders"),
+ "notes.mutationErrors.defaultFolderImmutable"
+ );
+ assert.equal(
+ localMutationErrorKey("Cannot purge the private space"),
+ "notes.mutationErrors.privateSpaceImmutable"
+ );
+});
+
+test("does not expose arbitrary main-process or cloud error text", async () => {
+ const { localMutationErrorKey } = await load();
+
+ assert.equal(
+ localMutationErrorKey("connect ECONNREFUSED api.example.test"),
+ "notes.mutationErrors.generic"
+ );
+ assert.equal(localMutationErrorKey(undefined), "notes.mutationErrors.generic");
+});
diff --git a/test/services/spaceActions.test.js b/test/services/spaceActions.test.js
new file mode 100644
index 000000000..29ff0e1d6
--- /dev/null
+++ b/test/services/spaceActions.test.js
@@ -0,0 +1,273 @@
+const test = require("node:test");
+const assert = require("node:assert/strict");
+
+const load = () => import("../../src/services/spaceActionsCore.ts");
+
+function makeHarness() {
+ const calls = [];
+ const cloudSpace = { id: "cloud-space-1", name: "Roadmap" };
+ const localSpace = {
+ id: 7,
+ cloud_space_id: "cloud-space-1",
+ name: "Roadmap",
+ emoji: null,
+ };
+ const deps = {
+ teams: {
+ create: async (workspaceId, input) => {
+ calls.push(["team.create", workspaceId, input]);
+ return { id: "new-team" };
+ },
+ update: async (teamId, input) => calls.push(["team.update", teamId, input]),
+ remove: async (teamId) => calls.push(["team.remove", teamId]),
+ addMember: async (teamId, userId, role) =>
+ calls.push(["team.addMember", teamId, userId, role]),
+ removeMember: async (teamId, userId) => calls.push(["team.removeMember", teamId, userId]),
+ },
+ spaces: {
+ mySpaces: async () => {
+ calls.push(["space.mySpaces"]);
+ return [cloudSpace];
+ },
+ create: async (workspaceId, input) => {
+ calls.push(["space.create", workspaceId, input]);
+ return cloudSpace;
+ },
+ update: async (spaceId, updates) => {
+ calls.push(["space.update", spaceId, updates]);
+ return { ...cloudSpace, ...updates };
+ },
+ remove: async (spaceId) => calls.push(["space.remove", spaceId]),
+ assignTeam: async (spaceId, teamId, access) =>
+ calls.push(["space.assignTeam", spaceId, teamId, access]),
+ unassignTeam: async (spaceId, teamId) => calls.push(["space.unassignTeam", spaceId, teamId]),
+ },
+ local: {
+ upsertSpaceFromCloud: async (space) => {
+ calls.push(["local.upsert", space.id]);
+ return localSpace;
+ },
+ setSpaceSyncStatus: async (id, status) => calls.push(["local.setStatus", id, status]),
+ updateSpaceMeta: async (id, updates) => {
+ calls.push(["local.update", id, updates]);
+ return { success: true };
+ },
+ purgeSpace: async (id) => {
+ calls.push(["local.purge", id]);
+ return { success: true };
+ },
+ loadSpaces: async () => calls.push(["local.load"]),
+ },
+ mirror: {
+ upsertCloudSpaces: async (spaces) =>
+ calls.push(["mirror.upsert", spaces.map((space) => space.id)]),
+ },
+ sync: {
+ requestSyncAll: (reason) => calls.push(["sync", reason]),
+ },
+ markSpacePurged: async (spaceId, reason) => calls.push(["guard", spaceId, reason]),
+ invalidateSpaceRoster: (spaceId) => calls.push(["roster.invalidate", spaceId]),
+ };
+ return { calls, cloudSpace, localSpace, deps };
+}
+
+test("createSpace orchestrates inline-team members, local settling, and sync", async () => {
+ const { createSpaceActions } = await load();
+ const { calls, deps, localSpace } = makeHarness();
+ deps.teams.addMember = async (teamId, userId) => {
+ calls.push(["team.addMember", teamId, userId]);
+ if (userId === "bad-user") throw new Error("member failed");
+ };
+ const actions = createSpaceActions(deps);
+
+ const result = await actions.createSpace(
+ "workspace-1",
+ { name: "Roadmap", emoji: "🧭" },
+ {
+ existingTeamIds: ["existing-team"],
+ newTeam: { name: "Product", memberIds: ["good-user", "bad-user"] },
+ }
+ );
+
+ assert.equal(result.space, localSpace);
+ assert.equal(result.failedMembers, 1);
+ assert.deepEqual(
+ calls.find(([name]) => name === "space.create"),
+ [
+ "space.create",
+ "workspace-1",
+ {
+ name: "Roadmap",
+ emoji: "🧭",
+ team_ids: ["existing-team", "new-team"],
+ },
+ ]
+ );
+ assert.ok(calls.some((call) => call[0] === "local.upsert"));
+ assert.ok(calls.some((call) => call[0] === "local.setStatus" && call[2] === "synced"));
+ assert.deepEqual(calls.at(-1), ["sync", "manual"]);
+});
+
+test("createSpace removes an inline team when cloud space creation fails", async () => {
+ const { createSpaceActions } = await load();
+ const { calls, deps } = makeHarness();
+ const failure = new Error("plan limit");
+ deps.spaces.create = async () => {
+ throw failure;
+ };
+ // Cleanup is best-effort and must never replace the create failure.
+ deps.teams.remove = async (teamId) => {
+ calls.push(["team.remove", teamId]);
+ throw new Error("cleanup failed");
+ };
+ const actions = createSpaceActions(deps);
+
+ await assert.rejects(
+ actions.createSpace(
+ "workspace-1",
+ { name: "Roadmap" },
+ { existingTeamIds: [], newTeam: { name: "Product", memberIds: [] } }
+ ),
+ failure
+ );
+ assert.deepEqual(
+ calls.find(([name]) => name === "team.remove"),
+ ["team.remove", "new-team"]
+ );
+ assert.equal(
+ calls.some(([name]) => name === "local.upsert"),
+ false
+ );
+});
+
+test("renameSpace rolls back a rejected cloud rename", async () => {
+ const { createSpaceActions } = await load();
+ const { calls, deps, localSpace } = makeHarness();
+ deps.spaces.update = async () => {
+ throw new Error("offline");
+ };
+ const actions = createSpaceActions(deps);
+
+ const result = await actions.renameSpace(localSpace, { name: "New name", emoji: "✨" });
+
+ assert.deepEqual(result, { success: false, error: "offline" });
+ assert.deepEqual(
+ calls.filter(([name]) => name === "local.update"),
+ [
+ ["local.update", 7, { name: "New name", emoji: "✨" }],
+ ["local.update", 7, { name: "Roadmap", emoji: null }],
+ ]
+ );
+ assert.ok(calls.some((call) => call[0] === "local.setStatus" && call[2] === "synced"));
+});
+
+test("renameSpace leaves a server-successful rename pending when mirroring fails", async (t) => {
+ const { createSpaceActions } = await load();
+ const { calls, deps, localSpace } = makeHarness();
+ t.mock.method(console, "error", () => {});
+ deps.local.upsertSpaceFromCloud = async () => {
+ throw new Error("database unavailable");
+ };
+ const actions = createSpaceActions(deps);
+
+ assert.deepEqual(await actions.renameSpace(localSpace, { name: "New name", emoji: null }), {
+ success: true,
+ });
+ assert.deepEqual(calls.at(-1), ["sync", "manual"]);
+ assert.equal(
+ calls.filter(([name]) => name === "local.update").length,
+ 1,
+ "a server-successful rename must not roll back locally"
+ );
+});
+
+test("deleteSpace archives and guards cloud rows before local purge", async () => {
+ const { createSpaceActions } = await load();
+ const { calls, deps, localSpace } = makeHarness();
+ const actions = createSpaceActions(deps);
+
+ assert.deepEqual(await actions.deleteSpace(localSpace), { success: true });
+ assert.deepEqual(calls, [
+ ["space.remove", "cloud-space-1"],
+ ["roster.invalidate", "cloud-space-1"],
+ ["guard", "cloud-space-1", "deleted"],
+ ["local.purge", 7],
+ ]);
+
+ calls.length = 0;
+ deps.spaces.remove = async () => {
+ throw new Error("forbidden");
+ };
+ assert.deepEqual(await actions.deleteSpace(localSpace), {
+ success: false,
+ error: "forbidden",
+ });
+ assert.equal(
+ calls.some(([name]) => name === "local.purge"),
+ false
+ );
+});
+
+test("team mutations refresh the full mirror and schedule sync only when needed", async () => {
+ const { createSpaceActions } = await load();
+ const { calls, deps, localSpace } = makeHarness();
+ const actions = createSpaceActions(deps);
+
+ await actions.assignTeamToSpace(localSpace, "team-1");
+ await actions.setSpaceTeamAccess(localSpace, "team-1", "admin");
+ await actions.unassignTeamFromSpace(localSpace, "team-1");
+ await actions.removeTeamMember("team-1", "user-1");
+ await actions.setTeamMemberRole("team-1", "user-1", "admin");
+ await actions.leaveTeam("team-1", "user-1");
+ await actions.renameTeam("team-1", "Renamed");
+ await actions.deleteTeam("team-1");
+
+ assert.equal(
+ calls.filter(([name]) => name === "roster.invalidate").length,
+ 8,
+ "every membership or assignment change invalidates before refreshing"
+ );
+ assert.equal(calls.filter(([name]) => name === "mirror.upsert").length, 8);
+ assert.equal(calls.filter(([name]) => name === "local.load").length, 8);
+ assert.equal(
+ calls.filter(([name]) => name === "sync").length,
+ 3,
+ "unassign, leave, and delete can revoke container access"
+ );
+ assert.ok(
+ calls.some(
+ (call) =>
+ call[0] === "space.assignTeam" &&
+ call[1] === "cloud-space-1" &&
+ call[2] === "team-1" &&
+ call[3] === "admin"
+ )
+ );
+});
+
+test("addTeamMembers reports partial failures and still refreshes the mirror", async () => {
+ const { createSpaceActions } = await load();
+ const { calls, deps } = makeHarness();
+ deps.teams.addMember = async (_teamId, userId) => {
+ if (userId === "bad-user") throw new Error("bad member");
+ };
+ const actions = createSpaceActions(deps);
+
+ const { failures } = await actions.addTeamMembers("team-1", ["good-user", "bad-user"]);
+
+ assert.equal(failures.length, 1);
+ assert.match(failures[0].message, /bad member/);
+ assert.ok(calls.some(([name]) => name === "mirror.upsert"));
+});
+
+test("team assignment rejects local-only spaces before making a cloud request", async () => {
+ const { createSpaceActions } = await load();
+ const { calls, deps, localSpace } = makeHarness();
+ const actions = createSpaceActions(deps);
+
+ await assert.rejects(
+ actions.assignTeamToSpace({ ...localSpace, cloud_space_id: null }, "team-1"),
+ /Not a cloud space/
+ );
+ assert.equal(calls.length, 0);
+});
diff --git a/test/services/syncPassPolicy.test.js b/test/services/syncPassPolicy.test.js
index d4acea4bb..7d3605af9 100644
--- a/test/services/syncPassPolicy.test.js
+++ b/test/services/syncPassPolicy.test.js
@@ -107,6 +107,42 @@ test("purge guard: live-set sweep keeps only still-live deleted entries", async
assert.equal(keepPurgedSpaceEntry({ at: 1, reason: "revoked" }, false), false);
});
+// --- resolvePulledNoteFolderId ---------------------------------------------
+
+test("pull folder resolution accepts only mappings in the note's local space", async () => {
+ const { resolvePulledNoteFolderId } = await load();
+ const folders = new Map([
+ ["same-space", { id: 10, space_id: 2 }],
+ ["other-space", { id: 11, space_id: 3 }],
+ ]);
+
+ assert.equal(
+ resolvePulledNoteFolderId({ space_id: "cloud-space", folder_id: "same-space" }, 2, folders, 99),
+ 10
+ );
+ assert.equal(
+ resolvePulledNoteFolderId(
+ { space_id: "cloud-space", folder_id: "other-space" },
+ 2,
+ folders,
+ 99
+ ),
+ null,
+ "a team note must fall back to its space root, never another space's folder"
+ );
+});
+
+test("pull folder resolution uses the default folder only for personal notes", async () => {
+ const { resolvePulledNoteFolderId } = await load();
+ const folders = new Map();
+
+ assert.equal(resolvePulledNoteFolderId({ space_id: null, folder_id: null }, 1, folders, 99), 99);
+ assert.equal(
+ resolvePulledNoteFolderId({ space_id: "cloud-space", folder_id: null }, 2, folders, 99),
+ null
+ );
+});
+
// --- revokedNoteForkUpdate --------------------------------------------------
test("revoked fork: a push rejection moves, forks and clears the retraction", async () => {