Skip to content

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

chore(phai): make agent-run surface composable and Max-free (#66141)

Georgiy Tarasova15fce12462b
diff --git a/frontend/src/scenes/inbox/components/detail/AgentRunDetail.tsx b/frontend/src/scenes/inbox/components/detail/AgentRunDetail.tsx
index 2ad022ffdeaa..bdee5ddd78eb 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/sandbox'
+import { isTerminalRunStatus, SandboxRunViewer } from 'products/posthog_ai/frontend'
import { Task, TaskRunStatus } from 'products/tasks/frontend/types'
import { inboxReportDetailLogic } from '../../logics/inboxReportDetailLogic'
diff --git a/frontend/src/scenes/inbox/components/detail/ArtefactTaskRun.tsx b/frontend/src/scenes/inbox/components/detail/ArtefactTaskRun.tsx
index 5c57086ee33f..48eca2a5c47c 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/sandbox'
+import { isTerminalRunStatus, SandboxRunViewer } from 'products/posthog_ai/frontend'
import { Task, TaskRunStatus } from 'products/tasks/frontend/types'
import { isCustomAgentTaskRun, taskRunTypeLabel, TaskRunArtefactContent } from './artefactTypes'
diff --git a/frontend/src/scenes/inbox/components/detail/ReportTasksSection.tsx b/frontend/src/scenes/inbox/components/detail/ReportTasksSection.tsx
index f553aa60b706..295266f8b06f 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/sandbox'
+import { isTerminalRunStatus, SandboxRunViewer } from 'products/posthog_ai/frontend'
import { TaskRunStatus } from 'products/tasks/frontend/types'
import { inboxReportDetailLogic, ReportTaskEntry } from '../../logics/inboxReportDetailLogic'
diff --git a/frontend/src/scenes/max/AGENTS.md b/frontend/src/scenes/max/AGENTS.md
index 2d2495c4c77b..c6d38e6e41ac 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 coexisting
Per-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.ts` (SSE over products/tasks)
-- **Activity renderer**: `components/Activity/LangGraphActivity.tsx` → `components/Activity/SandboxActivity.tsx`
-- **Thread renderer**: `Thread.tsx` (default path) → `Thread.tsx` → `SandboxThread()`
+- **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`
- **Context shape**: rich `MaxUIContext` (full objects) → flat `AttachedContext` (typed refs, agent fetches)
-- **Approvals**: `DangerousOperationApprovalCard.tsx` / `approvalOperationUtils.ts` → `SandboxPermissionInput` / `SandboxQuestionInput`
-- **Tool widgets**: `messages/` + `messages/adapters/` → `sandboxToolRegistry` / `sandboxToolResolver`
+- **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`)
### Rule: do not extend the LangGraph path unless explicitly asked
@@ -32,71 +32,41 @@ New behavior — new tools, new context types, new UI affordances — goes on th
If a task genuinely needs the LangGraph path extended, confirm that intent explicitly before touching `maxThreadLogic.tsx`, `LangGraphActivity.tsx`, `max-constants.tsx` (`EnhancedToolCall`), the `MaxUIContext` half of `maxContextLogic.ts`, or `messages/` + `messages/adapters/`.
-## 2. Sandbox architecture (the new path)
+## 2. Sandbox architecture & conventions live with the surface
-`sandboxStreamLogic.ts` is the heart of the sandbox runtime:
+The sandbox runtime's heart — `sandboxStreamLogic` (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.
-- **SSE connection** — a `fetch` body reader pumped through `eventsource-parser`; a reconnect resumes after the last Redis stream id via `Last-Event-ID` (capped exponential backoff + healthy-connection forgiveness + cumulative cap).
-- **Ordered, append-only `log` is the single source of truth** — every wire frame (plus a few client-injected synthetic entries) is appended, never keyed or per-entry deduped.
-- **Pure projection** `foldLogToThread(entries) → { threadItems, toolInvocations }`, memoized on `log` identity, derives the rendered thread.
-- **Keyed by `streamKey`** (conversation id for Max, task id for a generic task viewer), so concurrent streams stay independent.
+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
+parsing wire frames in a Max component.
-**Lifecycle:** `bootstrapRun` (connect SSE → buffer live frames → read the S3 `logs/` snapshot → `dedupeBufferedAgainstHistory` drains the seam) → `ingestAcpFrame` appends + fires fire-once side effects → projection → `Thread.tsx`'s `SandboxThread()` renders `threadItems`, looking up `toolInvocations` by id.
+## 4. The sandbox surface lives in `products/posthog_ai/frontend`
-**Permissions:** parse (`parsePermissionRequestFrame`) → route (`sandboxToolPolicy.defaultPermissionDecision` auto-approves built-ins + read-only PostHog `exec`, else surfaces a card) → answer (`respondToPermission`) → resolve (clears the card, pins the id so a reconnect replay can't re-surface it).
+The conversation-agnostic sandbox run surface (stream logic, thread/tool/permission/composer components,
+policy, wire types) **no longer lives under `scenes/max`** — it's the composable PostHog AI agent-run
+library 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
+hard rule that it must never import `scenes/max`.
-**Supporting modules:** `sandboxToolPolicy`, `sandboxPermissionUtils`, `sandboxPermissionDisplayUtils`, `sandboxQuestionUtils`, `sandboxToolResolver`; types in `types/sandboxStreamTypes.ts` (folded thread shapes) + `types/sandboxWireTypes.ts` (ACP wire shapes + discriminant guards).
-
-**Wire types are loosely typed** (`notification.params` is `Record<string, unknown>`) — guard at the parse boundary with runtime `typeof`/shape checks; never assume a field is present because the type says so.
-
-## 3. Conventions for new sandbox code
-
-### Streaming/runtime logic stays in the logic, never in a component
-
-Wire parsing, log folding, SSE handling, telemetry, and permission routing belong in `sandboxStreamLogic` (or a sibling logic/util). Components **consume selectors and dispatch actions** — never parse ACP frames, hold SSE/connection state, or fold wire data in a component body.
-
-Selectors to consume: `threadItems`, `toolInvocations`, `isThinking`, `streamPhase`, `pendingPermissionRequest`, `respondingToPermission`, `contextUsage`, `resourcesUsed`.
-
-### Keep UI runtime-agnostic
-
-Render components take **plain props** — `ThreadItem`, `ToolInvocation`, `PermissionRequestRecord` — and know nothing about langgraph vs sandbox; this is what lets the legacy path be deleted later without touching shared UI. If a component must branch on runtime, branch **high** (in `Thread.tsx`, off `agent_runtime`) and pass resolved props down.
-
-### Atomic components
-
-One responsibility per component: extract each thread-item type into a **small leaf presenter**, not a giant inline `switch`/`map`. `SandboxThread()` in `Thread.tsx` (inline dispatch over 15+ item types) and the 1900-line `sandboxStreamLogic.ts` are anti-patterns to shrink, not extend.
-
-### Memoize — `threadItems` re-projects on every appended frame
-
-- Wrap leaf renderers in `React.memo`, keyed by the stable item `id`.
-- Derive per-item data with `useMemo`; wrap callbacks passed to children in `useCallback`.
-- **Subscribe narrowly** — select only what the component renders; pulling in unrelated selectors means an unrelated fold re-renders it.
-
-### Keep the projection pure
-
-`foldLogToThread` and its helpers must be **pure and deterministic** — item ids stay stable across re-folds. Never mutate thread/invocation state from a listener; derive everything in the projection. Listeners fire only **side effects** (telemetry, API calls), each with its own fire-once guard, suppressed on `source: 'replay'`.
-
-## 4. Target directory organization
-
-The `max/` root is a flat sprawl (~70 files) with sandbox code scattered across the root, `sandbox/`, `components/`, `components/Activity/`, and `types/`. **Do not big-bang-move on the active branch** — it conflicts with in-flight work. Follow this target layout incrementally: new sandbox files land in the right place; an existing file moves only when you're already editing it and the move is low-risk.
-
-Target `sandbox/` subtree:
-
-```text
-sandbox/
- sandboxStreamLogic.ts # stream logic + orchestration (+ .test, + generated *LogicType.ts)
- components/ # SandboxActivity, SandboxApproval, SandboxPermissionInput,
- # SandboxQuestionInput, SandboxResourcesBar, SandboxContextUsage,
- # SandboxThreadItems, SandboxQuestionRenderer
- policy/ # sandboxToolPolicy, sandboxPermissionUtils,
- # sandboxPermissionDisplayUtils, sandboxQuestionUtils
- types/ # sandboxStreamTypes, sandboxWireTypes
-```
+What stays in `scenes/max`: conversation orchestration (`maxLogic`, `maxThreadLogic`, `maxGlobalLogic`), the
+Max 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
+`Thread.tsx`). Add a new product tool renderer there, not in `products/posthog_ai/frontend`.
## 5. Where do I add X?
-- **A new thread-item type** → add to the `ThreadItem` union in `types/sandboxStreamTypes.ts`, handle it in `foldLogToThread`, and add a memoized leaf renderer wired into `SandboxThread()`.
-- **A new permission affordance / auto-approval rule** → `sandboxToolPolicy.ts`, then surface it through `SandboxPermissionInput`.
-- **New telemetry** → a guarded `posthog.capture` in the relevant `sandboxStreamLogic` listener (fire-once, suppressed on replay).
+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 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`).
## 6. Don'ts
diff --git a/frontend/src/scenes/max/FeedbackPrompt.tsx b/frontend/src/scenes/max/FeedbackPrompt.tsx
index be6e02274ab5..0439153dc181 100644
--- a/frontend/src/scenes/max/FeedbackPrompt.tsx
+++ b/frontend/src/scenes/max/FeedbackPrompt.tsx
@@ -8,7 +8,7 @@ import { LemonButton, LemonInput, LemonModal } from '@posthog/lemon-ui'
import { SupportForm } from 'lib/components/Support/SupportForm'
import { supportLogic } from 'lib/components/Support/supportLogic'
-import { MessageTemplate } from 'products/posthog_ai/frontend/sandbox/messages/MessageTemplate'
+import { MessageTemplate } from 'products/posthog_ai/frontend'
import { feedbackPromptLogic } from './feedbackPromptLogic'
import { captureFeedback } from './utils'
diff --git a/frontend/src/scenes/max/Thread.tsx b/frontend/src/scenes/max/Thread.tsx
index 6bd96cfe37c3..9610d060bb2a 100644
--- a/frontend/src/scenes/max/Thread.tsx
+++ b/frontend/src/scenes/max/Thread.tsx
@@ -1,3 +1,7 @@
+// 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.
+import './messages/adapters/registerMaxToolRenderers'
+
import clsx from 'clsx'
import { BindLogic, useActions, useValues } from 'kea'
import posthog from 'posthog-js'
@@ -64,15 +68,17 @@ import { DataVisualizationNode, InsightVizNode } from '~/queries/schema/schema-g
import { isDataVisualizationNode, isHogQLQuery } from '~/queries/utils'
import { PendingApproval, Region } from '~/types'
-import { SandboxContextUsage } from 'products/posthog_ai/frontend/sandbox/components/SandboxContextUsage'
-import { SandboxResourcesBar } from 'products/posthog_ai/frontend/sandbox/components/SandboxResourcesBar'
-import { SandboxThreadView } from 'products/posthog_ai/frontend/sandbox/components/SandboxThreadView'
-import { MarkdownMessage } from 'products/posthog_ai/frontend/sandbox/MarkdownMessage'
-import { AssistantFailureMessage } from 'products/posthog_ai/frontend/sandbox/messages/AssistantFailureMessage'
-import { MessageTemplate } from 'products/posthog_ai/frontend/sandbox/messages/MessageTemplate'
-import { ReasoningAnswer } from 'products/posthog_ai/frontend/sandbox/messages/ReasoningAnswer'
-import { sandboxStreamLogic } from 'products/posthog_ai/frontend/sandbox/sandboxStreamLogic'
-import { getThinkingMessageFromResponse } from 'products/posthog_ai/frontend/sandbox/utils/thinkingMessages'
+import {
+ AssistantFailureMessage,
+ getThinkingMessageFromResponse,
+ MarkdownMessage,
+ MessageTemplate,
+ ReasoningAnswer,
+ SandboxContextUsage,
+ SandboxResourcesBar,
+ sandboxStreamLogic,
+ SandboxThreadView,
+} from 'products/posthog_ai/frontend'
import { LogEntry } from 'products/tasks/frontend/lib/parse-logs'
import { LangGraphActivity, ShimmeringContent } from './components/Activity'
diff --git a/frontend/src/scenes/max/components/Activity/LangGraphActivity.tsx b/frontend/src/scenes/max/components/Activity/LangGraphActivity.tsx
index ae0e69f48dd5..419814a98fd0 100644
--- a/frontend/src/scenes/max/components/Activity/LangGraphActivity.tsx
+++ b/frontend/src/scenes/max/components/Activity/LangGraphActivity.tsx
@@ -4,8 +4,7 @@ import { CodeSnippet, Language } from 'lib/components/CodeSnippet/CodeSnippet'
import { TaskExecutionStatus as ExecutionStatus } from '~/queries/schema/schema-assistant-messages'
-import { Activity, ActivityToggleSection } from 'products/posthog_ai/frontend/sandbox/ActivityPrimitives'
-import { MarkdownMessage } from 'products/posthog_ai/frontend/sandbox/MarkdownMessage'
+import { Activity, ActivityToggleSection, MarkdownMessage } from 'products/posthog_ai/frontend'
import type { EnhancedToolCall } from '../../max-constants'
import { SummarizeSessionsWidget, UIPayloadAnswer, isRenderableUIPayloadTool } from '../../messages/UIPayloadAnswer'
diff --git a/frontend/src/scenes/max/components/Activity/index.ts b/frontend/src/scenes/max/components/Activity/index.ts
index f06b613e99dc..bb0a1b5c8ec1 100644
--- a/frontend/src/scenes/max/components/Activity/index.ts
+++ b/frontend/src/scenes/max/components/Activity/index.ts
@@ -5,8 +5,8 @@ export {
ActivityStatusIcon,
ActivitySubsteps,
ActivityToggleSection,
+ SandboxActivity,
ShimmeringContent,
-} from 'products/posthog_ai/frontend/sandbox/ActivityPrimitives'
-export type { ActivityStatus } from 'products/posthog_ai/frontend/sandbox/ActivityPrimitives'
+} from 'products/posthog_ai/frontend'
+export type { ActivityStatus } from 'products/posthog_ai/frontend'
export { LangGraphActivity } from './LangGraphActivity'
-export { SandboxActivity } from 'products/posthog_ai/frontend/sandbox/SandboxActivity'
diff --git a/frontend/src/scenes/max/components/InputFormArea.tsx b/frontend/src/scenes/max/components/InputFormArea.tsx
index f669f50df373..57455246de97 100644
--- a/frontend/src/scenes/max/components/InputFormArea.tsx
+++ b/frontend/src/scenes/max/components/InputFormArea.tsx
@@ -12,16 +12,17 @@ import {
} from '~/queries/schema/schema-assistant-messages'
import {
+ isFieldValid,
+ MarkdownMessage,
MultiFieldQuestion,
+ type Option,
+ OptionSelector,
QuestionField,
- isFieldValid,
-} from 'products/posthog_ai/frontend/sandbox/components/QuestionField'
-import { SandboxPermissionInput } from 'products/posthog_ai/frontend/sandbox/components/SandboxPermissionInput'
-import { SandboxQuestionInput } from 'products/posthog_ai/frontend/sandbox/components/SandboxQuestionInput'
-import { MarkdownMessage } from 'products/posthog_ai/frontend/sandbox/MarkdownMessage'
+ SandboxPermissionInput,
+ SandboxQuestionInput,
+} from 'products/posthog_ai/frontend'
import { maxThreadLogic } from '../maxThreadLogic'
-import { Option, OptionSelector } from './OptionSelector'
function isQuestionComplete(
q: MultiQuestionFormQuestion,
diff --git a/frontend/src/scenes/max/components/MaxWebAnalyticsNudge.tsx b/frontend/src/scenes/max/components/MaxWebAnalyticsNudge.tsx
index 42ea44f7a7ca..efc6f82679c2 100644
--- a/frontend/src/scenes/max/components/MaxWebAnalyticsNudge.tsx
+++ b/frontend/src/scenes/max/components/MaxWebAnalyticsNudge.tsx
@@ -4,7 +4,7 @@ import { LemonButton } from '@posthog/lemon-ui'
import { iconForType } from '~/layout/panel-layout/ProjectTree/defaultTree'
-import { MessageTemplate } from 'products/posthog_ai/frontend/sandbox/messages/MessageTemplate'
+import { MessageTemplate } from 'products/posthog_ai/frontend'
import { maxWebAnalyticsNudgeLogic } from '../logics/maxWebAnalyticsNudgeLogic'
import { maxLogic, ThreadMessage } from '../maxLogic'
diff --git a/frontend/src/scenes/max/components/SandboxModeBadge.test.tsx b/frontend/src/scenes/max/components/SandboxModeBadge.test.tsx
new file mode 100644
index 000000000000..31aedfd382ca
--- /dev/null
+++ b/frontend/src/scenes/max/components/SandboxModeBadge.test.tsx
@@ -0,0 +1,49 @@
+import '@testing-library/jest-dom'
+
+import { cleanup, render, screen } from '@testing-library/react'
+import { useValues } from 'kea'
+
+import { SandboxModeBadge } from './InputFormArea'
+
+jest.mock('kea', () => ({
+ ...jest.requireActual('kea'),
+ useValues: jest.fn(),
+}))
+
+jest.mock('../maxThreadLogic', () => ({
+ maxThreadLogic: { __mock: 'maxThreadLogic' },
+}))
+
+describe('SandboxModeBadge', () => {
+ afterEach(() => {
+ cleanup()
+ jest.clearAllMocks()
+ })
+
+ it.each([
+ ['sandbox', 'plan', 'Plan mode'],
+ ['sandbox', 'default', 'Default mode'],
+ ])('renders the %s runtime in %s mode as a badge', (runtime, mode, label) => {
+ ;(useValues as jest.Mock).mockReturnValue({
+ conversation: { agent_runtime: runtime },
+ sandboxCurrentMode: mode,
+ })
+
+ render(<SandboxModeBadge />)
+
+ expect(screen.getByText(label)).toBeInTheDocument()
+ })
+
+ it.each([
+ ['no mode has been reported', 'sandbox', null],
+ ['the conversation is not sandbox-runtime', 'langgraph', 'plan'],
+ ])('renders nothing when %s', (_case, runtime, mode) => {
+ ;(useValues as jest.Mock).mockReturnValue({
+ conversation: { agent_runtime: runtime },
+ sandboxCurrentMode: mode,
+ })
+
+ const { container } = render(<SandboxModeBadge />)
+ expect(container).toBeEmptyDOMElement()
+ })
+})
diff --git a/frontend/src/scenes/max/maxThreadLogic.test.ts b/frontend/src/scenes/max/maxThreadLogic.test.ts
index af085bfd84d0..5fb09cdb1803 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/sandbox/sandboxStreamLogic'
+import { sandboxStreamLogic } from 'products/posthog_ai/frontend'
import { EnhancedToolCall, TOOL_DEFINITIONS } from './max-constants'
import { maxContextLogic } from './maxContextLogic'
diff --git a/frontend/src/scenes/max/maxThreadLogic.tsx b/frontend/src/scenes/max/maxThreadLogic.tsx
index 8ad80e6bf390..a712e610130d 100644
--- a/frontend/src/scenes/max/maxThreadLogic.tsx
+++ b/frontend/src/scenes/max/maxThreadLogic.tsx
@@ -65,11 +65,11 @@ import {
} from '~/types'
import {
- SANDBOX_INITIAL_PERMISSION_MODE,
+ getRandomThinkingMessage,
isTerminalRunStatus,
+ SANDBOX_INITIAL_PERMISSION_MODE,
sandboxStreamLogic,
-} from 'products/posthog_ai/frontend/sandbox/sandboxStreamLogic'
-import { getRandomThinkingMessage } from 'products/posthog_ai/frontend/sandbox/utils/thinkingMessages'
+} from 'products/posthog_ai/frontend'
import { LogEntry, parseLogEvent } from 'products/tasks/frontend/lib/parse-logs'
import { handsFreeLogic } from './handsFreeLogic'
diff --git a/frontend/src/scenes/max/maxTypes.ts b/frontend/src/scenes/max/maxTypes.ts
index 716cedcac2e6..4c9c8d6f0be2 100644
--- a/frontend/src/scenes/max/maxTypes.ts
+++ b/frontend/src/scenes/max/maxTypes.ts
@@ -245,7 +245,7 @@ export function isAgentMode(mode: unknown): mode is AgentMode {
// `SandboxToolCallMessage` 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/sandbox/types/sandboxToolTypes'
+export type { SandboxToolCallMessage } 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/MultiQuestionForm.tsx b/frontend/src/scenes/max/messages/MultiQuestionForm.tsx
index f940ba511699..94456294ecb1 100644
--- a/frontend/src/scenes/max/messages/MultiQuestionForm.tsx
+++ b/frontend/src/scenes/max/messages/MultiQuestionForm.tsx
@@ -2,7 +2,7 @@ import { IconCheck, IconX } from '@posthog/icons'
import { MultiQuestionForm as MultiQuestionFormType } from '~/queries/schema/schema-assistant-messages'
-import { MessageTemplate } from 'products/posthog_ai/frontend/sandbox/messages/MessageTemplate'
+import { MessageTemplate } from 'products/posthog_ai/frontend'
interface MultiQuestionFormRecapProps {
form: MultiQuestionFormType
diff --git a/frontend/src/scenes/max/messages/NotebookArtifactAnswer.tsx b/frontend/src/scenes/max/messages/NotebookArtifactAnswer.tsx
index 9648c6c8fad0..d07d52a4894e 100644
--- a/frontend/src/scenes/max/messages/NotebookArtifactAnswer.tsx
+++ b/frontend/src/scenes/max/messages/NotebookArtifactAnswer.tsx
@@ -35,8 +35,7 @@ import { NotebookArtifactContent } from '~/queries/schema/schema-assistant-messa
import { DataVisualizationNode, InsightVizNode, NodeKind } from '~/queries/schema/schema-general'
import { isFunnelsQuery, isHogQLQuery, isInsightVizNode } from '~/queries/utils'
-import { MarkdownMessage } from 'products/posthog_ai/frontend/sandbox/MarkdownMessage'
-import { MessageTemplate } from 'products/posthog_ai/frontend/sandbox/messages/MessageTemplate'
+import { MarkdownMessage, MessageTemplate } from 'products/posthog_ai/frontend'
import { MessageStatus } from '../maxLogic'
import { castAssistantQuery, visualizationTypeToQuery } from '../utils'
diff --git a/frontend/src/scenes/max/messages/UIPayloadAnswer.tsx b/frontend/src/scenes/max/messages/UIPayloadAnswer.tsx
index fc138b7d0164..a3cc9065aa61 100644
--- a/frontend/src/scenes/max/messages/UIPayloadAnswer.tsx
+++ b/frontend/src/scenes/max/messages/UIPayloadAnswer.tsx
@@ -31,7 +31,7 @@ import {
issueQueryOptionsLogic,
} from 'products/error_tracking/frontend/components/IssueQueryOptions/issueQueryOptionsLogic'
import { ERROR_TRACKING_SCENE_LOGIC_KEY } from 'products/error_tracking/frontend/scenes/ErrorTrackingScene/errorTrackingSceneLogic'
-import { MessageTemplate } from 'products/posthog_ai/frontend/sandbox/messages/MessageTemplate'
+import { MessageTemplate } from 'products/posthog_ai/frontend'
import { isDangerousOperationResponse, normalizeDangerousOperationResponse } from '../approvalOperationUtils'
import { DangerousOperationApprovalCard } from '../DangerousOperationApprovalCard'
diff --git a/frontend/src/scenes/max/messages/VisualizationWidget.tsx b/frontend/src/scenes/max/messages/VisualizationWidget.tsx
index fb3f142fd8af..958610f3bafd 100644
--- a/frontend/src/scenes/max/messages/VisualizationWidget.tsx
+++ b/frontend/src/scenes/max/messages/VisualizationWidget.tsx
@@ -24,7 +24,7 @@ import { QueryContext } from '~/queries/types'
import { isFunnelsQuery, isHogQLQuery, isInsightVizNode } from '~/queries/utils'
import { InsightShortId } from '~/types'
-import { MessageTemplate } from 'products/posthog_ai/frontend/sandbox/messages/MessageTemplate'
+import { MessageTemplate } from 'products/posthog_ai/frontend'
import { visualizationTypeToQuery } from '../utils'
diff --git a/frontend/src/scenes/max/messages/adapters/CreateInsightWidget.tsx b/frontend/src/scenes/max/messages/adapters/CreateInsightWidget.tsx
index 3827814f0794..07cc27a838bd 100644
--- a/frontend/src/scenes/max/messages/adapters/CreateInsightWidget.tsx
+++ b/frontend/src/scenes/max/messages/adapters/CreateInsightWidget.tsx
@@ -1,6 +1,4 @@
-import { GenericMcpToolRenderer } from 'products/posthog_ai/frontend/sandbox/components/tool/GenericMcpToolRenderer'
-import { SandboxDataToolRow } from 'products/posthog_ai/frontend/sandbox/components/tool/SandboxDataToolRow'
-import type { SandboxToolRendererProps } from 'products/posthog_ai/frontend/sandbox/sandboxToolRegistry'
+import { GenericMcpToolRenderer, SandboxDataToolRow, type SandboxToolRendererProps } from 'products/posthog_ai/frontend'
import { VisualizationWidget, getArtifactOpenTarget } from '../VisualizationWidget'
import { extractVisualizationArtifact } from './extractors'
diff --git a/frontend/src/scenes/max/messages/adapters/CreateNotebookWidget.test.tsx b/frontend/src/scenes/max/messages/adapters/CreateNotebookWidget.test.tsx
index f03e4b38ac67..1bc8c429b9df 100644
--- a/frontend/src/scenes/max/messages/adapters/CreateNotebookWidget.test.tsx
+++ b/frontend/src/scenes/max/messages/adapters/CreateNotebookWidget.test.tsx
@@ -1,7 +1,8 @@
-import {
- lookupSandboxToolRenderer,
- sandboxToolRegistry,
-} from 'products/posthog_ai/frontend/sandbox/sandboxToolRegistry'
+// Side-effect: Max registers its product tool renderers (incl. the notebook keys) into the shared
+// 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 type { SandboxToolCallMessage } from '../../maxTypes'
import { extractNotebook } from './CreateNotebookWidget'
diff --git a/frontend/src/scenes/max/messages/adapters/CreateNotebookWidget.tsx b/frontend/src/scenes/max/messages/adapters/CreateNotebookWidget.tsx
index b74fb078fbb0..d580a2e39a99 100644
--- a/frontend/src/scenes/max/messages/adapters/CreateNotebookWidget.tsx
+++ b/frontend/src/scenes/max/messages/adapters/CreateNotebookWidget.tsx
@@ -4,9 +4,7 @@ import { LemonButton } from '@posthog/lemon-ui'
import { IconOpenInNew } from 'lib/lemon-ui/icons'
import { urls } from 'scenes/urls'
-import { GenericMcpToolRenderer } from 'products/posthog_ai/frontend/sandbox/components/tool/GenericMcpToolRenderer'
-import { SandboxDataToolRow } from 'products/posthog_ai/frontend/sandbox/components/tool/SandboxDataToolRow'
-import type { SandboxToolRendererProps } from 'products/posthog_ai/frontend/sandbox/sandboxToolRegistry'
+import { GenericMcpToolRenderer, SandboxDataToolRow, type SandboxToolRendererProps } from 'products/posthog_ai/frontend'
/** The notebook fields the widget renders, pulled from the REST payload. */
export interface NotebookExtraction {
diff --git a/frontend/src/scenes/max/messages/adapters/ErrorTrackingWidget.tsx b/frontend/src/scenes/max/messages/adapters/ErrorTrackingWidget.tsx
index 0116288ef9c6..011d0473f95c 100644
--- a/frontend/src/scenes/max/messages/adapters/ErrorTrackingWidget.tsx
+++ b/frontend/src/scenes/max/messages/adapters/ErrorTrackingWidget.tsx
@@ -1,6 +1,4 @@
-import { GenericMcpToolRenderer } from 'products/posthog_ai/frontend/sandbox/components/tool/GenericMcpToolRenderer'
-import { SandboxDataToolRow } from 'products/posthog_ai/frontend/sandbox/components/tool/SandboxDataToolRow'
-import type { SandboxToolRendererProps } from 'products/posthog_ai/frontend/sandbox/sandboxToolRegistry'
+import { GenericMcpToolRenderer, SandboxDataToolRow, type SandboxToolRendererProps } from 'products/posthog_ai/frontend'
import { ErrorTrackingFiltersWidget } from '../UIPayloadAnswer'
import { extractErrorTrackingResponse } from './extractors'
diff --git a/frontend/src/scenes/max/messages/adapters/QueryWidget.tsx b/frontend/src/scenes/max/messages/adapters/QueryWidget.tsx
index 8565b6f32976..003a009d0e28 100644
--- a/frontend/src/scenes/max/messages/adapters/QueryWidget.tsx
+++ b/frontend/src/scenes/max/messages/adapters/QueryWidget.tsx
@@ -1,6 +1,4 @@
-import { GenericMcpToolRenderer } from 'products/posthog_ai/frontend/sandbox/components/tool/GenericMcpToolRenderer'
-import { SandboxDataToolRow } from 'products/posthog_ai/frontend/sandbox/components/tool/SandboxDataToolRow'
-import type { SandboxToolRendererProps } from 'products/posthog_ai/frontend/sandbox/sandboxToolRegistry'
+import { GenericMcpToolRenderer, SandboxDataToolRow, type SandboxToolRendererProps } from 'products/posthog_ai/frontend'
import { VisualizationWidget } from '../VisualizationWidget'
import { extractQueryResult } from './extractors'
diff --git a/frontend/src/scenes/max/messages/adapters/SearchSessionRecordingsWidget.tsx b/frontend/src/scenes/max/messages/adapters/SearchSessionRecordingsWidget.tsx
index 5970cd539d3b..283da4ca478d 100644
--- a/frontend/src/scenes/max/messages/adapters/SearchSessionRecordingsWidget.tsx
+++ b/frontend/src/scenes/max/messages/adapters/SearchSessionRecordingsWidget.tsx
@@ -1,6 +1,4 @@
-import { GenericMcpToolRenderer } from 'products/posthog_ai/frontend/sandbox/components/tool/GenericMcpToolRenderer'
-import { SandboxDataToolRow } from 'products/posthog_ai/frontend/sandbox/components/tool/SandboxDataToolRow'
-import type { SandboxToolRendererProps } from 'products/posthog_ai/frontend/sandbox/sandboxToolRegistry'
+import { GenericMcpToolRenderer, SandboxDataToolRow, type SandboxToolRendererProps } from 'products/posthog_ai/frontend'
import { RecordingsWidget } from '../UIPayloadAnswer'
import { extractRecordingFilters } from './extractors'
diff --git a/frontend/src/scenes/max/messages/adapters/UpsertDashboardWidget.tsx b/frontend/src/scenes/max/messages/adapters/UpsertDashboardWidget.tsx
index 6a6743df6a12..3c7d32d97889 100644
--- a/frontend/src/scenes/max/messages/adapters/UpsertDashboardWidget.tsx
+++ b/frontend/src/scenes/max/messages/adapters/UpsertDashboardWidget.tsx
@@ -4,9 +4,7 @@ import { LemonButton } from '@posthog/lemon-ui'
import { IconOpenInNew } from 'lib/lemon-ui/icons'
import { urls } from 'scenes/urls'
-import { GenericMcpToolRenderer } from 'products/posthog_ai/frontend/sandbox/components/tool/GenericMcpToolRenderer'
-import { SandboxDataToolRow } from 'products/posthog_ai/frontend/sandbox/components/tool/SandboxDataToolRow'
-import type { SandboxToolRendererProps } from 'products/posthog_ai/frontend/sandbox/sandboxToolRegistry'
+import { GenericMcpToolRenderer, SandboxDataToolRow, type SandboxToolRendererProps } from 'products/posthog_ai/frontend'
import { extractDashboard } from './extractors'
diff --git a/frontend/src/scenes/max/messages/adapters/registerMaxToolRenderers.test.ts b/frontend/src/scenes/max/messages/adapters/registerMaxToolRenderers.test.ts
new file mode 100644
index 000000000000..9323485a9f34
--- /dev/null
+++ b/frontend/src/scenes/max/messages/adapters/registerMaxToolRenderers.test.ts
@@ -0,0 +1,29 @@
+// 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
+// Renderer itself is an opaque chunk).
+import './registerMaxToolRenderers'
+
+import { sandboxToolRegistry } from 'products/posthog_ai/frontend'
+
+describe('registerMaxToolRenderers', () => {
+ it.each([
+ ['insight-create', 'Insight'],
+ ['insight-update', 'Insight'],
+ ['insight-get', 'Insight'],
+ ['create_insight', 'Insight'],
+ ['dashboard-create', 'Dashboard'],
+ ['upsert_dashboard', 'Dashboard'],
+ ['query-session-recordings-list', 'Session recordings'],
+ ['search_session_recordings', 'Session recordings'],
+ ['query-error-tracking-issues-list', 'Error tracking'],
+ ['search_error_tracking_issues', 'Error tracking'],
+ ['query-trends', 'Trends query'],
+ ['query-funnel', 'Funnel query'],
+ ['notebooks-create', 'Notebook'],
+ ['notebook-edit', 'Notebook'],
+ ])('registers %s into the shared registry with displayName "%s"', (key, displayName) => {
+ const entry = sandboxToolRegistry.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.tsx
new file mode 100644
index 000000000000..c21041a83667
--- /dev/null
+++ b/frontend/src/scenes/max/messages/adapters/registerMaxToolRenderers.tsx
@@ -0,0 +1,118 @@
+import { type ComponentType, lazy } from 'react'
+
+import {
+ IconDashboard,
+ IconFunnels,
+ IconGraph,
+ IconLifecycle,
+ IconLlmAnalytics,
+ IconNotebook,
+ IconPerson,
+ IconRetention,
+ IconRewindPlay,
+ IconStickiness,
+ IconTrends,
+ IconUserPaths,
+ IconWarning,
+} from '@posthog/icons'
+
+import { sandboxToolRegistry, type SandboxToolRendererProps } 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
+// 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.
+//
+// Renderers are code-split: each lazy() pulls its chunk on first use, not at registration time.
+const InsightRenderer = lazy(() => import('./CreateInsightWidget').then((m) => ({ default: m.CreateInsightWidget })))
+const DashboardRenderer = lazy(() =>
+ import('./UpsertDashboardWidget').then((m) => ({ default: m.UpsertDashboardWidget }))
+)
+const SessionRecordingsRenderer = lazy(() =>
+ import('./SearchSessionRecordingsWidget').then((m) => ({ default: m.SearchSessionRecordingsWidget }))
+)
+const ErrorTrackingRenderer = lazy(() =>
+ import('./ErrorTrackingWidget').then((m) => ({ default: m.ErrorTrackingWidget }))
+)
+const NotebookRenderer = lazy(() => import('./CreateNotebookWidget').then((m) => ({ default: m.CreateNotebookWidget })))
+const QueryRenderer = lazy(() => import('./QueryWidget').then((m) => ({ default: m.QueryWidget })))
+
+// The single-exec inner tool names exist in two conventions — hyphenated (the MCP yaml definitions) and
+// snake_case (legacy Max tools) — so we register both aliases where both are real tool names.
+function register(
+ keys: string[],
+ displayName: string,
+ icon: JSX.Element,
+ Renderer: ComponentType<SandboxToolRendererProps>
+): void {
+ for (const key of keys) {
+ sandboxToolRegistry.register({ key, displayName, icon, Renderer })
+ }
+}
+
+// --- Data tools: insight (create / update / read) ---
+register(
+ ['insight-create', 'insight-update', 'insight-get', 'create_insight'],
+ 'Insight',
+ <IconGraph />,
+ InsightRenderer
+)
+
+// --- Data tools: dashboard ---
+register(
+ ['dashboard-create', 'dashboard-update', 'upsert_dashboard'],
+ 'Dashboard',
+ <IconDashboard />,
+ DashboardRenderer
+)
+
+// --- Data tools: session recordings ---
+register(
+ ['query-session-recordings-list', 'search_session_recordings', 'filter_session_recordings'],
+ 'Session recordings',
+ <IconRewindPlay />,
+ SessionRecordingsRenderer
+)
+
+// --- Data tools: error tracking ---
+register(
+ [
+ 'query-error-tracking-issues-list',
+ 'query-error-tracking-issue',
+ 'query-error-tracking-issue-events',
+ 'search_error_tracking_issues',
+ 'filter_error_tracking_issues',
+ ],
+ 'Error tracking',
+ <IconWarning />,
+ ErrorTrackingRenderer
+)
+
+// --- Data tools: notebooks ---
+// The generated CRUD tools and the handwritten notebook-edit (the collab-safe content editor) all
+// return the same REST notebook payload.
+register(
+ ['notebooks-create', 'notebooks-partial-update', 'notebooks-retrieve', 'notebook-edit'],
+ 'Notebook',
+ <IconNotebook />,
+ NotebookRenderer
+)
+
+// --- Data tools: query wrappers (analytics/product queries executed inline by the agent) ---
+const QUERY_WRAPPER_TOOLS: { key: string; displayName: string; icon: JSX.Element }[] = [
+ { key: 'query-trends', displayName: 'Trends query', icon: <IconTrends /> },
+ { key: 'query-funnel', displayName: 'Funnel query', icon: <IconFunnels /> },
+ { key: 'query-retention', displayName: 'Retention query', icon: <IconRetention /> },
+ { key: 'query-stickiness', displayName: 'Stickiness query', icon: <IconStickiness /> },
+ { key: 'query-paths', displayName: 'Paths query', icon: <IconUserPaths /> },
+ { key: 'query-lifecycle', displayName: 'Lifecycle query', icon: <IconLifecycle /> },
+ { key: 'query-llm-traces-list', displayName: 'LLM traces', icon: <IconLlmAnalytics /> },
+ { key: 'query-trends-actors', displayName: 'Trends persons', icon: <IconPerson /> },
+ { key: 'query-lifecycle-actors', displayName: 'Lifecycle persons', icon: <IconPerson /> },
+ { 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 })
+}
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index c5d2de1f3f66..596be5681f13 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -308,7 +308,7 @@ importers:
version: 3.12.1
jest:
specifier: 'catalog:'
- version: 29.7.0(@types/[email protected])
oxfmt:
specifier: 'catalog:'
version: 0.35.0
@@ -363,7 +363,7 @@ importers:
version: 0.25.12
jest:
specifier: ^29.7.0
- version: 29.7.0
puppeteer:
specifier: 19.0.0
version: 19.0.0([email protected])
@@ -391,7 +391,7 @@ importers:
version: 29.5.14
jest:
specifier: ^29.7.0
- version: 29.7.0
common/storybook:
dependencies:
@@ -1854,7 +1854,7 @@ importers:
'@storybook/test-runner':
specifier: ^0.19.1
'@storybook/theming':
specifier: ^8.6.14
@@ -1875,7 +1875,7 @@ importers:
jest-image-snapshot:
specifier: ^6.4.0
- version: 6.4.0([email protected](@types/[email protected]))
storybook:
specifier: ^8.6.14
version: 8.6.18([email protected])
@@ -1991,7 +1991,7 @@ importers:
jest:
specifier: ^29.7.0
- version: 29.7.0(@types/[email protected])
typescript:
specifier: 6.0.3
version: 6.0.3
@@ -2844,7 +2844,7 @@ importers:
version: 14.6.1(@testing-library/[email protected])
jest:
specifier: ^29.7.0
- version: 29.7.0
kea-test-utils:
specifier: 'catalog:'
@@ -2964,7 +2964,7 @@ importers:
version: 14.6.1(@testing-library/[email protected])
jest:
specifier: ^29.7.0
- version: 29.7.0
products/data_modeling:
dependencies:
@@ -3539,7 +3539,7 @@ importers:
version: 3.1.3
jest:
specifier: '*'
- version: 29.7.0
kea:
specifier: 'catalog:'
version: 4.0.0-pre.5([email protected])
@@ -3802,6 +3802,9 @@ importers:
marked:
specifier: '*'
version: 17.0.4
+ monaco-editor:
+ specifier: ^0.55.1
+ version: 0.55.1
posthog-js:
specifier: 'catalog:'
version: 1.393.4
@@ -3811,6 +3814,9 @@ importers:
react-dom:
specifier: 18.3.1
version: 18.3.1([email protected])
+ react-intersection-observer:
+ specifier: ^9.5.3
+ version: 9.5.3([email protected])
react-window:
specifier: '*'
@@ -27258,6 +27264,41 @@ snapshots:
- supports-color
- ts-node
+ dependencies:
+ '@jest/console': 29.7.0
+ '@jest/reporters': 29.7.0
+ '@jest/test-result': 29.7.0
+ '@jest/transform': 29.7.0
+ '@jest/types': 29.6.3
+ '@types/node': 22.18.8
+ ansi-escapes: 4.3.2
+ chalk: 4.1.2
+ ci-info: 3.8.0
+ exit: 0.1.2
+ graceful-fs: 4.2.11
+ jest-changed-files: 29.7.0
+ jest-haste-map: 29.7.0
+ jest-message-util: 29.7.0
+ jest-regex-util: 29.6.3
+ jest-resolve: 29.7.0
+ jest-resolve-dependencies: 29.7.0
+ jest-runner: 29.7.0
+ jest-runtime: 29.7.0
+ jest-snapshot: 29.7.0
+ jest-util: 29.7.0
+ jest-validate: 29.7.0
+ jest-watcher: 29.7.0
+ micromatch: 4.0.8
+ pretty-format: 29.7.0
+ slash: 3.0.0
+ strip-ansi: 6.0.1
+ transitivePeerDependencies:
+ - babel-plugin-macros
+ - supports-color
+ - ts-node
+
dependencies:
'@jest/console': 29.7.0
@@ -27293,6 +27334,41 @@ snapshots:
- supports-color
- ts-node
+ dependencies:
+ '@jest/console': 29.7.0
+ '@jest/reporters': 29.7.0
+ '@jest/test-result': 29.7.0
+ '@jest/transform': 29.7.0
+ '@jest/types': 29.6.3
+ '@types/node': 22.18.8
+ ansi-escapes: 4.3.2
+ chalk: 4.1.2
+ ci-info: 3.8.0
+ exit: 0.1.2
+ graceful-fs: 4.2.11
+ jest-changed-files: 29.7.0
+ jest-haste-map: 29.7.0
+ jest-message-util: 29.7.0
+ jest-regex-util: 29.6.3
+ jest-resolve: 29.7.0
+ jest-resolve-dependencies: 29.7.0
+ jest-runner: 29.7.0
+ jest-runtime: 29.7.0
+ jest-snapshot: 29.7.0
+ jest-util: 29.7.0
+ jest-validate: 29.7.0
+ jest-watcher: 29.7.0
+ micromatch: 4.0.8
+ pretty-format: 29.7.0
+ slash: 3.0.0
+ strip-ansi: 6.0.1
+ transitivePeerDependencies:
+ - babel-plugin-macros
+ - supports-color
+ - ts-node
+
dependencies:
'@jest/console': 30.0.5
@@ -31786,7 +31862,7 @@ snapshots:
prettier: 3.6.2
storybook: 8.6.18([email protected])
dependencies:
'@babel/core': 7.29.0
'@babel/generator': 7.29.1
@@ -31800,14 +31876,14 @@ snapshots:
'@swc/core': 1.15.18
'@swc/jest': 0.2.37(@swc/[email protected])
expect-playwright: 0.8.0
- jest: 29.7.0(@types/[email protected])
jest-circus: 29.7.0
jest-environment-node: 29.7.0
jest-junit: 16.0.0
jest-runner: 29.7.0
jest-serializer-html: 7.1.0
- jest-watch-typeahead: 2.2.2([email protected](@types/[email protected]))
nyc: 15.1.0
playwright: 1.60.0
transitivePeerDependencies:
@@ -35599,13 +35675,13 @@ snapshots:
- supports-color
- ts-node
dependencies:
'@jest/types': 29.6.3
chalk: 4.1.2
exit: 0.1.2
graceful-fs: 4.2.11
- jest-config: 29.7.0(@types/[email protected])
jest-util: 29.7.0
prompts: 2.4.2
transitivePeerDependencies:
@@ -35629,13 +35705,13 @@ snapshots:
- supports-color
- ts-node
dependencies:
'@jest/types': 29.6.3
chalk: 4.1.2
exit: 0.1.2
graceful-fs: 4.2.11
- jest-config: 29.7.0(@types/[email protected])
jest-util: 29.7.0
prompts: 2.4.2
transitivePeerDependencies:
@@ -38857,16 +38933,16 @@ snapshots:
- supports-color
- ts-node
dependencies:
- '@jest/core': 29.7.0
'@jest/test-result': 29.7.0
'@jest/types': 29.6.3
chalk: 4.1.2
- create-jest: 29.7.0(@types/[email protected])
exit: 0.1.2
import-local: 3.2.0
- jest-config: 29.7.0(@types/[email protected])
jest-util: 29.7.0
jest-validate: 29.7.0
yargs: 17.7.2
@@ -38895,16 +38971,16 @@ snapshots:
- supports-color
- ts-node
dependencies:
- '@jest/core': 29.7.0
'@jest/test-result': 29.7.0
'@jest/types': 29.6.3
chalk: 4.1.2
- create-jest: 29.7.0(@types/[email protected])
exit: 0.1.2
import-local: 3.2.0
- jest-config: 29.7.0(@types/[email protected])
jest-util: 29.7.0
jest-validate: 29.7.0
yargs: 17.7.2
@@ -39044,6 +39120,37 @@ snapshots:
- babel-plugin-macros
- supports-color
+ dependencies:
+ '@babel/core': 7.29.0
+ '@jest/test-sequencer': 29.7.0
+ '@jest/types': 29.6.3
+ babel-jest: 29.7.0(@babel/[email protected])
+ chalk: 4.1.2
+ ci-info: 3.8.0
+ deepmerge: 4.3.1
+ glob: 7.2.3
+ graceful-fs: 4.2.11
+ jest-circus: 29.7.0
+ jest-environment-node: 29.7.0
+ jest-get-type: 29.6.3
+ jest-regex-util: 29.6.3
+ jest-resolve: 29.7.0
+ jest-runner: 29.7.0
+ jest-util: 29.7.0
+ jest-validate: 29.7.0
+ micromatch: 4.0.8
+ parse-json: 5.2.0
+ pretty-format: 29.7.0
+ slash: 3.0.0
+ strip-json-comments: 3.1.1
+ optionalDependencies:
+ '@types/node': 22.18.8
+ transitivePeerDependencies:
+ - babel-plugin-macros
+ - supports-color
+
dependencies:
'@babel/core': 7.29.0
@@ -39075,7 +39182,38 @@ snapshots:
- babel-plugin-macros
- supports-color
+ dependencies:
+ '@babel/core': 7.29.0
+ '@jest/test-sequencer': 29.7.0
+ '@jest/types': 29.6.3
+ babel-jest: 29.7.0(@babel/[email protected])
+ chalk: 4.1.2
+ ci-info: 3.8.0
+ deepmerge: 4.3.1
+ glob: 7.2.3
+ graceful-fs: 4.2.11
+ jest-circus: 29.7.0
+ jest-environment-node: 29.7.0
+ jest-get-type: 29.6.3
+ jest-regex-util: 29.6.3
+ jest-resolve: 29.7.0
+ jest-runner: 29.7.0
+ jest-util: 29.7.0
+ jest-validate: 29.7.0
+ micromatch: 4.0.8
+ parse-json: 5.2.0
+ pretty-format: 29.7.0
+ slash: 3.0.0
+ strip-json-comments: 3.1.1
+ optionalDependencies:
+ '@types/node': 22.18.8
+ transitivePeerDependencies:
+ - babel-plugin-macros
+ - supports-color
+
dependencies:
'@babel/core': 7.29.0
'@jest/test-sequencer': 29.7.0
@@ -39101,6 +39239,7 @@ snapshots:
strip-json-comments: 3.1.1
optionalDependencies:
'@types/node': 25.8.0
transitivePeerDependencies:
- babel-plugin-macros
- supports-color
@@ -39405,7 +39544,7 @@ snapshots:
optionalDependencies:
dependencies:
chalk: 4.1.2
get-stdin: 5.0.1
@@ -39416,7 +39555,7 @@ snapshots:
rimraf: 2.7.1
ssim.js: 3.5.0
optionalDependencies:
- jest: 29.7.0(@types/[email protected])
dependencies:
@@ -39562,10 +39701,10 @@ snapshots:
'@types/node': 22.18.8
jest-util: 30.0.5
dependencies:
expect-playwright: 0.8.0
- jest: 29.7.0(@types/[email protected])
jest-circus: 29.7.0
jest-environment-node: 29.7.0
jest-process-manager: 0.4.0
@@ -40001,11 +40140,11 @@ snapshots:
leven: 3.1.0
pretty-format: 30.0.5
dependencies:
ansi-escapes: 6.0.0
chalk: 5.6.2
- jest: 29.7.0(@types/[email protected])
jest-regex-util: 29.6.3
jest-watcher: 29.7.0
slash: 5.1.0
@@ -40100,12 +40239,12 @@ snapshots:
- supports-color
- ts-node
dependencies:
- '@jest/core': 29.7.0
'@jest/types': 29.6.3
import-local: 3.2.0
- jest-cli: 29.7.0(@types/[email protected])
transitivePeerDependencies:
- '@types/node'
- babel-plugin-macros
@@ -40124,12 +40263,12 @@ snapshots:
- supports-color
- ts-node
dependencies:
- '@jest/core': 29.7.0
'@jest/types': 29.6.3
import-local: 3.2.0
- jest-cli: 29.7.0(@types/[email protected])
transitivePeerDependencies:
- '@types/node'
- babel-plugin-macros
@@ -45819,6 +45958,27 @@ snapshots:
tslib: 2.8.1
typescript: 6.0.3
+ dependencies:
+ '@cspotcode/source-map-support': 0.8.1
+ '@tsconfig/node10': 1.0.9
+ '@tsconfig/node12': 1.0.11
+ '@tsconfig/node14': 1.0.3
+ '@tsconfig/node16': 1.0.3
+ '@types/node': 22.18.8
+ acorn: 8.15.0
+ acorn-walk: 8.3.2
+ arg: 4.1.3
+ create-require: 1.1.1
+ diff: 4.0.2
+ make-error: 1.3.6
+ typescript: 6.0.3
+ v8-compile-cache-lib: 3.0.1
+ yn: 3.1.1
+ optionalDependencies:
+ '@swc/core': 1.11.4
+ optional: true
+
dependencies:
'@cspotcode/source-map-support': 0.8.1
diff --git a/products/ai_observability/frontend/ConversationDisplay/TranscriptBubbleStream.tsx b/products/ai_observability/frontend/ConversationDisplay/TranscriptBubbleStream.tsx
index 9455f36d0a25..769ce1ebd6c7 100644
--- a/products/ai_observability/frontend/ConversationDisplay/TranscriptBubbleStream.tsx
+++ b/products/ai_observability/frontend/ConversationDisplay/TranscriptBubbleStream.tsx
@@ -5,7 +5,7 @@ import { IconChevronRight } from '@posthog/icons'
import { LemonMarkdown } from 'lib/lemon-ui/LemonMarkdown'
-import { MessageTemplate } from 'products/posthog_ai/frontend/sandbox/messages/MessageTemplate'
+import { MessageTemplate } from 'products/posthog_ai/frontend'
import { CompatMessage } from '../types'
import {
diff --git a/products/posthog_ai/frontend/AGENTS.md b/products/posthog_ai/frontend/AGENTS.md
new file mode 100644
index 000000000000..422f27fca9ab
--- /dev/null
+++ b/products/posthog_ai/frontend/AGENTS.md
@@ -0,0 +1,100 @@
+# PostHog AI agent-run surface — frontend guide
+
+This directory is the **composable PostHog AI agent-run UI**: a conversation-agnostic library of surfaces
+that render and drive an agent run (the streamed thread, tool cards, approvals, the composer). It is
+consumed by the Max scene (`frontend/src/scenes/max`), the Tasks product, and the signals inbox — and is
+meant 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.
+
+## 1. The public API is the barrel (`index.ts`)
+
+Every external consumer imports from `products/posthog_ai/frontend` (the barrel) — **never** from deep
+paths. The barrel is the contract; internal files can move freely behind it. The headline exports:
+
+- **`RunViewer`** — Radix-style compound for an embeddable run. `RunViewer.Root` binds the stream logic and
+ bootstraps 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.
+- **`Thread`** — Radix-style compound for the run thread. `Thread.Root` is the virtualized presenter; the
+ atoms `Thread.Message / .Markdown / .Reasoning / .Failure / .Activity / .ToolCall` are the same
+ presentational 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
+ Max-agnostic follow-up/queue interaction facade.
+- Tool rendering: **`sandboxToolRegistry`**, `lookupSandboxToolRenderer`, `GenericMcpToolRenderer`,
+ `SandboxToolActivity`, `SandboxDataToolRow`, `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
+
+This surface **couples to the tasks run API by design** (`products/tasks/frontend/generated/api`): a task +
+its run + the SSE stream together _are_ the agent-run surface. Importing the tasks run/stream/command API
+from the stream and interaction logics is expected.
+
+It must stay **free of the Max scene and conversation orchestration**. Do not import `scenes/max/*`,
+`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
+ viewer). 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
+ `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 that
+ never load Max (tasks, signals inbox) fall through to the generic card for those product keys — by design.
+- If Max needs something the surface doesn't express generically, **lift it to a generic prop/selector here
+ and 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`)
+
+The heart of the surface:
+
+- **SSE connection** — a `fetch` body reader pumped through `eventsource-parser`; a reconnect resumes after
+ the last Redis stream id via `Last-Event-ID` (capped exponential backoff + cumulative cap).
+- **Ordered, append-only `log` is the single source of truth** — every wire frame (plus a few synthetic
+ client entries) is appended, never keyed or per-entry deduped.
+- **Pure projection** `foldLogToThread(entries) → { threadItems, toolInvocations }`, memoized on `log`
+ identity, derives the rendered thread.
+- **Keyed by `streamKey`** so concurrent streams stay independent.
+
+**Permissions:** parse (`parsePermissionRequestFrame`) → route (`policy/sandboxToolPolicy` auto-approves
+built-ins + read-only PostHog `exec`, else surfaces a card) → answer (`respondToPermission`) → resolve (pins
+the 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
+loosely 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
+ and dispatch actions.
+- **Keep UI runtime-agnostic.** Render components take plain props (`ThreadItem`, `ToolInvocation`,
+ `PermissionRequestRecord`); they know nothing about langgraph vs sandbox or the conversation.
+- **Atomic components.** One responsibility per component — small memoized leaf presenters keyed by the
+ stable item `id`, not a giant inline switch.
+- **Memoize — `threadItems` re-projects on every appended frame.** Wrap leaves in `React.memo`, derive with
+ `useMemo`, wrap child callbacks in `useCallback`, and subscribe narrowly (select only what you render).
+- **Keep the projection pure.** `foldLogToThread` is pure and deterministic; item ids stay stable across
+ re-folds. Listeners fire only side effects, each with a fire-once guard, suppressed on `source: 'replay'`.
+
+## 5. Layout
+
+```text
+index.ts # public API barrel (the contract)
+components/ # RunViewer, Thread, Composer, permission/question/resource surfaces, activity, tool/
+ composer/ # the Composer compound
+ tool/ # tool registry + renderers (built-ins, generic MCP, EditDiffRenderer, diff/exec utils)
+logics/ # sandboxStreamLogic, taskRunInteractionLogic (+ generated *LogicType.ts)
+policy/ # tool policy + permission/question utils
+types/ # sandboxStreamTypes (folded thread), sandboxWireTypes (ACP), sandboxToolTypes
+messages/ # MessageTemplate, MarkdownMessage, ReasoningAnswer, AssistantFailureMessage
+utils/ # thinkingMessages
+generated/ # auto-generated API types (mcp_tools / docs_search) — do not edit by hand
+```
diff --git a/products/posthog_ai/frontend/CLAUDE.md b/products/posthog_ai/frontend/CLAUDE.md
new file mode 120000
index 000000000000..47dc3e3d863c
--- /dev/null
+++ b/products/posthog_ai/frontend/CLAUDE.md
@@ -0,0 +1 @@
+AGENTS.md
\ No newline at end of file
diff --git a/products/posthog_ai/frontend/sandbox/ActivityPrimitives.test.tsx b/products/posthog_ai/frontend/components/ActivityPrimitives.test.tsx
similarity index 100%
rename from products/posthog_ai/frontend/sandbox/ActivityPrimitives.test.tsx
rename to products/posthog_ai/frontend/components/ActivityPrimitives.test.tsx
diff --git a/products/posthog_ai/frontend/sandbox/ActivityPrimitives.tsx b/products/posthog_ai/frontend/components/ActivityPrimitives.tsx
similarity index 99%
rename from products/posthog_ai/frontend/sandbox/ActivityPrimitives.tsx
rename to products/posthog_ai/frontend/components/ActivityPrimitives.tsx
index ed87f47343bd..e20741210ee1 100644
--- a/products/posthog_ai/frontend/sandbox/ActivityPrimitives.tsx
+++ b/products/posthog_ai/frontend/components/ActivityPrimitives.tsx
@@ -4,7 +4,7 @@ import React, { useLayoutEffect, useState } from 'react'
import { IconCheck, IconChevronDown, IconChevronRight, IconX } from '@posthog/icons'
import { LemonButton, Spinner } from '@posthog/lemon-ui'
-import { MarkdownMessage } from './MarkdownMessage'
+import { MarkdownMessage } from '../messages/MarkdownMessage'
export type ActivityStatus = 'pending' | 'in_progress' | 'completed' | 'failed'
diff --git a/frontend/src/scenes/max/components/OptionSelector.tsx b/products/posthog_ai/frontend/components/OptionSelector.tsx
similarity index 100%
rename from frontend/src/scenes/max/components/OptionSelector.tsx
rename to products/posthog_ai/frontend/components/OptionSelector.tsx
diff --git a/products/posthog_ai/frontend/sandbox/components/QuestionField.test.tsx b/products/posthog_ai/frontend/components/QuestionField.test.tsx
similarity index 100%
rename from products/posthog_ai/frontend/sandbox/components/QuestionField.test.tsx
rename to products/posthog_ai/frontend/components/QuestionField.test.tsx
diff --git a/products/posthog_ai/frontend/sandbox/components/QuestionField.tsx b/products/posthog_ai/frontend/components/QuestionField.tsx
similarity index 99%
rename from products/posthog_ai/frontend/sandbox/components/QuestionField.tsx
rename to products/posthog_ai/frontend/components/QuestionField.tsx
index 3882d39ff1e8..83483d649ff7 100644
--- a/products/posthog_ai/frontend/sandbox/components/QuestionField.tsx
+++ b/products/posthog_ai/frontend/components/QuestionField.tsx
@@ -4,10 +4,11 @@ import { IconPlus } from '@posthog/icons'
import { LemonButton, LemonCheckbox, LemonInput, LemonSelect, LemonSwitch } from '@posthog/lemon-ui'
import { LemonSlider } from 'lib/lemon-ui/LemonSlider/LemonSlider'
-import { OptionSelector, type Option } from 'scenes/max/components/OptionSelector'
import type { MultiQuestionFormField, MultiQuestionFormQuestion } from '~/queries/schema/schema-assistant-messages'
+import { OptionSelector, type Option } from './OptionSelector'
+
interface QuestionFieldProps {
question: MultiQuestionFormQuestion
value: string | string[] | undefined
diff --git a/products/posthog_ai/frontend/sandbox/components/QueuedMessageList.stories.tsx b/products/posthog_ai/frontend/components/QueuedMessageList.stories.tsx
similarity index 95%
rename from products/posthog_ai/frontend/sandbox/components/QueuedMessageList.stories.tsx
rename to products/posthog_ai/frontend/components/QueuedMessageList.stories.tsx
index 4ef715257ab8..31a09a694946 100644
--- a/products/posthog_ai/frontend/sandbox/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 '../taskRunInteractionLogic'
+import type { QueuedMessage } from '../logics/taskRunInteractionLogic'
import { QueuedMessageList } from './QueuedMessageList'
// Logic-free and controlled — the story owns the queue and wires `onUpdate` / `onRemove`, exactly as the
diff --git a/products/posthog_ai/frontend/sandbox/components/QueuedMessageList.tsx b/products/posthog_ai/frontend/components/QueuedMessageList.tsx
similarity index 98%
rename from products/posthog_ai/frontend/sandbox/components/QueuedMessageList.tsx
rename to products/posthog_ai/frontend/components/QueuedMessageList.tsx
index c43738c8464a..9c7d36a05fc9 100644
--- a/products/posthog_ai/frontend/sandbox/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 '../taskRunInteractionLogic'
+import type { QueuedMessage } from '../logics/taskRunInteractionLogic'
interface QueuedMessageListProps {
messages: QueuedMessage[]
diff --git a/products/posthog_ai/frontend/sandbox/SandboxActivity.tsx b/products/posthog_ai/frontend/components/SandboxActivity.tsx
similarity index 100%
rename from products/posthog_ai/frontend/sandbox/SandboxActivity.tsx
rename to products/posthog_ai/frontend/components/SandboxActivity.tsx
diff --git a/products/posthog_ai/frontend/sandbox/components/SandboxApproval.test.tsx b/products/posthog_ai/frontend/components/SandboxApproval.test.tsx
similarity index 86%
rename from products/posthog_ai/frontend/sandbox/components/SandboxApproval.test.tsx
rename to products/posthog_ai/frontend/components/SandboxApproval.test.tsx
index 4b9c6559c79f..8f9d1a987bb2 100644
--- a/products/posthog_ai/frontend/sandbox/components/SandboxApproval.test.tsx
+++ b/products/posthog_ai/frontend/components/SandboxApproval.test.tsx
@@ -3,8 +3,6 @@ import '@testing-library/jest-dom'
import { cleanup, fireEvent, render, screen } from '@testing-library/react'
import { useActions, useValues } from 'kea'
-import { SandboxModeBadge } from 'scenes/max/components/InputFormArea'
-
import type { PermissionRequestRecord, ToolInvocation } from '../types/sandboxStreamTypes'
import { SandboxPermissionInput } from './SandboxPermissionInput'
@@ -19,16 +17,12 @@ jest.mock('use-resize-observer', () => () => ({
ref: { current: null },
}))
-jest.mock('scenes/max/maxThreadLogic', () => ({
- maxThreadLogic: { __mock: 'maxThreadLogic' },
-}))
-
-jest.mock('../sandboxStreamLogic', () => ({
+jest.mock('../logics/sandboxStreamLogic', () => ({
// Keyed logic — the component binds it with `sandboxStreamLogic({ streamKey })`.
sandboxStreamLogic: jest.fn(() => ({ __mock: 'sandboxStreamLogicInstance' })),
}))
-jest.mock('../MarkdownMessage', () => ({
+jest.mock('../messages/MarkdownMessage', () => ({
MarkdownMessage: ({ content }: { content: string }) => <div data-attr="markdown">{content}</div>,
}))
@@ -217,33 +211,4 @@ describe('Sandbox approval input area', () => {
expect(screen.getByText('Approve always')).toBeInTheDocument()
})
})
-
- describe('SandboxModeBadge', () => {
- it.each([
- ['sandbox', 'plan', 'Plan mode'],
- ['sandbox', 'default', 'Default mode'],
- ])('renders the %s runtime in %s mode as a badge', (runtime, mode, label) => {
- ;(useValues as jest.Mock).mockReturnValue({
- conversation: { agent_runtime: runtime },
- sandboxCurrentMode: mode,
- })
-
- render(<SandboxModeBadge />)
-
- expect(screen.getByText(label)).toBeInTheDocument()
- })
-
- it.each([
- ['no mode has been reported', 'sandbox', null],
- ['the conversation is not sandbox-runtime', 'langgraph', 'plan'],
- ])('renders nothing when %s', (_case, runtime, mode) => {
- ;(useValues as jest.Mock).mockReturnValue({
- conversation: { agent_runtime: runtime },
- sandboxCurrentMode: mode,
- })
-
- const { container } = render(<SandboxModeBadge />)
- expect(container).toBeEmptyDOMElement()
- })
- })
})
diff --git a/products/posthog_ai/frontend/sandbox/components/SandboxComposer.test.tsx b/products/posthog_ai/frontend/components/SandboxComposer.test.tsx
similarity index 100%
rename from products/posthog_ai/frontend/sandbox/components/SandboxComposer.test.tsx
rename to products/posthog_ai/frontend/components/SandboxComposer.test.tsx
diff --git a/products/posthog_ai/frontend/sandbox/components/SandboxComposer.tsx b/products/posthog_ai/frontend/components/SandboxComposer.tsx
similarity index 100%
rename from products/posthog_ai/frontend/sandbox/components/SandboxComposer.tsx
rename to products/posthog_ai/frontend/components/SandboxComposer.tsx
diff --git a/products/posthog_ai/frontend/sandbox/components/SandboxContextUsage.tsx b/products/posthog_ai/frontend/components/SandboxContextUsage.tsx
similarity index 97%
rename from products/posthog_ai/frontend/sandbox/components/SandboxContextUsage.tsx
rename to products/posthog_ai/frontend/components/SandboxContextUsage.tsx
index 68b0dad234ad..a7f330dfd818 100644
--- a/products/posthog_ai/frontend/sandbox/components/SandboxContextUsage.tsx
+++ b/products/posthog_ai/frontend/components/SandboxContextUsage.tsx
@@ -4,7 +4,7 @@ import { Tooltip } from '@posthog/lemon-ui'
import { humanFriendlyNumber } from 'lib/utils/numbers'
-import { sandboxStreamLogic } from '../sandboxStreamLogic'
+import { sandboxStreamLogic } from '../logics/sandboxStreamLogic'
/** Compact SVG ring showing the context-window fill percentage. */
function UsageRing({ percentage }: { percentage: number }): JSX.Element {
diff --git a/products/posthog_ai/frontend/sandbox/SandboxGitArtifacts.test.tsx b/products/posthog_ai/frontend/components/SandboxGitArtifacts.test.tsx
similarity index 100%
rename from products/posthog_ai/frontend/sandbox/SandboxGitArtifacts.test.tsx
rename to products/posthog_ai/frontend/components/SandboxGitArtifacts.test.tsx
diff --git a/products/posthog_ai/frontend/sandbox/components/SandboxPermissionInput.tsx b/products/posthog_ai/frontend/components/SandboxPermissionInput.tsx
similarity index 96%
rename from products/posthog_ai/frontend/sandbox/components/SandboxPermissionInput.tsx
rename to products/posthog_ai/frontend/components/SandboxPermissionInput.tsx
index d11463aece76..83628a4c741e 100644
--- a/products/posthog_ai/frontend/sandbox/components/SandboxPermissionInput.tsx
+++ b/products/posthog_ai/frontend/components/SandboxPermissionInput.tsx
@@ -7,10 +7,10 @@ import { CodeSnippet, Language } from 'lib/components/CodeSnippet'
import type { MultiQuestionFormQuestion } from '~/queries/schema/schema-assistant-messages'
-import { MarkdownMessage } from '../MarkdownMessage'
-import { getSandboxPermissionDisplay } from '../sandboxPermissionDisplayUtils'
-import { mapPermissionOptions, type ApprovalCardOption } from '../sandboxPermissionUtils'
-import { sandboxStreamLogic } from '../sandboxStreamLogic'
+import { sandboxStreamLogic } from '../logics/sandboxStreamLogic'
+import { MarkdownMessage } from '../messages/MarkdownMessage'
+import { getSandboxPermissionDisplay } from '../policy/sandboxPermissionDisplayUtils'
+import { mapPermissionOptions, type ApprovalCardOption } from '../policy/sandboxPermissionUtils'
import type { PermissionRequestRecord } from '../types/sandboxStreamTypes'
import { QuestionField } from './QuestionField'
diff --git a/products/posthog_ai/frontend/sandbox/SandboxPullRequestCard.tsx b/products/posthog_ai/frontend/components/SandboxPullRequestCard.tsx
similarity index 100%
rename from products/posthog_ai/frontend/sandbox/SandboxPullRequestCard.tsx
rename to products/posthog_ai/frontend/components/SandboxPullRequestCard.tsx
diff --git a/products/posthog_ai/frontend/sandbox/components/SandboxQuestionInput.test.tsx b/products/posthog_ai/frontend/components/SandboxQuestionInput.test.tsx
similarity index 98%
rename from products/posthog_ai/frontend/sandbox/components/SandboxQuestionInput.test.tsx
rename to products/posthog_ai/frontend/components/SandboxQuestionInput.test.tsx
index c53f89196d9b..ef83fc9fbe1f 100644
--- a/products/posthog_ai/frontend/sandbox/components/SandboxQuestionInput.test.tsx
+++ b/products/posthog_ai/frontend/components/SandboxQuestionInput.test.tsx
@@ -3,7 +3,7 @@ import '@testing-library/jest-dom'
import { cleanup, fireEvent, render, screen } from '@testing-library/react'
import { useActions, useValues } from 'kea'
-import type { SandboxQuestion } from '../sandboxQuestionUtils'
+import type { SandboxQuestion } from '../policy/sandboxQuestionUtils'
import type { PermissionRequestRecord, ToolInvocation } from '../types/sandboxStreamTypes'
import { SandboxQuestionInput } from './SandboxQuestionInput'
@@ -13,7 +13,7 @@ jest.mock('kea', () => ({
useValues: jest.fn(),
}))
-jest.mock('../sandboxStreamLogic', () => ({
+jest.mock('../logics/sandboxStreamLogic', () => ({
sandboxStreamLogic: jest.fn(() => ({ __mock: 'sandboxStreamLogicInstance' })),
}))
diff --git a/products/posthog_ai/frontend/sandbox/components/SandboxQuestionInput.tsx b/products/posthog_ai/frontend/components/SandboxQuestionInput.tsx
similarity index 98%
rename from products/posthog_ai/frontend/sandbox/components/SandboxQuestionInput.tsx
rename to products/posthog_ai/frontend/components/SandboxQuestionInput.tsx
index 417f8ca25051..ab0411567144 100644
--- a/products/posthog_ai/frontend/sandbox/components/SandboxQuestionInput.tsx
+++ b/products/posthog_ai/frontend/components/SandboxQuestionInput.tsx
@@ -6,8 +6,8 @@ import { LemonTag, Spinner } from '@posthog/lemon-ui'
import type { MultiQuestionFormQuestion } from '~/queries/schema/schema-assistant-messages'
-import { deriveQuestionOptionId, type SandboxQuestion } from '../sandboxQuestionUtils'
-import { sandboxStreamLogic } from '../sandboxStreamLogic'
+import { sandboxStreamLogic } from '../logics/sandboxStreamLogic'
+import { deriveQuestionOptionId, type SandboxQuestion } from '../policy/sandboxQuestionUtils'
import type { PermissionRequestRecord } from '../types/sandboxStreamTypes'
import { QuestionField } from './QuestionField'
diff --git a/products/posthog_ai/frontend/sandbox/SandboxQuestionRenderer.test.tsx b/products/posthog_ai/frontend/components/SandboxQuestionRenderer.test.tsx
similarity index 98%
rename from products/posthog_ai/frontend/sandbox/SandboxQuestionRenderer.test.tsx
rename to products/posthog_ai/frontend/components/SandboxQuestionRenderer.test.tsx
index da338cefa431..0069e243ecf7 100644
--- a/products/posthog_ai/frontend/sandbox/SandboxQuestionRenderer.test.tsx
+++ b/products/posthog_ai/frontend/components/SandboxQuestionRenderer.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/sandbox/types/sandboxToolTypes'
+import type { SandboxToolCallMessage } from 'products/posthog_ai/frontend/types/sandboxToolTypes'
import { SandboxQuestionRenderer } from './SandboxQuestionRenderer'
diff --git a/products/posthog_ai/frontend/sandbox/SandboxQuestionRenderer.tsx b/products/posthog_ai/frontend/components/SandboxQuestionRenderer.tsx
similarity index 88%
rename from products/posthog_ai/frontend/sandbox/SandboxQuestionRenderer.tsx
rename to products/posthog_ai/frontend/components/SandboxQuestionRenderer.tsx
index ca9db1c5d0bd..6711a063c03e 100644
--- a/products/posthog_ai/frontend/sandbox/SandboxQuestionRenderer.tsx
+++ b/products/posthog_ai/frontend/components/SandboxQuestionRenderer.tsx
@@ -1,14 +1,14 @@
import { IconAI } from '@posthog/icons'
-import { GenericMcpToolRenderer } from './components/tool/GenericMcpToolRenderer'
-import { SandboxToolActivity } from './components/tool/SandboxToolActivity'
-import { truncateText } from './components/tool/toolContentUtils'
import {
extractSandboxQuestionAnswer,
parseSandboxQuestionAnswers,
parseSandboxQuestions,
-} from './sandboxQuestionUtils'
-import type { SandboxToolRendererProps } from './sandboxToolRegistry'
+} from '../policy/sandboxQuestionUtils'
+import { GenericMcpToolRenderer } from './tool/GenericMcpToolRenderer'
+import { SandboxToolActivity } from './tool/SandboxToolActivity'
+import type { SandboxToolRendererProps } from './tool/sandboxToolRegistry'
+import { truncateText } from './tool/toolContentUtils'
/**
* Thread recap for the `AskUserQuestion` Claude built-in. The interactive answering happens in the
diff --git a/products/posthog_ai/frontend/sandbox/components/SandboxResourcesBar.tsx b/products/posthog_ai/frontend/components/SandboxResourcesBar.tsx
similarity index 95%
rename from products/posthog_ai/frontend/sandbox/components/SandboxResourcesBar.tsx
rename to products/posthog_ai/frontend/components/SandboxResourcesBar.tsx
index 655c7571774b..7d9e49b9b3cd 100644
--- a/products/posthog_ai/frontend/sandbox/components/SandboxResourcesBar.tsx
+++ b/products/posthog_ai/frontend/components/SandboxResourcesBar.tsx
@@ -2,8 +2,8 @@ import { useValues } from 'kea'
import { Tooltip } from '@posthog/lemon-ui'
+import { sandboxStreamLogic } from '../logics/sandboxStreamLogic'
import { resolveProductMeta } from '../messages/posthogProducts'
-import { sandboxStreamLogic } from '../sandboxStreamLogic'
/**
* Persistent "PostHog resources used" bar for sandbox conversations. Reads the session-cumulative
diff --git a/products/posthog_ai/frontend/sandbox/SandboxRunContext.tsx b/products/posthog_ai/frontend/components/SandboxRunContext.tsx
similarity index 100%
rename from products/posthog_ai/frontend/sandbox/SandboxRunContext.tsx
rename to products/posthog_ai/frontend/components/SandboxRunContext.tsx
diff --git a/products/posthog_ai/frontend/sandbox/components/SandboxRunViewer.test.tsx b/products/posthog_ai/frontend/components/SandboxRunViewer.test.tsx
similarity index 97%
rename from products/posthog_ai/frontend/sandbox/components/SandboxRunViewer.test.tsx
rename to products/posthog_ai/frontend/components/SandboxRunViewer.test.tsx
index b421c1a7eb03..794f7b352f4e 100644
--- a/products/posthog_ai/frontend/sandbox/components/SandboxRunViewer.test.tsx
+++ b/products/posthog_ai/frontend/components/SandboxRunViewer.test.tsx
@@ -3,7 +3,7 @@ import '@testing-library/jest-dom'
import { cleanup, render, screen } from '@testing-library/react'
import { useActions, useValues } from 'kea'
-import type { SandboxRunStatus } from '../sandboxStreamLogic'
+import type { SandboxRunStatus } from '../logics/sandboxStreamLogic'
import type { PermissionRequestRecord } from '../types/sandboxStreamTypes'
import { SandboxRunViewer } from './SandboxRunViewer'
@@ -14,7 +14,7 @@ jest.mock('kea', () => ({
useValues: jest.fn(),
}))
-jest.mock('../sandboxStreamLogic', () => ({
+jest.mock('../logics/sandboxStreamLogic', () => ({
sandboxStreamLogic: jest.fn(() => ({ __mock: 'sandboxStreamLogic' })),
isTerminalRunStatus: (status: string | null) =>
status != null && ['completed', 'failed', 'cancelled'].includes(status),
diff --git a/products/posthog_ai/frontend/components/SandboxRunViewer.tsx b/products/posthog_ai/frontend/components/SandboxRunViewer.tsx
new file mode 100644
index 000000000000..9273b6d402c7
--- /dev/null
+++ b/products/posthog_ai/frontend/components/SandboxRunViewer.tsx
@@ -0,0 +1,295 @@
+import { BindLogic, useActions, useValues } from 'kea'
+import { createContext, type ReactNode, useContext, useEffect } from 'react'
+
+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 { Composer } from './composer/Composer'
+import { QueuedMessageList } from './QueuedMessageList'
+import { SandboxContextUsage } from './SandboxContextUsage'
+import { SandboxPermissionInput } from './SandboxPermissionInput'
+import { SandboxQuestionInput } from './SandboxQuestionInput'
+import { SandboxResourcesBar } from './SandboxResourcesBar'
+import { SandboxThreadView } from './SandboxThreadView'
+
+export interface SandboxRunViewerProps {
+ taskId: string
+ runId: string
+ /** Stable logic key; defaults to `runId` (the run is the unit being viewed). */
+ streamKey?: string
+ /** Telemetry tag only — omit for conversation-less runs (automation, Slack, signals, PR-triggered). */
+ conversationId?: string
+ /**
+ * `'read-only'` (default) replays the persisted `logs/` snapshot once and never opens SSE — the safe
+ * choice for a static viewer. `'live'` streams an in-progress run over SSE (falling back to replay once
+ * terminal) and adds approvals/questions plus the follow-up composer. The mode is folded into the logic
+ * key, so a live and a read-only viewer of the same run can never share state.
+ */
+ interaction?: 'live' | 'read-only'
+ className?: string
+ /**
+ * Composer wiring — live mode only. Provide all of `composerValue`/`onComposerChange`/`onComposerSubmit`
+ * to render the follow-up composer; the consumer owns the draft and the send (this module never POSTs
+ * task commands itself). Omit to stream live without a composer.
+ */
+ composerValue?: string
+ onComposerChange?: (value: string) => void
+ onComposerSubmit?: () => void
+ composerLoading?: boolean
+ composerPlaceholder?: string
+ /**
+ * Editable "Up next" queue — live mode only, rendered above the composer when non-empty. Provide all
+ * three to surface staged follow-ups; the consumer owns the queue (this module never mutates it).
+ */
+ queuedMessages?: QueuedMessage[]
+ onUpdateQueuedMessage?: (id: string, content: string) => void
+ onRemoveQueuedMessage?: (id: string) => void
+}
+
+// --- Compound context -------------------------------------------------------------------------------
+// `RunViewer.Root` binds a `sandboxStreamLogic` 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`
+// (default slot order) or compose the slots themselves for a custom layout. State stays in the logic and
+// in the caller-owned composer/queue props — the slots are presentational.
+
+interface RunViewerContextValue {
+ /** Original run id passed to `bootstrapRun`. */
+ rawRunId: string
+ /** Logic key (used for child stream keys). */
+ runId: string
+ interaction: 'live' | 'read-only'
+ composer: {
+ value?: string
+ onChange?: (value: string) => void
+ onSubmit?: () => void
+ loading?: boolean
+ placeholder?: string
+ queuedMessages?: QueuedMessage[]
+ onUpdateQueuedMessage?: (id: string, content: string) => void
+ onRemoveQueuedMessage?: (id: string) => void
+ }
+}
+
+const RunViewerContext = createContext<RunViewerContextValue | null>(null)
+
+function useRunViewerContext(): RunViewerContextValue {
+ const ctx = useContext(RunViewerContext)
+ if (!ctx) {
+ throw new Error('RunViewer.* slots must be rendered inside <RunViewer.Root> (or <SandboxRunViewer>)')
+ }
+ return ctx
+}
+
+export interface RunViewerRootProps extends SandboxRunViewerProps {
+ /** 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
+ * the run, and provides the run/composer context the slots read. In `'read-only'` mode it replays the
+ * persisted `logs/` snapshot once — no SSE; in `'live'` mode it streams an in-progress run. Renders the
+ * given slot children, or the prepackaged default layout when none are supplied.
+ */
+function RunViewerRoot({
+ taskId,
+ runId,
+ streamKey,
+ conversationId,
+ interaction = 'read-only',
+ className,
+ composerValue,
+ onComposerChange,
+ onComposerSubmit,
+ composerLoading,
+ composerPlaceholder,
+ queuedMessages,
+ onUpdateQueuedMessage,
+ onRemoveQueuedMessage,
+ children,
+}: RunViewerRootProps): JSX.Element {
+ const replayOnly = interaction !== 'live'
+ const logicKey = streamKey ?? runId
+ return (
+ <BindLogic logic={sandboxStreamLogic} props={{ streamKey: logicKey, conversationId, replayOnly }}>
+ <RunViewerContext.Provider
+ value={{
+ rawRunId: runId,
+ runId: logicKey,
+ interaction,
+ composer: {
+ value: composerValue,
+ onChange: onComposerChange,
+ onSubmit: onComposerSubmit,
+ loading: composerLoading,
+ placeholder: composerPlaceholder,
+ queuedMessages,
+ onUpdateQueuedMessage,
+ onRemoveQueuedMessage,
+ },
+ }}
+ >
+ <RunViewerBootstrap taskId={taskId} />
+ {children ?? <DefaultRunViewerLayout className={className} />}
+ </RunViewerContext.Provider>
+ </BindLogic>
+ )
+}
+
+/** Drives the run bootstrap as a side effect; renders nothing. Kept separate so slots stay presentational. */
+function RunViewerBootstrap({ taskId }: { taskId: string }): null {
+ const { rawRunId, interaction } = useRunViewerContext()
+ const { bootstrapRun, reset } = useActions(sandboxStreamLogic)
+
+ useEffect(() => {
+ // Reset first so a reused instance (stable streamKey, changed run) replays/streams the new run
+ // cleanly; the bound logic keys read-only instances apart from any live stream of the same run.
+ // `interaction` is in the deps so a status transition (live → terminal) re-bootstraps the right
+ // mode — the bound logic re-keys on it, so `bootstrapRun`/`reset` are fresh references anyway.
+ reset()
+ bootstrapRun({ taskId, runId: rawRunId })
+ }, [taskId, rawRunId, interaction, bootstrapRun, reset])
+
+ return null
+}
+
+/** Thread slot: the streamed run thread, with a centered spinner during the first bootstrap. */
+function RunViewerThread(): JSX.Element {
+ const { bootstrapLoading, threadItems } = useValues(sandboxStreamLogic)
+ const showSpinner = bootstrapLoading && threadItems.length === 0
+ if (showSpinner) {
+ return (
+ <div className="flex justify-center py-8">
+ <Spinner className="text-2xl" />
+ </div>
+ )
+ }
+ // An error surfaces as a `handleStreamError` item folded into the thread, so it renders here too.
+ return <SandboxThreadView />
+}
+
+/**
+ * Prompt slot: the pending approval / question input. Follows the non-terminal precedence — a pending
+ * request replaces the composer — and renders nothing outside live mode or once the run is terminal.
+ */
+function RunViewerPrompt(): JSX.Element | null {
+ const { interaction, runId } = useRunViewerContext()
+ const { pendingPermissionRequest, currentRunStatus } = useValues(sandboxStreamLogic)
+ const showApproval = interaction === 'live' && !!pendingPermissionRequest && !isTerminalRunStatus(currentRunStatus)
+ if (!showApproval) {
+ return null
+ }
+ const isQuestion = !!pendingPermissionRequest!.questions && pendingPermissionRequest!.questions.length > 0
+ return (
+ <div className="border-t px-4 py-3">
+ {isQuestion ? (
+ <SandboxQuestionInput streamKey={runId} request={pendingPermissionRequest!} />
+ ) : (
+ <SandboxPermissionInput streamKey={runId} request={pendingPermissionRequest!} />
+ )}
+ </div>
+ )
+}
+
+/**
+ * Composer slot: the follow-up composer + editable "Up next" queue. Shows for any settled run status
+ * (active runs take a follow-up, terminal runs start a fresh run from the typed message); hidden during
+ * the `null` bootstrap window and whenever a permission/question prompt is pending. Renders nothing unless
+ * the caller supplied the composer wiring (value/onChange/onSubmit).
+ */
+function RunViewerComposer(): JSX.Element | null {
+ const { interaction, composer } = useRunViewerContext()
+ const { pendingPermissionRequest, currentRunStatus } = useValues(sandboxStreamLogic)
+ const hasComposer =
+ interaction === 'live' && !!composer.onSubmit && composer.onChange !== undefined && composer.value !== undefined
+ if (!hasComposer || pendingPermissionRequest || currentRunStatus === null) {
+ return null
+ }
+ const isRunTerminal = isTerminalRunStatus(currentRunStatus)
+ const { queuedMessages, onUpdateQueuedMessage, onRemoveQueuedMessage } = composer
+ return (
+ // Composed from the logic-free Composer.* primitives directly (rather than via SandboxComposer) so
+ // the run surface can slot its own footer/actions later. The wrapper keeps a stable `data-attr`.
+ <div data-attr="composer" className="border-t px-4 py-3">
+ <Composer.Root
+ value={composer.value!}
+ onChange={composer.onChange!}
+ onSubmit={composer.onSubmit!}
+ loading={composer.loading}
+ >
+ {queuedMessages && queuedMessages.length > 0 && onUpdateQueuedMessage && onRemoveQueuedMessage && (
+ <Composer.Banner>
+ <QueuedMessageList
+ messages={queuedMessages}
+ onUpdate={onUpdateQueuedMessage}
+ onRemove={onRemoveQueuedMessage}
+ />
+ </Composer.Banner>
+ )}
+ <Composer.Frame>
+ <Composer.Field>
+ <Composer.Placeholder>
+ {composer.placeholder ??
+ (isRunTerminal ? 'Send a message to start a new run…' : 'Send a follow-up message…')}
+ </Composer.Placeholder>
+ <Composer.Textarea data-attr="sandbox-composer-input" submitShortcut="cmd-enter" />
+ </Composer.Field>
+ </Composer.Frame>
+ <Composer.Submit data-attr="sandbox-composer-send" />
+ </Composer.Root>
+ </div>
+ )
+}
+
+/** Default prepackaged layout: thread, then (live only) resources, prompt, composer, and context usage. */
+function DefaultRunViewerLayout({ className }: { className?: string }): JSX.Element {
+ const { interaction } = useRunViewerContext()
+ if (interaction !== 'live') {
+ return (
+ <div className={cn('flex flex-col h-full min-h-0 w-full', className)}>
+ <RunViewerThread />
+ </div>
+ )
+ }
+ return (
+ <div className={cn('@container/thread flex flex-col h-full overflow-hidden', className)}>
+ <div className="flex-1 min-h-0">
+ <RunViewerThread />
+ </div>
+ <SandboxResourcesBar />
+ <RunViewerPrompt />
+ <RunViewerComposer />
+ <SandboxContextUsage />
+ </div>
+ )
+}
+
+/**
+ * Compound run surface. `RunViewer.Root` binds the stream logic and provides context; the slots
+ * (`RunViewer.Thread/.Prompt/.Composer/.Resources/.ContextUsage`) compose into a custom layout, or omit
+ * children for the prepackaged default. Prefer the `SandboxRunViewer` prepackaged component for the
+ * common embed; reach for the slots only when a surface needs to reorder or wrap the regions.
+ */
+export const RunViewer = Object.assign(RunViewerRoot, {
+ Root: RunViewerRoot,
+ Thread: RunViewerThread,
+ Prompt: RunViewerPrompt,
+ Composer: RunViewerComposer,
+ Resources: SandboxResourcesBar,
+ ContextUsage: SandboxContextUsage,
+})
+
+/**
+ * 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/sandbox/SandboxThreadItems.tsx b/products/posthog_ai/frontend/components/SandboxThreadItems.tsx
similarity index 97%
rename from products/posthog_ai/frontend/sandbox/SandboxThreadItems.tsx
rename to products/posthog_ai/frontend/components/SandboxThreadItems.tsx
index 821c7b09c00a..2b9af7a07c95 100644
--- a/products/posthog_ai/frontend/sandbox/SandboxThreadItems.tsx
+++ b/products/posthog_ai/frontend/components/SandboxThreadItems.tsx
@@ -4,7 +4,7 @@ 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/sandboxStreamTypes'
/** Inline `_posthog/status` item — a spinner while compacting, a generic status line otherwise. */
export function SandboxStatusItem({ item }: { item: ThreadItem }): JSX.Element {
diff --git a/products/posthog_ai/frontend/sandbox/components/SandboxThreadRow.tsx b/products/posthog_ai/frontend/components/SandboxThreadRow.tsx
similarity index 94%
rename from products/posthog_ai/frontend/sandbox/components/SandboxThreadRow.tsx
rename to products/posthog_ai/frontend/components/SandboxThreadRow.tsx
index d5b94d23a5c9..956a78cfc310 100644
--- a/products/posthog_ai/frontend/sandbox/components/SandboxThreadRow.tsx
+++ b/products/posthog_ai/frontend/components/SandboxThreadRow.tsx
@@ -4,18 +4,18 @@ import { IconWrench } from '@posthog/icons'
import { TaskExecutionStatus as ExecutionStatus } from '~/queries/schema/schema-assistant-messages'
-import type { SandboxToolCallMessage } from 'products/posthog_ai/frontend/sandbox/types/sandboxToolTypes'
+import type { SandboxToolCallMessage } from 'products/posthog_ai/frontend/types/sandboxToolTypes'
-import { MarkdownMessage } from '../MarkdownMessage'
+import { sandboxStreamLogic } from '../logics/sandboxStreamLogic'
import { AssistantFailureMessage } from '../messages/AssistantFailureMessage'
+import { MarkdownMessage } from '../messages/MarkdownMessage'
import { MessageTemplate } from '../messages/MessageTemplate'
import { ReasoningAnswer } from '../messages/ReasoningAnswer'
-import { SandboxActivity } from '../SandboxActivity'
-import { sandboxStreamLogic } from '../sandboxStreamLogic'
-import { SandboxCompactBoundaryItem, SandboxStatusItem, SandboxTaskNotificationItem } from '../SandboxThreadItems'
-import { resolveToolCall } from '../sandboxToolResolver'
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'
type ToolInvocations = typeof sandboxStreamLogic.values.toolInvocations
diff --git a/products/posthog_ai/frontend/sandbox/components/SandboxThreadView.tsx b/products/posthog_ai/frontend/components/SandboxThreadView.tsx
similarity index 97%
rename from products/posthog_ai/frontend/sandbox/components/SandboxThreadView.tsx
rename to products/posthog_ai/frontend/components/SandboxThreadView.tsx
index d3b0c3daac51..7f544dfe3978 100644
--- a/products/posthog_ai/frontend/sandbox/components/SandboxThreadView.tsx
+++ b/products/posthog_ai/frontend/components/SandboxThreadView.tsx
@@ -1,12 +1,12 @@
import { useValues } from 'kea'
import { memo, useCallback, useMemo } from 'react'
+import { sandboxStreamLogic } from '../logics/sandboxStreamLogic'
import { ReasoningAnswer } from '../messages/ReasoningAnswer'
-import { SandboxPullRequestCard } from '../SandboxPullRequestCard'
-import { SandboxRunContext } from '../SandboxRunContext'
-import { sandboxStreamLogic } from '../sandboxStreamLogic'
import type { ThreadItem } from '../types/sandboxStreamTypes'
import { getRandomThinkingMessage } from '../utils/thinkingMessages'
+import { SandboxPullRequestCard } from './SandboxPullRequestCard'
+import { SandboxRunContext } from './SandboxRunContext'
import { SandboxThreadRow } from './SandboxThreadRow'
import { VirtualizedThread } from './VirtualizedThread'
diff --git a/products/posthog_ai/frontend/components/Thread.tsx b/products/posthog_ai/frontend/components/Thread.tsx
new file mode 100644
index 000000000000..b58fb49770a3
--- /dev/null
+++ b/products/posthog_ai/frontend/components/Thread.tsx
@@ -0,0 +1,29 @@
+import { AssistantFailureMessage } from '../messages/AssistantFailureMessage'
+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'
+
+// 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
+// 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, {
+ /** The full streamed thread: virtualized rows + run-context header + thinking/PR footer. */
+ Root: SandboxThreadView,
+ /** Human/assistant message bubble wrapper. */
+ Message: MessageTemplate,
+ /** Markdown body renderer (used inside messages and activity details). */
+ Markdown: MarkdownMessage,
+ /** Extended-thinking / reasoning line (a bubble-free Activity card). */
+ Reasoning: ReasoningAnswer,
+ /** Error / crash message card. */
+ Failure: AssistantFailureMessage,
+ /** Progress / status activity card. */
+ Activity: Activity,
+ /** Tool-call card — resolves its renderer through the tool registry. */
+ ToolCall: SandboxToolCall,
+})
diff --git a/products/posthog_ai/frontend/sandbox/components/VirtualizedThread.tsx b/products/posthog_ai/frontend/components/VirtualizedThread.tsx
similarity index 100%
rename from products/posthog_ai/frontend/sandbox/components/VirtualizedThread.tsx
rename to products/posthog_ai/frontend/components/VirtualizedThread.tsx
diff --git a/products/posthog_ai/frontend/sandbox/components/composer/Composer.stories.tsx b/products/posthog_ai/frontend/components/composer/Composer.stories.tsx
similarity index 100%
rename from products/posthog_ai/frontend/sandbox/components/composer/Composer.stories.tsx
rename to products/posthog_ai/frontend/components/composer/Composer.stories.tsx
diff --git a/products/posthog_ai/frontend/sandbox/components/composer/Composer.test.tsx b/products/posthog_ai/frontend/components/composer/Composer.test.tsx
similarity index 100%
rename from products/posthog_ai/frontend/sandbox/components/composer/Composer.test.tsx
rename to products/posthog_ai/frontend/components/composer/Composer.test.tsx
diff --git a/products/posthog_ai/frontend/sandbox/components/composer/Composer.tsx b/products/posthog_ai/frontend/components/composer/Composer.tsx
similarity index 100%
rename from products/posthog_ai/frontend/sandbox/components/composer/Composer.tsx
rename to products/posthog_ai/frontend/components/composer/Composer.tsx
diff --git a/frontend/src/scenes/max/messages/adapters/EditDiffRenderer.test.tsx b/products/posthog_ai/frontend/components/tool/EditDiffRenderer.test.tsx
similarity index 98%
rename from frontend/src/scenes/max/messages/adapters/EditDiffRenderer.test.tsx
rename to products/posthog_ai/frontend/components/tool/EditDiffRenderer.test.tsx
index 270c29650dcb..67d25b27ec5d 100644
--- a/frontend/src/scenes/max/messages/adapters/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 '../../maxTypes'
+import type { SandboxToolCallMessage } from '../../types/sandboxToolTypes'
import { EditDiffRenderer } from './EditDiffRenderer'
// Monaco can't render in jsdom — stand it in for a marker that echoes the diff props we care about.
diff --git a/frontend/src/scenes/max/messages/adapters/EditDiffRenderer.tsx b/products/posthog_ai/frontend/components/tool/EditDiffRenderer.tsx
similarity index 88%
rename from frontend/src/scenes/max/messages/adapters/EditDiffRenderer.tsx
rename to products/posthog_ai/frontend/components/tool/EditDiffRenderer.tsx
index fbdfd0d83296..1e4a552d585f 100644
--- a/frontend/src/scenes/max/messages/adapters/EditDiffRenderer.tsx
+++ b/products/posthog_ai/frontend/components/tool/EditDiffRenderer.tsx
@@ -8,16 +8,11 @@ import MonacoDiffEditor from 'lib/components/MonacoDiffEditor'
import { themeLogic } from '~/layout/navigation-3000/themeLogic'
-import { GenericMcpToolRenderer } from 'products/posthog_ai/frontend/sandbox/components/tool/GenericMcpToolRenderer'
-import { SandboxFilePath } from 'products/posthog_ai/frontend/sandbox/components/tool/SandboxFilePath'
-import { SandboxToolActivity } from 'products/posthog_ai/frontend/sandbox/components/tool/SandboxToolActivity'
-import type { SandboxToolRendererProps } from 'products/posthog_ai/frontend/sandbox/sandboxToolRegistry'
-import {
- findAllDiffContent,
- getDiffStats,
- languageFromPath,
- type ToolCallDiffContent,
-} from 'products/posthog_ai/frontend/sandbox/toolDiffContent'
+import { GenericMcpToolRenderer } from './GenericMcpToolRenderer'
+import { SandboxFilePath } from './SandboxFilePath'
+import { SandboxToolActivity } from './SandboxToolActivity'
+import type { SandboxToolRendererProps } from './sandboxToolRegistry'
+import { findAllDiffContent, getDiffStats, languageFromPath, type ToolCallDiffContent } from './toolDiffContent'
// 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
diff --git a/products/posthog_ai/frontend/sandbox/components/tool/GenericMcpToolRenderer.tsx b/products/posthog_ai/frontend/components/tool/GenericMcpToolRenderer.tsx
similarity index 97%
rename from products/posthog_ai/frontend/sandbox/components/tool/GenericMcpToolRenderer.tsx
rename to products/posthog_ai/frontend/components/tool/GenericMcpToolRenderer.tsx
index a86a29357489..35d1b3d8df6d 100644
--- a/products/posthog_ai/frontend/sandbox/components/tool/GenericMcpToolRenderer.tsx
+++ b/products/posthog_ai/frontend/components/tool/GenericMcpToolRenderer.tsx
@@ -3,8 +3,8 @@ import { memo } from 'react'
import { IconWrench } from '@posthog/icons'
-import type { SandboxToolRendererProps } from '../../sandboxToolRegistry'
import { SandboxToolActivity } from './SandboxToolActivity'
+import type { SandboxToolRendererProps } from './sandboxToolRegistry'
import { compactInput, formatInput, getContentText, stripCodeFences } from './toolContentUtils'
import { ToolOutput } from './ToolOutput'
diff --git a/products/posthog_ai/frontend/sandbox/components/tool/SandboxDataToolRow.tsx b/products/posthog_ai/frontend/components/tool/SandboxDataToolRow.tsx
similarity index 93%
rename from products/posthog_ai/frontend/sandbox/components/tool/SandboxDataToolRow.tsx
rename to products/posthog_ai/frontend/components/tool/SandboxDataToolRow.tsx
index 0ec21a811347..83e82916e0e1 100644
--- a/products/posthog_ai/frontend/sandbox/components/tool/SandboxDataToolRow.tsx
+++ b/products/posthog_ai/frontend/components/tool/SandboxDataToolRow.tsx
@@ -1,7 +1,7 @@
import { type PropsWithChildren } from 'react'
-import type { SandboxToolRendererProps } from '../../sandboxToolRegistry'
import { SandboxToolActivity } from './SandboxToolActivity'
+import type { SandboxToolRendererProps } from './sandboxToolRegistry'
/**
* Shared shell for the data-tool adapters (insight, dashboard, recordings, query, error tracking,
diff --git a/products/posthog_ai/frontend/sandbox/components/tool/SandboxFilePath.tsx b/products/posthog_ai/frontend/components/tool/SandboxFilePath.tsx
similarity index 100%
rename from products/posthog_ai/frontend/sandbox/components/tool/SandboxFilePath.tsx
rename to products/posthog_ai/frontend/components/tool/SandboxFilePath.tsx
diff --git a/products/posthog_ai/frontend/sandbox/components/tool/SandboxToolActivity.test.tsx b/products/posthog_ai/frontend/components/tool/SandboxToolActivity.test.tsx
similarity index 98%
rename from products/posthog_ai/frontend/sandbox/components/tool/SandboxToolActivity.test.tsx
rename to products/posthog_ai/frontend/components/tool/SandboxToolActivity.test.tsx
index 7b22cf3b12d0..8457a08e4f5b 100644
--- a/products/posthog_ai/frontend/sandbox/components/tool/SandboxToolActivity.test.tsx
+++ b/products/posthog_ai/frontend/components/tool/SandboxToolActivity.test.tsx
@@ -2,7 +2,7 @@ import '@testing-library/jest-dom'
import { fireEvent, render, screen } from '@testing-library/react'
-import type { SandboxToolCallMessage } from 'products/posthog_ai/frontend/sandbox/types/sandboxToolTypes'
+import type { SandboxToolCallMessage } from 'products/posthog_ai/frontend/types/sandboxToolTypes'
import { SandboxToolActivity } from './SandboxToolActivity'
diff --git a/products/posthog_ai/frontend/sandbox/components/tool/SandboxToolActivity.tsx b/products/posthog_ai/frontend/components/tool/SandboxToolActivity.tsx
similarity index 95%
rename from products/posthog_ai/frontend/sandbox/components/tool/SandboxToolActivity.tsx
rename to products/posthog_ai/frontend/components/tool/SandboxToolActivity.tsx
index 76cbe5a43531..2ec89b2537c9 100644
--- a/products/posthog_ai/frontend/sandbox/components/tool/SandboxToolActivity.tsx
+++ b/products/posthog_ai/frontend/components/tool/SandboxToolActivity.tsx
@@ -2,10 +2,10 @@ import { type ReactNode } from 'react'
import { IconWarning, IconWrench } from '@posthog/icons'
-import type { SandboxToolCallMessage } from 'products/posthog_ai/frontend/sandbox/types/sandboxToolTypes'
+import type { SandboxToolCallMessage } from 'products/posthog_ai/frontend/types/sandboxToolTypes'
-import { Activity } from '../../ActivityPrimitives'
-import type { ActivityStatus } from '../../ActivityPrimitives'
+import { Activity } from '../ActivityPrimitives'
+import type { ActivityStatus } from '../ActivityPrimitives'
import { resolveToolCallStatus } from './toolContentUtils'
export interface SandboxToolActivityProps {
diff --git a/products/posthog_ai/frontend/sandbox/components/tool/SandboxToolCall.tsx b/products/posthog_ai/frontend/components/tool/SandboxToolCall.tsx
similarity index 92%
rename from products/posthog_ai/frontend/sandbox/components/tool/SandboxToolCall.tsx
rename to products/posthog_ai/frontend/components/tool/SandboxToolCall.tsx
index 16fd5cab4404..5c60a0d7db05 100644
--- a/products/posthog_ai/frontend/sandbox/components/tool/SandboxToolCall.tsx
+++ b/products/posthog_ai/frontend/components/tool/SandboxToolCall.tsx
@@ -1,8 +1,8 @@
import { Suspense, memo } from 'react'
-import type { SandboxToolCallMessage } from 'products/posthog_ai/frontend/sandbox/types/sandboxToolTypes'
+import type { SandboxToolCallMessage } from 'products/posthog_ai/frontend/types/sandboxToolTypes'
-import { lookupSandboxToolRenderer } from '../../sandboxToolRegistry'
+import { lookupSandboxToolRenderer } from './sandboxToolRegistry'
import { ToolCardSkeleton } from './ToolCardSkeleton'
export interface SandboxToolCallProps {
diff --git a/products/posthog_ai/frontend/sandbox/components/tool/ToolCardSkeleton.tsx b/products/posthog_ai/frontend/components/tool/ToolCardSkeleton.tsx
similarity index 100%
rename from products/posthog_ai/frontend/sandbox/components/tool/ToolCardSkeleton.tsx
rename to products/posthog_ai/frontend/components/tool/ToolCardSkeleton.tsx
diff --git a/products/posthog_ai/frontend/sandbox/components/tool/ToolOutput.tsx b/products/posthog_ai/frontend/components/tool/ToolOutput.tsx
similarity index 100%
rename from products/posthog_ai/frontend/sandbox/components/tool/ToolOutput.tsx
rename to products/posthog_ai/frontend/components/tool/ToolOutput.tsx
diff --git a/products/posthog_ai/frontend/sandbox/components/tool/builtinToolRenderers.test.tsx b/products/posthog_ai/frontend/components/tool/builtinToolRenderers.test.tsx
similarity index 99%
rename from products/posthog_ai/frontend/sandbox/components/tool/builtinToolRenderers.test.tsx
rename to products/posthog_ai/frontend/components/tool/builtinToolRenderers.test.tsx
index 85cffdbd8989..49df426a664c 100644
--- a/products/posthog_ai/frontend/sandbox/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/sandbox/types/sandboxToolTypes'
+import type { SandboxToolCallMessage } from 'products/posthog_ai/frontend/types/sandboxToolTypes'
import { BuiltinToolRenderer } from './builtinToolRenderers'
import { GenericMcpToolRenderer } from './GenericMcpToolRenderer'
diff --git a/products/posthog_ai/frontend/sandbox/components/tool/builtinToolRenderers.tsx b/products/posthog_ai/frontend/components/tool/builtinToolRenderers.tsx
similarity index 98%
rename from products/posthog_ai/frontend/sandbox/components/tool/builtinToolRenderers.tsx
rename to products/posthog_ai/frontend/components/tool/builtinToolRenderers.tsx
index 13e784f8bbc8..36eb220df1d2 100644
--- a/products/posthog_ai/frontend/sandbox/components/tool/builtinToolRenderers.tsx
+++ b/products/posthog_ai/frontend/components/tool/builtinToolRenderers.tsx
@@ -7,12 +7,11 @@ 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 { getPostHogExecDisplay } from '../../posthogExecDisplay'
-import type { SandboxToolRendererProps } from '../../sandboxToolRegistry'
-import { languageFromPath } from '../../toolDiffContent'
import { GenericMcpToolRenderer } from './GenericMcpToolRenderer'
+import { getPostHogExecDisplay } from './posthogExecDisplay'
import { SandboxFilePath } from './SandboxFilePath'
import { SandboxToolActivity } from './SandboxToolActivity'
+import type { SandboxToolRendererProps } from './sandboxToolRegistry'
import {
MAX_COMMAND_LENGTH,
MAX_URL_LENGTH,
@@ -27,6 +26,7 @@ import {
stripCodeFences,
truncateText,
} from './toolContentUtils'
+import { languageFromPath } from './toolDiffContent'
import { ToolOutput } from './ToolOutput'
function asString(value: unknown): string {
diff --git a/products/posthog_ai/frontend/sandbox/posthogExecDisplay.ts b/products/posthog_ai/frontend/components/tool/posthogExecDisplay.ts
similarity index 100%
rename from products/posthog_ai/frontend/sandbox/posthogExecDisplay.ts
rename to products/posthog_ai/frontend/components/tool/posthogExecDisplay.ts
diff --git a/products/posthog_ai/frontend/sandbox/sandboxToolRegistry.test.tsx b/products/posthog_ai/frontend/components/tool/sandboxToolRegistry.test.tsx
similarity index 76%
rename from products/posthog_ai/frontend/sandbox/sandboxToolRegistry.test.tsx
rename to products/posthog_ai/frontend/components/tool/sandboxToolRegistry.test.tsx
index 2a4bbcd1d086..f57a755c8c85 100644
--- a/products/posthog_ai/frontend/sandbox/sandboxToolRegistry.test.tsx
+++ b/products/posthog_ai/frontend/components/tool/sandboxToolRegistry.test.tsx
@@ -2,9 +2,9 @@ import '@testing-library/jest-dom'
import { render, screen } from '@testing-library/react'
-import type { SandboxToolCallMessage } from 'products/posthog_ai/frontend/sandbox/types/sandboxToolTypes'
+import type { SandboxToolCallMessage } from 'products/posthog_ai/frontend/types/sandboxToolTypes'
-import { SandboxToolCall } from './components/tool/SandboxToolCall'
+import { SandboxToolCall } from './SandboxToolCall'
import { lookupSandboxToolRenderer, sandboxToolRegistry } from './sandboxToolRegistry'
function makeMessage(overrides: Partial<SandboxToolCallMessage> = {}): SandboxToolCallMessage {
@@ -21,42 +21,21 @@ function makeMessage(overrides: Partial<SandboxToolCallMessage> = {}): SandboxTo
}
describe('sandboxToolRegistry', () => {
- // Renderers are lazy() chunks, so entry.Renderer is an opaque LazyExoticComponent — assert on the
- // stable metadata (key → displayName/icon) the registry contributes, not on renderer identity.
- const dataToolCases: [string, string][] = [
- ['insight-create', 'Insight'],
- ['insight-update', 'Insight'],
- ['insight-get', 'Insight'],
- ['create_insight', 'Insight'],
- ['dashboard-create', 'Dashboard'],
- ['dashboard-update', 'Dashboard'],
- ['upsert_dashboard', 'Dashboard'],
- ['query-session-recordings-list', 'Session recordings'],
- ['search_session_recordings', 'Session recordings'],
- ['filter_session_recordings', 'Session recordings'],
- ['query-error-tracking-issues-list', 'Error tracking'],
- ['search_error_tracking_issues', 'Error tracking'],
- ['filter_error_tracking_issues', 'Error tracking'],
- ['query-trends', 'Trends query'],
- ['query-funnel', 'Funnel query'],
- ['notebooks-create', 'Notebook'],
- ['notebook-edit', 'Notebook'],
- ]
-
- it.each(dataToolCases)('resolves %s to a registered entry with displayName "%s"', (key, displayName) => {
- const entry = sandboxToolRegistry.lookup(key)
- expect(entry).not.toBeNull()
- expect(entry?.displayName).toEqual(displayName)
- expect(lookupSandboxToolRenderer(key).displayName).toEqual(displayName)
- })
+ // 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 unknown / unregistered tool names unregistered, resolving to the key as displayName', () => {
+ it('leaves product-specific and unknown tool names unregistered, resolving to the key as displayName', () => {
expect(sandboxToolRegistry.lookup('mcp__user-installed__something')).toBeNull()
// The synthesized fallback uses the resolved key as its displayName.
expect(lookupSandboxToolRenderer('mcp__user-installed__something').displayName).toEqual(
'mcp__user-installed__something'
)
expect(lookupSandboxToolRenderer('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()
diff --git a/products/posthog_ai/frontend/sandbox/sandboxToolRegistry.tsx b/products/posthog_ai/frontend/components/tool/sandboxToolRegistry.tsx
similarity index 59%
rename from products/posthog_ai/frontend/sandbox/sandboxToolRegistry.tsx
rename to products/posthog_ai/frontend/components/tool/sandboxToolRegistry.tsx
index 14febd3951a6..13f2691f7323 100644
--- a/products/posthog_ai/frontend/sandbox/sandboxToolRegistry.tsx
+++ b/products/posthog_ai/frontend/components/tool/sandboxToolRegistry.tsx
@@ -2,34 +2,21 @@ import { type ComponentType, type LazyExoticComponent, lazy } from 'react'
import {
IconAI,
- IconDashboard,
IconDocument,
IconEye,
- IconFunnels,
IconGlobe,
- IconGraph,
- IconLifecycle,
IconListCheck,
- IconLlmAnalytics,
IconMagicWand,
- IconNotebook,
IconPencil,
- IconPerson,
- IconRetention,
- IconRewindPlay,
IconSearch,
- IconStickiness,
IconTerminal,
- IconTrends,
- IconUserPaths,
- IconWarning,
IconWrench,
} from '@posthog/icons'
// 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/sandbox/types/sandboxToolTypes'
+import type { SandboxToolCallMessage } from 'products/posthog_ai/frontend/types/sandboxToolTypes'
export interface SandboxToolRendererProps {
message: SandboxToolCallMessage
@@ -88,33 +75,11 @@ class MapBackedRegistry implements SandboxToolRegistry {
// and the generic MCP card share one chunk (`builtinToolRenderers`); each heavy data-tool adapter and
// the Monaco-backed diff renderer stay in their own chunks.
const BuiltinToolRenderer = lazy(() =>
- import('./components/tool/builtinToolRenderers').then((m) => ({ default: m.BuiltinToolRenderer }))
-)
-const EditToolRenderer = lazy(() =>
- import('scenes/max/messages/adapters/EditDiffRenderer').then((m) => ({ default: m.EditDiffRenderer }))
-)
-const InsightRenderer = lazy(() =>
- import('scenes/max/messages/adapters/CreateInsightWidget').then((m) => ({ default: m.CreateInsightWidget }))
-)
-const DashboardRenderer = lazy(() =>
- import('scenes/max/messages/adapters/UpsertDashboardWidget').then((m) => ({ default: m.UpsertDashboardWidget }))
-)
-const SessionRecordingsRenderer = lazy(() =>
- import('scenes/max/messages/adapters/SearchSessionRecordingsWidget').then((m) => ({
- default: m.SearchSessionRecordingsWidget,
- }))
-)
-const ErrorTrackingRenderer = lazy(() =>
- import('scenes/max/messages/adapters/ErrorTrackingWidget').then((m) => ({ default: m.ErrorTrackingWidget }))
-)
-const NotebookRenderer = lazy(() =>
- import('scenes/max/messages/adapters/CreateNotebookWidget').then((m) => ({ default: m.CreateNotebookWidget }))
-)
-const QueryRenderer = lazy(() =>
- import('scenes/max/messages/adapters/QueryWidget').then((m) => ({ default: m.QueryWidget }))
+ 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 }))
+ import('../SandboxQuestionRenderer').then((m) => ({ default: m.SandboxQuestionRenderer }))
)
/**
@@ -124,86 +89,10 @@ const QuestionRenderer = lazy(() =>
*/
export const sandboxToolRegistry: SandboxToolRegistry = new MapBackedRegistry()
-// Custom adapters are registered here as they land. The single-exec inner tool names exist in two
-// conventions — hyphenated (the MCP yaml definitions) and snake_case (legacy Max tools) — so we
-// register both aliases where both are real tool names.
-
-// --- Data tools: insight ---
-// VisualizationWidget renderer — create / update / read insight.
-for (const key of ['insight-create', 'insight-update', 'insight-get', 'create_insight']) {
- sandboxToolRegistry.register({
- key,
- displayName: 'Insight',
- icon: <IconGraph />,
- Renderer: InsightRenderer,
- })
-}
-
-// --- Data tools: dashboard ---
-for (const key of ['dashboard-create', 'dashboard-update', 'upsert_dashboard']) {
- sandboxToolRegistry.register({
- key,
- displayName: 'Dashboard',
- icon: <IconDashboard />,
- Renderer: DashboardRenderer,
- })
-}
-
-// --- Data tools: session recordings ---
-for (const key of ['query-session-recordings-list', 'search_session_recordings', 'filter_session_recordings']) {
- sandboxToolRegistry.register({
- key,
- displayName: 'Session recordings',
- icon: <IconRewindPlay />,
- Renderer: SessionRecordingsRenderer,
- })
-}
-
-// --- Data tools: error tracking ---
-for (const key of [
- 'query-error-tracking-issues-list',
- 'query-error-tracking-issue',
- 'query-error-tracking-issue-events',
- 'search_error_tracking_issues',
- 'filter_error_tracking_issues',
-]) {
- sandboxToolRegistry.register({
- key,
- displayName: 'Error tracking',
- icon: <IconWarning />,
- Renderer: ErrorTrackingRenderer,
- })
-}
-
-// --- Data tools: notebooks ---
-// The generated CRUD tools and the handwritten notebook-edit (the collab-safe content editor)
-// all return the same REST notebook payload.
-for (const key of ['notebooks-create', 'notebooks-partial-update', 'notebooks-retrieve', 'notebook-edit']) {
- sandboxToolRegistry.register({
- key,
- displayName: 'Notebook',
- icon: <IconNotebook />,
- Renderer: NotebookRenderer,
- })
-}
-
-// --- Data tools: query wrappers ---
-// VisualizationWidget renderer — analytics and product queries executed inline by the agent.
-const QUERY_WRAPPER_TOOLS: { key: string; displayName: string; icon: JSX.Element }[] = [
- { key: 'query-trends', displayName: 'Trends query', icon: <IconTrends /> },
- { key: 'query-funnel', displayName: 'Funnel query', icon: <IconFunnels /> },
- { key: 'query-retention', displayName: 'Retention query', icon: <IconRetention /> },
- { key: 'query-stickiness', displayName: 'Stickiness query', icon: <IconStickiness /> },
- { key: 'query-paths', displayName: 'Paths query', icon: <IconUserPaths /> },
- { key: 'query-lifecycle', displayName: 'Lifecycle query', icon: <IconLifecycle /> },
- { key: 'query-llm-traces-list', displayName: 'LLM traces', icon: <IconLlmAnalytics /> },
- { key: 'query-trends-actors', displayName: 'Trends persons', icon: <IconPerson /> },
- { key: 'query-lifecycle-actors', displayName: 'Lifecycle persons', icon: <IconPerson /> },
- { 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 })
-}
+// 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
+// into this registry via `registerMaxToolRenderers` so this surface stays free of any scenes/max import.
+// Surfaces without those adapters (tasks, signals inbox) fall through to the generic MCP card.
// --- Claude built-in tools ---
// Keyed by the stable SDK tool name (reachable via `_meta.claudeCode.toolName`). Bash/Read/Search/Web
diff --git a/products/posthog_ai/frontend/sandbox/sandboxToolResolver.test.ts b/products/posthog_ai/frontend/components/tool/sandboxToolResolver.test.ts
similarity index 100%
rename from products/posthog_ai/frontend/sandbox/sandboxToolResolver.test.ts
rename to products/posthog_ai/frontend/components/tool/sandboxToolResolver.test.ts
diff --git a/products/posthog_ai/frontend/sandbox/sandboxToolResolver.ts b/products/posthog_ai/frontend/components/tool/sandboxToolResolver.ts
similarity index 100%
rename from products/posthog_ai/frontend/sandbox/sandboxToolResolver.ts
rename to products/posthog_ai/frontend/components/tool/sandboxToolResolver.ts
diff --git a/products/posthog_ai/frontend/sandbox/components/tool/toolContentUtils.test.ts b/products/posthog_ai/frontend/components/tool/toolContentUtils.test.ts
similarity index 100%
rename from products/posthog_ai/frontend/sandbox/components/tool/toolContentUtils.test.ts
rename to products/posthog_ai/frontend/components/tool/toolContentUtils.test.ts
diff --git a/products/posthog_ai/frontend/sandbox/components/tool/toolContentUtils.ts b/products/posthog_ai/frontend/components/tool/toolContentUtils.ts
similarity index 99%
rename from products/posthog_ai/frontend/sandbox/components/tool/toolContentUtils.ts
rename to products/posthog_ai/frontend/components/tool/toolContentUtils.ts
index a2826e790bf0..cf92fb42abc5 100644
--- a/products/posthog_ai/frontend/sandbox/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/sandbox/types/sandboxToolTypes'
+import type { SandboxToolCallMessage } from 'products/posthog_ai/frontend/types/sandboxToolTypes'
/** Compact single-line preview length for a generic MCP tool's input JSON. */
export const INPUT_PREVIEW_MAX_LENGTH = 60
diff --git a/products/posthog_ai/frontend/sandbox/toolDiffContent.test.ts b/products/posthog_ai/frontend/components/tool/toolDiffContent.test.ts
similarity index 100%
rename from products/posthog_ai/frontend/sandbox/toolDiffContent.test.ts
rename to products/posthog_ai/frontend/components/tool/toolDiffContent.test.ts
diff --git a/products/posthog_ai/frontend/sandbox/toolDiffContent.ts b/products/posthog_ai/frontend/components/tool/toolDiffContent.ts
similarity index 100%
rename from products/posthog_ai/frontend/sandbox/toolDiffContent.ts
rename to products/posthog_ai/frontend/components/tool/toolDiffContent.ts
diff --git a/products/posthog_ai/frontend/index.ts b/products/posthog_ai/frontend/index.ts
new file mode 100644
index 000000000000..5e89f3622d1e
--- /dev/null
+++ b/products/posthog_ai/frontend/index.ts
@@ -0,0 +1,95 @@
+// Public component API of the PostHog AI agent-run surface — the conversation-agnostic agent UI.
+// Every external consumer (tasks, the signals inbox, and the Max scene in scenes/max) imports from
+// THIS barrel, never from deep subtree paths, so the internal layout can move without touching them.
+//
+// Coupling boundary: this surface couples to the tasks run API (`products/tasks/frontend/generated/api`)
+// by design — task + taskrun + streaming together ARE the surface. It must never import the conversations
+// API or Max conversation orchestration (`scenes/max/*`, `maxThreadLogic`, `maxContextLogic`, `MaxUIContext`):
+// Max is a consumer of this surface, not a dependency of it.
+
+// --- 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'
+
+// --- Composer (Radix-style compound) ---
+export { Composer } from './components/composer/Composer'
+export type {
+ ComposerRootProps,
+ ComposerFrameProps,
+ ComposerTextareaProps,
+ ComposerSubmitProps,
+} from './components/composer/Composer'
+
+// --- 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`).
+export { Thread } from './components/Thread'
+export { SandboxThreadView } from './components/SandboxThreadView'
+export { MessageTemplate } from './messages/MessageTemplate'
+export { MarkdownMessage } from './messages/MarkdownMessage'
+export { ReasoningAnswer } from './messages/ReasoningAnswer'
+export type { ReasoningAnswerProps } from './messages/ReasoningAnswer'
+export { AssistantFailureMessage } from './messages/AssistantFailureMessage'
+
+// --- Activity primitives ---
+export {
+ Activity,
+ ActivityDetails,
+ ActivityHeader,
+ ActivityStatusIcon,
+ ActivitySubsteps,
+ ActivityToggleSection,
+ ShimmeringContent,
+} from './components/ActivityPrimitives'
+export type { ActivityStatus } from './components/ActivityPrimitives'
+export { SandboxActivity } from './components/SandboxActivity'
+
+// --- Tool rendering + registry ---
+export { sandboxToolRegistry, lookupSandboxToolRenderer } from './components/tool/sandboxToolRegistry'
+export type {
+ SandboxToolRendererProps,
+ SandboxToolRegistryEntry,
+ SandboxToolRegistry,
+} from './components/tool/sandboxToolRegistry'
+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 { findAllDiffContent, getDiffStats, languageFromPath } from './components/tool/toolDiffContent'
+export type { ToolCallDiffContent } from './components/tool/toolDiffContent'
+
+// --- Questions / multi-field forms ---
+export { QuestionField, MultiFieldQuestion, isFieldValid } from './components/QuestionField'
+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'
+
+// --- Permission / question / resource surfaces ---
+export { SandboxPermissionInput } from './components/SandboxPermissionInput'
+export { SandboxQuestionInput } from './components/SandboxQuestionInput'
+export { SandboxResourcesBar } from './components/SandboxResourcesBar'
+export { SandboxContextUsage } from './components/SandboxContextUsage'
+
+// --- Thinking-message helpers ---
+export { getThinkingMessageFromResponse, getRandomThinkingMessage, THINKING_MESSAGES } from './utils/thinkingMessages'
+
+// --- Types ---
+export type {
+ ThreadItem,
+ ToolInvocation,
+ PermissionRequestRecord,
+ ContextUsage,
+ RunArtifacts,
+ SandboxProgressStep,
+} from './types/sandboxStreamTypes'
+export type { SandboxToolCallMessage } from './types/sandboxToolTypes'
diff --git a/products/posthog_ai/frontend/sandbox/sandboxStreamLogic.test.ts b/products/posthog_ai/frontend/logics/sandboxStreamLogic.test.ts
similarity index 99%
rename from products/posthog_ai/frontend/sandbox/sandboxStreamLogic.test.ts
rename to products/posthog_ai/frontend/logics/sandboxStreamLogic.test.ts
index 9288cc65cabd..cbdbb95e5cf8 100644
--- a/products/posthog_ai/frontend/sandbox/sandboxStreamLogic.test.ts
+++ b/products/posthog_ai/frontend/logics/sandboxStreamLogic.test.ts
@@ -11,6 +11,7 @@ import { initKeaTests } from '~/test/init'
import { tasksRunsCommandCreate, tasksRunsStreamTokenRetrieve } from 'products/tasks/frontend/generated/api'
+import type { PermissionRequestFrame, StoredLogEntry } from '../types/sandboxWireTypes'
import {
extractRunArtifacts,
mapHttpStatusToStreamError,
@@ -26,7 +27,6 @@ import {
SSE_RECONNECT_BASE_DELAY_MS,
SSE_RECONNECT_MAX_DELAY_MS,
} from './sandboxStreamLogic'
-import type { PermissionRequestFrame, StoredLogEntry } from './types/sandboxWireTypes'
jest.mock('products/tasks/frontend/generated/api', () => ({
tasksRunsCommandCreate: jest.fn(),
diff --git a/products/posthog_ai/frontend/sandbox/sandboxStreamLogic.ts b/products/posthog_ai/frontend/logics/sandboxStreamLogic.ts
similarity index 99%
rename from products/posthog_ai/frontend/sandbox/sandboxStreamLogic.ts
rename to products/posthog_ai/frontend/logics/sandboxStreamLogic.ts
index 57acad04b808..d7252ac6f24e 100644
--- a/products/posthog_ai/frontend/sandbox/sandboxStreamLogic.ts
+++ b/products/posthog_ai/frontend/logics/sandboxStreamLogic.ts
@@ -12,10 +12,9 @@ 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 { parseSandboxQuestions } from './sandboxQuestionUtils'
-import type { sandboxStreamLogicType } from './sandboxStreamLogicType'
-import { defaultPermissionDecision, findAllowOptionId } from './sandboxToolPolicy'
-import { getClaudeCodeMeta, resolveToolCall } from './sandboxToolResolver'
+import { getClaudeCodeMeta, resolveToolCall } from '../components/tool/sandboxToolResolver'
+import { parseSandboxQuestions } from '../policy/sandboxQuestionUtils'
+import { defaultPermissionDecision, findAllowOptionId } from '../policy/sandboxToolPolicy'
import type {
ContextUsage,
PermissionRequestRecord,
@@ -28,7 +27,7 @@ import type {
ThreadItemType,
ToolInvocation,
ToolInvocationStatus,
-} from './types/sandboxStreamTypes'
+} from '../types/sandboxStreamTypes'
import {
type PermissionOption,
type PermissionRequestFrame,
@@ -46,7 +45,8 @@ import {
isSessionUpdateUsage,
isSessionUpdateUserMessage,
isTaskRunStateFrame,
-} from './types/sandboxWireTypes'
+} from '../types/sandboxWireTypes'
+import type { sandboxStreamLogicType } from './sandboxStreamLogicType'
export type SandboxSseStatus = 'idle' | 'connecting' | 'open' | 'reconnecting' | 'closed' | 'error'
export type SandboxRunStatus = 'queued' | 'in_progress' | 'completed' | 'failed' | 'cancelled'
@@ -1039,7 +1039,7 @@ export const sandboxStreamLogic = kea<sandboxStreamLogicType>([
// 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', 'sandbox', 'sandboxStreamLogic', key]),
+ path((key) => ['products', 'posthog_ai', 'frontend', 'logics', 'sandboxStreamLogic', key]),
connect(() => ({
values: [projectLogic, ['currentProjectId'], featureFlagLogic, ['featureFlags'], preflightLogic, ['preflight']],
})),
diff --git a/products/posthog_ai/frontend/sandbox/taskRunInteractionLogic.test.ts b/products/posthog_ai/frontend/logics/taskRunInteractionLogic.test.ts
similarity index 100%
rename from products/posthog_ai/frontend/sandbox/taskRunInteractionLogic.test.ts
rename to products/posthog_ai/frontend/logics/taskRunInteractionLogic.test.ts
diff --git a/products/posthog_ai/frontend/sandbox/taskRunInteractionLogic.ts b/products/posthog_ai/frontend/logics/taskRunInteractionLogic.ts
similarity index 99%
rename from products/posthog_ai/frontend/sandbox/taskRunInteractionLogic.ts
rename to products/posthog_ai/frontend/logics/taskRunInteractionLogic.ts
index 3bcbc4618a25..f5be40ba3662 100644
--- a/products/posthog_ai/frontend/sandbox/taskRunInteractionLogic.ts
+++ b/products/posthog_ai/frontend/logics/taskRunInteractionLogic.ts
@@ -40,7 +40,7 @@ const QUEUED_MESSAGE_ID = 'queued'
* conversation/Max coupling.
*/
export const taskRunInteractionLogic = kea<taskRunInteractionLogicType>([
- path(['products', 'posthog_ai', 'frontend', 'sandbox', 'taskRunInteractionLogic']),
+ path(['products', 'posthog_ai', 'frontend', 'logics', 'taskRunInteractionLogic']),
props({} as TaskRunInteractionLogicProps),
key((props) => props.runId),
diff --git a/products/posthog_ai/frontend/sandbox/messages/AssistantFailureMessage.test.tsx b/products/posthog_ai/frontend/messages/AssistantFailureMessage.test.tsx
similarity index 100%
rename from products/posthog_ai/frontend/sandbox/messages/AssistantFailureMessage.test.tsx
rename to products/posthog_ai/frontend/messages/AssistantFailureMessage.test.tsx
diff --git a/products/posthog_ai/frontend/sandbox/messages/AssistantFailureMessage.tsx b/products/posthog_ai/frontend/messages/AssistantFailureMessage.tsx
similarity index 87%
rename from products/posthog_ai/frontend/sandbox/messages/AssistantFailureMessage.tsx
rename to products/posthog_ai/frontend/messages/AssistantFailureMessage.tsx
index 46c8a9970ec1..0dace8304297 100644
--- a/products/posthog_ai/frontend/sandbox/messages/AssistantFailureMessage.tsx
+++ b/products/posthog_ai/frontend/messages/AssistantFailureMessage.tsx
@@ -1,11 +1,11 @@
import React from 'react'
-import { MarkdownMessage } from '../MarkdownMessage'
+import { MarkdownMessage } from './MarkdownMessage'
import { MessageTemplate } from './MessageTemplate'
const DEFAULT_FAILURE_MESSAGE = '*PostHog AI has failed to generate an answer. Please try again.*'
-interface AssistantFailureMessageProps {
+export interface AssistantFailureMessageProps {
id: string
content?: string | null
action?: React.ReactNode
diff --git a/products/posthog_ai/frontend/sandbox/MarkdownMessage.tsx b/products/posthog_ai/frontend/messages/MarkdownMessage.tsx
similarity index 100%
rename from products/posthog_ai/frontend/sandbox/MarkdownMessage.tsx
rename to products/posthog_ai/frontend/messages/MarkdownMessage.tsx
diff --git a/products/posthog_ai/frontend/sandbox/messages/MessageTemplate.tsx b/products/posthog_ai/frontend/messages/MessageTemplate.tsx
similarity index 97%
rename from products/posthog_ai/frontend/sandbox/messages/MessageTemplate.tsx
rename to products/posthog_ai/frontend/messages/MessageTemplate.tsx
index c1dcff03c80f..a7aa0ea326f4 100644
--- a/products/posthog_ai/frontend/sandbox/messages/MessageTemplate.tsx
+++ b/products/posthog_ai/frontend/messages/MessageTemplate.tsx
@@ -1,7 +1,7 @@
import React from 'react'
import { twMerge } from 'tailwind-merge'
-interface MessageTemplateProps {
+export interface MessageTemplateProps {
type: 'human' | 'ai'
action?: React.ReactNode
className?: string
diff --git a/products/posthog_ai/frontend/sandbox/messages/ReasoningAnswer.tsx b/products/posthog_ai/frontend/messages/ReasoningAnswer.tsx
similarity index 72%
rename from products/posthog_ai/frontend/sandbox/messages/ReasoningAnswer.tsx
rename to products/posthog_ai/frontend/messages/ReasoningAnswer.tsx
index 821b0f6ba682..486a4dea40d2 100644
--- a/products/posthog_ai/frontend/sandbox/messages/ReasoningAnswer.tsx
+++ b/products/posthog_ai/frontend/messages/ReasoningAnswer.tsx
@@ -1,10 +1,12 @@
import { IconBrain } from '@posthog/icons'
import { inStorybookTestRunner } from 'lib/utils/dom'
-import { LangGraphActivity } from 'scenes/max/components/Activity'
import { TaskExecutionStatus as ExecutionStatus } from '~/queries/schema/schema-assistant-messages'
+import { Activity } from '../components/ActivityPrimitives'
+import { MarkdownMessage } from './MarkdownMessage'
+
export interface ReasoningAnswerProps {
content: string
completed: boolean
@@ -21,11 +23,11 @@ export function ReasoningAnswer({
animate = false,
}: ReasoningAnswerProps): JSX.Element {
return (
- <LangGraphActivity
+ <Activity
id={id}
- content={completed ? 'Thought' : content}
+ title={<MarkdownMessage id={id} content={completed ? 'Thought' : content} />}
substeps={completed ? [content] : []}
- state={completed ? ExecutionStatus.Completed : ExecutionStatus.InProgress}
+ status={completed ? ExecutionStatus.Completed : ExecutionStatus.InProgress}
icon={<IconBrain />}
animate={!inStorybookTestRunner() && animate} // Avoiding flaky snapshots in Storybook
showCompletionIcon={showCompletionIcon}
diff --git a/products/posthog_ai/frontend/sandbox/messages/posthogProducts.ts b/products/posthog_ai/frontend/messages/posthogProducts.ts
similarity index 100%
rename from products/posthog_ai/frontend/sandbox/messages/posthogProducts.ts
rename to products/posthog_ai/frontend/messages/posthogProducts.ts
diff --git a/products/posthog_ai/frontend/sandbox/sandboxPermissionDisplayUtils.test.ts b/products/posthog_ai/frontend/policy/sandboxPermissionDisplayUtils.test.ts
similarity index 96%
rename from products/posthog_ai/frontend/sandbox/sandboxPermissionDisplayUtils.test.ts
rename to products/posthog_ai/frontend/policy/sandboxPermissionDisplayUtils.test.ts
index f000d817c77d..f669b6c4405a 100644
--- a/products/posthog_ai/frontend/sandbox/sandboxPermissionDisplayUtils.test.ts
+++ b/products/posthog_ai/frontend/policy/sandboxPermissionDisplayUtils.test.ts
@@ -1,5 +1,5 @@
+import type { PermissionRequestRecord, ToolInvocation } from '../types/sandboxStreamTypes'
import { getPostHogExecDisplay, getSandboxPermissionDisplay } from './sandboxPermissionDisplayUtils'
-import type { PermissionRequestRecord, ToolInvocation } from './types/sandboxStreamTypes'
const rawToolCall: ToolInvocation = {
toolCallId: 'tc-1',
diff --git a/products/posthog_ai/frontend/sandbox/sandboxPermissionDisplayUtils.ts b/products/posthog_ai/frontend/policy/sandboxPermissionDisplayUtils.ts
similarity index 85%
rename from products/posthog_ai/frontend/sandbox/sandboxPermissionDisplayUtils.ts
rename to products/posthog_ai/frontend/policy/sandboxPermissionDisplayUtils.ts
index cf15f8ffb6db..daa82c62b2e1 100644
--- a/products/posthog_ai/frontend/sandbox/sandboxPermissionDisplayUtils.ts
+++ b/products/posthog_ai/frontend/policy/sandboxPermissionDisplayUtils.ts
@@ -1,9 +1,13 @@
-import { POSTHOG_EXEC_TOOL_RE, formatPostHogExecBody, getPostHogExecDisplay } from './posthogExecDisplay'
-import { resolveToolCall } from './sandboxToolResolver'
-import type { PermissionRequestRecord } from './types/sandboxStreamTypes'
+import {
+ POSTHOG_EXEC_TOOL_RE,
+ formatPostHogExecBody,
+ getPostHogExecDisplay,
+} from '../components/tool/posthogExecDisplay'
+import { resolveToolCall } from '../components/tool/sandboxToolResolver'
+import type { PermissionRequestRecord } from '../types/sandboxStreamTypes'
// Re-exported so existing importers (and tests) keep resolving the exec display from here.
-export { getPostHogExecDisplay } from './posthogExecDisplay'
+export { getPostHogExecDisplay } from '../components/tool/posthogExecDisplay'
export interface SandboxPermissionDisplay {
title?: string
diff --git a/products/posthog_ai/frontend/sandbox/sandboxPermissionUtils.test.ts b/products/posthog_ai/frontend/policy/sandboxPermissionUtils.test.ts
similarity index 97%
rename from products/posthog_ai/frontend/sandbox/sandboxPermissionUtils.test.ts
rename to products/posthog_ai/frontend/policy/sandboxPermissionUtils.test.ts
index eca480d63d65..47d64851aba3 100644
--- a/products/posthog_ai/frontend/sandbox/sandboxPermissionUtils.test.ts
+++ b/products/posthog_ai/frontend/policy/sandboxPermissionUtils.test.ts
@@ -1,5 +1,5 @@
+import type { PermissionOption } from '../types/sandboxWireTypes'
import { mapPermissionOption, mapPermissionOptions } from './sandboxPermissionUtils'
-import type { PermissionOption } from './types/sandboxWireTypes'
describe('sandboxPermissionUtils', () => {
describe('mapPermissionOption', () => {
diff --git a/products/posthog_ai/frontend/sandbox/sandboxPermissionUtils.ts b/products/posthog_ai/frontend/policy/sandboxPermissionUtils.ts
similarity index 98%
rename from products/posthog_ai/frontend/sandbox/sandboxPermissionUtils.ts
rename to products/posthog_ai/frontend/policy/sandboxPermissionUtils.ts
index 1127170fc66d..dbd15efb63ee 100644
--- a/products/posthog_ai/frontend/sandbox/sandboxPermissionUtils.ts
+++ b/products/posthog_ai/frontend/policy/sandboxPermissionUtils.ts
@@ -1,4 +1,4 @@
-import type { PermissionOption } from './types/sandboxWireTypes'
+import type { PermissionOption } from '../types/sandboxWireTypes'
/**
* The card-facing decision a user can take on a sandbox ACP `permission_request` option. The
diff --git a/products/posthog_ai/frontend/sandbox/sandboxQuestionUtils.test.ts b/products/posthog_ai/frontend/policy/sandboxQuestionUtils.test.ts
similarity index 100%
rename from products/posthog_ai/frontend/sandbox/sandboxQuestionUtils.test.ts
rename to products/posthog_ai/frontend/policy/sandboxQuestionUtils.test.ts
diff --git a/products/posthog_ai/frontend/sandbox/sandboxQuestionUtils.ts b/products/posthog_ai/frontend/policy/sandboxQuestionUtils.ts
similarity index 100%
rename from products/posthog_ai/frontend/sandbox/sandboxQuestionUtils.ts
rename to products/posthog_ai/frontend/policy/sandboxQuestionUtils.ts
diff --git a/products/posthog_ai/frontend/sandbox/sandboxToolPolicy.test.ts b/products/posthog_ai/frontend/policy/sandboxToolPolicy.test.ts
similarity index 97%
rename from products/posthog_ai/frontend/sandbox/sandboxToolPolicy.test.ts
rename to products/posthog_ai/frontend/policy/sandboxToolPolicy.test.ts
index a5c3d0fca841..8282b7e8bd08 100644
--- a/products/posthog_ai/frontend/sandbox/sandboxToolPolicy.test.ts
+++ b/products/posthog_ai/frontend/policy/sandboxToolPolicy.test.ts
@@ -1,3 +1,5 @@
+import type { PermissionRequestRecord, ToolInvocation } from '../types/sandboxStreamTypes'
+import type { PermissionOption } from '../types/sandboxWireTypes'
import type { SandboxQuestion } from './sandboxQuestionUtils'
import {
defaultPermissionDecision,
@@ -6,8 +8,6 @@ import {
isPostHogExecTool,
type PermissionDecision,
} from './sandboxToolPolicy'
-import type { PermissionRequestRecord, ToolInvocation } from './types/sandboxStreamTypes'
-import type { PermissionOption } from './types/sandboxWireTypes'
function makeRecord(
overrides: {
diff --git a/products/posthog_ai/frontend/sandbox/sandboxToolPolicy.ts b/products/posthog_ai/frontend/policy/sandboxToolPolicy.ts
similarity index 92%
rename from products/posthog_ai/frontend/sandbox/sandboxToolPolicy.ts
rename to products/posthog_ai/frontend/policy/sandboxToolPolicy.ts
index 3cf2632a4acd..84c527d9b57c 100644
--- a/products/posthog_ai/frontend/sandbox/sandboxToolPolicy.ts
+++ b/products/posthog_ai/frontend/policy/sandboxToolPolicy.ts
@@ -1,9 +1,9 @@
-import { isPostHogExecTool } from './posthogExecDisplay'
-import { resolveToolCall } from './sandboxToolResolver'
-import type { PermissionRequestRecord } from './types/sandboxStreamTypes'
+import { isPostHogExecTool } from '../components/tool/posthogExecDisplay'
+import { resolveToolCall } from '../components/tool/sandboxToolResolver'
+import type { PermissionRequestRecord } from '../types/sandboxStreamTypes'
// Re-exported so existing importers (and tests) keep resolving the exec-tool check from here.
-export { isPostHogExecTool } from './posthogExecDisplay'
+export { isPostHogExecTool } from '../components/tool/posthogExecDisplay'
/**
* Default sandbox tool-permission policy, ported from Twig
diff --git a/products/posthog_ai/frontend/sandbox/components/SandboxRunViewer.tsx b/products/posthog_ai/frontend/sandbox/components/SandboxRunViewer.tsx
deleted file mode 100644
index 11fc2f680153..000000000000
--- a/products/posthog_ai/frontend/sandbox/components/SandboxRunViewer.tsx
+++ /dev/null
@@ -1,228 +0,0 @@
-import { BindLogic, useActions, useValues } from 'kea'
-import { useEffect } from 'react'
-
-import { Spinner } from '@posthog/lemon-ui'
-
-import { cn } from 'lib/utils/css-classes'
-
-import { isTerminalRunStatus, sandboxStreamLogic } from '../sandboxStreamLogic'
-import type { QueuedMessage } from '../taskRunInteractionLogic'
-import { Composer } from './composer/Composer'
-import { QueuedMessageList } from './QueuedMessageList'
-import { SandboxContextUsage } from './SandboxContextUsage'
-import { SandboxPermissionInput } from './SandboxPermissionInput'
-import { SandboxQuestionInput } from './SandboxQuestionInput'
-import { SandboxResourcesBar } from './SandboxResourcesBar'
-import { SandboxThreadView } from './SandboxThreadView'
-
-export interface SandboxRunViewerProps {
- taskId: string
- runId: string
- /** Stable logic key; defaults to `runId` (the run is the unit being viewed). */
- streamKey?: string
- /** Telemetry tag only — omit for conversation-less runs (automation, Slack, signals, PR-triggered). */
- conversationId?: string
- /**
- * `'read-only'` (default) replays the persisted `logs/` snapshot once and never opens SSE — the safe
- * choice for a static viewer. `'live'` streams an in-progress run over SSE (falling back to replay once
- * terminal) and adds approvals/questions plus the follow-up composer. The mode is folded into the logic
- * key, so a live and a read-only viewer of the same run can never share state.
- */
- interaction?: 'live' | 'read-only'
- className?: string
- /**
- * Composer wiring — live mode only. Provide all of `composerValue`/`onComposerChange`/`onComposerSubmit`
- * to render the follow-up composer; the consumer owns the draft and the send (this module never POSTs
- * task commands itself). Omit to stream live without a composer.
- */
- composerValue?: string
- onComposerChange?: (value: string) => void
- onComposerSubmit?: () => void
- composerLoading?: boolean
- composerPlaceholder?: string
- /**
- * Editable "Up next" queue — live mode only, rendered above the composer when non-empty. Provide all
- * three to surface staged follow-ups; the consumer owns the queue (this module never mutates it).
- */
- queuedMessages?: QueuedMessage[]
- onUpdateQueuedMessage?: (id: string, content: string) => void
- onRemoveQueuedMessage?: (id: string) => void
-}
-
-/**
- * Embeddable viewer of a task run's agent thread. 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 the run goes terminal.
- */
-export function SandboxRunViewer({
- taskId,
- runId,
- streamKey,
- conversationId,
- interaction = 'read-only',
- className,
- composerValue,
- onComposerChange,
- onComposerSubmit,
- composerLoading,
- composerPlaceholder,
- queuedMessages,
- onUpdateQueuedMessage,
- onRemoveQueuedMessage,
-}: SandboxRunViewerProps): JSX.Element {
- const replayOnly = interaction !== 'live'
- return (
- <BindLogic logic={sandboxStreamLogic} props={{ streamKey: streamKey ?? runId, conversationId, replayOnly }}>
- <SandboxRunViewerContent
- taskId={taskId}
- runId={streamKey ?? runId}
- rawRunId={runId}
- interaction={interaction}
- className={className}
- composerValue={composerValue}
- onComposerChange={onComposerChange}
- onComposerSubmit={onComposerSubmit}
- composerLoading={composerLoading}
- composerPlaceholder={composerPlaceholder}
- queuedMessages={queuedMessages}
- onUpdateQueuedMessage={onUpdateQueuedMessage}
- onRemoveQueuedMessage={onRemoveQueuedMessage}
- />
- </BindLogic>
- )
-}
-
-interface SandboxRunViewerContentProps {
- taskId: string
- /** Logic key (used for child stream keys). */
- runId: string
- /** Original run id passed to `bootstrapRun`. */
- rawRunId: string
- interaction: 'live' | 'read-only'
- className?: string
- composerValue?: string
- onComposerChange?: (value: string) => void
- onComposerSubmit?: () => void
- composerLoading?: boolean
- composerPlaceholder?: string
- queuedMessages?: QueuedMessage[]
- onUpdateQueuedMessage?: (id: string, content: string) => void
- onRemoveQueuedMessage?: (id: string) => void
-}
-
-function SandboxRunViewerContent({
- taskId,
- runId,
- rawRunId,
- interaction,
- className,
- composerValue,
- onComposerChange,
- onComposerSubmit,
- composerLoading,
- composerPlaceholder,
- queuedMessages,
- onUpdateQueuedMessage,
- onRemoveQueuedMessage,
-}: SandboxRunViewerContentProps): JSX.Element {
- const { bootstrapLoading, threadItems, pendingPermissionRequest, currentRunStatus } = useValues(sandboxStreamLogic)
- const { bootstrapRun, reset } = useActions(sandboxStreamLogic)
-
- useEffect(() => {
- // Reset first so a reused instance (stable streamKey, changed run) replays/streams the new run
- // cleanly; the bound logic keys read-only instances apart from any live stream of the same run.
- // `interaction` is in the deps so a status transition (live → terminal) re-bootstraps the right
- // mode — the bound logic re-keys on it, so `bootstrapRun`/`reset` are fresh references anyway.
- reset()
- bootstrapRun({ taskId, runId: rawRunId })
- }, [taskId, rawRunId, interaction, bootstrapRun, reset])
-
- const isLive = interaction === 'live'
- const showSpinner = bootstrapLoading && threadItems.length === 0
-
- // Approvals/questions follow the existing non-terminal precedence: a pending request replaces the
- // composer. The composer itself is gated on explicit live statuses only — never during the `null`
- // bootstrap window, never for terminal runs — so a finished run can't flash a follow-up input.
- const showApproval = isLive && !!pendingPermissionRequest && !isTerminalRunStatus(currentRunStatus)
- const isQuestion = !!pendingPermissionRequest?.questions && pendingPermissionRequest.questions.length > 0
- const hasComposer = isLive && !!onComposerSubmit && onComposerChange !== undefined && composerValue !== undefined
- // The composer shows for any settled run status — active runs take a follow-up, terminal runs start a
- // fresh run from the typed message. It's hidden only during the `null` bootstrap window and while a
- // permission/question prompt is pending.
- const isRunTerminal = isTerminalRunStatus(currentRunStatus)
- const showComposer = hasComposer && !pendingPermissionRequest && currentRunStatus !== null
-
- const thread = showSpinner ? (
- <div className="flex justify-center py-8">
- <Spinner className="text-2xl" />
- </div>
- ) : (
- // An error surfaces as a `handleStreamError` item folded into the thread, so it renders here too.
- <SandboxThreadView />
- )
-
- if (!isLive) {
- return <div className={cn('flex flex-col h-full min-h-0 w-full', className)}>{thread}</div>
- }
-
- return (
- <div className={cn('@container/thread flex flex-col h-full overflow-hidden', className)}>
- <div className="flex-1 min-h-0">{thread}</div>
-
- <SandboxResourcesBar />
-
- {showApproval && (
- <div className="border-t px-4 py-3">
- {isQuestion ? (
- <SandboxQuestionInput streamKey={runId} request={pendingPermissionRequest!} />
- ) : (
- <SandboxPermissionInput streamKey={runId} request={pendingPermissionRequest!} />
- )}
- </div>
- )}
-
- {showComposer && (
- // Composed from the logic-free Composer.* primitives directly (rather than via
- // SandboxComposer) so the run surface can slot its own footer/actions later. The
- // wrapper keeps a stable `data-attr` for the gating tests above.
- <div data-attr="composer" className="border-t px-4 py-3">
- <Composer.Root
- value={composerValue!}
- onChange={onComposerChange!}
- onSubmit={onComposerSubmit!}
- loading={composerLoading}
- >
- {queuedMessages &&
- queuedMessages.length > 0 &&
- onUpdateQueuedMessage &&
- onRemoveQueuedMessage && (
- <Composer.Banner>
- <QueuedMessageList
- messages={queuedMessages}
- onUpdate={onUpdateQueuedMessage}
- onRemove={onRemoveQueuedMessage}
- />
- </Composer.Banner>
- )}
- <Composer.Frame>
- <Composer.Field>
- <Composer.Placeholder>
- {composerPlaceholder ??
- (isRunTerminal
- ? 'Send a message to start a new run…'
- : 'Send a follow-up message…')}
- </Composer.Placeholder>
- <Composer.Textarea data-attr="sandbox-composer-input" submitShortcut="cmd-enter" />
- </Composer.Field>
- </Composer.Frame>
- <Composer.Submit data-attr="sandbox-composer-send" />
- </Composer.Root>
- </div>
- )}
-
- <SandboxContextUsage />
- </div>
- )
-}
diff --git a/products/posthog_ai/frontend/sandbox/index.ts b/products/posthog_ai/frontend/sandbox/index.ts
deleted file mode 100644
index 7d2c0712f30e..000000000000
--- a/products/posthog_ai/frontend/sandbox/index.ts
+++ /dev/null
@@ -1,40 +0,0 @@
-// Public run surface of the sandbox renderer — the conversation-agnostic PostHog AI agent-run UI.
-// Tasks and the signals inbox consume this barrel (`SandboxRunViewer`, `SandboxComposer`, the logic,
-// and the types), never deep paths. PostHog AI (scenes/max) additionally composes lower-level
-// primitives from the subtree directly, by design. This module talks to tasks only via `api.tasks.*`
-// / `products/tasks/frontend/generated/api` and must never import the conversations API or Max
-// conversation orchestration.
-
-export { SandboxRunViewer } from './components/SandboxRunViewer'
-export type { SandboxRunViewerProps } from './components/SandboxRunViewer'
-export { SandboxComposer } from './components/SandboxComposer'
-export type { SandboxComposerProps } from './components/SandboxComposer'
-export { Composer } from './components/composer/Composer'
-export type {
- ComposerRootProps,
- ComposerFrameProps,
- ComposerTextareaProps,
- ComposerSubmitProps,
-} from './components/composer/Composer'
-export { SandboxThreadView } from './components/SandboxThreadView'
-
-export { sandboxStreamLogic, isTerminalRunStatus, SANDBOX_INITIAL_PERMISSION_MODE } from './sandboxStreamLogic'
-export type { SandboxStreamLogicProps, SandboxSseStatus, SandboxRunStatus } from './sandboxStreamLogic'
-
-export { taskRunInteractionLogic } from './taskRunInteractionLogic'
-export type { TaskRunInteractionLogicProps, QueuedMessage } from './taskRunInteractionLogic'
-
-export { SandboxPermissionInput } from './components/SandboxPermissionInput'
-export { SandboxQuestionInput } from './components/SandboxQuestionInput'
-export { SandboxResourcesBar } from './components/SandboxResourcesBar'
-export { SandboxContextUsage } from './components/SandboxContextUsage'
-
-export type {
- ThreadItem,
- ToolInvocation,
- PermissionRequestRecord,
- ContextUsage,
- RunArtifacts,
- SandboxProgressStep,
-} from './types/sandboxStreamTypes'
-export type { SandboxToolCallMessage } from './types/sandboxToolTypes'
diff --git a/products/posthog_ai/frontend/sandbox/types/sandboxStreamTypes.ts b/products/posthog_ai/frontend/types/sandboxStreamTypes.ts
similarity index 99%
rename from products/posthog_ai/frontend/sandbox/types/sandboxStreamTypes.ts
rename to products/posthog_ai/frontend/types/sandboxStreamTypes.ts
index 6c7352f72860..f41d2374fa9b 100644
--- a/products/posthog_ai/frontend/sandbox/types/sandboxStreamTypes.ts
+++ b/products/posthog_ai/frontend/types/sandboxStreamTypes.ts
@@ -6,7 +6,7 @@
* `./sandboxWireTypes`) into `ToolInvocation` / `ThreadItem` stream state.
*/
-import type { SandboxQuestion } from '../sandboxQuestionUtils'
+import type { SandboxQuestion } from '../policy/sandboxQuestionUtils'
import type { PermissionOption } from './sandboxWireTypes'
export type ToolInvocationStatus = 'pending' | 'in_progress' | 'completed' | 'failed'
diff --git a/products/posthog_ai/frontend/sandbox/types/sandboxToolTypes.ts b/products/posthog_ai/frontend/types/sandboxToolTypes.ts
similarity index 100%
rename from products/posthog_ai/frontend/sandbox/types/sandboxToolTypes.ts
rename to products/posthog_ai/frontend/types/sandboxToolTypes.ts
diff --git a/products/posthog_ai/frontend/sandbox/types/sandboxWireTypes.test.ts b/products/posthog_ai/frontend/types/sandboxWireTypes.test.ts
similarity index 100%
rename from products/posthog_ai/frontend/sandbox/types/sandboxWireTypes.test.ts
rename to products/posthog_ai/frontend/types/sandboxWireTypes.test.ts
diff --git a/products/posthog_ai/frontend/sandbox/types/sandboxWireTypes.ts b/products/posthog_ai/frontend/types/sandboxWireTypes.ts
similarity index 100%
rename from products/posthog_ai/frontend/sandbox/types/sandboxWireTypes.ts
rename to products/posthog_ai/frontend/types/sandboxWireTypes.ts
diff --git a/products/posthog_ai/frontend/sandbox/utils/thinkingMessages.ts b/products/posthog_ai/frontend/utils/thinkingMessages.ts
similarity index 100%
rename from products/posthog_ai/frontend/sandbox/utils/thinkingMessages.ts
rename to products/posthog_ai/frontend/utils/thinkingMessages.ts
diff --git a/products/posthog_ai/package.json b/products/posthog_ai/package.json
index aa1ac2db8014..06c974af7edb 100644
--- a/products/posthog_ai/package.json
+++ b/products/posthog_ai/package.json
@@ -7,7 +7,9 @@
"eventsource-parser": "*",
"kea-subscriptions": "catalog:",
"marked": "*",
+ "monaco-editor": "^0.55.1",
"posthog-js": "catalog:",
+ "react-intersection-observer": "^9.5.3",
"react-window": "*",
"tailwind-merge": "*"
},
diff --git a/products/tasks/frontend/components/TaskRunChat.tsx b/products/tasks/frontend/components/TaskRunChat.tsx
index 19ff2c95bf4c..9f12fd855994 100644
--- a/products/tasks/frontend/components/TaskRunChat.tsx
+++ b/products/tasks/frontend/components/TaskRunChat.tsx
@@ -4,7 +4,7 @@ import {
SandboxRunViewer,
type TaskRunInteractionLogicProps,
taskRunInteractionLogic,
-} from 'products/posthog_ai/frontend/sandbox'
+} from 'products/posthog_ai/frontend'
import { taskDetailSceneLogic } from '../logics/taskDetailSceneLogic'