:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
chore(workflows): add e2e guarding hidden built-in templates load (#62076)
Meikel Ratzaf75ae00e132
diff --git a/playwright/e2e/workflows-hidden-templates-load.spec.ts b/playwright/e2e/workflows-hidden-templates-load.spec.tsnew file mode 100644index 000000000000..6abade0a55dc--- /dev/null+++ b/playwright/e2e/workflows-hidden-templates-load.spec.ts@@ -0,0 +1,147 @@+import { PlaywrightWorkspaceSetupResult, expect, test } from '../utils/workspace-test-base'++const TRIGGER_NODE_ID = 'trigger_node'+const EXIT_NODE_ID = 'exit_node'+const CAPTURE_NODE_ID = 'capture_node'++// `template-posthog-capture` is shipped with `status: 'hidden'` (see+// nodejs/src/cdp/templates/_destinations/posthog_capture/posthog-capture.template.ts).+// The workflow editor loads every template via the authenticated project list and uses the+// resulting map to render each step's config. A previous change excluded hidden templates from+// that list, which made workflows containing this step render "Template not found!" and blocked+// editing or creating them. This test guards against that regression.+function buildWorkflowWithCaptureStep(): Record<string, any> {+ return {+ name: `Hidden template load ${Date.now()}`,+ actions: [+ {+ id: TRIGGER_NODE_ID,+ type: 'trigger',+ name: 'Trigger',+ description: 'Triggered by an event',+ created_at: 0,+ updated_at: 0,+ config: {+ type: 'event',+ filters: { events: [{ id: '$pageview', type: 'events' }] },+ },+ },+ {+ id: CAPTURE_NODE_ID,+ type: 'function',+ name: 'Capture a PostHog event',+ description: '',+ created_at: 0,+ updated_at: 0,+ config: {+ template_id: 'template-posthog-capture',+ inputs: {},+ },+ },+ {+ id: EXIT_NODE_ID,+ type: 'exit',+ name: 'Exit',+ description: 'Default exit',+ created_at: 0,+ updated_at: 0,+ config: { reason: 'Default exit' },+ },+ ],+ edges: [+ { from: TRIGGER_NODE_ID, to: CAPTURE_NODE_ID, type: 'continue' },+ { from: CAPTURE_NODE_ID, to: EXIT_NODE_ID, type: 'continue' },+ ],+ conversion: { window_minutes: null, filters: [] },+ exit_condition: 'exit_only_at_end',+ version: 1,+ status: 'draft',+ }+}++test.describe('Workflows hidden built-in templates load', () => {+ test.describe.configure({ mode: 'serial' })+ test.setTimeout(90 * 1000)++ let workspace: PlaywrightWorkspaceSetupResult | null = null++ test.beforeAll(async ({ playwrightSetup }) => {+ workspace = await playwrightSetup.createWorkspace({+ skip_onboarding: true,+ no_demo_data: true,+ })+ // Playwright CI doesn't run sync_hog_function_templates, so the templates table is+ // empty. Seed the one this test references with status='hidden' — that's the regression+ // class we want to catch (a server-side filter that strips hidden templates).+ await playwrightSetup.seedHogFunctionTemplate({+ template_id: 'template-posthog-capture',+ name: 'Capture a PostHog event',+ status: 'hidden',+ template_type: 'destination',+ inputs_schema: [+ {+ key: 'event',+ type: 'string',+ label: 'Event name',+ required: true,+ description: 'The name of the event to capture.',+ },+ ],+ })+ })++ test.beforeEach(async ({ page, playwrightSetup }) => {+ await playwrightSetup.loginAndNavigateToTeam(page, workspace!)+ })++ test('opening a workflow whose step uses a hidden template renders its config (no "Template not found")', async ({+ page,+ }) => {+ const teamId = workspace!.team_id+ const workflowPayload = buildWorkflowWithCaptureStep()+ const workflowId = await page.evaluate(+ async ({ teamId, payload }) => {+ const csrfToken =+ document.cookie+ .split(';')+ .map((c) => c.trim())+ .find((c) => c.startsWith('posthog_csrftoken='))+ ?.split('=')+ .slice(1)+ .join('=') || ''+ if (!csrfToken) {+ throw new Error('CSRF cookie missing')+ }+ const response = await fetch(`/api/environments/${teamId}/hog_flows/`, {+ method: 'POST',+ credentials: 'include',+ headers: {+ 'Content-Type': 'application/json',+ 'X-CSRFToken': decodeURIComponent(csrfToken),+ },+ body: JSON.stringify(payload),+ })+ if (!response.ok) {+ throw new Error(`hog_flows POST failed: ${response.status} ${await response.text()}`)+ }+ const data = await response.json()+ return data.id as string+ },+ { teamId, payload: workflowPayload }+ )++ await test.step('open the workflow editor and select the capture step', async () => {+ await page.goto(`/workflows/${workflowId}/workflow`)+ await page.waitForSelector('[data-attr="workflow-editor"]', { timeout: 30000 })+ await page.locator(`[data-testid="rf__node-${CAPTURE_NODE_ID}"]`).click()+ })++ await test.step('the template config renders instead of the not-found fallback', async () => {+ // `template-posthog-capture` declares an "Event name" input in its inputs_schema.+ // If the project list omitted hidden templates, the panel would render+ // <div>Template not found!</div> and this label would never appear.+ await expect(page.getByText('Event name', { exact: true })).toBeVisible({ timeout: 15000 })+ await expect(page.getByText('Template not found!')).toHaveCount(0)+ })+ })+})diff --git a/playwright/utils/playwright-setup.ts b/playwright/utils/playwright-setup.tsindex a79ab424c3fe..0e5290b09f6b 100644--- a/playwright/utils/playwright-setup.ts+++ b/playwright/utils/playwright-setup.ts@@ -302,6 +302,26 @@ export class PlaywrightSetup {await page.goto(`${this.baseURL}/project/${workspace.team_id}`)}++ /**+ * Seed a single HogFunctionTemplate row. Templates are global (not team-scoped) and+ * Playwright CI doesn't run sync_hog_function_templates, so any test that exercises+ * the workflow editor or hog function configuration must seed the templates it needs.+ * Idempotent across parallel workers.+ */+ async seedHogFunctionTemplate(data: {+ template_id: string+ name?: string+ status?: 'alpha' | 'beta' | 'stable' | 'deprecated' | 'hidden' | 'coming_soon' | 'client_side'+ template_type?: 'destination' | 'transformation' | 'source_webhook' | 'site_destination' | 'site_app'+ inputs_schema?: Array<Record<string, any>>+ }): Promise<{ template_id: string; created: boolean }> {+ const result = await this.callSetupEndpoint('hog_function_template', { data })+ if (!result.success) {+ throw new Error(`Failed to seed hog function template: ${result.error}`)+ }+ return result.result as { template_id: string; created: boolean }+ }}/**@@ -314,10 +334,7 @@ export function createPlaywrightSetup(baseURL?: string): PlaywrightSetup {/*** One-off workspace creation (for simple cases)*/-export async function createTestWorkspace(- setupType: string,- data?: Record<string, any>-): Promise<TestSetupResponse> {+export async function createTestWorkspace(setupType: string, data?: Record<string, any>): Promise<TestSetupResponse> {const playwrightSetup = createPlaywrightSetup()try {return await playwrightSetup.callSetupEndpoint(setupType, { data })diff --git a/posthog/test/playwright_setup_functions.py b/posthog/test/playwright_setup_functions.pyindex f53a7fe65b1f..8b94aa556532 100644--- a/posthog/test/playwright_setup_functions.py+++ b/posthog/test/playwright_setup_functions.py@@ -496,6 +496,57 @@ def _create_events_and_persons(data: PlaywrightWorkspaceSetupData, team: Team) -infer_taxonomy_for_team(team.pk)+class PlaywrightHogFunctionTemplateData(BaseModel):+ template_id: str+ name: str = "Test template"+ status: str = "hidden"+ template_type: str = "destination"+ inputs_schema: list[dict[str, Any]] = []+++class PlaywrightHogFunctionTemplateResult(BaseModel):+ template_id: str+ created: bool+++def create_hog_function_template(+ data: PlaywrightHogFunctionTemplateData,+) -> PlaywrightHogFunctionTemplateResult:+ """Seeds a single HogFunctionTemplate row.++ Playwright CI doesn't run `sync_hog_function_templates`, so the templates table is empty.+ Tests that exercise the workflow editor or hog function configuration need to seed any+ template they reference. Templates are global (not team-scoped), so we no-op when a row+ with the same template_id already exists — keeps it idempotent across parallel workers+ without fighting `HogFunctionTemplate.save()` which recomputes `sha` from content.+ """+ from django.db import IntegrityError++ from products.cdp.backend.models.hog_function_template import HogFunctionTemplate++ if HogFunctionTemplate.objects.filter(template_id=data.template_id).exists():+ return PlaywrightHogFunctionTemplateResult(template_id=data.template_id, created=False)++ try:+ HogFunctionTemplate.objects.create(+ template_id=data.template_id,+ sha="playwright-seed",+ name=data.name,+ description=data.name,+ code="return event",+ code_language="hog",+ inputs_schema=data.inputs_schema,+ type=data.template_type,+ status=data.status,+ category=["Other"],+ free=True,+ )+ return PlaywrightHogFunctionTemplateResult(template_id=data.template_id, created=True)+ except IntegrityError:+ # Lost a race with a parallel worker — the row exists now.+ return PlaywrightHogFunctionTemplateResult(template_id=data.template_id, created=False)++@dataclass(frozen=True)class SetupFunctionConfig:function: PlaywrightSetupFunction@@ -509,4 +560,9 @@ PLAYWRIGHT_SETUP_FUNCTIONS: dict[str, SetupFunctionConfig] = {input_model=PlaywrightWorkspaceSetupData,description="Creates org → team + user + API key",),+ "hog_function_template": SetupFunctionConfig(+ function=create_hog_function_template, # type: ignore+ input_model=PlaywrightHogFunctionTemplateData,+ description="Seeds a single HogFunctionTemplate row (templates are global, not team-scoped)",+ ),}diff --git a/products/workflows/frontend/Workflows/hogflows/steps/components/HogFlowFunctionConfiguration.tsx b/products/workflows/frontend/Workflows/hogflows/steps/components/HogFlowFunctionConfiguration.tsxindex 38ac291ca8f4..280c89b30df0 100644--- a/products/workflows/frontend/Workflows/hogflows/steps/components/HogFlowFunctionConfiguration.tsx+++ b/products/workflows/frontend/Workflows/hogflows/steps/components/HogFlowFunctionConfiguration.tsx@@ -1,4 +1,5 @@import { useActions, useValues } from 'kea'+import posthog from 'posthog-js'import { useEffect } from 'react'import { IconCheck } from '@posthog/icons'@@ -56,7 +57,7 @@ export function HogFlowFunctionConfiguration({}if (!template) {- return <div>Template not found!</div>+ return <TemplateNotFoundFallback templateId={templateId} />}const triggerType = workflow?.trigger?.type@@ -199,3 +200,18 @@ export function HogFlowFunctionConfiguration({</>)}++// Reaching this fallback means the workflow editor finished loading the template list but the+// referenced template was not in it — typically a server-side filter regression (see PR #61992)+// or a workflow that points at a deleted/renamed template. Surfaces to error tracking so an+// alert can fire before users start reporting it.+function TemplateNotFoundFallback({ templateId }: { templateId: string }): JSX.Element {+ useEffect(() => {+ posthog.captureException(new Error('Workflow editor: hog function template not found'), {+ severity: 'error',+ tag: 'workflow_editor_template_not_found',+ templateId,+ })+ }, [templateId])+ return <div>Template not found!</div>+}