: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): bound requests and classify transport failures (#127514)
Chris Volzerd37f8ac95932
diff --git a/products/mobile/docs/API.md b/products/mobile/docs/API.mdindex f15c3022fa28..8a86aab8f03c 100644--- a/products/mobile/docs/API.md+++ b/products/mobile/docs/API.md@@ -1,11 +1,17 @@# APIEvery request goes through `src/api/client.ts`: it prefixes the host, adds the bearer token,-sets `X-PostHog-Client-Platform: mobile`, refreshes the token once on a 401, and throws-`ApiError` with the server's `code` and `detail` on any other failure.+sets `X-PostHog-Client-Platform: mobile`, refreshes the token once on a 401, and represents HTTP failures+as `ApiError` with the server's `code` and `detail`.`projectPath('signals/reports/')` builds `/api/projects/{projectId}/signals/reports/`.Streams use `apiStream` (expo's fetch, so the body streams on native) and `src/api/sse.ts`.+Ordinary API requests have a 30-second deadline across token refresh and body reads. Caller cancellation stays distinct+from a deadline, and neither a timeout nor a lost connection automatically retries a write. A write can reach the server+before its response is lost, so a timeout does not mean it failed on the server. Long-lived task streams use their own+idle watchdog and reconnect policy. Transport failures have a dedicated error type; unrelated programming errors are+not reported as connectivity failures.+Most existing types are written by hand per module and name the Django serializer they mirror.PR checks use `PullRequestChecksResponseApi` from the Signals generated schemas. New APItypes should come from the generated schemas; update the Django serializer and rundiff --git a/products/mobile/docs/AUTH.md b/products/mobile/docs/AUTH.mdindex 6011f76b43eb..b2f63fe383b3 100644--- a/products/mobile/docs/AUTH.md+++ b/products/mobile/docs/AUTH.md@@ -22,6 +22,8 @@ Sign in ──► AuthRequest (PKCE S256, state) ──► system browser: {hostIt refreshes first when the access token has less than a minute left.- Any request that gets a 401 refreshes once and retries (`src/api/client.ts`).Concurrent 401s share one refresh, because each refresh rotates the token.+ Sign-in token exchanges and refreshes have a single 20-second deadline covering the request and response body, including error bodies.+ Expiry aborts the OAuth request and reports a network failure, allowing a later refresh to retry. Canceling an individual API caller does not cancel the shared refresh.- A refresh rejected with 400, 401 or 403 ends the session: tokens and the query cache are cleared and every screen goes to sign in, which says the session ended. Push cleanup needs valid credentials, so expiry cannot unregister the old token. The next successful registration on the same instance transfers that device token to the signed-in user; see [Push](PUSH.md#token-lifecycle).A network error or 5xx keeps the session; the request fails and the next one tries again.- Sign out waits for the push registration queue, unregisters the device token, revokes the refresh token (`POST {host}/oauth/revoke`, form body, `client_id`), then clears tokens, the query cache and the analytics identity.diff --git a/products/mobile/src/api/client.test.ts b/products/mobile/src/api/client.test.tsindex e5c574365477..e567c3c5f4c5 100644--- a/products/mobile/src/api/client.test.ts+++ b/products/mobile/src/api/client.test.ts@@ -1,9 +1,12 @@import { isAppReloadBlocked } from '@/lib/appReload'import { BUDGETS, BudgetExceededError, resetBudgets } from './budget'-import { apiJson, setAuthProvider } from './client'+import { apiJson, apiStream, setAuthProvider } from './client'import { resetServerClock, serverOffsetMs } from './serverClock'import { createTask, sendTaskRunCommand, startTaskRun } from './tasks'+import { REQUEST_TIMEOUT_MS, RequestTimeoutError, TransportError } from './transport'++jest.mock('expo/fetch', () => ({ fetch: jest.fn() }))describe('api client send path', () => {let fetchMock: jest.Mock@@ -88,7 +91,7 @@ describe('api client send path', () => {if (failure) {fail(new Error('Offline'))- await expect(request).rejects.toThrow('Offline')+ await expect(request).rejects.toBeInstanceOf(TransportError)} else {finish({ ok: true, status: 200, text: async () => '{}' })await request@@ -96,6 +99,131 @@ describe('api client send path', () => {expect(isAppReloadBlocked()).toBe(false)})+ test.each(['headers', 'body', 'refresh'])('bounds a hung %s without retrying a write', async (stage) => {+ jest.useFakeTimers()+ let finishRefresh!: (token: string) => void+ if (stage === 'headers') {+ fetchMock.mockImplementation(() => new Promise(() => undefined))+ } else {+ fetchMock.mockResolvedValue({+ ok: stage !== 'refresh',+ status: stage === 'refresh' ? 401 : 200,+ text: () => new Promise(() => undefined),+ })+ }+ setAuthProvider({+ getAuth: () => ({ host: 'https://app.example.com', accessToken: 'token', projectId: 2, session: 1 }),+ refreshAccessToken: () =>+ new Promise((resolve) => {+ finishRefresh = resolve+ }),+ })+ const request = apiJson('/api/projects/2/tasks/task-1/', { method: 'PATCH', json: { archived: true } })+ const assertion = expect(request).rejects.toBeInstanceOf(RequestTimeoutError)+ await jest.advanceTimersByTimeAsync(REQUEST_TIMEOUT_MS)+ await assertion+ expect(isAppReloadBlocked()).toBe(false)+ expect(fetchMock.mock.calls[0]?.[1].signal.aborted).toBe(true)+ if (stage === 'refresh') {+ finishRefresh('rotated')+ await jest.advanceTimersByTimeAsync(0)+ }+ expect(fetchMock).toHaveBeenCalledTimes(1)+ expect(jest.getTimerCount()).toBe(0)+ })++ test.each(['before', 'headers', 'refresh'])('cancels %s without sending a late retry', async (stage) => {+ jest.useFakeTimers()+ let finishRefresh!: (token: string) => void+ let markRefreshStarted!: () => void+ const refreshStarted = new Promise<void>((resolve) => {+ markRefreshStarted = resolve+ })+ const refreshed = new Promise<string>((resolve) => {+ finishRefresh = resolve+ })+ fetchMock.mockImplementation(() =>+ stage === 'refresh' ? Promise.resolve({ status: 401 }) : new Promise(() => undefined)+ )+ setAuthProvider({+ getAuth: () => ({ host: 'https://app.example.com', accessToken: 'token', projectId: 2, session: 1 }),+ refreshAccessToken: () => {+ markRefreshStarted()+ return refreshed+ },+ })+ const controller = new AbortController()+ if (stage === 'before') {+ controller.abort()+ }+ const request = apiJson('/api/projects/2/tasks/task-1/', { signal: controller.signal })+ const assertion = expect(request).rejects.toMatchObject({ name: 'AbortError' })+ if (stage === 'refresh') {+ await refreshStarted+ }+ controller.abort()+ await assertion+ if (stage === 'refresh') {+ finishRefresh('rotated')+ await refreshed+ await jest.advanceTimersByTimeAsync(0)+ }+ expect(fetchMock).toHaveBeenCalledTimes(stage === 'before' ? 0 : 1)+ expect(isAppReloadBlocked()).toBe(false)+ })++ test.each(['fetch', 'native fetch', 'body', 'serialization'])(+ 'classifies %s failures without relabeling serialization errors',+ async (stage) => {+ const failure = new TypeError('Example failure')+ if (stage === 'native fetch') {+ fetchMock.mockRejectedValue(new Error('Example native failure'))+ }+ if (stage === 'fetch') {+ fetchMock.mockRejectedValue(failure)+ }+ if (stage === 'body') {+ fetchMock.mockResolvedValue({+ ok: true,+ status: 200,+ text: async () => {+ throw failure+ },+ })+ }+ const json =+ stage === 'serialization'+ ? {+ toJSON: () => {+ throw failure+ },+ }+ : {}+ await expect(apiJson('/api/projects/2/tasks/task-1/', { method: 'POST', json })).rejects.toBeInstanceOf(+ stage === 'serialization' ? TypeError : TransportError+ )+ expect(fetchMock).toHaveBeenCalledTimes(stage === 'serialization' ? 0 : 1)+ }+ )++ test('keeps a live stream open past an ordinary request deadline', async () => {+ jest.useFakeTimers()+ const { fetch: streamFetch } = jest.requireMock('expo/fetch') as { fetch: jest.Mock }+ let open!: (response: unknown) => void+ streamFetch.mockImplementationOnce(+ () =>+ new Promise((resolve) => {+ open = resolve+ })+ )+ const request = apiStream('/api/projects/2/tasks/task-1/runs/run-1/stream/')+ await jest.advanceTimersByTimeAsync(REQUEST_TIMEOUT_MS * 2)+ const signal = streamFetch.mock.calls.at(-1)?.[1].signal as AbortSignal | undefined+ expect(signal?.aborted ?? false).toBe(false)+ open({ ok: true, status: 200 })+ await expect(request).resolves.toMatchObject({ status: 200 })+ })+test('sends nothing once a budget family has used its minute of tokens', async () => {const perMinute = BUDGETS.insights[0]?.capacity ?? 0for (let index = 0; index < perMinute; index += 1) {diff --git a/products/mobile/src/api/client.ts b/products/mobile/src/api/client.tsindex 9a8899fe7093..a0ff80f2baf5 100644--- a/products/mobile/src/api/client.ts+++ b/products/mobile/src/api/client.ts@@ -1,10 +1,12 @@import { fetch as streamingFetch } from 'expo/fetch'+import { abortError } from '@/lib/abort'import { withAppReloadBlocked } from '@/lib/appReload'import { isRecord } from '@/lib/records'import { BudgetExceededError, type BudgetFamily, budgetFamilyFor, trySpend } from './budget'import { recordServerDate } from './serverClock'+import { requestWithDeadline, transport } from './transport'export interface ApiAuth {host: string@@ -155,7 +157,17 @@ async function send(fetcher: Fetcher, path: string, init: ApiInit, accept: strinthrow new BudgetExceededError(family)}const sent = auth.accessToken as string- let response = await fetcher(url, buildInit(init, sent, accept))+ const fetchResponse = (token: string): Promise<Response> => {+ if (init.signal?.aborted) {+ throw abortError()+ }+ const options = buildInit(init, token, accept)+ return transport(() => fetcher(url, options))+ }+ let response = await fetchResponse(sent)+ if (init.signal?.aborted) {+ throw abortError()+ }noteServerDate(response)if (response.status === 401 && provider) {// The retry goes to `url`, which belongs to the session that sent the request. If the user signed out or@@ -175,14 +187,14 @@ async function send(fetcher: Fetcher, path: string, init: ApiInit, accept: strinif (!token || !isSameSession(auth, provider.getAuth())) {throw new NotSignedInError()}- response = await fetcher(url, buildInit(init, token, accept))+ response = await fetchResponse(token)noteServerDate(response)}return response}async function parseBody(response: Response): Promise<unknown> {- const text = await response.text()+ const text = await transport(() => response.text())if (!text) {return undefined}@@ -193,14 +205,29 @@ async function parseBody(response: Response): Promise<unknown> {}}-/** Sends a request and returns the raw response. Refreshes the token once on a 401. */-export async function apiFetch(path: string, init: ApiInit = {}): Promise<Response> {- return withAppReloadBlocked(() => send((url, options) => fetch(url, options), path, init, 'application/json'))+export async function apiReadResponse<T>(+ path: string,+ init: ApiInit,+ read: (response: Response) => Promise<T>+): Promise<T> {+ return withAppReloadBlocked(() =>+ requestWithDeadline(async (signal) => {+ const response = await send(+ (url, options) => fetch(url, options),+ path,+ { ...init, signal },+ 'application/json'+ )+ if (signal.aborted) {+ throw abortError()+ }+ return read(response)+ }, init.signal)+ )}export async function apiJson<T>(path: string, init: ApiInit = {}): Promise<T> {- return withAppReloadBlocked(async () => {- const response = await apiFetch(path, init)+ return apiReadResponse(path, init, async (response) => {const body = await parseBody(response)if (!response.ok) {throw new ApiError(response.status, body, response.headers)diff --git a/products/mobile/src/api/replayVision.ts b/products/mobile/src/api/replayVision.tsindex f4354a8f0df8..b49e77af6b28 100644--- a/products/mobile/src/api/replayVision.ts+++ b/products/mobile/src/api/replayVision.ts@@ -1,5 +1,6 @@-import { ApiError, apiFetch, apiJson, projectPath } from './client'+import { ApiError, apiJson, apiReadResponse, projectPath } from './client'import { type ProjectScope, scopeKey } from './reports'+import { transport } from './transport'// Shapes follow `ReplayObservationSerializer`, `InlineScanResponseSerializer` and `WatchFeedResponseSerializer` in// `products/replay_vision/backend/api/`, keeping the fields the app reads. The summarizer's `model_output` follows@@ -118,23 +119,28 @@ export async function fetchFrameUrl(chapter: number | null,signal?: AbortSignal): Promise<string> {- const response = await apiFetch(+ return apiReadResponse(projectPath(`vision/observations/${encodeURIComponent(observationId)}/thumbnail/`),{query: { chapter },redirect: 'manual',signal,+ },+ async (response) => {+ const location = response.headers.get('Location')+ if (response.status >= 300 && response.status < 400 && location) {+ return location+ }+ if (response.ok) {+ // Local dev and a deployment without object storage serve the bytes from the API itself.+ return frameDataUri(+ await transport(() => response.arrayBuffer()),+ response.headers.get('Content-Type') ?? 'image/png'+ )+ }+ throw new ApiError(response.status, undefined, response.headers)})- const location = response.headers.get('Location')- if (response.status >= 300 && response.status < 400 && location) {- return location- }- if (response.ok) {- // Local dev and a deployment without object storage serve the bytes from the API itself.- return frameDataUri(await response.arrayBuffer(), response.headers.get('Content-Type') ?? 'image/png')- }- throw new ApiError(response.status, undefined, response.headers)}function frameDataUri(bytes: ArrayBuffer, contentType: string): string {diff --git a/products/mobile/src/api/tasks.ts b/products/mobile/src/api/tasks.tsindex bfe6b2e1f16b..47e2e7f3a5d2 100644--- a/products/mobile/src/api/tasks.ts+++ b/products/mobile/src/api/tasks.ts@@ -1,4 +1,5 @@-import { ApiError, apiFetch, apiJson, apiStream, projectPath } from './client'+import { ApiError, apiJson, apiReadResponse, apiStream, projectPath } from './client'+import { transport } from './transport'// Shapes follow `products/tasks/backend/presentation/serializers.py`, keeping the fields the app reads.@@ -319,15 +320,17 @@ export function getTaskRun(taskId: string, runId: string, signal?: AbortSignal):/** The stored run log, one JSON record per line. A resumed run's log starts with its ancestors' logs, oldest first. */export async function getTaskRunLogs(taskId: string, runId: string, signal?: AbortSignal): Promise<unknown[]> {- const response = await apiFetch(+ return apiReadResponse(projectPath(`tasks/${encodeURIComponent(taskId)}/runs/${encodeURIComponent(runId)}/logs/`),- { signal }+ { signal },+ async (response) => {+ const text = await transport(() => response.text())+ if (!response.ok) {+ throw new ApiError(response.status, parseJsonLine(text), response.headers)+ }+ return parseJsonLines(text)+ })- const text = await response.text()- if (!response.ok) {- throw new ApiError(response.status, parseJsonLine(text), response.headers)- }- return parseJsonLines(text)}function parseJsonLine(line: string): unknown {diff --git a/products/mobile/src/api/transport.ts b/products/mobile/src/api/transport.tsnew file mode 100644index 000000000000..c6bc8d0f5066--- /dev/null+++ b/products/mobile/src/api/transport.ts@@ -0,0 +1,59 @@+import { abortError } from '@/lib/abort'++export const REQUEST_TIMEOUT_MS = 30_000++export class TransportError extends Error {+ constructor() {+ super("Couldn't reach PostHog. Check your connection and try again.")+ this.name = 'TransportError'+ }+}++export class RequestTimeoutError extends TransportError {+ constructor() {+ super()+ this.message = 'The request took too long. Try again.'+ this.name = 'RequestTimeoutError'+ }+}++export async function transport<T>(work: () => Promise<T>): Promise<T> {+ try {+ return await work()+ } catch (error) {+ if (error instanceof SyntaxError || (error instanceof Error && error.name === 'AbortError')) {+ throw error+ }+ throw new TransportError()+ }+}++export async function requestWithDeadline<T>(+ work: (signal: AbortSignal) => Promise<T>,+ caller?: AbortSignal | null,+ timeoutMs = REQUEST_TIMEOUT_MS+): Promise<T> {+ if (caller?.aborted) {+ throw abortError()+ }+ const controller = new AbortController()+ let timer: ReturnType<typeof setTimeout> | undefined+ let onAbort: () => void = () => undefined+ const cancelled = new Promise<never>((_resolve, reject) => {+ onAbort = () => {+ reject(abortError())+ controller.abort()+ }+ caller?.addEventListener('abort', onAbort, { once: true })+ timer = setTimeout(() => {+ reject(new RequestTimeoutError())+ controller.abort()+ }, timeoutMs)+ })+ try {+ return await Promise.race([work(controller.signal), cancelled])+ } finally {+ clearTimeout(timer)+ caller?.removeEventListener('abort', onAbort)+ }+}diff --git a/products/mobile/src/auth/account.ts b/products/mobile/src/auth/account.tsindex d444eaa636e6..94135c344639 100644--- a/products/mobile/src/auth/account.ts+++ b/products/mobile/src/auth/account.ts@@ -1,4 +1,5 @@import { ApiError, NotSignedInError } from '@/api/client'+import { requestWithDeadline, transport } from '@/api/transport'import { fetchMe, fetchOrganization, type MeApi, type OrganizationApi } from '@/api/users'export interface AuthUser {@@ -97,24 +98,28 @@ export function loadAccount(): Promise<Account> {/** Checks a candidate sign-in without changing the active API client's host or credentials. */export function loadAccountWithCredentials(host: string, accessToken: string): Promise<Account> {- const read = async <T>(path: string): Promise<T> => {- const response = await fetch(`${host}${path}`, {- headers: { Accept: 'application/json', Authorization: `Bearer ${accessToken}` },- })- if (!response.ok) {- if (response.status === 401) {- throw new NotSignedInError()- }- let body: unknown- try {- body = await response.json()- } catch {- body = undefined+ const read = <T>(path: string): Promise<T> =>+ requestWithDeadline(async (signal) => {+ const response = await transport(() =>+ fetch(`${host}${path}`, {+ signal,+ headers: { Accept: 'application/json', Authorization: `Bearer ${accessToken}` },+ })+ )+ if (!response.ok) {+ if (response.status === 401) {+ throw new NotSignedInError()+ }+ let body: unknown+ try {+ body = await transport(() => response.json())+ } catch {+ body = undefined+ }+ throw new ApiError(response.status, body, response.headers)}- throw new ApiError(response.status, body, response.headers)- }- return (await response.json()) as T- }+ return (await transport(() => response.json())) as T+ })return loadAccountFrom(() => read<MeApi>('/api/users/@me/'),(organizationId) => read<OrganizationApi>(`/api/organizations/${encodeURIComponent(organizationId)}/`)diff --git a/products/mobile/src/auth/authStore.ts b/products/mobile/src/auth/authStore.tsindex c3804e8cc9ba..8919cbcc6cd3 100644--- a/products/mobile/src/auth/authStore.ts+++ b/products/mobile/src/auth/authStore.ts@@ -4,6 +4,7 @@ import { createJSONStorage, persist } from 'zustand/middleware'import { ApiError, NotSignedInError, setAuthProvider } from '@/api/client'import { queryClient } from '@/api/queryClient'+import { TransportError } from '@/api/transport'import { identify, resetAnalytics, track } from '@/lib/analytics'import { toError } from '@/lib/errors'import { createPersistHydrationGate } from '@/lib/persistHydration'@@ -120,8 +121,8 @@ function accountLoadMessage(error: unknown, method: AuthMethod): string {if (error instanceof ApiError) {return `Couldn't load your account. ${error.message}`}- if (error instanceof TypeError) {- return "Couldn't reach PostHog. Check your connection and try again."+ if (error instanceof TransportError) {+ return error.message}return toError(error).message}@@ -537,6 +538,9 @@ async function refreshOnce(): Promise<string | null> {await endSession('expired')return null}+ if (error instanceof OAuthError && error.kind === 'network') {+ throw new TransportError()+ }throw error}if (sessionGeneration() !== session) {diff --git a/products/mobile/src/auth/oauth.ts b/products/mobile/src/auth/oauth.tsindex 13c75eb30aa3..9ad7b826cee9 100644--- a/products/mobile/src/auth/oauth.ts+++ b/products/mobile/src/auth/oauth.ts@@ -1,6 +1,7 @@import { AuthRequest, type AuthSessionResult, makeRedirectUri } from 'expo-auth-session'import { Platform } from 'react-native'+import { requestWithDeadline, TransportError, transport } from '@/api/transport'import { appScheme } from '@/lib/environment'import type { SessionTokens } from './tokens'@@ -128,6 +129,15 @@ async function fetchWithTimeout(url: string, init: RequestInit, timeoutMs: numbe}}+async function readTokenBody(response: Response): Promise<unknown> {+ try {+ return await transport(() => response.json())+ } catch (error) {+ if (error instanceof TransportError) throw new OAuthError('network')+ throw error+ }+}+async function readOAuthError(response: Response): Promise<{ error?: string; description?: string }> {try {const body = (await response.json()) as Record<string, unknown>@@ -140,16 +150,31 @@ async function readOAuthError(response: Response): Promise<{ error?: string; des}}-async function postToken(host: string, body: Record<string, string>): Promise<Response> {- return fetchWithTimeout(- `${host}/oauth/token`,- {- method: 'POST',- headers: { 'Content-Type': 'application/json', Accept: 'application/json' },- body: JSON.stringify(body),- },- REQUEST_TIMEOUT_MS- )+async function postToken<T>(+ host: string,+ body: Record<string, string>,+ readResponse: (response: Response) => Promise<T>+): Promise<T> {+ try {+ return await requestWithDeadline(+ async (signal) => {+ const response = await transport(() =>+ fetch(`${host}/oauth/token`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json', Accept: 'application/json' },+ body: JSON.stringify(body),+ signal,+ })+ )+ return readResponse(response)+ },+ undefined,+ REQUEST_TIMEOUT_MS+ )+ } catch (error) {+ if (error instanceof TransportError) throw new OAuthError('network')+ throw error+ }}function authResultError(result: AuthSessionResult): OAuthError {@@ -200,25 +225,34 @@ export async function authorize({ host, clientId }: { host: string; clientId: stif (!request.codeVerifier) {throw new OAuthError('rejected', 'The sign-in request lost its PKCE verifier.')}- const response = await postToken(host, {- grant_type: 'authorization_code',- code,- redirect_uri: request.redirectUri,- client_id: clientId,- code_verifier: request.codeVerifier,- })- if (!response.ok) {- const { error, description } = await readOAuthError(response)- if (error === 'invalid_scope') {- throw new OAuthError('missing_scope', description)+ return postToken(+ host,+ {+ grant_type: 'authorization_code',+ code,+ redirect_uri: request.redirectUri,+ client_id: clientId,+ code_verifier: request.codeVerifier,+ },+ async (response) => {+ if (!response.ok) {+ const { error, description } = await readOAuthError(response)+ if (error === 'invalid_scope') {+ throw new OAuthError('missing_scope', description)+ }+ throw new OAuthError(response.status >= 500 ? 'server' : 'rejected', description ?? error)+ }+ const body = await readTokenBody(response)+ if (!isTokenResponse(body)) {+ throw new OAuthError('rejected', 'The token response had no access token.')+ }+ return toSessionTokens(body, {+ refreshToken: null,+ grantedScopes: null,+ requestedScopes: [...OAUTH_SCOPES],+ })}- throw new OAuthError(response.status >= 500 ? 'server' : 'rejected', description ?? error)- }- const body: unknown = await response.json()- if (!isTokenResponse(body)) {- throw new OAuthError('rejected', 'The token response had no access token.')- }- return toSessionTokens(body, { refreshToken: null, grantedScopes: null, requestedScopes: [...OAUTH_SCOPES] })+ )}// The server rotates the refresh token on every call and revokes the whole family when an old one is reused after a@@ -236,26 +270,31 @@ export async function refreshTokens({grantedScopes?: string[] | nullrequestedScopes?: string[] | null}): Promise<SessionTokens> {- const response = await postToken(host, {- grant_type: 'refresh_token',- refresh_token: refreshToken,- client_id: clientId,- })- if (response.status === 400 || response.status === 401 || response.status === 403) {- const { error, description } = await readOAuthError(response)- throw new OAuthError('session_expired', description ?? error)- }- if (!response.ok) {- throw new OAuthError(- response.status >= 500 ? 'server' : 'rejected',- `Token refresh failed with ${response.status}`- )- }- const body: unknown = await response.json()- if (!isTokenResponse(body)) {- throw new OAuthError('rejected', 'The token response had no access token.')- }- return toSessionTokens(body, { refreshToken, grantedScopes, requestedScopes })+ return postToken(+ host,+ {+ grant_type: 'refresh_token',+ refresh_token: refreshToken,+ client_id: clientId,+ },+ async (response) => {+ if (response.status === 400 || response.status === 401 || response.status === 403) {+ const { error, description } = await readOAuthError(response)+ throw new OAuthError('session_expired', description ?? error)+ }+ if (!response.ok) {+ throw new OAuthError(+ response.status >= 500 ? 'server' : 'rejected',+ `Token refresh failed with ${response.status}`+ )+ }+ const body = await readTokenBody(response)+ if (!isTokenResponse(body)) {+ throw new OAuthError('rejected', 'The token response had no access token.')+ }+ return toSessionTokens(body, { refreshToken, grantedScopes, requestedScopes })+ }+ )}// Revocation follows RFC 7009, which takes a form body. Failures are ignored because sign out must work offline.diff --git a/products/mobile/src/auth/sessionRestore.test.ts b/products/mobile/src/auth/sessionRestore.test.tsindex 33e8ca2409ef..90fbe36f9612 100644--- a/products/mobile/src/auth/sessionRestore.test.ts+++ b/products/mobile/src/auth/sessionRestore.test.ts@@ -1,5 +1,5 @@import * as SecureStore from 'expo-secure-store'-import { installAuthProvider, useAuthStore } from './authStore'+import { installAuthProvider, refreshAccessToken, useAuthStore } from './authStore'import { loadTokens, saveTokens, setSessionTokens } from './tokens'jest.mock('@react-native-async-storage/async-storage', () =>@@ -38,66 +38,85 @@ describe('stored session identity', () => {expect(await loadTokens()).toBeNull()})- test('restores and refreshes using the secure identity when cached metadata belongs to an earlier account', async () => {- const requests: string[] = []- globalThis.fetch = jest.fn(async (url: string) => {- requests.push(url)- if (url.endsWith('/oauth/token')) {+ test('restores the secure identity after a stalled refresh and allows a later refresh to recover', async () => {+ jest.useFakeTimers()+ try {+ let stalledSignal: AbortSignal | null | undefined+ let stall = true+ const requests: string[] = []+ globalThis.fetch = jest.fn(async (url: string, init?: RequestInit) => {+ requests.push(url)+ if (url.endsWith('/oauth/token')) {+ if (stall) {+ stall = false+ stalledSignal = init?.signal+ return Object.assign(json({}), { json: () => new Promise<never>(() => undefined) })+ }+ return json({+ access_token: 'example-rotated-access',+ refresh_token: 'example-rotated-refresh',+ expires_in: 3600,+ })+ }return json({- access_token: 'example-rotated-access',- refresh_token: 'example-rotated-refresh',- expires_in: 3600,+ id: 1,+ uuid: 'current-user',+ distinct_id: 'current-user',+ email: '[email protected]',+ first_name: '',+ last_name: '',+ team: null,+ organization: null,+ organizations: [],})- }- return json({- id: 1,- uuid: 'current-user',- distinct_id: 'current-user',- email: '[email protected]',- first_name: '',- last_name: '',- team: null,- organization: null,- organizations: [],- })- }) as unknown as typeof fetch- await saveTokens(tokens, { host, clientId: 'example-client', method: 'oauth', userUuid: 'current-user' })- useAuthStore.setState({- status: 'loading',- signedIn: false,- host: 'https://previous.example.com',- clientId: 'previous-client',- method: 'oauth',- user: {- uuid: 'previous-user',- distinctId: 'previous-user',- email: '[email protected]',- name: 'Previous',- },- projectId: 9,- projects: [- {- id: 9,- name: 'Previous project',- organizationId: 'previous-org',- organizationName: 'Previous organization',+ }) as unknown as typeof fetch+ await saveTokens(tokens, { host, clientId: 'example-client', method: 'oauth', userUuid: 'current-user' })+ useAuthStore.setState({+ status: 'loading',+ signedIn: false,+ host: 'https://previous.example.com',+ clientId: 'previous-client',+ method: 'oauth',+ user: {+ uuid: 'previous-user',+ distinctId: 'previous-user',+ email: '[email protected]',+ name: 'Previous',},- ],- })- setSessionTokens(null)- installAuthProvider()- await useAuthStore.getState().restore()- expect(requests).toEqual([`${host}/oauth/token`, `${host}/api/users/@me/`])- expect(useAuthStore.getState()).toMatchObject({- host,- clientId: 'example-client',- user: { uuid: 'current-user' },- projectId: null,- projects: [],- })- expect(JSON.parse((await SecureStore.getItemAsync('posthog_mobile_session')) ?? '{}')).toMatchObject({- identity: { host, userUuid: 'current-user' },- tokens: { accessToken: 'example-rotated-access' },- })+ projectId: 9,+ projects: [+ {+ id: 9,+ name: 'Previous project',+ organizationId: 'previous-org',+ organizationName: 'Previous organization',+ },+ ],+ })+ setSessionTokens(null)+ installAuthProvider()+ const restoring = useAuthStore.getState().restore()+ await jest.advanceTimersByTimeAsync(20_000)+ await restoring+ expect(stalledSignal?.aborted).toBe(true)+ expect(useAuthStore.getState()).toMatchObject({ status: 'signed_in', signedIn: true })+ expect(await loadTokens()).toMatchObject({ accessToken: 'example-access', refreshToken: 'example-refresh' })+ expect(requests).toEqual([`${host}/oauth/token`, `${host}/api/users/@me/`])+ expect(useAuthStore.getState()).toMatchObject({+ host,+ clientId: 'example-client',+ user: { uuid: 'current-user' },+ projectId: null,+ projects: [],+ })+ await expect(refreshAccessToken()).resolves.toBe('example-rotated-access')+ expect(requests.filter((url) => url.endsWith('/oauth/token'))).toHaveLength(2)+ expect(JSON.parse((await SecureStore.getItemAsync('posthog_mobile_session')) ?? '{}')).toMatchObject({+ identity: { host, userUuid: 'current-user' },+ tokens: { accessToken: 'example-rotated-access' },+ })+ } finally {+ jest.useRealTimers()+ }})})diff --git a/products/mobile/src/auth/signInErrors.test.ts b/products/mobile/src/auth/signInErrors.test.tsindex ea9f608f6e79..f094718e0dfb 100644--- a/products/mobile/src/auth/signInErrors.test.ts+++ b/products/mobile/src/auth/signInErrors.test.ts@@ -1,4 +1,5 @@import { ApiError, NotSignedInError } from '@/api/client'+import { TransportError } from '@/api/transport'import type { AuthMethod } from './authStore'import { OAuthError } from './oauth'@@ -25,7 +26,8 @@ describe('signInFailureReason', () => {['a rejected OAuth session', accountError(new NotSignedInError()), 'oauth', 'account_rejected'],['a 403 on the account', accountError(new ApiError(403, {})), 'oauth', 'account_forbidden'],['a 500 on the account', accountError(new ApiError(500, {})), 'oauth', 'account_load'],- ['no connection for the account', accountError(new TypeError('Network request failed')), 'oauth', 'network'],+ ['no connection for the account', accountError(new TransportError()), 'oauth', 'network'],+ ['an account programming error', accountError(new TypeError('Network state is undefined')), 'oauth', 'unknown'],['anything else', new Error('boom'), 'oauth', 'unknown'],])('%s', (_name, error, method, expected) => {expect(signInFailureReason(error, method)).toBe(expected)diff --git a/products/mobile/src/auth/signInErrors.ts b/products/mobile/src/auth/signInErrors.tsindex bb322d8e057b..51be6a966bde 100644--- a/products/mobile/src/auth/signInErrors.ts+++ b/products/mobile/src/auth/signInErrors.ts@@ -1,4 +1,5 @@import { ApiError, NotSignedInError } from '@/api/client'+import { TransportError } from '@/api/transport'import type { AuthMethod } from './authStore'import { OAuthError, type OAuthErrorKind } from './oauth'@@ -19,7 +20,7 @@ export function accountLoadKind(error: unknown): AccountLoadKind {if (error instanceof ApiError) {return error.status === 403 ? 'forbidden' : 'api_error'}- if (error instanceof TypeError) {+ if (error instanceof TransportError) {return 'network'}return 'unknown'diff --git a/products/mobile/src/auth/tokenRefresh.test.ts b/products/mobile/src/auth/tokenRefresh.test.tsindex 8c8e44c7f96d..c0155b283a0a 100644--- a/products/mobile/src/auth/tokenRefresh.test.ts+++ b/products/mobile/src/auth/tokenRefresh.test.ts@@ -1,8 +1,9 @@import * as SecureStore from 'expo-secure-store'import { apiJson, NotSignedInError, projectPath } from '@/api/client'+import { TransportError } from '@/api/transport'import { addSessionEndTask, addSignOutTask, installAuthProvider, useAuthStore } from './authStore'-import { OAuthError } from './oauth'+import { authorize, OAuthError, refreshTokens } from './oauth'import { getSessionIdentity, getSessionTokens, loadTokens, saveTokens, setSessionTokens } from './tokens'jest.mock('@react-native-async-storage/async-storage', () =>@@ -129,7 +130,20 @@ describe('token refresh through the API client', () => {token: async (): Promise<Response> => {throw new TypeError('Network request failed')},- error: OAuthError,+ error: TransportError,+ status: 'signed_in',+ reason: null,+ accessToken: 'old-access',+ },+ {+ name: 'a dropped refresh response body keeps the session for a later retry',+ token: async (): Promise<Response> =>+ Object.assign(json(200, {}), {+ json: async () => {+ throw new TypeError('Network request failed')+ },+ }),+ error: TransportError,status: 'signed_in',reason: null,accessToken: 'old-access',@@ -143,6 +157,63 @@ describe('token refresh through the API client', () => {expect(getSessionTokens()?.accessToken).toBe(accessToken)})+ test.each([+ { operation: 'sign-in', status: 200 },+ { operation: 'sign-in', status: 400 },+ { operation: 'sign-in', status: 500 },+ { operation: 'refresh', status: 200 },+ { operation: 'refresh', status: 400 },+ ])('$operation bounds a stalled $status body with the original deadline', async ({ operation, status }) => {+ jest.useFakeTimers()+ try {+ let signal: AbortSignal | null | undefined+ const readBody = jest.fn(() => new Promise<never>(() => undefined))+ fetchMock.mockImplementationOnce(async (_url, init) => {+ signal = init?.signal+ await new Promise((resolve) => setTimeout(resolve, 5_000))+ return Object.assign(json(status, {}), { json: readBody })+ })+ const request = (): Promise<unknown> =>+ operation === 'sign-in'+ ? authorize({ host: HOST, clientId: 'test-client' })+ : refreshTokens({ host: HOST, clientId: 'test-client', refreshToken: 'example-refresh' })+ const failure = expect(request()).rejects.toMatchObject({ name: 'OAuthError', kind: 'network' })+ await jest.advanceTimersByTimeAsync(5_000)+ expect(readBody).toHaveBeenCalledTimes(1)+ await jest.advanceTimersByTimeAsync(14_999)+ expect(signal?.aborted).toBe(false)+ await jest.advanceTimersByTimeAsync(1)+ await failure+ expect(signal?.aborted).toBe(true)++ fetchMock.mockResolvedValueOnce(json(200, { access_token: 'recovered-access' }))+ await expect(request()).resolves.toMatchObject({ accessToken: 'recovered-access' })+ expect(jest.getTimerCount()).toBe(0)+ } finally {+ jest.useRealTimers()+ }+ })++ test.each([new TypeError('Network request failed'), new SyntaxError('Invalid JSON')])(+ 'OAuth callers distinguish transport failures from invalid JSON: %p',+ async (failure) => {+ fetchMock.mockResolvedValue(+ Object.assign(json(200, {}), {+ json: async () => {+ throw failure+ },+ })+ )+ const response = refreshTokens({ host: HOST, clientId: 'test-client', refreshToken: 'example-refresh' })+ if (failure instanceof SyntaxError) {+ await expect(response).rejects.toBe(failure)+ } else {+ await expect(response).rejects.toBeInstanceOf(OAuthError)+ await expect(response).rejects.toMatchObject({ kind: 'network' })+ }+ }+ )+test.each([{ name: 'API response', held: `${OLD_HOST}/api/users/@me/`, answer: (): Response => json(401, {}) },{diff --git a/products/mobile/src/features/chat/chatErrors.test.ts b/products/mobile/src/features/chat/chatErrors.test.tsindex 5a97a731f327..7edfc924700f 100644--- a/products/mobile/src/features/chat/chatErrors.test.ts+++ b/products/mobile/src/features/chat/chatErrors.test.ts@@ -1,4 +1,5 @@import { ApiError, NotSignedInError } from '@/api/client'+import { TransportError } from '@/api/transport'import { toChatError } from './chatErrors'import type { ChatError } from './types'@@ -86,7 +87,8 @@ describe('chat error mapping', () => {new ApiError(502, { error: 'Failed to queue user message for task run' }),{ kind: 'unavailable', message: "Your message didn't reach the agent. Try again in a moment." },],- ['a dropped connection', new TypeError('Network request failed'), { kind: 'network' }],+ ['a programming error', new TypeError('Network state is undefined'), { kind: 'unknown' }],+ ['a dropped connection', new TransportError(), { kind: 'network' }],['a signed-out session', new NotSignedInError(), { kind: 'auth' }],])('%s', (_label, error, expected) => {expect(toChatError(error)).toMatchObject(expected)diff --git a/products/mobile/src/features/chat/chatErrors.ts b/products/mobile/src/features/chat/chatErrors.tsindex 77afef81efe9..185bbfe6efab 100644--- a/products/mobile/src/features/chat/chatErrors.ts+++ b/products/mobile/src/features/chat/chatErrors.ts@@ -1,4 +1,5 @@import { ApiError, NotSignedInError } from '@/api/client'+import { TransportError } from '@/api/transport'import { isRecord } from '@/lib/records'import type { ChatError } from './types'@@ -19,18 +20,6 @@ function retryHint(seconds: number | undefined): string {return `Try again in ${Math.ceil(seconds / 60)} minutes.`}-function isAbortError(error: unknown): boolean {- return error instanceof Error && error.name === 'AbortError'-}--export function isNetworkError(error: unknown): boolean {- if (error instanceof ApiError || error instanceof NotSignedInError || isAbortError(error)) {- return false- }- // fetch reports a lost connection as a TypeError on every platform the app runs on.- return error instanceof TypeError || (error instanceof Error && /network|connection|socket/i.test(error.message))-}-/** The tasks API's PostHog Desktop gate and limits. Their copy is under `error`, which `ApiError.detail` carries. */function taskRunError(error: ApiError): ChatError | undefined {const type = isRecord(error.body) ? error.body.type : undefined@@ -114,8 +103,8 @@ export function toChatError(error: unknown): ChatError {return { kind: 'unknown', message: 'Something went wrong. Try again.' }}}- if (isNetworkError(error)) {- return { kind: 'network', message: "Couldn't reach PostHog. Check your connection and try again." }+ if (error instanceof TransportError) {+ return { kind: 'network', message: error.message }}return { kind: 'unknown', message: 'Something went wrong. Try again.' }}diff --git a/products/mobile/src/features/notifications/pushRegistration.ts b/products/mobile/src/features/notifications/pushRegistration.tsindex 59c646ebc173..81926c7c1476 100644--- a/products/mobile/src/features/notifications/pushRegistration.ts+++ b/products/mobile/src/features/notifications/pushRegistration.ts@@ -4,6 +4,7 @@ import { Platform } from 'react-native'import { ApiError } from '@/api/client'import { registerPushToken, unregisterPushToken } from '@/api/pushTokens'+import { TransportError } from '@/api/transport'import { useAuthStore } from '@/auth/authStore'import { sessionGeneration } from '@/auth/tokens'import { track } from '@/lib/analytics'@@ -39,7 +40,7 @@ function registrationFailure(error: unknown, gotToken: boolean): RegistrationFaiif (error instanceof ApiError) {return 'api_error'}- return error instanceof TypeError ? 'network' : 'unknown'+ return error instanceof TransportError ? 'network' : 'unknown'}export function configureNotifications(): void {diff --git a/products/mobile/src/features/report/reportAnalytics.test.ts b/products/mobile/src/features/report/reportAnalytics.test.tsindex 6bb23628b6e9..193066b0c23e 100644--- a/products/mobile/src/features/report/reportAnalytics.test.ts+++ b/products/mobile/src/features/report/reportAnalytics.test.ts@@ -1,6 +1,7 @@import { renderHook } from '@testing-library/react-native'import { ApiError, NotSignedInError } from '@/api/client'+import { TransportError } from '@/api/transport'import { setAnalyticsClient } from '@/lib/analytics'import { apiErrorKind, useSheetFunnel } from './reportAnalytics'@@ -17,7 +18,8 @@ describe('reportAnalytics', () => {['no session', new NotSignedInError(), 'auth'],['a 404', new ApiError(404, {}), 'not_found'],['a 502', new ApiError(502, {}), 'server'],- ['a network failure', new TypeError('Network request failed'), 'network'],+ ['a programming error', new TypeError('Network state is undefined'), 'unknown'],+ ['a network failure', new TransportError(), 'network'],])('apiErrorKind: %s', (_name, error, expected) => {expect(apiErrorKind(error)).toBe(expected)})diff --git a/products/mobile/src/features/report/reportAnalytics.ts b/products/mobile/src/features/report/reportAnalytics.tsindex f05adb9d1854..ccd319e3aeab 100644--- a/products/mobile/src/features/report/reportAnalytics.ts+++ b/products/mobile/src/features/report/reportAnalytics.ts@@ -2,6 +2,7 @@ import { useMemo, useRef } from 'react'import { ApiError, NotSignedInError } from '@/api/client'import { missingScope } from '@/api/scopeErrors'+import { TransportError } from '@/api/transport'import { track } from '@/lib/analytics'/** How the report screen was reached. Sent with `mobile_report_opened`, so it travels in the route as `from`. */@@ -49,7 +50,7 @@ export function apiErrorKind(error: unknown): ApiErrorKind {}return error.status >= 500 ? 'server' : 'unknown'}- return error instanceof TypeError ? 'network' : 'unknown'+ return error instanceof TransportError ? 'network' : 'unknown'}export interface SheetFunnel {diff --git a/products/mobile/src/lib/errors.ts b/products/mobile/src/lib/errors.tsindex c3bb00e7a758..1169ffa9e3cf 100644--- a/products/mobile/src/lib/errors.ts+++ b/products/mobile/src/lib/errors.ts@@ -1,4 +1,5 @@import { ApiError } from '@/api/client'+import { TransportError } from '@/api/transport'export function toError(value: unknown): Error {return value instanceof Error ? value : new Error(String(value))@@ -9,8 +10,8 @@ export function actionErrorMessage(error: unknown): string {if (error instanceof ApiError) {return error.detail ?? `PostHog couldn't do that (error ${error.status}). Try again.`}- if (error instanceof TypeError) {- return "Couldn't reach PostHog. Check your connection and try again."+ if (error instanceof TransportError) {+ return error.message}return toError(error).message}