Skip to content

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

feat: chat for spaces

Chadpihaaeeabc4b9903
diff --git a/preload.js b/preload.js
index b88316818..317ab4d83 100644
--- a/preload.js
+++ b/preload.js
@@ -113,15 +113,16 @@ contextBridge.exposeInMainWorld("electronAPI", {
getNote: (id) => ipcRenderer.invoke("db-get-note", id),
getNotes: (noteType, limit, folderId, spaceId) =>
ipcRenderer.invoke("db-get-notes", noteType, limit, folderId, spaceId),
+ getSpaceNotes: (spaceId, limit) => ipcRenderer.invoke("db-get-space-notes", spaceId, limit),
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, spaceId) =>
- ipcRenderer.invoke("db-search-notes", query, limit, spaceId),
- semanticSearchNotes: (query, limit, spaceId) =>
- ipcRenderer.invoke("db-semantic-search-notes", query, limit, spaceId),
+ searchNotes: (query, limit, spaceId, folderId) =>
+ ipcRenderer.invoke("db-search-notes", query, limit, spaceId, folderId),
+ semanticSearchNotes: (query, limit, spaceId, folderId) =>
+ ipcRenderer.invoke("db-semantic-search-notes", query, limit, spaceId, folderId),
semanticReindexAll: () => ipcRenderer.invoke("db-semantic-reindex-all"),
onSemanticReindexProgress: (callback) => {
const listener = (_event, data) => callback?.(data);
@@ -143,7 +144,6 @@ contextBridge.exposeInMainWorld("electronAPI", {
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),
@@ -879,8 +879,8 @@ contextBridge.exposeInMainWorld("electronAPI", {
agentOpenNote: (noteId) => ipcRenderer.invoke("agent-open-note", noteId),
// Agent conversation persistence
- createAgentConversation: (title, noteId) =>
- ipcRenderer.invoke("db-create-agent-conversation", title, noteId),
+ createAgentConversation: (title, noteId, spaceId, folderId) =>
+ ipcRenderer.invoke("db-create-agent-conversation", title, noteId, spaceId, folderId),
getAgentConversations: (limit) => ipcRenderer.invoke("db-get-agent-conversations", limit),
getAgentConversation: (id) => ipcRenderer.invoke("db-get-agent-conversation", id),
deleteAgentConversation: (id) => ipcRenderer.invoke("db-delete-agent-conversation", id),
@@ -895,6 +895,8 @@ contextBridge.exposeInMainWorld("electronAPI", {
ipcRenderer.invoke("db-search-agent-conversations", query, limit),
getConversationsForNote: (noteId, limit) =>
ipcRenderer.invoke("db-get-conversations-for-note", noteId, limit),
+ getConversationsForContainer: (spaceId, folderId, limit) =>
+ ipcRenderer.invoke("db-get-conversations-for-container", spaceId, folderId, limit),
archiveAgentConversation: (id) => ipcRenderer.invoke("db-archive-agent-conversation", id),
unarchiveAgentConversation: (id) => ipcRenderer.invoke("db-unarchive-agent-conversation", id),
updateAgentConversationCloudId: (id, cloudId) =>
diff --git a/src/components/ControlPanel.tsx b/src/components/ControlPanel.tsx
index fb5a3c315..04ff3d796 100644
--- a/src/components/ControlPanel.tsx
+++ b/src/components/ControlPanel.tsx
@@ -67,6 +67,10 @@ const platform = getCachedPlatform();
const SIDEBAR_WIDTH_PX = 192;
+// Bump to force a one-time full semantic reindex on next launch (see the
+// reindex effect for the per-version history).
+const SEMANTIC_REINDEX_VERSION = 2;
+
const toggleIconClass =
"text-foreground/60 group-hover:text-foreground/75 dark:text-foreground/50 dark:group-hover:text-foreground/65 transition-colors duration-150";
@@ -202,17 +206,20 @@ 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.
+ // One-time background reindex, versioned: v1 backfilled space_id payloads
+ // after the spaces migration; v2 backfills cloud-pulled notes, which were
+ // never incrementally indexed before the upsert-from-cloud handler gained a
+ // vector upsert. 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;
+ if (Number(localStorage.getItem("semanticReindexVersion")) >= SEMANTIC_REINDEX_VERSION) return;
const timer = setTimeout(() => {
window.electronAPI
?.semanticReindexAll?.()
.then((result) => {
- if (result?.success) localStorage.setItem("semanticSpaceReindexDone", "true");
+ if (result?.success) {
+ localStorage.setItem("semanticReindexVersion", String(SEMANTIC_REINDEX_VERSION));
+ }
})
.catch(() => {});
}, 15_000);
diff --git a/src/components/chat/ChatInput.tsx b/src/components/chat/ChatInput.tsx
index 4a35cb95e..2705e43f5 100644
--- a/src/components/chat/ChatInput.tsx
+++ b/src/components/chat/ChatInput.tsx
@@ -10,6 +10,7 @@ interface ChatInputProps {
onTextSubmit?: (text: string) => void;
onCancel?: () => void;
autoFocus?: boolean;
+ placeholder?: string;
}
function RecordingIndicator() {
@@ -46,6 +47,7 @@ export function ChatInput({
onTextSubmit,
onCancel,
autoFocus = false,
+ placeholder,
}: ChatInputProps) {
const { t } = useTranslation();
const [inputText, setInputText] = useState("");
@@ -119,7 +121,7 @@ export function ChatInput({
onKeyDown={handleKeyDown}
disabled={isBusy}
autoFocus={autoFocus}
- placeholder={t("agentMode.input.typeMessage")}
+ placeholder={placeholder ?? t("agentMode.input.typeMessage")}
className={cn(
"input-inline flex-1 outline-none bg-transparent",
"text-[13px] text-foreground placeholder:text-muted-foreground/40",
diff --git a/src/components/chat/ConversationItem.tsx b/src/components/chat/ConversationItem.tsx
index 591519c3a..5d03873bd 100644
--- a/src/components/chat/ConversationItem.tsx
+++ b/src/components/chat/ConversationItem.tsx
@@ -9,7 +9,7 @@ import {
DropdownMenuSeparator,
} from "../ui/dropdown-menu";
import { cn } from "../lib/utils";
-import { normalizeDbDate } from "../../utils/dateFormatting";
+import { formatShortDate, normalizeDbDate } from "../../utils/dateFormatting";
export interface ConversationPreview {
id: number;
@@ -42,7 +42,7 @@ function formatTimestamp(dateStr: string): string {
if (minutes < 60) return `${minutes}m`;
if (hours < 24) return `${hours}h`;
if (days < 7) return `${days}d`;
- return date.toLocaleDateString(undefined, { month: "short", day: "numeric" });
+ return formatShortDate(dateStr);
}
export default function ConversationItem({
diff --git a/src/components/chat/ConversationList.tsx b/src/components/chat/ConversationList.tsx
index cf38b0d6b..952cc1183 100644
--- a/src/components/chat/ConversationList.tsx
+++ b/src/components/chat/ConversationList.tsx
@@ -3,7 +3,7 @@ import { SquarePen, Search, Archive as ArchiveIcon } from "lucide-react";
import { useTranslation } from "react-i18next";
import { useVirtualizer } from "@tanstack/react-virtual";
import { cn } from "../lib/utils";
-import { normalizeDbDate } from "../../utils/dateFormatting";
+import { groupItemsByDate } from "../../utils/dateGrouping";
import ConversationItem, { type ConversationPreview } from "./ConversationItem";
import ConversationDateGroup from "./ConversationDateGroup";
import EmptyConversationList from "./EmptyConversationList";
@@ -22,41 +22,10 @@ interface ConversationListProps {
}
function groupByDate(conversations: ConversationPreview[], t: (key: string) => string): FlatItem[] {
- if (conversations.length === 0) return [];
-
- const now = new Date();
- const today = new Date(now.getFullYear(), now.getMonth(), now.getDate());
- const yesterday = new Date(today);
- yesterday.setDate(yesterday.getDate() - 1);
- const weekAgo = new Date(today);
- weekAgo.setDate(weekAgo.getDate() - 7);
-
- const items: FlatItem[] = [];
- let currentGroup: string | null = null;
-
- for (const conv of conversations) {
- const date = normalizeDbDate(conv.updated_at);
- const target = new Date(date.getFullYear(), date.getMonth(), date.getDate());
-
- let group: string;
- if (target.getTime() >= today.getTime()) {
- group = t("chat.today");
- } else if (target.getTime() >= yesterday.getTime()) {
- group = t("chat.yesterday");
- } else if (target.getTime() >= weekAgo.getTime()) {
- group = t("chat.previousWeek");
- } else {
- group = t("chat.older");
- }
-
- if (group !== currentGroup) {
- items.push({ type: "header", label: group });
- currentGroup = group;
- }
- items.push({ type: "conversation", data: conv });
- }
-
- return items;
+ return groupItemsByDate(conversations, (c) => c.updated_at, t).flatMap((group) => [
+ { type: "header" as const, label: group.label },
+ ...group.items.map((data) => ({ type: "conversation" as const, data })),
+ ]);
}
function SkeletonRows() {
diff --git a/src/components/chat/useChatPersistence.ts b/src/components/chat/useChatPersistence.ts
index 640b72f05..6f2e7d4d1 100644
--- a/src/components/chat/useChatPersistence.ts
+++ b/src/components/chat/useChatPersistence.ts
@@ -6,11 +6,20 @@ interface UseChatPersistenceOptions {
onConversationCreated?: (id: number, title: string) => void;
}
+export interface ConversationScope {
+ spaceId: number;
+ folderId: number | null;
+}
+
export interface ChatPersistence {
messages: Message[];
setMessages: React.Dispatch<React.SetStateAction<Message[]>>;
conversationId: number | null;
- createConversation: (title: string, noteId?: number | null) => Promise<number>;
+ createConversation: (
+ title: string,
+ noteId?: number | null,
+ scope?: ConversationScope
+ ) => Promise<number>;
loadConversation: (id: number) => Promise<void>;
saveUserMessage: (text: string) => Promise<void>;
saveAssistantMessage: (content: string, toolCalls?: ToolCallInfo[]) => Promise<void>;
@@ -29,8 +38,13 @@ export function useChatPersistence(options: UseChatPersistenceOptions = {}): Cha
}, [conversationId]);
const createConversation = useCallback(
- async (title: string, noteId?: number | null): Promise<number> => {
- const conv = await window.electronAPI?.createAgentConversation?.(title, noteId ?? undefined);
+ async (title: string, noteId?: number | null, scope?: ConversationScope): Promise<number> => {
+ const conv = await window.electronAPI?.createAgentConversation?.(
+ title,
+ noteId ?? undefined,
+ scope?.spaceId,
+ scope?.folderId ?? undefined
+ );
const id = conv?.id ?? 0;
conversationIdRef.current = id;
setConversationId(id);
diff --git a/src/components/chat/useChatStreaming.ts b/src/components/chat/useChatStreaming.ts
index f3943c3e6..b01820df3 100644
--- a/src/components/chat/useChatStreaming.ts
+++ b/src/components/chat/useChatStreaming.ts
@@ -18,10 +18,20 @@ function estimateModelSizeB(modelId: string): number {
return match ? parseFloat(match[1]) : 0;
}
-async function buildRAGContext(userText: string): Promise<string> {
+export interface ChatSearchScope {
+ spaceId: number;
+ folderId: number | null;
+}
+
+async function buildRAGContext(userText: string, scope?: ChatSearchScope): Promise<string> {
if (!window.electronAPI?.semanticSearchNotes) return "";
try {
- const results = await window.electronAPI.semanticSearchNotes(userText, RAG_NOTE_LIMIT);
+ const results = await window.electronAPI.semanticSearchNotes(
+ userText,
+ RAG_NOTE_LIMIT,
+ scope?.spaceId ?? null,
+ scope?.folderId ?? null
+ );
if (!results || results.length === 0) return "";
const snippets = await Promise.all(
@@ -44,6 +54,8 @@ interface UseChatStreamingOptions {
setMessages: React.Dispatch<React.SetStateAction<Message[]>>;
/** Optional note context to prepend to the system prompt (used by embedded note chat). */
noteContext?: string;
+ /** Optional container scope applied to RAG and the search_notes tool (container overview chat). */
+ searchScope?: ChatSearchScope;
onStreamComplete?: (assistantId: string, content: string, toolCalls?: ToolCallInfo[]) => void;
}
@@ -59,6 +71,7 @@ export function useChatStreaming({
messages,
setMessages,
noteContext: externalNoteContext,
+ searchScope,
onStreamComplete,
}: UseChatStreamingOptions): ChatStreaming {
const { t } = useTranslation();
@@ -69,6 +82,8 @@ export function useChatStreaming({
const messagesRef = useRef<Message[]>([]);
const noteContextRef = useRef(externalNoteContext);
noteContextRef.current = externalNoteContext;
+ const searchScopeRef = useRef(searchScope);
+ searchScopeRef.current = searchScope;
const toolRegistryRef = useRef<{ key: string; registry: ToolRegistry } | null>(null);
useEffect(() => {
@@ -116,9 +131,11 @@ export function useChatStreaming({
isLocalProvider && estimateModelSizeB(settings.chatAgentModel) >= LOCAL_TOOL_MIN_PARAMS_B;
const supportsTools = isCloudAgent || !isLocalProvider || localModelCanUseTool;
+ const scope = searchScopeRef.current;
let registry: ToolRegistry | null = null;
if (supportsTools) {
- const cacheKey = `${settings.isSignedIn}-${settings.gcalConnected}-${settings.cloudBackupEnabled}`;
+ const scopeKey = scope ? `${scope.spaceId}:${scope.folderId ?? ""}` : "";
+ const cacheKey = `${settings.isSignedIn}-${settings.gcalConnected}-${settings.cloudBackupEnabled}-${scopeKey}`;
if (toolRegistryRef.current?.key === cacheKey) {
registry = toolRegistryRef.current.registry;
} else {
@@ -126,12 +143,13 @@ export function useChatStreaming({
isSignedIn: settings.isSignedIn,
gcalConnected: settings.gcalConnected,
cloudBackupEnabled: settings.cloudBackupEnabled,
+ searchScope: scope,
});
toolRegistryRef.current = { key: cacheKey, registry };
}
}
- const ragContext = await buildRAGContext(userText);
+ const ragContext = await buildRAGContext(userText, scope);
const combinedContext = [noteContextRef.current, ragContext].filter(Boolean).join("\n\n");
const systemPrompt = getAgentSystemPrompt(
registry?.getAll().map((t) => t.name),
diff --git a/src/components/notes/EmbeddedChat.tsx b/src/components/notes/EmbeddedChat.tsx
index 04c0b3733..84b9ec22c 100644
--- a/src/components/notes/EmbeddedChat.tsx
+++ b/src/components/notes/EmbeddedChat.tsx
@@ -6,7 +6,7 @@ import { ChatMessages } from "../chat/ChatMessages";
import { ChatInput } from "../chat/ChatInput";
import type { Message, AgentState } from "../chat/types";
import { setActiveNoteId, setActiveFolderId } from "../../stores/noteStore";
-import { normalizeDbDate } from "../../utils/dateFormatting";
+import { formatShortDate } from "../../utils/dateFormatting";
import {
DropdownMenu,
DropdownMenuTrigger,
@@ -47,12 +47,6 @@ function EmptyState() {
);
}
-function formatConversationDate(dateStr: string): string {
- const date = normalizeDbDate(dateStr);
- if (Number.isNaN(date.getTime())) return "";
- return date.toLocaleDateString(undefined, { month: "short", day: "numeric" });
-}
-
export default function EmbeddedChat({
mode,
onModeChange,
@@ -131,7 +125,7 @@ export default function EmbeddedChat({
>
<span className="truncate flex-1">{conv.title}</span>
<span className="text-[10px] text-foreground/30 shrink-0">
- {formatConversationDate(conv.updated_at)}
+ {formatShortDate(conv.updated_at)}
</span>
</DropdownMenuItem>
))}
diff --git a/src/components/notes/NoteEditor.tsx b/src/components/notes/NoteEditor.tsx
index c9b0ea072..38ad38726 100644
--- a/src/components/notes/NoteEditor.tsx
+++ b/src/components/notes/NoteEditor.tsx
@@ -34,7 +34,7 @@ import {
navigateToContainer,
updateNoteInStore,
} from "../../stores/noteStore";
-import { TeamsService } from "../../services/TeamsService";
+import { fetchTeamRoster } from "../../hooks/useTeamRoster";
import { readIsSubscribed, subscribeIsSubscribed } from "../../lib/subscriptionFlag";
import { useAuth } from "../../hooks/useAuth";
import { RichTextEditor } from "../ui/RichTextEditor";
@@ -52,7 +52,7 @@ import {
DropdownMenuSeparator,
} from "../ui/dropdown-menu";
import { cn } from "../lib/utils";
-import type { NoteItem, FolderItem, TeamMember } from "../../types/electron";
+import type { NoteItem, FolderItem } from "../../types/electron";
import type { ActionProcessingState } from "../../hooks/useActionProcessing";
import ActionProcessingOverlay from "./ActionProcessingOverlay";
import NoteBottomBar from "./NoteBottomBar";
@@ -72,19 +72,6 @@ import type { CalendarAttendee } from "../../types/calendar";
const CHIP_BUTTON_CLASS =
"inline-flex items-center gap-1.5 text-[11px] px-1.5 py-0.5 rounded-md border border-border/70 dark:border-white/25 text-foreground/50 dark:text-foreground/35 hover:text-foreground/60 hover:border-border/60 hover:bg-foreground/3 dark:hover:text-foreground/40 dark:hover:border-white/10 dark:hover:bg-white/3 transition-all duration-150 cursor-pointer outline-none focus-visible:ring-1 focus-visible:ring-ring/30";
-// Conflict attribution rosters, cached per team so repeated conflicts don't refetch.
-const conflictRosterCache = new Map<string, Promise<TeamMember[]>>();
-
-function fetchTeamRoster(teamId: string): Promise<TeamMember[]> {
- let roster = conflictRosterCache.get(teamId);
- if (!roster) {
- roster = TeamsService.listMembers(teamId);
- roster.catch(() => conflictRosterCache.delete(teamId));
- conflictRosterCache.set(teamId, roster);
- }
- return roster;
-}
-
function formatNoteDate(dateStr: string): string {
const date = normalizeDbDate(dateStr);
if (Number.isNaN(date.getTime())) return "";
diff --git a/src/components/notes/PersonalNotesView.tsx b/src/components/notes/PersonalNotesView.tsx
index 5f44eb3ba..193998f71 100644
--- a/src/components/notes/PersonalNotesView.tsx
+++ b/src/components/notes/PersonalNotesView.tsx
@@ -17,6 +17,7 @@ import { Input } from "../ui/input";
import { useToast } from "../ui/useToast";
import NoteEditor from "./NoteEditor";
import SpacesTree from "./SpacesTree";
+import { ContainerOverview } from "./overview/ContainerOverview";
import NotesStructureIntroDialog from "./NotesStructureIntroDialog";
import ActionPicker from "./ActionPicker";
import ActionManagerDialog from "./ActionManagerDialog";
@@ -154,6 +155,17 @@ export default function PersonalNotesView({
const spaces = useSpaces();
const folders = useFolders();
const activeContext = useActiveContext();
+ const overviewSpace = useMemo(
+ () => (activeContext ? (spaces.find((s) => s.id === activeContext.spaceId) ?? null) : null),
+ [activeContext, spaces]
+ );
+ const overviewFolder = useMemo(
+ () =>
+ activeContext?.folderId != null
+ ? (folders.find((f) => f.id === activeContext.folderId) ?? null)
+ : null,
+ [activeContext, folders]
+ );
useEffect(() => {
initializeNotesTree();
@@ -814,6 +826,15 @@ export default function PersonalNotesView({
/>
<ActionManagerDialog open={showActionManager} onOpenChange={setShowActionManager} />
</>
+ ) : activeContext && overviewSpace ? (
+ <ContainerOverview
+ key={activeContext.folderId != null ? `f:${activeContext.folderId}` : `s:${activeContext.spaceId}`}
+ space={overviewSpace}
+ folder={overviewFolder}
+ onOpenNote={setActiveNoteId}
+ onNewNote={handleNewNote}
+ onAddExisting={activeFolderId != null ? () => setShowAddNotesDialog(true) : undefined}
+ />
) : (
<div className="flex-1 flex flex-col items-center justify-center -mt-6">
<svg
diff --git a/src/components/notes/SpacesTree.tsx b/src/components/notes/SpacesTree.tsx
index b7b14f8c7..1995be91a 100644
--- a/src/components/notes/SpacesTree.tsx
+++ b/src/components/notes/SpacesTree.tsx
@@ -103,8 +103,20 @@ type TFn = (key: string, options?: Record<string, unknown>) => string;
type TreeRow =
| { type: "space"; key: string; space: SpaceItem; parentKey?: undefined }
- | { type: "folder"; key: string; folder: FolderItem; parentKey: string }
- | { type: "note"; key: string; note: NoteItem; parentKey: string; level: 2 | 3 };
+ | {
+ type: "folder";
+ key: string;
+ folder: FolderItem;
+ parentKey?: string;
+ level: 1 | 2;
+ }
+ | {
+ type: "note";
+ key: string;
+ note: NoteItem;
+ parentKey?: string;
+ level: 1 | 2 | 3;
+ };
interface DropHandlers {
onDragOver: (e: React.DragEvent) => void;
@@ -145,22 +157,72 @@ function SectionHeader({
label,
action,
className,
+ expanded,
+ onToggle,
+ toggleRef,
+ dropHandlers,
+ isDragOver,
+ isDropSuccess,
}: {
label: string;
action?: React.ReactNode;
className?: string;
+ expanded?: boolean;
+ onToggle?: () => void;
+ toggleRef?: React.Ref<HTMLButtonElement>;
+ dropHandlers?: DropHandlers;
+ isDragOver?: boolean;
+ isDropSuccess?: boolean;
}) {
+ const labelClassName =
+ "text-[10px] font-semibold uppercase tracking-wide text-foreground/50 select-none";
+
return (
- <div role="none" className={cn("flex items-center justify-between h-6 px-2 mt-1", className)}>
- <span className="text-[10px] font-semibold uppercase tracking-wide text-foreground/50 select-none">
- {label}
- </span>
+ <div
+ role="none"
+ {...dropHandlers}
+ className={cn(
+ "flex items-center justify-between h-6 px-2 mt-1 rounded-md",
+ isDragOver && "bg-primary/12 dark:bg-primary/15 ring-1 ring-primary/25",
+ isDropSuccess && "bg-emerald-500/10 dark:bg-emerald-400/10 ring-1 ring-emerald-500/20",
+ className
+ )}
+ >
+ {onToggle ? (
+ <button
+ ref={toggleRef}
+ type="button"
+ aria-expanded={expanded}
+ onClick={onToggle}
+ className="flex h-full min-w-0 items-center gap-1 rounded-sm outline-none hover:text-foreground focus-visible:ring-1 focus-visible:ring-ring/30"
+ >
+ <ChevronRight
+ size={11}
+ aria-hidden="true"
+ className={cn(
+ "shrink-0 text-foreground/40 transition-transform duration-150",
+ expanded && "rotate-90"
+ )}
+ />
+ <span className={labelClassName}>{label}</span>
+ </button>
+ ) : (
+ <span className={labelClassName}>{label}</span>
+ )}
{action}
</div>
);
}
-function TreeChildren({ open, children }: { open: boolean; children: React.ReactNode }) {
+function TreeChildren({
+ open,
+ children,
+ grouped = true,
+}: {
+ open: boolean;
+ children: React.ReactNode;
+ grouped?: boolean;
+}) {
return (
<div
role="none"
@@ -170,7 +232,7 @@ function TreeChildren({ open, children }: { open: boolean; children: React.React
)}
>
<div
- role="group"
+ role={grouped ? "group" : "none"}
className={cn(
"min-h-0 overflow-hidden transition-opacity duration-[80ms]",
open ? "opacity-100" : "opacity-0"
@@ -437,6 +499,7 @@ function SpaceRow({
function FolderRow({
folder,
+ level,
spaces,
isExpanded,
isActive,
@@ -455,6 +518,7 @@ function FolderRow({
t,
}: {
folder: FolderItem;
+ level: 1 | 2;
spaces: SpaceItem[];
isExpanded: boolean;
isActive: boolean;
@@ -487,7 +551,7 @@ function FolderRow({
return (
<div
role="treeitem"
- aria-level={2}
+ aria-level={level}
aria-expanded={isExpanded}
aria-selected={isActive}
aria-label={
@@ -502,7 +566,8 @@ function FolderRow({
{...dropHandlers}
className={cn(
ROW_BASE_CLASS,
- "h-7 pl-[14px] pr-2",
+ "h-7 pr-2",
+ level === 1 ? "pl-2" : "pl-[14px]",
isActive
? "bg-primary/8 dark:bg-primary/10"
: "hover:bg-foreground/4 dark:hover:bg-white/4",
@@ -679,6 +744,7 @@ interface MoveOption {
function NoteLeaf({
note,
level,
+ indentClassName,
isActive,
isDragging,
dragHandlers,
@@ -694,7 +760,8 @@ function NoteLeaf({
t,
}: {
note: NoteItem;
- level: 2 | 3;
+ level: 1 | 2 | 3;
+ indentClassName?: string;
isActive: boolean;
isDragging: boolean;
dragHandlers: {
@@ -786,7 +853,7 @@ function NoteLeaf({
className={cn(
ROW_BASE_CLASS,
"h-7 pr-2",
- level === 3 ? "pl-7" : "pl-[14px]",
+ indentClassName ?? (level === 3 ? "pl-10" : "pl-[14px]"),
isActive
? "bg-primary/8 dark:bg-primary/10"
: "hover:bg-foreground/4 dark:hover:bg-white/4",
@@ -1060,11 +1127,16 @@ export default function SpacesTree({
const [deleteSpaceTarget, setDeleteSpaceTarget] = useState<SpaceItem | null>(null);
const [focusedKey, setFocusedKey] = useState<string | null>(null);
const rowRefs = useRef(new Map<string, HTMLDivElement>());
+ const privateSectionToggleRef = useRef<HTMLButtonElement>(null);
const undoToastIdRef = useRef<string | null>(null);
const { confirmDialog, showConfirmDialog, hideConfirmDialog } = useDialogs();
const privateSpaces = useMemo(() => spaces.filter((s) => s.kind === "private"), [spaces]);
+ const privateSpace = privateSpaces[0];
+ const privateSectionExpanded = privateSpace
+ ? expanded.has(spaceContainerKey(privateSpace.id))
+ : false;
const teamSpaces = useMemo(() => spaces.filter((s) => s.kind === "team"), [spaces]);
const showWorkspaceGroups = workspaces.length > 1;
const teamSpaceGroups = useMemo(
@@ -1310,6 +1382,30 @@ export default function SpacesTree({
const visibleRows = useMemo<TreeRow[]>(() => {
const rows: TreeRow[] = [];
+ const pushPrivateSpace = (space: SpaceItem) => {
+ const spaceKey = spaceContainerKey(space.id);
+ if (!expanded.has(spaceKey)) return;
+ folders
+ .filter((f) => f.space_id === space.id)
+ .forEach((folder) => {
+ const folderKey = folderContainerKey(folder.id);
+ rows.push({ type: "folder", key: folderKey, folder, level: 1 });
+ if (expanded.has(folderKey)) {
+ (notesByContainer[folderKey] ?? []).forEach((note) => {
+ rows.push({
+ type: "note",
+ key: `n:${note.id}`,
+ note,
+ parentKey: folderKey,
+ level: 2,
+ });
+ });
+ }
+ });
+ (notesByContainer[spaceKey] ?? []).forEach((note) => {
+ rows.push({ type: "note", key: `n:${note.id}`, note, level: 1 });
+ });
+ };
const pushSpace = (space: SpaceItem) => {
const spaceKey = spaceContainerKey(space.id);
rows.push({ type: "space", key: spaceKey, space });
@@ -1318,7 +1414,7 @@ export default function SpacesTree({
.filter((f) => f.space_id === space.id)
.forEach((folder) => {
const folderKey = folderContainerKey(folder.id);
- rows.push({ type: "folder", key: folderKey, folder, parentKey: spaceKey });
+ rows.push({ type: "folder", key: folderKey, folder, parentKey: spaceKey, level: 2 });
if (expanded.has(folderKey)) {
(notesByContainer[folderKey] ?? []).forEach((note) => {
rows.push({
@@ -1335,7 +1431,7 @@ export default function SpacesTree({
rows.push({ type: "note", key: `n:${note.id}`, note, parentKey: spaceKey, level: 2 });
});
};
- privateSpaces.forEach(pushSpace);
+ privateSpaces.forEach(pushPrivateSpace);
if (teamCapability) teamSpaces.forEach(pushSpace);
return rows;
}, [privateSpaces, teamSpaces, folders, notesByContainer, expanded, teamCapability]);
@@ -1359,9 +1455,12 @@ export default function SpacesTree({
const activateRow = (row: TreeRow) => {
if (row.type === "space") {
+ // Deselect the note so the main pane shows the container overview.
+ setActiveNoteId(null);
setActiveContext(row.space.id, null);
toggleContainerExpanded(row.key);
} else if (row.type === "folder") {
+ setActiveNoteId(null);
setActiveContext(row.folder.space_id, row.folder.id);
toggleContainerExpanded(row.key);
} else {
@@ -1593,11 +1692,17 @@ export default function SpacesTree({
}
};
- const renderNote = (note: NoteItem, level: 2 | 3, parentKey: string) => (
+ const renderNote = (
+ note: NoteItem,
+ level: 1 | 2 | 3,
+ parentKey?: string,
+ indentClassName?: string
+ ) => (
<NoteLeaf
key={note.id}
note={note}
level={level}
+ indentClassName={indentClassName}
isActive={note.id === activeNoteId}
isDragging={dragState.draggingNoteId === note.id}
dragHandlers={noteDragHandlers({
@@ -1619,14 +1724,14 @@ export default function SpacesTree({
/>
);
- const renderFolder = (folder: FolderItem, parentKey: string) => {
+ const renderFolder = (folder: FolderItem, parentKey?: string, level: 1 | 2 = 2) => {
const folderKey = folderContainerKey(folder.id);
const isExpanded = expanded.has(folderKey);
const isRenaming = renamingFolderId === folder.id;
if (isRenaming) {
return (
- <div key={folder.id} role="none" className="pl-[14px] pr-2">
+ <div key={folder.id} role="none" className={cn(level === 1 ? "pl-2" : "pl-[14px]", "pr-2")}>
<input
autoFocus
value={renameValue}
@@ -1654,6 +1759,7 @@ export default function SpacesTree({
<div key={folder.id} role="none">
<FolderRow
folder={folder}
+ level={level}
spaces={visibleSpaces}
isExpanded={isExpanded}
isActive={activeContext?.folderId === folder.id}
@@ -1668,7 +1774,9 @@ export default function SpacesTree({
})}
noteFilesEnabled={noteFilesEnabled}
fileManagerName={fileManagerName}
- onActivate={() => activateRow({ type: "folder", key: folderKey, folder, parentKey })}
+ onActivate={() =>
+ activateRow({ type: "folder", key: folderKey, folder, parentKey, level })
+ }
onToggle={() => toggleContainerExpanded(folderKey)}
onRename={() => startRenameFolder(folder)}
onMoveToSpace={(space) => requestMoveFolder(folder, space)}
@@ -1678,24 +1786,19 @@ export default function SpacesTree({
/>
<TreeChildren open={isExpanded}>
<div className="space-y-px">
- {(notesByContainer[folderKey] ?? []).map((note) => renderNote(note, 3, folderKey))}
+ {(notesByContainer[folderKey] ?? []).map((note) =>
+ level === 1 ? renderNote(note, 2, folderKey, "pl-8") : renderNote(note, 3, folderKey)
+ )}
</div>
</TreeChildren>
</div>
);
};
- const renderSpace = (space: SpaceItem) => {
+ const renderSpaceContents = (space: SpaceItem, flattened = false) => {
const spaceKey = spaceContainerKey(space.id);
- const isExpanded = expanded.has(spaceKey);
const spaceFolders = folders.filter((f) => f.space_id === space.id);
const rootNotes = notesByContainer[spaceKey];
- const displayName = spaceDisplayName(space, t);
- // DB-backed counts: space-root notes count before their container loads,
- // and the root contribution isn't capped at the container's page size.
- const noteCount =
- spaceFolders.reduce((sum, f) => sum + (folderCounts[f.id] ?? 0), 0) +
- (spaceRootCounts[space.id] ?? 0);
const showSkeletons =
space.kind === "team" &&
space.sync_status === "pending" &&
@@ -1704,6 +1807,68 @@ export default function SpacesTree({
const showEmptySpace =
space.kind === "team" && spaceFolders.length === 0 && rootNotes?.length === 0;
+ return (
+ <div className="space-y-px">
+ {spaceFolders.map((folder) =>
+ flattened ? renderFolder(folder, undefined, 1) : renderFolder(folder, spaceKey)
+ )}
+ {creatingFolderSpaceId === space.id && (
+ <div className={cn(flattened ? "pl-2" : "pl-[14px]", "pr-2")}>
+ <input
+ autoFocus
+ value={newFolderName}
+ onChange={(e) => setNewFolderName(e.target.value)}
+ onKeyDown={(e) => {
+ if (e.key === "Enter") {
+ void confirmCreateFolder().then((key) => key && focusRowSoon(key));
+ }
+ if (e.key === "Escape") {
+ setCreatingFolderSpaceId(null);
+ setNewFolderName("");
+ if (flattened) privateSectionToggleRef.current?.focus();
+ else focusRowSoon(spaceKey);
+ }
+ }}
+ onBlur={confirmCreateFolder}
+ placeholder={t("notes.folders.folderName")}
+ className={cn(FOLDER_INPUT_CLASS, "placeholder:text-foreground/20")}
+ />
+ </div>
+ )}
+ {(rootNotes ?? []).map((note) =>
+ flattened ? renderNote(note, 1, undefined, "pl-[30px]") : renderNote(note, 2, spaceKey)
+ )}
+ {showSkeletons && <SkeletonRows />}
+ {showEmptySpace && (
+ <div className="pl-[18px] pr-2 py-1">
+ <p className="text-xs text-foreground/40 leading-relaxed mb-1.5">
+ {t("notes.spaces.emptySpace", { space: space.name })}
+ </p>
+ <Button
+ variant="ghost"
+ size="sm"
+ onClick={() => onNewNote(space.id, null)}
+ className="h-6 px-2 text-xs gap-1 text-primary/70 hover:text-primary hover:bg-primary/8"
+ >
+ <Plus size={11} />
+ {t("notes.list.newNote")}
+ </Button>
+ </div>
+ )}
+ </div>
+ );
+ };
+
+ const renderSpace = (space: SpaceItem) => {
+ const spaceKey = spaceContainerKey(space.id);
+ const isExpanded = expanded.has(spaceKey);
+ const spaceFolders = folders.filter((f) => f.space_id === space.id);
+ const displayName = spaceDisplayName(space, t);
+ // DB-backed counts: space-root notes count before their container loads,
+ // and the root contribution isn't capped at the container's page size.
+ const noteCount =
+ spaceFolders.reduce((sum, f) => sum + (folderCounts[f.id] ?? 0), 0) +
+ (spaceRootCounts[space.id] ?? 0);
return (
<div key={space.id} role="none">
{renamingSpaceId === space.id ? (
@@ -1769,51 +1934,7 @@ export default function SpacesTree({
t={t}
/>
)}
- <TreeChildren open={isExpanded}>
- <div className="space-y-px">
- {spaceFolders.map((folder) => renderFolder(folder, spaceKey))}
- {creatingFolderSpaceId === space.id && (
- <div className="pl-[14px] pr-2">
- <input
- autoFocus
- value={newFolderName}
- onChange={(e) => setNewFolderName(e.target.value)}
- onKeyDown={(e) => {
- if (e.key === "Enter") {
- void confirmCreateFolder().then((key) => key && focusRowSoon(key));
- }
- if (e.key === "Escape") {
- setCreatingFolderSpaceId(null);
- setNewFolderName("");
- focusRowSoon(spaceKey);
- }
- }}
- onBlur={confirmCreateFolder}
- placeholder={t("notes.folders.folderName")}
- className={cn(FOLDER_INPUT_CLASS, "placeholder:text-foreground/20")}
- />
- </div>
- )}
- {(rootNotes ?? []).map((note) => renderNote(note, 2, spaceKey))}
- {showSkeletons && <SkeletonRows />}
- {showEmptySpace && (
- <div className="pl-[18px] pr-2 py-1">
- <p className="text-xs text-foreground/40 leading-relaxed mb-1.5">
- {t("notes.spaces.emptySpace", { space: space.name })}
- </p>
- <Button
- variant="ghost"
- size="sm"
- onClick={() => onNewNote(space.id, null)}
- className="h-6 px-2 text-xs gap-1 text-primary/70 hover:text-primary hover:bg-primary/8"
- >
- <Plus size={11} />
- {t("notes.list.newNote")}
- </Button>
- </div>
- )}
- </div>
- </TreeChildren>
+ <TreeChildren open={isExpanded}>{renderSpaceContents(space)}</TreeChildren>
</div>
);
};
@@ -1836,8 +1957,50 @@ export default function SpacesTree({
aria-label={t("notes.list.title")}
className="flex-1 overflow-y-auto px-1.5 pb-2 space-y-px"
>
- <SectionHeader label={t("notes.spaces.privateSpaces")} />
- {privateSpaces.map(renderSpace)}
+ <div role="none" className="group/section">
+ <SectionHeader
+ label={t("notes.spaces.privateSpaces")}
+ expanded={privateSectionExpanded}
+ onToggle={() => {
+ if (privateSpace) toggleContainerExpanded(spaceContainerKey(privateSpace.id));
+ }}
+ toggleRef={privateSectionToggleRef}
+ dropHandlers={
+ privateSpace
+ ? dropTargetHandlers({ spaceId: privateSpace.id, folderId: null })
+ : undefined
+ }
+ isDragOver={
+ privateSpace && dragState.dragOverKey === spaceContainerKey(privateSpace.id)
+ }
+ isDropSuccess={
+ privateSpace && dragState.dropSuccessKey === spaceContainerKey(privateSpace.id)
+ }
+ action={
+ privateSpace ? (
+ <Button
+ variant="ghost"
+ size="icon"
+ aria-label={t("notes.context.newFolder")}
+ onClick={() => startCreateFolder(privateSpace)}
+ className={cn(
+ "h-5 w-5 rounded-sm opacity-0 group-hover/section:opacity-100 focus-visible:opacity-100",
+ "transition-opacity text-muted-foreground/60 dark:text-muted-foreground/40",
+ "hover:text-foreground/60 hover:bg-foreground/5 active:bg-foreground/8"
+ )}
+ >
+ <Plus size={12} />
+ </Button>
+ ) : undefined
+ }
+ />
+ {privateSpace && (
+ <TreeChildren open={privateSectionExpanded} grouped={false}>
+ {/* The private space remains the storage/sync boundary but is flattened in the UI. */}
+ {renderSpaceContents(privateSpace, true)}
+ </TreeChildren>
+ )}
+ </div>
{teamCapability && (
<div role="none" className="group/section">
<SectionHeader
diff --git a/src/components/notes/overview/ContainerIcon.tsx b/src/components/notes/overview/ContainerIcon.tsx
new file mode 100644
index 000000000..d339c5a6b
--- /dev/null
+++ b/src/components/notes/overview/ContainerIcon.tsx
@@ -0,0 +1,25 @@
+import { Folder, Lock, Users } from "lucide-react";
+import type { SpaceItem, FolderItem } from "../../../types/electron";
+
+interface ContainerIconProps {
+ space: SpaceItem;
+ folder: FolderItem | null;
+ size?: number;
+}
+
+export function ContainerIcon({ space, folder, size = 14 }: ContainerIconProps) {
+ if (folder) {
+ return <Folder size={size} className="text-muted-foreground/60 shrink-0" />;
+ }
+ if (space.kind === "private") {
+ return <Lock size={size} className="text-muted-foreground/60 shrink-0" />;
+ }
+ if (space.emoji) {
+ return (
+ <span className="leading-none shrink-0" style={{ fontSize: size }} aria-hidden="true">
+ {space.emoji}
+ </span>
+ );
+ }
+ return <Users size={size} className="text-muted-foreground/60 shrink-0" />;
+}
diff --git a/src/components/notes/overview/ContainerOverview.tsx b/src/components/notes/overview/ContainerOverview.tsx
new file mode 100644
index 000000000..65aee20c8
--- /dev/null
+++ b/src/components/notes/overview/ContainerOverview.tsx
@@ -0,0 +1,164 @@
+import { useEffect, useMemo, useState } from "react";
+import { UserPlus } from "lucide-react";
+import { useTranslation } from "react-i18next";
+import InviteTeammateDialog from "../../InviteTeammateDialog";
+import { useWorkspaceStore } from "../../../stores/workspaceStore";
+import { canManageSpace } from "../../../lib/spacePermissions";
+import {
+ useNotes,
+ useNotesByContainer,
+ useFolders,
+ useFolderCounts,
+ useSpaceRootCounts,
+} from "../../../stores/noteStore";
+import { useContainerChat } from "../../../hooks/useContainerChat";
+import { ContainerIcon } from "./ContainerIcon";
+import { OverviewExplainerBanner } from "./OverviewExplainerBanner";
+import { OverviewAskSection } from "./OverviewAskSection";
+import { OverviewNoteList } from "./OverviewNoteList";
+import type { NoteItem, SpaceItem, FolderItem } from "../../../types/electron";
+
+const SPACE_NOTES_LIMIT = 50;
+
+interface ContainerOverviewProps {
+ space: SpaceItem;
+ folder: FolderItem | null;
+ onOpenNote: (noteId: number) => void;
+ onNewNote: () => void;
+ onAddExisting?: () => void;
+}
+
+export function ContainerOverview({
+ space,
+ folder,
+ onOpenNote,
+ onNewNote,
+ onAddExisting,
+}: ContainerOverviewProps) {
+ const { t } = useTranslation();
+ const workspaces = useWorkspaceStore((s) => s.workspaces);
+ const folders = useFolders();
+ const containerNotes = useNotes();
+ const notesByContainer = useNotesByContainer();
+ const folderCounts = useFolderCounts();
+ const spaceRootCounts = useSpaceRootCounts();
+ const [spaceNotes, setSpaceNotes] = useState<NoteItem[] | null>(null);
+ const [showInviteDialog, setShowInviteDialog] = useState(false);
+
+ // Folder overviews mirror the store's active container; space overviews list
+ // the whole space (foldered + root), which the store doesn't hold — fetched
+ // here and refreshed whenever any container's notes change.
+ useEffect(() => {
+ if (folder) return;
+ let stale = false;
+ window.electronAPI
+ .getSpaceNotes(space.id, SPACE_NOTES_LIMIT)
+ .then((rows) => {
+ if (!stale) setSpaceNotes(rows ?? []);
+ })
+ .catch(() => {
+ if (!stale) setSpaceNotes([]);
+ });
+ return () => {
+ stale = true;
+ };
+ }, [folder, space.id, notesByContainer]);
+
+ const notes = folder ? containerNotes : (spaceNotes ?? []);
+
+ const chat = useContainerChat({ space, folder, notes });
+
+ const workspace = space.workspace_id
+ ? workspaces.find((w) => w.id === space.workspace_id)
+ : undefined;
+ const canInvite =
+ space.kind === "team" &&
+ !!space.cloud_team_id &&
+ !!workspace &&
+ canManageSpace(space, workspace.role ?? null);
+
+ const spaceFolders = useMemo(
+ () => folders.filter((f) => f.space_id === space.id),
+ [folders, space.id]
+ );
+ // DB-backed counts, as in SpacesTree: the visible list is capped at the
+ // container page size, so notes.length undercounts large containers.
+ const noteCount = folder
+ ? (folderCounts[folder.id] ?? notes.length)
+ : spaceFolders.reduce((sum, f) => sum + (folderCounts[f.id] ?? 0), 0) +
+ (spaceRootCounts[space.id] ?? 0);
+
+ const metaParts: string[] = [];
+ if (space.kind === "team" && workspace) metaParts.push(workspace.name);
+ if (!folder && spaceFolders.length > 0) {
+ metaParts.push(t("notes.overview.meta.folders", { count: spaceFolders.length }));
+ }
+ metaParts.push(t("notes.spaces.noteCount", { count: noteCount }));
+ if (space.kind === "team" && space.member_count != null) {
+ metaParts.push(t("notes.overview.meta.members", { count: space.member_count }));
+ }
+
+ return (
+ <div className="flex-1 overflow-y-auto min-h-0">
+ <div className="max-w-2xl mx-auto px-6 py-8 flex flex-col gap-5">
+ <div className="flex flex-col items-center text-center gap-2 pt-4">
+ <div className="h-12 w-12 rounded-xl bg-foreground/4 dark:bg-white/5 border border-border/25 dark:border-white/8 flex items-center justify-center mb-1">
+ <ContainerIcon space={space} folder={folder} size={20} />
+ </div>
+ <h1 className="text-xl font-semibold text-foreground tracking-tight">
+ {folder?.name ?? space.name}
+ </h1>
+ <p className="text-[13px] text-foreground/50 dark:text-foreground/40">
+ {t(`notes.overview.subtitle.${space.kind === "team" ? "team" : "private"}`)}
+ </p>
+ <p className="text-xs text-foreground/35 dark:text-foreground/25">
+ {metaParts.join(" · ")}
+ </p>
+ {canInvite && (
+ <button
+ onClick={() => setShowInviteDialog(true)}
+ className="mt-1 inline-flex items-center gap-1.5 px-3 h-7 rounded-md border border-border/40 dark:border-white/10 text-xs font-medium text-foreground/60 hover:text-foreground/85 hover:border-border/70 hover:bg-foreground/3 dark:hover:bg-white/3 transition-colors duration-150 focus:outline-none focus-visible:ring-1 focus-visible:ring-ring/30"
+ >
+ <UserPlus size={12} />
+ {t("notes.overview.invite")}
+ </button>
+ )}
+ </div>
+
+ <OverviewExplainerBanner kind={space.kind === "team" ? "team" : "private"} />
+
+ <OverviewAskSection
+ messages={chat.messages}
+ agentState={chat.agentState}
+ onTextSubmit={chat.sendMessage}
+ onCancel={chat.cancelStream}
+ conversations={chat.conversations}
+ activeConversationId={chat.activeConversationId}
+ onSwitchConversation={chat.switchConversation}
+ onNewChat={chat.startNewChat}
+ onOpenNote={onOpenNote}
+ />
+
+ <div className="border-t border-border/20 dark:border-white/5">
+ <OverviewNoteList
+ notes={notes}
+ space={space}
+ onOpenNote={onOpenNote}
+ onNewNote={onNewNote}
+ onAddExisting={onAddExisting}
+ />
+ </div>
+ </div>
+
+ {canInvite && workspace && space.cloud_team_id && (
+ <InviteTeammateDialog
+ open={showInviteDialog}
+ onOpenChange={setShowInviteDialog}
+ workspaceId={workspace.id}
+ workspaceName={workspace.name}
+ teamIds={[space.cloud_team_id]}
+ />
+ )}
+ </div>
+ );
+}
diff --git a/src/components/notes/overview/OverviewAskSection.tsx b/src/components/notes/overview/OverviewAskSection.tsx
new file mode 100644
index 000000000..5c5614c85
--- /dev/null
+++ b/src/components/notes/overview/OverviewAskSection.tsx
@@ -0,0 +1,131 @@
+import { ChevronDown, Plus, Sparkles } from "lucide-react";
+import { useTranslation } from "react-i18next";
+import { cn } from "../../lib/utils";
+import { ChatMessages } from "../../chat/ChatMessages";
+import { ChatInput } from "../../chat/ChatInput";
+import type { Message, AgentState } from "../../chat/types";
+import { formatShortDate } from "../../../utils/dateFormatting";
+import {
+ DropdownMenu,
+ DropdownMenuTrigger,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuSeparator,
+} from "../../ui/dropdown-menu";
+
+const PROMPT_CHIP_KEYS = [
+ "notes.overview.ask.chips.catchUp",
+ "notes.overview.ask.chips.keyDecisions",
+ "notes.overview.ask.chips.inFlight",
+] as const;
+
+interface OverviewAskSectionProps {
+ messages: Message[];
+ agentState: AgentState;
+ onTextSubmit: (text: string) => void;
+ onCancel: () => void;
+ conversations: Array<{
+ id: number;
+ title: string;
+ created_at: string;
+ updated_at: string;
+ message_count: number;
+ }>;
+ activeConversationId: number | null;
+ onSwitchConversation: (id: number) => void;
+ onNewChat: () => void;
+ onOpenNote: (noteId: number) => void;
+}
+
+export function OverviewAskSection({
+ messages,
+ agentState,
+ onTextSubmit,
+ onCancel,
+ conversations,
+ activeConversationId,
+ onSwitchConversation,
+ onNewChat,
+ onOpenNote,
+}: OverviewAskSectionProps) {
+ const { t } = useTranslation();
+ const hasMessages = messages.length > 0;
+ const activeConversation = conversations.find((c) => c.id === activeConversationId);
+
+ const conversationPicker = (conversations.length > 0 || hasMessages) && (
+ <div className="flex items-center px-3 pt-2">
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <button
+ className="inline-flex items-center gap-1 text-xs font-medium text-foreground/50 hover:text-foreground/70 hover:bg-foreground/5 rounded-md px-1.5 py-0.5 -ml-1.5 transition-colors duration-150 outline-none"
+ aria-label={t("embeddedChat.conversationSelector")}
+ >
+ <span className="truncate max-w-40">
+ {activeConversation?.title || t("embeddedChat.newChat")}
+ </span>
+ <ChevronDown size={10} className="shrink-0 text-foreground/30" />
+ </button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="start" sideOffset={4} className="min-w-44 max-w-56 p-1">
+ <DropdownMenuItem onClick={onNewChat} className="text-xs gap-2 rounded-md px-2 py-1.5">
+ <Plus size={10} className="text-foreground/40 shrink-0" />
+ {t("embeddedChat.newChat")}
+ </DropdownMenuItem>
+ {conversations.length > 0 && (
+ <>
+ <DropdownMenuSeparator />
+ {conversations.map((conv) => (
+ <DropdownMenuItem
+ key={conv.id}
+ onClick={() => onSwitchConversation(conv.id)}
+ className={cn(
+ "text-xs gap-2 rounded-md px-2 py-1.5",
+ conv.id === activeConversationId && "bg-foreground/4"
+ )}
+ >
+ <span className="truncate flex-1">{conv.title}</span>
+ <span className="text-[10px] text-foreground/30 shrink-0">
+ {formatShortDate(conv.updated_at)}
+ </span>
+ </DropdownMenuItem>
+ ))}
+ </>
+ )}
+ </DropdownMenuContent>
+ </DropdownMenu>
+ </div>
+ );
+
+ return (
+ <div className="rounded-xl bg-surface-1/50 dark:bg-white/2 border border-border/25 dark:border-white/6">
+ {conversationPicker}
+ {hasMessages && (
+ <div className="max-h-[min(26rem,50vh)] flex flex-col">
+ <ChatMessages messages={messages} onOpenNote={onOpenNote} />
+ </div>
+ )}
+ <ChatInput
+ agentState={agentState}
+ partialTranscript=""
+ onTextSubmit={onTextSubmit}
+ onCancel={onCancel}
+ placeholder={t("notes.overview.ask.placeholder")}
+ />
+ {!hasMessages && (
+ <div className="flex items-center flex-wrap gap-1.5 px-3 pb-3">
+ {PROMPT_CHIP_KEYS.map((key) => (
+ <button
+ key={key}
+ onClick={() => onTextSubmit(t(key))}
+ disabled={agentState !== "idle"}
+ className="inline-flex items-center gap-1.5 px-2.5 h-7 rounded-md border border-border/40 dark:border-white/8 text-[11px] text-foreground/55 hover:text-foreground/80 hover:border-border/70 hover:bg-foreground/3 dark:hover:bg-white/3 disabled:opacity-50 disabled:pointer-events-none transition-colors duration-150 focus:outline-none focus-visible:ring-1 focus-visible:ring-ring/30"
+ >
+ <Sparkles size={10} className="text-foreground/30 shrink-0" />
+ {t(key)}
+ </button>
+ ))}
+ </div>
+ )}
+ </div>
+ );
+}
diff --git a/src/components/notes/overview/OverviewExplainerBanner.tsx b/src/components/notes/overview/OverviewExplainerBanner.tsx
new file mode 100644
index 000000000..21a8c5a60
--- /dev/null
+++ b/src/components/notes/overview/OverviewExplainerBanner.tsx
@@ -0,0 +1,39 @@
+import { useState } from "react";
+import { X } from "lucide-react";
+import { useTranslation } from "react-i18next";
+import {
+ markContainerOverviewIntroSeen,
+ shouldShowContainerOverviewIntro,
+} from "../../../lib/containerOverviewIntro";
+
+interface OverviewExplainerBannerProps {
+ kind: "team" | "private";
+}
+
+export function OverviewExplainerBanner({ kind }: OverviewExplainerBannerProps) {
+ const { t } = useTranslation();
+ const [visible, setVisible] = useState(() => shouldShowContainerOverviewIntro(localStorage));
+
+ if (!visible) return null;
+
+ return (
+ <div className="relative rounded-lg bg-primary/5 dark:bg-primary/8 border border-primary/10 dark:border-primary/15 px-4 py-3">
+ <button
+ onClick={() => {
+ markContainerOverviewIntroSeen(localStorage);
+ setVisible(false);
+ }}
+ aria-label={t("notes.overview.banner.dismiss")}
+ className="absolute top-2.5 right-2.5 h-5 w-5 flex items-center justify-center rounded-sm text-foreground/30 hover:text-foreground/60 hover:bg-foreground/6 transition-colors duration-150 focus:outline-none focus-visible:ring-1 focus-visible:ring-ring/30"
+ >
+ <X size={12} />
+ </button>
+ <p className="text-xs font-medium text-foreground/80 mb-0.5">
+ {t(`notes.overview.banner.title.${kind}`)}
+ </p>
+ <p className="text-xs text-foreground/55 dark:text-foreground/45 max-w-lg pr-6">
+ {t(`notes.overview.banner.body.${kind}`)}
+ </p>
+ </div>
+ );
+}
diff --git a/src/components/notes/overview/OverviewNoteList.tsx b/src/components/notes/overview/OverviewNoteList.tsx
new file mode 100644
index 000000000..39f7a923f
--- /dev/null
+++ b/src/components/notes/overview/OverviewNoteList.tsx
@@ -0,0 +1,107 @@
+import { useMemo } from "react";
+import { FileText, Plus } from "lucide-react";
+import { useTranslation } from "react-i18next";
+import MemberAvatar from "../../MemberAvatar";
+import { groupItemsByDate } from "../../../utils/dateGrouping";
+import { formatRelativeTime } from "../../../utils/dateFormatting";
+import { useTeamRoster } from "../../../hooks/useTeamRoster";
+import { useAuth } from "../../../hooks/useAuth";
+import type { NoteItem, SpaceItem } from "../../../types/electron";
+
+interface OverviewNoteListProps {
+ notes: NoteItem[];
+ space: SpaceItem;
+ onOpenNote: (noteId: number) => void;
+ onNewNote: () => void;
+ onAddExisting?: () => void;
+}
+
+export function OverviewNoteList({
+ notes,
+ space,
+ onOpenNote,
+ onNewNote,
+ onAddExisting,
+}: OverviewNoteListProps) {
+ const { t } = useTranslation();
+ const { user } = useAuth();
+ const isTeamSpace = space.kind === "team";
+ const roster = useTeamRoster(isTeamSpace ? space.cloud_team_id : null);
+
+ const groups = useMemo(() => groupItemsByDate(notes, (n) => n.updated_at, t), [notes, t]);
+
+ if (notes.length === 0) {
+ return (
+ <div className="flex flex-col items-center py-8">
+ <p className="text-xs text-foreground/40 dark:text-foreground/30 mb-3">
+ {t("notes.overview.list.empty")}
+ </p>
+ <div className="flex items-center gap-2">
+ <button
+ onClick={onNewNote}
+ className="flex items-center gap-1.5 px-4 h-7 rounded-md bg-primary/8 dark:bg-primary/10 border border-primary/12 dark:border-primary/15 text-xs font-medium text-primary/70 hover:bg-primary/12 hover:text-primary hover:border-primary/20 transition-colors"
+ >
+ <Plus size={11} />
+ {t("notes.empty.createNote")}
+ </button>
+ {onAddExisting && (
+ <button
+ onClick={onAddExisting}
+ className="flex items-center gap-1.5 px-4 h-7 rounded-md border border-foreground/8 dark:border-white/8 text-xs text-foreground/40 hover:text-foreground/60 hover:border-foreground/15 hover:bg-foreground/3 dark:hover:bg-white/3 transition-colors"
+ >
+ {t("notes.addToFolder.addExisting")}
+ </button>
+ )}
+ </div>
+ </div>
+ );
+ }
+
+ return (
+ <div className="pb-6">
+ {groups.map((group) => (
+ <div key={group.label}>
+ <div className="pt-4 pb-1 text-[10px] font-semibold text-muted-foreground/40 uppercase tracking-wider select-none">
+ {group.label}
+ </div>
+ {group.items.map((note) => {
+ const authorId = isTeamSpace ? note.updated_by_user_id : null;
+ const member = authorId ? roster?.get(authorId) : undefined;
+ const isSelf = authorId != null && authorId === user?.id;
+ const authorName = isSelf
+ ? t("notes.overview.author.you")
+ : (member?.name ?? member?.email ?? null);
+ return (
+ <button
+ key={note.id}
+ onClick={() => onOpenNote(note.id)}
+ className="w-full flex items-center gap-3 px-2 py-2 -mx-2 rounded-md text-left hover:bg-foreground/4 dark:hover:bg-white/4 transition-colors duration-150 focus:outline-none focus-visible:ring-1 focus-visible:ring-ring/30"
+ >
+ <FileText size={14} className="text-foreground/30 dark:text-foreground/20 shrink-0" />
+ <span className="text-[13px] text-foreground/85 truncate flex-1">
+ {note.title || t("notes.list.untitled")}
+ </span>
+ {authorName && (
+ <span className="flex items-center gap-1.5 shrink-0">
+ <MemberAvatar
+ name={member?.name ?? authorName}
+ email={member?.email ?? ""}
+ image={member?.image}
+ size="sm"
+ />
+ <span className="text-[11px] text-foreground/40 max-w-28 truncate">
+ {authorName}
+ </span>
+ </span>
+ )}
+ <span className="text-[11px] text-foreground/35 dark:text-foreground/25 shrink-0 tabular-nums">
+ {formatRelativeTime(note.updated_at, t)}
+ </span>
+ </button>
+ );
+ })}
+ </div>
+ ))}
+ </div>
+ );
+}
diff --git a/src/components/settings/WorkspaceSection.tsx b/src/components/settings/WorkspaceSection.tsx
index a2a7fcc52..2d78bffe1 100644
--- a/src/components/settings/WorkspaceSection.tsx
+++ b/src/components/settings/WorkspaceSection.tsx
@@ -161,7 +161,7 @@ export default function WorkspaceSection({ initialSubTab }: Props) {
<div className="space-y-4">
<div className="flex items-center justify-between">
<div className="min-w-0">
- <DropdownMenu>
+ <DropdownMenu modal={false}>
<DropdownMenuTrigger
className={cn(
"group flex items-center gap-1.5 outline-none rounded-md px-2 -mx-2 py-0.5",
diff --git a/src/helpers/database.js b/src/helpers/database.js
index 498df8f61..2178c86ad 100644
--- a/src/helpers/database.js
+++ b/src/helpers/database.js
@@ -310,6 +310,19 @@ class DatabaseManager {
this.db.exec(
"CREATE INDEX IF NOT EXISTS idx_agent_conversations_note ON agent_conversations(note_id)"
);
+ try {
+ this.db.exec("ALTER TABLE agent_conversations ADD COLUMN space_id INTEGER");
+ } catch (err) {
+ if (!err.message.includes("duplicate column")) throw err;
+ }
+ try {
+ this.db.exec("ALTER TABLE agent_conversations ADD COLUMN folder_id INTEGER");
+ } catch (err) {
+ if (!err.message.includes("duplicate column")) throw err;
+ }
+ this.db.exec(
+ "CREATE INDEX IF NOT EXISTS idx_agent_conversations_container ON agent_conversations(space_id, folder_id)"
+ );
const actionCount = this.db.prepare("SELECT COUNT(*) as count FROM actions").get();
if (actionCount.count === 0) {
@@ -793,6 +806,15 @@ class DatabaseManager {
if (!err.message.includes("duplicate column")) throw err;
}
+ // Last cloud editor (CloudNote.updated_by_user_id); only populated on
+ // cloud pull — local edits don't set it. Resolved to a display name via
+ // the team roster when rendering note authorship.
+ try {
+ this.db.exec("ALTER TABLE notes ADD COLUMN updated_by_user_id TEXT");
+ } catch (err) {
+ if (!err.message.includes("duplicate column")) throw err;
+ }
+
// Space vector purges owed to Qdrant while the sidecar was down/booting;
// drained once the vector index is ready.
this.db.exec(`
@@ -1655,6 +1677,35 @@ class DatabaseManager {
}
}
+ // Unlike getNotes(null, limit, null, spaceId) — which is root-only — this
+ // lists every note in the space, foldered or not (space overview list).
+ getNotesForSpace(spaceId, limit = 50) {
+ try {
+ if (!this.db) throw new Error("Database not initialized");
+ return this.db
+ .prepare(
+ "SELECT * FROM notes WHERE space_id = ? AND deleted_at IS NULL ORDER BY updated_at DESC LIMIT ?"
+ )
+ .all(spaceId, limit);
+ } catch (error) {
+ debugLogger.error("Error getting notes for space", { error: error.message }, "notes");
+ throw error;
+ }
+ }
+
+ getNoteIdsInFolder(folderId) {
+ try {
+ if (!this.db) throw new Error("Database not initialized");
+ return this.db
+ .prepare("SELECT id FROM notes WHERE folder_id = ? AND deleted_at IS NULL")
+ .all(folderId)
+ .map((row) => row.id);
+ } catch (error) {
+ debugLogger.error("Error getting note ids in folder", { error: error.message }, "notes");
+ throw error;
+ }
+ }
+
updateNote(id, updates) {
try {
if (!this.db) throw new Error("Database not initialized");
@@ -1929,6 +1980,11 @@ class DatabaseManager {
createSpace({ name, emoji = null, kind = "team" } = {}) {
try {
if (!this.db) throw new Error("Database not initialized");
+ if (kind !== "team") {
+ // The single private space is seeded by the migration; a second one
+ // would split default-folder resolution and purge relocation targets.
+ return { success: false, error: "Only team spaces can be created" };
+ }
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();
@@ -2033,7 +2089,7 @@ class DatabaseManager {
this.db
.prepare(
`UPDATE spaces SET workspace_id = ?, name = ?, emoji = ?, my_role = ?, member_count = ?,
- sync_status = 'synced', deleted_at = NULL, updated_at = ? WHERE id = ?`
+ deleted_at = NULL, updated_at = ? WHERE id = ?`
)
.run(
team.workspace_id ?? null,
@@ -2047,11 +2103,14 @@ class DatabaseManager {
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();
+ // New spaces insert as 'pending' (skeletons until the content backfill
+ // completes); updates never touch sync_status, so an interrupted
+ // backfill's 'pending' survives the next mirror pass and re-runs.
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', ?, ?)`
+ VALUES (?, ?, ?, 'team', ?, ?, ?, ?, ?, 'pending', ?, ?)`
)
.run(
randomUUID(),
@@ -2072,7 +2131,8 @@ class DatabaseManager {
}
}
- // FKs are not enforced in this DB — clean speaker rows explicitly.
+ // Speaker rows cascade on note delete (ON DELETE CASCADE), but callers that
+ // only tombstone notes still need the explicit cleanup.
_deleteSpeakerRowsForNotes(noteIdSubquery, param) {
this.db.prepare(`DELETE FROM speaker_mappings WHERE note_id IN (${noteIdSubquery})`).run(param);
this.db
@@ -2090,24 +2150,27 @@ class DatabaseManager {
}
const privateSpaceId = this.getPrivateSpaceId();
const { noteIds, folderNames, relocatedNotes } = this.db.transaction(() => {
- // Never-synced notes exist nowhere else — move them to the private
- // space root instead of destroying them with the space.
+ // Dirty or never-synced notes are the only surviving content (plan
+ // §7.2, matching relocateRevokedFolder): they move to the private
+ // space root with forked identities — the server row (if any) stays
+ // the team's, so the next push re-creates them as personal notes.
let relocated = [];
if (privateSpaceId != null) {
- const neverSynced = this.db
+ const preservedIds = this.db
.prepare(
- "SELECT id FROM notes WHERE space_id = ? AND cloud_id IS NULL AND deleted_at IS NULL"
+ "SELECT id FROM notes WHERE space_id = ? AND deleted_at IS NULL AND (sync_status != 'synced' OR cloud_id IS NULL)"
)
.all(localSpaceId)
.map((row) => row.id);
- if (neverSynced.length > 0) {
- this.db
- .prepare(
- "UPDATE notes SET space_id = ?, folder_id = NULL, sync_status = 'pending', updated_at = datetime('now') WHERE space_id = ? AND cloud_id IS NULL AND deleted_at IS NULL"
- )
- .run(privateSpaceId, localSpaceId);
+ if (preservedIds.length > 0) {
+ const relocateNote = this.db.prepare(
+ "UPDATE notes SET space_id = ?, folder_id = NULL, client_note_id = ?, cloud_id = NULL, sync_status = 'pending', left_team = 0, updated_at = datetime('now') WHERE id = ?"
+ );
+ for (const noteId of preservedIds) {
+ relocateNote.run(privateSpaceId, randomUUID(), noteId);
+ }
const getNote = this.db.prepare("SELECT * FROM notes WHERE id = ?");
- relocated = neverSynced.map((id) => getNote.get(id));
+ relocated = preservedIds.map((id) => getNote.get(id));
}
}
const ids = this.db
@@ -2120,6 +2183,14 @@ class DatabaseManager {
.map((row) => row.name);
this._deleteSpeakerRowsForNotes("SELECT id FROM notes WHERE space_id = ?", localSpaceId);
this.db.prepare("DELETE FROM notes WHERE space_id = ?").run(localSpaceId);
+ // Deleted-note tombstones in other spaces can still reference folders
+ // in this space (folder moved across spaces after the delete); clear
+ // the refs or the folder delete below aborts on the FK.
+ this.db
+ .prepare(
+ "UPDATE notes SET folder_id = NULL WHERE space_id != ? AND folder_id IN (SELECT id FROM folders WHERE space_id = ?)"
+ )
+ .run(localSpaceId, 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, relocatedNotes: relocated };
@@ -2271,15 +2342,15 @@ class DatabaseManager {
}
}
- createAgentConversation(title = "Untitled", noteId = null) {
+ createAgentConversation(title = "Untitled", noteId = null, spaceId = null, folderId = null) {
try {
if (!this.db) throw new Error("Database not initialized");
const clientConversationId = randomUUID();
const result = this.db
.prepare(
- "INSERT INTO agent_conversations (title, note_id, client_conversation_id) VALUES (?, ?, ?)"
+ "INSERT INTO agent_conversations (title, note_id, space_id, folder_id, client_conversation_id) VALUES (?, ?, ?, ?, ?)"
)
- .run(title, noteId, clientConversationId);
+ .run(title, noteId, spaceId, folderId, clientConversationId);
return this.db
.prepare("SELECT * FROM agent_conversations WHERE id = ?")
.get(result.lastInsertRowid);
@@ -2314,6 +2385,36 @@ class DatabaseManager {
}
}
+ // Space-root scope (folderId null) intentionally excludes folder-scoped
+ // conversations — each container surfaces only its own chats.
+ getConversationsForContainer(spaceId, folderId = null, limit = 20) {
+ try {
+ if (!this.db) throw new Error("Database not initialized");
+ const scopeFilter =
+ folderId != null ? "c.folder_id = ?" : "c.space_id = ? AND c.folder_id IS NULL";
+ const params = folderId != null ? [folderId, limit] : [spaceId, limit];
+ return this.db
+ .prepare(
+ `SELECT c.id, c.title, c.created_at, c.updated_at,
+ COUNT(m.id) AS message_count
+ FROM agent_conversations c
+ LEFT JOIN agent_messages m ON m.conversation_id = c.id
+ WHERE ${scopeFilter} AND c.deleted_at IS NULL
+ GROUP BY c.id
+ ORDER BY c.updated_at DESC
+ LIMIT ?`
+ )
+ .all(...params);
+ } catch (error) {
+ debugLogger.error(
+ "Error getting conversations for container",
+ { error: error.message },
+ "database"
+ );
+ throw error;
+ }
+ }
+
getAgentConversations(limit = 50) {
try {
if (!this.db) throw new Error("Database not initialized");
@@ -2654,17 +2755,21 @@ class DatabaseManager {
}
}
- searchNotes(query, limit = 50, spaceId = null) {
+ searchNotes(query, limit = 50, spaceId = null, folderId = null) {
try {
if (!this.db) throw new Error("Database not initialized");
const ftsQuery = buildNoteSearchQuery(query);
if (!ftsQuery) return [];
const params = [ftsQuery];
- let spaceFilter = "";
+ let scopeFilter = "";
if (spaceId != null) {
- spaceFilter = "AND n.space_id = ?";
+ scopeFilter += " AND n.space_id = ?";
params.push(spaceId);
}
+ if (folderId != null) {
+ scopeFilter += " AND n.folder_id = ?";
+ params.push(folderId);
+ }
params.push(limit);
return this.db
.prepare(
@@ -2672,7 +2777,7 @@ class DatabaseManager {
SELECT n.*
FROM notes n
JOIN notes_fts ON notes_fts.rowid = n.id
- WHERE notes_fts MATCH ? AND n.deleted_at IS NULL ${spaceFilter}
+ WHERE notes_fts MATCH ? AND n.deleted_at IS NULL${scopeFilter}
ORDER BY notes_fts.rank
LIMIT ?
`
@@ -3229,12 +3334,16 @@ class DatabaseManager {
spaceKind === "team" ? " OR (n.left_team = 1 AND n.cloud_id IS NOT NULL)" : "";
return this.db
.prepare(
- `SELECT n.* FROM notes n JOIN spaces s ON s.id = n.space_id WHERE n.sync_status = 'pending' AND n.deleted_at IS NULL AND (s.kind = ?${leftTeam})`
+ `SELECT n.* FROM notes n JOIN spaces s ON s.id = n.space_id WHERE n.sync_status IN ('pending', 'error') AND n.deleted_at IS NULL AND (s.kind = ?${leftTeam})`
)
.all(spaceKind);
}
+ // 'error' rows retry too: a transient failure (e.g. one offline pass)
+ // must not strand a note until its next local edit.
return this.db
- .prepare("SELECT * FROM notes WHERE sync_status = 'pending' AND deleted_at IS NULL")
+ .prepare(
+ "SELECT * FROM notes WHERE sync_status IN ('pending', 'error') AND deleted_at IS NULL"
+ )
.all();
} catch (error) {
debugLogger.error("Error getting pending notes", { error: error.message }, "database");
@@ -3275,8 +3384,8 @@ class DatabaseManager {
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, space_id, participants, calendar_event_id,
- diarization_enabled, expected_speaker_count, sync_status, created_at, updated_at)
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'synced', ?, ?)
+ diarization_enabled, expected_speaker_count, updated_by_user_id, sync_status, created_at, updated_at)
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'synced', ?, ?)
ON CONFLICT(client_note_id) DO UPDATE SET
cloud_id = excluded.cloud_id,
title = excluded.title,
@@ -3291,6 +3400,7 @@ class DatabaseManager {
calendar_event_id = COALESCE(excluded.calendar_event_id, calendar_event_id),
diarization_enabled = COALESCE(excluded.diarization_enabled, diarization_enabled),
expected_speaker_count = COALESCE(excluded.expected_speaker_count, expected_speaker_count),
+ updated_by_user_id = COALESCE(excluded.updated_by_user_id, updated_by_user_id),
sync_status = 'synced',
left_team = 0,
updated_at = excluded.updated_at
@@ -3313,6 +3423,7 @@ class DatabaseManager {
cloudNote.calendar_event_id || null,
cloudNote.diarization_enabled ?? null,
cloudNote.expected_speaker_count ?? null,
+ cloudNote.updated_by_user_id || null,
cloudNote.created_at,
cloudNote.updated_at
);
@@ -3562,7 +3673,12 @@ class DatabaseManager {
// index idx_folders_space_name is a different conflict target than the
// client_folder_id upsert). Converge on the existing folder by adopting
// the cloud row's identity instead of wedging the pull.
- if (!err.message.includes("folders.space_id, folders.name")) throw err;
+ // Match the error code, not the message text (which SQLite could
+ // reformat); the column check keeps client_folder_id collisions on
+ // the rethrow path.
+ if (err.code !== "SQLITE_CONSTRAINT_UNIQUE" || !err.message.includes("folders.space_id")) {
+ throw err;
+ }
const existing = this.db
.prepare("SELECT id FROM folders WHERE space_id = ? AND name = ? AND deleted_at IS NULL")
.get(spaceId, cloudFolder.name);
diff --git a/src/helpers/ipcHandlers.js b/src/helpers/ipcHandlers.js
index 3d2835382..03caeb0bb 100644
--- a/src/helpers/ipcHandlers.js
+++ b/src/helpers/ipcHandlers.js
@@ -503,7 +503,9 @@ 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, { space_id: note.space_id }).catch(() => {});
+ vectorIndex
+ .upsertNote(note.id, text, { space_id: note.space_id, folder_id: note.folder_id ?? null })
+ .catch(() => {});
});
}
@@ -1222,6 +1224,10 @@ class IPCHandlers {
return this.databaseManager.getNotes(noteType, limit, folderId, spaceId);
});
+ ipcMain.handle("db-get-space-notes", async (event, spaceId, limit) => {
+ return this.databaseManager.getNotesForSpace(spaceId, limit);
+ });
+
ipcMain.handle("db-update-note", async (event, id, updates) => {
const result = this.databaseManager.updateNote(id, updates);
if (result?.success && result?.note) {
@@ -1237,26 +1243,34 @@ class IPCHandlers {
return this.deleteNoteInternal(id);
});
- ipcMain.handle("db-search-notes", async (event, query, limit, spaceId) => {
- return this.databaseManager.searchNotes(query, limit, spaceId);
+ ipcMain.handle("db-search-notes", async (event, query, limit, spaceId, folderId) => {
+ return this.databaseManager.searchNotes(query, limit, spaceId, folderId);
});
- ipcMain.handle("db-semantic-search-notes", async (event, query, limit = 5, spaceId) => {
+ ipcMain.handle("db-semantic-search-notes", async (event, query, limit = 5, spaceId, folderId) => {
const vectorIndex = require("./vectorIndex");
if (!vectorIndex.isReady()) {
- return this.databaseManager.searchNotes(query, limit, spaceId);
+ return this.databaseManager.searchNotes(query, limit, spaceId, folderId);
}
try {
+ // Folder scoping post-filters the vector leg by note-id set (existing
+ // Qdrant payloads only carry space_id), so over-fetch harder to
+ // compensate for discarded out-of-folder hits.
+ const scopedIds =
+ folderId != null ? new Set(this.databaseManager.getNoteIdsInFolder(folderId)) : null;
+ const overFetch = folderId != null ? limit * 4 : limit * 2;
const vectorFilter =
spaceId != null ? { must: [{ key: "space_id", match: { value: spaceId } }] } : undefined;
const [ftsResults, vectorResults] = await Promise.all([
- this.databaseManager.searchNotes(query, limit * 2, spaceId),
- vectorIndex.search(query, limit * 2, vectorFilter),
+ this.databaseManager.searchNotes(query, overFetch, spaceId, folderId),
+ vectorIndex.search(query, overFetch, vectorFilter),
]);
// Filter low-confidence semantic matches before RRF
- const filteredVectorResults = vectorResults.filter(({ score }) => score > 0.3);
+ const filteredVectorResults = vectorResults.filter(
+ ({ noteId, score }) => score > 0.3 && (!scopedIds || scopedIds.has(noteId))
+ );
// Reciprocal Rank Fusion (K=60, matching cloud implementation)
const scores = new Map();
@@ -1284,7 +1298,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, spaceId);
+ return this.databaseManager.searchNotes(query, limit, spaceId, folderId);
}
});
@@ -1389,16 +1403,6 @@ class IPCHandlers {
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) {
@@ -1460,14 +1464,24 @@ class IPCHandlers {
});
// Agent conversation handlers
- ipcMain.handle("db-create-agent-conversation", async (event, title, noteId) => {
- return this.databaseManager.createAgentConversation(title, noteId);
- });
+ ipcMain.handle(
+ "db-create-agent-conversation",
+ async (event, title, noteId, spaceId, folderId) => {
+ return this.databaseManager.createAgentConversation(title, noteId, spaceId, folderId);
+ }
+ );
ipcMain.handle("db-get-conversations-for-note", async (event, noteId, limit) => {
return this.databaseManager.getConversationsForNote(noteId, limit);
});
+ ipcMain.handle(
+ "db-get-conversations-for-container",
+ async (event, spaceId, folderId, limit) => {
+ return this.databaseManager.getConversationsForContainer(spaceId, folderId, limit);
+ }
+ );
+
ipcMain.handle("db-get-agent-conversations", async (event, limit) => {
return this.databaseManager.getAgentConversations(limit);
});
@@ -1575,7 +1589,10 @@ class IPCHandlers {
);
ipcMain.handle("db-upsert-note-from-cloud", (_, cloudNote, localFolderId, localSpaceId) => {
const note = this.databaseManager.upsertNoteFromCloud(cloudNote, localFolderId, localSpaceId);
- if (note) setImmediate(() => this.broadcastToWindows("note-synced", note));
+ if (note) {
+ setImmediate(() => this.broadcastToWindows("note-synced", note));
+ this._asyncVectorUpsert(note);
+ }
return note;
});
ipcMain.handle("db-mark-note-synced", (_, id, cloudId) =>
diff --git a/src/helpers/vectorIndex.js b/src/helpers/vectorIndex.js
index e24e7de04..4c0f0419f 100644
--- a/src/helpers/vectorIndex.js
+++ b/src/helpers/vectorIndex.js
@@ -94,7 +94,7 @@ class VectorIndex {
const points = batch.map((n, j) => ({
id: n.id,
vector: Array.from(vectors[j]),
- payload: { space_id: n.space_id },
+ payload: { space_id: n.space_id, folder_id: n.folder_id ?? null },
}));
await this.client.upsert(this.collectionName, { points });
} catch (err) {
diff --git a/src/hooks/useContainerChat.ts b/src/hooks/useContainerChat.ts
new file mode 100644
index 000000000..2dca919b7
--- /dev/null
+++ b/src/hooks/useContainerChat.ts
@@ -0,0 +1,145 @@
+import { useState, useCallback, useEffect, useMemo } from "react";
+import { useChatPersistence } from "../components/chat/useChatPersistence";
+import { useChatStreaming, type ChatSearchScope } from "../components/chat/useChatStreaming";
+import type { Message, AgentState } from "../components/chat/types";
+import type { SpaceItem, FolderItem, NoteItem } from "../types/electron";
+
+const MAX_CONTEXT_NOTES = 12;
+const NOTE_SNIPPET_LENGTH = 600;
+
+interface UseContainerChatOptions {
+ space: SpaceItem;
+ folder: FolderItem | null;
+ notes: NoteItem[];
+}
+
+interface ContainerConversationItem {
+ id: number;
+ title: string;
+ created_at: string;
+ updated_at: string;
+ message_count: number;
+}
+
+interface UseContainerChatReturn {
+ messages: Message[];
+ agentState: AgentState;
+ sendMessage: (text: string) => Promise<void>;
+ cancelStream: () => void;
+ conversations: ContainerConversationItem[];
+ activeConversationId: number | null;
+ switchConversation: (id: number) => Promise<void>;
+ startNewChat: () => void;
+}
+
+/**
+ * Chat scoped to a space or folder (container overview). The host component
+ * remounts per container (key prop), so this hook always starts with a fresh
+ * ask box; past container conversations are reachable via the picker.
+ */
+export function useContainerChat({
+ space,
+ folder,
+ notes,
+}: UseContainerChatOptions): UseContainerChatReturn {
+ const [conversationId, setConversationId] = useState<number | null>(null);
+ const [conversations, setConversations] = useState<ContainerConversationItem[]>([]);
+ const folderId = folder?.id ?? null;
+
+ const persistence = useChatPersistence({
+ onConversationCreated: (id) => setConversationId(id),
+ });
+
+ const containerContext = useMemo(() => {
+ const header = folder
+ ? `The user is viewing the folder "${folder.name}" in the space "${space.name}" (${notes.length} notes).`
+ : `The user is viewing the space "${space.name}" (${notes.length} notes).`;
+ const noteBlocks = notes.slice(0, MAX_CONTEXT_NOTES).map((note) => {
+ const body = (note.enhanced_content || note.content || "").slice(0, NOTE_SNIPPET_LENGTH);
+ return `<note id="${note.id}" title="${note.title}" updated="${note.updated_at}">\n${body}\n</note>`;
+ });
+ return [header, ...noteBlocks].join("\n\n");
+ }, [folder, space.name, notes]);
+
+ const searchScope = useMemo<ChatSearchScope>(
+ () => ({ spaceId: space.id, folderId }),
+ [space.id, folderId]
+ );
+
+ const streaming = useChatStreaming({
+ messages: persistence.messages,
+ setMessages: persistence.setMessages,
+ noteContext: containerContext,
+ searchScope,
+ onStreamComplete: (_id, content, toolCalls) => {
+ persistence.saveAssistantMessage(content, toolCalls);
+ },
+ });
+
+ const fetchConversations = useCallback(async () => {
+ const list = await window.electronAPI?.getConversationsForContainer?.(space.id, folderId);
+ setConversations(list ?? []);
+ }, [space.id, folderId]);
+
+ useEffect(() => {
+ let stale = false;
+ (async () => {
+ const list = await window.electronAPI?.getConversationsForContainer?.(space.id, folderId);
+ if (!stale) setConversations(list ?? []);
+ })();
+ return () => {
+ stale = true;
+ };
+ }, [space.id, folderId]);
+
+ const switchConversation = useCallback(
+ async (id: number) => {
+ await persistence.loadConversation(id);
+ setConversationId(id);
+ },
+ [persistence]
+ );
+
+ const startNewChat = useCallback(() => {
+ persistence.handleNewChat();
+ setConversationId(null);
+ }, [persistence]);
+
+ const sendMessage = useCallback(
+ async (text: string) => {
+ let convId = conversationId;
+ if (!convId) {
+ const title = folder?.name ?? space.name;
+ convId = await persistence.createConversation(title, null, {
+ spaceId: space.id,
+ folderId,
+ });
+ fetchConversations();
+ }
+
+ const userMsg: Message = {
+ id: crypto.randomUUID(),
+ role: "user",
+ content: text,
+ isStreaming: false,
+ };
+ persistence.setMessages((prev) => [...prev, userMsg]);
+ await persistence.saveUserMessage(text);
+
+ const allMessages = [...persistence.messages, userMsg];
+ await streaming.sendToAI(text, allMessages);
+ },
+ [conversationId, folder, folderId, space.id, space.name, persistence, streaming, fetchConversations]
+ );
+
+ return {
+ messages: persistence.messages,
+ agentState: streaming.agentState,
+ sendMessage,
+ cancelStream: streaming.cancelStream,
+ conversations,
+ activeConversationId: conversationId,
+ switchConversation,
+ startNewChat,
+ };
+}
diff --git a/src/hooks/useTeamRoster.ts b/src/hooks/useTeamRoster.ts
new file mode 100644
index 000000000..c035e0bf8
--- /dev/null
+++ b/src/hooks/useTeamRoster.ts
@@ -0,0 +1,41 @@
+import { useEffect, useState } from "react";
+import { TeamsService } from "../services/TeamsService";
+import type { TeamMember } from "../types/electron";
+
+// Rosters cached per team so repeated lookups (conflict attribution, note
+// authorship) don't refetch.
+const rosterCache = new Map<string, Promise<TeamMember[]>>();
+
+export function fetchTeamRoster(teamId: string): Promise<TeamMember[]> {
+ let roster = rosterCache.get(teamId);
+ if (!roster) {
+ roster = TeamsService.listMembers(teamId);
+ roster.catch(() => rosterCache.delete(teamId));
+ rosterCache.set(teamId, roster);
+ }
+ return roster;
+}
+
+export function useTeamRoster(teamId: string | null): Map<string, TeamMember> | null {
+ const [membersById, setMembersById] = useState<Map<string, TeamMember> | null>(null);
+
+ useEffect(() => {
+ if (!teamId) {
+ setMembersById(null);
+ return;
+ }
+ let stale = false;
+ fetchTeamRoster(teamId)
+ .then((members) => {
+ if (!stale) setMembersById(new Map(members.map((m) => [m.user_id, m])));
+ })
+ .catch(() => {
+ if (!stale) setMembersById(null);
+ });
+ return () => {
+ stale = true;
+ };
+ }, [teamId]);
+
+ return membersById;
+}
diff --git a/src/lib/containerOverviewIntro.ts b/src/lib/containerOverviewIntro.ts
new file mode 100644
index 000000000..724438c83
--- /dev/null
+++ b/src/lib/containerOverviewIntro.ts
@@ -0,0 +1,19 @@
+type IntroStorage = Pick<Storage, "getItem" | "setItem">;
+
+export const CONTAINER_OVERVIEW_INTRO_VERSION = 1;
+export const CONTAINER_OVERVIEW_INTRO_STORAGE_KEY = "containerOverviewIntroVersion";
+
+export function shouldShowContainerOverviewIntro(
+ storage: IntroStorage,
+ version: number = CONTAINER_OVERVIEW_INTRO_VERSION
+): boolean {
+ const seenVersion = Number(storage.getItem(CONTAINER_OVERVIEW_INTRO_STORAGE_KEY));
+ return !Number.isFinite(seenVersion) || seenVersion < version;
+}
+
+export function markContainerOverviewIntroSeen(
+ storage: IntroStorage,
+ version: number = CONTAINER_OVERVIEW_INTRO_VERSION
+): void {
+ storage.setItem(CONTAINER_OVERVIEW_INTRO_STORAGE_KEY, String(version));
+}
diff --git a/src/lib/noteConflictRegistry.ts b/src/lib/noteConflictRegistry.ts
new file mode 100644
index 000000000..8c3192aa3
--- /dev/null
+++ b/src/lib/noteConflictRegistry.ts
@@ -0,0 +1,27 @@
+// Client ids of notes with an unresolved pull conflict, persisted so the push
+// engine keeps honoring a conflict across restarts and windows (the banner's
+// CloudNote payload stays in-memory; the first pull after launch re-surfaces
+// it). Written only via the noteStore conflict setters.
+const KEY = "noteConflicts.clientIds";
+
+export function readNoteConflictIds(): Set<string> {
+ try {
+ const raw = localStorage.getItem(KEY);
+ return new Set(raw ? (JSON.parse(raw) as string[]) : []);
+ } catch {
+ return new Set();
+ }
+}
+
+export function addNoteConflictId(clientNoteId: string): void {
+ const ids = readNoteConflictIds();
+ if (ids.has(clientNoteId)) return;
+ ids.add(clientNoteId);
+ localStorage.setItem(KEY, JSON.stringify([...ids]));
+}
+
+export function removeNoteConflictId(clientNoteId: string): void {
+ const ids = readNoteConflictIds();
+ if (!ids.delete(clientNoteId)) return;
+ localStorage.setItem(KEY, JSON.stringify([...ids]));
+}
diff --git a/src/locales/de/translation.json b/src/locales/de/translation.json
index 85a3b534c..4622b265a 100644
--- a/src/locales/de/translation.json
+++ b/src/locales/de/translation.json
@@ -2746,6 +2746,44 @@
"othersInCall_one": "{{count}} weitere Person im Gespräch",
"othersInCall_other": "{{count}} weitere Personen im Gespräch"
}
+ },
+ "overview": {
+ "subtitle": {
+ "team": "Notizen sind für alle in diesem Space sichtbar.",
+ "private": "Nur du kannst diese Notizen sehen."
+ },
+ "meta": {
+ "folders_one": "{{count}} Ordner",
+ "folders_other": "{{count}} Ordner",
+ "members_one": "{{count}} Mitglied",
+ "members_other": "{{count}} Mitglieder"
+ },
+ "banner": {
+ "title": {
+ "team": "Dein Team-Space",
+ "private": "Dein privater Space"
+ },
+ "body": {
+ "team": "Teile Meeting-Notizen mit deinem Team. Füge Nutzerinterviews, Vertriebsgespräche und Team-Meetings hinzu, damit alle auf dem Laufenden bleiben.",
+ "private": "Bewahre Meeting-Notizen, Ideen und Entwürfe an einem Ort auf – und frag nach allem in diesem Space."
+ },
+ "dismiss": "Ausblenden"
+ },
+ "ask": {
+ "placeholder": "Frag etwas",
+ "chips": {
+ "catchUp": "Bring mich auf den neuesten Stand",
+ "keyDecisions": "Liste die wichtigsten Entscheidungen auf",
+ "inFlight": "Zeig laufende Projekte"
+ }
+ },
+ "invite": "Einladen",
+ "list": {
+ "empty": "Hier gibt es noch keine Notizen"
+ },
+ "author": {
+ "you": "Du"
+ }
}
},
"dictionary": {
diff --git a/src/locales/en/translation.json b/src/locales/en/translation.json
index 0a6423e7d..36def036d 100644
--- a/src/locales/en/translation.json
+++ b/src/locales/en/translation.json
@@ -2746,6 +2746,44 @@
"othersInCall_one": "{{count}} other in call",
"othersInCall_other": "{{count}} others in call"
}
+ },
+ "overview": {
+ "subtitle": {
+ "team": "Notes visible to everyone in this space.",
+ "private": "Only you can see these notes."
+ },
+ "meta": {
+ "folders_one": "{{count}} folder",
+ "folders_other": "{{count}} folders",
+ "members_one": "{{count}} member",
+ "members_other": "{{count}} members"
+ },
+ "banner": {
+ "title": {
+ "team": "Your team space",
+ "private": "Your private space"
+ },
+ "body": {
+ "team": "Share meeting notes with your team. Add user interviews, sales calls and team meetings so everyone stays in the loop.",
+ "private": "Keep meeting notes, ideas and drafts in one place — and ask about anything in this space."
+ },
+ "dismiss": "Dismiss"
+ },
+ "ask": {
+ "placeholder": "Ask anything",
+ "chips": {
+ "catchUp": "Catch me up",
+ "keyDecisions": "List key decisions",
+ "inFlight": "Show in flight projects"
+ }
+ },
+ "invite": "Invite",
+ "list": {
+ "empty": "No notes here yet"
+ },
+ "author": {
+ "you": "You"
+ }
}
},
"dictionary": {
diff --git a/src/locales/es/translation.json b/src/locales/es/translation.json
index 671c17bc9..e75c998cf 100644
--- a/src/locales/es/translation.json
+++ b/src/locales/es/translation.json
@@ -2586,6 +2586,44 @@
"othersInCall_one": "{{count}} otra persona en la llamada",
"othersInCall_other": "{{count}} otras personas en la llamada"
}
+ },
+ "overview": {
+ "subtitle": {
+ "team": "Notas visibles para todos en este espacio.",
+ "private": "Solo tú puedes ver estas notas."
+ },
+ "meta": {
+ "folders_one": "{{count}} carpeta",
+ "folders_other": "{{count}} carpetas",
+ "members_one": "{{count}} miembro",
+ "members_other": "{{count}} miembros"
+ },
+ "banner": {
+ "title": {
+ "team": "Tu espacio de equipo",
+ "private": "Tu espacio privado"
+ },
+ "body": {
+ "team": "Comparte notas de reuniones con tu equipo. Añade entrevistas con usuarios, llamadas de ventas y reuniones de equipo para que todos estén al día.",
+ "private": "Guarda notas de reuniones, ideas y borradores en un solo lugar, y pregunta sobre cualquier cosa de este espacio."
+ },
+ "dismiss": "Descartar"
+ },
+ "ask": {
+ "placeholder": "Pregunta lo que quieras",
+ "chips": {
+ "catchUp": "Ponme al día",
+ "keyDecisions": "Lista las decisiones clave",
+ "inFlight": "Muestra los proyectos en curso"
+ }
+ },
+ "invite": "Invitar",
+ "list": {
+ "empty": "Aún no hay notas aquí"
+ },
+ "author": {
+ "you": "Tú"
+ }
}
},
"dictionary": {
diff --git a/src/locales/fr/translation.json b/src/locales/fr/translation.json
index c8cd8b46f..4b48df9bd 100644
--- a/src/locales/fr/translation.json
+++ b/src/locales/fr/translation.json
@@ -2746,6 +2746,44 @@
"othersInCall_one": "{{count}} autre dans l'appel",
"othersInCall_other": "{{count}} autres dans l'appel"
}
+ },
+ "overview": {
+ "subtitle": {
+ "team": "Notes visibles par tout le monde dans cet espace.",
+ "private": "Vous seul pouvez voir ces notes."
+ },
+ "meta": {
+ "folders_one": "{{count}} dossier",
+ "folders_other": "{{count}} dossiers",
+ "members_one": "{{count}} membre",
+ "members_other": "{{count}} membres"
+ },
+ "banner": {
+ "title": {
+ "team": "Votre espace d'équipe",
+ "private": "Votre espace privé"
+ },
+ "body": {
+ "team": "Partagez vos notes de réunion avec votre équipe. Ajoutez des entretiens utilisateurs, des appels commerciaux et des réunions d'équipe pour que tout le monde reste informé.",
+ "private": "Regroupez notes de réunion, idées et brouillons au même endroit, et posez des questions sur tout ce que contient cet espace."
+ },
+ "dismiss": "Fermer"
+ },
+ "ask": {
+ "placeholder": "Posez une question",
+ "chips": {
+ "catchUp": "Résume-moi les nouveautés",
+ "keyDecisions": "Liste les décisions clés",
+ "inFlight": "Montre les projets en cours"
+ }
+ },
+ "invite": "Inviter",
+ "list": {
+ "empty": "Aucune note ici pour l'instant"
+ },
+ "author": {
+ "you": "Vous"
+ }
}
},
"dictionary": {
diff --git a/src/locales/it/translation.json b/src/locales/it/translation.json
index 2d66272c2..22772f07b 100644
--- a/src/locales/it/translation.json
+++ b/src/locales/it/translation.json
@@ -2538,6 +2538,44 @@
"othersInCall_one": "{{count}} altra persona in chiamata",
"othersInCall_other": "{{count}} altre persone in chiamata"
}
+ },
+ "overview": {
+ "subtitle": {
+ "team": "Note visibili a tutti in questo spazio.",
+ "private": "Solo tu puoi vedere queste note."
+ },
+ "meta": {
+ "folders_one": "{{count}} cartella",
+ "folders_other": "{{count}} cartelle",
+ "members_one": "{{count}} membro",
+ "members_other": "{{count}} membri"
+ },
+ "banner": {
+ "title": {
+ "team": "Il tuo spazio di team",
+ "private": "Il tuo spazio privato"
+ },
+ "body": {
+ "team": "Condividi le note delle riunioni con il tuo team. Aggiungi interviste agli utenti, chiamate di vendita e riunioni di team così tutti restano aggiornati.",
+ "private": "Tieni note delle riunioni, idee e bozze in un unico posto — e chiedi qualsiasi cosa su questo spazio."
+ },
+ "dismiss": "Chiudi"
+ },
+ "ask": {
+ "placeholder": "Chiedi qualsiasi cosa",
+ "chips": {
+ "catchUp": "Aggiornami",
+ "keyDecisions": "Elenca le decisioni chiave",
+ "inFlight": "Mostra i progetti in corso"
+ }
+ },
+ "invite": "Invita",
+ "list": {
+ "empty": "Ancora nessuna nota qui"
+ },
+ "author": {
+ "you": "Tu"
+ }
}
},
"dictionary": {
diff --git a/src/locales/ja/translation.json b/src/locales/ja/translation.json
index c6dd650e2..aef065164 100644
--- a/src/locales/ja/translation.json
+++ b/src/locales/ja/translation.json
@@ -2466,6 +2466,44 @@
"addContact": "連絡先を追加",
"save": "保存",
"cancel": "キャンセル"
+ },
+ "overview": {
+ "subtitle": {
+ "team": "このスペースの全員がノートを閲覧できます。",
+ "private": "このノートはあなただけが閲覧できます。"
+ },
+ "meta": {
+ "folders_one": "{{count}} 件のフォルダ",
+ "folders_other": "{{count}} 件のフォルダ",
+ "members_one": "{{count}} 人のメンバー",
+ "members_other": "{{count}} 人のメンバー"
+ },
+ "banner": {
+ "title": {
+ "team": "チームスペース",
+ "private": "プライベートスペース"
+ },
+ "body": {
+ "team": "会議のノートをチームと共有しましょう。ユーザーインタビュー、営業の通話、チームミーティングを追加して、全員が最新情報を把握できます。",
+ "private": "会議のノート、アイデア、下書きを一か所にまとめて、このスペースの内容について何でも質問できます。"
+ },
+ "dismiss": "閉じる"
+ },
+ "ask": {
+ "placeholder": "何でも質問",
+ "chips": {
+ "catchUp": "最新情報をまとめて",
+ "keyDecisions": "重要な決定事項を一覧に",
+ "inFlight": "進行中のプロジェクトを表示"
+ }
+ },
+ "invite": "招待",
+ "list": {
+ "empty": "まだノートがありません"
+ },
+ "author": {
+ "you": "自分"
+ }
}
},
"dictionary": {
diff --git a/src/locales/pt/translation.json b/src/locales/pt/translation.json
index fba41a692..f99dcff9b 100644
--- a/src/locales/pt/translation.json
+++ b/src/locales/pt/translation.json
@@ -2538,6 +2538,44 @@
"othersInCall_one": "{{count}} outra pessoa na chamada",
"othersInCall_other": "{{count}} outras pessoas na chamada"
}
+ },
+ "overview": {
+ "subtitle": {
+ "team": "Notas visíveis para todos neste espaço.",
+ "private": "Só você pode ver estas notas."
+ },
+ "meta": {
+ "folders_one": "{{count}} pasta",
+ "folders_other": "{{count}} pastas",
+ "members_one": "{{count}} membro",
+ "members_other": "{{count}} membros"
+ },
+ "banner": {
+ "title": {
+ "team": "Seu espaço de equipe",
+ "private": "Seu espaço privado"
+ },
+ "body": {
+ "team": "Compartilhe notas de reuniões com sua equipe. Adicione entrevistas com usuários, ligações de vendas e reuniões de equipe para que todos fiquem por dentro.",
+ "private": "Guarde notas de reuniões, ideias e rascunhos em um só lugar — e pergunte sobre qualquer coisa neste espaço."
+ },
+ "dismiss": "Dispensar"
+ },
+ "ask": {
+ "placeholder": "Pergunte qualquer coisa",
+ "chips": {
+ "catchUp": "Me atualize",
+ "keyDecisions": "Liste as decisões principais",
+ "inFlight": "Mostre os projetos em andamento"
+ }
+ },
+ "invite": "Convidar",
+ "list": {
+ "empty": "Ainda não há notas aqui"
+ },
+ "author": {
+ "you": "Você"
+ }
}
},
"dictionary": {
diff --git a/src/locales/ru/translation.json b/src/locales/ru/translation.json
index 9d84417ff..03495fa84 100644
--- a/src/locales/ru/translation.json
+++ b/src/locales/ru/translation.json
@@ -2548,6 +2548,48 @@
"othersInCall_many": "{{count}} собеседников в разговоре",
"othersInCall_other": "{{count}} собеседника в разговоре"
}
+ },
+ "overview": {
+ "subtitle": {
+ "team": "Заметки видны всем в этом пространстве.",
+ "private": "Эти заметки видите только вы."
+ },
+ "meta": {
+ "folders_one": "{{count}} папка",
+ "folders_few": "{{count}} папки",
+ "folders_many": "{{count}} папок",
+ "folders_other": "{{count}} папки",
+ "members_one": "{{count}} участник",
+ "members_few": "{{count}} участника",
+ "members_many": "{{count}} участников",
+ "members_other": "{{count}} участника"
+ },
+ "banner": {
+ "title": {
+ "team": "Ваше командное пространство",
+ "private": "Ваше личное пространство"
+ },
+ "body": {
+ "team": "Делитесь заметками со встреч с командой. Добавляйте интервью с пользователями, звонки по продажам и командные встречи, чтобы все были в курсе.",
+ "private": "Храните заметки со встреч, идеи и черновики в одном месте — и спрашивайте о чём угодно в этом пространстве."
+ },
+ "dismiss": "Скрыть"
+ },
+ "ask": {
+ "placeholder": "Спросите что угодно",
+ "chips": {
+ "catchUp": "Введи меня в курс дела",
+ "keyDecisions": "Перечисли ключевые решения",
+ "inFlight": "Покажи текущие проекты"
+ }
+ },
+ "invite": "Пригласить",
+ "list": {
+ "empty": "Здесь пока нет заметок"
+ },
+ "author": {
+ "you": "Вы"
+ }
}
},
"dictionary": {
diff --git a/src/locales/zh-CN/translation.json b/src/locales/zh-CN/translation.json
index e3efe71c3..53ceeab18 100644
--- a/src/locales/zh-CN/translation.json
+++ b/src/locales/zh-CN/translation.json
@@ -2538,6 +2538,44 @@
"othersInCall_one": "通话中还有 {{count}} 人",
"othersInCall_other": "通话中还有 {{count}} 人"
}
+ },
+ "overview": {
+ "subtitle": {
+ "team": "此空间中的所有成员都可以查看这些笔记。",
+ "private": "只有你可以查看这些笔记。"
+ },
+ "meta": {
+ "folders_one": "{{count}} 个文件夹",
+ "folders_other": "{{count}} 个文件夹",
+ "members_one": "{{count}} 位成员",
+ "members_other": "{{count}} 位成员"
+ },
+ "banner": {
+ "title": {
+ "team": "你的团队空间",
+ "private": "你的私人空间"
+ },
+ "body": {
+ "team": "与团队共享会议笔记。添加用户访谈、销售通话和团队会议,让所有人保持同步。",
+ "private": "将会议笔记、想法和草稿集中在一处,并随时询问此空间中的任何内容。"
+ },
+ "dismiss": "关闭"
+ },
+ "ask": {
+ "placeholder": "随便问点什么",
+ "chips": {
+ "catchUp": "帮我补上进展",
+ "keyDecisions": "列出关键决定",
+ "inFlight": "显示进行中的项目"
+ }
+ },
+ "invite": "邀请",
+ "list": {
+ "empty": "这里还没有笔记"
+ },
+ "author": {
+ "you": "你"
+ }
}
},
"dictionary": {
diff --git a/src/locales/zh-TW/translation.json b/src/locales/zh-TW/translation.json
index 0345c31ac..6599b0808 100644
--- a/src/locales/zh-TW/translation.json
+++ b/src/locales/zh-TW/translation.json
@@ -2538,6 +2538,44 @@
"othersInCall_one": "通話中還有 {{count}} 人",
"othersInCall_other": "通話中還有 {{count}} 人"
}
+ },
+ "overview": {
+ "subtitle": {
+ "team": "此空間中的所有成員都可以檢視這些筆記。",
+ "private": "只有你可以檢視這些筆記。"
+ },
+ "meta": {
+ "folders_one": "{{count}} 個資料夾",
+ "folders_other": "{{count}} 個資料夾",
+ "members_one": "{{count}} 位成員",
+ "members_other": "{{count}} 位成員"
+ },
+ "banner": {
+ "title": {
+ "team": "你的團隊空間",
+ "private": "你的私人空間"
+ },
+ "body": {
+ "team": "與團隊共享會議筆記。加入使用者訪談、銷售通話和團隊會議,讓所有人保持同步。",
+ "private": "將會議筆記、想法和草稿集中在一處,並隨時詢問此空間中的任何內容。"
+ },
+ "dismiss": "關閉"
+ },
+ "ask": {
+ "placeholder": "隨便問點什麼",
+ "chips": {
+ "catchUp": "幫我補上進度",
+ "keyDecisions": "列出關鍵決策",
+ "inFlight": "顯示進行中的專案"
+ }
+ },
+ "invite": "邀請",
+ "list": {
+ "empty": "這裡還沒有筆記"
+ },
+ "author": {
+ "you": "你"
+ }
}
},
"dictionary": {
diff --git a/src/services/SyncService.ts b/src/services/SyncService.ts
index 91293d5de..9300c599b 100644
--- a/src/services/SyncService.ts
+++ b/src/services/SyncService.ts
@@ -15,6 +15,7 @@ import { SnippetService, type CloudSnippetEntry } from "./SnippetService.js";
import { CloudApiError } from "./cloudApi.js";
import { notifyTeamSpacesCapabilityChanged } from "../lib/teamSpacesCapability";
import { subscribeIsSubscribed } from "../lib/subscriptionFlag";
+import { readNoteConflictIds } from "../lib/noteConflictRegistry";
function isHttpStatus(err: unknown, status: number): boolean {
return err instanceof CloudApiError && err.status === status;
@@ -87,6 +88,10 @@ function normalizeTimestamp(value: string | null | undefined): string {
// leave cannot hide a still-live team forever.
const PURGED_TEAM_GUARD_KEY = "purgedTeamIds";
const PURGED_TEAM_GUARD_TTL_MS = 15 * 60 * 1000;
+// Serializes the guard's read-modify-write across windows: a prune inside a
+// sync pass racing a leave/delete in another window must not drop the
+// just-written entry.
+const PURGED_TEAM_GUARD_LOCK = "openwhispr-purged-teams";
function readPurgedTeamIds(): Record<string, number> {
try {
@@ -103,18 +108,22 @@ function readPurgedTeamIds(): Record<string, number> {
// Call BEFORE purgeSpace, from every purge path (sync revocation, sign-out,
// and the UI's leave/delete-space flows).
-export function markTeamSpacePurged(cloudTeamId: string): void {
- localStorage.setItem(
- PURGED_TEAM_GUARD_KEY,
- JSON.stringify({ ...readPurgedTeamIds(), [cloudTeamId]: Date.now() })
- );
+export async function markTeamSpacePurged(cloudTeamId: string): Promise<void> {
+ await navigator.locks.request(PURGED_TEAM_GUARD_LOCK, () => {
+ localStorage.setItem(
+ PURGED_TEAM_GUARD_KEY,
+ JSON.stringify({ ...readPurgedTeamIds(), [cloudTeamId]: Date.now() })
+ );
+ });
}
-function prunePurgedTeamIds(liveCloudTeamIds: Set<string>): void {
- const kept = Object.fromEntries(
- Object.entries(readPurgedTeamIds()).filter(([id]) => liveCloudTeamIds.has(id))
- );
- localStorage.setItem(PURGED_TEAM_GUARD_KEY, JSON.stringify(kept));
+async function prunePurgedTeamIds(liveCloudTeamIds: Set<string>): Promise<void> {
+ await navigator.locks.request(PURGED_TEAM_GUARD_LOCK, () => {
+ const kept = Object.fromEntries(
+ Object.entries(readPurgedTeamIds()).filter(([id]) => liveCloudTeamIds.has(id))
+ );
+ localStorage.setItem(PURGED_TEAM_GUARD_KEY, JSON.stringify(kept));
+ });
}
class SyncService {
@@ -168,12 +177,26 @@ class SyncService {
// and backfills from scratch. Never throws — a failed purge must not block
// signing out.
async purgeTeamSpacesForSignOut(): Promise<void> {
+ // Wait for the sync lock: an in-flight pass (often in another window)
+ // still holds a pre-purge space map, and its remaining rows would
+ // re-insert team content after the purge — unreachable by any later
+ // cleanup once the guard entries below are gone.
+ try {
+ await navigator.locks.request(SYNC_ALL_LOCK, () => this.purgeAllTeamSpaces());
+ } catch (err) {
+ console.error("Sign-out purge could not take the sync lock:", err);
+ // Never block sign-out: purge unfenced rather than not at all.
+ await this.purgeAllTeamSpaces();
+ }
+ }
+
+ private async purgeAllTeamSpaces(): Promise<void> {
try {
const spaces = (await window.electronAPI.getSpaces?.()) ?? [];
for (const space of spaces) {
if (space.kind !== "team") continue;
try {
- if (space.cloud_team_id) markTeamSpacePurged(space.cloud_team_id);
+ if (space.cloud_team_id) await markTeamSpacePurged(space.cloud_team_id);
await window.electronAPI.purgeSpace?.(space.id);
} catch (err) {
console.error(`Purging space ${space.id} on sign-out failed:`, err);
@@ -634,16 +657,16 @@ class SyncService {
const cloudIds = new Set(teams.map((t) => t.id));
// Teams confirmed gone can no longer resurrect through pulls — their
// purge-race guard entries are done.
- prunePurgedTeamIds(cloudIds);
+ await prunePurgedTeamIds(cloudIds);
const prior = (await window.electronAPI.getSpaces?.()) ?? [];
- const backfillIds = await this.upsertTeamSpaces(teams, prior);
+ const backfillIds = await this.upsertTeamSpaces(teams);
for (const space of prior) {
if (space.kind !== "team" || !space.cloud_team_id || cloudIds.has(space.cloud_team_id)) {
continue;
}
- markTeamSpacePurged(space.cloud_team_id);
+ await markTeamSpacePurged(space.cloud_team_id);
const purged = await window.electronAPI.purgeSpace?.(space.id);
this.dispatchSpaceRevoked(space.name);
// Never-synced notes survive the purge in Personal (plan §10.6) —
@@ -675,24 +698,19 @@ class SyncService {
// Upserts cloud teams into local spaces. Returns local ids of spaces that
// still need a content backfill: brand new, or left 'pending' by a backfill
// that never finished.
- private async upsertTeamSpaces(teams: MyTeam[], prior: SpaceItem[]): Promise<number[]> {
- const priorByCloudId = new Map(
- prior.filter((s) => s.cloud_team_id).map((s) => [s.cloud_team_id!, s])
- );
+ private async upsertTeamSpaces(teams: MyTeam[]): Promise<number[]> {
const purged = readPurgedTeamIds();
const backfillIds: number[] = [];
for (const team of teams) {
// A purge racing this pass (leave/delete just clicked, or the server
// hasn't processed it yet) must not resurrect the space.
if (purged[team.id]) continue;
- const existing = priorByCloudId.get(team.id);
const space = await window.electronAPI.upsertSpaceFromCloud?.(
team as unknown as Record<string, unknown>
);
- if (space && (!existing || existing.sync_status === "pending")) {
- // The upsert marks rows synced; flag the space back to pending until
- // its content backfill completes.
- await window.electronAPI.setSpaceSyncStatus?.(space.id, "pending");
+ // New spaces insert as 'pending' and stay that way until their content
+ // backfill completes, so an interruption anywhere re-runs it.
+ if (space?.sync_status === "pending") {
backfillIds.push(space.id);
}
}
@@ -728,10 +746,9 @@ class SyncService {
ctx.refreshedSpaces = true;
try {
const teams = await TeamsService.myTeams();
- const prior = (await window.electronAPI.getSpaces?.()) ?? [];
// New spaces stay 'pending' so the next spaces pass backfills their
// pre-existing content (this delta pull only sees rows past the cursor).
- await this.upsertTeamSpaces(teams, prior);
+ await this.upsertTeamSpaces(teams);
} catch (err) {
console.error("Mid-pass spaces refresh failed:", err);
return null;
@@ -758,22 +775,28 @@ class SyncService {
}
// A push was rejected because the note's team is gone or access was revoked
- // (plan §7.2): a row already on the server stays the team's — drop the local
- // copy; a row that never reached the server is the only content the client
- // keeps — move it to the private space so the next push creates it as
- // personal.
+ // (plan §7.2). The server row (if any) stays the team's, but this pending
+ // row carries unpushed work — it is here because a push was attempted — so
+ // it survives as a personal note with a forked identity, exactly like the
+ // pull-side access_removed stub; never destroy the edits.
private async handleRevokedNotePush(note: NoteItem, ctx: SpaceSyncContext): Promise<void> {
const spaceName = ctx.byId.get(note.space_id)?.name ?? null;
- if (note.cloud_id) {
- await window.electronAPI.hardDeleteNote?.(note.id);
- this.dispatchSpaceRevoked(spaceName);
- } else if (ctx.privateSpace) {
- await window.electronAPI.updateNote(note.id, {
- space_id: ctx.privateSpace.id,
- folder_id: null,
- });
- this.dispatchNoteRelocated(note.title, spaceName);
+ if (!ctx.privateSpace) {
+ if (note.cloud_id) {
+ await window.electronAPI.hardDeleteNote?.(note.id);
+ this.dispatchSpaceRevoked(spaceName);
+ }
+ return;
}
+ // left_team rows already sit in the private space — fork in place.
+ const alreadyPrivate = note.space_id === ctx.privateSpace.id;
+ await window.electronAPI.updateNote(note.id, {
+ ...(alreadyPrivate ? {} : { space_id: ctx.privateSpace.id, folder_id: null }),
+ ...(note.cloud_id ? { client_note_id: crypto.randomUUID() } : {}),
+ cloud_id: null,
+ left_team: 0,
+ });
+ if (!alreadyPrivate) this.dispatchNoteRelocated(note.title, spaceName);
}
// Sync passes run in whichever window holds the web lock (often the always-
@@ -814,6 +837,9 @@ class SyncService {
if (!teamOnly) await this.adoptDefaultFolders();
await this.pushPendingFolders(teamOnly);
await this.pushFolderDeletes(teamOnly);
+ if (!teamOnly && this.teamCursorLagging("folders")) {
+ await this.pullFolders(true);
+ }
await this.pullFolders(teamOnly);
}
@@ -1030,6 +1056,8 @@ class SyncService {
if (cloudFolder.deleted_at) {
await window.electronAPI.hardDeleteFolder?.(local.id);
} else if (
+ // Pending rows are never overwritten by pull (D2), here too.
+ local.sync_status !== "pending" &&
normalizeTimestamp(cloudFolder.updated_at) > normalizeTimestamp(local.updated_at)
) {
await window.electronAPI.upsertFolderFromCloud?.(
@@ -1108,15 +1136,18 @@ class SyncService {
// A backfill snapshot never sees tombstones or stubs, and a dirty pass
// must re-see its parked/failed rows, so neither advances the cursors.
if (!snapshot && dirtyRows === 0) {
- // A degraded (own-rows-only) pull never saw team rows; advancing
- // would permanently skip teammate edits once the capability probe
- // recovers.
const hasTeamSpaces = [...ctx.byId.values()].some((s) => s.kind === "team");
if (teamCapable || !hasTeamSpaces) {
localStorage.setItem(cursorKey, syncStartedAt);
// Full pulls cover team rows too; keep the team cursor current so a
// later backup-off pass doesn't re-pull from the distant past.
if (!teamOnly) localStorage.setItem("lastSyncedAt.folders.team", syncStartedAt);
+ } else if (!teamOnly) {
+ // Degraded (own-rows-only) full pull: personal rows were fully
+ // covered, so the personal cursor may advance; the untouched .team
+ // cursor lets syncFolders' recovery pull catch up on teammate
+ // edits made during the outage.
+ localStorage.setItem(cursorKey, syncStartedAt);
}
}
return dirtyRows === 0;
@@ -1126,9 +1157,22 @@ class SyncService {
}
}
+ // The team cursor lags the personal one only when degraded passes advanced
+ // the personal cursor during a capability outage; the gap is exactly the
+ // teammate edits the recovery pull below must cover.
+ private teamCursorLagging(kind: "notes" | "folders"): boolean {
+ if (!this.canSyncTeamSpaces() || !this.hasTeamSpacesCapability()) return false;
+ const team = localStorage.getItem(`lastSyncedAt.${kind}.team`);
+ const full = localStorage.getItem(`lastSyncedAt.${kind}`);
+ return !!team && !!full && team < full;
+ }
+
private async syncNotes(teamOnly = false): Promise<void> {
await this.pushPendingNotes(teamOnly);
await this.pushNoteDeletes();
+ if (!teamOnly && this.teamCursorLagging("notes")) {
+ await this.pullNotes(true);
+ }
// A dirty pull left its cursors in place, so the next pass re-sees the
// parked rows — typically after syncSpaces has mirrored the missing team.
await this.pullNotes(teamOnly);
@@ -1141,8 +1185,15 @@ class SyncService {
const { localToCloud, blockedFolderIds } = await this.buildLocalToCloudFolderMap();
const ctx = await this.buildSpaceContext();
+ const conflicted = readNoteConflictIds();
const pushable: Array<{ note: NoteItem; scope: PushScopeFields }> = [];
for (const note of pending) {
+ if (conflicted.has(note.client_note_id)) {
+ // An unresolved pull conflict: pushing now would auto-resolve it as
+ // local-wins before the user chose Keep or Refresh (which clear the
+ // registry entry and unblock the row).
+ continue;
+ }
if (note.folder_id && blockedFolderIds.has(note.folder_id)) {
// The folder's own changes haven't landed (e.g. a cross-space move
// that 409'd on a name conflict): the server would reject the note's
@@ -1274,11 +1325,12 @@ class SyncService {
);
// Redacted stub: the note moved out of one of our teams. Clean local
- // copies are no longer ours to keep; dirty ones move to the private
- // space so unpushed work survives (plan §7.2).
+ // copies are no longer ours to keep; dirty ones ('pending' or
+ // 'error') move to the private space so unpushed work survives
+ // (plan §7.2).
if (cloudNote.access_removed) {
if (!local) continue;
- if (local.sync_status === "pending" && !local.deleted_at && ctx.privateSpace) {
+ if (local.sync_status !== "synced" && !local.deleted_at && ctx.privateSpace) {
// Already-private rows were just relocated by their folder's
// stub — keep their folder link, only fork identity: the server
// row now belongs to a scope we can't write, so pushing under
@@ -1312,8 +1364,16 @@ class SyncService {
} else if (
normalizeTimestamp(cloudNote.updated_at) > normalizeTimestamp(local.updated_at)
) {
- if (local.sync_status === "pending") {
+ // 'error' rows carry unpushed work just like 'pending' ones.
+ if (local.sync_status !== "synced") {
await this.surfaceNoteConflict(local.client_note_id, cloudNote);
+ } else if (cloudNote.folder_id && !cloudToLocal.has(cloudNote.folder_id)) {
+ // Filing to the fallback would stick (the advanced cursor
+ // never re-pulls this row) — park until the folder arrives.
+ dirtyRows++;
+ console.warn(
+ `Parking note ${cloudNote.id}: unknown folder ${cloudNote.folder_id}`
+ );
} else if (ctx.privateSpace) {
await window.electronAPI.upsertNoteFromCloud?.(
cloudNote as unknown as Record<string, unknown>,
@@ -1347,13 +1407,22 @@ class SyncService {
!local ||
normalizeTimestamp(cloudNote.updated_at) > normalizeTimestamp(local.updated_at)
) {
- if (local?.sync_status === "pending") {
- // A newer cloud copy over unpushed local edits: surface the
- // conflict to the editor banner instead of silently dropping
- // the local edit (plan §7.3).
+ if (local && local.sync_status !== "synced") {
+ // A newer cloud copy over unpushed local edits ('pending' or
+ // 'error'): surface the conflict to the editor banner instead
+ // of silently dropping the local edit (plan §7.3).
await this.surfaceNoteConflict(local.client_note_id, cloudNote);
continue;
}
+ if (cloudNote.folder_id && !cloudToLocal.has(cloudNote.folder_id)) {
+ // The note's folder isn't known locally yet (created moments
+ // ago, or its pull failed). Filing it to the fallback would
+ // stick — the advanced cursor never re-pulls the row — so park
+ // it like an unknown team until the folder arrives.
+ dirtyRows++;
+ console.warn(`Parking note ${cloudNote.id}: unknown folder ${cloudNote.folder_id}`);
+ continue;
+ }
await window.electronAPI.upsertNoteFromCloud?.(
cloudNote as unknown as Record<string, unknown>,
this.resolveLocalFolderId(cloudNote, space, cloudToLocal, defaultFolderId),
@@ -1380,15 +1449,18 @@ class SyncService {
// A backfill snapshot never sees tombstones or stubs, so it must not
// advance the delta cursors.
if (!snapshot && dirtyRows === 0) {
- // A degraded (own-rows-only) pull never saw team rows; advancing
- // would permanently skip teammate edits once the capability probe
- // recovers.
const hasTeamSpaces = [...ctx.byId.values()].some((s) => s.kind === "team");
if (teamCapable || !hasTeamSpaces) {
localStorage.setItem(cursorKey, syncStartedAt);
// Full pulls cover team rows too; keep the team cursor current so a
// later backup-off pass doesn't re-pull from the distant past.
if (!teamOnly) localStorage.setItem("lastSyncedAt.notes.team", syncStartedAt);
+ } else if (!teamOnly) {
+ // Degraded (own-rows-only) full pull: personal rows were fully
+ // covered, so the personal cursor may advance; the untouched .team
+ // cursor lets syncNotes' recovery pull catch up on teammate edits
+ // made during the outage.
+ localStorage.setItem(cursorKey, syncStartedAt);
}
}
return dirtyRows === 0;
diff --git a/src/services/teamSpaceActions.ts b/src/services/teamSpaceActions.ts
index cb9c04e76..3d4b780df 100644
--- a/src/services/teamSpaceActions.ts
+++ b/src/services/teamSpaceActions.ts
@@ -46,6 +46,9 @@ export async function createTeamSpace(
my_role: "admin",
member_count: memberIds.length - failedMembers,
})) ?? null;
+ // Cloud upserts insert as 'pending' (backfill marker); a team 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 };
@@ -79,7 +82,7 @@ export async function deleteTeamSpace(
return { success: false, error: errorMessage(err) };
}
// Park the team id so an in-flight pull can't resurrect purged rows.
- markTeamSpacePurged(space.cloud_team_id);
+ await markTeamSpacePurged(space.cloud_team_id);
}
// Store cleanup rides on the space-purged broadcast.
return purgeSpace(space.id);
@@ -102,7 +105,7 @@ export async function leaveTeamSpace(
const roster = await TeamsService.listMembers(teamId);
if (isImplicitAdmin || !roster.some((m) => m.user_id === userId)) return "implicit";
await TeamsService.removeMember(teamId, userId);
- markTeamSpacePurged(teamId);
+ await markTeamSpacePurged(teamId);
await purgeSpace(space.id);
return "left";
}
diff --git a/src/services/tools/index.ts b/src/services/tools/index.ts
index 296859a52..7c8f5c3b5 100644
--- a/src/services/tools/index.ts
+++ b/src/services/tools/index.ts
@@ -15,13 +15,15 @@ interface ToolRegistrySettings {
isSignedIn: boolean;
gcalConnected: boolean;
cloudBackupEnabled: boolean;
+ /** Pins search_notes to a container (overview chat); the LLM cannot widen it. */
+ searchScope?: { spaceId: number; folderId: number | null };
}
export function createToolRegistry(settings: ToolRegistrySettings): ToolRegistry {
const registry = new ToolRegistry();
const useCloudSearch = settings.isSignedIn && settings.cloudBackupEnabled;
- registry.register(createSearchNotesTool({ useCloudSearch }));
+ registry.register(createSearchNotesTool({ useCloudSearch, fixedScope: settings.searchScope }));
registry.register(getNoteTool);
registry.register(createNoteTool);
registry.register(updateNoteTool);
diff --git a/src/services/tools/searchNotesTool.ts b/src/services/tools/searchNotesTool.ts
index 64eaf5fe5..09dd29305 100644
--- a/src/services/tools/searchNotesTool.ts
+++ b/src/services/tools/searchNotesTool.ts
@@ -6,15 +6,27 @@ const MAX_CONTENT_LENGTH = 500;
interface SearchToolOptions {
useCloudSearch: boolean;
+ /** Pins every search to this container; the LLM's space arg is dropped. */
+ fixedScope?: { spaceId: number; folderId: number | null };
}
export function createSearchNotesTool(options: SearchToolOptions): ToolDefinition {
- const { useCloudSearch } = options;
+ const { useCloudSearch, fixedScope } = options;
+
+ const spaceParameter = fixedScope
+ ? {}
+ : {
+ space: {
+ type: "string",
+ description: "Space name to search within. Omit to search all accessible spaces.",
+ },
+ };
return {
name: "search_notes",
- description:
- "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.",
+ description: fixedScope
+ ? "Search the notes in the folder or space the user is currently viewing, using semantic search. Understands meaning and context, not just keywords. Returns matching notes with title, date, relevance score, space, 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: {
@@ -26,10 +38,7 @@ export function createSearchNotesTool(options: SearchToolOptions): ToolDefinitio
type: "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.",
- },
+ ...spaceParameter,
},
required: ["query"],
additionalProperties: false,
@@ -39,28 +48,38 @@ export function createSearchNotesTool(options: SearchToolOptions): ToolDefinitio
async 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 spaceName = fixedScope ? undefined : (args.space as string | undefined);
const spaces = (await window.electronAPI.getSpaces?.()) ?? [];
let space: SpaceItem | undefined;
- if (spaceName) {
+ if (fixedScope) {
+ space = spaces.find((s) => s.id === fixedScope.spaceId);
+ } else if (spaceName) {
const resolved = resolveSpace(spaces, spaceName);
if (resolved.error) {
return { success: false, data: null, displayText: resolved.error };
}
space = resolved.space;
}
+ const spaceId = fixedScope?.spaceId ?? space?.id ?? null;
+ const folderId = fixedScope?.folderId ?? null;
// 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.
+ // searches go straight to the local legs. Folder scoping is local-only:
+ // the cloud API has no folder filter, and a pinned scope whose space
+ // didn't resolve must not widen to an all-spaces cloud search.
const strategies: Array<() => Promise<ToolResult>> = [];
- const cloudCanScope = !space || space.kind === "private" || !!space.cloud_team_id;
- if (useCloudSearch && cloudCanScope) {
+ const cloudCanScope = fixedScope
+ ? !!space && (space.kind === "private" || !!space.cloud_team_id)
+ : !space || space.kind === "private" || !!space.cloud_team_id;
+ if (useCloudSearch && cloudCanScope && folderId == null) {
strategies.push(() => executeCloudSearch(query, limit, space, spaces));
}
- strategies.push(() => executeLocalSearch(query, limit, true, space, spaces));
- strategies.push(() => executeLocalSearch(query, limit, false, space, spaces));
+ strategies.push(() => executeLocalSearch(query, limit, true, space, spaces, spaceId, folderId));
+ strategies.push(() =>
+ executeLocalSearch(query, limit, false, space, spaces, spaceId, folderId)
+ );
for (let i = 0; i < strategies.length; i++) {
try {
@@ -97,12 +116,13 @@ async function executeLocalSearch(
limit: number,
semantic: boolean,
space: SpaceItem | undefined,
- spaces: SpaceItem[]
+ spaces: SpaceItem[],
+ spaceId: number | null,
+ folderId: number | null
): Promise<ToolResult> {
- const spaceId = space?.id ?? null;
const notes = semantic
- ? await window.electronAPI.semanticSearchNotes(query, limit, spaceId)
- : await window.electronAPI.searchNotes(query, limit, spaceId);
+ ? await window.electronAPI.semanticSearchNotes(query, limit, spaceId, folderId)
+ : await window.electronAPI.searchNotes(query, limit, spaceId, folderId);
const spaceNameById = new Map(spaces.map((s) => [s.id, s.name]));
const results = notes.map((note) => ({
diff --git a/src/stores/noteStore.ts b/src/stores/noteStore.ts
index 6c590503c..8a4faa4bc 100644
--- a/src/stores/noteStore.ts
+++ b/src/stores/noteStore.ts
@@ -1,5 +1,6 @@
import { create } from "zustand";
import { syncService } from "../services/SyncService.js";
+import { addNoteConflictId, removeNoteConflictId } from "../lib/noteConflictRegistry";
import { findDefaultFolder } from "../components/notes/shared";
import type { CloudNote } from "../services/NotesService.js";
import type {
@@ -574,6 +575,9 @@ function handleSpacePurged(spaceId: number): void {
(purgedTeamId == null || cloudNote.team_id !== purgedTeamId)
)
);
+ Object.keys(state.noteConflicts).forEach((clientId) => {
+ if (!(clientId in noteConflicts)) removeNoteConflictId(clientId);
+ });
const extra: Partial<NoteState> = {
spaces: state.spaces.filter((s) => s.id !== spaceId),
@@ -723,6 +727,9 @@ export function setActiveNoteId(id: number | null): void {
* initializeNotesTree resolves on mount.
*/
export function navigateToContainer(spaceId: number, folderId: number | null): void {
+ // Container jumps land on the overview; flows that open a note afterwards
+ // (e.g. CommandSearch note select) re-set activeNoteId themselves.
+ setActiveNoteId(null);
if (folderId != null) {
setActiveFolderId(folderId);
return;
@@ -871,11 +878,15 @@ export async function startMigration(): Promise<void> {
}
export function setNoteConflict(clientNoteId: string, cloudNote: CloudNote): void {
+ addNoteConflictId(clientNoteId);
const { noteConflicts } = useNoteStore.getState();
useNoteStore.setState({ noteConflicts: { ...noteConflicts, [clientNoteId]: cloudNote } });
}
export function clearNoteConflict(clientNoteId: string): void {
+ // Unblock the push gate even when the in-memory banner state is gone
+ // (e.g. cleared in another window or dropped by a restart).
+ removeNoteConflictId(clientNoteId);
const { noteConflicts } = useNoteStore.getState();
if (!(clientNoteId in noteConflicts)) return;
const next = { ...noteConflicts };
diff --git a/src/types/electron.ts b/src/types/electron.ts
index 6104f3b6a..960a9a649 100644
--- a/src/types/electron.ts
+++ b/src/types/electron.ts
@@ -62,6 +62,8 @@ export interface NoteItem {
cloud_id: string | null;
is_shared: number;
share_token: string | null;
+ // Last cloud editor; only populated on cloud pull (local edits don't set it).
+ updated_by_user_id?: string | null;
created_at: string;
updated_at: string;
client_note_id: string;
@@ -654,6 +656,7 @@ declare global {
folderId?: number | null,
spaceId?: number | null
) => Promise<NoteItem[]>;
+ getSpaceNotes: (spaceId: number, limit?: number) => Promise<NoteItem[]>;
updateNote: (
id: number,
updates: {
@@ -671,6 +674,7 @@ declare global {
expected_speaker_count?: number | null;
client_note_id?: string;
cloud_id?: string | null;
+ left_team?: number;
}
) => Promise<{ success: boolean; note?: NoteItem }>;
deleteNote: (id: number) => Promise<{ success: boolean }>;
@@ -683,11 +687,17 @@ 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, spaceId?: number | null) => Promise<NoteItem[]>;
+ searchNotes: (
+ query: string,
+ limit?: number,
+ spaceId?: number | null,
+ folderId?: number | null
+ ) => Promise<NoteItem[]>;
semanticSearchNotes: (
query: string,
limit?: number,
- spaceId?: number | null
+ spaceId?: number | null,
+ folderId?: number | null
) => Promise<NoteItem[]>;
semanticReindexAll: () => Promise<{ success: boolean; indexed?: number; error?: string }>;
onSemanticReindexProgress: (
@@ -728,7 +738,6 @@ declare global {
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[];
@@ -1575,11 +1584,15 @@ declare global {
saveAgentKey?: (key: string) => Promise<void>;
createAgentConversation?: (
title: string,
- noteId?: number
+ noteId?: number | null,
+ spaceId?: number | null,
+ folderId?: number | null
) => Promise<{
id: number;
title: string;
note_id?: number | null;
+ space_id?: number | null;
+ folder_id?: number | null;
created_at: string;
updated_at: string;
}>;
@@ -1595,6 +1608,19 @@ declare global {
message_count: number;
}>
>;
+ getConversationsForContainer?: (
+ spaceId: number,
+ folderId?: number | null,
+ limit?: number
+ ) => Promise<
+ Array<{
+ id: number;
+ title: string;
+ created_at: string;
+ updated_at: string;
+ message_count: number;
+ }>
+ >;
getAgentConversations?: (limit?: number) => Promise<
Array<{
id: number;
diff --git a/src/utils/dateFormatting.ts b/src/utils/dateFormatting.ts
index d3a535a8f..85504ed59 100644
--- a/src/utils/dateFormatting.ts
+++ b/src/utils/dateFormatting.ts
@@ -3,6 +3,12 @@ export function normalizeDbDate(dateStr: string): Date {
return new Date(source);
}
+export function formatShortDate(dateStr: string): string {
+ const date = normalizeDbDate(dateStr);
+ if (Number.isNaN(date.getTime())) return "";
+ return date.toLocaleDateString(undefined, { month: "short", day: "numeric" });
+}
+
export function formatRelativeTime(
dateStr: string,
t: (key: string, options?: Record<string, unknown>) => string
@@ -17,7 +23,7 @@ export function formatRelativeTime(
if (minutes < 60) return t("notes.list.minutesAgo", { count: minutes });
if (hours < 24) return t("notes.list.hoursAgo", { count: hours });
if (days < 7) return t("notes.list.daysAgo", { count: days });
- return date.toLocaleDateString(undefined, { month: "short", day: "numeric" });
+ return formatShortDate(dateStr);
}
export function formatUpcomingDateGroup(date: Date | string, t: (key: string) => string): string {
diff --git a/src/utils/dateGrouping.ts b/src/utils/dateGrouping.ts
new file mode 100644
index 000000000..833a03c97
--- /dev/null
+++ b/src/utils/dateGrouping.ts
@@ -0,0 +1,52 @@
+import { normalizeDbDate } from "./dateFormatting.ts";
+
+export interface DateGroup<T> {
+ label: string;
+ items: T[];
+}
+
+/**
+ * Buckets newest-first items into Today / Yesterday / Previous 7 days / Older
+ * groups, preserving item order within each group.
+ */
+export function groupItemsByDate<T>(
+ items: T[],
+ getDate: (item: T) => string,
+ t: (key: string) => string
+): Array<DateGroup<T>> {
+ if (items.length === 0) return [];
+
+ const now = new Date();
+ const today = new Date(now.getFullYear(), now.getMonth(), now.getDate());
+ const yesterday = new Date(today);
+ yesterday.setDate(yesterday.getDate() - 1);
+ const weekAgo = new Date(today);
+ weekAgo.setDate(weekAgo.getDate() - 7);
+
+ const groups: Array<DateGroup<T>> = [];
+ let current: DateGroup<T> | null = null;
+
+ for (const item of items) {
+ const date = normalizeDbDate(getDate(item));
+ const target = new Date(date.getFullYear(), date.getMonth(), date.getDate());
+
+ let label: string;
+ if (target.getTime() >= today.getTime()) {
+ label = t("chat.today");
+ } else if (target.getTime() >= yesterday.getTime()) {
+ label = t("chat.yesterday");
+ } else if (target.getTime() >= weekAgo.getTime()) {
+ label = t("chat.previousWeek");
+ } else {
+ label = t("chat.older");
+ }
+
+ if (!current || current.label !== label) {
+ current = { label, items: [] };
+ groups.push(current);
+ }
+ current.items.push(item);
+ }
+
+ return groups;
+}
diff --git a/test/helpers/containerConversationsDatabase.test.js b/test/helpers/containerConversationsDatabase.test.js
new file mode 100644
index 000000000..3c2fc137c
--- /dev/null
+++ b/test/helpers/containerConversationsDatabase.test.js
@@ -0,0 +1,222 @@
+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-container-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-container-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("container scope migration is idempotent across launches", (t) => {
+ const db = createDb(t);
+ if (!db) return;
+
+ const columns = db.db.pragma("table_info('agent_conversations')").map((col) => col.name);
+ assert.ok(columns.includes("space_id"));
+ assert.ok(columns.includes("folder_id"));
+
+ const noteColumns = db.db.pragma("table_info('notes')").map((col) => col.name);
+ assert.ok(noteColumns.includes("updated_by_user_id"));
+
+ db.db.close();
+
+ const db2 = new DatabaseManager();
+ const indexes = db2.db
+ .prepare(
+ "SELECT name FROM sqlite_master WHERE type = 'index' AND tbl_name = 'agent_conversations'"
+ )
+ .all()
+ .map((row) => row.name);
+ assert.ok(indexes.includes("idx_agent_conversations_container"));
+});
+
+test("createAgentConversation stores container scope", (t) => {
+ const db = createDb(t);
+ if (!db) return;
+ const space = db.createSpace({ name: "Eng" }).space;
+ const folder = db.createFolder("Docs", space.id).folder;
+
+ const folderConv = db.createAgentConversation("Docs", null, space.id, folder.id);
+ assert.equal(folderConv.space_id, space.id);
+ assert.equal(folderConv.folder_id, folder.id);
+
+ const spaceConv = db.createAgentConversation("Eng", null, space.id);
+ assert.equal(spaceConv.space_id, space.id);
+ assert.equal(spaceConv.folder_id, null);
+
+ const globalConv = db.createAgentConversation("Global");
+ assert.equal(globalConv.space_id, null);
+ assert.equal(globalConv.folder_id, null);
+ assert.equal(globalConv.note_id, null);
+});
+
+test("getConversationsForContainer separates folder and space-root scopes", (t) => {
+ const db = createDb(t);
+ if (!db) return;
+ const space = db.createSpace({ name: "Eng" }).space;
+ const folder = db.createFolder("Docs", space.id).folder;
+
+ const folderConv = db.createAgentConversation("Folder chat", null, space.id, folder.id);
+ const spaceConv = db.createAgentConversation("Space chat", null, space.id);
+ db.createAgentConversation("Global chat");
+ db.addAgentMessage(folderConv.id, "user", "hello");
+
+ const folderList = db.getConversationsForContainer(space.id, folder.id);
+ assert.equal(folderList.length, 1);
+ assert.equal(folderList[0].id, folderConv.id);
+ assert.equal(folderList[0].message_count, 1);
+
+ const spaceList = db.getConversationsForContainer(space.id, null);
+ assert.equal(spaceList.length, 1, "space root must exclude folder-scoped conversations");
+ assert.equal(spaceList[0].id, spaceConv.id);
+ assert.equal(spaceList[0].message_count, 0);
+});
+
+test("getConversationsForContainer excludes deleted conversations", (t) => {
+ const db = createDb(t);
+ if (!db) return;
+ const space = db.createSpace({ name: "Eng" }).space;
+
+ const conv = db.createAgentConversation("Doomed", null, space.id);
+ db.db
+ .prepare("UPDATE agent_conversations SET deleted_at = datetime('now') WHERE id = ?")
+ .run(conv.id);
+
+ assert.equal(db.getConversationsForContainer(space.id, null).length, 0);
+});
+
+test("searchNotes filters by folder", (t) => {
+ const db = createDb(t);
+ if (!db) return;
+ const space = db.createSpace({ name: "Eng" }).space;
+ const folder = db.createFolder("Docs", space.id).folder;
+
+ db.saveNote("Roadmap planning", "quarterly roadmap", "personal", null, null, folder.id, space.id);
+ db.saveNote("Roadmap ideas", "more roadmap", "personal", null, null, null, space.id);
+
+ const spaceHits = db.searchNotes("roadmap", 10, space.id);
+ assert.equal(spaceHits.length, 2);
+
+ const folderHits = db.searchNotes("roadmap", 10, space.id, folder.id);
+ assert.equal(folderHits.length, 1);
+ assert.equal(folderHits[0].folder_id, folder.id);
+});
+
+test("getNotesForSpace includes foldered notes, unlike the root-only getNotes", (t) => {
+ const db = createDb(t);
+ if (!db) return;
+ const space = db.createSpace({ name: "Eng" }).space;
+ const folder = db.createFolder("Docs", space.id).folder;
+
+ const rootNote = db.saveNote("Root", "", "personal", null, null, null, space.id).note;
+ const folderNote = db.saveNote("Foldered", "", "personal", null, null, folder.id, space.id).note;
+ db.deleteNote(folderNote.id);
+ const keptNote = db.saveNote("Kept", "", "personal", null, null, folder.id, space.id).note;
+
+ const rootOnly = db.getNotes(null, 50, null, space.id);
+ assert.deepEqual(
+ rootOnly.map((n) => n.id),
+ [rootNote.id]
+ );
+
+ const all = db.getNotesForSpace(space.id);
+ assert.deepEqual(new Set(all.map((n) => n.id)), new Set([rootNote.id, keptNote.id]));
+});
+
+test("getNoteIdsInFolder excludes deleted notes", (t) => {
+ const db = createDb(t);
+ if (!db) return;
+ const space = db.createSpace({ name: "Eng" }).space;
+ const folder = db.createFolder("Docs", space.id).folder;
+
+ const kept = db.saveNote("Kept", "", "personal", null, null, folder.id, space.id).note;
+ const removed = db.saveNote("Removed", "", "personal", null, null, folder.id, space.id).note;
+ db.deleteNote(removed.id);
+
+ assert.deepEqual(db.getNoteIdsInFolder(folder.id), [kept.id]);
+});
+
+test("upsertNoteFromCloud round-trips updated_by_user_id", (t) => {
+ const db = createDb(t);
+ if (!db) return;
+ const privateId = db.getPrivateSpaceId();
+
+ const cloudNote = {
+ id: "cloud-1",
+ client_note_id: "client-1",
+ title: "Synced",
+ content: "body",
+ updated_by_user_id: "user-a",
+ created_at: "2026-07-01 10:00:00",
+ updated_at: "2026-07-01 10:00:00",
+ };
+ const inserted = db.upsertNoteFromCloud(cloudNote, null, privateId);
+ assert.equal(inserted.updated_by_user_id, "user-a");
+
+ const updated = db.upsertNoteFromCloud(
+ { ...cloudNote, updated_by_user_id: "user-b", updated_at: "2026-07-02 10:00:00" },
+ null,
+ privateId
+ );
+ assert.equal(updated.updated_by_user_id, "user-b");
+
+ // A pull without the field must keep the last known editor.
+ const unchanged = db.upsertNoteFromCloud(
+ { ...cloudNote, updated_by_user_id: null, updated_at: "2026-07-03 10:00:00" },
+ null,
+ privateId
+ );
+ assert.equal(unchanged.updated_by_user_id, "user-b");
+});
diff --git a/test/helpers/containerOverviewIntro.test.js b/test/helpers/containerOverviewIntro.test.js
new file mode 100644
index 000000000..c352f1176
--- /dev/null
+++ b/test/helpers/containerOverviewIntro.test.js
@@ -0,0 +1,45 @@
+const test = require("node:test");
+const assert = require("node:assert/strict");
+
+const load = () => import("../../src/lib/containerOverviewIntro.ts");
+
+function memoryStorage(initial = {}) {
+ const values = new Map(Object.entries(initial));
+ return {
+ getItem: (key) => values.get(key) ?? null,
+ setItem: (key, value) => values.set(key, value),
+ };
+}
+
+test("container overview intro is shown until the current version is recorded", async () => {
+ const {
+ CONTAINER_OVERVIEW_INTRO_STORAGE_KEY,
+ CONTAINER_OVERVIEW_INTRO_VERSION,
+ markContainerOverviewIntroSeen,
+ shouldShowContainerOverviewIntro,
+ } = await load();
+ const storage = memoryStorage();
+
+ assert.equal(shouldShowContainerOverviewIntro(storage), true);
+ markContainerOverviewIntroSeen(storage);
+ assert.equal(
+ storage.getItem(CONTAINER_OVERVIEW_INTRO_STORAGE_KEY),
+ String(CONTAINER_OVERVIEW_INTRO_VERSION)
+ );
+ assert.equal(shouldShowContainerOverviewIntro(storage), false);
+});
+
+test("a version bump reopens the container overview intro", async () => {
+ const { CONTAINER_OVERVIEW_INTRO_STORAGE_KEY, shouldShowContainerOverviewIntro } = await load();
+ const storage = memoryStorage({ [CONTAINER_OVERVIEW_INTRO_STORAGE_KEY]: "1" });
+
+ assert.equal(shouldShowContainerOverviewIntro(storage, 1), false);
+ assert.equal(shouldShowContainerOverviewIntro(storage, 2), true);
+});
+
+test("malformed stored versions do not suppress the intro", async () => {
+ const { CONTAINER_OVERVIEW_INTRO_STORAGE_KEY, shouldShowContainerOverviewIntro } = await load();
+ const storage = memoryStorage({ [CONTAINER_OVERVIEW_INTRO_STORAGE_KEY]: "not-a-number" });
+
+ assert.equal(shouldShowContainerOverviewIntro(storage), true);
+});
diff --git a/test/helpers/spacesDatabase.test.js b/test/helpers/spacesDatabase.test.js
index da6a47596..f5db76ecc 100644
--- a/test/helpers/spacesDatabase.test.js
+++ b/test/helpers/spacesDatabase.test.js
@@ -824,3 +824,121 @@ test("folders rebuild succeeds on a legacy DB with notes referencing folders", (
);
db.db.close();
});
+
+test("purgeSpace preserves dirty cloud-backed notes with forked identities", (t) => {
+ const db = createDb(t);
+ if (!db) return;
+ const privateId = db.getPrivateSpaceId();
+ const team = db.createSpace({ name: "Revoked" }).space;
+ const folder = db.createFolder("Ops", team.id).folder;
+
+ const dirty = db.saveNote(
+ "Edited offline",
+ "walrus intel",
+ "personal",
+ null,
+ null,
+ folder.id
+ ).note;
+ db.markNoteSynced(dirty.id, "cloud-dirty-note");
+ db.updateNote(dirty.id, { content: "walrus intel v2" });
+ const errored = db.saveNote(
+ "Errored push",
+ "narwhal notes",
+ "personal",
+ null,
+ null,
+ folder.id
+ ).note;
+ db.markNoteSynced(errored.id, "cloud-error-note");
+ db.updateNote(errored.id, { content: "narwhal v2" });
+ db.markNoteSyncError(errored.id);
+ const clean = db.saveNote("Clean", "synced beluga", "personal", null, null, folder.id).note;
+ db.markNoteSynced(clean.id, "cloud-clean-note");
+ const before = { dirty: db.getNote(dirty.id), errored: db.getNote(errored.id) };
+
+ const result = db.purgeSpace(team.id);
+ assert.ok(result.success);
+ assert.equal(result.relocatedCount, 2);
+
+ // Unpushed edits ('pending' and 'error') survive in the private space as
+ // forked personal notes; only the clean server-owned copy is destroyed.
+ for (const [id, prior] of [
+ [dirty.id, before.dirty],
+ [errored.id, before.errored],
+ ]) {
+ const relocated = db.getNote(id);
+ assert.equal(relocated.space_id, privateId);
+ assert.equal(relocated.folder_id, null);
+ assert.equal(relocated.cloud_id, null);
+ assert.equal(relocated.sync_status, "pending");
+ assert.equal(relocated.left_team, 0);
+ assert.notEqual(relocated.client_note_id, prior.client_note_id);
+ }
+ const count = (sql, ...args) => db.db.prepare(sql).get(...args).count;
+ assert.equal(count("SELECT COUNT(*) as count FROM notes WHERE id = ?", clean.id), 0);
+});
+
+test("purgeSpace survives tombstones in other spaces referencing its folders", (t) => {
+ const db = createDb(t);
+ if (!db) return;
+ const privateId = db.getPrivateSpaceId();
+ const team = db.createSpace({ name: "Movers" }).space;
+
+ // Deleting a note keeps folder_id on the tombstone; moving the folder into
+ // the team afterwards leaves a cross-space reference that must not abort
+ // the purge on the notes→folders FK.
+ const folder = db.createFolder("Shared docs", privateId).folder;
+ const note = db.saveNote("Doomed", "tombstone gazelle", "personal", null, null, folder.id).note;
+ db.markNoteSynced(note.id, "cloud-tombstone-note");
+ db.deleteNote(note.id);
+ db.moveFolderToSpace(folder.id, team.id);
+
+ const result = db.purgeSpace(team.id);
+ assert.ok(result.success);
+
+ const tombstone = db.db.prepare("SELECT * FROM notes WHERE id = ?").get(note.id);
+ assert.ok(tombstone.deleted_at, "the tombstone survives — its cloud delete still has to push");
+ assert.equal(tombstone.folder_id, null);
+ assert.ok(db.getPendingNoteDeletes().some((n) => n.id === note.id));
+ const count = (sql, ...args) => db.db.prepare(sql).get(...args).count;
+ 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);
+});
+
+test("getPendingNotes includes error rows so failed pushes retry", (t) => {
+ const db = createDb(t);
+ if (!db) return;
+ const note = db.saveNote("Retry me", "flaky ferret").note;
+ db.markNoteSyncError(note.id);
+
+ assert.ok(db.getPendingNotes().some((n) => n.id === note.id));
+ assert.ok(db.getPendingNotes("private").some((n) => n.id === note.id));
+});
+
+test("upsertSpaceFromCloud inserts as pending and never flips status on update", (t) => {
+ const db = createDb(t);
+ if (!db) return;
+ const team = db.upsertSpaceFromCloud({ id: "team-1", name: "Cloud team", workspace_id: "ws-1" });
+ assert.equal(team.sync_status, "pending", "new spaces need a content backfill");
+
+ // A second mirror pass before the backfill completes must not settle it.
+ const again = db.upsertSpaceFromCloud({ id: "team-1", name: "Renamed" });
+ assert.equal(again.sync_status, "pending");
+
+ db.setSpaceSyncStatus(team.id, "synced");
+ const after = db.upsertSpaceFromCloud({ id: "team-1", name: "Renamed again" });
+ assert.equal(after.sync_status, "synced");
+});
+
+test("createSpace refuses non-team kinds so the private space stays unique", (t) => {
+ const db = createDb(t);
+ if (!db) return;
+ const result = db.createSpace({ name: "Sneaky", kind: "private" });
+ assert.equal(result.success, false);
+
+ const privateCount = db.db
+ .prepare("SELECT COUNT(*) as count FROM spaces WHERE kind = 'private'")
+ .get().count;
+ assert.equal(privateCount, 1);
+});
diff --git a/test/utils/dateGrouping.test.js b/test/utils/dateGrouping.test.js
new file mode 100644
index 000000000..3fed1de95
--- /dev/null
+++ b/test/utils/dateGrouping.test.js
@@ -0,0 +1,83 @@
+const test = require("node:test");
+const assert = require("node:assert/strict");
+
+// Requires Node's native TypeScript type-stripping (Node >= 22.6 with
+// --experimental-strip-types, on by default in Node 23.6+/24). CI runs Node 24.
+
+const load = () => import("../../src/utils/dateGrouping.ts");
+
+const t = (key) =>
+ ({
+ "chat.today": "Today",
+ "chat.yesterday": "Yesterday",
+ "chat.previousWeek": "Previous 7 days",
+ "chat.older": "Older",
+ })[key] || key;
+
+// Local-time constructors keep these assertions timezone-independent.
+const NOON_JUNE_15 = new Date(2024, 5, 15, 12, 0, 0).getTime();
+
+function localDbDate(year, month, day, hour) {
+ // normalizeDbDate treats zoneless SQLite timestamps as UTC, so emit UTC.
+ return new Date(Date.UTC(year, month, day, hour)).toISOString().replace("T", " ").slice(0, 19);
+}
+
+test("groups newest-first items into calendar buckets in order", async (t2) => {
+ const { groupItemsByDate } = await load();
+ t2.mock.timers.enable({ apis: ["Date"], now: NOON_JUNE_15 });
+
+ const items = [
+ { id: 1, updated_at: "2024-06-15T10:00:00Z" },
+ { id: 2, updated_at: "2024-06-15T08:00:00Z" },
+ { id: 3, updated_at: "2024-06-14T22:00:00Z" },
+ { id: 4, updated_at: "2024-06-10T12:00:00Z" },
+ { id: 5, updated_at: "2024-01-01T12:00:00Z" },
+ ];
+ const groups = groupItemsByDate(items, (i) => i.updated_at, t);
+
+ assert.deepEqual(
+ groups.map((g) => g.label),
+ ["Today", "Yesterday", "Previous 7 days", "Older"]
+ );
+ assert.deepEqual(
+ groups.map((g) => g.items.map((i) => i.id)),
+ [[1, 2], [3], [4], [5]]
+ );
+});
+
+test("boundary days land in the nearest bucket", async (t2) => {
+ const { groupItemsByDate } = await load();
+ t2.mock.timers.enable({ apis: ["Date"], now: NOON_JUNE_15 });
+
+ const items = [
+ // Exactly 7 days back is still "Previous 7 days"; 8 days back is "Older".
+ { id: 1, updated_at: localDbDate(2024, 5, 8, 12) },
+ { id: 2, updated_at: localDbDate(2024, 5, 7, 12) },
+ ];
+ const groups = groupItemsByDate(items, (i) => i.updated_at, t);
+ assert.deepEqual(
+ groups.map((g) => g.label),
+ ["Previous 7 days", "Older"]
+ );
+});
+
+test("empty input yields no groups", async () => {
+ const { groupItemsByDate } = await load();
+ assert.deepEqual(groupItemsByDate([], () => "", t), []);
+});
+
+test("SQLite zoneless timestamps are grouped like their UTC instant", async (t2) => {
+ const { groupItemsByDate } = await load();
+ t2.mock.timers.enable({ apis: ["Date"], now: NOON_JUNE_15 });
+
+ const utcNow = new Date();
+ const todayDb = localDbDate(
+ utcNow.getUTCFullYear(),
+ utcNow.getUTCMonth(),
+ utcNow.getUTCDate(),
+ utcNow.getUTCHours()
+ );
+ const groups = groupItemsByDate([{ updated_at: todayDb }], (i) => i.updated_at, t);
+ assert.equal(groups.length, 1);
+ assert.equal(groups[0].label, "Today");
+});