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(workflows): open the ai panel with workflow context pre-attached (#80639)

Harley Alexanderfc9657982163
diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsx
index a061e88cb546..a55b0cbf0577 100644
--- a/frontend/src/lib/constants.tsx
+++ b/frontend/src/lib/constants.tsx
@@ -424,6 +424,7 @@ export const FEATURE_FLAGS = {
PASSWORD_PROTECTED_SHARES: 'password-protected-shares', // owner: @aspicer
PHAI_PLAN_MODE: 'phai-plan-mode', // owner: #team-posthog-ai
PHAI_SANDBOX_MODE: 'phai-sandbox-mode', // owner: #team-posthog-ai
+ PHAI_SCENE_AUTO_OPEN: 'phai-scene-auto-open', // owner: #team-posthog-ai
PHAI_TASKS: 'phai-tasks', // owner: #team-array
PIPELINE_STATUS_PAGE: 'pipeline-status-page', // owner: @clr182 #team-support
POSTHOG_AI_BILLING_DISPLAY: 'posthog-ai-billing-display', // owner: #team-posthog-ai
diff --git a/frontend/src/scenes/max/max-storage-keys.ts b/frontend/src/scenes/max/max-storage-keys.ts
index ea4c664299ea..9cf644927a77 100644
--- a/frontend/src/scenes/max/max-storage-keys.ts
+++ b/frontend/src/scenes/max/max-storage-keys.ts
@@ -8,3 +8,6 @@ export const PENDING_AI_PROMPT_KEY = 'posthog_ai_pending_prompt'
/** Which PostHog AI implementation the Max scene renders when the sandbox flag is on (see maxGlobalLogic). */
export const PHAI_VIEW_MODE_KEY = 'posthog_ai_view_mode'
+
+/** Scene keys whose PostHog AI panel auto-open the user has dismissed (see sceneAgentPanelLogic). */
+export const PHAI_SCENE_AUTO_OPEN_DISMISSED_KEY = 'posthog_ai_scene_auto_open_dismissed'
diff --git a/frontend/src/scenes/max/sceneAgentPanelLogic.test.ts b/frontend/src/scenes/max/sceneAgentPanelLogic.test.ts
new file mode 100644
index 000000000000..94f63e525129
--- /dev/null
+++ b/frontend/src/scenes/max/sceneAgentPanelLogic.test.ts
@@ -0,0 +1,206 @@
+import { expectLogic } from 'kea-test-utils'
+
+import { FEATURE_FLAGS } from 'lib/constants'
+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
+
+import { sidePanelStateLogic } from '~/layout/navigation-3000/sidepanel/sidePanelStateLogic'
+import { useMocks } from '~/mocks/jest'
+import { initKeaTests } from '~/test/init'
+import { SidePanelTab } from '~/types'
+
+import { sceneAgentPanelLogic } from './sceneAgentPanelLogic'
+import { maxMocks } from './testUtils'
+
+describe('sceneAgentPanelLogic', () => {
+ let logic: ReturnType<typeof sceneAgentPanelLogic.build>
+
+ const setFlags = (flags: string[]): void => {
+ featureFlagLogic.actions.setFeatureFlags(flags, Object.fromEntries(flags.map((flag) => [flag, true])))
+ }
+
+ const allFlags = [FEATURE_FLAGS.PHAI_SCENE_AUTO_OPEN, FEATURE_FLAGS.PHAI_SANDBOX_MODE]
+
+ beforeEach(() => {
+ useMocks(maxMocks)
+ initKeaTests()
+ localStorage.clear()
+ sidePanelStateLogic.mount()
+ sidePanelStateLogic.actions.setSidePanelAvailable(true)
+ logic = sceneAgentPanelLogic()
+ logic.mount()
+ })
+
+ afterEach(() => {
+ logic?.unmount()
+ })
+
+ it('opens the PostHog AI panel when a scene registers and all gates pass', async () => {
+ setFlags(allFlags)
+
+ await expectLogic(logic, () => {
+ logic.actions.sceneEntered('workflow')
+ }).toFinishAllListeners()
+
+ expect(sidePanelStateLogic.values.sidePanelOpen).toBe(true)
+ expect(sidePanelStateLogic.values.selectedTab).toBe(SidePanelTab.Max)
+ })
+
+ // Auto-open is the most intrusive behavior here: any gate regression leaks a self-opening panel
+ // to users who never opted in (flag off), users on the legacy Max view (which has no attached-context
+ // consumer), or clobbers a panel the user explicitly opened.
+ it.each([
+ {
+ name: 'the auto-open flag is off',
+ flags: [FEATURE_FLAGS.PHAI_SANDBOX_MODE],
+ setup: () => {},
+ },
+ {
+ name: 'the sandbox flag is off (legacy Max view)',
+ flags: [FEATURE_FLAGS.PHAI_SCENE_AUTO_OPEN],
+ setup: () => {},
+ },
+ {
+ name: 'another side panel tab is open',
+ flags: allFlags,
+ setup: () => sidePanelStateLogic.actions.openSidePanel(SidePanelTab.Notebooks),
+ },
+ {
+ name: 'the side panel is unavailable',
+ flags: allFlags,
+ setup: () => sidePanelStateLogic.actions.setSidePanelAvailable(false),
+ },
+ ])('does not open the panel when $name', async ({ flags, setup }) => {
+ setFlags(flags)
+ setup()
+ const tabBefore = sidePanelStateLogic.values.selectedTab
+
+ await expectLogic(logic, () => {
+ logic.actions.sceneEntered('workflow')
+ }).toFinishAllListeners()
+
+ expect(sidePanelStateLogic.values.selectedTab).toBe(tabBefore)
+ expect(sidePanelStateLogic.values.sidePanelOpen).toBe(tabBefore !== null)
+ })
+
+ it('records a persisted dismissal when the user closes the panel, and stops auto-opening that scene', async () => {
+ setFlags(allFlags)
+
+ await expectLogic(logic, () => {
+ logic.actions.sceneEntered('workflow')
+ }).toFinishAllListeners()
+ expect(sidePanelStateLogic.values.sidePanelOpen).toBe(true)
+
+ await expectLogic(logic, () => {
+ sidePanelStateLogic.actions.closeSidePanel()
+ }).toFinishAllListeners()
+ expect(logic.values.autoOpenDismissedScenes).toEqual({ workflow: true })
+
+ // Re-entering the scene (e.g. navigating away and back) must respect the dismissal.
+ await expectLogic(logic, () => {
+ logic.actions.sceneLeft('workflow')
+ logic.actions.sceneEntered('workflow')
+ }).toFinishAllListeners()
+ expect(sidePanelStateLogic.values.sidePanelOpen).toBe(false)
+ })
+
+ // Closing an unrelated tab (e.g. docs panel the user peeked at) must not count as dismissing
+ // the AI panel for the active scene.
+ it('does not record a dismissal when a non-Max tab is closed', async () => {
+ setFlags(allFlags)
+
+ await expectLogic(logic, () => {
+ logic.actions.sceneEntered('workflow')
+ }).toFinishAllListeners()
+ sidePanelStateLogic.actions.openSidePanel(SidePanelTab.Support)
+
+ await expectLogic(logic, () => {
+ sidePanelStateLogic.actions.closeSidePanel(SidePanelTab.Support)
+ }).toFinishAllListeners()
+
+ expect(logic.values.autoOpenDismissedScenes).toEqual({})
+ })
+
+ // A user who closes Max on the scene before the feature reaches them (flag off / legacy view)
+ // never exercised auto-open, so it must not be recorded as a permanent opt-out.
+ it('does not record a dismissal when the auto-open flag is off', async () => {
+ setFlags([FEATURE_FLAGS.PHAI_SANDBOX_MODE])
+ sidePanelStateLogic.actions.openSidePanel(SidePanelTab.Max)
+
+ await expectLogic(logic, () => {
+ logic.actions.sceneEntered('workflow')
+ sidePanelStateLogic.actions.closeSidePanel()
+ }).toFinishAllListeners()
+
+ expect(logic.values.autoOpenDismissedScenes).toEqual({})
+ })
+
+ // On a cold load the gates resolve asynchronously; a scene entered before they land must still
+ // get its auto-open when they do, not silently miss it until the user re-enters the scene.
+ it.each([
+ {
+ name: 'the feature flags load after the scene was entered',
+ setup: () => {},
+ resolve: () => setFlags(allFlags),
+ },
+ {
+ name: 'the side panel becomes available after the scene was entered',
+ setup: () => {
+ setFlags(allFlags)
+ sidePanelStateLogic.actions.setSidePanelAvailable(false)
+ },
+ resolve: () => sidePanelStateLogic.actions.setSidePanelAvailable(true),
+ },
+ ])('opens the panel when $name', async ({ setup, resolve }) => {
+ setup()
+
+ await expectLogic(logic, () => {
+ logic.actions.sceneEntered('workflow')
+ }).toFinishAllListeners()
+ expect(sidePanelStateLogic.values.sidePanelOpen).toBe(false)
+
+ await expectLogic(logic, () => {
+ resolve()
+ }).toFinishAllListeners()
+ expect(sidePanelStateLogic.values.selectedTab).toBe(SidePanelTab.Max)
+ expect(sidePanelStateLogic.values.sidePanelOpen).toBe(true)
+ })
+
+ // Flags re-resolve throughout a session (identify, reloadFeatureFlags), so the late-gate retry
+ // must be one-shot per scene: closing the panel from a non-Max tab records no dismissal, which
+ // would otherwise leave the user exposed to a surprise re-open on the next flags response.
+ it('does not reopen the panel on a later feature flag response after the user closed it', async () => {
+ setFlags(allFlags)
+
+ await expectLogic(logic, () => {
+ logic.actions.sceneEntered('workflow')
+ }).toFinishAllListeners()
+ expect(sidePanelStateLogic.values.sidePanelOpen).toBe(true)
+
+ sidePanelStateLogic.actions.openSidePanel(SidePanelTab.Support)
+ await expectLogic(logic, () => {
+ sidePanelStateLogic.actions.closeSidePanel(SidePanelTab.Support)
+ }).toFinishAllListeners()
+ expect(sidePanelStateLogic.values.sidePanelOpen).toBe(false)
+
+ await expectLogic(logic, () => {
+ setFlags(allFlags)
+ }).toFinishAllListeners()
+
+ expect(sidePanelStateLogic.values.sidePanelOpen).toBe(false)
+ })
+
+ it('does not record a dismissal for scenes registered after the panel was closed', async () => {
+ setFlags(allFlags)
+
+ await expectLogic(logic, () => {
+ sidePanelStateLogic.actions.closeSidePanel()
+ }).toFinishAllListeners()
+
+ expect(logic.values.autoOpenDismissedScenes).toEqual({})
+
+ await expectLogic(logic, () => {
+ logic.actions.sceneEntered('workflow')
+ }).toFinishAllListeners()
+ expect(sidePanelStateLogic.values.sidePanelOpen).toBe(true)
+ })
+})
diff --git a/frontend/src/scenes/max/sceneAgentPanelLogic.ts b/frontend/src/scenes/max/sceneAgentPanelLogic.ts
new file mode 100644
index 000000000000..46789a516bea
--- /dev/null
+++ b/frontend/src/scenes/max/sceneAgentPanelLogic.ts
@@ -0,0 +1,176 @@
+import { MakeLogicType, actions, connect, kea, listeners, path, reducers, selectors } from 'kea'
+
+import { FEATURE_FLAGS } from 'lib/constants'
+import { FeatureFlagsSet, featureFlagLogic } from 'lib/logic/featureFlagLogic'
+
+import { sidePanelStateLogic } from '~/layout/navigation-3000/sidepanel/sidePanelStateLogic'
+import { SidePanelTab } from '~/types'
+
+import { PHAI_SCENE_AUTO_OPEN_DISMISSED_KEY } from './max-storage-keys'
+import { PhaiViewMode, maxGlobalLogic } from './maxGlobalLogic'
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface sceneAgentPanelLogicValues {
+ featureFlags: FeatureFlagsSet // featureFlagLogic
+ receivedFeatureFlags: boolean // featureFlagLogic
+ effectivePhaiView: PhaiViewMode // maxGlobalLogic
+ isMaxAvailable: boolean // maxGlobalLogic
+ modalMode: boolean // sidePanelStateLogic
+ selectedTab: SidePanelTab | null // sidePanelStateLogic
+ sidePanelAvailable: boolean // sidePanelStateLogic
+ sidePanelOpen: boolean // sidePanelStateLogic
+ activeSceneKeys: string[]
+ autoOpenDismissedScenes: Record<string, true>
+ sceneIntegrationEnabled: boolean
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface sceneAgentPanelLogicActions {
+ openSidePanel: (
+ tab: SidePanelTab,
+ options?: string | undefined
+ ) => {
+ options: string | undefined
+ tab: SidePanelTab
+ } // sidePanelStateLogic
+ markAutoOpenDismissed: (sceneKeys: string[]) => {
+ sceneKeys: string[]
+ }
+ sceneEntered: (sceneKey: string) => {
+ sceneKey: string
+ }
+ sceneLeft: (sceneKey: string) => {
+ sceneKey: string
+ }
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface sceneAgentPanelLogicMeta {
+ __keaTypeGenInternalSelectorTypes: {
+ sceneIntegrationEnabled: (
+ featureFlags: FeatureFlagsSet,
+ effectivePhaiView: PhaiViewMode,
+ isMaxAvailable: boolean
+ ) => boolean
+ }
+}
+
+export type sceneAgentPanelLogicType = MakeLogicType<
+ sceneAgentPanelLogicValues,
+ sceneAgentPanelLogicActions,
+ Record<string, any>,
+ sceneAgentPanelLogicMeta
+>
+
+/**
+ * Auto-opens the PostHog AI side panel for scenes that opt in (via `useSceneAgentPanel`), with a
+ * persisted per-scene opt-out: once the user closes the panel while such a scene is active, that
+ * scene stops auto-opening on this device. Only ever opens the new (sandbox) view - the legacy Max
+ * view has its own scene-context system and predates this behavior.
+ */
+export const sceneAgentPanelLogic = kea<sceneAgentPanelLogicType>([
+ path(['scenes', 'max', 'sceneAgentPanelLogic']),
+ connect(() => ({
+ values: [
+ featureFlagLogic,
+ ['featureFlags', 'receivedFeatureFlags'],
+ maxGlobalLogic,
+ ['effectivePhaiView', 'isMaxAvailable'],
+ sidePanelStateLogic,
+ ['sidePanelOpen', 'selectedTab', 'sidePanelAvailable', 'modalMode'],
+ ],
+ actions: [sidePanelStateLogic, ['openSidePanel']],
+ })),
+ actions({
+ sceneEntered: (sceneKey: string) => ({ sceneKey }),
+ sceneLeft: (sceneKey: string) => ({ sceneKey }),
+ markAutoOpenDismissed: (sceneKeys: string[]) => ({ sceneKeys }),
+ }),
+ reducers({
+ activeSceneKeys: [
+ [] as string[],
+ {
+ sceneEntered: (state, { sceneKey }) => (state.includes(sceneKey) ? state : [...state, sceneKey]),
+ sceneLeft: (state, { sceneKey }) => state.filter((key) => key !== sceneKey),
+ },
+ ],
+ autoOpenDismissedScenes: [
+ {} as Record<string, true>,
+ { persist: true, storageKey: PHAI_SCENE_AUTO_OPEN_DISMISSED_KEY },
+ {
+ markAutoOpenDismissed: (state, { sceneKeys }) => ({
+ ...state,
+ ...Object.fromEntries(sceneKeys.map((key) => [key, true as const])),
+ }),
+ },
+ ],
+ }),
+ selectors({
+ // The single gate for the whole scene integration: context attachment and headline overrides
+ // (applied by useSceneAgentPanel) as well as the auto-open below all hang off this, so no part
+ // of the feature reaches users the rollout flag hasn't. Only the new (sandbox) view qualifies,
+ // because only it consumes attached context.
+ sceneIntegrationEnabled: [
+ (s) => [s.featureFlags, s.effectivePhaiView, s.isMaxAvailable],
+ (featureFlags: FeatureFlagsSet, effectivePhaiView: PhaiViewMode, isMaxAvailable: boolean): boolean =>
+ Boolean(
+ featureFlags[FEATURE_FLAGS.PHAI_SCENE_AUTO_OPEN] && effectivePhaiView === 'new' && isMaxAvailable
+ ),
+ ],
+ }),
+ listeners(({ actions, values }) => {
+ // Scenes whose auto-open decision has been made with the async gates resolved (flags received,
+ // side panel mounted). Flags re-resolve throughout a session (identify, reloadFeatureFlags), so
+ // without this the retry listeners below would re-open a panel the user closed in any state that
+ // records no dismissal, e.g. closed while a non-Max tab was selected.
+ const decidedSceneKeys = new Set<string>()
+ // Shared by the open and dismissal paths: dismissal must be gated exactly like auto-open, or a
+ // Max close on this scene before the feature reaches the user permanently opts them out.
+ const autoOpenEligible = (): boolean =>
+ Boolean(
+ values.sceneIntegrationEnabled &&
+ values.sidePanelAvailable &&
+ // In modal mode (narrow viewports) the panel overlays the whole scene - never force it open.
+ !values.modalMode
+ )
+ const maybeAutoOpen = (sceneKeys: string[]): void => {
+ if (values.receivedFeatureFlags && values.sidePanelAvailable) {
+ sceneKeys.forEach((key) => decidedSceneKeys.add(key))
+ }
+ if (
+ !autoOpenEligible() ||
+ sceneKeys.every((key) => values.autoOpenDismissedScenes[key]) ||
+ // Already open: either on Max (nothing to do) or on a tab the user chose (don't clobber it).
+ values.sidePanelOpen
+ ) {
+ return
+ }
+ actions.openSidePanel(SidePanelTab.Max)
+ }
+ // The gates resolve asynchronously on a cold load (flags fetch, side panel mount), so a scene
+ // entered before they land would otherwise silently miss its auto-open until re-entry. One-shot
+ // per scene: only scenes not yet decided are retried.
+ const retryUndecidedScenes = (): void => {
+ const undecided = values.activeSceneKeys.filter((key) => !decidedSceneKeys.has(key))
+ if (undecided.length > 0) {
+ maybeAutoOpen(undecided)
+ }
+ }
+ return {
+ sceneEntered: ({ sceneKey }) => maybeAutoOpen([sceneKey]),
+ [featureFlagLogic.actionTypes.setFeatureFlags]: retryUndecidedScenes,
+ [sidePanelStateLogic.actionTypes.setSidePanelAvailable]: retryUndecidedScenes,
+ [sidePanelStateLogic.actionTypes.closeSidePanel]: ({ tab }: { tab?: SidePanelTab }) => {
+ // Any close of the Max tab while an opted-in scene is active counts as "stop auto-opening
+ // here" - regardless of whether this logic or the user opened the panel.
+ if (values.activeSceneKeys.length === 0 || !autoOpenEligible()) {
+ return
+ }
+ if ((tab && tab !== SidePanelTab.Max) || values.selectedTab !== SidePanelTab.Max) {
+ return
+ }
+ actions.markAutoOpenDismissed(values.activeSceneKeys)
+ },
+ }
+ }),
+])
diff --git a/frontend/src/scenes/max/useSceneAgentPanel.ts b/frontend/src/scenes/max/useSceneAgentPanel.ts
new file mode 100644
index 000000000000..c7c0be930f8d
--- /dev/null
+++ b/frontend/src/scenes/max/useSceneAgentPanel.ts
@@ -0,0 +1,50 @@
+import { useActions, useValues } from 'kea'
+import { useEffect } from 'react'
+
+import { useAttachedContext, useWelcomeOverride } from 'products/posthog_ai/frontend/api/logics'
+import { AttachedContextItem } from 'products/posthog_ai/frontend/api/types'
+
+import { sceneAgentPanelLogic } from './sceneAgentPanelLogic'
+
+export interface SceneAgentPanelOptions {
+ /** Stable key for this scene's auto-open dismissal memory, e.g. 'workflow'. */
+ sceneKey: string
+ /** Context attached while the scene is mounted — the entity ref, live state, skill and tool guidance. */
+ contextItems: AttachedContextItem[] | null
+ /** Contextual welcome headlines for the composer's empty state; defaults apply when omitted. */
+ headlines?: string[]
+ /** When false, nothing is attached or opened (e.g. while the entity is still loading). Defaults to true. */
+ active?: boolean
+ /** Set false to attach context without auto-opening the panel. Defaults to true. */
+ autoOpen?: boolean
+}
+
+/**
+ * Scene-level PostHog AI integration: attaches the given context items for the lifetime of the
+ * scene and auto-opens the AI side panel (subject to `sceneAgentPanelLogic`'s gates, including the
+ * user's persisted per-scene dismissal). The whole integration rides
+ * `sceneAgentPanelLogic.sceneIntegrationEnabled`, so nothing is attached or overridden for users
+ * the rollout flag hasn't reached. Call once from a scene component.
+ */
+export function useSceneAgentPanel({
+ sceneKey,
+ contextItems,
+ headlines,
+ active = true,
+ autoOpen = true,
+}: SceneAgentPanelOptions): void {
+ const { sceneIntegrationEnabled } = useValues(sceneAgentPanelLogic)
+ const { sceneEntered, sceneLeft } = useActions(sceneAgentPanelLogic)
+ useAttachedContext(contextItems, { active: active && sceneIntegrationEnabled })
+ useWelcomeOverride(headlines ?? null, { active: active && sceneIntegrationEnabled })
+
+ useEffect(() => {
+ // Deliberately not gated on sceneIntegrationEnabled: the logic decides eligibility itself,
+ // including the late-resolving flag case (scene entered before the flags response lands).
+ if (!active || !autoOpen) {
+ return
+ }
+ sceneEntered(sceneKey)
+ return () => sceneLeft(sceneKey)
+ }, [active, autoOpen, sceneKey, sceneEntered, sceneLeft])
+}
diff --git a/hogli.yaml b/hogli.yaml
index d8ef8fc7f421..ded8101527a4 100644
--- a/hogli.yaml
+++ b/hogli.yaml
@@ -546,6 +546,11 @@ build:
cmd: pnpm --filter=@posthog/mcp run generate-cli-agent-scopes
description: Generate the CLI `agent` login use-case scope list from the MCP
tool definitions (must run after build:openapi-mcp-tools)
+ build:openapi-scene-tool-context:
+ cmd: pnpm --filter=@posthog/mcp run generate-scene-tool-context
+ description: Generate per-product agent-context payloads (MCP tool summaries +
+ skill bodies) for scene-level PostHog AI integration (must run after
+ build:openapi-mcp-tools)
build:openapi-exec-docs:
cmd: pnpm --filter=@posthog/mcp run generate-exec-docs
description: Render the MCP exec tool's command reference into the markdown
@@ -560,6 +565,7 @@ build:
- build:openapi-mcp-tools
- build:openapi-mcp-scopes
- build:openapi-cli-agent-scopes
+ - build:openapi-scene-tool-context
- build:openapi-exec-docs
description: Generate OpenAPI schema and TypeScript types from the backend
build:grammar:
diff --git a/products/posthog_ai/frontend/api/logics.ts b/products/posthog_ai/frontend/api/logics.ts
index e896b03b8d29..fcfc5d4d1ac3 100644
--- a/products/posthog_ai/frontend/api/logics.ts
+++ b/products/posthog_ai/frontend/api/logics.ts
@@ -29,6 +29,11 @@ export { attachedContextLogic } from '../logics/attachedContextLogic'
export { useAttachedContext } from '../hooks/useAttachedContext'
export type { UseAttachedContextOptions } from '../hooks/useAttachedContext'
export { attachedContextItemKey } from '../types/contextTypes'
+// Contextual welcome headlines: a host registers headlines matching what the user is looking at,
+// and the composer's empty state picks from them instead of the generic defaults.
+export { welcomeOverrideLogic } from '../logics/welcomeOverrideLogic'
+export { useWelcomeOverride } from '../hooks/useWelcomeOverride'
+export type { UseWelcomeOverrideOptions } from '../hooks/useWelcomeOverride'
// The standing "act via tool calls" instruction the sidebar surfaces attach while the user watches a
// run — the prompt-side half of `useMcpToolApplyBack` (hidden from chips, deduped once per task).
export { AGENT_TOOL_APPLY_BACK_CONTEXT_ITEM } from '../utils/posthogContextBlock'
diff --git a/products/posthog_ai/frontend/components/composer/AttachedContextBar.tsx b/products/posthog_ai/frontend/components/composer/AttachedContextBar.tsx
index 7a1f0712306a..b3091c695849 100644
--- a/products/posthog_ai/frontend/components/composer/AttachedContextBar.tsx
+++ b/products/posthog_ai/frontend/components/composer/AttachedContextBar.tsx
@@ -94,7 +94,9 @@ export function AttachedContextBar(): JSX.Element {
<Tooltip key={key} title={label}>
<LemonTag
icon={iconForType(item.type)}
- onClose={() => (pickedKeys.has(key) ? removePickedItem(key) : dismissContext(key))}
+ onClose={() =>
+ pickedKeys.has(key) ? removePickedItem(key) : dismissContext(key, item.dismissGroup)
+ }
closable
closeOnClick
className="flex items-center text-secondary max-w-48"
diff --git a/products/posthog_ai/frontend/hooks/useWelcomeOverride.ts b/products/posthog_ai/frontend/hooks/useWelcomeOverride.ts
new file mode 100644
index 000000000000..66ceaf088d85
--- /dev/null
+++ b/products/posthog_ai/frontend/hooks/useWelcomeOverride.ts
@@ -0,0 +1,39 @@
+import { useActions } from 'kea'
+import { useEffect, useMemo, useRef } from 'react'
+
+import { uuid } from 'lib/utils/dom'
+
+import { welcomeOverrideLogic } from '../logics/welcomeOverrideLogic'
+
+export interface UseWelcomeOverrideOptions {
+ /** When false, the provider is deregistered (defaults apply). Defaults to true. */
+ active?: boolean
+}
+
+/**
+ * Registers contextual welcome headlines into the global `welcomeOverrideLogic` under a stable
+ * per-mount provider id, so the composer's empty state uses them instead of the generic defaults.
+ * Deregisters on unmount or when `active: false`.
+ */
+export function useWelcomeOverride(headlines: string[] | null, options?: UseWelcomeOverrideOptions): void {
+ const active = options?.active ?? true
+ const { registerHeadlines, deregisterHeadlines } = useActions(welcomeOverrideLogic)
+ const providerIdRef = useRef<string>(`welcome-${uuid()}`)
+ // Memo key so re-renders that produce an equal array don't churn the registry.
+ const headlinesKey = useMemo(() => JSON.stringify(headlines ?? []), [headlines])
+
+ useEffect(() => {
+ const providerId = providerIdRef.current
+ if (!active || !headlines || headlines.length === 0) {
+ deregisterHeadlines(providerId)
+ return
+ }
+ registerHeadlines(providerId, headlines)
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [active, headlinesKey, registerHeadlines, deregisterHeadlines])
+
+ useEffect(() => {
+ const providerId = providerIdRef.current
+ return () => deregisterHeadlines(providerId)
+ }, [deregisterHeadlines])
+}
diff --git a/products/posthog_ai/frontend/logics/attachedContextLogic.test.ts b/products/posthog_ai/frontend/logics/attachedContextLogic.test.ts
index b0e457dc78bd..823687bacc6b 100644
--- a/products/posthog_ai/frontend/logics/attachedContextLogic.test.ts
+++ b/products/posthog_ai/frontend/logics/attachedContextLogic.test.ts
@@ -2,6 +2,7 @@ import { expectLogic } from 'kea-test-utils'
import { initKeaTests } from '~/test/init'
+import type { AttachedContextItem } from '../types/contextTypes'
import { attachedContextLogic } from './attachedContextLogic'
describe('attachedContextLogic', () => {
@@ -85,4 +86,28 @@ describe('attachedContextLogic', () => {
logic.actions.undismissContext('insight:x')
}).toMatchValues({ contextItems: [item] })
})
+
+ // A chip's dismissal must extend to the hidden payload items registered alongside it, and must
+ // survive re-registrations whose value (and therefore dedupe key) changed, as live editor state
+ // does on every edit; key-based dismissal alone lets the payload resurrect on the next edit.
+ it('dismissing with a dismissGroup hides the whole group, including re-registrations with new values', async () => {
+ const groupItems = (stateValue: string): AttachedContextItem[] => [
+ { type: 'hog_flow', key: '1', label: 'Flow', dismissGroup: 'g' },
+ { type: 'hog_flow_editor_state', value: stateValue, hidden: true, dismissGroup: 'g' },
+ { type: 'insight', key: 'other' },
+ ]
+
+ await expectLogic(logic, () => {
+ logic.actions.registerContext('scene', groupItems('v1'))
+ logic.actions.dismissContext('hog_flow:1', 'g')
+ }).toMatchValues({ contextItems: [{ type: 'insight', key: 'other' }] })
+
+ await expectLogic(logic, () => {
+ logic.actions.registerContext('scene', groupItems('v2'))
+ }).toMatchValues({ contextItems: [{ type: 'insight', key: 'other' }] })
+
+ await expectLogic(logic, () => {
+ logic.actions.undismissContext('hog_flow:1', 'g')
+ }).toMatchValues({ contextItems: groupItems('v2') })
+ })
})
diff --git a/products/posthog_ai/frontend/logics/attachedContextLogic.ts b/products/posthog_ai/frontend/logics/attachedContextLogic.ts
index ba2524111eb9..08eb7b4af3d5 100644
--- a/products/posthog_ai/frontend/logics/attachedContextLogic.ts
+++ b/products/posthog_ai/frontend/logics/attachedContextLogic.ts
@@ -5,6 +5,7 @@ import { type AttachedContextItem, attachedContextItemKey } from '../types/conte
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface attachedContextLogicValues {
contextItems: AttachedContextItem[]
+ dismissedGroups: Record<string, true>
dismissedKeys: Record<string, true>
hasContext: boolean
providers: Record<string, AttachedContextItem[]>
@@ -17,7 +18,11 @@ export interface attachedContextLogicActions {
deregisterContext: (providerId: string) => {
providerId: string
}
- dismissContext: (key: string) => {
+ dismissContext: (
+ key: string,
+ dismissGroup?: string
+ ) => {
+ dismissGroup: string | undefined
key: string
}
markContextLinesSeen: (
@@ -41,7 +46,11 @@ export interface attachedContextLogicActions {
items: AttachedContextItem[]
providerId: string
}
- undismissContext: (key: string) => {
+ undismissContext: (
+ key: string,
+ dismissGroup?: string
+ ) => {
+ dismissGroup: string | undefined
key: string
}
}
@@ -51,7 +60,8 @@ export interface attachedContextLogicMeta {
__keaTypeGenInternalSelectorTypes: {
contextItems: (
providers: Record<string, AttachedContextItem[]>,
- dismissedKeys: Record<string, true>
+ dismissedKeys: Record<string, true>,
+ dismissedGroups: Record<string, true>
) => AttachedContextItem[]
hasContext: (contextItems: AttachedContextItem[]) => boolean
}
@@ -101,10 +111,12 @@ export const attachedContextLogic = kea<attachedContextLogicType>([
/**
* Hide one item (by `attachedContextItemKey`) regardless of which provider contributed it —
* the user closing a chip must stick even when the provider re-registers the same item
- * (e.g. the scene bridge upserting on every scene read).
+ * (e.g. the scene bridge upserting on every scene read). Passing the item's `dismissGroup`
+ * also hides every item sharing that group, including future re-registrations whose value
+ * (and therefore key) differs, which is how a chip detaches the hidden payload it stands for.
*/
- dismissContext: (key: string) => ({ key }),
- undismissContext: (key: string) => ({ key }),
+ dismissContext: (key: string, dismissGroup?: string) => ({ key, dismissGroup }),
+ undismissContext: (key: string, dismissGroup?: string) => ({ key, dismissGroup }),
}),
reducers({
@@ -171,16 +183,32 @@ export const attachedContextLogic = kea<attachedContextLogicType>([
},
},
],
+ dismissedGroups: [
+ {} as Record<string, true>,
+ {
+ dismissContext: (state, { dismissGroup }) =>
+ dismissGroup ? { ...state, [dismissGroup]: true as const } : state,
+ undismissContext: (state, { dismissGroup }) => {
+ if (!dismissGroup || !(dismissGroup in state)) {
+ return state
+ }
+ const { [dismissGroup]: _dropped, ...rest } = state
+ return rest
+ },
+ },
+ ],
}),
selectors({
// Flattened across providers, deduped by `${type}:${key ?? value}` (first writer wins).
- // Items with neither `key` nor `value` carry no payload and are dropped, as are dismissed keys.
+ // Items with neither `key` nor `value` carry no payload and are dropped, as are dismissed
+ // keys and members of dismissed groups.
contextItems: [
- (s) => [s.providers, s.dismissedKeys],
+ (s) => [s.providers, s.dismissedKeys, s.dismissedGroups],
(
providers: Record<string, AttachedContextItem[]>,
- dismissedKeys: Record<string, true>
+ dismissedKeys: Record<string, true>,
+ dismissedGroups: Record<string, true>
): AttachedContextItem[] => {
const seen = new Set<string>()
const out: AttachedContextItem[] = []
@@ -191,6 +219,9 @@ export const attachedContextLogic = kea<attachedContextLogicType>([
if (!hasKey && !hasValue) {
continue
}
+ if (item.dismissGroup && dismissedGroups[item.dismissGroup]) {
+ continue
+ }
const key = attachedContextItemKey(item)
if (seen.has(key) || dismissedKeys[key]) {
continue
diff --git a/products/posthog_ai/frontend/logics/contextPickerLogic.ts b/products/posthog_ai/frontend/logics/contextPickerLogic.ts
index 2a0732d22d43..c0d7888922c3 100644
--- a/products/posthog_ai/frontend/logics/contextPickerLogic.ts
+++ b/products/posthog_ai/frontend/logics/contextPickerLogic.ts
@@ -75,7 +75,11 @@ export interface contextPickerLogicActions {
items: AttachedContextItem[]
providerId: string
} // attachedContextLogic
- undismissContext: (key: string) => {
+ undismissContext: (
+ key: string,
+ dismissGroup?: string | undefined
+ ) => {
+ dismissGroup: string | undefined
key: string
} // attachedContextLogic
handleTaxonomicFilterChange: (
diff --git a/products/posthog_ai/frontend/logics/welcomeOverrideLogic.test.ts b/products/posthog_ai/frontend/logics/welcomeOverrideLogic.test.ts
new file mode 100644
index 000000000000..eeffefc728f7
--- /dev/null
+++ b/products/posthog_ai/frontend/logics/welcomeOverrideLogic.test.ts
@@ -0,0 +1,48 @@
+import { expectLogic } from 'kea-test-utils'
+
+import { useMocks } from '~/mocks/jest'
+import { initKeaTests } from '~/test/init'
+
+import { DEFAULT_HEADLINES } from '../components/welcome/welcomeDefaults'
+import { taskTrackerSceneLogic } from '../scenes/TaskTracker/taskTrackerSceneLogic'
+import { welcomeOverrideLogic } from './welcomeOverrideLogic'
+
+describe('welcomeOverrideLogic', () => {
+ let overrideLogic: ReturnType<typeof welcomeOverrideLogic.build>
+ let trackerLogic: ReturnType<typeof taskTrackerSceneLogic.build>
+
+ beforeEach(() => {
+ useMocks({
+ get: {
+ '/api/projects/:team/tasks/': { results: [], count: 0 },
+ '/api/projects/:team/tasks/repositories/': { repositories: [] },
+ '/api/environments/:team/integrations/': { results: [] },
+ },
+ })
+ initKeaTests()
+ overrideLogic = welcomeOverrideLogic()
+ overrideLogic.mount()
+ trackerLogic = taskTrackerSceneLogic({ panelId: 'max-side-panel' })
+ trackerLogic.mount()
+ })
+
+ afterEach(() => {
+ trackerLogic?.unmount()
+ overrideLogic?.unmount()
+ })
+
+ // A scene that registers contextual headlines (e.g. the workflow editor) must win over the generic
+ // defaults, and must stop winning once it deregisters (navigating away) — otherwise the /tasks
+ // composer keeps showing another scene's headline.
+ it('overrides the composer headline while registered and falls back on deregister', async () => {
+ await expectLogic(overrideLogic, () => {
+ overrideLogic.actions.registerHeadlines('scene', ['How can I help with this workflow?'])
+ }).toFinishAllListeners()
+ expect(trackerLogic.values.displayHeadline).toBe('How can I help with this workflow?')
+
+ await expectLogic(overrideLogic, () => {
+ overrideLogic.actions.deregisterHeadlines('scene')
+ }).toFinishAllListeners()
+ expect(DEFAULT_HEADLINES).toContain(trackerLogic.values.displayHeadline)
+ })
+})
diff --git a/products/posthog_ai/frontend/logics/welcomeOverrideLogic.ts b/products/posthog_ai/frontend/logics/welcomeOverrideLogic.ts
new file mode 100644
index 000000000000..649ad9549716
--- /dev/null
+++ b/products/posthog_ai/frontend/logics/welcomeOverrideLogic.ts
@@ -0,0 +1,76 @@
+import { MakeLogicType, actions, kea, path, reducers, selectors } from 'kea'
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface welcomeOverrideLogicValues {
+ overrideHeadlines: string[] | null
+ providers: Record<string, string[]>
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface welcomeOverrideLogicActions {
+ deregisterHeadlines: (providerId: string) => {
+ providerId: string
+ }
+ registerHeadlines: (
+ providerId: string,
+ headlines: string[]
+ ) => {
+ headlines: string[]
+ providerId: string
+ }
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface welcomeOverrideLogicMeta {
+ __keaTypeGenInternalSelectorTypes: {
+ overrideHeadlines: (providers: Record<string, string[]>) => string[] | null
+ }
+}
+
+export type welcomeOverrideLogicType = MakeLogicType<
+ welcomeOverrideLogicValues,
+ welcomeOverrideLogicActions,
+ Record<string, any>,
+ welcomeOverrideLogicMeta
+>
+
+/**
+ * Global registry of contextual welcome headlines. A host surface (e.g. a scene with the AI panel
+ * integration) registers headlines that fit what the user is looking at, and the composer's empty
+ * state picks from them instead of the generic defaults while the provider stays registered.
+ */
+export const welcomeOverrideLogic = kea<welcomeOverrideLogicType>([
+ path(['products', 'posthog_ai', 'frontend', 'logics', 'welcomeOverrideLogic']),
+
+ actions({
+ /** Idempotent upsert — re-register the same `providerId` to update its headlines. */
+ registerHeadlines: (providerId: string, headlines: string[]) => ({ providerId, headlines }),
+ deregisterHeadlines: (providerId: string) => ({ providerId }),
+ }),
+
+ reducers({
+ providers: [
+ {} as Record<string, string[]>,
+ {
+ registerHeadlines: (state, { providerId, headlines }) => ({ ...state, [providerId]: headlines }),
+ deregisterHeadlines: (state, { providerId }) => {
+ if (!(providerId in state)) {
+ return state
+ }
+ const { [providerId]: _dropped, ...rest } = state
+ return rest
+ },
+ },
+ ],
+ }),
+
+ selectors({
+ // First registered provider with headlines wins (object insertion order) — mirrors the
+ // first-writer-wins convention of `attachedContextLogic`.
+ overrideHeadlines: [
+ (s) => [s.providers],
+ (providers: Record<string, string[]>): string[] | null =>
+ Object.values(providers).find((headlines) => headlines.length > 0) ?? null,
+ ],
+ }),
+])
diff --git a/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskComposer.tsx b/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskComposer.tsx
index 2aaf0e35cfcc..f3be673725fb 100644
--- a/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskComposer.tsx
+++ b/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskComposer.tsx
@@ -25,7 +25,7 @@ import { RepositorySelector } from './RepositorySelector'
export function TaskComposer(): JSX.Element {
const { submitNewTask, setNewTaskData, setActiveSuggestionGroup, applySuggestion, clearConsentBlock } =
useActions(taskTrackerSceneLogic)
- const { newTaskData, isSubmittingTask, activeSuggestionGroup, headline, consentBlocked } =
+ const { newTaskData, isSubmittingTask, activeSuggestionGroup, displayHeadline, consentBlocked } =
useValues(taskTrackerSceneLogic)
// Buffer the description locally and debounce the write to kea so each keystroke is a cheap, isolated
@@ -45,7 +45,7 @@ export function TaskComposer(): JSX.Element {
return (
<div className="flex flex-col h-full min-h-0 items-center justify-center overflow-y-auto p-4">
<div className="w-full max-w-2xl flex flex-col items-center gap-4">
- <Welcome headline={headline} />
+ <Welcome headline={displayHeadline} />
<Suggestions.Root
activeGroup={activeSuggestionGroup}
diff --git a/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.ts b/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.ts
index 6b837165e84e..8bb9127a47fd 100644
--- a/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.ts
+++ b/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.ts
@@ -1,4 +1,4 @@
-import { MakeLogicType, actions, connect, events, kea, key, listeners, path, props, reducers } from 'kea'
+import { MakeLogicType, actions, connect, events, kea, key, listeners, path, props, reducers, selectors } from 'kea'
import { router, urlToAction } from 'kea-router'
import { lemonToast } from '@posthog/lemon-ui'
@@ -27,6 +27,7 @@ import { runnerPanelLogic } from '../../logics/runnerPanelLogic'
import type { ActiveCreation } from '../../logics/runnerPanelLogic'
import { tasksLogic } from '../../logics/tasksLogic'
import { toolStreamEventsLogic } from '../../logics/toolStreamEventsLogic'
+import { welcomeOverrideLogic } from '../../logics/welcomeOverrideLogic'
import type { AttachedContextItem } from '../../types/contextTypes'
import type { RepositoryConfig, Task } from '../../types/taskTypes'
import type { TaskListParams } from '../../types/taskTypes'
@@ -81,9 +82,11 @@ export interface taskTrackerSceneLogicValues {
repositories: string[] // tasksLogic
taskListParams: TaskListParams // tasksLogic
tasks: Task[] // tasksLogic
+ overrideHeadlines: string[] | null // welcomeOverrideLogic
activeSuggestionGroup: SuggestionGroup | null
consentBlocked: boolean
- headline: string
+ displayHeadline: string
+ headlineSeed: number
isSubmittingTask: boolean
newTaskData: TaskCreateForm
persistedRepositoryConfig: PersistedRepositoryConfig
@@ -258,8 +261,8 @@ export interface taskTrackerSceneLogicActions {
setActiveSuggestionGroup: (group: SuggestionGroup | null) => {
group: SuggestionGroup | null
}
- setHeadline: (headline: string) => {
- headline: string
+ setHeadlineSeed: (seed: number) => {
+ seed: number
}
setNewTaskData: (data: Partial<TaskCreateForm>) => {
data: Partial<TaskCreateForm>
@@ -284,6 +287,9 @@ export interface taskTrackerSceneLogicActions {
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface taskTrackerSceneLogicMeta {
key: string
+ __keaTypeGenInternalSelectorTypes: {
+ displayHeadline: (overrideHeadlines: string[] | null, headlineSeed: number) => string
+ }
}
export type taskTrackerSceneLogicType = MakeLogicType<
@@ -317,6 +323,8 @@ export const taskTrackerSceneLogic = kea<taskTrackerSceneLogicType>([
['currentProjectId'],
composerSeedLogic(props),
['seed'],
+ welcomeOverrideLogic,
+ ['overrideHeadlines'],
],
actions: [
runnerPanelLogic(props),
@@ -343,7 +351,7 @@ export const taskTrackerSceneLogic = kea<taskTrackerSceneLogicType>([
maybeAutoSelectIntegration: true,
setActiveSuggestionGroup: (group: SuggestionGroup | null) => ({ group }),
applySuggestion: (item: SuggestionItem) => ({ item }),
- setHeadline: (headline: string) => ({ headline }),
+ setHeadlineSeed: (seed: number) => ({ seed }),
setPersistedRepositoryConfig: (config: PersistedRepositoryConfig) => ({ config }),
openExistingTask: (task: Task) => ({ task }),
// Re-points the panel at a fresh run started from the composer on a reopened terminal task
@@ -398,14 +406,24 @@ export const taskTrackerSceneLogic = kea<taskTrackerSceneLogicType>([
resetNewTaskData: () => null,
},
],
- headline: [
- DEFAULT_HEADLINES[0],
+ headlineSeed: [
+ 0,
{
- setHeadline: (_, { headline }) => headline,
+ setHeadlineSeed: (_, { seed }) => seed,
},
],
}),
+ selectors({
+ // Contextual headlines registered by the active scene (welcomeOverrideLogic) win over the
+ // generic defaults; the seed keeps the pick stable across re-renders.
+ displayHeadline: [
+ (s) => [s.overrideHeadlines, s.headlineSeed],
+ (overrideHeadlines: string[] | null, headlineSeed: number): string =>
+ pickHeadline(overrideHeadlines ?? DEFAULT_HEADLINES, headlineSeed),
+ ],
+ }),
+
listeners(({ actions, values, cache, props }) => ({
// Release the manually-mounted optimistic stream once the create resolves (navigated to the real run)
// or fails (returned to the composer), so the throwaway draft instance never leaks.
@@ -617,8 +635,9 @@ export const taskTrackerSceneLogic = kea<taskTrackerSceneLogicType>([
afterMount: () => {
actions.loadTasks(values.taskListParams)
actions.loadRepositories()
- // Roll a headline once per mount (pickHeadline forces index 0 under Storybook for stable snapshots).
- actions.setHeadline(pickHeadline())
+ // Roll a headline seed once per mount (pickHeadline forces index 0 under Storybook for
+ // stable snapshots regardless of seed).
+ actions.setHeadlineSeed(Math.floor(Math.random() * 1000))
// integrationsLogic loads on its own mount (triggered by the connect above), so we don't call
// loadIntegrations ourselves. loadIntegrationsSuccess covers that first load; this call covers
// integrations already cached by an earlier mount.
diff --git a/products/posthog_ai/frontend/types/contextTypes.ts b/products/posthog_ai/frontend/types/contextTypes.ts
index 40549175e219..34dd8bfc11ed 100644
--- a/products/posthog_ai/frontend/types/contextTypes.ts
+++ b/products/posthog_ai/frontend/types/contextTypes.ts
@@ -19,6 +19,14 @@ export interface AttachedContextItem {
value?: string
/** Rendered into the context blocks as usual but never shown as a composer chip (so not dismissable either). */
hidden?: boolean
+ /**
+ * Items sharing a `dismissGroup` are dismissed together: closing any chip in the group also
+ * detaches the group's hidden items, so a chip never claims control it doesn't have. Dismissal
+ * is recorded against this stable name rather than the dedupe key, which makes it stick for
+ * hidden items whose value (and therefore key) changes on every re-registration, e.g. live
+ * editor state.
+ */
+ dismissGroup?: string
}
/** Stable dedupe key for an attached context item: `${type}:${key ?? value}`. */
diff --git a/products/workflows/frontend/Workflows/WorkflowScene.tsx b/products/workflows/frontend/Workflows/WorkflowScene.tsx
index fb7ee3b2e085..86052e9d09fa 100644
--- a/products/workflows/frontend/Workflows/WorkflowScene.tsx
+++ b/products/workflows/frontend/Workflows/WorkflowScene.tsx
@@ -1,6 +1,7 @@
import clsx from 'clsx'
import { BindLogic, useActions, useValues } from 'kea'
import { router } from 'kea-router'
+import { useMemo } from 'react'
import { IconInfo } from '@posthog/icons'
import { LemonSwitch, Spinner, SpinnerOverlay } from '@posthog/lemon-ui'
@@ -12,6 +13,8 @@ import { useDebouncedValue } from 'lib/hooks/useDebouncedValue'
import { LemonTab, LemonTabs } from 'lib/lemon-ui/LemonTabs'
import { Tooltip } from 'lib/lemon-ui/Tooltip'
import { useAttachedLogic } from 'lib/logic/scenes/useAttachedLogic'
+import { sceneAgentPanelLogic } from 'scenes/max/sceneAgentPanelLogic'
+import { useSceneAgentPanel } from 'scenes/max/useSceneAgentPanel'
import { SceneExport } from 'scenes/sceneTypes'
import { urls } from 'scenes/urls'
@@ -21,6 +24,7 @@ import { ActivityScope } from '~/types'
import { batchWorkflowJobsLogic } from './batchWorkflowJobsLogic'
import { Workflow } from './Workflow'
+import { WORKFLOW_AGENT_HEADLINES, buildWorkflowAgentContext } from './workflowAgentContext'
import { WorkflowAssets } from './WorkflowAssets'
import { WorkflowInvocations } from './WorkflowInvocations'
import { workflowLogic } from './workflowLogic'
@@ -52,7 +56,15 @@ export function WorkflowScene(props: WorkflowSceneLogicProps): JSX.Element {
const batchJobsLogic = batchWorkflowJobsLogic({ id: workflowSceneProps.id })
const logic = workflowLogic({ id: props.id, templateId, editTemplateId })
- const { workflowLoading, originalWorkflow, lastSavedAt, isAutoSavePending, autoSaveEnabled } = useValues(logic)
+ const {
+ workflow,
+ workflowLoading,
+ originalWorkflow,
+ lastSavedAt,
+ isAutoSavePending,
+ autoSaveEnabled,
+ hogFunctionTemplatesById,
+ } = useValues(logic)
const { setAutoSaveEnabled } = useActions(logic)
const showSaving = useDebouncedValue(isAutoSavePending || workflowLoading, 1000)
const isDraft = originalWorkflow?.status === 'draft'
@@ -61,6 +73,34 @@ export function WorkflowScene(props: WorkflowSceneLogicProps): JSX.Element {
useAttachedLogic(batchJobsLogic, sceneLogic)
useAttachedLogic(logic, sceneLogic)
+ // Debounced so per-keystroke edits don't re-serialize the whole graph into the agent context.
+ // The id is debounced with the workflow as one value so a navigation between workflows can never
+ // pair one workflow's ref with the other's editor state during the debounce window.
+ const debouncedAgentSource = useDebouncedValue(
+ useMemo(() => ({ workflow, id: workflowSceneProps.id ?? 'new' }), [workflow, workflowSceneProps.id]),
+ 500
+ )
+ const { sceneIntegrationEnabled } = useValues(sceneAgentPanelLogic)
+ // Serializing the whole graph is real work on large workflows, so skip building the context
+ // entirely for users the integration flag hasn't reached.
+ const agentContextItems = useMemo(
+ () =>
+ sceneIntegrationEnabled
+ ? buildWorkflowAgentContext(
+ debouncedAgentSource.workflow,
+ debouncedAgentSource.id,
+ hogFunctionTemplatesById
+ )
+ : null,
+ [sceneIntegrationEnabled, debouncedAgentSource, hogFunctionTemplatesById]
+ )
+ useSceneAgentPanel({
+ sceneKey: 'workflow',
+ contextItems: agentContextItems,
+ headlines: WORKFLOW_AGENT_HEADLINES,
+ active: !!originalWorkflow || workflowSceneProps.id === 'new',
+ })
+
if (!originalWorkflow && workflowLoading) {
return <SpinnerOverlay sceneLevel />
}
diff --git a/products/workflows/frontend/Workflows/workflowAgentContext.test.ts b/products/workflows/frontend/Workflows/workflowAgentContext.test.ts
new file mode 100644
index 000000000000..49b41de2db71
--- /dev/null
+++ b/products/workflows/frontend/Workflows/workflowAgentContext.test.ts
@@ -0,0 +1,198 @@
+import { HogFunctionTemplateType } from '~/types'
+
+import type { HogFlow } from './hogflows/types'
+import {
+ EDITOR_STATE_MAX_CHARS,
+ redactWorkflowSecretInputs,
+ serializeWorkflowEditorState,
+} from './workflowAgentContext'
+
+const templatesById = {
+ 'template-webhook-dest': {
+ id: 'template-webhook-dest',
+ inputs_schema: [
+ { key: 'api_key', type: 'string', secret: true },
+ { key: 'url', type: 'string' },
+ ],
+ } as unknown as HogFunctionTemplateType,
+ // Hidden built-in templates like template-email are returned on the authenticated mount, so the
+ // loaded map contains them in practice.
+ 'template-email': {
+ id: 'template-email',
+ inputs_schema: [{ key: 'email', type: 'email' }],
+ } as unknown as HogFunctionTemplateType,
+}
+
+function workflowWith(overrides: Partial<HogFlow>): HogFlow {
+ return {
+ id: 'flow-1',
+ name: 'Test flow',
+ actions: [],
+ edges: [],
+ ...overrides,
+ } as unknown as HogFlow
+}
+
+function emailActions(value: Record<string, unknown>): HogFlow['actions'] {
+ return [
+ {
+ id: 'e1',
+ type: 'function_email',
+ config: { template_id: 'template-email', inputs: { email: { value } } },
+ },
+ ] as unknown as HogFlow['actions']
+}
+
+describe('workflowAgentContext', () => {
+ describe('redactWorkflowSecretInputs', () => {
+ it('redacts a typed-but-unsaved schema-secret input on a function action, keeping non-secret values', () => {
+ const workflow = workflowWith({
+ actions: [
+ {
+ id: 'a1',
+ type: 'function',
+ config: {
+ template_id: 'template-webhook-dest',
+ inputs: {
+ api_key: { value: 'sk-live-1234567890', bytecode: ['_H', 'sk-live-1234567890'] },
+ url: { value: 'https://example.com/hook' },
+ },
+ },
+ },
+ ] as unknown as HogFlow['actions'],
+ })
+
+ const redacted = redactWorkflowSecretInputs(workflow, templatesById)
+ const inputs = (redacted.actions[0] as any).config.inputs
+
+ expect(inputs.api_key.value).toBe('[secret]')
+ expect(inputs.api_key.bytecode).toBeUndefined()
+ expect(inputs.url.value).toBe('https://example.com/hook')
+ expect(JSON.stringify(redacted)).not.toContain('sk-live-1234567890')
+ })
+
+ // Templates load asynchronously (and the fetch can fail), so a secret typed into a field whose
+ // template schema isn't available yet must not leak: without the schema every value is redacted.
+ it('redacts every input value when the template schema is unavailable (fail closed)', () => {
+ const workflow = workflowWith({
+ actions: [
+ {
+ id: 'a1',
+ type: 'function',
+ config: {
+ template_id: 'template-not-loaded',
+ inputs: {
+ token: { value: 'leaked-token', secret: true },
+ url: {
+ value: 'https://example.com/hook',
+ bytecode: ['_H', 'https://example.com/hook'],
+ },
+ },
+ },
+ },
+ ] as unknown as HogFlow['actions'],
+ })
+
+ const inputs = (redactWorkflowSecretInputs(workflow, {}).actions[0] as any).config.inputs
+ expect(inputs.token.value).toBe('[redacted]')
+ expect(inputs.url.value).toBe('[redacted]')
+ expect(inputs.url.bytecode).toBeUndefined()
+ })
+
+ it('redacts webhook trigger action inputs via the trigger template schema', () => {
+ const workflow = workflowWith({
+ actions: [
+ {
+ id: 't1',
+ type: 'trigger',
+ config: {
+ type: 'webhook',
+ template_id: 'template-webhook-dest',
+ inputs: { api_key: { value: 'sk-live-1234567890' } },
+ },
+ },
+ ] as unknown as HogFlow['actions'],
+ })
+
+ const inputs = (redactWorkflowSecretInputs(workflow, templatesById).actions[0] as any).config.inputs
+ expect(inputs.api_key.value).toBe('[secret]')
+ })
+
+ it('redacts mapping inputs via the mapping inline schema', () => {
+ const workflow = workflowWith({
+ actions: [
+ {
+ id: 'a1',
+ type: 'function',
+ config: {
+ template_id: 'template-unknown',
+ inputs: {},
+ mappings: [
+ {
+ name: 'm1',
+ inputs_schema: [{ key: 'password', type: 'string', secret: true }],
+ inputs: { password: { value: 'hunter2' } },
+ },
+ ],
+ },
+ },
+ ] as unknown as HogFlow['actions'],
+ })
+
+ const mapping = (redactWorkflowSecretInputs(workflow, templatesById).actions[0] as any).config.mappings[0]
+ expect(mapping.inputs.password.value).toBe('[secret]')
+ })
+
+ it('does not mutate the input workflow', () => {
+ const workflow = workflowWith({
+ actions: [
+ {
+ id: 'a1',
+ type: 'function',
+ config: {
+ template_id: 'template-webhook-dest',
+ inputs: { api_key: { value: 'sk-live-1234567890' } },
+ },
+ },
+ ] as unknown as HogFlow['actions'],
+ })
+
+ redactWorkflowSecretInputs(workflow, templatesById)
+ expect((workflow.actions[0] as any).config.inputs.api_key.value).toBe('sk-live-1234567890')
+ })
+ })
+
+ describe('serializeWorkflowEditorState', () => {
+ // The rendered html is re-derived server-side from the design on every save, so shipping it
+ // alongside the design would double (or worse) the payload attached to every message.
+ it('drops the rendered html from email steps with a design, keeping it on html-only steps', () => {
+ const withDesign = serializeWorkflowEditorState(
+ workflowWith({ actions: emailActions({ design: { rows: ['r1'] }, html: '<html>rendered</html>' }) }),
+ templatesById
+ )
+ expect(withDesign).not.toContain('rendered')
+ expect(withDesign).toContain('r1')
+ expect(withDesign).not.toContain('elided for size')
+
+ const htmlOnly = serializeWorkflowEditorState(
+ workflowWith({ actions: emailActions({ html: '<html>only body</html>' }) }),
+ templatesById
+ )
+ expect(htmlOnly).toContain('only body')
+ })
+
+ it('elides email designs once the serialized state exceeds the cap, keeping the JSON parseable', () => {
+ const serialized = serializeWorkflowEditorState(
+ workflowWith({
+ actions: emailActions({ design: { blocks: 'x'.repeat(EDITOR_STATE_MAX_CHARS) }, subject: 'Hi' }),
+ }),
+ templatesById
+ )
+
+ expect(serialized.length).toBeLessThan(EDITOR_STATE_MAX_CHARS)
+ const emailValue = JSON.parse(serialized).actions[0].config.inputs.email.value
+ expect(emailValue.design).toContain('elided for size')
+ expect(emailValue.subject).toBe('Hi')
+ })
+ })
+})
diff --git a/products/workflows/frontend/Workflows/workflowAgentContext.ts b/products/workflows/frontend/Workflows/workflowAgentContext.ts
new file mode 100644
index 000000000000..46d3fff45cf8
--- /dev/null
+++ b/products/workflows/frontend/Workflows/workflowAgentContext.ts
@@ -0,0 +1,218 @@
+import { redactSecretHogFunctionInputs } from 'scenes/hog-functions/hog-function-utils'
+
+import { CyclotronJobInputSchemaType, CyclotronJobInputType, HogFunctionTemplateType } from '~/types'
+
+import { AttachedContextItem } from 'products/posthog_ai/frontend/api/types'
+
+import { BUILDING_WORKFLOWS_SKILL, WORKFLOWS_MCP_TOOLS } from '../agentContext.generated'
+import { isEmailAction, isFunctionAction, isTriggerFunction } from './hogflows/steps/types'
+import type { HogFlow } from './hogflows/types'
+
+// Each visible chip and the hidden payload items it stands for share a dismiss group, so closing
+// the chip actually detaches the payload instead of only hiding the chip.
+const SKILL_DISMISS_GROUP = 'workflow-scene-skill'
+const EDITOR_STATE_DISMISS_GROUP = 'workflow-scene-state'
+
+// All static strings below are build-time constants from our own repo (skill markdown + tool
+// descriptions), which is what makes them safe to attach as trusted `instructions` items.
+const PREAMBLE_CONTEXT_ITEM: AttachedContextItem = {
+ type: 'instructions',
+ hidden: true,
+ dismissGroup: SKILL_DISMISS_GROUP,
+ value:
+ 'The user has the PostHog workflow editor open. The full building-workflows skill and the complete ' +
+ 'workflows MCP tool catalog are included in this context - you already have everything needed to act. ' +
+ 'Do not spend turns discovering tools or reading skill files: call the listed tools directly, and use ' +
+ 'the exec `info <tool>` command only when you need a full input schema.',
+}
+
+const SKILL_CONTENT_CONTEXT_ITEM: AttachedContextItem = {
+ type: 'instructions',
+ hidden: true,
+ dismissGroup: SKILL_DISMISS_GROUP,
+ value:
+ `Skill ${BUILDING_WORKFLOWS_SKILL.name} (embedded, including its graph-schema reference): ` +
+ BUILDING_WORKFLOWS_SKILL.content,
+}
+
+const EDITOR_STATE_CONTEXT_ITEM: AttachedContextItem = {
+ type: 'instructions',
+ hidden: true,
+ dismissGroup: EDITOR_STATE_DISMISS_GROUP,
+ value:
+ 'The hog_flow_editor_state item is the current, possibly unsaved editor state of the workflow the user ' +
+ 'has open - prefer it over a fetched definition when reading. Use workflows-get only when you need the ' +
+ 'persisted state. Oversized email designs may be elided from this state; read them with workflows-get, ' +
+ 'or workflows-get-email-template for library templates.',
+}
+
+const TOOL_CONTEXT_ITEMS: AttachedContextItem[] = WORKFLOWS_MCP_TOOLS.map((tool) => ({
+ type: 'instructions',
+ hidden: true,
+ dismissGroup: SKILL_DISMISS_GROUP,
+ value: `MCP tool ${tool.name}: ${tool.description}`,
+}))
+
+const SKILL_CHIP_CONTEXT_ITEM: AttachedContextItem = {
+ type: 'skill',
+ key: BUILDING_WORKFLOWS_SKILL.name,
+ label: 'Building workflows skill',
+ dismissGroup: SKILL_DISMISS_GROUP,
+}
+
+export const WORKFLOW_AGENT_HEADLINES: string[] = [
+ 'How can I help with this workflow?',
+ 'What should this workflow do?',
+]
+
+function redactInputsRecord(
+ inputs: Record<string, CyclotronJobInputType>,
+ inputsSchema: CyclotronJobInputSchemaType[] | undefined
+): Record<string, CyclotronJobInputType> {
+ if (!inputsSchema) {
+ // Without a schema (templates still loading, fetch failed, or the template was deleted) there
+ // is no way to tell which inputs are secret, so fail closed and redact every value. The agent
+ // can still read the persisted state with workflows-get, where secrets are masked server-side.
+ return Object.fromEntries(
+ Object.entries(inputs).map(([key, entry]) => [
+ key,
+ entry ? { ...entry, value: '[redacted]', bytecode: undefined } : entry,
+ ])
+ )
+ }
+ const redacted = redactSecretHogFunctionInputs(inputs, inputsSchema)
+ // Compiled bytecode of a redacted entry can embed the literal value, so it must not survive either.
+ return Object.fromEntries(
+ Object.entries(redacted).map(([key, entry]) =>
+ entry?.value === '[secret]' && inputs[key]?.value !== '[secret]'
+ ? [key, { ...entry, bytecode: undefined }]
+ : [key, entry]
+ )
+ )
+}
+
+/**
+ * Strip secret input values from a workflow before it is serialized into agent context. Saved
+ * secrets never reach the frontend, but a secret typed into the editor and not yet saved sits in
+ * cleartext in the live form state - and function steps carry only a `template_id`, so the secret
+ * fields are only identifiable through the loaded template schemas.
+ */
+export function redactWorkflowSecretInputs(
+ workflow: HogFlow,
+ hogFunctionTemplatesById: Record<string, HogFunctionTemplateType>
+): HogFlow {
+ const clone: HogFlow = structuredClone(workflow)
+ for (const action of clone.actions ?? []) {
+ if (!isFunctionAction(action) && !isTriggerFunction(action)) {
+ continue
+ }
+ const config = action.config as {
+ template_id?: string
+ inputs?: Record<string, CyclotronJobInputType> | null
+ mappings?: {
+ inputs?: Record<string, CyclotronJobInputType> | null
+ inputs_schema?: CyclotronJobInputSchemaType[]
+ }[]
+ }
+ const template = config.template_id ? hogFunctionTemplatesById[config.template_id] : undefined
+ if (config.inputs) {
+ config.inputs = redactInputsRecord(config.inputs, template?.inputs_schema ?? undefined)
+ }
+ for (const mapping of config.mappings ?? []) {
+ if (mapping.inputs) {
+ mapping.inputs = redactInputsRecord(mapping.inputs, mapping.inputs_schema)
+ }
+ }
+ }
+ const trigger = clone.trigger as
+ | { template_id?: string; inputs?: Record<string, CyclotronJobInputType> | null }
+ | undefined
+ if (trigger?.inputs) {
+ const template = trigger.template_id ? hogFunctionTemplatesById[trigger.template_id] : undefined
+ trigger.inputs = redactInputsRecord(trigger.inputs, template?.inputs_schema ?? undefined)
+ }
+ return clone
+}
+
+function emailValueOf(action: HogFlow['actions'][number]): Record<string, unknown> | null {
+ if (!isEmailAction(action)) {
+ return null
+ }
+ const value = (action.config as { inputs?: Record<string, CyclotronJobInputType> | null })?.inputs?.email?.value
+ return value && typeof value === 'object' ? (value as Record<string, unknown>) : null
+}
+
+/** Serialized editor state beyond this budget gets its email designs elided (see `serializeWorkflowEditorState`). */
+export const EDITOR_STATE_MAX_CHARS = 64_000
+
+const DESIGN_ELIDED_MARKER =
+ '[design elided for size: read it with workflows-get, or workflows-get-email-template for library templates]'
+
+/**
+ * Serialize the live workflow for agent context, bounding the payload that rides along with every
+ * message: secrets are redacted (failing closed while template schemas are unavailable), the
+ * rendered email html is dropped from steps that carry a design (the server re-renders html from
+ * the design on every save, so it is derived weight), and if the result still exceeds
+ * `EDITOR_STATE_MAX_CHARS` the email designs themselves are swapped for a fetch hint. Elision keeps
+ * the JSON parseable, which blind truncation would not.
+ */
+export function serializeWorkflowEditorState(
+ workflow: HogFlow,
+ hogFunctionTemplatesById: Record<string, HogFunctionTemplateType>
+): string {
+ const prepared = redactWorkflowSecretInputs(workflow, hogFunctionTemplatesById)
+ for (const action of prepared.actions ?? []) {
+ const email = emailValueOf(action)
+ // Steps without a design keep their html, because it is the only body they have.
+ if (email?.design && email.html) {
+ delete email.html
+ }
+ }
+ const serialized = JSON.stringify(prepared)
+ if (serialized.length <= EDITOR_STATE_MAX_CHARS) {
+ return serialized
+ }
+ for (const action of prepared.actions ?? []) {
+ const email = emailValueOf(action)
+ if (email?.design) {
+ email.design = DESIGN_ELIDED_MARKER
+ }
+ }
+ return JSON.stringify(prepared)
+}
+
+/**
+ * The default agent context for the workflow editor scene: the embedded building-workflows skill,
+ * the workflows MCP tool catalog, and the current workflow (a visible ref for saved workflows plus
+ * the live editor state so unsaved edits are visible to the agent).
+ */
+export function buildWorkflowAgentContext(
+ workflow: HogFlow | null,
+ id: string,
+ hogFunctionTemplatesById: Record<string, HogFunctionTemplateType>
+): AttachedContextItem[] {
+ const items: AttachedContextItem[] = [
+ PREAMBLE_CONTEXT_ITEM,
+ SKILL_CHIP_CONTEXT_ITEM,
+ SKILL_CONTENT_CONTEXT_ITEM,
+ ...TOOL_CONTEXT_ITEMS,
+ EDITOR_STATE_CONTEXT_ITEM,
+ ]
+ if (id !== 'new') {
+ items.push({
+ type: 'hog_flow',
+ key: id,
+ label: workflow?.name || 'Current workflow',
+ dismissGroup: EDITOR_STATE_DISMISS_GROUP,
+ })
+ }
+ if (workflow) {
+ items.push({
+ type: 'hog_flow_editor_state',
+ hidden: true,
+ dismissGroup: EDITOR_STATE_DISMISS_GROUP,
+ value: serializeWorkflowEditorState(workflow, hogFunctionTemplatesById),
+ })
+ }
+ return items
+}
diff --git a/products/workflows/frontend/agentContext.generated.ts b/products/workflows/frontend/agentContext.generated.ts
new file mode 100644
index 000000000000..6be726c6986e
--- /dev/null
+++ b/products/workflows/frontend/agentContext.generated.ts
@@ -0,0 +1,181 @@
+// AUTO-GENERATED by services/mcp/scripts/build-scene-tool-context.ts.
+// Regenerate with `hogli build:openapi`. Do not edit.
+//
+// Static agent-context payloads for scene-level PostHog AI integration: the enabled
+// MCP tool catalog (names + live descriptions) and embedded skill bodies, attached
+// as context by `useSceneAgentPanel` callers so the agent starts with everything it
+// needs instead of discovering tools and reading skills at run time.
+
+export interface McpToolSummary {
+ name: string
+ description: string
+}
+
+export interface EmbeddedSkill {
+ name: string
+ description: string
+ content: string
+}
+
+export const WORKFLOWS_MCP_TOOLS: McpToolSummary[] = [
+ {
+ name: 'workflows-create',
+ description:
+ "Create a workflow. It is created as a draft and does NOT run until enabled: test it with workflows-test-run first, then enable (workflows-enable) only with the user's explicit approval — from then on it runs on real people, and further content edits stage as a draft you must publish (workflows-publish) to take effect. Provide an actions array with exactly one type='trigger' (config.type: event|webhook|manual|batch|tracking_pixel) plus action nodes (function/function_email/function_sms/function_push, delay, conditional_branch, wait_until_condition, ...) connected by edges. A webhook or manual trigger also needs config.template_id set to the literal 'template-source-webhook', and a tracking_pixel trigger needs 'template-source-webhook-pixel'; without it the create is rejected with 'Template not found' against the trigger node. Read the building-workflows skill for node shapes before composing: a node that mismatches the per-type schema saves but breaks the visual editor. Two traps that save but break: (1) a conditional_branch condition needs a 'filters' wrapper — {filters:{properties:[...]}}, not {properties:[...]} on the condition; omitting it passes save but the editor flags it and the branch won't evaluate your condition. (2) Never hand-author bytecode anywhere; send properties/hash and the server compiles it. A 'batch' trigger broadcasts to an audience (config.filters.properties: person-property conditions and/or cohort references), one run per matching person, and does NOT fire on enable: dispatch with workflows-run-batch or attach a schedule with workflows-schedule-create. Behavioral targeting ('did event X at least N times over the last M days') is unsupported; reject it and explain why.",
+ },
+ {
+ name: 'workflows-discard-draft',
+ description:
+ "Throw away a workflow's staged draft without touching the live config. Idempotent — discarding when nothing is staged is a no-op. Returns the workflow.",
+ },
+ {
+ name: 'workflows-get',
+ description:
+ "Get a specific workflow by ID, where id is the workflow's UUID. When you have a workflow's name instead, resolve it first with workflows-list (search=<name>) and use the id from that result. Returns the full workflow definition including trigger, edges, actions, exit condition, variables, and any recurring 'schedules' (read-only here). For a batch workflow, check status=='active' plus an active entry in 'schedules' to confirm it will actually fire. On an active workflow, 'draft' holds staged content changes awaiting workflows-publish (null when nothing is staged) — the live config in actions/edges is what's running.",
+ },
+ {
+ name: 'workflows-get-invocation',
+ description:
+ 'Get a single workflow invocation by invocation_id, including invocation_globals — the raw triggering payload (event/person/groups) that the run executed against. Use after workflows-list-invocations to inspect exactly what input produced a failure.',
+ },
+ {
+ name: 'workflows-get-revision',
+ description:
+ 'Get one revision of a workflow by version number, including its full content snapshot (actions, edges, trigger, variables). Use to inspect what was live at that version before restoring it with workflows-restore-revision.',
+ },
+ {
+ name: 'workflows-global-stats',
+ description:
+ "At-a-glance health across ALL workflows in one call: per-workflow succeeded/failed counts over a window (after/before, default last 7 days), sorted most-failing first. Start here when debugging — find which workflows are failing, then drill into those with workflows-list-invocations (who it failed for) → workflows-get-invocation (the triggering payload) → workflows-logs (the failing step). Avoids scanning every workflow one at a time. For a single workflow's time-series, use workflows-stats.",
+ },
+ {
+ name: 'workflows-list',
+ description:
+ "List all workflows in the project. Returns workflows with their name, description, status (draft/active/archived), version, trigger configuration, and timestamps. Pass search=<name> to find a workflow by name and read its id. Most workflows-* tools take that value as 'id'; workflows-blast-radius, workflows-run-batch and workflows-schedule-create take it as 'workflow_id'.",
+ },
+ {
+ name: 'workflows-list-batch-jobs',
+ description:
+ 'List past batch runs for a workflow (both one-off broadcasts and schedule-triggered runs). Each entry shows the audience filters and variable overrides the run used, plus when it was created. The status field is not tracked — use workflows-logs / workflows-stats for the outcome of a run.',
+ },
+ {
+ name: 'workflows-list-invocations',
+ description:
+ "List a workflow's individual invocations (one execution per person/event), each collapsed to its final outcome — status, error_kind/error_message, distinct_id, person_id, timings. This is the per-recipient failure view: filter status=failed to see who it failed for and why. Filter by distinct_id and time range. Distinct from workflows-list-batch-jobs (the dispatch ledger, which has no per-person outcome) — drill from a failed invocation into workflows-logs for the step-by-step trace.",
+ },
+ {
+ name: 'workflows-list-revisions',
+ description:
+ "List a workflow's revision history, newest first. Every live-content change (publish, direct edit) appends a version; each entry shows version, when, and by whom. Fetch a version's content with workflows-get-revision; roll back with workflows-restore-revision.",
+ },
+ {
+ name: 'workflows-logs',
+ description:
+ 'Retrieve execution logs for a specific workflow by ID. Returns log entries with timestamp, level (DEBUG, LOG, INFO, WARN, ERROR), and message. Use to debug why a workflow is failing or not producing expected results. Supports filtering by log level, text search, time range (after/before), and pagination via limit.',
+ },
+ {
+ name: 'workflows-patch-action-email',
+ description:
+ "Surgically edit the email inside one function_email step - the fastest path for copy tweaks and design changes on a workflow email. Use operations (the same design ops as workflows-patch-email-template, addressing blocks by id from the step's config.inputs.email.value.design) to edit the design, and email_patch to change subject, preheader, text, or recipients. After design ops the HTML is re-rendered server-side, so the sent email always matches the design. Edits apply atomically: an invalid batch changes nothing. On an active workflow, edits stage a draft (composing with any staged graph edits) and nothing reaches real people until workflows-publish. The full updated workflow is returned. Prefer this over workflows-patch-graph update_action for email content - it's smaller to send and keeps design and HTML in sync. For library templates use workflows-patch-email-template instead.",
+ },
+ {
+ name: 'workflows-patch-graph',
+ description:
+ "Surgically edit a workflow's graph by sending a small, ordered list of operations instead of resending every action and edge. Prefer this over workflows-update for any graph change — to tweak one node's config use update_action with a deep-merge patch (e.g. change just an email subject), and use add_action / remove_action / add_edge / remove_edge / replace_action_edges for structural changes. Reference nodes and edges by id. Operations apply atomically: the graph is read, the ops applied in order, the result fully validated (dangling edges, branch indexes, single trigger), and saved only if valid — otherwise nothing changes. On an active workflow, patches stage a draft instead of changing what's running: the first patch copies the live graph into the draft, later patches compose onto it, and nothing reaches real people until workflows-publish. The full updated workflow is returned, so you don't need to re-fetch before the next edit. When adding or editing a conditional_branch, each condition needs a 'filters' wrapper: {filters:{properties:[...]}}, not {properties:[...]} on the condition. Re-test the changed path with workflows-test-run after patching.",
+ },
+ {
+ name: 'workflows-publish',
+ description:
+ "Apply a workflow's staged draft to its live config. Two-step: call without confirm first — it returns in_flight_runs, a confirm_token, and an impact summary (per deleted step: about how many people are parked there and whether they move to a surviving step or exit; variables that may render empty for runs that never executed their new producer; schedules overriding removed variables), changing nothing. Echo the impact to the user and get their go-ahead, then call again with confirm=true and that confirm_token. A 409 means the draft changed since the preview and a 400 means the token expired — preview again and re-confirm either way. Publish revalidates the draft fully and recompiles it, so an invalid draft is rejected with the reason and the live config stays untouched. Test the draft first with workflows-test-run (use_draft=true). Shortened delays apply to parked runs via a spread sweep: runs already waking soon keep their original time, and wakes moved earlier by the sweep trickle in from a few minutes after publish rather than all at once - so runs still parked shortly after publishing are normal, not a sign of a failed publish.",
+ },
+ {
+ name: 'workflows-restore-revision',
+ description:
+ "Roll a workflow back (or forward) by copying a revision's content into its staged draft — the live config is untouched until you publish. Then run the normal cycle: test with workflows-test-run (use_draft=true), preview with workflows-publish, confirm. The preview shows exactly what the rollback does to people in-flight. A 409 means a draft is already open — publish or discard it, or pass overwrite=true to replace it. Note what a rollback can't undo: runs that already moved on while the newer version was live keep their positions.",
+ },
+ {
+ name: 'workflows-stats',
+ description:
+ "Execution stats for a single workflow by ID: time-series success/failure counts over a configurable interval (hour, day, or week). Use to inspect one workflow's health — failure spikes and reliability trends. For an at-a-glance view across ALL workflows, call workflows-global-stats first, then drill in here. Supports breakdown by metric kind (success/failure) or name, and time range filtering. For email engagement, read email_opened and email_link_clicked against (email_sent - email_untracked): email_untracked counts sends with open/click tracking off, which can never register an open or a click.",
+ },
+ {
+ name: 'workflows-test-run',
+ description:
+ "Test-invoke a workflow one node at a time; it does NOT traverse the full graph in one call. The result includes nextActionId. To verify a path end to end, chain calls: start at the trigger (omit current_action_id), then pass the returned nextActionId as current_action_id on the next call, and repeat. To test a specific branch, set current_action_id to that node. Skip delay nodes by jumping to the action after them, since delays are not simulated. Pass test data via globals (typically {event, person, groups}). Async actions (HTTP/email/SMS/push) are mocked by default; set mock_async_functions=false to fire real side effects. Returns the step's execution trace. Set use_draft=true to test a workflow's staged draft instead of its live config — always do this before workflows-publish. use_draft requires a staged draft to exist (workflows-get shows it in 'draft'); on a workflow with nothing staged, omit it.",
+ },
+ {
+ name: 'workflows-update',
+ description:
+ "Updates workflow fields a graph patch can't express: name, description, exit_condition, conversion, trigger_masking, variables. Graph content (actions/edges) is rejected here - a partial list would silently drop every step it omits - so all graph edits go through workflows-patch-graph. On an active workflow, content fields stage a draft (published with workflows-publish) while name/description apply immediately. Status changes go through workflows-enable / workflows-archive.",
+ },
+ {
+ name: 'workflows-update-schedule',
+ description:
+ "Update a recurring schedule's RRULE, start time, timezone, or variable overrides. Changing the cadence reschedules the next run. Each firing re-broadcasts to the workflow's current trigger audience.",
+ },
+ {
+ name: 'workflows-enable',
+ description:
+ "Enable / activate a draft workflow and start processing events. From then on it runs on real people: test it first with workflows-test-run and get the user's explicit approval before invoking - don't enable on your own initiative. Once live, content edits stage as a draft you publish with workflows-publish.",
+ },
+ {
+ name: 'workflows-archive',
+ description: 'Archive a draft or disabled workflow.',
+ },
+ {
+ name: 'workflows-blast-radius',
+ description:
+ "Count how many users a batch workflow's audience matches (person/cohort, not event behavior). Always run this BEFORE run-batch / schedule-create. Then STOP and get the user's explicit confirmation: tell them the exact count and that running will send real messages to that many people. Do not proceed to run-batch / schedule-create until they say yes. The response's confirm_token signs the sized audience - pass it to workflows-run-batch along with the acknowledged count; it expires in 15 minutes and goes stale if the audience filters change.",
+ },
+ {
+ name: 'workflows-run-batch',
+ description:
+ 'Broadcast a batch workflow to its matching users NOW — sends real messages/webhooks, not a test. Workflow must be enabled. STOP before calling: show the user the audience size from workflows-blast-radius and get their explicit confirmation in a separate turn — never size and fire in one step. Requires acknowledged_affected_count AND the confirm_token from that same workflows-blast-radius preview; the API rejects dispatch without the token, on audience drift, over the cap, or after 15 minutes.',
+ },
+ {
+ name: 'workflows-schedule-create',
+ description:
+ "Attach a recurring RRULE schedule to a batch workflow. The workflow must already be active (enable it first). Each run broadcasts real messages to the trigger audience — STOP and get the user's explicit confirmation first, then pass acknowledged_affected_count from workflows-blast-radius.",
+ },
+]
+
+export const EMAIL_TEMPLATE_MCP_TOOLS: McpToolSummary[] = [
+ {
+ name: 'workflows-create-email-template',
+ description:
+ "Save an email template to the workflows library. Provide name and content.email with subject, a plain-text fallback, and design (design JSON for PostHog's visual email editor — schema in the designing-email-templates skill); the sent email is compiled from the design JSON. Liquid personalization works throughout — Liquid tags, apostrophes, and emoji are ordinary JSON characters, so pass the design inline exactly as authored. Then call workflows-show-email-template and share the _posthogUrl link with the user.",
+ },
+ {
+ name: 'workflows-get-email-template',
+ description:
+ 'Get an email template by ID, including content.email (subject, text, design). Use this to fetch before updating — content is replaced as a whole and humans may have edited the design in the visual editor since you last saw it, so build your update payload from this response. To display a template to the user, use workflows-show-email-template instead.',
+ },
+ {
+ name: 'workflows-list-email-templates',
+ description:
+ "List email templates in the workflows library — metadata only; fetch a template's content with workflows-get-email-template. Templates are referenced from a workflow's function_email action.",
+ },
+ {
+ name: 'workflows-patch-email-template',
+ description:
+ "Surgically edit an email template's design by sending a small, ordered list of operations instead of resending the whole design JSON. Prefer this over workflows-update-email-template for any change to an existing design. Reference blocks by their id (call workflows-get-email-template first to read the current design and its ids). For the common case — tweak one block — use update_content with a deep-merge patch (e.g. {op: update_content, id: '<block-id>', patch: {values: {text: '<p>New copy</p>'}}}); a null leaf deletes that key. Use add_content / remove_content / move_content / add_row / remove_row for structural changes; ids and Unlayer numbering for added blocks are assigned for you. Operations apply atomically — the design is read, the ops applied in order, the result validated and re-rendered to HTML, and saved only if valid, otherwise nothing changes. After patching, call workflows-show-email-template so the user sees the result.",
+ },
+ {
+ name: 'workflows-show-email-template',
+ description:
+ 'Render an email template as an inline preview for the user. Call after creating or updating a template, and whenever the user asks to see one. The response carries the final rendered html — read it before describing the result. For fetching a template to edit it, use workflows-get-email-template.',
+ },
+ {
+ name: 'workflows-update-email-template',
+ description:
+ "Replace an email template's content as a whole. For small edits to an existing design (change a heading, a button color, one paragraph), prefer workflows-patch-email-template — it sends just the changed fields instead of the entire design JSON. Use this tool to set content from scratch or replace it wholesale: call workflows-get-email-template first (the design may carry fresh human edits from the visual editor) and send back the complete content.email with your edited design. The server re-renders the sent email from the design on save. After updating, call workflows-show-email-template so the user sees the result, and share the returned _posthogUrl edit link.",
+ },
+]
+
+export const BUILDING_WORKFLOWS_SKILL: EmbeddedSkill = {
+ name: 'building-workflows',
+ description:
+ 'Build, edit, test, enable, and monitor PostHog workflows over MCP. Author the action/edge graph so it runs and opens cleanly in the visual editor, then change drafts surgically with patch operations. Use when asked to build, set up, automate, change, fix, or debug a workflow, campaign, broadcast, drip sequence, or event-triggered automation in the workflows product.',
+ content:
+ '# Building workflows\n\nA PostHog **workflow** is a directed graph: a list of **action nodes** (`actions`) wired by **edges** (`edges`), with exactly one `trigger` node that starts every run. You author that graph as JSON and ship it over MCP. Always call it a "workflow" to the user. "Hog flow" is the internal code name (`HogFlow`), not a user-facing term.\n\nThe single biggest failure mode is **getting the graph JSON structurally wrong**. The backend stores `actions`/`config` as loose JSON, but the visual editor parses every node against a strict schema, so a malformed node saves but then **breaks the editor view** for the whole workflow. Before composing or editing any graph, read [references/graph-schema.md](references/graph-schema.md). It is the contract; do not improvise node shapes from these examples alone.\n\n## The lifecycle\n\nWork the workflow through these stages. Don\'t jump straight to enabling it.\n\n1. **Compose the graph.** Build `actions` + `edges` per [references/graph-schema.md](references/graph-schema.md). For any `function` node, don\'t guess the template: list the live catalog with `cdp-function-templates-list` and read its required inputs with `cdp-function-templates-retrieve`.\n2. **Create as a draft.** `workflows-create`. Every workflow is created `draft`; it does not execute yet.\n3. **Test-run it.** `workflows-test-run` runs **one step at a time**. Start at the first step (omit `current_action_id`, or point it at the trigger) with sample `globals` (`{event, person, groups}`); the result includes the next step\'s id (`nextActionId`). Feed that back as `current_action_id` and run again, walking step by step to the end. Skip `delay` nodes by jumping to the action after them (delays aren\'t simulated). Async side effects (HTTP/email/SMS/push) are mocked unless you set `mock_async_functions=false`. Read each step\'s trace to confirm the path taken.\n4. **Read logs while iterating.** `workflows-logs` shows the per-step execution trace (levels DEBUG to ERROR). This is how you see _why_ a step skipped, branched, or errored.\n5. **Edit, then re-test.** Patch the graph with `workflows-patch-graph` (see [Editing a draft](#editing-a-draft)). **Every edit invalidates your earlier test** — re-run the affected path before moving on. On a draft workflow, edits apply directly; on an active one they stage a draft (see [Changing a live workflow](#changing-a-live-workflow)).\n6. **Enable (needs the user\'s explicit sign-off).** `workflows-enable` flips it to `active` and an **event/webhook/manual** trigger starts firing on matching activity. From then on it runs on real people, and every change goes through the draft → test → publish cycle before taking effect — so finish testing, then get the user\'s explicit go before enabling. Don\'t enable on your own initiative.\n7. **Dispatch (batch/schedule only).** A `batch` workflow does **not** fire on enable alone. Send a one-off broadcast with `workflows-run-batch`, or attach a recurring schedule with `workflows-schedule-create`. Confirm with `workflows-get` that `status==\'active\'` _and_ its read-only `schedules` field has an active entry.\n8. **Monitor.** Drill down: `workflows-global-stats` (which workflows are failing) to `workflows-stats` (one workflow\'s trend) to `workflows-list-invocations` (who it failed for) to `workflows-get-invocation` (the triggering payload) to `workflows-logs` (the failing step).\n\nFull tool catalog, grouped by job: [references/lifecycle-and-debugging.md](references/lifecycle-and-debugging.md).\n\n## Editing a draft\n\n**Patch, don\'t replace.** Edit a draft with `workflows-patch-graph`: a small, ordered list of id-addressed operations (`update_action`, `add_action`, `remove_action`, `add_edge`, `remove_edge`, `replace_action_edges`). `update_action` deep-merges its patch, so changing one email subject is a few lines, not the whole graph. The ops apply atomically server-side (read, apply in order, validate, save only if valid), and the response echoes the **full updated graph**, so you never re-fetch before the next edit. This keeps each round-trip tiny instead of re-transmitting every action and edge.\n\n`workflows-update` covers only what a graph patch can\'t express: top-level fields like name, description, exit_condition, conversion, trigger_masking, and variables. It rejects `actions`/`edges` outright - a partial list would silently drop every step it omits - so every graph change goes through `workflows-patch-graph`.\n\nAfter **any** patch, re-test the path you changed (step 3). A patch that validates structurally can still route the wrong way.\n\nEmail content follows the same rule.\nThe email inside a `function_email` step is edited with **`workflows-patch-action-email`**: the same id-addressed design ops as the template patch, plus an `email_patch` merge for subject/preheader/text/recipients, with the HTML re-rendered server-side so it always matches the design.\nPrefer it over `workflows-patch-graph` `update_action` for email content - an `update_action` that changes `design` leaves the stored `html` stale.\nLibrary templates are edited with **`workflows-patch-email-template`**, not `workflows-update-email-template` (which resends the entire design JSON).\nCompose and edit email designs with the **`designing-email-templates`** skill.\n\n## Changing a live workflow\n\nEditing an active workflow stages a **draft** instead of changing what\'s running: nothing reaches real people until you publish. Work the cycle:\n\n1. **Edit.** `workflows-patch-graph` (or `workflows-update` for content fields) on the active workflow writes to its draft — the first edit copies the live graph into the draft, later edits compose onto it. `workflows-get` shows the staged draft in `draft`; the live config stays in `actions`/`edges`. Metadata (name, description) applies live immediately.\n2. **Test the draft.** `workflows-test-run` with `use_draft=true` executes the staged draft instead of the live config. Re-test every path you changed.\n3. **Publish deliberately.** `workflows-publish` without `confirm` returns `in_flight_runs`, a `confirm_token`, and an `impact` summary: per deleted step, about how many people are parked there and whether they move to a surviving step (`moves_to`) or exit; `empty_variables` that may render empty for people already past their new producer when they reach a reference (a structural warning — it can fire even when everyone in-flight is still upstream of the producer); `schedule_conflicts` where a schedule overrides a variable the draft removes. **Echo the impact to the user and get their go-ahead**, then call again with `confirm=true` and that `confirm_token`. A 409 means the draft changed since the preview and a 400 means the token expired (15 minutes) — preview again and re-confirm either way. Publish revalidates everything, so an invalid draft is rejected and live config stays untouched.\n4. **Or bail.** `workflows-discard-draft` throws the staged draft away.\n\nIn-flight runs follow the live config: once published, people mid-flow continue from their current step on the new version. Steps they already passed don\'t re-run; people parked on a step the publish deletes skip forward to its next surviving step (or exit at a dead end), exactly as the impact preview reported.\n\nTiming edits apply to parked runs gradually, not instantly. Publishing a shortened delay (or a moved wait window) reschedules the runs parked on it via a rate-limited sweep. Runs already due to wake soon keep their original earlier wake untouched; only wakes that the sweep moves earlier are affected, and those land spread out, no sooner than a few minutes after publish (and never later than their original wake). Runs still parked shortly after publishing are expected - tell the user this rather than re-publishing or treating it as a failure.\n\n### Rolling back\n\nEvery live-content change appends a snapshot to the workflow\'s revision history. `workflows-list-revisions` lists versions (newest first); `workflows-get-revision` returns one version\'s full content. To roll back (or forward), `workflows-restore-revision` copies that version\'s content into the draft — it never touches the live config — then the normal publish cycle applies: test with `use_draft=true`, preview, confirm. The preview shows exactly what the rollback does to people in-flight, same as any publish.\n\nA restore returns 409 when a draft is already open; publish or discard it, or pass `overwrite=true` to replace it. Two things a rollback cannot undo: runs that already moved or exited while the newer version was live keep their positions (their side effects happened), and a publish that shortened a delay may have pulled parked wake times earlier — rolling back doesn\'t push them later again.\n\n## What the server owns, never send it\n\nThe server compiles and manages these. Authoring them by hand is the fastest way to a broken workflow:\n\n- **`bytecode`** on any filter, trigger, condition, conversion, or masking. Compiled server-side from the human-readable `properties`/`hash`. Omit it; send `filters: {...}`, not bytecode.\n- **`trigger`** (top-level). _Derived_ from the `trigger` action in `actions`. Read-only. Set the trigger by adding the trigger node, not by setting this field.\n- **`billable_action_types`**, `version`, `id`, `created_*`. Computed/managed.\n\n## Minimal worked example\n\nEvent trigger, wait 1 day, send email, exit. Note: exactly one `trigger`, every non-exit node has an outgoing edge, ids are referenced consistently by `edges`, and no `bytecode` is sent.\n\n```json\n{\n "name": "Nudge after signup",\n "description": "One day after signup, send a reminder.",\n "exit_condition": "exit_only_at_end",\n "actions": [\n {\n "id": "trigger_node",\n "name": "Signed up",\n "type": "trigger",\n "config": {\n "type": "event",\n "filters": { "events": [{ "id": "user signed up", "name": "user signed up", "type": "events", "order": 0 }] }\n }\n },\n {\n "id": "delay_1",\n "name": "Wait 1 day",\n "type": "delay",\n "config": { "delay_duration": "1d" }\n },\n {\n "id": "email_1",\n "name": "Reminder email",\n "type": "function_email",\n "config": {\n "template_id": "template-email",\n "template_uuid": "<uuid returned by workflows-create-email-template>",\n "message_category_type": "marketing",\n "inputs": {\n "email": {\n "value": {\n "to": { "email": "{person.properties.email}", "name": "" },\n "from": { "email": "[email protected]", "name": "Example" }\n }\n }\n }\n }\n },\n {\n "id": "exit_node",\n "name": "Exit",\n "type": "exit",\n "config": { "reason": "Done" }\n }\n ],\n "edges": [\n { "from": "trigger_node", "to": "delay_1", "type": "continue" },\n { "from": "delay_1", "to": "email_1", "type": "continue" },\n { "from": "email_1", "to": "exit_node", "type": "continue" }\n ]\n}\n```\n\nEmail bodies come from the template library, not hand-written html:\n\n1. **Reuse first.** List the library with `workflows-list-email-templates` and pick a template that fits. A drip campaign typically references one base template (say, a branded announcement) from every email step.\n2. **Create only if nothing fits.** Author a new template design-first with the **`designing-email-templates`** skill: compose the `design`, omit `html` (the server renders html from the design).\n3. **Reference it** by putting the template\'s UUID in each step\'s `config.template_uuid`, as above. The save snapshots the template\'s subject, text, html, and design into the step.\n4. **Differentiate per step** with `workflows-patch-action-email` design operations - each step\'s snapshot is edited independently, so five steps from one base template can each carry their own content.\n\nThe snapshot is one-way: editing the library template later does not change steps that already referenced it, and patching a step never touches the library template. If a user expects a template edit to flow into their workflows, correct that - the steps keep their copies, and each one is updated with `workflows-patch-action-email`.\n\nAlways give templates a real plain-text `text` alongside the design: clients that block rich content show only `text`, so filler like "placeholder" reaches real inboxes.\n\n## Hard rules to surface to the user, not work around\n\n- **Behavioral targeting is unsupported.** "Did event X at least N times over the last M days" can\'t be expressed as a trigger or a batch/schedule audience. If asked, reject it and explain; don\'t approximate it with a broken filter. (The backend rejects behavioral cohorts in batch audiences outright.)\n- **Batch audiences target _who a person is_, not what they did.** Person properties and/or static/property-based cohorts only. Event/action filters in a batch audience are silently dropped, so they\'re rejected.\n- **Prefer re-evaluating audiences.** For batch, inline person-property conditions or a dynamic (filter-based) cohort re-evaluate as people qualify; a static cohort is a frozen list, use only for an explicit given set.\n\n# Workflow graph schema\n\nThe contract for `actions` and `edges`. The stored workflow is loose JSON, but **the visual editor validates every node against a strict schema keyed on `type`**. A node that saves successfully but doesn\'t match this contract will **break the editor view for the whole workflow** when someone opens it. Treat the shapes below as required, not advisory.\n\n## Contents\n\n- Node (action) shape\n- Action types and their `config`\n- Edges\n- `function*` inputs\n- Duration strings (`delay_duration`, `max_wait_duration`)\n- Conversion & exit condition\n- Pre-submit checklist\n\n## Node (action) shape\n\nEvery action object has these common fields plus a type-specific `config`:\n\n```json\n{\n "id": "unique_within_workflow",\n "name": "Human label",\n "description": "",\n "type": "<see action types>",\n "config": {},\n "on_error": "continue",\n "filters": null,\n "output_variable": null\n}\n```\n\n- `id` — unique within the workflow; edges reference it by `from`/`to`.\n- `on_error` — optional; **only `continue` or `abort`.** Omit to use the default.\n- `filters` — optional property filters gating the action: `{properties: [<cond>]}`. Send `properties`, not `bytecode`.\n- `output_variable` — optional; store a step result into a workflow variable. `{key, result_path?, spread?}`.\n\n## Action types and their `config`\n\nUse **only** these `type` values — they are the complete supported set. An unknown or unsupported `type` breaks the editor\'s parse for the entire graph.\n\n| `type` | `config` |\n| ------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |\n| `trigger` | a trigger config (see below). Exactly one trigger node per workflow. |\n| `delay` | `{ "delay_duration": "30m" }` — see duration rules below. |\n| `conditional_branch` | `{ "conditions": [ { "filters": {"properties": [<cond>]}, "name?": "" } ] }`. Index N pairs with the `branch` edge `index: N`. |\n| `random_cohort_branch` | `{ "cohorts": [ { "percentage": 50, "name?": "A" } ] }`. Percentages are relative weights and should sum to 100, but a total above or below 100 still splits traffic in the given proportions. |\n| `wait_until_condition` | `{ "condition?": {"filters": {"properties": [<cond>]}}, "events?": [{"filters": {...}, "name?": ""}], "max_wait_duration": "7d" }`. `condition` is optional: an **events-only** wait is valid (server seeds a missing `condition` as `{filters: null}`). Duration rules as `delay`. |\n| `wait_until_time_window` | `{ "timezone": "UTC", "use_person_timezone?": false, "day": <"weekday" / "weekend" / "any" / ["monday",...]>, "time": <"any" / ["10:00","11:00"]> }`. |\n| `function` | `{ "template_id": "<live template id>", "inputs": { ... }, "mappings?": [] }`. Don\'t guess the id or its inputs — discover them live (see below). |\n| `function_email` | `{ "template_id?": "template-email", "template_uuid?": "<saved template UUID>", "inputs": {"email": {"value": {...}}}, "message_category_type?": <"marketing" / "transactional">, "tracking_enabled?": <bool> }`. `template_id` is the **literal** `template-email`; omit it and the server infers it from the step type. Reference a saved library template (from `workflows-list-email-templates`) by putting its UUID in `template_uuid`, never in `template_id` — a UUID sent as `template_id` is moved into `template_uuid` automatically. When `template_uuid` is set and the value has no body keys (`subject`/`text`/`html`/`design`), the server copies the template\'s body into `inputs.email.value` at save (a snapshot — later template edits don\'t propagate); you still supply `from` and `to`. If you author any body key inline, your body wins and `template_uuid` is provenance only. `tracking_enabled` defaults to true; when false, no open pixel is injected and links are not rewritten, so opens/clicks are not recorded for this step (delivery/bounce/unsubscribe still are). |\n| `function_sms` | `{ "template_id?": "template-twilio", "inputs": { ... }, "message_category_type?": "..." }`. `template_id` is the **literal** `template-twilio`; omit it and the server infers it. |\n| `function_push` | `{ "template_id?": "template-native-push", "inputs": { ... }, "message_category_type?": <"marketing" / "transactional"> }`. `template_id` is the **literal** `template-native-push`; omit it and the server infers it. Sends a mobile push notification via FCM/APNs. Its `inputs` are richer than email\'s — `title`, `body`, and a `channels` list of the FCM/APNs integration ids to send through — so retrieve the `template-native-push` `inputs_schema` (as with `function`) for the exact keys, and use the project\'s push integration ids for `channels`. |\n| `exit` | `{ "reason?": "Done" }`. Usually one terminal exit node. |\n\n### Branch and wait condition filters (the `filters` wrapper is mandatory)\n\n`conditional_branch` and `wait_until_condition` gate on a **`filters` object**, the action-filter shape (`{properties?, events?, actions?, source?, filter_test_accounts?}`). The wrapper is not optional:\n\n- Write `{ "filters": { "properties": [<cond>] } }` on each condition, **never** `{ "properties": [<cond>] }` directly on the condition object. The bare form saves but the visual editor flags it and the branch compiles to a constant, so it never evaluates your condition.\n- `conditional_branch` conditions are **property-only** (person/group `<cond>`s). Event/action filters are rejected here ("Event filters are not allowed in conditionals").\n- `wait_until_condition` is event-aware: its `condition.filters` and each `events?[].filters` may also carry `events`/`actions`. An entry naming neither an event nor an action is dropped (it would match everything).\n- `source` is optional (defaults to `events`). Never send `bytecode`; the server compiles it from `properties`.\n\n### Trigger `config` (the `trigger` node)\n\nDiscriminated on `config.type`:\n\n- `event` — `{ "type": "event", "filters": { "events": [{ "id": "<event>", "name": "<event>", "type": "events", "order": 0, "properties": [<cond>] }], "properties": [<cond>], "filter_test_accounts": false } }`. Fires on **every** matching occurrence. Throttle repeats with `trigger_masking` (dedup/sampling — not behavioral filtering).\n- `webhook` / `manual` / `tracking_pixel` — `{ "type": "webhook", "template_id": "<literal>", "inputs": { ... } }`. These use a **fixed built-in source template**, not one you look up: `template-source-webhook` for both `webhook` and `manual`, `template-source-webhook-pixel` for `tracking_pixel`. Omitting or guessing it fails the create with `Template not found` against the trigger node. They are `source_webhook` templates and are **not** in the destination catalog (`cdp-function-templates-list` is `type=destination`), so don\'t try to discover them there. Each needs `inputs.event` and `inputs.distinct_id` wrapped in `{value: ...}`, and the right values **differ per trigger type** because a different request reaches the template:\n - `webhook` — a POST whose body you control: `"inputs": { "event": { "value": "{request.body.event}" }, "distinct_id": { "value": "{request.body.distinct_id}" } }`.\n - `manual` — the "trigger manually" button POSTs `{user_id, $variables}`, so the body carries no `event`: use the fixed literal `"inputs": { "event": { "value": "$workflow_triggered" }, "distinct_id": { "value": "{request.body.user_id}" } }`. Pointing `event` at `{request.body.event}` here makes every manual run return 400 (the source template rejects an empty `event`) while the UI still shows a success toast, so the workflow silently never fires.\n - `tracking_pixel` — a bodyless `GET`, so read query params: `"inputs": { "event": { "value": "{request.query.ph_event}" }, "distinct_id": { "value": "{request.query.ph_distinct_id}" } }`. Body references resolve empty here and the pixel still returns its 200 GIF, so every hit is dropped with no error to retry on.\n- `batch` — `{ "type": "batch", "filters": { "properties": [<cond>] } }`. The audience: person-property conditions and/or cohort references. **No event/action filters** (silently dropped, so rejected). Does not fire on enable — dispatch a one-off broadcast with `workflows-run-batch`, or make it **recurring** with `workflows-schedule-create` (attaches an RRULE schedule; each firing re-broadcasts to this same `config.filters.properties` audience). A recurring workflow is a `batch` trigger plus a schedule — there is no separate "schedule" trigger type to author.\n\n### Trigger masking (throttling an event trigger)\n\n`trigger_masking` is a top-level workflow field (not an action) that throttles an already-matching `event` trigger — it dedups/samples firings, it does not decide who enters.\n\n```json\n"trigger_masking": { "hash": "{person.id}", "ttl": 3600, "threshold": null }\n```\n\n- `hash` — HogQL template defining the dedup key. `"{person.id}"` = once per person.\n- `ttl` — seconds to suppress repeats of the same hash (60–94608000).\n- `threshold?` — fire once per N matches of the same hash (a sampler: N=3 fires on the 1st, 4th, 7th…). Omit to fire once then suppress within `ttl`.\n- Don\'t send `bytecode` — compiled server-side from `hash`.\n\n### Condition shape (`<cond>`)\n\nProperty conditions used in trigger/action `filters`, branch conditions, and conversion:\n\n```json\n{ "key": "plan", "value": ["pro"], "operator": "exact", "type": "person" }\n```\n\n`type` is `event` | `person` | `group`. Never include `bytecode` — the server compiles it.\n\n## Edges\n\n```json\n{ "from": "source_id", "to": "target_id", "type": "continue", "index": 0 }\n```\n\n- `type: "continue"` — fall-through: the sequential next step, or the **no-match** path out of a `conditional_branch`. For a `wait_until_condition` it is the **`max_wait_duration` timeout** path.\n- `type: "branch"` — requires `index`, matching `config.conditions[index]` on a `conditional_branch`. A `wait_until_condition` **resolves** (its `condition` matches or an `events` entry fires) out the `branch` edge at **`index: 0`**.\n- **Every non-exit node needs a reachable next action** via an outgoing edge, or execution fails with "No next action found".\n- A `conditional_branch` with N conditions typically has N `branch` edges (`index: 0..N-1`) plus one `continue` edge for the no-match path.\n- A `wait_until_condition` needs a `branch` edge at `index: 0` (resolution) **and** a `continue` edge (timeout). Without the `index: 0` branch it only ever advances on timeout, never on the event/condition firing.\n\n## `function*` inputs\n\nInputs are keyed by the template\'s input schema, each wrapped in `{value: ...}`:\n\n```json\n"inputs": { "url": { "value": "https://example.com/hook" } }\n```\n\n- **Wrap values in `{value: ...}`.** A flat string won\'t enable templating.\n- Templating uses **single-curly** `{person.x}` / `{event.x}` inside the value string. Liquid-style `{{ ... }}` is rejected on hog-templated fields ("Placeholders are not allowed in this context") — the only fields that accept Liquid are ones whose input schema declares `templating: liquid` (the email input on `function_email` does; most others don\'t).\n- **Dictionary input values are template strings too** — write booleans/numbers as single-expression templates: `"{true}"`, `"{42}"`, which evaluate to the typed value.\n- Required inputs must be present, or create fails with "This field is required".\n\n### Discovering function templates (do this, don\'t guess)\n\nThe set of available `function` templates and their required inputs is **live data**, not something to hardcode — it changes as integrations are added. For a `function` node:\n\n1. `cdp-function-templates-list` (filter `type=destination`) to find the right template and its `id`.\n2. `cdp-function-templates-retrieve` with that id to read its **`inputs_schema`** — the exact keys, types, and which are required.\n3. Build `inputs` from that schema. A `template_id` not in the live list fails with "Template not found".\n\n`function_email`, `function_sms`, and `function_push` are the exception — their `template_id` is the fixed literal `template-email` / `template-twilio` / `template-native-push`, so you don\'t look the `template_id` up, and you can omit it entirely: the server infers the literal from the step type. A saved email template\'s UUID goes in `template_uuid` alongside the literal, never in `template_id` (a UUID sent as `template_id` is moved into `template_uuid` automatically). For `function_email`, referencing a template means you only author `from`/`to`: the server materializes the template\'s body at save (see the action-types table). `function_push` still has variable `inputs` (notably `channels`), so retrieve its `inputs_schema` even though the id is fixed.\n\n### `function_push` worked example\n\nRetrieve `template-native-push` with `cdp-function-templates-retrieve` for the full `inputs_schema` (it has many optional Android/iOS keys), but the core shape is:\n\n```json\n{\n "id": "push_1",\n "name": "Re-engagement push",\n "type": "function_push",\n "config": {\n "template_id": "template-native-push",\n "inputs": {\n "distinctId": { "value": "{event.distinct_id}" },\n "channels": { "value": [6, 7] },\n "title": { "value": "Notification from {event.event}" },\n "body": { "value": "Hi {{ person.properties.first_name }}, come finish setting up.", "templating": "liquid" }\n }\n }\n}\n```\n\n- **`channels`** is an `integration_multi` input: its `value` is an array of **integration id numbers** (e.g. `[6, 7]`), not objects. Find the FCM/APNs integration ids with `integrations-list` (look for `kind` `firebase` / `apns`); at least one is required or the send throws "No push channel configured".\n- **Templating differs per input.** `body` is **liquid** — interpolate with `{{ person.x }}` / `{{ event.x }}` (double braces) and set `"templating": "liquid"`. `title` and the other string inputs are **hog** — use `{event.x}` / `{person.x}` (single braces). The wrong brace style leaves the expression as a literal.\n- Required: `distinctId`, `channels`, `title`. Optional: `body`, `image`, `data`, `ttlSeconds`, `android_*`, `ios_*` (retrieve the `inputs_schema` for the full set).\n- Never hand-author `bytecode` — the server compiles it from `value`. Omit `order` too: the editor lays fields out in the template\'s `inputs_schema` order (fixed and consistent), not by the `order` on your inputs, so leaving it off doesn\'t change the form. Push has no delivered/opened/clicked signal (FCM/APNs respond synchronously), so a successful send means "accepted for delivery", nothing more.\n\n## Duration strings (`delay_duration`, `max_wait_duration`)\n\nMust match `^\\d*\\.?\\d+[dhm]$` — a number plus unit `m` | `h` | `d`. Examples: `30m`, `2h`, `1d`, `0.5m` (=30s).\n\n- **No seconds, no ISO-8601.** For sub-minute, use a fraction of a minute.\n- Per-unit caps are **silently clamped**: `m`≤60, `h`≤24, `d`≤30. Max total 30d. Use the larger unit (`90m` → use `1.5h`) to avoid surprise clamping.\n\n## Conversion & exit condition\n\n- `exit_condition`: `exit_only_at_end` (default), `exit_on_conversion`, `exit_on_trigger_not_matched`, `exit_on_trigger_not_matched_or_conversion`.\n- The `…conversion` variants require a `conversion` goal with two slots plus a window:\n - `filters` — **property conditions only**, an array `[{key, value, operator, type}, ...]` (empty array = any event in the window converts).\n - `events` — **event-based goals**, `[{ "filters": { "events": [{ "id": "<event>", "name": "<event>", "type": "events" }] } }]`.\n - `window_minutes` — minutes after entry (`null` = no window).\n- **An event goal goes in `events`, never in `filters`.** An event object stuffed into `filters` is invisible to the conversion matcher and breaks the conversion picker. Without a goal the `…conversion` exit is a silent no-op. Server compiles the bytecode.\n\n## Pre-submit checklist\n\n- [ ] Exactly **one** `type: "trigger"` action; usually exactly one `exit`.\n- [ ] Every action `type` and `config` matches a row above (no types outside the supported set).\n- [ ] `on_error` is only `continue` or `abort`.\n- [ ] `function_email.template_id == "template-email"`, `function_sms.template_id == "template-twilio"`, `function_push.template_id == "template-native-push"`.\n- [ ] A `webhook` / `manual` trigger sets `template_id == "template-source-webhook"` (a `tracking_pixel` uses `"template-source-webhook-pixel"`) — these are built-in source templates, not catalog lookups.\n- [ ] That trigger\'s `inputs.event` / `inputs.distinct_id` match its own type: `{request.body.*}` for `webhook`, `$workflow_triggered` + `{request.body.user_id}` for `manual`, `{request.query.ph_*}` for `tracking_pixel`. The wrong pair saves fine and then fails at trigger time.\n- [ ] Every non-exit node has an outgoing edge; `branch` edges have an `index` matching a condition.\n- [ ] Every `conditional_branch` / `wait_until_condition` condition is wrapped: `{filters: {properties: [...]}}`, not `{properties: [...]}`.\n- [ ] All durations match `^\\d*\\.?\\d+[dhm]$` and dodge the silent per-unit clamp.\n- [ ] Function inputs are `{key: {value: ...}}`; no hand-written `bytecode` anywhere; no top-level `trigger` field set.',
+}
diff --git a/services/mcp/package.json b/services/mcp/package.json
index 46c7b432fcb8..e51d2caa84d4 100644
--- a/services/mcp/package.json
+++ b/services/mcp/package.json
@@ -38,6 +38,7 @@
"generate-tools": "tsx scripts/generate-tools.ts",
"generate-exec-docs": "tsx scripts/generate-exec-docs.ts",
"generate-cli-agent-scopes": "tsx scripts/build-cli-agent-scopes.ts",
+ "generate-scene-tool-context": "tsx scripts/build-scene-tool-context.ts",
"scaffold-yaml": "tsx scripts/scaffold-yaml.ts",
"lint-tool-names": "tsx scripts/lint-tool-names.ts",
"lint": "oxlint --quiet",
diff --git a/services/mcp/scripts/build-scene-tool-context.ts b/services/mcp/scripts/build-scene-tool-context.ts
new file mode 100644
index 000000000000..e86c32bedee5
--- /dev/null
+++ b/services/mcp/scripts/build-scene-tool-context.ts
@@ -0,0 +1,202 @@
+#!/usr/bin/env tsx
+/**
+ * Generates per-product agent-context payloads for scene-level PostHog AI integration.
+ *
+ * Scenes that auto-attach AI context (via `useSceneAgentPanel`) front-load the MCP tool
+ * catalog and skill bodies relevant to their product, so the agent can act immediately
+ * instead of spending turns on tool discovery and skill reads. The payloads must track
+ * the live tool descriptions (actively tuned in mcp/*.yaml) and skill markdown, so they
+ * are generated here rather than hand-maintained.
+ *
+ * Reads:
+ * - schema/tool-definitions-all.json (resolved descriptions; produced by generate-tools.ts)
+ * - products/<product>/mcp/*.yaml (which tools are enabled, grouped by source file)
+ * - products/<product>/skills/<skill>/ markdown
+ *
+ * Produces:
+ * - products/<product>/frontend/agentContext.generated.ts
+ *
+ * Run via hogli: `hogli build:openapi-scene-tool-context` (also runs as part of
+ * `build:openapi`, after `build:openapi-mcp-tools` which produces the tool
+ * definitions this reads). See `hogli.yaml`.
+ */
+import { spawnSync } from 'node:child_process'
+import * as fs from 'node:fs'
+import * as path from 'node:path'
+import { parse as parseYaml } from 'yaml'
+
+const MCP_ROOT = path.resolve(__dirname, '..')
+const REPO_ROOT = path.resolve(MCP_ROOT, '../..')
+const ALL_DEFINITIONS_PATH = path.resolve(MCP_ROOT, 'schema/tool-definitions-all.json')
+
+interface ToolSourceConfig {
+ constName: string
+ yamlPath: string
+ /**
+ * Tools registered directly in services/mcp/src/tools (no `enabled:` entry in the YAML), which
+ * YAML-derived membership would silently omit. Resolution still requires each name to exist in
+ * tool-definitions-all.json, so a renamed or removed tool fails the build instead of shrinking
+ * the catalog.
+ */
+ extraTools?: string[]
+}
+
+interface SkillSourceConfig {
+ constName: string
+ skillDir: string
+ /** Markdown files to embed, in order. The first file's YAML frontmatter is stripped. */
+ files: string[]
+}
+
+interface SceneContextConfig {
+ output: string
+ tools: ToolSourceConfig[]
+ skills: SkillSourceConfig[]
+}
+
+const CONFIGS: SceneContextConfig[] = [
+ {
+ output: 'products/workflows/frontend/agentContext.generated.ts',
+ tools: [
+ {
+ constName: 'WORKFLOWS_MCP_TOOLS',
+ yamlPath: 'products/workflows/mcp/tools.yaml',
+ extraTools: [
+ 'workflows-enable',
+ 'workflows-archive',
+ 'workflows-blast-radius',
+ 'workflows-run-batch',
+ 'workflows-schedule-create',
+ ],
+ },
+ { constName: 'EMAIL_TEMPLATE_MCP_TOOLS', yamlPath: 'products/workflows/mcp/email_templates.yaml' },
+ ],
+ skills: [
+ {
+ constName: 'BUILDING_WORKFLOWS_SKILL',
+ skillDir: 'products/workflows/skills/building-workflows',
+ files: ['SKILL.md', 'references/graph-schema.md'],
+ },
+ ],
+ },
+]
+
+interface ToolDefinition {
+ description?: string
+ feature?: string
+}
+
+function enabledToolNames(yamlPath: string): string[] {
+ const parsed = parseYaml(fs.readFileSync(path.resolve(REPO_ROOT, yamlPath), 'utf8')) as {
+ tools?: Record<string, { enabled?: boolean }>
+ }
+ return Object.entries(parsed.tools ?? {})
+ .filter(([, config]) => config?.enabled === true)
+ .map(([name]) => name)
+}
+
+interface FrontmatterResult {
+ meta: { name?: string; description?: string }
+ body: string
+}
+
+function splitFrontmatter(markdown: string): FrontmatterResult {
+ const match = markdown.match(/^---\n([\s\S]*?)\n---\n/)
+ if (!match?.[1]) {
+ return { meta: {}, body: markdown }
+ }
+ return {
+ meta: parseYaml(match[1]) as FrontmatterResult['meta'],
+ body: markdown.slice(match[0].length),
+ }
+}
+
+function renderToolConst(config: ToolSourceConfig, definitions: Record<string, ToolDefinition>): string {
+ const { constName, yamlPath } = config
+ const names = [...enabledToolNames(yamlPath), ...(config.extraTools ?? [])]
+ const entries = names.map((name) => {
+ const definition = definitions[name]
+ if (!definition?.description) {
+ throw new Error(
+ `tool "${name}" is enabled in ${yamlPath} (or listed in extraTools) but has no description in ` +
+ 'tool-definitions-all.json — run `hogli build:openapi-mcp-tools` first'
+ )
+ }
+ return (
+ ' {\n' +
+ ` name: ${JSON.stringify(name)},\n` +
+ ` description: ${JSON.stringify(definition.description)},\n` +
+ ' },'
+ )
+ })
+ return `export const ${constName}: McpToolSummary[] = [\n${entries.join('\n')}\n]\n`
+}
+
+function renderSkillConst(config: SkillSourceConfig): string {
+ const [firstFile, ...restFiles] = config.files
+ if (!firstFile) {
+ throw new Error(`skill config ${config.constName} has no files`)
+ }
+ const first = splitFrontmatter(fs.readFileSync(path.resolve(REPO_ROOT, config.skillDir, firstFile), 'utf8'))
+ const skillName = first.meta.name ?? path.basename(config.skillDir)
+ const parts = [
+ first.body.trim(),
+ ...restFiles.map((file) => fs.readFileSync(path.resolve(REPO_ROOT, config.skillDir, file), 'utf8').trim()),
+ ]
+ return (
+ `export const ${config.constName}: EmbeddedSkill = {\n` +
+ ` name: ${JSON.stringify(skillName)},\n` +
+ ` description: ${JSON.stringify(first.meta.description ?? '')},\n` +
+ ` content: ${JSON.stringify(parts.join('\n\n'))},\n` +
+ '}\n'
+ )
+}
+
+const HEADER =
+ '// AUTO-GENERATED by services/mcp/scripts/build-scene-tool-context.ts.\n' +
+ '// Regenerate with `hogli build:openapi`. Do not edit.\n' +
+ '//\n' +
+ '// Static agent-context payloads for scene-level PostHog AI integration: the enabled\n' +
+ '// MCP tool catalog (names + live descriptions) and embedded skill bodies, attached\n' +
+ '// as context by `useSceneAgentPanel` callers so the agent starts with everything it\n' +
+ '// needs instead of discovering tools and reading skills at run time.\n' +
+ '\n' +
+ 'export interface McpToolSummary {\n' +
+ ' name: string\n' +
+ ' description: string\n' +
+ '}\n' +
+ '\n' +
+ 'export interface EmbeddedSkill {\n' +
+ ' name: string\n' +
+ ' description: string\n' +
+ ' content: string\n' +
+ '}\n'
+
+function main(): void {
+ const definitions = JSON.parse(fs.readFileSync(ALL_DEFINITIONS_PATH, 'utf8')) as Record<string, ToolDefinition>
+
+ for (const config of CONFIGS) {
+ const sections = [
+ HEADER,
+ ...config.tools.map((tool) => renderToolConst(tool, definitions)),
+ ...config.skills.map((skill) => renderSkillConst(skill)),
+ ]
+ const output = sections.join('\n')
+ const outputPath = path.resolve(REPO_ROOT, config.output)
+ const existing = fs.existsSync(outputPath) ? fs.readFileSync(outputPath, 'utf8') : null
+ fs.writeFileSync(outputPath, output)
+ // JSON.stringify emits double quotes; run the repo formatter so the committed file is oxfmt-stable.
+ const format = spawnSync(path.join(REPO_ROOT, 'node_modules/.bin/oxfmt'), [config.output], {
+ cwd: REPO_ROOT,
+ stdio: 'inherit',
+ })
+ if (format.status !== 0) {
+ throw new Error(`oxfmt failed on ${config.output}`)
+ }
+ const formatted = fs.readFileSync(outputPath, 'utf8')
+ // eslint-disable-next-line no-console
+ console.log(formatted === existing ? `${outputPath} already up to date` : `wrote ${outputPath}`)
+ }
+}
+
+main()