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): show last opened chats in search (#115150)

Dylan Martin35b5e09a0838
diff --git a/products/desktop/apps/mobilehog/src/app/(drawer)/recents.tsx b/products/desktop/apps/mobilehog/src/app/(drawer)/recents.tsx
index 4a65d5e60e6d..d6f2c6a144b4 100644
--- a/products/desktop/apps/mobilehog/src/app/(drawer)/recents.tsx
+++ b/products/desktop/apps/mobilehog/src/app/(drawer)/recents.tsx
@@ -2,8 +2,9 @@ import { Button, Host, Image, Menu } from "@expo/ui/swift-ui";
import { frame, glassEffect } from "@expo/ui/swift-ui/modifiers";
import type { SignalReport, Task } from "@posthog/shared/domain-types";
import { FlashList } from "@shopify/flash-list";
-import { useNavigation, useRouter } from "expo-router";
-import { useEffect, useMemo, useRef, useState } from "react";
+import { useQueries } from "@tanstack/react-query";
+import { useFocusEffect, useNavigation, useRouter } from "expo-router";
+import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { Pressable, StyleSheet, Text, TextInput, View } from "react-native";
import { KeyboardStickyView } from "react-native-keyboard-controller";
import Animated, {
@@ -22,11 +23,14 @@ import { Glass, GlassCircleButton } from "@/components/Glass";
import { MenuIcon } from "@/components/Icons";
import {
activityAt,
- ListRow,
+ ChatRow,
RowSkeletons,
- TaskRow,
+ TaskChatRow,
} from "@/components/TaskRow";
-import { useTaskPages } from "@/lib/queries";
+import { useAuth } from "@/lib/auth";
+import { getClient } from "@/lib/client";
+import { lastOpened, loadOpened } from "@/lib/openedChats";
+import { keys, useTaskPages, useTasks } from "@/lib/queries";
import { useReports } from "@/lib/reports";
import { colors, fonts, radius } from "@/lib/theme";
@@ -44,6 +48,29 @@ const SCOPES = [
] as const;
const HEADER_HEIGHT = 64;
+const LAST_OPENED_LIMIT = 8;
+
+function foundTasks(results: { data?: Task; isLoading: boolean }[]) {
+ return {
+ data: results.flatMap((result) => (result.data ? [result.data] : [])),
+ isLoading: results.some((result) => result.isLoading),
+ };
+}
+
+// Opened chats the recent page does not hold. Failed lookups (deleted tasks)
+// are left out.
+function useOpenedTasks(ids: readonly string[]) {
+ const session = useAuth((s) => s.session);
+ return useQueries({
+ queries: ids.map((id) => ({
+ queryKey: keys.task(id),
+ queryFn: () => getClient().getTask(id),
+ enabled: !!session,
+ staleTime: 60_000,
+ })),
+ combine: foundTasks,
+ });
+}
function useDebounced(value: string, delay: number): string {
const [debounced, setDebounced] = useState(value);
@@ -59,16 +86,46 @@ export default function RecentsScreen() {
const navigation = useNavigation<{ openDrawer: () => void }>();
const insets = useSafeAreaInsets();
const input = useRef<TextInput>(null);
- const [searching, setSearching] = useState(true);
+ const [searching, setSearching] = useState(false);
const [query, setQuery] = useState("");
const [scope, setScope] = useState<Scope>("all");
const search = useDebounced(query.trim(), 250);
const archived = scope === "archived";
- const showReports = scope === "all" || scope === "reports";
+ const recentMode = !search && scope === "all";
+ const showReports = !recentMode && (scope === "all" || scope === "reports");
const tasks = useTaskPages(search, archived);
const reports = useReports(search);
+ const recentTasks = useTasks();
+ const [opened, setOpened] = useState(loadOpened);
+ useFocusEffect(useCallback(() => setOpened(loadOpened()), []));
+ // The recent page holds at most one page of tasks, so a chat opened from an
+ // older search result is fetched on its own.
+ const missing = useMemo(() => {
+ if (!recentMode || !recentTasks.data) return [];
+ const inPage = new Set(recentTasks.data.map((task) => task.id));
+ return opened.slice(0, LAST_OPENED_LIMIT).filter((id) => !inPage.has(id));
+ }, [recentMode, recentTasks.data, opened]);
+ const openedTasks = useOpenedTasks(missing);
const items = useMemo(() => {
+ if (recentMode) {
+ const recent = [...(recentTasks.data ?? [])].sort((a, b) =>
+ activityAt(b).localeCompare(activityAt(a)),
+ );
+ return lastOpened(
+ opened,
+ recent,
+ openedTasks.data,
+ LAST_OPENED_LIMIT,
+ ).map(
+ (task): Item => ({
+ kind: "task",
+ id: task.id,
+ time: activityAt(task),
+ task,
+ }),
+ );
+ }
const list: Item[] = [];
if (scope !== "reports") {
for (const task of tasks.data?.pages.flatMap((page) => page.visible) ??
@@ -87,11 +144,21 @@ export default function RecentsScreen() {
}
}
return list.sort((a, b) => b.time.localeCompare(a.time));
- }, [scope, showReports, tasks.data, reports.data]);
+ }, [
+ recentMode,
+ recentTasks.data,
+ openedTasks.data,
+ opened,
+ scope,
+ showReports,
+ tasks.data,
+ reports.data,
+ ]);
- const loading =
- (scope !== "reports" && tasks.isLoading) ||
- (showReports && reports.isLoading);
+ const loading = recentMode
+ ? recentTasks.isLoading || openedTasks.isLoading
+ : (scope !== "reports" && tasks.isLoading) ||
+ (showReports && reports.isLoading);
const closeSearch = (): void => {
setQuery("");
@@ -109,9 +176,8 @@ export default function RecentsScreen() {
getItemType={(item) => item.kind}
renderItem={({ item }) =>
item.kind === "task" ? (
- <TaskRow
+ <TaskChatRow
task={item.task}
- label="Task"
archived={archived}
onPress={() =>
router.push({
@@ -121,10 +187,10 @@ export default function RecentsScreen() {
}
/>
) : (
- <ListRow
+ <ChatRow
+ icon="steeringwheel"
title={item.report.title ?? "Untitled report"}
- label="Report"
- time={item.time}
+ snippet="Report"
onPress={() =>
router.push({
pathname: "/(drawer)/self-driving",
@@ -139,21 +205,33 @@ export default function RecentsScreen() {
paddingBottom: insets.bottom + 140,
paddingHorizontal: 18,
}}
+ ListHeaderComponent={
+ recentMode && items.length > 0 ? (
+ <Text style={styles.section}>Last opened</Text>
+ ) : null
+ }
onEndReached={() => {
- if (scope !== "reports" && tasks.hasNextPage && !tasks.isFetching) {
+ if (
+ !recentMode &&
+ scope !== "reports" &&
+ tasks.hasNextPage &&
+ !tasks.isFetching
+ ) {
void tasks.fetchNextPage();
}
}}
onEndReachedThreshold={0.5}
ListFooterComponent={
- tasks.isFetchingNextPage ? <RowSkeletons count={2} /> : null
+ tasks.isFetchingNextPage && !recentMode ? (
+ <RowSkeletons count={2} chat />
+ ) : null
}
keyboardDismissMode="on-drag"
keyboardShouldPersistTaps="handled"
/>
{loading && items.length === 0 ? (
<View style={[styles.overlay, { top }]} pointerEvents="none">
- <RowSkeletons />
+ <RowSkeletons chat />
</View>
) : null}
{!loading && items.length === 0 ? (
@@ -251,7 +329,6 @@ export default function RecentsScreen() {
onFocus={() => setSearching(true)}
placeholder="Search"
placeholderTextColor={colors.inkMute}
- autoFocus
autoCorrect={false}
returnKeyType="search"
clearButtonMode="while-editing"
@@ -303,6 +380,15 @@ const styles = StyleSheet.create({
transform: [{ rotate: "180deg" }],
},
overlay: { position: "absolute", left: 18, right: 18 },
+ section: {
+ fontFamily: fonts.sansSemi,
+ fontSize: 12,
+ letterSpacing: 1.2,
+ textTransform: "uppercase",
+ color: colors.inkMute,
+ paddingLeft: 4,
+ marginBottom: 4,
+ },
empty: {
position: "absolute",
left: 22,
diff --git a/products/desktop/apps/mobilehog/src/app/(drawer)/task/[id].tsx b/products/desktop/apps/mobilehog/src/app/(drawer)/task/[id].tsx
index db4b23c4f50d..d6e479f6b2c5 100644
--- a/products/desktop/apps/mobilehog/src/app/(drawer)/task/[id].tsx
+++ b/products/desktop/apps/mobilehog/src/app/(drawer)/task/[id].tsx
@@ -17,6 +17,7 @@ import {
} from "@/components/Transcript";
import type { Photo } from "@/lib/attachments";
import { useComposer } from "@/lib/composer";
+import { recordOpened } from "@/lib/openedChats";
import { usePrefs } from "@/lib/prefs";
import { useTask } from "@/lib/queries";
import { useSessions } from "@/lib/session";
@@ -42,6 +43,10 @@ export default function TaskScreen() {
const [pinRoom, setPinRoom] = useState(false);
const topPadding = insets.top + 70;
+ useEffect(() => {
+ if (!isPending) recordOpened(id);
+ }, [id, isPending]);
+
const runId = task.data?.latest_run?.id;
useEffect(() => {
if (task.data && runId) connect(task.data);
diff --git a/products/desktop/apps/mobilehog/src/components/TaskRow.tsx b/products/desktop/apps/mobilehog/src/components/TaskRow.tsx
index b002721393a1..93d87d15b0ca 100644
--- a/products/desktop/apps/mobilehog/src/components/TaskRow.tsx
+++ b/products/desktop/apps/mobilehog/src/components/TaskRow.tsx
@@ -1,13 +1,21 @@
-import { Button, ContextMenu, Host, RNHostView } from "@expo/ui/swift-ui";
+import {
+ Button,
+ ContextMenu,
+ Host,
+ Image,
+ type ImageProps,
+ RNHostView,
+} from "@expo/ui/swift-ui";
import { formatRelativeAge } from "@posthog/shared";
import type { Task } from "@posthog/shared/domain-types";
-import { useEffect } from "react";
+import { type ReactElement, useEffect } from "react";
import {
ActivityIndicator,
Alert,
Pressable,
StyleSheet,
Text,
+ useWindowDimensions,
View,
} from "react-native";
import Animated, {
@@ -95,16 +103,14 @@ export function useTaskActions(task: Task | undefined) {
return { rename, setArchived };
}
-export function TaskRow({
+function TaskMenu({
task,
- label,
- archived = false,
- onPress,
+ archived,
+ children,
}: {
task: Task;
- label?: string;
- archived?: boolean;
- onPress: () => void;
+ archived: boolean;
+ children: ReactElement;
}) {
const { rename, setArchived } = useTaskActions(task);
return (
@@ -127,28 +133,132 @@ export function TaskRow({
)}
</ContextMenu.Items>
<ContextMenu.Trigger>
- <RNHostView matchContents>
- <ListRow
- title={taskTitle(task)}
- label={label}
- time={activityAt(task)}
- running={isRunning(task)}
- onPress={onPress}
- />
- </RNHostView>
+ <RNHostView matchContents>{children}</RNHostView>
</ContextMenu.Trigger>
</ContextMenu>
</Host>
);
}
+export function TaskRow({
+ task,
+ label,
+ archived = false,
+ onPress,
+}: {
+ task: Task;
+ label?: string;
+ archived?: boolean;
+ onPress: () => void;
+}) {
+ return (
+ <TaskMenu task={task} archived={archived}>
+ <ListRow
+ title={taskTitle(task)}
+ label={label}
+ time={activityAt(task)}
+ running={isRunning(task)}
+ onPress={onPress}
+ />
+ </TaskMenu>
+ );
+}
+
+function oneLine(text: string): string {
+ return text.replace(/\s+/g, " ").trim();
+}
+
+// Titles made from the prompt repeat it, so the age stands in for the snippet.
+function taskSnippet(task: Task, title: string): string {
+ const snippet = oneLine(task.description_preview || task.description);
+ return snippet && !snippet.startsWith(oneLine(title))
+ ? snippet
+ : formatRelativeAge(activityAt(task));
+}
+
+// A fixed height, so the SwiftUI host around a row never has to catch up with
+// a title that wraps. Only the two text lines follow the text size setting.
+function useChatRowHeight(): number {
+ const { fontScale } = useWindowDimensions();
+ return Math.ceil(21 + 39 * fontScale);
+}
+
+export function ChatRow({
+ icon,
+ title,
+ snippet,
+ running = false,
+ onPress,
+}: {
+ icon: NonNullable<ImageProps["systemName"]>;
+ title: string;
+ snippet: string;
+ running?: boolean;
+ onPress: () => void;
+}) {
+ const height = useChatRowHeight();
+ return (
+ <Pressable
+ onPress={onPress}
+ style={({ pressed }) => [
+ styles.chatRow,
+ { height },
+ pressed && { opacity: 0.5 },
+ ]}
+ >
+ <View style={styles.chatIcon}>
+ <Host matchContents>
+ <Image systemName={icon} size={16} color={colors.inkSoft} />
+ </Host>
+ </View>
+ <View style={styles.body}>
+ <Text style={styles.chatTitle} numberOfLines={1}>
+ {title}
+ </Text>
+ <Text style={styles.chatSnippet} numberOfLines={1}>
+ {snippet}
+ </Text>
+ </View>
+ {running ? (
+ <ActivityIndicator size="small" color={colors.inkSoft} />
+ ) : null}
+ </Pressable>
+ );
+}
+
+export function TaskChatRow({
+ task,
+ archived = false,
+ onPress,
+}: {
+ task: Task;
+ archived?: boolean;
+ onPress: () => void;
+}) {
+ const title = taskTitle(task);
+ return (
+ <TaskMenu task={task} archived={archived}>
+ <ChatRow
+ icon="bubble.left"
+ title={title}
+ snippet={taskSnippet(task, title)}
+ running={isRunning(task)}
+ onPress={onPress}
+ />
+ </TaskMenu>
+ );
+}
+
const SKELETON_WIDTHS = ["72%", "54%", "86%", "62%", "78%"] as const;
export function RowSkeletons({
count = SKELETON_WIDTHS.length,
+ chat = false,
}: {
count?: number;
+ chat?: boolean;
}) {
+ const chatHeight = useChatRowHeight();
const opacity = useSharedValue(1);
useEffect(() => {
opacity.value = withRepeat(
@@ -161,7 +271,11 @@ export function RowSkeletons({
return (
<Animated.View style={pulse}>
{SKELETON_WIDTHS.slice(0, count).map((width) => (
- <View key={width} style={styles.row}>
+ <View
+ key={width}
+ style={chat ? [styles.chatRow, { height: chatHeight }] : styles.row}
+ >
+ {chat ? <View style={styles.chatIcon} /> : null}
<View style={styles.body}>
<View style={[styles.skeletonTitle, { width }]} />
<View style={styles.skeletonTime} />
@@ -189,6 +303,33 @@ const styles = StyleSheet.create({
color: colors.ink,
},
time: { fontFamily: fonts.sans, fontSize: 14, color: colors.inkSoft },
+ chatRow: {
+ flexDirection: "row",
+ alignItems: "center",
+ gap: 12,
+ paddingHorizontal: 4,
+ },
+ chatIcon: {
+ width: 36,
+ height: 36,
+ borderRadius: 10,
+ borderCurve: "continuous",
+ backgroundColor: colors.fill,
+ alignItems: "center",
+ justifyContent: "center",
+ },
+ chatTitle: {
+ fontFamily: fonts.sansMedium,
+ fontSize: 16,
+ lineHeight: 21,
+ color: colors.ink,
+ },
+ chatSnippet: {
+ fontFamily: fonts.sans,
+ fontSize: 14,
+ lineHeight: 18,
+ color: colors.inkMute,
+ },
skeletonTitle: {
height: 17,
marginVertical: 3,
diff --git a/products/desktop/apps/mobilehog/src/lib/openedChats.test.ts b/products/desktop/apps/mobilehog/src/lib/openedChats.test.ts
new file mode 100644
index 000000000000..85d6491fd676
--- /dev/null
+++ b/products/desktop/apps/mobilehog/src/lib/openedChats.test.ts
@@ -0,0 +1,132 @@
+import type { Task } from "@posthog/shared/domain-types";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+const mocks = vi.hoisted(() => {
+ const stores = new Map<string, Map<string, string>>();
+ const session = {
+ region: "us",
+ host: "https://us.posthog.com",
+ apiKey: "key",
+ projectId: 1,
+ projectName: "Project",
+ userId: 7,
+ userName: "Max",
+ };
+ const auth = { session: session as typeof session | null };
+
+ // One store per account, like accountStore in cache.ts.
+ function accountStore({ host, userId }: { host: string; userId: number }) {
+ const id = `${host}-${userId}`;
+ let data = stores.get(id);
+ if (!data) {
+ data = new Map();
+ stores.set(id, data);
+ }
+ const values = data;
+ return {
+ getString: (key: string) => values.get(key),
+ set: (key: string, value: string) => values.set(key, value),
+ };
+ }
+
+ return { accountStore, auth, session, stores };
+});
+
+vi.mock("@/lib/cache", () => ({ accountStore: mocks.accountStore }));
+vi.mock("@/lib/auth", () => ({
+ useAuth: { getState: () => mocks.auth },
+}));
+
+import { lastOpened, loadOpened, recordOpened } from "./openedChats";
+
+function task(id: string): Task {
+ return { id } as Task;
+}
+
+beforeEach(() => {
+ mocks.stores.clear();
+ mocks.auth.session = { ...mocks.session };
+});
+
+describe("opened chats", () => {
+ it("keeps the most recently opened first without duplicates", () => {
+ recordOpened("a");
+ recordOpened("b");
+ recordOpened("a");
+
+ expect(loadOpened()).toEqual(["a", "b"]);
+ });
+
+ it("keeps each project and account separate", () => {
+ recordOpened("a");
+ mocks.auth.session = { ...mocks.session, projectId: 2 };
+ recordOpened("b");
+ mocks.auth.session = { ...mocks.session, userId: 8 };
+ recordOpened("c");
+
+ expect(loadOpened()).toEqual(["c"]);
+ mocks.auth.session = { ...mocks.session, projectId: 2 };
+ expect(loadOpened()).toEqual(["b"]);
+ mocks.auth.session = { ...mocks.session };
+ expect(loadOpened()).toEqual(["a"]);
+ });
+
+ it("drops the oldest past the limit", () => {
+ for (let index = 0; index < 60; index++) recordOpened(`task-${index}`);
+
+ const opened = loadOpened();
+ expect(opened).toHaveLength(50);
+ expect(opened[0]).toBe("task-59");
+ expect(opened).not.toContain("task-9");
+ });
+
+ it("does nothing while signed out", () => {
+ mocks.auth.session = null;
+ recordOpened("a");
+ mocks.auth.session = { ...mocks.session };
+
+ expect(loadOpened()).toEqual([]);
+ });
+});
+
+describe("lastOpened", () => {
+ const recent = ["r1", "r2", "r3", "r4"].map(task);
+
+ it.each([
+ {
+ name: "fills with recent tasks after the opened ones",
+ opened: ["r3"],
+ limit: 3,
+ expected: ["r3", "r1", "r2"],
+ },
+ {
+ name: "skips opened ids whose task is gone",
+ opened: ["deleted", "r4"],
+ limit: 2,
+ expected: ["r4", "r1"],
+ },
+ {
+ name: "stops at the limit",
+ opened: ["r4", "r3", "r2"],
+ limit: 2,
+ expected: ["r4", "r3"],
+ },
+ {
+ name: "shows recent tasks when nothing was opened",
+ opened: [],
+ limit: 8,
+ expected: ["r1", "r2", "r3", "r4"],
+ },
+ {
+ name: "finds an opened task outside the recent page",
+ opened: ["old", "r2"],
+ known: ["old"],
+ limit: 3,
+ expected: ["old", "r2", "r1"],
+ },
+ ])("$name", ({ opened, known = [], limit, expected }) => {
+ expect(
+ lastOpened(opened, recent, known.map(task), limit).map(({ id }) => id),
+ ).toEqual(expected);
+ });
+});
diff --git a/products/desktop/apps/mobilehog/src/lib/openedChats.ts b/products/desktop/apps/mobilehog/src/lib/openedChats.ts
new file mode 100644
index 000000000000..aa4e7e89576d
--- /dev/null
+++ b/products/desktop/apps/mobilehog/src/lib/openedChats.ts
@@ -0,0 +1,63 @@
+import type { Task } from "@posthog/shared/domain-types";
+import type { MMKV } from "react-native-mmkv";
+import { useAuth } from "@/lib/auth";
+import { accountStore } from "@/lib/cache";
+
+const OPENED_LIMIT = 50;
+
+function openedScope(): { store: MMKV; key: string } | null {
+ const { session } = useAuth.getState();
+ if (!session) return null;
+ return {
+ store: accountStore(session),
+ key: `opened-${session.projectId}`,
+ };
+}
+
+function readOpened(store: MMKV, key: string): string[] {
+ try {
+ const order = JSON.parse(store.getString(key) ?? "[]");
+ return Array.isArray(order)
+ ? order.filter((item): item is string => typeof item === "string")
+ : [];
+ } catch {
+ return [];
+ }
+}
+
+export function recordOpened(taskId: string): void {
+ const scope = openedScope();
+ if (!scope) return;
+ const order = [
+ taskId,
+ ...readOpened(scope.store, scope.key).filter((id) => id !== taskId),
+ ];
+ scope.store.set(scope.key, JSON.stringify(order.slice(0, OPENED_LIMIT)));
+}
+
+// Task ids opened on this device, most recent first.
+export function loadOpened(): string[] {
+ const scope = openedScope();
+ return scope ? readOpened(scope.store, scope.key) : [];
+}
+
+// `known` holds opened tasks fetched outside the recent page. Opened ids with
+// no task are skipped, and recent tasks fill the rest so a fresh install still
+// shows something.
+export function lastOpened(
+ opened: string[],
+ recent: Task[],
+ known: Task[],
+ limit: number,
+): Task[] {
+ const byId = new Map([...recent, ...known].map((task) => [task.id, task]));
+ const picked = new Map<string, Task>();
+ for (const task of [
+ ...opened.flatMap((id) => byId.get(id) ?? []),
+ ...recent,
+ ]) {
+ if (picked.size === limit) break;
+ picked.set(task.id, task);
+ }
+ return [...picked.values()];
+}