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.

feat(phai): persist-tool reactions and cdp diff-gated updates (#69269)

Georgiy Tarasov8921d2fe6332
diff --git a/frontend/jest.config.ts b/frontend/jest.config.ts
index fc3b18bd6a7e..f7853222fbbf 100644
--- a/frontend/jest.config.ts
+++ b/frontend/jest.config.ts
@@ -16,6 +16,8 @@ const esmModules = [
'@shadcn/react',
'@react-hook',
'@medv',
+ // @toon-format/toon ships ESM-only; the posthog_ai widget extractors decode TOON tool output.
+ '@toon-format',
'monaco-editor',
'@posthog/hedgehog-mode',
// @marsidev/react-turnstile ships ESM-only; the auth flow variant registry pulls it
diff --git a/frontend/src/scenes/hog-functions/configuration/HogFunctionConfigDiff.tsx b/frontend/src/scenes/hog-functions/configuration/HogFunctionConfigDiff.tsx
new file mode 100644
index 000000000000..aa7b7a883257
--- /dev/null
+++ b/frontend/src/scenes/hog-functions/configuration/HogFunctionConfigDiff.tsx
@@ -0,0 +1,37 @@
+import { DiffEvidenceCard } from 'products/posthog_ai/frontend/api/tools'
+
+import type { HogFunctionFieldDiff } from './hogFunctionConfigDiffUtils'
+
+// A pseudo-path per field so the shared diff viewer picks the right syntax highlighting — JSON
+// fields pretty-print as JSON; hog source has no registered grammar and falls back to plain text.
+function fieldPath(diff: HogFunctionFieldDiff): string {
+ return diff.kind === 'json' ? `${diff.field}.json` : `${diff.field}.txt`
+}
+
+/**
+ * Approval-card preview for a `cdp-functions-partial-update`: one evidence card per changed field —
+ * the field label and +/- line stats in the card's header bar, the full change in the shared diff
+ * viewer, capped with a "Show all n lines" expander. Pure presentational — the diff is precomputed
+ * by `buildHogFunctionConfigDiff`.
+ */
+export function HogFunctionConfigDiff({ diffs }: { diffs: HogFunctionFieldDiff[] }): JSX.Element {
+ return (
+ <div className="flex flex-col gap-2 min-w-0">
+ {diffs.map((diff) =>
+ diff.truncated ? (
+ <div key={diff.field} className="text-xs text-secondary">
+ {diff.label}: large change — {diff.added} added, {diff.removed} removed lines
+ </div>
+ ) : (
+ <DiffEvidenceCard
+ key={diff.field}
+ label={diff.label}
+ oldText={diff.currentText || null}
+ newText={diff.proposedText}
+ path={fieldPath(diff)}
+ />
+ )
+ )}
+ </div>
+ )
+}
diff --git a/frontend/src/scenes/hog-functions/configuration/HogFunctionConfiguration.tsx b/frontend/src/scenes/hog-functions/configuration/HogFunctionConfiguration.tsx
index e28a61725439..ce714b86a720 100644
--- a/frontend/src/scenes/hog-functions/configuration/HogFunctionConfiguration.tsx
+++ b/frontend/src/scenes/hog-functions/configuration/HogFunctionConfiguration.tsx
@@ -1,5 +1,9 @@
+// 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, useValues } from 'kea'
+import { BindLogic, useActions, useValues } from 'kea'
import { Form } from 'kea-forms'
import {
@@ -20,6 +24,9 @@ import { HogFunctionMappings } from 'scenes/hog-functions/mapping/HogFunctionMap
import { HogFunctionEventEstimates } from 'scenes/hog-functions/metrics/HogFunctionEventEstimates'
import { SurveyResponseKeysReference } from 'scenes/surveys/components/SurveyResponseKeysReference'
+import { useAttachedContext, useToolStreamListener } from 'products/posthog_ai/frontend/api/logics'
+import { resolveToolCall } from 'products/posthog_ai/frontend/api/tools'
+
import { humanizeHogFunctionType } from '../hog-function-utils'
import { HogFunctionStatusIndicator } from '../misc/HogFunctionStatusIndicator'
import { HogFunctionStatusTag } from '../misc/HogFunctionStatusTag'
@@ -63,6 +70,44 @@ export function HogFunctionConfiguration({
showTesting,
survey,
} = useValues(logic)
+ const { loadHogFunction } = useActions(logic)
+
+ // The section components attach the config blobs (code, inputs, filters) as unkeyed values; only a
+ // keyed item renders its id into the context line, and the agent needs the id for cdp-functions-partial-update.
+ useAttachedContext(
+ hogFunction?.id
+ ? [
+ {
+ type: 'hog_function',
+ key: hogFunction.id,
+ label: `Current ${humanizeHogFunctionType(type)}: ${hogFunction.name}`,
+ },
+ ]
+ : null
+ )
+
+ // An approved `cdp-functions-partial-update` mutates the function server-side while this form keeps
+ // pre-update state, so the scene (and the approval-card diff for any later proposal, e.g. a revert)
+ // would show stale values. Refetch on completion — `loadHogFunctionSuccess` resets the form, which
+ // also discards unsaved manual edits; tool results land in the open scene. A plain tool-stream
+ // listener, not `useMcpToolApplyBack`: the refetch is idempotent, so it must not be dropped by the
+ // apply-back claim gating (claims snapshot the targets mounted at prompt-send and release each turn).
+ useToolStreamListener({
+ tools: ['cdp-functions-partial-update'],
+ onEvent: (event) => {
+ if (event.phase !== 'completed' || !hogFunction?.id) {
+ return
+ }
+ // A parseable payload targeting a different function is not ours to absorb; an unparseable
+ // one may still be ours, and a same-data refetch is harmless, so reload in that case.
+ const innerInput = resolveToolCall(event.invocation).innerInput
+ const targetId = typeof innerInput?.id === 'string' ? innerInput.id : null
+ if (targetId && targetId !== hogFunction.id) {
+ return
+ }
+ loadHogFunction()
+ },
+ })
if (loading && !loaded) {
return <SpinnerOverlay />
diff --git a/frontend/src/scenes/hog-functions/configuration/components/HogFunctionCode.tsx b/frontend/src/scenes/hog-functions/configuration/components/HogFunctionCode.tsx
index cfcc08885786..eb9673177a53 100644
--- a/frontend/src/scenes/hog-functions/configuration/components/HogFunctionCode.tsx
+++ b/frontend/src/scenes/hog-functions/configuration/components/HogFunctionCode.tsx
@@ -13,6 +13,7 @@ import { iconForType } from '~/layout/panel-layout/ProjectTree/defaultTree'
import { useAttachedContext } from 'products/posthog_ai/frontend/api/logics'
+import { truncateHogFunctionContext } from '../../hog-function-utils'
import { hogFunctionConfigurationLogic } from '../hogFunctionConfigurationLogic'
import { HogFunctionTemplateOptions } from './HogFunctionTemplateOptions'
@@ -42,7 +43,11 @@ export function HogFunctionCode(): JSX.Element {
const sourceCodeRef = useRef<HTMLDivElement>(null)
useAttachedContext([
- { type: 'hog_code', value: JSON.stringify(configuration.hog ?? ''), label: 'Current Hog code' },
+ {
+ type: 'hog_code',
+ value: truncateHogFunctionContext(JSON.stringify(configuration.hog ?? '')),
+ label: 'Current Hog code',
+ },
])
const content = (
diff --git a/frontend/src/scenes/hog-functions/configuration/components/HogFunctionInputs.tsx b/frontend/src/scenes/hog-functions/configuration/components/HogFunctionInputs.tsx
index 7f18d4bb6949..87ceb9ff4d50 100644
--- a/frontend/src/scenes/hog-functions/configuration/components/HogFunctionInputs.tsx
+++ b/frontend/src/scenes/hog-functions/configuration/components/HogFunctionInputs.tsx
@@ -13,6 +13,7 @@ import { AvailableFeature, CyclotronJobInputSchemaType } from '~/types'
import { useAttachedContext } from 'products/posthog_ai/frontend/api/logics'
+import { redactSecretHogFunctionInputs, truncateHogFunctionContext } from '../../hog-function-utils'
import { hogFunctionConfigurationLogic } from '../hogFunctionConfigurationLogic'
export function HogFunctionInputs(): JSX.Element {
@@ -43,10 +44,17 @@ export function HogFunctionInputs(): JSX.Element {
useAttachedContext([
{
type: 'hog_function_inputs_schema',
- value: JSON.stringify({
- inputs_schema: configuration.inputs_schema ?? [],
- hog_code: configuration.hog ?? '',
- }),
+ value: truncateHogFunctionContext(
+ JSON.stringify({
+ inputs_schema: configuration.inputs_schema ?? [],
+ // Secret values never leave the scene: a freshly typed secret is cleartext in form state.
+ inputs: redactSecretHogFunctionInputs(
+ configuration.inputs ?? {},
+ configuration.inputs_schema ?? []
+ ),
+ hog_code: configuration.hog ?? '',
+ })
+ ),
label: 'Current inputs schema',
},
])
diff --git a/frontend/src/scenes/hog-functions/configuration/hogFunctionConfigDiffUtils.test.ts b/frontend/src/scenes/hog-functions/configuration/hogFunctionConfigDiffUtils.test.ts
new file mode 100644
index 000000000000..49c788e734ec
--- /dev/null
+++ b/frontend/src/scenes/hog-functions/configuration/hogFunctionConfigDiffUtils.test.ts
@@ -0,0 +1,64 @@
+import { buildHogFunctionConfigDiff } from './hogFunctionConfigDiffUtils'
+
+describe('buildHogFunctionConfigDiff', () => {
+ it('classifies each proposed field as added / removed / changed and drops unchanged ones', () => {
+ const current = {
+ name: 'Old name',
+ hog: 'return event',
+ filters: {},
+ enabled: true,
+ masking: { hash: 'all', ttl: 60 },
+ inputs_schema: [{ key: 'url', type: 'string' }],
+ }
+ const proposed = {
+ name: 'New name', // changed
+ hog: 'return event', // unchanged → dropped
+ filters: { events: [{ id: '$pageview' }] }, // empty → set = added
+ enabled: false, // changed
+ masking: null, // set → empty = removed
+ inputs_schema: [{ key: 'url', type: 'string' }], // unchanged → dropped
+ }
+ const byField = Object.fromEntries(
+ buildHogFunctionConfigDiff(current, proposed).map((diff) => [diff.field, diff.status])
+ )
+ expect(byField).toEqual({ name: 'changed', filters: 'added', enabled: 'changed', masking: 'removed' })
+ })
+
+ it('ignores server-only input noise so an unchanged input value is not a spurious change', () => {
+ const current = { inputs: { url: { value: 'https://x', bytecode: ['_H', 1], order: 0 } } }
+ const proposed = { inputs: { url: { value: 'https://x' } } }
+ expect(buildHogFunctionConfigDiff(current, proposed)).toEqual([])
+ })
+
+ it('never exposes a current secret input value while still surfacing the change', () => {
+ const current = {
+ inputs: { api_key: { value: 'sk-live-supersecret' } },
+ inputs_schema: [{ key: 'api_key', type: 'string', secret: true }],
+ }
+ const proposed = { inputs: { api_key: { value: 'sk-live-agent-proposed' } } }
+ const diffs = buildHogFunctionConfigDiff(current, proposed)
+ expect(diffs).toHaveLength(1)
+ expect(diffs[0].status).toBe('changed')
+ expect(diffs[0].currentText).not.toContain('sk-live-supersecret')
+ expect(diffs[0].currentText).toContain('[secret]')
+ expect(diffs[0].proposedText).toContain('sk-live-agent-proposed')
+ })
+
+ it('redacts per-mapping secret inputs on the current side of a mappings diff', () => {
+ const current = {
+ mappings: [
+ {
+ name: 'Slack channel',
+ inputs: { webhook_token: { value: 'xoxb-mapping-secret' } },
+ inputs_schema: [{ key: 'webhook_token', type: 'string', secret: true }],
+ },
+ ],
+ }
+ const proposed = { mappings: [] }
+ const diffs = buildHogFunctionConfigDiff(current, proposed)
+ expect(diffs).toHaveLength(1)
+ expect(diffs[0].status).toBe('removed')
+ expect(diffs[0].currentText).not.toContain('xoxb-mapping-secret')
+ expect(diffs[0].currentText).toContain('[secret]')
+ })
+})
diff --git a/frontend/src/scenes/hog-functions/configuration/hogFunctionConfigDiffUtils.ts b/frontend/src/scenes/hog-functions/configuration/hogFunctionConfigDiffUtils.ts
new file mode 100644
index 000000000000..dc848d534d75
--- /dev/null
+++ b/frontend/src/scenes/hog-functions/configuration/hogFunctionConfigDiffUtils.ts
@@ -0,0 +1,177 @@
+import type { CyclotronJobInputSchemaType, CyclotronJobInputType } from '~/types'
+
+import { getDiffStats } from 'products/posthog_ai/frontend/api/tools'
+
+import { redactSecretHogFunctionInputs } from '../hog-function-utils'
+
+/** How a proposed field relates to the current config: newly set, cleared, or a value change. */
+export type HogFunctionFieldStatus = 'added' | 'removed' | 'changed'
+
+/** One field the agent's `cdp-functions-partial-update` proposes to change, resolved against current config. */
+export interface HogFunctionFieldDiff {
+ field: string
+ /** Sentence-case field label, e.g. 'Filters', 'Source code'. */
+ label: string
+ /** How the field's display text was produced — drives the diff viewer's syntax highlighting. */
+ kind: 'json' | 'text'
+ status: HogFunctionFieldStatus
+ /** Pretty-printed current value (empty when `added`). */
+ currentText: string
+ /** Pretty-printed proposed value (empty when `removed`). */
+ proposedText: string
+ /** Line-level added/removed counts, from the surface's shared `getDiffStats`. */
+ added: number
+ removed: number
+ /** True when either side exceeds the render cap — the card shows the stat summary, not the content. */
+ truncated: boolean
+}
+
+interface DiffableField {
+ field: string
+ label: string
+ kind: 'json' | 'text'
+ /** Optional projection applied to both sides before diffing, to drop server-only noise. */
+ normalize?: (value: unknown) => unknown
+}
+
+/**
+ * `inputs` entries carry server-computed noise (bytecode / order / templating) in the live form config
+ * that the MCP tool strips from its payload. Compare value-only maps so an unchanged input doesn't read
+ * as a change.
+ */
+function normalizeInputs(value: unknown): unknown {
+ if (!value || typeof value !== 'object' || Array.isArray(value)) {
+ return value
+ }
+ const out: Record<string, unknown> = {}
+ for (const [key, entry] of Object.entries(value as Record<string, unknown>)) {
+ out[key] = entry && typeof entry === 'object' && 'value' in entry ? (entry as { value: unknown }).value : entry
+ }
+ return out
+}
+
+// The subset of a hog function's config that `cdp-functions-partial-update` can touch and that reads
+// meaningfully as a diff. Order is display order in the card.
+const DIFFABLE_FIELDS: DiffableField[] = [
+ { field: 'name', label: 'Name', kind: 'text' },
+ { field: 'description', label: 'Description', kind: 'text' },
+ { field: 'enabled', label: 'Enabled', kind: 'text' },
+ { field: 'hog', label: 'Source code', kind: 'text' },
+ { field: 'filters', label: 'Filters', kind: 'json' },
+ { field: 'inputs', label: 'Inputs', kind: 'json', normalize: normalizeInputs },
+ { field: 'inputs_schema', label: 'Inputs schema', kind: 'json' },
+ { field: 'mappings', label: 'Mappings', kind: 'json' },
+ { field: 'masking', label: 'Masking', kind: 'json' },
+]
+
+/**
+ * Per-side character cap — a larger value collapses to the +/- stat summary in the card. The diff
+ * viewer hides unchanged regions, so this is a safety valve against pathological payloads, not a
+ * render budget.
+ */
+export const MAX_DIFF_FIELD_CHARS = 50_000
+
+function isEmptyValue(value: unknown): boolean {
+ if (value == null || value === '') {
+ return true
+ }
+ if (Array.isArray(value)) {
+ return value.length === 0
+ }
+ if (typeof value === 'object') {
+ return Object.keys(value as Record<string, unknown>).length === 0
+ }
+ return false
+}
+
+function toDisplayText(value: unknown, kind: DiffableField['kind']): string {
+ if (value == null) {
+ return ''
+ }
+ if (kind === 'text') {
+ return typeof value === 'string' ? value : String(value)
+ }
+ try {
+ return JSON.stringify(value, null, 2)
+ } catch {
+ return String(value)
+ }
+}
+
+/** A mapping's own inputs carry secrets exactly like top-level inputs do; redact each in place. */
+function redactMappingSecrets(value: unknown): unknown {
+ if (!Array.isArray(value)) {
+ return value
+ }
+ return value.map((mapping) => {
+ if (!mapping || typeof mapping !== 'object') {
+ return mapping
+ }
+ const { inputs, inputs_schema } = mapping as {
+ inputs?: Record<string, CyclotronJobInputType>
+ inputs_schema?: CyclotronJobInputSchemaType[]
+ }
+ return inputs ? { ...mapping, inputs: redactSecretHogFunctionInputs(inputs, inputs_schema ?? []) } : mapping
+ })
+}
+
+/**
+ * Only the current side can hold user secrets (a freshly typed secret is cleartext in form state);
+ * redact it by schema before the value ever reaches the rendered card. The proposed side is
+ * agent-authored, so showing it is not a leak, and redacting it would hide a real change to a
+ * secret input. Secrets live in top-level `inputs` and in each mapping's own `inputs`.
+ */
+function redactCurrentValue(field: string, current: Record<string, unknown>): unknown {
+ if (field === 'inputs') {
+ return redactSecretHogFunctionInputs(
+ (current.inputs ?? {}) as Record<string, CyclotronJobInputType>,
+ (current.inputs_schema ?? []) as CyclotronJobInputSchemaType[]
+ )
+ }
+ if (field === 'mappings') {
+ return redactMappingSecrets(current.mappings)
+ }
+ return current[field]
+}
+
+/**
+ * Builds a field-level diff of a proposed `cdp-functions-partial-update` against the current hog function
+ * config. Only fields present in `proposed` are considered (a partial update leaves the rest untouched);
+ * unchanged fields are dropped. Pure and dependency-light so it's cheap to unit-test.
+ */
+export function buildHogFunctionConfigDiff(
+ current: Record<string, unknown>,
+ proposed: Record<string, unknown>
+): HogFunctionFieldDiff[] {
+ const diffs: HogFunctionFieldDiff[] = []
+ for (const { field, label, kind, normalize } of DIFFABLE_FIELDS) {
+ if (!(field in proposed)) {
+ continue
+ }
+ const rawCurrent = redactCurrentValue(field, current)
+ const currentValue = normalize ? normalize(rawCurrent) : rawCurrent
+ const proposedValue = normalize ? normalize(proposed[field]) : proposed[field]
+ const currentText = toDisplayText(currentValue, kind)
+ const proposedText = toDisplayText(proposedValue, kind)
+ if (currentText === proposedText) {
+ continue
+ }
+ const currentEmpty = isEmptyValue(currentValue)
+ const proposedEmpty = isEmptyValue(proposedValue)
+ const status: HogFunctionFieldStatus =
+ currentEmpty && !proposedEmpty ? 'added' : !currentEmpty && proposedEmpty ? 'removed' : 'changed'
+ const { added, removed } = getDiffStats(currentText, proposedText)
+ diffs.push({
+ field,
+ label,
+ kind,
+ status,
+ currentText,
+ proposedText,
+ added,
+ removed,
+ truncated: currentText.length > MAX_DIFF_FIELD_CHARS || proposedText.length > MAX_DIFF_FIELD_CHARS,
+ })
+ }
+ return diffs
+}
diff --git a/frontend/src/scenes/hog-functions/configuration/registerHogFunctionToolPreviews.tsx b/frontend/src/scenes/hog-functions/configuration/registerHogFunctionToolPreviews.tsx
new file mode 100644
index 000000000000..7b6af3959b15
--- /dev/null
+++ b/frontend/src/scenes/hog-functions/configuration/registerHogFunctionToolPreviews.tsx
@@ -0,0 +1,54 @@
+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/hog-functions/filters/HogFunctionFilters.tsx b/frontend/src/scenes/hog-functions/filters/HogFunctionFilters.tsx
index 7e06670c8ae3..b45322680550 100644
--- a/frontend/src/scenes/hog-functions/filters/HogFunctionFilters.tsx
+++ b/frontend/src/scenes/hog-functions/filters/HogFunctionFilters.tsx
@@ -22,6 +22,7 @@ import { AnyPropertyFilter, CyclotronJobFiltersType, EntityTypes, FilterType } f
import { useAttachedContext } from 'products/posthog_ai/frontend/api/logics'
import { hogFunctionConfigurationLogic } from '../configuration/hogFunctionConfigurationLogic'
+import { truncateHogFunctionContext } from '../hog-function-utils'
import { HogFunctionFiltersInternal } from './HogFunctionFiltersInternal'
const MASKING_HASH_ALL = 'all'
@@ -103,7 +104,9 @@ export function HogFunctionFilters({
useAttachedContext([
{
type: 'hog_function_filters',
- value: JSON.stringify({ filters: configuration?.filters ?? {}, function_type: type }),
+ value: truncateHogFunctionContext(
+ JSON.stringify({ filters: configuration?.filters ?? {}, function_type: type })
+ ),
label: 'Current filters',
},
])
diff --git a/frontend/src/scenes/hog-functions/hog-function-utils.test.ts b/frontend/src/scenes/hog-functions/hog-function-utils.test.ts
index 0b47208b39bc..02450630f600 100644
--- a/frontend/src/scenes/hog-functions/hog-function-utils.test.ts
+++ b/frontend/src/scenes/hog-functions/hog-function-utils.test.ts
@@ -1,4 +1,22 @@
-import { getHogFunctionDeliveryType } from './hog-function-utils'
+import { CyclotronJobInputSchemaType } from '~/types'
+
+import { getHogFunctionDeliveryType, redactSecretHogFunctionInputs } from './hog-function-utils'
+
+// The diff-builder test covers schema-marked secrets end to end; this covers the entry-marked branch
+// (a saved secret carries `secret: true` on the input entry itself, with no schema flag needed).
+describe('redactSecretHogFunctionInputs', () => {
+ it('redacts entry-marked secrets and leaves plain inputs untouched', () => {
+ const redacted = redactSecretHogFunctionInputs(
+ {
+ token: { value: 'tok-cleartext', secret: true },
+ url: { value: 'https://example.com' },
+ },
+ [] as CyclotronJobInputSchemaType[]
+ )
+ expect(redacted.token.value).toBe('[secret]')
+ expect(redacted.url.value).toBe('https://example.com')
+ })
+})
describe('getHogFunctionDeliveryType', () => {
it.each([
diff --git a/frontend/src/scenes/hog-functions/hog-function-utils.ts b/frontend/src/scenes/hog-functions/hog-function-utils.ts
index c3af4f06dee3..3b7915b2d34d 100644
--- a/frontend/src/scenes/hog-functions/hog-function-utils.ts
+++ b/frontend/src/scenes/hog-functions/hog-function-utils.ts
@@ -1,4 +1,4 @@
-import { HogFunctionTypeType } from '~/types'
+import { CyclotronJobInputSchemaType, CyclotronJobInputType, HogFunctionTypeType } from '~/types'
export type HogFunctionDeliveryType = 'batch' | 'realtime'
@@ -16,3 +16,34 @@ export function humanizeHogFunctionType(type: HogFunctionTypeType, plural: boole
}
return type.replaceAll('_', ' ') + (plural ? 's' : '')
}
+
+/** Default char cap for a config blob attached to the PostHog AI agent as context. */
+export const HOG_FUNCTION_CONTEXT_MAX_CHARS = 10_000
+
+/**
+ * Caps a stringified config blob before it's registered as PostHog AI attached context, so a pathological
+ * hog source or inputs payload can't bloat the agent's context window. These are keyed entity-style items
+ * (not `type: 'text'`), so they're sent once per run rather than every turn; the cap is a safety ceiling.
+ */
+export function truncateHogFunctionContext(value: string, max: number = HOG_FUNCTION_CONTEXT_MAX_CHARS): string {
+ return value.length > max ? value.slice(0, max) + '… (truncated)' : value
+}
+
+/**
+ * Replaces secret input values with a placeholder before the live form config leaves the scene (agent
+ * context, approval-card diffs). A saved secret comes back masked from the API, but a value the user
+ * just typed sits in form state in cleartext and must never reach the LLM. An entry counts as secret
+ * when the schema marks its key secret or the entry itself carries `secret: true`.
+ */
+export function redactSecretHogFunctionInputs(
+ inputs: Record<string, CyclotronJobInputType>,
+ inputsSchema: CyclotronJobInputSchemaType[]
+): Record<string, CyclotronJobInputType> {
+ const secretKeys = new Set(inputsSchema.filter((schema) => schema.secret).map((schema) => schema.key))
+ return Object.fromEntries(
+ Object.entries(inputs).map(([key, entry]) => {
+ const isSecret = secretKeys.has(key) || entry?.secret === true
+ return [key, isSecret && entry ? { ...entry, value: '[secret]' } : entry]
+ })
+ )
+}
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 6ccb80c168f5..58d5e4171a7e 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -3941,6 +3941,9 @@ importers:
'@tanstack/react-virtual':
specifier: '*'
+ '@toon-format/toon':
+ specifier: ^2.1.0
+ version: 2.1.0
'@types/react':
specifier: 18.3.27
version: 18.3.27
diff --git a/products/posthog_ai/frontend/api/tools.ts b/products/posthog_ai/frontend/api/tools.ts
index 09fb941792a7..0a06140bb9f0 100644
--- a/products/posthog_ai/frontend/api/tools.ts
+++ b/products/posthog_ai/frontend/api/tools.ts
@@ -1,5 +1,11 @@
export { toolRegistry, lookupToolRenderer, registerToolRenderers } from '../components/tool/toolRegistry'
-export type { ToolRendererProps, ToolRegistryEntry, ToolRegistry } from '../components/tool/toolRegistry'
+export type {
+ ToolRendererProps,
+ ToolRegistryEntry,
+ ResolvedToolRegistryEntry,
+ ToolRegistry,
+} from '../components/tool/toolRegistry'
+export { getPermissionRequestToolInput, resolveToolCall } from '../utils/toolResolver'
export { GenericMcpToolRenderer } from '../components/tool/GenericMcpToolRenderer'
export { DataToolRow } from '../components/tool/DataToolRow'
export { ToolActivity } from '../components/tool/ToolActivity'
@@ -7,3 +13,5 @@ export type { ToolActivityProps } from '../components/tool/ToolActivity'
export { FilePath } from '../components/tool/FilePath'
export { findAllDiffContent, getDiffStats, languageFromPath } from '../components/tool/toolDiffContent'
export type { ToolCallDiffContent } from '../components/tool/toolDiffContent'
+export { DiffEvidenceCard } from '../components/tool/DiffEvidenceCard'
+export type { DiffEvidenceCardProps } from '../components/tool/DiffEvidenceCard'
diff --git a/products/posthog_ai/frontend/components/PermissionInput.tsx b/products/posthog_ai/frontend/components/PermissionInput.tsx
index d9bc1da275f5..5c51c88b1118 100644
--- a/products/posthog_ai/frontend/components/PermissionInput.tsx
+++ b/products/posthog_ai/frontend/components/PermissionInput.tsx
@@ -1,4 +1,6 @@
import { useActions, useValues } from 'kea'
+import posthog from 'posthog-js'
+import type { ReactNode } from 'react'
import { useEffect, useRef, useState } from 'react'
import { IconWarning } from '@posthog/icons'
@@ -12,10 +14,12 @@ import { MarkdownMessage } from '../messages/MarkdownMessage'
import { getPermissionDisplay } from '../policy/permissionDisplayUtils'
import { isPlanPermissionRequest, mapPermissionOptions, type ApprovalCardOption } from '../policy/permissionUtils'
import type { PermissionRequestRecord } from '../types/streamTypes'
+import { resolveToolCall } from '../utils/toolResolver'
import { isPlanApprovalModeOptionId, InlineEditableText, PlanApprovalSelector } from './PlanApprovalActions'
import { DiffEditor, DiffStats } from './tool/EditDiffRenderer'
import { FilePath } from './tool/FilePath'
import { findAllDiffContent, getDiffStats } from './tool/toolDiffContent'
+import { lookupToolRenderer } from './tool/toolRegistry'
interface PermissionInputProps {
streamKey: string
@@ -25,6 +29,21 @@ 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 {
@@ -348,6 +367,11 @@ export function PermissionInput({ streamKey, request }: PermissionInputProps): J
// 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)
+
return (
<div className="flex flex-col gap-2.5 p-3">
<div className="flex items-start gap-2 text-sm font-medium">
@@ -360,11 +384,15 @@ export function PermissionInput({ streamKey, request }: PermissionInputProps): J
<span>{display.title ?? 'Approval required'}</span>
)}
</div>
- <PermissionEvidence
- request={request}
- label={headlineBody ? display.title : undefined}
- payload={display.payload}
- />
+ {previewNode ? (
+ <div className="max-h-80 overflow-y-auto">{previewNode}</div>
+ ) : (
+ <PermissionEvidence
+ request={request}
+ label={headlineBody ? display.title : undefined}
+ payload={display.payload}
+ />
+ )}
{respondingToPermission ? (
<div className="flex items-center gap-2 text-muted pt-1">
<Spinner className="size-4" />
diff --git a/products/posthog_ai/frontend/components/composer/Composer.test.tsx b/products/posthog_ai/frontend/components/composer/Composer.test.tsx
index 5d47cce12b55..7d0aa71c0263 100644
--- a/products/posthog_ai/frontend/components/composer/Composer.test.tsx
+++ b/products/posthog_ai/frontend/components/composer/Composer.test.tsx
@@ -77,6 +77,17 @@ describe('Composer', () => {
expect(onSubmit).toHaveBeenCalledTimes(1)
})
+ it('submits on Enter and keeps Shift+Enter for new lines', () => {
+ renderComposer({ value: 'ship it' })
+ const textarea = screen.getByRole('textbox')
+
+ fireEvent.keyDown(textarea, { key: 'Enter', shiftKey: true })
+ expect(onSubmit).not.toHaveBeenCalled()
+
+ fireEvent.keyDown(textarea, { key: 'Enter' })
+ expect(onSubmit).toHaveBeenCalledTimes(1)
+ })
+
it('turns the send button into a Stop button while a turn is active with empty input', () => {
const { container } = renderComposer({ value: '', isTurnActive: true, onStop })
// Enabled (no "Type a message first"), and clicking cancels the run rather than submitting the form.
diff --git a/products/posthog_ai/frontend/components/composer/Composer.tsx b/products/posthog_ai/frontend/components/composer/Composer.tsx
index 5ca74e65f218..834fcb3fc1ef 100644
--- a/products/posthog_ai/frontend/components/composer/Composer.tsx
+++ b/products/posthog_ai/frontend/components/composer/Composer.tsx
@@ -290,26 +290,20 @@ export interface ComposerTextareaProps {
autoFocus?: boolean
minRows?: number
maxRows?: number
- /** `'enter'` submits on Enter (PostHog AI), `'cmd-enter'` on Cmd/Ctrl+Enter (tasks composer). */
- submitShortcut?: 'enter' | 'cmd-enter'
- /** Extra key handling (e.g. the mode picker's `shift+tab` cycle); runs after the submit shortcut. */
+ /** Extra key handling (e.g. the mode picker's `shift+tab` cycle); runs after Enter handling. */
onKeyDown?: KeyboardEventHandler<HTMLTextAreaElement>
'data-attr'?: string
}
-/** The textarea itself, wired to the context value/submit. */
+/** The textarea itself, wired to the context value/submit. Submits on Enter, Shift+Enter for a newline. */
function ComposerTextarea({
className,
autoFocus,
minRows = 1,
maxRows = 10,
- submitShortcut = 'enter',
...rest
}: ComposerTextareaProps): JSX.Element {
const { value, onChange, submit, textAreaRef, disabled, id } = useComposerContext()
- // onPressEnter / onPressCmdEnter are mutually exclusive in LemonTextArea's type — pick one.
- const submitProps =
- submitShortcut === 'cmd-enter' ? { onPressCmdEnter: () => submit() } : { onPressEnter: () => submit() }
return (
<LemonTextArea
id={id}
@@ -323,7 +317,7 @@ function ComposerTextarea({
autoFocus={autoFocus}
className={cn('!border-none !bg-transparent min-h-16 py-2 pl-2 pr-12 resize-none', className)}
hideFocus
- {...submitProps}
+ onPressEnter={() => submit()}
{...rest}
/>
)
diff --git a/products/posthog_ai/frontend/components/tool/DiffEvidenceCard.tsx b/products/posthog_ai/frontend/components/tool/DiffEvidenceCard.tsx
new file mode 100644
index 000000000000..ebd4d09ac049
--- /dev/null
+++ b/products/posthog_ai/frontend/components/tool/DiffEvidenceCard.tsx
@@ -0,0 +1,66 @@
+import type { ReactNode } from 'react'
+import { useState } from 'react'
+
+import { Button } from '@posthog/quill-primitives'
+
+import { cn } from 'lib/utils/css-classes'
+
+import { DiffEditor, DiffStats } from './EditDiffRenderer'
+import { getDiffStats } from './toolDiffContent'
+
+/** Collapsed body cap — roughly a dozen diff lines, per the permission-card evidence design. Must stay in sync with the `max-h-60` class below. */
+const COLLAPSED_MAX_HEIGHT_PX = 240
+/** Monaco's approximate diff line height, used to decide whether the cap would actually clip. */
+const APPROX_LINE_HEIGHT_PX = 18
+
+export interface DiffEvidenceCardProps {
+ /** Identity in the header bar — a field label ('Source code') or a file path node. */
+ label: ReactNode
+ /** Current content; null renders an all-additions diff (nothing existed before). */
+ oldText: string | null
+ /** Proposed content; empty renders an all-deletions diff. */
+ newText: string
+ /** Pseudo/real path driving the diff viewer's syntax highlighting. */
+ path?: string
+}
+
+/**
+ * The permission card's evidence block for a change payload: a bordered card whose header bar carries
+ * the identity and the +/- line stats, and whose body is the shared diff viewer showing every line
+ * (side-by-side when the container affords it, no collapsed unchanged regions). Bodies taller than the
+ * cap start clipped behind a fade with a "Show all n lines" expander, so the card stays scannable
+ * without hiding what changed.
+ */
+export function DiffEvidenceCard({ label, oldText, newText, path }: DiffEvidenceCardProps): JSX.Element {
+ const [showAll, setShowAll] = useState(false)
+
+ const { added, removed } = getDiffStats(oldText, newText)
+ const lineCount = Math.max(oldText?.split('\n').length ?? 0, newText ? newText.split('\n').length : 0)
+ const collapsible = lineCount * APPROX_LINE_HEIGHT_PX > COLLAPSED_MAX_HEIGHT_PX
+ const collapsed = collapsible && !showAll
+
+ return (
+ <div className="flex flex-col rounded border border-border-secondary overflow-hidden min-w-0">
+ <div className="flex items-center gap-2 border-b border-border-secondary bg-surface-secondary px-2 py-1 text-xs min-w-0">
+ <span className="font-mono font-medium truncate">{label}</span>
+ <DiffStats added={added} removed={removed} />
+ </div>
+ <div className={cn('min-w-0', collapsed && 'relative max-h-60 overflow-hidden')}>
+ <DiffEditor diff={{ type: 'diff', oldText, newText }} path={path} sideBySide hideUnchanged={false} />
+ {collapsed && (
+ <div className="absolute inset-x-0 bottom-0 h-10 bg-gradient-to-t from-surface-primary to-transparent pointer-events-none" />
+ )}
+ </div>
+ {collapsible && (
+ <Button
+ variant="link-muted"
+ size="xs"
+ className="self-center my-0.5"
+ onClick={() => setShowAll(!showAll)}
+ >
+ {showAll ? 'Show less' : `Show all ${lineCount} lines`}
+ </Button>
+ )}
+ </div>
+ )
+}
diff --git a/products/posthog_ai/frontend/components/tool/EditDiffRenderer.tsx b/products/posthog_ai/frontend/components/tool/EditDiffRenderer.tsx
index 9d1fe8e278c9..512dd69d4e8a 100644
--- a/products/posthog_ai/frontend/components/tool/EditDiffRenderer.tsx
+++ b/products/posthog_ai/frontend/components/tool/EditDiffRenderer.tsx
@@ -55,14 +55,34 @@ const SIDE_BY_SIDE_DIFF_EDITOR_OPTIONS: editor.IDiffEditorConstructionOptions =
renderSideBySideInlineBreakpoint: 560,
}
+// Show-everything variants for evidence cards that cap height themselves — collapsing unchanged
+// regions AND capping would hide the same content twice and make the expand affordance lie.
+const SHOW_ALL_DIFF_EDITOR_OPTIONS: editor.IDiffEditorConstructionOptions = {
+ ...DIFF_EDITOR_OPTIONS,
+ hideUnchangedRegions: { enabled: false },
+}
+const SIDE_BY_SIDE_SHOW_ALL_DIFF_EDITOR_OPTIONS: editor.IDiffEditorConstructionOptions = {
+ ...SIDE_BY_SIDE_DIFF_EDITOR_OPTIONS,
+ hideUnchangedRegions: { enabled: false },
+}
+
+function pickDiffEditorOptions(sideBySide: boolean, hideUnchanged: boolean): editor.IDiffEditorConstructionOptions {
+ if (sideBySide) {
+ return hideUnchanged ? SIDE_BY_SIDE_DIFF_EDITOR_OPTIONS : SIDE_BY_SIDE_SHOW_ALL_DIFF_EDITOR_OPTIONS
+ }
+ return hideUnchanged ? DIFF_EDITOR_OPTIONS : SHOW_ALL_DIFF_EDITOR_OPTIONS
+}
+
export function DiffEditor({
diff,
path,
sideBySide,
+ hideUnchanged = true,
}: {
diff: ToolCallDiffContent
path?: string
sideBySide?: boolean
+ hideUnchanged?: boolean
}): JSX.Element {
// Lazy-mount: only instantiate the Monaco diff editor once the card scrolls near the viewport.
const { ref, inView } = useInView({ rootMargin: '500px', triggerOnce: true })
@@ -78,7 +98,7 @@ export function DiffEditor({
modified={diff.newText ?? ''}
language={languageFromPath(path)}
theme={isDarkModeOn ? 'vs-dark' : 'vs'}
- options={sideBySide ? SIDE_BY_SIDE_DIFF_EDITOR_OPTIONS : DIFF_EDITOR_OPTIONS}
+ options={pickDiffEditorOptions(!!sideBySide, hideUnchanged)}
loading={<EditorSkeleton />}
/>
) : (
diff --git a/products/posthog_ai/frontend/components/tool/toolRegistry.test.tsx b/products/posthog_ai/frontend/components/tool/toolRegistry.test.tsx
index e2801328762d..715b5f3e45f7 100644
--- a/products/posthog_ai/frontend/components/tool/toolRegistry.test.tsx
+++ b/products/posthog_ai/frontend/components/tool/toolRegistry.test.tsx
@@ -1,6 +1,7 @@
import '@testing-library/jest-dom'
import { render, screen } from '@testing-library/react'
+import type { ReactNode } from 'react'
import type { ToolCallMessage } from 'products/posthog_ai/frontend/types/toolTypes'
@@ -44,6 +45,25 @@ describe('toolRegistry', () => {
expect(toolRegistry.lookup('query-trends')?.displayName).toEqual('Trends query')
})
+ // 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('falls back to the key as displayName for unknown and unmapped tool names', () => {
expect(toolRegistry.lookup('mcp__user-installed__something')).toBeNull()
// The synthesized fallback uses the resolved key as its displayName.
diff --git a/products/posthog_ai/frontend/components/tool/toolRegistry.tsx b/products/posthog_ai/frontend/components/tool/toolRegistry.tsx
index f88a7db227e0..1b3fad91303e 100644
--- a/products/posthog_ai/frontend/components/tool/toolRegistry.tsx
+++ b/products/posthog_ai/frontend/components/tool/toolRegistry.tsx
@@ -1,4 +1,4 @@
-import { type ComponentType, type LazyExoticComponent } from 'react'
+import { type ComponentType, type LazyExoticComponent, type ReactNode } from 'react'
import {
IconAI,
@@ -20,6 +20,7 @@ import {
import { IconRobot } from 'lib/lemon-ui/icons'
import { lazyWithRetry } from 'lib/utils/retryImport'
+import type { PermissionRequestRecord } from 'products/posthog_ai/frontend/types/streamTypes'
import type { ToolCallMessage } from 'products/posthog_ai/frontend/types/toolTypes'
export interface ToolRendererProps {
@@ -52,7 +53,20 @@ export interface ToolRegistryEntry {
/** Display name / icon for fallback rendering and for the tool-call header line. */
displayName: string
icon: JSX.Element
- Renderer: ToolRendererComponent
+ /**
+ * 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`.
+ */
+ 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
/**
* 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
@@ -65,6 +79,11 @@ export interface ToolRegistryEntry {
requiresPostHogOrigin?: boolean
}
+/** A registry entry resolved for the card path — `lookupToolRenderer` guarantees a `Renderer`. */
+export interface ResolvedToolRegistryEntry extends ToolRegistryEntry {
+ Renderer: ToolRendererComponent
+}
+
export interface ToolRegistry {
register: (entry: ToolRegistryEntry) => void
lookup: (toolName: string) => ToolRegistryEntry | null
@@ -204,12 +223,14 @@ toolRegistry.register({
* `fromPostHogExec` is whether the call came through the trusted single-exec PostHog server (its inner
* tool name was parsed out of the exec command). An entry marked `requiresPostHogOrigin` only matches a
* trusted call, so a third-party tool whose bare name collides with a product-widget key can't spoof a
- * first-party card — it falls through to the generic card here.
+ * 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
+ * result card stays the built-in one.
*/
-export function lookupToolRenderer(resolvedKey: string, fromPostHogExec: boolean): ToolRegistryEntry {
+export function lookupToolRenderer(resolvedKey: string, fromPostHogExec: boolean): ResolvedToolRegistryEntry {
const entry = toolRegistry.lookup(resolvedKey)
if (entry && (!entry.requiresPostHogOrigin || fromPostHogExec)) {
- return entry
+ return { ...entry, Renderer: entry.Renderer ?? BuiltinToolRenderer }
}
return {
key: resolvedKey,
diff --git a/products/posthog_ai/frontend/components/tool/widgets/CreateNotebookWidget.tsx b/products/posthog_ai/frontend/components/tool/widgets/CreateNotebookWidget.tsx
index bdec40b7cb8f..614ce578e454 100644
--- a/products/posthog_ai/frontend/components/tool/widgets/CreateNotebookWidget.tsx
+++ b/products/posthog_ai/frontend/components/tool/widgets/CreateNotebookWidget.tsx
@@ -8,6 +8,7 @@ import { MessageTemplate } from '../../../messages/MessageTemplate'
import { DataToolRow } from '../DataToolRow'
import { GenericMcpToolRenderer } from '../GenericMcpToolRenderer'
import type { ToolRendererProps } from '../toolRegistry'
+import { parseToolOutputRecord } from './extractors'
/** The notebook fields the widget renders, pulled from the REST payload. */
export interface NotebookExtraction {
@@ -23,8 +24,8 @@ export interface NotebookExtraction {
* generic card.
*/
export function extractNotebook(message: ToolRendererProps['message']): NotebookExtraction | null {
- const output = message.rawOutput
- if (!output || typeof output !== 'object' || Array.isArray(output)) {
+ const output = parseToolOutputRecord(message)
+ if (!output) {
return null
}
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 3dadf06136e6..1ea685cef186 100644
--- a/products/posthog_ai/frontend/components/tool/widgets/extractors.test.ts
+++ b/products/posthog_ai/frontend/components/tool/widgets/extractors.test.ts
@@ -69,6 +69,30 @@ describe('mcp tool adapter extractors', () => {
)
expect(dashboard).toEqual({ id: '7', name: 'From input', url: '/dashboard/7' })
})
+
+ // String rawOutput goes through the best-effort JSON/TOON parse — exec `call`s respond with
+ // JSON when `--json` was passed and TOON otherwise, and the off-order format is a fallback.
+ test.each([
+ [
+ 'JSON output when the command carried --json',
+ 'call --json dashboard-create {}',
+ '{"id": 7, "name": "Growth"}',
+ ],
+ ['TOON output when the command had no flag', 'call dashboard-create {}', 'id: 7\nname: Growth'],
+ ['JSON output even without the flag', 'call dashboard-create {}', '{"id": 7, "name": "Growth"}'],
+ ])('parses %s', (_name, command, rawOutput) => {
+ const dashboard = extractDashboard({ ...toolMessage(rawOutput), rawInput: { command } })
+ expect(dashboard?.id).toBe(7)
+ expect(dashboard?.name).toBe('Growth')
+ })
+
+ it('extracts nothing when a string output parses as neither JSON nor TOON', () => {
+ const dashboard = extractDashboard({
+ ...toolMessage('created the dashboard for you'),
+ rawInput: { command: 'call dashboard-create {}' },
+ })
+ expect(dashboard).toBeNull()
+ })
})
describe('extractRecordingFilters', () => {
diff --git a/products/posthog_ai/frontend/components/tool/widgets/extractors.ts b/products/posthog_ai/frontend/components/tool/widgets/extractors.ts
index a32841cbc5fd..a28c39e22d2e 100644
--- a/products/posthog_ai/frontend/components/tool/widgets/extractors.ts
+++ b/products/posthog_ai/frontend/components/tool/widgets/extractors.ts
@@ -1,3 +1,5 @@
+import { decode } from '@toon-format/toon'
+
import { recordingsQueryToUniversalFilters } from 'scenes/session-recordings/filters/recordingsQueryConversions'
import { MaxErrorTrackingSearchResponse } from '~/queries/schema/schema-assistant-error-tracking'
@@ -14,6 +16,8 @@ import { RecordingUniversalFilters } from '~/types'
import type { ToolCallMessage } from 'products/posthog_ai/frontend/types/toolTypes'
+import { parseExecCall, parseExecCommand } from '../posthogExecDisplay'
+
/**
* 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
@@ -24,6 +28,59 @@ function asRecord(value: unknown): Record<string, unknown> | null {
return value && typeof value === 'object' && !Array.isArray(value) ? (value as Record<string, unknown>) : null
}
+function parseJsonRecord(text: string): Record<string, unknown> | null {
+ try {
+ return asRecord(JSON.parse(text))
+ } catch {
+ return null
+ }
+}
+
+function parseToonRecord(text: string): Record<string, unknown> | null {
+ // TOON decode is lenient — JSON text doesn't throw, it mangles into a garbage record — so
+ // anything that reads as JSON syntax must never reach it.
+ if (/^[[{]/.test(text)) {
+ return null
+ }
+ try {
+ return asRecord(decode(text))
+ } catch {
+ return null
+ }
+}
+
+/**
+ * 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 widget falls back to the generic card.
+ */
+export function parseToolOutputRecord(message: ToolCallMessage): Record<string, unknown> | null {
+ const direct = asRecord(message.rawOutput)
+ if (direct) {
+ return direct
+ }
+ if (typeof message.rawOutput !== 'string') {
+ return null
+ }
+ const text = message.rawOutput.trim()
+ if (!text) {
+ return null
+ }
+ const command = typeof message.rawInput.command === 'string' ? message.rawInput.command : ''
+ const { verb, rest } = parseExecCommand(command)
+ const forceJson = verb === 'call' && parseExecCall(rest).forceJson
+ const attempts = forceJson ? [parseJsonRecord, parseToonRecord] : [parseToonRecord, parseJsonRecord]
+ for (const attempt of attempts) {
+ const record = attempt(text)
+ // decode('') and JSON '{}' both yield {}, which carries nothing a widget can render.
+ if (record && Object.keys(record).length > 0) {
+ return record
+ }
+ }
+ return null
+}
+
function asString(value: unknown): string | undefined {
return typeof value === 'string' ? value : undefined
}
@@ -72,7 +129,7 @@ export interface VisualizationArtifactExtraction {
* query-only outputs carry neither and render inline as ephemeral visualizations.
*/
export function extractVisualizationArtifact(message: ToolCallMessage): VisualizationArtifactExtraction | null {
- const output = asRecord(message.rawOutput)
+ const output = parseToolOutputRecord(message)
if (!output) {
return null
}
@@ -118,7 +175,7 @@ export interface QueryResultExtraction {
* renderer (e.g. a single LLM trace) return null and fall back to the generic card.
*/
export function extractQueryResult(message: ToolCallMessage): QueryResultExtraction | null {
- const output = asRecord(message.rawOutput)
+ const output = parseToolOutputRecord(message)
const query = (output ? asRecord(output.query) : null) ?? queryFromToolInput(message)
if (!query || typeof query.kind !== 'string') {
return null
@@ -161,7 +218,7 @@ export interface DashboardExtraction {
}
export function extractDashboard(message: ToolCallMessage): DashboardExtraction | null {
- const output = asRecord(message.rawOutput)
+ const output = parseToolOutputRecord(message)
if (!output) {
return null
}
@@ -180,7 +237,7 @@ export function extractDashboard(message: ToolCallMessage): DashboardExtraction
* falls back to the generic card rather than feeding the playlist a shape it can't use.
*/
export function extractRecordingFilters(message: ToolCallMessage): RecordingUniversalFilters | null {
- const output = asRecord(message.rawOutput)
+ const output = parseToolOutputRecord(message)
if (!output) {
return null
}
@@ -223,7 +280,7 @@ const ERROR_TRACKING_RESPONSE_KEYS: readonly (keyof MaxErrorTrackingSearchRespon
* REST issues list — fall back to the generic card instead of rendering empty filter chips.
*/
export function extractErrorTrackingResponse(message: ToolCallMessage): MaxErrorTrackingSearchResponse | null {
- const output = asRecord(message.rawOutput)
+ const output = parseToolOutputRecord(message)
if (!output || !ERROR_TRACKING_RESPONSE_KEYS.some((key) => key in output)) {
return null
}
diff --git a/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskComposer.tsx b/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskComposer.tsx
index 6446706c99da..2aaf0e35cfcc 100644
--- a/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskComposer.tsx
+++ b/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskComposer.tsx
@@ -75,11 +75,7 @@ export function TaskComposer(): JSX.Element {
</Composer.Header>
<Composer.Field>
<Composer.Placeholder>Describe the task in detail…</Composer.Placeholder>
- <Composer.Textarea
- submitShortcut="cmd-enter"
- autoFocus
- data-attr="task-composer-input"
- />
+ <Composer.Textarea autoFocus data-attr="task-composer-input" />
</Composer.Field>
<Composer.Footer className="flex flex-wrap items-center gap-1 pl-2">
<ComposerModePicker
diff --git a/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskRunChat.tsx b/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskRunChat.tsx
index c284f2a8d4d4..ea45becf0507 100644
--- a/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskRunChat.tsx
+++ b/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskRunChat.tsx
@@ -162,7 +162,7 @@ function LiveComposer({ logicProps }: { logicProps: RunInteractionLogicProps }):
<Composer.Placeholder>
{isTerminal ? 'Send a message to start a new run…' : 'Send a follow-up message…'}
</Composer.Placeholder>
- <Composer.Textarea data-attr="sandbox-composer-input" submitShortcut="cmd-enter" />
+ <Composer.Textarea data-attr="sandbox-composer-input" />
</Composer.Field>
<Composer.Footer className="flex flex-wrap items-center gap-1 pl-2">
{/* Mode + model/effort pickers: selection lives in the bound runInteractionLogic and is
diff --git a/products/posthog_ai/frontend/utils/toolResolver.ts b/products/posthog_ai/frontend/utils/toolResolver.ts
index 437ac79265b9..d4f5d1a2a536 100644
--- a/products/posthog_ai/frontend/utils/toolResolver.ts
+++ b/products/posthog_ai/frontend/utils/toolResolver.ts
@@ -1,4 +1,5 @@
import { parseExecCall, parseExecCommand, POSTHOG_EXEC_TOOL_RE } from '../components/tool/posthogExecDisplay'
+import type { PermissionRequestRecord } from '../types/streamTypes'
export interface ResolvedToolKey {
resolvedKey: string
@@ -90,3 +91,20 @@ export function resolveToolCall(toolCall: ResolvableToolCall): ResolvedToolCall
claudeToolName,
}
}
+
+/**
+ * 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
+ * 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.
+ */
+export function getPermissionRequestToolInput(record: PermissionRequestRecord): Record<string, unknown> {
+ const resolved = resolveToolCall(record.rawToolCall)
+ if (resolved.innerInput && Object.keys(resolved.innerInput).length > 0) {
+ return resolved.innerInput
+ }
+ const explicit = (record.rawToolCall.input as { input?: unknown }).input
+ return explicit && typeof explicit === 'object' && !Array.isArray(explicit)
+ ? (explicit as Record<string, unknown>)
+ : {}
+}
diff --git a/products/posthog_ai/package.json b/products/posthog_ai/package.json
index d46759ad89ec..a523591287ae 100644
--- a/products/posthog_ai/package.json
+++ b/products/posthog_ai/package.json
@@ -6,6 +6,7 @@
"dependencies": {
"@posthog/quill-primitives": "workspace:*",
"@tanstack/react-virtual": "*",
+ "@toon-format/toon": "^2.1.0",
"eventsource-parser": "*",
"kea-subscriptions": "catalog:",
"marked": "*",