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.

feat(mobile): show regional incident status in the menu and chats (#128447)

Chris Volzer4186b7a162a5
diff --git a/products/mobile/docs/CHAT.md b/products/mobile/docs/CHAT.md
index b247eb802050..c92c1fdbfce6 100644
--- a/products/mobile/docs/CHAT.md
+++ b/products/mobile/docs/CHAT.md
@@ -7,6 +7,10 @@ New and existing chats open as full-screen stack pages. Back returns to the prev
configured default page for a direct link. The title-free header uses the shared blur and fading edge;
New chat and the ellipsis share the Inbox's pill control. The composer clears the keyboard and safe area.
+An active incident affecting PostHog AI in the selected cloud region appears below the header in new and existing chats.
+The notice shows the published incident title and phase. Tap it to read the update. For other services, open **PostHog status** below the project name in the
+main tabs’ ellipsis menu. An indicator on that menu signals a regional incident or in-progress maintenance. The menu shows the highest current impact and the number of concurrent incidents. The status row has a green dot for a healthy region, yellow for degraded performance or maintenance, and red for partial or major outages. Chat warnings use the impact on the regional AI component.
+
The ellipsis menu offers **Copy link to chat** and **Archive chat**. Copy uses the current project's
web URL. Archive returns to the previous page after success and keeps the chat open for retry on failure.
The menu is disabled for an unsaved new chat. Model, Mode, and attachment options still open as overlays.
diff --git a/products/mobile/docs/DATA.md b/products/mobile/docs/DATA.md
index 914485f5657e..7f5a90a5358c 100644
--- a/products/mobile/docs/DATA.md
+++ b/products/mobile/docs/DATA.md
@@ -31,7 +31,7 @@ Query keys (`reportKeys` in `src/api/reports.ts`) carry the host and project id,
## 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.
+`src/lib/connectivity.ts` maps Expo Network events to `unknown`, `connected` or `offline` and keeps the connection type for prefetch. 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.
@@ -93,7 +93,7 @@ A failed background refetch keeps the cached report on screen.
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 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 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 Wi-Fi or Ethernet link, and no observed foreground query is fetching. Unknown connection types and cellular links pause prefetch but do 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/chat/AiIncidentNotice.tsx b/products/mobile/src/features/chat/AiIncidentNotice.tsx
new file mode 100644
index 000000000000..7a5ea54d622a
--- /dev/null
+++ b/products/mobile/src/features/chat/AiIncidentNotice.tsx
@@ -0,0 +1,50 @@
+import type { ReactElement } from 'react'
+import { Linking, Text } from 'react-native'
+
+import type { PostHogStatus } from '@/features/status/usePostHogStatus'
+import { ExternalLinkIcon } from '@/ui/icons/ExternalLinkIcon'
+import { WarningIcon } from '@/ui/icons/WarningIcon'
+import { Pressable44 } from '@/ui/Pressable44'
+import { createStyles, useColors } from '@/ui/theme'
+import { radii, type } from '@/ui/tokens'
+
+export function AiIncidentNotice({ incident }: { incident: NonNullable<PostHogStatus['aiIncident']> }): ReactElement {
+ const styles = useStyles()
+ const colors = useColors()
+ const label = `PostHog AI incident (${incident.status}) · ${incident.title}`
+ return (
+ <Pressable44
+ accessibilityRole="link"
+ accessibilityLabel={label}
+ accessibilityHint="Opens the incident update"
+ onPress={() => void Linking.openURL(incident.url).catch(() => undefined)}
+ pressedBackground={colors.sunken}
+ style={styles.notice}
+ testID="chat-ai-incident"
+ >
+ <WarningIcon size={18} color={colors[incident.color]} />
+ <Text style={styles.text} numberOfLines={2}>
+ {label}
+ </Text>
+ <ExternalLinkIcon size={16} color={colors.muted} />
+ </Pressable44>
+ )
+}
+
+const useStyles = createStyles(({ colors }) => ({
+ notice: {
+ marginHorizontal: 16,
+ marginBottom: 6,
+ paddingHorizontal: 12,
+ paddingVertical: 6,
+ minHeight: 44,
+ flexDirection: 'row',
+ alignItems: 'center',
+ gap: 8,
+ backgroundColor: colors.background,
+ borderColor: colors.hairline,
+ borderWidth: 1,
+ borderRadius: radii.card,
+ },
+ text: { ...type.meta, flex: 1, color: colors.ink },
+}))
diff --git a/products/mobile/src/features/chat/ChatScreen.test.tsx b/products/mobile/src/features/chat/ChatScreen.test.tsx
index fb4e0d22bb6e..073f43d889c0 100644
--- a/products/mobile/src/features/chat/ChatScreen.test.tsx
+++ b/products/mobile/src/features/chat/ChatScreen.test.tsx
@@ -19,6 +19,18 @@ jest.mock(
() => jest.requireActual('react-native-safe-area-context/jest/mock').default
)
jest.mock('react-native-keyboard-controller', () => jest.requireActual('react-native-keyboard-controller/jest'))
+jest.mock('@/features/status/usePostHogStatus', () => ({
+ usePostHogStatus: () => ({
+ pageUrl: 'https://www.posthogstatus.com/eu',
+ summary: 'Elevated latency',
+ aiIncident: {
+ status: 'monitoring',
+ color: 'yellow',
+ title: 'Elevated latency',
+ url: 'https://www.posthogstatus.com/incidents/example',
+ },
+ }),
+}))
jest.mock('@/auth/useProjectScope', () => ({ useProjectScope: () => ({ host: 'https://example.com', projectId: 1 }) }))
jest.mock('@/demo/demoMode', () => ({ useDataMode: () => 'live' }))
jest.mock('@/features/chats/hooks', () => ({ useArchiveChat: () => ({ archive: jest.fn() }) }))
@@ -82,6 +94,13 @@ function mockReadyChat(): { session: ReturnType<typeof useSession>; draft: Retur
return { session, draft }
}
+test.each([null, 'task-1'])('shows the regional AI incident for chat %s', (taskId) => {
+ const { session } = mockReadyChat()
+ session.taskId = taskId
+ render(<ChatScreen source={{ entry: 'compose', origin: null }} onBack={jest.fn()} />)
+ expect(screen.getByLabelText('PostHog AI incident (monitoring) · Elevated latency')).toBeTruthy()
+})
+
describe('chat send preparation', () => {
test('keeps an unsaved draft notice visible and disables retry while saving', () => {
const { session, draft } = mockReadyChat()
diff --git a/products/mobile/src/features/chat/ChatScreen.tsx b/products/mobile/src/features/chat/ChatScreen.tsx
index bbc337af8e03..9b6403c4fc69 100644
--- a/products/mobile/src/features/chat/ChatScreen.tsx
+++ b/products/mobile/src/features/chat/ChatScreen.tsx
@@ -10,6 +10,7 @@ import { useProjectScope } from '@/auth/useProjectScope'
import { useDataMode } from '@/demo/demoMode'
import { useArchiveChat } from '@/features/chats/hooks'
import { setViewedNotificationTask } from '@/features/notifications/foregroundNotifications'
+import { usePostHogStatus } from '@/features/status/usePostHogStatus'
import { track } from '@/lib/analytics'
import { isReportId } from '@/lib/ids'
import { useNow } from '@/lib/useNow'
@@ -25,6 +26,7 @@ import { useScreenInsets } from '@/ui/useScreenInsets'
import { defaultModelSelection, isPermissionMode, modeLabel } from '../handoff/runOptions'
import { useModelCatalogue, useRunDefaults } from '../handoff/useRunOptions'
import { useInboxItems } from '../inbox/hooks'
+import { AiIncidentNotice } from './AiIncidentNotice'
import { AttachMenuSheet } from './attachments/AttachMenuSheet'
import { AttachmentChip } from './attachments/AttachmentChip'
import type { AttachmentSource, PendingAttachment } from './attachments/types'
@@ -103,6 +105,9 @@ export function ChatScreen({
const [target, setTarget] = useState<SessionOptions>(() => sessionTarget(initialTaskId, initialRunId))
const session = useSession(target)
const scope = useProjectScope()
+ const { aiIncident } = usePostHogStatus(scope?.host)
+ const headerInset = insets.top + headerHeight
+ const contentInset = aiIncident ? 0 : headerInset
const demo = useDataMode() === 'demo'
const keyboard = useReanimatedKeyboardAnimation()
const blurTarget = useRef<View>(null)
@@ -606,10 +611,15 @@ export function ChatScreen({
<View style={styles.page}>
<BlurTargetView ref={blurTarget} style={styles.body}>
<Animated.View style={[styles.keyboard, keyboardStyle]}>
+ {aiIncident ? (
+ <View style={{ paddingTop: headerInset }}>
+ <AiIncidentNotice incident={aiIncident} />
+ </View>
+ ) : null}
{showEmptyState ? (
<ScrollView
style={styles.empty}
- contentContainerStyle={{ flexGrow: 1, paddingTop: insets.top + headerHeight }}
+ contentContainerStyle={{ flexGrow: 1, paddingTop: contentInset }}
keyboardShouldPersistTaps="handled"
>
<ChatEmptyState
@@ -621,7 +631,7 @@ export function ChatScreen({
) : (
<SessionThread
session={session}
- topInset={insets.top + headerHeight}
+ topInset={contentInset}
onRetryHistory={() => {
track('mobile_session_load_retried')
if (session.reconnect) session.reconnect()
diff --git a/products/mobile/src/features/chat/session/useSession.test.tsx b/products/mobile/src/features/chat/session/useSession.test.tsx
index 2ebbfb3b8038..726f01d7e93d 100644
--- a/products/mobile/src/features/chat/session/useSession.test.tsx
+++ b/products/mobile/src/features/chat/session/useSession.test.tsx
@@ -3,6 +3,7 @@ import { AppState } from 'react-native'
import { ApiError } from '@/api/client'
import type { TaskApi, TaskCreateResponseApi, TaskRunApi } from '@/api/tasks'
import * as tasks from '@/api/tasks'
+import { TransportError } from '@/api/transport'
import { useAuthStore } from '@/auth/authStore'
import { getSessionTokens, setSessionTokens } from '@/auth/tokens'
import { useAiApproval } from '@/features/ai/aiApproval'
@@ -179,8 +180,7 @@ describe('useSession', () => {
'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 if (initial === 'failed-read') mocked.getTask.mockRejectedValueOnce(new TransportError())
else
mocked.getTask.mockImplementationOnce(
(_id, signal) =>
diff --git a/products/mobile/src/features/inbox/ReportInbox.test.tsx b/products/mobile/src/features/inbox/ReportInbox.test.tsx
index 3d72a41b7e31..ae2bf76c8ea7 100644
--- a/products/mobile/src/features/inbox/ReportInbox.test.tsx
+++ b/products/mobile/src/features/inbox/ReportInbox.test.tsx
@@ -1,14 +1,15 @@
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { act, fireEvent, render, screen, waitFor } from '@testing-library/react-native'
-import { FlatList } from 'react-native'
+import { getNetworkStateAsync, NetworkStateType } from 'expo-network'
+import { AppState, FlatList } 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, reportSignalsQuery } from '../report/queries'
-import { INITIAL_PREFETCH_COUNT } from './prefetchPlan'
import { ReportInbox } from './ReportInbox'
jest.mock('react-native-worklets', () => jest.requireActual('react-native-worklets/src/mock'))
@@ -37,9 +38,7 @@ jest.mock('./InboxRowActions', () => ({ InboxRowActions: () => null }))
const mockScope = { host: 'https://app.example.com', projectId: 2 }
let mockDataMode: 'live' | 'demo' = 'live'
-const mockItems = inboxFromReports(
- Array.from({ length: INITIAL_PREFETCH_COUNT + 5 }, (_, index) => reportFixture({ id: `report-${index}` }))
-)
+const mockItems = inboxFromReports(Array.from({ length: 20 }, (_, index) => reportFixture({ id: `report-${index}` })))
function response(status: number, body: unknown): Response {
return {
@@ -51,17 +50,22 @@ function response(status: number, body: unknown): Response {
}
describe('ReportInbox', () => {
+ const originalAppState = AppState.currentState
beforeEach(() => {
+ AppState.currentState = 'active'
mockDataMode = 'live'
+ useConnectivity.setState({ status: 'connected', type: NetworkStateType.WIFI })
+ jest.mocked(getNetworkStateAsync).mockResolvedValue({ type: NetworkStateType.WIFI, isConnected: true })
})
afterEach(() => {
+ AppState.currentState = originalAppState
setAuthProvider(null)
jest.restoreAllMocks()
jest.useRealTimers()
})
- test('warms the report cache when scrolling past the initial prefetch window', async () => {
+ test('prefetches visible reports only while the inbox is active', async () => {
setAuthProvider({
getAuth: () => ({ ...mockScope, accessToken: 'token', session: 1 }),
refreshAccessToken: async () => null,
@@ -98,12 +102,13 @@ describe('ReportInbox', () => {
</QueryClientProvider>
)
await waitFor(() =>
- expect(
- client.getQueryData(reportDetailQuery(mockScope, `report-${INITIAL_PREFETCH_COUNT - 1}`).queryKey)
- ).toBeDefined()
+ expect(client.getQueryData(reportDetailQuery(mockScope, 'report-0').queryKey)).toBeDefined()
+ )
+ await waitFor(() =>
+ expect(client.getQueryData(reportDetailQuery(mockScope, 'report-1').queryKey)).toBeDefined()
)
- const index = INITIAL_PREFETCH_COUNT + 4
+ const index = 15
const item = mockItems[index]
if (!item) {
throw new Error('Missing visible report fixture')
diff --git a/products/mobile/src/features/inbox/ReportInbox.tsx b/products/mobile/src/features/inbox/ReportInbox.tsx
index 874f4e9e7d95..60b35db3b851 100644
--- a/products/mobile/src/features/inbox/ReportInbox.tsx
+++ b/products/mobile/src/features/inbox/ReportInbox.tsx
@@ -30,7 +30,7 @@ export function ReportInbox({ selectedReportId, active }: { selectedReportId: st
const now = useNow()
const filters = useInboxFilters()
const query = useInboxItems({ filters, refreshWhileVisible: active })
- const prefetch = usePrefetchReports(active ? query.data : undefined)
+ const prefetch = usePrefetchReports(query.data, active)
const setRead = useSetReportRead()
const filterActions = inboxFilterActions(filters)
const [filtersOpen, setFiltersOpen] = useState(false)
diff --git a/products/mobile/src/features/inbox/usePrefetchReports.test.tsx b/products/mobile/src/features/inbox/usePrefetchReports.test.tsx
index 80c5ec7edc28..fcdabd30ba0b 100644
--- a/products/mobile/src/features/inbox/usePrefetchReports.test.tsx
+++ b/products/mobile/src/features/inbox/usePrefetchReports.test.tsx
@@ -1,6 +1,6 @@
-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 { getNetworkStateAsync, NetworkStateType } from 'expo-network'
import type { ReactElement, ReactNode } from 'react'
import { AppState, type ViewToken } from 'react-native'
import { setAuthProvider } from '@/api/client'
@@ -68,18 +68,15 @@ describe('usePrefetchReports', () => {
refreshAccessToken: async () => null,
})
AppState.currentState = 'active'
- useConnectivity.setState({ status: 'connected', isConnectionExpensive: false })
- jest.mocked(NetInfo.refresh).mockResolvedValue({
- isConnected: true,
- details: { isConnectionExpensive: false },
- } as NetInfoState)
+ useConnectivity.setState({ status: 'connected', type: NetworkStateType.WIFI })
+ jest.mocked(getNetworkStateAsync).mockResolvedValue({ type: NetworkStateType.WIFI, isConnected: true })
})
afterEach(() => {
setAuthProvider(null)
jest.restoreAllMocks()
})
- test.each(['focus', 'offline', 'unknown', 'expensive', 'project', 'background', 'unmount'] as const)(
+ test.each(['focus', 'offline', 'unknown', 'cellular', 'project', 'background', 'unmount'] as const)(
'%s pauses pending work and cancels only speculative reads',
async (pause) => {
const appListeners = new Set<(state: 'active' | 'background') => void>()
@@ -108,7 +105,7 @@ describe('usePrefetchReports', () => {
else if (pause === 'project') {
mockScope = { ...mockScope, projectId: 3 }
screen.rerender({ focused: true })
- } else if (pause === 'expensive') useConnectivity.setState({ isConnectionExpensive: true })
+ } else if (pause === 'cellular') useConnectivity.setState({ type: NetworkStateType.CELLULAR })
else if (pause === 'background') for (const listener of appListeners) listener('background')
else screen.unmount()
})
@@ -120,7 +117,7 @@ describe('usePrefetchReports', () => {
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 if (pause === 'cellular') useConnectivity.setState({ type: NetworkStateType.WIFI })
else for (const listener of appListeners) listener('active')
})
await waitFor(() => expect(requests.pending).toHaveLength(2))
diff --git a/products/mobile/src/features/inbox/usePrefetchReports.ts b/products/mobile/src/features/inbox/usePrefetchReports.ts
index 176d36ec8aa9..84fc2e88fd3f 100644
--- a/products/mobile/src/features/inbox/usePrefetchReports.ts
+++ b/products/mobile/src/features/inbox/usePrefetchReports.ts
@@ -6,6 +6,7 @@ import {
useIsFetching,
useQueryClient,
} from '@tanstack/react-query'
+import { NetworkStateType } from 'expo-network'
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import type { ViewabilityConfig, ViewToken } from 'react-native'
@@ -95,7 +96,11 @@ export function usePrefetchReports(items: InboxItem[] | undefined, focused: bool
const accountRef = useRef(account)
accountRef.current = account
const active = useAppActive()
- const connected = useConnectivity((state) => state.status === 'connected' && state.isConnectionExpensive === false)
+ const connected = useConnectivity(
+ (state) =>
+ state.status === 'connected' &&
+ (state.type === NetworkStateType.WIFI || state.type === NetworkStateType.ETHERNET)
+ )
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]) : ''
diff --git a/products/mobile/src/features/status/usePostHogStatus.test.tsx b/products/mobile/src/features/status/usePostHogStatus.test.tsx
new file mode 100644
index 000000000000..223af30addda
--- /dev/null
+++ b/products/mobile/src/features/status/usePostHogStatus.test.tsx
@@ -0,0 +1,103 @@
+import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
+import { act, renderHook, waitFor } from '@testing-library/react-native'
+import type { PropsWithChildren, ReactElement } from 'react'
+
+import { useDataMode } from '@/demo/demoMode'
+
+import { regionalStatus, usePostHogStatus } from './usePostHogStatus'
+
+jest.mock('@/demo/demoMode', () => ({ useDataMode: jest.fn(() => 'live') }))
+
+const euAI = { current_status: 'degraded_performance' as const, name: 'PostHog AI', group_name: 'EU Cloud 🇪🇺' }
+const usAPI = { current_status: 'degraded_performance' as const, name: 'API', group_name: 'US Cloud 🇺🇸' }
+const incident = {
+ current_worst_impact: 'degraded_performance' as const,
+ status: 'investigating' as const,
+ id: 'incident-123',
+ name: 'Elevated error rate',
+ affected_components: [euAI, usAPI],
+}
+const summary = { ongoing_incidents: [incident], in_progress_maintenances: [] }
+
+test('shows a cross-region incident in both menus but only in the affected AI chat', () => {
+ expect(regionalStatus(summary, 'us')).toEqual({
+ pageUrl: 'https://www.posthogstatus.com/us',
+ indicatorColor: 'yellow',
+ summary: `Degraded performance · ${incident.name}`,
+ })
+ expect(regionalStatus(summary, 'eu').aiIncident).toEqual({
+ title: incident.name,
+ color: 'yellow',
+ status: incident.status,
+ url: 'https://www.posthogstatus.com/incidents/incident-123',
+ })
+})
+
+test('global incidents and maintenance appear in the menu without implying AI is affected', () => {
+ const global = { ...incident, affected_components: [] }
+ const maintenance = { name: 'Database maintenance', affected_components: [euAI] }
+ const events = { ongoing_incidents: [global], in_progress_maintenances: [maintenance] }
+ expect(regionalStatus(events, 'us').summary).toBe(`Degraded performance · ${global.name}`)
+ expect(regionalStatus(events, 'eu').aiIncident).toBeUndefined()
+ const resolved = { ...events, ongoing_incidents: [] }
+ expect(regionalStatus(resolved, 'us').indicatorColor).toBe('diffGreen')
+ expect(regionalStatus(resolved, 'eu').indicatorColor).toBe('yellow')
+ expect(regionalStatus(resolved, 'us').summary).toBeUndefined()
+ expect(regionalStatus(resolved, 'eu').summary).toBe(`Maintenance in progress · ${maintenance.name}`)
+ expect(regionalStatus(resolved, 'eu').aiIncident).toBeUndefined()
+})
+
+test('clears a resolved AI incident and skips status requests in demo and self-hosted sessions', async () => {
+ const client = new QueryClient({ defaultOptions: { queries: { retry: false } } })
+ const fetchStatus = jest.spyOn(global, 'fetch').mockResolvedValue(Response.json(summary))
+ function wrapper({ children }: PropsWithChildren): ReactElement {
+ return <QueryClientProvider client={client}>{children}</QueryClientProvider>
+ }
+ const hook = renderHook((host: string) => usePostHogStatus(host), {
+ initialProps: 'https://eu.posthog.com',
+ wrapper,
+ })
+ try {
+ await waitFor(() => expect(hook.result.current.aiIncident?.title).toBe(incident.name))
+ fetchStatus.mockResolvedValue(Response.json({ ongoing_incidents: [], in_progress_maintenances: [] }))
+ await act(() => client.invalidateQueries({ queryKey: ['posthog-status'] }))
+ await waitFor(() => expect(hook.result.current.aiIncident).toBeUndefined())
+ fetchStatus.mockClear()
+ hook.rerender('https://self-hosted.example.com')
+ expect(hook.result.current).toEqual({ pageUrl: 'https://www.posthogstatus.com' })
+ jest.mocked(useDataMode).mockReturnValue('demo')
+ hook.rerender('https://eu.posthog.com')
+ expect(hook.result.current).toEqual({ pageUrl: 'https://www.posthogstatus.com' })
+ expect(fetchStatus).not.toHaveBeenCalled()
+ } finally {
+ hook.unmount()
+ client.clear()
+ fetchStatus.mockRestore()
+ jest.mocked(useDataMode).mockReturnValue('live')
+ }
+})
+
+test('ranks the regional outage separately from the AI component and updates as incidents change', () => {
+ const partial = {
+ ...incident,
+ id: 'partial',
+ name: 'AI requests failing',
+ current_worst_impact: 'partial_outage' as const,
+ affected_components: [{ ...euAI, current_status: 'partial_outage' as const }],
+ }
+ const major = { ...incident, id: 'major', name: 'API unavailable', current_worst_impact: 'full_outage' as const }
+ const majorStatus = regionalStatus({ ...summary, ongoing_incidents: [major] }, 'eu')
+ expect(majorStatus.indicatorColor).toBe('diffRed')
+ expect(majorStatus.aiIncident?.color).toBe('yellow')
+ const events = { ...summary, ongoing_incidents: [incident, partial, major] }
+ expect(regionalStatus(events, 'eu').summary).toBe('Major outage (3 incidents) · API unavailable')
+ expect(regionalStatus(events, 'eu').indicatorColor).toBe('diffRed')
+ expect(regionalStatus(events, 'eu').aiIncident?.color).toBe('diffRed')
+ expect(regionalStatus(events, 'eu').aiIncident?.title).toBe(partial.name)
+ const monitoring = { ...partial, status: 'monitoring' as const }
+ const remaining = { ...summary, ongoing_incidents: [monitoring] }
+ expect(regionalStatus(remaining, 'eu').indicatorColor).toBe('diffRed')
+ expect(regionalStatus(remaining, 'eu').summary).toBe('Partial outage · AI requests failing')
+ expect(regionalStatus(remaining, 'eu').aiIncident?.status).toBe('monitoring')
+ expect(regionalStatus(remaining, 'us').summary).toBeUndefined()
+})
diff --git a/products/mobile/src/features/status/usePostHogStatus.ts b/products/mobile/src/features/status/usePostHogStatus.ts
new file mode 100644
index 000000000000..b016b03c260c
--- /dev/null
+++ b/products/mobile/src/features/status/usePostHogStatus.ts
@@ -0,0 +1,106 @@
+import { useQuery } from '@tanstack/react-query'
+
+import { type RegionId, regionForHost } from '@/auth/regions'
+import { useDataMode } from '@/demo/demoMode'
+
+const STATUS_PAGE = 'https://www.posthogstatus.com'
+const FIVE_MINUTES = 5 * 60_000
+
+// incident.io uses full_outage for the state the web app calls a major outage.
+const impactLabels = {
+ degraded_performance: 'Degraded performance',
+ partial_outage: 'Partial outage',
+ full_outage: 'Major outage',
+} as const
+type Impact = keyof typeof impactLabels
+type IncidentPhase = 'investigating' | 'identified' | 'monitoring'
+const impactRank: Record<Impact | 'operational', number> = {
+ operational: 0,
+ degraded_performance: 1,
+ partial_outage: 2,
+ full_outage: 3,
+}
+
+interface Component {
+ current_status: Impact | 'operational'
+ group_name?: string
+ name: string
+}
+
+interface StatusEvent {
+ name: string
+ affected_components: Component[]
+}
+
+interface Summary {
+ ongoing_incidents: (StatusEvent & {
+ id: string
+ current_worst_impact: Impact
+ status: IncidentPhase
+ })[]
+ in_progress_maintenances: StatusEvent[]
+}
+
+function incidentColor(impact: Component['current_status']): 'yellow' | 'diffRed' {
+ return impact === 'partial_outage' || impact === 'full_outage' ? 'diffRed' : 'yellow'
+}
+
+export interface PostHogStatus {
+ indicatorColor?: 'diffGreen' | ReturnType<typeof incidentColor>
+ pageUrl: string
+ summary?: string
+ aiIncident?: { title: string; url: string; status: IncidentPhase; color: ReturnType<typeof incidentColor> }
+}
+
+export function regionalStatus(summary: Summary, region: 'us' | 'eu'): PostHogStatus {
+ const group = region === 'us' ? 'US Cloud' : 'EU Cloud'
+ const inRegion = (component: Component): boolean =>
+ component.group_name?.replace(/[^\p{L}\p{N}\s]/gu, '').trim() === group
+ const relevant = (event: StatusEvent): boolean =>
+ event.affected_components.length === 0 || event.affected_components.some(inRegion)
+ const incidents = summary.ongoing_incidents
+ .filter(relevant)
+ .sort((a, b) => impactRank[b.current_worst_impact] - impactRank[a.current_worst_impact])
+ const incident = incidents[0]
+ const maintenance = summary.in_progress_maintenances.find(relevant)
+ const [ai] = incidents
+ .flatMap((event) => {
+ const component = event.affected_components.find((item) => item.name === 'PostHog AI' && inRegion(item))
+ return component ? [{ event, impact: component.current_status }] : []
+ })
+ .sort((a, b) => impactRank[b.impact] - impactRank[a.impact])
+ const impact = incident && impactLabels[incident.current_worst_impact]
+ const count = incidents.length > 1 ? ` (${incidents.length} incidents)` : ''
+ return {
+ pageUrl: `${STATUS_PAGE}/${region}`,
+ indicatorColor: incident ? incidentColor(incident.current_worst_impact) : maintenance ? 'yellow' : 'diffGreen',
+ summary: incident
+ ? `${impact ?? 'Incident'}${count} · ${incident.name}`
+ : maintenance && `Maintenance in progress · ${maintenance.name}`,
+ aiIncident: ai && {
+ title: ai.event.name,
+ color: incidentColor(ai.impact),
+ status: ai.event.status,
+ url: `${STATUS_PAGE}/incidents/${encodeURIComponent(ai.event.id)}`,
+ },
+ }
+}
+
+export function usePostHogStatus(host: string | undefined): PostHogStatus {
+ const mode = useDataMode()
+ const region: RegionId = mode === 'live' && host ? regionForHost(host) : 'custom'
+ const { data } = useQuery({
+ queryKey: ['posthog-status', region],
+ enabled: region !== 'custom',
+ queryFn: async ({ signal }): Promise<PostHogStatus> => {
+ if (region === 'custom') return { pageUrl: STATUS_PAGE }
+ const response = await fetch(`${STATUS_PAGE}/api/v1/summary`, { signal, credentials: 'omit' })
+ if (!response.ok) throw new Error(`Status page returned ${response.status}`)
+ return regionalStatus(await response.json(), region)
+ },
+ staleTime: FIVE_MINUTES,
+ refetchInterval: FIVE_MINUTES,
+ refetchOnWindowFocus: true,
+ })
+ return data ?? { pageUrl: region === 'custom' ? STATUS_PAGE : `${STATUS_PAGE}/${region}` }
+}
diff --git a/products/mobile/src/features/tabs/NavMenu.tsx b/products/mobile/src/features/tabs/NavMenu.tsx
index 2cfd5fbbb9d0..c747f3b2ba4f 100644
--- a/products/mobile/src/features/tabs/NavMenu.tsx
+++ b/products/mobile/src/features/tabs/NavMenu.tsx
@@ -2,10 +2,12 @@ import { type ComponentType, type ReactElement, useEffect, useState } from 'reac
import { Text, View } from 'react-native'
import { useAuthStore } from '@/auth/authStore'
import { ProjectSheet } from '@/features/projects/ProjectSheet'
+import type { PostHogStatus } from '@/features/status/usePostHogStatus'
import { track } from '@/lib/analytics'
import { FloatingCard } from '@/ui/FloatingCard'
import { ChevronUpDownIcon } from '@/ui/icons/ChevronUpDownIcon'
import { ExternalLinkIcon } from '@/ui/icons/ExternalLinkIcon'
+import { GlobeIcon } from '@/ui/icons/GlobeIcon'
import { GripIcon } from '@/ui/icons/GripIcon'
import { PinIcon } from '@/ui/icons/PinIcon'
import { SettingsIcon } from '@/ui/icons/SettingsIcon'
@@ -28,6 +30,8 @@ interface NavMenuProps {
/** A pinned list's rows, at the top while its tab is focused. Null leaves the section out. */
navList: { onUnpin: () => void; onOpenWeb: (() => void) | null } | null
onClose: () => void
+ status: PostHogStatus
+ onOpenStatus: () => void
onSettings: () => void
onSignOut: () => void
/** Replaces the rows with the sign-out confirmation. */
@@ -72,6 +76,8 @@ export function NavMenu({
navList,
onClose,
onSettings,
+ status: { summary: statusUpdate, indicatorColor },
+ onOpenStatus,
onSignOut,
confirmingSignOut,
signOutPending,
@@ -143,6 +149,38 @@ export function NavMenu({
/>
) : (
<>
+ <Pressable44
+ accessibilityRole="link"
+ accessibilityLabel={
+ statusUpdate
+ ? `PostHog status: ${statusUpdate}`
+ : indicatorColor
+ ? 'PostHog status: All systems operational'
+ : 'PostHog status'
+ }
+ pressedBackground={colors.sunken}
+ style={styles.row}
+ onPress={onOpenStatus}
+ testID="nav-status"
+ >
+ {indicatorColor ? (
+ <View style={styles.statusIcon}>
+ <View style={[styles.statusDot, { backgroundColor: colors[indicatorColor] }]} />
+ </View>
+ ) : (
+ <GlobeIcon size={iconSizes.control} />
+ )}
+ <View style={styles.statusBody}>
+ <Text style={styles.statusTitle}>PostHog status</Text>
+ {statusUpdate ? (
+ <Text style={styles.statusSummary} numberOfLines={2}>
+ {statusUpdate}
+ </Text>
+ ) : null}
+ </View>
+ <ExternalLinkIcon size={iconSizes.small} color={colors.tertiary} />
+ </Pressable44>
+ <View style={[styles.divider, styles.sectionDivider]} />
{navList ? (
<>
<MenuRow
@@ -225,6 +263,11 @@ const useStyles = createStyles(({ colors }) => ({
paddingHorizontal: 14,
borderRadius: radii.menuRow,
},
+ statusIcon: { width: iconSizes.control, alignItems: 'center' },
+ statusDot: { width: 10, height: 10, borderRadius: 5 },
+ statusBody: { flex: 1 },
+ statusTitle: { ...type.menuRow, color: colors.ink },
+ statusSummary: { ...type.meta, color: colors.muted },
rowLabel: {
...type.menuRow,
color: colors.ink,
diff --git a/products/mobile/src/features/tabs/TabsHeader.tsx b/products/mobile/src/features/tabs/TabsHeader.tsx
index c8a248580a09..97dc4341c662 100644
--- a/products/mobile/src/features/tabs/TabsHeader.tsx
+++ b/products/mobile/src/features/tabs/TabsHeader.tsx
@@ -1,6 +1,6 @@
import type { ReactElement } from 'react'
import { Text, View } from 'react-native'
-
+import type { PostHogStatus } from '@/features/status/usePostHogStatus'
import { INBOX_PANE_WIDTH } from '@/ui/adaptiveLayout'
import { BlurEdge } from '@/ui/BlurEdge'
import { FadeEdge } from '@/ui/FadeEdge'
@@ -48,6 +48,7 @@ interface TabsHeaderProps {
tab: TabKey
/** Null until the tab's screen publishes its header state. */
slot: TabHeaderSlot | null
+ status: PostHogStatus
onMore: () => void
}
@@ -56,7 +57,12 @@ interface TabsHeaderProps {
* keep their place and their state across a tab switch. The status line is absolutely positioned, so it never moves
* the title row, and the refresh hint takes its place while it shows, so every tab's content starts at the same offset.
*/
-export function TabsHeader({ tab, slot, onMore }: TabsHeaderProps): ReactElement {
+export function TabsHeader({
+ tab,
+ slot,
+ status: { summary: statusUpdate, indicatorColor },
+ onMore,
+}: TabsHeaderProps): ReactElement {
const colors = useColors()
const styles = useStyles()
const insets = useScreenInsets()
@@ -133,11 +139,19 @@ export function TabsHeader({ tab, slot, onMore }: TabsHeaderProps): ReactElement
<Pressable44
onPress={onMore}
accessibilityLabel="More"
+ accessibilityValue={
+ statusUpdate ? { text: `PostHog status update: ${statusUpdate}` } : undefined
+ }
pressedBackground={colors.background}
style={styles.button}
testID="tabs-more"
>
- <MoreIcon size={22} />
+ <View>
+ <MoreIcon size={22} />
+ {statusUpdate && indicatorColor ? (
+ <View style={[styles.filterDot, { backgroundColor: colors[indicatorColor] }]} />
+ ) : null}
+ </View>
</Pressable44>
</PillControl>
)}
diff --git a/products/mobile/src/features/tabs/TabsLayout.test.tsx b/products/mobile/src/features/tabs/TabsLayout.test.tsx
index 41bc2e8832bd..ea545e3585b6 100644
--- a/products/mobile/src/features/tabs/TabsLayout.test.tsx
+++ b/products/mobile/src/features/tabs/TabsLayout.test.tsx
@@ -20,6 +20,18 @@ jest.mock('react-native-reanimated/mock', () => ({
jest.mock('@react-native-async-storage/async-storage', () =>
require('@react-native-async-storage/async-storage/jest/async-storage-mock')
)
+jest.mock('@/features/status/usePostHogStatus', () => ({
+ usePostHogStatus: () => ({
+ pageUrl: 'https://www.posthogstatus.com/eu',
+ summary: 'Elevated latency',
+ indicatorColor: 'yellow',
+ aiIncident: {
+ status: 'monitoring',
+ title: 'Elevated latency',
+ url: 'https://www.posthogstatus.com/incidents/example',
+ },
+ }),
+}))
jest.mock('@/auth/useProjectScope', () => ({ useProjectScope: () => null }))
function InboxStub(): ReactElement {
@@ -107,6 +119,23 @@ describe('TabsLayout', () => {
setFeatureFlags({})
})
+ test('exposes the regional status update from the main menu', () => {
+ renderRouter(
+ {
+ '(tabs)/_layout': TabsLayout,
+ '(tabs)/inbox': InboxStub,
+ '(tabs)/chats': ChatsStub,
+ '(tabs)/views': ViewsStub,
+ ...LIST_TABS,
+ },
+ { initialUrl: '/inbox' }
+ )
+ const more = screen.getByTestId('tabs-more')
+ expect(more.props.accessibilityValue.text).toContain('Elevated latency')
+ fireEvent.press(more)
+ expect(screen.getByLabelText('PostHog status: Elevated latency')).toBeTruthy()
+ })
+
test.each(['inbox', 'chats', 'views'] as const)(
'uses the %s logo as the refresh indicator only while the focused page refreshes',
(tab) => {
diff --git a/products/mobile/src/features/tabs/TabsLayout.tsx b/products/mobile/src/features/tabs/TabsLayout.tsx
index 6368aed7086e..cbf8de12cb09 100644
--- a/products/mobile/src/features/tabs/TabsLayout.tsx
+++ b/products/mobile/src/features/tabs/TabsLayout.tsx
@@ -6,6 +6,7 @@ import { useAuthStore } from '@/auth/authStore'
import { useProjectScope } from '@/auth/useProjectScope'
import { useViewer } from '@/auth/useViewer'
import type { ChatSheetEntry } from '@/features/chat/chatSheetEvents'
+import { usePostHogStatus } from '@/features/status/usePostHogStatus'
import { useViewsOpenedEvent } from '@/features/views/list/useViewsOpenedEvent'
import { useToasts, ViewsToast } from '@/features/views/ViewsToast'
import { navListWebUrl } from '@/features/views/webLinks'
@@ -104,6 +105,7 @@ function TabsChrome(): ReactElement {
const [menuOpen, setMenuOpen] = useState(false)
const [confirmingSignOut, setConfirmingSignOut] = useState(false)
const scope = useProjectScope()
+ const status = usePostHogStatus(scope?.host)
// The pinned list's tab has no menu of its own, so its Unpin toast draws from here, inside the tabs' overlay host.
const toasts = useToasts()
@@ -145,10 +147,15 @@ function TabsChrome(): ReactElement {
return (
<>
- <TabsHeader tab={tab} slot={slot} onMore={() => setMenuOpen(true)} />
+ <TabsHeader tab={tab} slot={slot} status={status} onMore={() => setMenuOpen(true)} />
<NavMenu
visible={menuOpen}
projectName={viewer.projectName}
+ status={status}
+ onOpenStatus={() => {
+ closeMenu()
+ Linking.openURL(status.pageUrl).catch(() => toasts.show("Couldn't open PostHog status."))
+ }}
navList={navList}
editPins={
editPins && {
diff --git a/products/mobile/src/lib/connectivity.test.ts b/products/mobile/src/lib/connectivity.test.ts
index 56d3909c70ce..7914085902cc 100644
--- a/products/mobile/src/lib/connectivity.test.ts
+++ b/products/mobile/src/lib/connectivity.test.ts
@@ -20,7 +20,7 @@ describe('connectivity', () => {
beforeEach(() => {
jest.useFakeTimers()
AppState.currentState = 'active'
- useConnectivity.setState({ status: 'unknown' })
+ useConnectivity.setState({ status: 'unknown', type: NetworkStateType.UNKNOWN })
unsubscribe = jest.fn()
remove = jest.fn()
jest.mocked(addNetworkStateListener).mockImplementation((listener) => {
@@ -62,7 +62,9 @@ describe('connectivity', () => {
expect(useConnectivity.getState().status).toBe('unknown')
update(state(true))
await jest.advanceTimersByTimeAsync(0)
- expect(useConnectivity.getState()).toEqual({ status: 'connected' })
+ expect(useConnectivity.getState()).toEqual({ status: 'connected', type: NetworkStateType.WIFI })
+ update({ type: NetworkStateType.CELLULAR, isConnected: true })
+ expect(useConnectivity.getState()).toEqual({ status: 'connected', type: NetworkStateType.CELLULAR })
stop()
client.unmount()
client.clear()
diff --git a/products/mobile/src/lib/connectivity.ts b/products/mobile/src/lib/connectivity.ts
index e396ad094302..13450ce894f8 100644
--- a/products/mobile/src/lib/connectivity.ts
+++ b/products/mobile/src/lib/connectivity.ts
@@ -4,9 +4,10 @@ import { create } from 'zustand'
export interface Connectivity {
status: 'unknown' | 'connected' | 'offline'
+ type: NetworkStateType
}
-export const useConnectivity = create<Connectivity>(() => ({ status: 'unknown' }))
+export const useConnectivity = create<Connectivity>(() => ({ status: 'unknown', type: NetworkStateType.UNKNOWN }))
export class OfflineError extends Error {
constructor() {
@@ -46,7 +47,9 @@ export function monitorConnectivity(setOnline: (online: boolean) => void): () =>
: state.isConnected === false && state.type !== NetworkStateType.UNKNOWN
? 'offline'
: 'unknown'
- if (status !== useConnectivity.getState().status) useConnectivity.setState({ status })
+ const type = state.type ?? NetworkStateType.UNKNOWN
+ if (status !== useConnectivity.getState().status || type !== useConnectivity.getState().type)
+ useConnectivity.setState({ status, type })
setOnline(status !== 'offline')
}
const refresh = (): void => {