: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): reject invalid inbox pages before caching (#126796)
Chris Volzeraf9d34aa7c48
diff --git a/products/mobile/docs/TESTING.md b/products/mobile/docs/TESTING.mdindex efc0429d3ce5..0548d9c66f22 100644--- a/products/mobile/docs/TESTING.md+++ b/products/mobile/docs/TESTING.md@@ -14,6 +14,9 @@ pnpm test`pnpm typecheck` includes this compatibility check automatically.CI runs typecheck, lint, and tests; see [CI.md](CI.md).+For inbox pagination, check that an invalid next-page response keeps the loaded reports visible and shows the retry footer.+Retry after the server returns a valid page and confirm that the remaining reports load.+## Authenticated local checksRun the setup in [README.md](../README.md#sign-in-to-the-local-backend) first.diff --git a/products/mobile/src/api/reports.test.ts b/products/mobile/src/api/reports.test.tsindex 30c6a16f2ffd..afb5894cae9b 100644--- a/products/mobile/src/api/reports.test.ts+++ b/products/mobile/src/api/reports.test.ts@@ -29,7 +29,7 @@ describe('reports api', () => {})test.each([0, INBOX_PAGE_SIZE])('the inbox asks for personal reports at offset %i', async (offset) => {- await fetchInboxPage(offset)+ await expect(fetchInboxPage(offset)).resolves.toEqual({ count: 0, next: null, results: [] })const url = new URL(urls[0] ?? '')expect(url.pathname).toBe('/api/projects/2/signals/reports/')@@ -41,6 +41,20 @@ describe('reports api', () => {})})+ test.each([undefined, [], { count: 1 }, { results: [null] }, { results: [{}] }])(+ 'rejects an invalid inbox page: %p',+ async (body) => {+ globalThis.fetch = jest.fn(async () => ({+ ok: true,+ status: 200,+ headers: { get: () => null },+ text: async () => JSON.stringify(body) ?? '',+ })) as unknown as typeof fetch++ await expect(fetchInboxPage(0)).rejects.toThrow("Couldn't load your inbox. Try again.")+ }+ )+test('finds the newest reviewer assignment beyond the first artefact page', async () => {const assignment = { id: 'assignment', type: 'suggested_reviewers', content: [{ github_login: 'reviewer' }] }const pages = [diff --git a/products/mobile/src/api/reports.ts b/products/mobile/src/api/reports.tsindex f6a36f0f69f2..6b8b63fa43c2 100644--- a/products/mobile/src/api/reports.ts+++ b/products/mobile/src/api/reports.ts@@ -1,3 +1,4 @@+import { isRecord } from '@/lib/records'import type { ReportPriority } from '@/model/types'import { type DismissReason, type ResolveReason, VERDICT_NOTE_MAX_LENGTH } from '@/model/verdictReasons'import type {@@ -186,11 +187,19 @@ export interface InboxPageApi {export const INBOX_PAGE_SIZE = 20-export function fetchInboxPage(offset: number, signal?: AbortSignal): Promise<InboxPageApi> {- return apiJson<InboxPageApi>(projectPath('signals/reports/'), {+export async function fetchInboxPage(offset: number, signal?: AbortSignal): Promise<InboxPageApi> {+ const page = await apiJson<InboxPageApi>(projectPath('signals/reports/'), {query: { view: 'for_you', sort: 'priority', limit: INBOX_PAGE_SIZE, offset } satisfies SignalsReportsListParams,signal,})+ if (+ !isRecord(page) ||+ !Array.isArray(page.results) ||+ page.results.some((report) => !isRecord(report) || typeof report.id !== 'string')+ ) {+ throw new Error("Couldn't load your inbox. Try again.")+ }+ return page}export function fetchReport(reportId: string, signal?: AbortSignal): Promise<SignalReportApi> {diff --git a/products/mobile/src/features/inbox/hooks.test.tsx b/products/mobile/src/features/inbox/hooks.test.tsxindex d1e007d4c6e3..b5efd2e406b2 100644--- a/products/mobile/src/features/inbox/hooks.test.tsx+++ b/products/mobile/src/features/inbox/hooks.test.tsx@@ -382,50 +382,56 @@ describe('inbox hooks', () => {}})- test('pages through the ranking, retrying a failed page only when asked, reading states once per page', async () => {- const offsets: string[] = []- const readStateBatches: string[][] = []- const firstPage = Array.from({ length: INBOX_PAGE_SIZE }, (_, index) => reportFixture({ id: `r${index}` }))- let secondPageFailures = 1- globalThis.fetch = jest.fn(async (url: string, init?: RequestInit) => {- const { pathname, searchParams } = new URL(url)- if (pathname.endsWith('/read_state/')) {- readStateBatches.push(JSON.parse(String(init?.body)).report_ids)- return jsonResponse({ states: {} })- }- const offset = searchParams.get('offset') ?? ''- offsets.push(offset)- if (offset !== '0' && secondPageFailures > 0) {- secondPageFailures -= 1- return jsonResponse({ detail: 'Server error' }, 500)- }- return jsonResponse(- offset === '0'- ? { count: INBOX_PAGE_SIZE + 1, next: 'https://app.example.com/next', results: firstPage }- : { count: INBOX_PAGE_SIZE + 1, next: null, results: [reportFixture({ id: 'last' })] }+ test.each(['server error', 'invalid page'])(+ 'pages through the ranking, retrying after %s only when asked, reading states once per page',+ async (failure) => {+ const offsets: string[] = []+ const readStateBatches: string[][] = []+ const firstPage = Array.from({ length: INBOX_PAGE_SIZE }, (_, index) => reportFixture({ id: `r${index}` }))+ let secondPageFailures = 1+ globalThis.fetch = jest.fn(async (url: string, init?: RequestInit) => {+ const { pathname, searchParams } = new URL(url)+ if (pathname.endsWith('/read_state/')) {+ readStateBatches.push(JSON.parse(String(init?.body)).report_ids)+ return jsonResponse({ states: {} })+ }+ const offset = searchParams.get('offset') ?? ''+ offsets.push(offset)+ if (offset !== '0' && secondPageFailures > 0) {+ secondPageFailures -= 1+ return failure === 'server error'+ ? jsonResponse({ detail: 'Server error' }, 500)+ : jsonResponse({ count: INBOX_PAGE_SIZE + 1, next: null })+ }+ return jsonResponse(+ offset === '0'+ ? { count: INBOX_PAGE_SIZE + 1, next: 'https://app.example.com/next', results: firstPage }+ : { count: INBOX_PAGE_SIZE + 1, next: null, results: [reportFixture({ id: 'last' })] }+ )+ }) as unknown as typeof fetch+ const queryClient = new QueryClient({ defaultOptions: { queries: { gcTime: Infinity, retry: false } } })+ const wrapper = ({ children }: { children: ReactNode }): ReactElement => (+ <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>)- }) as unknown as typeof fetch- const queryClient = new QueryClient({ defaultOptions: { queries: { gcTime: Infinity, retry: false } } })- const wrapper = ({ children }: { children: ReactNode }): ReactElement => (- <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>- )- const { result } = renderHook(() => useInboxItems(), { wrapper })+ const { result } = renderHook(() => useInboxItems(), { wrapper })- await waitFor(() => expect(result.current.data).toHaveLength(INBOX_PAGE_SIZE))- expect(result.current.hasMore).toBe(true)- act(() => result.current.loadMore())- await waitFor(() => expect(result.current.loadMoreFailed).toBe(true))- // The list calls this again when the error footer replaces the spinner.- act(() => result.current.loadMore())- expect(result.current.isLoadingMore).toBe(false)- act(() => result.current.retryLoadMore())- await waitFor(() => expect(result.current.data).toHaveLength(INBOX_PAGE_SIZE + 1))- await waitFor(() => expect(readStateBatches).toHaveLength(2))+ await waitFor(() => expect(result.current.data).toHaveLength(INBOX_PAGE_SIZE))+ expect(result.current.hasMore).toBe(true)+ act(() => result.current.loadMore())+ await waitFor(() => expect(result.current.loadMoreFailed).toBe(true))+ expect(result.current.data).toHaveLength(INBOX_PAGE_SIZE)+ // The list calls this again when the error footer replaces the spinner.+ act(() => result.current.loadMore())+ expect(result.current.isLoadingMore).toBe(false)+ act(() => result.current.retryLoadMore())+ await waitFor(() => expect(result.current.data).toHaveLength(INBOX_PAGE_SIZE + 1))+ await waitFor(() => expect(readStateBatches).toHaveLength(2))- expect(result.current.hasMore).toBe(false)- expect(offsets).toEqual(['0', String(INBOX_PAGE_SIZE), String(INBOX_PAGE_SIZE)])- expect(readStateBatches.map((ids) => ids.length)).toEqual([INBOX_PAGE_SIZE, 1])- })+ expect(result.current.hasMore).toBe(false)+ expect(offsets).toEqual(['0', String(INBOX_PAGE_SIZE), String(INBOX_PAGE_SIZE)])+ expect(readStateBatches.map((ids) => ids.length)).toEqual([INBOX_PAGE_SIZE, 1])+ }+ )test('loads every page by itself for a sort and orders the items across pages', async () => {const offsets: string[] = []