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): start new workflows from a PostHog AI composer behind an experiment flag (#101217)

Harley Alexander16f4af657741
diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsx
index 16c519290cab..26e81277da12 100644
--- a/frontend/src/lib/constants.tsx
+++ b/frontend/src/lib/constants.tsx
@@ -572,6 +572,7 @@ export const FEATURE_FLAGS = {
WIZARD_UI_ENABLED: 'wizard-ui-enabled', // owner: @fercgomes #team-growth — gates the /wizard/runs interface and its sidebar entry
WORKFLOW_AI_TASK_ACTION: 'workflow-ai-task-action', // owner: @mayteio #team-workflows
WORKFLOW_RUN_SCOUT_ACTION: 'workflow-run-scout-action', // owner: #team-workflows
+ WORKFLOWS_AI_FIRST_NEW: 'workflows-ai-first-new', // owner: @mayteio #team-workflows
WORKFLOWS_DELAY_UNTIL_DATE: 'workflows-delay-until-date', // owner: @dmarchuk #team-workflows
WORKFLOWS_EMAIL_REPUTATION: 'workflows-email-reputation', // owner: #team-workflows
WORKFLOWS_EMAIL_SENDER_ROTATION: 'workflows-email-sender-rotation', // owner: @arthurdedeus #team-workflows
diff --git a/frontend/src/scenes/max/useSceneAgentPanel.ts b/frontend/src/scenes/max/useSceneAgentPanel.ts
index c7c0be930f8d..011b55e8eb76 100644
--- a/frontend/src/scenes/max/useSceneAgentPanel.ts
+++ b/frontend/src/scenes/max/useSceneAgentPanel.ts
@@ -1,7 +1,12 @@
import { useActions, useValues } from 'kea'
import { useEffect } from 'react'
-import { useAttachedContext, useWelcomeOverride } from 'products/posthog_ai/frontend/api/logics'
+import {
+ ComposerOverride,
+ useAttachedContext,
+ useComposerOverride,
+ useWelcomeOverride,
+} from 'products/posthog_ai/frontend/api/logics'
import { AttachedContextItem } from 'products/posthog_ai/frontend/api/types'
import { sceneAgentPanelLogic } from './sceneAgentPanelLogic'
@@ -13,6 +18,8 @@ export interface SceneAgentPanelOptions {
contextItems: AttachedContextItem[] | null
/** Contextual welcome headlines for the composer's empty state; defaults apply when omitted. */
headlines?: string[]
+ /** Contextual composer override (suggestions, repo picker) for the empty state; a module-level constant. */
+ composer?: ComposerOverride
/** When false, nothing is attached or opened (e.g. while the entity is still loading). Defaults to true. */
active?: boolean
/** Set false to attach context without auto-opening the panel. Defaults to true. */
@@ -30,6 +37,7 @@ export function useSceneAgentPanel({
sceneKey,
contextItems,
headlines,
+ composer,
active = true,
autoOpen = true,
}: SceneAgentPanelOptions): void {
@@ -37,6 +45,7 @@ export function useSceneAgentPanel({
const { sceneEntered, sceneLeft } = useActions(sceneAgentPanelLogic)
useAttachedContext(contextItems, { active: active && sceneIntegrationEnabled })
useWelcomeOverride(headlines ?? null, { active: active && sceneIntegrationEnabled })
+ useComposerOverride(composer ?? null, { active: active && sceneIntegrationEnabled })
useEffect(() => {
// Deliberately not gated on sceneIntegrationEnabled: the logic decides eligibility itself,
diff --git a/products/posthog_ai/frontend/api/logics.ts b/products/posthog_ai/frontend/api/logics.ts
index ce35a813e58c..3dea851d5c6d 100644
--- a/products/posthog_ai/frontend/api/logics.ts
+++ b/products/posthog_ai/frontend/api/logics.ts
@@ -38,6 +38,11 @@ export { attachedContextItemKey } from '../types/contextTypes'
export { welcomeOverrideLogic } from '../logics/welcomeOverrideLogic'
export { useWelcomeOverride } from '../hooks/useWelcomeOverride'
export type { UseWelcomeOverrideOptions } from '../hooks/useWelcomeOverride'
+// Contextual composer overrides (suggestions, repo picker), the sibling of the welcome headline override above.
+export { composerOverrideLogic } from '../logics/composerOverrideLogic'
+export type { ComposerOverride } from '../logics/composerOverrideLogic'
+export { useComposerOverride } from '../hooks/useComposerOverride'
+export type { UseComposerOverrideOptions } from '../hooks/useComposerOverride'
// The standing "act via tool calls" instruction the sidebar surfaces attach while the user watches a
// run — the prompt-side half of `useMcpToolApplyBack` (hidden from chips, deduped once per task).
export { AGENT_TOOL_APPLY_BACK_CONTEXT_ITEM, wrapWithPosthogContext } from '../utils/posthogContextBlock'
diff --git a/products/posthog_ai/frontend/hooks/useComposerOverride.ts b/products/posthog_ai/frontend/hooks/useComposerOverride.ts
new file mode 100644
index 000000000000..e17377e947d6
--- /dev/null
+++ b/products/posthog_ai/frontend/hooks/useComposerOverride.ts
@@ -0,0 +1,32 @@
+import { useActions } from 'kea'
+import { useEffect, useRef } from 'react'
+
+import { uuid } from 'lib/utils/dom'
+
+import { ComposerOverride, composerOverrideLogic } from '../logics/composerOverrideLogic'
+
+export interface UseComposerOverrideOptions {
+ /** When false, the provider is deregistered (defaults apply). Defaults to true. */
+ active?: boolean
+}
+
+/** Registers a composer override for this mount. Pass a module-level constant: registration is keyed on object identity. */
+export function useComposerOverride(override: ComposerOverride | null, options?: UseComposerOverrideOptions): void {
+ const active = options?.active ?? true
+ const { registerComposerOverride, deregisterComposerOverride } = useActions(composerOverrideLogic)
+ const providerIdRef = useRef<string>(`composer-${uuid()}`)
+
+ useEffect(() => {
+ const providerId = providerIdRef.current
+ if (!active || !override) {
+ deregisterComposerOverride(providerId)
+ return
+ }
+ registerComposerOverride(providerId, override)
+ }, [active, override, registerComposerOverride, deregisterComposerOverride])
+
+ useEffect(() => {
+ const providerId = providerIdRef.current
+ return () => deregisterComposerOverride(providerId)
+ }, [deregisterComposerOverride])
+}
diff --git a/products/posthog_ai/frontend/logics/composerOverrideLogic.ts b/products/posthog_ai/frontend/logics/composerOverrideLogic.ts
new file mode 100644
index 000000000000..62195e370993
--- /dev/null
+++ b/products/posthog_ai/frontend/logics/composerOverrideLogic.ts
@@ -0,0 +1,82 @@
+import { MakeLogicType, actions, kea, path, reducers, selectors } from 'kea'
+
+/** What a host surface can change about the composer's empty state. */
+export interface ComposerOverride {
+ /** Hide the repository and branch picker when the task never touches a repo. */
+ hideRepositorySelector?: boolean
+ /** Hide the generic "Try PostHog AI for…" row when the host renders its own suggestions. */
+ hideSuggestions?: boolean
+ /** Hide the recent-tasks list under the composer. */
+ hideRecentTasks?: boolean
+ /** Hide the onboarding replay button on a host outside `resolvePhaiOnboardingMounts`, which has no takeover to open. */
+ hideOnboardingReplay?: boolean
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface composerOverrideLogicValues {
+ composerOverride: ComposerOverride | null
+ providers: Record<string, ComposerOverride>
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface composerOverrideLogicActions {
+ deregisterComposerOverride: (providerId: string) => {
+ providerId: string
+ }
+ registerComposerOverride: (
+ providerId: string,
+ override: ComposerOverride
+ ) => {
+ override: ComposerOverride
+ providerId: string
+ }
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface composerOverrideLogicMeta {
+ __keaTypeGenInternalSelectorTypes: {
+ composerOverride: (providers: Record<string, ComposerOverride>) => ComposerOverride | null
+ }
+}
+
+export type composerOverrideLogicType = MakeLogicType<
+ composerOverrideLogicValues,
+ composerOverrideLogicActions,
+ Record<string, any>,
+ composerOverrideLogicMeta
+>
+
+/** Registry of composer overrides, the sibling of `welcomeOverrideLogic`. The first registered provider wins. */
+export const composerOverrideLogic = kea<composerOverrideLogicType>([
+ path(['products', 'posthog_ai', 'frontend', 'logics', 'composerOverrideLogic']),
+
+ actions({
+ /** Idempotent upsert: re-registering the same `providerId` updates its override. */
+ registerComposerOverride: (providerId: string, override: ComposerOverride) => ({ providerId, override }),
+ deregisterComposerOverride: (providerId: string) => ({ providerId }),
+ }),
+
+ reducers({
+ providers: [
+ {} as Record<string, ComposerOverride>,
+ {
+ registerComposerOverride: (state, { providerId, override }) => ({ ...state, [providerId]: override }),
+ deregisterComposerOverride: (state, { providerId }) => {
+ if (!(providerId in state)) {
+ return state
+ }
+ const { [providerId]: _dropped, ...rest } = state
+ return rest
+ },
+ },
+ ],
+ }),
+
+ selectors({
+ composerOverride: [
+ (s) => [s.providers],
+ (providers: Record<string, ComposerOverride>): ComposerOverride | null =>
+ Object.values(providers)[0] ?? null,
+ ],
+ }),
+])
diff --git a/products/posthog_ai/frontend/scenes/TaskTracker/components/SidePanelRunnerImpl.tsx b/products/posthog_ai/frontend/scenes/TaskTracker/components/SidePanelRunnerImpl.tsx
index f1a1576c6dc1..23d8327f89bd 100644
--- a/products/posthog_ai/frontend/scenes/TaskTracker/components/SidePanelRunnerImpl.tsx
+++ b/products/posthog_ai/frontend/scenes/TaskTracker/components/SidePanelRunnerImpl.tsx
@@ -6,6 +6,7 @@ import { LemonButton, LemonDivider } from '@posthog/lemon-ui'
import { useAttachedContext } from '../../../hooks/useAttachedContext'
import { useForegroundStream } from '../../../hooks/useForegroundStream'
+import { composerOverrideLogic } from '../../../logics/composerOverrideLogic'
import { AGENT_TOOL_APPLY_BACK_CONTEXT_ITEM } from '../../../utils/posthogContextBlock'
import { taskTrackerSceneLogic } from '../taskTrackerSceneLogic'
import { StartupRunChat } from './StartupRunChat'
@@ -36,6 +37,7 @@ export function SidePanelRunnerImpl({ panelId, composer }: SidePanelRunnerImplPr
function SidePanelRunnerContent({ composer }: { composer?: ReactNode }): JSX.Element {
const { activeCreation, historyExpanded } = useValues(taskTrackerSceneLogic)
+ const { composerOverride } = useValues(composerOverrideLogic)
const { toggleHistory, updateActiveCreationRun, setStartupDraft } = useActions(taskTrackerSceneLogic)
const startupFocusedRef = useRef(false)
@@ -81,7 +83,7 @@ function SidePanelRunnerContent({ composer }: { composer?: ReactNode }): JSX.Ele
<div className="grow min-h-0 flex flex-col">
<TaskComposer />
</div>
- <TaskHistoryPreview />
+ {!composerOverride?.hideRecentTasks && <TaskHistoryPreview />}
</div>
)
}
diff --git a/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskComposer.tsx b/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskComposer.tsx
index 5453770a4e17..85a4675fed92 100644
--- a/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskComposer.tsx
+++ b/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskComposer.tsx
@@ -12,6 +12,7 @@ import {
Suggestions,
Welcome,
} from 'products/posthog_ai/frontend/api/primitives'
+import { composerOverrideLogic } from 'products/posthog_ai/frontend/logics/composerOverrideLogic'
import { modelCatalogueLogic } from 'products/posthog_ai/frontend/logics/modelCatalogueLogic'
import { taskRunDefaultsLogic } from 'products/posthog_ai/frontend/logics/taskRunDefaultsLogic'
import { getRuntimeAdapterForModel, resolveEffortForModel } from 'products/posthog_ai/frontend/utils/composerModels'
@@ -49,6 +50,7 @@ export function TaskComposer(): JSX.Element {
} = useValues(taskTrackerSceneLogic)
const { catalogue } = useValues(modelCatalogueLogic)
const { myConfigLoading } = useValues(taskRunDefaultsLogic)
+ const { composerOverride } = useValues(composerOverrideLogic)
// The bound instance's key — 'scene' on `/ai` and `/tasks`, the panel key when embedded. The onboarding
// takeover is keyed the same way, so a starter prompt chosen on replay reaches this composer.
@@ -74,7 +76,7 @@ export function TaskComposer(): JSX.Element {
<Welcome headline={displayHeadline}>
{/* Temporary migration affordance — delete with the rest of the onboarding takeover
once everyone is on the new PostHog AI. */}
- <OnboardingReplayButton panelId={panelId} />
+ {!composerOverride?.hideOnboardingReplay && <OnboardingReplayButton panelId={panelId} />}
</Welcome>
<Suggestions.Root
@@ -85,10 +87,12 @@ export function TaskComposer(): JSX.Element {
>
{/* Repo/branch picker sits 8px above the input it configures. */}
<div className="w-full flex flex-col gap-2">
- <RepositorySelector
- value={newTaskData.repositoryConfig}
- onChange={(config) => setNewTaskData({ repositoryConfig: config })}
- />
+ {!composerOverride?.hideRepositorySelector && (
+ <RepositorySelector
+ value={newTaskData.repositoryConfig}
+ onChange={(config) => setNewTaskData({ repositoryConfig: config })}
+ />
+ )}
<ComposerModeShortcut
onCycle={() =>
setNewTaskData({
@@ -153,7 +157,8 @@ export function TaskComposer(): JSX.Element {
/>
</Composer.Footer>
</Composer.Frame>
- <Suggestions.Dropdown />
+ {/* Open-group state is shared with the side panel; a group left open there would list generic prompts here. */}
+ {!composerOverride?.hideSuggestions && <Suggestions.Dropdown />}
<AIConsentPopoverWrapper
placement="bottom-end"
showArrow
@@ -167,7 +172,7 @@ export function TaskComposer(): JSX.Element {
</Composer.Root>
</div>
- <Suggestions.Buttons data={DEFAULT_SUGGESTIONS_DATA} />
+ {!composerOverride?.hideSuggestions && <Suggestions.Buttons data={DEFAULT_SUGGESTIONS_DATA} />}
</Suggestions.Root>
</div>
</div>
diff --git a/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.test.ts b/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.test.ts
index e333a82df746..c2b44ea28de4 100644
--- a/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.test.ts
+++ b/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.test.ts
@@ -13,6 +13,7 @@ import { initKeaTests } from '~/test/init'
import { TaskRuntimeEnumApi } from 'products/tasks/frontend/generated/api.schemas'
import { attachedContextLogic, runStreamLogic } from '../../api/logics'
+import { composerOverrideLogic } from '../../logics/composerOverrideLogic'
import { composerSeedLogic } from '../../logics/composerSeedLogic'
import { runCancellationLogic } from '../../logics/runCancellationLogic'
import { runInteractionLogic } from '../../logics/runInteractionLogic'
@@ -586,6 +587,34 @@ describe('taskTrackerSceneLogic', () => {
expect(logic.values.newTaskData.repositoryConfig.integrationId).toBe(7)
})
+ // The side panel shares this logic, so a hidden picker can still hold a remembered repo. It must not reach the requests.
+ it('keeps a hidden repository out of the warm and create requests', async () => {
+ useMocks({
+ get: {
+ '/api/projects/:team/integrations/': {
+ results: [{ id: 7, kind: 'github', display_name: 'acme/widgets', config: {} }],
+ },
+ },
+ })
+ const overrides = composerOverrideLogic()
+ overrides.mount()
+ overrides.actions.registerComposerOverride('new-workflow', { hideRepositorySelector: true })
+ logic.mount()
+ await expectLogic(logic).toFinishAllListeners()
+ logic.actions.setNewTaskData({ repositoryConfig: { integrationId: 7, repository: 'acme/widgets' } })
+
+ await expectLogic(logic, () => {
+ logic.actions.setNewTaskData({ description: 'draft a welcome sequence' })
+ }).toDispatchActions(['noteDraft'])
+
+ logic.actions.submitNewTask()
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(createBody).toMatchObject({ repository: null, github_integration: null })
+
+ overrides.unmount()
+ })
+
// An embedded instance (e.g. Max's side panel runner) keeps the run in place instead of navigating the
// host to `/tasks/:id`, and must never have its `activeCreation` cleared by unrelated main-app
// navigation. Guards against either guard (`props.panelId` in `submitNewTask` / `urlToAction`) being
diff --git a/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.ts b/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.ts
index 216175616c27..ec53deb2a252 100644
--- a/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.ts
+++ b/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.ts
@@ -30,6 +30,8 @@ import type { IntegrationType } from '../../../../../frontend/src/types'
import { attachedContextItemKey, attachedContextLogic, runStreamLogic } from '../../api/logics'
import type { SuggestionGroup, SuggestionItem } from '../../api/primitives'
import { DEFAULT_HEADLINES, pickHeadline } from '../../api/primitives'
+import { composerOverrideLogic } from '../../logics/composerOverrideLogic'
+import type { ComposerOverride } from '../../logics/composerOverrideLogic'
import { composerSeedLogic } from '../../logics/composerSeedLogic'
import type { ComposerSeed } from '../../logics/composerSeedLogic'
import { modelCatalogueLogic } from '../../logics/modelCatalogueLogic'
@@ -160,6 +162,7 @@ const EMPTY_TASK_FORM: TaskCreateForm = {
export interface taskTrackerSceneLogicValues {
dataProcessingAccepted: boolean // aiConsentLogic
contextItems: AttachedContextItem[] // attachedContextLogic
+ composerOverride: ComposerOverride | null // composerOverrideLogic
seed: ComposerSeed | null // composerSeedLogic
integrations: IntegrationType[] | null // integrationsLogic
catalogue: ModelChoiceApi[] // modelCatalogueLogic
@@ -182,6 +185,7 @@ export interface taskTrackerSceneLogicValues {
displayEffort: ReasoningEffortEnumApi
displayHeadline: string
displayModel: string
+ effectiveRepositoryConfig: RepositoryConfig
hasDesktopAccess: boolean
headlineSeed: number
isDefaultSelection: boolean
@@ -343,6 +347,10 @@ export interface taskTrackerSceneLogicMeta {
defaultRuntimeAdapter: string | null,
catalogue: ModelChoiceApi[]
) => string
+ effectiveRepositoryConfig: (
+ newTaskData: TaskCreateForm,
+ composerOverride: ComposerOverride | null
+ ) => RepositoryConfig
isDefaultSelection: (newTaskData: TaskCreateForm) => boolean
}
}
@@ -378,6 +386,8 @@ export const taskTrackerSceneLogic = kea<taskTrackerSceneLogicType>([
['currentProjectId'],
composerSeedLogic(props),
['seed'],
+ composerOverrideLogic,
+ ['composerOverride'],
welcomeOverrideLogic,
['overrideHeadlines'],
modelCatalogueLogic,
@@ -536,6 +546,12 @@ export const taskTrackerSceneLogic = kea<taskTrackerSceneLogicType>([
? getRuntimeAdapterForModel(catalogue, displayModel)
: defaultRuntimeAdapter,
],
+ // The shared form may still hold a remembered repo while the picker is hidden. Drop it here, not from the form.
+ effectiveRepositoryConfig: [
+ (s) => [s.newTaskData, s.composerOverride],
+ (newTaskData: TaskCreateForm, composerOverride: ComposerOverride | null): RepositoryConfig =>
+ composerOverride?.hideRepositorySelector ? {} : newTaskData.repositoryConfig,
+ ],
// Neither picker touched: submit omits the triple so the backend resolves it, which also
// lets a warm run provisioned under the default match.
isDefaultSelection: [
@@ -572,7 +588,7 @@ export const taskTrackerSceneLogic = kea<taskTrackerSceneLogicType>([
// accepts AI data processing.
if (!values.activeCreation && values.dataProcessingAccepted) {
const request = buildWarmRequest(
- values.newTaskData,
+ { ...values.newTaskData, repositoryConfig: values.effectiveRepositoryConfig },
values.catalogue,
values.displayModel,
values.displayEffort
@@ -626,7 +642,8 @@ export const taskTrackerSceneLogic = kea<taskTrackerSceneLogicType>([
return
}
- const { description, repositoryConfig, permissionMode } = values.newTaskData
+ const { description, permissionMode } = values.newTaskData
+ const repositoryConfig = values.effectiveRepositoryConfig
if (!description.trim()) {
lemonToast.error('Description is required')
diff --git a/products/workflows/frontend/Workflows/NewWorkflowAgent.tsx b/products/workflows/frontend/Workflows/NewWorkflowAgent.tsx
new file mode 100644
index 000000000000..510de1fced47
--- /dev/null
+++ b/products/workflows/frontend/Workflows/NewWorkflowAgent.tsx
@@ -0,0 +1,73 @@
+import { useActions, useValues } from 'kea'
+import { useEffect } from 'react'
+
+import { LemonBanner } from '@posthog/lemon-ui'
+
+import { cn } from 'lib/utils/css-classes'
+import { MAX_SIDE_PANEL_ID } from 'scenes/max/components/PhaiSidePanelChat'
+import { SuggestionCard } from 'scenes/max/components/SuggestionCard'
+
+import { iconForType } from '~/layout/panel-layout/ProjectTree/defaultTree'
+
+import { composerSeedLogic, runnerPanelLogic } from 'products/posthog_ai/frontend/api/logics'
+import { SidePanelRunner } from 'products/posthog_ai/frontend/api/runner'
+
+import { newWorkflowAgentLogic } from './newWorkflowAgentLogic'
+import { newWorkflowLogic } from './newWorkflowLogic'
+import { NewWorkflowModal } from './NewWorkflowModal'
+import { NEW_WORKFLOW_SUGGESTIONS } from './workflowAgentContext'
+
+/** The AI-first "New workflow" screen: the side panel's runner rendered full page, with a way back to the editor. */
+export function NewWorkflowAgent(): JSX.Element {
+ const { composerShown } = useActions(newWorkflowAgentLogic)
+ const { openEditorFromAiComposer } = useActions(newWorkflowLogic)
+ useEffect(() => composerShown(), [composerShown])
+ const { activeCreation } = useValues(runnerPanelLogic({ panelId: MAX_SIDE_PANEL_ID }))
+ // A card only fills the composer (no auto-submit) so the prompt can be tweaked before the agent starts.
+ const { setSeed } = useActions(composerSeedLogic({ panelId: MAX_SIDE_PANEL_ID }))
+ const fillComposer = (prompt: string): void => {
+ setSeed({ prompt, autoSubmit: false })
+ const textarea = document.querySelector<HTMLTextAreaElement>('[data-attr="task-composer-input"]')
+ textarea?.focus()
+ textarea?.setSelectionRange(prompt.length, prompt.length)
+ }
+
+ return (
+ // Natural height while drafting so the cards sit under the composer; full page once a run starts.
+ <div className="flex flex-col grow min-h-0" data-attr="new-workflow-agent">
+ {/* The escape hatch stays up during a run, so a turn that never creates the draft has a way out. */}
+ <LemonBanner
+ type="ai"
+ className="m-2 shrink-0"
+ action={{
+ children: 'Use the editor instead',
+ onClick: openEditorFromAiComposer,
+ 'data-attr': 'new-workflow-agent-open-editor',
+ }}
+ >
+ We're trialling building workflows with PostHog AI. Describe what you want and it drafts the workflow
+ for you to refine.
+ </LemonBanner>
+ <div className={cn('flex flex-col', activeCreation ? 'grow min-h-0' : 'shrink-0 mt-auto')}>
+ <SidePanelRunner panelId={MAX_SIDE_PANEL_ID} />
+ </div>
+ {!activeCreation && (
+ <div className="flex flex-col items-center gap-4 shrink-0 pb-6 mb-auto">
+ <div className="grid grid-cols-1 @min-[40rem]/main-content:grid-cols-2 gap-1 w-full max-w-2xl px-4">
+ {NEW_WORKFLOW_SUGGESTIONS.map((suggestion) => (
+ <SuggestionCard
+ key={suggestion.prompt}
+ title={suggestion.title}
+ description={suggestion.description}
+ icon={iconForType('workflows')}
+ onClick={() => fillComposer(suggestion.prompt)}
+ data-attr="new-workflow-agent-suggestion"
+ />
+ ))}
+ </div>
+ </div>
+ )}
+ <NewWorkflowModal />
+ </div>
+ )
+}
diff --git a/products/workflows/frontend/Workflows/WorkflowScene.tsx b/products/workflows/frontend/Workflows/WorkflowScene.tsx
index e7a3c9488460..1132c4add39d 100644
--- a/products/workflows/frontend/Workflows/WorkflowScene.tsx
+++ b/products/workflows/frontend/Workflows/WorkflowScene.tsx
@@ -20,10 +20,15 @@ import { ProductKey } from '~/queries/schema/schema-general'
import { ActivityScope } from '~/types'
import { batchWorkflowJobsLogic } from './batchWorkflowJobsLogic'
+import { NewWorkflowAgent } from './NewWorkflowAgent'
+import { newWorkflowLogic } from './newWorkflowLogic'
import { Workflow } from './Workflow'
import {
EMAIL_EDITOR_AGENT_HEADLINES,
+ NEW_WORKFLOW_AGENT_HEADLINES,
+ NEW_WORKFLOW_COMPOSER_OVERRIDE,
WORKFLOW_AGENT_HEADLINES,
+ buildNewWorkflowComposerContext,
buildWorkflowAgentContext,
isEditingEmailAction,
} from './workflowAgentContext'
@@ -84,6 +89,9 @@ export function WorkflowScene(props: WorkflowSceneLogicProps): JSX.Element {
500
)
const { sceneIntegrationEnabled } = useValues(sceneAgentPanelLogic)
+ const { aiComposerAvailable } = useValues(newWorkflowLogic)
+ // Deep links that carry a starting point, and the escape hatch, land in the editor instead (see `aiComposerAvailable`).
+ const showAiComposer = workflowSceneProps.id === 'new' && aiComposerAvailable
// The email takeover reflects its state into the URL (?editor=email beside the step's ?node=);
// while it is open the panel's framing follows the email being edited, not the graph. Both
// swaps update the same provider registrations in place, so they keep their first-registered
@@ -95,23 +103,40 @@ export function WorkflowScene(props: WorkflowSceneLogicProps): JSX.Element {
// entirely for users the integration flag hasn't reached.
const agentContextItems = useMemo(
() =>
- sceneIntegrationEnabled
- ? buildWorkflowAgentContext(
- debouncedAgentSource.workflow,
- debouncedAgentSource.id,
- hogFunctionTemplatesById,
- editingEmailActionId
- )
- : null,
- [sceneIntegrationEnabled, debouncedAgentSource, hogFunctionTemplatesById, editingEmailActionId]
+ showAiComposer
+ ? buildNewWorkflowComposerContext()
+ : sceneIntegrationEnabled
+ ? buildWorkflowAgentContext(
+ debouncedAgentSource.workflow,
+ debouncedAgentSource.id,
+ hogFunctionTemplatesById,
+ editingEmailActionId
+ )
+ : null,
+ [showAiComposer, sceneIntegrationEnabled, debouncedAgentSource, hogFunctionTemplatesById, editingEmailActionId]
)
useSceneAgentPanel({
sceneKey: 'workflow',
contextItems: agentContextItems,
- headlines: editingEmail ? EMAIL_EDITOR_AGENT_HEADLINES : WORKFLOW_AGENT_HEADLINES,
+ headlines: showAiComposer
+ ? NEW_WORKFLOW_AGENT_HEADLINES
+ : editingEmail
+ ? EMAIL_EDITOR_AGENT_HEADLINES
+ : WORKFLOW_AGENT_HEADLINES,
+ composer: showAiComposer ? NEW_WORKFLOW_COMPOSER_OVERRIDE : undefined,
active: !!originalWorkflow || workflowSceneProps.id === 'new',
+ // The composer is the page while drafting; the panel opens itself once the draft exists.
+ autoOpen: !showAiComposer,
})
+ if (showAiComposer) {
+ return (
+ <SceneContent className="h-full flex flex-col grow" data-attr="workflow-scene">
+ <NewWorkflowAgent />
+ </SceneContent>
+ )
+ }
+
if (!originalWorkflow && workflowLoading) {
return <SpinnerOverlay sceneLevel />
}
diff --git a/products/workflows/frontend/Workflows/newWorkflowAgentLogic.test.ts b/products/workflows/frontend/Workflows/newWorkflowAgentLogic.test.ts
new file mode 100644
index 000000000000..7078b3c33975
--- /dev/null
+++ b/products/workflows/frontend/Workflows/newWorkflowAgentLogic.test.ts
@@ -0,0 +1,152 @@
+import { router } from 'kea-router'
+import { expectLogic } from 'kea-test-utils'
+
+import { lemonToast } from 'lib/lemon-ui/LemonToast'
+import { removeProjectIdIfPresent } from 'lib/utils/kea-router'
+import { MAX_SIDE_PANEL_ID } from 'scenes/max/components/PhaiSidePanelChat'
+import { maxMocks } from 'scenes/max/testUtils'
+
+import { sidePanelStateLogic } from '~/layout/navigation-3000/sidepanel/sidePanelStateLogic'
+import { useMocks } from '~/mocks/jest'
+import { initKeaTests } from '~/test/init'
+import { SidePanelTab } from '~/types'
+
+import { composerSeedLogic, runnerPanelLogic, toolStreamEventsLogic } from 'products/posthog_ai/frontend/api/logics'
+import type { ToolStreamEvent } from 'products/posthog_ai/frontend/api/types'
+
+import { newWorkflowAgentLogic } from './newWorkflowAgentLogic'
+
+const WORKFLOW_ID = '2f1e9c3a-5b7d-4e8f-9a0b-1c2d3e4f5a6b'
+const OLDER_ID = '7a1b2c3d-0000-4e8f-9a0b-1c2d3e4f5a6b'
+const NAME = 'Win back inactive users'
+
+function createEvent(overrides: Partial<ToolStreamEvent>): ToolStreamEvent {
+ return {
+ streamKey: 'draft-1',
+ toolCallId: 'call-1',
+ toolName: 'workflows-create',
+ rawToolName: 'exec',
+ phase: 'completed',
+ source: 'live',
+ invocation: {
+ toolCallId: 'call-1',
+ rawServerName: 'posthog',
+ rawToolName: 'exec',
+ input: { command: `call workflows-create ${JSON.stringify({ name: NAME })}` },
+ // Large creates come back as a "saved to file" notice, so the id never rides the output.
+ output: { content: 'Error: result exceeds maximum allowed tokens.', isError: false },
+ status: 'completed',
+ contentBlocks: [],
+ },
+ ...overrides,
+ }
+}
+
+describe('newWorkflowAgentLogic', () => {
+ let logic: ReturnType<typeof newWorkflowAgentLogic.build>
+
+ beforeEach(() => {
+ useMocks({
+ ...maxMocks,
+ get: {
+ ...maxMocks.get,
+ // Ordered by update time like the real list, so the same-named older draft comes first.
+ '/api/environments/:team_id/hog_flows/': {
+ results: [
+ { id: OLDER_ID, name: NAME, created_at: '2026-09-01T00:00:00Z' },
+ { id: WORKFLOW_ID, name: NAME, created_at: '2026-09-15T00:00:00Z' },
+ ],
+ count: 2,
+ },
+ },
+ })
+ initKeaTests()
+ sidePanelStateLogic.mount()
+ sidePanelStateLogic.actions.setSidePanelAvailable(true)
+ router.actions.push('/workflows/new/workflow', {}, {})
+ logic = newWorkflowAgentLogic()
+ logic.mount()
+ runnerPanelLogic({ panelId: MAX_SIDE_PANEL_ID }).actions.setActiveCreation({ streamKey: 'draft-1' })
+ })
+
+ afterEach(() => {
+ logic?.unmount()
+ })
+
+ // Otherwise the composer and the side panel show the same empty chat side by side.
+ it('closes an open PostHog AI panel when the composer is shown', async () => {
+ sidePanelStateLogic.actions.openSidePanel(SidePanelTab.Max)
+
+ await expectLogic(logic, () => {
+ logic.actions.composerShown()
+ }).toFinishAllListeners()
+
+ expect(sidePanelStateLogic.values.sidePanelOpen).toBe(false)
+ })
+
+ // The composer is the panel's own instance, so an unsent panel prompt would show here. An empty seed clears it.
+ it('empties the shared composer when the composer is shown', async () => {
+ const seeds = composerSeedLogic({ panelId: MAX_SIDE_PANEL_ID })
+ seeds.mount()
+
+ await expectLogic(logic, () => {
+ logic.actions.composerShown()
+ }).toFinishAllListeners()
+
+ expect(seeds.values.seed).toEqual({ prompt: '', autoSubmit: false })
+
+ seeds.unmount()
+ })
+
+ it('opens the side panel and routes to the draft once this run creates a workflow', async () => {
+ await expectLogic(logic, () => {
+ toolStreamEventsLogic.actions.emitToolEvent(createEvent({}))
+ }).toFinishAllListeners()
+
+ expect(sidePanelStateLogic.values.selectedTab).toBe(SidePanelTab.Max)
+ expect(sidePanelStateLogic.values.sidePanelOpen).toBe(true)
+ expect(removeProjectIdIfPresent(router.values.location.pathname)).toBe(`/workflows/${WORKFLOW_ID}/workflow`)
+ })
+
+ // The draft is already saved, so a lookup that fails or matches nothing must say where it went.
+ it.each([
+ { name: 'the lookup fails', response: () => [500, { detail: 'boom' }] },
+ { name: 'no workflow matches', response: () => [200, { results: [], count: 0 }] },
+ {
+ name: 'the create call sent no name',
+ overrides: { invocation: { input: { command: 'call workflows-create {}' } } },
+ },
+ ])('says the draft could not be opened when $name', async ({ response, overrides }) => {
+ if (response) {
+ useMocks({ get: { '/api/environments/:team_id/hog_flows/': response } })
+ }
+ const toast = jest.spyOn(lemonToast, 'error')
+
+ await expectLogic(logic, () => {
+ toolStreamEventsLogic.actions.emitToolEvent(
+ createEvent(overrides ? { invocation: { ...createEvent({}).invocation, ...overrides.invocation } } : {})
+ )
+ }).toFinishAllListeners()
+
+ expect(toast).toHaveBeenCalledTimes(1)
+ expect(sidePanelStateLogic.values.sidePanelOpen).toBe(false)
+ expect(removeProjectIdIfPresent(router.values.location.pathname)).toBe('/workflows/new/workflow')
+
+ toast.mockRestore()
+ })
+
+ // The bus is global: a replay, another run's create, or a still-streaming call must not move the user.
+ it.each([
+ { name: 'a replayed event', overrides: { source: 'replay' as const } },
+ { name: 'another stream', overrides: { streamKey: 'other-run' } },
+ { name: 'an unfinished call', overrides: { phase: 'started' as const } },
+ { name: 'a different tool', overrides: { toolName: 'workflows-get' } },
+ ])('ignores $name', async ({ overrides }) => {
+ await expectLogic(logic, () => {
+ toolStreamEventsLogic.actions.emitToolEvent(createEvent(overrides))
+ }).toFinishAllListeners()
+
+ expect(sidePanelStateLogic.values.sidePanelOpen).toBe(false)
+ expect(removeProjectIdIfPresent(router.values.location.pathname)).toBe('/workflows/new/workflow')
+ })
+})
diff --git a/products/workflows/frontend/Workflows/newWorkflowAgentLogic.ts b/products/workflows/frontend/Workflows/newWorkflowAgentLogic.ts
new file mode 100644
index 000000000000..1977e008cd20
--- /dev/null
+++ b/products/workflows/frontend/Workflows/newWorkflowAgentLogic.ts
@@ -0,0 +1,157 @@
+import { MakeLogicType, actions, connect, kea, listeners, path } from 'kea'
+import { router } from 'kea-router'
+import posthog from 'posthog-js'
+
+import api from 'lib/api'
+import { lemonToast } from 'lib/lemon-ui/LemonToast'
+import { MAX_SIDE_PANEL_ID } from 'scenes/max/components/PhaiSidePanelChat'
+import { urls } from 'scenes/urls'
+
+import { sidePanelStateLogic } from '~/layout/navigation-3000/sidepanel/sidePanelStateLogic'
+import { SidePanelTab } from '~/types'
+
+import {
+ composerSeedLogic,
+ resolveToolCall,
+ runnerPanelLogic,
+ toolStreamEventsLogic,
+} from 'products/posthog_ai/frontend/api/logics'
+import type { ActiveCreation, ComposerSeed } from 'products/posthog_ai/frontend/api/logics'
+import type { ToolStreamEvent } from 'products/posthog_ai/frontend/api/types'
+
+// pinned: MCP tool name from products/workflows/mcp/tools.yaml
+const CREATE_WORKFLOW_TOOL = 'workflows-create'
+
+/** The tool output is truncated, so the draft is found by exact name, newest `created_at` first. No name means no guess. */
+export async function findCreatedWorkflowId(name: unknown): Promise<string | null> {
+ const search = typeof name === 'string' && name.trim() ? name.trim() : undefined
+ if (!search) {
+ return null
+ }
+ const { results } = await api.hogFlows.getHogFlows({ search, limit: 5 })
+ const match = results
+ .filter((workflow) => workflow.name === search)
+ .sort((a, b) => b.created_at.localeCompare(a.created_at))[0]
+ return match?.id ?? null
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface newWorkflowAgentLogicValues {
+ activeCreation: ActiveCreation | null // runnerPanelLogic
+ selectedTab: SidePanelTab | null // sidePanelStateLogic
+ sidePanelOpen: boolean // sidePanelStateLogic
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface newWorkflowAgentLogicActions {
+ setSeed: (seed: ComposerSeed) => {
+ seed: ComposerSeed
+ } // composerSeedLogic
+ clearActiveCreation: () => {
+ value: true
+ } // runnerPanelLogic
+ setActiveCreation: (creation: ActiveCreation) => {
+ creation: ActiveCreation
+ } // runnerPanelLogic
+ setHistoryExpanded: (expanded: boolean) => {
+ expanded: boolean
+ } // runnerPanelLogic
+ closeSidePanel: (tab?: SidePanelTab | undefined) => {
+ tab: SidePanelTab | undefined
+ } // sidePanelStateLogic
+ openSidePanel: (
+ tab: SidePanelTab,
+ options?: string | undefined
+ ) => {
+ options: string | undefined
+ tab: SidePanelTab
+ } // sidePanelStateLogic
+ emitToolEvent: (event: ToolStreamEvent) => {
+ event: ToolStreamEvent
+ } // toolStreamEventsLogic
+ composerShown: () => {
+ value: true
+ }
+}
+
+export type newWorkflowAgentLogicType = MakeLogicType<newWorkflowAgentLogicValues, newWorkflowAgentLogicActions>
+
+/** The composer is the side panel's own runner: a completed `workflows-create` opens the panel and routes to the draft. */
+export const newWorkflowAgentLogic = kea<newWorkflowAgentLogicType>([
+ path(['products', 'workflows', 'frontend', 'newWorkflowAgentLogic']),
+ connect(() => ({
+ values: [
+ runnerPanelLogic({ panelId: MAX_SIDE_PANEL_ID }),
+ ['activeCreation'],
+ sidePanelStateLogic,
+ ['sidePanelOpen', 'selectedTab'],
+ ],
+ actions: [
+ runnerPanelLogic({ panelId: MAX_SIDE_PANEL_ID }),
+ ['setActiveCreation', 'clearActiveCreation', 'setHistoryExpanded'],
+ sidePanelStateLogic,
+ ['openSidePanel', 'closeSidePanel'],
+ toolStreamEventsLogic,
+ ['emitToolEvent'],
+ composerSeedLogic({ panelId: MAX_SIDE_PANEL_ID }),
+ ['setSeed'],
+ ],
+ })),
+ actions({
+ composerShown: true,
+ }),
+ listeners(({ actions, cache, values }) => ({
+ // Runs after the previous scene left the panel registry, so its close is not read as dismissing the auto-open.
+ composerShown: () => {
+ // The panel is shared with the side panel: a run or history list left open there must not replace the composer.
+ actions.clearActiveCreation()
+ actions.setHistoryExpanded(false)
+ // An unsent prompt typed in the panel is still in the shared form. An empty seed is how a host clears it.
+ actions.setSeed({ prompt: '', autoSubmit: false })
+ if (values.sidePanelOpen && values.selectedTab === SidePanelTab.Max) {
+ actions.closeSidePanel()
+ }
+ posthog.capture('workflow ai composer viewed')
+ },
+ setActiveCreation: ({ creation }, _breakpoint, _action, previousState) => {
+ // The first set for a stream key is the send; later ones attach the task and run ids.
+ const previous = runnerPanelLogic({ panelId: MAX_SIDE_PANEL_ID }).selectors.activeCreation(previousState)
+ if (previous?.streamKey !== creation.streamKey) {
+ posthog.capture('workflow ai composer submitted')
+ }
+ },
+ emitToolEvent: async ({ event }) => {
+ if (
+ event.source !== 'live' ||
+ event.phase !== 'completed' ||
+ event.toolName !== CREATE_WORKFLOW_TOOL ||
+ event.streamKey !== values.activeCreation?.streamKey ||
+ cache.handedOff
+ ) {
+ return
+ }
+ let workflowId: string | null = null
+ try {
+ workflowId = await findCreatedWorkflowId(resolveToolCall(event.invocation).innerInput?.name)
+ } catch {
+ // A rejected list call reads like no match: the draft is saved and the run stays on screen.
+ workflowId = null
+ }
+ // The composer can be cleared or re-sent while the lookup is in flight.
+ if (cache.handedOff || event.streamKey !== values.activeCreation?.streamKey) {
+ return
+ }
+ if (!workflowId) {
+ lemonToast.error(
+ 'Your workflow was created, but it could not be opened. Find it in the workflows list.'
+ )
+ return
+ }
+ cache.handedOff = true
+ posthog.capture('workflow ai composer created workflow', { workflow_id: workflowId })
+ // Open the panel before leaving the page so the runner instance stays mounted with its run.
+ actions.openSidePanel(SidePanelTab.Max)
+ router.actions.push(urls.workflow(workflowId, 'workflow'))
+ },
+ })),
+])
diff --git a/products/workflows/frontend/Workflows/newWorkflowLogic.test.ts b/products/workflows/frontend/Workflows/newWorkflowLogic.test.ts
index a5cf8804b084..7ec80f157078 100644
--- a/products/workflows/frontend/Workflows/newWorkflowLogic.test.ts
+++ b/products/workflows/frontend/Workflows/newWorkflowLogic.test.ts
@@ -1,15 +1,138 @@
import { router } from 'kea-router'
import { expectLogic } from 'kea-test-utils'
+import posthog from 'posthog-js'
+import { FEATURE_FLAGS } from 'lib/constants'
+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
+import { removeProjectIdIfPresent } from 'lib/utils/kea-router'
+import { maxMocks } from 'scenes/max/testUtils'
+
+import { useMocks } from '~/mocks/jest'
import { initKeaTests } from '~/test/init'
import { newWorkflowLogic } from './newWorkflowLogic'
+import { TRIGGER_PREFILL_PARAM } from './workflowTriggerPrefill'
+
+const AI_FIRST_FLAGS = [
+ FEATURE_FLAGS.WORKFLOWS_AI_FIRST_NEW,
+ FEATURE_FLAGS.PHAI_SCENE_AUTO_OPEN,
+ FEATURE_FLAGS.PHAI_SANDBOX_MODE,
+]
describe('newWorkflowLogic', () => {
+ const setFlags = (flags: string[], variants: Record<string, string | boolean> = {}): void => {
+ featureFlagLogic.actions.setFeatureFlags(flags, {
+ ...Object.fromEntries(flags.map((flag) => [flag, true])),
+ ...variants,
+ })
+ }
+
beforeEach(() => {
+ useMocks(maxMocks)
initKeaTests()
})
+ describe('AI-first new workflow', () => {
+ // The flag-off path must stay byte-identical, and exposure is recorded only for a click the composer could answer.
+ it.each([
+ { name: 'flag on', flags: AI_FIRST_FLAGS, routed: true, exposed: true },
+ {
+ name: 'flag off',
+ flags: [FEATURE_FLAGS.PHAI_SCENE_AUTO_OPEN, FEATURE_FLAGS.PHAI_SANDBOX_MODE],
+ routed: false,
+ exposed: true,
+ },
+ {
+ name: 'scene integration off',
+ flags: [FEATURE_FLAGS.WORKFLOWS_AI_FIRST_NEW],
+ routed: false,
+ exposed: false,
+ },
+ ])('startNewWorkflow routes to the composer only with $name', async ({ flags, routed, exposed }) => {
+ setFlags(flags)
+ const recordExposure = jest.spyOn(posthog, 'getFeatureFlag').mockReturnValue(undefined)
+ const logic = newWorkflowLogic()
+ logic.mount()
+ router.actions.push('/workflows', {}, {})
+
+ await expectLogic(logic, () => {
+ logic.actions.startNewWorkflow()
+ }).toFinishAllListeners()
+
+ expect(logic.values.newWorkflowModalVisible).toBe(!routed)
+ expect(removeProjectIdIfPresent(router.values.location.pathname)).toBe(
+ routed ? '/workflows/new/workflow' : '/workflows'
+ )
+ // The composer answers a marked entry only, so the click has to mark its own route.
+ expect(router.values.searchParams).toEqual(routed ? { mode: 'ai' } : {})
+ expect(recordExposure.mock.calls.map(([flag]) => flag)).toEqual(
+ exposed ? [FEATURE_FLAGS.WORKFLOWS_AI_FIRST_NEW] : []
+ )
+ recordExposure.mockRestore()
+ })
+
+ // Deep links and the escape hatch must keep landing in the editor, or the composer swallows a chosen starting point.
+ it.each([
+ { name: 'an AI entry', path: '/workflows/new/workflow', search: { mode: 'ai' }, available: true },
+ // Other products open the plain URL for a specific job and tell the person the editor is there.
+ { name: 'a plain new URL', path: '/workflows/new/workflow', search: {}, available: false },
+ {
+ name: 'a template',
+ path: '/workflows/new/workflow',
+ search: { mode: 'ai', templateId: 'tpl-1' },
+ available: false,
+ },
+ {
+ name: 'a template edit',
+ path: '/workflows/new/workflow',
+ search: { mode: 'ai', editTemplateId: 'tpl-1' },
+ available: false,
+ },
+ {
+ name: 'a trigger prefill',
+ path: '/workflows/new/workflow',
+ search: { mode: 'ai', [TRIGGER_PREFILL_PARAM]: 'x' },
+ available: false,
+ },
+ {
+ name: 'the editor mode param',
+ path: '/workflows/new/workflow',
+ search: { mode: 'editor' },
+ available: false,
+ },
+ // The editor reads this for every workflow, so an existing one must answer false without reading the flag.
+ {
+ name: 'an existing workflow',
+ path: '/workflows/wf-1/workflow',
+ search: { mode: 'ai' },
+ available: false,
+ },
+ ])('aiComposerAvailable is $available for $name', ({ path, search, available }) => {
+ setFlags(AI_FIRST_FLAGS)
+ const logic = newWorkflowLogic()
+ logic.mount()
+
+ router.actions.push(path, search, {})
+
+ expect(logic.values.aiComposerAvailable).toBe(available)
+ })
+
+ it('createEmptyWorkflow marks the editor route so the composer does not render again', async () => {
+ setFlags(AI_FIRST_FLAGS)
+ const logic = newWorkflowLogic()
+ logic.mount()
+ router.actions.push('/workflows/new/workflow', {}, {})
+
+ await expectLogic(logic, () => {
+ logic.actions.openEditorFromAiComposer()
+ logic.actions.createEmptyWorkflow()
+ }).toFinishAllListeners()
+
+ expect(router.values.searchParams).toEqual({ mode: 'editor' })
+ expect(logic.values.aiComposerAvailable).toBe(false)
+ })
+ })
+
describe('urlToAction', () => {
it('opens modal when navigating to /workflows with #newWorkflow hash param', async () => {
const logic = newWorkflowLogic()
diff --git a/products/workflows/frontend/Workflows/newWorkflowLogic.ts b/products/workflows/frontend/Workflows/newWorkflowLogic.ts
index 95306d2fec35..afa53dfe043a 100644
--- a/products/workflows/frontend/Workflows/newWorkflowLogic.ts
+++ b/products/workflows/frontend/Workflows/newWorkflowLogic.ts
@@ -1,12 +1,50 @@
-import { MakeLogicType, actions, kea, listeners, path, reducers } from 'kea'
-import { actionToUrl, router, urlToAction } from 'kea-router'
+import { MakeLogicType, actions, connect, kea, listeners, path, reducers, selectors } from 'kea'
+import { actionToUrl, combineUrl, router, urlToAction } from 'kea-router'
+import posthog from 'posthog-js'
+import { FEATURE_FLAGS } from 'lib/constants'
+import { FeatureFlagsSet, featureFlagLogic } from 'lib/logic/featureFlagLogic'
+import { removeProjectIdIfPresent } from 'lib/utils/kea-router'
+import { sceneAgentPanelLogic } from 'scenes/max/sceneAgentPanelLogic'
import { urls } from 'scenes/urls'
import type { HogFlowTemplate } from './hogflows/types'
+import { TRIGGER_PREFILL_PARAM } from './workflowTriggerPrefill'
+
+// pinned: URL search param for the surface a new workflow opens on. A URL that says neither opens the editor.
+export const EDITOR_MODE_PARAM = 'mode'
+export const EDITOR_MODE_VALUE = 'editor'
+export const AI_COMPOSER_MODE_VALUE = 'ai'
+
+/** The new-workflow URL for an entry that means "start from nothing", the only kind the composer answers. */
+export function urlForNewWorkflowComposer(): string {
+ return combineUrl(urls.workflowNew(), { [EDITOR_MODE_PARAM]: AI_COMPOSER_MODE_VALUE }).url
+}
+
+/** Reading the flag captures `$feature_flag_called`, the experiment's exposure, so this runs after every cheaper check. */
+function isAiFirstVariant(featureFlags: FeatureFlagsSet): boolean {
+ const variant = featureFlags[FEATURE_FLAGS.WORKFLOWS_AI_FIRST_NEW]
+ return variant === true || variant === 'test'
+}
+
+// The editor scene is `/workflows/:id/:tab`, and only the `new` id can show the composer.
+function isNewWorkflowRoute(pathname: string): boolean {
+ const [, section, id] = removeProjectIdIfPresent(pathname).split('/')
+ return section === 'workflows' && id === 'new'
+}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface newWorkflowLogicValues {
+ featureFlags: FeatureFlagsSet // featureFlagLogic
+ location: {
+ pathname: string
+ search: string
+ hash: string
+ } // router
+ searchParams: Record<string, any> // router
+ sceneIntegrationEnabled: boolean // sceneAgentPanelLogic
+ aiComposerAvailable: boolean
+ aiFirstNewEnabled: boolean
newWorkflowModalVisible: boolean
}
@@ -21,18 +59,58 @@ export interface newWorkflowLogicActions {
hideNewWorkflowModal: () => {
value: true
}
+ openEditorFromAiComposer: () => {
+ value: true
+ }
showNewWorkflowModal: () => {
value: true
}
+ startNewWorkflow: () => {
+ value: true
+ }
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface newWorkflowLogicMeta {
+ __keaTypeGenInternalSelectorTypes: {
+ aiFirstNewEnabled: (featureFlags: FeatureFlagsSet, sceneIntegrationEnabled: boolean) => boolean
+ aiComposerAvailable: (
+ featureFlags: FeatureFlagsSet,
+ sceneIntegrationEnabled: boolean,
+ searchParams: Record<string, any>,
+ location: {
+ hash: string
+ pathname: string
+ search: string
+ }
+ ) => boolean
+ }
}
-export type newWorkflowLogicType = MakeLogicType<newWorkflowLogicValues, newWorkflowLogicActions>
+export type newWorkflowLogicType = MakeLogicType<
+ newWorkflowLogicValues,
+ newWorkflowLogicActions,
+ Record<string, any>,
+ newWorkflowLogicMeta
+>
export const newWorkflowLogic = kea<newWorkflowLogicType>([
path(['products', 'workflows', 'frontend', 'newWorkflowLogic']),
+ connect(() => ({
+ values: [
+ featureFlagLogic,
+ ['featureFlags'],
+ sceneAgentPanelLogic,
+ ['sceneIntegrationEnabled'],
+ router,
+ ['searchParams', 'location'],
+ ],
+ })),
actions({
+ startNewWorkflow: true,
showNewWorkflowModal: true,
hideNewWorkflowModal: true,
+ openEditorFromAiComposer: true,
createWorkflowFromTemplate: (template: HogFlowTemplate) => ({ template }),
createEmptyWorkflow: true,
}),
@@ -45,14 +123,57 @@ export const newWorkflowLogic = kea<newWorkflowLogicType>([
},
],
}),
- listeners(({ actions }) => ({
+ selectors({
+ // Same gate as the scene integration. Only the `test` variant, or a plain boolean rollout, qualifies.
+ aiFirstNewEnabled: [
+ (s) => [s.featureFlags, s.sceneIntegrationEnabled],
+ (featureFlags: FeatureFlagsSet, sceneIntegrationEnabled: boolean): boolean =>
+ sceneIntegrationEnabled && isAiFirstVariant(featureFlags),
+ ],
+ // Deep links with a starting point stay on the editor. Checked here so the scene never reads the flag early.
+ aiComposerAvailable: [
+ (s) => [s.featureFlags, s.sceneIntegrationEnabled, s.searchParams, s.location],
+ (
+ featureFlags: FeatureFlagsSet,
+ sceneIntegrationEnabled: boolean,
+ searchParams: Record<string, any>,
+ location: { pathname: string }
+ ): boolean =>
+ sceneIntegrationEnabled &&
+ isNewWorkflowRoute(location.pathname) &&
+ !searchParams.templateId &&
+ !searchParams.editTemplateId &&
+ !searchParams[TRIGGER_PREFILL_PARAM] &&
+ searchParams[EDITOR_MODE_PARAM] === AI_COMPOSER_MODE_VALUE &&
+ isAiFirstVariant(featureFlags),
+ ],
+ }),
+ listeners(({ actions, values }) => ({
+ startNewWorkflow: () => {
+ // Exposure is recorded at the click, and only when the composer could answer it.
+ if (values.sceneIntegrationEnabled) {
+ posthog.getFeatureFlag(FEATURE_FLAGS.WORKFLOWS_AI_FIRST_NEW)
+ }
+ if (values.aiFirstNewEnabled) {
+ router.actions.push(urls.workflowNew(), { [EDITOR_MODE_PARAM]: AI_COMPOSER_MODE_VALUE })
+ } else {
+ actions.showNewWorkflowModal()
+ }
+ },
+ openEditorFromAiComposer: () => {
+ posthog.capture('workflow ai composer escape hatch clicked')
+ actions.showNewWorkflowModal()
+ },
createWorkflowFromTemplate: ({ template }) => {
actions.hideNewWorkflowModal()
router.actions.push(urls.workflowNew(), { templateId: template.id })
},
createEmptyWorkflow: () => {
actions.hideNewWorkflowModal()
- router.actions.push(urls.workflowNew())
+ router.actions.push(
+ urls.workflowNew(),
+ values.aiFirstNewEnabled ? { [EDITOR_MODE_PARAM]: EDITOR_MODE_VALUE } : {}
+ )
},
})),
urlToAction(({ actions }) => ({
diff --git a/products/workflows/frontend/Workflows/workflowAgentContext.test.ts b/products/workflows/frontend/Workflows/workflowAgentContext.test.ts
index 458b049c0e0f..e32c8b537f7c 100644
--- a/products/workflows/frontend/Workflows/workflowAgentContext.test.ts
+++ b/products/workflows/frontend/Workflows/workflowAgentContext.test.ts
@@ -3,6 +3,7 @@ import { HogFunctionTemplateType } from '~/types'
import type { HogFlow } from './hogflows/types'
import {
EDITOR_STATE_MAX_CHARS,
+ buildNewWorkflowComposerContext,
buildWorkflowAgentContext,
redactWorkflowSecretInputs,
serializeWorkflowEditorState,
@@ -284,4 +285,20 @@ describe('workflowAgentContext', () => {
expect(instructionValues(items).some((value) => value.includes('designing-email-templates'))).toBe(false)
})
})
+
+ describe('buildNewWorkflowComposerContext', () => {
+ // A dismissal is global and never resets, so a chip closed on a workflow must not strip this page's instructions.
+ it('cannot be dismissed from the workflow editor scene, or from its own chip', () => {
+ const editorGroups = new Set(
+ buildWorkflowAgentContext(workflowWith({}), 'flow-1', templatesById)
+ .map((item) => item.dismissGroup)
+ .filter(Boolean)
+ )
+ const items = buildNewWorkflowComposerContext()
+
+ expect(items.every((item) => !editorGroups.has(item.dismissGroup))).toBe(true)
+ expect(items.find((item) => item.type === 'skill')?.dismissible).toBe(false)
+ expect(items.some((item) => item.value?.includes('workflows-create'))).toBe(true)
+ })
+ })
})
diff --git a/products/workflows/frontend/Workflows/workflowAgentContext.ts b/products/workflows/frontend/Workflows/workflowAgentContext.ts
index 4c28b3b93a89..3f7415cdd344 100644
--- a/products/workflows/frontend/Workflows/workflowAgentContext.ts
+++ b/products/workflows/frontend/Workflows/workflowAgentContext.ts
@@ -2,6 +2,7 @@ import { redactSecretHogFunctionInputs } from 'scenes/hog-functions/hog-function
import { CyclotronJobInputSchemaType, CyclotronJobInputType, HogFunctionTemplateType } from '~/types'
+import type { ComposerOverride } from 'products/posthog_ai/frontend/api/logics'
import { AttachedContextItem } from 'products/posthog_ai/frontend/api/types'
import { isEmailAction, isFunctionAction, isTriggerFunction } from './hogflows/steps/types'
@@ -11,6 +12,8 @@ import type { HogFlow } from './hogflows/types'
// the chip actually detaches the payload instead of only hiding the chip.
const SKILL_DISMISS_GROUP = 'workflow-scene-skill'
const EDITOR_STATE_DISMISS_GROUP = 'workflow-scene-state'
+// Own dismiss group: a dismissal is global and never resets, so a chip closed on a workflow must not strip this page.
+const NEW_WORKFLOW_DISMISS_GROUP = 'new-workflow-composer'
const BUILDING_WORKFLOWS_SKILL = 'building-workflows'
const DESIGNING_EMAIL_TEMPLATES_SKILL = 'designing-email-templates'
@@ -19,18 +22,23 @@ const DESIGNING_EMAIL_TEMPLATES_SKILL = 'designing-email-templates'
// as trusted `instructions` items. The skill bodies and tool schemas are not embedded: product skills
// are installed in the agent's sandbox, and the exec MCP tool already exposes the workflows commands,
// so naming them is enough to skip discovery.
-const PREAMBLE_CONTEXT_ITEM: AttachedContextItem = {
+const TOOLING_CONTEXT_ITEM: AttachedContextItem = {
type: 'instructions',
hidden: true,
dismissGroup: SKILL_DISMISS_GROUP,
value:
- `The user has the PostHog workflow editor open. Load the ${BUILDING_WORKFLOWS_SKILL} skill before your ` +
+ `Load the ${BUILDING_WORKFLOWS_SKILL} skill before your ` +
'first tool call; it covers the action/edge graph schema and the patch workflow. Act through the ' +
'workflows MCP tools (the exec `workflows-*` commands: workflows-get, workflows-patch-graph, ' +
'workflows-update, workflows-test-run, workflows-publish, workflows-logs, and the rest). Do not search ' +
'for tools; use the exec `info <tool>` command when you need a full input schema.',
}
+const PREAMBLE_CONTEXT_ITEM: AttachedContextItem = {
+ ...TOOLING_CONTEXT_ITEM,
+ value: `The user has the PostHog workflow editor open. ${TOOLING_CONTEXT_ITEM.value}`,
+}
+
const EDITOR_STATE_CONTEXT_ITEM: AttachedContextItem = {
type: 'instructions',
hidden: true,
@@ -56,6 +64,88 @@ export const WORKFLOW_AGENT_HEADLINES: string[] = [
export const EMAIL_EDITOR_AGENT_HEADLINES: string[] = ['How should this email look?']
+export const NEW_WORKFLOW_AGENT_HEADLINES: string[] = ['What workflow would you like to build today?']
+
+export const NEW_WORKFLOW_COMPOSER_OVERRIDE: ComposerOverride = {
+ hideRepositorySelector: true,
+ hideSuggestions: true,
+ hideRecentTasks: true,
+ // Not a takeover host, and the side panel is closed here, so nothing would receive the replay click.
+ hideOnboardingReplay: true,
+}
+
+export interface NewWorkflowSuggestion {
+ title: string
+ description: string
+ prompt: string
+}
+
+// The first is the data-driven ask; the rest follow the templates users pick most often.
+export const NEW_WORKFLOW_SUGGESTIONS: NewWorkflowSuggestion[] = [
+ {
+ title: 'Improve my conversion',
+ description: 'Look at the funnel and draft a campaign for the biggest drop-off',
+ prompt: 'Look at my conversion funnel and draft a campaign to improve the biggest drop-off',
+ },
+ {
+ title: 'Welcome new signups',
+ description: 'A short email sequence over the first week',
+ prompt: 'Send a welcome email sequence to new signups over their first week',
+ },
+ {
+ title: 'Alert on new support tickets',
+ description: 'Post to Slack when a ticket comes in',
+ prompt: 'Notify the team in Slack when a new support ticket comes in',
+ },
+ {
+ title: 'Finish onboarding',
+ description: 'Nudge people who started but never completed it',
+ prompt: 'Remind users who started onboarding but never finished it',
+ },
+ {
+ title: 'Win back inactive users',
+ description: 'Reach out after 30 days of silence',
+ prompt: 'Re-engage users who have been inactive for 30 days',
+ },
+ {
+ title: 'Webhook on upgrade',
+ description: 'Call my endpoint when a customer upgrades',
+ prompt: 'Send a webhook when a user upgrades their plan',
+ },
+ {
+ title: 'Triage alerts from Slack',
+ description: 'Investigate each new alert and reply with findings in the thread',
+ prompt: 'When an alert is posted in my Slack alerts channel, start an AI investigation and reply with the findings in the thread',
+ },
+ {
+ title: 'Celebrate a milestone',
+ description: 'Congratulate people when they hit one, and point at the next',
+ prompt: 'Send a congratulations email when a user reaches a milestone and point them at the next one',
+ },
+]
+
+// The fastest useful outcome from nothing is a draft in the editor, refined with the agent alongside.
+const DRAFT_FIRST_CONTEXT_ITEM: AttachedContextItem = {
+ type: 'instructions',
+ hidden: true,
+ dismissGroup: NEW_WORKFLOW_DISMISS_GROUP,
+ value:
+ 'The user is starting a new workflow from a description. Make workflows-create your first tool call and ' +
+ 'keep it minimal: the trigger plus the steps as placeholders, with placeholder email subjects and bodies. ' +
+ 'Do not ask clarifying questions first. The editor opens the draft the moment it exists, so fill in ' +
+ 'content and details afterwards with workflows-patch-graph and workflows-patch-action-email, then test. ' +
+ 'Never enable it.',
+}
+
+/** Skill pointer plus the draft-first instruction, no editor state. Not dismissible: the page only advances once the draft exists. */
+export function buildNewWorkflowComposerContext(): AttachedContextItem[] {
+ return [
+ { ...TOOLING_CONTEXT_ITEM, dismissGroup: NEW_WORKFLOW_DISMISS_GROUP },
+ { ...SKILL_CHIP_CONTEXT_ITEM, dismissGroup: NEW_WORKFLOW_DISMISS_GROUP, dismissible: false },
+ DRAFT_FIRST_CONTEXT_ITEM,
+ ]
+}
+
const EMAIL_EDITING_DISMISS_GROUP = 'workflow-scene-email-editing'
// Action IDs are arbitrary strings a workflow writer controls, and this one gets interpolated
diff --git a/products/workflows/frontend/WorkflowsScene.tsx b/products/workflows/frontend/WorkflowsScene.tsx
index 473cbe04bbef..bcbce31c2ffb 100644
--- a/products/workflows/frontend/WorkflowsScene.tsx
+++ b/products/workflows/frontend/WorkflowsScene.tsx
@@ -139,7 +139,7 @@ export function WorkflowsScene(props: WorkflowsSceneProps = {}): JSX.Element {
const { featureFlags } = useValues(featureFlagLogic)
const { openSetupModal } = useActions(integrationsLogic)
const { openNewCategoryModal } = useActions(optOutCategoriesLogic)
- const { showNewWorkflowModal } = useActions(newWorkflowLogic)
+ const { startNewWorkflow } = useActions(newWorkflowLogic)
const newChannelRestrictedReason = useRestrictedArea({
scope: RestrictionScope.Project,
minimumAccessLevel: TeamMembershipLevel.Admin,
@@ -269,7 +269,7 @@ export function WorkflowsScene(props: WorkflowsSceneProps = {}): JSX.Element {
product_type: ProductKey.WORKFLOWS,
intent_context: ProductIntentContext.WORKFLOW_CREATED,
})
- showNewWorkflowModal()
+ startNewWorkflow()
}}
type="primary"
size="small"
diff --git a/products/workflows/frontend/emptyState/workflowsEmptyState.tsx b/products/workflows/frontend/emptyState/workflowsEmptyState.tsx
index 3a3e69f35c9a..113949495b46 100644
--- a/products/workflows/frontend/emptyState/workflowsEmptyState.tsx
+++ b/products/workflows/frontend/emptyState/workflowsEmptyState.tsx
@@ -4,10 +4,10 @@ import { IconDecisionTree } from '@posthog/icons'
import { pngHoggie } from 'lib/brand/hoggies'
import type { SceneProductEmptyState } from 'lib/components/ProductEmptyState/types'
import { Scene } from 'scenes/sceneTypes'
-import { urls } from 'scenes/urls'
import { ProductKey } from '~/queries/schema/schema-general'
+import { urlForNewWorkflowComposer } from '../Workflows/newWorkflowLogic'
import { WorkflowsPreview } from './WorkflowsPreview'
import { workflowsSetupLogic } from './workflowsSetupLogic'
@@ -34,7 +34,8 @@ export const workflowsEmptyState: SceneProductEmptyState = {
},
primaryAction: {
label: 'New workflow',
- to: urls.workflowNew(),
+ // The same "start from nothing" intent as the list page's button, so it reaches the same surface.
+ to: urlForNewWorkflowComposer(),
},
docsUrl: 'https://posthog.com/docs/workflows',
previewLabel: 'Your journeys, once running',