Skip to content

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

fix(chat): rigour pass over multi-chat sidebar — edge cases + persistence

Louis Beaumont9a5be008d5b2
diff --git a/apps/screenpipe-app-tauri/components/chat-sidebar.tsx b/apps/screenpipe-app-tauri/components/chat-sidebar.tsx
index b54214214..ec38b4c1f 100644
--- a/apps/screenpipe-app-tauri/components/chat-sidebar.tsx
+++ b/apps/screenpipe-app-tauri/components/chat-sidebar.tsx
@@ -8,22 +8,32 @@
* that have a Pi process running in the background. Renders to the left of
* the chat panel when the user is on the Home / Chat view.
*
- * Phase 1 scope (this commit):
- * - List sessions from the chat store (hydrated by pi-event-router from
- * ~/.screenpipe/chats/*.json on boot).
- * - "+ new chat" emits the existing `chat-load-conversation` event with a
- * fresh uuid so `standalone-chat.tsx`'s existing handler kicks in.
- * - Click a row → emits the same event with the row's id.
- * - Live `●` dot driven by `session.status === "streaming" | "thinking"`.
- * - Pin / close hover actions.
+ * Data flow:
*
- * Phase 2 will replace the cross-component event with direct store reads
- * once `standalone-chat` is migrated to the store.
+ * ┌────────────────────────┐ emit chat-load-conversation ┌───────────┐
+ * │ ChatSidebar (this file)├──────────────────────────────▶│ Standalone│
+ * │ │ │ Chat │
+ * │ reads chat-store │ emit chat-current-session │ │
+ * │ emits user actions │◀──────────────────────────────┤ (mounts │
+ * │ │ │ Pi via │
+ * │ │ │ piStart) │
+ * └────────┬───────────────┘ └────┬──────┘
+ * │ writes pinned/hidden │ writes deltas
+ * ▼ ▼ to Pi stdout
+ * ┌────────────────────────┐ ┌────────────────────────────────┐
+ * │ chat-storage.ts │ │ pi-event-router.ts │
+ * │ (~/.screenpipe/chats/) │ │ listens app-wide for pi_event │
+ * │ │ │ writes status/preview to store │
+ * └────────────────────────┘ └────────────────────────────────┘
+ *
+ * Pin / close persist to the conversation's JSON file on disk so the state
+ * survives app restart. Close is non-destructive (sets `hidden: true`);
+ * a separate "delete forever" action would unlink the file.
*/
-import React, { useMemo } from "react";
-import { Plus, Pin, X } from "lucide-react";
-import { emit } from "@tauri-apps/api/event";
+import React, { useEffect, useMemo } from "react";
+import { Plus, Pin, X, AlertCircle } from "lucide-react";
+import { emit, listen } from "@tauri-apps/api/event";
import { cn } from "@/lib/utils";
import {
useChatStore,
@@ -31,7 +41,7 @@ import {
selectOrderedSessions,
type SessionRecord,
} from "@/lib/stores/chat-store";
-import { deleteConversationFile } from "@/lib/chat-storage";
+import { updateConversationFlags } from "@/lib/chat-storage";
interface ChatSidebarProps {
className?: string;
@@ -42,6 +52,27 @@ export function ChatSidebar({ className }: ChatSidebarProps) {
const currentId = useChatStore((s) => s.currentId);
const actions = useChatActions();
+ // Sync currentId from standalone-chat. Whenever the chat panel switches
+ // its piSessionIdRef (new chat, prefill auto-send, history click in the
+ // panel itself), it emits this event so the sidebar can highlight the
+ // matching row. Without this the sidebar would silently disagree with
+ // the chat about "which session is current".
+ useEffect(() => {
+ let unlistenFn: (() => void) | undefined;
+ let cancelled = false;
+ (async () => {
+ const u = await listen<{ id: string }>("chat-current-session", (e) => {
+ if (cancelled) return;
+ actions.setCurrent(e.payload.id);
+ });
+ unlistenFn = u;
+ })();
+ return () => {
+ cancelled = true;
+ unlistenFn?.();
+ };
+ }, [actions]);
+
const { pinned, recents } = useMemo(() => {
const p: SessionRecord[] = [];
const r: SessionRecord[] = [];
@@ -51,7 +82,9 @@ export function ChatSidebar({ className }: ChatSidebarProps) {
const handleNew = () => {
const id = crypto.randomUUID();
- emit("chat-load-conversation", { conversationId: id });
+ // Optimistically add the row so the sidebar feels responsive even if
+ // standalone-chat takes a tick to react. The router will pick up the
+ // session if/when Pi starts emitting events for it.
actions.upsert({
id,
title: "new chat",
@@ -62,9 +95,14 @@ export function ChatSidebar({ className }: ChatSidebarProps) {
pinned: false,
});
actions.setCurrent(id);
+ // chat-load-conversation with an unknown id is treated by
+ // standalone-chat's listener as "start a new chat with this id" —
+ // see the matching handler in components/standalone-chat.tsx.
+ emit("chat-load-conversation", { conversationId: id });
};
const handleSelect = (id: string) => {
+ if (id === currentId) return; // already on it, no-op
actions.setCurrent(id);
emit("chat-load-conversation", { conversationId: id });
};
@@ -72,12 +110,47 @@ export function ChatSidebar({ className }: ChatSidebarProps) {
const handleClose = async (e: React.MouseEvent, id: string) => {
e.stopPropagation();
actions.drop(id);
- await deleteConversationFile(id).catch(() => {});
+ // If the user closed the chat they were viewing, tell standalone-chat
+ // to clear the panel. Otherwise the panel would keep showing a
+ // conversation that no longer exists in the sidebar.
+ if (id === currentId) {
+ const fresh = crypto.randomUUID();
+ actions.upsert({
+ id: fresh,
+ title: "new chat",
+ preview: "",
+ status: "idle",
+ messageCount: 0,
+ updatedAt: Date.now(),
+ pinned: false,
+ });
+ actions.setCurrent(fresh);
+ emit("chat-load-conversation", { conversationId: fresh });
+ }
+ // Persist hidden=true to disk so the close survives restart. Failures
+ // here are best-effort — if the file doesn't exist (session never
+ // saved) the in-memory drop is enough; if the disk write fails (perm,
+ // disk full) the sidebar will re-show the row on next launch which is
+ // not great but recoverable by closing again. We don't surface an
+ // error toast for this — too low-stakes.
+ try {
+ await updateConversationFlags(id, { hidden: true });
+ } catch {
+ // intentional — see comment above
+ }
};
- const handleTogglePin = (e: React.MouseEvent, id: string) => {
+ const handleTogglePin = async (e: React.MouseEvent, id: string) => {
e.stopPropagation();
+ const session = useChatStore.getState().sessions[id];
+ if (!session) return;
+ const next = !session.pinned;
actions.togglePinned(id);
+ try {
+ await updateConversationFlags(id, { pinned: next });
+ } catch {
+ // best-effort persistence — UI already updated
+ }
};
return (
@@ -89,7 +162,6 @@ export function ChatSidebar({ className }: ChatSidebarProps) {
)}
data-testid="chat-sidebar"
>
- {/* + new chat */}
<div className="px-3 pt-3 pb-2">
<button
onClick={handleNew}
@@ -98,12 +170,12 @@ export function ChatSidebar({ className }: ChatSidebarProps) {
"text-foreground hover:bg-muted/50 transition-colors",
"text-sm font-medium"
)}
+ data-testid="chat-sidebar-new"
>
<Plus className="h-4 w-4" /> new chat
</button>
</div>
- {/* scroll region */}
<div className="flex-1 overflow-y-auto overflow-x-hidden">
{pinned.length > 0 && (
<Section title="pinned">
@@ -168,8 +240,8 @@ interface ChatRowProps {
session: SessionRecord;
isCurrent: boolean;
onSelect: (id: string) => void;
- onClose: (e: React.MouseEvent, id: string) => void;
- onTogglePin: (e: React.MouseEvent, id: string) => void;
+ onClose: (e: React.MouseEvent, id: string) => Promise<void> | void;
+ onTogglePin: (e: React.MouseEvent, id: string) => Promise<void> | void;
}
function ChatRow({
@@ -183,6 +255,7 @@ function ChatRow({
session.status === "streaming" ||
session.status === "thinking" ||
session.status === "tool";
+ const isError = session.status === "error";
return (
<button
onClick={() => onSelect(session.id)}
@@ -194,6 +267,7 @@ function ChatRow({
: "text-foreground/80 hover:bg-muted/40"
)}
data-testid={`chat-row-${session.id}`}
+ title={isError && session.lastError ? session.lastError : undefined}
>
<div className="flex items-center gap-1.5 min-w-0">
<span className="truncate flex-1 text-sm">
@@ -205,6 +279,12 @@ function ChatRow({
title={session.status}
/>
)}
+ {isError && (
+ <AlertCircle
+ className="h-3 w-3 text-red-500 shrink-0"
+ aria-label={session.lastError || "error"}
+ />
+ )}
{/* hover-only actions */}
<span className="hidden group-hover:inline-flex items-center gap-1 shrink-0">
<span
@@ -216,7 +296,9 @@ function ChatRow({
<Pin
className={cn(
"h-3 w-3",
- session.pinned ? "text-foreground fill-current" : "text-muted-foreground"
+ session.pinned
+ ? "text-foreground fill-current"
+ : "text-muted-foreground"
)}
/>
</span>
@@ -224,7 +306,7 @@ function ChatRow({
role="button"
onClick={(e) => onClose(e, session.id)}
className="p-0.5 rounded hover:bg-muted text-muted-foreground"
- title="close + delete"
+ title="close"
>
<X className="h-3 w-3" />
</span>
@@ -234,7 +316,11 @@ function ChatRow({
<div
className={cn(
"text-[11px] truncate mt-0.5",
- isLive ? "text-orange-600/80 italic" : "text-muted-foreground/70"
+ isError
+ ? "text-red-500/80"
+ : isLive
+ ? "text-orange-600/80 italic"
+ : "text-muted-foreground/70"
)}
>
{session.preview}
diff --git a/apps/screenpipe-app-tauri/components/standalone-chat.tsx b/apps/screenpipe-app-tauri/components/standalone-chat.tsx
index 18909ff7f..51bc9cff6 100644
--- a/apps/screenpipe-app-tauri/components/standalone-chat.tsx
+++ b/apps/screenpipe-app-tauri/components/standalone-chat.tsx
@@ -1609,21 +1609,71 @@ export function StandaloneChat({ className }: { className?: string } = {}) {
};
}, [piInfo]);
- // Listen for chat-load-conversation events from timeline
+ // Listen for chat-load-conversation events. Sources:
+ // - timeline (clicking a previous chat in the timeline view)
+ // - chat sidebar (selecting a row, OR clicking "+ new chat" which
+ // sends a freshly-generated id we've never seen before)
+ // - pi_session_evicted handler below (fresh id when the pool kills
+ // the current session)
+ //
+ // If the id corresponds to a saved conversation on disk, load it. If
+ // not, treat it as "start a new chat using THIS id" — the caller (e.g.
+ // the sidebar's + new chat button) generated the id and wants the chat
+ // panel to adopt it so both agree on the session id from message 1.
useEffect(() => {
const unlisten = listen<{ conversationId: string }>("chat-load-conversation", async (event) => {
const { conversationId: convId } = event.payload;
- // Load from file-based storage
const { loadConversationFile } = await import("@/lib/chat-storage");
const conv = await loadConversationFile(convId);
if (conv) {
loadConversation(conv);
+ } else {
+ // Unknown id → start a new chat that adopts the requested id so
+ // sidebar + chat agree. startNewConversation generates its own
+ // uuid; we override piSessionIdRef immediately after to honor the
+ // caller's id.
+ await startNewConversation();
+ piSessionIdRef.current = convId;
+ // Mirror the new id back to the sidebar so its currentId matches.
+ emit("chat-current-session", { id: convId });
}
});
return () => { unlisten.then((fn) => fn()); };
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
+ // Tell the sidebar which session is current whenever the chat panel
+ // assigns or resumes a session id. Without this the sidebar wouldn't
+ // know about session changes initiated inside the chat (in-panel "new",
+ // chat-prefill auto-send, history pick from the in-panel history view).
+ useEffect(() => {
+ if (!conversationId) return;
+ emit("chat-current-session", { id: conversationId });
+ }, [conversationId]);
+
+ // If the Pi pool evicted the session we're currently viewing, swap the
+ // panel to a fresh one. The pool only evicts idle sessions (see
+ // pi.rs::pi_start_inner), so this is rare — but when it does happen the
+ // user shouldn't be left with a panel pointing at a dead pid.
+ useEffect(() => {
+ let unlistenFn: (() => void) | undefined;
+ let cancelled = false;
+ (async () => {
+ const u = await listen<{ session: string }>("pi_session_evicted", async (event) => {
+ if (cancelled) return;
+ if (event.payload.session !== piSessionIdRef.current) return;
+ await startNewConversation();
+ emit("chat-current-session", { id: piSessionIdRef.current });
+ });
+ unlistenFn = u;
+ })();
+ return () => {
+ cancelled = true;
+ unlistenFn?.();
+ };
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, []);
+
// Pick up pending conversation from pipe execution history (set via localStorage
// because the emit event is lost during page navigation/remount)
useEffect(() => {
@@ -4492,10 +4542,10 @@ export function StandaloneChat({ className }: { className?: string } = {}) {
</div>
<div className="text-muted-foreground">
{!isPro
- ? "Remove names, emails, phone numbers and other personal info from your screen data before the AI sees it. Click the shield to upgrade."
+ ? "Remove names, emails, phone numbers and other personal info from your screen data before the AI sees it. Adds ~1–2s per search. Click the shield to upgrade."
: privacyOn
- ? "Names, emails, phone numbers and other personal info are removed from your screen data before it reaches the AI. Click the shield to turn off."
- : "Turn this on to strip personal info (names, emails, phones, addresses, account numbers) from your screen data before the AI sees it."}
+ ? "Names, emails, phone numbers and other personal info are removed from your screen data before it reaches the AI. Adds ~1–2s per search. Click the shield to turn off."
+ : "Turn this on to strip personal info (names, emails, phones, addresses, account numbers) from your screen data before the AI sees it. Adds ~1–2s per search."}
</div>
<button
type="button"
diff --git a/apps/screenpipe-app-tauri/lib/chat-storage.ts b/apps/screenpipe-app-tauri/lib/chat-storage.ts
index b17b7bf97..cb550bf4e 100644
--- a/apps/screenpipe-app-tauri/lib/chat-storage.ts
+++ b/apps/screenpipe-app-tauri/lib/chat-storage.ts
@@ -74,6 +74,12 @@ export interface ConversationMeta {
createdAt: number;
updatedAt: number;
messageCount: number;
+ /** User-pinned (keeps row at the top of the sidebar). Defaults to false. */
+ pinned: boolean;
+ /** User-closed (excluded from default sidebar listing). Defaults to false.
+ * Conversation file is still on disk; only an explicit delete action removes
+ * it. The sidebar filters these out by default. */
+ hidden: boolean;
}
export async function listConversations(): Promise<ConversationMeta[]> {
@@ -94,6 +100,8 @@ export async function listConversations(): Promise<ConversationMeta[]> {
createdAt: conv.createdAt,
updatedAt: conv.updatedAt,
messageCount: conv.messages.length,
+ pinned: conv.pinned === true,
+ hidden: conv.hidden === true,
});
} catch {
// skip corrupt files
@@ -105,6 +113,25 @@ export async function listConversations(): Promise<ConversationMeta[]> {
return metas;
}
+/**
+ * Patch a single field on a conversation file in place. Used by the chat
+ * sidebar to persist `pinned` / `hidden` toggles without rewriting messages.
+ *
+ * No-op if the file doesn't exist (caller may be acting on a session that
+ * was never sent to disk yet — sidebar's row exists in memory only). The
+ * read+write is not atomic across processes, but conflicts are functionally
+ * harmless for these flags (last writer wins, no data loss).
+ */
+export async function updateConversationFlags(
+ id: string,
+ patch: Partial<Pick<ChatConversation, "pinned" | "hidden" | "title">>
+): Promise<void> {
+ const conv = await loadConversationFile(id);
+ if (!conv) return;
+ const next: ChatConversation = { ...conv, ...patch };
+ await saveConversationFile(next);
+}
+
export async function loadAllConversations(): Promise<ChatConversation[]> {
const dir = await getChatsDir();
if (!(await exists(dir))) return [];
diff --git a/apps/screenpipe-app-tauri/lib/hooks/use-settings.tsx b/apps/screenpipe-app-tauri/lib/hooks/use-settings.tsx
index 10f3efb1c..ff50c4914 100644
--- a/apps/screenpipe-app-tauri/lib/hooks/use-settings.tsx
+++ b/apps/screenpipe-app-tauri/lib/hooks/use-settings.tsx
@@ -90,6 +90,14 @@ export interface ChatConversation {
messages: ChatMessage[];
createdAt: number;
updatedAt: number;
+ /** User pinned this conversation in the chat sidebar — keeps it at the top.
+ * Persists across app restarts via the on-disk conversation file. */
+ pinned?: boolean;
+ /** User closed this conversation from the chat sidebar — keeps the file on
+ * disk (so deleting via close is non-destructive) but excludes it from the
+ * sidebar listing. Re-surface via a future "show hidden" UI; meanwhile a
+ * dedicated delete-forever action is the only way to actually remove. */
+ hidden?: boolean;
}
export interface ChatHistoryStore {
diff --git a/apps/screenpipe-app-tauri/lib/stores/chat-store.ts b/apps/screenpipe-app-tauri/lib/stores/chat-store.ts
index f2d1fedc6..2720dc66c 100644
--- a/apps/screenpipe-app-tauri/lib/stores/chat-store.ts
+++ b/apps/screenpipe-app-tauri/lib/stores/chat-store.ts
@@ -38,6 +38,8 @@ export interface SessionRecord {
preview: string;
/** Current liveness state (drives the sidebar dot / pulse). */
status: SessionStatus;
+ /** Last error message — only meaningful when `status === "error"`. */
+ lastError?: string;
/** Number of messages persisted to disk for this session. */
messageCount: number;
/** ms since epoch of the most recent activity (for sort + LRU). */
diff --git a/apps/screenpipe-app-tauri/lib/stores/pi-event-router.ts b/apps/screenpipe-app-tauri/lib/stores/pi-event-router.ts
index f45ef7144..7dee8a498 100644
--- a/apps/screenpipe-app-tauri/lib/stores/pi-event-router.ts
+++ b/apps/screenpipe-app-tauri/lib/stores/pi-event-router.ts
@@ -5,19 +5,24 @@
/**
* App-level Pi event router.
*
- * Subscribes to `pi_event` and `pi_session_evicted` ONCE per webview, lives
- * outside any React component lifecycle so subscriptions survive when the
- * user navigates away from the chat view. Mirrors per-session liveness into
- * the chat store so the sidebar can show live status (●, pulse, "thinking…")
+ * Subscribes to Pi lifecycle events ONCE per webview, lives outside any
+ * React component lifecycle so subscriptions survive when the user
+ * navigates away from the chat view. Mirrors per-session liveness into the
+ * chat store so the sidebar can show live status (●, pulse, "thinking…")
* for chats running in the background.
*
- * Phase 1 scope: status mirroring + last-preview update + on-disk hydration.
- * Does NOT take ownership of the message stream — `standalone-chat.tsx`
- * still owns its own message state for the active chat. Phase 2 lifts that
- * state into the chat-store and this router becomes the sole writer.
+ * Events handled:
+ * - `pi_event` : streaming events (status + preview)
+ * - `pi_terminated` : session subprocess exited (clean or crash)
+ * - `pi_session_evicted` : pool kicked the session out for capacity
+ *
+ * Phase 2 scope: status mirroring + preview update + on-disk hydration +
+ * persistence of pin/hide flags (the *content* of messages still belongs
+ * to standalone-chat — phase 3 lifts that into the store too).
*
* Idempotent: calling `mountPiEventRouter()` more than once is a no-op
- * after the first successful mount.
+ * after the first successful mount. Safe under React Strict Mode's
+ * double-invoke and under hot reload.
*/
import { listen, type UnlistenFn } from "@tauri-apps/api/event";
@@ -28,29 +33,39 @@ import {
type SessionRecord,
} from "@/lib/stores/chat-store";
+// Module-level state — the router is a singleton process-wide.
let mounted = false;
+let mountPromise: Promise<UnlistenFn> | null = null;
let unlisteners: UnlistenFn[] = [];
/**
* Pi RPC events delivered on the `pi_event` topic. The shape is whatever
* the Pi agent writes to stdout, augmented by `pi.rs` with a `session`
* field identifying which Pi process produced it.
- *
- * We only inspect a few fields here — the chat component still does the
- * heavy parsing for its own state. We just need to know "which session?"
- * + "is it still streaming?" + "what was the last text snippet?".
*/
interface PiEventPayload {
session?: string;
type?: string;
- // text_delta / message_update payloads carry the assistant text
delta?: string;
- // message_update is the 0.70+ event shape
+ // message_update is the 0.70+ event shape (text_delta lives inside)
assistantMessageEvent?: {
type?: string;
delta?: string;
contentIndex?: number;
};
+ // agent_end / message_end may carry an error
+ message?: {
+ role?: string;
+ stopReason?: string;
+ errorMessage?: string;
+ error?: string;
+ };
+}
+
+interface PiTerminatedPayload {
+ session: string;
+ exitCode?: number | null;
+ reason?: string;
}
interface PiSessionEvictedPayload {
@@ -58,7 +73,10 @@ interface PiSessionEvictedPayload {
reason: string;
}
-/** Map a raw event type to a SessionStatus, or null to leave unchanged. */
+/** Map a raw event type to a SessionStatus. Returns null when the event
+ * doesn't carry a status signal (e.g. `tool_execution_end` is ambiguous —
+ * could go back to streaming or end the turn entirely; we wait for the
+ * next definitive event). */
function statusForEvent(evt: PiEventPayload): SessionStatus | null {
switch (evt.type) {
case "agent_start":
@@ -73,15 +91,27 @@ function statusForEvent(evt: PiEventPayload): SessionStatus | null {
return "streaming";
case "agent_end":
case "turn_end":
+ // A turn may end with an error; surface that as a distinct state
+ // so the sidebar can show a red indicator instead of just "idle".
+ if (evt.message?.stopReason === "error") return "error";
return "idle";
+ case "message_start":
+ case "message_end":
+ if (evt.message?.role === "assistant" && evt.message.stopReason === "error") {
+ return "error";
+ }
+ return null;
case "message_update": {
const inner = evt.assistantMessageEvent?.type;
- if (inner === "thinking_start") return "thinking";
- if (inner === "thinking_end" || inner === "thinking_delta") return "thinking";
+ if (inner === "thinking_start" || inner === "thinking_delta") return "thinking";
+ if (inner === "thinking_end") return "streaming";
if (inner === "text_delta") return "streaming";
return null;
}
case "auto_retry_end":
+ // success-or-not is in payload; we conservatively don't change status.
+ // The follow-up agent_end will set the correct terminal state.
+ return null;
case "error":
return "error";
default:
@@ -93,11 +123,29 @@ function statusForEvent(evt: PiEventPayload): SessionStatus | null {
function previewSnippet(evt: PiEventPayload): string | null {
const delta = evt.delta ?? evt.assistantMessageEvent?.delta;
if (typeof delta === "string" && delta.trim()) {
- return delta.slice(0, 80).replace(/\s+/g, " ").trim();
+ // Truncate and normalize whitespace for the sidebar row.
+ const snippet = delta.replace(/\s+/g, " ").trim();
+ return snippet.length > 80 ? `${snippet.slice(0, 80)}…` : snippet;
}
return null;
}
+/** Pull a human-readable error message out of an error-shaped event. */
+function errorMessage(evt: PiEventPayload): string | null {
+ const m = evt.message;
+ if (m?.stopReason === "error") {
+ return m.errorMessage || m.error || "unknown error";
+ }
+ return null;
+}
+
+// Per-session throttling: text_delta fires at ~100Hz; rendering the sidebar
+// row that fast wastes CPU. We coalesce to one preview update per
+// `PREVIEW_THROTTLE_MS` window per session. Status changes bypass the
+// throttle (they're rare and we want them snappy).
+const PREVIEW_THROTTLE_MS = 250;
+const previewLastEmittedAt = new Map<string, number>();
+
async function handlePiEvent(payload: PiEventPayload) {
const sid = payload.session;
if (!sid) return; // events without a session id can't be routed
@@ -105,27 +153,61 @@ async function handlePiEvent(payload: PiEventPayload) {
const store = useChatStore.getState();
const existing = store.sessions[sid];
- // Lazy-create a session record on first event from a previously-unknown
- // session id. This handles the case where Pi was started outside the
- // chat-storage flow (e.g. resumed from disk before we hydrated).
+ const nextStatus = statusForEvent(payload);
+ const snippet = previewSnippet(payload);
+ const err = errorMessage(payload);
+
+ // Lazy-create on first event from a previously-unknown session id.
+ // Handles the case where Pi was started outside the chat-storage flow
+ // (e.g. resumed from disk before we hydrated).
if (!existing) {
store.actions.upsert({
id: sid,
title: "new chat",
- preview: "",
- status: statusForEvent(payload) ?? "streaming",
+ preview: snippet ?? "",
+ status: nextStatus ?? "streaming",
+ lastError: err ?? undefined,
messageCount: 0,
updatedAt: Date.now(),
pinned: false,
});
+ if (snippet) previewLastEmittedAt.set(sid, Date.now());
return;
}
- const nextStatus = statusForEvent(payload);
- const snippet = previewSnippet(payload);
+ // Decide whether to write a preview update — throttled per session.
+ // Status changes always pass through (they're terminal-ish and rare).
+ let writePreview = false;
+ if (snippet) {
+ const last = previewLastEmittedAt.get(sid) ?? 0;
+ const now = Date.now();
+ if (now - last >= PREVIEW_THROTTLE_MS) {
+ writePreview = true;
+ previewLastEmittedAt.set(sid, now);
+ }
+ }
+
const patch: Partial<SessionRecord> = { updatedAt: Date.now() };
if (nextStatus) patch.status = nextStatus;
- if (snippet) patch.preview = snippet;
+ if (writePreview) patch.preview = snippet!;
+ if (nextStatus === "error" && err) patch.lastError = err;
+ if (nextStatus && nextStatus !== "error") patch.lastError = undefined;
+
+ // Skip the store write entirely if nothing meaningful changed (avoids
+ // re-renders for no-op events like the ones whose statusForEvent returns
+ // null and whose preview is throttled).
+ if (
+ patch.status === undefined &&
+ patch.preview === undefined &&
+ patch.lastError === undefined
+ ) {
+ // Still bump updatedAt so the row re-sorts, but only if it's been
+ // longer than the throttle window since the last bump (otherwise we'd
+ // re-render at full delta rate purely for the timestamp).
+ const lastBump = existing.updatedAt;
+ if (Date.now() - lastBump < PREVIEW_THROTTLE_MS) return;
+ }
+
store.actions.patch(sid, patch);
}
@@ -134,25 +216,50 @@ function handleSessionEvicted(payload: PiSessionEvictedPayload) {
// record from the in-memory store so the sidebar reflects reality. The
// on-disk transcript is preserved — user can re-open the conversation
// and a fresh Pi process will be started for the same id.
+ previewLastEmittedAt.delete(payload.session);
useChatStore.getState().actions.drop(payload.session);
}
-/**
- * Hydrate the store from on-disk chat history once at boot. The router
- * keeps this in sync afterwards via incremental events.
- */
+function handleTerminated(payload: PiTerminatedPayload) {
+ // Pi subprocess exited (clean shutdown, crash, manual kill, or app quit).
+ // Flip the session to idle so the sidebar dot stops pulsing. The
+ // conversation history is still on disk; if the user sends another
+ // message, the chat will spawn a fresh process under the same session id.
+ // Clean exits (exitCode 0) are silent; non-zero gets surfaced as an
+ // error so users can see "something happened" instead of a frozen
+ // streaming dot.
+ const store = useChatStore.getState();
+ if (!store.sessions[payload.session]) return;
+ const isCleanExit = payload.exitCode === 0 || payload.exitCode == null;
+ store.actions.patch(payload.session, {
+ status: isCleanExit ? "idle" : "error",
+ lastError: isCleanExit
+ ? undefined
+ : `pi process exited (code ${payload.exitCode}${payload.reason ? `: ${payload.reason}` : ""})`,
+ updatedAt: Date.now(),
+ });
+ previewLastEmittedAt.delete(payload.session);
+}
+
+/** Hydrate the store from on-disk chat history once at boot. The router
+ * keeps this in sync afterwards via incremental events. */
async function hydrate() {
try {
const metas = await listConversations();
- const records: SessionRecord[] = metas.map((m) => ({
- id: m.id,
- title: m.title || "untitled",
- preview: "",
- status: "idle",
- messageCount: m.messageCount,
- updatedAt: m.updatedAt,
- pinned: false,
- }));
+ const records: SessionRecord[] = metas
+ // Hidden conversations are filtered at this boundary so the rest of
+ // the store doesn't need to know about them. A future "show hidden"
+ // UI would need to bypass this filter and read the unfiltered list.
+ .filter((m) => !m.hidden)
+ .map((m) => ({
+ id: m.id,
+ title: m.title || "untitled",
+ preview: "",
+ status: "idle",
+ messageCount: m.messageCount,
+ updatedAt: m.updatedAt,
+ pinned: m.pinned,
+ }));
useChatStore.getState().actions.hydrateFromDisk(records);
} catch {
// Storage may not be ready yet on first launch — non-fatal.
@@ -160,28 +267,38 @@ async function hydrate() {
}
/**
- * Mount the router. Safe to call multiple times — subsequent calls return
- * the same unmount function bound to the original subscriptions.
+ * Mount the router. Safe to call multiple times — concurrent calls return
+ * the same in-flight promise; calls after the mount has completed are a
+ * no-op that returns the existing unmount function.
*
* Returns an unmount function for tests / hot-reload; in production this
* is mounted once at app boot and never torn down.
*/
export async function mountPiEventRouter(): Promise<UnlistenFn> {
- if (mounted) return () => unmountPiEventRouter();
- mounted = true;
+ if (mounted) return unmountPiEventRouter;
+ if (mountPromise) return mountPromise;
- await hydrate();
+ mountPromise = (async () => {
+ await hydrate();
- const piEventUnlisten = await listen<PiEventPayload>("pi_event", (event) => {
- handlePiEvent(event.payload);
- });
- const evictedUnlisten = await listen<PiSessionEvictedPayload>(
- "pi_session_evicted",
- (event) => handleSessionEvicted(event.payload)
- );
- unlisteners.push(piEventUnlisten, evictedUnlisten);
+ const piEventUnlisten = await listen<PiEventPayload>(
+ "pi_event",
+ (event) => handlePiEvent(event.payload)
+ );
+ const evictedUnlisten = await listen<PiSessionEvictedPayload>(
+ "pi_session_evicted",
+ (event) => handleSessionEvicted(event.payload)
+ );
+ const terminatedUnlisten = await listen<PiTerminatedPayload>(
+ "pi_terminated",
+ (event) => handleTerminated(event.payload)
+ );
+ unlisteners.push(piEventUnlisten, evictedUnlisten, terminatedUnlisten);
+ mounted = true;
+ return unmountPiEventRouter;
+ })();
- return () => unmountPiEventRouter();
+ return mountPromise;
}
function unmountPiEventRouter(): void {
@@ -193,5 +310,7 @@ function unmountPiEventRouter(): void {
}
}
unlisteners = [];
+ previewLastEmittedAt.clear();
mounted = false;
+ mountPromise = null;
}