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): add classic ai chat transport (#129702)

Chris Volzer90601909ad69
diff --git a/.github/workflows/mobile-ci.yml b/.github/workflows/mobile-ci.yml
index 8370adb85d73..1a17c20a91ae 100644
--- a/.github/workflows/mobile-ci.yml
+++ b/.github/workflows/mobile-ci.yml
@@ -68,6 +68,7 @@ jobs:
- '!products/mobile/**/*.md'
- '.github/workflows/mobile-ci.yml'
api_types:
+ - 'products/posthog_ai/frontend/generated/api.schemas.ts'
- 'products/signals/frontend/generated/api.schemas.ts'
- 'products/error_tracking/frontend/generated/api.schemas.ts'
@@ -94,6 +95,7 @@ jobs:
persist-credentials: false
sparse-checkout: |
products/mobile
+ products/posthog_ai/frontend/generated/api.schemas.ts
products/signals/frontend/generated/api.schemas.ts
products/error_tracking/frontend/generated/api.schemas.ts
sparse-checkout-cone-mode: false
diff --git a/ee/api/conversation.py b/ee/api/conversation.py
index 3fe60b8f2228..296c3c488752 100644
--- a/ee/api/conversation.py
+++ b/ee/api/conversation.py
@@ -305,6 +305,7 @@ class ConversationViewSet(
TeamAndOrgViewSetMixin, ListModelMixin, RetrieveModelMixin, DestroyModelMixin, GenericViewSet
):
scope_object = "conversation"
+ scope_object_write_actions = ["create", "update", "partial_update", "patch", "destroy", "cancel"]
serializer_class = ConversationSerializer
queryset = Conversation.objects.all()
lookup_url_kwarg = "conversation"
diff --git a/ee/api/tests/test_conversation.py b/ee/api/tests/test_conversation.py
index 8b87c6575a03..b07e8f52f9f9 100644
--- a/ee/api/tests/test_conversation.py
+++ b/ee/api/tests/test_conversation.py
@@ -30,6 +30,8 @@ from posthog.schema import (
SpendHistoryItem,
)
+from posthog.models.oauth import OAuthAccessToken, OAuthApplication
+from posthog.models.personal_api_key import PersonalAPIKey, hash_key_value
from posthog.models.team.team import Team
from posthog.models.user import User
from posthog.rate_limit import AIBurstRateThrottle
@@ -335,8 +337,45 @@ class TestConversation(APIBaseTest):
)
self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)
- @patch("ee.hogai.core.executor.AgentExecutor.cancel_workflow")
- def test_cancel_conversation(self, mock_cancel):
+ @parameterized.expand(
+ [
+ ("session", "conversation:write", status.HTTP_204_NO_CONTENT),
+ ("personal_api_key", "conversation:write", status.HTTP_204_NO_CONTENT),
+ ("oauth", "conversation:write", status.HTTP_204_NO_CONTENT),
+ ("personal_api_key", "conversation:read", status.HTTP_403_FORBIDDEN),
+ ("oauth", "conversation:read", status.HTTP_403_FORBIDDEN),
+ ]
+ )
+ @patch("ee.hogai.core.executor.AgentExecutor.cancel_workflow", new_callable=AsyncMock)
+ def test_cancel_conversation(
+ self, authentication: str, scope: str, expected_status: int, mock_cancel: AsyncMock
+ ) -> None:
+ if authentication != "session":
+ self.client.logout()
+ if authentication == "personal_api_key":
+ token = "phx_fake_conversation_cancel_test"
+ PersonalAPIKey.objects.create(
+ user=self.user, label="Cancel test", secure_value=hash_key_value(token), scopes=[scope]
+ )
+ else:
+ token = "pha_fake_conversation_cancel_test"
+ application = OAuthApplication.objects.create(
+ name="Cancel test",
+ user=self.user,
+ organization=self.organization,
+ client_type=OAuthApplication.CLIENT_CONFIDENTIAL,
+ authorization_grant_type=OAuthApplication.GRANT_AUTHORIZATION_CODE,
+ redirect_uris="https://example.com/callback",
+ algorithm="RS256",
+ )
+ OAuthAccessToken.objects.create(
+ user=self.user,
+ application=application,
+ token=token,
+ expires=timezone.now() + datetime.timedelta(hours=1),
+ scope=scope,
+ )
+ self.client.credentials(HTTP_AUTHORIZATION=f"Bearer {token}")
conversation = Conversation.objects.create(
user=self.user,
team=self.team,
@@ -344,11 +383,11 @@ class TestConversation(APIBaseTest):
type=Conversation.Type.ASSISTANT,
status=Conversation.Status.IN_PROGRESS,
)
- mock_cancel.return_value = AsyncMock(return_value=True)()
response = self.client.patch(
f"/api/environments/{self.team.id}/conversations/{conversation.id}/cancel/",
)
- self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT)
+ self.assertEqual(response.status_code, expected_status)
+ self.assertEqual(mock_cancel.await_count, int(expected_status == status.HTTP_204_NO_CONTENT))
def test_cancel_already_canceling_conversation(self):
conversation = Conversation.objects.create(
diff --git a/products/mobile/docs/API.md b/products/mobile/docs/API.md
index c521d33e29b0..0635f27e053e 100644
--- a/products/mobile/docs/API.md
+++ b/products/mobile/docs/API.md
@@ -12,6 +12,17 @@ before its response is lost, so a timeout does not mean it failed on the server.
idle watchdog and reconnect policy. Transport failures have a dedicated error type; unrelated programming errors are
not reported as connectivity failures.
+The classic conversation transport uses a 30-second connection deadline and a 60-second inactivity deadline.
+Each received chunk, including a heartbeat, resets the inactivity deadline.
+An interrupted accepted reply offers reconnection; the app does not resend it automatically.
+History reconciliation retains streamed generation failures.
+Pending approvals and clarification forms pause reconnection until the person responds.
+The classic chat hook exposes form questions from both streamed replies and history, with submit and dismiss methods.
+Form responses send no new chat message; they resume the conversation with the selected answers or a dismissal.
+Notebook artifacts retain their Markdown and chart blocks, with links to saved notebooks and a web fallback for other content.
+Reply links without a project prefix use the conversation's project; explicit project links and external links keep their destination.
+Canceling a classic reply requires `conversation:write` for OAuth and personal API tokens.
+
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 API
types should come from the generated schemas; update the Django serializer and run
diff --git a/products/mobile/src/api/conversations.ts b/products/mobile/src/api/conversations.ts
new file mode 100644
index 000000000000..f50a220b6a3e
--- /dev/null
+++ b/products/mobile/src/api/conversations.ts
@@ -0,0 +1,28 @@
+import type {
+ ConversationApi,
+ ConversationMinimalApi,
+ MessageApi,
+ PaginatedConversationMinimalListApi,
+} from '../../../../products/posthog_ai/frontend/generated/api.schemas'
+
+import { apiJson, apiStream, projectPath } from './client'
+
+export async function listConversations(signal?: AbortSignal): Promise<ConversationMinimalApi[]> {
+ const response = await apiJson<PaginatedConversationMinimalListApi>(projectPath('conversations/'), {
+ query: { limit: 100 },
+ signal,
+ })
+ return response.results
+}
+
+export function getConversation(id: string, signal?: AbortSignal): Promise<ConversationApi> {
+ return apiJson<ConversationApi>(projectPath(`conversations/${encodeURIComponent(id)}/`), { signal })
+}
+
+export function streamConversation(body: MessageApi, signal?: AbortSignal): Promise<Response> {
+ return apiStream(projectPath('conversations/'), { method: 'POST', json: body, signal })
+}
+
+export async function cancelConversation(id: string): Promise<void> {
+ await apiJson(projectPath(`conversations/${encodeURIComponent(id)}/cancel/`), { method: 'PATCH' })
+}
diff --git a/products/mobile/src/api/sse.test.ts b/products/mobile/src/api/sse.test.ts
index d33f81e64eb3..06946d7fedd3 100644
--- a/products/mobile/src/api/sse.test.ts
+++ b/products/mobile/src/api/sse.test.ts
@@ -1,4 +1,5 @@
import { createSseParser, readSse, type SseEvent } from './sse'
+import { RequestTimeoutError } from './transport'
function parse(chunks: string[]): SseEvent[] {
const events: SseEvent[] = []
@@ -62,4 +63,35 @@ describe('sse', () => {
await readSse(response, (event) => events.push(event))
expect(events).toEqual([{ event: 'message', data: '"Größe"', id: undefined }])
})
+ test.each(['stalled', 'active'])('bounds %s readers while allowing heartbeat activity', async (kind) => {
+ jest.useFakeTimers()
+ const reader = {
+ read: jest.fn(() => new Promise<ReadableStreamReadResult<Uint8Array>>(() => undefined)),
+ cancel: jest.fn(async () => undefined),
+ }
+ let heartbeat!: (value: ReadableStreamReadResult<Uint8Array>) => void
+ if (kind === 'active')
+ reader.read.mockImplementationOnce(
+ () =>
+ new Promise((resolve) => {
+ heartbeat = resolve
+ })
+ )
+ const response = { body: { getReader: () => reader } } as unknown as Response
+ const pending = readSse(response, jest.fn(), undefined, 60_000)
+ const rejected = expect(pending).rejects.toBeInstanceOf(RequestTimeoutError)
+ try {
+ await jest.advanceTimersByTimeAsync(59_000)
+ if (kind === 'active') {
+ heartbeat({ value: new TextEncoder().encode(': ping\n\n'), done: false })
+ await jest.advanceTimersByTimeAsync(59_000)
+ expect(reader.cancel).not.toHaveBeenCalled()
+ }
+ await jest.advanceTimersByTimeAsync(1_000)
+ await rejected
+ expect(reader.cancel).toHaveBeenCalledTimes(1)
+ } finally {
+ jest.useRealTimers()
+ }
+ })
})
diff --git a/products/mobile/src/api/sse.ts b/products/mobile/src/api/sse.ts
index fc448aa054ea..ba78df3ba686 100644
--- a/products/mobile/src/api/sse.ts
+++ b/products/mobile/src/api/sse.ts
@@ -1,4 +1,5 @@
import { abortError } from '@/lib/abort'
+import { requestWithDeadline } from './transport'
/** One server-sent event. `event` defaults to `message` when the frame names none. */
export interface SseEvent {
@@ -88,7 +89,8 @@ export function createSseParser(onEvent: (event: SseEvent) => void): SseParser {
export async function readSse(
response: Response,
onEvent: (event: SseEvent) => void,
- signal?: AbortSignal
+ signal?: AbortSignal,
+ inactivityTimeoutMs?: number
): Promise<void> {
const body = response.body
if (!body) {
@@ -102,7 +104,7 @@ export async function readSse(
const reader = body.getReader()
const decoder = new TextDecoder()
const abort = (): void => {
- void reader.cancel()
+ void reader.cancel().catch(() => undefined)
}
signal?.addEventListener('abort', abort, { once: true })
try {
@@ -110,7 +112,9 @@ export async function readSse(
if (signal?.aborted) {
throw abortError()
}
- const { value, done } = await reader.read()
+ const { value, done } = await (inactivityTimeoutMs === undefined
+ ? reader.read()
+ : requestWithDeadline(() => reader.read(), signal, inactivityTimeoutMs))
if (done) {
parser.feed(decoder.decode())
break
@@ -119,5 +123,6 @@ export async function readSse(
}
} finally {
signal?.removeEventListener('abort', abort)
+ abort()
}
}
diff --git a/products/mobile/src/features/chat/ChatMarkdown.test.tsx b/products/mobile/src/features/chat/ChatMarkdown.test.tsx
index 18523508fff7..a1c5a0acd3a4 100644
--- a/products/mobile/src/features/chat/ChatMarkdown.test.tsx
+++ b/products/mobile/src/features/chat/ChatMarkdown.test.tsx
@@ -11,10 +11,10 @@ jest.mock('@/api/insights', () => ({ getInsightSummary: jest.fn() }))
jest.mock('./MermaidDiagram', () => ({ MermaidDiagram: jest.fn(() => null) }))
const summary = getInsightSummary as jest.MockedFunction<typeof getInsightSummary>
let client: QueryClient
-function view(text: string): ReturnType<typeof render> {
+function view(text: string, projectUrl?: string): ReturnType<typeof render> {
return render(
<QueryClientProvider client={client}>
- <ChatMarkdown text={text} />
+ <ChatMarkdown text={text} projectUrl={projectUrl} />
</QueryClientProvider>
)
}
@@ -63,6 +63,17 @@ describe('reply object rendering', () => {
fireEvent.press(screen.getByText('https://example.com/auto'))
expect(open.mock.calls).toEqual([['https://example.com/guide'], ['https://example.com/auto']])
})
+ test.each([
+ ['/dashboard/123?tab=details#top', 'https://app.example.com/project/42/dashboard/123?tab=details#top'],
+ ['/project/99/insights/abc', 'https://app.example.com/project/99/insights/abc'],
+ ['/organization/settings', 'https://app.example.com/organization/settings'],
+ ['https://external.example.com/guide', 'https://external.example.com/guide'],
+ ])('opens %s in its intended project', (path, expected) => {
+ const open = jest.spyOn(Linking, 'openURL').mockResolvedValue(undefined)
+ const screen = view(`[Link](${path})`, 'https://app.example.com/project/42')
+ fireEvent.press(screen.getByText('Link'))
+ expect(open).toHaveBeenCalledWith(expected)
+ })
test.each([
['ordinary prose', 'plain words '],
['a repeated mailto: scheme', 'mailto:'],
diff --git a/products/mobile/src/features/chat/ChatMarkdown.tsx b/products/mobile/src/features/chat/ChatMarkdown.tsx
index 0979f120ed28..c40630db5830 100644
--- a/products/mobile/src/features/chat/ChatMarkdown.tsx
+++ b/products/mobile/src/features/chat/ChatMarkdown.tsx
@@ -53,8 +53,8 @@ const rules: RenderRules = {
},
}
-function openLink(url: string): boolean {
- const resolved = resolveReplyLink(url)
+function openLink(url: string, projectUrl?: string): boolean {
+ const resolved = resolveReplyLink(url, projectUrl)
if (resolved) {
openReplyUrl(resolved, 'markdown', { appLink: resolved !== url })
}
@@ -67,11 +67,12 @@ const TRAILING_LIST_MARKER = /\n[ \t]*(?:[-*+]|\d+[.)])[ \t]*$/
interface ChatMarkdownProps {
text: string
+ projectUrl?: string
streaming?: boolean
tone?: 'reply' | 'thought'
}
-export function ChatMarkdown({ text, streaming = false, tone = 'reply' }: ChatMarkdownProps): ReactElement {
+export function ChatMarkdown({ text, projectUrl, streaming = false, tone = 'reply' }: ChatMarkdownProps): ReactElement {
const replyStyles = useReplyStyles()
const thoughtStyles = useThoughtStyles()
return (
@@ -79,7 +80,7 @@ export function ChatMarkdown({ text, streaming = false, tone = 'reply' }: ChatMa
markdownit={markdownIt}
rules={rules}
style={tone === 'thought' ? thoughtStyles : replyStyles}
- onLinkPress={openLink}
+ onLinkPress={(url) => openLink(url, projectUrl)}
>
{streaming ? text.replace(TRAILING_LIST_MARKER, '') : text}
</Markdown>
diff --git a/products/mobile/src/features/chat/classic/classicMessages.test.ts b/products/mobile/src/features/chat/classic/classicMessages.test.ts
new file mode 100644
index 000000000000..67187e67a5cd
--- /dev/null
+++ b/products/mobile/src/features/chat/classic/classicMessages.test.ts
@@ -0,0 +1,183 @@
+import {
+ appendClassicMessage,
+ classicHistory,
+ classicThreadItems,
+ EMPTY_CLASSIC_STATE,
+ reduceClassicEvent,
+} from './classicMessages'
+
+describe('classic conversation events', () => {
+ test('replaces the optimistic human echo and accumulated answer snapshots without duplicating turns', () => {
+ let state = appendClassicMessage(EMPTY_CLASSIC_STATE, {
+ type: 'human',
+ content: 'A question',
+ trace_id: 'trace-1',
+ })
+ state = appendClassicMessage(state, {
+ id: 'human-1',
+ type: 'human',
+ content: 'A question',
+ trace_id: 'trace-1',
+ })
+ state = appendClassicMessage(state, { type: 'ai', content: 'The' })
+ state = appendClassicMessage(state, { type: 'ai', content: 'The answer' })
+ state = appendClassicMessage(state, { id: 'ai-1', type: 'ai', content: 'The answer.' })
+ state = appendClassicMessage(state, { id: 'ai-1', type: 'ai', content: 'The answer.' })
+ expect(state.messages).toHaveLength(2)
+ expect(classicThreadItems(state, '')).toEqual([
+ { kind: 'user', id: 'stream-0', text: 'A question' },
+ { kind: 'assistant', id: 'stream-1', text: 'The answer.', complete: true, projectUrl: '' },
+ ])
+ })
+
+ test('keeps separate answers and turns intact when loading history', () => {
+ const state = classicHistory(
+ [
+ { id: 'a', type: 'ai', content: 'First answer' },
+ { id: 'b', type: 'human', content: 'Follow-up' },
+ { id: 'c', type: 'ai', content: 'Second answer' },
+ ],
+ 'Saved title'
+ )
+ expect(state.title).toBe('Saved title')
+ expect(classicThreadItems(state, '').map((item) => item.id)).toEqual(['a', 'b', 'c'])
+ })
+
+ test('restores pending approvals and ignores malformed stream frames', () => {
+ const approval = {
+ proposal_id: 'proposal-1',
+ decision_status: 'pending',
+ tool_name: 'Create dashboard',
+ preview: 'Create a dashboard',
+ }
+ const state = reduceClassicEvent(EMPTY_CLASSIC_STATE, {
+ event: 'approval',
+ data: JSON.stringify(approval),
+ })
+ expect(state.approval).toEqual({
+ id: 'proposal-1',
+ toolName: 'Create dashboard',
+ preview: 'Create a dashboard',
+ })
+ expect(classicHistory([], null, [approval]).approval).toEqual(state.approval)
+ expect(reduceClassicEvent(state, { event: 'message', data: '{broken' })).toBe(state)
+ expect(reduceClassicEvent(state, { event: 'message', data: 'null' })).toBe(state)
+ })
+
+ test('preserves links to generated charts and saved insights', () => {
+ const state = classicHistory(
+ [
+ { type: 'ai/viz', id: 'chart', answer: { kind: 'TrendsQuery', series: [] } },
+ { type: 'ai/artifact', id: 'saved', source: 'insight', artifact_id: 'abc123', content: {} },
+ ],
+ null
+ )
+ const items = classicThreadItems(state, 'https://app.example.com/project/42')
+ expect(items[0]).toMatchObject({ text: expect.stringContaining('/insights/new#q=') })
+ expect(items[1]).toMatchObject({
+ text: '[View insight](https://app.example.com/project/42/insights/abc123)',
+ })
+ })
+ test('preserves distinct temporary answers while replacing snapshots of each', () => {
+ let state = EMPTY_CLASSIC_STATE
+ for (const data of [
+ { id: 'temp-0', type: 'ai', content: 'Searching' },
+ { id: 'temp-1', type: 'ai', content: 'Found' },
+ { id: 'temp-0', type: 'ai', content: 'Searching the web' },
+ { id: 'temp-1', type: 'ai', content: 'Found an answer' },
+ ])
+ state = appendClassicMessage(state, data)
+ expect(classicThreadItems(state, '').map((item) => ('text' in item ? item.text : null))).toEqual([
+ 'Searching the web',
+ 'Found an answer',
+ ])
+ })
+
+ test.each([
+ [
+ { kind: 'TrendsQuery', series: [] },
+ { kind: 'InsightVizNode', source: { kind: 'TrendsQuery', series: [] }, showHeader: true },
+ ],
+ [
+ { kind: 'HogQLQuery', query: 'SELECT 1' },
+ { kind: 'DataVisualizationNode', source: { kind: 'HogQLQuery', query: 'SELECT 1' } },
+ ],
+ [
+ {
+ kind: 'DataVisualizationNode',
+ source: { kind: 'HogQLQuery', query: 'SELECT 1' },
+ display: 'ActionsBar',
+ },
+ {
+ kind: 'DataVisualizationNode',
+ source: { kind: 'HogQLQuery', query: 'SELECT 1' },
+ display: 'ActionsBar',
+ },
+ ],
+ ])('keeps chart links compatible with the query schema: %j', (query, expected) => {
+ const state = classicHistory([{ type: 'ai/viz', id: 'chart', answer: query }], null)
+ const item = classicThreadItems(state, 'https://app.example.com/project/42')[0]
+ const encoded = item && 'text' in item ? (item.text.split('#q=')[1]?.slice(0, -1) ?? '') : ''
+ expect(JSON.parse(decodeURIComponent(encoded))).toEqual(expected)
+ })
+ test.each(['Saved answer', 'Saved'])('reconciles replayed %s with unique IDs across model calls', (snapshot) => {
+ let state = classicHistory(
+ [
+ { id: 'earlier', type: 'ai', content: 'Earlier turn' },
+ { id: 'saved', type: 'ai', content: 'Saved answer' },
+ ],
+ null
+ )
+ state = appendClassicMessage(state, { id: 'temp-0', type: 'ai', content: snapshot })
+ state = appendClassicMessage(state, { id: 'temp-1', type: 'ai', content: 'Next answer' })
+ const nextId = state.messages.at(-1)?.id
+ state = appendClassicMessage(state, { id: 'saved', type: 'ai', content: 'Saved answer' })
+ expect(state.messages.map((message) => message.data.content)).toEqual([
+ 'Earlier turn',
+ 'Saved answer',
+ 'Next answer',
+ ])
+ state = appendClassicMessage(state, { id: 'next', type: 'ai', content: 'Next answer' })
+ expect(state.messages.at(-1)?.id).toBe(nextId)
+ state = appendClassicMessage(state, { id: 'temp-0', type: 'ai', content: 'Another call' })
+ state = appendClassicMessage(state, { id: 'final', type: 'ai', content: 'Another call' })
+ state = appendClassicMessage(state, { id: 'temp-0', type: 'ai', content: 'Last call' })
+ const items = classicThreadItems(state, '')
+ expect(new Set(items.map((item) => item.id)).size).toBe(items.length)
+ expect(state.messages.map((message) => message.data.content)).toEqual([
+ 'Earlier turn',
+ 'Saved answer',
+ 'Next answer',
+ 'Another call',
+ 'Last call',
+ ])
+ })
+
+ test.each(['stream', 'history'])('preserves notebook blocks from %s', (source) => {
+ const data = {
+ id: 'notebook-message',
+ type: 'ai/artifact',
+ source: 'artifact',
+ artifact_id: 'report-1',
+ content: {
+ content_type: 'notebook',
+ is_saved: true,
+ blocks: [
+ { type: 'markdown', content: '# Report\n\nA synthetic summary.' },
+ { type: 'session_replay', session_id: 'session-1', timestamp_ms: 0 },
+ { type: 'markdown', content: 'A conclusion.' },
+ ],
+ },
+ }
+ const state =
+ source === 'history'
+ ? classicHistory([data], null)
+ : reduceClassicEvent(EMPTY_CLASSIC_STATE, { event: 'message', data: JSON.stringify(data) })
+ expect(classicThreadItems(state, 'https://app.example.com/project/42')[0]).toMatchObject({
+ text: '# Report\n\nA synthetic summary.\n\nOpen this report on the web to view this content.\n\nA conclusion.\n\n[View notebook](https://app.example.com/project/42/notebooks/report-1)',
+ })
+ data.content.is_saved = false
+ const draft = classicThreadItems(classicHistory([data], null), 'https://app.example.com/project/42')[0]
+ expect(draft && 'text' in draft ? draft.text : '').not.toContain('[View notebook]')
+ })
+})
diff --git a/products/mobile/src/features/chat/classic/classicMessages.ts b/products/mobile/src/features/chat/classic/classicMessages.ts
new file mode 100644
index 000000000000..54cffbd4a13e
--- /dev/null
+++ b/products/mobile/src/features/chat/classic/classicMessages.ts
@@ -0,0 +1,249 @@
+import type { SseEvent } from '@/api/sse'
+import { asRecord, isRecord } from '@/lib/records'
+
+import type { SessionThreadItem } from '../session/types'
+
+export interface ClassicMessage {
+ id: string
+ data: Record<string, unknown>
+ complete: boolean
+}
+
+export interface ClassicApproval {
+ id: string
+ preview: string
+ toolName: string
+}
+
+export interface ClassicForm {
+ id: string
+ questions: Record<string, unknown>[]
+}
+
+export interface ClassicState {
+ messages: ClassicMessage[]
+ nextMessageId: number
+ title: string | null
+ progress: string | null
+ approval: ClassicApproval | null
+ form: ClassicForm | null
+ error: string | null
+}
+
+export const EMPTY_CLASSIC_STATE: ClassicState = {
+ messages: [],
+ nextMessageId: 0,
+ title: null,
+ progress: null,
+ approval: null,
+ form: null,
+ error: null,
+}
+
+function approvalFrom(value: unknown): ClassicApproval | null {
+ const data = asRecord(value) ?? {}
+ return typeof data.proposal_id === 'string' && data.decision_status === 'pending'
+ ? {
+ id: data.proposal_id,
+ preview: typeof data.preview === 'string' ? data.preview : 'Allow this change?',
+ toolName: typeof data.tool_name === 'string' ? data.tool_name : 'PostHog AI',
+ }
+ : null
+}
+
+function pendingForm(messages: ClassicMessage[]): ClassicForm | null {
+ const data = messages.at(-1)?.data
+ if (data?.type !== 'ai' || !Array.isArray(data.tool_calls)) return null
+ const call = data.tool_calls.find((call) => isRecord(call) && call.name === 'create_form')
+ const args = asRecord(call?.args)
+ if (typeof call?.id !== 'string' || !Array.isArray(args?.questions)) return null
+ const questions = args.questions.filter(isRecord)
+ return questions.length ? { id: call.id, questions } : null
+}
+
+export function appendClassicMessage(state: ClassicState, data: Record<string, unknown>): ClassicState {
+ if (typeof data.type !== 'string') {
+ return state
+ }
+ const wireId = typeof data.id === 'string' ? data.id : null
+ const complete = wireId !== null && !wireId.startsWith('temp-')
+ let index = wireId ? state.messages.findIndex((message) => message.data.id === wireId) : -1
+ if (index < 0 && data.type === 'human') {
+ index = state.messages.findLastIndex(
+ (message) =>
+ message.data.type === 'human' &&
+ !message.complete &&
+ (data.trace_id ? message.data.trace_id === data.trace_id : message.data.content === data.content)
+ )
+ }
+ const finalCalls = Array.isArray(data.tool_calls) ? data.tool_calls.filter(isRecord) : []
+ const pendingIndex = state.messages.findIndex((message) => {
+ if (message.complete || message.data.type !== data.type) return false
+ const calls = Array.isArray(message.data.tool_calls) ? message.data.tool_calls.filter(isRecord) : []
+ if (calls.length) return calls.some((call) => finalCalls.some((finalCall) => finalCall.id === call.id))
+ return (
+ typeof message.data.content === 'string' &&
+ message.data.content.length > 0 &&
+ typeof data.content === 'string' &&
+ data.content.startsWith(message.data.content)
+ )
+ })
+ if (index < 0 && data.type !== 'human' && (!wireId || complete)) {
+ index =
+ pendingIndex >= 0
+ ? pendingIndex
+ : state.messages.findIndex((message) => !message.complete && message.data.type === data.type)
+ }
+ const entry: ClassicMessage = {
+ id: complete && wireId ? wireId : `stream-${state.nextMessageId}`,
+ data,
+ complete,
+ }
+ const messages = [...state.messages]
+ if (index >= 0) {
+ messages[index] = { ...entry, id: messages[index]?.id ?? entry.id }
+ } else {
+ messages.push(entry)
+ }
+ if (complete && index >= 0 && pendingIndex >= 0 && pendingIndex !== index) {
+ messages.splice(pendingIndex, 1)
+ }
+ return {
+ ...state,
+ messages,
+ form: pendingForm(messages),
+ nextMessageId: state.nextMessageId + (index < 0 ? 1 : 0),
+ progress: data.type === 'ai' ? null : state.progress,
+ error:
+ data.type === 'ai/failure'
+ ? String(data.content || 'PostHog AI ran into a problem. Try again.')
+ : state.error,
+ }
+}
+
+export function classicHistory(
+ messages: readonly Record<string, unknown>[],
+ title: string | null,
+ approvals: readonly Record<string, unknown>[] = []
+): ClassicState {
+ const entries = messages.map((data, index) => ({
+ id: typeof data.id === 'string' ? data.id : `history-${index}`,
+ data,
+ complete: true,
+ }))
+ return {
+ ...EMPTY_CLASSIC_STATE,
+ title,
+ messages: entries,
+ nextMessageId: entries.length,
+ form: pendingForm(entries),
+ approval: approvals.map(approvalFrom).find((approval) => approval !== null) ?? null,
+ }
+}
+
+export function reduceClassicEvent(state: ClassicState, event: SseEvent): ClassicState {
+ let data: unknown
+ try {
+ data = JSON.parse(event.data)
+ } catch {
+ return state
+ }
+ if (!isRecord(data)) {
+ return state
+ }
+ switch (event.event) {
+ case 'message':
+ return appendClassicMessage(state, data)
+ case 'conversation':
+ return { ...state, title: typeof data.title === 'string' ? data.title : state.title }
+ case 'update':
+ return {
+ ...state,
+ progress: typeof data.content === 'string' ? data.content : state.progress,
+ }
+ case 'approval':
+ return { ...state, approval: approvalFrom(data) }
+ case 'status':
+ return data.type === 'generation_error'
+ ? { ...state, error: 'PostHog AI ran into a problem. Try again.' }
+ : state
+ default:
+ return state
+ }
+}
+
+function visualizationLink(data: Record<string, unknown>, projectUrl: string): string | null {
+ const content = asRecord(data.content) ?? {}
+ const shortId = data.short_id ?? (data.source === 'insight' ? data.artifact_id : content.short_id)
+ if (typeof shortId === 'string') {
+ return `[View insight](${projectUrl}/insights/${encodeURIComponent(shortId)})`
+ }
+ const query = data.answer ?? content.query
+ if (!isRecord(query)) return null
+ const insightKinds = [
+ 'TrendsQuery',
+ 'FunnelsQuery',
+ 'RetentionQuery',
+ 'PathsQuery',
+ 'StickinessQuery',
+ 'LifecycleQuery',
+ ]
+ const visualization =
+ query.kind === 'HogQLQuery'
+ ? { kind: 'DataVisualizationNode', source: query }
+ : insightKinds.includes(String(query.kind))
+ ? { kind: 'InsightVizNode', source: query, showHeader: true }
+ : query
+ return `[View chart](${projectUrl}/insights/new#q=${encodeURIComponent(JSON.stringify(visualization))})`
+}
+
+function notebookText(data: Record<string, unknown>, projectUrl: string): string {
+ const content = asRecord(data.content) ?? {}
+ const blocks = Array.isArray(content.blocks) ? content.blocks : []
+ const parts = blocks.map((value): string => {
+ const block = asRecord(value) ?? {}
+ if (block.type === 'markdown' && typeof block.content === 'string') return block.content
+ if (block.type === 'visualization')
+ return visualizationLink({ content: block }, projectUrl) ?? 'Chart unavailable.'
+ if (block.type === 'error' && typeof block.message === 'string') return block.message
+ return 'Open this report on the web to view this content.'
+ })
+ if (content.is_saved === true && typeof data.artifact_id === 'string') {
+ parts.push(`[View notebook](${projectUrl}/notebooks/${encodeURIComponent(data.artifact_id)})`)
+ }
+ return parts.filter(Boolean).join('\n\n') || 'This report has no content yet.'
+}
+
+export function classicThreadItems(state: ClassicState, projectUrl: string): SessionThreadItem[] {
+ return state.messages.flatMap((message): SessionThreadItem[] => {
+ const data = message.data
+ const text = typeof data.content === 'string' ? data.content : ''
+ switch (data.type) {
+ case 'human':
+ return [{ kind: 'user', id: message.id, text }]
+ case 'ai':
+ return text ? [{ kind: 'assistant', id: message.id, text, complete: message.complete, projectUrl }] : []
+ case 'ai/reasoning':
+ return text ? [{ kind: 'thought', id: message.id, text, complete: message.complete }] : []
+ case 'ai/viz':
+ case 'ai/artifact': {
+ const link =
+ asRecord(data.content)?.content_type === 'notebook'
+ ? notebookText(data, projectUrl)
+ : visualizationLink(data, projectUrl)
+ return link ? [{ kind: 'assistant', id: message.id, text: link, complete: true, projectUrl }] : []
+ }
+ case 'ai/multi_viz':
+ return Array.isArray(data.visualizations)
+ ? data.visualizations.flatMap((viz, index): SessionThreadItem[] => {
+ const link = visualizationLink(asRecord(viz) ?? {}, projectUrl)
+ return link
+ ? [{ kind: 'assistant', id: `${message.id}-${index}`, text: link, complete: true }]
+ : []
+ })
+ : []
+ default:
+ return []
+ }
+ })
+}
diff --git a/products/mobile/src/features/chat/classic/useClassicChat.test.tsx b/products/mobile/src/features/chat/classic/useClassicChat.test.tsx
new file mode 100644
index 000000000000..44632a7f5bf4
--- /dev/null
+++ b/products/mobile/src/features/chat/classic/useClassicChat.test.tsx
@@ -0,0 +1,365 @@
+import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
+import { act, renderHook } from '@testing-library/react-native'
+import { randomUUID } from 'expo-crypto'
+import { type PropsWithChildren, type ReactElement, useState } from 'react'
+
+import { ApiError } from '@/api/client'
+import { cancelConversation, getConversation, streamConversation } from '@/api/conversations'
+import { readSse } from '@/api/sse'
+import { REQUEST_TIMEOUT_MS } from '@/api/transport'
+import { useProjectScope } from '@/auth/useProjectScope'
+
+import { useClassicChat } from './useClassicChat'
+
+jest.mock('@/api/conversations', () => ({
+ cancelConversation: jest.fn(),
+ getConversation: jest.fn(),
+ streamConversation: jest.fn(),
+}))
+jest.mock('@/api/sse', () => ({ readSse: jest.fn() }))
+jest.mock('expo-crypto', () => ({ randomUUID: jest.fn() }))
+jest.mock('@/auth/useProjectScope', () => ({ useProjectScope: jest.fn(() => null) }))
+jest.mock('@/features/chats/hooks', () => ({
+ sessionListKeys: { all: () => [] },
+ conversationListKeys: { all: () => [] },
+}))
+
+function wrapper({ children }: PropsWithChildren): ReactElement {
+ const [client] = useState(() => new QueryClient({ defaultOptions: { queries: { gcTime: Infinity } } }))
+ return <QueryClientProvider client={client}>{children}</QueryClientProvider>
+}
+
+describe('classic chat transport', () => {
+ beforeEach(() => {
+ jest.resetAllMocks()
+ jest.mocked(useProjectScope).mockReturnValue(null)
+ let id = 0
+ jest.mocked(randomUUID).mockImplementation(() => `00000000-0000-4000-8000-${String(++id).padStart(12, '0')}`)
+ jest.mocked(streamConversation).mockResolvedValue({} as Response)
+ jest.mocked(getConversation).mockResolvedValue({
+ messages: [],
+ title: 'A chat',
+ pending_approvals: [],
+ } as unknown as Awaited<ReturnType<typeof getConversation>>)
+ jest.mocked(readSse).mockResolvedValue()
+ })
+
+ afterEach(() => jest.useRealTimers())
+
+ test('sends new and subsequent turns to the same classic conversation', async () => {
+ const { result } = renderHook(() => useClassicChat(), { wrapper })
+ await act(async () => {
+ expect(await result.current.send('First')).toBe(true)
+ })
+ const first = jest.mocked(streamConversation).mock.calls[0]?.[0]
+ expect(first).toMatchObject({ content: 'First', is_sandbox: false })
+ await act(async () => {
+ await result.current.send('Second')
+ })
+ expect(jest.mocked(streamConversation).mock.calls[1]?.[0]).toMatchObject({
+ conversation: first?.conversation,
+ content: 'Second',
+ is_sandbox: false,
+ })
+ })
+
+ test('blocks double submission and removes an undelivered optimistic message', async () => {
+ let reject!: (error: Error) => void
+ jest.mocked(streamConversation).mockReturnValue(
+ new Promise((_resolve, rejectPromise) => {
+ reject = rejectPromise
+ })
+ )
+ const { result } = renderHook(() => useClassicChat(), { wrapper })
+ let pending!: Promise<boolean>
+ act(() => {
+ pending = result.current.send('Keep this draft')
+ })
+ await act(async () => {
+ expect(await result.current.send('Duplicate')).toBe(false)
+ })
+ await act(async () => {
+ reject(new ApiError(429, { detail: 'Try later' }))
+ expect(await pending).toBe(false)
+ })
+ expect(streamConversation).toHaveBeenCalledTimes(1)
+ expect(result.current.state.messages).toEqual([])
+ expect(result.current.error).toBe('Try later')
+ expect(result.current.working).toBe(false)
+ })
+
+ test('ignores frames and completion from a conversation reset during streaming', async () => {
+ let finish!: () => void
+ jest.mocked(readSse).mockImplementation(
+ (_response, onEvent) =>
+ new Promise<void>((resolve) => {
+ finish = () => {
+ onEvent({
+ event: 'message',
+ data: JSON.stringify({ id: 'old', type: 'ai', content: 'Old answer' }),
+ })
+ resolve()
+ }
+ })
+ )
+ const { result } = renderHook(() => useClassicChat(), { wrapper })
+ let pending!: Promise<boolean>
+ await act(async () => {
+ pending = result.current.send('Old question')
+ await Promise.resolve()
+ })
+ act(() => result.current.reset())
+ await act(async () => {
+ finish()
+ await pending
+ })
+ expect(result.current.id).toBeNull()
+ expect(result.current.state.messages).toEqual([])
+ })
+
+ test('offers history recovery after an accepted stream disconnects', async () => {
+ jest.mocked(readSse).mockRejectedValueOnce(new TypeError('Connection lost'))
+ const { result } = renderHook(() => useClassicChat(), { wrapper })
+ await act(async () => {
+ expect(await result.current.send('Question')).toBe(true)
+ })
+ expect(result.current.historyError).toContain('Reconnect')
+ await act(async () => result.current.reload())
+ expect(result.current.historyError).toBeNull()
+ expect(getConversation).toHaveBeenCalledWith(result.current.id, expect.any(AbortSignal))
+ })
+
+ test('guards duplicate cancellation requests', async () => {
+ let finish!: () => void
+ jest.mocked(cancelConversation).mockImplementation(
+ () =>
+ new Promise<void>((resolve) => {
+ finish = resolve
+ })
+ )
+ const { result } = renderHook(() => useClassicChat('saved-chat'), { wrapper })
+ await act(async () => undefined)
+ let pending!: Promise<void>
+ act(() => {
+ pending = result.current.stop()
+ })
+ await act(async () => result.current.stop())
+ expect(cancelConversation).toHaveBeenCalledTimes(1)
+ await act(async () => {
+ finish()
+ await pending
+ })
+ expect(result.current.stopping).toBe(false)
+ })
+ test.each(['persisted', 'transient'])(
+ 'retains a %s generation failure after history reconciliation',
+ async (kind) => {
+ const failure = {
+ id: 'failure-1',
+ type: 'ai/failure',
+ content: 'Could not start this reply. Try again.',
+ }
+ jest.mocked(readSse).mockImplementation(async (_response, onEvent) => {
+ onEvent({ event: 'message', data: JSON.stringify(failure) })
+ })
+ if (kind === 'persisted')
+ jest.mocked(getConversation).mockResolvedValue({
+ messages: [failure],
+ title: 'A chat',
+ pending_approvals: [],
+ } as unknown as Awaited<ReturnType<typeof getConversation>>)
+ const { result } = renderHook(() => useClassicChat(), { wrapper })
+ await act(async () => {
+ await result.current.send('Question')
+ })
+ expect(result.current.error).toBe(failure.content)
+ expect(result.current.working).toBe(false)
+ }
+ )
+
+ test.each(['pending', 'approved', 'rejected', 'expired'])(
+ 'reconnects only when the %s approval needs no decision',
+ async (decision_status) => {
+ jest.mocked(getConversation).mockResolvedValue({
+ messages: [],
+ title: 'A chat',
+ status: 'in_progress',
+ pending_approvals: [{ proposal_id: 'proposal-1', decision_status }],
+ } as unknown as Awaited<ReturnType<typeof getConversation>>)
+ const { result } = renderHook(() => useClassicChat('saved-chat'), { wrapper })
+ await act(async () => undefined)
+ expect(streamConversation).toHaveBeenCalledTimes(decision_status === 'pending' ? 0 : 1)
+ expect(result.current.loading).toBe(false)
+ }
+ )
+
+ test('releases a stalled connection and allows another send', async () => {
+ jest.useFakeTimers()
+ jest.mocked(streamConversation).mockReturnValueOnce(new Promise(() => undefined))
+ const { result } = renderHook(() => useClassicChat(), { wrapper })
+ let pending!: Promise<boolean>
+ act(() => {
+ pending = result.current.send('Question')
+ })
+ await act(async () => {
+ await jest.advanceTimersByTimeAsync(REQUEST_TIMEOUT_MS)
+ expect(await pending).toBe(false)
+ })
+ expect(result.current.working).toBe(false)
+ expect(result.current.error).toContain('too long')
+ await act(async () => {
+ expect(await result.current.send('Retry')).toBe(true)
+ })
+ })
+
+ test.each(['history', 'stream', 'stop'])(
+ 'releases an in-flight %s when the conversation changes',
+ async (phase) => {
+ let finish!: () => void
+ const stalled = new Promise<void>((resolve) => {
+ finish = resolve
+ })
+ if (phase === 'history')
+ jest.mocked(getConversation).mockImplementationOnce(async () => {
+ await stalled
+ return {
+ messages: [{ type: 'ai', content: 'Stale' }],
+ pending_approvals: [],
+ } as unknown as Awaited<ReturnType<typeof getConversation>>
+ })
+ if (phase === 'stream') jest.mocked(readSse).mockImplementationOnce(() => stalled)
+ if (phase === 'stop') jest.mocked(cancelConversation).mockReturnValueOnce(stalled)
+ const { result, rerender } = renderHook(({ id }: { id: string }) => useClassicChat(id), {
+ wrapper,
+ initialProps: { id: 'old-chat' },
+ })
+ let pending: Promise<unknown> = Promise.resolve()
+ await act(async () => {
+ if (phase === 'stream') pending = result.current.send('Old question')
+ if (phase === 'stop') pending = result.current.stop()
+ })
+ await act(async () => rerender({ id: 'new-chat' }))
+ expect(result.current.id).toBe('new-chat')
+ expect(result.current.loading).toBe(false)
+ expect(result.current.working).toBe(false)
+ expect(result.current.stopping).toBe(false)
+ await act(async () => {
+ finish()
+ await pending
+ })
+ expect(result.current.state.messages).toEqual([])
+ await act(async () => {
+ expect(await result.current.send('New question')).toBe(true)
+ })
+ expect(jest.mocked(streamConversation).mock.lastCall?.[0].conversation).toBe('new-chat')
+ }
+ )
+
+ test('reloads history after the project changes during a request', async () => {
+ jest.mocked(useProjectScope).mockReturnValue({ host: 'https://app.example.com', projectId: 1 })
+ jest.mocked(getConversation).mockReturnValueOnce(new Promise(() => undefined))
+ const { result, rerender } = renderHook(() => useClassicChat('saved-chat'), { wrapper })
+ jest.mocked(useProjectScope).mockReturnValue({ host: 'https://app.example.com', projectId: 2 })
+ await act(async () => rerender({}))
+ expect(result.current.loading).toBe(false)
+ expect(getConversation).toHaveBeenCalledTimes(2)
+ expect(result.current.state.title).toBe('A chat')
+ })
+ test('exposes recovery and releases the lock after an accepted stream stalls', async () => {
+ jest.useFakeTimers()
+ const reader = {
+ read: () => new Promise(() => undefined),
+ cancel: jest.fn(async () => undefined),
+ }
+ jest.mocked(streamConversation).mockResolvedValueOnce({
+ body: { getReader: () => reader },
+ } as unknown as Response)
+ jest.mocked(readSse).mockImplementationOnce(jest.requireActual('@/api/sse').readSse)
+ const { result } = renderHook(() => useClassicChat(), { wrapper })
+ let pending!: Promise<boolean>
+ await act(async () => {
+ pending = result.current.send('Question')
+ await Promise.resolve()
+ })
+ await act(async () => {
+ await jest.advanceTimersByTimeAsync(60_000)
+ expect(await pending).toBe(true)
+ })
+ expect(result.current.working).toBe(false)
+ expect(result.current.historyError).toContain('Reconnect')
+ expect(reader.cancel).toHaveBeenCalled()
+ await act(async () => result.current.reload())
+ expect(result.current.historyError).toBeNull()
+ })
+ test.each(['stream', 'history'])(
+ 'exposes and resumes forms from %s without reconnecting or duplicating submissions',
+ async (source) => {
+ const form = {
+ id: 'form-call',
+ name: 'create_form',
+ args: {
+ questions: [{ id: 'q1', title: 'Scope', question: 'Which events?', options: [{ value: 'All' }] }],
+ },
+ }
+ const message = { id: 'form-message', type: 'ai', content: '', tool_calls: [form] }
+ const saved = {
+ messages: [message],
+ title: 'A chat',
+ pending_approvals: [],
+ status: 'in_progress',
+ } as unknown as Awaited<ReturnType<typeof getConversation>>
+ if (source === 'history') jest.mocked(getConversation).mockResolvedValueOnce(saved)
+ const { result } = renderHook(() => useClassicChat(source === 'history' ? 'saved-chat' : undefined), {
+ wrapper,
+ })
+ await act(async () => undefined)
+ if (source === 'stream') {
+ jest.mocked(readSse).mockImplementationOnce(async (_response, onEvent) => {
+ onEvent({ event: 'message', data: JSON.stringify(message) })
+ })
+ jest.mocked(getConversation).mockRejectedValueOnce(new Error('Connection lost'))
+ await act(async () => {
+ await result.current.send('Question')
+ })
+ } else {
+ expect(streamConversation).not.toHaveBeenCalled()
+ }
+ expect(result.current.form).toEqual({ id: 'form-call', questions: form.args.questions })
+ jest.mocked(streamConversation).mockClear()
+ let finish!: (response: Response) => void
+ jest.mocked(streamConversation).mockReturnValueOnce(
+ new Promise((resolve) => {
+ finish = resolve
+ })
+ )
+ let pending!: Promise<boolean>
+ act(() => {
+ pending = result.current.submitForm({ q1: ['All', 'Custom'] })
+ })
+ await act(async () => {
+ expect(await result.current.dismissForm()).toBe(false)
+ })
+ expect(streamConversation).toHaveBeenCalledTimes(1)
+ expect(jest.mocked(streamConversation).mock.lastCall?.[0]).toMatchObject({
+ content: null,
+ resume_payload: { action: 'form', form_answers: { q1: ['All', 'Custom'] } },
+ })
+ await act(async () => {
+ finish({} as Response)
+ await pending
+ })
+ expect(result.current.form).toBeNull()
+ jest.mocked(getConversation).mockResolvedValueOnce(saved)
+ await act(async () => result.current.reload())
+ await act(async () => {
+ expect(await result.current.dismissForm()).toBe(true)
+ })
+ expect(jest.mocked(streamConversation).mock.lastCall?.[0]).toMatchObject({
+ content: null,
+ resume_payload: { action: 'dismiss_form' },
+ })
+ expect(result.current.form).toBeNull()
+ expect(result.current.state.messages).toEqual([])
+ }
+ )
+})
diff --git a/products/mobile/src/features/chat/classic/useClassicChat.ts b/products/mobile/src/features/chat/classic/useClassicChat.ts
new file mode 100644
index 000000000000..9efe6679f3a7
--- /dev/null
+++ b/products/mobile/src/features/chat/classic/useClassicChat.ts
@@ -0,0 +1,253 @@
+import { useQueryClient } from '@tanstack/react-query'
+import { randomUUID } from 'expo-crypto'
+import { useCallback, useEffect, useRef, useState } from 'react'
+
+import { ApiError } from '@/api/client'
+import { cancelConversation, getConversation, streamConversation } from '@/api/conversations'
+import { readSse } from '@/api/sse'
+import { requestWithDeadline } from '@/api/transport'
+import { useProjectScope } from '@/auth/useProjectScope'
+import { conversationListKeys } from '@/features/chats/conversationKeys'
+import { sessionListKeys } from '@/features/chats/hooks'
+
+import { toChatError } from '../chatErrors'
+import {
+ appendClassicMessage,
+ type ClassicForm,
+ classicHistory,
+ EMPTY_CLASSIC_STATE,
+ reduceClassicEvent,
+} from './classicMessages'
+
+export function useClassicChat(initialId?: string): {
+ id: string | null
+ state: typeof EMPTY_CLASSIC_STATE
+ loading: boolean
+ historyError: string | null
+ working: boolean
+ stopping: boolean
+ error: string | null
+ send: (text: string) => Promise<boolean>
+ answer: (approved: boolean) => Promise<boolean>
+ form: ClassicForm | null
+ submitForm: (answers: Record<string, string | string[]>) => Promise<boolean>
+ dismissForm: () => Promise<boolean>
+ stop: () => Promise<void>
+ reload: () => Promise<void>
+ reset: () => void
+ dismissError: () => void
+} {
+ const scope = useProjectScope()
+ const client = useQueryClient()
+ const [id, setId] = useState<string | null>(initialId ?? null)
+ const idRef = useRef(id)
+ const [state, setState] = useState(EMPTY_CLASSIC_STATE)
+ const [loading, setLoading] = useState(!!initialId)
+ const [historyError, setHistoryError] = useState<string | null>(null)
+ const [working, setWorking] = useState(false)
+ const [stopping, setStopping] = useState(false)
+ const [error, setError] = useState<string | null>(null)
+ const busy = useRef(false)
+ const stopBusy = useRef(false)
+ const reloadBusy = useRef(false)
+ const epoch = useRef(0)
+ const controller = useRef<AbortController | null>(null)
+
+ const stream = useCallback(
+ async (
+ content: string | null,
+ resumePayload?:
+ | { proposal_id: string; action: 'approve' | 'reject' }
+ | { action: 'form'; form_answers: Record<string, string | string[]> }
+ | { action: 'dismiss_form' }
+ ): Promise<boolean> => {
+ if (busy.current) return false
+ busy.current = true
+ const generation = epoch.current
+ const active = (): boolean => generation === epoch.current
+ const conversation = idRef.current ?? randomUUID()
+ idRef.current = conversation
+ const traceId = randomUUID()
+ const abort = new AbortController()
+ controller.current = abort
+ setWorking(true)
+ setError(null)
+ setState((previous) => {
+ const next = { ...previous, error: null }
+ return content ? appendClassicMessage(next, { type: 'human', content, trace_id: traceId }) : next
+ })
+ let accepted = false
+ try {
+ const response = await requestWithDeadline(
+ (signal) =>
+ streamConversation(
+ {
+ conversation,
+ content,
+ trace_id: traceId,
+ is_sandbox: false,
+ ...(resumePayload ? { resume_payload: resumePayload } : {}),
+ },
+ signal
+ ),
+ abort.signal
+ )
+ accepted = true
+ if (!active()) return true
+ idRef.current = conversation
+ setId(conversation)
+ if (resumePayload) setState((previous) => ({ ...previous, approval: null, form: null }))
+ await readSse(
+ response,
+ (event) => {
+ if (active()) setState((previous) => reduceClassicEvent(previous, event))
+ },
+ abort.signal,
+ 60_000
+ )
+ if (active()) {
+ const saved = await getConversation(conversation, abort.signal)
+ if (active())
+ setState((previous) => ({
+ ...classicHistory(saved.messages, saved.title, saved.pending_approvals),
+ error: previous.error,
+ }))
+ }
+ return true
+ } catch (failure) {
+ if (active() && !abort.signal.aborted) {
+ if (accepted) {
+ setHistoryError('The reply was interrupted. Reconnect to load the latest messages.')
+ } else {
+ setError(toChatError(failure).message)
+ }
+ if (!accepted && content) {
+ setState((previous) => ({
+ ...previous,
+ messages: previous.messages.filter((message) => message.data.trace_id !== traceId),
+ }))
+ }
+ if (failure instanceof ApiError && failure.status === 409) {
+ idRef.current = conversation
+ setId(conversation)
+ setHistoryError('PostHog AI is still answering. Reconnect to continue this chat.')
+ }
+ }
+ return accepted
+ } finally {
+ if (active()) {
+ busy.current = false
+ controller.current = null
+ setWorking(false)
+ setStopping(false)
+ if (scope) {
+ void client.invalidateQueries({ queryKey: sessionListKeys.all(scope) })
+ void client.invalidateQueries({ queryKey: conversationListKeys.all(scope) })
+ }
+ }
+ }
+ },
+ [client, scope]
+ )
+
+ const reload = useCallback(async (): Promise<void> => {
+ const conversation = idRef.current
+ if (!conversation || busy.current || reloadBusy.current) return
+ reloadBusy.current = true
+ const generation = epoch.current
+ const abort = new AbortController()
+ controller.current = abort
+ setLoading(true)
+ setHistoryError(null)
+ setError(null)
+ try {
+ const saved = await getConversation(conversation, abort.signal)
+ if (generation !== epoch.current) return
+ const history = classicHistory(saved.messages, saved.title, saved.pending_approvals)
+ setState(history)
+ if (
+ saved.status === 'in_progress' &&
+ !saved.pending_approvals.some((approval) => approval.decision_status === 'pending') &&
+ !history.form
+ )
+ void stream(null)
+ } catch (failure) {
+ if (generation === epoch.current && !abort.signal.aborted) setHistoryError(toChatError(failure).message)
+ } finally {
+ if (generation === epoch.current) {
+ reloadBusy.current = false
+ setLoading(false)
+ }
+ }
+ }, [stream])
+
+ const stop = async (): Promise<void> => {
+ if (!idRef.current || stopBusy.current) return
+ const generation = epoch.current
+ stopBusy.current = true
+ setStopping(true)
+ try {
+ await cancelConversation(idRef.current)
+ } catch (failure) {
+ if (generation === epoch.current) setError(toChatError(failure).message)
+ } finally {
+ if (generation === epoch.current) {
+ stopBusy.current = false
+ setStopping(false)
+ }
+ }
+ }
+ const invalidate = useCallback((): void => {
+ epoch.current++
+ controller.current?.abort()
+ controller.current = null
+ busy.current = false
+ stopBusy.current = false
+ reloadBusy.current = false
+ }, [])
+ const reset = useCallback((): void => {
+ invalidate()
+ idRef.current = null
+ setId(null)
+ setState(EMPTY_CLASSIC_STATE)
+ setError(null)
+ setLoading(false)
+ setHistoryError(null)
+ setWorking(false)
+ setStopping(false)
+ }, [invalidate])
+
+ useEffect(() => {
+ reset()
+ idRef.current = initialId ?? null
+ setId(initialId ?? null)
+ if (initialId) void reload()
+ return invalidate
+ }, [initialId, reload, reset, invalidate])
+
+ return {
+ id,
+ state,
+ loading,
+ historyError,
+ working,
+ stopping,
+ error: error ?? state.error,
+ send: (text) => stream(text),
+ answer: (approved) =>
+ state.approval
+ ? stream(null, { proposal_id: state.approval.id, action: approved ? 'approve' : 'reject' })
+ : Promise.resolve(false),
+ form: state.form,
+ submitForm: (answers) =>
+ state.form ? stream(null, { action: 'form', form_answers: answers }) : Promise.resolve(false),
+ dismissForm: () => (state.form ? stream(null, { action: 'dismiss_form' }) : Promise.resolve(false)),
+ stop,
+ reload,
+ reset,
+ dismissError: () => {
+ setError(null)
+ setState((previous) => ({ ...previous, error: null }))
+ },
+ }
+}
diff --git a/products/mobile/src/features/chat/session/SessionThread.tsx b/products/mobile/src/features/chat/session/SessionThread.tsx
index c6faba684c7c..c7e785a6ac91 100644
--- a/products/mobile/src/features/chat/session/SessionThread.tsx
+++ b/products/mobile/src/features/chat/session/SessionThread.tsx
@@ -28,7 +28,7 @@ const AssistantRow = memo(function AssistantRow({ item }: { item: SessionAssista
const styles = useStyles()
return (
<View style={styles.assistant} testID="session-assistant">
- <ChatMarkdown text={item.text} streaming={!item.complete} />
+ <ChatMarkdown text={item.text} streaming={!item.complete} projectUrl={item.projectUrl} />
</View>
)
})
diff --git a/products/mobile/src/features/chat/session/types.ts b/products/mobile/src/features/chat/session/types.ts
index 2ad4a9c8fb07..17bd598c6f6b 100644
--- a/products/mobile/src/features/chat/session/types.ts
+++ b/products/mobile/src/features/chat/session/types.ts
@@ -49,6 +49,7 @@ export interface SessionUserItem {
}
export interface SessionAssistantItem {
+ projectUrl?: string
kind: 'assistant'
id: string
text: string
diff --git a/products/mobile/src/features/chat/webLinks.ts b/products/mobile/src/features/chat/webLinks.ts
index be21c71a067c..b1581a7012f7 100644
--- a/products/mobile/src/features/chat/webLinks.ts
+++ b/products/mobile/src/features/chat/webLinks.ts
@@ -4,12 +4,17 @@ import { apiUrl } from '@/api/client'
import { track } from '@/lib/analytics'
// PostHog AI writes app links as paths such as `/project/2/insights/abc`. Only http(s) links open.
-export function resolveReplyLink(url: string): string | undefined {
+export function resolveReplyLink(url: string, projectUrl?: string): string | undefined {
if (/^https?:\/\//i.test(url)) {
return url
}
if (url.startsWith('/') && !url.startsWith('//')) {
try {
+ if (projectUrl) {
+ return /^\/(?:project|organization)(?:\/|$)/.test(url)
+ ? new URL(url, projectUrl).toString()
+ : `${projectUrl}${url}`
+ }
return apiUrl(url)
} catch {
return undefined
diff --git a/products/mobile/src/features/chats/conversationKeys.ts b/products/mobile/src/features/chats/conversationKeys.ts
new file mode 100644
index 000000000000..9a460dfa2bfd
--- /dev/null
+++ b/products/mobile/src/features/chats/conversationKeys.ts
@@ -0,0 +1,5 @@
+import { type ProjectScope, scopeKey } from '@/api/reports'
+
+export const conversationListKeys = {
+ all: (scope: ProjectScope | null) => ['classic-conversations', ...scopeKey(scope)] as const,
+}