: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): keep sent photos visible after a chat reloads (#109527)
Dylan Martin7d5bae8bbe32
diff --git a/products/desktop/apps/mobilehog/src/app/(drawer)/task/[id].tsx b/products/desktop/apps/mobilehog/src/app/(drawer)/task/[id].tsxindex d6e479f6b2c5..f08608a70dd9 100644--- a/products/desktop/apps/mobilehog/src/app/(drawer)/task/[id].tsx+++ b/products/desktop/apps/mobilehog/src/app/(drawer)/task/[id].tsx@@ -126,6 +126,7 @@ export default function TaskScreen() {renderItem={({ item }) => (<TranscriptRowViewrow={item}+ taskId={id}onPermission={(toolCallId, optionId) =>respondToPermission(id, toolCallId, optionId)}diff --git a/products/desktop/apps/mobilehog/src/components/Transcript.tsx b/products/desktop/apps/mobilehog/src/components/Transcript.tsxindex eae43c69c526..f3008107558d 100644--- a/products/desktop/apps/mobilehog/src/components/Transcript.tsx+++ b/products/desktop/apps/mobilehog/src/components/Transcript.tsx@@ -1,3 +1,4 @@+import { Host, Image as SymbolImage } from "@expo/ui/swift-ui";import { memo, useEffect, useState } from "react";import {ActivityIndicator,@@ -13,9 +14,16 @@ import { Glass } from "@/components/Glass";import { Markdown } from "@/components/Markdown";import { appResourceUri, McpAppHost } from "@/components/McpAppHost";import { ShimmerText } from "@/components/ShimmerText";+import { sentPhotoUri } from "@/lib/attachments";+import { usePhotoUrl } from "@/lib/queries";import type { TaskSession } from "@/lib/session";import { colors, fonts, radius } from "@/lib/theme";-import type { Block, PermissionRequest, ToolStatus } from "@/lib/transcript";+import type {+ Block,+ PermissionRequest,+ PhotoRef,+ ToolStatus,+} from "@/lib/transcript";interface TranscriptProps {onPermission: (toolCallId: string, optionId: string) => void;@@ -130,14 +138,16 @@ export function buildTranscriptRows(export const TranscriptRowView = memo(function TranscriptRowView({row,+ taskId,onPermission,}: {row: TranscriptRow;+ taskId: string;onPermission: TranscriptProps["onPermission"];}) {switch (row.kind) {case "block":- return <BlockView block={row.block} />;+ return <BlockView block={row.block} taskId={taskId} />;case "app":return <McpAppHost block={row.block} />;case "activity":@@ -185,12 +195,69 @@ export const TranscriptRowView = memo(},);-function BlockView({ block }: { block: Block }) {+// Shows the file on disk when this device sent it, else a download URL.+function SentPhoto({+ taskId,+ photo,+ savedUri,+}: {+ taskId: string;+ photo: PhotoRef;+ savedUri?: string;+}) {+ const localUri = sentPhotoUri(taskId, photo.artifactId) ?? savedUri;+ const [localFailed, setLocalFailed] = useState(false);+ const [failedUri, setFailedUri] = useState<string | null>(null);+ const showLocal = !!localUri && !localFailed;+ const remote = usePhotoUrl(taskId, showLocal ? null : photo);+ const uri = showLocal ? localUri : remote.data;+ // The failure belongs to one URL, so a refreshed URL loads the photo again.+ if (uri ? uri === failedUri : remote.isError) {+ return (+ <View+ accessibilityLabel={photo.name}+ style={[styles.userImage, styles.userImageMissing]}+ >+ <Host matchContents>+ <SymbolImage systemName="photo" size={20} color={colors.inkMute} />+ </Host>+ </View>+ );+ }+ if (!uri) return <View style={styles.userImage} />;+ return (+ <Image+ source={{ uri }}+ accessibilityLabel={photo.name}+ style={styles.userImage}+ onError={() => (showLocal ? setLocalFailed(true) : setFailedUri(uri))}+ />+ );+}++function BlockView({ block, taskId }: { block: Block; taskId: string }) {switch (block.kind) {- case "user":+ case "user": {+ // A saved chat keeps the picker URIs in photo order, and they outlive+ // the in-memory list of sent photos when the app restarts.+ const savedUris =+ block.images?.length === block.photos?.length+ ? block.images+ : undefined;return (<View style={styles.userRow}>- {block.images?.length ? (+ {block.photos?.length ? (+ <View style={styles.userImages}>+ {block.photos.map((photo, index) => (+ <SentPhoto+ key={photo.artifactId}+ taskId={taskId}+ photo={photo}+ savedUri={savedUris?.[index]}+ />+ ))}+ </View>+ ) : block.images?.length ? (<View style={styles.userImages}>{block.images.map((uri) => (<Image key={uri} source={{ uri }} style={styles.userImage} />@@ -206,6 +273,7 @@ function BlockView({ block }: { block: Block }) {) : null}</View>);+ }case "agent":return (<View style={styles.agentRow}>@@ -559,6 +627,10 @@ const styles = StyleSheet.create({borderRadius: 16,backgroundColor: colors.fill,},+ userImageMissing: {+ alignItems: "center",+ justifyContent: "center",+ },userBubble: {maxWidth: "84%",backgroundColor: colors.dark,diff --git a/products/desktop/apps/mobilehog/src/lib/accountLifecycle.ts b/products/desktop/apps/mobilehog/src/lib/accountLifecycle.tsindex 5d1e482d6c0f..d1b18dd17414 100644--- a/products/desktop/apps/mobilehog/src/lib/accountLifecycle.ts+++ b/products/desktop/apps/mobilehog/src/lib/accountLifecycle.ts@@ -1,4 +1,5 @@import { QueryClient } from "@tanstack/react-query";+import { resetSentPhotos } from "@/lib/attachments";import { sessionIdentity, useAuth } from "@/lib/auth";import {CACHE_MAX_AGE,@@ -43,6 +44,7 @@ useAuth.subscribe((state, previous) => {useRepo.setState({ repository: undefined });useSeenReports.setState({ seen: new Set(), hydrated: false });resetUnstartedReportTasks();+ resetSentPhotos();});export function getAccountQueryClient(): QueryClient {diff --git a/products/desktop/apps/mobilehog/src/lib/attachments.test.ts b/products/desktop/apps/mobilehog/src/lib/attachments.test.tsindex c98fb3d06389..972118194f24 100644--- a/products/desktop/apps/mobilehog/src/lib/attachments.test.ts+++ b/products/desktop/apps/mobilehog/src/lib/attachments.test.ts@@ -27,10 +27,23 @@ vi.mock("expo-image-picker", () => ({}));vi.mock("@/lib/client", () => ({ getClient: () => mocks.client }));-import { uploadStagedPhotos } from "./attachments";+import {+ resetSentPhotos,+ sentPhotoUri,+ uploadStagedPhotos,+} from "./attachments";++const photo = {+ id: "photo-id",+ uri: "file:///photo.png",+ name: "photo.png",+ mimeType: "image/png",+ size: mocks.photoBytes.byteLength,+};beforeEach(() => {vi.clearAllMocks();+ resetSentPhotos();mocks.client.prepareTaskStagedArtifactUploads.mockResolvedValue([{id: "prepared-id",@@ -54,15 +67,7 @@ describe("uploadStagedPhotos", () => {return { ok: true };});- const result = await uploadStagedPhotos("task-id", [- {- id: "photo-id",- uri: "file:///photo.png",- name: "photo.png",- mimeType: "image/png",- size: mocks.photoBytes.byteLength,- },- ]);+ const result = await uploadStagedPhotos("task-id", [photo]);expect(uploadedBytes).toEqual(mocks.photoBytes);expect(mocks.expoFetch).toHaveBeenCalledWith(@@ -70,5 +75,25 @@ describe("uploadStagedPhotos", () => {expect.objectContaining({ method: "POST" }),);expect(result).toEqual(["artifact-id"]);+ expect(sentPhotoUri("task-id", "artifact-id")).toBe("file:///photo.png");+ });+});++describe("sentPhotoUri", () => {+ beforeEach(() => {+ mocks.expoFetch.mockResolvedValue({ ok: true });+ });++ it("shows a sent photo only in the task it was sent to", async () => {+ await uploadStagedPhotos("task-id", [photo]);++ expect(sentPhotoUri("other-task-id", "artifact-id")).toBeNull();+ });++ it("forgets sent photos when the account changes", async () => {+ await uploadStagedPhotos("task-id", [photo]);+ resetSentPhotos();++ expect(sentPhotoUri("task-id", "artifact-id")).toBeNull();});});diff --git a/products/desktop/apps/mobilehog/src/lib/attachments.ts b/products/desktop/apps/mobilehog/src/lib/attachments.tsindex 8eff4314d2e9..4155b4090e62 100644--- a/products/desktop/apps/mobilehog/src/lib/attachments.ts+++ b/products/desktop/apps/mobilehog/src/lib/attachments.ts@@ -10,6 +10,38 @@ import { getClient } from "@/lib/client";export const MAX_PHOTOS = 10;const MAX_PHOTO_BYTES = 30 * 1024 * 1024;+// Photos sent from this device by task and artifact id, so the chat can show+// the file already on disk rather than download it again. The account-change+// reset clears it, so one account never shows another account's file.+const sentPhotoUris = new Map<string, string>();++function sentPhotoKey(taskId: string, artifactId: string): string {+ return `${taskId}/${artifactId}`;+}++export function sentPhotoUri(+ taskId: string,+ artifactId: string,+): string | null {+ return sentPhotoUris.get(sentPhotoKey(taskId, artifactId)) ?? null;+}++export function resetSentPhotos(): void {+ sentPhotoUris.clear();+}++function rememberSent(+ taskId: string,+ photos: Photo[],+ artifactIds: string[],+): string[] {+ artifactIds.forEach((artifactId, index) => {+ const photo = photos[index];+ if (photo) sentPhotoUris.set(sentPhotoKey(taskId, artifactId), photo.uri);+ });+ return artifactIds;+}+export interface Photo {id: string;uri: string;@@ -95,7 +127,11 @@ export async function uploadStagedPhotos(taskId,prepared,);- return finalized.map((artifact) => artifact.id);+ return rememberSent(+ taskId,+ photos,+ finalized.map((artifact) => artifact.id),+ );}export async function uploadRunPhotos(@@ -116,5 +152,9 @@ export async function uploadRunPhotos(runId,prepared,);- return finalized.map((artifact) => artifact.id);+ return rememberSent(+ taskId,+ photos,+ finalized.map((artifact) => artifact.id),+ );}diff --git a/products/desktop/apps/mobilehog/src/lib/queries.ts b/products/desktop/apps/mobilehog/src/lib/queries.tsindex 9910895055bd..0ca483183ada 100644--- a/products/desktop/apps/mobilehog/src/lib/queries.ts+++ b/products/desktop/apps/mobilehog/src/lib/queries.ts@@ -12,6 +12,7 @@ import { useAuth } from "@/lib/auth";import { getClient } from "@/lib/client";import { currentRunConfig } from "@/lib/composer";import { useRepo } from "@/lib/repo";+import type { PhotoRef } from "@/lib/transcript";const TERMINAL: ReadonlySet<string> = new Set(["completed",@@ -25,8 +26,15 @@ export const keys = {models: ["models"] as const,repository: ["repository"] as const,repositories: ["repositories"] as const,+ runArtifacts: (taskId: string, runId: string) =>+ ["run-artifacts", taskId, runId] as const,+ photoUrl: (taskId: string, runId: string, artifactId: string) =>+ ["photo-url", taskId, runId, artifactId] as const,};+// Presigned photo URLs expire after an hour; refresh them well before that.+const PHOTO_URL_TTL = 50 * 60_000;+const PAGE_SIZE = 50;function visibleTasks(tasks: Task[]): Task[] {@@ -216,3 +224,40 @@ export async function createAndRunTask(input: {...currentRunConfig(),});}++// Resolves a sent photo to a short-lived download URL. Pass null to skip.+export function usePhotoUrl(taskId: string, photo: PhotoRef | null) {+ const session = useAuth((s) => s.session);+ const queryClient = useQueryClient();+ return useQuery({+ queryKey: keys.photoUrl(+ taskId,+ photo?.runId ?? "",+ photo?.artifactId ?? "",+ ),+ queryFn: async () => {+ if (!photo) throw new Error("No photo");+ const client = getClient();+ const findPath = async (staleTime: number) => {+ const artifacts = await queryClient.fetchQuery({+ queryKey: keys.runArtifacts(taskId, photo.runId),+ queryFn: async () =>+ (await client.getTaskRun(taskId, photo.runId)).artifacts ?? [],+ staleTime,+ });+ return artifacts.find((artifact) => artifact.id === photo.artifactId)+ ?.storage_path;+ };+ // One manifest fetch serves every photo of the run, but a cached one can+ // predate a photo that was just sent, so a miss fetches it again.+ const storagePath = (await findPath(10_000)) ?? (await findPath(0));+ if (!storagePath) throw new Error("Photo not found");+ return client.presignTaskRunArtifact(taskId, photo.runId, storagePath);+ },+ enabled: !!session && !!photo,+ staleTime: PHOTO_URL_TTL,+ gcTime: PHOTO_URL_TTL,+ refetchInterval: PHOTO_URL_TTL,+ retry: false,+ });+}diff --git a/products/desktop/apps/mobilehog/src/lib/session.ts b/products/desktop/apps/mobilehog/src/lib/session.tsindex ea9f2f17e8bb..1cf0cde9cf89 100644--- a/products/desktop/apps/mobilehog/src/lib/session.ts+++ b/products/desktop/apps/mobilehog/src/lib/session.ts@@ -395,6 +395,20 @@ export const useSessions = create<SessionState>((set, get) => {session.runId,photos,);+ if (artifactIds.length) {+ const sent = artifactIds.map((artifactId, index) => ({+ runId: session.runId,+ artifactId,+ name: photos[index].name,+ }));+ patch(taskId, (s) => ({+ blocks: s.blocks.map((block) =>+ block.id === localId && block.kind === "user"+ ? { ...block, photos: sent }+ : block,+ ),+ }));+ }await getClient().sendCloudRunCommand(taskId,session.runId,diff --git a/products/desktop/apps/mobilehog/src/lib/transcript.test.ts b/products/desktop/apps/mobilehog/src/lib/transcript.test.tsnew file mode 100644index 000000000000..ba5741c53a5e--- /dev/null+++ b/products/desktop/apps/mobilehog/src/lib/transcript.test.ts@@ -0,0 +1,172 @@+import type { StoredLogEntry } from "@posthog/shared";+import { describe, expect, it } from "vitest";+import { type Block, foldEntries, promptPhotos } from "./transcript";++const photoUri = (runId: string, artifactId: string, name: string) =>+ `file:///tmp/workspace/.posthog/attachments/${runId}/${artifactId}/${name}`;++function promptEntry(prompt: unknown[]): StoredLogEntry {+ return {+ type: "notification",+ notification: { id: 1, method: "session/prompt", params: { prompt } },+ };+}++function userChunk(content: Record<string, unknown>): StoredLogEntry {+ return {+ type: "notification",+ notification: {+ method: "session/update",+ params: { update: { sessionUpdate: "user_message_chunk", content } },+ },+ };+}++const photoPrompt = [+ { type: "text", text: "what is this?" },+ {+ type: "resource_link",+ uri: photoUri("run-1", "artifact-1", "IMG_0001.jpg"),+ name: "IMG_0001.jpg",+ mimeType: "image/jpeg",+ },+];++// What the agent logs for a turn with a photo: the prompt, then its echo.+const photoTurn = [+ promptEntry(photoPrompt),+ userChunk({ type: "text", text: "what is this?" }),+ userChunk(photoPrompt[1]),+];++const photo = {+ runId: "run-1",+ artifactId: "artifact-1",+ name: "IMG_0001.jpg",+};++describe("promptPhotos", () => {+ it("reads photos from visible attachment links and skips other files", () => {+ const result = promptPhotos([+ { type: "text", text: "look", _meta: { ui: { hidden: true } } },+ { type: "text", text: "at these" },+ {+ type: "resource_link",+ uri: photoUri("run-1", "artifact-1", "IMG_0001.HEIC"),+ name: "IMG_0001.HEIC",+ },+ {+ type: "resource_link",+ uri: photoUri("run-1", "artifact-3", "IMG_0002.jpg"),+ name: "IMG_0002.jpg",+ _meta: { ui: { hidden: true } },+ },+ {+ type: "resource_link",+ uri: photoUri("run-1", "artifact-2", "notes.pdf"),+ name: "notes.pdf",+ },+ { type: "resource_link", uri: "file:///repo/cat.png", name: "cat.png" },+ ]);++ expect(result).toEqual({+ text: "at these",+ texts: ["at these"],+ photos: [+ { runId: "run-1", artifactId: "artifact-1", name: "IMG_0001.HEIC" },+ ],+ });+ });+});++describe("foldEntries with photos", () => {+ it("rebuilds a user message with its photos from the log", () => {+ const result = foldEntries([], photoTurn, new Set());++ expect(result.blocks).toEqual([+ expect.objectContaining({+ kind: "user",+ text: "what is this?",+ photos: [photo],+ }),+ ]);+ expect(result.externalUserMessages).toBe(1);+ });++ it("rebuilds a photo-only message", () => {+ const result = foldEntries(+ [],+ [promptEntry([photoPrompt[1]]), userChunk(photoPrompt[1])],+ new Set(),+ );++ expect(result.blocks).toEqual([+ expect.objectContaining({ kind: "user", text: "", photos: [photo] }),+ ]);+ });++ it("adds the photos to a message sent from this device", () => {+ const sent: Block = {+ kind: "user",+ id: "local-1",+ text: "what is this?",+ images: ["file:///picker/IMG_0001.jpg"],+ };+ const echoes = new Set(["what is this?"]);++ const result = foldEntries([sent], photoTurn, echoes);++ expect(result.blocks).toEqual([{ ...sent, photos: [photo] }]);+ expect(result.externalUserMessages).toBe(0);+ expect(echoes.size).toBe(0);+ });++ it("keeps photos already known for a sent message", () => {+ const known = { ...photo, artifactId: "artifact-9" };+ const sent: Block = {+ kind: "user",+ id: "local-1",+ text: "what is this?",+ photos: [known],+ };++ const result = foldEntries([sent], photoTurn, new Set(["what is this?"]));++ expect(result.blocks).toEqual([sent]);+ });++ it("clears the echo of a photo-only message sent from this device", () => {+ const sent: Block = { kind: "user", id: "local-1", text: "" };+ const echoes = new Set([""]);++ const result = foldEntries([sent], [promptEntry([photoPrompt[1]])], echoes);++ expect(result.blocks).toEqual([{ ...sent, photos: [photo] }]);+ expect(echoes.size).toBe(0);+ });++ it("matches the prompt and its echo across batches", () => {+ const echoes = new Set<string>();+ const first = foldEntries([], [promptEntry(photoPrompt)], echoes);+ const second = foldEntries(first.blocks, photoTurn.slice(1), echoes);++ expect(second.blocks).toHaveLength(1);+ expect(second.externalUserMessages).toBe(0);+ });++ it("leaves text-only prompts to the message echo", () => {+ const result = foldEntries(+ [],+ [+ promptEntry([{ type: "text", text: "hello" }]),+ userChunk({ type: "text", text: "hello" }),+ ],+ new Set(),+ );++ expect(result.blocks).toEqual([+ expect.objectContaining({ kind: "user", text: "hello" }),+ ]);+ expect(result.blocks[0]).not.toHaveProperty("photos");+ });+});diff --git a/products/desktop/apps/mobilehog/src/lib/transcript.ts b/products/desktop/apps/mobilehog/src/lib/transcript.tsindex 4907ab1ed4bf..4c2b8b68a40a 100644--- a/products/desktop/apps/mobilehog/src/lib/transcript.ts+++ b/products/desktop/apps/mobilehog/src/lib/transcript.ts@@ -1,5 +1,6 @@+import { extractPromptDisplayContent } from "@posthog/core/sessions/promptContent";import type { StoredLogEntry } from "@posthog/shared";-import { isIdleResumeTurnComplete } from "@posthog/shared";+import { isIdleResumeTurnComplete, isRasterImageFile } from "@posthog/shared";export type ToolStatus = "pending" | "running" | "completed" | "failed";@@ -9,9 +10,22 @@ export interface PlanEntry {priority?: string;}+// A photo the person sent, stored as a run artifact.+export interface PhotoRef {+ runId: string;+ artifactId: string;+ name: string;+}+export type Block =- // images: local photo URIs, shown until the chat reloads.- | { kind: "user"; id: string; text: string; images?: string[] }+ | {+ kind: "user";+ id: string;+ text: string;+ // Local picker URIs, shown until the sent photos are known.+ images?: string[];+ photos?: PhotoRef[];+ }| { kind: "agent"; id: string; text: string; complete: boolean }| { kind: "thought"; id: string; text: string; at: number }| {@@ -97,6 +111,36 @@ function last(blocks: Block[]): Block | undefined {return blocks[blocks.length - 1];}+type PromptBlock = Parameters<typeof extractPromptDisplayContent>[0][number];++// iOS photo names can end in .HEIC, which React Native renders.+function isPhotoName(name: string): boolean {+ return isRasterImageFile(name) || /\.hei[cf]$/i.test(name);+}++export function promptPhotos(prompt: PromptBlock[]): {+ text: string;+ texts: string[];+ photos: PhotoRef[];+} {+ // An upstream retry resends every block of the prompt as hidden, photo links+ // too, so hidden blocks must not add the photos again.+ const visible = prompt.filter(+ (block) =>+ !(block._meta as { ui?: { hidden?: boolean } } | undefined)?.ui?.hidden,+ );+ const { text, attachments } = extractPromptDisplayContent(visible);+ const texts = visible.flatMap((block) =>+ block.type === "text" && block.text ? [block.text] : [],+ );+ const photos = attachments.flatMap((attachment) =>+ attachment.cloudArtifact && isPhotoName(attachment.label)+ ? [{ ...attachment.cloudArtifact, name: attachment.label }]+ : [],+ );+ return { text, texts, photos };+}+export function closeOpenAgent(blocks: Block[]): void {const open = last(blocks);if (open?.kind === "agent" && !open.complete) {@@ -186,6 +230,31 @@ export function foldEntries(if (params?.requestId) result.resolvedRequestIds.push(params.requestId);continue;}+ // Only the prompt request links the attachments for every agent, so a turn+ // with photos is built from it and the text echo that follows is skipped.+ if (method === "session/prompt") {+ const prompt = (entry.notification?.params as { prompt?: unknown })+ ?.prompt;+ if (!Array.isArray(prompt)) continue;+ const { text, texts, photos } = promptPhotos(prompt as PromptBlock[]);+ if (!photos.length) continue;+ if (localEchoes.has(text)) {+ const index = blocks.findLastIndex(+ (block) => block.kind === "user" && block.text === text,+ );+ const sent = blocks[index];+ if (sent?.kind === "user" && !sent.photos) {+ blocks[index] = { ...sent, photos };+ }+ if (!text) localEchoes.delete(text);+ continue;+ }+ result.externalUserMessages += 1;+ closeOpenAgent(blocks);+ blocks.push({ kind: "user", id: nextId("user"), text, photos });+ for (const chunk of texts) localEchoes.add(chunk);+ continue;+ }if (method !== "session/update") continue;const update = (entry.notification?.params as { update?: SessionUpdate })