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

refactor(effects): move home single-listener effects to useTauriEvent & extract chat-session-activity (#4979)

Ansh Grover40f5dc772d66
diff --git a/apps/screenpipe-app-tauri/app/home/page.tsx b/apps/screenpipe-app-tauri/app/home/page.tsx
index 8e5990937..0f102d002 100644
--- a/apps/screenpipe-app-tauri/app/home/page.tsx
+++ b/apps/screenpipe-app-tauri/app/home/page.tsx
@@ -21,10 +21,10 @@ import {
} from "lucide-react";
import { emit } from "@tauri-apps/api/event";
import {
- isSessionForeground,
+ applyChatSessionActivity,
sessionRecordFromMeta,
useChatStore,
- type SessionStatus,
+ type ChatSessionActivityPayload,
} from "@/lib/stores/chat-store";
import {
conversationMetaFromJson,
@@ -61,6 +61,7 @@ import {
} from "@/lib/chat-utils";
import { useTeam } from "@/lib/hooks/use-team";
import { useEnterprisePolicy } from "@/lib/hooks/use-enterprise-policy";
+import { useTauriEvent } from "@/lib/hooks/use-tauri-event";
import { EnterpriseLicensePrompt } from "@/components/enterprise-license-prompt";
import { PipeActivityIndicator } from "@/components/pipe-activity-indicator";
import { open as openUrl } from "@tauri-apps/plugin-shell";
@@ -201,75 +202,9 @@ function HomeContent() {
// 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() || "untitled",
- 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 && !isSessionForeground(store, id)) {
- store.actions.patch(id, { lastContentAt: Date.now() });
- }
- });
- unlistenFn = unlisten;
- })();
- return () => {
- cancelled = true;
- unlistenFn?.();
- };
- }, []);
+ useTauriEvent<ChatSessionActivityPayload>("chat-session-activity", (event) => {
+ applyChatSessionActivity(useChatStore.getState(), event.payload);
+ });
// Saved-title correction path. Activity updates are best-effort during
// streaming; this event is emitted after canonical on-disk save, so use it
@@ -350,23 +285,10 @@ function HomeContent() {
// but the user is still looking at a different view. They'd have to
// also click "New chat" or similar to see the result. Hooking the
// listener at the page level fixes the cross-view UX.
- useEffect(() => {
- let unlistenFn: (() => void) | undefined;
- let cancelled = false;
- (async () => {
- const { listen } = await import("@tauri-apps/api/event");
- const u = await listen<ChatLoadConversationPayload>("chat-load-conversation", (event) => {
- if (cancelled) return;
- if (!shouldActivateHomeSectionForChatLoadConversation(event.payload)) return;
- setActiveSection("home");
- });
- unlistenFn = u;
- })();
- return () => {
- cancelled = true;
- unlistenFn?.();
- };
- }, [setActiveSection]);
+ useTauriEvent<ChatLoadConversationPayload>("chat-load-conversation", (event) => {
+ if (!shouldActivateHomeSectionForChatLoadConversation(event.payload)) return;
+ setActiveSection("home");
+ });
// Clear the sidebar's "current" highlight when leaving the chat
// view. The chat panel stays mounted (display:none) and keeps streaming.
@@ -585,13 +507,9 @@ function HomeContent() {
return () => { clearInterval(interval); };
}, [refreshRecordingDevices]);
- useEffect(() => {
- let unlisten: (() => void) | null = null;
- listen("audio-device-status-changed", () => {
- void refreshRecordingDevices();
- }).then((fn) => { unlisten = fn; });
- return () => { unlisten?.(); };
- }, [refreshRecordingDevices]);
+ useTauriEvent("audio-device-status-changed", () => {
+ void refreshRecordingDevices();
+ });
const pauseRecording = useCallback(async () => {
await emit("shortcut-stop-recording", {});
@@ -762,47 +680,39 @@ function HomeContent() {
// Native overlay already toggles the meeting in Rust. Refresh local state
// here instead of toggling again, otherwise one click can create or stop
// two meetings depending on which UI surfaces are mounted.
- useEffect(() => {
- let unlisten: (() => void) | null = null;
- listen<MeetingStatusResponse>("native-shortcut-toggle-meeting", (event) => {
- const payload = event.payload;
- if (typeof payload?.active === "boolean") {
- if (payload.active) {
- manualMeetingStartedAt.current = Date.now();
- } else {
- manualMeetingStartedAt.current = 0;
- }
- setMeetingState({
- active: payload.active,
- manualActive: payload.manualActive ?? false,
- activeMeetingId: payload.activeMeetingId ?? null,
- stoppableMeetingId: payload.stoppableMeetingId ?? payload.activeMeetingId ?? null,
- meetingApp: payload.meetingApp ?? null,
- detectionSource: payload.detectionSource ?? null,
- });
- return;
+ useTauriEvent<MeetingStatusResponse>("native-shortcut-toggle-meeting", (event) => {
+ const payload = event.payload;
+ if (typeof payload?.active === "boolean") {
+ if (payload.active) {
+ manualMeetingStartedAt.current = Date.now();
+ } else {
+ manualMeetingStartedAt.current = 0;
}
- void (async () => {
- try {
- const res = await localFetch("/meetings/status");
- const status = res.ok ? await res.json() as MeetingStatusResponse : null;
- setMeetingState(computeMeetingActive(status, manualMeetingStartedAt.current));
- } catch {
- // ignore sync failures; websocket remains source of truth
- }
- })();
- }).then((fn) => { unlisten = fn; });
- return () => { unlisten?.(); };
- }, []);
+ setMeetingState({
+ active: payload.active,
+ manualActive: payload.manualActive ?? false,
+ activeMeetingId: payload.activeMeetingId ?? null,
+ stoppableMeetingId: payload.stoppableMeetingId ?? payload.activeMeetingId ?? null,
+ meetingApp: payload.meetingApp ?? null,
+ detectionSource: payload.detectionSource ?? null,
+ });
+ return;
+ }
+ void (async () => {
+ try {
+ const res = await localFetch("/meetings/status");
+ const status = res.ok ? await res.json() as MeetingStatusResponse : null;
+ setMeetingState(computeMeetingActive(status, manualMeetingStartedAt.current));
+ } catch {
+ // ignore sync failures; websocket remains source of truth
+ }
+ })();
+ });
// Watch pipe: navigate to chat when user clicks "watch" on a running pipe
- useEffect(() => {
- let unlisten: (() => void) | null = null;
- listen<{ pipeName: string; executionId: number }>("watch_pipe", () => {
- setActiveSection("home");
- }).then((fn) => { unlisten = fn; });
- return () => { unlisten?.(); };
- }, [setActiveSection]);
+ useTauriEvent<{ pipeName: string; executionId: number }>("watch_pipe", () => {
+ setActiveSection("home");
+ });
const openSettings = useCallback((section: string = "general") => {
const chatId = activeSection === "home" ? useChatStore.getState().currentId : null;
@@ -929,22 +839,19 @@ function HomeContent() {
.filter((s) => !(s.id === "timeline" && (settings.disableTimeline ?? false)));
// Listen for navigation events from other windows (e.g. tray, Rust-side links)
- useEffect(() => {
- const unlisten = listen<{ url: string }>("navigate", (event) => {
- const url = new URL(event.payload.url, window.location.origin);
- const section = url.searchParams.get("section");
- if (!section) return;
- if (SETTINGS_SECTIONS.has(section)) {
- const mapped = section === "disk-usage" || section === "cloud-archive" || section === "cloud-sync"
- ? "storage" : section;
- router.push(`/settings?section=${mapped}`);
- } else {
- const mapped = section === "feedback" ? "help" : section;
- if (ALL_SECTIONS.includes(mapped)) setActiveSection(mapped);
- }
- });
- return () => { unlisten.then((fn) => fn()); };
- }, [setActiveSection, router]);
+ useTauriEvent<{ url: string }>("navigate", (event) => {
+ const url = new URL(event.payload.url, window.location.origin);
+ const section = url.searchParams.get("section");
+ if (!section) return;
+ if (SETTINGS_SECTIONS.has(section)) {
+ const mapped = section === "disk-usage" || section === "cloud-archive" || section === "cloud-sync"
+ ? "storage" : section;
+ router.push(`/settings?section=${mapped}`);
+ } else {
+ const mapped = section === "feedback" ? "help" : section;
+ if (ALL_SECTIONS.includes(mapped)) setActiveSection(mapped);
+ }
+ });
const isFullHeight =
activeSection === "home" ||
diff --git a/apps/screenpipe-app-tauri/lib/__tests__/chat-store.test.ts b/apps/screenpipe-app-tauri/lib/__tests__/chat-store.test.ts
index da95f38d8..6258d590b 100644
--- a/apps/screenpipe-app-tauri/lib/__tests__/chat-store.test.ts
+++ b/apps/screenpipe-app-tauri/lib/__tests__/chat-store.test.ts
@@ -16,7 +16,9 @@ import {
getOrCreateEmptyChatId,
dedupeSessionRecords,
sessionRecordFromMeta,
+ applyChatSessionActivity,
type SessionRecord,
+ type ChatSessionActivityPayload,
} from "../stores/chat-store";
function reset() {
@@ -671,3 +673,143 @@ describe("chat-store: cross-window duplicate row collapsing", () => {
expect(selectOrderedSessions(useChatStore.getState())).toHaveLength(2);
});
});
+
+/**
+ * applyChatSessionActivity — characterization tests for the `chat-session-activity`
+ * merge logic extracted from app/home/page.tsx. These lock in the exact
+ * upsert-vs-patch, staleness, title/preview/status merge, lastError, and
+ * unread-hint behavior so the useEffect→useTauriEvent refactor (#4791) is
+ * provably behavior-preserving. `now` is injected for determinism.
+ */
+describe("chat-store: applyChatSessionActivity", () => {
+ beforeEach(reset);
+
+ const NOW = 9_999;
+
+ it("creates a new session with defaults when none exists", () => {
+ applyChatSessionActivity(useChatStore.getState(), { id: "A", updatedAt: 2_000 });
+ const s = useChatStore.getState().sessions["A"];
+ expect(s).toBeDefined();
+ expect(s.title).toBe("untitled");
+ expect(s.preview).toBe("");
+ expect(s.status).toBe("idle");
+ expect(s.createdAt).toBe(2_000);
+ expect(s.updatedAt).toBe(2_000);
+ expect(s.messageCount).toBe(0);
+ expect(s.pinned).toBe(false);
+ });
+
+ it("carries title/preview/status through on create and trims the title", () => {
+ applyChatSessionActivity(useChatStore.getState(), {
+ id: "A",
+ title: " hello ",
+ preview: "hi there",
+ status: "streaming",
+ updatedAt: 2_000,
+ });
+ const s = useChatStore.getState().sessions["A"];
+ expect(s.title).toBe("hello");
+ expect(s.preview).toBe("hi there");
+ expect(s.status).toBe("streaming");
+ });
+
+ it("ignores undefined payloads and those missing id or updatedAt", () => {
+ applyChatSessionActivity(useChatStore.getState(), undefined);
+ applyChatSessionActivity(useChatStore.getState(), { id: "", updatedAt: 1 });
+ applyChatSessionActivity(useChatStore.getState(), { id: "A", updatedAt: 0 });
+ expect(Object.keys(useChatStore.getState().sessions)).toHaveLength(0);
+ });
+
+ it("drops stale events (existing.updatedAt > incoming.updatedAt)", () => {
+ useChatStore.getState().actions.upsert(baseRecord({ id: "A", title: "keep", updatedAt: 5_000 }));
+ applyChatSessionActivity(useChatStore.getState(), { id: "A", title: "stale", updatedAt: 4_000 });
+ const s = useChatStore.getState().sessions["A"];
+ expect(s.title).toBe("keep");
+ expect(s.updatedAt).toBe(5_000);
+ });
+
+ it("patches existing and falls back to existing preview/status when omitted", () => {
+ useChatStore.getState().actions.upsert(
+ baseRecord({ id: "A", title: "old", preview: "oldprev", status: "idle", updatedAt: 1_000 }),
+ );
+ applyChatSessionActivity(useChatStore.getState(), { id: "A", title: "new", updatedAt: 2_000 });
+ const s = useChatStore.getState().sessions["A"];
+ expect(s.title).toBe("new");
+ expect(s.preview).toBe("oldprev");
+ expect(s.status).toBe("idle");
+ expect(s.updatedAt).toBe(2_000);
+ });
+
+ it("keeps the existing title when the incoming title is blank", () => {
+ useChatStore.getState().actions.upsert(baseRecord({ id: "A", title: "real", updatedAt: 1_000 }));
+ applyChatSessionActivity(useChatStore.getState(), { id: "A", title: " ", updatedAt: 2_000 });
+ expect(useChatStore.getState().sessions["A"].title).toBe("real");
+ });
+
+ describe("lastError handling", () => {
+ it("sets a non-empty lastError", () => {
+ useChatStore.getState().actions.upsert(baseRecord({ id: "A", updatedAt: 1_000 }));
+ applyChatSessionActivity(useChatStore.getState(), { id: "A", lastError: "boom", updatedAt: 2_000 });
+ expect(useChatStore.getState().sessions["A"].lastError).toBe("boom");
+ });
+
+ it("clears lastError when passed an empty string", () => {
+ useChatStore.getState().actions.upsert(baseRecord({ id: "A", lastError: "old", updatedAt: 1_000 }));
+ applyChatSessionActivity(useChatStore.getState(), { id: "A", lastError: "", updatedAt: 2_000 });
+ expect(useChatStore.getState().sessions["A"].lastError).toBeUndefined();
+ });
+
+ it("preserves existing lastError when omitted and status stays error", () => {
+ useChatStore.getState().actions.upsert(
+ baseRecord({ id: "A", status: "error", lastError: "prev", updatedAt: 1_000 }),
+ );
+ applyChatSessionActivity(useChatStore.getState(), { id: "A", preview: "changed", updatedAt: 2_000 });
+ expect(useChatStore.getState().sessions["A"].lastError).toBe("prev");
+ });
+
+ it("drops lastError when omitted and status is not error", () => {
+ useChatStore.getState().actions.upsert(
+ baseRecord({ id: "A", status: "error", lastError: "prev", updatedAt: 1_000 }),
+ );
+ applyChatSessionActivity(useChatStore.getState(), { id: "A", status: "idle", updatedAt: 2_000 });
+ expect(useChatStore.getState().sessions["A"].lastError).toBeUndefined();
+ });
+ });
+
+ describe("unreadHint -> lastContentAt", () => {
+ it("sets lastContentAt (injected now) when hinted and NOT foreground", () => {
+ useChatStore.getState().actions.upsert(baseRecord({ id: "A", updatedAt: 1_000 }));
+ applyChatSessionActivity(
+ useChatStore.getState(),
+ { id: "A", preview: "changed", unreadHint: true, updatedAt: 2_000 },
+ NOW,
+ );
+ expect(useChatStore.getState().sessions["A"].lastContentAt).toBe(NOW);
+ });
+
+ it("does NOT set lastContentAt when the session is foreground", () => {
+ useChatStore.getState().actions.upsert(baseRecord({ id: "A", updatedAt: 1_000 }));
+ useChatStore.setState({ currentId: "A" });
+ applyChatSessionActivity(
+ useChatStore.getState(),
+ { id: "A", preview: "changed", unreadHint: true, updatedAt: 2_000 },
+ NOW,
+ );
+ expect(useChatStore.getState().sessions["A"].lastContentAt).toBeUndefined();
+ });
+
+ it("skips the unread hint when the merge is a no-op (equality early-return)", () => {
+ // Characterizes existing behavior: the no-op equality guard returns from
+ // the whole function, so an unread hint is skipped when nothing changed.
+ useChatStore.getState().actions.upsert(
+ baseRecord({ id: "A", title: "same", preview: "same", status: "idle", updatedAt: 2_000 }),
+ );
+ applyChatSessionActivity(
+ useChatStore.getState(),
+ { id: "A", title: "same", preview: "same", status: "idle", unreadHint: true, updatedAt: 2_000 },
+ NOW,
+ );
+ expect(useChatStore.getState().sessions["A"].lastContentAt).toBeUndefined();
+ });
+ });
+});
diff --git a/apps/screenpipe-app-tauri/lib/stores/chat-store.ts b/apps/screenpipe-app-tauri/lib/stores/chat-store.ts
index 02820f3e2..a005279a8 100644
--- a/apps/screenpipe-app-tauri/lib/stores/chat-store.ts
+++ b/apps/screenpipe-app-tauri/lib/stores/chat-store.ts
@@ -301,6 +301,80 @@ export function isSessionForeground(
return state.currentId === id || state.panelSessionId === id;
}
+/** Payload of the backend `chat-session-activity` event — a lightweight
+ * overlay-side activity mirror (status + preview + title), never full
+ * message bodies. */
+export interface ChatSessionActivityPayload {
+ id: string;
+ status?: SessionStatus;
+ preview?: string;
+ title?: string;
+ updatedAt: number;
+ lastError?: string;
+ unreadHint?: boolean;
+}
+
+/** Merge a `chat-session-activity` event into the sidebar store.
+ *
+ * Extracted verbatim from the home page's listener so the upsert-vs-patch,
+ * staleness (`existing.updatedAt > updatedAt`), title/preview/status merge,
+ * and unread-hint branches are unit-testable in isolation. `now` is injected
+ * so the `lastContentAt` write is deterministic under test.
+ */
+export function applyChatSessionActivity(
+ store: Pick<ChatStore, "sessions" | "currentId" | "panelSessionId" | "actions">,
+ payload: ChatSessionActivityPayload | undefined,
+ now: number = Date.now(),
+): void {
+ const { id, status, preview, title, updatedAt, lastError, unreadHint } =
+ payload ?? ({} as Partial<ChatSessionActivityPayload>);
+ if (!id || !updatedAt) return;
+ const existing = store.sessions[id];
+ if (!existing) {
+ store.actions.upsert({
+ id,
+ title: title?.trim() || "untitled",
+ 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 && !isSessionForeground(store, id)) {
+ store.actions.patch(id, { lastContentAt: now });
+ }
+}
+
/** Compute unread from timestamps — immune to non-content writes.
* A session is unread when its most recent real message append happened
* AFTER the last time the user viewed it. Falls back to