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

Add closed chat in chat list (#3363)

Harsh Kumar087ca6762b6b
diff --git a/apps/screenpipe-app-tauri/app/home/page.tsx b/apps/screenpipe-app-tauri/app/home/page.tsx
index dd6a2e09b..7a9fac1ff 100644
--- a/apps/screenpipe-app-tauri/app/home/page.tsx
+++ b/apps/screenpipe-app-tauri/app/home/page.tsx
@@ -26,7 +26,7 @@ import {
NotebookPen,
} from "lucide-react";
import { emit } from "@tauri-apps/api/event";
-import { useChatStore } from "@/lib/stores/chat-store";
+import { useChatStore, type SessionStatus } from "@/lib/stores/chat-store";
import { useOverlayData } from "@/app/shortcut-reminder/use-overlay-data";
import { cn } from "@/lib/utils";
import { AppSidebar, SidebarProvider, useSidebarContext } from "@/components/app-sidebar";
@@ -151,6 +151,124 @@ function HomeContent() {
void mountPipeWatchWriter();
}, []);
+ // Overlay-side foreground sessions don't pass through this window's
+ // background router path. Mirror lightweight activity (status + preview)
+ // so the home sidebar stays live without mirroring full message bodies.
+ useEffect(() => {
+ let cancelled = false;
+ let unlistenFn: (() => void) | undefined;
+ (async () => {
+ const unlisten = await listen<{
+ id: string;
+ status?: SessionStatus;
+ preview?: string;
+ title?: string;
+ updatedAt: number;
+ lastError?: string;
+ unreadHint?: boolean;
+ }>("chat-session-activity", (event) => {
+ if (cancelled) return;
+ const { id, status, preview, title, updatedAt, lastError, unreadHint } = event.payload ?? {};
+ if (!id || !updatedAt) return;
+ const store = useChatStore.getState();
+ const existing = store.sessions[id];
+ if (!existing) {
+ store.actions.upsert({
+ id,
+ title: title?.trim() || "new chat",
+ preview: preview ?? "",
+ status: status ?? "idle",
+ lastError,
+ messageCount: 0,
+ createdAt: updatedAt,
+ updatedAt,
+ pinned: false,
+ hidden: false,
+ unread: false,
+ });
+ } else {
+ if (existing.updatedAt > updatedAt) return;
+ const nextTitle = title?.trim() || existing.title;
+ const nextPreview = preview ?? existing.preview;
+ const nextStatus = status ?? existing.status;
+ const nextLastError =
+ lastError !== undefined
+ ? lastError || undefined
+ : nextStatus === "error"
+ ? existing.lastError
+ : undefined;
+ if (
+ existing.title === nextTitle &&
+ existing.preview === nextPreview &&
+ existing.status === nextStatus &&
+ existing.lastError === nextLastError &&
+ existing.updatedAt === updatedAt
+ ) return;
+ store.actions.patch(id, {
+ title: nextTitle,
+ preview: nextPreview,
+ status: nextStatus,
+ lastError: nextLastError,
+ updatedAt,
+ });
+ }
+ if (unreadHint && store.currentId !== id && store.panelSessionId !== id) {
+ store.actions.markUnread(id);
+ }
+ });
+ unlistenFn = unlisten;
+ })();
+ return () => {
+ cancelled = true;
+ unlistenFn?.();
+ };
+ }, []);
+
+ // Saved-title correction path. Activity updates are best-effort during
+ // streaming; this event is emitted after canonical on-disk save, so use it
+ // to guarantee Main row title converges from "new chat" to real title.
+ useEffect(() => {
+ let cancelled = false;
+ let unlistenFn: (() => void) | undefined;
+ (async () => {
+ const unlisten = await listen<{ id: string; title?: string }>(
+ "chat-conversation-saved",
+ (event) => {
+ if (cancelled) return;
+ const { id, title } = event.payload ?? {};
+ const nextTitle = title?.trim();
+ if (!id || !nextTitle) return;
+
+ const store = useChatStore.getState();
+ const existing = store.sessions[id];
+ if (!existing) {
+ store.actions.upsert({
+ id,
+ title: nextTitle,
+ preview: "",
+ status: "idle",
+ messageCount: 0,
+ createdAt: Date.now(),
+ updatedAt: Date.now(),
+ pinned: false,
+ hidden: false,
+ unread: false,
+ });
+ return;
+ }
+ if (existing.title !== nextTitle) {
+ store.actions.patch(id, { title: nextTitle });
+ }
+ },
+ );
+ unlistenFn = unlisten;
+ })();
+ return () => {
+ cancelled = true;
+ unlistenFn?.();
+ };
+ }, []);
+
// Selecting a chat from the sidebar (or any other source that emits
// chat-load-conversation) should also FLIP the active view to the chat
// panel. Without this, clicking a chat from the Pipes / Timeline /
diff --git a/apps/screenpipe-app-tauri/components/chat-sidebar.tsx b/apps/screenpipe-app-tauri/components/chat-sidebar.tsx
index 561d2fb79..3e228cb20 100644
--- a/apps/screenpipe-app-tauri/components/chat-sidebar.tsx
+++ b/apps/screenpipe-app-tauri/components/chat-sidebar.tsx
@@ -26,13 +26,22 @@
* │ │ │ 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.
+ * Pin / archive persist to the conversation's JSON file on disk so the state
+ * survives app restart. Delete removes the file.
*/
import React, { useEffect, useMemo, useState } from "react";
-import { Pin, X, AlertCircle, ChevronDown, ChevronRight, MessageSquare } from "lucide-react";
+import {
+ Pin,
+ Archive,
+ Undo2,
+ Trash2,
+ AlertCircle,
+ ChevronDown,
+ ChevronRight,
+ MessageSquare,
+ X,
+} from "lucide-react";
import { useRunningPipes } from "@/lib/hooks/use-running-pipes";
import { useUpcomingPipes, type UpcomingPipe } from "@/lib/hooks/use-upcoming-pipes";
import { localFetch } from "@/lib/api";
@@ -49,12 +58,21 @@ import {
useOrderedSessions,
type SessionRecord,
} from "@/lib/stores/chat-store";
-import { updateConversationFlags } from "@/lib/chat-storage";
+import { deleteConversationFile, updateConversationFlags } from "@/lib/chat-storage";
import { pipeSessionId } from "@/lib/events/types";
import { commands } from "@/lib/utils/tauri";
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+} from "@/components/ui/dialog";
+import { Button } from "@/components/ui/button";
import { normalizeQueueEventPayload } from "@/lib/chat-queue-controls";
import { Skeleton } from "@/components/ui/skeleton";
@@ -62,9 +80,31 @@ interface ChatSidebarProps {
className?: string;
}
+function readCollapsedPref(key: string): boolean {
+ try {
+ return localStorage.getItem(key) === "true";
+ } catch {
+ return false;
+ }
+}
+
+function useCollapsedPref(key: string) {
+ const [collapsed, setCollapsedRaw] = useState<boolean>(() => readCollapsedPref(key));
+ const setCollapsed = (v: boolean) => {
+ setCollapsedRaw(v);
+ try {
+ localStorage.setItem(key, String(v));
+ } catch {
+ // ignore
+ }
+ };
+ return [collapsed, setCollapsed] as const;
+}
+
function useVisibleChatSections(): {
pinned: SessionRecord[];
recents: SessionRecord[];
+ archived: SessionRecord[];
} {
const sessions = useOrderedSessions();
const runningPipes = useRunningPipes();
@@ -80,13 +120,18 @@ function useVisibleChatSections(): {
return useMemo(() => {
const pinned: SessionRecord[] = [];
const recents: SessionRecord[] = [];
+ const archived: SessionRecord[] = [];
for (const s of sessions) {
const isPipeKind = s.kind === "pipe-watch" || s.kind === "pipe-run";
if (isPipeKind && liveScheduledSids.has(s.id)) continue;
if (s.draft) continue;
+ if (s.hidden) {
+ archived.push(s);
+ continue;
+ }
(s.pinned ? pinned : recents).push(s);
}
- return { pinned, recents };
+ return { pinned, recents, archived };
}, [sessions, liveScheduledSids]);
}
@@ -141,6 +186,16 @@ export function ChatSidebar({ className }: ChatSidebarProps) {
const diskHydrated = useChatStore((s) => s.diskHydrated);
const actions = useChatActions();
const queueDepths = useQueueDepths();
+ const [isPinnedScrolling, setIsPinnedScrolling] = useState(false);
+ const [isRecentsScrolling, setIsRecentsScrolling] = useState(false);
+ const [isArchivedScrolling, setIsArchivedScrolling] = useState(false);
+ const [isScheduledScrolling, setIsScheduledScrolling] = useState(false);
+ const scrollStopTimersRef = React.useRef<Record<string, ReturnType<typeof setTimeout> | null>>({
+ pinned: null,
+ recents: null,
+ archived: null,
+ scheduled: null,
+ });
// Sync currentId from standalone-chat. Whenever the chat panel switches
// its piSessionIdRef (new chat, prefill auto-send, history click in the
@@ -188,7 +243,31 @@ export function ChatSidebar({ className }: ChatSidebarProps) {
void refetchUpcoming();
};
- const { pinned, recents } = useVisibleChatSections();
+ const { pinned, recents, archived } = useVisibleChatSections();
+ const [deletingSessionId, setDeletingSessionId] = useState<string | null>(null);
+
+ const hasScheduledSlice = upcomingPipes.length > 0 || runningPipes.length > 0;
+ const [pinnedCollapsed, setPinnedCollapsed] = useCollapsedPref("screenpipe:pinned-collapsed");
+ const [recentsCollapsed, setRecentsCollapsed] = useCollapsedPref("screenpipe:recents-collapsed");
+ const [archivedCollapsed, setArchivedCollapsed] = useCollapsedPref("screenpipe:closed-collapsed");
+ const [scheduledCollapsed, setScheduledCollapsed] = useCollapsedPref("screenpipe:scheduled-collapsed");
+ const [upcomingCollapsed, setUpcomingCollapsed] = useCollapsedPref("screenpipe:upcoming-collapsed");
+
+ const openAllCollapsed = recentsCollapsed && (archived.length === 0 || archivedCollapsed);
+
+ const setScrolling = (key: "pinned" | "recents" | "archived" | "scheduled", v: boolean) => {
+ if (key === "pinned") setIsPinnedScrolling(v);
+ if (key === "recents") setIsRecentsScrolling(v);
+ if (key === "archived") setIsArchivedScrolling(v);
+ if (key === "scheduled") setIsScheduledScrolling(v);
+ };
+
+ const handleSliceScroll = (key: "pinned" | "recents" | "archived" | "scheduled") => {
+ setScrolling(key, true);
+ const t = scrollStopTimersRef.current[key];
+ if (t) clearTimeout(t);
+ scrollStopTimersRef.current[key] = setTimeout(() => setScrolling(key, false), 120);
+ };
const recentsLoading = !diskHydrated && recents.length === 0;
const handleSelect = (id: string) => {
@@ -204,16 +283,16 @@ export function ChatSidebar({ className }: ChatSidebarProps) {
emit("chat-load-conversation", { conversationId: id });
};
- const handleClose = async (e: React.MouseEvent, id: string) => {
+ const handleArchive = async (e: React.MouseEvent, id: string) => {
e.stopPropagation();
- // Abort the Pi process first. Otherwise a still-streaming Pi keeps
- // emitting events for `id`, and pi-event-router's lazy-create branch
- // resurrects the row in the sidebar a beat after the user closed it.
+ // Stop any active session first to avoid immediate row resurrection
+ // from trailing stream events.
commands.piAbort(id).catch(() => {});
- actions.drop(id);
- // 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.
+ actions.patch(id, { hidden: true, unread: false });
+ // Archiving should tuck chats away immediately; users can reopen
+ // the bucket manually when they want to review archived items.
+ setArchivedCollapsed(true);
+ // Move the panel off a chat that just left the visible list.
if (id === currentId) {
const fresh = crypto.randomUUID();
actions.upsert({
@@ -231,16 +310,62 @@ export function ChatSidebar({ className }: ChatSidebarProps) {
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.
+ // Best-effort persistence for restart durability.
try {
await updateConversationFlags(id, { hidden: true });
} catch {
- // intentional — see comment above
+ // ignore
+ }
+ try {
+ await emit("chat-visibility-changed", { id, hidden: true });
+ } catch {
+ // ignore
+ }
+ };
+
+ const handleUnarchive = async (e: React.MouseEvent, id: string) => {
+ e.stopPropagation();
+ actions.patch(id, { hidden: false, unread: false });
+ try {
+ await updateConversationFlags(id, { hidden: false });
+ } catch {
+ // ignore
+ }
+ try {
+ await emit("chat-visibility-changed", { id, hidden: false });
+ } catch {
+ // ignore
+ }
+ };
+
+ const handleDeleteConfirmed = async (id: string) => {
+ actions.drop(id);
+ try {
+ await deleteConversationFile(id);
+ } catch {
+ // ignore
+ }
+ try {
+ await emit("chat-deleted", { id });
+ } catch {
+ // ignore
+ }
+ if (id === currentId) {
+ const fresh = crypto.randomUUID();
+ actions.upsert({
+ id: fresh,
+ title: "new chat",
+ preview: "",
+ status: "idle",
+ messageCount: 0,
+ createdAt: Date.now(),
+ updatedAt: Date.now(),
+ pinned: false,
+ unread: false,
+ draft: true,
+ });
+ actions.setCurrent(fresh);
+ emit("chat-load-conversation", { conversationId: fresh });
}
};
@@ -257,73 +382,215 @@ export function ChatSidebar({ className }: ChatSidebarProps) {
}
};
- // Layout contract:
- // - Scheduled (pipe runs): only renders when something's running;
- // own collapsible scroll viewport capped at ~25% so it never
- // squeezes recents off-screen.
- // - Pinned (chats): non-scrolling. Few rows in practice.
- // - Recents: fixed collapsible header; rows fill the rest and
- // scroll. flex-1 + min-h-0 is what makes the inner overflow-y-auto
- // actually work without leaking past the sidebar bottom.
- // Collapse state for both Scheduled and Recents persists in
- // localStorage — "I closed it, leave it closed" across reloads.
return (
// px-2 cancels the parent wrapper's -mx-2 (used to make the
// border-t span the full sidebar width). Without this the chat
// rows + section headers sit 8px left of the main nav items
// (Timeline / Memories / ...) and look misaligned.
<div
- className={cn("flex flex-col min-h-0 text-sm px-2", className)}
+ className={cn("flex flex-col min-h-full text-sm px-2", className)}
data-testid="chat-sidebar"
>
- {upcomingPipes.length > 0 && (
- <CollapsibleUpcoming
- pipes={upcomingPipes}
- onCancel={handleCancelUpcoming}
- />
- )}
+ <div className="flex-1 min-h-0 flex flex-col gap-1">
+ {hasScheduledSlice && (
+ <div
+ className={cn(
+ "min-h-0 flex flex-col shrink-0",
+ (scheduledCollapsed && upcomingCollapsed) ? "" : "max-h-[35%]"
+ )}
+ >
+ {upcomingPipes.length > 0 && (
+ <div
+ className={cn(
+ "min-h-0 flex flex-col shrink-0",
+ upcomingCollapsed ? "" : "flex-1"
+ )}
+ >
+ <Section
+ title="upcoming"
+ count={upcomingPipes.length}
+ collapsed={upcomingCollapsed}
+ onCollapsedChange={setUpcomingCollapsed}
+ bodyClassName="flex-1 min-h-0 overflow-y-auto overflow-x-hidden scrollbar-hide"
+ onBodyScroll={() => handleSliceScroll("scheduled")}
+ >
+ {upcomingPipes.map((p) => (
+ <UpcomingRow key={p.pipeName} pipe={p} onCancel={handleCancelUpcoming} />
+ ))}
+ </Section>
+ </div>
+ )}
+ {runningPipes.length > 0 && (
+ <div
+ className={cn(
+ "min-h-0 flex flex-col shrink-0",
+ scheduledCollapsed ? "" : "flex-1"
+ )}
+ >
+ <Section
+ title="scheduled"
+ count={runningPipes.length}
+ collapsed={scheduledCollapsed}
+ onCollapsedChange={setScheduledCollapsed}
+ bodyClassName="flex-1 min-h-0 overflow-y-auto overflow-x-hidden scrollbar-hide"
+ onBodyScroll={() => handleSliceScroll("scheduled")}
+ >
+ {runningPipes.map((p) => (
+ <ScheduledRow key={p.pipeName} pipe={p} />
+ ))}
+ </Section>
+ </div>
+ )}
+ </div>
+ )}
- {runningPipes.length > 0 && (
- <CollapsibleScheduled pipes={runningPipes} />
- )}
+ <div className="min-h-0 flex flex-col flex-1">
+ {pinned.length > 0 && (
+ <div
+ className={cn(
+ "min-h-0 flex flex-col shrink-0",
+ pinnedCollapsed ? "" : "max-h-[40%]"
+ )}
+ >
+ <Section
+ title="pinned"
+ count={pinned.length}
+ collapsed={pinnedCollapsed}
+ onCollapsedChange={setPinnedCollapsed}
+ bodyClassName="flex-1 min-h-0 overflow-y-auto overflow-x-hidden scrollbar-hide"
+ onBodyScroll={() => handleSliceScroll("pinned")}
+ >
+ {pinned.map((s) => (
+ <SidebarChatRow
+ key={s.id}
+ session={s}
+ isCurrent={s.id === currentId}
+ disableHover={isPinnedScrolling}
+ queuedCount={queueDepths.get(s.id) ?? 0}
+ onSelect={handleSelect}
+ onArchive={handleArchive}
+ onUnarchive={handleUnarchive}
+ onDeleteRequest={setDeletingSessionId}
+ onTogglePin={handleTogglePin}
+ />
+ ))}
+ </Section>
+ </div>
+ )}
- {pinned.length > 0 && (
- <ChatSection title="pinned">
- {pinned.map((s) => (
- <SidebarChatRow
- key={s.id}
- session={s}
- isCurrent={s.id === currentId}
- queuedCount={queueDepths.get(s.id) ?? 0}
- onSelect={handleSelect}
- onClose={handleClose}
- onTogglePin={handleTogglePin}
- />
- ))}
- </ChatSection>
- )}
+ <div className="min-h-0 flex flex-col">
+ <div className="min-h-0 flex flex-col">
+ <div
+ className={cn(
+ "min-h-0 flex flex-col",
+ archived.length > 0 && !archivedCollapsed ? "max-h-[75%]" : "flex-1",
+ recentsCollapsed ? "shrink-0" : ""
+ )}
+ >
+ <Section
+ title="recents"
+ collapsed={recentsCollapsed}
+ onCollapsedChange={setRecentsCollapsed}
+ bodyClassName="overflow-y-auto overflow-x-hidden scrollbar-hide"
+ onBodyScroll={() => handleSliceScroll("recents")}
+ >
+ {recentsLoading ? (
+ <div className="px-2.5 py-2 space-y-1.5">
+ {Array.from({ length: 3 }).map((_, i) => (
+ <Skeleton key={i} className="h-6 w-full rounded-md" />
+ ))}
+ </div>
+ ) : recents.length === 0 ? (
+ <div className="px-2.5 py-2 text-xs text-muted-foreground/70 italic">
+ {pinned.length === 0 ? "no chats yet — click + to start" : "no recent chats"}
+ </div>
+ ) : (
+ recents.map((s) => (
+ <SidebarChatRow
+ key={s.id}
+ session={s}
+ isCurrent={s.id === currentId}
+ disableHover={isRecentsScrolling}
+ queuedCount={queueDepths.get(s.id) ?? 0}
+ onSelect={handleSelect}
+ onArchive={handleArchive}
+ onUnarchive={handleUnarchive}
+ onDeleteRequest={setDeletingSessionId}
+ onTogglePin={handleTogglePin}
+ />
+ ))
+ )}
+ </Section>
+ </div>
- <CollapsibleRecents
- empty={recents.length === 0}
- loading={recentsLoading}
- emptyText={
- pinned.length === 0
- ? "no chats yet — click + to start"
- : "no recent chats"
- }
+ {archived.length > 0 && (
+ <div
+ className={cn(
+ "min-h-0 flex flex-col",
+ !archivedCollapsed ? "flex-1" : ""
+ )}
+ >
+ <Section
+ title="archived"
+ count={archived.length}
+ tone="subtle"
+ collapsed={archivedCollapsed}
+ onCollapsedChange={setArchivedCollapsed}
+ bodyClassName="overflow-y-auto overflow-x-hidden scrollbar-hide"
+ onBodyScroll={() => handleSliceScroll("archived")}
+ >
+ {archived.map((s) => (
+ <SidebarChatRow
+ key={s.id}
+ session={s}
+ isCurrent={s.id === currentId}
+ disableHover={isArchivedScrolling}
+ tone="subtle"
+ queuedCount={0}
+ onSelect={handleSelect}
+ onArchive={handleArchive}
+ onUnarchive={handleUnarchive}
+ onDeleteRequest={setDeletingSessionId}
+ onTogglePin={handleTogglePin}
+ />
+ ))}
+ </Section>
+ </div>
+ )}
+ </div>
+ </div>
+ </div>
+ </div>
+
+ <Dialog
+ open={!!deletingSessionId}
+ onOpenChange={(open) => {
+ if (!open) setDeletingSessionId(null);
+ }}
>
- {recents.map((s) => (
- <SidebarChatRow
- key={s.id}
- session={s}
- isCurrent={s.id === currentId}
- queuedCount={queueDepths.get(s.id) ?? 0}
- onSelect={handleSelect}
- onClose={handleClose}
- onTogglePin={handleTogglePin}
- />
- ))}
- </CollapsibleRecents>
+ <DialogContent className="sm:max-w-sm">
+ <DialogHeader>
+ <DialogTitle>Delete chat</DialogTitle>
+ <DialogDescription>Delete this chat? This cannot be undone.</DialogDescription>
+ </DialogHeader>
+ <DialogFooter>
+ <Button variant="outline" onClick={() => setDeletingSessionId(null)}>
+ Cancel
+ </Button>
+ <Button
+ variant="destructive"
+ onClick={async () => {
+ const id = deletingSessionId;
+ setDeletingSessionId(null);
+ if (!id) return;
+ await handleDeleteConfirmed(id);
+ }}
+ >
+ Delete
+ </Button>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
</div>
);
}
@@ -336,26 +603,32 @@ export function CollapsedChatSidebarButton({
isTranslucent: boolean;
}) {
const currentId = useChatStore((s) => s.currentId);
+ const { pinned, recents, archived } = useVisibleChatSections();
const diskHydrated = useChatStore((s) => s.diskHydrated);
- const { pinned, recents } = useVisibleChatSections();
const [open, setOpen] = useState(false);
const [tooltipOpen, setTooltipOpen] = useState(false);
const [suppressTooltip, setSuppressTooltip] = useState(false);
- const [activeTab, setActiveTab] = useState<"recents" | "pinned">("recents");
- const visiblePinned = pinned;
- const visibleRecents = recents;
- const emptyText = visiblePinned.length === 0
+ const [tab, setTab] = useState<"pinned" | "recents" | "archived">(() => {
+ if (pinned.length > 0) return "pinned";
+ if (recents.length > 0) return "recents";
+ return "archived";
+ });
+ const emptyText = pinned.length === 0
? "no chats yet — click + to start"
: "no recent chats";
- const recentsTabLoading = !diskHydrated && visibleRecents.length === 0;
+ const recentsTabLoading = !diskHydrated && recents.length === 0;
const isLoadingChats =
- !diskHydrated && visiblePinned.length === 0 && visibleRecents.length === 0;
+ !diskHydrated && pinned.length === 0 && recents.length === 0;
useEffect(() => {
- if (visiblePinned.length === 0 && activeTab === "pinned") {
- setActiveTab("recents");
+ if (tab === "pinned" && pinned.length === 0) {
+ setTab(recents.length > 0 ? "recents" : "archived");
+ } else if (tab === "recents" && recents.length === 0) {
+ setTab(pinned.length > 0 ? "pinned" : "archived");
+ } else if (tab === "archived" && archived.length === 0) {
+ setTab(pinned.length > 0 ? "pinned" : "recents");
}
- }, [visiblePinned.length, activeTab]);
+ }, [archived.length, pinned.length, recents.length, tab]);
const handleSelect = (id: string) => {
setOpen(false);
@@ -420,85 +693,63 @@ export function CollapsedChatSidebarButton({
<div className="py-1" aria-busy="true" data-testid="collapsed-chat-sidebar-skeleton">
<ChatRowsSkeleton rows={4} />
</div>
- ) : visiblePinned.length === 0 && visibleRecents.length === 0 ? (
+ ) : pinned.length === 0 && recents.length === 0 && archived.length === 0 ? (
<div className="px-2.5 py-2 text-xs text-muted-foreground/70 italic">
{emptyText}
</div>
) : (
<Tabs
- value={activeTab}
- onValueChange={(value) => setActiveTab(value as "recents" | "pinned")}
+ value={tab}
+ onValueChange={(v) => setTab(v as typeof tab)}
className="w-full"
>
- <TabsList
- className={cn(
- "grid w-full h-8 rounded-none bg-transparent border-b border-border p-0",
- visiblePinned.length > 0 ? "grid-cols-2" : "grid-cols-1"
- )}
- >
+ <TabsList className="grid w-full grid-cols-3 h-8 rounded-none bg-transparent border-b border-border p-0">
+ <TabsTrigger
+ value="pinned"
+ disabled={pinned.length === 0}
+ className="relative h-8 rounded-none bg-transparent px-2 text-[10px] uppercase tracking-wider shadow-none data-[state=active]:bg-transparent data-[state=active]:shadow-none data-[state=active]:after:absolute data-[state=active]:after:left-0 data-[state=active]:after:right-0 data-[state=active]:after:bottom-0 data-[state=active]:after:h-0.5 data-[state=active]:after:bg-foreground"
+ >
+ Pinned
+ </TabsTrigger>
<TabsTrigger
value="recents"
- className="rounded-none border-b-2 border-transparent data-[state=active]:border-foreground data-[state=active]:bg-transparent data-[state=active]:shadow-none text-[10px] uppercase tracking-wider px-3 h-8"
+ disabled={recents.length === 0}
+ className="relative h-8 rounded-none bg-transparent px-2 text-[10px] uppercase tracking-wider shadow-none data-[state=active]:bg-transparent data-[state=active]:shadow-none data-[state=active]:after:absolute data-[state=active]:after:left-0 data-[state=active]:after:right-0 data-[state=active]:after:bottom-0 data-[state=active]:after:h-0.5 data-[state=active]:after:bg-foreground"
>
- recents
+ Recents
+ </TabsTrigger>
+ <TabsTrigger
+ value="archived"
+ disabled={archived.length === 0}
+ className="relative h-8 rounded-none bg-transparent px-2 text-[10px] uppercase tracking-wider shadow-none data-[state=active]:bg-transparent data-[state=active]:shadow-none data-[state=active]:after:absolute data-[state=active]:after:left-0 data-[state=active]:after:right-0 data-[state=active]:after:bottom-0 data-[state=active]:after:h-0.5 data-[state=active]:after:bg-foreground"
+ >
+ Archived
</TabsTrigger>
- {visiblePinned.length > 0 && (
- <TabsTrigger
- value="pinned"
- className="rounded-none border-b-2 border-transparent data-[state=active]:border-foreground data-[state=active]:bg-transparent data-[state=active]:shadow-none text-[10px] uppercase tracking-wider px-3 h-8"
- >
- pinned
- </TabsTrigger>
- )}
</TabsList>
+
+ <TabsContent value="pinned" className="mt-0">
+ <CompactDrawerList
+ items={pinned}
+ currentId={currentId}
+ onSelect={handleSelect}
+ />
+ </TabsContent>
<TabsContent value="recents" className="mt-0">
{recentsTabLoading ? (
<div className="py-1" aria-busy="true">
<ChatRowsSkeleton rows={4} />
</div>
- ) : visibleRecents.length === 0 ? (
+ ) : recents.length === 0 ? (
<div className="px-2.5 py-2 text-xs text-muted-foreground/70 italic">
- {visiblePinned.length === 0 ? emptyText : "no recent chats"}
+ {pinned.length === 0 ? emptyText : "no recent chats"}
</div>
) : (
- <div className="max-h-52 overflow-y-auto overflow-x-hidden scrollbar-minimal">
- <div className="flex flex-col py-1">
- {visibleRecents.map((session) => (
- <SidebarChatRow
- key={session.id}
- session={session}
- isCurrent={session.id === currentId}
- queuedCount={0}
- onSelect={handleSelect}
- onClose={() => {}}
- onTogglePin={() => {}}
- showActions={false}
- />
- ))}
- </div>
- </div>
+ <CompactDrawerList items={recents} currentId={currentId} onSelect={handleSelect} />
)}
</TabsContent>
- {visiblePinned.length > 0 && (
- <TabsContent value="pinned" className="mt-0">
- <div className="max-h-52 overflow-y-auto overflow-x-hidden scrollbar-minimal">
- <div className="flex flex-col py-1">
- {visiblePinned.map((session) => (
- <SidebarChatRow
- key={session.id}
- session={session}
- isCurrent={session.id === currentId}
- queuedCount={0}
- onSelect={handleSelect}
- onClose={() => {}}
- onTogglePin={() => {}}
- showActions={false}
- />
- ))}
- </div>
- </div>
- </TabsContent>
- )}
+ <TabsContent value="archived" className="mt-0">
+ <CompactDrawerList items={archived} currentId={currentId} onSelect={handleSelect} />
+ </TabsContent>
</Tabs>
)}
</PopoverContent>
@@ -506,69 +757,33 @@ export function CollapsedChatSidebarButton({
);
}
-/** Recents container with a fixed (non-scrolling) header and a
- * scrollable body underneath. Click the header to collapse. */
-function CollapsibleRecents({
- empty,
- loading = false,
- emptyText,
- children,
+function CompactDrawerList({
+ items,
+ currentId,
+ onSelect,
}: {
- empty: boolean;
- loading?: boolean;
- emptyText: string;
- children: React.ReactNode;
+ items: SessionRecord[];
+ currentId: string | null;
+ onSelect: (id: string) => void;
}) {
- const [collapsed, setCollapsedRaw] = useState<boolean>(() => {
- try {
- return localStorage.getItem("screenpipe:recents-collapsed") === "true";
- } catch {
- return false;
- }
- });
- const setCollapsed = (v: boolean) => {
- setCollapsedRaw(v);
- try {
- localStorage.setItem("screenpipe:recents-collapsed", String(v));
- } catch {
- // ignore — collapse state is best-effort
- }
- };
return (
- <div className="flex flex-col flex-1 min-h-0 mb-2">
- <button
- type="button"
- onClick={() => setCollapsed(!collapsed)}
- className="shrink-0 px-2.5 py-1.5 flex items-center gap-1 hover:bg-muted/30 rounded-md text-left"
- aria-expanded={!collapsed}
- aria-controls="chat-sidebar-recents"
- >
- {collapsed ? (
- <ChevronRight className="h-3 w-3 text-muted-foreground/60 shrink-0" />
- ) : (
- <ChevronDown className="h-3 w-3 text-muted-foreground/60 shrink-0" />
- )}
- <span className="text-[10px] uppercase tracking-wider text-muted-foreground/60">
- recents
- </span>
- </button>
- {!collapsed && (
- <div
- id="chat-sidebar-recents"
- className="flex-1 min-h-0 overflow-y-auto overflow-x-hidden scrollbar-hide"
- aria-busy={loading}
- >
- {loading ? (
- <ChatRowsSkeleton rows={6} />
- ) : empty ? (
- <div className="px-2.5 py-2 text-xs text-muted-foreground/70 italic">
- {emptyText}
- </div>
- ) : (
- <div className="flex flex-col">{children}</div>
- )}
- </div>
- )}
+ <div className="max-h-72 overflow-y-auto overflow-x-hidden scrollbar-minimal">
+ <div className="flex flex-col py-1">
+ {items.map((session) => (
+ <SidebarChatRow
+ key={session.id}
+ session={session}
+ isCurrent={session.id === currentId}
+ queuedCount={0}
+ onSelect={onSelect}
+ onArchive={() => {}}
+ onUnarchive={() => {}}
+ onDeleteRequest={() => {}}
+ onTogglePin={() => {}}
+ showActions={false}
+ />
+ ))}
+ </div>
</div>
);
}
@@ -869,24 +1084,75 @@ function UpcomingRow({
);
}
-export function ChatSection({
+function Section({
title,
- action,
+ count,
+ tone = "default",
+ collapsed,
+ onCollapsedChange,
+ bodyClassName,
+ onBodyScroll,
children,
}: {
title: string;
- action?: React.ReactNode;
+ count?: number;
+ tone?: "default" | "subtle";
+ collapsed: boolean;
+ onCollapsedChange: (next: boolean) => void;
+ bodyClassName: string;
+ onBodyScroll?: () => void;
children: React.ReactNode;
}) {
return (
- <div className="mb-2">
- <div className="px-2.5 py-1.5 flex items-center justify-between">
- <span className="text-[10px] uppercase tracking-wider text-muted-foreground/60">
+ <div className="flex flex-col min-h-0">
+ <button
+ type="button"
+ onClick={() => onCollapsedChange(!collapsed)}
+ className={cn(
+ "shrink-0 px-2.5 py-1.5 flex items-center gap-1 rounded-md text-left",
+ tone === "subtle" ? "hover:bg-muted/20" : "hover:bg-muted/30"
+ )}
+ aria-expanded={!collapsed}
+ >
+ {collapsed ? (
+ <ChevronRight
+ className={cn(
+ "h-3 w-3 shrink-0",
+ tone === "subtle" ? "text-muted-foreground/45" : "text-muted-foreground/60"
+ )}
+ />
+ ) : (
+ <ChevronDown
+ className={cn(
+ "h-3 w-3 shrink-0",
+ tone === "subtle" ? "text-muted-foreground/45" : "text-muted-foreground/60"
+ )}
+ />
+ )}
+ <span
+ className={cn(
+ "text-[10px] uppercase tracking-wider flex-1",
+ tone === "subtle" ? "text-muted-foreground/45" : "text-muted-foreground/60"
+ )}
+ >
{title}
</span>
- {action}
- </div>
- <div className="flex flex-col">{children}</div>
+ {count !== undefined && (
+ <span
+ className={cn(
+ "text-[10px] tabular-nums",
+ tone === "subtle" ? "text-muted-foreground/40" : "text-muted-foreground/60"
+ )}
+ >
+ {count}
+ </span>
+ )}
+ </button>
+ {!collapsed && (
+ <div className={bodyClassName} onScroll={onBodyScroll}>
+ <div className="flex flex-col">{children}</div>
+ </div>
+ )}
</div>
);
}
@@ -894,12 +1160,14 @@ export function ChatSection({
interface ChatRowProps {
session: SessionRecord;
isCurrent: boolean;
- /** Number of follow-up prompts queued for this session at the rust level.
- * > 0 → render an unobtrusive `↑N` badge so the user can spot pending
- * work in chats they've navigated away from. */
+ disableHover?: boolean;
+ tone?: "default" | "subtle";
+ leadingIndicator?: React.ReactNode;
queuedCount: number;
onSelect: (id: string) => void;
- onClose: (e: React.MouseEvent, id: string) => Promise<void> | void;
+ onArchive: (e: React.MouseEvent, id: string) => Promise<void> | void;
+ onUnarchive: (e: React.MouseEvent, id: string) => Promise<void> | void;
+ onDeleteRequest: (id: string | null) => void;
onTogglePin: (e: React.MouseEvent, id: string) => Promise<void> | void;
showActions?: boolean;
}
@@ -926,9 +1194,14 @@ interface ChatRowProps {
export function SidebarChatRow({
session,
isCurrent,
+ disableHover = false,
+ tone = "default",
+ leadingIndicator,
queuedCount,
onSelect,
- onClose,
+ onArchive,
+ onUnarchive,
+ onDeleteRequest,
onTogglePin,
showActions = true,
}: ChatRowProps) {
@@ -938,6 +1211,7 @@ export function SidebarChatRow({
session.status === "tool";
const isError = session.status === "error";
const isUnread = session.unread && !isCurrent;
+ const canShowActions = showActions && !disableHover;
const activityAt = session.lastUserMessageAt ?? session.updatedAt ?? session.createdAt;
const now = useMinuteTick(!isLive && !isUnread && !isError && queuedCount === 0);
const age = formatCompactAge(activityAt, now);
@@ -957,13 +1231,25 @@ export function SidebarChatRow({
"transition-colors",
isCurrent
? "bg-muted/70 text-foreground"
- : "text-muted-foreground hover:bg-muted/40"
+ : disableHover
+ ? tone === "subtle"
+ ? "text-muted-foreground/75"
+ : "text-muted-foreground"
+ : tone === "subtle"
+ ? "text-muted-foreground/75 hover:bg-muted/25"
+ : "text-muted-foreground hover:bg-muted/40"
)}
data-testid={`chat-row-${session.id}`}
title={isError && session.lastError ? session.lastError : undefined}
>
<div className="flex items-center gap-2 min-w-0">
- <RowBullet />
+ {leadingIndicator ? (
+ <span className="h-3 w-3 shrink-0 flex items-center justify-center" aria-label="pinned">
+ {leadingIndicator}
+ </span>
+ ) : (
+ <RowBullet />
+ )}
<span
className={cn(
"truncate flex-1 text-xs",
@@ -971,60 +1257,129 @@ export function SidebarChatRow({
? "font-semibold text-foreground"
: isCurrent
? "text-foreground/80"
+ : tone === "subtle"
+ ? "text-muted-foreground/70"
: "text-muted-foreground"
)}
>
{session.title || "untitled"}
</span>
- <RowRightSignal
- isLive={isLive}
- isError={isError}
- isUnread={isUnread}
- queuedCount={queuedCount}
- status={session.status}
- age={age}
- hideOnHover={showActions}
- />
- {/* hover-only actions — REAL <button>s now (was <span role=button>
- inside the outer <button>, which is invalid nested-button HTML
- and made the X click silently no-op on close). */}
- <span
- className={cn(
- "shrink-0",
- showActions ? "hidden group-hover:inline-flex items-center gap-0.5" : "hidden"
- )}
- >
- <button
- type="button"
- onClick={(e) => {
- e.stopPropagation();
- void onTogglePin(e, session.id);
- }}
- className="p-0.5 rounded hover:bg-muted"
- title={session.pinned ? "unpin" : "pin"}
- aria-label={session.pinned ? "unpin" : "pin"}
+ <span className="ml-1 w-10 h-4 shrink-0 relative">
+ <span
+ className={cn(
+ "absolute inset-0 inline-flex items-center justify-end transition-opacity duration-100",
+ canShowActions ? "opacity-100 group-hover:opacity-0" : "opacity-100"
+ )}
>
- <Pin
- className={cn(
- "h-3 w-3",
- session.pinned
- ? "text-foreground fill-current"
- : "text-muted-foreground"
- )}
+ <RowRightSignal
+ isLive={isLive}
+ isError={isError}
+ isUnread={isUnread}
+ queuedCount={queuedCount}
+ status={session.status}
+ age={age}
/>
- </button>
- <button
- type="button"
- onClick={(e) => {
- e.stopPropagation();
- void onClose(e, session.id);
- }}
- className="p-0.5 rounded hover:bg-muted text-muted-foreground"
- title="close"
- aria-label="close"
+ </span>
+ {/* hover-only actions in a fixed slot to avoid row reflow flicker */}
+ <span
+ className={cn(
+ "absolute inset-0 inline-flex items-center justify-end gap-0.5 transition-opacity duration-100",
+ canShowActions
+ ? "opacity-0 pointer-events-none group-hover:opacity-100 group-hover:pointer-events-auto"
+ : "opacity-0 pointer-events-none"
+ )}
>
- <X className="h-3 w-3" />
- </button>
+ {!session.hidden ? (
+ <>
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <button
+ type="button"
+ onClick={(e) => {
+ e.stopPropagation();
+ void onTogglePin(e, session.id);
+ }}
+ className="p-0.5 rounded hover:bg-muted"
+ title={session.pinned ? "unpin" : "pin"}
+ aria-label={session.pinned ? "unpin" : "pin"}
+ >
+ <Pin
+ className={cn(
+ "h-3 w-3",
+ session.pinned
+ ? "text-foreground fill-current"
+ : "text-muted-foreground"
+ )}
+ />
+ </button>
+ </TooltipTrigger>
+ <TooltipContent side="top" className="text-xs">
+ {session.pinned ? "Unpin" : "Pin"}
+ </TooltipContent>
+ </Tooltip>
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <button
+ type="button"
+ onClick={(e) => {
+ e.stopPropagation();
+ void onArchive(e, session.id);
+ }}
+ className="p-0.5 rounded hover:bg-muted text-muted-foreground"
+ title="archive chat"
+ aria-label="archive chat"
+ >
+ <Archive className="h-3 w-3" />
+ </button>
+ </TooltipTrigger>
+ <TooltipContent side="top" className="text-xs">
+ Archive
+ </TooltipContent>
+ </Tooltip>
+ </>
+ ) : (
+ <>
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <button
+ type="button"
+ onClick={(e) => {
+ e.stopPropagation();
+ void onUnarchive(e, session.id);
+ }}
+ className="p-0.5 rounded hover:bg-muted text-muted-foreground"
+ title="unarchive"
+ aria-label="unarchive"
+ >
+ <Undo2 className="h-3 w-3" />
+ </button>
+ </TooltipTrigger>
+ <TooltipContent side="top" className="text-xs">
+ Unarchive
+ </TooltipContent>
+ </Tooltip>
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <button
+ type="button"
+ onClick={(e) => {
+ e.stopPropagation();
+ onDeleteRequest(session.id);
+ }}
+ className="p-0.5 rounded hover:bg-muted text-muted-foreground"
+ title="delete forever"
+ aria-label="delete forever"
+ >
+ <Trash2 className="h-3 w-3" />
+ </button>
+ </TooltipTrigger>
+ <TooltipContent side="top" className="text-xs">
+ Delete forever
+ </TooltipContent>
+ </Tooltip>
+ </>
+ )}
+ </span>
</span>
</div>
</div>
@@ -1049,7 +1404,6 @@ function RowRightSignal({
queuedCount,
status,
age,
- hideOnHover,
}: {
isLive: boolean;
isError: boolean;
@@ -1057,7 +1411,6 @@ function RowRightSignal({
queuedCount: number;
status: string;
age: string | null;
- hideOnHover: boolean;
}) {
const content = (() => {
if (isError) {
@@ -1094,16 +1447,7 @@ function RowRightSignal({
if (!content) return null;
- return (
- <span
- className={cn(
- "ml-1 min-w-5 shrink-0 inline-flex justify-end",
- hideOnHover && "group-hover:hidden"
- )}
- >
- {content}
- </span>
- );
+ return <span className="min-w-5 shrink-0 inline-flex justify-end">{content}</span>;
}
function LiveSignal({ ariaLabel = "loading" }: { ariaLabel?: string }) {
diff --git a/apps/screenpipe-app-tauri/components/hooks/use-chat-conversations.ts b/apps/screenpipe-app-tauri/components/hooks/use-chat-conversations.ts
index 4c33d513c..865bc278c 100644
--- a/apps/screenpipe-app-tauri/components/hooks/use-chat-conversations.ts
+++ b/apps/screenpipe-app-tauri/components/hooks/use-chat-conversations.ts
@@ -13,6 +13,7 @@ import {
type RefObject,
type MutableRefObject,
} from "react";
+import { emit, listen } from "@tauri-apps/api/event";
import { ChatConversation } from "@/lib/hooks/use-settings";
import { commands } from "@/lib/utils/tauri";
import {
@@ -122,6 +123,7 @@ export function useChatConversations(opts: UseChatConversationsOpts) {
const historyRequestRef = useRef(0);
const lastHistoryQueryRef = useRef<string | null>(null);
const [historyReady, setHistoryReady] = useState(false);
+ const historyRefreshTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
const loadConversationMetas = useCallback(async (query: string) => {
const options = {
limit: CHAT_HISTORY_INITIAL_LIMIT,
@@ -172,12 +174,90 @@ export function useChatConversations(opts: UseChatConversationsOpts) {
return () => clearTimeout(timer);
}, [historyReady, historySearch, loadConversationMetas]);
- const refreshFileConversations = async () => {
+ const refreshFileConversations = useCallback(async () => {
const q = historySearch.trim();
const convs = await loadConversationMetas(q);
setFileConversations(convs);
lastHistoryQueryRef.current = q;
- };
+ }, [historySearch, loadConversationMetas]);
+
+ const scheduleHistoryRefresh = useCallback((delayMs = 80) => {
+ if (historyRefreshTimerRef.current) {
+ clearTimeout(historyRefreshTimerRef.current);
+ }
+ historyRefreshTimerRef.current = setTimeout(() => {
+ historyRefreshTimerRef.current = null;
+ void refreshFileConversations().catch(() => {});
+ }, delayMs);
+ }, [refreshFileConversations]);
+
+ useEffect(() => {
+ return () => {
+ if (historyRefreshTimerRef.current) {
+ clearTimeout(historyRefreshTimerRef.current);
+ historyRefreshTimerRef.current = null;
+ }
+ };
+ }, []);
+
+ // Cross-window history sync. The overlay and home windows keep separate
+ // React states, so sidebar archive/delete actions in one window won't
+ // update the other's file-backed history list unless we listen for the
+ // broadcast events and refresh locally.
+ useEffect(() => {
+ let cancelled = false;
+ const unlistenFns: Array<() => void> = [];
+
+ (async () => {
+ const unlistenDeleted = await listen<{ id: string }>(
+ "chat-deleted",
+ (event) => {
+ if (cancelled) return;
+ const id = event.payload?.id;
+ if (!id) return;
+ setFileConversations((prev) => prev.filter((c) => c.id !== id));
+ if (conversationId === id) {
+ setMessages([]);
+ setConversationId(null);
+ }
+ scheduleHistoryRefresh();
+ },
+ );
+ unlistenFns.push(unlistenDeleted);
+
+ const unlistenVisibility = await listen<{ id: string; hidden: boolean }>(
+ "chat-visibility-changed",
+ (event) => {
+ if (cancelled) return;
+ const { id, hidden } = event.payload ?? {};
+ if (!id) return;
+ if (hidden) {
+ setFileConversations((prev) => prev.filter((c) => c.id !== id));
+ }
+ scheduleHistoryRefresh();
+ },
+ );
+ unlistenFns.push(unlistenVisibility);
+
+ const unlistenSaved = await listen<{ id: string; title?: string }>(
+ "chat-conversation-saved",
+ (event) => {
+ if (cancelled) return;
+ const { id } = event.payload ?? {};
+ if (!id) return;
+ scheduleHistoryRefresh();
+ },
+ );
+ unlistenFns.push(unlistenSaved);
+ })().catch(() => {
+ // ignore: chat still works without cross-window sync listeners
+ });
+
+ return () => {
+ cancelled = true;
+ for (const unlisten of unlistenFns) unlisten();
+ };
+ }, [conversationId, scheduleHistoryRefresh, setConversationId, setMessages]);
const upsertFileConversationMeta = (conversation: ChatConversation) => {
if (historySearch.trim()) return;
@@ -280,6 +360,7 @@ export function useChatConversations(opts: UseChatConversationsOpts) {
role: m.role,
content,
timestamp: m.timestamp,
+ ...(m.displayContent ? { displayContent: m.displayContent } : {}),
...(blocks?.length ? { contentBlocks: blocks } : {}),
...(m.images?.length ? { images: m.images } : {}),
...(m.model ? { model: m.model } : {}),
@@ -327,6 +408,14 @@ export function useChatConversations(opts: UseChatConversationsOpts) {
} else {
upsertFileConversationMeta(conversation);
}
+ try {
+ await emit("chat-conversation-saved", {
+ id: conversation.id,
+ title: conversation.title,
+ });
+ } catch {
+ // ignore broadcast failures; local save already succeeded
+ }
// Sync the persisted title back into the in-memory chat-store so the
// sidebar (which reads `sessions[id].title` directly) updates immediately.
@@ -488,7 +577,6 @@ export function useChatConversations(opts: UseChatConversationsOpts) {
// vice versa) until the next on-disk hydration. Listeners in
// standalone-chat.tsx patch their local store on receipt.
try {
- const { emit } = await import("@tauri-apps/api/event");
await emit("chat-renamed", { id: convId, title: trimmed });
} catch (e) {
console.warn("[chat] failed to broadcast rename:", e);
@@ -521,6 +609,13 @@ export function useChatConversations(opts: UseChatConversationsOpts) {
} catch (e) {
console.warn("[chat] failed to clear activeConversationId:", e);
}
+
+ // Broadcast so other windows (home sidebar / overlay) update immediately.
+ try {
+ await emit("chat-deleted", { id: convId });
+ } catch (e) {
+ console.warn("[chat] failed to broadcast delete:", e);
+ }
};
// ---- loadConversation ----
@@ -646,6 +741,7 @@ export function useChatConversations(opts: UseChatConversationsOpts) {
role: m.role,
content: m.content,
timestamp: m.timestamp,
+ ...(m.displayContent ? { displayContent: m.displayContent } : {}),
...(m.contentBlocks?.length ? { contentBlocks: m.contentBlocks } : {}),
...((m as any).images?.length
? { images: (m as any).images }
diff --git a/apps/screenpipe-app-tauri/components/standalone-chat.tsx b/apps/screenpipe-app-tauri/components/standalone-chat.tsx
index bda7ff450..791677788 100644
--- a/apps/screenpipe-app-tauri/components/standalone-chat.tsx
+++ b/apps/screenpipe-app-tauri/components/standalone-chat.tsx
@@ -1637,6 +1637,7 @@ function ChatTitleMenu({
}) {
const [open, setOpen] = useState(false);
const [renaming, setRenaming] = useState(false);
+ const [confirmingDelete, setConfirmingDelete] = useState(false);
const [draft, setDraft] = useState("");
const inputRef = useRef<HTMLInputElement | null>(null);
@@ -1700,7 +1701,10 @@ function ChatTitleMenu({
};
const handleDelete = async () => {
setOpen(false);
- if (!confirm("Delete this chat? This cannot be undone.")) return;
+ setConfirmingDelete(true);
+ };
+ const confirmDelete = async () => {
+ setConfirmingDelete(false);
try {
await deleteConversation(conversationId);
useChatStore.getState().actions.drop(conversationId);
@@ -1780,6 +1784,24 @@ function ChatTitleMenu({
Delete
</button>
</PopoverContent>
+ <Dialog open={confirmingDelete} onOpenChange={setConfirmingDelete}>
+ <DialogContent className="sm:max-w-sm">
+ <DialogHeader>
+ <DialogTitle>delete chat</DialogTitle>
+ <p className="text-sm text-muted-foreground">
+ Delete this chat? This cannot be undone.
+ </p>
+ </DialogHeader>
+ <DialogFooter>
+ <Button variant="outline" onClick={() => setConfirmingDelete(false)}>
+ Cancel
+ </Button>
+ <Button variant="destructive" onClick={() => void confirmDelete()}>
+ Delete
+ </Button>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
</Popover>
);
}
@@ -2012,6 +2034,8 @@ export function StandaloneChat({
const piLastErrorRef = useRef<string | null>(null);
const piStartInFlightRef = useRef(false);
const piFirstCallRetried = useRef(false);
+ const sessionActivityLastEmitAtRef = useRef<Record<string, number>>({});
+ const sessionActivityLastSigRef = useRef<Record<string, string>>({});
const piStoppedIntentionallyRef = useRef(false);
const piIntentionallyStoppedPidsRef = useRef<Set<number>>(new Set());
const piPresetSwitchPromiseRef = useRef<Promise<void> | null>(null);
@@ -3469,6 +3493,47 @@ export function StandaloneChat({
};
const handlePiEventData = (data: any) => {
+ const emitSessionActivity = (
+ partial: {
+ status?: ReturnType<typeof statusForEvent>;
+ preview?: string;
+ title?: string;
+ lastError?: string;
+ unreadHint?: boolean;
+ },
+ opts?: { throttleMs?: number },
+ ) => {
+ try {
+ const sid = piSessionIdRef.current;
+ if (!sid) return;
+ const status = partial.status ?? null;
+ const preview = partial.preview?.replace(/\s+/g, " ").trim();
+ const title = partial.title?.trim();
+ const lastError = partial.lastError;
+ const unreadHint = partial.unreadHint === true;
+ const updatedAt = Date.now();
+ const sig = `${status ?? ""}|${preview ?? ""}|${title ?? ""}|${lastError ?? ""}|${unreadHint ? "1" : "0"}`;
+ const lastSig = sessionActivityLastSigRef.current[sid];
+ const throttleMs = opts?.throttleMs ?? 0;
+ const lastAt = sessionActivityLastEmitAtRef.current[sid] ?? 0;
+ if (sig === lastSig && throttleMs > 0 && updatedAt - lastAt < throttleMs) return;
+ if (sig === lastSig && throttleMs === 0) return;
+ if (throttleMs > 0 && updatedAt - lastAt < throttleMs && !status && !lastError) return;
+ sessionActivityLastSigRef.current[sid] = sig;
+ sessionActivityLastEmitAtRef.current[sid] = updatedAt;
+ void emit("chat-session-activity", {
+ id: sid,
+ status: status ?? undefined,
+ preview: preview || undefined,
+ title: title || undefined,
+ updatedAt,
+ lastError,
+ unreadHint,
+ });
+ } catch {
+ // best effort only
+ }
+ };
// Mirror status into the chat-store so the sidebar dot reflects what
// Pi is actually doing. The bus routes foreground events exclusively
@@ -3487,6 +3552,11 @@ export function StandaloneChat({
if (cur !== next) {
store.actions.patch(sid, { status: next });
}
+ emitSessionActivity({
+ status: next,
+ title: useChatStore.getState().sessions[sid]?.title,
+ lastError: next === "error" ? (piLastErrorRef.current ?? undefined) : undefined,
+ });
}
} catch {
/* defensive — never let a status-mirror failure break the
@@ -3516,6 +3586,11 @@ export function StandaloneChat({
// First delta of a queued turn → create the placeholder lazily.
if (!ensureAssistantPlaceholder()) return;
piStreamingTextRef.current += evt.delta;
+ emitSessionActivity({
+ status: "streaming",
+ preview: evt.delta,
+ unreadHint: true,
+ }, { throttleMs: 250 });
// Append to last text block or create new one
const blocks = piContentBlocksRef.current;
@@ -3620,6 +3695,7 @@ export function StandaloneChat({
const errorStr = data.finalError || "Request failed after retries";
console.error("[Pi] Auto-retry failed:", errorStr);
piLastErrorRef.current = errorStr;
+ emitSessionActivity({ status: "error", lastError: errorStr });
// Detect rate limit or daily limit from the error
const quotaErrorType = classifyQuotaError(errorStr);
@@ -3651,6 +3727,7 @@ export function StandaloneChat({
const reason = data.assistantMessageEvent.reason || "";
const errorDetail = data.assistantMessageEvent.error || "";
console.error("[Pi] Message error:", reason, errorDetail);
+ emitSessionActivity({ status: "error", lastError: `${reason} ${errorDetail}`.trim() || undefined });
if (piMessageIdRef.current) {
const msgId = piMessageIdRef.current;
@@ -3749,6 +3826,7 @@ export function StandaloneChat({
const errMsg = data.message.errorMessage || data.message.error || "Unknown error";
console.error("[Pi] LLM error via", data.type, ":", errMsg);
piLastErrorRef.current = errMsg;
+ emitSessionActivity({ status: "error", lastError: errMsg });
if (piMessageIdRef.current) {
const msgId = piMessageIdRef.current;
@@ -3906,9 +3984,11 @@ export function StandaloneChat({
followUpFiredRef.current = false;
setIsLoading(false);
setIsStreaming(false);
+ emitSessionActivity({ status: "idle" });
}
} else if (data.type === "response" && data.success === false) {
const errorStr = data.error || "Unknown error";
+ emitSessionActivity({ status: "error", lastError: errorStr });
// Pi agent first-call bug (pi-mono#2461) — first RPC prompt crashes.
// Auto-retry the same prompt once. The second call works.
if (errorStr.includes("startsWith") || errorStr.includes("text.startsWith")) {
diff --git a/apps/screenpipe-app-tauri/lib/stores/chat-store.ts b/apps/screenpipe-app-tauri/lib/stores/chat-store.ts
index 6b2fe8300..c5538ba8f 100644
--- a/apps/screenpipe-app-tauri/lib/stores/chat-store.ts
+++ b/apps/screenpipe-app-tauri/lib/stores/chat-store.ts
@@ -70,6 +70,8 @@ export interface SessionRecord {
lastUserMessageAt?: number;
/** User pinned this conversation to the top of the sidebar. */
pinned: boolean;
+ /** Archived conversation hidden from recents. */
+ hidden?: boolean;
/** True when there's new assistant activity (delta or completion) that
* the user hasn't seen yet. Set by the event router when content lands
* for a session that is NOT the currently-viewed one; cleared the
@@ -259,6 +261,7 @@ export const useChatStore = create<ChatStore>((set) => ({
preview: r.preview,
messageCount: r.messageCount,
pinned: existing.pinned || r.pinned,
+ hidden: existing.hidden ?? r.hidden ?? false,
// updatedAt: take the larger so memory doesn't get clobbered
updatedAt: Math.max(existing.updatedAt, r.updatedAt),
}