Voice-to-text dictation app with local (Nvidia Parakeet/Whisper) and cloud models (BYOK). Privacy-first and available cross-platform.
JavaScript aianthropiccross-platformgeminigroqlinuxmacosnvidiaopen-sourceopenaiparakeetspeech-to-texttranscribewhisperwindows
feat(notes): space-scoped search & agent tools, cross-space folder sync
Gabriel Stein146ff4e05ea4
diff --git a/src/components/CommandSearch.tsx b/src/components/CommandSearch.tsxindex 30fd4cf09..16d9398e8 100644--- a/src/components/CommandSearch.tsx+++ b/src/components/CommandSearch.tsx@@ -1,8 +1,25 @@import { useState, useEffect, useCallback, useMemo, useRef } from "react";import { useTranslation } from "react-i18next";import * as DialogPrimitive from "@radix-ui/react-dialog";-import { Search, FileText, Mic, Folder, Lock, Users, Upload, MessageSquare } from "lucide-react";+import {+ Search,+ FileText,+ Mic,+ Folder,+ Lock,+ Users,+ Upload,+ MessageSquare,+ ChevronDown,+} from "lucide-react";import { cn } from "./lib/utils";+import {+ DropdownMenu,+ DropdownMenuTrigger,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuSeparator,+} from "./ui/dropdown-menu";import type { NoteItem, FolderItem, SpaceItem, TranscriptionItem } from "../types/electron.js";import { formatRelativeTime } from "../utils/dateFormatting";@@ -62,6 +79,7 @@ export default function CommandSearch({const [notes, setNotes] = useState<NoteItem[]>([]);const [folders, setFolders] = useState<FolderItem[]>([]);const [spaces, setSpaces] = useState<SpaceItem[]>([]);+ const [scopeSpaceId, setScopeSpaceId] = useState<number | null>(null);const [conversations, setConversations] = useState<ConversationResult[]>([]);const [selectedIndex, setSelectedIndex] = useState(0);const inputRef = useRef<HTMLInputElement>(null);@@ -88,6 +106,7 @@ export default function CommandSearch({if (open && !prevOpen) {setPrevOpen(open);setQuery("");+ setScopeSpaceId(null);setSelectedIndex(0);} else if (open !== prevOpen) {setPrevOpen(open);@@ -162,7 +181,7 @@ export default function CommandSearch({}searchTimerRef.current = setTimeout(async () => {try {- const results = await window.electronAPI.searchNotes(query);+ const results = await window.electronAPI.searchNotes(query, undefined, scopeSpaceId);setNotes(results);} catch {/* keep current */@@ -173,7 +192,7 @@ export default function CommandSearch({return () => {if (searchTimerRef.current) clearTimeout(searchTimerRef.current);};- }, [query, isConversationsMode]);+ }, [query, isConversationsMode, scopeSpaceId]);if (notes !== prevNotes || query !== prevQuery) {setPrevNotes(notes);@@ -183,6 +202,21 @@ export default function CommandSearch({const folderMap = useMemo(() => new Map(folders.map((f) => [f.id, f])), [folders]);const spaceMap = useMemo(() => new Map(spaces.map((s) => [s.id, s])), [spaces]);+ const scopeSpace = scopeSpaceId != null ? spaceMap.get(scopeSpaceId) : undefined;++ // Scoping re-filters the visible list immediately, so the keyboard+ // highlight must restart from the top.+ const selectScope = useCallback((spaceId: number | null) => {+ setScopeSpaceId(spaceId);+ setSelectedIndex(0);+ }, []);++ // The search leg scopes at the DB; this also covers browsed (empty-query)+ // results and stale in-flight results after a scope switch.+ const scopedNotes = useMemo(+ () => (scopeSpaceId == null ? notes : notes.filter((n) => n.space_id === scopeSpaceId)),+ [notes, scopeSpaceId]+ );const spaceLabel = useCallback((space: SpaceItem) =>@@ -239,10 +273,10 @@ export default function CommandSearch({}const items: FlatItem[] = [];for (const target of jumpTargets) items.push({ kind: "container", target });- for (const note of notes) items.push({ kind: "note", note });+ for (const note of scopedNotes) items.push({ kind: "note", note });for (const transcript of filteredTranscripts) items.push({ kind: "transcript", transcript });return items;- }, [jumpTargets, notes, filteredTranscripts, conversations, isConversationsMode]);+ }, [jumpTargets, scopedNotes, filteredTranscripts, conversations, isConversationsMode]);const selectItem = useCallback((item: FlatItem) => {@@ -306,6 +340,42 @@ export default function CommandSearch({{/* Search input */}<div className="flex items-center gap-2.5 px-3.5 py-3 border-b border-border/40"><Search size={14} className="shrink-0 text-muted-foreground/50" />+ {!isConversationsMode && spaces.length > 1 && (+ <DropdownMenu>+ <DropdownMenuTrigger asChild>+ <button+ type="button"+ className={cn(+ "flex items-center gap-1 shrink-0 rounded-md border border-border/50 bg-muted/40",+ "px-1.5 py-0.5 text-[11px] transition-colors outline-none",+ scopeSpace ? "text-foreground" : "text-muted-foreground hover:text-foreground"+ )}+ >+ <span className="truncate max-w-32">+ {scopeSpace ? spaceLabel(scopeSpace) : t("commandSearch.allSpaces")}+ </span>+ <ChevronDown size={11} className="shrink-0 text-muted-foreground/50" />+ </button>+ </DropdownMenuTrigger>+ <DropdownMenuContent+ align="start"+ onCloseAutoFocus={(e) => {+ e.preventDefault();+ inputRef.current?.focus();+ }}+ >+ <DropdownMenuItem onSelect={() => selectScope(null)}>+ {t("commandSearch.allSpaces")}+ </DropdownMenuItem>+ <DropdownMenuSeparator />+ {spaces.map((space) => (+ <DropdownMenuItem key={space.id} onSelect={() => selectScope(space.id)}>+ {spaceLabel(space)}+ </DropdownMenuItem>+ ))}+ </DropdownMenuContent>+ </DropdownMenu>+ )}<inputref={inputRef}value={query}@@ -407,13 +477,13 @@ export default function CommandSearch({</div>)}- {notes.length > 0 && (+ {scopedNotes.length > 0 && (<div className={jumpTargets.length > 0 ? "mt-0.5" : ""}><SectionHeadericon={<FileText size={11} />}label={t("commandSearch.sections.notes")}/>- {notes.map((note) => {+ {scopedNotes.map((note) => {const idx = flatItems.findIndex((fi) => fi.kind === "note" && fi.note.id === note.id);@@ -434,7 +504,7 @@ export default function CommandSearch({)}{filteredTranscripts.length > 0 && (- <div className={jumpTargets.length > 0 || notes.length > 0 ? "mt-0.5" : ""}>+ <div className={jumpTargets.length > 0 || scopedNotes.length > 0 ? "mt-0.5" : ""}><SectionHeadericon={<Mic size={11} />}label={t("commandSearch.sections.transcripts")}diff --git a/src/components/ControlPanel.tsx b/src/components/ControlPanel.tsxindex 734413aa2..e64218168 100644--- a/src/components/ControlPanel.tsx+++ b/src/components/ControlPanel.tsx@@ -170,6 +170,23 @@ export default function ControlPanel({ initialSettingsSection }: ControlPanelPro});}, []);+ // One-time background reindex after the spaces migration: pre-existing+ // Qdrant points carry no space_id payload, so scoped semantic search would+ // miss them. Delayed so the Qdrant sidecar has time to come up; if it isn't+ // ready yet the flag stays unset and the next launch retries.+ useEffect(() => {+ if (localStorage.getItem("semanticSpaceReindexDone") === "true") return;+ const timer = setTimeout(() => {+ window.electronAPI+ ?.semanticReindexAll?.()+ .then((result) => {+ if (result?.success) localStorage.setItem("semanticSpaceReindexDone", "true");+ })+ .catch(() => {});+ }, 15_000);+ return () => clearTimeout(timer);+ }, []);+useEffect(() => {if (platform !== "darwin") return;window.electronAPI?.getPostMigrationState?.().then((state) => {diff --git a/src/components/notes/SpaceSyncToastListener.tsx b/src/components/notes/SpaceSyncToastListener.tsxindex 05b6c7da9..a0956dd39 100644--- a/src/components/notes/SpaceSyncToastListener.tsx+++ b/src/components/notes/SpaceSyncToastListener.tsx@@ -2,13 +2,14 @@ import { useEffect } from "react";import { useTranslation } from "react-i18next";import { useToast } from "../ui/useToast";-const REVOKED_DEDUPE_MS = 15_000;+const DEDUPE_MS = 15_000;/*** Headless. Mount once inside ToastProvider so team-space access changes* raised by sync surface even when the user is outside the notes view.* A rejected push and the following spaces-pass purge can both announce the- * same space, so access-revoked toasts dedupe by space name.+ * same space, so access-revoked toasts dedupe by space name; folder name+ * conflicts recur every sync pass while unresolved, so they dedupe too.*/export default function SpaceSyncToastListener() {const { t } = useTranslation();@@ -16,12 +17,13 @@ export default function SpaceSyncToastListener() {useEffect(() => {const lastRevokedAt = new Map<string, number>();+ const lastFolderConflictAt = new Map<string, number>();const onSpaceRevoked = (event: Event) => {const { spaceName } = (event as CustomEvent<{ spaceName: string | null }>).detail;if (!spaceName) return;const now = Date.now();- if (now - (lastRevokedAt.get(spaceName) ?? 0) < REVOKED_DEDUPE_MS) return;+ if (now - (lastRevokedAt.get(spaceName) ?? 0) < DEDUPE_MS) return;lastRevokedAt.set(spaceName, now);toast({title: t("notes.spaces.accessRevoked", { space: spaceName }),@@ -29,6 +31,17 @@ export default function SpaceSyncToastListener() {});};+ const onFolderNameTaken = (event: Event) => {+ const { name } = (event as CustomEvent<{ name: string }>).detail;+ const now = Date.now();+ if (now - (lastFolderConflictAt.get(name) ?? 0) < DEDUPE_MS) return;+ lastFolderConflictAt.set(name, now);+ toast({+ title: t("notes.spaces.folderNameTaken", { name }),+ variant: "destructive",+ });+ };+const onNoteRelocated = (event: Event) => {const { title, spaceName } = (event as CustomEvent<{ title: string | null; spaceName: string | null }>@@ -44,9 +57,11 @@ export default function SpaceSyncToastListener() {window.addEventListener("openwhispr:space-revoked", onSpaceRevoked);window.addEventListener("openwhispr:note-relocated", onNoteRelocated);+ window.addEventListener("openwhispr:folder-name-taken", onFolderNameTaken);return () => {window.removeEventListener("openwhispr:space-revoked", onSpaceRevoked);window.removeEventListener("openwhispr:note-relocated", onNoteRelocated);+ window.removeEventListener("openwhispr:folder-name-taken", onFolderNameTaken);};}, [toast, t]);diff --git a/src/locales/de/translation.json b/src/locales/de/translation.jsonindex 8f1099d71..b33138f69 100644--- a/src/locales/de/translation.json+++ b/src/locales/de/translation.json@@ -2403,6 +2403,7 @@"moved": "„{{title}}“ nach {{target}} verschoben","couldNotMove": "Ordner konnte nicht verschoben werden","couldNotMoveNote": "Notiz konnte nicht verschoben werden",+ "folderNameTaken": "„{{name}}“ konnte nicht verschoben werden – dort existiert bereits ein Ordner mit diesem Namen","undo": "Rückgängig","emptySpace": "Noch keine Notizen. Notizen hier sind für alle in {{space}} sichtbar.","noteCount_one": "{{count}} Notiz",@@ -3033,6 +3034,7 @@}},"commandSearch": {+ "allSpaces": "Alle Bereiche","title": "Suche","description": "In Notizen und Transkripten suchen","shortPlaceholder": "Suche",diff --git a/src/locales/en/translation.json b/src/locales/en/translation.jsonindex 797b0da26..f9b1eeb73 100644--- a/src/locales/en/translation.json+++ b/src/locales/en/translation.json@@ -2403,6 +2403,7 @@"moved": "Moved “{{title}}” to {{target}}","couldNotMove": "Couldn't move folder","couldNotMoveNote": "Couldn't move note",+ "folderNameTaken": "Couldn't move “{{name}}” — a folder with that name already exists there","undo": "Undo","emptySpace": "No notes yet. Notes here are visible to everyone in {{space}}.","noteCount_one": "{{count}} note",@@ -3033,6 +3034,7 @@}},"commandSearch": {+ "allSpaces": "All spaces","title": "Search","description": "Search across notes and transcripts","shortPlaceholder": "Search",diff --git a/src/locales/es/translation.json b/src/locales/es/translation.jsonindex ea0934d28..053a1cd2d 100644--- a/src/locales/es/translation.json+++ b/src/locales/es/translation.json@@ -2245,6 +2245,7 @@"moved": "«{{title}}» se movió a {{target}}","couldNotMove": "No se pudo mover la carpeta","couldNotMoveNote": "No se pudo mover la nota",+ "folderNameTaken": "No se pudo mover «{{name}}»: ya existe una carpeta con ese nombre allí","undo": "Deshacer","emptySpace": "Aún no hay notas. Las notas aquí son visibles para todos en {{space}}.","noteCount_one": "{{count}} nota",@@ -2976,6 +2977,7 @@}},"commandSearch": {+ "allSpaces": "Todos los espacios","title": "Buscar","description": "Buscar en notas y transcripciones","shortPlaceholder": "Buscar",diff --git a/src/locales/fr/translation.json b/src/locales/fr/translation.jsonindex 7f261ffed..f4d046d13 100644--- a/src/locales/fr/translation.json+++ b/src/locales/fr/translation.json@@ -2403,6 +2403,7 @@"moved": "« {{title}} » déplacée vers {{target}}","couldNotMove": "Impossible de déplacer le dossier","couldNotMoveNote": "Impossible de déplacer la note",+ "folderNameTaken": "Impossible de déplacer « {{name}} » : un dossier portant ce nom existe déjà à cet emplacement","undo": "Annuler","emptySpace": "Aucune note pour le moment. Les notes ici sont visibles par tous les membres de {{space}}.","noteCount_one": "{{count}} note",@@ -3033,6 +3034,7 @@}},"commandSearch": {+ "allSpaces": "Tous les espaces","title": "Rechercher","description": "Rechercher dans les notes et transcriptions","shortPlaceholder": "Rechercher",diff --git a/src/locales/it/translation.json b/src/locales/it/translation.jsonindex fe33f6d69..37758bee1 100644--- a/src/locales/it/translation.json+++ b/src/locales/it/translation.json@@ -2197,6 +2197,7 @@"moved": "“{{title}}” spostata in {{target}}","couldNotMove": "Impossibile spostare la cartella","couldNotMoveNote": "Impossibile spostare la nota",+ "folderNameTaken": "Impossibile spostare “{{name}}”: esiste già una cartella con questo nome in quella posizione","undo": "Annulla","emptySpace": "Ancora nessuna nota. Le note qui sono visibili a tutti in {{space}}.","noteCount_one": "{{count}} nota",@@ -2928,6 +2929,7 @@}},"commandSearch": {+ "allSpaces": "Tutti gli spazi","title": "Cerca","description": "Cerca tra note e trascrizioni","shortPlaceholder": "Cerca",diff --git a/src/locales/ja/translation.json b/src/locales/ja/translation.jsonindex c1db36258..b2dc7f64b 100644--- a/src/locales/ja/translation.json+++ b/src/locales/ja/translation.json@@ -2125,6 +2125,7 @@"moved": "「{{title}}」を{{target}}に移動しました","couldNotMove": "フォルダを移動できませんでした","couldNotMoveNote": "ノートを移動できませんでした",+ "folderNameTaken": "「{{name}}」を移動できませんでした。同じ名前のフォルダが既に存在します","undo": "元に戻す","emptySpace": "まだノートがありません。ここのノートは{{space}}の全員に表示されます。","noteCount_one": "{{count}} 件のノート",@@ -2928,6 +2929,7 @@}},"commandSearch": {+ "allSpaces": "すべてのスペース","title": "検索","description": "ノートと文字起こしを検索","shortPlaceholder": "検索",diff --git a/src/locales/pt/translation.json b/src/locales/pt/translation.jsonindex 82cebc5bd..a053433a4 100644--- a/src/locales/pt/translation.json+++ b/src/locales/pt/translation.json@@ -2197,6 +2197,7 @@"moved": "“{{title}}” movida para {{target}}","couldNotMove": "Não foi possível mover a pasta","couldNotMoveNote": "Não foi possível mover a nota",+ "folderNameTaken": "Não foi possível mover “{{name}}”: já existe uma pasta com esse nome nesse local","undo": "Desfazer","emptySpace": "Nenhuma nota ainda. As notas aqui são visíveis para todos em {{space}}.","noteCount_one": "{{count}} nota",@@ -2928,6 +2929,7 @@}},"commandSearch": {+ "allSpaces": "Todos os espaços","title": "Pesquisar","description": "Pesquisar notas e transcrições","shortPlaceholder": "Pesquisar",diff --git a/src/locales/ru/translation.json b/src/locales/ru/translation.jsonindex c2eb98217..58239655d 100644--- a/src/locales/ru/translation.json+++ b/src/locales/ru/translation.json@@ -2199,6 +2199,7 @@"moved": "«{{title}}» перемещено в {{target}}","couldNotMove": "Не удалось переместить папку","couldNotMoveNote": "Не удалось переместить заметку",+ "folderNameTaken": "Не удалось переместить «{{name}}» — там уже есть папка с таким именем","undo": "Отменить","emptySpace": "Пока нет заметок. Заметки здесь видны всем в {{space}}.","noteCount_one": "{{count}} заметка",@@ -2938,6 +2939,7 @@}},"commandSearch": {+ "allSpaces": "Все пространства","title": "Поиск","description": "Поиск по заметкам и транскрипциям","shortPlaceholder": "Поиск",diff --git a/src/locales/zh-CN/translation.json b/src/locales/zh-CN/translation.jsonindex 6d22c5fc2..59fe09488 100644--- a/src/locales/zh-CN/translation.json+++ b/src/locales/zh-CN/translation.json@@ -1209,12 +1209,7 @@"annualEquivalent": "$16.67","includesPrefix": "所有 Pro 功能 +","badge": "最受欢迎",- "features": [- "无限会议录制",- "代理模式",- "与您的数据对话",- "优先支持"- ],+ "features": ["无限会议录制", "代理模式", "与您的数据对话", "优先支持"],"cta": "开始使用","switchToAnnual": "切换为年付"},@@ -2197,6 +2192,7 @@"moved": "已将“{{title}}”移动到 {{target}}","couldNotMove": "无法移动文件夹","couldNotMoveNote": "无法移动笔记",+ "folderNameTaken": "无法移动“{{name}}”:该位置已存在同名文件夹","undo": "撤销","emptySpace": "还没有笔记。这里的笔记对 {{space}} 中的所有人可见。","noteCount_one": "{{count}} 条笔记",@@ -2928,6 +2924,7 @@}},"commandSearch": {+ "allSpaces": "所有空间","title": "搜索","description": "搜索笔记和转录","shortPlaceholder": "搜索",diff --git a/src/locales/zh-TW/translation.json b/src/locales/zh-TW/translation.jsonindex c545da5ab..134a264b3 100644--- a/src/locales/zh-TW/translation.json+++ b/src/locales/zh-TW/translation.json@@ -1209,12 +1209,7 @@"annualEquivalent": "$16.67","includesPrefix": "所有 Pro 功能 +","badge": "最熱門",- "features": [- "無限會議錄製",- "代理模式",- "與您的資料對話",- "優先支援"- ],+ "features": ["無限會議錄製", "代理模式", "與您的資料對話", "優先支援"],"cta": "開始使用","switchToAnnual": "切換為年付"},@@ -2197,6 +2192,7 @@"moved": "已將「{{title}}」移動到 {{target}}","couldNotMove": "無法移動資料夾","couldNotMoveNote": "無法移動筆記",+ "folderNameTaken": "無法移動「{{name}}」:該位置已存在同名資料夾","undo": "復原","emptySpace": "還沒有筆記。這裡的筆記對 {{space}} 中的所有人可見。","noteCount_one": "{{count}} 則筆記",@@ -2928,6 +2924,7 @@}},"commandSearch": {+ "allSpaces": "所有空間","title": "搜尋","description": "搜尋筆記與轉錄","shortPlaceholder": "搜尋",diff --git a/src/services/NotesService.ts b/src/services/NotesService.tsindex 575b0ce99..82bafeca6 100644--- a/src/services/NotesService.ts+++ b/src/services/NotesService.ts@@ -105,10 +105,19 @@ async function deleteAll(): Promise<{ deleted: number; errors: number }> {return { deleted: results.length - errors, errors };}-async function search(query: string, limit?: number): Promise<{ notes: SearchResult[] }> {+// scope "all" opts into team results (legacy clients stay personal-only);+// team_id narrows to a single team and takes precedence over scope.+async function search(+ query: string,+ limit?: number,+ scope?: "all",+ teamId?: string+): Promise<{ notes: SearchResult[] }> {return cloudPost<{ notes: SearchResult[] }>("/api/notes/search", {query,...(limit !== undefined ? { limit } : {}),+ ...(scope !== undefined ? { scope } : {}),+ ...(teamId !== undefined ? { team_id: teamId } : {}),});}diff --git a/src/services/SyncService.ts b/src/services/SyncService.tsindex 0542923b3..0967ba53a 100644--- a/src/services/SyncService.ts+++ b/src/services/SyncService.ts@@ -29,6 +29,12 @@ function isTeamAccessError(err: unknown): boolean {);}+// Typed 409 from a folder rename/move colliding with a same-named folder in+// the target scope; the row stays pending until the conflict is resolved.+function isFolderNameTakenError(err: unknown): boolean {+ return err instanceof CloudApiError && err.code === "folder_name_taken";+}+// Extra fields pushed with note/folder payloads so the server files rows into// the right team scope; `null` scope means the row must not push at all.type PushScopeFields = { workspace_id?: string | null; team_id?: string | null };@@ -219,9 +225,7 @@ class SyncService {}}- requestSyncAll(- reason: "start" | "focus" | "interval" | "online" | "manual" | "team-push"- ): void {+ requestSyncAll(reason: "start" | "focus" | "interval" | "online" | "manual" | "team-push"): void {if (!this.canSync() && !this.canSyncSharedNotes()) return;if (reason !== "manual" &&@@ -315,18 +319,25 @@ class SyncService {const folder = folders.find((f) => f.id === id);if (!folder) return;+ const ctx = await this.buildSpaceContext();+ const scope = this.pushScopeFields(ctx.byId.get(folder.space_id));+ if (!scope) {+ console.warn(`Skipping folder ${folder.id} push: its team space has no cloud team yet`);+ return;+ }+if (folder.cloud_id) {- await FoldersService.update(folder.cloud_id, {- name: folder.name,- sort_order: folder.sort_order,- });- } else {- const ctx = await this.buildSpaceContext();- const scope = this.pushScopeFields(ctx.byId.get(folder.space_id));- if (!scope) {- console.warn(`Skipping folder ${folder.id} push: its team space has no cloud team yet`);- return;+ try {+ await FoldersService.update(folder.cloud_id, {+ name: folder.name,+ sort_order: folder.sort_order,+ ...scope,+ });+ } catch (err) {+ if (!isFolderNameTakenError(err)) throw err;+ this.dispatchFolderNameTaken(folder.name);}+ } else {const cloud = await FoldersService.create({name: folder.name,client_folder_id: folder.client_folder_id,@@ -593,9 +604,7 @@ class SyncService {}private dispatchSpaceRevoked(spaceName: string | null): void {- window.dispatchEvent(- new CustomEvent("openwhispr:space-revoked", { detail: { spaceName } })- );+ window.dispatchEvent(new CustomEvent("openwhispr:space-revoked", { detail: { spaceName } }));}private dispatchNoteRelocated(title: string | null, spaceName: string | null | undefined): void {@@ -606,6 +615,10 @@ class SyncService {);}+ private dispatchFolderNameTaken(name: string): void {+ window.dispatchEvent(new CustomEvent("openwhispr:folder-name-taken", { detail: { name } }));+ }+private async syncFolders(teamOnly = false): Promise<void> {if (!teamOnly) await this.adoptDefaultFolders();await this.pushPendingFolders(teamOnly);@@ -688,14 +701,17 @@ class SyncService {const migration = pushable.filter(({ folder }) => folder.cloud_id);const fresh = pushable.filter(({ folder }) => !folder.cloud_id);- for (const { folder } of migration) {+ for (const { folder, scope } of migration) {try {- // The folders update endpoint carries no scope fields — folder moves- // between spaces don't propagate through PATCH in v1.- await FoldersService.update(folder.cloud_id!, { name: folder.name });+ await FoldersService.update(folder.cloud_id!, { name: folder.name, ...scope });await window.electronAPI.markFolderSynced?.(folder.id, folder.cloud_id!);} catch (err) {- console.error("Folder migration sync failed:", err);+ if (isFolderNameTakenError(err)) {+ // Leave the row pending; retried on the next pass.+ this.dispatchFolderNameTaken(folder.name);+ } else {+ console.error("Folder migration sync failed:", err);+ }}}diff --git a/src/services/tools/createNoteTool.ts b/src/services/tools/createNoteTool.tsindex 6d6da972c..a16d89cd2 100644--- a/src/services/tools/createNoteTool.ts+++ b/src/services/tools/createNoteTool.ts@@ -1,11 +1,11 @@import type { ToolDefinition, ToolResult } from "./ToolRegistry";-import { resolveFolderId } from "./utils";+import { resolveFolderId, resolveSpace } from "./utils";import { syncService } from "../SyncService.js";export const createNoteTool: ToolDefinition = {name: "create_note",description:- "Always call list_folders first. Reuse an existing folder whenever one is a reasonable semantic fit for the note's topic (e.g. a story goes into an existing 'Stories' folder), even if the user didn't name it. Only pass a new folder name when nothing existing fits. Creates a note with title, content, and optional folder (auto-created if missing).",+ "Always call list_folders first. Reuse an existing folder whenever one is a reasonable semantic fit for the note's topic (e.g. a story goes into an existing 'Stories' folder), even if the user didn't name it. Only pass a new folder name when nothing existing fits. Creates a note with title, content, optional folder (auto-created if missing), and optional space.",parameters: {type: "object",properties: {@@ -21,6 +21,10 @@ export const createNoteTool: ToolDefinition = {type: "string",description: "Folder name for the note. Created automatically if it does not exist.",},+ space: {+ type: "string",+ description: "Space name to create the note in. Omit for the user's personal space.",+ },},required: ["title", "content"],additionalProperties: false,@@ -31,13 +35,24 @@ export const createNoteTool: ToolDefinition = {const title = args.title as string;const content = args.content as string;const folderName = args.folder as string | undefined;+ const spaceName = args.space as string | undefined;try {+ let spaceId: number | null = null;+ if (spaceName) {+ const spaces = (await window.electronAPI.getSpaces?.()) ?? [];+ const resolved = resolveSpace(spaces, spaceName);+ if (resolved.error) {+ return { success: false, data: null, displayText: resolved.error };+ }+ spaceId = resolved.space.id;+ }+let folderId: number | null = null;let folderCreated = false;if (folderName) {- const resolved = await resolveFolderId(folderName, { createIfMissing: true });+ const resolved = await resolveFolderId(folderName, { createIfMissing: true }, spaceId);if (resolved.error) {return { success: false, data: null, displayText: resolved.error };}@@ -51,7 +66,8 @@ export const createNoteTool: ToolDefinition = {"personal",null,null,- folderId+ folderId,+ spaceId);if (!result.success || !result.note) {diff --git a/src/services/tools/listFoldersTool.ts b/src/services/tools/listFoldersTool.tsindex d28b26463..662073614 100644--- a/src/services/tools/listFoldersTool.ts+++ b/src/services/tools/listFoldersTool.ts@@ -3,7 +3,7 @@ import type { ToolDefinition, ToolResult } from "./ToolRegistry";export const listFoldersTool: ToolDefinition = {name: "list_folders",description:- "List all available note folders. Use before create_note or update_note to reuse an existing folder instead of creating a near-duplicate.",+ "List all available note folders with the space each belongs to. Use before create_note or update_note to reuse an existing folder instead of creating a near-duplicate.",parameters: {type: "object",properties: {},@@ -13,10 +13,20 @@ export const listFoldersTool: ToolDefinition = {async execute(): Promise<ToolResult> {try {- const folders = await window.electronAPI.getFolders();- const data = folders.map((f) => ({ id: f.id, name: f.name }));- const displayText = folders.length- ? `Folders: ${folders.map((f) => f.name).join(", ")}`+ const [folders, spaces] = await Promise.all([+ window.electronAPI.getFolders(),+ window.electronAPI.getSpaces?.() ?? Promise.resolve([]),+ ]);+ const spaceNameById = new Map(spaces.map((s) => [s.id, s.name]));+ const data = folders.map((f) => ({+ id: f.id,+ name: f.name,+ space: spaceNameById.get(f.space_id) ?? null,+ }));+ const displayText = data.length+ ? `Folders: ${data+ .map((f) => (spaces.length > 1 && f.space ? `${f.name} (${f.space})` : f.name))+ .join(", ")}`: "No folders";return { success: true, data, displayText };} catch (error) {diff --git a/src/services/tools/searchNotesTool.ts b/src/services/tools/searchNotesTool.tsindex d01b9adf3..64eaf5fe5 100644--- a/src/services/tools/searchNotesTool.ts+++ b/src/services/tools/searchNotesTool.ts@@ -1,4 +1,6 @@+import type { SpaceItem } from "../../types/electron";import type { ToolDefinition, ToolResult } from "./ToolRegistry";+import { resolveSpace } from "./utils";const MAX_CONTENT_LENGTH = 500;@@ -12,7 +14,7 @@ export function createSearchNotesTool(options: SearchToolOptions): ToolDefinitioreturn {name: "search_notes",description:- "Search the user's notes using semantic search. Understands meaning and context, not just keywords. Returns matching notes with title, date, relevance score, and a preview of content.",+ "Search the user's notes using semantic search. Understands meaning and context, not just keywords. Searches every space the user can access by default; pass space to search within a single space. Returns matching notes with title, date, relevance score, space, and a preview of content.",parameters: {type: "object",properties: {@@ -24,6 +26,10 @@ export function createSearchNotesTool(options: SearchToolOptions): ToolDefinitiotype: "number",description: "Maximum number of results to return (default 5)",},+ space: {+ type: "string",+ description: "Space name to search within. Omit to search all accessible spaces.",+ },},required: ["query"],additionalProperties: false,@@ -33,12 +39,28 @@ export function createSearchNotesTool(options: SearchToolOptions): ToolDefinitioasync execute(args: Record<string, unknown>): Promise<ToolResult> {const query = args.query as string;const limit = typeof args.limit === "number" ? args.limit : 5;+ const spaceName = args.space as string | undefined;++ const spaces = (await window.electronAPI.getSpaces?.()) ?? [];+ let space: SpaceItem | undefined;+ if (spaceName) {+ const resolved = resolveSpace(spaces, spaceName);+ if (resolved.error) {+ return { success: false, data: null, displayText: resolved.error };+ }+ space = resolved.space;+ }- // Fallback chain: cloud → local semantic (hybrid RRF) → FTS5 keyword+ // Fallback chain: cloud → local semantic (hybrid RRF) → FTS5 keyword.+ // A team space without a cloud team can't be scoped server-side, so its+ // searches go straight to the local legs.const strategies: Array<() => Promise<ToolResult>> = [];- if (useCloudSearch) strategies.push(() => executeCloudSearch(query, limit));- strategies.push(() => executeLocalSearch(query, limit, true));- strategies.push(() => executeLocalSearch(query, limit, false));+ const cloudCanScope = !space || space.kind === "private" || !!space.cloud_team_id;+ if (useCloudSearch && cloudCanScope) {+ strategies.push(() => executeCloudSearch(query, limit, space, spaces));+ }+ strategies.push(() => executeLocalSearch(query, limit, true, space, spaces));+ strategies.push(() => executeLocalSearch(query, limit, false, space, spaces));for (let i = 0; i < strategies.length; i++) {try {@@ -59,62 +81,76 @@ export function createSearchNotesTool(options: SearchToolOptions): ToolDefinitio};}+function summaryText(+ count: number,+ query: string,+ space: SpaceItem | undefined,+ semantic: boolean+): string {+ const scope = space ? ` in ${space.name}` : "";+ if (count === 0) return `No notes found for "${query}"${scope}`;+ return `Found ${count} note${count === 1 ? "" : "s"} for "${query}"${scope}${semantic ? " (semantic search)" : ""}`;+}+async function executeLocalSearch(query: string,limit: number,- semantic: boolean+ semantic: boolean,+ space: SpaceItem | undefined,+ spaces: SpaceItem[]): Promise<ToolResult> {+ const spaceId = space?.id ?? null;const notes = semantic- ? await window.electronAPI.semanticSearchNotes(query, limit)- : await window.electronAPI.searchNotes(query, limit);-- if (notes.length === 0) {- return {- success: true,- data: [],- displayText: `No notes found for "${query}"`,- };- }+ ? await window.electronAPI.semanticSearchNotes(query, limit, spaceId)+ : await window.electronAPI.searchNotes(query, limit, spaceId);+ const spaceNameById = new Map(spaces.map((s) => [s.id, s.name]));const results = notes.map((note) => ({id: note.id,title: note.title,date: note.created_at,type: note.note_type,+ space: spaceNameById.get(note.space_id) ?? null,content: (note.enhanced_content || note.content).slice(0, MAX_CONTENT_LENGTH),}));return {success: true,data: results,- displayText: `Found ${results.length} note${results.length === 1 ? "" : "s"} for "${query}"${semantic ? " (semantic search)" : ""}`,+ displayText: summaryText(results.length, query, space, semantic),};}-async function executeCloudSearch(query: string, limit: number): Promise<ToolResult> {+async function executeCloudSearch(+ query: string,+ limit: number,+ space: SpaceItem | undefined,+ spaces: SpaceItem[]+): Promise<ToolResult> {const { NotesService } = await import("../../services/NotesService.js");- const { notes: cloudNotes } = await NotesService.search(query, limit);-- if (cloudNotes.length === 0) {- return {- success: true,- data: [],- displayText: `No notes found for "${query}"`,- };- }-+ // No space → all accessible spaces; team space → that team only (membership+ // is server-enforced); private space → the personal-only default.+ const teamId = space?.kind === "team" ? (space.cloud_team_id ?? undefined) : undefined;+ const scope = space ? undefined : ("all" as const);+ const { notes: cloudNotes } = await NotesService.search(query, limit, scope, teamId);++ const spaceNameByTeamId = new Map(+ spaces.filter((s) => s.cloud_team_id).map((s) => [s.cloud_team_id!, s.name])+ );+ const privateSpaceName = spaces.find((s) => s.kind === "private")?.name ?? null;const results = cloudNotes.map((cn) => ({id: cn.client_note_id ? parseInt(cn.client_note_id, 10) : null,title: cn.title,date: cn.created_at,type: cn.note_type,score: cn.score,+ space: cn.team_id ? (spaceNameByTeamId.get(cn.team_id) ?? null) : privateSpaceName,content: (cn.enhanced_content || cn.content).slice(0, MAX_CONTENT_LENGTH),}));return {success: true,data: results,- displayText: `Found ${results.length} note${results.length === 1 ? "" : "s"} for "${query}" (semantic search)`,+ displayText: summaryText(results.length, query, space, true),};}diff --git a/src/services/tools/updateNoteTool.ts b/src/services/tools/updateNoteTool.tsindex 0ceb78835..4ec3948c7 100644--- a/src/services/tools/updateNoteTool.ts+++ b/src/services/tools/updateNoteTool.ts@@ -57,7 +57,13 @@ export const updateNoteTool: ToolDefinition = {let folderCreated = false;if (folderName) {- const resolved = await resolveFolderId(folderName, { createIfMissing: true });+ // Folder resolution stays within the note's space so a move by name+ // never drags the note into another space.+ const resolved = await resolveFolderId(+ folderName,+ { createIfMissing: true },+ note.space_id+ );if (resolved.error) {return { success: false, data: null, displayText: resolved.error };}diff --git a/src/services/tools/utils.ts b/src/services/tools/utils.tsindex 85eb57360..4a7d37b19 100644--- a/src/services/tools/utils.ts+++ b/src/services/tools/utils.ts@@ -1,12 +1,15 @@+import type { SpaceItem } from "../../types/electron";+type ResolveFolderResult =| { folderId: number; created: boolean; error?: undefined }| { folderId?: undefined; created?: undefined; error: string };export async function resolveFolderId(folderName: string,- options: { createIfMissing?: boolean } = {}+ options: { createIfMissing?: boolean } = {},+ spaceId: number | null = null): Promise<ResolveFolderResult> {- const folders = await window.electronAPI.getFolders();+ const folders = await window.electronAPI.getFolders(spaceId);const match = folders.find((f) => f.name.toLowerCase() === folderName.toLowerCase());if (match) return { folderId: match.id, created: false };@@ -15,14 +18,24 @@ export async function resolveFolderId(return { error: `Folder "${folderName}" not found. Available folders: ${available}` };}- const result = await window.electronAPI.createFolder(folderName);+ const result = await window.electronAPI.createFolder(folderName, spaceId);if (result.success && result.folder) {return { folderId: result.folder.id, created: true };}- const retry = await window.electronAPI.getFolders();+ const retry = await window.electronAPI.getFolders(spaceId);const reMatch = retry.find((f) => f.name.toLowerCase() === folderName.toLowerCase());if (reMatch) return { folderId: reMatch.id, created: false };return { error: result.error || `Failed to create folder "${folderName}"` };}++type ResolveSpaceResult =+ { space: SpaceItem; error?: undefined } | { space?: undefined; error: string };++export function resolveSpace(spaces: SpaceItem[], spaceName: string): ResolveSpaceResult {+ const match = spaces.find((s) => s.name.toLowerCase() === spaceName.trim().toLowerCase());+ if (match) return { space: match };+ const available = spaces.map((s) => s.name).join(", ");+ return { error: `Space "${spaceName}" not found. Available spaces: ${available}` };+}