: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.
Chat
Choosing the chat version
New general chats use the Tasks agent only in project 2 on https://us.posthog.com.
Every other project uses classic PostHog AI through the existing conversations/ API.
This temporary routing rule is local to the mobile app. It does not evaluate rollout flags
or request an AI access field from the server. Organization approval and personal consent
still apply before sending messages.
Saved conversation links read their runtime from the existing conversation detail response. Report discussions and existing task links keep the Tasks path and its report-specific access exemptions. New chat starts the version selected for the current project. Demo mode keeps its local Tasks fixtures.
Classic chat supports streamed responses, saved history, follow-up messages, stopping a reply,
and approving or rejecting a requested change. Generated charts and insights link to the web.
Its composer omits the model and permission controls that only the Tasks runtime supports.
The Chats list combines unlinked conversations and tasks. Conversations with a linked task use the task row. Classic
conversation links use conversationId; Tasks links continue to use taskId and runId.
Only task rows offer Archive, because classic conversations have no reversible archive API.
The Tasks chat screen talks to PostHog AI on the task runtime. Each Tasks chat has interactive runs in a sandbox. A new chat creates the task on its first message; the Chats list reopens one by its task id. New and existing chats open as full-screen stack pages. Back returns to the previous screen or the configured default page for a direct link. The title-free header uses the shared blur and fading edge. The labeled Back chip matches Settings in style and position. Saved chats show New chat and the ellipsis in a matching bordered pill; unsaved chats show only Back. The composer clears the keyboard and safe area and receives focus after the page finishes its opening transition.
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.
Unsaved new chats hide both right-side controls until the first message creates a task.
Model, Mode, and attachment options still open as overlays.
The protocol below follows the web's taskTrackerSceneLogic.ts, runInteractionLogic.ts and runStreamLogic.ts in products/posthog_ai/frontend.
Files
| File | Role |
|---|---|
src/features/chat/ChatScreen.tsx |
The sheet: header, thread or empty state, composer, the options reducer, draft restore |
src/features/chat/chatSheetEvents.ts |
The sheet's entry from the route params, and the opened and closed events |
src/features/chat/ChatAccessGate.tsx |
The organization AI approval and the personal consent before the composer (see AI consent) |
src/features/chat/session/useSession.ts |
useSession({ taskId?, runId? }): create, follow, send, sync options, resume, stop, answer, reset, demo replies |
src/features/chat/session/sessionRun.ts |
Pure request bodies: the create shapes, run fields, the set_config_option plan, the tracked run config |
src/features/chat/session/sessionReducer.ts |
Folds run log lines and stream frames into the thread, as the web's foldLogFromCheckpoint does |
src/features/chat/session/sessionDisplay.ts |
Groups thoughts and tool calls into activity rows, error copy |
src/features/chat/session/sessionTurn.ts |
SessionTurnTracker: one mobile_session_finished per turn the person started |
src/features/chat/session/SessionThread.tsx |
The thread, its rows, the PR card and the status line |
src/features/chat/session/SessionDecisionPanel.tsx |
The notice line and a pending question, plan approval or permission |
src/features/chat/messageQueue.ts |
The queue reducer, the hold, and the queue, drain and Send now rules |
src/features/chat/QueuedMessages.tsx |
The queue banner above the composer: count, rows, remove and Send now |
src/features/chat/chatRunOptions.ts |
ChatRunOptions (model and permission mode), its reducer, the chip label, seeding from a run |
src/features/chat/ChatOptionsSheet.tsx |
The Model and Mode pages in a sheet over the chat |
src/features/chat/contextPrompt.ts |
The leading context blocks, bareQuestion, stripInjectedContext |
src/features/chat/objectContext.ts |
The issue and recording item types, objectContextFromParams, their trusted lines (see Object context) |
src/features/chat/attachments/ |
Files in the composer: the limits and content types (attachmentRules.ts), the pickers, the three-step upload (uploadAttachments.ts), useComposerAttachments, the Attach sheet and the file chip (see Attachments) |
src/features/chat/chatErrors.ts |
Maps HTTP and network failures to copy, including the PostHog Desktop gate |
src/features/chat/*.tsx |
Composer, ContextChip, MentionPopover, ChatEmptyState, ChatMarkdown, ChatErrorBubble, ChatProgressLine, UserBubble |
src/features/chats/ |
The Chats screen: list, search, day groups and useChatList() (see DESIGN.md) |
src/demo/sessionThreads.ts |
Demo run logs keyed by the demo task ids in src/demo/chats.ts, and the demo replies |
The transport is src/api/tasks.ts, shared with the hand-off (see HANDOFF.md).
Every request carries X-PostHog-Client-Platform: mobile, so run/ never reuses a warm run a web composer booted.
AI consent
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'smembership_levelfromOrganizationSerializerin/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 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.
Classic chat refreshes history whenever it opens, even while the cached response is fresh, and reuses that download. An accepted message leaves draft recovery as soon as the server accepts it, while the reply continues streaming. If its stream disconnects or times out, classic chat checks the saved conversation automatically without sending the message again. Completed replies and pending decisions load from that saved state. If recovery still needs a connection, received messages stay visible with Reconnect. Linked conversations stay visible when their task is absent from the list. Opening a linked chat checks its conversation runtime before continuing. If one chat history source fails, Chats keeps the loaded rows and offers a retry for the remaining history. Classic chat shows draft save failures with a retry action, and checks AI approval before each message or approval response.
Composer drafts
The message input wraps long text onto multiple lines and grows up to 120 points tall. Longer drafts scroll vertically within the input. The keyboard's Send action sends the message and keeps the keyboard open for a follow-up.
Text and attached report IDs are saved separately for each task, each report discussion, and
the new-chat composer. Native drafts use encrypted device storage, scoped to the account,
host and project, with at most 50 drafts per project. Changes save after 400 ms of idle time
and flush when the composer closes or the app backgrounds. Opening a saved chat restores its
draft after storage loads. If a save fails, the composer keeps the text and shows an unsaved-draft
notice with Retry save. The notice stays until saving succeeds. When saved messages reach the
device limit, remove a queued message to free space, then retry before closing the chat.
Close and background saves use the same storage checks; a failed save leaves previously saved
messages intact.
mobile_chat_draft_restored is captured with text_length and report_count when the restored draft has text.
A successful send clears the submitted text. A failed send keeps it, and a delayed completion does not replace text typed for a later message. Sign-out or session expiry clears the account's drafts. Demo drafts stay in the current composer; the web preview stores drafts in memory only. Picked files are not part of a draft. They stay in memory and go when the sheet closes (see Attachments).
Rich replies
PostHog object tags render as inline links to the selected host and project. Standalone
display="block" insight tags show the saved name and description; SQL tags show a three-line
preview with Show all. Insight summaries use refresh=force_cache, so opening a reply does not
run its insight queries. A reply renders at most ten cards, then uses inline links. Unknown
object kinds keep their labels, tags inside code stay literal, and unfinished tags stay hidden
while the reply streams. The object registry is generated from posthog/object_tags/kinds.py
into this app so standalone builds do not depend on the desktop app.
Closed Mermaid fences render offline in a native WebView. The bundled renderer uses strict
mode and a policy that blocks network requests; navigation is disabled. Wide diagrams scroll
horizontally. Incomplete, invalid, or remote-image diagrams stay as code. The web preview also
uses the code fallback. Adding this renderer requires a new native build with
react-native-webview before distributing an update that uses it.
mobile_chat_diagram_failed is captured once per diagram with reason (timeout, render_error, load_error, process_gone or open_window).
A tap on an object link, an insight card, a SQL card or a markdown link opens it in the browser.
mobile_chat_link_opened is captured after the system opens it, with source (object_chip, insight_card, query_card or markdown),
object_kind (the registry kind, null for a markdown link) and app_link (a markdown link that was an app path).
Insight summaries need the insight:read OAuth scope. Existing sessions need a new sign-in,
and the server's mobile OAuth application must allow the scope.
Starting a chat
The first send creates a task, then starts an interactive run on it.
Both calls go through withWarmRetry, which retries a 503 warm_run_activation_unavailable with the server's retry token.
The bubble shows at once and is taken back if the start fails.
Two create shapes (chatStartRequests in sessionRun.ts):
PostHog AI chat (no report, or more than one report attached).
POST tasks/:{ "title": "", "description": "<bare question>", "origin_product": "posthog_ai", "initial_permission_mode": "auto", "pending_user_message": "<context blocks>\n\n<question>" }The server generates the title from
descriptionin the create request, so the response already carries it. The app sends nobranchand norepository, so the create never claims a warm run.Inbox "Discuss" (exactly one attached report).
POST tasks/:{ "title": "<report title>", "description": "<prompt>", "origin_product": "signal_report", "signal_report": "<report id>", "signal_report_task_relationship": "discussion", "signal_report_discussion_question": "<question as typed, at most 4000 characters>", "pending_user_message": "<prompt>" }The server exempts a repo-less report discussion from the PostHog Desktop gate.
signal_report_discussion_questionis the trimmed question as typed, without the prompt's tag escaping, cut at 4000 code points. Every later fresh run of a task with asignal_reportcarriesrun_source: "signal_report"andsignal_report_id, also when the Chats list opens it. It counts toward the report's discussion task limit (see Errors).
Then POST tasks/{t}/run/, unless the create answered with a latest_run:
{ "mode": "interactive", "pending_user_message": "<context blocks>\n\n<question>", "initial_permission_mode": "auto" }
mode: "interactive"is required: only interactive runs relay approvals and questions to the client.- A picked model adds
runtime_adapter,modelandreasoning_effort(left out for a model without effort control), and maps the mode onto that harness. An untouched model sends only the mode, so the server applies the stored default. - The app follows
run.idfrom the response (latest_runon older servers). - A refused run (any 4xx, or a 503) deletes the task it just created with
DELETE tasks/{t}/, so no empty row stays in the Chats list. A 5xx other than 503 or a lost connection may still have started a run, so the task stays, and the next message first looks for that run (see Follow-ups and resume). - Closing the sheet or tapping New chat does not abort the create or the run start, so the app always learns the task id and whether a run started. When the create finishes after the chat was dropped, the app deletes the new task and starts no run.
Options
The composer has a Model chip and a Mode chip after @.
They open ChatOptionsSheet with the hand-off's ModelPage and ModePage.
mobile_chat_options_opened is captured with page (model or mode) when a chip opens the sheet.
mobile_chat_option_changed is captured with option (model, effort or mode) only.
The resolved default model is selected when no model is pinned: its row has a tinted background, bold model and Default labels, and a checkmark. A known default reasoning effort uses the same filled pill as an explicit choice. Picking another model or resetting to default moves these selection indicators to the active options.
- Seeding. When an existing chat opens, the sheet seeds the options from
session.runConfig: the run's model and effort as a pinned model, and its permission mode. A new chat keeps "Default" after sending, even when the run resolves a model and effort. Its model changes only when the person picks a model or effort. A run with no known harness or model seeds "Default"; an unknown mode seeds Auto. Seeding stops once the person picks anything in this sheet, and New chat starts seeding again. While seeding, the Mode chip follows the mode the stream reports (current_mode_update), also for a run the app started. After a pick, a new mode from the stream still replaces the picked mode, as the web drops its mode override: the agent can leave Plan on its own when a plan is approved. - Enabled while the agent is idle, the history has loaded, no send is in flight and no decision waits, also on an open chat.
- One harness per run. A live run cannot switch between Claude Code and Codex. On an open chat the Model page lists only the models of the run's harness, and an untouched model keeps that harness. The hook still refuses a cross-harness pick with a notice.
- The mode that is sent. The Mode chip shows the mode mapped onto the harness the next message runs on (
chatPermissionMode), and the sheet sends that mode.
Live changes: set_config_option
A pick alone sends nothing.
On the next message to a live run, useSession first sends one command per changed value, in the web's order (model, effort, mode):
{ "jsonrpc": "2.0", "method": "set_config_option", "params": { "configId": "model", "value": "claude-opus-5-5" } }
- "Changed" means different from what the run last had: what it started with, then each change the app applied (
TrackedRunConfig). A mode the app set wins over the mode the stream reported before it, until the stream reports a mode again; then the stream's mode wins, as the web clearssentModeonsetCurrentMode. - The starting mode is the run's
state.initial_permission_modefrom therun/response, which can differ from the mode sent. - Each change is recorded as it succeeds, so a later failure resends only what did not go out.
- 503
sandbox_not_readyretries for up to 10 seconds, honoringRetry-After. - 409 means the run ended. The message then starts a resume run that carries the options.
- A 400 (such as a model outside the run's gateway pin), a 502, or a JSON-RPC
errorin the body stops the send before itsuser_message, shows the notice and restores the draft.
Follow-ups and resume
- Live run.
POST tasks/{t}/runs/{r}/command/withuser_messageand the context-wrapped text. Success isresult.queued. The bubble moves to where the turn starts when the agent echoes it. - No run known. After a first run that failed with a 5xx or a lost connection, or on a task opened without a run,
GET tasks/{t}/comes first. A livelatest_rungets the message and is followed; an ended one is resumed. Only a task with no run gets a fresh run. - Ended run, or a 409 on
user_message.POST tasks/{t}/run/withmode: "interactive",resume_from_run_id,pending_user_message, and the run fields. An untouched model sends no triple, so the server keeps the previous run's selection; the mode maps onto the previous run's harness. Nobranch: a resumed run keeps its base branch. - Queue. A message sent while the agent works, while a send or an answer is in flight, while a decision waits, or behind earlier queued messages goes into a queue above the composer instead (
messageQueue.ts,QueuedMessages.tsx), as on the web. The banner shows "N queued" and one row per message, each with a remove control. During delivery it shows "Sending queued messages" and hides the recovery warning until delivery settles. Queued text is saved with the chat's draft in native secure storage before the composer clears. Task adoption waits for pending queue writes and carries live files, cleared composer text, and Stop holds into the saved task. A failed storage read aborts the save and leaves existing queues intact. A per-project storage budget refuses additional text while preserving saved messages; removing messages still works if an older store exceeds the limit. While the agent works and the input has text, Send shows beside Stop, which turns into an outline button. - Automatic drain. When the turn ends and nothing else is in flight or waiting, the queued rows go out as one message, joined by blank lines. A run that has ended takes the queue too: the send resumes it, as for any follow-up.
- Send now. Sends the queue into the live turn at once with
params.steer: trueonuser_message, when the session reportscanSteer; otherwise it goes as an ordinary follow-up. It is disabled with "Answer the agent first" while a decision waits, and with "Wait for the agent to start" while the turn runs but the stream has not shown the agent generating yet. It also waits for saved messages and conversation history to load. If history fails, retry loading it before sending recovered messages. The reason shows under the banner, because a phone has no tooltip. - Hold. Stop holds the queue, so it does not go out when the stopped turn ends; the banner then says "N queued, review before sending". A new message lifts that hold. Acknowledged rows are removed even if Stop interrupts delivery; any remaining rows keep the Stop hold. Delivery keeps its saved rows until acknowledgment. A failed delivery holds them; only Send now sends them again, because the failed send may have reached the agent.
- Closing the sheet or using Android back preserves queued text separately from the composer. Reopening holds the recovered queue for review before Send now. New chat waits while a taskless send or queue is pending, so those messages cannot drain into a different conversation.
- Files. A queued message takes the composer's files with it, as on the web, and the row shows "1 file" or "N files". The drained message, or Send now, carries the files of every row in queue order. The 10-file cap applies per composer message, not to the join. A failed delivery puts the rows back with their files. Removing a row drops its files. Closing the sheet or New chat drops the queued files, as closing drops unsent composer files. Recovered rows record that files are missing and cannot send until their text is copied, removed, and attached again. File paths and contents are not saved. Attach stays enabled while messages queue. Files of a direct send still in flight stay with that send and never join the queue.
mobile_session_queuedis captured withqueue_lengthwhen a message joins the queue,mobile_session_queue_removedwithqueue_lengthafter a row is removed, andmobile_session_queue_sent_nowwithqueued_countandsteer(the session could steer at the tap).mobile_session_sentis captured withnew_task,resumed_run,report_count,attachment_count,model,reasoning_effort,permission_mode,delivery(steerwhen the agent accepted a steered message,queuefor a drained queue, elsedirect) andqueued_count. Model and mode changes still go out asset_config_optionbefore a steered message, as on the web.mobile_session_send_failedis captured withcodeandnew_taskwhen a send shows a notice.codeisupload_failed,config_rejected,command_failed,run_not_started,warm_run_unavailable, or theChatErrorkind fromchatErrors.ts.mobile_session_finishedis captured once per turn the person started, withstatus,duration_s(from the accepted send) andhad_decision. A steered message joins the turn it steers, so it adds no event of its own.statusiscompleted(the turn ended),failed(the run failed, or the turn ended with a new run error),cancelled(the run was cancelled without Stop),stopped(the turn or run ended after Stop) orabandoned(the sheet closed or New chat dropped the chat first).
Attachments
The Attach button opens a sheet with Photo library and Choose a file.
Photo library uses expo-image-picker (images only, never the camera); Choose a file uses expo-document-picker (any type).
Both allow several files. The keyboard drops before the sheet opens and comes back after the pick.
The limits and content types are the web's (products/posthog_ai/frontend/utils/attachments.ts):
- Any file type. At most 30 MiB per file, 10 MiB for a
.pdf. An empty file is refused. - At most 10 files per message. At 10 the Attach button is dimmed, and its accessibility hint says "Up to 10 files fit in one message"; no visible text says it. Files picked past the cap are left off, and one line says how many.
- The content type comes from the extension, never from the picker. An unknown extension is
application/octet-stream; a file is an image when its type starts withimage/. iOS gives a converted photo the name of its original (IMG_0001.HEICfor a JPEG), so the extension of the file the picker wrote wins. - A refused file shows in the notice line above the composer, such as "notes.txt is empty." or "slides.pdf is over the 10 MB limit for PDFs."
Picked files show as chips after the report chips: an image with a small thumbnail, any other file with a document icon, each with a remove ×. They live in memory only, never in the draft store. Text stays required: a send with files and no text does not go, as on the web.
Files upload when the message sends, in three steps per batch, as the web's artifactUpload.ts does:
POST .../prepare_upload/with{ "artifacts": [{ "name", "type": "user_attachment", "source": "posthog_ai", "size", "content_type" }] }. The answer keeps the request's order, and each entry has anid, astorage_pathand apresigned_post.- A
multipart/form-dataPOSTto eachpresigned_post.url, all files at once. Everypresigned_post.fieldsentry goes first, then the file asfile. It is a plainfetch, so the PostHog token never goes to S3. POST .../finalize_upload/with eachid,name,type,source,storage_pathand the extension'scontent_type.
One failed file fails the send, so a message never arrives with fewer files than the person attached. The order of a send:
- New chat.
POST tasks/(nobranch, so it never claims a warm run and never answers with a run), then the staged upload against the new task (tasks/{t}/staged_artifacts/...), thenPOST tasks/{t}/run/withpending_user_artifact_ids. A failed upload deletes the new task, as a refused run does. If a create ever answers with a run while the send has files, the send fails the same way, because that run would never get the files. - Live run. The changed options, then the run-scoped upload against the current run (
tasks/{t}/runs/{r}/artifacts/...), thenuser_messagewithparams.artifact_ids. - Ended run, or a 409. Run-scoped ids belong to that run only, so the files upload again, staged against the task, and the resume
run/carriespending_user_artifact_ids. - Demo. Nothing uploads. The chips and the bubble show the files, and the canned reply plays.
While a send uploads, its chips show a spinner instead of ×, and Attach is dimmed. A successful send clears its chips.
A message that goes into the queue takes the composer's files with it (see Follow-ups and resume).
A failed send keeps them, puts the text back, and the notice says "Your files didn't upload. Try again."
Every failure while the files upload (prepare, the S3 post, finalize) shows this copy and counts as upload_failed, also when the server sent its own copy.
The first failed S3 post stops the other posts of the batch.
Closing the sheet or New chat aborts an upload in flight.
The bubble shows a picked image as a thumbnail from the file on the device and any other file as a chip with its name.
The echo names each file by a resource_link (or image) block whose URI ends in .posthog/attachments/<runId>/<artifactId>/<name>.
The reducer reads the ids from that path, keeps one entry per artifact, and fills the first entry of the same name that has no id yet, so the optimistic bubble keeps its thumbnail.
It also keeps each artifact's device file, so a resume, which draws the thread again from the log, keeps the thumbnails of files sent from this sheet.
A message with files and no text, which another client can send, has no bubble of its own: its files join the previous bubble, as on the web.
A file from history has no local copy and shows by name only (see GAPS.md).
mobile_chat_attach_menu_openedwhen the sheet opens.mobile_chat_file_attachedwithsource(photosorfiles),attached_count(files in the composer after the pick) andimage_count(images in the pick).mobile_chat_file_rejectedwithreason(empty,too_large,unreadableortoo_many), once per refused file and once per pick that went past the cap.mobile_chat_file_removedwithattached_countwhen a chip's × removes a file.mobile_chat_file_upload_failedwithstatus(the HTTP status of prepare, finalize or the S3 post, when there was one) andnew_task.- No event carries a file name or its content.
Reading a run
GET tasks/{t}/gives the title and the latest run. With arunIdthe sheet follows that run throughGET tasks/{t}/runs/{r}/.- Ended run.
GET tasks/{t}/runs/{r}/logs/returns the whole resume chain as JSON lines, folded into the thread. - Live run.
GET tasks/{t}/runs/{r}/stream/without a cursor replays the stored log, then streams. The app buffers catch-up frames and shows the history together, then streams new replies. Catch-up ends on a keepalive, stream completion, or 250 ms of silence after a Redis frame; silence during durable-log replay never ends it. Opening a thread scrolls straight to the latest message without animation. Reconnects follow the hand-off rules (see HANDOFF.md). A reconnect keeps the cursor and buffered history through a transport rotation, and buffers each new connection's backlog before showing it. A replay after a lost cursor rebuilds the thread with a fresh event deduplication set, so previously displayed or buffered frames remain in the full replay. mobile_session_resumedis captured with the run status.mobile_session_load_failedis captured withcode(theChatErrorkind) each time the thread shows "Couldn't load this session".mobile_session_load_retriedis captured when the person taps Try again there.
Stop
Stop sends the cancel command ({ "jsonrpc": "2.0", "method": "cancel" }), which interrupts the turn and keeps the run alive.
The app sends it only after the stream showed the agent generating, because a cancel before that drops the run's first message; until then the notice says "The agent hasn't started yet."
A JSON-RPC error in the answer shows "Couldn't stop this run. Try again."
mobile_session_stopped is captured when the cancel goes out. The turn's mobile_session_finished then has status: stopped.
Decisions
Permission requests go through the hand-off tool policy (toolPolicy.ts, see HANDOFF.md):
the app allows built-in tools and PostHog exec calls on the person's behalf and asks about the rest.
A question, plan approval or permission shows in SessionDecisionPanel and replaces the composer while it waits.
The answer goes as a permission_response command and shows in the thread as the person's bubble.
mobile_decision_shown is captured once per request with kind (question, plan or permission), surface: chat and replayed (the request was in the stored log).
mobile_decision_answered follows with task_id, kind, picked_option and surface: chat.
Errors
ChatErrorNotice owns the message surface, screen-reader alert, optional recovery actions and 44pt Dismiss button.
SessionDecisionPanel supplies the message and callbacks. Recovery actions wrap below the message on narrow screens.
New-chat suggestions scroll above the notice and composer. Tap empty space or drag the suggestions area to dismiss the keyboard.
Tapping a suggestion still fills the draft in one tap.
- A send, answer or stop that fails shows a bordered notice above the composer, wrapping to fit its full text.
A failed send also sets
unsentText; the sheet puts it back into an empty input once. - PostHog Desktop gate.
run/anduser_messageanswer 403code_access_requiredfor a user the gate refuses. The message is undererror, and the app shows it as is, because it names the reason (Startup plan, prepaid credits). A 503desktop_access_unavailablesays "We couldn't verify PostHog Desktop access. Try again." A 429usage_limit_exceededorbilling_limitshows the server copy.cancelandset_config_optionare not gated. Only the Inbox "Discuss" shape is exempt. - Report discussion limit. A one-report chat counts toward the report's discussion task limit.
POST tasks/andrun/answer 429signal_report_task_capwith the copy undererror; the app shows it, else "This report has reached its chat limit. Try again later." - A 400 shows the server copy (
detailorerror, such as "Invalid resume_from_run_id" or a model the account cannot use), else a generic line. - A 502 "Failed to queue" says the message did not reach the agent.
- The run's own failure (
error_message,_posthog/error) shows inline in the thread.
Context block
chatPrompt(question, context) ports the web's wrapWithPosthogContext.
The web thread strips only leading blocks, so the blocks lead and the question follows.
<posthog_trusted_context>
- A user sent the message after this block about the PostHog Inbox report at {report url}. If it is a question, answer it; if it asks for action, carry the action out and summarize what you did.
- {REPORT_DISCUSSION_STATE_INSTRUCTIONS}
- {NO_CHECKOUT_INSTRUCTIONS}
</posthog_trusted_context>
<posthog_untrusted_context>
{the web's hardening header}
- signal_report {report id} ("Report: {title}")
{the web's reminder}
</posthog_untrusted_context>
{question}
- The trusted block goes only with attached reports. Its first line names the report by the web URL the app builds from the signed-in host, as the web's
discussReportInstructionsdoes. When the report cannot be acted on, the first line becomes "Answer this question about the PostHog Inbox report at {report url}. The question is the message after this block." and the state instructions drop out. - The web has no framing for several reports. The app names them all ("these PostHog Inbox reports: {url}, {url}") and adds "The instructions below speak of one report. Apply them to each of these reports on its own."
- With no report attached, the first message of a new chat lists up to 20 inbox rows as
signal_reportlines in the untrusted block. Follow-ups and opened chats send no inbox list. - The agent reads report details through the inbox MCP tools, so the prompt carries no summaries.
defangescapes context tags and line breaks in every item field;bareQuestionescapes context tags in the question.descriptionand the bubble get the bare question.stripInjectedContextremoves leading blocks from echoes and logs.- The blocks go with every message while a chip stays attached, because the chip says it is attached.
Object context
The issue and session screens open the sheet with entry (issue or replay), objectType, objectId and objectLabel.
objectContextFromParams in objectContext.ts keeps only the two types the web uses, error_tracking_issue and session_recording.
The message carries one untrusted item line, - {type} {id} ("{label}"), and one static trusted line that names the investigating skill and the fetch tool (query-error-tracking-issue, session-recording-get).
The object shows as a removable chip with the issue or recording icon. While it is attached, @-mentions are off and report chips stay hidden, because a message frames one kind of context.
New chat drops it.
Rendering
- Assistant text renders as markdown with
react-native-markdown-display, styled fromsrc/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, 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_expandedis captured withrunningandtool_countwhen the person opens one. - Background-task notices (including checkmarked completion summaries) align left and show at most two lines by default. Notices that wrap beyond two lines offer Show more to read the full text and Show less to return to the preview. Expanding or collapsing a notice pauses automatic scrolling so it stays in view. Scrolling back also pauses automatic scrolling; scroll to the bottom to follow new messages again.
- Known PRs remain available while execution is active, idle or terminal. Their state is separate from execution; a discovered URL starts unknown until the report supplies authoritative state.
- Report task status opens that implementation task, including idle and completed runs that can resume. The Chat button beside the report action pill starts a separate report discussion. A completed turn alone does not create an attention request; the task composer provides continuation.
New chat
The compose button is available in a saved chat's header.
It drops the open task (or the one the first send created), clears the text and attached reports, and resets the options to Default and Auto.
The header has no chat title.
The empty state with suggested prompts shows while there is no task and no message.
mobile_chat_suggestion_picked is captured with source (report for the report's own prompts, else default), index and report_count; never the prompt.
@ or the @ button opens the report list. mobile_chat_mention_opened is captured with trigger (typed or button),
mobile_chat_report_attached with attached_count, and mobile_chat_report_removed (a chip's ×) with attached_count and initial (the report the sheet opened with).
Page lifecycle
The navigator keeps one chat screen. Opening another chat reuses that screen and loads fresh conversation state. A notification for the chat already on screen leaves its session, draft and scroll position intact, including a chat started from the composer. A notification for a different chat replaces the open chat, so one Back returns to the screen underneath. Starting New chat does not prevent a later notification from reopening the previous conversation.
Changing the selected account, host or project closes an open chat and aborts its scoped work. Callbacks captured in the old scope cannot send to the newly selected project. A send waiting for encrypted draft storage is cancelled by New chat or closing the sheet, and its text remains recoverable in the original draft.
Chat pauses streams while offline. Task and history reads resume when the connection returns. When the connection returns or the app enters the foreground, chat resumes the same run with its saved cursor and transcript. The Reconnect button also restarts streams after the retry limit. Authentication, permission and missing-run errors prevent automatic recovery. Recovery does not resend messages, answers or run creation requests.
A connected device can still fail to reach PostHog. Stream retries and the idle timeout handle these failures. Repeated connected events do not reset the retry limit.
The page opens from the bottom bar's compose button, a report's Chat button, a report's task status, an inbox row's menu and the Chats tab.
The route takes an optional entry param; chatSheetSource falls back on report with a reportId, task with only a taskId, else compose.
mobile_chat_sheet_openedis captured once per open withentry(chats_list,chats_search,chats_empty,compose,report,report_task,inbox_menuortask),origin(the Chats row's origin, else null),has_context(a report is attached) andresumed(an existing task opened).mobile_chat_sheet_closedis captured on unmount, also after an Android back, withentry,messages_sent,new_chats(New chat taps),had_runanddwell_s.
Chats list
useChatList() (src/features/chats/hooks.ts) lists the person's sandbox sessions:
GET tasks/?created_by={user id}&ordering=-last_activity_at&basic=true&limit=30.
created_bytakes the numeric user id fromGET /api/users/@me/. A session restored from before the app stored it has none: the hook callsreloadAccount()once and shows loading until it settles, then the list, the account error with Try again, or an empty list.chatListFromSessions(src/model/adapters/chats.ts) mapsorigin_productto the row's origin:posthog_aiis a chat,signal_reporta report, anything else a session. The server already leaves out archived tasks.- A row opens the sheet with
{ taskId, entry, origin }:entryischats_searchwhile the search field has text, elsechats_list.mobile_chat_sheet_openedcarries both; the list sends no event of its own for a row. mobile_chats_searchedis captured withquery_lengthandresult_countonce per query, after typing pauses.mobile_chats_refreshedis captured withtrigger(pullorretry).mobile_chats_load_failedis captured withcode(theChatErrorkind) each time the list shows "Couldn't load your chats".- A 403 or 404 from tasks means the user has no sessions and shows the empty state.
chatGroups.tslabels rows by local calendar day and filters titles on the device.- A long press (or the screen reader's "Show actions") opens the row menu (
ChatRowMenu) with Archive.useArchiveChat()hides the row at once and sendsPATCH tasks/{id}/with{ "archived": true }; the server stampsarchived_atand leaves the task out of every later list. The toast offers Undo, which puts the row back and sends{ "archived": false }after any pending archive request finishes. Archive and Undo update linked conversations in the cached history too, so they cannot recreate a hidden task row. Repeated archive submissions share the pending request. A failed archive puts the row back and shows "Couldn't archive this chat. Try again." A failed Undo hides the row again and shows "Couldn't restore this chat. Try again." There is no archived list in the app: the web app and PostHog Desktop show archived tasks. mobile_chat_row_menu_opened,mobile_chat_archivedandmobile_chat_archive_undonecarry the row'soriginandstatus;mobile_chat_archive_failedcarriesaction(archiveorrestore) andcode(theChatErrorkind).- Regaining focus (closing the sheet) invalidates the list, so a new chat appears with its title.
- Classic conversations are listed once; their mirrored tasks are omitted.
Demo mode
No request goes out, and attached files do not upload.
A new chat gets a demo task id, echoes the message and plays DEMO_REPLY through the session reducer: streamed chunks, the final message, then a turn end.
Demo sessions replay the run logs in src/demo/sessionThreads.ts:
"Fix the flaky checkout test" ended with a PR, "Add dark mode to settings" waits on a question,
and "Migrate billing webhooks" failed. A send plays DEMO_REPLY, an answer plays DEMO_ANSWER_REPLY, and Stop cuts the reply short.
The model list is the static catalogue, and the options change nothing about the reply.
Archiving a demo chat hides it in the demo store until the demo refreshes or resets.