Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(mobilehog): sync report read state with the server (#109530)

Dylan Martin1766292e924b
diff --git a/products/desktop/apps/mobilehog/src/app/(drawer)/self-driving.tsx b/products/desktop/apps/mobilehog/src/app/(drawer)/self-driving.tsx
index 798cdb46ca74..00b8ac95ef50 100644
--- a/products/desktop/apps/mobilehog/src/app/(drawer)/self-driving.tsx
+++ b/products/desktop/apps/mobilehog/src/app/(drawer)/self-driving.tsx
@@ -22,8 +22,9 @@ import { TriageDeck } from "@/components/TriageDeck";
import { REPORT_FILTERS, type ReportFilter } from "@/lib/reportFilters";
import {
useDismissReport,
+ useMarkReportRead,
+ useReportReadStates,
useReports,
- useSeenReports,
useStartReportTask,
} from "@/lib/reports";
import { colors, fonts, radius } from "@/lib/theme";
@@ -42,9 +43,7 @@ export default function SelfDrivingScreen() {
// The deck always works on the reports that need attention.
const reports = useReports();
const listed = useReports("", filter);
- const seen = useSeenReports((s) => s.seen);
- const seenHydrated = useSeenReports((s) => s.hydrated);
- const markSeen = useSeenReports((s) => s.markSeen);
+ const markRead = useMarkReportRead();
const dismiss = useDismissReport();
const startTask = useStartReportTask();
// Locally swiped ids, so a card leaves the deck before the server catches up.
@@ -63,23 +62,23 @@ export default function SelfDrivingScreen() {
);
const rows = filter === "attention" ? all : (listed.data ?? []);
const listFailed = listed.isError && !listed.data;
- const unseen = useMemo(
- () => all.filter((report) => !seen.has(report.id)),
- [all, seen],
- );
+ const allIds = useMemo(() => all.map((report) => report.id), [all]);
+ const rowIds = useMemo(() => rows.map((report) => report.id), [rows]);
+ const readStates = useReportReadStates(allIds);
+ const rowReadStates = useReportReadStates(rowIds);
- // New reports since the last visit open the deck on their own.
+ // Unread reports open the deck on their own.
useEffect(() => {
if (
deck === null &&
filter === "attention" &&
- seenHydrated &&
reports.data &&
- unseen.length > 0
+ readStates.settled
) {
- setDeck(unseen.map((report) => report.id));
+ const unread = allIds.filter((id) => readStates.unread.has(id));
+ if (unread.length > 0) setDeck(unread);
}
- }, [deck, filter, seenHydrated, reports.data, unseen]);
+ }, [deck, filter, reports.data, readStates, allIds]);
const deckReports = useMemo(
() =>
@@ -89,15 +88,14 @@ export default function SelfDrivingScreen() {
[deck, all],
);
- // Whatever surfaces at the top of the deck counts as seen.
+ // Whatever surfaces at the top of the deck counts as read.
const topId = deckReports[0]?.id;
useEffect(() => {
- if (topId && !seen.has(topId)) markSeen([topId]);
- }, [topId, seen, markSeen]);
+ if (topId) markRead(topId);
+ }, [topId, markRead]);
const finish = (report: SignalReport): void => {
setHandled((current) => new Set(current).add(report.id));
- markSeen([report.id]);
};
// A failed action leaves the report open on the server, so put the card back
@@ -221,7 +219,7 @@ export default function SelfDrivingScreen() {
{formatRelativeAge(report.updated_at)}
</Text>
</View>
- {filter === "attention" && !seen.has(report.id) ? (
+ {rowReadStates.unread.has(report.id) ? (
<View style={styles.newDot} />
) : null}
</Pressable>
diff --git a/products/desktop/apps/mobilehog/src/app/_layout.tsx b/products/desktop/apps/mobilehog/src/app/_layout.tsx
index 91207b45fb6c..e7d00ef38cf8 100644
--- a/products/desktop/apps/mobilehog/src/app/_layout.tsx
+++ b/products/desktop/apps/mobilehog/src/app/_layout.tsx
@@ -14,7 +14,6 @@ import "@/lib/network";
import { usePushNotifications } from "@/lib/notifications";
import { usePrefs } from "@/lib/prefs";
import { useRepo } from "@/lib/repo";
-import { useSeenReports } from "@/lib/reports";
import { useSessions } from "@/lib/session";
import { colors, fonts } from "@/lib/theme";
@@ -27,7 +26,6 @@ function AuthGate() {
const hydrateRepo = useRepo((s) => s.hydrate);
const hydratePrefs = usePrefs((s) => s.hydrate);
- const hydrateSeen = useSeenReports((s) => s.hydrate);
usePushNotifications();
useEffect(() => {
hydrate();
@@ -37,8 +35,7 @@ function AuthGate() {
useEffect(() => {
if (!useAuth.getState().session) return;
hydrateRepo();
- hydrateSeen();
- }, [hydrateRepo, hydrateSeen]);
+ }, [hydrateRepo]);
useEffect(() => {
if (!hydrated) return;
diff --git a/products/desktop/apps/mobilehog/src/app/report/[id].tsx b/products/desktop/apps/mobilehog/src/app/report/[id].tsx
index 93170c117882..9f946baee5b0 100644
--- a/products/desktop/apps/mobilehog/src/app/report/[id].tsx
+++ b/products/desktop/apps/mobilehog/src/app/report/[id].tsx
@@ -21,8 +21,8 @@ import {
import {
useDismissReport,
useHasLiveImplementationTask,
+ useMarkReportRead,
useReport,
- useSeenReports,
useStartReportTask,
} from "@/lib/reports";
import { colors, fonts, radius } from "@/lib/theme";
@@ -34,16 +34,12 @@ export default function ReportScreen() {
const dismiss = useDismissReport();
const startTask = useStartReportTask();
const liveTask = useHasLiveImplementationTask(id);
- const seenHydrated = useSeenReports((s) => s.hydrated);
- const isSeen = useSeenReports((s) => s.seen.has(id));
- const markSeen = useSeenReports((s) => s.markSeen);
-
+ const markRead = useMarkReportRead();
+ // A report that failed to load or is still loading stays unread.
const reportId = report?.id;
useEffect(() => {
- if (reportId && seenHydrated && !isSeen) {
- markSeen([reportId]).catch(() => {});
- }
- }, [reportId, seenHydrated, isSeen, markSeen]);
+ if (reportId) markRead(reportId);
+ }, [reportId, markRead]);
if (!report) {
return (
diff --git a/products/desktop/apps/mobilehog/src/components/DrawerContent.tsx b/products/desktop/apps/mobilehog/src/components/DrawerContent.tsx
index f599ec5a6f3b..8a879fb1198e 100644
--- a/products/desktop/apps/mobilehog/src/components/DrawerContent.tsx
+++ b/products/desktop/apps/mobilehog/src/components/DrawerContent.tsx
@@ -1,5 +1,6 @@
import { Host, Image } from "@expo/ui/swift-ui";
import { useRouter } from "expo-router";
+import { useDrawerStatus } from "expo-router/drawer";
import { useMemo } from "react";
import { Pressable, ScrollView, StyleSheet, Text, View } from "react-native";
import { useSafeAreaInsets } from "react-native-safe-area-context";
@@ -11,7 +12,7 @@ import { activityAt, RowSkeletons, TaskRow } from "@/components/TaskRow";
import { useActivity } from "@/lib/activity";
import { useAuth } from "@/lib/auth";
import { useTasks } from "@/lib/queries";
-import { useReports, useSeenReports } from "@/lib/reports";
+import { useReportReadStates, useReports } from "@/lib/reports";
import { colors, fonts, radius } from "@/lib/theme";
export function DrawerContent({ closeDrawer }: { closeDrawer: () => void }) {
@@ -20,11 +21,16 @@ export function DrawerContent({ closeDrawer }: { closeDrawer: () => void }) {
const tasks = useTasks();
const userName = useAuth((s) => s.session?.userName ?? "");
const unread = useActivity().data?.unread_count ?? 0;
- const reports = useReports().data ?? [];
- const seenReports = useSeenReports((s) => s.seen);
- const newReports = reports.filter(
- (report) => !seenReports.has(report.id),
- ).length;
+ const reports = useReports().data;
+ const reportIds = useMemo(
+ () => (reports ?? []).map((report) => report.id),
+ [reports],
+ );
+ // The badge shows only while the drawer is open, so read state does not poll
+ // behind a closed drawer.
+ const drawerOpen = useDrawerStatus() === "open";
+ const newReports = useReportReadStates(reportIds, { enabled: drawerOpen })
+ .unread.size;
const sorted = useMemo(
() =>
[...(tasks.data ?? [])].sort((a, b) =>
diff --git a/products/desktop/apps/mobilehog/src/lib/accountLifecycle.ts b/products/desktop/apps/mobilehog/src/lib/accountLifecycle.ts
index d1b18dd17414..0746669e0f86 100644
--- a/products/desktop/apps/mobilehog/src/lib/accountLifecycle.ts
+++ b/products/desktop/apps/mobilehog/src/lib/accountLifecycle.ts
@@ -11,7 +11,7 @@ import { useComposer } from "@/lib/composer";
import { resetEngine } from "@/lib/engine";
import { resetMcpClient } from "@/lib/mcp/client";
import { useRepo } from "@/lib/repo";
-import { resetUnstartedReportTasks, useSeenReports } from "@/lib/reports";
+import { resetUnstartedReportTasks } from "@/lib/reports";
import { useSessions } from "@/lib/session";
let stopPersisting: (() => void) | undefined;
@@ -42,7 +42,6 @@ useAuth.subscribe((state, previous) => {
resetMcpClient();
useComposer.getState().reset();
useRepo.setState({ repository: undefined });
- useSeenReports.setState({ seen: new Set(), hydrated: false });
resetUnstartedReportTasks();
resetSentPhotos();
});
diff --git a/products/desktop/apps/mobilehog/src/lib/reportReadState.test.ts b/products/desktop/apps/mobilehog/src/lib/reportReadState.test.ts
new file mode 100644
index 000000000000..d6806ef3036e
--- /dev/null
+++ b/products/desktop/apps/mobilehog/src/lib/reportReadState.test.ts
@@ -0,0 +1,52 @@
+import { QueryClient } from "@tanstack/react-query";
+import { describe, expect, it } from "vitest";
+import {
+ markReadOptimistically,
+ restoreReadState,
+ summarizeReadStates,
+} from "./reportReadState";
+
+describe("reportReadState", () => {
+ it("counts only a fresh, successful false as unread", () => {
+ const states = summarizeReadStates(
+ ["read", "unread", "failed", "cached", "stale-after-error"],
+ [
+ { data: true, isError: false, isFetchedAfterMount: true },
+ { data: false, isError: false, isFetchedAfterMount: true },
+ { data: undefined, isError: true, isFetchedAfterMount: true },
+ { data: false, isError: false, isFetchedAfterMount: false },
+ { data: false, isError: true, isFetchedAfterMount: true },
+ ],
+ );
+ expect([...states.unread]).toEqual(["unread"]);
+ });
+
+ it("is not settled while a cached state waits for the server", () => {
+ const states = summarizeReadStates(
+ ["a", "b"],
+ [
+ { data: false, isError: false, isFetchedAfterMount: false },
+ { data: true, isError: false, isFetchedAfterMount: true },
+ ],
+ );
+ expect(states.settled).toBe(false);
+ });
+
+ it.each([
+ [false, false],
+ [undefined, undefined],
+ ])(
+ "puts back %s after a failed write so the next open retries",
+ async (previous, restored) => {
+ const queryClient = new QueryClient();
+ const key = ["reports", "read", "r"];
+ if (previous !== undefined) queryClient.setQueryData(key, previous);
+
+ const saved = await markReadOptimistically(queryClient, key);
+ expect(queryClient.getQueryData(key)).toBe(true);
+
+ await restoreReadState(queryClient, key, saved);
+ expect(queryClient.getQueryData(key)).toBe(restored);
+ },
+ );
+});
diff --git a/products/desktop/apps/mobilehog/src/lib/reportReadState.ts b/products/desktop/apps/mobilehog/src/lib/reportReadState.ts
new file mode 100644
index 000000000000..e58749b1e1e6
--- /dev/null
+++ b/products/desktop/apps/mobilehog/src/lib/reportReadState.ts
@@ -0,0 +1,63 @@
+import type { QueryClient, QueryKey } from "@tanstack/react-query";
+
+export interface ReadStateResult {
+ data?: boolean;
+ isError: boolean;
+ isFetchedAfterMount: boolean;
+}
+
+export interface ReportReadStates {
+ unread: ReadonlySet<string>;
+ // Every state came from the server since mount, not only from the saved
+ // cache, so a report read on another device does not count as unread.
+ settled: boolean;
+}
+
+// Only a fresh, successful answer counts as unread. A cached value or a failed
+// refresh counts as read, so stale or missing state never lights a dot or pops
+// the deck.
+export function summarizeReadStates(
+ reportIds: readonly string[],
+ results: readonly ReadStateResult[],
+): ReportReadStates {
+ const unread = new Set<string>();
+ reportIds.forEach((id, index) => {
+ const result = results[index];
+ if (
+ result?.data === false &&
+ result.isFetchedAfterMount &&
+ !result.isError
+ ) {
+ unread.add(id);
+ }
+ });
+ return {
+ unread,
+ settled: results.every((result) => result.isFetchedAfterMount),
+ };
+}
+
+export async function markReadOptimistically(
+ queryClient: QueryClient,
+ key: QueryKey,
+): Promise<boolean | undefined> {
+ await queryClient.cancelQueries({ queryKey: key, exact: true });
+ const previous = queryClient.getQueryData<boolean>(key);
+ queryClient.setQueryData(key, true);
+ return previous;
+}
+
+// Put back what the cache held before the failed write, so the next open does
+// not see the report as read and tries the write again.
+export async function restoreReadState(
+ queryClient: QueryClient,
+ key: QueryKey,
+ previous: boolean | undefined,
+): Promise<void> {
+ if (previous === undefined) {
+ await queryClient.resetQueries({ queryKey: key, exact: true });
+ return;
+ }
+ queryClient.setQueryData(key, previous);
+ await queryClient.invalidateQueries({ queryKey: key, exact: true });
+}
diff --git a/products/desktop/apps/mobilehog/src/lib/reports.ts b/products/desktop/apps/mobilehog/src/lib/reports.ts
index bd5e93c01c59..c72d4b974273 100644
--- a/products/desktop/apps/mobilehog/src/lib/reports.ts
+++ b/products/desktop/apps/mobilehog/src/lib/reports.ts
@@ -11,13 +11,13 @@ import type {
import {
type QueryClient,
useMutation,
+ useQueries,
useQuery,
useQueryClient,
} from "@tanstack/react-query";
import { type Href, router } from "expo-router";
-import * as SecureStore from "expo-secure-store";
-import { create } from "zustand";
-import { accountStorageKey, sessionIdentity, useAuth } from "@/lib/auth";
+import { useCallback, useMemo } from "react";
+import { useAuth } from "@/lib/auth";
import { getClient } from "@/lib/client";
import { currentRunConfig } from "@/lib/composer";
import {
@@ -25,6 +25,13 @@ import {
type ReportFilter,
reportFilterParams,
} from "@/lib/reportFilters";
+import {
+ markReadOptimistically,
+ type ReadStateResult,
+ type ReportReadStates,
+ restoreReadState,
+ summarizeReadStates,
+} from "@/lib/reportReadState";
import { fetchHasLiveImplementationTask } from "@/lib/reportTasks";
import { useSessions } from "@/lib/session";
@@ -32,6 +39,7 @@ export const reportKeys = {
all: ["reports"] as const,
list: ["reports", "list"] as const,
detail: (id: string) => ["reports", "detail", id] as const,
+ read: (id: string) => ["reports", "read", id] as const,
signals: (id: string) => ["reports", id, "signals"] as const,
artefacts: (id: string) => ["reports", id, "artefacts"] as const,
liveTask: (id: string) => ["reports", id, "live-task"] as const,
@@ -223,43 +231,66 @@ export function useStartReportTask() {
return { start: run, isPending: start.isPending };
}
-// Which reports this device has already surfaced in triage, so only new ones
-// pop the deck automatically.
-const SEEN_KEY = "mobilehog_seen_reports";
-const SEEN_CAP = 500;
+// Read state lives on the server, so a report read on one device is read on
+// all of them. The client batches the per-report lookups into one request.
+export function useReportReadStates(
+ reportIds: readonly string[],
+ { enabled = true }: { enabled?: boolean } = {},
+): ReportReadStates {
+ const results = useQueries({
+ queries: reportIds.map((id) => ({
+ queryKey: reportKeys.read(id),
+ queryFn: () => getClient().getReportReadState(id),
+ enabled,
+ // Unread needs a fetch after mount, so every new screen (and the drawer
+ // when it opens) asks the server again even if the cache is recent.
+ staleTime: 0,
+ refetchInterval: enabled ? 30_000 : false,
+ })),
+ combine: pickReadStates,
+ });
+ return useMemo(
+ () => summarizeReadStates(reportIds, results),
+ [reportIds, results],
+ );
+}
-interface SeenState {
- seen: Set<string>;
- hydrated: boolean;
- hydrate: () => Promise<void>;
- markSeen: (ids: string[]) => Promise<void>;
+function pickReadStates(results: ReadStateResult[]): ReadStateResult[] {
+ return results.map(({ data, isError, isFetchedAfterMount }) => ({
+ data,
+ isError,
+ isFetchedAfterMount,
+ }));
}
-export const useSeenReports = create<SeenState>((set, get) => ({
- seen: new Set(),
- hydrated: false,
- hydrate: async () => {
- if (!useAuth.getState().session) return;
- const identity = sessionIdentity();
- try {
- const raw = await SecureStore.getItemAsync(accountStorageKey(SEEN_KEY));
- if (sessionIdentity() !== identity) return;
- set({
- seen: new Set(raw ? (JSON.parse(raw) as string[]) : []),
- hydrated: true,
- });
- } catch {
- if (sessionIdentity() === identity) set({ hydrated: true });
- }
- },
- markSeen: async (ids) => {
- const next = new Set(get().seen);
- for (const id of ids) next.add(id);
- const list = [...next].slice(-SEEN_CAP);
- set({ seen: new Set(list) });
- await SecureStore.setItemAsync(
- accountStorageKey(SEEN_KEY),
- JSON.stringify(list),
- );
- },
-}));
+export function useMarkReportRead(): (reportId: string) => void {
+ const queryClient = useQueryClient();
+ const { mutate } = useMutation({
+ mutationFn: (reportId: string) =>
+ getClient().getReportReadStates([reportId], true),
+ onMutate: async (reportId) => ({
+ previous: await markReadOptimistically(
+ queryClient,
+ reportKeys.read(reportId),
+ ),
+ }),
+ onSuccess: (states, reportId) =>
+ queryClient.setQueryData(
+ reportKeys.read(reportId),
+ states[reportId] === true,
+ ),
+ onError: (_error, reportId, context) =>
+ restoreReadState(
+ queryClient,
+ reportKeys.read(reportId),
+ context?.previous,
+ ),
+ });
+ return useCallback(
+ (reportId: string) => {
+ if (queryClient.getQueryData(reportKeys.read(reportId)) === true) return;
+ mutate(reportId);
+ },
+ [queryClient, mutate],
+ );
+}