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): add sidebar chat tab with conversation history, cloud sync, and semantic search

Gabriel Stein4648a7ae0aa7
diff --git a/package-lock.json b/package-lock.json
index 0c3ec9e38..b4666fa6e 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -16,6 +16,7 @@
"@ai-sdk/openai": "^3.0.41",
"@neondatabase/auth": "^0.1.0-beta.21",
"@neondatabase/neon-js": "^0.1.0-beta.22",
+ "@qdrant/js-client-rest": "^1.12.0",
"@radix-ui/react-accordion": "^1.1.2",
"@radix-ui/react-dialog": "^1.1.14",
"@radix-ui/react-dropdown-menu": "^2.1.15",
@@ -24,6 +25,7 @@
"@radix-ui/react-select": "^2.2.5",
"@radix-ui/react-slot": "^1.2.3",
"@radix-ui/react-tabs": "^1.1.12",
+ "@tanstack/react-virtual": "^3.13.2",
"@tiptap/core": "^3.20.4",
"@tiptap/extension-placeholder": "^3.20.4",
"@tiptap/extension-task-item": "^3.20.4",
@@ -42,6 +44,7 @@
"i18next": "^25.8.4",
"lucide-react": "^0.518.0",
"object-assign": "^4.1.1",
+ "onnxruntime-node": "^1.21.0",
"ps-list": "^9.0.0",
"react": "^19.1.0",
"react-dom": "^19.1.0",
@@ -3615,6 +3618,33 @@
"@opentelemetry/api": "^1.8"
}
},
+ "node_modules/@qdrant/js-client-rest": {
+ "version": "1.17.0",
+ "resolved": "https://registry.npmjs.org/@qdrant/js-client-rest/-/js-client-rest-1.17.0.tgz",
+ "integrity": "sha512-aZFQeirWVqWAa1a8vJ957LMzcXkFHGbsoRhzc8AkGfg6V0jtK8PlG8/eyyc2xhYsR961FDDx1Tx6nyE0K7lS+A==",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "@qdrant/openapi-typescript-fetch": "1.2.6",
+ "undici": "^6.23.0"
+ },
+ "engines": {
+ "node": ">=18.17.0",
+ "pnpm": ">=8"
+ },
+ "peerDependencies": {
+ "typescript": ">=4.7"
+ }
+ },
+ "node_modules/@qdrant/openapi-typescript-fetch": {
+ "version": "1.2.6",
+ "resolved": "https://registry.npmjs.org/@qdrant/openapi-typescript-fetch/-/openapi-typescript-fetch-1.2.6.tgz",
+ "integrity": "sha512-oQG/FejNpItrxRHoyctYvT3rwGZOnK4jr3JdppO/c78ktDvkWiPXPHNsrDf33K9sZdRb6PR7gi4noIapu5q4HA==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=18.0.0",
+ "pnpm": ">=8"
+ }
+ },
"node_modules/@radix-ui/number": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/@radix-ui/number/-/number-1.1.1.tgz",
@@ -6653,6 +6683,33 @@
"react": "^18 || ^19"
}
},
+ "node_modules/@tanstack/react-virtual": {
+ "version": "3.13.23",
+ "resolved": "https://registry.npmjs.org/@tanstack/react-virtual/-/react-virtual-3.13.23.tgz",
+ "integrity": "sha512-XnMRnHQ23piOVj2bzJqHrRrLg4r+F86fuBcwteKfbIjJrtGxb4z7tIvPVAe4B+4UVwo9G4Giuz5fmapcrnZ0OQ==",
+ "license": "MIT",
+ "dependencies": {
+ "@tanstack/virtual-core": "3.13.23"
+ },
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/tannerlinsley"
+ },
+ "peerDependencies": {
+ "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0",
+ "react-dom": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0"
+ }
+ },
+ "node_modules/@tanstack/virtual-core": {
+ "version": "3.13.23",
+ "resolved": "https://registry.npmjs.org/@tanstack/virtual-core/-/virtual-core-3.13.23.tgz",
+ "integrity": "sha512-zSz2Z2HNyLjCplANTDyl3BcdQJc2k1+yyFoKhNRmCr7V7dY8o8q5m8uFTI1/Pg1kL+Hgrz6u3Xo6eFUB7l66cg==",
+ "license": "MIT",
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/tannerlinsley"
+ }
+ },
"node_modules/@tiptap/core": {
"version": "3.20.4",
"resolved": "https://registry.npmjs.org/@tiptap/core/-/core-3.20.4.tgz",
@@ -7929,6 +7986,15 @@
"acorn": "^6.0.0 || ^7.0.0 || ^8.0.0"
}
},
+ "node_modules/adm-zip": {
+ "version": "0.5.16",
+ "resolved": "https://registry.npmjs.org/adm-zip/-/adm-zip-0.5.16.tgz",
+ "integrity": "sha512-TGw5yVi4saajsSEgz25grObGHEUaDrniwvA2qwSC060KfqGPdglhvPMA2lPIoxs3PQIItj2iag35fONcQqgUaQ==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=12.0"
+ }
+ },
"node_modules/agent-base": {
"version": "7.1.4",
"resolved": "https://registry.npmjs.org/agent-base/-/agent-base-7.1.4.tgz",
@@ -8716,9 +8782,7 @@
"resolved": "https://registry.npmjs.org/boolean/-/boolean-3.2.0.tgz",
"integrity": "sha512-d0II/GO9uf9lfUHH2BQsjxzRJZBdsjgsBiW4BvhWk/3qoKwQFjIDVN19PfX8F2D/r9PCMTtLWjYVCFrpeYUzsw==",
"deprecated": "Package no longer supported. Contact Support at https://www.npmjs.com/support for more info.",
- "dev": true,
- "license": "MIT",
- "optional": true
+ "license": "MIT"
},
"node_modules/brace-expansion": {
"version": "2.0.2",
@@ -9664,9 +9728,7 @@
"version": "1.1.4",
"resolved": "https://registry.npmjs.org/define-data-property/-/define-data-property-1.1.4.tgz",
"integrity": "sha512-rBMvIzlpA8v6E+SJZoo++HAYqsLrkg7MSfIinMPFhmkorw7X+dOXVJQs+QT69zGkzMyfDnIMN2Wid1+NbL3T+A==",
- "dev": true,
"license": "MIT",
- "optional": true,
"dependencies": {
"es-define-property": "^1.0.0",
"es-errors": "^1.3.0",
@@ -9683,9 +9745,7 @@
"version": "1.2.1",
"resolved": "https://registry.npmjs.org/define-properties/-/define-properties-1.2.1.tgz",
"integrity": "sha512-8QmQKqEASLd5nx0U1B1okLElbUuuttJ/AnYmRXbbbGDWh6uS208EjD4Xqq/I9wK7u0v6O08XhTWnt5XtEbR6Dg==",
- "dev": true,
"license": "MIT",
- "optional": true,
"dependencies": {
"define-data-property": "^1.0.1",
"has-property-descriptors": "^1.0.0",
@@ -9763,9 +9823,7 @@
"version": "2.1.0",
"resolved": "https://registry.npmjs.org/detect-node/-/detect-node-2.1.0.tgz",
"integrity": "sha512-T0NIuQpnTvFDATNuHN5roPwSBG83rFsuO+MXXH9/3N1eFbn4wcPjttvjMLEPWJ0RGUYgQE7cGgS3tNxbqCGM7g==",
- "dev": true,
- "license": "MIT",
- "optional": true
+ "license": "MIT"
},
"node_modules/detect-node-es": {
"version": "1.1.0",
@@ -10430,7 +10488,6 @@
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.1.tgz",
"integrity": "sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==",
- "dev": true,
"license": "MIT",
"engines": {
"node": ">= 0.4"
@@ -10440,7 +10497,6 @@
"version": "1.3.0",
"resolved": "https://registry.npmjs.org/es-errors/-/es-errors-1.3.0.tgz",
"integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==",
- "dev": true,
"license": "MIT",
"engines": {
"node": ">= 0.4"
@@ -10479,9 +10535,7 @@
"version": "4.1.1",
"resolved": "https://registry.npmjs.org/es6-error/-/es6-error-4.1.1.tgz",
"integrity": "sha512-Um/+FxMr9CISWh0bi5Zv0iOD+4cFh5qLeks1qhAopKVAJw3drgKbKySikp7wGhDL0HPeaja0P5ULZrxLkniUVg==",
- "dev": true,
- "license": "MIT",
- "optional": true
+ "license": "MIT"
},
"node_modules/esbuild": {
"version": "0.25.12",
@@ -11601,9 +11655,7 @@
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/global-agent/-/global-agent-3.0.0.tgz",
"integrity": "sha512-PT6XReJ+D07JvGoxQMkT6qji/jVNfX/h364XHZOWeRzy64sSFr+xJ5OX7LI3b4MPQzdL4H8Y8M0xzPpsVMwA8Q==",
- "dev": true,
"license": "BSD-3-Clause",
- "optional": true,
"dependencies": {
"boolean": "^3.0.1",
"es6-error": "^4.1.1",
@@ -11633,9 +11685,7 @@
"version": "1.0.4",
"resolved": "https://registry.npmjs.org/globalthis/-/globalthis-1.0.4.tgz",
"integrity": "sha512-DpLKbNU4WylpxJykQujfCcwYWiV/Jhm50Goo0wrVILAv5jOr9d+H+UR3PhSCD2rCCEIg0uc+G+muBTwD54JhDQ==",
- "dev": true,
"license": "MIT",
- "optional": true,
"dependencies": {
"define-properties": "^1.2.1",
"gopd": "^1.0.1"
@@ -11651,7 +11701,6 @@
"version": "1.2.0",
"resolved": "https://registry.npmjs.org/gopd/-/gopd-1.2.0.tgz",
"integrity": "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==",
- "dev": true,
"license": "MIT",
"engines": {
"node": ">= 0.4"
@@ -11731,9 +11780,7 @@
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/has-property-descriptors/-/has-property-descriptors-1.0.2.tgz",
"integrity": "sha512-55JNKuIW+vq4Ke1BjOTjM2YctQIvCT7GFzHwmfZPGo5wnrgkid0YQtnAleFSqumZm4az3n2BS+erby5ipJdgrg==",
- "dev": true,
"license": "MIT",
- "optional": true,
"dependencies": {
"es-define-property": "^1.0.0"
},
@@ -12586,8 +12633,7 @@
"version": "5.0.1",
"resolved": "https://registry.npmjs.org/json-stringify-safe/-/json-stringify-safe-5.0.1.tgz",
"integrity": "sha512-ZClg6AaYvamvYEE82d3Iyd3vSSIjQ+odgjaTzRuO3s7toCdFKczob2i0zCh7JE8kWn17yvAWhUVxvqGwUalsRA==",
- "license": "ISC",
- "optional": true
+ "license": "ISC"
},
"node_modules/json5": {
"version": "2.2.3",
@@ -13206,9 +13252,7 @@
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/matcher/-/matcher-3.0.0.tgz",
"integrity": "sha512-OkeDaAZ/bQCxeFAozM55PKcKU0yJMPGifLwV4Qgjitu+5MoAfSQN4lsLJeXZ1b8w0x+/Emda6MZgXS1jvsapng==",
- "dev": true,
"license": "MIT",
- "optional": true,
"dependencies": {
"escape-string-regexp": "^4.0.0"
},
@@ -14479,9 +14523,7 @@
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/object-keys/-/object-keys-1.1.1.tgz",
"integrity": "sha512-NuAESUOUMrlIXOfHKzD6bpPu3tYt3xvjNdRIQ+FeT0lNb4K8WR70CaDxhuNguS2XG+GjkyMwOzsN5ZktImfhLA==",
- "dev": true,
"license": "MIT",
- "optional": true,
"engines": {
"node": ">= 0.4"
}
@@ -14526,6 +14568,29 @@
"url": "https://github.com/sponsors/sindresorhus"
}
},
+ "node_modules/onnxruntime-common": {
+ "version": "1.24.3",
+ "resolved": "https://registry.npmjs.org/onnxruntime-common/-/onnxruntime-common-1.24.3.tgz",
+ "integrity": "sha512-GeuPZO6U/LBJXvwdaqHbuUmoXiEdeCjWi/EG7Y1HNnDwJYuk6WUbNXpF6luSUY8yASul3cmUlLGrCCL1ZgVXqA==",
+ "license": "MIT"
+ },
+ "node_modules/onnxruntime-node": {
+ "version": "1.24.3",
+ "resolved": "https://registry.npmjs.org/onnxruntime-node/-/onnxruntime-node-1.24.3.tgz",
+ "integrity": "sha512-JH7+czbc8ALA819vlTgcV+Q214/+VjGeBHDjX81+ZCD0PCVCIFGFNtT0V4sXG/1JXypKPgScQcB3ij/hk3YnTg==",
+ "hasInstallScript": true,
+ "license": "MIT",
+ "os": [
+ "win32",
+ "darwin",
+ "linux"
+ ],
+ "dependencies": {
+ "adm-zip": "^0.5.16",
+ "global-agent": "^3.0.0",
+ "onnxruntime-common": "1.24.3"
+ }
+ },
"node_modules/openapi-types": {
"version": "12.1.3",
"resolved": "https://registry.npmjs.org/openapi-types/-/openapi-types-12.1.3.tgz",
@@ -16261,9 +16326,7 @@
"version": "2.15.4",
"resolved": "https://registry.npmjs.org/roarr/-/roarr-2.15.4.tgz",
"integrity": "sha512-CHhPh+UNHD2GTXNYhPWLnU8ONHdI+5DI+4EYIAOaiD63rHeYlZvyh8P+in5999TTSFgUYuKUAjzRI4mdh/p+2A==",
- "dev": true,
"license": "BSD-3-Clause",
- "optional": true,
"dependencies": {
"boolean": "^3.0.1",
"detect-node": "^2.0.4",
@@ -16447,17 +16510,13 @@
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/semver-compare/-/semver-compare-1.0.0.tgz",
"integrity": "sha512-YM3/ITh2MJ5MtzaM429anh+x2jiLVjqILF4m4oyQB18W7Ggea7BfqdH/wGMK7dDiMghv/6WG7znWMwUDzJiXow==",
- "dev": true,
- "license": "MIT",
- "optional": true
+ "license": "MIT"
},
"node_modules/serialize-error": {
"version": "7.0.1",
"resolved": "https://registry.npmjs.org/serialize-error/-/serialize-error-7.0.1.tgz",
"integrity": "sha512-8I8TjW5KMOKsZQTvoxjuSIa7foAwPWGOts+6o7sgjz41/qMD9VQHEDxi6PBvK2l0MXUmqZyNpUK+T2tQaaElvw==",
- "dev": true,
"license": "MIT",
- "optional": true,
"dependencies": {
"type-fest": "^0.13.1"
},
@@ -16778,9 +16837,7 @@
"version": "1.1.3",
"resolved": "https://registry.npmjs.org/sprintf-js/-/sprintf-js-1.1.3.tgz",
"integrity": "sha512-Oo+0REFV59/rz3gfJNKQiBlwfHaSESl1pcGyABQsnnIfWOFt6JNj5gCog2U6MLZ//IGYD+nA8nI+mTShREReaA==",
- "dev": true,
- "license": "BSD-3-Clause",
- "optional": true
+ "license": "BSD-3-Clause"
},
"node_modules/sql-formatter": {
"version": "14.0.0",
@@ -17472,9 +17529,7 @@
"version": "0.13.1",
"resolved": "https://registry.npmjs.org/type-fest/-/type-fest-0.13.1.tgz",
"integrity": "sha512-34R7HTnG0XIJcBSn5XhDd7nNFPRcXYRZrBB2O2jdKqYODldSzBAqzsWoZYYvduky73toYS/ESqxPvkDf/F0XMg==",
- "dev": true,
"license": "(MIT OR CC0-1.0)",
- "optional": true,
"engines": {
"node": ">=10"
},
diff --git a/package.json b/package.json
index c7bb3e111..684fef926 100644
--- a/package.json
+++ b/package.json
@@ -113,6 +113,7 @@
"@qdrant/js-client-rest": "^1.12.0",
"@neondatabase/auth": "^0.1.0-beta.21",
"@neondatabase/neon-js": "^0.1.0-beta.22",
+ "@tanstack/react-virtual": "^3.13.2",
"@radix-ui/react-accordion": "^1.1.2",
"@radix-ui/react-dialog": "^1.1.14",
"@radix-ui/react-dropdown-menu": "^2.1.15",
diff --git a/preload.js b/preload.js
index 4d18e6a63..8c943cec0 100644
--- a/preload.js
+++ b/preload.js
@@ -612,6 +612,16 @@ contextBridge.exposeInMainWorld("electronAPI", {
addAgentMessage: (conversationId, role, content, metadata) =>
ipcRenderer.invoke("db-add-agent-message", conversationId, role, content, metadata),
getAgentMessages: (conversationId) => ipcRenderer.invoke("db-get-agent-messages", conversationId),
+ getAgentConversationsWithPreview: (limit, offset, includeArchived) =>
+ ipcRenderer.invoke("db-get-agent-conversations-with-preview", limit, offset, includeArchived),
+ searchAgentConversations: (query, limit) =>
+ ipcRenderer.invoke("db-search-agent-conversations", query, limit),
+ archiveAgentConversation: (id) => ipcRenderer.invoke("db-archive-agent-conversation", id),
+ unarchiveAgentConversation: (id) => ipcRenderer.invoke("db-unarchive-agent-conversation", id),
+ updateAgentConversationCloudId: (id, cloudId) =>
+ ipcRenderer.invoke("db-update-agent-conversation-cloud-id", id, cloudId),
+ semanticSearchConversations: (query, limit) =>
+ ipcRenderer.invoke("db-semantic-search-conversations", query, limit),
// Google Calendar
gcalStartOAuth: () => ipcRenderer.invoke("gcal-start-oauth"),
diff --git a/src/components/AgentOverlay.tsx b/src/components/AgentOverlay.tsx
index 938587fba..a0ed30b21 100644
--- a/src/components/AgentOverlay.tsx
+++ b/src/components/AgentOverlay.tsx
@@ -2,76 +2,55 @@ import { useState, useEffect, useRef, useCallback } from "react";
import { useTranslation } from "react-i18next";
import { cn } from "./lib/utils";
import { AgentTitleBar } from "./agent/AgentTitleBar";
-import { AgentChat, type Message } from "./agent/AgentChat";
+import { AgentChat } from "./agent/AgentChat";
import { AgentInput } from "./agent/AgentInput";
import AudioManager from "../helpers/audioManager";
-import ReasoningService, { type AgentStreamChunk } from "../services/ReasoningService";
-import { getSettings } from "../stores/settingsStore";
-import { getAgentSystemPrompt } from "../config/prompts";
-import { createToolRegistry } from "../services/tools";
-import type { ToolRegistry } from "../services/tools/ToolRegistry";
-
-type AgentState =
- | "idle"
- | "listening"
- | "transcribing"
- | "thinking"
- | "streaming"
- | "tool-executing";
+import { useChatPersistence } from "./chat/useChatPersistence";
+import { useChatStreaming } from "./chat/useChatStreaming";
+import type { Message } from "./chat/types";
const MIN_HEIGHT = 200;
const MIN_WIDTH = 360;
export default function AgentOverlay() {
const { t } = useTranslation();
- const [messages, setMessages] = useState<Message[]>([]);
- const [agentState, setAgentState] = useState<AgentState>("idle");
const [partialTranscript, setPartialTranscript] = useState("");
- const [toolStatus, setToolStatus] = useState("");
- const [activeToolName, setActiveToolName] = useState("");
const audioManagerRef = useRef<InstanceType<typeof AudioManager> | null>(null);
- const messagesRef = useRef<Message[]>([]);
- const agentStateRef = useRef<AgentState>("idle");
- const conversationIdRef = useRef<number | null>(null);
- const mountedRef = useRef(true);
- const toolRegistryRef = useRef<{ key: string; registry: ToolRegistry } | null>(null);
+ const agentStateRef = useRef<string>("idle");
- useEffect(() => {
- messagesRef.current = messages;
- }, [messages]);
+ const persistence = useChatPersistence();
+ const { messages, setMessages, handleNewChat: persistenceNewChat } = persistence;
+
+ const streaming = useChatStreaming({
+ messages,
+ setMessages,
+ onStreamComplete: (_assistantId, content, toolCalls) => {
+ persistence.saveAssistantMessage(content, toolCalls);
+ },
+ });
+
+ const { agentState, toolStatus, activeToolName } = streaming;
useEffect(() => {
agentStateRef.current = agentState;
}, [agentState]);
- useEffect(() => {
- mountedRef.current = true;
- return () => {
- mountedRef.current = false;
- ReasoningService.cancelActiveStream();
- };
- }, []);
-
- const addSystemMessage = useCallback((content: string) => {
- setMessages((prev) => [
- ...prev,
- { id: crypto.randomUUID(), role: "assistant" as const, content, isStreaming: false },
- ]);
- }, []);
+ const addSystemMessage = useCallback(
+ (content: string) => {
+ setMessages((prev) => [
+ ...prev,
+ { id: crypto.randomUUID(), role: "assistant" as const, content, isStreaming: false },
+ ]);
+ },
+ [setMessages]
+ );
const handleTranscriptionComplete = useCallback(
async (text: string) => {
- if (!text.trim()) {
- setAgentState("idle");
- return;
- }
+ if (!text.trim()) return;
- // Create conversation on first message
- if (!conversationIdRef.current) {
- const conv = await window.electronAPI?.createAgentConversation?.(
- t("agentMode.titleBar.newChat")
- );
- conversationIdRef.current = conv?.id ?? null;
+ if (!persistence.conversationId) {
+ await persistence.createConversation(t("agentMode.titleBar.newChat"));
}
const userMsg: Message = {
@@ -82,202 +61,16 @@ export default function AgentOverlay() {
};
setMessages((prev) => [...prev, userMsg]);
- if (conversationIdRef.current) {
- window.electronAPI?.addAgentMessage?.(conversationIdRef.current, "user", text);
- }
+ await persistence.saveUserMessage(text);
- // Auto-title after first user message
- const allMessages = messagesRef.current;
- if (conversationIdRef.current && allMessages.length === 0) {
+ if (persistence.conversationId && messages.length === 0) {
const title = text.slice(0, 50) + (text.length > 50 ? "..." : "");
- window.electronAPI?.updateAgentConversationTitle?.(conversationIdRef.current, title);
+ window.electronAPI?.updateAgentConversationTitle?.(persistence.conversationId, title);
}
- setAgentState("thinking");
-
- const settings = getSettings();
-
- const isCloudAgent = settings.isSignedIn && settings.cloudAgentMode === "openwhispr";
- const toolSupportedProviders = ["openai", "groq", "custom", "anthropic", "gemini"];
- const supportsTools = isCloudAgent || toolSupportedProviders.includes(settings.agentProvider);
-
- let registry: ToolRegistry | null = null;
- if (supportsTools) {
- const cacheKey = `${settings.isSignedIn}-${settings.gcalConnected}-${settings.cloudBackupEnabled}`;
- if (toolRegistryRef.current?.key === cacheKey) {
- registry = toolRegistryRef.current.registry;
- } else {
- registry = createToolRegistry({
- isSignedIn: settings.isSignedIn,
- gcalConnected: settings.gcalConnected,
- cloudBackupEnabled: settings.cloudBackupEnabled,
- });
- toolRegistryRef.current = { key: cacheKey, registry };
- }
- }
- const systemPrompt = getAgentSystemPrompt(registry?.getAll().map((t) => t.name));
-
- const llmMessages = [
- { role: "system", content: systemPrompt },
- ...[...allMessages, userMsg].slice(-20).map((m) => ({ role: m.role, content: m.content })),
- ];
-
- const assistantId = crypto.randomUUID();
- setMessages((prev) => [
- ...prev,
- { id: assistantId, role: "assistant", content: "", isStreaming: true },
- ]);
- setAgentState("streaming");
-
- try {
- let fullContent = "";
- let stream: AsyncGenerator<AgentStreamChunk>;
-
- if (isCloudAgent) {
- const executeToolCall = registry
- ? async (name: string, argsJson: string) => {
- const tool = registry.get(name);
- if (!tool)
- return {
- data: `Unknown tool: ${name}`,
- displayText: t("agentMode.tools.unknownTool", { name }),
- };
- let args: Record<string, unknown>;
- try {
- args = JSON.parse(argsJson);
- } catch {
- return {
- data: `Invalid tool arguments for ${name}`,
- displayText: t("agentMode.tools.invalidArgs", { name }),
- };
- }
- const result = await tool.execute(args);
- const data = result.success
- ? typeof result.data === "string"
- ? result.data
- : JSON.stringify(result.data)
- : result.displayText;
- const metadata =
- result.success && result.data && typeof result.data === "object"
- ? (result.data as Record<string, unknown>)
- : undefined;
- return { data, displayText: result.displayText, metadata };
- }
- : undefined;
-
- stream = ReasoningService.processTextStreamingCloud(llmMessages, {
- systemPrompt,
- tools: registry?.getAll().map((t) => ({
- name: t.name,
- description: t.description,
- parameters: t.parameters,
- })),
- executeToolCall,
- });
- } else {
- const aiTools = registry?.toAISDKFormat();
- stream = ReasoningService.processTextStreamingAI(
- llmMessages,
- settings.agentModel,
- settings.agentProvider,
- { systemPrompt },
- aiTools
- );
- }
-
- for await (const chunk of stream) {
- if (!mountedRef.current) {
- ReasoningService.cancelActiveStream();
- break;
- }
- if (chunk.type === "content") {
- fullContent += chunk.text;
- setMessages((prev) =>
- prev.map((m) => (m.id === assistantId ? { ...m, content: fullContent } : m))
- );
- } else if (chunk.type === "tool_calls") {
- for (const call of chunk.calls) {
- setAgentState("tool-executing");
- setActiveToolName(call.name);
- setToolStatus(
- t(`agentMode.tools.${call.name}Status`, { defaultValue: `Using ${call.name}...` })
- );
- setMessages((prev) =>
- prev.map((m) =>
- m.id === assistantId
- ? {
- ...m,
- toolCalls: [
- ...(m.toolCalls || []),
- {
- id: call.id,
- name: call.name,
- arguments: call.arguments,
- status: "executing" as const,
- },
- ],
- }
- : m
- )
- );
- }
- } else if (chunk.type === "tool_result") {
- setMessages((prev) =>
- prev.map((m) =>
- m.id === assistantId && m.toolCalls
- ? {
- ...m,
- toolCalls: m.toolCalls.map((tc) =>
- tc.id === chunk.callId
- ? {
- ...tc,
- status: "completed" as const,
- result: chunk.displayText,
- ...(chunk.metadata ? { metadata: chunk.metadata } : {}),
- }
- : tc
- ),
- }
- : m
- )
- );
- setAgentState("streaming");
- setToolStatus("");
- setActiveToolName("");
- }
- }
-
- setMessages((prev) =>
- prev.map((m) => (m.id === assistantId ? { ...m, isStreaming: false } : m))
- );
-
- if (conversationIdRef.current) {
- const finalMsg = messagesRef.current.find((m) => m.id === assistantId);
- const toolCalls = finalMsg?.toolCalls;
- window.electronAPI?.addAgentMessage?.(
- conversationIdRef.current,
- "assistant",
- fullContent,
- toolCalls?.length ? { toolCalls } : undefined
- );
- }
- } catch (error) {
- setMessages((prev) =>
- prev.map((m) =>
- m.id === assistantId
- ? {
- ...m,
- content: `${t("agentMode.chat.errorPrefix")}: ${(error as Error).message}`,
- isStreaming: false,
- }
- : m
- )
- );
- }
-
- setAgentState("idle");
+ await streaming.sendToAI(text, [...messages, userMsg]);
},
- [t]
+ [t, messages, setMessages, persistence, streaming]
);
useEffect(() => {
@@ -285,20 +78,10 @@ export default function AgentOverlay() {
am.setSkipReasoning(true);
am.setContext("agent");
am.setCallbacks({
- onStateChange: ({
- isRecording,
- isProcessing,
- }: {
- isRecording: boolean;
- isProcessing: boolean;
- }) => {
- if (isRecording) setAgentState("listening");
- else if (isProcessing) setAgentState("transcribing");
- },
+ onStateChange: () => {},
onError: (error: { message?: string }) => {
const msg = error?.message || (typeof error === "string" ? error : "Transcription failed");
addSystemMessage(`${t("agentMode.chat.errorPrefix")}: ${msg}`);
- setAgentState("idle");
},
onTranscriptionComplete: (result: { text: string }) => {
handleTranscriptionComplete(result.text);
@@ -313,6 +96,7 @@ export default function AgentOverlay() {
am.cleanup?.();
window.removeEventListener("api-key-changed", (am as any)._onApiKeyChanged);
};
+ // eslint-disable-next-line react-hooks/exhaustive-deps
}, [addSystemMessage, handleTranscriptionComplete]);
const handleResizeStart = useCallback((e: React.MouseEvent, direction: string) => {
@@ -400,14 +184,10 @@ export default function AgentOverlay() {
);
const handleNewChat = useCallback(() => {
- setMessages([]);
- setAgentState("idle");
+ persistenceNewChat();
setPartialTranscript("");
- setToolStatus("");
- setActiveToolName("");
- conversationIdRef.current = null;
- toolRegistryRef.current = null;
- }, []);
+ streaming.cancelStream();
+ }, [persistenceNewChat, streaming]);
const handleClose = useCallback(() => {
window.electronAPI?.hideAgentOverlay?.();
@@ -435,7 +215,7 @@ export default function AgentOverlay() {
/>
</div>
- {/* Resize handles — edges */}
+ {/* Resize handles -- edges */}
<div
className="absolute top-0 left-2 right-2 h-[5px] cursor-n-resize"
onMouseDown={(e) => handleResizeStart(e, "n")}
@@ -453,7 +233,7 @@ export default function AgentOverlay() {
onMouseDown={(e) => handleResizeStart(e, "e")}
/>
- {/* Resize handles — corners */}
+ {/* Resize handles -- corners */}
<div
className="absolute top-0 left-0 w-[10px] h-[10px] cursor-nw-resize"
onMouseDown={(e) => handleResizeStart(e, "nw")}
diff --git a/src/components/ControlPanel.tsx b/src/components/ControlPanel.tsx
index bf79438a7..a39ba3b32 100644
--- a/src/components/ControlPanel.tsx
+++ b/src/components/ControlPanel.tsx
@@ -33,6 +33,7 @@ const PersonalNotesView = React.lazy(() => import("./notes/PersonalNotesView"));
const DictionaryView = React.lazy(() => import("./DictionaryView"));
const UploadAudioView = React.lazy(() => import("./notes/UploadAudioView"));
const IntegrationsView = React.lazy(() => import("./IntegrationsView"));
+const ChatView = React.lazy(() => import("./chat/ChatView"));
const CommandSearch = React.lazy(() => import("./CommandSearch"));
export default function ControlPanel() {
@@ -732,6 +733,11 @@ export default function ControlPanel() {
}}
/>
)}
+ {activeView === "chat" && (
+ <Suspense fallback={null}>
+ <ChatView />
+ </Suspense>
+ )}
{activeView === "personal-notes" && (
<Suspense fallback={null}>
<PersonalNotesView
diff --git a/src/components/ControlPanelSidebar.tsx b/src/components/ControlPanelSidebar.tsx
index 2c092cb0b..60ba72fff 100644
--- a/src/components/ControlPanelSidebar.tsx
+++ b/src/components/ControlPanelSidebar.tsx
@@ -1,6 +1,7 @@
import React, { useState } from "react";
import {
Home,
+ MessageSquare,
NotebookPen,
BookOpen,
Upload,
@@ -20,7 +21,13 @@ import { getCachedPlatform } from "../utils/platform";
const platform = getCachedPlatform();
-export type ControlPanelView = "home" | "personal-notes" | "dictionary" | "upload" | "integrations";
+export type ControlPanelView =
+ | "home"
+ | "chat"
+ | "personal-notes"
+ | "dictionary"
+ | "upload"
+ | "integrations";
interface ControlPanelSidebarProps {
activeView: ControlPanelView;
@@ -78,6 +85,7 @@ export default function ControlPanelSidebar({
icon: React.ComponentType<{ size?: number; className?: string }>;
}[] = [
{ id: "home", label: t("sidebar.home"), icon: Home },
+ { id: "chat", label: t("sidebar.chat"), icon: MessageSquare },
{ id: "personal-notes", label: t("sidebar.notes"), icon: NotebookPen },
{ id: "upload", label: t("sidebar.upload"), icon: Upload },
{ id: "dictionary", label: t("sidebar.dictionary"), icon: BookOpen },
diff --git a/src/components/agent/AgentChat.tsx b/src/components/agent/AgentChat.tsx
index 5c37222e7..398b58a38 100644
--- a/src/components/agent/AgentChat.tsx
+++ b/src/components/agent/AgentChat.tsx
@@ -1,27 +1,11 @@
-import { useRef, useEffect } from "react";
import { Mic } from "lucide-react";
import { useTranslation } from "react-i18next";
-import { cn } from "../lib/utils";
-import { AgentMessage } from "./AgentMessage";
import { useSettingsStore } from "../../stores/settingsStore";
import { formatHotkeyLabel } from "../../utils/hotkeys";
+import { ChatMessages } from "../chat/ChatMessages";
+import type { Message } from "../chat/types";
-export interface ToolCallInfo {
- id: string;
- name: string;
- arguments: string;
- status: "executing" | "completed" | "error";
- result?: string;
- metadata?: Record<string, unknown>;
-}
-
-export interface Message {
- id: string;
- role: "user" | "assistant" | "tool";
- content: string;
- isStreaming: boolean;
- toolCalls?: ToolCallInfo[];
-}
+export type { Message, ToolCallInfo } from "../chat/types";
interface AgentChatProps {
messages: Message[];
@@ -29,20 +13,13 @@ interface AgentChatProps {
export function AgentChat({ messages }: AgentChatProps) {
const { t } = useTranslation();
- const scrollRef = useRef<HTMLDivElement>(null);
const agentKey = useSettingsStore((s) => s.agentKey);
const hotkeyLabel = formatHotkeyLabel(agentKey);
- useEffect(() => {
- const el = scrollRef.current;
- if (el) {
- el.scrollTop = el.scrollHeight;
- }
- }, [messages]);
-
return (
- <div ref={scrollRef} className={cn("flex-1 overflow-y-auto agent-chat-scroll", "px-3 py-2")}>
- {messages.length === 0 ? (
+ <ChatMessages
+ messages={messages}
+ emptyState={
<div className="flex flex-col items-center justify-center h-full gap-2 select-none">
<div
className="text-muted-foreground/30"
@@ -59,21 +36,7 @@ export function AgentChat({ messages }: AgentChatProps) {
</p>
</div>
</div>
- ) : (
- <div className="flex flex-col gap-1.5">
- {messages
- .filter((msg) => msg.role !== "tool")
- .map((msg) => (
- <AgentMessage
- key={msg.id}
- role={msg.role as "user" | "assistant"}
- content={msg.content}
- isStreaming={msg.isStreaming}
- toolCalls={msg.toolCalls}
- />
- ))}
- </div>
- )}
- </div>
+ }
+ />
);
}
diff --git a/src/components/agent/AgentInput.tsx b/src/components/agent/AgentInput.tsx
index 99aebc208..211e52a0b 100644
--- a/src/components/agent/AgentInput.tsx
+++ b/src/components/agent/AgentInput.tsx
@@ -1,27 +1,5 @@
-import { useState, useRef, useCallback } from "react";
-import {
- Mic,
- SendHorizontal,
- Search,
- Globe,
- ClipboardCheck,
- Calendar,
- FileText,
- FilePlus,
- FilePen,
-} from "lucide-react";
-import { useTranslation } from "react-i18next";
-import { cn } from "../lib/utils";
-import { useSettingsStore } from "../../stores/settingsStore";
-import { formatHotkeyLabel, isGlobeLikeHotkey } from "../../utils/hotkeys";
-
-type AgentState =
- | "idle"
- | "listening"
- | "transcribing"
- | "thinking"
- | "streaming"
- | "tool-executing";
+import { ChatInput } from "../chat/ChatInput";
+import type { AgentState } from "../chat/types";
interface AgentInputProps {
agentState: AgentState;
@@ -31,212 +9,6 @@ interface AgentInputProps {
onTextSubmit?: (text: string) => void;
}
-const toolIcons: Record<string, typeof Search> = {
- search_notes: Search,
- web_search: Globe,
- copy_to_clipboard: ClipboardCheck,
- get_calendar_events: Calendar,
- get_note: FileText,
- create_note: FilePlus,
- update_note: FilePen,
-};
-
-function Kbd({ children }: { children: React.ReactNode }) {
- return (
- <kbd
- className={cn(
- "inline-flex items-center justify-center",
- "min-w-5 h-4.5 px-1.5",
- "text-[10px] font-medium leading-none",
- "text-muted-foreground/70",
- "bg-foreground/6 border border-foreground/8",
- "rounded-sm",
- "shadow-[0_1px_0_0_rgba(0,0,0,0.04)]"
- )}
- >
- {children}
- </kbd>
- );
-}
-
-function HotkeyKeys({ hotkey }: { hotkey: string }) {
- const label = formatHotkeyLabel(hotkey);
-
- if (isGlobeLikeHotkey(hotkey) || !label.includes("+")) {
- return <Kbd>{label}</Kbd>;
- }
-
- const parts = label.split("+");
-
- return (
- <span className="inline-flex items-center gap-0.5">
- {parts.map((part, i) => (
- <Kbd key={i}>{part}</Kbd>
- ))}
- </span>
- );
-}
-
-function RecordingIndicator() {
- return (
- <div className="relative flex items-center justify-center w-5 h-5 shrink-0">
- <div className="absolute inset-0 rounded-full border-2 border-primary/40 animate-pulse" />
- <div className="w-2.5 h-2.5 rounded-full bg-primary" />
- </div>
- );
-}
-
-function ProcessingIndicator() {
- return (
- <div className="flex items-center justify-center w-5 h-5 shrink-0">
- <div className="flex items-center gap-0.5">
- {[0, 1, 2, 3].map((i) => (
- <div
- key={i}
- className="w-0.5 bg-accent rounded-full"
- style={{
- height: "8px",
- animation: `waveform-bar 0.6s ease-in-out ${i * 0.1}s infinite`,
- }}
- />
- ))}
- </div>
- </div>
- );
-}
-
-function ThinkingIndicator() {
- return (
- <div
- className="w-10 h-0.75 rounded-full shrink-0"
- style={{
- background: "linear-gradient(90deg, transparent, oklch(0.65 0.2 260 / 0.4), transparent)",
- backgroundSize: "200% 100%",
- animation: "tool-status-sweep 1.5s ease-in-out infinite",
- }}
- />
- );
-}
-
-export function AgentInput({
- agentState,
- partialTranscript,
- toolStatus,
- activeToolName,
- onTextSubmit,
-}: AgentInputProps) {
- const { t } = useTranslation();
- const agentKey = useSettingsStore((s) => s.agentKey);
- const [inputText, setInputText] = useState("");
- const inputRef = useRef<HTMLInputElement>(null);
-
- const handleSubmit = useCallback(() => {
- const text = inputText.trim();
- if (!text || !onTextSubmit) return;
- onTextSubmit(text);
- setInputText("");
- }, [inputText, onTextSubmit]);
-
- const handleKeyDown = useCallback(
- (e: React.KeyboardEvent<HTMLInputElement>) => {
- if (e.key === "Enter" && !e.shiftKey) {
- e.preventDefault();
- handleSubmit();
- }
- },
- [handleSubmit]
- );
-
- const isIdle = agentState === "idle";
- const ToolIcon = activeToolName ? toolIcons[activeToolName] : null;
-
- return (
- <div
- className={cn(
- "flex items-center gap-2 min-h-11 px-3 py-2 shrink-0",
- "bg-surface-1 border-t border-border/30"
- )}
- >
- {isIdle && (
- <div className="flex items-center gap-2 w-full">
- <input
- ref={inputRef}
- type="text"
- value={inputText}
- onChange={(e) => setInputText(e.target.value)}
- onKeyDown={handleKeyDown}
- placeholder={t("agentMode.input.typeMessage")}
- className={cn(
- "bg-transparent border-none outline-none flex-1",
- "text-[13px] text-foreground placeholder:text-muted-foreground/40",
- "min-w-0"
- )}
- />
- {inputText.trim() ? (
- <button
- onClick={handleSubmit}
- className={cn(
- "p-1 rounded-sm shrink-0",
- "text-primary hover:text-primary/80",
- "focus:outline-none focus-visible:ring-1 focus-visible:ring-ring/30",
- "transition-colors duration-100"
- )}
- >
- <SendHorizontal size={14} />
- </button>
- ) : (
- <div className="flex items-center gap-2 shrink-0">
- <div
- className="text-muted-foreground/50"
- style={{ animation: "agent-mic-pulse 2.5s ease-in-out infinite" }}
- >
- <Mic size={14} />
- </div>
- <HotkeyKeys hotkey={agentKey} />
- </div>
- )}
- </div>
- )}
-
- {agentState === "listening" && (
- <>
- <RecordingIndicator />
- <span className="text-[12px] text-foreground/80 truncate flex-1">
- {partialTranscript || t("agentMode.input.listening")}
- </span>
- </>
- )}
-
- {agentState === "transcribing" && (
- <>
- <ProcessingIndicator />
- <span className="text-[12px] text-muted-foreground select-none">
- {t("agentMode.input.transcribing")}
- </span>
- </>
- )}
-
- {(agentState === "thinking" || agentState === "streaming") && (
- <>
- <ThinkingIndicator />
- <span className="text-[12px] text-muted-foreground select-none">
- {t("agentMode.input.thinking")}
- </span>
- </>
- )}
-
- {agentState === "tool-executing" && (
- <>
- {ToolIcon ? (
- <ToolIcon size={12} className="text-primary/60 shrink-0" />
- ) : (
- <ThinkingIndicator />
- )}
- <span className="text-[12px] text-muted-foreground select-none truncate">
- {toolStatus || t("agentMode.input.thinking")}
- </span>
- </>
- )}
- </div>
- );
+export function AgentInput(props: AgentInputProps) {
+ return <ChatInput {...props} showHotkey={true} />;
}
diff --git a/src/components/agent/AgentMessage.tsx b/src/components/agent/AgentMessage.tsx
index 73524d0c9..306d0252c 100644
--- a/src/components/agent/AgentMessage.tsx
+++ b/src/components/agent/AgentMessage.tsx
@@ -1,289 +1 @@
-import { useState } from "react";
-import { useTranslation } from "react-i18next";
-import {
- Copy,
- Check,
- Search,
- Globe,
- ClipboardCheck,
- Calendar,
- FileText,
- FilePlus,
- FilePen,
- ChevronDown,
- ChevronRight,
- CircleAlert,
-} from "lucide-react";
-import { cn } from "../lib/utils";
-import { MarkdownRenderer } from "../ui/MarkdownRenderer";
-import type { ToolCallInfo } from "./AgentChat";
-
-interface AgentMessageProps {
- role: "user" | "assistant";
- content: string;
- isStreaming: boolean;
- toolCalls?: ToolCallInfo[];
-}
-
-const toolIcons: Record<string, typeof Search> = {
- search_notes: Search,
- web_search: Globe,
- copy_to_clipboard: ClipboardCheck,
- get_calendar_events: Calendar,
- get_note: FileText,
- create_note: FilePlus,
- update_note: FilePen,
-};
-
-const NOTE_TOOLS = new Set(["create_note", "update_note", "get_note"]);
-
-function ToolCallStep({ toolCall }: { toolCall: ToolCallInfo }) {
- const { t } = useTranslation();
- const [expanded, setExpanded] = useState(false);
- const Icon = toolIcons[toolCall.name] || Search;
- const isExecuting = toolCall.status === "executing";
- const isError = toolCall.status === "error";
- const isCompleted = toolCall.status === "completed";
- const isClipboard = toolCall.name === "copy_to_clipboard" && isCompleted;
-
- const resultLines = toolCall.result?.split("\n") ?? [];
- const hasDetail = resultLines.length > 1 && !isClipboard;
-
- return (
- <div
- className={cn(
- "relative rounded-md mb-1 overflow-hidden",
- "border-l-2 transition-colors duration-300",
- isExecuting && "border-l-primary/60",
- isCompleted && !isError && "border-l-muted-foreground/20",
- isClipboard && "border-l-emerald-500/50",
- isError && "border-l-destructive/50"
- )}
- >
- {isExecuting && (
- <div
- className="absolute inset-0 pointer-events-none"
- style={{ animation: "tool-step-shimmer 2s ease-in-out infinite" }}
- />
- )}
-
- <div
- className={cn(
- "flex items-center gap-1.5 px-2.5 py-1.5",
- "bg-surface-1/60",
- hasDetail && !isExecuting && "cursor-pointer"
- )}
- onClick={hasDetail && !isExecuting ? () => setExpanded((v) => !v) : undefined}
- >
- <Icon
- size={12}
- className={cn(
- "shrink-0 transition-colors duration-300",
- isExecuting && "text-primary/70",
- isCompleted && !isError && !isClipboard && "text-muted-foreground/50",
- isClipboard && "text-emerald-500/70",
- isError && "text-destructive/60"
- )}
- />
-
- {isExecuting ? (
- <span className="text-[11px] text-muted-foreground/80">
- {t(`agentMode.tools.${toolCall.name}Status`, { defaultValue: toolCall.name })}
- </span>
- ) : isError ? (
- <div className="flex items-center gap-1">
- <CircleAlert size={10} className="text-destructive/60 shrink-0" />
- <span className="text-[11px] text-destructive/70">
- {toolCall.result || toolCall.name}
- </span>
- </div>
- ) : isClipboard ? (
- <div className="flex items-center gap-1">
- <span className="text-[11px] text-emerald-600 dark:text-emerald-400/80">
- {t("agentMode.tools.copiedToClipboard")}
- </span>
- <Check
- size={10}
- className="text-emerald-500 shrink-0"
- style={{ animation: "tool-check-pop 300ms ease-out both" }}
- />
- </div>
- ) : (
- <span className="text-[11px] text-muted-foreground/70">
- {toolCall.result || toolCall.name}
- </span>
- )}
-
- {hasDetail && !isExecuting && (
- <ChevronDown
- size={10}
- className={cn(
- "ml-auto text-muted-foreground/40 shrink-0 transition-transform duration-200",
- expanded && "rotate-180"
- )}
- />
- )}
- </div>
-
- {hasDetail && !isExecuting && (
- <div
- className="overflow-hidden transition-all duration-200"
- style={{ maxHeight: expanded ? `${resultLines.length * 16 + 12}px` : "0px" }}
- >
- <pre className="text-[10px] text-muted-foreground/60 px-2.5 pb-1.5 whitespace-pre-wrap leading-tight">
- {toolCall.result}
- </pre>
- </div>
- )}
- </div>
- );
-}
-
-function NoteCard({ noteId, title }: { noteId: number; title: string }) {
- const { t } = useTranslation();
-
- return (
- <button
- onClick={() => window.electronAPI?.agentOpenNote?.(noteId)}
- className={cn(
- "flex items-center gap-2 w-full mt-2 px-2.5 py-2 rounded-md",
- "bg-primary/6 border border-primary/12",
- "hover:bg-primary/10 hover:border-primary/20",
- "active:scale-[0.99]",
- "transition-all duration-150",
- "text-left group/note"
- )}
- >
- <div className={cn("shrink-0 p-1 rounded", "bg-primary/10")}>
- <FileText size={12} className="text-primary/70" />
- </div>
- <div className="min-w-0 flex-1">
- <p className="text-[12px] font-medium text-foreground truncate">{title}</p>
- <p className="text-[10px] text-muted-foreground/50">{t("agentMode.tools.openNote")}</p>
- </div>
- <ChevronRight
- size={12}
- className="text-muted-foreground/30 group-hover/note:text-primary/50 shrink-0 transition-colors duration-150"
- />
- </button>
- );
-}
-
-function extractNoteCards(toolCalls?: ToolCallInfo[]): Array<{ noteId: number; title: string }> {
- if (!toolCalls) return [];
- const cards: Array<{ noteId: number; title: string }> = [];
- const seen = new Set<number>();
-
- for (const tc of toolCalls) {
- if (tc.status !== "completed" || !NOTE_TOOLS.has(tc.name) || !tc.metadata?.id) continue;
- const noteId = Number(tc.metadata.id);
- if (seen.has(noteId)) continue;
- seen.add(noteId);
- const title =
- (tc.metadata.title as string) ||
- tc.result?.replace(/^(Created|Updated|Retrieved) note: "(.+)"$/, "$2") ||
- "Note";
- cards.push({ noteId, title });
- }
- return cards;
-}
-
-export function AgentMessage({ role, content, isStreaming, toolCalls }: AgentMessageProps) {
- const [copied, setCopied] = useState(false);
-
- const handleCopy = async () => {
- try {
- await navigator.clipboard.writeText(content);
- setCopied(true);
- setTimeout(() => setCopied(false), 1500);
- } catch {
- // clipboard unavailable
- }
- };
-
- if (role === "user") {
- return (
- <div
- className="flex justify-end"
- style={{ animation: "agent-message-in 200ms ease-out both" }}
- >
- <div
- className={cn(
- "max-w-[80%] px-3 py-2 rounded-lg rounded-br-sm",
- "bg-primary/90 text-primary-foreground",
- "text-[13px] leading-relaxed"
- )}
- >
- {content}
- </div>
- </div>
- );
- }
-
- const hasToolCalls = toolCalls && toolCalls.length > 0;
- const hasContent = content.length > 0;
- const noteCards = extractNoteCards(toolCalls);
-
- return (
- <div
- className="group/msg flex justify-start"
- style={{ animation: "agent-message-in 200ms ease-out both" }}
- >
- <div
- className={cn(
- "relative max-w-[85%] px-3 py-2 rounded-lg rounded-bl-sm",
- "bg-surface-2 border border-border/30 text-foreground",
- "text-[13px] leading-relaxed"
- )}
- >
- {hasToolCalls && (
- <div
- className={cn(
- (hasContent || noteCards.length > 0) && "mb-2 pb-1.5 border-b border-border/15"
- )}
- >
- {toolCalls.map((tc) => (
- <ToolCallStep key={tc.id} toolCall={tc} />
- ))}
- </div>
- )}
-
- {hasContent && (
- <MarkdownRenderer
- content={content}
- className="text-[13px] leading-relaxed [&_p]:text-[13px] [&_li]:text-[13px]"
- />
- )}
-
- {isStreaming && (
- <span
- className="inline-block w-[2px] h-[14px] bg-foreground/70 align-middle ml-0.5"
- style={{ animation: "agent-cursor-blink 1s ease-in-out infinite" }}
- />
- )}
-
- {noteCards.length > 0 && !isStreaming && (
- <div>
- {noteCards.map((card) => (
- <NoteCard key={card.noteId} noteId={card.noteId} title={card.title} />
- ))}
- </div>
- )}
-
- {hasContent && !isStreaming && (
- <button
- onClick={handleCopy}
- className={cn(
- "absolute bottom-1.5 right-1.5 p-1 rounded-sm",
- "text-muted-foreground/40 hover:text-foreground hover:bg-foreground/8",
- "opacity-0 group-hover/msg:opacity-100 transition-all duration-150",
- "focus:outline-none focus-visible:ring-1 focus-visible:ring-ring/30"
- )}
- >
- {copied ? <Check size={12} className="text-emerald-500" /> : <Copy size={12} />}
- </button>
- )}
- </div>
- </div>
- );
-}
+export { ChatMessage as AgentMessage } from "../chat/ChatMessage";
diff --git a/src/components/chat/ChatHeader.tsx b/src/components/chat/ChatHeader.tsx
new file mode 100644
index 000000000..e61963faa
--- /dev/null
+++ b/src/components/chat/ChatHeader.tsx
@@ -0,0 +1,86 @@
+import { useState, useRef, useCallback } from "react";
+import { Plus } from "lucide-react";
+import { useTranslation } from "react-i18next";
+import { cn } from "../lib/utils";
+
+interface ChatHeaderProps {
+ title: string;
+ onTitleChange: (title: string) => void;
+ onNewChat: () => void;
+}
+
+export default function ChatHeader({ title, onTitleChange, onNewChat }: ChatHeaderProps) {
+ const { t } = useTranslation();
+ const [isEditing, setIsEditing] = useState(false);
+ const [editValue, setEditValue] = useState(title);
+ const inputRef = useRef<HTMLInputElement>(null);
+
+ const startEditing = useCallback(() => {
+ setEditValue(title);
+ setIsEditing(true);
+ requestAnimationFrame(() => inputRef.current?.select());
+ }, [title]);
+
+ const commitEdit = useCallback(() => {
+ setIsEditing(false);
+ const trimmed = editValue.trim();
+ if (trimmed && trimmed !== title) {
+ onTitleChange(trimmed);
+ }
+ }, [editValue, title, onTitleChange]);
+
+ const handleKeyDown = useCallback(
+ (e: React.KeyboardEvent) => {
+ if (e.key === "Enter") {
+ e.preventDefault();
+ commitEdit();
+ }
+ if (e.key === "Escape") {
+ setIsEditing(false);
+ setEditValue(title);
+ }
+ },
+ [commitEdit, title]
+ );
+
+ return (
+ <div className="flex items-center h-10 px-3 border-b border-border/20 shrink-0">
+ <div className="flex-1 min-w-0">
+ {isEditing ? (
+ <input
+ ref={inputRef}
+ value={editValue}
+ onChange={(e) => setEditValue(e.target.value)}
+ onBlur={commitEdit}
+ onKeyDown={handleKeyDown}
+ className={cn(
+ "w-full bg-transparent text-xs font-medium text-foreground",
+ "outline-none border-none appearance-none",
+ "rounded-sm focus-visible:ring-1 focus-visible:ring-primary/30 px-1 -mx-1"
+ )}
+ />
+ ) : (
+ <p
+ onDoubleClick={startEditing}
+ className="text-xs font-medium text-foreground truncate cursor-default"
+ title={t("chat.editTitle")}
+ >
+ {title}
+ </p>
+ )}
+ </div>
+ <button
+ onClick={onNewChat}
+ className={cn(
+ "p-1 rounded-sm shrink-0 ml-2",
+ "text-muted-foreground/60 hover:text-foreground hover:bg-foreground/8",
+ "transition-colors duration-150",
+ "focus:outline-none focus-visible:ring-1 focus-visible:ring-ring/30"
+ )}
+ aria-label={t("chat.newChat")}
+ >
+ <Plus size={14} />
+ </button>
+ </div>
+ );
+}
diff --git a/src/components/chat/ChatInput.tsx b/src/components/chat/ChatInput.tsx
new file mode 100644
index 000000000..53ba4d2aa
--- /dev/null
+++ b/src/components/chat/ChatInput.tsx
@@ -0,0 +1,237 @@
+import { useState, useRef, useCallback } from "react";
+import {
+ Mic,
+ SendHorizontal,
+ Search,
+ Globe,
+ ClipboardCheck,
+ Calendar,
+ FileText,
+ FilePlus,
+ FilePen,
+} from "lucide-react";
+import { useTranslation } from "react-i18next";
+import { cn } from "../lib/utils";
+import { useSettingsStore } from "../../stores/settingsStore";
+import { formatHotkeyLabel, isGlobeLikeHotkey } from "../../utils/hotkeys";
+import type { AgentState } from "./types";
+
+interface ChatInputProps {
+ agentState: AgentState;
+ partialTranscript: string;
+ toolStatus?: string;
+ activeToolName?: string;
+ onTextSubmit?: (text: string) => void;
+ showHotkey?: boolean;
+}
+
+const toolIcons: Record<string, typeof Search> = {
+ search_notes: Search,
+ web_search: Globe,
+ copy_to_clipboard: ClipboardCheck,
+ get_calendar_events: Calendar,
+ get_note: FileText,
+ create_note: FilePlus,
+ update_note: FilePen,
+};
+
+function Kbd({ children }: { children: React.ReactNode }) {
+ return (
+ <kbd
+ className={cn(
+ "inline-flex items-center justify-center",
+ "min-w-5 h-4.5 px-1.5",
+ "text-[10px] font-medium leading-none",
+ "text-muted-foreground/70",
+ "bg-foreground/6 border border-foreground/8",
+ "rounded-sm",
+ "shadow-[0_1px_0_0_rgba(0,0,0,0.04)]"
+ )}
+ >
+ {children}
+ </kbd>
+ );
+}
+
+function HotkeyKeys({ hotkey }: { hotkey: string }) {
+ const label = formatHotkeyLabel(hotkey);
+
+ if (isGlobeLikeHotkey(hotkey) || !label.includes("+")) {
+ return <Kbd>{label}</Kbd>;
+ }
+
+ const parts = label.split("+");
+
+ return (
+ <span className="inline-flex items-center gap-0.5">
+ {parts.map((part, i) => (
+ <Kbd key={i}>{part}</Kbd>
+ ))}
+ </span>
+ );
+}
+
+function RecordingIndicator() {
+ return (
+ <div className="relative flex items-center justify-center w-5 h-5 shrink-0">
+ <div className="absolute inset-0 rounded-full border-2 border-primary/40 animate-pulse" />
+ <div className="w-2.5 h-2.5 rounded-full bg-primary" />
+ </div>
+ );
+}
+
+function ProcessingIndicator() {
+ return (
+ <div className="flex items-center justify-center w-5 h-5 shrink-0">
+ <div className="flex items-center gap-0.5">
+ {[0, 1, 2, 3].map((i) => (
+ <div
+ key={i}
+ className="w-0.5 bg-accent rounded-full"
+ style={{
+ height: "8px",
+ animation: `waveform-bar 0.6s ease-in-out ${i * 0.1}s infinite`,
+ }}
+ />
+ ))}
+ </div>
+ </div>
+ );
+}
+
+function ThinkingIndicator() {
+ return (
+ <div
+ className="w-10 h-0.75 rounded-full shrink-0"
+ style={{
+ background: "linear-gradient(90deg, transparent, oklch(0.65 0.2 260 / 0.4), transparent)",
+ backgroundSize: "200% 100%",
+ animation: "tool-status-sweep 1.5s ease-in-out infinite",
+ }}
+ />
+ );
+}
+
+export function ChatInput({
+ agentState,
+ partialTranscript,
+ toolStatus,
+ activeToolName,
+ onTextSubmit,
+ showHotkey = false,
+}: ChatInputProps) {
+ const { t } = useTranslation();
+ const agentKey = useSettingsStore((s) => s.agentKey);
+ const [inputText, setInputText] = useState("");
+ const inputRef = useRef<HTMLInputElement>(null);
+
+ const handleSubmit = useCallback(() => {
+ const text = inputText.trim();
+ if (!text || !onTextSubmit) return;
+ onTextSubmit(text);
+ setInputText("");
+ }, [inputText, onTextSubmit]);
+
+ const handleKeyDown = useCallback(
+ (e: React.KeyboardEvent<HTMLInputElement>) => {
+ if (e.key === "Enter" && !e.shiftKey) {
+ e.preventDefault();
+ handleSubmit();
+ }
+ },
+ [handleSubmit]
+ );
+
+ const isIdle = agentState === "idle";
+ const ToolIcon = activeToolName ? toolIcons[activeToolName] : null;
+
+ return (
+ <div
+ className={cn(
+ "flex items-center gap-2 min-h-11 px-3 py-2 shrink-0",
+ "bg-surface-1 border-t border-border/30"
+ )}
+ >
+ {isIdle && (
+ <div className="flex items-center gap-2 w-full">
+ <input
+ ref={inputRef}
+ type="text"
+ value={inputText}
+ onChange={(e) => setInputText(e.target.value)}
+ onKeyDown={handleKeyDown}
+ placeholder={t("agentMode.input.typeMessage")}
+ className={cn(
+ "bg-transparent border-none outline-none flex-1",
+ "text-[13px] text-foreground placeholder:text-muted-foreground/40",
+ "min-w-0"
+ )}
+ />
+ {inputText.trim() ? (
+ <button
+ onClick={handleSubmit}
+ className={cn(
+ "p-1 rounded-sm shrink-0",
+ "text-primary hover:text-primary/80",
+ "focus:outline-none focus-visible:ring-1 focus-visible:ring-ring/30",
+ "transition-colors duration-100"
+ )}
+ >
+ <SendHorizontal size={14} />
+ </button>
+ ) : showHotkey ? (
+ <div className="flex items-center gap-2 shrink-0">
+ <div
+ className="text-muted-foreground/50"
+ style={{ animation: "agent-mic-pulse 2.5s ease-in-out infinite" }}
+ >
+ <Mic size={14} />
+ </div>
+ <HotkeyKeys hotkey={agentKey} />
+ </div>
+ ) : null}
+ </div>
+ )}
+
+ {agentState === "listening" && (
+ <>
+ <RecordingIndicator />
+ <span className="text-[12px] text-foreground/80 truncate flex-1">
+ {partialTranscript || t("agentMode.input.listening")}
+ </span>
+ </>
+ )}
+
+ {agentState === "transcribing" && (
+ <>
+ <ProcessingIndicator />
+ <span className="text-[12px] text-muted-foreground select-none">
+ {t("agentMode.input.transcribing")}
+ </span>
+ </>
+ )}
+
+ {(agentState === "thinking" || agentState === "streaming") && (
+ <>
+ <ThinkingIndicator />
+ <span className="text-[12px] text-muted-foreground select-none">
+ {t("agentMode.input.thinking")}
+ </span>
+ </>
+ )}
+
+ {agentState === "tool-executing" && (
+ <>
+ {ToolIcon ? (
+ <ToolIcon size={12} className="text-primary/60 shrink-0" />
+ ) : (
+ <ThinkingIndicator />
+ )}
+ <span className="text-[12px] text-muted-foreground select-none truncate">
+ {toolStatus || t("agentMode.input.thinking")}
+ </span>
+ </>
+ )}
+ </div>
+ );
+}
diff --git a/src/components/chat/ChatMessage.tsx b/src/components/chat/ChatMessage.tsx
new file mode 100644
index 000000000..a1b50606e
--- /dev/null
+++ b/src/components/chat/ChatMessage.tsx
@@ -0,0 +1,289 @@
+import { useState } from "react";
+import { useTranslation } from "react-i18next";
+import {
+ Copy,
+ Check,
+ Search,
+ Globe,
+ ClipboardCheck,
+ Calendar,
+ FileText,
+ FilePlus,
+ FilePen,
+ ChevronDown,
+ ChevronRight,
+ CircleAlert,
+} from "lucide-react";
+import { cn } from "../lib/utils";
+import { MarkdownRenderer } from "../ui/MarkdownRenderer";
+import type { ToolCallInfo } from "./types";
+
+interface ChatMessageProps {
+ role: "user" | "assistant";
+ content: string;
+ isStreaming: boolean;
+ toolCalls?: ToolCallInfo[];
+}
+
+const toolIcons: Record<string, typeof Search> = {
+ search_notes: Search,
+ web_search: Globe,
+ copy_to_clipboard: ClipboardCheck,
+ get_calendar_events: Calendar,
+ get_note: FileText,
+ create_note: FilePlus,
+ update_note: FilePen,
+};
+
+const NOTE_TOOLS = new Set(["create_note", "update_note", "get_note"]);
+
+function ToolCallStep({ toolCall }: { toolCall: ToolCallInfo }) {
+ const { t } = useTranslation();
+ const [expanded, setExpanded] = useState(false);
+ const Icon = toolIcons[toolCall.name] || Search;
+ const isExecuting = toolCall.status === "executing";
+ const isError = toolCall.status === "error";
+ const isCompleted = toolCall.status === "completed";
+ const isClipboard = toolCall.name === "copy_to_clipboard" && isCompleted;
+
+ const resultLines = toolCall.result?.split("\n") ?? [];
+ const hasDetail = resultLines.length > 1 && !isClipboard;
+
+ return (
+ <div
+ className={cn(
+ "relative rounded-md mb-1 overflow-hidden",
+ "border-l-2 transition-colors duration-300",
+ isExecuting && "border-l-primary/60",
+ isCompleted && !isError && "border-l-muted-foreground/20",
+ isClipboard && "border-l-emerald-500/50",
+ isError && "border-l-destructive/50"
+ )}
+ >
+ {isExecuting && (
+ <div
+ className="absolute inset-0 pointer-events-none"
+ style={{ animation: "tool-step-shimmer 2s ease-in-out infinite" }}
+ />
+ )}
+
+ <div
+ className={cn(
+ "flex items-center gap-1.5 px-2.5 py-1.5",
+ "bg-surface-1/60",
+ hasDetail && !isExecuting && "cursor-pointer"
+ )}
+ onClick={hasDetail && !isExecuting ? () => setExpanded((v) => !v) : undefined}
+ >
+ <Icon
+ size={12}
+ className={cn(
+ "shrink-0 transition-colors duration-300",
+ isExecuting && "text-primary/70",
+ isCompleted && !isError && !isClipboard && "text-muted-foreground/50",
+ isClipboard && "text-emerald-500/70",
+ isError && "text-destructive/60"
+ )}
+ />
+
+ {isExecuting ? (
+ <span className="text-[11px] text-muted-foreground/80">
+ {t(`agentMode.tools.${toolCall.name}Status`, { defaultValue: toolCall.name })}
+ </span>
+ ) : isError ? (
+ <div className="flex items-center gap-1">
+ <CircleAlert size={10} className="text-destructive/60 shrink-0" />
+ <span className="text-[11px] text-destructive/70">
+ {toolCall.result || toolCall.name}
+ </span>
+ </div>
+ ) : isClipboard ? (
+ <div className="flex items-center gap-1">
+ <span className="text-[11px] text-emerald-600 dark:text-emerald-400/80">
+ {t("agentMode.tools.copiedToClipboard")}
+ </span>
+ <Check
+ size={10}
+ className="text-emerald-500 shrink-0"
+ style={{ animation: "tool-check-pop 300ms ease-out both" }}
+ />
+ </div>
+ ) : (
+ <span className="text-[11px] text-muted-foreground/70">
+ {toolCall.result || toolCall.name}
+ </span>
+ )}
+
+ {hasDetail && !isExecuting && (
+ <ChevronDown
+ size={10}
+ className={cn(
+ "ml-auto text-muted-foreground/40 shrink-0 transition-transform duration-200",
+ expanded && "rotate-180"
+ )}
+ />
+ )}
+ </div>
+
+ {hasDetail && !isExecuting && (
+ <div
+ className="overflow-hidden transition-all duration-200"
+ style={{ maxHeight: expanded ? `${resultLines.length * 16 + 12}px` : "0px" }}
+ >
+ <pre className="text-[10px] text-muted-foreground/60 px-2.5 pb-1.5 whitespace-pre-wrap leading-tight">
+ {toolCall.result}
+ </pre>
+ </div>
+ )}
+ </div>
+ );
+}
+
+function NoteCard({ noteId, title }: { noteId: number; title: string }) {
+ const { t } = useTranslation();
+
+ return (
+ <button
+ onClick={() => window.electronAPI?.agentOpenNote?.(noteId)}
+ className={cn(
+ "flex items-center gap-2 w-full mt-2 px-2.5 py-2 rounded-md",
+ "bg-primary/6 border border-primary/12",
+ "hover:bg-primary/10 hover:border-primary/20",
+ "active:scale-[0.99]",
+ "transition-all duration-150",
+ "text-left group/note"
+ )}
+ >
+ <div className={cn("shrink-0 p-1 rounded", "bg-primary/10")}>
+ <FileText size={12} className="text-primary/70" />
+ </div>
+ <div className="min-w-0 flex-1">
+ <p className="text-[12px] font-medium text-foreground truncate">{title}</p>
+ <p className="text-[10px] text-muted-foreground/50">{t("agentMode.tools.openNote")}</p>
+ </div>
+ <ChevronRight
+ size={12}
+ className="text-muted-foreground/30 group-hover/note:text-primary/50 shrink-0 transition-colors duration-150"
+ />
+ </button>
+ );
+}
+
+function extractNoteCards(toolCalls?: ToolCallInfo[]): Array<{ noteId: number; title: string }> {
+ if (!toolCalls) return [];
+ const cards: Array<{ noteId: number; title: string }> = [];
+ const seen = new Set<number>();
+
+ for (const tc of toolCalls) {
+ if (tc.status !== "completed" || !NOTE_TOOLS.has(tc.name) || !tc.metadata?.id) continue;
+ const noteId = Number(tc.metadata.id);
+ if (seen.has(noteId)) continue;
+ seen.add(noteId);
+ const title =
+ (tc.metadata.title as string) ||
+ tc.result?.replace(/^(Created|Updated|Retrieved) note: "(.+)"$/, "$2") ||
+ "Note";
+ cards.push({ noteId, title });
+ }
+ return cards;
+}
+
+export function ChatMessage({ role, content, isStreaming, toolCalls }: ChatMessageProps) {
+ const [copied, setCopied] = useState(false);
+
+ const handleCopy = async () => {
+ try {
+ await navigator.clipboard.writeText(content);
+ setCopied(true);
+ setTimeout(() => setCopied(false), 1500);
+ } catch {
+ // clipboard unavailable
+ }
+ };
+
+ if (role === "user") {
+ return (
+ <div
+ className="flex justify-end"
+ style={{ animation: "agent-message-in 200ms ease-out both" }}
+ >
+ <div
+ className={cn(
+ "max-w-[80%] px-3 py-2 rounded-lg rounded-br-sm",
+ "bg-primary/90 text-primary-foreground",
+ "text-[13px] leading-relaxed"
+ )}
+ >
+ {content}
+ </div>
+ </div>
+ );
+ }
+
+ const hasToolCalls = toolCalls && toolCalls.length > 0;
+ const hasContent = content.length > 0;
+ const noteCards = extractNoteCards(toolCalls);
+
+ return (
+ <div
+ className="group/msg flex justify-start"
+ style={{ animation: "agent-message-in 200ms ease-out both" }}
+ >
+ <div
+ className={cn(
+ "relative max-w-[85%] px-3 py-2 rounded-lg rounded-bl-sm",
+ "bg-surface-2 border border-border/30 text-foreground",
+ "text-[13px] leading-relaxed"
+ )}
+ >
+ {hasToolCalls && (
+ <div
+ className={cn(
+ (hasContent || noteCards.length > 0) && "mb-2 pb-1.5 border-b border-border/15"
+ )}
+ >
+ {toolCalls.map((tc) => (
+ <ToolCallStep key={tc.id} toolCall={tc} />
+ ))}
+ </div>
+ )}
+
+ {hasContent && (
+ <MarkdownRenderer
+ content={content}
+ className="text-[13px] leading-relaxed [&_p]:text-[13px] [&_li]:text-[13px]"
+ />
+ )}
+
+ {isStreaming && (
+ <span
+ className="inline-block w-[2px] h-[14px] bg-foreground/70 align-middle ml-0.5"
+ style={{ animation: "agent-cursor-blink 1s ease-in-out infinite" }}
+ />
+ )}
+
+ {noteCards.length > 0 && !isStreaming && (
+ <div>
+ {noteCards.map((card) => (
+ <NoteCard key={card.noteId} noteId={card.noteId} title={card.title} />
+ ))}
+ </div>
+ )}
+
+ {hasContent && !isStreaming && (
+ <button
+ onClick={handleCopy}
+ className={cn(
+ "absolute bottom-1.5 right-1.5 p-1 rounded-sm",
+ "text-muted-foreground/40 hover:text-foreground hover:bg-foreground/8",
+ "opacity-0 group-hover/msg:opacity-100 transition-all duration-150",
+ "focus:outline-none focus-visible:ring-1 focus-visible:ring-ring/30"
+ )}
+ >
+ {copied ? <Check size={12} className="text-emerald-500" /> : <Copy size={12} />}
+ </button>
+ )}
+ </div>
+ </div>
+ );
+}
diff --git a/src/components/chat/ChatMessages.tsx b/src/components/chat/ChatMessages.tsx
new file mode 100644
index 000000000..297990eed
--- /dev/null
+++ b/src/components/chat/ChatMessages.tsx
@@ -0,0 +1,42 @@
+import { useRef, useEffect } from "react";
+import { cn } from "../lib/utils";
+import { ChatMessage } from "./ChatMessage";
+import type { Message } from "./types";
+
+interface ChatMessagesProps {
+ messages: Message[];
+ emptyState?: React.ReactNode;
+}
+
+export function ChatMessages({ messages, emptyState }: ChatMessagesProps) {
+ const scrollRef = useRef<HTMLDivElement>(null);
+
+ useEffect(() => {
+ const el = scrollRef.current;
+ if (el) {
+ el.scrollTop = el.scrollHeight;
+ }
+ }, [messages]);
+
+ return (
+ <div ref={scrollRef} className={cn("flex-1 overflow-y-auto agent-chat-scroll", "px-3 py-2")}>
+ {messages.length === 0 ? (
+ (emptyState ?? null)
+ ) : (
+ <div className="flex flex-col gap-1.5">
+ {messages
+ .filter((msg) => msg.role !== "tool")
+ .map((msg) => (
+ <ChatMessage
+ key={msg.id}
+ role={msg.role as "user" | "assistant"}
+ content={msg.content}
+ isStreaming={msg.isStreaming}
+ toolCalls={msg.toolCalls}
+ />
+ ))}
+ </div>
+ )}
+ </div>
+ );
+}
diff --git a/src/components/chat/ChatView.tsx b/src/components/chat/ChatView.tsx
new file mode 100644
index 000000000..9216ebdfd
--- /dev/null
+++ b/src/components/chat/ChatView.tsx
@@ -0,0 +1,171 @@
+import { useState, useCallback, useEffect } from "react";
+import { useTranslation } from "react-i18next";
+import { useChatPersistence } from "./useChatPersistence";
+import { useChatStreaming } from "./useChatStreaming";
+import { ChatMessages } from "./ChatMessages";
+import { ChatInput } from "./ChatInput";
+import ChatHeader from "./ChatHeader";
+import ConversationList from "./ConversationList";
+import EmptyChatState from "./EmptyChatState";
+import { ConfirmDialog } from "../ui/dialog";
+import { useDialogs } from "../../hooks/useDialogs";
+import { getCachedPlatform } from "../../utils/platform";
+
+const platform = getCachedPlatform();
+
+export default function ChatView() {
+ const { t } = useTranslation();
+ const [activeConversationId, setActiveConversationId] = useState<number | null>(null);
+ const [activeTitle, setActiveTitle] = useState("Untitled");
+ const [refreshKey, setRefreshKey] = useState(0);
+ const { confirmDialog, showConfirmDialog, hideConfirmDialog } = useDialogs();
+
+ const persistence = useChatPersistence({
+ conversationId: activeConversationId,
+ onConversationCreated: (id, title) => {
+ setActiveConversationId(id);
+ setActiveTitle(title);
+ setRefreshKey((k) => k + 1);
+ },
+ });
+
+ const streaming = useChatStreaming({
+ messages: persistence.messages,
+ setMessages: persistence.setMessages,
+ onStreamComplete: (_id, content, toolCalls) => {
+ persistence.saveAssistantMessage(content, toolCalls);
+ },
+ });
+
+ const handleSelectConversation = useCallback(
+ async (id: number, title: string) => {
+ if (id === activeConversationId) return;
+ setActiveConversationId(id);
+ setActiveTitle(title);
+ await persistence.loadConversation(id);
+ },
+ [activeConversationId, persistence]
+ );
+
+ const handleNewChat = useCallback(() => {
+ setActiveConversationId(null);
+ setActiveTitle("Untitled");
+ persistence.handleNewChat();
+ }, [persistence]);
+
+ const handleTextSubmit = useCallback(
+ async (text: string) => {
+ let convId = activeConversationId;
+ if (!convId) {
+ const title = text.length > 50 ? `${text.slice(0, 50)}...` : text;
+ convId = await persistence.createConversation(title);
+ setActiveTitle(title);
+ }
+
+ const userMsg = {
+ id: crypto.randomUUID(),
+ role: "user" as const,
+ content: text,
+ isStreaming: false,
+ };
+ persistence.setMessages((prev) => [...prev, userMsg]);
+ persistence.saveUserMessage(text);
+
+ const allMessages = [...persistence.messages, userMsg];
+ streaming.sendToAI(text, allMessages);
+ },
+ [activeConversationId, persistence, streaming]
+ );
+
+ const handleTitleChange = useCallback(
+ async (title: string) => {
+ if (!activeConversationId) return;
+ setActiveTitle(title);
+ await window.electronAPI?.updateAgentConversationTitle?.(activeConversationId, title);
+ setRefreshKey((k) => k + 1);
+ },
+ [activeConversationId]
+ );
+
+ const handleArchive = useCallback(async (_id: number) => {
+ // Archive not yet supported in the DB API
+ }, []);
+
+ const handleDelete = useCallback(
+ (id: number) => {
+ showConfirmDialog({
+ title: t("chat.delete"),
+ description: t("chat.deleteConfirm"),
+ onConfirm: async () => {
+ await window.electronAPI?.deleteAgentConversation?.(id);
+ if (activeConversationId === id) {
+ handleNewChat();
+ }
+ setRefreshKey((k) => k + 1);
+ },
+ variant: "destructive",
+ });
+ },
+ [activeConversationId, handleNewChat, showConfirmDialog, t]
+ );
+
+ useEffect(() => {
+ const handleKeyDown = (e: KeyboardEvent) => {
+ const mod = platform === "darwin" ? e.metaKey : e.ctrlKey;
+ if (mod && e.key === "n") {
+ e.preventDefault();
+ handleNewChat();
+ }
+ };
+ window.addEventListener("keydown", handleKeyDown);
+ return () => window.removeEventListener("keydown", handleKeyDown);
+ }, [handleNewChat]);
+
+ const hasActiveChat = activeConversationId !== null || persistence.messages.length > 0;
+
+ return (
+ <>
+ <ConfirmDialog
+ open={confirmDialog.open}
+ onOpenChange={hideConfirmDialog}
+ title={confirmDialog.title}
+ description={confirmDialog.description}
+ onConfirm={confirmDialog.onConfirm}
+ variant={confirmDialog.variant}
+ />
+ <div className="flex h-full">
+ <div className="w-56 min-w-50 shrink-0 border-r border-border/15 dark:border-white/6">
+ <ConversationList
+ activeConversationId={activeConversationId}
+ onSelectConversation={handleSelectConversation}
+ onNewChat={handleNewChat}
+ onArchive={handleArchive}
+ onDelete={handleDelete}
+ refreshKey={refreshKey}
+ />
+ </div>
+ <div className="flex-1 min-w-80 flex flex-col">
+ {hasActiveChat ? (
+ <>
+ <ChatHeader
+ title={activeTitle}
+ onTitleChange={handleTitleChange}
+ onNewChat={handleNewChat}
+ />
+ <ChatMessages messages={persistence.messages} />
+ <ChatInput
+ agentState={streaming.agentState}
+ partialTranscript=""
+ toolStatus={streaming.toolStatus}
+ activeToolName={streaming.activeToolName}
+ onTextSubmit={handleTextSubmit}
+ />
+ </>
+ ) : (
+ <EmptyChatState />
+ )}
+ </div>
+ </div>
+ </>
+ );
+}
diff --git a/src/components/chat/ConversationDateGroup.tsx b/src/components/chat/ConversationDateGroup.tsx
new file mode 100644
index 000000000..b73c720dc
--- /dev/null
+++ b/src/components/chat/ConversationDateGroup.tsx
@@ -0,0 +1,19 @@
+import { cn } from "../lib/utils";
+
+interface ConversationDateGroupProps {
+ label: string;
+}
+
+export default function ConversationDateGroup({ label }: ConversationDateGroupProps) {
+ return (
+ <div
+ className={cn(
+ "px-3 pt-3 pb-1",
+ "text-[10px] font-semibold text-muted-foreground/40 uppercase tracking-wider",
+ "select-none"
+ )}
+ >
+ {label}
+ </div>
+ );
+}
diff --git a/src/components/chat/ConversationItem.tsx b/src/components/chat/ConversationItem.tsx
new file mode 100644
index 000000000..f0c2a7036
--- /dev/null
+++ b/src/components/chat/ConversationItem.tsx
@@ -0,0 +1,133 @@
+import { useTranslation } from "react-i18next";
+import { MoreHorizontal, Archive, ArchiveRestore, Trash2 } from "lucide-react";
+import { Button } from "../ui/button";
+import {
+ DropdownMenu,
+ DropdownMenuTrigger,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuSeparator,
+} from "../ui/dropdown-menu";
+import { cn } from "../lib/utils";
+import { normalizeDbDate } from "../../utils/dateFormatting";
+
+export interface ConversationPreview {
+ id: number;
+ title: string;
+ preview?: string;
+ created_at: string;
+ updated_at: string;
+ is_archived?: boolean;
+}
+
+interface ConversationItemProps {
+ conversation: ConversationPreview;
+ isActive: boolean;
+ onClick: () => void;
+ onArchive: (id: number) => void;
+ onDelete: (id: number) => void;
+}
+
+function formatTimestamp(dateStr: string): string {
+ const date = normalizeDbDate(dateStr);
+ if (Number.isNaN(date.getTime())) return "";
+ const now = new Date();
+ const diff = now.getTime() - date.getTime();
+ const minutes = Math.floor(diff / 60000);
+ const hours = Math.floor(diff / 3600000);
+ const days = Math.floor(diff / 86400000);
+
+ if (minutes < 1) return "now";
+ 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" });
+}
+
+export default function ConversationItem({
+ conversation,
+ isActive,
+ onClick,
+ onArchive,
+ onDelete,
+}: ConversationItemProps) {
+ const { t } = useTranslation();
+ const isArchived = !!conversation.is_archived;
+
+ return (
+ <button
+ type="button"
+ onClick={onClick}
+ className={cn(
+ "group relative w-full text-left px-3 py-2 cursor-pointer transition-all duration-150",
+ "focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring/30",
+ isActive ? "bg-primary/8 dark:bg-primary/10" : "hover:bg-foreground/4 dark:hover:bg-white/4"
+ )}
+ >
+ {isActive && (
+ <div className="absolute left-0 top-1/2 -translate-y-1/2 w-0.5 h-4 rounded-r-full bg-primary" />
+ )}
+ <div className="flex-1 min-w-0">
+ <div className="flex items-center justify-between gap-2">
+ <p className={cn("text-xs truncate text-foreground", isActive && "font-medium")}>
+ {conversation.title}
+ </p>
+ <div className="flex items-center gap-0.5 shrink-0">
+ <span className="text-[10px] text-muted-foreground/40 tabular-nums group-hover:opacity-0 transition-opacity">
+ {formatTimestamp(conversation.updated_at)}
+ </span>
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <Button
+ size="icon"
+ variant="ghost"
+ onClick={(e) => e.stopPropagation()}
+ className="h-5 w-5 rounded-sm opacity-0 group-hover:opacity-100 data-[state=open]:opacity-100 transition-opacity absolute right-2 text-muted-foreground/60 dark:text-muted-foreground/40 hover:text-foreground/60 hover:bg-foreground/5 active:bg-foreground/8"
+ >
+ <MoreHorizontal size={12} />
+ </Button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end" sideOffset={4} className="min-w-36">
+ <DropdownMenuItem
+ onClick={(e) => {
+ e.stopPropagation();
+ onArchive(conversation.id);
+ }}
+ className="text-xs gap-2 rounded-lg px-2.5 py-1.5 cursor-pointer focus:bg-foreground/5"
+ >
+ {isArchived ? (
+ <>
+ <ArchiveRestore size={12} className="text-muted-foreground/80" />
+ {t("chat.unarchive")}
+ </>
+ ) : (
+ <>
+ <Archive size={12} className="text-muted-foreground/80" />
+ {t("chat.archive")}
+ </>
+ )}
+ </DropdownMenuItem>
+ <DropdownMenuSeparator />
+ <DropdownMenuItem
+ onClick={(e) => {
+ e.stopPropagation();
+ onDelete(conversation.id);
+ }}
+ className="text-xs gap-2 rounded-lg px-2.5 py-1.5 text-destructive focus:text-destructive focus:bg-destructive/10 cursor-pointer"
+ >
+ <Trash2 size={12} />
+ {t("chat.delete")}
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ </div>
+ </div>
+ {conversation.preview && (
+ <p className="text-[11px] text-muted-foreground/50 line-clamp-1 mt-0.5">
+ {conversation.preview}
+ </p>
+ )}
+ </div>
+ </button>
+ );
+}
diff --git a/src/components/chat/ConversationList.tsx b/src/components/chat/ConversationList.tsx
new file mode 100644
index 000000000..f7d18c984
--- /dev/null
+++ b/src/components/chat/ConversationList.tsx
@@ -0,0 +1,323 @@
+import { useState, useEffect, useRef, useCallback, useMemo } from "react";
+import { Plus, Search, Archive as ArchiveIcon } from "lucide-react";
+import { useTranslation } from "react-i18next";
+import { useVirtualizer } from "@tanstack/react-virtual";
+import { cn } from "../lib/utils";
+import { useDebouncedCallback } from "../../hooks/useDebouncedCallback";
+import { normalizeDbDate } from "../../utils/dateFormatting";
+import ConversationItem, { type ConversationPreview } from "./ConversationItem";
+import ConversationDateGroup from "./ConversationDateGroup";
+import EmptyConversationList from "./EmptyConversationList";
+
+type FlatItem =
+ | { type: "header"; label: string }
+ | { type: "conversation"; data: ConversationPreview };
+
+interface ConversationListProps {
+ activeConversationId: number | null;
+ onSelectConversation: (id: number, title: string) => void;
+ onNewChat: () => void;
+ onArchive: (id: number) => void;
+ onDelete: (id: number) => void;
+ refreshKey: number;
+}
+
+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;
+}
+
+function SkeletonRows() {
+ return (
+ <div className="px-3 pt-4 space-y-3">
+ {[0, 1, 2, 3].map((i) => (
+ <div key={i} className="space-y-1.5">
+ <div
+ className="h-3 rounded bg-foreground/5"
+ style={{
+ width: `${60 + i * 10}%`,
+ animation: `tool-status-sweep 1.5s ease-in-out ${i * 0.15}s infinite`,
+ backgroundSize: "200% 100%",
+ background: "linear-gradient(90deg, transparent, oklch(0.5 0 0 / 0.06), transparent)",
+ }}
+ />
+ <div
+ className="h-2.5 rounded bg-foreground/3"
+ style={{
+ width: `${80 + (i % 2) * 10}%`,
+ animation: `tool-status-sweep 1.5s ease-in-out ${i * 0.15 + 0.08}s infinite`,
+ backgroundSize: "200% 100%",
+ background: "linear-gradient(90deg, transparent, oklch(0.5 0 0 / 0.04), transparent)",
+ }}
+ />
+ </div>
+ ))}
+ </div>
+ );
+}
+
+export default function ConversationList({
+ activeConversationId,
+ onSelectConversation,
+ onNewChat,
+ onArchive,
+ onDelete,
+ refreshKey,
+}: ConversationListProps) {
+ const { t } = useTranslation();
+ const [conversations, setConversations] = useState<ConversationPreview[]>([]);
+ const [isLoading, setIsLoading] = useState(true);
+ const [searchQuery, setSearchQuery] = useState("");
+ const [showArchived, setShowArchived] = useState(false);
+ const scrollRef = useRef<HTMLDivElement>(null);
+ const showSkeletonTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
+ const [showSkeleton, setShowSkeleton] = useState(false);
+
+ const loadConversations = useCallback(async () => {
+ try {
+ const result = await window.electronAPI.getAgentConversations?.(200);
+ if (result) {
+ setConversations(
+ result.map((c) => ({
+ ...c,
+ preview: undefined,
+ is_archived: false,
+ }))
+ );
+ }
+ } catch {
+ // silently fail
+ } finally {
+ setIsLoading(false);
+ setShowSkeleton(false);
+ if (showSkeletonTimer.current) {
+ clearTimeout(showSkeletonTimer.current);
+ showSkeletonTimer.current = null;
+ }
+ }
+ }, []);
+
+ useEffect(() => {
+ setIsLoading(true);
+ showSkeletonTimer.current = setTimeout(() => setShowSkeleton(true), 150);
+ loadConversations();
+ return () => {
+ if (showSkeletonTimer.current) clearTimeout(showSkeletonTimer.current);
+ };
+ }, [loadConversations, refreshKey]);
+
+ const filtered = useMemo(() => {
+ let list = conversations;
+ if (!showArchived) {
+ list = list.filter((c) => !c.is_archived);
+ } else {
+ list = list.filter((c) => c.is_archived);
+ }
+ if (searchQuery.trim()) {
+ const q = searchQuery.toLowerCase();
+ list = list.filter((c) => c.title.toLowerCase().includes(q));
+ }
+ return list;
+ }, [conversations, searchQuery, showArchived]);
+
+ const flatItems = useMemo(() => groupByDate(filtered, t), [filtered, t]);
+
+ const debouncedSearch = useDebouncedCallback((value: string) => {
+ setSearchQuery(value);
+ }, 200);
+
+ const virtualizer = useVirtualizer({
+ count: flatItems.length,
+ getScrollElement: () => scrollRef.current,
+ estimateSize: (index) => (flatItems[index].type === "header" ? 28 : 52),
+ overscan: 5,
+ });
+
+ const handleKeyDown = useCallback(
+ (e: React.KeyboardEvent) => {
+ if (flatItems.length === 0) return;
+
+ const convItems = flatItems
+ .map((item, index) => ({ item, index }))
+ .filter((entry) => entry.item.type === "conversation");
+ if (convItems.length === 0) return;
+
+ const currentIdx = convItems.findIndex(
+ (entry) => entry.item.type === "conversation" && entry.item.data.id === activeConversationId
+ );
+
+ if (e.key === "ArrowDown") {
+ e.preventDefault();
+ const next = currentIdx < convItems.length - 1 ? currentIdx + 1 : 0;
+ const item = convItems[next].item;
+ if (item.type === "conversation") onSelectConversation(item.data.id, item.data.title);
+ virtualizer.scrollToIndex(convItems[next].index);
+ } else if (e.key === "ArrowUp") {
+ e.preventDefault();
+ const prev = currentIdx > 0 ? currentIdx - 1 : convItems.length - 1;
+ const item = convItems[prev].item;
+ if (item.type === "conversation") onSelectConversation(item.data.id, item.data.title);
+ virtualizer.scrollToIndex(convItems[prev].index);
+ } else if (e.key === "Enter" && activeConversationId) {
+ e.preventDefault();
+ }
+ },
+ [flatItems, activeConversationId, onSelectConversation, virtualizer]
+ );
+
+ if (isLoading && showSkeleton) {
+ return (
+ <div className="flex flex-col h-full">
+ <div className="px-2 pt-2 pb-1 flex items-center gap-1.5">
+ <h2 className="text-xs font-medium text-foreground px-1 flex-1">{t("sidebar.chat")}</h2>
+ </div>
+ <SkeletonRows />
+ </div>
+ );
+ }
+
+ if (isLoading && !showSkeleton) {
+ return (
+ <div className="flex flex-col h-full">
+ <div className="px-2 pt-2 pb-1 flex items-center gap-1.5">
+ <h2 className="text-xs font-medium text-foreground px-1 flex-1">{t("sidebar.chat")}</h2>
+ </div>
+ </div>
+ );
+ }
+
+ return (
+ <div className="flex flex-col h-full" onKeyDown={handleKeyDown} tabIndex={-1}>
+ <div className="px-2 pt-2 pb-1 space-y-1.5 shrink-0">
+ <div className="flex items-center gap-1.5">
+ <h2 className="text-xs font-medium text-foreground px-1 flex-1">{t("sidebar.chat")}</h2>
+ <button
+ onClick={() => setShowArchived((v) => !v)}
+ className={cn(
+ "flex items-center gap-1 h-5 px-1.5 rounded-md text-[10px] transition-colors duration-150",
+ "focus:outline-none focus-visible:ring-1 focus-visible:ring-primary/30",
+ showArchived
+ ? "bg-primary/10 text-primary"
+ : "text-muted-foreground/50 hover:text-muted-foreground hover:bg-foreground/4"
+ )}
+ >
+ <ArchiveIcon size={10} />
+ {t("chat.archived")}
+ </button>
+ <button
+ onClick={onNewChat}
+ className={cn(
+ "p-1 rounded-sm",
+ "text-muted-foreground/60 hover:text-foreground hover:bg-foreground/8",
+ "transition-colors duration-150",
+ "focus:outline-none focus-visible:ring-1 focus-visible:ring-ring/30"
+ )}
+ aria-label={t("chat.newChat")}
+ >
+ <Plus size={14} />
+ </button>
+ </div>
+ <div className="relative">
+ <Search
+ size={11}
+ className="absolute left-2 top-1/2 -translate-y-1/2 text-muted-foreground/40 pointer-events-none"
+ />
+ <input
+ type="text"
+ onChange={(e) => debouncedSearch(e.target.value)}
+ placeholder={t("chat.search")}
+ className={cn(
+ "w-full h-6 pl-6 pr-2 rounded-md text-[11px]",
+ "bg-foreground/3 dark:bg-white/3 border border-border/25 dark:border-white/8",
+ "text-foreground placeholder:text-muted-foreground/40",
+ "outline-none focus-visible:ring-1 focus-visible:ring-primary/30",
+ "transition-colors"
+ )}
+ />
+ </div>
+ </div>
+
+ {flatItems.length === 0 ? (
+ searchQuery.trim() ? (
+ <div className="flex items-center justify-center flex-1">
+ <p className="text-xs text-muted-foreground/40">{t("chat.noResults")}</p>
+ </div>
+ ) : (
+ <EmptyConversationList onNewChat={onNewChat} />
+ )
+ ) : (
+ <div ref={scrollRef} className="flex-1 overflow-y-auto">
+ <div
+ style={{
+ height: `${virtualizer.getTotalSize()}px`,
+ width: "100%",
+ position: "relative",
+ }}
+ >
+ {virtualizer.getVirtualItems().map((virtualItem) => {
+ const item = flatItems[virtualItem.index];
+ return (
+ <div
+ key={virtualItem.key}
+ style={{
+ position: "absolute",
+ top: 0,
+ left: 0,
+ width: "100%",
+ height: `${virtualItem.size}px`,
+ transform: `translateY(${virtualItem.start}px)`,
+ }}
+ >
+ {item.type === "header" ? (
+ <ConversationDateGroup label={item.label} />
+ ) : (
+ <ConversationItem
+ conversation={item.data}
+ isActive={item.data.id === activeConversationId}
+ onClick={() => onSelectConversation(item.data.id, item.data.title)}
+ onArchive={onArchive}
+ onDelete={onDelete}
+ />
+ )}
+ </div>
+ );
+ })}
+ </div>
+ </div>
+ )}
+ </div>
+ );
+}
diff --git a/src/components/chat/EmptyChatState.tsx b/src/components/chat/EmptyChatState.tsx
new file mode 100644
index 000000000..f7a9f0d0b
--- /dev/null
+++ b/src/components/chat/EmptyChatState.tsx
@@ -0,0 +1,11 @@
+import { useTranslation } from "react-i18next";
+
+export default function EmptyChatState() {
+ const { t } = useTranslation();
+
+ return (
+ <div className="flex items-center justify-center h-full select-none">
+ <p className="text-xs text-muted-foreground/40">{t("chat.selectChat")}</p>
+ </div>
+ );
+}
diff --git a/src/components/chat/EmptyConversationList.tsx b/src/components/chat/EmptyConversationList.tsx
new file mode 100644
index 000000000..cf0fae566
--- /dev/null
+++ b/src/components/chat/EmptyConversationList.tsx
@@ -0,0 +1,29 @@
+import { Plus } from "lucide-react";
+import { useTranslation } from "react-i18next";
+import { cn } from "../lib/utils";
+
+interface EmptyConversationListProps {
+ onNewChat: () => void;
+}
+
+export default function EmptyConversationList({ onNewChat }: EmptyConversationListProps) {
+ const { t } = useTranslation();
+
+ return (
+ <div className="flex flex-col items-center justify-center h-full gap-2 px-4 select-none">
+ <p className="text-xs text-muted-foreground/40 text-center">{t("chat.noConversations")}</p>
+ <button
+ onClick={onNewChat}
+ className={cn(
+ "flex items-center gap-1.5 h-7 px-2.5 rounded-md",
+ "text-xs text-primary hover:bg-primary/8",
+ "transition-colors duration-150",
+ "focus:outline-none focus-visible:ring-1 focus-visible:ring-primary/30"
+ )}
+ >
+ <Plus size={12} />
+ {t("chat.newChat")}
+ </button>
+ </div>
+ );
+}
diff --git a/src/components/chat/types.ts b/src/components/chat/types.ts
new file mode 100644
index 000000000..b2ca6a8c4
--- /dev/null
+++ b/src/components/chat/types.ts
@@ -0,0 +1,24 @@
+export interface ToolCallInfo {
+ id: string;
+ name: string;
+ arguments: string;
+ status: "executing" | "completed" | "error";
+ result?: string;
+ metadata?: Record<string, unknown>;
+}
+
+export interface Message {
+ id: string;
+ role: "user" | "assistant" | "tool";
+ content: string;
+ isStreaming: boolean;
+ toolCalls?: ToolCallInfo[];
+}
+
+export type AgentState =
+ | "idle"
+ | "listening"
+ | "transcribing"
+ | "thinking"
+ | "streaming"
+ | "tool-executing";
diff --git a/src/components/chat/useChatPersistence.ts b/src/components/chat/useChatPersistence.ts
new file mode 100644
index 000000000..1ed040015
--- /dev/null
+++ b/src/components/chat/useChatPersistence.ts
@@ -0,0 +1,94 @@
+import { useState, useRef, useCallback } from "react";
+import type { Message, ToolCallInfo } from "./types";
+
+interface UseChatPersistenceOptions {
+ conversationId?: number | null;
+ onConversationCreated?: (id: number, title: string) => void;
+}
+
+export interface ChatPersistence {
+ messages: Message[];
+ setMessages: React.Dispatch<React.SetStateAction<Message[]>>;
+ conversationId: number | null;
+ createConversation: (title: string) => Promise<number>;
+ loadConversation: (id: number) => Promise<void>;
+ saveUserMessage: (text: string) => Promise<void>;
+ saveAssistantMessage: (content: string, toolCalls?: ToolCallInfo[]) => Promise<void>;
+ handleNewChat: () => void;
+}
+
+export function useChatPersistence(options: UseChatPersistenceOptions = {}): ChatPersistence {
+ const [messages, setMessages] = useState<Message[]>([]);
+ const conversationIdRef = useRef<number | null>(options.conversationId ?? null);
+
+ const createConversation = useCallback(
+ async (title: string): Promise<number> => {
+ const conv = await window.electronAPI?.createAgentConversation?.(title);
+ const id = conv?.id ?? 0;
+ conversationIdRef.current = id;
+ options.onConversationCreated?.(id, title);
+ return id;
+ },
+ [options]
+ );
+
+ const loadConversation = useCallback(async (id: number) => {
+ const conv = await window.electronAPI?.getAgentConversation?.(id);
+ if (!conv) return;
+ conversationIdRef.current = id;
+ const loaded: Message[] = conv.messages.map((m) => {
+ const parsed = m.metadata ? tryParseMetadata(m.metadata) : undefined;
+ const toolCalls = parsed?.toolCalls as ToolCallInfo[] | undefined;
+ return {
+ id: crypto.randomUUID(),
+ role: m.role as Message["role"],
+ content: m.content,
+ isStreaming: false,
+ ...(toolCalls ? { toolCalls } : {}),
+ };
+ });
+ setMessages(loaded);
+ }, []);
+
+ const saveUserMessage = useCallback(async (text: string) => {
+ if (conversationIdRef.current) {
+ window.electronAPI?.addAgentMessage?.(conversationIdRef.current, "user", text);
+ }
+ }, []);
+
+ const saveAssistantMessage = useCallback(async (content: string, toolCalls?: ToolCallInfo[]) => {
+ if (conversationIdRef.current) {
+ window.electronAPI?.addAgentMessage?.(
+ conversationIdRef.current,
+ "assistant",
+ content,
+ toolCalls?.length ? { toolCalls } : undefined
+ );
+ }
+ }, []);
+
+ const handleNewChat = useCallback(() => {
+ setMessages([]);
+ conversationIdRef.current = null;
+ }, []);
+
+ return {
+ messages,
+ setMessages,
+ conversationId: conversationIdRef.current,
+ createConversation,
+ loadConversation,
+ saveUserMessage,
+ saveAssistantMessage,
+ handleNewChat,
+ };
+}
+
+function tryParseMetadata(raw: string | undefined): Record<string, unknown> | undefined {
+ if (!raw) return undefined;
+ try {
+ return JSON.parse(raw);
+ } catch {
+ return undefined;
+ }
+}
diff --git a/src/components/chat/useChatStreaming.ts b/src/components/chat/useChatStreaming.ts
new file mode 100644
index 000000000..17702e7ef
--- /dev/null
+++ b/src/components/chat/useChatStreaming.ts
@@ -0,0 +1,245 @@
+import { useState, useRef, useEffect, useCallback } from "react";
+import { useTranslation } from "react-i18next";
+import ReasoningService, { type AgentStreamChunk } from "../../services/ReasoningService";
+import { getSettings } from "../../stores/settingsStore";
+import { getAgentSystemPrompt } from "../../config/prompts";
+import { createToolRegistry } from "../../services/tools";
+import type { ToolRegistry } from "../../services/tools/ToolRegistry";
+import type { Message, AgentState, ToolCallInfo } from "./types";
+
+interface UseChatStreamingOptions {
+ messages: Message[];
+ setMessages: React.Dispatch<React.SetStateAction<Message[]>>;
+ onStreamComplete?: (assistantId: string, content: string, toolCalls?: ToolCallInfo[]) => void;
+}
+
+export interface ChatStreaming {
+ agentState: AgentState;
+ toolStatus: string;
+ activeToolName: string;
+ sendToAI: (userText: string, allMessages: Message[]) => Promise<void>;
+ cancelStream: () => void;
+}
+
+export function useChatStreaming({
+ messages,
+ setMessages,
+ onStreamComplete,
+}: UseChatStreamingOptions): ChatStreaming {
+ const { t } = useTranslation();
+ const [agentState, setAgentState] = useState<AgentState>("idle");
+ const [toolStatus, setToolStatus] = useState("");
+ const [activeToolName, setActiveToolName] = useState("");
+ const mountedRef = useRef(true);
+ const messagesRef = useRef<Message[]>([]);
+ const toolRegistryRef = useRef<{ key: string; registry: ToolRegistry } | null>(null);
+
+ useEffect(() => {
+ messagesRef.current = messages;
+ }, [messages]);
+
+ useEffect(() => {
+ mountedRef.current = true;
+ return () => {
+ mountedRef.current = false;
+ ReasoningService.cancelActiveStream();
+ };
+ }, []);
+
+ const cancelStream = useCallback(() => {
+ ReasoningService.cancelActiveStream();
+ setAgentState("idle");
+ setToolStatus("");
+ setActiveToolName("");
+ }, []);
+
+ const sendToAI = useCallback(
+ async (userText: string, allMessages: Message[]) => {
+ setAgentState("thinking");
+
+ const settings = getSettings();
+ const isCloudAgent = settings.isSignedIn && settings.cloudAgentMode === "openwhispr";
+ const toolSupportedProviders = ["openai", "groq", "custom", "anthropic", "gemini"];
+ const supportsTools = isCloudAgent || toolSupportedProviders.includes(settings.agentProvider);
+
+ let registry: ToolRegistry | null = null;
+ if (supportsTools) {
+ const cacheKey = `${settings.isSignedIn}-${settings.gcalConnected}-${settings.cloudBackupEnabled}`;
+ if (toolRegistryRef.current?.key === cacheKey) {
+ registry = toolRegistryRef.current.registry;
+ } else {
+ registry = createToolRegistry({
+ isSignedIn: settings.isSignedIn,
+ gcalConnected: settings.gcalConnected,
+ cloudBackupEnabled: settings.cloudBackupEnabled,
+ });
+ toolRegistryRef.current = { key: cacheKey, registry };
+ }
+ }
+ const systemPrompt = getAgentSystemPrompt(registry?.getAll().map((t) => t.name));
+
+ const llmMessages = [
+ { role: "system", content: systemPrompt },
+ ...allMessages.slice(-20).map((m) => ({ role: m.role, content: m.content })),
+ ];
+
+ const assistantId = crypto.randomUUID();
+ setMessages((prev) => [
+ ...prev,
+ { id: assistantId, role: "assistant", content: "", isStreaming: true },
+ ]);
+ setAgentState("streaming");
+
+ try {
+ let fullContent = "";
+ let stream: AsyncGenerator<AgentStreamChunk>;
+
+ if (isCloudAgent) {
+ const executeToolCall = registry
+ ? async (name: string, argsJson: string) => {
+ const tool = registry.get(name);
+ if (!tool)
+ return {
+ data: `Unknown tool: ${name}`,
+ displayText: t("agentMode.tools.unknownTool", { name }),
+ };
+ let args: Record<string, unknown>;
+ try {
+ args = JSON.parse(argsJson);
+ } catch {
+ return {
+ data: `Invalid tool arguments for ${name}`,
+ displayText: t("agentMode.tools.invalidArgs", { name }),
+ };
+ }
+ const result = await tool.execute(args);
+ const data = result.success
+ ? typeof result.data === "string"
+ ? result.data
+ : JSON.stringify(result.data)
+ : result.displayText;
+ const metadata =
+ result.success && result.data && typeof result.data === "object"
+ ? (result.data as Record<string, unknown>)
+ : undefined;
+ return { data, displayText: result.displayText, metadata };
+ }
+ : undefined;
+
+ stream = ReasoningService.processTextStreamingCloud(llmMessages, {
+ systemPrompt,
+ tools: registry?.getAll().map((t) => ({
+ name: t.name,
+ description: t.description,
+ parameters: t.parameters,
+ })),
+ executeToolCall,
+ });
+ } else {
+ const aiTools = registry?.toAISDKFormat();
+ stream = ReasoningService.processTextStreamingAI(
+ llmMessages,
+ settings.agentModel,
+ settings.agentProvider,
+ { systemPrompt },
+ aiTools
+ );
+ }
+
+ for await (const chunk of stream) {
+ if (!mountedRef.current) {
+ ReasoningService.cancelActiveStream();
+ break;
+ }
+ if (chunk.type === "content") {
+ fullContent += chunk.text;
+ setMessages((prev) =>
+ prev.map((m) => (m.id === assistantId ? { ...m, content: fullContent } : m))
+ );
+ } else if (chunk.type === "tool_calls") {
+ for (const call of chunk.calls) {
+ setAgentState("tool-executing");
+ setActiveToolName(call.name);
+ setToolStatus(
+ t(`agentMode.tools.${call.name}Status`, { defaultValue: `Using ${call.name}...` })
+ );
+ setMessages((prev) =>
+ prev.map((m) =>
+ m.id === assistantId
+ ? {
+ ...m,
+ toolCalls: [
+ ...(m.toolCalls || []),
+ {
+ id: call.id,
+ name: call.name,
+ arguments: call.arguments,
+ status: "executing" as const,
+ },
+ ],
+ }
+ : m
+ )
+ );
+ }
+ } else if (chunk.type === "tool_result") {
+ setMessages((prev) =>
+ prev.map((m) =>
+ m.id === assistantId && m.toolCalls
+ ? {
+ ...m,
+ toolCalls: m.toolCalls.map((tc) =>
+ tc.id === chunk.callId
+ ? {
+ ...tc,
+ status: "completed" as const,
+ result: chunk.displayText,
+ ...(chunk.metadata ? { metadata: chunk.metadata } : {}),
+ }
+ : tc
+ ),
+ }
+ : m
+ )
+ );
+ setAgentState("streaming");
+ setToolStatus("");
+ setActiveToolName("");
+ }
+ }
+
+ setMessages((prev) =>
+ prev.map((m) => (m.id === assistantId ? { ...m, isStreaming: false } : m))
+ );
+
+ const finalMsg = messagesRef.current.find((m) => m.id === assistantId);
+ onStreamComplete?.(assistantId, fullContent, finalMsg?.toolCalls);
+ } catch (error) {
+ setMessages((prev) =>
+ prev.map((m) =>
+ m.id === assistantId
+ ? {
+ ...m,
+ content: `${t("agentMode.chat.errorPrefix")}: ${(error as Error).message}`,
+ isStreaming: false,
+ }
+ : m
+ )
+ );
+ }
+
+ setAgentState("idle");
+ setToolStatus("");
+ setActiveToolName("");
+ },
+ [t, setMessages, onStreamComplete]
+ );
+
+ return {
+ agentState,
+ toolStatus,
+ activeToolName,
+ sendToAI,
+ cancelStream,
+ };
+}
diff --git a/src/helpers/conversationChunker.js b/src/helpers/conversationChunker.js
new file mode 100644
index 000000000..76548acf7
--- /dev/null
+++ b/src/helpers/conversationChunker.js
@@ -0,0 +1,26 @@
+const CHUNK_SIZE = 5;
+const CHUNK_OVERLAP = 2;
+
+function chunkConversation(title, messages) {
+ const relevant = messages.filter((m) => m.role !== "system");
+ if (relevant.length === 0) return [];
+
+ if (relevant.length <= CHUNK_SIZE) {
+ return [{ chunkIndex: 0, text: formatChunkText(title, relevant) }];
+ }
+
+ const chunks = [];
+ for (let i = 0; i < relevant.length; i += CHUNK_SIZE - CHUNK_OVERLAP) {
+ const window = relevant.slice(i, i + CHUNK_SIZE);
+ if (window.length < 2) break;
+ chunks.push({ chunkIndex: chunks.length, text: formatChunkText(title, window) });
+ }
+ return chunks;
+}
+
+function formatChunkText(title, messages) {
+ const body = messages.map((m) => `${m.role}: ${m.content}`).join("\n");
+ return `${title}\n${body}`.slice(0, 1500);
+}
+
+module.exports = { chunkConversation, CHUNK_SIZE };
diff --git a/src/helpers/database.js b/src/helpers/database.js
index f0ae9bc31..c729c9435 100644
--- a/src/helpers/database.js
+++ b/src/helpers/database.js
@@ -235,6 +235,16 @@ class DatabaseManager {
} catch (err) {
if (!err.message.includes("duplicate column")) throw err;
}
+ try {
+ this.db.exec("ALTER TABLE agent_conversations ADD COLUMN archived_at DATETIME");
+ } catch (err) {
+ if (!err.message.includes("duplicate column")) throw err;
+ }
+ try {
+ this.db.exec("ALTER TABLE agent_conversations ADD COLUMN cloud_id TEXT");
+ } catch (err) {
+ if (!err.message.includes("duplicate column")) throw err;
+ }
const actionCount = this.db.prepare("SELECT COUNT(*) as count FROM actions").get();
if (actionCount.count === 0) {
@@ -1271,6 +1281,106 @@ class DatabaseManager {
debugLogger.error("Error deleting database file", { error: error.message }, "database");
}
}
+ getAgentConversationsWithPreview(limit = 50, offset = 0, includeArchived = false) {
+ try {
+ if (!this.db) throw new Error("Database not initialized");
+ const archiveFilter = includeArchived ? "" : "WHERE c.archived_at IS NULL";
+ return this.db
+ .prepare(
+ `SELECT c.id, c.title, c.created_at, c.updated_at, c.archived_at, c.cloud_id,
+ COUNT(m.id) AS message_count,
+ (SELECT content FROM agent_messages WHERE conversation_id = c.id ORDER BY created_at DESC LIMIT 1) AS last_message,
+ (SELECT role FROM agent_messages WHERE conversation_id = c.id ORDER BY created_at DESC LIMIT 1) AS last_message_role
+ FROM agent_conversations c
+ LEFT JOIN agent_messages m ON m.conversation_id = c.id
+ ${archiveFilter}
+ GROUP BY c.id
+ ORDER BY c.updated_at DESC
+ LIMIT ? OFFSET ?`
+ )
+ .all(limit, offset);
+ } catch (error) {
+ debugLogger.error(
+ "Error getting agent conversations with preview",
+ { error: error.message },
+ "database"
+ );
+ throw error;
+ }
+ }
+
+ searchAgentConversations(query, limit = 20) {
+ try {
+ if (!this.db) throw new Error("Database not initialized");
+ const pattern = `%${query}%`;
+ return this.db
+ .prepare(
+ `SELECT DISTINCT c.id, c.title, c.created_at, c.updated_at, c.archived_at, c.cloud_id,
+ COUNT(m.id) AS message_count,
+ (SELECT content FROM agent_messages WHERE conversation_id = c.id ORDER BY created_at DESC LIMIT 1) AS last_message,
+ (SELECT role FROM agent_messages WHERE conversation_id = c.id ORDER BY created_at DESC LIMIT 1) AS last_message_role
+ FROM agent_conversations c
+ LEFT JOIN agent_messages m ON m.conversation_id = c.id
+ LEFT JOIN agent_messages ms ON ms.conversation_id = c.id
+ WHERE c.archived_at IS NULL
+ AND (c.title LIKE ? OR ms.content LIKE ?)
+ GROUP BY c.id
+ ORDER BY c.updated_at DESC
+ LIMIT ?`
+ )
+ .all(pattern, pattern, limit);
+ } catch (error) {
+ debugLogger.error(
+ "Error searching agent conversations",
+ { error: error.message },
+ "database"
+ );
+ throw error;
+ }
+ }
+
+ archiveAgentConversation(id) {
+ try {
+ if (!this.db) throw new Error("Database not initialized");
+ this.db
+ .prepare("UPDATE agent_conversations SET archived_at = CURRENT_TIMESTAMP WHERE id = ?")
+ .run(id);
+ return { success: true };
+ } catch (error) {
+ debugLogger.error("Error archiving agent conversation", { error: error.message }, "database");
+ throw error;
+ }
+ }
+
+ unarchiveAgentConversation(id) {
+ try {
+ if (!this.db) throw new Error("Database not initialized");
+ this.db.prepare("UPDATE agent_conversations SET archived_at = NULL WHERE id = ?").run(id);
+ return { success: true };
+ } catch (error) {
+ debugLogger.error(
+ "Error unarchiving agent conversation",
+ { error: error.message },
+ "database"
+ );
+ throw error;
+ }
+ }
+
+ updateAgentConversationCloudId(id, cloudId) {
+ try {
+ if (!this.db) throw new Error("Database not initialized");
+ this.db.prepare("UPDATE agent_conversations SET cloud_id = ? WHERE id = ?").run(cloudId, id);
+ return { success: true };
+ } catch (error) {
+ debugLogger.error(
+ "Error updating agent conversation cloud_id",
+ { error: error.message },
+ "database"
+ );
+ throw error;
+ }
+ }
}
module.exports = DatabaseManager;
diff --git a/src/helpers/ipcHandlers.js b/src/helpers/ipcHandlers.js
index 15deec0d8..3fc7aa46f 100644
--- a/src/helpers/ipcHandlers.js
+++ b/src/helpers/ipcHandlers.js
@@ -751,6 +751,37 @@ class IPCHandlers {
return this.databaseManager.getAgentMessages(conversationId);
});
+ ipcMain.handle(
+ "db-get-agent-conversations-with-preview",
+ async (event, limit, offset, includeArchived) => {
+ return this.databaseManager.getAgentConversationsWithPreview(
+ limit,
+ offset,
+ includeArchived
+ );
+ }
+ );
+
+ ipcMain.handle("db-search-agent-conversations", async (event, query, limit) => {
+ return this.databaseManager.searchAgentConversations(query, limit);
+ });
+
+ ipcMain.handle("db-archive-agent-conversation", async (event, id) => {
+ return this.databaseManager.archiveAgentConversation(id);
+ });
+
+ ipcMain.handle("db-unarchive-agent-conversation", async (event, id) => {
+ return this.databaseManager.unarchiveAgentConversation(id);
+ });
+
+ ipcMain.handle("db-update-agent-conversation-cloud-id", async (event, id, cloudId) => {
+ return this.databaseManager.updateAgentConversationCloudId(id, cloudId);
+ });
+
+ ipcMain.handle("db-semantic-search-conversations", async (event, query, limit) => {
+ return this.databaseManager.searchAgentConversations(query, limit);
+ });
+
ipcMain.handle("export-note", async (event, noteId, format) => {
try {
const note = this.databaseManager.getNote(noteId);
diff --git a/src/helpers/vectorIndex.js b/src/helpers/vectorIndex.js
index da53038cb..5cc85eb0b 100644
--- a/src/helpers/vectorIndex.js
+++ b/src/helpers/vectorIndex.js
@@ -2,11 +2,13 @@ const { QdrantClient } = require("@qdrant/js-client-rest");
const localEmbeddings = require("./localEmbeddings");
const { LocalEmbeddings } = localEmbeddings;
const debugLogger = require("./debugLogger");
+const { chunkConversation } = require("./conversationChunker");
class VectorIndex {
constructor() {
this.client = null;
this.collectionName = "notes";
+ this.conversationChunksCollection = "conversation_chunks";
}
init(port) {
@@ -87,6 +89,118 @@ class VectorIndex {
}
}
+ async ensureConversationChunksCollection() {
+ if (!this.client) return;
+ try {
+ await this.client.getCollection(this.conversationChunksCollection);
+ } catch {
+ try {
+ await this.client.createCollection(this.conversationChunksCollection, {
+ vectors: { size: 384, distance: "Cosine" },
+ });
+ } catch (err) {
+ debugLogger.error("Failed to create conversation_chunks collection", {
+ error: err.message,
+ });
+ }
+ }
+ }
+
+ async upsertConversationChunks(conversationId, title, messages) {
+ if (!this.client) return;
+ try {
+ await this.deleteConversationChunks(conversationId);
+ const chunks = chunkConversation(title, messages);
+ if (chunks.length === 0) return;
+
+ const texts = chunks.map((c) => c.text);
+ const vectors = await localEmbeddings.embedTexts(texts);
+ const points = chunks.map((c, i) => ({
+ id: conversationId * 1000 + c.chunkIndex,
+ vector: Array.from(vectors[i]),
+ payload: { conversation_id: conversationId, chunk_index: c.chunkIndex },
+ }));
+ await this.client.upsert(this.conversationChunksCollection, { points });
+ } catch (err) {
+ debugLogger.debug("Conversation chunks upsert failed", {
+ conversationId,
+ error: err.message,
+ });
+ }
+ }
+
+ async deleteConversationChunks(conversationId) {
+ if (!this.client) return;
+ try {
+ await this.client.delete(this.conversationChunksCollection, {
+ filter: { must: [{ key: "conversation_id", match: { value: conversationId } }] },
+ });
+ } catch (err) {
+ debugLogger.debug("Conversation chunks delete failed", {
+ conversationId,
+ error: err.message,
+ });
+ }
+ }
+
+ async searchConversations(queryText, limit = 10) {
+ if (!this.client) return [];
+ try {
+ const vector = await localEmbeddings.embedText(queryText);
+ const results = await this.client.search(this.conversationChunksCollection, {
+ vector: Array.from(vector),
+ limit: limit * 3,
+ });
+
+ const bestByConversation = new Map();
+ for (const r of results) {
+ if (r.score < 0.3) continue;
+ const convId = r.payload.conversation_id;
+ if (!bestByConversation.has(convId) || r.score > bestByConversation.get(convId)) {
+ bestByConversation.set(convId, r.score);
+ }
+ }
+
+ return [...bestByConversation.entries()]
+ .sort((a, b) => b[1] - a[1])
+ .slice(0, limit)
+ .map(([conversationId, score]) => ({ conversationId, score }));
+ } catch (err) {
+ debugLogger.debug("Conversation search failed", { error: err.message });
+ return [];
+ }
+ }
+
+ async reindexAllConversations(conversations, onProgress) {
+ if (!this.client) return;
+ const BATCH_SIZE = 50;
+ for (let i = 0; i < conversations.length; i += BATCH_SIZE) {
+ const batch = conversations.slice(i, i + BATCH_SIZE);
+ for (const conv of batch) {
+ try {
+ const chunks = chunkConversation(conv.title, conv.messages);
+ if (chunks.length === 0) continue;
+
+ const texts = chunks.map((c) => c.text);
+ const vectors = await localEmbeddings.embedTexts(texts);
+ const points = chunks.map((c, j) => ({
+ id: conv.id * 1000 + c.chunkIndex,
+ vector: Array.from(vectors[j]),
+ payload: { conversation_id: conv.id, chunk_index: c.chunkIndex },
+ }));
+ await this.client.upsert(this.conversationChunksCollection, { points });
+ } catch (err) {
+ debugLogger.debug("Conversation reindex failed", {
+ conversationId: conv.id,
+ error: err.message,
+ });
+ }
+ }
+ if (onProgress)
+ onProgress(Math.min(i + BATCH_SIZE, conversations.length), conversations.length);
+ }
+ }
+
isReady() {
return this.client !== null;
}
diff --git a/src/locales/de/translation.json b/src/locales/de/translation.json
index 46514273d..0cccff0f4 100644
--- a/src/locales/de/translation.json
+++ b/src/locales/de/translation.json
@@ -1735,7 +1735,25 @@
"learnMore": "Mehr erfahren",
"integrations": "Integrationen",
"defaultUser": "Benutzer",
- "notSignedIn": "Nicht angemeldet"
+ "notSignedIn": "Nicht angemeldet",
+ "chat": "Chat"
+ },
+ "chat": {
+ "newChat": "Neuer Chat",
+ "search": "Unterhaltungen suchen...",
+ "archived": "Archiviert",
+ "noConversations": "Starten Sie Ihre erste Unterhaltung",
+ "selectChat": "Wählen Sie eine Unterhaltung oder starten Sie eine neue",
+ "noResults": "Keine passenden Unterhaltungen",
+ "today": "Heute",
+ "yesterday": "Gestern",
+ "previousWeek": "Letzte 7 Tage",
+ "older": "Älter",
+ "archive": "Archivieren",
+ "unarchive": "Dearchivieren",
+ "delete": "Löschen",
+ "deleteConfirm": "Diese Unterhaltung wird dauerhaft gelöscht. Dies kann nicht rückgängig gemacht werden.",
+ "editTitle": "Doppelklick zum Bearbeiten des Titels"
},
"usage": {
"approachingLimit": "Wochenlimit fast erreicht",
diff --git a/src/locales/en/translation.json b/src/locales/en/translation.json
index c2a10f910..793ef3ec9 100644
--- a/src/locales/en/translation.json
+++ b/src/locales/en/translation.json
@@ -1523,7 +1523,25 @@
"learnMore": "Learn more",
"integrations": "Integrations",
"defaultUser": "User",
- "notSignedIn": "Not signed in"
+ "notSignedIn": "Not signed in",
+ "chat": "Chat"
+ },
+ "chat": {
+ "newChat": "New chat",
+ "search": "Search conversations...",
+ "archived": "Archived",
+ "noConversations": "Start your first conversation",
+ "selectChat": "Select a conversation or start a new one",
+ "noResults": "No matching conversations",
+ "today": "Today",
+ "yesterday": "Yesterday",
+ "previousWeek": "Previous 7 Days",
+ "older": "Older",
+ "archive": "Archive",
+ "unarchive": "Unarchive",
+ "delete": "Delete",
+ "deleteConfirm": "This conversation will be permanently deleted. This cannot be undone.",
+ "editTitle": "Double-click to edit title"
},
"referral": {
"title": "Refer and earn rewards",
diff --git a/src/locales/es/translation.json b/src/locales/es/translation.json
index 106b7e71d..a79fd6874 100644
--- a/src/locales/es/translation.json
+++ b/src/locales/es/translation.json
@@ -1735,7 +1735,25 @@
"learnMore": "Más información",
"integrations": "Integraciones",
"defaultUser": "Usuario",
- "notSignedIn": "Sin sesión iniciada"
+ "notSignedIn": "Sin sesión iniciada",
+ "chat": "Chat"
+ },
+ "chat": {
+ "newChat": "Nuevo chat",
+ "search": "Buscar conversaciones...",
+ "archived": "Archivadas",
+ "noConversations": "Inicia tu primera conversación",
+ "selectChat": "Selecciona una conversación o inicia una nueva",
+ "noResults": "Sin conversaciones coincidentes",
+ "today": "Hoy",
+ "yesterday": "Ayer",
+ "previousWeek": "Últimos 7 días",
+ "older": "Anteriores",
+ "archive": "Archivar",
+ "unarchive": "Desarchivar",
+ "delete": "Eliminar",
+ "deleteConfirm": "Esta conversación se eliminará permanentemente. No se puede deshacer.",
+ "editTitle": "Doble clic para editar el título"
},
"usage": {
"approachingLimit": "Cerca del límite semanal",
diff --git a/src/locales/fr/translation.json b/src/locales/fr/translation.json
index d73e7dc33..9fdc11707 100644
--- a/src/locales/fr/translation.json
+++ b/src/locales/fr/translation.json
@@ -1475,7 +1475,25 @@
"learnMore": "En savoir plus",
"integrations": "Intégrations",
"defaultUser": "Utilisateur",
- "notSignedIn": "Non connecté"
+ "notSignedIn": "Non connecté",
+ "chat": "Chat"
+ },
+ "chat": {
+ "newChat": "Nouveau chat",
+ "search": "Rechercher des conversations...",
+ "archived": "Archivées",
+ "noConversations": "Démarrez votre première conversation",
+ "selectChat": "Sélectionnez une conversation ou démarrez-en une nouvelle",
+ "noResults": "Aucune conversation correspondante",
+ "today": "Aujourd'hui",
+ "yesterday": "Hier",
+ "previousWeek": "7 derniers jours",
+ "older": "Plus anciennes",
+ "archive": "Archiver",
+ "unarchive": "Désarchiver",
+ "delete": "Supprimer",
+ "deleteConfirm": "Cette conversation sera définitivement supprimée. Cette action est irréversible.",
+ "editTitle": "Double-cliquez pour modifier le titre"
},
"referral": {
"title": "Parrainez et gagnez des récompenses",
diff --git a/src/locales/it/translation.json b/src/locales/it/translation.json
index 05536bcf9..b4f87c422 100644
--- a/src/locales/it/translation.json
+++ b/src/locales/it/translation.json
@@ -1735,7 +1735,25 @@
"learnMore": "Scopri di più",
"integrations": "Integrazioni",
"defaultUser": "Utente",
- "notSignedIn": "Non hai effettuato l'accesso"
+ "notSignedIn": "Non hai effettuato l'accesso",
+ "chat": "Chat"
+ },
+ "chat": {
+ "newChat": "Nuova chat",
+ "search": "Cerca conversazioni...",
+ "archived": "Archiviate",
+ "noConversations": "Inizia la tua prima conversazione",
+ "selectChat": "Seleziona una conversazione o avviane una nuova",
+ "noResults": "Nessuna conversazione corrispondente",
+ "today": "Oggi",
+ "yesterday": "Ieri",
+ "previousWeek": "Ultimi 7 giorni",
+ "older": "Precedenti",
+ "archive": "Archivia",
+ "unarchive": "Ripristina",
+ "delete": "Elimina",
+ "deleteConfirm": "Questa conversazione verrà eliminata permanentemente. Non è possibile annullare.",
+ "editTitle": "Doppio clic per modificare il titolo"
},
"usage": {
"approachingLimit": "Limite settimanale quasi raggiunto",
diff --git a/src/locales/ja/translation.json b/src/locales/ja/translation.json
index 6b153204c..408d54e8c 100644
--- a/src/locales/ja/translation.json
+++ b/src/locales/ja/translation.json
@@ -1735,7 +1735,25 @@
"learnMore": "詳しく見る",
"integrations": "連携",
"defaultUser": "ユーザー",
- "notSignedIn": "未サインイン"
+ "notSignedIn": "未サインイン",
+ "chat": "チャット"
+ },
+ "chat": {
+ "newChat": "新しいチャット",
+ "search": "会話を検索...",
+ "archived": "アーカイブ済み",
+ "noConversations": "最初の会話を始めましょう",
+ "selectChat": "会話を選択するか、新しく始めてください",
+ "noResults": "該当する会話がありません",
+ "today": "今日",
+ "yesterday": "昨日",
+ "previousWeek": "過去7日間",
+ "older": "それ以前",
+ "archive": "アーカイブ",
+ "unarchive": "アーカイブ解除",
+ "delete": "削除",
+ "deleteConfirm": "この会話は完全に削除されます。元に戻すことはできません。",
+ "editTitle": "ダブルクリックでタイトルを編集"
},
"usage": {
"approachingLimit": "週間制限に近づいています",
diff --git a/src/locales/pt/translation.json b/src/locales/pt/translation.json
index e0e34e5b0..7683a1348 100644
--- a/src/locales/pt/translation.json
+++ b/src/locales/pt/translation.json
@@ -1735,7 +1735,25 @@
"learnMore": "Saiba mais",
"integrations": "Integrações",
"defaultUser": "Usuário",
- "notSignedIn": "Não conectado"
+ "notSignedIn": "Não conectado",
+ "chat": "Chat"
+ },
+ "chat": {
+ "newChat": "Novo chat",
+ "search": "Pesquisar conversas...",
+ "archived": "Arquivadas",
+ "noConversations": "Inicie sua primeira conversa",
+ "selectChat": "Selecione uma conversa ou inicie uma nova",
+ "noResults": "Nenhuma conversa encontrada",
+ "today": "Hoje",
+ "yesterday": "Ontem",
+ "previousWeek": "Últimos 7 dias",
+ "older": "Mais antigas",
+ "archive": "Arquivar",
+ "unarchive": "Desarquivar",
+ "delete": "Excluir",
+ "deleteConfirm": "Esta conversa será excluída permanentemente. Não é possível desfazer.",
+ "editTitle": "Clique duplo para editar o título"
},
"usage": {
"approachingLimit": "Próximo do limite semanal",
diff --git a/src/locales/ru/translation.json b/src/locales/ru/translation.json
index e367dc180..7f15d2e50 100644
--- a/src/locales/ru/translation.json
+++ b/src/locales/ru/translation.json
@@ -1735,7 +1735,25 @@
"learnMore": "Узнать больше",
"integrations": "Интеграции",
"defaultUser": "Пользователь",
- "notSignedIn": "Не авторизован"
+ "notSignedIn": "Не авторизован",
+ "chat": "Чат"
+ },
+ "chat": {
+ "newChat": "Новый чат",
+ "search": "Поиск бесед...",
+ "archived": "Архив",
+ "noConversations": "Начните свою первую беседу",
+ "selectChat": "Выберите беседу или начните новую",
+ "noResults": "Совпадений не найдено",
+ "today": "Сегодня",
+ "yesterday": "Вчера",
+ "previousWeek": "Последние 7 дней",
+ "older": "Ранее",
+ "archive": "В архив",
+ "unarchive": "Из архива",
+ "delete": "Удалить",
+ "deleteConfirm": "Эта беседа будет удалена навсегда. Отменить действие невозможно.",
+ "editTitle": "Двойной клик для редактирования названия"
},
"usage": {
"approachingLimit": "Приближается недельный лимит",
diff --git a/src/locales/zh-CN/translation.json b/src/locales/zh-CN/translation.json
index 93c3ec54a..79afac049 100644
--- a/src/locales/zh-CN/translation.json
+++ b/src/locales/zh-CN/translation.json
@@ -1730,7 +1730,25 @@
"learnMore": "了解更多",
"integrations": "集成",
"defaultUser": "用户",
- "notSignedIn": "未登录"
+ "notSignedIn": "未登录",
+ "chat": "聊天"
+ },
+ "chat": {
+ "newChat": "新对话",
+ "search": "搜索对话...",
+ "archived": "已归档",
+ "noConversations": "开始你的第一个对话",
+ "selectChat": "选择一个对话或开始新的对话",
+ "noResults": "没有匹配的对话",
+ "today": "今天",
+ "yesterday": "昨天",
+ "previousWeek": "最近 7 天",
+ "older": "更早",
+ "archive": "归档",
+ "unarchive": "取消归档",
+ "delete": "删除",
+ "deleteConfirm": "此对话将被永久删除,无法撤消。",
+ "editTitle": "双击编辑标题"
},
"usage": {
"approachingLimit": "即将达到周限额",
diff --git a/src/locales/zh-TW/translation.json b/src/locales/zh-TW/translation.json
index e3811b4da..818b8208d 100644
--- a/src/locales/zh-TW/translation.json
+++ b/src/locales/zh-TW/translation.json
@@ -1730,7 +1730,25 @@
"learnMore": "瞭解更多",
"integrations": "整合",
"defaultUser": "使用者",
- "notSignedIn": "尚未登入"
+ "notSignedIn": "尚未登入",
+ "chat": "聊天"
+ },
+ "chat": {
+ "newChat": "新對話",
+ "search": "搜尋對話...",
+ "archived": "已封存",
+ "noConversations": "開始你的第一個對話",
+ "selectChat": "選擇一個對話或開始新的對話",
+ "noResults": "沒有符合的對話",
+ "today": "今天",
+ "yesterday": "昨天",
+ "previousWeek": "最近 7 天",
+ "older": "更早",
+ "archive": "封存",
+ "unarchive": "取消封存",
+ "delete": "刪除",
+ "deleteConfirm": "此對話將被永久刪除,無法復原。",
+ "editTitle": "雙擊編輯標題"
},
"usage": {
"approachingLimit": "即將達到每週上限",
diff --git a/src/services/ConversationsService.ts b/src/services/ConversationsService.ts
new file mode 100644
index 000000000..c75f4d663
--- /dev/null
+++ b/src/services/ConversationsService.ts
@@ -0,0 +1,141 @@
+import { OPENWHISPR_API_URL } from "../config/constants.js";
+
+interface ConversationInput {
+ client_conversation_id?: string;
+ title?: string;
+ created_at?: string;
+ updated_at?: string;
+ messages?: Array<{
+ role: "user" | "assistant" | "system";
+ content: string;
+ metadata?: Record<string, unknown> | null;
+ }>;
+}
+
+interface CloudConversation {
+ id: string;
+ client_conversation_id: string | null;
+ title: string;
+ archived_at: string | null;
+ deleted_at: string | null;
+ created_at: string;
+ updated_at: string;
+}
+
+interface CloudMessage {
+ id: string;
+ conversation_id: string;
+ role: "user" | "assistant" | "system";
+ content: string;
+ metadata: Record<string, unknown> | null;
+ created_at: string;
+}
+
+async function create(input: ConversationInput): Promise<CloudConversation> {
+ const res = await fetch(`${OPENWHISPR_API_URL}/api/conversations/create`, {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ credentials: "include",
+ body: JSON.stringify(input),
+ });
+ if (!res.ok) throw new Error(await res.text());
+ return res.json() as Promise<CloudConversation>;
+}
+
+async function update(
+ id: string,
+ updates: { title?: string; archived_at?: string }
+): Promise<CloudConversation> {
+ const res = await fetch(`${OPENWHISPR_API_URL}/api/conversations/update`, {
+ method: "PATCH",
+ headers: { "Content-Type": "application/json" },
+ credentials: "include",
+ body: JSON.stringify({ id, ...updates }),
+ });
+ if (!res.ok) throw new Error(await res.text());
+ return res.json() as Promise<CloudConversation>;
+}
+
+async function deleteConversation(id: string): Promise<void> {
+ const res = await fetch(`${OPENWHISPR_API_URL}/api/conversations/delete`, {
+ method: "DELETE",
+ headers: { "Content-Type": "application/json" },
+ credentials: "include",
+ body: JSON.stringify({ id }),
+ });
+ if (!res.ok) throw new Error(await res.text());
+}
+
+async function list(
+ limit?: number,
+ before?: string,
+ archived?: boolean
+): Promise<{ conversations: CloudConversation[] }> {
+ const params = new URLSearchParams();
+ if (limit !== undefined) params.set("limit", String(limit));
+ if (before !== undefined) params.set("before", before);
+ if (archived) params.set("archived", "true");
+ const query = params.toString();
+ const res = await fetch(
+ `${OPENWHISPR_API_URL}/api/conversations/list${query ? `?${query}` : ""}`,
+ { credentials: "include" }
+ );
+ if (!res.ok) throw new Error(await res.text());
+ return res.json() as Promise<{ conversations: CloudConversation[] }>;
+}
+
+async function addMessage(
+ conversationId: string,
+ role: "user" | "assistant" | "system",
+ content: string,
+ metadata?: Record<string, unknown> | null
+): Promise<CloudMessage> {
+ const res = await fetch(`${OPENWHISPR_API_URL}/api/conversations/messages`, {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ credentials: "include",
+ body: JSON.stringify({
+ conversation_id: conversationId,
+ role,
+ content,
+ ...(metadata ? { metadata } : {}),
+ }),
+ });
+ if (!res.ok) throw new Error(await res.text());
+ return res.json() as Promise<CloudMessage>;
+}
+
+async function listMessages(conversationId: string): Promise<{ messages: CloudMessage[] }> {
+ const params = new URLSearchParams({ conversation_id: conversationId });
+ const res = await fetch(`${OPENWHISPR_API_URL}/api/conversations/messages?${params}`, {
+ credentials: "include",
+ });
+ if (!res.ok) throw new Error(await res.text());
+ return res.json() as Promise<{ messages: CloudMessage[] }>;
+}
+
+async function search(
+ query: string,
+ limit?: number
+): Promise<{ conversations: CloudConversation[] }> {
+ const res = await fetch(`${OPENWHISPR_API_URL}/api/conversations/search`, {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ credentials: "include",
+ body: JSON.stringify({ query, ...(limit !== undefined ? { limit } : {}) }),
+ });
+ if (!res.ok) throw new Error(await res.text());
+ return res.json() as Promise<{ conversations: CloudConversation[] }>;
+}
+
+export { create, update, deleteConversation, list, addMessage, listMessages, search };
+
+export const ConversationsService = {
+ create,
+ update,
+ delete: deleteConversation,
+ list,
+ addMessage,
+ listMessages,
+ search,
+};
diff --git a/src/stores/chatStore.ts b/src/stores/chatStore.ts
new file mode 100644
index 000000000..96b9df065
--- /dev/null
+++ b/src/stores/chatStore.ts
@@ -0,0 +1,173 @@
+import { create } from "zustand";
+
+interface ConversationItem {
+ id: number;
+ title: string;
+ cloud_id?: string | null;
+ created_at: string;
+ updated_at: string;
+}
+
+interface ChatState {
+ conversations: ConversationItem[];
+ activeConversationId: number | null;
+ migration: { total: number; done: number } | null;
+}
+
+const useChatStore = create<ChatState>()(() => ({
+ conversations: [],
+ activeConversationId: null,
+ migration: null,
+}));
+
+let hasBoundIpcListeners = false;
+const DEFAULT_LIMIT = 50;
+
+function ensureIpcListeners() {
+ if (hasBoundIpcListeners || typeof window === "undefined") {
+ return;
+ }
+ hasBoundIpcListeners = true;
+}
+
+export async function initializeConversations(limit = DEFAULT_LIMIT): Promise<ConversationItem[]> {
+ ensureIpcListeners();
+ const items = (await window.electronAPI?.getAgentConversations?.(limit)) ?? [];
+ useChatStore.setState({ conversations: items });
+ return items;
+}
+
+export function addConversation(conversation: ConversationItem): void {
+ if (!conversation) return;
+ const { conversations } = useChatStore.getState();
+ const withoutDuplicate = conversations.filter((c) => c.id !== conversation.id);
+ useChatStore.setState({ conversations: [conversation, ...withoutDuplicate] });
+}
+
+export function updateConversation(conversation: ConversationItem): void {
+ if (!conversation) return;
+ const { conversations } = useChatStore.getState();
+ useChatStore.setState({
+ conversations: conversations.map((c) => (c.id === conversation.id ? conversation : c)),
+ });
+}
+
+export function removeConversation(id: number): void {
+ if (id == null) return;
+ const { conversations, activeConversationId } = useChatStore.getState();
+ const next = conversations.filter((c) => c.id !== id);
+ if (next.length === conversations.length) return;
+ const update: Partial<ChatState> = { conversations: next };
+ if (activeConversationId === id) {
+ const idx = conversations.findIndex((c) => c.id === id);
+ const neighbor = next[Math.min(idx, next.length - 1)] ?? null;
+ update.activeConversationId = neighbor?.id ?? null;
+ }
+ useChatStore.setState(update);
+}
+
+export function setActiveConversationId(id: number | null): void {
+ if (useChatStore.getState().activeConversationId === id) return;
+ useChatStore.setState({ activeConversationId: id });
+}
+
+export function getActiveConversationIdValue(): number | null {
+ return useChatStore.getState().activeConversationId;
+}
+
+export function useConversations(): ConversationItem[] {
+ return useChatStore((state) => state.conversations);
+}
+
+export function useActiveConversationId(): number | null {
+ return useChatStore((state) => state.activeConversationId);
+}
+
+export function useActiveConversation(): ConversationItem | null {
+ return useChatStore((state) => {
+ if (state.activeConversationId == null) return null;
+ return state.conversations.find((c) => c.id === state.activeConversationId) ?? null;
+ });
+}
+
+export function useChatMigration(): { total: number; done: number } | null {
+ return useChatStore((state) => state.migration);
+}
+
+export async function syncConversationToCloud(conversation: ConversationItem): Promise<void> {
+ const { ConversationsService } = await import("../services/ConversationsService.js");
+
+ const messages = (await window.electronAPI?.getAgentMessages?.(conversation.id)) ?? [];
+
+ const cloudConv = await ConversationsService.create({
+ client_conversation_id: String(conversation.id),
+ title: conversation.title,
+ created_at: conversation.created_at,
+ updated_at: conversation.updated_at,
+ messages: messages.map((m) => ({
+ role: m.role,
+ content: m.content,
+ })),
+ });
+
+ updateConversation({ ...conversation, cloud_id: cloudConv.id });
+}
+
+export async function syncMessageToCloud(
+ conversation: ConversationItem,
+ role: "user" | "assistant" | "system",
+ content: string,
+ metadata?: Record<string, unknown> | null
+): Promise<void> {
+ const { ConversationsService } = await import("../services/ConversationsService.js");
+ if (conversation.cloud_id) {
+ await ConversationsService.addMessage(conversation.cloud_id, role, content, metadata);
+ } else {
+ await syncConversationToCloud(conversation);
+ }
+}
+
+export async function syncConversationUpdateToCloud(
+ conversation: ConversationItem,
+ updates: { title?: string; archived_at?: string }
+): Promise<void> {
+ const { ConversationsService } = await import("../services/ConversationsService.js");
+ if (conversation.cloud_id) {
+ await ConversationsService.update(conversation.cloud_id, updates);
+ } else {
+ await syncConversationToCloud(conversation);
+ }
+}
+
+export async function syncConversationDeleteToCloud(cloudId: string): Promise<void> {
+ const { ConversationsService } = await import("../services/ConversationsService.js");
+ await ConversationsService.delete(cloudId);
+}
+
+export async function startConversationMigration(): Promise<void> {
+ const allConversations = (await window.electronAPI?.getAgentConversations?.(9999)) ?? [];
+ const unsynced = allConversations.filter(
+ (c: ConversationItem) => !(c as ConversationItem).cloud_id
+ );
+ if (unsynced.length === 0) return;
+
+ useChatStore.setState({ migration: { total: unsynced.length, done: 0 } });
+
+ for (const conv of unsynced) {
+ try {
+ await syncConversationToCloud(conv as ConversationItem);
+ useChatStore.setState((s) => ({
+ migration: s.migration
+ ? {
+ total: s.migration.total,
+ done: Math.min(s.migration.done + 1, s.migration.total),
+ }
+ : null,
+ }));
+ } catch (err) {
+ console.error("Conversation migration failed:", err);
+ }
+ }
+
+ useChatStore.setState({ migration: null });
+}
diff --git a/src/types/electron.ts b/src/types/electron.ts
index fd7c551b3..e27974439 100644
--- a/src/types/electron.ts
+++ b/src/types/electron.ts
@@ -269,6 +269,18 @@ export interface LlamaVulkanDownloadProgress {
percentage: number;
}
+export interface ConversationPreview {
+ id: number;
+ title: string;
+ created_at: string;
+ updated_at: string;
+ archived_at?: string | null;
+ cloud_id?: string | null;
+ message_count: number;
+ last_message?: string | null;
+ last_message_role?: "user" | "assistant" | "system" | null;
+}
+
export interface ReferralItem {
id: string;
email: string;
@@ -1014,6 +1026,7 @@ declare global {
conversation_id: number;
role: "user" | "assistant" | "system";
content: string;
+ metadata?: string;
created_at: string;
}>;
} | null>;
@@ -1038,9 +1051,26 @@ declare global {
conversation_id: number;
role: "user" | "assistant" | "system";
content: string;
+ metadata?: string;
created_at: string;
}>
>;
+ getAgentConversationsWithPreview?: (
+ limit?: number,
+ offset?: number,
+ includeArchived?: boolean
+ ) => Promise<ConversationPreview[]>;
+ searchAgentConversations?: (query: string, limit?: number) => Promise<ConversationPreview[]>;
+ archiveAgentConversation?: (id: number) => Promise<{ success: boolean }>;
+ unarchiveAgentConversation?: (id: number) => Promise<{ success: boolean }>;
+ updateAgentConversationCloudId?: (
+ id: number,
+ cloudId: string
+ ) => Promise<{ success: boolean }>;
+ semanticSearchConversations?: (
+ query: string,
+ limit?: number
+ ) => Promise<ConversationPreview[]>;
// Deepgram Streaming
deepgramStreamingWarmup?: (options?: { sampleRate?: number; language?: string }) => Promise<{