: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): compare ai task instructions with past versions (#113845)
Chris Shine838473a4b27d
diff --git a/products/workflows/frontend/Workflows/hogflows/steps/StepFunction.tsx b/products/workflows/frontend/Workflows/hogflows/steps/StepFunction.tsxindex 1d5af921ef27..62b97960bd24 100644--- a/products/workflows/frontend/Workflows/hogflows/steps/StepFunction.tsx+++ b/products/workflows/frontend/Workflows/hogflows/steps/StepFunction.tsx@@ -1,6 +1,7 @@import { useActions, useValues } from 'kea'import { workflowLogic } from '../../workflowLogic'+import { AiTaskInstructionsCompare } from './components/AiTaskInstructionsCompare'import { HogFlowFunctionConfiguration } from './components/HogFlowFunctionConfiguration'import { StepSchemaErrors } from './components/StepSchemaErrors'import { StepFunctionNode } from './hogFunctionStepLogic'@@ -17,6 +18,7 @@ export function StepFunctionConfiguration({ node }: { node: StepFunctionNode }):return (<><StepSchemaErrors />+ {templateId === 'template-posthog-create-task' && <AiTaskInstructionsCompare actionId={node.id} />}<HogFlowFunctionConfiguration// Remount per node: the input renderer snapshots its values on mount, so switching to// another step of the same template must remount to show the newly selected node's inputs.diff --git a/products/workflows/frontend/Workflows/hogflows/steps/components/AiTaskInstructionsCompare.tsx b/products/workflows/frontend/Workflows/hogflows/steps/components/AiTaskInstructionsCompare.tsxnew file mode 100644index 000000000000..6debb8133d2e--- /dev/null+++ b/products/workflows/frontend/Workflows/hogflows/steps/components/AiTaskInstructionsCompare.tsx@@ -0,0 +1,128 @@+import { useActions, useValues } from 'kea'++import { IconClock } from '@posthog/icons'+import { LemonButton, LemonSelect, LemonSkeleton } from '@posthog/lemon-ui'++import { ErrorBoundary } from '~/layout/ErrorBoundary'++import { workflowLogic } from '../../../workflowLogic'+import { aiTaskInstructionsCompareLogic, findAiTaskPrompt } from './aiTaskInstructionsCompareLogic'+import { InstructionsDiff } from './InstructionsDiff'++// Fills the h-64 result box under the one-line legend, so the editor is the only scroll area in the box.+const DIFF_HEIGHT = 'calc(16rem - 1.25rem - 2px)'++export function AiTaskInstructionsCompare({ actionId }: { actionId: string }): JSX.Element | null {+ const { logicProps, originalWorkflow, workflow, externallyEdited } = useValues(workflowLogic)+ const logic = aiTaskInstructionsCompareLogic({ workflowId: logicProps.id ?? 'new', actionId })+ const {+ isOpen,+ selectedVersion,+ revisionOptions,+ revisionsResponse,+ revisionsResponseLoading,+ revisionsLoadFailed,+ selectedRevisionPrompt,+ revisionLoadFailed,+ } = useValues(logic)+ const { setOpen, selectVersion, loadRevision, loadRevisions } = useActions(logic)++ // The default comparison is with the live version, and only an active workflow runs one.+ if (!originalWorkflow || originalWorkflow.status !== 'active') {+ return null+ }++ const livePrompt = findAiTaskPrompt(originalWorkflow.actions, actionId)+ const currentPrompt = findAiTaskPrompt(workflow.actions, actionId) ?? ''++ if (!isOpen) {+ return (+ <div>+ <LemonButton+ size="small"+ type="secondary"+ icon={<IconClock />}+ // Compared with live, unchanged instructions only say "No differences", so open on a past version.+ onClick={() => setOpen(true, currentPrompt === livePrompt ? originalWorkflow.version : null)}+ data-attr="workflow-ai-task-compare-open"+ >+ Compare instructions with another version+ </LemonButton>+ </div>+ )+ }++ const comparedPrompt = selectedVersion === null ? livePrompt : selectedRevisionPrompt+ const versionName = selectedVersion === null ? 'the live version' : `v${selectedVersion}`+ // The editor's live copy can be older than the list, which loads on each open. A newer version is not+ // past, and listing it would sit beside a stale "Live version" label.+ const pastVersionOptions = revisionOptions.filter((option) => option.value < originalWorkflow.version)++ return (+ <div className="flex flex-col gap-2 rounded border p-2" data-attr="workflow-ai-task-compare">+ <div className="flex flex-wrap items-center gap-2">+ <span className="text-sm font-semibold">Compare instructions with</span>+ <LemonSelect<number | null>+ size="small"+ value={selectedVersion}+ onChange={selectVersion}+ loading={revisionsResponseLoading && !revisionsResponse}+ aria-label="Version to compare with"+ options={[+ { value: null, label: `Live version (v${originalWorkflow.version})` },+ ...pastVersionOptions,+ ]}+ data-attr="workflow-ai-task-compare-version"+ />+ <LemonButton size="small" type="tertiary" className="ml-auto" onClick={() => setOpen(false)}>+ Close+ </LemonButton>+ </div>+ {externallyEdited && (+ <span className="text-xs text-warning">+ This workflow changed elsewhere, so the live version here may be out of date.+ </span>+ )}+ {revisionsResponse && !revisionsLoadFailed && pastVersionOptions.length === 0 && (+ <span className="text-xs text-secondary">+ No past versions yet. One is saved each time the live workflow changes.+ </span>+ )}+ {revisionsLoadFailed && (+ <div className="flex flex-wrap items-center gap-2">+ <span className="text-sm text-danger">Couldn't load past versions.</span>+ <LemonButton size="xsmall" type="secondary" onClick={() => loadRevisions()}>+ Try again+ </LemonButton>+ </div>+ )}+ {/* A fixed height keeps the Instructions field below in place while the diff follows each keystroke. */}+ <div className="ph-no-capture h-64 overflow-auto">+ {selectedVersion !== null && revisionLoadFailed ? (+ <div className="flex flex-wrap items-center gap-2">+ <span className="text-sm text-danger">{`Couldn't load ${versionName}.`}</span>+ <LemonButton size="xsmall" type="secondary" onClick={() => loadRevision(selectedVersion)}>+ Try again+ </LemonButton>+ </div>+ ) : comparedPrompt === undefined ? (+ <LemonSkeleton className="h-24 w-full" />+ ) : comparedPrompt === null ? (+ <span className="text-sm text-secondary">{`This AI task step isn't in ${versionName}.`}</span>+ ) : comparedPrompt === currentPrompt ? (+ <span className="text-sm text-secondary">{`No differences from ${versionName}.`}</span>+ ) : (+ <div className="flex flex-col gap-1">+ <span className="text-xs text-secondary">+ {`Removed lines are from ${versionName}. Added lines are in this step now.`}+ </span>+ {/* Keeps a failed editor load inside this box, so the rest of the step panel stays usable. */}+ <ErrorBoundary>+ <InstructionsDiff before={comparedPrompt} after={currentPrompt} height={DIFF_HEIGHT} />+ </ErrorBoundary>+ </div>+ )}+ </div>+ </div>+ )+}diff --git a/products/workflows/frontend/Workflows/hogflows/steps/components/InstructionsDiff.tsx b/products/workflows/frontend/Workflows/hogflows/steps/components/InstructionsDiff.tsxnew file mode 100644index 000000000000..b023bb5ee8eb--- /dev/null+++ b/products/workflows/frontend/Workflows/hogflows/steps/components/InstructionsDiff.tsx@@ -0,0 +1,69 @@+import clsx from 'clsx'+import { Suspense } from 'react'++import { LemonSkeleton } from '@posthog/lemon-ui'++import type { MonacoDiffEditorProps } from 'lib/components/MonacoDiffEditor'+import { useBodyIsDark } from 'lib/hooks/useBodyIsDark'+import { lazyWithRetry } from 'lib/utils/retryImport'++const MonacoDiffEditor = lazyWithRetry(() => import('lib/components/MonacoDiffEditor'))++const DIFF_OPTIONS: MonacoDiffEditorProps['options'] = {+ readOnly: true,+ renderSideBySide: false,+ minimap: { enabled: false },+ scrollBeyondLastLine: false,+ wordWrap: 'on',+ lineNumbers: 'off',+ folding: false,+ hideUnchangedRegions: { enabled: true },+ // The editor sizes itself to the diff after first layout. Without this, Monaco keeps its first+ // measured height and cuts off the last lines.+ automaticLayout: true,+ scrollbar: { alwaysConsumeMouseWheel: false },+ // The compare panel treats any difference in the text as a change, so the diff must show whitespace-only edits too.+ ignoreTrimWhitespace: false,+}++export function InstructionsDiff({+ before,+ after,+ height,+}: {+ before: string+ after: string+ height: MonacoDiffEditorProps['height']+}): JSX.Element {+ const isDarkMode = useBodyIsDark()++ // Monaco reads empty text as one blank line, so a diff against it would show that line as changed.+ // With nothing on one side, the whole text is either added or removed.+ if (!before || !after) {+ return (+ <div className={clsx('rounded border', before ? 'bg-fill-error-highlight' : 'bg-fill-success-highlight')}>+ <div className="px-2 pt-2 text-xs font-semibold">+ {before ? 'Instructions removed' : 'New instructions'}+ </div>+ <pre className="m-0 p-2 whitespace-pre-wrap break-words font-mono text-xs">{before || after}</pre>+ </div>+ )+ }++ return (+ <div className="overflow-hidden rounded border">+ <Suspense fallback={<LemonSkeleton className="h-24 w-full" />}>+ <MonacoDiffEditor+ original={before}+ value={after}+ modified={after}+ language="markdown"+ theme={isDarkMode ? 'vs-dark' : 'vs'}+ options={DIFF_OPTIONS}+ height={height}+ loading={<LemonSkeleton className="h-24 w-full" />}+ />+ </Suspense>+ </div>+ )+}diff --git a/products/workflows/frontend/Workflows/hogflows/steps/components/aiTaskInstructionsCompareLogic.test.ts b/products/workflows/frontend/Workflows/hogflows/steps/components/aiTaskInstructionsCompareLogic.test.tsnew file mode 100644index 000000000000..080faa249a29--- /dev/null+++ b/products/workflows/frontend/Workflows/hogflows/steps/components/aiTaskInstructionsCompareLogic.test.ts@@ -0,0 +1,101 @@+import { expectLogic } from 'kea-test-utils'++import { resumeKeaLoadersErrors, silenceKeaLoadersErrors } from '~/initKea'+import { useMocks } from '~/mocks/jest'+import { initKeaTests } from '~/test/init'++import type { HogFlowAction } from '../../types'+import { aiTaskInstructionsCompareLogic } from './aiTaskInstructionsCompareLogic'++const LIST_URL = '/api/environments/:team_id/hog_flows/:id/revisions/'+const REVISION_URL = '/api/environments/:team_id/hog_flows/:id/revisions/:version/'++const revisionList = (versions: number[]): Record<string, unknown> => ({+ count: versions.length,+ next: null,+ previous: null,+ results: versions.map((version) => ({ version, created_at: '2026-09-01T10:00:00Z', created_by: null })),+})++const aiTask = (id: string, prompt: string): HogFlowAction => ({+ id,+ type: 'function',+ name: `Step ${id}`,+ description: '',+ created_at: 0,+ updated_at: 0,+ config: { template_id: 'template-posthog-create-task', inputs: { prompt: { value: prompt } } },+})++describe('aiTaskInstructionsCompareLogic', () => {+ afterEach(resumeKeaLoadersErrors)++ it.each([+ ['the instructions of the step in that version', [aiTask('triage', 'Old instructions')], 'Old instructions'],+ ['null when the step is not in that version', [aiTask('other', 'Something else')], null],+ ['null when the stored step has no config', [{ id: 'triage', type: 'function', name: 'Step triage' }], null],+ ])('selecting a past version yields %s', async (_, actions, expected) => {+ useMocks({ get: { [REVISION_URL]: { version: 2, created_at: '', created_by: null, content: { actions } } } })+ initKeaTests()+ const logic = aiTaskInstructionsCompareLogic({ workflowId: 'wf-1', actionId: 'triage' })+ logic.mount()++ await expectLogic(logic, () => logic.actions.selectVersion(2)).toDispatchActions(['loadRevisionSuccess'])++ expect(logic.values.selectedRevisionPrompt).toEqual(expected)+ })++ it('reloads the version list on every open, so a version published since the last open shows', async () => {+ let published: number[] = [1]+ useMocks({+ get: {+ [LIST_URL]: () => [200, revisionList(published)],+ },+ })+ initKeaTests()+ const logic = aiTaskInstructionsCompareLogic({ workflowId: 'wf-1', actionId: 'triage' })+ logic.mount()++ await expectLogic(logic, () => logic.actions.setOpen(true)).toDispatchActions(['loadRevisionsSuccess'])+ logic.actions.setOpen(false)+ published = [2, 1]+ await expectLogic(logic, () => logic.actions.setOpen(true)).toDispatchActions(['loadRevisionsSuccess'])++ expect(logic.values.revisionOptions.map((option) => option.value)).toEqual([2, 1])+ })++ it.each([+ ['the newest version below live', [3, 2, 1], 2],+ ['live when no version is below live', [3], null],+ ])('opening with instructions that match live selects %s', async (_, versions, expected) => {+ useMocks({+ get: {+ [LIST_URL]: () => [200, revisionList(versions)],+ [REVISION_URL]: { version: 2, created_at: '', created_by: null, content: { actions: [] } },+ },+ })+ initKeaTests()+ const logic = aiTaskInstructionsCompareLogic({ workflowId: 'wf-1', actionId: 'triage' })+ logic.mount()++ await expectLogic(logic, () => logic.actions.setOpen(true, 3)).toDispatchActions(['loadRevisionsSuccess'])++ expect(logic.values.selectedVersion).toBe(expected)+ })++ it('reports a failed version load, and clears it on switching to the live version', async () => {+ useMocks({ get: { [REVISION_URL]: () => [500, { detail: 'error' }] } })+ initKeaTests()+ silenceKeaLoadersErrors()+ const logic = aiTaskInstructionsCompareLogic({ workflowId: 'wf-1', actionId: 'triage' })+ logic.mount()++ await expectLogic(logic, () => logic.actions.selectVersion(2)).toDispatchActions(['loadRevisionFailure'])++ expect(logic.values.revisionLoadFailed).toBe(true)++ logic.actions.selectVersion(null)++ expect(logic.values.revisionLoadFailed).toBe(false)+ })+})diff --git a/products/workflows/frontend/Workflows/hogflows/steps/components/aiTaskInstructionsCompareLogic.ts b/products/workflows/frontend/Workflows/hogflows/steps/components/aiTaskInstructionsCompareLogic.tsnew file mode 100644index 000000000000..23959b3d43a4--- /dev/null+++ b/products/workflows/frontend/Workflows/hogflows/steps/components/aiTaskInstructionsCompareLogic.ts@@ -0,0 +1,286 @@+import { MakeLogicType, actions, connect, kea, key, listeners, path, props, reducers, selectors } from 'kea'+import { loaders } from 'kea-loaders'+import posthog from 'posthog-js'++import { dayjs } from 'lib/dayjs'+import { teamLogic } from 'scenes/teamLogic'++import { hogFlowsRevisionsList, hogFlowsRevisionsRetrieve } from '../../../../generated/api'+import type {+ HogFlowRevisionApi,+ HogFlowRevisionBasicApi,+ PaginatedHogFlowRevisionBasicListApi,+} from '../../../../generated/api.schemas'+import type { HogFlow, HogFlowAction } from '../../types'++export interface AiTaskInstructionsCompareLogicProps {+ workflowId: string+ actionId: string+}++/** The step's instructions in a list of actions, or null when the step is not an AI task there. */+export function findAiTaskPrompt(actions: HogFlowAction[] | undefined, actionId: string): string | null {+ // Version snapshots are stored as loose JSON, so every level is checked before use.+ const action = Array.isArray(actions) ? actions.find((candidate) => candidate?.id === actionId) : undefined+ if (action?.type !== 'function' || action.config?.template_id !== 'template-posthog-create-task') {+ return null+ }+ const value = action.config.inputs?.prompt?.value+ // A prompt written through the API can use CRLF line endings, and the editor saves LF. The diff+ // cannot show that difference, so it must not count as a change.+ return typeof value === 'string' ? value.replace(/\r\n?/g, '\n') : ''+}++type CompareTrigger = 'open' | 'select_version'++function captureCompared(workflowId: string, version: number | null, trigger: CompareTrigger): void {+ // pinned: analytics event name+ posthog.capture('workflows ai task instructions compared', {+ workflow_id: workflowId,+ compared_version: version === null ? 'live' : String(version),+ trigger,+ })+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface aiTaskInstructionsCompareLogicValues {+ currentTeamIdStrict: number | string // teamLogic+ isOpen: boolean+ revision: HogFlowRevisionApi | null+ revisionLoadFailed: boolean+ revisionLoading: boolean+ revisionOptions: {+ label: string+ labelInMenu: string+ value: number+ }[]+ revisions: HogFlowRevisionBasicApi[]+ revisionsLoadFailed: boolean+ revisionsResponse: PaginatedHogFlowRevisionBasicListApi | null+ revisionsResponseLoading: boolean+ selectedRevisionPrompt: string | null | undefined+ selectedVersion: number | null+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface aiTaskInstructionsCompareLogicActions {+ loadRevision: (version: number) => number+ loadRevisionFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ loadRevisionSuccess: (+ revision: HogFlowRevisionApi,+ payload?: number+ ) => {+ revision: HogFlowRevisionApi+ payload?: number+ }+ loadRevisions: () => any+ loadRevisionsFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ loadRevisionsSuccess: (+ revisionsResponse: PaginatedHogFlowRevisionBasicListApi,+ payload?: any+ ) => {+ revisionsResponse: PaginatedHogFlowRevisionBasicListApi+ payload?: any+ }+ selectVersion: (+ version: number | null,+ trigger?: CompareTrigger+ ) => {+ trigger: CompareTrigger+ version: number | null+ }+ setOpen: (+ open: boolean,+ newestPastBelow?: number | null+ ) => {+ newestPastBelow: number | null+ open: boolean+ }+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface aiTaskInstructionsCompareLogicMeta {+ key: string+ __keaTypeGenInternalSelectorTypes: {+ revisions: (revisionsResponse: PaginatedHogFlowRevisionBasicListApi | null) => HogFlowRevisionBasicApi[]+ revisionOptions: (revisions: HogFlowRevisionBasicApi[]) => {+ label: string+ labelInMenu: string+ value: number+ }[]+ selectedRevisionPrompt: (+ selectedVersion: number | null,+ revision: HogFlowRevisionApi | null,+ arg: any+ ) => string | null | undefined+ }+}++export type aiTaskInstructionsCompareLogicType = MakeLogicType<+ aiTaskInstructionsCompareLogicValues,+ aiTaskInstructionsCompareLogicActions,+ AiTaskInstructionsCompareLogicProps,+ aiTaskInstructionsCompareLogicMeta+>++export const aiTaskInstructionsCompareLogic = kea<aiTaskInstructionsCompareLogicType>([+ path((key) => [+ 'products',+ 'workflows',+ 'frontend',+ 'Workflows',+ 'hogflows',+ 'steps',+ 'components',+ 'aiTaskInstructionsCompareLogic',+ key,+ ]),+ props({} as AiTaskInstructionsCompareLogicProps),+ key(({ workflowId, actionId }) => `${workflowId}:${actionId}`),+ connect(() => ({+ values: [teamLogic, ['currentTeamIdStrict']],+ })),+ actions({+ // With newestPastBelow set, the panel opens on the newest version below it once the list loads.+ setOpen: (open: boolean, newestPastBelow: number | null = null) => ({ open, newestPastBelow }),+ // null compares with the live version, which the editor already holds.+ selectVersion: (version: number | null, trigger: CompareTrigger = 'select_version') => ({ version, trigger }),+ }),+ reducers({+ isOpen: [false, { setOpen: (_, { open }) => open }],+ selectedVersion: [null as number | null, { selectVersion: (_, { version }) => version }],+ revisionLoadFailed: [+ false,+ {+ selectVersion: () => false,+ loadRevision: () => false,+ loadRevisionFailure: () => true,+ },+ ],+ revisionsLoadFailed: [+ false,+ {+ loadRevisions: () => false,+ loadRevisionsFailure: () => true,+ },+ ],+ }),+ loaders(({ props, values }) => ({+ revisionsResponse: [+ null as PaginatedHogFlowRevisionBasicListApi | null,+ {+ // 500 is the endpoint's page limit.+ loadRevisions: async () =>+ await hogFlowsRevisionsList(String(values.currentTeamIdStrict), props.workflowId, { limit: 500 }),+ },+ ],+ revision: [+ null as HogFlowRevisionApi | null,+ {+ loadRevision: async (version: number, breakpoint) => {+ // A response for a version the user has since moved away from must not land, whether it+ // succeeded or failed, so each call checks the breakpoint once its request settles.+ try {+ const revision = await hogFlowsRevisionsRetrieve(+ String(values.currentTeamIdStrict),+ props.workflowId,+ version+ )+ breakpoint()+ return revision+ } catch (error) {+ breakpoint()+ throw error+ }+ },+ },+ ],+ })),+ selectors({+ revisions: [+ (s) => [s.revisionsResponse],+ (response: PaginatedHogFlowRevisionBasicListApi | null): HogFlowRevisionBasicApi[] =>+ response?.results ?? [],+ ],+ revisionOptions: [+ (s) => [s.revisions],+ (revisions: HogFlowRevisionBasicApi[]): { value: number; label: string; labelInMenu: string }[] =>+ revisions.map((revision) => ({+ value: revision.version,+ label: `v${revision.version}`,+ labelInMenu: `v${revision.version} · ${dayjs(revision.created_at).format('MMM D, YYYY, h:mm A')}`,+ })),+ ],+ // undefined while the chosen version loads, and null when the step is not an AI task in it.+ selectedRevisionPrompt: [+ (s) => [s.selectedVersion, s.revision, (_, props) => props.actionId],+ (+ selectedVersion: number | null,+ revision: HogFlowRevisionApi | null,+ actionId: string+ ): string | null | undefined =>+ selectedVersion === null || revision?.version !== selectedVersion+ ? undefined+ : findAiTaskPrompt((revision.content as Partial<HogFlow> | null)?.actions, actionId),+ ],+ }),+ listeners(({ actions, values, props, cache }) => ({+ setOpen: ({ open, newestPastBelow }) => {+ if (!open) {+ cache.newestPastBelow = null+ return+ }+ // Reload on every open, because a publish since the last open adds a version.+ if (!values.revisionsResponseLoading) {+ actions.loadRevisions()+ }+ if (newestPastBelow !== null && values.selectedVersion === null) {+ cache.newestPastBelow = newestPastBelow+ return+ }+ captureCompared(props.workflowId, values.selectedVersion, 'open')+ },+ loadRevisionsSuccess: () => {+ const below: number | null = cache.newestPastBelow ?? null+ if (below === null) {+ return+ }+ cache.newestPastBelow = null+ // The list comes newest first.+ const newestPast = values.revisions.find((revision) => revision.version < below)+ if (newestPast && values.selectedVersion === null) {+ actions.selectVersion(newestPast.version, 'open')+ } else {+ captureCompared(props.workflowId, values.selectedVersion, 'open')+ }+ },+ loadRevisionsFailure: () => {+ if (cache.newestPastBelow != null) {+ cache.newestPastBelow = null+ captureCompared(props.workflowId, values.selectedVersion, 'open')+ }+ },+ selectVersion: ({ version, trigger }) => {+ // A version the user picks wins over the default that waits for the list.+ if (trigger === 'select_version') {+ cache.newestPastBelow = null+ }+ if (version !== null) {+ actions.loadRevision(version)+ }+ captureCompared(props.workflowId, version, trigger)+ },+ })),+])