: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.
PostHog AI agent-run surface — consumer guide
This directory is the conversation-agnostic agent-run UI: a library that renders and drives a streamed agent run — the thread, tool cards, approvals, the composer. If you're embedding a run, showing a status badge, or registering a product's tool cards, you consume it from here.
Building on the surface (adding a thread-item type, a permission rule, stream telemetry)? That's the contributor guide —
AGENTS.md— not this file.
Integrating a product scene with the agent — attaching context, injecting instructions, reacting to tool calls, registering your product's tool cards? Start at
../README.md, which walks those seams end to end and routes you back here for the detail.
1. How to import — the one rule
Import from a domain-scoped api/<module> entry. Never reach into deep internal paths
(../components/..., ../logics/...); the api/ modules are the contract and internal files move behind
them. The products/* path alias is configured in tsconfig, so the import is absolute:
import { ReadonlyRunSurface } from 'products/posthog_ai/frontend/api/readableRun'
import { isTerminalRunStatus } from 'products/posthog_ai/frontend/api/logics'
Prefer the narrowest module that does the job. The split exists to preserve code-splitting: the
side-effectful tool registry (api/tools) and the markdown/virtualization-heavy thread (api/primitives)
must not leak into a bundle that only needs a status helper from api/logics. A status badge that imports
a fat path drags presenters and the registry into its chunk; importing api/logics alone does not.
In the same way, an eager surface that only needs an input box imports Composer from api/composer,
while chart and recording widgets use api/dataWidgets.
This keeps the query and replay code out of an input-only surface.
There is deliberately no root index.ts barrel — a barrel that re-exports every tier would
re-introduce the exact bundling problem the split solves. Always import an api/<module>.
2. Which surface do I use?
Pick the lowest tier that does the job.
| Tier | Module | What's in it | Use when |
|---|---|---|---|
| 1 — Prepackaged surfaces | api/readableRun + api/runSurface + api/runner |
ReadonlyRunSurface (lazy, code-split read-only embed); the RunSurface compound (Root + slots, eager) for custom layouts; EmbeddedRunner (lazy TaskTracker workspace for inline hosts) |
"Just show a run" → ReadonlyRunSurface (inbox embeds). "Drive a run / custom layout" → RunSurface (tasks). "Embed the /tasks workspace" → EmbeddedRunner (Max). |
| 2 — Compound primitives | api/primitives + api/composer + api/dataWidgets |
Thread + atoms (.Message/.Markdown/.Reasoning/.Failure/.Activity/.ToolCall), ThreadView, AttachedContextBar, task navigation items and filters, QueuedMessageList, RunLogSkeleton, activity primitives + RunActivity, message presenters, permission/question/resource surfaces; api/composer holds Composer.* and the quill composer frame |
Custom layout, shared navigation, or a bespoke/compact thread. An input box alone imports only api/composer. Chart and recording widgets use api/dataWidgets. |
| 3 — Headless logic + types | api/logics + api/types |
runStreamLogic, runInteractionLogic, tasksLogic, status helpers (isTerminalRunStatus, INITIAL_PERMISSION_MODE), thinking-message helpers, context injection (useAttachedContext, contextPickerLogic), tool-stream subscriptions (toolStreamEventsLogic, useToolStreamListener); folded-thread, task, and tool types |
Status badge, automation, context injection, task navigation, tool-event listeners — no presenters or registry. |
| 4 — Extension seam | api/tools |
toolRegistry, lookupToolRenderer, GenericMcpToolRenderer, DataToolRow, ToolActivity, FilePath, diff helpers |
Your product renders tool cards (insights, dashboards…). Declare them in your product list and include it in the central manifest. |
The Tier 1 surfaces are built on api/primitives (Tier 2), which consumes the headless
api/logics/api/types (Tier 3). Going down a tier trades convenience for control and a smaller chunk.
ReadonlyRunSurface is lazy by default — code-split behind a RunLogSkeleton Suspense fallback —
because the embeds that use it (the inbox detail views) show it as a secondary panel. The RunSurface
compound (api/runSurface) is eager: import it only where the surface is the primary content of an
already-code-split route (the /tasks runner scene composes its own live-composer layout), so it doesn't pay
a second chunk fetch + Suspense flash for the one thing the route exists to show.
3. Recipes
Each recipe shows the granular import to copy.
Read-only embed (inbox-style)
import { ReadonlyRunSurface } from 'products/posthog_ai/frontend/api/readableRun'
;<ReadonlyRunSurface taskId={task.id} runId={run.id} interaction="read-only" />
The prepackaged, lazy read-only surface: thread (with the context-usage footer for a live run), no composer and no
approval prompt. It streams fresh frames while running when interaction='live', and replays the snapshot
once when 'read-only'. This is what all three inbox embeds drop in.
Live embed with composer (tasks-style; caller owns the composer + draft/queue)
Compose the RunSurface compound (api/runSurface, eager) and pass your composer UI as the
RunSurface.Composer children — the slot owns prompt-vs-composer precedence and the bootstrap gate (optimistic startup keeps the composer visible); you
own the composer. See scenes/TaskTracker/components/TaskRunChat.tsx for the full wiring.
import { RunSurface } from 'products/posthog_ai/frontend/api/runSurface'
import { Composer } from 'products/posthog_ai/frontend/api/composer'
import { QueuedMessageList } from 'products/posthog_ai/frontend/api/primitives'
import { runInteractionLogic } from 'products/posthog_ai/frontend/api/logics'
// Bind runInteractionLogic (the follow-up/queue facade) keyed by the same runId RunSurface.Root binds.
const { draft, isSubmitting, isBusy, queuedMessages } = useValues(runInteractionLogic(props))
const { cancelRun } = useActions(runInteractionLogic(props))
;<RunSurface.Root taskId={task.id} runId={run.id} interaction="live">
<div className="@container/thread flex flex-col h-full overflow-hidden">
<div className="flex-1 min-h-0">
<RunSurface.Thread />
</div>
<RunSurface.Composer>
<Composer.Root
value={draft}
onChange={setDraft}
onSubmit={submit}
loading={isSubmitting}
isTurnActive={isBusy}
onStop={() => cancelRun()}
>
{/* …Composer.Frame / Field / Textarea / Submit… */}
</Composer.Root>
</RunSurface.Composer>
<RunSurface.ContextUsage />
</div>
</RunSurface.Root>
Pass isTurnActive + onStop to make the send button a Stop button while the agent is working a turn and
the input is empty (clicking cancels the run); with drafted text it stays Send and queues the follow-up.
Omit both for a send-only composer.
Task creation and resumption keep the submitted draft and unsent context while a warm run starts. Web retries confirmed startup failures for up to 20 seconds, then leaves the message available to submit again.
Custom layout via the RunSurface compound
RunSurface.Root (Tier 1, api/runSurface) binds the stream logic and bootstraps the run; the slots
(.Thread/.Composer/.ContextUsage) compose into any layout — there is no default. Omit
RunSurface.Composer for a no-input surface (that's exactly what ReadonlyRunSurface does); render it with
composer children for an interactive one. For something even more bespoke, drop to the Tier 2 primitives
(ThreadView, Composer.*, ContextUsageChip) and bind runStreamLogic yourself.
Optimistically open a run before it exists
To show the thread the instant a user hits send — their message + a "spinning up" indicator — before the
create/run round-trips finish, mount RunSurface.Root in its pending state (a null runId keyed by a
client streamKey), seed it via runStreamLogic.startOptimisticRun(message), then supply the real runId
once created; the surface attaches it (preserving the seed) and the live SSE echo dedups the message.
import { runStreamLogic } from 'products/posthog_ai/frontend/api/logics'
import { RunSurface } from 'products/posthog_ai/frontend/api/runSurface'
const streamKey = `draft-${uuid()}`
const stream = runStreamLogic({ streamKey })
stream.mount() // hold it across the render swap; release when done
stream.actions.startOptimisticRun(message) // empty → "spinning up" + the typed message
// render the pending surface (no run yet):
;<RunSurface.Root taskId="" runId={null} streamKey={streamKey} interaction="live">
<RunSurface.Thread />
</RunSurface.Root>
// …after api create/run resolve, set runId on the same surface to attach + stream it.
For an interactive optimistic start, mount runInteractionLogic with empty taskId/runId and explicit
streamKey/interactionKey values. Hold its mount through creation, then supply the real IDs with the same
keys. The composer preserves its draft, settings, and editable "Up next" queue through attachment.
Startup submissions stay local until the agent starts and its first turn completes; manual Steer is available
once the agent has started. Configuration changes apply to the next message, not the initial prompt.
Release the held mount when the creation is abandoned or fails. Later successor runs use their own interaction key.
The attach is idempotent and seed-preserving via runStreamLogic's bootstrappedRunId /
awaitingOptimisticAttach state — so the run can be adopted by a different surface that mounts later, not
only by an in-place runId flip. A consumer that navigates (e.g. /tasks/new → /tasks/:id) keeps the seeded
instance alive (hold the manual .mount()), then has the destination surface bind the same streamKey plus
the real runId: RunSurface.Root sees the instance is already bootstrapped for that run and adopts it without
a reset() — no skeleton re-flash, the thread is continuous across the unmount/mount. If that destination also
drives runInteractionLogic, pass it the same streamKey (a streamKey ?? runId connect-key) so the composer
reads the exact stream the thread renders; runInteractionLogic still keys its own per-run state by runId.
The tasks runner composes exactly this (scenes/TaskTracker/taskTrackerSceneLogic.ts + TaskCreateThread for
the pending phase, then TaskDetailPage → TaskRunLog → TaskRunChat adopting the seeded stream after navigation).
Bespoke / compact thread via Thread.* atoms
import { Thread } from 'products/posthog_ai/frontend/api/primitives'
// Compose only the atoms you want — e.g. a compact inline preview that drops the activity/tool chrome.
;<Thread.Root items={items}>{(item) => <Thread.Message item={item} />}</Thread.Root>
Declare product tool renderers (Tier 4)
Export a typed declaration list from products/<product>/frontend/posthogAiToolRenderers.tsx.
Add one direct import and one spread to frontend/src/posthogAiToolRenderers.ts for your product.
Keep individual entries with their product; import no scenes or broad component barrels from declaration modules.
Use type-only imports from api/tools for the contract, so declarations cannot create a runtime cycle with the registry.
The registry initializes synchronously from built-ins and this manifest before rendering.
The manifest is the sole extension mechanism: there is no runtime registration, subscription, or asynchronous initialization.
toolRegistry.lookup and lookupToolRenderer remain available; keep headless api/logics and api/types free of registry imports.
import { IconBolt } from '@posthog/icons'
import { lazyWithRetry } from 'lib/utils/retryImport'
import type { ToolRegistryEntry } from 'products/posthog_ai/frontend/api/tools'
export const posthogAiToolRenderers: ToolRegistryEntry[] = [
{
key: 'cdp-functions-partial-update',
displayName: 'Update function',
icon: <IconBolt />,
PermissionPreview: lazyWithRetry(() =>
import('./HogFunctionPermissionPreview').then((m) => ({ default: m.HogFunctionPermissionPreview }))
),
requiresPostHogOrigin: true,
},
]
PermissionPreview receives { request, fallback }, typed as PermissionPreviewProps from api/tools.
Return fallback when there is no available matching mounted configuration or no changes to show.
Do not mount or fetch a product scene to produce a preview.
PermissionInput supplies its evidence block as fallback, and wraps the preview in Suspense and PostHogErrorBoundary.
Both boundaries use that evidence fallback; approval controls remain outside them and stay usable during loading or failure.
Errors retain the posthog_ai_permission_preview feature tag, and a new permission request resets the error boundary.
Insights, dashboards, recordings, notebooks, and query widgets live in components/tool/widgets/, with lazy declarations in the frontend-root posthogAiToolRenderers.tsx. This declaration list is a product contribution, outside the reusable api/ facade.
Error tracking owns its widget family and declaration list in products/error_tracking/frontend/; replay vision owns its scan widget and polling logic in products/replay_vision/frontend/posthogAi/.
Product-owned tool adapters consume ToolRendererProps, DataToolRow, GenericMcpToolRenderer, and getToolOutputRecord through api/tools. Shared frontend dependencies are allowed; widget-specific product internals stay with their owner.
getToolOutputRecord reads the handler object from MCP app-data metadata in ACP rawOutput, with support for existing structuredContent and direct objects. It does not parse tool result text. Transcripts with only TOON or JSON text use the generic tool card.
CDP's products/cdp/frontend/posthogAiToolRenderers.tsx declares a preview-only entry; its result card stays generic.
Set requiresPostHogOrigin: true for product entries; unknown or untrusted colliding keys use generic cards and evidence.
Headless status badge / automation
import { runStreamLogic, isTerminalRunStatus } from 'products/posthog_ai/frontend/api/logics'
const { currentRunStatus } = useValues(runStreamLogic({ streamKey }))
const done = isTerminalRunStatus(currentRunStatus)
No React presenters, no tool registry — this import lane stays out of those chunks.
Inject context the agent should see
Register the resource(s) the user is looking at; while registered, every message sent from the surface is
prefixed with invisible context blocks describing them (the user only ever sees their own text):
type: 'instructions' items render into <posthog_trusted_context> (our own injected guidance — never put
user/ingested data there), everything else into <posthog_untrusted_context> behind hardening prose. Items
are abstract — type is any string ('insight', 'trace', 'text'…), plus key/label/value — and
are deduped across providers and across sends within a task (the whole resume chain of runs, matching the
backend's per-task semantics; except text, which always resends).
import { useAttachedContext } from 'products/posthog_ai/frontend/api/logics'
// In your scene/component — registered while mounted, removed on unmount:
useAttachedContext([{ type: 'insight', key: insight.short_id, label: insight.name }])
JSX-only call sites can render <AttachedContextProvider items={...} /> (api/primitives) instead.
From a kea logic, connect to the shell-owned attachedContextLogic (~/layout/ai/attachedContextLogic) and register through a disposable (the repo-preferred
teardown idiom — see /using-kea-disposables); the returned cleanup deregisters on unmount, no
beforeUnmount needed. Pass pauseOnPageHidden: false: the registration costs nothing while idle, and the
default hide-pause would silently drop context from a queued follow-up that flushes while the tab is hidden.
afterMount(({ actions, cache, values }) => {
cache.disposables.add(
() => {
actions.registerContext('my-scene', [{ type: 'dashboard', key: values.dashboard.id }])
return () => actions.deregisterContext('my-scene')
},
'attachedContext',
{ pauseOnPageHidden: false }
)
})
Re-dispatching registerContext with the same provider id (e.g. from a subscriptions handler when the
resource changes) is an upsert — see logics/contextPickerLogic.ts for the full shape.
Let the user pick context (the composer @-affordance)
AttachedContextBar (api/primitives) is the prepackaged picker + chips row — drop it into
Composer.Header, the wrapping row at the top of the frame above the textarea (that's exactly what
TaskComposer and TaskRunChat do, so /tasks and the side panel already have it; the footer stays
free for the model/effort pickers):
import { Composer } from 'products/posthog_ai/frontend/api/composer'
import { AttachedContextBar } from 'products/posthog_ai/frontend/api/primitives'
;<Composer.Header>
<AttachedContextBar />
</Composer.Header>
The @-button opens a TaxonomicPopover over events/actions/insights/dashboards/notebooks/error-tracking
issues; a selection becomes a flat { type, key, label } ref through contextPickerLogic (api/logics) — no
entity loading, the agent fetches details. In a new chat the chips render your picks and everything in
contextItems, whatever provider contributed it. A started chat freezes its chips: pass taskId to AttachedContextChips or
QuillAttachedContextChips to show what chatContextLogic holds for that chat. Closing a chip the picker owns removes the pick; closing any other provider's chip
dismisses that key (attachedContextLogic.dismissContext), which sticks even while the provider keeps
re-registering the item — re-picking it through the popover adds it back as a pick.
React to the agent invoking a tool
Subscribe to tool-call lifecycle events (resolved tool names) — e.g. refresh a list when the agent creates
a dashboard. Replay events are suppressed by default so a page reload never re-triggers your handler; opt
in with includeReplay if you need them.
import { useToolStreamListener } from 'products/posthog_ai/frontend/api/logics'
useToolStreamListener({
tools: ['create_dashboard'],
onEvent: (event) => {
if (event.phase === 'completed') {
loadDashboards()
}
},
})
From a kea logic, either connect to toolStreamEventsLogic and listen to its emitToolEvent action (you
filter everything yourself, including event.source), or register a subscription through a disposable —
same shape as the context recipe above, calling registerToolListener(listenerId, { tools, onEvent }) in
setup and deregisterToolListener(listenerId) in cleanup, with pauseOnPageHidden: false (tool events fire
while the tab is hidden and missed live events are not redelivered).
Note: for exec-wrapped PostHog tools the resolved name can be unknown at phase: 'started' (the command
streams in later) — match on completed when you need certainty.
Editor mutations use useMcpToolApplyBack with a stable targetKey for the resource being edited. The
send paths snapshot the active targets for that stream before making a request. A response is applied only
when exactly one snapshotted target matches the tool, and changing editors creates a new activation that
cannot inherit the old response. The default turn_end mode applies only the final matching completion.
4. Coupling boundary
This surface couples to the tasks run API by design (products/tasks/frontend/generated/api) and
never to Max or the conversations API — Max is a consumer, not a dependency. The full rule (and the
grep gate that enforces it) is in AGENTS.md.
5. Replacement-ready by design
This surface is the intended replacement for Max's legacy LangGraph thread. The new-vs-legacy switch is a
consumer concern (Max routes agent_runtime === 'sandbox' conversations through runStreamLogic and
renders this surface; its LangGraph path renders its own thread). The surface never branches on
Max/LangGraph/conversation. Anything the LangGraph path owns that the surface doesn't express generically
(agent modes, billing context, scene attachments) stays in Max and feeds the surface through generic props
/ the tool registry / streamKey — lifted to a generic seam here, never special-cased. The four-tier
contract above is unchanged whichever side of the switch is active. See
AGENTS.md for the contributor-side detail.
Task selection in embedded hosts
Pass taskId to EmbeddedRunner to render an existing task.
The AI scene reads it from /ai?task=<id>, so shared history links and reloads select the same task.
Tasks created from /ai stay under that route; the standalone /tasks scene keeps its existing routes.