Skip to content

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

fix(mobile): keep chat available during connectivity checks (#130886)

Chris Volzer2e8ca9ae8e39
diff --git a/products/mobile/docs/CHAT.md b/products/mobile/docs/CHAT.md
index 072b7a9158ce..b305cf0ff690 100644
--- a/products/mobile/docs/CHAT.md
+++ b/products/mobile/docs/CHAT.md
@@ -70,11 +70,11 @@ Every request carries `X-PostHog-Client-Platform: mobile`, so `run/` never reuse
## AI consent
-The same approval rules cover Chat, Create PR/task handoff, and replay summarization. The chat composer and decision panel remain hidden until approval is known.
+The same approval rules cover Chat, Create PR/task handoff, and replay summarization. Pending access checks keep the chat composer available without a loading indicator. Known organization restrictions and personal consent still gate the composer; every AI action checks current approval before sending.
- **Organization approval.** The selected project's organization must have `is_ai_data_processing_approved: true`. The app reads the requesting user's `membership_level` from `OrganizationSerializer` in `/api/users/@me/` and `/api/organizations/{id}/`: 8 is an administrator and 15 is an owner. Only those confirmed roles see Open settings; other members and unknown roles see instructions to ask an admin or owner. The settings link opens the organization's existing web approval control; mobile never changes that setting itself.
- **Personal consent.** The shared sheet explains that messages, reports, attached files and photos, selected recordings, and project data used by the agent can go to PostHog AI and third-party model providers. It links to the privacy policy. Continue records the disclosure on this device for this host and user; Not now sends nothing. The broader disclosure invalidates consent saved by older versions of the chat-only sheet. Sign-out and session expiry clear consent.
-- **Fresh checks.** Every submitted message (including queue delivery), handoff, decision answer, and replay summary first reads the organization's current approval. The chat also rechecks on foreground before showing role-specific controls. Unknown approval, a failed read, and removed project access stop the action. Changing host, user, project or session, or leaving the originating screen while the sheet is open, cancels its pending action.
+- **Fresh checks.** Every submitted message (including queue delivery), handoff, decision answer, and replay summary first reads the organization's current approval. The chat also rechecks on foreground without replacing the composer during the read. Unknown approval, a failed read, and removed project access stop the action. Changing host, user, project or session, or leaving the originating screen while the sheet is open, cancels its pending action.
- Demo mode skips approval and sends no live requests.
These client checks supplement existing server scopes, resource RBAC and product checks. They do not grant an organization role or replace server authorization. Revocation after a check must still be enforced by the backend; mobile cannot stop an agent that is already running on the server.
@@ -430,7 +430,7 @@ New chat drops it.
- Assistant text renders as markdown with `react-native-markdown-display`, styled from `src/ui/tokens.ts`.
`html: false`; images are dropped. Relative links open on the signed-in host; only http(s) links open.
-- The status line shows the current stage or tool, "Thinking…", or "Reconnecting…".
+- The status line shows the current stage or tool, or "Thinking…". Automatic reconnection stays quiet; confirmed failures still show recovery controls.
- Compacting and clearing each show one active spinner, even when the stream repeats the start.
Completion removes that spinner, so a later compaction or clear can show a new one.
- Thoughts and tool calls fold into activity rows. Every row starts closed, also while it runs. `mobile_chat_activity_expanded` is captured with `running` and `tool_count` when the person opens one.
diff --git a/products/mobile/src/features/chat/ChatAccessGate.test.tsx b/products/mobile/src/features/chat/ChatAccessGate.test.tsx
index 23ffe6458274..5200f212ae41 100644
--- a/products/mobile/src/features/chat/ChatAccessGate.test.tsx
+++ b/products/mobile/src/features/chat/ChatAccessGate.test.tsx
@@ -1,5 +1,6 @@
import { act, fireEvent, render, screen } from '@testing-library/react-native'
-import { Linking, Text } from 'react-native'
+import { type ReactElement, useState } from 'react'
+import { ActivityIndicator, AppState, Linking, TextInput } from 'react-native'
import { fetchOrganization } from '@/api/users'
import { useAuthStore } from '@/auth/authStore'
@@ -43,10 +44,15 @@ function signIn(approved: boolean, membershipLevel: number | null = 8): void {
})
}
+function DraftComposer(): ReactElement {
+ const [text, setText] = useState('')
+ return <TextInput testID="composer" value={text} onChangeText={setText} />
+}
+
async function renderGate(onDecline: () => void = jest.fn()): Promise<void> {
render(
<ChatAccessGate onDecline={onDecline}>
- <Text testID="composer">Composer</Text>
+ <DraftComposer />
</ChatAccessGate>,
{ wrapper: OverlayHost }
)
@@ -66,6 +72,57 @@ afterEach(() => {
})
describe('ChatAccessGate', () => {
+ test.each([true, false])('keeps a draft editable during an access check (cached approval: %s)', async (cached) => {
+ signIn(true)
+ useAiConsentStore.getState().accept(aiConsentKey(HOST, USER_UUID))
+ if (!cached) useAuthStore.setState({ organizations: [] })
+ let finish!: (value: Awaited<ReturnType<typeof fetchOrganization>>) => void
+ jest.mocked(fetchOrganization).mockImplementation(
+ () =>
+ new Promise((resolve) => {
+ finish = resolve
+ })
+ )
+ await renderGate()
+ fireEvent.changeText(screen.getByTestId('composer'), 'Keep this question')
+ expect(screen.UNSAFE_queryByType(ActivityIndicator)).toBeNull()
+ await act(async () =>
+ finish({
+ id: 'org-1',
+ name: 'Hedgebox',
+ teams: [{ id: 7, name: 'Hedgebox' }],
+ is_ai_data_processing_approved: true,
+ membership_level: 8,
+ })
+ )
+ expect(screen.getByDisplayValue('Keep this question')).toBeTruthy()
+ })
+
+ test('keeps the composer mounted during a foreground recheck and shows a confirmed failure', async () => {
+ let foreground!: (state: 'active') => void
+ jest.spyOn(AppState, 'addEventListener').mockImplementation((_event, listener) => {
+ foreground = listener
+ return { remove: jest.fn() }
+ })
+ signIn(true)
+ useAiConsentStore.getState().accept(aiConsentKey(HOST, USER_UUID))
+ await renderGate()
+ fireEvent.changeText(screen.getByTestId('composer'), 'Unsent question')
+ let fail!: (error: Error) => void
+ jest.mocked(fetchOrganization).mockImplementation(
+ () =>
+ new Promise((_resolve, reject) => {
+ fail = reject
+ })
+ )
+ await act(async () => foreground('active'))
+ expect(screen.getByDisplayValue('Unsent question')).toBeTruthy()
+ expect(screen.UNSAFE_queryByType(ActivityIndicator)).toBeNull()
+ await act(async () => fail(new TypeError('Network request failed')))
+ expect(screen.getByTestId('chat-ai-org-notice')).toBeTruthy()
+ jest.restoreAllMocks()
+ })
+
test.each<[string, { approved: boolean; consented: boolean; demo: boolean }, string, string[]]>([
[
'an organization that has not approved AI shows the notice instead of the composer',
diff --git a/products/mobile/src/features/chat/ChatAccessGate.tsx b/products/mobile/src/features/chat/ChatAccessGate.tsx
index d29d28a5083f..7b90609aa99b 100644
--- a/products/mobile/src/features/chat/ChatAccessGate.tsx
+++ b/products/mobile/src/features/chat/ChatAccessGate.tsx
@@ -1,8 +1,7 @@
import { type ReactElement, type ReactNode, useEffect, useState } from 'react'
-import { ActivityIndicator, Linking, StyleSheet, View } from 'react-native'
+import { Linking } from 'react-native'
import { track } from '@/lib/analytics'
-import { useColors } from '@/ui/theme'
import { AiConsentSheet } from './AiConsentSheet'
import { AiOrgNotice } from './AiOrgNotice'
import { PRIVACY_POLICY_URL } from './aiAccess'
@@ -15,9 +14,7 @@ interface ChatAccessGateProps {
children: ReactNode
}
-/** Shows `children` only once the organization allows PostHog AI and the person agreed on this device. */
export function ChatAccessGate({ onDecline, children }: ChatAccessGateProps): ReactElement {
- const colors = useColors()
const { access, rechecking, accept, checkAgain } = useChatAccess()
const [declined, setDeclined] = useState(false)
const kind = access.kind
@@ -43,13 +40,6 @@ export function ChatAccessGate({ onDecline, children }: ChatAccessGateProps): Re
onDecline()
}
- if (access.kind === 'checking') {
- return (
- <View style={styles.checking} accessibilityLabel="Checking PostHog AI access" testID="chat-access-checking">
- <ActivityIndicator color={colors.ink} />
- </View>
- )
- }
if (access.kind === 'org_blocked' || access.kind === 'org_unknown') {
const settingsUrl = access.kind === 'org_blocked' ? access.settingsUrl : null
return (
@@ -72,7 +62,7 @@ export function ChatAccessGate({ onDecline, children }: ChatAccessGateProps): Re
}
return (
<>
- {access.kind === 'ready' ? children : null}
+ {access.kind === 'ready' || access.kind === 'checking' ? children : null}
{/* The sheet stays mounted after Continue, so it slides out while the composer appears. */}
<AiConsentSheet
visible={access.kind === 'needs_consent' && !declined}
@@ -85,11 +75,3 @@ export function ChatAccessGate({ onDecline, children }: ChatAccessGateProps): Re
</>
)
}
-
-const styles = StyleSheet.create({
- checking: {
- height: 64,
- alignItems: 'center',
- justifyContent: 'center',
- },
-})
diff --git a/products/mobile/src/features/chat/classic/ClassicChatScreen.test.tsx b/products/mobile/src/features/chat/classic/ClassicChatScreen.test.tsx
index eee5642ac04d..8789ed7ec1ba 100644
--- a/products/mobile/src/features/chat/classic/ClassicChatScreen.test.tsx
+++ b/products/mobile/src/features/chat/classic/ClassicChatScreen.test.tsx
@@ -81,7 +81,12 @@ describe('classic chat draft recovery', () => {
} else {
expect(screen.getByText('Received reply')).toBeTruthy()
expect(screen.queryByText("Couldn't load this session")).toBeNull()
- fireEvent.press(screen.getByLabelText('Reconnect'))
+ if (kind === 'reloading') {
+ expect(screen.queryByLabelText('Reconnect')).toBeNull()
+ expect(screen.queryByText('Reconnecting…')).toBeNull()
+ } else {
+ fireEvent.press(screen.getByLabelText('Reconnect'))
+ }
}
expect(reload).toHaveBeenCalledTimes(kind === 'reloading' ? 0 : 1)
}
diff --git a/products/mobile/src/features/chat/classic/ClassicChatScreen.tsx b/products/mobile/src/features/chat/classic/ClassicChatScreen.tsx
index 152c0cf85242..da5369c31157 100644
--- a/products/mobile/src/features/chat/classic/ClassicChatScreen.tsx
+++ b/products/mobile/src/features/chat/classic/ClassicChatScreen.tsx
@@ -174,10 +174,10 @@ export function ClassicChatScreen({
topInset={insets.top + CHAT_HEADER_HEIGHT}
/>
)}
- {items.length > 0 && (chat.historyError || chat.loading) ? (
+ {items.length > 0 && chat.historyError ? (
<View style={styles.recovery}>
<ChatErrorNotice
- message={chat.historyError ?? 'Reconnecting…'}
+ message={chat.historyError}
actions={
<Pressable44
disabled={chat.loading || chat.working}
diff --git a/products/mobile/src/features/chat/session/SessionThread.test.tsx b/products/mobile/src/features/chat/session/SessionThread.test.tsx
index 4b8a2e2a04dd..2cc4302fb78b 100644
--- a/products/mobile/src/features/chat/session/SessionThread.test.tsx
+++ b/products/mobile/src/features/chat/session/SessionThread.test.tsx
@@ -1,5 +1,5 @@
import { fireEvent, render, screen } from '@testing-library/react-native'
-import { ScrollView } from 'react-native'
+import { ActivityIndicator, ScrollView } from 'react-native'
import { SessionThread } from './SessionThread'
import type { Session, SessionThreadItem, SessionToolInvocation } from './types'
@@ -72,6 +72,18 @@ const TWO_GROUPS: SessionThreadItem[] = [
describe('SessionThread', () => {
afterEach(() => jest.restoreAllMocks())
+ test('keeps received messages visible without a reconnecting indicator', () => {
+ render(
+ <SessionThread
+ session={session({ items: TWO_GROUPS.slice(0, 1), phase: 'reconnecting' })}
+ onRetryHistory={jest.fn()}
+ />
+ )
+ expect(screen.getByText('Fix the legend')).toBeTruthy()
+ expect(screen.queryByText('Reconnecting…')).toBeNull()
+ expect(screen.UNSAFE_queryByType(ActivityIndicator)).toBeNull()
+ })
+
test.each([
['above newer messages', 200],
['at the bottom', 1300],
diff --git a/products/mobile/src/features/chat/session/SessionThread.tsx b/products/mobile/src/features/chat/session/SessionThread.tsx
index 919c01dc4b3c..ab48e48522cf 100644
--- a/products/mobile/src/features/chat/session/SessionThread.tsx
+++ b/products/mobile/src/features/chat/session/SessionThread.tsx
@@ -61,7 +61,6 @@ function statusLine(session: SessionThreadState): string | null {
case 'working':
return session.stage ?? 'Thinking…'
case 'reconnecting':
- return 'Reconnecting…'
case 'idle':
return null
}
diff --git a/products/mobile/src/features/chat/useChatAccess.ts b/products/mobile/src/features/chat/useChatAccess.ts
index f5486ce8aafb..fdf247405744 100644
--- a/products/mobile/src/features/chat/useChatAccess.ts
+++ b/products/mobile/src/features/chat/useChatAccess.ts
@@ -74,9 +74,10 @@ export function useChatAccess(): ChatAccessState {
!verification ||
verification.identity !== identity ||
verification.checking
- )
- access = { kind: 'checking' }
- else if (verification.failed) access = { kind: 'org_unknown' }
+ ) {
+ const cached = consentHydrated ? currentAiAccess() : null
+ access = cached && cached.kind !== 'org_unknown' ? cached : { kind: 'checking' }
+ } else if (verification.failed) access = { kind: 'org_unknown' }
else access = currentAiAccess(verification.organization)
return { access, rechecking: verification?.checking ?? false, accept, checkAgain }
}