Skip to content

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

perf(phai): lazy-load the embeddable RunViewer and unify the run-log loader (#66185)

Georgiy Tarasov971d73fe31ac
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index 49ab5fe8b4a5..c125fc83b182 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -6777,9 +6777,9 @@ snapshots:
scenes-app-tasks--new-task--light:
hash: v1.k794b7964.0873123f13ccdc83104f94c89d562a43c89b7c2c788e1264f499d38f7a78ad79.Zi2QsmppKkEO3piOxpmRAC-s1BFLahgR9MqWLhWuih0
scenes-app-tasks--task-detail-loading--dark:
- hash: v1.k794b7964.2ca0709e24a1b5958aceed241d0d104873ae9ceb61b0930b0bb6f88bdf4d676c.3VebRCT1zPPVca2Zsn0B85kLidnorEouYgduwKfWBlw
+ hash: v1.k794b7964.4e7464d60099a8450a3bbdce6cd6f55eefab279b3711f96d30bb19d0699460d1.nyXVcroEmfj0PXfsRp6Cx7WDkqF_ViQW3IJgtYBQC6w
scenes-app-tasks--task-detail-loading--light:
- hash: v1.k794b7964.1c97be6dba9ad86d3fc6d4a84f5cceaa2a1083141d8568f7808b817cb4f2fb7c._eMG90otpS6HQM0TEC7LNvFT2s3XzL4nPrhcTKGebNE
+ hash: v1.k794b7964.fff3b9c0672f7b587207e47277a0bf4ea31f3ce5f4e627516d40792d56ceb5b7.19yIVqbDBDJK6bz837XIzMwMGDhfLNAqEjI6HlvISFc
scenes-app-tasks--task-load-error--dark:
hash: v1.k794b7964.b945c04a5f6ce7dce2c1b38e46cf57df2c5f18eb8ba2f7ee8973c78035125465.kggPLzQhG1IhgnDvoy6odZpMs16As580yZ-09bNNr2o
scenes-app-tasks--task-load-error--light:
diff --git a/products/posthog_ai/frontend/AGENTS.md b/products/posthog_ai/frontend/AGENTS.md
index 5b4393cca1ee..0e83fb031140 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 c
preserves 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` (call directly → default layout), `RunComposer` |
-| **2 — Compound primitives** | `api/primitives` | `RunViewer.Root` + slots, `Thread` + atoms, `ThreadView`, `Composer.*`, 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/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 |
**Why the split, not one flat barrel:** the tool registry registers built-ins at module load — a top-level
side effect that is _not_ tree-shaken. A single barrel statically re-exports it alongside the
@@ -39,14 +39,19 @@ reached through an `api/<module>` entry; add new exports to the relevant tier mo
The headline exports per module:
-- **`api/run`** — **`RunViewer`** (Radix-style compound; call directly for the default-layout embed, or use
- `.Root` + slots `.Thread/.Prompt/.Composer/.Resources/.ContextUsage` for a custom layout) and
- **`RunComposer`**.
+- **`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). It is the only form any consumer
+ uses; the compound (`Root` + `.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/primitives`** — **`Thread`** (Radix-style compound: `Thread.Root` is the virtualized presenter, the
atoms `Thread.Message/.Markdown/.Reasoning/.Failure/.Activity/.ToolCall` are the building blocks for
bespoke threads), **`Composer`** (logic-free compound input — the caller owns
- `value`/`onChange`/`onSubmit`), activity primitives, message presenters, and the
- permission/question/resource surfaces.
+ `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
+ presenters, and the permission/question/resource surfaces.
- **`api/logics`** — **`runStreamLogic`** (SSE stream + thread projection, see §3),
**`runInteractionLogic`** (Max-agnostic follow-up/queue facade), status helpers
(`isTerminalRunStatus`, `INITIAL_PERMISSION_MODE`), and thinking-message helpers. Imports only
@@ -125,7 +130,8 @@ api/ # public API facade — the contract (import api/<module>, n
logics.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, Thread, Composer, permission/question/resource surfaces, activity, tool/
+components/ # RunViewer (lazy wrapper) + RunViewerImpl (heavy chunk), RunLogSkeleton (shared loader),
+ # Thread, Composer, permission/question/resource surfaces, activity, tool/
composer/ # the Composer compound
tool/ # 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.md
index 3066e3545fdb..17068603cd6f 100644
--- a/products/posthog_ai/frontend/README.md
+++ b/products/posthog_ai/frontend/README.md
@@ -30,12 +30,12 @@ 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` (call directly → default layout), `RunComposer` | "Just show/drive a run." Inbox read-only embed, tasks embed. |
-| **2 — Compound primitives** | `api/primitives` | `RunViewer.Root` + slots, `Thread` + atoms (`.Message/.Markdown/.Reasoning/.Failure/.Activity/.ToolCall`), `ThreadView`, `Composer.*`, 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/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. |
`api/run` (Tier 1) is built on `api/primitives` (Tier 2); `api/primitives` consumes the headless
`api/logics`/`api/types` (Tier 3). Going down a tier trades convenience for control and a smaller chunk.
@@ -62,17 +62,13 @@ const { queuedMessages } = useValues(runInteractionLogic(props))
<RunViewer taskId={task.id} runId={run.id} />
```
-### Custom layout via `RunViewer.Root` + slots
+### Custom layout via `Thread.*` + the run primitives
-```tsx
-import { RunViewer } from 'products/posthog_ai/frontend/api/run'
-;<RunViewer.Root taskId={task.id} runId={run.id}>
- <RunViewer.Resources />
- <RunViewer.Thread />
- <RunViewer.ContextUsage />
- <RunViewer.Composer />
-</RunViewer.Root>
-```
+`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.
### Bespoke / compact thread via `Thread.*` atoms
diff --git a/products/posthog_ai/frontend/api/primitives.ts b/products/posthog_ai/frontend/api/primitives.ts
index a60ec58fba5c..2ba0e951e6de 100644
--- a/products/posthog_ai/frontend/api/primitives.ts
+++ b/products/posthog_ai/frontend/api/primitives.ts
@@ -1,8 +1,8 @@
// 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, 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, or a custom layout via `RunViewer.Root` + slots.
+// 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.
//
// (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.)
@@ -29,6 +29,7 @@ export { MarkdownMessage } from '../messages/MarkdownMessage'
export { ReasoningAnswer } from '../messages/ReasoningAnswer'
export type { ReasoningAnswerProps } from '../messages/ReasoningAnswer'
export { AssistantFailureMessage } from '../messages/AssistantFailureMessage'
+export { RunLogSkeleton } from '../components/RunLogSkeleton'
// --- Activity primitives ---
export {
diff --git a/products/posthog_ai/frontend/api/run.ts b/products/posthog_ai/frontend/api/run.ts
index 33539e9a9531..2bd61a6ec495 100644
--- a/products/posthog_ai/frontend/api/run.ts
+++ b/products/posthog_ai/frontend/api/run.ts
@@ -1,4 +1,12 @@
+// 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 { RunViewerRootProps, RunViewerProps } 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/components/RunLogSkeleton.tsx b/products/posthog_ai/frontend/components/RunLogSkeleton.tsx
new file mode 100644
index 000000000000..24f427a72326
--- /dev/null
+++ b/products/posthog_ai/frontend/components/RunLogSkeleton.tsx
@@ -0,0 +1,27 @@
+import { memo } from 'react'
+
+import { LemonSkeleton } from '@posthog/lemon-ui'
+
+/**
+ * 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`
+ * 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.
+ */
+export const RunLogSkeleton = memo(function RunLogSkeleton(): JSX.Element {
+ return (
+ <div className="flex flex-col h-full min-h-0 w-full" data-attr="run-log-skeleton">
+ <div className="flex flex-col gap-1.5 w-full max-w-180 mx-auto pt-4">
+ <div className="flex justify-start w-full">
+ <LemonSkeleton className="h-16 w-3/4 rounded-lg" />
+ </div>
+ <div className="flex justify-end w-full">
+ <LemonSkeleton className="h-10 w-1/2 rounded-lg" />
+ </div>
+ <div className="flex justify-start w-full">
+ <LemonSkeleton className="h-24 w-4/5 rounded-lg" />
+ </div>
+ </div>
+ </div>
+ )
+})
diff --git a/products/posthog_ai/frontend/components/RunViewer.test.tsx b/products/posthog_ai/frontend/components/RunViewer.test.tsx
index c1d75e3d6730..a9dafa31ca6a 100644
--- a/products/posthog_ai/frontend/components/RunViewer.test.tsx
+++ b/products/posthog_ai/frontend/components/RunViewer.test.tsx
@@ -5,7 +5,9 @@ import { useActions, useValues } from 'kea'
import type { RunStatus } from '../logics/runStreamLogic'
import type { PermissionRequestRecord } from '../types/streamTypes'
-import { RunViewer } from './RunViewer'
+// 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'),
@@ -121,4 +123,13 @@ describe('RunViewer', () => {
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.tsx
index 2149312cd8eb..cf5f37a3ca3e 100644
--- a/products/posthog_ai/frontend/components/RunViewer.tsx
+++ b/products/posthog_ai/frontend/components/RunViewer.tsx
@@ -1,284 +1,28 @@
-import { BindLogic, useActions, useValues } from 'kea'
-import { createContext, type ReactNode, useContext, useEffect } from 'react'
+import { lazy, Suspense } from 'react'
-import { Spinner } from '@posthog/lemon-ui'
+import { RunLogSkeleton } from './RunLogSkeleton'
+import type { RunViewerProps } from './RunViewerImpl'
-import { cn } from 'lib/utils/css-classes'
+export type { RunViewerProps } from './RunViewerImpl'
-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 { 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
- /**
- * 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
-}
+// 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 })))
/**
- * 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.
+ * 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.
*/
-function RunViewerRoot({
- taskId,
- runId,
- streamKey,
- conversationId,
- interaction = 'read-only',
- className,
- composerValue,
- onComposerChange,
- onComposerSubmit,
- composerLoading,
- composerPlaceholder,
- queuedMessages,
- onUpdateQueuedMessage,
- onRemoveQueuedMessage,
- children,
-}: RunViewerRootProps): JSX.Element {
- const replayOnly = interaction !== 'live'
- const logicKey = streamKey ?? runId
+export function RunViewer(props: RunViewerProps): JSX.Element {
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} />}
- </RunViewerContext.Provider>
- </BindLogic>
+ <Suspense fallback={<RunLogSkeleton />}>
+ <LazyRunViewer {...props} />
+ </Suspense>
)
}
-
-/** 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 a centered spinner during the first bootstrap. */
-function RunViewerThread(): JSX.Element {
- const { bootstrapLoading, threadItems } = useValues(runStreamLogic)
- const showSpinner = bootstrapLoading && threadItems.length === 0
- if (showSpinner) {
- return (
- <div className="flex justify-center py-8">
- <Spinner className="text-2xl" />
- </div>
- )
- }
- // An error surfaces as a `handleStreamError` item folded into the thread, so it renders here too.
- return <ThreadView />
-}
-
-/**
- * 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 }: { className?: 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 />
- </div>
- )
- }
- return (
- <div className={cn('@container/thread flex flex-col h-full overflow-hidden', className)}>
- <div className="flex-1 min-h-0">
- <RunViewerThread />
- </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/components/RunViewerImpl.tsx b/products/posthog_ai/frontend/components/RunViewerImpl.tsx
new file mode 100644
index 000000000000..f9e9e5c0e6ea
--- /dev/null
+++ b/products/posthog_ai/frontend/components/RunViewerImpl.tsx
@@ -0,0 +1,279 @@
+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
+ /**
+ * 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,
+ 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} />}
+ </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(): JSX.Element {
+ const { bootstrapLoading, threadItems } = useValues(runStreamLogic)
+ const showSkeleton = bootstrapLoading && threadItems.length === 0
+ if (showSkeleton) {
+ return <RunLogSkeleton />
+ }
+ // An error surfaces as a `handleStreamError` item folded into the thread, so it renders here too.
+ return <ThreadView />
+}
+
+/**
+ * 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 }: { className?: 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 />
+ </div>
+ )
+ }
+ return (
+ <div className={cn('@container/thread flex flex-col h-full overflow-hidden', className)}>
+ <div className="flex-1 min-h-0">
+ <RunViewerThread />
+ </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/TaskDetailPage.tsx b/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskDetailPage.tsx
index 6aa30af040c2..0c045ff790d6 100644
--- a/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskDetailPage.tsx
+++ b/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskDetailPage.tsx
@@ -28,6 +28,8 @@ import {
ScenePanelInfoSection,
} from '~/layout/scenes/SceneLayout'
+import { RunLogSkeleton } from 'products/posthog_ai/frontend/api/primitives'
+
import { TaskRun } from '../../../types/taskTypes'
import { taskDetailSceneLogic } from '../taskDetailSceneLogic'
import { TaskRunChat } from './TaskRunChat'
@@ -241,17 +243,6 @@ function TaskActionsSkeleton(): JSX.Element {
)
}
-function TaskRunLogSkeleton(): JSX.Element {
- return (
- <div className="flex flex-col gap-3 max-w-6xl mx-auto w-full" data-attr="task-run-log-skeleton">
- <LemonSkeleton className="h-4 w-40" />
- <LemonSkeleton className="h-20 w-11/12" />
- <LemonSkeleton className="h-4 w-32 ml-auto opacity-60" />
- <LemonSkeleton className="h-24 w-4/5 ml-auto opacity-40" />
- </div>
- )
-}
-
function TaskLoadErrorBanner({ message, onRetry }: { message: string; onRetry: () => void }): JSX.Element {
return (
<LemonBanner
@@ -343,7 +334,7 @@ function TaskRunLogState({
return <TaskRunsErrorBanner message={runsError} onRetry={onRetryRuns} />
}
if (runsLoading && runsLength === 0) {
- return <TaskRunLogSkeleton />
+ return <RunLogSkeleton />
}
if (selectedRunNotFound) {
return <NotFound object="task run" className="m-0 py-8" />
@@ -352,7 +343,7 @@ function TaskRunLogState({
return <TaskRunsErrorBanner message={selectedRunError} onRetry={onRetrySelectedRun} />
}
if (selectedRunDataLoading && !selectedRun) {
- return <TaskRunLogSkeleton />
+ return <RunLogSkeleton />
}
if (runsLength === 0 && !selectedRunId) {
return (
@@ -368,5 +359,5 @@ function TaskRunLogState({
</div>
)
}
- return selectedRunId ? <TaskRunLogSkeleton /> : null
+ return selectedRunId ? <RunLogSkeleton /> : null
}