YC (S26) | Open Computer History | Continuously record your company computer work, map your workflows, help you find work worth automating, and power your agents' context
Rust agentsagiaiai-memoryaudio-recordingcomputer-visionhermeshermes-agentllmlocal-ailocal-firstmachine-learningmcpmultimodalopenclawprivacyrewindscreen-recordingspeech-to-textycombinator
fix(chat): resolve multiple chat state bugs (#4082)
Divanshuc5d59c078613
diff --git a/apps/screenpipe-app-tauri/components/chat-sidebar.tsx b/apps/screenpipe-app-tauri/components/chat-sidebar.tsxindex a93e9cd10..f4b94218d 100644--- a/apps/screenpipe-app-tauri/components/chat-sidebar.tsx+++ b/apps/screenpipe-app-tauri/components/chat-sidebar.tsx@@ -145,6 +145,8 @@ function useVisibleChatSections(): {for (const s of sessions) {const isPipeKind = s.kind === "pipe-watch" || s.kind === "pipe-run";if (isPipeKind && liveScheduledSids.has(s.id)) continue;+ // Hide drafts (no user message sent yet)+ // Once a message is sent, draft is cleared and the chat becomes visibleif (s.draft) continue;if (s.hidden) {archived.push(s);diff --git a/apps/screenpipe-app-tauri/components/hooks/use-chat-conversations.ts b/apps/screenpipe-app-tauri/components/hooks/use-chat-conversations.tsindex f4291c584..796a1fa9e 100644--- a/apps/screenpipe-app-tauri/components/hooks/use-chat-conversations.ts+++ b/apps/screenpipe-app-tauri/components/hooks/use-chat-conversations.ts@@ -734,6 +734,9 @@ export function useChatConversations(opts: UseChatConversationsOpts) {computedLastUserMessageAt ?? fromStore ?? existing?.lastUserMessageAt;return lastUserMessageAt ? { lastUserMessageAt } : {};})()),+ // Persist the preset ID so the model selection survives app restart+ // and is restored when switching between chats.+ ...(selectedPreset?.id ? { presetId: selectedPreset.id } : existing?.presetId ? { presetId: existing.presetId } : {}),};// Mirror the final messages into the in-memory chat-store BEFORE@@ -1257,6 +1260,17 @@ export function useChatConversations(opts: UseChatConversationsOpts) {} catch (e) {console.warn("Failed to update active conversation:", e);}++ // Emit the preset ID so the chat panel can restore the model selection.+ // This ensures the model selector reflects the preset used in this chat.+ const presetId = persisted?.presetId ?? (conv as ChatConversation).presetId;+ if (presetId) {+ try {+ await emit("chat-preset-restore", { presetId });+ } catch {+ // ignore broadcast failures+ }+ }};// ---- branchConversation ----diff --git a/apps/screenpipe-app-tauri/components/standalone-chat.tsx b/apps/screenpipe-app-tauri/components/standalone-chat.tsxindex dca812fdf..44e6c8afa 100644--- a/apps/screenpipe-app-tauri/components/standalone-chat.tsx+++ b/apps/screenpipe-app-tauri/components/standalone-chat.tsx@@ -3964,6 +3964,26 @@ export function StandaloneChat({};}, []);+ // Listen for preset restore events when switching chats.+ // This ensures the model selector reflects the preset used in the+ // conversation being loaded, preventing model bleed across chats.+ useEffect(() => {+ const unlisten = listen<{ presetId: string }>(+ "chat-preset-restore",+ (event) => {+ const { presetId } = event.payload;+ if (!presetId || !settings?.aiPresets) return;+ const match = settings.aiPresets.find((p: any) => p.id === presetId);+ if (match) {+ setActivePreset(match);+ }+ },+ );+ return () => {+ unlisten.then((fn) => fn()).catch(() => {});+ };+ }, [settings?.aiPresets]);+// Component-lifetime guard for bus handlers that fire across the// longer-lived useEffects (terminated, foreground registrations).// Useful because the panel's per-effect `mounted` flags are scoped@@ -5505,6 +5525,15 @@ export function StandaloneChat({// When watching a pipe, agent_end fires before pipe_done — don't// clear pipe refs here, let pipe_done handle cleanup instead.const isPipeWatch = piMessageIdRef.current?.startsWith("pipe-");++ // Always clear loading/streaming state on agent_end, even if piMessageIdRef is null+ // This fixes the "stuck loading" bug when the ref was cleared prematurely+ if (!isPipeWatch) {+ setIsLoading(false);+ setIsStreaming(false);+ emitSessionActivity({ status: "idle" });+ }+if (piMessageIdRef.current && !isPipeWatch) {const msgId = piMessageIdRef.current;// Use streamed text if available, otherwise extract from agent_end messages@@ -6698,6 +6727,10 @@ export function StandaloneChat({// activity (text_delta, agent_end) does NOT bump this; the// sidebar order is otherwise stable.storeState.actions.patch(sidNow, { lastUserMessageAt: Date.now() });+ // Clear the draft flag so the chat appears in the sidebar immediately.+ // Without this, navigating away before the assistant responds leaves+ // the session hidden (draft:true) even though there's a user message.+ storeState.actions.patch(sidNow, { draft: false });}posthog.capture("chat_message_sent", {diff --git a/apps/screenpipe-app-tauri/lib/chat-storage.ts b/apps/screenpipe-app-tauri/lib/chat-storage.tsindex 8aec9d6fb..eef93e4dd 100644--- a/apps/screenpipe-app-tauri/lib/chat-storage.ts+++ b/apps/screenpipe-app-tauri/lib/chat-storage.ts@@ -193,6 +193,9 @@ export interface ConversationMeta {* `chat-conversation-saved`) the same way `dedupeConversationMetas` does* on disk. Undefined for pipe runs / chats with no user message yet. */dedupKey?: string;+ /** The AI preset ID last used in this conversation. Used to restore+ * the model selection when switching between chats. */+ presetId?: string;}interface ConversationEntry {@@ -307,6 +310,7 @@ export function conversationMetaFromJson(conv: any): ConversationMeta | null {pipeContext: conv.pipeContext,titleSource: conv.titleSource,dedupKey: conversationDedupKey(conv) ?? undefined,+ presetId: typeof conv.presetId === "string" ? conv.presetId : undefined,};}diff --git a/apps/screenpipe-app-tauri/lib/hooks/use-settings.tsx b/apps/screenpipe-app-tauri/lib/hooks/use-settings.tsxindex e8ba06abe..716c1800d 100644--- a/apps/screenpipe-app-tauri/lib/hooks/use-settings.tsx+++ b/apps/screenpipe-app-tauri/lib/hooks/use-settings.tsx@@ -182,6 +182,10 @@ export interface ChatConversation {/** Title source priority: user > ai > fallback. Used to prevent* lower-priority titles from overwriting higher-priority ones. */titleSource?: "user" | "ai" | "fallback";+ /** The AI preset ID last used in this conversation. Used to restore+ * the model selection when switching between chats. Persisted to disk+ * so the selection survives app restart. */+ presetId?: string;}export interface ChatHistoryStore {diff --git a/apps/screenpipe-app-tauri/lib/stores/chat-store.ts b/apps/screenpipe-app-tauri/lib/stores/chat-store.tsindex e55b451ca..372a049f8 100644--- a/apps/screenpipe-app-tauri/lib/stores/chat-store.ts+++ b/apps/screenpipe-app-tauri/lib/stores/chat-store.ts@@ -120,6 +120,10 @@ export interface SessionRecord {* by clicking "New chat" repeatedly. Cleared on the first successful* save (after the assistant replies). */draft?: boolean;+ /** The AI preset ID last used in this conversation. Used to restore+ * the model selection when switching between chats. Persisted to disk+ * so the selection survives app restart. */+ presetId?: string;// ── Live session content (Phase 3) ─────────────────────────────────// The chat panel reads these instead of holding its own per-render@@ -641,6 +645,7 @@ export function sessionRecordFromMeta(m: ConversationMeta): SessionRecord {kind: m.kind,pipeContext: m.pipeContext,dedupKey: m.dedupKey,+ presetId: m.presetId,};}@@ -741,6 +746,24 @@ function sessionDedupKey(s: SessionRecord): string | null {return conversationDedupKey({ kind: s.kind, messages: s.messages }) ?? s.dedupKey ?? null;}+/** Special dedup key for empty/draft sessions (no user message yet).+ * All empty drafts within the dedup window are considered duplicates+ * to prevent the sidebar from showing multiple "new chat" rows from+ * rapid clicks or race conditions. Returns a sentinel key for drafts,+ * null for non-drafts. */+function emptyDraftDedupKey(s: SessionRecord): string | null {+ // Pipe sessions are exempt from dedup+ if (s.kind === "pipe-watch" || s.kind === "pipe-run") return null;+ // Only apply to draft sessions (no user messages yet)+ if (!s.draft) return null;+ // Check if truly empty+ const msgs = (s.messages as Array<{ role?: string }> | undefined) ?? [];+ const hasUserMessage = msgs.some((m) => m?.role === "user");+ if (hasUserMessage) return null;+ // All empty drafts dedup to this sentinel key+ return "__empty_draft__";+}+/** Which of two same-conversation rows to keep: the copy the user should see.* Prefer a visible (non-archived) row, then pinned, then a row with a real* (non-"Processing…") reply, then more messages, then most-recent activity.@@ -766,7 +789,12 @@ export function dedupeSessionRecords(records: SessionRecord[]): SessionRecord[]const kept: SessionRecord[] = [];const indicesByKey = new Map<string, number[]>();for (const rec of records) {- const key = sessionDedupKey(rec);+ // First try the standard dedup key (from first user message)+ let key = sessionDedupKey(rec);+ // If no standard key, try the empty draft key+ if (!key) {+ key = emptyDraftDedupKey(rec);+ }if (!key) {kept.push(rec);continue;diff --git a/apps/screenpipe-app-tauri/lib/stores/pi-event-router.ts b/apps/screenpipe-app-tauri/lib/stores/pi-event-router.tsindex 7c6577be6..4b5152484 100644--- a/apps/screenpipe-app-tauri/lib/stores/pi-event-router.ts+++ b/apps/screenpipe-app-tauri/lib/stores/pi-event-router.ts@@ -528,6 +528,10 @@ function applyEventToSessionContent(sid: string, payload: PiInnerEvent) {isStreaming: true,isLoading: true,});+ // Clear the draft flag so the chat appears in the sidebar.+ // This is needed when a queued follow-up starts while the user+ // has navigated away from the chat.+ store.actions.patch(sid, { draft: false });return;}