: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(mobilehog): add a full report screen (#109528)
Dylan Martin82fe79ac3a73
diff --git a/products/desktop/apps/mobilehog/src/app/(drawer)/recents.tsx b/products/desktop/apps/mobilehog/src/app/(drawer)/recents.tsxindex d6f2c6a144b4..d9d7d0e3a32c 100644--- a/products/desktop/apps/mobilehog/src/app/(drawer)/recents.tsx+++ b/products/desktop/apps/mobilehog/src/app/(drawer)/recents.tsx@@ -193,8 +193,8 @@ export default function RecentsScreen() {snippet="Report"onPress={() =>router.push({- pathname: "/(drawer)/self-driving",- params: { report: item.id },+ pathname: "/report/[id]",+ params: { id: item.id },})}/>diff --git a/products/desktop/apps/mobilehog/src/app/(drawer)/self-driving.tsx b/products/desktop/apps/mobilehog/src/app/(drawer)/self-driving.tsxindex a070e5b77d2b..687d6deabeac 100644--- a/products/desktop/apps/mobilehog/src/app/(drawer)/self-driving.tsx+++ b/products/desktop/apps/mobilehog/src/app/(drawer)/self-driving.tsx@@ -1,8 +1,7 @@-import { buildCreatePrReportPrompt } from "@posthog/core/inbox/reportActions";import { formatRelativeAge } from "@posthog/shared";import type { SignalReport } from "@posthog/shared/domain-types";import * as Haptics from "expo-haptics";-import { useLocalSearchParams, useNavigation, useRouter } from "expo-router";+import { useNavigation, useRouter } from "expo-router";import { useEffect, useMemo, useState } from "react";import { Pressable, StyleSheet, Text, View } from "react-native";import Animated, {@@ -22,9 +21,8 @@ import {useDismissReport,useReports,useSeenReports,- useStartReport,+ useStartReportTask,} from "@/lib/reports";-import { useSessions } from "@/lib/session";import { colors, fonts, radius } from "@/lib/theme";export default function SelfDrivingScreen() {@@ -36,14 +34,10 @@ export default function SelfDrivingScreen() {const seenHydrated = useSeenReports((s) => s.hydrated);const markSeen = useSeenReports((s) => s.markSeen);const dismiss = useDismissReport();- const start = useStartReport();+ const startTask = useStartReportTask();// Locally swiped ids, so a card leaves the deck before the server catches up.const [handled, setHandled] = useState<Set<string>>(new Set());const [deck, setDeck] = useState<string[] | null>(null);- const { report: linkedReport } = useLocalSearchParams<{ report?: string }>();- useEffect(() => {- if (linkedReport) setDeck([linkedReport]);- }, [linkedReport]);const [notice, setNotice] = useState<string | null>(null);useEffect(() => {if (!notice) return;@@ -107,31 +101,16 @@ export default function SelfDrivingScreen() {});};- // Open the chat immediately with the report prompt in it (the same pending- // pattern as the new-chat screen), then re-key it to the real task id.const onStart = (report: SignalReport): void => {Haptics.notificationAsync(Haptics.NotificationFeedbackType.Success).catch(() => {},);finish(report);- const tempId = `new-${Date.now()}`;- const prompt = buildCreatePrReportPrompt({ reportId: report.id });- const { startPending, adopt, failPending } = useSessions.getState();- startPending(tempId, prompt, `local-${Date.now()}`);- router.push({ pathname: "/(drawer)/task/[id]", params: { id: tempId } });- start.mutate(report, {- onSuccess: (task) => {- adopt(tempId, task);- router.replace({- pathname: "/(drawer)/task/[id]",- params: { id: task.id },- });- },- onError: (error) => {- restore(report);- failPending(tempId, error.message);- },- });+ startTask.start(report, router.push).catch(() => restore(report));+ };++ const openReport = (report: SignalReport): void => {+ router.push({ pathname: "/report/[id]", params: { id: report.id } });};const showDeck = deck !== null && deckReports.length > 0;@@ -164,7 +143,8 @@ export default function SelfDrivingScreen() {reports={deckReports}onDismiss={onDismiss}onStart={onStart}- starting={start.isPending}+ onOpen={openReport}+ starting={startTask.isPending}headerHeight={headerHeight}/></Animated.View>@@ -185,7 +165,7 @@ export default function SelfDrivingScreen() {{all.map((report) => (<Pressablekey={report.id}- onPress={() => setDeck([report.id])}+ onPress={() => openReport(report)}style={({ pressed }) => [styles.row, pressed && { opacity: 0.5 }]}>{report.priority ? (diff --git a/products/desktop/apps/mobilehog/src/app/_layout.tsx b/products/desktop/apps/mobilehog/src/app/_layout.tsxindex 2b5dd951898a..91207b45fb6c 100644--- a/products/desktop/apps/mobilehog/src/app/_layout.tsx+++ b/products/desktop/apps/mobilehog/src/app/_layout.tsx@@ -16,7 +16,7 @@ import { usePrefs } from "@/lib/prefs";import { useRepo } from "@/lib/repo";import { useSeenReports } from "@/lib/reports";import { useSessions } from "@/lib/session";-import { colors } from "@/lib/theme";+import { colors, fonts } from "@/lib/theme";SplashScreen.preventAutoHideAsync().catch(() => {});@@ -89,6 +89,18 @@ export default function RootLayout() {><Stack.Screen name="login" options={{ animation: "fade" }} /><Stack.Screen name="(drawer)" />+ <Stack.Screen+ name="report/[id]"+ options={{+ headerShown: true,+ title: "Report",+ headerBackButtonDisplayMode: "minimal",+ headerShadowVisible: false,+ headerTintColor: colors.ink,+ headerStyle: { backgroundColor: colors.bg },+ headerTitleStyle: { fontFamily: fonts.sansSemi },+ }}+ /><Stack.Screenname="config"options={{diff --git a/products/desktop/apps/mobilehog/src/app/report/[id].tsx b/products/desktop/apps/mobilehog/src/app/report/[id].tsxnew file mode 100644index 000000000000..62cd91a77a56--- /dev/null+++ b/products/desktop/apps/mobilehog/src/app/report/[id].tsx@@ -0,0 +1,127 @@+import { canCreateImplementationPr } from "@posthog/core/inbox/reportActions";+import { isDismissedReport } from "@posthog/core/inbox/reportMembership";+import * as Haptics from "expo-haptics";+import { router, useLocalSearchParams } from "expo-router";+import { useEffect } from "react";+import { Pressable, StyleSheet, Text, View } from "react-native";+import { useSafeAreaInsets } from "react-native-safe-area-context";+import { Glass } from "@/components/Glass";+import { CardButton, ReportDetail } from "@/components/ReportCard";+import {+ useDismissReport,+ useHasLiveImplementationTask,+ useReport,+ useSeenReports,+ useStartReportTask,+} from "@/lib/reports";+import { colors, fonts, radius } from "@/lib/theme";++export default function ReportScreen() {+ const { id } = useLocalSearchParams<{ id: string }>();+ const insets = useSafeAreaInsets();+ const { data: report, isLoading } = useReport(id);+ 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 reportId = report?.id;+ useEffect(() => {+ if (reportId && seenHydrated && !isSeen) {+ markSeen([reportId]).catch(() => {});+ }+ }, [reportId, seenHydrated, isSeen, markSeen]);++ if (!report) {+ return (+ <View style={styles.root}>+ <Text style={styles.muted}>+ {isLoading ? "Loading" : "This report is not available."}+ </Text>+ </View>+ );+ }++ const canDismiss = !isDismissedReport(report);+ const canStart = canCreateImplementationPr(report, {+ hasLiveImplementationTask: liveTask.data === true,+ // Unknown task state must not offer a second task on live work.+ isTaskLookupPending: liveTask.isPending || liveTask.isError,+ });+ const taskCheckFailed = liveTask.isError && canCreateImplementationPr(report);++ const onDismiss = (): void => {+ Haptics.impactAsync(Haptics.ImpactFeedbackStyle.Rigid).catch(() => {});+ dismiss.mutate(report.id, { onSuccess: () => router.back() });+ };++ // Pop back to the drawer and open the task there, so the report does not+ // stay under the chat.+ const onStart = (): void => {+ Haptics.notificationAsync(Haptics.NotificationFeedbackType.Success).catch(+ () => {},+ );+ startTask.start(report, router.dismissTo).catch(() => {});+ };++ return (+ <View style={styles.root}>+ <ReportDetail report={report} />+ {canDismiss || canStart || taskCheckFailed ? (+ <View style={[styles.actions, { paddingBottom: insets.bottom + 12 }]}>+ {dismiss.isError ? (+ <Text style={styles.error}>Could not dismiss. Try again.</Text>+ ) : null}+ {taskCheckFailed ? (+ <Pressable+ disabled={liveTask.isFetching}+ onPress={() => liveTask.refetch()}+ >+ <Text style={styles.error}>+ Could not check task status. Tap to try again.+ </Text>+ </Pressable>+ ) : null}+ <Glass style={styles.actionsGlass} tint={colors.glassTint}>+ {canDismiss ? (+ <CardButton+ label="Dismiss"+ disabled={dismiss.isPending}+ onPress={onDismiss}+ />+ ) : null}+ {canStart ? (+ <CardButton+ label="Start task"+ primary+ disabled={startTask.isPending}+ onPress={onStart}+ />+ ) : null}+ </Glass>+ </View>+ ) : null}+ </View>+ );+}++const styles = StyleSheet.create({+ root: { flex: 1, paddingHorizontal: 20, paddingTop: 12 },+ muted: { fontFamily: fonts.sans, fontSize: 14, color: colors.inkMute },+ actions: { position: "absolute", left: 16, right: 16, bottom: 0, gap: 8 },+ actionsGlass: {+ flexDirection: "row",+ gap: 8,+ padding: 10,+ borderRadius: radius.pill,+ overflow: "hidden",+ },+ error: {+ alignSelf: "center",+ fontFamily: fonts.sans,+ fontSize: 13,+ color: colors.inkMute,+ },+});diff --git a/products/desktop/apps/mobilehog/src/components/TriageDeck.tsx b/products/desktop/apps/mobilehog/src/components/TriageDeck.tsxindex 71dc9e31db41..306a81d4b83a 100644--- a/products/desktop/apps/mobilehog/src/components/TriageDeck.tsx+++ b/products/desktop/apps/mobilehog/src/components/TriageDeck.tsx@@ -1,13 +1,7 @@import type { SignalReport } from "@posthog/shared/domain-types";import * as Haptics from "expo-haptics";import { useState } from "react";-import {- Image,- StyleSheet,- Text,- useWindowDimensions,- View,-} from "react-native";+import { Image, StyleSheet, Text, View } from "react-native";import { Gesture, GestureDetector } from "react-native-gesture-handler";import Animated, {FadeInDown,@@ -19,13 +13,9 @@ import Animated, {withTiming,} from "react-native-reanimated";import { useSafeAreaInsets } from "react-native-safe-area-context";-import { Glass, GlassCircleButton } from "@/components/Glass";+import { GlassCircleButton } from "@/components/Glass";import { BinIcon } from "@/components/Icons";-import {- CardButton,- ReportDetail,- ReportSummary,-} from "@/components/ReportCard";+import { CardButton, ReportSummary } from "@/components/ReportCard";import { colors, fonts, radius } from "@/lib/theme";const SWIPE_THRESHOLD = 110;@@ -38,27 +28,26 @@ interface TriageDeckProps {reports: SignalReport[];onDismiss: (report: SignalReport) => void;onStart: (report: SignalReport) => void;+ onOpen: (report: SignalReport) => void;starting?: boolean;// Height of the screen header the deck sits under; the frame starts below it.headerHeight: number;}// Tinder-style stack: swipe left to dismiss, right to start a task, or open-// the card in place to read the whole report before deciding.+// the report to read all of it before deciding.export function TriageDeck({reports,onDismiss,onStart,+ onOpen,starting,headerHeight,}: TriageDeckProps) {- const { width, height } = useWindowDimensions();const insets = useSafeAreaInsets();- const [expanded, setExpanded] = useState(false);const [frame, setFrame] = useState({ x: 0, y: 0, w: 0, h: 0 });const x = useSharedValue(0);const y = useSharedValue(0);- const grow = useSharedValue(0);const top = reports[0];const rest = reports.slice(1, 3);@@ -78,7 +67,7 @@ export function TriageDeck({};const pan = Gesture.Pan()- .enabled(!expanded && !!top)+ .enabled(!!top).activeOffsetX([-12, 12]).failOffsetY([-16, 16]).onChange((event) => {@@ -96,26 +85,7 @@ export function TriageDeck({}});- const toggleExpanded = (): void => {- const next = !expanded;- setExpanded(next);- // Critically damped and quick, like a UIKit sheet, no bounce.- grow.value = withSpring(next ? 1 : 0, {- duration: 380,- dampingRatio: 1,- overshootClamping: true,- });- };-- // The top card lives in a fixed frame; expanding animates that frame out to- // the full screen so the report opens from where the card sits.const topStyle = useAnimatedStyle(() => ({- position: "absolute",- left: interpolate(grow.value, [0, 1], [frame.x, 0]),- top: interpolate(grow.value, [0, 1], [frame.y, 0]),- width: interpolate(grow.value, [0, 1], [frame.w, width]),- height: interpolate(grow.value, [0, 1], [frame.h - STACK_PEEK, height]),- borderRadius: interpolate(grow.value, [0, 1], [CARD_RADIUS, 0]),transform: [{ translateX: x.value },{ translateY: y.value },@@ -128,15 +98,6 @@ export function TriageDeck({const dismissHint = useAnimatedStyle(() => ({opacity: interpolate(x.value, [-SWIPE_THRESHOLD, -20], [1, 0], "clamp"),}));- // The overlay clips itself, since the card no longer does (its shadow needs- // to escape).- const detailStyle = useAnimatedStyle(() => ({- opacity: interpolate(grow.value, [0.6, 1], [0, 1], "clamp"),- borderRadius: interpolate(grow.value, [0, 1], [CARD_RADIUS, 0]),- }));- const faceStyle = useAnimatedStyle(() => ({- opacity: interpolate(grow.value, [0, 0.4], [1, 0], "clamp"),- }));return (<View style={styles.root} pointerEvents="box-none">@@ -178,15 +139,22 @@ export function TriageDeck({<GestureDetector gesture={pan}><Animated.Viewentering={FadeInDown.duration(280)}- style={[styles.card, styles.topCard, topStyle]}+ style={[+ styles.card,+ styles.topCard,+ {+ left: frame.x,+ top: frame.y,+ width: frame.w,+ height: frame.h - STACK_PEEK,+ },+ topStyle,+ ]}>- <Animated.View- style={[styles.face, faceStyle]}- pointerEvents={expanded ? "none" : "auto"}- >+ <View style={styles.face}><ReportSummary report={top} withEvidence /><View style={styles.actions}>- <CardButton label="Open report" onPress={toggleExpanded} />+ <CardButton label="Open report" onPress={() => onOpen(top)} /></View><Animated.View style={[styles.hint, styles.hintStart, startHint]}><Text style={styles.hintText}>Start</Text>@@ -196,91 +164,41 @@ export function TriageDeck({><Text style={styles.hintText}>Dismiss</Text></Animated.View>- </Animated.View>- {expanded ? (- <Animated.View- style={[- StyleSheet.absoluteFill,- styles.detail,- { paddingTop: insets.top + 64 },- detailStyle,- ]}- >- <ReportDetail report={top} />- <View style={[styles.detailHeader, { top: insets.top + 6 }]}>- <GlassCircleButton- onPress={toggleExpanded}- tint={colors.glassTint}- >- <Text style={styles.close}>×</Text>- </GlassCircleButton>- </View>- <View- style={[- styles.detailActions,- { paddingBottom: insets.bottom + 12 },- ]}- >- <Glass- style={styles.detailActionsGlass}- tint={colors.glassTint}- >- <CardButton- label="Dismiss"- onPress={() => {- toggleExpanded();- setTimeout(() => flyOut(-1, top), 250);- }}- />- <CardButton- label="Start task"- primary- disabled={starting}- onPress={() => {- toggleExpanded();- setTimeout(() => flyOut(1, top), 250);- }}- />- </Glass>- </View>- </Animated.View>- ) : null}+ </View></Animated.View></GestureDetector>) : null}{/* Glass never renders when mounted inside a layout animation, so thefooter stays out of the deck's entering fade. */}- {!expanded ? (- <View style={[styles.footer, { paddingBottom: insets.bottom + 8 }]}>- <View style={styles.verdict}>- <GlassCircleButton- size={64}- disabled={!top}- onPress={() => swipe(-1)}- >- <BinIcon />- </GlassCircleButton>- <Text style={styles.caption}>Dismiss</Text>- </View>- <Text style={styles.counter}>{reports.length} to triage</Text>- <View style={styles.verdict}>- <GlassCircleButton- size={64}- disabled={!top || starting}- onPress={() => swipe(1)}- >- <View style={styles.goClip}>- <Image- source={require("../../assets/hedgehog/idle-strip.png")}- style={styles.goSprite}- />- </View>- </GlassCircleButton>- <Text style={styles.caption}>Start task</Text>- </View>+ <View style={[styles.footer, { paddingBottom: insets.bottom + 8 }]}>+ <View style={styles.verdict}>+ <GlassCircleButton+ size={64}+ disabled={!top}+ onPress={() => swipe(-1)}+ >+ <BinIcon />+ </GlassCircleButton>+ <Text style={styles.caption}>Dismiss</Text></View>- ) : null}+ <Text style={styles.counter}>{reports.length} to triage</Text>+ <View style={styles.verdict}>+ <GlassCircleButton+ size={64}+ disabled={!top || starting}+ onPress={() => swipe(1)}+ >+ <View style={styles.goClip}>+ <Image+ source={require("../../assets/hedgehog/idle-strip.png")}+ style={styles.goSprite}+ />+ </View>+ </GlassCircleButton>+ <Text style={styles.caption}>Start task</Text>+ </View>+ </View></View>);}@@ -298,7 +216,7 @@ const styles = StyleSheet.create({shadowOffset: { width: 0, height: 14 },},behind: { position: "absolute", top: 0, left: 0, right: 0 },- topCard: { justifyContent: "space-between" },+ topCard: { position: "absolute", justifyContent: "space-between" },face: { flex: 1, justifyContent: "space-between" },actions: { flexDirection: "row", gap: 8, marginTop: 16 },hint: {@@ -311,21 +229,6 @@ const styles = StyleSheet.create({hintStart: { left: 0, backgroundColor: colors.ok },hintDismiss: { right: 0, backgroundColor: colors.inkMute },hintText: { fontFamily: fonts.sansBold, fontSize: 13, color: "#FFFFFF" },- detail: {- backgroundColor: colors.bgRaised,- paddingHorizontal: 20,- overflow: "hidden",- },- detailHeader: { position: "absolute", left: 16 },- detailActions: { position: "absolute", left: 16, right: 16, bottom: 0 },- detailActionsGlass: {- flexDirection: "row",- gap: 8,- padding: 10,- borderRadius: radius.pill,- overflow: "hidden",- },- close: { fontSize: 26, lineHeight: 28, color: colors.ink, marginTop: -2 },footer: {flexDirection: "row",alignItems: "center",diff --git a/products/desktop/apps/mobilehog/src/lib/reportTasks.test.ts b/products/desktop/apps/mobilehog/src/lib/reportTasks.test.tsnew file mode 100644index 000000000000..5cf6c0ba21ea--- /dev/null+++ b/products/desktop/apps/mobilehog/src/lib/reportTasks.test.ts@@ -0,0 +1,131 @@+import { ApiRequestError } from "@posthog/api-client/fetcher";+import type {+ SignalReportArtefactsResponse,+ Task,+} from "@posthog/shared/domain-types";+import { describe, expect, it, vi } from "vitest";+import {+ fetchHasLiveImplementationTask,+ implementationTaskIds,+ isLiveImplementationTask,+} from "./reportTasks";++function taskRun(taskId: string, type: string, product = "signals") {+ return {+ id: `artefact-${taskId}-${type}`,+ type: "task_run",+ created_at: "2026-01-01T00:00:00Z",+ content: { task_id: taskId, product, type },+ };+}++function artefacts(+ results: ReturnType<typeof taskRun>[],+): SignalReportArtefactsResponse {+ return {+ results,+ count: results.length,+ } as unknown as SignalReportArtefactsResponse;+}++function task(+ id: string,+ status: string | null,+ output: Record<string, unknown> | null = null,+): Task {+ return {+ id,+ latest_run: status === null ? undefined : { status, output },+ } as unknown as Task;+}++describe("implementationTaskIds", () => {+ it("keeps only signals implementation runs, once per task", () => {+ expect(+ implementationTaskIds(+ artefacts([+ taskRun("a", "implementation"),+ taskRun("a", "implementation"),+ taskRun("b", "research"),+ taskRun("c", "implementation", "custom"),+ taskRun("d", "implementation"),+ ]),+ ),+ ).toEqual(["a", "d"]);+ });+});++describe("isLiveImplementationTask", () => {+ it.each([+ ["a running run", task("t", "in_progress"), true],+ ["a failed run with no PR", task("t", "failed"), false],+ ["a task with no run", task("t", null), false],+ [+ "a finished run with an open PR",+ task("t", "completed", { pr_url: "https://github.com/o/r/pull/1" }),+ true,+ ],+ [+ "a merged PR",+ task("t", "completed", {+ pr_url: "https://github.com/o/r/pull/1",+ pr_state: "merged",+ }),+ false,+ ],+ [+ "a legacy merged PR",+ task("t", "completed", {+ pr_url: "https://github.com/o/r/pull/1",+ pr_merged: true,+ }),+ false,+ ],+ ])("%s", (_label, value, expected) => {+ expect(isLiveImplementationTask(value)).toBe(expected);+ });+});++describe("fetchHasLiveImplementationTask", () => {+ function client(tasks: Record<string, Task | Error>) {+ return {+ getSignalReportArtefacts: vi+ .fn()+ .mockResolvedValue(+ artefacts(+ Object.keys(tasks).map((id) => taskRun(id, "implementation")),+ ),+ ),+ getTask: vi.fn((id: string) => {+ const value = tasks[id];+ return value instanceof Error+ ? Promise.reject(value)+ : Promise.resolve(value);+ }),+ };+ }++ it("is true when one linked task is live", async () => {+ const c = client({+ a: task("a", "failed"),+ b: task("b", "in_progress"),+ });+ await expect(fetchHasLiveImplementationTask(c, "r")).resolves.toBe(true);+ expect(c.getSignalReportArtefacts).toHaveBeenCalledWith("r", {+ limit: 1000,+ });+ });++ it("skips a deleted task", async () => {+ const c = client({+ a: new ApiRequestError(404, "not found"),+ b: task("b", "completed"),+ });+ await expect(fetchHasLiveImplementationTask(c, "r")).resolves.toBe(false);+ });++ it("fails when a task lookup fails for another reason", async () => {+ const c = client({ a: new ApiRequestError(500, "boom") });+ await expect(fetchHasLiveImplementationTask(c, "r")).rejects.toThrow();+ });+});diff --git a/products/desktop/apps/mobilehog/src/lib/reportTasks.ts b/products/desktop/apps/mobilehog/src/lib/reportTasks.tsnew file mode 100644index 000000000000..22d1cc4aa66a--- /dev/null+++ b/products/desktop/apps/mobilehog/src/lib/reportTasks.ts@@ -0,0 +1,62 @@+import { requestErrorStatus } from "@posthog/api-client/fetcher";+import type { PostHogAPIClient } from "@posthog/api-client/posthog-client";+import {+ isTerminalStatus,+ type SignalReportArtefactsResponse,+ type Task,+ type TaskRunArtefactContent,+} from "@posthog/shared/domain-types";++type ReportTaskClient = Pick<+ PostHogAPIClient,+ "getSignalReportArtefacts" | "getTask"+>;++export function implementationTaskIds(+ artefacts: SignalReportArtefactsResponse,+): string[] {+ const ids = new Set<string>();+ for (const artefact of artefacts.results) {+ if (artefact.type !== "task_run") continue;+ const content = artefact.content as TaskRunArtefactContent;+ if (content.product === "signals" && content.type === "implementation") {+ ids.add(content.task_id);+ }+ }+ return [...ids];+}++// Live work is a run still going, or a PR that has not merged yet. Starting+// another task on top of it would open a duplicate PR.+export function isLiveImplementationTask(task: Task): boolean {+ const run = task.latest_run;+ if (!run) return false;+ const prUrl = run.output?.pr_url;+ if (typeof prUrl === "string" && prUrl.length > 0) {+ return run.output?.pr_state !== "merged" && run.output?.pr_merged !== true;+ }+ return !isTerminalStatus(run.status);+}++export async function fetchHasLiveImplementationTask(+ client: ReportTaskClient,+ reportId: string,+): Promise<boolean> {+ // The whole log: a default page can drop the task_run rows.+ const artefacts = await client.getSignalReportArtefacts(reportId, {+ limit: 1000,+ });+ const tasks = await Promise.all(+ implementationTaskIds(artefacts).map((id) =>+ // A deleted task leaves its artefact behind. Skip it, but fail on any+ // other error so unknown state does not read as "no live work".+ client+ .getTask(id)+ .catch((error: unknown) => {+ if (requestErrorStatus(error) === 404) return null;+ throw error;+ }),+ ),+ );+ return tasks.some((task) => task !== null && isLiveImplementationTask(task));+}diff --git a/products/desktop/apps/mobilehog/src/lib/reports.ts b/products/desktop/apps/mobilehog/src/lib/reports.tsindex 1a24706d7547..de7d3969cd11 100644--- a/products/desktop/apps/mobilehog/src/lib/reports.ts+++ b/products/desktop/apps/mobilehog/src/lib/reports.ts@@ -10,19 +10,30 @@ import type {SignalReport,SignalReportArtefactsResponse,SignalReportSignalsResponse,+ SignalReportsResponse,} from "@posthog/shared/domain-types";-import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";+import {+ type QueryClient,+ useMutation,+ 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 { getClient } from "@/lib/client";import { currentRunConfig } from "@/lib/composer";+import { fetchHasLiveImplementationTask } from "@/lib/reportTasks";+import { useSessions } from "@/lib/session";export const reportKeys = {all: ["reports"] as const,list: ["reports", "list"] as const,+ detail: (id: string) => ["reports", "detail", 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,};// Reports a person can act on right now, highest priority first.@@ -45,6 +56,31 @@ export function useReports(search = "") {});}+// Seeded from whichever list already holds the report, so the screen opens+// with content and refreshes behind it.+export function useReport(reportId: string) {+ const queryClient = useQueryClient();+ const cached = () => {+ for (const [key, page] of queryClient.getQueriesData<SignalReportsResponse>(+ { queryKey: reportKeys.list },+ )) {+ const report = page?.results.find((item) => item.id === reportId);+ if (report) return { report, key };+ }+ return undefined;+ };+ return useQuery({+ queryKey: reportKeys.detail(reportId),+ queryFn: () => getClient().getSignalReport(reportId),+ enabled: !!reportId,+ initialData: () => cached()?.report,+ initialDataUpdatedAt: () => {+ const key = cached()?.key;+ return key ? queryClient.getQueryState(key)?.dataUpdatedAt : undefined;+ },+ });+}+export function useReportSignals(reportId: string | null) {return useQuery<SignalReportSignalsResponse>({queryKey: reportKeys.signals(reportId ?? ""),@@ -63,11 +99,37 @@ export function useReportArtefacts(reportId: string | null) {});}+export function useHasLiveImplementationTask(reportId: string) {+ return useQuery({+ queryKey: reportKeys.liveTask(reportId),+ queryFn: () => fetchHasLiveImplementationTask(getClient(), reportId),+ enabled: !!reportId,+ });+}++// Takes an acted-on report out of every loaded list at once, wherever the+// action came from. A failed action refetches and brings it back.+async function dropFromLists(+ queryClient: QueryClient,+ reportId: string,+): Promise<void> {+ await queryClient.cancelQueries({ queryKey: reportKeys.list });+ queryClient.setQueriesData<SignalReportsResponse>(+ { queryKey: reportKeys.list },+ (page) =>+ page && {+ ...page,+ results: page.results.filter((report) => report.id !== reportId),+ },+ );+}+export function useDismissReport() {const queryClient = useQueryClient();return useMutation({mutationFn: (reportId: string) =>getClient().updateSignalReportState(reportId, { state: "suppressed" }),+ onMutate: (reportId) => dropFromLists(queryClient, reportId),onSettled: () =>queryClient.invalidateQueries({ queryKey: reportKeys.all }),});@@ -90,6 +152,9 @@ export function useStartReport() {const prompt = buildCreatePrReportPrompt({ reportId: report.id });let taskId = unstartedTasks.get(report.id);if (!taskId) {+ if (await fetchHasLiveImplementationTask(client, report.id)) {+ throw new Error("This report already has a task in progress.");+ }// The server picks the repository from the report's repo selection.const task = await client.createTask({description: prompt,@@ -110,6 +175,7 @@ export function useStartReport() {unstartedTasks.delete(report.id);return started;},+ onMutate: (report) => dropFromLists(queryClient, report.id),onSettled: () => {queryClient.invalidateQueries({ queryKey: reportKeys.all });queryClient.invalidateQueries({ queryKey: ["tasks"] });@@ -117,6 +183,37 @@ export function useStartReport() {});}+// Opens the chat at once with the report prompt in it (the same pending+// pattern as the new-chat screen), then re-keys it to the real task id.+export function useStartReportTask() {+ const start = useStartReport();+ const run = (+ report: SignalReport,+ open: (href: Href) => void,+ ): Promise<void> => {+ const tempId = `new-${Date.now()}`;+ const prompt = buildCreatePrReportPrompt({ reportId: report.id });+ const { startPending, adopt, failPending } = useSessions.getState();+ startPending(tempId, prompt, `local-${Date.now()}`);+ open({ pathname: "/(drawer)/task/[id]", params: { id: tempId } });+ // mutateAsync, not mutate callbacks: the caller may unmount on navigation.+ return start.mutateAsync(report).then(+ (task) => {+ adopt(tempId, task);+ router.replace({+ pathname: "/(drawer)/task/[id]",+ params: { id: task.id },+ });+ },+ (error: Error) => {+ failPending(tempId, error.message);+ throw error;+ },+ );+ };+ 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";