Skip to content

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

feat(workflows): ask the AI task for the fields its output variables read (#97303)

Harley Alexanderb589d7246dee
diff --git a/docs/internal/workflow-ai-task-limits.md b/docs/internal/workflow-ai-task-limits.md
index 5ea795a455fd..959ed1a9a02c 100644
--- a/docs/internal/workflow-ai-task-limits.md
+++ b/docs/internal/workflow-ai-task-limits.md
@@ -20,6 +20,17 @@ After success, the next step sees the dispatch IDs, `status: completed`, and a c
A failed or cancelled run fails the step. The step's `on_error` setting decides whether the workflow continues.
With `on_error: continue`, the dispatch IDs remain available. The failed step does not store the terminal status, message, or `error_message` in its result.
+### Fields the agent returns
+
+An AI task step can hand fields the agent produced to later steps.
+The author adds an output variable mapping with the result path `output.<name>`, for example `output.verdict` into the variable `verdict`.
+The engine sends these fields with the create request as `output_fields`, a name to type map typed after the workflow variable (`string`, `number`, or `boolean`), with at most 20 fields.
+The tasks API builds the schema from that map. Field names are identifiers, and the names the task result uses for itself (`final_message`, `pr_urls` and the other bookkeeping keys) are refused.
+The agent runtime enforces the schema at the end of the run, and the resume result carries the fields under `output`, ahead of the final message.
+The agent prompt names the fields and their budget: each text field is capped at 1500 characters, and the fields share the 4096 byte step result with the final message, fields first.
+When the agent finishes without output that matches the fields, or a field was cut to fit the step result, the step still completes.
+The resume result carries `warnings`, the engine writes each one to the run log at `warn` level and counts the resume in `cdp_hogflow_awaited_step_resumed_with_warnings`, and the unmatched variables stay null.
+
A template asks for the wait by returning an `await` object next to its result, for example `{ 'id': ..., 'run_id': ..., 'await': { 'max_wait': '190m', 'label': 'task' } }`.
`max_wait` is set by the template's author, never by the workflow author, and the engine caps it at 24 hours.
The task template uses 190 minutes and the scout template 35 minutes: each product's own runtime cap plus slack, so the product's own timeout wake lands before the step's deadline.
diff --git a/nodejs/src/cdp/async-functions/create-task.ts b/nodejs/src/cdp/async-functions/create-task.ts
index 1017f1f02857..a3b6e3d371d7 100644
--- a/nodejs/src/cdp/async-functions/create-task.ts
+++ b/nodejs/src/cdp/async-functions/create-task.ts
@@ -8,6 +8,7 @@ import { registerAsyncFunction } from '../async-function-registry'
import { PosthogJwtAudience } from '../utils/jwt-utils'
import { ScopedServiceJwt } from '../utils/scoped-service-jwt'
import { workflowStepDispatchKeyFromInvocation } from '../utils/workflow-step-dispatch-key'
+import { buildWorkflowTaskOutputFields } from '../utils/workflow-task-output-fields'
// The token rides the staged fetch verbatim through every engine retry (executeFetch re-queues
// the identical request), so its lifetime must cover the whole backoff chain plus queue lag,
@@ -45,6 +46,10 @@ registerAsyncFunction('postHogCreateTask', {
}
const token = jwt.mint({ team_id: context.invocation.teamId, hog_flow_id: hogFlow.id }, TOKEN_TTL_SECONDS)
+ // Derived from the step's own output variables, so the author declares the fields once.
+ const action = hogFlow.actions?.find((candidate) => candidate.id === context.invocation.state.actionId)
+ const outputFields = buildWorkflowTaskOutputFields(action?.output_variable, hogFlow.variables)
+
result.invocation.queueParameters = CyclotronInvocationQueueParametersFetchSchema.parse({
type: 'fetch',
url: `${context.siteUrl}/api/projects/${context.invocation.teamId}/workflow_tasks/`,
@@ -56,6 +61,7 @@ registerAsyncFunction('postHogCreateTask', {
body: JSON.stringify({
...payload,
idempotency_key: idempotencyKey,
+ ...(outputFields ? { output_fields: outputFields } : {}),
}),
})
},
diff --git a/nodejs/src/cdp/templates/_destinations/posthog_tasks/posthog-create-task.template.test.ts b/nodejs/src/cdp/templates/_destinations/posthog_tasks/posthog-create-task.template.test.ts
index 7cd11339e500..71799aa5e57d 100644
--- a/nodejs/src/cdp/templates/_destinations/posthog_tasks/posthog-create-task.template.test.ts
+++ b/nodejs/src/cdp/templates/_destinations/posthog_tasks/posthog-create-task.template.test.ts
@@ -109,6 +109,28 @@ describe('posthog create task template', () => {
})
})
+ it('asks the agent for the fields the output variables read from the output', async () => {
+ const hogFlow = {
+ ...workflowOptions.hogFlow,
+ actions: [
+ {
+ id: 'action_1',
+ output_variable: [
+ { key: 'verdict', result_path: 'output.verdict' },
+ { key: 'run', result_path: 'run_id' },
+ ],
+ },
+ ],
+ variables: [{ key: 'verdict', type: 'string', label: 'Verdict', description: 'ship or hold' }],
+ } as any
+ const response = await tester.invoke({ prompt: 'Judge the PR' }, undefined, { ...workflowOptions, hogFlow })
+
+ expect(response.error).toBeUndefined()
+ expect(parseJSON((response.invocation.queueParameters as any).body).output_fields).toEqual({
+ verdict: 'string',
+ })
+ })
+
it.each([
['a top-level post binds to its own ts', { thread_ts: null }, '1700000000.000100'],
['a thread reply binds to the parent thread', { thread_ts: '1699999999.000001' }, '1699999999.000001'],
diff --git a/nodejs/src/cdp/templates/test/test-helpers.ts b/nodejs/src/cdp/templates/test/test-helpers.ts
index 8f0b0883b0fd..65a3c76cf2b3 100644
--- a/nodejs/src/cdp/templates/test/test-helpers.ts
+++ b/nodejs/src/cdp/templates/test/test-helpers.ts
@@ -4,6 +4,7 @@ import { Settings } from 'luxon'
import { getTransformationFunctions } from '~/cdp/hog-transformations/transformation-functions'
import { CyclotronInputType } from '~/cdp/schema/cyclotron'
+import { HogFlow } from '~/cdp/schema/hogflow'
import { formatLiquidInput } from '~/cdp/services/hog-inputs.service'
import { NativeDestinationExecutorService } from '~/cdp/services/native-destination-executor.service'
import { isNativeHogFunction } from '~/cdp/utils'
@@ -282,7 +283,7 @@ export class TemplateTester {
async invoke(
_inputs: Record<string, any>,
_globals?: DeepPartialHogFunctionInvocationGlobals,
- _options?: { hogFlow?: { id: string }; actionId?: string }
+ _options?: { hogFlow?: Partial<HogFlow> & { id: string }; actionId?: string }
): Promise<CyclotronJobInvocationResult<CyclotronJobInvocationHogFunction>> {
if (this.template.mapping_templates) {
throw new Error('Mapping templates found. Use invokeMapping instead.')
@@ -312,7 +313,7 @@ export class TemplateTester {
// Workflow-only async functions read the flow id and step id off the invocation the way
// HogFlowFunctionsService sets them; there is no flow in this harness, so inject them.
if (_options?.hogFlow) {
- ;(invocation as { hogFlow?: { id: string } }).hogFlow = _options.hogFlow
+ ;(invocation as { hogFlow?: Partial<HogFlow> }).hogFlow = _options.hogFlow
}
if (_options?.actionId) {
invocation.state.actionId = _options.actionId
diff --git a/nodejs/src/cdp/utils/workflow-task-output-fields.test.ts b/nodejs/src/cdp/utils/workflow-task-output-fields.test.ts
new file mode 100644
index 000000000000..ab6fa933a182
--- /dev/null
+++ b/nodejs/src/cdp/utils/workflow-task-output-fields.test.ts
@@ -0,0 +1,40 @@
+import { buildWorkflowTaskOutputFields } from './workflow-task-output-fields'
+
+describe('buildWorkflowTaskOutputFields', () => {
+ const variables = [
+ { key: 'verdict', type: 'string' as const, label: 'Verdict', description: 'ship or hold' },
+ { key: 'score', type: 'number' as const, label: 'Confidence score' },
+ { key: 'urgent', type: 'boolean' as const, label: 'urgent' },
+ { key: 'details', type: 'json' as const, label: 'details' },
+ ]
+
+ it('turns each output.<name> mapping into a typed field', () => {
+ const fields = buildWorkflowTaskOutputFields(
+ [
+ { key: 'verdict', result_path: 'output.verdict' },
+ { key: 'score', result_path: 'output.score' },
+ { key: 'urgent', result_path: 'output.is_urgent' },
+ { key: 'details', result_path: 'output.details' },
+ ],
+ variables
+ )
+
+ expect(fields).toEqual({ verdict: 'string', score: 'number', is_urgent: 'boolean', details: 'string' })
+ })
+
+ it.each([
+ ['a mapping of the whole result', { key: 'task' }],
+ ['a mapping of a fixed field', { key: 'run', result_path: 'run_id' }],
+ ['a spread of the output object', { key: 'task', result_path: 'output', spread: true }],
+ ['a nested output path', { key: 'verdict', result_path: 'output.a.b' }],
+ ['a mapping with no variable selected', { key: '', result_path: 'output.verdict' }],
+ ])('asks for nothing when the only mapping is %s', (_name, mapping) => {
+ expect(buildWorkflowTaskOutputFields(mapping, variables)).toBeNull()
+ })
+
+ it('asks for text when it cannot match the mapping to a variable', () => {
+ expect(buildWorkflowTaskOutputFields({ key: 'missing', result_path: 'output.verdict' }, [])).toEqual({
+ verdict: 'string',
+ })
+ })
+})
diff --git a/nodejs/src/cdp/utils/workflow-task-output-fields.ts b/nodejs/src/cdp/utils/workflow-task-output-fields.ts
new file mode 100644
index 000000000000..747df9de4d9b
--- /dev/null
+++ b/nodejs/src/cdp/utils/workflow-task-output-fields.ts
@@ -0,0 +1,37 @@
+import { HogFlow, HogFlowAction } from '../schema/hogflow'
+
+// One level only: `output.verdict`, not `output.a.b`. Nested paths still resolve at resume time
+// through `result_path`, but the agent is only asked for top-level fields.
+const OUTPUT_FIELD_PATH = /^output\.([A-Za-z_][A-Za-z0-9_]*)$/
+
+export type WorkflowTaskOutputFieldType = 'string' | 'number' | 'boolean'
+const FIELD_TYPES: ReadonlySet<string> = new Set<WorkflowTaskOutputFieldType>(['string', 'number', 'boolean'])
+
+export type WorkflowTaskOutputFields = Record<string, WorkflowTaskOutputFieldType>
+
+/**
+ * The fields the AI task step asks the agent for, derived from the step's output variables.
+ * Every mapping whose result path is `output.<name>` becomes one field, typed after the
+ * workflow variable it stores into. The tasks API builds the schema from this map.
+ * Returns null when no mapping reads from `output`.
+ */
+export const buildWorkflowTaskOutputFields = (
+ outputVariable: HogFlowAction['output_variable'],
+ variables: HogFlow['variables']
+): WorkflowTaskOutputFields | null => {
+ const mappings = Array.isArray(outputVariable) ? outputVariable : outputVariable ? [outputVariable] : []
+ const variablesByKey = new Map((variables ?? []).map((variable) => [variable.key, variable]))
+ const fields: WorkflowTaskOutputFields = {}
+
+ for (const mapping of mappings) {
+ const field = mapping.key ? OUTPUT_FIELD_PATH.exec(mapping.result_path ?? '')?.[1] : undefined
+ if (!field) {
+ continue
+ }
+ const type = variablesByKey.get(mapping.key)?.type
+ // A variable of another type, or none, still gets asked for: text is what any of them can hold.
+ fields[field] = type && FIELD_TYPES.has(type) ? (type as WorkflowTaskOutputFieldType) : 'string'
+ }
+
+ return Object.keys(fields).length === 0 ? null : fields
+}
diff --git a/nodejs/tests/fixtures/hog-bytecode/f2c4719ee2dcc681ed91578073f01af620249c0e168358d06a75c7e670167f00.json b/nodejs/tests/fixtures/hog-bytecode/f2c4719ee2dcc681ed91578073f01af620249c0e168358d06a75c7e670167f00.json
new file mode 100644
index 000000000000..a7421ac2b36f
--- /dev/null
+++ b/nodejs/tests/fixtures/hog-bytecode/f2c4719ee2dcc681ed91578073f01af620249c0e168358d06a75c7e670167f00.json
@@ -0,0 +1 @@
+["_H",1,32,"Judge the PR",38]
diff --git a/products/workflows/frontend/Workflows/hogflows/panel/HogFlowEditorPanelBuildDetail.tsx b/products/workflows/frontend/Workflows/hogflows/panel/HogFlowEditorPanelBuildDetail.tsx
index bae3dd6c6694..e934d0f8cee8 100644
--- a/products/workflows/frontend/Workflows/hogflows/panel/HogFlowEditorPanelBuildDetail.tsx
+++ b/products/workflows/frontend/Workflows/hogflows/panel/HogFlowEditorPanelBuildDetail.tsx
@@ -9,6 +9,7 @@ import {
LemonCollapse,
LemonDivider,
LemonInput,
+ LemonInputSelect,
LemonLabel,
LemonSelect,
LemonSwitch,
@@ -29,7 +30,11 @@ import { hogFlowEditorLogic } from '../hogFlowEditorLogic'
import { useHogFlowStep } from '../steps/HogFlowSteps'
import { isEmailAction, isOptOutEligibleAction } from '../steps/types'
import type { HogFlowAction } from '../types'
-import { hogFlowOutputMappingLogic } from './hogFlowOutputMappingLogic'
+import {
+ WORKFLOW_VARIABLE_TYPE_OPTIONS,
+ hogFlowOutputMappingLogic,
+ sanitizeVariableKey,
+} from './hogFlowOutputMappingLogic'
import { OutputTestResultTree } from './OutputTestResultTree'
export function HogFlowEditorPanelBuildDetail(): JSX.Element | null {
@@ -40,7 +45,6 @@ export function HogFlowEditorPanelBuildDetail(): JSX.Element | null {
useValues(hogFlowOutputMappingLogic(logicProps))
const {
setSelectedActionId,
- setMappings,
updateMappingResultPath,
addMapping,
removeMapping,
@@ -49,6 +53,8 @@ export function HogFlowEditorPanelBuildDetail(): JSX.Element | null {
cancelPendingPath,
runOutputTest,
applySuggestion,
+ setMappingVariable,
+ setVariableType,
} = useActions(hogFlowOutputMappingLogic(logicProps))
useEffect(() => {
@@ -62,6 +68,9 @@ export function HogFlowEditorPanelBuildDetail(): JSX.Element | null {
}
const action = selectedNode.data
+ // A real run of this step starts an agent and parks for minutes, so the panel offers the
+ // known result fields instead of a live test call.
+ const isAiTaskAction = action.type === 'function' && action.config.template_id === 'template-posthog-create-task'
const isBranchingStep = ['conditional_branch', 'wait_until_condition', 'random_cohort_branch'].includes(action.type)
const actionFilters = action.filters ?? {}
@@ -174,32 +183,49 @@ export function HogFlowEditorPanelBuildDetail(): JSX.Element | null {
>
<div className="flex items-center gap-1">
<LemonField.Pure label="Variable" className="flex-1">
- <LemonSelect
- options={[
- { value: '', label: 'Select variable...' },
- ...(workflow.variables || [])
- .filter(
- ({ key }) =>
- key === mapping.key ||
- !mappings.some((m) => m.key === key)
- )
- .map(({ key }) => ({
- value: key,
- label: key,
- })),
- ]}
- value={mapping.key || ''}
- onChange={(value) => {
- const updated = [...mappings]
- updated[index] = {
- ...updated[index],
- key: value || '',
- }
- setMappings(updated)
- }}
+ <LemonInputSelect
+ mode="single"
+ allowCustomValues
+ placeholder="Select or type a new name"
+ formatCreateLabel={(input) =>
+ `Create variable "${input}"`
+ }
+ inputTransform={sanitizeVariableKey}
+ options={(workflow.variables || [])
+ .filter(
+ ({ key }) =>
+ key === mapping.key ||
+ !mappings.some((m) => m.key === key)
+ )
+ .map(({ key }) => ({ key, label: key }))}
+ value={mapping.key ? [mapping.key] : []}
+ onChange={([value]) =>
+ setMappingVariable(index, value || '')
+ }
size="small"
/>
</LemonField.Pure>
+ {mapping.key && (
+ <LemonField.Pure label="Type">
+ <LemonSelect
+ options={WORKFLOW_VARIABLE_TYPE_OPTIONS}
+ value={
+ WORKFLOW_VARIABLE_TYPE_OPTIONS.find(
+ ({ value }) =>
+ value ===
+ workflow.variables?.find(
+ (v) => v.key === mapping.key
+ )?.type
+ )?.value ?? null
+ }
+ placeholder="Other"
+ onChange={(type) =>
+ type && setVariableType(mapping.key, type)
+ }
+ size="small"
+ />
+ </LemonField.Pure>
+ )}
<LemonButton
icon={<IconX />}
size="small"
@@ -209,7 +235,11 @@ export function HogFlowEditorPanelBuildDetail(): JSX.Element | null {
</div>
<LemonField.Pure
label="Result path"
- info="Specify a path within the step result to store, e.g. 'body.results[0].id'. Leave blank for the entire result."
+ info={
+ isAiTaskAction
+ ? "Specify a path within the step result to store. A path like 'output.verdict' asks the agent to return that field, typed like the variable. Leave blank for the entire result."
+ : "Specify a path within the step result to store, e.g. 'body.results[0].id'. Leave blank for the entire result."
+ }
className="w-full"
>
<LemonInput
@@ -220,7 +250,9 @@ export function HogFlowEditorPanelBuildDetail(): JSX.Element | null {
prefix={<span>result.</span>}
value={mapping.result_path}
onChange={(value) => updateMappingResultPath(index, value)}
- placeholder="body.results[0].id"
+ placeholder={
+ isAiTaskAction ? 'output.verdict' : 'body.results[0].id'
+ }
size="small"
/>
</LemonField.Pure>
@@ -253,17 +285,19 @@ export function HogFlowEditorPanelBuildDetail(): JSX.Element | null {
>
Add mapping
</LemonButton>
- <LemonButton
- icon={<IconPlay />}
- size="small"
- type="primary"
- className={shakePickButton ? 'animate-shake' : ''}
- loading={testLoading}
- tooltip="Executes a real HTTP request to this step's endpoint and shows the response so you can pick which property to store."
- onClick={runOutputTest}
- >
- Pick from response
- </LemonButton>
+ {!isAiTaskAction && (
+ <LemonButton
+ icon={<IconPlay />}
+ size="small"
+ type="primary"
+ className={shakePickButton ? 'animate-shake' : ''}
+ loading={testLoading}
+ tooltip="Executes a real HTTP request to this step's endpoint and shows the response so you can pick which property to store."
+ onClick={runOutputTest}
+ >
+ Pick from response
+ </LemonButton>
+ )}
</div>
{testError && (
<LemonBanner type="error" className="w-full">
@@ -334,13 +368,12 @@ export function HogFlowEditorPanelBuildDetail(): JSX.Element | null {
)}
<LemonDivider className="my-1" />
<LemonButton
- icon={<IconPlus />}
sideIcon={<IconExternal />}
size="small"
type="secondary"
onClick={() => setMode('variables')}
>
- New variable
+ View all workflow variables
</LemonButton>
</div>
),
diff --git a/products/workflows/frontend/Workflows/hogflows/panel/HogFlowEditorPanelVariables.tsx b/products/workflows/frontend/Workflows/hogflows/panel/HogFlowEditorPanelVariables.tsx
index 9d067dfe2179..bc843b15163a 100644
--- a/products/workflows/frontend/Workflows/hogflows/panel/HogFlowEditorPanelVariables.tsx
+++ b/products/workflows/frontend/Workflows/hogflows/panel/HogFlowEditorPanelVariables.tsx
@@ -8,6 +8,7 @@ import { ScrollableShadows } from 'lib/components/ScrollableShadows/ScrollableSh
import { LemonField } from 'lib/lemon-ui/LemonField/LemonField'
import { hogFlowEditorLogic } from '../hogFlowEditorLogic'
+import { sanitizeVariableKey } from './hogFlowOutputMappingLogic'
export function HogFlowEditorPanelVariables(): JSX.Element | null {
const { workflow } = useValues(hogFlowEditorLogic)
@@ -29,7 +30,7 @@ export function HogFlowEditorPanelVariables(): JSX.Element | null {
}
const editVariableKey = (idx: number, key: string): void => {
- const sanitizedKey = key.replace(/\s+/g, '_')
+ const sanitizedKey = sanitizeVariableKey(key)
setWorkflowInfo({
variables: (workflow?.variables || []).map((variable, index) =>
index === idx ? { ...variable, key: sanitizedKey, label: sanitizedKey } : variable
diff --git a/products/workflows/frontend/Workflows/hogflows/panel/hogFlowOutputMappingLogic.test.ts b/products/workflows/frontend/Workflows/hogflows/panel/hogFlowOutputMappingLogic.test.ts
index 712b13999624..2220f5d77c11 100644
--- a/products/workflows/frontend/Workflows/hogflows/panel/hogFlowOutputMappingLogic.test.ts
+++ b/products/workflows/frontend/Workflows/hogflows/panel/hogFlowOutputMappingLogic.test.ts
@@ -487,6 +487,55 @@ describe('hogFlowOutputMappingLogic', () => {
})
})
+ describe('setMappingVariable', () => {
+ it('creates the workflow variable when the name is new, then maps and persists it', async () => {
+ const node = makeActionNode('action-new-var')
+ await expectLogic(editorLogic, () => {
+ editorLogic.actions.setNodesRaw([node])
+ editorLogic.actions.setSelectedNodeId('action-new-var')
+ }).toMatchValues({ selectedNode: node })
+ logic.actions.initMappings([{ key: '', result_path: 'output.verdict' }])
+
+ await expectLogic(logic, () => {
+ logic.actions.setMappingVariable(0, 'verdict')
+ })
+ .toDispatchActions([
+ (action: any) => action.type === wfLogic.actionCreators.setWorkflowAction('', {} as any).type,
+ ])
+ .toMatchValues({ mappings: [{ key: 'verdict', result_path: 'output.verdict' }] })
+
+ expect(wfLogic.values.workflow.variables).toEqual([
+ { key: 'verdict', label: 'verdict', type: 'string', default: '' },
+ ])
+ })
+
+ it('drops a pick of a variable another mapping already stores into', async () => {
+ logic.actions.initMappings([
+ { key: 'verdict', result_path: 'output.verdict' },
+ { key: '', result_path: 'output.score' },
+ ])
+
+ logic.actions.setMappingVariable(1, 'verdict')
+
+ expect(logic.values.mappings).toEqual([
+ { key: 'verdict', result_path: 'output.verdict' },
+ { key: '', result_path: 'output.score' },
+ ])
+ })
+
+ it('changes the type of the mapped variable in place', async () => {
+ wfLogic.actions.setWorkflowInfo({
+ variables: [{ key: 'score', label: 'Score', type: 'string', default: '' }],
+ })
+
+ logic.actions.setVariableType('score', 'number')
+
+ expect(wfLogic.values.workflow.variables).toEqual([
+ { key: 'score', label: 'Score', type: 'number', default: '' },
+ ])
+ })
+ })
+
describe('addMapping and removeMapping', () => {
it('addMapping appends an empty mapping to the existing list', async () => {
logic.actions.initMappings([{ key: 'existing', result_path: 'x' }])
diff --git a/products/workflows/frontend/Workflows/hogflows/panel/hogFlowOutputMappingLogic.ts b/products/workflows/frontend/Workflows/hogflows/panel/hogFlowOutputMappingLogic.ts
index 50ed79be17ec..429cbee5e1ae 100644
--- a/products/workflows/frontend/Workflows/hogflows/panel/hogFlowOutputMappingLogic.ts
+++ b/products/workflows/frontend/Workflows/hogflows/panel/hogFlowOutputMappingLogic.ts
@@ -15,6 +15,19 @@ import type { HogFlow, HogFlowActionNode } from '../types'
import { hogFlowEditorTestLogic } from './testing/hogFlowEditorTestLogic'
export type OutputMapping = { key: string; result_path: string; spread?: boolean | null }
+// The variable types the output schema of an AI task step can express. Other input types stay
+// selectable only from the variables tab.
+export type WorkflowVariableType = 'string' | 'number' | 'boolean'
+export const WORKFLOW_VARIABLE_TYPE_OPTIONS: { value: WorkflowVariableType; label: string }[] = [
+ { value: 'string', label: 'Text' },
+ { value: 'number', label: 'Number' },
+ { value: 'boolean', label: 'True or false' },
+]
+
+// A key must be addressable as `variables.<key>` in a template, so only identifier characters survive.
+export function sanitizeVariableKey(key: string): string {
+ return key.replace(/[^A-Za-z0-9_]+/g, '_')
+}
export function normalizeOutputVariable(raw: HogFlowAction['output_variable']): OutputMapping[] {
if (!raw) {
@@ -94,6 +107,13 @@ export interface hogFlowOutputMappingLogicActions {
selectPath: (path: string) => {
path: string
}
+ setMappingVariable: (
+ index: number,
+ key: string
+ ) => {
+ index: number
+ key: string
+ }
setMappings: (mappings: OutputMapping[]) => {
mappings: OutputMapping[]
}
@@ -112,6 +132,13 @@ export interface hogFlowOutputMappingLogicActions {
setTestResultData: (data: unknown | null) => {
data: unknown
}
+ setVariableType: (
+ key: string,
+ type: WorkflowVariableType
+ ) => {
+ key: string
+ type: WorkflowVariableType
+ }
triggerShake: () => {
value: true
}
@@ -171,6 +198,8 @@ export const hogFlowOutputMappingLogic = kea<hogFlowOutputMappingLogicType>([
initMappings: (mappings: OutputMapping[]) => ({ mappings }),
setMappings: (mappings: OutputMapping[]) => ({ mappings }),
updateMappingResultPath: (index: number, path: string) => ({ index, path }),
+ setMappingVariable: (index: number, key: string) => ({ index, key }),
+ setVariableType: (key: string, type: WorkflowVariableType) => ({ key, type }),
addMapping: true,
removeMapping: (index: number) => ({ index }),
selectPath: (path: string) => ({ path }),
@@ -235,6 +264,15 @@ export const hogFlowOutputMappingLogic = kea<hogFlowOutputMappingLogicType>([
updated[index] = { ...updated[index], result_path: path }
return updated
},
+ setMappingVariable: (state, { index, key }) => {
+ // Two rows storing into one variable would race; the second pick is dropped.
+ if (key && state.some((mapping, i) => i !== index && mapping.key === key)) {
+ return state
+ }
+ const updated = [...state]
+ updated[index] = { ...updated[index], key }
+ return updated
+ },
addMapping: (state) => [...state, { key: '', result_path: '' }],
removeMapping: (state, { index }) => state.filter((_, i) => i !== index),
assignPendingPathToMapping: (state) => state,
@@ -310,6 +348,18 @@ export const hogFlowOutputMappingLogic = kea<hogFlowOutputMappingLogicType>([
} as HogFlowAction)
}
+ // A mapping can name a variable the workflow does not have yet. Creating it here keeps the
+ // author on the step instead of sending them to the variables tab and back.
+ const ensureVariable = (key: string, label: string): void => {
+ const existingVars = values.workflow.variables ?? []
+ if (existingVars.some((v) => v.key === key)) {
+ return
+ }
+ workflowLogic(props).actions.setWorkflowInfo({
+ variables: [...existingVars, { key, label, type: 'string' as const, default: '' }],
+ })
+ }
+
return {
setSelectedActionId: () => {
const selectedNode = values.selectedNode
@@ -325,6 +375,18 @@ export const hogFlowOutputMappingLogic = kea<hogFlowOutputMappingLogicType>([
persistMappings(values.mappings)
actions.triggerShake()
},
+ setMappingVariable: ({ key }) => {
+ if (key) {
+ ensureVariable(key, key)
+ }
+ persistMappings(values.mappings)
+ },
+ setVariableType: ({ key, type }) => {
+ const existingVars = values.workflow.variables ?? []
+ workflowLogic(props).actions.setWorkflowInfo({
+ variables: existingVars.map((v) => (v.key === key ? { ...v, type } : v)),
+ })
+ },
addMapping: () => {
persistMappings(values.mappings)
},
@@ -355,19 +417,8 @@ export const hogFlowOutputMappingLogic = kea<hogFlowOutputMappingLogicType>([
}
},
applySuggestion: ({ suggestion }) => {
- const newMappings = [...values.mappings, { key: suggestion.key, result_path: suggestion.result_path }]
- actions.setMappings(newMappings)
-
- const { workflow } = values
- const existingVars = workflow.variables ?? []
- if (!existingVars.some((v) => v.key === suggestion.key)) {
- workflowLogic(props).actions.setWorkflowInfo({
- variables: [
- ...existingVars,
- { key: suggestion.key, label: suggestion.label, type: 'string' as const, default: '' },
- ],
- })
- }
+ actions.setMappings([...values.mappings, { key: suggestion.key, result_path: suggestion.result_path }])
+ ensureVariable(suggestion.key, suggestion.label)
},
runOutputTest: async () => {
const { selectedNode, workflow, hogFunctionTemplatesById } = values