: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): recover interrupted connections in place (#127545)
Chris Volzer1508e65b9f21
diff --git a/products/mobile/docs/CHAT.md b/products/mobile/docs/CHAT.mdindex 91289c17a101..8ff714004081 100644--- a/products/mobile/docs/CHAT.md+++ b/products/mobile/docs/CHAT.md@@ -419,6 +419,10 @@ does not prevent a later notification from reopening the previous conversation.Changing the selected account, host or project closes an open chat and aborts its scoped work. Callbacks captured in the old scope cannot send to the newly selected project.A send waiting for encrypted draft storage is cancelled by New chat or closing the sheet, and its text remains recoverable in the original draft.+Chat pauses streams while offline. Task and history reads resume when the connection returns. When the connection returns or the app enters the foreground, chat resumes the same run with its saved cursor and transcript. The Reconnect button also restarts streams after the retry limit. Authentication, permission and missing-run errors prevent automatic recovery. Recovery does not resend messages, answers or run creation requests.++A connected device can still fail to reach PostHog. Stream retries and the idle timeout handle these failures. Repeated connected events do not reset the retry limit.+The page opens from the bottom bar's compose button, a report's Chat button, a report's task status, an inbox row's menu and the Chats tab.The route takes an optional `entry` param; `chatSheetSource` falls back on `report` with a `reportId`, `task` with only a `taskId`, else `compose`.diff --git a/products/mobile/docs/DATA.md b/products/mobile/docs/DATA.mdindex d12ccf035f44..91703b8e66b1 100644--- a/products/mobile/docs/DATA.md+++ b/products/mobile/docs/DATA.md@@ -29,6 +29,17 @@ Each interface names the serializer it mirrors.Query keys (`reportKeys` in `src/api/reports.ts`) carry the host and project id, so a project switch never shows another project's cache.`useProjectScope()` reads both from the auth store and returns null until the session is signed in.+## Connectivity++`src/lib/connectivity.ts` maps Expo Network events to `unknown`, `connected` or `offline`. Unknown states permit reads. The monitor checks state on foreground entry and removes listeners on disposal. It sends no external probes and stores no network names or addresses. Connected state does not confirm backend availability.++- TanStack Query pauses reads offline and resumes them on reconnect. Cached content stays visible. Screens without cached data show an offline message.+- Report streams resume from the saved cursor. Streams with fatal errors or terminal runs stay stopped.+- Views retries each failed, interrupted read once on reconnect, including failures reported after reconnect. This retry skips the one-minute client interval. Server refresh limits still apply.+- A handoff or pin stops if the connection drops during a prerequisite read. Reconnect can complete the shared read but cannot resume the write.++Expo Network requires new iOS and Android binaries. Do not deploy this dependency through an OTA update to an older native runtime.+## The inbox list`useInboxItems()` reads `signals/reports/?view=for_you&sort=priority` one page of 20 reports at a time, with `useInfiniteQuery`.diff --git a/products/mobile/jest.setup.ts b/products/mobile/jest.setup.tsindex b9fb3742ffd5..8e9537433e01 100644--- a/products/mobile/jest.setup.ts+++ b/products/mobile/jest.setup.ts@@ -1,5 +1,11 @@import type { MetricChartProps } from '@/ui/chart/types'+jest.mock('expo-network', () => ({+ ...jest.requireActual<typeof import('expo-network')>('expo-network'),+ addNetworkStateListener: jest.fn(() => ({ remove: jest.fn() })),+ getNetworkStateAsync: jest.fn(async () => ({ isConnected: true })),+}))+jest.mock('@react-native-async-storage/async-storage', () =>jest.requireActual('@react-native-async-storage/async-storage/jest/async-storage-mock'))diff --git a/products/mobile/package.json b/products/mobile/package.jsonindex df06e9dcf389..bb8c94114e9d 100644--- a/products/mobile/package.json+++ b/products/mobile/package.json@@ -67,6 +67,7 @@"expo-image-picker": "~57.0.20","expo-linking": "~57.0.4","expo-localization": "~57.0.2",+ "expo-network": "57.0.2","expo-notifications": "~57.0.7","expo-router": "~57.0.8","expo-secure-store": "~57.0.1",diff --git a/products/mobile/pnpm-lock.yaml b/products/mobile/pnpm-lock.yamlindex 9205bf16f83b..8f76cd2bae36 100644--- a/products/mobile/pnpm-lock.yaml+++ b/products/mobile/pnpm-lock.yaml@@ -74,6 +74,9 @@ importers:expo-localization:specifier: ~57.0.2version: 57.0.2([email protected])([email protected])+ expo-network:+ specifier: 57.0.2+ version: 57.0.2([email protected])([email protected])expo-notifications:specifier: ~57.0.7version: 57.0.21([email protected])([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected])([email protected]))(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected]))([email protected])([email protected])@@ -2660,6 +2663,12 @@ packages:peerDependencies:react-native: '*'+ resolution: {integrity: sha512-BfK1kdftZcM6o9o1FAG7/y0l6vWX0n8td0M5lwkvaMeRXZ9LkRwOi9CQXwvsMTQGQiPwtQXgwiAze13cqjt75g==}+ peerDependencies:+ expo: '*'+ react: '*'+resolution: {integrity: sha512-CWBW6DxqRJ2MaYZW5+/WfEWwIwbiVk5UAPqx0kE676B4R1+PlAXARk/kuNeQBcVrcDNV6i9ihE9B0db8Cd2RXQ==}peerDependencies:@@ -7906,6 +7915,11 @@ snapshots:dependencies:react-native: 0.86.3(@babel/[email protected])(@react-native/[email protected](@babel/[email protected])([email protected]))(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected])+ dependencies:+ expo: 57.0.26(@babel/[email protected])(@expo/[email protected])(@expo/[email protected])([email protected])([email protected]([email protected]))([email protected]([email protected]([email protected]))([email protected]))([email protected]([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected])([email protected]))(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected]))([email protected]))([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected])([email protected]))(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected]))([email protected]))([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected])([email protected]))(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected]))([email protected])([email protected])+ react: 19.2.6+[email protected]([email protected])([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected])([email protected]))(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected]))([email protected])([email protected]):dependencies:'@expo/image-utils': 0.11.5([email protected])diff --git a/products/mobile/src/api/queryClient.ts b/products/mobile/src/api/queryClient.tsindex ec29a124fe86..5798e2739530 100644--- a/products/mobile/src/api/queryClient.ts+++ b/products/mobile/src/api/queryClient.ts@@ -1,6 +1,10 @@-import { focusManager, QueryClient } from '@tanstack/react-query'+import { focusManager, onlineManager, QueryClient } from '@tanstack/react-query'import { AppState } from 'react-native'+import { monitorConnectivity } from '@/lib/connectivity'++onlineManager.setEventListener(monitorConnectivity)+// TanStack's default focus listener needs `window` visibility events, which React Native lacks, so the focus state never// changed on iOS or Android. App state drives it instead.focusManager.setEventListener((setFocused) => {diff --git a/products/mobile/src/features/chat/ChatScreen.test.tsx b/products/mobile/src/features/chat/ChatScreen.test.tsxindex d3bdb2a38234..fb4e0d22bb6e 100644--- a/products/mobile/src/features/chat/ChatScreen.test.tsx+++ b/products/mobile/src/features/chat/ChatScreen.test.tsx@@ -84,11 +84,14 @@ function mockReadyChat(): { session: ReturnType<typeof useSession>; draft: Returdescribe('chat send preparation', () => {test('keeps an unsaved draft notice visible and disables retry while saving', () => {- const { draft } = mockReadyChat()+ const { session, draft } = mockReadyChat()+ session.notice = 'Connection interrupted. Reconnect to continue.'+ session.reconnect = jest.fn()draft.draftError = 'Draft not saved. Remove a queued message before saving more.'const view = render(<ChatScreen source={{ entry: 'compose', origin: null }} onBack={jest.fn()} />)expect(screen.getByDisplayValue('First message')).toBeTruthy()expect(screen.getByText(draft.draftError)).toBeTruthy()+ expect(screen.queryByTestId('session-reconnect')).toBeNull()fireEvent.press(screen.getByTestId('chat-draft-retry'))expect(draft.retrySave).toHaveBeenCalledTimes(1)draft.draftSaving = true@@ -100,6 +103,9 @@ describe('chat send preparation', () => {draft.draftError = undefinedview.rerender(<ChatScreen source={{ entry: 'compose', origin: null }} onBack={jest.fn()} />)expect(screen.queryByTestId('chat-draft-retry')).toBeNull()+ expect(screen.getByText(session.notice)).toBeTruthy()+ fireEvent.press(screen.getByTestId('session-reconnect'))+ expect(session.reconnect).toHaveBeenCalledTimes(1)})test.each(['new', 'close', 'unmount'])('a prepared message does not send after %s', async (transition) => {let finishStorage!: (settle: (sent: boolean) => Promise<void>) => voiddiff --git a/products/mobile/src/features/chat/ChatScreen.tsx b/products/mobile/src/features/chat/ChatScreen.tsxindex 1c142894c525..8a6176e0425e 100644--- a/products/mobile/src/features/chat/ChatScreen.tsx+++ b/products/mobile/src/features/chat/ChatScreen.tsx@@ -616,7 +616,8 @@ export function ChatScreen({topInset={insets.top + CHAT_HEADER_HEIGHT}onRetryHistory={() => {track('mobile_session_load_retried')- session.reloadHistory().catch(() => undefined)+ if (session.reconnect) session.reconnect()+ else session.reloadHistory().catch(() => undefined)}}/>)}@@ -655,6 +656,7 @@ export function ChatScreen({pending={session.isSending}onAnswer={(answerInput) => void session.answer(answerInput)}onDismissNotice={dismissNotice}+ onReconnect={notice === session.notice ? session.reconnect : undefined}onRetryNotice={composerDraft.draftError ? composerDraft.retrySave : undefined}noticePending={composerDraft.draftSaving}/>diff --git a/products/mobile/src/features/chat/session/SessionDecisionPanel.tsx b/products/mobile/src/features/chat/session/SessionDecisionPanel.tsxindex 22b54e71d39e..1341bacfef95 100644--- a/products/mobile/src/features/chat/session/SessionDecisionPanel.tsx+++ b/products/mobile/src/features/chat/session/SessionDecisionPanel.tsx@@ -18,6 +18,7 @@ interface SessionDecisionPanelProps {onRetryNotice?: () => voidnoticePending?: booleanonDismissNotice: () => void+ onReconnect?: () => void}export function SessionDecisionPanel({@@ -26,6 +27,7 @@ export function SessionDecisionPanel({pending,onAnswer,onDismissNotice,+ onReconnect,onRetryNotice,noticePending,}: SessionDecisionPanelProps): ReactElement | null {@@ -39,6 +41,15 @@ export function SessionDecisionPanel({{notice ? (<View style={styles.notice} testID="session-decision-notice"><Text style={styles.noticeText}>{notice}</Text>+ {onReconnect ? (+ <Pressable44+ onPress={onReconnect}+ accessibilityLabel="Reconnect to the agent"+ testID="session-reconnect"+ >+ <Text style={styles.reconnectText}>Reconnect</Text>+ </Pressable44>+ ) : null}{onRetryNotice ? (<Pressable44onPress={onRetryNotice}@@ -92,6 +103,10 @@ const useStyles = createStyles(({ colors }) => ({color: colors.orange,flex: 1,},+ reconnectText: {+ ...type.meta,+ color: colors.orange,+ },retry: { paddingHorizontal: 8 },retryText: { ...type.meta, color: colors.orange },close: {diff --git a/products/mobile/src/features/chat/session/types.ts b/products/mobile/src/features/chat/session/types.tsindex b609e7f11730..2ad4a9c8fb07 100644--- a/products/mobile/src/features/chat/session/types.ts+++ b/products/mobile/src/features/chat/session/types.ts@@ -189,6 +189,7 @@ export interface Session {answer: (input: DecisionAnswerInput) => Promise<void>/** Asks the agent to stop the current turn. Only while `phase` is not `idle`. */stop: () => void+ reconnect?: () => voidreloadHistory: () => Promise<void>reset: () => voiddismissNotice: () => voiddiff --git a/products/mobile/src/features/chat/session/useSession.test.tsx b/products/mobile/src/features/chat/session/useSession.test.tsxindex 2eaf63b2485a..2ebbfb3b8038 100644--- a/products/mobile/src/features/chat/session/useSession.test.tsx+++ b/products/mobile/src/features/chat/session/useSession.test.tsx@@ -6,7 +6,9 @@ import * as tasks from '@/api/tasks'import { useAuthStore } from '@/auth/authStore'import { getSessionTokens, setSessionTokens } from '@/auth/tokens'import { useAiApproval } from '@/features/ai/aiApproval'+import { RECONNECT_ATTEMPTS_PER_DROP } from '@/features/handoff/runStream'import { setAnalyticsClient } from '@/lib/analytics'+import { useConnectivity } from '@/lib/connectivity'import type { PendingAttachment } from '../attachments/types'import { AttachmentUploadError, uploadAttachments } from '../attachments/uploadAttachments'@@ -153,7 +155,9 @@ const LIVE_TOOL_CALL = logLine({describe('useSession', () => {const originalAppState = AppState.currentStatebeforeEach(() => {+ jest.spyOn(AppState, 'addEventListener').mockReturnValue({ remove: jest.fn() })AppState.currentState = 'active'+ useConnectivity.setState({ status: 'unknown' })jest.mocked(useAiApproval).mockReturnValue({request: jest.fn(async () => true),pending: false,@@ -171,6 +175,232 @@ describe('useSession', () => {jest.clearAllMocks()})+ test.each(['offline', 'failed-read', 'pending-read'] as const)(+ 'session bootstrap resumes after %s when the link returns',+ async (initial) => {+ if (initial === 'offline') useConnectivity.setState({ status: 'offline' })+ else if (initial === 'failed-read')+ mocked.getTask.mockRejectedValueOnce(new TypeError('Network request failed'))+ else+ mocked.getTask.mockImplementationOnce(+ (_id, signal) =>+ new Promise((_resolve, reject) => {+ signal?.addEventListener('abort', () => reject(new DOMException('Aborted', 'AbortError')))+ })+ )+ mocked.getTask.mockResolvedValue(task(run({ status: 'in_progress' })))+ const { result, unmount } = renderHook(() => useSession({ taskId: TASK_ID }))+ try {+ await act(async () => {})+ expect(mocked.getTask).toHaveBeenCalledTimes(initial === 'offline' ? 0 : 1)+ if (initial === 'offline')+ expect(result.current.history).toMatchObject({ status: 'error', error: { kind: 'network' } })+ await act(async () => {+ useConnectivity.setState({ status: 'offline' })+ })+ expect(result.current.history).toMatchObject({ status: 'error', error: { kind: 'network' } })+ const stream = liveStream(false)+ mocked.openTaskRunStream.mockResolvedValueOnce(stream.response)+ await act(async () => {+ useConnectivity.setState({ status: 'connected' })+ })+ expect(result.current.history.status).toBe('loading')+ await act(async () => stream.push({}, undefined, 'keepalive'))+ expect(result.current.history.status).toBe('idle')+ expect(mocked.getTask).toHaveBeenCalledTimes(initial === 'offline' ? 1 : 2)+ expect(mocked.sendTaskRunCommand).not.toHaveBeenCalled()+ } finally {+ unmount()+ }+ }+ )++ test('interrupted initial hydration shows offline feedback until the stream resumes', async () => {+ const first = liveStream(false)+ const second = liveStream(false)+ mocked.getTask.mockResolvedValue(task(run({ status: 'in_progress' })))+ mocked.openTaskRunStream.mockResolvedValueOnce(first.response).mockResolvedValueOnce(second.response)+ const { result, unmount } = renderHook(() => useSession({ taskId: TASK_ID }))+ try {+ await act(async () => {})+ expect(result.current.history.status).toBe('loading')+ await act(async () => useConnectivity.setState({ status: 'offline' }))+ expect(result.current.history).toMatchObject({ status: 'error', error: { kind: 'network' } })+ expect(mocked.openTaskRunStream).toHaveBeenCalledTimes(1)+ await act(async () => useConnectivity.setState({ status: 'connected' }))+ expect(result.current.history.status).toBe('loading')+ expect(mocked.openTaskRunStream).toHaveBeenCalledTimes(2)+ await act(async () => second.push({}, undefined, 'keepalive'))+ expect(result.current.history.status).toBe('idle')+ expect(mocked.sendTaskRunCommand).not.toHaveBeenCalled()+ expect(mocked.startTaskRun).not.toHaveBeenCalled()+ } finally {+ unmount()+ }+ })++ test('a completed stream stays ended when the link returns', async () => {+ const stream = liveStream()+ mocked.getTask.mockResolvedValue(task(run({ status: 'in_progress' })))+ mocked.getTaskRun.mockResolvedValue(run({ status: 'completed' }))+ mocked.openTaskRunStream.mockResolvedValueOnce(stream.response)+ const { result, unmount } = renderHook(() => useSession({ taskId: TASK_ID }))+ try {+ await act(async () => {})+ await act(async () => {+ stream.push({}, undefined, 'stream-end')+ })+ expect(result.current.runStatus).toBe('completed')+ await act(async () => {+ useConnectivity.setState({ status: 'offline' })+ })+ await act(async () => {+ useConnectivity.setState({ status: 'connected' })+ })+ expect(mocked.openTaskRunStream).toHaveBeenCalledTimes(1)+ expect(result.current.reconnect).toBeUndefined()+ } finally {+ unmount()+ }+ })++ test.each(['network', 'foreground'] as const)(+ 'a %s recovery retains the transcript and cursor without sending commands',+ async (trigger) => {+ let changeAppState: (state: 'active' | 'background') => void = () => undefined+ const appListener = jest.spyOn(AppState, 'addEventListener').mockImplementation((_event, listener) => {+ changeAppState = listener+ return { remove: jest.fn() }+ })+ const first = liveStream()+ const second = liveStream(false)+ const saved = {+ ...logLine({ sessionUpdate: 'agent_message_chunk', content: { text: 'Saved reply.' } }),+ event_id: 'saved-reply',+ }+ mocked.openTaskRunStream.mockResolvedValueOnce(first.response).mockResolvedValueOnce(second.response)+ mocked.getTask.mockResolvedValue(task(run({ status: 'in_progress' })))+ const { result, unmount } = renderHook(() => useSession({ taskId: TASK_ID }))+ try {+ await act(async () => {})+ await act(async () => {+ first.push(saved, '100-0')+ })+ expect(result.current.items).toEqual([+ expect.objectContaining({ kind: 'assistant', text: 'Saved reply.' }),+ ])+ await act(async () => {+ if (trigger === 'network') useConnectivity.setState({ status: 'offline' })+ else changeAppState('background')+ })+ expect(mocked.openTaskRunStream.mock.calls[0]?.[2]?.signal?.aborted).toBe(true)+ expect(mocked.openTaskRunStream).toHaveBeenCalledTimes(1)+ await act(async () => {+ if (trigger === 'network') useConnectivity.setState({ status: 'connected' })+ else changeAppState('active')+ })+ expect(mocked.openTaskRunStream).toHaveBeenCalledTimes(2)+ expect(mocked.openTaskRunStream.mock.calls[1]?.[2]?.lastEventId).toBe('100-0')+ await act(async () => {+ second.push(saved, '100-0')+ second.push({}, undefined, 'keepalive')+ })+ expect(result.current.items).toEqual([+ expect.objectContaining({ kind: 'assistant', text: 'Saved reply.' }),+ ])+ expect(mocked.sendTaskRunCommand).not.toHaveBeenCalled()+ expect(mocked.startTaskRun).not.toHaveBeenCalled()+ } finally {+ unmount()+ appListener.mockRestore()+ }+ }+ )++ test.each(['network', 'foreground', 'manual'] as const)(+ 'exhausted retries rearm once after %s recovery',+ async (trigger) => {+ jest.useFakeTimers()+ let changeAppState: (state: 'active' | 'background') => void = () => undefined+ const appListener = jest.spyOn(AppState, 'addEventListener').mockImplementation((_event, listener) => {+ changeAppState = listener+ return { remove: jest.fn() }+ })+ mocked.getTask.mockResolvedValue(task(run({ status: 'in_progress' })))+ mocked.getTaskRun.mockResolvedValue(run({ status: 'in_progress' }))+ mocked.openTaskRunStream.mockRejectedValue(new TypeError('Network request failed'))+ const { result, unmount } = renderHook(() => useSession({ taskId: TASK_ID }))+ try {+ await act(async () => {})+ for (let retry = 0; retry < RECONNECT_ATTEMPTS_PER_DROP; retry++) {+ await act(async () => {+ jest.advanceTimersByTime(30_000)+ })+ }+ expect(result.current.reconnect).toBeDefined()+ expect(result.current.history.status).toBe('error')+ const attempts = mocked.openTaskRunStream.mock.calls.length+ await act(async () => {+ useConnectivity.setState({ status: 'connected' })+ jest.advanceTimersByTime(60_000)+ })+ expect(mocked.openTaskRunStream).toHaveBeenCalledTimes(attempts)+ const restored = liveStream()+ let connect: (response: Response) => void = () => undefined+ mocked.openTaskRunStream.mockImplementationOnce(+ () =>+ new Promise((resolve) => {+ connect = resolve+ })+ )+ await act(async () => {+ if (trigger === 'manual') {+ const reconnect = result.current.reconnect+ reconnect?.()+ reconnect?.()+ } else if (trigger === 'network') useConnectivity.setState({ status: 'offline' })+ else changeAppState('background')+ })+ if (trigger !== 'manual')+ await act(async () => {+ if (trigger === 'network') useConnectivity.setState({ status: 'connected' })+ else changeAppState('active')+ })+ expect(mocked.openTaskRunStream).toHaveBeenCalledTimes(attempts + 1)+ expect(result.current.reconnect).toBeUndefined()+ expect(result.current.notice).toBeUndefined()+ expect(result.current.history.status).toBe('loading')+ await act(async () => connect(restored.response))+ expect(result.current.history.status).toBe('idle')+ expect(mocked.sendTaskRunCommand).not.toHaveBeenCalled()+ expect(mocked.createTask).not.toHaveBeenCalled()+ } finally {+ unmount()+ appListener.mockRestore()+ jest.useRealTimers()+ }+ }+ )++ test.each([401, 403, 404])('connectivity recovery does not retry a fatal stream %s', async (status) => {+ mocked.getTask.mockResolvedValue(task(run({ status: 'in_progress' })))+ mocked.openTaskRunStream.mockRejectedValueOnce(new ApiError(status, undefined))+ const { result, unmount } = renderHook(() => useSession({ taskId: TASK_ID }))+ try {+ await act(async () => {})+ expect(result.current.reconnect).toBeUndefined()+ await act(async () => {+ useConnectivity.setState({ status: 'offline' })+ })+ await act(async () => {+ useConnectivity.setState({ status: 'connected' })+ })+ expect(mocked.openTaskRunStream).toHaveBeenCalledTimes(1)+ } finally {+ unmount()+ }+ })+test.each([false, true])('a denied AI approval prevents uploads and message delivery (existing task: %s)',async (existing) => {diff --git a/products/mobile/src/features/chat/session/useSession.ts b/products/mobile/src/features/chat/session/useSession.tsindex 09bf6e974f57..ec06a4b615a7 100644--- a/products/mobile/src/features/chat/session/useSession.ts+++ b/products/mobile/src/features/chat/session/useSession.ts@@ -52,6 +52,7 @@ import type { PermissionRecord, RunStreamState } from '@/features/handoff/types'import { IDLE_TIMEOUT_MS, isAbort, isFatal, useAppActive } from '@/features/handoff/useTaskRun'import { abortError } from '@/lib/abort'import { track } from '@/lib/analytics'+import { useConnectivity } from '@/lib/connectivity'import { asRecord } from '@/lib/records'import { sleep } from '@/lib/sleep'import type { DecisionAnswerInput } from '@/model/types'@@ -97,12 +98,19 @@ const NOT_STARTED = "The agent hasn't started yet."const STOP_FAILED = "Couldn't stop this run. Try again."const ANSWERED_ELSEWHERE = 'Someone else answered this already.'const ANSWER_RUN_ENDED = "Your answer wasn't sent. The run ended."-const CONNECTION_LOST = 'The connection to the agent dropped. Close this chat and open it again.'+const CONNECTION_LOST = 'The connection to the agent dropped. Reconnect to continue.'const CONFIG_NOT_APPLIED = "Your model or mode change didn't reach the agent. Try again."const UPLOAD_FAILED = "Your files didn't upload. Try again."const LOADING: SessionHistory = { status: 'loading', error: null }const IDLE: SessionHistory = { status: 'idle', error: null }+const OFFLINE: SessionHistory = {+ status: 'error',+ error: {+ kind: 'network',+ message: "You're offline. This chat will reconnect when your connection returns.",+ },+}const UNKNOWN_RUN_CONFIG: TrackedRunConfig = {runtimeAdapter: null,@@ -564,6 +572,7 @@ export function useSession(options: SessionOptions): Session {const scopeIsCurrent = useCallback((): boolean => sessionScope() === openedScope.current, [])const demo = useDemoMode((state) => state.enabled)const active = useAppActive()+ const online = useConnectivity((state) => state.status !== 'offline')const [thread, dispatchThread] = useReducer(sessionThreadReducer, false, initialSessionThread)const [live, setLiveState] = useState<RunStreamState | null>(null)const [title, setTitle] = useState<string | null>(null)@@ -575,6 +584,8 @@ export function useSession(options: SessionOptions): Session {const [partial, setPartialState] = useState<PartialAnswer | null>(null)const [follow, setFollow] = useState<Follow | null>(null)const [followEnded, setFollowEnded] = useState(false)+ const lastFollow = useRef<{ follow: Follow | null; outcome: FollowOutcome | null }>({ follow: null, outcome: null })+ const bootstrapRetryable = useRef(false)const [demoPlaying, setDemoPlaying] = useState(false)const [createdTaskId, setCreatedTaskId] = useState<string | null>(null)const [unsentText, setUnsentText] = useState<string | undefined>(undefined)@@ -764,6 +775,8 @@ export function useSession(options: SessionOptions): Session {endStopping()setFollow(null)setFollowEnded(false)+ lastFollow.current = { follow: null, outcome: null }+ bootstrapRetryable.current = falsesetReconnecting(false)setDemoPlaying(false)setSending(false)@@ -809,6 +822,11 @@ export function useSession(options: SessionOptions): Session {track('mobile_session_resumed', { status: log.status })return}+ if (useConnectivity.getState().status === 'offline') {+ bootstrapRetryable.current = true+ setHistory(OFFLINE)+ return+ }const controller = new AbortController()bootController.current = controllerconst { signal } = controller@@ -859,6 +877,7 @@ export function useSession(options: SessionOptions): Session {if (epoch.current !== mine || !scopeIsCurrent() || isAbort(error, signal)) {return}+ bootstrapRetryable.current = !isFatal(error)setHistory({ status: 'error', error: toChatError(error) })} finally {if (bootController.current === controller) {@@ -899,10 +918,52 @@ export function useSession(options: SessionOptions): Session {track('mobile_decision_shown', { kind: pendingKind, surface: 'chat', replayed: pendingReplayed })}, [pendingRequestId, pendingKind, pendingReplayed])+ const wasAvailable = useRef(active && online)+ useEffect(() => {+ const available = active && online+ const recovered = available && !wasAvailable.current+ wasAvailable.current = available+ if (!online && !demo && scopeIsCurrent()) {+ setHistory((current) => (current.status === 'loading' ? OFFLINE : current))+ }+ if (!available && !demo && !follow && bootController.current) {+ bootstrapRetryable.current = true+ bootController.current.abort()+ }+ if (recovered && !demo && scopeIsCurrent() && !follow && bootstrapRetryable.current) {+ void reloadHistory()+ }+ }, [active, online, demo, follow, reloadHistory, scopeIsCurrent])++ const reconnect = useCallback((): void => {+ if (!scopeIsCurrent() || !active || !online || demo || lastFollow.current.outcome !== 'gave_up') {+ return+ }+ lastFollow.current.outcome = 'aborted'+ setFollow((current) => (current ? { ...current, key: current.key + 1 } : current))+ }, [active, online, demo, scopeIsCurrent])+useEffect(() => {- if (!follow || !activeTaskId || !active || demo) {+ if (lastFollow.current.follow !== follow) {+ lastFollow.current = { follow, outcome: null }+ }+ if (!active || !online) {+ if (lastFollow.current.outcome === 'gave_up') lastFollow.current.outcome = nullreturn}+ if (+ !follow ||+ !activeTaskId ||+ demo ||+ lastFollow.current.outcome === 'gave_up' ||+ lastFollow.current.outcome === 'ended' ||+ (typeof lastFollow.current.outcome === 'object' && lastFollow.current.outcome !== null)+ ) {+ return+ }+ lastFollow.current.outcome = null+ setHistory((current) => (current.status === 'error' ? LOADING : current))+ setNotice((current) => (current === CONNECTION_LOST ? undefined : current))const controller = new AbortController()const { signal } = controllerconst { runId } = follow@@ -914,13 +975,15 @@ export function useSession(options: SessionOptions): Session {if (entry.followed && entry.cursor.cursor === undefined) {dispatchThread({ type: 'resuming' })}+ setReconnecting(entry.followed)entry.followed = truesetFollowEnded(false)const handlers: FollowHandlers = {onOpen: () => {- setReconnecting(false)+ if (!entry.hydrate) setReconnecting(false)},onHistory: (frames) => {+ setReconnecting(false)dispatchThread({ type: 'frames', frames })const current = liveRef.currentif (current?.runId === runId) {@@ -947,6 +1010,7 @@ export function useSession(options: SessionOptions): Session {if (outcome === 'aborted' || signal.aborted) {return}+ lastFollow.current.outcome = outcomesetReconnecting(false)setFollowEnded(true)if (outcome === 'gave_up') {@@ -963,7 +1027,7 @@ export function useSession(options: SessionOptions): Session {}})return () => controller.abort()- }, [active, activeTaskId, applyFrame, applySnapshot, demo, follow, setLive])+ }, [active, online, activeTaskId, applyFrame, applySnapshot, demo, follow, setLive])const liveStatus = live?.statusconst liveTurnEnded = live?.turnEnded@@ -1598,7 +1662,7 @@ export function useSession(options: SessionOptions): Session {const terminal = live ? isTerminalRunStatus(live.status) : trueconst following = follow !== null && !followEndedlet phase: SessionPhase = 'idle'- if (reconnecting) {+ if (reconnecting || (!demo && follow && !followEnded && !online)) {phase = 'reconnecting'} else if (demoPlaying || (active && live?.phase === 'working' && !terminal && !live.turnEnded && following)) {phase = 'working'@@ -1649,6 +1713,7 @@ export function useSession(options: SessionOptions): Session {answer,stop,reloadHistory,+ ...(lastFollow.current.outcome === 'gave_up' && active && online && !isSending ? { reconnect } : {}),reset,dismissNotice,}diff --git a/products/mobile/src/features/chats/hooks.ts b/products/mobile/src/features/chats/hooks.tsindex 9c15b58c468d..3701c9e1ed4a 100644--- a/products/mobile/src/features/chats/hooks.ts+++ b/products/mobile/src/features/chats/hooks.ts@@ -8,9 +8,10 @@ import { useAuthStore } from '@/auth/authStore'import { useProjectScope } from '@/auth/useProjectScope'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 { errorQuery, loadingQuery, successQuery } from '@/model/queryStates'+import { connectionLoadingQuery, errorQuery, loadingQuery, successQuery } from '@/model/queryStates'import type { ChatListItem, QueryState } from '@/model/types'const CHAT_LIST_STALE_MS = 30_000@@ -24,6 +25,7 @@ export const sessionListKeys = {function useLiveChatList(enabled: boolean): QueryState<ChatListItem[]> {const scope = useProjectScope()+ const offline = useConnectivity((state) => state.status === 'offline')const userId = useAuthStore((state) => state.user?.id)const accountLoading = useAuthStore((state) => state.accountLoading)const accountError = useAuthStore((state) => state.accountError)@@ -35,7 +37,7 @@ function useLiveChatList(enabled: boolean): QueryState<ChatListItem[]> {const [accountChecked, setAccountChecked] = useState(false)useEffect(() => {- if (!missingUserId || accountChecked) {+ if (!missingUserId || accountChecked || offline) {return undefined}let current = true@@ -47,7 +49,7 @@ function useLiveChatList(enabled: boolean): QueryState<ChatListItem[]> {return () => {current = false}- }, [missingUserId, accountChecked, reloadAccount])+ }, [missingUserId, accountChecked, reloadAccount, offline])const sessions = useQuery({queryKey: sessionListKeys.mine(scope, userId),@@ -81,7 +83,7 @@ function useLiveChatList(enabled: boolean): QueryState<ChatListItem[]> {}if (missingUserId) {if (!accountChecked || accountLoading) {- return { ...loadingQuery<ChatListItem[]>(), refetch: reloadAccount }+ return connectionLoadingQuery<ChatListItem[]>(offline, reloadAccount)}if (accountError) {return errorQuery(new Error(accountError), reloadAccount)@@ -92,7 +94,7 @@ function useLiveChatList(enabled: boolean): QueryState<ChatListItem[]> {return errorQuery(toError(sessions.error), refetch)}if (sessions.data === undefined && !unavailable) {- return { ...loadingQuery<ChatListItem[]>(), refetch }+ return connectionLoadingQuery<ChatListItem[]>(offline, refetch)}return {data: items,diff --git a/products/mobile/src/features/handoff/hooksApproval.test.tsx b/products/mobile/src/features/handoff/hooksApproval.test.tsxindex 73b6b16db0f3..b3ee620680ff 100644--- a/products/mobile/src/features/handoff/hooksApproval.test.tsx+++ b/products/mobile/src/features/handoff/hooksApproval.test.tsx@@ -1,20 +1,24 @@import { QueryClient, QueryClientProvider } from '@tanstack/react-query'import { act, renderHook, waitFor } from '@testing-library/react-native'import type { ReactElement, ReactNode } from 'react'-+import { getMyTaskConfig, type TaskUserConfigApi } from '@/api/tasks'import { fetchOrganization } from '@/api/users'import { useAuthStore } from '@/auth/authStore'import { useDemoMode } from '@/demo/demoMode'import { cancelAiApproval, checkAiApproval, useAiApprovalStore } from '@/features/ai/aiApproval'import { aiConsentKey, useAiConsentStore, waitForAiConsent } from '@/features/chat/aiConsentStore'+import { useConnectivity } from '@/lib/connectivity'import { deliverPermissionResponse } from './commands'import { handoffEntry, useHandoffStore } from './handoffStore'import { useDecisionAnswer, useHandoffActions } from './hooks'+import { kickOffReportTask } from './kickoff'import { currentDecision } from './liveReport'import { parsePermissionRequest, requestKind } from './permissionRequest'import { initialRunState } from './runStream'+jest.mock('@/api/tasks', () => ({ ...jest.requireActual('@/api/tasks'), getMyTaskConfig: jest.fn() }))+jest.mock('./kickoff', () => ({ ...jest.requireActual('./kickoff'), kickOffReportTask: jest.fn() }))jest.mock('@/api/users', () => ({ fetchOrganization: jest.fn() }))jest.mock('./commands', () => ({ ...jest.requireActual('./commands'), deliverPermissionResponse: jest.fn() }))@@ -55,6 +59,7 @@ function setup(): {}beforeEach(async () => {+ useConnectivity.setState({ status: 'connected' })await waitForAiConsent()useDemoMode.setState({ enabled: false })useAiConsentStore.getState().clear()@@ -78,6 +83,7 @@ beforeEach(async () => {setRun()})afterEach(() => {+ useConnectivity.setState({ status: 'unknown' })cancelAiApproval()useAiConsentStore.getState().clear()useHandoffStore.setState({ reports: {} })@@ -142,3 +148,43 @@ test('leaving the screen aborts an approved decision delivery', async () => {expect(signal?.aborted).toBe(true)hook.clear()})++test.each(['offline', 'disconnect'] as const)(+ 'handoff fails promptly on %s without creating a task after reconnect',+ async (when) => {+ useAiConsentStore.getState().accept(aiConsentKey(HOST, 'person-1'))+ let finish: (config: TaskUserConfigApi) => void = () => undefined+ jest.mocked(getMyTaskConfig).mockClear()+ jest.mocked(getMyTaskConfig).mockReturnValue(+ new Promise((resolve) => {+ finish = resolve+ })+ )+ jest.mocked(kickOffReportTask).mockClear()+ const hook = setup()+ await act(async () => {+ await new Promise((resolve) => setTimeout(resolve, 0))+ })+ if (when === 'offline') act(() => useConnectivity.setState({ status: 'offline' }))+ let pending!: Promise<void>+ act(() => {+ pending = hook.result.current.handOff.run()+ })+ if (when === 'disconnect') {+ await waitFor(() => expect(getMyTaskConfig).toHaveBeenCalled())+ act(() => useConnectivity.setState({ status: 'offline' }))+ }+ await waitFor(() => expect(hook.result.current.handOff.pending).toBe(false))+ await pending+ expect(hook.result.current.handOff.pending).toBe(false)+ expect(handoffEntry(REPORT).notice).toBe("Couldn't reach PostHog. Check your connection and try again.")+ await act(async () => {+ useConnectivity.setState({ status: 'connected' })+ finish({ resolved_ai_run_defaults: {} } as TaskUserConfigApi)+ await Promise.resolve()+ })+ expect(kickOffReportTask).not.toHaveBeenCalled()+ hook.unmount()+ hook.clear()+ }+)diff --git a/products/mobile/src/features/handoff/useRunOptions.ts b/products/mobile/src/features/handoff/useRunOptions.tsindex 16e7e18e58c9..aedfff3e8579 100644--- a/products/mobile/src/features/handoff/useRunOptions.ts+++ b/products/mobile/src/features/handoff/useRunOptions.ts@@ -14,6 +14,7 @@ import {import { useProjectScope } from '@/auth/useProjectScope'import { useDemoMode } from '@/demo/demoMode'import { track } from '@/lib/analytics'+import { OfflineError, whileOnline } from '@/lib/connectivity'import {catalogueEntry,@@ -92,15 +93,18 @@ export async function fetchRunDefaults(scope: ProjectScope | null): Promise<ResolvedAiRunDefaultsApi | undefined> {try {- const config = await queryClient.fetchQuery({- queryKey: runOptionKeys.myConfig(scope),- queryFn: ({ signal }) => getMyTaskConfig(signal),- staleTime: DEFAULTS_STALE_MS,- // The hand-off is waiting on this, and a failure only means the server picks the defaults.- retry: false,- })+ const config = await whileOnline(() =>+ queryClient.fetchQuery({+ queryKey: runOptionKeys.myConfig(scope),+ queryFn: ({ signal }) => getMyTaskConfig(signal),+ staleTime: DEFAULTS_STALE_MS,+ // The hand-off is waiting on this, and a failure only means the server picks the defaults.+ retry: false,+ })+ )return config.resolved_ai_run_defaults- } catch {+ } catch (error) {+ if (error instanceof OfflineError) throw errorreturn undefined}}diff --git a/products/mobile/src/features/handoff/useTaskRun.test.ts b/products/mobile/src/features/handoff/useTaskRun.test.tsindex 1ec1f29190ae..05aa13d57cb2 100644--- a/products/mobile/src/features/handoff/useTaskRun.test.ts+++ b/products/mobile/src/features/handoff/useTaskRun.test.ts@@ -1,11 +1,14 @@+import { act, renderHook } from '@testing-library/react-native'+import { AppState } from 'react-native'import { ApiError } from '@/api/client'import { getTask, getTaskRun, openTaskRunStream, type TaskRunApi } from '@/api/tasks'+import { useConnectivity } from '@/lib/connectivity'import { deliverPermissionResponse } from './commands'import { useHandoffStore } from './handoffStore'import { visibleAnswer } from './liveReport'import { HYDRATION_QUIET_MS } from './runHydration'-import { followRun } from './useTaskRun'+import { followRun, useTaskRun } from './useTaskRun'jest.mock('@react-native-async-storage/async-storage', () =>require('@react-native-async-storage/async-storage/jest/async-storage-mock')@@ -129,6 +132,9 @@ describe('report run connection lifecycle', () => {beforeEach(() => {jest.useFakeTimers()jest.clearAllMocks()+ AppState.currentState = 'active'+ jest.spyOn(AppState, 'addEventListener').mockReturnValue({ remove: jest.fn() })+ useConnectivity.setState({ status: 'unknown' })useHandoffStore.setState({ reports: {} })jest.mocked(getTask).mockResolvedValue({ id: TASK, title: '', signal_report: REPORT, latest_run: RUN })jest.mocked(getTaskRun).mockResolvedValue(RUN)@@ -138,6 +144,59 @@ describe('report run connection lifecycle', () => {jest.useRealTimers()})+ test('an offline report waits, resumes with its cursor, and never resends commands', async () => {+ useConnectivity.setState({ status: 'offline' })+ const first = controlledStream()+ const second = controlledStream()+ jest.mocked(openTaskRunStream).mockResolvedValueOnce(first.response).mockResolvedValueOnce(second.response)+ const { unmount } = renderHook(() => useTaskRun(REPORT, { taskId: TASK, runId: RUN.id }, true))+ try {+ await act(async () => {})+ expect(openTaskRunStream).not.toHaveBeenCalled()+ await act(async () => {+ useConnectivity.setState({ status: 'connected' })+ })+ await act(async () => {+ first.send(event('network-100-0', toolFrame('Read source', 'network-event')))+ first.send('event: keepalive\ndata: {}\n\n')+ })+ await act(async () => {+ useConnectivity.setState({ status: 'offline' })+ })+ expect(jest.mocked(openTaskRunStream).mock.calls[0]?.[2]?.signal?.aborted).toBe(true)+ await act(async () => {+ useConnectivity.setState({ status: 'connected' })+ })+ expect(openTaskRunStream).toHaveBeenCalledTimes(2)+ expect(jest.mocked(openTaskRunStream).mock.calls[1]?.[2]?.lastEventId).toBe('network-100-0')+ expect(deliverPermissionResponse).not.toHaveBeenCalled()+ } finally {+ unmount()+ }+ })++ test.each([401, 403, 404, 'completed'] as const)(+ 'link recovery leaves a %s report stream stopped',+ async (outcome) => {+ if (outcome === 'completed') jest.mocked(getTaskRun).mockResolvedValue({ ...RUN, status: 'completed' })+ else jest.mocked(openTaskRunStream).mockRejectedValueOnce(new ApiError(outcome, undefined))+ const { unmount } = renderHook(() => useTaskRun(REPORT, { taskId: TASK, runId: RUN.id }, true))+ try {+ await act(async () => {})+ const attempts = jest.mocked(getTaskRun).mock.calls.length+ await act(async () => {+ useConnectivity.setState({ status: 'offline' })+ })+ await act(async () => {+ useConnectivity.setState({ status: 'connected' })+ })+ expect(getTaskRun).toHaveBeenCalledTimes(attempts)+ } finally {+ unmount()+ }+ }+ )+test('shows reconnecting while admission retries, then unavailable when access is refused', async () => {jest.mocked(openTaskRunStream).mockRejectedValueOnce(new Error('offline'))diff --git a/products/mobile/src/features/handoff/useTaskRun.ts b/products/mobile/src/features/handoff/useTaskRun.tsindex 30ed60e42bd1..4893c07bced9 100644--- a/products/mobile/src/features/handoff/useTaskRun.ts+++ b/products/mobile/src/features/handoff/useTaskRun.ts@@ -1,10 +1,11 @@-import { useEffect, useState } from 'react'+import { useEffect, useRef, useState } from 'react'import { AppState, type AppStateStatus } from 'react-native'import { ApiError, NotSignedInError } from '@/api/client'import { readSse } from '@/api/sse'import { getTask, getTaskRun, openTaskRunStream, type TaskApi, type TaskRunApi } from '@/api/tasks'import { addSessionEndTask } from '@/auth/authStore'+import { useConnectivity } from '@/lib/connectivity'import { sleep } from '@/lib/sleep'import { deliverPermissionResponse } from './commands'@@ -235,7 +236,9 @@ async function readOnce(}}-export async function followRun(args: FollowArgs): Promise<void> {+type FollowOutcome = 'ended' | 'gave_up' | 'fatal' | 'aborted'++export async function followRun(args: FollowArgs): Promise<FollowOutcome> {const { reportId, taskId, signal } = argsconst store = useHandoffStore.getStateconst previous = store().reports[reportId]?.live@@ -263,18 +266,18 @@ export async function followRun(args: FollowArgs): Promise<void> {// Until this succeeds the screen shows what the report itself knows about the run.if (isAbort(error, signal) || isFatal(error) || attempt >= BOOTSTRAP_ATTEMPTS - 1) {setConnection('unavailable')- return+ return isAbort(error, signal) ? 'aborted' : isFatal(error) ? 'fatal' : 'gave_up'}setConnection('reconnecting')}try {await sleep(reconnectDelayMs(attempt), signal)} catch {- return+ return 'aborted'}}if (!run || signal.aborted) {- return+ return signal.aborted ? 'aborted' : 'ended'}const runId = run.idfollowedRunId = runId@@ -284,7 +287,7 @@ export async function followRun(args: FollowArgs): Promise<void> {}if (isTerminalRunStatus(state.status)) {setConnection(undefined)- return+ return 'ended'}setConnection('connecting')if (previous?.taskId !== taskId || previous.runId !== runId) {@@ -303,7 +306,7 @@ export async function followRun(args: FollowArgs): Promise<void> {try {const current = store().reports[reportId]?.liveif (!current || current.taskId !== taskId || current.runId !== runId) {- return+ return 'aborted'}hydration.resume(current, store().reports[reportId]?.answer)const result = await readOnce(args, runId, hydration, signal)@@ -314,14 +317,14 @@ export async function followRun(args: FollowArgs): Promise<void> {} catch (error) {if (isAbort(error, signal) || isFatal(error)) {setConnection('unavailable')- return+ return isAbort(error, signal) ? 'aborted' : 'fatal'}if (error instanceof ApiError && error.status === 503 && error.retryAfterSeconds) {retryAfterMs = error.retryAfterSeconds * 1000}}if (signal.aborted || !isCurrent()) {- return+ return 'aborted'}setConnection('reconnecting')if (control?.type === 'rotated' || control?.type === 'resync') {@@ -330,14 +333,14 @@ export async function followRun(args: FollowArgs): Promise<void> {try {const latest = await getTaskRun(taskId, runId, signal)if (signal.aborted || !isCurrent()) {- return+ return 'aborted'}state = store().applySnapshot(reportId, taskId, latest)hydration.applySnapshot(latest)} catch (error) {if (isAbort(error, signal) || isFatal(error)) {setConnection('unavailable')- return+ return isAbort(error, signal) ? 'aborted' : 'fatal'}}if (control?.type === 'ended' || !shouldReconnect(state, { perDrop, total })) {@@ -350,16 +353,17 @@ export async function followRun(args: FollowArgs): Promise<void> {setConnection(isTerminalRunStatus(state.status) ? undefined : 'unavailable')}args.onRefresh?.()- return+ return control?.type === 'ended' || isTerminalRunStatus(state.status) ? 'ended' : 'gave_up'}try {await sleep(retryAfterMs ?? reconnectDelayMs(perDrop), signal)} catch {- return+ return 'aborted'}perDrop += 1total += 1}+ return 'aborted'}export function useTaskRun(@@ -370,16 +374,31 @@ export function useTaskRun(onTaskSnapshot?: (task: TaskApi) => void): void {const active = useAppActive()+ const online = useConnectivity((state) => state.status !== 'offline')+ const lastFollow = useRef<{ key: string; outcome: FollowOutcome | null }>({ key: '', outcome: null })const refresh = useHandoffStore((state) => state.reports[reportId]?.refresh ?? 0)const taskId = target?.taskIdconst runId = target?.runId- // biome-ignore lint/correctness/useExhaustiveDependencies: `refresh` restarts the follow after a command found the run ended or moved on.+ const key = JSON.stringify([reportId, taskId, runId, refresh])useEffect(() => {- if (!enabled || !active || !taskId) {+ if (lastFollow.current.key !== key) lastFollow.current = { key, outcome: null }+ if (!enabled || !active || !online || !taskId) {+ if (lastFollow.current.outcome === 'gave_up') lastFollow.current.outcome = nullreturn}+ if (+ lastFollow.current.outcome === 'fatal' ||+ lastFollow.current.outcome === 'ended' ||+ lastFollow.current.outcome === 'gave_up'+ )+ returnconst controller = new AbortController()- void followRun({ reportId, taskId, runId, signal: controller.signal, onRefresh, onTaskSnapshot })+ lastFollow.current.outcome = null+ void followRun({ reportId, taskId, runId, signal: controller.signal, onRefresh, onTaskSnapshot }).then(+ (outcome) => {+ if (!controller.signal.aborted) lastFollow.current.outcome = outcome+ }+ )return () => controller.abort()- }, [enabled, active, reportId, taskId, runId, refresh, onRefresh, onTaskSnapshot])+ }, [enabled, active, online, reportId, taskId, runId, key, onRefresh, onTaskSnapshot])}diff --git a/products/mobile/src/features/inbox/hooks.test.tsx b/products/mobile/src/features/inbox/hooks.test.tsxindex 7f6d3239ed35..2fee0ef8032e 100644--- a/products/mobile/src/features/inbox/hooks.test.tsx+++ b/products/mobile/src/features/inbox/hooks.test.tsx@@ -255,10 +255,13 @@ describe('inbox hooks', () => {jest.useFakeTimers()const previousState = AppState.currentStateAppState.currentState = 'active'- let appChange: ((state: AppStateStatus) => void) | undefined+ const appListeners = new Set<(state: AppStateStatus) => void>()+ const appChange = (state: AppStateStatus): void => {+ for (const listener of appListeners) listener(state)+ }const listener = jest.spyOn(AppState, 'addEventListener').mockImplementation((_event, handler) => {- appChange = handler- return { remove: () => undefined }+ appListeners.add(handler)+ return { remove: () => appListeners.delete(handler) }})let reads = 0globalThis.fetch = jest.fn(async (url: string) => {diff --git a/products/mobile/src/features/inbox/hooks.ts b/products/mobile/src/features/inbox/hooks.tsindex d9df6ab4c1ac..87e1953d5ff2 100644--- a/products/mobile/src/features/inbox/hooks.ts+++ b/products/mobile/src/features/inbox/hooks.ts@@ -28,11 +28,12 @@ import { useProjectScope } from '@/auth/useProjectScope'import { useDataMode, useDemoMode } from '@/demo/demoMode'import { useDemoInboxQuery } from '@/demo/hooks'import { track } from '@/lib/analytics'+import { useConnectivity } from '@/lib/connectivity'import { toError } from '@/lib/errors'import { type AsyncAction, useAsyncAction } from '@/lib/useAsyncAction'import { useNow } from '@/lib/useNow'import { inboxFromReports, reportsFromPages, signalCountsFromReports } from '@/model/adapters/inbox'-import { errorQuery, loadingQuery } from '@/model/queryStates'+import { connectionLoadingQuery, errorQuery, loadingQuery } from '@/model/queryStates'import type { InboxItem, QueryState } from '@/model/types'import { useAppActive } from '../handoff/useTaskRun'@@ -130,6 +131,7 @@ function useLiveInboxItems(now: Date): InboxQueryState {const scope = useProjectScope()+ const offline = useConnectivity((state) => state.status === 'offline')const appActive = useAppActive()const active = enabled && scope !== nullconst snoozes = useSnoozeEntries()@@ -305,7 +307,7 @@ function useLiveInboxItems(if (list.isError) {return { ...errorQuery(toError(list.error), refetch), ...noMorePages, ...noItems }}- return { ...loadingQuery<InboxItem[]>(), refetch, ...noMorePages, ...noItems }+ return { ...connectionLoadingQuery<InboxItem[]>(offline, refetch), ...noMorePages, ...noItems }}/** `for_you/` has no sort or filter parameters, so `filters` apply on the device to the ranked reports. */diff --git a/products/mobile/src/features/report/hooks.test.tsx b/products/mobile/src/features/report/hooks.test.tsxindex e00972703c32..898d82486db4 100644--- a/products/mobile/src/features/report/hooks.test.tsx+++ b/products/mobile/src/features/report/hooks.test.tsx@@ -93,10 +93,13 @@ describe('useReport', () => {test('polls only the visible foreground report and refreshes on return without polling evidence', async () => {jest.useFakeTimers()- let appChange!: (state: AppStateStatus) => void+ const appListeners = new Set<(state: AppStateStatus) => void>()+ const appChange = (state: AppStateStatus): void => {+ for (const listener of appListeners) listener(state)+ }const listener = jest.spyOn(AppState, 'addEventListener').mockImplementation((_event, handler) => {- appChange = handler- return { remove: () => undefined }+ appListeners.add(handler)+ return { remove: () => appListeners.delete(handler) }})const data = reportFixture({ id: REPORT_ID })globalThis.fetch = jest.fn(async (input) => {diff --git a/products/mobile/src/features/report/hooks.ts b/products/mobile/src/features/report/hooks.tsindex 15cee3a25278..5d9f4fa0f7a4 100644--- a/products/mobile/src/features/report/hooks.ts+++ b/products/mobile/src/features/report/hooks.ts@@ -7,9 +7,10 @@ import { getTask, type TaskApi } from '@/api/tasks'import { useProjectScope } from '@/auth/useProjectScope'import { useDataMode } from '@/demo/demoMode'import { useDemoReportQuery } from '@/demo/hooks'+import { useConnectivity } from '@/lib/connectivity'import { toError } from '@/lib/errors'import { type ReportTaskInput, reportTaskId, reportView } from '@/model/adapters/report'-import { errorQuery, loadingQuery, successQuery } from '@/model/queryStates'+import { connectionLoadingQuery, errorQuery, loadingQuery, successQuery } from '@/model/queryStates'import type { InboxItem, QueryState, ReportActions, ReportView } from '@/model/types'import { useHandoffActions } from '../handoff/hooks'@@ -31,6 +32,7 @@ type TaskWithCreator = TaskApi & Pick<ReportTaskInput, 'created_by'>// page, because they are the evidence then.function useLiveReport(reportId: string, enabled: boolean, refreshWhileVisible: boolean): QueryState<ReportView> {const scope = useProjectScope()+ const offline = useConnectivity((state) => state.status === 'offline')const appActive = useAppActive()const active = enabled && appActive && scope !== nullconst queryClient = useQueryClient()@@ -119,7 +121,7 @@ function useLiveReport(reportId: string, enabled: boolean, refreshWhileVisible:report.isFetching || artefacts.isFetching || page.isFetching || signals.isFetching || task.isFetchingreturn successQuery(view, { refetch, isRefetching })}- return { ...loadingQuery<ReportView>(), refetch }+ return connectionLoadingQuery<ReportView>(offline, refetch)}export function useReport(reportId: string, refreshWhileVisible = false, enabled = true): QueryState<ReportView> {diff --git a/products/mobile/src/features/views/browseHooks.ts b/products/mobile/src/features/views/browseHooks.tsindex c1b8558f7581..e38e23cf3b78 100644--- a/products/mobile/src/features/views/browseHooks.ts+++ b/products/mobile/src/features/views/browseHooks.ts@@ -6,7 +6,7 @@ import type { PaginatedApi } from '@/api/reports'import { demoDashboardRefFor, demoDashboardRows, demoInsightRows } from '@/demo/views'import { toError } from '@/lib/errors'import { dashboardRows, insightRows } from '@/model/adapters/viewPins'-import { errorQuery, loadingQuery, successQuery } from '@/model/queryStates'+import { connectionLoadingQuery, errorQuery, loadingQuery, successQuery } from '@/model/queryStates'import type { QueryState } from '@/model/types'import type { BrowseRow, PinView, RecentView } from '@/model/views'@@ -108,7 +108,7 @@ function useBrowseList<T extends DashboardBasicApi | InsightBasicApi>(if (list.isError) {return { ...errorQuery(toError(list.error), refetch), ...NO_PAGING }}- return { ...loadingQuery<BrowseRow[]>(), refetch, ...NO_PAGING }+ return { ...connectionLoadingQuery<BrowseRow[]>(context.offline, refetch), ...NO_PAGING }}/** Browse, Dashboards: the web Views order (`-last_viewed_at`), without deleted dashboards. */@@ -173,7 +173,7 @@ function useServerSearch(kind: 'dashboards' | 'insights', query: string, active:if (search.isError) {return errorQuery(toError(search.error), search.refetch)}- return loadingQuery()+ return connectionLoadingQuery(context.ready && context.offline, search.refetch)}function useDebouncedSearchText(text: string): string {diff --git a/products/mobile/src/features/views/list/ViewsScreen.tsx b/products/mobile/src/features/views/list/ViewsScreen.tsxindex 635d0e6e3e96..00f8286404dd 100644--- a/products/mobile/src/features/views/list/ViewsScreen.tsx+++ b/products/mobile/src/features/views/list/ViewsScreen.tsx@@ -389,7 +389,10 @@ function ViewsBody(): ReactElement {? {type: 'note',key: `${key}:error`,- text: `Couldn't search ${title.toLowerCase()}. Try again in a moment.`,+ text:+ context.offline && state.error+ ? state.error.message+ : `Couldn't search ${title.toLowerCase()}. Try again in a moment.`,}: nulladd(key, title, note ? [note] : viewItems(rows, 'search', key))@@ -455,7 +458,7 @@ function ViewsBody(): ReactElement {),})return result- }, [search, pins, recent, list.pinsTruncated, now, hintTargetId, browseEntries])+ }, [search, pins, recent, list.pinsTruncated, now, hintTargetId, browseEntries, context.offline])const renderItem = useCallback(({ item }: { item: ListItem }): ReactElement | null => {diff --git a/products/mobile/src/features/views/pinHooks.test.ts b/products/mobile/src/features/views/pinHooks.test.tsindex 5d285c3d652c..145751dcc9d1 100644--- a/products/mobile/src/features/views/pinHooks.test.ts+++ b/products/mobile/src/features/views/pinHooks.test.ts@@ -1,11 +1,12 @@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 { createElement, type ReactNode } from 'react'import type { PaginatedApi } from '@/api/reports'-import { createShortcut, deleteShortcut, type FileSystemShortcutApi } from '@/api/shortcuts'+import { createShortcut, deleteShortcut, type FileSystemShortcutApi, fetchShortcuts } from '@/api/shortcuts'import { useAuthStore } from '@/auth/authStore'import { setSessionTokens } from '@/auth/tokens'+import { OfflineError, useConnectivity } from '@/lib/connectivity'import { pinView, unpinView, usePinActions } from './pinHooks'import { useViewsContext } from './useViewsContext'@@ -16,6 +17,7 @@ jest.mock('@react-native-async-storage/async-storage', () =>jest.mock('@/api/shortcuts', () => ({...jest.requireActual<typeof import('@/api/shortcuts')>('@/api/shortcuts'),createShortcut: jest.fn(),+ fetchShortcuts: jest.fn(),deleteShortcut: jest.fn(),}))@@ -32,7 +34,43 @@ const created: FileSystemShortcutApi = {}describe('pin writes', () => {- beforeEach(() => jest.clearAllMocks())+ beforeEach(() => {+ jest.clearAllMocks()+ useConnectivity.setState({ status: 'connected' })+ })+ afterEach(() => useConnectivity.setState({ status: 'unknown' }))++ test.each(['offline', 'disconnect'] as const)(+ 'pin fails promptly on %s and never resumes its write',+ async (when) => {+ const client = new QueryClient({ defaultOptions: { queries: { retry: false, gcTime: Infinity } } })+ const listKey = ['views', 'https://us.example.com', 1, 'shortcuts']+ let finish: (page: PaginatedApi<FileSystemShortcutApi>) => void = () => undefined+ jest.mocked(fetchShortcuts).mockReturnValue(+ new Promise((resolve) => {+ finish = resolve+ })+ )+ await new Promise((resolve) => setTimeout(resolve, 0))+ if (when === 'offline') useConnectivity.setState({ status: 'offline' })+ const pending = pinView(+ { client, listKey, demo: false, isCurrent: () => true },+ { kind: 'dashboard', id: 12, name: 'Growth' },+ 'header'+ )+ if (when === 'disconnect') {+ await waitFor(() => expect(fetchShortcuts).toHaveBeenCalledTimes(1))+ useConnectivity.setState({ status: 'offline' })+ }+ await expect(pending).rejects.toBeInstanceOf(OfflineError)+ useConnectivity.setState({ status: 'connected' })+ finish({ count: 0, next: null, results: [] })+ await Promise.resolve()+ await Promise.resolve()+ expect(createShortcut).not.toHaveBeenCalled()+ client.clear()+ }+ )test('an unpin made while the pin saves waits for it and deletes the row it created', async () => {const client = new QueryClient({ defaultOptions: { queries: { gcTime: Number.POSITIVE_INFINITY } } })@@ -67,6 +105,7 @@ describe('pin writes', () => {client.setQueryData<PaginatedApi<FileSystemShortcutApi>>(listKey, { count: 0, next: null, results: [] })jest.mocked(useViewsContext).mockReturnValue({mode: 'live',+ offline: false,identity: 'example-session',scope,dataScope: `${scope.host}|${scope.projectId}`,diff --git a/products/mobile/src/features/views/pinHooks.ts b/products/mobile/src/features/views/pinHooks.tsindex 4608c09beda7..e09831ba56e1 100644--- a/products/mobile/src/features/views/pinHooks.ts+++ b/products/mobile/src/features/views/pinHooks.ts@@ -15,9 +15,10 @@ import { useAuthStore } from '@/auth/authStore'import { sessionGeneration } from '@/auth/tokens'import { useDemoViews } from '@/demo/views'import { abortError } from '@/lib/abort'+import { OfflineError, useConnectivity, whileOnline } from '@/lib/connectivity'import { toError } from '@/lib/errors'import { mergeRecent, pinsFromShortcuts, shortcutMatchKey } from '@/model/adapters/viewPins'-import { errorQuery, loadingQuery, successQuery } from '@/model/queryStates'+import { connectionLoadingQuery, errorQuery, loadingQuery, successQuery } from '@/model/queryStates'import type { QueryState } from '@/model/types'import type {DashboardTileView,@@ -141,7 +142,7 @@ export function usePins({ refetchOnMount = false }: { refetchOnMount?: boolean }} else if (query.isError) {state = errorQuery(toError(query.error), refetch)} else {- state = { ...loadingQuery<PinView[]>(), refetch }+ state = connectionLoadingQuery<PinView[]>(context.offline, refetch)}return {pins: state,@@ -203,10 +204,12 @@ function assertCurrentWrite(list: PinWriteTarget): void {// being dropped. An unpin that waits for a pin then finds the row the pin created and deletes it.const pinWrites = new Map<string, Promise<void>>()-function queuePinWrite(list: PinWriteTarget, matchKey: string, run: () => Promise<void>): Promise<void> {+async function queuePinWrite(list: PinWriteTarget, matchKey: string, run: () => Promise<void>): Promise<void> {+ if (!list.demo && useConnectivity.getState().status === 'offline') throw new OfflineError()const key = `${list.demo ? 'demo' : freshnessKey(list.listKey)}|${matchKey}`const next = (pinWrites.get(key) ?? Promise.resolve()).then(() => {assertCurrentWrite(list)+ if (!list.demo && useConnectivity.getState().status === 'offline') throw new OfflineError()return run()})const settled = next.catch(() => undefined)@@ -241,15 +244,17 @@ export function pinView(list: PinWriteTarget, target: PinTarget, from: PinSourceconst page =state?.data && Date.now() - state.dataUpdatedAt < READ_FLOOR_MS? state.data- : await client.fetchQuery({- queryKey: listKey,- queryFn: async ({ signal }) => {- const page = await readShortcuts(signal, () => assertCurrentWrite(list))- assertCurrentWrite(list)- return page- },- staleTime: 0,- })+ : await whileOnline(() =>+ client.fetchQuery({+ queryKey: listKey,+ queryFn: async ({ signal }) => {+ const page = await readShortcuts(signal, () => assertCurrentWrite(list))+ assertCurrentWrite(list)+ return page+ },+ staleTime: 0,+ })+ )assertCurrentWrite(list)if (rowsFor(page).some((row) => shortcutMatchKey(row.type, row.ref) === key)) {return@@ -498,7 +503,7 @@ export function useRecentViews(pinnedKeys: ReadonlySet<string>): RecentState {// A failed web read still shows the phone's own views.recent = successQuery(merged, { isRefetching: server.isRefetching, refetch })} else {- recent = { ...loadingQuery<RecentView[]>(), refetch }+ recent = connectionLoadingQuery<RecentView[]>(context.offline, refetch)}return { recent, list }}@@ -635,7 +640,7 @@ export function useViewsList(): ViewsListState {items,visibleKeys: visibility.visibleKeys,lists,- enabled: context.ready,+ enabled: context.ready && !context.offline,})return {pins,diff --git a/products/mobile/src/features/views/useViewRefresh.test.tsx b/products/mobile/src/features/views/useViewRefresh.test.tsxindex 4b9c6d616be4..1d77c679b448 100644--- a/products/mobile/src/features/views/useViewRefresh.test.tsx+++ b/products/mobile/src/features/views/useViewRefresh.test.tsx@@ -3,7 +3,7 @@ import { act, renderHook } from '@testing-library/react-native'import type { Freshness } from '@/model/views'-import { REFRESH_MIN_MS } from './freshness'+import { READ_FLOOR_MS, REFRESH_MIN_MS } from './freshness'import type { ReadResult, RefreshMode } from './refreshQueue'import { viewsQueue } from './refreshQueue'import { type RefreshContainer, type RefreshItem, useViewRefresh, type ViewRefreshOptions } from './useViewRefresh'@@ -104,6 +104,103 @@ describe('useViewRefresh on a dashboard', () => {viewsQueue.reset()})+ test('reconnect retries tile work interrupted while awaiting its dashboard container', async () => {+ const current = {+ ...options('7d', tiles('7d', 2, false)),+ container: { ...dashboard('7d'), read: read('7d-dashboard', true) },+ }+ const { rerender, unmount } = renderHook(+ ({ enabled }: { enabled: boolean }) => useViewRefresh({ ...current, enabled }),+ { initialProps: { enabled: true } }+ )+ try {+ await flush()+ expect(reads).toEqual(['7d-dashboard'])+ rerender({ enabled: false })+ await flush()+ rerender({ enabled: true })+ await flush()+ await settle('7d-dashboard')+ expect(reads).toEqual(['7d-dashboard', '7d-tile-0', '7d-tile-1'])+ } finally {+ unmount()+ }+ })++ test.each(+ (['insight', 'web_analytics'] as const).flatMap((screen) =>+ (['uncached', 'cached', 'still pending'] as const).map((state) => ({ screen, state }))+ )+ )(+ '$screen retries a $state interrupted read on reconnect while successful reads keep their floor',+ async ({ screen, state }) => {+ jest.useFakeTimers()+ let finish: ((value: ReadResult) => void) | undefined+ let snapshot: Freshness | undefined = state === 'cached' ? oldValue() : undefined+ const itemRead = jest.fn(+ () =>+ new Promise<ReadResult>((resolve) => {+ finish = resolve+ })+ )+ const item: RefreshItem = {+ key: 'interrupted',+ family: screen === 'insight' ? 'insights' : 'query',+ windowMode: 'blocking',+ snapshot: () => snapshot,+ read: itemRead,+ }+ const current: ViewRefreshOptions = {+ screen,+ dataScope: 'demo',+ screenKey: screen,+ items: [item],+ enabled: true,+ }+ const { rerender, unmount } = renderHook((props: ViewRefreshOptions) => useViewRefresh(props), {+ initialProps: current,+ })+ try {+ await flush()+ expect(itemRead).toHaveBeenCalledTimes(1)+ rerender({ ...current, enabled: false })+ const fail = async (): Promise<void> => {+ await act(async () => {+ if (snapshot) snapshot = { ...snapshot, readAt: Date.now(), refreshFailed: true }+ finish?.({ status: 'failed', computed: false })+ })+ }+ if (state !== 'still pending') await fail()+ rerender(current)+ await flush()+ if (state === 'still pending') {+ expect(itemRead).toHaveBeenCalledTimes(1)+ await fail()+ }+ expect(itemRead).toHaveBeenCalledTimes(2)+ await act(async () => {+ snapshot = {+ lastRefreshAt: new Date().toISOString(),+ readAt: Date.now(),+ cacheTargetAge: null,+ nextAllowedRefreshAt: null,+ refreshFailed: false,+ }+ finish?.(OK)+ })+ rerender({ ...current, enabled: false })+ rerender(current)+ await flush()+ expect(itemRead).toHaveBeenCalledTimes(2)+ await act(async () => jest.advanceTimersByTime(READ_FLOOR_MS))+ expect(itemRead).toHaveBeenCalledTimes(2)+ } finally {+ unmount()+ jest.useRealTimers()+ }+ }+ )+test('computes only the first rows before the list reports what it shows', async () => {const { unmount } = renderHook(() => useViewRefresh(options('7d', tiles('7d', 10, false))))await flush()diff --git a/products/mobile/src/features/views/useViewRefresh.ts b/products/mobile/src/features/views/useViewRefresh.tsindex 78ade2865a57..57e40aaf34ca 100644--- a/products/mobile/src/features/views/useViewRefresh.ts+++ b/products/mobile/src/features/views/useViewRefresh.ts@@ -197,6 +197,8 @@ export function useViewRefresh(options: ViewRefreshOptions): ViewRefresh {useNow(30_000)const containerReading = useRef<Promise<JobResult> | null>(null)+ const itemReads = useRef(new Map<string, Promise<JobResult>>())+ const recoverOnEnable = useRef(false)const recordEmptyFailure = useCallback((key: string, result: JobResult, hasValue: () => boolean): void => {if ((result.status === 'failed' || result.status === 'capped') && !hasValue()) {@@ -224,6 +226,7 @@ export function useViewRefresh(options: ViewRefreshOptions): ViewRefresh {run: read,userRetry,})+ itemReads.current.set(key, job)counters.jobs.push(job)void job.then((result) =>recordEmptyFailure(key, result, () => {@@ -307,7 +310,8 @@ export function useViewRefresh(options: ViewRefreshOptions): ViewRefresh {trigger: PassTrigger,counters: PassCounters,generation: number,- passGroup: string+ passGroup: string,+ recovering: boolean) => {const current = optionsRef.currentconst startedAt = Date.now()@@ -322,14 +326,22 @@ export function useViewRefresh(options: ViewRefreshOptions): ViewRefresh {return}for (const item of fresh) {+ const previous = recovering ? await itemReads.current.get(item.key) : undefined+ if (!stillActive(generation, passGroup)) {+ return+ }+ const failed = previous?.status === 'failed'const snapshot = item.snapshot()// Dashboard tiles follow the web's open path: after the cache-only dashboard read, a tile computes// only when it has no result or its `cache_target_age` has passed.- const wanted = current.container- ? drawable(item) && (!hasGoodValue(snapshot) || cacheTargetPassed(snapshot))- : drawable(item) && (item.openDue?.() ?? isDue(snapshot))+ const wanted =+ drawable(item) &&+ (failed ||+ (current.container+ ? !hasGoodValue(snapshot) || cacheTargetPassed(snapshot)+ : (item.openDue?.() ?? isDue(snapshot))))if (wanted) {- send(counters, item.key, item.family, 'blocking', item.read)+ send(counters, item.key, item.family, 'blocking', item.read, failed)}}await report(trigger, counters, startedAt, age, null)@@ -425,6 +437,9 @@ export function useViewRefresh(options: ViewRefreshOptions): ViewRefresh {// biome-ignore lint/correctness/useExhaustiveDependencies: the key strings stand for the items, read through the ref.useEffect(() => {if (!enabled || !isFocused) {+ if (!enabled) recoverOnEnable.current = true+ seen.current.clear()+ containerKey.current = nullreturn}const current = optionsRef.current@@ -433,6 +448,7 @@ export function useViewRefresh(options: ViewRefreshOptions): ViewRefresh {// Leaving a range dropped its queued reads, so coming back to it checks its items again.seenGroup.current = groupOf(current)seen.current.clear()+ itemReads.current.clear()}let containerOpened = falseif (current.container && containerKey.current !== current.container.key) {@@ -453,7 +469,9 @@ export function useViewRefresh(options: ViewRefreshOptions): ViewRefresh {}const trigger: PassTrigger = pendingRangeTrigger.current ? 'range' : 'open'pendingRangeTrigger.current = false- void openItems(fresh, trigger, counters, passGeneration.current, group)+ const recovering = recoverOnEnable.current+ recoverOnEnable.current = false+ void openItems(fresh, trigger, counters, passGeneration.current, group, recovering)}, [enabled, isFocused, group, itemKeys, visibleKeyList, options.container?.key, openItems, readContainer])// Screen focus after the first one, which is the mount. Leaving drops what only this screen queued.@@ -525,6 +543,7 @@ export function useViewRefresh(options: ViewRefreshOptions): ViewRefresh {run: item.read,userRetry: true,})+ itemReads.current.set(item.key, job)void job.then((result) => recordEmptyFailure(item.key, result, () => hasGoodValue(item.snapshot())))return true},diff --git a/products/mobile/src/features/views/useViewsContext.ts b/products/mobile/src/features/views/useViewsContext.tsindex fa54dcfd552a..9b0656862c95 100644--- a/products/mobile/src/features/views/useViewsContext.ts+++ b/products/mobile/src/features/views/useViewsContext.ts@@ -6,6 +6,7 @@ import { useAuthStore } from '@/auth/authStore'import { sessionGeneration } from '@/auth/tokens'import { useProjectScope } from '@/auth/useProjectScope'import { type DataMode, useDataMode } from '@/demo/demoMode'+import { useConnectivity } from '@/lib/connectivity'import type { ItemContext } from './items'import { useViewsAccess, type ViewsAccess } from './useViewsAccess'@@ -13,6 +14,7 @@ import { useViewsAccess, type ViewsAccess } from './useViewsAccess'export interface ViewsContext {identity: stringmode: DataMode+ offline: boolean/** Null in demo mode, so demo cache entries never mix with a project's. */scope: ProjectScope | null/** `demo`, or `{host}|{project id}`: refresh floors and session ranges stay inside one. */@@ -25,6 +27,7 @@ export interface ViewsContext {export function useViewsContext(): ViewsContext {const mode = useDataMode()+ const offline = useConnectivity((state) => state.status === 'offline') && mode === 'live'const account = useAuthStore((state) => `${state.status}|${state.user?.uuid ?? ''}`)const projectScope = useProjectScope()const client = useQueryClient()@@ -35,5 +38,5 @@ export function useViewsContext(): ViewsContext {const ready = demo || (mode === 'live' && scope !== null && access.state === 'ok')const dataScope = demo ? 'demo' : scope ? `${scope.host}|${scope.projectId}` : 'none'const identity = `${mode}|${account}|${sessionGeneration()}|${dataScope}`- return { identity, mode, scope, dataScope, access, ready, item }+ return { identity, mode, offline, scope, dataScope, access, ready, item }}diff --git a/products/mobile/src/features/views/viewHooks.ts b/products/mobile/src/features/views/viewHooks.tsindex 48a12703c816..76d15fa8680e 100644--- a/products/mobile/src/features/views/viewHooks.ts+++ b/products/mobile/src/features/views/viewHooks.ts@@ -11,7 +11,7 @@ import { DEMO_READ_MS, demoActorsResponse } from '@/demo/views'import { sleep } from '@/lib/sleep'import { ignoresRangeOverride } from '@/model/adapters/insightSnapshot'import { actorsFromResponse } from '@/model/adapters/webOverview'-import { errorQuery, loadingQuery, successQuery } from '@/model/queryStates'+import { connectionLoadingQuery, errorQuery, loadingQuery, successQuery } from '@/model/queryStates'import type { QueryState } from '@/model/types'import type {ActorRow,@@ -98,7 +98,8 @@ function viewState<T>(error: ItemErrorKind | null,ready: boolean,busy: boolean,- refetch: () => void+ refetch: () => void,+ offline: boolean): QueryState<T> {if (data !== undefined) {return successQuery(data, { refetch })@@ -106,7 +107,7 @@ function viewState<T>(if (error && !busy) {return errorQuery(new Error(ERROR_COPY[error]), refetch)}- return ready ? { ...loadingQuery<T>(), refetch } : loadingQuery()+ return ready ? connectionLoadingQuery<T>(offline, refetch) : loadingQuery()}interface Held<T> {@@ -298,7 +299,7 @@ export function useDashboardScreen(dashboardRef: string, options: ViewOpenOptionitems,visibleKeys,container,- enabled: context.ready,+ enabled: context.ready && !context.offline,rangeKey: overrideId,})useRecordRecentView(view ? { kind: 'dashboard', ref: dashboardRef, name: view.name } : null)@@ -306,7 +307,7 @@ export function useDashboardScreen(dashboardRef: string, options: ViewOpenOptionuseDashboardTilesShownEvent(view, tiles, items)return {access: context.access,- dashboard: viewState(view, error, context.ready, refresh.busy, refresh.retry),+ dashboard: viewState(view, error, context.ready, refresh.busy, refresh.retry, context.offline),error,tiles,range,@@ -428,7 +429,7 @@ export function useInsightScreen(shortId: string, options: InsightScreenOptions)dataScope: context.dataScope,screenKey: `insight:${shortId}`,items,- enabled: context.ready,+ enabled: context.ready && !context.offline,rangeKey: `${overrideId}|${compareId ?? ''}`,})const itemKey = items[0]?.key ?? null@@ -467,7 +468,8 @@ export function useInsightScreen(shortId: string, options: InsightScreenOptions)error,context.ready,refresh.busy,- refresh.retry+ refresh.retry,+ context.offline),error,range,@@ -514,7 +516,7 @@ export function useWebAnalyticsScreen(options: ViewOpenOptions): WebAnalyticsScrdataScope: context.dataScope,screenKey: 'web',items,- enabled: context.ready,+ enabled: context.ready && !context.offline,rangeKey: queryId,})const error = useItemError(items[0]?.key ?? null)@@ -528,7 +530,8 @@ export function useWebAnalyticsScreen(options: ViewOpenOptions): WebAnalyticsScrerror,context.ready,refresh.busy,- refresh.retry+ refresh.retry,+ context.offline),error,range,diff --git a/products/mobile/src/lib/connectionLoading.test.tsx b/products/mobile/src/lib/connectionLoading.test.tsxnew file mode 100644index 000000000000..73f5031ac196--- /dev/null+++ b/products/mobile/src/lib/connectionLoading.test.tsx@@ -0,0 +1,134 @@+import { onlineManager, QueryClient, QueryClientProvider } from '@tanstack/react-query'+import { act, renderHook, waitFor } from '@testing-library/react-native'+import { getNetworkStateAsync } from 'expo-network'+import type { ReactElement, ReactNode } from 'react'+import { AppState } from 'react-native'+import { setAuthProvider } from '@/api/client'+import { useAuthStore } from '@/auth/authStore'+import { useChatList } from '@/features/chats/hooks'+import { useInboxItems } from '@/features/inbox/hooks'+import { useReport } from '@/features/report/hooks'+import { useBrowseDashboards } from '@/features/views/browseHooks'+import { usePins, useRecentViews } from '@/features/views/pinHooks'+import { viewsQueue } from '@/features/views/refreshQueue'+import { useDashboardScreen } from '@/features/views/viewHooks'+import { reportFixture } from '@/model/adapters/testFixtures'+import type { QueryState } from '@/model/types'++import { useConnectivity } from './connectivity'++jest.mock('expo-notifications', () => ({}))+jest.mock('expo-router', () => {+ const { useEffect } = jest.requireActual<typeof import('react')>('react')+ return {+ useFocusEffect: (effect: () => undefined | (() => void)) => useEffect(effect, [effect]),+ useIsFocused: () => true,+ }+})+jest.mock('@/auth/useProjectScope', () => {+ const scope = { host: 'https://app.example.com', projectId: 2 }+ return { useProjectScope: () => scope }+})+jest.mock('@/demo/demoMode', () => ({ ...jest.requireActual('@/demo/demoMode'), useDataMode: () => 'live' }))+jest.mock('@/features/views/useViewsAccess', () => ({+ ...jest.requireActual('@/features/views/useViewsAccess'),+ useViewsAccess: () => ({ state: 'ok', missingScope: null }),+}))++const NO_PINS = new Set<string>()++describe('paused reads without cached data', () => {+ beforeEach(() => {+ viewsQueue.reset()+ AppState.currentState = 'active'+ jest.spyOn(AppState, 'addEventListener').mockReturnValue({ remove: jest.fn() })+ useAuthStore.setState({+ status: 'signed_in',+ signedIn: true,+ host: 'https://app.example.com',+ projectId: 2,+ user: {+ id: 7,+ uuid: 'synthetic-user',+ distinctId: 'synthetic-user',+ email: '[email protected]',+ name: 'Example',+ },+ })+ setAuthProvider({+ getAuth: () => ({ host: 'https://app.example.com', accessToken: 'fake', projectId: 2, session: 1 }),+ refreshAccessToken: async () => null,+ })+ jest.mocked(getNetworkStateAsync).mockImplementation(() => new Promise(() => undefined))+ useConnectivity.setState({ status: 'offline' })+ onlineManager.setOnline(false)+ globalThis.fetch = jest.fn(async (url: string) => ({+ ok: true,+ status: 200,+ headers: { get: () => null },+ text: async () =>+ JSON.stringify(+ url.includes('/dashboards/1/')+ ? { id: 1, name: 'Example dashboard', tiles: [] }+ : url.endsWith('/signals/reports/offline-report/')+ ? reportFixture({ id: 'offline-report' })+ : url.includes('/today/')+ ? { lead: '', evidence: [], impact_sentence: '', impact_numbers: [], last_seen: null }+ : url.endsWith('/signals/')+ ? { signals: [] }+ : { count: 0, next: null, results: [] }+ ),+ })) as unknown as typeof fetch+ })+ afterEach(() => {+ viewsQueue.reset()+ onlineManager.setOnline(true)+ useConnectivity.setState({ status: 'unknown' })+ setAuthProvider(null)+ jest.restoreAllMocks()+ })++ test.each<[string, () => QueryState<unknown>]>([+ ['inbox', () => useInboxItems()],+ ['chats', () => useChatList()],+ ['report', () => useReport('offline-report')],+ ['pinned views', () => usePins().pins],+ ['recent views', () => useRecentViews(NO_PINS).recent],+ ['browse dashboards', () => useBrowseDashboards()],+ ['dashboard detail', () => useDashboardScreen('1', { from: 'browse' }).dashboard],+ ])(+ '%s shows a connection state, resumes automatically, and retains loaded data offline',+ async (_name, useRead) => {+ const client = new QueryClient({+ defaultOptions: { queries: { retry: false, gcTime: Infinity, staleTime: Infinity } },+ })+ const wrapper = ({ children }: { children: ReactNode }): ReactElement => (+ <QueryClientProvider client={client}>{children}</QueryClientProvider>+ )+ const { result, unmount } = renderHook(() => useRead(), { wrapper })+ try {+ expect(result.current.data).toBeUndefined()+ expect(result.current.isLoading).toBe(false)+ expect(result.current.error?.message).toContain('Your data will load when your connection returns')+ expect(globalThis.fetch).not.toHaveBeenCalled()+ await act(async () => {+ useConnectivity.setState({ status: 'connected' })+ onlineManager.setOnline(true)+ })+ await waitFor(() => expect(result.current.data).toBeDefined())+ const loaded = result.current.data+ expect(result.current.isError).toBe(false)+ await act(async () => {+ useConnectivity.setState({ status: 'offline' })+ onlineManager.setOnline(false)+ })+ expect(result.current.data).toEqual(loaded)+ expect(result.current.isError).toBe(false)+ expect(result.current.isLoading).toBe(false)+ } finally {+ unmount()+ client.clear()+ }+ }+ )+})diff --git a/products/mobile/src/lib/connectivity.native.test.ts b/products/mobile/src/lib/connectivity.native.test.tsnew file mode 100644index 000000000000..d92071c060ae--- /dev/null+++ b/products/mobile/src/lib/connectivity.native.test.ts@@ -0,0 +1,110 @@+import { type NetworkState, NetworkStateType } from 'expo-network'+import { AppState, type AppStateStatus } from 'react-native'++import { monitorConnectivity, useConnectivity } from './connectivity'++jest.mock('expo-network', () => jest.requireActual('expo-network'))+jest.mock('expo-network/build/ExpoNetwork', () => ({+ __esModule: true,+ default: {+ getNetworkStateAsync: jest.fn(),+ addListener: jest.fn(),+ },+}))++const bridge = jest.requireMock('expo-network/build/ExpoNetwork').default as {+ getNetworkStateAsync: jest.Mock<Promise<NetworkState>, []>+ addListener: jest.Mock+}++function state(connected: boolean): NetworkState {+ return {+ type: NetworkStateType.WIFI,+ isConnected: connected,+ isInternetReachable: false,+ }+}++describe('connectivity with the installed Expo Network module', () => {+ let nativeEvent: (state: NetworkState) => void+ let appChange: (state: AppStateStatus) => void+ const originalAppState = AppState.currentState++ beforeEach(() => {+ jest.useFakeTimers()+ AppState.currentState = 'active'+ useConnectivity.setState({ status: 'unknown' })+ bridge.getNetworkStateAsync.mockImplementation(async () => state(true))+ bridge.addListener.mockImplementation((_event, listener) => {+ nativeEvent = listener+ return { remove: jest.fn() }+ })+ jest.spyOn(AppState, 'addEventListener').mockImplementation((_event, listener) => {+ appChange = listener+ return { remove: jest.fn() }+ })+ })+ afterEach(() => {+ AppState.currentState = originalAppState+ jest.restoreAllMocks()+ jest.useRealTimers()+ })++ test.each([false, true])(+ 'a late refresh reporting %s cannot overwrite a newer native event',+ async (oldConnected) => {+ bridge.getNetworkStateAsync.mockResolvedValueOnce(state(oldConnected))+ const setOnline = jest.fn()+ const stop = monitorConnectivity(setOnline)+ try {+ await jest.advanceTimersByTimeAsync(0)+ expect(useConnectivity.getState().status).toBe(oldConnected ? 'connected' : 'offline')+ let resolve: (state: NetworkState) => void = () => undefined+ bridge.getNetworkStateAsync.mockImplementationOnce(+ () =>+ new Promise((yes) => {+ resolve = yes+ })+ )+ appChange('background')+ appChange('active')+ const deliveredBefore = setOnline.mock.calls.length+ nativeEvent(state(!oldConnected))+ await jest.advanceTimersByTimeAsync(0)+ resolve(state(oldConnected))+ await jest.advanceTimersByTimeAsync(0)+ expect(useConnectivity.getState().status).toBe(oldConnected ? 'offline' : 'connected')+ expect(setOnline.mock.calls.slice(deliveredBefore)).toEqual([[!oldConnected]])+ } finally {+ stop()+ }+ }+ )++ test('native events remain responsive while refresh is unresolved and cleanup discards the late result', async () => {+ const setOnline = jest.fn()+ const stop = monitorConnectivity(setOnline)+ await jest.advanceTimersByTimeAsync(0)+ let resolve: (state: NetworkState) => void = () => undefined+ bridge.getNetworkStateAsync.mockImplementationOnce(+ () =>+ new Promise((yes) => {+ resolve = yes+ })+ )+ appChange('background')+ appChange('active')+ nativeEvent(state(false))+ await jest.advanceTimersByTimeAsync(0)+ expect(useConnectivity.getState().status).toBe('offline')+ nativeEvent(state(true))+ await jest.advanceTimersByTimeAsync(0)+ expect(useConnectivity.getState().status).toBe('connected')+ stop()+ const calls = setOnline.mock.calls.length+ resolve(state(false))+ await jest.advanceTimersByTimeAsync(0)+ expect(setOnline).toHaveBeenCalledTimes(calls)+ expect(useConnectivity.getState().status).toBe('connected')+ })+})diff --git a/products/mobile/src/lib/connectivity.test.ts b/products/mobile/src/lib/connectivity.test.tsnew file mode 100644index 000000000000..56d3909c70ce--- /dev/null+++ b/products/mobile/src/lib/connectivity.test.ts@@ -0,0 +1,107 @@+import { onlineManager, QueryClient, QueryObserver } from '@tanstack/react-query'+import { addNetworkStateListener, getNetworkStateAsync, type NetworkState, NetworkStateType } from 'expo-network'+import { AppState, type AppStateStatus } from 'react-native'+import { monitorConnectivity, useConnectivity } from './connectivity'++function state(isConnected: boolean | undefined): NetworkState {+ return {+ type: NetworkStateType.WIFI,+ isConnected,+ isInternetReachable: false,+ }+}++describe('connectivity', () => {+ let update: (state: NetworkState) => void+ let changeAppState: (state: AppStateStatus) => void+ let unsubscribe: jest.Mock+ let remove: jest.Mock+ const originalAppState = AppState.currentState+ beforeEach(() => {+ jest.useFakeTimers()+ AppState.currentState = 'active'+ useConnectivity.setState({ status: 'unknown' })+ unsubscribe = jest.fn()+ remove = jest.fn()+ jest.mocked(addNetworkStateListener).mockImplementation((listener) => {+ update = listener+ return { remove: unsubscribe }+ })+ jest.mocked(getNetworkStateAsync)+ .mockClear()+ .mockImplementation(() => new Promise(() => undefined))+ jest.spyOn(AppState, 'addEventListener').mockImplementation((_event, listener) => {+ changeAppState = listener+ return { remove }+ })+ })+ afterEach(() => {+ AppState.currentState = originalAppState+ jest.restoreAllMocks()+ onlineManager.setEventListener(() => undefined)+ onlineManager.setOnline(true)+ jest.useRealTimers()+ })+ test.each<NetworkState>([{}, { type: NetworkStateType.UNKNOWN, isConnected: false }])(+ 'unknown state %j allows reads, offline pauses them, and reconnect resumes one request',+ async (unknownState) => {+ onlineManager.setEventListener(monitorConnectivity)+ const client = new QueryClient({ defaultOptions: { queries: { retry: false, gcTime: Infinity } } })+ client.mount()+ const fetch = jest.fn(async () => 'loaded')+ const observer = new QueryObserver(client, { queryKey: ['connectivity-read'], queryFn: fetch })+ update(state(false))+ await jest.advanceTimersByTimeAsync(0)+ const stop = observer.subscribe(() => undefined)+ expect(observer.getCurrentResult().fetchStatus).toBe('paused')+ expect(fetch).not.toHaveBeenCalled()+ update(unknownState)+ await jest.advanceTimersByTimeAsync(0)+ expect(observer.getCurrentResult().data).toBe('loaded')+ expect(fetch).toHaveBeenCalledTimes(1)+ expect(useConnectivity.getState().status).toBe('unknown')+ update(state(true))+ await jest.advanceTimersByTimeAsync(0)+ expect(useConnectivity.getState()).toEqual({ status: 'connected' })+ stop()+ client.unmount()+ client.clear()+ expect(unsubscribe).toHaveBeenCalledTimes(1)+ expect(remove).toHaveBeenCalledTimes(1)+ }+ )+ test.each(['success', 'failure'] as const)(+ 'foreground refresh %s preserves newer events and cleanup stops late updates',+ async (outcome) => {+ let resolve: (state: NetworkState) => void = () => undefined+ let reject: (error: Error) => void = () => undefined+ jest.mocked(getNetworkStateAsync)+ .mockResolvedValueOnce(state(true))+ .mockImplementationOnce(+ () =>+ new Promise((yes, no) => {+ resolve = yes+ reject = no+ })+ )+ const setOnline = jest.fn()+ const stop = monitorConnectivity(setOnline)+ await Promise.resolve()+ await Promise.resolve()+ await Promise.resolve()+ changeAppState('background')+ changeAppState('active')+ changeAppState('active')+ expect(getNetworkStateAsync).toHaveBeenCalledTimes(2)+ update(state(false))+ if (outcome === 'success') resolve(state(true))+ else reject(new Error('Native state unavailable'))+ await jest.advanceTimersByTimeAsync(0)+ expect(useConnectivity.getState().status).toBe('offline')+ stop()+ update(state(true))+ expect(useConnectivity.getState().status).toBe('offline')+ expect(setOnline).toHaveBeenLastCalledWith(false)+ }+ )+})diff --git a/products/mobile/src/lib/connectivity.ts b/products/mobile/src/lib/connectivity.tsnew file mode 100644index 000000000000..e396ad094302--- /dev/null+++ b/products/mobile/src/lib/connectivity.ts@@ -0,0 +1,82 @@+import { addNetworkStateListener, getNetworkStateAsync, type NetworkState, NetworkStateType } from 'expo-network'+import { AppState } from 'react-native'+import { create } from 'zustand'++export interface Connectivity {+ status: 'unknown' | 'connected' | 'offline'+}++export const useConnectivity = create<Connectivity>(() => ({ status: 'unknown' }))++export class OfflineError extends Error {+ constructor() {+ super("You're offline. Reconnect and try again.")+ this.name = 'OfflineError'+ }+}++// Stop an action waiting on a read when the link drops, without canceling a query another screen may share.+export async function whileOnline<T>(read: () => Promise<T>): Promise<T> {+ if (useConnectivity.getState().status === 'offline') throw new OfflineError()+ let unsubscribe = (): void => undefined+ const disconnected = new Promise<never>((_resolve, reject) => {+ unsubscribe = useConnectivity.subscribe((state) => {+ if (state.status === 'offline') reject(new OfflineError())+ })+ })+ try {+ return await Promise.race([read(), disconnected])+ } finally {+ unsubscribe()+ }+}++export function monitorConnectivity(setOnline: (online: boolean) => void): () => void {+ let disposed = false+ let revision = 0+ let refreshing = false+ let appState = AppState.currentState+ const apply = (state: NetworkState): void => {+ if (disposed) return+ // Expo can report UNKNOWN with isConnected=false when the native state cannot be read. Allow requests then.+ // Reachability is not a backend health check, so only a known disconnected link pauses reads.+ const status =+ state.isConnected === true+ ? 'connected'+ : state.isConnected === false && state.type !== NetworkStateType.UNKNOWN+ ? 'offline'+ : 'unknown'+ if (status !== useConnectivity.getState().status) useConnectivity.setState({ status })+ setOnline(status !== 'offline')+ }+ const refresh = (): void => {+ if (refreshing || disposed) return+ refreshing = true+ const started = revision+ void getNetworkStateAsync()+ .then((state) => {+ if (revision === started) apply(state)+ })+ .catch(() => {+ // A failed native read does not prove the device is offline. Keep the last observed state.+ })+ .finally(() => {+ refreshing = false+ })+ }+ const networkSubscription = addNetworkStateListener((state) => {+ revision += 1+ apply(state)+ })+ const subscription = AppState.addEventListener('change', (next) => {+ const becameActive = next === 'active' && appState !== 'active'+ appState = next+ if (becameActive) refresh()+ })+ refresh()+ return () => {+ disposed = true+ networkSubscription.remove()+ subscription.remove()+ }+}diff --git a/products/mobile/src/model/queryStates.ts b/products/mobile/src/model/queryStates.tsindex 4ec5965e887c..1b93be6e3533 100644--- a/products/mobile/src/model/queryStates.ts+++ b/products/mobile/src/model/queryStates.ts@@ -6,6 +6,12 @@ export function loadingQuery<T>(): QueryState<T> {return { data: undefined, isLoading: true, isError: false, error: null, isRefetching: false, refetch: noop }}+export function connectionLoadingQuery<T>(offline: boolean, refetch: () => unknown = noop): QueryState<T> {+ return offline+ ? errorQuery(new Error("You're offline. Your data will load when your connection returns."), refetch)+ : { ...loadingQuery<T>(), refetch }+}+export function errorQuery<T>(error: Error, refetch: () => unknown = noop): QueryState<T> {return { data: undefined, isLoading: false, isError: true, error, isRefetching: false, refetch }}