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): keep Recents stable when the Pi pool evicts a session (#6741)
Louis Beaumont3d10440e5ad2
diff --git a/apps/screenpipe-app-tauri/components/chat/standalone/hooks/use-chat-session-runtime.test.tsx b/apps/screenpipe-app-tauri/components/chat/standalone/hooks/use-chat-session-runtime.test.tsxindex d56e42f5d..909370f8a 100644--- a/apps/screenpipe-app-tauri/components/chat/standalone/hooks/use-chat-session-runtime.test.tsx+++ b/apps/screenpipe-app-tauri/components/chat/standalone/hooks/use-chat-session-runtime.test.tsx@@ -60,7 +60,6 @@ function useRuntimeHarness() {const isStreamingRef = useRef(false);const messagesRef = useRef([]);const handleAgentEventDataRef = useRef<((data: unknown) => void) | null>(null);- const startNewConversationRef = useRef<(() => Promise<void>) | null>(null);const forceQueueModeRef = useRef(false);const sendDispatchInFlightRef = useRef(false);@@ -79,7 +78,6 @@ function useRuntimeHarness() {isStreamingRef,messagesRef,handleAgentEventDataRef,- startNewConversationRef,forceQueueModeRef,sendDispatchInFlightRef,});diff --git a/apps/screenpipe-app-tauri/components/chat/standalone/hooks/use-chat-session-runtime.ts b/apps/screenpipe-app-tauri/components/chat/standalone/hooks/use-chat-session-runtime.tsindex 4ba92526c..beab7e39c 100644--- a/apps/screenpipe-app-tauri/components/chat/standalone/hooks/use-chat-session-runtime.ts+++ b/apps/screenpipe-app-tauri/components/chat/standalone/hooks/use-chat-session-runtime.ts@@ -4,10 +4,8 @@import { useEffect, useRef } from "react";import type * as React from "react";-import { emit } from "@tauri-apps/api/event";import {mountAgentEventBus,- onEvicted as onAgentEvicted,registerForeground,} from "@/lib/events/bus";import { useChatPipeWatch } from "@/components/chat/standalone/hooks/use-chat-pipe-watch";@@ -32,7 +30,6 @@ interface UseChatSessionRuntimeOptions {isStreamingRef: React.MutableRefObject<boolean>;messagesRef: React.MutableRefObject<Message[]>;handleAgentEventDataRef: React.MutableRefObject<((data: any) => void) | null>;- startNewConversationRef: React.MutableRefObject<(() => Promise<void>) | null>;forceQueueModeRef: React.MutableRefObject<boolean>;sendDispatchInFlightRef: React.MutableRefObject<boolean>;}@@ -81,7 +78,6 @@ export function useChatSessionRuntime({isStreamingRef,messagesRef,handleAgentEventDataRef,- startNewConversationRef,forceQueueModeRef,sendDispatchInFlightRef,}: UseChatSessionRuntimeOptions) {@@ -339,29 +335,6 @@ export function useChatSessionRuntime({piStreamingTextRef,]);- useEffect(() => {- let cancelled = false;- let off: (() => void) | null = null;- (async () => {- await mountAgentEventBus();- if (cancelled) return;- off = onAgentEvicted(async (payload) => {- if (cancelled) return;- if (payload.sessionId !== piSessionIdRef.current) return;- await startNewConversationRef.current?.();- emit("chat-current-session", { id: piSessionIdRef.current });- });- })();- return () => {- cancelled = true;- try {- off?.();- } catch {- // ignore- }- };- }, [piSessionIdRef, startNewConversationRef]);-return {...pipeWatch,currentSessionKind,diff --git a/apps/screenpipe-app-tauri/components/standalone-chat.tsx b/apps/screenpipe-app-tauri/components/standalone-chat.tsxindex 865f9f572..a31d3ffc9 100644--- a/apps/screenpipe-app-tauri/components/standalone-chat.tsx+++ b/apps/screenpipe-app-tauri/components/standalone-chat.tsx@@ -1026,7 +1026,6 @@ export function StandaloneChat({isStreamingRef,messagesRef,handleAgentEventDataRef,- startNewConversationRef,forceQueueModeRef,sendDispatchInFlightRef,});diff --git a/apps/screenpipe-app-tauri/lib/__tests__/pi-event-router.test.ts b/apps/screenpipe-app-tauri/lib/__tests__/pi-event-router.test.tsindex be61b3248..b48ed77aa 100644--- a/apps/screenpipe-app-tauri/lib/__tests__/pi-event-router.test.ts+++ b/apps/screenpipe-app-tauri/lib/__tests__/pi-event-router.test.ts@@ -41,9 +41,10 @@ import { saveConversationFile } from "@/lib/chat-storage";import {flushPendingSaves,handlePiEvent,+ handleSessionEvicted,handleTerminated,} from "../stores/pi-event-router";-import { useChatStore, type SessionRecord } from "../stores/chat-store";+import { useChatStore, selectOrderedSessions, type SessionRecord } from "../stores/chat-store";import { useAcpSessionConfig } from "../stores/acp-session-config";import type { AgentEventEnvelope, AgentInnerEvent } from "../events/types";@@ -728,6 +729,61 @@ describe("pi-event-router: agent_terminated", () => {});});+describe("pi-event-router: agent_session_evicted", () => {+ beforeEach(reset);++ it("keeps the recents row and sort keys when the pool kills Pi", () => {+ seed("older", { createdAt: 100, lastUserMessageAt: 100, status: "streaming" });+ seed("newer", { createdAt: 200, lastUserMessageAt: 200, status: "streaming" });++ handleSessionEvicted({ sessionId: "older" });++ const older = useChatStore.getState().sessions.older;+ expect(older).toBeDefined();+ expect(older.status).toBe("idle");+ expect(older.createdAt).toBe(100);+ expect(older.lastUserMessageAt).toBe(100);+ expect(older.isStreaming).toBe(false);+ expect(selectOrderedSessions(useChatStore.getState()).map((s) => s.id)).toEqual([+ "newer",+ "older",+ ]);+ });++ it("does not lazy-recreate the row after eviction, so later tokens cannot reshuffle it", async () => {+ seed("A", {+ createdAt: 100,+ lastUserMessageAt: 100,+ title: "real title",+ status: "streaming",+ });+ seed("B", { createdAt: 200, lastUserMessageAt: 200 });++ handleSessionEvicted({ sessionId: "A" });+ await handlePiEvent(piEvt("A", { type: "agent_start" }));+ await handlePiEvent(+ piEvt("A", {+ type: "message_start",+ message: { role: "assistant" },+ } as AgentInnerEvent),+ );++ const a = useChatStore.getState().sessions.A;+ expect(a.createdAt).toBe(100);+ expect(a.lastUserMessageAt).toBe(100);+ expect(a.title).toBe("real title");+ expect(selectOrderedSessions(useChatStore.getState()).map((s) => s.id)).toEqual([+ "B",+ "A",+ ]);+ });++ it("ignores eviction for unknown sessions", () => {+ handleSessionEvicted({ sessionId: "ghost" });+ expect(useChatStore.getState().sessions.ghost).toBeUndefined();+ });+});+describe("pi-event-router: live tool output", () => {beforeEach(reset);diff --git a/apps/screenpipe-app-tauri/lib/stores/pi-event-router.ts b/apps/screenpipe-app-tauri/lib/stores/pi-event-router.tsindex 069fa3e14..e408daec1 100644--- a/apps/screenpipe-app-tauri/lib/stores/pi-event-router.ts+++ b/apps/screenpipe-app-tauri/lib/stores/pi-event-router.ts@@ -358,13 +358,24 @@ export async function handlePiEvent(envelope: AgentEventEnvelope) {store.actions.patch(sid, patch);}-function handleSessionEvicted(payload: AgentSessionEvictedPayload) {- // The Pi process for this session has been killed by the pool. Drop the- // 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.sessionId);- useChatStore.getState().actions.drop(payload.sessionId);+export function handleSessionEvicted(payload: AgentSessionEvictedPayload) {+ // Pool eviction only kills the Pi process. The conversation still exists+ // on disk and in the sidebar — dropping the store row made RECENTS jump:+ // the chat vanished, then the next token lazy-created it as untitled with+ // createdAt=now (no lastUserMessageAt), so it popped to a new position.+ // Stay put and go idle, same as a clean process exit. The next send+ // respawns Pi under this same id.+ const sid = payload.sessionId;+ if (!sid) return;+ previewLastEmittedAt.delete(sid);+ const store = useChatStore.getState();+ if (!store.sessions[sid]) return;+ store.actions.patch(sid, {+ status: "idle",+ lastError: undefined,+ updatedAt: Date.now(),+ });+ store.actions.endTurn(sid);}export function handleTerminated(payload: AgentTerminatedPayload) {