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): preserve live hydration state

Ezra Ellettef26e055f4085
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 7a5929884..c47d5243a 100644
--- a/apps/screenpipe-app-tauri/components/hooks/use-chat-conversations.ts
+++ b/apps/screenpipe-app-tauri/components/hooks/use-chat-conversations.ts
@@ -1330,7 +1330,11 @@ export function useChatConversations(opts: UseChatConversationsOpts) {
useAcpSessionConfig.getState().seedSessionId(conv.id, priorAcpSessionId);
}
if (persisted) {
- if (!store.sessions[conv.id]) {
+ // Disk I/O yields to the event router. Re-read before reconciling so a
+ // session created or advanced while the file was loading keeps its
+ // router-owned activity fields (status, counts, and freshness).
+ const sessionAfterLoad = useChatStore.getState().sessions[conv.id];
+ if (!sessionAfterLoad) {
store.actions.upsert({
id: conv.id,
title: persisted.title || "untitled",
@@ -1353,11 +1357,14 @@ export function useChatConversations(opts: UseChatConversationsOpts) {
});
} else {
store.actions.patch(conv.id, {
- title: persisted.title || existing?.title || "untitled",
+ title: persisted.title || sessionAfterLoad.title || "untitled",
...(persisted.titleSource ? { titleSource: persisted.titleSource } : {}),
pinned: persisted.pinned === true,
hidden: persisted.hidden === true,
- updatedAt: Math.max(existing?.updatedAt ?? 0, persisted.updatedAt ?? 0),
+ updatedAt: Math.max(
+ sessionAfterLoad.updatedAt,
+ persisted.updatedAt ?? 0,
+ ),
...(persisted.kind ? { kind: persisted.kind } : {}),
...(persisted.pipeContext ? { pipeContext: persisted.pipeContext } : {}),
...(persisted.sidebarGroup ? { sidebarGroup: persisted.sidebarGroup } : {}),
@@ -1448,7 +1455,8 @@ export function useChatConversations(opts: UseChatConversationsOpts) {
...((m as any).stoppedByUser ? { stoppedByUser: true } : {}),
}));
// Make sure a record exists, then seed messages and mark hydrated.
- if (!store.sessions[conv.id]) {
+ const sessionBeforeSeed = useChatStore.getState().sessions[conv.id];
+ if (!sessionBeforeSeed) {
store.actions.upsert({
id: conv.id,
title: full.title || "untitled",
@@ -1474,11 +1482,11 @@ export function useChatConversations(opts: UseChatConversationsOpts) {
});
} else if (conv.kind || conv.pipeContext || conv.sidebarGroup || full.sidebarGroup) {
store.actions.patch(conv.id, {
- title: full.title || store.sessions[conv.id]?.title || "untitled",
+ title: full.title || sessionBeforeSeed.title || "untitled",
...(full.titleSource ? { titleSource: full.titleSource } : {}),
pinned: full.pinned === true,
hidden: full.hidden === true,
- updatedAt: Math.max(store.sessions[conv.id]?.updatedAt ?? 0, full.updatedAt ?? 0),
+ updatedAt: Math.max(sessionBeforeSeed.updatedAt, full.updatedAt ?? 0),
...(conv.kind ? { kind: conv.kind } : {}),
...(conv.pipeContext ? { pipeContext: conv.pipeContext } : {}),
...(conv.sidebarGroup ? { sidebarGroup: conv.sidebarGroup } : full.sidebarGroup ? { sidebarGroup: full.sidebarGroup } : {}),
diff --git a/apps/screenpipe-app-tauri/lib/__tests__/load-conversation-hydration.test.tsx b/apps/screenpipe-app-tauri/lib/__tests__/load-conversation-hydration.test.tsx
index 1875d854e..a03fa4de8 100644
--- a/apps/screenpipe-app-tauri/lib/__tests__/load-conversation-hydration.test.tsx
+++ b/apps/screenpipe-app-tauri/lib/__tests__/load-conversation-hydration.test.tsx
@@ -88,6 +88,11 @@ function useHarness() {
const messagesRef = useRef<any[]>([]);
const conversationIdRef = useRef<string | null>(null);
const piSessionIdRef = useRef("");
+ const piStreamingTextRef = useRef("");
+ const piMessageIdRef = useRef<string | null>(null);
+ const piContentBlocksRef = useRef<any[]>([]);
+ const setIsLoading = vi.fn();
+ const setIsStreaming = vi.fn();
const hook = useChatConversations({
messages: messagesRef.current,
setMessages: ((next: any) => {
@@ -102,19 +107,27 @@ function useHarness() {
inputRef: useRef<HTMLTextAreaElement | null>(null),
isLoading: false,
isStreaming: false,
- piStreamingTextRef: useRef(""),
- piMessageIdRef: useRef<string | null>(null),
- piContentBlocksRef: useRef<any[]>([]),
+ piStreamingTextRef,
+ piMessageIdRef,
+ piContentBlocksRef,
piSessionSyncedRef: useRef(false),
piSessionIdRef,
- setIsLoading: vi.fn() as any,
- setIsStreaming: vi.fn() as any,
+ setIsLoading: setIsLoading as any,
+ setIsStreaming: setIsStreaming as any,
setPastedImages: vi.fn() as any,
settings: { chatHistory: { historyEnabled: true } },
inlineHistoryEnabled: false,
selectedPreset: null,
});
- return { hook, messagesRef };
+ return {
+ hook,
+ messagesRef,
+ piStreamingTextRef,
+ piMessageIdRef,
+ piContentBlocksRef,
+ setIsLoading,
+ setIsStreaming,
+ };
}
beforeEach(() => {
@@ -163,6 +176,77 @@ describe("direct conversation hydration", () => {
]);
});
+ it("preserves router activity that arrives while persisted state is loading", async () => {
+ const liveUpdatedAt = Date.now();
+ const richer = {
+ ...completed,
+ content: "newer live answer still streaming",
+ contentBlocks: [{ type: "text", text: "newer live answer still streaming" }],
+ };
+ const liveMessages = [user, richer];
+ const liveBlocks = [{ type: "text", text: "still streaming" }];
+ let resolveLoad!: (value: ReturnType<typeof conversation>) => void;
+ loadConversationFile.mockReturnValueOnce(
+ new Promise((resolve) => {
+ resolveLoad = resolve;
+ }),
+ );
+ const { result } = renderHook(() => useHarness());
+ let loadPromise!: Promise<void>;
+
+ await act(async () => {
+ loadPromise = result.current.hook.loadConversation(conversation([]) as any);
+ await vi.waitFor(() => {
+ expect(loadConversationFile).toHaveBeenCalledWith("chat-target");
+ });
+ });
+
+ act(() => {
+ useChatStore.getState().actions.upsert({
+ id: "chat-target",
+ title: "question",
+ preview: "newer live answer still streaming",
+ status: "streaming",
+ messageCount: liveMessages.length,
+ createdAt: 1,
+ updatedAt: liveUpdatedAt,
+ pinned: false,
+ unread: false,
+ messages: liveMessages,
+ isLoading: true,
+ isStreaming: true,
+ streamingMessageId: richer.id,
+ streamingText: richer.content,
+ contentBlocks: liveBlocks,
+ });
+ });
+
+ await act(async () => {
+ resolveLoad({
+ ...conversation([user, completed]),
+ updatedAt: liveUpdatedAt - 60_000,
+ });
+ await loadPromise;
+ });
+
+ const selected = useChatStore.getState().sessions["chat-target"];
+ expect(result.current.messagesRef.current).toBe(selected.messages);
+ expect(selected.messages).toEqual(liveMessages);
+ expect(selected.updatedAt).toBe(liveUpdatedAt);
+ expect(selected.status).toBe("streaming");
+ expect(selected.messageCount).toBe(liveMessages.length);
+ expect(selected.isLoading).toBe(true);
+ expect(selected.isStreaming).toBe(true);
+ expect(selected.streamingMessageId).toBe(richer.id);
+ expect(selected.streamingText).toBe(richer.content);
+ expect(selected.contentBlocks).toEqual(liveBlocks);
+ expect(result.current.piMessageIdRef.current).toBe(richer.id);
+ expect(result.current.piStreamingTextRef.current).toBe(richer.content);
+ expect(result.current.piContentBlocksRef.current).toEqual(liveBlocks);
+ expect(result.current.setIsLoading).toHaveBeenLastCalledWith(true);
+ expect(result.current.setIsStreaming).toHaveBeenLastCalledWith(true);
+ });
+
it("reuses an already-hydrated store session without reading disk", async () => {
seedStore([user, completed], {
hydratedAt: 10,