:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(workflows): create customer analytics tasks (#97753)
Arthur Moreira de Deus7f240a8bc052
diff --git a/docs/internal/customer-analytics-tasks-workflows.md b/docs/internal/customer-analytics-tasks-workflows.mdnew file mode 100644index 000000000000..b55ed6e95fd9--- /dev/null+++ b/docs/internal/customer-analytics-tasks-workflows.md@@ -0,0 +1,46 @@+# Create customer tasks from workflows++In the workflow editor, add **Customer analytics > Create task**. Enter a task name and optionally a description, an account UUID, an assigned project member's user ID, and an ISO 8601 due date. All fields support workflow variables. For **Account** and **Assignee**, choose **Raw** to enter an ID or workflow expression, or **Picker** to select an account or project member using the same pickers as the task modal. Switching modes preserves the current value. A **Get account** step can supply the account UUID in raw mode.++Tasks start with the **Open** status. The created task ID is available as the step's output, including on a retry.+New workflow runs create at most one task per action visit while that task exists.+A retry returns the same task ID without changing the task. A loop that visits the action again creates another task.+An empty or null assignee creates an unassigned task.++New task creation runs with the workflow owner's current customer task permissions.+The owner must be active, retain access to the workflow project and its canonical project, and have editor access to customer tasks.+Account visibility and assignee eligibility match ordinary task creation. A child project's tasks are stored in its canonical parent project.+The customer tasks feature flag must be enabled for the workflow owner.++An authenticated retry returns an existing task's UUID even if the workflow was deleted, the owner's access changed, or the flag was disabled.+The retry must still pass token verification and match the project, workflow, and invocation key.+This response does not grant access to task contents. Requests for new tasks still pass all creation checks.++## Deployment++Task creation reuses `CUSTOMER_ANALYTICS_ACCOUNTS_JWT_SECRET`, the signing key for account actions.+Configure matching keys in Django and the workflow worker before enabling the action in production.+Both accept comma-separated keys for rotation. The worker signs with the first key, and Django verifies against all keys.+Development and test environments use the matching local default.++New runs record their task key version before execution. Retries and manual reruns preserve that version and the action visit count.+Runs created without a version retain their original run-and-action keys, even if no function state was saved before a worker restart.+Those legacy runs create at most one task per action, including across loop visits.+Start a new workflow run to use per-visit task creation.++Task tokens retain their own `posthog:customer-tasks:create` audience. Account tokens cannot call the task endpoint.+The shared key couples service access and rotation for both surfaces. See [Workflow task signing key](../../products/customer_analytics/backend/COMPROMISES.md#workflow-task-signing-key).+Task creation fails when the shared key is missing. Unlike account actions, it has no fallback to the project secret API token.++The worker calls `POST /api/projects/{team_id}/workflow_customer_tasks/` through `INTERNAL_API_BASE_URL`, with a short-lived service token scoped to the project, workflow, and invocation/action key. The call goes directly to the backend, avoiding login redirects on the public app URL. Redirects and responses without a valid task UUID fail the workflow step. User API credentials and tokens for other actions cannot call this endpoint. No database migration is required.++For local development, set `INTERNAL_API_BASE_URL` to the address where the backend listens. Linux devboxes may bind to the Docker bridge address, such as `http://172.17.0.1:8000`, instead of localhost. Restart the dev processes after changing the local environment.++## Backend ownership++Customer analytics registers the endpoint in `products/customer_analytics/backend/routes.py`.+The HTTP view lives in `products/customer_analytics/backend/presentation/views/workflow_customer_tasks.py` and delegates creation to `backend/facade/workflow_customer_tasks.py` in the same product.+That facade reads the workflow owner ID through `products/workflows/backend/facade/api.py`.+Only Workflows queries the workflow model.+The URL and basename stay unchanged.+The view pins its OpenAPI product attribution to `workflows` but remains excluded from generated API docs.diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 4afa42596ba3..4d71800ce097 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -6132,6 +6132,14 @@ snapshots:hash: v1.k794b7964.908aa54619e9e4669005bebc9ed7166052200b1613a2f36900bb18af7c74b2ba.PAhdvkGE9vb64e93_Ap6KJohFsSBjwa8BsPKVRT-IXEproducts-workflows-reputation--shared-sending-domain--light:hash: v1.k794b7964.95181ed4e0a17456b9e62c3e467ddc605b1a733c81ea6f7c6e0c61928aa3f22d.ZMctRK-G6wUmjfa2paqyxhRtmF0TG_WVyOPLWhFWXyU+ products-workflows-steps-customer-task-reference-input--account--dark:+ hash: v1.k794b7964.c83bf0997a28fd49e6d3dbae06e5ee75aa10a76365a5cb39c530324ecf112875.addysRvtjXvOb8pPGo4RZl1HL2_YcGnvqrpSB067bNs+ products-workflows-steps-customer-task-reference-input--account--light:+ hash: v1.k794b7964.a373f14a674936c9fd76f26ce8abbf735b977f4a4dbaf90ff3c785cd16eb9ea8.toZvK0UtefEnMcf994SYInWq-s3Vhtju6U-rMzq5E9Q+ products-workflows-steps-customer-task-reference-input--assignee--dark:+ hash: v1.k794b7964.6aba25e0cf13e9f0851aab52c7e13e4f849a386bae1e387c9931e5aeb2c1d445.vdRw1Brlx8435mOkTj6OS8IhQslGTaZ2BBExKMLnRNI+ products-workflows-steps-customer-task-reference-input--assignee--light:+ hash: v1.k794b7964.636b550779f4281c61e425a0c91ad7e9f58fd6dd1b2a6e70961ac8033b8ff78d.KfkxsuB-QaL4_Na5ZLLCWoN3Pa4cmWXs79McVX3-J-Mproducts-workflows-steps-delay--date-not-chosen-yet--dark:hash: v1.k794b7964.ec9c913ba6edb54c2b521e3b1913e45fe914dcd4fc5b45febacd543038865cd0.khqeV0deGQR_Ows3heRrRyvzw8fUBJ6KUNQbhb1asasproducts-workflows-steps-delay--date-not-chosen-yet--light:diff --git a/nodejs/src/cdp/async-functions/create-customer-task.test.ts b/nodejs/src/cdp/async-functions/create-customer-task.test.tsnew file mode 100644index 000000000000..f6a3d3cfc889--- /dev/null+++ b/nodejs/src/cdp/async-functions/create-customer-task.test.ts@@ -0,0 +1,80 @@+import { defaultConfig } from '~/common/config/config'+import { parseJSON } from '~/common/utils/json-parse'+import * as requestModule from '~/common/utils/request'++import { createExampleInvocation } from '../_tests/fixtures'+import { AsyncFunctionContext, getAsyncFunctionHandler } from '../async-function-registry'+import { CyclotronJobInvocationHogFunctionContext, MinimalLogEntry } from '../types'+import { createInvocationResult } from '../utils/invocation-utils'+import './create-customer-task'++describe('postHogCreateCustomerTask', () => {+ const invokeMock = (payload: Record<string, unknown>): any =>+ getAsyncFunctionHandler('postHogCreateCustomerTask')!.mock([payload], [] as MinimalLogEntry[])++ const invokeLive = async (+ payload: Record<string, unknown>,+ state: Partial<CyclotronJobInvocationHogFunctionContext> = {}+ ): Promise<void> => {+ const invocation = {+ ...createExampleInvocation(),+ hogFlow: { id: 'flow-1' },+ }+ Object.assign(invocation.state, { actionId: 'action_1', ...state })+ await getAsyncFunctionHandler('postHogCreateCustomerTask')!.execute(+ [payload],+ {+ invocation,+ internalApiBaseUrl: defaultConfig.INTERNAL_API_BASE_URL,+ consumeInlineAsyncBudget: () => {},+ } as unknown as AsyncFunctionContext,+ createInvocationResult<typeof invocation>(invocation)+ )+ }++ let fetchSpy: jest.SpyInstance+ beforeEach(() => {+ fetchSpy = jest.spyOn(requestModule, 'internalFetch').mockResolvedValue({+ status: 201,+ text: () => Promise.resolve(JSON.stringify({ id: '00000000-0000-4000-8000-000000000000' })),+ } as requestModule.FetchResponse)+ })+ afterEach(() => jest.restoreAllMocks())++ // The step test panel mocks async functions by default. A mock body carrying fields the+ // endpoint never returns lets an author map an output that resolves to nothing live.+ it.each([42, null, undefined])('accepts assignee %j and returns only the task ID', (assigned_to_id) => {+ expect(invokeMock({ name: 'Follow up', description: 'Review the account', assigned_to_id })).toEqual({+ status: 201,+ body: { id: '00000000-0000-4000-8000-000000000000' },+ })+ })++ it.each([+ ['a blank name', { name: ' ' }, /Enter a task name/],+ ['a zero assignee', { name: 'Follow up', assigned_to_id: 0 }, /valid numeric assignee user ID/],+ ['a boolean assignee', { name: 'Follow up', assigned_to_id: true }, /valid numeric assignee user ID/],+ ['a fractional assignee', { name: 'Follow up', assigned_to_id: 1.5 }, /valid numeric assignee user ID/],+ ['a non-numeric assignee', { name: 'Follow up', assigned_to_id: 'someone' }, /valid numeric assignee user ID/],+ ])('rejects %s in both mocked and live calls', async (_name, payload, expected) => {+ expect(() => invokeMock(payload)).toThrow(expected)+ await expect(invokeLive(payload)).rejects.toThrow(expected)+ expect(fetchSpy).not.toHaveBeenCalled()+ })++ it.each([null, undefined])('omits assignee %j from the live request', async (assigned_to_id) => {+ await invokeLive({ name: 'Follow up', assigned_to_id })++ expect(fetchSpy).toHaveBeenCalledTimes(1)+ const body = parseJSON(fetchSpy.mock.calls[0][1].body)+ expect(body.name).toBe('Follow up')+ expect(body).not.toHaveProperty('assigned_to_id')+ })++ it.each([undefined, -1, 1.5, NaN])('rejects invalid versioned visit count %j', async (actionStepCount) => {+ await expect(+ invokeLive({ name: 'Follow up' }, { customerTaskIdempotencyVersion: 1, actionStepCount })+ ).rejects.toThrow(/valid workflow visit count/)+ expect(fetchSpy).not.toHaveBeenCalled()+ })+})diff --git a/nodejs/src/cdp/async-functions/create-customer-task.ts b/nodejs/src/cdp/async-functions/create-customer-task.tsnew file mode 100644index 000000000000..f27d810e238c--- /dev/null+++ b/nodejs/src/cdp/async-functions/create-customer-task.ts@@ -0,0 +1,84 @@+import { DateTime } from 'luxon'++import { HogFlow } from '~/cdp/schema/hogflow'+import { defaultConfig } from '~/common/config/config'++import { registerAsyncFunction } from '../async-function-registry'+import { PosthogJwtAudience } from '../utils/jwt-utils'+import { ScopedServiceJwt } from '../utils/scoped-service-jwt'+import { callInternalApi } from './internal-api-call'++let customerTasksJwt: ScopedServiceJwt | undefined+const getCustomerTasksJwt = (): ScopedServiceJwt =>+ (customerTasksJwt ??= new ScopedServiceJwt(+ PosthogJwtAudience.CUSTOMER_TASKS_CREATE,+ defaultConfig.CUSTOMER_ANALYTICS_ACCOUNTS_JWT_SECRET+ ))++// The workflow step test panel mocks async functions by default, so `mock` runs these checks too.+// A payload the mock accepts but the endpoint rejects lets an author ship a step that only ever+// worked in the test panel.+const parseTaskPayload = (args: any[]): { payload: Record<string, unknown>; assigneeId: number | undefined } => {+ const [payload] = args as [Record<string, unknown> | undefined]+ if (typeof payload?.name !== 'string' || !payload.name.trim()) {+ throw new Error('Enter a task name')+ }++ const assigneeId = payload.assigned_to_id == null ? undefined : Number(payload.assigned_to_id)+ if (+ assigneeId !== undefined &&+ (!['number', 'string'].includes(typeof payload.assigned_to_id) ||+ !Number.isSafeInteger(assigneeId) ||+ assigneeId <= 0)+ ) {+ throw new Error('Enter a valid numeric assignee user ID')+ }++ return { payload, assigneeId }+}++registerAsyncFunction('postHogCreateCustomerTask', {+ execute: async (args, context, result) => {+ const { payload, assigneeId } = parseTaskPayload(args)++ const hogFlow = (context.invocation as { hogFlow?: HogFlow }).hogFlow+ const { actionId, actionStepCount, customerTaskIdempotencyVersion } = context.invocation.state+ if (!hogFlow?.id || !actionId) {+ throw new Error('Customer analytics tasks can only be created inside a workflow')+ }++ // Bind both the request and token to the trusted run and step, never to user input.+ let idempotencyKey = `${context.invocation.id}:${actionId}`+ if (customerTaskIdempotencyVersion === 1) {+ if (typeof actionStepCount !== 'number' || !Number.isSafeInteger(actionStepCount) || actionStepCount < 0) {+ throw new Error('Customer task creation requires a valid workflow visit count. Contact support.')+ }+ idempotencyKey = `${idempotencyKey}:${actionStepCount}`+ }++ const jwt = getCustomerTasksJwt()+ if (!jwt.enabled) {+ throw new Error(+ 'Customer task creation is not configured. Set CUSTOMER_ANALYTICS_ACCOUNTS_JWT_SECRET on the worker and Django to matching keys.'+ )+ }+ await callInternalApi(context, result, {+ jwt,+ path: `/api/projects/${context.invocation.teamId}/workflow_customer_tasks/`,+ method: 'POST',+ entityClaims: { hog_flow_id: hogFlow.id, idempotency_key: idempotencyKey },+ body: JSON.stringify({ ...payload, assigned_to_id: assigneeId, idempotency_key: idempotencyKey }),+ })+ },+ mock: (args, logs) => {+ parseTaskPayload(args)+ logs.push({+ level: 'info',+ timestamp: DateTime.now(),+ message: 'Customer task creation was mocked. No task was created or permissions checked.',+ })+ // Only the field the endpoint returns, so a mapping built against a mocked test still+ // resolves live. The template checks the ID is a UUID, so the placeholder must be one.+ return { status: 201, body: { id: '00000000-0000-4000-8000-000000000000' } }+ },+})diff --git a/nodejs/src/cdp/async-functions/index.ts b/nodejs/src/cdp/async-functions/index.tsindex 6c55f5d6216a..97df8292265f 100644--- a/nodejs/src/cdp/async-functions/index.ts+++ b/nodejs/src/cdp/async-functions/index.ts@@ -1,4 +1,5 @@import './conversations'+import './create-customer-task'import './create-task'import './customer_analytics'import './fetch-handler'diff --git a/nodejs/src/cdp/config.ts b/nodejs/src/cdp/config.tsindex 87ef65cd8b63..59bf1d2a0eef 100644--- a/nodejs/src/cdp/config.ts+++ b/nodejs/src/cdp/config.ts@@ -375,8 +375,8 @@ export function getDefaultCdpConfig(): CdpConfig {// Dev default must equal Django's CONVERSATIONS_TICKETS_JWT_SECRETS default so local// end-to-end works; empty in prod until provisioned (worker then stays on legacy auth).CONVERSATIONS_TICKETS_JWT_SECRET: isTestEnv() || isDevEnv() ? 'local-dev-conversations-tickets-jwt' : '',- // Dev default must equal Django's CUSTOMER_ANALYTICS_ACCOUNTS_JWT_SECRETS default so local- // end-to-end works; empty in prod until provisioned (worker then stays on legacy auth).+ // Dev/test default must match Django's CUSTOMER_ANALYTICS_ACCOUNTS_JWT_SECRETS so local calls work.+ // When empty, account actions use legacy auth. Customer task creation fails closed without a fallback.CUSTOMER_ANALYTICS_ACCOUNTS_JWT_SECRET:isTestEnv() || isDevEnv() ? 'local-dev-customer-analytics-accounts-jwt' : '',// Dev/test default must match Django's (posthog/settings/data_stores.py).diff --git a/nodejs/src/cdp/consumers/cdp-cyclotron-worker-batch-resolve.consumer.test.ts b/nodejs/src/cdp/consumers/cdp-cyclotron-worker-batch-resolve.consumer.test.tsindex bc7f44e22793..f5b85ca0fd4a 100644--- a/nodejs/src/cdp/consumers/cdp-cyclotron-worker-batch-resolve.consumer.test.ts+++ b/nodejs/src/cdp/consumers/cdp-cyclotron-worker-batch-resolve.consumer.test.ts@@ -50,6 +50,7 @@ describe('CdpCyclotronWorkerBatchResolve', () => {// Account broadcasts convert long after the send, so the run has to carry the version// that sent or the conversion is credited to whatever is published by then.expect(state.flowVersion).toBe(4)+ expect(state.customerTaskIdempotencyVersion).toBe(1)expect(state.variables).toEqual({ greeting: 'hi' })expect(invocation.parentRunId).toEqual('batch-job-1')expect(invocation.queue).toEqual('hogflow')@@ -191,7 +192,7 @@ describe('CdpCyclotronWorkerBatchResolve', () => {}})- it('stamps the enqueue time into the state that gets persisted', async () => {+ it('persists the enqueue time and customer task key version for new person runs', async () => {// The stamp is written onto the invocation by queueLifecycleRow, so it only lands in// cyclotron if that runs before the state is serialized. Out of order, the terminal// row written when the run wakes records the wake time and wins the argMax collapse.@@ -200,7 +201,11 @@ describe('CdpCyclotronWorkerBatchResolve', () => {const { newJobs } = bulkCreateAndCheckIn.mock.calls[0][0]expect(newJobs).toHaveLength(2)for (const job of newJobs) {- expect(job.state.toString()).toContain('firstScheduledAt')+ expect(parseJSON(job.state.toString()).state).toMatchObject({+ firstScheduledAt: expect.any(String),+ actionStepCount: 0,+ customerTaskIdempotencyVersion: 1,+ })}})diff --git a/nodejs/src/cdp/consumers/cdp-cyclotron-worker-batch-resolve.consumer.ts b/nodejs/src/cdp/consumers/cdp-cyclotron-worker-batch-resolve.consumer.tsindex 2b091b46952c..653905562e71 100644--- a/nodejs/src/cdp/consumers/cdp-cyclotron-worker-batch-resolve.consumer.ts+++ b/nodejs/src/cdp/consumers/cdp-cyclotron-worker-batch-resolve.consumer.ts@@ -614,6 +614,7 @@ export function buildAccountHogFlowInvocation(params: {event: invocationGlobals.event,accountAudience: true,actionStepCount: 0,+ customerTaskIdempotencyVersion: 1,variables: params.defaultVariables,// Same reason as createHogFlowInvocation: a broadcast's conversions arrive long after// the send, so they attribute to the version that sent, not the one live by then.@@ -658,6 +659,7 @@ function buildHogFlowInvocation(params: {event: invocationGlobals.event,personId: params.personId,actionStepCount: 0,+ customerTaskIdempotencyVersion: 1,variables: params.defaultVariables,// Same reason as createHogFlowInvocation: a broadcast's conversions arrive days after// the send, so they have to attribute to the version that sent, not the one live then.diff --git a/nodejs/src/cdp/rerun/rerun-paginator.replay-fidelity.test.ts b/nodejs/src/cdp/rerun/rerun-paginator.replay-fidelity.test.tsindex dddb7588293d..edbf876c8f46 100644--- a/nodejs/src/cdp/rerun/rerun-paginator.replay-fidelity.test.ts+++ b/nodejs/src/cdp/rerun/rerun-paginator.replay-fidelity.test.ts@@ -76,10 +76,11 @@ describe('RerunPaginatorService replay fidelity (hog_flow)', () => {progress: { queued: 0, skipped: 0, done: false },}- it('restores currentAction and personId so a partially-run flow resumes instead of restarting', async () => {+ it.each([undefined, 1] as const)('restores progress and customer task key version %j', async (version) => {const persistedState = {event: { uuid: 'evt-1', distinct_id: 'd-1', properties: {}, timestamp: '2026-06-01T09:00:00Z' },actionStepCount: 3,+ customerTaskIdempotencyVersion: version,variables: { ticket_id: '123' },// The flow had already advanced to (and parked at) this action. The parked// hogFunctionState is stored as `stripInputs` wrote it: `globals.inputs` gone.@@ -126,6 +127,7 @@ describe('RerunPaginatorService replay fidelity (hog_flow)', () => {expect(invocation.state?.currentAction).toEqual({ id: 'send_email', startedAtTimestamp: 999 })expect(invocation.state?.personId).toBe('person-1')expect(invocation.state?.actionStepCount).toBe(3)+ expect(invocation.state?.customerTaskIdempotencyVersion).toBe(version)expect(invocation.state?.variables).toEqual({ ticket_id: '123' })// Sticky rerun counter still increments so max_attempts guards apply.expect(invocation.state?.rerunAttempts).toBe(1)@@ -157,5 +159,6 @@ describe('RerunPaginatorService replay fidelity (hog_flow)', () => {const invocation = hogFlowQueue.queueInvocations.mock.calls[0][0][0] as CyclotronJobInvocationHogFlowexpect(invocation.state?.currentAction).toBeUndefined()+ expect(invocation.state?.customerTaskIdempotencyVersion).toBeUndefined()})})diff --git a/nodejs/src/cdp/rerun/rerun-paginator.service.ts b/nodejs/src/cdp/rerun/rerun-paginator.service.tsindex ba65985840bb..f4a73a0cb61a 100644--- a/nodejs/src/cdp/rerun/rerun-paginator.service.ts+++ b/nodejs/src/cdp/rerun/rerun-paginator.service.ts@@ -808,6 +808,8 @@ export class RerunPaginatorService {...invocation.state!,event: eventForFilter,actionStepCount: persistedState.actionStepCount ?? 0,+ // Absence must override the new-run default so legacy replays keep their original task keys.+ customerTaskIdempotencyVersion: persistedState.customerTaskIdempotencyVersion,variables: persistedState.variables ?? {},// Restore where the flow had progressed to. The executor resumes// from `currentAction` (via ensureCurrentAction); without it thediff --git a/nodejs/src/cdp/services/hogflows/hogflow-executor.service.test.ts b/nodejs/src/cdp/services/hogflows/hogflow-executor.service.test.tsindex 1b9be3619de8..49a5c6e445b6 100644--- a/nodejs/src/cdp/services/hogflows/hogflow-executor.service.test.ts+++ b/nodejs/src/cdp/services/hogflows/hogflow-executor.service.test.ts@@ -7,10 +7,14 @@ import { FixtureHogFlowBuilder, SimpleHogFlowRepresentation } from '~/cdp/_testsimport { createHogExecutionGlobals, insertHogFunctionTemplate, insertIntegration } from '~/cdp/_tests/fixtures'import { HogFlow } from '~/cdp/schema/hogflow'import { template as posthogCaptureTemplate } from '~/cdp/templates/_destinations/posthog_capture/posthog-capture.template'+import { template as customerTaskTemplate } from '~/cdp/templates/_destinations/posthog_customer_analytics/posthog-create-customer-task.template'+import { template as setVariableTemplate } from '~/cdp/templates/_destinations/posthog_workflows/posthog-set-variable.template'import { compileHog } from '~/cdp/templates/compiler'+import { convertToHogFunctionFilterGlobal } from '~/cdp/utils/hog-function-filtering'import { createHub } from '~/common/utils/db/hub'+import { parseJSON } from '~/common/utils/json-parse'import { logger } from '~/common/utils/logger'-import { fetch } from '~/common/utils/request'+import { FetchResponse, fetch, internalFetch } from '~/common/utils/request'import { createTestTeamFixture, uniqueTestId } from '~/tests/helpers/sql'import { Hub, Team } from '../../../types'@@ -37,6 +41,7 @@ jest.mock('~/common/utils/request', () => {const original = jest.requireActual('~/common/utils/request')return {...original,+ internalFetch: jest.fn(),fetch: jest.fn().mockImplementation((url, options) => {return original.fetch(url, options)}),@@ -50,6 +55,7 @@ const cleanLogs = (logs: string[]): string[] => {describe('Hogflow Executor', () => {let executor: HogFlowExecutorService+ let hogFlowFunctionsService: HogFlowFunctionsServicelet hub: Hublet team: Teamlet integrationId: number@@ -122,11 +128,7 @@ describe('Hogflow Executor', () => {})const hogFunctionTemplateManager = new HogFunctionTemplateManagerService(hub.postgres)- const hogFlowFunctionsService = new HogFlowFunctionsService(- hub.SITE_URL,- hogFunctionTemplateManager,- hogExecutor- )+ hogFlowFunctionsService = new HogFlowFunctionsService(hub.SITE_URL, hogFunctionTemplateManager, hogExecutor)const recipientsManager = new RecipientsManagerService(hub.postgres)const recipientPreferencesService = new RecipientPreferencesService(recipientsManager, emailSuppressionService)// Stubbed to always allow: this suite covers executor routing and flow control,@@ -424,11 +426,137 @@ describe('Hogflow Executor', () => {})})+ it.each([false, true])('keeps legacy task keys with saved function state: %s', async (hasSavedState) => {+ await insertHogFunctionTemplate(hub.postgres, customerTaskTemplate)+ const config = {+ template_id: customerTaskTemplate.id,+ inputs: { name: { value: 'Follow up' } },+ }+ hogFlow.actions = hogFlow.actions.map((action) =>+ action.id === 'function_id_1' ? { ...action, type: 'function', config } : action+ )+ const invocation = createExampleHogFlowInvocation(hogFlow, {+ actionStepCount: 7,+ rerunAttempts: 2,+ currentAction: { id: 'function_id_1', startedAtTimestamp: Date.now() },+ })+ if (hasSavedState) {+ const hogFunction = await hogFlowFunctionsService.buildHogFunction(hogFlow, config)+ const functionInvocation = await hogFlowFunctionsService.buildHogFunctionInvocation(+ invocation,+ hogFunction,+ { event: invocation.state.event, person: invocation.person }+ )+ invocation.state.currentAction!.hogFunctionState = parseJSON(JSON.stringify(functionInvocation.state))+ }+ const internalFetchSpy = jest.mocked(internalFetch).mockResolvedValue({+ status: 201,+ text: () => Promise.resolve(JSON.stringify({ id: '00000000-0000-4000-8000-000000000000' })),+ } as FetchResponse)+ try {+ const result = await executor.execute(invocation)+ expect(result.error).toBeUndefined()+ expect(result.finished).toBe(true)+ expect(result.invocation.state.customerTaskIdempotencyVersion).toBeUndefined()+ expect(internalFetchSpy).toHaveBeenCalledTimes(1)+ expect(parseJSON(internalFetchSpy.mock.calls[0][1]!.body!.toString()).idempotency_key).toBe(+ `${invocation.id}:function_id_1`+ )+ } finally {+ internalFetchSpy.mockReset()+ }+ })++ it('creates distinct customer task keys when a conditional loop revisits the same action', async () => {+ await insertHogFunctionTemplate(hub.postgres, customerTaskTemplate)+ await insertHogFunctionTemplate(hub.postgres, setVariableTemplate)+ const cyclicFlow = new FixtureHogFlowBuilder()+ .withTeamId(team.id)+ .withWorkflow({+ actions: {+ trigger: { type: 'trigger', config: { type: 'event', filters: {} } },+ customer_task: {+ type: 'function',+ on_error: 'abort',+ config: {+ template_id: customerTaskTemplate.id,+ inputs: { name: { value: 'Follow up' } },+ },+ },+ increment_visits: {+ type: 'function',+ on_error: 'abort',+ config: {+ template_id: setVariableTemplate.id,+ inputs: {+ variable_value: {+ value: '{variables.task_visits + 1}',+ bytecode: await compileHog('return variables.task_visits + 1'),+ },+ },+ },+ output_variable: { key: 'task_visits', result_path: null },+ },+ repeat: {+ type: 'conditional_branch',+ config: {+ conditions: [+ {+ filters: {+ properties: [{ type: 'hogql', key: 'variables.task_visits < 2' }],+ bytecode: await compileHog('return variables.task_visits < 2'),+ },+ },+ ],+ },+ },+ exit: { type: 'exit', config: {} },+ },+ edges: [+ { from: 'trigger', to: 'customer_task', type: 'continue' },+ { from: 'customer_task', to: 'increment_visits', type: 'continue' },+ { from: 'increment_visits', to: 'repeat', type: 'continue' },+ { from: 'repeat', to: 'customer_task', type: 'branch', index: 0 },+ { from: 'repeat', to: 'exit', type: 'continue' },+ ],+ })+ .build()+ const globals = createHogExecutionGlobals({ variables: { task_visits: 0 } })+ const invocation = createHogFlowInvocation(globals, cyclicFlow, convertToHogFunctionFilterGlobal(globals))+ const taskResponse = {+ status: 201,+ text: () => Promise.resolve(JSON.stringify({ id: '00000000-0000-4000-8000-000000000000' })),+ } as FetchResponse+ const internalFetchSpy = jest+ .mocked(internalFetch)+ .mockResolvedValueOnce(taskResponse)+ .mockResolvedValueOnce(taskResponse)+ .mockRejectedValue(new Error('Unexpected task visit'))+ try {+ const result = await executor.execute(invocation)++ expect(result.error).toBeUndefined()+ expect(result.finished).toBe(true)+ expect(result.invocation.state).toMatchObject({+ customerTaskIdempotencyVersion: 1,+ actionStepCount: 6,+ currentAction: { id: 'exit' },+ variables: { task_visits: 2 },+ })+ expect(+ internalFetchSpy.mock.calls.map(([, params]) => parseJSON(params!.body!.toString()).idempotency_key)+ ).toEqual([`${invocation.id}:customer_task:0`, `${invocation.id}:customer_task:3`])+ } finally {+ internalFetchSpy.mockReset()+ }+ })+it('can execute a hogflow with async function delays', async () => {const action = hogFlow.actions.find((action) => action.id === 'function_id_1')!;(action.config as any).template_id = 'template-test-hogflow-executor-async'const invocation = createExampleHogFlowInvocation(hogFlow, {+ customerTaskIdempotencyVersion: 1,event: {...createHogExecutionGlobals().event,properties: {@@ -441,7 +569,13 @@ describe('Hogflow Executor', () => {const result = await executor.execute(invocation)expect(result.finished).toEqual(false)- expect(result.invocation.state.currentAction!.hogFunctionState).toEqual(expect.any(Object))+ expect(result.invocation.state).toMatchObject({+ customerTaskIdempotencyVersion: 1,+ actionStepCount: 0,+ currentAction: {+ hogFunctionState: { customerTaskIdempotencyVersion: 1, actionStepCount: 0 },+ },+ })expect(result.invocation.queueScheduledAt).toEqual(expect.any(DateTime))expect(result.logs.map((log) => log.message)).toMatchInlineSnapshot(`[@@ -456,7 +590,13 @@ describe('Hogflow Executor', () => {const result2 = await executor.execute(result.invocation)expect(result2.finished).toEqual(false)- expect(result2.invocation.state.currentAction!.hogFunctionState).toEqual(expect.any(Object))+ expect(result2.invocation.state).toMatchObject({+ customerTaskIdempotencyVersion: 1,+ actionStepCount: 0,+ currentAction: {+ hogFunctionState: { customerTaskIdempotencyVersion: 1, actionStepCount: 0 },+ },+ })expect(result2.logs.map((log) => log.message)).toMatchInlineSnapshot(`["Resuming workflow execution at [Action:function_id_1] on [Event:uuid|test|2026-01-30T20:20:20.200Z]",@@ -469,6 +609,7 @@ describe('Hogflow Executor', () => {const result3 = await executor.execute(result2.invocation)expect(result3.finished).toEqual(true)+ expect(result3.invocation.state.customerTaskIdempotencyVersion).toBe(1)expect(cleanLogs(result3.logs.map((log) => log.message))).toMatchInlineSnapshot(`["Resuming workflow execution at [Action:function_id_1] on [Event:uuid|test|2026-01-30T20:20:20.200Z]",@@ -2296,6 +2437,7 @@ describe('Hogflow Executor', () => {},}const invocation = createHogFlowInvocation(globals, hogFlow, {} as any)+ expect(invocation.state.customerTaskIdempotencyVersion).toBe(1)expect(invocation.state.variables).toEqual({foo: 'bar',baz: 123,diff --git a/nodejs/src/cdp/services/hogflows/hogflow-executor.service.ts b/nodejs/src/cdp/services/hogflows/hogflow-executor.service.tsindex 34ab46ddb2d8..9f357a71512f 100644--- a/nodejs/src/cdp/services/hogflows/hogflow-executor.service.ts+++ b/nodejs/src/cdp/services/hogflows/hogflow-executor.service.ts@@ -87,6 +87,7 @@ export function createHogFlowInvocation(state: {event: globals.event,actionStepCount: 0,+ customerTaskIdempotencyVersion: 1,variables: mergedVariables,// Seeded at run start and persisted with the state, because the flow itself isn't: the// job is re-loaded by functionId on every resume, so by the time a conversion lands thediff --git a/nodejs/src/cdp/services/hogflows/hogflow-functions.service.ts b/nodejs/src/cdp/services/hogflows/hogflow-functions.service.tsindex ac0d60c52105..f86e71bea706 100644--- a/nodejs/src/cdp/services/hogflows/hogflow-functions.service.ts+++ b/nodejs/src/cdp/services/hogflows/hogflow-functions.service.ts@@ -126,6 +126,7 @@ export class HogFlowFunctionsService {attempts: 0,actionId: invocation.state.currentAction?.id,actionStepCount: invocation.state.actionStepCount,+ customerTaskIdempotencyVersion: invocation.state.customerTaskIdempotencyVersion,rerunAttempts: invocation.state.rerunAttempts,},}diff --git a/nodejs/src/cdp/templates/_destinations/posthog_customer_analytics/posthog-create-customer-task.template.test.ts b/nodejs/src/cdp/templates/_destinations/posthog_customer_analytics/posthog-create-customer-task.template.test.tsnew file mode 100644index 000000000000..60430aef3de6--- /dev/null+++ b/nodejs/src/cdp/templates/_destinations/posthog_customer_analytics/posthog-create-customer-task.template.test.ts@@ -0,0 +1,153 @@+import jwt from 'jsonwebtoken'++import { defaultConfig } from '~/common/config/config'+import { parseJSON } from '~/common/utils/json-parse'+import * as requestModule from '~/common/utils/request'++import { TemplateTester } from '../../test/test-helpers'+import { template } from './posthog-create-customer-task.template'++describe('posthog create customer task template', () => {+ const tester = new TemplateTester(template)+ const workflowOptions = {+ hogFlow: { id: '0198c9f1-0000-0000-0000-000000000001' },+ actionId: 'action_1',+ actionStepCount: 3,+ customerTaskIdempotencyVersion: 1 as const,+ }++ const task = { id: '0198c9f1-0000-0000-0000-000000000003' }+ let fetchSpy: jest.SpyInstance+ const internalResponse = (status: number, body: unknown): requestModule.FetchResponse => ({+ status,+ headers: {},+ text: () => Promise.resolve(typeof body === 'string' ? body : JSON.stringify(body)),+ json: () => Promise.resolve(body),+ dump: async () => {},+ })+ beforeEach(async () => {+ await tester.beforeEach()+ fetchSpy = jest.spyOn(requestModule, 'internalFetch').mockResolvedValue(internalResponse(201, task))+ })+ afterEach(() => jest.restoreAllMocks())++ it.each([+ {+ name: 'Follow up',+ description: 'Arrange an onboarding session',+ account_id: '0198c9f1-0000-0000-0000-000000000002',+ assigned_to_id: '42',+ due_at: '2030-01-15T17:00:00Z',+ },+ { name: 'Follow up', description: '', account_id: '', due_at: '' },+ ])('calls the trusted internal API with task fields and workflow claims: %j', async (inputs) => {+ const response = await tester.invoke(inputs, undefined, workflowOptions)+ expect(response.error).toBeUndefined()+ expect(response.finished).toBe(false)+ const resumed = await tester.resumeInvocation(response.invocation)+ expect(resumed.finished).toBe(true)+ expect(resumed.execResult).toEqual(task)+ expect(response.invocation.queueParameters).toBeUndefined()+ expect(fetchSpy).toHaveBeenCalledTimes(1)+ const [url, params] = fetchSpy.mock.calls[0] as [string, requestModule.FetchOptions]+ expect(params.method).toBe('POST')+ expect(url).toBe(`${defaultConfig.INTERNAL_API_BASE_URL}/api/projects/1/workflow_customer_tasks/`)+ const idempotencyKey = `${response.invocation.id}:action_1:3`+ expect(parseJSON(params.body!.toString())).toEqual({+ ...Object.fromEntries(Object.entries(inputs).filter(([, value]) => value !== '')),+ ...('assigned_to_id' in inputs ? { assigned_to_id: Number(inputs.assigned_to_id) } : {}),+ idempotency_key: idempotencyKey,+ })+ const claims = jwt.verify(+ new Headers(params.headers as Record<string, string>).get('authorization')!.replace('Bearer ', ''),+ defaultConfig.CUSTOMER_ANALYTICS_ACCOUNTS_JWT_SECRET,+ {+ audience: 'posthog:customer-tasks:create',+ algorithms: ['HS256'],+ }+ ) as jwt.JwtPayload+ expect(claims).toMatchObject({+ team_id: 1,+ hog_flow_id: workflowOptions.hogFlow.id,+ idempotency_key: idempotencyKey,+ })+ expect(claims.exp! - claims.iat!).toBe(5 * 60)+ })++ it('keeps a visit key across resume and retry but changes it on a repeated visit', async () => {+ const first = await tester.invoke({ name: 'Follow up' }, undefined, workflowOptions)+ expect(first.error).toBeUndefined()+ const persistedState = parseJSON(JSON.stringify(first.invocation.state))+ const resumed = await tester.resumeInvocation({ ...first.invocation, state: persistedState })+ expect(resumed.error).toBeUndefined()+ expect(resumed.execResult).toEqual(task)+ expect(resumed.invocation.state).toMatchObject({+ actionStepCount: 3,+ customerTaskIdempotencyVersion: 1,+ })+ expect(fetchSpy).toHaveBeenCalledTimes(1)++ const retry = await tester.resumeInvocation({+ ...first.invocation,+ state: { ...persistedState, vmState: undefined, attempts: 1, rerunAttempts: 2 },+ })+ expect(retry.error).toBeUndefined()+ const revisit = await tester.resumeInvocation({+ ...first.invocation,+ state: { ...persistedState, vmState: undefined, actionStepCount: 4 },+ })+ expect(revisit.error).toBeUndefined()++ expect(fetchSpy.mock.calls.map(([, params]) => parseJSON(params.body).idempotency_key)).toEqual([+ `${first.invocation.id}:action_1:3`,+ `${first.invocation.id}:action_1:3`,+ `${first.invocation.id}:action_1:4`,+ ])+ })++ it.each(['', ' '])('rejects a blank task name %j without creating a task', async (name) => {+ const response = await tester.invoke({ name }, undefined, workflowOptions)+ expect(response.error).toMatch(/Enter a task name/)+ expect(response.invocation.queueParameters).toBeUndefined()+ })++ it('rejects a fractional assignee ID without creating a task', async () => {+ const response = await tester.invoke({ name: 'Follow up', assigned_to_id: 1.5 }, undefined, workflowOptions)+ expect(response.error).toMatch(/valid numeric assignee user ID/)+ expect(response.invocation.queueParameters).toBeUndefined()+ })++ it('rejects invocation outside a workflow', async () => {+ const response = await tester.invoke({ name: 'Follow up' })+ expect(response.error).toMatch(/inside a workflow/)+ expect(response.invocation.queueParameters).toBeUndefined()+ })++ it.each([200, 201])('returns the task after a %i response', async (status) => {+ fetchSpy.mockResolvedValue(internalResponse(status, task))+ const invocation = await tester.invoke({ name: 'Follow up' }, undefined, workflowOptions)+ const response = await tester.resumeInvocation(invocation.invocation)+ expect(response.error).toBeUndefined()+ expect(response.execResult).toEqual(task)+ })++ it('reports backend validation errors', async () => {+ fetchSpy.mockResolvedValue(internalResponse(400, { detail: 'Assignee must be a project member' }))+ const invocation = await tester.invoke({ name: 'Follow up' }, undefined, workflowOptions)+ const response = await tester.resumeInvocation(invocation.invocation)+ expect(response.error).toEqual('Failed to create customer task (400): Assignee must be a project member')+ })++ it.each([+ [303, ''],+ [200, ''],+ [201, { status: 303, body: '' }],+ [201, { id: 'not-a-task-id' }],+ ])('rejects a redirect or malformed success (%i, %j)', async (status, body) => {+ fetchSpy.mockResolvedValue(internalResponse(status, body))+ const invocation = await tester.invoke({ name: 'Follow up' }, undefined, workflowOptions)+ const response = await tester.resumeInvocation(invocation.invocation)+ expect(response.error).toMatch(/Failed to create customer task/)+ expect(response.execResult).toBeUndefined()+ })+})diff --git a/nodejs/src/cdp/templates/_destinations/posthog_customer_analytics/posthog-create-customer-task.template.ts b/nodejs/src/cdp/templates/_destinations/posthog_customer_analytics/posthog-create-customer-task.template.tsnew file mode 100644index 000000000000..735c0374f17e--- /dev/null+++ b/nodejs/src/cdp/templates/_destinations/posthog_customer_analytics/posthog-create-customer-task.template.ts@@ -0,0 +1,87 @@+import { HogFunctionTemplate } from '~/cdp/types'++import { hogApiErrorMessageFn } from '../../hog-helpers'++export const template: HogFunctionTemplate = {+ free: true,+ status: 'hidden',+ type: 'destination',+ id: 'template-posthog-create-customer-task',+ name: 'Create customer task',+ description:+ 'Create a Customer analytics task with an optional account, assignee, and due date. All fields support workflow variables.',+ icon_url: '/static/posthog-icon.svg',+ category: ['Custom'],+ code_language: 'hog',+ code: `+${hogApiErrorMessageFn}++if (empty(inputs.name)) {+ throw Error('Enter a task name')+}+let payload := { 'name': inputs.name }+if (not empty(inputs.description)) {+ payload.description := inputs.description+}+if (not empty(inputs.account_id)) {+ payload.account_id := inputs.account_id+}+if (not empty(inputs.assigned_to_id)) {+ payload.assigned_to_id := inputs.assigned_to_id+}+if (not empty(inputs.due_at)) {+ payload.due_at := inputs.due_at+}+let response := postHogCreateCustomerTask(payload)+if (response.status < 200 or response.status >= 300) {+ throw Error(f'Failed to create customer task ({response.status}): {apiErrorMessage(response)}')+}+if (typeof(response.body) != 'object' or typeof(response.body.id) != 'string' or not match(response.body.id, '^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$')) {+ throw Error('Failed to create customer task: the server did not return a task ID')+}+return response.body+`,+ inputs_schema: [+ {+ key: 'name',+ type: 'string',+ label: 'Task name',+ secret: false,+ required: true,+ description: 'What needs to be done.',+ },+ {+ key: 'description',+ type: 'string',+ label: 'Description',+ secret: false,+ required: false,+ description: 'Additional details for the person completing the task.',+ },+ {+ key: 'account_id',+ type: 'string',+ label: 'Account',+ secret: false,+ required: false,+ description:+ 'The account UUID from a Get account or Create account step. Leave empty for no linked account.',+ },+ {+ key: 'assigned_to_id',+ type: 'string',+ label: 'Assignee',+ secret: false,+ required: false,+ description: 'The numeric ID of a project member. Leave empty to create an unassigned task.',+ },+ {+ key: 'due_at',+ type: 'string',+ label: 'Due date',+ secret: false,+ required: false,+ description: 'A date and time with a timezone, such as 2030-01-15T17:00:00Z.',+ },+ ],+}diff --git a/nodejs/src/cdp/templates/index.ts b/nodejs/src/cdp/templates/index.tsindex 7bd3dbdd30cf..167c8c8bd161 100644--- a/nodejs/src/cdp/templates/index.ts+++ b/nodejs/src/cdp/templates/index.ts@@ -26,6 +26,7 @@ import { template as posthogUpdatePersonPropertiesTemplate } from './_destinatioimport { template as posthogGetTicketTemplate } from './_destinations/posthog_conversations/posthog-get-ticket.template'import { template as posthogUpdateTicketTemplate } from './_destinations/posthog_conversations/posthog-update-ticket.template'import { template as posthogCreateAccountTemplate } from './_destinations/posthog_customer_analytics/posthog-create-account.template'+import { template as posthogCreateCustomerTaskTemplate } from './_destinations/posthog_customer_analytics/posthog-create-customer-task.template'import { template as posthogGetAccountTemplate } from './_destinations/posthog_customer_analytics/posthog-get-account.template'import { template as posthogTagAccountTemplate } from './_destinations/posthog_customer_analytics/posthog-tag-account.template'import { template as posthogUpdateAccountPropertyTemplate } from './_destinations/posthog_customer_analytics/posthog-update-account-property.template'@@ -103,6 +104,7 @@ export const HOG_FUNCTION_TEMPLATES_DESTINATIONS: HogFunctionTemplate[] = [posthogCreateTaskTemplate,posthogRunScoutTemplate,posthogCreateAccountTemplate,+ posthogCreateCustomerTaskTemplate,posthogGetAccountTemplate,posthogTagAccountTemplate,posthogUpdateAccountRelationshipsTemplate,diff --git a/nodejs/src/cdp/templates/test/test-helpers.ts b/nodejs/src/cdp/templates/test/test-helpers.tsindex 65a3c76cf2b3..756fc83e6bff 100644--- a/nodejs/src/cdp/templates/test/test-helpers.ts+++ b/nodejs/src/cdp/templates/test/test-helpers.ts@@ -283,7 +283,12 @@ export class TemplateTester {async invoke(_inputs: Record<string, any>,_globals?: DeepPartialHogFunctionInvocationGlobals,- _options?: { hogFlow?: Partial<HogFlow> & { id: string }; actionId?: string }+ _options?: {+ hogFlow?: Partial<HogFlow> & { id: string }+ actionId?: string+ actionStepCount?: number+ customerTaskIdempotencyVersion?: 1+ }): Promise<CyclotronJobInvocationResult<CyclotronJobInvocationHogFunction>> {if (this.template.mapping_templates) {throw new Error('Mapping templates found. Use invokeMapping instead.')@@ -317,7 +322,8 @@ export class TemplateTester {}if (_options?.actionId) {invocation.state.actionId = _options.actionId- invocation.state.actionStepCount = 0+ invocation.state.actionStepCount = _options.actionStepCount ?? 0+ invocation.state.customerTaskIdempotencyVersion = _options.customerTaskIdempotencyVersion}const transformationFunctions = getTransformationFunctions(this.geoIp!)const extraFunctions = invocation.hogFunction.type === 'transformation' ? transformationFunctions : {}@@ -396,6 +402,12 @@ export class TemplateTester {return this.getExecutor().execute(invocation)}+ async resumeInvocation(+ invocation: CyclotronJobInvocationHogFunction+ ): Promise<CyclotronJobInvocationResult<CyclotronJobInvocationHogFunction>> {+ return this.hogExecutor.execute(invocation)+ }+async invokeFetchResponse(invocation: CyclotronJobInvocationHogFunction,response: { status: number; body: unknown }diff --git a/nodejs/src/cdp/types.ts b/nodejs/src/cdp/types.tsindex b4e5343663ce..b58bb38d4d26 100644--- a/nodejs/src/cdp/types.ts+++ b/nodejs/src/cdp/types.ts@@ -384,6 +384,7 @@ export type CyclotronJobInvocationHogFunctionContext = {firstScheduledAt?: stringactionId?: string // The hogflow action node ID, used for metrics instance_id when executing within a workflowactionStepCount?: number+ customerTaskIdempotencyVersion?: 1}export type WorkflowStepResumeStatus = 'completed' | 'failed' | 'cancelled'@@ -431,6 +432,8 @@ export type HogFlowInvocationContext = {// rather than to a wrong one.flowVersion?: numberactionStepCount: number+ // Missing on legacy runs, which must keep run:action keys even when no function state was persisted.+ customerTaskIdempotencyVersion?: 1currentAction?: {id: stringstartedAtTimestamp: numberdiff --git a/nodejs/src/cdp/utils/jwt-utils.ts b/nodejs/src/cdp/utils/jwt-utils.tsindex 3eea15d6d617..48ee6d2aa6b1 100644--- a/nodejs/src/cdp/utils/jwt-utils.ts+++ b/nodejs/src/cdp/utils/jwt-utils.ts@@ -6,6 +6,7 @@ export enum PosthogJwtAudience {WORKFLOWS_RESCHEDULE_PARKED = 'posthog:workflows:reschedule_parked',WORKFLOWS_CANCEL_INVOCATIONS = 'posthog:workflows:cancel_invocations',WORKFLOWS_CANCEL_BATCH = 'posthog:workflows:cancel_batch',+ CUSTOMER_TASKS_CREATE = 'posthog:customer-tasks:create',TASKS_CREATE = 'posthog:tasks:create',WORKFLOW_SCOUT_RUN = 'posthog:workflows:scout_run',// Must match PosthogJwtAudience.CONVERSATIONS_TICKETS in posthog/jwt.py exactly.diff --git a/nodejs/tests/fixtures/hog-bytecode/06708e0c91851bc589bdeb8f324bddf446e23aa3a8483d6d1a2ebb770705e6ec.json b/nodejs/tests/fixtures/hog-bytecode/06708e0c91851bc589bdeb8f324bddf446e23aa3a8483d6d1a2ebb770705e6ec.jsonnew file mode 100644index 000000000000..3c618cfe5849--- /dev/null+++ b/nodejs/tests/fixtures/hog-bytecode/06708e0c91851bc589bdeb8f324bddf446e23aa3a8483d6d1a2ebb770705e6ec.json@@ -0,0 +1 @@+["_H",1,32,"42",38]diff --git a/nodejs/tests/fixtures/hog-bytecode/25a068b0c5f3e0fc261c9eecf8343cc01e2072f05a2ecf0a61c8605e9b5f628d.json b/nodejs/tests/fixtures/hog-bytecode/25a068b0c5f3e0fc261c9eecf8343cc01e2072f05a2ecf0a61c8605e9b5f628d.jsonnew file mode 100644index 000000000000..45309ad0a6bc--- /dev/null+++ b/nodejs/tests/fixtures/hog-bytecode/25a068b0c5f3e0fc261c9eecf8343cc01e2072f05a2ecf0a61c8605e9b5f628d.json@@ -0,0 +1 @@+["_H",1,32,"variable_value",32,"inputs",1,2,38]diff --git a/nodejs/tests/fixtures/hog-bytecode/472073ce68c0a5e8ae542002ece54a32df849c4c3a023b91441e1d1e50709886.json b/nodejs/tests/fixtures/hog-bytecode/472073ce68c0a5e8ae542002ece54a32df849c4c3a023b91441e1d1e50709886.jsonnew file mode 100644index 000000000000..3aee524a9924--- /dev/null+++ b/nodejs/tests/fixtures/hog-bytecode/472073ce68c0a5e8ae542002ece54a32df849c4c3a023b91441e1d1e50709886.json@@ -0,0 +1 @@+["_H",1,33,2,32,"task_visits",32,"variables",1,2,15,38]diff --git a/nodejs/tests/fixtures/hog-bytecode/57c3164ab42b11137f4052defd5590be44d5a78063e985b6c2fbeffc678b9f5b.json b/nodejs/tests/fixtures/hog-bytecode/57c3164ab42b11137f4052defd5590be44d5a78063e985b6c2fbeffc678b9f5b.jsonnew file mode 100644index 000000000000..aedfe8b72591--- /dev/null+++ b/nodejs/tests/fixtures/hog-bytecode/57c3164ab42b11137f4052defd5590be44d5a78063e985b6c2fbeffc678b9f5b.json@@ -0,0 +1 @@+["_H",1,33,1,32,"task_visits",32,"variables",1,2,6,38]diff --git a/nodejs/tests/fixtures/hog-bytecode/7f57d7afe90a9862f00dc39669297321123c459ff12c50ddc096e90892125e0d.json b/nodejs/tests/fixtures/hog-bytecode/7f57d7afe90a9862f00dc39669297321123c459ff12c50ddc096e90892125e0d.jsonnew file mode 100644index 000000000000..257b89f75120--- /dev/null+++ b/nodejs/tests/fixtures/hog-bytecode/7f57d7afe90a9862f00dc39669297321123c459ff12c50ddc096e90892125e0d.json@@ -0,0 +1 @@+["_H",1,32,"0198c9f1-0000-0000-0000-000000000002",38]diff --git a/nodejs/tests/fixtures/hog-bytecode/8ba01609b892dbe9bc40b8b99911ac0efc344621740f0247f75cbd150603fd3e.json b/nodejs/tests/fixtures/hog-bytecode/8ba01609b892dbe9bc40b8b99911ac0efc344621740f0247f75cbd150603fd3e.jsonnew file mode 100644index 000000000000..f179b8796d4b--- /dev/null+++ b/nodejs/tests/fixtures/hog-bytecode/8ba01609b892dbe9bc40b8b99911ac0efc344621740f0247f75cbd150603fd3e.json@@ -0,0 +1 @@+["_H",1,32," ",38]diff --git a/nodejs/tests/fixtures/hog-bytecode/b44e727065d2ee09bed198693e1d42b5a094b0c45634b06b52ef0b4c82096407.json b/nodejs/tests/fixtures/hog-bytecode/b44e727065d2ee09bed198693e1d42b5a094b0c45634b06b52ef0b4c82096407.jsonnew file mode 100644index 000000000000..e45c1e6d8f6f--- /dev/null+++ b/nodejs/tests/fixtures/hog-bytecode/b44e727065d2ee09bed198693e1d42b5a094b0c45634b06b52ef0b4c82096407.json@@ -0,0 +1 @@+["_H",1,32,"2030-01-15T17:00:00Z",38]diff --git a/nodejs/tests/fixtures/hog-bytecode/b6977d3da9487680b07e214f5dd9bdd4841423a7484ef97e679309f36c8c9e66.json b/nodejs/tests/fixtures/hog-bytecode/b6977d3da9487680b07e214f5dd9bdd4841423a7484ef97e679309f36c8c9e66.jsonnew file mode 100644index 000000000000..d047614d1060--- /dev/null+++ b/nodejs/tests/fixtures/hog-bytecode/b6977d3da9487680b07e214f5dd9bdd4841423a7484ef97e679309f36c8c9e66.json@@ -0,0 +1 @@+["_H",1,32,"Follow up",38]diff --git a/nodejs/tests/fixtures/hog-bytecode/eacf4397fed38b5152d27a6c4fb9ecac7b8f3e12c98982bd14ae168a1fe23980.json b/nodejs/tests/fixtures/hog-bytecode/eacf4397fed38b5152d27a6c4fb9ecac7b8f3e12c98982bd14ae168a1fe23980.jsonnew file mode 100644index 000000000000..7a57bd81cfa0--- /dev/null+++ b/nodejs/tests/fixtures/hog-bytecode/eacf4397fed38b5152d27a6c4fb9ecac7b8f3e12c98982bd14ae168a1fe23980.json@@ -0,0 +1 @@+["_H",1,52,"apiErrorMessage",1,0,28,36,0,32,"body",45,32,"error",45,47,9,35,36,0,32,"body",45,32,"detail",45,47,6,35,36,0,32,"body",45,38,53,0,32,"name",32,"inputs",1,2,2,"empty",1,40,6,32,"Enter a task name",2,"Error",1,49,32,"name",32,"name",32,"inputs",1,2,42,1,32,"description",32,"inputs",1,2,2,"empty",1,5,40,11,36,1,32,"description",32,"description",32,"inputs",1,2,46,32,"account_id",32,"inputs",1,2,2,"empty",1,5,40,11,36,1,32,"account_id",32,"account_id",32,"inputs",1,2,46,32,"assigned_to_id",32,"inputs",1,2,2,"empty",1,5,40,11,36,1,32,"assigned_to_id",32,"assigned_to_id",32,"inputs",1,2,46,32,"due_at",32,"inputs",1,2,2,"empty",1,5,40,11,36,1,32,"due_at",32,"due_at",32,"inputs",1,2,46,36,1,2,"postHogCreateCustomerTask",1,33,200,36,2,32,"status",45,15,33,300,36,2,32,"status",45,14,4,2,40,22,32,"Failed to create customer task (",36,2,32,"status",45,32,"): ",36,2,36,0,54,1,2,"concat",4,2,"Error",1,49,32,"object",36,2,32,"body",45,2,"typeof",1,12,32,"string",36,2,32,"body",45,32,"id",45,2,"typeof",1,12,36,2,32,"body",45,32,"id",45,32,"^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$",2,"match",2,5,4,3,40,6,32,"Failed to create customer task: the server did not return a task ID",2,"Error",1,49,36,2,32,"body",45,38,35,35,35]diff --git a/nodejs/tests/fixtures/hog-bytecode/f03e9303d67b69613853d1823c9227e8c572e8bcaf527a6b3c81d2948c449382.json b/nodejs/tests/fixtures/hog-bytecode/f03e9303d67b69613853d1823c9227e8c572e8bcaf527a6b3c81d2948c449382.jsonnew file mode 100644index 000000000000..61c656b323c6--- /dev/null+++ b/nodejs/tests/fixtures/hog-bytecode/f03e9303d67b69613853d1823c9227e8c572e8bcaf527a6b3c81d2948c449382.json@@ -0,0 +1 @@+["_H",1,52,"apiErrorMessage",1,0,28,36,0,32,"body",45,32,"error",45,47,9,35,36,0,32,"body",45,32,"detail",45,47,6,35,36,0,32,"body",45,38,53,0,32,"name",32,"inputs",1,2,2,"empty",1,40,6,32,"Enter a task name",2,"Error",1,49,32,"name",32,"name",32,"inputs",1,2,42,1,32,"description",32,"inputs",1,2,2,"empty",1,5,40,11,36,1,32,"description",32,"description",32,"inputs",1,2,46,32,"account_id",32,"inputs",1,2,2,"empty",1,5,40,11,36,1,32,"account_id",32,"account_id",32,"inputs",1,2,46,32,"assigned_to_id",32,"inputs",1,2,2,"empty",1,5,40,11,36,1,32,"assigned_to_id",32,"assigned_to_id",32,"inputs",1,2,46,32,"due_at",32,"inputs",1,2,2,"empty",1,5,40,11,36,1,32,"due_at",32,"due_at",32,"inputs",1,2,46,36,1,2,"postHogCreateCustomerTask",1,33,400,36,2,32,"status",45,14,40,22,32,"Failed to create customer task (",36,2,32,"status",45,32,"): ",36,2,36,0,54,1,2,"concat",4,2,"Error",1,49,36,2,32,"body",45,38,35,35,35]diff --git a/nodejs/tests/fixtures/hog-bytecode/f4c8f74da2e7371e8bea969219c20e99df4f59647009b19811c306a689bafa04.json b/nodejs/tests/fixtures/hog-bytecode/f4c8f74da2e7371e8bea969219c20e99df4f59647009b19811c306a689bafa04.jsonnew file mode 100644index 000000000000..5dfb865cf68c--- /dev/null+++ b/nodejs/tests/fixtures/hog-bytecode/f4c8f74da2e7371e8bea969219c20e99df4f59647009b19811c306a689bafa04.json@@ -0,0 +1 @@+["_H",1,32,"Arrange an onboarding session",38]diff --git a/posthog/jwt.py b/posthog/jwt.pyindex a648250d447f..fa737ceaa4a4 100644--- a/posthog/jwt.py+++ b/posthog/jwt.py@@ -26,6 +26,7 @@ class PosthogJwtAudience(Enum):WORKFLOWS_CANCEL_BATCH = "posthog:workflows:cancel_batch"INTEGRATION_SERVICE = "posthog:integration_service"TASKS_CREATE = "posthog:tasks:create"+ CUSTOMER_TASKS_CREATE = "posthog:customer-tasks:create"WORKFLOW_SCOUT_RUN = "posthog:workflows:scout_run"CONVERSATIONS_TICKETS = "posthog:conversations:tickets"CUSTOMER_ANALYTICS_ACCOUNTS = "posthog:customer_analytics:accounts"diff --git a/posthog/settings/data_stores.py b/posthog/settings/data_stores.pyindex 862bf6b01fe5..09617a4ec49a 100644--- a/posthog/settings/data_stores.py+++ b/posthog/settings/data_stores.py@@ -609,11 +609,11 @@ CONVERSATIONS_TICKETS_JWT_SECRETS = get_list(get_from_env("CONVERSATIONS_TICKETS_JWT_SECRET", "local-dev-conversations-tickets-jwt" if DEBUG or TEST else ""))-# Verifies the scoped JWTs the CDP worker's customer analytics account actions send to the-# internal account routes (the worker mints, Django verifies;-# products/customer_analytics/backend/presentation/views/internal.py). Comma-separated,-# newest first. Empty outside dev/test, so the internal routes reject every request until-# the secret is provisioned and the worker stays on its legacy auth path (#82564).+# Account actions and customer task creation share these keys but require distinct JWT audiences.+# The worker mints, Django verifies. Comma-separated, newest first. Empty outside dev/test,+# so scoped routes fail closed until provisioned. Account actions retain their legacy auth+# fallback (#82564). Customer task creation has no fallback.+# The dev/test value must match the worker's default (nodejs/src/cdp/config.ts).CUSTOMER_ANALYTICS_ACCOUNTS_JWT_SECRETS = get_list(get_from_env("CUSTOMER_ANALYTICS_ACCOUNTS_JWT_SECRET", "local-dev-customer-analytics-accounts-jwt" if DEBUG or TEST else ""diff --git a/products/customer_analytics/backend/COMPROMISES.md b/products/customer_analytics/backend/COMPROMISES.mdindex f580aedc2998..fe4b9ffb2f86 100644--- a/products/customer_analytics/backend/COMPROMISES.md+++ b/products/customer_analytics/backend/COMPROMISES.md@@ -139,6 +139,16 @@ once the command has run everywhere.(same call `get_bot_user_id_cached` already caches a field from), so the fix is a cached lookupin conversations exposed through its facade, consumed here and by the frontend.+## Workflow task signing key++- **Account actions and task creation share a signing key.** Both use `CUSTOMER_ANALYTICS_ACCOUNTS_JWT_SECRET` to avoid provisioning another key for workflow task creation.+ Task tokens retain the `posthog:customer-tasks:create` audience and project, workflow, and invocation claims.+ Account tokens cannot call the task endpoint, and task creation still checks the workflow owner's permissions.+- **Key access and rotation are shared.** A service with the signing key can mint tokens for either audience.+ A key compromise therefore affects both surfaces, and rotating the key affects both.+ Use a dedicated task signing key when these surfaces need separate service access or independent rotation.+- **Task creation has no legacy fallback.** If the shared key is unset, task creation fails even when account actions work through the project secret API token.+## Tech debt- **Account property writes have no single choke point.** `Account._properties` is mutated fromdiff --git a/products/customer_analytics/backend/facade/workflow_customer_tasks.py b/products/customer_analytics/backend/facade/workflow_customer_tasks.pynew file mode 100644index 000000000000..e4107f083dd6--- /dev/null+++ b/products/customer_analytics/backend/facade/workflow_customer_tasks.py@@ -0,0 +1,104 @@+from uuid import NAMESPACE_URL, UUID, uuid5++from django.db import connection, transaction++from posthog.models import Team, User+from posthog.models.team.team import DEPRECATED_ATTRS+from posthog.permissions import posthog_feature_flag_enabled++from products.access_control.backend.facade.user_access_control import UserAccessControl+from products.customer_analytics.backend.facade.constants import CUSTOMER_ANALYTICS_CUSTOMER_TASKS_FLAG+from products.customer_analytics.backend.facade.contracts import CreateCustomerTaskInput, CustomerTaskAccessDenied+from products.customer_analytics.backend.logic.customer_tasks import create_customer_task+from products.customer_analytics.backend.models import CustomerTask+from products.workflows.backend.facade.api import get_workflow_owner_id+++class WorkflowCustomerTaskOwnerInactive(Exception):+ pass+++class WorkflowCustomerTaskProjectAccessDenied(Exception):+ pass+++class WorkflowCustomerTasksDisabled(Exception):+ pass+++def _get_task_id(team_id: int, workflow_id: UUID, idempotency_key: str) -> UUID:+ return uuid5(NAMESPACE_URL, f"posthog:customer-task:{team_id}:{workflow_id}:{idempotency_key}")+++def get_workflow_customer_task_id(*, team_id: int, workflow_id: UUID, idempotency_key: str) -> UUID | None:+ task_id = _get_task_id(team_id, workflow_id, idempotency_key)+ return task_id if CustomerTask.objects.for_team(team_id).filter(id=task_id).exists() else None+++def create_workflow_customer_task(+ *,+ team: Team,+ workflow_id: UUID,+ idempotency_key: str,+ input: CreateCustomerTaskInput,+ actor: User,+ user_access_control: UserAccessControl,+) -> UUID:+ task_id = _get_task_id(team.id, workflow_id, idempotency_key)+ with transaction.atomic():+ # Lock the invocation even before its task exists, so concurrent retries create one activity and assignment.+ with connection.cursor() as cursor:+ cursor.execute("SELECT pg_advisory_xact_lock(%s, hashtext(%s))", [team.id, str(task_id)])+ if CustomerTask.objects.for_team(team.id).filter(id=task_id).exists():+ return task_id+ if not user_access_control.has_project_access or not user_access_control.check_access_level_for_resource(+ "customer_task", "editor"+ ):+ raise CustomerTaskAccessDenied()+ task = create_customer_task(+ team=team, input=input, actor=actor, user_access_control=user_access_control, task_id=task_id+ )+ return task.id+++def create_customer_task_from_workflow(+ *, team_id: int, workflow_id: UUID, idempotency_key: str, input: CreateCustomerTaskInput+) -> UUID:+ # `select_related` builds its columns from the related model rather than through `TeamManager`,+ # so re-apply its defer to the joined parent. Without it every task creation in a child+ # environment re-reads the deprecated taxonomy columns, which TOAST out to megabytes per team.+ team = (+ Team.objects.select_related("parent_team")+ .defer(*(f"parent_team__{attr}" for attr in DEPRECATED_ATTRS))+ .get(id=team_id)+ )+ canonical_team = team.parent_team or team+ # A verified retry acknowledges a committed task without granting access to its contents.+ existing_task_id = get_workflow_customer_task_id(+ team_id=canonical_team.id, workflow_id=workflow_id, idempotency_key=idempotency_key+ )+ if existing_task_id is not None:+ return existing_task_id+ owner_id = get_workflow_owner_id(team_id=team_id, workflow_id=workflow_id)+ owner = User.objects.filter(id=owner_id).first()+ if owner is None or not owner.is_active:+ raise WorkflowCustomerTaskOwnerInactive()+ access = UserAccessControl(user=owner, team=team, organization_id=team.organization_id)+ if not access.has_project_access:+ raise WorkflowCustomerTaskProjectAccessDenied()+ if not posthog_feature_flag_enabled(+ CUSTOMER_ANALYTICS_CUSTOMER_TASKS_FLAG,+ str(owner.distinct_id),+ organization_id=team.organization_id,+ team_id=team.id,+ ):+ raise WorkflowCustomerTasksDisabled()+ canonical_access = UserAccessControl(user=owner, team=canonical_team, organization_id=team.organization_id)+ return create_workflow_customer_task(+ team=canonical_team,+ workflow_id=workflow_id,+ idempotency_key=idempotency_key,+ input=input,+ actor=owner,+ user_access_control=canonical_access,+ )diff --git a/products/customer_analytics/backend/logic/customer_tasks.py b/products/customer_analytics/backend/logic/customer_tasks.pyindex a66ea22739ff..fb4e12cd7c43 100644--- a/products/customer_analytics/backend/logic/customer_tasks.py+++ b/products/customer_analytics/backend/logic/customer_tasks.py@@ -332,6 +332,7 @@ def create_customer_task(input: contracts.CreateCustomerTaskInput,actor: User | None,user_access_control: UserAccessControl,+ task_id: UUID | None = None,) -> CustomerTask:account = _account_for_write(team.id, input.account_id, user_access_control)assignee = _validate_assignee(team=team, account=account, assignee_id=input.assigned_to_id)@@ -339,6 +340,7 @@ def create_customer_task(completed_by = actor if completed_at is not None and actor is not None else assignee if completed_at else Nonewith transaction.atomic():task = CustomerTask.objects.for_team(team.id).create(+ **({"id": task_id} if task_id is not None else {}),team_id=team.id,account=account,name=input.name,diff --git a/products/customer_analytics/backend/presentation/views/workflow_customer_tasks.py b/products/customer_analytics/backend/presentation/views/workflow_customer_tasks.pynew file mode 100644index 000000000000..e1ac7e17ce2a--- /dev/null+++ b/products/customer_analytics/backend/presentation/views/workflow_customer_tasks.py@@ -0,0 +1,109 @@+from typing import Any, cast+from uuid import UUID++from drf_spectacular.utils import extend_schema+from rest_framework import serializers, status, viewsets+from rest_framework.exceptions import AuthenticationFailed, NotFound, PermissionDenied, ValidationError+from rest_framework.permissions import IsAuthenticated+from rest_framework.request import Request+from rest_framework.response import Response++from posthog.auth import InternalAPIUser, ScopedServiceJWTAuthentication+from posthog.jwt import PosthogJwtAudience+from posthog.scoped_service_jwt import ScopedServiceJwtPurpose++from products.customer_analytics.backend.facade import contracts+from products.customer_analytics.backend.facade.workflow_customer_tasks import (+ WorkflowCustomerTaskOwnerInactive,+ WorkflowCustomerTaskProjectAccessDenied,+ WorkflowCustomerTasksDisabled,+ create_customer_task_from_workflow,+)+from products.workflows.backend.facade.api import WorkflowNotFound+++class WorkflowCustomerTasksJWTAuthentication(ScopedServiceJWTAuthentication):+ purpose = ScopedServiceJwtPurpose(+ audience=PosthogJwtAudience.CUSTOMER_TASKS_CREATE,+ settings_name="CUSTOMER_ANALYTICS_ACCOUNTS_JWT_SECRETS",+ )+++class WorkflowCustomerTaskCreateSerializer(serializers.Serializer):+ name = serializers.CharField(max_length=400, help_text="Task name.")+ description = serializers.CharField(+ required=False, allow_blank=True, allow_null=True, help_text="Task description."+ )+ account_id = serializers.UUIDField(required=False, allow_null=True, help_text="UUID of the linked account.")+ assigned_to_id = serializers.IntegerField(+ required=False,+ allow_null=True,+ min_value=1,+ max_value=2147483647,+ help_text="PostHog user ID of the assigned project member.",+ )+ due_at = serializers.DateTimeField(required=False, allow_null=True, help_text="ISO 8601 task deadline.")+ idempotency_key = serializers.CharField(+ max_length=128, help_text="Invocation and action key from the workflow worker."+ )++ def validate(self, attrs: dict[str, Any]) -> dict[str, Any]:+ unexpected = set(self.initial_data) - set(self.fields)+ if unexpected:+ raise serializers.ValidationError(dict.fromkeys(unexpected, "This field is not accepted."))+ return attrs+++class WorkflowCustomerTaskResponseSerializer(serializers.Serializer):+ id = serializers.UUIDField(read_only=True, help_text="UUID of the created or previously created customer task.")+++class WorkflowCustomerTaskViewSet(viewsets.GenericViewSet):+ authentication_classes = [WorkflowCustomerTasksJWTAuthentication]+ permission_classes = [IsAuthenticated]+ serializer_class = WorkflowCustomerTaskCreateSerializer++ @extend_schema(+ request=WorkflowCustomerTaskCreateSerializer,+ responses={201: WorkflowCustomerTaskResponseSerializer},+ extensions={"x-product": "workflows"},+ )+ def create(self, request: Request, **kwargs: Any) -> Response:+ serializer = WorkflowCustomerTaskCreateSerializer(data=request.data)+ serializer.is_valid(raise_exception=True)+ data = dict(serializer.validated_data)+ idempotency_key = data.pop("idempotency_key")+ claims = cast(dict[str, Any], request.auth)+ if claims.get("idempotency_key") != idempotency_key:+ raise AuthenticationFailed("Service token does not grant access to this invocation.")+ try:+ workflow_id = UUID(str(claims.get("hog_flow_id")))+ except ValueError:+ raise AuthenticationFailed("Service token is missing its workflow claim.") from None+ team_id = cast(int, cast(InternalAPIUser, request.user).current_team_id)+ try:+ task_id = create_customer_task_from_workflow(+ team_id=team_id,+ workflow_id=workflow_id,+ idempotency_key=idempotency_key,+ input=contracts.CreateCustomerTaskInput(**data),+ )+ except WorkflowNotFound:+ raise NotFound("Workflow not found.") from None+ except WorkflowCustomerTaskOwnerInactive:+ raise PermissionDenied("Choose an active workflow owner before creating customer tasks.") from None+ except WorkflowCustomerTaskProjectAccessDenied:+ raise PermissionDenied("The workflow owner no longer has access to this project.") from None+ except WorkflowCustomerTasksDisabled:+ raise PermissionDenied("Enable customer tasks before using this workflow action.") from None+ except contracts.CustomerTaskAccessDenied:+ raise PermissionDenied(+ "The workflow owner needs editor access to customer tasks in the canonical project."+ ) from None+ except contracts.CustomerTaskAccountNotFound:+ raise NotFound("Account not found.") from None+ except (contracts.CustomerTaskAssigneeInvalid, contracts.CustomerTaskAssigneeCannotViewAccount):+ raise ValidationError(+ {"assigned_to_id": "Choose a project member who can access the linked account."}+ ) from None+ return Response(WorkflowCustomerTaskResponseSerializer({"id": task_id}).data, status=status.HTTP_201_CREATED)diff --git a/products/customer_analytics/backend/routes.py b/products/customer_analytics/backend/routes.pyindex 9c1142ac38f9..7a078c01e8d5 100644--- a/products/customer_analytics/backend/routes.py+++ b/products/customer_analytics/backend/routes.py@@ -24,6 +24,7 @@ from products.customer_analytics.backend.presentation.views.views import (FeatureRequestViewSet,UserCustomerAnalyticsConfigViewSet,)+from products.customer_analytics.backend.presentation.views.workflow_customer_tasks import WorkflowCustomerTaskViewSetdef register_routes(routers: RouterRegistry) -> None:@@ -129,3 +130,9 @@ def register_routes(routers: RouterRegistry) -> None:["team_id", "account_id"],)routers.projects.register(r"customer_tasks", CustomerTaskViewSet, "project_customer_tasks", ["team_id"])+ routers.projects.register(+ r"workflow_customer_tasks",+ WorkflowCustomerTaskViewSet,+ "project_workflow_customer_tasks",+ ["team_id"],+ )diff --git a/products/workflows/backend/facade/__init__.py b/products/workflows/backend/facade/__init__.pynew file mode 100644index 000000000000..e69de29bb2d1diff --git a/products/workflows/backend/facade/api.py b/products/workflows/backend/facade/api.pynew file mode 100644index 000000000000..1000c81728fc--- /dev/null+++ b/products/workflows/backend/facade/api.py@@ -0,0 +1,14 @@+from uuid import UUID++from products.workflows.backend.models import HogFlow+++class WorkflowNotFound(Exception):+ pass+++def get_workflow_owner_id(*, team_id: int, workflow_id: UUID) -> int | None:+ try:+ return HogFlow.objects.values_list("created_by_id", flat=True).get(team_id=team_id, id=workflow_id)+ except HogFlow.DoesNotExist:+ raise WorkflowNotFound() from Nonediff --git a/products/workflows/backend/test/test_workflow_customer_tasks.py b/products/workflows/backend/test/test_workflow_customer_tasks.pynew file mode 100644index 000000000000..876083aaee61--- /dev/null+++ b/products/workflows/backend/test/test_workflow_customer_tasks.py@@ -0,0 +1,315 @@+from datetime import timedelta+from typing import Any+from uuid import UUID, uuid4++from posthog.test.base import APIBaseTest+from unittest.mock import patch++from django.test import override_settings+from django.utils import timezone++from parameterized import parameterized+from rest_framework.response import Response++from posthog.constants import AvailableFeature+from posthog.jwt import PosthogJwtAudience, encode_jwt+from posthog.models import OrganizationMembership, Team, User+from posthog.models.team.team import DEPRECATED_ATTRS+from posthog.test.db_context_capturing import capture_db_queries++from products.access_control.backend.facade.user_access_control import UserAccessControl+from products.access_control.backend.models.access_control import AccessControl+from products.customer_analytics.backend.facade import api, contracts+from products.customer_analytics.backend.facade.workflow_customer_tasks import get_workflow_customer_task_id+from products.workflows.backend.models import HogFlow++SECRET = "test-customer-tasks-workflow-key"+++@override_settings(CUSTOMER_ANALYTICS_ACCOUNTS_JWT_SECRETS=[SECRET])+class TestWorkflowCustomerTasks(APIBaseTest):+ def setUp(self) -> None:+ super().setUp()+ self.client.logout()+ self.organization.available_product_features = [+ {"name": AvailableFeature.ACCESS_CONTROL, "key": AvailableFeature.ACCESS_CONTROL}+ ]+ self.organization.save(update_fields=["available_product_features"])+ self.workflow = HogFlow.objects.create(+ team=self.team, created_by=self.user, name="Account follow-up", trigger={"type": "manual"}+ )+ self.url = f"/api/projects/{self.team.id}/workflow_customer_tasks/"+ self.flag = patch(+ "products.customer_analytics.backend.facade.workflow_customer_tasks.posthog_feature_flag_enabled",+ return_value=True,+ )+ self.flag_mock = self.flag.start()+ self.addCleanup(self.flag.stop)++ def _get_user_access_control(self, team: Team | None = None) -> UserAccessControl:+ return UserAccessControl(user=self.user, team=team or self.team)++ def _get_task_count(self) -> int:+ _, total = api.list_customer_tasks(+ team_id=self.team.id,+ user_access_control=self._get_user_access_control(),+ filters=contracts.CustomerTaskListFilters(archive_state="all"),+ offset=0,+ limit=1,+ )+ return total++ def _get_task_activity_count(self, task_id: UUID | str) -> int:+ result = api.list_customer_task_activities(+ team_id=self.team.id,+ task_id=task_id,+ user_access_control=self._get_user_access_control(),+ offset=0,+ limit=1,+ )+ assert result is not None+ return result[1]++ def _token(self, **claims: Any) -> str:+ return encode_jwt(+ {"team_id": self.team.id, "hog_flow_id": str(self.workflow.id), "idempotency_key": "run:step", **claims},+ timedelta(minutes=30),+ PosthogJwtAudience.CUSTOMER_TASKS_CREATE,+ signing_key=SECRET,+ )++ def _post(self, data: dict[str, Any] | None = None, token: str | None = None) -> Response:+ return self.client.post(+ self.url,+ {"name": "Follow up", "idempotency_key": "run:step", **(data or {})},+ format="json",+ HTTP_AUTHORIZATION=f"Bearer {token or self._token()}",+ )++ def test_creates_assigned_account_task_once_and_distinguishes_steps(self) -> None:+ account = api.create_account_for_view(+ team=self.team,+ input=contracts.CreateAccountInput(name="Example account"),+ user=self.user,+ was_impersonated=False,+ )+ deadline = timezone.now() + timedelta(days=2)+ response = self._post(+ {+ "account_id": str(account.id),+ "assigned_to_id": self.user.id,+ "description": "Review the account",+ "due_at": deadline.isoformat(),+ }+ )+ assert response.status_code == 201, response.data+ task = api.get_customer_task(+ team_id=self.team.id,+ task_id=response.data["id"],+ user_access_control=self._get_user_access_control(),+ )+ assert task is not None+ assert task.account is not None and task.account.id == account.id+ assert task.assigned_to is not None and task.assigned_to.id == self.user.id+ assert task.created_by is not None and task.created_by.id == self.user.id+ assert task.due_at == deadline+ repeated = self._post({"name": "A retry must not change the task"})+ assert repeated.status_code == 201+ assert repeated.data == response.data+ task = api.get_customer_task(+ team_id=self.team.id,+ task_id=response.data["id"],+ user_access_control=self._get_user_access_control(),+ )+ assert task is not None and task.name == "Follow up"+ assert self._get_task_activity_count(task.id) == 1+ different_step = self._post({"idempotency_key": "run:other"}, self._token(idempotency_key="run:other"))+ assert different_step.status_code == 201+ assert different_step.data["id"] != response.data["id"]++ @parameterized.expand(+ [+ ("other_team", {"team_id": -1}, 401),+ ("other_workflow", {"hog_flow_id": str(uuid4())}, 404),+ ("missing_workflow", {"hog_flow_id": None}, 401),+ ("other_invocation", {"idempotency_key": "another:step"}, 401),+ ("missing_invocation", {"idempotency_key": None}, 401),+ ]+ )+ def test_rejects_invalid_claims(self, _name: str, claims: dict[str, Any], expected_status: int) -> None:+ assert self._post().status_code == 201+ response = self._post(token=self._token(**claims))+ assert response.status_code == expected_status, response.data+ assert self._get_task_count() == 1++ @parameterized.expand(+ [+ ("tasks_create", PosthogJwtAudience.TASKS_CREATE),+ ("customer_analytics_accounts", PosthogJwtAudience.CUSTOMER_ANALYTICS_ACCOUNTS),+ ]+ )+ def test_rejects_user_credentials_and_other_purpose_tokens(self, _name: str, audience: PosthogJwtAudience) -> None:+ self.client.force_login(self.user)+ assert self.client.post(self.url, {"name": "Follow up", "idempotency_key": "run:step"}).status_code == 401+ other_purpose = encode_jwt(+ {"team_id": self.team.id, "hog_flow_id": str(self.workflow.id), "idempotency_key": "run:step"},+ timedelta(minutes=30),+ audience,+ signing_key=SECRET,+ )+ assert self._post(token=other_purpose).status_code == 401++ def test_rechecks_owner_access_and_flag_for_new_tasks(self) -> None:+ owner = User.objects.create_and_join(self.organization, "[email protected]", "testpassword")+ self.workflow.created_by = owner+ self.workflow.save(update_fields=["created_by"])+ membership = OrganizationMembership.objects.get(user=owner, organization=self.organization)+ restriction = AccessControl.objects.create(+ team=self.team,+ resource="customer_analytics",+ resource_id=None,+ organization_member=membership,+ access_level="viewer",+ )+ assert self._post().status_code == 403+ restriction.delete()+ self.flag_mock.return_value = False+ assert self._post().status_code == 403+ self.flag_mock.return_value = True+ owner.is_active = False+ owner.save(update_fields=["is_active"])+ assert self._post().status_code == 403+ self.workflow.created_by = None+ self.workflow.save(update_fields=["created_by"])+ assert self._post().status_code == 403+ assert self._get_task_count() == 0++ @parameterized.expand(+ [+ ("inactive_owner", 403),+ ("deleted_workflow", 404),+ ("project_access", 403),+ ("task_access", 403),+ ("disabled_flag", 403),+ ]+ )+ def test_replays_completed_creation_after_gate_changes(self, gate: str, expected_new_status: int) -> None:+ owner = User.objects.create_and_join(self.organization, "[email protected]", "testpassword")+ self.workflow.created_by = owner+ self.workflow.save(update_fields=["created_by"])+ response = self._post()+ assert response.status_code == 201, response.data++ if gate == "inactive_owner":+ owner.is_active = False+ owner.save(update_fields=["is_active"])+ elif gate == "deleted_workflow":+ HogFlow.objects.filter(team_id=self.team.id, id=self.workflow.id).delete()+ elif gate in {"project_access", "task_access"}:+ membership = OrganizationMembership.objects.get(user=owner, organization=self.organization)+ AccessControl.objects.create(+ team=self.team,+ resource="project" if gate == "project_access" else "customer_analytics",+ resource_id=str(self.team.id) if gate == "project_access" else None,+ organization_member=membership,+ access_level="none",+ )+ else:+ self.flag_mock.return_value = False++ replayed = self._post({"name": "A retry must not change the task"})+ assert replayed.status_code == 201, replayed.data+ assert replayed.data == response.data+ task = api.get_customer_task(+ team_id=self.team.id,+ task_id=response.data["id"],+ user_access_control=self._get_user_access_control(),+ )+ assert task is not None and task.name == "Follow up"+ assert self._get_task_activity_count(task.id) == 1+ new_task = self._post({"idempotency_key": "run:new"}, self._token(idempotency_key="run:new"))+ assert new_task.status_code == expected_new_status, new_task.data+ assert self._get_task_count() == 1++ def test_child_project_requires_canonical_access_and_stores_in_parent(self) -> None:+ child = Team.objects.create(organization=self.organization, parent_team=self.team, name="Child project")+ owner = User.objects.create_and_join(self.organization, "[email protected]", "testpassword")+ self.workflow.team = child+ self.workflow.created_by = owner+ self.workflow.save(update_fields=["team", "created_by"])+ membership = OrganizationMembership.objects.get(user=owner, organization=self.organization)+ restriction = AccessControl.objects.create(+ team=self.team,+ resource="project",+ resource_id=str(self.team.id),+ organization_member=membership,+ access_level="none",+ )+ AccessControl.objects.create(+ team=child,+ resource="project",+ resource_id=str(child.id),+ organization_member=membership,+ access_level="member",+ )+ self.url = f"/api/projects/{child.id}/workflow_customer_tasks/"+ token = self._token(team_id=child.id)+ assert self._post(token=token).status_code == 403+ restriction.delete()+ response = self._post(token=token)+ assert response.status_code == 201, response.data+ assert (+ api.get_customer_task(+ team_id=self.team.id,+ task_id=response.data["id"],+ user_access_control=self._get_user_access_control(),+ )+ is not None+ )+ assert (+ get_workflow_customer_task_id(team_id=child.id, workflow_id=self.workflow.id, idempotency_key="run:step")+ is None+ )++ AccessControl.objects.create(+ team=self.team,+ resource="project",+ resource_id=str(self.team.id),+ organization_member=membership,+ access_level="none",+ )+ replayed = self._post(token=token)+ assert replayed.status_code == 201, replayed.data+ assert replayed.data == response.data+ new_task = self._post({"idempotency_key": "run:new"}, self._token(team_id=child.id, idempotency_key="run:new"))+ assert new_task.status_code == 403, new_task.data+ assert self._get_task_count() == 1++ def test_child_project_creation_defers_deprecated_parent_team_columns(self) -> None:+ child = Team.objects.create(organization=self.organization, parent_team=self.team, name="Child project")+ self.workflow.team = child+ self.workflow.save(update_fields=["team"])+ self.url = f"/api/projects/{child.id}/workflow_customer_tasks/"++ with capture_db_queries() as context:+ assert self._post(token=self._token(team_id=child.id)).status_code == 201++ # T2 is the joined parent row. Requiring a non-deprecated column off it keeps the check below+ # from passing vacuously if the join ever stops hydrating the parent.+ parent_hydrating = [q["sql"] for q in context.captured_queries if 'T2."test_account_filters"' in q["sql"]]+ assert parent_hydrating, "expected the create to hydrate the parent team through a join"+ for sql in parent_hydrating:+ for attr in DEPRECATED_ATTRS:+ assert f'T2."{attr}"' not in sql, f"parent column {attr} was selected"++ def test_foreign_account_and_assignee_are_rejected(self) -> None:+ other_team = Team.objects.create(organization=self.organization, name="Other project")+ account = api.create_account_for_view(+ team=other_team,+ input=contracts.CreateAccountInput(name="Other account"),+ user=self.user,+ was_impersonated=False,+ )+ assert self._post({"account_id": str(account.id)}).status_code == 404+ assert self._post({"assigned_to_id": 2147483647}).status_code == 400+ assert self._get_task_count() == 0diff --git a/products/workflows/frontend/Workflows/hogflows/panel/HogFlowEditorPanelBuild.tsx b/products/workflows/frontend/Workflows/hogflows/panel/HogFlowEditorPanelBuild.tsxindex 766ece8bef50..b8375960bf51 100644--- a/products/workflows/frontend/Workflows/hogflows/panel/HogFlowEditorPanelBuild.tsx+++ b/products/workflows/frontend/Workflows/hogflows/panel/HogFlowEditorPanelBuild.tsx@@ -362,9 +362,7 @@ export function HogFlowEditorPanelBuild({const { currentTeam } = useValues(teamLogic)const { isRowScopedTrigger } = useValues(workflowLogic)- const registeredCategories = getRegisteredActionNodeCategories().filter(- (cat) => !cat.featureFlag || featureFlags[cat.featureFlag]- )+ const registeredCategories = getRegisteredActionNodeCategories(featureFlags)// Warehouse-triggered workflows have no person, so don't offer person-dependent steps at all.const hideIfRowScoped = (nodes: CreateActionType[]): CreateActionType[] =>diff --git a/products/workflows/frontend/Workflows/hogflows/registry/actions/actionNodeRegistry.ts b/products/workflows/frontend/Workflows/hogflows/registry/actions/actionNodeRegistry.tsindex 7a45fe0de265..a384c01e3346 100644--- a/products/workflows/frontend/Workflows/hogflows/registry/actions/actionNodeRegistry.ts+++ b/products/workflows/frontend/Workflows/hogflows/registry/actions/actionNodeRegistry.ts@@ -5,7 +5,7 @@ import { CreateActionType } from '../../hogFlowEditorLogic'export type ActionNodeCategory = {label: stringfeatureFlag?: FeatureFlagKey- nodes: CreateActionType[]+ nodes: (CreateActionType & { featureFlag?: FeatureFlagKey })[]}const registeredCategories: ActionNodeCategory[] = []@@ -14,6 +14,15 @@ export function registerActionNodeCategory(category: ActionNodeCategory): void {registeredCategories.push(category)}-export function getRegisteredActionNodeCategories(): ActionNodeCategory[] {+export function getRegisteredActionNodeCategories(featureFlags?: Record<string, unknown>): ActionNodeCategory[] {+ if (!featureFlags) {+ return registeredCategories+ }return registeredCategories+ .filter((category) => !category.featureFlag || featureFlags[category.featureFlag])+ .map((category) => ({+ ...category,+ nodes: category.nodes.filter((node) => !node.featureFlag || featureFlags[node.featureFlag]),+ }))+ .filter((category) => category.nodes.length > 0)}diff --git a/products/workflows/frontend/Workflows/hogflows/registry/actions/customer_analytics.test.ts b/products/workflows/frontend/Workflows/hogflows/registry/actions/customer_analytics.test.tsindex cc3db6f78257..716850604094 100644--- a/products/workflows/frontend/Workflows/hogflows/registry/actions/customer_analytics.test.ts+++ b/products/workflows/frontend/Workflows/hogflows/registry/actions/customer_analytics.test.ts@@ -26,6 +26,21 @@ describe('customer analytics action registry', () => {expect(getCategory().featureFlag).toBe(FEATURE_FLAGS.CUSTOMER_ANALYTICS_CSP)})+ it.each([+ [false, false, false],+ [false, true, false],+ [true, false, false],+ [true, true, true],+ ])('shows Create task with CSP %s and tasks %s: %s', (cspEnabled, tasksEnabled, visible) => {+ const categories = getRegisteredActionNodeCategories({+ [FEATURE_FLAGS.CUSTOMER_ANALYTICS_CSP]: cspEnabled,+ [FEATURE_FLAGS.CUSTOMER_ANALYTICS_CUSTOMER_TASKS]: tasksEnabled,+ })+ const nodes = categories.flatMap((category) => category.nodes)+ expect(nodes.some((node) => node.name === 'Create task')).toBe(visible)+ expect(nodes.some((node) => node.name === 'Get account')).toBe(cspEnabled)+ })+it('wires the Get account node to its hog function template', () => {const node = getCategory().nodes.find((n) => n.name === 'Get account')expect(node).toMatchObject({diff --git a/products/workflows/frontend/Workflows/hogflows/registry/actions/customer_analytics.ts b/products/workflows/frontend/Workflows/hogflows/registry/actions/customer_analytics.tsindex 76b1aa48b1ac..98808c80353b 100644--- a/products/workflows/frontend/Workflows/hogflows/registry/actions/customer_analytics.ts+++ b/products/workflows/frontend/Workflows/hogflows/registry/actions/customer_analytics.ts@@ -98,6 +98,15 @@ registerActionNodeCategory({label: 'Customer analytics',featureFlag: FEATURE_FLAGS.CUSTOMER_ANALYTICS_CSP,nodes: [+ {+ type: 'function',+ name: 'Create task',+ featureFlag: FEATURE_FLAGS.CUSTOMER_ANALYTICS_CUSTOMER_TASKS,+ description:+ 'Create a Customer analytics task with an optional account, assignee, and due date. All fields support workflow variables.',+ config: { template_id: 'template-posthog-create-customer-task', inputs: {} },+ output_variable: { key: 'customer_task', result_path: null, label: 'Task' },+ },{type: 'function',name: 'Create account',diff --git a/products/workflows/frontend/Workflows/hogflows/steps/components/CustomerTaskWorkflowReferenceInput.stories.tsx b/products/workflows/frontend/Workflows/hogflows/steps/components/CustomerTaskWorkflowReferenceInput.stories.tsxnew file mode 100644index 000000000000..e8ea557c1b64--- /dev/null+++ b/products/workflows/frontend/Workflows/hogflows/steps/components/CustomerTaskWorkflowReferenceInput.stories.tsx@@ -0,0 +1,49 @@+import { Meta, StoryFn } from '@storybook/react'+import { useState } from 'react'++import { CyclotronJobInputType } from '~/types'++import { CustomerTaskWorkflowReferenceInput } from './CustomerTaskWorkflowReferenceInput'++const meta: Meta<typeof CustomerTaskWorkflowReferenceInput> = {+ title: 'Products/Workflows/Steps/Customer task reference input',+ component: CustomerTaskWorkflowReferenceInput,+ parameters: {+ mockDate: '2026-01-01',+ msw: {+ mocks: {+ get: {+ '/api/projects/:project_id/accounts/': {+ results: [{ id: '11111111-1111-4111-8111-111111111111', name: 'Example account' }],+ },+ },+ },+ },+ },+}+export default meta++const Template: StoryFn<typeof CustomerTaskWorkflowReferenceInput> = (args) => {+ const [input, setInput] = useState<CyclotronJobInputType>(args.input)+ return (+ <div className="p-4 max-w-lg">+ <CustomerTaskWorkflowReferenceInput {...args} input={input} onChange={setInput} />+ </div>+ )+}++export const Account = Template.bind({})+Account.args = {+ schema: { key: 'account_id', type: 'string', label: 'Account' },+ input: { value: '{variables.account.id}', templating: 'hog' },+ projectId: 1,+ sampleGlobals: { variables: { account: { id: '11111111-1111-4111-8111-111111111111' } } },+}++export const Assignee = Template.bind({})+Assignee.args = {+ schema: { key: 'assigned_to_id', type: 'string', label: 'Assignee' },+ input: { value: '{variables.owner_id}', templating: 'hog' },+ projectId: 1,+ sampleGlobals: { variables: { owner_id: 1 } },+}diff --git a/products/workflows/frontend/Workflows/hogflows/steps/components/CustomerTaskWorkflowReferenceInput.test.tsx b/products/workflows/frontend/Workflows/hogflows/steps/components/CustomerTaskWorkflowReferenceInput.test.tsxnew file mode 100644index 000000000000..9da1e744203c--- /dev/null+++ b/products/workflows/frontend/Workflows/hogflows/steps/components/CustomerTaskWorkflowReferenceInput.test.tsx@@ -0,0 +1,104 @@+import { MOCK_DEFAULT_BASIC_USER, MOCK_SECOND_BASIC_USER, MOCK_USER_UUID } from 'lib/api.mock'++import '@testing-library/jest-dom'++import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'+import { Provider } from 'kea'+import { expectLogic } from 'kea-test-utils'++import { userLogic } from 'scenes/userLogic'++import { useMocks } from '~/mocks/jest'+import { initKeaTests } from '~/test/init'++import { CustomerTaskWorkflowReferenceInput } from './CustomerTaskWorkflowReferenceInput'++jest.mock('lib/monaco/CodeEditorInline', () => ({+ CodeEditorInline: ({ value, onChange }: { value: string; onChange: (value: string) => void }) => (+ <input aria-label="Raw expression" value={value} onChange={(event) => onChange(event.target.value)} />+ ),+}))++const accountId = '11111111-1111-4111-8111-111111111111'+const UNAVAILABLE_ASSIGNEE = 'Saved assignee is unavailable. Choose another member or edit the raw value.'++describe('CustomerTaskWorkflowReferenceInput', () => {+ beforeEach(async () => {+ useMocks({+ get: {+ '/api/projects/:project_id/accounts/': { results: [{ id: accountId, name: 'Example account' }] },+ '/api/organizations/:organization_id/members/': {+ results: [+ { id: '1', user: MOCK_DEFAULT_BASIC_USER, level: 8 },+ { id: '2', user: MOCK_SECOND_BASIC_USER, level: 1 },+ ],+ },+ },+ })+ initKeaTests()+ userLogic().mount()+ await expectLogic(userLogic).toMatchValues({ user: expect.objectContaining({ uuid: MOCK_USER_UUID }) })+ })+ afterEach(cleanup)++ function renderInput(key: string, value: string, onChange = jest.fn()): jest.Mock {+ render(+ <Provider>+ <CustomerTaskWorkflowReferenceInput+ schema={{ key, type: 'string', label: key }}+ input={{ value, templating: 'hog' }}+ onChange={onChange}+ projectId={1}+ sampleGlobals={{}}+ />+ </Provider>+ )+ return onChange+ }++ it.each(['account_id', 'assigned_to_id'])(+ 'preserves %s expressions across mode changes and raw edits',+ async (key) => {+ const expression = '{variables.account_or_user}'+ const onChange = renderInput(key, expression)+ fireEvent.click(screen.getByText('Picker'))+ expect(onChange).not.toHaveBeenCalled()+ expect(screen.getByText('Choose a value to replace the raw expression.')).toBeInTheDocument()+ fireEvent.click(screen.getByText('Raw'))+ expect(screen.getByLabelText('Raw expression')).toHaveValue(expression)+ fireEvent.change(screen.getByLabelText('Raw expression'), { target: { value: '{variables.other}' } })+ expect(onChange).toHaveBeenCalledWith({ value: '{variables.other}', templating: 'hog' })+ }+ )++ it('stores the picked account UUID and preserves templating metadata', async () => {+ const onChange = renderInput('account_id', '')+ fireEvent.click(screen.getByText('Picker'))+ fireEvent.click(screen.getByPlaceholderText('No account'))+ await waitFor(() => expect(screen.getByText('Example account')).toBeInTheDocument())+ fireEvent.click(screen.getByText('Example account'))+ expect(onChange).toHaveBeenCalledWith({ value: accountId, templating: 'hog' })+ })++ it.each([+ ['resolves a saved member', String(MOCK_SECOND_BASIC_USER.id), MOCK_SECOND_BASIC_USER.first_name, false],+ ['flags a saved member the organization cannot resolve', '999', 'User 999', true],+ ])('%s on entering Picker without opening the member menu', async (_name, value, label, unavailable) => {+ const onChange = renderInput('assigned_to_id', value)+ fireEvent.click(screen.getByText('Picker'))+ await waitFor(() => {+ expect(screen.getByText(label)).toBeInTheDocument()+ expect(screen.queryByText(UNAVAILABLE_ASSIGNEE) !== null).toBe(unavailable)+ })+ expect(onChange).not.toHaveBeenCalled()+ })++ it('stores the picked member as a string ID for the templated schema', async () => {+ const onChange = renderInput('assigned_to_id', '{variables.owner_id}')+ fireEvent.click(screen.getByText('Picker'))+ fireEvent.click(screen.getByText('Unassigned'))+ await waitFor(() => expect(screen.getByText(MOCK_SECOND_BASIC_USER.first_name)).toBeInTheDocument())+ fireEvent.click(screen.getByText(MOCK_SECOND_BASIC_USER.first_name))+ expect(onChange).toHaveBeenCalledWith({ value: String(MOCK_SECOND_BASIC_USER.id), templating: 'hog' })+ })+})diff --git a/products/workflows/frontend/Workflows/hogflows/steps/components/CustomerTaskWorkflowReferenceInput.tsx b/products/workflows/frontend/Workflows/hogflows/steps/components/CustomerTaskWorkflowReferenceInput.tsxnew file mode 100644index 000000000000..a6f65d3a3a4d--- /dev/null+++ b/products/workflows/frontend/Workflows/hogflows/steps/components/CustomerTaskWorkflowReferenceInput.tsx@@ -0,0 +1,151 @@+import { useActions, useValues } from 'kea'+import { useEffect, useId, useState } from 'react'++import { LemonButton, LemonInputSelect, LemonLabel, LemonSegmentedButton } from '@posthog/lemon-ui'++import { MemberSelect } from 'lib/components/MemberSelect'+import { LemonField } from 'lib/lemon-ui/LemonField'+import { CodeEditorInline } from 'lib/monaco/CodeEditorInline'+import { fullName } from 'lib/utils/strings'+import { membersLogic } from 'scenes/organization/membersLogic'++import { CyclotronJobInputSchemaType, CyclotronJobInputType, CyclotronJobInvocationGlobalsWithInputs } from '~/types'++import { customerTaskWorkflowAccountLogic } from './customerTaskWorkflowAccountLogic'++export function CustomerTaskWorkflowReferenceInput({+ schema,+ input,+ onChange,+ projectId,+ sampleGlobals,+ error,+}: {+ schema: CyclotronJobInputSchemaType+ input: CyclotronJobInputType+ onChange: (input: CyclotronJobInputType) => void+ projectId: number | null+ sampleGlobals: CyclotronJobInvocationGlobalsWithInputs+ error?: string+}): JSX.Element {+ const [mode, setMode] = useState<'raw' | 'picker'>('raw')+ const id = useId()+ const logic = customerTaskWorkflowAccountLogic({ id, projectId })+ const { choices, choicesLoading } = useValues(logic)+ const { loadChoices } = useActions(logic)+ const { members, meFirstMembers, membersLoading } = useValues(membersLogic)+ const { ensureAllMembersLoaded } = useActions(membersLogic)+ const isAccount = schema.key === 'account_id'+ const rawValue = input.value == null ? '' : String(input.value)+ const accountId = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(rawValue) ? rawValue : null+ const memberId = /^[1-9]\d*$/.test(rawValue) && Number(rawValue) <= 2147483647 ? Number(rawValue) : null+ // MemberSelect labels an id it cannot match with its defaultLabel, so a departed member or an+ // id from another organization would read as unassigned while the step still carries it.+ const savedMember = memberId === null ? null : (meFirstMembers.find((m) => m.user.id === memberId)?.user ?? null)++ useEffect(() => {+ if (mode === 'picker') {+ if (isAccount) {+ loadChoices({ query: '', accountId })+ } else {+ ensureAllMembersLoaded()+ }+ }+ }, [isAccount, mode, accountId, loadChoices, ensureAllMembersLoaded])++ return (+ <LemonField.Pure error={error} className="gap-1">+ <div+ className="flex items-center justify-between gap-2"+ data-attr={`customer-task-${schema.key}-input-mode`}+ >+ <LemonLabel showOptional>{isAccount ? 'Account' : 'Assignee'}</LemonLabel>+ <LemonSegmentedButton+ size="xsmall"+ value={mode}+ onChange={setMode}+ options={[+ { value: 'raw' as const, label: 'Raw' },+ { value: 'picker' as const, label: 'Picker' },+ ]}+ />+ </div>+ {mode === 'raw' ? (+ <CodeEditorInline+ className="ph-no-capture"+ minHeight="37"+ value={rawValue}+ onChange={(value) => onChange({ ...input, value: value ?? '' })}+ language={input.templating === 'liquid' ? 'liquid' : 'hogTemplate'}+ globals={sampleGlobals}+ />+ ) : (+ <>+ {isAccount ? (+ choices?.failed ? (+ <div className="flex items-center gap-2 text-danger">+ <span>Could not load accounts.</span>+ <LemonButton size="small" onClick={() => loadChoices({ query: '', accountId })}>+ Retry+ </LemonButton>+ </div>+ ) : (+ <LemonInputSelect+ mode="single"+ value={+ accountId && choices?.options.some((option) => option.key === accountId)+ ? [accountId]+ : []+ }+ options={choices?.options ?? []}+ loading={choicesLoading || choices === null}+ onInputChange={(query) => loadChoices({ query, accountId })}+ onChange={(values) => onChange({ ...input, value: values[0] ?? '' })}+ placeholder="No account"+ disabledReason={projectId === null ? 'Select a project first' : undefined}+ fullWidth+ data-attr="workflow-customer-task-account"+ />+ )+ ) : (+ <MemberSelect+ value={memberId}+ defaultLabel="Unassigned"+ type="secondary"+ size="small"+ onChange={(user) => onChange({ ...input, value: user ? String(user.id) : null })}+ >+ {() => (+ <LemonButton type="secondary" size="small">+ {savedMember+ ? fullName(savedMember) || savedMember.email+ : memberId === null+ ? 'Unassigned'+ : `User ${memberId}`}+ </LemonButton>+ )}+ </MemberSelect>+ )}+ {!isAccount && memberId !== null && !savedMember && members !== null && !membersLoading && (+ <span className="text-xs text-secondary">+ Saved assignee is unavailable. Choose another member or edit the raw value.+ </span>+ )}+ {isAccount &&+ accountId &&+ choices &&+ !choicesLoading &&+ !choices.failed &&+ !choices.options.some((option) => option.key === accountId) && (+ <span className="text-xs text-secondary">+ Saved account is unavailable. Choose another account or edit the raw value.+ </span>+ )}+ {rawValue && !(isAccount ? accountId : memberId) && (+ <span className="text-xs text-secondary">Choose a value to replace the raw expression.</span>+ )}+ </>+ )}+ </LemonField.Pure>+ )+}diff --git a/products/workflows/frontend/Workflows/hogflows/steps/components/HogFlowFunctionConfiguration.tsx b/products/workflows/frontend/Workflows/hogflows/steps/components/HogFlowFunctionConfiguration.tsxindex 1416769ddb3b..23ab2bed95ed 100644--- a/products/workflows/frontend/Workflows/hogflows/steps/components/HogFlowFunctionConfiguration.tsx+++ b/products/workflows/frontend/Workflows/hogflows/steps/components/HogFlowFunctionConfiguration.tsx@@ -16,6 +16,7 @@ import { CyclotronJobInputType, HogFunctionMappingType } from '~/types'import { workflowLogic } from '../../../workflowLogic'import { isGithubEventTriggerConfig } from '../../registry/triggers/githubTriggerFilters'import { isSlackMessageTriggerConfig } from '../../registry/triggers/slackTriggerFilters'+import { CustomerTaskWorkflowReferenceInput } from './CustomerTaskWorkflowReferenceInput'import { HogFlowFunctionMappings } from './HogFlowFunctionMappings'import { WorkflowAutoSaveIndicator } from './WorkflowAutoSaveIndicator'@@ -241,7 +242,27 @@ export function HogFlowFunctionConfiguration({return (<>- {renderInputs(coreInputsSchema)}+ {templateId === 'template-posthog-create-customer-task' ? (+ <div className="flex flex-col gap-3">+ {coreInputsSchema.map((schema) =>+ schema.key === 'account_id' || schema.key === 'assigned_to_id' ? (+ <CustomerTaskWorkflowReferenceInput+ key={schema.key}+ schema={schema}+ input={inputs[schema.key] ?? { value: null }}+ onChange={(value) => setInputs({ ...inputs, [schema.key]: value })}+ projectId={currentTeam?.id ?? null}+ sampleGlobals={sampleGlobals}+ error={errors?.[schema.key]}+ />+ ) : (+ <div key={schema.key}>{renderInputs([schema])}</div>+ )+ )}+ </div>+ ) : (+ renderInputs(coreInputsSchema)+ )}{isPushStep && (androidInputsSchema.length > 0 || iosInputsSchema.length > 0) && (<LemonCollapseclassName="mt-2"diff --git a/products/workflows/frontend/Workflows/hogflows/steps/components/customerTaskWorkflowAccountLogic.test.ts b/products/workflows/frontend/Workflows/hogflows/steps/components/customerTaskWorkflowAccountLogic.test.tsnew file mode 100644index 000000000000..f44dda30b267--- /dev/null+++ b/products/workflows/frontend/Workflows/hogflows/steps/components/customerTaskWorkflowAccountLogic.test.ts@@ -0,0 +1,56 @@+import { expectLogic } from 'kea-test-utils'++import { ApiError } from 'lib/api-error'++import { initKeaTests } from '~/test/init'++import * as api from 'products/customer_analytics/frontend/generated/api'++import { customerTaskWorkflowAccountLogic } from './customerTaskWorkflowAccountLogic'++jest.mock('products/customer_analytics/frontend/generated/api')++const accountsList = jest.mocked(api.accountsList)+const accountsRetrieve = jest.mocked(api.accountsRetrieve)+const accountId = '11111111-1111-4111-8111-111111111111'++describe('customerTaskWorkflowAccountLogic', () => {+ let logic: ReturnType<typeof customerTaskWorkflowAccountLogic.build>++ beforeEach(() => {+ initKeaTests()+ // The saved account is absent from the first page, which is what sends the loader to+ // accountsRetrieve. Any team with more accounts than the page limit hits this on every open.+ accountsList.mockResolvedValue({ results: [] } as any)+ logic = customerTaskWorkflowAccountLogic({ id: 'test', projectId: 1 })+ logic.mount()+ })++ afterEach(() => {+ logic.unmount()+ jest.restoreAllMocks()+ })++ // The picker only tells someone their saved account is unavailable, and to replace it, when+ // `failed` is false. That advice is safe for a deleted account and wrong for a transient error.+ it.each([+ ['a deleted account as unavailable', new ApiError(undefined, 404), false],+ ['a server error as retryable', new ApiError(undefined, 500), true],+ ['a permission failure as retryable', new ApiError(undefined, 403), true],+ ['a network failure as retryable', new Error('Failed to fetch'), true],+ ])('reports %s', async (_name, error, failed) => {+ accountsRetrieve.mockRejectedValue(error)+ logic.actions.loadChoices({ query: '', accountId })+ await expectLogic(logic)+ .toFinishAllListeners()+ .toMatchValues({ choices: { options: [], failed } })+ })++ it('keeps a saved account that resolves outside the first page', async () => {+ accountsRetrieve.mockResolvedValue({ id: accountId, name: 'Example account' } as any)+ logic.actions.loadChoices({ query: '', accountId })+ await expectLogic(logic)+ .toFinishAllListeners()+ .toMatchValues({ choices: { options: [{ key: accountId, label: 'Example account' }], failed: false } })+ })+})diff --git a/products/workflows/frontend/Workflows/hogflows/steps/components/customerTaskWorkflowAccountLogic.ts b/products/workflows/frontend/Workflows/hogflows/steps/components/customerTaskWorkflowAccountLogic.tsnew file mode 100644index 000000000000..dfaad2410bd9--- /dev/null+++ b/products/workflows/frontend/Workflows/hogflows/steps/components/customerTaskWorkflowAccountLogic.ts@@ -0,0 +1,93 @@+import { MakeLogicType, kea, key, path, props } from 'kea'+import { loaders } from 'kea-loaders'++import { ApiError } from 'lib/api-error'++import { accountsList, accountsRetrieve } from 'products/customer_analytics/frontend/generated/api'++interface AccountChoices {+ options: { key: string; label: string }[]+ failed: boolean+}+interface AccountQuery {+ query: string+ accountId: string | null+}+interface AccountLogicProps {+ id: string+ projectId: number | null+}++export interface customerTaskWorkflowAccountLogicValues {+ choices: AccountChoices | null+ choicesLoading: boolean+}+export interface customerTaskWorkflowAccountLogicActions {+ loadChoices: (query: AccountQuery) => AccountQuery+ loadChoicesSuccess: (+ choices: AccountChoices | null,+ payload?: AccountQuery+ ) => { choices: AccountChoices | null; payload?: AccountQuery }+ loadChoicesFailure: (error: string, errorObject?: unknown) => { error: string; errorObject?: unknown }+}+export type customerTaskWorkflowAccountLogicType = MakeLogicType<+ customerTaskWorkflowAccountLogicValues,+ customerTaskWorkflowAccountLogicActions,+ AccountLogicProps,+ { key: string }+>++export const customerTaskWorkflowAccountLogic = kea<customerTaskWorkflowAccountLogicType>([+ path([+ 'products',+ 'workflows',+ 'frontend',+ 'Workflows',+ 'hogflows',+ 'steps',+ 'components',+ 'customerTaskWorkflowAccountLogic',+ ]),+ props({} as AccountLogicProps),+ key(({ id, projectId }) => `${id}:${projectId}`),+ loaders(({ props }) => ({+ choices: [+ null as AccountChoices | null,+ {+ loadChoices: async ({ query, accountId }: AccountQuery, breakpoint): Promise<AccountChoices> => {+ await breakpoint(300)+ if (props.projectId === null) {+ return { options: [], failed: false }+ }+ try {+ const response = await accountsList(String(props.projectId), {+ search: query || undefined,+ limit: 25,+ })+ breakpoint()+ const options = response.results.map((account) => ({ key: account.id, label: account.name }))+ if (accountId && !options.some((option) => option.key === accountId)) {+ try {+ const selected = await accountsRetrieve(String(props.projectId), accountId)+ breakpoint()+ options.unshift({ key: selected.id, label: selected.name })+ } catch (error) {+ breakpoint()+ // Only a 404 proves the saved account is really gone. Any other failure+ // leaves that unanswered, so report it as retryable instead of letting the+ // picker advise replacing an account that is probably still valid.+ if (!(error instanceof ApiError) || error.status !== 404) {+ return { options: [], failed: true }+ }+ }+ }+ return { options, failed: false }+ } catch {+ breakpoint()+ return { options: [], failed: true }+ }+ },+ },+ ],+ })),+])