: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
fix(mobile): limit agent chat to the internal project (#129719)
Chris Volzer39bdc6768527
diff --git a/products/mobile/app/chat.tsx b/products/mobile/app/chat.tsxindex f6c51cce70ac..82a498618e5f 100644--- a/products/mobile/app/chat.tsx+++ b/products/mobile/app/chat.tsx@@ -1,8 +1,9 @@import { useLocalSearchParams, useRouter } from 'expo-router'import { type ReactElement, useCallback } from 'react'+import { useAuthStore } from '@/auth/authStore'import { useDataMode } from '@/demo/demoMode'-import { ChatScreen } from '@/features/chat/ChatScreen'+import { ChatEntryScreen } from '@/features/chat/ChatEntryScreen'import { chatSheetSource } from '@/features/chat/chatSheetEvents'import { objectContextFromParams } from '@/features/chat/objectContext'import { useChatAutoFocus } from '@/features/chat/useChatAutoFocus'@@ -10,18 +11,23 @@ import { currentDefaultPageHref } from '@/features/settings/defaultPageStore'export default function ChatRoute(): ReactElement {const router = useRouter()+ const host = useAuthStore((state) => state.host)+ const userUuid = useAuthStore((state) => state.user?.uuid)+ const projectId = useAuthStore((state) => state.projectId)const dataMode = useDataMode()const autoFocus = useChatAutoFocus()- const { reportId, taskId, runId, entry, origin, objectType, objectId, objectLabel } = useLocalSearchParams<{- reportId?: string- taskId?: string- runId?: string- entry?: string- origin?: string- objectType?: string- objectId?: string- objectLabel?: string- }>()+ const { reportId, taskId, runId, conversationId, entry, origin, objectType, objectId, objectLabel } =+ useLocalSearchParams<{+ reportId?: string+ taskId?: string+ runId?: string+ conversationId?: string+ entry?: string+ origin?: string+ objectType?: string+ objectId?: string+ objectLabel?: string+ }>()const close = useCallback(() => {if (router.canGoBack()) {router.back()@@ -30,8 +36,19 @@ export default function ChatRoute(): ReactElement {}}, [router])return (- <ChatScreen- key={JSON.stringify([dataMode, taskId, runId, reportId, objectId])}+ <ChatEntryScreen+ key={JSON.stringify([+ host,+ userUuid,+ projectId,+ dataMode,+ taskId,+ runId,+ reportId,+ objectId,+ conversationId,+ ])}+ conversationId={conversationId}initialReportId={reportId}initialTaskId={taskId}initialRunId={runId}diff --git a/products/mobile/docs/API.md b/products/mobile/docs/API.mdindex 0635f27e053e..08a015a90ce8 100644--- a/products/mobile/docs/API.md+++ b/products/mobile/docs/API.md@@ -39,6 +39,7 @@ the request while previously loaded pages remain visible. The load-more retry re| Inbox and reports | `src/api/reports.ts` | `signals/reports/?view=for_you&sort=priority`, `.../{id}/`, `.../signals/`, `.../artefacts/`, `read_state/`, `.../state/`, `.../reviewers/`, `available_reviewers/` | [DATA.md](DATA.md) || Today | `src/api/today.ts` | `today/reports/{id}/page/` | 403 or 404 means the project lacks Today; the report screen shows signals instead || Tasks | `src/api/tasks.ts` | `tasks/`, `tasks/{id}/` (`PATCH { archived }` archives a chat), `tasks/{id}/run/` (a chat's resume adds `resume_from_run_id` and `pending_user_message`; `pending_user_artifact_ids` carries staged files), `.../runs/{runId}/`, `.../logs/`, `.../stream/`, `.../command/` (`user_message`, with `artifact_ids` for files; `set_config_option`, `permission_response`, `cancel`) | [HANDOFF.md](HANDOFF.md), [CHAT.md](CHAT.md) |+| Classic AI | `src/api/conversations.ts` | `GET conversations/`, `GET conversations/{id}/`, `POST conversations/` (SSE), `PATCH conversations/{id}/cancel/` | [CHAT.md](CHAT.md) || Chat attachments | `src/api/tasks.ts`, `src/features/chat/attachments/uploadAttachments.ts` | `tasks/{id}/staged_artifacts/prepare_upload/`, `tasks/{id}/staged_artifacts/finalize_upload/`, `.../runs/{runId}/artifacts/prepare_upload/`, `.../runs/{runId}/artifacts/finalize_upload/`, all `task:write`; then a presigned S3 `POST` with no PostHog auth | [CHAT.md](CHAT.md#attachments) || Push | `src/api/pushTokens.ts` | `/api/users/@me/push_tokens/`, `.../unregister/` | [PUSH.md](PUSH.md) || Views pins | `src/api/shortcuts.ts` | `file_system_shortcut/`, `.../{id}/` | [VIEWS.md](VIEWS.md) |diff --git a/products/mobile/docs/CHAT.md b/products/mobile/docs/CHAT.mdindex 7c7667c2adbb..072b7a9158ce 100644--- a/products/mobile/docs/CHAT.md+++ b/products/mobile/docs/CHAT.md@@ -1,7 +1,27 @@# Chat-The chat screen talks to PostHog AI on the task runtime, as the web app's side-panel chat does.-Every chat is a task with interactive runs in a sandbox.+## Choosing the chat version++New general chats use the Tasks agent only in project 2 on `https://us.posthog.com`.+Every other project uses classic PostHog AI through the existing `conversations/` API.+This temporary routing rule is local to the mobile app. It does not evaluate rollout flags+or request an AI access field from the server. Organization approval and personal consent+still apply before sending messages.++Saved conversation links read their runtime from the existing conversation detail response.+Report discussions and existing task links keep the Tasks path and its report-specific access+exemptions. **New chat** starts the version selected for the current project. Demo mode keeps+its local Tasks fixtures.++Classic chat supports streamed responses, saved history, follow-up messages, stopping a reply,+and approving or rejecting a requested change. Generated charts and insights link to the web.+Its composer omits the model and permission controls that only the Tasks runtime supports.+The Chats list combines unlinked conversations and tasks. Conversations with a linked task use the task row. Classic+conversation links use `conversationId`; Tasks links continue to use `taskId` and `runId`.+Only task rows offer Archive, because classic conversations have no reversible archive API.++The Tasks chat screen talks to PostHog AI on the task runtime.+Each Tasks chat has interactive runs in a sandbox.A new chat creates the task on its first message; the Chats list reopens one by its task id.New and existing chats open as full-screen stack pages. Back returns to the previous screen or theconfigured default page for a direct link. The title-free header uses the shared blur and fading edge.@@ -59,6 +79,15 @@ The same approval rules cover Chat, Create PR/task handoff, and replay summarizaThese client checks supplement existing server scopes, resource RBAC and product checks. They do not grant an organization role or replace server authorization. Revocation after a check must still be enforced by the backend; mobile cannot stop an agent that is already running on the server.+Classic chat refreshes history whenever it opens, even while the cached response is fresh, and reuses that download.+An accepted message leaves draft recovery as soon as the server accepts it, while the reply continues streaming.+If its stream disconnects or times out, classic chat checks the saved conversation automatically without sending the message again.+Completed replies and pending decisions load from that saved state. If recovery still needs a connection, received messages stay visible with Reconnect.+Linked conversations stay visible when their task is absent from the list.+Opening a linked chat checks its conversation runtime before continuing.+If one chat history source fails, Chats keeps the loaded rows and offers a retry for the remaining history.+Classic chat shows draft save failures with a retry action, and checks AI approval before each message or approval response.+## Composer draftsThe message input wraps long text onto multiple lines and grows up to 120 points tall.@@ -467,13 +496,14 @@ The route takes an optional `entry` param; `chatSheetSource` falls back on `repo- A long press (or the screen reader's "Show actions") opens the row menu (`ChatRowMenu`) with Archive.`useArchiveChat()` hides the row at once and sends `PATCH tasks/{id}/` with `{ "archived": true }`; the server stamps `archived_at`and leaves the task out of every later list. The toast offers Undo, which puts the row back and sends `{ "archived": false }` after any pending archive request finishes.+ Archive and Undo update linked conversations in the cached history too, so they cannot recreate a hidden task row.Repeated archive submissions share the pending request. A failed archive puts the row back and shows "Couldn't archive this chat. Try again."A failed Undo hides the row again and shows "Couldn't restore this chat. Try again."There is no archived list in the app: the web app and PostHog Desktop show archived tasks.- `mobile_chat_row_menu_opened`, `mobile_chat_archived` and `mobile_chat_archive_undone` carry the row's `origin` and `status`;`mobile_chat_archive_failed` carries `action` (`archive` or `restore`) and `code` (the `ChatError` kind).- Regaining focus (closing the sheet) invalidates the list, so a new chat appears with its title.-- Legacy LangGraph conversations are not listed. The web's new side panel does not list them either.+- Classic conversations are listed once; their mirrored tasks are omitted.## Demo modediff --git a/products/mobile/src/features/chat/ChatEmptyState.tsx b/products/mobile/src/features/chat/ChatEmptyState.tsxindex 4fdaa30154c2..a0a9d41f26ae 100644--- a/products/mobile/src/features/chat/ChatEmptyState.tsx+++ b/products/mobile/src/features/chat/ChatEmptyState.tsx@@ -13,6 +13,7 @@ const GLOBAL_PROMPTS = ['What needs me today?', 'Summarize this week', 'What didinterface ChatEmptyStateProps {reportCount: numbersuggestedPrompts?: string[]+ description?: stringonPrompt: (prompt: string) => void}@@ -32,11 +33,20 @@ function copyFor(reportCount: number): { title: string; sub: string } {}}-export function ChatEmptyState({ reportCount, suggestedPrompts, onPrompt }: ChatEmptyStateProps): ReactElement {+export function ChatEmptyState({+ reportCount,+ suggestedPrompts,+ description,+ onPrompt,+}: ChatEmptyStateProps): ReactElement {const colors = useColors()const styles = useStyles()- const fromReport = suggestedPrompts !== undefined && suggestedPrompts.length > 0- const prompts: readonly string[] = fromReport ? suggestedPrompts : reportCount > 0 ? REPORT_PROMPTS : GLOBAL_PROMPTS+ const fromReport = reportCount > 0 && suggestedPrompts !== undefined && suggestedPrompts.length > 0+ const prompts: readonly string[] = suggestedPrompts?.length+ ? suggestedPrompts+ : reportCount > 0+ ? REPORT_PROMPTS+ : GLOBAL_PROMPTSconst copy = copyFor(reportCount)// A report's own prompts are generated text, so the event names the list and the position only.const pick = (prompt: string, index: number): void => {@@ -51,7 +61,7 @@ export function ChatEmptyState({ reportCount, suggestedPrompts, onPrompt }: Chat<View style={styles.container} testID="chat-empty"><PostHogLogomark height={28} /><Text style={styles.title}>{copy.title}</Text>- <Text style={[styles.sub, prettyWrap]}>{copy.sub}</Text>+ <Text style={[styles.sub, prettyWrap]}>{description ?? copy.sub}</Text><View style={styles.chips}>{prompts.map((prompt, index) => (<Pressable44diff --git a/products/mobile/src/features/chat/ChatEntryScreen.test.tsx b/products/mobile/src/features/chat/ChatEntryScreen.test.tsxnew file mode 100644index 000000000000..93a070beb11c--- /dev/null+++ b/products/mobile/src/features/chat/ChatEntryScreen.test.tsx@@ -0,0 +1,187 @@+import { onlineManager, QueryClient, QueryClientProvider } from '@tanstack/react-query'+import { act, fireEvent, render, screen, waitFor } from '@testing-library/react-native'+import type { ReactElement } from 'react'++import { getConversation } from '@/api/conversations'+import { useProjectScope } from '@/auth/useProjectScope'+import { useDataMode } from '@/demo/demoMode'+import { ChatEntryScreen } from './ChatEntryScreen'++jest.mock('@/api/conversations', () => ({ getConversation: jest.fn() }))+jest.mock('@/auth/useProjectScope', () => ({ useProjectScope: jest.fn() }))+jest.mock('@/demo/demoMode', () => ({ ...jest.requireActual('@/demo/demoMode'), useDataMode: jest.fn() }))+jest.mock('./ChatHeader', () => {+ const { Button } = require('react-native')+ return {+ ChatHeader: ({ onBack }: { onBack: () => void }): ReactElement => (+ <Button testID="chat-back" title="Back" onPress={onBack} />+ ),+ }+})+jest.mock('./ChatScreen', () => {+ const { Button, Text, View } = require('react-native')+ return {+ ChatScreen: ({ initialTaskId, onNewChat }: { initialTaskId?: string; onNewChat: () => void }): ReactElement => (+ <View testID="sandbox">+ <Text>{initialTaskId}</Text>+ <Button title="New" onPress={onNewChat} />+ </View>+ ),+ }+})+jest.mock('./classic/ClassicChatScreen', () => {+ const { Button, Text, View } = require('react-native')+ return {+ ClassicChatScreen: ({+ conversationId,+ initialConversation,+ onNewChat,+ }: {+ conversationId?: string+ initialConversation?: { title: string | null }+ onNewChat: () => void+ }): ReactElement => (+ <View testID="classic">+ <Text>{conversationId}</Text>+ <Text>{initialConversation?.title}</Text>+ <Button title="New" onPress={onNewChat} />+ </View>+ ),+ }+})++function open(+ props: Partial<React.ComponentProps<typeof ChatEntryScreen>> = {},+ seed?: (client: QueryClient) => void+): void {+ const client = new QueryClient({+ defaultOptions: { queries: { retry: false, gcTime: Infinity, staleTime: 30_000 } },+ })+ seed?.(client)+ render(+ <QueryClientProvider client={client}>+ <ChatEntryScreen+ source={{ entry: 'chats_empty', origin: null }}+ autoFocus={false}+ onBack={() => undefined}+ {...props}+ />+ </QueryClientProvider>+ )+}++describe('mobile AI runtime selection', () => {+ beforeEach(() => {+ jest.clearAllMocks()+ jest.mocked(getConversation).mockReset()+ jest.mocked(useDataMode).mockReturnValue('live')+ jest.mocked(useProjectScope).mockReturnValue({ host: 'https://us.posthog.com', projectId: 42 })+ })++ test.each([+ ['https://us.posthog.com', 2, 'sandbox'],+ ['https://us.posthog.com', 42, 'classic'],+ ['https://eu.posthog.com', 2, 'classic'],+ ['https://example.com', 2, 'classic'],+ ['http://localhost:8010', 2, 'classic'],+ ])('selects %s project %s as %s', (host, projectId, runtime) => {+ jest.mocked(useProjectScope).mockReturnValue({ host, projectId })+ open()+ expect(screen.getByTestId(runtime)).toBeTruthy()+ expect(getConversation).not.toHaveBeenCalled()+ })++ test('a new offline chat opens without waiting for a network lookup', () => {+ onlineManager.setOnline(false)+ try {+ open()+ expect(screen.getByTestId('classic')).toBeTruthy()+ expect(getConversation).not.toHaveBeenCalled()+ } finally {+ onlineManager.setOnline(true)+ }+ })++ test('waits for the selected project before showing a new chat', () => {+ jest.mocked(useProjectScope).mockReturnValue(null)+ open()+ expect(screen.getByLabelText('Loading chat')).toBeTruthy()+ expect(screen.queryByTestId('sandbox')).toBeNull()+ expect(screen.queryByTestId('classic')).toBeNull()+ })++ test('an existing classic conversation stays classic in the agent project', async () => {+ jest.mocked(useProjectScope).mockReturnValue({ host: 'https://us.posthog.com', projectId: 2 })+ jest.mocked(getConversation).mockResolvedValue({ agent_runtime: 'langgraph' } as Awaited<+ ReturnType<typeof getConversation>+ >)+ open({ conversationId: 'conversation-1' })+ await screen.findByTestId('classic')+ })++ test('an existing sandbox conversation opens its task outside the agent project', async () => {+ jest.mocked(getConversation).mockResolvedValue({ agent_runtime: 'sandbox', task: { id: 'task-1' } } as Awaited<+ ReturnType<typeof getConversation>+ >)+ open({ conversationId: 'conversation-1' })+ await screen.findByText('task-1')+ expect(screen.getByTestId('sandbox')).toBeTruthy()+ })++ test('starting a new chat from a task uses the current project rule', () => {+ open({ initialTaskId: 'task-1' })+ expect(screen.getByText('task-1')).toBeTruthy()+ fireEvent.press(screen.getByText('New'))+ expect(screen.getByTestId('classic')).toBeTruthy()+ })++ test('report chats keep their task path outside the agent project', () => {+ open({ initialReportId: 'report-1' })+ expect(screen.getByTestId('sandbox')).toBeTruthy()+ })++ test('an incomplete sandbox conversation never opens in the classic runtime', async () => {+ jest.mocked(getConversation).mockResolvedValue({ agent_runtime: 'sandbox', task: null } as Awaited<+ ReturnType<typeof getConversation>+ >)+ open({ conversationId: 'conversation-1' })+ await screen.findByText('This chat is not ready yet')+ expect(screen.queryByTestId('classic')).toBeNull()+ expect(screen.getByTestId('chat-back')).toBeTruthy()+ })++ test('a new demo chat resets its task without requesting conversation history', () => {+ jest.mocked(useDataMode).mockReturnValue('demo')+ open({ initialTaskId: 'demo-task' })+ expect(screen.getByText('demo-task')).toBeTruthy()+ fireEvent.press(screen.getByText('New'))+ expect(screen.queryByText('demo-task')).toBeNull()+ expect(screen.getByTestId('sandbox')).toBeTruthy()+ expect(getConversation).not.toHaveBeenCalled()+ })+ test('waits for refreshed history before mounting a cached classic chat', async () => {+ let refresh!: (value: Awaited<ReturnType<typeof getConversation>>) => void+ jest.mocked(getConversation).mockReturnValueOnce(+ new Promise((resolve) => {+ refresh = resolve+ })+ )+ open({ conversationId: 'saved-chat' }, (client) => {+ client.setQueryData(['chat-conversation', 'https://us.posthog.com', 42, 'saved-chat'], {+ id: 'saved-chat',+ title: 'Old history',+ agent_runtime: 'langgraph',+ })+ })+ expect(screen.queryByTestId('classic')).toBeNull()+ await waitFor(() => expect(getConversation).toHaveBeenCalledTimes(1))+ await act(async () => {+ refresh({ id: 'saved-chat', title: 'Updated history', agent_runtime: 'langgraph' } as Awaited<+ ReturnType<typeof getConversation>+ >)+ })+ await screen.findByText('Updated history')+ expect(screen.queryByText('Old history')).toBeNull()+ expect(getConversation).toHaveBeenCalledTimes(1)+ })+})diff --git a/products/mobile/src/features/chat/ChatEntryScreen.tsx b/products/mobile/src/features/chat/ChatEntryScreen.tsxnew file mode 100644index 000000000000..ee8eb57e8171--- /dev/null+++ b/products/mobile/src/features/chat/ChatEntryScreen.tsx@@ -0,0 +1,109 @@+import { useQuery } from '@tanstack/react-query'+import { type ComponentProps, type ReactElement, useState } from 'react'+import { View } from 'react-native'++import { getConversation } from '@/api/conversations'+import { scopeKey } from '@/api/reports'+import { useProjectScope } from '@/auth/useProjectScope'+import { useDataMode } from '@/demo/demoMode'+import { WarningIcon } from '@/ui/icons/WarningIcon'+import { LoadingView, StateView } from '@/ui/StateView'+import { createStyles } from '@/ui/theme'+import { iconSizes } from '@/ui/tokens'+import { ChatHeader } from './ChatHeader'+import { ChatScreen } from './ChatScreen'+import { ClassicChatScreen } from './classic/ClassicChatScreen'++type ChatEntryScreenProps = ComponentProps<typeof ChatScreen> & { conversationId?: string }++export function ChatEntryScreen({ conversationId, ...props }: ChatEntryScreenProps): ReactElement {+ const styles = useStyles()+ const scope = useProjectScope()+ const mode = useDataMode()+ const explicitTask = !!props.initialTaskId || !!props.initialReportId || !!props.initialObject+ const [newChat, setNewChat] = useState(false)+ const [generation, setGeneration] = useState(0)+ const conversation = useQuery({+ queryKey: ['chat-conversation', ...scopeKey(scope), conversationId],+ queryFn: ({ signal }) => getConversation(conversationId as string, signal),+ enabled: mode === 'live' && !!scope && !!conversationId && !newChat,+ retry: false,+ refetchOnMount: 'always',+ })+ const detail = conversation.isFetchedAfterMount ? conversation.data : undefined+ const restart = (): void => {+ setNewChat(true)+ setGeneration((value) => value + 1)+ }+ if (mode === 'demo' || (explicitTask && !newChat))+ return (+ <ChatScreen+ key={generation}+ {...props}+ initialTaskId={newChat ? undefined : props.initialTaskId}+ initialRunId={newChat ? undefined : props.initialRunId}+ initialReportId={newChat ? undefined : props.initialReportId}+ initialObject={newChat ? null : props.initialObject}+ onNewChat={restart}+ />+ )+ if (conversationId && !newChat) {+ if (detail && (detail.agent_runtime !== 'sandbox' || detail.task)) {+ return detail.agent_runtime === 'sandbox' && detail.task ? (+ <ChatScreen {...props} initialTaskId={detail.task.id} initialRunId={undefined} onNewChat={restart} />+ ) : (+ <ClassicChatScreen+ conversationId={conversationId}+ initialConversation={detail}+ source={props.source}+ autoFocus={props.autoFocus ?? false}+ onBack={props.onBack}+ onNewChat={restart}+ />+ )+ }+ return (+ <View style={styles.screen}>+ {conversation.isError || detail ? (+ <StateView+ icon={<WarningIcon size={iconSizes.empty} />}+ title={detail ? 'This chat is not ready yet' : "Couldn't load this chat"}+ actionLabel="Try again"+ onAction={() => void conversation.refetch()}+ />+ ) : (+ <LoadingView label="Loading chat" />+ )}+ <ChatHeader webUrl={undefined} onBack={props.onBack} onNewChat={restart} />+ </View>+ )+ }+ if (mode === 'loading' || !scope)+ return (+ <View style={styles.screen}>+ <LoadingView label="Loading chat" />+ <ChatHeader webUrl={undefined} onBack={props.onBack} onNewChat={restart} />+ </View>+ )+ return scope.host === 'https://us.posthog.com' && scope.projectId === 2 ? (+ <ChatScreen+ key={generation}+ {...props}+ initialTaskId={undefined}+ initialRunId={undefined}+ initialReportId={undefined}+ initialObject={null}+ onNewChat={restart}+ />+ ) : (+ <ClassicChatScreen+ key={generation}+ source={props.source}+ autoFocus={props.autoFocus ?? false}+ onBack={props.onBack}+ onNewChat={restart}+ />+ )+}++const useStyles = createStyles(({ colors }) => ({ screen: { flex: 1, backgroundColor: colors.surface } }))diff --git a/products/mobile/src/features/chat/ChatScreen.tsx b/products/mobile/src/features/chat/ChatScreen.tsxindex 18df8f9ec131..6d30231ae155 100644--- a/products/mobile/src/features/chat/ChatScreen.tsx+++ b/products/mobile/src/features/chat/ChatScreen.tsx@@ -81,6 +81,7 @@ interface ChatScreenProps {source: ChatSheetSourceautoFocus?: booleanonBack: () => void+ onNewChat?: () => void}function sessionTarget(taskId: string | undefined, runId: string | undefined): SessionOptions {@@ -98,6 +99,7 @@ export function ChatScreen({source,autoFocus = false,onBack,+ onNewChat,}: ChatScreenProps): ReactElement {const styles = useStyles()const insets = useScreenInsets()@@ -586,6 +588,7 @@ export function ChatScreen({pickedOptions.current = falsedispatchRunOptions({ type: 'reset' })input.current?.focus()+ onNewChat?.()}const archiveChat = async (): Promise<void> => {diff --git a/products/mobile/src/features/chat/chatNavigation.test.tsx b/products/mobile/src/features/chat/chatNavigation.test.tsxindex e28f1b7e76ec..408045f19d99 100644--- a/products/mobile/src/features/chat/chatNavigation.test.tsx+++ b/products/mobile/src/features/chat/chatNavigation.test.tsx@@ -39,14 +39,14 @@ jest.mock('expo-notifications', () => ({jest.mock('@/features/notifications/pushSupport', () => ({ notificationsSupported: () => true }))jest.mock('@/features/notifications/taskLookup', () => ({ findTask: jest.fn() }))jest.mock('@/lib/posthogClient', () => ({ initAnalytics: jest.fn() }))-jest.mock('@/features/chat/ChatScreen', () => {+jest.mock('@/features/chat/ChatEntryScreen', () => {const { useEffect, useState } = jest.requireActual<typeof import('react')>('react')const { Button, Text, TextInput, View } = jest.requireActual<typeof import('react-native')>('react-native')const { setViewedNotificationTask } = jest.requireActual<typeof import('@/features/notifications/foregroundNotifications')>('@/features/notifications/foregroundNotifications')return {- ChatScreen: ({ initialTaskId, onBack }: { initialTaskId?: string; onBack: () => void }): ReactElement => {+ ChatEntryScreen: ({ initialTaskId, onBack }: { initialTaskId?: string; onBack: () => void }): ReactElement => {const [taskId, setTaskId] = useState(initialTaskId)const [draft, setDraft] = useState('')useEffect(() => {diff --git a/products/mobile/src/features/chat/chatSheetEvents.ts b/products/mobile/src/features/chat/chatSheetEvents.tsindex 4ac8b4f25486..a39885a92f15 100644--- a/products/mobile/src/features/chat/chatSheetEvents.ts+++ b/products/mobile/src/features/chat/chatSheetEvents.ts@@ -56,6 +56,8 @@ export function chatSheetSource(params: {}interface ChatSheetOpen extends ChatSheetSource {+ conversationId?: string | null+ runtime?: 'langgraph' | 'sandbox'hasContext: booleanresumed: boolean}@@ -82,10 +84,18 @@ export function useChatSheetEvents(useEffect(() => {const { entry, origin, hasContext, resumed } = opened.currentconst openedAt = Date.now()- track('mobile_chat_sheet_opened', { entry, origin, has_context: hasContext, resumed })+ track('mobile_chat_sheet_opened', {+ entry,+ origin,+ has_context: hasContext,+ resumed,+ conversation_id: opened.current.conversationId,+ agent_runtime: opened.current.runtime,+ })return () => {track('mobile_chat_sheet_closed', {entry,+ agent_runtime: opened.current.runtime,messages_sent: sent.current,new_chats: newChats.current,had_run: hadRun.current,diff --git a/products/mobile/src/features/chat/classic/ClassicChatScreen.test.tsx b/products/mobile/src/features/chat/classic/ClassicChatScreen.test.tsxnew file mode 100644index 000000000000..eee5642ac04d--- /dev/null+++ b/products/mobile/src/features/chat/classic/ClassicChatScreen.test.tsx@@ -0,0 +1,225 @@+import { act, fireEvent, render, screen, waitFor } from '@testing-library/react-native'++import { useChatDraft } from '../useChatDraft'+import { ClassicChatScreen } from './ClassicChatScreen'+import { classicHistory, EMPTY_CLASSIC_STATE } from './classicMessages'+import { useClassicChat } from './useClassicChat'++jest.mock('react-native-worklets', () => jest.requireActual('react-native-worklets/src/mock'))+jest.mock('react-native-reanimated', () => ({+ ...jest.requireActual('react-native-reanimated/mock'),+ useReducedMotion: () => true,+}))+jest.mock('react-native-keyboard-controller', () => jest.requireActual('react-native-keyboard-controller/jest'))+jest.mock(+ 'react-native-safe-area-context',+ () => jest.requireActual('react-native-safe-area-context/jest/mock').default+)+jest.mock('@/auth/useProjectScope', () => ({ useProjectScope: () => null }))+jest.mock('../ChatAccessGate', () => ({ ChatAccessGate: ({ children }: { children: React.ReactNode }) => children }))+jest.mock('../ChatEmptyState', () => ({ ChatEmptyState: () => null }))+jest.mock('../ChatHeader', () => {+ const { Button, View } = require('react-native')+ return {+ CHAT_HEADER_HEIGHT: 52,+ ChatHeader: ({ onBack, onNewChat }: { onBack: () => void; onNewChat: () => void }) => (+ <View>+ <Button title="Back" onPress={onBack} />+ <Button title="New chat" onPress={onNewChat} />+ </View>+ ),+ }+})+jest.mock('../chatSheetEvents', () => ({+ useChatSheetEvents: () => ({ countSent: jest.fn(), countNewChat: jest.fn() }),+}))+jest.mock('../useChatDraft', () => ({ useChatDraft: jest.fn() }))+jest.mock('./useClassicChat', () => ({ useClassicChat: jest.fn() }))++describe('classic chat draft recovery', () => {+ test.each(['empty', 'partial', 'reloading'] as const)(+ 'keeps %s history recoverable without hiding received messages',+ (kind) => {+ const reload = jest.fn(async () => undefined)+ jest.mocked(useChatDraft).mockReturnValue({+ draft: { text: '', reportIds: [] },+ ready: true,+ } as unknown as ReturnType<typeof useChatDraft>)+ jest.mocked(useClassicChat).mockReturnValue({+ id: 'saved-chat',+ loading: kind === 'reloading',+ working: false,+ stopping: false,+ historyError: kind === 'reloading' ? null : 'The reply was interrupted.',+ error: null,+ state: classicHistory(+ kind === 'empty' ? [] : [{ id: 'reply-1', type: 'ai', content: 'Received reply' }],+ 'A chat'+ ),+ form: null,+ send: jest.fn(),+ answer: jest.fn(),+ submitForm: jest.fn(),+ dismissForm: jest.fn(),+ stop: jest.fn(),+ reload,+ reset: jest.fn(),+ dismissError: jest.fn(),+ })+ render(+ <ClassicChatScreen+ conversationId="saved-chat"+ source={{ entry: 'chats_list', origin: 'chat' }}+ autoFocus={false}+ onBack={jest.fn()}+ onNewChat={jest.fn()}+ />+ )+ if (kind === 'empty') {+ expect(screen.getByText("Couldn't load this session")).toBeTruthy()+ fireEvent.press(screen.getByText('Try again'))+ } else {+ expect(screen.getByText('Received reply')).toBeTruthy()+ expect(screen.queryByText("Couldn't load this session")).toBeNull()+ fireEvent.press(screen.getByLabelText('Reconnect'))+ }+ expect(reload).toHaveBeenCalledTimes(kind === 'reloading' ? 0 : 1)+ }+ )+ test('keeps the unsaved text visible and guards retry until storage settles', async () => {+ let finish!: () => void+ const retrySave = jest.fn(+ () =>+ new Promise<void>((resolve) => {+ finish = resolve+ })+ )+ const draft = {+ draft: { text: 'Saved question', reportIds: [] },+ ready: true,+ draftError: 'Draft not saved. Try saving again.',+ retrySave,+ } as unknown as ReturnType<typeof useChatDraft>+ jest.mocked(useChatDraft).mockReturnValue(draft)+ jest.mocked(useClassicChat).mockReturnValue({+ id: null,+ loading: false,+ historyError: null,+ working: false,+ error: 'Reply failed. Try again.',+ state: { messages: [], title: null, approval: null, progress: null, error: null },+ } as unknown as ReturnType<typeof useClassicChat>)+ const element = (+ <ClassicChatScreen+ source={{ entry: 'compose', origin: null }}+ autoFocus={false}+ onBack={jest.fn()}+ onNewChat={jest.fn()}+ />+ )+ const view = render(element)+ expect(screen.getByDisplayValue('Saved question')).toBeTruthy()+ expect(screen.getByText(draft.draftError as string)).toBeTruthy()+ expect(screen.getByText('Reply failed. Try again.')).toBeTruthy()+ fireEvent.press(screen.getByLabelText('Retry saving draft'))+ fireEvent.press(screen.getByLabelText('Retry saving draft'))+ expect(retrySave).toHaveBeenCalledTimes(1)+ await act(async () => {+ finish()+ })+ draft.draftError = undefined+ view.rerender(+ <ClassicChatScreen+ source={{ entry: 'compose', origin: null }}+ autoFocus={false}+ onBack={jest.fn()}+ onNewChat={jest.fn()}+ />+ )+ expect(screen.queryByLabelText('Retry saving draft')).toBeNull()+ expect(screen.getByDisplayValue('Saved question')).toBeTruthy()+ })+ test.each(['Back', 'New chat', 'unmount'])('restores a prepared draft after %s', async (transition) => {+ let finish!: (settle: (sent: boolean) => Promise<void>) => void+ const settle = jest.fn(async () => undefined)+ const send = jest.fn()+ jest.mocked(useChatDraft).mockReturnValue({+ draft: { text: 'Unsent question', reportIds: [] },+ ready: true,+ beginSend: () =>+ new Promise((resolve) => {+ finish = resolve+ }),+ } as unknown as ReturnType<typeof useChatDraft>)+ jest.mocked(useClassicChat).mockReturnValue({+ id: null,+ loading: false,+ working: false,+ state: { messages: [], approval: null },+ send,+ reset: jest.fn(),+ } as unknown as ReturnType<typeof useClassicChat>)+ const view = render(+ <ClassicChatScreen+ source={{ entry: 'compose', origin: null }}+ autoFocus={false}+ onBack={jest.fn()}+ onNewChat={jest.fn()}+ />+ )+ fireEvent.press(screen.getByTestId('chat-send'))+ if (transition === 'unmount') view.unmount()+ else fireEvent.press(screen.getByText(transition))+ await act(async () => {+ finish(settle)+ })+ expect(send).not.toHaveBeenCalled()+ expect(settle).toHaveBeenCalledWith(false)+ })+ test('settles an accepted draft while the reply is still streaming', async () => {+ const settle = jest.fn(async () => undefined)+ let finish!: (accepted: boolean) => void+ jest.mocked(useChatDraft).mockReturnValue({+ draft: { text: 'A question', reportIds: [] },+ ready: true,+ beginSend: async () => settle,+ } as unknown as ReturnType<typeof useChatDraft>)+ jest.mocked(useClassicChat).mockReturnValue({+ id: null,+ loading: false,+ working: false,+ historyError: null,+ stopping: false,+ error: null,+ state: EMPTY_CLASSIC_STATE,+ answer: jest.fn(),+ form: null,+ submitForm: jest.fn(),+ dismissForm: jest.fn(),+ stop: jest.fn(),+ reload: jest.fn(),+ reset: jest.fn(),+ dismissError: jest.fn(),+ send: async (_text, onAccepted) => {+ await onAccepted?.()+ return new Promise((resolve) => {+ finish = resolve+ })+ },+ })+ render(+ <ClassicChatScreen+ source={{ entry: 'compose', origin: null }}+ autoFocus={false}+ onBack={jest.fn()}+ onNewChat={jest.fn()}+ />+ )+ fireEvent.press(screen.getByTestId('chat-send'))+ await waitFor(() => expect(settle).toHaveBeenCalledWith(true))+ await act(async () => {+ finish(true)+ })+ expect(settle).toHaveBeenCalledTimes(1)+ })+})diff --git a/products/mobile/src/features/chat/classic/ClassicChatScreen.tsx b/products/mobile/src/features/chat/classic/ClassicChatScreen.tsxnew file mode 100644index 000000000000..152c0cf85242--- /dev/null+++ b/products/mobile/src/features/chat/classic/ClassicChatScreen.tsx@@ -0,0 +1,289 @@+import { BlurTargetView } from 'expo-blur'+import { type ReactElement, useCallback, useEffect, useMemo, useRef, useState } from 'react'+import {+ ActivityIndicator,+ Keyboard,+ ScrollView,+ Text,+ type TextInputInstance,+ View,+ type ViewInstance,+} from 'react-native'+import { useReanimatedKeyboardAnimation } from 'react-native-keyboard-controller'+import Animated, { useAnimatedStyle } from 'react-native-reanimated'++import type { getConversation } from '@/api/conversations'+import { useProjectScope } from '@/auth/useProjectScope'+import { track } from '@/lib/analytics'+import { conversationWebUrl } from '@/model/adapters/chats'+import { READING_WIDTH } from '@/ui/adaptiveLayout'+import { OverlayHost } from '@/ui/OverlayPortal'+import { Pressable44 } from '@/ui/Pressable44'+import { createStyles, useColors } from '@/ui/theme'+import { radii, type } from '@/ui/tokens'+import { useScreenInsets } from '@/ui/useScreenInsets'++import { ChatAccessGate } from '../ChatAccessGate'+import { ChatEmptyState } from '../ChatEmptyState'+import { ChatErrorNotice } from '../ChatErrorNotice'+import { CHAT_HEADER_HEIGHT, ChatHeader } from '../ChatHeader'+import { type ChatSheetSource, useChatSheetEvents } from '../chatSheetEvents'+import { SessionThread, type SessionThreadState } from '../session/SessionThread'+import { useChatDraft } from '../useChatDraft'+import { ClassicComposer } from './ClassicComposer'+import { classicThreadItems } from './classicMessages'+import { useClassicChat } from './useClassicChat'++interface ClassicChatScreenProps {+ conversationId?: string+ initialConversation?: Awaited<ReturnType<typeof getConversation>>+ source: ChatSheetSource+ autoFocus: boolean+ onBack: () => void+ onNewChat: () => void+}++export function ClassicChatScreen({+ conversationId,+ initialConversation,+ source,+ autoFocus,+ onBack,+ onNewChat,+}: ClassicChatScreenProps): ReactElement {+ const colors = useColors()+ const styles = useStyles()+ const chat = useClassicChat(conversationId, initialConversation)+ const events = useChatSheetEvents(+ { ...source, conversationId: chat.id, runtime: 'langgraph', hasContext: false, resumed: !!conversationId },+ null+ )+ const scope = useProjectScope()+ const insets = useScreenInsets()+ const blurTarget = useRef<ViewInstance>(null)+ const input = useRef<TextInputInstance>(null)+ const draft = useChatDraft(chat.id, undefined, false, 'conversation')+ const [sending, setSending] = useState(false)+ const [saving, setSaving] = useState(false)+ const saveLock = useRef(false)+ const sendLock = useRef(false)+ const lifetime = useRef(0)+ useEffect(+ () => () => {+ lifetime.current+++ },+ []+ )+ const keyboard = useReanimatedKeyboardAnimation()+ const keyboardStyle = useAnimatedStyle(() => ({ paddingBottom: Math.max(-keyboard.height.value, insets.bottom) }))+ const projectUrl = scope ? `${scope.host.replace(/\/$/, '')}/project/${scope.projectId}` : ''+ const items = useMemo(() => classicThreadItems(chat.state, projectUrl), [chat.state, projectUrl])+ const thread: SessionThreadState = {+ history: {+ status: items.length > 0 ? 'idle' : chat.loading ? 'loading' : chat.historyError ? 'error' : 'idle',+ error: chat.historyError ? { kind: 'unknown', message: chat.historyError } : null,+ },+ items,+ invocations: new Map(),+ phase: chat.working ? 'working' : 'idle',+ stage: chat.state.progress ?? undefined,+ runStatus: null,+ }+ const send = async (): Promise<void> => {+ const text = draft.draft.text.trim()+ if (!text || sendLock.current || chat.working || chat.loading || !draft.ready) return+ sendLock.current = true+ setSending(true)+ const generation = lifetime.current+ try {+ const settle = await draft.beginSend({ text, reportIds: [] })+ if (generation !== lifetime.current) {+ await settle(false)+ return+ }+ let settled = false+ const accepted = await chat.send(text, async () => {+ await settle(true)+ settled = true+ })+ if (!settled) await settle(accepted)+ if (accepted) {+ events.countSent()+ track('mobile_session_sent', { agent_runtime: 'langgraph', conversation_id: chat.id })+ }+ } finally {+ sendLock.current = false+ if (generation === lifetime.current) setSending(false)+ }+ }+ const retrySave = async (): Promise<void> => {+ if (saveLock.current) return+ saveLock.current = true+ setSaving(true)+ try {+ await draft.retrySave()+ } finally {+ saveLock.current = false+ setSaving(false)+ }+ }+ const close = (): void => {+ lifetime.current+++ Keyboard.dismiss()+ onBack()+ }+ const approval = chat.state.approval+ const inputRef = useCallback(+ (node: TextInputInstance | null): void => {+ input.current = node+ if (autoFocus) node?.focus()+ },+ [autoFocus]+ )+ return (+ <View style={styles.screen} testID="classic-chat-screen">+ <OverlayHost>+ <BlurTargetView ref={blurTarget} style={styles.content}>+ <Animated.View style={[styles.fill, keyboardStyle]}>+ {!chat.loading && !chat.historyError && items.length === 0 ? (+ <ScrollView+ style={styles.fill}+ contentContainerStyle={{+ flexGrow: 1,+ paddingTop: insets.top + CHAT_HEADER_HEIGHT,+ paddingBottom: 16,+ }}+ keyboardShouldPersistTaps="handled"+ keyboardDismissMode="on-drag"+ >+ <ChatEmptyState+ reportCount={0}+ description="Ask about your product and explore your data."+ suggestedPrompts={[+ 'Summarize this week',+ 'What are my top events?',+ 'Where are users dropping off?',+ ]}+ onPrompt={(text) => draft.change({ text, reportIds: [] })}+ />+ </ScrollView>+ ) : (+ <SessionThread+ session={thread}+ onRetryHistory={() => void chat.reload()}+ topInset={insets.top + CHAT_HEADER_HEIGHT}+ />+ )}+ {items.length > 0 && (chat.historyError || chat.loading) ? (+ <View style={styles.recovery}>+ <ChatErrorNotice+ message={chat.historyError ?? 'Reconnecting…'}+ actions={+ <Pressable44+ disabled={chat.loading || chat.working}+ accessibilityRole="button"+ accessibilityLabel="Reconnect"+ onPress={() => void chat.reload()}+ style={styles.action}+ >+ {chat.loading ? <ActivityIndicator color={colors.ink} /> : null}+ <Text style={styles.label}>Reconnect</Text>+ </Pressable44>+ }+ />+ </View>+ ) : null}+ <ChatAccessGate onDecline={close}>+ {draft.draftError ? (+ <ChatErrorNotice+ message={draft.draftError}+ actions={+ <Pressable44+ disabled={saving}+ accessibilityRole="button"+ accessibilityLabel="Retry saving draft"+ onPress={() => void retrySave()}+ style={styles.action}+ >+ {saving ? <ActivityIndicator color={colors.ink} /> : null}+ <Text style={styles.label}>Retry saving draft</Text>+ </Pressable44>+ }+ />+ ) : null}+ {chat.error ? <ChatErrorNotice message={chat.error} onDismiss={chat.dismissError} /> : null}+ {approval ? (+ <View style={styles.approval} testID="classic-approval">+ <Text style={styles.label}>{approval.toolName}</Text>+ <Text style={styles.body}>{approval.preview}</Text>+ <View style={styles.actions}>+ {chat.working ? <ActivityIndicator color={colors.ink} /> : null}+ <Pressable44+ disabled={chat.working}+ accessibilityRole="button"+ accessibilityLabel="Reject change"+ onPress={() => void chat.answer(false)}+ style={styles.action}+ >+ <Text style={styles.label}>Reject</Text>+ </Pressable44>+ <Pressable44+ disabled={chat.working}+ accessibilityRole="button"+ accessibilityLabel="Approve change"+ onPress={() => void chat.answer(true)}+ style={styles.action}+ >+ <Text style={styles.label}>Approve</Text>+ </Pressable44>+ </View>+ </View>+ ) : (+ <ClassicComposer+ ref={inputRef}+ text={draft.draft.text}+ onChangeText={(text) => draft.change({ ...draft.draft, text })}+ onSend={() => void send()}+ onStop={() => void chat.stop()}+ disabled={!draft.ready || chat.loading || !!chat.historyError || sending}+ working={chat.working}+ stopping={chat.stopping}+ />+ )}+ </ChatAccessGate>+ </Animated.View>+ </BlurTargetView>+ <ChatHeader+ blurTarget={blurTarget}+ webUrl={conversationWebUrl(scope, chat.id)}+ onBack={close}+ onNewChat={() => {+ lifetime.current+++ events.countNewChat()+ chat.reset()+ onNewChat()+ }}+ />+ </OverlayHost>+ </View>+ )+}++const useStyles = createStyles(({ colors }) => ({+ screen: { flex: 1, backgroundColor: colors.surface },+ fill: { flex: 1 },+ content: { flex: 1, width: '100%', maxWidth: READING_WIDTH, alignSelf: 'center' },+ recovery: { margin: 10 },+ approval: {+ margin: 10,+ padding: 12,+ borderWidth: 1,+ borderColor: colors.hairline,+ borderRadius: radii.card,+ gap: 8,+ },+ label: { ...type.bodyStrong, color: colors.ink },+ body: { ...type.body, color: colors.ink },+ actions: { flexDirection: 'row', justifyContent: 'flex-end', gap: 8 },+ action: { paddingHorizontal: 12, backgroundColor: colors.sunken, borderRadius: radii.pill },+}))diff --git a/products/mobile/src/features/chat/classic/ClassicComposer.tsx b/products/mobile/src/features/chat/classic/ClassicComposer.tsxnew file mode 100644index 000000000000..9e916f24edf7--- /dev/null+++ b/products/mobile/src/features/chat/classic/ClassicComposer.tsx@@ -0,0 +1,95 @@+import { forwardRef, type ReactElement } from 'react'+import { ActivityIndicator, TextInput, type TextInputInstance, View } from 'react-native'++import { ArrowUpIcon } from '@/ui/icons/ArrowUpIcon'+import { Pressable44 } from '@/ui/Pressable44'+import { createStyles, useTheme } from '@/ui/theme'+import { iconSizes, inputReset, radii, type } from '@/ui/tokens'++interface ClassicComposerProps {+ text: string+ onChangeText: (text: string) => void+ onSend: () => void+ onStop: () => void+ disabled: boolean+ working: boolean+ stopping: boolean+}++export const ClassicComposer = forwardRef<TextInputInstance, ClassicComposerProps>(function ClassicComposer(+ { text, onChangeText, onSend, onStop, disabled, working, stopping },+ ref+): ReactElement {+ const { colors, shadows, scheme } = useTheme()+ const styles = useStyles()+ const canSend = !disabled && !working && text.trim().length > 0+ return (+ <View style={[styles.card, shadows.popover]}>+ <TextInput+ ref={ref}+ value={text}+ onChangeText={onChangeText}+ placeholder="Ask anything…"+ placeholderTextColor={colors.tertiary}+ accessibilityLabel="Message"+ keyboardAppearance={scheme}+ multiline+ returnKeyType="send"+ submitBehavior="submit"+ onSubmitEditing={() => canSend && onSend()}+ style={styles.input}+ testID="chat-input"+ />+ <View style={styles.toolbar}>+ {working ? (+ <Pressable44+ onPress={onStop}+ disabled={stopping}+ accessibilityLabel="Stop the reply"+ accessibilityState={{ disabled: stopping }}+ style={styles.send}+ testID="chat-stop"+ >+ {stopping ? <ActivityIndicator color={colors.white} /> : <View style={styles.stopSquare} />}+ </Pressable44>+ ) : (+ <Pressable44+ onPress={onSend}+ disabled={!canSend}+ accessibilityLabel="Send"+ accessibilityState={{ disabled: !canSend }}+ style={[styles.send, !canSend && styles.disabled]}+ testID="chat-send"+ >+ <ArrowUpIcon size={iconSizes.control} color={colors.white} />+ </Pressable44>+ )}+ </View>+ </View>+ )+})++const useStyles = createStyles(({ colors }) => ({+ card: {+ marginHorizontal: 10,+ marginBottom: 10,+ borderWidth: 1,+ borderColor: colors.hairline,+ borderRadius: radii.softCard,+ backgroundColor: colors.surface,+ padding: 12,+ gap: 10,+ },+ input: { ...inputReset, ...type.input, color: colors.ink, minHeight: 40, maxHeight: 120 },+ toolbar: { alignItems: 'flex-end' },+ send: {+ width: 40,+ height: 40,+ borderRadius: radii.pill,+ backgroundColor: colors.ink,+ alignItems: 'center',+ justifyContent: 'center',+ },+ disabled: { backgroundColor: colors.border },+ stopSquare: { width: 12, height: 12, borderRadius: 2, backgroundColor: colors.surface },+}))diff --git a/products/mobile/src/features/chat/classic/useClassicChat.test.tsx b/products/mobile/src/features/chat/classic/useClassicChat.test.tsxindex 44632a7f5bf4..c25477fec6ca 100644--- a/products/mobile/src/features/chat/classic/useClassicChat.test.tsx+++ b/products/mobile/src/features/chat/classic/useClassicChat.test.tsx@@ -1,5 +1,5 @@import { QueryClient, QueryClientProvider } from '@tanstack/react-query'-import { act, renderHook } from '@testing-library/react-native'+import { act, renderHook, waitFor } from '@testing-library/react-native'import { randomUUID } from 'expo-crypto'import { type PropsWithChildren, type ReactElement, useState } from 'react'@@ -8,6 +8,7 @@ import { cancelConversation, getConversation, streamConversation } from '@/api/cimport { readSse } from '@/api/sse'import { REQUEST_TIMEOUT_MS } from '@/api/transport'import { useProjectScope } from '@/auth/useProjectScope'+import { currentAiIdentity, useAiApproval } from '@/features/ai/aiApproval'import { useClassicChat } from './useClassicChat'@@ -16,6 +17,7 @@ jest.mock('@/api/conversations', () => ({getConversation: jest.fn(),streamConversation: jest.fn(),}))+jest.mock('@/features/ai/aiApproval', () => ({ currentAiIdentity: jest.fn(), useAiApproval: jest.fn() }))jest.mock('@/api/sse', () => ({ readSse: jest.fn() }))jest.mock('expo-crypto', () => ({ randomUUID: jest.fn() }))jest.mock('@/auth/useProjectScope', () => ({ useProjectScope: jest.fn(() => null) }))@@ -33,12 +35,16 @@ describe('classic chat transport', () => {beforeEach(() => {jest.resetAllMocks()jest.mocked(useProjectScope).mockReturnValue(null)+ jest.mocked(currentAiIdentity).mockReturnValue('origin-project')+ const approval = { request: jest.fn(async () => true), pending: false, signal: new AbortController().signal }+ jest.mocked(useAiApproval).mockReturnValue(approval)let id = 0jest.mocked(randomUUID).mockImplementation(() => `00000000-0000-4000-8000-${String(++id).padStart(12, '0')}`)jest.mocked(streamConversation).mockResolvedValue({} as Response)jest.mocked(getConversation).mockResolvedValue({messages: [],title: 'A chat',+ status: 'idle',pending_approvals: [],} as unknown as Awaited<ReturnType<typeof getConversation>>)jest.mocked(readSse).mockResolvedValue()@@ -109,6 +115,7 @@ describe('classic chat transport', () => {await Promise.resolve()})act(() => result.current.reset())+ await waitFor(() => expect(readSse).toHaveBeenCalled())await act(async () => {finish()await pending@@ -119,6 +126,7 @@ describe('classic chat transport', () => {test('offers history recovery after an accepted stream disconnects', async () => {jest.mocked(readSse).mockRejectedValueOnce(new TypeError('Connection lost'))+ jest.mocked(getConversation).mockRejectedValueOnce(new TypeError('Connection lost'))const { result } = renderHook(() => useClassicChat(), { wrapper })await act(async () => {expect(await result.current.send('Question')).toBe(true)@@ -129,6 +137,36 @@ describe('classic chat transport', () => {expect(getConversation).toHaveBeenCalledWith(result.current.id, expect.any(AbortSignal))})+ test('ignores recovered history after starting a new chat', async () => {+ let recover!: (saved: Awaited<ReturnType<typeof getConversation>>) => void+ jest.mocked(readSse).mockRejectedValueOnce(new TypeError('Connection lost'))+ jest.mocked(getConversation).mockReturnValueOnce(+ new Promise((resolve) => {+ recover = resolve+ })+ )+ const { result } = renderHook(() => useClassicChat(), { wrapper })+ let pending!: Promise<boolean>+ await act(async () => {+ pending = result.current.send('Question')+ await Promise.resolve()+ })+ await waitFor(() => expect(getConversation).toHaveBeenCalledTimes(1))+ act(() => result.current.reset())+ await act(async () => {+ recover({+ messages: [{ id: 'reply-1', type: 'ai', content: 'Old reply' }],+ title: 'Old chat',+ status: 'idle',+ pending_approvals: [],+ } as unknown as Awaited<ReturnType<typeof getConversation>>)+ await pending+ })+ expect(result.current.id).toBeNull()+ expect(result.current.state.messages).toEqual([])+ expect(result.current.historyError).toBeNull()+ })+test('guards duplicate cancellation requests', async () => {let finish!: () => voidjest.mocked(cancelConversation).mockImplementation(@@ -265,33 +303,55 @@ describe('classic chat transport', () => {expect(getConversation).toHaveBeenCalledTimes(2)expect(result.current.state.title).toBe('A chat')})- test('exposes recovery and releases the lock after an accepted stream stalls', async () => {- jest.useFakeTimers()- const reader = {- read: () => new Promise(() => undefined),- cancel: jest.fn(async () => undefined),+ test.each(['idle', 'in_progress', 'unavailable'] as const)(+ 'checks saved history after an accepted stream stalls with %s history',+ async (status) => {+ jest.useFakeTimers()+ const saved = {+ messages: [+ { id: 'human-1', type: 'human', content: 'Question' },+ { id: 'reply-1', type: 'ai', content: 'Saved reply' },+ ],+ title: 'A chat',+ status,+ pending_approvals: [],+ } as unknown as Awaited<ReturnType<typeof getConversation>>+ if (status === 'unavailable') jest.mocked(getConversation).mockRejectedValueOnce(new TypeError('Offline'))+ else jest.mocked(getConversation).mockResolvedValueOnce(saved)+ const reader = {+ read: () => new Promise(() => undefined),+ cancel: jest.fn(async () => undefined),+ }+ jest.mocked(streamConversation).mockResolvedValueOnce({+ body: { getReader: () => reader },+ } as unknown as Response)+ jest.mocked(readSse).mockImplementationOnce(jest.requireActual('@/api/sse').readSse)+ const { result } = renderHook(() => useClassicChat(), { wrapper })+ let pending!: Promise<boolean>+ await act(async () => {+ pending = result.current.send('Question')+ await Promise.resolve()+ })+ await act(async () => {+ await jest.advanceTimersByTimeAsync(60_000)+ expect(await pending).toBe(true)+ })+ expect(result.current.working).toBe(false)+ expect(streamConversation).toHaveBeenCalledTimes(1)+ expect(getConversation).toHaveBeenCalledTimes(1)+ if (status === 'idle') {+ expect(result.current.historyError).toBeNull()+ expect(result.current.state.messages.at(-1)?.data.content).toBe('Saved reply')+ } else {+ expect(result.current.historyError).toContain('Reconnect')+ expect(result.current.state.messages[0]?.data.content).toBe('Question')+ }+ expect(reader.cancel).toHaveBeenCalled()+ await act(async () => result.current.reload())+ expect(result.current.historyError).toBeNull()}- jest.mocked(streamConversation).mockResolvedValueOnce({- body: { getReader: () => reader },- } as unknown as Response)- jest.mocked(readSse).mockImplementationOnce(jest.requireActual('@/api/sse').readSse)- const { result } = renderHook(() => useClassicChat(), { wrapper })- let pending!: Promise<boolean>- await act(async () => {- pending = result.current.send('Question')- await Promise.resolve()- })- await act(async () => {- await jest.advanceTimersByTimeAsync(60_000)- expect(await pending).toBe(true)- })- expect(result.current.working).toBe(false)- expect(result.current.historyError).toContain('Reconnect')- expect(reader.cancel).toHaveBeenCalled()- await act(async () => result.current.reload())- expect(result.current.historyError).toBeNull()- })- test.each(['stream', 'history'])(+ )+ test.each(['stream', 'history', 'snapshot'])('exposes and resumes forms from %s without reconnecting or duplicating submissions',async (source) => {const form = {@@ -303,21 +363,29 @@ describe('classic chat transport', () => {}const message = { id: 'form-message', type: 'ai', content: '', tool_calls: [form] }const saved = {+ id: 'saved-chat',messages: [message],title: 'A chat',pending_approvals: [],status: 'in_progress',} as unknown as Awaited<ReturnType<typeof getConversation>>if (source === 'history') jest.mocked(getConversation).mockResolvedValueOnce(saved)- const { result } = renderHook(() => useClassicChat(source === 'history' ? 'saved-chat' : undefined), {- wrapper,- })+ const { result } = renderHook(+ () =>+ useClassicChat(+ source === 'stream' ? undefined : 'saved-chat',+ source === 'snapshot' ? saved : undefined+ ),+ { wrapper }+ )await act(async () => undefined)if (source === 'stream') {jest.mocked(readSse).mockImplementationOnce(async (_response, onEvent) => {onEvent({ event: 'message', data: JSON.stringify(message) })})- jest.mocked(getConversation).mockRejectedValueOnce(new Error('Connection lost'))+ jest.mocked(getConversation)+ .mockRejectedValueOnce(new Error('Connection lost'))+ .mockRejectedValueOnce(new Error('Connection lost'))await act(async () => {await result.current.send('Question')})@@ -362,4 +430,122 @@ describe('classic chat transport', () => {expect(result.current.state.messages).toEqual([])})++ test.each(['send', 'approve', 'reject'] as const)('checks AI approval before %s', async (action) => {+ const saved = {+ id: 'saved-chat',+ title: 'Saved chat',+ status: 'idle',+ messages: [{ id: 'human-1', type: 'human', content: 'Show my events' }],+ pending_approvals: [{ proposal_id: 'proposal-1', decision_status: 'pending', tool_name: 'Update insight' }],+ } as unknown as Awaited<ReturnType<typeof getConversation>>+ const { result } = renderHook(() => useClassicChat(saved.id, saved), { wrapper })+ const approval = jest.mocked(useAiApproval).mock.results[0]?.value as ReturnType<typeof useAiApproval>+ jest.mocked(approval.request).mockResolvedValueOnce(false)+ await act(async () => {+ expect(+ await (action === 'send'+ ? result.current.send('Question')+ : result.current.answer(action === 'approve'))+ ).toBe(false)+ })+ expect(streamConversation).not.toHaveBeenCalled()+ expect(result.current.working).toBe(false)+ expect(result.current.state.messages[0]?.data.content).toBe('Show my events')+ expect(getConversation).not.toHaveBeenCalled()+ })++ test.each(['unmount', 'project'] as const)('ignores a prepared send after %s', async (transition) => {+ const { result, unmount } = renderHook(() => useClassicChat(), { wrapper })+ const send = result.current.send+ if (transition === 'unmount') unmount()+ else if (transition === 'project') jest.mocked(currentAiIdentity).mockReturnValue('other-project')+ await act(async () => {+ expect(await send('Question')).toBe(false)+ })+ expect(streamConversation).not.toHaveBeenCalled()+ })++ test.each(['unmount', 'project', 'reset'] as const)('abandons an approval check after %s', async (transition) => {+ let approve!: (value: boolean) => void+ const { result, unmount } = renderHook(() => useClassicChat(), { wrapper })+ const approval = jest.mocked(useAiApproval).mock.results[0]?.value as ReturnType<typeof useAiApproval>+ jest.mocked(approval.request).mockReturnValueOnce(+ new Promise((resolve) => {+ approve = resolve+ })+ )+ let sending!: Promise<boolean>+ act(() => {+ sending = result.current.send('Question')+ })+ if (transition === 'unmount') unmount()+ else if (transition === 'project') jest.mocked(currentAiIdentity).mockReturnValue('other-project')+ else act(() => result.current.reset())+ await act(async () => {+ approve(true)+ expect(await sending).toBe(false)+ })+ expect(streamConversation).not.toHaveBeenCalled()+ })++ test.each(['idle', 'in_progress'] as const)(+ 'reuses loaded %s history and can explicitly reload',+ async (status) => {+ const saved = {+ id: 'saved-chat',+ title: 'Saved chat',+ status,+ messages: [{ id: 'message-1', type: 'human', content: 'Saved question' }],+ pending_approvals: [],+ } as unknown as Awaited<ReturnType<typeof getConversation>>+ let finish!: () => void+ jest.mocked(readSse).mockImplementation(+ () =>+ new Promise((resolve) => {+ finish = resolve+ })+ )+ const { result } = renderHook(() => useClassicChat(saved.id, saved), { wrapper })+ expect(result.current.state.messages[0]?.data.content).toBe('Saved question')+ expect(result.current.loading).toBe(false)+ expect(getConversation).not.toHaveBeenCalled()+ if (status === 'in_progress') {+ await waitFor(() => expect(readSse).toHaveBeenCalled())+ expect(streamConversation).toHaveBeenCalledWith(+ expect.objectContaining({ conversation: saved.id, content: null }),+ expect.any(AbortSignal)+ )+ await act(async () => {+ finish()+ })+ }+ await act(async () => {+ await result.current.reload()+ })+ expect(getConversation).toHaveBeenCalledWith(saved.id, expect.any(AbortSignal))+ }+ )+ test('reports acceptance before the reply finishes', async () => {+ let finish!: () => void+ jest.mocked(readSse).mockImplementation(+ () =>+ new Promise((resolve) => {+ finish = resolve+ })+ )+ const accepted = jest.fn(async () => undefined)+ const { result } = renderHook(() => useClassicChat(), { wrapper })+ let sending!: Promise<boolean>+ act(() => {+ sending = result.current.send('A question', accepted)+ })+ await waitFor(() => expect(readSse).toHaveBeenCalled())+ expect(accepted).toHaveBeenCalledTimes(1)+ expect(result.current.working).toBe(true)+ await act(async () => {+ finish()+ expect(await sending).toBe(true)+ })+ })})diff --git a/products/mobile/src/features/chat/classic/useClassicChat.ts b/products/mobile/src/features/chat/classic/useClassicChat.tsindex 9efe6679f3a7..d06599426f6a 100644--- a/products/mobile/src/features/chat/classic/useClassicChat.ts+++ b/products/mobile/src/features/chat/classic/useClassicChat.ts@@ -7,6 +7,7 @@ import { cancelConversation, getConversation, streamConversation } from '@/api/cimport { readSse } from '@/api/sse'import { requestWithDeadline } from '@/api/transport'import { useProjectScope } from '@/auth/useProjectScope'+import { currentAiIdentity, useAiApproval } from '@/features/ai/aiApproval'import { conversationListKeys } from '@/features/chats/conversationKeys'import { sessionListKeys } from '@/features/chats/hooks'@@ -19,7 +20,10 @@ import {reduceClassicEvent,} from './classicMessages'-export function useClassicChat(initialId?: string): {+export function useClassicChat(+ initialId?: string,+ initialConversation?: Awaited<ReturnType<typeof getConversation>>+): {id: string | nullstate: typeof EMPTY_CLASSIC_STATEloading: boolean@@ -27,7 +31,7 @@ export function useClassicChat(initialId?: string): {working: booleanstopping: booleanerror: string | null- send: (text: string) => Promise<boolean>+ send: (text: string, onAccepted?: () => Promise<void>) => Promise<boolean>answer: (approved: boolean) => Promise<boolean>form: ClassicForm | nullsubmitForm: (answers: Record<string, string | string[]>) => Promise<boolean>@@ -39,10 +43,21 @@ export function useClassicChat(initialId?: string): {} {const scope = useProjectScope()const client = useQueryClient()+ const approval = useAiApproval('chat', initialId ?? 'new')+ const openedIdentity = useRef(currentAiIdentity())+ const initialSnapshot = useRef(initialConversation?.id === initialId ? initialConversation : undefined)const [id, setId] = useState<string | null>(initialId ?? null)const idRef = useRef(id)- const [state, setState] = useState(EMPTY_CLASSIC_STATE)- const [loading, setLoading] = useState(!!initialId)+ const [state, setState] = useState(() =>+ initialSnapshot.current+ ? classicHistory(+ initialSnapshot.current.messages,+ initialSnapshot.current.title,+ initialSnapshot.current.pending_approvals+ )+ : EMPTY_CLASSIC_STATE+ )+ const [loading, setLoading] = useState(!!initialId && !initialSnapshot.current)const [historyError, setHistoryError] = useState<string | null>(null)const [working, setWorking] = useState(false)const [stopping, setStopping] = useState(false)@@ -51,6 +66,7 @@ export function useClassicChat(initialId?: string): {const stopBusy = useRef(false)const reloadBusy = useRef(false)const epoch = useRef(0)+ const mounted = useRef(true)const controller = useRef<AbortController | null>(null)const stream = useCallback(@@ -59,25 +75,31 @@ export function useClassicChat(initialId?: string): {resumePayload?:| { proposal_id: string; action: 'approve' | 'reject' }| { action: 'form'; form_answers: Record<string, string | string[]> }- | { action: 'dismiss_form' }+ | { action: 'dismiss_form' },+ onAccepted?: () => Promise<void>): Promise<boolean> => {- if (busy.current) return false- busy.current = trueconst generation = epoch.current- const active = (): boolean => generation === epoch.current+ const active = (): boolean =>+ mounted.current &&+ generation === epoch.current &&+ !approval.signal.aborted &&+ currentAiIdentity() === openedIdentity.current+ if (busy.current || !active()) return false+ busy.current = true+ setWorking(true)const conversation = idRef.current ?? randomUUID()- idRef.current = conversationconst traceId = randomUUID()const abort = new AbortController()- controller.current = abort- setWorking(true)- setError(null)- setState((previous) => {- const next = { ...previous, error: null }- return content ? appendClassicMessage(next, { type: 'human', content, trace_id: traceId }) : next- })let accepted = falsetry {+ if (!(await approval.request()) || !active()) return false+ idRef.current = conversation+ controller.current = abort+ setError(null)+ setState((previous) => {+ const next = { ...previous, error: null }+ return content ? appendClassicMessage(next, { type: 'human', content, trace_id: traceId }) : next+ })const response = await requestWithDeadline((signal) =>streamConversation(@@ -93,6 +115,7 @@ export function useClassicChat(initialId?: string): {abort.signal)accepted = true+ await onAccepted?.()if (!active()) return trueidRef.current = conversationsetId(conversation)@@ -117,7 +140,20 @@ export function useClassicChat(initialId?: string): {} catch (failure) {if (active() && !abort.signal.aborted) {if (accepted) {- setHistoryError('The reply was interrupted. Reconnect to load the latest messages.')+ try {+ const saved = await getConversation(conversation, abort.signal)+ if (!active()) return true+ const history = classicHistory(saved.messages, saved.title, saved.pending_approvals)+ if (saved.status === 'idle' || history.approval || history.form) {+ setState((previous) => ({ ...history, error: previous.error }))+ setHistoryError(null)+ } else {+ setHistoryError('The reply was interrupted. Reconnect to load the latest messages.')+ }+ } catch {+ if (active() && !abort.signal.aborted)+ setHistoryError('The reply was interrupted. Reconnect to load the latest messages.')+ }} else {setError(toChatError(failure).message)}@@ -147,7 +183,7 @@ export function useClassicChat(initialId?: string): {}}},- [client, scope]+ [client, scope, approval.request, approval.signal])const reload = useCallback(async (): Promise<void> => {@@ -218,12 +254,28 @@ export function useClassicChat(initialId?: string): {}, [invalidate])useEffect(() => {+ mounted.current = truereset()idRef.current = initialId ?? nullsetId(initialId ?? null)- if (initialId) void reload()- return invalidate- }, [initialId, reload, reset, invalidate])+ const saved = initialSnapshot.current?.id === initialId ? initialSnapshot.current : undefined+ if (saved) {+ const history = classicHistory(saved.messages, saved.title, saved.pending_approvals)+ setState(history)+ if (+ saved.status === 'in_progress' &&+ !saved.pending_approvals.some((approval) => approval.decision_status === 'pending') &&+ !history.form+ )+ void stream(null)+ } else if (initialId) {+ void reload()+ }+ return () => {+ mounted.current = false+ invalidate()+ }+ }, [initialId, reload, reset, invalidate, stream])return {id,@@ -233,7 +285,7 @@ export function useClassicChat(initialId?: string): {working,stopping,error: error ?? state.error,- send: (text) => stream(text),+ send: (text, onAccepted) => stream(text, undefined, onAccepted),answer: (approved) =>state.approval? stream(null, { proposal_id: state.approval.id, action: approved ? 'approve' : 'reject' })diff --git a/products/mobile/src/features/chat/session/SessionThread.tsx b/products/mobile/src/features/chat/session/SessionThread.tsxindex c7e785a6ac91..919c01dc4b3c 100644--- a/products/mobile/src/features/chat/session/SessionThread.tsx+++ b/products/mobile/src/features/chat/session/SessionThread.tsx@@ -18,8 +18,22 @@ import { ProgressRow } from './ProgressRow'import { errorItemText, groupSessionItems, shouldShowRunError } from './sessionDisplay'import type { Session, SessionAssistantItem, SessionDisplayItem, SessionErrorItem } from './types'+export type SessionThreadState = Pick<+ Session,+ | 'history'+ | 'items'+ | 'invocations'+ | 'phase'+ | 'stage'+ | 'decision'+ | 'pullRequests'+ | 'pullRequest'+ | 'runStatus'+ | 'runError'+>+interface SessionThreadProps {- session: Session+ session: SessionThreadStateonRetryHistory: () => voidtopInset?: number}@@ -42,7 +56,7 @@ const TurnEndRow = memo(function TurnEndRow(): ReactElement {return <View style={styles.turnEnd} />})-function statusLine(session: Session): string | null {+function statusLine(session: SessionThreadState): string | null {switch (session.phase) {case 'working':return session.stage ?? 'Thinking…'diff --git a/products/mobile/src/features/chat/useChatDraft.ts b/products/mobile/src/features/chat/useChatDraft.tsindex 0d4098f86fcb..005f7c73d275 100644--- a/products/mobile/src/features/chat/useChatDraft.ts+++ b/products/mobile/src/features/chat/useChatDraft.ts@@ -17,7 +17,8 @@ interface DraftTarget {export function useChatDraft(taskId: string | null,reportId: string | undefined,- demo = false+ demo = false,+ kind: 'task' | 'conversation' = 'task'): {draft: ChatDraftqueue: QueueState@@ -37,7 +38,13 @@ export function useChatDraft(const userId = useAuthStore((state) => state.user?.uuid)const projectId = useAuthStore((state) => state.projectId)const identity = !demo && signedIn && host && userId && projectId !== null ? draftIdentity() : null- const key = taskId ? `task:${taskId}` : reportId ? `report:${reportId}` : 'new-chat'+ const key = taskId+ ? `${kind}:${taskId}`+ : reportId+ ? `report:${reportId}`+ : kind === 'conversation'+ ? 'new-classic-chat'+ : 'new-chat'const initial = { text: '', reportIds: reportId ? [reportId] : [] }const [draft, setDraft] = useState<ChatDraft>(initial)const [queue, setQueue] = useState<QueueState>(EMPTY_QUEUE)@@ -128,7 +135,7 @@ export function useChatDraft(setQueueError(undefined)const previous = target.currentconst prior = previousDestination.current- const adopting = prior.identity === identity && !prior.key.startsWith('task:') && key.startsWith('task:')+ const adopting = prior.identity === identity && !prior.key.startsWith(`${kind}:`) && key.startsWith(`${kind}:`)previousDestination.current = { identity, key }if (!adopting) {destination.current++@@ -206,7 +213,7 @@ export function useChatDraft(mounted.current = falsecancelled = true}- }, [identity, key, reportId, flush])+ }, [identity, key, reportId, flush, kind])const updateQueue = useCallback(async (action: QueueAction, clearComposer = false): Promise<boolean> => {diff --git a/products/mobile/src/features/chats/ChatRow.tsx b/products/mobile/src/features/chats/ChatRow.tsxindex 59a269ea1731..680df2a82f03 100644--- a/products/mobile/src/features/chats/ChatRow.tsx+++ b/products/mobile/src/features/chats/ChatRow.tsx@@ -33,6 +33,7 @@ export const ChatRow = memo(function ChatRow({ item, now, onOpen, onLongPress }:const colors = useColors()const styles = useStyles()const menu = useMenuTrigger(item, onLongPress)+ const hasActions = item.kind !== 'conversation'const when = formatRelativeAgo(item.updatedAt, now)const status = sessionStatusDisplay(item.status, colors)const origin = ORIGIN_LABEL[item.origin]@@ -41,9 +42,9 @@ export const ChatRow = memo(function ChatRow({ item, now, onOpen, onLongPress }:<Pressable44ref={menu.ref}onPress={() => onOpen(item)}- onLongPress={menu.onLongPress}- accessibilityActions={menu.accessibilityActions}- onAccessibilityAction={menu.onAccessibilityAction}+ onLongPress={hasActions ? menu.onLongPress : undefined}+ accessibilityActions={hasActions ? menu.accessibilityActions : undefined}+ onAccessibilityAction={hasActions ? menu.onAccessibilityAction : undefined}pressedBackground={colors.sunken}style={styles.row}accessibilityLabel={`${item.title}, ${metaText}${item.pullRequestUrl ? ', has a pull request' : ''}`}diff --git a/products/mobile/src/features/chats/ChatsScreen.tsx b/products/mobile/src/features/chats/ChatsScreen.tsxindex 004934f8712c..56ad02d954f8 100644--- a/products/mobile/src/features/chats/ChatsScreen.tsx+++ b/products/mobile/src/features/chats/ChatsScreen.tsx@@ -1,8 +1,7 @@import { useQueryClient } from '@tanstack/react-query'import { useFocusEffect, useRouter } from 'expo-router'import { type ReactElement, useCallback, useEffect, useMemo, useRef, useState } from 'react'-import { RefreshControl, SectionList, View } from 'react-native'-+import { RefreshControl, SectionList, Text, View } from 'react-native'import { useProjectScope } from '@/auth/useProjectScope'import type { RowAnchor } from '@/features/inbox/contextMenuPlacement'import { useToasts, ViewsToast } from '@/features/views/ViewsToast'@@ -13,12 +12,14 @@ import { Eyebrow } from '@/ui/Eyebrow'import { ChatBubbleIcon } from '@/ui/icons/ChatBubbleIcon'import { SearchIcon } from '@/ui/icons/SearchIcon'import { WarningIcon } from '@/ui/icons/WarningIcon'+import { Pressable44 } from '@/ui/Pressable44'import { SearchField } from '@/ui/SearchField'import { LoadingView, StateView } from '@/ui/StateView'import { createStyles, useColors } from '@/ui/theme'-import { iconSizes, layout } from '@/ui/tokens'+import { iconSizes, layout, type } from '@/ui/tokens'import { topOffset, useScreenInsets, useTabBottomOffset } from '@/ui/useScreenInsets'+import { ChatErrorNotice } from '../chat/ChatErrorNotice'import { toChatError } from '../chat/chatErrors'import type { ChatSheetEntry } from '../chat/chatSheetEvents'import { TABS_HEADER_BOTTOM } from '../tabs/TabsHeader'@@ -26,7 +27,7 @@ import { useTabHeader } from '../tabs/tabHeaderStore'import { ChatRow } from './ChatRow'import { ChatRowMenu, type ChatRowMenuTarget } from './ChatRowMenu'import { filterChats, groupChats } from './chatGroups'-import { sessionListKeys, useArchiveChat, useChatList } from './hooks'+import { conversationListKeys, sessionListKeys, useArchiveChat, useChatList } from './hooks'interface ChatSection {label: string@@ -80,6 +81,7 @@ export function ChatsScreen(): ReactElement {}if (scope) {void queryClient.invalidateQueries({ queryKey: sessionListKeys.all(scope) })+ void queryClient.invalidateQueries({ queryKey: conversationListKeys.all(scope) })}}, [queryClient, scope]))@@ -92,7 +94,15 @@ export function ChatsScreen(): ReactElement {const openChat = useCallback((item: ChatListItem) => {const entry: ChatSheetEntry = searching ? 'chats_search' : 'chats_list'- router.push({ pathname: '/chat', params: { taskId: item.sourceId, entry, origin: item.origin } })+ router.push({+ pathname: '/chat',+ params: {+ [item.conversationId || item.kind === 'conversation' ? 'conversationId' : 'taskId']:+ item.conversationId ?? item.sourceId,+ entry,+ origin: item.origin,+ },+ })},[router, searching])@@ -204,6 +214,21 @@ export function ChatsScreen(): ReactElement {// An element, not a component, so typing does not remount the field and drop the keyboard.const listHeader = hasItems ? (<View style={styles.search}>+ {query.isError ? (+ <ChatErrorNotice+ message="Some chats couldn't load. Try again to load the rest."+ actions={+ <Pressable44+ disabled={query.isRefetching}+ accessibilityRole="button"+ accessibilityLabel="Retry loading chats"+ onPress={() => refresh('retry')}+ >+ <Text style={styles.retry}>Try again</Text>+ </Pressable44>+ }+ />+ ) : null}<SearchField value={search} onChangeText={setSearch} placeholder="Search chats" testID="chats-search" /></View>) : null@@ -247,6 +272,7 @@ const useStyles = createStyles(({ colors }) => ({flexGrow: 1,paddingHorizontal: layout.inboxGutter,},+ retry: { ...type.meta, color: colors.ink, padding: 8 },search: {marginTop: 4,marginBottom: 4,diff --git a/products/mobile/src/features/chats/hooks.test.tsx b/products/mobile/src/features/chats/hooks.test.tsxindex bd6ba8b51e10..d898b2a6d626 100644--- a/products/mobile/src/features/chats/hooks.test.tsx+++ b/products/mobile/src/features/chats/hooks.test.tsx@@ -2,11 +2,15 @@ import { QueryClient, QueryClientProvider } from '@tanstack/react-query'import { act, type RenderHookResult, renderHook, waitFor } from '@testing-library/react-native'import type { ReactElement, ReactNode } from 'react'+import { ApiError } from '@/api/client'+import { listConversations } from '@/api/conversations'import type { TaskSummaryApi } from '@/api/tasks'import { useAuthStore } from '@/auth/authStore'import { useArchiveChat, useChatList } from './hooks'+jest.mock('@/api/conversations', () => ({ listConversations: jest.fn().mockResolvedValue([]) }))+jest.mock('@react-native-async-storage/async-storage', () =>require('@react-native-async-storage/async-storage/jest/async-storage-mock'))@@ -19,6 +23,7 @@ jest.mock('@/demo/demoMode', () => ({...jest.requireActual('@/demo/demoMode'),useDataMode: () => 'live',}))+jest.mock('@/api/reports', () => ({ ...jest.requireActual('@/api/reports'), retryUnlessMissing: () => false }))jest.mock('@/api/tasks', () => ({ listMySessions: jest.fn(), setTaskArchived: jest.fn() }))const mocked = jest.requireMock('@/api/tasks') as {@@ -56,9 +61,43 @@ function renderChats(): RenderHookResult<ChatsHooks, unknown> {describe('chats hooks', () => {beforeEach(() => {jest.clearAllMocks()+ jest.mocked(listConversations).mockReset().mockResolvedValue([])})describe('useChatList', () => {+ test.each(['tasks', 'conversations'] as const)(+ 'preserves history when %s fail and retries',+ async (failedSource) => {+ useAuthStore.setState({+ user: { id: 7, uuid: 'u1', distinctId: 'd1', email: '[email protected]', name: 'A' },+ })+ const tasks = [session('task-1', '2026-10-15T10:00:00Z')]+ const conversations = [+ {+ id: 'conversation-1',+ title: 'Saved chat',+ task: null,+ created_at: '2026-10-15T10:00:00Z',+ updated_at: '2026-10-15T10:00:00Z',+ },+ ] as unknown as Awaited<ReturnType<typeof listConversations>>+ mocked.listMySessions.mockResolvedValue(tasks)+ jest.mocked(listConversations).mockResolvedValue(conversations)+ const failed = failedSource === 'tasks' ? mocked.listMySessions : jest.mocked(listConversations)+ failed.mockRejectedValueOnce(new ApiError(500, { detail: 'Try again' }))+ const { result } = renderChats()+ await waitFor(() => expect(result.current.list.isError).toBe(true))+ expect(result.current.list.data?.map((item) => item.sourceId)).toEqual([+ failedSource === 'tasks' ? 'conversation-1' : 'task-1',+ ])+ await act(async () => {+ await result.current.list.refetch()+ })+ await waitFor(() => expect(result.current.list.isError).toBe(false))+ expect(result.current.list.data).toHaveLength(2)+ }+ )+test.each<[string, string | null, boolean]>([['shows the account error when the reload fails', 'Your account did not load.', true],['shows an empty list when the reload brings no id', null, false],@@ -92,6 +131,15 @@ describe('chats hooks', () => {session('task-1', '2026-10-15T10:00:00Z'),session('task-2', '2026-10-14T10:00:00Z'),])+ jest.mocked(listConversations).mockResolvedValue([+ {+ id: 'conversation-1',+ title: 'Linked chat',+ task: { id: 'task-1', archived: false },+ created_at: '2026-10-15T10:00:00Z',+ updated_at: '2026-10-15T10:00:00Z',+ },+ ] as unknown as Awaited<ReturnType<typeof listConversations>>)})test.each([diff --git a/products/mobile/src/features/chats/hooks.ts b/products/mobile/src/features/chats/hooks.tsindex 3701c9e1ed4a..c40e7d2e6944 100644--- a/products/mobile/src/features/chats/hooks.ts+++ b/products/mobile/src/features/chats/hooks.ts@@ -2,6 +2,7 @@ import { useQuery, useQueryClient } from '@tanstack/react-query'import { useCallback, useEffect, useMemo, useRef, useState } from 'react'import { NotSignedInError } from '@/api/client'+import { listConversations } from '@/api/conversations'import { isMissingFeature, type ProjectScope, retryUnlessMissing, scopeKey } from '@/api/reports'import { listMySessions, setTaskArchived, type TaskSummaryApi } from '@/api/tasks'import { useAuthStore } from '@/auth/authStore'@@ -10,10 +11,14 @@ import { useDataMode, useDemoMode } from '@/demo/demoMode'import { useDemoChatsQuery } from '@/demo/hooks'import { useConnectivity } from '@/lib/connectivity'import { toError } from '@/lib/errors'-import { chatListFromSessions } from '@/model/adapters/chats'+import { mergeChatLists } from '@/model/adapters/chats'import { connectionLoadingQuery, errorQuery, loadingQuery, successQuery } from '@/model/queryStates'import type { ChatListItem, QueryState } from '@/model/types'+import { conversationListKeys } from './conversationKeys'++export { conversationListKeys } from './conversationKeys'+const CHAT_LIST_STALE_MS = 30_000/** Query keys for the chats list. Every key carries the host and project so a project switch never shows stale data. */@@ -59,24 +64,33 @@ function useLiveChatList(enabled: boolean): QueryState<ChatListItem[]> {staleTime: CHAT_LIST_STALE_MS,})+ const conversations = useQuery({+ queryKey: conversationListKeys.all(scope),+ queryFn: ({ signal }) => listConversations(signal),+ enabled: active,+ retry: retryUnlessMissing,+ staleTime: CHAT_LIST_STALE_MS,+ })+const failed = sessions.isError && sessions.data === undefined// A 403 or 404 from tasks means this user has no sandbox sessions to show, not a load that a retry can fix.const unavailable = failed && isMissingFeature(sessions.error)const items = useMemo(- () => (unavailable ? [] : chatListFromSessions(sessions.data, scope)),- [unavailable, sessions.data, scope]+ () => mergeChatLists(unavailable ? [] : sessions.data, conversations.data, scope),+ [unavailable, sessions.data, conversations.data, scope])const { refetch: refetchSessions } = sessions+ const { refetch: refetchConversations } = conversationsconst refetch = useCallback(async (): Promise<void> => {setPulling(true)try {- await refetchSessions()+ await Promise.all([refetchSessions(), refetchConversations()])} finally {setPulling(false)}- }, [refetchSessions])+ }, [refetchSessions, refetchConversations])if (!scope) {return errorQuery(new NotSignedInError())@@ -90,17 +104,24 @@ function useLiveChatList(enabled: boolean): QueryState<ChatListItem[]> {}return successQuery<ChatListItem[]>([], { refetch: reloadAccount })}- if (failed && !unavailable) {- return errorQuery(toError(sessions.error), refetch)+ const loadError =+ failed && !unavailable+ ? toError(sessions.error)+ : conversations.isError && !isMissingFeature(conversations.error)+ ? toError(conversations.error)+ : null+ const hasLoadedSource = sessions.data !== undefined || conversations.data !== undefined+ if (loadError && !hasLoadedSource) {+ return errorQuery(loadError, refetch)}- if (sessions.data === undefined && !unavailable) {+ if (!hasLoadedSource && ((sessions.data === undefined && !unavailable) || conversations.isPending)) {return connectionLoadingQuery<ChatListItem[]>(offline, refetch)}return {data: items,isLoading: false,- isError: false,- error: null,+ isError: loadError !== null,+ error: loadError,isRefetching: pulling,refetch,}@@ -133,19 +154,38 @@ function useLiveArchiveChat(): ChatArchiveActions {const hidden = useRef(new Map<string, TaskSummaryApi>())const archivesInFlight = useRef(new Map<string, Promise<void>>())+ const updateLinkedConversations = useCallback(+ (taskId: string, archived: boolean): void => {+ if (!scope) return+ queryClient.setQueriesData<Awaited<ReturnType<typeof listConversations>>>(+ { queryKey: conversationListKeys.all(scope) },+ (conversations) =>+ conversations?.map((conversation) =>+ conversation.task?.id === taskId+ ? { ...conversation, task: { ...conversation.task, archived } }+ : conversation+ )+ )+ },+ [queryClient, scope]+ )+const putBack = useCallback((taskId: string): void => {- const session = hidden.current.get(taskId)- if (!session || !scope) {+ if (!scope) {return}- queryClient.setQueriesData<TaskSummaryApi[]>({ queryKey: sessionListKeys.all(scope) }, (sessions) =>- !sessions || sessions.some((entry) => entry.id === taskId)- ? sessions- : [...sessions, { ...session, archived: false }]- )+ const session = hidden.current.get(taskId)+ if (session) {+ queryClient.setQueriesData<TaskSummaryApi[]>({ queryKey: sessionListKeys.all(scope) }, (sessions) =>+ !sessions || sessions.some((entry) => entry.id === taskId)+ ? sessions+ : [...sessions, { ...session, archived: false }]+ )+ }+ updateLinkedConversations(taskId, false)},- [queryClient, scope]+ [queryClient, scope, updateLinkedConversations])const archive = useCallback(@@ -159,7 +199,10 @@ function useLiveArchiveChat(): ChatArchiveActions {throw new NotSignedInError()}const filters = { queryKey: sessionListKeys.all(scope) }- await queryClient.cancelQueries(filters)+ await Promise.all([+ queryClient.cancelQueries(filters),+ queryClient.cancelQueries({ queryKey: conversationListKeys.all(scope) }),+ ])for (const [, sessions] of queryClient.getQueriesData<TaskSummaryApi[]>(filters)) {const session = sessions?.find((entry) => entry.id === item.sourceId)if (session) {@@ -169,6 +212,7 @@ function useLiveArchiveChat(): ChatArchiveActions {queryClient.setQueriesData<TaskSummaryApi[]>(filters, (sessions) =>sessions?.filter((entry) => entry.id !== item.sourceId))+ updateLinkedConversations(item.sourceId, true)try {await setTaskArchived(item.sourceId, true)} catch (error) {@@ -183,7 +227,7 @@ function useLiveArchiveChat(): ChatArchiveActions {void request.then(settled, settled)return request},- [queryClient, scope, putBack]+ [queryClient, scope, putBack, updateLinkedConversations])const restore = useCallback(@@ -199,13 +243,15 @@ function useLiveArchiveChat(): ChatArchiveActions {queryClient.setQueriesData<TaskSummaryApi[]>({ queryKey: sessionListKeys.all(scope) }, (sessions) =>sessions?.filter((entry) => entry.id !== item.sourceId))+ updateLinkedConversations(item.sourceId, true)throw error}hidden.current.delete(item.sourceId)// The server orders the list, so a refetch puts the row back where it belongs.void queryClient.invalidateQueries({ queryKey: sessionListKeys.all(scope) })+ void queryClient.invalidateQueries({ queryKey: conversationListKeys.all(scope) })},- [queryClient, scope, putBack]+ [queryClient, scope, putBack, updateLinkedConversations])return useMemo(() => ({ archive, restore }), [archive, restore])diff --git a/products/mobile/src/model/adapters/chats.test.ts b/products/mobile/src/model/adapters/chats.test.tsindex 5c72299b2a9a..b295cc87da71 100644--- a/products/mobile/src/model/adapters/chats.test.ts+++ b/products/mobile/src/model/adapters/chats.test.ts@@ -1,7 +1,8 @@import type { TaskRunStatusApi, TaskSummaryApi } from '@/api/tasks'+import type { ConversationMinimalApi } from '../../../../posthog_ai/frontend/generated/api.schemas'import type { ChatOrigin, ChatSessionStatus } from '../types'-import { chatListFromSessions } from './chats'+import { chatListFromSessions, mergeChatLists } from './chats'const scope = { host: 'https://us.posthog.com', projectId: 7 }@@ -20,6 +21,25 @@ function session(overrides: Partial<TaskSummaryApi> = {}): TaskSummaryApi {}describe('chatListFromSessions', () => {+ test('merges unlinked classic history and report tasks', () => {+ const conversations = [+ {+ id: 'classic-1',+ title: 'A classic chat',+ status: 'idle',+ updated_at: '2026-10-10T12:00:00Z',+ task: null,+ },+ ] as ConversationMinimalApi[]+ const items = mergeChatLists(+ [session({ id: 'report-task', origin_product: 'signal_report' })],+ conversations,+ scope+ )+ expect(items.map((item) => item.id)).toEqual(['conversation:classic-1', 'session:report-task'])+ expect(items[0]?.webUrl).toBe('https://us.posthog.com/project/7/ai?chat=classic-1')+ })+test('lists sessions newest first and links each row to the web app', () => {const items = chatListFromSessions([@@ -48,6 +68,23 @@ describe('chatListFromSessions', () => {])})+ test.each([+ [true, false],+ [false, false],+ [false, true],+ ])('merges a linked conversation with task present %s and archived %s', (taskPresent, archived) => {+ const conversations = [{ id: 'linked-chat', task: { id: 't1', archived } }] as ConversationMinimalApi[]+ const items = mergeChatLists(taskPresent ? [session()] : [], conversations, scope)+ expect(items).toHaveLength(archived ? 0 : 1)+ if (archived) return+ expect(items[0]).toMatchObject(+ taskPresent+ ? { kind: 'session', sourceId: 't1', conversationId: 'linked-chat', status: 'completed' }+ : { kind: 'conversation', sourceId: 'linked-chat' }+ )+ expect(items[0]?.webUrl).toBe('https://us.posthog.com/project/7/ai?chat=linked-chat')+ })+test('leaves the web link out without a project scope', () => {const [item] = chatListFromSessions([session()], null)expect(item?.webUrl).toBeUndefined()diff --git a/products/mobile/src/model/adapters/chats.ts b/products/mobile/src/model/adapters/chats.tsindex 83c032b40a98..228bbb3d012a 100644--- a/products/mobile/src/model/adapters/chats.ts+++ b/products/mobile/src/model/adapters/chats.ts@@ -1,5 +1,6 @@import type { ProjectScope } from '@/api/reports'import type { TaskRunStatusApi, TaskSummaryApi } from '@/api/tasks'+import type { ConversationMinimalApi } from '../../../../posthog_ai/frontend/generated/api.schemas'import type { ChatListItem, ChatOrigin, ChatSessionStatus } from '../types'@@ -27,6 +28,55 @@ export function taskWebUrl(scope: ProjectScope | null, taskId: string | null): s: undefined}+export function conversationWebUrl(scope: ProjectScope | null, conversationId: string | null): string | undefined {+ return scope && conversationId+ ? `${scope.host.replace(/\/$/, '')}/project/${scope.projectId}/ai?chat=${encodeURIComponent(conversationId)}`+ : undefined+}++export function mergeChatLists(+ sessions: TaskSummaryApi[] | undefined,+ conversations: ConversationMinimalApi[] | undefined,+ scope: ProjectScope | null+): ChatListItem[] {+ const visibleConversations = (conversations ?? []).filter((conversation) => !conversation.task?.archived)+ const taskIds = new Set(sessions?.map((session) => session.id))+ const linkedConversations = new Map(+ visibleConversations.flatMap((conversation) =>+ conversation.task ? [[conversation.task.id, conversation.id] as const] : []+ )+ )+ const classic = visibleConversations.filter(+ (conversation) => !conversation.task || !taskIds.has(conversation.task.id)+ )+ return [+ ...chatListFromSessions(sessions, scope).map((item) => {+ const conversationId = linkedConversations.get(item.sourceId)+ return conversationId+ ? { ...item, conversationId, webUrl: conversationWebUrl(scope, conversationId) }+ : item+ }),+ ...classic.map(+ (conversation): ChatListItem => ({+ id: `conversation:${conversation.id}`,+ kind: 'conversation',+ sourceId: conversation.id,+ origin: 'chat',+ title: titleOr(conversation.title, 'Untitled chat'),+ updatedAt: conversation.updated_at ?? conversation.created_at ?? '',+ status:+ conversation.status === 'in_progress'+ ? 'working'+ : conversation.status === 'canceling'+ ? 'stopped'+ : 'idle',+ pullRequestUrl: null,+ webUrl: conversationWebUrl(scope, conversation.id),+ })+ ),+ ].sort((a, b) => sortTime(b) - sortTime(a))+}+function sessionStatus(session: TaskSummaryApi): ChatSessionStatus {const status = session.latest_run?.statusreturn status ? (SESSION_STATUS[status] ?? 'idle') : 'idle'diff --git a/products/mobile/src/model/types.ts b/products/mobile/src/model/types.tsindex 85a99b071eb4..c5b09b446989 100644--- a/products/mobile/src/model/types.ts+++ b/products/mobile/src/model/types.ts@@ -393,7 +393,8 @@ export type ChatOrigin = 'chat' | 'report' | 'session'export interface ChatListItem {/** Stable list key: `session:<task id>`. */id: string- kind: 'session'+ kind: 'session' | 'conversation'+ conversationId?: string/** The task id. */sourceId: stringorigin: ChatOrigin