Skip to content

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

feat(notes): local space foundations — spaces table, per-space folders, purge primitive

Gabriel Stein6fd35b40e7bd
diff --git a/preload.js b/preload.js
index fe5db96cc..b34f3593f 100644
--- a/preload.js
+++ b/preload.js
@@ -98,7 +98,7 @@ contextBridge.exposeInMainWorld("electronAPI", {
undoLearnedCorrections: (words) => ipcRenderer.invoke("undo-learned-corrections", words),
// Note functions
- saveNote: (title, content, noteType, sourceFile, audioDuration, folderId) =>
+ saveNote: (title, content, noteType, sourceFile, audioDuration, folderId, spaceId) =>
ipcRenderer.invoke(
"db-save-note",
title,
@@ -106,19 +106,21 @@ contextBridge.exposeInMainWorld("electronAPI", {
noteType,
sourceFile,
audioDuration,
- folderId
+ folderId,
+ spaceId
),
getNote: (id) => ipcRenderer.invoke("db-get-note", id),
- getNotes: (noteType, limit, folderId) =>
- ipcRenderer.invoke("db-get-notes", noteType, limit, folderId),
+ getNotes: (noteType, limit, folderId, spaceId) =>
+ ipcRenderer.invoke("db-get-notes", noteType, limit, folderId, spaceId),
updateNote: (id, updates) => ipcRenderer.invoke("db-update-note", id, updates),
deleteNote: (id) => ipcRenderer.invoke("db-delete-note", id),
exportNote: (noteId, format) => ipcRenderer.invoke("export-note", noteId, format),
exportTranscript: (noteId, format) => ipcRenderer.invoke("export-transcript", noteId, format),
exportDictionary: (words) => ipcRenderer.invoke("export-dictionary", words),
- searchNotes: (query, limit) => ipcRenderer.invoke("db-search-notes", query, limit),
- semanticSearchNotes: (query, limit) =>
- ipcRenderer.invoke("db-semantic-search-notes", query, limit),
+ searchNotes: (query, limit, spaceId) =>
+ ipcRenderer.invoke("db-search-notes", query, limit, spaceId),
+ semanticSearchNotes: (query, limit, spaceId) =>
+ ipcRenderer.invoke("db-semantic-search-notes", query, limit, spaceId),
semanticReindexAll: () => ipcRenderer.invoke("db-semantic-reindex-all"),
onSemanticReindexProgress: (callback) => {
const listener = (_event, data) => callback?.(data);
@@ -129,12 +131,27 @@ contextBridge.exposeInMainWorld("electronAPI", {
updateNoteShareState: (id, state) => ipcRenderer.invoke("db-update-note-share-state", id, state),
// Folder functions
- getFolders: () => ipcRenderer.invoke("db-get-folders"),
- createFolder: (name) => ipcRenderer.invoke("db-create-folder", name),
+ getFolders: (spaceId) => ipcRenderer.invoke("db-get-folders", spaceId),
+ createFolder: (name, spaceId) => ipcRenderer.invoke("db-create-folder", name, spaceId),
deleteFolder: (id) => ipcRenderer.invoke("db-delete-folder", id),
renameFolder: (id, name) => ipcRenderer.invoke("db-rename-folder", id, name),
getFolderNoteCounts: () => ipcRenderer.invoke("db-get-folder-note-counts"),
+ // Space functions
+ getSpaces: () => ipcRenderer.invoke("db-get-spaces"),
+ createSpace: (space) => ipcRenderer.invoke("db-create-space", space),
+ updateSpace: (id, updates) => ipcRenderer.invoke("db-update-space", id, updates),
+ deleteSpace: (id) => ipcRenderer.invoke("db-delete-space", id),
+ purgeSpace: (id) => ipcRenderer.invoke("db-purge-space", id),
+ getSpaceByCloudTeamId: (cloudTeamId) =>
+ ipcRenderer.invoke("db-get-space-by-cloud-team-id", cloudTeamId),
+ upsertSpaceFromCloud: (team) => ipcRenderer.invoke("db-upsert-space-from-cloud", team),
+ onSpacePurged: (callback) => {
+ const listener = (_event, payload) => callback?.(payload);
+ ipcRenderer.on("space-purged", listener);
+ return () => ipcRenderer.removeListener("space-purged", listener);
+ },
+
// Note files (markdown mirror) functions
noteFilesSetEnabled: (enabled, customPath, options) =>
ipcRenderer.invoke("note-files-set-enabled", enabled, customPath, options),
@@ -824,8 +841,8 @@ contextBridge.exposeInMainWorld("electronAPI", {
getPendingNotes: () => ipcRenderer.invoke("db-get-pending-notes"),
getPendingNoteDeletes: () => ipcRenderer.invoke("db-get-pending-note-deletes"),
getNoteByClientId: (clientNoteId) => ipcRenderer.invoke("db-get-note-by-client-id", clientNoteId),
- upsertNoteFromCloud: (cloudNote, localFolderId) =>
- ipcRenderer.invoke("db-upsert-note-from-cloud", cloudNote, localFolderId),
+ upsertNoteFromCloud: (cloudNote, localFolderId, localSpaceId) =>
+ ipcRenderer.invoke("db-upsert-note-from-cloud", cloudNote, localFolderId, localSpaceId),
markNoteSynced: (id, cloudId) => ipcRenderer.invoke("db-mark-note-synced", id, cloudId),
markNoteSyncError: (id) => ipcRenderer.invoke("db-mark-note-sync-error", id),
hardDeleteNote: (id) => ipcRenderer.invoke("db-hard-delete-note", id),
@@ -833,8 +850,8 @@ contextBridge.exposeInMainWorld("electronAPI", {
getPendingFolders: () => ipcRenderer.invoke("db-get-pending-folders"),
getFolderByClientId: (clientFolderId) =>
ipcRenderer.invoke("db-get-folder-by-client-id", clientFolderId),
- upsertFolderFromCloud: (cloudFolder) =>
- ipcRenderer.invoke("db-upsert-folder-from-cloud", cloudFolder),
+ upsertFolderFromCloud: (cloudFolder, localSpaceId) =>
+ ipcRenderer.invoke("db-upsert-folder-from-cloud", cloudFolder, localSpaceId),
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),
diff --git a/src/helpers/database.js b/src/helpers/database.js
index 54997c9b6..08d4d5a80 100644
--- a/src/helpers/database.js
+++ b/src/helpers/database.js
@@ -635,6 +635,109 @@ class DatabaseManager {
"CREATE INDEX IF NOT EXISTS idx_snippets_pending_sync ON snippets(sync_status) WHERE sync_status = 'pending'"
);
+ // Team spaces
+ this.db.exec(`
+ CREATE TABLE IF NOT EXISTS spaces (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ client_space_id TEXT,
+ cloud_team_id TEXT,
+ workspace_id TEXT,
+ kind TEXT NOT NULL DEFAULT 'team' CHECK (kind IN ('private','team')),
+ name TEXT NOT NULL,
+ emoji TEXT,
+ sort_order INTEGER NOT NULL DEFAULT 0,
+ my_role TEXT,
+ member_count INTEGER,
+ sync_status TEXT NOT NULL DEFAULT 'pending',
+ deleted_at TEXT,
+ created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
+ updated_at DATETIME DEFAULT CURRENT_TIMESTAMP
+ )
+ `);
+ this.db.exec(
+ "CREATE UNIQUE INDEX IF NOT EXISTS idx_spaces_client_space_id ON spaces(client_space_id)"
+ );
+ this.db.exec(
+ "CREATE UNIQUE INDEX IF NOT EXISTS idx_spaces_cloud_team_id ON spaces(cloud_team_id) WHERE cloud_team_id IS NOT NULL"
+ );
+
+ const privateSpaceCount = this.db
+ .prepare("SELECT COUNT(*) as count FROM spaces WHERE kind = 'private'")
+ .get();
+ if (privateSpaceCount.count === 0) {
+ this.db
+ .prepare(
+ "INSERT INTO spaces (client_space_id, kind, name, sort_order, sync_status) VALUES (?, 'private', 'Personal', 0, 'synced')"
+ )
+ .run(randomUUID());
+ }
+
+ try {
+ this.db.exec("ALTER TABLE notes ADD COLUMN space_id INTEGER");
+ } catch (err) {
+ if (!err.message.includes("duplicate column")) throw err;
+ }
+ try {
+ this.db.exec("ALTER TABLE folders ADD COLUMN space_id INTEGER");
+ } catch (err) {
+ if (!err.message.includes("duplicate column")) throw err;
+ }
+
+ // Rebuild folders to drop the table-level UNIQUE(name); per-space name
+ // uniqueness is enforced by idx_folders_space_name below.
+ const foldersTable = this.db
+ .prepare("SELECT sql FROM sqlite_master WHERE type = 'table' AND name = 'folders'")
+ .get();
+ if (foldersTable?.sql.includes("UNIQUE")) {
+ this.db.transaction(() => {
+ this.db.exec(`
+ CREATE TABLE folders_new (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ name TEXT NOT NULL,
+ is_default INTEGER NOT NULL DEFAULT 0,
+ sort_order INTEGER NOT NULL DEFAULT 0,
+ created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
+ updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
+ client_folder_id TEXT,
+ cloud_id TEXT,
+ sync_status TEXT DEFAULT 'pending',
+ deleted_at TEXT,
+ space_id INTEGER
+ )
+ `);
+ this.db.exec(`
+ INSERT INTO folders_new (id, name, is_default, sort_order, created_at, updated_at,
+ client_folder_id, cloud_id, sync_status, deleted_at, space_id)
+ SELECT id, name, is_default, sort_order, created_at, updated_at,
+ client_folder_id, cloud_id, sync_status, deleted_at, space_id
+ FROM folders
+ `);
+ this.db.exec("DROP TABLE folders");
+ this.db.exec("ALTER TABLE folders_new RENAME TO folders");
+ this.db.exec(
+ "CREATE UNIQUE INDEX IF NOT EXISTS idx_folders_client_folder_id ON folders(client_folder_id)"
+ );
+ })();
+ }
+ this.db.exec(
+ "CREATE UNIQUE INDEX IF NOT EXISTS idx_folders_space_name ON folders(space_id, name) WHERE deleted_at IS NULL"
+ );
+
+ const privateSpace = this.db.prepare("SELECT id FROM spaces WHERE kind = 'private'").get();
+ this.db
+ .prepare("UPDATE folders SET space_id = ? WHERE space_id IS NULL")
+ .run(privateSpace.id);
+ this.db.prepare("UPDATE notes SET space_id = ? WHERE space_id IS NULL").run(privateSpace.id);
+
+ this.db.exec("CREATE INDEX IF NOT EXISTS idx_notes_folder_id ON notes(folder_id)");
+ this.db.exec("CREATE INDEX IF NOT EXISTS idx_notes_updated_at ON notes(updated_at)");
+ this.db.exec(
+ "CREATE INDEX IF NOT EXISTS idx_notes_space_updated ON notes(space_id, updated_at)"
+ );
+ this.db.exec(
+ "CREATE INDEX IF NOT EXISTS idx_folders_space_sort ON folders(space_id, sort_order)"
+ );
+
return true;
} catch (error) {
debugLogger.error("Database initialization failed", { error: error.message }, "database");
@@ -1397,22 +1500,28 @@ class DatabaseManager {
noteType = "personal",
sourceFile = null,
audioDuration = null,
- folderId = null
+ folderId = null,
+ spaceId = null
) {
try {
if (!this.db) {
throw new Error("Database not initialized");
}
- if (!folderId) {
+ if (folderId) {
+ // D2: a note's space always follows its folder's space.
+ const folder = this.db.prepare("SELECT space_id FROM folders WHERE id = ?").get(folderId);
+ spaceId = folder?.space_id ?? spaceId ?? this.getPrivateSpaceId();
+ } else {
+ if (spaceId == null) spaceId = this.getPrivateSpaceId();
const defaultFolderName = noteType === "meeting" ? "Meetings" : "Personal";
const defaultFolder = this.db
- .prepare("SELECT id FROM folders WHERE name = ? AND is_default = 1")
- .get(defaultFolderName);
+ .prepare("SELECT id FROM folders WHERE name = ? AND is_default = 1 AND space_id = ?")
+ .get(defaultFolderName, spaceId);
folderId = defaultFolder?.id || null;
}
const clientNoteId = randomUUID();
const stmt = this.db.prepare(
- "INSERT INTO notes (title, content, note_type, source_file, audio_duration_seconds, folder_id, client_note_id) VALUES (?, ?, ?, ?, ?, ?, ?)"
+ "INSERT INTO notes (title, content, note_type, source_file, audio_duration_seconds, folder_id, space_id, client_note_id) VALUES (?, ?, ?, ?, ?, ?, ?, ?)"
);
const result = stmt.run(
title,
@@ -1421,6 +1530,7 @@ class DatabaseManager {
sourceFile,
audioDuration,
folderId,
+ spaceId,
clientNoteId
);
@@ -1447,7 +1557,7 @@ class DatabaseManager {
}
}
- getNotes(noteType = null, limit = 100, folderId = null) {
+ getNotes(noteType = null, limit = 100, folderId = null, spaceId = null) {
try {
if (!this.db) {
throw new Error("Database not initialized");
@@ -1458,10 +1568,14 @@ class DatabaseManager {
conditions.push("note_type = ?");
params.push(noteType);
}
- if (folderId) {
+ if (folderId != null) {
conditions.push("folder_id = ?");
params.push(folderId);
}
+ if (spaceId != null) {
+ conditions.push("space_id = ?");
+ params.push(spaceId);
+ }
const where = `WHERE ${conditions.join(" AND ")}`;
const stmt = this.db.prepare(`SELECT * FROM notes ${where} ORDER BY updated_at DESC LIMIT ?`);
params.push(limit);
@@ -1475,6 +1589,13 @@ class DatabaseManager {
updateNote(id, updates) {
try {
if (!this.db) throw new Error("Database not initialized");
+ if (updates.folder_id != null) {
+ // D2: a note's space always follows its folder's space.
+ const folder = this.db
+ .prepare("SELECT space_id FROM folders WHERE id = ?")
+ .get(updates.folder_id);
+ if (folder) updates = { ...updates, space_id: folder.space_id };
+ }
const allowedFields = [
"title",
"content",
@@ -1482,6 +1603,7 @@ class DatabaseManager {
"enhancement_prompt",
"enhanced_at_content_hash",
"folder_id",
+ "space_id",
"transcript",
"calendar_event_id",
"participants",
@@ -1519,33 +1641,46 @@ class DatabaseManager {
}
}
- getFolders() {
+ getFolders(spaceId = null) {
try {
if (!this.db) throw new Error("Database not initialized");
+ const conditions = ["deleted_at IS NULL"];
+ const params = [];
+ if (spaceId != null) {
+ conditions.push("space_id = ?");
+ params.push(spaceId);
+ }
return this.db
.prepare(
- "SELECT * FROM folders WHERE deleted_at IS NULL ORDER BY sort_order ASC, created_at ASC"
+ `SELECT * FROM folders WHERE ${conditions.join(" AND ")} ORDER BY sort_order ASC, created_at ASC`
)
- .all();
+ .all(...params);
} catch (error) {
debugLogger.error("Error getting folders", { error: error.message }, "notes");
throw error;
}
}
- createFolder(name) {
+ createFolder(name, spaceId = null) {
try {
if (!this.db) throw new Error("Database not initialized");
const trimmed = (name || "").trim();
if (!trimmed) return { success: false, error: "Folder name is required" };
- const existing = this.db.prepare("SELECT id FROM folders WHERE name = ?").get(trimmed);
+ if (spaceId == null) spaceId = this.getPrivateSpaceId();
+ const existing = this.db
+ .prepare("SELECT id FROM folders WHERE name = ? AND space_id = ? AND deleted_at IS NULL")
+ .get(trimmed, spaceId);
if (existing) return { success: false, error: "A folder with that name already exists" };
- const maxOrder = this.db.prepare("SELECT MAX(sort_order) as max_order FROM folders").get();
+ const maxOrder = this.db
+ .prepare("SELECT MAX(sort_order) as max_order FROM folders WHERE space_id = ?")
+ .get(spaceId);
const sortOrder = (maxOrder?.max_order ?? 0) + 1;
const clientFolderId = randomUUID();
const result = this.db
- .prepare("INSERT INTO folders (name, sort_order, client_folder_id) VALUES (?, ?, ?)")
- .run(trimmed, sortOrder, clientFolderId);
+ .prepare(
+ "INSERT INTO folders (name, sort_order, space_id, client_folder_id) VALUES (?, ?, ?, ?)"
+ )
+ .run(trimmed, sortOrder, spaceId, clientFolderId);
const folder = this.db
.prepare("SELECT * FROM folders WHERE id = ?")
.get(result.lastInsertRowid);
@@ -1593,8 +1728,10 @@ class DatabaseManager {
const trimmed = (name || "").trim();
if (!trimmed) return { success: false, error: "Folder name is required" };
const existing = this.db
- .prepare("SELECT id FROM folders WHERE name = ? AND id != ?")
- .get(trimmed, id);
+ .prepare(
+ "SELECT id FROM folders WHERE name = ? AND space_id = ? AND deleted_at IS NULL AND id != ?"
+ )
+ .get(trimmed, folder.space_id, id);
if (existing) return { success: false, error: "A folder with that name already exists" };
this.db
.prepare(
@@ -1623,6 +1760,188 @@ class DatabaseManager {
}
}
+ getPrivateSpaceId() {
+ try {
+ if (!this.db) throw new Error("Database not initialized");
+ return this.db.prepare("SELECT id FROM spaces WHERE kind = 'private'").get()?.id ?? null;
+ } catch (error) {
+ debugLogger.error("Error getting private space id", { error: error.message }, "spaces");
+ throw error;
+ }
+ }
+
+ getSpaces() {
+ try {
+ if (!this.db) throw new Error("Database not initialized");
+ return this.db
+ .prepare(
+ "SELECT * FROM spaces WHERE deleted_at IS NULL ORDER BY CASE WHEN kind = 'private' THEN 0 ELSE 1 END, sort_order ASC, name ASC"
+ )
+ .all();
+ } catch (error) {
+ debugLogger.error("Error getting spaces", { error: error.message }, "spaces");
+ throw error;
+ }
+ }
+
+ createSpace({ name, emoji = null, kind = "team" } = {}) {
+ try {
+ if (!this.db) throw new Error("Database not initialized");
+ const trimmed = (name || "").trim();
+ if (!trimmed) return { success: false, error: "Space name is required" };
+ const maxOrder = this.db.prepare("SELECT MAX(sort_order) as max_order FROM spaces").get();
+ const sortOrder = (maxOrder?.max_order ?? 0) + 1;
+ const result = this.db
+ .prepare(
+ "INSERT INTO spaces (client_space_id, kind, name, emoji, sort_order) VALUES (?, ?, ?, ?, ?)"
+ )
+ .run(randomUUID(), kind, trimmed, emoji, sortOrder);
+ const space = this.db
+ .prepare("SELECT * FROM spaces WHERE id = ?")
+ .get(result.lastInsertRowid);
+ return { success: true, space };
+ } catch (error) {
+ debugLogger.error("Error creating space", { error: error.message }, "spaces");
+ throw error;
+ }
+ }
+
+ updateSpace(id, { name, emoji } = {}) {
+ try {
+ if (!this.db) throw new Error("Database not initialized");
+ const space = this.db.prepare("SELECT * FROM spaces WHERE id = ?").get(id);
+ if (!space) return { success: false, error: "Space not found" };
+ const fields = [];
+ const values = [];
+ if (name !== undefined) {
+ if (space.kind === "private") {
+ return { success: false, error: "Cannot rename the private space" };
+ }
+ const trimmed = (name || "").trim();
+ if (!trimmed) return { success: false, error: "Space name is required" };
+ fields.push("name = ?");
+ values.push(trimmed);
+ }
+ if (emoji !== undefined) {
+ fields.push("emoji = ?");
+ values.push(emoji);
+ }
+ if (fields.length === 0) return { success: false };
+ fields.push("sync_status = 'pending'", "updated_at = datetime('now')");
+ values.push(id);
+ this.db.prepare(`UPDATE spaces SET ${fields.join(", ")} WHERE id = ?`).run(...values);
+ const updated = this.db.prepare("SELECT * FROM spaces WHERE id = ?").get(id);
+ return { success: true, space: updated };
+ } catch (error) {
+ debugLogger.error("Error updating space", { error: error.message }, "spaces");
+ throw error;
+ }
+ }
+
+ renameSpace(id, name) {
+ return this.updateSpace(id, { name });
+ }
+
+ getSpaceByCloudTeamId(cloudTeamId) {
+ try {
+ if (!this.db) throw new Error("Database not initialized");
+ return (
+ this.db.prepare("SELECT * FROM spaces WHERE cloud_team_id = ?").get(cloudTeamId) || null
+ );
+ } catch (error) {
+ debugLogger.error("Error getting space by cloud team id", { error: error.message }, "spaces");
+ throw error;
+ }
+ }
+
+ upsertSpaceFromCloud(team) {
+ try {
+ if (!this.db) throw new Error("Database not initialized");
+ const updatedAt = team.updated_at || team.created_at || new Date().toISOString();
+ const existing = this.db.prepare("SELECT * FROM spaces WHERE cloud_team_id = ?").get(team.id);
+ if (existing) {
+ this.db
+ .prepare(
+ `UPDATE spaces SET workspace_id = ?, name = ?, emoji = ?, my_role = ?, member_count = ?,
+ sync_status = 'synced', deleted_at = NULL, updated_at = ? WHERE id = ?`
+ )
+ .run(
+ team.workspace_id ?? null,
+ team.name,
+ team.emoji ?? null,
+ team.my_role ?? null,
+ team.member_count ?? null,
+ updatedAt,
+ existing.id
+ );
+ return this.db.prepare("SELECT * FROM spaces WHERE id = ?").get(existing.id);
+ }
+ const maxOrder = this.db.prepare("SELECT MAX(sort_order) as max_order FROM spaces").get();
+ const result = this.db
+ .prepare(
+ `INSERT INTO spaces (client_space_id, cloud_team_id, workspace_id, kind, name, emoji,
+ sort_order, my_role, member_count, sync_status, created_at, updated_at)
+ VALUES (?, ?, ?, 'team', ?, ?, ?, ?, ?, 'synced', ?, ?)`
+ )
+ .run(
+ randomUUID(),
+ team.id,
+ team.workspace_id ?? null,
+ team.name,
+ team.emoji ?? null,
+ (maxOrder?.max_order ?? 0) + 1,
+ team.my_role ?? null,
+ team.member_count ?? null,
+ team.created_at || updatedAt,
+ updatedAt
+ );
+ return this.db.prepare("SELECT * FROM spaces WHERE id = ?").get(result.lastInsertRowid);
+ } catch (error) {
+ debugLogger.error("Error upserting space from cloud", { error: error.message }, "spaces");
+ throw error;
+ }
+ }
+
+ purgeSpace(localSpaceId) {
+ try {
+ if (!this.db) throw new Error("Database not initialized");
+ const space = this.db.prepare("SELECT * FROM spaces WHERE id = ?").get(localSpaceId);
+ if (!space) return { success: false, error: "Space not found" };
+ if (space.kind === "private") {
+ return { success: false, error: "Cannot purge the private space" };
+ }
+ const { noteIds, folderNames } = this.db.transaction(() => {
+ const ids = this.db
+ .prepare("SELECT id FROM notes WHERE space_id = ?")
+ .all(localSpaceId)
+ .map((row) => row.id);
+ const names = this.db
+ .prepare("SELECT name FROM folders WHERE space_id = ?")
+ .all(localSpaceId)
+ .map((row) => row.name);
+ // FKs are not enforced in this DB — clean speaker rows explicitly.
+ this.db
+ .prepare(
+ "DELETE FROM speaker_mappings WHERE note_id IN (SELECT id FROM notes WHERE space_id = ?)"
+ )
+ .run(localSpaceId);
+ this.db
+ .prepare(
+ "DELETE FROM note_speaker_embeddings WHERE note_id IN (SELECT id FROM notes WHERE space_id = ?)"
+ )
+ .run(localSpaceId);
+ this.db.prepare("DELETE FROM notes WHERE space_id = ?").run(localSpaceId);
+ this.db.prepare("DELETE FROM folders WHERE space_id = ?").run(localSpaceId);
+ this.db.prepare("DELETE FROM spaces WHERE id = ?").run(localSpaceId);
+ return { noteIds: ids, folderNames: names };
+ })();
+ return { success: true, noteIds, folderNames, spaceId: localSpaceId };
+ } catch (error) {
+ debugLogger.error("Error purging space", { error: error.message }, "spaces");
+ throw error;
+ }
+ }
+
getActions() {
try {
if (!this.db) throw new Error("Database not initialized");
@@ -2104,7 +2423,7 @@ class DatabaseManager {
}
}
- searchNotes(query, limit = 50) {
+ searchNotes(query, limit = 50, spaceId = null) {
try {
if (!this.db) throw new Error("Database not initialized");
const term = query
@@ -2112,18 +2431,25 @@ class DatabaseManager {
.replace(/[^\w\s]/g, " ")
.trim();
if (!term) return [];
+ const params = [term + "*"];
+ let spaceFilter = "";
+ if (spaceId != null) {
+ spaceFilter = "AND n.space_id = ?";
+ params.push(spaceId);
+ }
+ params.push(limit);
return this.db
.prepare(
`
SELECT n.*
FROM notes n
JOIN notes_fts ON notes_fts.rowid = n.id
- WHERE notes_fts MATCH ? AND n.deleted_at IS NULL
+ WHERE notes_fts MATCH ? AND n.deleted_at IS NULL ${spaceFilter}
ORDER BY notes_fts.rank
LIMIT ?
`
)
- .all(term + "*", limit);
+ .all(...params);
} catch (error) {
debugLogger.error("Error searching notes", { error: error.message }, "database");
throw error;
@@ -2266,13 +2592,15 @@ class DatabaseManager {
}
}
- getMeetingsFolder() {
+ getMeetingsFolder(spaceId = null) {
try {
if (!this.db) throw new Error("Database not initialized");
return (
this.db
- .prepare("SELECT id FROM folders WHERE name = 'Meetings' AND is_default = 1")
- .get() || null
+ .prepare(
+ "SELECT id FROM folders WHERE name = 'Meetings' AND is_default = 1 AND space_id = ?"
+ )
+ .get(spaceId ?? this.getPrivateSpaceId()) || null
);
} catch (error) {
debugLogger.error("Error getting meetings folder", { error: error.message }, "gcal");
@@ -2701,15 +3029,15 @@ class DatabaseManager {
}
}
- upsertNoteFromCloud(cloudNote, localFolderId) {
+ upsertNoteFromCloud(cloudNote, localFolderId, localSpaceId = null) {
try {
if (!this.db) throw new Error("Database not initialized");
const stmt = this.db.prepare(`
INSERT INTO notes (client_note_id, cloud_id, title, content, enhanced_content,
enhancement_prompt, enhanced_at_content_hash, note_type, source_file,
- audio_duration_seconds, transcript, folder_id, participants, calendar_event_id,
+ audio_duration_seconds, transcript, folder_id, space_id, participants, calendar_event_id,
diarization_enabled, expected_speaker_count, sync_status, created_at, updated_at)
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'synced', ?, ?)
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'synced', ?, ?)
ON CONFLICT(client_note_id) DO UPDATE SET
cloud_id = excluded.cloud_id,
title = excluded.title,
@@ -2719,6 +3047,7 @@ class DatabaseManager {
enhanced_at_content_hash = excluded.enhanced_at_content_hash,
transcript = excluded.transcript,
folder_id = excluded.folder_id,
+ space_id = excluded.space_id,
participants = COALESCE(excluded.participants, participants),
calendar_event_id = COALESCE(excluded.calendar_event_id, calendar_event_id),
diarization_enabled = COALESCE(excluded.diarization_enabled, diarization_enabled),
@@ -2739,6 +3068,7 @@ class DatabaseManager {
cloudNote.audio_duration_seconds || null,
cloudNote.transcript || null,
localFolderId,
+ localSpaceId ?? this.getPrivateSpaceId(),
cloudNote.participants || null,
cloudNote.calendar_event_id || null,
cloudNote.diarization_enabled ?? null,
@@ -2852,16 +3182,17 @@ class DatabaseManager {
}
}
- upsertFolderFromCloud(cloudFolder) {
+ upsertFolderFromCloud(cloudFolder, localSpaceId = null) {
try {
if (!this.db) throw new Error("Database not initialized");
const stmt = this.db.prepare(`
- INSERT INTO folders (client_folder_id, cloud_id, name, is_default, sort_order, sync_status, created_at, updated_at)
- VALUES (?, ?, ?, ?, ?, 'synced', ?, ?)
+ INSERT INTO folders (client_folder_id, cloud_id, name, is_default, sort_order, space_id, sync_status, created_at, updated_at)
+ VALUES (?, ?, ?, ?, ?, ?, 'synced', ?, ?)
ON CONFLICT(client_folder_id) DO UPDATE SET
cloud_id = excluded.cloud_id,
name = excluded.name,
sort_order = excluded.sort_order,
+ space_id = excluded.space_id,
sync_status = 'synced',
updated_at = excluded.updated_at
`);
@@ -2871,6 +3202,7 @@ class DatabaseManager {
cloudFolder.name,
cloudFolder.is_default ? 1 : 0,
cloudFolder.sort_order || 0,
+ localSpaceId ?? this.getPrivateSpaceId(),
cloudFolder.created_at,
cloudFolder.updated_at || cloudFolder.created_at
);
diff --git a/src/helpers/ipcHandlers.js b/src/helpers/ipcHandlers.js
index 2fd023ba6..83a76ef9f 100644
--- a/src/helpers/ipcHandlers.js
+++ b/src/helpers/ipcHandlers.js
@@ -439,7 +439,7 @@ class IPCHandlers {
if (!vectorIndex.isReady()) return;
const { LocalEmbeddings } = require("./localEmbeddings");
const text = LocalEmbeddings.noteEmbedText(note.title, note.content, note.enhanced_content);
- vectorIndex.upsertNote(note.id, text).catch(() => {});
+ vectorIndex.upsertNote(note.id, text, { space_id: note.space_id }).catch(() => {});
});
}
@@ -1107,14 +1107,15 @@ class IPCHandlers {
ipcMain.handle(
"db-save-note",
- async (event, title, content, noteType, sourceFile, audioDuration, folderId) => {
+ async (event, title, content, noteType, sourceFile, audioDuration, folderId, spaceId) => {
const result = this.databaseManager.saveNote(
title,
content,
noteType,
sourceFile,
audioDuration,
- folderId
+ folderId,
+ spaceId
);
if (result?.success && result?.note) {
setImmediate(() => this.broadcastToWindows("note-added", result.note));
@@ -1129,8 +1130,8 @@ class IPCHandlers {
return this.databaseManager.getNote(id);
});
- ipcMain.handle("db-get-notes", async (event, noteType, limit, folderId) => {
- return this.databaseManager.getNotes(noteType, limit, folderId);
+ ipcMain.handle("db-get-notes", async (event, noteType, limit, folderId, spaceId) => {
+ return this.databaseManager.getNotes(noteType, limit, folderId, spaceId);
});
ipcMain.handle("db-update-note", async (event, id, updates) => {
@@ -1148,20 +1149,22 @@ class IPCHandlers {
return this.deleteNoteInternal(id);
});
- ipcMain.handle("db-search-notes", async (event, query, limit) => {
- return this.databaseManager.searchNotes(query, limit);
+ ipcMain.handle("db-search-notes", async (event, query, limit, spaceId) => {
+ return this.databaseManager.searchNotes(query, limit, spaceId);
});
- ipcMain.handle("db-semantic-search-notes", async (event, query, limit = 5) => {
+ ipcMain.handle("db-semantic-search-notes", async (event, query, limit = 5, spaceId) => {
const vectorIndex = require("./vectorIndex");
if (!vectorIndex.isReady()) {
- return this.databaseManager.searchNotes(query, limit);
+ return this.databaseManager.searchNotes(query, limit, spaceId);
}
try {
+ const vectorFilter =
+ spaceId != null ? { must: [{ key: "space_id", match: { value: spaceId } }] } : undefined;
const [ftsResults, vectorResults] = await Promise.all([
- this.databaseManager.searchNotes(query, limit * 2),
- vectorIndex.search(query, limit * 2),
+ this.databaseManager.searchNotes(query, limit * 2, spaceId),
+ vectorIndex.search(query, limit * 2, vectorFilter),
]);
// Filter low-confidence semantic matches before RRF
@@ -1193,7 +1196,7 @@ class IPCHandlers {
return rankedIds.map((id) => noteMap.get(id)).filter(Boolean);
} catch (error) {
debugLogger.error("Semantic search failed, falling back to FTS5", { error: error.message });
- return this.databaseManager.searchNotes(query, limit);
+ return this.databaseManager.searchNotes(query, limit, spaceId);
}
});
@@ -1222,12 +1225,12 @@ class IPCHandlers {
return note;
});
- ipcMain.handle("db-get-folders", async () => {
- return this.databaseManager.getFolders();
+ ipcMain.handle("db-get-folders", async (event, spaceId) => {
+ return this.databaseManager.getFolders(spaceId);
});
- ipcMain.handle("db-create-folder", async (event, name) => {
- const result = this.databaseManager.createFolder(name);
+ ipcMain.handle("db-create-folder", async (event, name, spaceId) => {
+ const result = this.databaseManager.createFolder(name, spaceId);
if (result?.success && result?.folder) {
setImmediate(() => {
this.broadcastToWindows("folder-created", result.folder);
@@ -1277,6 +1280,52 @@ class IPCHandlers {
return this.databaseManager.getFolderNoteCounts();
});
+ ipcMain.handle("db-get-spaces", async () => {
+ return this.databaseManager.getSpaces();
+ });
+
+ ipcMain.handle("db-create-space", async (event, space) => {
+ return this.databaseManager.createSpace(space);
+ });
+
+ ipcMain.handle("db-update-space", async (event, id, updates) => {
+ return this.databaseManager.updateSpace(id, updates);
+ });
+
+ ipcMain.handle("db-delete-space", async (event, id) => {
+ const space = this.databaseManager.db.prepare("SELECT kind FROM spaces WHERE id = ?").get(id);
+ if (!space) return { success: false, error: "Space not found" };
+ if (space.kind === "private") {
+ return { success: false, error: "Cannot delete the private space" };
+ }
+ this.databaseManager.db.prepare("DELETE FROM spaces WHERE id = ?").run(id);
+ return { success: true, id };
+ });
+
+ ipcMain.handle("db-purge-space", async (event, id) => {
+ const result = this.databaseManager.purgeSpace(id);
+ if (result?.success) {
+ setImmediate(() => {
+ const vectorIndex = require("./vectorIndex");
+ if (!vectorIndex.isReady()) return;
+ vectorIndex.deleteBySpace(result.spaceId).catch(() => {});
+ });
+ for (const noteId of result.noteIds ?? []) {
+ this._asyncMirrorDelete(noteId);
+ }
+ setImmediate(() => {
+ this.broadcastToWindows("space-purged", { spaceId: result.spaceId });
+ if (this._noteFilesEnabled) {
+ const markdownMirror = require("./markdownMirror");
+ for (const folderName of result.folderNames ?? []) {
+ markdownMirror.deleteFolder(folderName);
+ }
+ }
+ });
+ }
+ return result;
+ });
+
ipcMain.handle("db-get-actions", async () => {
return this.databaseManager.getActions();
});
@@ -1427,8 +1476,8 @@ class IPCHandlers {
ipcMain.handle("db-get-note-by-client-id", (_, clientNoteId) =>
this.databaseManager.getNoteByClientId(clientNoteId)
);
- ipcMain.handle("db-upsert-note-from-cloud", (_, cloudNote, localFolderId) =>
- this.databaseManager.upsertNoteFromCloud(cloudNote, localFolderId)
+ ipcMain.handle("db-upsert-note-from-cloud", (_, cloudNote, localFolderId, localSpaceId) =>
+ this.databaseManager.upsertNoteFromCloud(cloudNote, localFolderId, localSpaceId)
);
ipcMain.handle("db-mark-note-synced", (_, id, cloudId) =>
this.databaseManager.markNoteSynced(id, cloudId)
@@ -1451,8 +1500,8 @@ class IPCHandlers {
ipcMain.handle("db-get-folder-by-client-id", (_, clientFolderId) =>
this.databaseManager.getFolderByClientId(clientFolderId)
);
- ipcMain.handle("db-upsert-folder-from-cloud", (_, cloudFolder) =>
- this.databaseManager.upsertFolderFromCloud(cloudFolder)
+ ipcMain.handle("db-upsert-folder-from-cloud", (_, cloudFolder, localSpaceId) =>
+ this.databaseManager.upsertFolderFromCloud(cloudFolder, localSpaceId)
);
ipcMain.handle("db-mark-folder-synced", (_, id, cloudId) =>
this.databaseManager.markFolderSynced(id, cloudId)
@@ -1481,6 +1530,14 @@ class IPCHandlers {
return result;
});
+ // Spaces sync
+ ipcMain.handle("db-get-space-by-cloud-team-id", (_, cloudTeamId) =>
+ this.databaseManager.getSpaceByCloudTeamId(cloudTeamId)
+ );
+ ipcMain.handle("db-upsert-space-from-cloud", (_, team) =>
+ this.databaseManager.upsertSpaceFromCloud(team)
+ );
+
// Conversations sync
ipcMain.handle("db-get-pending-conversations", () =>
this.databaseManager.getPendingConversations()
diff --git a/src/helpers/vectorIndex.js b/src/helpers/vectorIndex.js
index 5cc85eb0b..1f26242f2 100644
--- a/src/helpers/vectorIndex.js
+++ b/src/helpers/vectorIndex.js
@@ -30,12 +30,12 @@ class VectorIndex {
}
}
- async upsertNote(noteId, text) {
+ async upsertNote(noteId, text, payload = {}) {
if (!this.client) return;
try {
const vector = await localEmbeddings.embedText(text);
await this.client.upsert(this.collectionName, {
- points: [{ id: noteId, vector: Array.from(vector), payload: {} }],
+ points: [{ id: noteId, vector: Array.from(vector), payload }],
});
} catch (err) {
debugLogger.debug("Vector index upsert failed", { noteId, error: err.message });
@@ -51,13 +51,25 @@ class VectorIndex {
}
}
- async search(queryText, limit = 5) {
+ async deleteBySpace(spaceId) {
+ if (!this.client) return;
+ try {
+ await this.client.delete(this.collectionName, {
+ filter: { must: [{ key: "space_id", match: { value: spaceId } }] },
+ });
+ } catch (err) {
+ debugLogger.debug("Vector index space delete failed", { spaceId, error: err.message });
+ }
+ }
+
+ async search(queryText, limit = 5, filter) {
if (!this.client) return [];
try {
const vector = await localEmbeddings.embedText(queryText);
const results = await this.client.search(this.collectionName, {
vector: Array.from(vector),
limit,
+ ...(filter ? { filter } : {}),
});
return results.map((r) => ({ noteId: r.id, score: r.score }));
} catch (err) {
@@ -79,7 +91,7 @@ class VectorIndex {
const points = batch.map((n, j) => ({
id: n.id,
vector: Array.from(vectors[j]),
- payload: {},
+ payload: { space_id: n.space_id },
}));
await this.client.upsert(this.collectionName, { points });
} catch (err) {
diff --git a/src/types/electron.ts b/src/types/electron.ts
index 4b214a3c6..00a3442ce 100644
--- a/src/types/electron.ts
+++ b/src/types/electron.ts
@@ -52,6 +52,7 @@ export interface NoteItem {
source_file: string | null;
audio_duration_seconds: number | null;
folder_id: number | null;
+ space_id: number;
transcript: string | null;
calendar_event_id: string | null;
participants: string | null;
@@ -94,6 +95,7 @@ export interface FolderItem {
name: string;
is_default: number;
sort_order: number;
+ space_id: number;
created_at: string;
updated_at: string;
client_folder_id: string;
@@ -104,6 +106,23 @@ export interface FolderItem {
team_id?: string | null;
}
+export interface SpaceItem {
+ id: number;
+ client_space_id: string;
+ cloud_team_id: string | null;
+ workspace_id: string | null;
+ kind: "private" | "team";
+ name: string;
+ emoji: string | null;
+ sort_order: number;
+ my_role: "admin" | "member" | null;
+ member_count: number | null;
+ sync_status: "synced" | "pending" | "error";
+ deleted_at: string | null;
+ created_at: string;
+ updated_at: string;
+}
+
export interface DictionaryEntryItem {
id: number;
word: string;
@@ -607,13 +626,15 @@ declare global {
noteType?: string,
sourceFile?: string | null,
audioDuration?: number | null,
- folderId?: number | null
+ folderId?: number | null,
+ spaceId?: number | null
) => Promise<{ success: boolean; note?: NoteItem }>;
getNote: (id: number) => Promise<NoteItem | null>;
getNotes: (
noteType?: string | null,
limit?: number,
- folderId?: number | null
+ folderId?: number | null,
+ spaceId?: number | null
) => Promise<NoteItem[]>;
updateNote: (
id: number,
@@ -624,6 +645,7 @@ declare global {
enhancement_prompt?: string | null;
enhanced_at_content_hash?: string | null;
folder_id?: number | null;
+ space_id?: number;
transcript?: string | null;
calendar_event_id?: string | null;
participants?: string | null;
@@ -641,8 +663,12 @@ declare global {
format: "txt" | "srt" | "json" | "md"
) => Promise<{ success: boolean; error?: string }>;
exportDictionary: (words: string[]) => Promise<{ success: boolean; error?: string }>;
- searchNotes: (query: string, limit?: number) => Promise<NoteItem[]>;
- semanticSearchNotes: (query: string, limit?: number) => Promise<NoteItem[]>;
+ searchNotes: (query: string, limit?: number, spaceId?: number | null) => Promise<NoteItem[]>;
+ semanticSearchNotes: (
+ query: string,
+ limit?: number,
+ spaceId?: number | null
+ ) => Promise<NoteItem[]>;
semanticReindexAll: () => Promise<{ success: boolean; indexed?: number; error?: string }>;
onSemanticReindexProgress: (
callback: (data: { done: number; total: number }) => void
@@ -654,9 +680,10 @@ declare global {
) => Promise<NoteItem>;
// Folder operations
- getFolders: () => Promise<FolderItem[]>;
+ getFolders: (spaceId?: number | null) => Promise<FolderItem[]>;
createFolder: (
- name: string
+ name: string,
+ spaceId?: number | null
) => Promise<{ success: boolean; folder?: FolderItem; error?: string }>;
deleteFolder: (id: number) => Promise<{ success: boolean; error?: string }>;
renameFolder: (
@@ -665,6 +692,28 @@ declare global {
) => Promise<{ success: boolean; folder?: FolderItem; error?: string }>;
getFolderNoteCounts: () => Promise<Array<{ folder_id: number; count: number }>>;
+ // Space operations
+ getSpaces?: () => Promise<SpaceItem[]>;
+ createSpace?: (space: {
+ name: string;
+ emoji?: string | null;
+ }) => Promise<{ success: boolean; space?: SpaceItem; error?: string }>;
+ updateSpace?: (
+ id: number,
+ updates: { name?: string; emoji?: string | null }
+ ) => Promise<{ success: boolean; space?: SpaceItem; error?: string }>;
+ deleteSpace?: (id: number) => Promise<{ success: boolean; id?: number; error?: string }>;
+ purgeSpace?: (id: number) => Promise<{
+ success: boolean;
+ noteIds?: number[];
+ folderNames?: string[];
+ spaceId?: number;
+ error?: string;
+ }>;
+ getSpaceByCloudTeamId?: (cloudTeamId: string) => Promise<SpaceItem | null>;
+ upsertSpaceFromCloud?: (team: Record<string, unknown>) => Promise<SpaceItem>;
+ onSpacePurged?: (callback: (payload: { spaceId: number }) => void) => () => void;
+
// Note files (markdown mirror)
noteFilesSetEnabled?: (
enabled: boolean,
@@ -1934,7 +1983,8 @@ declare global {
getNoteByClientId?: (clientNoteId: string) => Promise<NoteItem | null>;
upsertNoteFromCloud?: (
cloudNote: Record<string, unknown>,
- localFolderId: number | null
+ localFolderId: number | null,
+ localSpaceId?: number | null
) => Promise<NoteItem>;
markNoteSynced?: (id: number, cloudId: string) => Promise<void>;
markNoteSyncError?: (id: number) => Promise<void>;
@@ -1942,7 +1992,10 @@ declare global {
getPendingFolders?: () => Promise<FolderItem[]>;
getFolderByClientId?: (clientFolderId: string) => Promise<FolderItem | null>;
- upsertFolderFromCloud?: (cloudFolder: Record<string, unknown>) => Promise<FolderItem>;
+ upsertFolderFromCloud?: (
+ cloudFolder: Record<string, unknown>,
+ localSpaceId?: number | null
+ ) => Promise<FolderItem>;
markFolderSynced?: (id: number, cloudId: string) => Promise<void>;
adoptFolderIdentity?: (
id: number,
diff --git a/test/helpers/spacesDatabase.test.js b/test/helpers/spacesDatabase.test.js
new file mode 100644
index 000000000..e8879edcd
--- /dev/null
+++ b/test/helpers/spacesDatabase.test.js
@@ -0,0 +1,275 @@
+const test = require("node:test");
+const assert = require("node:assert/strict");
+const fs = require("node:fs");
+const os = require("node:os");
+const path = require("node:path");
+const Module = require("node:module");
+
+let userDataDir = fs.mkdtempSync(path.join(os.tmpdir(), "openwhispr-spaces-db-"));
+const originalLoad = Module._load;
+
+Module._load = function patchedLoad(request, parent, isMain) {
+ if (request === "electron") {
+ return {
+ app: {
+ getPath: () => userDataDir,
+ getAppPath: () => process.cwd(),
+ isReady: () => false,
+ },
+ };
+ }
+ return originalLoad.call(this, request, parent, isMain);
+};
+
+process.env.NODE_ENV = "test";
+
+const DatabaseManager = require("../../src/helpers/database.js");
+
+function isNativeBindingUnavailable(error) {
+ const message = String(error?.message || error);
+ return (
+ message.includes("NODE_MODULE_VERSION") ||
+ message.includes("Could not locate the bindings file")
+ );
+}
+
+function createDb(t) {
+ userDataDir = fs.mkdtempSync(path.join(os.tmpdir(), "openwhispr-spaces-db-"));
+ try {
+ const BetterSqlite = require("better-sqlite3");
+ const probe = new BetterSqlite(path.join(userDataDir, "probe.db"));
+ probe.close();
+ fs.rmSync(path.join(userDataDir, "probe.db"), { force: true });
+ } catch (error) {
+ if (isNativeBindingUnavailable(error)) {
+ t.skip("better-sqlite3 native binding is not available for this Node runtime");
+ return null;
+ }
+ throw error;
+ }
+
+ try {
+ return new DatabaseManager();
+ } catch (error) {
+ if (isNativeBindingUnavailable(error)) {
+ t.skip("better-sqlite3 native binding is not available for this Node runtime");
+ return null;
+ }
+ throw error;
+ }
+}
+
+test("spaces migration is idempotent across launches", (t) => {
+ const db = createDb(t);
+ if (!db) return;
+
+ const foldersSql = db.db
+ .prepare("SELECT sql FROM sqlite_master WHERE type = 'table' AND name = 'folders'")
+ .get().sql;
+ assert.ok(
+ !foldersSql.includes("UNIQUE"),
+ "folders rebuild should drop the UNIQUE(name) constraint"
+ );
+ db.db.close();
+
+ const db2 = new DatabaseManager();
+ const rerunSql = db2.db
+ .prepare("SELECT sql FROM sqlite_master WHERE type = 'table' AND name = 'folders'")
+ .get().sql;
+ assert.equal(rerunSql, foldersSql, "second launch must not rebuild folders again");
+
+ const noteColumns = db2.db.pragma("table_info('notes')").map((col) => col.name);
+ assert.ok(noteColumns.includes("space_id"));
+ const folderColumns = db2.db.pragma("table_info('folders')").map((col) => col.name);
+ assert.ok(folderColumns.includes("space_id"));
+
+ const indexes = db2.db
+ .prepare("SELECT name FROM sqlite_master WHERE type = 'index' AND tbl_name = 'folders'")
+ .all()
+ .map((row) => row.name);
+ assert.ok(indexes.includes("idx_folders_client_folder_id"));
+ assert.ok(indexes.includes("idx_folders_space_name"));
+
+ const privates = db2.db
+ .prepare("SELECT COUNT(*) as count FROM spaces WHERE kind = 'private'")
+ .get();
+ assert.equal(privates.count, 1);
+});
+
+test("pre-migration rows are backfilled into the private space", (t) => {
+ const db = createDb(t);
+ if (!db) return;
+ const privateId = db.getPrivateSpaceId();
+ assert.ok(privateId);
+
+ for (const folder of db.getFolders()) {
+ assert.equal(folder.space_id, privateId);
+ }
+ for (const note of db.getNotes()) {
+ assert.equal(note.space_id, privateId);
+ }
+
+ // Simulate rows written before the spaces migration existed.
+ db.db
+ .prepare("INSERT INTO folders (name, client_folder_id) VALUES ('Legacy', 'legacy-folder')")
+ .run();
+ db.db
+ .prepare(
+ "INSERT INTO notes (title, content, client_note_id) VALUES ('Legacy', '', 'legacy-note')"
+ )
+ .run();
+ db.db.close();
+
+ const db2 = new DatabaseManager();
+ const legacyFolder = db2.db
+ .prepare("SELECT * FROM folders WHERE client_folder_id = 'legacy-folder'")
+ .get();
+ assert.equal(legacyFolder.space_id, privateId);
+ const legacyNote = db2.db
+ .prepare("SELECT * FROM notes WHERE client_note_id = 'legacy-note'")
+ .get();
+ assert.equal(legacyNote.space_id, privateId);
+});
+
+test("folder names are unique per space, not globally", (t) => {
+ const db = createDb(t);
+ if (!db) return;
+ const team = db.createSpace({ name: "Design" });
+ assert.ok(team.success);
+ assert.equal(team.space.kind, "team");
+
+ const inPrivate = db.createFolder("Projects");
+ assert.ok(inPrivate.success);
+ assert.equal(inPrivate.folder.space_id, db.getPrivateSpaceId());
+
+ const inTeam = db.createFolder("Projects", team.space.id);
+ assert.ok(inTeam.success, "same name in another space must be allowed");
+ assert.equal(inTeam.folder.space_id, team.space.id);
+
+ assert.equal(db.createFolder("Projects").success, false);
+ assert.equal(db.createFolder("Projects", team.space.id).success, false);
+});
+
+test("updateNote forces space_id to follow folder_id (D2)", (t) => {
+ const db = createDb(t);
+ if (!db) return;
+ const privateId = db.getPrivateSpaceId();
+ const team = db.createSpace({ name: "Eng" }).space;
+ const teamFolder = db.createFolder("Docs", team.id).folder;
+
+ const { note } = db.saveNote("Move me", "content");
+ assert.equal(note.space_id, privateId);
+
+ const moved = db.updateNote(note.id, { folder_id: teamFolder.id, space_id: privateId });
+ assert.equal(moved.note.folder_id, teamFolder.id);
+ assert.equal(moved.note.space_id, team.id, "folder's space must win over an explicit space_id");
+
+ const detached = db.updateNote(note.id, { folder_id: null, space_id: privateId });
+ assert.equal(detached.note.folder_id, null);
+ assert.equal(detached.note.space_id, privateId);
+
+ const retitled = db.updateNote(note.id, { title: "kept" });
+ assert.equal(
+ retitled.note.space_id,
+ privateId,
+ "space must not change without folder/space updates"
+ );
+});
+
+test("purgeSpace leaves zero residue for the space and spares the private space", (t) => {
+ const db = createDb(t);
+ if (!db) return;
+ const privateId = db.getPrivateSpaceId();
+ const team = db.createSpace({ name: "Secret" }).space;
+ const teamFolder = db.createFolder("Vault", team.id).folder;
+
+ const teamNote = db.saveNote(
+ "Team plan",
+ "classified zebracorn intel",
+ "personal",
+ null,
+ null,
+ teamFolder.id
+ ).note;
+ assert.equal(teamNote.space_id, team.id);
+ const privateNote = db.saveNote("Mine", "private groundhog data").note;
+
+ const seedMapping = db.db.prepare(
+ "INSERT INTO speaker_mappings (note_id, speaker_id, display_name) VALUES (?, ?, ?)"
+ );
+ const seedEmbedding = db.db.prepare(
+ "INSERT INTO note_speaker_embeddings (note_id, speaker_id, embedding) VALUES (?, ?, ?)"
+ );
+ for (const note of [teamNote, privateNote]) {
+ seedMapping.run(note.id, "spk_0", "Alice");
+ seedEmbedding.run(note.id, "spk_0", Buffer.from(new Float32Array([0.1, 0.2]).buffer));
+ }
+
+ const result = db.purgeSpace(team.id);
+ assert.ok(result.success);
+ assert.deepEqual(result.noteIds, [teamNote.id]);
+ assert.deepEqual(result.folderNames, ["Vault"]);
+ assert.equal(result.spaceId, team.id);
+
+ const count = (sql, ...args) => db.db.prepare(sql).get(...args).count;
+ assert.equal(count("SELECT COUNT(*) as count FROM notes WHERE space_id = ?", team.id), 0);
+ assert.equal(count("SELECT COUNT(*) as count FROM folders WHERE space_id = ?", team.id), 0);
+ assert.equal(count("SELECT COUNT(*) as count FROM spaces WHERE id = ?", team.id), 0);
+ assert.equal(
+ count("SELECT COUNT(*) as count FROM speaker_mappings WHERE note_id = ?", teamNote.id),
+ 0
+ );
+ assert.equal(
+ count("SELECT COUNT(*) as count FROM note_speaker_embeddings WHERE note_id = ?", teamNote.id),
+ 0
+ );
+ assert.equal(
+ count("SELECT COUNT(*) as count FROM notes_fts WHERE notes_fts MATCH 'zebracorn'"),
+ 0
+ );
+
+ assert.equal(count("SELECT COUNT(*) as count FROM notes WHERE space_id = ?", privateId), 1);
+ assert.equal(
+ count("SELECT COUNT(*) as count FROM speaker_mappings WHERE note_id = ?", privateNote.id),
+ 1
+ );
+ assert.equal(
+ count("SELECT COUNT(*) as count FROM notes_fts WHERE notes_fts MATCH 'groundhog'"),
+ 1
+ );
+
+ const refused = db.purgeSpace(privateId);
+ assert.equal(refused.success, false);
+ assert.equal(count("SELECT COUNT(*) as count FROM spaces WHERE id = ?", privateId), 1);
+});
+
+test("saveNote resolves default folders within the target space", (t) => {
+ const db = createDb(t);
+ if (!db) return;
+ const privateId = db.getPrivateSpaceId();
+ const team = db.createSpace({ name: "Ops" }).space;
+ db.db
+ .prepare(
+ "INSERT INTO folders (name, is_default, sort_order, space_id, client_folder_id) VALUES ('Meetings', 1, 0, ?, 'team-meetings')"
+ )
+ .run(team.id);
+
+ const privateMeetingsFolder = db.getMeetingsFolder();
+ const teamMeetingsFolder = db.getMeetingsFolder(team.id);
+ assert.ok(privateMeetingsFolder);
+ assert.ok(teamMeetingsFolder);
+ assert.notEqual(teamMeetingsFolder.id, privateMeetingsFolder.id);
+
+ const privateMeeting = db.saveNote("Standup", "notes", "meeting").note;
+ assert.equal(privateMeeting.folder_id, privateMeetingsFolder.id);
+ assert.equal(privateMeeting.space_id, privateId);
+
+ const teamMeeting = db.saveNote("Sync", "notes", "meeting", null, null, null, team.id).note;
+ assert.equal(teamMeeting.folder_id, teamMeetingsFolder.id);
+ assert.equal(teamMeeting.space_id, team.id);
+
+ // No matching default folder in the team space → note keeps the space, no folder.
+ const teamDoc = db.saveNote("Doc", "body", "personal", null, null, null, team.id).note;
+ assert.equal(teamDoc.folder_id, null);
+ assert.equal(teamDoc.space_id, team.id);
+});