Skip to content

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

fix: cleanup duplicate code for syncing, chats and filtering

Chadpiha959c4840f2f0
diff --git a/src/components/AgentOverlay.tsx b/src/components/AgentOverlay.tsx
index c9de69c65..8c24a0660 100644
--- a/src/components/AgentOverlay.tsx
+++ b/src/components/AgentOverlay.tsx
@@ -7,7 +7,7 @@ import { AgentInput } from "./agent/AgentInput";
import AudioManager from "../helpers/audioManager";
import { useChatPersistence } from "./chat/useChatPersistence";
import { useChatStreaming } from "./chat/useChatStreaming";
-import type { Message } from "./chat/types";
+import { useChatMessageSender } from "./chat/useChatMessageSender";
const MIN_HEIGHT = 200;
const MIN_WIDTH = 360;
@@ -45,32 +45,38 @@ export default function AgentOverlay() {
[setMessages]
);
+ const createConversation = useCallback(
+ () => persistence.createConversation(t("agentMode.titleBar.newChat")),
+ [persistence, t]
+ );
+ const updateFirstMessageTitle = useCallback(
+ ({
+ conversationId,
+ text,
+ isFirstMessage,
+ }: {
+ conversationId: number;
+ text: string;
+ isFirstMessage: boolean;
+ }) => {
+ if (!isFirstMessage) return;
+ const title = text.slice(0, 50) + (text.length > 50 ? "..." : "");
+ window.electronAPI?.updateAgentConversationTitle?.(conversationId, title);
+ },
+ []
+ );
+ const sendMessage = useChatMessageSender({
+ conversationId: persistence.conversationId,
+ persistence,
+ streaming,
+ createConversation,
+ onMessagePersisted: updateFirstMessageTitle,
+ });
const handleTranscriptionComplete = useCallback(
async (text: string) => {
- if (!text.trim()) return;
-
- if (!persistence.conversationId) {
- await persistence.createConversation(t("agentMode.titleBar.newChat"));
- }
-
- const userMsg: Message = {
- id: crypto.randomUUID(),
- role: "user",
- content: text,
- isStreaming: false,
- };
- setMessages((prev) => [...prev, userMsg]);
-
- await persistence.saveUserMessage(text);
-
- if (persistence.conversationId && messages.length === 0) {
- const title = text.slice(0, 50) + (text.length > 50 ? "..." : "");
- window.electronAPI?.updateAgentConversationTitle?.(persistence.conversationId, title);
- }
-
- await streaming.sendToAI(text, [...messages, userMsg]);
+ if (text.trim()) await sendMessage(text);
},
- [t, messages, setMessages, persistence, streaming]
+ [sendMessage]
);
useEffect(() => {
diff --git a/src/components/CreateTeamDialog.tsx b/src/components/CreateTeamDialog.tsx
index 57d062d3c..f7e0444e9 100644
--- a/src/components/CreateTeamDialog.tsx
+++ b/src/components/CreateTeamDialog.tsx
@@ -58,14 +58,6 @@ export default function CreateTeamDialog({
() => (rosterLoaded ? orderMemberCandidates(roster, user?.id) : []),
[roster, rosterLoaded, user?.id]
);
- const filteredCandidates = useMemo(() => {
- const query = memberSearch.trim().toLowerCase();
- if (!query) return candidates;
- return candidates.filter(
- (m) => (m.name ?? "").toLowerCase().includes(query) || m.email.toLowerCase().includes(query)
- );
- }, [candidates, memberSearch]);
-
const handleOpenChange = (nextOpen: boolean) => {
onOpenChange(nextOpen);
if (!nextOpen) {
@@ -171,7 +163,7 @@ export default function CreateTeamDialog({
<div className="h-24 rounded bg-foreground/5 dark:bg-white/5 animate-pulse" />
) : (
<MemberPickList
- members={filteredCandidates}
+ members={candidates}
search={memberSearch}
onSearchChange={setMemberSearch}
onSelect={toggleMember}
diff --git a/src/components/MemberPickList.tsx b/src/components/MemberPickList.tsx
index 35562e0c3..55d8f575e 100644
--- a/src/components/MemberPickList.tsx
+++ b/src/components/MemberPickList.tsx
@@ -1,7 +1,9 @@
+import { useMemo } from "react";
import { useTranslation } from "react-i18next";
import { Check, Loader2, Search } from "lucide-react";
import MemberAvatar from "./MemberAvatar";
import { cn } from "./lib/utils";
+import { filterMemberCandidates } from "../lib/memberCandidates";
import type { WorkspaceMember } from "../types/electron";
interface MemberPickListProps {
@@ -33,6 +35,7 @@ export default function MemberPickList({
footer,
}: MemberPickListProps) {
const { t } = useTranslation();
+ const filteredMembers = useMemo(() => filterMemberCandidates(members, search), [members, search]);
return (
<div className="rounded border border-border/70 dark:border-border-subtle/50 overflow-hidden">
<div className="relative border-b border-border/40 dark:border-border-subtle/40">
@@ -48,7 +51,7 @@ export default function MemberPickList({
/>
</div>
<div className={cn("overflow-y-auto p-1", listClassName ?? "max-h-36")}>
- {members.map((member) => {
+ {filteredMembers.map((member) => {
const isSelected = selectedIds?.has(member.user_id) ?? false;
const isBusy = busyIds?.has(member.user_id) ?? false;
return (
@@ -82,12 +85,12 @@ export default function MemberPickList({
</button>
);
})}
- {members.length === 0 && !footer && (
+ {filteredMembers.length === 0 && !footer && (
<p className="text-xs text-foreground/25 text-center py-2">
{t("notes.context.noResults")}
</p>
)}
- {footer}
+ {filteredMembers.length === 0 && footer}
</div>
</div>
);
diff --git a/src/components/TeamRosterSection.tsx b/src/components/TeamRosterSection.tsx
index 3a1cdfb58..888e02cd0 100644
--- a/src/components/TeamRosterSection.tsx
+++ b/src/components/TeamRosterSection.tsx
@@ -109,23 +109,19 @@ export default function TeamRosterSection({
};
const memberIds = useMemo(() => new Set(members.map((m) => m.user_id)), [members]);
- const addCandidates = useMemo(() => {
- const query = addSearch.trim().toLowerCase();
- const matches = workspaceMembers.filter(
- (m) =>
- !memberIds.has(m.user_id) &&
- (!query ||
- (m.name ?? "").toLowerCase().includes(query) ||
- m.email.toLowerCase().includes(query))
- );
- return orderMemberCandidates(matches, currentUserId);
- }, [workspaceMembers, memberIds, addSearch, currentUserId]);
+ const addCandidates = useMemo(
+ () =>
+ orderMemberCandidates(
+ workspaceMembers.filter((member) => !memberIds.has(member.user_id)),
+ currentUserId
+ ),
+ [workspaceMembers, memberIds, currentUserId]
+ );
const searchEmail = addSearch.trim().toLowerCase();
const showInviteFooter =
!!onInvite &&
searchEmail.includes("@") &&
- addCandidates.length === 0 &&
!members.some((m) => m.email.toLowerCase() === searchEmail) &&
!workspaceMembers.some((m) => m.email.toLowerCase() === searchEmail);
diff --git a/src/components/chat/ChatView.tsx b/src/components/chat/ChatView.tsx
index b5158dfb9..26684eab2 100644
--- a/src/components/chat/ChatView.tsx
+++ b/src/components/chat/ChatView.tsx
@@ -2,6 +2,7 @@ import { useState, useCallback, useEffect, lazy, Suspense } from "react";
import { useTranslation } from "react-i18next";
import { useChatPersistence } from "./useChatPersistence";
import { useChatStreaming } from "./useChatStreaming";
+import { useChatMessageSender } from "./useChatMessageSender";
import { ChatMessages } from "./ChatMessages";
import { ChatInput } from "./ChatInput";
import { ChatEmptyIllustration } from "./ChatEmptyIllustration";
@@ -67,29 +68,21 @@ export default function ChatView() {
persistence.handleNewChat();
}, [persistence]);
- const handleTextSubmit = useCallback(
+ const createConversation = useCallback(
async (text: string) => {
- setIsNewChat(false);
- let convId = activeConversationId;
- if (!convId) {
- const title = text.length > 50 ? `${text.slice(0, 50)}...` : text;
- convId = await persistence.createConversation(title);
- }
-
- const userMsg = {
- id: crypto.randomUUID(),
- role: "user" as const,
- content: text,
- isStreaming: false,
- };
- persistence.setMessages((prev) => [...prev, userMsg]);
- await persistence.saveUserMessage(text);
-
- const allMessages = [...persistence.messages, userMsg];
- await streaming.sendToAI(text, allMessages);
+ const title = text.length > 50 ? `${text.slice(0, 50)}...` : text;
+ return persistence.createConversation(title);
},
- [activeConversationId, persistence, streaming]
+ [persistence]
);
+ const markChatStarted = useCallback(() => setIsNewChat(false), []);
+ const handleTextSubmit = useChatMessageSender({
+ conversationId: activeConversationId,
+ persistence,
+ streaming,
+ createConversation,
+ onBeforeSend: markChatStarted,
+ });
const handleArchive = useCallback(
async (id: number) => {
diff --git a/src/components/chat/useChatMessageSender.ts b/src/components/chat/useChatMessageSender.ts
new file mode 100644
index 000000000..9358c1495
--- /dev/null
+++ b/src/components/chat/useChatMessageSender.ts
@@ -0,0 +1,52 @@
+import { useCallback } from "react";
+import type { ChatPersistence } from "./useChatPersistence";
+import type { ChatStreaming } from "./useChatStreaming";
+import type { Message } from "./types";
+
+interface PersistedMessageContext {
+ conversationId: number;
+ text: string;
+ isFirstMessage: boolean;
+}
+
+interface UseChatMessageSenderOptions {
+ conversationId: number | null;
+ persistence: ChatPersistence;
+ streaming: Pick<ChatStreaming, "sendToAI">;
+ createConversation: (text: string) => Promise<number>;
+ onBeforeSend?: () => void;
+ onMessagePersisted?: (context: PersistedMessageContext) => void | Promise<void>;
+}
+
+export function useChatMessageSender({
+ conversationId,
+ persistence,
+ streaming,
+ createConversation,
+ onBeforeSend,
+ onMessagePersisted,
+}: UseChatMessageSenderOptions): (text: string) => Promise<void> {
+ return useCallback(
+ async (text: string) => {
+ onBeforeSend?.();
+ const convId = conversationId ?? (await createConversation(text));
+ const previousMessages = persistence.messages;
+ const userMessage: Message = {
+ id: crypto.randomUUID(),
+ role: "user",
+ content: text,
+ isStreaming: false,
+ };
+
+ persistence.setMessages((messages) => [...messages, userMessage]);
+ await persistence.saveUserMessage(text);
+ await onMessagePersisted?.({
+ conversationId: convId,
+ text,
+ isFirstMessage: previousMessages.length === 0,
+ });
+ await streaming.sendToAI(text, [...previousMessages, userMessage]);
+ },
+ [conversationId, createConversation, onBeforeSend, onMessagePersisted, persistence, streaming]
+ );
+}
diff --git a/src/components/chat/useChatPersistence.ts b/src/components/chat/useChatPersistence.ts
index 6f2e7d4d1..d57c86c63 100644
--- a/src/components/chat/useChatPersistence.ts
+++ b/src/components/chat/useChatPersistence.ts
@@ -1,16 +1,12 @@
import { useState, useRef, useCallback, useEffect } from "react";
import type { Message, ToolCallInfo } from "./types";
+import type { ContainerScope } from "../../types/chat";
interface UseChatPersistenceOptions {
conversationId?: number | null;
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[]>>;
@@ -18,7 +14,7 @@ export interface ChatPersistence {
createConversation: (
title: string,
noteId?: number | null,
- scope?: ConversationScope
+ scope?: ContainerScope
) => Promise<number>;
loadConversation: (id: number) => Promise<void>;
saveUserMessage: (text: string) => Promise<void>;
@@ -38,7 +34,7 @@ export function useChatPersistence(options: UseChatPersistenceOptions = {}): Cha
}, [conversationId]);
const createConversation = useCallback(
- async (title: string, noteId?: number | null, scope?: ConversationScope): Promise<number> => {
+ async (title: string, noteId?: number | null, scope?: ContainerScope): Promise<number> => {
const conv = await window.electronAPI?.createAgentConversation?.(
title,
noteId ?? undefined,
diff --git a/src/components/chat/useChatStreaming.ts b/src/components/chat/useChatStreaming.ts
index fd76a430f..896e8b029 100644
--- a/src/components/chat/useChatStreaming.ts
+++ b/src/components/chat/useChatStreaming.ts
@@ -7,6 +7,7 @@ import { getAgentSystemPrompt } from "../../config/prompts";
import { createToolRegistry } from "../../services/tools";
import type { ToolRegistry } from "../../services/tools/ToolRegistry";
import type { Message, AgentState, ToolCallInfo } from "./types";
+import type { ContainerScope } from "../../types/chat";
const RAG_NOTE_LIMIT = 5;
const RAG_NOTE_SNIPPET_LENGTH = 500;
@@ -18,12 +19,7 @@ function estimateModelSizeB(modelId: string): number {
return match ? parseFloat(match[1]) : 0;
}
-export interface ChatSearchScope {
- spaceId: number;
- folderId: number | null;
-}
-
-async function buildRAGContext(userText: string, scope?: ChatSearchScope): Promise<string> {
+async function buildRAGContext(userText: string, scope?: ContainerScope): Promise<string> {
if (!window.electronAPI?.semanticSearchNotes) return "";
try {
const results = await window.electronAPI.semanticSearchNotes(
@@ -55,7 +51,7 @@ interface UseChatStreamingOptions {
/** 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;
+ searchScope?: ContainerScope;
onStreamComplete?: (assistantId: string, content: string, toolCalls?: ToolCallInfo[]) => void;
}
diff --git a/src/components/notes/CreateSpaceDialog.tsx b/src/components/notes/CreateSpaceDialog.tsx
index 94706c1a7..eb71b0e07 100644
--- a/src/components/notes/CreateSpaceDialog.tsx
+++ b/src/components/notes/CreateSpaceDialog.tsx
@@ -146,14 +146,6 @@ export default function CreateSpaceDialog({
() => (rosterWorkspaceId === workspace?.id ? orderMemberCandidates(roster, user?.id) : []),
[roster, rosterWorkspaceId, user?.id, workspace?.id]
);
- const filteredCandidates = useMemo(() => {
- const query = memberSearch.trim().toLowerCase();
- if (!query) return candidates;
- return candidates.filter(
- (m) => (m.name ?? "").toLowerCase().includes(query) || m.email.toLowerCase().includes(query)
- );
- }, [candidates, memberSearch]);
-
const handleOpenChange = (nextOpen: boolean) => {
onOpenChange(nextOpen);
if (!nextOpen) {
@@ -458,7 +450,7 @@ export default function CreateSpaceDialog({
</div>
) : candidates.length > 0 ? (
<MemberPickList
- members={filteredCandidates}
+ members={candidates}
search={memberSearch}
onSearchChange={setMemberSearch}
onSelect={toggleMember}
diff --git a/src/components/notes/SpacesTree.tsx b/src/components/notes/SpacesTree.tsx
index 122cdedc3..65b2a2210 100644
--- a/src/components/notes/SpacesTree.tsx
+++ b/src/components/notes/SpacesTree.tsx
@@ -98,6 +98,13 @@ const MENU_ITEM_CLASS = "text-xs gap-2 rounded-md px-2 py-1";
const SUB_CONTENT_CLASS = "min-w-36 rounded-xl border border-border p-1";
+const DROP_TARGET_CLASS = "bg-primary/12 dark:bg-primary/15 ring-1 ring-primary/25";
+const DROP_SUCCESS_CLASS = "bg-emerald-500/10 dark:bg-emerald-400/10 ring-1 ring-emerald-500/20";
+const SUB_TRIGGER_CLASS = cn(
+ MENU_ITEM_CLASS,
+ "cursor-pointer focus:bg-foreground/5 data-[state=open]:bg-foreground/5"
+);
+
type TFn = (key: string, options?: Record<string, unknown>) => string;
type TreeRow =
@@ -183,8 +190,8 @@ function SectionHeader({
{...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",
+ isDragOver && DROP_TARGET_CLASS,
+ isDropSuccess && DROP_SUCCESS_CLASS,
className
)}
>
@@ -262,6 +269,91 @@ function Chevron({ isExpanded, onToggle }: { isExpanded: boolean; onToggle: () =
);
}
+function ContainerRowTrailing({
+ count,
+ isActive,
+ isDropSuccess,
+}: {
+ count: number;
+ isActive: boolean;
+ isDropSuccess: boolean;
+}) {
+ return isDropSuccess ? (
+ <Check
+ size={10}
+ className="text-emerald-500 dark:text-emerald-400 shrink-0 animate-[scale-in_200ms_ease-out]"
+ />
+ ) : (
+ <span
+ aria-hidden="true"
+ className={cn(
+ "text-xs tabular-nums shrink-0 transition-opacity group-hover:opacity-0",
+ isActive
+ ? "text-foreground/50 dark:text-foreground/30"
+ : "text-foreground/35 dark:text-foreground/15"
+ )}
+ >
+ {count > 0 ? count : ""}
+ </span>
+ );
+}
+
+function SearchableMoveSubmenu({
+ icon,
+ label,
+ itemCount,
+ search,
+ onSearchChange,
+ searchPlaceholder,
+ children,
+ footer,
+}: {
+ icon: React.ReactNode;
+ label: string;
+ itemCount: number;
+ search: string;
+ onSearchChange: (value: string) => void;
+ searchPlaceholder: string;
+ children: React.ReactNode;
+ footer?: React.ReactNode;
+}) {
+ return (
+ <DropdownMenuSub>
+ <DropdownMenuSubTrigger className={SUB_TRIGGER_CLASS}>
+ {icon}
+ {label}
+ </DropdownMenuSubTrigger>
+ <DropdownMenuSubContent sideOffset={4} className={SUB_CONTENT_CLASS}>
+ {itemCount > 5 && (
+ <>
+ <div className="relative px-1.5 py-0.5">
+ <Search
+ size={9}
+ className="absolute left-3.5 top-1/2 -translate-y-1/2 text-foreground/15 pointer-events-none"
+ />
+ <input
+ value={search}
+ onChange={(event) => onSearchChange(event.target.value)}
+ onKeyDown={(event) => event.stopPropagation()}
+ placeholder={searchPlaceholder}
+ className="input-inline w-full pl-4.5 pr-1 py-0.5 text-xs text-foreground placeholder:text-foreground/15 outline-none border-none appearance-none"
+ />
+ </div>
+ <DropdownMenuSeparator />
+ </>
+ )}
+ <div className="overflow-y-auto max-h-40">{children}</div>
+ {footer && (
+ <>
+ <DropdownMenuSeparator />
+ {footer}
+ </>
+ )}
+ </DropdownMenuSubContent>
+ </DropdownMenuSub>
+ );
+}
+
function SpaceMenuIcon({ space }: { space: SpaceItem }) {
if (space.kind === "private") {
return <Lock size={11} className="text-muted-foreground/60 shrink-0" />;
@@ -336,8 +428,8 @@ function SpaceRow({
isActive
? "bg-primary/8 dark:bg-primary/10"
: "hover:bg-foreground/4 dark:hover:bg-white/4",
- 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"
+ isDragOver && DROP_TARGET_CLASS,
+ isDropSuccess && DROP_SUCCESS_CLASS
)}
>
<Chevron isExpanded={isExpanded} onToggle={onToggle} />
@@ -374,24 +466,7 @@ function SpaceRow({
>
{displayName}
</span>
- {isDropSuccess ? (
- <Check
- size={10}
- className="text-emerald-500 dark:text-emerald-400 shrink-0 animate-[scale-in_200ms_ease-out]"
- />
- ) : (
- <span
- aria-hidden="true"
- className={cn(
- "text-xs tabular-nums shrink-0 transition-opacity group-hover:opacity-0",
- isActive
- ? "text-foreground/50 dark:text-foreground/30"
- : "text-foreground/35 dark:text-foreground/15"
- )}
- >
- {count > 0 ? count : ""}
- </span>
- )}
+ <ContainerRowTrailing count={count} isActive={isActive} isDropSuccess={isDropSuccess} />
<span className="absolute right-1.5 flex items-center gap-px">
<Button
variant="ghost"
@@ -555,8 +630,8 @@ function FolderRow({
isActive
? "bg-primary/8 dark:bg-primary/10"
: "hover:bg-foreground/4 dark:hover:bg-white/4",
- 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"
+ isDragOver && DROP_TARGET_CLASS,
+ isDropSuccess && DROP_SUCCESS_CLASS
)}
>
<Chevron isExpanded={isExpanded} onToggle={onToggle} />
@@ -579,24 +654,7 @@ function FolderRow({
>
{folder.name}
</span>
- {isDropSuccess ? (
- <Check
- size={10}
- className="text-emerald-500 dark:text-emerald-400 shrink-0 animate-[scale-in_200ms_ease-out]"
- />
- ) : (
- <span
- aria-hidden="true"
- className={cn(
- "text-xs tabular-nums shrink-0 transition-opacity group-hover:opacity-0",
- isActive
- ? "text-foreground/50 dark:text-foreground/30"
- : "text-foreground/35 dark:text-foreground/15"
- )}
- >
- {count > 0 ? count : ""}
- </span>
- )}
+ <ContainerRowTrailing count={count} isActive={isActive} isDropSuccess={isDropSuccess} />
{(!folder.is_default || noteFilesEnabled) && (
<DropdownMenu onOpenChange={(open) => !open && setSpaceSearch("")}>
<DropdownMenuTrigger asChild>
@@ -637,62 +695,38 @@ function FolderRow({
{t("notes.context.rename")}
</DropdownMenuItem>
{canMoveToSpace && (
- <DropdownMenuSub>
- <DropdownMenuSubTrigger
- className={cn(
- MENU_ITEM_CLASS,
- "cursor-pointer focus:bg-foreground/5 data-[state=open]:bg-foreground/5"
- )}
- >
- <Users size={11} className="text-muted-foreground/60" />
- {t("notes.spaces.moveToSpace")}
- </DropdownMenuSubTrigger>
- <DropdownMenuSubContent sideOffset={4} className={SUB_CONTENT_CLASS}>
- {spaces.length > 5 && (
- <>
- <div className="relative px-1.5 py-0.5">
- <Search
- size={9}
- className="absolute left-3.5 top-1/2 -translate-y-1/2 text-foreground/15 pointer-events-none"
- />
- <input
- value={spaceSearch}
- onChange={(e) => setSpaceSearch(e.target.value)}
- onKeyDown={(e) => e.stopPropagation()}
- placeholder={t("notes.spaces.searchSpaces")}
- className="input-inline w-full pl-4.5 pr-1 py-0.5 text-xs text-foreground placeholder:text-foreground/15 outline-none border-none appearance-none"
- />
- </div>
- <DropdownMenuSeparator />
- </>
- )}
- <div className="overflow-y-auto max-h-40">
- {filteredSpaces.map((space) => {
- const isCurrent = space.id === folder.space_id;
- return (
- <DropdownMenuItem
- key={space.id}
- disabled={isCurrent}
- onClick={(e) => {
- e.stopPropagation();
- onMoveToSpace(space);
- }}
- className={MENU_ITEM_CLASS}
- >
- <SpaceMenuIcon space={space} />
- <span className="truncate flex-1">{spaceDisplayName(space, t)}</span>
- {isCurrent && <Check size={9} className="text-primary shrink-0" />}
- </DropdownMenuItem>
- );
- })}
- {spaceSearch && filteredSpaces.length === 0 && (
- <p className="text-xs text-foreground/20 text-center py-1.5">
- {t("notes.spaces.noSpacesFound")}
- </p>
- )}
- </div>
- </DropdownMenuSubContent>
- </DropdownMenuSub>
+ <SearchableMoveSubmenu
+ icon={<Users size={11} className="text-muted-foreground/60" />}
+ label={t("notes.spaces.moveToSpace")}
+ itemCount={spaces.length}
+ search={spaceSearch}
+ onSearchChange={setSpaceSearch}
+ searchPlaceholder={t("notes.spaces.searchSpaces")}
+ >
+ {filteredSpaces.map((space) => {
+ const isCurrent = space.id === folder.space_id;
+ return (
+ <DropdownMenuItem
+ key={space.id}
+ disabled={isCurrent}
+ onClick={(e) => {
+ e.stopPropagation();
+ onMoveToSpace(space);
+ }}
+ className={MENU_ITEM_CLASS}
+ >
+ <SpaceMenuIcon space={space} />
+ <span className="truncate flex-1">{spaceDisplayName(space, t)}</span>
+ {isCurrent && <Check size={9} className="text-primary shrink-0" />}
+ </DropdownMenuItem>
+ );
+ })}
+ {spaceSearch && filteredSpaces.length === 0 && (
+ <p className="text-xs text-foreground/20 text-center py-1.5">
+ {t("notes.spaces.noSpacesFound")}
+ </p>
+ )}
+ </SearchableMoveSubmenu>
)}
<DropdownMenuSeparator />
<DropdownMenuItem
@@ -913,91 +947,15 @@ function NoteLeaf({
<DropdownMenuSeparator />
</>
)}
- <DropdownMenuSub>
- <DropdownMenuSubTrigger
- className={cn(
- MENU_ITEM_CLASS,
- "cursor-pointer focus:bg-foreground/5 data-[state=open]:bg-foreground/5"
- )}
- >
- <FolderOpen size={11} className="text-muted-foreground/60" />
- {multiSpace ? t("notes.spaces.moveTo") : t("notes.context.moveToFolder")}
- </DropdownMenuSubTrigger>
- <DropdownMenuSubContent sideOffset={4} className={SUB_CONTENT_CLASS}>
- {moveOptions.length > 5 && (
- <>
- <div className="relative px-1.5 py-0.5">
- <Search
- size={9}
- className="absolute left-3.5 top-1/2 -translate-y-1/2 text-foreground/15 pointer-events-none"
- />
- <input
- value={moveSearch}
- onChange={(e) => setMoveSearch(e.target.value)}
- onKeyDown={(e) => e.stopPropagation()}
- placeholder={t("notes.context.searchFolders")}
- className="input-inline w-full pl-4.5 pr-1 py-0.5 text-xs text-foreground placeholder:text-foreground/15 outline-none border-none appearance-none"
- />
- </div>
- <DropdownMenuSeparator />
- </>
- )}
- <div className="overflow-y-auto max-h-40">
- {moveSearch ? (
- <>
- {filteredOptions.map((option) =>
- renderOption(
- option,
- multiSpace && option.target.folderId != null
- ? `${spaceDisplayName(option.space, t)} / ${option.label}`
- : option.label
- )
- )}
- {filteredOptions.length === 0 && (
- <p className="text-xs text-foreground/20 text-center py-1.5">
- {t("notes.context.noResults")}
- </p>
- )}
- </>
- ) : multiSpace ? (
- spaces.map((space) => {
- const spaceOptions = moveOptions.filter(
- (option) => option.space.id === space.id
- );
- if (spaceOptions.length === 0) return null;
- return (
- <DropdownMenuSub key={space.id}>
- <DropdownMenuSubTrigger
- className={cn(
- MENU_ITEM_CLASS,
- "cursor-pointer focus:bg-foreground/5 data-[state=open]:bg-foreground/5"
- )}
- >
- <SpaceMenuIcon space={space} />
- <span className="truncate flex-1">{spaceDisplayName(space, t)}</span>
- </DropdownMenuSubTrigger>
- <DropdownMenuSubContent
- sideOffset={4}
- className={cn(SUB_CONTENT_CLASS, "max-h-40 overflow-y-auto")}
- >
- {spaceOptions.map((option) =>
- renderOption(
- option,
- option.target.folderId == null
- ? t("notes.spaces.spaceRoot")
- : option.label
- )
- )}
- </DropdownMenuSubContent>
- </DropdownMenuSub>
- );
- })
- ) : (
- moveOptions.map((option) => renderOption(option, option.label))
- )}
- </div>
- <DropdownMenuSeparator />
- {isCreating ? (
+ <SearchableMoveSubmenu
+ icon={<FolderOpen size={11} className="text-muted-foreground/60" />}
+ label={multiSpace ? t("notes.spaces.moveTo") : t("notes.context.moveToFolder")}
+ itemCount={moveOptions.length}
+ search={moveSearch}
+ onSearchChange={setMoveSearch}
+ searchPlaceholder={t("notes.context.searchFolders")}
+ footer={
+ isCreating ? (
<div className="px-1">
<input
autoFocus
@@ -1030,9 +988,55 @@ function NoteLeaf({
<Plus size={10} />
{t("notes.context.newFolder")}
</DropdownMenuItem>
- )}
- </DropdownMenuSubContent>
- </DropdownMenuSub>
+ )
+ }
+ >
+ {moveSearch ? (
+ <>
+ {filteredOptions.map((option) =>
+ renderOption(
+ option,
+ multiSpace && option.target.folderId != null
+ ? `${spaceDisplayName(option.space, t)} / ${option.label}`
+ : option.label
+ )
+ )}
+ {filteredOptions.length === 0 && (
+ <p className="text-xs text-foreground/20 text-center py-1.5">
+ {t("notes.context.noResults")}
+ </p>
+ )}
+ </>
+ ) : multiSpace ? (
+ spaces.map((space) => {
+ const spaceOptions = moveOptions.filter((option) => option.space.id === space.id);
+ if (spaceOptions.length === 0) return null;
+ return (
+ <DropdownMenuSub key={space.id}>
+ <DropdownMenuSubTrigger className={SUB_TRIGGER_CLASS}>
+ <SpaceMenuIcon space={space} />
+ <span className="truncate flex-1">{spaceDisplayName(space, t)}</span>
+ </DropdownMenuSubTrigger>
+ <DropdownMenuSubContent
+ sideOffset={4}
+ className={cn(SUB_CONTENT_CLASS, "max-h-40 overflow-y-auto")}
+ >
+ {spaceOptions.map((option) =>
+ renderOption(
+ option,
+ option.target.folderId == null
+ ? t("notes.spaces.spaceRoot")
+ : option.label
+ )
+ )}
+ </DropdownMenuSubContent>
+ </DropdownMenuSub>
+ );
+ })
+ ) : (
+ moveOptions.map((option) => renderOption(option, option.label))
+ )}
+ </SearchableMoveSubmenu>
<DropdownMenuSeparator />
<DropdownMenuItem
onClick={(e) => {
@@ -1215,10 +1219,9 @@ export default function SpacesTree({
if (!intoSpace) return;
showConfirmDialog({
title: t("notes.spaces.confirmMoveInTitle", { space: intoSpace.name }),
- description: t(
- isFolder ? "notes.spaces.confirmMoveInFolder" : "notes.spaces.confirmMoveIn",
- { space: intoSpace.name }
- ),
+ description: t(isFolder ? "notes.spaces.confirmMoveInFolder" : "notes.spaces.confirmMoveIn", {
+ space: intoSpace.name,
+ }),
confirmText: t("notes.spaces.moveConfirm"),
onConfirm,
});
@@ -1334,8 +1337,7 @@ export default function SpacesTree({
confirmCrossSpaceMove(note.spaceId, target.spaceId, false, commit);
},
canCrossSpaceDrop: (note, target) => allowsCrossSpaceMove(note.spaceId, target.spaceId),
- onCrossSpaceVeto: () =>
- toast({ title: t("notes.spaces.cantMoveOut"), duration: 4000 }),
+ onCrossSpaceVeto: () => toast({ title: t("notes.spaces.cantMoveOut"), duration: 4000 }),
onHoverTarget: (key) => setContainerExpanded(key, true),
});
diff --git a/src/hooks/useContainerChat.ts b/src/hooks/useContainerChat.ts
index 4c33bc30a..eb36cf570 100644
--- a/src/hooks/useContainerChat.ts
+++ b/src/hooks/useContainerChat.ts
@@ -1,9 +1,11 @@
import { useState, useCallback, useEffect, useMemo } from "react";
import { useChatPersistence } from "../components/chat/useChatPersistence";
-import { useChatStreaming, type ChatSearchScope } from "../components/chat/useChatStreaming";
+import { useChatStreaming } from "../components/chat/useChatStreaming";
+import { useChatMessageSender } from "../components/chat/useChatMessageSender";
import type { Message, AgentState } from "../components/chat/types";
import { deriveConversationTitle } from "../lib/conversationTitle";
import type { SpaceItem, FolderItem, NoteItem } from "../types/electron";
+import type { ContainerScope } from "../types/chat";
const MAX_CONTEXT_NOTES = 12;
const NOTE_SNIPPET_LENGTH = 600;
@@ -62,7 +64,7 @@ export function useContainerChat({
return [header, ...noteBlocks].join("\n\n");
}, [folder, space.name, notes]);
- const searchScope = useMemo<ChatSearchScope>(
+ const searchScope = useMemo<ContainerScope>(
() => ({ spaceId: space.id, folderId }),
[space.id, folderId]
);
@@ -106,32 +108,24 @@ export function useContainerChat({
setConversationId(null);
}, [persistence]);
- const sendMessage = useCallback(
+ const createConversation = useCallback(
async (text: string) => {
- let convId = conversationId;
- if (!convId) {
- const title = deriveConversationTitle(text, 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);
+ const title = deriveConversationTitle(text, folder?.name ?? space.name);
+ const id = await persistence.createConversation(title, null, {
+ spaceId: space.id,
+ folderId,
+ });
+ void fetchConversations();
+ return id;
},
- [conversationId, folder, folderId, space.id, space.name, persistence, streaming, fetchConversations]
+ [fetchConversations, folder, folderId, persistence, space.id, space.name]
);
+ const sendMessage = useChatMessageSender({
+ conversationId,
+ persistence,
+ streaming,
+ createConversation,
+ });
return {
messages: persistence.messages,
diff --git a/src/hooks/useEmbeddedChat.ts b/src/hooks/useEmbeddedChat.ts
index 465349547..5d989cda9 100644
--- a/src/hooks/useEmbeddedChat.ts
+++ b/src/hooks/useEmbeddedChat.ts
@@ -1,6 +1,7 @@
import { useState, useCallback, useEffect, useMemo, useRef } from "react";
import { useChatPersistence } from "../components/chat/useChatPersistence";
import { useChatStreaming } from "../components/chat/useChatStreaming";
+import { useChatMessageSender } from "../components/chat/useChatMessageSender";
import type { Message, AgentState } from "../components/chat/types";
interface UseEmbeddedChatOptions {
@@ -127,29 +128,20 @@ export function useEmbeddedChat({
setConversationId(null);
}, [persistence]);
- const sendMessage = useCallback(
+ const createConversation = useCallback(
async (text: string) => {
- let convId = conversationId;
- if (!convId) {
- const title = `Note: ${noteTitle || "Untitled"}`;
- convId = await persistence.createConversation(title, noteId);
- fetchNoteConversations();
- }
-
- 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);
+ const id = await persistence.createConversation(`Note: ${noteTitle || "Untitled"}`, noteId);
+ void fetchNoteConversations();
+ return id;
},
- [conversationId, noteId, noteTitle, persistence, streaming, fetchNoteConversations]
+ [fetchNoteConversations, noteId, noteTitle, persistence]
);
+ const sendMessage = useChatMessageSender({
+ conversationId,
+ persistence,
+ streaming,
+ createConversation,
+ });
return {
messages: persistence.messages,
diff --git a/src/hooks/useUsage.ts b/src/hooks/useUsage.ts
index 6503e25bd..8cb592f16 100644
--- a/src/hooks/useUsage.ts
+++ b/src/hooks/useUsage.ts
@@ -2,7 +2,7 @@ import { useState, useEffect, useCallback, useRef } from "react";
import { useAuth } from "./useAuth";
import { CACHE_CONFIG } from "../config/constants";
import { withSessionRefresh } from "../lib/auth";
-import { notifyIsSubscribedChanged, readIsSubscribed } from "../lib/subscriptionFlag";
+import { writeIsSubscribed } from "../lib/subscriptionFlag";
interface UsageData {
wordsUsed: number;
@@ -110,10 +110,7 @@ export function useUsage(): UseUsageResult | null {
},
});
lastFetchRef.current = Date.now();
- const isSubscribed = result.isSubscribed ?? false;
- const flagChanged = readIsSubscribed() !== isSubscribed;
- localStorage.setItem("isSubscribed", String(isSubscribed));
- if (flagChanged) notifyIsSubscribedChanged();
+ writeIsSubscribed(result.isSubscribed ?? false);
} else {
const error: any = new Error(result.error || "Failed to fetch usage");
error.code = result.code;
diff --git a/src/lib/memberCandidates.ts b/src/lib/memberCandidates.ts
index fe2d10486..657c9fe53 100644
--- a/src/lib/memberCandidates.ts
+++ b/src/lib/memberCandidates.ts
@@ -10,3 +10,16 @@ export function orderMemberCandidates<M extends { user_id: string }>(
if (self.length === 0) return members;
return [...self, ...members.filter((m) => m.user_id !== currentUserId)];
}
+
+export function filterMemberCandidates<M extends { name?: string | null; email: string }>(
+ members: M[],
+ search: string
+): M[] {
+ const query = search.trim().toLowerCase();
+ if (!query) return members;
+ return members.filter(
+ (member) =>
+ (member.name ?? "").toLowerCase().includes(query) ||
+ member.email.toLowerCase().includes(query)
+ );
+}
diff --git a/src/lib/reactiveLocalFlag.ts b/src/lib/reactiveLocalFlag.ts
index 55cb66bec..3966da030 100644
--- a/src/lib/reactiveLocalFlag.ts
+++ b/src/lib/reactiveLocalFlag.ts
@@ -1,16 +1,28 @@
-// Reactive view over a boolean localStorage flag: same-window writers call
-// notify(); cross-window flips ride the storage event.
+// Reactive boolean localStorage flag. Writes notify same-window subscribers;
+// cross-window flips ride the storage event.
export interface ReactiveLocalFlag {
read: () => boolean;
- notify: () => void;
+ write: (value: boolean) => void;
+ clear: () => void;
subscribe: (onChange: () => void) => () => void;
}
export function createReactiveLocalFlag(key: string): ReactiveLocalFlag {
const subscribers = new Set<() => void>();
+ const notify = () => subscribers.forEach((subscriber) => subscriber());
return {
read: () => localStorage.getItem(key) === "true",
- notify: () => subscribers.forEach((n) => n()),
+ write: (value) => {
+ const next = String(value);
+ if (localStorage.getItem(key) === next) return;
+ localStorage.setItem(key, next);
+ notify();
+ },
+ clear: () => {
+ if (localStorage.getItem(key) == null) return;
+ localStorage.removeItem(key);
+ notify();
+ },
subscribe: (onChange) => {
subscribers.add(onChange);
const onStorage = (e: StorageEvent) => {
diff --git a/src/lib/subscriptionFlag.ts b/src/lib/subscriptionFlag.ts
index 302dd2e3a..8828606ee 100644
--- a/src/lib/subscriptionFlag.ts
+++ b/src/lib/subscriptionFlag.ts
@@ -5,5 +5,6 @@ import { createReactiveLocalFlag } from "./reactiveLocalFlag";
const flag = createReactiveLocalFlag("isSubscribed");
export const readIsSubscribed = flag.read;
-export const notifyIsSubscribedChanged = flag.notify;
+export const writeIsSubscribed = flag.write;
+export const clearIsSubscribed = flag.clear;
export const subscribeIsSubscribed = flag.subscribe;
diff --git a/src/lib/teamSpacesCapability.ts b/src/lib/teamSpacesCapability.ts
index 910d6499c..67bb19de1 100644
--- a/src/lib/teamSpacesCapability.ts
+++ b/src/lib/teamSpacesCapability.ts
@@ -4,5 +4,6 @@ import { createReactiveLocalFlag } from "./reactiveLocalFlag";
const flag = createReactiveLocalFlag("teamSpacesCapability");
export const readTeamSpacesCapability = flag.read;
-export const notifyTeamSpacesCapabilityChanged = flag.notify;
+export const writeTeamSpacesCapability = flag.write;
+export const clearTeamSpacesCapability = flag.clear;
export const subscribeTeamSpacesCapability = flag.subscribe;
diff --git a/src/services/SyncService.ts b/src/services/SyncService.ts
index 55a4f029f..60f22a0e8 100644
--- a/src/services/SyncService.ts
+++ b/src/services/SyncService.ts
@@ -13,8 +13,12 @@ import { TranscriptionsService } from "./TranscriptionsService.js";
import { DictionaryService } from "./DictionaryService.js";
import { SnippetService, type CloudSnippetEntry } from "./SnippetService.js";
import { CloudApiError } from "./cloudApi.js";
-import { notifyTeamSpacesCapabilityChanged } from "../lib/teamSpacesCapability";
-import { subscribeIsSubscribed } from "../lib/subscriptionFlag";
+import {
+ clearTeamSpacesCapability,
+ readTeamSpacesCapability,
+ writeTeamSpacesCapability,
+} from "../lib/teamSpacesCapability";
+import { readIsSubscribed, subscribeIsSubscribed } from "../lib/subscriptionFlag";
import { readNoteConflictIds } from "../lib/noteConflictRegistry";
import {
buildNoteUpdatePayload,
@@ -186,17 +190,14 @@ class SyncService {
return (
localStorage.getItem("isSignedIn") === "true" &&
localStorage.getItem("cloudBackupEnabled") === "true" &&
- localStorage.getItem("isSubscribed") === "true"
+ readIsSubscribed()
);
}
// Sharing a note is per-note consent: shared notes keep syncing even when
// the global cloud-backup toggle is off, as long as the account can sync.
private canSyncSharedNotes(): boolean {
- return (
- localStorage.getItem("isSignedIn") === "true" &&
- localStorage.getItem("isSubscribed") === "true"
- );
+ return localStorage.getItem("isSignedIn") === "true" && readIsSubscribed();
}
// Team-space membership, like sharing, is per-space consent: team content
@@ -208,14 +209,12 @@ class SyncService {
// Whether the API supports team scope (GET /api/me/teams deployed); probed
// by syncSpaces and cached for the UI gate (useTeamSpacesCapability).
private hasTeamSpacesCapability(): boolean {
- return localStorage.getItem("teamSpacesCapability") === "true";
+ return readTeamSpacesCapability();
}
private cacheTeamSpacesCapability(available: boolean): void {
- const changed = localStorage.getItem("teamSpacesCapability") !== String(available);
- localStorage.setItem("teamSpacesCapability", String(available));
+ writeTeamSpacesCapability(available);
localStorage.setItem("teamSpacesCapability.probedAt", new Date().toISOString());
- if (changed) notifyTeamSpacesCapabilityChanged();
}
// Sign-out leaves no team content behind: purge every team space locally and
@@ -254,9 +253,8 @@ class SyncService {
} catch (err) {
console.error("Team space purge on sign-out failed:", err);
}
- localStorage.removeItem("teamSpacesCapability");
+ clearTeamSpacesCapability();
localStorage.removeItem("teamSpacesCapability.probedAt");
- notifyTeamSpacesCapabilityChanged();
localStorage.removeItem("lastSyncedAt.notes.team");
localStorage.removeItem("lastSyncedAt.folders.team");
// The guard protected any pass still in flight during the purge; drop it
@@ -494,18 +492,10 @@ class SyncService {
const folders = (await window.electronAPI.getFolders?.()) ?? [];
const folder = folders.find((f) => f.id === id);
if (!folder) return;
- if (folder.left_team && folder.cloud_id && !this.hasTeamSpacesCapability()) {
- // The retraction PATCH needs team-scope support; without it the push
- // would settle the row and erase the pending scope change.
- return;
- }
const ctx = await this.buildSpaceContext();
- const scope = this.pushScopeFields(ctx.byId.get(folder.space_id));
- if (!scope) {
- console.warn(`Skipping folder ${folder.id} push: its team space has no cloud team yet`);
- return;
- }
+ const scope = this.resolvePushScope("folder", folder, ctx);
+ if (!scope) return;
if (folder.cloud_id) {
try {
@@ -584,18 +574,9 @@ class SyncService {
// folder settles.
return;
}
- if (note.left_team && note.cloud_id && !this.hasTeamSpacesCapability()) {
- // The retraction PATCH needs team-scope support; without it the push
- // would settle the row and erase the pending scope change. Defer until
- // the capability probe recovers.
- return;
- }
const ctx = await this.buildSpaceContext();
- const scope = this.pushScopeFields(ctx.byId.get(note.space_id));
- if (!scope) {
- console.warn(`Skipping note ${note.id} push: its team space has no cloud team yet`);
- return;
- }
+ const scope = this.resolvePushScope("note", note, ctx);
+ if (!scope) return;
const cloudFolderId = note.folder_id ? (localToCloud.get(note.folder_id) ?? null) : null;
try {
@@ -813,6 +794,23 @@ class SyncService {
return this.hasTeamSpacesCapability() ? { workspace_id: null, space_id: null } : {};
}
+ // Resolves every note/folder push through the same two gates. Retractions
+ // must wait for team-scope support or settling the row would erase the
+ // pending scope change; team rows without a cloud scope must stay local.
+ private resolvePushScope(
+ kind: "folder" | "note",
+ row: FolderItem | NoteItem,
+ ctx: SpaceSyncContext
+ ): PushScopeFields | null {
+ if (row.left_team && row.cloud_id && !this.hasTeamSpacesCapability()) return null;
+
+ const scope = this.pushScopeFields(ctx.byId.get(row.space_id));
+ if (!scope) {
+ console.warn(`Skipping ${kind} ${row.id} push: its team space has no cloud team yet`);
+ }
+ return scope;
+ }
+
// A push was rejected because the note's team is gone or access was revoked
// (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
@@ -963,16 +961,8 @@ class SyncService {
const ctx = await this.buildSpaceContext();
const pushable: Array<{ folder: FolderItem; scope: PushScopeFields }> = [];
for (const folder of pending) {
- if (folder.left_team && folder.cloud_id && !this.hasTeamSpacesCapability()) {
- // The retraction PATCH needs team-scope support; without it the push
- // would settle the row and erase the pending scope change.
- continue;
- }
- const scope = this.pushScopeFields(ctx.byId.get(folder.space_id));
- if (!scope) {
- console.warn(`Skipping folder ${folder.id} push: its team space has no cloud team yet`);
- continue;
- }
+ const scope = this.resolvePushScope("folder", folder, ctx);
+ if (!scope) continue;
pushable.push({ folder, scope });
}
@@ -1243,16 +1233,8 @@ class SyncService {
// folder and notes push together once the conflict resolves.
continue;
}
- if (note.left_team && note.cloud_id && !this.hasTeamSpacesCapability()) {
- // The retraction PATCH needs team-scope support; without it the push
- // would settle the row and erase the pending scope change.
- continue;
- }
- const scope = this.pushScopeFields(ctx.byId.get(note.space_id));
- if (!scope) {
- console.warn(`Skipping note ${note.id} push: its team space has no cloud team yet`);
- continue;
- }
+ const scope = this.resolvePushScope("note", note, ctx);
+ if (!scope) continue;
pushable.push({ note, scope });
}
diff --git a/src/services/tools/index.ts b/src/services/tools/index.ts
index 7c8f5c3b5..611af8585 100644
--- a/src/services/tools/index.ts
+++ b/src/services/tools/index.ts
@@ -7,6 +7,7 @@ import { listFoldersTool } from "./listFoldersTool";
import { clipboardTool } from "./clipboardTool";
import { webSearchTool } from "./webSearchTool";
import { calendarTool } from "./calendarTool";
+import type { ContainerScope } from "../../types/chat";
export { ToolRegistry } from "./ToolRegistry";
export type { ToolDefinition, ToolResult } from "./ToolRegistry";
@@ -16,7 +17,7 @@ interface ToolRegistrySettings {
gcalConnected: boolean;
cloudBackupEnabled: boolean;
/** Pins search_notes to a container (overview chat); the LLM cannot widen it. */
- searchScope?: { spaceId: number; folderId: number | null };
+ searchScope?: ContainerScope;
}
export function createToolRegistry(settings: ToolRegistrySettings): ToolRegistry {
diff --git a/src/services/tools/searchNotesTool.ts b/src/services/tools/searchNotesTool.ts
index 8181d97b7..9454e65e9 100644
--- a/src/services/tools/searchNotesTool.ts
+++ b/src/services/tools/searchNotesTool.ts
@@ -1,4 +1,5 @@
import type { SpaceItem } from "../../types/electron";
+import type { ContainerScope } from "../../types/chat";
import type { ToolDefinition, ToolResult } from "./ToolRegistry";
import { resolveLocalNoteId, resolveSpace } from "./utils";
@@ -7,7 +8,7 @@ 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 };
+ fixedScope?: ContainerScope;
}
export function createSearchNotesTool(options: SearchToolOptions): ToolDefinition {
diff --git a/src/stores/noteListOps.ts b/src/stores/noteListOps.ts
index 5ca9a296d..89a9d0b6d 100644
--- a/src/stores/noteListOps.ts
+++ b/src/stores/noteListOps.ts
@@ -10,6 +10,16 @@ export interface RemoveNoteResult extends NoteListsState {
changed: boolean;
}
+export interface NoteContainerState {
+ notesByContainer: Record<string, NoteItem[]>;
+ expandedContainers: Set<string>;
+ activeNoteId: number | null;
+}
+
+export interface TeardownContainersResult extends NoteContainerState {
+ removedNotes: NoteItem[];
+}
+
/**
* Remove a note from every container list AND the flat `notes` list. The flat
* list can hold notes absent from every loaded container (flat-only loads,
@@ -45,3 +55,32 @@ export function removeNoteFromLists(state: NoteListsState, id: number): RemoveNo
return { notesByContainer, notes, activeNoteId, changed };
}
+
+/**
+ * Remove cached note containers and all renderer state that points into them.
+ * Folder deletion and space purging share this operation; callers remain
+ * responsible for choosing a replacement active context.
+ */
+export function teardownNoteContainers(
+ state: NoteContainerState,
+ keys: Iterable<string>
+): TeardownContainersResult {
+ const removedKeys = new Set(keys);
+ const notesByContainer: Record<string, NoteItem[]> = {};
+ const removedNotes: NoteItem[] = [];
+
+ for (const [key, items] of Object.entries(state.notesByContainer)) {
+ if (removedKeys.has(key)) removedNotes.push(...items);
+ else notesByContainer[key] = items;
+ }
+
+ const expandedContainers = new Set(
+ [...state.expandedContainers].filter((key) => !removedKeys.has(key))
+ );
+ const activeNoteId =
+ state.activeNoteId != null && removedNotes.some((note) => note.id === state.activeNoteId)
+ ? null
+ : state.activeNoteId;
+
+ return { notesByContainer, expandedContainers, activeNoteId, removedNotes };
+}
diff --git a/src/stores/noteStore.ts b/src/stores/noteStore.ts
index 744eaac29..4332464c1 100644
--- a/src/stores/noteStore.ts
+++ b/src/stores/noteStore.ts
@@ -1,6 +1,6 @@
import { create } from "zustand";
import { syncService } from "../services/SyncService.js";
-import { removeNoteFromLists } from "./noteListOps";
+import { removeNoteFromLists, teardownNoteContainers } from "./noteListOps";
import {
addNoteConflict,
readNoteConflicts,
@@ -248,23 +248,20 @@ function ensureIpcListeners() {
if (id == null) return;
const state = useNoteStore.getState();
const key = folderContainerKey(id);
- const removedNotes = state.notesByContainer[key];
- const notesByContainer = { ...state.notesByContainer };
- delete notesByContainer[key];
- const expanded = new Set(state.expandedContainers);
- if (expanded.delete(key)) persistExpandedContainers(expanded);
- const extra: Partial<NoteState> = { expandedContainers: expanded };
- if (state.activeNoteId != null && removedNotes?.some((n) => n.id === state.activeNoteId)) {
- extra.activeNoteId = null;
- }
+ const teardown = teardownNoteContainers(state, [key]);
+ persistExpandedContainers(teardown.expandedContainers);
+ const extra: Partial<NoteState> = {
+ expandedContainers: teardown.expandedContainers,
+ activeNoteId: teardown.activeNoteId,
+ };
let fallbackContext: ActiveContext | null = null;
if (state.activeContext?.folderId === id) {
// The active folder vanished under us — degrade to its space root.
fallbackContext = { spaceId: state.activeContext.spaceId, folderId: null };
extra.activeContext = fallbackContext;
- extra.notes = notesByContainer[contextContainerKey(fallbackContext)] ?? [];
+ extra.notes = teardown.notesByContainer[contextContainerKey(fallbackContext)] ?? [];
}
- useNoteStore.setState({ notesByContainer, ...extra });
+ useNoteStore.setState({ notesByContainer: teardown.notesByContainer, ...extra });
if (fallbackContext) void ensureContainerLoaded(contextContainerKey(fallbackContext));
void loadFolders();
});
@@ -348,7 +345,11 @@ export async function loadFolders(): Promise<FolderItem[]> {
const containerLoadGenerations = new Map<string, number>();
const containerLoadsInFlight = new Map<string, Promise<NoteItem[]>>();
-export async function loadContainerNotes(key: string): Promise<NoteItem[]> {
+export async function loadContainerNotes(
+ key: string,
+ noteType: string | null = null,
+ limit = DEFAULT_LIMIT
+): Promise<NoteItem[]> {
const gen = (containerLoadGenerations.get(key) ?? 0) + 1;
containerLoadGenerations.set(key, gen);
const load = (async (): Promise<NoteItem[]> => {
@@ -356,8 +357,8 @@ export async function loadContainerNotes(key: string): Promise<NoteItem[]> {
const id = Number(idStr);
const items =
kind === "f"
- ? ((await window.electronAPI?.getNotes(null, DEFAULT_LIMIT, id)) ?? [])
- : ((await window.electronAPI?.getNotes(null, DEFAULT_LIMIT, null, id)) ?? []);
+ ? ((await window.electronAPI?.getNotes(noteType, limit, id)) ?? [])
+ : ((await window.electronAPI?.getNotes(noteType, limit, null, id)) ?? []);
// A newer load for this container may have resolved first.
if (containerLoadGenerations.get(key) === gen) {
applyContainers({ ...useNoteStore.getState().notesByContainer, [key]: items });
@@ -477,19 +478,16 @@ export async function initializeNotes(
limit = DEFAULT_LIMIT,
folderId?: number | null
): Promise<NoteItem[]> {
- const gen = ++loadGeneration;
currentLimit = limit;
ensureIpcListeners();
- const items = (await window.electronAPI?.getNotes(noteType, limit, folderId)) ?? [];
- if (gen !== loadGeneration) return items;
if (folderId != null) {
- applyContainers({
- ...useNoteStore.getState().notesByContainer,
- [folderContainerKey(folderId)]: items,
- });
- } else {
- useNoteStore.setState({ notes: items });
+ return loadContainerNotes(folderContainerKey(folderId), noteType ?? null, limit);
}
+
+ const gen = ++loadGeneration;
+ const items = (await window.electronAPI?.getNotes(noteType, limit, folderId)) ?? [];
+ if (gen !== loadGeneration) return items;
+ useNoteStore.setState({ notes: items });
return items;
}
@@ -572,18 +570,14 @@ function handleSpacePurged(spaceId: number): void {
if (f.space_id === spaceId) removedKeys.add(folderContainerKey(f.id));
});
- const notesByContainer: Record<string, NoteItem[]> = {};
- for (const [key, items] of Object.entries(state.notesByContainer)) {
- if (!removedKeys.has(key)) notesByContainer[key] = items;
- }
+ const teardown = teardownNoteContainers(state, removedKeys);
const folderCounts = { ...state.folderCounts };
state.folders.forEach((f) => {
if (f.space_id === spaceId) delete folderCounts[f.id];
});
const spaceRootCounts = { ...state.spaceRootCounts };
delete spaceRootCounts[spaceId];
- const expanded = new Set([...state.expandedContainers].filter((key) => !removedKeys.has(key)));
- persistExpandedContainers(expanded);
+ persistExpandedContainers(teardown.expandedContainers);
// Purge completeness (plan §5.4): purged notes' share-cache entries (which
// can hold raw link tokens) and conflict banners (which hold full cloud
@@ -592,11 +586,9 @@ function handleSpacePurged(spaceId: number): void {
// never have been loaded.
const purgedCloudIds = new Set<string>();
const purgedClientIds = new Set<string>();
- removedKeys.forEach((key) => {
- (state.notesByContainer[key] ?? []).forEach((n) => {
- if (n.cloud_id) purgedCloudIds.add(n.cloud_id);
- purgedClientIds.add(n.client_note_id);
- });
+ teardown.removedNotes.forEach((note) => {
+ if (note.cloud_id) purgedCloudIds.add(note.cloud_id);
+ purgedClientIds.add(note.client_note_id);
});
const shareByCloudId = new Map(state.shareByCloudId);
purgedCloudIds.forEach((id) => shareByCloudId.delete(id));
@@ -616,7 +608,8 @@ function handleSpacePurged(spaceId: number): void {
folders: state.folders.filter((f) => f.space_id !== spaceId),
folderCounts,
spaceRootCounts,
- expandedContainers: expanded,
+ expandedContainers: teardown.expandedContainers,
+ activeNoteId: teardown.activeNoteId,
shareByCloudId,
noteConflicts,
};
@@ -638,10 +631,10 @@ function handleSpacePurged(spaceId: number): void {
const fallbackFolder = findDefaultFolder(privateFolders) ?? privateFolders[0];
fallbackContext = { spaceId: privateSpace.id, folderId: fallbackFolder?.id ?? null };
extra.activeContext = fallbackContext;
- extra.notes = notesByContainer[contextContainerKey(fallbackContext)] ?? [];
+ extra.notes = teardown.notesByContainer[contextContainerKey(fallbackContext)] ?? [];
}
}
- useNoteStore.setState({ notesByContainer, ...extra });
+ useNoteStore.setState({ notesByContainer: teardown.notesByContainer, ...extra });
if (fallbackContext) void ensureContainerLoaded(contextContainerKey(fallbackContext));
// The purge relocates never-synced notes to the private space root —
// refresh counts, and the root container when it's already cached.
@@ -686,16 +679,13 @@ export async function deleteFolder(id: number): Promise<{ success: boolean; erro
const state = useNoteStore.getState();
const folder = state.folders.find((f) => f.id === id);
const key = folderContainerKey(id);
- const deletedNotes = state.notesByContainer[key];
- const notesByContainer = { ...state.notesByContainer };
- delete notesByContainer[key];
- const expanded = new Set(state.expandedContainers);
- if (expanded.delete(key)) persistExpandedContainers(expanded);
- const extra: Partial<NoteState> = { expandedContainers: expanded };
- if (state.activeNoteId != null && deletedNotes?.some((n) => n.id === state.activeNoteId)) {
- extra.activeNoteId = null;
- }
- useNoteStore.setState({ notesByContainer, ...extra });
+ const teardown = teardownNoteContainers(state, [key]);
+ persistExpandedContainers(teardown.expandedContainers);
+ useNoteStore.setState({
+ notesByContainer: teardown.notesByContainer,
+ expandedContainers: teardown.expandedContainers,
+ activeNoteId: teardown.activeNoteId,
+ });
await loadFolders();
if (getActiveFolderIdValue() === id && folder) {
diff --git a/src/types/chat.ts b/src/types/chat.ts
new file mode 100644
index 000000000..c2279ec5b
--- /dev/null
+++ b/src/types/chat.ts
@@ -0,0 +1,4 @@
+export interface ContainerScope {
+ spaceId: number;
+ folderId: number | null;
+}
diff --git a/test/helpers/noteListOps.test.js b/test/helpers/noteListOps.test.js
index 0e72b3519..7af4e618d 100644
--- a/test/helpers/noteListOps.test.js
+++ b/test/helpers/noteListOps.test.js
@@ -101,3 +101,43 @@ test("no-ops when the note is nowhere", async () => {
assert.equal(result.changed, false);
assert.equal(result.activeNoteId, 1);
});
+
+test("tears down multiple containers and clears an active note inside them", async () => {
+ const { teardownNoteContainers } = await load();
+ const state = {
+ notesByContainer: {
+ "s:1": [note(1, null, 1)],
+ "f:2": [note(2, 2, 1)],
+ "s:3": [note(3, null, 3)],
+ },
+ expandedContainers: new Set(["s:1", "f:2", "s:3"]),
+ activeNoteId: 2,
+ };
+
+ const result = teardownNoteContainers(state, ["s:1", "f:2"]);
+
+ assert.deepEqual(Object.keys(result.notesByContainer), ["s:3"]);
+ assert.deepEqual(
+ result.removedNotes.map((n) => n.id),
+ [1, 2]
+ );
+ assert.deepEqual([...result.expandedContainers], ["s:3"]);
+ assert.equal(result.activeNoteId, null);
+});
+
+test("container teardown preserves active notes outside the removed containers", async () => {
+ const { teardownNoteContainers } = await load();
+ const state = {
+ notesByContainer: {
+ "f:1": [note(1)],
+ "f:2": [note(2, 2)],
+ },
+ expandedContainers: new Set(["f:1", "f:2"]),
+ activeNoteId: 2,
+ };
+
+ const result = teardownNoteContainers(state, ["f:1"]);
+
+ assert.equal(result.notesByContainer["f:2"], state.notesByContainer["f:2"]);
+ assert.equal(result.activeNoteId, 2);
+});
diff --git a/test/lib/memberCandidates.test.js b/test/lib/memberCandidates.test.js
index c068e082a..37d3985c0 100644
--- a/test/lib/memberCandidates.test.js
+++ b/test/lib/memberCandidates.test.js
@@ -1,6 +1,9 @@
const test = require("node:test");
const assert = require("node:assert/strict");
-const { orderMemberCandidates } = require("../../src/lib/memberCandidates.ts");
+const {
+ filterMemberCandidates,
+ orderMemberCandidates,
+} = require("../../src/lib/memberCandidates.ts");
const member = (userId) => ({ user_id: userId });
@@ -18,3 +21,14 @@ test("orderMemberCandidates: keeps order when current user is absent or unknown"
assert.deepEqual(orderMemberCandidates(members, undefined), members);
assert.deepEqual(orderMemberCandidates([], "me"), []);
});
+
+test("filterMemberCandidates: matches names and emails case-insensitively", () => {
+ const members = [
+ { user_id: "1", name: "Ada Lovelace", email: "[email protected]" },
+ { user_id: "2", name: null, email: "[email protected]" },
+ ];
+
+ assert.deepEqual(filterMemberCandidates(members, " love "), [members[0]]);
+ assert.deepEqual(filterMemberCandidates(members, "grace@"), [members[1]]);
+ assert.equal(filterMemberCandidates(members, ""), members);
+});
diff --git a/test/lib/reactiveLocalFlag.test.js b/test/lib/reactiveLocalFlag.test.js
new file mode 100644
index 000000000..e0fcd059b
--- /dev/null
+++ b/test/lib/reactiveLocalFlag.test.js
@@ -0,0 +1,49 @@
+const test = require("node:test");
+const assert = require("node:assert/strict");
+
+const load = () => import("../../src/lib/reactiveLocalFlag.ts");
+
+function installBrowserStubs() {
+ const values = new Map();
+ const listeners = new Map();
+ const previous = { localStorage: global.localStorage, window: global.window };
+ global.localStorage = {
+ getItem: (key) => values.get(key) ?? null,
+ setItem: (key, value) => values.set(key, String(value)),
+ removeItem: (key) => values.delete(key),
+ };
+ global.window = {
+ addEventListener: (name, listener) => listeners.set(name, listener),
+ removeEventListener: (name, listener) => {
+ if (listeners.get(name) === listener) listeners.delete(name);
+ },
+ };
+ return () => {
+ global.localStorage = previous.localStorage;
+ global.window = previous.window;
+ };
+}
+
+test("write and clear own the storage-plus-notify contract", async (t) => {
+ const restore = installBrowserStubs();
+ t.after(restore);
+ const { createReactiveLocalFlag } = await load();
+ const flag = createReactiveLocalFlag("feature");
+ let changes = 0;
+ const unsubscribe = flag.subscribe(() => changes++);
+
+ flag.write(true);
+ assert.equal(flag.read(), true);
+ assert.equal(changes, 1);
+
+ flag.write(true);
+ assert.equal(changes, 1);
+
+ flag.clear();
+ assert.equal(flag.read(), false);
+ assert.equal(changes, 2);
+
+ flag.clear();
+ assert.equal(changes, 2);
+ unsubscribe();
+});