: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): render product tool widgets across all posthog_ai surfaces (#67498)
Georgiy Tarasov1669f8d84a04
diff --git a/frontend/src/scenes/max/AGENTS.md b/frontend/src/scenes/max/AGENTS.mdindex a8f9a2b27d0b..007283f96bd9 100644--- a/frontend/src/scenes/max/AGENTS.md+++ b/frontend/src/scenes/max/AGENTS.md@@ -19,7 +19,7 @@ Per-concern mapping, `langgraph` (LEGACY, frozen) → `sandbox` (NEW, build here- **Thread renderer**: `Thread.tsx` (default path) → `Thread.tsx` binds the surface's `ThreadView`- **Context shape**: rich `MaxUIContext` (full objects) → flat `AttachedContext` (typed refs, agent fetches)- **Approvals**: `DangerousOperationApprovalCard.tsx` / `approvalOperationUtils.ts` → the surface's `PermissionInput` / `QuestionInput`-- **Tool widgets**: `messages/` + `messages/adapters/` → the surface's `toolRegistry` (Max's product renderers register via `messages/adapters/registerMaxToolRenderers`)+- **Tool widgets**: `messages/` (LangGraph presenters) → the surface's `toolRegistry`. The PostHog product renderers (insight/dashboard/recordings/error-tracking/notebook/query) now live in `products/posthog_ai/frontend/components/tool/widgets` and self-register there; Max is a consumer.### Rule: do not extend the LangGraph path unless explicitly asked@@ -30,7 +30,7 @@ New behavior — new tools, new context types, new UI affordances — goes on th- ❌ 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/`.+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/`.## 2. Sandbox architecture & conventions live with the surface@@ -56,10 +56,11 @@ directory's `README.md` for the tier decision table + recipes and its `AGENTS.mdand the hard rule that it must never import `scenes/max`.What stays in `scenes/max`: conversation orchestration (`maxLogic`, `maxThreadLogic`, `maxGlobalLogic`), the-Max Context subsystem, slash commands, `useMaxTool`/`MaxTool`, feedback/ratings, the frozen LangGraph path,-and Max's **product-specific tool renderers** (`messages/adapters/*`), which register themselves into the-shared `toolRegistry` via `messages/adapters/registerMaxToolRenderers` (imported once from-`Thread.tsx`). Add a new product tool renderer there, not in `products/posthog_ai/frontend`.+Max Context subsystem, slash commands, `useMaxTool`/`MaxTool`, feedback/ratings, and the frozen LangGraph+path (including its `messages/*` presenters). The **PostHog product tool renderers** (insight, dashboard,+recordings, error-tracking, notebook, query) now live in `products/posthog_ai/frontend/components/tool/widgets`+and self-register there — add a new one in the surface, not here. Max's LangGraph path consumes the heavier+ones (`VisualizationWidget` / `RecordingsWidget` / `ErrorTrackingFiltersWidget`) through `api/primitives`.## 5. Where do I add X?@@ -68,7 +69,7 @@ The first three now live in `products/posthog_ai/frontend` (the shared surface)- **A new thread-item type** → `products/posthog_ai/frontend/types/streamTypes.ts` (the `ThreadItem` union), handle it in `foldLogToThread`, and add a memoized leaf renderer wired into `ThreadView`/`ThreadRow`.- **A new permission affordance / auto-approval rule** → `products/posthog_ai/frontend/policy/toolPolicy.ts`, then surface it through `PermissionInput`.- **New stream telemetry** → a guarded `posthog.capture` in the relevant `runStreamLogic` listener (fire-once, suppressed on replay).-- **A new product tool renderer** (renders a PostHog entity) → `scenes/max/messages/adapters/*` + register it in `messages/adapters/registerMaxToolRenderers`.+- **A new product tool renderer** (renders a PostHog entity) → `products/posthog_ai/frontend/components/tool/widgets/*` + register it in `widgets/registerDataToolRenderers` (the surface self-registers; every consumer, including Max's sandbox path, picks it up).- **New context the agent should see** → extend `AttachedContext` (not `MaxUIContext`).## 6. Don'tsdiff --git a/frontend/src/scenes/max/Thread.tsx b/frontend/src/scenes/max/Thread.tsxindex 186fcd346e11..d444f0b73172 100644--- a/frontend/src/scenes/max/Thread.tsx+++ b/frontend/src/scenes/max/Thread.tsx@@ -1,7 +1,3 @@-// Side-effect: registers Max's product-specific tool renderers (insight/dashboard/recordings/etc.) into-// the shared toolRegistry. Imported here so they're registered whenever the Max thread renders.-import './messages/adapters/registerMaxToolRenderers'-import clsx from 'clsx'import { BindLogic, useActions, useValues } from 'kea'import posthog from 'posthog-js'@@ -66,7 +62,7 @@ import {} from '~/queries/schema/schema-assistant-messages'import { DataVisualizationNode, InsightVizNode } from '~/queries/schema/schema-general'import { isDataVisualizationNode, isHogQLQuery } from '~/queries/utils'-import { PendingApproval, Region } from '~/types'+import { PendingApproval, RecordingUniversalFilters, Region } from '~/types'import { getThinkingMessageFromResponse, runStreamLogic } from 'products/posthog_ai/frontend/api/logics'import {@@ -75,6 +71,7 @@ import {MarkdownMessage,MessageTemplate,ReasoningAnswer,+ RecordingsWidget,ResourcesBar,ThreadView,} from 'products/posthog_ai/frontend/api/primitives'@@ -94,7 +91,7 @@ import { maxThreadLogic } from './maxThreadLogic'import { MultiQuestionFormRecap } from './messages/MultiQuestionForm'import { NotebookArtifactAnswer } from './messages/NotebookArtifactAnswer'import { SessionSummarizationProgress } from './messages/SessionSummarizationProgress'-import { RecordingsWidget, isRenderableUIPayloadTool } from './messages/UIPayloadAnswer'+import { isRenderableUIPayloadTool } from './messages/UIPayloadAnswer'import { VisualizationArtifact } from './messages/VisualizationArtifact'import { MAX_SLASH_COMMANDS, SlashCommandName } from './slash-commands'import { TicketPrompt } from './TicketPrompt'@@ -1019,6 +1016,7 @@ interface ToolCallsAnswerProps {}function ToolCallsAnswer({ toolCalls, registeredToolMap }: ToolCallsAnswerProps): JSX.Element {+ const { onAcceptSessionFilters } = useValues(maxLogic)// Separate todo_write tool calls from regular tool callsconst todoWriteToolCalls = toolCalls.filter((tc) => tc.name === 'todo_write')const regularToolCalls = toolCalls.filter((tc) => tc.name !== 'todo_write')@@ -1045,7 +1043,7 @@ function ToolCallsAnswer({ toolCalls, registeredToolMap }: ToolCallsAnswerProps){regularToolCalls.map((toolCall) => {const definition = getToolDefinitionFromToolCall(toolCall)const [description, widgetDef] = getToolCallDescriptionAndWidgetDef(toolCall, registeredToolMap)- const widget = renderToolCallWidget(widgetDef, toolCall.id)+ const widget = renderToolCallWidget(widgetDef, toolCall.id, onAcceptSessionFilters)return (<LangGraphActivitykey={toolCall.id}@@ -1428,10 +1426,21 @@ function SuccessActions({)}-function renderToolCallWidget(widgetDef: ToolCallWidgetDef | null, toolCallId: string): JSX.Element | null {+function renderToolCallWidget(+ widgetDef: ToolCallWidgetDef | null,+ toolCallId: string,+ onAcceptSessionFilters?: ((filters: RecordingUniversalFilters) => void) | null+): JSX.Element | null {switch (widgetDef?.widget) {case 'recordings':- return <RecordingsWidget toolCallId={toolCallId} filters={widgetDef.args} embedded />+ return (+ <RecordingsWidget+ toolCallId={toolCallId}+ filters={widgetDef.args}+ embedded+ onAcceptFilters={onAcceptSessionFilters}+ />+ )case 'session_summarization':return <SessionSummarizationProgress updates={widgetDef.args.updates} />default:diff --git a/frontend/src/scenes/max/messages/adapters/AnnotatedScreenshotView.tsx b/frontend/src/scenes/max/messages/AnnotatedScreenshotView.tsxsimilarity index 100%rename from frontend/src/scenes/max/messages/adapters/AnnotatedScreenshotView.tsxrename to frontend/src/scenes/max/messages/AnnotatedScreenshotView.tsxdiff --git a/frontend/src/scenes/max/messages/UIPayloadAnswer.tsx b/frontend/src/scenes/max/messages/UIPayloadAnswer.tsxindex 8793749226d1..2556c59398dd 100644--- a/frontend/src/scenes/max/messages/UIPayloadAnswer.tsx+++ b/frontend/src/scenes/max/messages/UIPayloadAnswer.tsx@@ -1,46 +1,24 @@-import { BindLogic, useActions, useValues } from 'kea'-import { useEffect } from 'react'+import { useValues } from 'kea'-import { IconCheck, IconNotebook } from '@posthog/icons'-import { LemonButton, Spinner } from '@posthog/lemon-ui'+import { IconNotebook } from '@posthog/icons'+import { LemonButton } from '@posthog/lemon-ui'-import { EmptyMessage } from 'lib/components/EmptyMessage/EmptyMessage'-import { IconOpenInNew } from 'lib/lemon-ui/icons'-import { sceneLogic } from 'scenes/sceneLogic'-import { Scene } from 'scenes/sceneTypes'-import { sessionPlayerModalLogic } from 'scenes/session-recordings/player/modal/sessionPlayerModalLogic'-import { SessionRecordingPreview } from 'scenes/session-recordings/playlist/SessionRecordingPreview'-import {- SessionRecordingPlaylistLogicProps,- sessionRecordingsPlaylistLogic,-} from 'scenes/session-recordings/playlist/sessionRecordingsPlaylistLogic'import { urls } from 'scenes/urls'-import {- MaxErrorTrackingIssuePreview,- MaxErrorTrackingSearchResponse,-} from '~/queries/schema/schema-assistant-error-tracking'+import { MaxErrorTrackingSearchResponse } from '~/queries/schema/schema-assistant-error-tracking'import { AssistantTool } from '~/queries/schema/schema-assistant-messages'import { RecordingUniversalFilters } from '~/types'-import { issueFiltersLogic } from 'products/error_tracking/frontend/components/IssueFilters/issueFiltersLogic'import {- ErrorTrackingQueryOrderBy,- ErrorTrackingQueryOrderDirection,- ErrorTrackingQueryStatus,- issueQueryOptionsLogic,-} from 'products/error_tracking/frontend/components/IssueQueryOptions/issueQueryOptionsLogic'-import { ERROR_TRACKING_SCENE_LOGIC_KEY } from 'products/error_tracking/frontend/scenes/ErrorTrackingScene/errorTrackingSceneLogic'-import { MessageTemplate } from 'products/posthog_ai/frontend/api/primitives'+ ErrorTrackingFiltersWidget,+ MessageTemplate,+ RecordingsWidget,+} from 'products/posthog_ai/frontend/api/primitives'import { isDangerousOperationResponse, normalizeDangerousOperationResponse } from '../approvalOperationUtils'import { DangerousOperationApprovalCard } from '../DangerousOperationApprovalCard'import { maxLogic } from '../maxLogic'-import { AnnotatedScreenshotView, parseAnnotatedScreenshot } from './adapters/AnnotatedScreenshotView'-import { ErrorTrackingFiltersSummary } from './ErrorTrackingFiltersSummary'-import { ErrorTrackingIssueCard } from './ErrorTrackingIssueCard'-import { MaxErrorTrackingWidgetLogicProps, maxErrorTrackingWidgetLogic } from './maxErrorTrackingWidgetLogic'-import { RecordingsFiltersSummary } from './RecordingsFiltersSummary'+import { AnnotatedScreenshotView, parseAnnotatedScreenshot } from './AnnotatedScreenshotView'export const RENDERABLE_UI_PAYLOAD_TOOLS: AssistantTool[] = ['search_session_recordings',@@ -69,11 +47,18 @@ export function UIPayloadAnswer({toolPayload: anyembedded?: boolean}): JSX.Element | null {- const { conversationId } = useValues(maxLogic)+ const { conversationId, onAcceptSessionFilters } = useValues(maxLogic)if (toolName === 'search_session_recordings') {const filters = toolPayload as RecordingUniversalFilters- return <RecordingsWidget toolCallId={toolCallId} filters={filters} embedded={embedded} />+ return (+ <RecordingsWidget+ toolCallId={toolCallId}+ filters={filters}+ embedded={embedded}+ onAcceptFilters={onAcceptSessionFilters}+ />+ )}if (toolName === 'search_error_tracking_issues') {const filters = toolPayload as MaxErrorTrackingSearchResponse@@ -109,268 +94,6 @@ export function UIPayloadAnswer({return null}-export function RecordingsWidget({- toolCallId,- filters,- embedded = false,-}: {- toolCallId: string- filters: RecordingUniversalFilters- embedded?: boolean-}): JSX.Element {- const { onAcceptSessionFilters } = useValues(maxLogic)- const logicProps: SessionRecordingPlaylistLogicProps = {- logicKey: `ai-recordings-widget-${toolCallId}`,- filters,- updateSearchParams: false,- autoPlay: false,- }- const content = (- <>- <RecordingsFiltersSummary filters={filters} />- <RecordingsListContent />- {onAcceptSessionFilters && <AcceptFiltersBar filters={filters} onAccept={onAcceptSessionFilters} />}- </>- )-- return (- <BindLogic logic={sessionRecordingsPlaylistLogic} props={logicProps}>- {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>- )-}--function AcceptFiltersBar({- filters,- onAccept,-}: {- filters: RecordingUniversalFilters- onAccept: (filters: RecordingUniversalFilters) => void-}): JSX.Element {- return (- <div className="border-t px-3 py-2 flex items-center justify-end">- <LemonButton type="primary" size="small" icon={<IconCheck />} onClick={() => onAccept(filters)}>- Use these filters for session analysis- </LemonButton>- </div>- )-}--function RecordingsListContent(): JSX.Element {- const { otherRecordings, sessionRecordingsResponseLoading, hasNext } = useValues(sessionRecordingsPlaylistLogic)- const { maybeLoadSessionRecordings } = useActions(sessionRecordingsPlaylistLogic)- const { openSessionPlayer } = useActions(sessionPlayerModalLogic())-- const hasRecordings = otherRecordings.length > 0-- return (- <div className="border-t *:not-first:border-t max-h-80 overflow-y-auto">- {sessionRecordingsResponseLoading && !hasRecordings ? (- <div className="flex items-center justify-center gap-2 py-12 text-muted">- <Spinner textColored />- <span>Loading recordings...</span>- </div>- ) : !hasRecordings ? (- <div className="py-2">- <EmptyMessage title="No recordings found" description="No recordings match the specified filters" />- </div>- ) : (- <>- {otherRecordings.map((recording) => (- <div- key={recording.id}- onClick={(e) => {- e.preventDefault()- openSessionPlayer(recording)- }}- >- <SessionRecordingPreview recording={recording} selectable={false} />- </div>- ))}- {hasNext && (- <div className="p-2">- <LemonButton- fullWidth- type="secondary"- size="small"- onClick={() => maybeLoadSessionRecordings('older')}- loading={sessionRecordingsResponseLoading}- >- Load more recordings- </LemonButton>- </div>- )}- </>- )}- </div>- )-}--export function ErrorTrackingFiltersWidget({- toolCallId,- filters,- embedded = false,-}: {- toolCallId: string- filters: 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">- {emptyState}- </MessageTemplate>- )- }-- return (- <BindLogic logic={maxErrorTrackingWidgetLogic} props={logicProps}>- <ErrorTrackingFiltersWidgetContent filters={filters} embedded={embedded} />- </BindLogic>- )-}--function ErrorTrackingFiltersWidgetContent({- filters,- embedded,-}: {- filters: MaxErrorTrackingSearchResponse- embedded: boolean-}): JSX.Element {- const { activeSceneId } = useValues(sceneLogic)- const isOnErrorTrackingPage = activeSceneId === Scene.ErrorTracking-- const { issues, hasMore, isLoading } = useValues(maxErrorTrackingWidgetLogic)- const { loadMoreIssues } = useActions(maxErrorTrackingWidgetLogic)-- const filtersLogic = issueFiltersLogic({ logicKey: ERROR_TRACKING_SCENE_LOGIC_KEY })- const queryOptionsLogic = issueQueryOptionsLogic({ logicKey: ERROR_TRACKING_SCENE_LOGIC_KEY })-- const { setDateRange, setSearchQuery } = useActions(filtersLogic)- const { setStatus, setOrderBy, setOrderDirection } = useActions(queryOptionsLogic)-- // Automatically apply filters when on the Error Tracking page- useEffect(() => {- if (isOnErrorTrackingPage) {- if (filters.date_from || filters.date_to) {- setDateRange({ date_from: filters.date_from ?? null, date_to: filters.date_to ?? null })- }- if (filters.search_query) {- setSearchQuery(filters.search_query)- }- if (filters.status) {- setStatus(filters.status as ErrorTrackingQueryStatus)- }- if (filters.order_by) {- setOrderBy(filters.order_by as ErrorTrackingQueryOrderBy)- }- if (filters.order_direction) {- setOrderDirection(filters.order_direction as ErrorTrackingQueryOrderDirection)- }- }- }, [- isOnErrorTrackingPage,- setOrderDirection,- filters.search_query,- filters.order_direction,- setOrderBy,- filters.date_from,- filters.order_by,- filters.status,- setSearchQuery,- setStatus,- filters.date_to,- setDateRange,- ])-- const buildErrorTrackingUrl = (): string => {- const params = new URLSearchParams()- if (filters.status) {- params.set('status', filters.status)- }- if (filters.search_query) {- params.set('searchQuery', filters.search_query)- }- if (filters.date_from) {- params.set('dateFrom', filters.date_from)- }- if (filters.date_to) {- params.set('dateTo', filters.date_to)- }- const query = params.toString()- return urls.errorTracking() + (query ? `?${query}` : '')- }-- const hasIssues = issues.length > 0- const errorTrackingUrl = buildErrorTrackingUrl()-- 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>- <LemonButton- to={errorTrackingUrl}- icon={<IconOpenInNew />}- size="xsmall"- tooltip="Open in Error tracking"- />- </div>- )}- <ErrorTrackingFiltersSummary filters={filters} />- <div className="border-t">- {hasIssues ? (- <div className="*:not-first:border-t max-h-80 overflow-y-auto">- {issues.map((issue: MaxErrorTrackingIssuePreview) => (- <ErrorTrackingIssueCard key={issue.id} issue={issue} />- ))}- </div>- ) : (- <div className="py-2">- <EmptyMessage title="No issues found" description="No issues match the specified filters" />- </div>- )}- {hasMore && (- <div className="flex justify-center p-2 border-t">- <LemonButton type="tertiary" size="xsmall" onClick={() => loadMoreIssues()} loading={isLoading}>- Load more issues- </LemonButton>- </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>- )-}-export function SummarizeSessionsWidget({payload,title,diff --git a/frontend/src/scenes/max/messages/VisualizationArtifact.tsx b/frontend/src/scenes/max/messages/VisualizationArtifact.tsxindex 4279e6c0b0a1..942980c72edc 100644--- a/frontend/src/scenes/max/messages/VisualizationArtifact.tsx+++ b/frontend/src/scenes/max/messages/VisualizationArtifact.tsx@@ -10,8 +10,9 @@ import { Scene } from 'scenes/sceneTypes'import { ArtifactMessage, VisualizationArtifactContent } from '~/queries/schema/schema-assistant-messages'+import { VisualizationWidget, getArtifactOpenTarget } from 'products/posthog_ai/frontend/api/primitives'+import { MessageStatus } from '../maxLogic'-import { VisualizationWidget, getArtifactOpenTarget } from './VisualizationWidget'interface VisualizationArtifactProps {message: ArtifactMessage & { status?: MessageStatus }diff --git a/frontend/src/scenes/max/messages/adapters/UpsertDashboardWidget.tsx b/frontend/src/scenes/max/messages/adapters/UpsertDashboardWidget.tsxdeleted file mode 100644index 6253368f15a8..000000000000--- a/frontend/src/scenes/max/messages/adapters/UpsertDashboardWidget.tsx+++ /dev/null@@ -1,41 +0,0 @@-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, DataToolRow, type ToolRendererProps } from 'products/posthog_ai/frontend/api/tools'--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: ToolRendererProps): 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 (- <DataToolRow {...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>- </DataToolRow>- )-}diff --git a/products/logs/frontend/components/LogsViewer/LogDetailsModal/Tabs/RelatedErrors/RelatedErrorsTab.tsx b/products/logs/frontend/components/LogsViewer/LogDetailsModal/Tabs/RelatedErrors/RelatedErrorsTab.tsxindex 4c0ad8289b61..0f8008f6a4a3 100644--- a/products/logs/frontend/components/LogsViewer/LogDetailsModal/Tabs/RelatedErrors/RelatedErrorsTab.tsx+++ b/products/logs/frontend/components/LogsViewer/LogDetailsModal/Tabs/RelatedErrors/RelatedErrorsTab.tsx@@ -3,10 +3,11 @@ import { BindLogic, useActions, useValues } from 'kea'import { LemonBanner, LemonSkeleton } from '@posthog/lemon-ui'import { EmptyMessage } from 'lib/components/EmptyMessage/EmptyMessage'-import { ErrorTrackingIssueCard } from 'scenes/max/messages/ErrorTrackingIssueCard'import { MaxErrorTrackingIssuePreview } from '~/queries/schema/schema-assistant-error-tracking'+import { ErrorTrackingIssueCard } from 'products/posthog_ai/frontend/api/primitives'+import { RelatedErrorsLogicProps, relatedErrorsLogic } from './relatedErrorsLogic'export interface RelatedErrorsTabProps {diff --git a/products/posthog_ai/frontend/AGENTS.md b/products/posthog_ai/frontend/AGENTS.mdindex 85b483ac2649..e485792c1474 100644--- a/products/posthog_ai/frontend/AGENTS.md+++ b/products/posthog_ai/frontend/AGENTS.md@@ -90,19 +90,23 @@ It must stay **free of the Max scene and conversation orchestration**. Do not im- `runStreamLogic` keys on a generic `streamKey` (conversation id for Max, run/task id for a taskviewer). Keep it generic — no Max-specific branching.-- **Product-specific tool renderers live in the consuming product, not here — via the generic seam.**+- **The PostHog product data-tool renderers live in this surface and self-register — via the generic seam.**`api/tools` exposes `toolRegistry` and the convenience wrapper **`registerToolRenderers(entries)`**: the- generic per-product mechanism for a product to plug in cards that display its own entities. A product- registers from its own scene's entrypoint; the shared registry stays free of product imports. **Max is- the first consumer of this pattern, not a special case** — its renderers (insights, dashboards,- recordings, error-tracking issues, notebooks, query results) live in `scenes/max/messages/adapters` and- call `registerToolRenderers` via `registerMaxToolRenderers` (imported once by the Max scene). The shared- registry only knows the built-ins, the exec verbs, the question card, the generic MCP card, and the- generic `EditDiffRenderer`. Surfaces without an adapter for a key (tasks, signals inbox) fall through to- the generic card — by design.+ generic per-product mechanism for plugging in cards that display PostHog entities. The data-tool widgets+ (insights, dashboards, recordings, error-tracking issues, notebooks, query results) live in+ `components/tool/widgets/` and register themselves via `widgets/registerDataToolRenderers`, which+ `components/tool/ToolCallCard` side-effect-imports. Because that import sits at the render chokepoint,+ **every consumer that renders a tool card — the `/tasks` runner, the signals inbox, and Max's sandbox+ path — gets the widgets**, without the consumer having to opt in. The base `toolRegistry` module itself+ stays product-free (built-ins, exec verbs, question card, generic MCP card, generic `EditDiffRenderer`);+ the widgets carry no `scenes/max` import, so the grep gate below stays green. Max's frozen LangGraph path+ is a _consumer_: it composes `VisualizationWidget` / `RecordingsWidget` / `ErrorTrackingFiltersWidget`+ through `api/primitives`.- If Max needs something the surface doesn't express generically, **lift it to a generic prop/selector here- and have Max adapt** — never special-case Max in this directory. Enforced by a grep gate:- `grep -rE "scenes/max|maxThreadLogic|MaxUIContext" products/posthog_ai/frontend` must be empty.+ and have Max adapt** — never special-case Max in this directory. (The recordings "accept these filters"+ bar is one such lift: `RecordingsWidget` takes an optional `onAcceptFilters` prop; Max's LangGraph path+ passes its `onAcceptSessionFilters` selector, the sandbox path passes nothing.) Enforced by a grep gate:+ `grep -rE "scenes/max|maxThreadLogic|MaxUIContext" products/posthog_ai/frontend` must be empty of imports.## 3. Streaming architecture (`logics/runStreamLogic.ts`)@@ -167,6 +171,7 @@ components/ # RunSurfaceImpl (the RunSurface compound, heavy chunk); Rea# RunLogSkeleton (shared loader), Thread, Composer, perm/question/resource surfaces, activity, tool/composer/ # the Composer compoundtool/ # tool registry + renderers (built-ins, generic MCP, EditDiffRenderer, diff/exec utils)+ widgets/ # PostHog product data-tool widgets (insight/dashboard/recordings/error-tracking/notebook/query) + registerDataToolRendererslogics/ # runStreamLogic, runInteractionLogic; tasksLogic/taskLogic data logics (+ *LogicType.ts)policy/ # tool policy + permission/question utilstypes/ # streamTypes (folded thread), wireTypes (ACP), toolTypes, taskTypes (task/run domain)diff --git a/products/posthog_ai/frontend/README.md b/products/posthog_ai/frontend/README.mdindex d8a056847ab8..7ab398788ef2 100644--- a/products/posthog_ai/frontend/README.md+++ b/products/posthog_ai/frontend/README.md@@ -166,8 +166,9 @@ registerToolRenderers([])```-This is the generic per-product mechanism. Max is its first consumer-(`scenes/max/messages/adapters/registerMaxToolRenderers`), not a special case.+This is the generic per-product mechanism. The surface itself is its first consumer: the PostHog product+data-tool widgets live in `components/tool/widgets/` and self-register via `widgets/registerDataToolRenderers`+(side-effect-imported by `ToolCallCard`), so every surface that renders a tool card gets them.### Headless status badge / automationdiff --git a/products/posthog_ai/frontend/api/primitives.ts b/products/posthog_ai/frontend/api/primitives.tsindex 60813dff43fd..bfe9c5d250fd 100644--- a/products/posthog_ai/frontend/api/primitives.ts+++ b/products/posthog_ai/frontend/api/primitives.ts@@ -75,3 +75,11 @@ export { ContextUsageBar } from '../components/ContextUsageBar'export { QuestionField, MultiFieldQuestion, isFieldValid } from '../components/QuestionField'export { OptionSelector } from '../components/OptionSelector'export type { Option } from '../components/OptionSelector'++// Product data-tool widgets — the atomic PostHog-entity renderers Max's LangGraph path composes directly+// (the sandbox path reaches them through the tool registry, not these exports).+export { VisualizationWidget, getArtifactOpenTarget } from '../components/tool/widgets/VisualizationWidget'+export type { VisualizationWidgetProps } from '../components/tool/widgets/VisualizationWidget'+export { RecordingsWidget } from '../components/tool/widgets/RecordingsWidget'+export { ErrorTrackingFiltersWidget } from '../components/tool/widgets/ErrorTrackingFiltersWidget'+export { ErrorTrackingIssueCard } from '../components/tool/widgets/ErrorTrackingIssueCard'diff --git a/products/posthog_ai/frontend/components/tool/DataToolRow.tsx b/products/posthog_ai/frontend/components/tool/DataToolRow.tsxindex 0a93bdc92c34..0b05a4f21dee 100644--- a/products/posthog_ai/frontend/components/tool/DataToolRow.tsx+++ b/products/posthog_ai/frontend/components/tool/DataToolRow.tsx@@ -1,22 +1,27 @@import { type PropsWithChildren } from 'react'+import { getMcpToolPresentation } from './GenericMcpToolRenderer'import { ToolActivity } from './ToolActivity'import type { ToolRendererProps } from './toolRegistry'/*** 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.+ * notebook). Renders the same header/accordion as the generic MCP card — `Call <tool>` title,+ * compact input preview, expandable input/output body — with the adapter's visualization as+ * always-visible content below it (via the Activity bridge), while each adapter keeps its own+ * lazy chunk.*/export function DataToolRow({ children, ...props }: PropsWithChildren<ToolRendererProps>): JSX.Element {const { message, icon, displayName, turnComplete, turnCancelled } = props+ const { title, subtitle, body } = getMcpToolPresentation(message, displayName)return (<ToolActivitymessage={message}icon={icon}- title={message.title || displayName || 'Tool'}+ title={title}+ subtitle={subtitle}+ body={body}turnComplete={turnComplete}turnCancelled={turnCancelled}>diff --git a/products/posthog_ai/frontend/components/tool/GenericMcpToolRenderer.tsx b/products/posthog_ai/frontend/components/tool/GenericMcpToolRenderer.tsxindex 576c35b48675..90d22cc18871 100644--- a/products/posthog_ai/frontend/components/tool/GenericMcpToolRenderer.tsx+++ b/products/posthog_ai/frontend/components/tool/GenericMcpToolRenderer.tsx@@ -7,16 +7,24 @@ import { compactInput, formatInput, getContentText, stripCodeFences } from './toimport { ToolBody, ToolBodySection, ToolOutput } from './ToolOutput'import type { ToolRendererProps } from './toolRegistry'+export interface McpToolPresentation {+ title: string+ /** Compact mono input preview for the header's second line. */+ subtitle: JSX.Element | undefined+ /** Collapsible input/output accordion body. */+ body: JSX.Element | undefined+}+/**- * 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`.+ * The shared MCP tool-card presentation: PostHog `exec` inner tools read `Call <tool>`; other MCP+ * tools read `Call <server> – <tool> (MCP)`; non-MCP built-ins show their friendly title. The+ * subtitle is a compact input preview and the body shows the full input plus any text output.+ * Used by the generic card and by `DataToolRow`, so data-tool widgets keep the same header/accordion.*/-export const GenericMcpToolRenderer = memo(function GenericMcpToolRenderer(props: ToolRendererProps): JSX.Element {- const { message, icon, displayName, turnComplete, turnCancelled } = props-+export function getMcpToolPresentation(+ message: ToolRendererProps['message'],+ displayName?: string+): McpToolPresentation {const isPostHogExec = !!message.innerToolNameconst isMcp =isPostHogExec || (!!message.rawServerName && !!message.rawToolName && message.rawServerName !== 'claude')@@ -36,7 +44,6 @@ export const GenericMcpToolRenderer = memo(function GenericMcpToolRenderer(props? `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 ? (@@ -50,12 +57,28 @@ export const GenericMcpToolRenderer = memo(function GenericMcpToolRenderer(props</ToolBody>) : undefined+ return {+ title,+ subtitle: preview ? <span className="font-mono">{preview}</span> : undefined,+ body,+ }+}++/**+ * The catch-all tool card — user-installed MCP tools, unmapped PostHog `exec` inner tools, and Claude+ * built-ins without a bespoke renderer. Renders the shared MCP presentation with no always-visible+ * content. Replaces the old `FallbackMcpToolRenderer`.+ */+export const GenericMcpToolRenderer = memo(function GenericMcpToolRenderer(props: ToolRendererProps): JSX.Element {+ const { message, icon, displayName, turnComplete, turnCancelled } = props+ const { title, subtitle, body } = getMcpToolPresentation(message, displayName)+return (<ToolActivitymessage={message}icon={icon ?? <IconWrench />}title={title}- subtitle={preview ? <span className="font-mono">{preview}</span> : undefined}+ subtitle={subtitle}body={body}turnComplete={turnComplete}turnCancelled={turnCancelled}diff --git a/products/posthog_ai/frontend/components/tool/ToolCallCard.tsx b/products/posthog_ai/frontend/components/tool/ToolCallCard.tsxindex 9d778373ce0d..1e443dc1ac75 100644--- a/products/posthog_ai/frontend/components/tool/ToolCallCard.tsx+++ b/products/posthog_ai/frontend/components/tool/ToolCallCard.tsx@@ -1,3 +1,8 @@+// Side-effect: registers the surface's product data-tool renderers (insight/dashboard/recordings/etc.)+// into the shared toolRegistry. Placed at the render chokepoint so every surface that renders a tool+// card (the /tasks runner, the signals inbox, Max's sandbox path) resolves those widgets.+import './widgets/registerDataToolRenderers'+import { Suspense, memo } from 'react'import type { ToolCallMessage } from 'products/posthog_ai/frontend/types/toolTypes'@@ -22,7 +27,9 @@ export const ToolCallCard = memo(function ToolCallCard({turnComplete,turnCancelled,}: ToolCallCardProps): JSX.Element {- const entry = lookupToolRenderer(message.resolvedKey)+ // `innerToolName` is set only when `resolveToolKey` parsed this key out of a trusted PostHog exec+ // command, so it doubles as the "first-party origin" signal that gates the product-widget entries.+ const entry = lookupToolRenderer(message.resolvedKey, message.innerToolName != null)return (<Suspense fallback={<ToolCardSkeleton icon={entry.icon} displayName={entry.displayName} />}><entry.Rendererdiff --git a/products/posthog_ai/frontend/components/tool/posthogCodeToolRenderers.test.tsx b/products/posthog_ai/frontend/components/tool/posthogCodeToolRenderers.test.tsxindex 0e9b5fd3e392..21b5abb11f34 100644--- a/products/posthog_ai/frontend/components/tool/posthogCodeToolRenderers.test.tsx+++ b/products/posthog_ai/frontend/components/tool/posthogCodeToolRenderers.test.tsx@@ -157,6 +157,9 @@ describe('posthog-code tool renderers', () => {])('resolves the %s key shape to the signed-commit renderer', (_label, toolCall, expectedKey) => {const resolved = resolveToolCall(toolCall)expect(resolved.resolvedKey).toEqual(expectedKey)- expect(lookupToolRenderer(resolved.resolvedKey).displayName).toEqual('Signed commits')+ // The posthog-code git tools aren't origin-gated, so they resolve for a non-exec call too.+ expect(lookupToolRenderer(resolved.resolvedKey, resolved.innerToolName != null).displayName).toEqual(+ 'Signed commits'+ )})})diff --git a/products/posthog_ai/frontend/components/tool/toolRegistry.test.tsx b/products/posthog_ai/frontend/components/tool/toolRegistry.test.tsxindex bc00458934a0..e2801328762d 100644--- a/products/posthog_ai/frontend/components/tool/toolRegistry.test.tsx+++ b/products/posthog_ai/frontend/components/tool/toolRegistry.test.tsx@@ -21,10 +21,10 @@ function makeMessage(overrides: Partial<ToolCallMessage> = {}): ToolCallMessage}describe('toolRegistry', () => {- // Product-specific data-tool renderers (insight/dashboard/recordings/error-tracking/query/notebook)- // are NOT registered by this shared registry — they're contributed by scenes/max via- // `registerMaxToolRenderers` and covered by that module's own test. Here we assert only what the- // shared, Max-free registry registers: built-ins, exec verbs, the question card, and the fallback.+ // The base registry module registers only built-ins, exec verbs, the question card, and the fallback.+ // The PostHog product data-tools self-register via `widgets/registerDataToolRenderers`, which+ // `ToolCallCard` side-effect-imports — and this file imports `ToolCallCard`, so those keys resolve here+ // too. Genuinely unmapped keys still fall through to the wrench card.it('bulk-registers every entry it is handed', () => {const Renderer = (() => null) as unknown as ToolRegistryEntry['Renderer']@@ -37,21 +37,39 @@ describe('toolRegistry', () => {expect(toolRegistry.lookup('__test_beta__')?.displayName).toEqual('Beta')})- it('leaves product-specific and unknown tool names unregistered, resolving to the key as displayName', () => {+ it('resolves product data-tools because importing ToolCallCard self-registers them', () => {+ // Guards the fix: if the `registerDataToolRenderers` side-effect import is dropped from ToolCallCard,+ // these keys fall through to the generic JSON card instead of their widgets.+ expect(toolRegistry.lookup('insight-create')?.displayName).toEqual('Insight')+ expect(toolRegistry.lookup('query-trends')?.displayName).toEqual('Trends query')+ })++ it('falls back to the key as displayName for unknown and unmapped tool names', () => {expect(toolRegistry.lookup('mcp__user-installed__something')).toBeNull()// The synthesized fallback uses the resolved key as its displayName.- expect(lookupToolRenderer('mcp__user-installed__something').displayName).toEqual(+ expect(lookupToolRenderer('mcp__user-installed__something', false).displayName).toEqual('mcp__user-installed__something')- expect(lookupToolRenderer('experiment-create').displayName).toEqual('experiment-create')- // Product adapters live in scenes/max now, so the bare registry resolves them to the fallback.- expect(toolRegistry.lookup('insight-create')).toBeNull()- expect(toolRegistry.lookup('query-trends')).toBeNull()+ expect(lookupToolRenderer('experiment-create', false).displayName).toEqual('experiment-create')+ // Never-registered keys (not built-ins, not any product data-tool) resolve to the fallback.expect(toolRegistry.lookup('insight-query')).toBeNull()expect(toolRegistry.lookup('read_insight')).toBeNull()expect(toolRegistry.lookup('query-llm-trace')).toBeNull()})+ // A user-installed MCP server can expose a tool whose bare name collides with a product-widget key+ // (e.g. "notebooks-create") and return an arbitrary `_posthogUrl`. Such a call is NOT from the+ // trusted single-exec PostHog server (no inner tool name was parsed, so `fromPostHogExec` is false),+ // and must fall through to the generic card rather than spoofing a first-party Notebook/Dashboard card.+ it.each([+ ['notebooks-create', 'Notebook'],+ ['dashboard-create', 'Dashboard'],+ ['query-trends', 'Trends query'],+ ])('gates product widget %s on a trusted PostHog-exec origin', (key, displayName) => {+ expect(lookupToolRenderer(key, false).displayName).toEqual(key)+ expect(lookupToolRenderer(key, true).displayName).toEqual(displayName)+ })+// 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][] = [@@ -83,7 +101,7 @@ describe('toolRegistry', () => {const entry = toolRegistry.lookup(key)expect(entry).not.toBeNull()expect(entry?.displayName).toEqual(displayName)- expect(lookupToolRenderer(key).displayName).toEqual(displayName)+ expect(lookupToolRenderer(key, false).displayName).toEqual(displayName)})// PostHog single-exec discovery verbs are keyed by their sentinel key (from `resolveToolKey`); the@@ -100,12 +118,12 @@ describe('toolRegistry', () => {const entry = toolRegistry.lookup(key)expect(entry).not.toBeNull()expect(entry?.displayName).toEqual(displayName)- expect(lookupToolRenderer(key).displayName).toEqual(displayName)+ expect(lookupToolRenderer(key, false).displayName).toEqual(displayName)})it('falls back to the wrench card (key as displayName) for an unmapped built-in-looking name', () => {expect(toolRegistry.lookup('NotARealTool')).toBeNull()- expect(lookupToolRenderer('NotARealTool').displayName).toEqual('NotARealTool')+ expect(lookupToolRenderer('NotARealTool', false).displayName).toEqual('NotARealTool')})// Render-level: ToolCallCard resolves the entry, loads the lazy renderer behind a Suspensediff --git a/products/posthog_ai/frontend/components/tool/toolRegistry.tsx b/products/posthog_ai/frontend/components/tool/toolRegistry.tsxindex cca1fd30b82e..f88a7db227e0 100644--- a/products/posthog_ai/frontend/components/tool/toolRegistry.tsx+++ b/products/posthog_ai/frontend/components/tool/toolRegistry.tsx@@ -53,6 +53,16 @@ export interface ToolRegistryEntry {displayName: stringicon: JSX.ElementRenderer: ToolRendererComponent+ /**+ * When set, this entry only matches a call that came through the trusted single-exec PostHog+ * server — one whose inner tool name we parsed out of the exec command. The product data-tool+ * widgets set it: a user-installed MCP server can expose a tool whose bare name collides with a+ * widget key (e.g. "notebooks-create" or "dashboard-create") and return the expected fields with+ * an arbitrary `_posthogUrl`. Without this gate that result would render as a first-party Notebook+ * or Dashboard card whose Open button points at the attacker's site. Untrusted callers fall+ * through to the generic MCP card instead.+ */+ requiresPostHogOrigin?: boolean}export interface ToolRegistry {@@ -98,8 +108,8 @@ export const toolRegistry: ToolRegistry = new MapBackedRegistry()/*** Bulk-register tool renderers into the shared registry. The generic per-product seam: a product- * registers its tool cards from its own scene's entrypoint (as Max does via `registerMaxToolRenderers`).- * `toolRegistry.register` stays available for single-entry use.+ * registers its tool cards from its own entrypoint (the surface itself does this for the PostHog data+ * tools via `widgets/registerDataToolRenderers`). `toolRegistry.register` stays available for single-entry use.*/export function registerToolRenderers(entries: ToolRegistryEntry[]): void {for (const entry of entries) {@@ -108,9 +118,9 @@ export function registerToolRenderers(entries: ToolRegistryEntry[]): void {}// Product-specific data-tool renderers (insight, dashboard, session recordings, error tracking,-// notebooks, query wrappers) are NOT registered here — they live in scenes/max and register themselves-// into this registry via `registerMaxToolRenderers` so this surface stays free of any scenes/max import.-// Surfaces without those adapters (tasks, signals inbox) fall through to the generic MCP card.+// notebooks, query wrappers) are NOT registered in this module — that keeps the base registry a light+// string+lazy side effect. They live in `./widgets` and self-register via `registerDataToolRenderers`,+// which `ToolCallCard` side-effect-imports, so every surface that renders a tool card gets them.// --- Claude built-in tools ---// Keyed by the stable SDK tool name (reachable via `_meta.claudeCode.toolName`). Bash/Read/Search/Web@@ -189,14 +199,22 @@ toolRegistry.register({Renderer: QuestionRenderer,})-/** Looks up the renderer entry for a resolved tool key, falling back to the generic built-in card. */-export function lookupToolRenderer(resolvedKey: string): ToolRegistryEntry {- return (- toolRegistry.lookup(resolvedKey) ?? {- key: resolvedKey,- displayName: resolvedKey,- icon: <IconWrench />,- Renderer: BuiltinToolRenderer,- }- )+/**+ * Looks up the renderer entry for a resolved tool key, falling back to the generic built-in card.+ * `fromPostHogExec` is whether the call came through the trusted single-exec PostHog server (its inner+ * tool name was parsed out of the exec command). An entry marked `requiresPostHogOrigin` only matches a+ * trusted call, so a third-party tool whose bare name collides with a product-widget key can't spoof a+ * first-party card — it falls through to the generic card here.+ */+export function lookupToolRenderer(resolvedKey: string, fromPostHogExec: boolean): ToolRegistryEntry {+ const entry = toolRegistry.lookup(resolvedKey)+ if (entry && (!entry.requiresPostHogOrigin || fromPostHogExec)) {+ return entry+ }+ return {+ key: resolvedKey,+ displayName: resolvedKey,+ icon: <IconWrench />,+ Renderer: BuiltinToolRenderer,+ }}diff --git a/frontend/src/scenes/max/messages/adapters/CreateInsightWidget.tsx b/products/posthog_ai/frontend/components/tool/widgets/CreateInsightWidget.tsxsimilarity index 64%rename from frontend/src/scenes/max/messages/adapters/CreateInsightWidget.tsxrename to products/posthog_ai/frontend/components/tool/widgets/CreateInsightWidget.tsxindex 3174d6bb53c1..6a2b8056e936 100644--- a/frontend/src/scenes/max/messages/adapters/CreateInsightWidget.tsx+++ b/products/posthog_ai/frontend/components/tool/widgets/CreateInsightWidget.tsx@@ -1,7 +1,8 @@-import { GenericMcpToolRenderer, DataToolRow, type ToolRendererProps } from 'products/posthog_ai/frontend/api/tools'--import { VisualizationWidget, getArtifactOpenTarget } from '../VisualizationWidget'+import { DataToolRow } from '../DataToolRow'+import { GenericMcpToolRenderer } from '../GenericMcpToolRenderer'+import type { ToolRendererProps } from '../toolRegistry'import { extractVisualizationArtifact } from './extractors'+import { VisualizationWidget, getArtifactOpenTarget } from './VisualizationWidget'/*** Renders insight create / update / read tool calls through `VisualizationWidget`. Until the@@ -20,12 +21,7 @@ export function CreateInsightWidget(props: ToolRendererProps): JSX.Element {return (<DataToolRow {...props}>- <VisualizationWidget- content={artifact.content}- openUrl={target.url}- openTooltip={target.tooltip}- embedded- />+ <VisualizationWidget content={artifact.content} openUrl={target.url} openTooltip={target.tooltip} /></DataToolRow>)}diff --git a/frontend/src/scenes/max/messages/adapters/CreateNotebookWidget.test.tsx b/products/posthog_ai/frontend/components/tool/widgets/CreateNotebookWidget.test.tsxsimilarity index 79%rename from frontend/src/scenes/max/messages/adapters/CreateNotebookWidget.test.tsxrename to products/posthog_ai/frontend/components/tool/widgets/CreateNotebookWidget.test.tsxindex cddbffa28be5..70925c898b84 100644--- a/frontend/src/scenes/max/messages/adapters/CreateNotebookWidget.test.tsx+++ b/products/posthog_ai/frontend/components/tool/widgets/CreateNotebookWidget.test.tsx@@ -1,10 +1,10 @@-// Side-effect: Max registers its product tool renderers (incl. the notebook keys) into the shared-// registry. The bare registry no longer knows product keys, so the resolution assertions below need it.-import './registerMaxToolRenderers'+// Side-effect: registers the surface's product data-tool renderers (incl. the notebook keys) into the+// shared registry. The bare registry no longer knows product keys, so the resolution assertions below need it.+import './registerDataToolRenderers'import { lookupToolRenderer, toolRegistry } from 'products/posthog_ai/frontend/api/tools'+import type { ToolCallMessage } from 'products/posthog_ai/frontend/types/toolTypes'-import type { ToolCallMessage } from '../../maxTypes'import { extractNotebook } from './CreateNotebookWidget'function toolMessage(rawOutput: unknown, innerInput?: Record<string, unknown>): ToolCallMessage {@@ -26,12 +26,13 @@ describe('CreateNotebookWidget', () => {'resolves %s to the notebook widget',(key) => {expect(toolRegistry.lookup(key)?.displayName).toBe('Notebook')- expect(lookupToolRenderer(key).displayName).toBe('Notebook')+ // The notebook widget is gated on a trusted PostHog-exec origin, so pass `fromPostHogExec`.+ expect(lookupToolRenderer(key, true).displayName).toBe('Notebook')})it('falls back to the generic renderer for an unknown inner tool key', () => {- expect(lookupToolRenderer('some-unwired-tool').displayName).not.toBe('Notebook')+ expect(lookupToolRenderer('some-unwired-tool', true).displayName).not.toBe('Notebook')})describe('extractNotebook', () => {diff --git a/frontend/src/scenes/max/messages/adapters/CreateNotebookWidget.tsx b/products/posthog_ai/frontend/components/tool/widgets/CreateNotebookWidget.tsxsimilarity index 68%rename from frontend/src/scenes/max/messages/adapters/CreateNotebookWidget.tsxrename to products/posthog_ai/frontend/components/tool/widgets/CreateNotebookWidget.tsxindex 5c4e5fa27100..bdec40b7cb8f 100644--- a/frontend/src/scenes/max/messages/adapters/CreateNotebookWidget.tsx+++ b/products/posthog_ai/frontend/components/tool/widgets/CreateNotebookWidget.tsx@@ -4,7 +4,10 @@ import { LemonButton } from '@posthog/lemon-ui'import { IconOpenInNew } from 'lib/lemon-ui/icons'import { urls } from 'scenes/urls'-import { GenericMcpToolRenderer, DataToolRow, type ToolRendererProps } from 'products/posthog_ai/frontend/api/tools'+import { MessageTemplate } from '../../../messages/MessageTemplate'+import { DataToolRow } from '../DataToolRow'+import { GenericMcpToolRenderer } from '../GenericMcpToolRenderer'+import type { ToolRendererProps } from '../toolRegistry'/** The notebook fields the widget renders, pulled from the REST payload. */export interface NotebookExtraction {@@ -54,21 +57,23 @@ export function CreateNotebookWidget(props: ToolRendererProps): JSX.Element {return (<DataToolRow {...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>+ <MessageTemplate type="ai" wrapperClassName="w-full">+ <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>- <LemonButton- to={notebook.url ?? urls.notebook(notebook.shortId)}- targetBlank- icon={<IconOpenInNew />}- size="xsmall"- tooltip="Open notebook"- >- Open notebook- </LemonButton>- </div>+ </MessageTemplate></DataToolRow>)}diff --git a/frontend/src/scenes/max/messages/ErrorTrackingFiltersSummary.tsx b/products/posthog_ai/frontend/components/tool/widgets/ErrorTrackingFiltersSummary.tsxsimilarity index 100%rename from frontend/src/scenes/max/messages/ErrorTrackingFiltersSummary.tsxrename to products/posthog_ai/frontend/components/tool/widgets/ErrorTrackingFiltersSummary.tsxdiff --git a/products/posthog_ai/frontend/components/tool/widgets/ErrorTrackingFiltersWidget.tsx b/products/posthog_ai/frontend/components/tool/widgets/ErrorTrackingFiltersWidget.tsxnew file mode 100644index 000000000000..f5ecaf4faa2b--- /dev/null+++ b/products/posthog_ai/frontend/components/tool/widgets/ErrorTrackingFiltersWidget.tsx@@ -0,0 +1,188 @@+import { BindLogic, useActions, useValues } from 'kea'+import { useEffect } from 'react'++import { LemonButton } from '@posthog/lemon-ui'++import { EmptyMessage } from 'lib/components/EmptyMessage/EmptyMessage'+import { IconOpenInNew } from 'lib/lemon-ui/icons'+import { sceneLogic } from 'scenes/sceneLogic'+import { Scene } from 'scenes/sceneTypes'+import { urls } from 'scenes/urls'++import {+ MaxErrorTrackingIssuePreview,+ MaxErrorTrackingSearchResponse,+} from '~/queries/schema/schema-assistant-error-tracking'++import { issueFiltersLogic } from 'products/error_tracking/frontend/components/IssueFilters/issueFiltersLogic'+import {+ ErrorTrackingQueryOrderBy,+ ErrorTrackingQueryOrderDirection,+ ErrorTrackingQueryStatus,+ issueQueryOptionsLogic,+} from 'products/error_tracking/frontend/components/IssueQueryOptions/issueQueryOptionsLogic'+import { ERROR_TRACKING_SCENE_LOGIC_KEY } from 'products/error_tracking/frontend/scenes/ErrorTrackingScene/errorTrackingSceneLogic'++import { MessageTemplate } from '../../../messages/MessageTemplate'+import { ErrorTrackingFiltersSummary } from './ErrorTrackingFiltersSummary'+import { ErrorTrackingIssueCard } from './ErrorTrackingIssueCard'+import { MaxErrorTrackingWidgetLogicProps, maxErrorTrackingWidgetLogic } from './maxErrorTrackingWidgetLogic'++export function ErrorTrackingFiltersWidget({+ toolCallId,+ filters,+ embedded = false,+}: {+ toolCallId: string+ filters: 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">+ {emptyState}+ </MessageTemplate>+ )+ }++ return (+ <BindLogic logic={maxErrorTrackingWidgetLogic} props={logicProps}>+ <ErrorTrackingFiltersWidgetContent filters={filters} embedded={embedded} />+ </BindLogic>+ )+}++function ErrorTrackingFiltersWidgetContent({+ filters,+ embedded,+}: {+ filters: MaxErrorTrackingSearchResponse+ embedded: boolean+}): JSX.Element {+ const { activeSceneId } = useValues(sceneLogic)+ const isOnErrorTrackingPage = activeSceneId === Scene.ErrorTracking++ const { issues, hasMore, isLoading } = useValues(maxErrorTrackingWidgetLogic)+ const { loadMoreIssues } = useActions(maxErrorTrackingWidgetLogic)++ const filtersLogic = issueFiltersLogic({ logicKey: ERROR_TRACKING_SCENE_LOGIC_KEY })+ const queryOptionsLogic = issueQueryOptionsLogic({ logicKey: ERROR_TRACKING_SCENE_LOGIC_KEY })++ const { setDateRange, setSearchQuery } = useActions(filtersLogic)+ const { setStatus, setOrderBy, setOrderDirection } = useActions(queryOptionsLogic)++ // Automatically apply filters when on the Error Tracking page+ useEffect(() => {+ if (isOnErrorTrackingPage) {+ if (filters.date_from || filters.date_to) {+ setDateRange({ date_from: filters.date_from ?? null, date_to: filters.date_to ?? null })+ }+ if (filters.search_query) {+ setSearchQuery(filters.search_query)+ }+ if (filters.status) {+ setStatus(filters.status as ErrorTrackingQueryStatus)+ }+ if (filters.order_by) {+ setOrderBy(filters.order_by as ErrorTrackingQueryOrderBy)+ }+ if (filters.order_direction) {+ setOrderDirection(filters.order_direction as ErrorTrackingQueryOrderDirection)+ }+ }+ }, [+ isOnErrorTrackingPage,+ setOrderDirection,+ filters.search_query,+ filters.order_direction,+ setOrderBy,+ filters.date_from,+ filters.order_by,+ filters.status,+ setSearchQuery,+ setStatus,+ filters.date_to,+ setDateRange,+ ])++ const buildErrorTrackingUrl = (): string => {+ const params = new URLSearchParams()+ if (filters.status) {+ params.set('status', filters.status)+ }+ if (filters.search_query) {+ params.set('searchQuery', filters.search_query)+ }+ if (filters.date_from) {+ params.set('dateFrom', filters.date_from)+ }+ if (filters.date_to) {+ params.set('dateTo', filters.date_to)+ }+ const query = params.toString()+ return urls.errorTracking() + (query ? `?${query}` : '')+ }++ const hasIssues = issues.length > 0+ const errorTrackingUrl = buildErrorTrackingUrl()++ 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>+ <LemonButton+ to={errorTrackingUrl}+ icon={<IconOpenInNew />}+ size="xsmall"+ tooltip="Open in Error tracking"+ />+ </div>+ )}+ <ErrorTrackingFiltersSummary filters={filters} />+ <div className="border-t">+ {hasIssues ? (+ <div className="*:not-first:border-t max-h-80 overflow-y-auto">+ {issues.map((issue: MaxErrorTrackingIssuePreview) => (+ <ErrorTrackingIssueCard key={issue.id} issue={issue} />+ ))}+ </div>+ ) : (+ <div className="py-2">+ <EmptyMessage title="No issues found" description="No issues match the specified filters" />+ </div>+ )}+ {hasMore && (+ <div className="flex justify-center p-2 border-t">+ <LemonButton type="tertiary" size="xsmall" onClick={() => loadMoreIssues()} loading={isLoading}>+ Load more issues+ </LemonButton>+ </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/ErrorTrackingIssueCard.tsx b/products/posthog_ai/frontend/components/tool/widgets/ErrorTrackingIssueCard.tsxsimilarity index 100%rename from frontend/src/scenes/max/messages/ErrorTrackingIssueCard.tsxrename to products/posthog_ai/frontend/components/tool/widgets/ErrorTrackingIssueCard.tsxdiff --git a/frontend/src/scenes/max/messages/adapters/ErrorTrackingWidget.tsx b/products/posthog_ai/frontend/components/tool/widgets/ErrorTrackingWidget.tsxsimilarity index 75%rename from frontend/src/scenes/max/messages/adapters/ErrorTrackingWidget.tsxrename to products/posthog_ai/frontend/components/tool/widgets/ErrorTrackingWidget.tsxindex a43ab5f69645..7ebfda1e30c3 100644--- a/frontend/src/scenes/max/messages/adapters/ErrorTrackingWidget.tsx+++ b/products/posthog_ai/frontend/components/tool/widgets/ErrorTrackingWidget.tsx@@ -1,6 +1,7 @@-import { GenericMcpToolRenderer, DataToolRow, type ToolRendererProps } from 'products/posthog_ai/frontend/api/tools'--import { ErrorTrackingFiltersWidget } from '../UIPayloadAnswer'+import { DataToolRow } from '../DataToolRow'+import { GenericMcpToolRenderer } from '../GenericMcpToolRenderer'+import type { ToolRendererProps } from '../toolRegistry'+import { ErrorTrackingFiltersWidget } from './ErrorTrackingFiltersWidget'import { extractErrorTrackingResponse } from './extractors'/**@@ -19,7 +20,7 @@ export function ErrorTrackingWidget(props: ToolRendererProps): JSX.Element {return (<DataToolRow {...props}>- <ErrorTrackingFiltersWidget toolCallId={message.id} filters={filters} embedded />+ <ErrorTrackingFiltersWidget toolCallId={message.id} filters={filters} /></DataToolRow>)}diff --git a/frontend/src/scenes/max/messages/adapters/QueryWidget.tsx b/products/posthog_ai/frontend/components/tool/widgets/QueryWidget.tsxsimilarity index 53%rename from frontend/src/scenes/max/messages/adapters/QueryWidget.tsxrename to products/posthog_ai/frontend/components/tool/widgets/QueryWidget.tsxindex 15f04c024c25..e1178e048a28 100644--- a/frontend/src/scenes/max/messages/adapters/QueryWidget.tsx+++ b/products/posthog_ai/frontend/components/tool/widgets/QueryWidget.tsx@@ -1,7 +1,8 @@-import { GenericMcpToolRenderer, DataToolRow, type ToolRendererProps } from 'products/posthog_ai/frontend/api/tools'--import { VisualizationWidget } from '../VisualizationWidget'+import { DataToolRow } from '../DataToolRow'+import { GenericMcpToolRenderer } from '../GenericMcpToolRenderer'+import type { ToolRendererProps } from '../toolRegistry'import { extractQueryResult } from './extractors'+import { VisualizationWidget, getQueryOpenTarget } from './VisualizationWidget'/*** Renders the MCP query-wrapper tools (query-trends, query-funnel, ...) through@@ -16,9 +17,13 @@ export function QueryWidget(props: ToolRendererProps): JSX.Element {return <GenericMcpToolRenderer {...props} />}+ // Not every wrapper output carries the MCP server's `_posthogUrl` enrichment — fall back to+ // opening the rendered query as a new unsaved insight, like the artifact path does.+ const target = result.url ? { url: result.url, tooltip: 'Open as insight' } : getQueryOpenTarget(result.content)+return (<DataToolRow {...props}>- <VisualizationWidget content={result.content} openUrl={result.url} openTooltip="Open as insight" embedded />+ <VisualizationWidget content={result.content} openUrl={target.url} openTooltip={target.tooltip} /></DataToolRow>)}diff --git a/frontend/src/scenes/max/messages/RecordingsFiltersSummary.tsx b/products/posthog_ai/frontend/components/tool/widgets/RecordingsFiltersSummary.tsxsimilarity index 100%rename from frontend/src/scenes/max/messages/RecordingsFiltersSummary.tsxrename to products/posthog_ai/frontend/components/tool/widgets/RecordingsFiltersSummary.tsxdiff --git a/products/posthog_ai/frontend/components/tool/widgets/RecordingsWidget.tsx b/products/posthog_ai/frontend/components/tool/widgets/RecordingsWidget.tsxnew file mode 100644index 000000000000..b19a404b530b--- /dev/null+++ b/products/posthog_ai/frontend/components/tool/widgets/RecordingsWidget.tsx@@ -0,0 +1,122 @@+import { BindLogic, useActions, useValues } from 'kea'++import { IconCheck } from '@posthog/icons'+import { LemonButton, Spinner } from '@posthog/lemon-ui'++import { EmptyMessage } from 'lib/components/EmptyMessage/EmptyMessage'+import { sessionPlayerModalLogic } from 'scenes/session-recordings/player/modal/sessionPlayerModalLogic'+import { SessionRecordingPreview } from 'scenes/session-recordings/playlist/SessionRecordingPreview'+import {+ SessionRecordingPlaylistLogicProps,+ sessionRecordingsPlaylistLogic,+} from 'scenes/session-recordings/playlist/sessionRecordingsPlaylistLogic'++import { RecordingUniversalFilters } from '~/types'++import { MessageTemplate } from '../../../messages/MessageTemplate'+import { RecordingsFiltersSummary } from './RecordingsFiltersSummary'++export function RecordingsWidget({+ toolCallId,+ filters,+ embedded = false,+ onAcceptFilters,+}: {+ toolCallId: string+ filters: RecordingUniversalFilters+ embedded?: boolean+ /** When provided, renders an "accept these filters" bar under the list. Consumer-specific. */+ onAcceptFilters?: ((filters: RecordingUniversalFilters) => void) | null+}): JSX.Element {+ const logicProps: SessionRecordingPlaylistLogicProps = {+ logicKey: `ai-recordings-widget-${toolCallId}`,+ filters,+ updateSearchParams: false,+ autoPlay: false,+ }+ const content = (+ <>+ <RecordingsFiltersSummary filters={filters} />+ <RecordingsListContent />+ {onAcceptFilters && <AcceptFiltersBar filters={filters} onAccept={onAcceptFilters} />}+ </>+ )++ return (+ <BindLogic logic={sessionRecordingsPlaylistLogic} props={logicProps}>+ {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>+ )+}++function AcceptFiltersBar({+ filters,+ onAccept,+}: {+ filters: RecordingUniversalFilters+ onAccept: (filters: RecordingUniversalFilters) => void+}): JSX.Element {+ return (+ <div className="border-t px-3 py-2 flex items-center justify-end">+ <LemonButton type="primary" size="small" icon={<IconCheck />} onClick={() => onAccept(filters)}>+ Use these filters for session analysis+ </LemonButton>+ </div>+ )+}++function RecordingsListContent(): JSX.Element {+ const { otherRecordings, sessionRecordingsResponseLoading, hasNext } = useValues(sessionRecordingsPlaylistLogic)+ const { maybeLoadSessionRecordings } = useActions(sessionRecordingsPlaylistLogic)+ const { openSessionPlayer } = useActions(sessionPlayerModalLogic())++ const hasRecordings = otherRecordings.length > 0++ return (+ <div className="border-t *:not-first:border-t max-h-80 overflow-y-auto">+ {sessionRecordingsResponseLoading && !hasRecordings ? (+ <div className="flex items-center justify-center gap-2 py-12 text-muted">+ <Spinner textColored />+ <span>Loading recordings...</span>+ </div>+ ) : !hasRecordings ? (+ <div className="py-2">+ <EmptyMessage title="No recordings found" description="No recordings match the specified filters" />+ </div>+ ) : (+ <>+ {otherRecordings.map((recording) => (+ <div+ key={recording.id}+ onClick={(e) => {+ e.preventDefault()+ openSessionPlayer(recording)+ }}+ >+ <SessionRecordingPreview recording={recording} selectable={false} />+ </div>+ ))}+ {hasNext && (+ <div className="p-2">+ <LemonButton+ fullWidth+ type="secondary"+ size="small"+ onClick={() => maybeLoadSessionRecordings('older')}+ loading={sessionRecordingsResponseLoading}+ >+ Load more recordings+ </LemonButton>+ </div>+ )}+ </>+ )}+ </div>+ )+}diff --git a/frontend/src/scenes/max/messages/adapters/SearchSessionRecordingsWidget.tsx b/products/posthog_ai/frontend/components/tool/widgets/SearchSessionRecordingsWidget.tsxsimilarity index 76%rename from frontend/src/scenes/max/messages/adapters/SearchSessionRecordingsWidget.tsxrename to products/posthog_ai/frontend/components/tool/widgets/SearchSessionRecordingsWidget.tsxindex affc97c209c5..1b90add155f1 100644--- a/frontend/src/scenes/max/messages/adapters/SearchSessionRecordingsWidget.tsx+++ b/products/posthog_ai/frontend/components/tool/widgets/SearchSessionRecordingsWidget.tsx@@ -1,7 +1,8 @@-import { GenericMcpToolRenderer, DataToolRow, type ToolRendererProps } from 'products/posthog_ai/frontend/api/tools'--import { RecordingsWidget } from '../UIPayloadAnswer'+import { DataToolRow } from '../DataToolRow'+import { GenericMcpToolRenderer } from '../GenericMcpToolRenderer'+import type { ToolRendererProps } from '../toolRegistry'import { extractRecordingFilters } from './extractors'+import { RecordingsWidget } from './RecordingsWidget'/*** Session-recording search / filter tool calls. The resolved `RecordingUniversalFilters` come back@@ -18,7 +19,7 @@ export function SearchSessionRecordingsWidget(props: ToolRendererProps): JSX.Elereturn (<DataToolRow {...props}>- <RecordingsWidget toolCallId={message.id} filters={filters} embedded />+ <RecordingsWidget toolCallId={message.id} filters={filters} /></DataToolRow>)}diff --git a/products/posthog_ai/frontend/components/tool/widgets/UpsertDashboardWidget.tsx b/products/posthog_ai/frontend/components/tool/widgets/UpsertDashboardWidget.tsxnew file mode 100644index 000000000000..f18073b9ac80--- /dev/null+++ b/products/posthog_ai/frontend/components/tool/widgets/UpsertDashboardWidget.tsx@@ -0,0 +1,51 @@+import { IconDashboard } from '@posthog/icons'+import { LemonButton } from '@posthog/lemon-ui'++import { IconOpenInNew } from 'lib/lemon-ui/icons'+import { urls } from 'scenes/urls'++import { MessageTemplate } from '../../../messages/MessageTemplate'+import { DataToolRow } from '../DataToolRow'+import { GenericMcpToolRenderer } from '../GenericMcpToolRenderer'+import type { ToolRendererProps } from '../toolRegistry'+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: ToolRendererProps): 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 (+ <DataToolRow {...props}>+ <MessageTemplate type="ai" wrapperClassName="w-full">+ <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>+ </MessageTemplate>+ </DataToolRow>+ )+}diff --git a/frontend/src/scenes/max/messages/VisualizationWidget.tsx b/products/posthog_ai/frontend/components/tool/widgets/VisualizationWidget.tsxsimilarity index 94%rename from frontend/src/scenes/max/messages/VisualizationWidget.tsxrename to products/posthog_ai/frontend/components/tool/widgets/VisualizationWidget.tsxindex f2da16399726..314666211bd8 100644--- a/frontend/src/scenes/max/messages/VisualizationWidget.tsx+++ b/products/posthog_ai/frontend/components/tool/widgets/VisualizationWidget.tsx@@ -24,9 +24,8 @@ import { QueryContext } from '~/queries/types'import { isFunnelsQuery, isHogQLQuery, isInsightVizNode } from '~/queries/utils'import { InsightShortId } from '~/types'-import { MessageTemplate } from 'products/posthog_ai/frontend/api/primitives'--import { visualizationTypeToQuery } from '../utils'+import { MessageTemplate } from '../../../messages/MessageTemplate'+import { visualizationTypeToQuery } from '../../../utils/visualizationQuery'const QUERY_CONTEXT_POSTHOG_AI: QueryContext = { limitContext: 'posthog_ai' } as const@@ -45,6 +44,15 @@ export interface VisualizationWidgetProps {embedded?: boolean}+/** Fallback CTA for ephemeral visualizations: open the rendered query as a new unsaved insight. */+export function getQueryOpenTarget(content: VisualizationArtifactContent): { url: string | null; tooltip: string } {+ const query = visualizationTypeToQuery(content)+ return {+ url: query ? urls.insightNew({ query: query as InsightVizNode | DataVisualizationNode }) : null,+ tooltip: 'Open as new insight',+ }+}+/** Resolves the "Open as insight" CTA target for a visualization artifact. */export function getArtifactOpenTarget(envelope: ArtifactMessage,@@ -53,11 +61,7 @@ export function getArtifactOpenTarget(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',- }+ return getQueryOpenTarget(content)}/**diff --git a/frontend/src/scenes/max/messages/adapters/extractors.test.ts b/products/posthog_ai/frontend/components/tool/widgets/extractors.test.tssimilarity index 98%rename from frontend/src/scenes/max/messages/adapters/extractors.test.tsrename to products/posthog_ai/frontend/components/tool/widgets/extractors.test.tsindex 29f0c4802c2d..3dadf06136e6 100644--- a/frontend/src/scenes/max/messages/adapters/extractors.test.ts+++ b/products/posthog_ai/frontend/components/tool/widgets/extractors.test.ts@@ -1,6 +1,7 @@import { ArtifactSource } from '~/queries/schema/schema-assistant-messages'-import type { ToolCallMessage } from '../../maxTypes'+import type { ToolCallMessage } from 'products/posthog_ai/frontend/types/toolTypes'+import {extractDashboard,extractErrorTrackingResponse,diff --git a/frontend/src/scenes/max/messages/adapters/extractors.ts b/products/posthog_ai/frontend/components/tool/widgets/extractors.tssimilarity index 99%rename from frontend/src/scenes/max/messages/adapters/extractors.tsrename to products/posthog_ai/frontend/components/tool/widgets/extractors.tsindex de41a3893ebe..a32841cbc5fd 100644--- a/frontend/src/scenes/max/messages/adapters/extractors.ts+++ b/products/posthog_ai/frontend/components/tool/widgets/extractors.ts@@ -12,7 +12,7 @@ import { DataTableNode, NodeKind, RecordingsQuery } from '~/queries/schema/schemimport { isInsightQueryNode } from '~/queries/utils'import { RecordingUniversalFilters } from '~/types'-import type { ToolCallMessage } from '../../maxTypes'+import type { ToolCallMessage } from 'products/posthog_ai/frontend/types/toolTypes'/*** Shared shape extractors for the sandbox MCP tool renderer widgets. Each turns a flatteneddiff --git a/frontend/src/scenes/max/messages/maxErrorTrackingWidgetLogic.ts b/products/posthog_ai/frontend/components/tool/widgets/maxErrorTrackingWidgetLogic.tssimilarity index 97%rename from frontend/src/scenes/max/messages/maxErrorTrackingWidgetLogic.tsrename to products/posthog_ai/frontend/components/tool/widgets/maxErrorTrackingWidgetLogic.tsindex 58c63bddf95d..2fae9b46929d 100644--- a/frontend/src/scenes/max/messages/maxErrorTrackingWidgetLogic.ts+++ b/products/posthog_ai/frontend/components/tool/widgets/maxErrorTrackingWidgetLogic.ts@@ -16,7 +16,7 @@ export interface MaxErrorTrackingWidgetLogicProps {}export const maxErrorTrackingWidgetLogic = kea<maxErrorTrackingWidgetLogicType>([- path(['scenes', 'max', 'messages', 'maxErrorTrackingWidgetLogic']),+ path(['products', 'posthog_ai', 'frontend', 'components', 'tool', 'widgets', 'maxErrorTrackingWidgetLogic']),props({} as MaxErrorTrackingWidgetLogicProps),key((props) => props.toolCallId),diff --git a/frontend/src/scenes/max/messages/adapters/registerMaxToolRenderers.test.ts b/products/posthog_ai/frontend/components/tool/widgets/registerDataToolRenderers.test.tssimilarity index 77%rename from frontend/src/scenes/max/messages/adapters/registerMaxToolRenderers.test.tsrename to products/posthog_ai/frontend/components/tool/widgets/registerDataToolRenderers.test.tsindex 1c397e470782..644c3b6b1493 100644--- a/frontend/src/scenes/max/messages/adapters/registerMaxToolRenderers.test.ts+++ b/products/posthog_ai/frontend/components/tool/widgets/registerDataToolRenderers.test.ts@@ -1,11 +1,11 @@-// Importing the module runs its side effect: registering Max's product-specific tool renderers into the-// shared toolRegistry. We assert the stable key → displayName metadata it contributes (the lazy+// Importing the module runs its side effect: registering the surface's product-specific tool renderers+// into the shared toolRegistry. We assert the stable key → displayName metadata it contributes (the lazy// Renderer itself is an opaque chunk).-import './registerMaxToolRenderers'+import './registerDataToolRenderers'import { toolRegistry } from 'products/posthog_ai/frontend/api/tools'-describe('registerMaxToolRenderers', () => {+describe('registerDataToolRenderers', () => {it.each([['insight-create', 'Insight'],['insight-update', 'Insight'],diff --git a/frontend/src/scenes/max/messages/adapters/registerMaxToolRenderers.tsx b/products/posthog_ai/frontend/components/tool/widgets/registerDataToolRenderers.tsxsimilarity index 80%rename from frontend/src/scenes/max/messages/adapters/registerMaxToolRenderers.tsxrename to products/posthog_ai/frontend/components/tool/widgets/registerDataToolRenderers.tsxindex 8281a18c7c2a..04de3578c2ef 100644--- a/frontend/src/scenes/max/messages/adapters/registerMaxToolRenderers.tsx+++ b/products/posthog_ai/frontend/components/tool/widgets/registerDataToolRenderers.tsx@@ -18,18 +18,13 @@ import {import { lazyWithRetry } from 'lib/utils/retryImport'-import {- registerToolRenderers,- type ToolRegistryEntry,- type ToolRendererProps,-} from 'products/posthog_ai/frontend/api/tools'+import { registerToolRenderers, type ToolRegistryEntry, type ToolRendererProps } from '../toolRegistry'// Product-specific tool-call renderers for the PostHog AI agent run surface. These render PostHog-// product entities (insights, dashboards, recordings, error-tracking issues, notebooks, query results)-// and therefore live in scenes/max — the shared `toolRegistry` must not import them. Importing-// this module (done once by the Max scene, see Thread.tsx) registers them into the shared registry so-// they're resolved when a sandbox conversation renders the matching tool call. Surfaces that never load-// Max (tasks, signals inbox) simply fall through to the generic MCP card for these keys.+// product entities (insights, dashboards, recordings, error-tracking issues, notebooks, query results).+// They aren't registered by the shared `toolRegistry` module itself (which stays product-free); instead+// this surface self-registers them via the side-effect import in `ToolCallCard`, so every consumer —+// the /tasks runner, the signals inbox, and Max's sandbox path — resolves the widget for these keys.//// Renderers are code-split: each lazyWithRetry() pulls its chunk on first use, not at registration time.const InsightRenderer = lazyWithRetry(() =>@@ -51,15 +46,20 @@ const QueryRenderer = lazyWithRetry(() => import('./QueryWidget').then((m) => ({// 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. Each call-// fans the aliases into one entry per key and feeds them through the surface's `registerToolRenderers`-// seam (Tier 4) — Max is the first consumer of that generic per-product mechanism.+// fans the aliases into one entry per key and feeds them through the `registerToolRenderers` seam (Tier 4).+// `requiresPostHogOrigin` on every entry: these render first-party PostHog cards (some with an Open+// button built from a payload `_posthogUrl`), so they must only match a call that came through the+// trusted single-exec PostHog server — not a user-installed MCP tool whose bare name collides with one+// of these keys. See `ToolRegistryEntry.requiresPostHogOrigin`.function register(keys: string[],displayName: string,icon: JSX.Element,Renderer: ComponentType<ToolRendererProps>): void {- registerToolRenderers(keys.map((key): ToolRegistryEntry => ({ key, displayName, icon, Renderer })))+ registerToolRenderers(+ keys.map((key): ToolRegistryEntry => ({ key, displayName, icon, Renderer, requiresPostHogOrigin: true }))+ )}// --- Data tools: insight (create / update / read) ---@@ -130,6 +130,7 @@ registerToolRenderers(displayName,icon,Renderer: QueryRenderer,+ requiresPostHogOrigin: true,})))diff --git a/products/posthog_ai/frontend/utils/visualizationQuery.ts b/products/posthog_ai/frontend/utils/visualizationQuery.tsnew file mode 100644index 000000000000..51a728f44099--- /dev/null+++ b/products/posthog_ai/frontend/utils/visualizationQuery.ts@@ -0,0 +1,37 @@+import { VisualizationBlock } from '~/queries/schema/schema-assistant-artifacts'+import {+ AnyAssistantGeneratedQuery,+ VisualizationArtifactContent,+ VisualizationItem,+} from '~/queries/schema/schema-assistant-messages'+import {+ DataVisualizationNode,+ InsightVizNode,+ NodeKind,+ QuerySchema,+ QuerySchemaRoot,+} from '~/queries/schema/schema-general'+import { isHogQLQuery, isInsightQueryNode } from '~/queries/utils'++export function castAssistantQuery(query: AnyAssistantGeneratedQuery | QuerySchemaRoot | null): QuerySchemaRoot | null {+ if (query) {+ return query as QuerySchemaRoot+ }+ return null+}++export const visualizationTypeToQuery = (+ visualization: VisualizationItem | VisualizationArtifactContent | VisualizationBlock+): QuerySchema | null => {+ if (!visualization) {+ return null+ }+ const source = castAssistantQuery('answer' in visualization ? visualization.answer : visualization.query)+ if (isHogQLQuery(source)) {+ return { kind: NodeKind.DataVisualizationNode, source: source } satisfies DataVisualizationNode+ }+ if (isInsightQueryNode(source)) {+ return { kind: NodeKind.InsightVizNode, source, showHeader: true } satisfies InsightVizNode+ }+ return source+}