: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
chore(phai): drop Sandbox codename prefix from agent-run surface (#66154)
Georgiy Tarasov0993e41953fd
diff --git a/frontend/src/scenes/inbox/__mocks__/inboxMocks.ts b/frontend/src/scenes/inbox/__mocks__/inboxMocks.tsindex 66e32fe0d0a1..41e71fcb671c 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 `SandboxRunViewer` reads before replaying its log. */+/** The run-status payload (`/runs/:runId`) the `RunViewer` 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 bdee5ddd78eb..1af64f8f5052 100644--- a/frontend/src/scenes/inbox/components/detail/AgentRunDetail.tsx+++ b/frontend/src/scenes/inbox/components/detail/AgentRunDetail.tsx@@ -20,7 +20,7 @@ import { maxGlobalLogic } from 'scenes/max/maxGlobalLogic'import { SANDBOX_BIND_TASK_PARAM } from 'scenes/max/maxLogic'import { urls } from 'scenes/urls'-import { isTerminalRunStatus, SandboxRunViewer } from 'products/posthog_ai/frontend'+import { isTerminalRunStatus, RunViewer } from 'products/posthog_ai/frontend'import { Task, TaskRunStatus } from 'products/tasks/frontend/types'import { inboxReportDetailLogic } from '../../logics/inboxReportDetailLogic'@@ -192,7 +192,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. */}- <SandboxRunViewer taskId={task.id} runId={runId} interaction={replayOnly ? 'read-only' : 'live'} />+ <RunViewer taskId={task.id} runId={runId} interaction={replayOnly ? 'read-only' : 'live'} /></div>)}@@ -243,7 +243,7 @@ export function OpenTaskButton({ taskId, runStatus }: { taskId: string; runStatu/*** Inline "Task log": the selected linked task's agent transcript, rendered with the shared- * `SandboxRunViewer` — live for an in-progress run, static replay once terminal. A `LemonSelect`+ * `RunViewer` — 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.*/@@ -294,7 +294,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 `SandboxRunViewer`), and contributing evidence.+ * inline (`TaskLogSection`, via the shared `RunViewer`), 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 48eca2a5c47c..42c1f8b1211b 100644--- a/frontend/src/scenes/inbox/components/detail/ArtefactTaskRun.tsx+++ b/frontend/src/scenes/inbox/components/detail/ArtefactTaskRun.tsx@@ -6,7 +6,7 @@ import { LemonTag } from '@posthog/lemon-ui'import api from 'lib/api'import { identifierToHuman } from 'lib/utils/strings'-import { isTerminalRunStatus, SandboxRunViewer } from 'products/posthog_ai/frontend'+import { isTerminalRunStatus, RunViewer } from 'products/posthog_ai/frontend'import { Task, TaskRunStatus } from 'products/tasks/frontend/types'import { isCustomAgentTaskRun, taskRunTypeLabel, TaskRunArtefactContent } from './artefactTypes'@@ -15,7 +15,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 `SandboxRunViewer`. Mirrors desktop+ * type), expanding to the task's run transcript via the shared `RunViewer`. Mirrors desktop* `ArtefactTaskRun` (which embeds `TaskLogsPanel`). The task is resolved lazily and the row is* disabled until it loads.*/@@ -106,7 +106,7 @@ export function ArtefactTaskRun({{expanded && task && runId ? (<div className="mt-2 h-[420px] overflow-hidden rounded border border-primary bg-surface-primary">- <SandboxRunViewer taskId={task.id} runId={runId} interaction={replayOnly ? 'read-only' : 'live'} />+ <RunViewer taskId={task.id} runId={runId} interaction={replayOnly ? 'read-only' : 'live'} /></div>) : null}</div>diff --git a/frontend/src/scenes/inbox/components/detail/ReportTasksSection.tsx b/frontend/src/scenes/inbox/components/detail/ReportTasksSection.tsxindex 295266f8b06f..9718e5b119e5 100644--- a/frontend/src/scenes/inbox/components/detail/ReportTasksSection.tsx+++ b/frontend/src/scenes/inbox/components/detail/ReportTasksSection.tsx@@ -3,7 +3,7 @@ import { useActions, useValues } from 'kea'import { IconChevronDown, IconChevronRight, IconTerminal } from '@posthog/icons'import { Spinner } from '@posthog/lemon-ui'-import { isTerminalRunStatus, SandboxRunViewer } from 'products/posthog_ai/frontend'+import { isTerminalRunStatus, RunViewer } from 'products/posthog_ai/frontend'import { TaskRunStatus } from 'products/tasks/frontend/types'import { inboxReportDetailLogic, ReportTaskEntry } from '../../logics/inboxReportDetailLogic'@@ -13,7 +13,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 `SandboxRunViewer` — live for an in-progress run, static+ * the task's run transcript via the shared `RunViewer` — 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.@@ -85,7 +85,7 @@ function TaskRow({<div className="mt-1.5 mb-1 ml-1.5">{runId ? (<div className="h-[420px] overflow-y-auto rounded border border-primary bg-surface-primary">- <SandboxRunViewer+ <RunViewertaskId={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 c6d38e6e41ac..39c370f6ef06 100644--- a/frontend/src/scenes/max/AGENTS.md+++ b/frontend/src/scenes/max/AGENTS.md@@ -14,12 +14,12 @@ This is the scene for **PostHog AI**, PostHog's agent. It hosts **two coexistingPer-concern mapping, `langgraph` (LEGACY, frozen) → `sandbox` (NEW, build here):- **Runtime flag**: `agent_runtime === 'langgraph'` → `agent_runtime === 'sandbox'`-- **Stream logic**: `maxThreadLogic.tsx` (LangGraph stream loop) → `sandboxStreamLogic` (SSE; in `products/posthog_ai/frontend/logics/`)-- **Activity renderer**: `components/Activity/LangGraphActivity.tsx` → `SandboxActivity` (in `products/posthog_ai/frontend/components/`)-- **Thread renderer**: `Thread.tsx` (default path) → `Thread.tsx` binds the surface's `SandboxThreadView`+- **Stream logic**: `maxThreadLogic.tsx` (LangGraph stream loop) → `runStreamLogic` (SSE; in `products/posthog_ai/frontend/logics/`)+- **Activity renderer**: `components/Activity/LangGraphActivity.tsx` → `RunActivity` (in `products/posthog_ai/frontend/components/`)+- **Thread renderer**: `Thread.tsx` (default path) → `Thread.tsx` binds the surface's `ThreadView`- **Context shape**: rich `MaxUIContext` (full objects) → flat `AttachedContext` (typed refs, agent fetches)-- **Approvals**: `DangerousOperationApprovalCard.tsx` / `approvalOperationUtils.ts` → the surface's `SandboxPermissionInput` / `SandboxQuestionInput`-- **Tool widgets**: `messages/` + `messages/adapters/` → the surface's `sandboxToolRegistry` (Max's product renderers register via `messages/adapters/registerMaxToolRenderers`)+- **Approvals**: `DangerousOperationApprovalCard.tsx` / `approvalOperationUtils.ts` → the surface's `PermissionInput` / `QuestionInput`+- **Tool widgets**: `messages/` + `messages/adapters/` → the surface's `toolRegistry` (Max's product renderers register via `messages/adapters/registerMaxToolRenderers`)### Rule: do not extend the LangGraph path unless explicitly asked@@ -34,14 +34,14 @@ If a task genuinely needs the LangGraph path extended, confirm that intent expli## 2. Sandbox architecture & conventions live with the surface-The sandbox runtime's heart — `sandboxStreamLogic` (SSE connection, the append-only `log`, the pure+The sandbox runtime's heart — `runStreamLogic` (SSE connection, the append-only `log`, the pure`foldLogToThread` projection, permission routing) — and the conventions for working on it (logic-not-component, runtime-agnostic plain-props UI, atomic memoized leaves, pure projection) are documented in**`products/posthog_ai/frontend/AGENTS.md`**, where that code now lives. Read it before touching the surface.What's Max-specific on the sandbox path and stays here: `Thread.tsx` branches **high** on-`conversation.agent_runtime` and, for the sandbox branch, binds `sandboxStreamLogic` (keyed by the-conversation id) and renders `SandboxThreadView` from the surface — passing resolved props down, never+`conversation.agent_runtime` and, for the sandbox branch, binds `runStreamLogic` (keyed by the+conversation id) and renders `ThreadView` from the surface — passing resolved props down, neverparsing wire frames in a Max component.## 4. The sandbox surface lives in `products/posthog_ai/frontend`@@ -50,22 +50,22 @@ The conversation-agnostic sandbox run surface (stream logic, thread/tool/permisspolicy, wire types) **no longer lives under `scenes/max`** — it's the composable PostHog AI agent-runlibrary at `products/posthog_ai/frontend`, consumed here via its barrel(`import { ... } from 'products/posthog_ai/frontend'`). See that directory's `AGENTS.md` for its layout,-public component API (`RunViewer`, `Thread`, `Composer`, `sandboxStreamLogic`, the tool registry), and the+public component API (`RunViewer`, `Thread`, `Composer`, `runStreamLogic`, the tool registry), and thehard 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,and Max's **product-specific tool renderers** (`messages/adapters/*`), which register themselves into the-shared `sandboxToolRegistry` via `messages/adapters/registerMaxToolRenderers` (imported once from+shared `toolRegistry` via `messages/adapters/registerMaxToolRenderers` (imported once from`Thread.tsx`). Add a new product tool renderer there, not in `products/posthog_ai/frontend`.## 5. Where do I add X?The first three now live in `products/posthog_ai/frontend` (the shared surface) — make the change there, not in `scenes/max`:-- **A new thread-item type** → `products/posthog_ai/frontend/types/sandboxStreamTypes.ts` (the `ThreadItem` union), handle it in `foldLogToThread`, and add a memoized leaf renderer wired into `SandboxThreadView`/`SandboxThreadRow`.-- **A new permission affordance / auto-approval rule** → `products/posthog_ai/frontend/policy/sandboxToolPolicy.ts`, then surface it through `SandboxPermissionInput`.-- **New stream telemetry** → a guarded `posthog.capture` in the relevant `sandboxStreamLogic` listener (fire-once, suppressed on replay).+- **A new thread-item type** → `products/posthog_ai/frontend/types/streamTypes.ts` (the `ThreadItem` union), handle it in `foldLogToThread`, and add a memoized leaf renderer wired into `ThreadView`/`ThreadRow`.+- **A new permission affordance / auto-approval rule** → `products/posthog_ai/frontend/policy/toolPolicy.ts`, then surface it through `PermissionInput`.+- **New stream telemetry** → a guarded `posthog.capture` in the relevant `runStreamLogic` listener (fire-once, suppressed on replay).- **A new product tool renderer** (renders a PostHog entity) → `scenes/max/messages/adapters/*` + register it in `messages/adapters/registerMaxToolRenderers`.- **New context the agent should see** → extend `AttachedContext` (not `MaxUIContext`).diff --git a/frontend/src/scenes/max/Thread.tsx b/frontend/src/scenes/max/Thread.tsxindex 9610d060bb2a..e4629082e624 100644--- a/frontend/src/scenes/max/Thread.tsx+++ b/frontend/src/scenes/max/Thread.tsx@@ -1,5 +1,5 @@// Side-effect: registers Max's product-specific tool renderers (insight/dashboard/recordings/etc.) into-// the shared sandboxToolRegistry. Imported here so they're registered whenever the Max thread renders.+// the shared toolRegistry. Imported here so they're registered whenever the Max thread renders.import './messages/adapters/registerMaxToolRenderers'import clsx from 'clsx'@@ -74,10 +74,10 @@ import {MarkdownMessage,MessageTemplate,ReasoningAnswer,- SandboxContextUsage,- SandboxResourcesBar,- sandboxStreamLogic,- SandboxThreadView,+ ContextUsageBar,+ ResourcesBar,+ runStreamLogic,+ ThreadView,} from 'products/posthog_ai/frontend'import { LogEntry } from 'products/tasks/frontend/lib/parse-logs'@@ -139,11 +139,11 @@ export function Thread({ className }: { className?: string }): JSX.Element | nul<div className={containerClassName}>{/* Same key maxThreadLogic's connect() uses, so both resolve the same instance */}<BindLogic- logic={sandboxStreamLogic}+ logic={runStreamLogic}props={{ streamKey: sandboxConversationKey, conversationId: sandboxConversationKey }}>{/* The live Max column owns scroll via ThreadAutoScroller — render rows in flow, not virtualized. */}- <SandboxThreadView virtualized={false} />+ <ThreadView virtualized={false} /></BindLogic></div>)@@ -160,10 +160,10 @@ export function Thread({ className }: { className?: string }): JSX.Element | nul<LegacyThread showTrailers={false} /><LemonDivider dashed label="Message history was converted to the new format" className="my-3" /><BindLogic- logic={sandboxStreamLogic}+ logic={runStreamLogic}props={{ streamKey: sandboxConversationKey, conversationId: sandboxConversationKey }}>- <SandboxThreadView virtualized={false} />+ <ThreadView virtualized={false} /></BindLogic></div>)@@ -345,7 +345,7 @@ function LegacyThread({ showTrailers }: { showTrailers: boolean }): JSX.Element/*** Persistent sandbox surfaces mounted between the thread and the sticky composer: the- * "PostHog resources used" bar and the context-usage indicator. Both read `sandboxStreamLogic`+ * "PostHog resources used" bar and the context-usage indicator. Both read `runStreamLogic`* values directly, so this binds the same logic instance `Thread`'s sandbox path uses. Renders* nothing for non-sandbox conversations; the inner components hide themselves when empty.*/@@ -359,12 +359,12 @@ export function SandboxComposerSurfaces(): JSX.Element | null {return (<BindLogic- logic={sandboxStreamLogic}+ logic={runStreamLogic}props={{ streamKey: sandboxConversationKey, conversationId: sandboxConversationKey }}><div className="w-full max-w-180 self-center mx-auto">- <SandboxResourcesBar />- <SandboxContextUsage />+ <ResourcesBar />+ <ContextUsageBar /></div></BindLogic>)diff --git a/frontend/src/scenes/max/components/Activity/index.ts b/frontend/src/scenes/max/components/Activity/index.tsindex bb0a1b5c8ec1..b292e39f5cdd 100644--- a/frontend/src/scenes/max/components/Activity/index.ts+++ b/frontend/src/scenes/max/components/Activity/index.ts@@ -5,7 +5,7 @@ export {ActivityStatusIcon,ActivitySubsteps,ActivityToggleSection,- SandboxActivity,+ RunActivity,ShimmeringContent,} from 'products/posthog_ai/frontend'export type { ActivityStatus } from 'products/posthog_ai/frontend'diff --git a/frontend/src/scenes/max/components/InputFormArea.tsx b/frontend/src/scenes/max/components/InputFormArea.tsxindex 57455246de97..db71efba0249 100644--- a/frontend/src/scenes/max/components/InputFormArea.tsx+++ b/frontend/src/scenes/max/components/InputFormArea.tsx@@ -18,8 +18,8 @@ import {type Option,OptionSelector,QuestionField,- SandboxPermissionInput,- SandboxQuestionInput,+ PermissionInput,+ QuestionInput,} from 'products/posthog_ai/frontend'import { maxThreadLogic } from '../maxThreadLogic'@@ -413,7 +413,7 @@ function DangerousOperationInput({ operation }: DangerousOperationInputProps): J/*** Compact badge showing the active ACP permission mode (e.g. plan vs default) for sandbox* conversations. Hidden when no mode has been reported. Reads the mode via `maxThreadLogic`'s- * alias — this renders outside SandboxThread's BindLogic subtree, so it cannot bind the keyed+ * alias — this renders outside ThreadView's BindLogic subtree, so it cannot bind the keyed* stream logic itself.*/export function SandboxModeBadge(): JSX.Element | null {@@ -466,7 +466,7 @@ export function InputFormArea(): JSX.Element | null {}, [pendingApprovalProposalId, pendingApprovalsData, resolvedApprovalStatuses])// Sandbox permission requests take precedence in the input area, mirroring the LangGraph- // dangerous-operation flow but driven by sandboxStreamLogic. A pending request only ever+ // dangerous-operation flow but driven by runStreamLogic. A pending request only ever// originates from the sandbox stream, so its presence is sufficient — gating on `agent_runtime`// would strand approvals on new conversations whose runtime isn't resolved yet.if (pendingSandboxPermissionRequest) {@@ -474,7 +474,7 @@ export function InputFormArea(): JSX.Element | null {// render the interactive question overlay instead of the approve/decline card.if (pendingSandboxPermissionRequest.questions?.length) {return (- <SandboxQuestionInput+ <QuestionInputkey={pendingSandboxPermissionRequest.requestId}streamKey={sandboxConversationKey}request={pendingSandboxPermissionRequest}@@ -482,7 +482,7 @@ export function InputFormArea(): JSX.Element | null {)}return (- <SandboxPermissionInput+ <PermissionInputkey={pendingSandboxPermissionRequest.requestId}streamKey={sandboxConversationKey}request={pendingSandboxPermissionRequest}diff --git a/frontend/src/scenes/max/maxThreadLogic.test.ts b/frontend/src/scenes/max/maxThreadLogic.test.tsindex 5fb09cdb1803..d091258a0dd1 100644--- a/frontend/src/scenes/max/maxThreadLogic.test.ts+++ b/frontend/src/scenes/max/maxThreadLogic.test.ts@@ -30,7 +30,7 @@ import {import { initKeaTests } from '~/test/init'import { Conversation, ConversationDetail, ConversationStatus, ConversationType } from '~/types'-import { sandboxStreamLogic } from 'products/posthog_ai/frontend'+import { runStreamLogic } from 'products/posthog_ai/frontend'import { EnhancedToolCall, TOOL_DEFINITIONS } from './max-constants'import { maxContextLogic } from './maxContextLogic'@@ -3498,7 +3498,7 @@ describe('maxThreadLogic', () => {expect(maxLogicInstance.values.activeStreamingThreads).toEqual(1)// The thread logic connects to the instance keyed by its own conversationId- const sandboxStreamInstance = sandboxStreamLogic({ streamKey: MOCK_CONVERSATION_ID })+ const sandboxStreamInstance = runStreamLogic({ streamKey: MOCK_CONVERSATION_ID })// The release listeners are synchronous, so the lock state settles with the dispatchsandboxStreamInstance.actions.markTurnComplete()@@ -3521,7 +3521,7 @@ describe('maxThreadLogic', () => {)}).toDispatchActions(['openSandboxSse'])- const sandboxStreamInstance = sandboxStreamLogic({ streamKey: MOCK_CONVERSATION_ID })+ const sandboxStreamInstance = runStreamLogic({ streamKey: MOCK_CONVERSATION_ID })// queued / in_progress frames arrive before the turn is done — the lock must stay held.sandboxStreamInstance.actions.handleTerminalStatus({ status: 'queued' })@@ -3546,7 +3546,7 @@ describe('maxThreadLogic', () => {expect(maxLogicInstance.values.activeStreamingThreads).toEqual(0)expect(- sandboxStreamLogic({ streamKey: MOCK_CONVERSATION_ID }).values.threadItems.some(+ runStreamLogic({ streamKey: MOCK_CONVERSATION_ID }).values.threadItems.some((item) =>item.type === 'error' && item.errorMessage === 'Failed to send your message. Please try again.')@@ -3591,7 +3591,7 @@ describe('maxThreadLogic', () => {delete (globalThis as any).EventSource})- async function startSandboxTurn(): Promise<ReturnType<typeof sandboxStreamLogic.build>> {+ async function startSandboxTurn(): Promise<ReturnType<typeof runStreamLogic.build>> {await expectLogic(logic, () => {logic.actions.streamConversation({ agent_mode: null, is_sandbox: true, content: 'hello', conversation: MOCK_CONVERSATION_ID },@@ -3599,7 +3599,7 @@ describe('maxThreadLogic', () => {)}).toDispatchActions(['openSandboxSse'])expect(logic.values.streamingActive).toBe(true)- return sandboxStreamLogic({ streamKey: MOCK_CONVERSATION_ID })+ return runStreamLogic({ streamKey: MOCK_CONVERSATION_ID })}it('tears down streamingActive on markTurnComplete', async () => {@@ -3695,7 +3695,7 @@ describe('maxThreadLogic', () => {it('history-replay terminal events do not fire teardown while streamingActive is false', async () => {// No live turn: streamingActive is false (no streamConversation was dispatched)expect(logic.values.streamingActive).toBe(false)- const sandboxStreamInstance = sandboxStreamLogic({ streamKey: MOCK_CONVERSATION_ID })+ const sandboxStreamInstance = runStreamLogic({ streamKey: MOCK_CONVERSATION_ID })await expectLogic(logic, () => {sandboxStreamInstance.actions.handleTerminalStatus({ status: 'completed', replayedFromHistory: true })diff --git a/frontend/src/scenes/max/maxThreadLogic.tsx b/frontend/src/scenes/max/maxThreadLogic.tsxindex a712e610130d..58db8c21ca25 100644--- a/frontend/src/scenes/max/maxThreadLogic.tsx+++ b/frontend/src/scenes/max/maxThreadLogic.tsx@@ -67,8 +67,8 @@ import {import {getRandomThinkingMessage,isTerminalRunStatus,- SANDBOX_INITIAL_PERMISSION_MODE,- sandboxStreamLogic,+ INITIAL_PERMISSION_MODE,+ runStreamLogic,} from 'products/posthog_ai/frontend'import { LogEntry, parseLogEvent } from 'products/tasks/frontend/lib/parse-logs'@@ -181,10 +181,10 @@ export const maxThreadLogic = kea<maxThreadLogicType>([// mounts it itself).posthogAiContextLogic({ conversationId }),['attachments as sandboxAttachments'],- // Surfaces the sandbox stream's input-area state to components outside SandboxThread's+ // Surfaces the sandbox stream's input-area state to components outside ThreadView's// BindLogic subtree (the input area renders for LangGraph conversations too, so they// can't bind the keyed stream logic themselves).- sandboxStreamLogic({ streamKey: conversationId, conversationId }),+ runStreamLogic({ streamKey: conversationId, conversationId }),['pendingPermissionRequest as pendingSandboxPermissionRequest', 'currentMode as sandboxCurrentMode'],],actions: [@@ -204,10 +204,10 @@ export const maxThreadLogic = kea<maxThreadLogicType>([maxGlobalLogic,['loadConversation'],// Pulling the action in (rather than calling the instance's actions directly) mounts this- // conversation's stream logic as a dependency, so its listeners actually run. SandboxThread+ // conversation's stream logic as a dependency, so its listeners actually run. ThreadView// only mounts it while a sandbox conversation is rendered — too late for the first message// of a new one.- sandboxStreamLogic({ streamKey: conversationId, conversationId }),+ runStreamLogic({ streamKey: conversationId, conversationId }),['openSseForRun as openSandboxSse','pushHumanMessage as pushSandboxHumanMessage',@@ -669,7 +669,7 @@ export const maxThreadLogic = kea<maxThreadLogicType>([actions.setTraceId(traceId)// Sandbox runtime: route the message to a non-streaming products/tasks Run, then hand the- // SSE connection off to sandboxStreamLogic. The LangGraph EventSource loop below is never+ // SSE connection off to runStreamLogic. The LangGraph EventSource loop below is never// entered for sandbox conversations.//// An *existing* sandbox conversation (`agent_runtime === 'sandbox'`) uses the dedicated@@ -681,9 +681,9 @@ export const maxThreadLogic = kea<maxThreadLogicType>([const isSandboxConversation = isExistingSandboxConversation || !!isSandbox// Echo the human message into whichever thread the renderer actually shows. A sandbox- // conversation renders sandboxStreamLogic's threadItems (not this logic's thread) and+ // conversation renders runStreamLogic's threadItems (not this logic's thread) and// echoes via pushSandboxHumanMessage below; adding it to the legacy thread too would- // briefly show a duplicate (until the runtime resolves to the SandboxThread) that vanishes+ // briefly show a duplicate (until the runtime resolves to the ThreadView) that vanishes// on reload, since sandbox turns live in the run log, not the legacy conversation messages.if (generationAttempt === 0 && streamData.content && addToThread && !isSandboxConversation) {const message: ThreadMessage = {@@ -696,7 +696,7 @@ export const maxThreadLogic = kea<maxThreadLogicType>([}if (isSandboxConversation) {- // SandboxThread renders sandboxStreamLogic's threadItems, not this logic's thread,+ // ThreadView renders runStreamLogic's threadItems, not this logic's thread,// so the human message must be echoed there to show up in the UI.if (generationAttempt === 0 && streamData.content && addToThread) {actions.pushSandboxHumanMessage(streamData.content)@@ -724,7 +724,7 @@ export const maxThreadLogic = kea<maxThreadLogicType>([content: streamData.content,trace_id: traceId,attached_context: attachedContext,- initial_permission_mode: SANDBOX_INITIAL_PERMISSION_MODE,+ initial_permission_mode: INITIAL_PERMISSION_MODE,// Bind a brand-new conversation to an existing Task (inbox "Open task") so the// backend resumes that Task's run. Only the first message carries it....(values.pendingBindTaskId ? { task_id: values.pendingBindTaskId } : {}),@@ -749,7 +749,7 @@ export const maxThreadLogic = kea<maxThreadLogicType>([// The streaming lock must span the whole SSE stream so the input stays// guarded until `_posthog/turn_complete` or a terminal/error event —// mirrors the LangGraph path holding the lock for its entire stream.- // Released exactly once by the sandboxStreamLogic listeners below; the+ // Released exactly once by the runStreamLogic listeners below; the// closure nulls itself so a second terminal event is a no-op.cache.sandboxStreamRelease = (): void => {cache.sandboxStreamRelease = null@@ -983,12 +983,12 @@ export const maxThreadLogic = kea<maxThreadLogicType>([releaseStreamingLock() // release the lock},})),- // Sandbox runs stream through this conversation's sandboxStreamLogic instance, so the streaming+ // Sandbox runs stream through this conversation's runStreamLogic instance, so the streaming// lock taken in streamConversation can only be released when that instance signals the turn// ended — on turn completion, a terminal run status, or a stream error. Its action types are// per-instance (the key is in the path), so they're resolved from props at build time.listeners(({ props, cache, actions, values }) => {- const sandboxStreamActionTypes = sandboxStreamLogic({ streamKey: props.conversationId }).actionTypes+ const sandboxStreamActionTypes = runStreamLogic({ streamKey: props.conversationId }).actionTypes// Normal turn completion: full turn-end, including the sandbox queue-drain that starts the// next queued message (completeThreadGeneration's intended next-turn behavior).const completeSandboxTurn = (): void => {@@ -1011,7 +1011,7 @@ export const maxThreadLogic = kea<maxThreadLogicType>([[sandboxStreamActionTypes.markTurnComplete]: completeSandboxTurn,// handleTerminalStatus fires for every task_run_state frame, including the initial// non-terminal queued/in_progress ones — only tear down on an actually terminal- // status, mirroring sandboxStreamLogic's own guard.+ // status, mirroring runStreamLogic's own guard.[sandboxStreamActionTypes.handleTerminalStatus]: ({ status }: { status: string }) => {if (isTerminalRunStatus(status)) {endSandboxStream()@@ -1095,7 +1095,7 @@ export const maxThreadLogic = kea<maxThreadLogicType>([// pool returns null — nothing to release).const warm = await api.conversations.open(values.conversationId, {content: null,- initial_permission_mode: SANDBOX_INITIAL_PERMISSION_MODE,+ initial_permission_mode: INITIAL_PERMISSION_MODE,})cache.warmRun = warm ? { taskId: warm.task_id, runId: warm.run_id } : nullcache.prewarmed = true@@ -2264,10 +2264,10 @@ export const maxThreadLogic = kea<maxThreadLogicType>([// Sandbox history-load branch. Sandbox conversations don't persist messages Django-side —// history lives in S3 ACP logs, read via the products/tasks logs/ endpoint. Hand off to- // sandboxStreamLogic, which replays logs/ then opens SSE if non-terminal. The LangGraph+ // runStreamLogic, which replays logs/ then opens SSE if non-terminal. The LangGraph// reconnect path below is never entered for sandbox runtimes (coexistence).if (conversation.agent_runtime === 'sandbox') {- // sandboxStreamLogic and posthogAiContextLogic are connected (so already mounted) for this+ // runStreamLogic and posthogAiContextLogic are connected (so already mounted) for this// conversation. Reset their per-conversation state before replaying this run's history.actions.resetSandboxStream()actions.clearSandboxAttachments()diff --git a/frontend/src/scenes/max/maxTypes.ts b/frontend/src/scenes/max/maxTypes.tsindex 4c9c8d6f0be2..cd6c3d929d4f 100644--- a/frontend/src/scenes/max/maxTypes.ts+++ b/frontend/src/scenes/max/maxTypes.ts@@ -243,9 +243,9 @@ export function isAgentMode(mode: unknown): mode is AgentMode {return typeof mode === 'string' && Object.values(AgentMode).includes(mode as AgentMode)}-// `SandboxToolCallMessage` now lives with the relocated sandbox renderer. Re-exported here so+// `ToolCallMessage` now lives with the relocated sandbox renderer. Re-exported here so// the frozen LangGraph path and any in-flight branches keep resolving it from `maxTypes`.-export type { SandboxToolCallMessage } from 'products/posthog_ai/frontend'+export type { ToolCallMessage } from 'products/posthog_ai/frontend'/*** Flat context attachment sent to the sandbox agent runtime (`agent_runtime === 'sandbox'`).diff --git a/frontend/src/scenes/max/messages/adapters/CreateInsightWidget.tsx b/frontend/src/scenes/max/messages/adapters/CreateInsightWidget.tsxindex 07cc27a838bd..1898ffc1803b 100644--- a/frontend/src/scenes/max/messages/adapters/CreateInsightWidget.tsx+++ b/frontend/src/scenes/max/messages/adapters/CreateInsightWidget.tsx@@ -1,4 +1,4 @@-import { GenericMcpToolRenderer, SandboxDataToolRow, type SandboxToolRendererProps } from 'products/posthog_ai/frontend'+import { GenericMcpToolRenderer, DataToolRow, type ToolRendererProps } from 'products/posthog_ai/frontend'import { VisualizationWidget, getArtifactOpenTarget } from '../VisualizationWidget'import { extractVisualizationArtifact } from './extractors'@@ -8,7 +8,7 @@ import { extractVisualizationArtifact } from './extractors'* artifact lands (pending / in-progress / malformed output) we fall back to the generic card so* the call still renders something.*/-export function CreateInsightWidget(props: SandboxToolRendererProps): JSX.Element {+export function CreateInsightWidget(props: ToolRendererProps): JSX.Element {const { message } = propsconst artifact = message.status === 'completed' ? extractVisualizationArtifact(message) : null@@ -19,13 +19,13 @@ export function CreateInsightWidget(props: SandboxToolRendererProps): JSX.Elemenconst target = getArtifactOpenTarget(artifact.envelope, artifact.content)return (- <SandboxDataToolRow {...props}>+ <DataToolRow {...props}><VisualizationWidgetcontent={artifact.content}openUrl={target.url}openTooltip={target.tooltip}embedded/>- </SandboxDataToolRow>+ </DataToolRow>)}diff --git a/frontend/src/scenes/max/messages/adapters/CreateNotebookWidget.test.tsx b/frontend/src/scenes/max/messages/adapters/CreateNotebookWidget.test.tsxindex 1bc8c429b9df..a74b4351a778 100644--- a/frontend/src/scenes/max/messages/adapters/CreateNotebookWidget.test.tsx+++ b/frontend/src/scenes/max/messages/adapters/CreateNotebookWidget.test.tsx@@ -2,12 +2,12 @@// registry. The bare registry no longer knows product keys, so the resolution assertions below need it.import './registerMaxToolRenderers'-import { lookupSandboxToolRenderer, sandboxToolRegistry } from 'products/posthog_ai/frontend'+import { lookupToolRenderer, toolRegistry } from 'products/posthog_ai/frontend'-import type { SandboxToolCallMessage } from '../../maxTypes'+import type { ToolCallMessage } from '../../maxTypes'import { extractNotebook } from './CreateNotebookWidget'-function toolMessage(rawOutput: unknown, innerInput?: Record<string, unknown>): SandboxToolCallMessage {+function toolMessage(rawOutput: unknown, innerInput?: Record<string, unknown>): ToolCallMessage {return {id: 'call-1',resolvedKey: 'notebooks-create',@@ -25,13 +25,13 @@ describe('CreateNotebookWidget', () => {it.each(['notebooks-create', 'notebooks-partial-update', 'notebooks-retrieve', 'notebook-edit'])('resolves %s to the notebook widget',(key) => {- expect(sandboxToolRegistry.lookup(key)?.displayName).toBe('Notebook')- expect(lookupSandboxToolRenderer(key).displayName).toBe('Notebook')+ expect(toolRegistry.lookup(key)?.displayName).toBe('Notebook')+ expect(lookupToolRenderer(key).displayName).toBe('Notebook')})it('falls back to the generic renderer for an unknown inner tool key', () => {- expect(lookupSandboxToolRenderer('some-unwired-tool').displayName).not.toBe('Notebook')+ expect(lookupToolRenderer('some-unwired-tool').displayName).not.toBe('Notebook')})describe('extractNotebook', () => {diff --git a/frontend/src/scenes/max/messages/adapters/CreateNotebookWidget.tsx b/frontend/src/scenes/max/messages/adapters/CreateNotebookWidget.tsxindex d580a2e39a99..e8031f4b0c68 100644--- a/frontend/src/scenes/max/messages/adapters/CreateNotebookWidget.tsx+++ b/frontend/src/scenes/max/messages/adapters/CreateNotebookWidget.tsx@@ -4,7 +4,7 @@ import { LemonButton } from '@posthog/lemon-ui'import { IconOpenInNew } from 'lib/lemon-ui/icons'import { urls } from 'scenes/urls'-import { GenericMcpToolRenderer, SandboxDataToolRow, type SandboxToolRendererProps } from 'products/posthog_ai/frontend'+import { GenericMcpToolRenderer, DataToolRow, type ToolRendererProps } from 'products/posthog_ai/frontend'/** The notebook fields the widget renders, pulled from the REST payload. */export interface NotebookExtraction {@@ -19,7 +19,7 @@ export interface NotebookExtraction {* `short_id` is required: outputs without it aren't a notebook payload and fall back to the* generic card.*/-export function extractNotebook(message: SandboxToolRendererProps['message']): NotebookExtraction | null {+export function extractNotebook(message: ToolRendererProps['message']): NotebookExtraction | null {const output = message.rawOutputif (!output || typeof output !== 'object' || Array.isArray(output)) {return null@@ -44,7 +44,7 @@ export function extractNotebook(message: SandboxToolRendererProps['message']): N* ProseMirror document, not the assistant block format `NotebookArtifactAnswer` renders.* Pre-completion or malformed output falls back to the generic card.*/-export function CreateNotebookWidget(props: SandboxToolRendererProps): JSX.Element {+export function CreateNotebookWidget(props: ToolRendererProps): JSX.Element {const { message } = propsconst notebook = message.status === 'completed' ? extractNotebook(message) : null@@ -53,7 +53,7 @@ export function CreateNotebookWidget(props: SandboxToolRendererProps): JSX.Eleme}return (- <SandboxDataToolRow {...props}>+ <DataToolRow {...props}><div className="flex items-center justify-between gap-2"><div className="flex items-center gap-1.5"><IconNotebook className="text-base" />@@ -69,6 +69,6 @@ export function CreateNotebookWidget(props: SandboxToolRendererProps): JSX.ElemeOpen notebook</LemonButton></div>- </SandboxDataToolRow>+ </DataToolRow>)}diff --git a/frontend/src/scenes/max/messages/adapters/ErrorTrackingWidget.tsx b/frontend/src/scenes/max/messages/adapters/ErrorTrackingWidget.tsxindex 011d0473f95c..d70abb5837cf 100644--- a/frontend/src/scenes/max/messages/adapters/ErrorTrackingWidget.tsx+++ b/frontend/src/scenes/max/messages/adapters/ErrorTrackingWidget.tsx@@ -1,4 +1,4 @@-import { GenericMcpToolRenderer, SandboxDataToolRow, type SandboxToolRendererProps } from 'products/posthog_ai/frontend'+import { GenericMcpToolRenderer, DataToolRow, type ToolRendererProps } from 'products/posthog_ai/frontend'import { ErrorTrackingFiltersWidget } from '../UIPayloadAnswer'import { extractErrorTrackingResponse } from './extractors'@@ -9,7 +9,7 @@ import { extractErrorTrackingResponse } from './extractors'* pushes filters into the error-tracking scene when it is active). Pre-completion or missing output* falls back to the generic card.*/-export function ErrorTrackingWidget(props: SandboxToolRendererProps): JSX.Element {+export function ErrorTrackingWidget(props: ToolRendererProps): JSX.Element {const { message } = propsconst filters = message.status === 'completed' ? extractErrorTrackingResponse(message) : null@@ -18,8 +18,8 @@ export function ErrorTrackingWidget(props: SandboxToolRendererProps): JSX.Elemen}return (- <SandboxDataToolRow {...props}>+ <DataToolRow {...props}><ErrorTrackingFiltersWidget toolCallId={message.id} filters={filters} embedded />- </SandboxDataToolRow>+ </DataToolRow>)}diff --git a/frontend/src/scenes/max/messages/adapters/QueryWidget.tsx b/frontend/src/scenes/max/messages/adapters/QueryWidget.tsxindex 003a009d0e28..27c82061337c 100644--- a/frontend/src/scenes/max/messages/adapters/QueryWidget.tsx+++ b/frontend/src/scenes/max/messages/adapters/QueryWidget.tsx@@ -1,4 +1,4 @@-import { GenericMcpToolRenderer, SandboxDataToolRow, type SandboxToolRendererProps } from 'products/posthog_ai/frontend'+import { GenericMcpToolRenderer, DataToolRow, type ToolRendererProps } from 'products/posthog_ai/frontend'import { VisualizationWidget } from '../VisualizationWidget'import { extractQueryResult } from './extractors'@@ -8,7 +8,7 @@ import { extractQueryResult } from './extractors'* `VisualizationWidget` as inline ephemeral visualizations. Pending calls and outputs without an* inline renderer fall back to the generic card.*/-export function QueryWidget(props: SandboxToolRendererProps): JSX.Element {+export function QueryWidget(props: ToolRendererProps): JSX.Element {const { message } = propsconst result = message.status === 'completed' ? extractQueryResult(message) : null@@ -17,8 +17,8 @@ export function QueryWidget(props: SandboxToolRendererProps): JSX.Element {}return (- <SandboxDataToolRow {...props}>+ <DataToolRow {...props}><VisualizationWidget content={result.content} openUrl={result.url} openTooltip="Open as insight" embedded />- </SandboxDataToolRow>+ </DataToolRow>)}diff --git a/frontend/src/scenes/max/messages/adapters/SearchSessionRecordingsWidget.tsx b/frontend/src/scenes/max/messages/adapters/SearchSessionRecordingsWidget.tsxindex 283da4ca478d..92861e521e98 100644--- a/frontend/src/scenes/max/messages/adapters/SearchSessionRecordingsWidget.tsx+++ b/frontend/src/scenes/max/messages/adapters/SearchSessionRecordingsWidget.tsx@@ -1,4 +1,4 @@-import { GenericMcpToolRenderer, SandboxDataToolRow, type SandboxToolRendererProps } from 'products/posthog_ai/frontend'+import { GenericMcpToolRenderer, DataToolRow, type ToolRendererProps } from 'products/posthog_ai/frontend'import { RecordingsWidget } from '../UIPayloadAnswer'import { extractRecordingFilters } from './extractors'@@ -8,7 +8,7 @@ import { extractRecordingFilters } from './extractors'* in `rawOutput.filters`; `RecordingsWidget` renders the live playlist inline. Pre-completion or a* missing filter object falls back to the generic card.*/-export function SearchSessionRecordingsWidget(props: SandboxToolRendererProps): JSX.Element {+export function SearchSessionRecordingsWidget(props: ToolRendererProps): JSX.Element {const { message } = propsconst filters = message.status === 'completed' ? extractRecordingFilters(message) : null@@ -17,8 +17,8 @@ export function SearchSessionRecordingsWidget(props: SandboxToolRendererProps):}return (- <SandboxDataToolRow {...props}>+ <DataToolRow {...props}><RecordingsWidget toolCallId={message.id} filters={filters} embedded />- </SandboxDataToolRow>+ </DataToolRow>)}diff --git a/frontend/src/scenes/max/messages/adapters/UpsertDashboardWidget.tsx b/frontend/src/scenes/max/messages/adapters/UpsertDashboardWidget.tsxindex 3c7d32d97889..350ea886a376 100644--- a/frontend/src/scenes/max/messages/adapters/UpsertDashboardWidget.tsx+++ b/frontend/src/scenes/max/messages/adapters/UpsertDashboardWidget.tsx@@ -4,7 +4,7 @@ import { LemonButton } from '@posthog/lemon-ui'import { IconOpenInNew } from 'lib/lemon-ui/icons'import { urls } from 'scenes/urls'-import { GenericMcpToolRenderer, SandboxDataToolRow, type SandboxToolRendererProps } from 'products/posthog_ai/frontend'+import { GenericMcpToolRenderer, DataToolRow, type ToolRendererProps } from 'products/posthog_ai/frontend'import { extractDashboard } from './extractors'@@ -13,7 +13,7 @@ import { extractDashboard } from './extractors'* dashboard embed is deliberately deferred). Pre-completion or malformed output falls back to* the generic card.*/-export function UpsertDashboardWidget(props: SandboxToolRendererProps): JSX.Element {+export function UpsertDashboardWidget(props: ToolRendererProps): JSX.Element {const { message } = propsconst dashboard = message.status === 'completed' ? extractDashboard(message) : null@@ -24,7 +24,7 @@ export function UpsertDashboardWidget(props: SandboxToolRendererProps): JSX.Elemconst to = dashboard.url ?? (dashboard.id !== undefined ? urls.dashboard(dashboard.id) : undefined)return (- <SandboxDataToolRow {...props}>+ <DataToolRow {...props}><div className="flex items-center justify-between gap-2"><div className="flex items-center gap-1.5"><IconDashboard className="text-base" />@@ -36,6 +36,6 @@ export function UpsertDashboardWidget(props: SandboxToolRendererProps): JSX.Elem</LemonButton>)}</div>- </SandboxDataToolRow>+ </DataToolRow>)}diff --git a/frontend/src/scenes/max/messages/adapters/extractors.test.ts b/frontend/src/scenes/max/messages/adapters/extractors.test.tsindex 07223a933557..29f0c4802c2d 100644--- a/frontend/src/scenes/max/messages/adapters/extractors.test.ts+++ b/frontend/src/scenes/max/messages/adapters/extractors.test.ts@@ -1,6 +1,6 @@import { ArtifactSource } from '~/queries/schema/schema-assistant-messages'-import type { SandboxToolCallMessage } from '../../maxTypes'+import type { ToolCallMessage } from '../../maxTypes'import {extractDashboard,extractErrorTrackingResponse,@@ -13,7 +13,7 @@ function toolMessage(rawOutput: unknown,innerInput?: Record<string, unknown>,resolvedKey = 'test-tool'-): SandboxToolCallMessage {+): ToolCallMessage {return {id: 'call-1',resolvedKey,diff --git a/frontend/src/scenes/max/messages/adapters/extractors.ts b/frontend/src/scenes/max/messages/adapters/extractors.tsindex b4bd3ae392cf..de41a3893ebe 100644--- a/frontend/src/scenes/max/messages/adapters/extractors.ts+++ b/frontend/src/scenes/max/messages/adapters/extractors.ts@@ -12,11 +12,11 @@ import { DataTableNode, NodeKind, RecordingsQuery } from '~/queries/schema/schemimport { isInsightQueryNode } from '~/queries/utils'import { RecordingUniversalFilters } from '~/types'-import type { SandboxToolCallMessage } from '../../maxTypes'+import type { ToolCallMessage } from '../../maxTypes'/*** Shared shape extractors for the sandbox MCP tool renderer widgets. Each turns a flattened- * `SandboxToolCallMessage` (built by `sandboxStreamLogic` from ACP frames) into the props the atomic+ * `ToolCallMessage` (built by `runStreamLogic` from ACP frames) into the props the atomic* `messages/*` widgets expect.*/@@ -42,7 +42,7 @@ const QUERY_WRAPPER_KIND_BY_TOOL_KEY: Record<string, NodeKind> = {'query-retention-actors': NodeKind.InsightActorsQuery,}-function queryFromToolInput(message: SandboxToolCallMessage): Record<string, unknown> | null {+function queryFromToolInput(message: ToolCallMessage): Record<string, unknown> | null {const input = asRecord(message.innerInput)if (!input) {return null@@ -71,7 +71,7 @@ export interface VisualizationArtifactExtraction {* (create / update / get) carry a `short_id` in the REST payload (or an explicit `artifact_id`);* query-only outputs carry neither and render inline as ephemeral visualizations.*/-export function extractVisualizationArtifact(message: SandboxToolCallMessage): VisualizationArtifactExtraction | null {+export function extractVisualizationArtifact(message: ToolCallMessage): VisualizationArtifactExtraction | null {const output = asRecord(message.rawOutput)if (!output) {return null@@ -117,7 +117,7 @@ export interface QueryResultExtraction {* table-renderable kinds are wrapped in a `DataTableNode` here. Kinds without an inline* renderer (e.g. a single LLM trace) return null and fall back to the generic card.*/-export function extractQueryResult(message: SandboxToolCallMessage): QueryResultExtraction | null {+export function extractQueryResult(message: ToolCallMessage): QueryResultExtraction | null {const output = asRecord(message.rawOutput)const query = (output ? asRecord(output.query) : null) ?? queryFromToolInput(message)if (!query || typeof query.kind !== 'string') {@@ -160,7 +160,7 @@ export interface DashboardExtraction {url?: string}-export function extractDashboard(message: SandboxToolCallMessage): DashboardExtraction | null {+export function extractDashboard(message: ToolCallMessage): DashboardExtraction | null {const output = asRecord(message.rawOutput)if (!output) {return null@@ -179,7 +179,7 @@ export function extractDashboard(message: SandboxToolCallMessage): DashboardExtr* ready-made universal filters object under `rawOutput.filters` is passed through. Anything else* falls back to the generic card rather than feeding the playlist a shape it can't use.*/-export function extractRecordingFilters(message: SandboxToolCallMessage): RecordingUniversalFilters | null {+export function extractRecordingFilters(message: ToolCallMessage): RecordingUniversalFilters | null {const output = asRecord(message.rawOutput)if (!output) {return null@@ -222,7 +222,7 @@ const ERROR_TRACKING_RESPONSE_KEYS: readonly (keyof MaxErrorTrackingSearchRespon* previews) for `ErrorTrackingFiltersWidget`. Outputs that carry none of its fields — e.g. a raw* REST issues list — fall back to the generic card instead of rendering empty filter chips.*/-export function extractErrorTrackingResponse(message: SandboxToolCallMessage): MaxErrorTrackingSearchResponse | null {+export function extractErrorTrackingResponse(message: ToolCallMessage): MaxErrorTrackingSearchResponse | null {const output = asRecord(message.rawOutput)if (!output || !ERROR_TRACKING_RESPONSE_KEYS.some((key) => key in output)) {return nulldiff --git a/frontend/src/scenes/max/messages/adapters/registerMaxToolRenderers.test.ts b/frontend/src/scenes/max/messages/adapters/registerMaxToolRenderers.test.tsindex 9323485a9f34..5c9b96c3a34f 100644--- a/frontend/src/scenes/max/messages/adapters/registerMaxToolRenderers.test.ts+++ b/frontend/src/scenes/max/messages/adapters/registerMaxToolRenderers.test.ts@@ -1,9 +1,9 @@// Importing the module runs its side effect: registering Max's product-specific tool renderers into the-// shared sandboxToolRegistry. We assert the stable key → displayName metadata it contributes (the lazy+// shared toolRegistry. We assert the stable key → displayName metadata it contributes (the lazy// Renderer itself is an opaque chunk).import './registerMaxToolRenderers'-import { sandboxToolRegistry } from 'products/posthog_ai/frontend'+import { toolRegistry } from 'products/posthog_ai/frontend'describe('registerMaxToolRenderers', () => {it.each([@@ -22,7 +22,7 @@ describe('registerMaxToolRenderers', () => {['notebooks-create', 'Notebook'],['notebook-edit', 'Notebook'],])('registers %s into the shared registry with displayName "%s"', (key, displayName) => {- const entry = sandboxToolRegistry.lookup(key)+ const entry = toolRegistry.lookup(key)expect(entry).not.toBeNull()expect(entry?.displayName).toEqual(displayName)})diff --git a/frontend/src/scenes/max/messages/adapters/registerMaxToolRenderers.tsx b/frontend/src/scenes/max/messages/adapters/registerMaxToolRenderers.tsxindex c21041a83667..2ef4d681c23e 100644--- a/frontend/src/scenes/max/messages/adapters/registerMaxToolRenderers.tsx+++ b/frontend/src/scenes/max/messages/adapters/registerMaxToolRenderers.tsx@@ -16,11 +16,11 @@ import {IconWarning,} from '@posthog/icons'-import { sandboxToolRegistry, type SandboxToolRendererProps } from 'products/posthog_ai/frontend'+import { toolRegistry, type ToolRendererProps } from 'products/posthog_ai/frontend'// Product-specific tool-call renderers for the PostHog AI agent run surface. These render PostHog// product entities (insights, dashboards, recordings, error-tracking issues, notebooks, query results)-// and therefore live in scenes/max — the shared `sandboxToolRegistry` must not import them. Importing+// and therefore live in scenes/max — the shared `toolRegistry` must not import them. Importing// this module (done once by the Max scene, see Thread.tsx) registers them into the shared registry so// they're resolved when a sandbox conversation renders the matching tool call. Surfaces that never load// Max (tasks, signals inbox) simply fall through to the generic MCP card for these keys.@@ -45,10 +45,10 @@ function register(keys: string[],displayName: string,icon: JSX.Element,- Renderer: ComponentType<SandboxToolRendererProps>+ Renderer: ComponentType<ToolRendererProps>): void {for (const key of keys) {- sandboxToolRegistry.register({ key, displayName, icon, Renderer })+ toolRegistry.register({ key, displayName, icon, Renderer })}}@@ -114,5 +114,5 @@ const QUERY_WRAPPER_TOOLS: { key: string; displayName: string; icon: JSX.Element{ key: 'query-paths-actors', displayName: 'Paths persons', icon: <IconPerson /> },]for (const { key, displayName, icon } of QUERY_WRAPPER_TOOLS) {- sandboxToolRegistry.register({ key, displayName, icon, Renderer: QueryRenderer })+ toolRegistry.register({ key, displayName, icon, Renderer: QueryRenderer })}diff --git a/products/posthog_ai/frontend/AGENTS.md b/products/posthog_ai/frontend/AGENTS.mdindex 422f27fca9ab..a9d7f7840891 100644--- a/products/posthog_ai/frontend/AGENTS.md+++ b/products/posthog_ai/frontend/AGENTS.md@@ -5,9 +5,9 @@ that render and drive an agent run (the streamed thread, tool cards, approvals,consumed by the Max scene (`frontend/src/scenes/max`), the Tasks product, and the signals inbox — and ismeant to be embeddable anywhere an agent run needs to be shown or interacted with.-> This used to live under a `sandbox/` subfolder; it's now laid out conventionally directly under-> `frontend/`. Many identifiers still carry a `Sandbox*` prefix (the old codename) — that's a pending-> cosmetic rename, not a meaningful boundary.+> This used to live under a `sandbox/` subfolder behind a `Sandbox*` codename prefix; it's now laid out+> conventionally directly under `frontend/` with the prefix dropped. The word "sandbox" that remains is the+> agent _runtime_ (`agent_runtime === 'sandbox'`), a real domain term — not the old codename.## 1. The public API is the barrel (`index.ts`)@@ -16,16 +16,17 @@ paths. The barrel is the contract; internal files can move freely behind it. The- **`RunViewer`** — Radix-style compound for an embeddable run. `RunViewer.Root` binds the stream logic andbootstraps the run; slots `RunViewer.Thread / .Prompt / .Composer / .Resources / .ContextUsage` compose a- custom layout. **`SandboxRunViewer`** is the prepackaged default layout — use it for the common embed.+ custom layout. Calling `RunViewer` directly (`<RunViewer .../>`) renders the prepackaged default layout —+ use that for the common embed.- **`Thread`** — Radix-style compound for the run thread. `Thread.Root` is the virtualized presenter; theatoms `Thread.Message / .Markdown / .Reasoning / .Failure / .Activity / .ToolCall` are the samepresentational building blocks, exposed for bespoke threads.- **`Composer`** — logic-free compound input (`Composer.Root/Frame/Field/Placeholder/Textarea/Footer/Submit/Banner`). The caller owns `value`/`onChange`/`onSubmit`; every part is a styled slot.-- **`sandboxStreamLogic`** — the SSE stream + thread projection (see §3). **`taskRunInteractionLogic`** — the+- **`runStreamLogic`** — the SSE stream + thread projection (see §3). **`runInteractionLogic`** — theMax-agnostic follow-up/queue interaction facade.-- Tool rendering: **`sandboxToolRegistry`**, `lookupSandboxToolRenderer`, `GenericMcpToolRenderer`,- `SandboxToolActivity`, `SandboxDataToolRow`, `EditDiffRenderer`, and the diff/exec helpers.+- Tool rendering: **`toolRegistry`**, `lookupToolRenderer`, `GenericMcpToolRenderer`,+ `ToolActivity`, `DataToolRow`, `EditDiffRenderer`, and the diff/exec helpers.- Permission/question/resource surfaces, message presenters, and the folded-thread types.## 2. Coupling boundary — couples to tasks runs, never to Max@@ -38,11 +39,11 @@ It must stay **free of the Max scene and conversation orchestration**. Do not im`maxThreadLogic`, `maxContextLogic`, `MaxUIContext`, or the conversations API from anywhere under`products/posthog_ai/frontend`. Max is a _consumer_ of this surface, not a dependency of it.-- `sandboxStreamLogic` keys on a generic `streamKey` (conversation id for Max, run/task id for a task+- `runStreamLogic` keys on a generic `streamKey` (conversation id for Max, run/task id for a taskviewer). Keep it generic — no Max-specific branching.- **Product-specific tool renderers live in Max, not here.** Renderers that display PostHog product entities(insights, dashboards, recordings, error-tracking issues, notebooks, query results) live in- `scenes/max/messages/adapters` and register themselves into `sandboxToolRegistry` via+ `scenes/max/messages/adapters` and register themselves into `toolRegistry` via`registerMaxToolRenderers` (imported once by the Max scene). The shared registry only knows the built-ins,the exec verbs, the question card, the generic MCP card, and the generic `EditDiffRenderer`. Surfaces thatnever load Max (tasks, signals inbox) fall through to the generic card for those product keys — by design.@@ -50,7 +51,7 @@ It must stay **free of the Max scene and conversation orchestration**. Do not imand have Max adapt** — never special-case Max in this directory. Enforced by a grep gate:`grep -rE "scenes/max|maxThreadLogic|MaxUIContext" products/posthog_ai/frontend` must be empty.-## 3. Streaming architecture (`logics/sandboxStreamLogic.ts`)+## 3. Streaming architecture (`logics/runStreamLogic.ts`)The heart of the surface:@@ -62,18 +63,18 @@ The heart of the surface:identity, derives the rendered thread.- **Keyed by `streamKey`** so concurrent streams stay independent.-**Permissions:** parse (`parsePermissionRequestFrame`) → route (`policy/sandboxToolPolicy` auto-approves+**Permissions:** parse (`parsePermissionRequestFrame`) → route (`policy/toolPolicy` auto-approvesbuilt-ins + read-only PostHog `exec`, else surfaces a card) → answer (`respondToPermission`) → resolve (pinsthe id so a reconnect replay can't re-surface it).Supporting modules live in `policy/` (tool policy + permission/question utils) and `types/`-(`sandboxStreamTypes` = folded thread shapes; `sandboxWireTypes` = ACP wire shapes + guards). Wire types are+(`streamTypes` = folded thread shapes; `wireTypes` = ACP wire shapes + guards). Wire types areloosely typed — guard at the parse boundary with runtime checks; never assume a field is present.## 4. Conventions- **Logic in the logic, never in a component.** Wire parsing, log folding, SSE handling, telemetry, and- permission routing belong in `sandboxStreamLogic` (or a `policy/` sibling). Components consume selectors+ permission routing belong in `runStreamLogic` (or a `policy/` sibling). Components consume selectorsand dispatch actions.- **Keep UI runtime-agnostic.** Render components take plain props (`ThreadItem`, `ToolInvocation`,`PermissionRequestRecord`); they know nothing about langgraph vs sandbox or the conversation.@@ -91,9 +92,9 @@ index.ts # public API barrel (the contract)components/ # RunViewer, Thread, Composer, permission/question/resource surfaces, activity, tool/composer/ # the Composer compoundtool/ # tool registry + renderers (built-ins, generic MCP, EditDiffRenderer, diff/exec utils)-logics/ # sandboxStreamLogic, taskRunInteractionLogic (+ generated *LogicType.ts)+logics/ # runStreamLogic, runInteractionLogic (+ generated *LogicType.ts)policy/ # tool policy + permission/question utils-types/ # sandboxStreamTypes (folded thread), sandboxWireTypes (ACP), sandboxToolTypes+types/ # streamTypes (folded thread), wireTypes (ACP), toolTypesmessages/ # MessageTemplate, MarkdownMessage, ReasoningAnswer, AssistantFailureMessageutils/ # thinkingMessagesgenerated/ # auto-generated API types (mcp_tools / docs_search) — do not edit by handdiff --git a/products/posthog_ai/frontend/components/SandboxApproval.test.tsx b/products/posthog_ai/frontend/components/Approval.test.tsxsimilarity index 87%rename from products/posthog_ai/frontend/components/SandboxApproval.test.tsxrename to products/posthog_ai/frontend/components/Approval.test.tsxindex 8f9d1a987bb2..8a237748bbb3 100644--- a/products/posthog_ai/frontend/components/SandboxApproval.test.tsx+++ b/products/posthog_ai/frontend/components/Approval.test.tsx@@ -3,8 +3,8 @@ import '@testing-library/jest-dom'import { cleanup, fireEvent, render, screen } from '@testing-library/react'import { useActions, useValues } from 'kea'-import type { PermissionRequestRecord, ToolInvocation } from '../types/sandboxStreamTypes'-import { SandboxPermissionInput } from './SandboxPermissionInput'+import type { PermissionRequestRecord, ToolInvocation } from '../types/streamTypes'+import { PermissionInput } from './PermissionInput'jest.mock('kea', () => ({...jest.requireActual('kea'),@@ -17,9 +17,9 @@ jest.mock('use-resize-observer', () => () => ({ref: { current: null },}))-jest.mock('../logics/sandboxStreamLogic', () => ({- // Keyed logic — the component binds it with `sandboxStreamLogic({ streamKey })`.- sandboxStreamLogic: jest.fn(() => ({ __mock: 'sandboxStreamLogicInstance' })),+jest.mock('../logics/runStreamLogic', () => ({+ // Keyed logic — the component binds it with `runStreamLogic({ streamKey })`.+ runStreamLogic: jest.fn(() => ({ __mock: 'runStreamLogicInstance' })),}))jest.mock('../messages/MarkdownMessage', () => ({@@ -69,9 +69,9 @@ describe('Sandbox approval input area', () => {cleanup()})- describe('SandboxPermissionInput', () => {+ describe('PermissionInput', () => {it('renders the approval prompt with the same two permission options', () => {- render(<SandboxPermissionInput streamKey="conv-1" request={makeRequest()} />)+ render(<PermissionInput streamKey="conv-1" request={makeRequest()} />)expect(screen.getByText('Approval required')).toBeInTheDocument()expect(screen.getByText('posthog - insight-create (MCP)')).toBeInTheDocument()@@ -82,7 +82,7 @@ describe('Sandbox approval input area', () => {it('renders the unwrapped PostHog exec payload like PostHog Code', () => {render(- <SandboxPermissionInput+ <PermissionInputstreamKey="conv-1"request={makeRequest({rawToolCall: {@@ -101,7 +101,7 @@ describe('Sandbox approval input area', () => {})it('posts the chosen optionId on click', () => {- render(<SandboxPermissionInput streamKey="conv-1" request={makeRequest()} />)+ render(<PermissionInput streamKey="conv-1" request={makeRequest()} />)fireEvent.click(screen.getByText('Approve'))@@ -115,7 +115,7 @@ describe('Sandbox approval input area', () => {// The logic's respondingToPermission flag drives the loading state — it flips// synchronously on dispatch and resets on success and on failure alike.;(useValues as jest.Mock).mockReturnValue({ respondingToPermission: true })- render(<SandboxPermissionInput streamKey="conv-1" request={makeRequest()} />)+ render(<PermissionInput streamKey="conv-1" request={makeRequest()} />)// Loading message replaces the option list, so nothing can be clicked.expect(screen.getByText('Sending response…')).toBeInTheDocument()@@ -126,7 +126,7 @@ describe('Sandbox approval input area', () => {it('sends feedback text through the reject_with_feedback option when it is the decline path', () => {render(- <SandboxPermissionInput+ <PermissionInputstreamKey="conv-1"request={makeRequest({options: [@@ -156,7 +156,7 @@ describe('Sandbox approval input area', () => {{ optionId: 'opt-reject', name: 'No', kind: 'reject_once', customInput: true },],})- render(<SandboxPermissionInput streamKey="conv-1" request={request} />)+ render(<PermissionInput streamKey="conv-1" request={request} />)// No optional-feedback affordance — the decline is a plain one-click button.expect(screen.queryByText('Add feedback…')).not.toBeInTheDocument()@@ -182,17 +182,14 @@ describe('Sandbox approval input area', () => {],])('shows plan copy when %s', (_case, arrange, request) => {arrange()- render(<SandboxPermissionInput streamKey="conv-1" request={request} />)+ render(<PermissionInput streamKey="conv-1" request={request} />)expect(screen.getByText('Approve this plan?')).toBeInTheDocument()})it('does not show plan copy just because the title mentions a plan', () => {render(- <SandboxPermissionInput- streamKey="conv-1"- request={makeRequest({ title: 'Create a data retention plan' })}- />+ <PermissionInput streamKey="conv-1" request={makeRequest({ title: 'Create a data retention plan' })} />)expect(screen.getByText('Approval required')).toBeInTheDocument()@@ -200,7 +197,7 @@ describe('Sandbox approval input area', () => {it('falls back to showing every option when filtering would leave none', () => {render(- <SandboxPermissionInput+ <PermissionInputstreamKey="conv-1"request={makeRequest({options: [{ optionId: 'opt-always', name: '', kind: 'allow_always' }],diff --git a/products/posthog_ai/frontend/components/SandboxContextUsage.tsx b/products/posthog_ai/frontend/components/ContextUsageBar.tsxsimilarity index 92%rename from products/posthog_ai/frontend/components/SandboxContextUsage.tsxrename to products/posthog_ai/frontend/components/ContextUsageBar.tsxindex a7f330dfd818..12644d095449 100644--- a/products/posthog_ai/frontend/components/SandboxContextUsage.tsx+++ b/products/posthog_ai/frontend/components/ContextUsageBar.tsx@@ -4,7 +4,7 @@ import { Tooltip } from '@posthog/lemon-ui'import { humanFriendlyNumber } from 'lib/utils/numbers'-import { sandboxStreamLogic } from '../logics/sandboxStreamLogic'+import { runStreamLogic } from '../logics/runStreamLogic'/** Compact SVG ring showing the context-window fill percentage. */function UsageRing({ percentage }: { percentage: number }): JSX.Element {@@ -34,8 +34,8 @@ function UsageRing({ percentage }: { percentage: number }): JSX.Element {* and renders a fill ring + `used / size · %` label when the numeric aggregate is present, plus the* run cost when known. Hidden when there is nothing to show. The breakdown popover is deferred.*/-export function SandboxContextUsage(): JSX.Element | null {- const { contextUsage } = useValues(sandboxStreamLogic)+export function ContextUsageBar(): JSX.Element | null {+ const { contextUsage } = useValues(runStreamLogic)if (!contextUsage) {return nulldiff --git a/products/posthog_ai/frontend/components/SandboxGitArtifacts.test.tsx b/products/posthog_ai/frontend/components/GitArtifacts.test.tsxsimilarity index 55%rename from products/posthog_ai/frontend/components/SandboxGitArtifacts.test.tsxrename to products/posthog_ai/frontend/components/GitArtifacts.test.tsxindex fbc6101be313..d619d306faf6 100644--- a/products/posthog_ai/frontend/components/SandboxGitArtifacts.test.tsx+++ b/products/posthog_ai/frontend/components/GitArtifacts.test.tsx@@ -2,32 +2,32 @@ import '@testing-library/jest-dom'import { cleanup, render, screen } from '@testing-library/react'-import { SandboxPullRequestCard } from './SandboxPullRequestCard'-import { SandboxRunContext } from './SandboxRunContext'+import { PullRequestCard } from './PullRequestCard'+import { RunContext } from './RunContext'const PR_URL = 'https://github.com/PostHog/posthog/pull/123'-// Visibility is the caller's concern (SandboxThread mounts these only when the run reports the+// Visibility is the caller's concern (ThreadView mounts these only when the run reports the// relevant artifact), so these cover only that each renders its data when mounted.describe('sandbox git artifacts', () => {afterEach(() => {cleanup()})- it('SandboxRunContext renders the working and base branch', () => {- render(<SandboxRunContext branch="feat/x" baseBranch="master" repo="PostHog/posthog" />)+ it('RunContext renders the working and base branch', () => {+ render(<RunContext branch="feat/x" baseBranch="master" repo="PostHog/posthog" />)expect(screen.getByText('feat/x')).toBeInTheDocument()expect(screen.getByText('master')).toBeInTheDocument()expect(screen.getByText('PostHog/posthog')).toBeInTheDocument()})- it('SandboxRunContext renders just the branch when there is no base or repo', () => {- render(<SandboxRunContext branch="feat/x" />)+ it('RunContext renders just the branch when there is no base or repo', () => {+ render(<RunContext branch="feat/x" />)expect(screen.getByText('feat/x')).toBeInTheDocument()})- it('SandboxPullRequestCard renders the success card and a link to the PR', () => {- render(<SandboxPullRequestCard prUrl={PR_URL} branch="feat/x" />)+ it('PullRequestCard renders the success card and a link to the PR', () => {+ render(<PullRequestCard prUrl={PR_URL} branch="feat/x" />)expect(screen.getByText('Pull request opened')).toBeInTheDocument()expect(screen.getByText('feat/x')).toBeInTheDocument()expect(screen.getByRole('link', { name: /Open on GitHub/ })).toHaveAttribute('href', PR_URL)diff --git a/products/posthog_ai/frontend/components/SandboxPermissionInput.tsx b/products/posthog_ai/frontend/components/PermissionInput.tsxsimilarity index 90%rename from products/posthog_ai/frontend/components/SandboxPermissionInput.tsxrename to products/posthog_ai/frontend/components/PermissionInput.tsxindex 83628a4c741e..d928ecd12dc5 100644--- a/products/posthog_ai/frontend/components/SandboxPermissionInput.tsx+++ b/products/posthog_ai/frontend/components/PermissionInput.tsx@@ -7,14 +7,14 @@ import { CodeSnippet, Language } from 'lib/components/CodeSnippet'import type { MultiQuestionFormQuestion } from '~/queries/schema/schema-assistant-messages'-import { sandboxStreamLogic } from '../logics/sandboxStreamLogic'+import { runStreamLogic } from '../logics/runStreamLogic'import { MarkdownMessage } from '../messages/MarkdownMessage'-import { getSandboxPermissionDisplay } from '../policy/sandboxPermissionDisplayUtils'-import { mapPermissionOptions, type ApprovalCardOption } from '../policy/sandboxPermissionUtils'-import type { PermissionRequestRecord } from '../types/sandboxStreamTypes'+import { getPermissionDisplay } from '../policy/permissionDisplayUtils'+import { mapPermissionOptions, type ApprovalCardOption } from '../policy/permissionUtils'+import type { PermissionRequestRecord } from '../types/streamTypes'import { QuestionField } from './QuestionField'-interface SandboxPermissionInputProps {+interface PermissionInputProps {streamKey: stringrequest: PermissionRequestRecord}@@ -42,12 +42,12 @@ function toPermissionQuestion(* Reuses the same `QuestionField` surface as sandbox questions while preserving the ACP option ids* sent back to the runtime. `allow_always` stays hidden unless filtering would leave no choices.*- * Submitting POSTs through `sandboxStreamLogic.respondToPermission`; the logic's+ * Submitting POSTs through `runStreamLogic.respondToPermission`; the logic's* `respondingToPermission` drives the loading/double-submit guard and re-enables the controls when the* POST fails (the pending request only clears on success).*/-export function SandboxPermissionInput({ streamKey, request }: SandboxPermissionInputProps): JSX.Element {- const boundLogic = sandboxStreamLogic({ streamKey })+export function PermissionInput({ streamKey, request }: PermissionInputProps): JSX.Element {+ const boundLogic = runStreamLogic({ streamKey })const { respondToPermission } = useActions(boundLogic)const { respondingToPermission, currentMode } = useValues(boundLogic)@@ -67,7 +67,7 @@ export function SandboxPermissionInput({ streamKey, request }: SandboxPermission// `toolCall.kind === 'plan'` covers adapters that tag the request directly.const isPlan = currentMode === 'plan' || request.rawToolCall.kind === 'plan'const prompt = isPlan ? 'Approve this plan?' : 'Approval required'- const display = getSandboxPermissionDisplay(request)+ const display = getPermissionDisplay(request)const payloadLanguage = display.payload?.trim().match(/^[{[]/) ? Language.JSON : Language.Textconst respond = (optionId: string): void => {diff --git a/products/posthog_ai/frontend/components/SandboxPullRequestCard.tsx b/products/posthog_ai/frontend/components/PullRequestCard.tsxsimilarity index 95%rename from products/posthog_ai/frontend/components/SandboxPullRequestCard.tsxrename to products/posthog_ai/frontend/components/PullRequestCard.tsxindex 64ccbf5baad4..6e86488c0cd4 100644--- a/products/posthog_ai/frontend/components/SandboxPullRequestCard.tsx+++ b/products/posthog_ai/frontend/components/PullRequestCard.tsx@@ -10,7 +10,7 @@ import { LemonButton } from '@posthog/lemon-ui'* Frontend-only: it shows the link + branch, no diff stats (those need a backend wire field; see the* logic's follow-ups).*/-export const SandboxPullRequestCard = memo(function SandboxPullRequestCard({+export const PullRequestCard = memo(function PullRequestCard({prUrl,branch,}: {diff --git a/products/posthog_ai/frontend/components/SandboxQuestionInput.test.tsx b/products/posthog_ai/frontend/components/QuestionInput.test.tsxsimilarity index 80%rename from products/posthog_ai/frontend/components/SandboxQuestionInput.test.tsxrename to products/posthog_ai/frontend/components/QuestionInput.test.tsxindex ef83fc9fbe1f..5f78cb451dbe 100644--- a/products/posthog_ai/frontend/components/SandboxQuestionInput.test.tsx+++ b/products/posthog_ai/frontend/components/QuestionInput.test.tsx@@ -3,9 +3,9 @@ import '@testing-library/jest-dom'import { cleanup, fireEvent, render, screen } from '@testing-library/react'import { useActions, useValues } from 'kea'-import type { SandboxQuestion } from '../policy/sandboxQuestionUtils'-import type { PermissionRequestRecord, ToolInvocation } from '../types/sandboxStreamTypes'-import { SandboxQuestionInput } from './SandboxQuestionInput'+import type { AgentQuestion } from '../policy/questionUtils'+import type { PermissionRequestRecord, ToolInvocation } from '../types/streamTypes'+import { QuestionInput } from './QuestionInput'jest.mock('kea', () => ({...jest.requireActual('kea'),@@ -13,8 +13,8 @@ jest.mock('kea', () => ({useValues: jest.fn(),}))-jest.mock('../logics/sandboxStreamLogic', () => ({- sandboxStreamLogic: jest.fn(() => ({ __mock: 'sandboxStreamLogicInstance' })),+jest.mock('../logics/runStreamLogic', () => ({+ runStreamLogic: jest.fn(() => ({ __mock: 'runStreamLogicInstance' })),}))const rawToolCall: ToolInvocation = {@@ -27,7 +27,7 @@ const rawToolCall: ToolInvocation = {meta: { claudeCode: { toolName: 'AskUserQuestion' } },}-function makeRequest(questions: SandboxQuestion[]): PermissionRequestRecord {+function makeRequest(questions: AgentQuestion[]): PermissionRequestRecord {return {requestId: 'req-1',toolCallId: 'tc-1',@@ -42,14 +42,14 @@ function makeRequest(questions: SandboxQuestion[]): PermissionRequestRecord {}}-const goalQuestion: SandboxQuestion = {+const goalQuestion: AgentQuestion = {question: 'Which goal matters most?',header: 'Goal',multiSelect: false,options: [{ label: 'Activation', description: 'aha moment' }, { label: 'Revenue' }],}-describe('SandboxQuestionInput', () => {+describe('QuestionInput', () => {const respondToPermission = jest.fn()beforeEach(() => {@@ -63,7 +63,7 @@ describe('SandboxQuestionInput', () => {})it('renders the header chip, question text, and options via QuestionField', () => {- render(<SandboxQuestionInput streamKey="conv-1" request={makeRequest([goalQuestion])} />)+ render(<QuestionInput streamKey="conv-1" request={makeRequest([goalQuestion])} />)expect(screen.getByText('Goal')).toBeInTheDocument()expect(screen.getByText('Which goal matters most?')).toBeInTheDocument()@@ -73,7 +73,7 @@ describe('SandboxQuestionInput', () => {})it('submits a single-select answer on pick with the derived optionId', () => {- render(<SandboxQuestionInput streamKey="conv-1" request={makeRequest([goalQuestion])} />)+ render(<QuestionInput streamKey="conv-1" request={makeRequest([goalQuestion])} />)// Single-select advances/submits on pick (QuestionField behaviour) — the last question submits.fireEvent.click(screen.getByText('Revenue'))@@ -87,13 +87,13 @@ describe('SandboxQuestionInput', () => {})it('joins multiple selections for a multi-select question', () => {- const productsQuestion: SandboxQuestion = {+ const productsQuestion: AgentQuestion = {question: 'Which products?',header: 'Products',multiSelect: true,options: [{ label: 'Insights' }, { label: 'Replay' }, { label: 'Flags' }],}- render(<SandboxQuestionInput streamKey="conv-1" request={makeRequest([productsQuestion])} />)+ render(<QuestionInput streamKey="conv-1" request={makeRequest([productsQuestion])} />)fireEvent.click(screen.getByText('Insights'))fireEvent.click(screen.getByText('Flags'))@@ -108,7 +108,7 @@ describe('SandboxQuestionInput', () => {})it('sends a free-typed answer through the custom path with option_0 fallback', () => {- render(<SandboxQuestionInput streamKey="conv-1" request={makeRequest([goalQuestion])} />)+ render(<QuestionInput streamKey="conv-1" request={makeRequest([goalQuestion])} />)// Open the custom "Type your answer" field, type, and submit.fireEvent.click(screen.getByText("Explain what you'd like instead."))@@ -124,13 +124,13 @@ describe('SandboxQuestionInput', () => {})it('does not submit a multi-select question with nothing selected', () => {- const productsQuestion: SandboxQuestion = {+ const productsQuestion: AgentQuestion = {question: 'Which products?',header: 'Products',multiSelect: true,options: [{ label: 'Insights' }, { label: 'Replay' }],}- render(<SandboxQuestionInput streamKey="conv-1" request={makeRequest([productsQuestion])} />)+ render(<QuestionInput streamKey="conv-1" request={makeRequest([productsQuestion])} />)fireEvent.click(screen.getByRole('button', { name: 'Submit' }))@@ -139,13 +139,13 @@ describe('SandboxQuestionInput', () => {})it('steps through multiple questions and submits all answers at once', () => {- const second: SandboxQuestion = {+ const second: AgentQuestion = {question: 'Which timeframe?',header: 'Timeframe',multiSelect: false,options: [{ label: 'Weekly' }, { label: 'Monthly' }],}- render(<SandboxQuestionInput streamKey="conv-1" request={makeRequest([goalQuestion, second])} />)+ render(<QuestionInput streamKey="conv-1" request={makeRequest([goalQuestion, second])} />)expect(screen.getByText('1/2')).toBeInTheDocument()// Single-select pick auto-advances to the next question.@@ -166,7 +166,7 @@ describe('SandboxQuestionInput', () => {it('shows a sending state and blocks interaction while a reply is in flight', () => {;(useValues as jest.Mock).mockReturnValue({ respondingToPermission: true })- render(<SandboxQuestionInput streamKey="conv-1" request={makeRequest([goalQuestion])} />)+ render(<QuestionInput streamKey="conv-1" request={makeRequest([goalQuestion])} />)expect(screen.getByText('Sending response…')).toBeInTheDocument()expect(screen.queryByText('Revenue')).not.toBeInTheDocument()diff --git a/products/posthog_ai/frontend/components/SandboxQuestionInput.tsx b/products/posthog_ai/frontend/components/QuestionInput.tsxsimilarity index 91%rename from products/posthog_ai/frontend/components/SandboxQuestionInput.tsxrename to products/posthog_ai/frontend/components/QuestionInput.tsxindex ab0411567144..baa1419d48f9 100644--- a/products/posthog_ai/frontend/components/SandboxQuestionInput.tsx+++ b/products/posthog_ai/frontend/components/QuestionInput.tsx@@ -6,18 +6,18 @@ import { LemonTag, Spinner } from '@posthog/lemon-ui'import type { MultiQuestionFormQuestion } from '~/queries/schema/schema-assistant-messages'-import { sandboxStreamLogic } from '../logics/sandboxStreamLogic'-import { deriveQuestionOptionId, type SandboxQuestion } from '../policy/sandboxQuestionUtils'-import type { PermissionRequestRecord } from '../types/sandboxStreamTypes'+import { runStreamLogic } from '../logics/runStreamLogic'+import { deriveQuestionOptionId, type AgentQuestion } from '../policy/questionUtils'+import type { PermissionRequestRecord } from '../types/streamTypes'import { QuestionField } from './QuestionField'-interface SandboxQuestionInputProps {+interface QuestionInputProps {streamKey: stringrequest: PermissionRequestRecord}/** Adapt a sandbox question onto the `MultiQuestionFormQuestion` shape `QuestionField` renders. */-function toFormQuestion(question: SandboxQuestion, index: number): MultiQuestionFormQuestion {+function toFormQuestion(question: AgentQuestion, index: number): MultiQuestionFormQuestion {return {id: String(index),title: question.header ?? 'Question',@@ -38,7 +38,7 @@ function selectedLabels(answer: string | string[] | undefined): string[] {/*** Interactive input-area overlay for an `AskUserQuestion` on a sandbox conversation. The agent (Twig)* routes questions through the ACP permission framework, so this rides the same `pendingPermissionRequest`- * rails as `SandboxPermissionInput` but renders the question(s) instead of an approve/decline card.+ * rails as `PermissionInput` but renders the question(s) instead of an approve/decline card.** It reuses the LangGraph `QuestionField` (and therefore `OptionSelector` / `LemonCheckbox`) for the* options, and mirrors `MultiQuestionFormInput`'s flow: single-select answers advance on pick,@@ -47,8 +47,8 @@ function selectedLabels(answer: string | string[] | undefined): string[] {* text — the agent reads `_meta.answers`; `optionId` only has to be a valid offered option (derived* from the first question's selection). `respondingToPermission` drives the loading / double-submit guard.*/-export function SandboxQuestionInput({ streamKey, request }: SandboxQuestionInputProps): JSX.Element | null {- const boundLogic = sandboxStreamLogic({ streamKey })+export function QuestionInput({ streamKey, request }: QuestionInputProps): JSX.Element | null {+ const boundLogic = runStreamLogic({ streamKey })const { respondToPermission } = useActions(boundLogic)const { respondingToPermission } = useValues(boundLogic)diff --git a/products/posthog_ai/frontend/components/SandboxQuestionRenderer.test.tsx b/products/posthog_ai/frontend/components/QuestionRenderer.test.tsxsimilarity index 88%rename from products/posthog_ai/frontend/components/SandboxQuestionRenderer.test.tsxrename to products/posthog_ai/frontend/components/QuestionRenderer.test.tsxindex 0069e243ecf7..3c6a18d07e73 100644--- a/products/posthog_ai/frontend/components/SandboxQuestionRenderer.test.tsx+++ b/products/posthog_ai/frontend/components/QuestionRenderer.test.tsx@@ -2,11 +2,11 @@ import '@testing-library/jest-dom'import { cleanup, fireEvent, render, screen } from '@testing-library/react'-import type { SandboxToolCallMessage } from 'products/posthog_ai/frontend/types/sandboxToolTypes'+import type { ToolCallMessage } from 'products/posthog_ai/frontend/types/toolTypes'-import { SandboxQuestionRenderer } from './SandboxQuestionRenderer'+import { QuestionRenderer } from './QuestionRenderer'-function makeMessage(overrides: Partial<SandboxToolCallMessage> = {}): SandboxToolCallMessage {+function makeMessage(overrides: Partial<ToolCallMessage> = {}): ToolCallMessage {return {id: 'tc-1',resolvedKey: 'AskUserQuestion',@@ -29,11 +29,11 @@ function makeMessage(overrides: Partial<SandboxToolCallMessage> = {}): SandboxTo}}-function renderCard(message: SandboxToolCallMessage): void {- render(<SandboxQuestionRenderer message={message} isLastInGroup displayName="Question" />)+function renderCard(message: ToolCallMessage): void {+ render(<QuestionRenderer message={message} isLastInGroup displayName="Question" />)}-describe('SandboxQuestionRenderer', () => {+describe('QuestionRenderer', () => {afterEach(() => {cleanup()})diff --git a/products/posthog_ai/frontend/components/SandboxQuestionRenderer.tsx b/products/posthog_ai/frontend/components/QuestionRenderer.tsxsimilarity index 85%rename from products/posthog_ai/frontend/components/SandboxQuestionRenderer.tsxrename to products/posthog_ai/frontend/components/QuestionRenderer.tsxindex 6711a063c03e..2bd8bf6fafc5 100644--- a/products/posthog_ai/frontend/components/SandboxQuestionRenderer.tsx+++ b/products/posthog_ai/frontend/components/QuestionRenderer.tsx@@ -4,19 +4,19 @@ import {extractSandboxQuestionAnswer,parseSandboxQuestionAnswers,parseSandboxQuestions,-} from '../policy/sandboxQuestionUtils'+} from '../policy/questionUtils'import { GenericMcpToolRenderer } from './tool/GenericMcpToolRenderer'-import { SandboxToolActivity } from './tool/SandboxToolActivity'-import type { SandboxToolRendererProps } from './tool/sandboxToolRegistry'+import { ToolActivity } from './tool/ToolActivity'import { truncateText } from './tool/toolContentUtils'+import type { ToolRendererProps } from './tool/toolRegistry'/*** Thread recap for the `AskUserQuestion` Claude built-in. The interactive answering happens in the- * input overlay (`SandboxQuestionInput`); this is the transcript record: the chosen answers preview on+ * input overlay (`QuestionInput`); this is the transcript record: the chosen answers preview on* the header's second line, and the full question + answer in the expandable body. Malformed input* falls back to the generic tool card.*/-export function SandboxQuestionRenderer(props: SandboxToolRendererProps): JSX.Element {+export function QuestionRenderer(props: ToolRendererProps): JSX.Element {const { message, icon, displayName, turnComplete, turnCancelled } = propsconst questions = parseSandboxQuestions(message.rawInput)@@ -52,7 +52,7 @@ export function SandboxQuestionRenderer(props: SandboxToolRendererProps): JSX.El) : undefinedreturn (- <SandboxToolActivity+ <ToolActivitymessage={message}icon={icon ?? <IconAI />}title={message.title || displayName || 'Question'}diff --git a/products/posthog_ai/frontend/components/QueuedMessageList.stories.tsx b/products/posthog_ai/frontend/components/QueuedMessageList.stories.tsxindex 31a09a694946..513a64f43bc1 100644--- a/products/posthog_ai/frontend/components/QueuedMessageList.stories.tsx+++ b/products/posthog_ai/frontend/components/QueuedMessageList.stories.tsx@@ -1,7 +1,7 @@import type { Meta, StoryObj } from '@storybook/react'import { useState } from 'react'-import type { QueuedMessage } from '../logics/taskRunInteractionLogic'+import type { QueuedMessage } from '../logics/runInteractionLogic'import { QueuedMessageList } from './QueuedMessageList'// Logic-free and controlled — the story owns the queue and wires `onUpdate` / `onRemove`, exactly as thediff --git a/products/posthog_ai/frontend/components/QueuedMessageList.tsx b/products/posthog_ai/frontend/components/QueuedMessageList.tsxindex 9c7d36a05fc9..70178974fdbd 100644--- a/products/posthog_ai/frontend/components/QueuedMessageList.tsx+++ b/products/posthog_ai/frontend/components/QueuedMessageList.tsx@@ -3,7 +3,7 @@ import { useEffect, useRef, useState } from 'react'import { IconCheck, IconPencil, IconTrash, IconX } from '@posthog/icons'import { LemonButton, LemonTextArea } from '@posthog/lemon-ui'-import type { QueuedMessage } from '../logics/taskRunInteractionLogic'+import type { QueuedMessage } from '../logics/runInteractionLogic'interface QueuedMessageListProps {messages: QueuedMessage[]diff --git a/products/posthog_ai/frontend/components/SandboxResourcesBar.tsx b/products/posthog_ai/frontend/components/ResourcesBar.tsxsimilarity index 88%rename from products/posthog_ai/frontend/components/SandboxResourcesBar.tsxrename to products/posthog_ai/frontend/components/ResourcesBar.tsxindex 7d9e49b9b3cd..0f2711cdd238 100644--- a/products/posthog_ai/frontend/components/SandboxResourcesBar.tsx+++ b/products/posthog_ai/frontend/components/ResourcesBar.tsx@@ -2,7 +2,7 @@ import { useValues } from 'kea'import { Tooltip } from '@posthog/lemon-ui'-import { sandboxStreamLogic } from '../logics/sandboxStreamLogic'+import { runStreamLogic } from '../logics/runStreamLogic'import { resolveProductMeta } from '../messages/posthogProducts'/**@@ -11,8 +11,8 @@ import { resolveProductMeta } from '../messages/posthogProducts'* product the agent grounded an answer in. Hidden when empty. Each chip is a product icon plus a* Sentence-cased label; unknown ids degrade to the wire label and a generic icon.*/-export function SandboxResourcesBar(): JSX.Element | null {- const { resourcesUsed } = useValues(sandboxStreamLogic)+export function ResourcesBar(): JSX.Element | null {+ const { resourcesUsed } = useValues(runStreamLogic)if (resourcesUsed.length === 0) {return nulldiff --git a/products/posthog_ai/frontend/components/SandboxActivity.tsx b/products/posthog_ai/frontend/components/RunActivity.tsxsimilarity index 82%rename from products/posthog_ai/frontend/components/SandboxActivity.tsxrename to products/posthog_ai/frontend/components/RunActivity.tsxindex beaf5cb2aee5..d3229a167c13 100644--- a/products/posthog_ai/frontend/components/SandboxActivity.tsx+++ b/products/posthog_ai/frontend/components/RunActivity.tsx@@ -5,10 +5,10 @@ import type { ActivityStatus } from './ActivityPrimitives'/*** Progress / status card for the sandbox runtime — a thin adapter over the shared `Activity` used by- * `SandboxProgressItem` and the status/substep thread items. (Tool calls render via the dedicated- * `SandboxToolActivity` bridge, not this.)+ * `ProgressItem` and the status/substep thread items. (Tool calls render via the dedicated+ * `ToolActivity` bridge, not this.)*/-export function SandboxActivity({+export function RunActivity({id,content,substeps,diff --git a/products/posthog_ai/frontend/components/SandboxComposer.test.tsx b/products/posthog_ai/frontend/components/RunComposer.test.tsxsimilarity index 80%rename from products/posthog_ai/frontend/components/SandboxComposer.test.tsxrename to products/posthog_ai/frontend/components/RunComposer.test.tsxindex 6a8991b8ecd2..5defb0987df7 100644--- a/products/posthog_ai/frontend/components/SandboxComposer.test.tsx+++ b/products/posthog_ai/frontend/components/RunComposer.test.tsx@@ -2,9 +2,9 @@ import '@testing-library/jest-dom'import { cleanup, fireEvent, render, screen } from '@testing-library/react'-import { SandboxComposer } from './SandboxComposer'+import { RunComposer } from './RunComposer'-describe('SandboxComposer', () => {+describe('RunComposer', () => {const onChange = jest.fn()const onSubmit = jest.fn()@@ -16,8 +16,8 @@ describe('SandboxComposer', () => {cleanup()})- const renderComposer = (props: Partial<Parameters<typeof SandboxComposer>[0]> = {}): ReturnType<typeof render> =>- render(<SandboxComposer value="" onChange={onChange} onSubmit={onSubmit} {...props} />)+ const renderComposer = (props: Partial<Parameters<typeof RunComposer>[0]> = {}): ReturnType<typeof render> =>+ render(<RunComposer value="" onChange={onChange} onSubmit={onSubmit} {...props} />)const getSendButton = (container: HTMLElement): HTMLButtonElement =>container.querySelector('[data-attr="sandbox-composer-send"]') as HTMLButtonElement@@ -30,12 +30,7 @@ describe('SandboxComposer', () => {expect(screen.getByText('Send a follow-up message…')).toBeInTheDocument()rerender(- <SandboxComposer- value="hi"- onChange={onChange}- onSubmit={onSubmit}- placeholder="Send a follow-up message…"- />+ <RunComposer value="hi" onChange={onChange} onSubmit={onSubmit} placeholder="Send a follow-up message…" />)expect(screen.queryByText('Send a follow-up message…')).not.toBeInTheDocument()})diff --git a/products/posthog_ai/frontend/components/SandboxComposer.tsx b/products/posthog_ai/frontend/components/RunComposer.tsxsimilarity index 94%rename from products/posthog_ai/frontend/components/SandboxComposer.tsxrename to products/posthog_ai/frontend/components/RunComposer.tsxindex 116decc4563d..f199e881e374 100644--- a/products/posthog_ai/frontend/components/SandboxComposer.tsx+++ b/products/posthog_ai/frontend/components/RunComposer.tsx@@ -1,6 +1,6 @@import { Composer } from './composer/Composer'-export interface SandboxComposerProps {+export interface RunComposerProps {value: stringonChange: (value: string) => voidonSubmit: () => void@@ -21,7 +21,7 @@ export interface SandboxComposerProps {* own the value and the submit handler. Surfaces that need to slot extra chrome should compose the* `Composer.*` parts directly instead of using this wrapper.*/-export function SandboxComposer({+export function RunComposer({value,onChange,onSubmit,@@ -30,7 +30,7 @@ export function SandboxComposer({disabledReason,autoFocus,className,-}: SandboxComposerProps): JSX.Element {+}: RunComposerProps): JSX.Element {return (<Composer.Rootvalue={value}diff --git a/products/posthog_ai/frontend/components/SandboxRunContext.tsx b/products/posthog_ai/frontend/components/RunContext.tsxsimilarity index 95%rename from products/posthog_ai/frontend/components/SandboxRunContext.tsxrename to products/posthog_ai/frontend/components/RunContext.tsxindex 19e8aa33da35..3566dc43b125 100644--- a/products/posthog_ai/frontend/components/SandboxRunContext.tsx+++ b/products/posthog_ai/frontend/components/RunContext.tsx@@ -8,7 +8,7 @@ import { IconGitBranch } from '@posthog/icons'* it (only when a run reports git context). This complements — does not replace — the* `_posthog/progress` provisioning steps.*/-export const SandboxRunContext = memo(function SandboxRunContext({+export const RunContext = memo(function RunContext({branch,baseBranch,repo,diff --git a/products/posthog_ai/frontend/components/SandboxRunViewer.test.tsx b/products/posthog_ai/frontend/components/RunViewer.test.tsxsimilarity index 68%rename from products/posthog_ai/frontend/components/SandboxRunViewer.test.tsxrename to products/posthog_ai/frontend/components/RunViewer.test.tsxindex 794f7b352f4e..c1d75e3d6730 100644--- a/products/posthog_ai/frontend/components/SandboxRunViewer.test.tsx+++ b/products/posthog_ai/frontend/components/RunViewer.test.tsx@@ -3,9 +3,9 @@ import '@testing-library/jest-dom'import { cleanup, render, screen } from '@testing-library/react'import { useActions, useValues } from 'kea'-import type { SandboxRunStatus } from '../logics/sandboxStreamLogic'-import type { PermissionRequestRecord } from '../types/sandboxStreamTypes'-import { SandboxRunViewer } from './SandboxRunViewer'+import type { RunStatus } from '../logics/runStreamLogic'+import type { PermissionRequestRecord } from '../types/streamTypes'+import { RunViewer } from './RunViewer'jest.mock('kea', () => ({...jest.requireActual('kea'),@@ -14,17 +14,17 @@ jest.mock('kea', () => ({useValues: jest.fn(),}))-jest.mock('../logics/sandboxStreamLogic', () => ({- sandboxStreamLogic: jest.fn(() => ({ __mock: 'sandboxStreamLogic' })),+jest.mock('../logics/runStreamLogic', () => ({+ runStreamLogic: jest.fn(() => ({ __mock: 'runStreamLogic' })),isTerminalRunStatus: (status: string | null) =>status != null && ['completed', 'failed', 'cancelled'].includes(status),}))-jest.mock('./SandboxThreadView', () => ({ SandboxThreadView: () => <div data-attr="thread" /> }))-jest.mock('./SandboxResourcesBar', () => ({ SandboxResourcesBar: () => <div data-attr="resources" /> }))-jest.mock('./SandboxContextUsage', () => ({ SandboxContextUsage: () => <div data-attr="context" /> }))-jest.mock('./SandboxPermissionInput', () => ({ SandboxPermissionInput: () => <div data-attr="permission" /> }))-jest.mock('./SandboxQuestionInput', () => ({ SandboxQuestionInput: () => <div data-attr="question" /> }))+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: '',@@ -35,7 +35,7 @@ const composerProps = {function setValues(overrides: Partial<{- currentRunStatus: SandboxRunStatus | null+ currentRunStatus: RunStatus | nullpendingPermissionRequest: PermissionRequestRecord | nullbootstrapLoading: booleanthreadItems: unknown[]@@ -50,7 +50,7 @@ function setValues(})}-describe('SandboxRunViewer', () => {+describe('RunViewer', () => {beforeEach(() => {jest.clearAllMocks();(useActions as jest.Mock).mockReturnValue({ bootstrapRun: jest.fn(), reset: jest.fn() })@@ -61,16 +61,16 @@ describe('SandboxRunViewer', () => {cleanup()})- const renderLive = (statusOrOverrides: SandboxRunStatus | null | Parameters<typeof setValues>[0]): void => {+ const renderLive = (statusOrOverrides: RunStatus | null | Parameters<typeof setValues>[0]): void => {if (typeof statusOrOverrides === 'object' && statusOrOverrides !== null) {setValues(statusOrOverrides)} else {- setValues({ currentRunStatus: statusOrOverrides as SandboxRunStatus | null })+ setValues({ currentRunStatus: statusOrOverrides as RunStatus | null })}- render(<SandboxRunViewer taskId="task-1" runId="run-1" interaction="live" {...composerProps} />)+ render(<RunViewer taskId="task-1" runId="run-1" interaction="live" {...composerProps} />)}- it.each<SandboxRunStatus>(['queued', 'in_progress'])('shows the composer for an active run (%s)', (status) => {+ it.each<RunStatus>(['queued', 'in_progress'])('shows the composer for an active run (%s)', (status) => {renderLive(status)expect(screen.getByTestId('composer')).toBeInTheDocument()})@@ -82,7 +82,7 @@ describe('SandboxRunViewer', () => {expect(screen.getByTestId('thread')).toBeInTheDocument()})- it.each<SandboxRunStatus>(['completed', 'failed', 'cancelled'])(+ it.each<RunStatus>(['completed', 'failed', 'cancelled'])('shows the composer for a terminal run so a new run can be started (%s)',(status) => {renderLive(status)@@ -110,7 +110,7 @@ describe('SandboxRunViewer', () => {it('does not show a composer in read-only mode even for an active run', () => {setValues({ currentRunStatus: 'in_progress' })- render(<SandboxRunViewer taskId="task-1" runId="run-1" interaction="read-only" />)+ 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()@@ -118,7 +118,7 @@ describe('SandboxRunViewer', () => {it('omits the composer in live mode when no composer props are supplied', () => {setValues({ currentRunStatus: 'in_progress' })- render(<SandboxRunViewer taskId="task-1" runId="run-1" interaction="live" />)+ render(<RunViewer taskId="task-1" runId="run-1" interaction="live" />)expect(screen.queryByTestId('composer')).not.toBeInTheDocument()})})diff --git a/products/posthog_ai/frontend/components/SandboxRunViewer.tsx b/products/posthog_ai/frontend/components/RunViewer.tsxsimilarity index 82%rename from products/posthog_ai/frontend/components/SandboxRunViewer.tsxrename to products/posthog_ai/frontend/components/RunViewer.tsxindex 9273b6d402c7..2149312cd8eb 100644--- a/products/posthog_ai/frontend/components/SandboxRunViewer.tsx+++ b/products/posthog_ai/frontend/components/RunViewer.tsx@@ -5,17 +5,17 @@ import { Spinner } from '@posthog/lemon-ui'import { cn } from 'lib/utils/css-classes'-import { isTerminalRunStatus, sandboxStreamLogic } from '../logics/sandboxStreamLogic'-import type { QueuedMessage } from '../logics/taskRunInteractionLogic'+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 { SandboxContextUsage } from './SandboxContextUsage'-import { SandboxPermissionInput } from './SandboxPermissionInput'-import { SandboxQuestionInput } from './SandboxQuestionInput'-import { SandboxResourcesBar } from './SandboxResourcesBar'-import { SandboxThreadView } from './SandboxThreadView'+import { ResourcesBar } from './ResourcesBar'+import { ThreadView } from './ThreadView'-export interface SandboxRunViewerProps {+export interface RunViewerProps {taskId: stringrunId: string/** Stable logic key; defaults to `runId` (the run is the unit being viewed). */@@ -50,9 +50,9 @@ export interface SandboxRunViewerProps {}// --- Compound context --------------------------------------------------------------------------------// `RunViewer.Root` binds a `sandboxStreamLogic` instance and bootstraps the run; the slot components+// `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 `SandboxRunViewer`+// 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.@@ -79,18 +79,18 @@ 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 <SandboxRunViewer>)')+ throw new Error('RunViewer.* slots must be rendered inside <RunViewer.Root> (or <RunViewer>)')}return ctx}-export interface RunViewerRootProps extends SandboxRunViewerProps {+export interface RunViewerRootProps extends RunViewerProps {/** Custom composition of `RunViewer.*` slots. Omit to render the prepackaged default layout. */children?: ReactNode}/**- * Binds a `sandboxStreamLogic` instance (keyed apart from any other stream of the same run), bootstraps+ * 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.@@ -115,7 +115,7 @@ function RunViewerRoot({const replayOnly = interaction !== 'live'const logicKey = streamKey ?? runIdreturn (- <BindLogic logic={sandboxStreamLogic} props={{ streamKey: logicKey, conversationId, replayOnly }}>+ <BindLogic logic={runStreamLogic} props={{ streamKey: logicKey, conversationId, replayOnly }}><RunViewerContext.Providervalue={{rawRunId: runId,@@ -143,7 +143,7 @@ function RunViewerRoot({/** 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(sandboxStreamLogic)+ const { bootstrapRun, reset } = useActions(runStreamLogic)useEffect(() => {// Reset first so a reused instance (stable streamKey, changed run) replays/streams the new run@@ -159,7 +159,7 @@ function RunViewerBootstrap({ taskId }: { taskId: string }): null {/** Thread slot: the streamed run thread, with a centered spinner during the first bootstrap. */function RunViewerThread(): JSX.Element {- const { bootstrapLoading, threadItems } = useValues(sandboxStreamLogic)+ const { bootstrapLoading, threadItems } = useValues(runStreamLogic)const showSpinner = bootstrapLoading && threadItems.length === 0if (showSpinner) {return (@@ -169,7 +169,7 @@ function RunViewerThread(): JSX.Element {)}// An error surfaces as a `handleStreamError` item folded into the thread, so it renders here too.- return <SandboxThreadView />+ return <ThreadView />}/**@@ -178,7 +178,7 @@ function RunViewerThread(): JSX.Element {*/function RunViewerPrompt(): JSX.Element | null {const { interaction, runId } = useRunViewerContext()- const { pendingPermissionRequest, currentRunStatus } = useValues(sandboxStreamLogic)+ const { pendingPermissionRequest, currentRunStatus } = useValues(runStreamLogic)const showApproval = interaction === 'live' && !!pendingPermissionRequest && !isTerminalRunStatus(currentRunStatus)if (!showApproval) {return null@@ -187,9 +187,9 @@ function RunViewerPrompt(): JSX.Element | null {return (<div className="border-t px-4 py-3">{isQuestion ? (- <SandboxQuestionInput streamKey={runId} request={pendingPermissionRequest!} />+ <QuestionInput streamKey={runId} request={pendingPermissionRequest!} />) : (- <SandboxPermissionInput streamKey={runId} request={pendingPermissionRequest!} />+ <PermissionInput streamKey={runId} request={pendingPermissionRequest!} />)}</div>)@@ -203,7 +203,7 @@ function RunViewerPrompt(): JSX.Element | null {*/function RunViewerComposer(): JSX.Element | null {const { interaction, composer } = useRunViewerContext()- const { pendingPermissionRequest, currentRunStatus } = useValues(sandboxStreamLogic)+ const { pendingPermissionRequest, currentRunStatus } = useValues(runStreamLogic)const hasComposer =interaction === 'live' && !!composer.onSubmit && composer.onChange !== undefined && composer.value !== undefinedif (!hasComposer || pendingPermissionRequest || currentRunStatus === null) {@@ -212,7 +212,7 @@ function RunViewerComposer(): JSX.Element | null {const isRunTerminal = isTerminalRunStatus(currentRunStatus)const { queuedMessages, onUpdateQueuedMessage, onRemoveQueuedMessage } = composerreturn (- // Composed from the logic-free Composer.* primitives directly (rather than via SandboxComposer) so+ // 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@@ -260,10 +260,10 @@ function DefaultRunViewerLayout({ className }: { className?: string }): JSX.Elem<div className="flex-1 min-h-0"><RunViewerThread /></div>- <SandboxResourcesBar />+ <ResourcesBar /><RunViewerPrompt /><RunViewerComposer />- <SandboxContextUsage />+ <ContextUsageBar /></div>)}@@ -271,7 +271,7 @@ function DefaultRunViewerLayout({ className }: { className?: string }): JSX.Elem/*** 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 `SandboxRunViewer` prepackaged component for the+ * 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, {@@ -279,17 +279,6 @@ export const RunViewer = Object.assign(RunViewerRoot, {Thread: RunViewerThread,Prompt: RunViewerPrompt,Composer: RunViewerComposer,- Resources: SandboxResourcesBar,- ContextUsage: SandboxContextUsage,+ Resources: ResourcesBar,+ ContextUsage: ContextUsageBar,})--/**- * Embeddable viewer of a task run's agent thread — the prepackaged `RunViewer.Root` with the default slot- * layout. Binds a `sandboxStreamLogic` instance (keyed apart from any other stream of the same run) and- * renders the shared `SandboxThreadView`. In `'read-only'` mode it replays the persisted `logs/` snapshot- * once — no SSE, no composer. In `'live'` mode it streams an in-progress run, surfaces permission/question- * prompts, and (given composer props) renders a follow-up composer, automatically replaying once terminal.- */-export function SandboxRunViewer(props: SandboxRunViewerProps): JSX.Element {- return <RunViewerRoot {...props} />-}diff --git a/products/posthog_ai/frontend/components/Thread.tsx b/products/posthog_ai/frontend/components/Thread.tsxindex b58fb49770a3..5b69e1c30079 100644--- a/products/posthog_ai/frontend/components/Thread.tsx+++ b/products/posthog_ai/frontend/components/Thread.tsx@@ -3,17 +3,17 @@ import { MarkdownMessage } from '../messages/MarkdownMessage'import { MessageTemplate } from '../messages/MessageTemplate'import { ReasoningAnswer } from '../messages/ReasoningAnswer'import { Activity } from './ActivityPrimitives'-import { SandboxThreadView } from './SandboxThreadView'-import { SandboxToolCall } from './tool/SandboxToolCall'+import { ThreadView } from './ThreadView'+import { ToolCallCard } from './tool/ToolCallCard'// Radix-style compound for the agent run thread. `Thread.Root` is the prepackaged, virtualized presenter-// that reads the bound `sandboxStreamLogic` and dispatches every thread item; the leaf atoms below are the+// that reads the bound `runStreamLogic` and dispatches every thread item; the leaf atoms below are the// same presentational building blocks it uses, exposed so a surface can assemble a bespoke thread (e.g. a// static transcript, an embedded preview) from plain props without the streaming machinery. The atoms are// runtime-agnostic and take plain props — they know nothing about langgraph vs sandbox or the conversation.-export const Thread = Object.assign(SandboxThreadView, {+export const Thread = Object.assign(ThreadView, {/** The full streamed thread: virtualized rows + run-context header + thinking/PR footer. */- Root: SandboxThreadView,+ Root: ThreadView,/** Human/assistant message bubble wrapper. */Message: MessageTemplate,/** Markdown body renderer (used inside messages and activity details). */@@ -25,5 +25,5 @@ export const Thread = Object.assign(SandboxThreadView, {/** Progress / status activity card. */Activity: Activity,/** Tool-call card — resolves its renderer through the tool registry. */- ToolCall: SandboxToolCall,+ ToolCall: ToolCallCard,})diff --git a/products/posthog_ai/frontend/components/SandboxThreadItems.tsx b/products/posthog_ai/frontend/components/ThreadItems.tsxsimilarity index 86%rename from products/posthog_ai/frontend/components/SandboxThreadItems.tsxrename to products/posthog_ai/frontend/components/ThreadItems.tsxindex 2b9af7a07c95..0da0321d1cf9 100644--- a/products/posthog_ai/frontend/components/SandboxThreadItems.tsx+++ b/products/posthog_ai/frontend/components/ThreadItems.tsx@@ -4,10 +4,10 @@ import { Spinner } from '@posthog/lemon-ui'import { cn } from 'lib/utils/css-classes'import { humanFriendlyNumber } from 'lib/utils/numbers'-import type { ThreadItem } from '../types/sandboxStreamTypes'+import type { ThreadItem } from '../types/streamTypes'/** Inline `_posthog/status` item — a spinner while compacting, a generic status line otherwise. */-export function SandboxStatusItem({ item }: { item: ThreadItem }): JSX.Element {+export function StatusItem({ item }: { item: ThreadItem }): JSX.Element {const isCompacting = item.status === 'compacting' && !item.isCompletereturn (<div className="flex items-center justify-center gap-2 py-1 text-xs text-muted">@@ -24,7 +24,7 @@ export function SandboxStatusItem({ item }: { item: ThreadItem }): JSX.Element {}/** Inline `_posthog/compact_boundary` item — the post-compaction rule. */-export function SandboxCompactBoundaryItem({ item }: { item: ThreadItem }): JSX.Element {+export function CompactBoundaryItem({ item }: { item: ThreadItem }): JSX.Element {return (<div className="flex items-center gap-2 py-1 text-xs text-muted"><div className="h-px grow bg-border" />@@ -41,7 +41,7 @@ export function SandboxCompactBoundaryItem({ item }: { item: ThreadItem }): JSX.}/** Inline `_posthog/task_notification` item — a colored rule by status (completed/failed/stopped). */-export function SandboxTaskNotificationItem({ item }: { item: ThreadItem }): JSX.Element {+export function TaskNotificationItem({ item }: { item: ThreadItem }): JSX.Element {const colorClass =item.status === 'completed' ? 'text-success' : item.status === 'failed' ? 'text-danger' : 'text-warning'const icon =diff --git a/products/posthog_ai/frontend/components/SandboxThreadRow.tsx b/products/posthog_ai/frontend/components/ThreadRow.tsxsimilarity index 71%rename from products/posthog_ai/frontend/components/SandboxThreadRow.tsxrename to products/posthog_ai/frontend/components/ThreadRow.tsxindex 956a78cfc310..858b2556860c 100644--- a/products/posthog_ai/frontend/components/SandboxThreadRow.tsx+++ b/products/posthog_ai/frontend/components/ThreadRow.tsx@@ -4,23 +4,23 @@ import { IconWrench } from '@posthog/icons'import { TaskExecutionStatus as ExecutionStatus } from '~/queries/schema/schema-assistant-messages'-import type { SandboxToolCallMessage } from 'products/posthog_ai/frontend/types/sandboxToolTypes'+import type { ToolCallMessage } from 'products/posthog_ai/frontend/types/toolTypes'-import { sandboxStreamLogic } from '../logics/sandboxStreamLogic'+import { runStreamLogic } from '../logics/runStreamLogic'import { AssistantFailureMessage } from '../messages/AssistantFailureMessage'import { MarkdownMessage } from '../messages/MarkdownMessage'import { MessageTemplate } from '../messages/MessageTemplate'import { ReasoningAnswer } from '../messages/ReasoningAnswer'-import type { SandboxProgressStep, ThreadItem as SandboxThreadItem } from '../types/sandboxStreamTypes'-import { SandboxActivity } from './SandboxActivity'-import { SandboxCompactBoundaryItem, SandboxStatusItem, SandboxTaskNotificationItem } from './SandboxThreadItems'-import { SandboxToolCall } from './tool/SandboxToolCall'-import { resolveToolCall } from './tool/sandboxToolResolver'+import type { ProgressStep, ThreadItem } from '../types/streamTypes'+import { RunActivity } from './RunActivity'+import { CompactBoundaryItem, StatusItem, TaskNotificationItem } from './ThreadItems'+import { ToolCallCard } from './tool/ToolCallCard'+import { resolveToolCall } from './tool/toolResolver'-type ToolInvocations = typeof sandboxStreamLogic.values.toolInvocations+type ToolInvocations = typeof runStreamLogic.values.toolInvocations-/** Maps a raw merged `ToolInvocation` into the flat `SandboxToolCallMessage` the registry renderers read. */-function toolInvocationToMessage(invocation: ReturnType<ToolInvocations['get']>): SandboxToolCallMessage | null {+/** Maps a raw merged `ToolInvocation` into the flat `ToolCallMessage` the registry renderers read. */+function toolInvocationToMessage(invocation: ReturnType<ToolInvocations['get']>): ToolCallMessage | null {if (!invocation) {return null}@@ -44,11 +44,11 @@ function toolInvocationToMessage(invocation: ReturnType<ToolInvocations['get']>)}}-function progressStepText(step: SandboxProgressStep): string {+function progressStepText(step: ProgressStep): string {return step.detail ? `${step.label}\n\n${step.detail}` : step.label}-function resolveSandboxProgressState(steps: SandboxProgressStep[]): ExecutionStatus {+function resolveProgressState(steps: ProgressStep[]): ExecutionStatus {if (steps.some((step) => step.status === 'failed')) {return ExecutionStatus.Failed}@@ -61,7 +61,7 @@ function resolveSandboxProgressState(steps: SandboxProgressStep[]): ExecutionStareturn ExecutionStatus.Completed}-function resolveSandboxProgressHeadline(steps: SandboxProgressStep[]): string {+function resolveProgressHeadline(steps: ProgressStep[]): string {const active = steps.find((step) => step.status === 'in_progress')if (active) {return active.label@@ -69,18 +69,18 @@ function resolveSandboxProgressHeadline(steps: SandboxProgressStep[]): string {return steps.at(-1)?.label ?? 'Working'}-function SandboxProgressItem({ item }: { item: SandboxThreadItem }): JSX.Element | null {+function ProgressItem({ item }: { item: ThreadItem }): JSX.Element | null {const steps = item.progressSteps ?? []if (!steps.length) {return null}- const headline = resolveSandboxProgressHeadline(steps)+ const headline = resolveProgressHeadline(steps)const substeps = steps.length > 1 ? steps.map(progressStepText) : []- const state = resolveSandboxProgressState(steps)+ const state = resolveProgressState(steps)return (- <SandboxActivity+ <RunActivityid={item.id}content={headline}substeps={substeps}@@ -91,8 +91,8 @@ function SandboxProgressItem({ item }: { item: SandboxThreadItem }): JSX.Element)}-export interface SandboxThreadRowProps {- item: SandboxThreadItem+export interface ThreadRowProps {+ item: ThreadItem/** Last item in the thread — drives reasoning collapse alongside `isThinking`. */isLast: booleanisThinking: boolean@@ -105,14 +105,14 @@ export interface SandboxThreadRowProps {* Renders a single sandbox thread item by type. Memoized and keyed by stable `item.id` so a re-projected* `threadItems` array only re-renders rows whose data actually changed.*/-export const SandboxThreadRow = memo(function SandboxThreadRow({+export const ThreadRow = memo(function ThreadRow({item,isLast,isThinking,toolInvocations,turnComplete,turnCancelled,-}: SandboxThreadRowProps): JSX.Element | null {+}: ThreadRowProps): JSX.Element | null {if (item.type === 'human_message') {return (<MessageTemplate type="human">@@ -143,22 +143,22 @@ export const SandboxThreadRow = memo(function SandboxThreadRow({if (!message) {return null}- return <SandboxToolCall message={message} turnComplete={turnComplete} turnCancelled={turnCancelled} />+ return <ToolCallCard message={message} turnComplete={turnComplete} turnCancelled={turnCancelled} />}if (item.type === 'error') {return <AssistantFailureMessage id={item.id} content={item.errorMessage} />}if (item.type === 'status') {- return <SandboxStatusItem item={item} />+ return <StatusItem item={item} />}if (item.type === 'compact_boundary') {- return <SandboxCompactBoundaryItem item={item} />+ return <CompactBoundaryItem item={item} />}if (item.type === 'task_notification') {- return <SandboxTaskNotificationItem item={item} />+ return <TaskNotificationItem item={item} />}if (item.type === 'progress') {- return <SandboxProgressItem item={item} />+ return <ProgressItem item={item} />}return null})diff --git a/products/posthog_ai/frontend/components/SandboxThreadView.tsx b/products/posthog_ai/frontend/components/ThreadView.tsxsimilarity index 75%rename from products/posthog_ai/frontend/components/SandboxThreadView.tsxrename to products/posthog_ai/frontend/components/ThreadView.tsxindex 7f544dfe3978..667ec8497430 100644--- a/products/posthog_ai/frontend/components/SandboxThreadView.tsx+++ b/products/posthog_ai/frontend/components/ThreadView.tsx@@ -1,13 +1,13 @@import { useValues } from 'kea'import { memo, useCallback, useMemo } from 'react'-import { sandboxStreamLogic } from '../logics/sandboxStreamLogic'+import { runStreamLogic } from '../logics/runStreamLogic'import { ReasoningAnswer } from '../messages/ReasoningAnswer'-import type { ThreadItem } from '../types/sandboxStreamTypes'+import type { ThreadItem } from '../types/streamTypes'import { getRandomThinkingMessage } from '../utils/thinkingMessages'-import { SandboxPullRequestCard } from './SandboxPullRequestCard'-import { SandboxRunContext } from './SandboxRunContext'-import { SandboxThreadRow } from './SandboxThreadRow'+import { PullRequestCard } from './PullRequestCard'+import { RunContext } from './RunContext'+import { ThreadRow } from './ThreadRow'import { VirtualizedThread } from './VirtualizedThread'/** Stable row key — defined at module scope so `getItemKey` never changes identity across renders. */@@ -16,8 +16,8 @@ function getThreadItemKey(item: ThreadItem): string {}/**- * Sandbox-runtime thread presenter. Reads `sandboxStreamLogic.values.threadItems` (assistant text,- * tool-invocation references, run separators, inline errors) from whatever `sandboxStreamLogic`+ * Sandbox-runtime thread presenter. Reads `runStreamLogic.values.threadItems` (assistant text,+ * tool-invocation references, run separators, inline errors) from whatever `runStreamLogic`* instance is bound above it — a live PostHog AI conversation or a read-only run viewer — and* dispatches tool cards through the sandbox tool registry. Conversation-agnostic by design: it knows* only the bound stream logic, never langgraph vs sandbox or the conversation.@@ -27,9 +27,9 @@ function getThreadItemKey(item: ThreadItem): string {* `virtualized={false}` when an ancestor already owns scroll (the live Max column + auto-scroller) — rows* then render in document flow, unchanged from the pre-virtualized layout.*/-export function SandboxThreadView({ virtualized = true }: { virtualized?: boolean } = {}): JSX.Element {+export function ThreadView({ virtualized = true }: { virtualized?: boolean } = {}): JSX.Element {const { threadItems, toolInvocations, isThinking, streamPhase, runArtifacts, turnComplete, currentRunStatus } =- useValues(sandboxStreamLogic)+ useValues(runStreamLogic)const turnCancelled = currentRunStatus === 'cancelled'const hasActiveProgressItem = threadItems.some((item) => item.type === 'progress' && item.progressSteps?.some((step) => step.status === 'in_progress')@@ -43,7 +43,7 @@ export function SandboxThreadView({ virtualized = true }: { virtualized?: boolea() =>branch ? (<VirtualizedThread.Row>- <SandboxThreadHeader branch={branch} baseBranch={baseBranch} repo={repo} />+ <ThreadHeader branch={branch} baseBranch={baseBranch} repo={repo} /></VirtualizedThread.Row>) : undefined,[branch, baseBranch, repo]@@ -56,11 +56,7 @@ export function SandboxThreadView({ virtualized = true }: { virtualized?: boolea() =>showThinking || pullRequestUrl ? (<VirtualizedThread.Row>- <SandboxThreadFooter- showThinking={showThinking}- pullRequestUrl={pullRequestUrl}- prBranch={branch}- />+ <ThreadFooter showThinking={showThinking} pullRequestUrl={pullRequestUrl} prBranch={branch} /></VirtualizedThread.Row>) : undefined,[showThinking, pullRequestUrl, branch]@@ -69,7 +65,7 @@ export function SandboxThreadView({ virtualized = true }: { virtualized?: booleaconst renderItem = useCallback((item: ThreadItem, index: number): JSX.Element => (<VirtualizedThread.Row>- <SandboxThreadRow+ <ThreadRowitem={item}isLast={index === threadItems.length - 1}isThinking={isThinking}@@ -97,7 +93,7 @@ export function SandboxThreadView({ virtualized = true }: { virtualized?: boolea}/** Leading run-context row. Memoized so it only re-renders when the run's branch/repo refs change. */-const SandboxThreadHeader = memo(function SandboxThreadHeader({+const ThreadHeader = memo(function ThreadHeader({branch,baseBranch,repo,@@ -106,15 +102,15 @@ const SandboxThreadHeader = memo(function SandboxThreadHeader({baseBranch?: stringrepo?: string}): JSX.Element {- return <SandboxRunContext branch={branch} baseBranch={baseBranch} repo={repo} />+ return <RunContext branch={branch} baseBranch={baseBranch} repo={repo} />})/*** Trailing row: the "what's it doing now" thinking line and/or the produced PR card. Subscribes to* `currentProgress` itself so the frequently-updating progress text stays isolated here — it never- * re-renders `SandboxThreadView` or destabilizes the footer's element identity during streaming.+ * re-renders `ThreadView` or destabilizes the footer's element identity during streaming.*/-const SandboxThreadFooter = memo(function SandboxThreadFooter({+const ThreadFooter = memo(function ThreadFooter({showThinking,pullRequestUrl,prBranch,@@ -123,11 +119,11 @@ const SandboxThreadFooter = memo(function SandboxThreadFooter({pullRequestUrl?: stringprBranch?: string}): JSX.Element {- const { currentProgress } = useValues(sandboxStreamLogic)+ const { currentProgress } = useValues(runStreamLogic)return (<>- {showThinking && <SandboxThinkingIndicator progress={currentProgress} />}- {pullRequestUrl && <SandboxPullRequestCard prUrl={pullRequestUrl} branch={prBranch} />}+ {showThinking && <ThinkingIndicator progress={currentProgress} />}+ {pullRequestUrl && <PullRequestCard prUrl={pullRequestUrl} branch={prBranch} />}</>)})@@ -136,7 +132,7 @@ const SandboxThreadFooter = memo(function SandboxThreadFooter({* Bottom-of-thread "what's it doing right now" line for sandbox conversations. Reflects the latest* `_posthog/progress` message when present, otherwise the canned thinking rotation.*/-function SandboxThinkingIndicator({ progress }: { progress: string | null }): JSX.Element {+function ThinkingIndicator({ progress }: { progress: string | null }): JSX.Element {// One roll per mount — re-rolling on every progress transition would visibly swap the verb.const fallbackMessage = useMemo(() => getRandomThinkingMessage(), [])const message = progress?.trim() ? progress : fallbackMessagediff --git a/products/posthog_ai/frontend/components/tool/SandboxDataToolRow.tsx b/products/posthog_ai/frontend/components/tool/DataToolRow.tsxsimilarity index 70%rename from products/posthog_ai/frontend/components/tool/SandboxDataToolRow.tsxrename to products/posthog_ai/frontend/components/tool/DataToolRow.tsxindex 83e82916e0e1..0a93bdc92c34 100644--- a/products/posthog_ai/frontend/components/tool/SandboxDataToolRow.tsx+++ b/products/posthog_ai/frontend/components/tool/DataToolRow.tsx@@ -1,7 +1,7 @@import { type PropsWithChildren } from 'react'-import { SandboxToolActivity } from './SandboxToolActivity'-import type { SandboxToolRendererProps } from './sandboxToolRegistry'+import { ToolActivity } from './ToolActivity'+import type { ToolRendererProps } from './toolRegistry'/*** Shared shell for the data-tool adapters (insight, dashboard, recordings, query, error tracking,@@ -9,11 +9,11 @@ import type { SandboxToolRendererProps } from './sandboxToolRegistry'* always-visible content below it (via the Activity bridge), keeping data tools consistent with the* per-tool cards while each adapter keeps its own lazy chunk.*/-export function SandboxDataToolRow({ children, ...props }: PropsWithChildren<SandboxToolRendererProps>): JSX.Element {+export function DataToolRow({ children, ...props }: PropsWithChildren<ToolRendererProps>): JSX.Element {const { message, icon, displayName, turnComplete, turnCancelled } = propsreturn (- <SandboxToolActivity+ <ToolActivitymessage={message}icon={icon}title={message.title || displayName || 'Tool'}@@ -21,6 +21,6 @@ export function SandboxDataToolRow({ children, ...props }: PropsWithChildren<SanturnCancelled={turnCancelled}>{children}- </SandboxToolActivity>+ </ToolActivity>)}diff --git a/products/posthog_ai/frontend/components/tool/EditDiffRenderer.test.tsx b/products/posthog_ai/frontend/components/tool/EditDiffRenderer.test.tsxindex 67d25b27ec5d..0e5f0959260d 100644--- a/products/posthog_ai/frontend/components/tool/EditDiffRenderer.test.tsx+++ b/products/posthog_ai/frontend/components/tool/EditDiffRenderer.test.tsx@@ -2,7 +2,7 @@ import '@testing-library/jest-dom'import { cleanup, fireEvent, render, screen } from '@testing-library/react'-import type { SandboxToolCallMessage } from '../../types/sandboxToolTypes'+import type { ToolCallMessage } from '../../types/toolTypes'import { EditDiffRenderer } from './EditDiffRenderer'// Monaco can't render in jsdom — stand it in for a marker that echoes the diff props we care about.@@ -42,7 +42,7 @@ jest.mock('kea', () => ({useValues: () => ({ isDarkModeOn: mockDarkMode }),}))-function makeMessage(overrides: Partial<SandboxToolCallMessage> = {}): SandboxToolCallMessage {+function makeMessage(overrides: Partial<ToolCallMessage> = {}): ToolCallMessage {return {id: 'tc-1',resolvedKey: 'Edit',@@ -57,7 +57,7 @@ function makeMessage(overrides: Partial<SandboxToolCallMessage> = {}): SandboxTo// The diff lives in the Activity's collapsible body, which auto-collapses once the call completes —// expand it so the editor + stats render.-function renderExpanded(message: SandboxToolCallMessage): void {+function renderExpanded(message: ToolCallMessage): void {render(<EditDiffRenderer message={message} displayName="Edit" isLastInGroup />)fireEvent.click(screen.getByRole('button'))}diff --git a/products/posthog_ai/frontend/components/tool/EditDiffRenderer.tsx b/products/posthog_ai/frontend/components/tool/EditDiffRenderer.tsxindex 1e4a552d585f..263a5c8af358 100644--- a/products/posthog_ai/frontend/components/tool/EditDiffRenderer.tsx+++ b/products/posthog_ai/frontend/components/tool/EditDiffRenderer.tsx@@ -8,11 +8,11 @@ import MonacoDiffEditor from 'lib/components/MonacoDiffEditor'import { themeLogic } from '~/layout/navigation-3000/themeLogic'+import { FilePath } from './FilePath'import { GenericMcpToolRenderer } from './GenericMcpToolRenderer'-import { SandboxFilePath } from './SandboxFilePath'-import { SandboxToolActivity } from './SandboxToolActivity'-import type { SandboxToolRendererProps } from './sandboxToolRegistry'+import { ToolActivity } from './ToolActivity'import { findAllDiffContent, getDiffStats, languageFromPath, type ToolCallDiffContent } from './toolDiffContent'+import type { ToolRendererProps } from './toolRegistry'// A stripped-down, unified diff that reads cleanly embedded in a chat card — mirrors the look of the// sandbox agent's own diff UI (unified style, soft-wrapped, compact font, no editor chrome). Module-level@@ -81,7 +81,7 @@ function DiffStats({ added, removed }: { added: number; removed: number }): JSX.* file" (or "Edited N files"); expanding the card reveals the filename, line stats, and an inline visual* diff per file. Without `type: "diff"` content blocks it degrades to the generic card.*/-export function EditDiffRenderer(props: SandboxToolRendererProps): JSX.Element {+export function EditDiffRenderer(props: ToolRendererProps): JSX.Element {const { message, icon, turnComplete, turnCancelled } = propsconst diffs = findAllDiffContent(message.content)@@ -101,7 +101,7 @@ export function EditDiffRenderer(props: SandboxToolRendererProps): JSX.Element {return (<div key={index} className="flex flex-col gap-1 w-full min-w-0"><div className="flex items-center gap-2 min-w-0">- {path && <SandboxFilePath path={path} />}+ {path && <FilePath path={path} />}<DiffStats added={stats.added} removed={stats.removed} /></div><DiffEditor diff={diff} path={path} />@@ -112,7 +112,7 @@ export function EditDiffRenderer(props: SandboxToolRendererProps): JSX.Element {)return (- <SandboxToolActivity+ <ToolActivitymessage={message}icon={icon ?? <IconPencil />}title={title}diff --git a/products/posthog_ai/frontend/components/tool/SandboxFilePath.tsx b/products/posthog_ai/frontend/components/tool/FilePath.tsxsimilarity index 91%rename from products/posthog_ai/frontend/components/tool/SandboxFilePath.tsxrename to products/posthog_ai/frontend/components/tool/FilePath.tsxindex b280219f3ba3..fb212084fc1b 100644--- a/products/posthog_ai/frontend/components/tool/SandboxFilePath.tsx+++ b/products/posthog_ai/frontend/components/tool/FilePath.tsx@@ -7,7 +7,7 @@ import { getFilename } from './toolContentUtils'* directory that ellipsizes on overflow. There is no file-open panel in the sandbox UI, so unlike* the agent's own FileMentionChip this is purely informational.*/-export function SandboxFilePath({ path }: { path: string }): JSX.Element {+export function FilePath({ path }: { path: string }): JSX.Element {const filename = getFilename(path)const dir = path.slice(0, path.length - filename.length).replace(/\/+$/, '')diff --git a/products/posthog_ai/frontend/components/tool/GenericMcpToolRenderer.tsx b/products/posthog_ai/frontend/components/tool/GenericMcpToolRenderer.tsxindex 35d1b3d8df6d..1bd375dce073 100644--- a/products/posthog_ai/frontend/components/tool/GenericMcpToolRenderer.tsx+++ b/products/posthog_ai/frontend/components/tool/GenericMcpToolRenderer.tsx@@ -3,10 +3,10 @@ import { memo } from 'react'import { IconWrench } from '@posthog/icons'-import { SandboxToolActivity } from './SandboxToolActivity'-import type { SandboxToolRendererProps } from './sandboxToolRegistry'+import { ToolActivity } from './ToolActivity'import { compactInput, formatInput, getContentText, stripCodeFences } from './toolContentUtils'import { ToolOutput } from './ToolOutput'+import type { ToolRendererProps } from './toolRegistry'/*** The catch-all tool card — user-installed MCP tools, unmapped PostHog `exec` inner tools, and Claude@@ -15,9 +15,7 @@ import { ToolOutput } from './ToolOutput'* preview sits on the second line and the body shows any text output. Replaces the old* `FallbackMcpToolRenderer`.*/-export const GenericMcpToolRenderer = memo(function GenericMcpToolRenderer(- props: SandboxToolRendererProps-): JSX.Element {+export const GenericMcpToolRenderer = memo(function GenericMcpToolRenderer(props: ToolRendererProps): JSX.Element {const { message, icon, displayName, turnComplete, turnCancelled } = propsconst isPostHogExec = !!message.innerToolName@@ -54,7 +52,7 @@ export const GenericMcpToolRenderer = memo(function GenericMcpToolRenderer() : undefinedreturn (- <SandboxToolActivity+ <ToolActivitymessage={message}icon={icon ?? <IconWrench />}title={title}diff --git a/products/posthog_ai/frontend/components/tool/SandboxToolActivity.test.tsx b/products/posthog_ai/frontend/components/tool/ToolActivity.test.tsxsimilarity index 69%rename from products/posthog_ai/frontend/components/tool/SandboxToolActivity.test.tsxrename to products/posthog_ai/frontend/components/tool/ToolActivity.test.tsxindex 8457a08e4f5b..8322fdc15618 100644--- a/products/posthog_ai/frontend/components/tool/SandboxToolActivity.test.tsx+++ b/products/posthog_ai/frontend/components/tool/ToolActivity.test.tsx@@ -2,11 +2,11 @@ import '@testing-library/jest-dom'import { fireEvent, render, screen } from '@testing-library/react'-import type { SandboxToolCallMessage } from 'products/posthog_ai/frontend/types/sandboxToolTypes'+import type { ToolCallMessage } from 'products/posthog_ai/frontend/types/toolTypes'-import { SandboxToolActivity } from './SandboxToolActivity'+import { ToolActivity } from './ToolActivity'-function makeMessage(overrides: Partial<SandboxToolCallMessage> = {}): SandboxToolCallMessage {+function makeMessage(overrides: Partial<ToolCallMessage> = {}): ToolCallMessage {return {id: 'tc-1',resolvedKey: 'Bash',@@ -19,15 +19,15 @@ function makeMessage(overrides: Partial<SandboxToolCallMessage> = {}): SandboxTo}}-describe('SandboxToolActivity', () => {+describe('ToolActivity', () => {it('renders the title and subtitle (second line)', () => {- render(<SandboxToolActivity message={makeMessage()} title="Terminal" subtitle="ls -la" />)+ render(<ToolActivity message={makeMessage()} title="Terminal" subtitle="ls -la" />)expect(screen.getByText('Terminal')).toBeInTheDocument()expect(screen.getByText('ls -la')).toBeInTheDocument()})it('keeps the body collapsed once completed and expands on click', () => {- render(<SandboxToolActivity message={makeMessage()} title="Terminal" body={<div>command output</div>} />)+ render(<ToolActivity message={makeMessage()} title="Terminal" body={<div>command output</div>} />)expect(screen.queryByText('command output')).not.toBeInTheDocument()fireEvent.click(screen.getByRole('button'))expect(screen.getByText('command output')).toBeInTheDocument()@@ -35,7 +35,7 @@ describe('SandboxToolActivity', () => {it('auto-expands the body while the tool is running', () => {render(- <SandboxToolActivity+ <ToolActivitymessage={makeMessage({ status: 'in_progress' })}title="Terminal"body={<div>streaming…</div>}@@ -46,16 +46,16 @@ describe('SandboxToolActivity', () => {it('renders children always-visible without expanding', () => {render(- <SandboxToolActivity message={makeMessage()} title="Insight">+ <ToolActivity message={makeMessage()} title="Insight"><div>the visualization</div>- </SandboxToolActivity>+ </ToolActivity>)expect(screen.getByText('the visualization')).toBeInTheDocument()})it('surfaces the failure message', () => {render(- <SandboxToolActivity+ <ToolActivitymessage={makeMessage({ status: 'failed', error: { message: 'boom' } })}title="Terminal"body={<div>partial</div>}@@ -65,7 +65,7 @@ describe('SandboxToolActivity', () => {})it('marks a turn-cancelled tool', () => {- render(<SandboxToolActivity message={makeMessage({ status: 'in_progress' })} title="Terminal" turnCancelled />)+ render(<ToolActivity message={makeMessage({ status: 'in_progress' })} title="Terminal" turnCancelled />)expect(screen.getByText('(cancelled)')).toBeInTheDocument()})})diff --git a/products/posthog_ai/frontend/components/tool/SandboxToolActivity.tsx b/products/posthog_ai/frontend/components/tool/ToolActivity.tsxsimilarity index 92%rename from products/posthog_ai/frontend/components/tool/SandboxToolActivity.tsxrename to products/posthog_ai/frontend/components/tool/ToolActivity.tsxindex 2ec89b2537c9..b638fc92fd2a 100644--- a/products/posthog_ai/frontend/components/tool/SandboxToolActivity.tsx+++ b/products/posthog_ai/frontend/components/tool/ToolActivity.tsx@@ -2,14 +2,14 @@ import { type ReactNode } from 'react'import { IconWarning, IconWrench } from '@posthog/icons'-import type { SandboxToolCallMessage } from 'products/posthog_ai/frontend/types/sandboxToolTypes'+import type { ToolCallMessage } from 'products/posthog_ai/frontend/types/toolTypes'import { Activity } from '../ActivityPrimitives'import type { ActivityStatus } from '../ActivityPrimitives'import { resolveToolCallStatus } from './toolContentUtils'-export interface SandboxToolActivityProps {- message: SandboxToolCallMessage+export interface ToolActivityProps {+ message: ToolCallMessage/** Registry icon; defaults to the generic wrench. */icon?: ReactNode/** Header line 1. */@@ -31,7 +31,7 @@ export interface SandboxToolActivityProps {* collapsible body (`body` → Activity `details`, auto-expands while running) or the always-visible* region (`children`). Every sandbox tool card renders through this.*/-export function SandboxToolActivity({+export function ToolActivity({message,icon,title,@@ -40,7 +40,7 @@ export function SandboxToolActivity({children,turnComplete,turnCancelled,-}: SandboxToolActivityProps): JSX.Element {+}: ToolActivityProps): JSX.Element {const { isLoading, isFailed, wasCancelled } = resolveToolCallStatus(message.status, !!turnCancelled, !!turnComplete)const status: ActivityStatus = isFailed ? 'failed' : isLoading ? 'in_progress' : 'completed'diff --git a/products/posthog_ai/frontend/components/tool/SandboxToolCall.tsx b/products/posthog_ai/frontend/components/tool/ToolCallCard.tsxsimilarity index 70%rename from products/posthog_ai/frontend/components/tool/SandboxToolCall.tsxrename to products/posthog_ai/frontend/components/tool/ToolCallCard.tsxindex 5c60a0d7db05..9d778373ce0d 100644--- a/products/posthog_ai/frontend/components/tool/SandboxToolCall.tsx+++ b/products/posthog_ai/frontend/components/tool/ToolCallCard.tsx@@ -1,12 +1,12 @@import { Suspense, memo } from 'react'-import type { SandboxToolCallMessage } from 'products/posthog_ai/frontend/types/sandboxToolTypes'+import type { ToolCallMessage } from 'products/posthog_ai/frontend/types/toolTypes'-import { lookupSandboxToolRenderer } from './sandboxToolRegistry'import { ToolCardSkeleton } from './ToolCardSkeleton'+import { lookupToolRenderer } from './toolRegistry'-export interface SandboxToolCallProps {- message: SandboxToolCallMessage+export interface ToolCallCardProps {+ message: ToolCallMessage/** Turn-level signals for resolving a still-incomplete tool as loading vs cancelled vs idle. */turnComplete?: booleanturnCancelled?: boolean@@ -15,14 +15,14 @@ export interface SandboxToolCallProps {/*** Eager dispatch for a single sandbox tool call: resolves the registry entry by `resolvedKey`, then* renders its (lazy) renderer inside a `Suspense` boundary that shows a `ToolCardSkeleton` while the- * chunk loads. Replaces the inline `tool_invocation` branch in `SandboxThread`.+ * chunk loads. Replaces the inline `tool_invocation` branch in `ThreadView`.*/-export const SandboxToolCall = memo(function SandboxToolCall({+export const ToolCallCard = memo(function ToolCallCard({message,turnComplete,turnCancelled,-}: SandboxToolCallProps): JSX.Element {- const entry = lookupSandboxToolRenderer(message.resolvedKey)+}: ToolCallCardProps): JSX.Element {+ const entry = lookupToolRenderer(message.resolvedKey)return (<Suspense fallback={<ToolCardSkeleton icon={entry.icon} displayName={entry.displayName} />}><entry.Rendererdiff --git a/products/posthog_ai/frontend/components/tool/builtinToolRenderers.test.tsx b/products/posthog_ai/frontend/components/tool/builtinToolRenderers.test.tsxindex 49df426a664c..ab4103d99e03 100644--- a/products/posthog_ai/frontend/components/tool/builtinToolRenderers.test.tsx+++ b/products/posthog_ai/frontend/components/tool/builtinToolRenderers.test.tsx@@ -2,7 +2,7 @@ import '@testing-library/jest-dom'import { cleanup, fireEvent, render, screen } from '@testing-library/react'-import type { SandboxToolCallMessage } from 'products/posthog_ai/frontend/types/sandboxToolTypes'+import type { ToolCallMessage } from 'products/posthog_ai/frontend/types/toolTypes'import { BuiltinToolRenderer } from './builtinToolRenderers'import { GenericMcpToolRenderer } from './GenericMcpToolRenderer'@@ -15,7 +15,7 @@ function imageBlock(data: string, mimeType: string): unknown {return { type: 'content', content: { type: 'image', data, mimeType } }}-function makeMessage(overrides: Partial<SandboxToolCallMessage> = {}): SandboxToolCallMessage {+function makeMessage(overrides: Partial<ToolCallMessage> = {}): ToolCallMessage {return {id: 'tc-1',resolvedKey: 'Bash',diff --git a/products/posthog_ai/frontend/components/tool/builtinToolRenderers.tsx b/products/posthog_ai/frontend/components/tool/builtinToolRenderers.tsxindex 36eb220df1d2..3dde07654e87 100644--- a/products/posthog_ai/frontend/components/tool/builtinToolRenderers.tsx+++ b/products/posthog_ai/frontend/components/tool/builtinToolRenderers.tsx@@ -7,11 +7,10 @@ import { CodeSnippet } from 'lib/components/CodeSnippet/CodeSnippet'// IconRobot is not exported from @posthog/icons — it lives only in the legacy lib icon set.import { IconRobot } from 'lib/lemon-ui/icons'+import { FilePath } from './FilePath'import { GenericMcpToolRenderer } from './GenericMcpToolRenderer'import { getPostHogExecDisplay } from './posthogExecDisplay'-import { SandboxFilePath } from './SandboxFilePath'-import { SandboxToolActivity } from './SandboxToolActivity'-import type { SandboxToolRendererProps } from './sandboxToolRegistry'+import { ToolActivity } from './ToolActivity'import {MAX_COMMAND_LENGTH,MAX_URL_LENGTH,@@ -28,24 +27,25 @@ import {} from './toolContentUtils'import { languageFromPath } from './toolDiffContent'import { ToolOutput } from './ToolOutput'+import type { ToolRendererProps } from './toolRegistry'function asString(value: unknown): string {return typeof value === 'string' ? value : ''}-function firstLocationPath(props: SandboxToolRendererProps): string | undefined {+function firstLocationPath(props: ToolRendererProps): string | undefined {return props.message.locations?.[0]?.path ?? (asString(props.message.rawInput.file_path) || undefined)}/** Bash / BashOutput / KillShell — command on the second line, ANSI-stripped output in the body. */-const BashToolRenderer = memo(function BashToolRenderer(props: SandboxToolRendererProps): JSX.Element {+const BashToolRenderer = memo(function BashToolRenderer(props: ToolRendererProps): JSX.Element {const { message, icon, turnComplete, turnCancelled } = propsconst command = asString(message.rawInput.command)const description = asString(message.rawInput.description)const output = stripAnsi(stripCodeFences(getCommandOutput(message.content, command, message.rawOutput)))return (- <SandboxToolActivity+ <ToolActivitymessage={message}icon={icon ?? <IconTerminal />}title={description || message.title || 'Terminal'}@@ -64,7 +64,7 @@ const BashToolRenderer = memo(function BashToolRenderer(props: SandboxToolRender})/** Read / NotebookRead — line/image summary on line 1, file chip on line 2, preview in the body. */-const ReadToolRenderer = memo(function ReadToolRenderer(props: SandboxToolRendererProps): JSX.Element {+const ReadToolRenderer = memo(function ReadToolRenderer(props: ToolRendererProps): JSX.Element {const { message, icon, turnComplete, turnCancelled } = propsconst path = firstLocationPath(props)const image = getContentImage(message.content)@@ -95,11 +95,11 @@ const ReadToolRenderer = memo(function ReadToolRenderer(props: SandboxToolRender}return (- <SandboxToolActivity+ <ToolActivitymessage={message}icon={icon ?? <IconDocument />}title={title}- subtitle={path ? <SandboxFilePath path={path} /> : undefined}+ subtitle={path ? <FilePath path={path} /> : undefined}body={body}turnComplete={turnComplete}turnCancelled={turnCancelled}@@ -108,13 +108,13 @@ const ReadToolRenderer = memo(function ReadToolRenderer(props: SandboxToolRender})/** Grep / Glob / LS — result count on line 2, matched lines in the body. */-const SearchToolRenderer = memo(function SearchToolRenderer(props: SandboxToolRendererProps): JSX.Element {+const SearchToolRenderer = memo(function SearchToolRenderer(props: ToolRendererProps): JSX.Element {const { message, icon, displayName, turnComplete, turnCancelled } = propsconst output = getContentText(message.content)const count = getResultCount(output)return (- <SandboxToolActivity+ <ToolActivitymessage={message}icon={icon ?? <IconSearch />}title={message.title || displayName || 'Search'}@@ -131,7 +131,7 @@ const SearchToolRenderer = memo(function SearchToolRenderer(props: SandboxToolRe* body carries the prompt the subagent was handed plus its returned output. The description lives only* in the title (not echoed as a subtitle or input dump), so the card no longer duplicates it.*/-const SubagentToolRenderer = memo(function SubagentToolRenderer(props: SandboxToolRendererProps): JSX.Element {+const SubagentToolRenderer = memo(function SubagentToolRenderer(props: ToolRendererProps): JSX.Element {const { message, icon, turnComplete, turnCancelled } = propsconst subagentType = asString(message.rawInput.subagent_type)const description = asString(message.rawInput.description) || message.title || ''@@ -156,7 +156,7 @@ const SubagentToolRenderer = memo(function SubagentToolRenderer(props: SandboxTo) : undefinedreturn (- <SandboxToolActivity+ <ToolActivitymessage={message}icon={icon ?? <IconRobot />}title={title}@@ -168,7 +168,7 @@ const SubagentToolRenderer = memo(function SubagentToolRenderer(props: SandboxTo})/** WebFetch / WebSearch — linked URL (or query) on line 2, fetched content in the body. */-const FetchToolRenderer = memo(function FetchToolRenderer(props: SandboxToolRendererProps): JSX.Element {+const FetchToolRenderer = memo(function FetchToolRenderer(props: ToolRendererProps): JSX.Element {const { message, icon, turnComplete, turnCancelled } = propsconst url = asString(message.rawInput.url)const query = asString(message.rawInput.query)@@ -178,7 +178,7 @@ const FetchToolRenderer = memo(function FetchToolRenderer(props: SandboxToolRendconst target = url || queryreturn (- <SandboxToolActivity+ <ToolActivitymessage={message}icon={icon ?? <IconGlobe />}title={message.title || (isSearch ? 'Web search' : 'Fetched')}@@ -203,14 +203,14 @@ const FetchToolRenderer = memo(function FetchToolRenderer(props: SandboxToolRend* discovery output renders in the body. The `call` verb never reaches here — it resolves to its inner* tool's renderer instead.*/-const PostHogExecRenderer = memo(function PostHogExecRenderer(props: SandboxToolRendererProps): JSX.Element {+const PostHogExecRenderer = memo(function PostHogExecRenderer(props: ToolRendererProps): JSX.Element {const { message, icon, turnComplete, turnCancelled } = propsconst display = getPostHogExecDisplay(message.rawInput)const input = display?.inputconst output = stripCodeFences(getContentText(message.content))return (- <SandboxToolActivity+ <ToolActivitymessage={message}icon={icon ?? <IconWrench />}title={display?.label || message.title || 'Run command'}@@ -233,7 +233,7 @@ const PostHogExecRenderer = memo(function PostHogExecRenderer(props: SandboxTool* UI's `ToolCallBlock` dispatch. Switches on the resolved tool name; anything unrecognised renders* through `GenericMcpToolRenderer`. Registered for each built-in key and as the registry's default.*/-export const BuiltinToolRenderer = memo(function BuiltinToolRenderer(props: SandboxToolRendererProps): JSX.Element {+export const BuiltinToolRenderer = memo(function BuiltinToolRenderer(props: ToolRendererProps): JSX.Element {if (props.message.resolvedKey.startsWith('__posthog_exec_')) {return <PostHogExecRenderer {...props} />}diff --git a/products/posthog_ai/frontend/components/tool/toolContentUtils.ts b/products/posthog_ai/frontend/components/tool/toolContentUtils.tsindex cf92fb42abc5..a6a9e30c8141 100644--- a/products/posthog_ai/frontend/components/tool/toolContentUtils.ts+++ b/products/posthog_ai/frontend/components/tool/toolContentUtils.ts@@ -1,4 +1,4 @@-import type { SandboxToolCallMessage } from 'products/posthog_ai/frontend/types/sandboxToolTypes'+import type { ToolCallMessage } from 'products/posthog_ai/frontend/types/toolTypes'/** Compact single-line preview length for a generic MCP tool's input JSON. */export const INPUT_PREVIEW_MAX_LENGTH = 60@@ -21,7 +21,7 @@ export interface ToolCallStatusFlags {* not a hook despite reading like one, so it is safe to call conditionally.*/export function resolveToolCallStatus(- status: SandboxToolCallMessage['status'],+ status: ToolCallMessage['status'],turnCancelled: boolean,turnComplete: boolean): ToolCallStatusFlags {diff --git a/products/posthog_ai/frontend/components/tool/sandboxToolRegistry.test.tsx b/products/posthog_ai/frontend/components/tool/toolRegistry.test.tsxsimilarity index 73%rename from products/posthog_ai/frontend/components/tool/sandboxToolRegistry.test.tsxrename to products/posthog_ai/frontend/components/tool/toolRegistry.test.tsxindex f57a755c8c85..a5797a17eedd 100644--- a/products/posthog_ai/frontend/components/tool/sandboxToolRegistry.test.tsx+++ b/products/posthog_ai/frontend/components/tool/toolRegistry.test.tsx@@ -2,12 +2,12 @@ import '@testing-library/jest-dom'import { render, screen } from '@testing-library/react'-import type { SandboxToolCallMessage } from 'products/posthog_ai/frontend/types/sandboxToolTypes'+import type { ToolCallMessage } from 'products/posthog_ai/frontend/types/toolTypes'-import { SandboxToolCall } from './SandboxToolCall'-import { lookupSandboxToolRenderer, sandboxToolRegistry } from './sandboxToolRegistry'+import { ToolCallCard } from './ToolCallCard'+import { lookupToolRenderer, toolRegistry } from './toolRegistry'-function makeMessage(overrides: Partial<SandboxToolCallMessage> = {}): SandboxToolCallMessage {+function makeMessage(overrides: Partial<ToolCallMessage> = {}): ToolCallMessage {return {id: 'tc-1',resolvedKey: 'Edit',@@ -20,25 +20,25 @@ function makeMessage(overrides: Partial<SandboxToolCallMessage> = {}): SandboxTo}}-describe('sandboxToolRegistry', () => {+describe('toolRegistry', () => {// Product-specific data-tool renderers (insight/dashboard/recordings/error-tracking/query/notebook)// are NOT registered by this shared registry — they're contributed by scenes/max via// `registerMaxToolRenderers` and covered by that module's own test. Here we assert only what the// shared, Max-free registry registers: built-ins, exec verbs, the question card, and the fallback.it('leaves product-specific and unknown tool names unregistered, resolving to the key as displayName', () => {- expect(sandboxToolRegistry.lookup('mcp__user-installed__something')).toBeNull()+ expect(toolRegistry.lookup('mcp__user-installed__something')).toBeNull()// The synthesized fallback uses the resolved key as its displayName.- expect(lookupSandboxToolRenderer('mcp__user-installed__something').displayName).toEqual(+ expect(lookupToolRenderer('mcp__user-installed__something').displayName).toEqual('mcp__user-installed__something')- expect(lookupSandboxToolRenderer('experiment-create').displayName).toEqual('experiment-create')+ expect(lookupToolRenderer('experiment-create').displayName).toEqual('experiment-create')// Product adapters live in scenes/max now, so the bare registry resolves them to the fallback.- expect(sandboxToolRegistry.lookup('insight-create')).toBeNull()- expect(sandboxToolRegistry.lookup('query-trends')).toBeNull()- expect(sandboxToolRegistry.lookup('insight-query')).toBeNull()- expect(sandboxToolRegistry.lookup('read_insight')).toBeNull()- expect(sandboxToolRegistry.lookup('query-llm-trace')).toBeNull()+ expect(toolRegistry.lookup('insight-create')).toBeNull()+ expect(toolRegistry.lookup('query-trends')).toBeNull()+ expect(toolRegistry.lookup('insight-query')).toBeNull()+ expect(toolRegistry.lookup('read_insight')).toBeNull()+ expect(toolRegistry.lookup('query-llm-trace')).toBeNull()})// Claude built-ins are keyed by their stable SDK name; the registry contributes a friendly@@ -69,10 +69,10 @@ describe('sandboxToolRegistry', () => {]it.each(builtinCases)('resolves built-in %s to a registered entry with displayName "%s"', (key, displayName) => {- const entry = sandboxToolRegistry.lookup(key)+ const entry = toolRegistry.lookup(key)expect(entry).not.toBeNull()expect(entry?.displayName).toEqual(displayName)- expect(lookupSandboxToolRenderer(key).displayName).toEqual(displayName)+ expect(lookupToolRenderer(key).displayName).toEqual(displayName)})// PostHog single-exec discovery verbs are keyed by their sentinel key (from `resolveToolKey`); the@@ -86,23 +86,23 @@ describe('sandboxToolRegistry', () => {]it.each(execVerbCases)('resolves exec verb %s to a registered entry with displayName "%s"', (key, displayName) => {- const entry = sandboxToolRegistry.lookup(key)+ const entry = toolRegistry.lookup(key)expect(entry).not.toBeNull()expect(entry?.displayName).toEqual(displayName)- expect(lookupSandboxToolRenderer(key).displayName).toEqual(displayName)+ expect(lookupToolRenderer(key).displayName).toEqual(displayName)})it('falls back to the wrench card (key as displayName) for an unmapped built-in-looking name', () => {- expect(sandboxToolRegistry.lookup('NotARealTool')).toBeNull()- expect(lookupSandboxToolRenderer('NotARealTool').displayName).toEqual('NotARealTool')+ expect(toolRegistry.lookup('NotARealTool')).toBeNull()+ expect(lookupToolRenderer('NotARealTool').displayName).toEqual('NotARealTool')})- // Render-level: SandboxToolCall resolves the entry, loads the lazy renderer behind a Suspense+ // Render-level: ToolCallCard resolves the entry, loads the lazy renderer behind a Suspense// skeleton, and the resolved renderer reaches the screen. The skeleton shows the displayName first.describe('lazy dispatch', () => {it('renders a Bash call through its dedicated card once the chunk loads', async () => {render(- <SandboxToolCall+ <ToolCallCardmessage={makeMessage({resolvedKey: 'Bash',claudeToolName: 'Bash',@@ -118,7 +118,7 @@ describe('sandboxToolRegistry', () => {it('renders an unmapped MCP tool through the generic card', async () => {render(- <SandboxToolCall+ <ToolCallCardmessage={makeMessage({resolvedKey: 'do_thing',rawServerName: 'user-mcp',diff --git a/products/posthog_ai/frontend/components/tool/sandboxToolRegistry.tsx b/products/posthog_ai/frontend/components/tool/toolRegistry.tsxsimilarity index 80%rename from products/posthog_ai/frontend/components/tool/sandboxToolRegistry.tsxrename to products/posthog_ai/frontend/components/tool/toolRegistry.tsxindex 13f2691f7323..d70ae0eddeed 100644--- a/products/posthog_ai/frontend/components/tool/sandboxToolRegistry.tsx+++ b/products/posthog_ai/frontend/components/tool/toolRegistry.tsx@@ -16,10 +16,10 @@ import {// IconRobot is not exported from @posthog/icons — it lives only in the legacy lib icon set.import { IconRobot } from 'lib/lemon-ui/icons'-import type { SandboxToolCallMessage } from 'products/posthog_ai/frontend/types/sandboxToolTypes'+import type { ToolCallMessage } from 'products/posthog_ai/frontend/types/toolTypes'-export interface SandboxToolRendererProps {- message: SandboxToolCallMessage+export interface ToolRendererProps {+ message: ToolCallMessageisLastInGroup: boolean/*** Resolved registry entry's icon — the registry's contribution to the card. Renderers use it for@@ -34,12 +34,10 @@ export interface SandboxToolRendererProps {turnCancelled?: boolean}-/** A renderer reachable eagerly or via a lazy chunk — both render identically in `SandboxToolCall`. */-type SandboxToolRendererComponent =- | ComponentType<SandboxToolRendererProps>- | LazyExoticComponent<ComponentType<SandboxToolRendererProps>>+/** A renderer reachable eagerly or via a lazy chunk — both render identically in `ToolCallCard`. */+type ToolRendererComponent = ComponentType<ToolRendererProps> | LazyExoticComponent<ComponentType<ToolRendererProps>>-export interface SandboxToolRegistryEntry {+export interface ToolRegistryEntry {/*** Registry key. For single-exec PostHog tools, this is the **inner** tool name parsed from* `rawInput.command` (e.g. "execute-sql", "insight-create"); for `exec`'s discovery verbs,@@ -50,22 +48,22 @@ export interface SandboxToolRegistryEntry {/** Display name / icon for fallback rendering and for the tool-call header line. */displayName: stringicon: JSX.Element- Renderer: SandboxToolRendererComponent+ Renderer: ToolRendererComponent}-export interface SandboxToolRegistry {- register: (entry: SandboxToolRegistryEntry) => void- lookup: (toolName: string) => SandboxToolRegistryEntry | null+export interface ToolRegistry {+ register: (entry: ToolRegistryEntry) => void+ lookup: (toolName: string) => ToolRegistryEntry | null}-class MapBackedRegistry implements SandboxToolRegistry {- private entries = new Map<string, SandboxToolRegistryEntry>()+class MapBackedRegistry implements ToolRegistry {+ private entries = new Map<string, ToolRegistryEntry>()- register(entry: SandboxToolRegistryEntry): void {+ register(entry: ToolRegistryEntry): void {this.entries.set(entry.key, entry)}- lookup(toolName: string): SandboxToolRegistryEntry | null {+ lookup(toolName: string): ToolRegistryEntry | null {return this.entries.get(toolName) ?? null}}@@ -78,16 +76,14 @@ const BuiltinToolRenderer = lazy(() =>import('./builtinToolRenderers').then((m) => ({ default: m.BuiltinToolRenderer })))const EditToolRenderer = lazy(() => import('./EditDiffRenderer').then((m) => ({ default: m.EditDiffRenderer })))-const QuestionRenderer = lazy(() =>- import('../SandboxQuestionRenderer').then((m) => ({ default: m.SandboxQuestionRenderer }))-)+const QuestionRenderer = lazy(() => import('../QuestionRenderer').then((m) => ({ default: m.QuestionRenderer })))/*** Single module-level registry of tool-name → renderer entry. All entries are registered at module* load — no dynamic registration, no hooks, no scene callbacks. Custom adapters are registered per* tool; any tool without one falls through to the built-in renderer's generic MCP card.*/-export const sandboxToolRegistry: SandboxToolRegistry = new MapBackedRegistry()+export const toolRegistry: ToolRegistry = new MapBackedRegistry()// Product-specific data-tool renderers (insight, dashboard, session recordings, error tracking,// notebooks, query wrappers) are NOT registered here — they live in scenes/max and register themselves@@ -118,14 +114,14 @@ const BUILTIN_TOOLS: { keys: string[]; displayName: string; icon: JSX.Element }[]for (const { keys, displayName, icon } of BUILTIN_TOOLS) {for (const key of keys) {- sandboxToolRegistry.register({ key, displayName, icon, Renderer: BuiltinToolRenderer })+ toolRegistry.register({ key, displayName, icon, Renderer: BuiltinToolRenderer })}}// File-editing built-ins render an inline visual diff when the agent attaches `type: "diff"` content// blocks; EditDiffRenderer falls back to the generic card when none are present.for (const key of ['Edit', 'Write', 'NotebookEdit', 'MultiEdit']) {- sandboxToolRegistry.register({ key, displayName: 'Edit', icon: <IconPencil />, Renderer: EditToolRenderer })+ toolRegistry.register({ key, displayName: 'Edit', icon: <IconPencil />, Renderer: EditToolRenderer })}// PostHog single-exec discovery verbs. `resolveToolKey` parses `exec tools|search|info|schema` into@@ -139,12 +135,12 @@ const POSTHOG_EXEC_VERBS: { key: string; displayName: string; icon: JSX.Element{ key: '__posthog_exec_unknown__', displayName: 'Run command', icon: <IconWrench /> },]for (const { key, displayName, icon } of POSTHOG_EXEC_VERBS) {- sandboxToolRegistry.register({ key, displayName, icon, Renderer: BuiltinToolRenderer })+ toolRegistry.register({ key, displayName, icon, Renderer: BuiltinToolRenderer })}// AskUserQuestion (the agent asking the user to pick between options) gets a bespoke renderer that// lays the question + options out like the LangGraph question recap, rather than the generic JSON card.-sandboxToolRegistry.register({+toolRegistry.register({key: 'AskUserQuestion',displayName: 'Question',icon: <IconAI />,@@ -152,9 +148,9 @@ sandboxToolRegistry.register({})/** Looks up the renderer entry for a resolved tool key, falling back to the generic built-in card. */-export function lookupSandboxToolRenderer(resolvedKey: string): SandboxToolRegistryEntry {+export function lookupToolRenderer(resolvedKey: string): ToolRegistryEntry {return (- sandboxToolRegistry.lookup(resolvedKey) ?? {+ toolRegistry.lookup(resolvedKey) ?? {key: resolvedKey,displayName: resolvedKey,icon: <IconWrench />,diff --git a/products/posthog_ai/frontend/components/tool/sandboxToolResolver.test.ts b/products/posthog_ai/frontend/components/tool/toolResolver.test.tssimilarity index 97%rename from products/posthog_ai/frontend/components/tool/sandboxToolResolver.test.tsrename to products/posthog_ai/frontend/components/tool/toolResolver.test.tsindex ce736d977daa..e69017203c86 100644--- a/products/posthog_ai/frontend/components/tool/sandboxToolResolver.test.ts+++ b/products/posthog_ai/frontend/components/tool/toolResolver.test.ts@@ -1,6 +1,6 @@-import { resolveToolCall, resolveToolKey } from './sandboxToolResolver'+import { resolveToolCall, resolveToolKey } from './toolResolver'-describe('sandboxToolResolver', () => {+describe('toolResolver', () => {describe('resolveToolKey', () => {it('parses the inner tool name out of a single-exec call command', () => {const resolved = resolveToolKey('posthog', 'exec', { command: 'call insight-create {"name":"Signups"}' })diff --git a/products/posthog_ai/frontend/components/tool/sandboxToolResolver.ts b/products/posthog_ai/frontend/components/tool/toolResolver.tssimilarity index 100%rename from products/posthog_ai/frontend/components/tool/sandboxToolResolver.tsrename to products/posthog_ai/frontend/components/tool/toolResolver.tsdiff --git a/products/posthog_ai/frontend/index.ts b/products/posthog_ai/frontend/index.tsindex 5e89f3622d1e..b0f72373b00d 100644--- a/products/posthog_ai/frontend/index.ts+++ b/products/posthog_ai/frontend/index.ts@@ -9,11 +9,11 @@// --- Embeddable run surface ---// `RunViewer` is the Radix-style compound (Root + Thread/Prompt/Composer/Resources/ContextUsage slots);-// `SandboxRunViewer` is the prepackaged default layout for the common embed (tasks, signals inbox).-export { RunViewer, SandboxRunViewer } from './components/SandboxRunViewer'-export type { RunViewerRootProps, SandboxRunViewerProps } from './components/SandboxRunViewer'-export { SandboxComposer } from './components/SandboxComposer'-export type { SandboxComposerProps } from './components/SandboxComposer'+// called directly (`<RunViewer .../>`) it renders the prepackaged default layout for the common embed.+export { RunViewer } from './components/RunViewer'+export type { RunViewerRootProps, RunViewerProps } from './components/RunViewer'+export { RunComposer } from './components/RunComposer'+export type { RunComposerProps } from './components/RunComposer'// --- Composer (Radix-style compound) ---export { Composer } from './components/composer/Composer'@@ -26,9 +26,9 @@ export type {// --- Thread + message presenters ---// `Thread` is the Radix-style compound (Root + Message/Markdown/Reasoning/Failure/Activity/ToolCall atoms);-// `SandboxThreadView` is the prepackaged virtualized presenter (also `Thread.Root`).+// `ThreadView` is the prepackaged virtualized presenter (also `Thread.Root`).export { Thread } from './components/Thread'-export { SandboxThreadView } from './components/SandboxThreadView'+export { ThreadView } from './components/ThreadView'export { MessageTemplate } from './messages/MessageTemplate'export { MarkdownMessage } from './messages/MarkdownMessage'export { ReasoningAnswer } from './messages/ReasoningAnswer'@@ -46,20 +46,16 @@ export {ShimmeringContent,} from './components/ActivityPrimitives'export type { ActivityStatus } from './components/ActivityPrimitives'-export { SandboxActivity } from './components/SandboxActivity'+export { RunActivity } from './components/RunActivity'// --- Tool rendering + registry ----export { sandboxToolRegistry, lookupSandboxToolRenderer } from './components/tool/sandboxToolRegistry'-export type {- SandboxToolRendererProps,- SandboxToolRegistryEntry,- SandboxToolRegistry,-} from './components/tool/sandboxToolRegistry'+export { toolRegistry, lookupToolRenderer } from './components/tool/toolRegistry'+export type { ToolRendererProps, ToolRegistryEntry, ToolRegistry } from './components/tool/toolRegistry'export { GenericMcpToolRenderer } from './components/tool/GenericMcpToolRenderer'-export { SandboxDataToolRow } from './components/tool/SandboxDataToolRow'-export { SandboxToolActivity } from './components/tool/SandboxToolActivity'-export type { SandboxToolActivityProps } from './components/tool/SandboxToolActivity'-export { SandboxFilePath } from './components/tool/SandboxFilePath'+export { DataToolRow } from './components/tool/DataToolRow'+export { ToolActivity } from './components/tool/ToolActivity'+export type { ToolActivityProps } from './components/tool/ToolActivity'+export { FilePath } from './components/tool/FilePath'export { findAllDiffContent, getDiffStats, languageFromPath } from './components/tool/toolDiffContent'export type { ToolCallDiffContent } from './components/tool/toolDiffContent'@@ -69,16 +65,16 @@ export { OptionSelector } from './components/OptionSelector'export type { Option } from './components/OptionSelector'// --- Stream logic + interaction facade ----export { sandboxStreamLogic, isTerminalRunStatus, SANDBOX_INITIAL_PERMISSION_MODE } from './logics/sandboxStreamLogic'-export type { SandboxStreamLogicProps, SandboxSseStatus, SandboxRunStatus } from './logics/sandboxStreamLogic'-export { taskRunInteractionLogic } from './logics/taskRunInteractionLogic'-export type { TaskRunInteractionLogicProps, QueuedMessage } from './logics/taskRunInteractionLogic'+export { runStreamLogic, isTerminalRunStatus, INITIAL_PERMISSION_MODE } from './logics/runStreamLogic'+export type { RunStreamLogicProps, RunSseStatus, RunStatus } from './logics/runStreamLogic'+export { runInteractionLogic } from './logics/runInteractionLogic'+export type { RunInteractionLogicProps, QueuedMessage } from './logics/runInteractionLogic'// --- Permission / question / resource surfaces ----export { SandboxPermissionInput } from './components/SandboxPermissionInput'-export { SandboxQuestionInput } from './components/SandboxQuestionInput'-export { SandboxResourcesBar } from './components/SandboxResourcesBar'-export { SandboxContextUsage } from './components/SandboxContextUsage'+export { PermissionInput } from './components/PermissionInput'+export { QuestionInput } from './components/QuestionInput'+export { ResourcesBar } from './components/ResourcesBar'+export { ContextUsageBar } from './components/ContextUsageBar'// --- Thinking-message helpers ---export { getThinkingMessageFromResponse, getRandomThinkingMessage, THINKING_MESSAGES } from './utils/thinkingMessages'@@ -90,6 +86,6 @@ export type {PermissionRequestRecord,ContextUsage,RunArtifacts,- SandboxProgressStep,-} from './types/sandboxStreamTypes'-export type { SandboxToolCallMessage } from './types/sandboxToolTypes'+ ProgressStep,+} from './types/streamTypes'+export type { ToolCallMessage } from './types/toolTypes'diff --git a/products/posthog_ai/frontend/logics/taskRunInteractionLogic.test.ts b/products/posthog_ai/frontend/logics/runInteractionLogic.test.tssimilarity index 96%rename from products/posthog_ai/frontend/logics/taskRunInteractionLogic.test.tsrename to products/posthog_ai/frontend/logics/runInteractionLogic.test.tsindex 1fb28c5f79f6..59c765f1b8fb 100644--- a/products/posthog_ai/frontend/logics/taskRunInteractionLogic.test.ts+++ b/products/posthog_ai/frontend/logics/runInteractionLogic.test.ts@@ -7,16 +7,16 @@ import { initKeaTests } from '~/test/init'import { tasksRunCreate, tasksRunsCommandCreate } from 'products/tasks/frontend/generated/api'-import { sandboxStreamLogic } from './sandboxStreamLogic'-import { taskRunInteractionLogic } from './taskRunInteractionLogic'+import { runInteractionLogic } from './runInteractionLogic'+import { runStreamLogic } from './runStreamLogic'// Minimal kea stub for the shared sandbox stream logic — gives the test full control over the busy gate// (`isThinking`) and `currentRunStatus`, and lets us fire `markTurnComplete` and observe `pushHumanMessage`// without the real SSE machinery.-jest.mock('./sandboxStreamLogic', () => {+jest.mock('./runStreamLogic', () => {const { kea, actions, key, path, props, reducers } = jest.requireActual('kea')const stub = kea([- path(['test', 'sandboxStreamLogicStub']),+ path(['test', 'runStreamLogicStub']),props({}),key((p: { streamKey: string }) => p.streamKey),actions({@@ -45,7 +45,7 @@ jest.mock('./sandboxStreamLogic', () => {}),])return {- sandboxStreamLogic: stub,+ runStreamLogic: stub,isTerminalRunStatus: (status: string | null) =>status != null && ['completed', 'failed', 'cancelled'].includes(status),}@@ -77,9 +77,9 @@ jest.mock('lib/lemon-ui/LemonToast', () => ({lemonToast: { error: jest.fn() },}))-describe('taskRunInteractionLogic', () => {- let logic: ReturnType<typeof taskRunInteractionLogic.build>- let stream: ReturnType<typeof sandboxStreamLogic.build>+describe('runInteractionLogic', () => {+ let logic: ReturnType<typeof runInteractionLogic.build>+ let stream: ReturnType<typeof runStreamLogic.build>let project: ReturnType<typeof projectLogic.build>const TASK_ID = 'task-1'@@ -106,9 +106,9 @@ describe('taskRunInteractionLogic', () => {initKeaTests()project = projectLogic()project.mount()- stream = sandboxStreamLogic({ streamKey: RUN_ID })+ stream = runStreamLogic({ streamKey: RUN_ID })stream.mount()- logic = taskRunInteractionLogic({ taskId: TASK_ID, runId: RUN_ID, onRunStarted })+ logic = runInteractionLogic({ taskId: TASK_ID, runId: RUN_ID, onRunStarted })logic.mount()})diff --git a/products/posthog_ai/frontend/logics/taskRunInteractionLogic.ts b/products/posthog_ai/frontend/logics/runInteractionLogic.tssimilarity index 93%rename from products/posthog_ai/frontend/logics/taskRunInteractionLogic.tsrename to products/posthog_ai/frontend/logics/runInteractionLogic.tsindex f5be40ba3662..097381e8f3bd 100644--- a/products/posthog_ai/frontend/logics/taskRunInteractionLogic.ts+++ b/products/posthog_ai/frontend/logics/runInteractionLogic.ts@@ -6,10 +6,10 @@ import { projectLogic } from 'scenes/projectLogic'import { tasksRunCreate, tasksRunsCommandCreate } from 'products/tasks/frontend/generated/api'import type { TaskRunResumeRequestSchemaApi } from 'products/tasks/frontend/generated/api.schemas'-import { isTerminalRunStatus, sandboxStreamLogic } from './sandboxStreamLogic'-import type { taskRunInteractionLogicType } from './taskRunInteractionLogicType'+import type { runInteractionLogicType } from './runInteractionLogicType'+import { isTerminalRunStatus, runStreamLogic } from './runStreamLogic'-export interface TaskRunInteractionLogicProps {+export interface RunInteractionLogicProps {taskId: stringrunId: string/** Called with the new run's id after a terminal-run send starts a fresh run, so the surface can@@ -29,9 +29,9 @@ const QUEUED_MESSAGE_ID = 'queued'/*** Max-agnostic interaction facade for a single task run. The UI binds to this one logic to drive every* user → run interaction — sending follow-ups, staging an editable "Up next" message while the agent is- * busy, and (re-exposed from `sandboxStreamLogic`) answering questions / approving operations. It owns no+ * busy, and (re-exposed from `runStreamLogic`) answering questions / approving operations. It owns no* transport: the SSE stream, thread projection, run status, and permission routing all live in- * `sandboxStreamLogic`, which this connects to by `streamKey` (the `runId`).+ * `runStreamLogic`, which this connects to by `streamKey` (the `runId`).** Queueing is client-side and holds at most a single message: a follow-up typed while the agent is working* a turn is staged here (editable, removable), and a second follow-up typed before the turn ends is@@ -39,20 +39,20 @@ const QUEUED_MESSAGE_ID = 'queued'* as one `user_message` when the turn completes. This mirrors the PostHog AI sandbox flush path without any* conversation/Max coupling.*/-export const taskRunInteractionLogic = kea<taskRunInteractionLogicType>([- path(['products', 'posthog_ai', 'frontend', 'logics', 'taskRunInteractionLogic']),- props({} as TaskRunInteractionLogicProps),+export const runInteractionLogic = kea<runInteractionLogicType>([+ path(['products', 'posthog_ai', 'frontend', 'logics', 'runInteractionLogic']),+ props({} as RunInteractionLogicProps),key((props) => props.runId),- connect((props: TaskRunInteractionLogicProps) => ({+ connect((props: RunInteractionLogicProps) => ({values: [projectLogic,['currentProjectId'],- sandboxStreamLogic({ streamKey: props.runId }),+ runStreamLogic({ streamKey: props.runId }),['currentRunStatus', 'pendingPermissionRequest', 'respondingToPermission', 'isThinking'],],actions: [- sandboxStreamLogic({ streamKey: props.runId }),+ runStreamLogic({ streamKey: props.runId }),['pushHumanMessage', 'respondToPermission', 'cancelRun', 'markTurnComplete'],],})),diff --git a/products/posthog_ai/frontend/logics/sandboxStreamLogic.test.ts b/products/posthog_ai/frontend/logics/runStreamLogic.test.tssimilarity index 99%rename from products/posthog_ai/frontend/logics/sandboxStreamLogic.test.tsrename to products/posthog_ai/frontend/logics/runStreamLogic.test.tsindex cbdbb95e5cf8..d0ad4b9cc22e 100644--- a/products/posthog_ai/frontend/logics/sandboxStreamLogic.test.ts+++ b/products/posthog_ai/frontend/logics/runStreamLogic.test.ts@@ -11,7 +11,7 @@ import { initKeaTests } from '~/test/init'import { tasksRunsCommandCreate, tasksRunsStreamTokenRetrieve } from 'products/tasks/frontend/generated/api'-import type { PermissionRequestFrame, StoredLogEntry } from '../types/sandboxWireTypes'+import type { PermissionRequestFrame, StoredLogEntry } from '../types/wireTypes'import {extractRunArtifacts,mapHttpStatusToStreamError,@@ -21,12 +21,12 @@ import {mergeRunArtifacts,parsePermissionRequestFrame,reconnectDelayMs,- resolveSandboxStreamTarget,- sandboxStreamLogic,+ resolveStreamTarget,+ runStreamLogic,SSE_HEALTHY_CONNECTION_MS,SSE_RECONNECT_BASE_DELAY_MS,SSE_RECONNECT_MAX_DELAY_MS,-} from './sandboxStreamLogic'+} from './runStreamLogic'jest.mock('products/tasks/frontend/generated/api', () => ({tasksRunsCommandCreate: jest.fn(),@@ -181,8 +181,8 @@ class MockStream {}}-describe('sandboxStreamLogic', () => {- let logic: ReturnType<typeof sandboxStreamLogic.build>+describe('runStreamLogic', () => {+ let logic: ReturnType<typeof runStreamLogic.build>beforeEach(() => {initKeaTests()@@ -194,7 +194,7 @@ describe('sandboxStreamLogic', () => {projectLogic.mount()projectLogic.actions.loadCurrentProjectSuccess({ id: 997 } as any);(tasksRunsCommandCreate as jest.Mock).mockReset().mockResolvedValue({ jsonrpc: '2.0' })- logic = sandboxStreamLogic({ streamKey: 'test-conversation', conversationId: 'test-conversation' })+ logic = runStreamLogic({ streamKey: 'test-conversation', conversationId: 'test-conversation' })logic.mount()})@@ -932,7 +932,7 @@ describe('sandboxStreamLogic', () => {describe('per-conversation isolation', () => {it('keeps thread state independent between two mounted conversations', async () => {- const otherLogic = sandboxStreamLogic({ streamKey: 'other-conversation' })+ const otherLogic = runStreamLogic({ streamKey: 'other-conversation' })otherLogic.mount()await expectLogic(logic, () => {@@ -1749,8 +1749,8 @@ describe('sandboxStreamLogic', () => {})describe('replayOnly viewer (read-only)', () => {- function mountViewer(streamKey: string): ReturnType<typeof sandboxStreamLogic.build> {- const viewer = sandboxStreamLogic({ streamKey, replayOnly: true })+ function mountViewer(streamKey: string): ReturnType<typeof runStreamLogic.build> {+ const viewer = runStreamLogic({ streamKey, replayOnly: true })viewer.mount()return viewer}@@ -1838,7 +1838,7 @@ describe('sandboxStreamLogic', () => {])jest.spyOn(api.tasks.runs, 'get').mockResolvedValue({ status: 'completed' } as any)- const live = sandboxStreamLogic({ streamKey: 'run-shared' })+ const live = runStreamLogic({ streamKey: 'run-shared' })live.mount()const viewer = mountViewer('run-shared')@@ -2812,7 +2812,7 @@ describe('sandboxStreamLogic', () => {// The renderer must work for runs created by other products that never mint a Conversation:// keyed by task id, commanding the relay by (task, run), with conversation_id absent from telemetry.const captureSpy = jest.spyOn(posthog, 'capture').mockImplementation(() => undefined as any)- const viewerLogic = sandboxStreamLogic({ streamKey: 'task-7' })+ const viewerLogic = runStreamLogic({ streamKey: 'task-7' })viewerLogic.mount()try {viewerLogic.actions.openSseForRun({ taskId: 'task-7', runId: 'run-7' })@@ -2982,9 +2982,9 @@ describe('sandboxStreamLogic', () => {;(tasksRunsStreamTokenRetrieve as jest.Mock).mockReset()})- describe('resolveSandboxStreamTarget', () => {+ describe('resolveStreamTarget', () => {it('skips the token mint and streams from Django when the rollout is off', async () => {- expect(await resolveSandboxStreamTarget('997', 'task-1', 'run-1', false)).toBeNull()+ expect(await resolveStreamTarget('997', 'task-1', 'run-1', false)).toBeNull()expect(tasksRunsStreamTokenRetrieve).not.toHaveBeenCalled()})@@ -2993,7 +2993,7 @@ describe('sandboxStreamLogic', () => {token: 'tok-1',stream_base_url: 'https://proxy.example/',})- expect(await resolveSandboxStreamTarget('997', 'task-1', 'run-1', true)).toEqual({+ expect(await resolveStreamTarget('997', 'task-1', 'run-1', true)).toEqual({baseUrl: 'https://proxy.example/',token: 'tok-1',})@@ -3004,12 +3004,12 @@ describe('sandboxStreamLogic', () => {token: 'tok-1',stream_base_url: null,})- expect(await resolveSandboxStreamTarget('997', 'task-1', 'run-1', true)).toBeNull()+ expect(await resolveStreamTarget('997', 'task-1', 'run-1', true)).toBeNull()})it('falls back to Django when minting the token throws', async () => {;(tasksRunsStreamTokenRetrieve as jest.Mock).mockRejectedValue(new Error('forbidden'))- expect(await resolveSandboxStreamTarget('997', 'task-1', 'run-1', true)).toBeNull()+ expect(await resolveStreamTarget('997', 'task-1', 'run-1', true)).toBeNull()})})diff --git a/products/posthog_ai/frontend/logics/sandboxStreamLogic.ts b/products/posthog_ai/frontend/logics/runStreamLogic.tssimilarity index 97%rename from products/posthog_ai/frontend/logics/sandboxStreamLogic.tsrename to products/posthog_ai/frontend/logics/runStreamLogic.tsindex d7252ac6f24e..85973e55d483 100644--- a/products/posthog_ai/frontend/logics/sandboxStreamLogic.ts+++ b/products/posthog_ai/frontend/logics/runStreamLogic.ts@@ -12,22 +12,22 @@ import { projectLogic } from 'scenes/projectLogic'import { tasksRunsCommandCreate, tasksRunsStreamTokenRetrieve } from 'products/tasks/frontend/generated/api'import type { TaskRunBootstrapCreateRequestInitialPermissionModeEnumApi } from 'products/tasks/frontend/generated/api.schemas'-import { getClaudeCodeMeta, resolveToolCall } from '../components/tool/sandboxToolResolver'-import { parseSandboxQuestions } from '../policy/sandboxQuestionUtils'-import { defaultPermissionDecision, findAllowOptionId } from '../policy/sandboxToolPolicy'+import { getClaudeCodeMeta, resolveToolCall } from '../components/tool/toolResolver'+import { parseSandboxQuestions } from '../policy/questionUtils'+import { defaultPermissionDecision, findAllowOptionId } from '../policy/toolPolicy'import type {ContextUsage,PermissionRequestRecord,ResourceProduct,RunArtifacts,- SandboxProgressStatus,- SandboxProgressStep,+ ProgressStatus,+ ProgressStep,SdkSession,ThreadItem,ThreadItemType,ToolInvocation,ToolInvocationStatus,-} from '../types/sandboxStreamTypes'+} from '../types/streamTypes'import {type PermissionOption,type PermissionRequestFrame,@@ -45,13 +45,13 @@ import {isSessionUpdateUsage,isSessionUpdateUserMessage,isTaskRunStateFrame,-} from '../types/sandboxWireTypes'-import type { sandboxStreamLogicType } from './sandboxStreamLogicType'+} from '../types/wireTypes'+import type { runStreamLogicType } from './runStreamLogicType'-export type SandboxSseStatus = 'idle' | 'connecting' | 'open' | 'reconnecting' | 'closed' | 'error'-export type SandboxRunStatus = 'queued' | 'in_progress' | 'completed' | 'failed' | 'cancelled'+export type RunSseStatus = 'idle' | 'connecting' | 'open' | 'reconnecting' | 'closed' | 'error'+export type RunStatus = 'queued' | 'in_progress' | 'completed' | 'failed' | 'cancelled'-export interface SandboxStreamLogicProps {+export interface RunStreamLogicProps {/*** Stable logic key. PostHog AI passes the conversation id; a generic task viewer (no conversation)* passes the task id. The logic operates on `(taskId, runId)` internally, so it never needs the@@ -80,7 +80,7 @@ export const SSE_RECONNECT_MAX_DELAY_MS = 30_000export const MAX_CUMULATIVE_RECONNECT_ATTEMPTS = 30/** A connection open at least this long before dropping is healthy — its drop is forgiven. */export const SSE_HEALTHY_CONNECTION_MS = 60_000-export const SANDBOX_INITIAL_PERMISSION_MODE: TaskRunBootstrapCreateRequestInitialPermissionModeEnumApi = 'auto'+export const INITIAL_PERMISSION_MODE: TaskRunBootstrapCreateRequestInitialPermissionModeEnumApi = 'auto'/** The crash-error string the in-sandbox agent server writes on a fatal exception. */const AGENT_CRASH_PREFIX = 'Agent server crashed'@@ -99,33 +99,33 @@ const STREAM_END_EVENT = 'stream-end'* falls back to when the in-memory cursor is gone (a keyed-logic remount). Keyed by run id so two* runs never collide. Cleared when the run's stream completes or reaches a terminal status.*/-function sandboxStreamResumeKey(runId: string): string {+function streamResumeKey(runId: string): string {return `posthog-ai:stream-resume:${runId}`}-function readSandboxStreamResumeId(runId: string): string | null {+function readStreamResumeId(runId: string): string | null {try {- return window.sessionStorage.getItem(sandboxStreamResumeKey(runId))+ return window.sessionStorage.getItem(streamResumeKey(runId))} catch {return null}}-function writeSandboxStreamResumeId(runId: string, eventId: string): void {+function writeStreamResumeId(runId: string, eventId: string): void {try {- window.sessionStorage.setItem(sandboxStreamResumeKey(runId), eventId)+ window.sessionStorage.setItem(streamResumeKey(runId), eventId)} catch {// sessionStorage may be unavailable (private mode / quota) — resume from in-memory state only.}}-function clearSandboxStreamResumeId(runId: string): void {+function clearStreamResumeId(runId: string): void {try {- window.sessionStorage.removeItem(sandboxStreamResumeKey(runId))+ window.sessionStorage.removeItem(streamResumeKey(runId))} catch {// ignore}}/** Resolved live-stream destination: the agent-proxy origin plus the run-scoped read token. */-export interface SandboxStreamProxyTarget {+export interface StreamProxyTarget {baseUrl: stringtoken: string}@@ -135,12 +135,12 @@ export interface SandboxStreamProxyTarget {* rollout flag off we skip the token mint entirely (pre-proxy behavior); with it on but the server* resolves no base URL — or the mint throws — we fall back to Django so streaming never breaks.*/-export async function resolveSandboxStreamTarget(+export async function resolveStreamTarget(projectId: string,taskId: string,runId: string,viaProxy: boolean-): Promise<SandboxStreamProxyTarget | null> {+): Promise<StreamProxyTarget | null> {if (!viaProxy) {return null}@@ -485,7 +485,7 @@ function mapAcpStatus(status: unknown): ToolInvocationStatus {}}-function normalizeProgressStatus(status: unknown): SandboxProgressStatus {+function normalizeProgressStatus(status: unknown): ProgressStatus {switch (status) {case 'pending':case 'in_progress':@@ -614,7 +614,7 @@ export interface StoredEntry {* before the live tail is appended. Steady-state live frames resume exactly after the last-seen* Redis id (exclusive), so they never re-deliver — a plain append therefore cannot double the thread.*/-export interface SandboxLog {+export interface RunLog {entries: StoredEntry[]}@@ -877,7 +877,7 @@ export function foldLogToThread(entries: StoredEntry[], options: { isResumeRun:const label = stringifyOptional(params.label)if (group && step && label) {const detail = stringifyOptional(params.detail)- const nextStep: SandboxProgressStep = {+ const nextStep: ProgressStep = {key: step,status: normalizeProgressStatus(params.status),label,@@ -1033,13 +1033,13 @@ export function foldLogToThread(entries: StoredEntry[], options: { isResumeRun:* Keyed by `streamKey` (the conversation id for PostHog AI, the task id for a generic task viewer)* so concurrent streams keep independent stream state and connections.*/-export const sandboxStreamLogic = kea<sandboxStreamLogicType>([+export const runStreamLogic = kea<runStreamLogicType>([// `replayOnly` needs a default so selectors can depend on it as a prop (kea throws on a missing prop).- props({ replayOnly: false } as SandboxStreamLogicProps),+ props({ replayOnly: false } as RunStreamLogicProps),// A read-only viewer keys under a `replay:` namespace so it never shares an instance with a live// stream of the same run — streaming can't bleed into a read-only thread.key((props) => (props.replayOnly ? `replay:${props.streamKey}` : props.streamKey)),- path((key) => ['products', 'posthog_ai', 'frontend', 'logics', 'sandboxStreamLogic', key]),+ path((key) => ['products', 'posthog_ai', 'frontend', 'logics', 'runStreamLogic', key]),connect(() => ({values: [projectLogic, ['currentProjectId'], featureFlagLogic, ['featureFlags'], preflightLogic, ['preflight']],})),@@ -1094,7 +1094,7 @@ export const sandboxStreamLogic = kea<sandboxStreamLogicType>([}),/*** Entry point for every parsed permission request. Applies the default tool policy- * (`sandboxToolPolicy`): auto-approve built-in tools + non-destructive PostHog exec, prompt+ * (`toolPolicy`): auto-approve built-in tools + non-destructive PostHog exec, prompt* for update/delete exec (and other MCP). Replayed-from-history requests are never* auto-approved — they're a read-only restore and the run may already be terminal.*/@@ -1137,7 +1137,7 @@ export const sandboxStreamLogic = kea<sandboxStreamLogicType>([*/permissionResponseFailed: true,handleTerminalStatus: (status: {- status: SandboxRunStatus+ status: RunStatuserrorMessage?: string | nullreplayedFromHistory?: boolean}) => status,@@ -1165,7 +1165,7 @@ export const sandboxStreamLogic = kea<sandboxStreamLogicType>([}),reducers({sseStatus: [- 'idle' as SandboxSseStatus,+ 'idle' as RunSseStatus,{sseConnecting: () => 'connecting',sseOpened: () => 'open',@@ -1197,7 +1197,7 @@ export const sandboxStreamLogic = kea<sandboxStreamLogicType>([},],currentRunStatus: [- null as SandboxRunStatus | null,+ null as RunStatus | null,{// A reconnect reopens the same in-flight run — keep its known status rather than// flickering back to queued; only a fresh open (no/terminal status) resets.@@ -1225,7 +1225,7 @@ export const sandboxStreamLogic = kea<sandboxStreamLogicType>([// steady-state live frames resume exclusively after the last-seen Redis id, so a plain// append never doubles the thread.log: [- { entries: [] } as SandboxLog,+ { entries: [] } as RunLog,{appendEntries: (state, { entries }) =>entries.length === 0 ? state : { entries: [...state.entries, ...entries] },@@ -1461,7 +1461,7 @@ export const sandboxStreamLogic = kea<sandboxStreamLogicType>([* workflow is still setting up the sandbox); it holds the gerund loader off until `run_started`* so it can't show before a turn begins. Boot UX is surfaced by `_posthog/progress` items, not* a dedicated indicator. `thinking` = the agent is working a turn (mirrors `isThinking`), and is- * what `SandboxThreadView` gates the gerund loader on; `idle` otherwise (terminal, errored, or+ * what `ThreadView` gates the gerund loader on; `idle` otherwise (terminal, errored, or* not yet connecting). A read-only viewer is always `idle` — it never streams.*/streamPhase: [@@ -1540,7 +1540,7 @@ export const sandboxStreamLogic = kea<sandboxStreamLogicType>([if (isTerminalRunStatus(replayRun.status ?? null)) {// Record the terminal status read-only — no SSE to close, no termination telemetry.actions.handleTerminalStatus({- status: replayRun.status as SandboxRunStatus,+ status: replayRun.status as RunStatus,replayedFromHistory: true,})}@@ -1619,7 +1619,7 @@ export const sandboxStreamLogic = kea<sandboxStreamLogicType>([if (terminal) {// Read-only history — surface the terminal status, do not open SSE. Flag the replay// so the listener records the status without re-emitting termination telemetry.- actions.handleTerminalStatus({ status: run.status as SandboxRunStatus, replayedFromHistory: true })+ actions.handleTerminalStatus({ status: run.status as RunStatus, replayedFromHistory: true })actions.bootstrapLogReady()return}@@ -1661,7 +1661,7 @@ export const sandboxStreamLogic = kea<sandboxStreamLogicType>([// steady-state stream never re-delivers a frame we've already appended. Mirrored to// sessionStorage so a live reconnect that lost the in-memory cursor can recover it.cache.lastEventId = id- writeSandboxStreamResumeId(runId, id)+ writeStreamResumeId(runId, id)}if (event === STREAM_END_EVENT) {// Durable end-of-run sentinel — the run's event stream is finished, so stop here@@ -1670,7 +1670,7 @@ export const sandboxStreamLogic = kea<sandboxStreamLogicType>([// the listener. `streamEnded` (read by the reader loop) suppresses the clean-EOF// drop that follows.cache.streamEnded = true- clearSandboxStreamResumeId(runId)+ clearStreamResumeId(runId)actions.streamEnded()return}@@ -1730,7 +1730,7 @@ export const sandboxStreamLogic = kea<sandboxStreamLogicType>([// a PR — fold them in so the post-turn PR card appears the moment it lands.actions.mergeRunArtifacts(extractRunArtifacts(parsed))actions.handleTerminalStatus({- status: parsed.status as SandboxRunStatus,+ status: parsed.status as RunStatus,errorMessage: parsed.error_message ?? null,})}@@ -1748,7 +1748,7 @@ export const sandboxStreamLogic = kea<sandboxStreamLogicType>([// carries a valid one); with it off, or on the fallback, it's a no-op and we hit// Django. A failed mint falls back to Django — streaming never breaks on the proxy.const proxyTarget = values.streamViaProxyEnabled- ? await resolveSandboxStreamTarget(String(projectId), taskId, runId, true)+ ? await resolveStreamTarget(String(projectId), taskId, runId, true): nullif (signal.aborted) {return@@ -1760,7 +1760,7 @@ export const sandboxStreamLogic = kea<sandboxStreamLogicType>([// pre-empt it — only a live reconnect that lost its in-memory cursor honors it.const lastEventId =(cache.lastEventId as string | undefined) ??- (cache.bufferingLiveFrames ? undefined : (readSandboxStreamResumeId(runId) ?? undefined))+ (cache.bufferingLiveFrames ? undefined : (readStreamResumeId(runId) ?? undefined))let response: Responsetry {@@ -1891,7 +1891,7 @@ export const sandboxStreamLogic = kea<sandboxStreamLogicType>([// Terminal → final terminal-status action + close.if (isTerminalRunStatus(result.status)) {- actions.handleTerminalStatus({ status: result.status as SandboxRunStatus })+ actions.handleTerminalStatus({ status: result.status as RunStatus })return}@@ -1961,7 +1961,7 @@ export const sandboxStreamLogic = kea<sandboxStreamLogicType>([// A reconnect/end refetch can be the first place a freshly-opened PR (or branch) shows up.actions.mergeRunArtifacts(result.artifacts)if (isTerminalRunStatus(result.status)) {- actions.handleTerminalStatus({ status: result.status as SandboxRunStatus })+ actions.handleTerminalStatus({ status: result.status as RunStatus })}},routePermissionRequest: ({ record, replayedFromHistory }) => {@@ -2088,7 +2088,7 @@ export const sandboxStreamLogic = kea<sandboxStreamLogicType>([// resume a finished stream (the S3 history replay is the reopen path).const terminalRun = cache.activeRun as { taskId: string; runId: string } | undefinedif (terminalRun) {- clearSandboxStreamResumeId(terminalRun.runId)+ clearStreamResumeId(terminalRun.runId)}// A run that already terminated in a prior session is surfaced read-only on reopen —diff --git a/products/posthog_ai/frontend/policy/sandboxPermissionDisplayUtils.test.ts b/products/posthog_ai/frontend/policy/permissionDisplayUtils.test.tssimilarity index 88%rename from products/posthog_ai/frontend/policy/sandboxPermissionDisplayUtils.test.tsrename to products/posthog_ai/frontend/policy/permissionDisplayUtils.test.tsindex f669b6c4405a..6b3902fd7ab7 100644--- a/products/posthog_ai/frontend/policy/sandboxPermissionDisplayUtils.test.ts+++ b/products/posthog_ai/frontend/policy/permissionDisplayUtils.test.ts@@ -1,5 +1,5 @@-import type { PermissionRequestRecord, ToolInvocation } from '../types/sandboxStreamTypes'-import { getPostHogExecDisplay, getSandboxPermissionDisplay } from './sandboxPermissionDisplayUtils'+import type { PermissionRequestRecord, ToolInvocation } from '../types/streamTypes'+import { getPostHogExecDisplay, getPermissionDisplay } from './permissionDisplayUtils'const rawToolCall: ToolInvocation = {toolCallId: 'tc-1',@@ -24,9 +24,9 @@ function makeRequest(overrides: Partial<PermissionRequestRecord> = {}): Permissi}}-describe('sandboxPermissionDisplayUtils', () => {+describe('permissionDisplayUtils', () => {it('unwraps PostHog exec call commands into an MCP title and pretty JSON payload', () => {- const display = getSandboxPermissionDisplay(+ const display = getPermissionDisplay(makeRequest({rawToolCall: {...rawToolCall,@@ -54,7 +54,7 @@ describe('sandboxPermissionDisplayUtils', () => {})it('keeps non-JSON PostHog exec args displayable', () => {- const display = getSandboxPermissionDisplay(+ const display = getPermissionDisplay(makeRequest({rawToolCall: {...rawToolCall,@@ -70,7 +70,7 @@ describe('sandboxPermissionDisplayUtils', () => {})it('formats generic MCP tool input as JSON', () => {- const display = getSandboxPermissionDisplay(+ const display = getPermissionDisplay(makeRequest({toolName: 'mcp__github__create_issue',rawToolCall: {diff --git a/products/posthog_ai/frontend/policy/sandboxPermissionDisplayUtils.ts b/products/posthog_ai/frontend/policy/permissionDisplayUtils.tssimilarity index 87%rename from products/posthog_ai/frontend/policy/sandboxPermissionDisplayUtils.tsrename to products/posthog_ai/frontend/policy/permissionDisplayUtils.tsindex daa82c62b2e1..042c2b16d729 100644--- a/products/posthog_ai/frontend/policy/sandboxPermissionDisplayUtils.ts+++ b/products/posthog_ai/frontend/policy/permissionDisplayUtils.ts@@ -3,13 +3,13 @@ import {formatPostHogExecBody,getPostHogExecDisplay,} from '../components/tool/posthogExecDisplay'-import { resolveToolCall } from '../components/tool/sandboxToolResolver'-import type { PermissionRequestRecord } from '../types/sandboxStreamTypes'+import { resolveToolCall } from '../components/tool/toolResolver'+import type { PermissionRequestRecord } from '../types/streamTypes'// Re-exported so existing importers (and tests) keep resolving the exec display from here.export { getPostHogExecDisplay } from '../components/tool/posthogExecDisplay'-export interface SandboxPermissionDisplay {+export interface PermissionDisplay {title?: stringpayload?: string}@@ -37,7 +37,7 @@ function formatInput(rawInput: unknown): string | undefined {}}-export function getSandboxPermissionDisplay(request: PermissionRequestRecord): SandboxPermissionDisplay {+export function getPermissionDisplay(request: PermissionRequestRecord): PermissionDisplay {const mcpTool = parseMcpToolKey(request.toolName)if (!mcpTool) {return {diff --git a/products/posthog_ai/frontend/policy/sandboxPermissionUtils.test.ts b/products/posthog_ai/frontend/policy/permissionUtils.test.tssimilarity index 93%rename from products/posthog_ai/frontend/policy/sandboxPermissionUtils.test.tsrename to products/posthog_ai/frontend/policy/permissionUtils.test.tsindex 47d64851aba3..2a29b075fd31 100644--- a/products/posthog_ai/frontend/policy/sandboxPermissionUtils.test.ts+++ b/products/posthog_ai/frontend/policy/permissionUtils.test.ts@@ -1,7 +1,7 @@-import type { PermissionOption } from '../types/sandboxWireTypes'-import { mapPermissionOption, mapPermissionOptions } from './sandboxPermissionUtils'+import type { PermissionOption } from '../types/wireTypes'+import { mapPermissionOption, mapPermissionOptions } from './permissionUtils'-describe('sandboxPermissionUtils', () => {+describe('permissionUtils', () => {describe('mapPermissionOption', () => {it.each<[string, Partial<ReturnType<typeof mapPermissionOption>>]>([[diff --git a/products/posthog_ai/frontend/policy/sandboxPermissionUtils.ts b/products/posthog_ai/frontend/policy/permissionUtils.tssimilarity index 98%rename from products/posthog_ai/frontend/policy/sandboxPermissionUtils.tsrename to products/posthog_ai/frontend/policy/permissionUtils.tsindex dbd15efb63ee..e07dcf931f7b 100644--- a/products/posthog_ai/frontend/policy/sandboxPermissionUtils.ts+++ b/products/posthog_ai/frontend/policy/permissionUtils.ts@@ -1,4 +1,4 @@-import type { PermissionOption } from '../types/sandboxWireTypes'+import type { PermissionOption } from '../types/wireTypes'/*** The card-facing decision a user can take on a sandbox ACP `permission_request` option. Thediff --git a/products/posthog_ai/frontend/policy/sandboxQuestionUtils.test.ts b/products/posthog_ai/frontend/policy/questionUtils.test.tssimilarity index 96%rename from products/posthog_ai/frontend/policy/sandboxQuestionUtils.test.tsrename to products/posthog_ai/frontend/policy/questionUtils.test.tsindex 7ab65e93d323..df2d3cf5b1b6 100644--- a/products/posthog_ai/frontend/policy/sandboxQuestionUtils.test.ts+++ b/products/posthog_ai/frontend/policy/questionUtils.test.ts@@ -3,10 +3,10 @@ import {extractSandboxQuestionAnswer,parseSandboxQuestionAnswers,parseSandboxQuestions,- type SandboxQuestion,-} from './sandboxQuestionUtils'+ type AgentQuestion,+} from './questionUtils'-describe('sandboxQuestionUtils', () => {+describe('questionUtils', () => {describe('parseSandboxQuestions', () => {it('parses the { questions: [...] } shape with options and descriptions', () => {const result = parseSandboxQuestions({@@ -85,7 +85,7 @@ describe('sandboxQuestionUtils', () => {})describe('deriveQuestionOptionId', () => {- const question: SandboxQuestion = {+ const question: AgentQuestion = {question: 'Pick',multiSelect: false,options: [{ label: 'Activation' }, { label: 'Revenue' }],diff --git a/products/posthog_ai/frontend/policy/sandboxQuestionUtils.ts b/products/posthog_ai/frontend/policy/questionUtils.tssimilarity index 88%rename from products/posthog_ai/frontend/policy/sandboxQuestionUtils.tsrename to products/posthog_ai/frontend/policy/questionUtils.tsindex a92e9646cb69..768cbadcdfb3 100644--- a/products/posthog_ai/frontend/policy/sandboxQuestionUtils.ts+++ b/products/posthog_ai/frontend/policy/questionUtils.ts@@ -6,37 +6,37 @@* `AskUserQuestion`. Twig routes it through the ACP permission framework: a single* `permission_request` carries `toolCall._meta.codeToolKind === 'question'` + `_meta.questions`, and* the answer is returned on the existing `permission_response` command as an `answers` map keyed by- * question text. These helpers are shared by `sandboxStreamLogic` (parsing the request), the input- * overlay (`SandboxQuestionInput`, building the reply), and the thread recap (`SandboxQuestionRenderer`).+ * question text. These helpers are shared by `runStreamLogic` (parsing the request), the input+ * overlay (`QuestionInput`, building the reply), and the thread recap (`QuestionRenderer`).*//** The `option_${idx}` ids Twig's `buildQuestionOptions` mints for the first question's options. */export const SANDBOX_QUESTION_OPTION_PREFIX = 'option_'/** One choice the agent offered for a question. */-export interface SandboxQuestionOption {+export interface AgentQuestionOption {label: stringdescription?: string}/** One question parsed from an `AskUserQuestion` permission request or tool call. */-export interface SandboxQuestion {+export interface AgentQuestion {question: string/** Short chip label (≤12 chars in the tool schema) shown above the question. */header?: stringmultiSelect: boolean- options: SandboxQuestionOption[]+ options: AgentQuestionOption[]}function asRecord(value: unknown): Record<string, unknown> | null {return value && typeof value === 'object' && !Array.isArray(value) ? (value as Record<string, unknown>) : null}-function parseOptions(raw: unknown): SandboxQuestionOption[] {+function parseOptions(raw: unknown): AgentQuestionOption[] {if (!Array.isArray(raw)) {return []}- const options: SandboxQuestionOption[] = []+ const options: AgentQuestionOption[] = []for (const entry of raw) {const record = asRecord(entry)if (!record || typeof record.label !== 'string') {@@ -50,7 +50,7 @@ function parseOptions(raw: unknown): SandboxQuestionOption[] {return options}-function parseQuestionItem(record: Record<string, unknown>): SandboxQuestion | null {+function parseQuestionItem(record: Record<string, unknown>): AgentQuestion | null {if (typeof record.question !== 'string') {return null}@@ -67,13 +67,13 @@ function parseQuestionItem(record: Record<string, unknown>): SandboxQuestion | n* (`normalizeAskUserQuestionInput`): the preferred `{ questions: [...] }`, or a single* `{ question, header, options, multiSelect }`. Returns `[]` when nothing parseable is present.*/-export function parseSandboxQuestions(raw: unknown): SandboxQuestion[] {+export function parseSandboxQuestions(raw: unknown): AgentQuestion[] {const record = asRecord(raw)if (!record) {return []}if (Array.isArray(record.questions)) {- const questions: SandboxQuestion[] = []+ const questions: AgentQuestion[] = []for (const entry of record.questions) {const itemRecord = asRecord(entry)const item = itemRecord ? parseQuestionItem(itemRecord) : null@@ -160,7 +160,7 @@ export function extractSandboxQuestionAnswer(result: unknown): string | null {* `option_0` for a free-typed ("Other") answer that matches no option. The `answers` map carries the* real content for the agent — `optionId` only has to be a valid offered option.*/-export function deriveQuestionOptionId(question: SandboxQuestion, selectedLabels: string[]): string {+export function deriveQuestionOptionId(question: AgentQuestion, selectedLabels: string[]): string {const first = selectedLabels[0]const idx = first !== undefined ? question.options.findIndex((o) => o.label === first) : -1return `${SANDBOX_QUESTION_OPTION_PREFIX}${idx >= 0 ? idx : 0}`diff --git a/products/posthog_ai/frontend/policy/sandboxToolPolicy.test.ts b/products/posthog_ai/frontend/policy/toolPolicy.test.tssimilarity index 96%rename from products/posthog_ai/frontend/policy/sandboxToolPolicy.test.tsrename to products/posthog_ai/frontend/policy/toolPolicy.test.tsindex 8282b7e8bd08..c92ed8747f69 100644--- a/products/posthog_ai/frontend/policy/sandboxToolPolicy.test.ts+++ b/products/posthog_ai/frontend/policy/toolPolicy.test.ts@@ -1,13 +1,13 @@-import type { PermissionRequestRecord, ToolInvocation } from '../types/sandboxStreamTypes'-import type { PermissionOption } from '../types/sandboxWireTypes'-import type { SandboxQuestion } from './sandboxQuestionUtils'+import type { PermissionRequestRecord, ToolInvocation } from '../types/streamTypes'+import type { PermissionOption } from '../types/wireTypes'+import type { AgentQuestion } from './questionUtils'import {defaultPermissionDecision,findAllowOptionId,isPostHogDestructiveSubTool,isPostHogExecTool,type PermissionDecision,-} from './sandboxToolPolicy'+} from './toolPolicy'function makeRecord(overrides: {@@ -17,7 +17,7 @@ function makeRecord(input?: Record<string, unknown>meta?: unknownoptions?: PermissionOption[]- questions?: SandboxQuestion[]+ questions?: AgentQuestion[]} = {}): PermissionRequestRecord {const rawToolCall: ToolInvocation = {@@ -39,7 +39,7 @@ function makeRecord(}}-describe('sandboxToolPolicy', () => {+describe('toolPolicy', () => {describe('isPostHogExecTool', () => {it.each([['mcp__posthog__exec', true],diff --git a/products/posthog_ai/frontend/policy/sandboxToolPolicy.ts b/products/posthog_ai/frontend/policy/toolPolicy.tssimilarity index 96%rename from products/posthog_ai/frontend/policy/sandboxToolPolicy.tsrename to products/posthog_ai/frontend/policy/toolPolicy.tsindex 84c527d9b57c..5f1cd45172cd 100644--- a/products/posthog_ai/frontend/policy/sandboxToolPolicy.ts+++ b/products/posthog_ai/frontend/policy/toolPolicy.ts@@ -1,6 +1,6 @@import { isPostHogExecTool } from '../components/tool/posthogExecDisplay'-import { resolveToolCall } from '../components/tool/sandboxToolResolver'-import type { PermissionRequestRecord } from '../types/sandboxStreamTypes'+import { resolveToolCall } from '../components/tool/toolResolver'+import type { PermissionRequestRecord } from '../types/streamTypes'// Re-exported so existing importers (and tests) keep resolving the exec-tool check from here.export { isPostHogExecTool } from '../components/tool/posthogExecDisplay'diff --git a/products/posthog_ai/frontend/types/sandboxStreamTypes.ts b/products/posthog_ai/frontend/types/streamTypes.tssimilarity index 92%rename from products/posthog_ai/frontend/types/sandboxStreamTypes.tsrename to products/posthog_ai/frontend/types/streamTypes.tsindex f41d2374fa9b..3a46a6a60db6 100644--- a/products/posthog_ai/frontend/types/sandboxStreamTypes.ts+++ b/products/posthog_ai/frontend/types/streamTypes.ts@@ -2,20 +2,20 @@* Thread shapes for the sandbox agent runtime (`agent_runtime === 'sandbox'`).** The sandbox path consumes the products/tasks SSE endpoint directly (the same endpoint- * PostHog Code uses). `sandboxStreamLogic` folds the raw wire frames (typed in- * `./sandboxWireTypes`) into `ToolInvocation` / `ThreadItem` stream state.+ * PostHog Code uses). `runStreamLogic` folds the raw wire frames (typed in+ * `./wireTypes`) into `ToolInvocation` / `ThreadItem` stream state.*/-import type { SandboxQuestion } from '../policy/sandboxQuestionUtils'-import type { PermissionOption } from './sandboxWireTypes'+import type { AgentQuestion } from '../policy/questionUtils'+import type { PermissionOption } from './wireTypes'export type ToolInvocationStatus = 'pending' | 'in_progress' | 'completed' | 'failed'-export type SandboxProgressStatus = 'pending' | 'in_progress' | 'completed' | 'failed'+export type ProgressStatus = 'pending' | 'in_progress' | 'completed' | 'failed'-export interface SandboxProgressStep {+export interface ProgressStep {key: stringlabel: string- status: SandboxProgressStatus+ status: ProgressStatusdetail?: string}@@ -99,7 +99,7 @@ export interface ThreadItem {/** For `progress` items — backend-supplied group id, scoped to the task run. */progressGroup?: string/** For `progress` items — ordered setup/runtime progress rows. */- progressSteps?: SandboxProgressStep[]+ progressSteps?: ProgressStep[]}/** One PostHog product the agent grounded an answer in, accumulated across the whole session. */@@ -166,7 +166,7 @@ export interface RunArtifacts {/*** A pending ACP `permission_request` surfaced by the products/tasks stream, rendered by- * `SandboxPermissionInput` in the input area.+ * `PermissionInput` in the input area.*/export interface PermissionRequestRecord {requestId: string@@ -182,5 +182,5 @@ export interface PermissionRequestRecord {* framework (`toolCall._meta.codeToolKind === 'question'`, `_meta.questions`). Drives the* interactive question overlay instead of the approve/decline card, and blocks auto-approval.*/- questions?: SandboxQuestion[]+ questions?: AgentQuestion[]}diff --git a/products/posthog_ai/frontend/types/sandboxToolTypes.ts b/products/posthog_ai/frontend/types/toolTypes.tssimilarity index 88%rename from products/posthog_ai/frontend/types/sandboxToolTypes.tsrename to products/posthog_ai/frontend/types/toolTypes.tsindex 1d30f3bd524e..665a99ff708e 100644--- a/products/posthog_ai/frontend/types/sandboxToolTypes.ts+++ b/products/posthog_ai/frontend/types/toolTypes.ts@@ -1,8 +1,8 @@/**- * The shape `sandboxToolRegistry` renderers receive — raw `ToolInvocation` stream state plus+ * The shape `toolRegistry` renderers receive — raw `ToolInvocation` stream state plus* renderer-facing fields resolved at render time.*/-export interface SandboxToolCallMessage {+export interface ToolCallMessage {/** Stable id — the tool call id. */id: string/** Registry lookup key — the inner tool name for single-exec calls, otherwise the wire tool name. */diff --git a/products/posthog_ai/frontend/types/sandboxWireTypes.test.ts b/products/posthog_ai/frontend/types/wireTypes.test.tssimilarity index 99%rename from products/posthog_ai/frontend/types/sandboxWireTypes.test.tsrename to products/posthog_ai/frontend/types/wireTypes.test.tsindex f1a2d866858e..8730c9435a8d 100644--- a/products/posthog_ai/frontend/types/sandboxWireTypes.test.ts+++ b/products/posthog_ai/frontend/types/wireTypes.test.ts@@ -12,7 +12,7 @@ import {isTaskRunStateFrame,hasUsageBreakdown,hasUsageUsed,-} from './sandboxWireTypes'+} from './wireTypes'const TIMESTAMP = '2026-06-11T09:00:00.000000+00:00'const RUN_ID = '3d2f3e7a-5c1b-4f7e-9d51-0a9b8c7d6e5f'@@ -206,7 +206,7 @@ function notificationOf(frame: unknown): AcpNotification {return frame.notification}-describe('sandboxWireTypes guards', () => {+describe('wireTypes guards', () => {it.each([['queued', { type: 'task_run_state', run_id: RUN_ID, task_id: TASK_ID, status: 'queued', stage: null }],[diff --git a/products/posthog_ai/frontend/types/sandboxWireTypes.ts b/products/posthog_ai/frontend/types/wireTypes.tssimilarity index 99%rename from products/posthog_ai/frontend/types/sandboxWireTypes.tsrename to products/posthog_ai/frontend/types/wireTypes.tsindex b8a6dbffc0ab..988d208a040c 100644--- a/products/posthog_ai/frontend/types/sandboxWireTypes.ts+++ b/products/posthog_ai/frontend/types/wireTypes.ts@@ -77,7 +77,7 @@ export interface PermissionRequestFrame {toolCall?: Record<string, unknown>}-export type SandboxWireFrame = StoredLogEntry | TaskRunStateFrame | KeepaliveFrame | PermissionRequestFrame+export type WireFrame = StoredLogEntry | TaskRunStateFrame | KeepaliveFrame | PermissionRequestFrame/*** `event: error` payload. The products/tasks relay emits `{error}`; cloud-agent envelopes carrydiff --git a/products/tasks/frontend/components/TaskRunChat.tsx b/products/tasks/frontend/components/TaskRunChat.tsxindex 9f12fd855994..a95a46910acb 100644--- a/products/tasks/frontend/components/TaskRunChat.tsx+++ b/products/tasks/frontend/components/TaskRunChat.tsx@@ -1,10 +1,6 @@import { BindLogic, useActions, useValues } from 'kea'-import {- SandboxRunViewer,- type TaskRunInteractionLogicProps,- taskRunInteractionLogic,-} from 'products/posthog_ai/frontend'+import { RunViewer, type RunInteractionLogicProps, runInteractionLogic } from 'products/posthog_ai/frontend'import { taskDetailSceneLogic } from '../logics/taskDetailSceneLogic'@@ -14,8 +10,8 @@ export interface TaskRunChatProps {}/**- * Live task-run surface. Binds `taskRunInteractionLogic` (the Max-agnostic interaction facade, which- * connects to the shared `sandboxStreamLogic` keyed by `runId`) and renders `SandboxRunViewer` in live+ * 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@@ -23,7 +19,7 @@ export interface TaskRunChatProps {*/export function TaskRunChat({ taskId, runId }: TaskRunChatProps): JSX.Element {const { setSelectedRunId, loadTaskRuns } = useActions(taskDetailSceneLogic({ taskId }))- const logicProps: TaskRunInteractionLogicProps = {+ const logicProps: RunInteractionLogicProps = {taskId,runId,onRunStarted: (newRunId) => {@@ -33,20 +29,18 @@ export function TaskRunChat({ taskId, runId }: TaskRunChatProps): JSX.Element {}return (- <BindLogic logic={taskRunInteractionLogic} props={logicProps}>+ <BindLogic logic={runInteractionLogic} props={logicProps}><TaskRunChatContent logicProps={logicProps} /></BindLogic>)}-function TaskRunChatContent({ logicProps }: { logicProps: TaskRunInteractionLogicProps }): JSX.Element {- const { draft, isSubmitting, queuedMessages } = useValues(taskRunInteractionLogic(logicProps))- const { setDraft, submit, updateQueuedMessage, removeQueuedMessage } = useActions(- taskRunInteractionLogic(logicProps)- )+function TaskRunChatContent({ logicProps }: { logicProps: RunInteractionLogicProps }): JSX.Element {+ const { draft, isSubmitting, queuedMessages } = useValues(runInteractionLogic(logicProps))+ const { setDraft, submit, updateQueuedMessage, removeQueuedMessage } = useActions(runInteractionLogic(logicProps))return (- <SandboxRunViewer+ <RunViewertaskId={logicProps.taskId}runId={logicProps.runId}interaction="live"