: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(phai): replace default RunViewer layout with RunSurface compound (#66352)
Georgiy Tarasovf8699fbc4361
diff --git a/frontend/src/scenes/inbox/__mocks__/inboxMocks.ts b/frontend/src/scenes/inbox/__mocks__/inboxMocks.tsindex 41e71fcb671c..97e3e40947ef 100644--- a/frontend/src/scenes/inbox/__mocks__/inboxMocks.ts+++ b/frontend/src/scenes/inbox/__mocks__/inboxMocks.ts@@ -401,7 +401,7 @@ export function mockTask(taskId: string, runStatus?: string): any {}}-/** The run-status payload (`/runs/:runId`) the `RunViewer` reads before replaying its log. */+/** The run-status payload (`/runs/:runId`) the `ReadonlyRunSurface` reads before replaying its log. */export function mockTaskRun(taskId: string, runId: string): any {return makeTaskRun(taskId, runId, 'completed')}diff --git a/frontend/src/scenes/inbox/components/detail/AgentRunDetail.tsx b/frontend/src/scenes/inbox/components/detail/AgentRunDetail.tsxindex 07f5ebbcdf71..81c879bb6cda 100644--- a/frontend/src/scenes/inbox/components/detail/AgentRunDetail.tsx+++ b/frontend/src/scenes/inbox/components/detail/AgentRunDetail.tsx@@ -21,7 +21,7 @@ import { SANDBOX_BIND_TASK_PARAM } from 'scenes/max/maxLogic'import { urls } from 'scenes/urls'import { isTerminalRunStatus } from 'products/posthog_ai/frontend/api/logics'-import { RunViewer } from 'products/posthog_ai/frontend/api/run'+import { ReadonlyRunSurface } from 'products/posthog_ai/frontend/api/readableRun'import { Task, TaskRunStatus } from 'products/posthog_ai/frontend/types/taskTypes'import { inboxReportDetailLogic } from '../../logics/inboxReportDetailLogic'@@ -193,7 +193,7 @@ function TaskLogBody({return (<div className="h-[calc(100dvh-22rem)] min-h-[420px] w-full overflow-hidden rounded border border-primary bg-surface-primary">{/* In-progress runs stream live; terminal runs show the static replay. */}- <RunViewer+ <ReadonlyRunSurfacetaskId={task.id}runId={runId}interaction={replayOnly ? 'read-only' : 'live'}@@ -250,7 +250,7 @@ export function OpenTaskButton({ taskId, runStatus }: { taskId: string; runStatu/*** Inline "Task log": the selected linked task's agent transcript, rendered with the shared- * `RunViewer` — live for an in-progress run, static replay once terminal. A `LemonSelect`+ * `ReadonlyRunSurface` — live for an in-progress run, static replay once terminal. A `LemonSelect`* switches between linked tasks (research / implementation) when there's more than one; "Open task"* continues the task in a new PostHog AI chat. Mirrors desktop `AgentRunDetail`'s Task-log section.*/@@ -301,7 +301,7 @@ function TaskLogSection({ report }: { report: SignalReport }): JSX.Element {/*** Agent run detail body. Shows the run state strip + output state, the linked run's agent transcript- * inline (`TaskLogSection`, via the shared `RunViewer`), and contributing evidence.+ * inline (`TaskLogSection`, via the shared `ReadonlyRunSurface`), and contributing evidence.* Mirrors desktop `AgentRunDetail`.*/export function AgentRunDetail({ report }: { report: SignalReport }): JSX.Element {diff --git a/frontend/src/scenes/inbox/components/detail/ArtefactTaskRun.tsx b/frontend/src/scenes/inbox/components/detail/ArtefactTaskRun.tsxindex c77409890d33..5b7c675eb1fc 100644--- a/frontend/src/scenes/inbox/components/detail/ArtefactTaskRun.tsx+++ b/frontend/src/scenes/inbox/components/detail/ArtefactTaskRun.tsx@@ -7,7 +7,7 @@ import api from 'lib/api'import { identifierToHuman } from 'lib/utils/strings'import { isTerminalRunStatus } from 'products/posthog_ai/frontend/api/logics'-import { RunViewer } from 'products/posthog_ai/frontend/api/run'+import { ReadonlyRunSurface } from 'products/posthog_ai/frontend/api/readableRun'import { Task, TaskRunStatus } from 'products/posthog_ai/frontend/types/taskTypes'import { isCustomAgentTaskRun, taskRunTypeLabel, TaskRunArtefactContent } from './artefactTypes'@@ -16,7 +16,7 @@ import { TaskRunStatusDot } from './taskRunDisplay'/*** A `task_run` artefact: the linked task badged from its `(product, type)` (signals-pipeline runs* show Research / Implementation / Repo selection; custom agents show their humanized product +- * type), expanding to the task's run transcript via the shared `RunViewer`. Mirrors desktop+ * type), expanding to the task's run transcript via the shared `ReadonlyRunSurface`. Mirrors desktop* `ArtefactTaskRun` (which embeds `TaskLogsPanel`). The task is resolved lazily and the row is* disabled until it loads.*/@@ -107,7 +107,7 @@ export function ArtefactTaskRun({{expanded && task && runId ? (<div className="mt-2 h-[420px] overflow-hidden rounded border border-primary bg-surface-primary">- <RunViewer+ <ReadonlyRunSurfacetaskId={task.id}runId={runId}interaction={replayOnly ? 'read-only' : 'live'}diff --git a/frontend/src/scenes/inbox/components/detail/ReportTasksSection.tsx b/frontend/src/scenes/inbox/components/detail/ReportTasksSection.tsxindex 669b2a7f4abf..c7205494aece 100644--- a/frontend/src/scenes/inbox/components/detail/ReportTasksSection.tsx+++ b/frontend/src/scenes/inbox/components/detail/ReportTasksSection.tsx@@ -4,7 +4,7 @@ import { IconChevronDown, IconChevronRight, IconTerminal } from '@posthog/icons'import { Spinner } from '@posthog/lemon-ui'import { isTerminalRunStatus } from 'products/posthog_ai/frontend/api/logics'-import { RunViewer } from 'products/posthog_ai/frontend/api/run'+import { ReadonlyRunSurface } from 'products/posthog_ai/frontend/api/readableRun'import { TaskRunStatus } from 'products/posthog_ai/frontend/types/taskTypes'import { inboxReportDetailLogic, ReportTaskEntry } from '../../logics/inboxReportDetailLogic'@@ -14,7 +14,7 @@ import { TaskRunStatusDot } from './taskRunDisplay'/*** Renders the report's linked tasks inline (latest status + purpose). Each row expands in place to- * the task's run transcript via the shared `RunViewer` — live for an in-progress run, static+ * the task's run transcript via the shared `ReadonlyRunSurface` — live for an in-progress run, static* replay once terminal — mirroring the Code experience instead of navigating away to a separate run* page. The purpose label is derived from each task's `task_run` artefact; `repo_selection` runs are* filtered out.@@ -89,7 +89,7 @@ function TaskRow({// clips — an `overflow-y-auto` here would nest a second scrollbar. Content is kept off// the border via `threadRowClassName`/`threadListClassName`, not padding on this box.<div className="h-[420px] overflow-hidden rounded border border-primary bg-surface-primary">- <RunViewer+ <ReadonlyRunSurfacetaskId={task.id}runId={runId}interaction={replayOnly ? 'read-only' : 'live'}diff --git a/frontend/src/scenes/max/AGENTS.md b/frontend/src/scenes/max/AGENTS.mdindex 0b7e02e1ddfb..a8f9a2b27d0b 100644--- a/frontend/src/scenes/max/AGENTS.md+++ b/frontend/src/scenes/max/AGENTS.md@@ -49,11 +49,11 @@ parsing wire frames in a Max component.The conversation-agnostic sandbox run surface (stream logic, thread/tool/permission/composer components,policy, wire types) **no longer lives under `scenes/max`** — it's the composable PostHog AI agent-runlibrary at `products/posthog_ai/frontend`, consumed here through its tiered `api/<module>` facade-(`import { ... } from 'products/posthog_ai/frontend/api/run'` / `api/primitives` / `api/logics` /-`api/types` / `api/tools` — there is no root barrel; pick the narrowest tier). See that directory's-`README.md` for the tier decision table + recipes and its `AGENTS.md` for layout, the public API-(`RunViewer`, `Thread`, `Composer`, `runStreamLogic`, the tool registry), and the hard rule that it must-never import `scenes/max`.+(`import { ... } from 'products/posthog_ai/frontend/api/readableRun'` / `api/runSurface` / `api/primitives` /+`api/logics` / `api/types` / `api/tools` — there is no root barrel; pick the narrowest tier). See that+directory's `README.md` for the tier decision table + recipes and its `AGENTS.md` for layout, the public API+(`ReadonlyRunSurface`, the `RunSurface` compound, `Thread`, `Composer`, `runStreamLogic`, the tool registry),+and the hard rule that it must never import `scenes/max`.What stays in `scenes/max`: conversation orchestration (`maxLogic`, `maxThreadLogic`, `maxGlobalLogic`), theMax Context subsystem, slash commands, `useMaxTool`/`MaxTool`, feedback/ratings, the frozen LangGraph path,diff --git a/products/posthog_ai/frontend/AGENTS.md b/products/posthog_ai/frontend/AGENTS.mdindex b7c2a7f6fa68..37cccfa5f62e 100644--- a/products/posthog_ai/frontend/AGENTS.md+++ b/products/posthog_ai/frontend/AGENTS.md@@ -18,12 +18,12 @@ them. There are four tiers, split along dependency/side-effect boundaries (not cpreserves code-splitting). Consumers pick the **lowest tier** that does the job. The full decision table,import rule, and copy-paste recipes live in the consumer-facing [`README.md`](./README.md); the summary:-| Tier | Module | What's in it |-| ------------------------------ | -------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------- |-| **1 — Prepackaged surfaces** | `api/run` | `RunViewer` (lazy, code-split embeddable → default layout), `RunComposer` |-| **2 — Compound primitives** | `api/primitives` | `Thread` + atoms, `ThreadView`, `Composer.*`, `RunLogSkeleton`, activity primitives + `RunActivity`, message presenters, permission/question/resource surfaces |-| **3 — Headless logic + types** | `api/logics` + `api/types` | `runStreamLogic`, `runInteractionLogic`, status + thinking helpers; folded-thread + tool types |-| **4 — Extension seam** | `api/tools` | `toolRegistry`, `registerToolRenderers`, `lookupToolRenderer`, `GenericMcpToolRenderer`, `DataToolRow`, `ToolActivity`, `FilePath`, diff helpers |+| Tier | Module | What's in it |+| ------------------------------ | ------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |+| **1 — Prepackaged surfaces** | `api/readableRun` + `api/runSurface` | `ReadonlyRunSurface` (lazy, code-split read-only embed); the `RunSurface` compound (`Root` + slots, eager) for custom layouts |+| **2 — Compound primitives** | `api/primitives` | `Thread` + atoms, `ThreadView`, `Composer.*`, `QueuedMessageList`, `RunLogSkeleton`, activity primitives + `RunActivity`, message presenters, permission/question/resource surfaces |+| **3 — Headless logic + types** | `api/logics` + `api/types` | `runStreamLogic`, `runInteractionLogic`, status + thinking helpers; folded-thread + tool types |+| **4 — Extension seam** | `api/tools` | `toolRegistry`, `registerToolRenderers`, `lookupToolRenderer`, `GenericMcpToolRenderer`, `DataToolRow`, `ToolActivity`, `FilePath`, diff helpers |**Why the split, not one flat barrel:** the tool registry registers built-ins at module load — a top-levelside effect that is _not_ tree-shaken. A single barrel statically re-exports it alongside the@@ -39,22 +39,29 @@ reached through an `api/<module>` entry; add new exports to the relevant tier moThe headline exports per module:-- **`api/run`** — **`RunViewer`**, the lazy, code-split embeddable: calling `<RunViewer .../>` binds the- stream logic and renders the default layout behind a `RunLogSkeleton` Suspense fallback (the heavy chunk —- stream logic, virtualized thread, tool/diff renderers — loads on demand). This is the form every **embed**- uses (the inbox detail views), where the viewer is a secondary panel worth splitting out. The one exception- is the **runner scene** (`scenes/TaskTracker`), which renders `components/RunViewerImpl` **directly (eager,- relative import)**: the `/tasks` route is already a code-split scene chunk and the viewer is its primary- content, so a second `lazy()` would only add a redundant chunk fetch + Suspense flash. The compound- (`Root` plus the `.Thread/.Prompt/.Composer/.Resources/.ContextUsage` slots) stays internal to- `components/RunViewerImpl` backing the default layout, not surfaced (no consumer composes the slots, and- lazy-wrapping each would only add Suspense boundaries that never fire). For a custom layout, bind- `runStreamLogic` and compose the Tier 2 primitives. Also **`RunComposer`**.+- **`api/readableRun`** — **`ReadonlyRunSurface`**, the lazy, code-split read-only embed: calling+ `<ReadonlyRunSurface .../>` renders the run thread (and, for a live run, the meta bars) behind a+ `RunLogSkeleton` Suspense fallback — no composer, no approval prompt. The heavy chunk (the `RunSurface`+ compound — stream logic, virtualized thread, tool/diff renderers) is reached only through its dynamic+ `import()`, so importing this light module never statically pulls the impl. This is the form every **embed**+ uses (the inbox detail views), where the surface is a secondary panel worth splitting out. It streams fresh+ frames while running when `interaction='live'`, and replays the snapshot once when `'read-only'`.+- **`api/runSurface`** — the **`RunSurface`** compound (`Root` + the `.Thread/.Composer/.Resources/.ContextUsage`+ slots), **eager**, for consumers that build a **custom layout**. `RunSurface.Root` binds the stream logic and+ bootstraps the run; the slots compose into whatever layout the surface needs. `RunSurface.Composer` is the+ input-region slot — it owns prompt-vs-composer precedence (a pending approval/question replaces the composer)+ and the null-bootstrap gate, and takes the composer UI as `children`; omit it for no input region. The meta+ slots (`.Resources`/`.ContextUsage`) self-bind and self-hide when empty. There is **no default layout** — the+ prepackaged read-only embed (`ReadonlyRunSurface`) is one concrete composition; the runner scene+ (`scenes/TaskTracker/TaskRunChat`) composes its own live-composer layout. Because the compound is eager, import+ it only from an already route-split scene (the `/tasks` runner) or another lazily-loaded layout module — a+ light bundle that should stay split uses `api/readableRun` instead.- **`api/primitives`** — **`Thread`** (Radix-style compound: `Thread.Root` is the virtualized presenter, theatoms `Thread.Message/.Markdown/.Reasoning/.Failure/.Activity/.ToolCall` are the building blocks forbespoke threads), **`Composer`** (logic-free compound input — the caller owns`value`/`onChange`/`onSubmit`), **`RunLogSkeleton`** (the shared "run log is loading" loader — the- `RunViewer` Suspense/bootstrap fallback, also used by the runner scene), activity primitives, message+ `ReadonlyRunSurface` Suspense fallback and the `RunSurface` bootstrap fallback, also used by the runner+ scene), activity primitives, messagepresenters, and the permission/question/resource surfaces.- **`api/logics`** — **`runStreamLogic`** (SSE stream + thread projection, see §3),**`runInteractionLogic`** (Max-agnostic follow-up/queue facade), status helpers@@ -129,13 +136,15 @@ loosely typed — guard at the parse boundary with runtime checks; never assume```textapi/ # public API facade — the contract (import api/<module>, never deep paths)- run.ts # Tier 1: RunViewer, RunComposer- primitives.ts # Tier 2: Composer, Thread + atoms, ThreadView, presenters, perm/question/resource+ readableRun.ts # Tier 1: ReadonlyRunSurface (lazy read-only embed)+ runSurface.ts # Tier 1: RunSurface compound (Root + slots, eager) for custom layouts+ primitives.ts # Tier 2: Composer, Thread + atoms, ThreadView, QueuedMessageList, presenters, perm/question/resourcelogics.ts # Tier 3: runStreamLogic, runInteractionLogic, status + thinking helpers (headless)types.ts # Tier 3: folded-thread + tool domain types (pure types)tools.ts # Tier 4: toolRegistry + registerToolRenderers seam (side-effectful — isolated)-components/ # RunViewer (lazy wrapper) + RunViewerImpl (heavy chunk), RunLogSkeleton (shared loader),- # Thread, Composer, permission/question/resource surfaces, activity, tool/+components/ # RunSurfaceImpl (the RunSurface compound, heavy chunk); ReadonlyRunSurfaceImpl (prepackaged+ # read-only layout) + ReadonlyRunSurface (its lazy wrapper, replaces the old RunViewer.tsx);+ # RunLogSkeleton (shared loader), Thread, Composer, perm/question/resource surfaces, activity, tool/composer/ # the Composer compoundtool/ # tool registry + renderers (built-ins, generic MCP, EditDiffRenderer, diff/exec utils)logics/ # runStreamLogic, runInteractionLogic; tasksLogic/taskLogic data logics (+ *LogicType.ts)diff --git a/products/posthog_ai/frontend/README.md b/products/posthog_ai/frontend/README.mdindex 0d1e24d7931d..4148677dcbe2 100644--- a/products/posthog_ai/frontend/README.md+++ b/products/posthog_ai/frontend/README.md@@ -14,7 +14,7 @@ Import from a domain-scoped **`api/<module>`** entry. Never reach into deep intethem. The `products/*` path alias is configured in tsconfig, so the import is absolute:```ts-import { RunViewer } from 'products/posthog_ai/frontend/api/run'+import { ReadonlyRunSurface } from 'products/posthog_ai/frontend/api/readableRun'import { isTerminalRunStatus } from 'products/posthog_ai/frontend/api/logics'```@@ -30,21 +30,21 @@ re-introduce the exact bundling problem the split solves. Always import an `api/Pick the **lowest tier** that does the job.-| Tier | Module | What's in it | Use when |-| ------------------------------ | -------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------- |-| **1 — Prepackaged surfaces** | `api/run` | `RunViewer` (lazy, code-split embeddable → default layout), `RunComposer` | "Just show/drive a run." Inbox read-only embed, tasks embed. |-| **2 — Compound primitives** | `api/primitives` | `Thread` + atoms (`.Message/.Markdown/.Reasoning/.Failure/.Activity/.ToolCall`), `ThreadView`, `Composer.*`, `RunLogSkeleton`, activity primitives + `RunActivity`, message presenters, permission/question/resource surfaces | Custom layout, or a bespoke/compact thread. |-| **3 — Headless logic + types** | `api/logics` + `api/types` | `runStreamLogic`, `runInteractionLogic`, status helpers (`isTerminalRunStatus`, `INITIAL_PERMISSION_MODE`), thinking-message helpers; folded-thread + tool types | Status badge or automation — no React, no registry. |-| **4 — Extension seam** | `api/tools` | `toolRegistry`, `registerToolRenderers`, `lookupToolRenderer`, `GenericMcpToolRenderer`, `DataToolRow`, `ToolActivity`, `FilePath`, diff helpers | Your product renders tool cards (insights, dashboards…). Register them from your own scene. |+| Tier | Module | What's in it | Use when |+| ------------------------------ | ------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------- |+| **1 — Prepackaged surfaces** | `api/readableRun` + `api/runSurface` | `ReadonlyRunSurface` (lazy, code-split read-only embed); the `RunSurface` compound (`Root` + slots, eager) for custom layouts | "Just show a run" → `ReadonlyRunSurface` (inbox embeds). "Drive a run / custom layout" → `RunSurface` (tasks). |+| **2 — Compound primitives** | `api/primitives` | `Thread` + atoms (`.Message/.Markdown/.Reasoning/.Failure/.Activity/.ToolCall`), `ThreadView`, `Composer.*`, `QueuedMessageList`, `RunLogSkeleton`, activity primitives + `RunActivity`, message presenters, permission/question/resource surfaces | Custom layout, or a bespoke/compact thread. |+| **3 — Headless logic + types** | `api/logics` + `api/types` | `runStreamLogic`, `runInteractionLogic`, status helpers (`isTerminalRunStatus`, `INITIAL_PERMISSION_MODE`), thinking-message helpers; folded-thread + tool types | Status badge or automation — no React, no registry. |+| **4 — Extension seam** | `api/tools` | `toolRegistry`, `registerToolRenderers`, `lookupToolRenderer`, `GenericMcpToolRenderer`, `DataToolRow`, `ToolActivity`, `FilePath`, diff helpers | Your product renders tool cards (insights, dashboards…). Register them from your own scene. |-`api/run` (Tier 1) is built on `api/primitives` (Tier 2); `api/primitives` consumes the headless+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.-`RunViewer` 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. A surface where the run viewer is-the _primary_ content of an already-code-split route (the `/tasks` runner scene) is the exception: it renders-the eager implementation directly so it doesn't pay a second chunk fetch + Suspense flash for the one thing-the route exists to show.+`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@@ -53,28 +53,50 @@ Each recipe shows the granular import to copy.### Read-only embed (inbox-style)```tsx-import { RunViewer } from 'products/posthog_ai/frontend/api/run'-;<RunViewer taskId={task.id} runId={run.id} interaction="read-only" />+import { ReadonlyRunSurface } from 'products/posthog_ai/frontend/api/readableRun'+;<ReadonlyRunSurface taskId={task.id} runId={run.id} interaction="read-only" />```-### Live embed with composer + queue (tasks-style; caller owns draft/queue)+The prepackaged, lazy read-only surface: thread (plus the meta bars 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.-```tsx-import { RunViewer } from 'products/posthog_ai/frontend/api/run'-import { runInteractionLogic, type RunInteractionLogicProps } from 'products/posthog_ai/frontend/api/logics'+### 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 null-bootstrap gate; you+own the composer. See `scenes/TaskTracker/components/TaskRunChat.tsx` for the full wiring.-// Bind runInteractionLogic for the follow-up/queue facade, then render the viewer with a composer slot.-const { queuedMessages } = useValues(runInteractionLogic(props))-<RunViewer taskId={task.id} runId={run.id} />+```tsx+import { RunSurface } from 'products/posthog_ai/frontend/api/runSurface'+import { Composer, 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, queuedMessages } = useValues(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.Resources />+ <RunSurface.Composer>+ <Composer.Root value={draft} onChange={setDraft} onSubmit={submit} loading={isSubmitting}>+ {/* …Composer.Frame / Field / Textarea / Submit… */}+ </Composer.Root>+ </RunSurface.Composer>+ <RunSurface.ContextUsage />+ </div>+</RunSurface.Root>```-### Custom layout via `Thread.*` + the run primitives+### Custom layout via the `RunSurface` compound-`RunViewer` (Tier 1) is a single lazy embeddable — it renders the default layout and intentionally does-not surface slot atoms (no consumer composed them, and lazy-wrapping each would only add Suspense-boundaries that never fire). For a custom layout, bind `runStreamLogic` yourself and compose the Tier 2-primitives (`ThreadView`, `ResourcesBar`, `PermissionInput`, `Composer.*`, `ContextUsageBar`) — use-`RunLogSkeleton` for the loading state so the surface keeps its shape.+`RunSurface.Root` (Tier 1, `api/runSurface`) binds the stream logic and bootstraps the run; the slots+(`.Thread/.Composer/.Resources/.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`, `ResourcesBar`, `Composer.*`, `ContextUsageBar`) and bind `runStreamLogic` yourself.### Bespoke / compact thread via `Thread.*` atomsdiff --git a/products/posthog_ai/frontend/api/primitives.ts b/products/posthog_ai/frontend/api/primitives.tsindex 2ba0e951e6de..18320494768c 100644--- a/products/posthog_ai/frontend/api/primitives.ts+++ b/products/posthog_ai/frontend/api/primitives.ts@@ -1,8 +1,9 @@// Tier 2 — compound primitives & presenters: the broad presentational bucket for custom layouts and// bespoke threads. The Composer compound, the Thread compound + atoms, the prepackaged `ThreadView`,// message presenters, the shared `RunLogSkeleton` loader, activity primitives, and the-// permission/question/resource surfaces. Use when the prepackaged `RunViewer` (Tier 1, ./run) doesn't fit-// and you need to compose the pieces yourself — e.g. a compact inline thread via `Thread.*` atoms.+// permission/question/resource surfaces. Use when the prepackaged `ReadonlyRunSurface` (Tier 1,+// ./readableRun) doesn't fit and you need to compose the pieces yourself — e.g. a compact inline thread via+// `Thread.*` atoms.//// (This is intentionally the wide presentational module; it can be subdivided later — e.g. thread.ts /// composer.ts — if a consumer needs finer code-splitting.)@@ -10,7 +11,6 @@// Part of the `products/posthog_ai/frontend/api/<module>` public surface — import from here, not from// deep `../components/*` paths. See ../README.md for the tier model and ../AGENTS.md for the coupling rule.-// --- Composer (Radix-style compound) ---export { Composer } from '../components/composer/Composer'export type {ComposerRootProps,@@ -19,7 +19,6 @@ export type {ComposerSubmitProps,} from '../components/composer/Composer'-// --- Thread + message presenters ---// `Thread` is the Radix-style compound (Root + Message/Markdown/Reasoning/Failure/Activity/ToolCall// atoms); `ThreadView` is the prepackaged virtualized presenter (also `Thread.Root`).export { Thread } from '../components/Thread'@@ -30,8 +29,9 @@ export { ReasoningAnswer } from '../messages/ReasoningAnswer'export type { ReasoningAnswerProps } from '../messages/ReasoningAnswer'export { AssistantFailureMessage } from '../messages/AssistantFailureMessage'export { RunLogSkeleton } from '../components/RunLogSkeleton'+export { QueuedMessageList } from '../components/QueuedMessageList'+export type { QueuedMessageListProps } from '../components/QueuedMessageList'-// --- Activity primitives ---export {Activity,ActivityDetails,@@ -44,7 +44,6 @@ export {export type { ActivityStatus } from '../components/ActivityPrimitives'export { RunActivity } from '../components/RunActivity'-// --- Permission / question / resource surfaces ---export { PermissionInput } from '../components/PermissionInput'export { QuestionInput } from '../components/QuestionInput'export { ResourcesBar } from '../components/ResourcesBar'diff --git a/products/posthog_ai/frontend/api/readableRun.ts b/products/posthog_ai/frontend/api/readableRun.tsnew file mode 100644index 000000000000..ff94d9979de4--- /dev/null+++ b/products/posthog_ai/frontend/api/readableRun.ts@@ -0,0 +1,14 @@+// Tier 1 — prepackaged read-only run surface. `ReadonlyRunSurface` (`<ReadonlyRunSurface .../>`) is the lazy,+// code-split embeddable for "just show a run": it renders the run thread (and, for a live run, the meta bars)+// behind a `RunLogSkeleton` fallback — no composer, no approval prompt. This is the common embed (the inbox+// detail views). It streams fresh frames while running when `interaction='live'`, and replays the snapshot+// once when `interaction='read-only'`.+//+// LIGHT boundary: the heavy `RunSurface` compound is reached only through `ReadonlyRunSurface`'s dynamic+// `import()`, so importing this module never statically pulls the impl/thread/stream logic/tool registry —+// the consumer's bundle stays split. For a custom layout, reach for the eager compound in ./runSurface.+//+// Part of the `products/posthog_ai/frontend/api/<module>` public surface — import from here, not from+// deep `../components/*` paths. See ../README.md for the tier model and ../AGENTS.md for the coupling rule.++export { ReadonlyRunSurface, type ReadonlyRunSurfaceProps } from '../components/ReadonlyRunSurface'diff --git a/products/posthog_ai/frontend/api/run.ts b/products/posthog_ai/frontend/api/run.tsdeleted file mode 100644index 2bd61a6ec495..000000000000--- a/products/posthog_ai/frontend/api/run.ts+++ /dev/null@@ -1,12 +0,0 @@-// Tier 1 — prepackaged run surfaces. `RunViewer` (`<RunViewer .../>`) is the lazy, code-split embeddable:-// it binds the stream logic and renders the default layout behind a `RunLogSkeleton` fallback — the common-// embed for "just show/drive a run" (inbox read-only, tasks live), and the only form any consumer uses.-// `RunComposer` is the standalone composer for a caller that owns its own thread rendering.-//-// Part of the `products/posthog_ai/frontend/api/<module>` public surface — import from here, not from-// deep `../components/*` paths. See ../README.md for the tier model and ../AGENTS.md for the coupling rule.--export { RunViewer } from '../components/RunViewer'-export type { RunViewerProps } from '../components/RunViewer'-export { RunComposer } from '../components/RunComposer'-export type { RunComposerProps } from '../components/RunComposer'diff --git a/products/posthog_ai/frontend/api/runSurface.ts b/products/posthog_ai/frontend/api/runSurface.tsnew file mode 100644index 000000000000..d7ead3c31c12--- /dev/null+++ b/products/posthog_ai/frontend/api/runSurface.ts@@ -0,0 +1,15 @@+// Tier 1 — the `RunSurface` compound (`Root` + the `.Thread/.Composer/.Resources/.ContextUsage` slots) for+// consumers that build a custom run layout: `RunSurface.Root` binds the stream logic and bootstraps the run;+// the slots compose into whatever layout the surface needs (a live composer for tasks; the meta bars for an+// embed). There is no default layout — for the common no-input read-only embed, use `ReadonlyRunSurface`+// (./readableRun) instead.+//+// EAGER, not lazy: this statically pulls the heavy compound (stream logic, virtualized thread, tool/diff+// renderers). Import it only from an already route-split scene (the tasks runner) or another lazily-loaded+// layout module — never from a light bundle that should stay split (use ./readableRun there).+//+// Part of the `products/posthog_ai/frontend/api/<module>` public surface — import from here, not from+// deep `../components/*` paths. See ../README.md for the tier model and ../AGENTS.md for the coupling rule.++export { RunSurface } from '../components/RunSurfaceImpl'+export type { RunSurfaceRootProps } from '../components/RunSurfaceImpl'diff --git a/products/posthog_ai/frontend/components/QueuedMessageList.tsx b/products/posthog_ai/frontend/components/QueuedMessageList.tsxindex 70178974fdbd..c2359f47140a 100644--- a/products/posthog_ai/frontend/components/QueuedMessageList.tsx+++ b/products/posthog_ai/frontend/components/QueuedMessageList.tsx@@ -5,7 +5,7 @@ import { LemonButton, LemonTextArea } from '@posthog/lemon-ui'import type { QueuedMessage } from '../logics/runInteractionLogic'-interface QueuedMessageListProps {+export interface QueuedMessageListProps {messages: QueuedMessage[]onUpdate: (id: string, content: string) => voidonRemove: (id: string) => voiddiff --git a/products/posthog_ai/frontend/components/ReadonlyRunSurface.test.tsx b/products/posthog_ai/frontend/components/ReadonlyRunSurface.test.tsxnew file mode 100644index 000000000000..64f127c46c0d--- /dev/null+++ b/products/posthog_ai/frontend/components/ReadonlyRunSurface.test.tsx@@ -0,0 +1,23 @@+import '@testing-library/jest-dom'++import { cleanup, render, screen } from '@testing-library/react'++import { ReadonlyRunSurface } from './ReadonlyRunSurface'++// Stand in for the heavy impl chunk so the test exercises the lazy/Suspense wiring, not the real surface.+jest.mock('./ReadonlyRunSurfaceImpl', () => ({ __esModule: true, default: () => <div data-attr="thread" /> }))+jest.mock('./RunLogSkeleton', () => ({ RunLogSkeleton: () => <div data-attr="run-log-skeleton" /> }))++describe('ReadonlyRunSurface', () => {+ afterEach(() => {+ cleanup()+ })++ it('lazy-loads behind the run-log skeleton, then renders the thread', async () => {+ render(<ReadonlyRunSurface taskId="task-1" runId="run-1" interaction="read-only" />)+ // The Suspense fallback shows the shared skeleton while the impl chunk resolves...+ expect(screen.getByTestId('run-log-skeleton')).toBeInTheDocument()+ // ...then the lazily-imported surface mounts and the thread appears.+ expect(await screen.findByTestId('thread')).toBeInTheDocument()+ })+})diff --git a/products/posthog_ai/frontend/components/ReadonlyRunSurface.tsx b/products/posthog_ai/frontend/components/ReadonlyRunSurface.tsxnew file mode 100644index 000000000000..39adf5ffb5bb--- /dev/null+++ b/products/posthog_ai/frontend/components/ReadonlyRunSurface.tsx@@ -0,0 +1,27 @@+import { lazy, Suspense } from 'react'++import type { ReadonlyRunSurfaceProps } from './ReadonlyRunSurfaceImpl'+import { RunLogSkeleton } from './RunLogSkeleton'++export type { ReadonlyRunSurfaceProps } from './ReadonlyRunSurfaceImpl'++// Heavy chunk (the RunSurface compound — stream logic, virtualized thread, tool/diff renderers) loaded on+// demand; the RunLogSkeleton fallback matches the loaded thread, so the surface keeps its shape across+// chunk-load → bootstrap → first frame. Only `react` + the lightweight skeleton are imported statically — the+// impl is reached solely via dynamic `import()` (the type import below is erased), so the chunk genuinely splits.+const Lazy = lazy(() => import('./ReadonlyRunSurfaceImpl'))++/**+ * Prepackaged read-only run surface, code-split behind a `RunLogSkeleton` fallback. This is the common+ * embed: the inbox detail views (`ArtefactTaskRun` / `AgentRunDetail` / `ReportTasksSection`) drop it in.+ * It renders the run thread (and, for a live run, the meta bars) with no composer and no approval prompt;+ * see `ReadonlyRunSurfaceImpl` for the layout. For a custom layout, compose the `RunSurface` compound+ * directly (api/runSurface).+ */+export function ReadonlyRunSurface(props: ReadonlyRunSurfaceProps): JSX.Element {+ return (+ <Suspense fallback={<RunLogSkeleton />}>+ <Lazy {...props} />+ </Suspense>+ )+}diff --git a/products/posthog_ai/frontend/components/ReadonlyRunSurfaceImpl.test.tsx b/products/posthog_ai/frontend/components/ReadonlyRunSurfaceImpl.test.tsxnew file mode 100644index 000000000000..d2465a8d9d32--- /dev/null+++ b/products/posthog_ai/frontend/components/ReadonlyRunSurfaceImpl.test.tsx@@ -0,0 +1,77 @@+import '@testing-library/jest-dom'++import { cleanup, render, screen } from '@testing-library/react'+import { useActions, useValues } from 'kea'++import type { PermissionRequestRecord } from '../types/streamTypes'+import ReadonlyRunSurfaceImpl from './ReadonlyRunSurfaceImpl'++jest.mock('kea', () => ({+ ...jest.requireActual('kea'),+ BindLogic: ({ children }: { children: React.ReactNode }) => children,+ useActions: jest.fn(),+ useValues: jest.fn(),+}))++jest.mock('../logics/runStreamLogic', () => ({+ runStreamLogic: jest.fn(() => ({ __mock: 'runStreamLogic' })),+ isTerminalRunStatus: (status: string | null) =>+ status != null && ['completed', 'failed', 'cancelled'].includes(status),+}))++jest.mock('./ThreadView', () => ({ ThreadView: () => <div data-attr="thread" /> }))+jest.mock('./ResourcesBar', () => ({ ResourcesBar: () => <div data-attr="resources" /> }))+jest.mock('./ContextUsageBar', () => ({ ContextUsageBar: () => <div data-attr="context" /> }))+jest.mock('./PermissionInput', () => ({ PermissionInput: () => <div data-attr="permission" /> }))+jest.mock('./QuestionInput', () => ({ QuestionInput: () => <div data-attr="question" /> }))+jest.mock('./RunLogSkeleton', () => ({ RunLogSkeleton: () => <div data-attr="run-log-skeleton" /> }))++function setValues(overrides: Partial<{ pendingPermissionRequest: PermissionRequestRecord | null }> = {}): void {+ ;(useValues as jest.Mock).mockReturnValue({+ bootstrapLoading: false,+ threadItems: [{ id: 'x' }],+ pendingPermissionRequest: null,+ currentRunStatus: 'in_progress',+ ...overrides,+ })+}++describe('ReadonlyRunSurfaceImpl', () => {+ beforeEach(() => {+ jest.clearAllMocks()+ ;(useActions as jest.Mock).mockReturnValue({ bootstrapRun: jest.fn(), reset: jest.fn() })+ setValues()+ })++ afterEach(() => {+ cleanup()+ })++ it('renders only the thread in read-only mode — no meta bars, composer, or prompt', () => {+ render(<ReadonlyRunSurfaceImpl taskId="task-1" runId="run-1" interaction="read-only" />)+ expect(screen.getByTestId('thread')).toBeInTheDocument()+ expect(screen.queryByTestId('resources')).not.toBeInTheDocument()+ expect(screen.queryByTestId('context')).not.toBeInTheDocument()+ expect(screen.queryByTestId('composer')).not.toBeInTheDocument()+ expect(screen.queryByTestId('permission')).not.toBeInTheDocument()+ expect(screen.queryByTestId('question')).not.toBeInTheDocument()+ })++ it('renders the thread plus meta bars for a live run, but never a composer or approval prompt', () => {+ render(<ReadonlyRunSurfaceImpl taskId="task-1" runId="run-1" interaction="live" />)+ expect(screen.getByTestId('thread')).toBeInTheDocument()+ expect(screen.getByTestId('resources')).toBeInTheDocument()+ expect(screen.getByTestId('context')).toBeInTheDocument()+ expect(screen.queryByTestId('composer')).not.toBeInTheDocument()+ expect(screen.queryByTestId('permission')).not.toBeInTheDocument()+ expect(screen.queryByTestId('question')).not.toBeInTheDocument()+ })++ it('stays non-interactive for a live run even when a permission request is pending', () => {+ setValues({ pendingPermissionRequest: { requestId: 'r1' } as PermissionRequestRecord })+ render(<ReadonlyRunSurfaceImpl taskId="task-1" runId="run-1" interaction="live" />)+ expect(screen.queryByTestId('permission')).not.toBeInTheDocument()+ expect(screen.queryByTestId('question')).not.toBeInTheDocument()+ expect(screen.queryByTestId('composer')).not.toBeInTheDocument()+ })+})diff --git a/products/posthog_ai/frontend/components/ReadonlyRunSurfaceImpl.tsx b/products/posthog_ai/frontend/components/ReadonlyRunSurfaceImpl.tsxnew file mode 100644index 000000000000..3b6483901432--- /dev/null+++ b/products/posthog_ai/frontend/components/ReadonlyRunSurfaceImpl.tsx@@ -0,0 +1,47 @@+import { cn } from 'lib/utils/css-classes'++import { RunSurface } from './RunSurfaceImpl'++export interface ReadonlyRunSurfaceProps {+ taskId: string+ runId: string+ /** `'read-only'` (default) replays the snapshot once; `'live'` streams over SSE while the run is in progress. */+ interaction?: 'live' | 'read-only'+ threadListClassName?: string+ threadRowClassName?: string+ className?: string+}++/**+ * Prepackaged read-only run surface — the common inbox embed, owned by the library. Composes the+ * `RunSurface` compound and never renders `<RunSurface.Composer>`, so there is no composer and no approval+ * prompt (you don't act on a run from the inbox). It still streams fresh frames while the run is in progress+ * when `interaction='live'`, surfacing the meta bars (resources + context usage); a terminal run replays the+ * snapshot once and shows only the thread.+ */+export default function ReadonlyRunSurfaceImpl({+ taskId,+ runId,+ interaction = 'read-only',+ threadListClassName,+ threadRowClassName,+ className,+}: ReadonlyRunSurfaceProps): JSX.Element {+ return (+ <RunSurface.Root taskId={taskId} runId={runId} interaction={interaction}>+ {interaction !== 'live' ? (+ <div className={cn('flex flex-col h-full min-h-0 w-full', className)}>+ <RunSurface.Thread listClassName={threadListClassName} rowClassName={threadRowClassName} />+ </div>+ ) : (+ <div className={cn('@container/thread flex flex-col h-full overflow-hidden', className)}>+ <div className="flex-1 min-h-0">+ <RunSurface.Thread listClassName={threadListClassName} rowClassName={threadRowClassName} />+ </div>+ <RunSurface.Resources />+ <RunSurface.ContextUsage />+ </div>+ )}+ </RunSurface.Root>+ )+}diff --git a/products/posthog_ai/frontend/components/RunLogSkeleton.tsx b/products/posthog_ai/frontend/components/RunLogSkeleton.tsxindex e3c419189e6f..53a4afe9cd94 100644--- a/products/posthog_ai/frontend/components/RunLogSkeleton.tsx+++ b/products/posthog_ai/frontend/components/RunLogSkeleton.tsx@@ -5,8 +5,8 @@ import { LemonSkeleton } from '@posthog/lemon-ui'import { cn } from 'lib/utils/css-classes'/**- * Loading state for "a run/task log is loading" — shared by the runner scene, the lazy `RunViewer` chunk's- * Suspense fallback, and `RunViewer`'s in-stream bootstrap. Mirrors `ThreadView`'s centered `max-w-180`+ * Loading state for "a run/task log is loading" — shared by the runner scene, the lazy `ReadonlyRunSurface`+ * chunk's Suspense fallback, and the `RunSurface` in-stream bootstrap. Mirrors `ThreadView`'s centered `max-w-180`* column and `MessageTemplate`'s rounded left/right bubbles so the surface keeps its shape when content* mounts. A `LemonSkeleton`-only leaf, so it stays out of the heavy chunk and is safe as a fallback.*/diff --git a/products/posthog_ai/frontend/components/RunSurfaceImpl.test.tsx b/products/posthog_ai/frontend/components/RunSurfaceImpl.test.tsxnew file mode 100644index 000000000000..729ab83516af--- /dev/null+++ b/products/posthog_ai/frontend/components/RunSurfaceImpl.test.tsx@@ -0,0 +1,183 @@+import '@testing-library/jest-dom'++import { cleanup, render, screen } from '@testing-library/react'+import { useActions, useValues } from 'kea'++import type { RunStatus } from '../logics/runStreamLogic'+import type { PermissionRequestRecord } from '../types/streamTypes'+import { RunSurface } from './RunSurfaceImpl'++jest.mock('kea', () => ({+ ...jest.requireActual('kea'),+ BindLogic: ({ children }: { children: React.ReactNode }) => children,+ useActions: jest.fn(),+ useValues: jest.fn(),+}))++jest.mock('../logics/runStreamLogic', () => ({+ runStreamLogic: jest.fn(() => ({ __mock: 'runStreamLogic' })),+ isTerminalRunStatus: (status: string | null) =>+ status != null && ['completed', 'failed', 'cancelled'].includes(status),+}))++jest.mock('./ThreadView', () => ({ ThreadView: () => <div data-attr="thread" /> }))+jest.mock('./ResourcesBar', () => ({ ResourcesBar: () => <div data-attr="resources" /> }))+jest.mock('./ContextUsageBar', () => ({ ContextUsageBar: () => <div data-attr="context" /> }))+jest.mock('./PermissionInput', () => ({ PermissionInput: () => <div data-attr="permission" /> }))+jest.mock('./QuestionInput', () => ({ QuestionInput: () => <div data-attr="question" /> }))+jest.mock('./RunLogSkeleton', () => ({ RunLogSkeleton: () => <div data-attr="run-log-skeleton" /> }))++function setValues(+ overrides: Partial<{+ currentRunStatus: RunStatus | null+ pendingPermissionRequest: PermissionRequestRecord | null+ bootstrapLoading: boolean+ threadItems: unknown[]+ }>+): void {+ ;(useValues as jest.Mock).mockReturnValue({+ bootstrapLoading: false,+ threadItems: [],+ pendingPermissionRequest: null,+ currentRunStatus: 'in_progress',+ ...overrides,+ })+}++// A live surface with the composer slot rendering an identifiable composer child.+function renderLiveWithComposer(statusOrOverrides: RunStatus | null | Parameters<typeof setValues>[0]): void {+ if (typeof statusOrOverrides === 'object' && statusOrOverrides !== null) {+ setValues(statusOrOverrides)+ } else {+ setValues({ currentRunStatus: statusOrOverrides as RunStatus | null })+ }+ render(+ <RunSurface.Root taskId="task-1" runId="run-1" interaction="live">+ <RunSurface.Thread />+ <RunSurface.Composer>+ <div data-attr="composer-child" />+ </RunSurface.Composer>+ </RunSurface.Root>+ )+}++describe('RunSurface', () => {+ beforeEach(() => {+ jest.clearAllMocks()+ ;(useActions as jest.Mock).mockReturnValue({ bootstrapRun: jest.fn(), reset: jest.fn() })+ setValues({})+ })++ afterEach(() => {+ cleanup()+ })++ describe('Composer slot', () => {+ it.each<RunStatus>(['queued', 'in_progress'])(+ 'renders the composer children for an active run (%s)',+ (status) => {+ renderLiveWithComposer(status)+ expect(screen.getByTestId('composer')).toBeInTheDocument()+ expect(screen.getByTestId('composer-child')).toBeInTheDocument()+ }+ )++ it.each<RunStatus>(['completed', 'failed', 'cancelled'])(+ 'renders the composer children for a terminal run so a new run can be started (%s)',+ (status) => {+ renderLiveWithComposer(status)+ expect(screen.getByTestId('composer')).toBeInTheDocument()+ }+ )++ it('hides the composer during the null bootstrap window', () => {+ renderLiveWithComposer(null)+ expect(screen.queryByTestId('composer')).not.toBeInTheDocument()+ // The thread still renders while bootstrapping.+ expect(screen.getByTestId('thread')).toBeInTheDocument()+ })++ it('renders the permission input instead of the composer when a request is pending', () => {+ renderLiveWithComposer({+ currentRunStatus: 'in_progress',+ pendingPermissionRequest: { requestId: 'r1' } as PermissionRequestRecord,+ })+ expect(screen.getByTestId('permission')).toBeInTheDocument()+ expect(screen.queryByTestId('composer')).not.toBeInTheDocument()+ })++ it('renders the question input when the pending request carries questions', () => {+ renderLiveWithComposer({+ currentRunStatus: 'in_progress',+ pendingPermissionRequest: {+ requestId: 'r1',+ questions: [{ question: 'q' }],+ } as PermissionRequestRecord,+ })+ expect(screen.getByTestId('question')).toBeInTheDocument()+ expect(screen.queryByTestId('composer')).not.toBeInTheDocument()+ })++ it('renders nothing in read-only mode', () => {+ setValues({ currentRunStatus: 'in_progress' })+ render(+ <RunSurface.Root taskId="task-1" runId="run-1" interaction="read-only">+ <RunSurface.Composer>+ <div data-attr="composer-child" />+ </RunSurface.Composer>+ </RunSurface.Root>+ )+ expect(screen.queryByTestId('composer')).not.toBeInTheDocument()+ expect(screen.queryByTestId('composer-child')).not.toBeInTheDocument()+ })++ it('renders only the prompt-when-pending (never a composer) when no children are supplied', () => {+ setValues({+ currentRunStatus: 'in_progress',+ pendingPermissionRequest: { requestId: 'r1' } as PermissionRequestRecord,+ })+ render(+ <RunSurface.Root taskId="task-1" runId="run-1" interaction="live">+ <RunSurface.Composer />+ </RunSurface.Root>+ )+ expect(screen.getByTestId('permission')).toBeInTheDocument()+ expect(screen.queryByTestId('composer')).not.toBeInTheDocument()+ })++ it('renders nothing with no children once settled and no request pending', () => {+ setValues({ currentRunStatus: 'in_progress' })+ render(+ <RunSurface.Root taskId="task-1" runId="run-1" interaction="live">+ <RunSurface.Composer />+ </RunSurface.Root>+ )+ expect(screen.queryByTestId('composer')).not.toBeInTheDocument()+ expect(screen.queryByTestId('permission')).not.toBeInTheDocument()+ })+ })++ describe('Thread slot', () => {+ it('shows the run-log skeleton while bootstrapping with no thread items yet', () => {+ setValues({ bootstrapLoading: true, threadItems: [] })+ render(+ <RunSurface.Root taskId="task-1" runId="run-1" interaction="read-only">+ <RunSurface.Thread />+ </RunSurface.Root>+ )+ expect(screen.getByTestId('run-log-skeleton')).toBeInTheDocument()+ expect(screen.queryByTestId('thread')).not.toBeInTheDocument()+ })++ it('swaps the skeleton for the thread once items arrive', () => {+ setValues({ bootstrapLoading: true, threadItems: [{ id: 'x' }] })+ render(+ <RunSurface.Root taskId="task-1" runId="run-1" interaction="read-only">+ <RunSurface.Thread />+ </RunSurface.Root>+ )+ expect(screen.getByTestId('thread')).toBeInTheDocument()+ expect(screen.queryByTestId('run-log-skeleton')).not.toBeInTheDocument()+ })+ })+})diff --git a/products/posthog_ai/frontend/components/RunSurfaceImpl.tsx b/products/posthog_ai/frontend/components/RunSurfaceImpl.tsxnew file mode 100644index 000000000000..eb3e2abc6f2c--- /dev/null+++ b/products/posthog_ai/frontend/components/RunSurfaceImpl.tsx@@ -0,0 +1,173 @@+import { BindLogic, useActions, useValues } from 'kea'+import { createContext, type ReactNode, useContext, useEffect } from 'react'++import { isTerminalRunStatus, runStreamLogic } from '../logics/runStreamLogic'+import { ContextUsageBar } from './ContextUsageBar'+import { PermissionInput } from './PermissionInput'+import { QuestionInput } from './QuestionInput'+import { ResourcesBar } from './ResourcesBar'+import { RunLogSkeleton } from './RunLogSkeleton'+import { ThreadView } from './ThreadView'++export interface RunSurfaceProps {+ taskId: string+ runId: string+ /** Stable logic key; defaults to `runId` (the run is the unit being viewed). */+ streamKey?: string+ /** Telemetry tag only — omit for conversation-less runs (automation, Slack, signals, PR-triggered). */+ conversationId?: string+ /**+ * `'read-only'` (default) replays the persisted `logs/` snapshot once and never opens SSE — the safe+ * choice for a static surface. `'live'` streams an in-progress run over SSE (falling back to replay once+ * terminal) and arms the `RunSurface.Composer` input slot (approvals/questions + the follow-up composer) —+ * but those affordances appear only if the consumer renders that slot. A consumer can stream live yet stay+ * read-only by setting `interaction='live'` and omitting `<RunSurface.Composer>`. The mode is folded into+ * the logic key, so a live and a read-only surface of the same run can never share state.+ */+ interaction?: 'live' | 'read-only'+}++// `RunSurface.Root` binds a `runStreamLogic` instance and bootstraps the run; the slot components+// (`RunSurface.Thread/.Composer/.Resources/.ContextUsage`) read the bound logic via selectors and the+// run wiring from this context. Consumers compose the slots into a custom layout — there is no default+// layout; the prepackaged read-only embed lives in `ReadonlyRunSurfaceImpl`. State stays in the logic;+// the slots are presentational and the composer UI is supplied by the consumer as children.++interface RunSurfaceContextValue {+ /** Original run id passed to `bootstrapRun`. */+ rawRunId: string+ /** Logic key (used for child stream keys). */+ runId: string+ interaction: 'live' | 'read-only'+}++const RunSurfaceContext = createContext<RunSurfaceContextValue | null>(null)++function useRunSurfaceContext(): RunSurfaceContextValue {+ const ctx = useContext(RunSurfaceContext)+ if (!ctx) {+ throw new Error('RunSurface.* slots must be rendered inside <RunSurface.Root>')+ }+ return ctx+}++export interface RunSurfaceRootProps extends RunSurfaceProps {+ /** Custom composition of `RunSurface.*` slots. */+ children: ReactNode+}++/**+ * Binds a `runStreamLogic` instance (keyed apart from any other stream of the same run), bootstraps+ * the run, and provides the run context the slots read. In `'read-only'` mode it replays the persisted+ * `logs/` snapshot once — no SSE; in `'live'` mode it streams an in-progress run. Renders the given+ * slot children — the consumer owns the layout.+ */+function RunSurfaceRoot({+ taskId,+ runId,+ streamKey,+ conversationId,+ interaction = 'read-only',+ children,+}: RunSurfaceRootProps): JSX.Element {+ const replayOnly = interaction !== 'live'+ const logicKey = streamKey ?? runId+ return (+ <BindLogic logic={runStreamLogic} props={{ streamKey: logicKey, conversationId, replayOnly }}>+ <RunSurfaceContext.Provider+ value={{+ rawRunId: runId,+ runId: logicKey,+ interaction,+ }}+ >+ <RunSurfaceBootstrap taskId={taskId} />+ {children}+ </RunSurfaceContext.Provider>+ </BindLogic>+ )+}++/** Drives the run bootstrap as a side effect; renders nothing. Kept separate so slots stay presentational. */+function RunSurfaceBootstrap({ taskId }: { taskId: string }): null {+ const { rawRunId, interaction } = useRunSurfaceContext()+ const { bootstrapRun, reset } = useActions(runStreamLogic)++ useEffect(() => {+ // Reset first so a reused instance (stable streamKey, changed run) replays/streams the new run+ // cleanly; the bound logic keys read-only instances apart from any live stream of the same run.+ // `interaction` is in the deps so a status transition (live → terminal) re-bootstraps the right+ // mode — the bound logic re-keys on it, so `bootstrapRun`/`reset` are fresh references anyway.+ reset()+ bootstrapRun({ taskId, runId: rawRunId })+ }, [taskId, rawRunId, interaction, bootstrapRun, reset])++ return null+}++/** Thread slot: the streamed run thread, with the shared run-log skeleton during the first bootstrap. */+function RunSurfaceThread({+ className,+ listClassName,+ rowClassName,+}: { className?: string; listClassName?: string; rowClassName?: string } = {}): JSX.Element {+ const { bootstrapLoading, threadItems } = useValues(runStreamLogic)+ const showSkeleton = bootstrapLoading && threadItems.length === 0+ if (showSkeleton) {+ return <RunLogSkeleton className={className} listClassName={listClassName} rowClassName={rowClassName} />+ }+ // An error surfaces as a `handleStreamError` item folded into the thread, so it renders here too.+ return <ThreadView className={className} listClassName={listClassName} rowClassName={rowClassName} />+}++/**+ * Input-region slot: owns prompt-vs-composer precedence and the null-bootstrap gate. While a permission /+ * question request is pending (and the run isn't terminal) it renders the approval prompt; otherwise it+ * renders the consumer's composer `children`. Renders nothing outside live mode, during the `null` bootstrap+ * window, or when no composer children are supplied (e.g. `ReadonlyRunSurface`). The composer thus shows for+ * any settled run status (active runs take a follow-up, terminal runs start a fresh run from the typed+ * message), is hidden during bootstrap, and is replaced by the prompt while a request is pending.+ */+function RunSurfaceComposer({ children }: { children?: ReactNode }): JSX.Element | null {+ const { interaction, runId } = useRunSurfaceContext()+ const { pendingPermissionRequest, currentRunStatus } = useValues(runStreamLogic)+ if (interaction !== 'live') {+ return null+ }+ // Pending approval/question takes precedence over the composer.+ if (pendingPermissionRequest && !isTerminalRunStatus(currentRunStatus)) {+ const isQuestion = !!pendingPermissionRequest.questions && pendingPermissionRequest.questions.length > 0+ return (+ <div className="border-t px-4 py-3">+ {isQuestion ? (+ <QuestionInput streamKey={runId} request={pendingPermissionRequest} />+ ) : (+ <PermissionInput streamKey={runId} request={pendingPermissionRequest} />+ )}+ </div>+ )+ }+ if (!children || currentRunStatus === null) {+ return null // no composer UI supplied (e.g. ReadonlyRunSurface) or pre-bootstrap+ }+ return (+ <div data-attr="composer" className="border-t px-4 py-3">+ {children}+ </div>+ )+}++/**+ * Compound run surface. `RunSurface.Root` binds the stream logic, bootstraps the run, and provides context;+ * the slots (`RunSurface.Thread/.Composer/.Resources/.ContextUsage`) compose into a custom layout — there is+ * no default layout. `RunSurface.Composer` owns the prompt-vs-composer precedence and takes the composer UI+ * as children; the meta slots (`.Resources`/`.ContextUsage`) self-bind and self-hide when empty. For the+ * common no-input embed, prefer the prepackaged `ReadonlyRunSurface` (api/readableRun).+ */+export const RunSurface = Object.assign(RunSurfaceRoot, {+ Root: RunSurfaceRoot,+ Thread: RunSurfaceThread,+ Composer: RunSurfaceComposer,+ Resources: ResourcesBar,+ ContextUsage: ContextUsageBar,+})diff --git a/products/posthog_ai/frontend/components/RunViewer.test.tsx b/products/posthog_ai/frontend/components/RunViewer.test.tsxdeleted file mode 100644index a9dafa31ca6a..000000000000--- a/products/posthog_ai/frontend/components/RunViewer.test.tsx+++ /dev/null@@ -1,135 +0,0 @@-import '@testing-library/jest-dom'--import { cleanup, render, screen } from '@testing-library/react'-import { useActions, useValues } from 'kea'--import type { RunStatus } from '../logics/runStreamLogic'-import type { PermissionRequestRecord } from '../types/streamTypes'-// The compound is exercised synchronously from the impl; the public lazy wrapper is covered separately below.-import { RunViewer as LazyRunViewer } from './RunViewer'-import { RunViewer } from './RunViewerImpl'--jest.mock('kea', () => ({- ...jest.requireActual('kea'),- BindLogic: ({ children }: { children: React.ReactNode }) => children,- useActions: jest.fn(),- useValues: jest.fn(),-}))--jest.mock('../logics/runStreamLogic', () => ({- runStreamLogic: jest.fn(() => ({ __mock: 'runStreamLogic' })),- isTerminalRunStatus: (status: string | null) =>- status != null && ['completed', 'failed', 'cancelled'].includes(status),-}))--jest.mock('./ThreadView', () => ({ ThreadView: () => <div data-attr="thread" /> }))-jest.mock('./ResourcesBar', () => ({ ResourcesBar: () => <div data-attr="resources" /> }))-jest.mock('./ContextUsageBar', () => ({ ContextUsageBar: () => <div data-attr="context" /> }))-jest.mock('./PermissionInput', () => ({ PermissionInput: () => <div data-attr="permission" /> }))-jest.mock('./QuestionInput', () => ({ QuestionInput: () => <div data-attr="question" /> }))--const composerProps = {- composerValue: '',- onComposerChange: jest.fn(),- onComposerSubmit: jest.fn(),- composerLoading: false,-}--function setValues(- overrides: Partial<{- currentRunStatus: RunStatus | null- pendingPermissionRequest: PermissionRequestRecord | null- bootstrapLoading: boolean- threadItems: unknown[]- }>-): void {- ;(useValues as jest.Mock).mockReturnValue({- bootstrapLoading: false,- threadItems: [],- pendingPermissionRequest: null,- currentRunStatus: 'in_progress',- ...overrides,- })-}--describe('RunViewer', () => {- beforeEach(() => {- jest.clearAllMocks()- ;(useActions as jest.Mock).mockReturnValue({ bootstrapRun: jest.fn(), reset: jest.fn() })- setValues({})- })-- afterEach(() => {- cleanup()- })-- const renderLive = (statusOrOverrides: RunStatus | null | Parameters<typeof setValues>[0]): void => {- if (typeof statusOrOverrides === 'object' && statusOrOverrides !== null) {- setValues(statusOrOverrides)- } else {- setValues({ currentRunStatus: statusOrOverrides as RunStatus | null })- }- render(<RunViewer taskId="task-1" runId="run-1" interaction="live" {...composerProps} />)- }-- it.each<RunStatus>(['queued', 'in_progress'])('shows the composer for an active run (%s)', (status) => {- renderLive(status)- expect(screen.getByTestId('composer')).toBeInTheDocument()- })-- it('does not show the composer during the null bootstrap window', () => {- renderLive(null)- expect(screen.queryByTestId('composer')).not.toBeInTheDocument()- // The thread still renders while bootstrapping.- expect(screen.getByTestId('thread')).toBeInTheDocument()- })-- it.each<RunStatus>(['completed', 'failed', 'cancelled'])(- 'shows the composer for a terminal run so a new run can be started (%s)',- (status) => {- renderLive(status)- expect(screen.getByTestId('composer')).toBeInTheDocument()- }- )-- it('shows the permission input instead of the composer when a permission request is pending', () => {- renderLive({- currentRunStatus: 'in_progress',- pendingPermissionRequest: { requestId: 'r1' } as PermissionRequestRecord,- })- expect(screen.getByTestId('permission')).toBeInTheDocument()- expect(screen.queryByTestId('composer')).not.toBeInTheDocument()- })-- it('shows the question input when the pending request carries questions', () => {- renderLive({- currentRunStatus: 'in_progress',- pendingPermissionRequest: { requestId: 'r1', questions: [{ question: 'q' }] } as PermissionRequestRecord,- })- expect(screen.getByTestId('question')).toBeInTheDocument()- expect(screen.queryByTestId('composer')).not.toBeInTheDocument()- })-- it('does not show a composer in read-only mode even for an active run', () => {- setValues({ currentRunStatus: 'in_progress' })- render(<RunViewer taskId="task-1" runId="run-1" interaction="read-only" />)- expect(screen.queryByTestId('composer')).not.toBeInTheDocument()- expect(screen.queryByTestId('resources')).not.toBeInTheDocument()- expect(screen.getByTestId('thread')).toBeInTheDocument()- })-- it('omits the composer in live mode when no composer props are supplied', () => {- setValues({ currentRunStatus: 'in_progress' })- render(<RunViewer taskId="task-1" runId="run-1" interaction="live" />)- expect(screen.queryByTestId('composer')).not.toBeInTheDocument()- })-- it('lazy-loads behind the run-log skeleton, then renders the thread', async () => {- setValues({ currentRunStatus: 'in_progress' })- render(<LazyRunViewer taskId="task-1" runId="run-1" interaction="read-only" />)- // The Suspense fallback shows the shared skeleton while the impl chunk resolves...- expect(screen.getByTestId('run-log-skeleton')).toBeInTheDocument()- // ...then the lazily-imported viewer mounts and the thread appears.- expect(await screen.findByTestId('thread')).toBeInTheDocument()- })-})diff --git a/products/posthog_ai/frontend/components/RunViewer.tsx b/products/posthog_ai/frontend/components/RunViewer.tsxdeleted file mode 100644index cf5f37a3ca3e..000000000000--- a/products/posthog_ai/frontend/components/RunViewer.tsx+++ /dev/null@@ -1,28 +0,0 @@-import { lazy, Suspense } from 'react'--import { RunLogSkeleton } from './RunLogSkeleton'-import type { RunViewerProps } from './RunViewerImpl'--export type { RunViewerProps } from './RunViewerImpl'--// Heavy chunk (stream logic, virtualized thread, tool/diff renderers) loaded on demand; the RunLogSkeleton-// fallback matches the loaded thread, so the surface keeps its shape across chunk-load → bootstrap → first-// frame. Only `react` + the lightweight skeleton are imported statically — the impl is reached solely via-// dynamic `import()` (the type import below is erased), so the chunk genuinely splits.-const LazyRunViewer = lazy(() => import('./RunViewerImpl').then((m) => ({ default: m.RunViewer })))--/**- * Embeddable run surface — binds the stream logic and renders the default layout, code-split behind a- * `RunLogSkeleton` fallback. This is the common embed: all four consumers (the runner scene's- * `TaskRunChat`, and the inbox `ArtefactTaskRun` / `AgentRunDetail` / `ReportTasksSection`) use this- * prepackaged form. The compound (`Root` + slots) stays internal to `RunViewerImpl`, backing the default- * layout — slot atoms aren't surfaced because no consumer composes them and lazy-wrapping each would only- * add Suspense boundaries that never fire.- */-export function RunViewer(props: RunViewerProps): JSX.Element {- return (- <Suspense fallback={<RunLogSkeleton />}>- <LazyRunViewer {...props} />- </Suspense>- )-}diff --git a/products/posthog_ai/frontend/components/RunViewerImpl.tsx b/products/posthog_ai/frontend/components/RunViewerImpl.tsxdeleted file mode 100644index ef21a6332e0a..000000000000--- a/products/posthog_ai/frontend/components/RunViewerImpl.tsx+++ /dev/null@@ -1,313 +0,0 @@-import { BindLogic, useActions, useValues } from 'kea'-import { createContext, type ReactNode, useContext, useEffect } from 'react'--import { cn } from 'lib/utils/css-classes'--import type { QueuedMessage } from '../logics/runInteractionLogic'-import { isTerminalRunStatus, runStreamLogic } from '../logics/runStreamLogic'-import { Composer } from './composer/Composer'-import { ContextUsageBar } from './ContextUsageBar'-import { PermissionInput } from './PermissionInput'-import { QuestionInput } from './QuestionInput'-import { QueuedMessageList } from './QueuedMessageList'-import { ResourcesBar } from './ResourcesBar'-import { RunLogSkeleton } from './RunLogSkeleton'-import { ThreadView } from './ThreadView'--export interface RunViewerProps {- taskId: string- runId: string- /** Stable logic key; defaults to `runId` (the run is the unit being viewed). */- streamKey?: string- /** Telemetry tag only — omit for conversation-less runs (automation, Slack, signals, PR-triggered). */- conversationId?: string- /**- * `'read-only'` (default) replays the persisted `logs/` snapshot once and never opens SSE — the safe- * choice for a static viewer. `'live'` streams an in-progress run over SSE (falling back to replay once- * terminal) and adds approvals/questions plus the follow-up composer. The mode is folded into the logic- * key, so a live and a read-only viewer of the same run can never share state.- */- interaction?: 'live' | 'read-only'- className?: string- /** Applied to the thread's list wrapper (`VirtualizedThread.Root`), not the react-window scroll viewport. */- threadListClassName?: string- /** Applied to each thread item row's centered content (`VirtualizedThread.Row`); header/footer rows excluded. */- threadRowClassName?: string- /**- * Composer wiring — live mode only. Provide all of `composerValue`/`onComposerChange`/`onComposerSubmit`- * to render the follow-up composer; the consumer owns the draft and the send (this module never POSTs- * task commands itself). Omit to stream live without a composer.- */- composerValue?: string- onComposerChange?: (value: string) => void- onComposerSubmit?: () => void- composerLoading?: boolean- composerPlaceholder?: string- /**- * Editable "Up next" queue — live mode only, rendered above the composer when non-empty. Provide all- * three to surface staged follow-ups; the consumer owns the queue (this module never mutates it).- */- queuedMessages?: QueuedMessage[]- onUpdateQueuedMessage?: (id: string, content: string) => void- onRemoveQueuedMessage?: (id: string) => void-}--// --- Compound context --------------------------------------------------------------------------------// `RunViewer.Root` binds a `runStreamLogic` instance and bootstraps the run; the slot components-// (`RunViewer.Thread/.Prompt/.Composer/.Resources/.ContextUsage`) read the bound logic via selectors and-// the run/composer wiring from this context. Consumers either drop the prepackaged `RunViewer`-// (default slot order) or compose the slots themselves for a custom layout. State stays in the logic and-// in the caller-owned composer/queue props — the slots are presentational.--interface RunViewerContextValue {- /** Original run id passed to `bootstrapRun`. */- rawRunId: string- /** Logic key (used for child stream keys). */- runId: string- interaction: 'live' | 'read-only'- composer: {- value?: string- onChange?: (value: string) => void- onSubmit?: () => void- loading?: boolean- placeholder?: string- queuedMessages?: QueuedMessage[]- onUpdateQueuedMessage?: (id: string, content: string) => void- onRemoveQueuedMessage?: (id: string) => void- }-}--const RunViewerContext = createContext<RunViewerContextValue | null>(null)--function useRunViewerContext(): RunViewerContextValue {- const ctx = useContext(RunViewerContext)- if (!ctx) {- throw new Error('RunViewer.* slots must be rendered inside <RunViewer.Root> (or <RunViewer>)')- }- return ctx-}--export interface RunViewerRootProps extends RunViewerProps {- /** Custom composition of `RunViewer.*` slots. Omit to render the prepackaged default layout. */- children?: ReactNode-}--/**- * Binds a `runStreamLogic` instance (keyed apart from any other stream of the same run), bootstraps- * the run, and provides the run/composer context the slots read. In `'read-only'` mode it replays the- * persisted `logs/` snapshot once — no SSE; in `'live'` mode it streams an in-progress run. Renders the- * given slot children, or the prepackaged default layout when none are supplied.- */-function RunViewerRoot({- taskId,- runId,- streamKey,- conversationId,- interaction = 'read-only',- className,- threadListClassName,- threadRowClassName,- composerValue,- onComposerChange,- onComposerSubmit,- composerLoading,- composerPlaceholder,- queuedMessages,- onUpdateQueuedMessage,- onRemoveQueuedMessage,- children,-}: RunViewerRootProps): JSX.Element {- const replayOnly = interaction !== 'live'- const logicKey = streamKey ?? runId- return (- <BindLogic logic={runStreamLogic} props={{ streamKey: logicKey, conversationId, replayOnly }}>- <RunViewerContext.Provider- value={{- rawRunId: runId,- runId: logicKey,- interaction,- composer: {- value: composerValue,- onChange: onComposerChange,- onSubmit: onComposerSubmit,- loading: composerLoading,- placeholder: composerPlaceholder,- queuedMessages,- onUpdateQueuedMessage,- onRemoveQueuedMessage,- },- }}- >- <RunViewerBootstrap taskId={taskId} />- {children ?? (- <DefaultRunViewerLayout- className={className}- threadListClassName={threadListClassName}- threadRowClassName={threadRowClassName}- />- )}- </RunViewerContext.Provider>- </BindLogic>- )-}--/** Drives the run bootstrap as a side effect; renders nothing. Kept separate so slots stay presentational. */-function RunViewerBootstrap({ taskId }: { taskId: string }): null {- const { rawRunId, interaction } = useRunViewerContext()- const { bootstrapRun, reset } = useActions(runStreamLogic)-- useEffect(() => {- // Reset first so a reused instance (stable streamKey, changed run) replays/streams the new run- // cleanly; the bound logic keys read-only instances apart from any live stream of the same run.- // `interaction` is in the deps so a status transition (live → terminal) re-bootstraps the right- // mode — the bound logic re-keys on it, so `bootstrapRun`/`reset` are fresh references anyway.- reset()- bootstrapRun({ taskId, runId: rawRunId })- }, [taskId, rawRunId, interaction, bootstrapRun, reset])-- return null-}--/** Thread slot: the streamed run thread, with the shared run-log skeleton during the first bootstrap. */-function RunViewerThread({- className,- listClassName,- rowClassName,-}: { className?: string; listClassName?: string; rowClassName?: string } = {}): JSX.Element {- const { bootstrapLoading, threadItems } = useValues(runStreamLogic)- const showSkeleton = bootstrapLoading && threadItems.length === 0- if (showSkeleton) {- return <RunLogSkeleton className={className} listClassName={listClassName} rowClassName={rowClassName} />- }- // An error surfaces as a `handleStreamError` item folded into the thread, so it renders here too.- return <ThreadView className={className} listClassName={listClassName} rowClassName={rowClassName} />-}--/**- * Prompt slot: the pending approval / question input. Follows the non-terminal precedence — a pending- * request replaces the composer — and renders nothing outside live mode or once the run is terminal.- */-function RunViewerPrompt(): JSX.Element | null {- const { interaction, runId } = useRunViewerContext()- const { pendingPermissionRequest, currentRunStatus } = useValues(runStreamLogic)- const showApproval = interaction === 'live' && !!pendingPermissionRequest && !isTerminalRunStatus(currentRunStatus)- if (!showApproval) {- return null- }- const isQuestion = !!pendingPermissionRequest!.questions && pendingPermissionRequest!.questions.length > 0- return (- <div className="border-t px-4 py-3">- {isQuestion ? (- <QuestionInput streamKey={runId} request={pendingPermissionRequest!} />- ) : (- <PermissionInput streamKey={runId} request={pendingPermissionRequest!} />- )}- </div>- )-}--/**- * Composer slot: the follow-up composer + editable "Up next" queue. Shows for any settled run status- * (active runs take a follow-up, terminal runs start a fresh run from the typed message); hidden during- * the `null` bootstrap window and whenever a permission/question prompt is pending. Renders nothing unless- * the caller supplied the composer wiring (value/onChange/onSubmit).- */-function RunViewerComposer(): JSX.Element | null {- const { interaction, composer } = useRunViewerContext()- const { pendingPermissionRequest, currentRunStatus } = useValues(runStreamLogic)- const hasComposer =- interaction === 'live' && !!composer.onSubmit && composer.onChange !== undefined && composer.value !== undefined- if (!hasComposer || pendingPermissionRequest || currentRunStatus === null) {- return null- }- const isRunTerminal = isTerminalRunStatus(currentRunStatus)- const { queuedMessages, onUpdateQueuedMessage, onRemoveQueuedMessage } = composer- return (- // Composed from the logic-free Composer.* primitives directly (rather than via RunComposer) so- // the run surface can slot its own footer/actions later. The wrapper keeps a stable `data-attr`.- <div data-attr="composer" className="border-t px-4 py-3">- <Composer.Root- value={composer.value!}- onChange={composer.onChange!}- onSubmit={composer.onSubmit!}- loading={composer.loading}- >- {queuedMessages && queuedMessages.length > 0 && onUpdateQueuedMessage && onRemoveQueuedMessage && (- <Composer.Banner>- <QueuedMessageList- messages={queuedMessages}- onUpdate={onUpdateQueuedMessage}- onRemove={onRemoveQueuedMessage}- />- </Composer.Banner>- )}- <Composer.Frame>- <Composer.Field>- <Composer.Placeholder>- {composer.placeholder ??- (isRunTerminal ? 'Send a message to start a new run…' : 'Send a follow-up message…')}- </Composer.Placeholder>- <Composer.Textarea data-attr="sandbox-composer-input" submitShortcut="cmd-enter" />- </Composer.Field>- </Composer.Frame>- <Composer.Submit data-attr="sandbox-composer-send" />- </Composer.Root>- </div>- )-}--/** Default prepackaged layout: thread, then (live only) resources, prompt, composer, and context usage. */-function DefaultRunViewerLayout({- className,- threadClassName,- threadListClassName,- threadRowClassName,-}: {- className?: string- threadClassName?: string- threadListClassName?: string- threadRowClassName?: string-}): JSX.Element {- const { interaction } = useRunViewerContext()- if (interaction !== 'live') {- return (- <div className={cn('flex flex-col h-full min-h-0 w-full', className)}>- <RunViewerThread- className={threadClassName}- listClassName={threadListClassName}- rowClassName={threadRowClassName}- />- </div>- )- }- return (- <div className={cn('@container/thread flex flex-col h-full overflow-hidden', className)}>- <div className="flex-1 min-h-0">- <RunViewerThread- className={threadClassName}- listClassName={threadListClassName}- rowClassName={threadRowClassName}- />- </div>- <ResourcesBar />- <RunViewerPrompt />- <RunViewerComposer />- <ContextUsageBar />- </div>- )-}--/**- * Compound run surface. `RunViewer.Root` binds the stream logic and provides context; the slots- * (`RunViewer.Thread/.Prompt/.Composer/.Resources/.ContextUsage`) compose into a custom layout, or omit- * children for the prepackaged default. Prefer the `RunViewer` prepackaged component for the- * common embed; reach for the slots only when a surface needs to reorder or wrap the regions.- */-export const RunViewer = Object.assign(RunViewerRoot, {- Root: RunViewerRoot,- Thread: RunViewerThread,- Prompt: RunViewerPrompt,- Composer: RunViewerComposer,- Resources: ResourcesBar,- ContextUsage: ContextUsageBar,-})diff --git a/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskRunChat.tsx b/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskRunChat.tsxindex 035b1fabe8f4..33af5b0f1c91 100644--- a/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskRunChat.tsx+++ b/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskRunChat.tsx@@ -1,11 +1,12 @@import { BindLogic, useActions, useValues } from 'kea'import { runInteractionLogic, type RunInteractionLogicProps } from 'products/posthog_ai/frontend/api/logics'+import { Composer, QueuedMessageList } from 'products/posthog_ai/frontend/api/primitives'+// Eager, NOT the lazy `api/readableRun` facade: the runner scene is already a route-split chunk and the run+// surface is its primary content, so a second `lazy()` would only add a redundant chunk fetch + Suspense+// flash. The inbox embeds keep the lazy `ReadonlyRunSurface`.+import { RunSurface } from 'products/posthog_ai/frontend/api/runSurface'-// Eager, NOT the lazy `api/run` facade: the runner scene is already a route-split chunk and the run viewer is-// its primary content, so a second `lazy()` would only add a redundant chunk fetch + Suspense flash. The inbox-// embeds keep the lazy `RunViewer`. `RunViewerImpl` is an internal sibling, so this is a relative import.-import { RunViewer } from '../../../components/RunViewerImpl'import { taskDetailSceneLogic } from '../taskDetailSceneLogic'export interface TaskRunChatProps {@@ -14,12 +15,12 @@ export interface TaskRunChatProps {}/**- * Live task-run surface. Binds `runInteractionLogic` (the Max-agnostic interaction facade, which- * connects to the shared `runStreamLogic` keyed by `runId`) and renders `RunViewer` in live- * mode with the composer + "Up next" queue wired to it. The composer stays visible after a run finishes;- * sending then starts a fresh run (seeded with the message), and `onRunStarted` re-points scene selection- * to it. The viewer owns bootstrap: it reads the run status from the tasks API and never opens SSE for an- * already-terminal run.+ * Live task-run surface. Binds `runInteractionLogic` (the Max-agnostic interaction facade, which connects to+ * the shared `runStreamLogic` keyed by `runId`) and composes the `RunSurface` compound in live mode with the+ * composer + "Up next" queue wired to it as the `RunSurface.Composer` children. The composer stays visible+ * after a run finishes; sending then starts a fresh run (seeded with the message), and `onRunStarted`+ * re-points scene selection to it. `RunSurface.Root` owns bootstrap: it reads the run status from the tasks+ * API and never opens SSE for an already-terminal run.*/export function TaskRunChat({ taskId, runId }: TaskRunChatProps): JSX.Element {const { setSelectedRunId, loadTaskRuns } = useActions(taskDetailSceneLogic({ taskId }))@@ -40,23 +41,42 @@ export function TaskRunChat({ taskId, runId }: TaskRunChatProps): JSX.Element {}function TaskRunChatContent({ logicProps }: { logicProps: RunInteractionLogicProps }): JSX.Element {- const { draft, isSubmitting, queuedMessages } = useValues(runInteractionLogic(logicProps))+ const { draft, isSubmitting, queuedMessages, isTerminal } = useValues(runInteractionLogic(logicProps))const { setDraft, submit, updateQueuedMessage, removeQueuedMessage } = useActions(runInteractionLogic(logicProps))return (- <RunViewer- taskId={logicProps.taskId}- runId={logicProps.runId}- interaction="live"- threadListClassName="pt-4"- threadRowClassName="pr-4"- composerValue={draft}- onComposerChange={setDraft}- onComposerSubmit={submit}- composerLoading={isSubmitting}- queuedMessages={queuedMessages}- onUpdateQueuedMessage={updateQueuedMessage}- onRemoveQueuedMessage={removeQueuedMessage}- />+ // `RunSurface.Root` binds `runStreamLogic` keyed by `runId`; `runInteractionLogic` connects to the same+ // key, so the composer slot's gating reads the right stream. Don't introduce a diverging `streamKey`.+ <RunSurface.Root taskId={logicProps.taskId} runId={logicProps.runId} interaction="live">+ <div className="@container/thread flex flex-col h-full overflow-hidden">+ <div className="flex-1 min-h-0">+ <RunSurface.Thread listClassName="pt-4" rowClassName="pr-4" />+ </div>+ <RunSurface.Resources />+ <RunSurface.Composer>+ <Composer.Root value={draft} onChange={setDraft} onSubmit={submit} loading={isSubmitting}>+ {queuedMessages.length > 0 && (+ <Composer.Banner>+ <QueuedMessageList+ messages={queuedMessages}+ onUpdate={updateQueuedMessage}+ onRemove={removeQueuedMessage}+ />+ </Composer.Banner>+ )}+ <Composer.Frame>+ <Composer.Field>+ <Composer.Placeholder>+ {isTerminal ? 'Send a message to start a new run…' : 'Send a follow-up message…'}+ </Composer.Placeholder>+ <Composer.Textarea data-attr="sandbox-composer-input" submitShortcut="cmd-enter" />+ </Composer.Field>+ </Composer.Frame>+ <Composer.Submit data-attr="sandbox-composer-send" />+ </Composer.Root>+ </RunSurface.Composer>+ <RunSurface.ContextUsage />+ </div>+ </RunSurface.Root>)}diff --git a/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskRunLog.tsx b/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskRunLog.tsxindex 8625f775284e..1f86c94ea5c3 100644--- a/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskRunLog.tsx+++ b/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskRunLog.tsx@@ -12,7 +12,7 @@ import { TaskRunChat } from './TaskRunChat'* Run-log slot state machine. Reads `taskDetailSceneLogic` directly (no prop drilling) and resolves to* exactly one of: an error banner, a `NotFound`, the shared `RunLogSkeleton`, an empty state, or the live* `TaskRunChat`. The skeleton is the only loading affordance here — once it hands off to `TaskRunChat`, the- * eager `RunViewer` shows the same `RunLogSkeleton` during its own bootstrap, so the transition is seamless.+ * eager `RunSurface` shows the same `RunLogSkeleton` during its own bootstrap, so the transition is seamless.*/export function TaskRunLog({ taskId }: { taskId: string }): JSX.Element | null {const logic = taskDetailSceneLogic({ taskId })