Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

fix(mobile): prioritize foreground reads over inbox prefetch (#127546)

Chris Volzera95eb981fb2b
diff --git a/products/mobile/docs/DATA.md b/products/mobile/docs/DATA.md
index 91703b8e66b1..914485f5657e 100644
--- a/products/mobile/docs/DATA.md
+++ b/products/mobile/docs/DATA.md
@@ -90,10 +90,10 @@ The task fills in when it arrives.
A failed background refetch keeps the cached report on screen.
**Prefetch and refresh.**
-The inbox prefetches the report detail, work log and Today page of the first 40 rows (the first two pages, as they load), and of the rows that scroll into view plus 5 ahead.
+The inbox waits for row visibility, then prefetches report detail, work log and Today page for visible rows plus one ahead. Earlier offscreen rows are excluded, and scrolling replaces queued work. There is no initial page-wide prefetch.
These are the requests the report screen waits for before its first render; the task and the metric queries load after it opens.
It also prefetches the signals of a report when the Today page answers 404 or 403, because the signals are the evidence then.
-It works on two reports at a time and skips done and dismissed rows.
+It skips done and dismissed rows and sends one speculative request at a time, without retries. It runs only while the inbox is focused and foregrounded, the device reports a connected inexpensive link, and no observed foreground query is fetching. Unknown connectivity or cost pauses prefetch but does not block foreground reads. Pausing, switching project or account, or unmounting cancels only inactive queries started by the prefetcher. Opening a report adopts its shared requests, so cleanup leaves those observed reads running and failures use the foreground observer’s retry policy.
It uses a 5 minute stale time, so a refresh or a scroll does not fetch a report again within 5 minutes of its prefetch.
A report the cache dropped while the app was idle is fetched again when its row comes into view.
The screen and the prefetcher share the query factories in `src/features/report/queries.ts`, so they read and write the same cache entries.
diff --git a/products/mobile/src/features/inbox/InboxScreen.tsx b/products/mobile/src/features/inbox/InboxScreen.tsx
index ea51d835d309..a5ed5aaf09eb 100644
--- a/products/mobile/src/features/inbox/InboxScreen.tsx
+++ b/products/mobile/src/features/inbox/InboxScreen.tsx
@@ -46,7 +46,7 @@ export function InboxScreen(): ReactElement {
)
const filters = useInboxFilters()
const query = useInboxItems({ refreshWhileVisible: focused, filters })
- const prefetch = usePrefetchReports(query.data)
+ const prefetch = usePrefetchReports(query.data, focused)
const [rowMenu, setRowMenu] = useState<RowMenuTarget | null>(null)
const [filtersOpen, setFiltersOpen] = useState(false)
const listRef = useRef<FlatList<InboxItem>>(null)
diff --git a/products/mobile/src/features/inbox/prefetchPlan.test.ts b/products/mobile/src/features/inbox/prefetchPlan.test.ts
index bfc770bfc689..817025494d86 100644
--- a/products/mobile/src/features/inbox/prefetchPlan.test.ts
+++ b/products/mobile/src/features/inbox/prefetchPlan.test.ts
@@ -1,11 +1,4 @@
-import {
- createPrefetchQueue,
- INITIAL_PREFETCH_COUNT,
- PREFETCH_CONCURRENCY,
- PREFETCH_LOOKAHEAD,
- prefetchRows,
- prefetchWindow,
-} from './prefetchPlan'
+import { createPrefetchQueue, PREFETCH_CONCURRENCY, prefetchRows, prefetchWindow } from './prefetchPlan'
const ids = (count: number): string[] => Array.from({ length: count }, (_, index) => `r${index}`)
@@ -27,14 +20,17 @@ function controlledRun(): { run: (id: string) => Promise<void>; started: string[
const flush = (): Promise<void> => new Promise((resolve) => setImmediate(resolve))
describe('prefetchPlan', () => {
- const deep = INITIAL_PREFETCH_COUNT + 10
- test.each<[string, number, number | null, number]>([
- ['no viewability event yet', deep * 2, null, INITIAL_PREFETCH_COUNT],
- ['a small visible index keeps the initial count', deep * 2, 2, INITIAL_PREFETCH_COUNT],
- ['a deep visible index extends past it by the lookahead', deep * 2, deep, deep + PREFETCH_LOOKAHEAD + 1],
- ['a short list is not overrun', 3, 2, 3],
- ])('prefetchWindow: %s', (_name, length, lastVisible, expectedCount) => {
- expect(prefetchWindow(ids(length), lastVisible)).toEqual(ids(length).slice(0, expectedCount))
+ test.each<[string, number, number | null, number | null, string[]]>([
+ ['no viewability event yet', 100, null, null, []],
+ ['visible rows plus one ahead', 100, 0, 2, ids(4)],
+ ['earlier offscreen rows are excluded', 100, 20, 23, ids(25).slice(20)],
+ ['a short list is not overrun', 3, 1, 2, ['r1', 'r2']],
+ ['only closed rows are visible', 10, 2, 1, []],
+ ])('prefetchWindow: %s', (_name, length, firstVisible, lastVisible, expected) => {
+ const rows = prefetchRows(ids(length).map((reportId) => ({ reportId, state: 'open' })))
+ const visible =
+ firstVisible === null || lastVisible === null ? null : { first: firstVisible, last: lastVisible }
+ expect(prefetchWindow(rows, visible)).toEqual(expected)
})
test('prefetchRows skips done and dismissed rows and maps list rows onto the remaining ids', () => {
@@ -45,6 +41,7 @@ describe('prefetchPlan', () => {
{ reportId: 'd', state: 'snoozed' },
])
expect(rows).toEqual({ ids: ['b', 'd'], idIndexByRow: [-1, 0, 0, 1] })
+ expect(prefetchWindow(rows, { first: 2, last: 3 })).toEqual(['d'])
})
test('queue runs an id once while it is pending or running, and again after its run settles', async () => {
@@ -80,6 +77,16 @@ describe('prefetchPlan', () => {
expect(started).toContain(`r${PREFETCH_CONCURRENCY}`)
})
+ test('a new visible window drops older pending rows', async () => {
+ const { run, started, settle } = controlledRun()
+ const queue = createPrefetchQueue(run)
+ queue.enqueue(['a', 'b', 'c'])
+ queue.enqueue(['x', 'y'])
+ settle.get('a')?.resolve()
+ await flush()
+ expect(started).toEqual(['a', 'x'])
+ })
+
test('queue reset drops the pending ids and lets the runs in flight finish', async () => {
const { run, started, settle } = controlledRun()
const queue = createPrefetchQueue(run)
diff --git a/products/mobile/src/features/inbox/prefetchPlan.ts b/products/mobile/src/features/inbox/prefetchPlan.ts
index dd2a6b55abd2..38b3d7ac20cf 100644
--- a/products/mobile/src/features/inbox/prefetchPlan.ts
+++ b/products/mobile/src/features/inbox/prefetchPlan.ts
@@ -1,11 +1,7 @@
-import { INBOX_PAGE_SIZE } from '@/api/reports'
import type { InboxItem } from '@/model/types'
-/** The first two pages of the list: the reports a session most likely opens. */
-export const INITIAL_PREFETCH_COUNT = 2 * INBOX_PAGE_SIZE
-export const PREFETCH_LOOKAHEAD = 5
-/** Reports in flight at once. Each report is 3 to 4 requests. */
-export const PREFETCH_CONCURRENCY = 2
+export const PREFETCH_LOOKAHEAD = 1
+export const PREFETCH_CONCURRENCY = 1
export interface PrefetchRows {
/** Report ids worth prefetching, in list order. */
@@ -27,37 +23,30 @@ export function prefetchRows(items: readonly Pick<InboxItem, 'reportId' | 'state
return { ids, idIndexByRow }
}
-/** The ids to prefetch, given the last visible index in `ids`, or `null` before the list reports what is visible. */
-export function prefetchWindow(ids: readonly string[], lastVisibleIndex: number | null): string[] {
- const last =
- lastVisibleIndex === null
- ? INITIAL_PREFETCH_COUNT - 1
- : Math.max(INITIAL_PREFETCH_COUNT - 1, lastVisibleIndex + PREFETCH_LOOKAHEAD)
- return ids.slice(0, last + 1)
+export function prefetchWindow(rows: PrefetchRows, visible: { first: number; last: number } | null): string[] {
+ if (!visible) return []
+ const first = visible.first === 0 ? 0 : (rows.idIndexByRow[visible.first - 1] ?? -1) + 1
+ const last = rows.idIndexByRow[visible.last] ?? -1
+ return last < first ? [] : rows.ids.slice(first, last + PREFETCH_LOOKAHEAD + 1)
}
export interface PrefetchQueue {
- /** Queues the ids that are not already pending or running. An id runs again once its last run settles. */
+ /** Replaces pending ids with this window, keeping any run already in flight. */
enqueue(ids: readonly string[]): void
/** Drops the pending ids. Runs in flight finish and still count toward the limit. */
reset(): void
}
-// Dedupes only queued and running ids: the prefetch stale time makes a repeat run of a fresh report a no-op, and a
-// report the cache dropped while idle is fetched again when it comes back into view.
export function createPrefetchQueue(run: (id: string) => Promise<void>): PrefetchQueue {
- let active = new Set<string>()
+ const running = new Set<string>()
let pending: string[] = []
- let inFlight = 0
const pump = (): void => {
- while (inFlight < PREFETCH_CONCURRENCY && pending.length > 0) {
+ while (running.size < PREFETCH_CONCURRENCY && pending.length > 0) {
const id = pending.shift() as string
- const owner = active
- inFlight += 1
+ running.add(id)
const settle = (): void => {
- inFlight -= 1
- owner.delete(id)
+ running.delete(id)
pump()
}
let result: Promise<void>
@@ -73,17 +62,10 @@ export function createPrefetchQueue(run: (id: string) => Promise<void>): Prefetc
return {
enqueue(ids: readonly string[]): void {
- for (const id of ids) {
- if (!active.has(id)) {
- active.add(id)
- pending.push(id)
- }
- }
+ pending = [...new Set(ids)].filter((id) => !running.has(id))
pump()
},
reset(): void {
- // A new set, so a run from before the reset does not clear an id queued after it.
- active = new Set()
pending = []
},
}
diff --git a/products/mobile/src/features/inbox/usePrefetchReports.test.tsx b/products/mobile/src/features/inbox/usePrefetchReports.test.tsx
index 64d3514550b2..80c5ec7edc28 100644
--- a/products/mobile/src/features/inbox/usePrefetchReports.test.tsx
+++ b/products/mobile/src/features/inbox/usePrefetchReports.test.tsx
@@ -1,20 +1,22 @@
-import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
-import { renderHook, waitFor } from '@testing-library/react-native'
+import NetInfo, { type NetInfoState } from '@react-native-community/netinfo'
+import { QueryClient, QueryClientProvider, QueryObserver } from '@tanstack/react-query'
+import { act, renderHook, waitFor } from '@testing-library/react-native'
import type { ReactElement, ReactNode } from 'react'
-
+import { AppState, type ViewToken } from 'react-native'
import { setAuthProvider } from '@/api/client'
+import { useConnectivity } from '@/lib/connectivity'
import { inboxFromReports } from '@/model/adapters/inbox'
import { reportFixture } from '@/model/adapters/testFixtures'
+import type { InboxItem } from '@/model/types'
+import { reportDetailQuery } from '../report/queries'
import { usePrefetchReports } from './usePrefetchReports'
jest.mock('@react-native-async-storage/async-storage', () =>
require('@react-native-async-storage/async-storage/jest/async-storage-mock')
)
-jest.mock('@/auth/useProjectScope', () => {
- const scope = { host: 'https://app.example.com', projectId: 2 }
- return { useProjectScope: () => scope }
-})
+let mockScope = { host: 'https://app.example.com', projectId: 2 }
+jest.mock('@/auth/useProjectScope', () => ({ useProjectScope: () => mockScope }))
jest.mock('@/demo/demoMode', () => ({
...jest.requireActual('@/demo/demoMode'),
useDataMode: () => 'live',
@@ -29,9 +31,248 @@ function response(status: number, body: unknown): Response {
} as unknown as Response
}
+function showRows(props: ReturnType<typeof usePrefetchReports>, first: number, last: number): void {
+ props.onViewableItemsChanged({
+ viewableItems: [{ index: first }, { index: last }] as ViewToken<InboxItem>[],
+ changed: [],
+ })
+}
+
+function controlledRequests(): {
+ fetch: typeof fetch
+ pending: { path: string; signal: AbortSignal | null | undefined; resolve: (response: Response) => void }[]
+} {
+ const pending: { path: string; signal: AbortSignal | null | undefined; resolve: (response: Response) => void }[] =
+ []
+ const fetcher = jest.fn(
+ (url: string, init?: RequestInit) =>
+ new Promise<Response>((resolve, reject) => {
+ pending.push({ path: new URL(url).pathname + new URL(url).search, signal: init?.signal, resolve })
+ init?.signal?.addEventListener('abort', () => reject(new DOMException('Aborted', 'AbortError')))
+ })
+ ) as unknown as typeof fetch
+ return { fetch: fetcher, pending }
+}
+
describe('usePrefetchReports', () => {
+ beforeEach(() => {
+ mockScope = { host: 'https://app.example.com', projectId: 2 }
+ jest.spyOn(AppState, 'addEventListener').mockReturnValue({ remove: jest.fn() })
+ setAuthProvider({
+ getAuth: () => ({
+ host: 'https://app.example.com',
+ accessToken: 'fake',
+ projectId: mockScope.projectId,
+ session: 1,
+ }),
+ refreshAccessToken: async () => null,
+ })
+ AppState.currentState = 'active'
+ useConnectivity.setState({ status: 'connected', isConnectionExpensive: false })
+ jest.mocked(NetInfo.refresh).mockResolvedValue({
+ isConnected: true,
+ details: { isConnectionExpensive: false },
+ } as NetInfoState)
+ })
afterEach(() => {
setAuthProvider(null)
+ jest.restoreAllMocks()
+ })
+
+ test.each(['focus', 'offline', 'unknown', 'expensive', 'project', 'background', 'unmount'] as const)(
+ '%s pauses pending work and cancels only speculative reads',
+ async (pause) => {
+ const appListeners = new Set<(state: 'active' | 'background') => void>()
+ const appListener = jest.spyOn(AppState, 'addEventListener').mockImplementation((_event, listener) => {
+ appListeners.add(listener)
+ return { remove: () => appListeners.delete(listener) }
+ })
+ const requests = controlledRequests()
+ globalThis.fetch = requests.fetch
+ const client = new QueryClient({ defaultOptions: { queries: { retry: false, gcTime: Infinity } } })
+ const wrapper = ({ children }: { children: ReactNode }): ReactElement => (
+ <QueryClientProvider client={client}>{children}</QueryClientProvider>
+ )
+ const items = inboxFromReports(['a', 'b', 'c'].map((id) => reportFixture({ id })))
+ const screen = renderHook(({ focused }: { focused: boolean }) => usePrefetchReports(items, focused), {
+ initialProps: { focused: true },
+ wrapper,
+ })
+ try {
+ act(() => showRows(screen.result.current, 0, 1))
+ await waitFor(() => expect(requests.pending).toHaveLength(1))
+ await act(async () => {
+ if (pause === 'focus') screen.rerender({ focused: false })
+ else if (pause === 'offline') useConnectivity.setState({ status: 'offline' })
+ else if (pause === 'unknown') useConnectivity.setState({ status: 'unknown' })
+ else if (pause === 'project') {
+ mockScope = { ...mockScope, projectId: 3 }
+ screen.rerender({ focused: true })
+ } else if (pause === 'expensive') useConnectivity.setState({ isConnectionExpensive: true })
+ else if (pause === 'background') for (const listener of appListeners) listener('background')
+ else screen.unmount()
+ })
+ expect(requests.pending[0]?.signal?.aborted).toBe(true)
+ expect(requests.pending).toHaveLength(1)
+ if (pause !== 'unmount') {
+ await act(async () => {
+ if (pause === 'focus') screen.rerender({ focused: true })
+ else if (pause === 'offline' || pause === 'unknown')
+ useConnectivity.setState({ status: 'connected' })
+ else if (pause === 'project') showRows(screen.result.current, 0, 1)
+ else if (pause === 'expensive') useConnectivity.setState({ isConnectionExpensive: false })
+ else for (const listener of appListeners) listener('active')
+ })
+ await waitFor(() => expect(requests.pending).toHaveLength(2))
+ }
+ } finally {
+ screen.unmount()
+ client.clear()
+ appListener.mockRestore()
+ }
+ }
+ )
+
+ test('scrolling replaces queued rows and stops subsequent stages for an offscreen report', async () => {
+ const requests = controlledRequests()
+ globalThis.fetch = requests.fetch
+ const client = new QueryClient({ defaultOptions: { queries: { retry: false, gcTime: Infinity } } })
+ const wrapper = ({ children }: { children: ReactNode }): ReactElement => (
+ <QueryClientProvider client={client}>{children}</QueryClientProvider>
+ )
+ const items = inboxFromReports(Array.from({ length: 40 }, (_, index) => reportFixture({ id: `r${index}` })))
+ const { result, unmount } = renderHook(() => usePrefetchReports(items, true), { wrapper })
+ try {
+ act(() => showRows(result.current, 10, 10))
+ await waitFor(() => expect(requests.pending).toHaveLength(1))
+ act(() => showRows(result.current, 20, 20))
+ await act(async () => requests.pending[0]?.resolve(response(200, reportFixture({ id: 'r10' }))))
+ await waitFor(() => expect(requests.pending).toHaveLength(2))
+ expect(requests.pending.map((request) => request.path)).toEqual([
+ '/api/projects/2/signals/reports/r10/',
+ '/api/projects/2/signals/reports/r20/',
+ ])
+ await act(async () => requests.pending[1]?.resolve(response(200, reportFixture({ id: 'r20' }))))
+ await waitFor(() => expect(requests.pending).toHaveLength(3))
+ expect(requests.pending[2]?.path).toContain('/r20/artefacts/')
+ } finally {
+ unmount()
+ client.clear()
+ }
+ })
+
+ test('opening a prefetched report adopts the shared request and cleanup cannot cancel it', async () => {
+ const requests = controlledRequests()
+ globalThis.fetch = requests.fetch
+ const client = new QueryClient({ defaultOptions: { queries: { retry: false, gcTime: Infinity } } })
+ const wrapper = ({ children }: { children: ReactNode }): ReactElement => (
+ <QueryClientProvider client={client}>{children}</QueryClientProvider>
+ )
+ const items = inboxFromReports([reportFixture({ id: 'a' })])
+ const { result, unmount } = renderHook(() => usePrefetchReports(items, true), { wrapper })
+ let stopObserving = (): void => undefined
+ try {
+ act(() => showRows(result.current, 0, 0))
+ await waitFor(() => expect(requests.pending).toHaveLength(1))
+ const observer = new QueryObserver(
+ client,
+ reportDetailQuery({ host: 'https://app.example.com', projectId: 2 }, 'a')
+ )
+ await act(async () => {
+ stopObserving = observer.subscribe(() => undefined)
+ })
+ unmount()
+ expect(requests.pending[0]?.signal?.aborted).toBe(false)
+ await act(async () => requests.pending[0]?.resolve(response(200, reportFixture({ id: 'a' }))))
+ await waitFor(() => expect(observer.getCurrentResult().data?.id).toBe('a'))
+ expect(requests.pending).toHaveLength(1)
+ } finally {
+ stopObserving()
+ unmount()
+ client.clear()
+ }
+ })
+
+ test.each(['unobserved', 'adopted', 'observer-policy'] as const)(
+ 'a transient prefetch failure follows the %s retry policy',
+ async (mode) => {
+ const requests = controlledRequests()
+ globalThis.fetch = requests.fetch
+ const client = new QueryClient({
+ defaultOptions: { queries: { retry: 1, retryDelay: 0, gcTime: Infinity } },
+ })
+ const wrapper = ({ children }: { children: ReactNode }): ReactElement => (
+ <QueryClientProvider client={client}>{children}</QueryClientProvider>
+ )
+ const options = reportDetailQuery(mockScope, 'a')
+ const items = inboxFromReports([reportFixture({ id: 'a' })])
+ const screen = renderHook(() => usePrefetchReports(items, true), { wrapper })
+ let stop = (): void => undefined
+ const observerPolicy = jest.fn(() => false)
+ try {
+ act(() => showRows(screen.result.current, 0, 0))
+ await waitFor(() => expect(requests.pending).toHaveLength(1))
+ const observer = new QueryObserver(client, {
+ ...options,
+ ...(mode === 'observer-policy' ? { retry: observerPolicy } : {}),
+ })
+ if (mode !== 'unobserved')
+ act(() => {
+ stop = observer.subscribe(() => undefined)
+ })
+ const detailPath = requests.pending[0]?.path
+ await act(async () => requests.pending[0]?.resolve(response(503, { detail: 'Try again' })))
+ if (mode === 'adopted') {
+ await waitFor(() =>
+ expect(requests.pending.filter((request) => request.path === detailPath)).toHaveLength(2)
+ )
+ await act(async () =>
+ requests.pending
+ .find((request, index) => index > 0 && request.path === detailPath)
+ ?.resolve(response(200, reportFixture({ id: 'a' })))
+ )
+ await waitFor(() => expect(observer.getCurrentResult().data?.id).toBe('a'))
+ } else {
+ await waitFor(() => expect(client.getQueryState(options.queryKey)?.status).toBe('error'))
+ expect(requests.pending.filter((request) => request.path === detailPath)).toHaveLength(1)
+ if (mode === 'observer-policy') expect(observerPolicy).toHaveBeenCalledWith(0, expect.any(Error))
+ }
+ } finally {
+ stop()
+ screen.unmount()
+ client.clear()
+ }
+ }
+ )
+
+ test('foreground reads finish before speculation begins', async () => {
+ const requests = controlledRequests()
+ globalThis.fetch = requests.fetch
+ const client = new QueryClient({ defaultOptions: { queries: { retry: false, gcTime: Infinity } } })
+ let finish = (): void => undefined
+ const observer = new QueryObserver(client, {
+ queryKey: ['foreground'],
+ queryFn: () =>
+ new Promise<string>((resolve) => {
+ finish = () => resolve('loaded')
+ }),
+ })
+ const stop = observer.subscribe(() => undefined)
+ const wrapper = ({ children }: { children: ReactNode }): ReactElement => (
+ <QueryClientProvider client={client}>{children}</QueryClientProvider>
+ )
+ const items = inboxFromReports([reportFixture({ id: 'a' })])
+ const { result, unmount } = renderHook(() => usePrefetchReports(items, true), { wrapper })
+ try {
+ act(() => showRows(result.current, 0, 0))
+ expect(requests.pending).toEqual([])
+ await act(async () => finish())
+ await waitFor(() => expect(requests.pending).toHaveLength(1))
+ } finally {
+ unmount()
+ stop()
+ client.clear()
+ }
})
test('asks once for a Today page the project does not have, not again when the window moves', async () => {
@@ -60,14 +301,29 @@ describe('usePrefetchReports', () => {
<QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
)
const signalsOf = (id: string) => paths.filter((path) => path.endsWith(`/reports/${id}/signals/`))
- const { rerender } = renderHook(({ ids }: { ids: string[] }) => usePrefetchReports(items(ids)), {
- initialProps: { ids: ['a', 'b'] },
- wrapper,
- })
+ const { result, rerender, unmount } = renderHook(
+ ({ ids }: { ids: string[] }) => usePrefetchReports(items(ids), true),
+ {
+ initialProps: { ids: ['a', 'b'] },
+ wrapper,
+ }
+ )
+ expect(paths).toEqual([])
+ act(() =>
+ result.current.onViewableItemsChanged({
+ viewableItems: [{ index: 0 }] as ViewToken<InboxItem>[],
+ changed: [],
+ })
+ )
await waitFor(() => expect(signalsOf('b')).toHaveLength(1))
- // A new row queues the whole window again, and `c` runs after `a` and `b`.
rerender({ ids: ['a', 'b', 'c'] })
+ act(() =>
+ result.current.onViewableItemsChanged({
+ viewableItems: [{ index: 1 }] as ViewToken<InboxItem>[],
+ changed: [],
+ })
+ )
await waitFor(() => expect(signalsOf('c')).toHaveLength(1))
expect(paths.filter((path) => path.includes('/today/'))).toEqual([
@@ -75,5 +331,7 @@ describe('usePrefetchReports', () => {
'/api/projects/2/today/reports/b/page/',
'/api/projects/2/today/reports/c/page/',
])
+ unmount()
+ queryClient.clear()
})
})
diff --git a/products/mobile/src/features/inbox/usePrefetchReports.ts b/products/mobile/src/features/inbox/usePrefetchReports.ts
index 97bde8dbd3c8..176d36ec8aa9 100644
--- a/products/mobile/src/features/inbox/usePrefetchReports.ts
+++ b/products/mobile/src/features/inbox/usePrefetchReports.ts
@@ -1,10 +1,21 @@
-import { type QueryClient, useQueryClient } from '@tanstack/react-query'
-import { useCallback, useEffect, useMemo, useRef } from 'react'
+import {
+ type DefaultError,
+ type FetchQueryOptions,
+ type QueryClient,
+ type QueryKey,
+ useIsFetching,
+ useQueryClient,
+} from '@tanstack/react-query'
+import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import type { ViewabilityConfig, ViewToken } from 'react-native'
import { isMissingFeature, type ProjectScope } from '@/api/reports'
+import { useAuthStore } from '@/auth/authStore'
+import { sessionGeneration } from '@/auth/tokens'
import { useProjectScope } from '@/auth/useProjectScope'
import { useDataMode } from '@/demo/demoMode'
+import { useAppActive } from '@/features/handoff/useTaskRun'
+import { useConnectivity } from '@/lib/connectivity'
import type { InboxItem } from '@/model/types'
import { reportArtefactsQuery, reportDetailQuery, reportPageQuery, reportSignalsQuery } from '../report/queries'
@@ -30,78 +41,121 @@ function knownMissing(queryClient: QueryClient, scope: ProjectScope, reportId: s
)
}
-async function prefetchReport(queryClient: QueryClient, scope: ProjectScope, reportId: string): Promise<void> {
- const options = { staleTime: PREFETCH_STALE_MS }
- await Promise.all([
- queryClient.prefetchQuery({ ...reportDetailQuery(scope, reportId), ...options }),
- queryClient.prefetchQuery({ ...reportArtefactsQuery(scope, reportId), ...options }),
- knownMissing(queryClient, scope, reportId)
- ? Promise.resolve()
- : queryClient.prefetchQuery({ ...reportPageQuery(scope, reportId), ...options }),
- ])
- // The screen shows the signals as the evidence only when the report has no Today page.
+async function prefetchReport(
+ queryClient: QueryClient,
+ scope: ProjectScope,
+ reportId: string,
+ signal: AbortSignal,
+ owned: Set<QueryKey>,
+ wanted: () => boolean
+): Promise<void> {
+ const prefetch = async <TData, TKey extends QueryKey>(
+ options: FetchQueryOptions<TData, DefaultError, TData, TKey>
+ ): Promise<void> => {
+ if (
+ signal.aborted ||
+ !wanted() ||
+ queryClient.isFetching({ predicate: (query) => query.getObserversCount() > 0 }) > 0
+ )
+ return
+ const query = queryClient.getQueryCache().find({ queryKey: options.queryKey, exact: true })
+ if (query && (query.getObserversCount() > 0 || query.state.fetchStatus !== 'idle')) return
+ const configuredRetry = queryClient.defaultQueryOptions(options).retry
+ const retry = (failureCount: number, error: DefaultError): boolean => {
+ const current = queryClient.getQueryCache().find({ queryKey: options.queryKey, exact: true })
+ if (!current || current.getObserversCount() === 0) return false
+ // The retryer captures this callback, even after an opened report replaces the query's options.
+ const policy = current.options.retry === retry ? configuredRetry : current.options.retry
+ return typeof policy === 'function'
+ ? policy(failureCount, error)
+ : policy === true || (typeof policy === 'number' && failureCount < policy)
+ }
+ owned.add(options.queryKey)
+ try {
+ await queryClient.prefetchQuery({ ...options, staleTime: PREFETCH_STALE_MS, retry })
+ } finally {
+ owned.delete(options.queryKey)
+ }
+ }
+ await prefetch(reportDetailQuery(scope, reportId))
+ await prefetch(reportArtefactsQuery(scope, reportId))
+ if (!knownMissing(queryClient, scope, reportId)) await prefetch(reportPageQuery(scope, reportId))
const page = queryClient.getQueryState(reportPageQuery(scope, reportId).queryKey)
if (page?.status === 'error' && isMissingFeature(page.error)) {
- await queryClient.prefetchQuery({ ...reportSignalsQuery(scope, reportId), ...options })
+ await prefetch(reportSignalsQuery(scope, reportId))
}
}
-/** Fills the report screen's cache for the rows on screen and a few ahead, so opening a row renders at once. */
-export function usePrefetchReports(items: InboxItem[] | undefined): ReportPrefetchListProps {
+/** Shares the report screen's cache so visible rows can open from a prefetched copy. */
+export function usePrefetchReports(items: InboxItem[] | undefined, focused: boolean): ReportPrefetchListProps {
const queryClient = useQueryClient()
const live = useDataMode() === 'live'
const scope = useProjectScope()
- const scopeRef = useRef(scope)
- scopeRef.current = scope
+ const account = useAuthStore((state) => JSON.stringify([state.user?.uuid, sessionGeneration()]))
+ const accountRef = useRef(account)
+ accountRef.current = account
+ const active = useAppActive()
+ const connected = useConnectivity((state) => state.status === 'connected' && state.isConnectionExpensive === false)
+ const foregroundFetching = useIsFetching({ predicate: (query) => query.getObserversCount() > 0 })
+ const enabled = live && scope !== null && focused && active && connected && foregroundFetching === 0
+ const scopeKey = scope ? JSON.stringify([scope.host, scope.projectId, account]) : ''
+ const scopeKeyRef = useRef(scopeKey)
+ scopeKeyRef.current = scopeKey
const queueRef = useRef<PrefetchQueue | null>(null)
- if (queueRef.current === null) {
- queueRef.current = createPrefetchQueue(async (reportId) => {
- const current = scopeRef.current
- if (current) {
- await prefetchReport(queryClient, current, reportId)
- }
- })
- }
- const lastVisibleRef = useRef<number | null>(null)
-
+ const [visible, setVisible] = useState<{ first: number; last: number; scopeKey: string } | null>(null)
const rows = useMemo(() => prefetchRows(items ?? []), [items])
- const idsKey = rows.ids.join(',')
- const rowsRef = useRef(rows)
- rowsRef.current = rows
- const enabled = live && scope !== null
- const enabledRef = useRef(enabled)
- enabledRef.current = enabled
-
- const scopeKey = scope ? `${scope.host}|${scope.projectId}` : ''
- const scopeKeyRef = useRef(scopeKey)
+ const currentVisible = visible?.scopeKey === scopeKey ? visible : null
+ const ids = prefetchWindow(rows, currentVisible)
+ const idsKey = ids.join(',')
+ const idsRef = useRef(ids)
+ idsRef.current = ids
- // Keyed on the id string, not `items`, so the inbox's once-a-minute clock re-render does not enqueue again.
- // biome-ignore lint/correctness/useExhaustiveDependencies: `idsKey` stands for `rows.ids`, read through the ref.
useEffect(() => {
- if (scopeKeyRef.current !== scopeKey) {
- scopeKeyRef.current = scopeKey
- queueRef.current?.reset()
- lastVisibleRef.current = null
- }
- if (enabled) {
- queueRef.current?.enqueue(prefetchWindow(rowsRef.current.ids, lastVisibleRef.current))
+ if (!enabled || !scope) return
+ const controller = new AbortController()
+ const owned = new Set<QueryKey>()
+ const queue = createPrefetchQueue((id) =>
+ prefetchReport(
+ queryClient,
+ scope,
+ id,
+ controller.signal,
+ owned,
+ () => accountRef.current === account && idsRef.current.includes(id)
+ )
+ )
+ queueRef.current = queue
+ return () => {
+ controller.abort()
+ queue.reset()
+ queueRef.current = null
+ for (const queryKey of owned) {
+ // A report opened since prefetch began owns the shared request now. Leave its observed reads running.
+ void queryClient.cancelQueries({
+ queryKey,
+ exact: true,
+ predicate: (query) => query.getObserversCount() === 0,
+ })
+ }
}
- }, [enabled, idsKey, scopeKey])
+ }, [enabled, scope, queryClient, account])
+
+ // biome-ignore lint/correctness/useExhaustiveDependencies: idsKey represents the current window, read through the ref.
+ useEffect(() => {
+ queueRef.current?.enqueue(idsRef.current)
+ }, [enabled, scopeKey, idsKey])
const onViewableItemsChanged = useCallback(({ viewableItems }: { viewableItems: ViewToken<InboxItem>[] }): void => {
- const maxRow = viewableItems.reduce((max, token) => Math.max(max, token.index ?? -1), -1)
- if (maxRow < 0) {
- return
- }
- const { ids, idIndexByRow } = rowsRef.current
- const lastVisible = idIndexByRow[maxRow] ?? ids.length - 1
- if (lastVisible === lastVisibleRef.current) {
- return
- }
- lastVisibleRef.current = lastVisible
- if (enabledRef.current) {
- queueRef.current?.enqueue(prefetchWindow(ids, lastVisible))
- }
+ const indices = viewableItems.flatMap((token) => (token.index === null ? [] : [token.index]))
+ const first = Math.min(...indices)
+ const last = Math.max(...indices)
+ const scopeKey = scopeKeyRef.current
+ setVisible((current) => {
+ if (indices.length === 0) return current === null ? current : null
+ return current?.first === first && current.last === last && current.scopeKey === scopeKey
+ ? current
+ : { first, last, scopeKey }
+ })
}, [])
return { onViewableItemsChanged, viewabilityConfig: VIEWABILITY_CONFIG }