Skip to content

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

fix(posthog-ai): declare tool widgets in a central manifest (#97264)

Georgiy Tarasove25e2136ee54
diff --git a/.agents/skills/integrating-with-posthog-ai/SKILL.md b/.agents/skills/integrating-with-posthog-ai/SKILL.md
index 3e2c33a1ab90..5e4b050fd435 100644
--- a/.agents/skills/integrating-with-posthog-ai/SKILL.md
+++ b/.agents/skills/integrating-with-posthog-ai/SKILL.md
@@ -38,7 +38,7 @@ Always a domain-scoped `api/<module>` entry, never a deep path, and there is del
import { useAttachedContext, useMcpToolApplyBack } from 'products/posthog_ai/frontend/api/logics'
```
-Pick the narrowest module. `api/logics` and `api/types` are headless; `api/primitives` drags in markdown and virtualization; `api/tools` registers built-ins at module load, so importing it is a side effect that is not tree-shaken. A status badge that imports the wrong tier doubles its chunk.
+Pick the narrowest module. `api/logics` and `api/types` are headless; `api/primitives` drags in markdown and virtualization; `api/tools` initializes the registry from built-ins and the central manifest at module load, so importing it is a side effect that is not tree-shaken. A status badge that imports the wrong tier doubles its chunk.
## The two mistakes that matter
diff --git a/.agents/skills/integrating-with-posthog-ai/references/rendering-widgets.md b/.agents/skills/integrating-with-posthog-ai/references/rendering-widgets.md
index 9db123e4bbad..6071d2fe8220 100644
--- a/.agents/skills/integrating-with-posthog-ai/references/rendering-widgets.md
+++ b/.agents/skills/integrating-with-posthog-ai/references/rendering-widgets.md
@@ -1,39 +1,55 @@
# Rendering tool cards in a thread
-Register a renderer and your product's tool calls display as a real card instead of the generic MCP fallback. The seam is `registerToolRenderers` from `api/tools` — a module-level side effect, no hooks and no dynamic registration.
+Export a typed declaration list from `products/<product>/frontend/posthogAiToolRenderers.tsx`.
+Add one direct import and one spread to `frontend/src/posthogAiToolRenderers.ts` for your product.
+Keep individual entries with their product; import no scenes or broad component barrels from declaration modules.
+Use **type-only** imports from `api/tools` for the contract, so declarations cannot create a runtime cycle with the registry.
+
+The registry initializes synchronously from built-ins and this manifest before rendering.
+The manifest is the sole extension mechanism: there is no runtime registration, subscription, or asynchronous initialization.
+`toolRegistry.lookup` and `lookupToolRenderer` remain available; keep headless `api/logics` and `api/types` free of registry imports.
```tsx
-import { registerToolRenderers } from 'products/posthog_ai/frontend/api/tools'
+import { IconBolt } from '@posthog/icons'
+
+import { lazyWithRetry } from 'lib/utils/retryImport'
+
+import type { ToolRegistryEntry } from 'products/posthog_ai/frontend/api/tools'
-registerToolRenderers([
+export const posthogAiToolRenderers: ToolRegistryEntry[] = [
{
key: 'cdp-functions-partial-update',
displayName: 'Update function',
icon: <IconBolt />,
- renderPermissionPreview: renderPartialUpdatePreview,
+ PermissionPreview: lazyWithRetry(() =>
+ import('./HogFunctionPermissionPreview').then((m) => ({ default: m.HogFunctionPermissionPreview }))
+ ),
requiresPostHogOrigin: true,
},
-])
+]
```
-Real caller: `frontend/src/scenes/hog-functions/configuration/registerHogFunctionToolPreviews.tsx`.
+Reference lists: `products/posthog_ai/frontend/posthogAiToolRenderers.tsx` for data widgets,
+`products/error_tracking/frontend/posthogAiToolRenderers.tsx` for product-owned error-tracking widgets,
+and `products/cdp/frontend/posthogAiToolRenderers.tsx` for a lazy permission preview.
+Declaration lists live at the product frontend root, outside `api/`. Implementations that use another
+product’s internals belong with that product. Use PostHog AI’s public `api/tools` helpers for the tool-card
+contract and generic output parsing; shared `frontend` dependencies are allowed.
+Implementations stay product-owned and load only on use through `lazyWithRetry`.
## The entry
-| Field | Meaning |
-| ------------------------- | ----------------------------------------------------------------------- |
-| `key` | The inner exec tool name, or the wire tool name for a built-in. |
-| `displayName` | Card title text. |
-| `icon` | Card icon. |
-| `Renderer` | Draws the **result** card. Optional — omit it for a preview-only entry. |
-| `renderPermissionPreview` | Draws the approval prompt shown **before** a write runs. |
-| `requiresPostHogOrigin` | Only match calls that came through the trusted PostHog server. |
+| Field | Meaning |
+| ----------------------- | -------------------------------------------------------------- |
+| `key` | Inner exec tool name, or the wire name for a built-in. |
+| `displayName` | Card title text. |
+| `icon` | Card icon. |
+| `Renderer` | Result card component. Omit for a preview-only entry. |
+| `PermissionPreview` | Approval evidence component receiving `{ request, fallback }`. |
+| `requiresPostHogOrigin` | Match only calls from the trusted PostHog server. |
-Set `requiresPostHogOrigin: true` for anything that renders PostHog entities. Without it, a tool of the same name from another MCP server would render through your card.
-
-Registration is by import, so call it once from your scene's entrypoint (or a small `register*.tsx` module the entrypoint imports for its side effect). Re-registering the same `key` overwrites. Wrap a heavy `Renderer` in `lazyWithRetry` so it does not weigh down the chunk that registers it.
-
-The built-in PostHog widgets — insights, dashboards, recordings, error tracking issues, notebooks, query results — live in `products/posthog_ai/frontend/components/tool/widgets/` and self-register the same way. Read `registerDataToolRenderers.tsx` there as the reference implementation; it is the same public seam, not a privileged path.
+Set `requiresPostHogOrigin: true` for PostHog entities. A colliding tool name from another server must keep generic rendering.
+Unknown tools and preview-only entries use the generic result card.
## A card is two header lines plus an accordion
@@ -48,7 +64,16 @@ Reserve `children` (always visible) for genuinely interactive payloads that woul
## Permission previews
-`renderPermissionPreview` runs at the approval prompt, before the tool executes, and receives the pending request record. It is worth writing for any destructive or hard-to-reverse write: show _what will change_, not just the tool name, so the user approves a real thing rather than a label. An entry can carry a preview and no `Renderer` at all.
+`PermissionPreview` receives `{ request, fallback }`, typed as `PermissionPreviewProps` from `api/tools`.
+Return `fallback` when there is no available matching mounted configuration or no changes to show.
+Do not mount or fetch a product scene to produce a preview.
+`PermissionInput` supplies its evidence block as fallback, and wraps the preview in `Suspense` and `PostHogErrorBoundary`.
+Both boundaries use that evidence fallback; approval controls remain outside them and stay usable during loading or failure.
+Errors retain the `posthog_ai_permission_preview` feature tag, and a new permission request resets the error boundary.
+
+Verify declarations are available from a registry-only import and do not evaluate lazy implementations.
+Render a matching card to check its skeleton resolves. Exercise preview loading, errors, missing/mismatched state,
+and successful diffs while keeping approvals usable. Keep trusted-origin and unknown-tool fallback coverage.
## Not to be confused with MCP UI apps
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index 7a2f0b299d91..01b99d205e27 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -5636,6 +5636,18 @@ snapshots:
hash: v1.k794b7964.4ca1129988e8d505656c9b1f1d88398516fdb24c8ffbdabab43251369514b1e6.0jyOb_I1ghN1euG9Pq-PrpA2WhttqN8WfGn2NZvAZ1g
products-posthog-ai-onboardingtakeover--start-step--light:
hash: v1.k794b7964.d1fadd3c1c5f4734cf0ae54b7ddc1f64e351cbd0ef1e7b16b78968f98ad51a44.1u2R4G2yaaKLW_puoLCQrIIPiZcZYN6UMWWziknTITk
+ products-posthog-ai-permissioninput--matching-configuration--dark:
+ hash: v1.k794b7964.be1eb7f0d99c67d743ea7fbc6ed8b4e0aefa7b561d30ae83b27546225b1a7703.08vwdgLYXwvFBF_mzK2cuSlZDQkpBLRDhRQY9dENK7I
+ products-posthog-ai-permissioninput--matching-configuration--light:
+ hash: v1.k794b7964.d478b95b0240c651b90a4634978a3f934ce34d7e7a92197d8a4e7aa4db6c0775.BIuSpIBo6bRQIfOtoOmZunCm5FarVrrEyUaCMb7oxlY
+ products-posthog-ai-permissioninput--mismatched-configuration--dark:
+ hash: v1.k794b7964.e331794504d3dcb057098e1a1789f53c59eb6d8aa31f27740ccbb35d8cdca32a.umeyxQPE6YC4nkiAkrcfcmnRKWjj4X5tsyZ88jrulcc
+ products-posthog-ai-permissioninput--mismatched-configuration--light:
+ hash: v1.k794b7964.7e45e80acefb74affb50575a4f3868ecab3150370d9ae9fb5860d3aff67c13ac.tyR_Xmxa03z7l_jFesZcUKXxVr11p-lZPSJw5z1DNbE
+ products-posthog-ai-permissioninput--no-mounted-configuration--dark:
+ hash: v1.k794b7964.10ef12662e0aad971cce5fd6798533d82268e53e801394405ae4d2a7e1926585.CwwPGCbOI5NlRrtyvkynGSsBd6GfSv6TT2nRjx6nlp0
+ products-posthog-ai-permissioninput--no-mounted-configuration--light:
+ hash: v1.k794b7964.3e33b0631e3b4b18ae60d2fa6b20925eaa130788449f03d1405e4540a5b1f177.vhrW1KHPbpGrUc3y5RnupJ-SBZf0jS1Q5oflYn0BpqE
products-posthog-ai-queuedmessagelist--empty--dark:
hash: v1.k794b7964.4313fbb59e762d6fc4a87fed828bb6c814697c489997e23111f95df3d84be347.VRvN01m1Gf36IcNO8lzu8q3mqxKWwSRROgPqtbxMiSU
products-posthog-ai-queuedmessagelist--empty--light:
@@ -5688,6 +5700,22 @@ snapshots:
hash: v1.k794b7964.dd4706709f78c02664f030c478cbb840a011b1ef2c5667a24b69f2da69d080e1.nyWDTetgXbFNe5gbJh_FRvK-1VQ0IzYQ22doIIokQeA
products-posthog-ai-threadactivitygroup--unknown-timing--light:
hash: v1.k794b7964.53f358e67f6b451f54117490d453d1a8ac9df23954e600c5136b8460ba176cdd.oPnmThRLe7TWRQMutMewFyRpHGhuYPXaEhUJN0FrWTs
+ products-posthog-ai-threadview--cold-conversation--dark:
+ hash: v1.k794b7964.f2ea4d6244d77619efdb7bee4249207dcba1e9cb61f2c76046ccdf505b3d094d.3f7mOytsWocBUaj3zrOjwyFwJaXUwfrVoF4jfxhK7_c
+ products-posthog-ai-threadview--cold-conversation--light:
+ hash: v1.k794b7964.291e97735011b04122176c87dd61d03661f36ed98b38c5f5d3f9ef51b3df24bb.iLJJ7McmcFrvRM_y66ydJ3QXTGazhPdjKFhBlYamRxE
+ products-posthog-ai-threadview--cold-task--dark:
+ hash: v1.k794b7964.f2ea4d6244d77619efdb7bee4249207dcba1e9cb61f2c76046ccdf505b3d094d.ejuZIcNm3Sepxnk_c88i8pKEIIL1i3RGBHBlm0uU3WU
+ products-posthog-ai-threadview--cold-task--light:
+ hash: v1.k794b7964.291e97735011b04122176c87dd61d03661f36ed98b38c5f5d3f9ef51b3df24bb.f-IoBwZjdOMxs3nQcUPjJQfMgfXlcIQiMJKdEGD6ejQ
+ products-posthog-ai-threadview--error-tracking--dark:
+ hash: v1.k794b7964.62b3ac295ab91b6a9369da2eda7fe32625e7a09cf294eeea8b325e5a2fd73727.ltGDrgZu-5Hm9-8_mKONY3B6jSpmiHOEq4kTvjMptJE
+ products-posthog-ai-threadview--error-tracking--light:
+ hash: v1.k794b7964.a6d1f1caf6f9db190492f6aaf34e767039050da2fa1054ca20ff4b7f351b664f.dziwktOLa5g7S874DtTlJ4Qgow2OOF24FQ8QwX252SM
+ products-posthog-ai-threadview--saved-insight-query--dark:
+ hash: v1.k794b7964.ff266ce4b007479bd8156db3c4b65a91a8b987d226bfd7622b20085df50d5d1c.2IsZbL1hVZEqsqWd22bNC0XJvJSqSlXHKCc0LGtJzJc
+ products-posthog-ai-threadview--saved-insight-query--light:
+ hash: v1.k794b7964.405cb15303a44d4f837d5569ab4110e07b62ffa71fc418e0aaeb29ddafe8cf8e.mnRWTc0Tao1ttGBbi8vm9n77TQn-RXrRtmeeaDk-yM8
products-posthog-ai-virtualizedthread--anchored-open--dark:
hash: v1.k794b7964.eecc3dde9e8475fb8f20f259880edae96e2750529897fc326c44d33ce20e0885.hQlXYcfwZ9CiFajcBHUg9oY6h2QcGrm91CkXVIht-OE
products-posthog-ai-virtualizedthread--anchored-open--light:
diff --git a/frontend/src/posthogAiToolRenderers.ts b/frontend/src/posthogAiToolRenderers.ts
new file mode 100644
index 000000000000..b16c8c3bf589
--- /dev/null
+++ b/frontend/src/posthogAiToolRenderers.ts
@@ -0,0 +1,12 @@
+import { posthogAiToolRenderers as cdpToolRenderers } from 'products/cdp/frontend/posthogAiToolRenderers'
+import { posthogAiToolRenderers as errorTrackingToolRenderers } from 'products/error_tracking/frontend/posthogAiToolRenderers'
+import { posthogAiToolRenderers as logsToolRenderers } from 'products/logs/frontend/posthogAiToolRenderers'
+import type { ToolRegistryEntry } from 'products/posthog_ai/frontend/api/tools'
+import { posthogAiToolRenderers as dataToolRenderers } from 'products/posthog_ai/frontend/posthogAiToolRenderers'
+
+export const posthogAiToolRenderers: ToolRegistryEntry[] = [
+ ...dataToolRenderers,
+ ...cdpToolRenderers,
+ ...errorTrackingToolRenderers,
+ ...logsToolRenderers,
+]
diff --git a/frontend/src/scenes/bootApp.ts b/frontend/src/scenes/bootApp.ts
index f4eb7b901159..4153ac94e7c4 100644
--- a/frontend/src/scenes/bootApp.ts
+++ b/frontend/src/scenes/bootApp.ts
@@ -1,7 +1,5 @@
import { registerNotebookLinkDrag } from 'scenes/notebooks/AddToNotebook/registerNotebookLinkDrag'
-import { registerLogsToolRenderers } from 'products/logs/frontend/agentTools/registerLogsToolRenderers'
-
import { initKea } from '../initKea'
import { loadPostHogJS } from '../loadPostHogJS'
@@ -31,9 +29,6 @@ export function bootApp(): void {
// Link resolves its drag-to-notebook behavior through a seam so bundles without
// notebooks (toolbar, exporter) don't ship them; the app opts in here
registerNotebookLinkDrag()
- // A logs tool card must resolve in any thread, including one opened before the lazy Logs
- // scene has loaded, so the app claims the logs tool names here instead of that scene
- registerLogsToolRenderers()
const idle =
typeof window.requestIdleCallback === 'function'
diff --git a/frontend/src/scenes/hog-functions/configuration/HogFunctionConfiguration.tsx b/frontend/src/scenes/hog-functions/configuration/HogFunctionConfiguration.tsx
index 19f7a36f4e7b..1f11f661a564 100644
--- a/frontend/src/scenes/hog-functions/configuration/HogFunctionConfiguration.tsx
+++ b/frontend/src/scenes/hog-functions/configuration/HogFunctionConfiguration.tsx
@@ -1,7 +1,3 @@
-// Side-effect: registers the CDP hog-function approval-card previews (cdp-functions-partial-update diff)
-// into the shared PostHog AI tool registry. Imported here so it's registered whenever the config scene loads.
-import './registerHogFunctionToolPreviews'
-
import clsx from 'clsx'
import { BindLogic, useActions, useValues } from 'kea'
import { Form } from 'kea-forms'
diff --git a/frontend/src/scenes/hog-functions/configuration/registerHogFunctionToolPreviews.tsx b/frontend/src/scenes/hog-functions/configuration/registerHogFunctionToolPreviews.tsx
deleted file mode 100644
index 7b6af3959b15..000000000000
--- a/frontend/src/scenes/hog-functions/configuration/registerHogFunctionToolPreviews.tsx
+++ /dev/null
@@ -1,54 +0,0 @@
-import type { ReactNode } from 'react'
-
-import { IconBolt } from '@posthog/icons'
-
-import { getPermissionRequestToolInput, registerToolRenderers } from 'products/posthog_ai/frontend/api/tools'
-import type { PermissionRequestRecord } from 'products/posthog_ai/frontend/api/types'
-
-import { HogFunctionConfigDiff } from './HogFunctionConfigDiff'
-import { buildHogFunctionConfigDiff } from './hogFunctionConfigDiffUtils'
-import { hogFunctionConfigurationLogic } from './hogFunctionConfigurationLogic'
-
-/**
- * Approval-card preview for `cdp-functions-partial-update`: a diff of the agent's proposed update
- * against the hog function the user has open. Reads the mounted `hogFunctionConfigurationLogic` for the
- * live config; when the scene isn't mounted there's no current config to diff against, so it returns
- * null and the surface falls back to the raw JSON payload. `findAllMounted` (not `findMounted`) because
- * the logic is keyed by function id — the surface can't reconstruct the key — and the edit scene mounts
- * a single instance.
- */
-function renderPartialUpdatePreview(record: PermissionRequestRecord): ReactNode | null {
- const mounted = hogFunctionConfigurationLogic.findAllMounted()[0]
- const current = mounted?.values.configuration as Record<string, unknown> | undefined
- if (!current) {
- return null
- }
- const proposed = getPermissionRequestToolInput(record)
- // An update aimed at a different function than the one on screen must not render a diff against
- // the open form — that would preview the wrong change. Fall back to the raw payload.
- const targetId = typeof proposed.id === 'string' ? proposed.id : null
- const mountedId = typeof mounted.props.id === 'string' ? mounted.props.id : null
- if (targetId && mountedId && targetId !== mountedId) {
- return null
- }
- const diffs = buildHogFunctionConfigDiff(current, proposed)
- if (diffs.length === 0) {
- return null
- }
- return <HogFunctionConfigDiff diffs={diffs} />
-}
-
-// Register on module load (idempotent — re-registering the same key overwrites). A preview-only entry:
-// no `Renderer`, so the tool-result card still resolves to the generic MCP card via `lookupToolRenderer`.
-// cdp-functions-create is intentionally left to the default JSON payload (no current config to diff).
-// `requiresPostHogOrigin`: an imported MCP server's tool with a colliding bare name must not have its
-// approval payload dressed up as this first-party diff — untrusted calls keep the raw JSON payload.
-registerToolRenderers([
- {
- key: 'cdp-functions-partial-update',
- displayName: 'Update function',
- icon: <IconBolt />,
- renderPermissionPreview: renderPartialUpdatePreview,
- requiresPostHogOrigin: true,
- },
-])
diff --git a/frontend/src/scenes/max/AGENTS.md b/frontend/src/scenes/max/AGENTS.md
index f0f9ecf57761..cff8c119a937 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/` (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.
+- **Tool widgets**: `messages/` (LangGraph presenters) → the surface's `toolRegistry`. The central `frontend/src/posthogAiToolRenderers.ts` manifest combines product-owned declarations before rendering. Max consumes the widgets; it does not register them.
### Rule: do not extend the LangGraph path unless explicitly asked
@@ -58,9 +58,12 @@ and 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, 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`.
+recordings, notebook, query) live in `products/posthog_ai/frontend/components/tool/widgets`; error tracking
+and replay vision own their widget families under their respective `products/<product>/frontend` directories.
+Error tracking contributes a declaration list to the central manifest, so its cards render on the sandbox path too.
+Replay vision has no declaration yet, so its scan widget renders only on the LangGraph path until one is added.
+Max's LangGraph path consumes the heavier ones (`VisualizationWidget` / `RecordingsWidget`) through `api/primitives`,
+and error-tracking and replay-vision widgets directly from their owning products.
## 5. Where do I add X?
@@ -69,7 +72,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) → `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).
+- **A new product tool renderer** (renders a PostHog entity) → the owning product’s frontend + declare it in `products/<product>/frontend/posthogAiToolRenderers.tsx` (the central manifest makes it available before any scene renders).
- **New context the agent should see** → register it from the owning product via the surface's context seam: `useAttachedContext` / `AttachedContextProvider` / `attachedContextLogic.registerContext` (see `products/posthog_ai/frontend/AGENTS.md` §3). Not `MaxUIContext`, and no new fields on the legacy stores. Scenes now register their on-screen context natively into that seam, and `maxThreadLogic`'s sandbox send merges the seam's items into `attached_context` — that bridge lives here and is deleted with `scenes/max`.
- **UI that reacts to the agent calling a tool** (sandbox path) → subscribe via the surface's `useToolStreamListener` / `toolStreamEventsLogic` (resolved tool names, replay suppressed by default). The legacy `useMaxTool` `callback` fires on LangGraph only.
diff --git a/frontend/src/scenes/max/Thread.tsx b/frontend/src/scenes/max/Thread.tsx
index bf166efcf38b..7483cd57c709 100644
--- a/frontend/src/scenes/max/Thread.tsx
+++ b/frontend/src/scenes/max/Thread.tsx
@@ -80,13 +80,13 @@ import {
MessageTemplate,
ReasoningAnswer,
RecordingsWidget,
- ReplayVisionScanWidget,
ThreadView,
TurnFeedbackActions,
type TurnTrailer,
} from 'products/posthog_ai/frontend/api/primitives'
import { LogEntry } from 'products/posthog_ai/frontend/lib/parse-logs'
import { isPiTaskRuntime } from 'products/posthog_ai/frontend/types/taskTypes'
+import { ReplayVisionScanWidget } from 'products/replay_vision/frontend/posthogAi/ReplayVisionScanWidget'
import { LangGraphActivity, ShimmeringContent } from './components/Activity'
import { FeedbackDisplay } from './components/FeedbackDisplay'
diff --git a/frontend/src/scenes/max/messages/UIPayloadAnswer.tsx b/frontend/src/scenes/max/messages/UIPayloadAnswer.tsx
index 5a196318eda5..efe524211a78 100644
--- a/frontend/src/scenes/max/messages/UIPayloadAnswer.tsx
+++ b/frontend/src/scenes/max/messages/UIPayloadAnswer.tsx
@@ -4,11 +4,8 @@ import { MaxErrorTrackingSearchResponse } from '~/queries/schema/schema-assistan
import { AssistantTool } from '~/queries/schema/schema-assistant-messages'
import { RecordingUniversalFilters } from '~/types'
-import {
- ErrorTrackingFiltersWidget,
- MessageTemplate,
- RecordingsWidget,
-} from 'products/posthog_ai/frontend/api/primitives'
+import { ErrorTrackingFiltersWidget } from 'products/error_tracking/frontend/posthogAi/ErrorTrackingFiltersWidget'
+import { MessageTemplate, RecordingsWidget } from 'products/posthog_ai/frontend/api/primitives'
import { isDangerousOperationResponse, normalizeDangerousOperationResponse } from '../approvalOperationUtils'
import { DangerousOperationApprovalCard } from '../DangerousOperationApprovalCard'
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index d3ba2c1e4d2e..4701226b973c 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -431,7 +431,7 @@ importers:
version: 0.25.12
jest:
specifier: ^29.7.0
puppeteer:
specifier: 19.0.0
version: 19.0.0([email protected])
@@ -2696,6 +2696,9 @@ importers:
'@storybook/react':
specifier: 'catalog:'
+ '@testing-library/react':
+ specifier: ^14.3.1
kea-test-utils:
specifier: 'catalog:'
version: 0.2.4([email protected](patch_hash=139b8d1f1304f9d9da452a9a1244c94ea679dbcb85687d8999563146879fb6f5)([email protected]))
@@ -4083,6 +4086,9 @@ importers:
'@posthog/quill-primitives':
specifier: workspace:*
version: link:../../packages/quill/packages/primitives
+ '@posthog/react':
+ specifier: 'catalog:'
'@storybook/react':
specifier: 'catalog:'
diff --git a/products/cdp/frontend/HogFunctionPermissionPreview.test.tsx b/products/cdp/frontend/HogFunctionPermissionPreview.test.tsx
new file mode 100644
index 000000000000..1936803cc132
--- /dev/null
+++ b/products/cdp/frontend/HogFunctionPermissionPreview.test.tsx
@@ -0,0 +1,116 @@
+import '@testing-library/jest-dom'
+
+import { cleanup, render, screen } from '@testing-library/react'
+
+import { hogFunctionConfigurationLogic } from 'scenes/hog-functions/configuration/hogFunctionConfigurationLogic'
+
+import type { PermissionRequestRecord } from 'products/posthog_ai/frontend/api/types'
+
+import { HogFunctionPermissionPreview } from './HogFunctionPermissionPreview'
+
+jest.mock('scenes/hog-functions/configuration/hogFunctionConfigurationLogic', () => ({
+ hogFunctionConfigurationLogic: { findAllMounted: jest.fn() },
+}))
+jest.mock('scenes/hog-functions/configuration/HogFunctionConfiguration', () => {
+ throw new Error('Permission previews must not import the product scene')
+})
+jest.mock('products/posthog_ai/frontend/components/tool/EditDiffRenderer', () => ({
+ DiffEditor: ({ diff }: { diff: { oldText: string; newText: string } }) => (
+ <div>
+ <span>{diff.oldText}</span>
+ <span>{diff.newText}</span>
+ </div>
+ ),
+}))
+
+describe('HogFunctionPermissionPreview', () => {
+ afterEach(cleanup)
+
+ const request: PermissionRequestRecord = {
+ requestId: 'permission-1',
+ toolCallId: 'call-1',
+ toolName: 'mcp__posthog__exec',
+ options: [],
+ rawToolCall: {
+ toolCallId: 'call-1',
+ rawServerName: 'posthog',
+ rawToolName: 'exec',
+ input: { command: 'call cdp-functions-partial-update {"id":"function-1","name":"Updated destination"}' },
+ status: 'pending',
+ contentBlocks: [],
+ },
+ }
+
+ it.each([
+ ['no mounted configuration', []],
+ ['configuration unavailable', [{ props: { id: 'function-1' }, values: { loaded: true } }]],
+ [
+ 'a configuration still loading',
+ [{ props: { id: 'function-1' }, values: { loaded: false, configuration: {} } }],
+ ],
+ ['an empty configuration', [{ props: { id: 'function-1' }, values: { loaded: true, configuration: {} } }]],
+ [
+ 'a new-function form carrying no id',
+ [
+ {
+ props: { templateId: 'template-1' },
+ values: { loaded: true, configuration: { name: 'Template default' } },
+ },
+ ],
+ ],
+ [
+ 'different function',
+ [
+ {
+ props: { id: 'function-2' },
+ values: { loaded: true, configuration: { name: 'Original destination' } },
+ },
+ ],
+ ],
+ [
+ 'no changes',
+ [
+ {
+ props: { id: 'function-1' },
+ values: { loaded: true, configuration: { name: 'Updated destination' } },
+ },
+ ],
+ ],
+ ])('uses evidence for %s without mounting or fetching a scene', (_name, mounted) => {
+ jest.mocked(hogFunctionConfigurationLogic.findAllMounted).mockReturnValue(
+ mounted as ReturnType<typeof hogFunctionConfigurationLogic.findAllMounted>
+ )
+ render(<HogFunctionPermissionPreview request={request} fallback={<div>Original evidence</div>} />)
+ expect(screen.getByText('Original evidence')).toBeInTheDocument()
+ })
+
+ it('uses evidence when the proposal names no function', () => {
+ jest.mocked(hogFunctionConfigurationLogic.findAllMounted).mockReturnValue([
+ { props: { id: 'function-1' }, values: { loaded: true, configuration: { name: 'Original destination' } } },
+ ] as ReturnType<typeof hogFunctionConfigurationLogic.findAllMounted>)
+ render(
+ <HogFunctionPermissionPreview
+ request={{
+ ...request,
+ rawToolCall: {
+ ...request.rawToolCall,
+ input: { command: 'call cdp-functions-partial-update {"name":"Updated destination"}' },
+ },
+ }}
+ fallback={<div>Original evidence</div>}
+ />
+ )
+ expect(screen.getByText('Original evidence')).toBeInTheDocument()
+ })
+
+ it('renders the proposed diff against the matching mounted configuration', async () => {
+ jest.mocked(hogFunctionConfigurationLogic.findAllMounted).mockReturnValue([
+ { props: { id: 'function-1' }, values: { loaded: true, configuration: { name: 'Original destination' } } },
+ ] as ReturnType<typeof hogFunctionConfigurationLogic.findAllMounted>)
+ render(<HogFunctionPermissionPreview request={request} fallback={<div>Original evidence</div>} />)
+ expect(screen.queryByText('Original evidence')).not.toBeInTheDocument()
+ expect(screen.getByText('Name')).toBeInTheDocument()
+ expect(await screen.findByText('Original destination')).toBeInTheDocument()
+ expect(screen.getByText('Updated destination')).toBeInTheDocument()
+ })
+})
diff --git a/products/cdp/frontend/HogFunctionPermissionPreview.tsx b/products/cdp/frontend/HogFunctionPermissionPreview.tsx
new file mode 100644
index 000000000000..1ab5b82cfb7f
--- /dev/null
+++ b/products/cdp/frontend/HogFunctionPermissionPreview.tsx
@@ -0,0 +1,41 @@
+import { HogFunctionConfigDiff } from 'scenes/hog-functions/configuration/HogFunctionConfigDiff'
+import { buildHogFunctionConfigDiff } from 'scenes/hog-functions/configuration/hogFunctionConfigDiffUtils'
+import { hogFunctionConfigurationLogic } from 'scenes/hog-functions/configuration/hogFunctionConfigurationLogic'
+
+import { getPermissionRequestToolInput, type PermissionPreviewProps } from 'products/posthog_ai/frontend/api/tools'
+
+/**
+ * Approval-card preview for `cdp-functions-partial-update`: a diff of the agent's proposed update
+ * against the hog function the user has open. Reads the mounted `hogFunctionConfigurationLogic` for the
+ * live config; when the scene isn't mounted, or its config has not loaded yet, there's nothing to diff
+ * against, so it returns the evidence fallback without mounting or fetching the scene. `findAllMounted`
+ * (not `findMounted`) because the logic is keyed by function id — the surface can't reconstruct the key —
+ * and the edit scene mounts a single instance.
+ */
+export function HogFunctionPermissionPreview({ request, fallback }: PermissionPreviewProps): JSX.Element {
+ const mounted = hogFunctionConfigurationLogic.findAllMounted()[0]
+ const current = mounted?.values.configuration as Record<string, unknown> | undefined
+ // The scene mounts with an empty form and fills it when its fetch lands. A diff against that empty
+ // config marks every proposed field as newly added, hiding the values the update replaces.
+ if (!mounted?.values.loaded || !current || Object.keys(current).length === 0) {
+ return <>{fallback}</>
+ }
+ const proposed = getPermissionRequestToolInput(request)
+ // An update aimed at a different function than the one on screen must not render a diff against
+ // the open form — that would preview the wrong change. Both ids must be known and match, because
+ // a new-function form carries no id and would otherwise diff against template defaults.
+ const targetId = typeof proposed.id === 'string' ? proposed.id : null
+ const mountedId = typeof mounted.props.id === 'string' ? mounted.props.id : null
+ if (!targetId || !mountedId || targetId !== mountedId) {
+ return <>{fallback}</>
+ }
+ const diffs = buildHogFunctionConfigDiff(current, proposed)
+ if (diffs.length === 0) {
+ return <>{fallback}</>
+ }
+ return (
+ <div className="max-h-80 overflow-y-auto">
+ <HogFunctionConfigDiff diffs={diffs} />
+ </div>
+ )
+}
diff --git a/products/cdp/frontend/posthogAiToolRenderers.tsx b/products/cdp/frontend/posthogAiToolRenderers.tsx
new file mode 100644
index 000000000000..364441e88276
--- /dev/null
+++ b/products/cdp/frontend/posthogAiToolRenderers.tsx
@@ -0,0 +1,17 @@
+import { IconBolt } from '@posthog/icons'
+
+import { lazyWithRetry } from 'lib/utils/retryImport'
+
+import type { ToolRegistryEntry } from 'products/posthog_ai/frontend/api/tools'
+
+export const posthogAiToolRenderers: ToolRegistryEntry[] = [
+ {
+ key: 'cdp-functions-partial-update',
+ displayName: 'Update function',
+ icon: <IconBolt />,
+ PermissionPreview: lazyWithRetry(() =>
+ import('./HogFunctionPermissionPreview').then((m) => ({ default: m.HogFunctionPermissionPreview }))
+ ),
+ requiresPostHogOrigin: true,
+ },
+]
diff --git a/products/cdp/package.json b/products/cdp/package.json
index a8a559f26126..05953d8bec12 100644
--- a/products/cdp/package.json
+++ b/products/cdp/package.json
@@ -10,6 +10,7 @@
},
"devDependencies": {
"@storybook/react": "catalog:",
+ "@testing-library/react": "^14.3.1",
"kea-test-utils": "catalog:"
},
"peerDependencies": {
diff --git a/products/posthog_ai/frontend/components/tool/widgets/ErrorTrackingIssueCard.tsx b/products/error_tracking/frontend/ErrorTrackingIssueCard.tsx
similarity index 96%
rename from products/posthog_ai/frontend/components/tool/widgets/ErrorTrackingIssueCard.tsx
rename to products/error_tracking/frontend/ErrorTrackingIssueCard.tsx
index f0a6e78b7e24..94ed7dd1907b 100644
--- a/products/posthog_ai/frontend/components/tool/widgets/ErrorTrackingIssueCard.tsx
+++ b/products/error_tracking/frontend/ErrorTrackingIssueCard.tsx
@@ -7,7 +7,7 @@ import { urls } from 'scenes/urls'
import { MaxErrorTrackingIssuePreview } from '~/queries/schema/schema-assistant-error-tracking'
-import { RuntimeIcon } from 'products/error_tracking/frontend/components/RuntimeIcon'
+import { RuntimeIcon } from './components/RuntimeIcon'
interface ErrorTrackingIssueCardProps {
issue: MaxErrorTrackingIssuePreview
diff --git a/products/posthog_ai/frontend/components/tool/widgets/ErrorTrackingFiltersSummary.tsx b/products/error_tracking/frontend/posthogAi/ErrorTrackingFiltersSummary.tsx
similarity index 100%
rename from products/posthog_ai/frontend/components/tool/widgets/ErrorTrackingFiltersSummary.tsx
rename to products/error_tracking/frontend/posthogAi/ErrorTrackingFiltersSummary.tsx
diff --git a/products/posthog_ai/frontend/components/tool/widgets/ErrorTrackingFiltersWidget.tsx b/products/error_tracking/frontend/posthogAi/ErrorTrackingFiltersWidget.tsx
similarity index 93%
rename from products/posthog_ai/frontend/components/tool/widgets/ErrorTrackingFiltersWidget.tsx
rename to products/error_tracking/frontend/posthogAi/ErrorTrackingFiltersWidget.tsx
index f5ecaf4faa2b..710a8da8cef8 100644
--- a/products/posthog_ai/frontend/components/tool/widgets/ErrorTrackingFiltersWidget.tsx
+++ b/products/error_tracking/frontend/posthogAi/ErrorTrackingFiltersWidget.tsx
@@ -14,18 +14,18 @@ import {
MaxErrorTrackingSearchResponse,
} from '~/queries/schema/schema-assistant-error-tracking'
-import { issueFiltersLogic } from 'products/error_tracking/frontend/components/IssueFilters/issueFiltersLogic'
+import { MessageTemplate } from 'products/posthog_ai/frontend/api/tools'
+
+import { issueFiltersLogic } from '../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'
+} from '../components/IssueQueryOptions/issueQueryOptionsLogic'
+import { ErrorTrackingIssueCard } from '../ErrorTrackingIssueCard'
+import { ERROR_TRACKING_SCENE_LOGIC_KEY } from '../scenes/ErrorTrackingScene/errorTrackingSceneLogic'
import { ErrorTrackingFiltersSummary } from './ErrorTrackingFiltersSummary'
-import { ErrorTrackingIssueCard } from './ErrorTrackingIssueCard'
import { MaxErrorTrackingWidgetLogicProps, maxErrorTrackingWidgetLogic } from './maxErrorTrackingWidgetLogic'
export function ErrorTrackingFiltersWidget({
diff --git a/products/error_tracking/frontend/posthogAi/ErrorTrackingWidget.test.tsx b/products/error_tracking/frontend/posthogAi/ErrorTrackingWidget.test.tsx
new file mode 100644
index 000000000000..cd5b898025da
--- /dev/null
+++ b/products/error_tracking/frontend/posthogAi/ErrorTrackingWidget.test.tsx
@@ -0,0 +1,50 @@
+import '@testing-library/jest-dom'
+
+import { render, screen } from '@testing-library/react'
+import { Suspense } from 'react'
+
+import { initKeaTests } from '~/test/init'
+
+import { lookupToolRenderer } from 'products/posthog_ai/frontend/api/tools'
+
+describe('ErrorTrackingWidget', () => {
+ it('loads the declared renderer and falls back for the MCP issues-list response', async () => {
+ initKeaTests()
+ const { Renderer } = lookupToolRenderer('query-error-tracking-issues-list', true)
+ render(
+ <Suspense fallback={<div>Loading widget</div>}>
+ <Renderer
+ isLastInGroup
+ message={{
+ id: 'synthetic-error-search',
+ resolvedKey: 'query-error-tracking-issues-list',
+ innerToolName: 'query-error-tracking-issues-list',
+ rawServerName: 'posthog',
+ rawToolName: 'exec',
+ rawInput: { command: 'call query-error-tracking-issues-list {}' },
+ rawOutput: {
+ results: [
+ {
+ id: 'example-issue',
+ name: 'Synthetic checkout error',
+ status: 'active',
+ library: 'web',
+ aggregations: { occurrences: 12, users: 3 },
+ },
+ ],
+ hasMore: false,
+ },
+ content: [],
+ status: 'completed',
+ }}
+ />
+ </Suspense>
+ )
+ expect(screen.getByText('Loading widget')).toBeInTheDocument()
+ expect(
+ await screen.findByText('Call query-error-tracking-issues-list', {}, { timeout: 10000 })
+ ).toBeInTheDocument()
+ expect(screen.queryByText('Loading widget')).not.toBeInTheDocument()
+ expect(screen.queryByText('No issues found')).not.toBeInTheDocument()
+ })
+})
diff --git a/products/posthog_ai/frontend/components/tool/widgets/ErrorTrackingWidget.tsx b/products/error_tracking/frontend/posthogAi/ErrorTrackingWidget.tsx
similarity index 78%
rename from products/posthog_ai/frontend/components/tool/widgets/ErrorTrackingWidget.tsx
rename to products/error_tracking/frontend/posthogAi/ErrorTrackingWidget.tsx
index 7ebfda1e30c3..0df0df2e4588 100644
--- a/products/posthog_ai/frontend/components/tool/widgets/ErrorTrackingWidget.tsx
+++ b/products/error_tracking/frontend/posthogAi/ErrorTrackingWidget.tsx
@@ -1,8 +1,7 @@
-import { DataToolRow } from '../DataToolRow'
-import { GenericMcpToolRenderer } from '../GenericMcpToolRenderer'
-import type { ToolRendererProps } from '../toolRegistry'
+import { DataToolRow, GenericMcpToolRenderer, type ToolRendererProps } from 'products/posthog_ai/frontend/api/tools'
+
import { ErrorTrackingFiltersWidget } from './ErrorTrackingFiltersWidget'
-import { extractErrorTrackingResponse } from './extractors'
+import { extractErrorTrackingResponse } from './extractErrorTrackingResponse'
/**
* Error-tracking search / filter tool calls. `rawOutput` is a `MaxErrorTrackingSearchResponse`
diff --git a/products/error_tracking/frontend/posthogAi/extractErrorTrackingResponse.test.ts b/products/error_tracking/frontend/posthogAi/extractErrorTrackingResponse.test.ts
new file mode 100644
index 000000000000..f2a591e4a209
--- /dev/null
+++ b/products/error_tracking/frontend/posthogAi/extractErrorTrackingResponse.test.ts
@@ -0,0 +1,38 @@
+import type { ToolCallMessage } from 'products/posthog_ai/frontend/api/types'
+
+import { extractErrorTrackingResponse } from './extractErrorTrackingResponse'
+
+function toolMessage(
+ rawOutput: unknown,
+ innerInput?: Record<string, unknown>,
+ resolvedKey = 'test-tool'
+): ToolCallMessage {
+ return {
+ id: 'call-1',
+ resolvedKey,
+ rawServerName: 'posthog',
+ rawToolName: 'mcp__posthog__exec',
+ rawInput: {},
+ innerInput,
+ rawOutput,
+ content: [],
+ status: 'completed',
+ }
+}
+
+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 one issue's details, which share only the status field", () => {
+ const detail = { id: 'issue-1', name: 'TypeError', status: 'active', severity: 'high', impact: {} }
+ expect(extractErrorTrackingResponse(toolMessage(detail))).toBeNull()
+ })
+
+ it('rejects outputs without any known field', () => {
+ expect(extractErrorTrackingResponse(toolMessage({ results: [{ id: 'issue-1' }] }))).toBeNull()
+ expect(extractErrorTrackingResponse(toolMessage(undefined))).toBeNull()
+ })
+})
diff --git a/products/error_tracking/frontend/posthogAi/extractErrorTrackingResponse.ts b/products/error_tracking/frontend/posthogAi/extractErrorTrackingResponse.ts
new file mode 100644
index 000000000000..f5c52a36aa13
--- /dev/null
+++ b/products/error_tracking/frontend/posthogAi/extractErrorTrackingResponse.ts
@@ -0,0 +1,27 @@
+import type { MaxErrorTrackingSearchResponse } from '~/queries/schema/schema-assistant-error-tracking'
+
+import { parseToolOutputRecord } from 'products/posthog_ai/frontend/api/tools'
+import type { ToolCallMessage } from 'products/posthog_ai/frontend/api/types'
+
+// Fields only a search response carries. `status` is excluded on purpose: an issue detail echoes it
+// too, so matching on it would render that detail as an empty issue list.
+const ERROR_TRACKING_RESPONSE_KEYS: readonly (keyof MaxErrorTrackingSearchResponse)[] = [
+ 'issues',
+ 'search_query',
+ 'date_from',
+ 'order_by',
+]
+
+/**
+ * Error-tracking search output is a `MaxErrorTrackingSearchResponse` (a filters echo plus issue
+ * previews) for `ErrorTrackingFiltersWidget`. Outputs that carry none of those fields — e.g. a raw
+ * REST issues list, or one issue's details — fall back to the generic card instead of rendering
+ * empty filter chips.
+ */
+export function extractErrorTrackingResponse(message: ToolCallMessage): MaxErrorTrackingSearchResponse | null {
+ const output = parseToolOutputRecord(message)
+ if (!output || !ERROR_TRACKING_RESPONSE_KEYS.some((key) => key in output)) {
+ return null
+ }
+ return output as MaxErrorTrackingSearchResponse
+}
diff --git a/products/posthog_ai/frontend/components/tool/widgets/maxErrorTrackingWidgetLogic.ts b/products/error_tracking/frontend/posthogAi/maxErrorTrackingWidgetLogic.ts
similarity index 98%
rename from products/posthog_ai/frontend/components/tool/widgets/maxErrorTrackingWidgetLogic.ts
rename to products/error_tracking/frontend/posthogAi/maxErrorTrackingWidgetLogic.ts
index d91a7fb3a0b3..9360e96f1f1c 100644
--- a/products/posthog_ai/frontend/components/tool/widgets/maxErrorTrackingWidgetLogic.ts
+++ b/products/error_tracking/frontend/posthogAi/maxErrorTrackingWidgetLogic.ts
@@ -76,7 +76,7 @@ export type maxErrorTrackingWidgetLogicType = MakeLogicType<
>
export const maxErrorTrackingWidgetLogic = kea<maxErrorTrackingWidgetLogicType>([
- path(['products', 'posthog_ai', 'frontend', 'components', 'tool', 'widgets', 'maxErrorTrackingWidgetLogic']),
+ path(['products', 'error_tracking', 'frontend', 'posthogAi', 'maxErrorTrackingWidgetLogic']),
props({} as MaxErrorTrackingWidgetLogicProps),
key((props) => props.toolCallId),
diff --git a/products/error_tracking/frontend/posthogAiToolRenderers.tsx b/products/error_tracking/frontend/posthogAiToolRenderers.tsx
new file mode 100644
index 000000000000..3068d00fd5c2
--- /dev/null
+++ b/products/error_tracking/frontend/posthogAiToolRenderers.tsx
@@ -0,0 +1,22 @@
+import { IconWarning } from '@posthog/icons'
+
+import { lazyWithRetry } from 'lib/utils/retryImport'
+
+import type { ToolRegistryEntry } from 'products/posthog_ai/frontend/api/tools'
+
+const ErrorTrackingRenderer = lazyWithRetry(() =>
+ import('./posthogAi/ErrorTrackingWidget').then((m) => ({ default: m.ErrorTrackingWidget }))
+)
+
+export const posthogAiToolRenderers: ToolRegistryEntry[] = [
+ 'query-error-tracking-issues-list',
+ 'query-error-tracking-issue',
+ 'query-error-tracking-issue-events',
+].map((key) => ({
+ key,
+ displayName: 'Error tracking',
+ icon: <IconWarning />,
+ Renderer: ErrorTrackingRenderer,
+ requiresPostHogOrigin: true,
+ keepVisible: true,
+}))
diff --git a/products/logs/frontend/agentTools/registerLogsToolRenderers.tsx b/products/logs/frontend/agentTools/registerLogsToolRenderers.tsx
deleted file mode 100644
index 4a266bba6bf7..000000000000
--- a/products/logs/frontend/agentTools/registerLogsToolRenderers.tsx
+++ /dev/null
@@ -1,62 +0,0 @@
-import { IconBell, IconList, IconPulse, IconSearch, IconServer, IconStack, IconWarning } from '@posthog/icons'
-
-import { lazyWithRetry } from 'lib/utils/retryImport'
-
-import { registerToolRenderers, type ToolRegistryEntry } from 'products/posthog_ai/frontend/api/tools'
-
-// The card pulls its chunk on first use, so registering the whole family stays a strings-and-icons cost.
-const LogsQueryRenderer = lazyWithRetry(() =>
- import('./LogsQueryToolWidget').then((m) => ({ default: m.LogsQueryToolWidget }))
-)
-
-// Friendly header (name + icon) for a logs tool call, without a bespoke result card. A no-Renderer
-// entry keeps its displayName and icon on the generic card (see `lookupToolRenderer`), so the whole
-// logs tool family reads as intentional logs actions in a thread even where only query-logs draws a
-// custom card. `requiresPostHogOrigin` so a user-installed MCP tool with a colliding bare name does
-// not borrow the logs branding.
-function labelled(keys: string[], displayName: string, icon: JSX.Element): ToolRegistryEntry[] {
- return keys.map((key) => ({ key, displayName, icon, requiresPostHogOrigin: true }))
-}
-
-/**
- * Claim the logs tool names in the shared registry. Called from `bootApp` rather than run at module
- * load: a thread renders tool cards wherever it is opened, including an `/ai/{id}` link followed
- * before the lazy Logs scene has ever loaded, so registering from the scene entrypoint would leave
- * those calls on the generic wrench card.
- */
-export function registerLogsToolRenderers(): void {
- registerToolRenderers([
- // The flagship: renders the returned log rows as a compact severity-tagged list.
- {
- key: 'query-logs',
- displayName: 'Query logs',
- icon: <IconSearch />,
- Renderer: LogsQueryRenderer,
- requiresPostHogOrigin: true,
- },
- ...labelled(['logs-services-create'], 'Logs services', <IconServer />),
- ...labelled(['logs-patterns', 'logs-patterns-diff'], 'Log patterns', <IconStack />),
- ...labelled(['logs-count', 'logs-count-ranges', 'logs-sparkline-query'], 'Count logs', <IconPulse />),
- ...labelled(
- ['logs-attributes-list', 'logs-attribute-values-list', 'logs-facet-values-create'],
- 'Log attributes',
- <IconList />
- ),
- ...labelled(['logs-anomalies-scan', 'logs-anomalies-series-bands'], 'Log anomalies', <IconWarning />),
- ...labelled(
- [
- 'logs-alerts-list',
- 'logs-alerts-retrieve',
- 'logs-alerts-create',
- 'logs-alerts-partial-update',
- 'logs-alerts-destroy',
- 'logs-alerts-simulate-create',
- 'logs-alerts-events-list',
- 'logs-alerts-destinations-create',
- 'logs-alerts-destinations-delete-create',
- ],
- 'Log alert',
- <IconBell />
- ),
- ])
-}
diff --git a/products/logs/frontend/components/LogsViewer/LogDetailsModal/Tabs/RelatedErrors/RelatedErrorsTab.tsx b/products/logs/frontend/components/LogsViewer/LogDetailsModal/Tabs/RelatedErrors/RelatedErrorsTab.tsx
index 12238b8636e2..696181340c35 100644
--- a/products/logs/frontend/components/LogsViewer/LogDetailsModal/Tabs/RelatedErrors/RelatedErrorsTab.tsx
+++ b/products/logs/frontend/components/LogsViewer/LogDetailsModal/Tabs/RelatedErrors/RelatedErrorsTab.tsx
@@ -7,7 +7,7 @@ import { pluralize } from 'lib/utils/strings'
import { MaxErrorTrackingIssuePreview } from '~/queries/schema/schema-assistant-error-tracking'
-import { ErrorTrackingIssueCard } from 'products/posthog_ai/frontend/api/primitives'
+import { ErrorTrackingIssueCard } from 'products/error_tracking/frontend/ErrorTrackingIssueCard'
import { RelatedErrorsLogicProps, relatedErrorsLogic } from './relatedErrorsLogic'
diff --git a/products/logs/frontend/agentTools/registerLogsToolRenderers.test.ts b/products/logs/frontend/posthogAiToolRenderers.test.ts
similarity index 81%
rename from products/logs/frontend/agentTools/registerLogsToolRenderers.test.ts
rename to products/logs/frontend/posthogAiToolRenderers.test.ts
index 0785dd114a55..cd54c1888e49 100644
--- a/products/logs/frontend/agentTools/registerLogsToolRenderers.test.ts
+++ b/products/logs/frontend/posthogAiToolRenderers.test.ts
@@ -3,13 +3,11 @@ import path from 'path'
import { toolRegistry } from 'products/posthog_ai/frontend/api/tools'
-import { registerLogsToolRenderers } from './registerLogsToolRenderers'
-
// Every logs tool the MCP codegen emits, so a tool added to the catalog without a registry entry
// fails here instead of shipping the generic wrench card. Read off the generated file rather than
// imported, to keep the services/mcp graph out of a frontend test.
function generatedLogsToolNames(): string[] {
- const generated = path.resolve(__dirname, '../../../../services/mcp/src/tools/generated/logs.ts')
+ const generated = path.resolve(__dirname, '../../../services/mcp/src/tools/generated/logs.ts')
const source = fs.readFileSync(generated, 'utf-8')
const names = [...source.matchAll(/name: '([a-z0-9-]+)'/g)].map((m) => m[1])
if (names.length === 0) {
@@ -18,11 +16,7 @@ function generatedLogsToolNames(): string[] {
return [...new Set(names)].sort()
}
-describe('registerLogsToolRenderers', () => {
- beforeAll(() => {
- registerLogsToolRenderers()
- })
-
+describe('posthogAiToolRenderers', () => {
it.each(generatedLogsToolNames())('claims %s in the shared registry', (key) => {
expect(toolRegistry.lookup(key)).not.toBeNull()
})
diff --git a/products/logs/frontend/posthogAiToolRenderers.tsx b/products/logs/frontend/posthogAiToolRenderers.tsx
new file mode 100644
index 000000000000..c05c9c40d9b9
--- /dev/null
+++ b/products/logs/frontend/posthogAiToolRenderers.tsx
@@ -0,0 +1,54 @@
+import { IconBell, IconList, IconPulse, IconSearch, IconServer, IconStack, IconWarning } from '@posthog/icons'
+
+import { lazyWithRetry } from 'lib/utils/retryImport'
+
+import type { ToolRegistryEntry } from 'products/posthog_ai/frontend/api/tools'
+
+// The card pulls its chunk on first use, so registering the whole family stays a strings-and-icons cost.
+const LogsQueryRenderer = lazyWithRetry(() =>
+ import('./agentTools/LogsQueryToolWidget').then((m) => ({ default: m.LogsQueryToolWidget }))
+)
+
+// Friendly header (name + icon) for a logs tool call, without a bespoke result card. A no-Renderer
+// entry keeps its displayName and icon on the generic card (see `lookupToolRenderer`), so the whole
+// logs tool family reads as intentional logs actions in a thread even where only query-logs draws a
+// custom card. `requiresPostHogOrigin` so a user-installed MCP tool with a colliding bare name does
+// not borrow the logs branding.
+function labelled(keys: string[], displayName: string, icon: JSX.Element): ToolRegistryEntry[] {
+ return keys.map((key) => ({ key, displayName, icon, requiresPostHogOrigin: true }))
+}
+
+export const posthogAiToolRenderers: ToolRegistryEntry[] = [
+ // The flagship: renders the returned log rows as a compact severity-tagged list.
+ {
+ key: 'query-logs',
+ displayName: 'Query logs',
+ icon: <IconSearch />,
+ Renderer: LogsQueryRenderer,
+ requiresPostHogOrigin: true,
+ },
+ ...labelled(['logs-services-create'], 'Logs services', <IconServer />),
+ ...labelled(['logs-patterns', 'logs-patterns-diff'], 'Log patterns', <IconStack />),
+ ...labelled(['logs-count', 'logs-count-ranges', 'logs-sparkline-query'], 'Count logs', <IconPulse />),
+ ...labelled(
+ ['logs-attributes-list', 'logs-attribute-values-list', 'logs-facet-values-create'],
+ 'Log attributes',
+ <IconList />
+ ),
+ ...labelled(['logs-anomalies-scan', 'logs-anomalies-series-bands'], 'Log anomalies', <IconWarning />),
+ ...labelled(
+ [
+ 'logs-alerts-list',
+ 'logs-alerts-retrieve',
+ 'logs-alerts-create',
+ 'logs-alerts-partial-update',
+ 'logs-alerts-destroy',
+ 'logs-alerts-simulate-create',
+ 'logs-alerts-events-list',
+ 'logs-alerts-destinations-create',
+ 'logs-alerts-destinations-delete-create',
+ ],
+ 'Log alert',
+ <IconBell />
+ ),
+]
diff --git a/products/posthog_ai/README.md b/products/posthog_ai/README.md
index aeead7323621..12234a76e740 100644
--- a/products/posthog_ai/README.md
+++ b/products/posthog_ai/README.md
@@ -33,7 +33,7 @@ Import from a domain-scoped `api/<module>` entry. Never reach into `components/.
```ts
import { useAttachedContext, useToolStreamListener } from 'products/posthog_ai/frontend/api/logics'
-import { registerToolRenderers } from 'products/posthog_ai/frontend/api/tools'
+import type { ToolRegistryEntry } from 'products/posthog_ai/frontend/api/tools'
```
Pick the narrowest module that does the job — the split preserves code-splitting, and a fat import drags the markdown/virtualization thread or the side-effectful tool registry into your chunk. The full tier table lives in [`frontend/README.md`](./frontend/README.md#2-which-surface-do-i-use).
@@ -120,27 +120,50 @@ From a kea logic, either listen to `toolStreamEventsLogic.actionTypes.emitToolEv
## Seam 4 — render your own tool cards
-Register a renderer so your product's tool calls display as a real card in the thread instead of the generic MCP fallback. Call it once at module load from your scene's entrypoint:
+Export a typed declaration list from `products/<product>/frontend/posthogAiToolRenderers.tsx`.
+Add one direct import and one spread to `frontend/src/posthogAiToolRenderers.ts` for your product.
+Keep individual entries with their product; import no scenes or broad component barrels from declaration modules.
+Use **type-only** imports from `api/tools` for the contract, so declarations cannot create a runtime cycle with the registry.
+
+The registry initializes synchronously from built-ins and this manifest before rendering.
+The manifest is the sole extension mechanism: there is no runtime registration, subscription, or asynchronous initialization.
+`toolRegistry.lookup` and `lookupToolRenderer` remain available; keep headless `api/logics` and `api/types` free of registry imports.
```tsx
-import { registerToolRenderers } from 'products/posthog_ai/frontend/api/tools'
+import { IconBolt } from '@posthog/icons'
+
+import { lazyWithRetry } from 'lib/utils/retryImport'
-registerToolRenderers([
+import type { ToolRegistryEntry } from 'products/posthog_ai/frontend/api/tools'
+
+export const posthogAiToolRenderers: ToolRegistryEntry[] = [
{
key: 'cdp-functions-partial-update',
displayName: 'Update function',
icon: <IconBolt />,
- renderPermissionPreview: renderPartialUpdatePreview,
+ PermissionPreview: lazyWithRetry(() =>
+ import('./HogFunctionPermissionPreview').then((m) => ({ default: m.HogFunctionPermissionPreview }))
+ ),
requiresPostHogOrigin: true,
},
-])
+]
```
-`key` is the inner exec tool name. A `Renderer` draws the result card; `renderPermissionPreview` draws the approval prompt shown _before_ a write runs. Set `requiresPostHogOrigin: true` so the entry only matches calls that came through the trusted PostHog server. Wrap a heavy renderer in `lazyWithRetry`.
+`key` is the inner exec tool name. `Renderer` draws the result card; `PermissionPreview` draws the approval evidence before a write runs.
+Either component can use `lazyWithRetry`; importing declarations never evaluates their implementations.
+Set `requiresPostHogOrigin: true` for PostHog entities so colliding third-party tool names retain generic cards and evidence.
+Unknown tools and preview-only entries keep the generic result card.
+
+`PermissionPreview` receives `{ request, fallback }`, typed as `PermissionPreviewProps` from `api/tools`.
+Return `fallback` when there is no available matching mounted configuration or no changes to show.
+Do not mount or fetch a product scene to produce a preview.
+`PermissionInput` supplies its evidence block as fallback, and wraps the preview in `Suspense` and `PostHogErrorBoundary`.
+Both boundaries use that evidence fallback; approval controls remain outside them and stay usable during loading or failure.
+Errors retain the `posthog_ai_permission_preview` feature tag, and a new permission request resets the error boundary.
**A tool card is two header lines plus an accordion.** `ToolActivity` gives you a `title` and one `subtitle` — the single most salient input. Everything else your tool produces goes in the collapsible `body`, never in always-visible `children`, so a thread with twenty tool calls stays scannable. Reserve `children` for payloads the user must act on.
-The built-in PostHog widgets (insights, dashboards, recordings, error tracking, notebooks, query results) live in `frontend/components/tool/widgets/` and self-register the same way — that's the reference implementation.
+Insights, dashboards, recordings, notebooks, and query widgets live in `frontend/components/tool/widgets/`, with declarations in `frontend/posthogAiToolRenderers.tsx`. The query renderer also handles `insight-query` saved-insight results. Error tracking owns its widgets under `products/error_tracking/frontend/posthogAi/` and declares them in its frontend-root `posthogAiToolRenderers.tsx`. Replay vision owns its scan widget and polling logic under `products/replay_vision/frontend/posthogAi/`; Max composes that widget directly. CDP declares its preview in `products/cdp/frontend/posthogAiToolRenderers.tsx`.
> **MCP UI apps are a different mechanism.** The `@posthog/mcp-ui` components under `products/*/mcp/apps/` render tool results in _external_ clients like Claude Desktop, served through `services/mcp/`. They do not render inside PostHog AI threads. See [`/implementing-mcp-ui-apps`](../../.agents/skills/implementing-mcp-ui-apps/SKILL.md).
diff --git a/products/posthog_ai/frontend/AGENTS.md b/products/posthog_ai/frontend/AGENTS.md
index 3deb3b373780..d962328777d0 100644
--- a/products/posthog_ai/frontend/AGENTS.md
+++ b/products/posthog_ai/frontend/AGENTS.md
@@ -23,9 +23,9 @@ import rule, and copy-paste recipes live in the consumer-facing [`README.md`](./
| **1 — Prepackaged surfaces** | `api/readableRun` + `api/runSurface` + `api/runner` | `ReadonlyRunSurface` (lazy, code-split read-only embed); the `RunSurface` compound (`Root` + slots, eager) for custom layouts; `EmbeddedRunner` (lazy TaskTracker product for inline hosts) |
| **2 — Compound primitives** | `api/primitives` | `Thread` + atoms, `ThreadView`, `Composer.*`, `QueuedMessageList`, `RunLogSkeleton`, activity primitives + `RunActivity`, message presenters, permission/question surfaces |
| **3 — Headless logic + types** | `api/logics` + `api/types` | `runStreamLogic`, `runInteractionLogic`, status + thinking helpers; folded-thread + tool types |
-| **4 — Extension seam** | `api/tools` | `toolRegistry`, `registerToolRenderers`, `lookupToolRenderer`, `GenericMcpToolRenderer`, `DataToolRow`, `ToolActivity`, `FilePath`, diff helpers |
+| **4 — Extension seam** | `api/tools` | `toolRegistry`, `lookupToolRenderer`, `GenericMcpToolRenderer`, `DataToolRow`, `ToolActivity`, `FilePath`, diff helpers |
-**Why the split, not one flat barrel:** the tool registry registers built-ins at module load — a top-level
+**Why the split, not one flat barrel:** the tool registry initializes from built-ins and the manifest at module load — a top-level
side effect that is _not_ tree-shaken. A single barrel statically re-exports it alongside the
markdown/virtualization-heavy thread and the headless logics, so a consumer wanting only
`isTerminalRunStatus` for a status badge would drag the registry + presenters into its chunk. Isolating the
@@ -78,7 +78,7 @@ The headline exports per module:
deliberate, mild deviation from the "no React" reading of this lane: they import `react` + `kea` but no
components, so the lane stays registry- and presenter-free.
- **`api/types`** — folded-thread + tool domain types, `AttachedContextItem`, `ToolStreamEvent` (pure types).
-- **`api/tools`** — **`toolRegistry`**, **`registerToolRenderers`** (the generic per-product seam, see §2),
+- **`api/tools`** — **`toolRegistry`**, **`ToolRegistryEntry`** (the declaration contract, see §2),
`lookupToolRenderer`, `GenericMcpToolRenderer`, `DataToolRow`, `ToolActivity`, `FilePath`, and the
diff/exec helpers. Isolated here because importing it pulls the side-effectful registry chunk.
@@ -94,18 +94,24 @@ 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 task
viewer). Keep it generic — no Max-specific branching.
-- **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 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`.
+- **Tool declarations load through the central manifest.** `frontend/src/posthogAiToolRenderers.ts` imports
+ lightweight product lists directly, with one import and spread per product. Insights, dashboards, recordings,
+ notebooks, and query widgets live in `components/tool/widgets/`; the frontend-root `posthogAiToolRenderers.tsx`
+ declares their keys, metadata, and lazy factories. Error tracking owns its widget family and declaration
+ list under `products/error_tracking/frontend/`; replay vision owns its scan widget and polling logic
+ under `products/replay_vision/frontend/posthogAi/`. Product adapters use the public `api/tools` contract
+ and shared helpers. Products may depend on shared frontend code; product internals stay with their owner.
+ CDP owns `products/cdp/frontend/posthogAiToolRenderers.tsx` and its lazy permission preview component.
+ Declaration modules use type-only contract imports from `api/tools`, never runtime facade imports,
+ scenes, or broad component barrels. The registry initializes once from built-ins and the manifest;
+ `toolRegistry.lookup` and `lookupToolRenderer` are synchronous. Runtime registration is not supported.
+ Every conversation, task, and inbox consumer sees the complete registry on its first render.
+ `PermissionPreview` takes `PermissionPreviewProps` (`request`, `fallback`) and returns fallback when
+ mounted state is unavailable, mismatched, or unchanged. It must not mount or fetch the product scene.
+ `PermissionInput` isolates lazy loading and rendering errors with evidence fallbacks; approval controls
+ remain outside both boundaries. The error boundary resets for a new permission request.
+ Max's frozen LangGraph path consumes `VisualizationWidget` and `RecordingsWidget` through
+ `api/primitives`, and the error-tracking and replay-vision widgets from their owning products.
- 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. (The recordings "accept these filters"
bar is one such lift: `RecordingsWidget` takes an optional `onAcceptFilters` prop; Max's LangGraph path
@@ -219,6 +225,7 @@ ingestion).
## 5. Layout
```text
+posthogAiToolRenderers.tsx # product declarations consumed by the central manifest
api/ # public API facade — the contract (import api/<module>, never deep paths)
readableRun.ts # Tier 1: ReadonlyRunSurface (lazy read-only embed)
runSurface.ts # Tier 1: RunSurface compound (Root + slots, eager) for custom layouts
@@ -226,14 +233,14 @@ api/ # public API facade — the contract (import api/<module>, n
primitives.ts # Tier 2: Composer, Thread + atoms, ThreadView, QueuedMessageList, presenters, perm/question
logics.ts # Tier 3: runStreamLogic, runInteractionLogic, context store + hooks, tool-event bus (headless)
types.ts # Tier 3: folded-thread + tool domain types, AttachedContextItem, ToolStreamEvent (pure types)
- tools.ts # Tier 4: toolRegistry + registerToolRenderers seam (side-effectful — isolated)
+ tools.ts # Tier 4: lookup + declaration contract (registry isolated)
components/ # RunSurfaceImpl (the RunSurface compound, heavy chunk); ReadonlyRunSurfaceImpl (prepackaged
# read-only layout) + ReadonlyRunSurface (its lazy wrapper, replaces the old RunViewer.tsx);
# RunLogSkeleton (shared loader), Thread, Composer, perm/question surfaces, activity, tool/;
# AttachedContextProvider (render-null context injection wrapper)
composer/ # the Composer compound; AttachedContextBar (@-picker + context chips)
tool/ # tool registry + renderers (built-ins, generic MCP, EditDiffRenderer, diff/exec utils)
- widgets/ # PostHog product data-tool widgets (insight/dashboard/recordings/error-tracking/notebook/query) + registerDataToolRenderers
+ widgets/ # PostHog product data-tool widgets (insight/dashboard/recordings/notebook/query)
hooks/ # useAttachedContext, useToolStream — mount-scoped registration wrappers over the logics
logics/ # runStreamLogic, runInteractionLogic, attachedContextLogic, contextPickerLogic, toolStreamEventsLogic;
# tasksLogic/taskLogic data logics (+ *LogicType.ts)
diff --git a/products/posthog_ai/frontend/README.md b/products/posthog_ai/frontend/README.md
index f3b9dd6048f9..a274fe7b8628 100644
--- a/products/posthog_ai/frontend/README.md
+++ b/products/posthog_ai/frontend/README.md
@@ -39,7 +39,7 @@ Pick the **lowest tier** that does the job.
| **1 — Prepackaged surfaces** | `api/readableRun` + `api/runSurface` + `api/runner` | `ReadonlyRunSurface` (lazy, code-split read-only embed); the `RunSurface` compound (`Root` + slots, eager) for custom layouts; `EmbeddedRunner` (lazy TaskTracker product for inline hosts) | "Just show a run" → `ReadonlyRunSurface` (inbox embeds). "Drive a run / custom layout" → `RunSurface` (tasks). "Embed the whole `/tasks` product" → `EmbeddedRunner` (Max). |
| **2 — Compound primitives** | `api/primitives` | `Thread` + atoms (`.Message/.Markdown/.Reasoning/.Failure/.Activity/.ToolCall`), `ThreadView`, `Composer.*`, `AttachedContextBar`, `QueuedMessageList`, `RunLogSkeleton`, activity primitives + `RunActivity`, message presenters, permission/question/resource surfaces | Custom layout, or a bespoke/compact thread. |
| **3 — Headless logic + types** | `api/logics` + `api/types` | `runStreamLogic`, `runInteractionLogic`, status helpers (`isTerminalRunStatus`, `INITIAL_PERMISSION_MODE`), thinking-message helpers, context injection (`attachedContextLogic`, `useAttachedContext`, `contextPickerLogic`), tool-stream subscriptions (`toolStreamEventsLogic`, `useToolStreamListener`); folded-thread + tool types, `AttachedContextItem`, `ToolStreamEvent` | Status badge, automation, context injection, tool-event listeners — no presenters, no registry. |
-| **4 — Extension seam** | `api/tools` | `toolRegistry`, `registerToolRenderers`, `lookupToolRenderer`, `GenericMcpToolRenderer`, `DataToolRow`, `ToolActivity`, `FilePath`, diff helpers | Your product renders tool cards (insights, dashboards…). Register them from your own scene. |
+| **4 — Extension seam** | `api/tools` | `toolRegistry`, `lookupToolRenderer`, `GenericMcpToolRenderer`, `DataToolRow`, `ToolActivity`, `FilePath`, diff helpers | Your product renders tool cards (insights, dashboards…). Declare them in your product list and include it in the central manifest. |
The Tier 1 surfaces are built on `api/primitives` (Tier 2), which consumes the headless
`api/logics`/`api/types` (Tier 3). Going down a tier trades convenience for control and a smaller chunk.
@@ -162,20 +162,49 @@ import { Thread } from 'products/posthog_ai/frontend/api/primitives'
;<Thread.Root items={items}>{(item) => <Thread.Message item={item} />}</Thread.Root>
```
-### Register product tool renderers (Tier 4)
+### Declare product tool renderers (Tier 4)
+
+Export a typed declaration list from `products/<product>/frontend/posthogAiToolRenderers.tsx`.
+Add one direct import and one spread to `frontend/src/posthogAiToolRenderers.ts` for your product.
+Keep individual entries with their product; import no scenes or broad component barrels from declaration modules.
+Use **type-only** imports from `api/tools` for the contract, so declarations cannot create a runtime cycle with the registry.
+
+The registry initializes synchronously from built-ins and this manifest before rendering.
+The manifest is the sole extension mechanism: there is no runtime registration, subscription, or asynchronous initialization.
+`toolRegistry.lookup` and `lookupToolRenderer` remain available; keep headless `api/logics` and `api/types` free of registry imports.
```tsx
-import { registerToolRenderers, type ToolRegistryEntry } from 'products/posthog_ai/frontend/api/tools'
+import { IconBolt } from '@posthog/icons'
+
+import { lazyWithRetry } from 'lib/utils/retryImport'
-// Call once from your scene's entrypoint. Tools without an adapter fall through to the generic MCP card.
-registerToolRenderers([
- { key: 'my-product-tool', displayName: 'My tool', icon: <IconWrench />, Renderer: MyToolRenderer },
-])
+import type { ToolRegistryEntry } from 'products/posthog_ai/frontend/api/tools'
+
+export const posthogAiToolRenderers: ToolRegistryEntry[] = [
+ {
+ key: 'cdp-functions-partial-update',
+ displayName: 'Update function',
+ icon: <IconBolt />,
+ PermissionPreview: lazyWithRetry(() =>
+ import('./HogFunctionPermissionPreview').then((m) => ({ default: m.HogFunctionPermissionPreview }))
+ ),
+ requiresPostHogOrigin: true,
+ },
+]
```
-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.
+`PermissionPreview` receives `{ request, fallback }`, typed as `PermissionPreviewProps` from `api/tools`.
+Return `fallback` when there is no available matching mounted configuration or no changes to show.
+Do not mount or fetch a product scene to produce a preview.
+`PermissionInput` supplies its evidence block as fallback, and wraps the preview in `Suspense` and `PostHogErrorBoundary`.
+Both boundaries use that evidence fallback; approval controls remain outside them and stay usable during loading or failure.
+Errors retain the `posthog_ai_permission_preview` feature tag, and a new permission request resets the error boundary.
+
+Insights, dashboards, recordings, notebooks, and query widgets live in `components/tool/widgets/`, with lazy declarations in the frontend-root `posthogAiToolRenderers.tsx`. This declaration list is a product contribution, outside the reusable `api/` facade.
+Error tracking owns its widget family and declaration list in `products/error_tracking/frontend/`; replay vision owns its scan widget and polling logic in `products/replay_vision/frontend/posthogAi/`.
+Product-owned tool adapters consume `ToolRendererProps`, `DataToolRow`, `GenericMcpToolRenderer`, and `parseToolOutputRecord` through `api/tools`. Shared frontend dependencies are allowed; widget-specific product internals stay with their owner.
+CDP's `products/cdp/frontend/posthogAiToolRenderers.tsx` declares a preview-only entry; its result card stays generic.
+Set `requiresPostHogOrigin: true` for product entries; unknown or untrusted colliding keys use generic cards and evidence.
### Headless status badge / automation
diff --git a/products/posthog_ai/frontend/api/primitives.ts b/products/posthog_ai/frontend/api/primitives.ts
index bd437a219ac4..e10a28b5ee74 100644
--- a/products/posthog_ai/frontend/api/primitives.ts
+++ b/products/posthog_ai/frontend/api/primitives.ts
@@ -95,6 +95,3 @@ export type { Option } from '../components/OptionSelector'
export { VisualizationWidget, getArtifactOpenTarget } from '../components/tool/widgets/VisualizationWidget'
export type { VisualizationWidgetProps } from '../components/tool/widgets/VisualizationWidget'
export { RecordingsWidget } from '../components/tool/widgets/RecordingsWidget'
-export { ReplayVisionScanWidget } from '../components/tool/widgets/ReplayVisionScanWidget'
-export { ErrorTrackingFiltersWidget } from '../components/tool/widgets/ErrorTrackingFiltersWidget'
-export { ErrorTrackingIssueCard } from '../components/tool/widgets/ErrorTrackingIssueCard'
diff --git a/products/posthog_ai/frontend/api/tools.ts b/products/posthog_ai/frontend/api/tools.ts
index ee76fc533cd6..d9f920c9e330 100644
--- a/products/posthog_ai/frontend/api/tools.ts
+++ b/products/posthog_ai/frontend/api/tools.ts
@@ -1,12 +1,12 @@
-export { toolRegistry, lookupToolRenderer, registerToolRenderers } from '../components/tool/toolRegistry'
+export { toolRegistry, lookupToolRenderer } from '../components/tool/toolRegistry'
export type {
ToolRendererProps,
+ PermissionPreviewProps,
ToolRegistryEntry,
ResolvedToolRegistryEntry,
ToolRegistry,
} from '../components/tool/toolRegistry'
export { getPermissionRequestToolInput, resolveToolCall } from '../utils/toolResolver'
-export { parseToolOutputRecord, asRecord } from '../components/tool/parseToolOutput'
export { GenericMcpToolRenderer } from '../components/tool/GenericMcpToolRenderer'
export { DataToolRow } from '../components/tool/DataToolRow'
export { ToolActivity } from '../components/tool/ToolActivity'
@@ -16,3 +16,5 @@ export { findAllDiffContent, getDiffStats, languageFromPath } from '../component
export type { ToolCallDiffContent } from '../components/tool/toolDiffContent'
export { DiffEvidenceCard } from '../components/tool/DiffEvidenceCard'
export type { DiffEvidenceCardProps } from '../components/tool/DiffEvidenceCard'
+export { parseToolOutputRecord, asRecord } from '../components/tool/parseToolOutputRecord'
+export { MessageTemplate } from '../messages/MessageTemplate'
diff --git a/products/posthog_ai/frontend/components/PermissionInput.stories.tsx b/products/posthog_ai/frontend/components/PermissionInput.stories.tsx
new file mode 100644
index 000000000000..eb534fc55fa2
--- /dev/null
+++ b/products/posthog_ai/frontend/components/PermissionInput.stories.tsx
@@ -0,0 +1,94 @@
+import type { Meta, StoryObj } from '@storybook/react'
+import { useEffect, useState } from 'react'
+
+import type { PermissionRequestRecord } from '../types/streamTypes'
+import { PermissionInput } from './PermissionInput'
+
+const request: PermissionRequestRecord = {
+ requestId: 'synthetic-permission',
+ toolCallId: 'synthetic-update',
+ toolName: 'mcp__posthog__exec',
+ options: [
+ { optionId: 'allow', name: 'Allow', kind: 'allow_once' },
+ { optionId: 'reject', name: 'Decline', kind: 'reject_once' },
+ ],
+ rawToolCall: {
+ toolCallId: 'synthetic-update',
+ rawServerName: 'posthog',
+ rawToolName: 'exec',
+ input: { command: 'call cdp-functions-partial-update {"id":"new","name":"Updated destination"}' },
+ status: 'pending',
+ contentBlocks: [],
+ },
+}
+
+const meta: Meta<typeof PermissionInput> = {
+ title: 'Products/PostHog AI/PermissionInput',
+ component: PermissionInput,
+ args: { streamKey: 'synthetic-preview', request },
+ decorators: [
+ (Story) => (
+ <div className="w-128 border rounded">
+ <Story />
+ </div>
+ ),
+ ],
+}
+export default meta
+
+type Story = StoryObj<typeof meta>
+
+export const NoMountedConfiguration: Story = {}
+
+export const MatchingConfiguration: Story = {
+ decorators: [
+ (Story) => {
+ const [ready, setReady] = useState(false)
+ useEffect(() => {
+ let disposed = false
+ let unmount: (() => void) | undefined
+ void import('scenes/hog-functions/configuration/hogFunctionConfigurationLogic').then(
+ ({ hogFunctionConfigurationLogic }) => {
+ if (disposed) {
+ return
+ }
+ const logic = hogFunctionConfigurationLogic({ id: 'new' })
+ unmount = logic.mount()
+ logic.actions.loadHogFunctionSuccess({
+ id: 'new',
+ type: 'destination',
+ name: 'Original destination',
+ description: '',
+ enabled: true,
+ hog: '',
+ created_by: null,
+ created_at: '2026-01-01T00:00:00Z',
+ updated_at: '2026-01-01T00:00:00Z',
+ })
+ setReady(true)
+ }
+ )
+ return () => {
+ disposed = true
+ unmount?.()
+ }
+ }, [])
+ return ready ? <Story /> : <div>Preparing configuration fixture</div>
+ },
+ ],
+}
+
+export const MismatchedConfiguration: Story = {
+ ...MatchingConfiguration,
+ args: {
+ request: {
+ ...request,
+ rawToolCall: {
+ ...request.rawToolCall,
+ input: {
+ command: 'call cdp-functions-partial-update {"id":"another-function","name":"Updated destination"}',
+ },
+ },
+ },
+ },
+}
diff --git a/products/posthog_ai/frontend/components/PermissionInput.test.tsx b/products/posthog_ai/frontend/components/PermissionInput.test.tsx
index 596128d8dea9..2260685507e7 100644
--- a/products/posthog_ai/frontend/components/PermissionInput.test.tsx
+++ b/products/posthog_ai/frontend/components/PermissionInput.test.tsx
@@ -1,14 +1,22 @@
import '@testing-library/jest-dom'
-import { cleanup, fireEvent, render, screen } from '@testing-library/react'
+import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'
import { useActions, useValues } from 'kea'
+import posthog from 'posthog-js'
+import { lazy, type ComponentType } from 'react'
+import type { PermissionPreviewProps } from '../api/tools'
import type { PermissionRequestRecord } from '../types/streamTypes'
import { PermissionInput } from './PermissionInput'
+import { lookupToolRenderer } from './tool/toolRegistry'
-jest.mock('kea', () => ({ ...jest.requireActual('kea'), useActions: jest.fn(), useValues: jest.fn() }))
+jest.mock('kea', () => ({
+ ...jest.requireActual<typeof import('kea')>('kea'),
+ useActions: jest.fn(),
+ useValues: jest.fn(),
+}))
jest.mock('../logics/runStreamLogic', () => ({ runStreamLogic: jest.fn(() => ({})) }))
-jest.mock('./tool/toolRegistry', () => ({ lookupToolRenderer: () => ({}) }))
+jest.mock('./tool/toolRegistry', () => ({ lookupToolRenderer: jest.fn(() => ({})) }))
describe('PermissionInput', () => {
const respondToPermission = jest.fn()
@@ -16,6 +24,7 @@ describe('PermissionInput', () => {
beforeEach(() => {
jest.clearAllMocks()
+ jest.mocked(lookupToolRenderer).mockReturnValue({} as ReturnType<typeof lookupToolRenderer>)
localStorage.clear()
;(useActions as jest.Mock).mockReturnValue({ respondToPermission, cancelRun })
;(useValues as jest.Mock).mockReturnValue({ respondingToPermission: false })
@@ -72,4 +81,97 @@ describe('PermissionInput', () => {
expect(respondToPermission).toHaveBeenCalledTimes(2)
}
)
+ const previewRequest: PermissionRequestRecord = {
+ requestId: 'preview-1',
+ toolCallId: 'preview-tool-1',
+ toolName: 'Bash',
+ options: [
+ { optionId: 'allow', name: 'Allow', kind: 'allow_once' },
+ { optionId: 'reject', name: 'Decline', kind: 'reject_once' },
+ ],
+ rawToolCall: {
+ toolCallId: 'preview-tool-1',
+ rawServerName: 'claude',
+ rawToolName: 'Bash',
+ input: { command: 'echo synthetic-evidence' },
+ status: 'pending',
+ contentBlocks: [],
+ },
+ }
+
+ it('keeps evidence and approval controls usable while a lazy preview loads', async () => {
+ let resolvePreview!: (value: { default: ComponentType<PermissionPreviewProps> }) => void
+ const PermissionPreview = lazy(
+ () =>
+ new Promise<{ default: ComponentType<PermissionPreviewProps> }>((resolve) => {
+ resolvePreview = resolve
+ })
+ )
+ jest.mocked(lookupToolRenderer).mockReturnValue({ PermissionPreview } as ReturnType<typeof lookupToolRenderer>)
+ render(<PermissionInput streamKey="run-1" request={previewRequest} />)
+ expect(screen.getByText(/echo synthetic-evidence/)).toBeInTheDocument()
+ fireEvent.click(screen.getByText('Allow'))
+ expect(respondToPermission).toHaveBeenLastCalledWith({
+ requestId: 'preview-1',
+ optionId: 'allow',
+ customInput: undefined,
+ })
+
+ await act(async () => resolvePreview({ default: ({ request }) => <div>Preview for {request.requestId}</div> }))
+ expect(screen.getByText('Preview for preview-1')).toBeInTheDocument()
+ expect(screen.queryByText(/echo synthetic-evidence/)).not.toBeInTheDocument()
+ fireEvent.keyDown(document.body, { key: '2' })
+ expect(respondToPermission).toHaveBeenLastCalledWith({
+ requestId: 'preview-1',
+ optionId: 'reject',
+ customInput: undefined,
+ })
+ })
+
+ it.each(['render', 'load'])('falls back after a preview %s error and keeps approvals usable', async (failure) => {
+ const error = new Error('Synthetic preview failure')
+ const capture = jest.spyOn(posthog, 'captureException').mockImplementation(() => undefined)
+ const consoleError = jest.spyOn(console, 'error').mockImplementation(() => {})
+ const PermissionPreview =
+ failure === 'load'
+ ? lazy(() => Promise.reject(error))
+ : ({ request }: PermissionPreviewProps): JSX.Element => {
+ if (request.requestId === 'preview-1') {
+ throw error
+ }
+ return <div>Recovered preview</div>
+ }
+ jest.mocked(lookupToolRenderer).mockReturnValue({ PermissionPreview } as ReturnType<typeof lookupToolRenderer>)
+ try {
+ const { rerender } = render(<PermissionInput streamKey="run-1" request={previewRequest} />)
+ await waitFor(() =>
+ expect(capture).toHaveBeenCalledWith(
+ error,
+ expect.objectContaining({ feature: 'posthog_ai_permission_preview' })
+ )
+ )
+ expect(screen.getByText(/echo synthetic-evidence/)).toBeInTheDocument()
+ fireEvent.keyDown(document.body, { key: '1' })
+ expect(respondToPermission).toHaveBeenCalledWith({
+ requestId: 'preview-1',
+ optionId: 'allow',
+ customInput: undefined,
+ })
+ const NextPreview = failure === 'load' ? () => <div>Recovered preview</div> : PermissionPreview
+ jest.mocked(lookupToolRenderer).mockReturnValue({ PermissionPreview: NextPreview } as ReturnType<
+ typeof lookupToolRenderer
+ >)
+ rerender(<PermissionInput streamKey="run-1" request={{ ...previewRequest, requestId: 'preview-2' }} />)
+ expect(screen.getByText('Recovered preview')).toBeInTheDocument()
+ fireEvent.click(screen.getByText('Decline'))
+ expect(respondToPermission).toHaveBeenLastCalledWith({
+ requestId: 'preview-2',
+ optionId: 'reject',
+ customInput: undefined,
+ })
+ } finally {
+ capture.mockRestore()
+ consoleError.mockRestore()
+ }
+ })
})
diff --git a/products/posthog_ai/frontend/components/PermissionInput.tsx b/products/posthog_ai/frontend/components/PermissionInput.tsx
index 61c419099aa5..c48a9f826648 100644
--- a/products/posthog_ai/frontend/components/PermissionInput.tsx
+++ b/products/posthog_ai/frontend/components/PermissionInput.tsx
@@ -1,10 +1,9 @@
import { useActions, useValues } from 'kea'
-import posthog from 'posthog-js'
-import type { ReactNode } from 'react'
-import { useEffect, useRef, useState } from 'react'
+import { Suspense, useEffect, useRef, useState } from 'react'
import { IconWarning } from '@posthog/icons'
import { Button } from '@posthog/quill-primitives'
+import { PostHogErrorBoundary } from '@posthog/react'
import { CodeSnippet, Language } from 'lib/components/CodeSnippet'
import { cn } from 'lib/utils/css-classes'
@@ -31,21 +30,6 @@ interface PermissionInputProps {
/** Collapsed height of the payload preview, in lines — enough to scan, never enough to bury the choices. */
const PAYLOAD_COLLAPSED_LINES = 12
-/**
- * Resolves the request's inner sub-tool and, if a registered entry provides a `renderPermissionPreview`,
- * returns its node (else null). Isolated + guarded so a throwing product preview can never break the
- * approval card — the card falls back to the generic evidence block.
- */
-function renderRegisteredPermissionPreview(request: PermissionRequestRecord): ReactNode | null {
- try {
- const { resolvedKey, innerToolName } = resolveToolCall(request.rawToolCall)
- return lookupToolRenderer(resolvedKey, innerToolName != null).renderPermissionPreview?.(request) ?? null
- } catch (error) {
- posthog.captureException(error, { feature: 'posthog_ai_permission_preview' })
- return null
- }
-}
-
const FEEDBACK_PLACEHOLDER = 'Tell the agent what to do differently'
interface PermissionEvidenceProps {
@@ -462,23 +446,35 @@ function PlanPermissionInput({
}
interface GenericPermissionInputProps {
+ streamKey: string
options: ApprovalCardOption[]
request: PermissionRequestRecord
responding: boolean
onRespond: (optionId: string, customInput?: string) => void
}
-function GenericPermissionInput({ options, request, responding, onRespond }: GenericPermissionInputProps): JSX.Element {
+function GenericPermissionInput({
+ streamKey,
+ options,
+ request,
+ responding,
+ onRespond,
+}: GenericPermissionInputProps): JSX.Element {
const display = getPermissionDisplay(request)
// Only a genuine wire-level description that says more than the tool title becomes the
// headline; a title-only request keeps the derived tool title as its headline (and the
// evidence block skips its label) so the tool identity is stated exactly once.
const headlineBody = request.description && request.description !== display.title ? request.description : undefined
- // A product may register a richer approval preview (e.g. a config diff) for the resolved sub-tool
- // via the tool registry. When it returns a node, it takes the evidence slot; a null return (or a
- // throwing preview, or no registered preview) falls back to the generic evidence block.
- const previewNode = renderRegisteredPermissionPreview(request)
+ const { resolvedKey, innerToolName } = resolveToolCall(request.rawToolCall)
+ const { PermissionPreview } = lookupToolRenderer(resolvedKey, innerToolName != null)
+ const evidence = (
+ <PermissionEvidence
+ request={request}
+ label={headlineBody ? display.title : undefined}
+ payload={display.payload}
+ />
+ )
return (
<div className="flex flex-col gap-2.5 p-3">
@@ -492,14 +488,18 @@ function GenericPermissionInput({ options, request, responding, onRespond }: Gen
<span>{display.title ?? 'Approval required'}</span>
)}
</div>
- {previewNode ? (
- <div className="max-h-80 overflow-y-auto">{previewNode}</div>
+ {PermissionPreview ? (
+ <PostHogErrorBoundary
+ key={`${streamKey}:${request.requestId}`}
+ additionalProperties={{ feature: 'posthog_ai_permission_preview' }}
+ fallback={evidence}
+ >
+ <Suspense fallback={evidence}>
+ <PermissionPreview request={request} fallback={evidence} />
+ </Suspense>
+ </PostHogErrorBoundary>
) : (
- <PermissionEvidence
- request={request}
- label={headlineBody ? display.title : undefined}
- payload={display.payload}
- />
+ evidence
)}
<PermissionOptionRows options={options} responding={responding} onRespond={onRespond} />
</div>
@@ -541,6 +541,7 @@ export function PermissionInput({ streamKey, request, disabled = false }: Permis
return (
<GenericPermissionInput
+ streamKey={streamKey}
options={mappedOptions}
request={request}
responding={respondingToPermission}
diff --git a/products/posthog_ai/frontend/components/ThreadView.stories.tsx b/products/posthog_ai/frontend/components/ThreadView.stories.tsx
new file mode 100644
index 000000000000..32fd06760414
--- /dev/null
+++ b/products/posthog_ai/frontend/components/ThreadView.stories.tsx
@@ -0,0 +1,130 @@
+import type { Meta, StoryObj } from '@storybook/react'
+import { BindLogic } from 'kea'
+import { useEffect } from 'react'
+
+import { mswDecorator } from '~/mocks/browser'
+
+import { runStreamLogic } from '../logics/runStreamLogic'
+import { ThreadView } from './ThreadView'
+
+interface ThreadFixtureProps {
+ streamKey: string
+ toolName: string
+ title: string
+ rawOutput: unknown
+}
+
+const meta: Meta<ThreadFixtureProps> = {
+ title: 'Products/PostHog AI/ThreadView',
+ args: {
+ streamKey: 'synthetic-conversation',
+ toolName: 'notebooks-create',
+ title: 'Create notebook',
+ rawOutput: { short_id: 'example-notebook', title: 'Synthetic notebook' },
+ },
+ render: ({ streamKey, toolName, title, rawOutput }) => {
+ useEffect(() => {
+ const logic = runStreamLogic({ streamKey })
+ const unmount = logic.mount()
+ logic.actions.ingestAcpFrame(
+ {
+ type: 'notification',
+ notification: {
+ method: 'session/update',
+ params: {
+ update: {
+ sessionUpdate: 'tool_call',
+ toolCallId: 'synthetic-tool-call',
+ title,
+ serverName: 'posthog',
+ toolName: 'exec',
+ status: 'in_progress',
+ rawInput: { command: `call ${toolName} {}` },
+ _meta: { claudeCode: { toolName: 'mcp__posthog__exec' } },
+ },
+ },
+ },
+ },
+ 'replay'
+ )
+ logic.actions.ingestAcpFrame(
+ {
+ type: 'notification',
+ notification: {
+ method: 'session/update',
+ params: {
+ update: {
+ sessionUpdate: 'tool_call_update',
+ toolCallId: 'synthetic-tool-call',
+ status: 'completed',
+ rawOutput,
+ },
+ },
+ },
+ },
+ 'replay'
+ )
+ return unmount
+ }, [streamKey, toolName, title, rawOutput])
+ return (
+ <div className="w-180 h-160 border rounded">
+ <BindLogic logic={runStreamLogic} props={{ streamKey }}>
+ <ThreadView />
+ </BindLogic>
+ </div>
+ )
+ },
+}
+export default meta
+
+type Story = StoryObj<typeof meta>
+
+export const ColdConversation: Story = {}
+export const ColdTask: Story = { args: { streamKey: 'synthetic-task-run' } }
+
+export const ErrorTracking: Story = {
+ args: {
+ toolName: 'query-error-tracking-issues-list',
+ title: 'Search error tracking issues',
+ rawOutput: {
+ results: [
+ {
+ id: '0199c0de-1111-7000-8000-0000000000aa',
+ name: 'Synthetic checkout error',
+ description: 'Example checkout request failed',
+ status: 'active',
+ library: 'web',
+ aggregations: { occurrences: 12, users: 3 },
+ },
+ ],
+ hasMore: false,
+ },
+ },
+}
+
+export const SavedInsightQuery: Story = {
+ args: {
+ toolName: 'insight-query',
+ title: 'Query saved insight',
+ rawOutput: {
+ query: { kind: 'HogQLQuery', query: 'SELECT 4242 AS value' },
+ insight: { name: 'Synthetic saved insight', url: '/project/1/insights/example' },
+ results: { columns: ['value'], results: [[4242]] },
+ _posthogUrl: '/project/1/insights/example',
+ },
+ },
+ decorators: [
+ mswDecorator({
+ post: {
+ '/api/environments/:team_id/query/': () => [
+ 200,
+ { results: [[4242]], columns: ['value'], types: [['value', 'UInt16']] },
+ ],
+ '/api/environments/:team_id/query/:query_kind/': () => [
+ 200,
+ { results: [[4242]], columns: ['value'], types: [['value', 'UInt16']] },
+ ],
+ },
+ }),
+ ],
+}
diff --git a/products/posthog_ai/frontend/components/tool/ToolCallCard.tsx b/products/posthog_ai/frontend/components/tool/ToolCallCard.tsx
index 1e443dc1ac75..6eacd9ec696a 100644
--- a/products/posthog_ai/frontend/components/tool/ToolCallCard.tsx
+++ b/products/posthog_ai/frontend/components/tool/ToolCallCard.tsx
@@ -1,8 +1,3 @@
-// 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'
diff --git a/products/posthog_ai/frontend/components/tool/parseToolOutput.ts b/products/posthog_ai/frontend/components/tool/parseToolOutputRecord.ts
similarity index 73%
rename from products/posthog_ai/frontend/components/tool/parseToolOutput.ts
rename to products/posthog_ai/frontend/components/tool/parseToolOutputRecord.ts
index 7acc0989e78c..60c2e216998e 100644
--- a/products/posthog_ai/frontend/components/tool/parseToolOutput.ts
+++ b/products/posthog_ai/frontend/components/tool/parseToolOutputRecord.ts
@@ -1,16 +1,9 @@
import { decode } from '@toon-format/toon'
-import type { ToolCallMessage } from 'products/posthog_ai/frontend/types/toolTypes'
-
+import type { ToolCallMessage } from '../../types/toolTypes'
import { parseExecCall, parseExecCommand } from './posthogExecDisplay'
import { getAllText } from './toolContentUtils'
-/**
- * Generic tool-output parsing, kept free of the entity-specific extractors so a product widget can
- * parse a tool's result through the `api/tools` facade without pulling the recordings / error-tracking
- * conversion deps that `widgets/extractors.ts` carries.
- */
-
export function asRecord(value: unknown): Record<string, unknown> | null {
return value && typeof value === 'object' && !Array.isArray(value) ? (value as Record<string, unknown>) : null
}
@@ -56,12 +49,7 @@ function unwrapToolOutput(rawOutput: unknown): unknown {
}
/**
- * Best-effort record from a tool call's `rawOutput`. Objects pass through; strings are parsed per the
- * exec `call` output contract: `--json` means the server responded with `JSON.stringify`, otherwise
- * TOON (`services/mcp/src/lib/response.ts`). The off-order format is still tried as a fallback, and
- * anything unparseable (or empty) resolves to null so the caller falls back to the generic card.
- * An MCP result envelope is unwrapped first, preferring its structured content because the text can be
- * an optimized summary without the entity fields.
+ * Prefer structured content because the text can be an optimized summary without the entity fields.
*/
export function parseToolOutputRecord(message: ToolCallMessage): Record<string, unknown> | null {
const rawOutput = unwrapToolOutput(message.rawOutput)
diff --git a/products/posthog_ai/frontend/components/tool/toolRegistry.test.tsx b/products/posthog_ai/frontend/components/tool/toolRegistry.test.tsx
index 394203dc2d61..2bb85d3270e7 100644
--- a/products/posthog_ai/frontend/components/tool/toolRegistry.test.tsx
+++ b/products/posthog_ai/frontend/components/tool/toolRegistry.test.tsx
@@ -1,12 +1,10 @@
import '@testing-library/jest-dom'
-import { fireEvent, render, screen } from '@testing-library/react'
-import type { ReactNode } from 'react'
+import { fireEvent, render, screen, within } from '@testing-library/react'
import type { ToolCallMessage } from 'products/posthog_ai/frontend/types/toolTypes'
-import { ToolCallCard } from './ToolCallCard'
-import { lookupToolRenderer, registerToolRenderers, toolRegistry, type ToolRegistryEntry } from './toolRegistry'
+import { lookupToolRenderer, toolRegistry } from './toolRegistry'
function makeMessage(overrides: Partial<ToolCallMessage> = {}): ToolCallMessage {
return {
@@ -22,46 +20,29 @@ function makeMessage(overrides: Partial<ToolCallMessage> = {}): ToolCallMessage
}
describe('toolRegistry', () => {
- // 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']
- const icon = null as unknown as JSX.Element
- registerToolRenderers([
- { key: '__test_alpha__', displayName: 'Alpha', icon, Renderer },
- { key: '__test_beta__', displayName: 'Beta', icon, Renderer },
- ])
- expect(toolRegistry.lookup('__test_alpha__')?.displayName).toEqual('Alpha')
- expect(toolRegistry.lookup('__test_beta__')?.displayName).toEqual('Beta')
- })
-
- 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.
+ it('resolves product declarations after importing only the registry', () => {
expect(toolRegistry.lookup('insight-create')?.displayName).toEqual('Insight')
expect(toolRegistry.lookup('query-trends')?.displayName).toEqual('Trends query')
+ expect(toolRegistry.lookup('query-error-tracking-issues-list')?.displayName).toEqual('Error tracking')
+ expect(
+ require.cache[require.resolve('products/error_tracking/frontend/posthogAi/ErrorTrackingWidget')]
+ ).toBeUndefined()
+ expect(require.cache[require.resolve('./widgets/QueryWidget')]).toBeUndefined()
+ expect(require.cache[require.resolve('./ToolCallCard')]).toBeUndefined()
+ expect(
+ require.cache[require.resolve('scenes/hog-functions/configuration/HogFunctionConfiguration')]
+ ).toBeUndefined()
+ expect(require.cache[require.resolve('products/cdp/frontend/HogFunctionPermissionPreview')]).toBeUndefined()
+ expect(require.cache[require.resolve('./widgets/CreateNotebookWidget')]).toBeUndefined()
})
- // The permission-preview seam: a preview-only entry (no Renderer) still resolves a card renderer,
- // and its `renderPermissionPreview` survives `lookupToolRenderer` so `PermissionInput` can call it;
- // an unregistered tool exposes none, so the approval card falls back to the raw JSON payload.
- it('preserves a registered renderPermissionPreview through lookupToolRenderer and defaults its Renderer', () => {
- const preview = jest.fn((): ReactNode => 'PREVIEW_NODE')
- registerToolRenderers([
- {
- key: '__test_preview__',
- displayName: 'Preview tool',
- icon: null as unknown as JSX.Element,
- renderPermissionPreview: preview,
- },
- ])
- const resolved = lookupToolRenderer('__test_preview__', false)
- expect(resolved.Renderer).not.toBeUndefined()
- expect(resolved.renderPermissionPreview).toBe(preview)
- expect(lookupToolRenderer('__unregistered_preview__', false).renderPermissionPreview).toBeUndefined()
+ it('preserves the declared CDP preview and defaults its result card', () => {
+ const resolved = lookupToolRenderer('cdp-functions-partial-update', true)
+ expect(resolved.Renderer).toBe(lookupToolRenderer('__unknown__', false).Renderer)
+ expect(resolved.PermissionPreview).toBe(toolRegistry.lookup('cdp-functions-partial-update')?.PermissionPreview)
+ expect(resolved.PermissionPreview).not.toBeUndefined()
+ expect(lookupToolRenderer('cdp-functions-partial-update', false).PermissionPreview).toBeUndefined()
+ expect(lookupToolRenderer('__unknown__', false).PermissionPreview).toBeUndefined()
})
it('falls back to the key as displayName for unknown and unmapped tool names', () => {
@@ -72,9 +53,14 @@ describe('toolRegistry', () => {
)
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()
+ expect(toolRegistry.lookup('search_error_tracking_issues')).toBeNull()
+ expect(toolRegistry.lookup('filter_error_tracking_issues')).toBeNull()
+ expect(toolRegistry.lookup('create_insight')).toBeNull()
+ expect(toolRegistry.lookup('upsert_dashboard')).toBeNull()
+ expect(toolRegistry.lookup('search_session_recordings')).toBeNull()
+ expect(toolRegistry.lookup('filter_session_recordings')).toBeNull()
})
// A user-installed MCP server can expose a tool whose bare name collides with a product-widget key
@@ -85,6 +71,8 @@ describe('toolRegistry', () => {
['notebooks-create', 'Notebook'],
['dashboard-create', 'Dashboard'],
['query-trends', 'Trends query'],
+ ['insight-query', 'Insight query'],
+ ['query-error-tracking-issues-list', 'Error tracking'],
])('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)
@@ -121,6 +109,7 @@ describe('toolRegistry', () => {
const entry = toolRegistry.lookup(key)
expect(entry).not.toBeNull()
expect(entry?.displayName).toEqual(displayName)
+ expect(entry?.keepVisible ?? false).toBe(['ExitPlanMode', 'AskUserQuestion'].includes(key))
expect(lookupToolRenderer(key, false).displayName).toEqual(displayName)
})
@@ -149,8 +138,27 @@ describe('toolRegistry', () => {
// Render-level: ToolCallCard resolves the entry, loads the lazy renderer behind a Suspense
// skeleton, and the resolved renderer reaches the screen. The skeleton shows the displayName first.
describe('lazy dispatch', () => {
- it('renders a Bash call through its dedicated card once the chunk loads', async () => {
+ it('loads a product implementation only when its matching card renders', async () => {
+ const { ToolCallCard } = await import('./ToolCallCard')
+ expect(require.cache[require.resolve('./widgets/CreateNotebookWidget')]).toBeUndefined()
render(
+ <ToolCallCard
+ message={makeMessage({
+ resolvedKey: 'notebooks-create',
+ innerToolName: 'notebooks-create',
+ rawOutput: { short_id: 'example-notebook', title: 'Synthetic notebook' },
+ })}
+ />
+ )
+ expect(screen.getByText('Notebook')).toBeInTheDocument()
+ expect(await screen.findByText('Synthetic notebook')).toBeInTheDocument()
+ expect(screen.queryByText('Notebook')).not.toBeInTheDocument()
+ expect(require.cache[require.resolve('./widgets/CreateNotebookWidget')]).not.toBeUndefined()
+ })
+
+ it('renders a Bash call through its dedicated card once the chunk loads', async () => {
+ const { ToolCallCard } = await import('./ToolCallCard')
+ const { container } = render(
<ToolCallCard
message={makeMessage({
resolvedKey: 'Bash',
@@ -162,11 +170,12 @@ describe('toolRegistry', () => {
// Skeleton first (registry displayName), then the resolved card whose header expands to the
// command. The generous timeout covers jest compiling the lazy chunk's heavy deps on first load.
expect(screen.getByText('Terminal')).toBeInTheDocument()
- fireEvent.click(await screen.findByRole('button', {}, { timeout: 10000 }))
- expect(screen.getByText('echo hello-bash')).toBeInTheDocument()
+ fireEvent.click(await within(container).findByRole('button', {}, { timeout: 10000 }))
+ expect(within(container).getByText('echo hello-bash')).toBeInTheDocument()
})
it('renders an unmapped MCP tool through the generic card', async () => {
+ const { ToolCallCard } = await import('./ToolCallCard')
render(
<ToolCallCard
message={makeMessage({
diff --git a/products/posthog_ai/frontend/components/tool/toolRegistry.tsx b/products/posthog_ai/frontend/components/tool/toolRegistry.tsx
index 7bf81d4962e8..3d66d2607925 100644
--- a/products/posthog_ai/frontend/components/tool/toolRegistry.tsx
+++ b/products/posthog_ai/frontend/components/tool/toolRegistry.tsx
@@ -20,6 +20,8 @@ import {
import { IconRobot } from 'lib/lemon-ui/icons'
import { lazyWithRetry } from 'lib/utils/retryImport'
+import { posthogAiToolRenderers } from '~/posthogAiToolRenderers'
+
import type { PermissionRequestRecord } from 'products/posthog_ai/frontend/types/streamTypes'
import type { ToolCallMessage } from 'products/posthog_ai/frontend/types/toolTypes'
@@ -55,20 +57,12 @@ export interface ToolRegistryEntry {
/** Display name / icon for fallback rendering and for the tool-call header line. */
displayName: string
icon: JSX.Element
- /**
- * Tool-result card renderer. Optional so a product can register a **preview-only** entry (just a
- * `renderPermissionPreview`) without also claiming the result card — such entries fall back to the
- * generic built-in card via `lookupToolRenderer`.
- */
+ /** Preview-only entries use the generic result card. */
Renderer?: ToolRendererComponent
- /**
- * Optional approval-card preview. When a pending permission request resolves to this tool,
- * `PermissionInput` calls this with the request and renders the returned node in place of the raw
- * JSON payload. Returning null falls back to the JSON payload — e.g. the owning scene isn't mounted,
- * so there's nothing to diff against. The generic surface never enumerates products here; a product
- * registers its own preview via `registerToolRenderers` from its scene entrypoint.
- */
- renderPermissionPreview?: (record: PermissionRequestRecord) => ReactNode | null
+ /** Return fallback when the product has no matching state to preview. */
+ PermissionPreview?:
+ | ComponentType<PermissionPreviewProps>
+ | LazyExoticComponent<ComponentType<PermissionPreviewProps>>
/**
* 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
@@ -86,21 +80,13 @@ export interface ResolvedToolRegistryEntry extends ToolRegistryEntry {
Renderer: ToolRendererComponent
}
-export interface ToolRegistry {
- register: (entry: ToolRegistryEntry) => void
- lookup: (toolName: string) => ToolRegistryEntry | null
+export interface PermissionPreviewProps {
+ request: PermissionRequestRecord
+ fallback: ReactNode
}
-class MapBackedRegistry implements ToolRegistry {
- private entries = new Map<string, ToolRegistryEntry>()
-
- register(entry: ToolRegistryEntry): void {
- this.entries.set(entry.key, entry)
- }
-
- lookup(toolName: string): ToolRegistryEntry | null {
- return this.entries.get(toolName) ?? null
- }
+export interface ToolRegistry {
+ lookup: (toolName: string) => ToolRegistryEntry | null
}
// Renderers are code-split: the static graph below carries only icons, types, and lazy factories, so a
@@ -120,29 +106,6 @@ const PostHogCodeToolRenderer = lazyWithRetry(() =>
import('./posthogCodeToolRenderers').then((m) => ({ default: m.PostHogCodeToolRenderer }))
)
-/**
- * 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 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 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) {
- toolRegistry.register(entry)
- }
-}
-
-// Product-specific data-tool renderers (insight, dashboard, session recordings, error tracking,
-// 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
// get a dedicated per-tool card; the rest fall through to the generic MCP card — all inside the single
@@ -165,23 +128,6 @@ const BUILTIN_TOOLS: { keys: string[]; displayName: string; icon: JSX.Element }[
{ 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) {
- toolRegistry.register({
- key,
- displayName,
- icon,
- Renderer: BuiltinToolRenderer,
- keepVisible: key === 'ExitPlanMode',
- })
- }
-}
-
-// 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']) {
- toolRegistry.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
@@ -193,9 +139,6 @@ const POSTHOG_EXEC_VERBS: { key: string; displayName: string; icon: JSX.Element
{ 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) {
- toolRegistry.register({ key, displayName, icon, Renderer: BuiltinToolRenderer })
-}
// posthog-code-tools — the coding agent's git/repo MCP tools. Registered under both the bare name and
// the `mcp__<server>__` qualified name because `resolveToolKey` yields the qualified form on the
@@ -211,21 +154,40 @@ const POSTHOG_CODE_TOOLS: { name: string; displayName: string; icon: JSX.Element
{ name: 'clone_repo', displayName: 'Clone repository', icon: <IconGithub /> },
{ name: 'list_repos', displayName: 'List repositories', icon: <IconGithub /> },
]
-for (const { name, displayName, icon } of POSTHOG_CODE_TOOLS) {
- for (const key of [name, `mcp__${POSTHOG_CODE_TOOLS_SERVER}__${name}`]) {
- toolRegistry.register({ key, displayName, icon, Renderer: PostHogCodeToolRenderer })
- }
-}
-// 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.
-toolRegistry.register({
- key: 'AskUserQuestion',
- keepVisible: true,
- displayName: 'Question',
- icon: <IconAI />,
- Renderer: QuestionRenderer,
-})
+const entries = new Map<string, ToolRegistryEntry>(
+ [
+ ...BUILTIN_TOOLS.flatMap(({ keys, ...entry }) =>
+ keys.map((key) => ({ key, ...entry, Renderer: BuiltinToolRenderer, keepVisible: key === 'ExitPlanMode' }))
+ ),
+ ...['Edit', 'Write', 'NotebookEdit', 'MultiEdit'].map((key) => ({
+ key,
+ displayName: 'Edit',
+ icon: <IconPencil />,
+ Renderer: EditToolRenderer,
+ })),
+ ...POSTHOG_EXEC_VERBS.map((entry) => ({ ...entry, Renderer: BuiltinToolRenderer })),
+ ...POSTHOG_CODE_TOOLS.flatMap(({ name, ...entry }) =>
+ [name, `mcp__${POSTHOG_CODE_TOOLS_SERVER}__${name}`].map((key) => ({
+ key,
+ ...entry,
+ Renderer: PostHogCodeToolRenderer,
+ }))
+ ),
+ {
+ key: 'AskUserQuestion',
+ displayName: 'Question',
+ icon: <IconAI />,
+ Renderer: QuestionRenderer,
+ keepVisible: true,
+ },
+ ...posthogAiToolRenderers,
+ ].map((entry) => [entry.key, entry])
+)
+
+export const toolRegistry: ToolRegistry = {
+ lookup: (toolName) => entries.get(toolName) ?? null,
+}
/**
* Looks up the renderer entry for a resolved tool key, falling back to the generic built-in card.
@@ -233,7 +195,7 @@ toolRegistry.register({
* 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. A registered preview-only entry (no
- * `Renderer`) resolves to the same generic card, so its `renderPermissionPreview` is preserved while the
+ * `Renderer`) resolves to the same generic card, so its `PermissionPreview` is preserved while the
* result card stays the built-in one.
*/
export function lookupToolRenderer(resolvedKey: string, fromPostHogExec: boolean): ResolvedToolRegistryEntry {
diff --git a/products/posthog_ai/frontend/components/tool/widgets/CreateNotebookWidget.test.tsx b/products/posthog_ai/frontend/components/tool/widgets/CreateNotebookWidget.test.tsx
index 45c5050fc0a7..670cf7d3cd87 100644
--- a/products/posthog_ai/frontend/components/tool/widgets/CreateNotebookWidget.test.tsx
+++ b/products/posthog_ai/frontend/components/tool/widgets/CreateNotebookWidget.test.tsx
@@ -1,7 +1,3 @@
-// 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'
diff --git a/products/posthog_ai/frontend/components/tool/widgets/CreateNotebookWidget.tsx b/products/posthog_ai/frontend/components/tool/widgets/CreateNotebookWidget.tsx
index d9cf813490ed..a59421d16fa1 100644
--- a/products/posthog_ai/frontend/components/tool/widgets/CreateNotebookWidget.tsx
+++ b/products/posthog_ai/frontend/components/tool/widgets/CreateNotebookWidget.tsx
@@ -7,7 +7,7 @@ import { urls } from 'scenes/urls'
import { MessageTemplate } from '../../../messages/MessageTemplate'
import { DataToolRow } from '../DataToolRow'
import { GenericMcpToolRenderer } from '../GenericMcpToolRenderer'
-import { parseToolOutputRecord } from '../parseToolOutput'
+import { parseToolOutputRecord } from '../parseToolOutputRecord'
import type { ToolRendererProps } from '../toolRegistry'
/** The notebook fields the widget renders, pulled from the REST payload. */
diff --git a/products/posthog_ai/frontend/components/tool/widgets/extractors.test.ts b/products/posthog_ai/frontend/components/tool/widgets/extractors.test.ts
index 37c3681650a3..9ae1e5fef57d 100644
--- a/products/posthog_ai/frontend/components/tool/widgets/extractors.test.ts
+++ b/products/posthog_ai/frontend/components/tool/widgets/extractors.test.ts
@@ -4,7 +4,6 @@ import type { ToolCallMessage } from 'products/posthog_ai/frontend/types/toolTyp
import {
extractDashboard,
- extractErrorTrackingResponse,
extractQueryResult,
extractRecordingFilters,
extractVisualizationArtifact,
@@ -168,19 +167,32 @@ describe('mcp tool adapter extractors', () => {
})
})
- 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([
+ { kind: 'TrendsQuery', series: [] },
+ { kind: 'HogQLQuery', query: 'SELECT 1' },
+ { kind: 'InsightVizNode', source: { kind: 'StickinessQuery', series: [] } },
+ { kind: 'DataVisualizationNode', source: { kind: 'HogQLQuery', query: 'SELECT 1' } },
+ { kind: 'DataTableNode', source: { kind: 'EventsQuery', select: ['*'] } },
+ ])('preserves a saved insight query ($kind) and its overridden link', (query) => {
+ const url = '/project/1/insights/example?variables_override=%7B%7D'
+ const result = extractQueryResult(
+ toolMessage(
+ {
+ query,
+ results: [],
+ insight: { name: 'Synthetic insight', description: 'Saved query', url: '/insights/example' },
+ _posthogUrl: url,
+ },
+ { insightId: 'example' },
+ 'insight-query'
+ )
+ )
+ expect(result?.content.query).toEqual(query)
+ expect(result?.content.name).toEqual('Synthetic insight')
+ expect(result?.url).toEqual(url)
})
- })
- describe('extractQueryResult', () => {
it.each(['TrendsQuery', 'FunnelsQuery', 'RetentionQuery', 'StickinessQuery', 'PathsQuery', 'LifecycleQuery'])(
'passes a bare %s through for InsightVizNode wrapping downstream',
(kind) => {
@@ -241,6 +253,10 @@ describe('mcp tool adapter extractors', () => {
expect(extractQueryResult(toolMessage({ results: [] }))).toBeNull()
expect(extractQueryResult(toolMessage({ query: 'not-an-object' }))).toBeNull()
expect(extractQueryResult(toolMessage(undefined))).toBeNull()
+ expect(extractQueryResult(toolMessage(undefined, { insightId: 'example' }, 'insight-query'))).toBeNull()
+ expect(extractQueryResult(toolMessage({ query: { kind: 'InsightVizNode' } }))).toBeNull()
+ expect(extractQueryResult(toolMessage({ query: { kind: 'DataVisualizationNode' } }))).toBeNull()
+ expect(extractQueryResult(toolMessage({ query: { kind: 'DataTableNode' } }))).toBeNull()
})
})
})
diff --git a/products/posthog_ai/frontend/components/tool/widgets/extractors.ts b/products/posthog_ai/frontend/components/tool/widgets/extractors.ts
index a57ddfb90169..cb8650499745 100644
--- a/products/posthog_ai/frontend/components/tool/widgets/extractors.ts
+++ b/products/posthog_ai/frontend/components/tool/widgets/extractors.ts
@@ -1,6 +1,5 @@
import { recordingsQueryToUniversalFilters } from 'scenes/session-recordings/filters/recordingsQueryConversions'
-import { MaxErrorTrackingSearchResponse } from '~/queries/schema/schema-assistant-error-tracking'
import {
ArtifactContentType,
ArtifactMessage,
@@ -9,19 +8,29 @@ import {
VisualizationArtifactContent,
} from '~/queries/schema/schema-assistant-messages'
import { DataTableNode, NodeKind, RecordingsQuery } from '~/queries/schema/schema-general'
-import { isInsightQueryNode } from '~/queries/utils'
+import {
+ isDataTableNode,
+ isDataVisualizationNode,
+ isHogQLQuery,
+ isInsightQueryNode,
+ isInsightVizNode,
+} from '~/queries/utils'
import { RecordingUniversalFilters } from '~/types'
import type { ToolCallMessage } from 'products/posthog_ai/frontend/types/toolTypes'
-import { asRecord, parseToolOutputRecord } from '../parseToolOutput'
+import { parseToolOutputRecord } from '../parseToolOutputRecord'
/**
* Shared shape extractors for the sandbox MCP tool renderer widgets. Each turns a flattened
* `ToolCallMessage` (built by `runStreamLogic` from ACP frames) into the props the atomic
- * `messages/*` widgets expect. Generic output parsing lives in `../parseToolOutput`.
+ * `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
}
@@ -123,7 +132,14 @@ export function extractQueryResult(message: ToolCallMessage): QueryResultExtract
}
let renderable: VisualizationArtifactContent['query'] | null = null
- if (isInsightQueryNode(query)) {
+ if (
+ isInsightQueryNode(query) ||
+ isHogQLQuery(query) ||
+ (isInsightVizNode(query) && isInsightQueryNode(query.source)) ||
+ (isDataVisualizationNode(query) && isHogQLQuery(query.source)) ||
+ // A saved table insight arrives as a bare node; its source can be any table-readable kind.
+ (isDataTableNode(query) && typeof asRecord(query.source)?.kind === 'string')
+ ) {
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.
@@ -140,14 +156,15 @@ export function extractQueryResult(message: ToolCallMessage): QueryResultExtract
return null
}
+ const insight = asRecord(output?.insight)
return {
content: {
content_type: ArtifactContentType.Visualization,
query: renderable,
- name: null,
- description: null,
+ name: asString(insight?.name) ?? null,
+ description: asString(insight?.description) ?? null,
},
- url: asString(output?._posthogUrl) ?? null,
+ url: asString(output?._posthogUrl) ?? asString(insight?.url) ?? null,
}
}
@@ -206,24 +223,3 @@ export function extractRecordingFilters(message: ToolCallMessage): RecordingUniv
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: ToolCallMessage): MaxErrorTrackingSearchResponse | null {
- const output = parseToolOutputRecord(message)
- if (!output || !ERROR_TRACKING_RESPONSE_KEYS.some((key) => key in output)) {
- return null
- }
- return output as MaxErrorTrackingSearchResponse
-}
diff --git a/products/posthog_ai/frontend/components/tool/widgets/registerDataToolRenderers.tsx b/products/posthog_ai/frontend/components/tool/widgets/registerDataToolRenderers.tsx
deleted file mode 100644
index 30aff6f6869f..000000000000
--- a/products/posthog_ai/frontend/components/tool/widgets/registerDataToolRenderers.tsx
+++ /dev/null
@@ -1,156 +0,0 @@
-import { type ComponentType } from 'react'
-
-import {
- IconDashboard,
- IconFunnels,
- IconGraph,
- IconLifecycle,
- IconLlmAnalytics,
- IconNotebook,
- IconPerson,
- IconRetention,
- IconRewindPlay,
- IconStickiness,
- IconTrends,
- IconUserPaths,
- IconWarning,
-} from '@posthog/icons'
-
-import { lazyWithRetry } from 'lib/utils/retryImport'
-
-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).
-// 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(() =>
- import('./CreateInsightWidget').then((m) => ({ default: m.CreateInsightWidget }))
-)
-const DashboardRenderer = lazyWithRetry(() =>
- import('./UpsertDashboardWidget').then((m) => ({ default: m.UpsertDashboardWidget }))
-)
-const SessionRecordingsRenderer = lazyWithRetry(() =>
- import('./SearchSessionRecordingsWidget').then((m) => ({ default: m.SearchSessionRecordingsWidget }))
-)
-const ErrorTrackingRenderer = lazyWithRetry(() =>
- import('./ErrorTrackingWidget').then((m) => ({ default: m.ErrorTrackingWidget }))
-)
-const NotebookRenderer = lazyWithRetry(() =>
- import('./CreateNotebookWidget').then((m) => ({ default: m.CreateNotebookWidget }))
-)
-const QueryRenderer = lazyWithRetry(() => import('./QueryWidget').then((m) => ({ default: m.QueryWidget })))
-
-// The single-exec inner tool names exist in two conventions — hyphenated (the MCP yaml definitions) and
-// snake_case (legacy Max tools) — so we register both aliases where both are real tool names. Each call
-// 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,
- requiresPostHogOrigin: true,
- keepVisible: true,
- })
- )
- )
-}
-
-// --- Data tools: insight (create / update / read) ---
-register(
- ['insight-create', 'insight-update', 'insight-get', 'create_insight'],
- 'Insight',
- <IconGraph />,
- InsightRenderer
-)
-
-// --- Data tools: dashboard ---
-register(
- ['dashboard-create', 'dashboard-update', 'upsert_dashboard'],
- 'Dashboard',
- <IconDashboard />,
- DashboardRenderer
-)
-
-// --- Data tools: session recordings ---
-register(
- ['query-session-recordings-list', 'search_session_recordings', 'filter_session_recordings'],
- 'Session recordings',
- <IconRewindPlay />,
- SessionRecordingsRenderer
-)
-
-// --- Data tools: error tracking ---
-register(
- [
- 'query-error-tracking-issues-list',
- 'query-error-tracking-issue',
- 'query-error-tracking-issue-events',
- 'search_error_tracking_issues',
- 'filter_error_tracking_issues',
- ],
- 'Error tracking',
- <IconWarning />,
- ErrorTrackingRenderer
-)
-
-// --- Data tools: notebooks ---
-// The generated CRUD tools and the handwritten notebook-edit (the collab-safe content editor) all
-// return the same REST notebook payload. A feature flag swaps that set for the markdown notebook
-// tools, so both sets are registered — a thread only ever contains calls from the set its own run
-// was served. The cell tools (add / update / delete) stay on the generic card: they return a cell
-// run, not a notebook, so this card has nothing to show for them.
-register(
- [
- 'notebooks-create',
- 'notebooks-partial-update',
- 'notebooks-retrieve',
- 'notebook-edit',
- 'notebooks-create-markdown',
- 'notebooks-get',
- ],
- 'Notebook',
- <IconNotebook />,
- NotebookRenderer
-)
-
-// --- Data tools: query wrappers (analytics/product queries executed inline by the agent) ---
-const QUERY_WRAPPER_TOOLS: { key: string; displayName: string; icon: JSX.Element }[] = [
- { key: 'query-trends', displayName: 'Trends query', icon: <IconTrends /> },
- { key: 'query-funnel', displayName: 'Funnel query', icon: <IconFunnels /> },
- { key: 'query-retention', displayName: 'Retention query', icon: <IconRetention /> },
- { key: 'query-stickiness', displayName: 'Stickiness query', icon: <IconStickiness /> },
- { key: 'query-paths', displayName: 'Paths query', icon: <IconUserPaths /> },
- { key: 'query-lifecycle', displayName: 'Lifecycle query', icon: <IconLifecycle /> },
- { key: 'query-llm-traces-list', displayName: 'LLM traces', icon: <IconLlmAnalytics /> },
- { key: 'query-trends-actors', displayName: 'Trends persons', icon: <IconPerson /> },
- { key: 'query-lifecycle-actors', displayName: 'Lifecycle persons', icon: <IconPerson /> },
- { key: 'query-paths-actors', displayName: 'Paths persons', icon: <IconPerson /> },
-]
-registerToolRenderers(
- QUERY_WRAPPER_TOOLS.map(
- ({ key, displayName, icon }): ToolRegistryEntry => ({
- key,
- displayName,
- icon,
- Renderer: QueryRenderer,
- requiresPostHogOrigin: true,
- keepVisible: true,
- })
- )
-)
diff --git a/products/posthog_ai/frontend/components/tool/widgets/registerDataToolRenderers.test.ts b/products/posthog_ai/frontend/posthogAiToolRenderers.test.ts
similarity index 53%
rename from products/posthog_ai/frontend/components/tool/widgets/registerDataToolRenderers.test.ts
rename to products/posthog_ai/frontend/posthogAiToolRenderers.test.ts
index 644c3b6b1493..07862fa6da2e 100644
--- a/products/posthog_ai/frontend/components/tool/widgets/registerDataToolRenderers.test.ts
+++ b/products/posthog_ai/frontend/posthogAiToolRenderers.test.ts
@@ -1,29 +1,25 @@
-// 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 './registerDataToolRenderers'
+import { toolRegistry } from './components/tool/toolRegistry'
-import { toolRegistry } from 'products/posthog_ai/frontend/api/tools'
-
-describe('registerDataToolRenderers', () => {
+describe('posthogAiToolRenderers', () => {
it.each([
['insight-create', 'Insight'],
['insight-update', 'Insight'],
['insight-get', 'Insight'],
- ['create_insight', 'Insight'],
+ ['insight-query', 'Insight query'],
['dashboard-create', 'Dashboard'],
- ['upsert_dashboard', 'Dashboard'],
+ ['dashboard-update', 'Dashboard'],
['query-session-recordings-list', 'Session recordings'],
- ['search_session_recordings', 'Session recordings'],
['query-error-tracking-issues-list', 'Error tracking'],
- ['search_error_tracking_issues', 'Error tracking'],
+ ['query-error-tracking-issue', 'Error tracking'],
+ ['query-error-tracking-issue-events', 'Error tracking'],
['query-trends', 'Trends query'],
['query-funnel', 'Funnel query'],
['notebooks-create', 'Notebook'],
['notebook-edit', 'Notebook'],
- ])('registers %s into the shared registry with displayName "%s"', (key, displayName) => {
+ ])('resolves %s from the central manifest with displayName "%s"', (key, displayName) => {
const entry = toolRegistry.lookup(key)
expect(entry).not.toBeNull()
expect(entry?.displayName).toEqual(displayName)
+ expect(entry?.keepVisible).toBe(true)
})
})
diff --git a/products/posthog_ai/frontend/posthogAiToolRenderers.tsx b/products/posthog_ai/frontend/posthogAiToolRenderers.tsx
new file mode 100644
index 000000000000..da1f039adcea
--- /dev/null
+++ b/products/posthog_ai/frontend/posthogAiToolRenderers.tsx
@@ -0,0 +1,104 @@
+import {
+ IconDashboard,
+ IconFunnels,
+ IconGraph,
+ IconLifecycle,
+ IconLlmAnalytics,
+ IconNotebook,
+ IconPerson,
+ IconRetention,
+ IconRewindPlay,
+ IconStickiness,
+ IconTrends,
+ IconUserPaths,
+} from '@posthog/icons'
+
+import { lazyWithRetry } from 'lib/utils/retryImport'
+
+import type { ToolRegistryEntry } from './api/tools'
+
+// Lazy factories keep widget implementations out of the registry's eager import graph.
+const InsightRenderer = lazyWithRetry(() =>
+ import('./components/tool/widgets/CreateInsightWidget').then((m) => ({ default: m.CreateInsightWidget }))
+)
+const DashboardRenderer = lazyWithRetry(() =>
+ import('./components/tool/widgets/UpsertDashboardWidget').then((m) => ({ default: m.UpsertDashboardWidget }))
+)
+const SessionRecordingsRenderer = lazyWithRetry(() =>
+ import('./components/tool/widgets/SearchSessionRecordingsWidget').then((m) => ({
+ default: m.SearchSessionRecordingsWidget,
+ }))
+)
+const NotebookRenderer = lazyWithRetry(() =>
+ import('./components/tool/widgets/CreateNotebookWidget').then((m) => ({ default: m.CreateNotebookWidget }))
+)
+const QueryRenderer = lazyWithRetry(() =>
+ import('./components/tool/widgets/QueryWidget').then((m) => ({ default: m.QueryWidget }))
+)
+
+const DATA_TOOLS = [
+ {
+ keys: ['insight-create', 'insight-update', 'insight-get'],
+ displayName: 'Insight',
+ icon: <IconGraph />,
+ Renderer: InsightRenderer,
+ },
+
+ {
+ keys: ['dashboard-create', 'dashboard-update'],
+ displayName: 'Dashboard',
+ icon: <IconDashboard />,
+ Renderer: DashboardRenderer,
+ },
+
+ {
+ keys: ['query-session-recordings-list'],
+ displayName: 'Session recordings',
+ icon: <IconRewindPlay />,
+ Renderer: SessionRecordingsRenderer,
+ },
+
+ // The generated CRUD tools and the handwritten notebook-edit (the collab-safe content editor) all
+ // return the same REST notebook payload. A feature flag swaps that set for the markdown notebook
+ // tools, so both sets are registered — a thread only ever contains calls from the set its own run
+ // was served. The cell tools (add / update / delete) stay on the generic card: they return a cell
+ // run, not a notebook, so this card has nothing to show for them.
+ {
+ keys: [
+ 'notebooks-create',
+ 'notebooks-partial-update',
+ 'notebooks-retrieve',
+ 'notebook-edit',
+ 'notebooks-create-markdown',
+ 'notebooks-get',
+ ],
+ displayName: 'Notebook',
+ icon: <IconNotebook />,
+ Renderer: NotebookRenderer,
+ },
+]
+
+const QUERY_TOOLS: { key: string; displayName: string; icon: JSX.Element }[] = [
+ { key: 'insight-query', displayName: 'Insight query', icon: <IconGraph /> },
+ { 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 /> },
+]
+export const posthogAiToolRenderers: ToolRegistryEntry[] = [
+ ...DATA_TOOLS.flatMap(({ keys, ...entry }) =>
+ keys.map((key) => ({ key, ...entry, requiresPostHogOrigin: true, keepVisible: true }))
+ ),
+ ...QUERY_TOOLS.map((entry) => ({
+ ...entry,
+ Renderer: QueryRenderer,
+ requiresPostHogOrigin: true,
+ keepVisible: true,
+ })),
+]
diff --git a/products/posthog_ai/frontend/utils/toolResolver.ts b/products/posthog_ai/frontend/utils/toolResolver.ts
index d4f5d1a2a536..aea1c9a7c077 100644
--- a/products/posthog_ai/frontend/utils/toolResolver.ts
+++ b/products/posthog_ai/frontend/utils/toolResolver.ts
@@ -94,7 +94,7 @@ export function resolveToolCall(toolCall: ResolvableToolCall): ResolvedToolCall
/**
* The proposed inner tool input for a permission request — the args a tool renderer or a
- * `renderPermissionPreview` needs to preview what an approval will do. For a PostHog exec call this is
+ * `PermissionPreview` needs to preview what an approval will do. For a PostHog exec call this is
* the command-embedded JSON args (`call <sub-tool> {…}`), falling back to the explicit `input` field
* when the agent sends args out of band. Returns an empty object when neither is present.
*/
diff --git a/products/posthog_ai/package.json b/products/posthog_ai/package.json
index a523591287ae..4f3a9069caf6 100644
--- a/products/posthog_ai/package.json
+++ b/products/posthog_ai/package.json
@@ -5,6 +5,7 @@
},
"dependencies": {
"@posthog/quill-primitives": "workspace:*",
+ "@posthog/react": "catalog:",
"@tanstack/react-virtual": "*",
"@toon-format/toon": "^2.1.0",
"eventsource-parser": "*",
diff --git a/products/posthog_ai/frontend/components/tool/widgets/ReplayVisionScanWidget.stories.tsx b/products/replay_vision/frontend/posthogAi/ReplayVisionScanWidget.stories.tsx
similarity index 100%
rename from products/posthog_ai/frontend/components/tool/widgets/ReplayVisionScanWidget.stories.tsx
rename to products/replay_vision/frontend/posthogAi/ReplayVisionScanWidget.stories.tsx
diff --git a/products/posthog_ai/frontend/components/tool/widgets/ReplayVisionScanWidget.tsx b/products/replay_vision/frontend/posthogAi/ReplayVisionScanWidget.tsx
similarity index 93%
rename from products/posthog_ai/frontend/components/tool/widgets/ReplayVisionScanWidget.tsx
rename to products/replay_vision/frontend/posthogAi/ReplayVisionScanWidget.tsx
index 65432b376c13..55999f9fd197 100644
--- a/products/posthog_ai/frontend/components/tool/widgets/ReplayVisionScanWidget.tsx
+++ b/products/replay_vision/frontend/posthogAi/ReplayVisionScanWidget.tsx
@@ -4,15 +4,9 @@ import { LemonBanner, Link, Spinner } from '@posthog/lemon-ui'
import { urls } from 'scenes/urls'
-import type { ReplayObservationApi } from 'products/replay_vision/frontend/generated/api.schemas'
-import { flattenMarkdownToLine } from 'products/replay_vision/frontend/utils/markdown'
-import {
- readErrorMessage,
- readReasoning,
- readSummary,
- readTitle,
-} from 'products/replay_vision/frontend/utils/observation'
-
+import type { ReplayObservationApi } from '../generated/api.schemas'
+import { flattenMarkdownToLine } from '../utils/markdown'
+import { readErrorMessage, readReasoning, readSummary, readTitle } from '../utils/observation'
import { replayVisionScanWidgetLogic } from './replayVisionScanWidgetLogic'
export interface ReplayVisionScanWidgetProps {
diff --git a/products/posthog_ai/frontend/components/tool/widgets/replayVisionScanWidgetLogic.test.ts b/products/replay_vision/frontend/posthogAi/replayVisionScanWidgetLogic.test.ts
similarity index 97%
rename from products/posthog_ai/frontend/components/tool/widgets/replayVisionScanWidgetLogic.test.ts
rename to products/replay_vision/frontend/posthogAi/replayVisionScanWidgetLogic.test.ts
index 43f444b53ff8..475bbcf0e548 100644
--- a/products/posthog_ai/frontend/components/tool/widgets/replayVisionScanWidgetLogic.test.ts
+++ b/products/replay_vision/frontend/posthogAi/replayVisionScanWidgetLogic.test.ts
@@ -3,11 +3,7 @@ import { expectLogic } from 'kea-test-utils'
import { useMocks } from '~/mocks/jest'
import { initKeaTests } from '~/test/init'
-import type {
- ObservationStatusEnumApi,
- ReplayObservationApi,
-} from 'products/replay_vision/frontend/generated/api.schemas'
-
+import type { ObservationStatusEnumApi, ReplayObservationApi } from '../generated/api.schemas'
import { replayVisionScanWidgetLogic } from './replayVisionScanWidgetLogic'
const SCAN_ID = 'scanner-1'
diff --git a/products/posthog_ai/frontend/components/tool/widgets/replayVisionScanWidgetLogic.ts b/products/replay_vision/frontend/posthogAi/replayVisionScanWidgetLogic.ts
similarity index 93%
rename from products/posthog_ai/frontend/components/tool/widgets/replayVisionScanWidgetLogic.ts
rename to products/replay_vision/frontend/posthogAi/replayVisionScanWidgetLogic.ts
index f3bf611fd2cb..d9a157dfd582 100644
--- a/products/posthog_ai/frontend/components/tool/widgets/replayVisionScanWidgetLogic.ts
+++ b/products/replay_vision/frontend/posthogAi/replayVisionScanWidgetLogic.ts
@@ -3,13 +3,9 @@ import { loaders } from 'kea-loaders'
import { teamLogic } from 'scenes/teamLogic'
-import { visionScannersObservationsList } from 'products/replay_vision/frontend/generated/api'
-import type { ReplayObservationApi } from 'products/replay_vision/frontend/generated/api.schemas'
-import {
- OBSERVE_POLL_GRACE_MS,
- scheduleObservationPoll,
- shouldPollObservations,
-} from 'products/replay_vision/frontend/logics/observationPolling'
+import { visionScannersObservationsList } from '../generated/api'
+import type { ReplayObservationApi } from '../generated/api.schemas'
+import { OBSERVE_POLL_GRACE_MS, scheduleObservationPoll, shouldPollObservations } from '../logics/observationPolling'
/**
* A scan takes at most MAX_SESSIONS_PER_SCAN (200) recordings and a session can hold more than one row,
@@ -76,7 +72,7 @@ export type replayVisionScanWidgetLogicType = MakeLogicType<
>
export const replayVisionScanWidgetLogic = kea<replayVisionScanWidgetLogicType>([
- path(['products', 'posthog_ai', 'frontend', 'components', 'tool', 'widgets', 'replayVisionScanWidgetLogic']),
+ path(['products', 'replay_vision', 'frontend', 'posthogAi', 'replayVisionScanWidgetLogic']),
props({} as ReplayVisionScanWidgetLogicProps),
key((props: ReplayVisionScanWidgetLogicProps) => `${props.scanId}:${props.sessionIds.join(',')}`),