:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(phai): sandbox streaming logic, wire types, and tool resolution (#65166)
Georgiy Tarasove07bebcd8f49
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 4b9dfd945d4d..326328b303eb 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -5479,17 +5479,17 @@ snapshots:scenes-app-inbox-detail--report-minimal--light:hash: v1.k794b7964.8d3708d246d553b9d29d028f8ea7804c7ab9e33ebc6b2cddaaaa6f12d3dc1cfe.BW5bHBxSPVtSfQXDtTuZT5aEK4T-HzsJLzA2qhmRpVEscenes-app-inbox-detail--run-failed--dark:- hash: v1.k794b7964.a81e0056d7e41aea91881fa658e2e744c6d38182cb85c8b2ae211c1d01564014.IDM9GRcQT4gRW-yqlq9Ntg-wAZDiQWrkZf69Va0fkjM+ hash: v1.k794b7964.24a6a48235fc55e744f38faacb816d25379dfcb367726e9444d21d6e282145c6.XzXgb6YX-JIB-e71TaHj8jg8pc4xKfRybxgMK21e0C0scenes-app-inbox-detail--run-failed--light:- hash: v1.k794b7964.eff26b30ff1b74bf77e68a9b83242b723a031a84668855f7fe67e29e7593f68b.Bcl6dB6ZwTS4CgbIG19B_Ys3nYY-6BfLZwdo8przN-0+ hash: v1.k794b7964.fd1cf8b6b12d828c5b84125bc64772ec23b0dac271ac42dc15fbd2e62956a3df.arjDseHyj4xrBHxKYt6x9s6jVnuF0sCPV5E_ZCzxb94scenes-app-inbox-detail--run-in-progress--dark:- hash: v1.k794b7964.6d479c1f9677e027c962151b3993648babea4aa7c1306fb158ed37c1fb10a929.WCZtZiBivqhAZTI7nY5ILqasbFEbISExNLoNOCpL4S8+ hash: v1.k794b7964.71b8c2315eaa8979c6abaf6de556baf1cb3139b8242f28016d60677f96340ec2.xuALS0wXmge0BuTvAouSfeIKZE_GZ8NmR-MhgAlTqyoscenes-app-inbox-detail--run-in-progress--light:- hash: v1.k794b7964.f8d95efb0fee8517003a95be0a740c37af51fd888ed5b9dd858f1840f69c49dd.4JG5rL4VNtEUk5shtZag-fimDVAUb2SU9fNd0BQhYXI+ hash: v1.k794b7964.c61995970036807317d228804325d6a542b468b690c375e91aa7cfe6767eb4d1.4e2PI0ItsnDkrBsk4ugLLLytmATlnTUE2Uf4qJtBXJcscenes-app-inbox-detail--run-ready--dark:- hash: v1.k794b7964.2c9966f4b6e2274d884b93b21add25f69cc934e3e580006654ebd1ef5123b563.fPwrKUERAtNpNXvrIgrBcYzWGBQaZtbE4spXnY67KnI+ hash: v1.k794b7964.3b9cffcdfe2ff247a8e96e83ad676e1a77b526d45195df95229ac59270619f9f.YPydasQ1CV9EzgOuKfN-JbSX6QtlFwbAsWFYcXNNbycscenes-app-inbox-detail--run-ready--light:- hash: v1.k794b7964.4050eb15b9d9c5ac9e2783ff55bdb3db37852d43f71832a59f308396a01c5a14.a5dDQZ2UQnE2VDGVWxSmlofmqd3niKKdxyrO1KQ9YKU+ hash: v1.k794b7964.081a81c8b063f2ec4d539da5d37b330aecc970cbb0081defd13256b2d97bba4d.B_97A5t9x5YmeLTqC_tJOSfRzwcJbfURFpWzcTPtc0Qscenes-app-inbox-scene--empty--dark:hash: v1.k794b7964.5e028d969ab0fde2b308bbc3bbc78ef671a5892454486d07739b43dd9a11fe2f.-cAwhDDmKAi9Ps2rzFpfUBl7Dc5RaHFxzLfHDR2XJRoscenes-app-inbox-scene--empty--light:diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.tsindex 4ab82a0ce1fc..18133db67c2b 100644--- a/frontend/src/lib/api.ts+++ b/frontend/src/lib/api.ts@@ -245,6 +245,7 @@ import type {SessionGroupSummaryType,SessionSummariesConfig,} from 'products/session_summaries/frontend/types'+import type { TaskRunBootstrapCreateRequestInitialPermissionModeEnumApi } from 'products/tasks/frontend/generated/api.schemas'import type { Task, TaskListParams, TaskRun, TaskUpsertProps } from 'products/tasks/frontend/types'import type { BlastRadiusApi } from 'products/workflows/frontend/generated/api.schemas'import type { OptOutEntry } from 'products/workflows/frontend/OptOuts/types'@@ -259,7 +260,7 @@ import type {} from 'products/workflows/frontend/Workflows/hogflows/types'import { AgentMode } from '../queries/schema'-import type { MaxUIContext } from '../scenes/max/maxTypes'+import type { AttachedContext, MaxUIContext } from '../scenes/max/maxTypes'import { AlertSimulationResult, AlertType, AlertTypeWrite } from './components/Alerts/types'import {ErrorTrackingFingerprint,@@ -5298,6 +5299,52 @@ const api = {}return ''},+ /**+ * Fetch the assembled resume-chain ACP log for a run (the products/tasks `logs/`+ * endpoint returns JSONL — one `StoredLogEntry` per line, concatenated server-side+ * across the entire resume chain). Used to bootstrap the sandbox stream before+ * opening SSE.+ */+ async getLogEntries(taskId: Task['id'], runId: TaskRun['id']): Promise<Record<string, any>[]> {+ const response = await new ApiRequest().taskRun(taskId, runId).withAction('logs').getResponse()+ const text = await response.text()+ const entries: Record<string, any>[] = []+ for (const line of text.split('\n')) {+ const trimmed = line.trim()+ if (!trimmed) {+ continue+ }+ try {+ entries.push(JSON.parse(trimmed))+ } catch {+ // Skip unparseable lines — the stream is best-effort historical replay.+ }+ }+ return entries+ },+ /**+ * Open the live SSE stream for a run as a `fetch` response (the caller reads it with+ * `response.body.getReader()` + an `eventsource-parser`). Unlike a native `EventSource`,+ * a `fetch` lets us set request headers — so a reconnect resumes exactly after the+ * last-seen frame via `Last-Event-ID` (the Redis stream id) instead of re-broadcasting+ * the whole stream. `startLatest` (the first connect after replaying S3 history) streams+ * only frames newer than the connect cutoff; it is ignored once a `lastEventId` is+ * present, since the header resume is exact.+ */+ async openStream(+ taskId: Task['id'],+ runId: TaskRun['id'],+ options: { signal: AbortSignal; lastEventId?: string; startLatest?: boolean }+ ): Promise<Response> {+ const headers: Record<string, string> = {}+ let request = new ApiRequest().taskRun(taskId, runId).withAction('stream')+ if (options.lastEventId) {+ headers['Last-Event-ID'] = options.lastEventId+ } else if (options.startLatest) {+ request = request.withQueryString({ start: 'latest' })+ }+ return request.getResponse({ signal: options.signal, headers })+ },},},@@ -6713,6 +6760,43 @@ const api = {return api.createResponse(new ApiRequest().conversations().assembleFullUrl(), data, options)},+ /**+ * Single sandbox session opener (`agent_runtime === 'sandbox'`). Create-or-resume: the+ * conversation row is created on first use from the client-minted id. With `content`,+ * processes the turn (first message, in-progress follow-up, or terminal resume); with+ * null/omitted `content`, warms a sandbox that idles awaiting the first message. Returns the+ * `(task, run)` handle to open SSE against, or `null` on a 204 (a warm that provisioned+ * nothing — the pool was full). Control verbs (cancel, permission reply, warm release) go+ * through the generic `runs/{run}/command/` relay, not this endpoint.+ */+ async open(+ conversationId: string,+ data: {+ content?: string | null+ trace_id?: string+ attached_context?: AttachedContext[]+ initial_permission_mode?: TaskRunBootstrapCreateRequestInitialPermissionModeEnumApi+ /** Bind a brand-new sandbox conversation to an existing Task, resuming its run on the first message. */+ task_id?: string+ }+ ): Promise<{+ task_id: string+ run_id: string+ trace_id: string | null+ run_status: 'queued' | 'in_progress'+ just_created_run: boolean+ } | null> {+ const response = await api.createResponse(+ new ApiRequest().conversation(conversationId).withAction('open').assembleFullUrl(),+ data+ )+ if (response.status === 204) {+ return null+ }+ return response.json()+ },++ /** Cancel an in-progress LangGraph run. Sandbox runs cancel through the tasks relay. */cancel(conversationId: string): Promise<void> {return new ApiRequest().conversation(conversationId).withAction('cancel').update()},diff --git a/frontend/src/scenes/inbox/__mocks__/inboxMocks.ts b/frontend/src/scenes/inbox/__mocks__/inboxMocks.tsindex f7b868939c9a..c7d116eb8ba5 100644--- a/frontend/src/scenes/inbox/__mocks__/inboxMocks.ts+++ b/frontend/src/scenes/inbox/__mocks__/inboxMocks.ts@@ -335,8 +335,30 @@ export function mockReportTasks(reportId: string): { results: any[]; count: numb}}-export function mockTask(taskId: string): any {- const failed = taskId.includes('research')+function makeTaskRun(taskId: string, runId: string, status: string): any {+ return {+ id: runId,+ task: taskId,+ stage: null,+ branch: 'inbox/fix-invites',+ status,+ environment: 'cloud',+ log_url: null,+ error_message: null,+ output: taskId.includes('impl') ? { pr_url: 'https://github.com/PostHog/posthog/pull/12001' } : {},+ state: {},+ artifacts: [],+ created_at: BASE_DATE,+ updated_at: BASE_DATE,+ completed_at: status === 'in_progress' ? null : BASE_DATE,+ }+}++// `runStatus` overrides the linked run's status; defaults keep the research task finished and the+// implementation task live. Pass a terminal status (e.g. 'completed') to render the run viewer's+// static replay rather than a live SSE stream.+export function mockTask(taskId: string, runStatus?: string): any {+ const status = runStatus ?? (taskId.includes('research') ? 'completed' : 'in_progress')return {id: taskId,task_number: 42,@@ -348,28 +370,43 @@ export function mockTask(taskId: string): any {github_integration: 1,json_schema: null,internal: false,- latest_run: {- id: `${taskId}-run`,- task: taskId,- stage: null,- branch: 'inbox/fix-invites',- status: failed ? 'completed' : 'in_progress',- environment: 'cloud',- log_url: null,- error_message: null,- output: taskId.includes('impl') ? { pr_url: 'https://github.com/PostHog/posthog/pull/12001' } : {},- state: {},- artifacts: [],- created_at: BASE_DATE,- updated_at: BASE_DATE,- completed_at: failed ? BASE_DATE : null,- },+ latest_run: makeTaskRun(taskId, `${taskId}-run`, status),created_at: BASE_DATE,updated_at: BASE_DATE,created_by: null,}}+/** The run-status payload (`/runs/:runId`) the `SandboxRunViewer` reads before replaying its log. */+export function mockTaskRun(taskId: string, runId: string): any {+ return makeTaskRun(taskId, runId, 'completed')+}++/**+ * A single-message agent run log as JSONL — what the `/runs/:runId/logs` endpoint returns (one+ * `StoredLogEntry` per line). One `agent_message` frame so the run viewer renders a single assistant+ * bubble instead of the "conversation backing run not found" error.+ */+export function mockRunLog(): string {+ const entry = {+ type: 'notification',+ notification: {+ method: 'session/update',+ params: {+ update: {+ sessionUpdate: 'agent_message',+ messageId: 'inbox-run-msg',+ content: {+ type: 'text',+ text: 'Investigated the invite failures, confirmed the missing-recipient 500, and opened a fix.',+ },+ },+ },+ },+ }+ return JSON.stringify(entry)+}+export const mockSourceConfigs = {results: [{diff --git a/frontend/src/scenes/inbox/components/detail/AgentRunDetail.tsx b/frontend/src/scenes/inbox/components/detail/AgentRunDetail.tsxindex 4b13d9b3ccf1..7dafc3de6b57 100644--- a/frontend/src/scenes/inbox/components/detail/AgentRunDetail.tsx+++ b/frontend/src/scenes/inbox/components/detail/AgentRunDetail.tsx@@ -1,4 +1,5 @@-import { useValues } from 'kea'+import { useActions, useValues } from 'kea'+import { combineUrl } from 'kea-router'import {IconArrowRight,@@ -7,15 +8,22 @@ import {IconDocument,IconPullRequest,IconSearch,+ IconTerminal,IconWarning,} from '@posthog/icons'-import { Link, Spinner, LemonTag, Tooltip } from '@posthog/lemon-ui'+import { LemonButton, Link, Spinner, LemonSelect, LemonSkeleton, LemonTag, Tooltip } from '@posthog/lemon-ui'import { TZLabel } from 'lib/components/TZLabel'import { LemonMarkdown } from 'lib/lemon-ui/LemonMarkdown'import { SignalNode } from 'scenes/debug/signals/types'+import { maxGlobalLogic } from 'scenes/max/maxGlobalLogic'+import { SANDBOX_BIND_TASK_PARAM } from 'scenes/max/maxLogic'+import { SandboxRunViewer } from 'scenes/max/sandbox/components/SandboxRunViewer'+import { isTerminalRunStatus } from 'scenes/max/sandboxStreamLogic'import { urls } from 'scenes/urls'+import { Task, TaskRunStatus } from 'products/tasks/frontend/types'+import { inboxReportDetailLogic } from '../../logics/inboxReportDetailLogic'import { SignalCard } from '../../SignalCard'import { SignalReport, SignalReportStatus } from '../../types'@@ -24,6 +32,7 @@ import { getSourceProductMeta } from '../badges/sourceProductIcons'import { DetailSection, RightColumnSection } from './DetailSection'import { ReportDetailBadges } from './ReportDetail'import { ReportTasksSection } from './ReportTasksSection'+import { RELATIONSHIP_LABEL, TaskRunStatusDot } from './taskRunDisplay'/*** Ready-state run output: a polished outcome card that links to the produced PR or report,@@ -121,8 +130,8 @@ function RunOutputWidget({ report }: { report: SignalReport }): JSX.Element {/*** Compact run-state strip: live/finished status, the produced branch (when a PR exists), and run- * timing. Mirrors desktop's run-state header line (status · branch · timing) without rebuilding the- * run log – the actual log lives behind the linked runs (see `ReportTasksSection`).+ * timing. Mirrors desktop's run-state header line (status · branch · timing); the agent transcript+ * itself renders inline below in `TaskLogSection`.*/function RunStateStrip({ report }: { report: SignalReport }): JSX.Element {const isLive =@@ -158,10 +167,135 @@ function RunStateStrip({ report }: { report: SignalReport }): JSX.Element {)}+/** The selected run's agent transcript, or a loading / empty placeholder. */+function TaskLogBody({+ loading,+ task,+ runId,+ replayOnly,+}: {+ loading: boolean+ task: Task | null+ runId: string | null+ replayOnly: boolean+}): JSX.Element {+ if (loading) {+ return (+ <div className="flex flex-col gap-2">+ <LemonSkeleton className="h-4 w-36" />+ <LemonSkeleton className="h-28 w-full" />+ </div>+ )+ }++ if (task && runId) {+ return (+ <div className="h-[calc(100vh-22rem)] min-h-[420px] w-full overflow-y-auto rounded border border-primary bg-surface-primary">+ {/* In-progress runs stream live; terminal runs show the static replay. */}+ <SandboxRunViewer taskId={task.id} runId={runId} replayOnly={replayOnly} />+ </div>+ )+ }++ return (+ <div className="flex flex-col gap-2 rounded border border-primary bg-surface-primary px-4 py-3.5">+ <span className="font-medium text-sm text-primary">+ {task ? 'Run hasn’t started yet' : 'Waiting for the linked task'}+ </span>+ <span className="max-w-2xl text-xs text-secondary leading-snug">+ {task+ ? 'This task is queued – its agent log will appear here once the run starts.'+ : 'Once the agent links this run to a task, its agent log appears here.'}+ </span>+ </div>+ )+}++/**+ * "Open task": continues the selected task in a new PostHog AI chat bound to it — the chat's first+ * message creates a conversation linked to this task and resumes its run interactively. A plain click+ * opens PostHog AI in the side panel (staying in the inbox); cmd/ctrl/middle-click follows the href to+ * open a new tab, carrying the bind via the `bind_task` URL param. Gated to a terminal run — the live+ * Task log already covers an in-progress run, and taking over a running automation run is out of scope.+ */+function OpenTaskButton({ taskId, runStatus }: { taskId: string; runStatus?: TaskRunStatus }): JSX.Element {+ const { openSidePanelMaxWithTaskBind } = useActions(maxGlobalLogic)+ const isTerminal = isTerminalRunStatus(runStatus)++ return (+ <LemonButton+ size="xsmall"+ type="secondary"+ to={combineUrl(urls.ai(), { [SANDBOX_BIND_TASK_PARAM]: taskId }).url}+ onClick={(e) => {+ // Plain left-click: open the side panel in place rather than navigating to /ai.+ // Link lets a modified click (cmd/ctrl/middle) through to the href for a new tab.+ e.preventDefault()+ openSidePanelMaxWithTaskBind(taskId)+ }}+ disabledReason={isTerminal ? undefined : 'Available once the run finishes'}+ tooltip="Continue this task in a new PostHog AI chat"+ >+ Open task+ </LemonButton>+ )+}++/**+ * Inline "Task log": the selected linked task's agent transcript, rendered with the shared+ * `SandboxRunViewer` — live for an in-progress run, static replay once terminal. A `LemonSelect`+ * switches between linked tasks (research / implementation) when there's more than one; "Open task"+ * continues the task in a new PostHog AI chat. Mirrors desktop `AgentRunDetail`'s Task-log section.+ */+function TaskLogSection({ report }: { report: SignalReport }): JSX.Element {+ const { reportTasks, reportTasksLoading, selectedTask } = useValues(+ inboxReportDetailLogic({ reportId: report.id, report })+ )+ const { setSelectedTaskId } = useActions(inboxReportDetailLogic({ reportId: report.id, report }))++ const task = selectedTask?.task ?? null+ const runId = task?.latest_run?.id ?? null+ const runStatus = task?.latest_run?.status+ const replayOnly = isTerminalRunStatus(runStatus)++ const rightSlot = task ? (+ <div className="flex items-center gap-2">+ {reportTasks && reportTasks.length > 1 && (+ <LemonSelect+ size="small"+ value={task.id}+ onChange={(id) => setSelectedTaskId(id)}+ options={reportTasks.map((entry) => ({+ value: entry.task.id,+ label: (+ <span className="flex items-center gap-1.5">+ <TaskRunStatusDot status={entry.task.latest_run?.status ?? TaskRunStatus.NOT_STARTED} />+ {RELATIONSHIP_LABEL[entry.relationship]}+ </span>+ ),+ }))}+ />+ )}+ <OpenTaskButton taskId={task.id} runStatus={runStatus} />+ </div>+ ) : null++ return (+ <DetailSection icon={<IconTerminal />} title="Task log" rightSlot={rightSlot}>+ <TaskLogBody+ loading={reportTasksLoading && !reportTasks}+ task={task}+ runId={runId}+ replayOnly={replayOnly}+ />+ </DetailSection>+ )+}+/**- * Agent run detail body. Shows the run state strip + output state, the linked run(s) (which link out- * to the task detail page – we do NOT rebuild the run-log viewer here), and contributing evidence.- * Mirrors desktop `AgentRunDetail`'s intent with cloud's existing task-detail run log.+ * Agent run detail body. Shows the run state strip + output state, the linked run's agent transcript+ * inline (`TaskLogSection`, via the shared `SandboxRunViewer`), and contributing evidence.+ * Mirrors desktop `AgentRunDetail`.*/export function AgentRunDetail({ report }: { report: SignalReport }): JSX.Element {const { reportSignals, reportSignalsLoading, isReResearch, priorityExplanation, actionabilityExplanation } =@@ -190,7 +324,7 @@ export function AgentRunDetail({ report }: { report: SignalReport }): JSX.Elemen<div className="flex flex-col min-w-0 gap-5"><RunStateStrip report={report} /><RunOutputWidget report={report} />- <ReportTasksSection report={report} />+ <TaskLogSection report={report} /></div><div className="flex flex-col min-w-0 gap-5">@@ -218,6 +352,7 @@ export function AgentRunDetail({ report }: { report: SignalReport }): JSX.Elemen)}</RightColumnSection>)}+ <ReportTasksSection report={report} /></div></div></div>diff --git a/frontend/src/scenes/inbox/components/detail/InboxDetail.stories.tsx b/frontend/src/scenes/inbox/components/detail/InboxDetail.stories.tsxindex 9ea1a8154f2c..cfce5781875a 100644--- a/frontend/src/scenes/inbox/components/detail/InboxDetail.stories.tsx+++ b/frontend/src/scenes/inbox/components/detail/InboxDetail.stories.tsx@@ -1,4 +1,5 @@import type { Meta, StoryObj } from '@storybook/react'+import { HttpResponse } from 'msw'import { mswDecorator } from '~/mocks/browser'@@ -7,8 +8,10 @@ import {mockArtefacts,mockReportTasks,mockReviewers,+ mockRunLog,mockSignals,mockTask,+ mockTaskRun,pullRequestReports,reportTabReports,runReportsMany,@@ -37,7 +40,13 @@ const detailMocks = mswDecorator({mockReportTasks(req.params.reportId as string),],'/api/projects/:id/signals/reports/available_reviewers': () => [200, mockReviewers],- '/api/projects/:id/tasks/:taskId': (req) => [200, mockTask(req.params.taskId as string)],+ // Terminal run status so the inline run viewer replays its static log instead of opening SSE.+ '/api/projects/:id/tasks/:taskId': (req) => [200, mockTask(req.params.taskId as string, 'completed')],+ '/api/projects/:id/tasks/:taskId/runs/:runId': (req) => [+ 200,+ mockTaskRun(req.params.taskId as string, req.params.runId as string),+ ],+ '/api/projects/:id/tasks/:taskId/runs/:runId/logs': () => new HttpResponse(mockRunLog()),},})diff --git a/frontend/src/scenes/inbox/components/detail/ReportTasksSection.tsx b/frontend/src/scenes/inbox/components/detail/ReportTasksSection.tsxindex 2c5b6802fa22..aaccd9ac9b90 100644--- a/frontend/src/scenes/inbox/components/detail/ReportTasksSection.tsx+++ b/frontend/src/scenes/inbox/components/detail/ReportTasksSection.tsx@@ -1,6 +1,4 @@-import clsx from 'clsx'import { useValues } from 'kea'-import { combineUrl } from 'kea-router'import { IconChevronRight, IconTerminal } from '@posthog/icons'import { Link, Spinner } from '@posthog/lemon-ui'@@ -10,37 +8,14 @@ import { urls } from 'scenes/urls'import { Task, TaskRunStatus } from 'products/tasks/frontend/types'import { inboxReportDetailLogic, ReportTaskEntry } from '../../logics/inboxReportDetailLogic'-import { SignalReport, SignalReportTaskRelationship } from '../../types'+import { SignalReport } from '../../types'import { RightColumnSection } from './DetailSection'--const RELATIONSHIP_LABEL: Record<SignalReportTaskRelationship, string> = {- research: 'Research',- implementation: 'Implementation',- repo_selection: 'Repo selection',-}--const TERMINAL_STATUSES: TaskRunStatus[] = [TaskRunStatus.COMPLETED, TaskRunStatus.FAILED, TaskRunStatus.CANCELLED]--function TaskRunStatusDot({ status }: { status: TaskRunStatus }): JSX.Element {- const terminal = TERMINAL_STATUSES.includes(status)- const color =- status === TaskRunStatus.FAILED || status === TaskRunStatus.CANCELLED- ? 'bg-danger'- : terminal- ? 'bg-success'- : 'bg-primary'- return (- <span- className={clsx('inline-block size-1.5 shrink-0 rounded-full', color, !terminal && 'animate-pulse')}- aria-hidden- />- )-}+import { RELATIONSHIP_LABEL, TaskRunStatusDot } from './taskRunDisplay'/**- * Renders the report's linked tasks inline (latest status + relationship) and links out to- * cloud's existing task detail page. The run-log/session viewer lives there; this is the doorway.- * Only `implementation` and `research` relationships are shown, implementation-first.+ * Renders the report's linked tasks inline (latest status + relationship). Each row opens the+ * report's run detail (`AgentRunDetail`), where the task's run log renders inline. Only+ * `implementation` and `research` relationships are shown, implementation-first.*/export function ReportTasksSection({ report }: { report: SignalReport }): JSX.Element | null {const { reportTasks, reportTasksLoading } = useValues(inboxReportDetailLogic({ reportId: report.id, report }))@@ -64,23 +39,21 @@ export function ReportTasksSection({ report }: { report: SignalReport }): JSX.El<RightColumnSection icon={<IconTerminal />} title="Runs"><div className="flex flex-col gap-0.5">{reportTasks.map((entry: ReportTaskEntry) => (- <TaskRow key={entry.task.id} entry={entry} />+ <TaskRow key={entry.task.id} entry={entry} reportId={report.id} />))}</div></RightColumnSection>)}-function TaskRow({ entry }: { entry: ReportTaskEntry }): JSX.Element {+function TaskRow({ entry, reportId }: { entry: ReportTaskEntry; reportId: string }): JSX.Element {const { task, relationship } = entryconst status = task.latest_run?.status ?? TaskRunStatus.NOT_STARTED- const runId = task.latest_run?.id- // Deep-link straight to the task's run logs in cloud's Tasks UI (selecting the latest run),- // rather than the in-inbox Runs route.- const taskLogUrl = runId ? combineUrl(urls.taskDetail(task.id), { runId }).url : urls.taskDetail(task.id)+ // Open this report's run detail (the inbox Runs route); `inboxSceneLogic` handles the cross-tab+ // open. The task's run log renders inline there — no need to leave the inbox for the Tasks UI.return (<Link- to={taskLogUrl}+ to={urls.inboxReport('runs', reportId)}className="group flex items-center gap-2 rounded px-1.5 py-1 text-left text-xs no-underline transition-colors hover:bg-fill-highlight-50"><TaskRunStatusDot status={status} />diff --git a/frontend/src/scenes/inbox/components/detail/taskRunDisplay.tsx b/frontend/src/scenes/inbox/components/detail/taskRunDisplay.tsxnew file mode 100644index 000000000000..fefd26071518--- /dev/null+++ b/frontend/src/scenes/inbox/components/detail/taskRunDisplay.tsx@@ -0,0 +1,36 @@+import clsx from 'clsx'++import { TaskRunStatus } from 'products/tasks/frontend/types'++import { SignalReportTaskRelationship } from '../../types'++/** Human label for a report→task relationship, shown next to a run in the inbox. */+export const RELATIONSHIP_LABEL: Record<SignalReportTaskRelationship, string> = {+ research: 'Research',+ implementation: 'Implementation',+ repo_selection: 'Repo selection',+}++/** Run statuses that count as terminal. Mirrors desktop `isTerminalStatus`. */+export const TERMINAL_STATUSES: TaskRunStatus[] = [+ TaskRunStatus.COMPLETED,+ TaskRunStatus.FAILED,+ TaskRunStatus.CANCELLED,+]++/** Small status dot: red for failed/cancelled, green for completed, pulsing blue while in motion. */+export function TaskRunStatusDot({ status }: { status: TaskRunStatus }): JSX.Element {+ const terminal = TERMINAL_STATUSES.includes(status)+ const color =+ status === TaskRunStatus.FAILED || status === TaskRunStatus.CANCELLED+ ? 'bg-danger'+ : terminal+ ? 'bg-success'+ : 'bg-primary'+ return (+ <span+ className={clsx('inline-block size-1.5 shrink-0 rounded-full', color, !terminal && 'animate-pulse')}+ aria-hidden+ />+ )+}diff --git a/frontend/src/scenes/inbox/logics/inboxReportDetailLogic.ts b/frontend/src/scenes/inbox/logics/inboxReportDetailLogic.tsindex 13e36be28adf..56abf3fc37ed 100644--- a/frontend/src/scenes/inbox/logics/inboxReportDetailLogic.ts+++ b/frontend/src/scenes/inbox/logics/inboxReportDetailLogic.ts@@ -98,6 +98,8 @@ export const inboxReportDetailLogic = kea<inboxReportDetailLogicType>([setOptimisticReviewers: (reviewers: EnrichedReviewer[] | null) => ({ reviewers }),// Debounced server-side org-member search for the add-reviewer picker.searchAvailableReviewers: (query: string) => ({ query }),+ // Which linked task's run log the detail view shows; null falls back to `primaryTask`.+ setSelectedTaskId: (taskId: string | null) => ({ taskId }),}),loaders(({ props }) => ({@@ -168,6 +170,15 @@ export const inboxReportDetailLogic = kea<inboxReportDetailLogicType>([setOptimisticReviewers: (_, { reviewers }) => reviewers,},],+ // Explicit task selection for the run-log viewer. Reset when the report changes so a freshly+ // opened run starts on its `primaryTask`.+ selectedTaskId: [+ null as string | null,+ {+ setSelectedTaskId: (_, { taskId }) => taskId,+ setReport: () => null,+ },+ ],}),selectors({@@ -267,6 +278,37 @@ export const inboxReportDetailLogic = kea<inboxReportDetailLogicType>([return hasInFlight && hasPriorTerminal},],+ // The default task whose run log is shown: prefer one still in motion, tie-break by most-recent+ // link. Mirrors desktop `AgentRunDetail`'s `pickPrimaryTask`.+ primaryTask: [+ (s) => [s.reportTasks],+ (reportTasks: ReportTaskEntry[] | null): ReportTaskEntry | null => {+ if (!reportTasks || reportTasks.length === 0) {+ return null+ }+ return [...reportTasks].sort((a, b) => {+ const aInMotion = !TERMINAL_RUN_STATUSES.includes(+ a.task.latest_run?.status ?? TaskRunStatus.NOT_STARTED+ )+ const bInMotion = !TERMINAL_RUN_STATUSES.includes(+ b.task.latest_run?.status ?? TaskRunStatus.NOT_STARTED+ )+ if (aInMotion !== bInMotion) {+ return aInMotion ? -1 : 1+ }+ return new Date(b.startedAt).getTime() - new Date(a.startedAt).getTime()+ })[0]+ },+ ],+ // The linked task the viewer renders: the explicit selection if it still exists, else `primaryTask`.+ selectedTask: [+ (s) => [s.reportTasks, s.selectedTaskId, s.primaryTask],+ (+ reportTasks: ReportTaskEntry[] | null,+ selectedTaskId: string | null,+ primaryTask: ReportTaskEntry | null+ ): ReportTaskEntry | null => reportTasks?.find((rt) => rt.task.id === selectedTaskId) ?? primaryTask,+ ],}),listeners(({ actions, values, cache, props }) => ({diff --git a/frontend/src/scenes/max/AGENTS.md b/frontend/src/scenes/max/AGENTS.mdnew file mode 100644index 000000000000..2d2495c4c77b--- /dev/null+++ b/frontend/src/scenes/max/AGENTS.md@@ -0,0 +1,109 @@+# PostHog AI scene — agent guide++This is the scene for **PostHog AI**, PostHog's agent. It hosts **two coexisting runtimes**, chosen per conversation by `conversation.agent_runtime` (`'langgraph' | 'sandbox'`):++- **`langgraph`** — the **legacy** runtime. Frozen.+- **`sandbox`** — the **new** runtime (Claude Code/Codex agent-server over SSE). New work goes here.++> **Naming:** the user-facing product is **PostHog AI** (was "Max"). Use "PostHog AI" in all user-facing copy. The directory stays `scenes/max/`, and existing internal identifiers (`Max*` components, `MaxUIContext`, `maxThreadLogic`, `maxContextLogic`, the "Max Context" subsystem) keep their names — don't mass-rename. New code shouldn't introduce fresh "Max" branding in copy.++> For the **Max Context** subsystem (how scenes expose dashboards/insights/events to the assistant), see [`README.md`](./README.md). This guide does not repeat it.++## 1. Legacy vs new runtime — read this first++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()`+- **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`++### Rule: do not extend the LangGraph path unless explicitly asked++New behavior — new tools, new context types, new UI affordances — goes on the **sandbox** path. The LangGraph runtime is slated for removal once sandbox reaches parity; keeping its surface from growing makes the eventual deletion a clean removal rather than an untangling.++- ✅ Bugfixes that keep existing LangGraph conversations working.+- ❌ Net-new capability on the LangGraph path.+- ❌ New fields on `MaxUIContext` for a sandbox feature — use `AttachedContext` instead.+- ❌ No new MaxTools.++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)++`sandboxStreamLogic.ts` is the heart of the sandbox runtime:++- **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.++**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.++**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).++**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+```++## 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).+- **New context the agent should see** → extend `AttachedContext` (not `MaxUIContext`).++## 6. Don'ts++- Don't extend the LangGraph runtime unless explicitly asked.+- Don't parse wire frames or hold SSE state inside a component.+- Don't mutate thread/invocation state from a listener — derive it in the projection.+- Don't add `MaxUIContext` fields for a sandbox feature — use `AttachedContext`.+- Don't subscribe to all sandbox selectors when you need one.+- Don't big-bang-move files on the active branch.diff --git a/frontend/src/scenes/max/CLAUDE.md b/frontend/src/scenes/max/CLAUDE.mdnew file mode 120000index 000000000000..47dc3e3d863c--- /dev/null+++ b/frontend/src/scenes/max/CLAUDE.md@@ -0,0 +1 @@+AGENTS.md\ No newline at end of filediff --git a/frontend/src/scenes/max/Context.tsx b/frontend/src/scenes/max/Context.tsxindex eb663a5c6143..91e03838f5a5 100644--- a/frontend/src/scenes/max/Context.tsx+++ b/frontend/src/scenes/max/Context.tsx@@ -1,5 +1,5 @@import clsx from 'clsx'-import { useActions, useValues } from 'kea'+import { BindLogic, useActions, useValues } from 'kea'import { useMemo } from 'react'import React from 'react'@@ -10,6 +10,7 @@ import { TaxonomicPopover } from 'lib/components/TaxonomicPopover/TaxonomicPopovimport { IconAction, IconEvent } from 'lib/lemon-ui/icons'import { ModeSelector } from './components/ModeSelector'+import { SandboxModeToggle } from './components/SandboxModeToggle'import { maxContextLogic } from './maxContextLogic'import { maxThreadLogic } from './maxThreadLogic'import {@@ -19,6 +20,7 @@ import {MaxInsightContext,MaxNotebookContext,} from './maxTypes'+import { posthogAiContextLogic } from './posthogAiContextLogic'function pluralize(count: number, word: string): string {return `${count} ${word}${count > 1 ? 's' : ''}`@@ -330,12 +332,45 @@ export function ContextToolInfoTags({ size = 'default' }: { size?: 'small' | 'de)}+/**+ * Sandbox-runtime chips, rendered from the flat `posthogAiContextLogic.chipsForDisplay`. The X on+ * each chip dispatches `detach(key)` — one removal path, no source distinction. Coexistence+ * sibling to `ContextTags` (LangGraph).+ */+export function SandboxContextTags({ size = 'default' }: { size?: 'small' | 'default' }): JSX.Element | null {+ const { chipsForDisplay } = useValues(posthogAiContextLogic)+ const { detach } = useActions(posthogAiContextLogic)++ if (chipsForDisplay.length === 0) {+ return null+ }++ return (+ <>+ {chipsForDisplay.map((chip) => (+ <Tooltip key={chip.key} title={chip.label}>+ <LemonTag+ icon={chip.icon as JSX.Element}+ onClose={() => detach(chip.key)}+ closable+ closeOnClick+ className={clsx('flex items-center text-secondary', size === 'small' ? 'max-w-20' : 'max-w-48')}+ >+ <span className="truncate min-w-0 flex-1">{chip.label}</span>+ </LemonTag>+ </Tooltip>+ ))}+ </>+ )+}+interface ContextDisplayProps {size?: 'small' | 'default'}export function ContextDisplay({ size = 'default' }: ContextDisplayProps): JSX.Element | null {- const { showContextUI, contextDisabledReason } = useValues(maxThreadLogic)+ const { showContextUI, contextDisabledReason, conversation, sandboxConversationKey } = useValues(maxThreadLogic)+ const isSandboxRuntime = conversation?.agent_runtime === 'sandbox'const { hasData, contextOptions, taxonomicGroupTypes, mainTaxonomicGroupType, toolContextItems } =useValues(maxContextLogic)const { handleTaxonomicFilterChange } = useActions(maxContextLogic)@@ -350,6 +385,7 @@ export function ContextDisplay({ size = 'default' }: ContextDisplayProps): JSX.E<div className="px-2 w-full"><div className="flex flex-wrap items-start gap-1 w-full"><ModeSelector />+ <SandboxModeToggle /><Tooltip title={contextDisabledReason ?? 'Add context to help PostHog AI answer your question'}>{/* Wrapper span prevents Base UI's Tooltip.Trigger from mergingprops into TaxonomicPopover. Without it, mergeProps treats@@ -372,8 +408,19 @@ export function ContextDisplay({ size = 'default' }: ContextDisplayProps): JSX.E/></span></Tooltip>- <ContextToolInfoTags size={size} />- <ContextTags size={size} />+ {isSandboxRuntime ? (+ sandboxConversationKey ? (+ // Same key maxThreadLogic's connect() uses, so both resolve the same instance+ <BindLogic logic={posthogAiContextLogic} props={{ conversationId: sandboxConversationKey }}>+ <SandboxContextTags size={size} />+ </BindLogic>+ ) : null+ ) : (+ <>+ <ContextToolInfoTags size={size} />+ <ContextTags size={size} />+ </>+ )}</div></div>)diff --git a/frontend/src/scenes/max/DangerousOperationApprovalCard.tsx b/frontend/src/scenes/max/DangerousOperationApprovalCard.tsxindex 7a2ba3fe2429..d744dc8f37c2 100644--- a/frontend/src/scenes/max/DangerousOperationApprovalCard.tsx+++ b/frontend/src/scenes/max/DangerousOperationApprovalCard.tsx@@ -1,21 +1,31 @@import { useValues } from 'kea'-import { IconWarning } from '@posthog/icons'+import { IconNotebook, IconWarning } from '@posthog/icons'import { Spinner } from '@posthog/lemon-ui'import { DangerousOperationResponse } from '~/queries/schema/schema-assistant-messages'import { maxThreadLogic } from './maxThreadLogic'+/**+ * `plan_approval` reuses this card for sandbox plan-mode approvals — it only swaps the icon+ * and the awaiting copy. `dangerous_operation` is the existing LangGraph default.+ */+export type ApprovalCardVariant = 'dangerous_operation' | 'plan_approval'+interface DangerousOperationApprovalCardProps {operation: DangerousOperationResponse+ variant?: ApprovalCardVariant}/*** In-thread approval card that shows a compact summary of the approval status.* The actual approval interaction happens in the input area (DangerousOperationInput).*/-export function DangerousOperationApprovalCard({ operation }: DangerousOperationApprovalCardProps): JSX.Element {+export function DangerousOperationApprovalCard({+ operation,+ variant = 'dangerous_operation',+}: DangerousOperationApprovalCardProps): JSX.Element {// Read both resolvedApprovalStatuses (frontend) and pendingApprovalsData (backend)// to ensure we show correct status for both new and historical approvalsconst { resolvedApprovalStatuses, pendingApprovalsData, isSharedThread } = useValues(maxThreadLogic)@@ -31,15 +41,18 @@ export function DangerousOperationApprovalCard({ operation }: DangerousOperationconst subject = isSharedThread ? 'User' : 'You'+ const isPlan = variant === 'plan_approval'+ const Icon = isPlan ? IconNotebook : IconWarning+// Show pending state while waiting for resolutionif (!resolvedStatus) {return (<div className="flex text-xs text-muted"><div className="flex items-center justify-center size-5">- <IconWarning />+ <Icon /></div><div className="flex items-center gap-1 flex-1 min-w-0">- <span>Awaiting approval...</span>+ <span>{isPlan ? 'Awaiting plan approval...' : 'Awaiting approval...'}</span><Spinner className="size-3" /></div></div>@@ -59,7 +72,7 @@ export function DangerousOperationApprovalCard({ operation }: DangerousOperationreturn (<div className="flex text-xs text-muted"><div className="flex items-center justify-center size-5">- <IconWarning />+ <Icon /></div><div className="flex items-center gap-1 flex-1 min-w-0"><span>{text}</span>diff --git a/frontend/src/scenes/max/Max.tsx b/frontend/src/scenes/max/Max.tsxindex c783c182a438..fdf8de99472a 100644--- a/frontend/src/scenes/max/Max.tsx+++ b/frontend/src/scenes/max/Max.tsx@@ -38,7 +38,7 @@ import { HistoryPreview } from './HistoryPreview'import { Intro } from './Intro'import { MaxLogicProps, SIDE_PANEL_PANEL_ID, maxLogic } from './maxLogic'import { MaxThreadLogicProps, maxThreadLogic } from './maxThreadLogic'-import { Thread } from './Thread'+import { SandboxComposerSurfaces, Thread } from './Thread'export const scene: SceneExport = {component: Max,@@ -147,6 +147,7 @@ export const MaxInstance = React.memo(function MaxInstance({ sidePanel, tabId }:</div>)}<Thread className={cn('p-3', sidePanel && 'p-1')} />+ <SandboxComposerSurfaces />{!conversation?.has_unsupported_content && (<SidebarQuestionInput isSticky sidePanel={sidePanel} />)}diff --git a/frontend/src/scenes/max/Thread.tsx b/frontend/src/scenes/max/Thread.tsxindex a5640dc81133..7ed226b261b6 100644--- a/frontend/src/scenes/max/Thread.tsx+++ b/frontend/src/scenes/max/Thread.tsx@@ -1,11 +1,9 @@import clsx from 'clsx'-import { useActions, useValues } from 'kea'+import { BindLogic, useActions, useValues } from 'kea'import posthog from 'posthog-js'import React, { useLayoutEffect, useMemo, useState } from 'react'import {- IconBrain,- IconCheck,IconChevronRight,IconCollapse,IconCopy,@@ -27,6 +25,7 @@ import {LemonButtonPropsBase,LemonCheckbox,LemonDialog,+ LemonDivider,LemonInput,LemonSkeleton,Tooltip,@@ -38,11 +37,9 @@ import {SeriesSummary,} from 'lib/components/Cards/InsightCard/InsightDetails'import { TopHeading } from 'lib/components/Cards/InsightCard/TopHeading'-import { CodeSnippet, Language } from 'lib/components/CodeSnippet/CodeSnippet'import { NotFound } from 'lib/components/NotFound'import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'import { cn } from 'lib/utils/css-classes'-import { inStorybookTestRunner } from 'lib/utils/dom'import { pluralize } from 'lib/utils/strings'import { preflightLogic } from 'scenes/PreflightCheck/preflightLogic'import { sceneLogic } from 'scenes/sceneLogic'@@ -69,8 +66,11 @@ import { PendingApproval, Region } from '~/types'import { LogEntry } from 'products/tasks/frontend/lib/parse-logs'+import { LangGraphActivity, ShimmeringContent } from './components/Activity'import { FeedbackDisplay } from './components/FeedbackDisplay'import { MaxWebAnalyticsNudge } from './components/MaxWebAnalyticsNudge'+import { SandboxContextUsage } from './components/SandboxContextUsage'+import { SandboxResourcesBar } from './components/SandboxResourcesBar'import { ContextSummary } from './Context'import { DangerousOperationApprovalCard } from './DangerousOperationApprovalCard'import { FeedbackPrompt } from './FeedbackPrompt'@@ -80,17 +80,16 @@ import { EnhancedToolCall, ToolRegistration, getToolDefinitionFromToolCall } froimport { maxGlobalLogic } from './maxGlobalLogic'import { ThreadMessage, maxLogic } from './maxLogic'import { maxThreadLogic } from './maxThreadLogic'+import { AssistantFailureMessage } from './messages/AssistantFailureMessage'import { MessageTemplate } from './messages/MessageTemplate'import { MultiQuestionFormRecap } from './messages/MultiQuestionForm'import { NotebookArtifactAnswer } from './messages/NotebookArtifactAnswer'+import { ReasoningAnswer } from './messages/ReasoningAnswer'import { SessionSummarizationProgress } from './messages/SessionSummarizationProgress'-import {- RecordingsWidget,- SummarizeSessionsWidget,- UIPayloadAnswer,- isRenderableUIPayloadTool,-} from './messages/UIPayloadAnswer'-import { VisualizationArtifactAnswer } from './messages/VisualizationArtifactAnswer'+import { RecordingsWidget, isRenderableUIPayloadTool } from './messages/UIPayloadAnswer'+import { VisualizationArtifact } from './messages/VisualizationArtifact'+import { SandboxThreadView } from './sandbox/components/SandboxThreadView'+import { sandboxStreamLogic } from './sandboxStreamLogic'import { MAX_SLASH_COMMANDS, SlashCommandName } from './slash-commands'import { TicketPrompt } from './TicketPrompt'import { getTicketPromptData, getTicketSummaryData, isTicketConfirmationMessage } from './ticketUtils'@@ -117,6 +116,67 @@ function isErrorMessage(message: ThreadMessage): boolean {}export function Thread({ className }: { className?: string }): JSX.Element | null {+ const { conversation, sandboxConversationKey, isConvertedConversation } = useValues(maxThreadLogic)+ const isSandboxRuntime = conversation?.agent_runtime === 'sandbox'++ const containerClassName = cn(+ '@container/thread flex flex-col items-stretch w-full max-w-180 self-center gap-1.5 grow mx-auto',+ className+ )++ // Born-sandbox conversation (no legacy history): render only the sandbox thread.+ if (isSandboxRuntime && !isConvertedConversation) {+ if (!sandboxConversationKey) {+ return null+ }+ return (+ <div className={containerClassName}>+ {/* Same key maxThreadLogic's connect() uses, so both resolve the same instance */}+ <BindLogic+ logic={sandboxStreamLogic}+ props={{ streamKey: sandboxConversationKey, conversationId: sandboxConversationKey }}+ >+ <SandboxThreadView />+ </BindLogic>+ </div>+ )+ }++ // Converted conversation: the full legacy thread, a "history was converted" divider, then the+ // live sandbox thread — all in one scroll container so auto-scroll lands at the sandbox bottom.+ if (isConvertedConversation) {+ if (!sandboxConversationKey) {+ return null+ }+ return (+ <div className={containerClassName}>+ <LegacyThread showTrailers={false} />+ <LemonDivider dashed label="Message history was converted to the new format" className="my-3" />+ <BindLogic+ logic={sandboxStreamLogic}+ props={{ streamKey: sandboxConversationKey, conversationId: sandboxConversationKey }}+ >+ <SandboxThreadView />+ </BindLogic>+ </div>+ )+ }++ // Pure LangGraph conversation.+ return (+ <div className={containerClassName}>+ <LegacyThread showTrailers />+ </div>+ )+}++/**+ * LangGraph thread renderer: renders `maxThreadLogic.threadGrouped` (message history), loading+ * skeletons, or a NotFound fallback. `showTrailers` gates the feedback / ticket prompts so a+ * converted conversation renders them once at the true bottom (below the sandbox thread), not+ * wedged above the conversion divider.+ */+function LegacyThread({ showTrailers }: { showTrailers: boolean }): JSX.Element | null {const { conversationLoading, messagesLoading, conversationId } = useValues(maxLogic)const { threadGrouped, streamingActive, threadLoading, sandboxEntries } = useValues(maxThreadLogic)const sandboxModeEnabled = useFeatureFlag('PHAI_SANDBOX_MODE')@@ -132,161 +192,174 @@ export function Thread({ className }: { className?: string }): JSX.Element | nul[threadGrouped, streamingActive])- return (- <div- className={cn(- '@container/thread flex flex-col items-stretch w-full max-w-180 self-center gap-1.5 grow mx-auto',- className- )}- >- {(conversationLoading || messagesLoading) && threadGrouped.length === 0 ? (- <>- <MessageGroupSkeleton groupType="human" />- <MessageGroupSkeleton groupType="ai" className="opacity-80" />- <MessageGroupSkeleton groupType="human" className="opacity-65" />- <MessageGroupSkeleton groupType="ai" className="opacity-40" />- <MessageGroupSkeleton groupType="human" className="opacity-20" />- <MessageGroupSkeleton groupType="ai" className="opacity-10" />- <MessageGroupSkeleton groupType="human" className="opacity-5" />- </>- ) : threadGrouped.length > 0 ? (- <>- {(() => {- // Track the current trace_id as we iterate forward through messages- let currentTraceId: string | undefined-- return threadGrouped.map((message, index) => {- // Update trace_id when we encounter a human message- if (message.type === 'human' && 'trace_id' in message && message.trace_id) {- currentTraceId = message.trace_id- }+ return (conversationLoading || messagesLoading) && threadGrouped.length === 0 ? (+ <>+ <MessageGroupSkeleton groupType="human" />+ <MessageGroupSkeleton groupType="ai" className="opacity-80" />+ <MessageGroupSkeleton groupType="human" className="opacity-65" />+ <MessageGroupSkeleton groupType="ai" className="opacity-40" />+ <MessageGroupSkeleton groupType="human" className="opacity-20" />+ <MessageGroupSkeleton groupType="ai" className="opacity-10" />+ <MessageGroupSkeleton groupType="human" className="opacity-5" />+ </>+ ) : threadGrouped.length > 0 ? (+ <>+ {(() => {+ // Track the current trace_id as we iterate forward through messages+ let currentTraceId: string | undefined++ return threadGrouped.map((message, index) => {+ // Update trace_id when we encounter a human message+ if (message.type === 'human' && 'trace_id' in message && message.trace_id) {+ currentTraceId = message.trace_id+ }- // Hide failed AI messages when retrying- if (threadLoading && isErrorMessage(message)) {- return null- }+ // Hide failed AI messages when retrying+ if (threadLoading && isErrorMessage(message)) {+ return null+ }- // Hide old failed attempts - only show the most recent error- if (isErrorMessage(message)) {- const hasNewerError = threadGrouped.slice(index + 1).some(isErrorMessage)- if (hasNewerError) {- return null- }- }+ // Hide old failed attempts - only show the most recent error+ if (isErrorMessage(message)) {+ const hasNewerError = threadGrouped.slice(index + 1).some(isErrorMessage)+ if (hasNewerError) {+ return null+ }+ }- // Hide duplicate human messages from retry pattern: Human → AI Error → Human (duplicate)- // This specific pattern only occurs when "Try again" is clicked after a failure- if (message.type === 'human' && 'content' in message && index >= 2) {- const prevMessage = threadGrouped[index - 1]- const prevPrevMessage = threadGrouped[index - 2]+ // Hide duplicate human messages from retry pattern: Human → AI Error → Human (duplicate)+ // This specific pattern only occurs when "Try again" is clicked after a failure+ if (message.type === 'human' && 'content' in message && index >= 2) {+ const prevMessage = threadGrouped[index - 1]+ const prevPrevMessage = threadGrouped[index - 2]- const isRetryPattern =- isErrorMessage(prevMessage) &&- prevPrevMessage.type === 'human' &&- 'content' in prevPrevMessage &&- prevPrevMessage.content === message.content+ const isRetryPattern =+ isErrorMessage(prevMessage) &&+ prevPrevMessage.type === 'human' &&+ 'content' in prevPrevMessage &&+ prevPrevMessage.content === message.content- if (isRetryPattern) {- return null- }- }+ if (isRetryPattern) {+ return null+ }+ }- // Hide UI payload answers that are not renderable to prevent rendering an empty message component- if (- isAssistantToolCallMessage(message) &&- (!message.ui_payload ||- !isRenderableUIPayloadTool(Object.keys(message.ui_payload)[0], message.ui_payload))- ) {- return null- }+ // Hide UI payload answers that are not renderable to prevent rendering an empty message component+ if (+ isAssistantToolCallMessage(message) &&+ (!message.ui_payload ||+ !isRenderableUIPayloadTool(Object.keys(message.ui_payload)[0], message.ui_payload))+ ) {+ return null+ }- const nextMessage = threadGrouped[index + 1]- const isLastInGroup =- !nextMessage || (message.type === 'human') !== (nextMessage.type === 'human')+ const nextMessage = threadGrouped[index + 1]+ const isLastInGroup = !nextMessage || (message.type === 'human') !== (nextMessage.type === 'human')- // Hiding rating buttons after /feedback and /ticket command outputs- const prevMessage = threadGrouped[index - 1]- const isSlashCommandResponse =- message.type !== 'human' &&- prevMessage?.type === 'human' &&- 'content' in prevMessage &&- (prevMessage.content.startsWith(SlashCommandName.SlashFeedback) ||- prevMessage.content.startsWith(SlashCommandName.SlashTicket))+ // Hiding rating buttons after /feedback and /ticket command outputs+ const prevMessage = threadGrouped[index - 1]+ const isSlashCommandResponse =+ message.type !== 'human' &&+ prevMessage?.type === 'human' &&+ 'content' in prevMessage &&+ (prevMessage.content.startsWith(SlashCommandName.SlashFeedback) ||+ prevMessage.content.startsWith(SlashCommandName.SlashTicket))- // Also hide for ticket confirmation messages- const isTicketConfirmation = isTicketConfirmationMessage(message)+ // Also hide for ticket confirmation messages+ const isTicketConfirmation = isTicketConfirmationMessage(message)- // Check if this message is a ticket summary that needs the ticket creation button- const isTicketSummaryMessage = ticketSummaryData && ticketSummaryData.messageIndex === index+ // Check if this message is a ticket summary that needs the ticket creation button+ const isTicketSummaryMessage = ticketSummaryData && ticketSummaryData.messageIndex === index- // For AI messages, use the current trace_id from the preceding human message- const messageTraceId = message.type !== 'human' ? currentTraceId : undefined+ // For AI messages, use the current trace_id from the preceding human message+ const messageTraceId = message.type !== 'human' ? currentTraceId : undefined- return (- <React.Fragment key={`${conversationId}-${index}`}>- <TraceIdProvider value={messageTraceId}>- <Message- message={message}- nextMessage={nextMessage}- isLastInGroup={isLastInGroup}- isFinal={index === threadGrouped.length - 1}- isSlashCommandResponse={isSlashCommandResponse || isTicketConfirmation}- />- </TraceIdProvider>- {sandboxModeEnabled &&- sandboxEntries.length > 0 &&- isAssistantMessage(message) &&- message.id?.startsWith('sandbox-') &&- isLastInGroup && <SandboxActivityPanel entries={sandboxEntries} />}- {conversationId &&- isTicketSummaryMessage &&- (ticketSummaryData.discarded ? (- <p className="m-0 ml-1 mt-1 text-xs text-muted italic">- Ticket creation discarded- </p>- ) : (- <TicketPrompt- conversationId={conversationId}- traceId={traceId}- summary={ticketSummaryData.summary}- />- ))}- </React.Fragment>- )- })- })()}- {conversationId && isPromptVisible && !streamingActive && (- <MessageTemplate type="ai">- <div className="flex flex-col gap-2">- <span className="text-xs text-muted">How is PostHog AI doing? (optional)</span>- <FeedbackDisplay conversationId={conversationId} />- </div>- </MessageTemplate>- )}- {conversationId && isDetailedFeedbackVisible && !streamingActive && (- <FeedbackPrompt conversationId={conversationId} traceId={traceId} />- )}- {conversationId && isThankYouVisible && !streamingActive && (- <MessageTemplate type="ai">- <p className="m-0 text-sm text-secondary">Thanks for your feedback and using PostHog AI!</p>- </MessageTemplate>- )}- {conversationId && ticketPromptData.needed && (- <TicketPrompt- conversationId={conversationId}- traceId={traceId}- initialText={ticketPromptData.initialText}- />- )}- </>- ) : (- conversationId && (- <div className="flex flex-1 items-center justify-center">- <NotFound object="conversation" className="m-0" />+ return (+ <React.Fragment key={`${conversationId}-${index}`}>+ <TraceIdProvider value={messageTraceId}>+ <Message+ message={message}+ nextMessage={nextMessage}+ isLastInGroup={isLastInGroup}+ isFinal={index === threadGrouped.length - 1}+ isSlashCommandResponse={isSlashCommandResponse || isTicketConfirmation}+ />+ </TraceIdProvider>+ {sandboxModeEnabled &&+ sandboxEntries.length > 0 &&+ isAssistantMessage(message) &&+ message.id?.startsWith('sandbox-') &&+ isLastInGroup && <SandboxActivityPanel entries={sandboxEntries} />}+ {conversationId &&+ isTicketSummaryMessage &&+ (ticketSummaryData.discarded ? (+ <p className="m-0 ml-1 mt-1 text-xs text-muted italic">Ticket creation discarded</p>+ ) : (+ <TicketPrompt+ conversationId={conversationId}+ traceId={traceId}+ summary={ticketSummaryData.summary}+ />+ ))}+ </React.Fragment>+ )+ })+ })()}+ {showTrailers && conversationId && isPromptVisible && !streamingActive && (+ <MessageTemplate type="ai">+ <div className="flex flex-col gap-2">+ <span className="text-xs text-muted">How is PostHog AI doing? (optional)</span>+ <FeedbackDisplay conversationId={conversationId} /></div>- )+ </MessageTemplate>+ )}+ {showTrailers && conversationId && isDetailedFeedbackVisible && !streamingActive && (+ <FeedbackPrompt conversationId={conversationId} traceId={traceId} />+ )}+ {showTrailers && conversationId && isThankYouVisible && !streamingActive && (+ <MessageTemplate type="ai">+ <p className="m-0 text-sm text-secondary">Thanks for your feedback and using PostHog AI!</p>+ </MessageTemplate>+ )}+ {showTrailers && conversationId && ticketPromptData.needed && (+ <TicketPrompt+ conversationId={conversationId}+ traceId={traceId}+ initialText={ticketPromptData.initialText}+ />)}+ </>+ ) : conversationId ? (+ <div className="flex flex-1 items-center justify-center">+ <NotFound object="conversation" className="m-0" /></div>+ ) : null+}++/**+ * Persistent sandbox surfaces mounted between the thread and the sticky composer: the+ * "PostHog resources used" bar and the context-usage indicator. Both read `sandboxStreamLogic`+ * values directly, so this binds the same logic instance `Thread`'s sandbox path uses. Renders+ * nothing for non-sandbox conversations; the inner components hide themselves when empty.+ */+export function SandboxComposerSurfaces(): JSX.Element | null {+ const { conversation, sandboxConversationKey } = useValues(maxThreadLogic)+ const sandboxModeEnabled = useFeatureFlag('PHAI_SANDBOX_MODE')++ if (conversation?.agent_runtime !== 'sandbox' || !sandboxModeEnabled || !sandboxConversationKey) {+ return null+ }++ return (+ <BindLogic+ logic={sandboxStreamLogic}+ props={{ streamKey: sandboxConversationKey, conversationId: sandboxConversationKey }}+ >+ <div className="w-full max-w-180 self-center mx-auto">+ <SandboxResourcesBar />+ <SandboxContextUsage />+ </div>+ </BindLogic>)}@@ -678,7 +751,7 @@ const Message = React.memo(function Message({} else if (isArtifactMessage(message)) {if (isVisualizationArtifactContent(message.content)) {return (- <VisualizationArtifactAnswer+ <VisualizationArtifactkey={key}message={message}content={message.content}@@ -786,21 +859,20 @@ const TextAnswer = React.forwardRef<HTMLDivElement, TextAnswerProps>(function Te})(): null+ if (isFailureMessage(message)) {+ return (+ <AssistantFailureMessage id={message.id || 'error'} content={message.content} ref={ref} action={action} />+ )+ }+return (<MessageTemplatetype="ai"- boxClassName={message.status === 'error' || message.type === 'ai/failure' ? 'border-danger' : undefined}+ boxClassName={message.status === 'error' ? 'border-danger' : undefined}ref={ref}action={action}>- {message.content ? (- <MarkdownMessage content={message.content} id={message.id || 'in-progress'} />- ) : (- <MarkdownMessage- content={message.content || '*PostHog AI has failed to generate an answer. Please try again.*'}- id={message.id || 'error'}- />- )}+ <MarkdownMessage content={message.content || ''} id={message.id || 'in-progress'} /></MessageTemplate>)})@@ -931,314 +1003,6 @@ function PlanningAnswer({ toolCall, isLastPlanningMessage = true }: PlanningAnsw)}-function ShimmeringContent({ children }: { children: React.ReactNode }): JSX.Element {- const isTextContent = typeof children === 'string'-- if (isTextContent) {- return (- <span- className="bg-clip-text text-transparent"- style={{- backgroundImage:- 'linear-gradient(in oklch 90deg, var(--text-3000), var(--muted-3000), var(--trace-3000), var(--muted-3000), var(--text-3000))',- backgroundSize: '200% 100%',- animation: 'shimmer 3s linear infinite',- }}- >- {children}- </span>- )- }-- return (- <span- className="inline-flex min-w-0 max-w-full"- style={{- animation: 'shimmer-opacity 3s linear infinite',- }}- >- {children}- </span>- )-}--function handleThreeDots(content: string, isInProgress: boolean): string {- if (content.at(0) === '[' && content.at(-1) === ')') {- // Skip ... for web search `updates`, where each is a Markdown-formatted link to a search results, _not_ an action- return content- }- if (!content.endsWith('...') && !content.endsWith('…') && !content.endsWith('.') && isInProgress) {- return content + '...'- } else if ((content.endsWith('...') || content.endsWith('…')) && !isInProgress) {- return content.replace(/[…]/g, '').replace(/[.]/g, '')- }- return content-}--function AssistantActionComponent({- id,- content,- substeps,- state,- icon,- animate = true,- showCompletionIcon = true,- widget = null,- isResultExpanded = false,- toolCall = null,-}: {- id: string- content: string- // actually a markdown message- substeps: string[]- state: ExecutionStatus- icon?: React.ReactNode- animate?: boolean- showCompletionIcon?: boolean- widget?: JSX.Element | null- isResultExpanded?: boolean- toolCall?: EnhancedToolCall | null-}): JSX.Element {- const isPending = state === 'pending'- const isCompleted = state === 'completed'- const isInProgress = state === 'in_progress'- const isFailed = state === 'failed'- const showSubstepsChevron = !!substeps.length || !!toolCall?.result?.content- // Initialize with the same logic as the effect to prevent flickering- const [isSubstepsExpanded, setIsSubstepsExpanded] = useState(showSubstepsChevron && !(isCompleted || isFailed))- const [showToolCallJson, setShowToolCallJson] = useState(false)- const [showResultJson, setShowResultJson] = useState(false)-- useLayoutEffect(() => {- setIsSubstepsExpanded(showSubstepsChevron && !(isCompleted || isFailed))- }, [showSubstepsChevron, isCompleted, isFailed])-- let markdownContent = <MarkdownMessage id={id} content={content} />- const result = toolCall?.result- const uiPayload = result?.ui_payload- const executedSQLQuery =- typeof uiPayload?.execute_sql === 'string'- ? uiPayload.execute_sql- : toolCall?.name === 'execute_sql' && typeof toolCall.args.query === 'string'- ? toolCall.args.query- : null-- return (- <div className="flex flex-col rounded transition-all duration-500 flex-1 min-w-0 gap-1 text-xs">- <div- className={clsx(- 'transition-all duration-500 flex select-none min-w-0',- (isPending || isFailed) && 'text-muted',- !isInProgress && !isPending && !isFailed && 'text-default',- !showSubstepsChevron ? 'cursor-default' : 'cursor-pointer'- )}- onClick={showSubstepsChevron ? () => setIsSubstepsExpanded(!isSubstepsExpanded) : undefined}- aria-label={- showSubstepsChevron- ? isSubstepsExpanded- ? 'Collapse history'- : 'Expand history'- : isResultExpanded- ? 'Collapse result'- : 'Expand result'- }- >- {icon && (- <div className="flex items-center justify-center size-5">- {isInProgress && animate ? (- <ShimmeringContent>{icon}</ShimmeringContent>- ) : (- <span className={clsx('inline-flex', isInProgress && 'text-muted')}>{icon}</span>- )}- </div>- )}- <div className="flex items-center gap-1 flex-1 min-w-0 h-full">- <div className="min-w-0">- {isInProgress && animate ? (- <ShimmeringContent>{markdownContent}</ShimmeringContent>- ) : (- <span className={clsx('inline-flex', isInProgress && 'text-muted')}>{markdownContent}</span>- )}- </div>- {showSubstepsChevron && (- <div className="relative flex-shrink-0 flex items-start justify-center h-full pt-px">- <button className="inline-flex items-center hover:opacity-70 transition-opacity flex-shrink-0 cursor-pointer">- <span- className={clsx(- 'transform transition-transform',- isSubstepsExpanded && 'rotate-90'- )}- >- <IconChevronRight />- </span>- </button>- </div>- )}- {isCompleted && showCompletionIcon && <IconCheck className="text-success size-3" />}- {isFailed && showCompletionIcon && <IconX className="text-danger size-3" />}- </div>- </div>- {isSubstepsExpanded && substeps && substeps.length > 0 && (- <div- className={clsx(- 'space-y-1 border-l-2 border-border-secondary',- icon && 'pl-3.5 ml-[calc(0.775rem)]'- )}- >- {substeps.map((substep, substepIndex) => {- const isCurrentSubstep = substepIndex === substeps.length - 1- const isCompletedSubstep = substepIndex < substeps.length - 1 || isCompleted-- return (- <div key={substepIndex} className="animate-fade-in">- <MarkdownMessage- id={id}- className={clsx(- 'leading-relaxed',- isFailed && 'text-danger',- !isFailed && isCompletedSubstep && 'text-muted',- !isFailed && isCurrentSubstep && !isCompleted && 'text-secondary'- )}- content={handleThreeDots(substep ?? '', true)}- />- </div>- )- })}- </div>- )}- {widget}- {/* Render summarize_sessions UI payload outside accordion so "Open report" is always visible */}- {!!uiPayload?.summarize_sessions && result && (- <SummarizeSessionsWidget- payload={uiPayload.summarize_sessions}- title={toolCall?.args.summary_title as string | undefined}- />- )}- {toolCall && isSubstepsExpanded && (- <>- {!!uiPayload &&- isRenderableUIPayloadTool(toolCall.name, uiPayload) &&- Object.entries(uiPayload)- .filter(([toolName]) => toolName !== 'summarize_sessions')- .map(([toolName, toolPayload]) => (- <div- key={`${result?.tool_call_id}-${toolName}`}- className="ml-3 border-l-2 border-border-secondary pl-3.5"- >- <UIPayloadAnswer- toolCallId={result!.tool_call_id}- toolName={toolName}- toolPayload={toolPayload}- />- </div>- ))}- {executedSQLQuery && (- <div className="ml-3 border-l-2 border-border-secondary pl-3.5 flex flex-col gap-1">- <b className="text-secondary">SQL query</b>- <CodeSnippet language={Language.SQL} className="text-xs" compact>- {executedSQLQuery}- </CodeSnippet>- </div>- )}- <div className="ml-3 border-l-2 border-border-secondary pl-3.5 flex flex-col gap-1">- <LemonButton- size="xxsmall"- type="tertiary"- onClick={(e) => {- e.stopPropagation()- setShowToolCallJson(!showToolCallJson)- }}- tooltip="Tool call arguments as JSON"- tooltipPlacement="top-start"- className="w-fit"- >- <span className="flex items-center gap-1">- <b>Tool called:</b>- <span className="text-secondary">{toolCall.name}</span>- <span- className={clsx('transform transition-transform', showToolCallJson && 'rotate-90')}- >- <IconChevronRight />- </span>- </span>- </LemonButton>- {showToolCallJson && (- <CodeSnippet language={Language.JSON} className="text-xs">- {JSON.stringify(toolCall.args, null, 2)}- </CodeSnippet>- )}- {result && result.content && (- <React.Fragment>- <LemonButton- size="xxsmall"- type="tertiary"- onClick={(e) => {- e.stopPropagation()- setShowResultJson(!showResultJson)- }}- tooltip="Show tool call results"- tooltipPlacement="top-start"- className="w-fit"- >- <span className="flex items-center gap-1">- <b>Tool result:</b>- <span className="text-secondary">{result.content.slice(0, 20)}...</span>- <span- className={clsx(- 'transform transition-transform',- showResultJson && 'rotate-90'- )}- >- <IconChevronRight />- </span>- </span>- </LemonButton>- {showResultJson && (- <div className="border rounded p-2 bg-surface-primary">- <MarkdownMessage- id={`${toolCall.id}-result`}- content={result.content}- className="text-xs [&_code]:text-xs"- />- </div>- )}- </React.Fragment>- )}- </div>- </>- )}- </div>- )-}--interface ReasoningAnswerProps {- content: string- completed: boolean- id: string- showCompletionIcon?: boolean- animate?: boolean-}--function ReasoningAnswer({- content,- completed,- id,- showCompletionIcon = true,- animate = false,-}: ReasoningAnswerProps): JSX.Element {- return (- <AssistantActionComponent- id={id}- content={completed ? 'Thought' : content}- substeps={completed ? [content] : []}- state={completed ? ExecutionStatus.Completed : ExecutionStatus.InProgress}- icon={<IconBrain />}- animate={!inStorybookTestRunner() && animate} // Avoiding flaky snapshots in Storybook- showCompletionIcon={showCompletionIcon}- />- )-}-interface ToolCallsAnswerProps {toolCalls: EnhancedToolCall[]registeredToolMap: Record<string, ToolRegistration>@@ -1273,7 +1037,7 @@ function ToolCallsAnswer({ toolCalls, registeredToolMap }: ToolCallsAnswerProps)const [description, widgetDef] = getToolCallDescriptionAndWidgetDef(toolCall, registeredToolMap)const widget = renderToolCallWidget(widgetDef, toolCall.id)return (- <AssistantActionComponent+ <LangGraphActivitykey={toolCall.id}id={toolCall.id}content={description}@@ -1657,7 +1421,7 @@ function SuccessActions({function renderToolCallWidget(widgetDef: ToolCallWidgetDef | null, toolCallId: string): JSX.Element | null {switch (widgetDef?.widget) {case 'recordings':- return <RecordingsWidget toolCallId={toolCallId} filters={widgetDef.args} />+ return <RecordingsWidget toolCallId={toolCallId} filters={widgetDef.args} embedded />case 'session_summarization':return <SessionSummarizationProgress updates={widgetDef.args.updates} />default:diff --git a/frontend/src/scenes/max/components/Activity/ActivityPrimitives.test.tsx b/frontend/src/scenes/max/components/Activity/ActivityPrimitives.test.tsxnew file mode 100644index 000000000000..58491c6c05ab--- /dev/null+++ b/frontend/src/scenes/max/components/Activity/ActivityPrimitives.test.tsx@@ -0,0 +1,31 @@+import '@testing-library/jest-dom'++import { render, screen } from '@testing-library/react'++import { Activity } from './ActivityPrimitives'++function expectBefore(first: HTMLElement, second: HTMLElement): void {+ expect(first.compareDocumentPosition(second) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy()+}++describe('Activity', () => {+ it('renders details before the widget body', () => {+ render(+ <Activity+ id="tool-call"+ title={<span data-attr="header">Query trends</span>}+ status="in_progress"+ details={<div data-attr="details">Input</div>}+ >+ <div data-attr="widget">Visualization</div>+ </Activity>+ )++ const header = screen.getByTestId('header')+ const details = screen.getByTestId('details')+ const widget = screen.getByTestId('widget')++ expectBefore(header, details)+ expectBefore(details, widget)+ })+})diff --git a/frontend/src/scenes/max/components/Activity/ActivityPrimitives.tsx b/frontend/src/scenes/max/components/Activity/ActivityPrimitives.tsxnew file mode 100644index 000000000000..f0e424756d47--- /dev/null+++ b/frontend/src/scenes/max/components/Activity/ActivityPrimitives.tsx@@ -0,0 +1,318 @@+import clsx from 'clsx'+import React, { useLayoutEffect, useState } from 'react'++import { IconCheck, IconChevronRight, IconX } from '@posthog/icons'+import { LemonButton, Spinner } from '@posthog/lemon-ui'++import { MarkdownMessage } from '../../MarkdownMessage'++export type ActivityStatus = 'pending' | 'in_progress' | 'completed' | 'failed'++export function ShimmeringContent({ children }: { children: React.ReactNode }): JSX.Element {+ const isTextContent = typeof children === 'string'++ if (isTextContent) {+ return (+ <span+ className="bg-clip-text text-transparent"+ style={{+ backgroundImage:+ 'linear-gradient(in oklch 90deg, var(--text-3000), var(--muted-3000), var(--trace-3000), var(--muted-3000), var(--text-3000))',+ backgroundSize: '200% 100%',+ animation: 'shimmer 3s linear infinite',+ }}+ >+ {children}+ </span>+ )+ }++ return (+ <span+ className="inline-flex min-w-0 max-w-full"+ style={{+ animation: 'shimmer-opacity 3s linear infinite',+ }}+ >+ {children}+ </span>+ )+}++function activitySubstepText(content: string, isInProgress: boolean): string {+ if (content.at(0) === '[' && content.at(-1) === ')') {+ // Skip ... for web search `updates`, where each is a Markdown-formatted link to a search result.+ return content+ }+ if (!content.endsWith('...') && !content.endsWith('\u2026') && !content.endsWith('.') && isInProgress) {+ return content + '...'+ } else if ((content.endsWith('...') || content.endsWith('\u2026')) && !isInProgress) {+ return content.replace(/\u2026/g, '').replace(/[.]/g, '')+ }+ return content+}++export function ActivityStatusIcon({+ status,+ showCompletionIcon = true,+ showProgressIcon = false,+ failedIcon,+}: {+ status: ActivityStatus+ showCompletionIcon?: boolean+ showProgressIcon?: boolean+ failedIcon?: React.ReactNode+}): JSX.Element | null {+ if ((status === 'pending' || status === 'in_progress') && showProgressIcon) {+ return <Spinner className="size-3" />+ }+ if (status === 'completed' && showCompletionIcon) {+ return <IconCheck className="text-success size-3" />+ }+ if (status === 'failed' && showCompletionIcon) {+ return failedIcon ? <>{failedIcon}</> : <IconX className="text-danger size-3" />+ }+ return null+}++export function ActivityHeader({+ title,+ children,+ status,+ icon,+ animate = true,+ hasDetails,+ isDetailsExpanded,+ onToggleDetails,+ showCompletionIcon = true,+ showProgressIcon = false,+ failedIcon,+}: {+ title: React.ReactNode+ children?: React.ReactNode+ status: ActivityStatus+ icon?: React.ReactNode+ animate?: boolean+ hasDetails: boolean+ isDetailsExpanded: boolean+ onToggleDetails: () => void+ showCompletionIcon?: boolean+ showProgressIcon?: boolean+ failedIcon?: React.ReactNode+}): JSX.Element {+ const isPending = status === 'pending'+ const isInProgress = status === 'in_progress'+ const isFailed = status === 'failed'++ const titleNode =+ isInProgress && animate ? (+ <ShimmeringContent>{title}</ShimmeringContent>+ ) : (+ <span className={clsx('inline-flex', isInProgress && 'text-muted')}>{title}</span>+ )+ const statusIcon = (+ <ActivityStatusIcon+ status={status}+ showCompletionIcon={showCompletionIcon}+ showProgressIcon={showProgressIcon}+ failedIcon={failedIcon}+ />+ )++ return (+ <div+ className={clsx(+ 'transition-all duration-500 flex select-none min-w-0',+ (isPending || isFailed) && 'text-muted',+ !isInProgress && !isPending && !isFailed && 'text-default',+ hasDetails ? 'cursor-pointer' : 'cursor-default',+ hasDetails && 'rounded px-1 -mx-1 hover:bg-fill-button-tertiary-hover',+ hasDetails && isDetailsExpanded && 'bg-fill-button-tertiary-active'+ )}+ onClick={hasDetails ? onToggleDetails : undefined}+ aria-label={hasDetails ? (isDetailsExpanded ? 'Collapse history' : 'Expand history') : undefined}+ >+ {icon && (+ <div className="flex items-center justify-center size-5">+ {isInProgress && animate ? (+ <ShimmeringContent>{icon}</ShimmeringContent>+ ) : (+ <span className={clsx('inline-flex', isInProgress && 'text-muted')}>{icon}</span>+ )}+ </div>+ )}+ <div className="flex items-center gap-1 flex-1 min-w-0 h-full">+ {children ? (+ // The title/subtitle column grows to fill the row, so the subtitle (second line) gets the+ // full available width before it truncates and the chevron stays pinned to the right.+ <div className="flex flex-col flex-1 min-w-0">+ {/* Status icon rides the first line with the title; the second line is the subtitle. */}+ <div className="flex items-center gap-1 min-w-0">+ <div className="min-w-0">{titleNode}</div>+ {statusIcon}+ </div>+ <div className="text-muted truncate min-w-0">{children}</div>+ </div>+ ) : (+ <div className="min-w-0">{titleNode}</div>+ )}+ {hasDetails && (+ <div className="relative shrink-0 flex flex-col items-start justify-center h-full">+ <button className="inline-flex items-center hover:opacity-70 transition-opacity shrink-0 cursor-pointer">+ <span className={clsx('transform transition-transform', isDetailsExpanded && 'rotate-90')}>+ <IconChevronRight />+ </span>+ </button>+ </div>+ )}+ {!children && statusIcon}+ </div>+ </div>+ )+}++export function ActivitySubsteps({+ id,+ substeps,+ status,+}: {+ id: string+ substeps: string[]+ status: ActivityStatus+}): JSX.Element {+ const isCompleted = status === 'completed'+ const isFailed = status === 'failed'++ return (+ <>+ {substeps.map((substep, substepIndex) => {+ const isCurrentSubstep = substepIndex === substeps.length - 1+ const isCompletedSubstep = substepIndex < substeps.length - 1 || isCompleted++ return (+ <div key={substepIndex} className="animate-fade-in">+ <MarkdownMessage+ id={id}+ className={clsx(+ 'leading-relaxed',+ isFailed && 'text-danger',+ !isFailed && isCompletedSubstep && 'text-muted',+ !isFailed && isCurrentSubstep && !isCompleted && 'text-secondary'+ )}+ content={activitySubstepText(substep ?? '', status === 'in_progress')}+ />+ </div>+ )+ })}+ </>+ )+}++export function ActivityDetails({ children, hasIcon }: { children: React.ReactNode; hasIcon: boolean }): JSX.Element {+ return (+ <div className={clsx('space-y-1 border-l-2 border-border-secondary', hasIcon && 'pl-3.5 ml-[calc(0.775rem)]')}>+ {children}+ </div>+ )+}++export function ActivityToggleSection({+ title,+ summary,+ tooltip,+ children,+}: {+ title: React.ReactNode+ summary?: React.ReactNode+ tooltip?: string+ children: React.ReactNode+}): JSX.Element {+ const [isExpanded, setIsExpanded] = useState(false)++ return (+ <div className="flex flex-col gap-1">+ <LemonButton+ size="xxsmall"+ type="tertiary"+ onClick={(e) => {+ e.stopPropagation()+ setIsExpanded(!isExpanded)+ }}+ tooltip={tooltip}+ tooltipPlacement="top-start"+ className="w-fit"+ >+ <span className="flex items-center gap-1">+ <b>{title}</b>+ {summary && <span className="text-secondary">{summary}</span>}+ <span className={clsx('transform transition-transform', isExpanded && 'rotate-90')}>+ <IconChevronRight />+ </span>+ </span>+ </LemonButton>+ {isExpanded && children}+ </div>+ )+}++export function Activity({+ id,+ title,+ subtitle,+ status,+ icon,+ animate = true,+ showCompletionIcon = true,+ showProgressIcon = false,+ failedIcon,+ substeps = [],+ details = null,+ children = null,+}: {+ id: string+ title: React.ReactNode+ subtitle?: React.ReactNode+ status: ActivityStatus+ icon?: React.ReactNode+ animate?: boolean+ showCompletionIcon?: boolean+ showProgressIcon?: boolean+ failedIcon?: React.ReactNode+ substeps?: string[]+ details?: React.ReactNode+ children?: React.ReactNode+}): JSX.Element {+ const hasDetails = substeps.length > 0 || !!details+ const shouldExpandDetails = hasDetails && status !== 'completed' && status !== 'failed'+ const [isDetailsExpanded, setIsDetailsExpanded] = useState(shouldExpandDetails)++ useLayoutEffect(() => {+ setIsDetailsExpanded(shouldExpandDetails)+ }, [shouldExpandDetails])++ return (+ <div className="flex flex-col rounded transition-all duration-500 w-full min-w-0 gap-1 text-xs">+ <ActivityHeader+ title={title}+ status={status}+ icon={icon}+ animate={animate}+ hasDetails={hasDetails}+ isDetailsExpanded={isDetailsExpanded}+ onToggleDetails={() => setIsDetailsExpanded(!isDetailsExpanded)}+ showCompletionIcon={showCompletionIcon}+ showProgressIcon={showProgressIcon}+ failedIcon={failedIcon}+ >+ {subtitle}+ </ActivityHeader>+ {isDetailsExpanded && hasDetails && (+ <ActivityDetails hasIcon={!!icon}>+ {substeps.length > 0 && <ActivitySubsteps id={id} substeps={substeps} status={status} />}+ {details}+ </ActivityDetails>+ )}+ {children}+ </div>+ )+}diff --git a/frontend/src/scenes/max/components/Activity/LangGraphActivity.tsx b/frontend/src/scenes/max/components/Activity/LangGraphActivity.tsxnew file mode 100644index 000000000000..130c53e1f3dc--- /dev/null+++ b/frontend/src/scenes/max/components/Activity/LangGraphActivity.tsx@@ -0,0 +1,126 @@+import React from 'react'++import { CodeSnippet, Language } from 'lib/components/CodeSnippet/CodeSnippet'++import { TaskExecutionStatus as ExecutionStatus } from '~/queries/schema/schema-assistant-messages'++import { MarkdownMessage } from '../../MarkdownMessage'+import type { EnhancedToolCall } from '../../max-constants'+import { SummarizeSessionsWidget, UIPayloadAnswer, isRenderableUIPayloadTool } from '../../messages/UIPayloadAnswer'+import { Activity, ActivityToggleSection } from './ActivityPrimitives'++export function LangGraphActivity({+ id,+ content,+ substeps,+ state,+ icon,+ animate = true,+ showCompletionIcon = true,+ widget = null,+ toolCall = null,+}: {+ id: string+ content: string+ // actually a markdown message+ substeps: string[]+ state: ExecutionStatus+ icon?: React.ReactNode+ animate?: boolean+ showCompletionIcon?: boolean+ widget?: JSX.Element | null+ toolCall?: EnhancedToolCall | null+}): JSX.Element {+ const result = toolCall?.result+ const resultContent = result?.content+ const uiPayload = result?.ui_payload+ const executedSQLQuery =+ typeof uiPayload?.execute_sql === 'string'+ ? uiPayload.execute_sql+ : toolCall?.name === 'execute_sql' && typeof toolCall.args.query === 'string'+ ? toolCall.args.query+ : null++ const uiPayloadBody =+ toolCall && uiPayload && isRenderableUIPayloadTool(toolCall.name, uiPayload)+ ? Object.entries(uiPayload)+ .filter(([toolName]) => toolName !== 'summarize_sessions')+ .map(([toolName, toolPayload]) => (+ <UIPayloadAnswer+ key={`${result?.tool_call_id}-${toolName}`}+ toolCallId={result!.tool_call_id}+ toolName={toolName}+ toolPayload={toolPayload}+ embedded+ />+ ))+ : []++ const activityChildren = (+ <>+ {widget}+ {/* Render summarize_sessions UI payload outside details so "Open report" is always visible. */}+ {!!uiPayload?.summarize_sessions && result && (+ <SummarizeSessionsWidget+ payload={uiPayload.summarize_sessions}+ title={toolCall?.args.summary_title as string | undefined}+ />+ )}+ </>+ )++ // The tool call's details — UI payload, SQL, args, and result — live behind the chevron and only+ // surface once the call has produced a result. An in-flight call shows just the shimmering title,+ // with no expandable child.+ const details =+ toolCall && resultContent ? (+ <div className="flex flex-col gap-1">+ {uiPayloadBody.length > 0 && <div className="flex flex-col gap-2">{uiPayloadBody}</div>}+ {executedSQLQuery && (+ <div className="flex flex-col gap-1">+ <b className="text-secondary">SQL query</b>+ <CodeSnippet language={Language.SQL} className="text-xs" compact>+ {executedSQLQuery}+ </CodeSnippet>+ </div>+ )}+ <ActivityToggleSection+ title="Tool called:"+ summary={<span>{toolCall.name}</span>}+ tooltip="Tool call arguments as JSON"+ >+ <CodeSnippet language={Language.JSON} className="text-xs">+ {JSON.stringify(toolCall.args, null, 2)}+ </CodeSnippet>+ </ActivityToggleSection>+ <ActivityToggleSection+ title="Tool result:"+ summary={<span>{resultContent.slice(0, 20)}...</span>}+ tooltip="Show tool call results"+ >+ <div className="border rounded p-2 bg-surface-primary">+ <MarkdownMessage+ id={`${toolCall.id}-result`}+ content={resultContent}+ className="text-xs [&_code]:text-xs"+ />+ </div>+ </ActivityToggleSection>+ </div>+ ) : null++ return (+ <Activity+ id={id}+ title={<MarkdownMessage id={id} content={content} />}+ substeps={substeps}+ status={state}+ icon={icon}+ animate={animate}+ showCompletionIcon={showCompletionIcon}+ details={details}+ >+ {activityChildren}+ </Activity>+ )+}diff --git a/frontend/src/scenes/max/components/Activity/SandboxActivity.tsx b/frontend/src/scenes/max/components/Activity/SandboxActivity.tsxnew file mode 100644index 000000000000..beaf5cb2aee5--- /dev/null+++ b/frontend/src/scenes/max/components/Activity/SandboxActivity.tsx@@ -0,0 +1,39 @@+import { type ReactNode } from 'react'++import { Activity } from './ActivityPrimitives'+import type { ActivityStatus } from './ActivityPrimitives'++/**+ * Progress / status card for the sandbox runtime — a thin adapter over the shared `Activity` used by+ * `SandboxProgressItem` and the status/substep thread items. (Tool calls render via the dedicated+ * `SandboxToolActivity` bridge, not this.)+ */+export function SandboxActivity({+ id,+ content,+ substeps,+ state,+ icon,+ animate = true,+ showCompletionIcon = true,+}: {+ id: string+ content: ReactNode+ substeps: string[]+ state: ActivityStatus+ icon?: ReactNode+ animate?: boolean+ showCompletionIcon?: boolean+}): JSX.Element {+ return (+ <Activity+ id={id}+ title={content}+ substeps={substeps}+ status={state}+ icon={icon}+ animate={animate}+ showCompletionIcon={showCompletionIcon}+ />+ )+}diff --git a/frontend/src/scenes/max/components/Activity/index.ts b/frontend/src/scenes/max/components/Activity/index.tsnew file mode 100644index 000000000000..1781e41e3505--- /dev/null+++ b/frontend/src/scenes/max/components/Activity/index.ts@@ -0,0 +1,12 @@+export {+ Activity,+ ActivityDetails,+ ActivityHeader,+ ActivityStatusIcon,+ ActivitySubsteps,+ ActivityToggleSection,+ ShimmeringContent,+} from './ActivityPrimitives'+export type { ActivityStatus } from './ActivityPrimitives'+export { LangGraphActivity } from './LangGraphActivity'+export { SandboxActivity } from './SandboxActivity'diff --git a/frontend/src/scenes/max/components/InputFormArea.tsx b/frontend/src/scenes/max/components/InputFormArea.tsxindex 88a019c49c81..4748ac207c2b 100644--- a/frontend/src/scenes/max/components/InputFormArea.tsx+++ b/frontend/src/scenes/max/components/InputFormArea.tsx@@ -3,7 +3,7 @@ import { useCallback, useMemo, useRef, useState } from 'react'import useResizeObserver from 'use-resize-observer'import { IconCheck, IconWarning, IconX } from '@posthog/icons'-import { LemonButton, LemonDivider, LemonTabs, Spinner } from '@posthog/lemon-ui'+import { LemonButton, LemonDivider, LemonTabs, LemonTag, Spinner } from '@posthog/lemon-ui'import {DangerousOperationResponse,@@ -15,6 +15,8 @@ import { MarkdownMessage } from '../MarkdownMessage'import { maxThreadLogic } from '../maxThreadLogic'import { Option, OptionSelector } from './OptionSelector'import { MultiFieldQuestion, QuestionField, isFieldValid } from './QuestionField'+import { SandboxPermissionInput } from './SandboxPermissionInput'+import { SandboxQuestionInput } from './SandboxQuestionInput'function isQuestionComplete(q: MultiQuestionFormQuestion,@@ -402,10 +404,37 @@ function DangerousOperationInput({ operation }: DangerousOperationInputProps): J)}+/**+ * Compact badge showing the active ACP permission mode (e.g. plan vs default) for sandbox+ * conversations. Hidden when no mode has been reported. Reads the mode via `maxThreadLogic`'s+ * alias — this renders outside SandboxThread's BindLogic subtree, so it cannot bind the keyed+ * stream logic itself.+ */+export function SandboxModeBadge(): JSX.Element | null {+ const { conversation, sandboxCurrentMode } = useValues(maxThreadLogic)++ if (conversation?.agent_runtime !== 'sandbox' || !sandboxCurrentMode) {+ return null+ }++ const isPlan = sandboxCurrentMode === 'plan'+ return (+ <LemonTag size="small" type={isPlan ? 'highlight' : 'muted'}>+ {isPlan ? 'Plan mode' : 'Default mode'}+ </LemonTag>+ )+}+export function InputFormArea(): JSX.Element | null {// Use raw state values instead of selector to ensure re-renders on state changes- const { activeMultiQuestionForm, pendingApprovalProposalId, pendingApprovalsData, resolvedApprovalStatuses } =- useValues(maxThreadLogic)+ const {+ activeMultiQuestionForm,+ pendingApprovalProposalId,+ pendingApprovalsData,+ resolvedApprovalStatuses,+ sandboxConversationKey,+ pendingSandboxPermissionRequest,+ } = useValues(maxThreadLogic)// Build the approval object to display - only show if not yet resolved// Resolved approvals are shown as summaries in the chat thread, not in the input area@@ -430,6 +459,31 @@ export function InputFormArea(): JSX.Element | null {}}, [pendingApprovalProposalId, pendingApprovalsData, resolvedApprovalStatuses])+ // Sandbox permission requests take precedence in the input area, mirroring the LangGraph+ // dangerous-operation flow but driven by sandboxStreamLogic. A pending request only ever+ // originates from the sandbox stream, so its presence is sufficient — gating on `agent_runtime`+ // would strand approvals on new conversations whose runtime isn't resolved yet.+ if (pendingSandboxPermissionRequest) {+ // An `AskUserQuestion` rides the same permission rails but is a question, not an approval —+ // render the interactive question overlay instead of the approve/decline card.+ if (pendingSandboxPermissionRequest.questions?.length) {+ return (+ <SandboxQuestionInput+ key={pendingSandboxPermissionRequest.requestId}+ streamKey={sandboxConversationKey}+ request={pendingSandboxPermissionRequest}+ />+ )+ }+ return (+ <SandboxPermissionInput+ key={pendingSandboxPermissionRequest.requestId}+ streamKey={sandboxConversationKey}+ request={pendingSandboxPermissionRequest}+ />+ )+ }+if (activeDangerousOperationApproval) {return (<DangerousOperationInputdiff --git a/frontend/src/scenes/max/components/ModeSelector.tsx b/frontend/src/scenes/max/components/ModeSelector.tsxindex a3cd67e9ef2c..10d02cff9c14 100644--- a/frontend/src/scenes/max/components/ModeSelector.tsx+++ b/frontend/src/scenes/max/components/ModeSelector.tsx@@ -114,7 +114,6 @@ function buildGeneralTooltip(description: string, defaultTools: ToolDefinition[]interface GetModeOptionsParams {planModeEnabled: booleanresearchEnabled: boolean- sandboxModeEnabled: booleanfeatureFlags: Record<string, boolean | string>hasExistingMessages: boolean}@@ -122,7 +121,6 @@ interface GetModeOptionsParams {function getModeOptions({planModeEnabled,researchEnabled,- sandboxModeEnabled,featureFlags,hasExistingMessages,}: GetModeOptionsParams): LemonSelectSection<ModeValue>[] {@@ -170,24 +168,6 @@ function getModeOptions({})}- if (sandboxModeEnabled && !hasExistingMessages) {- specialOptions.push({- value: 'sandbox' as ModeValue,- label: (- <span className="flex items-center gap-1">- {SPECIAL_MODES.sandbox.name}- {SPECIAL_MODES.sandbox.alpha && (- <LemonTag size="small" type="danger">- ALPHA- </LemonTag>- )}- </span>- ),- icon: SPECIAL_MODES.sandbox.icon,- tooltip: <div>{SPECIAL_MODES.sandbox.description}</div>,- })- }-const modeEntries = Object.entries(MODE_DEFINITIONS).filter(([_, def]) => {if (def.flag && !featureFlags[FEATURE_FLAGS[def.flag]]) {return false@@ -226,13 +206,11 @@ function getModeOptions({}export function ModeSelector(): JSX.Element | null {- const { agentMode, isSandboxMode, contextDisabledReason, conversation, threadMessageCount } =- useValues(maxThreadLogic)- const { setAgentMode, setIsSandboxMode } = useActions(maxThreadLogic)+ const { agentMode, contextDisabledReason, conversation, threadMessageCount } = useValues(maxThreadLogic)+ const { setAgentMode } = useActions(maxThreadLogic)const { featureFlags } = useValues(featureFlagLogic)const researchEnabled = useFeatureFlag('MAX_DEEP_RESEARCH')const planModeEnabled = useFeatureFlag('PHAI_PLAN_MODE')- const sandboxModeEnabled = useFeatureFlag('PHAI_SANDBOX_MODE')const hasExistingMessages = threadMessageCount > 0const modeOptions = useMemo(@@ -240,35 +218,28 @@ export function ModeSelector(): JSX.Element | null {getModeOptions({planModeEnabled,researchEnabled,- sandboxModeEnabled,featureFlags,hasExistingMessages,}),- [planModeEnabled, researchEnabled, sandboxModeEnabled, featureFlags, hasExistingMessages]+ [planModeEnabled, researchEnabled, featureFlags, hasExistingMessages])const handleChange = useCallback((value: ModeValue): void => {posthog.capture('phai mode switched', {- previous_mode: isSandboxMode ? 'sandbox' : agentMode,+ previous_mode: agentMode,new_mode: value,})- if (value === 'sandbox') {- setIsSandboxMode(true)- setAgentMode(null)- } else {- setIsSandboxMode(false)- setAgentMode(value as AgentMode | null)- }+ setAgentMode(value as AgentMode | null)},- [agentMode, isSandboxMode, setAgentMode, setIsSandboxMode]+ [agentMode, setAgentMode])const isDeepResearch = conversation?.type === ConversationType.DeepResearchreturn (<LemonSelect- value={isDeepResearch ? 'research' : isSandboxMode ? 'sandbox' : agentMode}+ value={isDeepResearch ? 'research' : agentMode}onChange={handleChange}options={modeOptions}size="xxsmall"diff --git a/frontend/src/scenes/max/components/OptionSelector.tsx b/frontend/src/scenes/max/components/OptionSelector.tsxindex 9b14488fea1c..5febfd704163 100644--- a/frontend/src/scenes/max/components/OptionSelector.tsx+++ b/frontend/src/scenes/max/components/OptionSelector.tsx@@ -176,7 +176,7 @@ export function OptionSelector({autoFocus={true}/>) : (- <span className="my-1.5">Explain what you'd like instead..</span>+ <span className="my-1.5">Explain what you'd like instead.</span>)}</label>)}diff --git a/frontend/src/scenes/max/components/QuestionInput.test.tsx b/frontend/src/scenes/max/components/QuestionInput.test.tsxindex 3ed3fa138e07..5503e6f6d63a 100644--- a/frontend/src/scenes/max/components/QuestionInput.test.tsx+++ b/frontend/src/scenes/max/components/QuestionInput.test.tsx@@ -21,7 +21,7 @@ jest.mock({ virtual: true })-describe('QuestionInput slash command autocomplete', () => {+describe('QuestionInput', () => {let maxLogicInstance: ReturnType<typeof maxLogic.build>let threadLogicInstance: ReturnType<typeof maxThreadLogic.build>@@ -61,6 +61,38 @@ describe('QuestionInput slash command autocomplete', () => {const slashCommandItem = (): HTMLElement | null => screen.queryByText('/init')+ const flush = (): Promise<void> => new Promise((resolve) => setTimeout(resolve, 0))++ it('does not release a sandbox pre-warm when blur moves to the send button', async () => {+ // Simulate a completed warm; a release would clear the flag (and relay-cancel the warm Run).+ threadLogicInstance.cache.prewarmed = true+ threadLogicInstance.cache.prewarming = false++ const input = screen.getByRole('textbox') as HTMLTextAreaElement+ const sendButton = document.querySelector('[data-attr="max-send-message"]') as HTMLElement+ expect(sendButton).not.toBeNull()++ // Clicking send blurs the textarea before the click fires the send — the warm must survive.+ fireEvent.blur(input, { relatedTarget: sendButton })+ await flush()++ // Blur-to-send does not trigger releaseSandboxPrewarm, so the warm is untouched.+ expect(threadLogicInstance.cache.prewarmed).toBe(true)+ })++ it('releases a sandbox pre-warm when blur leaves the input for somewhere else', async () => {+ threadLogicInstance.cache.prewarmed = true+ threadLogicInstance.cache.prewarming = false++ const input = screen.getByRole('textbox') as HTMLTextAreaElement++ fireEvent.blur(input, { relatedTarget: null })+ await flush()++ // Blur-away triggers releaseSandboxPrewarm, which clears the flag (and relay-cancels any warm Run).+ expect(threadLogicInstance.cache.prewarmed).toBe(false)+ })+it('reopens the popover after Escape dismisses it and a fresh slash is typed', async () => {const input = screen.getByRole('textbox') as HTMLTextAreaElement@@ -76,4 +108,39 @@ describe('QuestionInput slash command autocomplete', () => {fireEvent.change(input, { target: { value: '/' } })await waitFor(() => expect(slashCommandItem()).toBeInTheDocument())})++ describe('stop button cancel state', () => {+ const sendButton = (): HTMLElement | null => document.querySelector('[data-attr="max-send-message"]')+ const stopButton = (): HTMLElement | null => document.querySelector('[data-attr="max-stop-generation"]')++ it('shows the stop affordance while streaming and not cancelling', async () => {+ threadLogicInstance.actions.reconnectToStream()+ await waitFor(() => expect(stopButton()).not.toBeNull())+ expect(sendButton()).toHaveAttribute('aria-disabled', 'true')+ })++ it('shows send (not stop) while cancelLoading is true', async () => {+ threadLogicInstance.actions.reconnectToStream()+ threadLogicInstance.actions.setCancelLoading(true)++ await waitFor(() => expect(sendButton()).not.toBeNull())+ expect(stopButton()).toBeNull()+ // The composer button reads "Cancelling…" via disabledReason, never "Let's bail".+ expect(screen.queryByText("Let's bail")).not.toBeInTheDocument()+ })++ it('returns to send (not stop) after cancel resolves and loading clears', async () => {+ threadLogicInstance.actions.reconnectToStream()+ threadLogicInstance.actions.setCancelLoading(true)+ await waitFor(() => expect(sendButton()).not.toBeNull())++ // Cancel resolves: streaming ends and cancelLoading clears -> threadLoading false.+ threadLogicInstance.actions.endStreaming()+ threadLogicInstance.actions.setCancelLoading(false)++ await waitFor(() => expect(sendButton()).not.toBeNull())+ expect(stopButton()).toBeNull()+ expect(screen.queryByText("Let's bail")).not.toBeInTheDocument()+ })+ })})diff --git a/frontend/src/scenes/max/components/QuestionInput.tsx b/frontend/src/scenes/max/components/QuestionInput.tsxindex c393ceeec60b..26c1555a251c 100644--- a/frontend/src/scenes/max/components/QuestionInput.tsx+++ b/frontend/src/scenes/max/components/QuestionInput.tsx@@ -166,8 +166,14 @@ export const QuestionInput = React.forwardRef<HTMLDivElement, QuestionInputPropsqueuedMessages,queueSubmitting,} = useValues(maxThreadLogic)- const { askMax, stopGeneration, completeThreadGeneration, setSupportOverrideEnabled, updateQueuedMessage } =- useActions(maxThreadLogic)+ const {+ askMax,+ stopGeneration,+ completeThreadGeneration,+ setSupportOverrideEnabled,+ updateQueuedMessage,+ releaseSandboxPrewarm,+ } = useActions(maxThreadLogic)const { isActive: handsFreeActive } = useValues(handsFreeLogic({ panelId: maxPanelId }))// Only the hands-free row needs bottom-aligned pills — it has the mic + submit pair// pinned to the bottom and pills sitting in normal flow look misaligned next to them.@@ -226,7 +232,7 @@ export const QuestionInput = React.forwardRef<HTMLDivElement, QuestionInputPropsconst hasQuestion = inputValue.trim().length > 0const isQueueingSubmission = queueingEnabled && threadLoading && hasQuestion- const showStopButton = threadLoading && !isQueueingSubmission+ const showStopButton = threadLoading && !isQueueingSubmission && !cancelLoading// Mirrors maxThreadLogic's `submissionDisabledReason` selector, but using the local input// value so the submit guard stays correct while the debounced sync to kea is still pending.@@ -373,7 +379,23 @@ export const QuestionInput = React.forwardRef<HTMLDivElement, QuestionInputPropsref={textAreaRef}value={isSharedThread ? '' : inputValue}onChange={handleQuestionChange}- onBlur={() => debouncedSetQuestion.flush()}+ onBlur={(e) => {+ debouncedSetQuestion.flush()+ // Release any sandbox pre-warm when the user leaves the+ // input without sending. No-op on LangGraph / unwarmed+ // conversations.+ //+ // But clicking the send button blurs the textarea *before*+ // its onClick fires the send — releasing here would cancel+ // the very warm Run the send is about to consume. When focus+ // moves to the send button, skip the release and let the send+ // path consume the warm (it does so without a DELETE).+ const next = e.relatedTarget as HTMLElement | null+ if (next?.closest('[data-attr="max-send-message"]')) {+ return+ }+ releaseSandboxPrewarm()+ }}onPressEnter={() => {if (hasQuestion &&diff --git a/frontend/src/scenes/max/components/SandboxApproval.test.tsx b/frontend/src/scenes/max/components/SandboxApproval.test.tsxnew file mode 100644index 000000000000..d9d6854510e1--- /dev/null+++ b/frontend/src/scenes/max/components/SandboxApproval.test.tsx@@ -0,0 +1,248 @@+import '@testing-library/jest-dom'++import { cleanup, fireEvent, render, screen } from '@testing-library/react'+import { useActions, useValues } from 'kea'++import type { PermissionRequestRecord, ToolInvocation } from '../types/sandboxStreamTypes'+import { SandboxModeBadge } from './InputFormArea'+import { SandboxPermissionInput } from './SandboxPermissionInput'++jest.mock('kea', () => ({+ ...jest.requireActual('kea'),+ useActions: jest.fn(),+ useValues: jest.fn(),+}))++jest.mock('use-resize-observer', () => () => ({+ height: 160,+ ref: { current: null },+}))++jest.mock('../maxThreadLogic', () => ({+ maxThreadLogic: { __mock: 'maxThreadLogic' },+}))++jest.mock('../sandboxStreamLogic', () => ({+ // Keyed logic — the component binds it with `sandboxStreamLogic({ streamKey })`.+ sandboxStreamLogic: jest.fn(() => ({ __mock: 'sandboxStreamLogicInstance' })),+}))++jest.mock('../MarkdownMessage', () => ({+ MarkdownMessage: ({ content }: { content: string }) => <div data-attr="markdown">{content}</div>,+}))++jest.mock('lib/components/CodeSnippet', () => ({+ CodeSnippet: ({ children }: { children: string }) => <pre data-attr="code-snippet">{children}</pre>,+ Language: { JSON: 'json', Text: 'text' },+}))++const rawToolCall: ToolInvocation = {+ toolCallId: 'tc-1',+ rawServerName: 'posthog',+ rawToolName: 'exec',+ input: { command: 'call insight-create {"name":"Signups"}' },+ status: 'pending',+ contentBlocks: [],+}++function makeRequest(overrides: Partial<PermissionRequestRecord> = {}): PermissionRequestRecord {+ return {+ requestId: 'req-1',+ toolCallId: 'tc-1',+ toolName: 'mcp__posthog__exec',+ title: 'Create insight',+ description: 'The agent wants to create an insight.',+ options: [+ { optionId: 'opt-allow', name: 'Approve', kind: 'allow_once' },+ { optionId: 'opt-reject', name: 'Decline', kind: 'reject' },+ ],+ rawToolCall,+ ...overrides,+ }+}++describe('Sandbox approval input area', () => {+ const respondToPermission = jest.fn()++ beforeEach(() => {+ jest.clearAllMocks()+ ;(useActions as jest.Mock).mockReturnValue({ respondToPermission })+ ;(useValues as jest.Mock).mockReturnValue({ respondingToPermission: false, currentMode: null })+ })++ afterEach(() => {+ cleanup()+ })++ describe('SandboxPermissionInput', () => {+ it('renders the approval prompt with the same two permission options', () => {+ render(<SandboxPermissionInput streamKey="conv-1" request={makeRequest()} />)++ expect(screen.getByText('Approval required')).toBeInTheDocument()+ expect(screen.getByText('posthog - insight-create (MCP)')).toBeInTheDocument()+ expect(screen.getByText('Approve')).toBeInTheDocument()+ expect(screen.getByText('Decline')).toBeInTheDocument()+ expect(screen.queryByText("Explain what you'd like instead.")).not.toBeInTheDocument()+ })++ it('renders the unwrapped PostHog exec payload like PostHog Code', () => {+ render(+ <SandboxPermissionInput+ streamKey="conv-1"+ request={makeRequest({+ rawToolCall: {+ ...rawToolCall,+ input: { command: 'call execute-sql {"query":"select 1"}' },+ },+ })}+ />+ )++ expect(screen.getByText('posthog - execute-sql (MCP)')).toBeInTheDocument()+ expect(+ screen.getByText((_content, element) => element?.getAttribute('data-attr') === 'code-snippet')+ .textContent+ ).toEqual('{\n "query": "select 1"\n}')+ })++ it('posts the chosen optionId on click', () => {+ render(<SandboxPermissionInput streamKey="conv-1" request={makeRequest()} />)++ fireEvent.click(screen.getByText('Approve'))++ expect(respondToPermission).toHaveBeenCalledWith({+ requestId: 'req-1',+ optionId: 'opt-allow',+ })+ })++ it('guards against double-submit while the reply POST is in flight', () => {+ // The logic's respondingToPermission flag drives the loading state — it flips+ // synchronously on dispatch and resets on success and on failure alike.+ ;(useValues as jest.Mock).mockReturnValue({ respondingToPermission: true })+ render(<SandboxPermissionInput streamKey="conv-1" request={makeRequest()} />)++ // Loading message replaces the option list, so nothing can be clicked.+ expect(screen.getByText('Sending response…')).toBeInTheDocument()+ expect(screen.queryByText('Approve')).not.toBeInTheDocument()+ expect(screen.queryByText('Decline')).not.toBeInTheDocument()+ expect(respondToPermission).not.toHaveBeenCalled()+ })++ it('sends feedback text through the reject_with_feedback option when it is the decline path', () => {+ render(+ <SandboxPermissionInput+ streamKey="conv-1"+ request={makeRequest({+ options: [+ { optionId: 'opt-allow', name: 'Approve', kind: 'allow_once' },+ { optionId: 'opt-feedback', name: 'Decline with feedback', kind: 'reject_with_feedback' },+ ],+ })}+ />+ )++ fireEvent.click(screen.getByText("Explain what you'd like instead."))+ const input = screen.getByPlaceholderText('Type your answer...')+ fireEvent.change(input, { target: { value: 'Use a funnel instead' } })+ fireEvent.click(screen.getByRole('button', { name: 'Send' }))++ expect(respondToPermission).toHaveBeenCalledWith({+ requestId: 'req-1',+ optionId: 'opt-feedback',+ customInput: 'Use a funnel instead',+ })+ })++ it('renders reject_once as a one-click decline with no feedback toggle', () => {+ const request = makeRequest({+ options: [+ { optionId: 'opt-allow', name: 'Yes', kind: 'allow_once' },+ { optionId: 'opt-reject', name: 'No', kind: 'reject_once', customInput: true },+ ],+ })+ render(<SandboxPermissionInput streamKey="conv-1" request={request} />)++ // No optional-feedback affordance — the decline is a plain one-click button.+ expect(screen.queryByText('Add feedback…')).not.toBeInTheDocument()+ fireEvent.click(screen.getByText('No'))+ expect(respondToPermission).toHaveBeenCalledWith({+ requestId: 'req-1',+ optionId: 'opt-reject',+ })+ })++ it.each([+ [+ 'the agent is in plan mode',+ (): void => {+ ;(useValues as jest.Mock).mockReturnValue({ respondingToPermission: false, currentMode: 'plan' })+ },+ makeRequest(),+ ],+ [+ 'the tool call is tagged as a plan',+ (): void => {},+ makeRequest({ rawToolCall: { ...rawToolCall, kind: 'plan' } }),+ ],+ ])('shows plan copy when %s', (_case, arrange, request) => {+ arrange()+ render(<SandboxPermissionInput streamKey="conv-1" request={request} />)++ expect(screen.getByText('Approve this plan?')).toBeInTheDocument()+ })++ it('does not show plan copy just because the title mentions a plan', () => {+ render(+ <SandboxPermissionInput+ streamKey="conv-1"+ request={makeRequest({ title: 'Create a data retention plan' })}+ />+ )++ expect(screen.getByText('Approval required')).toBeInTheDocument()+ })++ it('falls back to showing every option when filtering would leave none', () => {+ render(+ <SandboxPermissionInput+ streamKey="conv-1"+ request={makeRequest({+ options: [{ optionId: 'opt-always', name: '', kind: 'allow_always' }],+ })}+ />+ )++ 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/frontend/src/scenes/max/components/SandboxContextUsage.tsx b/frontend/src/scenes/max/components/SandboxContextUsage.tsxnew file mode 100644index 000000000000..68b0dad234ad--- /dev/null+++ b/frontend/src/scenes/max/components/SandboxContextUsage.tsx@@ -0,0 +1,68 @@+import { useValues } from 'kea'++import { Tooltip } from '@posthog/lemon-ui'++import { humanFriendlyNumber } from 'lib/utils/numbers'++import { sandboxStreamLogic } from '../sandboxStreamLogic'++/** Compact SVG ring showing the context-window fill percentage. */+function UsageRing({ percentage }: { percentage: number }): JSX.Element {+ const radius = 7+ const circumference = 2 * Math.PI * radius+ const clamped = Math.max(0, Math.min(1, percentage / 100))+ return (+ <svg viewBox="0 0 18 18" className="size-4 shrink-0 -rotate-90">+ <circle cx="9" cy="9" r={radius} fill="none" strokeWidth="2.5" className="stroke-border" />+ <circle+ cx="9"+ cy="9"+ r={radius}+ fill="none"+ strokeWidth="2.5"+ strokeLinecap="round"+ strokeDasharray={circumference}+ strokeDashoffset={circumference * (1 - clamped)}+ className="stroke-accent"+ />+ </svg>+ )+}++/**+ * Context-usage indicator for sandbox conversations. Reads the latest-wins `contextUsage` snapshot+ * and renders a fill ring + `used / size · %` label when the numeric aggregate is present, plus the+ * run cost when known. Hidden when there is nothing to show. The breakdown popover is deferred.+ */+export function SandboxContextUsage(): JSX.Element | null {+ const { contextUsage } = useValues(sandboxStreamLogic)++ if (!contextUsage) {+ return null+ }++ const { used, size, cost } = contextUsage+ const hasRing = typeof used === 'number' && typeof size === 'number' && size > 0+ const percentage = hasRing ? Math.round((used! / size!) * 100) : null+ const hasCost = typeof cost === 'number'++ if (!hasRing && !hasCost) {+ return null+ }++ return (+ <div className="flex items-center gap-2 px-3 py-1 text-xs text-muted" data-attr="max-sandbox-context-usage">+ {hasRing && (+ <Tooltip title="Context window usage">+ <span className="flex items-center gap-1.5">+ <UsageRing percentage={percentage!} />+ <span>+ {humanFriendlyNumber(used!)} / {humanFriendlyNumber(size!)} · {percentage}%+ </span>+ </span>+ </Tooltip>+ )}+ {hasCost && <span>${cost!.toFixed(2)}</span>}+ </div>+ )+}diff --git a/frontend/src/scenes/max/components/SandboxModeToggle.tsx b/frontend/src/scenes/max/components/SandboxModeToggle.tsxnew file mode 100644index 000000000000..e99fff875d70--- /dev/null+++ b/frontend/src/scenes/max/components/SandboxModeToggle.tsx@@ -0,0 +1,66 @@+import { useActions, useValues } from 'kea'+import posthog from 'posthog-js'+import { useCallback } from 'react'++import { LemonButton, LemonTag } from '@posthog/lemon-ui'++import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'++import { SPECIAL_MODES } from '../max-constants'+import { maxThreadLogic } from '../maxThreadLogic'++/**+ * Standalone control for opting a conversation into the sandbox runtime. Rendered only when the+ * `PHAI_SANDBOX_MODE` flag is on. The runtime is stamped onto the conversation's `agent_runtime`+ * at create-time and never changes afterwards — so for a fresh conversation this acts as a toggle,+ * and once a conversation has started it stays locked as a read-only indicator of the runtime.+ */+export function SandboxModeToggle(): JSX.Element | null {+ const { isSandboxMode, conversation, threadMessageCount, contextDisabledReason } = useValues(maxThreadLogic)+ const { setIsSandboxMode } = useActions(maxThreadLogic)+ const sandboxModeEnabled = useFeatureFlag('PHAI_SANDBOX_MODE')++ const isSandboxRuntime = conversation?.agent_runtime === 'sandbox'+ const isActive = isSandboxRuntime || isSandboxMode+ const hasExistingMessages = threadMessageCount > 0++ const handleToggle = useCallback((): void => {+ const next = !isActive+ posthog.capture('phai sandbox toggled', { enabled: next })+ // The selected agent mode is kept — sandbox carries it through as a context note.+ setIsSandboxMode(next)+ }, [isActive, setIsSandboxMode])++ // Hide entirely for non-sandbox conversations that have already started — there's nothing to+ // toggle, and we only want to surface this as a locked indicator for actual sandbox runtimes.+ if (!sandboxModeEnabled || (hasExistingMessages && !isSandboxRuntime)) {+ return null+ }++ // Runtime is fixed once the conversation exists; until then `contextDisabledReason` still gates it.+ const disabledReason = hasExistingMessages+ ? 'Start a new conversation to change the runtime'+ : contextDisabledReason++ return (+ <LemonButton+ size="xxsmall"+ type="tertiary"+ icon={SPECIAL_MODES.sandbox.icon}+ active={isActive}+ onClick={handleToggle}+ disabledReason={disabledReason}+ tooltip={SPECIAL_MODES.sandbox.description}+ className="flex-shrink-0 border [&>span]:text-secondary"+ >+ <span className="flex items-center gap-1">+ {SPECIAL_MODES.sandbox.name}+ {SPECIAL_MODES.sandbox.alpha && (+ <LemonTag size="small" type="danger">+ ALPHA+ </LemonTag>+ )}+ </span>+ </LemonButton>+ )+}diff --git a/frontend/src/scenes/max/components/SandboxPermissionInput.tsx b/frontend/src/scenes/max/components/SandboxPermissionInput.tsxnew file mode 100644index 000000000000..d11463aece76--- /dev/null+++ b/frontend/src/scenes/max/components/SandboxPermissionInput.tsx@@ -0,0 +1,140 @@+import { useActions, useValues } from 'kea'++import { IconWarning } from '@posthog/icons'+import { LemonTag, Spinner } from '@posthog/lemon-ui'++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 type { PermissionRequestRecord } from '../types/sandboxStreamTypes'+import { QuestionField } from './QuestionField'++interface SandboxPermissionInputProps {+ streamKey: string+ request: PermissionRequestRecord+}++const ignoreMultiSelectChange = (_value: string[]): void => undefined+const ignoreMultiSelectSubmit = (): void => undefined++function toPermissionQuestion(+ prompt: string,+ options: ApprovalCardOption[],+ allowCustomAnswer: boolean+): MultiQuestionFormQuestion {+ return {+ id: 'permission',+ title: 'Approval',+ question: prompt,+ type: 'select',+ options: options.map((option) => ({ value: option.label })),+ allow_custom_answer: allowCustomAnswer,+ }+}++/**+ * Self-contained input-area renderer for an ACP `permission_request` on a sandbox conversation.+ * Reuses the same `QuestionField` surface as sandbox questions while preserving the ACP option ids+ * sent back to the runtime. `allow_always` stays hidden unless filtering would leave no choices.+ *+ * Submitting POSTs through `sandboxStreamLogic.respondToPermission`; the logic's+ * `respondingToPermission` drives the loading/double-submit guard and re-enables the controls when the+ * POST fails (the pending request only clears on success).+ */+export function SandboxPermissionInput({ streamKey, request }: SandboxPermissionInputProps): JSX.Element {+ const boundLogic = sandboxStreamLogic({ streamKey })+ const { respondToPermission } = useActions(boundLogic)+ const { respondingToPermission, currentMode } = useValues(boundLogic)++ // A request whose every option was filtered out (e.g. only `allow_always` without a rememberable+ // preview) must still be answerable — fall back to showing everything.+ const defaultOptions = mapPermissionOptions(request.options)+ const mappedOptions = defaultOptions.length > 0 ? defaultOptions : mapPermissionOptions(request.options, true)+ // Only the legacy `reject_with_feedback` kind is feedback-only — reachable solely through the+ // text field. A `reject_once` decline is a plain one-click button with no optional-feedback toggle.+ const feedbackOption = mappedOptions.find((o) => o.requiresFeedback)+ // Every option except the legacy feedback-only one renders as a one-click button.+ const buttonOptions = mappedOptions.filter((o) => !o.requiresFeedback)+ const hasOneClickDecline = buttonOptions.some((option) => option.decision === 'declined')+ const allowFeedback = !!feedbackOption && !hasOneClickDecline++ // Plan approvals are raised while the agent is in plan mode — the mode is the grounded signal;+ // `toolCall.kind === 'plan'` covers adapters that tag the request directly.+ const isPlan = currentMode === 'plan' || request.rawToolCall.kind === 'plan'+ const prompt = isPlan ? 'Approve this plan?' : 'Approval required'+ const display = getSandboxPermissionDisplay(request)+ const payloadLanguage = display.payload?.trim().match(/^[{[]/) ? Language.JSON : Language.Text++ const respond = (optionId: string): void => {+ if (respondingToPermission) {+ return+ }+ respondToPermission({ requestId: request.requestId, optionId })+ }++ const handleAnswer = (value: string | string[] | null): void => {+ if (respondingToPermission || value === null || Array.isArray(value)) {+ return+ }+ const selectedOption = buttonOptions.find((option) => option.label === value)+ if (selectedOption) {+ respond(selectedOption.optionId)+ return+ }+ if (allowFeedback && feedbackOption) {+ respondToPermission({+ requestId: request.requestId,+ optionId: feedbackOption.optionId,+ customInput: value,+ })+ }+ }++ return (+ <div className="flex flex-col gap-2 p-3">+ <div className="flex items-center gap-2 text-sm">+ <IconWarning className="text-warning size-4" />+ <LemonTag size="small" type="warning">+ {isPlan ? 'Plan approval' : 'Approval'}+ </LemonTag>+ </div>+ <div className="font-medium text-sm">{prompt}</div>+ {display.title && <div className="text-xs text-secondary">{display.title}</div>}+ {(request.title || request.description) && (+ <div className="max-h-60 overflow-y-auto text-sm">+ <MarkdownMessage+ content={request.description ?? request.title ?? ''}+ id={`permission-${request.requestId}`}+ />+ </div>+ )}+ {display.payload && (+ <div className="max-h-60 overflow-y-auto">+ <CodeSnippet language={payloadLanguage} className="text-xs" compact>+ {display.payload}+ </CodeSnippet>+ </div>+ )}+ {respondingToPermission ? (+ <div className="flex items-center gap-2 text-muted pt-1">+ <Spinner className="size-4" />+ <span>Sending response…</span>+ </div>+ ) : (+ <QuestionField+ question={toPermissionQuestion(prompt, buttonOptions, allowFeedback)}+ value={undefined}+ onAnswer={handleAnswer}+ onChange={ignoreMultiSelectChange}+ onSubmit={ignoreMultiSelectSubmit}+ submitLabel="Send"+ />+ )}+ </div>+ )+}diff --git a/frontend/src/scenes/max/components/SandboxQuestionInput.test.tsx b/frontend/src/scenes/max/components/SandboxQuestionInput.test.tsxnew file mode 100644index 000000000000..c53f89196d9b--- /dev/null+++ b/frontend/src/scenes/max/components/SandboxQuestionInput.test.tsx@@ -0,0 +1,175 @@+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 { PermissionRequestRecord, ToolInvocation } from '../types/sandboxStreamTypes'+import { SandboxQuestionInput } from './SandboxQuestionInput'++jest.mock('kea', () => ({+ ...jest.requireActual('kea'),+ useActions: jest.fn(),+ useValues: jest.fn(),+}))++jest.mock('../sandboxStreamLogic', () => ({+ sandboxStreamLogic: jest.fn(() => ({ __mock: 'sandboxStreamLogicInstance' })),+}))++const rawToolCall: ToolInvocation = {+ toolCallId: 'tc-1',+ rawServerName: 'claude',+ rawToolName: '',+ input: {},+ status: 'pending',+ contentBlocks: [],+ meta: { claudeCode: { toolName: 'AskUserQuestion' } },+}++function makeRequest(questions: SandboxQuestion[]): PermissionRequestRecord {+ return {+ requestId: 'req-1',+ toolCallId: 'tc-1',+ toolName: 'AskUserQuestion',+ options: questions[0].options.map((o, idx) => ({+ optionId: `option_${idx}`,+ name: o.label,+ kind: 'allow_once',+ })),+ rawToolCall,+ questions,+ }+}++const goalQuestion: SandboxQuestion = {+ question: 'Which goal matters most?',+ header: 'Goal',+ multiSelect: false,+ options: [{ label: 'Activation', description: 'aha moment' }, { label: 'Revenue' }],+}++describe('SandboxQuestionInput', () => {+ const respondToPermission = jest.fn()++ beforeEach(() => {+ jest.clearAllMocks()+ ;(useActions as jest.Mock).mockReturnValue({ respondToPermission })+ ;(useValues as jest.Mock).mockReturnValue({ respondingToPermission: false })+ })++ afterEach(() => {+ cleanup()+ })++ it('renders the header chip, question text, and options via QuestionField', () => {+ render(<SandboxQuestionInput streamKey="conv-1" request={makeRequest([goalQuestion])} />)++ expect(screen.getByText('Goal')).toBeInTheDocument()+ expect(screen.getByText('Which goal matters most?')).toBeInTheDocument()+ expect(screen.getByText('Activation')).toBeInTheDocument()+ expect(screen.getByText('Revenue')).toBeInTheDocument()+ expect(screen.getByText('aha moment')).toBeInTheDocument()+ })++ it('submits a single-select answer on pick with the derived optionId', () => {+ render(<SandboxQuestionInput streamKey="conv-1" request={makeRequest([goalQuestion])} />)++ // Single-select advances/submits on pick (QuestionField behaviour) — the last question submits.+ fireEvent.click(screen.getByText('Revenue'))++ expect(respondToPermission).toHaveBeenCalledWith({+ requestId: 'req-1',+ optionId: 'option_1',+ answers: { 'Which goal matters most?': 'Revenue' },+ customInput: undefined,+ })+ })++ it('joins multiple selections for a multi-select question', () => {+ const productsQuestion: SandboxQuestion = {+ question: 'Which products?',+ header: 'Products',+ multiSelect: true,+ options: [{ label: 'Insights' }, { label: 'Replay' }, { label: 'Flags' }],+ }+ render(<SandboxQuestionInput streamKey="conv-1" request={makeRequest([productsQuestion])} />)++ fireEvent.click(screen.getByText('Insights'))+ fireEvent.click(screen.getByText('Flags'))+ fireEvent.click(screen.getByRole('button', { name: 'Submit' }))++ expect(respondToPermission).toHaveBeenCalledWith({+ requestId: 'req-1',+ optionId: 'option_0',+ answers: { 'Which products?': 'Insights, Flags' },+ customInput: undefined,+ })+ })++ it('sends a free-typed answer through the custom path with option_0 fallback', () => {+ render(<SandboxQuestionInput streamKey="conv-1" request={makeRequest([goalQuestion])} />)++ // Open the custom "Type your answer" field, type, and submit.+ fireEvent.click(screen.getByText("Explain what you'd like instead."))+ fireEvent.change(screen.getByPlaceholderText('Type your answer...'), { target: { value: 'Cut churn' } })+ fireEvent.click(screen.getByRole('button', { name: 'Submit' }))++ expect(respondToPermission).toHaveBeenCalledWith({+ requestId: 'req-1',+ optionId: 'option_0',+ answers: { 'Which goal matters most?': 'Cut churn' },+ customInput: 'Cut churn',+ })+ })++ it('does not submit a multi-select question with nothing selected', () => {+ const productsQuestion: SandboxQuestion = {+ question: 'Which products?',+ header: 'Products',+ multiSelect: true,+ options: [{ label: 'Insights' }, { label: 'Replay' }],+ }+ render(<SandboxQuestionInput streamKey="conv-1" request={makeRequest([productsQuestion])} />)++ fireEvent.click(screen.getByRole('button', { name: 'Submit' }))++ expect(screen.getByText('Select at least one option')).toBeInTheDocument()+ expect(respondToPermission).not.toHaveBeenCalled()+ })++ it('steps through multiple questions and submits all answers at once', () => {+ const second: SandboxQuestion = {+ question: 'Which timeframe?',+ header: 'Timeframe',+ multiSelect: false,+ options: [{ label: 'Weekly' }, { label: 'Monthly' }],+ }+ render(<SandboxQuestionInput streamKey="conv-1" request={makeRequest([goalQuestion, second])} />)++ expect(screen.getByText('1/2')).toBeInTheDocument()+ // Single-select pick auto-advances to the next question.+ fireEvent.click(screen.getByText('Activation'))+ expect(screen.getByText('2/2')).toBeInTheDocument()+ expect(respondToPermission).not.toHaveBeenCalled()++ // Picking the last question's answer submits all collected answers.+ fireEvent.click(screen.getByText('Monthly'))++ expect(respondToPermission).toHaveBeenCalledWith({+ requestId: 'req-1',+ optionId: 'option_0',+ answers: { 'Which goal matters most?': 'Activation', 'Which timeframe?': 'Monthly' },+ customInput: undefined,+ })+ })++ it('shows a sending state and blocks interaction while a reply is in flight', () => {+ ;(useValues as jest.Mock).mockReturnValue({ respondingToPermission: true })+ render(<SandboxQuestionInput streamKey="conv-1" request={makeRequest([goalQuestion])} />)++ expect(screen.getByText('Sending response…')).toBeInTheDocument()+ expect(screen.queryByText('Revenue')).not.toBeInTheDocument()+ expect(respondToPermission).not.toHaveBeenCalled()+ })+})diff --git a/frontend/src/scenes/max/components/SandboxQuestionInput.tsx b/frontend/src/scenes/max/components/SandboxQuestionInput.tsxnew file mode 100644index 000000000000..417f8ca25051--- /dev/null+++ b/frontend/src/scenes/max/components/SandboxQuestionInput.tsx@@ -0,0 +1,176 @@+import { useActions, useValues } from 'kea'+import { useCallback, useMemo, useRef, useState } from 'react'++import { IconChat } from '@posthog/icons'+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 type { PermissionRequestRecord } from '../types/sandboxStreamTypes'+import { QuestionField } from './QuestionField'++interface SandboxQuestionInputProps {+ streamKey: string+ request: PermissionRequestRecord+}++/** Adapt a sandbox question onto the `MultiQuestionFormQuestion` shape `QuestionField` renders. */+function toFormQuestion(question: SandboxQuestion, index: number): MultiQuestionFormQuestion {+ return {+ id: String(index),+ title: question.header ?? 'Question',+ question: question.question,+ type: question.multiSelect ? 'multi_select' : 'select',+ options: question.options.map((option) => ({ value: option.label, description: option.description })),+ allow_custom_answer: true,+ }+}++function selectedLabels(answer: string | string[] | undefined): string[] {+ if (Array.isArray(answer)) {+ return answer+ }+ return answer ? [answer] : []+}++/**+ * Interactive input-area overlay for an `AskUserQuestion` on a sandbox conversation. The agent (Twig)+ * routes questions through the ACP permission framework, so this rides the same `pendingPermissionRequest`+ * rails as `SandboxPermissionInput` but renders the question(s) instead of an approve/decline card.+ *+ * It reuses the LangGraph `QuestionField` (and therefore `OptionSelector` / `LemonCheckbox`) for the+ * options, and mirrors `MultiQuestionFormInput`'s flow: single-select answers advance on pick,+ * multi-select accumulates behind a Next/Submit button, and the footer label flips to "Submit" on the+ * last question. On submit it replies via `respondToPermission` with the answers keyed by question+ * text — the agent reads `_meta.answers`; `optionId` only has to be a valid offered option (derived+ * from the first question's selection). `respondingToPermission` drives the loading / double-submit guard.+ */+export function SandboxQuestionInput({ streamKey, request }: SandboxQuestionInputProps): JSX.Element | null {+ const boundLogic = sandboxStreamLogic({ streamKey })+ const { respondToPermission } = useActions(boundLogic)+ const { respondingToPermission } = useValues(boundLogic)++ // Stable reference so the memoized callbacks below don't re-evaluate every render.+ const questions = useMemo(() => request.questions ?? [], [request.questions])++ const [currentIndex, setCurrentIndex] = useState(0)+ const [answers, setAnswers] = useState<Record<number, string | string[]>>({})+ const answersRef = useRef(answers)+ answersRef.current = answers++ const submit = useCallback(+ (finalAnswers: Record<number, string | string[]>) => {+ const answerMap: Record<string, string> = {}+ for (let index = 0; index < questions.length; index++) {+ const labels = selectedLabels(finalAnswers[index])+ if (labels.length) {+ answerMap[questions[index].question] = labels.join(', ')+ }+ }+ // Options only exist on the wire for the first question, so optionId / customInput derive+ // from it; the answers map carries the rest for the agent.+ const firstQuestion = questions[0]+ const firstLabels = selectedLabels(finalAnswers[0])+ const firstOptionLabels = new Set(firstQuestion.options.map((option) => option.label))+ respondToPermission({+ requestId: request.requestId,+ optionId: deriveQuestionOptionId(firstQuestion, firstLabels),+ answers: answerMap,+ customInput: firstLabels.find((label) => !firstOptionLabels.has(label)),+ })+ },+ [questions, request.requestId, respondToPermission]+ )++ const advanceOrSubmit = useCallback(+ (updatedAnswers: Record<number, string | string[]>) => {+ if (currentIndex < questions.length - 1) {+ setCurrentIndex(currentIndex + 1)+ } else {+ submit(updatedAnswers)+ }+ },+ [currentIndex, questions.length, submit]+ )++ const handleAnswer = useCallback(+ (value: string | string[] | null) => {+ if (respondingToPermission) {+ return+ }+ if (value === null) {+ const cleared = { ...answersRef.current }+ delete cleared[currentIndex]+ setAnswers(cleared)+ answersRef.current = cleared+ return+ }+ const updated = { ...answersRef.current, [currentIndex]: value }+ setAnswers(updated)+ answersRef.current = updated+ advanceOrSubmit(updated)+ },+ [advanceOrSubmit, currentIndex, respondingToPermission]+ )++ const handleMultiSelectChange = useCallback(+ (value: string[]) => {+ const updated = { ...answersRef.current, [currentIndex]: value }+ setAnswers(updated)+ answersRef.current = updated+ },+ [currentIndex]+ )++ const handleMultiSelectSubmit = useCallback(() => {+ if (respondingToPermission) {+ return+ }+ advanceOrSubmit(answersRef.current)+ }, [advanceOrSubmit, respondingToPermission])++ // The dispatcher only mounts this when `questions` is non-empty; keep the guard for type safety.+ const question = questions[currentIndex]+ if (!question) {+ return null+ }++ if (respondingToPermission) {+ return (+ <div className="flex items-center gap-2 text-muted p-3">+ <Spinner className="size-4" />+ <span>Sending response…</span>+ </div>+ )+ }++ const isLast = currentIndex === questions.length - 1++ return (+ <div className="flex flex-col gap-2 p-3">+ <div className="flex items-center gap-2 text-sm">+ <IconChat className="text-muted size-4" />+ <LemonTag size="small" type="muted">+ {question.header ?? 'Question'}+ </LemonTag>+ {questions.length > 1 && (+ <span className="text-muted text-xs">+ {currentIndex + 1}/{questions.length}+ </span>+ )}+ </div>+ <div className="font-medium text-sm">{question.question}</div>+ <QuestionField+ key={currentIndex}+ question={toFormQuestion(question, currentIndex)}+ value={answers[currentIndex]}+ onAnswer={handleAnswer}+ onChange={handleMultiSelectChange}+ onSubmit={handleMultiSelectSubmit}+ submitLabel={isLast ? 'Submit' : 'Next'}+ />+ </div>+ )+}diff --git a/frontend/src/scenes/max/components/SandboxResourcesBar.tsx b/frontend/src/scenes/max/components/SandboxResourcesBar.tsxnew file mode 100644index 000000000000..655c7571774b--- /dev/null+++ b/frontend/src/scenes/max/components/SandboxResourcesBar.tsx@@ -0,0 +1,37 @@+import { useValues } from 'kea'++import { Tooltip } from '@posthog/lemon-ui'++import { resolveProductMeta } from '../messages/posthogProducts'+import { sandboxStreamLogic } from '../sandboxStreamLogic'++/**+ * Persistent "PostHog resources used" bar for sandbox conversations. Reads the session-cumulative+ * `resourcesUsed` list (unioned by id across the whole conversation) and renders one chip per+ * product the agent grounded an answer in. Hidden when empty. Each chip is a product icon plus a+ * Sentence-cased label; unknown ids degrade to the wire label and a generic icon.+ */+export function SandboxResourcesBar(): JSX.Element | null {+ const { resourcesUsed } = useValues(sandboxStreamLogic)++ if (resourcesUsed.length === 0) {+ return null+ }++ return (+ <div className="flex flex-wrap items-center gap-1.5 px-3 py-1.5" data-attr="max-sandbox-resources-bar">+ <span className="text-xs text-muted mr-0.5">PostHog resources used:</span>+ {resourcesUsed.map((product) => {+ const { label, Icon } = resolveProductMeta(product.id, product.label)+ return (+ <Tooltip key={product.id} title={label}>+ <span className="inline-flex items-center gap-1 rounded border bg-surface-primary px-1.5 py-0.5 text-xs">+ <Icon className="size-3.5 shrink-0" />+ <span>{label}</span>+ </span>+ </Tooltip>+ )+ })}+ </div>+ )+}diff --git a/frontend/src/scenes/max/components/SidebarQuestionInput.tsx b/frontend/src/scenes/max/components/SidebarQuestionInput.tsxindex dcd83460aa94..c2bb9eded9d4 100644--- a/frontend/src/scenes/max/components/SidebarQuestionInput.tsx+++ b/frontend/src/scenes/max/components/SidebarQuestionInput.tsx@@ -12,7 +12,7 @@ import { cn } from 'lib/utils/css-classes'import { SuggestionGroup, maxLogic } from '../maxLogic'import { maxThreadLogic } from '../maxThreadLogic'-import { InputFormArea } from './InputFormArea'+import { InputFormArea, SandboxModeBadge } from './InputFormArea'import { QuestionInput } from './QuestionInput'export function SidebarQuestionInput({@@ -31,7 +31,11 @@ export function SidebarQuestionInput({pendingApprovalProposalId,pendingApprovalsData,resolvedApprovalStatuses,+ pendingSandboxPermissionRequest,} = useValues(maxThreadLogic)+ // A pending sandbox request only originates from the sandbox stream, so its presence alone is+ // enough — gating on `agent_runtime` would strand approvals on as-yet-unresolved conversations.+ const hasSandboxPermissionToShow = !!pendingSandboxPermissionRequest// Check if there's a pending (not yet resolved) approval to showconst hasApprovalToShow = useMemo(() => {@@ -61,7 +65,7 @@ export function SidebarQuestionInput({}, [focusCounter]) // Update focus when focusCounter changes// Show form area directly when there's a pending form/approval (even if showInput is false)- if (activeMultiQuestionForm || hasApprovalToShow) {+ if (activeMultiQuestionForm || hasApprovalToShow || hasSandboxPermissionToShow) {return (<div className="w-full max-w-180 self-center px-3 mx-auto bg-[var(--scene-layout-background)]/50 backdrop-blur-sm"><div className="border border-primary rounded-lg bg-surface-primary">@@ -78,6 +82,7 @@ export function SidebarQuestionInput({containerClassName={cn('mx-auto self-center backdrop-blur-sm z-50', sidePanel && 'px-0')}isThreadVisible={threadVisible}>+ <SandboxModeBadge /><SuggestionsList /></QuestionInput>)diff --git a/frontend/src/scenes/max/max-constants.tsx b/frontend/src/scenes/max/max-constants.tsxindex 9e32d84215e8..c56419286068 100644--- a/frontend/src/scenes/max/max-constants.tsx+++ b/frontend/src/scenes/max/max-constants.tsx@@ -1460,6 +1460,11 @@ export const SPECIAL_MODES: Record<string, ModeDefinition> = {},}+/** Human-readable label for an agent or special mode value (e.g. `'product_analytics'` → `'Product analytics'`). */+export function getModeDisplayName(mode: string): string {+ return MODE_DEFINITIONS[mode as keyof typeof MODE_DEFINITIONS]?.name ?? SPECIAL_MODES[mode]?.name ?? mode+}+/** Get tools available for a specific agent mode */export function getToolsForMode(mode: AgentMode): ToolDefinition[] {return Object.values(TOOL_DEFINITIONS).filter((tool) => tool.modes?.includes(mode))diff --git a/frontend/src/scenes/max/max-storage-keys.ts b/frontend/src/scenes/max/max-storage-keys.tsnew file mode 100644index 000000000000..2042acc70bd1--- /dev/null+++ b/frontend/src/scenes/max/max-storage-keys.ts@@ -0,0 +1,7 @@+// Dependency-free constants shared between maxLogic and maxThreadLogic. Keeping these+// out of maxThreadLogic.tsx lets the always-eager maxLogic reference them without pulling+// the heavy Max thread runtime (and the sandbox stream logic) into the authenticated-shell+// eager import graph — see frontend/bin/check-eager-graph.mjs.++/** Key for persisting pending AI prompts across page reloads (e.g., OAuth redirects) */+export const PENDING_AI_PROMPT_KEY = 'posthog_ai_pending_prompt'diff --git a/frontend/src/scenes/max/maxGlobalLogic.tsx b/frontend/src/scenes/max/maxGlobalLogic.tsxindex c0166574d1b4..a4ad2f590d68 100644--- a/frontend/src/scenes/max/maxGlobalLogic.tsx+++ b/frontend/src/scenes/max/maxGlobalLogic.tsx@@ -104,6 +104,7 @@ export const maxGlobalLogic = kea<maxGlobalLogicType>([})),actions({openSidePanelMax: (conversationId?: string) => ({ conversationId }),+ openSidePanelMaxWithTaskBind: (taskId: string) => ({ taskId }),askSidePanelMax: (prompt: string) => ({ prompt }),acceptDataProcessing: (testOnlyOverride?: boolean) => ({ testOnlyOverride }),registerTool: (tool: ToolRegistration) => ({ tool }),@@ -243,6 +244,22 @@ export const maxGlobalLogic = kea<maxGlobalLogicType>([logic.actions.openConversation(conversationId)}},+ // Open the side panel on a fresh chat bound to a sandbox Task (inbox "Open task" — in-place,+ // not a new tab). The side panel doesn't sync the URL, so the binding is seeded directly here+ // rather than via the `bind_task` param the scene route reads. `setPendingBindTaskId` runs+ // after `startNewConversation`, which clears it.+ openSidePanelMaxWithTaskBind: ({ taskId }) => {+ if (!values.sidePanelOpen || values.selectedTab !== SidePanelTab.Max) {+ actions.openSidePanel(SidePanelTab.Max)+ }+ let logic = maxLogic.findMounted({ panelId: SIDE_PANEL_PANEL_ID })+ if (!logic) {+ logic = maxLogic({ panelId: SIDE_PANEL_PANEL_ID })+ logic.mount() // we're never unmounting this+ }+ logic.actions.startNewConversation()+ logic.actions.setPendingBindTaskId(taskId)+ },loadConversationHistoryFailure: ({ errorObject }) => {lemonToast.error(errorObject?.data?.detail || 'Failed to load conversation history.')},diff --git a/frontend/src/scenes/max/maxLogic.tsx b/frontend/src/scenes/max/maxLogic.tsxindex c225caae9f93..297dd8616c51 100644--- a/frontend/src/scenes/max/maxLogic.tsx+++ b/frontend/src/scenes/max/maxLogic.tsx@@ -29,10 +29,10 @@ import {SidePanelTab,} from '~/types'+import { PENDING_AI_PROMPT_KEY } from './max-storage-keys'import { maxContextLogic } from './maxContextLogic'import { maxGlobalLogic } from './maxGlobalLogic'import type { maxLogicType } from './maxLogicType'-import { PENDING_AI_PROMPT_KEY } from './maxThreadLogic'import { MaxUIContext } from './maxTypes'/** Maximum age for restored prompts (5 minutes) */@@ -50,6 +50,14 @@ interface StoredMaxContext {timestamp: number}+/**+ * `/ai` query param carrying a sandbox Task to bind a fresh chat to (set by inbox "Open task").+ * A URL param (rather than sessionStorage) so the binding survives opening the chat in a new tab or+ * window. The side panel — which doesn't sync the URL — receives the same binding via a direct+ * `setPendingBindTaskId` (see `maxGlobalLogic.openSidePanelMaxWithTaskBind`).+ */+export const SANDBOX_BIND_TASK_PARAM = 'bind_task'+export type MessageStatus = 'loading' | 'completed' | 'error'export type ThreadMessage = RootAssistantMessage & {@@ -220,6 +228,7 @@ export const maxLogic = kea<maxLogicType>([incrActiveStreamingThreads: true,decrActiveStreamingThreads: true,setAutoRun: (autoRun: boolean) => ({ autoRun }),+ setPendingBindTaskId: (taskId: string | null) => ({ taskId }),}),reducers(({ props }) => ({@@ -248,6 +257,17 @@ export const maxLogic = kea<maxLogicType>([},],+ // A pending Task to bind a new sandbox conversation to (set by inbox "Open task"). Consumed by+ // maxThreadLogic on the first message, which sends it as `task_id` so the open resumes that+ // Task's run. Cleared once consumed, or when an explicit new chat starts without a bind.+ pendingBindTaskId: [+ null as string | null,+ {+ setPendingBindTaskId: (_, { taskId }) => taskId,+ startNewConversation: () => null,+ },+ ],+// The frontend-generated UUID for new conversationsfrontendConversationId: [(props.initialFrontendConversationId ?? uuid()) as string,@@ -692,6 +712,15 @@ export const maxLogic = kea<maxLogicType>([} else if (values.conversationHistoryVisible) {actions.toggleConversationHistory()}++ // A fresh chat (no `chat` param) may carry a task to bind via the URL (inbox "Open task").+ // Read it after the `startNewConversation` above (which clears it) so it survives, and the+ // first message resumes that task's run. The param naturally drops once `setConversationId`+ // rewrites the URL to `?chat=<id>` after the first message.+ const bindTaskId = search[SANDBOX_BIND_TASK_PARAM]+ if (!search.chat && bindTaskId) {+ actions.setPendingBindTaskId(String(bindTaskId))+ }},})),diff --git a/frontend/src/scenes/max/maxThreadLogic.test.ts b/frontend/src/scenes/max/maxThreadLogic.test.tsindex e1deb5cbea78..04b08f663bce 100644--- a/frontend/src/scenes/max/maxThreadLogic.test.ts+++ b/frontend/src/scenes/max/maxThreadLogic.test.ts@@ -3,6 +3,7 @@ import { MOCK_DEFAULT_BASIC_USER } from 'lib/api.mock'import { router } from 'kea-router'import { partial } from 'kea-test-utils'import { expectLogic } from 'kea-test-utils'+import posthog from 'posthog-js'import React from 'react'import api, { ApiError } from 'lib/api'@@ -33,7 +34,9 @@ import { EnhancedToolCall, TOOL_DEFINITIONS } from './max-constants'import { maxContextLogic } from './maxContextLogic'import { maxGlobalLogic } from './maxGlobalLogic'import { maxLogic } from './maxLogic'-import { maxThreadLogic } from './maxThreadLogic'+import { MAX_DASHBOARD_CONTEXT_WAIT_MS, maxThreadLogic } from './maxThreadLogic'+import { MaxContextType } from './maxTypes'+import { sandboxStreamLogic } from './sandboxStreamLogic'import {MOCK_CONVERSATION,MOCK_CONVERSATION_ID,@@ -460,24 +463,123 @@ describe('maxThreadLogic', () => {)})- it('sends the first message immediately even while the dashboard scene is still loading', async () => {- // Regression guard for the removed #63208 gate: on a Dashboard scene whose- // dashboardLogic.dashboard is still null, askMax must send synchronously (no poll/wait).- // If the gate were reinstated, stream would not be called until fake timers advanced.- const fakeDashboardLogic: any = { selectors: { maxContext: () => [] }, values: { dashboard: null } }+ // Simulate being on a dashboard scene whose data has not loaded yet: dashboardLogic.dashboard+ // is null, so its maxContext returns []. The first message must wait for the load, otherwise+ // it ships with no dashboard context and Max can't see the open dashboard.+ const mockLoadingDashboardScene = (): { values: { dashboard: any } } => {+ const fakeDashboardLogic: any = {+ selectors: {+ maxContext: () =>+ fakeDashboardLogic.values.dashboard+ ? [{ type: MaxContextType.DASHBOARD, data: fakeDashboardLogic.values.dashboard }]+ : [],+ },+ values: { dashboard: null as any },+ }jest.spyOn(sceneLogic.selectors, 'activeSceneId').mockReturnValue(Scene.Dashboard)jest.spyOn(sceneLogic.selectors, 'activeSceneLogic').mockReturnValue(fakeDashboardLogic)- const streamSpy = mockStream()+ jest.spyOn(sceneLogic.selectors, 'activeLoadedScene').mockReturnValue({+ paramsToProps: () => ({ id: 1 }),+ sceneParams: {},+ } as any)+ return fakeDashboardLogic+ }- maxLogicInstance.actions.setConversationId(MOCK_TEMP_CONVERSATION_ID)- logic = maxThreadLogic({ conversationId: MOCK_TEMP_CONVERSATION_ID, panelId: 'test' })- logic.mount()+ it('waits for the open dashboard to load before sending the first message (regression for #61414)', async () => {+ jest.useFakeTimers()+ const captureSpy = jest.spyOn(posthog, 'capture')+ try {+ const streamSpy = mockStream()+ const fakeDashboardLogic = mockLoadingDashboardScene()- await expectLogic(logic, () => {+ maxLogicInstance.actions.setConversationId(MOCK_TEMP_CONVERSATION_ID)+ logic = maxThreadLogic({ conversationId: MOCK_TEMP_CONVERSATION_ID, panelId: 'test' })+ logic.mount()++ // Fire the first message while the dashboard is still loading.logic.actions.askMax('what am I seeing on this dashboard?')- }).toDispatchActions(['askMax'])- expect(streamSpy).toHaveBeenCalledTimes(1)+ // The gate holds the send while the dashboard is loading.+ await jest.advanceTimersByTimeAsync(300)+ expect(streamSpy).toHaveBeenCalledTimes(0)++ // Dashboard finishes loading -> gate releases -> the message sends WITH the dashboard context.+ fakeDashboardLogic.values.dashboard = { id: 1, name: 'Test Dashboard', tiles: [] }+ await jest.advanceTimersByTimeAsync(500)++ expect(streamSpy).toHaveBeenCalledTimes(1)+ expect(streamSpy).toHaveBeenCalledWith(+ expect.objectContaining({+ ui_context: expect.objectContaining({+ dashboards: expect.arrayContaining([expect.objectContaining({ id: 1 })]),+ }),+ }),+ expect.any(Object)+ )+ // A normal load must NOT report a timeout.+ expect(captureSpy).not.toHaveBeenCalledWith('max dashboard context wait timed out', expect.anything())+ } finally {+ jest.useRealTimers()+ }+ })++ it('reports a telemetry event and still sends if the dashboard never loads within the cap', async () => {+ jest.useFakeTimers()+ const captureSpy = jest.spyOn(posthog, 'capture')+ try {+ const streamSpy = mockStream()+ mockLoadingDashboardScene() // dashboard stays null past the wait cap++ maxLogicInstance.actions.setConversationId(MOCK_TEMP_CONVERSATION_ID)+ logic = maxThreadLogic({ conversationId: MOCK_TEMP_CONVERSATION_ID, panelId: 'test' })+ logic.mount()++ logic.actions.askMax('what am I seeing on this dashboard?')++ // Advance past the 8s wait cap without the dashboard ever loading.+ await jest.advanceTimersByTimeAsync(8100)++ // The cap must never block the user - the message still sends...+ expect(streamSpy).toHaveBeenCalledTimes(1)+ // ...but we record that the wait timed out, so the cap's impact is observable in prod.+ expect(captureSpy).toHaveBeenCalledWith(+ 'max dashboard context wait timed out',+ expect.objectContaining({ dashboard_id: 1, waited_ms: expect.any(Number) })+ )+ // waited_ms is real elapsed time, so it must be at least the cap (never under-reported).+ const timeoutCall = captureSpy.mock.calls.find((c) => c[0] === 'max dashboard context wait timed out')+ expect(timeoutCall?.[1]?.waited_ms).toBeGreaterThanOrEqual(MAX_DASHBOARD_CONTEXT_WAIT_MS)+ } finally {+ jest.useRealTimers()+ }+ })++ it('releases the gate and sends if the user navigates away while the dashboard is still loading', async () => {+ jest.useFakeTimers()+ try {+ const streamSpy = mockStream()+ mockLoadingDashboardScene()++ maxLogicInstance.actions.setConversationId(MOCK_TEMP_CONVERSATION_ID)+ logic = maxThreadLogic({ conversationId: MOCK_TEMP_CONVERSATION_ID, panelId: 'test' })+ logic.mount()++ logic.actions.askMax('what am I seeing on this dashboard?')++ // Still on the (never-loading) dashboard -> the gate holds.+ await jest.advanceTimersByTimeAsync(300)+ expect(streamSpy).toHaveBeenCalledTimes(0)++ // User leaves the dashboard before it ever loads. The gate re-reads the scene each tick,+ // so it must stop waiting and send rather than block until the timeout.+ jest.spyOn(sceneLogic.selectors, 'activeSceneId').mockReturnValue(Scene.SavedInsights)+ jest.spyOn(sceneLogic.selectors, 'activeSceneLogic').mockReturnValue(null as any)+ await jest.advanceTimersByTimeAsync(300)++ expect(streamSpy).toHaveBeenCalledTimes(1)+ } finally {+ jest.useRealTimers()+ }})it('sends form_answers in ui_context when provided', async () => {@@ -1510,6 +1612,179 @@ describe('maxThreadLogic', () => {})})+ describe('sandbox history-load branch', () => {+ const SANDBOX_TASK_ID = 'task-abc'+ const SANDBOX_RUN_ID = 'run-abc'++ function sandboxConversation(currentRunId: string | null): ConversationDetail {+ return {+ id: MOCK_CONVERSATION_ID,+ status: ConversationStatus.InProgress,+ title: 'Sandbox chat',+ user: MOCK_DEFAULT_BASIC_USER,+ created_at: new Date().toISOString(),+ updated_at: new Date().toISOString(),+ type: ConversationType.Assistant,+ agent_runtime: 'sandbox',+ task: { id: SANDBOX_TASK_ID, latest_run: currentRunId },+ messages: [],+ }+ }++ it('replays logs/ then opens SSE for a non-terminal sandbox run, never reconnecting LangGraph', async () => {+ logic.unmount()+ jest.spyOn(api.conversations, 'get').mockResolvedValue(sandboxConversation(SANDBOX_RUN_ID))+ const logsSpy = jest.spyOn(api.tasks.runs, 'getLogEntries').mockResolvedValue([])+ const runSpy = jest.spyOn(api.tasks.runs, 'get').mockResolvedValue({ status: 'in_progress' } as any)+ const streamSpy = mockStream()++ logic = maxThreadLogic({+ conversationId: MOCK_CONVERSATION_ID,+ panelId: 'test',+ conversation: sandboxConversation(SANDBOX_RUN_ID),+ })+ logic.mount()+ // Drain the async afterMount (loadConversation → bootstrapRun → logs/ replay → run refetch).+ await new Promise((resolve) => setTimeout(resolve, 0))+ await new Promise((resolve) => setTimeout(resolve, 0))++ // bootstrapRun replayed logs/ and refetched the run, then opened SSE — and the LangGraph+ // stream was never touched (coexistence).+ expect(logsSpy).toHaveBeenCalledWith(SANDBOX_TASK_ID, SANDBOX_RUN_ID)+ expect(runSpy).toHaveBeenCalledWith(SANDBOX_TASK_ID, SANDBOX_RUN_ID)+ expect(streamSpy).not.toHaveBeenCalled()+ })++ it('does not bootstrap a sandbox run without a latest_run', async () => {+ logic.unmount()+ jest.spyOn(api.conversations, 'get').mockResolvedValue(sandboxConversation(null))+ const logsSpy = jest.spyOn(api.tasks.runs, 'getLogEntries')+ const streamSpy = mockStream()++ logic = maxThreadLogic({+ conversationId: MOCK_CONVERSATION_ID,+ panelId: 'test',+ conversation: sandboxConversation(null),+ })+ logic.mount()+ await new Promise((resolve) => setTimeout(resolve, 0))++ expect(logsSpy).not.toHaveBeenCalled()+ expect(streamSpy).not.toHaveBeenCalled()+ })+ })++ describe('sandbox prewarm', () => {+ const flush = (): Promise<void> => new Promise((resolve) => setTimeout(resolve, 0))++ function idleSandboxConversation(): ConversationDetail {+ return {+ id: MOCK_CONVERSATION_ID,+ status: ConversationStatus.Idle,+ title: 'Sandbox chat',+ user: MOCK_DEFAULT_BASIC_USER,+ created_at: new Date().toISOString(),+ updated_at: new Date().toISOString(),+ type: ConversationType.Assistant,+ agent_runtime: 'sandbox',+ task: { id: 'task-1', latest_run: null },+ messages: [],+ }+ }++ async function mountIdleSandbox(): Promise<void> {+ logic.unmount()+ jest.spyOn(api.conversations, 'get').mockResolvedValue(idleSandboxConversation())+ logic = maxThreadLogic({+ conversationId: MOCK_CONVERSATION_ID,+ panelId: 'test',+ conversation: idleSandboxConversation(),+ })+ logic.mount()+ await flush()+ }++ const warmHandle = {+ task_id: 'task-1',+ run_id: 'run-1',+ trace_id: null,+ run_status: 'in_progress' as const,+ just_created_run: true,+ }++ it('releases a warm sandbox abandoned while the warm POST was still in flight', async () => {+ await mountIdleSandbox()++ // Warm = open with content: null. Keep the POST in flight so the abandon races it.+ let resolvePrewarm: (handle: typeof warmHandle) => void = () => {}+ const openSpy = jest+ .spyOn(api.conversations, 'open')+ .mockReturnValue(new Promise<typeof warmHandle>((resolve) => (resolvePrewarm = resolve)) as any)++ logic.actions.prewarmSandbox()+ await flush()+ expect(openSpy).toHaveBeenCalledWith(MOCK_CONVERSATION_ID, {+ content: null,+ initial_permission_mode: 'auto',+ })++ // User abandons the input before the warm resolves — nothing is warm yet, so the release+ // is deferred (pendingRelease), not dropped, and no cancel fires.+ await expectLogic(logic, () => {+ logic.actions.releaseSandboxPrewarm()+ }).toNotHaveDispatchedActions(['cancelSandboxRun'])+ await flush()++ // The warm POST resolves — the deferred release fires cancelSandboxRun so the sandbox+ // isn't leaked.+ await expectLogic(logic, () => {+ resolvePrewarm(warmHandle)+ }).toDispatchActions(['cancelSandboxRun'])+ })++ it('does not release a warm that resolved with no pending abandon', async () => {+ await mountIdleSandbox()++ jest.spyOn(api.conversations, 'open').mockResolvedValue(warmHandle)++ await expectLogic(logic, () => {+ logic.actions.prewarmSandbox()+ }).toNotHaveDispatchedActions(['cancelSandboxRun'])+ await flush()+ await flush()+ })+ })++ describe('filteredCommands runtime filter', () => {+ function setRuntime(runtime: 'langgraph' | 'sandbox'): void {+ logic.actions.setConversation({+ ...MOCK_IN_PROGRESS_CONVERSATION,+ status: ConversationStatus.Idle,+ agent_runtime: runtime,+ } as Conversation)+ // Empty question matches every command by prefix.+ maxLogicInstance.actions.setQuestion('')+ }++ it('hides /init and /remember for sandbox conversations, keeps /usage and /feedback', async () => {+ setRuntime('sandbox')+ const names = logic.values.filteredCommands.map((c) => c.name)+ expect(names).not.toContain(SlashCommandName.SlashInit)+ expect(names).not.toContain(SlashCommandName.SlashRemember)+ expect(names).toContain(SlashCommandName.SlashUsage)+ expect(names).toContain(SlashCommandName.SlashFeedback)+ })++ it('keeps the full command set for langgraph conversations', async () => {+ setRuntime('langgraph')+ const names = logic.values.filteredCommands.map((c) => c.name)+ expect(names).toContain(SlashCommandName.SlashInit)+ expect(names).toContain(SlashCommandName.SlashRemember)+ expect(names).toContain(SlashCommandName.SlashUsage)+ expect(names).toContain(SlashCommandName.SlashFeedback)+ })+ })+describe('command selection and activation', () => {beforeEach(() => {logic = maxThreadLogic({ conversationId: MOCK_CONVERSATION_ID, panelId: 'test' })@@ -2855,6 +3130,25 @@ describe('maxThreadLogic', () => {})})+ describe('stopGeneration button state (LangGraph cancel race)', () => {+ it('clears all loading flags after a successful cancel so the stop button returns to send', async () => {+ jest.spyOn(api.conversations, 'cancel').mockResolvedValue(undefined)++ // An in-progress conversation drives conversationLoading -> true+ logic.actions.setConversation(MOCK_IN_PROGRESS_CONVERSATION)+ await expectLogic(logic).toMatchValues({ conversationLoading: true })++ await expectLogic(logic, () => {+ logic.actions.stopGeneration()+ }).toDispatchActions(['stopGeneration', 'setConversation', 'setCancelLoading'])++ expect(logic.values.conversationLoading).toBe(false)+ expect(logic.values.streamingActive).toBe(false)+ expect(logic.values.threadLoading).toBe(false)+ expect(logic.values.cancelLoading).toBe(false)+ })+ })+describe('multiQuestionFormPending selector', () => {it('returns true when thread ends with AssistantMessage containing create_form tool call', async () => {// With NodeInterrupt(None), no ToolCall message is created - the thread ends with the AssistantMessage@@ -3150,4 +3444,256 @@ describe('maxThreadLogic', () => {})})})++ describe('sandbox streaming lock', () => {+ const sandboxRunResponse = {+ task_id: 'task-1',+ run_id: 'run-1',+ trace_id: 'trace-1',+ run_status: 'queued' as const,+ just_created_run: true,+ }++ beforeEach(() => {+ // jsdom has no EventSource — a minimal stub lets openSseForRun set up its connection+ ;(globalThis as any).EventSource = class {+ onopen: ((event: Event) => void) | null = null+ onmessage: ((event: MessageEvent<string>) => void) | null = null+ addEventListener(): void {}+ close(): void {}+ }+ })++ afterEach(() => {+ delete (globalThis as any).EventSource+ })++ it('holds the streaming lock until the sandbox turn completes and releases exactly once', async () => {+ const openSpy = jest.spyOn(api.conversations, 'open').mockResolvedValue(sandboxRunResponse)++ await expectLogic(logic, () => {+ logic.actions.streamConversation(+ { agent_mode: null, is_sandbox: true, content: 'hello', conversation: MOCK_CONVERSATION_ID },+ 0+ )+ }).toDispatchActions(['openSandboxSse'])++ expect(openSpy).toHaveBeenCalledWith(+ MOCK_CONVERSATION_ID,+ expect.objectContaining({+ content: 'hello',+ initial_permission_mode: 'auto',+ })+ )++ // The POST finished, but the turn is still streaming — the lock must still be held+ expect(maxLogicInstance.values.activeStreamingThreads).toEqual(1)++ // The thread logic connects to the instance keyed by its own conversationId+ const sandboxStreamInstance = sandboxStreamLogic({ streamKey: MOCK_CONVERSATION_ID })++ // The release listeners are synchronous, so the lock state settles with the dispatch+ sandboxStreamInstance.actions.markTurnComplete()+ expect(maxLogicInstance.values.activeStreamingThreads).toEqual(0)++ // A later terminal event must not release the (already released) lock again+ maxLogicInstance.actions.incrActiveStreamingThreads()+ sandboxStreamInstance.actions.handleTerminalStatus({ status: 'completed' })+ expect(maxLogicInstance.values.activeStreamingThreads).toEqual(1)+ maxLogicInstance.actions.decrActiveStreamingThreads()+ })++ it('does not release the lock on a non-terminal task_run_state frame', async () => {+ jest.spyOn(api.conversations, 'open').mockResolvedValue(sandboxRunResponse)++ await expectLogic(logic, () => {+ logic.actions.streamConversation(+ { agent_mode: null, is_sandbox: true, content: 'hello', conversation: MOCK_CONVERSATION_ID },+ 0+ )+ }).toDispatchActions(['openSandboxSse'])++ const sandboxStreamInstance = sandboxStreamLogic({ streamKey: MOCK_CONVERSATION_ID })++ // queued / in_progress frames arrive before the turn is done — the lock must stay held.+ sandboxStreamInstance.actions.handleTerminalStatus({ status: 'queued' })+ expect(maxLogicInstance.values.activeStreamingThreads).toEqual(1)+ sandboxStreamInstance.actions.handleTerminalStatus({ status: 'in_progress' })+ expect(maxLogicInstance.values.activeStreamingThreads).toEqual(1)++ // Only an actually-terminal status releases it.+ sandboxStreamInstance.actions.handleTerminalStatus({ status: 'completed' })+ expect(maxLogicInstance.values.activeStreamingThreads).toEqual(0)+ })++ it('releases the lock immediately and surfaces an error when the send POST fails', async () => {+ jest.spyOn(api.conversations, 'open').mockRejectedValue(new Error('boom'))++ await expectLogic(logic, () => {+ logic.actions.streamConversation(+ { agent_mode: null, is_sandbox: true, content: 'hello', conversation: MOCK_CONVERSATION_ID },+ 0+ )+ }).toDispatchActions(['pushSandboxError', 'decrActiveStreamingThreads'])++ expect(maxLogicInstance.values.activeStreamingThreads).toEqual(0)+ expect(+ sandboxStreamLogic({ streamKey: MOCK_CONVERSATION_ID }).values.threadItems.some(+ (item) =>+ item.type === 'error' && item.errorMessage === 'Failed to send your message. Please try again.'+ )+ ).toEqual(true)+ })++ it('releases the lock immediately when no run was started', async () => {+ const openSpy = jest.spyOn(api.conversations, 'open')++ await expectLogic(logic, () => {+ logic.actions.streamConversation(+ { agent_mode: null, is_sandbox: true, content: null, conversation: MOCK_CONVERSATION_ID },+ 0+ )+ }).toDispatchActions(['decrActiveStreamingThreads'])++ expect(openSpy).not.toHaveBeenCalled()+ expect(maxLogicInstance.values.activeStreamingThreads).toEqual(0)+ })+ })++ describe('sandbox streamingActive teardown', () => {+ const sandboxRunResponse = {+ task_id: 'task-1',+ run_id: 'run-1',+ trace_id: 'trace-1',+ run_status: 'queued' as const,+ just_created_run: true,+ }++ beforeEach(() => {+ ;(globalThis as any).EventSource = class {+ onopen: ((event: Event) => void) | null = null+ onmessage: ((event: MessageEvent<string>) => void) | null = null+ addEventListener(): void {}+ close(): void {}+ }+ jest.spyOn(api.conversations, 'open').mockResolvedValue(sandboxRunResponse)+ })++ afterEach(() => {+ delete (globalThis as any).EventSource+ })++ async function startSandboxTurn(): Promise<ReturnType<typeof sandboxStreamLogic.build>> {+ await expectLogic(logic, () => {+ logic.actions.streamConversation(+ { agent_mode: null, is_sandbox: true, content: 'hello', conversation: MOCK_CONVERSATION_ID },+ 0+ )+ }).toDispatchActions(['openSandboxSse'])+ expect(logic.values.streamingActive).toBe(true)+ return sandboxStreamLogic({ streamKey: MOCK_CONVERSATION_ID })+ }++ it('tears down streamingActive on markTurnComplete', async () => {+ const sandboxStreamInstance = await startSandboxTurn()++ await expectLogic(logic, () => {+ sandboxStreamInstance.actions.markTurnComplete()+ }).toDispatchActions(['completeThreadGeneration'])++ expect(logic.values.streamingActive).toBe(false)+ expect(logic.values.threadLoading).toBe(false)+ })++ it('tears down streamingActive on handleTerminalStatus', async () => {+ const sandboxStreamInstance = await startSandboxTurn()++ await expectLogic(logic, () => {+ sandboxStreamInstance.actions.handleTerminalStatus({ status: 'completed' })+ }).toDispatchActions(['endStreaming'])++ expect(logic.values.streamingActive).toBe(false)+ expect(logic.values.threadLoading).toBe(false)+ })++ it('tears down streamingActive on handleStreamError', async () => {+ const sandboxStreamInstance = await startSandboxTurn()++ await expectLogic(logic, () => {+ sandboxStreamInstance.actions.handleStreamError({+ errorTitle: 'Error',+ errorMessage: 'boom',+ retryable: false,+ })+ }).toDispatchActions(['endStreaming'])++ expect(logic.values.streamingActive).toBe(false)+ expect(logic.values.threadLoading).toBe(false)+ })++ it('markTurnComplete drains the sandbox queue combined, without an optimistic echo', async () => {+ // No POSTHOG_AI_QUEUE_MESSAGES_SYSTEM flag — sandbox queueing is flag-independent.+ jest.spyOn(api.conversations.queue, 'clear').mockResolvedValue({ messages: [], max_queue_messages: 2 })++ const sandboxStreamInstance = await startSandboxTurn()+ // completeThreadGeneration's queue-drain only runs with a non-null conversation.+ // The id matches the mounted conversationId, so the setConversation listener won't clear the queue.+ logic.actions.setConversation(MOCK_CONVERSATION)+ logic.actions.setIsSandboxMode(true)+ logic.actions.setQueuedMessages([+ { id: 'queue-1', content: 'First', created_at: new Date().toISOString() },+ { id: 'queue-2', content: 'Second', created_at: new Date().toISOString() },+ ])++ // markTurnComplete tears down streaming, then the drain clears the queue and re-sends the+ // combined text with addToThread:false (so it renders on the live echo, not optimistically).+ await expectLogic(logic, () => {+ sandboxStreamInstance.actions.markTurnComplete()+ }).toDispatchActions([+ 'completeThreadGeneration',+ 'clearQueuedMessages',+ (action: any) => action.payload?.prompt === 'First\n\nSecond' && action.payload?.addToThread === false,+ ])+ })++ it('handleStreamError does NOT drain the sandbox queue (no clearQueuedMessages, no askMax)', async () => {+ featureFlagLogic.mount()+ featureFlagLogic.actions.setFeatureFlags([], {+ [FEATURE_FLAGS.POSTHOG_AI_QUEUE_MESSAGES_SYSTEM]: true,+ })++ const sandboxStreamInstance = await startSandboxTurn()+ logic.actions.setIsSandboxMode(true)+ const queueMessage = { id: 'queue-1', content: 'Next message', created_at: new Date().toISOString() }+ logic.actions.setQueuedMessages([queueMessage])++ await expectLogic(logic, () => {+ sandboxStreamInstance.actions.handleStreamError({+ errorTitle: 'Error',+ errorMessage: 'boom',+ retryable: false,+ })+ })+ .toDispatchActions(['endStreaming'])+ .toNotHaveDispatchedActions(['completeThreadGeneration', 'clearQueuedMessages', 'askMax'])++ expect(logic.values.streamingActive).toBe(false)+ // The failed turn must not auto-start the queued message+ expect(logic.values.queuedMessages).toEqual([queueMessage])++ featureFlagLogic.unmount()+ })++ it('history-replay terminal events do not fire teardown while streamingActive is false', async () => {+ // No live turn: streamingActive is false (no streamConversation was dispatched)+ expect(logic.values.streamingActive).toBe(false)+ const sandboxStreamInstance = sandboxStreamLogic({ streamKey: MOCK_CONVERSATION_ID })++ await expectLogic(logic, () => {+ sandboxStreamInstance.actions.handleTerminalStatus({ status: 'completed', replayedFromHistory: true })+ }).toNotHaveDispatchedActions(['endStreaming', 'completeThreadGeneration', 'askMax'])++ expect(logic.values.streamingActive).toBe(false)+ })+ })})diff --git a/frontend/src/scenes/max/maxThreadLogic.tsx b/frontend/src/scenes/max/maxThreadLogic.tsxindex c64a2b1d096a..513cf6ff7ace 100644--- a/frontend/src/scenes/max/maxThreadLogic.tsx+++ b/frontend/src/scenes/max/maxThreadLogic.tsx@@ -68,12 +68,21 @@ import { LogEntry, parseLogEvent } from 'products/tasks/frontend/lib/parse-logs'import { handsFreeLogic } from './handsFreeLogic'import { summariseAssistantThread } from './handsFreeUtils'-import { EnhancedToolCall, MODE_DEFINITIONS, TOOL_DEFINITIONS, ToolRegistration } from './max-constants'+import {+ EnhancedToolCall,+ MODE_DEFINITIONS,+ TOOL_DEFINITIONS,+ ToolRegistration,+ getModeDisplayName,+} from './max-constants'+import { PENDING_AI_PROMPT_KEY } from './max-storage-keys'import { MaxBillingContext, MaxBillingContextSubscriptionLevel, maxBillingContextLogic } from './maxBillingContextLogic'import { maxGlobalLogic } from './maxGlobalLogic'import { SIDE_PANEL_PANEL_ID, maxLogic } from './maxLogic'import type { maxThreadLogicType } from './maxThreadLogicType'-import { MaxUIContext } from './maxTypes'+import { AttachedContext, MaxUIContext } from './maxTypes'+import { posthogAiContextLogic } from './posthogAiContextLogic'+import { SANDBOX_INITIAL_PERMISSION_MODE, isTerminalRunStatus, sandboxStreamLogic } from './sandboxStreamLogic'import { MAX_SLASH_COMMANDS, SlashCommand } from './slash-commands'import { getToolCallDescriptionAndWidgetDef } from './toolCallDisplay'import {@@ -87,8 +96,11 @@ import {} from './utils'import { getRandomThinkingMessage } from './utils/thinkingMessages'-/** Key for persisting pending AI prompts across page reloads (e.g., OAuth redirects) */-export const PENDING_AI_PROMPT_KEY = 'posthog_ai_pending_prompt'+// On a dashboard, the first message can fire before the dashboard has loaded, when+// dashboardLogic.maxContext still returns []. askMax waits (bounded) for the load so the+// dashboard context is included. Bounded so a stuck/failed load never blocks sending.+export const MAX_DASHBOARD_CONTEXT_WAIT_MS = 8000+const DASHBOARD_CONTEXT_POLL_INTERVAL_MS = 100export type MessageStatus = 'loading' | 'completed' | 'error'@@ -142,7 +154,7 @@ export const maxThreadLogic = kea<maxThreadLogicType>([}}),- connect(({ panelId }: MaxThreadLogicProps) => ({+ connect(({ panelId, conversationId }: MaxThreadLogicProps) => ({values: [maxGlobalLogic,['dataProcessingAccepted', 'toolMap', 'tools', 'availableStaticTools'],@@ -153,6 +165,7 @@ export const maxThreadLogic = kea<maxThreadLogicType>(['threadLogicKey as activeThreadKey','activeStreamingThreads','conversationId as parentConversationId',+ 'pendingBindTaskId',],maxContextLogic,['compiledContext'],@@ -162,6 +175,16 @@ export const maxThreadLogic = kea<maxThreadLogicType>([['featureFlags'],sceneLogic,['sceneId'],+ // Mounts this conversation's sandbox attachment store so its `attachments` are readable+ // at send time even when no context-chip UI is rendered (a fresh conversation never+ // mounts it itself).+ posthogAiContextLogic({ conversationId }),+ ['attachments as sandboxAttachments'],+ // Surfaces the sandbox stream's input-area state to components outside SandboxThread's+ // BindLogic subtree (the input area renders for LangGraph conversations too, so they+ // can't bind the keyed stream logic themselves).+ sandboxStreamLogic({ streamKey: conversationId, conversationId }),+ ['pendingPermissionRequest as pendingSandboxPermissionRequest', 'currentMode as sandboxCurrentMode'],],actions: [maxLogic({ panelId }),@@ -175,9 +198,25 @@ export const maxThreadLogic = kea<maxThreadLogicType>(['setConversationId','setAutoRun','loadConversationHistorySuccess',+ 'setPendingBindTaskId',],maxGlobalLogic,['loadConversation'],+ // Pulling the action in (rather than calling the instance's actions directly) mounts this+ // conversation's stream logic as a dependency, so its listeners actually run. SandboxThread+ // only mounts it while a sandbox conversation is rendered — too late for the first message+ // of a new one.+ sandboxStreamLogic({ streamKey: conversationId, conversationId }),+ [+ 'openSseForRun as openSandboxSse',+ 'pushHumanMessage as pushSandboxHumanMessage',+ 'pushErrorItem as pushSandboxError',+ 'bootstrapRun as bootstrapSandboxRun',+ 'reset as resetSandboxStream',+ 'cancelRun as cancelSandboxRun',+ ],+ posthogAiContextLogic({ conversationId }),+ ['clearAttachments as clearSandboxAttachments'],],})),@@ -199,6 +238,10 @@ export const maxThreadLogic = kea<maxThreadLogicType>([) => ({ streamData, generationAttempt, addToThread }),stopGeneration: true,completeThreadGeneration: true,+ // Narrow teardown: flips only streamingActive -> false. Used by the sandbox error/terminal+ // listeners where completeThreadGeneration's queue-drain (auto-starting the next message)+ // would be wrong after a failure.+ endStreaming: true,addMessage: (message: ThreadMessage) => ({ message }),replaceMessage: (index: number, message: ThreadMessage) => ({index,@@ -254,6 +297,8 @@ export const maxThreadLogic = kea<maxThreadLogicType>([setPendingApproval: (proposalId: string) => ({ proposalId }),clearPendingApproval: true,appendSandboxEntry: (entry: LogEntry) => ({ entry }),+ prewarmSandbox: true,+ releaseSandboxPrewarm: true,refreshSandboxEntries: true,resetSandboxEntries: true,continueAfterForm: (formAnswers: MultiQuestionFormAnswers) => ({@@ -328,6 +373,7 @@ export const maxThreadLogic = kea<maxThreadLogicType>([reconnectToStream: () => true,streamConversation: () => true,completeThreadGeneration: () => false,+ endStreaming: () => false,},],@@ -621,7 +667,24 @@ export const maxThreadLogic = kea<maxThreadLogicType>([const traceId = uuid()actions.setTraceId(traceId)- if (generationAttempt === 0 && streamData.content && addToThread) {+ // Sandbox runtime: route the message to a non-streaming products/tasks Run, then hand the+ // SSE connection off to sandboxStreamLogic. The LangGraph EventSource loop below is never+ // entered for sandbox conversations.+ //+ // An *existing* sandbox conversation (`agent_runtime === 'sandbox'`) uses the dedicated+ // `/sandbox/` routing endpoint. A *brand-new* conversation has no row yet — it's created+ // lazily on the first message — so `agent_runtime` isn't known here; we detect the+ // `is_sandbox` flag and let the conversation-create endpoint create it + return the run+ // IDs as JSON (both endpoints return the identical { task_id, run_id, just_created_run }).+ const isExistingSandboxConversation = values.conversation?.agent_runtime === 'sandbox'+ const isSandboxConversation = isExistingSandboxConversation || !!isSandbox++ // Echo the human message into whichever thread the renderer actually shows. A sandbox+ // conversation renders sandboxStreamLogic's threadItems (not this logic's thread) and+ // echoes via pushSandboxHumanMessage below; adding it to the legacy thread too would+ // briefly show a duplicate (until the runtime resolves to the SandboxThread) that vanishes+ // on reload, since sandbox turns live in the run log, not the legacy conversation messages.+ if (generationAttempt === 0 && streamData.content && addToThread && !isSandboxConversation) {const message: ThreadMessage = {type: AssistantMessageType.Human,content: streamData.content,@@ -631,6 +694,80 @@ export const maxThreadLogic = kea<maxThreadLogicType>([actions.addMessage(message)}+ if (isSandboxConversation) {+ // SandboxThread renders sandboxStreamLogic's threadItems, not this logic's thread,+ // so the human message must be echoed there to show up in the UI.+ if (generationAttempt === 0 && streamData.content && addToThread) {+ actions.pushSandboxHumanMessage(streamData.content)+ // Pull the current scene's `maxContext` into the sandbox attachments at send+ // (consumption) time so on-scene entities flow into `sandboxAttachments` below.+ // Nothing else dispatches this, so without it scene context never auto-attaches.+ posthogAiContextLogic({ conversationId: props.conversationId }).actions.syncSceneAttachments()+ }+ try {+ const conversationId = values.conversation?.id || values.conversationId+ if (conversationId && streamData.content) {+ // The sandbox runtime has no agent modes — they're a legacy LangGraph concept. If the+ // user still picked one, carry it through as a context note so the agent can acknowledge it.+ const attachedContext: AttachedContext[] = [...values.sandboxAttachments]+ if (values.agentMode) {+ attachedContext.push({+ type: 'text',+ value: `The user selected a mode: "${getModeDisplayName(values.agentMode)}". It was in the legacy implementation. Acknowledge the mode if the user refers to it.`,+ })+ }+ // Single create-or-resume opener: it creates the conversation row on first use,+ // starts/continues the Run, and returns the (task, run) handle. A message always+ // provisions a run (a null handle only happens on a warm with a full pool).+ const handle = await api.conversations.open(conversationId, {+ content: streamData.content,+ trace_id: traceId,+ attached_context: attachedContext,+ initial_permission_mode: SANDBOX_INITIAL_PERMISSION_MODE,+ // Bind a brand-new conversation to an existing Task (inbox "Open task") so the+ // backend resumes that Task's run. Only the first message carries it.+ ...(values.pendingBindTaskId ? { task_id: values.pendingBindTaskId } : {}),+ })+ if (handle) {+ // The sent message consumes any in-flight warm — it's now the active run, so+ // drop the release handle to avoid cancelling the run out from under it.+ cache.warmRun = null+ // The bind is one-shot: the conversation now exists bound to the Task, so+ // follow-ups target it directly — don't re-send task_id.+ if (values.pendingBindTaskId) {+ actions.setPendingBindTaskId(null)+ }+ actions.openSandboxSse({+ taskId: handle.task_id,+ runId: handle.run_id,+ // Fresh runs need everything from the top; follow-ups resume from latest.+ startLatest: !handle.just_created_run,+ // Correlate SSE-side telemetry with the trace this run was sent under.+ traceId,+ })+ // The streaming lock must span the whole SSE stream so the input stays+ // guarded until `_posthog/turn_complete` or a terminal/error event —+ // mirrors the LangGraph path holding the lock for its entire stream.+ // Released exactly once by the sandboxStreamLogic listeners below; the+ // closure nulls itself so a second terminal event is a no-op.+ cache.sandboxStreamRelease = (): void => {+ cache.sandboxStreamRelease = null+ actions.decrActiveStreamingThreads()+ releaseStreamingLock()+ }+ return+ }+ }+ } catch (e) {+ posthog.captureException(e)+ actions.pushSandboxError('Failed to send your message. Please try again.')+ }+ // The POST failed or no run was started — nothing will stream, release the lock now.+ actions.decrActiveStreamingThreads()+ releaseStreamingLock()+ return+ }+let caughtException = falsetry {@@ -649,10 +786,6 @@ export const maxThreadLogic = kea<maxThreadLogicType>([apiData.agent_mode = agentMode}- if (isSandbox) {- apiData.is_sandbox = true- }-const response = await api.conversations.stream(apiData, {signal: cache.generationController.signal,})@@ -849,6 +982,43 @@ export const maxThreadLogic = kea<maxThreadLogicType>([releaseStreamingLock() // release the lock},})),+ // Sandbox runs stream through this conversation's sandboxStreamLogic instance, so the streaming+ // lock taken in streamConversation can only be released when that instance signals the turn+ // ended — on turn completion, a terminal run status, or a stream error. Its action types are+ // per-instance (the key is in the path), so they're resolved from props at build time.+ listeners(({ props, cache, actions, values }) => {+ const sandboxStreamActionTypes = sandboxStreamLogic({ streamKey: props.conversationId }).actionTypes+ // Normal turn completion: full turn-end, including the sandbox queue-drain that starts the+ // next queued message (completeThreadGeneration's intended next-turn behavior).+ const completeSandboxTurn = (): void => {+ cache.sandboxStreamRelease?.()+ if (values.streamingActive) {+ actions.completeThreadGeneration()+ }+ }+ // Error / terminal status: just stop streaming. Must NOT run completeThreadGeneration's+ // queue-drain — auto-starting the next queued message after a failure is wrong. The+ // streamingActive guard also keeps history-replay terminal events (replayedFromHistory,+ // dispatched during bootstrapRun with no live turn) from firing teardown.+ const endSandboxStream = (): void => {+ cache.sandboxStreamRelease?.()+ if (values.streamingActive) {+ actions.endStreaming()+ }+ }+ return {+ [sandboxStreamActionTypes.markTurnComplete]: completeSandboxTurn,+ // handleTerminalStatus fires for every task_run_state frame, including the initial+ // non-terminal queued/in_progress ones — only tear down on an actually terminal+ // status, mirroring sandboxStreamLogic's own guard.+ [sandboxStreamActionTypes.handleTerminalStatus]: ({ status }: { status: string }) => {+ if (isTerminalRunStatus(status)) {+ endSandboxStream()+ }+ },+ [sandboxStreamActionTypes.handleStreamError]: endSandboxStream,+ }+ }),listeners(({ actions, values, cache, props }) => ({setConversation: ({ conversation }) => {const nextConversationId = conversation?.id ?? null@@ -875,6 +1045,96 @@ export const maxThreadLogic = kea<maxThreadLogicType>([}// Note: pending approvals loading is handled in the reducer (pendingApprovalsData.setConversation)},+ setQuestion: ({ question }) => {+ // Sandbox pre-warming. Debounce on the first non-whitespace keystroke so the sandbox+ // boots while the user is still typing; release if the input empties.+ // LangGraph conversations are unaffected.+ if (values.conversation?.agent_runtime !== 'sandbox') {+ return+ }+ // Don't warm if a run is already active — the live Run is the desired state.+ if (values.threadLoading) {+ return+ }+ if (question.trim() === '') {+ // Input emptied — cancel a pending warm trigger and schedule release after 5s.+ cache.disposables.dispose('prewarm-debounce')+ if (cache.prewarmed) {+ cache.disposables.add(() => {+ const timer = setTimeout(() => actions.releaseSandboxPrewarm(), 5000)+ return () => clearTimeout(timer)+ }, 'prewarm-release')+ }+ return+ }+ // Non-empty input: cancel any pending release, then debounce the warm.+ cache.disposables.dispose('prewarm-release')+ if (cache.prewarmed) {+ return+ }+ cache.disposables.add(() => {+ const timer = setTimeout(() => actions.prewarmSandbox(), 250)+ return () => clearTimeout(timer)+ }, 'prewarm-debounce')+ },+ prewarmSandbox: async () => {+ cache.disposables.dispose('prewarm-debounce')+ if (values.conversation?.agent_runtime !== 'sandbox' || !values.conversationId) {+ return+ }+ // Guard against duplicate warms and warming over an active run.+ if (cache.prewarmed || cache.prewarming || values.threadLoading) {+ return+ }+ cache.prewarming = true+ cache.pendingRelease = false+ try {+ // Warm = open with no message: boots a Run that idles awaiting the first message. The+ // returned handle lets a later release cancel exactly that Run via the relay (a full+ // pool returns null — nothing to release).+ const warm = await api.conversations.open(values.conversationId, {+ content: null,+ initial_permission_mode: SANDBOX_INITIAL_PERMISSION_MODE,+ })+ cache.warmRun = warm ? { taskId: warm.task_id, runId: warm.run_id } : null+ cache.prewarmed = true+ // If the user abandoned the input while this POST was in flight, the blur/empty+ // release hit the early-exit (nothing was warm yet). Honor it now so the freshly+ // warmed sandbox isn't leaked until the agent-server's idle self-cancel.+ if (cache.pendingRelease) {+ cache.pendingRelease = false+ actions.releaseSandboxPrewarm()+ }+ } catch (e) {+ // Pre-warming is best-effort latency optimization; a failure just means the first+ // message takes the cold path. Don't surface it to the user.+ posthog.captureException(e)+ } finally {+ cache.prewarming = false+ }+ },+ releaseSandboxPrewarm: async () => {+ cache.disposables.dispose('prewarm-debounce')+ cache.disposables.dispose('prewarm-release')+ if (!cache.prewarmed || !values.conversationId) {+ // A warm POST may still be in flight — record the intent so its success handler+ // releases the sandbox instead of dropping the request on the floor.+ if (cache.prewarming) {+ cache.pendingRelease = true+ }+ cache.prewarmed = false+ return+ }+ // A warm consumed by a sent message must not be released — only release on abandon.+ cache.prewarmed = false+ const warmRun = cache.warmRun as { taskId: string; runId: string } | undefined+ cache.warmRun = null+ if (warmRun) {+ // Release = cancel the warm Run through the generic relay (owned by the renderer logic);+ // it transitions to terminal and drops out of the warm-pool count.+ actions.cancelSandboxRun(warmRun)+ }+ },enqueueQueuedMessage: async ({ content, contextualTools, uiContext, billingContext, agentMode }) => {if (!values.queueingEnabled || !values.conversation?.id) {actions.setQueuedMessages([])@@ -1000,11 +1260,57 @@ export const maxThreadLogic = kea<maxThreadLogicType>([actions.clearQueuedMessages()}},- askMax: async ({ prompt, addToThread = true, uiContext }) => {+ askMax: async ({ prompt, addToThread = true, uiContext }, breakpoint) => {// Only process if this thread is the currently active oneif (values.conversationId !== values.activeThreadKey) {return}+ // A sent message consumes any sandbox pre-warm: the warm Run is the in-progress run the+ // sandbox routing follows up on, so cancel pending timers and clear the flag WITHOUT+ // issuing a release/DELETE.+ cache.disposables.dispose('prewarm-debounce')+ cache.disposables.dispose('prewarm-release')+ cache.prewarmed = false+ cache.warmRun = null+ // A sent message consumes the warm — drop any in-flight release intent so the+ // run the message follows up on isn't cancelled out from under it.+ cache.pendingRelease = false+ // Wait for the open dashboard to finish loading before collecting context (see the+ // constants above for why). The scene is re-read every tick, so the gate releases the+ // moment the dashboard's metadata lands — and immediately if the user navigates away+ // mid-wait (no longer on a dashboard, or onto a different one that's already loaded).+ const isDashboardSceneLoading = (): boolean => {+ if (sceneLogic.values.activeSceneId !== Scene.Dashboard) {+ return false+ }+ const activeSceneLogic = sceneLogic.values.activeSceneLogic+ if (!activeSceneLogic || !('maxContext' in activeSceneLogic.selectors)) {+ return false+ }+ return !(activeSceneLogic.values as { dashboard?: unknown }).dashboard+ }+ // Measure real elapsed time, not tick count: breakpoint() only guarantees a *minimum*+ // delay, so a busy event loop would make a tick counter under-report the wait — letting+ // it run past the cap and skewing the telemetry below. performance.now() is monotonic.+ const dashboardWaitStart = performance.now()+ while (+ isDashboardSceneLoading() &&+ performance.now() - dashboardWaitStart < MAX_DASHBOARD_CONTEXT_WAIT_MS+ ) {+ await breakpoint(DASHBOARD_CONTEXT_POLL_INTERVAL_MS)+ }+ if (isDashboardSceneLoading()) {+ // We hit the wait cap while the dashboard was still loading, so the message ships+ // without dashboard context (the original "Max can't see this dashboard" symptom).+ // Capture it so we can tell whether the cap is ever the binding constraint in prod.+ const activeLoadedScene = sceneLogic.values.activeLoadedScene+ const sceneProps = activeLoadedScene?.paramsToProps?.(activeLoadedScene?.sceneParams) || {}+ posthog.capture('max dashboard context wait timed out', {+ waited_ms: Math.round(performance.now() - dashboardWaitStart),+ dashboard_id: (sceneProps as { id?: number | string }).id,+ conversation_id: values.conversation?.id || values.conversationId,+ })+ }const contextualTools = Object.fromEntries(values.tools.map((tool) => [tool.identifier, tool.context]))// Always send voice_mode as an explicit boolean when handsFreeLogic is mounted,// not just when active. Otherwise a typed turn following a spoken one inherits@@ -1086,6 +1392,13 @@ export const maxThreadLogic = kea<maxThreadLogicType>([actions.clearPendingApproval()actions.setResolvedApprovalStatus(pendingProposalId, 'auto_rejected')}+ // A pending task-bind (inbox "Open task") makes this first message a sandbox task-resume:+ // the conversation is created bound to the Task and its run is resumed. Force sandbox mode+ // so the message routes through the sandbox `open` endpoint (which carries the task_id).+ // Reducers apply synchronously, so the `is_sandbox` derivation below sees the new value.+ if (values.pendingBindTaskId && !values.isSandboxMode) {+ actions.setIsSandboxMode(true)+ }const agentMode = values.agentMode// Clear the question@@ -1132,10 +1445,24 @@ export const maxThreadLogic = kea<maxThreadLogicType>([}try {- await api.conversations.cancel(values.conversation.id)+ if (values.conversation.agent_runtime === 'sandbox') {+ // Sandbox runs cancel through the generic tasks relay (the renderer owns the run id).+ actions.cancelSandboxRun()+ } else {+ await api.conversations.cancel(values.conversation.id)+ }cache.generationController?.abort()actions.clearQueuedMessages()actions.resetThread()+ // Optimistically clear the loading flags so the composer button returns to "send"+ // immediately, instead of racing the fire-and-forget loadConversation refetch below+ // (whose success handler is gated on streamingActive). The refetch still reconciles+ // the true server status moments later.+ if (values.conversation) {+ const canceledConversation = { ...values.conversation, status: ConversationStatus.Idle }+ actions.setConversation(canceledConversation)+ actions.updateGlobalConversationCache(canceledConversation)+ }} catch (e: any) {posthog.captureException(e)lemonToast.error(e?.data?.detail || 'Failed to cancel the generation.')@@ -1212,11 +1539,13 @@ export const maxThreadLogic = kea<maxThreadLogicType>([// Process queued messages for sandbox conversations.// Regular conversations handle queue consumption on the backend// (process_chat_agent_activity pops and starts new workflows).- // Sandbox mode doesn't have this, so the frontend drives it.+ // Sandbox mode doesn't have this, so the frontend drives it: combine every queued+ // follow-up into one send. `addToThread: false` skips the optimistic echo so the message+ // renders only when the live stream echoes it back (stream-confirmed), not at drain time.if (shouldConsumeSandboxQueue) {- const nextMessage = values.queuedMessages[0]- actions.consumeQueuedMessage(nextMessage)- actions.askMax(nextMessage.content)+ const combined = values.queuedMessages.map((message) => message.content).join('\n\n')+ actions.clearQueuedMessages()+ actions.askMax(combined, false)}// Must go last. Otherwise, the logic will be unmounted before the lifecycle finishes.@@ -1445,6 +1774,19 @@ export const maxThreadLogic = kea<maxThreadLogicType>([(conversation, propsConversationId) => (conversation?.id ? conversation.id : propsConversationId),],+ // The exact id this instance was keyed with. React must bind the per-conversation sandbox+ // logics with the same id connect() used above, or the two would resolve different instances.+ sandboxConversationKey: [(_, p) => [p.conversationId], (conversationId): string => conversationId],++ // A converted conversation: now on the sandbox runtime but still carrying its legacy+ // LangGraph history. Drives the dual render (full legacy thread → "history was converted"+ // divider → live sandbox thread). Reads `threadRaw`, not `threadGrouped`, so the streaming+ // thinking-loader injected into `threadGrouped` can't be mistaken for legacy content.+ isConvertedConversation: [+ (s) => [s.conversation, s.threadRaw],+ (conversation, threadRaw): boolean => conversation?.agent_runtime === 'sandbox' && threadRaw.length > 0,+ ],+effectiveApprovalStatuses: [(s) => [s.resolvedApprovalStatuses, s.pendingApprovalsData],(resolved, pendingApprovalsData): Record<string, { status: ApprovalDecisionStatus; feedback?: string }> => {@@ -1497,8 +1839,12 @@ export const maxThreadLogic = kea<maxThreadLogicType>([],queueingEnabled: [- (s) => [s.featureFlags],- (featureFlags): boolean => !!featureFlags[FEATURE_FLAGS.POSTHOG_AI_QUEUE_MESSAGES_SYSTEM],+ // Sandbox conversations always queue follow-ups sent mid-turn (the backend queue endpoints+ // aren't flag-gated, and the sandbox runtime drives the drain itself); LangGraph stays+ // behind the rollout flag.+ (s) => [s.featureFlags, s.isSandboxMode],+ (featureFlags, isSandboxMode): boolean =>+ !!featureFlags[FEATURE_FLAGS.POSTHOG_AI_QUEUE_MESSAGES_SYSTEM] || isSandboxMode,],queueIsFull: [@@ -1770,12 +2116,13 @@ export const maxThreadLogic = kea<maxThreadLogicType>([],filteredCommands: [- (s) => [s.question, s.featureFlags, s.threadLoading, s.billingContext],+ (s) => [s.question, s.featureFlags, s.threadLoading, s.billingContext, s.conversation],(question: string,featureFlags: Record<string, boolean | string>,threadLoading: boolean,- billingContext: MaxBillingContext | null+ billingContext: MaxBillingContext | null,+ conversation: Conversation | null): SlashCommand[] => {const hasPaidPlan =billingContext?.subscription_level === MaxBillingContextSubscriptionLevel.PAID ||@@ -1783,12 +2130,16 @@ export const maxThreadLogic = kea<maxThreadLogicType>([billingContext?.trial?.is_active ||process.env.NODE_ENV === 'development'+ // Sandbox runtime drops core-memory commands; LangGraph keeps the full set.+ const isSandboxRuntime = conversation?.agent_runtime === 'sandbox'+return MAX_SLASH_COMMANDS.filter((command) =>command.name.toLowerCase().startsWith(question.toLowerCase()) &&(!command.flag || featureFlags[command.flag]) &&(!command.requiresIdle || !threadLoading) &&- (!command.requiresPaidPlan || hasPaidPlan)+ (!command.requiresPaidPlan || hasPaidPlan) &&+ (!command.hiddenInSandbox || !isSandboxRuntime))},],@@ -1910,6 +2261,27 @@ export const maxThreadLogic = kea<maxThreadLogicType>([return}+ // Sandbox history-load branch. Sandbox conversations don't persist messages Django-side —+ // history lives in S3 ACP logs, read via the products/tasks logs/ endpoint. Hand off to+ // sandboxStreamLogic, which replays logs/ then opens SSE if non-terminal. The LangGraph+ // reconnect path below is never entered for sandbox runtimes (coexistence).+ if (conversation.agent_runtime === 'sandbox') {+ // sandboxStreamLogic and posthogAiContextLogic are connected (so already mounted) for this+ // conversation. Reset their per-conversation state before replaying this run's history.+ actions.resetSandboxStream()+ actions.clearSandboxAttachments()+ if (conversation.task) {+ const runId = conversation.task.latest_run+ if (runId) {+ actions.bootstrapSandboxRun({+ taskId: conversation.task.id,+ runId,+ })+ }+ }+ return+ }+// Ensure threadRaw is hydrated before streaming, so setThread doesn't overwrite stream tokens.if (values.threadRaw.length === 0 && conversation.messages.length > 0) {actions.setThread(updateMessagesWithCompletedStatus(conversation.messages))diff --git a/frontend/src/scenes/max/maxTypes.ts b/frontend/src/scenes/max/maxTypes.tsindex 525b0fc46882..2602e88ea203 100644--- a/frontend/src/scenes/max/maxTypes.ts+++ b/frontend/src/scenes/max/maxTypes.ts@@ -242,3 +242,50 @@ export const createMaxContextHelpers = {export function isAgentMode(mode: unknown): mode is AgentMode {return typeof mode === 'string' && Object.values(AgentMode).includes(mode as AgentMode)}++/**+ * The shape `sandboxToolRegistry` renderers receive — raw `ToolInvocation` stream state plus+ * renderer-facing fields resolved at render time.+ */+export interface SandboxToolCallMessage {+ /** Stable id — the tool call id. */+ id: string+ /** Registry lookup key — the inner tool name for single-exec calls, otherwise the wire tool name. */+ resolvedKey: string+ rawServerName: string+ rawToolName: string+ innerToolName?: string+ /** Stable SDK tool name from `_meta.claudeCode.toolName` — set for Claude built-ins. */+ claudeToolName?: string+ /** rawInput at `tool_call` (for `exec`, includes the wrapper `{ command }`). */+ rawInput: Record<string, unknown>+ /** JSON-parsed inner args when `innerToolName` is set. */+ innerInput?: Record<string, unknown>+ rawOutput?: unknown+ /** Accumulated ACP `content[]`. */+ content: unknown[]+ status: 'pending' | 'in_progress' | 'completed' | 'failed'+ title?: string+ kind?: string+ /** ACP `toolCall.locations` — file paths (with optional line) the tool touched. */+ locations?: { path: string; line?: number }[]+ error?: { message?: string } | null+}++/**+ * Flat context attachment sent to the sandbox agent runtime (`agent_runtime === 'sandbox'`).+ *+ * Unlike the rich `MaxUIContext` payloads used by the LangGraph runtime, the sandbox runtime+ * carries only typed references the agent fetches on demand via its read tools. This is a new+ * export added alongside the existing context types during the coexistence window — existing+ * types are untouched.+ */+export interface AttachedContext {+ type: 'dashboard' | 'insight' | 'event' | 'action' | 'error_tracking_issue' | 'evaluation' | 'notebook' | 'text'+ /** Entity id — int for dashboards/actions, short_id for insights/notebooks, UUID for error tracking issues. */+ id?: string | number+ /** Optional human-readable label for entity types. */+ name?: string+ /** Free-text value — only set when `type === 'text'`. */+ value?: string+}diff --git a/frontend/src/scenes/max/messages/AssistantFailureMessage.test.tsx b/frontend/src/scenes/max/messages/AssistantFailureMessage.test.tsxnew file mode 100644index 000000000000..6d4bfb3cbeb4--- /dev/null+++ b/frontend/src/scenes/max/messages/AssistantFailureMessage.test.tsx@@ -0,0 +1,27 @@+import '@testing-library/jest-dom'++import { cleanup, render, screen } from '@testing-library/react'++import { AssistantFailureMessage } from './AssistantFailureMessage'++describe('AssistantFailureMessage', () => {+ afterEach(cleanup)++ it('renders the supplied failure message', () => {+ render(<AssistantFailureMessage id="failure-1" content="Internal error: Failed to authenticate" />)++ expect(screen.getByText('Internal error: Failed to authenticate')).toBeInTheDocument()+ })++ it('falls back when no failure message is supplied', () => {+ render(<AssistantFailureMessage id="failure-1" content={null} />)++ expect(screen.getByText('*PostHog AI has failed to generate an answer. Please try again.*')).toBeInTheDocument()+ })++ it('renders an optional action', () => {+ render(<AssistantFailureMessage id="failure-1" content="Failed" action={<button>Try again</button>} />)++ expect(screen.getByRole('button', { name: 'Try again' })).toBeInTheDocument()+ })+})diff --git a/frontend/src/scenes/max/messages/AssistantFailureMessage.tsx b/frontend/src/scenes/max/messages/AssistantFailureMessage.tsxnew file mode 100644index 000000000000..46c8a9970ec1--- /dev/null+++ b/frontend/src/scenes/max/messages/AssistantFailureMessage.tsx@@ -0,0 +1,22 @@+import React from 'react'++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 {+ id: string+ content?: string | null+ action?: React.ReactNode+}++export const AssistantFailureMessage = React.forwardRef<HTMLDivElement, AssistantFailureMessageProps>(+ function AssistantFailureMessage({ id, content, action }, ref) {+ return (+ <MessageTemplate type="ai" boxClassName="border-danger" ref={ref} action={action}>+ <MarkdownMessage content={content || DEFAULT_FAILURE_MESSAGE} id={id} />+ </MessageTemplate>+ )+ }+)diff --git a/frontend/src/scenes/max/messages/ReasoningAnswer.tsx b/frontend/src/scenes/max/messages/ReasoningAnswer.tsxnew file mode 100644index 000000000000..325cefe5e3c1--- /dev/null+++ b/frontend/src/scenes/max/messages/ReasoningAnswer.tsx@@ -0,0 +1,35 @@+import { IconBrain } from '@posthog/icons'++import { inStorybookTestRunner } from 'lib/utils/dom'++import { TaskExecutionStatus as ExecutionStatus } from '~/queries/schema/schema-assistant-messages'++import { LangGraphActivity } from '../components/Activity'++export interface ReasoningAnswerProps {+ content: string+ completed: boolean+ id: string+ showCompletionIcon?: boolean+ animate?: boolean+}++export function ReasoningAnswer({+ content,+ completed,+ id,+ showCompletionIcon = true,+ animate = false,+}: ReasoningAnswerProps): JSX.Element {+ return (+ <LangGraphActivity+ id={id}+ content={completed ? 'Thought' : content}+ substeps={completed ? [content] : []}+ state={completed ? ExecutionStatus.Completed : ExecutionStatus.InProgress}+ icon={<IconBrain />}+ animate={!inStorybookTestRunner() && animate} // Avoiding flaky snapshots in Storybook+ showCompletionIcon={showCompletionIcon}+ />+ )+}diff --git a/frontend/src/scenes/max/messages/UIPayloadAnswer.tsx b/frontend/src/scenes/max/messages/UIPayloadAnswer.tsxindex 1d18a77acfa9..ae33580bde2b 100644--- a/frontend/src/scenes/max/messages/UIPayloadAnswer.tsx+++ b/frontend/src/scenes/max/messages/UIPayloadAnswer.tsx@@ -61,20 +61,22 @@ export function UIPayloadAnswer({toolCallId,toolName,toolPayload,+ embedded = false,}: {toolCallId: stringtoolName: stringtoolPayload: any+ embedded?: boolean}): JSX.Element | null {const { conversationId } = useValues(maxLogic)if (toolName === 'search_session_recordings') {const filters = toolPayload as RecordingUniversalFilters- return <RecordingsWidget toolCallId={toolCallId} filters={filters} />+ return <RecordingsWidget toolCallId={toolCallId} filters={filters} embedded={embedded} />}if (toolName === 'search_error_tracking_issues') {const filters = toolPayload as MaxErrorTrackingSearchResponse- return <ErrorTrackingFiltersWidget toolCallId={toolCallId} filters={filters} />+ return <ErrorTrackingFiltersWidget toolCallId={toolCallId} filters={filters} embedded={embedded} />}// Check if this is a dangerous operation requiring approval@@ -94,9 +96,11 @@ export function UIPayloadAnswer({export function RecordingsWidget({toolCallId,filters,+ embedded = false,}: {toolCallId: stringfilters: RecordingUniversalFilters+ embedded?: boolean}): JSX.Element {const { onAcceptSessionFilters } = useValues(maxLogic)const logicProps: SessionRecordingPlaylistLogicProps = {@@ -105,14 +109,23 @@ export function RecordingsWidget({updateSearchParams: false,autoPlay: false,}+ const content = (+ <>+ <RecordingsFiltersSummary filters={filters} />+ <RecordingsListContent />+ {onAcceptSessionFilters && <AcceptFiltersBar filters={filters} onAccept={onAcceptSessionFilters} />}+ </>+ )return (<BindLogic logic={sessionRecordingsPlaylistLogic} props={logicProps}>- <MessageTemplate type="ai" wrapperClassName="w-full" boxClassName="p-0 overflow-hidden">- <RecordingsFiltersSummary filters={filters} />- <RecordingsListContent />- {onAcceptSessionFilters && <AcceptFiltersBar filters={filters} onAccept={onAcceptSessionFilters} />}- </MessageTemplate>+ {embedded ? (+ <div className="overflow-hidden rounded border bg-surface-primary">{content}</div>+ ) : (+ <MessageTemplate type="ai" wrapperClassName="w-full" boxClassName="p-0 overflow-hidden">+ {content}+ </MessageTemplate>+ )}</BindLogic>)}@@ -186,33 +199,47 @@ function RecordingsListContent(): JSX.Element {export function ErrorTrackingFiltersWidget({toolCallId,filters,+ embedded = false,}: {toolCallId: stringfilters: MaxErrorTrackingSearchResponse | null | undefined+ embedded?: boolean}): JSX.Element {const logicProps: MaxErrorTrackingWidgetLogicProps = { toolCallId, filters }if (!filters) {+ const emptyState = (+ <div className="py-2">+ <EmptyMessage+ title="Error tracking data unavailable"+ description="The error tracking search could not be completed"+ />+ </div>+ )+ if (embedded) {+ return <div className="overflow-hidden rounded border bg-surface-primary">{emptyState}</div>+ }return (<MessageTemplate type="ai" wrapperClassName="w-full" boxClassName="p-0 overflow-hidden">- <div className="py-2">- <EmptyMessage- title="Error tracking data unavailable"- description="The error tracking search could not be completed"- />- </div>+ {emptyState}</MessageTemplate>)}return (<BindLogic logic={maxErrorTrackingWidgetLogic} props={logicProps}>- <ErrorTrackingFiltersWidgetContent filters={filters} />+ <ErrorTrackingFiltersWidgetContent filters={filters} embedded={embedded} /></BindLogic>)}-function ErrorTrackingFiltersWidgetContent({ filters }: { filters: MaxErrorTrackingSearchResponse }): JSX.Element {+function ErrorTrackingFiltersWidgetContent({+ filters,+ embedded,+}: {+ filters: MaxErrorTrackingSearchResponse+ embedded: boolean+}): JSX.Element {const { activeSceneId } = useValues(sceneLogic)const isOnErrorTrackingPage = activeSceneId === Scene.ErrorTracking@@ -280,8 +307,8 @@ function ErrorTrackingFiltersWidgetContent({ filters }: { filters: MaxErrorTrackconst hasIssues = issues.length > 0const errorTrackingUrl = buildErrorTrackingUrl()- return (- <MessageTemplate type="ai" wrapperClassName="w-full" boxClassName="p-0 overflow-hidden">+ const content = (+ <>{!isOnErrorTrackingPage && (<div className="flex items-center justify-between px-2 pt-2"><span className="text-xs font-semibold text-secondary">Error tracking</span>@@ -314,6 +341,16 @@ function ErrorTrackingFiltersWidgetContent({ filters }: { filters: MaxErrorTrack</div>)}</div>+ </>+ )++ if (embedded) {+ return <div className="overflow-hidden rounded border bg-surface-primary">{content}</div>+ }++ return (+ <MessageTemplate type="ai" wrapperClassName="w-full" boxClassName="p-0 overflow-hidden">+ {content}</MessageTemplate>)}diff --git a/frontend/src/scenes/max/messages/VisualizationArtifact.tsx b/frontend/src/scenes/max/messages/VisualizationArtifact.tsxnew file mode 100644index 000000000000..7c7c11e649cc--- /dev/null+++ b/frontend/src/scenes/max/messages/VisualizationArtifact.tsx@@ -0,0 +1,88 @@+import { useActions, useValues } from 'kea'+import React, { useLayoutEffect, useState } from 'react'++import { IconCollapse, IconExpand } from '@posthog/icons'+import { LemonButton } from '@posthog/lemon-ui'++import { insightLogic } from 'scenes/insights/insightLogic'+import { insightSceneLogic } from 'scenes/insights/insightSceneLogic'+import { Scene } from 'scenes/sceneTypes'++import { ArtifactMessage, VisualizationArtifactContent } from '~/queries/schema/schema-assistant-messages'++import { MessageStatus } from '../maxLogic'+import { VisualizationWidget, getArtifactOpenTarget } from './VisualizationWidget'++interface VisualizationArtifactProps {+ message: ArtifactMessage & { status?: MessageStatus }+ content: VisualizationArtifactContent+ status?: MessageStatus+ isEditingInsight: boolean+ activeTabId?: string | null+ activeSceneId?: string | null+}++function InsightSuggestionButton(): JSX.Element {+ const { insight } = useValues(insightSceneLogic)+ const insightProps = { dashboardItemId: insight?.short_id }+ const { suggestedQuery, previousQuery } = useValues(insightLogic(insightProps))+ const { onRejectSuggestedInsight, onReapplySuggestedInsight } = useActions(insightLogic(insightProps))++ return (+ <>+ {suggestedQuery && (+ <LemonButton+ onClick={() => {+ if (previousQuery) {+ onRejectSuggestedInsight()+ } else {+ onReapplySuggestedInsight()+ }+ }}+ sideIcon={previousQuery ? <IconCollapse /> : <IconExpand />}+ size="xsmall"+ tooltip={previousQuery ? 'Reject changes' : 'Reapply changes'}+ />+ )}+ </>+ )+}++/**+ * LangGraph-runtime proxy for visualization artifacts. Owns the scene coupling — collapse while+ * the insight editor consumes the result, the suggestion accept/reject button, and CTA hiding —+ * and delegates rendering to the atomic `VisualizationWidget`.+ */+export const VisualizationArtifact = React.memo(function VisualizationArtifact({+ message,+ content,+ status,+ isEditingInsight,+ activeTabId,+ activeSceneId,+}: VisualizationArtifactProps): JSX.Element | null {+ // Controlled collapse synced to edit mode — a key-remount would refetch the query instead.+ const [isCollapsed, setIsCollapsed] = useState(isEditingInsight)++ useLayoutEffect(() => {+ setIsCollapsed(isEditingInsight)+ }, [isEditingInsight])++ if (status !== 'completed') {+ return null+ }++ const target = getArtifactOpenTarget(message, content)+ const showSuggestionButton = isEditingInsight && !!activeTabId && activeSceneId === Scene.Insight++ return (+ <VisualizationWidget+ content={content}+ openUrl={isEditingInsight ? null : target.url}+ openTooltip={target.tooltip}+ isCollapsed={isCollapsed}+ onCollapsedChange={setIsCollapsed}+ extraActions={showSuggestionButton ? <InsightSuggestionButton /> : null}+ />+ )+})diff --git a/frontend/src/scenes/max/messages/VisualizationArtifactAnswer.tsx b/frontend/src/scenes/max/messages/VisualizationWidget.tsxsimilarity index 60%rename from frontend/src/scenes/max/messages/VisualizationArtifactAnswer.tsxrename to frontend/src/scenes/max/messages/VisualizationWidget.tsxindex 515b51189299..490403654738 100644--- a/frontend/src/scenes/max/messages/VisualizationArtifactAnswer.tsx+++ b/frontend/src/scenes/max/messages/VisualizationWidget.tsx@@ -1,6 +1,5 @@import clsx from 'clsx'-import { useActions, useValues } from 'kea'-import React, { useLayoutEffect, useMemo, useState } from 'react'+import React, { useMemo, useState } from 'react'import { IconCollapse, IconExpand, IconEye, IconHide, IconWarning } from '@posthog/icons'import { LemonButton } from '@posthog/lemon-ui'@@ -12,9 +11,6 @@ import {} from 'lib/components/Cards/InsightCard/InsightDetails'import { TopHeading } from 'lib/components/Cards/InsightCard/TopHeading'import { IconOpenInNew } from 'lib/lemon-ui/icons'-import { insightLogic } from 'scenes/insights/insightLogic'-import { insightSceneLogic } from 'scenes/insights/insightSceneLogic'-import { Scene } from 'scenes/sceneTypes'import { urls } from 'scenes/urls'import { Query } from '~/queries/Query/Query'@@ -28,63 +24,61 @@ import { QueryContext } from '~/queries/types'import { isFunnelsQuery, isHogQLQuery, isInsightVizNode } from '~/queries/utils'import { InsightShortId } from '~/types'-import { MessageStatus } from '../maxLogic'import { visualizationTypeToQuery } from '../utils'import { MessageTemplate } from './MessageTemplate'-interface VisualizationArtifactAnswerProps {- message: ArtifactMessage & { status?: MessageStatus }+const QUERY_CONTEXT_POSTHOG_AI: QueryContext = { limitContext: 'posthog_ai' } as const++export interface VisualizationWidgetProps {content: VisualizationArtifactContent- status?: MessageStatus- isEditingInsight: boolean- activeTabId?: string | null- activeSceneId?: string | null+ /** Href for the "Open as insight" CTA; null/undefined hides the button. */+ openUrl?: string | null+ /** Tooltip for the CTA. */+ openTooltip?: string+ /** Controlled collapse state; omit for uncontrolled (starts expanded). */+ isCollapsed?: boolean+ onCollapsedChange?: (isCollapsed: boolean) => void+ /** Extra buttons rendered in the actions row before the CTA. */+ extraActions?: React.ReactNode+ /** Render only the widget body, for use inside an existing activity/message shell. */+ embedded?: boolean}-function InsightSuggestionButton(): JSX.Element {- const { insight } = useValues(insightSceneLogic)- const insightProps = { dashboardItemId: insight?.short_id }- const { suggestedQuery, previousQuery } = useValues(insightLogic(insightProps))- const { onRejectSuggestedInsight, onReapplySuggestedInsight } = useActions(insightLogic(insightProps))-- return (- <>- {suggestedQuery && (- <LemonButton- onClick={() => {- if (previousQuery) {- onRejectSuggestedInsight()- } else {- onReapplySuggestedInsight()- }- }}- sideIcon={previousQuery ? <IconCollapse /> : <IconExpand />}- size="xsmall"- tooltip={previousQuery ? 'Reject changes' : 'Reapply changes'}- />- )}- </>- )+/** Resolves the "Open as insight" CTA target for a visualization artifact. */+export function getArtifactOpenTarget(+ envelope: ArtifactMessage,+ content: VisualizationArtifactContent+): { url: string | null; tooltip: string } {+ if (envelope.source === ArtifactSource.Insight) {+ return { url: urls.insightView(envelope.artifact_id as InsightShortId), tooltip: 'Open insight' }+ }+ const query = visualizationTypeToQuery(content)+ return {+ url: query ? urls.insightNew({ query: query as InsightVizNode | DataVisualizationNode }) : null,+ tooltip: 'Open as new insight',+ }}-const QUERY_CONTEXT_POSTHOG_AI: QueryContext = { limitContext: 'posthog_ai' } as const--export const VisualizationArtifactAnswer = React.memo(function VisualizationArtifactAnswer({- message,+/**+ * Atomic, runtime-agnostic visualization renderer. Runtime-specific behavior (scene coupling,+ * status gating, suggestion flows) belongs in the proxy renderers that compose this widget.+ */+export const VisualizationWidget = React.memo(function VisualizationWidget({content,- status,- isEditingInsight,- activeTabId,- activeSceneId,-}: VisualizationArtifactAnswerProps): JSX.Element | null {- const isSavedInsight = message.source === ArtifactSource.Insight-+ openUrl,+ openTooltip = 'Open as new insight',+ isCollapsed: controlledCollapsed,+ onCollapsedChange,+ extraActions,+ embedded = false,+}: VisualizationWidgetProps): JSX.Element {const [isSummaryShown, setIsSummaryShown] = useState(false)- const [isCollapsed, setIsCollapsed] = useState(isEditingInsight)-- useLayoutEffect(() => {- setIsCollapsed(isEditingInsight)- }, [isEditingInsight])+ const [internalCollapsed, setInternalCollapsed] = useState(false)+ const isCollapsed = controlledCollapsed ?? internalCollapsed+ const setCollapsed = (next: boolean): void => {+ setInternalCollapsed(next)+ onCollapsedChange?.(next)+ }// Build query from either artifact content or inline visualization messageconst query = useMemo(() => {@@ -94,28 +88,13 @@ export const VisualizationArtifactAnswer = React.memo(function VisualizationArti// Get the raw query for height calculationconst rawQuery = content.query- if (status !== 'completed') {- return null- }-- if (!query) {- return (- <MessageTemplate- type="ai"- className="w-full"- wrapperClassName="w-full"- boxClassName="flex flex-col w-full border-danger"- >- <div className="flex items-center gap-1.5">- <IconWarning className="text-xl text-danger" />- <span>Failed to load visualization</span>- </div>- </MessageTemplate>- )- }-- return (- <MessageTemplate type="ai" className="w-full" wrapperClassName="w-full" boxClassName="flex flex-col w-full">+ const renderedContent = !query ? (+ <div className="flex items-center gap-1.5">+ <IconWarning className="text-xl text-danger" />+ <span>Failed to load visualization</span>+ </div>+ ) : (+ <div className="flex flex-col w-full">{!isCollapsed && (<div className={clsx('flex flex-col overflow-auto', isFunnelsQuery(rawQuery) ? 'h-[580px]' : 'h-96')}><Query query={query} readOnly embedded context={QUERY_CONTEXT_POSTHOG_AI} />@@ -142,25 +121,19 @@ export const VisualizationArtifactAnswer = React.memo(function VisualizationArti</h5>)}<div className="flex items-center gap-1.5">- {isEditingInsight && activeTabId && activeSceneId === Scene.Insight && <InsightSuggestionButton />}- {!isEditingInsight && (+ {extraActions}+ {openUrl && (<LemonButton- to={- isSavedInsight- ? urls.insightView(message.artifact_id as InsightShortId)- : urls.insightNew({- query: query as InsightVizNode | DataVisualizationNode,- })- }+ to={openUrl}targetBlankicon={<IconOpenInNew />}size="xsmall"- tooltip={isSavedInsight ? 'Open insight' : 'Open as new insight'}+ tooltip={openTooltip}/>)}<LemonButtonicon={isCollapsed ? <IconEye /> : <IconHide />}- onClick={() => setIsCollapsed(!isCollapsed)}+ onClick={() => setCollapsed(!isCollapsed)}size="xsmall"className="-m-1 shrink"tooltip={isCollapsed ? 'Show visualization' : 'Hide visualization'}@@ -178,6 +151,29 @@ export const VisualizationArtifactAnswer = React.memo(function VisualizationArti)}</>)}+ </div>+ )++ if (embedded) {+ return renderedContent+ }++ if (!query) {+ return (+ <MessageTemplate+ type="ai"+ className="w-full"+ wrapperClassName="w-full"+ boxClassName="flex flex-col w-full border-danger"+ >+ {renderedContent}+ </MessageTemplate>+ )+ }++ return (+ <MessageTemplate type="ai" className="w-full" wrapperClassName="w-full" boxClassName="flex flex-col w-full">+ {renderedContent}</MessageTemplate>)})diff --git a/frontend/src/scenes/max/messages/adapters/CreateInsightWidget.tsx b/frontend/src/scenes/max/messages/adapters/CreateInsightWidget.tsxnew file mode 100644index 000000000000..704209b75b01--- /dev/null+++ b/frontend/src/scenes/max/messages/adapters/CreateInsightWidget.tsx@@ -0,0 +1,32 @@+import { GenericMcpToolRenderer } from '../../sandbox/components/tool/GenericMcpToolRenderer'+import { SandboxDataToolRow } from '../../sandbox/components/tool/SandboxDataToolRow'+import type { SandboxToolRendererProps } from '../../sandbox/sandboxToolRegistry'+import { VisualizationWidget, getArtifactOpenTarget } from '../VisualizationWidget'+import { extractVisualizationArtifact } from './extractors'++/**+ * Renders insight create / update / read tool calls through `VisualizationWidget`. Until the+ * artifact lands (pending / in-progress / malformed output) we fall back to the generic card so+ * the call still renders something.+ */+export function CreateInsightWidget(props: SandboxToolRendererProps): JSX.Element {+ const { message } = props+ const artifact = message.status === 'completed' ? extractVisualizationArtifact(message) : null++ if (!artifact) {+ return <GenericMcpToolRenderer {...props} />+ }++ const target = getArtifactOpenTarget(artifact.envelope, artifact.content)++ return (+ <SandboxDataToolRow {...props}>+ <VisualizationWidget+ content={artifact.content}+ openUrl={target.url}+ openTooltip={target.tooltip}+ embedded+ />+ </SandboxDataToolRow>+ )+}diff --git a/frontend/src/scenes/max/messages/adapters/CreateNotebookWidget.test.tsx b/frontend/src/scenes/max/messages/adapters/CreateNotebookWidget.test.tsxnew file mode 100644index 000000000000..b087c8130fc3--- /dev/null+++ b/frontend/src/scenes/max/messages/adapters/CreateNotebookWidget.test.tsx@@ -0,0 +1,62 @@+import type { SandboxToolCallMessage } from '../../maxTypes'+import { lookupSandboxToolRenderer, sandboxToolRegistry } from '../../sandbox/sandboxToolRegistry'+import { extractNotebook } from './CreateNotebookWidget'++function toolMessage(rawOutput: unknown, innerInput?: Record<string, unknown>): SandboxToolCallMessage {+ return {+ id: 'call-1',+ resolvedKey: 'notebooks-create',+ rawServerName: 'posthog',+ rawToolName: 'mcp__posthog__exec',+ rawInput: {},+ innerInput,+ rawOutput,+ content: [],+ status: 'completed',+ }+}++describe('CreateNotebookWidget', () => {+ it.each(['notebooks-create', 'notebooks-partial-update', 'notebooks-retrieve', 'notebook-edit'])(+ 'resolves %s to the notebook widget',+ (key) => {+ expect(sandboxToolRegistry.lookup(key)?.displayName).toBe('Notebook')+ expect(lookupSandboxToolRenderer(key).displayName).toBe('Notebook')+ }+ )++ it('falls back to the generic renderer for an unknown inner tool key', () => {+ expect(lookupSandboxToolRenderer('some-unwired-tool').displayName).not.toBe('Notebook')+ })++ describe('extractNotebook', () => {+ it('reads short_id, title, and the _posthogUrl enrichment from the REST payload', () => {+ const notebook = extractNotebook(+ toolMessage({+ id: 'b3d0f2aa-1111-2222-3333-444455556666',+ short_id: 'aBcDe123',+ title: 'Churn deep dive',+ content: { type: 'doc', content: [] },+ version: 1,+ _posthogUrl: 'https://us.posthog.com/project/1/notebooks/aBcDe123',+ })+ )+ expect(notebook).toEqual({+ shortId: 'aBcDe123',+ title: 'Churn deep dive',+ url: 'https://us.posthog.com/project/1/notebooks/aBcDe123',+ })+ })++ it('falls back to the input title when the payload title is missing', () => {+ const notebook = extractNotebook(toolMessage({ short_id: 'aBcDe123' }, { title: 'From input' }))+ expect(notebook).toEqual({ shortId: 'aBcDe123', title: 'From input', url: undefined })+ })++ it('returns null for outputs without a short_id or that are not objects', () => {+ expect(extractNotebook(toolMessage({ blocks: [], title: 'Legacy artifact shape' }))).toBeNull()+ expect(extractNotebook(toolMessage('created notebook aBcDe123'))).toBeNull()+ expect(extractNotebook(toolMessage(undefined))).toBeNull()+ })+ })+})diff --git a/frontend/src/scenes/max/messages/adapters/CreateNotebookWidget.tsx b/frontend/src/scenes/max/messages/adapters/CreateNotebookWidget.tsxnew file mode 100644index 000000000000..c1b3b6a5a7af--- /dev/null+++ b/frontend/src/scenes/max/messages/adapters/CreateNotebookWidget.tsx@@ -0,0 +1,76 @@+import { IconNotebook } from '@posthog/icons'+import { LemonButton } from '@posthog/lemon-ui'++import { IconOpenInNew } from 'lib/lemon-ui/icons'+import { urls } from 'scenes/urls'++import { GenericMcpToolRenderer } from '../../sandbox/components/tool/GenericMcpToolRenderer'+import { SandboxDataToolRow } from '../../sandbox/components/tool/SandboxDataToolRow'+import type { SandboxToolRendererProps } from '../../sandbox/sandboxToolRegistry'++/** The notebook fields the widget renders, pulled from the REST payload. */+export interface NotebookExtraction {+ shortId: string+ title?: string+ url?: string+}++/**+ * Pulls the rendered fields out of a notebook tool's `rawOutput` — the REST notebook payload+ * (`short_id`, `title`, ProseMirror `content`, …) plus the MCP server's `_posthogUrl` enrichment.+ * `short_id` is required: outputs without it aren't a notebook payload and fall back to the+ * generic card.+ */+export function extractNotebook(message: SandboxToolRendererProps['message']): NotebookExtraction | null {+ const output = message.rawOutput+ if (!output || typeof output !== 'object' || Array.isArray(output)) {+ return null+ }++ const { short_id, title, _posthogUrl } = output as { short_id?: unknown; title?: unknown; _posthogUrl?: unknown }+ if (typeof short_id !== 'string') {+ return null+ }++ const inputTitle = message.innerInput?.title+ return {+ shortId: short_id,+ title: typeof title === 'string' ? title : typeof inputTitle === 'string' ? inputTitle : undefined,+ url: typeof _posthogUrl === 'string' ? _posthogUrl : undefined,+ }+}++/**+ * Notebook create / update / get tool calls. The tool already persisted the notebook server-side,+ * so v1 is a status line + "Open notebook" CTA — no inline preview, since the REST `content` is a+ * ProseMirror document, not the assistant block format `NotebookArtifactAnswer` renders.+ * Pre-completion or malformed output falls back to the generic card.+ */+export function CreateNotebookWidget(props: SandboxToolRendererProps): JSX.Element {+ const { message } = props+ const notebook = message.status === 'completed' ? extractNotebook(message) : null++ if (!notebook) {+ return <GenericMcpToolRenderer {...props} />+ }++ return (+ <SandboxDataToolRow {...props}>+ <div className="flex items-center justify-between gap-2">+ <div className="flex items-center gap-1.5">+ <IconNotebook className="text-base" />+ <span className="font-medium">{notebook.title || 'Notebook ready'}</span>+ </div>+ <LemonButton+ to={notebook.url ?? urls.notebook(notebook.shortId)}+ targetBlank+ icon={<IconOpenInNew />}+ size="xsmall"+ tooltip="Open notebook"+ >+ Open notebook+ </LemonButton>+ </div>+ </SandboxDataToolRow>+ )+}diff --git a/frontend/src/scenes/max/messages/adapters/EditDiffRenderer.test.tsx b/frontend/src/scenes/max/messages/adapters/EditDiffRenderer.test.tsxnew file mode 100644index 000000000000..270c29650dcb--- /dev/null+++ b/frontend/src/scenes/max/messages/adapters/EditDiffRenderer.test.tsx@@ -0,0 +1,163 @@+import '@testing-library/jest-dom'++import { cleanup, fireEvent, render, screen } from '@testing-library/react'++import type { SandboxToolCallMessage } from '../../maxTypes'+import { EditDiffRenderer } from './EditDiffRenderer'++// Monaco can't render in jsdom — stand it in for a marker that echoes the diff props we care about.+jest.mock('lib/components/MonacoDiffEditor', () => ({+ __esModule: true,+ default: ({+ original,+ modified,+ language,+ theme,+ }: {+ original?: string+ modified?: string+ language?: string+ theme?: string+ }) => (+ <div+ data-attr="monaco-diff"+ data-original={original}+ data-modified={modified}+ data-language={language}+ data-theme={theme}+ />+ ),+}))++// Force the lazy-mount gate open so the editor instantiates.+jest.mock('react-intersection-observer', () => ({+ useInView: () => ({ ref: () => {}, inView: true }),+}))++// Drive the app theme without mounting themeLogic (and its scene/user deps). The arrow reads+// `mockDarkMode` lazily at render time, so flipping it per test works.+let mockDarkMode = false+jest.mock('kea', () => ({+ ...jest.requireActual('kea'),+ useValues: () => ({ isDarkModeOn: mockDarkMode }),+}))++function makeMessage(overrides: Partial<SandboxToolCallMessage> = {}): SandboxToolCallMessage {+ return {+ id: 'tc-1',+ resolvedKey: 'Edit',+ rawServerName: 'posthog',+ rawToolName: 'Edit',+ rawInput: {},+ content: [],+ status: 'completed',+ ...overrides,+ }+}++// The diff lives in the Activity's collapsible body, which auto-collapses once the call completes —+// expand it so the editor + stats render.+function renderExpanded(message: SandboxToolCallMessage): void {+ render(<EditDiffRenderer message={message} displayName="Edit" isLastInGroup />)+ fireEvent.click(screen.getByRole('button'))+}++describe('EditDiffRenderer', () => {+ afterEach(() => {+ cleanup()+ mockDarkMode = false+ })++ it('renders an inline diff with +/- stats for an Edit with a diff block', () => {+ renderExpanded(+ makeMessage({+ title: 'Edit `foo.ts`',+ content: [{ type: 'diff', path: 'foo.ts', oldText: 'a\nb', newText: 'a\nb\nc' }],+ })+ )++ const editor = screen.getByTestId('monaco-diff')+ expect(editor).toBeInTheDocument()+ expect(editor).toHaveAttribute('data-original', 'a\nb')+ expect(editor).toHaveAttribute('data-modified', 'a\nb\nc')+ expect(editor).toHaveAttribute('data-language', 'typescript')+ expect(editor).toHaveAttribute('data-theme', 'vs')+ expect(screen.getByText('foo.ts')).toBeInTheDocument()+ expect(screen.getByText('+1')).toBeInTheDocument()+ expect(screen.getByText('-0')).toBeInTheDocument()+ })++ it('reads "Edited a file" in the header', () => {+ render(+ <EditDiffRenderer+ message={makeMessage({ content: [{ type: 'diff', path: 'foo.ts', oldText: 'a', newText: 'b' }] })}+ displayName="Edit"+ isLastInGroup+ />+ )+ expect(screen.getByText('Edited a file')).toBeInTheDocument()+ })++ it('renders one editor per diff block for a MultiEdit', () => {+ renderExpanded(+ makeMessage({+ resolvedKey: 'MultiEdit',+ content: [+ { type: 'diff', path: 'foo.ts', oldText: 'a', newText: 'b' },+ { type: 'content', content: { type: 'diff', path: 'foo.ts', oldText: 'b', newText: 'c' } },+ ],+ })+ )++ expect(screen.getAllByTestId('monaco-diff')).toHaveLength(2)+ })++ it('reads "Created a file" with all-added stats and an empty original for a new file (Write)', () => {+ const message = makeMessage({+ resolvedKey: 'Write',+ content: [{ type: 'diff', path: 'new.py', oldText: null, newText: 'print(1)\nprint(2)' }],+ })+ render(<EditDiffRenderer message={message} displayName="Edit" isLastInGroup />)+ expect(screen.getByText('Created a file')).toBeInTheDocument()++ fireEvent.click(screen.getByRole('button'))+ const editor = screen.getByTestId('monaco-diff')+ expect(editor).toHaveAttribute('data-original', '')+ expect(editor).toHaveAttribute('data-language', 'python')+ expect(screen.getByText('+2')).toBeInTheDocument()+ })++ it('resolves filename and language from rawInput.file_path when the diff block has no path', () => {+ renderExpanded(+ makeMessage({+ content: [{ type: 'diff', oldText: 'a', newText: 'b' }],+ rawInput: { file_path: 'main.go' },+ })+ )++ expect(screen.getByText('main.go')).toBeInTheDocument()+ expect(screen.getByTestId('monaco-diff')).toHaveAttribute('data-language', 'go')+ })++ it('falls back to the generic tool card (no editor) when there is no diff block', () => {+ // A built-in Edit carries its name in `claudeToolName` with an empty wire `toolName`.+ const message = makeMessage({+ title: 'Edit `foo.ts`',+ claudeToolName: 'Edit',+ rawToolName: '',+ content: [{ type: 'text', text: 'no diff yet' }],+ })+ render(<EditDiffRenderer message={message} displayName="Edit" isLastInGroup />)++ expect(screen.queryByTestId('monaco-diff')).not.toBeInTheDocument()+ // The generic card still renders the rich tool title as its header.+ expect(screen.getByText('Edit `foo.ts`')).toBeInTheDocument()+ })++ it('uses the dark Monaco theme when the app is in dark mode', () => {+ mockDarkMode = true+ renderExpanded(makeMessage({ content: [{ type: 'diff', path: 'foo.ts', oldText: 'a', newText: 'b' }] }))++ expect(screen.getByTestId('monaco-diff')).toHaveAttribute('data-theme', 'vs-dark')+ })+})diff --git a/frontend/src/scenes/max/messages/adapters/EditDiffRenderer.tsx b/frontend/src/scenes/max/messages/adapters/EditDiffRenderer.tsxnew file mode 100644index 000000000000..91442d0dd7db--- /dev/null+++ b/frontend/src/scenes/max/messages/adapters/EditDiffRenderer.tsx@@ -0,0 +1,124 @@+import { useValues } from 'kea'+import type { editor } from 'monaco-editor'+import { useInView } from 'react-intersection-observer'++import { IconPencil } from '@posthog/icons'++import MonacoDiffEditor from 'lib/components/MonacoDiffEditor'++import { themeLogic } from '~/layout/navigation-3000/themeLogic'++import { GenericMcpToolRenderer } from '../../sandbox/components/tool/GenericMcpToolRenderer'+import { SandboxFilePath } from '../../sandbox/components/tool/SandboxFilePath'+import { SandboxToolActivity } from '../../sandbox/components/tool/SandboxToolActivity'+import type { SandboxToolRendererProps } from '../../sandbox/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+// so the object identity is stable across renders: MonacoDiffEditor calls `updateOptions` whenever this+// prop changes, and a fresh literal each render would thrash it during streaming.+const DIFF_EDITOR_OPTIONS: editor.IDiffEditorConstructionOptions = {+ readOnly: true,+ renderSideBySide: false,+ hideUnchangedRegions: { enabled: true },+ diffAlgorithm: 'advanced',+ wordWrap: 'on',+ diffWordWrap: 'inherit',+ fontSize: 12,+ lineNumbers: 'on',+ minimap: { enabled: false },+ renderOverviewRuler: false,+ overviewRulerLanes: 0,+ overviewRulerBorder: false,+ hideCursorInOverviewRuler: true,+ scrollBeyondLastLine: false,+ folding: false,+ glyphMargin: false,+ renderLineHighlight: 'none',+ renderGutterMenu: false,+ guides: { indentation: false },+ padding: { top: 4, bottom: 4 },+ // Don't trap the thread's scroll when the cursor is over the diff.+ scrollbar: { alwaysConsumeMouseWheel: false, vertical: 'auto', horizontal: 'auto' },+}++function DiffEditor({ diff, path }: { diff: ToolCallDiffContent; path?: string }): JSX.Element {+ // Lazy-mount: only instantiate the Monaco diff editor once the card scrolls near the viewport.+ const { ref, inView } = useInView({ rootMargin: '500px', triggerOnce: true })+ // Match the surrounding app theme — without this Monaco falls back to its default `vs` (white) theme.+ const { isDarkModeOn } = useValues(themeLogic)++ return (+ <div ref={ref} className="w-full min-w-0">+ {inView ? (+ <MonacoDiffEditor+ original={diff.oldText ?? ''}+ value={diff.newText ?? ''}+ modified={diff.newText ?? ''}+ language={languageFromPath(path)}+ theme={isDarkModeOn ? 'vs-dark' : 'vs'}+ options={DIFF_EDITOR_OPTIONS}+ />+ ) : (+ <div className="h-24 rounded border border-border-secondary" />+ )}+ </div>+ )+}++/** +added / -removed mono stat chip for a diff. */+function DiffStats({ added, removed }: { added: number; removed: number }): JSX.Element {+ return (+ <span className="font-mono text-xs shrink-0">+ <span className="text-success">+{added}</span> <span className="text-danger">-{removed}</span>+ </span>+ )+}++/**+ * Renderer for Edit / Write / MultiEdit / NotebookEdit. The header reads "Edited a file" / "Created a+ * file" (or "Edited N files"); expanding the card reveals the filename, line stats, and an inline visual+ * diff per file. Without `type: "diff"` content blocks it degrades to the generic card.+ */+export function EditDiffRenderer(props: SandboxToolRendererProps): JSX.Element {+ const { message, icon, turnComplete, turnCancelled } = props+ const diffs = findAllDiffContent(message.content)++ if (diffs.length === 0) {+ return <GenericMcpToolRenderer {...props} />+ }++ const fallbackPath = typeof message.rawInput.file_path === 'string' ? message.rawInput.file_path : undefined+ const isCreate = diffs.length === 1 && diffs[0].oldText == null+ const title = diffs.length > 1 ? `Edited ${diffs.length} files` : isCreate ? 'Created a file' : 'Edited a file'++ const body = (+ <div className="flex flex-col gap-3 w-full min-w-0">+ {diffs.map((diff, index) => {+ const path = diff.path ?? fallbackPath+ const stats = getDiffStats(diff.oldText, diff.newText)+ return (+ <div key={index} className="flex flex-col gap-1 w-full min-w-0">+ <div className="flex items-center gap-2 min-w-0">+ {path && <SandboxFilePath path={path} />}+ <DiffStats added={stats.added} removed={stats.removed} />+ </div>+ <DiffEditor diff={diff} path={path} />+ </div>+ )+ })}+ </div>+ )++ return (+ <SandboxToolActivity+ message={message}+ icon={icon ?? <IconPencil />}+ title={title}+ body={body}+ turnComplete={turnComplete}+ turnCancelled={turnCancelled}+ />+ )+}diff --git a/frontend/src/scenes/max/messages/adapters/ErrorTrackingWidget.tsx b/frontend/src/scenes/max/messages/adapters/ErrorTrackingWidget.tsxnew file mode 100644index 000000000000..ada433bb8fb4--- /dev/null+++ b/frontend/src/scenes/max/messages/adapters/ErrorTrackingWidget.tsx@@ -0,0 +1,26 @@+import { GenericMcpToolRenderer } from '../../sandbox/components/tool/GenericMcpToolRenderer'+import { SandboxDataToolRow } from '../../sandbox/components/tool/SandboxDataToolRow'+import type { SandboxToolRendererProps } from '../../sandbox/sandboxToolRegistry'+import { ErrorTrackingFiltersWidget } from '../UIPayloadAnswer'+import { extractErrorTrackingResponse } from './extractors'++/**+ * Error-tracking search / filter tool calls. `rawOutput` is a `MaxErrorTrackingSearchResponse`+ * directly; `ErrorTrackingFiltersWidget` renders the filter chips + paginated issue list (and+ * pushes filters into the error-tracking scene when it is active). Pre-completion or missing output+ * falls back to the generic card.+ */+export function ErrorTrackingWidget(props: SandboxToolRendererProps): JSX.Element {+ const { message } = props+ const filters = message.status === 'completed' ? extractErrorTrackingResponse(message) : null++ if (!filters) {+ return <GenericMcpToolRenderer {...props} />+ }++ return (+ <SandboxDataToolRow {...props}>+ <ErrorTrackingFiltersWidget toolCallId={message.id} filters={filters} embedded />+ </SandboxDataToolRow>+ )+}diff --git a/frontend/src/scenes/max/messages/adapters/QueryWidget.tsx b/frontend/src/scenes/max/messages/adapters/QueryWidget.tsxnew file mode 100644index 000000000000..a286af0aaa9b--- /dev/null+++ b/frontend/src/scenes/max/messages/adapters/QueryWidget.tsx@@ -0,0 +1,25 @@+import { GenericMcpToolRenderer } from '../../sandbox/components/tool/GenericMcpToolRenderer'+import { SandboxDataToolRow } from '../../sandbox/components/tool/SandboxDataToolRow'+import type { SandboxToolRendererProps } from '../../sandbox/sandboxToolRegistry'+import { VisualizationWidget } from '../VisualizationWidget'+import { extractQueryResult } from './extractors'++/**+ * Renders the MCP query-wrapper tools (query-trends, query-funnel, ...) through+ * `VisualizationWidget` as inline ephemeral visualizations. Pending calls and outputs without an+ * inline renderer fall back to the generic card.+ */+export function QueryWidget(props: SandboxToolRendererProps): JSX.Element {+ const { message } = props+ const result = message.status === 'completed' ? extractQueryResult(message) : null++ if (!result) {+ return <GenericMcpToolRenderer {...props} />+ }++ return (+ <SandboxDataToolRow {...props}>+ <VisualizationWidget content={result.content} openUrl={result.url} openTooltip="Open as insight" embedded />+ </SandboxDataToolRow>+ )+}diff --git a/frontend/src/scenes/max/messages/adapters/SearchSessionRecordingsWidget.tsx b/frontend/src/scenes/max/messages/adapters/SearchSessionRecordingsWidget.tsxnew file mode 100644index 000000000000..9a00e9686d13--- /dev/null+++ b/frontend/src/scenes/max/messages/adapters/SearchSessionRecordingsWidget.tsx@@ -0,0 +1,25 @@+import { GenericMcpToolRenderer } from '../../sandbox/components/tool/GenericMcpToolRenderer'+import { SandboxDataToolRow } from '../../sandbox/components/tool/SandboxDataToolRow'+import type { SandboxToolRendererProps } from '../../sandbox/sandboxToolRegistry'+import { RecordingsWidget } from '../UIPayloadAnswer'+import { extractRecordingFilters } from './extractors'++/**+ * Session-recording search / filter tool calls. The resolved `RecordingUniversalFilters` come back+ * in `rawOutput.filters`; `RecordingsWidget` renders the live playlist inline. Pre-completion or a+ * missing filter object falls back to the generic card.+ */+export function SearchSessionRecordingsWidget(props: SandboxToolRendererProps): JSX.Element {+ const { message } = props+ const filters = message.status === 'completed' ? extractRecordingFilters(message) : null++ if (!filters) {+ return <GenericMcpToolRenderer {...props} />+ }++ return (+ <SandboxDataToolRow {...props}>+ <RecordingsWidget toolCallId={message.id} filters={filters} embedded />+ </SandboxDataToolRow>+ )+}diff --git a/frontend/src/scenes/max/messages/adapters/UpsertDashboardWidget.tsx b/frontend/src/scenes/max/messages/adapters/UpsertDashboardWidget.tsxnew file mode 100644index 000000000000..18eb99b447ca--- /dev/null+++ b/frontend/src/scenes/max/messages/adapters/UpsertDashboardWidget.tsx@@ -0,0 +1,42 @@+import { IconDashboard } from '@posthog/icons'+import { LemonButton } from '@posthog/lemon-ui'++import { IconOpenInNew } from 'lib/lemon-ui/icons'+import { urls } from 'scenes/urls'++import { GenericMcpToolRenderer } from '../../sandbox/components/tool/GenericMcpToolRenderer'+import { SandboxDataToolRow } from '../../sandbox/components/tool/SandboxDataToolRow'+import type { SandboxToolRendererProps } from '../../sandbox/sandboxToolRegistry'+import { extractDashboard } from './extractors'++/**+ * Dashboard create / update tool calls. v1 is a status line + "View dashboard" CTA (a full+ * dashboard embed is deliberately deferred). Pre-completion or malformed output falls back to+ * the generic card.+ */+export function UpsertDashboardWidget(props: SandboxToolRendererProps): JSX.Element {+ const { message } = props+ const dashboard = message.status === 'completed' ? extractDashboard(message) : null++ if (!dashboard) {+ return <GenericMcpToolRenderer {...props} />+ }++ const to = dashboard.url ?? (dashboard.id !== undefined ? urls.dashboard(dashboard.id) : undefined)++ return (+ <SandboxDataToolRow {...props}>+ <div className="flex items-center justify-between gap-2">+ <div className="flex items-center gap-1.5">+ <IconDashboard className="text-base" />+ <span className="font-medium">{dashboard.name || 'Dashboard ready'}</span>+ </div>+ {to && (+ <LemonButton to={to} targetBlank icon={<IconOpenInNew />} size="xsmall" tooltip="Open dashboard">+ View dashboard+ </LemonButton>+ )}+ </div>+ </SandboxDataToolRow>+ )+}diff --git a/frontend/src/scenes/max/messages/adapters/extractors.test.ts b/frontend/src/scenes/max/messages/adapters/extractors.test.tsnew file mode 100644index 000000000000..07223a933557--- /dev/null+++ b/frontend/src/scenes/max/messages/adapters/extractors.test.ts@@ -0,0 +1,188 @@+import { ArtifactSource } from '~/queries/schema/schema-assistant-messages'++import type { SandboxToolCallMessage } from '../../maxTypes'+import {+ extractDashboard,+ extractErrorTrackingResponse,+ extractQueryResult,+ extractRecordingFilters,+ extractVisualizationArtifact,+} from './extractors'++function toolMessage(+ rawOutput: unknown,+ innerInput?: Record<string, unknown>,+ resolvedKey = 'test-tool'+): SandboxToolCallMessage {+ return {+ id: 'call-1',+ resolvedKey,+ rawServerName: 'posthog',+ rawToolName: 'mcp__posthog__exec',+ rawInput: {},+ innerInput,+ rawOutput,+ content: [],+ status: 'completed',+ }+}++describe('mcp tool adapter extractors', () => {+ describe('extractVisualizationArtifact', () => {+ it('classifies a REST insight payload with short_id as a saved insight', () => {+ const artifact = extractVisualizationArtifact(+ toolMessage({ short_id: 'abc12345', name: 'Signups', query: { kind: 'TrendsQuery' } })+ )+ expect(artifact?.envelope.source).toBe(ArtifactSource.Insight)+ expect(artifact?.envelope.artifact_id).toBe('abc12345')+ expect(artifact?.content.name).toBe('Signups')+ })++ it('classifies a query-only output as ephemeral', () => {+ const artifact = extractVisualizationArtifact(toolMessage({ query: { kind: 'TrendsQuery' }, results: [] }))+ expect(artifact?.envelope.source).toBe(ArtifactSource.State)+ expect(artifact?.envelope.artifact_id).toBe('call-1')+ })++ it('returns null when the output has no query', () => {+ expect(extractVisualizationArtifact(toolMessage({ id: 1, name: 'No query here' }))).toBeNull()+ expect(extractVisualizationArtifact(toolMessage(undefined))).toBeNull()+ })+ })++ describe('extractDashboard', () => {+ it('reads id and the _posthogUrl enrichment from the REST payload', () => {+ const dashboard = extractDashboard(+ toolMessage({ id: 42, name: 'KPIs', _posthogUrl: 'https://us.posthog.com/project/1/dashboard/42' })+ )+ expect(dashboard).toEqual({+ id: 42,+ name: 'KPIs',+ url: 'https://us.posthog.com/project/1/dashboard/42',+ })+ })++ it('falls back to legacy dashboard_id / url fields and the input name', () => {+ const dashboard = extractDashboard(+ toolMessage({ dashboard_id: '7', url: '/dashboard/7' }, { name: 'From input' })+ )+ expect(dashboard).toEqual({ id: '7', name: 'From input', url: '/dashboard/7' })+ })+ })++ describe('extractRecordingFilters', () => {+ it('maps the query-wrapper output back to universal filters', () => {+ const filters = extractRecordingFilters(+ toolMessage({+ query: {+ kind: 'RecordingsQuery',+ date_from: '-7d',+ filter_test_accounts: true,+ properties: [{ type: 'person', key: 'email', operator: 'icontains', value: 'posthog' }],+ },+ results: [],+ _posthogUrl: 'https://us.posthog.com/project/1/replay',+ })+ )+ expect(filters?.date_from).toBe('-7d')+ expect(filters?.filter_test_accounts).toBe(true)+ expect(filters?.filter_group.values).toEqual([+ {+ type: 'AND',+ values: [{ type: 'person', key: 'email', operator: 'icontains', value: 'posthog' }],+ },+ ])+ })++ it('passes through a ready-made universal filters object', () => {+ const universal = {+ date_from: '-3d',+ duration: [],+ filter_group: { type: 'AND', values: [] },+ }+ expect(extractRecordingFilters(toolMessage({ filters: universal }))).toBe(universal)+ })++ it('returns null for outputs carrying neither shape', () => {+ expect(extractRecordingFilters(toolMessage({ results: [] }))).toBeNull()+ expect(extractRecordingFilters(toolMessage({ filters: { some: 'garbage' } }))).toBeNull()+ expect(extractRecordingFilters(toolMessage(undefined))).toBeNull()+ })+ })++ describe('extractErrorTrackingResponse', () => {+ it('accepts outputs carrying known search-response fields', () => {+ const response = { status: 'active', search_query: 'TypeError', issues: [] }+ expect(extractErrorTrackingResponse(toolMessage(response))).toBe(response)+ })++ it('rejects outputs without any known field', () => {+ expect(extractErrorTrackingResponse(toolMessage({ results: [{ id: 'issue-1' }] }))).toBeNull()+ expect(extractErrorTrackingResponse(toolMessage(undefined))).toBeNull()+ })+ })++ describe('extractQueryResult', () => {+ it.each(['TrendsQuery', 'FunnelsQuery', 'RetentionQuery', 'StickinessQuery', 'PathsQuery', 'LifecycleQuery'])(+ 'passes a bare %s through for InsightVizNode wrapping downstream',+ (kind) => {+ const result = extractQueryResult(+ toolMessage({+ query: { kind, series: [] },+ results: [],+ _posthogUrl: 'https://us.posthog.com/insights/new',+ })+ )+ expect(result?.content.query).toEqual({ kind, series: [] })+ expect(result?.url).toBe('https://us.posthog.com/insights/new')+ }+ )++ it('wraps a TracesQuery in a DataTableNode', () => {+ const result = extractQueryResult(toolMessage({ query: { kind: 'TracesQuery' }, results: [] }))+ expect(result?.content.query).toEqual({ kind: 'DataTableNode', source: { kind: 'TracesQuery' } })+ expect(result?.url).toBeNull()+ })++ it('uses the tool input when optimized streamed results omit structured raw output', () => {+ const result = extractQueryResult(+ toolMessage(undefined, { kind: 'TrendsQuery', series: [], output_format: 'optimized' }, 'query-trends')+ )+ expect(result?.content.query).toEqual({ kind: 'TrendsQuery', series: [] })+ expect(result?.url).toBeNull()+ })++ it('infers the query kind from the wrapper tool key when the input omits kind', () => {+ const result = extractQueryResult(toolMessage(undefined, { series: [] }, 'query-trends'))+ expect(result?.content.query).toEqual({ kind: 'TrendsQuery', series: [] })+ })++ it('wraps the actors wrapper output (ActorsQuery envelope) untouched in a DataTableNode', () => {+ const actorsQuery = {+ kind: 'ActorsQuery',+ source: { kind: 'InsightActorsQuery', source: { kind: 'TrendsQuery' } },+ select: ['actor'],+ }+ const result = extractQueryResult(+ toolMessage({ query: actorsQuery, results: { columns: [], results: [] } })+ )+ expect(result?.content.query).toEqual({ kind: 'DataTableNode', source: actorsQuery })+ })++ it('wraps a bare InsightActorsQuery in an ActorsQuery before the DataTableNode', () => {+ const insightActors = { kind: 'InsightActorsQuery', source: { kind: 'TrendsQuery' } }+ const result = extractQueryResult(toolMessage({ query: insightActors }))+ expect(result?.content.query).toEqual({+ kind: 'DataTableNode',+ source: { kind: 'ActorsQuery', source: insightActors, select: ['actor'] },+ })+ })++ it('returns null for kinds without an inline renderer or malformed outputs', () => {+ expect(extractQueryResult(toolMessage({ query: { kind: 'TraceQuery', traceId: 't1' } }))).toBeNull()+ expect(extractQueryResult(toolMessage({ results: [] }))).toBeNull()+ expect(extractQueryResult(toolMessage({ query: 'not-an-object' }))).toBeNull()+ expect(extractQueryResult(toolMessage(undefined))).toBeNull()+ })+ })+})diff --git a/frontend/src/scenes/max/messages/adapters/extractors.ts b/frontend/src/scenes/max/messages/adapters/extractors.tsnew file mode 100644index 000000000000..b4bd3ae392cf--- /dev/null+++ b/frontend/src/scenes/max/messages/adapters/extractors.ts@@ -0,0 +1,231 @@+import { recordingsQueryToUniversalFilters } from 'scenes/session-recordings/filters/recordingsQueryConversions'++import { MaxErrorTrackingSearchResponse } from '~/queries/schema/schema-assistant-error-tracking'+import {+ ArtifactContentType,+ ArtifactMessage,+ ArtifactSource,+ AssistantMessageType,+ VisualizationArtifactContent,+} from '~/queries/schema/schema-assistant-messages'+import { DataTableNode, NodeKind, RecordingsQuery } from '~/queries/schema/schema-general'+import { isInsightQueryNode } from '~/queries/utils'+import { RecordingUniversalFilters } from '~/types'++import type { SandboxToolCallMessage } from '../../maxTypes'++/**+ * Shared shape extractors for the sandbox MCP tool renderer widgets. Each turns a flattened+ * `SandboxToolCallMessage` (built by `sandboxStreamLogic` from ACP frames) into the props the atomic+ * `messages/*` widgets expect.+ */++function asRecord(value: unknown): Record<string, unknown> | null {+ return value && typeof value === 'object' && !Array.isArray(value) ? (value as Record<string, unknown>) : null+}++function asString(value: unknown): string | undefined {+ return typeof value === 'string' ? value : undefined+}++const QUERY_WRAPPER_KIND_BY_TOOL_KEY: Record<string, NodeKind> = {+ 'query-trends': NodeKind.TrendsQuery,+ 'query-funnel': NodeKind.FunnelsQuery,+ 'query-retention': NodeKind.RetentionQuery,+ 'query-stickiness': NodeKind.StickinessQuery,+ 'query-paths': NodeKind.PathsQuery,+ 'query-lifecycle': NodeKind.LifecycleQuery,+ 'query-llm-traces-list': NodeKind.TracesQuery,+ 'query-trends-actors': NodeKind.InsightActorsQuery,+ 'query-lifecycle-actors': NodeKind.InsightActorsQuery,+ 'query-paths-actors': NodeKind.InsightActorsQuery,+ 'query-retention-actors': NodeKind.InsightActorsQuery,+}++function queryFromToolInput(message: SandboxToolCallMessage): Record<string, unknown> | null {+ const input = asRecord(message.innerInput)+ if (!input) {+ return null+ }++ const query = { ...input }+ delete query.output_format++ if (typeof query.kind === 'string') {+ return query+ }++ const inferredKind = QUERY_WRAPPER_KIND_BY_TOOL_KEY[message.resolvedKey]+ return inferredKind ? { ...query, kind: inferredKind } : null+}++/** The artifact envelope + content the visualization widget proxies consume. */+export interface VisualizationArtifactExtraction {+ envelope: ArtifactMessage+ content: VisualizationArtifactContent+}++/**+ * Pulls a `VisualizationArtifactContent` out of an insight tool's `rawOutput`. The backend MCP+ * server returns the artifact directly in the existing schema shape. Saved insights+ * (create / update / get) carry a `short_id` in the REST payload (or an explicit `artifact_id`);+ * query-only outputs carry neither and render inline as ephemeral visualizations.+ */+export function extractVisualizationArtifact(message: SandboxToolCallMessage): VisualizationArtifactExtraction | null {+ const output = asRecord(message.rawOutput)+ if (!output) {+ return null+ }++ const query = output.query+ if (!query) {+ return null+ }++ const artifactId = asString(output.artifact_id) ?? asString(output.short_id) ?? message.id+ const isSaved = asString(output.short_id) !== undefined || asString(output.artifact_id) !== undefined+ const source = isSaved ? ArtifactSource.Insight : ArtifactSource.State++ const content: VisualizationArtifactContent = {+ content_type: ArtifactContentType.Visualization,+ query: query as VisualizationArtifactContent['query'],+ name: asString(output.name) ?? asString(message.innerInput?.name) ?? null,+ description: asString(output.description) ?? null,+ }++ const envelope: ArtifactMessage = {+ type: AssistantMessageType.Artifact,+ id: message.id,+ artifact_id: artifactId,+ source,+ content,+ }++ return { envelope, content }+}++/** A query-wrapper tool result mapped onto renderable visualization content. */+export interface QueryResultExtraction {+ content: VisualizationArtifactContent+ /** The MCP server's `_posthogUrl` enrichment — the "open as insight" CTA target. */+ url: string | null+}++/**+ * Maps a query-wrapper tool's output (`{query, results, _posthogUrl}`) onto visualization+ * content. Insight queries pass through bare (the widget wraps them in `InsightVizNode`);+ * table-renderable kinds are wrapped in a `DataTableNode` here. Kinds without an inline+ * renderer (e.g. a single LLM trace) return null and fall back to the generic card.+ */+export function extractQueryResult(message: SandboxToolCallMessage): QueryResultExtraction | null {+ const output = asRecord(message.rawOutput)+ const query = (output ? asRecord(output.query) : null) ?? queryFromToolInput(message)+ if (!query || typeof query.kind !== 'string') {+ return null+ }++ let renderable: VisualizationArtifactContent['query'] | null = null+ if (isInsightQueryNode(query)) {+ renderable = query as VisualizationArtifactContent['query']+ } else if (query.kind === NodeKind.TracesQuery || query.kind === NodeKind.ActorsQuery) {+ // The actors wrappers echo a ready-made ActorsQuery envelope; traces come back bare.+ renderable = { kind: NodeKind.DataTableNode, source: query } as unknown as DataTableNode+ } else if (query.kind === NodeKind.InsightActorsQuery) {+ // Defensive: a bare InsightActorsQuery isn't a table source — wrap it in an ActorsQuery first.+ renderable = {+ kind: NodeKind.DataTableNode,+ source: { kind: NodeKind.ActorsQuery, source: query, select: ['actor'] },+ } as unknown as DataTableNode+ }++ if (!renderable) {+ return null+ }++ return {+ content: {+ content_type: ArtifactContentType.Visualization,+ query: renderable,+ name: null,+ description: null,+ },+ url: asString(output?._posthogUrl) ?? null,+ }+}++/** Dashboard create/update output — the REST payload (`id`, `name`) plus the MCP server's `_posthogUrl` enrichment. */+export interface DashboardExtraction {+ id?: string | number+ name?: string+ url?: string+}++export function extractDashboard(message: SandboxToolCallMessage): DashboardExtraction | null {+ const output = asRecord(message.rawOutput)+ if (!output) {+ return null+ }+ const id = (output.id ?? output.dashboard_id) as string | number | undefined+ return {+ id,+ name: asString(output.name) ?? asString(message.innerInput?.name),+ url: asString(output._posthogUrl) ?? asString(output.url),+ }+}++/**+ * Resolves the `RecordingUniversalFilters` the playlist widget renders. The query-wrapper tool+ * echoes the executed `RecordingsQuery` back under `rawOutput.query`, which we convert; a+ * ready-made universal filters object under `rawOutput.filters` is passed through. Anything else+ * falls back to the generic card rather than feeding the playlist a shape it can't use.+ */+export function extractRecordingFilters(message: SandboxToolCallMessage): RecordingUniversalFilters | null {+ const output = asRecord(message.rawOutput)+ if (!output) {+ return null+ }++ const directFilters = asRecord(output.filters)+ if (directFilters && 'filter_group' in directFilters && Array.isArray(directFilters.duration)) {+ return directFilters as unknown as RecordingUniversalFilters+ }++ const query = asRecord(output.query)+ if (query && query.kind === NodeKind.RecordingsQuery) {+ const recordingsQuery = query as unknown as RecordingsQuery+ // The shared converter intentionally drops list-level fields (its caller manages them+ // separately) — carry them over so the widget reflects what the agent actually searched.+ return {+ ...recordingsQueryToUniversalFilters(recordingsQuery),+ date_from: recordingsQuery.date_from ?? null,+ date_to: recordingsQuery.date_to ?? null,+ order: recordingsQuery.order,+ order_direction: recordingsQuery.order_direction,+ limit: recordingsQuery.limit,+ session_ids: recordingsQuery.session_ids,+ }+ }++ return null+}++const ERROR_TRACKING_RESPONSE_KEYS: readonly (keyof MaxErrorTrackingSearchResponse)[] = [+ 'issues',+ 'search_query',+ 'status',+ 'date_from',+ 'order_by',+]++/**+ * Error-tracking search output is a `MaxErrorTrackingSearchResponse` (a filters echo plus issue+ * previews) for `ErrorTrackingFiltersWidget`. Outputs that carry none of its fields — e.g. a raw+ * REST issues list — fall back to the generic card instead of rendering empty filter chips.+ */+export function extractErrorTrackingResponse(message: SandboxToolCallMessage): MaxErrorTrackingSearchResponse | null {+ const output = asRecord(message.rawOutput)+ if (!output || !ERROR_TRACKING_RESPONSE_KEYS.some((key) => key in output)) {+ return null+ }+ return output as MaxErrorTrackingSearchResponse+}diff --git a/frontend/src/scenes/max/messages/posthogProducts.ts b/frontend/src/scenes/max/messages/posthogProducts.tsnew file mode 100644index 000000000000..c9c819ed035c--- /dev/null+++ b/frontend/src/scenes/max/messages/posthogProducts.ts@@ -0,0 +1,74 @@+/**+ * PostHog product taxonomy for the sandbox resources bar. Ported from the agent's+ * `POSTHOG_PRODUCTS` (ids + labels are authoritative there) with icons sourced from+ * `@posthog/icons`. The `_posthog/resources_used` wire frame already carries `{id, label}`, so this+ * map is the icon source plus a fallback label for any id the wire omits. Labels are NOT a+ * mechanical sentence-casing of the id (e.g. `llm_analytics → "AI observability"`,+ * `cdp → "Data pipelines"`, acronyms stay all-caps), so they are copied verbatim.+ */+import {+ IconAI,+ IconCursor,+ IconDatabase,+ IconFlask,+ IconGraph,+ IconHogQL,+ IconLogomark,+ IconMessage,+ IconPlug,+ IconPulse,+ IconRewind,+ IconServer,+ IconToggle,+ IconWarning,+} from '@posthog/icons'++export type PostHogProductId =+ | 'product_analytics'+ | 'web_analytics'+ | 'feature_flags'+ | 'experiments'+ | 'error_tracking'+ | 'session_replay'+ | 'surveys'+ | 'llm_analytics'+ | 'data_warehouse'+ | 'cdp'+ | 'logs'+ | 'apm'+ | 'sql'+ | 'posthog'++export interface PostHogProductMeta {+ label: string+ Icon: typeof IconGraph+}++export const POSTHOG_PRODUCTS: Record<PostHogProductId, PostHogProductMeta> = {+ product_analytics: { label: 'Product analytics', Icon: IconGraph },+ web_analytics: { label: 'Web analytics', Icon: IconPulse },+ feature_flags: { label: 'Feature flags', Icon: IconToggle },+ experiments: { label: 'Experiments', Icon: IconFlask },+ error_tracking: { label: 'Error tracking', Icon: IconWarning },+ session_replay: { label: 'Session replay', Icon: IconRewind },+ surveys: { label: 'Surveys', Icon: IconMessage },+ llm_analytics: { label: 'AI observability', Icon: IconAI },+ data_warehouse: { label: 'Data warehouse', Icon: IconDatabase },+ cdp: { label: 'Data pipelines', Icon: IconPlug },+ logs: { label: 'Logs', Icon: IconServer },+ apm: { label: 'APM', Icon: IconCursor },+ sql: { label: 'SQL', Icon: IconHogQL },+ posthog: { label: 'PostHog', Icon: IconLogomark },+}++/** Fallback icon for ids absent from the taxonomy — degrade gracefully rather than disappearing. */+export const FALLBACK_PRODUCT_ICON = IconLogomark++/** Resolve a product id to its icon + display label, tolerating unknown ids (uses the wire label). */+export function resolveProductMeta(id: string, wireLabel?: string): PostHogProductMeta {+ const known = POSTHOG_PRODUCTS[id as PostHogProductId]+ if (known) {+ return { label: wireLabel || known.label, Icon: known.Icon }+ }+ return { label: wireLabel || id, Icon: FALLBACK_PRODUCT_ICON }+}diff --git a/frontend/src/scenes/max/posthogAiContextLogic.tsx b/frontend/src/scenes/max/posthogAiContextLogic.tsxnew file mode 100644index 000000000000..c74fae08deb2--- /dev/null+++ b/frontend/src/scenes/max/posthogAiContextLogic.tsx@@ -0,0 +1,155 @@+import { actions, connect, kea, key, listeners, path, props, reducers, selectors } from 'kea'+import posthog from 'posthog-js'+import type { ReactNode } from 'react'++import { IconDashboard, IconGraph, IconNotebook } from '@posthog/icons'++import { IconAction, IconEvent } from 'lib/lemon-ui/icons'+import { sceneLogic } from 'scenes/sceneLogic'++import { AttachedContext, MaxContextInput, MaxContextType } from './maxTypes'+import type { posthogAiContextLogicType } from './posthogAiContextLogicType'++export interface PosthogAiContextLogicProps {+ conversationId: string+}++/** Stable dedupe + chip key for an attachment: `${type}:${id ?? value}`. */+export function attachedContextKey(item: AttachedContext): string {+ return `${item.type}:${item.id ?? item.value ?? ''}`+}++/**+ * Projects a rich scene `MaxContextInput` down to the flat `AttachedContext` shape the sandbox+ * runtime sends. Strips nested entity data — the agent fetches details via its read tools.+ * Returns null for inputs that have no flat representation.+ */+export function projectToAttachedContext(item: MaxContextInput): AttachedContext | null {+ switch (item.type) {+ case MaxContextType.DASHBOARD:+ return { type: 'dashboard', id: item.data.id, name: item.data.name ?? undefined }+ case MaxContextType.INSIGHT:+ return { type: 'insight', id: item.data.short_id, name: item.data.name ?? undefined }+ case MaxContextType.EVENT:+ return { type: 'event', id: item.data.id, name: item.data.name ?? undefined }+ case MaxContextType.ACTION:+ return { type: 'action', id: item.data.id, name: item.data.name ?? undefined }+ case MaxContextType.ERROR_TRACKING_ISSUE:+ return { type: 'error_tracking_issue', id: item.data.id, name: item.data.name ?? undefined }+ case MaxContextType.EVALUATION:+ return { type: 'evaluation', id: item.data.id, name: item.data.name ?? undefined }+ case MaxContextType.NOTEBOOK:+ return { type: 'notebook', id: item.data.short_id, name: item.data.title ?? undefined }+ default:+ return null+ }+}++function iconForType(type: AttachedContext['type']): ReactNode {+ switch (type) {+ case 'dashboard':+ return <IconDashboard />+ case 'insight':+ return <IconGraph />+ case 'event':+ return <IconEvent />+ case 'action':+ return <IconAction />+ case 'notebook':+ return <IconNotebook />+ default:+ return <IconGraph />+ }+}++function labelForItem(item: AttachedContext): string {+ if (item.type === 'text') {+ return item.value ?? 'Text'+ }+ if (item.name) {+ return item.name+ }+ return `${item.type} ${item.id ?? ''}`.trim()+}++/**+ * Sandbox-runtime context store. Holds one flat `attachments` reducer plus a scene-pull+ * listener that reads the existing scenes' `maxContext` selectors and projects their rich+ * items down to `AttachedContext` at consumption time — zero scene-side edits.+ *+ * Coexistence sibling to `maxContextLogic.ts`; used only when `agent_runtime === 'sandbox'`.+ *+ * Keyed by conversation id so each conversation keeps its own attachment set.+ */+export const posthogAiContextLogic = kea<posthogAiContextLogicType>([+ props({} as PosthogAiContextLogicProps),+ key((props) => props.conversationId),+ path((key) => ['scenes', 'max', 'posthogAiContextLogic', key]),+ connect(() => ({+ values: [sceneLogic, ['activeSceneLogic']],+ })),+ actions({+ /** Dedup-add. Called by scene sync AND by the TaxonomicFilter affordance. */+ attach: (item: AttachedContext) => ({ item }),+ /** Remove by `${type}:${id ?? value}` key. */+ detach: (key: string) => ({ key }),+ /** Convenience reset, e.g. on a new conversation. */+ clearAttachments: true,+ /** Router/scene listener — projects every current-scene item and attaches it. */+ syncSceneAttachments: true,+ }),+ reducers({+ attachments: [+ [] as AttachedContext[],+ {+ attach: (state, { item }) => {+ const key = attachedContextKey(item)+ // Text items are never deduped — repeated text is intentional.+ if (item.type !== 'text' && state.some((existing) => attachedContextKey(existing) === key)) {+ return state+ }+ return [...state, item]+ },+ detach: (state, { key }) => state.filter((item) => attachedContextKey(item) !== key),+ clearAttachments: () => [],+ },+ ],+ }),+ selectors({+ chipsForDisplay: [+ (s) => [s.attachments],+ // No onRemove closures here — removal dispatches `detach(key)` on the consumer's+ // bound instance, so chips stay instance-agnostic data.+ (attachments): { key: string; label: string; icon: ReactNode }[] =>+ attachments.map((item) => ({+ key: attachedContextKey(item),+ label: labelForItem(item),+ icon: iconForType(item.type),+ })),+ ],+ }),+ listeners(({ values, actions }) => ({+ syncSceneAttachments: () => {+ const activeSceneLogic = values.activeSceneLogic+ if (!activeSceneLogic || !('maxContext' in activeSceneLogic.selectors)) {+ return+ }+ let sceneItems: MaxContextInput[] = []+ try {+ // BuiltLogic exposes selector results on `.values`; props are already bound.+ sceneItems = (activeSceneLogic.values as { maxContext?: MaxContextInput[] }).maxContext ?? []+ } catch (error) {+ // The scene's maxContext selector threw (e.g. dereferencing still-loading state).+ // Capture so the dropped attach is observable instead of silent; nothing to attach.+ posthog.captureException(error)+ return+ }+ for (const item of sceneItems) {+ const projected = projectToAttachedContext(item)+ if (projected) {+ actions.attach(projected)+ }+ }+ },+ })),+])diff --git a/frontend/src/scenes/max/sandbox/SandboxGitArtifacts.test.tsx b/frontend/src/scenes/max/sandbox/SandboxGitArtifacts.test.tsxnew file mode 100644index 000000000000..fbc6101be313--- /dev/null+++ b/frontend/src/scenes/max/sandbox/SandboxGitArtifacts.test.tsx@@ -0,0 +1,35 @@+import '@testing-library/jest-dom'++import { cleanup, render, screen } from '@testing-library/react'++import { SandboxPullRequestCard } from './SandboxPullRequestCard'+import { SandboxRunContext } from './SandboxRunContext'++const PR_URL = 'https://github.com/PostHog/posthog/pull/123'++// Visibility is the caller's concern (SandboxThread mounts these only when the run reports the+// relevant artifact), so these cover only that each renders its data when mounted.+describe('sandbox git artifacts', () => {+ afterEach(() => {+ cleanup()+ })++ it('SandboxRunContext renders the working and base branch', () => {+ render(<SandboxRunContext branch="feat/x" baseBranch="master" repo="PostHog/posthog" />)+ expect(screen.getByText('feat/x')).toBeInTheDocument()+ expect(screen.getByText('master')).toBeInTheDocument()+ expect(screen.getByText('PostHog/posthog')).toBeInTheDocument()+ })++ it('SandboxRunContext renders just the branch when there is no base or repo', () => {+ render(<SandboxRunContext branch="feat/x" />)+ expect(screen.getByText('feat/x')).toBeInTheDocument()+ })++ it('SandboxPullRequestCard renders the success card and a link to the PR', () => {+ render(<SandboxPullRequestCard prUrl={PR_URL} branch="feat/x" />)+ expect(screen.getByText('Pull request opened')).toBeInTheDocument()+ expect(screen.getByText('feat/x')).toBeInTheDocument()+ expect(screen.getByRole('link', { name: /Open on GitHub/ })).toHaveAttribute('href', PR_URL)+ })+})diff --git a/frontend/src/scenes/max/sandbox/SandboxPullRequestCard.tsx b/frontend/src/scenes/max/sandbox/SandboxPullRequestCard.tsxnew file mode 100644index 000000000000..64ccbf5baad4--- /dev/null+++ b/frontend/src/scenes/max/sandbox/SandboxPullRequestCard.tsx@@ -0,0 +1,40 @@+import { memo } from 'react'++import { IconCheckCircle, IconExternal, IconPullRequest } from '@posthog/icons'+import { LemonButton } from '@posthog/lemon-ui'++/**+ * Post-turn "Pull request opened" card for a sandbox coding run — the web port of PostHog Code's+ * `GitActionResult`, adapted to LemonUI. Plain props, `React.memo`'d — `prUrl` is required, so the+ * caller decides whether to mount it (only once a run has opened a PR and is no longer thinking).+ * Frontend-only: it shows the link + branch, no diff stats (those need a backend wire field; see the+ * logic's follow-ups).+ */+export const SandboxPullRequestCard = memo(function SandboxPullRequestCard({+ prUrl,+ branch,+}: {+ prUrl: string+ branch?: string+}): JSX.Element {+ return (+ <div+ className="flex flex-col gap-2 rounded-lg border border-success bg-success-highlight p-3"+ data-attr="max-sandbox-pr-card"+ >+ <div className="flex items-center gap-2">+ <IconCheckCircle className="size-4 shrink-0 text-success" />+ <span className="text-sm font-medium text-success">Pull request opened</span>+ </div>+ <div className="flex flex-wrap items-center gap-2">+ <span className="flex items-center gap-1.5 text-xs text-muted">+ <IconPullRequest className="size-3.5 shrink-0" />+ {branch ? <span className="font-mono">{branch}</span> : null}+ </span>+ <LemonButton type="secondary" size="xsmall" icon={<IconExternal />} to={prUrl} targetBlank>+ Open on GitHub+ </LemonButton>+ </div>+ </div>+ )+})diff --git a/frontend/src/scenes/max/sandbox/SandboxQuestionRenderer.test.tsx b/frontend/src/scenes/max/sandbox/SandboxQuestionRenderer.test.tsxnew file mode 100644index 000000000000..b2d05a89f2e9--- /dev/null+++ b/frontend/src/scenes/max/sandbox/SandboxQuestionRenderer.test.tsx@@ -0,0 +1,99 @@+import '@testing-library/jest-dom'++import { cleanup, fireEvent, render, screen } from '@testing-library/react'++import type { SandboxToolCallMessage } from '../maxTypes'+import { SandboxQuestionRenderer } from './SandboxQuestionRenderer'++function makeMessage(overrides: Partial<SandboxToolCallMessage> = {}): SandboxToolCallMessage {+ return {+ id: 'tc-1',+ resolvedKey: 'AskUserQuestion',+ rawServerName: '',+ rawToolName: 'AskUserQuestion',+ claudeToolName: 'AskUserQuestion',+ rawInput: {+ questions: [+ {+ question: 'Which goal matters most?',+ header: 'Goal',+ multiSelect: false,+ options: [{ label: 'Activation' }, { label: 'Revenue' }],+ },+ ],+ },+ content: [],+ status: 'completed',+ ...overrides,+ }+}++function renderCard(message: SandboxToolCallMessage): void {+ render(<SandboxQuestionRenderer message={message} isLastInGroup displayName="Question" />)+}++describe('SandboxQuestionRenderer', () => {+ afterEach(() => {+ cleanup()+ })++ it('previews the answer on the second line and shows the full Q&A on expand', () => {+ renderCard(makeMessage({ rawOutput: { answers: { 'Which goal matters most?': 'Revenue' } } }))++ // Preview on the header's second line (always visible).+ expect(screen.getByText('Revenue')).toBeInTheDocument()+ // The full question + answer live in the collapsible body.+ expect(screen.queryByText('Which goal matters most?')).not.toBeInTheDocument()++ fireEvent.click(screen.getByRole('button'))+ expect(screen.getByText('Which goal matters most?')).toBeInTheDocument()+ expect(screen.getAllByText('Revenue').some((el) => el.classList.contains('font-medium'))).toBe(true)+ // The header label ("Goal") is dropped from the recap.+ expect(screen.queryByText('Goal')).not.toBeInTheDocument()+ })++ it('does not render a body while the question is still being asked', () => {+ renderCard(makeMessage({ status: 'in_progress', rawOutput: undefined }))++ expect(screen.queryByText('Which goal matters most?')).not.toBeInTheDocument()+ expect(screen.queryByRole('button')).not.toBeInTheDocument()+ })++ it('recaps each answer for a multi-question request', () => {+ renderCard(+ makeMessage({+ rawInput: {+ questions: [+ { question: 'Goal?', header: 'Goal', multiSelect: false, options: [{ label: 'Revenue' }] },+ { question: 'When?', header: 'When', multiSelect: false, options: [{ label: 'Weekly' }] },+ ],+ },+ rawOutput: { answers: { 'Goal?': 'Revenue', 'When?': 'Weekly' } },+ })+ )++ fireEvent.click(screen.getByRole('button'))+ expect(screen.getByText('Revenue')).toBeInTheDocument()+ expect(screen.getByText('Weekly')).toBeInTheDocument()+ })++ it('falls back to a joined answer string when there is no per-question map', () => {+ renderCard(makeMessage({ rawOutput: { text: 'User picked Revenue' } }))++ expect(screen.getByText('User picked Revenue')).toBeInTheDocument()+ })++ it('shows the error message when the call failed', () => {+ renderCard(makeMessage({ status: 'failed', rawOutput: undefined, error: { message: 'Question timed out' } }))++ expect(screen.getByText('Question timed out')).toBeInTheDocument()+ })++ it('falls back to the generic tool card when the input has no questions', () => {+ renderCard(makeMessage({ rawInput: {}, rawOutput: undefined }))++ // The generic card renders instead of the question recap.+ expect(screen.getByText('Question')).toBeInTheDocument()+ expect(screen.queryByText('Which goal matters most?')).not.toBeInTheDocument()+ })+})diff --git a/frontend/src/scenes/max/sandbox/SandboxQuestionRenderer.tsx b/frontend/src/scenes/max/sandbox/SandboxQuestionRenderer.tsxnew file mode 100644index 000000000000..3a4d34cfa494--- /dev/null+++ b/frontend/src/scenes/max/sandbox/SandboxQuestionRenderer.tsx@@ -0,0 +1,65 @@+import { IconAI } from '@posthog/icons'++import {+ extractSandboxQuestionAnswer,+ parseSandboxQuestionAnswers,+ parseSandboxQuestions,+} from '../sandboxQuestionUtils'+import { GenericMcpToolRenderer } from './components/tool/GenericMcpToolRenderer'+import { SandboxToolActivity } from './components/tool/SandboxToolActivity'+import { truncateText } from './components/tool/toolContentUtils'+import type { SandboxToolRendererProps } from './sandboxToolRegistry'++/**+ * Thread recap for the `AskUserQuestion` Claude built-in. The interactive answering happens in the+ * input overlay (`SandboxQuestionInput`); this is the transcript record: the chosen answers preview on+ * the header's second line, and the full question + answer in the expandable body. Malformed input+ * falls back to the generic tool card.+ */+export function SandboxQuestionRenderer(props: SandboxToolRendererProps): JSX.Element {+ const { message, icon, displayName, turnComplete, turnCancelled } = props+ const questions = parseSandboxQuestions(message.rawInput)++ if (questions.length === 0) {+ return <GenericMcpToolRenderer {...props} />+ }++ const answersByKey = parseSandboxQuestionAnswers(message.rawOutput)+ // When the result didn't carry a per-question map, fall back to a single joined answer string+ // (the agent's `extractAnswer`) attributed to the first question, so the answer is never lost.+ const fallbackAnswer =+ Object.keys(answersByKey).length === 0 ? extractSandboxQuestionAnswer(message.rawOutput) : null++ const answered = questions+ .map((question, index) => {+ const answer = answersByKey[question.question] ?? (index === 0 ? fallbackAnswer : null)+ return answer ? { question: question.question, answer } : null+ })+ .filter((entry): entry is { question: string; answer: string } => entry !== null)++ const answerPreview = answered.map((entry) => entry.answer).join(', ')++ const body =+ answered.length > 0 ? (+ <div className="flex flex-col gap-3">+ {answered.map((entry, index) => (+ <div key={index} className="flex flex-col gap-1 text-xs">+ <div className="text-muted">{entry.question}</div>+ <span className="font-medium text-secondary">{entry.answer}</span>+ </div>+ ))}+ </div>+ ) : undefined++ return (+ <SandboxToolActivity+ message={message}+ icon={icon ?? <IconAI />}+ title={message.title || displayName || 'Question'}+ subtitle={answerPreview ? truncateText(answerPreview, 120) : undefined}+ body={body}+ turnComplete={turnComplete}+ turnCancelled={turnCancelled}+ />+ )+}diff --git a/frontend/src/scenes/max/sandbox/SandboxRunContext.tsx b/frontend/src/scenes/max/sandbox/SandboxRunContext.tsxnew file mode 100644index 000000000000..19e8aa33da35--- /dev/null+++ b/frontend/src/scenes/max/sandbox/SandboxRunContext.tsx@@ -0,0 +1,41 @@+import { memo } from 'react'++import { IconGitBranch } from '@posthog/icons'++/**+ * Pre-turn header for a sandbox coding run: a one-line "Working on <repo> · <branch> → <base>"+ * summary. Plain props, `React.memo`'d — `branch` is required, so the caller decides whether to mount+ * it (only when a run reports git context). This complements — does not replace — the+ * `_posthog/progress` provisioning steps.+ */+export const SandboxRunContext = memo(function SandboxRunContext({+ branch,+ baseBranch,+ repo,+}: {+ branch: string+ baseBranch?: string+ repo?: string+}): JSX.Element {+ return (+ <div className="flex items-center gap-1.5 px-3 py-1 text-xs text-muted" data-attr="max-sandbox-run-context">+ <IconGitBranch className="size-3.5 shrink-0" />+ <span className="min-w-0 truncate">+ Working on{' '}+ {repo ? (+ <>+ <span className="font-medium">{repo}</span>+ {' · '}+ </>+ ) : null}+ <span className="font-mono">{branch}</span>+ {baseBranch ? (+ <>+ {' → '}+ <span className="font-mono">{baseBranch}</span>+ </>+ ) : null}+ </span>+ </div>+ )+})diff --git a/frontend/src/scenes/max/sandbox/SandboxThreadItems.tsx b/frontend/src/scenes/max/sandbox/SandboxThreadItems.tsxnew file mode 100644index 000000000000..2b9af7a07c95--- /dev/null+++ b/frontend/src/scenes/max/sandbox/SandboxThreadItems.tsx@@ -0,0 +1,61 @@+import { IconCheck, IconWarning, IconX } from '@posthog/icons'+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'++/** Inline `_posthog/status` item — a spinner while compacting, a generic status line otherwise. */+export function SandboxStatusItem({ item }: { item: ThreadItem }): JSX.Element {+ const isCompacting = item.status === 'compacting' && !item.isComplete+ return (+ <div className="flex items-center justify-center gap-2 py-1 text-xs text-muted">+ {isCompacting ? (+ <>+ <Spinner className="size-3" />+ <span>Compacting conversation history…</span>+ </>+ ) : (+ <span>Status: {item.status}</span>+ )}+ </div>+ )+}++/** Inline `_posthog/compact_boundary` item — the post-compaction rule. */+export function SandboxCompactBoundaryItem({ item }: { item: ThreadItem }): JSX.Element {+ return (+ <div className="flex items-center gap-2 py-1 text-xs text-muted">+ <div className="h-px grow bg-border" />+ <span className="shrink-0">+ Conversation compacted+ {item.trigger ? ` (${item.trigger})` : ''}+ {typeof item.preTokens === 'number'+ ? ` · ~${humanFriendlyNumber(item.preTokens)} tokens summarized`+ : ''}+ </span>+ <div className="h-px grow bg-border" />+ </div>+ )+}++/** Inline `_posthog/task_notification` item — a colored rule by status (completed/failed/stopped). */+export function SandboxTaskNotificationItem({ item }: { item: ThreadItem }): JSX.Element {+ const colorClass =+ item.status === 'completed' ? 'text-success' : item.status === 'failed' ? 'text-danger' : 'text-warning'+ const icon =+ item.status === 'completed' ? (+ <IconCheck className="size-3" />+ ) : item.status === 'failed' ? (+ <IconX className="size-3" />+ ) : (+ <IconWarning className="size-3" />+ )+ return (+ <div className={cn('flex items-center justify-center gap-1.5 py-1 text-xs', colorClass)}>+ {icon}+ <span>{item.summary || `Task ${item.status}`}</span>+ </div>+ )+}diff --git a/frontend/src/scenes/max/sandbox/components/SandboxRunViewer.tsx b/frontend/src/scenes/max/sandbox/components/SandboxRunViewer.tsxnew file mode 100644index 000000000000..04d9dfcf8ec5--- /dev/null+++ b/frontend/src/scenes/max/sandbox/components/SandboxRunViewer.tsx@@ -0,0 +1,92 @@+import { BindLogic, useActions, useValues } from 'kea'+import { useEffect } from 'react'++import { Spinner } from '@posthog/lemon-ui'++import { cn } from 'lib/utils/css-classes'++import { sandboxStreamLogic } from '../../sandboxStreamLogic'+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+ /**+ * Replay the persisted `logs/` snapshot once and never open SSE (default `true`, the safe choice+ * for a static run viewer). Pass `false` for an in-progress run to stream live frames over SSE,+ * falling back to replay automatically once the run goes terminal. Folded into the logic key, so a+ * live and a replay viewer of the same run can never share state.+ */+ replayOnly?: boolean+ className?: string+}++/**+ * Embeddable read-only 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`. With+ * the default `replayOnly`, it replays the persisted `logs/` snapshot once — no SSE. With+ * `replayOnly={false}` it streams an in-progress run live (and replays once terminal). No permissions,+ * no composer. Drop in anywhere with just `(taskId, runId)`.+ */+export function SandboxRunViewer({+ taskId,+ runId,+ streamKey,+ conversationId,+ replayOnly = true,+ className,+}: SandboxRunViewerProps): JSX.Element {+ return (+ <BindLogic logic={sandboxStreamLogic} props={{ streamKey: streamKey ?? runId, conversationId, replayOnly }}>+ <SandboxRunViewerContent taskId={taskId} runId={runId} replayOnly={replayOnly} className={className} />+ </BindLogic>+ )+}++function SandboxRunViewerContent({+ taskId,+ runId,+ replayOnly,+ className,+}: {+ taskId: string+ runId: string+ replayOnly: boolean+ className?: string+}): JSX.Element {+ const { bootstrapLoading, threadItems } = 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.+ // `replayOnly` 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 })+ }, [taskId, runId, replayOnly, bootstrapRun, reset])++ const showSpinner = bootstrapLoading && threadItems.length === 0++ return (+ <div+ className={cn(+ '@container/thread flex flex-col items-stretch w-full max-w-180 self-center gap-1.5 grow mx-auto',+ className+ )}+ >+ {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 />+ )}+ </div>+ )+}diff --git a/frontend/src/scenes/max/sandbox/components/SandboxThreadView.tsx b/frontend/src/scenes/max/sandbox/components/SandboxThreadView.tsxnew file mode 100644index 000000000000..44e225079dec--- /dev/null+++ b/frontend/src/scenes/max/sandbox/components/SandboxThreadView.tsx@@ -0,0 +1,218 @@+import { useValues } from 'kea'+import { useMemo } from 'react'++import { IconWrench } from '@posthog/icons'++import { TaskExecutionStatus as ExecutionStatus } from '~/queries/schema/schema-assistant-messages'++import { SandboxActivity } from '../../components/Activity'+import { MarkdownMessage } from '../../MarkdownMessage'+import type { SandboxToolCallMessage } from '../../maxTypes'+import { AssistantFailureMessage } from '../../messages/AssistantFailureMessage'+import { MessageTemplate } from '../../messages/MessageTemplate'+import { ReasoningAnswer } from '../../messages/ReasoningAnswer'+import { sandboxStreamLogic } from '../../sandboxStreamLogic'+import type { SandboxProgressStep, ThreadItem as SandboxThreadItem } from '../../types/sandboxStreamTypes'+import { getRandomThinkingMessage } from '../../utils/thinkingMessages'+import { SandboxPullRequestCard } from '../SandboxPullRequestCard'+import { SandboxRunContext } from '../SandboxRunContext'+import { SandboxCompactBoundaryItem, SandboxStatusItem, SandboxTaskNotificationItem } from '../SandboxThreadItems'+import { resolveToolCall } from '../sandboxToolResolver'+import { SandboxToolCall } from './tool/SandboxToolCall'++/** Maps a raw merged `ToolInvocation` into the flat `SandboxToolCallMessage` the registry renderers read. */+function toolInvocationToMessage(+ invocation: ReturnType<typeof sandboxStreamLogic.values.toolInvocations.get>+): SandboxToolCallMessage | null {+ if (!invocation) {+ return null+ }+ const resolved = resolveToolCall(invocation)+ return {+ id: invocation.toolCallId,+ resolvedKey: resolved.resolvedKey,+ rawServerName: invocation.rawServerName,+ rawToolName: invocation.rawToolName,+ innerToolName: resolved.innerToolName,+ claudeToolName: resolved.claudeToolName,+ rawInput: invocation.input,+ innerInput: resolved.innerInput,+ rawOutput: invocation.output,+ content: invocation.contentBlocks,+ status: invocation.status,+ title: invocation.title,+ kind: invocation.kind,+ locations: invocation.locations,+ error: invocation.error,+ }+}++/**+ * Sandbox-runtime thread presenter. Reads `sandboxStreamLogic.values.threadItems` (assistant text,+ * tool-invocation references, run separators, inline errors) from whatever `sandboxStreamLogic`+ * instance is bound above it — a live PostHog AI conversation or a read-only run viewer — and+ * dispatches tool cards through the sandbox tool registry. Conversation-agnostic by design: it knows+ * only the bound stream logic, never langgraph vs sandbox or the conversation.+ */+export function SandboxThreadView(): JSX.Element {+ // Drive the thinking indicator from real agent progress: show the latest `_posthog/progress`+ // message while the run is active, falling back to the canned rotation.+ const {+ threadItems,+ toolInvocations,+ currentProgress,+ isThinking,+ streamPhase,+ runArtifacts,+ turnComplete,+ currentRunStatus,+ } = useValues(sandboxStreamLogic)+ const turnCancelled = currentRunStatus === 'cancelled'+ const hasActiveProgressItem = threadItems.some(+ (item) => item.type === 'progress' && item.progressSteps?.some((step) => step.status === 'in_progress')+ )++ return (+ <>+ {runArtifacts.branch && (+ <SandboxRunContext+ branch={runArtifacts.branch}+ baseBranch={runArtifacts.baseBranch}+ repo={runArtifacts.repo}+ />+ )}+ {threadItems.map((item, index) => {+ if (item.type === 'human_message') {+ return (+ <MessageTemplate key={item.id} type="human">+ <MarkdownMessage content={item.text || '*No text.*'} id={item.id} />+ </MessageTemplate>+ )+ }+ if (item.type === 'assistant_message') {+ return (+ <MessageTemplate key={item.id} type="ai">+ <MarkdownMessage content={item.text ?? ''} id={item.id} />+ </MessageTemplate>+ )+ }+ if (item.type === 'assistant_thought') {+ // Empty chunks prime the stream before any reasoning text arrives — skip them so+ // a contentless "Thought" never shows; the bottom indicator covers that gap.+ if (!item.text?.trim()) {+ return null+ }+ // Collapse to "Thought" once a later block starts or the run stops thinking —+ // mirrors the LangGraph thread's reasoning-complete rule.+ const completed = index !== threadItems.length - 1 || !isThinking+ return (+ <ReasoningAnswer+ key={item.id}+ content={item.text}+ id={item.id}+ completed={completed}+ showCompletionIcon={false}+ />+ )+ }+ if (item.type === 'tool_invocation' && item.toolCallId) {+ const message = toolInvocationToMessage(toolInvocations.get(item.toolCallId))+ if (!message) {+ return null+ }+ return (+ <SandboxToolCall+ key={item.id}+ message={message}+ turnComplete={turnComplete}+ turnCancelled={turnCancelled}+ />+ )+ }+ if (item.type === 'error') {+ return <AssistantFailureMessage key={item.id} id={item.id} content={item.errorMessage} />+ }+ if (item.type === 'status') {+ return <SandboxStatusItem key={item.id} item={item} />+ }+ if (item.type === 'compact_boundary') {+ return <SandboxCompactBoundaryItem key={item.id} item={item} />+ }+ if (item.type === 'task_notification') {+ return <SandboxTaskNotificationItem key={item.id} item={item} />+ }+ if (item.type === 'progress') {+ return <SandboxProgressItem key={item.id} item={item} />+ }+ return null+ })}+ {streamPhase === 'thinking' && !hasActiveProgressItem && (+ <SandboxThinkingIndicator progress={currentProgress} />+ )}+ {/* Post-turn only: a reconnect refetch can fold in a pr_url mid-run, so gate on !isThinking. */}+ {!isThinking && runArtifacts.prUrl && (+ <SandboxPullRequestCard prUrl={runArtifacts.prUrl} branch={runArtifacts.branch} />+ )}+ </>+ )+}++function progressStepText(step: SandboxProgressStep): string {+ return step.detail ? `${step.label}\n\n${step.detail}` : step.label+}++function resolveSandboxProgressState(steps: SandboxProgressStep[]): ExecutionStatus {+ if (steps.some((step) => step.status === 'failed')) {+ return ExecutionStatus.Failed+ }+ if (steps.some((step) => step.status === 'in_progress')) {+ return ExecutionStatus.InProgress+ }+ if (steps.length > 0 && steps.every((step) => step.status === 'pending')) {+ return ExecutionStatus.Pending+ }+ return ExecutionStatus.Completed+}++function resolveSandboxProgressHeadline(steps: SandboxProgressStep[]): string {+ const active = steps.find((step) => step.status === 'in_progress')+ if (active) {+ return active.label+ }+ return steps.at(-1)?.label ?? 'Working'+}++function SandboxProgressItem({ item }: { item: SandboxThreadItem }): JSX.Element | null {+ const steps = item.progressSteps ?? []+ if (!steps.length) {+ return null+ }++ const headline = resolveSandboxProgressHeadline(steps)+ const substeps = steps.length > 1 ? steps.map(progressStepText) : []+ const state = resolveSandboxProgressState(steps)++ return (+ <SandboxActivity+ id={item.id}+ content={headline}+ substeps={substeps}+ state={state}+ icon={<IconWrench />}+ showCompletionIcon={true}+ />+ )+}++/**+ * Bottom-of-thread "what's it doing right now" line for sandbox conversations. Reflects the latest+ * `_posthog/progress` message when present, otherwise the canned thinking rotation.+ */+function SandboxThinkingIndicator({ progress }: { progress: string | null }): JSX.Element {+ // One roll per mount — re-rolling on every progress transition would visibly swap the verb.+ const fallbackMessage = useMemo(() => getRandomThinkingMessage(), [])+ const message = progress?.trim() ? progress : fallbackMessage+ // Match the LangGraph loader: a bubble-free reasoning line (muted brain icon + muted text),+ // static (no shimmer), via the shared Activity primitive — not a MessageTemplate bubble.+ return <ReasoningAnswer content={message} id="sandbox-thinking" completed={false} showCompletionIcon={false} />+}diff --git a/frontend/src/scenes/max/sandbox/components/tool/GenericMcpToolRenderer.tsx b/frontend/src/scenes/max/sandbox/components/tool/GenericMcpToolRenderer.tsxnew file mode 100644index 000000000000..a86a29357489--- /dev/null+++ b/frontend/src/scenes/max/sandbox/components/tool/GenericMcpToolRenderer.tsx@@ -0,0 +1,67 @@+import clsx from 'clsx'+import { memo } from 'react'++import { IconWrench } from '@posthog/icons'++import type { SandboxToolRendererProps } from '../../sandboxToolRegistry'+import { SandboxToolActivity } from './SandboxToolActivity'+import { compactInput, formatInput, getContentText, stripCodeFences } from './toolContentUtils'+import { ToolOutput } from './ToolOutput'++/**+ * The catch-all tool card — user-installed MCP tools, unmapped PostHog `exec` inner tools, and Claude+ * built-ins without a bespoke renderer. PostHog `exec` inner tools read `Call <tool>`; other MCP tools+ * read `Call <server> – <tool> (MCP)`; non-MCP built-ins show their friendly title. A compact input+ * preview sits on the second line and the body shows any text output. Replaces the old+ * `FallbackMcpToolRenderer`.+ */+export const GenericMcpToolRenderer = memo(function GenericMcpToolRenderer(+ props: SandboxToolRendererProps+): JSX.Element {+ const { message, icon, displayName, turnComplete, turnCancelled } = props++ const isPostHogExec = !!message.innerToolName+ const isMcp =+ isPostHogExec || (!!message.rawServerName && !!message.rawToolName && message.rawServerName !== 'claude')+ const serverName = isPostHogExec ? 'posthog' : message.rawServerName+ const toolLabel =+ message.innerToolName || message.rawToolName || message.claudeToolName || displayName || message.resolvedKey+ const inputForPreview = message.innerInput ?? message.rawInput+ const hasInput = !!inputForPreview && Object.keys(inputForPreview).length > 0+ const preview = hasInput ? compactInput(inputForPreview) : ''+ const output = stripCodeFences(getContentText(message.content))++ // Plain neutral title text, matching the built-in tool cards (e.g. "Read N lines"). A single text+ // node is also one flex item, so the header's `inline-flex` wrapper keeps the spaces intact.+ const title = isPostHogExec+ ? `Call ${toolLabel}`+ : isMcp+ ? `Call ${serverName} – ${toolLabel} (MCP)`+ : message.title || displayName || toolLabel++ // Subagent / MCP / unmapped tools show both the full input and the text output in the body.+ const formattedInput = hasInput ? formatInput(inputForPreview) : ''+ const body =+ formattedInput || output ? (+ <div className="flex flex-col gap-2 min-w-0">+ {formattedInput && <ToolOutput>{formattedInput}</ToolOutput>}+ {output && (+ <div className={clsx('min-w-0', formattedInput && 'border-t border-border-secondary pt-2')}>+ <ToolOutput>{output}</ToolOutput>+ </div>+ )}+ </div>+ ) : undefined++ return (+ <SandboxToolActivity+ message={message}+ icon={icon ?? <IconWrench />}+ title={title}+ subtitle={preview ? <span className="font-mono">{preview}</span> : undefined}+ body={body}+ turnComplete={turnComplete}+ turnCancelled={turnCancelled}+ />+ )+})diff --git a/frontend/src/scenes/max/sandbox/components/tool/SandboxDataToolRow.tsx b/frontend/src/scenes/max/sandbox/components/tool/SandboxDataToolRow.tsxnew file mode 100644index 000000000000..0ec21a811347--- /dev/null+++ b/frontend/src/scenes/max/sandbox/components/tool/SandboxDataToolRow.tsx@@ -0,0 +1,26 @@+import { type PropsWithChildren } from 'react'++import type { SandboxToolRendererProps } from '../../sandboxToolRegistry'+import { SandboxToolActivity } from './SandboxToolActivity'++/**+ * Shared shell for the data-tool adapters (insight, dashboard, recordings, query, error tracking,+ * notebook). Renders the registry icon + tool title as the header and the adapter's visualization as+ * always-visible content below it (via the Activity bridge), keeping data tools consistent with the+ * per-tool cards while each adapter keeps its own lazy chunk.+ */+export function SandboxDataToolRow({ children, ...props }: PropsWithChildren<SandboxToolRendererProps>): JSX.Element {+ const { message, icon, displayName, turnComplete, turnCancelled } = props++ return (+ <SandboxToolActivity+ message={message}+ icon={icon}+ title={message.title || displayName || 'Tool'}+ turnComplete={turnComplete}+ turnCancelled={turnCancelled}+ >+ {children}+ </SandboxToolActivity>+ )+}diff --git a/frontend/src/scenes/max/sandbox/components/tool/SandboxFilePath.tsx b/frontend/src/scenes/max/sandbox/components/tool/SandboxFilePath.tsxnew file mode 100644index 000000000000..b280219f3ba3--- /dev/null+++ b/frontend/src/scenes/max/sandbox/components/tool/SandboxFilePath.tsx@@ -0,0 +1,21 @@+import { IconDocument } from '@posthog/icons'++import { getFilename } from './toolContentUtils'++/**+ * Non-clickable file reference chip — a document icon, the bold filename, and a dimmed parent+ * directory that ellipsizes on overflow. There is no file-open panel in the sandbox UI, so unlike+ * the agent's own FileMentionChip this is purely informational.+ */+export function SandboxFilePath({ path }: { path: string }): JSX.Element {+ const filename = getFilename(path)+ const dir = path.slice(0, path.length - filename.length).replace(/\/+$/, '')++ return (+ <span className="inline-flex items-center gap-1 min-w-0 max-w-full font-mono text-xs">+ <IconDocument className="shrink-0 text-muted size-3.5" />+ <span className="font-medium text-secondary shrink-0">{filename}</span>+ {dir && <span className="text-muted truncate">{dir}</span>}+ </span>+ )+}diff --git a/frontend/src/scenes/max/sandbox/components/tool/SandboxToolActivity.test.tsx b/frontend/src/scenes/max/sandbox/components/tool/SandboxToolActivity.test.tsxnew file mode 100644index 000000000000..b062fa789569--- /dev/null+++ b/frontend/src/scenes/max/sandbox/components/tool/SandboxToolActivity.test.tsx@@ -0,0 +1,70 @@+import '@testing-library/jest-dom'++import { fireEvent, render, screen } from '@testing-library/react'++import type { SandboxToolCallMessage } from '../../../maxTypes'+import { SandboxToolActivity } from './SandboxToolActivity'++function makeMessage(overrides: Partial<SandboxToolCallMessage> = {}): SandboxToolCallMessage {+ return {+ id: 'tc-1',+ resolvedKey: 'Bash',+ rawServerName: 'claude',+ rawToolName: '',+ rawInput: {},+ content: [],+ status: 'completed',+ ...overrides,+ }+}++describe('SandboxToolActivity', () => {+ it('renders the title and subtitle (second line)', () => {+ render(<SandboxToolActivity message={makeMessage()} title="Terminal" subtitle="ls -la" />)+ expect(screen.getByText('Terminal')).toBeInTheDocument()+ expect(screen.getByText('ls -la')).toBeInTheDocument()+ })++ it('keeps the body collapsed once completed and expands on click', () => {+ render(<SandboxToolActivity message={makeMessage()} title="Terminal" body={<div>command output</div>} />)+ expect(screen.queryByText('command output')).not.toBeInTheDocument()+ fireEvent.click(screen.getByRole('button'))+ expect(screen.getByText('command output')).toBeInTheDocument()+ })++ it('auto-expands the body while the tool is running', () => {+ render(+ <SandboxToolActivity+ message={makeMessage({ status: 'in_progress' })}+ title="Terminal"+ body={<div>streaming…</div>}+ />+ )+ expect(screen.getByText('streaming…')).toBeInTheDocument()+ })++ it('renders children always-visible without expanding', () => {+ render(+ <SandboxToolActivity message={makeMessage()} title="Insight">+ <div>the visualization</div>+ </SandboxToolActivity>+ )+ expect(screen.getByText('the visualization')).toBeInTheDocument()+ })++ it('surfaces the failure message', () => {+ render(+ <SandboxToolActivity+ message={makeMessage({ status: 'failed', error: { message: 'boom' } })}+ title="Terminal"+ body={<div>partial</div>}+ />+ )+ expect(screen.getByText('boom')).toBeInTheDocument()+ })++ it('marks a turn-cancelled tool', () => {+ render(<SandboxToolActivity message={makeMessage({ status: 'in_progress' })} title="Terminal" turnCancelled />)+ expect(screen.getByText('(cancelled)')).toBeInTheDocument()+ })+})diff --git a/frontend/src/scenes/max/sandbox/components/tool/SandboxToolActivity.tsx b/frontend/src/scenes/max/sandbox/components/tool/SandboxToolActivity.tsxnew file mode 100644index 000000000000..74d57b9fdd47--- /dev/null+++ b/frontend/src/scenes/max/sandbox/components/tool/SandboxToolActivity.tsx@@ -0,0 +1,96 @@+import { type ReactNode } from 'react'++import { IconWarning, IconWrench } from '@posthog/icons'++import { Activity } from '../../../components/Activity'+import type { ActivityStatus } from '../../../components/Activity'+import type { SandboxToolCallMessage } from '../../../maxTypes'+import { resolveToolCallStatus } from './toolContentUtils'++export interface SandboxToolActivityProps {+ message: SandboxToolCallMessage+ /** Registry icon; defaults to the generic wrench. */+ icon?: ReactNode+ /** Header line 1. */+ title: ReactNode+ /** Header line 2 — the tool's salient input (command, path, url, …) where applicable. */+ subtitle?: ReactNode+ /** Collapsible body: streamed/expandable output (Bash output, file preview, diff, …). */+ body?: ReactNode+ /** Always-visible content below the header: data visualizations, the question recap, …. */+ children?: ReactNode+ /** Turn-level signals so a still-incomplete tool reads as loading vs cancelled vs idle. */+ turnComplete?: boolean+ turnCancelled?: boolean+}++/**+ * Bridges a sandbox tool call onto the shared `Activity` accordion: maps the tool's status to+ * Activity's status/icons, surfaces a failure line, and routes per-tool content to either the+ * collapsible body (`body` → Activity `details`, auto-expands while running) or the always-visible+ * region (`children`). Every sandbox tool card renders through this.+ */+export function SandboxToolActivity({+ message,+ icon,+ title,+ subtitle,+ body,+ children,+ turnComplete,+ turnCancelled,+}: SandboxToolActivityProps): JSX.Element {+ const { isLoading, isFailed, wasCancelled } = resolveToolCallStatus(message.status, !!turnCancelled, !!turnComplete)+ const status: ActivityStatus = isFailed ? 'failed' : isLoading ? 'in_progress' : 'completed'++ // Activity has no "cancelled" status — render it as a neutral terminal row (no check) with a marker+ // on the subtitle, or the title when there's no subtitle.+ const cancelledMarker = wasCancelled ? <span className="text-muted"> (cancelled)</span> : null+ const renderedTitle =+ !subtitle && cancelledMarker ? (+ <>+ {title}+ {cancelledMarker}+ </>+ ) : (+ title+ )+ const renderedSubtitle =+ subtitle && cancelledMarker ? (+ <>+ {subtitle}+ {cancelledMarker}+ </>+ ) : (+ subtitle+ )++ // The failure message lives in the always-visible region so it shows even though a failed tool's+ // details auto-collapse.+ const errorLine =+ isFailed && message.error?.message ? <div className="text-danger">{message.error.message}</div> : null+ const alwaysVisible = errorLine ? (+ <div className="flex flex-col gap-2">+ {errorLine}+ {children}+ </div>+ ) : (+ (children ?? null)+ )++ return (+ <Activity+ id={message.id}+ title={renderedTitle}+ subtitle={renderedSubtitle}+ status={status}+ icon={icon ?? <IconWrench />}+ showProgressIcon+ showCompletionIcon={!wasCancelled}+ failedIcon={<IconWarning className="text-danger size-3" />}+ details={body}+ >+ {alwaysVisible}+ </Activity>+ )+}diff --git a/frontend/src/scenes/max/sandbox/components/tool/SandboxToolCall.tsx b/frontend/src/scenes/max/sandbox/components/tool/SandboxToolCall.tsxnew file mode 100644index 000000000000..31f4a8add0c2--- /dev/null+++ b/frontend/src/scenes/max/sandbox/components/tool/SandboxToolCall.tsx@@ -0,0 +1,37 @@+import { Suspense, memo } from 'react'++import type { SandboxToolCallMessage } from '../../../maxTypes'+import { lookupSandboxToolRenderer } from '../../sandboxToolRegistry'+import { ToolCardSkeleton } from './ToolCardSkeleton'++export interface SandboxToolCallProps {+ message: SandboxToolCallMessage+ /** Turn-level signals for resolving a still-incomplete tool as loading vs cancelled vs idle. */+ turnComplete?: boolean+ turnCancelled?: boolean+}++/**+ * Eager dispatch for a single sandbox tool call: resolves the registry entry by `resolvedKey`, then+ * renders its (lazy) renderer inside a `Suspense` boundary that shows a `ToolCardSkeleton` while the+ * chunk loads. Replaces the inline `tool_invocation` branch in `SandboxThread`.+ */+export const SandboxToolCall = memo(function SandboxToolCall({+ message,+ turnComplete,+ turnCancelled,+}: SandboxToolCallProps): JSX.Element {+ const entry = lookupSandboxToolRenderer(message.resolvedKey)+ return (+ <Suspense fallback={<ToolCardSkeleton icon={entry.icon} displayName={entry.displayName} />}>+ <entry.Renderer+ message={message}+ isLastInGroup+ icon={entry.icon}+ displayName={entry.displayName}+ turnComplete={turnComplete}+ turnCancelled={turnCancelled}+ />+ </Suspense>+ )+})diff --git a/frontend/src/scenes/max/sandbox/components/tool/ToolCardSkeleton.tsx b/frontend/src/scenes/max/sandbox/components/tool/ToolCardSkeleton.tsxnew file mode 100644index 000000000000..ba1fcc815023--- /dev/null+++ b/frontend/src/scenes/max/sandbox/components/tool/ToolCardSkeleton.tsx@@ -0,0 +1,18 @@+import { Spinner } from '@posthog/lemon-ui'++/**+ * Eager, dependency-light placeholder shown while a tool renderer's lazy chunk loads. A single+ * Activity-style header line (registry icon + name + spinner, no body) — must not import the lazy+ * renderers, or it would defeat the code split it stands in for.+ */+export function ToolCardSkeleton({ icon, displayName }: { icon?: JSX.Element; displayName?: string }): JSX.Element {+ return (+ <div className="flex items-center select-none min-w-0 text-xs">+ <div className="flex items-center justify-center size-5 text-muted">{icon}</div>+ <div className="flex items-center gap-1 flex-1 min-w-0">+ <span className="text-muted truncate">{displayName ?? 'Tool'}</span>+ <Spinner className="size-3 shrink-0" />+ </div>+ </div>+ )+}diff --git a/frontend/src/scenes/max/sandbox/components/tool/ToolOutput.tsx b/frontend/src/scenes/max/sandbox/components/tool/ToolOutput.tsxnew file mode 100644index 000000000000..a0f2c4d44352--- /dev/null+++ b/frontend/src/scenes/max/sandbox/components/tool/ToolOutput.tsx@@ -0,0 +1,10 @@+import type { ReactNode } from 'react'++/** Monospace, scrollable output block for a tool card's collapsible body (terminal/search/fetch). */+export function ToolOutput({ children }: { children: ReactNode }): JSX.Element {+ return (+ <pre className="m-0 font-mono text-xs leading-relaxed text-secondary whitespace-pre-wrap break-all max-h-64 overflow-auto">+ {children}+ </pre>+ )+}diff --git a/frontend/src/scenes/max/sandbox/components/tool/builtinToolRenderers.test.tsx b/frontend/src/scenes/max/sandbox/components/tool/builtinToolRenderers.test.tsxnew file mode 100644index 000000000000..51f82410f3d2--- /dev/null+++ b/frontend/src/scenes/max/sandbox/components/tool/builtinToolRenderers.test.tsx@@ -0,0 +1,205 @@+import '@testing-library/jest-dom'++import { cleanup, fireEvent, render, screen } from '@testing-library/react'++import type { SandboxToolCallMessage } from '../../../maxTypes'+import { BuiltinToolRenderer } from './builtinToolRenderers'+import { GenericMcpToolRenderer } from './GenericMcpToolRenderer'++function textBlock(text: string): unknown {+ return { type: 'content', content: { type: 'text', text } }+}++function imageBlock(data: string, mimeType: string): unknown {+ return { type: 'content', content: { type: 'image', data, mimeType } }+}++function makeMessage(overrides: Partial<SandboxToolCallMessage> = {}): SandboxToolCallMessage {+ return {+ id: 'tc-1',+ resolvedKey: 'Bash',+ rawServerName: 'claude',+ rawToolName: '',+ rawInput: {},+ content: [],+ status: 'completed',+ ...overrides,+ }+}++describe('builtin tool renderers', () => {+ afterEach(() => cleanup())++ it('renders a Bash command in the header and its output on expand', () => {+ render(+ <BuiltinToolRenderer+ isLastInGroup+ message={makeMessage({+ claudeToolName: 'Bash',+ resolvedKey: 'Bash',+ rawInput: { command: 'pnpm build' },+ content: [textBlock('build succeeded')],+ })}+ />+ )+ expect(screen.getByText('pnpm build')).toBeInTheDocument()+ fireEvent.click(screen.getByRole('button'))+ expect(screen.getByText('build succeeded')).toBeInTheDocument()+ })++ it('summarizes a Read call with its line count and file chip', () => {+ render(+ <BuiltinToolRenderer+ isLastInGroup+ message={makeMessage({+ claudeToolName: 'Read',+ resolvedKey: 'Read',+ locations: [{ path: 'frontend/app.ts' }],+ content: [textBlock('const a = 1\nconst b = 2')],+ })}+ />+ )+ expect(screen.getByText('Read 2 lines')).toBeInTheDocument()+ expect(screen.getByText('app.ts')).toBeInTheDocument()+ })++ it('previews a Read image', () => {+ render(+ <BuiltinToolRenderer+ isLastInGroup+ message={makeMessage({+ claudeToolName: 'Read',+ resolvedKey: 'Read',+ locations: [{ path: 'shot.png' }],+ content: [imageBlock('AAAA', 'image/png')],+ })}+ />+ )+ expect(screen.getByText('Read image')).toBeInTheDocument()+ fireEvent.click(screen.getByRole('button'))+ expect(screen.getByAltText('shot.png')).toBeInTheDocument()+ })++ it('counts search results in the header', () => {+ render(+ <BuiltinToolRenderer+ isLastInGroup+ message={makeMessage({+ claudeToolName: 'Grep',+ resolvedKey: 'Grep',+ title: 'Grep TODO',+ content: [textBlock('a.ts:1\nb.ts:4\nc.ts:9')],+ })}+ />+ )+ expect(screen.getByText('Grep TODO')).toBeInTheDocument()+ expect(screen.getByText('3 results')).toBeInTheDocument()+ })++ it('titles a subagent "type: description" and shows its prompt + output on expand', () => {+ render(+ <BuiltinToolRenderer+ isLastInGroup+ message={makeMessage({+ claudeToolName: 'Task',+ resolvedKey: 'Task',+ title: 'Review the diff',+ rawInput: {+ subagent_type: 'code-reviewer',+ description: 'Review the diff',+ prompt: 'Please review the recent changes',+ },+ content: [textBlock('Looks good to me')],+ })}+ />+ )+ expect(screen.getByText('code-reviewer: Review the diff')).toBeInTheDocument()+ fireEvent.click(screen.getByRole('button'))+ expect(screen.getByText('Please review the recent changes')).toBeInTheDocument()+ expect(screen.getByText('Looks good to me')).toBeInTheDocument()+ })++ it('does not duplicate an echo subagent whose output repeats the prompt', () => {+ render(+ <BuiltinToolRenderer+ isLastInGroup+ message={makeMessage({+ claudeToolName: 'Task',+ resolvedKey: 'Task',+ rawInput: { subagent_type: 'echo', description: 'echo it', prompt: 'ping' },+ content: [textBlock('ping')],+ })}+ />+ )+ fireEvent.click(screen.getByRole('button'))+ expect(screen.getAllByText('ping')).toHaveLength(1)+ })++ it.each([+ ['tools', 'List tools', '__posthog_exec_tools__'],+ ['info execute-sql', 'Read execute-sql', '__posthog_exec_info__'],+ ['schema insight-create field', 'Inspect insight-create.field', '__posthog_exec_schema__'],+ ['bogus', 'Run command', '__posthog_exec_unknown__'],+ ])('labels the PostHog exec verb "%s" as "%s"', (command, label, resolvedKey) => {+ render(+ <BuiltinToolRenderer+ isLastInGroup+ message={makeMessage({+ resolvedKey,+ rawServerName: 'posthog',+ rawToolName: 'exec',+ rawInput: { command },+ })}+ />+ )+ expect(screen.getByText(label)).toBeInTheDocument()+ })++ it('shows the search regex as the PostHog exec subtitle', () => {+ render(+ <BuiltinToolRenderer+ isLastInGroup+ message={makeMessage({+ resolvedKey: '__posthog_exec_search__',+ rawServerName: 'posthog',+ rawToolName: 'exec',+ rawInput: { command: 'search funnel' },+ })}+ />+ )+ expect(screen.getByText('Search tools')).toBeInTheDocument()+ expect(screen.getByText('funnel')).toBeInTheDocument()+ })++ it('renders an unmapped MCP tool with a Call server – tool (MCP) header', () => {+ render(+ <GenericMcpToolRenderer+ isLastInGroup+ message={makeMessage({+ resolvedKey: 'do_thing',+ rawServerName: 'user-mcp',+ rawToolName: 'do_thing',+ rawInput: { foo: 'bar' },+ })}+ />+ )+ expect(screen.getByText('Call user-mcp – do_thing (MCP)')).toBeInTheDocument()+ })++ it('renders an unmapped PostHog exec inner tool as "Call <tool>" without the MCP suffix', () => {+ render(+ <GenericMcpToolRenderer+ isLastInGroup+ message={makeMessage({+ resolvedKey: 'read-data-schema',+ rawServerName: 'posthog',+ rawToolName: 'exec',+ innerToolName: 'read-data-schema',+ rawInput: { command: 'call read-data-schema' },+ })}+ />+ )+ expect(screen.getByText('Call read-data-schema')).toBeInTheDocument()+ expect(screen.queryByText(/\(MCP\)/)).not.toBeInTheDocument()+ })+})diff --git a/frontend/src/scenes/max/sandbox/components/tool/builtinToolRenderers.tsx b/frontend/src/scenes/max/sandbox/components/tool/builtinToolRenderers.tsxnew file mode 100644index 000000000000..b793e311b435--- /dev/null+++ b/frontend/src/scenes/max/sandbox/components/tool/builtinToolRenderers.tsx@@ -0,0 +1,262 @@+import clsx from 'clsx'+import { memo } from 'react'++import { IconDocument, IconGlobe, IconSearch, IconTerminal, IconWrench } from '@posthog/icons'++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 { languageFromPath } from '../../../toolDiffContent'+import { getPostHogExecDisplay } from '../../posthogExecDisplay'+import type { SandboxToolRendererProps } from '../../sandboxToolRegistry'+import { GenericMcpToolRenderer } from './GenericMcpToolRenderer'+import { SandboxFilePath } from './SandboxFilePath'+import { SandboxToolActivity } from './SandboxToolActivity'+import {+ MAX_COMMAND_LENGTH,+ MAX_URL_LENGTH,+ getCommandOutput,+ getContentImage,+ getContentText,+ getFilename,+ getLineCount,+ getReadToolContent,+ getResultCount,+ stripAnsi,+ stripCodeFences,+ truncateText,+} from './toolContentUtils'+import { ToolOutput } from './ToolOutput'++function asString(value: unknown): string {+ return typeof value === 'string' ? value : ''+}++function firstLocationPath(props: SandboxToolRendererProps): string | undefined {+ return props.message.locations?.[0]?.path ?? (asString(props.message.rawInput.file_path) || undefined)+}++/** Bash / BashOutput / KillShell — command on the second line, ANSI-stripped output in the body. */+const BashToolRenderer = memo(function BashToolRenderer(props: SandboxToolRendererProps): JSX.Element {+ const { message, icon, turnComplete, turnCancelled } = props+ const command = asString(message.rawInput.command)+ const description = asString(message.rawInput.description)+ const output = stripAnsi(stripCodeFences(getCommandOutput(message.content, command, message.rawOutput)))++ return (+ <SandboxToolActivity+ message={message}+ icon={icon ?? <IconTerminal />}+ title={description || message.title || 'Terminal'}+ subtitle={+ command ? (+ <span className="font-mono" title={command}>+ {command}+ </span>+ ) : undefined+ }+ body={output ? <ToolOutput>{output}</ToolOutput> : undefined}+ turnComplete={turnComplete}+ turnCancelled={turnCancelled}+ />+ )+})++/** Read / NotebookRead — line/image summary on line 1, file chip on line 2, preview in the body. */+const ReadToolRenderer = memo(function ReadToolRenderer(props: SandboxToolRendererProps): JSX.Element {+ const { message, icon, turnComplete, turnCancelled } = props+ const path = firstLocationPath(props)+ const image = getContentImage(message.content)+ const text = image ? '' : getReadToolContent(message.content)+ const lineCount = getLineCount(text)++ const title = image+ ? 'Read image'+ : lineCount > 0+ ? `Read ${lineCount} ${lineCount === 1 ? 'line' : 'lines'}`+ : 'Read'++ let body: JSX.Element | undefined+ if (image) {+ body = (+ <img+ src={`data:${image.mimeType};base64,${image.base64}`}+ alt={path ? getFilename(path) : 'Read image'}+ className="max-h-96 max-w-full object-contain rounded bg-surface-secondary p-2"+ />+ )+ } else if (text) {+ body = (+ <CodeSnippet language={languageFromPath(path)} compact maxLinesWithoutExpansion={20}>+ {text}+ </CodeSnippet>+ )+ }++ return (+ <SandboxToolActivity+ message={message}+ icon={icon ?? <IconDocument />}+ title={title}+ subtitle={path ? <SandboxFilePath path={path} /> : undefined}+ body={body}+ turnComplete={turnComplete}+ turnCancelled={turnCancelled}+ />+ )+})++/** Grep / Glob / LS — result count on line 2, matched lines in the body. */+const SearchToolRenderer = memo(function SearchToolRenderer(props: SandboxToolRendererProps): JSX.Element {+ const { message, icon, displayName, turnComplete, turnCancelled } = props+ const output = getContentText(message.content)+ const count = getResultCount(output)++ return (+ <SandboxToolActivity+ message={message}+ icon={icon ?? <IconSearch />}+ title={message.title || displayName || 'Search'}+ subtitle={output ? `${count} ${count === 1 ? 'result' : 'results'}` : undefined}+ body={output ? <ToolOutput>{output}</ToolOutput> : undefined}+ turnComplete={turnComplete}+ turnCancelled={turnCancelled}+ />+ )+})++/**+ * Task / Agent — a delegated subagent run. The header reads `{subagent_type}: {description}`, and the+ * body carries the prompt the subagent was handed plus its returned output. The description lives only+ * in the title (not echoed as a subtitle or input dump), so the card no longer duplicates it.+ */+const SubagentToolRenderer = memo(function SubagentToolRenderer(props: SandboxToolRendererProps): JSX.Element {+ const { message, icon, turnComplete, turnCancelled } = props+ const subagentType = asString(message.rawInput.subagent_type)+ const description = asString(message.rawInput.description) || message.title || ''+ const prompt = asString(message.rawInput.prompt)+ const output = stripCodeFences(getContentText(message.content))+ // An echo-style subagent returns its prompt verbatim — don't render the same text twice.+ const showOutput = !!output && output.trim() !== prompt.trim()++ const title =+ subagentType && description ? `${subagentType}: ${description}` : subagentType || description || 'Subagent'++ const body =+ prompt || showOutput ? (+ <div className="flex flex-col gap-2 min-w-0">+ {prompt && <ToolOutput>{prompt}</ToolOutput>}+ {showOutput && (+ <div className={clsx('min-w-0', prompt && 'border-t border-border-secondary pt-2')}>+ <ToolOutput>{output}</ToolOutput>+ </div>+ )}+ </div>+ ) : undefined++ return (+ <SandboxToolActivity+ message={message}+ icon={icon ?? <IconRobot />}+ title={title}+ body={body}+ turnComplete={turnComplete}+ turnCancelled={turnCancelled}+ />+ )+})++/** WebFetch / WebSearch — linked URL (or query) on line 2, fetched content in the body. */+const FetchToolRenderer = memo(function FetchToolRenderer(props: SandboxToolRendererProps): JSX.Element {+ const { message, icon, turnComplete, turnCancelled } = props+ const url = asString(message.rawInput.url)+ const query = asString(message.rawInput.query)+ const output = stripCodeFences(getContentText(message.content))+ const isSearch = !url && !!query+ // Render the URL as plain mono text — not a highlighted, openable link.+ const target = url || query++ return (+ <SandboxToolActivity+ message={message}+ icon={icon ?? <IconGlobe />}+ title={message.title || (isSearch ? 'Web search' : 'Fetched')}+ subtitle={+ target ? (+ <span className="font-mono" title={target}>+ {truncateText(target, MAX_URL_LENGTH)}+ </span>+ ) : undefined+ }+ body={output ? <ToolOutput>{output}</ToolOutput> : undefined}+ turnComplete={turnComplete}+ turnCancelled={turnCancelled}+ />+ )+})++/**+ * PostHog single-exec discovery verbs (`tools` / `search` / `info` / `schema`, plus the `unknown`+ * fallback). `getPostHogExecDisplay` turns the `command` into a friendly label ("List tools",+ * "Search tools", "Read <tool>", "Inspect <tool>.<field>") and an optional input preview; the+ * discovery output renders in the body. The `call` verb never reaches here — it resolves to its inner+ * tool's renderer instead.+ */+const PostHogExecRenderer = memo(function PostHogExecRenderer(props: SandboxToolRendererProps): JSX.Element {+ const { message, icon, turnComplete, turnCancelled } = props+ const display = getPostHogExecDisplay(message.rawInput)+ const input = display?.input+ const output = stripCodeFences(getContentText(message.content))++ return (+ <SandboxToolActivity+ message={message}+ icon={icon ?? <IconWrench />}+ title={display?.label || message.title || 'Run command'}+ subtitle={+ input ? (+ <span className="font-mono" title={input}>+ {truncateText(input, MAX_COMMAND_LENGTH)}+ </span>+ ) : undefined+ }+ body={output ? <ToolOutput>{output}</ToolOutput> : undefined}+ turnComplete={turnComplete}+ turnCancelled={turnCancelled}+ />+ )+})++/**+ * Single lazy entry covering every Claude built-in plus the generic MCP fallback — mirrors the agent+ * UI's `ToolCallBlock` dispatch. Switches on the resolved tool name; anything unrecognised renders+ * through `GenericMcpToolRenderer`. Registered for each built-in key and as the registry's default.+ */+export const BuiltinToolRenderer = memo(function BuiltinToolRenderer(props: SandboxToolRendererProps): JSX.Element {+ if (props.message.resolvedKey.startsWith('__posthog_exec_')) {+ return <PostHogExecRenderer {...props} />+ }+ const name = props.message.claudeToolName ?? props.message.resolvedKey+ switch (name) {+ case 'Bash':+ case 'BashOutput':+ case 'KillShell':+ return <BashToolRenderer {...props} />+ case 'Read':+ case 'NotebookRead':+ return <ReadToolRenderer {...props} />+ case 'Grep':+ case 'Glob':+ case 'LS':+ return <SearchToolRenderer {...props} />+ case 'Task':+ case 'Agent':+ return <SubagentToolRenderer {...props} />+ case 'WebFetch':+ case 'WebSearch':+ return <FetchToolRenderer {...props} />+ default:+ return <GenericMcpToolRenderer {...props} />+ }+})diff --git a/frontend/src/scenes/max/sandbox/components/tool/toolContentUtils.test.ts b/frontend/src/scenes/max/sandbox/components/tool/toolContentUtils.test.tsnew file mode 100644index 000000000000..aae22ea7d321--- /dev/null+++ b/frontend/src/scenes/max/sandbox/components/tool/toolContentUtils.test.ts@@ -0,0 +1,167 @@+import {+ compactInput,+ findResourceLink,+ formatInput,+ getCommandOutput,+ getContentImage,+ getContentText,+ getFilename,+ getLineCount,+ getReadToolContent,+ getResultCount,+ resolveToolCallStatus,+ stripAnsi,+ stripCodeFences,+ truncateText,+} from './toolContentUtils'++describe('toolContentUtils', () => {+ describe('resolveToolCallStatus', () => {+ it('treats an in-progress tool as loading while the turn is live', () => {+ expect(resolveToolCallStatus('in_progress', false, false)).toEqual({+ isLoading: true,+ wasCancelled: false,+ isFailed: false,+ isComplete: false,+ })+ })++ it('treats an incomplete tool as cancelled once the turn was cancelled', () => {+ const flags = resolveToolCallStatus('pending', true, false)+ expect(flags.wasCancelled).toBe(true)+ expect(flags.isLoading).toBe(false)+ })++ it('stops spinning a still-incomplete tool once the turn completes', () => {+ const flags = resolveToolCallStatus('in_progress', false, true)+ expect(flags.isLoading).toBe(false)+ expect(flags.wasCancelled).toBe(false)+ })++ it('maps terminal statuses directly', () => {+ expect(resolveToolCallStatus('failed', false, false).isFailed).toBe(true)+ expect(resolveToolCallStatus('completed', false, false).isComplete).toBe(true)+ })+ })++ describe('getContentText', () => {+ it('unwraps the ACP content envelope', () => {+ expect(getContentText([{ type: 'content', content: { type: 'text', text: 'hi' } }])).toBe('hi')+ })++ it('reads a flat text block and returns the first one', () => {+ expect(+ getContentText([+ { type: 'text', text: 'first' },+ { type: 'text', text: 'second' },+ ])+ ).toBe('first')+ })++ it('returns empty string when no text block is present', () => {+ expect(+ getContentText([{ type: 'content', content: { type: 'image', data: 'x', mimeType: 'image/png' } }])+ ).toBe('')+ })+ })++ describe('getCommandOutput', () => {+ it('drops a leading content block that echoes the command', () => {+ const content = [+ { type: 'text', text: 'ls -la' },+ { type: 'text', text: 'total 8\nfile.ts' },+ ]+ expect(getCommandOutput(content, 'ls -la', undefined)).toBe('total 8\nfile.ts')+ })++ it('strips a "command\\noutput" prefix from a single block', () => {+ expect(getCommandOutput([{ type: 'text', text: 'pwd\n/home/user' }], 'pwd', undefined)).toBe('/home/user')+ })++ it('returns plain output unchanged when it does not echo the command', () => {+ expect(getCommandOutput([{ type: 'text', text: 'build succeeded' }], 'pnpm build', undefined)).toBe(+ 'build succeeded'+ )+ })++ it('falls back to a string rawOutput when the command produced no content', () => {+ expect(getCommandOutput([{ type: 'text', text: 'echo hi' }], 'echo hi', 'hi')).toBe('hi')+ })+ })++ describe('getReadToolContent', () => {+ it('strips system reminders, code fences, and line-number gutters', () => {+ const raw =+ '```python\n 1→import os\n 2→print(os.getcwd())\n```\n<system-reminder>be careful</system-reminder>'+ expect(getReadToolContent([{ type: 'text', text: raw }])).toBe('import os\nprint(os.getcwd())')+ })+ })++ describe('getContentImage', () => {+ it('returns the base64 + mime of the first image block', () => {+ expect(+ getContentImage([{ type: 'content', content: { type: 'image', data: 'AAAA', mimeType: 'image/png' } }])+ ).toEqual({ base64: 'AAAA', mimeType: 'image/png' })+ })++ it('returns null when there is no image block', () => {+ expect(getContentImage([{ type: 'text', text: 'no image' }])).toBeNull()+ })+ })++ describe('findResourceLink', () => {+ it('returns the first resource_link block', () => {+ expect(+ findResourceLink([{ type: 'resource_link', uri: 'https://x.com', name: 'X', description: 'a site' }])+ ).toEqual({ uri: 'https://x.com', name: 'X', description: 'a site' })+ })+ })++ describe('stripAnsi', () => {+ it('removes SGR colour codes', () => {+ expect(stripAnsi('[31mred[0m text')).toBe('red text')+ })+ })++ describe('stripCodeFences', () => {+ it('removes leading and trailing fences', () => {+ expect(stripCodeFences('```ts\nconst a = 1\n```')).toBe('const a = 1')+ })++ it('leaves unfenced text untouched', () => {+ expect(stripCodeFences('plain text')).toBe('plain text')+ })+ })++ describe('counts and truncation', () => {+ it('counts non-empty result lines', () => {+ expect(getResultCount('a.ts\n\nb.ts\nc.ts\n')).toBe(3)+ })++ it('counts total lines, treating blank text as zero', () => {+ expect(getLineCount('one\ntwo')).toBe(2)+ expect(getLineCount(' ')).toBe(0)+ })++ it('truncates with an ellipsis only when over the limit', () => {+ expect(truncateText('short', 10)).toBe('short')+ expect(truncateText('abcdef', 3)).toBe('abc…')+ })++ it('extracts the basename', () => {+ expect(getFilename('a/b/c.ts')).toBe('c.ts')+ expect(getFilename('flat.ts')).toBe('flat.ts')+ })+ })++ describe('input previews', () => {+ it('compacts input JSON to a single truncated line', () => {+ expect(compactInput({ a: 1 })).toBe('{"a":1}')+ expect(compactInput({ key: 'a-very-long-value-that-keeps-going-and-going-and-going' }, 10)).toHaveLength(11)+ })++ it('pretty-prints input JSON', () => {+ expect(formatInput({ a: 1 })).toBe('{\n "a": 1\n}')+ })+ })+})diff --git a/frontend/src/scenes/max/sandbox/components/tool/toolContentUtils.ts b/frontend/src/scenes/max/sandbox/components/tool/toolContentUtils.tsnew file mode 100644index 000000000000..459a7709560d--- /dev/null+++ b/frontend/src/scenes/max/sandbox/components/tool/toolContentUtils.ts@@ -0,0 +1,204 @@+import type { SandboxToolCallMessage } from '../../../maxTypes'++/** Compact single-line preview length for a generic MCP tool's input JSON. */+export const INPUT_PREVIEW_MAX_LENGTH = 60+/** Max characters of a Bash command rendered inline before truncation. */+export const MAX_COMMAND_LENGTH = 120+/** Max characters of a fetched URL rendered inline before truncation. */+export const MAX_URL_LENGTH = 60++export interface ToolCallStatusFlags {+ isLoading: boolean+ isFailed: boolean+ wasCancelled: boolean+ isComplete: boolean+}++/**+ * Resolves the four visual states a tool card can be in from its wire status plus the turn-level+ * signals. A tool left `pending`/`in_progress` is *loading* while the turn is live, but *cancelled*+ * once the turn was cancelled, and simply idle once the turn completed without it finishing. Pure —+ * not a hook despite reading like one, so it is safe to call conditionally.+ */+export function resolveToolCallStatus(+ status: SandboxToolCallMessage['status'],+ turnCancelled: boolean,+ turnComplete: boolean+): ToolCallStatusFlags {+ const incomplete = status === 'pending' || status === 'in_progress'+ return {+ isLoading: incomplete && !turnCancelled && !turnComplete,+ wasCancelled: incomplete && turnCancelled,+ isFailed: status === 'failed',+ isComplete: status === 'completed',+ }+}++/** Unwraps the ACP `{ type: 'content', content: {...} }` envelope; flat blocks pass through. */+function unwrapBlock(block: unknown): unknown {+ if (!block || typeof block !== 'object') {+ return block+ }+ if ((block as { type?: unknown }).type === 'content' && 'content' in block) {+ return (block as { content: unknown }).content+ }+ return block+}++/** Text of every text content block (ACP-nested or flat), in order. */+export function getAllText(content: unknown[]): string[] {+ const texts: string[] = []+ for (const block of content) {+ const inner = unwrapBlock(block)+ if (inner && typeof inner === 'object' && (inner as { type?: unknown }).type === 'text') {+ const text = (inner as { text?: unknown }).text+ if (typeof text === 'string') {+ texts.push(text)+ }+ }+ }+ return texts+}++/** Text of the first text content block (ACP-nested or flat), or '' when none carries text. */+export function getContentText(content: unknown[]): string {+ return getAllText(content)[0] ?? ''+}++/**+ * Output of a Bash-style command. The agent prepends the executed command as its own content block+ * (or a `command\n…` prefix), so drop a leading line that echoes the command — leaving just stdout.+ * Falls back to a string `rawOutput` when the command produced no content blocks.+ */+export function getCommandOutput(content: unknown[], command: string, rawOutput: unknown): string {+ const blocks = getAllText(content)+ const cmd = command.trim()+ const trimmed = cmd && blocks[0]?.trim() === cmd ? blocks.slice(1) : blocks+ let output = trimmed.join('\n')+ if (cmd && output.trimStart().startsWith(cmd)) {+ output = output.trimStart().slice(cmd.length).replace(/^\n+/, '')+ }+ if (!output.trim() && typeof rawOutput === 'string') {+ output = rawOutput+ }+ return output+}++export interface ToolImageContent {+ base64: string+ mimeType: string+}++/** First image content block decoded to its base64 + mime type, or null when none is present. */+export function getContentImage(content: unknown[]): ToolImageContent | null {+ for (const block of content) {+ const inner = unwrapBlock(block)+ if (inner && typeof inner === 'object' && (inner as { type?: unknown }).type === 'image') {+ const { data, mimeType } = inner as { data?: unknown; mimeType?: unknown }+ if (typeof data === 'string' && typeof mimeType === 'string') {+ return { base64: data, mimeType }+ }+ }+ }+ return null+}++export interface ToolResourceLink {+ uri: string+ name?: string+ description?: string+}++/** First `resource_link` content block (a fetched/linked resource), or null. */+export function findResourceLink(content: unknown[]): ToolResourceLink | null {+ for (const block of content) {+ const inner = unwrapBlock(block)+ if (inner && typeof inner === 'object' && (inner as { type?: unknown }).type === 'resource_link') {+ const { uri, name, description } = inner as { uri?: unknown; name?: unknown; description?: unknown }+ if (typeof uri === 'string') {+ return {+ uri,+ name: typeof name === 'string' ? name : undefined,+ description: typeof description === 'string' ? description : undefined,+ }+ }+ }+ }+ return null+}++/** Strips a leading ```lang fence and a trailing ``` fence from a fenced code block. */+export function stripCodeFences(text: string): string {+ return text+ .trim()+ .replace(/^```[^\n]*\n?/, '')+ .replace(/\n?```$/, '')+ .trim()+}++// eslint-disable-next-line no-control-regex+const ANSI_ESCAPE_RE = /\x1b\[[0-9;]*m/g++/** Removes ANSI SGR colour codes from terminal output so it reads cleanly in a card. */+export function stripAnsi(text: string): string {+ return text.replace(ANSI_ESCAPE_RE, '')+}++const SYSTEM_REMINDER_RE = /<system-reminder>[\s\S]*?<\/system-reminder>/g+// `cat -n`-style gutter the Read tool prepends to each line: optional indent, line number, U+2192 arrow.+const READ_LINE_MARKER_RE = /^\s*\d+→/gm++/**+ * Cleans the Read tool's output for display: drops injected `<system-reminder>` blocks, the code+ * fences the agent wraps file contents in, and the per-line `NNN→` gutter — leaving the raw file text.+ */+export function getReadToolContent(content: unknown[]): string {+ return stripCodeFences(getContentText(content).replace(SYSTEM_REMINDER_RE, ''))+ .replace(READ_LINE_MARKER_RE, '')+ .trim()+}++/** Basename of a path (everything after the last slash). */+export function getFilename(path: string): string {+ const segments = path.split('/')+ return segments[segments.length - 1] || path+}++/** Number of lines in a block of text; empty/whitespace-only text counts as zero. */+export function getLineCount(text: string): number {+ if (!text.trim()) {+ return 0+ }+ return text.split('\n').length+}++/** Number of non-empty lines — the search-result count for Grep/Glob/LS output. */+export function getResultCount(text: string): number {+ return text.split('\n').filter((line) => line.trim().length > 0).length+}++/** Truncates `text` to `max` characters, appending an ellipsis when it overflows. */+export function truncateText(text: string, max: number, suffix = '…'): string {+ if (text.length <= max) {+ return text+ }+ return text.slice(0, max) + suffix+}++/** Pretty-prints a tool input object as indented JSON for the expanded body. */+export function formatInput(input: unknown): string {+ try {+ return JSON.stringify(input, null, 2)+ } catch {+ return String(input)+ }+}++/** Single-line, truncated JSON preview of a tool input — the generic MCP card's header hint. */+export function compactInput(input: unknown, max = INPUT_PREVIEW_MAX_LENGTH): string {+ try {+ return truncateText(JSON.stringify(input) ?? '', max)+ } catch {+ return ''+ }+}diff --git a/frontend/src/scenes/max/sandbox/posthogExecDisplay.ts b/frontend/src/scenes/max/sandbox/posthogExecDisplay.tsnew file mode 100644index 000000000000..90fa8b7733c5--- /dev/null+++ b/frontend/src/scenes/max/sandbox/posthogExecDisplay.ts@@ -0,0 +1,173 @@+/**+ * Shared display helpers for the PostHog single-exec MCP tool. The `posthog` MCP server exposes one+ * outer `exec` tool whose `command` string carries the real intent (`tools` / `search` / `info` /+ * `schema` / `call <sub-tool>`). Both the thread tool-card renderer and the permission card need the+ * same human-friendly label + input preview, so the parsing lives here — one source of truth.+ */++/** Matches the PostHog single-exec MCP tool (`mcp__posthog__exec`, plus plugin/regional variants). */+export const POSTHOG_EXEC_TOOL_RE = /^mcp__(?:plugin_)?posthog(?:_[^_]+)*__exec$/++export function isPostHogExecTool(toolName: string): boolean {+ return POSTHOG_EXEC_TOOL_RE.test(toolName)+}++/** The verbs the single-exec tool accepts. `call` runs a sub-tool; the rest are read-only. */+export type PostHogExecVerb = 'tools' | 'search' | 'info' | 'schema' | 'call'+const POSTHOG_EXEC_VERBS = new Set<PostHogExecVerb>(['tools', 'search', 'info', 'schema', 'call'])++/**+ * Splits the leading whitespace-delimited token off a command and returns it plus the trimmed+ * remainder. Mirrors the backend exec `parseCommand` (`services/mcp/src/tools/exec.ts`)+ * token-for-token — single-space split, trimmed remainder — so the client tokenizes a command+ * exactly the way the server that runs it does. This is a security boundary: any divergence lets a+ * crafted command resolve to a different (safer-looking) inner tool here than the backend executes.+ */+export function splitFirstToken(input: string): { head: string; rest: string } {+ const trimmed = input.trim()+ const idx = trimmed.indexOf(' ')+ if (idx === -1) {+ return { head: trimmed, rest: '' }+ }+ return { head: trimmed.slice(0, idx), rest: trimmed.slice(idx + 1).trim() }+}++/**+ * Parses an exec `command` into its verb and remainder. `verb` is null when the leading token isn't+ * a recognized verb (the backend rejects such a command as `Unknown command`).+ */+export function parseExecCommand(command: string): { verb: PostHogExecVerb | null; rest: string } {+ const { head, rest } = splitFirstToken(command)+ return POSTHOG_EXEC_VERBS.has(head as PostHogExecVerb)+ ? { verb: head as PostHogExecVerb, rest }+ : { verb: null, rest }+}++/**+ * Parses the body of a `call` command (everything after the `call` verb) into its inner sub-tool,+ * its remaining args, and the boolean flags. Strips leading `--json` / `--confirm` flags in any+ * order, mirroring the backend `parseCallFlags`, then takes the next token as the sub-tool.+ * `subTool` is null when no sub-tool remains, or when the next token still looks like a flag — a real+ * sub-tool name never starts with `-`. The permission gate keys destructive-tool detection off+ * `subTool`, so this MUST match the server's flag grammar: what the server strips, we strip; what it+ * can't resolve, we fail closed on.+ */+export function parseExecCall(callBody: string): {+ subTool: string | null+ args: string+ forceJson: boolean+ confirmed: boolean+} {+ let rest = callBody.trim()+ let forceJson = false+ let confirmed = false+ while (rest) {+ const { head, rest: next } = splitFirstToken(rest)+ if (head === '--json') {+ forceJson = true+ rest = next+ continue+ }+ if (head === '--confirm') {+ confirmed = true+ rest = next+ continue+ }+ break+ }+ const { head: subTool, rest: args } = splitFirstToken(rest)+ if (!subTool || subTool.startsWith('-')) {+ return { subTool: null, args, forceJson, confirmed }+ }+ return { subTool, args, forceJson, confirmed }+}++export interface PostHogExecDisplay {+ label: string+ input?: string+}++function readExplicitInput(value: unknown): string | undefined {+ if (value === undefined || value === null) {+ return undefined+ }+ if (typeof value === 'string') {+ return value.trim() || undefined+ }+ try {+ return JSON.stringify(value)+ } catch {+ return undefined+ }+}++/**+ * Unwraps an `exec` invocation's `command` (and optional explicit `input`) into a friendly label and+ * input preview. Returns null when the payload isn't a recognizable `exec` command, so callers can+ * fall back to generic rendering.+ */+export function getPostHogExecDisplay(toolInput: unknown): PostHogExecDisplay | null {+ if (!toolInput || typeof toolInput !== 'object') {+ return null+ }+ const obj = toolInput as { command?: unknown; input?: unknown }+ if (typeof obj.command !== 'string') {+ return null+ }++ const { verb, rest } = parseExecCommand(obj.command)+ if (!verb) {+ return null+ }+ const explicitInput = readExplicitInput(obj.input)++ switch (verb) {+ case 'tools':+ return { label: 'List tools', input: undefined }+ case 'search':+ return {+ label: 'Search tools',+ input: explicitInput ?? (rest.length > 0 ? rest : undefined),+ }+ case 'info':+ return rest.length > 0+ ? { label: `Read ${rest}`, input: undefined }+ : { label: 'Read tool', input: undefined }+ case 'schema': {+ const { head: subTool, rest: fieldPath } = splitFirstToken(rest)+ if (!subTool) {+ return { label: 'Inspect schema', input: undefined }+ }+ const path = explicitInput ?? (fieldPath.length > 0 ? fieldPath : undefined)+ return {+ label: path ? `Inspect ${subTool}.${path}` : `Inspect ${subTool} fields`,+ input: undefined,+ }+ }+ case 'call': {+ const { subTool, args } = parseExecCall(rest)+ if (!subTool) {+ return null+ }+ return {+ label: subTool,+ input: explicitInput ?? (args.length > 0 ? args : undefined),+ }+ }+ }+}++export function formatPostHogExecBody(input: string | undefined): string | undefined {+ if (!input) {+ return undefined+ }+ try {+ const parsed = JSON.parse(input)+ if (parsed && typeof parsed === 'object') {+ return JSON.stringify(parsed, null, 2)+ }+ } catch {+ // Non-JSON args, such as a search regex, are already displayable.+ }+ return input+}diff --git a/frontend/src/scenes/max/sandbox/sandboxToolRegistry.test.tsx b/frontend/src/scenes/max/sandbox/sandboxToolRegistry.test.tsxnew file mode 100644index 000000000000..f68bd55eb398--- /dev/null+++ b/frontend/src/scenes/max/sandbox/sandboxToolRegistry.test.tsx@@ -0,0 +1,154 @@+import '@testing-library/jest-dom'++import { render, screen } from '@testing-library/react'++import type { SandboxToolCallMessage } from '../maxTypes'+import { SandboxToolCall } from './components/tool/SandboxToolCall'+import { lookupSandboxToolRenderer, sandboxToolRegistry } from './sandboxToolRegistry'++function makeMessage(overrides: Partial<SandboxToolCallMessage> = {}): SandboxToolCallMessage {+ return {+ id: 'tc-1',+ resolvedKey: 'Edit',+ rawServerName: 'posthog',+ rawToolName: '',+ rawInput: {},+ content: [],+ status: 'completed',+ ...overrides,+ }+}++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)+ })++ it('leaves unknown / unregistered 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')+ expect(sandboxToolRegistry.lookup('insight-query')).toBeNull()+ expect(sandboxToolRegistry.lookup('read_insight')).toBeNull()+ expect(sandboxToolRegistry.lookup('query-llm-trace')).toBeNull()+ })++ // Claude built-ins are keyed by their stable SDK name; the registry contributes a friendly+ // displayName + icon (not the wrench fallback's key/wrench).+ const builtinCases: [string, string][] = [+ ['Read', 'Read'],+ ['NotebookRead', 'Read'],+ ['Edit', 'Edit'],+ ['Write', 'Edit'],+ ['NotebookEdit', 'Edit'],+ ['MultiEdit', 'Edit'],+ ['Grep', 'Search'],+ ['Glob', 'Search'],+ ['LS', 'Search'],+ ['Bash', 'Terminal'],+ ['BashOutput', 'Terminal'],+ ['KillShell', 'Terminal'],+ ['WebSearch', 'Web'],+ ['WebFetch', 'Web'],+ ['Task', 'Subagent'],+ ['Agent', 'Subagent'],+ ['TaskCreate', 'Tasks'],+ ['TodoWrite', 'Tasks'],+ ['Skill', 'Skill'],+ ['ToolSearch', 'Tool search'],+ ['ExitPlanMode', 'Plan'],+ ['AskUserQuestion', 'Question'],+ ]++ it.each(builtinCases)('resolves built-in %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)+ })++ // PostHog single-exec discovery verbs are keyed by their sentinel key (from `resolveToolKey`); the+ // registry gives each a fitting icon + displayName instead of the wrench fallback.+ const execVerbCases: [string, string][] = [+ ['__posthog_exec_tools__', 'List tools'],+ ['__posthog_exec_search__', 'Search tools'],+ ['__posthog_exec_info__', 'Read tool'],+ ['__posthog_exec_schema__', 'Inspect schema'],+ ['__posthog_exec_unknown__', 'Run command'],+ ]++ it.each(execVerbCases)('resolves exec verb %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)+ })++ it('falls back to the wrench card (key as displayName) for an unmapped built-in-looking name', () => {+ expect(sandboxToolRegistry.lookup('NotARealTool')).toBeNull()+ expect(lookupSandboxToolRenderer('NotARealTool').displayName).toEqual('NotARealTool')+ })++ // Render-level: SandboxToolCall resolves the entry, loads the lazy renderer behind a Suspense+ // skeleton, and the resolved renderer reaches the screen. The skeleton shows the displayName first.+ describe('lazy dispatch', () => {+ it('renders a Bash call through its dedicated card once the chunk loads', async () => {+ render(+ <SandboxToolCall+ message={makeMessage({+ resolvedKey: 'Bash',+ claudeToolName: 'Bash',+ rawInput: { command: 'echo hello-bash' },+ })}+ />+ )+ // Skeleton first (registry displayName), then the resolved card with the command. The+ // generous timeout covers jest compiling the lazy chunk's heavy deps on first load.+ expect(screen.getByText('Terminal')).toBeInTheDocument()+ expect(await screen.findByText('echo hello-bash', {}, { timeout: 10000 })).toBeInTheDocument()+ })++ it('renders an unmapped MCP tool through the generic card', async () => {+ render(+ <SandboxToolCall+ message={makeMessage({+ resolvedKey: 'do_thing',+ rawServerName: 'user-mcp',+ rawToolName: 'do_thing',+ })}+ />+ )+ expect(+ await screen.findByText('Call user-mcp – do_thing (MCP)', {}, { timeout: 10000 })+ ).toBeInTheDocument()+ })+ })+})diff --git a/frontend/src/scenes/max/sandbox/sandboxToolRegistry.tsx b/frontend/src/scenes/max/sandbox/sandboxToolRegistry.tsxnew file mode 100644index 000000000000..aaa718fe2ed1--- /dev/null+++ b/frontend/src/scenes/max/sandbox/sandboxToolRegistry.tsx@@ -0,0 +1,273 @@+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 '../maxTypes'++export interface SandboxToolRendererProps {+ message: SandboxToolCallMessage+ isLastInGroup: boolean+ /**+ * Resolved registry entry's icon — the registry's contribution to the card. Renderers use it for+ * the header icon (built-ins get their friendly icon instead of the generic wrench). Optional so+ * direct mounts default to the renderer's own fallback icon.+ */+ icon?: JSX.Element+ /** Resolved registry entry's stable display name, used as the header label when no title exists. */+ displayName?: string+ /** Turn-level signals so a still-incomplete tool reads as loading vs cancelled vs idle. */+ turnComplete?: boolean+ turnCancelled?: boolean+}++/** A renderer reachable eagerly or via a lazy chunk — both render identically in `SandboxToolCall`. */+type SandboxToolRendererComponent =+ | ComponentType<SandboxToolRendererProps>+ | LazyExoticComponent<ComponentType<SandboxToolRendererProps>>++export interface SandboxToolRegistryEntry {+ /**+ * Registry key. For single-exec PostHog tools, this is the **inner** tool name parsed from+ * `rawInput.command` (e.g. "execute-sql", "insight-create"); for `exec`'s discovery verbs,+ * the sentinel "__posthog_exec_tools__" etc.; for non-exec MCP tools and Claude built-ins,+ * the wire `toolName` directly (e.g. "TodoWrite", "WebSearch").+ */+ key: string+ /** Display name / icon for fallback rendering and for the tool-call header line. */+ displayName: string+ icon: JSX.Element+ Renderer: SandboxToolRendererComponent+}++export interface SandboxToolRegistry {+ register: (entry: SandboxToolRegistryEntry) => void+ lookup: (toolName: string) => SandboxToolRegistryEntry | null+}++class MapBackedRegistry implements SandboxToolRegistry {+ private entries = new Map<string, SandboxToolRegistryEntry>()++ register(entry: SandboxToolRegistryEntry): void {+ this.entries.set(entry.key, entry)+ }++ lookup(toolName: string): SandboxToolRegistryEntry | null {+ return this.entries.get(toolName) ?? null+ }+}++// Renderers are code-split: the static graph below carries only icons, types, and lazy factories, so a+// sandbox conversation pulls a renderer's chunk on first use, not at thread mount. The built-in tools+// 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('../messages/adapters/EditDiffRenderer').then((m) => ({ default: m.EditDiffRenderer }))+)+const InsightRenderer = lazy(() =>+ import('../messages/adapters/CreateInsightWidget').then((m) => ({ default: m.CreateInsightWidget }))+)+const DashboardRenderer = lazy(() =>+ import('../messages/adapters/UpsertDashboardWidget').then((m) => ({ default: m.UpsertDashboardWidget }))+)+const SessionRecordingsRenderer = lazy(() =>+ import('../messages/adapters/SearchSessionRecordingsWidget').then((m) => ({+ default: m.SearchSessionRecordingsWidget,+ }))+)+const ErrorTrackingRenderer = lazy(() =>+ import('../messages/adapters/ErrorTrackingWidget').then((m) => ({ default: m.ErrorTrackingWidget }))+)+const NotebookRenderer = lazy(() =>+ import('../messages/adapters/CreateNotebookWidget').then((m) => ({ default: m.CreateNotebookWidget }))+)+const QueryRenderer = lazy(() => import('../messages/adapters/QueryWidget').then((m) => ({ default: m.QueryWidget })))+const QuestionRenderer = lazy(() =>+ import('./SandboxQuestionRenderer').then((m) => ({ default: m.SandboxQuestionRenderer }))+)++/**+ * Single module-level registry of tool-name → renderer entry. All entries are registered at module+ * load — no dynamic registration, no hooks, no scene callbacks. Custom adapters are registered per+ * tool; any tool without one falls through to the built-in renderer's generic MCP card.+ */+export const sandboxToolRegistry: SandboxToolRegistry = new MapBackedRegistry()++// 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 })+}++// --- Claude built-in tools ---+// Keyed by the stable SDK tool name (reachable via `_meta.claudeCode.toolName`). Bash/Read/Search/Web+// get a dedicated per-tool card; the rest fall through to the generic MCP card — all inside the single+// `BuiltinToolRenderer` chunk, which switches on the resolved tool name. The registry supplies the+// friendly icon + a stable `displayName` for frames whose `title` is empty. `Skill` is registered+// speculatively (not enumerated in the agent's tools.ts) — zero cost if never emitted. File-editing+// built-ins are split out below into the dedicated diff renderer.+const BUILTIN_TOOLS: { keys: string[]; displayName: string; icon: JSX.Element }[] = [+ { keys: ['Read', 'NotebookRead'], displayName: 'Read', icon: <IconEye /> },+ { keys: ['Grep', 'Glob', 'LS'], displayName: 'Search', icon: <IconSearch /> },+ { keys: ['Bash', 'BashOutput', 'KillShell'], displayName: 'Terminal', icon: <IconTerminal /> },+ { keys: ['WebSearch', 'WebFetch'], displayName: 'Web', icon: <IconGlobe /> },+ { keys: ['Task', 'Agent'], displayName: 'Subagent', icon: <IconRobot /> },+ {+ keys: ['TaskCreate', 'TaskUpdate', 'TaskGet', 'TaskList', 'TodoWrite'],+ displayName: 'Tasks',+ icon: <IconListCheck />,+ },+ { keys: ['Skill'], displayName: 'Skill', icon: <IconMagicWand /> },+ { keys: ['ToolSearch'], displayName: 'Tool search', icon: <IconSearch /> },+ { keys: ['ExitPlanMode'], displayName: 'Plan', icon: <IconDocument /> },+]+for (const { keys, displayName, icon } of BUILTIN_TOOLS) {+ for (const key of keys) {+ sandboxToolRegistry.register({ key, displayName, icon, Renderer: BuiltinToolRenderer })+ }+}++// File-editing built-ins render an inline visual diff when the agent attaches `type: "diff"` content+// blocks; EditDiffRenderer falls back to the generic card when none are present.+for (const key of ['Edit', 'Write', 'NotebookEdit', 'MultiEdit']) {+ sandboxToolRegistry.register({ key, displayName: 'Edit', icon: <IconPencil />, Renderer: EditToolRenderer })+}++// PostHog single-exec discovery verbs. `resolveToolKey` parses `exec tools|search|info|schema` into+// these sentinel keys; PostHogExecRenderer (inside the built-in chunk) derives the friendly label and+// input preview from the command. Registered so they get a fitting icon instead of the wrench fallback.+const POSTHOG_EXEC_VERBS: { key: string; displayName: string; icon: JSX.Element }[] = [+ { key: '__posthog_exec_tools__', displayName: 'List tools', icon: <IconListCheck /> },+ { key: '__posthog_exec_search__', displayName: 'Search tools', icon: <IconSearch /> },+ { key: '__posthog_exec_info__', displayName: 'Read tool', icon: <IconDocument /> },+ { key: '__posthog_exec_schema__', displayName: 'Inspect schema', icon: <IconDocument /> },+ { key: '__posthog_exec_unknown__', displayName: 'Run command', icon: <IconWrench /> },+]+for (const { key, displayName, icon } of POSTHOG_EXEC_VERBS) {+ sandboxToolRegistry.register({ key, displayName, icon, Renderer: BuiltinToolRenderer })+}++// AskUserQuestion (the agent asking the user to pick between options) gets a bespoke renderer that+// lays the question + options out like the LangGraph question recap, rather than the generic JSON card.+sandboxToolRegistry.register({+ key: 'AskUserQuestion',+ displayName: 'Question',+ icon: <IconAI />,+ Renderer: QuestionRenderer,+})++/** Looks up the renderer entry for a resolved tool key, falling back to the generic built-in card. */+export function lookupSandboxToolRenderer(resolvedKey: string): SandboxToolRegistryEntry {+ return (+ sandboxToolRegistry.lookup(resolvedKey) ?? {+ key: resolvedKey,+ displayName: resolvedKey,+ icon: <IconWrench />,+ Renderer: BuiltinToolRenderer,+ }+ )+}diff --git a/frontend/src/scenes/max/sandbox/sandboxToolResolver.test.ts b/frontend/src/scenes/max/sandbox/sandboxToolResolver.test.tsnew file mode 100644index 000000000000..ce736d977daa--- /dev/null+++ b/frontend/src/scenes/max/sandbox/sandboxToolResolver.test.ts@@ -0,0 +1,122 @@+import { resolveToolCall, resolveToolKey } from './sandboxToolResolver'++describe('sandboxToolResolver', () => {+ describe('resolveToolKey', () => {+ it('parses the inner tool name out of a single-exec call command', () => {+ const resolved = resolveToolKey('posthog', 'exec', { command: 'call insight-create {"name":"Signups"}' })+ expect(resolved.resolvedKey).toEqual('insight-create')+ expect(resolved.innerToolName).toEqual('insight-create')+ expect(resolved.innerInput).toEqual({ name: 'Signups' })+ })++ it('parses --json single-exec call commands', () => {+ const resolved = resolveToolKey('posthog', 'exec', {+ command: 'call --json query-trends {"kind":"TrendsQuery"}',+ })+ expect(resolved.resolvedKey).toEqual('query-trends')+ expect(resolved.innerInput).toEqual({ kind: 'TrendsQuery' })+ })++ it('maps discovery verbs to sentinels', () => {+ expect(resolveToolKey('posthog', 'exec', { command: 'tools' }).resolvedKey).toEqual(+ '__posthog_exec_tools__'+ )+ expect(resolveToolKey('posthog', 'exec', { command: 'search recordings' }).resolvedKey).toEqual(+ '__posthog_exec_search__'+ )+ })++ it('falls back to unknown sentinel for malformed commands', () => {+ expect(resolveToolKey('posthog', 'exec', { command: '!!!' }).resolvedKey).toEqual(+ '__posthog_exec_unknown__'+ )+ })++ it.each([+ ['call --confirm feature-flag-delete {"key":"x"}'],+ ['call --json --confirm feature-flag-delete {"key":"x"}'],+ ['call --confirm --json feature-flag-delete {"key":"x"}'],+ ])('strips --json/--confirm flags in any order before the inner tool name (%s)', (command) => {+ const resolved = resolveToolKey('posthog', 'exec', { command })+ expect(resolved.resolvedKey).toEqual('feature-flag-delete')+ expect(resolved.innerToolName).toEqual('feature-flag-delete')+ expect(resolved.innerInput).toEqual({ key: 'x' })+ })++ it.each([['call'], ['call --json'], ['call --confirm --json']])(+ 'falls back to unknown sentinel for a call with no resolvable sub-tool (%s)',+ (command) => {+ const resolved = resolveToolKey('posthog', 'exec', { command })+ expect(resolved.resolvedKey).toEqual('__posthog_exec_unknown__')+ expect(resolved.innerToolName).toBeUndefined()+ }+ )++ it('returns the wire name for non-exec MCP tools that carry one', () => {+ expect(resolveToolKey('user-mcp', 'do_thing', {}).resolvedKey).toEqual('do_thing')+ })++ it.each(['Edit', 'TodoWrite', 'Grep', 'Task'])(+ 'falls back to the SDK %s name when the wire toolName is empty (every Claude built-in)',+ (sdkName) => {+ // Built-ins carry no top-level toolName on the wire — only `_meta.claudeCode.toolName`.+ expect(resolveToolKey('claude', '', {}, sdkName).resolvedKey).toEqual(sdkName)+ }+ )++ it('prefers the explicit wire toolName over the SDK name when both are present', () => {+ expect(resolveToolKey('user-mcp', 'do_thing', {}, 'Edit').resolvedKey).toEqual('do_thing')+ })++ it('resolves to empty string when neither a wire toolName nor an SDK name is present', () => {+ expect(resolveToolKey('claude', '', {}).resolvedKey).toEqual('')+ })+ })++ describe('resolveToolCall', () => {+ it('resolves a raw streamed exec invocation at render time', () => {+ expect(+ resolveToolCall({+ rawServerName: 'posthog',+ rawToolName: 'exec',+ input: { command: 'call query-trends {"kind":"TrendsQuery"}' },+ })+ ).toEqual({+ resolvedKey: 'query-trends',+ innerToolName: 'query-trends',+ innerInput: { kind: 'TrendsQuery' },+ claudeToolName: undefined,+ })+ })++ it('resolves exec invocations when the canonical tool name only arrives in metadata', () => {+ expect(+ resolveToolCall({+ rawServerName: 'posthog',+ rawToolName: '',+ input: { command: 'call query-trends {"kind":"TrendsQuery","series":[]}' },+ meta: { claudeCode: { toolName: 'mcp__posthog__exec' } },+ })+ ).toEqual({+ resolvedKey: 'query-trends',+ innerToolName: 'query-trends',+ innerInput: { kind: 'TrendsQuery', series: [] },+ claudeToolName: 'mcp__posthog__exec',+ })+ })++ it('resolves a raw built-in invocation from metadata at render time', () => {+ expect(+ resolveToolCall({+ rawServerName: 'claude',+ rawToolName: '',+ input: { file_path: 'app.ts' },+ meta: { claudeCode: { toolName: 'Edit' } },+ })+ ).toEqual({+ resolvedKey: 'Edit',+ claudeToolName: 'Edit',+ })+ })+ })+})diff --git a/frontend/src/scenes/max/sandbox/sandboxToolResolver.ts b/frontend/src/scenes/max/sandbox/sandboxToolResolver.tsnew file mode 100644index 000000000000..156451682f84--- /dev/null+++ b/frontend/src/scenes/max/sandbox/sandboxToolResolver.ts@@ -0,0 +1,92 @@+import { parseExecCall, parseExecCommand, POSTHOG_EXEC_TOOL_RE } from './posthogExecDisplay'++export interface ResolvedToolKey {+ resolvedKey: string+ innerToolName?: string+ innerInput?: Record<string, unknown>+}++export interface ResolvableToolCall {+ rawServerName: string+ rawToolName: string+ input: Record<string, unknown>+ meta?: unknown+}++export interface ResolvedToolCall extends ResolvedToolKey {+ claudeToolName?: string+}++/** Reads `_meta.claudeCode` off a tool frame's `_meta` without trusting its shape. */+export function getClaudeCodeMeta(meta: unknown): Record<string, unknown> | undefined {+ if (typeof meta !== 'object' || meta === null) {+ return undefined+ }+ const claudeCode = (meta as { claudeCode?: unknown }).claudeCode+ return typeof claudeCode === 'object' && claudeCode !== null ? (claudeCode as Record<string, unknown>) : undefined+}++/** Stable SDK tool name (`"Edit"`, `"TodoWrite"`) from `_meta.claudeCode.toolName`; undefined when absent. */+export function extractClaudeToolName(meta: unknown): string | undefined {+ const claudeCode = getClaudeCodeMeta(meta)+ return typeof claudeCode?.toolName === 'string' && claudeCode.toolName ? claudeCode.toolName : undefined+}++/**+ * Resolves the registry key for a tool call. The single-exec `posthog` MCP server exposes one+ * outer `exec` tool; the inner tool name is parsed out of `rawInput.command`. Non-exec MCP tools+ * and Claude built-ins look up by their wire name directly. Claude built-ins carry no wire+ * `toolName`, so `claudeToolName` (from `_meta.claudeCode.toolName`) is preferred as the fallback.+ */+export function resolveToolKey(+ serverName: string,+ toolName: string,+ input: Record<string, unknown>,+ claudeToolName?: string+): ResolvedToolKey {+ const fullName = `mcp__${serverName}__${toolName}`+ const isPostHogExecTool =+ POSTHOG_EXEC_TOOL_RE.test(fullName) ||+ POSTHOG_EXEC_TOOL_RE.test(toolName) ||+ (claudeToolName ? POSTHOG_EXEC_TOOL_RE.test(claudeToolName) : false)++ if (isPostHogExecTool && typeof input.command === 'string') {+ const { verb, rest } = parseExecCommand(input.command)+ if (!verb) {+ return { resolvedKey: '__posthog_exec_unknown__' }+ }++ if (verb !== 'call') {+ return { resolvedKey: `__posthog_exec_${verb}__` }+ }++ // Resolve the inner sub-tool the same way the backend does (flags in any order). When it+ // can't be resolved, fall back to the unknown sentinel so the permission gate fails closed+ // instead of treating an unparsed `call` as a non-destructive tool.+ const { subTool, args } = parseExecCall(rest)+ if (!subTool) {+ return { resolvedKey: '__posthog_exec_unknown__' }+ }++ let innerInput: Record<string, unknown> = {}+ if (args) {+ try {+ innerInput = JSON.parse(args)+ } catch {+ // Leave malformed payloads renderable as generic tool calls.+ }+ }+ return { resolvedKey: subTool, innerToolName: subTool, innerInput }+ }++ return { resolvedKey: toolName || claudeToolName || '' }+}++/** Resolves renderer-facing fields from a raw streamed tool invocation. */+export function resolveToolCall(toolCall: ResolvableToolCall): ResolvedToolCall {+ const claudeToolName = extractClaudeToolName(toolCall.meta)+ return {+ ...resolveToolKey(toolCall.rawServerName, toolCall.rawToolName, toolCall.input, claudeToolName),+ claudeToolName,+ }+}diff --git a/frontend/src/scenes/max/sandboxPermissionDisplayUtils.test.ts b/frontend/src/scenes/max/sandboxPermissionDisplayUtils.test.tsnew file mode 100644index 000000000000..f000d817c77d--- /dev/null+++ b/frontend/src/scenes/max/sandboxPermissionDisplayUtils.test.ts@@ -0,0 +1,90 @@+import { getPostHogExecDisplay, getSandboxPermissionDisplay } from './sandboxPermissionDisplayUtils'+import type { PermissionRequestRecord, ToolInvocation } from './types/sandboxStreamTypes'++const rawToolCall: ToolInvocation = {+ toolCallId: 'tc-1',+ rawServerName: 'posthog',+ rawToolName: 'exec',+ input: {},+ status: 'pending',+ contentBlocks: [],+}++function makeRequest(overrides: Partial<PermissionRequestRecord> = {}): PermissionRequestRecord {+ return {+ requestId: 'req-1',+ toolCallId: 'tc-1',+ toolName: 'mcp__posthog__exec',+ options: [+ { optionId: 'opt-allow', name: 'Approve', kind: 'allow_once' },+ { optionId: 'opt-reject', name: 'Decline', kind: 'reject' },+ ],+ rawToolCall,+ ...overrides,+ }+}++describe('sandboxPermissionDisplayUtils', () => {+ it('unwraps PostHog exec call commands into an MCP title and pretty JSON payload', () => {+ const display = getSandboxPermissionDisplay(+ makeRequest({+ rawToolCall: {+ ...rawToolCall,+ input: { command: 'call execute-sql {"query":"select 1"}' },+ },+ })+ )++ expect(display).toEqual({+ title: 'posthog - execute-sql (MCP)',+ payload: '{\n "query": "select 1"\n}',+ })+ })++ it('prefers explicit PostHog exec input when present', () => {+ expect(+ getPostHogExecDisplay({+ command: 'call execute-sql {"query":"wrapped"}',+ input: { query: 'explicit' },+ })+ ).toEqual({+ label: 'execute-sql',+ input: '{"query":"explicit"}',+ })+ })++ it('keeps non-JSON PostHog exec args displayable', () => {+ const display = getSandboxPermissionDisplay(+ makeRequest({+ rawToolCall: {+ ...rawToolCall,+ input: { command: 'search query-' },+ },+ })+ )++ expect(display).toEqual({+ title: 'posthog - Search tools (MCP)',+ payload: 'query-',+ })+ })++ it('formats generic MCP tool input as JSON', () => {+ const display = getSandboxPermissionDisplay(+ makeRequest({+ toolName: 'mcp__github__create_issue',+ rawToolCall: {+ ...rawToolCall,+ rawServerName: 'github',+ rawToolName: 'create_issue',+ input: { owner: 'PostHog', repo: 'posthog' },+ },+ })+ )++ expect(display).toEqual({+ title: 'github - create_issue (MCP)',+ payload: '{\n "owner": "PostHog",\n "repo": "posthog"\n}',+ })+ })+})diff --git a/frontend/src/scenes/max/sandboxPermissionDisplayUtils.ts b/frontend/src/scenes/max/sandboxPermissionDisplayUtils.tsnew file mode 100644index 000000000000..2569d9c381ea--- /dev/null+++ b/frontend/src/scenes/max/sandboxPermissionDisplayUtils.ts@@ -0,0 +1,69 @@+import { POSTHOG_EXEC_TOOL_RE, formatPostHogExecBody, getPostHogExecDisplay } from './sandbox/posthogExecDisplay'+import { resolveToolCall } from './sandbox/sandboxToolResolver'+import type { PermissionRequestRecord } from './types/sandboxStreamTypes'++// Re-exported so existing importers (and tests) keep resolving the exec display from here.+export { getPostHogExecDisplay } from './sandbox/posthogExecDisplay'++export interface SandboxPermissionDisplay {+ title?: string+ payload?: string+}++function parseMcpToolKey(toolName: string): { serverName: string; toolName: string } | null {+ const parts = toolName.split('__')+ if (parts.length < 3 || parts[0] !== 'mcp') {+ return null+ }+ return {+ serverName: parts[1],+ toolName: parts.slice(2).join('__'),+ }+}++function formatInput(rawInput: unknown): string | undefined {+ if (!rawInput || typeof rawInput !== 'object') {+ return undefined+ }+ try {+ const json = JSON.stringify(rawInput, null, 2)+ return json === '{}' ? undefined : json+ } catch {+ return undefined+ }+}++export function getSandboxPermissionDisplay(request: PermissionRequestRecord): SandboxPermissionDisplay {+ const mcpTool = parseMcpToolKey(request.toolName)+ if (!mcpTool) {+ return {+ title: request.title ?? request.rawToolCall.title ?? request.toolName,+ payload: formatInput(request.rawToolCall.input),+ }+ }++ if (POSTHOG_EXEC_TOOL_RE.test(request.toolName)) {+ const posthogDisplay = getPostHogExecDisplay(request.rawToolCall.input)+ if (posthogDisplay) {+ return {+ title: `posthog - ${posthogDisplay.label} (MCP)`,+ payload: formatPostHogExecBody(posthogDisplay.input),+ }+ }+ const resolved = resolveToolCall(request.rawToolCall)+ const resolvedName =+ resolved.innerToolName ??+ (resolved.resolvedKey.startsWith('__posthog_exec_') ? undefined : resolved.resolvedKey)+ if (resolvedName) {+ return {+ title: `posthog - ${resolvedName} (MCP)`,+ payload: formatInput(resolved.innerInput ?? request.rawToolCall.input),+ }+ }+ }++ return {+ title: `${mcpTool.serverName} - ${mcpTool.toolName} (MCP)`,+ payload: formatInput(request.rawToolCall.input),+ }+}diff --git a/frontend/src/scenes/max/sandboxPermissionUtils.test.ts b/frontend/src/scenes/max/sandboxPermissionUtils.test.tsnew file mode 100644index 000000000000..eca480d63d65--- /dev/null+++ b/frontend/src/scenes/max/sandboxPermissionUtils.test.ts@@ -0,0 +1,67 @@+import { mapPermissionOption, mapPermissionOptions } from './sandboxPermissionUtils'+import type { PermissionOption } from './types/sandboxWireTypes'++describe('sandboxPermissionUtils', () => {+ describe('mapPermissionOption', () => {+ it.each<[string, Partial<ReturnType<typeof mapPermissionOption>>]>([+ [+ 'allow_once',+ {+ decision: 'approved',+ primary: true,+ remembered: false,+ requiresFeedback: false,+ supportsFeedback: false,+ },+ ],+ ['allow_always', { decision: 'approved', primary: false, remembered: true }],+ ['reject', { decision: 'declined', primary: false, requiresFeedback: false, supportsFeedback: false }],+ ['reject_with_feedback', { decision: 'declined', requiresFeedback: true, supportsFeedback: false }],+ ])('maps the known kind %s onto the card model', (kind, expected) => {+ expect(mapPermissionOption({ optionId: 'x', name: '', kind })).toMatchObject(expected)+ })++ it('treats reject_once as a one-click decline that supports optional feedback via customInput', () => {+ expect(+ mapPermissionOption({ optionId: 'r', name: 'No', kind: 'reject_once', customInput: true })+ ).toMatchObject({+ decision: 'declined',+ requiresFeedback: false,+ supportsFeedback: true,+ })+ // Without customInput it is still a plain decline, just no feedback field.+ expect(mapPermissionOption({ optionId: 'r', name: 'No', kind: 'reject_once' })).toMatchObject({+ decision: 'declined',+ requiresFeedback: false,+ supportsFeedback: false,+ })+ })++ it.each([+ ['allow_for_session', 'approved'],+ ['deny_forever', 'declined'],+ ])('classifies the unknown kind %s by prefix instead of dropping it', (kind, decision) => {+ expect(mapPermissionOption({ optionId: 'x', name: '', kind }).decision).toEqual(decision)+ })++ it.each([+ ['allow_once', 'Approve'],+ ['allow_always', 'Approve always'],+ ['reject_once', 'Decline'],+ ['reject_with_feedback', 'Decline with feedback…'],+ ])('falls back to a default label for %s when the wire omits a name', (kind, label) => {+ expect(mapPermissionOption({ optionId: 'a', name: '', kind }).label).toEqual(label)+ })+ })++ describe('mapPermissionOptions', () => {+ it('hides allow_always unless the tool preview opts into remembering', () => {+ const options: PermissionOption[] = [+ { optionId: 'a', name: '', kind: 'allow_once' },+ { optionId: 'd', name: '', kind: 'allow_always' },+ ]+ expect(mapPermissionOptions(options).map((o) => o.optionId)).toEqual(['a'])+ expect(mapPermissionOptions(options, true).map((o) => o.optionId)).toEqual(['a', 'd'])+ })+ })+})diff --git a/frontend/src/scenes/max/sandboxPermissionUtils.ts b/frontend/src/scenes/max/sandboxPermissionUtils.tsnew file mode 100644index 000000000000..1127170fc66d--- /dev/null+++ b/frontend/src/scenes/max/sandboxPermissionUtils.ts@@ -0,0 +1,74 @@+import type { PermissionOption } from './types/sandboxWireTypes'++/**+ * The card-facing decision a user can take on a sandbox ACP `permission_request` option. The+ * sandbox runtime surfaces richer ACP option kinds that all map down onto approve / decline.+ */+export type ApprovalDecision = 'approved' | 'declined'++/**+ * One control the sandbox approval card renders, derived from an ACP `permission_request` option.+ * The card forwards `optionId` back verbatim on the `permission_response` — the kind only drives+ * the UI affordance and the resolution status recorded locally.+ */+export interface ApprovalCardOption {+ optionId: string+ label: string+ /** Resolution status the card records once this option is chosen. */+ decision: ApprovalDecision+ /** Primary CTA styling (the single `allow_once`/approve path). */+ primary: boolean+ /** `allow_always` — only shown when the tool preview opts in via `remember: true`. */+ remembered: boolean+ /** Legacy `reject_with_feedback` — actionable only through the feedback text input, never a plain button. */+ requiresFeedback: boolean+ /** `reject_once` carrying `_meta.customInput` — a one-click decline that ALSO offers an optional feedback input. */+ supportsFeedback: boolean+}++/**+ * Maps an ACP `permission_request` option onto the sandbox approval card's option model. The+ * affordance is resolved by prefix, not exact kind: `allow*` is an approval, everything else a+ * decline. This keeps adapter vocabulary drift (`reject` → `reject_once`, future renames) from+ * dropping options. `allow_always` is the one kind that needs exact matching — it drives the+ * rememberable hiding (hidden unless `allowRemember`; still returned, flagged via `remembered`).+ */+export function mapPermissionOption(option: PermissionOption): ApprovalCardOption {+ if (option.kind.startsWith('allow')) {+ const remembered = option.kind === 'allow_always'+ return {+ optionId: option.optionId,+ label: option.name || (remembered ? 'Approve always' : 'Approve'),+ decision: 'approved',+ primary: !remembered,+ remembered,+ requiresFeedback: false,+ supportsFeedback: false,+ }+ }++ // Decline. The legacy `reject_with_feedback` kind is feedback-only (no plain button); the current+ // adapter's `reject_once` stays a one-click decline and advertises optional feedback via+ // `_meta.customInput` (parsed onto `option.customInput`).+ const requiresFeedback = option.kind === 'reject_with_feedback'+ return {+ optionId: option.optionId,+ label: option.name || (requiresFeedback ? 'Decline with feedback…' : 'Decline'),+ decision: 'declined',+ primary: false,+ remembered: false,+ requiresFeedback,+ supportsFeedback: !requiresFeedback && option.customInput === true,+ }+}++/**+ * Maps the full ACP `options[]` to card options, dropping `allow_always` unless the tool preview+ * opted into a rememberable decision (`allowRemember`).+ */+export function mapPermissionOptions(+ options: PermissionOption[],+ allowRemember: boolean = false+): ApprovalCardOption[] {+ return options.map(mapPermissionOption).filter((option) => !option.remembered || allowRemember)+}diff --git a/frontend/src/scenes/max/sandboxQuestionUtils.test.ts b/frontend/src/scenes/max/sandboxQuestionUtils.test.tsnew file mode 100644index 000000000000..7ab65e93d323--- /dev/null+++ b/frontend/src/scenes/max/sandboxQuestionUtils.test.ts@@ -0,0 +1,103 @@+import {+ deriveQuestionOptionId,+ extractSandboxQuestionAnswer,+ parseSandboxQuestionAnswers,+ parseSandboxQuestions,+ type SandboxQuestion,+} from './sandboxQuestionUtils'++describe('sandboxQuestionUtils', () => {+ describe('parseSandboxQuestions', () => {+ it('parses the { questions: [...] } shape with options and descriptions', () => {+ const result = parseSandboxQuestions({+ questions: [+ {+ question: 'Which goal matters most?',+ header: 'Goal',+ multiSelect: false,+ options: [{ label: 'Activation', description: 'aha moment' }, { label: 'Revenue' }],+ },+ ],+ })++ expect(result).toEqual([+ {+ question: 'Which goal matters most?',+ header: 'Goal',+ multiSelect: false,+ options: [{ label: 'Activation', description: 'aha moment' }, { label: 'Revenue' }],+ },+ ])+ })++ it('normalizes a single { question, options } shape into a one-element array', () => {+ const result = parseSandboxQuestions({+ question: 'Pick one',+ options: [{ label: 'A' }, { label: 'B' }],+ multiSelect: true,+ })++ expect(result).toHaveLength(1)+ expect(result[0].question).toEqual('Pick one')+ expect(result[0].multiSelect).toBe(true)+ expect(result[0].options).toEqual([{ label: 'A' }, { label: 'B' }])+ })++ it('drops malformed entries and returns [] when nothing is parseable', () => {+ expect(parseSandboxQuestions({ questions: [{ noQuestion: true }, 'nope'] })).toEqual([])+ expect(parseSandboxQuestions({})).toEqual([])+ expect(parseSandboxQuestions(null)).toEqual([])+ })+ })++ describe('parseSandboxQuestionAnswers', () => {+ it('reads a bare answers map keyed by question text', () => {+ expect(parseSandboxQuestionAnswers({ answers: { 'Which goal?': 'Revenue' } })).toEqual({+ 'Which goal?': 'Revenue',+ })+ })++ it('reads an answers map wrapped under output and joins array values', () => {+ expect(parseSandboxQuestionAnswers({ output: { answers: { Products: ['Insights', 'Flags'] } } })).toEqual({+ Products: 'Insights, Flags',+ })+ })++ it('returns {} when there is no answers map', () => {+ expect(parseSandboxQuestionAnswers({ text: 'hi' })).toEqual({})+ expect(parseSandboxQuestionAnswers(undefined)).toEqual({})+ })+ })++ describe('extractSandboxQuestionAnswer', () => {+ const cases: [string, unknown, string | null][] = [+ ['a bare string', 'Revenue', 'Revenue'],+ ['an answer field', { answer: 'Revenue' }, 'Revenue'],+ ['a joined answers map', { answers: { q1: 'A', q2: 'B' } }, 'A, B'],+ ['a text field', { text: 'done' }, 'done'],+ ['a content field', { content: 'picked' }, 'picked'],+ ['nothing usable', { foo: 1 }, null],+ ]++ it.each(cases)('extracts from %s', (_label, result, expected) => {+ expect(extractSandboxQuestionAnswer(result)).toEqual(expected)+ })+ })++ describe('deriveQuestionOptionId', () => {+ const question: SandboxQuestion = {+ question: 'Pick',+ multiSelect: false,+ options: [{ label: 'Activation' }, { label: 'Revenue' }],+ }++ it('uses the index of the first selected option', () => {+ expect(deriveQuestionOptionId(question, ['Revenue'])).toEqual('option_1')+ })++ it('falls back to option_0 for a free-typed answer that matches no option', () => {+ expect(deriveQuestionOptionId(question, ['Cut churn'])).toEqual('option_0')+ expect(deriveQuestionOptionId(question, [])).toEqual('option_0')+ })+ })+})diff --git a/frontend/src/scenes/max/sandboxQuestionUtils.ts b/frontend/src/scenes/max/sandboxQuestionUtils.tsnew file mode 100644index 000000000000..a92e9646cb69--- /dev/null+++ b/frontend/src/scenes/max/sandboxQuestionUtils.ts@@ -0,0 +1,167 @@+/**+ * Parsing + answer helpers for the sandbox `AskUserQuestion` flow, ported from Twig+ * (`packages/agent/src/adapters/claude/questions/utils.ts` and the mobile `QuestionCard`).+ *+ * In the sandbox runtime the agent asks the user to pick between options via the Claude built-in+ * `AskUserQuestion`. Twig routes it through the ACP permission framework: a single+ * `permission_request` carries `toolCall._meta.codeToolKind === 'question'` + `_meta.questions`, and+ * the answer is returned on the existing `permission_response` command as an `answers` map keyed by+ * question text. These helpers are shared by `sandboxStreamLogic` (parsing the request), the input+ * overlay (`SandboxQuestionInput`, building the reply), and the thread recap (`SandboxQuestionRenderer`).+ */++/** The `option_${idx}` ids Twig's `buildQuestionOptions` mints for the first question's options. */+export const SANDBOX_QUESTION_OPTION_PREFIX = 'option_'++/** One choice the agent offered for a question. */+export interface SandboxQuestionOption {+ label: string+ description?: string+}++/** One question parsed from an `AskUserQuestion` permission request or tool call. */+export interface SandboxQuestion {+ question: string+ /** Short chip label (≤12 chars in the tool schema) shown above the question. */+ header?: string+ multiSelect: boolean+ options: SandboxQuestionOption[]+}++function asRecord(value: unknown): Record<string, unknown> | null {+ return value && typeof value === 'object' && !Array.isArray(value) ? (value as Record<string, unknown>) : null+}++function parseOptions(raw: unknown): SandboxQuestionOption[] {+ if (!Array.isArray(raw)) {+ return []+ }+ const options: SandboxQuestionOption[] = []+ for (const entry of raw) {+ const record = asRecord(entry)+ if (!record || typeof record.label !== 'string') {+ continue+ }+ options.push({+ label: record.label,+ description: typeof record.description === 'string' && record.description ? record.description : undefined,+ })+ }+ return options+}++function parseQuestionItem(record: Record<string, unknown>): SandboxQuestion | null {+ if (typeof record.question !== 'string') {+ return null+ }+ return {+ question: record.question,+ header: typeof record.header === 'string' && record.header ? record.header : undefined,+ multiSelect: record.multiSelect === true,+ options: parseOptions(record.options),+ }+}++/**+ * Parse the questions out of an `AskUserQuestion` payload. Accepts Twig's two input shapes+ * (`normalizeAskUserQuestionInput`): the preferred `{ questions: [...] }`, or a single+ * `{ question, header, options, multiSelect }`. Returns `[]` when nothing parseable is present.+ */+export function parseSandboxQuestions(raw: unknown): SandboxQuestion[] {+ const record = asRecord(raw)+ if (!record) {+ return []+ }+ if (Array.isArray(record.questions)) {+ const questions: SandboxQuestion[] = []+ for (const entry of record.questions) {+ const itemRecord = asRecord(entry)+ const item = itemRecord ? parseQuestionItem(itemRecord) : null+ if (item) {+ questions.push(item)+ }+ }+ return questions+ }+ const single = parseQuestionItem(record)+ return single ? [single] : []+}++/**+ * Per-question answers keyed by question text, read from the tool result. The result may be the+ * bare object or wrapped under an `output` envelope; array values (multi-select) are joined.+ */+export function parseSandboxQuestionAnswers(result: unknown): Record<string, string> {+ const outer = asRecord(result)+ for (const candidate of [outer, asRecord(outer?.output)]) {+ const map = asRecord(candidate?.answers)+ if (!map) {+ continue+ }+ const answers: Record<string, string> = {}+ for (const [key, value] of Object.entries(map)) {+ if (typeof value === 'string' && value.trim()) {+ answers[key] = value.trim()+ } else if (Array.isArray(value)) {+ const joined = value+ .filter((v): v is string => typeof v === 'string' && v.trim().length > 0)+ .map((v) => v.trim())+ .join(', ')+ if (joined) {+ answers[key] = joined+ }+ }+ }+ if (Object.keys(answers).length) {+ return answers+ }+ }+ return {}+}++/**+ * A single joined answer string for the compact recap — Twig's `extractAnswer`. Falls back through+ * `answer` / `answers` (joined) / `text` / `content` so an answer is shown even when the result+ * doesn't match the per-question map shape.+ */+export function extractSandboxQuestionAnswer(result: unknown): string | null {+ if (typeof result === 'string') {+ return result.trim() || null+ }+ const record = asRecord(result)+ if (!record) {+ return null+ }+ if (typeof record.answer === 'string' && record.answer.trim()) {+ return record.answer.trim()+ }+ const answers = asRecord(record.answers)+ if (answers) {+ const joined = Object.values(answers)+ .filter((v): v is string => typeof v === 'string' && v.trim().length > 0)+ .map((v) => v.trim())+ .join(', ')+ if (joined) {+ return joined+ }+ }+ if (typeof record.text === 'string' && record.text.trim()) {+ return record.text.trim()+ }+ if (typeof record.content === 'string' && record.content.trim()) {+ return record.content.trim()+ }+ return null+}++/**+ * The ACP `optionId` to send on the reply. Twig builds options server-side as `option_${idx}` over+ * the FIRST question's options; pick the index of the first selected label, falling back to+ * `option_0` for a free-typed ("Other") answer that matches no option. The `answers` map carries the+ * real content for the agent — `optionId` only has to be a valid offered option.+ */+export function deriveQuestionOptionId(question: SandboxQuestion, selectedLabels: string[]): string {+ const first = selectedLabels[0]+ const idx = first !== undefined ? question.options.findIndex((o) => o.label === first) : -1+ return `${SANDBOX_QUESTION_OPTION_PREFIX}${idx >= 0 ? idx : 0}`+}diff --git a/frontend/src/scenes/max/sandboxStreamLogic.test.ts b/frontend/src/scenes/max/sandboxStreamLogic.test.tsnew file mode 100644index 000000000000..764f8f409445--- /dev/null+++ b/frontend/src/scenes/max/sandboxStreamLogic.test.ts@@ -0,0 +1,2897 @@+import { expectLogic } from 'kea-test-utils'+import posthog from 'posthog-js'++import api from 'lib/api'+import { lemonToast } from 'lib/lemon-ui/LemonToast'+import { projectLogic } from 'scenes/projectLogic'++import { initKeaTests } from '~/test/init'++import { tasksRunsCommandCreate } from 'products/tasks/frontend/generated/api'++import {+ extractRunArtifacts,+ mapHttpStatusToStreamError,+ MAX_CUMULATIVE_RECONNECT_ATTEMPTS,+ MAX_SSE_RECONNECT_ATTEMPTS,+ mergeResourceProducts,+ mergeRunArtifacts,+ parsePermissionRequestFrame,+ reconnectDelayMs,+ sandboxStreamLogic,+ SSE_HEALTHY_CONNECTION_MS,+ 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(),+}))++function notification(method: string, params: Record<string, unknown>): StoredLogEntry {+ return { type: 'notification', notification: { method, params } }+}++function sessionUpdate(update: Record<string, unknown>): StoredLogEntry {+ return notification('session/update', { update })+}++function sessionPrompt(text: string, sessionId: string = 'session-1'): StoredLogEntry {+ return notification('session/prompt', {+ sessionId,+ prompt: [{ type: 'text', text }],+ })+}++function legacyNotification(method: string, params: Record<string, unknown>): Record<string, unknown> {+ return { notification: { method, params } }+}++type ReaderResult = { done: false; value: Uint8Array } | { done: true; value: undefined }++/**+ * Stand-in for one `api.tasks.runs.openStream` connection. Backs a fetch-style streaming `Response`+ * whose `body.getReader()` the logic pumps through `eventsource-parser`. Tests drive it by emitting+ * SSE-encoded frames; each `emit*` resolves the logic's pending `reader.read()` and drains the+ * microtask queue so the dispatched actions have settled before the test asserts.+ */+class MockStreamConnection {+ readonly options: { signal: AbortSignal; lastEventId?: string; startLatest?: boolean }+ private pendingRead: ((r: ReaderResult) => void) | null = null+ private queued: ReaderResult[] = []+ private encoder = new TextEncoder()++ constructor(options: { signal: AbortSignal; lastEventId?: string; startLatest?: boolean }) {+ this.options = options+ // Teardown (dispose 'event-source') aborts the signal — unblock any pending read so the+ // logic's loop sees `done`/`aborted` and exits without scheduling a reconnect.+ options.signal.addEventListener('abort', () => this.deliver({ done: true, value: undefined }))+ }++ /** Mirrors `MockEventSource.closed`: the logic aborted the fetch (teardown / terminal / close). */+ get closed(): boolean {+ return this.options.signal.aborted+ }++ response(): Response {+ const reader = {+ read: (): Promise<ReaderResult> => {+ const next = this.queued.shift()+ if (next) {+ return Promise.resolve(next)+ }+ if (this.options.signal.aborted) {+ return Promise.resolve({ done: true, value: undefined })+ }+ return new Promise<ReaderResult>((resolve) => {+ this.pendingRead = resolve+ })+ },+ }+ return { body: { getReader: () => reader } } as unknown as Response+ }++ private deliver(result: ReaderResult): void {+ if (this.pendingRead) {+ const resolve = this.pendingRead+ this.pendingRead = null+ resolve(result)+ } else {+ this.queued.push(result)+ }+ }++ private encodeFrame(fields: { data: string; event?: string; id?: string }): Uint8Array {+ const parts: string[] = []+ if (fields.event) {+ parts.push(`event: ${fields.event}`)+ }+ if (fields.id) {+ parts.push(`id: ${fields.id}`)+ }+ parts.push(`data: ${fields.data}`)+ return this.encoder.encode(parts.join('\n') + '\n\n')+ }++ /** The connection opens automatically once `openStream` resolves; this just drains the queue. */+ async emitOpen(): Promise<void> {+ await flushPromises()+ }++ /** Emit a default-channel data frame (optionally with the SSE `id:` = Redis stream id). */+ async emitMessage(data: object, id?: string): Promise<void> {+ this.deliver({ done: false, value: this.encodeFrame({ data: JSON.stringify(data), id }) })+ await flushPromises()+ }++ /** Emit a named `event: error` envelope frame. */+ async emitErrorFrame(envelope: Record<string, unknown>): Promise<void> {+ this.deliver({ done: false, value: this.encodeFrame({ data: JSON.stringify(envelope), event: 'error' }) })+ await flushPromises()+ }++ /** Server cleanly closes the stream body → the logic treats it as a drop. */+ async emitClose(): Promise<void> {+ this.deliver({ done: true, value: undefined })+ await flushPromises()+ }+}++class MockStream {+ static connections: MockStreamConnection[] = []++ static latest(): MockStreamConnection {+ return MockStream.connections[MockStream.connections.length - 1]+ }++ static reset(): void {+ MockStream.connections = []+ }++ /** Install the `api.tasks.runs.openStream` spy that records and backs each connection. */+ static install(): void {+ jest.spyOn(api.tasks.runs, 'openStream').mockImplementation((_taskId, _runId, options) => {+ const connection = new MockStreamConnection(options)+ MockStream.connections.push(connection)+ return Promise.resolve(connection.response())+ })+ }+}++describe('sandboxStreamLogic', () => {+ let logic: ReturnType<typeof sandboxStreamLogic.build>++ beforeEach(() => {+ initKeaTests()+ MockStream.reset()+ MockStream.install()+ projectLogic.mount()+ projectLogic.actions.loadCurrentProjectSuccess({ id: 997 } as any)+ ;(tasksRunsCommandCreate as jest.Mock).mockReset().mockResolvedValue({ jsonrpc: '2.0' })+ logic = sandboxStreamLogic({ streamKey: 'test-conversation', conversationId: 'test-conversation' })+ logic.mount()+ })++ afterEach(() => {+ logic.unmount()+ jest.restoreAllMocks()+ })++ describe('ingestAcpFrame replay', () => {+ it('folds a stream of StoredLogEntry frames into thread items', async () => {+ const frames: StoredLogEntry[] = [+ notification('_posthog/run_started', {}),+ sessionUpdate({ sessionUpdate: 'agent_message_chunk', messageId: 'm1', content: { text: 'Hel' } }),+ sessionUpdate({ sessionUpdate: 'agent_message_chunk', messageId: 'm1', content: { text: 'lo' } }),+ sessionUpdate({ sessionUpdate: 'agent_message', messageId: 'm1', content: { text: 'Hello' } }),+ sessionUpdate({+ sessionUpdate: 'tool_call',+ toolCallId: 't1',+ serverName: 'posthog',+ toolName: 'exec',+ rawInput: { command: 'call execute-sql {"query":"select 1"}' },+ status: 'in_progress',+ }),+ sessionUpdate({+ sessionUpdate: 'tool_call_update',+ toolCallId: 't1',+ status: 'completed',+ rawOutput: { rows: 1 },+ content: [{ type: 'text', text: 'done' }],+ }),+ notification('_posthog/turn_complete', {}),+ ]++ await expectLogic(logic, () => {+ frames.forEach((frame) => logic.actions.ingestAcpFrame(frame))+ }).toFinishAllListeners()++ expect(logic.values.runStarted).toEqual(true)+ expect(logic.values.turnComplete).toEqual(true)++ const assistantItem = logic.values.threadItems.find((item) => item.type === 'assistant_message')+ expect(assistantItem?.text).toEqual('Hello')+ expect(assistantItem?.complete).toEqual(true)++ const toolItem = logic.values.threadItems.find((item) => item.type === 'tool_invocation')+ expect(toolItem?.toolCallId).toEqual('t1')++ const invocation = logic.values.toolInvocations.get('t1')+ expect(invocation?.rawServerName).toEqual('posthog')+ expect(invocation?.rawToolName).toEqual('exec')+ expect(invocation?.input).toEqual({ command: 'call execute-sql {"query":"select 1"}' })+ expect(invocation?.status).toEqual('completed')+ expect(invocation?.output).toEqual({ rows: 1 })+ expect(invocation?.contentBlocks).toEqual([{ type: 'text', text: 'done' }])++ expect(logic.values.threadItems.some((item) => item.type === 'turn_separator')).toEqual(true)+ })++ it('sets currentMode on a current_mode_update frame', async () => {+ await expectLogic(logic, () => {+ logic.actions.ingestAcpFrame(+ sessionUpdate({ sessionUpdate: 'current_mode_update', currentModeId: 'plan' })+ )+ }).toFinishAllListeners()++ expect(logic.values.currentMode).toEqual('plan')+ })++ it('sets currentProgress on a _posthog/progress frame and clears it on turn complete', async () => {+ await expectLogic(logic, () => {+ logic.actions.ingestAcpFrame(notification('_posthog/progress', { label: 'Querying events' }))+ }).toFinishAllListeners()++ expect(logic.values.currentProgress).toEqual('Querying events')++ await expectLogic(logic, () => {+ logic.actions.ingestAcpFrame(notification('_posthog/turn_complete', {}))+ }).toFinishAllListeners()++ expect(logic.values.currentProgress).toBeNull()+ })++ it('drives terminal status off handleTerminalStatus', async () => {+ await expectLogic(logic, () => {+ logic.actions.handleTerminalStatus({ status: 'completed' })+ }).toFinishAllListeners()++ expect(logic.values.currentRunStatus).toEqual('completed')+ })+ })++ describe('assistant message buffering without messageId', () => {+ it('keeps two consecutive turns without a messageId in separate thread items', async () => {+ const frames: StoredLogEntry[] = [+ sessionUpdate({ sessionUpdate: 'agent_message_chunk', content: { text: 'One' } }),+ sessionUpdate({ sessionUpdate: 'agent_message', content: { text: 'One' } }),+ notification('_posthog/turn_complete', {}),+ sessionUpdate({ sessionUpdate: 'agent_message_chunk', content: { text: 'Tw' } }),+ sessionUpdate({ sessionUpdate: 'agent_message_chunk', content: { text: 'o' } }),+ sessionUpdate({ sessionUpdate: 'agent_message', content: { text: 'Two' } }),+ ]++ await expectLogic(logic, () => {+ frames.forEach((frame) => logic.actions.ingestAcpFrame(frame))+ }).toFinishAllListeners()++ const assistantItems = logic.values.threadItems.filter((item) => item.type === 'assistant_message')+ expect(assistantItems).toHaveLength(2)+ expect(assistantItems[0].text).toEqual('One')+ expect(assistantItems[0].complete).toEqual(true)+ expect(assistantItems[1].text).toEqual('Two')+ expect(assistantItems[1].complete).toEqual(true)+ expect(assistantItems[0].id).not.toEqual(assistantItems[1].id)+ })++ it('keeps text before and after a tool call as separate items in wire order', async () => {+ // Real wire pattern: streamed text, a tool call, then more streamed text — all in one+ // turn with no agent_message finalize between them and no messageId on any chunk.+ const frames: StoredLogEntry[] = [+ sessionUpdate({ sessionUpdate: 'agent_message_chunk', content: { text: 'Let me ' } }),+ sessionUpdate({ sessionUpdate: 'agent_message_chunk', content: { text: 'check.' } }),+ sessionUpdate({+ sessionUpdate: 'tool_call',+ toolCallId: 't1',+ serverName: 'posthog',+ toolName: 'exec',+ rawInput: { command: 'tools' },+ status: 'in_progress',+ }),+ sessionUpdate({ sessionUpdate: 'agent_message_chunk', content: { text: 'All ' } }),+ sessionUpdate({ sessionUpdate: 'agent_message_chunk', content: { text: 'set.' } }),+ ]++ await expectLogic(logic, () => {+ frames.forEach((frame) => logic.actions.ingestAcpFrame(frame))+ }).toFinishAllListeners()++ expect(logic.values.threadItems.map((item) => item.type)).toEqual([+ 'assistant_message',+ 'tool_invocation',+ 'assistant_message',+ ])+ const assistantItems = logic.values.threadItems.filter((item) => item.type === 'assistant_message')+ expect(assistantItems[0].text).toEqual('Let me check.')+ expect(assistantItems[1].text).toEqual('All set.')+ expect(assistantItems[0].id).not.toEqual(assistantItems[1].id)+ })++ it('starts a new bubble for a chunk arriving after finalize instead of mutating the finalized one', async () => {+ const frames: StoredLogEntry[] = [+ sessionUpdate({ sessionUpdate: 'agent_message_chunk', messageId: 'm1', content: { text: 'Done' } }),+ sessionUpdate({ sessionUpdate: 'agent_message', messageId: 'm1', content: { text: 'Done' } }),+ sessionUpdate({ sessionUpdate: 'agent_message_chunk', messageId: 'm1', content: { text: 'More' } }),+ ]++ await expectLogic(logic, () => {+ frames.forEach((frame) => logic.actions.ingestAcpFrame(frame))+ }).toFinishAllListeners()++ const assistantItems = logic.values.threadItems.filter((item) => item.type === 'assistant_message')+ expect(assistantItems).toHaveLength(2)+ expect(assistantItems[0].text).toEqual('Done')+ expect(assistantItems[0].complete).toEqual(true)+ expect(assistantItems[1].text).toEqual('More')+ expect(assistantItems[1].complete).toEqual(false)+ expect(assistantItems[0].id).not.toEqual(assistantItems[1].id)+ })++ it('finalizes the streamed message when chunks carry a messageId but the finalize omits it', async () => {+ // The live wire often streams `agent_message_chunk`s with a messageId but closes the turn+ // with an `agent_message` that has none. The finalize must close the in-flight bubble, not+ // append a second one with the same text.+ const frames: StoredLogEntry[] = [+ sessionUpdate({+ sessionUpdate: 'agent_message_chunk',+ messageId: 'm1',+ content: { text: "I'll query. " },+ }),+ sessionUpdate({+ sessionUpdate: 'agent_message_chunk',+ messageId: 'm1',+ content: { text: 'Loading tools.' },+ }),+ sessionUpdate({ sessionUpdate: 'agent_message', content: { text: "I'll query. Loading tools." } }),+ ]++ await expectLogic(logic, () => {+ frames.forEach((frame) => logic.actions.ingestAcpFrame(frame))+ }).toFinishAllListeners()++ const assistantItems = logic.values.threadItems.filter((item) => item.type === 'assistant_message')+ expect(assistantItems).toHaveLength(1)+ expect(assistantItems[0].text).toEqual("I'll query. Loading tools.")+ expect(assistantItems[0].complete).toEqual(true)+ })++ it('finalizes the streamed message when chunks omit the messageId but the finalize carries it', async () => {+ const frames: StoredLogEntry[] = [+ sessionUpdate({ sessionUpdate: 'agent_message_chunk', content: { text: "I'll query. " } }),+ sessionUpdate({ sessionUpdate: 'agent_message_chunk', content: { text: 'Loading tools.' } }),+ sessionUpdate({+ sessionUpdate: 'agent_message',+ messageId: 'm1',+ content: { text: "I'll query. Loading tools." },+ }),+ ]++ await expectLogic(logic, () => {+ frames.forEach((frame) => logic.actions.ingestAcpFrame(frame))+ }).toFinishAllListeners()++ const assistantItems = logic.values.threadItems.filter((item) => item.type === 'assistant_message')+ expect(assistantItems).toHaveLength(1)+ expect(assistantItems[0].text).toEqual("I'll query. Loading tools.")+ expect(assistantItems[0].complete).toEqual(true)+ })++ it('does not let an id-less finalize reach back across a turn separator', async () => {+ // A finalize with no matching buffer falls back to the in-flight message, but must not+ // close a still-open bubble from a previous turn.+ const frames: StoredLogEntry[] = [+ sessionUpdate({+ sessionUpdate: 'agent_message_chunk',+ messageId: 'm1',+ content: { text: 'First turn' },+ }),+ notification('_posthog/turn_complete', {}),+ sessionUpdate({ sessionUpdate: 'agent_message', content: { text: 'Second turn' } }),+ ]++ await expectLogic(logic, () => {+ frames.forEach((frame) => logic.actions.ingestAcpFrame(frame))+ }).toFinishAllListeners()++ const assistantItems = logic.values.threadItems.filter((item) => item.type === 'assistant_message')+ expect(assistantItems.map((item) => item.text)).toEqual(['First turn', 'Second turn'])+ // The first turn's bubble stayed open (never finalized); the second turn's finalize made+ // its own complete bubble rather than closing the first.+ expect(assistantItems[0].complete).toEqual(false)+ expect(assistantItems[1].complete).toEqual(true)+ })+ })++ describe('agent thought buffering', () => {+ it('folds consecutive thought chunks into one assistant_thought item', async () => {+ const frames: StoredLogEntry[] = [+ sessionUpdate({ sessionUpdate: 'agent_thought_chunk', content: { text: 'Let me ' } }),+ sessionUpdate({ sessionUpdate: 'agent_thought_chunk', content: { text: 'think.' } }),+ ]++ await expectLogic(logic, () => {+ frames.forEach((frame) => logic.actions.ingestAcpFrame(frame))+ }).toFinishAllListeners()++ const thoughtItems = logic.values.threadItems.filter((item) => item.type === 'assistant_thought')+ expect(thoughtItems).toHaveLength(1)+ expect(thoughtItems[0].text).toEqual('Let me think.')+ })++ it('keeps thoughts, messages, and tool calls as separate items in wire order', async () => {+ const frames: StoredLogEntry[] = [+ sessionUpdate({ sessionUpdate: 'agent_thought_chunk', content: { text: 'Checking the data' } }),+ sessionUpdate({ sessionUpdate: 'agent_message_chunk', content: { text: 'Let me look.' } }),+ sessionUpdate({+ sessionUpdate: 'tool_call',+ toolCallId: 't1',+ serverName: 'posthog',+ toolName: 'exec',+ rawInput: { command: 'tools' },+ status: 'in_progress',+ }),+ sessionUpdate({ sessionUpdate: 'agent_thought_chunk', content: { text: 'Now I know.' } }),+ ]++ await expectLogic(logic, () => {+ frames.forEach((frame) => logic.actions.ingestAcpFrame(frame))+ }).toFinishAllListeners()++ expect(logic.values.threadItems.map((item) => item.type)).toEqual([+ 'assistant_thought',+ 'assistant_message',+ 'tool_invocation',+ 'assistant_thought',+ ])+ const thoughtItems = logic.values.threadItems.filter((item) => item.type === 'assistant_thought')+ expect(thoughtItems[0].text).toEqual('Checking the data')+ expect(thoughtItems[1].text).toEqual('Now I know.')+ expect(thoughtItems[0].id).not.toEqual(thoughtItems[1].id)+ })++ it('does not collide thought and message buffers that share the fallback id', async () => {+ const frames: StoredLogEntry[] = [+ sessionUpdate({ sessionUpdate: 'agent_thought_chunk', content: { text: 'Thinking' } }),+ sessionUpdate({ sessionUpdate: 'agent_message_chunk', content: { text: 'Answer' } }),+ ]++ await expectLogic(logic, () => {+ frames.forEach((frame) => logic.actions.ingestAcpFrame(frame))+ }).toFinishAllListeners()++ const thought = logic.values.threadItems.find((item) => item.type === 'assistant_thought')+ const message = logic.values.threadItems.find((item) => item.type === 'assistant_message')+ expect(thought?.text).toEqual('Thinking')+ expect(message?.text).toEqual('Answer')+ expect(thought?.id).not.toEqual(message?.id)+ })+ })++ describe('streamed tool input', () => {+ it('folds rawInput arriving on a later update into a built-in tool call and keeps _meta raw', async () => {+ // Built-ins carry no top-level toolName — the SDK name arrives only on `_meta.claudeCode`.+ const frames: StoredLogEntry[] = [+ sessionUpdate({+ sessionUpdate: 'tool_call',+ toolCallId: 't1',+ title: 'ToolSearch',+ rawInput: {},+ status: 'pending',+ _meta: { claudeCode: { toolName: 'ToolSearch' } },+ }),+ sessionUpdate({+ sessionUpdate: 'tool_call_update',+ toolCallId: 't1',+ rawInput: { query: 'find recordings', max_results: 10 },+ status: 'completed',+ }),+ ]++ await expectLogic(logic, () => {+ frames.forEach((frame) => logic.actions.ingestAcpFrame(frame))+ }).toFinishAllListeners()++ const invocation = logic.values.toolInvocations.get('t1')+ expect(invocation?.input).toEqual({ query: 'find recordings', max_results: 10 })+ expect(invocation?.rawToolName).toEqual('')+ expect(invocation?.meta).toEqual({ claudeCode: { toolName: 'ToolSearch' } })+ })++ it('folds an exec command that streams in after an empty tool_call without resolving it', async () => {+ const frames: StoredLogEntry[] = [+ sessionUpdate({+ sessionUpdate: 'tool_call',+ toolCallId: 't2',+ serverName: 'posthog',+ toolName: 'exec',+ rawInput: {},+ status: 'pending',+ }),+ sessionUpdate({+ sessionUpdate: 'tool_call_update',+ toolCallId: 't2',+ rawInput: { command: 'call insight-create {"name":"Signups"}' },+ status: 'in_progress',+ }),+ ]++ await expectLogic(logic, () => {+ frames.forEach((frame) => logic.actions.ingestAcpFrame(frame))+ }).toFinishAllListeners()++ const invocation = logic.values.toolInvocations.get('t2')+ expect(invocation?.rawServerName).toEqual('posthog')+ expect(invocation?.rawToolName).toEqual('exec')+ expect(invocation?.input).toEqual({ command: 'call insight-create {"name":"Signups"}' })+ })++ it('keeps a subagent inner tool call out of the top-level thread but in the invocation map', async () => {+ const frames: StoredLogEntry[] = [+ sessionUpdate({+ sessionUpdate: 'tool_call',+ toolCallId: 'parent',+ title: 'Task `review`',+ rawInput: { subagent_type: 'code-reviewer', description: 'review', prompt: 'check it' },+ status: 'in_progress',+ _meta: { claudeCode: { toolName: 'Task' } },+ }),+ sessionUpdate({+ sessionUpdate: 'tool_call',+ toolCallId: 'inner',+ title: 'Bash `echo hi`',+ rawInput: { command: 'echo hi' },+ status: 'completed',+ _meta: { claudeCode: { toolName: 'Bash', parentToolCallId: 'parent' } },+ }),+ ]++ await expectLogic(logic, () => {+ frames.forEach((frame) => logic.actions.ingestAcpFrame(frame))+ }).toFinishAllListeners()++ const toolItems = logic.values.threadItems.filter((item) => item.type === 'tool_invocation')+ expect(toolItems).toHaveLength(1)+ expect(toolItems[0]).toEqual({ id: 'parent', type: 'tool_invocation', toolCallId: 'parent' })+ // The inner call is still resolvable (so a parent card could render it) — it just isn't a sibling.+ expect(logic.values.toolInvocations.get('inner')?.title).toEqual('Bash `echo hi`')+ })++ it.each(['Edit', 'TodoWrite', 'Grep', 'Task'])(+ 'keeps a built-in %s tool_call raw despite an empty wire toolName',+ async (sdkName) => {+ const frames: StoredLogEntry[] = [+ sessionUpdate({+ sessionUpdate: 'tool_call',+ toolCallId: 'tb',+ title: `${sdkName} \`foo.ts\``,+ rawInput: {},+ status: 'in_progress',+ _meta: { claudeCode: { toolName: sdkName } },+ }),+ ]++ await expectLogic(logic, () => {+ frames.forEach((frame) => logic.actions.ingestAcpFrame(frame))+ }).toFinishAllListeners()++ const invocation = logic.values.toolInvocations.get('tb')+ expect(invocation?.rawToolName).toEqual('')+ expect(invocation?.meta).toEqual({ claudeCode: { toolName: sdkName } })+ }+ )++ it('keeps the raw input when a later update carries none', async () => {+ const frames: StoredLogEntry[] = [+ sessionUpdate({+ sessionUpdate: 'tool_call',+ toolCallId: 't3',+ serverName: 'posthog',+ toolName: 'exec',+ rawInput: { command: 'call execute-sql {"query":"select 1"}' },+ status: 'in_progress',+ }),+ sessionUpdate({+ sessionUpdate: 'tool_call_update',+ toolCallId: 't3',+ status: 'completed',+ rawOutput: { rows: 1 },+ }),+ ]++ await expectLogic(logic, () => {+ frames.forEach((frame) => logic.actions.ingestAcpFrame(frame))+ }).toFinishAllListeners()++ const invocation = logic.values.toolInvocations.get('t3')+ expect(invocation?.rawToolName).toEqual('exec')+ expect(invocation?.input).toEqual({ command: 'call execute-sql {"query":"select 1"}' })+ })+ })++ describe('pushHumanMessage', () => {+ it('appends a human_message item ordered before subsequently ingested assistant frames', async () => {+ await expectLogic(logic, () => {+ logic.actions.pushHumanMessage('hello agent')+ logic.actions.ingestAcpFrame(+ sessionUpdate({ sessionUpdate: 'agent_message', messageId: 'm1', content: { text: 'Hi!' } })+ )+ }).toFinishAllListeners()++ expect(logic.values.threadItems).toHaveLength(2)+ expect(logic.values.threadItems[0]).toEqual({+ id: 'human-0',+ type: 'human_message',+ text: 'hello agent',+ complete: true,+ })+ expect(logic.values.threadItems[1].type).toEqual('assistant_message')+ })+ })++ describe('_posthog/user_message rendering', () => {+ it('renders a seeded user turn into the thread on bootstrap replay', async () => {+ const frames: StoredLogEntry[] = [+ notification('_posthog/user_message', { content: 'Why did checkout drop?' }),+ sessionUpdate({ sessionUpdate: 'agent_message', messageId: 'm1', content: { text: 'Let me check.' } }),+ ]+ jest.spyOn(api.tasks.runs, 'getLogEntries').mockResolvedValue(frames as any)+ jest.spyOn(api.tasks.runs, 'get').mockResolvedValue({ status: 'completed' } as any)++ await expectLogic(logic, () => {+ logic.actions.bootstrapRun({ taskId: 'task-1', runId: 'run-1' })+ }).toFinishAllListeners()++ // Both the human question and the assistant reply must render, in order.+ expect(logic.values.threadItems).toHaveLength(2)+ expect(logic.values.threadItems[0]).toEqual({+ id: 'human-0',+ type: 'human_message',+ text: 'Why did checkout drop?',+ complete: true,+ })+ expect(logic.values.threadItems[1].type).toEqual('assistant_message')+ })++ it('extracts text from ACP content blocks', async () => {+ const frames: StoredLogEntry[] = [+ notification('_posthog/user_message', {+ content: [+ { type: 'text', text: 'first ' },+ { type: 'text', text: 'second' },+ ],+ }),+ ]+ jest.spyOn(api.tasks.runs, 'getLogEntries').mockResolvedValue(frames as any)+ jest.spyOn(api.tasks.runs, 'get').mockResolvedValue({ status: 'completed' } as any)++ await expectLogic(logic, () => {+ logic.actions.bootstrapRun({ taskId: 'task-1', runId: 'run-1' })+ }).toFinishAllListeners()++ expect(logic.values.threadItems).toHaveLength(1)+ expect(logic.values.threadItems[0]).toMatchObject({ type: 'human_message', text: 'first second' })+ })++ it('strips the posthog_context wrapper so a replayed prompt matches the live one', async () => {+ const wrapped =+ '<posthog_context>\nThe user attached the following PostHog entities.\n- Insight #1\n</posthog_context>\n\nWhy did signups drop?'+ const frames: StoredLogEntry[] = [notification('_posthog/user_message', { content: wrapped })]+ jest.spyOn(api.tasks.runs, 'getLogEntries').mockResolvedValue(frames as any)+ jest.spyOn(api.tasks.runs, 'get').mockResolvedValue({ status: 'completed' } as any)++ await expectLogic(logic, () => {+ logic.actions.bootstrapRun({ taskId: 'task-1', runId: 'run-1' })+ }).toFinishAllListeners()++ expect(logic.values.threadItems.find((item) => item.type === 'human_message')?.text).toEqual(+ 'Why did signups drop?'+ )+ })++ it('renders a live (non-replay) user_message frame with no optimistic echo (queue drain)', async () => {+ await expectLogic(logic, () => {+ logic.actions.ingestAcpFrame(notification('_posthog/user_message', { content: 'drained message' }))+ }).toFinishAllListeners()++ expect(logic.values.threadItems).toHaveLength(1)+ expect(logic.values.threadItems[0]).toMatchObject({ type: 'human_message', text: 'drained message' })+ })++ it('does not double a live user_message frame already echoed optimistically on send', async () => {+ await expectLogic(logic, () => {+ logic.actions.pushHumanMessage('hello agent')+ logic.actions.ingestAcpFrame(notification('_posthog/user_message', { content: 'hello agent' }))+ }).toFinishAllListeners()++ expect(logic.values.threadItems.filter((item) => item.type === 'human_message')).toHaveLength(1)+ })++ // The backend persists the human turn as a session/update `user_message_chunk`, not a+ // `_posthog/user_message` ext-notification — this is the frame a thread actually loads from logs.+ it('renders a persisted user_message_chunk session update on bootstrap replay', async () => {+ const frames: StoredLogEntry[] = [+ sessionUpdate({+ sessionUpdate: 'user_message_chunk',+ content: { type: 'text', text: 'what posthog tools do you have?' },+ }),+ sessionUpdate({ sessionUpdate: 'agent_message', messageId: 'm1', content: { text: 'Several.' } }),+ ]+ jest.spyOn(api.tasks.runs, 'getLogEntries').mockResolvedValue(frames as any)+ jest.spyOn(api.tasks.runs, 'get').mockResolvedValue({ status: 'completed' } as any)++ await expectLogic(logic, () => {+ logic.actions.bootstrapRun({ taskId: 'task-1', runId: 'run-1' })+ }).toFinishAllListeners()++ expect(logic.values.threadItems).toHaveLength(2)+ expect(logic.values.threadItems[0]).toEqual({+ id: 'human-0',+ type: 'human_message',+ text: 'what posthog tools do you have?',+ complete: true,+ })+ expect(logic.values.threadItems[1].type).toEqual('assistant_message')+ })++ it('renders a legacy notification-only user message and suppresses resume prompt echoes', async () => {+ const resumePrompt =+ 'You are resuming a previous conversation. Here is the conversation history. Continue from where you left off.'+ const frames: unknown[] = [+ notification('session/update', {+ sessionId: 'ancestor-session',+ update: {+ sessionUpdate: 'user_message_chunk',+ content: { type: 'text', text: "what's my pageview count" },+ },+ }),+ notification('_posthog/console', { sessionId: 'run-1', level: 'debug', message: 'Starting resume' }),+ legacyNotification('_posthog/user_message', {+ content: 'break down by a country',+ _meta: { attached_context: [] },+ }),+ notification('_posthog/sdk_session', {+ taskRunId: 'run-1',+ sessionId: 'acp-session-1',+ adapter: 'claude',+ }),+ notification('_posthog/run_started', {+ runId: 'run-1',+ taskId: 'task-1',+ sessionId: 'acp-session-1',+ }),+ sessionPrompt(resumePrompt, 'acp-session-1'),+ notification('session/update', {+ sessionId: 'acp-session-1',+ update: {+ sessionUpdate: 'user_message_chunk',+ content: { type: 'text', text: resumePrompt },+ },+ }),+ sessionPrompt('break down by a country', 'acp-session-1'),+ notification('session/update', {+ sessionId: 'acp-session-1',+ update: {+ sessionUpdate: 'user_message_chunk',+ content: { type: 'text', text: 'break down by a country' },+ },+ }),+ sessionUpdate({ sessionUpdate: 'agent_message', messageId: 'm1', content: { text: 'Here you go.' } }),+ ]+ jest.spyOn(api.tasks.runs, 'getLogEntries').mockResolvedValue(frames as any)+ jest.spyOn(api.tasks.runs, 'get').mockResolvedValue({+ status: 'completed',+ state: { resume_from_run_id: 'ancestor-run' },+ } as any)++ await expectLogic(logic, () => {+ logic.actions.bootstrapRun({ taskId: 'task-1', runId: 'run-1' })+ }).toFinishAllListeners()++ expect(+ logic.values.threadItems.filter((item) => item.type === 'human_message').map((item) => item.text)+ ).toEqual(["what's my pageview count", 'break down by a country'])+ expect(+ logic.values.threadItems.some((item) => item.type === 'human_message' && item.text === resumePrompt)+ ).toBe(false)+ expect(logic.values.threadItems.find((item) => item.type === 'assistant_message')?.text).toEqual(+ 'Here you go.'+ )+ })++ it('hides a resume prompt with no canonical user message on bootstrap replay', async () => {+ const resumePrompt =+ 'You are resuming a previous conversation. Here is the conversation history. Continue from where you left off.'+ const frames: StoredLogEntry[] = [+ notification('_posthog/console', { sessionId: 'run-1', level: 'debug', message: 'Starting resume' }),+ notification('_posthog/sdk_session', {+ taskRunId: 'run-1',+ sessionId: 'acp-session-1',+ adapter: 'claude',+ }),+ notification('_posthog/run_started', {+ runId: 'run-1',+ taskId: 'task-1',+ sessionId: 'acp-session-1',+ }),+ sessionPrompt(resumePrompt, 'acp-session-1'),+ notification('session/update', {+ sessionId: 'acp-session-1',+ update: {+ sessionUpdate: 'user_message_chunk',+ content: { type: 'text', text: resumePrompt },+ },+ }),+ sessionUpdate({ sessionUpdate: 'agent_message', messageId: 'm1', content: { text: 'Continuing.' } }),+ ]+ jest.spyOn(api.tasks.runs, 'getLogEntries').mockResolvedValue(frames as any)+ jest.spyOn(api.tasks.runs, 'get').mockResolvedValue({+ status: 'completed',+ state: { resume_from_run_id: 'ancestor-run' },+ } as any)++ await expectLogic(logic, () => {+ logic.actions.bootstrapRun({ taskId: 'task-1', runId: 'run-1' })+ }).toFinishAllListeners()++ expect(logic.values.threadItems.some((item) => item.type === 'human_message')).toBe(false)+ expect(logic.values.threadItems.find((item) => item.type === 'assistant_message')?.text).toEqual(+ 'Continuing.'+ )+ })++ it('places replayed setup progress below the human turn it belongs to', async () => {+ const frames: StoredLogEntry[] = [+ notification('_posthog/progress', {+ sessionId: 's',+ step: 'agent',+ status: 'completed',+ label: 'Started agent',+ group: 'setup:run-1',+ }),+ sessionUpdate({+ sessionUpdate: 'user_message_chunk',+ content: { type: 'text', text: 'build me a dashboard' },+ }),+ ]+ jest.spyOn(api.tasks.runs, 'getLogEntries').mockResolvedValue(frames as any)+ jest.spyOn(api.tasks.runs, 'get').mockResolvedValue({ status: 'completed' } as any)++ await expectLogic(logic, () => {+ logic.actions.bootstrapRun({ taskId: 'task-1', runId: 'run-1' })+ }).toFinishAllListeners()++ expect(logic.values.threadItems.map((item) => item.type)).toEqual(['human_message', 'progress'])+ expect(logic.values.threadItems[0]).toMatchObject({+ type: 'human_message',+ text: 'build me a dashboard',+ })+ expect(logic.values.threadItems[1]).toMatchObject({+ type: 'progress',+ progressSteps: [{ key: 'agent', status: 'completed', label: 'Started agent' }],+ })+ })++ it('renders a live (non-replay) user_message_chunk with no optimistic echo (queue drain)', async () => {+ await expectLogic(logic, () => {+ logic.actions.ingestAcpFrame(+ sessionUpdate({ sessionUpdate: 'user_message_chunk', content: { type: 'text', text: 'drained' } })+ )+ }).toFinishAllListeners()++ expect(logic.values.threadItems).toHaveLength(1)+ expect(logic.values.threadItems[0]).toMatchObject({ type: 'human_message', text: 'drained' })+ })++ it('dedupes a drained send echoed in both user_message wire forms into one bubble', async () => {+ await expectLogic(logic, () => {+ logic.actions.ingestAcpFrame(notification('_posthog/user_message', { content: 'drained' }))+ logic.actions.ingestAcpFrame(+ sessionUpdate({ sessionUpdate: 'user_message_chunk', content: { type: 'text', text: 'drained' } })+ )+ }).toFinishAllListeners()++ expect(logic.values.threadItems.filter((item) => item.type === 'human_message')).toHaveLength(1)+ })+ })++ describe('per-conversation isolation', () => {+ it('keeps thread state independent between two mounted conversations', async () => {+ const otherLogic = sandboxStreamLogic({ streamKey: 'other-conversation' })+ otherLogic.mount()++ await expectLogic(logic, () => {+ logic.actions.pushHumanMessage('hello agent')+ logic.actions.ingestAcpFrame(+ sessionUpdate({ sessionUpdate: 'agent_message', messageId: 'm1', content: { text: 'Hi!' } })+ )+ }).toFinishAllListeners()++ expect(logic.values.threadItems).toHaveLength(2)+ expect(otherLogic.values.threadItems).toHaveLength(0)++ otherLogic.unmount()+ })+ })++ describe('tool call errors', () => {+ it('populates error from a failed tool_call_update carrying an error message', async () => {+ const frames: StoredLogEntry[] = [+ sessionUpdate({+ sessionUpdate: 'tool_call',+ toolCallId: 't1',+ serverName: 'posthog',+ toolName: 'exec',+ rawInput: { command: 'tools' },+ status: 'in_progress',+ }),+ sessionUpdate({+ sessionUpdate: 'tool_call_update',+ toolCallId: 't1',+ status: 'failed',+ error: { message: 'command exploded' },+ }),+ ]++ await expectLogic(logic, () => {+ frames.forEach((frame) => logic.actions.ingestAcpFrame(frame))+ }).toFinishAllListeners()++ const invocation = logic.values.toolInvocations.get('t1')+ expect(invocation?.status).toEqual('failed')+ expect(invocation?.error?.message).toEqual('command exploded')+ })++ it('falls back to the notification-level error when a failed update has none', async () => {+ const frames: StoredLogEntry[] = [+ sessionUpdate({+ sessionUpdate: 'tool_call',+ toolCallId: 't2',+ serverName: 'posthog',+ toolName: 'exec',+ rawInput: { command: 'tools' },+ status: 'in_progress',+ }),+ {+ type: 'notification',+ notification: {+ method: 'session/update',+ params: { update: { sessionUpdate: 'tool_call_update', toolCallId: 't2', status: 'failed' } },+ error: { message: 'sandbox crashed' },+ },+ },+ ]++ await expectLogic(logic, () => {+ frames.forEach((frame) => logic.actions.ingestAcpFrame(frame))+ }).toFinishAllListeners()++ expect(logic.values.toolInvocations.get('t2')?.error?.message).toEqual('sandbox crashed')+ })++ it('surfaces the _meta.claudeCode denial reason on a failed update with no explicit error', async () => {+ const frames: StoredLogEntry[] = [+ sessionUpdate({+ sessionUpdate: 'tool_call',+ toolCallId: 't3',+ title: 'Edit `foo.ts`',+ rawInput: {},+ status: 'in_progress',+ _meta: { claudeCode: { toolName: 'Edit' } },+ }),+ sessionUpdate({+ sessionUpdate: 'tool_call_update',+ toolCallId: 't3',+ status: 'failed',+ content: [+ { type: 'content', content: { type: 'text', text: 'Permission denied: writes blocked' } },+ ],+ _meta: {+ claudeCode: {+ toolName: 'Edit',+ toolResponse: {+ decisionReason: 'Edits are not allowed in read-only mode',+ decisionReasonType: 'policy',+ message: 'denied',+ },+ },+ },+ }),+ ]++ await expectLogic(logic, () => {+ frames.forEach((frame) => logic.actions.ingestAcpFrame(frame))+ }).toFinishAllListeners()++ const invocation = logic.values.toolInvocations.get('t3')+ expect(invocation?.status).toEqual('failed')+ expect(invocation?.error?.message).toEqual('Edits are not allowed in read-only mode')+ })++ it('upserts a renderable invocation from a terminal update whose tool_call frame was lost', async () => {+ // A reconnect with ?start=latest can drop the creating frame; the terminal update must+ // still render a card, and must not fire completion telemetry with an undefined name.+ const captureSpy = jest.spyOn(posthog, 'capture').mockImplementation(() => undefined as any)++ await expectLogic(logic, () => {+ logic.actions.ingestAcpFrame(+ sessionUpdate({ sessionUpdate: 'tool_call_update', toolCallId: 'orphan', status: 'completed' })+ )+ }).toFinishAllListeners()++ expect(logic.values.toolInvocations.get('orphan')?.status).toEqual('completed')+ expect(logic.values.threadItems.some((item) => item.toolCallId === 'orphan')).toEqual(true)+ expect(captureSpy.mock.calls.filter((c) => c[0] === 'tool_call_completed')).toHaveLength(0)+ })++ it('does not throw and keeps no error on the inline-denial path (failed, no _meta)', async () => {+ const frames: StoredLogEntry[] = [+ sessionUpdate({+ sessionUpdate: 'tool_call',+ toolCallId: 't4',+ title: 'Bash `rm -rf`',+ rawInput: {},+ status: 'in_progress',+ _meta: { claudeCode: { toolName: 'Bash' } },+ }),+ sessionUpdate({+ sessionUpdate: 'tool_call_update',+ toolCallId: 't4',+ status: 'failed',+ content: [+ { type: 'content', content: { type: 'text', text: 'User refused permission to run Bash' } },+ ],+ }),+ ]++ await expectLogic(logic, () => {+ frames.forEach((frame) => logic.actions.ingestAcpFrame(frame))+ }).toFinishAllListeners()++ const invocation = logic.values.toolInvocations.get('t4')+ expect(invocation?.status).toEqual('failed')+ // No _meta and no explicit error → the renderer falls back to the content text; no error.message synthesized.+ expect(invocation?.error?.message).toBeUndefined()+ expect(invocation?.contentBlocks).toHaveLength(1)+ })+ })++ describe('chunk folding', () => {+ it('folds distinct chunks of the same message into one growing buffer', async () => {+ await expectLogic(logic, () => {+ logic.actions.ingestAcpFrame(+ sessionUpdate({ sessionUpdate: 'agent_message_chunk', messageId: 'm1', content: { text: 'A' } })+ )+ logic.actions.ingestAcpFrame(+ sessionUpdate({ sessionUpdate: 'agent_message_chunk', messageId: 'm1', content: { text: 'B' } })+ )+ }).toFinishAllListeners()++ const assistantItem = logic.values.threadItems.find((item) => item.type === 'assistant_message')+ expect(assistantItem?.text).toEqual('AB')+ })++ it('keeps two chunks with identical text instead of collapsing them', async () => {+ // A repeated identical token is real content, not a duplicate — the append-only log keeps+ // both and they fold into one growing buffer (no per-frame content dedup at ingest).+ await expectLogic(logic, () => {+ logic.actions.ingestAcpFrame(+ sessionUpdate({ sessionUpdate: 'agent_message_chunk', messageId: 'm1', content: { text: 'tok ' } })+ )+ logic.actions.ingestAcpFrame(+ sessionUpdate({ sessionUpdate: 'agent_message_chunk', messageId: 'm1', content: { text: 'tok ' } })+ )+ }).toFinishAllListeners()++ const assistant = logic.values.threadItems.find((item) => item.type === 'assistant_message')+ expect(assistant?.text).toEqual('tok tok ')+ expect(logic.values.log.entries).toHaveLength(2)+ })+ })++ describe('assistant message id uniqueness', () => {+ it('assigns unique ids to no-messageId finalized messages across turns (no React key collision)', async () => {+ // S3 replay drops `agent_message_chunk`, so each prior turn arrives as a bare finalized+ // `agent_message` with no `messageId` — they all fall back to the same id base. Each must+ // still get a unique thread-item id, or they collide as React keys and render duplicated.+ const frames: StoredLogEntry[] = [+ sessionUpdate({ sessionUpdate: 'agent_message', content: { text: 'first answer' } }),+ notification('_posthog/turn_complete', {}),+ sessionUpdate({ sessionUpdate: 'agent_message', content: { text: 'second answer' } }),+ notification('_posthog/turn_complete', {}),+ sessionUpdate({ sessionUpdate: 'agent_message', content: { text: 'third answer' } }),+ ]++ await expectLogic(logic, () => {+ frames.forEach((frame) => logic.actions.ingestAcpFrame(frame, 'replay'))+ }).toFinishAllListeners()++ const assistants = logic.values.threadItems.filter((item) => item.type === 'assistant_message')+ expect(assistants.map((item) => item.text)).toEqual(['first answer', 'second answer', 'third answer'])+ const ids = assistants.map((item) => item.id)+ expect(new Set(ids).size).toEqual(ids.length)+ })++ it('assigns unique ids to no-messageId chunked messages across turns', async () => {+ // The live path: each turn streams chunks with no `messageId` (so the same `current` base),+ // closed by a finalize. Distinct turns must still produce distinct bubble ids.+ const frames: StoredLogEntry[] = [+ sessionUpdate({ sessionUpdate: 'agent_message_chunk', content: { text: 'one' } }),+ sessionUpdate({ sessionUpdate: 'agent_message', content: { text: 'one' } }),+ notification('_posthog/turn_complete', {}),+ sessionUpdate({ sessionUpdate: 'agent_message_chunk', content: { text: 'two' } }),+ sessionUpdate({ sessionUpdate: 'agent_message', content: { text: 'two' } }),+ ]++ await expectLogic(logic, () => {+ frames.forEach((frame) => logic.actions.ingestAcpFrame(frame, 'live'))+ }).toFinishAllListeners()++ const assistants = logic.values.threadItems.filter((item) => item.type === 'assistant_message')+ expect(assistants.map((item) => item.text)).toEqual(['one', 'two'])+ const ids = assistants.map((item) => item.id)+ expect(new Set(ids).size).toEqual(ids.length)+ })+ })++ describe('resume-context filter (§6)', () => {+ it('drops the synthetic resume-context prompt on a resume run but keeps the genuine turn (§6)', async () => {+ const resumePrompt =+ 'You are resuming a previous conversation. Here is the conversation history. Continue from where you left off.'+ const frames: StoredLogEntry[] = [+ notification('_posthog/run_started', { runId: 'run-1', sessionId: 'acp-1' }),+ sessionUpdate({ sessionUpdate: 'user_message_chunk', content: { type: 'text', text: resumePrompt } }),+ sessionUpdate({+ sessionUpdate: 'user_message_chunk',+ content: { type: 'text', text: 'break it down by country' },+ }),+ ]+ jest.spyOn(api.tasks.runs, 'getLogEntries').mockResolvedValue(frames as any)+ jest.spyOn(api.tasks.runs, 'get').mockResolvedValue({+ status: 'completed',+ state: { resume_from_run_id: 'run-0' },+ } as any)++ await expectLogic(logic, () => {+ logic.actions.bootstrapRun({ taskId: 'task-1', runId: 'run-1' })+ }).toFinishAllListeners()++ expect(+ logic.values.threadItems.filter((item) => item.type === 'human_message').map((item) => item.text)+ ).toEqual(['break it down by country'])+ })++ it('keeps a "You are resuming…" message when the run is NOT a resume run (gate is resume-only)', async () => {+ const looksLikeResume = 'You are resuming a previous conversation. (but the user actually typed this)'+ const frames: StoredLogEntry[] = [+ notification('_posthog/run_started', { runId: 'run-1' }),+ sessionUpdate({+ sessionUpdate: 'user_message_chunk',+ content: { type: 'text', text: looksLikeResume },+ }),+ ]+ jest.spyOn(api.tasks.runs, 'getLogEntries').mockResolvedValue(frames as any)+ jest.spyOn(api.tasks.runs, 'get').mockResolvedValue({ status: 'completed' } as any)++ await expectLogic(logic, () => {+ logic.actions.bootstrapRun({ taskId: 'task-1', runId: 'run-1' })+ }).toFinishAllListeners()++ expect(+ logic.values.threadItems.filter((item) => item.type === 'human_message').map((item) => item.text)+ ).toEqual([looksLikeResume])+ })+ })++ describe('error mapping', () => {+ it('maps HTTP statuses to error envelopes', () => {+ expect(mapHttpStatusToStreamError(401)).toEqual({+ errorTitle: 'Cloud authentication expired',+ retryable: true,+ })+ expect(mapHttpStatusToStreamError(403)).toEqual({ errorTitle: 'Cloud access denied', retryable: true })+ expect(mapHttpStatusToStreamError(404)).toEqual({+ errorTitle: 'Conversation backing run not found',+ retryable: false,+ })+ expect(mapHttpStatusToStreamError(406)).toEqual({+ errorTitle: 'Cloud stream unavailable',+ retryable: true,+ })+ expect(mapHttpStatusToStreamError(500)).toEqual({ errorTitle: 'Cloud stream failed', retryable: true })+ expect(mapHttpStatusToStreamError(undefined)).toEqual({+ errorTitle: 'Cloud stream failed',+ retryable: true,+ })+ })++ it('caps the backoff schedule at 2s/4s/8s/16s/30s', () => {+ expect([1, 2, 3, 4, 5].map(reconnectDelayMs)).toEqual([2000, 4000, 8000, 16000, 30000])+ expect(reconnectDelayMs(6)).toEqual(SSE_RECONNECT_MAX_DELAY_MS)+ })++ it('surfaces a named event:error frame verbatim', async () => {+ logic.actions.openSseForRun({ taskId: 'task-1', runId: 'run-1' })++ await MockStream.latest().emitErrorFrame({+ errorTitle: 'Sandbox crashed',+ errorMessage: 'boom',+ retryable: false,+ })++ expect(logic.values.sseStatus).toEqual('error')+ })+ })++ describe('isThinking', () => {+ it('is on only while a started turn is incomplete, surviving non-terminal status updates', () => {+ expect(logic.values.isThinking).toEqual(false)++ logic.actions.ingestAcpFrame(notification('_posthog/run_started', {}))+ expect(logic.values.isThinking).toEqual(true)++ logic.actions.handleTerminalStatus({ status: 'queued' })+ expect(logic.values.isThinking).toEqual(true)++ logic.actions.ingestAcpFrame(notification('_posthog/turn_complete', {}))+ expect(logic.values.isThinking).toEqual(false)+ })++ it.each([+ ['a terminal run status', (): void => logic.actions.handleTerminalStatus({ status: 'failed' })],+ ['a stream error', (): void => logic.actions.handleStreamError({ errorTitle: 'x', retryable: true })],+ ])('turns off on %s even when turn_complete never arrives', (_case, act) => {+ logic.actions.ingestAcpFrame(notification('_posthog/run_started', {}))+ expect(logic.values.isThinking).toEqual(true)++ act()+ expect(logic.values.isThinking).toEqual(false)+ })++ it('re-raises on a follow-up turn opened by a human message, with no new run_started', () => {+ logic.actions.ingestAcpFrame(notification('_posthog/run_started', {}))+ logic.actions.ingestAcpFrame(notification('_posthog/turn_complete', {}))+ expect(logic.values.isThinking).toEqual(false)++ // A follow-up on the same run starts a new turn — no second run_started frame arrives.+ logic.actions.pushHumanMessage('and the mobile funnel?')+ expect(logic.values.isThinking).toEqual(true)+ })++ it('is on during the cold-boot queued window before the first run_started', async () => {+ await expectLogic(logic, () => {+ logic.actions.openSseForRun({ taskId: 'task-1', runId: 'run-1' })+ }).toFinishAllListeners()++ // currentRunStatus is 'queued' and runStarted is still false — the indicator must show.+ expect(logic.values.currentRunStatus).toEqual('queued')+ expect(logic.values.isThinking).toEqual(true)+ })+ })++ describe('terminal-status handling', () => {+ it('closes the SSE and stops reconnects on a terminal task_run_state', async () => {+ logic.actions.openSseForRun({ taskId: 'task-1', runId: 'run-1' })+ const source = MockStream.latest()+ await source.emitOpen()++ await expectLogic(logic, () => {+ logic.actions.handleTerminalStatus({ status: 'completed' })+ }).toFinishAllListeners()++ expect(logic.values.currentRunStatus).toEqual('completed')+ expect(source.closed).toEqual(true)+ })++ it('keeps the stream open on a non-terminal task_run_state', async () => {+ logic.actions.openSseForRun({ taskId: 'task-1', runId: 'run-1' })+ const source = MockStream.latest()+ await source.emitOpen()++ await expectLogic(logic, () => {+ logic.actions.handleTerminalStatus({ status: 'in_progress' })+ }).toFinishAllListeners()++ expect(logic.values.currentRunStatus).toEqual('in_progress')+ expect(source.closed).toEqual(false)+ })+ })++ describe('runArtifacts (git context)', () => {+ const PR_URL = 'https://github.com/PostHog/posthog/pull/123'++ it('mergeRunArtifacts is latest-wins and ignores undefined/empty values', () => {+ const base = mergeRunArtifacts({}, { branch: 'feat/a', baseBranch: 'master' })+ expect(base).toEqual({ branch: 'feat/a', baseBranch: 'master' })++ // A later non-empty value overwrites; undefined/empty fields leave the prior value intact.+ const next = mergeRunArtifacts(base, { branch: 'feat/b', baseBranch: undefined, prUrl: '' })+ expect(next).toEqual({ branch: 'feat/b', baseBranch: 'master' })+ })++ it('extractRunArtifacts reads branch/base/pr from a bootstrap run and a live frame', () => {+ expect(+ extractRunArtifacts({+ branch: 'feat/x',+ state: { pr_base_branch: 'master', repository: 'PostHog/posthog' },+ output: { pr_url: PR_URL },+ })+ ).toEqual({ branch: 'feat/x', baseBranch: 'master', repo: 'PostHog/posthog', prUrl: PR_URL })++ // A live task_run_state frame has no `state`, so only branch + pr_url are extracted.+ expect(extractRunArtifacts({ branch: 'feat/x', output: { pr_url: PR_URL } })).toEqual({+ branch: 'feat/x',+ prUrl: PR_URL,+ })+ })++ it('captures branch / base / pr from the bootstrap run fetch', async () => {+ jest.spyOn(api.tasks.runs, 'getLogEntries').mockResolvedValue([] as any)+ jest.spyOn(api.tasks.runs, 'get').mockResolvedValue({+ status: 'completed',+ branch: 'feat/posthog-ai-sandboxes',+ state: { pr_base_branch: 'master' },+ output: { pr_url: PR_URL },+ } as any)++ await expectLogic(logic, () => {+ logic.actions.bootstrapRun({ taskId: 'task-1', runId: 'run-1' })+ }).toFinishAllListeners()++ expect(logic.values.runArtifacts).toEqual({+ branch: 'feat/posthog-ai-sandboxes',+ baseBranch: 'master',+ prUrl: PR_URL,+ })+ expect(logic.values.hasGitArtifacts).toBe(true)+ })++ it('captures the pr url from a live task_run_state frame', async () => {+ logic.actions.openSseForRun({ taskId: 'task-1', runId: 'run-1' })+ await MockStream.latest().emitOpen()++ await expectLogic(logic, async () => {+ await MockStream.latest().emitMessage({+ type: 'task_run_state',+ status: 'in_progress',+ branch: 'feat/x',+ output: { pr_url: PR_URL },+ })+ }).toFinishAllListeners()++ expect(logic.values.runArtifacts).toMatchObject({ branch: 'feat/x', prUrl: PR_URL })+ expect(logic.values.hasGitArtifacts).toBe(true)+ })++ it('stays empty and self-hideable for a run with no git context', async () => {+ jest.spyOn(api.tasks.runs, 'getLogEntries').mockResolvedValue([] as any)+ jest.spyOn(api.tasks.runs, 'get').mockResolvedValue({ status: 'completed' } as any)++ await expectLogic(logic, () => {+ logic.actions.bootstrapRun({ taskId: 'task-1', runId: 'run-1' })+ }).toFinishAllListeners()++ expect(logic.values.runArtifacts).toEqual({})+ expect(logic.values.hasGitArtifacts).toBe(false)+ })++ it('clears runArtifacts on reset', async () => {+ await expectLogic(logic, () => {+ logic.actions.mergeRunArtifacts({ branch: 'feat/x', prUrl: PR_URL })+ }).toFinishAllListeners()+ expect(logic.values.hasGitArtifacts).toBe(true)++ await expectLogic(logic, () => {+ logic.actions.reset()+ }).toFinishAllListeners()+ expect(logic.values.runArtifacts).toEqual({})+ expect(logic.values.hasGitArtifacts).toBe(false)+ })+ })++ describe('reconnect / backoff', () => {+ it('refetches and surfaces terminal status on a drop, without reopening', async () => {+ const getSpy = jest.spyOn(api.tasks.runs, 'get').mockResolvedValue({ status: 'completed' } as any)++ logic.actions.openSseForRun({ taskId: 'task-1', runId: 'run-1' })+ await MockStream.latest().emitOpen()++ const beforeDrop = MockStream.connections.length+ logic.actions.sseDropped()+ await flushPromises()++ expect(getSpy).toHaveBeenCalledWith('task-1', 'run-1')+ expect(logic.values.currentRunStatus).toEqual('completed')+ // No new connection was opened (terminal → no reconnect).+ expect(MockStream.connections.length).toEqual(beforeDrop)+ })++ it('backs off and reopens on a drop while the run is non-terminal', async () => {+ jest.spyOn(api.tasks.runs, 'get').mockResolvedValue({ status: 'in_progress' } as any)++ logic.actions.openSseForRun({ taskId: 'task-1', runId: 'run-1' })+ await MockStream.latest().emitOpen()+ const beforeDrop = MockStream.connections.length++ jest.useFakeTimers()+ logic.actions.sseDropped()+ await flushPromises()++ expect(logic.values.sseStatus).toEqual('reconnecting')+ expect(logic.values.reconnectAttempt).toEqual(1)++ jest.advanceTimersByTime(2000)+ expect(MockStream.connections.length).toEqual(beforeDrop + 1)+ // No frame carried an id before the drop, so there's nothing to resume from — the reopen+ // requests start=latest (only new frames) rather than re-broadcasting the whole stream.+ expect(MockStream.latest().options.startLatest).toEqual(true)+ expect(MockStream.latest().options.lastEventId).toBeUndefined()+ jest.useRealTimers()+ })++ it('resumes from the last-seen event id via the Last-Event-ID header on reconnect', async () => {+ jest.spyOn(api.tasks.runs, 'get').mockResolvedValue({ status: 'in_progress' } as any)++ logic.actions.openSseForRun({ taskId: 'task-1', runId: 'run-1' })+ // A live frame stamps its Redis stream id as the resume cursor.+ await MockStream.latest().emitMessage(notification('_posthog/run_started', {}), '1700-0')++ jest.useFakeTimers()+ logic.actions.sseDropped()+ await flushPromises()+ jest.advanceTimersByTime(2000)++ // The reconnect resumes exactly after the last-seen frame — header set, no start=latest.+ expect(MockStream.latest().options.lastEventId).toEqual('1700-0')+ jest.useRealTimers()+ })++ it('preserves a known in-flight status when the reconnect reopens the stream', async () => {+ logic.actions.openSseForRun({ taskId: 'task-1', runId: 'run-1' })+ logic.actions.handleTerminalStatus({ status: 'in_progress' })+ logic.actions.openSseForRun({ taskId: 'task-1', runId: 'run-1', startLatest: false })++ expect(logic.values.currentRunStatus).toEqual('in_progress')+ })++ it('abandons the drop loop when the stream is closed mid-refetch', async () => {+ let resolveGet: (value: unknown) => void = () => {}+ jest.spyOn(api.tasks.runs, 'get').mockReturnValue(new Promise((resolve) => (resolveGet = resolve)) as any)++ logic.actions.openSseForRun({ taskId: 'task-1', runId: 'run-1' })+ logic.actions.sseDropped()+ logic.actions.closeSse()++ resolveGet({ status: 'in_progress' })+ await flushPromises()++ expect(logic.values.sseStatus).toEqual('closed')+ expect(logic.values.reconnectAttempt).toEqual(0)+ })++ it('surfaces a retryable error after exhausting the attempt cap', async () => {+ jest.spyOn(api.tasks.runs, 'get').mockResolvedValue({ status: 'in_progress' } as any)++ logic.actions.openSseForRun({ taskId: 'task-1', runId: 'run-1' })+ // Drive the attempt counter to the cap without an intervening successful open.+ logic.actions.sseReconnecting(MAX_SSE_RECONNECT_ATTEMPTS)++ logic.actions.sseDropped()+ await flushPromises()++ expect(logic.values.sseStatus).toEqual('error')+ })++ it('maps a refetch failure through the HTTP-status table', async () => {+ jest.spyOn(api.tasks.runs, 'get').mockRejectedValue({ status: 404 })++ logic.actions.openSseForRun({ taskId: 'task-1', runId: 'run-1' })+ logic.actions.sseDropped()+ await flushPromises()++ expect(logic.values.sseStatus).toEqual('error')+ })+ })++ describe('connection teardown', () => {+ // The keyed log store makes duplicate ingestion idempotent, so correctness no longer depends+ // on closing the exact connection a hot reload orphaned (the old EventSource registry is+ // gone). Teardown still aborts the active fetch so it stops streaming.+ it('aborts the active stream on closeSse', () => {+ logic.actions.openSseForRun({ taskId: 'task-1', runId: 'run-1' })+ const source = MockStream.latest()++ logic.actions.closeSse()++ expect(source.closed).toEqual(true)+ })++ it('aborts the active stream on reset', () => {+ logic.actions.openSseForRun({ taskId: 'task-1', runId: 'run-1' })+ const source = MockStream.latest()++ logic.actions.reset()++ expect(source.closed).toEqual(true)+ })+ })++ describe('bootstrapRun', () => {+ it('skips logs/ and opens SSE directly on the fresh-run fast path', async () => {+ const logsSpy = jest.spyOn(api.tasks.runs, 'getLogEntries')++ logic.actions.bootstrapRun({ taskId: 'task-1', runId: 'run-1', justCreatedRun: true })+ await flushPromises()++ expect(logsSpy).not.toHaveBeenCalled()+ expect(MockStream.connections.length).toEqual(1)+ expect(MockStream.latest().options.startLatest).toEqual(false)+ })++ it('opens SSE with start=latest and replays history for a non-terminal run', async () => {+ jest.spyOn(api.tasks.runs, 'getLogEntries').mockResolvedValue([+ notification('_posthog/run_started', {}) as any,+ sessionUpdate({ sessionUpdate: 'agent_message', messageId: 'm1', content: { text: 'history' } }) as any,+ ])+ jest.spyOn(api.tasks.runs, 'get').mockResolvedValue({ status: 'in_progress' } as any)++ logic.actions.bootstrapRun({ taskId: 'task-1', runId: 'run-1' })+ await flushPromises()++ expect(logic.values.runStarted).toEqual(true)+ const assistantItem = logic.values.threadItems.find((item) => item.type === 'assistant_message')+ expect(assistantItem?.text).toEqual('history')+ // No live frame carried an id, so the connect opens from latest (no resume cursor).+ expect(MockStream.latest().options.startLatest).toEqual(true)+ expect(MockStream.latest().options.lastEventId).toBeUndefined()+ })++ it('replays logs/ and stays read-only for a terminal run', async () => {+ jest.spyOn(api.tasks.runs, 'getLogEntries').mockResolvedValue([])+ jest.spyOn(api.tasks.runs, 'get').mockResolvedValue({ status: 'completed' } as any)++ logic.actions.bootstrapRun({ taskId: 'task-1', runId: 'run-1' })+ await flushPromises()++ expect(logic.values.currentRunStatus).toEqual('completed')+ expect(MockStream.connections.length).toEqual(0)+ })++ it('fetches history exactly once for a terminal run (no terminal reconcile pass)', async () => {+ const logsSpy = jest.spyOn(api.tasks.runs, 'getLogEntries').mockResolvedValue([])+ jest.spyOn(api.tasks.runs, 'get').mockResolvedValue({ status: 'completed' } as any)++ logic.actions.bootstrapRun({ taskId: 'task-1', runId: 'run-1' })+ await flushPromises()++ expect(logsSpy).toHaveBeenCalledTimes(1)+ })++ it('connects the SSE before reading history and buffers live frames until the snapshot drains', async () => {+ // Connect-first is what closes the seam: a frame the agent emits while the history fetch+ // is in flight is captured by the (already-open) live stream and buffered, not gapped.+ let resolveLogs: (value: unknown) => void = () => {}+ jest.spyOn(api.tasks.runs, 'getLogEntries').mockReturnValue(+ new Promise((resolve) => (resolveLogs = resolve)) as any+ )+ jest.spyOn(api.tasks.runs, 'get').mockResolvedValue({ status: 'in_progress' } as any)++ logic.actions.bootstrapRun({ taskId: 'task-1', runId: 'run-1' })+ await flushPromises()++ // The SSE is open before the (still-pending) history fetch resolves.+ expect(MockStream.connections.length).toEqual(1)+ expect(MockStream.latest().options.startLatest).toEqual(true)++ // A live frame arriving now is buffered, not yet rendered.+ await MockStream.latest().emitOpen()+ await MockStream.latest().emitMessage(+ sessionUpdate({ sessionUpdate: 'agent_message', messageId: 'm-live', content: { text: 'live tail' } }),+ '5-0'+ )+ expect(logic.values.threadItems.filter((item) => item.type === 'assistant_message')).toHaveLength(0)++ // Snapshot lands → history renders, then the buffered live tail drains in after it.+ resolveLogs([+ notification('_posthog/run_started', {}) as any,+ sessionUpdate({+ sessionUpdate: 'agent_message',+ messageId: 'm-hist',+ content: { text: 'history' },+ }) as any,+ ])+ await flushPromises()++ expect(+ logic.values.threadItems.filter((item) => item.type === 'assistant_message').map((item) => item.text)+ ).toEqual(['history', 'live tail'])+ })++ it('drains the seam by content: a frame in both history and the buffered live tail renders once', async () => {+ // The exact keyless-`agent_message` duplication: the same finalized message is delivered+ // live during the fetch AND persisted in the snapshot. The multiset absorbs the live copy.+ let resolveLogs: (value: unknown) => void = () => {}+ jest.spyOn(api.tasks.runs, 'getLogEntries').mockReturnValue(+ new Promise((resolve) => (resolveLogs = resolve)) as any+ )+ jest.spyOn(api.tasks.runs, 'get').mockResolvedValue({ status: 'in_progress' } as any)++ logic.actions.bootstrapRun({ taskId: 'task-1', runId: 'run-1' })+ await flushPromises()+ await MockStream.latest().emitOpen()++ const overlap = sessionUpdate({ sessionUpdate: 'agent_message', content: { text: 'overlap' } })+ await MockStream.latest().emitMessage(overlap, '9-0')++ resolveLogs([overlap as any])+ await flushPromises()++ expect(+ logic.values.threadItems.filter((item) => item.type === 'assistant_message').map((item) => item.text)+ ).toEqual(['overlap'])+ })++ it('keeps a genuinely repeated payload when the buffer holds more copies than history (multiset)', async () => {+ // The agent legitimately emitted the same message twice live; the snapshot captured only+ // one (the second landed after the snapshot read). One historical copy absorbs one buffered+ // copy; the surplus survives — counts, not a set.+ let resolveLogs: (value: unknown) => void = () => {}+ jest.spyOn(api.tasks.runs, 'getLogEntries').mockReturnValue(+ new Promise((resolve) => (resolveLogs = resolve)) as any+ )+ jest.spyOn(api.tasks.runs, 'get').mockResolvedValue({ status: 'in_progress' } as any)++ logic.actions.bootstrapRun({ taskId: 'task-1', runId: 'run-1' })+ await flushPromises()+ await MockStream.latest().emitOpen()++ const repeated = sessionUpdate({+ sessionUpdate: 'agent_message',+ messageId: 'm1',+ content: { text: 'ping' },+ })+ await MockStream.latest().emitMessage(repeated, '1-0')+ await MockStream.latest().emitMessage(repeated, '2-0')++ resolveLogs([repeated as any])+ await flushPromises()++ expect(+ logic.values.threadItems.filter((item) => item.type === 'assistant_message').map((item) => item.text)+ ).toEqual(['ping', 'ping'])+ })+ })++ describe('replayOnly viewer (read-only)', () => {+ function mountViewer(streamKey: string): ReturnType<typeof sandboxStreamLogic.build> {+ const viewer = sandboxStreamLogic({ streamKey, replayOnly: true })+ viewer.mount()+ return viewer+ }++ it('replays a terminal run read-only without opening SSE and never thinks', async () => {+ jest.spyOn(api.tasks.runs, 'getLogEntries').mockResolvedValue([+ notification('_posthog/run_started', {}) as any,+ sessionUpdate({ sessionUpdate: 'agent_message', messageId: 'm1', content: { text: 'done' } }) as any,+ ])+ jest.spyOn(api.tasks.runs, 'get').mockResolvedValue({ status: 'completed' } as any)++ const viewer = mountViewer('run-ro-terminal')+ viewer.actions.bootstrapRun({ taskId: 'task-1', runId: 'run-1' })+ await flushPromises()++ expect(viewer.values.threadItems.find((item) => item.type === 'assistant_message')?.text).toEqual('done')+ expect(viewer.values.currentRunStatus).toEqual('completed')+ expect(MockStream.connections.length).toEqual(0)+ expect(viewer.values.isThinking).toEqual(false)+ expect(viewer.values.bootstrapLoading).toEqual(false)++ viewer.unmount()+ })++ it('replays an in-progress snapshot without opening SSE and stays idle', async () => {+ jest.spyOn(api.tasks.runs, 'getLogEntries').mockResolvedValue([+ notification('_posthog/run_started', {}) as any,+ sessionUpdate({ sessionUpdate: 'agent_message', messageId: 'm1', content: { text: 'partial' } }) as any,+ ])+ jest.spyOn(api.tasks.runs, 'get').mockResolvedValue({ status: 'in_progress' } as any)++ const viewer = mountViewer('run-ro-inprogress')+ viewer.actions.bootstrapRun({ taskId: 'task-1', runId: 'run-2' })+ await flushPromises()++ expect(viewer.values.threadItems.find((item) => item.type === 'assistant_message')?.text).toEqual('partial')+ // run_started replayed, but a read-only snapshot never streams and never spins the indicator.+ expect(MockStream.connections.length).toEqual(0)+ expect(viewer.values.streamPhase).toEqual('idle')+ expect(viewer.values.isThinking).toEqual(false)++ viewer.unmount()+ })++ it('folds the snapshot only once across a re-bootstrap of the shared instance', async () => {+ jest.spyOn(api.tasks.runs, 'getLogEntries').mockResolvedValue([+ sessionUpdate({ sessionUpdate: 'agent_message', messageId: 'm1', content: { text: 'once' } }) as any,+ ])+ jest.spyOn(api.tasks.runs, 'get').mockResolvedValue({ status: 'completed' } as any)++ const viewer = mountViewer('run-ro-idempotent')+ viewer.actions.bootstrapRun({ taskId: 'task-1', runId: 'run-3' })+ await flushPromises()+ // A second mounted viewer of the same run re-bootstraps the shared keyed instance.+ viewer.actions.bootstrapRun({ taskId: 'task-1', runId: 'run-3' })+ await flushPromises()++ expect(viewer.values.threadItems.filter((item) => item.type === 'assistant_message')).toHaveLength(1)++ viewer.unmount()+ })++ it('surfaces an error item when the snapshot fetch fails and opens no SSE', async () => {+ jest.spyOn(api.tasks.runs, 'get').mockResolvedValue({ status: 'completed' } as any)+ jest.spyOn(api.tasks.runs, 'getLogEntries').mockRejectedValue({ status: 500 })++ const viewer = mountViewer('run-ro-error')+ viewer.actions.bootstrapRun({ taskId: 'task-1', runId: 'run-4' })+ await flushPromises()++ expect(viewer.values.threadItems.some((item) => item.type === 'error')).toEqual(true)+ expect(MockStream.connections.length).toEqual(0)+ expect(viewer.values.bootstrapLoading).toEqual(false)++ viewer.unmount()+ })++ it('keys read-only instances apart from a live stream of the same run', async () => {+ jest.spyOn(api.tasks.runs, 'getLogEntries').mockResolvedValue([+ sessionUpdate({+ sessionUpdate: 'agent_message',+ messageId: 'm1',+ content: { text: 'replayed' },+ }) as any,+ ])+ jest.spyOn(api.tasks.runs, 'get').mockResolvedValue({ status: 'completed' } as any)++ const live = sandboxStreamLogic({ streamKey: 'run-shared' })+ live.mount()+ const viewer = mountViewer('run-shared')++ // Same streamKey, but the read-only `replay:` namespace resolves a distinct instance.+ expect(viewer).not.toBe(live)++ viewer.actions.bootstrapRun({ taskId: 'task-1', runId: 'run-5' })+ await flushPromises()++ // The replay folds into the viewer only; the live instance is untouched — streaming can't bleed in.+ expect(viewer.values.threadItems.find((item) => item.type === 'assistant_message')?.text).toEqual(+ 'replayed'+ )+ expect(live.values.threadItems).toHaveLength(0)++ viewer.unmount()+ live.unmount()+ })+ })++ describe('wire frame parsing through the SSE reader', () => {+ it('reads the snake_case error_message off task_run_state frames', async () => {+ logic.actions.openSseForRun({ taskId: 'task-1', runId: 'run-1' })+ const source = MockStream.latest()+ await source.emitOpen()++ await source.emitMessage({+ type: 'task_run_state',+ run_id: 'run-1',+ task_id: 'task-1',+ status: 'failed',+ error_message: 'sandbox exploded',+ })++ expect(logic.values.currentRunStatus).toEqual('failed')+ expect(source.closed).toEqual(true)+ })++ it('keeps the stream open for non-terminal task_run_state frames', async () => {+ logic.actions.openSseForRun({ taskId: 'task-1', runId: 'run-1' })+ const source = MockStream.latest()+ await source.emitOpen()++ await source.emitMessage({ type: 'task_run_state', status: 'in_progress', error_message: null })++ expect(logic.values.currentRunStatus).toEqual('in_progress')+ expect(source.closed).toEqual(false)+ })++ it('ignores unrecognized frame types', async () => {+ logic.actions.openSseForRun({ taskId: 'task-1', runId: 'run-1' })+ const source = MockStream.latest()+ await source.emitOpen()++ await source.emitMessage({ type: 'telemetry_v2', payload: { value: 1 } })++ expect(logic.values.threadItems).toEqual([])+ expect(logic.values.log.entries).toHaveLength(0)+ })+ })++ describe('_posthog/progress handling', () => {+ it('renders the emitter label as current progress and stores a progress thread item', async () => {+ await expectLogic(logic, () => {+ logic.actions.ingestAcpFrame(+ notification('_posthog/progress', {+ sessionId: 's',+ step: 'clone',+ status: 'in_progress',+ label: 'Cloning repository',+ group: 'setup:run-1',+ })+ )+ }).toMatchValues({ currentProgress: 'Cloning repository' })++ expect(logic.values.threadItems).toEqual([+ {+ id: 'progress-setup:run-1',+ type: 'progress',+ progressGroup: 'setup:run-1',+ progressSteps: [+ {+ key: 'clone',+ status: 'in_progress',+ label: 'Cloning repository',+ },+ ],+ },+ ])+ })++ it('coalesces setup progress by group and updates repeated steps in place', async () => {+ await expectLogic(logic, () => {+ logic.actions.ingestAcpFrame(+ notification('_posthog/progress', {+ sessionId: 's',+ step: 'sandbox',+ status: 'in_progress',+ label: 'Setting up sandbox',+ group: 'setup:run-1',+ })+ )+ logic.actions.ingestAcpFrame(+ notification('_posthog/progress', {+ sessionId: 's',+ step: 'sandbox',+ status: 'completed',+ label: 'Set up sandbox',+ group: 'setup:run-1',+ })+ )+ logic.actions.ingestAcpFrame(+ notification('_posthog/progress', {+ sessionId: 's',+ step: 'clone',+ status: 'in_progress',+ label: 'Cloning repository',+ group: 'setup:run-1',+ })+ )+ }).toFinishAllListeners()++ expect(logic.values.threadItems).toEqual([+ {+ id: 'progress-setup:run-1',+ type: 'progress',+ progressGroup: 'setup:run-1',+ progressSteps: [+ {+ key: 'sandbox',+ status: 'completed',+ label: 'Set up sandbox',+ },+ {+ key: 'clone',+ status: 'in_progress',+ label: 'Cloning repository',+ },+ ],+ },+ ])+ })++ it('falls back to detail when label is absent', async () => {+ await expectLogic(logic, () => {+ logic.actions.ingestAcpFrame(+ notification('_posthog/progress', { sessionId: 's', detail: 'PostHog/posthog @ master' })+ )+ }).toMatchValues({ currentProgress: 'PostHog/posthog @ master' })++ expect(logic.values.threadItems).toEqual([])+ })+ })++ describe('mergeResourceProducts', () => {+ it('unions by id, preserves first-seen order, and tolerates empty/idless input', () => {+ const first = mergeResourceProducts([], [{ id: 'product_analytics', label: 'Product analytics' }])+ expect(first).toEqual([{ id: 'product_analytics', label: 'Product analytics' }])++ const second = mergeResourceProducts(first, [+ { id: 'product_analytics', label: 'dup' },+ { id: 'session_replay', label: 'Session replay' },+ { label: 'no id' },+ { id: '' },+ ])+ expect(second.map((p) => p.id)).toEqual(['product_analytics', 'session_replay'])+ // First-seen label wins for an id already present.+ expect(second[0].label).toEqual('Product analytics')+ })+ })++ describe('_posthog/resources_used handling', () => {+ it('unions products into resourcesUsed by id in first-seen order', async () => {+ await expectLogic(logic, () => {+ logic.actions.ingestAcpFrame(+ notification('_posthog/resources_used', {+ products: [+ { id: 'product_analytics', label: 'Product analytics' },+ { id: 'session_replay', label: 'Session replay' },+ ],+ })+ )+ logic.actions.ingestAcpFrame(+ notification('_posthog/resources_used', {+ products: [+ { id: 'session_replay', label: 'Session replay' },+ { id: 'sql', label: 'SQL' },+ ],+ })+ )+ }).toFinishAllListeners()++ expect(logic.values.resourcesUsed.map((p) => p.id)).toEqual(['product_analytics', 'session_replay', 'sql'])+ })++ it('survives bootstrap replay without double-counting (same frame twice → one entry set)', async () => {+ const frame = notification('_posthog/resources_used', {+ products: [{ id: 'product_analytics', label: 'Product analytics' }],+ })+ jest.spyOn(api.tasks.runs, 'getLogEntries').mockResolvedValue([frame as any, frame as any])+ jest.spyOn(api.tasks.runs, 'get').mockResolvedValue({ status: 'in_progress' } as any)++ logic.actions.bootstrapRun({ taskId: 'task-1', runId: 'run-1' })+ await flushPromises()++ // Content-dedup drops the identical replay; the union would dedup by id regardless.+ expect(logic.values.resourcesUsed.map((p) => p.id)).toEqual(['product_analytics'])+ })+ })++ describe('_posthog/usage_update handling', () => {+ it('folds the Codex split frames (used + cost, then breakdown) into contextUsage', async () => {+ await expectLogic(logic, () => {+ logic.actions.ingestAcpFrame(+ notification('_posthog/usage_update', {+ used: { inputTokens: 100, outputTokens: 20 },+ cost: { amount: 0.42, currency: 'USD' },+ })+ )+ logic.actions.ingestAcpFrame(+ notification('_posthog/usage_update', { breakdown: { systemPrompt: 10, tools: 5 } })+ )+ }).toFinishAllListeners()++ expect(logic.values.contextUsage?.tokens).toEqual({ inputTokens: 100, outputTokens: 20 })+ expect(logic.values.contextUsage?.cost).toEqual(0.42)+ expect(logic.values.contextUsage?.breakdown).toEqual({ systemPrompt: 10, tools: 5 })+ })++ it('folds the Claude combined frame (used + numeric cost + breakdown) into contextUsage', async () => {+ await expectLogic(logic, () => {+ logic.actions.ingestAcpFrame(+ notification('_posthog/usage_update', {+ used: { inputTokens: 5000, outputTokens: 600 },+ cost: 0.18,+ breakdown: { conversation: 9000 },+ })+ )+ }).toFinishAllListeners()++ expect(logic.values.contextUsage?.tokens).toEqual({ inputTokens: 5000, outputTokens: 600 })+ expect(logic.values.contextUsage?.cost).toEqual(0.18)+ expect(logic.values.contextUsage?.breakdown).toEqual({ conversation: 9000 })+ })++ it('lands the numeric used/size aggregate from a session/update-framed usage_update', async () => {+ await expectLogic(logic, () => {+ logic.actions.ingestAcpFrame(+ sessionUpdate({+ sessionUpdate: 'usage_update',+ used: 168000,+ size: 200000,+ cost: { amount: 1.2, currency: 'USD' },+ })+ )+ }).toFinishAllListeners()++ expect(logic.values.contextUsage?.used).toEqual(168000)+ expect(logic.values.contextUsage?.size).toEqual(200000)+ expect(logic.values.contextUsage?.cost).toEqual(1.2)+ // The aggregate must not be misrouted into a thread item.+ expect(logic.values.threadItems).toEqual([])+ })++ it('merges the aggregate ring numbers with the ext-notification tokens/breakdown', async () => {+ await expectLogic(logic, () => {+ logic.actions.ingestAcpFrame(+ notification('_posthog/usage_update', {+ used: { inputTokens: 100 },+ breakdown: { tools: 5 },+ })+ )+ logic.actions.ingestAcpFrame(+ sessionUpdate({ sessionUpdate: 'usage_update', used: 12000, size: 200000 })+ )+ }).toFinishAllListeners()++ expect(logic.values.contextUsage).toEqual({+ tokens: { inputTokens: 100 },+ breakdown: { tools: 5 },+ used: 12000,+ size: 200000,+ })+ })+ })++ describe('_posthog/status + compact_boundary inline items', () => {+ it('pushes a status item for an in-progress compaction', async () => {+ await expectLogic(logic, () => {+ logic.actions.ingestAcpFrame(notification('_posthog/status', { status: 'compacting' }))+ }).toFinishAllListeners()++ const item = logic.values.threadItems.find((i) => i.type === 'status')+ expect(item).toEqual(expect.objectContaining({ type: 'status', status: 'compacting', isComplete: false }))+ })++ it('pushes nothing for a completed compaction status', async () => {+ await expectLogic(logic, () => {+ logic.actions.ingestAcpFrame(+ notification('_posthog/status', { status: 'compacting', isComplete: true })+ )+ }).toFinishAllListeners()++ expect(logic.values.threadItems).toEqual([])+ })++ it('pushes a compact_boundary item carrying trigger/preTokens/contextSize', async () => {+ await expectLogic(logic, () => {+ logic.actions.ingestAcpFrame(+ notification('_posthog/compact_boundary', {+ trigger: 'auto',+ preTokens: 168000,+ contextSize: 54000,+ })+ )+ }).toFinishAllListeners()++ const item = logic.values.threadItems.find((i) => i.type === 'compact_boundary')+ expect(item).toEqual(+ expect.objectContaining({+ type: 'compact_boundary',+ trigger: 'auto',+ preTokens: 168000,+ contextSize: 54000,+ })+ )+ })++ it('clears the in-progress compaction spinner once compaction completes', async () => {+ await expectLogic(logic, () => {+ logic.actions.ingestAcpFrame(notification('_posthog/status', { status: 'compacting' }))+ logic.actions.ingestAcpFrame(+ notification('_posthog/status', { status: 'compacting', isComplete: true })+ )+ }).toFinishAllListeners()++ expect(logic.values.threadItems.filter((i) => i.type === 'status')).toEqual([])+ })++ it('replaces the in-progress spinner with the compact_boundary divider', async () => {+ await expectLogic(logic, () => {+ logic.actions.ingestAcpFrame(notification('_posthog/status', { status: 'compacting' }))+ logic.actions.ingestAcpFrame(notification('_posthog/compact_boundary', { trigger: 'auto' }))+ }).toFinishAllListeners()++ const items = logic.values.threadItems+ expect(items.some((i) => i.type === 'status')).toBe(false)+ expect(items.some((i) => i.type === 'compact_boundary')).toBe(true)+ })+ })++ describe('_posthog/task_notification inline item', () => {+ it('pushes a task_notification item carrying status + summary', async () => {+ await expectLogic(logic, () => {+ logic.actions.ingestAcpFrame(+ notification('_posthog/task_notification', {+ status: 'completed',+ summary: 'Analysis written to report.md',+ })+ )+ }).toFinishAllListeners()++ const item = logic.values.threadItems.find((i) => i.type === 'task_notification')+ expect(item).toEqual(+ expect.objectContaining({+ type: 'task_notification',+ status: 'completed',+ summary: 'Analysis written to report.md',+ })+ )+ })+ })++ describe('_posthog/sdk_session handling', () => {+ it('stashes the adapter/session identity without rendering UI', async () => {+ await expectLogic(logic, () => {+ logic.actions.ingestAcpFrame(+ notification('_posthog/sdk_session', {+ taskRunId: 'run-1',+ sessionId: 'sess_a1b2c3',+ adapter: 'claude',+ })+ )+ }).toFinishAllListeners()++ expect(logic.values.sdkSession).toEqual({ sessionId: 'sess_a1b2c3', adapter: 'claude' })+ expect(logic.values.threadItems).toEqual([])+ })+ })++ describe('reset clears notification state', () => {+ it('clears resourcesUsed, contextUsage, and sdkSession on reset', async () => {+ await expectLogic(logic, () => {+ logic.actions.ingestAcpFrame(+ notification('_posthog/resources_used', { products: [{ id: 'sql', label: 'SQL' }] })+ )+ logic.actions.ingestAcpFrame(notification('_posthog/usage_update', { used: { inputTokens: 1 } }))+ logic.actions.ingestAcpFrame(notification('_posthog/sdk_session', { adapter: 'codex' }))+ }).toFinishAllListeners()++ expect(logic.values.resourcesUsed).toHaveLength(1)+ expect(logic.values.contextUsage).not.toBeNull()+ expect(logic.values.sdkSession).not.toBeNull()++ await expectLogic(logic, () => {+ logic.actions.reset()+ }).toFinishAllListeners()++ expect(logic.values.resourcesUsed).toEqual([])+ expect(logic.values.contextUsage).toBeNull()+ expect(logic.values.sdkSession).toBeNull()+ })++ it('keeps resourcesUsed across markTurnComplete (accumulates over the session)', async () => {+ await expectLogic(logic, () => {+ logic.actions.ingestAcpFrame(+ notification('_posthog/resources_used', { products: [{ id: 'sql', label: 'SQL' }] })+ )+ logic.actions.markTurnComplete()+ }).toFinishAllListeners()++ expect(logic.values.resourcesUsed.map((p) => p.id)).toEqual(['sql'])+ })+ })++ describe('mixed notification replay', () => {+ it('ingests known, unknown, and degenerate notifications without throwing, appending each once', async () => {+ const corpus: StoredLogEntry[] = [+ notification('_posthog/run_started', { runId: 'run-1' }),+ notification('_posthog/usage_update', { used: { inputTokens: 1 }, cost: null }),+ notification('_posthog/hologram_sync', { shards: 3 }),+ { type: 'notification', notification: { method: '_posthog/turn_complete' } },+ { type: 'notification', notification: { method: '_posthog/console', params: 'not-an-object' as any } },+ sessionUpdate({ sessionUpdate: 'plan_delta', entries: [] }),+ sessionUpdate({ sessionUpdate: 'agent_message_chunk', text: 'hi' }),+ ]++ await expectLogic(logic, () => {+ corpus.forEach((entry) => logic.actions.ingestAcpFrame(entry))+ }).toFinishAllListeners()++ // The log is append-only — every frame lands once, in order.+ expect(logic.values.log.entries).toHaveLength(corpus.length)+ })+ })++ describe('telemetry parity', () => {+ it('emits TASK_RUN_STARTED once on the first run_started frame, always cold (wire carries no warmth)', async () => {+ const captureSpy = jest.spyOn(posthog, 'capture').mockImplementation(() => undefined as any)+ logic.actions.openSseForRun({+ taskId: 'task-1',+ runId: 'run-1',+ traceId: 'trace-1',+ })++ await expectLogic(logic, () => {+ // A stray cold_start hint on the wire is ignored — pre-warming isn't wired yet.+ logic.actions.ingestAcpFrame(notification('_posthog/run_started', { cold_start: false }))+ logic.actions.ingestAcpFrame(notification('_posthog/run_started', {}))+ }).toFinishAllListeners()++ const startedCalls = captureSpy.mock.calls.filter((c) => c[0] === 'task_run_started')+ expect(startedCalls.length).toEqual(1)+ expect(startedCalls[0][1]).toEqual(+ expect.objectContaining({+ conversation_id: 'test-conversation',+ trace_id: 'trace-1',+ run_id: 'run-1',+ task_id: 'task-1',+ execution_type: 'sandbox',+ cold_start: true,+ })+ )+ })++ it('emits TASK_RUN_TERMINATED with duration_ms measured from run start', async () => {+ const captureSpy = jest.spyOn(posthog, 'capture').mockImplementation(() => undefined as any)+ logic.actions.openSseForRun({+ taskId: 'task-1',+ runId: 'run-1',+ traceId: 'trace-1',+ })++ await expectLogic(logic, () => {+ logic.actions.ingestAcpFrame(notification('_posthog/run_started', {}))+ logic.actions.handleTerminalStatus({ status: 'failed', errorMessage: 'boom' })+ }).toFinishAllListeners()++ const call = captureSpy.mock.calls.find((c) => c[0] === 'task_run_terminated')+ expect(call?.[1]).toEqual(+ expect.objectContaining({+ conversation_id: 'test-conversation',+ trace_id: 'trace-1',+ run_id: 'run-1',+ status: 'failed',+ error_message: 'boom',+ execution_type: 'sandbox',+ })+ )+ expect((call![1] as any).duration_ms).toBeGreaterThanOrEqual(0)+ })++ it('emits TOOL_CALL_COMPLETED once when a tool call reaches a terminal status', async () => {+ const captureSpy = jest.spyOn(posthog, 'capture').mockImplementation(() => undefined as any)+ logic.actions.openSseForRun({+ taskId: 'task-1',+ runId: 'run-1',+ traceId: 'trace-1',+ })++ await expectLogic(logic, () => {+ logic.actions.ingestAcpFrame(+ sessionUpdate({+ sessionUpdate: 'tool_call',+ toolCallId: 't1',+ serverName: 'posthog',+ toolName: 'exec',+ rawInput: { command: 'call execute-sql {"query":"select 1"}' },+ status: 'in_progress',+ })+ )+ logic.actions.ingestAcpFrame(+ sessionUpdate({ sessionUpdate: 'tool_call_update', toolCallId: 't1', status: 'completed' })+ )+ // A second terminal update must not re-emit.+ logic.actions.ingestAcpFrame(+ sessionUpdate({ sessionUpdate: 'tool_call_update', toolCallId: 't1', status: 'completed' })+ )+ }).toFinishAllListeners()++ const toolCalls = captureSpy.mock.calls.filter((c) => c[0] === 'tool_call_completed')+ expect(toolCalls.length).toEqual(1)+ expect(toolCalls[0][1]).toEqual(+ expect.objectContaining({+ conversation_id: 'test-conversation',+ trace_id: 'trace-1',+ tool_call_id: 't1',+ tool_qualified_name: 'execute-sql',+ status: 'completed',+ execution_type: 'sandbox',+ })+ )+ })++ it('commands the streamed run via the tasks relay on respondToPermission', async () => {+ logic.actions.openSseForRun({+ taskId: 'task-1',+ runId: 'run-1',+ traceId: 'trace-1',+ })++ await expectLogic(logic, () => {+ logic.actions.respondToPermission({+ requestId: 'req-1',+ optionId: 'allow_once',+ })+ }).toFinishAllListeners()++ // "Command the latest run": the reply targets the (task, run) the renderer is streaming.+ expect(tasksRunsCommandCreate).toHaveBeenCalledWith('997', 'task-1', 'run-1', {+ jsonrpc: '2.0',+ method: 'permission_response',+ params: { requestId: 'req-1', optionId: 'allow_once', customInput: undefined, answers: undefined },+ })+ })++ it('cancelRun cancels the streamed run via the tasks relay', async () => {+ logic.actions.openSseForRun({ taskId: 'task-1', runId: 'run-1' })++ await expectLogic(logic, () => {+ logic.actions.cancelRun()+ }).toFinishAllListeners()++ expect(tasksRunsCommandCreate).toHaveBeenCalledWith('997', 'task-1', 'run-1', {+ jsonrpc: '2.0',+ method: 'cancel',+ })+ })++ it('cancelRun cancels an explicit (warm) run the renderer is not streaming', async () => {+ // A warm Run is released by id without the renderer ever opening SSE against it.+ await expectLogic(logic, () => {+ logic.actions.cancelRun({ taskId: 'warm-task', runId: 'warm-run' })+ }).toFinishAllListeners()++ expect(tasksRunsCommandCreate).toHaveBeenCalledWith('997', 'warm-task', 'warm-run', {+ jsonrpc: '2.0',+ method: 'cancel',+ })+ })++ it('suppresses run lifecycle telemetry while replaying history on bootstrap', async () => {+ const captureSpy = jest.spyOn(posthog, 'capture').mockImplementation(() => undefined as any)+ jest.spyOn(api.tasks.runs, 'getLogEntries').mockResolvedValue([+ notification('_posthog/run_started', {}) as any,+ sessionUpdate({+ sessionUpdate: 'tool_call',+ toolCallId: 't1',+ serverName: 'posthog',+ toolName: 'exec',+ rawInput: { command: 'call execute-sql {"query":"select 1"}' },+ status: 'in_progress',+ }) as any,+ sessionUpdate({ sessionUpdate: 'tool_call_update', toolCallId: 't1', status: 'completed' }) as any,+ ])+ jest.spyOn(api.tasks.runs, 'get').mockResolvedValue({ status: 'completed' } as any)++ logic.actions.bootstrapRun({ taskId: 'task-1', runId: 'run-1' })+ await flushPromises()++ // History is folded in (run marked started, status terminal) but none of the lifecycle+ // events re-fire — the run lived and died in a prior session.+ expect(logic.values.runStarted).toEqual(true)+ expect(logic.values.currentRunStatus).toEqual('completed')+ const lifecycleEvents = ['task_run_started', 'task_run_terminated', 'tool_call_completed']+ expect(captureSpy.mock.calls.filter((c) => lifecycleEvents.includes(c[0] as string))).toEqual([])+ })+ })++ describe('crash affordance', () => {+ it('pushes a crash-variant error item and still captures task_run_terminated', async () => {+ const captureSpy = jest.spyOn(posthog, 'capture').mockImplementation(() => undefined as any)+ logic.actions.openSseForRun({ taskId: 'task-1', runId: 'run-1', traceId: 'trace-1' })++ await expectLogic(logic, () => {+ logic.actions.handleTerminalStatus({+ status: 'failed',+ errorMessage: 'Agent server crashed: boom',+ })+ }).toFinishAllListeners()++ const errorItem = logic.values.threadItems.find((item) => item.type === 'error')+ expect(errorItem?.variant).toEqual('crash')+ expect(errorItem?.errorMessage).toEqual('Agent server crashed: boom')+ // The existing termination telemetry is unchanged.+ const terminated = captureSpy.mock.calls.find((c) => c[0] === 'task_run_terminated')+ expect(terminated?.[1]).toEqual(+ expect.objectContaining({ status: 'failed', error_message: 'Agent server crashed: boom' })+ )+ })++ it('renders a plain failed run without the crash prefix as a raw error item', async () => {+ logic.actions.openSseForRun({ taskId: 'task-1', runId: 'run-1' })++ await expectLogic(logic, () => {+ logic.actions.handleTerminalStatus({ status: 'failed', errorMessage: 'usage limit reached' })+ }).toFinishAllListeners()++ const errorItem = logic.values.threadItems.find((item) => item.type === 'error')+ expect(errorItem?.variant).toEqual('error')+ expect(errorItem?.errorMessage).toEqual('usage limit reached')+ })++ it('does not push an error item for a failed run carrying no error message', async () => {+ logic.actions.openSseForRun({ taskId: 'task-1', runId: 'run-1' })++ await expectLogic(logic, () => {+ logic.actions.handleTerminalStatus({ status: 'failed' })+ }).toFinishAllListeners()++ expect(logic.values.threadItems.some((item) => item.type === 'error')).toEqual(false)+ })++ it('does not push an error item for a failed run replayed from history', async () => {+ await expectLogic(logic, () => {+ logic.actions.handleTerminalStatus({+ status: 'failed',+ errorMessage: 'Agent server crashed: old',+ replayedFromHistory: true,+ })+ }).toFinishAllListeners()++ expect(logic.values.threadItems.some((item) => item.type === 'error')).toEqual(false)+ })+ })++ describe('stream-disconnect telemetry', () => {+ it('captures sandbox_stream_disconnected with attempt counters and pushes a visible error item', async () => {+ jest.spyOn(api.tasks.runs, 'get').mockResolvedValue({ status: 'in_progress' } as any)+ const captureSpy = jest.spyOn(posthog, 'capture').mockImplementation(() => undefined as any)++ logic.actions.openSseForRun({ taskId: 'task-1', runId: 'run-1', traceId: 'trace-1' })+ // Drive the per-drop counter to the cap so the next drop exhausts the budget.+ logic.actions.sseReconnecting(MAX_SSE_RECONNECT_ATTEMPTS)++ logic.actions.sseDropped()+ await flushPromises()++ expect(logic.values.sseStatus).toEqual('error')+ const disconnect = captureSpy.mock.calls.find((c) => c[0] === 'sandbox_stream_disconnected')+ expect(disconnect?.[1]).toEqual(+ expect.objectContaining({+ conversation_id: 'test-conversation',+ trace_id: 'trace-1',+ run_id: 'run-1',+ task_id: 'task-1',+ error_title: 'Cloud stream failed',+ retryable: true,+ reconnect_attempts: MAX_SSE_RECONNECT_ATTEMPTS,+ cumulative_reconnect_attempts: 1,+ was_bootstrapping: false,+ execution_type: 'sandbox',+ })+ )+ expect(logic.values.threadItems.some((item) => item.type === 'error')).toEqual(true)+ })++ it('reports was_bootstrapping=true when the snapshot fails before the agent starts', async () => {+ const captureSpy = jest.spyOn(posthog, 'capture').mockImplementation(() => undefined as any)+ jest.spyOn(api.tasks.runs, 'get').mockResolvedValue({ status: 'in_progress' } as any)+ jest.spyOn(api.tasks.runs, 'getLogEntries').mockRejectedValue({ status: 500 })++ logic.actions.bootstrapRun({ taskId: 'task-1', runId: 'run-1' })+ await flushPromises()++ // The history fetch failed during bootstrap and no `_posthog/run_started` ever arrived, so+ // the provisioning flag is still set even though the SSE briefly opened (connect-first).+ const disconnect = captureSpy.mock.calls.find((c) => c[0] === 'sandbox_stream_disconnected')+ expect(disconnect?.[1]).toEqual(expect.objectContaining({ was_bootstrapping: true }))+ })+ })++ describe('stream phase', () => {+ it('is provisioning while the stream is open before run_started, then flips to thinking', async () => {+ expect(logic.values.streamPhase).toEqual('idle')++ logic.actions.openSseForRun({ taskId: 'task-1', runId: 'run-1' })+ await MockStream.latest().emitOpen()++ // SSE open, agent not started yet — provisioning, surfacing _posthog/progress.+ logic.actions.ingestAcpFrame(notification('_posthog/progress', { label: 'Setting up sandbox' }))+ expect(logic.values.streamPhase).toEqual('provisioning')+ expect(logic.values.currentProgress).toEqual('Setting up sandbox')++ // run_started arrives — phase flips to thinking.+ logic.actions.ingestAcpFrame(notification('_posthog/run_started', {}))+ expect(logic.values.streamPhase).toEqual('thinking')++ // turn_complete ends the turn — back to idle.+ logic.actions.ingestAcpFrame(notification('_posthog/turn_complete', {}))+ expect(logic.values.streamPhase).toEqual('idle')+ })++ it('tracks the optional task_run_state stage off the wire', async () => {+ logic.actions.openSseForRun({ taskId: 'task-1', runId: 'run-1' })+ const source = MockStream.latest()+ await source.emitOpen()++ await source.emitMessage({ type: 'task_run_state', status: 'in_progress', stage: 'build' })++ expect(logic.values.currentStage).toEqual('build')+ })+ })++ describe('reconnect refinements', () => {+ it('forgives a healthy connection drop — no reconnectAttempt increment but still schedules a reopen', async () => {+ jest.spyOn(api.tasks.runs, 'get').mockResolvedValue({ status: 'in_progress' } as any)++ logic.actions.openSseForRun({ taskId: 'task-1', runId: 'run-1' })+ const source = MockStream.latest()++ jest.useFakeTimers()+ // sseOpened stamps cache.sseConnectedAtMs in fake-time; drain the open then advance past+ // the healthy threshold before dropping.+ await source.emitOpen()+ const beforeDrop = MockStream.connections.length+ jest.advanceTimersByTime(SSE_HEALTHY_CONNECTION_MS + 1_000)++ logic.actions.sseDropped()+ await flushPromises()++ // Healthy drop: per-drop budget untouched, but cumulative still grows and a reopen is scheduled.+ expect(logic.values.reconnectAttempt).toEqual(0)+ expect(logic.values.cumulativeReconnectAttempt).toEqual(1)+ expect(logic.values.sseStatus).toEqual('reconnecting')++ jest.advanceTimersByTime(SSE_RECONNECT_BASE_DELAY_MS)+ expect(MockStream.connections.length).toEqual(beforeDrop + 1)+ jest.useRealTimers()+ })++ it('fails on the cumulative cap even when the per-drop counter keeps resetting', async () => {+ jest.spyOn(api.tasks.runs, 'get').mockResolvedValue({ status: 'in_progress' } as any)++ logic.actions.openSseForRun({ taskId: 'task-1', runId: 'run-1' })+ await MockStream.latest().emitOpen()+ // Drive the cumulative counter to the cap without growing the per-drop counter, as a+ // clean-EOF reopen loop would (every reopen resets reconnectAttempt to 0).+ for (let i = 0; i < MAX_CUMULATIVE_RECONNECT_ATTEMPTS; i++) {+ logic.actions.sseReconnecting(0)+ }+ expect(logic.values.cumulativeReconnectAttempt).toEqual(MAX_CUMULATIVE_RECONNECT_ATTEMPTS)++ logic.actions.sseDropped()+ await flushPromises()++ // The (cumulative + 1)th reconnect crosses the bound → terminal error.+ expect(logic.values.sseStatus).toEqual('error')+ })+ })++ describe('permission_request ingest', () => {+ // A destructive exec (`insight-update`) so the default policy prompts (shows a card) rather+ // than auto-approving — the lifecycle tests below all assume a card appears.+ const permissionFrame: PermissionRequestFrame = {+ type: 'permission_request',+ requestId: 'req-1',+ toolCall: {+ toolCallId: 't1',+ serverName: 'posthog',+ toolName: 'exec',+ _meta: { claudeCode: { toolName: 'mcp__posthog__exec' } },+ rawInput: { command: 'call insight-update {"id":"abc"}' },+ title: 'Update insight',+ status: 'pending',+ },+ options: [+ { optionId: 'allow_once', name: 'Approve', kind: 'allow_once' },+ { optionId: 'reject', name: 'Decline', kind: 'reject' },+ ],+ }++ it('parses a permission_request frame into a PermissionRequestRecord', () => {+ const record = parsePermissionRequestFrame(permissionFrame)+ expect(record).not.toBeNull()+ expect(record?.requestId).toEqual('req-1')+ expect(record?.toolCallId).toEqual('t1')+ expect(record?.toolName).toEqual('mcp__posthog__exec')+ expect(record?.options.map((o) => o.kind)).toEqual(['allow_once', 'reject'])+ expect(record?.rawToolCall.rawServerName).toEqual('posthog')+ expect(record?.rawToolCall.rawToolName).toEqual('exec')+ expect(record?.rawToolCall.input).toEqual({ command: 'call insight-update {"id":"abc"}' })+ expect(record?.rawToolCall.meta).toEqual({ claudeCode: { toolName: 'mcp__posthog__exec' } })+ })++ it('returns null for a frame with no usable options', () => {+ expect(parsePermissionRequestFrame({ ...permissionFrame, options: [] })).toBeNull()+ expect(parsePermissionRequestFrame({ type: 'permission_request', requestId: 'r', toolCall: {} })).toBeNull()+ })++ it('keeps a reject_once option and parses _meta.customInput (the previously-dropped decline)', () => {+ // Exact shape the agent adapter emits (see ee/hogai/sandbox/log.jsonl): the decline option+ // is `reject_once` carrying `_meta.customInput`, which the old exact-match allowlist dropped.+ const frame = {+ type: 'permission_request',+ requestId: 'req-2',+ toolCall: { toolCallId: 't2', title: 'exec' },+ options: [+ { optionId: 'allow', name: 'Yes', kind: 'allow_once' },+ { optionId: 'allow_always', name: 'Yes, always allow', kind: 'allow_always' },+ {+ optionId: 'reject',+ name: 'No, and tell the agent what to do differently',+ kind: 'reject_once',+ _meta: { customInput: true },+ },+ ],+ }+ const record = parsePermissionRequestFrame(frame as unknown as PermissionRequestFrame)+ expect(record?.options.map((o) => o.kind)).toEqual(['allow_once', 'allow_always', 'reject_once'])+ expect(record?.options.find((o) => o.kind === 'reject_once')?.customInput).toEqual(true)+ })++ it('keeps Claude tool metadata on the raw tool call', () => {+ const record = parsePermissionRequestFrame({+ type: 'permission_request',+ requestId: 'req-2',+ toolCall: {+ toolCallId: 't9',+ title: 'Edit `app.ts`',+ status: 'pending',+ _meta: { claudeCode: { toolName: 'Edit' } },+ },+ options: [{ optionId: 'allow_once', name: 'Approve', kind: 'allow_once' }],+ })+ expect(record).not.toBeNull()+ expect(record?.toolName).toEqual('Edit')+ expect(record?.rawToolCall.rawToolName).toEqual('')+ expect(record?.rawToolCall.meta).toEqual({ claudeCode: { toolName: 'Edit' } })+ })++ it('populates pendingPermissionRequest off a permission_request SSE frame', async () => {+ jest.spyOn(api.tasks.runs, 'get').mockResolvedValue({ status: 'in_progress' } as any)+ logic.actions.openSseForRun({ taskId: 'task-1', runId: 'run-1' })+ const captureSpy = jest.spyOn(posthog, 'capture').mockImplementation(() => undefined as any)++ await MockStream.latest().emitMessage({ ...permissionFrame })++ expect(logic.values.pendingPermissionRequest?.requestId).toEqual('req-1')+ expect(logic.values.pendingPermissionRequest?.toolCallId).toEqual('t1')+ expect(captureSpy).toHaveBeenCalledWith(+ 'permission_requested',+ expect.objectContaining({ request_id: 'req-1', execution_type: 'sandbox' })+ )+ })++ it('auto-approves a non-destructive PostHog exec without showing a card', async () => {+ const captureSpy = jest.spyOn(posthog, 'capture').mockImplementation(() => undefined as any)+ logic.actions.openSseForRun({ taskId: 'task-1', runId: 'run-1' })+ const source = MockStream.latest()++ await source.emitMessage({+ ...permissionFrame,+ requestId: 'req-auto',+ toolCall: {+ ...permissionFrame.toolCall,+ rawInput: { command: 'call insight-create {"name":"x"}' },+ },+ })++ expect(logic.values.pendingPermissionRequest).toBeNull()+ expect(tasksRunsCommandCreate).toHaveBeenCalledWith('997', 'task-1', 'run-1', {+ jsonrpc: '2.0',+ method: 'permission_response',+ params: { requestId: 'req-auto', optionId: 'allow_once' },+ })+ expect(captureSpy).toHaveBeenCalledWith(+ 'permission_auto_approved',+ expect.objectContaining({ request_id: 'req-auto', execution_type: 'sandbox' })+ )+ })++ it('auto-approves a built-in tool without showing a card', async () => {+ logic.actions.openSseForRun({ taskId: 'task-1', runId: 'run-1' })+ const source = MockStream.latest()++ await source.emitMessage({+ type: 'permission_request',+ requestId: 'req-bash',+ toolCall: {+ toolCallId: 't-bash',+ _meta: { claudeCode: { toolName: 'Bash' } },+ title: 'Bash',+ rawInput: { command: 'ls -la' },+ },+ options: [{ optionId: 'allow', name: 'Yes', kind: 'allow_once' }],+ })++ expect(logic.values.pendingPermissionRequest).toBeNull()+ expect(tasksRunsCommandCreate).toHaveBeenCalledWith('997', 'task-1', 'run-1', {+ jsonrpc: '2.0',+ method: 'permission_response',+ params: { requestId: 'req-bash', optionId: 'allow' },+ })+ })++ it('falls back to a manual card when the auto-approve POST fails', async () => {+ ;(tasksRunsCommandCreate as jest.Mock).mockRejectedValue({ status: 502 })+ jest.spyOn(posthog, 'captureException').mockImplementation(() => undefined as any)+ logic.actions.openSseForRun({ taskId: 'task-1', runId: 'run-1' })+ const source = MockStream.latest()++ await source.emitMessage({+ ...permissionFrame,+ requestId: 'req-fail',+ toolCall: {+ ...permissionFrame.toolCall,+ rawInput: { command: 'call insight-create {"name":"x"}' },+ },+ })++ expect(logic.values.pendingPermissionRequest?.requestId).toEqual('req-fail')+ })++ it('drives a generic task viewer with no conversation id', async () => {+ // The renderer must work for runs created by other products that never mint a Conversation:+ // keyed by task id, commanding the relay by (task, run), with conversation_id absent from telemetry.+ const captureSpy = jest.spyOn(posthog, 'capture').mockImplementation(() => undefined as any)+ const viewerLogic = sandboxStreamLogic({ streamKey: 'task-7' })+ viewerLogic.mount()+ try {+ viewerLogic.actions.openSseForRun({ taskId: 'task-7', runId: 'run-7' })+ viewerLogic.actions.ingestPermissionRequest(parsePermissionRequestFrame(permissionFrame)!)+ await expectLogic(viewerLogic, () => {+ viewerLogic.actions.respondToPermission({ requestId: 'req-1', optionId: 'allow_once' })+ }).toFinishAllListeners()++ expect(tasksRunsCommandCreate).toHaveBeenCalledWith('997', 'task-7', 'run-7', {+ jsonrpc: '2.0',+ method: 'permission_response',+ params: { requestId: 'req-1', optionId: 'allow_once', customInput: undefined, answers: undefined },+ })+ const permRequested = captureSpy.mock.calls.find((c) => c[0] === 'permission_requested')+ expect(permRequested).not.toBeUndefined()+ expect((permRequested?.[1] as any).conversation_id).toBeUndefined()+ expect((permRequested?.[1] as any).task_id).toEqual('task-7')+ } finally {+ viewerLogic.unmount()+ }+ })++ it('clears the pending request and commands the run on respondToPermission', async () => {+ logic.actions.openSseForRun({ taskId: 'task-1', runId: 'run-1' })+ logic.actions.ingestPermissionRequest(parsePermissionRequestFrame(permissionFrame)!)++ await expectLogic(logic, () => {+ logic.actions.respondToPermission({+ requestId: 'req-1',+ optionId: 'allow_once',+ })+ }).toFinishAllListeners()++ expect(logic.values.pendingPermissionRequest).toBeNull()+ expect(logic.values.respondingToPermission).toEqual(false)+ expect(tasksRunsCommandCreate).toHaveBeenCalledWith('997', 'task-1', 'run-1', {+ jsonrpc: '2.0',+ method: 'permission_response',+ params: { requestId: 'req-1', optionId: 'allow_once', customInput: undefined, answers: undefined },+ })+ })++ it('keeps the card pending and surfaces an error when the reply command fails', async () => {+ ;(tasksRunsCommandCreate as jest.Mock).mockRejectedValue({ status: 502 })+ const exceptionSpy = jest.spyOn(posthog, 'captureException').mockImplementation(() => undefined as any)+ const toastSpy = jest.spyOn(lemonToast, 'error').mockImplementation(() => undefined as any)+ logic.actions.openSseForRun({ taskId: 'task-1', runId: 'run-1' })+ logic.actions.ingestPermissionRequest(parsePermissionRequestFrame(permissionFrame)!)++ await expectLogic(logic, () => {+ logic.actions.respondToPermission({+ requestId: 'req-1',+ optionId: 'allow_once',+ })+ }).toFinishAllListeners()++ expect(logic.values.pendingPermissionRequest?.requestId).toEqual('req-1')+ // A failed reply POST must not tear down the live stream — the run is still alive and+ // blocked on this approval; only the card's buttons re-enable for a retry.+ expect(logic.values.sseStatus).not.toEqual('error')+ expect(logic.values.respondingToPermission).toEqual(false)+ expect(exceptionSpy).toHaveBeenCalled()+ expect(toastSpy).toHaveBeenCalled()+ })++ it('ignores a replayed permission_request envelope once the request is resolved', async () => {+ const captureSpy = jest.spyOn(posthog, 'capture').mockImplementation(() => undefined as any)+ logic.actions.openSseForRun({ taskId: 'task-1', runId: 'run-1' })+ const source = MockStream.latest()++ await source.emitMessage({ ...permissionFrame })+ await expectLogic(logic, () => {+ logic.actions.respondToPermission({+ requestId: 'req-1',+ optionId: 'allow_once',+ })+ }).toFinishAllListeners()+ expect(logic.values.pendingPermissionRequest).toBeNull()++ // A reconnect's resume re-delivers the envelope verbatim.+ await source.emitMessage({ ...permissionFrame })++ expect(logic.values.pendingPermissionRequest).toBeNull()+ expect(captureSpy).toHaveBeenCalledTimes(1)+ })++ it('does not double-capture telemetry when the same envelope arrives twice while pending', async () => {+ const captureSpy = jest.spyOn(posthog, 'capture').mockImplementation(() => undefined as any)+ logic.actions.openSseForRun({ taskId: 'task-1', runId: 'run-1' })+ const source = MockStream.latest()++ await source.emitMessage({ ...permissionFrame })+ await source.emitMessage({ ...permissionFrame })++ expect(logic.values.pendingPermissionRequest?.requestId).toEqual('req-1')+ expect(captureSpy).toHaveBeenCalledTimes(1)+ })++ it('re-derives a pending approval from a logged _posthog/permission_request without telemetry', async () => {+ const captureSpy = jest.spyOn(posthog, 'capture').mockImplementation(() => undefined as any)+ jest.spyOn(api.tasks.runs, 'getLogEntries').mockResolvedValue([+ notification('_posthog/permission_request', {+ requestId: 'req-1',+ toolCall: permissionFrame.toolCall,+ options: permissionFrame.options,+ }) as any,+ ])+ jest.spyOn(api.tasks.runs, 'get').mockResolvedValue({ status: 'in_progress' } as any)++ logic.actions.bootstrapRun({ taskId: 'task-1', runId: 'run-1' })+ await flushPromises()++ expect(logic.values.pendingPermissionRequest?.requestId).toEqual('req-1')+ expect(captureSpy).not.toHaveBeenCalled()+ })++ it('drops a logged permission_request that has a matching permission_resolved entry', async () => {+ jest.spyOn(api.tasks.runs, 'getLogEntries').mockResolvedValue([+ notification('_posthog/permission_request', {+ requestId: 'req-1',+ toolCall: permissionFrame.toolCall,+ options: permissionFrame.options,+ }) as any,+ notification('_posthog/permission_resolved', { requestId: 'req-1', optionId: 'allow_once' }) as any,+ ])+ jest.spyOn(api.tasks.runs, 'get').mockResolvedValue({ status: 'in_progress' } as any)++ logic.actions.bootstrapRun({ taskId: 'task-1', runId: 'run-1' })+ await flushPromises()++ expect(logic.values.pendingPermissionRequest).toBeNull()+ })++ it('clears the pending card when another client resolves the request', async () => {+ logic.actions.ingestPermissionRequest(parsePermissionRequestFrame(permissionFrame)!)+ expect(logic.values.pendingPermissionRequest?.requestId).toEqual('req-1')++ await expectLogic(logic, () => {+ logic.actions.ingestAcpFrame(notification('_posthog/permission_resolved', { requestId: 'req-1' }))+ }).toFinishAllListeners()++ expect(logic.values.pendingPermissionRequest).toBeNull()+ })++ it('drops the pending card when the run reaches a terminal status, but not before', () => {+ logic.actions.ingestPermissionRequest(parsePermissionRequestFrame(permissionFrame)!)++ logic.actions.handleTerminalStatus({ status: 'queued' })+ expect(logic.values.pendingPermissionRequest?.requestId).toEqual('req-1')++ logic.actions.handleTerminalStatus({ status: 'completed' })+ expect(logic.values.pendingPermissionRequest).toBeNull()+ })+ })+})++// Drain queued microtasks (chained `await`s in async listeners) without relying on timers, so it+// works under both real and fake timers.+async function flushPromises(): Promise<void> {+ for (let i = 0; i < 10; i++) {+ await Promise.resolve()+ }+}diff --git a/frontend/src/scenes/max/sandboxStreamLogic.ts b/frontend/src/scenes/max/sandboxStreamLogic.tsnew file mode 100644index 000000000000..cbc476fc94f4--- /dev/null+++ b/frontend/src/scenes/max/sandboxStreamLogic.ts@@ -0,0 +1,2149 @@+import { type EventSourceMessage, createParser } from 'eventsource-parser'+import { actions, connect, kea, key, listeners, path, props, reducers, selectors } from 'kea'+import posthog from 'posthog-js'++import api from 'lib/api'+import { lemonToast } from 'lib/lemon-ui/LemonToast'+import { projectLogic } from 'scenes/projectLogic'++import { tasksRunsCommandCreate } from 'products/tasks/frontend/generated/api'+import type { TaskRunBootstrapCreateRequestInitialPermissionModeEnumApi } from 'products/tasks/frontend/generated/api.schemas'++import { getClaudeCodeMeta, resolveToolCall } from './sandbox/sandboxToolResolver'+import { parseSandboxQuestions } from './sandboxQuestionUtils'+import type { sandboxStreamLogicType } from './sandboxStreamLogicType'+import { defaultPermissionDecision, findAllowOptionId } from './sandboxToolPolicy'+import type {+ ContextUsage,+ PermissionRequestRecord,+ ResourceProduct,+ RunArtifacts,+ SandboxProgressStatus,+ SandboxProgressStep,+ SdkSession,+ ThreadItem,+ ThreadItemType,+ ToolInvocation,+ ToolInvocationStatus,+} from './types/sandboxStreamTypes'+import {+ type PermissionOption,+ type PermissionRequestFrame,+ type PosthogPermissionRequestParams,+ type PosthogProgressParams,+ type PosthogUsageUpdateParams,+ type SessionUpdateUsage,+ type SseErrorFrameData,+ type StoredLogEntry,+ isKnownSessionUpdate,+ isNotificationFrame,+ isPermissionRequestFrame,+ isPosthogNotification,+ isSessionUpdateNotification,+ isSessionUpdateUsage,+ isSessionUpdateUserMessage,+ isTaskRunStateFrame,+} from './types/sandboxWireTypes'++export type SandboxSseStatus = 'idle' | 'connecting' | 'open' | 'reconnecting' | 'closed' | 'error'+export type SandboxRunStatus = 'queued' | 'in_progress' | 'completed' | 'failed' | 'cancelled'++export interface SandboxStreamLogicProps {+ /**+ * Stable logic key. PostHog AI passes the conversation id; a generic task viewer (no conversation)+ * passes the task id. The logic operates on `(taskId, runId)` internally, so it never needs the+ * conversation beyond this key and the optional telemetry tag below.+ */+ streamKey: string+ /** Optional telemetry tag — present for PostHog AI conversations, absent for a generic task viewer. */+ conversationId?: string+ /**+ * Read-only/replay mode for a generic run viewer: bootstrap replays the persisted `logs/` snapshot+ * once and never opens SSE — even for an in-progress run. Folded into the logic key so a read-only+ * instance can never share state with a live streaming instance, even for the same `streamKey`.+ */+ replayOnly?: boolean+}++/** Reconnect/backoff constants for the SSE drop-recovery loop. */+export const MAX_SSE_RECONNECT_ATTEMPTS = 5+export const SSE_RECONNECT_BASE_DELAY_MS = 2_000+export const SSE_RECONNECT_MAX_DELAY_MS = 30_000+/**+ * Cumulative cap across all drops in a run — bounds runaway clean-EOF loops that keep dodging the+ * per-drop counter (a connection that opens, immediately drops, and reopens resets `reconnectAttempt`+ * to 0 every cycle, so only this counter catches the loop).+ */+export const MAX_CUMULATIVE_RECONNECT_ATTEMPTS = 30+/** A connection open at least this long before dropping is healthy — its drop is forgiven. */+export const SSE_HEALTHY_CONNECTION_MS = 60_000+export const SANDBOX_INITIAL_PERMISSION_MODE: TaskRunBootstrapCreateRequestInitialPermissionModeEnumApi = 'auto'++/** The crash-error string the in-sandbox agent server writes on a fatal exception. */+const AGENT_CRASH_PREFIX = 'Agent server crashed'++const TERMINAL_RUN_STATUSES: ReadonlySet<string> = new Set(['completed', 'failed', 'cancelled'])++export function isTerminalRunStatus(status: string | null | undefined): boolean {+ return status != null && TERMINAL_RUN_STATUSES.has(status)+}++/** Capped exponential backoff: 2s / 4s / 8s / 16s / 30s. `attempt` is 1-based. */+export function reconnectDelayMs(attempt: number): number {+ const delay = SSE_RECONNECT_BASE_DELAY_MS * 2 ** (attempt - 1)+ return Math.min(delay, SSE_RECONNECT_MAX_DELAY_MS)+}++export interface StreamErrorEnvelope {+ errorTitle: string+ errorMessage?: string+ retryable: boolean+}++/**+ * HTTP status → user-visible error envelope for refetch/open failures. Cloud-agent also emits+ * some of these as `event: error` frames; those carry their own envelope and bypass this table.+ */+export function mapHttpStatusToStreamError(status: number | undefined): StreamErrorEnvelope {+ switch (status) {+ case 401:+ return { errorTitle: 'Cloud authentication expired', retryable: true }+ case 403:+ return { errorTitle: 'Cloud access denied', retryable: true }+ case 404:+ return { errorTitle: 'Conversation backing run not found', retryable: false }+ case 406:+ return { errorTitle: 'Cloud stream unavailable', retryable: true }+ default:+ return { errorTitle: 'Cloud stream failed', retryable: true }+ }+}++/**+ * Recovers the raw text the user typed from a persisted `_posthog/user_message`. The backend+ * prepends a `<posthog_context>…</posthog_context>` block when attachments are present+ * (`context_wrapper.wrap_user_message`); stripping it keeps a replayed prompt identical to the one+ * the live send path echoed via `pushHumanMessage`.+ */+function unwrapUserMessageContent(content: string): string {+ const closeTag = '</posthog_context>'+ if (content.startsWith('<posthog_context>')) {+ const closeIdx = content.indexOf(closeTag)+ if (closeIdx !== -1) {+ return content.slice(closeIdx + closeTag.length).replace(/^\n+/, '')+ }+ }+ return content+}++/**+ * Pull rendered text out of a `_posthog/user_message` frame's `content`. The seeder writes a plain+ * string; the live wire may instead carry ACP content blocks (`[{ type: 'text', text }]`). Returns+ * the concatenated text, or '' when there's nothing renderable.+ */+function extractUserMessageText(content: string | unknown[] | undefined): string {+ if (typeof content === 'string') {+ return content+ }+ if (Array.isArray(content)) {+ return content+ .map((block) =>+ block && typeof block === 'object' && typeof (block as { text?: unknown }).text === 'string'+ ? (block as { text: string }).text+ : ''+ )+ .join('')+ }+ return ''+}++function isRecord(value: unknown): value is Record<string, unknown> {+ return typeof value === 'object' && value !== null && !Array.isArray(value)+}++function normalizeNotificationEntry(entry: unknown): StoredLogEntry | null {+ if (isNotificationFrame(entry)) {+ return entry+ }++ // Older append_log callers wrote `{ notification }` directly, without the stream envelope.+ if (!isRecord(entry) || !isRecord(entry.notification)) {+ return null+ }++ return {+ type: 'notification',+ ...(typeof entry.timestamp === 'string' ? { timestamp: entry.timestamp } : {}),+ notification: entry.notification,+ } as StoredLogEntry+}++function isResumeRun(run: { state?: unknown }): boolean {+ const state = run.state+ return isRecord(state) && typeof state.resume_from_run_id === 'string' && state.resume_from_run_id !== ''+}++/**+ * Union incoming resource products into the accumulated list by `id`, preserving first-seen order.+ * Pure — mirrors the reference `accumulateSessionResources`. Products without an `id` are skipped.+ */+export function mergeResourceProducts(+ existing: ResourceProduct[],+ incoming: { id?: string; label?: string }[]+): ResourceProduct[] {+ const seen = new Set(existing.map((p) => p.id))+ const next = [...existing]+ for (const product of incoming) {+ if (typeof product.id !== 'string' || product.id === '' || seen.has(product.id)) {+ continue+ }+ seen.add(product.id)+ next.push({ id: product.id, label: product.label })+ }+ return next+}++const RUN_ARTIFACT_KEYS = ['prUrl', 'branch', 'baseBranch', 'repo'] as const++/**+ * Latest-wins fold of git artifacts onto the accumulated snapshot — a non-empty string overwrites,+ * undefined/empty values are ignored (so a later frame that omits a field never clears it). Mirrors+ * the `mergeResourceProducts` accumulation pattern.+ */+export function mergeRunArtifacts(existing: RunArtifacts, partial: Partial<RunArtifacts>): RunArtifacts {+ const next: RunArtifacts = { ...existing }+ for (const key of RUN_ARTIFACT_KEYS) {+ const value = partial[key]+ if (typeof value === 'string' && value !== '') {+ next[key] = value+ }+ }+ return next+}++/**+ * Pull the git artifacts a run-shaped payload exposes. The bootstrap `run` carries+ * `state.pr_base_branch`, a top-level `branch`, and `output.pr_url`; a live `task_run_state` frame+ * carries only the top-level `branch` and `output` (no `state`). Both feed through here. The wire is+ * loosely typed, so `state`/`output` are guarded with `isRecord` before any field read.+ */+export function extractRunArtifacts(run: {+ state?: unknown+ output?: unknown+ branch?: string | null+}): Partial<RunArtifacts> {+ const partial: Partial<RunArtifacts> = {}+ const state = isRecord(run.state) ? run.state : undefined+ const output = isRecord(run.output) ? run.output : undefined+ if (typeof run.branch === 'string') {+ partial.branch = run.branch+ }+ if (typeof state?.pr_base_branch === 'string') {+ partial.baseBranch = state.pr_base_branch+ }+ if (typeof state?.repository === 'string') {+ partial.repo = state.repository+ }+ if (typeof output?.pr_url === 'string') {+ partial.prUrl = output.pr_url+ }+ return partial+}++/** Normalize either wire cost shape (a bare number, or `{amount, currency}`) to a number | undefined. */+function normalizeUsageCost(+ cost: number | { amount?: number; currency?: string } | null | undefined+): number | undefined {+ if (cost == null) {+ return undefined+ }+ if (typeof cost === 'number') {+ return cost+ }+ return typeof cost.amount === 'number' ? cost.amount : undefined+}++/** Latest-wins fold of an `_posthog/usage_update` ext-notification onto the context-usage snapshot. */+export function foldUsageNotification(existing: ContextUsage | null, params: PosthogUsageUpdateParams): ContextUsage {+ const next: ContextUsage = { ...existing }+ if (params.used != null) {+ next.tokens = params.used+ }+ if (params.breakdown != null) {+ next.breakdown = params.breakdown+ }+ const cost = normalizeUsageCost(params.cost)+ if (cost !== undefined) {+ next.cost = cost+ }+ return next+}++/** Latest-wins fold of the numeric `session/update` usage aggregate (drives the percentage ring). */+export function foldUsageAggregate(existing: ContextUsage | null, update: SessionUpdateUsage): ContextUsage {+ const next: ContextUsage = { ...existing }+ if (typeof update.used === 'number') {+ next.used = update.used+ }+ if (typeof update.size === 'number') {+ next.size = update.size+ }+ const cost = normalizeUsageCost(update.cost)+ if (cost !== undefined) {+ next.cost = cost+ }+ return next+}++/** Refetch the run's status (plus any git artifacts it now exposes); on failure return the mapped error envelope. */+async function fetchRunStatus(+ taskId: string,+ runId: string+): Promise<{ status: string | null; artifacts: Partial<RunArtifacts> } | { error: StreamErrorEnvelope }> {+ try {+ const run: { status?: string; state?: unknown; output?: unknown; branch?: string | null } =+ await api.tasks.runs.get(taskId, runId)+ return { status: run.status ?? null, artifacts: extractRunArtifacts(run) }+ } catch (error) {+ return { error: mapHttpStatusToStreamError((error as { status?: number })?.status) }+ }+}++/**+ * The id of the parent Task tool call when this frame belongs to a subagent's inner work+ * (`_meta.claudeCode.parentToolCallId`), else undefined. Inner calls are rolled into their parent+ * Task card rather than surfaced as top-level thread items.+ */+export function subagentParentToolCallId(meta: unknown): string | undefined {+ const parent = getClaudeCodeMeta(meta)?.parentToolCallId+ return typeof parent === 'string' && parent ? parent : undefined+}++/**+ * Permission-denial reason from `_meta.claudeCode.toolResponse`, preferring `decisionReason` over+ * the generic `message`. Returns undefined when no `_meta` is present (the inline `canUseTool` path),+ * so the caller can fall back to the content text / existing error.+ */+export function extractDenialReason(meta: unknown): string | undefined {+ const claudeCode = getClaudeCodeMeta(meta)+ const toolResponse = claudeCode?.toolResponse+ if (typeof toolResponse !== 'object' || toolResponse === null) {+ return undefined+ }+ const r = toolResponse as { decisionReason?: unknown; message?: unknown }+ if (typeof r.decisionReason === 'string' && r.decisionReason) {+ return r.decisionReason+ }+ if (typeof r.message === 'string' && r.message) {+ return r.message+ }+ return undefined+}++/**+ * Finds the last buffer of `type` for a wire message id, also matching the derived `${id}@<n>` ids+ * minted when the wire omits `messageId` and every chunk shares the fallback id. Shared by the+ * assistant-message and agent-thought streams, which both buffer incremental chunks this way.+ */+function findLastBufferIndex(state: ThreadItem[], id: string, type: ThreadItemType, incompleteOnly: boolean): number {+ for (let i = state.length - 1; i >= 0; i--) {+ const item = state[i]+ if (+ item.type === type &&+ (item.id === id || item.id.startsWith(`${id}@`)) &&+ (!incompleteOnly || !item.complete)+ ) {+ return i+ }+ }+ return -1+}++/** The in-progress compaction spinner item — cleared when compaction completes or a boundary lands. */+function isPendingCompactingStatus(item: ThreadItem): boolean {+ return item.type === 'status' && item.status === 'compacting' && item.isComplete !== true+}++function insertHumanMessageAtTurnStart(state: ThreadItem[], item: ThreadItem): ThreadItem[] {+ const lastTurnSeparatorIndex = state.findLastIndex((threadItem) => threadItem.type === 'turn_separator')+ const turnStartIndex = lastTurnSeparatorIndex + 1+ const currentTurn = state.slice(turnStartIndex)++ if (currentTurn.some((threadItem) => threadItem.type === 'human_message')) {+ return [...state, item]+ }++ return [...state.slice(0, turnStartIndex), item, ...currentTurn]+}++/**+ * Is this human message already shown in the current turn (since the last separator)? Used to drop a+ * live wire user echo that's already on screen — the optimistic `_client/human_message` of an idle+ * send, or the first wire form of a queue-drained send (which can echo in two forms).+ */+function currentTurnHasHumanText(state: ThreadItem[], text: string): boolean {+ for (let i = state.length - 1; i >= 0; i--) {+ const item = state[i]+ if (item.type === 'turn_separator') {+ return false+ }+ if (item.type === 'human_message' && item.text === text) {+ return true+ }+ }+ return false+}++function mapAcpStatus(status: unknown): ToolInvocationStatus {+ switch (status) {+ case 'in_progress':+ return 'in_progress'+ case 'completed':+ return 'completed'+ case 'failed':+ return 'failed'+ default:+ return 'pending'+ }+}++function normalizeProgressStatus(status: unknown): SandboxProgressStatus {+ switch (status) {+ case 'pending':+ case 'in_progress':+ case 'completed':+ return status+ case 'failed':+ case 'cancelled':+ return 'failed'+ default:+ return 'in_progress'+ }+}++function stringifyOptional(value: unknown): string | undefined {+ return typeof value === 'string' ? value : undefined+}++function parsePermissionOption(raw: unknown): PermissionOption | null {+ if (typeof raw !== 'object' || raw === null) {+ return null+ }+ const r = raw as Record<string, unknown>+ const optionId = r.optionId+ const kind = String(r.kind ?? '')+ // Require only the two fields the card acts on: the `optionId` forwarded on the reply and a+ // non-empty `kind` to classify. The kind vocabulary tracks the agent adapter (`reject` became+ // `reject_once`, etc.), so accept any non-empty kind and let the prefix-based mapper resolve the+ // affordance — an exact-match allowlist silently dropped unknown kinds and blanked the prompt+ // whenever none survived.+ if (typeof optionId !== 'string' || !kind) {+ return null+ }+ const meta = r._meta+ const customInput =+ typeof meta === 'object' && meta !== null && (meta as Record<string, unknown>).customInput === true+ return {+ optionId,+ name: String(r.name ?? ''),+ kind,+ customInput,+ }+}++/**+ * Parses a permission request into a `PermissionRequestRecord` — either the live+ * `data.type === 'permission_request'` SSE envelope or the `_posthog/permission_request`+ * notification params the agent-server persists to the run log (both carry the same fields).+ * The toolCall payload mirrors the ACP `tool_call` shape. Returns null when the frame is malformed+ * or carries no usable options. The wire payload is typed, not validated, so every field read keeps+ * its runtime check.+ */+export function parsePermissionRequestFrame(+ frame: PermissionRequestFrame | PosthogPermissionRequestParams+): PermissionRequestRecord | null {+ const requestId = frame.requestId+ if (typeof requestId !== 'string') {+ return null+ }+ const toolCall = (frame.toolCall ?? {}) as Record<string, unknown>+ const toolCallId = String(toolCall.toolCallId ?? frame.toolCallId ?? '')+ if (!toolCallId) {+ return null+ }+ const options = Array.isArray(frame.options)+ ? frame.options.map(parsePermissionOption).filter((o): o is PermissionOption => o !== null)+ : []+ if (options.length === 0) {+ return null+ }++ const rawServerName = String(toolCall.serverName ?? 'posthog')+ const rawToolName = String(toolCall.toolName ?? '')+ const input = (toolCall.rawInput ?? toolCall.input ?? {}) as Record<string, unknown>++ // Canonical ACP tool name (e.g. `mcp__posthog__exec`, or a built-in like `Bash`). The wire puts+ // it on `_meta.claudeCode.toolName`; the bare fields are the fallback. The default permission+ // policy classifies off this — `mcp__`-prefixed vs built-in, plus the exec sub-tool.+ const meta = toolCall._meta+ const metaRecord = typeof meta === 'object' && meta !== null ? (meta as Record<string, unknown>) : {}+ const claudeCode = getClaudeCodeMeta(meta) ?? {}+ const toolName = String(claudeCode.toolName ?? toolCall.toolName ?? rawToolName)++ // `AskUserQuestion` is routed through the permission framework by the agent (Twig): the question+ // payload rides `_meta.codeToolKind === 'question'` + `_meta.questions`. When present, this renders+ // the interactive question overlay (not the approve/decline card) and is never auto-approved.+ const questions = metaRecord.codeToolKind === 'question' ? parseSandboxQuestions(metaRecord) : []++ return {+ requestId,+ toolCallId,+ toolName,+ options,+ title: toolCall.title as string | undefined,+ description: toolCall.description as string | undefined,+ ...(questions.length > 0 ? { questions } : {}),+ rawToolCall: {+ toolCallId,+ rawServerName,+ rawToolName,+ input,+ status: mapAcpStatus(toolCall.status),+ title: toolCall.title as string | undefined,+ kind: toolCall.kind as string | undefined,+ locations: toolCall.locations as { path: string; line?: number }[] | undefined,+ contentBlocks: Array.isArray(toolCall.content) ? toolCall.content : [],+ meta,+ },+ }+}++/** Who ingested a frame: the `logs/` bootstrap, the live SSE, or a client-injected synthetic entry. */+export type FrameSource = 'replay' | 'live' | 'client'++/** One frame in the ordered log, tagged with its source so the projection can branch on it (§6 resume filter). */+export interface StoredEntry {+ entry: StoredLogEntry+ source: FrameSource+}++/**+ * Ordered, append-only raw-frame log, in render order — the single source of truth. `threadItems`+ * and `toolInvocations` are pure projections of it (see `foldLogToThread`). Frames are appended,+ * never keyed or per-entry deduped: the only place two independently-identified sources overlap is+ * the bootstrap seam (the S3 history vs. the live SSE, which is connected *before* the history loads+ * so no frame is gapped), and that one overlap is reconciled once by `dedupeBufferedAgainstHistory`+ * before the live tail is appended. Steady-state live frames resume exactly after the last-seen+ * Redis id (exclusive), so they never re-deliver — a plain append therefore cannot double the thread.+ */+export interface SandboxLog {+ entries: StoredEntry[]+}++/**+ * The fixed prefix the agent-server's resume builder prepends to the synthetic "resume context"+ * prompt it injects between run start and the genuine human turn on a resume run. That prompt is+ * persisted to the S3 log (it never arrives live), so on bootstrap replay it would otherwise render+ * as a human bubble. The projection drops it when the bootstrapped run is a resume run (§6).+ */+const RESUME_CONTEXT_PREFIX = 'You are resuming a previous conversation.'+function isResumeContextPrompt(text: string): boolean {+ return text.startsWith(RESUME_CONTEXT_PREFIX)+}++/**+ * One-shot multiset reconciliation of the bootstrap seam (port of the reference client's+ * `drainBufferedLogBatches`). While the S3 history loads we connect the live SSE first and buffer+ * its frames; some buffered frames are the same logical entries the history already contains (the+ * live stream and the S3 log overlap around the connect cutoff). This drops each buffered frame a+ * historical frame accounts for, keyed on the ACP `notification` payload — the only field identical+ * across both copies. The SSE `id` is the Redis stream id (absent from S3), and the envelope+ * `timestamp` is stamped independently on the persist and the live-publish paths, so neither can be+ * part of the key. A *multiset* (counts, not a set) so N genuine repeats of an identical payload+ * survive: each historical copy absorbs exactly one buffered copy, and any buffered surplus passes+ * through. Steady-state live frames after the drain are appended directly and never deduped.+ */+function dedupeBufferedAgainstHistory(buffered: StoredLogEntry[], history: StoredLogEntry[]): StoredLogEntry[] {+ const seamKey = (entry: StoredLogEntry): string => JSON.stringify(entry.notification)+ const historicalCounts = new Map<string, number>()+ for (const entry of history) {+ const key = seamKey(entry)+ historicalCounts.set(key, (historicalCounts.get(key) ?? 0) + 1)+ }+ const survivors: StoredLogEntry[] = []+ for (const entry of buffered) {+ const key = seamKey(entry)+ const remaining = historicalCounts.get(key) ?? 0+ if (remaining > 0) {+ historicalCounts.set(key, remaining - 1)+ continue+ }+ survivors.push(entry)+ }+ return survivors+}++export interface FoldedThread {+ threadItems: ThreadItem[]+ toolInvocations: Map<string, ToolInvocation>+}++/**+ * Pure projection: fold the ordered log into the rendered thread (and the tool-invocation map the+ * renderer looks up). The fold rules (chunk buffering with the tail rule, tool-update merge,+ * human-turn hoisting) are computed deterministically from the ordered log so item ids are stable+ * across re-folds. `isResumeRun` drives the §6 resume-context filter; per-entry `source` decides+ * whether a wire user turn renders (replay) or is left to the live echo (live).+ */+export function foldLogToThread(entries: StoredEntry[], options: { isResumeRun: boolean }): FoldedThread {+ let items: ThreadItem[] = []+ const invocations = new Map<string, ToolInvocation>()+ // Texts already rendered by a `_posthog/user_message`, so a later identical `user_message_chunk`+ // (resume chains persist the same turn in both forms) is consumed once rather than doubled.+ const rememberedHumanTexts = new Map<string, number>()+ let humanCount = 0+ let bubbleSeq = 0+ let separatorSeq = 0+ let errorSeq = 0+ let statusSeq = 0+ let compactSeq = 0+ let taskSeq = 0++ const pushHuman = (text: string): void => {+ items = insertHumanMessageAtTurnStart(items, {+ id: `human-${humanCount++}`,+ type: 'human_message',+ text,+ complete: true,+ })+ }++ const appendChunk = (id: string, type: ThreadItemType, delta: string): void => {+ const idx = findLastBufferIndex(items, id, type, false)+ // Continue the matched buffer only while it's still the tail and incomplete; otherwise (no+ // buffer, a finalized one, or one interrupted by a tool call/separator) start a fresh bubble+ // so text resuming after an interruption renders in chronological order. Every fresh bubble+ // gets a unique `${id}@<seq>` id — the wire often omits `messageId` (and the S3 replay always+ // does, since the backend drops chunks), so the bare fallback id would collide as a React key+ // across messages. The continuation lookup matches the `${id}@` prefix, so it still works.+ if (idx === -1 || items[idx].complete || idx !== items.length - 1) {+ items.push({ id: `${id}@${bubbleSeq++}`, type, text: delta, complete: false })+ return+ }+ items[idx] = { ...items[idx], text: (items[idx].text ?? '') + delta }+ }++ const finalizeMessage = (id: string, text: string): void => {+ let idx = findLastBufferIndex(items, id, 'assistant_message', true)+ if (idx === -1) {+ // The wire isn't consistent about carrying `messageId` across a message's chunks and its+ // closing `agent_message` (the chunks often have one, the finalize doesn't, or vice+ // versa), so an id-keyed lookup can miss the buffer the chunks opened. Fall back to the+ // message still being streamed — the last open assistant buffer in the current turn —+ // and close that, rather than appending a second bubble with the same text. Bounded at+ // the turn separator so a finalize never reaches back into a prior turn.+ for (let i = items.length - 1; i >= 0; i--) {+ if (items[i].type === 'turn_separator') {+ break+ }+ if (items[i].type === 'assistant_message' && !items[i].complete) {+ idx = i+ break+ }+ }+ }+ if (idx === -1) {+ // No buffer to close (the common replay case: S3 drops chunks, so a finalized message+ // arrives alone). Push a fresh bubble with a unique id — a bare fallback id would collide+ // as a React key with every other no-`messageId` message in the thread.+ items.push({ id: `${id}@${bubbleSeq++}`, type: 'assistant_message', text, complete: true })+ return+ }+ items[idx] = { ...items[idx], text, complete: true }+ }++ const upsertInvocationItem = (toolCallId: string): void => {+ if (!items.some((item) => item.type === 'tool_invocation' && item.toolCallId === toolCallId)) {+ items.push({ id: toolCallId, type: 'tool_invocation', toolCallId })+ }+ }++ const renderReplayHuman = (rawText: string, remember: boolean): void => {+ const text = unwrapUserMessageContent(rawText)+ if (!text) {+ return+ }+ if (options.isResumeRun && isResumeContextPrompt(text)) {+ return+ }+ if (!remember) {+ const seen = rememberedHumanTexts.get(text) ?? 0+ if (seen > 0) {+ rememberedHumanTexts.set(text, seen - 1)+ return+ }+ }+ pushHuman(text)+ if (remember) {+ rememberedHumanTexts.set(text, (rememberedHumanTexts.get(text) ?? 0) + 1)+ }+ }++ const renderLiveHuman = (rawText: string): void => {+ const text = unwrapUserMessageContent(rawText)+ if (!text) {+ return+ }+ // The server echoes every user send live. An idle send already rendered it optimistically via+ // `_client/human_message`; a queue-drained send (dispatched with `addToThread: false`) did not,+ // so its echo is what surfaces it. Render unless the current turn already shows this message —+ // which both drops the optimistic-paired echo and dedupes a send echoed in two wire forms.+ if (currentTurnHasHumanText(items, text)) {+ return+ }+ pushHuman(text)+ }++ const handleToolCallUpdate = (+ update: Record<string, unknown>,+ notification: StoredLogEntry['notification']+ ): void => {+ const toolCallId = String(update.toolCallId ?? '')+ if (!toolCallId) {+ return+ }+ const existing = invocations.get(toolCallId)+ const status = mapAcpStatus(update.status ?? existing?.status)+ const rawInput =+ update.rawInput && typeof update.rawInput === 'object'+ ? (update.rawInput as Record<string, unknown>)+ : update.input && typeof update.input === 'object'+ ? (update.input as Record<string, unknown>)+ : undefined+ const denialReason = status === 'failed' ? extractDenialReason(update._meta) : undefined+ const errorMessage =+ (update.error as { message?: string } | null)?.message ??+ denialReason ??+ (status === 'failed' ? notification.error?.message : undefined)+ const updateContent = Array.isArray(update.content) ? update.content : []++ if (!existing) {+ // A reconnect can deliver a terminal update whose creating `tool_call` was lost — upsert a+ // minimal invocation so the card still renders instead of vanishing.+ invocations.set(toolCallId, {+ toolCallId,+ rawServerName: 'posthog',+ rawToolName: '',+ input: rawInput ?? {},+ status,+ title: update.title as string | undefined,+ locations: update.locations as { path: string; line?: number }[] | undefined,+ contentBlocks: updateContent,+ meta: update._meta,+ ...(errorMessage !== undefined ? { error: { message: errorMessage } } : {}),+ })+ if (!subagentParentToolCallId(update._meta)) {+ upsertInvocationItem(toolCallId)+ }+ return+ }++ invocations.set(toolCallId, {+ ...existing,+ status,+ title: (update.title as string | undefined) ?? existing.title,+ progress: update.progress ?? existing.progress,+ output: update.rawOutput ?? existing.output,+ locations: (update.locations as { path: string; line?: number }[] | undefined) ?? existing.locations,+ contentBlocks: [...existing.contentBlocks, ...updateContent],+ error: errorMessage !== undefined ? { message: errorMessage } : existing.error,+ ...(rawInput ? { input: rawInput } : {}),+ ...(update._meta ? { meta: update._meta } : {}),+ })+ }++ for (const { entry, source } of entries) {+ const notification = entry.notification+ const method = notification.method+ const params = (notification.params ?? {}) as Record<string, unknown>++ if (method === '_client/human_message') {+ pushHuman(String(params.content ?? ''))+ continue+ }+ if (method === '_client/error') {+ items.push({+ id: `error-${errorSeq++}`,+ type: 'error',+ errorMessage: String(params.message ?? ''),+ variant: params.variant === 'crash' ? 'crash' : 'error',+ })+ continue+ }+ if (method === '_posthog/error') {+ items.push({+ id: `error-${errorSeq++}`,+ type: 'error',+ errorMessage: String(params.message ?? notification.error?.message ?? 'Agent error'),+ variant: 'error',+ })+ continue+ }+ if (method === '_posthog/turn_complete') {+ items.push({ id: `turn-${separatorSeq++}`, type: 'turn_separator' })+ continue+ }+ if (method === '_posthog/progress') {+ const group = stringifyOptional(params.group)+ const step = stringifyOptional(params.step)+ const label = stringifyOptional(params.label)+ if (group && step && label) {+ const detail = stringifyOptional(params.detail)+ const nextStep: SandboxProgressStep = {+ key: step,+ status: normalizeProgressStatus(params.status),+ label,+ ...(detail !== undefined ? { detail } : {}),+ }+ const idx = items.findIndex((item) => item.type === 'progress' && item.progressGroup === group)+ if (idx === -1) {+ items.push({+ id: `progress-${group}`,+ type: 'progress',+ progressGroup: group,+ progressSteps: [nextStep],+ })+ } else {+ const existingSteps = items[idx].progressSteps ?? []+ const stepIdx = existingSteps.findIndex((s) => s.key === step)+ items[idx] = {+ ...items[idx],+ progressSteps:+ stepIdx === -1+ ? [...existingSteps, nextStep]+ : existingSteps.map((s, i) => (i === stepIdx ? nextStep : s)),+ }+ }+ }+ continue+ }+ if (method === '_posthog/status') {+ const status = String(params.status ?? '')+ const isComplete = params.isComplete === true+ if (status === 'compacting' && isComplete) {+ items = items.filter((item) => !isPendingCompactingStatus(item))+ } else {+ items.push({ id: `status-${statusSeq++}`, type: 'status', status, isComplete })+ }+ continue+ }+ if (method === '_posthog/compact_boundary') {+ items = items.filter((item) => !isPendingCompactingStatus(item))+ items.push({+ id: `compact-${compactSeq++}`,+ type: 'compact_boundary',+ trigger: stringifyOptional(params.trigger),+ preTokens: typeof params.preTokens === 'number' ? params.preTokens : undefined,+ contextSize: typeof params.contextSize === 'number' ? params.contextSize : undefined,+ })+ continue+ }+ if (method === '_posthog/task_notification') {+ items.push({+ id: `task-${taskSeq++}`,+ type: 'task_notification',+ status: stringifyOptional(params.status),+ summary: stringifyOptional(params.summary),+ })+ continue+ }+ if (method === '_posthog/user_message') {+ const userText = extractUserMessageText(params.content as string | unknown[] | undefined)+ if (source === 'replay') {+ renderReplayHuman(userText, true)+ } else {+ renderLiveHuman(userText)+ }+ continue+ }+ if (method?.startsWith('_posthog/')) {+ // run_started, usage_update, resources_used, sdk_session, console, sandbox_output, … — no thread item.+ continue+ }+ if (method !== 'session/update') {+ // session/prompt and everything else never produces a thread item.+ continue+ }+ const update = params.update+ if (!isRecord(update)) {+ continue+ }+ const sessionUpdate = update.sessionUpdate+ if (sessionUpdate === 'user_message_chunk' || sessionUpdate === 'user_message') {+ const content = update.content as { text?: string } | undefined+ const userText = String(content?.text ?? update.text ?? '')+ if (source === 'replay') {+ renderReplayHuman(userText, false)+ } else {+ renderLiveHuman(userText)+ }+ continue+ }+ const content = update.content as { text?: string } | undefined+ switch (sessionUpdate) {+ case 'agent_message_chunk':+ appendChunk(+ String(update.messageId ?? 'current'),+ 'assistant_message',+ String(content?.text ?? update.text ?? '')+ )+ break+ case 'agent_message':+ finalizeMessage(String(update.messageId ?? 'current'), String(content?.text ?? update.text ?? ''))+ break+ case 'agent_thought_chunk':+ appendChunk(+ String(update.messageId ?? 'current-thought'),+ 'assistant_thought',+ String(content?.text ?? update.text ?? '')+ )+ break+ case 'tool_call': {+ const toolCallId = String(update.toolCallId ?? '')+ if (!toolCallId) {+ break+ }+ invocations.set(toolCallId, {+ toolCallId,+ rawServerName: String(update.serverName ?? 'posthog'),+ rawToolName: String(update.toolName ?? ''),+ input: (update.rawInput ?? update.input ?? {}) as Record<string, unknown>,+ status: mapAcpStatus(update.status),+ title: update.title as string | undefined,+ kind: update.kind as string | undefined,+ locations: update.locations as { path: string; line?: number }[] | undefined,+ contentBlocks: Array.isArray(update.content) ? update.content : [],+ meta: update._meta,+ })+ // A subagent's inner tool calls carry the parent Task's id; they belong inside that+ // card, not as top-level siblings, so keep them out of the thread.+ if (!subagentParentToolCallId(update._meta)) {+ upsertInvocationItem(toolCallId)+ }+ break+ }+ case 'tool_call_update':+ handleToolCallUpdate(update, notification)+ break+ }+ }++ return { threadItems: items, toolInvocations: invocations }+}++/**+ * Owns the SSE connection to the products/tasks stream endpoint (a `fetch` reader driven by+ * `eventsource-parser`, so a reconnect can resume via a Last-Event-ID header), parses the ACP wire+ * format, and produces thread-shaped state the renderer consumes. Coexistence sibling to+ * `maxThreadLogic`'s streaming loop — the sandbox path never enters the LangGraph stream loop.+ *+ * Covers open/close, `data.type === 'notification'` → `ingestAcpFrame` dispatch, terminal status,+ * and stream-error capture, plus the reconnect/backoff loop on SSE drops, the ordered append-only+ * log the projection folds, HTTP-status error mapping, and the `bootstrapRun`+ * connect-first/buffer/snapshot/drain helper.+ *+ * Keyed by `streamKey` (the conversation id for PostHog AI, the task id for a generic task viewer)+ * so concurrent streams keep independent stream state and connections.+ */+export const sandboxStreamLogic = kea<sandboxStreamLogicType>([+ // `replayOnly` needs a default so selectors can depend on it as a prop (kea throws on a missing prop).+ props({ replayOnly: false } as SandboxStreamLogicProps),+ // 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) => ['scenes', 'max', 'sandboxStreamLogic', key]),+ connect(() => ({+ values: [projectLogic, ['currentProjectId']],+ })),+ actions({+ /**+ * Bootstrap an existing run on conversation open. Terminal run: replay the `logs/` history+ * and stay read-only (no SSE). In-progress run: connect the SSE *first* (buffering live+ * frames), then read the `logs/` snapshot, then drain the buffered tail against it+ * (`dedupeBufferedAgainstHistory`) so the seam neither duplicates nor gaps. `justCreatedRun`+ * skips the `logs/` round-trip (fresh-run fast path — nothing historical to assemble).+ */+ bootstrapRun: (payload: { taskId: string; runId: string; justCreatedRun?: boolean; traceId?: string }) =>+ payload,+ openSseForRun: (payload: { taskId: string; runId: string; startLatest?: boolean; traceId?: string }) => payload,+ /** Internal: the read-only replay snapshot finished loading — clears the bootstrap spinner. */+ bootstrapReplayComplete: true,+ closeSse: true,+ sseConnecting: true,+ sseOpened: true,+ sseReconnecting: (attempt: number) => ({ attempt }),+ /** Internal: an SSE drop initiates the refetch + backoff loop. */+ sseDropped: true,+ /**+ * Frame ingestion — appends one frame to the log and runs its one-shot side effects+ * (telemetry, permission routing, value folds). Called by the live SSE listener+ * (`source: 'live'`), the products/tasks `logs/` replay (`source: 'replay'`), and the+ * bootstrap drain (the deduped live tail). Telemetry is suppressed for replay; the+ * permission/run-started/tool-completion guards keep the side effects fired-once without a+ * per-frame key. The resume cursor (`cache.lastEventId`) is stamped by the SSE reader, not here.+ */+ ingestAcpFrame: (entry: StoredLogEntry, source: FrameSource = 'live') => ({ entry, source }),+ /** Append frames to the ordered log (the single source of truth). */+ appendEntries: (entries: StoredEntry[]) => ({ entries }),+ /** Records whether the bootstrapped run is a resume run, so the projection can drop its synthetic resume prompt. */+ markBootstrapResumeRun: (value: boolean) => ({ value }),+ /**+ * Surface a permission request. `replayedFromHistory` marks requests re-derived from the+ * `logs/` bootstrap — they restore card state but don't re-fire telemetry (the event+ * already fired when the request was live).+ */+ ingestPermissionRequest: (record: PermissionRequestRecord, replayedFromHistory: boolean = false) => ({+ record,+ replayedFromHistory,+ }),+ /**+ * Entry point for every parsed permission request. Applies the default tool policy+ * (`sandboxToolPolicy`): auto-approve built-in tools + non-destructive PostHog exec, prompt+ * for update/delete exec (and other MCP). Replayed-from-history requests are never+ * auto-approved — they're a read-only restore and the run may already be terminal.+ */+ routePermissionRequest: (record: PermissionRequestRecord, replayedFromHistory: boolean = false) => ({+ record,+ replayedFromHistory,+ }),+ /** Silently POST `allow` for a request the default policy auto-approves (no card shown). */+ autoApprovePermissionRequest: (record: PermissionRequestRecord, optionId: string) => ({ record, optionId }),+ /** Pin a requestId as seen without surfacing a card, so a reconnect replay can't re-process it. */+ markPermissionRequestSeen: (requestId: string) => ({ requestId }),+ /**+ * The request was answered — by this client (successful POST), another tab/client, or a+ * `_posthog/permission_resolved` log entry. Clears the matching card and pins the id so+ * reconnect/bootstrap replays cannot re-surface it.+ */+ markPermissionRequestResolved: (requestId: string) => ({ requestId }),+ /**+ * User picked an option on the approval card. POSTs the reply to the sandbox `permission/`+ * endpoint (which routes to the products/tasks `permission_response` command); the pending+ * request clears only once the POST succeeds, so a failure keeps the card for retry.+ * `customInput` carries `reject_with_feedback` text. `answers` carries `AskUserQuestion`+ * selections (keyed by question text) — the agent reads `_meta.answers` to resolve the question.+ */+ respondToPermission: (payload: {+ requestId: string+ optionId: string+ customInput?: string+ answers?: Record<string, string>+ }) => payload,+ clearPermissionRequest: true,+ /**+ * Cancel a run via the generic tasks relay. With no argument, cancels the streamed run+ * (`cache.activeRun`); pass an explicit run to cancel a warm Run the renderer isn't streaming.+ */+ cancelRun: (run?: { taskId: string; runId: string }) => ({ run }),+ /**+ * Internal: the reply POST failed. Resets the in-flight flag (so the surviving card's+ * buttons re-enable for retry) without coupling that reset to unrelated stream errors.+ */+ permissionResponseFailed: true,+ handleTerminalStatus: (status: {+ status: SandboxRunStatus+ errorMessage?: string | null+ replayedFromHistory?: boolean+ }) => status,+ handleStreamError: (envelope: { errorTitle: string; errorMessage?: string; retryable: boolean }) => envelope,+ // Value-fold side effects emitted by ingestAcpFrame (thread items are derived in the projection).+ setCurrentMode: (mode: string) => ({ mode }),+ setCurrentProgress: (progress: string) => ({ progress }),+ /** Optional `task_run_state.stage` — wired for a future richer status surface (G6). */+ setCurrentStage: (stage: string | null) => ({ stage }),+ markRunStarted: true,+ markTurnComplete: true,+ /** Echoes the user's own message into the thread as a `client`-sourced log entry (the wire never replays a live turn). */+ pushHumanMessage: (content: string) => ({ content }),+ /** Injects a client-side error (terminal failure / stream disconnect) into the log as a `client`-sourced entry. */+ pushErrorItem: (errorMessage: string, variant: 'error' | 'crash' = 'error') => ({ errorMessage, variant }),+ /** Union the products an answer was grounded in — accumulates across the whole session. */+ mergeResourcesUsed: (products: { id?: string; label?: string }[]) => ({ products }),+ /** Latest-wins merge of git artifacts (PR url / branch / base / repo) a run exposes. */+ mergeRunArtifacts: (partial: Partial<RunArtifacts>) => ({ partial }),+ /** Latest-wins context-usage snapshot fold (token/cost/breakdown or numeric aggregate). */+ setContextUsage: (usage: ContextUsage) => ({ usage }),+ /** Diagnostic `_posthog/sdk_session` plumbing — no UI. */+ setSdkSession: (session: SdkSession) => ({ session }),+ reset: true,+ }),+ reducers({+ sseStatus: [+ 'idle' as SandboxSseStatus,+ {+ sseConnecting: () => 'connecting',+ sseOpened: () => 'open',+ sseReconnecting: () => 'reconnecting',+ closeSse: () => 'closed',+ handleStreamError: () => 'error',+ reset: () => 'idle',+ },+ ],+ reconnectAttempt: [+ 0,+ {+ sseReconnecting: (_, { attempt }) => attempt,+ // A successful (re)connection clears the counter; bootstrapping a run starts fresh.+ sseOpened: () => 0,+ bootstrapRun: () => 0,+ reset: () => 0,+ },+ ],+ // Counts every drop in the run regardless of the per-drop counter (healthy-connection drops+ // don't bump `reconnectAttempt`, and a clean-EOF reopen loop keeps resetting it). Bounds+ // runaway loops via MAX_CUMULATIVE_RECONNECT_ATTEMPTS. Cleared only on a fresh bootstrap.+ cumulativeReconnectAttempt: [+ 0,+ {+ sseReconnecting: (state) => state + 1,+ bootstrapRun: () => 0,+ reset: () => 0,+ },+ ],+ currentRunStatus: [+ null as SandboxRunStatus | null,+ {+ // A reconnect reopens the same in-flight run — keep its known status rather than+ // flickering back to queued; only a fresh open (no/terminal status) resets.+ openSseForRun: (state) => (state && !isTerminalRunStatus(state) ? state : 'queued'),+ handleTerminalStatus: (_, { status }) => status,+ reset: () => null,+ },+ ],+ // Trace correlation for the telemetry inventory. The SSE bypasses Django, so the frontend+ // supplies the trace_id it minted for POST /sandbox/ when it opened the run; conversation_id+ // is this keyed logic's own props.conversationId. Undefined for history-loaded runs — a+ // reload can't recover the trace_id the original run was sent under.+ traceId: [+ null as string | null,+ {+ bootstrapRun: (state, { traceId }) => traceId ?? state,+ openSseForRun: (state, { traceId }) => traceId ?? state,+ reset: () => null,+ },+ ],+ // The single source of truth: an ordered, append-only log of every ingested frame (plus+ // client-injected synthetic entries). `threadItems` and `toolInvocations` are pure+ // projections of it (see the selectors). The bootstrap seam is reconciled once before its+ // live tail is appended (see `bootstrapRun` / `dedupeBufferedAgainstHistory`), and+ // steady-state live frames resume exclusively after the last-seen Redis id, so a plain+ // append never doubles the thread.+ log: [+ { entries: [] } as SandboxLog,+ {+ appendEntries: (state, { entries }) =>+ entries.length === 0 ? state : { entries: [...state.entries, ...entries] },+ reset: () => ({ entries: [] }),+ },+ ],+ // True while a bootstrap is in flight before the thread has anything to show. Cleared once the+ // live stream opens, the read-only replay snapshot finishes, or an error surfaces. Drives the+ // read-only viewer's initial spinner.+ bootstrapLoading: [+ false,+ {+ bootstrapRun: () => true,+ sseOpened: () => false,+ bootstrapReplayComplete: () => false,+ handleStreamError: () => false,+ reset: () => false,+ },+ ],+ // Whether the bootstrapped run is a resume run — drives the §6 resume-prompt filter in the+ // projection. Set from `run.state.resume_from_run_id` when bootstrap fetches the run.+ isBootstrapResumeRun: [+ false,+ {+ markBootstrapResumeRun: (_, { value }) => value,+ reset: () => false,+ },+ ],+ pendingPermissionRequest: [+ null as PermissionRequestRecord | null,+ {+ ingestPermissionRequest: (_, { record }) => record,+ // Cleared on resolution (successful POST or a permission_resolved entry), NOT on+ // respondToPermission dispatch — a failed POST keeps the card so the user can retry.+ markPermissionRequestResolved: (state, { requestId }) =>+ state?.requestId === requestId ? null : state,+ clearPermissionRequest: () => null,+ // A terminal run can't accept approvals — drop a card re-derived from its history.+ handleTerminalStatus: (state, { status }) => (isTerminalRunStatus(status) ? null : state),+ reset: () => null,+ },+ ],+ // requestIds ever surfaced, so a reconnect's full replay can't double-fire telemetry or+ // re-ingest a request this client already knows about.+ seenPermissionRequestIds: [+ new Set<string>(),+ {+ ingestPermissionRequest: (state, { record }) => {+ const next = new Set(state)+ next.add(record.requestId)+ return next+ },+ markPermissionRequestSeen: (state, { requestId }) => {+ const next = new Set(state)+ next.add(requestId)+ return next+ },+ reset: () => new Set<string>(),+ },+ ],+ // requestIds answered (locally or observed via permission_resolved) — replayed requests+ // with these ids must never re-surface as pending.+ resolvedPermissionRequestIds: [+ new Set<string>(),+ {+ markPermissionRequestResolved: (state, { requestId }) => {+ const next = new Set(state)+ next.add(requestId)+ return next+ },+ reset: () => new Set<string>(),+ },+ ],+ // In-flight state for the approval reply POST — drives the input card's loading/disabled+ // props. Cleared on resolution (success) and on the POST's own failure (the card stays+ // pending, so the buttons must re-enable for retry).+ respondingToPermission: [+ false,+ {+ respondToPermission: () => true,+ markPermissionRequestResolved: () => false,+ clearPermissionRequest: () => false,+ permissionResponseFailed: () => false,+ reset: () => false,+ },+ ],+ currentMode: [+ null as string | null,+ {+ setCurrentMode: (_, { mode }) => mode,+ reset: () => null,+ },+ ],+ currentProgress: [+ null as string | null,+ {+ setCurrentProgress: (_, { progress }) => progress,+ markTurnComplete: () => null,+ reset: () => null,+ },+ ],+ // Optional `task_run_state.stage` — generally unset for PHAI runs, but cheap to track so a+ // future richer status surface (G6) can render "research / plan / build" without re-touching+ // this logic. No render consumes it yet.+ currentStage: [+ null as string | null,+ {+ setCurrentStage: (_, { stage }) => stage,+ reset: () => null,+ },+ ],+ runStarted: [+ false,+ {+ markRunStarted: () => true,+ reset: () => false,+ },+ ],+ turnComplete: [+ false,+ {+ markTurnComplete: () => true,+ // A run emits `_posthog/run_started` once; a follow-up message on the same run starts+ // a fresh turn with no new run_started frame, so a human message also reopens the+ // turn — otherwise the thinking indicator would stay off for the whole follow-up.+ markRunStarted: () => false,+ pushHumanMessage: () => false,+ reset: () => false,+ },+ ],+ // Products the agent grounded answers in, unioned by id (first-seen order) across the whole+ // session. NOT cleared on markTurnComplete — the bar accumulates; only a reset clears it.+ resourcesUsed: [+ [] as ResourceProduct[],+ {+ mergeResourcesUsed: (state, { products }) => mergeResourceProducts(state, products),+ reset: () => [],+ },+ ],+ // Git artifacts a coding run exposes (PR url, working branch, base branch, repo), accumulated+ // latest-wins from the bootstrap run fetch and live task_run_state frames. The pre/post-turn+ // coding UI reads this and self-hides while empty, so a pure-analytics conversation shows+ // nothing. NOT cleared on markTurnComplete — only a reset clears it.+ runArtifacts: [+ {} as RunArtifacts,+ {+ mergeRunArtifacts: (state, { partial }) => mergeRunArtifacts(state, partial),+ reset: () => ({}),+ },+ ],+ // Latest-wins context-usage snapshot for the footer ring. The setContextUsage payload is the+ // already-folded snapshot (the listener merges onto the prior value).+ contextUsage: [+ null as ContextUsage | null,+ {+ setContextUsage: (_, { usage }) => usage,+ reset: () => null,+ },+ ],+ // Diagnostic resume plumbing — adapter/session identity for telemetry. No UI.+ sdkSession: [+ null as SdkSession | null,+ {+ setSdkSession: (_, { session }) => session,+ reset: () => null,+ },+ ],+ }),+ selectors({+ /**+ * Pure projection of the ordered log into the rendered thread plus the tool-invocation map.+ * Memoized on `log` identity, so it recomputes only when a frame is actually appended.+ */+ foldedThread: [+ (s) => [s.log, s.isBootstrapResumeRun],+ (log, isResumeRun): FoldedThread => foldLogToThread(log.entries, { isResumeRun }),+ ],+ threadItems: [(s) => [s.foldedThread], (foldedThread): ThreadItem[] => foldedThread.threadItems],+ toolInvocations: [+ (s) => [s.foldedThread],+ (foldedThread): Map<string, ToolInvocation> => foldedThread.toolInvocations,+ ],+ /**+ * Whether the agent is actively working a turn — drives the thread's thinking indicator.+ * Off once the turn completes, the run reaches a terminal status (a failed or cancelled+ * run may never emit `_posthog/turn_complete`), or the stream errors out.+ *+ * A run is "in flight" from the moment it is `queued` — keying off `currentRunStatus` as+ * well as `runStarted` lights the indicator during the multi-second cold-boot window before+ * the first `_posthog/run_started` frame, which `runStarted` alone misses.+ */+ isThinking: [+ // `replayOnly` always resolves (default in `props`); `!` drops the optional-prop `undefined`.+ (s, p) => [s.runStarted, s.turnComplete, s.currentRunStatus, s.sseStatus, p.replayOnly!],+ (runStarted, turnComplete, currentRunStatus, sseStatus, replayOnly): boolean => {+ // A read-only snapshot is never "thinking" — it's a static replay, so the indicator+ // must never spin (an in-progress run replayed read-only has no live turn to await).+ if (replayOnly) {+ return false+ }+ if (sseStatus === 'error' || isTerminalRunStatus(currentRunStatus)) {+ return false+ }+ const runInFlight = runStarted || currentRunStatus === 'queued' || currentRunStatus === 'in_progress'+ return runInFlight && !turnComplete+ },+ ],+ /**+ * Stream lifecycle phase gating the bottom-of-thread thinking indicator. `provisioning` = the+ * cold-boot window — the stream is opening or open but the agent hasn't started yet (the+ * workflow is still setting up the sandbox); it holds the gerund loader off until `run_started`+ * so it can't show before a turn begins. Boot UX is surfaced by `_posthog/progress` items, not+ * a dedicated indicator. `thinking` = the agent is working a turn (mirrors `isThinking`), and is+ * what `SandboxThreadView` gates the gerund loader on; `idle` otherwise (terminal, errored, or+ * not yet connecting). A read-only viewer is always `idle` — it never streams.+ */+ streamPhase: [+ (s, p) => [s.runStarted, s.isThinking, s.currentRunStatus, s.sseStatus, p.replayOnly!],+ (runStarted, isThinking, currentRunStatus, sseStatus, replayOnly): 'provisioning' | 'thinking' | 'idle' => {+ // A read-only snapshot never provisions or thinks — there is no live stream behind it.+ if (replayOnly) {+ return 'idle'+ }+ const connecting = sseStatus === 'connecting' || sseStatus === 'open' || sseStatus === 'reconnecting'+ if (connecting && !runStarted && !isTerminalRunStatus(currentRunStatus)) {+ return 'provisioning'+ }+ if (isThinking) {+ return 'thinking'+ }+ return 'idle'+ },+ ],+ /** Whether the run exposes any git artifact worth surfacing — gates the pre/post-turn coding UI. */+ hasGitArtifacts: [+ (s) => [s.runArtifacts],+ (runArtifacts): boolean => !!runArtifacts.prUrl || !!runArtifacts.branch,+ ],+ }),+ listeners(({ values, actions, cache, props }) => ({+ bootstrapRun: async ({ taskId, runId, justCreatedRun }, breakpoint) => {+ const projectId = values.currentProjectId+ if (projectId === null) {+ actions.handleStreamError({ errorTitle: 'No current project', retryable: false })+ return+ }++ // Read-only viewer: replay the `logs/` snapshot once and never open SSE, regardless of run+ // status. `breakpoint()` cancels a superseded in-flight bootstrap (a remount / StrictMode+ // double-invoke), and the log-empty guard before folding keeps a re-bootstrap of a shared+ // keyed instance (a second mounted viewer of the same run) from doubling the thread.+ if (props.replayOnly) {+ let replayRun: { status?: string; state?: unknown; output?: unknown; branch?: string | null }+ try {+ replayRun = await api.tasks.runs.get(taskId, runId)+ } catch (error) {+ actions.handleStreamError(mapHttpStatusToStreamError((error as { status?: number })?.status))+ return+ }+ breakpoint()+ actions.markBootstrapResumeRun(isResumeRun(replayRun))+ actions.mergeRunArtifacts(extractRunArtifacts(replayRun))++ let replayEntries: unknown[]+ try {+ replayEntries = await api.tasks.runs.getLogEntries(taskId, runId)+ } catch (error) {+ actions.handleStreamError(mapHttpStatusToStreamError((error as { status?: number })?.status))+ return+ }+ breakpoint()+ if (values.log.entries.length === 0) {+ replayEntries+ .map(normalizeNotificationEntry)+ .filter((entry): entry is StoredLogEntry => entry !== null)+ .forEach((entry) => actions.ingestAcpFrame(entry, 'replay'))+ }++ if (isTerminalRunStatus(replayRun.status ?? null)) {+ // Record the terminal status read-only — no SSE to close, no termination telemetry.+ actions.handleTerminalStatus({+ status: replayRun.status as SandboxRunStatus,+ replayedFromHistory: true,+ })+ }+ actions.bootstrapReplayComplete()+ return+ }++ // Persistent provisioning flag for disconnect telemetry: stays true across the async+ // gap between bootstrap and the first connection/run_started. Cleared on the first+ // `sseOpened`/`_posthog/run_started`.+ cache.isBootstrapping = true++ // Fresh-run fast path: nothing historical to assemble — stream from the top, with nothing+ // to buffer or drain.+ if (justCreatedRun) {+ actions.openSseForRun({ taskId, runId, startLatest: false })+ return+ }++ // Existing run: read the status first to branch terminal (read-only history) vs.+ // in-progress (connect-first, then reconcile the seam).+ let run: { status?: string; state?: unknown; output?: unknown; branch?: string | null }+ try {+ run = await api.tasks.runs.get(taskId, runId)+ } catch (error) {+ actions.handleStreamError(mapHttpStatusToStreamError((error as { status?: number })?.status))+ return+ }+ breakpoint()+ // Flag the run's resume-ness so the projection can drop the synthetic resume-context+ // prompt (§6) before any history frame folds.+ actions.markBootstrapResumeRun(isResumeRun(run))+ // Surface any git artifacts the run already carries (working/base branch, an opened PR)+ // so the pre-turn header and post-turn PR card render immediately on reopen.+ actions.mergeRunArtifacts(extractRunArtifacts(run))+ const terminal = isTerminalRunStatus(run.status ?? null)++ // Connect the live SSE *before* reading the S3 snapshot for an in-progress run. Frames the+ // agent emits while the history loads are then captured by the live stream and buffered+ // (see `handleSseEvent`), not gapped between the snapshot read and the connect cutoff. The+ // buffered tail is reconciled against the history once the snapshot lands (the drain below).+ if (!terminal) {+ cache.bufferingLiveFrames = true+ cache.bufferedLiveFrames = []+ actions.openSseForRun({ taskId, runId, startLatest: true })+ }++ let entries: unknown[]+ try {+ entries = await api.tasks.runs.getLogEntries(taskId, runId)+ } catch (error) {+ // The snapshot failed; for an in-progress run the SSE is already open, so tear it+ // down too — a thread of live-only frames with no history is more confusing than a+ // clean, retryable error.+ cache.bufferingLiveFrames = false+ cache.bufferedLiveFrames = undefined+ cache.disposables.dispose('reconnect-backoff')+ cache.disposables.dispose('event-source')+ actions.handleStreamError(mapHttpStatusToStreamError((error as { status?: number })?.status))+ return+ }+ breakpoint()++ // The full resume-chain S3 snapshot — replayed as `replay`, so the projection renders+ // persisted human turns and side-effect telemetry stays suppressed for history.+ const history = entries+ .map(normalizeNotificationEntry)+ .filter((entry): entry is StoredLogEntry => entry !== null)+ history.forEach((entry) => actions.ingestAcpFrame(entry, 'replay'))++ if (terminal) {+ // Read-only history — surface the terminal status, do not open SSE. Flag the replay+ // so the listener records the status without re-emitting termination telemetry.+ actions.handleTerminalStatus({ status: run.status as SandboxRunStatus, replayedFromHistory: true })+ return+ }++ // Drain the seam: drop buffered-live frames the snapshot already accounts for (content+ // multiset), then append the surviving tail as live. Stop buffering first so any frame+ // arriving during the drain appends directly rather than landing in a buffer we've moved past.+ const buffered = (cache.bufferedLiveFrames as StoredLogEntry[] | undefined) ?? []+ cache.bufferingLiveFrames = false+ cache.bufferedLiveFrames = undefined+ dedupeBufferedAgainstHistory(buffered, history).forEach((entry) => actions.ingestAcpFrame(entry, 'live'))+ },+ openSseForRun: ({ taskId, runId, startLatest }) => {+ // A read-only instance must never stream — guard here too, so even a stray or connected+ // dispatch can't open SSE into a read-only thread.+ if (props.replayOnly) {+ return+ }+ const projectId = values.currentProjectId+ if (projectId === null) {+ actions.handleStreamError({ errorTitle: 'No current project', retryable: false })+ return+ }++ // Track the active run so the reconnect loop can refetch it on a drop.+ cache.activeRun = { taskId, runId }++ actions.sseConnecting()+ cache.disposables.dispose('reconnect-backoff')++ // Route one parsed SSE event. `eventsource-parser` unifies the old `onmessage` (default+ // data channel — `event` undefined) and `addEventListener('error')` (named `error`+ // envelope) split into one callback keyed off the `event` field.+ const handleSseEvent = ({ id, event, data }: EventSourceMessage): void => {+ if (id) {+ // The Redis stream id. Stamped (even for a buffered frame) so a reconnect resumes+ // exactly after it via the Last-Event-ID header — an exclusive resume, so the+ // steady-state stream never re-delivers a frame we've already appended.+ cache.lastEventId = id+ }+ if (event === 'error') {+ // Named error envelope — surface verbatim. Real backend frames carry only `error`,+ // so the title/retryable fall back to the generic stream-failure defaults.+ try {+ const envelope: SseErrorFrameData = JSON.parse(data)+ actions.handleStreamError({+ errorTitle: envelope.errorTitle ?? 'Cloud stream failed',+ errorMessage: envelope.errorMessage,+ retryable: envelope.retryable ?? true,+ })+ } catch {+ actions.handleStreamError({ errorTitle: 'Cloud stream failed', retryable: true })+ }+ return+ }+ // keepalive (and any other named, non-data event) carries nothing to fold.+ if (event && event !== 'message') {+ return+ }+ let parsed: unknown+ try {+ parsed = JSON.parse(data)+ } catch {+ return+ }+ if (isNotificationFrame(parsed)) {+ // During the bootstrap window the SSE is connected before the S3 snapshot lands,+ // so buffer live notification frames instead of appending them; the drain+ // reconciles them against the snapshot once it loads (see `bootstrapRun`). Steady+ // state (and every send/reconnect open, which never buffers) appends directly.+ if (cache.bufferingLiveFrames) {+ ;(cache.bufferedLiveFrames as StoredLogEntry[]).push(parsed)+ } else {+ actions.ingestAcpFrame(parsed, 'live')+ }+ } else if (isPermissionRequestFrame(parsed)) {+ // requestId-keyed dedup: this top-level envelope isn't a notification, so a+ // reconnect's resume could re-deliver it verbatim.+ const record = parsePermissionRequestFrame(parsed)+ if (+ record &&+ !values.seenPermissionRequestIds.has(record.requestId) &&+ !values.resolvedPermissionRequestIds.has(record.requestId)+ ) {+ actions.routePermissionRequest(record)+ }+ } else if (isTaskRunStateFrame(parsed)) {+ // `stage` is dropped by handleTerminalStatus's status-only path; track it+ // separately for a future richer status surface. Generally unset for PHAI.+ if (parsed.stage !== undefined) {+ actions.setCurrentStage(parsed.stage ?? null)+ }+ // The frame carries the working `branch` and an `output.pr_url` once the run opens+ // a PR — fold them in so the post-turn PR card appears the moment it lands.+ actions.mergeRunArtifacts(extractRunArtifacts(parsed))+ actions.handleTerminalStatus({+ status: parsed.status as SandboxRunStatus,+ errorMessage: parsed.error_message ?? null,+ })+ }+ // unknown frame types are ignored.+ }++ // Open the stream as a fetch response and pump its body through the parser. A native+ // `EventSource` can't set request headers; a fetch can, so a reconnect resumes exactly+ // after `cache.lastEventId` via the Last-Event-ID header instead of re-broadcasting the+ // whole stream. A clean EOF or read error (not an abort) is a drop → run the recovery+ // loop; an aborted signal (teardown) is silent.+ const streamRun = async (signal: AbortSignal): Promise<void> => {+ let response: Response+ try {+ response = await api.tasks.runs.openStream(taskId, runId, {+ signal,+ lastEventId: cache.lastEventId as string | undefined,+ startLatest,+ })+ } catch (error) {+ if (signal.aborted) {+ return+ }+ // A fetch (unlike a native EventSource) exposes the HTTP status. Surface a+ // permanently-failed open (e.g. 404 — the backing run is gone) as a terminal+ // stream error instead of looping the reconnect logic forever; treat a transient+ // status or a network-level reject as a drop and let the recovery loop retry.+ const status = (error as { status?: number })?.status+ const mapped = status !== undefined ? mapHttpStatusToStreamError(status) : undefined+ if (mapped && !mapped.retryable) {+ actions.handleStreamError(mapped)+ } else {+ actions.sseDropped()+ }+ return+ }+ if (signal.aborted) {+ return+ }+ const reader = response.body?.getReader()+ if (!reader) {+ actions.sseDropped()+ return+ }+ // Headers received and a body to read → the connection is open.+ actions.sseOpened()+ const decoder = new TextDecoder()+ const parser = createParser({ onEvent: handleSseEvent })+ try {+ for (;;) {+ const { done, value } = await reader.read()+ if (value) {+ parser.feed(decoder.decode(value, { stream: true }))+ }+ if (done) {+ break+ }+ }+ } catch {+ if (!signal.aborted) {+ actions.sseDropped()+ }+ return+ }+ // Clean EOF: the server closed the stream. A terminal frame would already have torn+ // us down (dispose → abort); otherwise this is a drop, so refetch status and decide.+ if (!signal.aborted) {+ actions.sseDropped()+ }+ }++ // Replace any prior connection. A hot reload can orphan the previous build's reader (its+ // `cache`, and thus this disposable, is discarded before teardown runs), but the keyed+ // log store makes duplicate ingestion idempotent — a lingering orphan can no longer+ // double the thread, so the old `EventSource` registry is gone.+ cache.disposables.dispose('event-source')+ // pauseOnPageHidden: false — a live stream must survive tab hides; re-running setup on+ // show would reopen the stream and re-fold thread state.+ cache.disposables.add(+ (): (() => void) => {+ const controller = new AbortController()+ void streamRun(controller.signal)+ return () => controller.abort()+ },+ 'event-source',+ { pauseOnPageHidden: false }+ )+ },+ sseOpened: () => {+ // Stamp the connection time for the healthy-connection rule in sseDropped. The+ // provisioning flag (`isBootstrapping`, read by the disconnect telemetry) is NOT cleared+ // here: connect-first opens the SSE before the history snapshot loads, so the bootstrap+ // window (connect → snapshot → drain → first `run_started`) outlives the first connect.+ // It clears when the agent actually starts (`_posthog/run_started`) or on reset.+ cache.sseConnectedAtMs = Date.now()+ },+ sseDropped: async (_, breakpoint) => {+ const activeRun = cache.activeRun as { taskId: string; runId: string } | undefined+ if (!activeRun) {+ return+ }+ // Abort the in-flight reader so its clean-EOF/error handler can't also schedule a+ // reconnect while this loop owns recovery.+ cache.disposables.dispose('event-source')++ // First refetch the run to detect terminal state.+ const result = await fetchRunStatus(activeRun.taskId, activeRun.runId)+ breakpoint()+ // The stream was closed or replaced while the refetch was in flight — drop this loop.+ if (cache.activeRun !== activeRun) {+ return+ }+ if ('error' in result) {+ actions.handleStreamError(result.error)+ return+ }++ // A reconnect refetch can be the first place a freshly-opened PR (or branch) shows up —+ // fold it in even if the run has since terminated.+ actions.mergeRunArtifacts(result.artifacts)++ // Terminal → final terminal-status action + close.+ if (isTerminalRunStatus(result.status)) {+ actions.handleTerminalStatus({ status: result.status as SandboxRunStatus })+ return+ }++ // Cumulative cap — bounds runaway clean-EOF reopen loops that keep resetting the per-drop+ // counter. The about-to-be-scheduled reconnect is the (cumulative + 1)th.+ if (values.cumulativeReconnectAttempt + 1 > MAX_CUMULATIVE_RECONNECT_ATTEMPTS) {+ actions.handleStreamError({ errorTitle: 'Cloud stream failed', retryable: true })+ return+ }++ // Healthy-connection rule — a connection that stayed open ≥60s before dropping is not a+ // flaky transport, so its drop is forgiven: schedule a reconnect but don't grow the+ // per-drop budget. The cumulative counter still increments (via sseReconnecting) to+ // bound pathological reopen loops.+ const connectedAtMs = cache.sseConnectedAtMs as number | undefined+ const wasHealthy = connectedAtMs !== undefined && Date.now() - connectedAtMs >= SSE_HEALTHY_CONNECTION_MS++ // Non-terminal → capped exponential backoff; attempts exhausted surface a retryable error.+ const attempt = wasHealthy ? values.reconnectAttempt : values.reconnectAttempt + 1+ if (attempt > MAX_SSE_RECONNECT_ATTEMPTS) {+ actions.handleStreamError({ errorTitle: 'Cloud stream failed', retryable: true })+ return+ }+ // Backoff off the per-drop budget; a forgiven healthy drop (attempt 0) reconnects fast.+ const delayMs = reconnectDelayMs(Math.max(attempt, 1))+ actions.sseReconnecting(attempt)+ // pauseOnPageHidden: false — the SSE connection survives tab hides, so a drop in a+ // hidden tab must also reconnect there; a paused timer would stall until refocus.+ cache.disposables.add(+ (): (() => void) => {+ const timer = window.setTimeout(() => {+ // Resume from `cache.lastEventId` via the Last-Event-ID header (set inside+ // openSseForRun) — the backend replays exactly the frames after it, filling+ // the gap with no re-broadcast. `startLatest: true` only matters if no frame+ // was ever seen (dropped before the first one): then resume from the head+ // rather than re-streaming from `0`.+ actions.openSseForRun({ taskId: activeRun.taskId, runId: activeRun.runId, startLatest: true })+ }, delayMs)+ return () => clearTimeout(timer)+ },+ 'reconnect-backoff',+ { pauseOnPageHidden: false }+ )+ },+ routePermissionRequest: ({ record, replayedFromHistory }) => {+ // Replayed history is a read-only restore — never auto-approve (the run may be terminal).+ if (!replayedFromHistory && defaultPermissionDecision(record) === 'auto_allow') {+ const optionId = findAllowOptionId(record)+ if (optionId) {+ actions.autoApprovePermissionRequest(record, optionId)+ return+ }+ }+ actions.ingestPermissionRequest(record, replayedFromHistory)+ },+ autoApprovePermissionRequest: async ({ record, optionId }) => {+ // Pin it seen up front so a reconnect replay can't re-process the same request mid-POST.+ actions.markPermissionRequestSeen(record.requestId)+ const activeRun = cache.activeRun as { taskId: string; runId: string } | undefined+ const resolvedToolCall = resolveToolCall(record.rawToolCall)+ posthog.capture('permission_auto_approved', {+ conversation_id: props.conversationId,+ trace_id: values.traceId,+ request_id: record.requestId,+ tool_call_name: resolvedToolCall.resolvedKey,+ tool_call_id: record.toolCallId,+ run_id: activeRun?.runId,+ task_id: activeRun?.taskId,+ execution_type: 'sandbox',+ })+ if (!activeRun || values.currentProjectId == null) {+ // No active run to command yet — fall back to the manual card so the user can respond.+ actions.ingestPermissionRequest(record)+ return+ }+ try {+ await tasksRunsCommandCreate(String(values.currentProjectId), activeRun.taskId, activeRun.runId, {+ jsonrpc: '2.0',+ method: 'permission_response',+ params: { requestId: record.requestId, optionId },+ })+ actions.markPermissionRequestResolved(record.requestId)+ } catch (error) {+ // The auto-approve command failed — don't leave the agent silently blocked. Fall back to+ // the manual card so the user can respond.+ posthog.captureException(error)+ actions.ingestPermissionRequest(record)+ }+ },+ ingestPermissionRequest: ({ record, replayedFromHistory }) => {+ if (replayedFromHistory) {+ return+ }+ // conversation_id / trace_id are correlated by the caller (the SSE bypasses Django);+ // emit what this logic knows.+ const activeRun = cache.activeRun as { taskId: string; runId: string } | undefined+ const resolvedToolCall = resolveToolCall(record.rawToolCall)+ posthog.capture('permission_requested', {+ conversation_id: props.conversationId,+ trace_id: values.traceId,+ request_id: record.requestId,+ tool_call_name: resolvedToolCall.resolvedKey,+ tool_call_id: record.toolCallId,+ run_id: activeRun?.runId,+ task_id: activeRun?.taskId,+ execution_type: 'sandbox',+ })+ },+ respondToPermission: async ({ requestId, optionId, customInput, answers }) => {+ const activeRun = cache.activeRun as { taskId: string; runId: string } | undefined+ if (!activeRun || values.currentProjectId == null) {+ // No live run to command — keep the card so the user can retry once the stream resolves.+ actions.permissionResponseFailed()+ lemonToast.error('Failed to send approval. Please try again.')+ return+ }+ try {+ // PERMISSION_RESPONDED telemetry is emitted server-side by the tasks relay. The renderer+ // commands the run it is streaming (`cache.activeRun`); on a persistent sandbox the run+ // only advances when the old one dies and the successor takes over — which is exactly the+ // run the renderer has re-resolved, so the reply lands where it belongs.+ await tasksRunsCommandCreate(String(values.currentProjectId), activeRun.taskId, activeRun.runId, {+ jsonrpc: '2.0',+ method: 'permission_response',+ params: { requestId, optionId, customInput, answers },+ })+ actions.markPermissionRequestResolved(requestId)+ } catch (error) {+ // A failed reply POST does not mean the run died — the agent is still alive and+ // blocked on this same approval. Keep the failure local to the card (re-enable its+ // buttons for a retry) instead of tearing down the stream, which would release the+ // chat lock and hide the still-pending request behind the normal input.+ posthog.captureException(error)+ actions.permissionResponseFailed()+ lemonToast.error('Failed to send approval. Please try again.')+ }+ },+ cancelRun: async ({ run }) => {+ // Cancel a run through the generic tasks relay — the same command PostHog Code issues. The+ // SSE then receives a terminal task_run_state; cancellation telemetry is emitted server-side+ // by the relay. `run` defaults to the streamed run; a warm Run (not streamed) is passed in.+ // Fire-and-forget: a failure leaves the run alive for a retry.+ const target = run ?? (cache.activeRun as { taskId: string; runId: string } | undefined)+ if (!target || values.currentProjectId == null) {+ return+ }+ try {+ await tasksRunsCommandCreate(String(values.currentProjectId), target.taskId, target.runId, {+ jsonrpc: '2.0',+ method: 'cancel',+ })+ } catch (error) {+ posthog.captureException(error)+ }+ },+ handleTerminalStatus: ({ status, errorMessage, replayedFromHistory }) => {+ // The wire emits task_run_state for non-terminal transitions too (e.g. queued →+ // in_progress) — only an actually-terminal run has no more frames to stream.+ if (!isTerminalRunStatus(status)) {+ return+ }+ cache.disposables.dispose('reconnect-backoff')+ cache.disposables.dispose('event-source')++ // A run that already terminated in a prior session is surfaced read-only on reopen —+ // the reducers still record the terminal status, but re-emitting telemetry on every+ // page load would inflate termination counts.+ if (replayedFromHistory) {+ return+ }++ // Crash/failure affordance: a failed run carrying an error_message otherwise just blanks+ // the thinking indicator. Push a visible error item so the user sees why it stopped. The+ // in-sandbox agent server writes "Agent server crashed: …" on a fatal exception — render+ // that as a friendlier, retry-oriented `crash` variant; other failures show the raw line.+ if (status === 'failed' && errorMessage) {+ actions.pushErrorItem(errorMessage, errorMessage.startsWith(AGENT_CRASH_PREFIX) ? 'crash' : 'error')+ }++ // TASK_RUN_TERMINATED telemetry. `duration_ms` is measured from the current turn's start+ // (run start for the first turn, the latest human message for a follow-up); absent if the+ // run terminated before either was seen.+ const activeRun = cache.activeRun as { taskId: string; runId: string } | undefined+ const startedAt = cache.turnStartedAtMs as number | undefined+ posthog.capture('task_run_terminated', {+ conversation_id: props.conversationId,+ trace_id: values.traceId,+ run_id: activeRun?.runId,+ task_id: activeRun?.taskId,+ status,+ error_message: errorMessage ?? undefined,+ execution_type: 'sandbox',+ duration_ms: startedAt !== undefined ? Date.now() - startedAt : undefined,+ })+ },+ handleStreamError: ({ errorTitle, errorMessage, retryable }) => {+ // The composer-unlock is already wired off this action in maxThreadLogic; today it+ // unlocks silently. Push a visible, retryable error line so the user knows the stream+ // dropped — and capture the disconnect telemetry that mirrors the cloud client's+ // CLOUD_STREAM_DISCONNECTED (the relay can't see a client-side reconnect-budget exhaustion).+ actions.pushErrorItem(errorMessage ? `${errorTitle}: ${errorMessage}` : errorTitle)+ const activeRun = cache.activeRun as { taskId: string; runId: string } | undefined+ posthog.capture('sandbox_stream_disconnected', {+ conversation_id: props.conversationId,+ trace_id: values.traceId,+ run_id: activeRun?.runId,+ task_id: activeRun?.taskId,+ error_title: errorTitle,+ retryable,+ reconnect_attempts: values.reconnectAttempt,+ stream_error_attempts: 0,+ cumulative_reconnect_attempts: values.cumulativeReconnectAttempt,+ was_bootstrapping: cache.isBootstrapping === true,+ execution_type: 'sandbox',+ })+ },+ closeSse: () => {+ cache.activeRun = undefined+ cache.lastEventId = undefined+ cache.disposables.dispose('reconnect-backoff')+ // Aborts the in-flight fetch reader (its signal); the reader loop sees `aborted` and+ // exits without scheduling a reconnect.+ cache.disposables.dispose('event-source')+ },+ reset: () => {+ // `log` clears via its own reducer on `reset`, so the projection empties with it.+ cache.activeRun = undefined+ cache.turnStartedAtMs = undefined+ cache.isBootstrapping = false+ cache.bufferingLiveFrames = false+ cache.bufferedLiveFrames = undefined+ cache.sseConnectedAtMs = undefined+ // Drop the resume cursor so the next bootstrap opens fresh (start=latest) instead of+ // resuming a prior run's stream.+ cache.lastEventId = undefined+ cache.disposables.dispose('reconnect-backoff')+ cache.disposables.dispose('event-source')+ },+ pushHumanMessage: ({ content }) => {+ // The echo is always a live turn (replayed human turns render straight from the log), so+ // stamp the turn start for per-turn duration metrics and append it as a `client`-sourced+ // log entry the projection renders in order.+ cache.turnStartedAtMs = Date.now()+ actions.appendEntries([+ {+ entry: {+ type: 'notification',+ notification: { method: '_client/human_message', params: { content } },+ },+ source: 'client',+ },+ ])+ },+ pushErrorItem: ({ errorMessage, variant }) => {+ // Client-side errors (terminal failure, stream disconnect) aren't wire frames — append+ // them as `client`-sourced log entries so the projection renders them in thread order.+ actions.appendEntries([+ {+ entry: {+ type: 'notification',+ notification: { method: '_client/error', params: { message: errorMessage, variant } },+ },+ source: 'client',+ },+ ])+ },+ ingestAcpFrame: ({ entry, source }) => {+ const notification = entry?.notification+ if (!notification) {+ return+ }+ const method = notification.method+ const isReplay = source === 'replay'++ // Pre-update tool status for the once-per-transition `tool_call_completed` telemetry,+ // read from the projection BEFORE the append folds this update in. Live only — replay+ // suppresses the telemetry, so the lookup (and its O(N) re-fold) is skipped for history.+ let preToolStatus: ToolInvocationStatus | undefined+ if (!isReplay && method === 'session/update') {+ const u = notification.params?.update+ if (isRecord(u) && u.sessionUpdate === 'tool_call_update') {+ preToolStatus = values.toolInvocations.get(String(u.toolCallId ?? ''))?.status+ }+ }++ // Append to the ordered log — the single source of truth. The bootstrap seam was already+ // deduped (see `bootstrapRun`) and steady-state live frames resume exclusively, so the+ // side effects below run exactly once per frame without a per-frame key; the+ // run-started/permission/tool-completion guards enforce fire-once on their own.+ actions.appendEntries([{ entry, source }])++ // Custom `_posthog/*` notification namespace emitted by the agent-server. Thread items+ // (errors, status, compaction, task notifications, progress, human turns) are derived by+ // the projection straight from the log — handled here only for their value-fold side+ // effects (telemetry, usage/resources/mode folds, permission routing).+ if (method === '_posthog/run_started') {+ // TASK_RUN_STARTED telemetry — emit once per run on the first `_posthog/run_started`+ // frame. Suppressed while replaying history (the run started in a prior session);+ // `markRunStarted` still runs so started/thinking state stays correct.+ if (!values.runStarted && !isReplay) {+ const activeRun = cache.activeRun as { taskId: string; runId: string } | undefined+ cache.turnStartedAtMs = Date.now()+ posthog.capture('task_run_started', {+ conversation_id: props.conversationId,+ trace_id: values.traceId,+ run_id: activeRun?.runId,+ task_id: activeRun?.taskId,+ execution_type: 'sandbox',+ // The run-started frame carries no warmth signal and pre-warming isn't wired+ // yet, so every run is a cold start. A later pre-warm hook flips this.+ cold_start: true,+ })+ }+ cache.isBootstrapping = false+ actions.markRunStarted()+ return+ }+ if (method === '_posthog/turn_complete') {+ actions.markTurnComplete()+ return+ }+ if (method === '_posthog/progress') {+ const progress = (notification.params ?? {}) as PosthogProgressParams+ actions.setCurrentProgress(+ stringifyOptional(progress.label) ?? stringifyOptional(progress.detail) ?? ''+ )+ return+ }+ // The agent-server persists the permission lifecycle to the run log — pending approvals+ // are re-derived on bootstrap (a reload mid-approval would otherwise lose the card while+ // the agent stays blocked), and a resolution observed here clears the local card.+ if (isPosthogNotification(notification, '_posthog/permission_request')) {+ const record = parsePermissionRequestFrame(notification.params ?? {})+ if (+ record &&+ !values.seenPermissionRequestIds.has(record.requestId) &&+ !values.resolvedPermissionRequestIds.has(record.requestId)+ ) {+ actions.routePermissionRequest(record, isReplay)+ }+ return+ }+ if (isPosthogNotification(notification, '_posthog/permission_resolved')) {+ const requestId = notification.params?.requestId+ if (typeof requestId === 'string' && requestId) {+ actions.markPermissionRequestResolved(requestId)+ }+ return+ }+ // The agent reports, per turn, which PostHog products an answer was grounded in.+ if (isPosthogNotification(notification, '_posthog/resources_used')) {+ actions.mergeResourcesUsed(notification.params?.products ?? [])+ return+ }+ // Token usage + cost + context-window breakdown. The numeric used/size aggregate that+ // drives the percentage ring arrives separately on a session/update (handled below).+ if (isPosthogNotification(notification, '_posthog/usage_update')) {+ actions.setContextUsage(foldUsageNotification(values.contextUsage, notification.params ?? {}))+ return+ }+ // Diagnostic only — no UI; kept for resume telemetry / crash-affordance work.+ if (isPosthogNotification(notification, '_posthog/sdk_session')) {+ const params = notification.params+ actions.setSdkSession({ sessionId: params?.sessionId, adapter: params?.adapter })+ return+ }+ if (method?.startsWith('_posthog/')) {+ // _posthog/error, _posthog/status, _posthog/compact_boundary, _posthog/task_notification,+ // _posthog/user_message → rendered by the projection. _posthog/console, _posthog/+ // sandbox_output, _posthog/git_checkpoint, … → no UI. No side effect either way.+ return+ }+ // session/prompt never renders and the resume-context filter is handled in the projection.+ if (method === 'session/prompt') {+ return+ }+ if (!isSessionUpdateNotification(notification)) {+ return+ }+ const update = notification.params?.update+ // The numeric used/size usage aggregate is session/update-framed — fold it into the ring.+ if (isSessionUpdateUsage(update)) {+ actions.setContextUsage(foldUsageAggregate(values.contextUsage, update))+ return+ }+ // Wire user turns render only on replay (the projection branches on source) — no side effect.+ if (isSessionUpdateUserMessage(update)) {+ return+ }+ if (!isKnownSessionUpdate(update)) {+ return+ }+ if (update.sessionUpdate === 'current_mode_update') {+ actions.setCurrentMode(String(update.currentModeId ?? update.mode ?? ''))+ return+ }+ if (update.sessionUpdate === 'tool_call_update') {+ // TOOL_CALL_COMPLETED telemetry — emit once when a tool call first transitions to a+ // terminal status. `preToolStatus` (read before the upsert) gates the once-only fire;+ // the resolved key comes from the merged invocation in the projection. Suppressed on+ // replay, and skipped when the creating `tool_call` was lost (no pre-status).+ const toolCallId = String(update.toolCallId ?? '')+ if (!toolCallId) {+ return+ }+ const status = mapAcpStatus(update.status ?? preToolStatus)+ if (+ !isReplay &&+ preToolStatus !== undefined &&+ preToolStatus !== 'completed' &&+ preToolStatus !== 'failed' &&+ (status === 'completed' || status === 'failed')+ ) {+ const invocation = values.toolInvocations.get(toolCallId)+ const startedAt = cache.turnStartedAtMs as number | undefined+ posthog.capture('tool_call_completed', {+ conversation_id: props.conversationId,+ trace_id: values.traceId,+ tool_call_id: toolCallId,+ tool_qualified_name: invocation ? resolveToolCall(invocation).resolvedKey : undefined,+ status,+ duration_ms: startedAt !== undefined ? Date.now() - startedAt : undefined,+ execution_type: 'sandbox',+ })+ }+ return+ }+ // agent_message_chunk / agent_message / agent_thought_chunk / tool_call → projection only.+ },+ })),+])diff --git a/frontend/src/scenes/max/sandboxToolPolicy.test.ts b/frontend/src/scenes/max/sandboxToolPolicy.test.tsnew file mode 100644index 000000000000..a5c3d0fca841--- /dev/null+++ b/frontend/src/scenes/max/sandboxToolPolicy.test.ts@@ -0,0 +1,165 @@+import type { SandboxQuestion } from './sandboxQuestionUtils'+import {+ defaultPermissionDecision,+ findAllowOptionId,+ isPostHogDestructiveSubTool,+ isPostHogExecTool,+ type PermissionDecision,+} from './sandboxToolPolicy'+import type { PermissionRequestRecord, ToolInvocation } from './types/sandboxStreamTypes'+import type { PermissionOption } from './types/sandboxWireTypes'++function makeRecord(+ overrides: {+ toolName?: string+ rawServerName?: string+ rawToolName?: string+ input?: Record<string, unknown>+ meta?: unknown+ options?: PermissionOption[]+ questions?: SandboxQuestion[]+ } = {}+): PermissionRequestRecord {+ const rawToolCall: ToolInvocation = {+ toolCallId: 'tc',+ rawServerName: overrides.rawServerName ?? 'posthog',+ rawToolName: overrides.rawToolName ?? 'exec',+ input: overrides.input ?? {},+ status: 'pending',+ contentBlocks: [],+ meta: overrides.meta,+ }+ return {+ requestId: 'r',+ toolCallId: 'tc',+ toolName: overrides.toolName ?? 'mcp__posthog__exec',+ options: overrides.options ?? [{ optionId: 'allow', name: 'Yes', kind: 'allow_once' }],+ rawToolCall,+ ...(overrides.questions ? { questions: overrides.questions } : {}),+ }+}++describe('sandboxToolPolicy', () => {+ describe('isPostHogExecTool', () => {+ it.each([+ ['mcp__posthog__exec', true],+ ['mcp__posthog_us__exec', true],+ ['mcp__posthog__query', false],+ ['Bash', false],+ ])('%s → %s', (name, expected) => {+ expect(isPostHogExecTool(name)).toEqual(expected)+ })+ })++ describe('isPostHogDestructiveSubTool', () => {+ // Cases ported from Twig posthog-exec-gate.test.ts.+ it.each([+ 'experiment-update',+ 'feature-flag-delete',+ 'notebooks-destroy',+ 'experiment-partial-update',+ 'update-something',+ 'delete',+ ])('%s is destructive', (sub) => expect(isPostHogDestructiveSubTool(sub)).toBe(true))+ it.each(['experiment-get', 'feature-flag-list', 'experiment-create', 'insights-pause', 'get-updated-events'])(+ '%s is not destructive',+ (sub) => expect(isPostHogDestructiveSubTool(sub)).toBe(false)+ )+ })++ describe('defaultPermissionDecision', () => {+ it.each<[string, PermissionRequestRecord, PermissionDecision]>([+ [+ 'built-in tool',+ makeRecord({+ toolName: 'Bash',+ rawServerName: 'claude',+ rawToolName: '',+ meta: { claudeCode: { toolName: 'Bash' } },+ }),+ 'auto_allow',+ ],+ ['exec discovery verb', makeRecord({ input: { command: 'tools' } }), 'auto_allow'],+ ['exec create', makeRecord({ input: { command: 'call insight-create {"name":"Signups"}' } }), 'auto_allow'],+ ['exec update', makeRecord({ input: { command: 'call insight-update {"id":"abc"}' } }), 'prompt'],+ ['exec delete', makeRecord({ input: { command: 'call feature-flag-delete {"key":"new-nav"}' } }), 'prompt'],+ // A destructive sub-tool hidden behind --confirm/--json (in any order) must still prompt —+ // the inner tool name is resolved after the flags, not as the flag token.+ [+ 'exec delete behind --confirm',+ makeRecord({ input: { command: 'call --confirm feature-flag-delete {"key":"x"}' } }),+ 'prompt',+ ],+ [+ 'exec delete behind --confirm --json',+ makeRecord({ input: { command: 'call --confirm --json feature-flag-delete {"key":"x"}' } }),+ 'prompt',+ ],+ [+ 'exec delete behind --json --confirm',+ makeRecord({ input: { command: 'call --json --confirm feature-flag-delete {"key":"x"}' } }),+ 'prompt',+ ],+ // An exec call we can't resolve to a concrete sub-tool fails closed.+ ['exec call with no sub-tool', makeRecord({ input: { command: 'call --json' } }), 'prompt'],+ // A permission frame carrying no canonical tool name isn't a positively-identified built-in.+ [+ 'unidentified frame',+ makeRecord({ toolName: '', rawServerName: 'claude', rawToolName: '', input: {} }),+ 'prompt',+ ],+ [+ 'other mcp tool',+ makeRecord({ toolName: 'mcp__other__foo', rawServerName: 'other', rawToolName: 'foo' }),+ 'prompt',+ ],+ // AskUserQuestion rides the permission framework with allow_once options, but must never+ // auto-approve — picking option_0 with no answers gets rejected by the agent.+ [+ 'question request',+ makeRecord({+ toolName: 'AskUserQuestion',+ rawServerName: 'claude',+ rawToolName: '',+ meta: { claudeCode: { toolName: 'AskUserQuestion' } },+ questions: [{ question: 'Pick one', multiSelect: false, options: [{ label: 'A' }] }],+ }),+ 'prompt',+ ],+ ])('%s → %s', (_case, record, expected) => {+ expect(defaultPermissionDecision(record)).toEqual(expected)+ })+ })++ describe('findAllowOptionId', () => {+ it('prefers allow_once over allow_always', () => {+ const id = findAllowOptionId(+ makeRecord({+ options: [+ { optionId: 'aa', name: '', kind: 'allow_always' },+ { optionId: 'a1', name: '', kind: 'allow_once' },+ ],+ })+ )+ expect(id).toEqual('a1')+ })++ it('falls back to allow_always when there is no allow_once', () => {+ const id = findAllowOptionId(+ makeRecord({+ options: [+ { optionId: 'aa', name: '', kind: 'allow_always' },+ { optionId: 'r', name: '', kind: 'reject_once' },+ ],+ })+ )+ expect(id).toEqual('aa')+ })++ it('returns null when no allow option exists', () => {+ expect(+ findAllowOptionId(makeRecord({ options: [{ optionId: 'r', name: '', kind: 'reject_once' }] }))+ ).toBeNull()+ })+ })+})diff --git a/frontend/src/scenes/max/sandboxToolPolicy.ts b/frontend/src/scenes/max/sandboxToolPolicy.tsnew file mode 100644index 000000000000..45c2ab079c3a--- /dev/null+++ b/frontend/src/scenes/max/sandboxToolPolicy.ts@@ -0,0 +1,86 @@+import { isPostHogExecTool } from './sandbox/posthogExecDisplay'+import { resolveToolCall } from './sandbox/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 './sandbox/posthogExecDisplay'++/**+ * Default sandbox tool-permission policy, ported from Twig+ * (`packages/agent/src/adapters/claude/permissions/posthog-exec-gate.ts`).+ *+ * The deployed agent-server runs in `default` mode and asks for approval on every PostHog `exec`+ * call. We mirror Twig's policy on the client instead: auto-approve every built-in (default) tool+ * and every PostHog `exec` operation EXCEPT the destructive ones (update/delete/destroy/+ * partial-update), which still surface the approval card. Non-PostHog MCP tools fall outside the+ * default-allow contract and also prompt.+ */++/** A sub-tool is destructive when one of these verbs appears as a whole `-`-bounded segment. */+const POSTHOG_DESTRUCTIVE_SUBTOOL_RE = /(^|-)(partial-update|update|delete|destroy)(-|$)/i++export function isPostHogDestructiveSubTool(subTool: string): boolean {+ return POSTHOG_DESTRUCTIVE_SUBTOOL_RE.test(subTool)+}++export type PermissionDecision = 'auto_allow' | 'prompt'++/** Read-only exec discovery verbs — safe to auto-approve since they never mutate PostHog data. */+const POSTHOG_EXEC_READ_ONLY_KEYS = new Set([+ '__posthog_exec_tools__',+ '__posthog_exec_search__',+ '__posthog_exec_info__',+ '__posthog_exec_schema__',+])++/**+ * Decide whether a permission request can be auto-approved or must prompt the user. The policy fails+ * closed: a request only auto-approves when it is positively identified as safe.+ *+ * PostHog `exec` is detected by canonical tool name and by the parsed verb/sub-tool (robust to a+ * missing `_meta.claudeCode.toolName`): read-only discovery verbs (`tools`/`search`/`info`/`schema`)+ * and non-mutating `call <sub-tool>`s auto-approve; mutating sub-tools prompt, and an exec call whose+ * sub-tool can't be resolved (malformed, unknown verb, unrecognized flags) prompts rather than+ * silently allowing. A positively-identified built-in (non-MCP tool with a canonical name)+ * auto-approves; other MCP servers and any frame we can't identify prompt.+ */+export function defaultPermissionDecision(record: PermissionRequestRecord): PermissionDecision {+ // An `AskUserQuestion` rides the permission framework but is not an approval — auto-approving it+ // would pick the first option with no `answers`, which the agent rejects. Always prompt the user.+ if (record.questions?.length) {+ return 'prompt'+ }++ const { toolName } = record+ const { resolvedKey, innerToolName } = resolveToolCall(record.rawToolCall)++ const isExec = isPostHogExecTool(toolName) || innerToolName != null || resolvedKey.startsWith('__posthog_exec_')+ if (isExec) {+ if (POSTHOG_EXEC_READ_ONLY_KEYS.has(resolvedKey)) {+ return 'auto_allow'+ }+ // A resolved `call <sub-tool>`: auto-approve only non-mutating sub-tools.+ if (innerToolName) {+ return isPostHogDestructiveSubTool(innerToolName) ? 'prompt' : 'auto_allow'+ }+ // Exec call we couldn't resolve to a concrete sub-tool — fail closed.+ return 'prompt'+ }++ if (toolName.startsWith('mcp__')) {+ return 'prompt'+ }++ // A canonical name identifies a built-in (Bash, Edit, …); an empty name can't be identified.+ return toolName ? 'auto_allow' : 'prompt'+}++/** The optionId to auto-send when allowing — prefers the one-shot allow over `allow_always`. */+export function findAllowOptionId(record: PermissionRequestRecord): string | null {+ const allowOnce = record.options.find((o) => o.kind === 'allow_once')+ if (allowOnce) {+ return allowOnce.optionId+ }+ const anyAllow = record.options.find((o) => o.kind.startsWith('allow'))+ return anyAllow ? anyAllow.optionId : null+}diff --git a/frontend/src/scenes/max/slash-commands.tsx b/frontend/src/scenes/max/slash-commands.tsxindex 07daf3724615..f9f203618c03 100644--- a/frontend/src/scenes/max/slash-commands.tsx+++ b/frontend/src/scenes/max/slash-commands.tsx@@ -16,6 +16,12 @@ export interface SlashCommand {requiresIdle?: boolean/** If true, this command is only available for users on paid plans or with an active trial */requiresPaidPlan?: boolean+ /**+ * If true, this command is hidden for sandbox-runtime conversations.+ * Core-memory commands (`/init`, `/remember`) are not yet supported under sandbox AI.+ * LangGraph conversations are unaffected.+ */+ hiddenInSandbox?: boolean}export const MAX_SLASH_COMMANDS: SlashCommand[] = [@@ -23,12 +29,14 @@ export const MAX_SLASH_COMMANDS: SlashCommand[] = [name: SlashCommandName.SlashInit,description: 'Set up knowledge about your product & business',icon: <IconRocket />,+ hiddenInSandbox: true,},{name: SlashCommandName.SlashRemember,arg: '[information]',description: "Add [information] to PostHog AI's project-level memory",icon: <IconMemory />,+ hiddenInSandbox: true,},{name: SlashCommandName.SlashUsage,diff --git a/frontend/src/scenes/max/toolDiffContent.test.ts b/frontend/src/scenes/max/toolDiffContent.test.tsnew file mode 100644index 000000000000..df7885fdb3fe--- /dev/null+++ b/frontend/src/scenes/max/toolDiffContent.test.ts@@ -0,0 +1,64 @@+import { Language } from 'lib/components/CodeSnippet/CodeSnippet'++import { findAllDiffContent, getDiffStats, languageFromPath } from './toolDiffContent'++const flatDiff = { type: 'diff', path: 'a.ts', oldText: 'old', newText: 'new' }+const nestedDiff = { type: 'content', content: { type: 'diff', path: 'b.py', oldText: null, newText: 'print(1)' } }+const textBlock = { type: 'text', text: 'hello' }++describe('toolDiffContent', () => {+ describe('findAllDiffContent', () => {+ it('collects every diff block (flat + nested), in order — MultiEdit emits one per edit', () => {+ const second = { type: 'diff', path: 'a.ts', oldText: 'b', newText: 'c' }+ expect(findAllDiffContent([flatDiff, textBlock, nestedDiff, second])).toEqual([+ { type: 'diff', path: 'a.ts', oldText: 'old', newText: 'new' },+ { type: 'diff', path: 'b.py', oldText: null, newText: 'print(1)' },+ { type: 'diff', path: 'a.ts', oldText: 'b', newText: 'c' },+ ])+ })++ it.each([+ ['non-diff blocks', [textBlock, { type: 'content', content: textBlock }]],+ ['empty content', []],+ ['non-object members', [null, undefined, 'string', 42]],+ ])('returns an empty array for %s', (_label, content) => {+ expect(findAllDiffContent(content as unknown[])).toEqual([])+ })+ })++ describe('getDiffStats', () => {+ it.each([+ ['pure addition', 'a\nb', 'a\nb\nc', { added: 1, removed: 0 }],+ ['pure removal', 'a\nb\nc', 'a\nb', { added: 0, removed: 1 }],+ ['changed line', 'a\nb\nc', 'a\nB\nc', { added: 1, removed: 1 }],+ ['new file (null old)', null, 'a\nb\nc', { added: 3, removed: 0 }],+ ['new file (empty old)', '', 'a\nb', { added: 2, removed: 0 }],+ ['no change', 'a\nb', 'a\nb', { added: 0, removed: 0 }],+ ])('counts %s', (_label, oldText, newText, expected) => {+ expect(getDiffStats(oldText, newText)).toEqual(expected)+ })+ })++ describe('languageFromPath', () => {+ it.each([+ ['foo.ts', Language.TypeScript],+ ['foo.tsx', Language.TypeScript],+ ['foo.py', Language.Python],+ ['foo.js', Language.JavaScript],+ ['foo.jsx', Language.JavaScript],+ ['foo.json', Language.JSON],+ ['foo.sql', Language.SQL],+ ['foo.go', Language.Go],+ ['foo.yaml', Language.YAML],+ ['foo.yml', Language.YAML],+ ['foo.sh', Language.Bash],+ ['foo.rb', Language.Ruby],+ ['nested/dir/Component.TSX', Language.TypeScript],+ ['Dockerfile', Language.Text],+ ['foo.unknownext', Language.Text],+ [undefined, Language.Text],+ ])('maps %s to the expected language', (path, expected) => {+ expect(languageFromPath(path)).toBe(expected)+ })+ })+})diff --git a/frontend/src/scenes/max/toolDiffContent.ts b/frontend/src/scenes/max/toolDiffContent.tsnew file mode 100644index 000000000000..4f4911dfae0f--- /dev/null+++ b/frontend/src/scenes/max/toolDiffContent.ts@@ -0,0 +1,135 @@+import { Language } from 'lib/components/CodeSnippet/CodeSnippet'++/**+ * A normalized `type: "diff"` tool-call content block, as emitted by the sandbox agent's Claude+ * adapter for Edit/Write/MultiEdit/NotebookEdit calls. `oldText` is `null` for a brand-new file.+ */+export interface ToolCallDiffContent {+ type: 'diff'+ path?: string+ oldText?: string | null+ newText?: string+}++/**+ * Unwraps the ACP `{ type: 'content', content: {...} }` envelope — diff blocks may arrive flat or+ * nested under that wrapper.+ */+function unwrapBlock(block: unknown): unknown {+ if (!block || typeof block !== 'object') {+ return block+ }+ if ((block as { type?: unknown }).type === 'content' && 'content' in block) {+ return (block as { content: unknown }).content+ }+ return block+}++function asDiffContent(block: unknown): ToolCallDiffContent | null {+ const inner = unwrapBlock(block)+ if (!inner || typeof inner !== 'object' || (inner as { type?: unknown }).type !== 'diff') {+ return null+ }+ const { path, oldText, newText } = inner as { path?: unknown; oldText?: unknown; newText?: unknown }+ return {+ type: 'diff',+ path: typeof path === 'string' ? path : undefined,+ oldText: oldText === null ? null : typeof oldText === 'string' ? oldText : undefined,+ newText: typeof newText === 'string' ? newText : undefined,+ }+}++/** Every `type: "diff"` block — MultiEdit emits one per edit; the single-edit case is `[0]`. */+export function findAllDiffContent(content: unknown[]): ToolCallDiffContent[] {+ const diffs: ToolCallDiffContent[] = []+ for (const block of content) {+ const diff = asDiffContent(block)+ if (diff) {+ diffs.push(diff)+ }+ }+ return diffs+}++/**+ * Line-level +added/-removed counts via a line-frequency diff. Ported from the ../code EditToolView:+ * a missing/empty `oldText` means a new file, so every line is an addition.+ */+export function getDiffStats(+ oldText: string | null | undefined,+ newText: string | null | undefined+): { added: number; removed: number } {+ const oldLines = oldText ? oldText.split('\n') : []+ const newLines = newText ? newText.split('\n') : []++ if (!oldText) {+ return { added: newLines.length, removed: 0 }+ }++ const oldCounts = new Map<string, number>()+ for (const line of oldLines) {+ oldCounts.set(line, (oldCounts.get(line) ?? 0) + 1)+ }++ const newCounts = new Map<string, number>()+ for (const line of newLines) {+ newCounts.set(line, (newCounts.get(line) ?? 0) + 1)+ }++ let added = 0+ let removed = 0++ for (const [line, count] of newCounts) {+ const oldCount = oldCounts.get(line) ?? 0+ if (count > oldCount) {+ added += count - oldCount+ }+ }++ for (const [line, count] of oldCounts) {+ const newCount = newCounts.get(line) ?? 0+ if (count > newCount) {+ removed += count - newCount+ }+ }++ return { added, removed }+}++// The Language enum string values double as valid Monaco language ids, which is what+// MonacoDiffEditor.language wants.+const EXTENSION_LANGUAGE_MAP: Record<string, Language> = {+ ts: Language.TypeScript,+ tsx: Language.TypeScript,+ mts: Language.TypeScript,+ cts: Language.TypeScript,+ js: Language.JavaScript,+ jsx: Language.JavaScript,+ mjs: Language.JavaScript,+ cjs: Language.JavaScript,+ py: Language.Python,+ json: Language.JSON,+ sql: Language.SQL,+ go: Language.Go,+ yaml: Language.YAML,+ yml: Language.YAML,+ sh: Language.Bash,+ bash: Language.Bash,+ rb: Language.Ruby,+ java: Language.Java,+ kt: Language.Kotlin,+ php: Language.PHP,+ cs: Language.CSharp,+ swift: Language.Swift,+ html: Language.HTML,+ xml: Language.XML,+}++/** Maps a file path's extension to a Monaco language id, defaulting to plain text. */+export function languageFromPath(path?: string): Language {+ const ext = path?.split('.').pop()?.toLowerCase()+ if (!ext) {+ return Language.Text+ }+ return EXTENSION_LANGUAGE_MAP[ext] ?? Language.Text+}diff --git a/frontend/src/scenes/max/types/sandboxStreamTypes.ts b/frontend/src/scenes/max/types/sandboxStreamTypes.tsnew file mode 100644index 000000000000..6c7352f72860--- /dev/null+++ b/frontend/src/scenes/max/types/sandboxStreamTypes.ts@@ -0,0 +1,186 @@+/**+ * Thread shapes for the sandbox agent runtime (`agent_runtime === 'sandbox'`).+ *+ * The sandbox path consumes the products/tasks SSE endpoint directly (the same endpoint+ * PostHog Code uses). `sandboxStreamLogic` folds the raw wire frames (typed in+ * `./sandboxWireTypes`) into `ToolInvocation` / `ThreadItem` stream state.+ */++import type { SandboxQuestion } from '../sandboxQuestionUtils'+import type { PermissionOption } from './sandboxWireTypes'++export type ToolInvocationStatus = 'pending' | 'in_progress' | 'completed' | 'failed'+export type SandboxProgressStatus = 'pending' | 'in_progress' | 'completed' | 'failed'++export interface SandboxProgressStep {+ key: string+ label: string+ status: SandboxProgressStatus+ detail?: string+}++/**+ * One merged tool call: a `tool_call` creation plus N × `tool_call_update`s folded into a+ * single raw stream record keyed on `toolCallId`. Renderer-specific parsing, such as resolving+ * the inner tool name for PostHog's single-exec MCP server, happens outside this stream state.+ */+export interface ToolInvocation {+ toolCallId: string+ /** ACP-reported MCP server, e.g. 'posthog' or '<user-installed>'. */+ rawServerName: string+ /** ACP-reported tool, e.g. 'exec', 'TodoWrite', '<user-tool>'. */+ rawToolName: string+ /** rawInput at `tool_call` time (for `exec`, includes the wrapper `{ command }`). */+ input: Record<string, unknown>+ /** rawOutput on the final `tool_call_update`. */+ output?: unknown+ /** Error carried by a failed `tool_call_update` (from the update or its notification envelope). */+ error?: { message?: string } | null+ /** Partial result from intermediate updates. */+ progress?: unknown+ status: ToolInvocationStatus+ title?: string+ /** ACP `toolCall.kind`. */+ kind?: string+ locations?: { path: string; line?: number }[]+ /** Accumulated ACP `content[]` from updates. */+ contentBlocks: unknown[]+ /** Raw ACP `_meta` from the latest tool frame. */+ meta?: unknown+}++export type ThreadItemType =+ | 'human_message'+ | 'assistant_message'+ | 'assistant_thought'+ | 'tool_invocation'+ | 'turn_separator'+ | 'error'+ | 'status'+ | 'compact_boundary'+ | 'task_notification'+ | 'progress'++/**+ * An ordered, append-only entry the renderer consumes. Human messages, text chunks, streamed+ * reasoning ("thoughts"), tool-invocation references, run-lifecycle markers, inline errors, and+ * inline `_posthog/*` notifications (status / compaction / task milestones) all flow through this+ * list.+ */+export interface ThreadItem {+ /** Stable id — message buffer id, tool call id, or a generated separator/error id. */+ id: string+ type: ThreadItemType+ /** For `human_message`, `assistant_message`, and `assistant_thought` items. */+ text?: string+ /** Whether the assistant message buffer is finalized. */+ complete?: boolean+ /** For `tool_invocation` items — the keyed tool call id (look up in `toolInvocations`). */+ toolCallId?: string+ /** For `error` items. */+ errorMessage?: string+ /**+ * For `error` items — distinguishes a friendlier agent-crash affordance (`crash`) from a+ * raw error line (`error`, the default). Drives the copy/styling branch in the renderer.+ */+ variant?: 'error' | 'crash'+ /** For `status` and `task_notification` items — the wire `status` string. */+ status?: string+ /** For `status` items — whether the status phase has completed. */+ isComplete?: boolean+ /** For `compact_boundary` items — what triggered the compaction (e.g. 'auto'). */+ trigger?: string+ /** For `compact_boundary` items — token count before compaction. */+ preTokens?: number+ /** For `compact_boundary` items — post-compaction context size. */+ contextSize?: number+ /** For `task_notification` items — the milestone summary. */+ summary?: string+ /** For `progress` items — backend-supplied group id, scoped to the task run. */+ progressGroup?: string+ /** For `progress` items — ordered setup/runtime progress rows. */+ progressSteps?: SandboxProgressStep[]+}++/** One PostHog product the agent grounded an answer in, accumulated across the whole session. */+export interface ResourceProduct {+ /** Wire product id, e.g. 'product_analytics'. The local taxonomy maps it to an icon + label. */+ id: string+ /** Wire-supplied label; falls back to the local taxonomy label when absent. */+ label?: string+}++/**+ * Latest-wins context-usage snapshot for the footer ring. `used`/`size` (numeric token counts)+ * drive the percentage and arrive on the `session/update` aggregate; `tokens`/`cost`/`breakdown`+ * arrive on the `_posthog/usage_update` ext-notification.+ */+export interface ContextUsage {+ /** Numeric used-token count from the session/update aggregate (drives the ring). */+ used?: number+ /** Numeric context-window size from the session/update aggregate (drives the ring). */+ size?: number+ /** Cumulative token breakdown from the ext-notification. */+ tokens?: {+ inputTokens?: number+ outputTokens?: number+ cachedReadTokens?: number+ cachedWriteTokens?: number+ }+ /** Cost in USD (normalized to a number from either wire cost shape). */+ cost?: number+ /** Context-window composition breakdown from the ext-notification. */+ breakdown?: {+ systemPrompt?: number+ tools?: number+ rules?: number+ skills?: number+ mcp?: number+ subagents?: number+ conversation?: number+ }+}++/** Diagnostic resume plumbing — `taskRunId → sessionId / adapter`. No UI; kept for telemetry. */+export interface SdkSession {+ sessionId?: string+ adapter?: string+}++/**+ * Git artifacts a coding run exposes — surfaced pre-turn (working/base branch) and post-turn+ * (the opened PR). Accumulated latest-wins from the bootstrap run fetch (`state.pr_base_branch`,+ * top-level `branch`, `output.pr_url`) and live `task_run_state` frames. Stays empty for a pure+ * analytics conversation, so the coding UI it feeds self-hides.+ */+export interface RunArtifacts {+ /** `output.pr_url` — the opened pull request, when the run created one. */+ prUrl?: string+ /** The run's working branch (top-level `branch`). */+ branch?: string+ /** `state.pr_base_branch` — the branch the PR targets. */+ baseBranch?: string+ /** `owner/name` when present; generally unset on the run wire shape. */+ repo?: string+}++/**+ * A pending ACP `permission_request` surfaced by the products/tasks stream, rendered by+ * `SandboxPermissionInput` in the input area.+ */+export interface PermissionRequestRecord {+ requestId: string+ toolCallId: string+ /** Canonical ACP tool name (`mcp__posthog__exec`, or a built-in like `Bash`) — drives the default permission policy. */+ toolName: string+ options: PermissionOption[]+ title?: string+ description?: string+ rawToolCall: ToolInvocation+ /**+ * Present when this request is an `AskUserQuestion` — Twig routes questions through the permission+ * framework (`toolCall._meta.codeToolKind === 'question'`, `_meta.questions`). Drives the+ * interactive question overlay instead of the approve/decline card, and blocks auto-approval.+ */+ questions?: SandboxQuestion[]+}diff --git a/frontend/src/scenes/max/types/sandboxWireTypes.test.ts b/frontend/src/scenes/max/types/sandboxWireTypes.test.tsnew file mode 100644index 000000000000..f1a2d866858e--- /dev/null+++ b/frontend/src/scenes/max/types/sandboxWireTypes.test.ts@@ -0,0 +1,369 @@+import {+ type AcpNotification,+ type PosthogNotificationParamsByMethod,+ type StoredLogEntry,+ isKeepaliveFrame,+ isKnownSessionUpdate,+ isNotificationFrame,+ isPermissionRequestFrame,+ isPosthogNotification,+ isSessionUpdateNotification,+ isSessionUpdateUsage,+ isTaskRunStateFrame,+ hasUsageBreakdown,+ hasUsageUsed,+} from './sandboxWireTypes'++const TIMESTAMP = '2026-06-11T09:00:00.000000+00:00'+const RUN_ID = '3d2f3e7a-5c1b-4f7e-9d51-0a9b8c7d6e5f'+const TASK_ID = '9b8a7c6d-5e4f-3a2b-1c0d-e9f8a7b6c5d4'++function notification(method: string, params?: Record<string, unknown>): StoredLogEntry {+ return {+ type: 'notification',+ timestamp: TIMESTAMP,+ notification: { jsonrpc: '2.0', method, ...(params !== undefined ? { params } : {}) },+ }+}++function sessionUpdate(update: Record<string, unknown>): StoredLogEntry {+ return notification('session/update', { sessionId: 'sess_a1b2c3', update })+}++// Canonical `_posthog/*` payloads as the emitters produce them (products/tasks for the core+// methods, the agent adapters for the rest).+const NOTIFICATION_PARAMS_BY_METHOD: { [M in keyof PosthogNotificationParamsByMethod]: Record<string, unknown>[] } = {+ '_posthog/console': [{ sessionId: RUN_ID, level: 'info', message: 'Provisioning sandbox' }],+ '_posthog/progress': [+ {+ sessionId: RUN_ID,+ step: 'clone_repository',+ status: 'in_progress',+ label: 'Cloning repository',+ group: 'setup',+ detail: 'PostHog/posthog @ master',+ },+ { sessionId: RUN_ID, step: 'start_agent', status: 'completed', label: 'Starting agent', group: 'setup' },+ ],+ '_posthog/sandbox_output': [{ sessionId: RUN_ID, stdout: 'ok\n', stderr: '', exitCode: 0 }],+ '_posthog/user_message': [{ content: 'Why did checkout conversion drop last week?' }],+ '_posthog/usage_update': [+ {+ sessionId: 'sess_a1b2c3',+ used: { inputTokens: 12450, outputTokens: 980, cachedReadTokens: 110200, cachedWriteTokens: 2048 },+ cost: { amount: 0.42, currency: 'USD' },+ },+ {+ sessionId: 'sess_a1b2c3',+ used: { inputTokens: 900, outputTokens: 120, cachedReadTokens: 0, cachedWriteTokens: 0 },+ cost: null,+ },+ {+ sessionId: 'sess_a1b2c3',+ breakdown: {+ systemPrompt: 3100,+ tools: 8200,+ rules: 450,+ skills: 0,+ mcp: 12700,+ subagents: 0,+ conversation: 20410,+ },+ },+ {+ // Claude combined frame: used + cost (a bare number) + breakdown together.+ sessionId: 'sess_a1b2c3',+ used: { inputTokens: 5000, outputTokens: 600, cachedReadTokens: 100, cachedWriteTokens: 0 },+ cost: 0.18,+ breakdown: { systemPrompt: 2000, tools: 4000, conversation: 9000 },+ },+ ],+ '_posthog/status': [+ { sessionId: 'sess_a1b2c3', status: 'compacting' },+ { sessionId: 'sess_a1b2c3', status: 'compacting', isComplete: true },+ ],+ '_posthog/compact_boundary': [{ sessionId: 'sess_a1b2c3', trigger: 'auto', preTokens: 168000, contextSize: 54000 }],+ '_posthog/task_notification': [+ {+ sessionId: 'sess_a1b2c3',+ taskId: TASK_ID,+ status: 'completed',+ summary: 'Analysis written to report.md',+ outputFile: 'report.md',+ },+ ],+ '_posthog/error': [+ { message: 'Model request failed after 3 retries', classification: 'provider_error' },+ { message: 'Tool execution timed out' },+ ],+ '_posthog/sdk_session': [{ taskRunId: RUN_ID, sessionId: 'sess_a1b2c3', adapter: 'claude' }],+ '_posthog/resources_used': [+ {+ sessionId: 'sess_a1b2c3',+ products: [+ { id: 'product_analytics', label: 'Product analytics' },+ { id: 'session_replay', label: 'Session replay' },+ ],+ },+ ],+ '_posthog/permission_request': [+ {+ requestId: 'perm-1',+ toolCallId: 'toolu_01',+ options: [+ { optionId: 'allow_once', name: 'Allow once', kind: 'allow_once' },+ { optionId: 'reject', name: 'Reject', kind: 'reject' },+ ],+ toolCall: {+ toolCallId: 'toolu_01',+ title: 'Run SQL query',+ kind: 'execute',+ rawInput: { command: 'call execute-sql {"query": "SELECT 1"}' },+ },+ },+ ],+ '_posthog/permission_resolved': [{ requestId: 'perm-1', toolCallId: 'toolu_01', optionId: 'allow_once' }],+ '_posthog/run_started': [{ sessionId: 'sess_a1b2c3', runId: RUN_ID, taskId: TASK_ID, agentVersion: '1.42.0' }],+ '_posthog/turn_complete': [{ sessionId: 'sess_a1b2c3', stopReason: 'end_turn' }],+}++const KNOWN_POSTHOG_METHODS = Object.keys(NOTIFICATION_PARAMS_BY_METHOD) as (keyof PosthogNotificationParamsByMethod)[]++const SESSION_UPDATE_CASES: { kind: string; update: Record<string, unknown> }[] = [+ {+ kind: 'agent_message_chunk',+ update: {+ sessionUpdate: 'agent_message_chunk',+ messageId: 'msg_01',+ content: { type: 'text', text: 'Looking at the funnel' },+ },+ },+ { kind: 'agent_message_chunk', update: { sessionUpdate: 'agent_message_chunk', text: ' now.' } },+ {+ kind: 'agent_thought_chunk',+ update: {+ sessionUpdate: 'agent_thought_chunk',+ content: { type: 'text', text: 'Let me reason about the funnel drop-off' },+ },+ },+ {+ kind: 'agent_message',+ update: {+ sessionUpdate: 'agent_message',+ messageId: 'msg_01',+ content: { type: 'text', text: 'Looking at the funnel now.' },+ },+ },+ {+ kind: 'tool_call',+ update: {+ sessionUpdate: 'tool_call',+ toolCallId: 'toolu_02',+ serverName: 'posthog',+ toolName: 'exec',+ title: 'exec',+ kind: 'execute',+ status: 'pending',+ rawInput: { command: 'call insight-create {"name": "Weekly signups"}' },+ },+ },+ {+ kind: 'tool_call_update',+ update: {+ sessionUpdate: 'tool_call_update',+ toolCallId: 'toolu_02',+ status: 'completed',+ rawOutput: { short_id: 'abc123', name: 'Weekly signups' },+ content: [{ type: 'content', content: { type: 'text', text: '{"short_id": "abc123"}' } }],+ },+ },+ {+ kind: 'tool_call_update',+ update: {+ sessionUpdate: 'tool_call_update',+ toolCallId: 'toolu_04',+ status: 'failed',+ error: { message: 'Permission denied by user' },+ _meta: {+ claudeCode: {+ toolName: 'execute-sql',+ toolResponse: {+ decisionReason: 'User rejected the permission request',+ decisionReasonType: 'user_rejection',+ message: 'Permission denied',+ },+ },+ },+ },+ },+ { kind: 'current_mode_update', update: { sessionUpdate: 'current_mode_update', currentModeId: 'default' } },+]++function notificationOf(frame: unknown): AcpNotification {+ if (!isNotificationFrame(frame)) {+ throw new Error('expected a notification frame')+ }+ return frame.notification+}++describe('sandboxWireTypes guards', () => {+ it.each([+ ['queued', { type: 'task_run_state', run_id: RUN_ID, task_id: TASK_ID, status: 'queued', stage: null }],+ [+ 'failed',+ {+ type: 'task_run_state',+ run_id: RUN_ID,+ task_id: TASK_ID,+ status: 'failed',+ error_message: 'Agent server crashed: sandbox out of memory',+ completed_at: TIMESTAMP,+ },+ ],+ ])('classifies a %s task_run_state frame and exposes snake_case fields', (_name, frame) => {+ expect(isTaskRunStateFrame(frame)).toBe(true)+ expect(isNotificationFrame(frame)).toBe(false)+ expect(isKeepaliveFrame(frame)).toBe(false)+ expect(isPermissionRequestFrame(frame)).toBe(false)+ if (isTaskRunStateFrame(frame) && frame.status === 'failed') {+ expect(frame.error_message).toEqual(expect.any(String))+ }+ })++ it('classifies keepalive and top-level permission_request frames', () => {+ const keepalive = { type: 'keepalive' }+ expect(isKeepaliveFrame(keepalive)).toBe(true)+ expect(isNotificationFrame(keepalive)).toBe(false)++ const permission = {+ type: 'permission_request',+ requestId: 'perm-2',+ toolCallId: 'toolu_05',+ options: [{ optionId: 'allow_once', name: 'Allow once', kind: 'allow_once' }],+ toolCall: { toolCallId: 'toolu_05', title: 'Delete dashboard', kind: 'execute' },+ }+ expect(isPermissionRequestFrame(permission)).toBe(true)+ expect(isNotificationFrame(permission)).toBe(false)+ })++ it.each([+ ['unknown type', { type: 'telemetry_v2', payload: { metric: 'boot_time_ms', value: 5120 } }],+ ['missing type', { status: 'in_progress', note: 'frame with no type discriminant' }],+ ['notification with non-object body', { type: 'notification', notification: 'oops' }],+ ])('rejects a frame with %s from every envelope guard', (_name, frame) => {+ expect(isNotificationFrame(frame)).toBe(false)+ expect(isTaskRunStateFrame(frame)).toBe(false)+ expect(isKeepaliveFrame(frame)).toBe(false)+ expect(isPermissionRequestFrame(frame)).toBe(false)+ })++ it.each(+ KNOWN_POSTHOG_METHODS.flatMap((method) =>+ NOTIFICATION_PARAMS_BY_METHOD[method].map((params) => [method, params] as const)+ )+ )('%s notifications pass exactly the matching method guard', (method, params) => {+ const wireNotification = notificationOf(notification(method, params))+ for (const known of KNOWN_POSTHOG_METHODS) {+ expect(isPosthogNotification(wireNotification, known)).toBe(known === method)+ }+ expect(isSessionUpdateNotification(wireNotification)).toBe(false)+ })++ it('tolerates the Codex split frames and the Claude combined frame with "has field" checks', () => {+ const [used, usedNullCost, breakdown, combined] = NOTIFICATION_PARAMS_BY_METHOD['_posthog/usage_update'].map(+ (params) => notificationOf(notification('_posthog/usage_update', params))+ )+ for (const wireNotification of [used, usedNullCost]) {+ if (!isPosthogNotification(wireNotification, '_posthog/usage_update')) {+ throw new Error('expected usage_update notification')+ }+ expect(hasUsageUsed(wireNotification.params)).toBe(true)+ expect(hasUsageBreakdown(wireNotification.params)).toBe(false)+ expect(wireNotification.params?.used?.inputTokens).toEqual(expect.any(Number))+ }+ if (!isPosthogNotification(breakdown, '_posthog/usage_update')) {+ throw new Error('expected usage_update notification')+ }+ expect(hasUsageBreakdown(breakdown.params)).toBe(true)+ expect(hasUsageUsed(breakdown.params)).toBe(false)++ // Claude combined frame: both fields present, plus a numeric cost.+ if (!isPosthogNotification(combined, '_posthog/usage_update')) {+ throw new Error('expected usage_update notification')+ }+ expect(hasUsageUsed(combined.params)).toBe(true)+ expect(hasUsageBreakdown(combined.params)).toBe(true)+ expect(combined.params?.cost).toEqual(0.18)+ })++ it('recognizes the session/update-framed usage aggregate', () => {+ expect(isSessionUpdateUsage({ sessionUpdate: 'usage_update', used: 168000, size: 200000 })).toBe(true)+ expect(isKnownSessionUpdate({ sessionUpdate: 'usage_update', used: 168000, size: 200000 })).toBe(false)+ expect(isSessionUpdateUsage({ sessionUpdate: 'agent_message' })).toBe(false)+ })++ it('exposes typed progress params after narrowing', () => {+ const wireNotification = notificationOf(+ notification('_posthog/progress', NOTIFICATION_PARAMS_BY_METHOD['_posthog/progress'][0])+ )+ if (!isPosthogNotification(wireNotification, '_posthog/progress')) {+ throw new Error('expected progress notification')+ }+ expect(wireNotification.params?.label).toEqual('Cloning repository')+ expect(wireNotification.params?.detail).toEqual('PostHog/posthog @ master')+ })++ it.each(SESSION_UPDATE_CASES.map(({ kind, update }) => [kind, update] as const))(+ 'narrows a %s session/update to its kind',+ (kind, update) => {+ const wireNotification = notificationOf(sessionUpdate(update))+ expect(isSessionUpdateNotification(wireNotification)).toBe(true)+ const body = isSessionUpdateNotification(wireNotification) ? wireNotification.params?.update : undefined+ expect(isKnownSessionUpdate(body)).toBe(true)+ if (isKnownSessionUpdate(body)) {+ expect(body.sessionUpdate).toBe(kind)+ }+ }+ )++ it('carries the nested _meta.claudeCode denial reason on failed tool_call_update frames', () => {+ const failedCase = SESSION_UPDATE_CASES.find(({ update }) => update.status === 'failed')+ const wireNotification = notificationOf(sessionUpdate(failedCase!.update))+ const body = isSessionUpdateNotification(wireNotification) ? wireNotification.params?.update : undefined+ if (!isKnownSessionUpdate(body) || body.sessionUpdate !== 'tool_call_update') {+ throw new Error('expected a tool_call_update body')+ }+ const toolResponse = body._meta?.claudeCode?.toolResponse as { decisionReason?: string } | undefined+ expect(toolResponse?.decisionReason).toEqual(expect.any(String))+ expect(body._meta?.claudeCode?.toolName).toEqual(expect.any(String))+ expect(body.error?.message).toEqual(expect.any(String))+ })++ it('treats unknown sessionUpdate kinds as session/update of unknown body', () => {+ const wireNotification = notificationOf(+ sessionUpdate({ sessionUpdate: 'plan_delta', entries: [{ content: 'Investigate funnel' }] })+ )+ expect(isSessionUpdateNotification(wireNotification)).toBe(true)+ expect(isKnownSessionUpdate(wireNotification.params?.update)).toBe(false)+ })++ it('matches no known method guard for unknown _posthog methods', () => {+ const wireNotification = notificationOf(notification('_posthog/hologram_sync', { shards: 3 }))+ for (const known of KNOWN_POSTHOG_METHODS) {+ expect(isPosthogNotification(wireNotification, known)).toBe(false)+ }+ expect(isSessionUpdateNotification(wireNotification)).toBe(false)+ })++ it('still classifies degenerate notification bodies as notification frames', () => {+ // Real methods with missing or malformed params must pass the envelope guard — the+ // discriminant-only contract leaves payload defensiveness to the consumers.+ expect(isNotificationFrame(notification('_posthog/turn_complete'))).toBe(true)+ expect(+ isNotificationFrame({+ type: 'notification',+ notification: { method: '_posthog/console', params: 'not-an-object' },+ })+ ).toBe(true)+ })+})diff --git a/frontend/src/scenes/max/types/sandboxWireTypes.ts b/frontend/src/scenes/max/types/sandboxWireTypes.tsnew file mode 100644index 000000000000..b8a6dbffc0ab--- /dev/null+++ b/frontend/src/scenes/max/types/sandboxWireTypes.ts@@ -0,0 +1,429 @@+/**+ * Wire shapes for the sandbox agent stream (products/tasks SSE frames + persisted log entries).+ *+ * Two trust levels, matching who owns each shape: the `type`-discriminated envelope frames are+ * emitted by products/tasks (or follow JSON-RPC framing) and are guarded at the parse boundary;+ * everything inside `notification.params` is owned by the external agent adapters and evolves+ * independently — those shapes are typed but only discriminant-checked, never validated, so an+ * unknown or extended payload degrades to a no-op instead of an error. Old S3 log entries replay+ * forever; the parse path must accept the union of all historical formats.+ *+ * This file is the authoritative typed view of the contract — the frontend is the only consumer+ * of live SSE frames. The Python backend types just the slice it reads (persisted log entries)+ * at `products/posthog_ai/backend/wire_types.py`; keep that slice in sync when it grows.+ */++/** ACP notification body — the JSON-RPC payload carried inside a `StoredLogEntry`. */+export interface AcpNotification {+ jsonrpc?: string+ method?: string+ params?: Record<string, unknown>+ result?: unknown+ error?: { message?: string; code?: number } | null+}++/**+ * Wire envelope around a single ACP notification. The products/tasks stream emits these as+ * the bulk of `data.type === 'notification'` traffic; the `logs/` endpoint replays them.+ */+export interface StoredLogEntry {+ type: 'notification'+ timestamp?: string+ notification: AcpNotification+}++/**+ * Run-state frame from `TaskRun.build_stream_state_event` (products/tasks/backend/models.py).+ * Emitted for non-terminal transitions too (queued → in_progress) — never treat every frame+ * as terminal. Field names are snake_case on the wire.+ */+export interface TaskRunStateFrame {+ type: 'task_run_state'+ run_id?: string+ task_id?: string+ status?: string+ stage?: string | null+ output?: unknown+ branch?: string | null+ error_message?: string | null+ updated_at?: string | null+ completed_at?: string | null+}++export interface KeepaliveFrame {+ type: 'keepalive'+}++export interface PermissionOption {+ optionId: string+ name: string+ /**+ * ACP option kind. Known values: `allow_once`, `allow_always`, `reject_once`, plus the legacy+ * `reject` / `reject_with_feedback`. The vocabulary evolves with the agent adapter, so this stays+ * a `string` — the card resolves the affordance by prefix (`allow*` approve, everything else+ * decline), never by exact match. An exact-match allowlist silently dropped `reject_once`.+ */+ kind: string+ /** `_meta.customInput === true` — the option accepts optional free-text feedback. */+ customInput?: boolean+}++/** Top-level permission frame hoisted onto the stream by the relay. */+export interface PermissionRequestFrame {+ type: 'permission_request'+ requestId?: string+ toolCallId?: string+ options?: PermissionOption[]+ toolCall?: Record<string, unknown>+}++export type SandboxWireFrame = StoredLogEntry | TaskRunStateFrame | KeepaliveFrame | PermissionRequestFrame++/**+ * `event: error` payload. The products/tasks relay emits `{error}`; cloud-agent envelopes carry+ * `{errorTitle, errorMessage, retryable}` — consumers must tolerate either.+ */+export interface SseErrorFrameData {+ error?: string+ errorTitle?: string+ errorMessage?: string+ retryable?: boolean+}++function isRecord(value: unknown): value is Record<string, unknown> {+ return typeof value === 'object' && value !== null && !Array.isArray(value)+}++export function isNotificationFrame(value: unknown): value is StoredLogEntry {+ return isRecord(value) && value.type === 'notification' && isRecord(value.notification)+}++export function isTaskRunStateFrame(value: unknown): value is TaskRunStateFrame {+ return isRecord(value) && value.type === 'task_run_state'+}++export function isKeepaliveFrame(value: unknown): value is KeepaliveFrame {+ return isRecord(value) && value.type === 'keepalive'+}++export function isPermissionRequestFrame(value: unknown): value is PermissionRequestFrame {+ return isRecord(value) && value.type === 'permission_request'+}++// --- session/update bodies ---++export interface SessionUpdateText {+ type?: string+ text?: string+}++export interface SessionUpdateAgentMessageChunk {+ sessionUpdate: 'agent_message_chunk'+ messageId?: string+ content?: SessionUpdateText+ text?: string+}++export interface SessionUpdateAgentMessage {+ sessionUpdate: 'agent_message'+ messageId?: string+ content?: SessionUpdateText+ text?: string+}++/**+ * Streamed agent reasoning. Mirrors `agent_message_chunk` on the wire (a text `content` block,+ * usually no `messageId`) but renders as a collapsible "Thought" rather than chat text. ACP emits+ * no finalize counterpart — a thought is done once a later block (message or tool call) starts.+ */+export interface SessionUpdateAgentThoughtChunk {+ sessionUpdate: 'agent_thought_chunk'+ messageId?: string+ content?: SessionUpdateText+ text?: string+}++export interface SessionUpdateToolCall {+ sessionUpdate: 'tool_call'+ toolCallId?: string+ serverName?: string+ toolName?: string+ title?: string+ kind?: string+ status?: string+ rawInput?: Record<string, unknown>+ input?: Record<string, unknown>+ locations?: { path: string; line?: number }[]+ content?: unknown[]+ _meta?: SessionUpdateToolCallMeta+}++/**+ * Claude adapter metadata stamped under `_meta.claudeCode` on every Claude tool frame. `toolName`+ * is the stable SDK tool name (e.g. "Edit", "TodoWrite") — built-ins carry no top-level `toolName`,+ * so this is the only place the real name is reachable. `toolResponse` is present on a permission+ * denial and free-form otherwise. Mirrors Twig's `ToolUpdateMeta`.+ */+export interface SessionUpdateClaudeCodeMeta {+ toolName?: string+ /** Present on a permission denial; free-form on other frames. */+ toolResponse?: { decisionReason?: string; decisionReasonType?: string; message?: string } | unknown+ parentToolCallId?: string+ bashCommand?: string+}++export interface SessionUpdateToolCallMeta {+ claudeCode?: SessionUpdateClaudeCodeMeta+}++export interface SessionUpdateToolCallUpdate {+ sessionUpdate: 'tool_call_update'+ toolCallId?: string+ status?: string+ title?: string+ rawInput?: Record<string, unknown>+ input?: Record<string, unknown>+ rawOutput?: unknown+ progress?: unknown+ error?: { message?: string } | null+ locations?: { path: string; line?: number }[]+ content?: unknown[]+ _meta?: SessionUpdateToolCallMeta+}++export interface SessionUpdateCurrentMode {+ sessionUpdate: 'current_mode_update'+ currentModeId?: string+ mode?: string+}++export type SessionUpdateBody =+ | SessionUpdateAgentMessageChunk+ | SessionUpdateAgentMessage+ | SessionUpdateAgentThoughtChunk+ | SessionUpdateToolCall+ | SessionUpdateToolCallUpdate+ | SessionUpdateCurrentMode++export interface SessionUpdateParams {+ sessionId?: string+ update?: SessionUpdateBody | Record<string, unknown>+}++export function isSessionUpdateNotification(+ notification: AcpNotification+): notification is AcpNotification & { method: 'session/update'; params?: SessionUpdateParams } {+ return notification.method === 'session/update'+}++const KNOWN_SESSION_UPDATES: ReadonlySet<string> = new Set([+ 'agent_message_chunk',+ 'agent_message',+ 'agent_thought_chunk',+ 'tool_call',+ 'tool_call_update',+ 'current_mode_update',+])++export function isKnownSessionUpdate(update: unknown): update is SessionUpdateBody {+ return (+ isRecord(update) && typeof update.sessionUpdate === 'string' && KNOWN_SESSION_UPDATES.has(update.sessionUpdate)+ )+}++// --- `_posthog/*` notification params (adapter-owned; keys are camelCase as on the wire) ---++export interface PosthogConsoleParams {+ sessionId?: string+ level?: string+ message?: string+}++export interface PosthogProgressParams {+ sessionId?: string+ step?: string+ status?: string+ label?: string+ group?: string+ detail?: string+}++export interface PosthogSandboxOutputParams {+ sessionId?: string+ stdout?: string+ stderr?: string+ exitCode?: number+}++export interface PosthogUserMessageParams {+ content?: string | unknown[]+}++export interface PosthogUsageTokens {+ inputTokens?: number+ outputTokens?: number+ cachedReadTokens?: number+ cachedWriteTokens?: number+}++export interface PosthogUsageBreakdown {+ systemPrompt?: number+ tools?: number+ rules?: number+ skills?: number+ mcp?: number+ subagents?: number+ conversation?: number+}++/**+ * The `_posthog/usage_update` ext-notification. Permissive on purpose: the Codex adapter emits two+ * separate frames (one carrying `used`+`cost: null`, one carrying `breakdown`), while the Claude+ * adapter emits a single combined frame carrying `used`, `cost` (a bare number), AND `breakdown`+ * together. `cost` therefore tolerates either the `{amount, currency}` object (Codex / the+ * session/update aggregate) or a raw number (Claude). All fields optional so any adapter's framing+ * folds in without dropping data.+ */+export interface PosthogUsageUpdateParams {+ sessionId?: string+ used?: PosthogUsageTokens+ cost?: number | { amount?: number; currency?: string } | null+ breakdown?: PosthogUsageBreakdown+}++/**+ * The numeric `used`/`size` aggregate that drives the context-usage percentage ring. It does NOT+ * arrive on the `_posthog/usage_update` ext-notification — it is a `session/update`-framed update+ * (`sessionUpdate: 'usage_update'`) carrying flat numeric token counts plus cost.+ */+export interface SessionUpdateUsage {+ sessionUpdate: 'usage_update'+ used?: number+ size?: number+ cost?: { amount?: number; currency?: string } | null+}++export function isSessionUpdateUsage(update: unknown): update is SessionUpdateUsage {+ return isRecord(update) && update.sessionUpdate === 'usage_update'+}++/**+ * The user's own turn, echoed back by the agent adapter and persisted to the run log as a+ * `session/update` (not a `_posthog/*` ext-notification). Carries the full prompt text in a single+ * frame — it is not token-streamed like the agent's. Rendered only on `logs/` bootstrap replay: a+ * live turn is already echoed into the thread by maxThreadLogic the moment it's sent, so rendering+ * the wire echo too would duplicate it. This is the path that restores human turns on thread load.+ */+export interface SessionUpdateUserMessage {+ sessionUpdate: 'user_message_chunk' | 'user_message'+ messageId?: string+ content?: SessionUpdateText+ text?: string+}++export function isSessionUpdateUserMessage(update: unknown): update is SessionUpdateUserMessage {+ return (+ isRecord(update) && (update.sessionUpdate === 'user_message_chunk' || update.sessionUpdate === 'user_message')+ )+}++export interface PosthogStatusParams {+ sessionId?: string+ status?: string+ isComplete?: boolean+}++export interface PosthogCompactBoundaryParams {+ sessionId?: string+ trigger?: string+ preTokens?: number+ contextSize?: number+}++export interface PosthogTaskNotificationParams {+ sessionId?: string+ taskId?: string+ status?: string+ summary?: string+ outputFile?: string+}++export interface PosthogErrorParams {+ message?: string+ classification?: string+}++export interface PosthogSdkSessionParams {+ taskRunId?: string+ sessionId?: string+ adapter?: string+}++export interface PosthogResourcesUsedParams {+ sessionId?: string+ products?: { id?: string; label?: string }[]+}++/** Permission lifecycle persisted to the run log — pending approvals are re-derived from these on bootstrap. */+export interface PosthogPermissionRequestParams {+ requestId?: string+ toolCallId?: string+ options?: PermissionOption[]+ toolCall?: Record<string, unknown>+}++export interface PosthogPermissionResolvedParams {+ requestId?: string+ toolCallId?: string+ optionId?: string+}++export interface PosthogRunStartedParams {+ sessionId?: string+ runId?: string+ taskId?: string+ agentVersion?: string+}++export interface PosthogTurnCompleteParams {+ sessionId?: string+ stopReason?: string+}++export interface PosthogNotificationParamsByMethod {+ '_posthog/console': PosthogConsoleParams+ '_posthog/progress': PosthogProgressParams+ '_posthog/sandbox_output': PosthogSandboxOutputParams+ '_posthog/user_message': PosthogUserMessageParams+ '_posthog/usage_update': PosthogUsageUpdateParams+ '_posthog/status': PosthogStatusParams+ '_posthog/compact_boundary': PosthogCompactBoundaryParams+ '_posthog/task_notification': PosthogTaskNotificationParams+ '_posthog/error': PosthogErrorParams+ '_posthog/sdk_session': PosthogSdkSessionParams+ '_posthog/resources_used': PosthogResourcesUsedParams+ '_posthog/permission_request': PosthogPermissionRequestParams+ '_posthog/permission_resolved': PosthogPermissionResolvedParams+ '_posthog/run_started': PosthogRunStartedParams+ '_posthog/turn_complete': PosthogTurnCompleteParams+}++/**+ * Narrows a notification to a known `_posthog/*` method and its params shape. Discriminant-only:+ * the params contents stay trusted per the module contract.+ */+export function isPosthogNotification<M extends keyof PosthogNotificationParamsByMethod>(+ notification: AcpNotification,+ method: M+): notification is AcpNotification & { method: M; params?: PosthogNotificationParamsByMethod[M] } {+ return notification.method === method+}++/** "Has field" checks rather than mutually exclusive — the Claude combined frame carries both. */+export function hasUsageUsed(params: PosthogUsageUpdateParams | undefined): boolean {+ return !!params && params.used != null+}++export function hasUsageBreakdown(params: PosthogUsageUpdateParams | undefined): boolean {+ return !!params && params.breakdown != null+}diff --git a/frontend/src/scenes/max/utils/thinkingMessages.ts b/frontend/src/scenes/max/utils/thinkingMessages.tsindex 5e312a3919fa..b04637910d43 100644--- a/frontend/src/scenes/max/utils/thinkingMessages.ts+++ b/frontend/src/scenes/max/utils/thinkingMessages.ts@@ -36,6 +36,9 @@ export const THINKING_MESSAGES = ['Swizzling', // techy weirdness'Grokking', // deep understanding'Hedging', // hedgehog pun+ 'Posthogging', // brand pun+ 'Self-driving', // autonomy pun+ 'Signaling', // signals pun'Scheming', // clever planning'Unfurling', // opening up ideas'Puzzling', // solving something trickydiff --git a/frontend/src/types.ts b/frontend/src/types.tsindex b2f8e6bb3593..48459bcc1ad1 100644--- a/frontend/src/types.ts+++ b/frontend/src/types.ts@@ -7276,6 +7276,13 @@ export interface Conversation {is_internal?: booleanpending_approvals?: PendingApproval[]is_sandbox?: boolean+ /**+ * Runtime the conversation was created on. Stamped at create-time from the `phai-sandbox-mode`+ * flag and never re-read. Existing rows default to `'langgraph'`.+ */+ agent_runtime?: 'langgraph' | 'sandbox'+ /** Backing products/tasks Task for sandbox conversations. Null until the first message creates it. `latest_run` is the newest TaskRun id used to bootstrap the sandbox stream. */+ task?: { id: string; latest_run: string | null } | null}export interface ConversationDetail extends Conversation {