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(phai): seed the new side panel composer from ask-max prompts (#69246)

Georgiy Tarasovff2ca74297e2
diff --git a/frontend/src/scenes/max/components/AiFirstMaxInstance.tsx b/frontend/src/scenes/max/components/AiFirstMaxInstance.tsx
index 1dccae5d7d8c..c5c85c8c588e 100644
--- a/frontend/src/scenes/max/components/AiFirstMaxInstance.tsx
+++ b/frontend/src/scenes/max/components/AiFirstMaxInstance.tsx
@@ -16,6 +16,7 @@ import { Intro } from '../Intro'
import { maxGlobalLogic } from '../maxGlobalLogic'
import { maxLogic } from '../maxLogic'
import { MaxThreadLogicProps, maxThreadLogic } from '../maxThreadLogic'
+import { phaiAiComposerSeedLogic } from '../phaiAiComposerSeedLogic'
import { Thread } from '../Thread'
import { MaxNotConfigured } from './MaxNotConfigured'
import { PhaiViewToggle } from './PhaiViewToggle'
@@ -107,7 +108,9 @@ export function AiFirstMaxInstance({ tabId }: AiFirstMaxInstanceProps): JSX.Elem
<PhaiViewToggle variant="lemon" />
</div>
<div className="flex flex-col flex-1 min-h-0">
- <EmbeddedRunner />
+ <BindLogic logic={phaiAiComposerSeedLogic} props={{}}>
+ <EmbeddedRunner />
+ </BindLogic>
</div>
</div>
)
diff --git a/frontend/src/scenes/max/components/PhaiSidePanelChat.tsx b/frontend/src/scenes/max/components/PhaiSidePanelChat.tsx
index e1ddfa92f320..b7f29477921e 100644
--- a/frontend/src/scenes/max/components/PhaiSidePanelChat.tsx
+++ b/frontend/src/scenes/max/components/PhaiSidePanelChat.tsx
@@ -1,5 +1,9 @@
+import { useMountedLogic } from 'kea'
+
import { SidePanelRunner } from 'products/posthog_ai/frontend/api/runner'
+import { phaiSidePanelComposerSeedLogic } from '../phaiSidePanelComposerSeedLogic'
+
// The client-side key for the embedded `taskTrackerSceneLogic` (and paired `runnerPanelLogic`) instance
// this panel binds — stable so the panel keeps the same in-flight run across re-renders of its host.
export const MAX_SIDE_PANEL_ID = 'max-side-panel'
@@ -12,6 +16,9 @@ export const MAX_SIDE_PANEL_ID = 'max-side-panel'
* replaced outright by the posthog_ai product surface.
*/
export function PhaiSidePanelChat(): JSX.Element {
+ // Bridges the legacy `initialMaxPrompt` side-panel option into this panel's new composer (see the logic).
+ useMountedLogic(phaiSidePanelComposerSeedLogic({ panelId: MAX_SIDE_PANEL_ID }))
+
return (
// `flex-1 min-h-0`, NOT `h-full`: the side panel hosts this inside a ScrollArea whose content
// grows with its children (`min-height: auto`), so a percentage height resolves against the
diff --git a/frontend/src/scenes/max/maxLogic.test.ts b/frontend/src/scenes/max/maxLogic.test.ts
index 930cf7eb0ed3..0dfd1596f1e9 100644
--- a/frontend/src/scenes/max/maxLogic.test.ts
+++ b/frontend/src/scenes/max/maxLogic.test.ts
@@ -87,6 +87,28 @@ describe('maxLogic', () => {
})
})
+ it('does not set autoRun for #panel=max:!Foo when the new panel view is active', async () => {
+ // In the new view the prompt is consumed by phaiSidePanelComposerSeedLogic; autoRun here too
+ // would make the hidden legacy thread fire askMax on top of the new composer's submit.
+ featureFlagLogic.mount()
+ featureFlagLogic.actions.setFeatureFlags([], { [FEATURE_FLAGS.PHAI_SANDBOX_MODE]: true })
+
+ sidePanelStateLogic.mount()
+ await expectLogic(sidePanelStateLogic, () => {
+ sidePanelStateLogic.actions.openSidePanel(SidePanelTab.Max, '!Foo')
+ }).toDispatchActions(['openSidePanel'])
+
+ logic = maxLogic({ panelId: SIDE_PANEL_PANEL_ID })
+ logic.mount()
+
+ await expectLogic(logic).toMatchValues({
+ autoRun: false,
+ question: 'Foo',
+ })
+
+ featureFlagLogic.unmount()
+ })
+
it('does not reset conversation when 404 occurs during active message generation', async () => {
router.actions.push('', {}, { panel: 'max' })
sidePanelStateLogic.mount()
diff --git a/frontend/src/scenes/max/maxLogic.tsx b/frontend/src/scenes/max/maxLogic.tsx
index 8758fdf878ce..75f67c69f75d 100644
--- a/frontend/src/scenes/max/maxLogic.tsx
+++ b/frontend/src/scenes/max/maxLogic.tsx
@@ -29,7 +29,7 @@ import {
import { PENDING_AI_PROMPT_KEY } from './max-storage-keys'
import { maxContextLogic } from './maxContextLogic'
-import { maxGlobalLogic } from './maxGlobalLogic'
+import { maxGlobalLogic, type PhaiViewMode } from './maxGlobalLogic'
import type { maxLogicType } from './maxLogicType'
import { MaxUIContext } from './maxTypes'
@@ -88,7 +88,7 @@ interface ParsedCommand {
question: string
}
-function parseCommandString(options: string): ParsedCommand {
+export function parseCommandString(options: string): ParsedCommand {
let remaining = options
// Check for mode parameter (format: mode=<value>:rest), remove it if present
@@ -109,14 +109,21 @@ function parseCommandString(options: string): ParsedCommand {
}
}
-function handleCommandString(options: string, actions: maxLogicType['actions']): void {
+function handleCommandString(options: string, actions: maxLogicType['actions'], effectivePhaiView: PhaiViewMode): void {
const parsed = parseCommandString(options)
// Note: The mode parameter is handled directly by maxThreadLogic in its afterMount
// to ensure the correct logic instance sets its own mode
if (parsed.autoRun) {
- actions.setAutoRun(true)
+ // In the new panel view the prompt is consumed by `phaiSidePanelComposerSeedLogic` instead; setting
+ // autoRun here too would make the (mounted but hidden) legacy thread fire `askMax` on top of the new
+ // composer's submit, so one CTA would start two agent runs. The view mode is a connected value
+ // (maxGlobalLogic is mounted with maxLogic), so it's never in an unknown state that could fall
+ // through to the legacy auto-run.
+ if (effectivePhaiView !== 'new') {
+ actions.setAutoRun(true)
+ }
}
if (parsed.question !== '') {
@@ -166,6 +173,7 @@ export const maxLogic = kea<maxLogicType>([
'toolSuggestions',
'conversationHistory',
'conversationHistoryLoading',
+ 'effectivePhaiView',
],
// Actions are lazy-loaded. In order to display their names in the UI, we're loading them here.
actionsModel({ params: 'include_count=1' }),
@@ -472,7 +480,7 @@ export const maxLogic = kea<maxLogicType>([
// Listen for when the side panel state changes and check for initial prompt
[sidePanelStateLogic.actionTypes.openSidePanel]: ({ tab, options }) => {
if (tab === SidePanelTab.Max && options && typeof options === 'string') {
- handleCommandString(options, actions)
+ handleCommandString(options, actions, values.effectivePhaiView)
}
},
scrollThreadToBottom: ({ behavior }) => {
@@ -632,7 +640,7 @@ export const maxLogic = kea<maxLogicType>([
sidePanelStateLogic.values.selectedTabOptions &&
typeof sidePanelStateLogic.values.selectedTabOptions === 'string'
) {
- handleCommandString(sidePanelStateLogic.values.selectedTabOptions, actions)
+ handleCommandString(sidePanelStateLogic.values.selectedTabOptions, actions, values.effectivePhaiView)
}
// Load conversation history on mount
diff --git a/frontend/src/scenes/max/phaiAiComposerSeedLogic.test.ts b/frontend/src/scenes/max/phaiAiComposerSeedLogic.test.ts
new file mode 100644
index 000000000000..dc02bde5cc70
--- /dev/null
+++ b/frontend/src/scenes/max/phaiAiComposerSeedLogic.test.ts
@@ -0,0 +1,48 @@
+import { MOCK_DEFAULT_ORGANIZATION } from 'lib/api.mock'
+
+import { router } from 'kea-router'
+
+import { urls } from 'scenes/urls'
+
+import { initKeaTests } from '~/test/init'
+
+import { composerSeedLogic } from 'products/posthog_ai/frontend/api/logics'
+
+import { phaiAiComposerSeedLogic } from './phaiAiComposerSeedLogic'
+
+describe('phaiAiComposerSeedLogic', () => {
+ let logic: ReturnType<typeof phaiAiComposerSeedLogic.build>
+ let seedLogic: ReturnType<typeof composerSeedLogic.build>
+
+ afterEach(() => {
+ logic?.unmount()
+ seedLogic?.unmount()
+ })
+
+ // `ask` is URL-controlled: without the org-level AI data-processing consent gate a shared link would
+ // create and run a task on open — the same gate the legacy `askMax` path and the side-panel bridge apply.
+ test.each([
+ { consent: true, autoSubmit: true },
+ { consent: false, autoSubmit: false },
+ ])(
+ 'forwards the /ai ask query as a seed with autoSubmit=$autoSubmit when consent is $consent',
+ ({ consent, autoSubmit }) => {
+ initKeaTests(true, undefined, undefined, {
+ ...MOCK_DEFAULT_ORGANIZATION,
+ is_ai_data_processing_approved: consent,
+ })
+ seedLogic = composerSeedLogic()
+ seedLogic.mount()
+
+ router.actions.push(urls.ai(undefined, 'Explain this dashboard'))
+
+ logic = phaiAiComposerSeedLogic()
+ logic.mount()
+
+ expect(seedLogic.values.seed).toEqual({
+ prompt: 'Explain this dashboard',
+ autoSubmit,
+ })
+ }
+ )
+})
diff --git a/frontend/src/scenes/max/phaiAiComposerSeedLogic.ts b/frontend/src/scenes/max/phaiAiComposerSeedLogic.ts
new file mode 100644
index 000000000000..ba9cc4804ae3
--- /dev/null
+++ b/frontend/src/scenes/max/phaiAiComposerSeedLogic.ts
@@ -0,0 +1,33 @@
+import { connect, kea, path } from 'kea'
+import { urlToAction } from 'kea-router'
+
+import { urls } from 'scenes/urls'
+
+import { composerSeedLogic } from 'products/posthog_ai/frontend/api/logics'
+
+import { maxGlobalLogic } from './maxGlobalLogic'
+import type { phaiAiComposerSeedLogicType } from './phaiAiComposerSeedLogicType'
+
+/**
+ * Forwards the existing `/ai?ask=...` deep link into the new task composer. This logic is mounted only while
+ * the new PostHog AI view is rendered, leaving the legacy `maxLogic` query handling unchanged.
+ */
+export const phaiAiComposerSeedLogic = kea<phaiAiComposerSeedLogicType>([
+ path(['scenes', 'max', 'phaiAiComposerSeedLogic']),
+
+ connect({
+ values: [maxGlobalLogic, ['dataProcessingAccepted']],
+ actions: [composerSeedLogic, ['setSeed']],
+ }),
+
+ urlToAction(({ actions, values }) => ({
+ [urls.ai()]: (_, search) => {
+ if (search.ask && !search.chat) {
+ // `ask` is URL-controlled — same org-level AI data-processing consent gate as the legacy
+ // `askMax` path: without approval the seed only prefills the composer, and the user's own
+ // send goes through the composer's consent flow.
+ actions.setSeed({ prompt: String(search.ask), autoSubmit: values.dataProcessingAccepted })
+ }
+ },
+ })),
+])
diff --git a/frontend/src/scenes/max/phaiSidePanelComposerSeedLogic.test.ts b/frontend/src/scenes/max/phaiSidePanelComposerSeedLogic.test.ts
new file mode 100644
index 000000000000..0eaaabae0680
--- /dev/null
+++ b/frontend/src/scenes/max/phaiSidePanelComposerSeedLogic.test.ts
@@ -0,0 +1,104 @@
+import { MOCK_DEFAULT_ORGANIZATION } from 'lib/api.mock'
+
+import { expectLogic } from 'kea-test-utils'
+
+import { sidePanelStateLogic } from '~/layout/navigation-3000/sidepanel/sidePanelStateLogic'
+import { useMocks } from '~/mocks/jest'
+import { initKeaTests } from '~/test/init'
+import { SidePanelTab } from '~/types'
+
+import { taskTrackerSceneLogic } from 'products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic'
+
+import { phaiSidePanelComposerSeedLogic } from './phaiSidePanelComposerSeedLogic'
+
+describe('phaiSidePanelComposerSeedLogic', () => {
+ let seedLogic: ReturnType<typeof phaiSidePanelComposerSeedLogic.build>
+ let trackerLogic: ReturnType<typeof taskTrackerSceneLogic.build>
+ let createCount: number
+ let runCount: number
+
+ // No hook calls in here (rules-of-hooks) — mocks are set up in beforeEach / the test bodies.
+ const mountPanelLogics = (): void => {
+ sidePanelStateLogic.mount()
+ trackerLogic = taskTrackerSceneLogic({ panelId: 'max-side-panel' })
+ trackerLogic.mount()
+ seedLogic = phaiSidePanelComposerSeedLogic({ panelId: 'max-side-panel' })
+ seedLogic.mount()
+ }
+
+ beforeEach(() => {
+ createCount = 0
+ runCount = 0
+ useMocks({
+ get: {
+ '/api/projects/:team/tasks/': { results: [], count: 0 },
+ '/api/projects/:team/tasks/repositories/': { repositories: [] },
+ '/api/environments/:team/integrations/': { results: [] },
+ },
+ post: {
+ '/api/projects/:team/tasks/': async ({ request }) => {
+ createCount++
+ return [200, { id: 'new-task', ...((await request.json()) as Record<string, any>) }]
+ },
+ '/api/projects/:team/tasks/:id/run/': () => {
+ runCount++
+ return [200, { id: 'new-task' }]
+ },
+ },
+ })
+ })
+
+ afterEach(() => {
+ seedLogic?.unmount()
+ trackerLogic?.unmount()
+ })
+
+ // The org-level AI data-processing consent gate: an auto-run CTA (`!`-prefixed prompt) must never start
+ // an agent run before the org approved AI data processing — the legacy path blocks this in `askMax`, and
+ // dropping the `dataProcessingAccepted` check in the seed bridge would silently ship unconsented sandbox
+ // runs (the tasks backend has no server-side consent check).
+ it('holds an auto-run seed as prefill and sends no task create/run when consent is missing', async () => {
+ useMocks({
+ get: {
+ // The org bootstrapped via app context below gets re-fetched on organizationLogic mount —
+ // keep the API in agreement so a late load can't flip the consent value mid-test.
+ '/api/organizations/@current/': () => [
+ 200,
+ { ...MOCK_DEFAULT_ORGANIZATION, is_ai_data_processing_approved: false },
+ ],
+ },
+ })
+ initKeaTests(true, undefined, undefined, {
+ ...MOCK_DEFAULT_ORGANIZATION,
+ is_ai_data_processing_approved: false,
+ })
+ mountPanelLogics()
+
+ sidePanelStateLogic.actions.openSidePanel(SidePanelTab.Max, '!Foo bar')
+ await expectLogic(trackerLogic).toFinishAllListeners()
+
+ expect(createCount).toBe(0)
+ expect(runCount).toBe(0)
+ // The prompt is retained as a prefill so consent approval doesn't lose it; nothing was submitted.
+ expect(trackerLogic.values.newTaskData.description).toBe('Foo bar')
+ expect(trackerLogic.values.activeCreation).toBeNull()
+ })
+
+ // Control for the test above: with consent accepted the same CTA must create and run the task — proving
+ // the no-request assertion holds because of the gate, not because the bridge stopped forwarding seeds
+ // altogether. The org is passed explicitly since app context persists across tests in this file.
+ it('auto-submits an auto-run seed when consent is accepted', async () => {
+ initKeaTests(true, undefined, undefined, {
+ ...MOCK_DEFAULT_ORGANIZATION,
+ is_ai_data_processing_approved: true,
+ })
+ mountPanelLogics()
+
+ sidePanelStateLogic.actions.openSidePanel(SidePanelTab.Max, '!Foo bar')
+ await expectLogic(trackerLogic).toFinishAllListeners()
+
+ expect(createCount).toBe(1)
+ expect(runCount).toBe(1)
+ expect(trackerLogic.values.activeCreation).toMatchObject({ taskId: 'new-task' })
+ })
+})
diff --git a/frontend/src/scenes/max/phaiSidePanelComposerSeedLogic.ts b/frontend/src/scenes/max/phaiSidePanelComposerSeedLogic.ts
new file mode 100644
index 000000000000..22f348efc3fc
--- /dev/null
+++ b/frontend/src/scenes/max/phaiSidePanelComposerSeedLogic.ts
@@ -0,0 +1,78 @@
+import { afterMount, connect, kea, key, listeners, path, props } from 'kea'
+
+import { sidePanelStateLogic } from '~/layout/navigation-3000/sidepanel/sidePanelStateLogic'
+import { SidePanelTab } from '~/types'
+
+import { ComposerSeed, composerSeedLogic } from 'products/posthog_ai/frontend/api/logics'
+
+import { maxGlobalLogic } from './maxGlobalLogic'
+import { parseCommandString } from './maxLogic'
+import type { phaiSidePanelComposerSeedLogicType } from './phaiSidePanelComposerSeedLogicType'
+
+export interface PhaiSidePanelComposerSeedLogicProps {
+ /** The embedded composer's panel key — the same one passed to its `taskTrackerSceneLogic`/`composerSeedLogic`. */
+ panelId: string
+}
+
+// Parse the side-panel option string exactly as legacy Max does (`mode=` stripped, leading `!` = auto-run)
+// and forward the prompt to the surface seam. Reusing `parseCommandString` keeps the `!` convention
+// byte-for-byte identical to the legacy consumer; only the prompt + auto-submit flag cross into the surface.
+function forwardSeed(
+ options: string | null | undefined,
+ dataProcessingAccepted: boolean,
+ setSeed: (seed: ComposerSeed) => void
+): void {
+ if (typeof options !== 'string') {
+ return
+ }
+ const { autoRun, question } = parseCommandString(options)
+ if (!question) {
+ return
+ }
+ // Same org-level AI data-processing consent gate as the legacy `askMax` path: without approval an
+ // auto-run seed only prefills the composer — it never starts an agent run. The user's own send then
+ // goes through the composer's consent flow.
+ setSeed({ prompt: question, autoSubmit: autoRun && dataProcessingAccepted })
+}
+
+/**
+ * Bridges the legacy `initialMaxPrompt` side-panel option into the new PostHog AI composer. `openMax` (and any
+ * other producer) still rides the prompt on `openSidePanel(SidePanelTab.Max, prompt)` — the option only the
+ * legacy `maxLogic` used to read. Mounted by the new view's panel (`PhaiSidePanelChat`), this reads the same
+ * option and seeds the surface's `composerSeedLogic`, so a single consumer fixes every producer without
+ * touching `openMax` or the legacy consumption path. The two orderings both hold: a CTA that fires before this
+ * panel mounts leaves the option on `sidePanelStateLogic` for the afterMount read; a CTA fired while the panel
+ * is already open is caught by the `openSidePanel` listener.
+ */
+export const phaiSidePanelComposerSeedLogic = kea<phaiSidePanelComposerSeedLogicType>([
+ path(['scenes', 'max', 'phaiSidePanelComposerSeedLogic']),
+ props({} as PhaiSidePanelComposerSeedLogicProps),
+ key((props) => props.panelId),
+
+ connect((props: PhaiSidePanelComposerSeedLogicProps) => ({
+ values: [
+ sidePanelStateLogic,
+ ['selectedTab', 'selectedTabOptions'],
+ maxGlobalLogic,
+ ['dataProcessingAccepted'],
+ ],
+ actions: [composerSeedLogic({ panelId: props.panelId }), ['setSeed']],
+ })),
+
+ listeners(({ actions, values }) => ({
+ [sidePanelStateLogic.actionTypes.openSidePanel]: ({ tab, options }) => {
+ if (tab !== SidePanelTab.Max) {
+ return
+ }
+ forwardSeed(options, values.dataProcessingAccepted, actions.setSeed)
+ },
+ })),
+
+ afterMount(({ actions, values }) => {
+ // A CTA fires `openSidePanel` before this panel mounts, so the prompt is already sitting on
+ // `sidePanelStateLogic` by the time we mount — pick it up (mirrors legacy maxLogic's afterMount read).
+ if (values.selectedTab === SidePanelTab.Max) {
+ forwardSeed(values.selectedTabOptions, values.dataProcessingAccepted, actions.setSeed)
+ }
+ }),
+])
diff --git a/products/posthog_ai/frontend/api/logics.ts b/products/posthog_ai/frontend/api/logics.ts
index fd8216afef16..11d16bc1c494 100644
--- a/products/posthog_ai/frontend/api/logics.ts
+++ b/products/posthog_ai/frontend/api/logics.ts
@@ -49,3 +49,9 @@ export type { UseToolStreamListenerOptions } from '../hooks/useToolStream'
// header back button — outside the lazy panel chunk (Tier 1 `api/runner`).
export { runnerPanelLogic } from '../logics/runnerPanelLogic'
export type { RunnerPanelLogicProps, ActiveCreation } from '../logics/runnerPanelLogic'
+
+// --- Composer seed hand-off (headless) ---
+// A one-shot store that lets a host seed a not-yet-mounted composer with an initial prompt (optionally
+// auto-submitting it); the paired `taskTrackerSceneLogic` consumes it on mount or when it arrives.
+export { composerSeedLogic } from '../logics/composerSeedLogic'
+export type { ComposerSeed, ComposerSeedLogicProps } from '../logics/composerSeedLogic'
diff --git a/products/posthog_ai/frontend/logics/composerSeedLogic.ts b/products/posthog_ai/frontend/logics/composerSeedLogic.ts
new file mode 100644
index 000000000000..99e6583ecdc8
--- /dev/null
+++ b/products/posthog_ai/frontend/logics/composerSeedLogic.ts
@@ -0,0 +1,46 @@
+import { actions, kea, key, path, props, reducers } from 'kea'
+
+import type { composerSeedLogicType } from './composerSeedLogicType'
+
+// A prompt to prefill into the composer, plus whether to submit it straight away. Kept deliberately
+// generic — the Max-specific `!`/`mode=` command-string parsing happens in the consuming app before the
+// seed reaches this surface, so this seam never learns the side-panel option format.
+export interface ComposerSeed {
+ prompt: string
+ autoSubmit: boolean
+}
+
+// `panelId` keys the seed to a specific embedded composer (e.g. Max's side panel runner), matching the
+// `taskTrackerSceneLogic`/`runnerPanelLogic` keying so the paired instances stay aligned. No `panelId`
+// resolves to the same `'scene'` key those logics fall back to.
+export interface ComposerSeedLogicProps {
+ panelId?: string
+}
+
+/**
+ * A tiny hand-off store that lets a host seed a not-yet-mounted composer with an initial prompt. A producer
+ * (a main-app consumer of this surface) dispatches `setSeed`; the paired `taskTrackerSceneLogic` picks it up
+ * either on its own mount (the producer fired first — the common case, a CTA opening the panel) or via the
+ * `setSeed` action when the composer is already mounted. Consume-once: the consumer clears it with
+ * `consumeSeed` after applying, so reopening the panel later never re-seeds.
+ */
+export const composerSeedLogic = kea<composerSeedLogicType>([
+ path(['products', 'posthog_ai', 'frontend', 'logics', 'composerSeedLogic']),
+ props({} as ComposerSeedLogicProps),
+ key((props) => props.panelId ?? 'scene'),
+
+ actions({
+ setSeed: (seed: ComposerSeed) => ({ seed }),
+ consumeSeed: true,
+ }),
+
+ reducers({
+ seed: [
+ null as ComposerSeed | null,
+ {
+ setSeed: (_, { seed }) => seed,
+ consumeSeed: () => null,
+ },
+ ],
+ }),
+])
diff --git a/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.test.ts b/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.test.ts
index 9f7084df6c57..32d47818b51a 100644
--- a/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.test.ts
+++ b/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.test.ts
@@ -7,6 +7,7 @@ import { useMocks } from '~/mocks/jest'
import { initKeaTests } from '~/test/init'
import { attachedContextLogic } from '../../api/logics'
+import { composerSeedLogic } from '../../logics/composerSeedLogic'
import { OriginProduct, Task, TaskRunEnvironment, TaskRunStatus } from '../../types/taskTypes'
import { taskTrackerSceneLogic } from './taskTrackerSceneLogic'
@@ -225,4 +226,99 @@ describe('taskTrackerSceneLogic', () => {
expect(logic.values.historyExpanded).toBe(false)
expect(router.values.location.pathname).toContain(expectedPath ?? initialPath)
})
+
+ // A CTA opens the panel and stamps its prompt onto composerSeedLogic BEFORE the composer mounts, so the
+ // seed must be picked up on mount — this is the live breakage the seam fixes (the prompt was dropped).
+ // autoSubmit=false must only prefill, never send. Guards the afterMount pickup, the consume-once clear,
+ // and that a non-auto seed doesn't submit.
+ it('picks up a seed set before mount and prefills without submitting when autoSubmit is false', async () => {
+ const seedLogic = composerSeedLogic()
+ seedLogic.mount()
+ seedLogic.actions.setSeed({ prompt: 'analyze churn', autoSubmit: false })
+
+ logic.mount()
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(logic.values.newTaskData.description).toBe('analyze churn')
+ expect(seedLogic.values.seed).toBeNull()
+ // No submit: submitting opens an optimistic activeCreation, prefill-only leaves it null.
+ expect(logic.values.activeCreation).toBeNull()
+
+ seedLogic.unmount()
+ })
+
+ // A seed arriving while the composer is already mounted (the panel was open when another CTA fired) must
+ // apply immediately via the setSeed listener, and autoSubmit=true must send it. Re-applying afterwards must
+ // not re-submit — a reopened panel must never resend a stale prompt. Guards the listener path, the
+ // auto-submit wiring, and consume-once.
+ it('applies a seed that arrives while mounted, auto-submits it, and does not resubmit once consumed', async () => {
+ let createCount = 0
+ useMocks({
+ post: {
+ '/api/projects/:team/tasks/': async ({ request }) => {
+ createCount++
+ createBody = (await request.json()) as Record<string, any>
+ return [200, { id: 'new-task', ...createBody }]
+ },
+ '/api/projects/:team/tasks/:id/run/': () => [200, { id: 'new-task' }],
+ },
+ })
+
+ logic.mount()
+ await expectLogic(logic).toFinishAllListeners()
+
+ composerSeedLogic().actions.setSeed({ prompt: 'summarize experiment', autoSubmit: true })
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(createBody).toMatchObject({ description: 'summarize experiment', repository: null })
+ expect(logic.values.activeCreation).toMatchObject({ taskId: 'new-task' })
+ expect(composerSeedLogic().values.seed).toBeNull()
+ expect(createCount).toBe(1)
+
+ // Consumed seed is inert: re-triggering must not create a second task.
+ logic.actions.applyComposerSeed()
+ await expectLogic(logic).toFinishAllListeners()
+ expect(createCount).toBe(1)
+ })
+
+ // A seed arriving while a submit is in flight must not start a second concurrent create/run (the two
+ // requests would fight over the composer and activeCreation) and must not be lost: it stays pending and
+ // applies once the submission resolves — auto-submitting then, or surviving the post-submit form reset
+ // as a prefill. Guards the isSubmittingTask hold in applyComposerSeed and the reset-before-success order.
+ it.each([
+ { autoSubmit: true, expectedCreates: 2 },
+ { autoSubmit: false, expectedCreates: 1 },
+ ])(
+ 'holds a seed arriving mid-submit and applies it after the submission resolves (autoSubmit=$autoSubmit)',
+ async ({ autoSubmit, expectedCreates }) => {
+ let createCount = 0
+ useMocks({
+ post: {
+ '/api/projects/:team/tasks/': async ({ request }) => {
+ createCount++
+ createBody = (await request.json()) as Record<string, any>
+ return [200, { id: `task-${createCount}`, ...createBody }]
+ },
+ '/api/projects/:team/tasks/:id/run/': () => [200, { id: 'run-1' }],
+ },
+ })
+ logic.mount()
+
+ composerSeedLogic().actions.setSeed({ prompt: 'first', autoSubmit: true })
+ // The first submit is now in flight; a second CTA fires before it resolves.
+ composerSeedLogic().actions.setSeed({ prompt: 'second', autoSubmit })
+ // Held, not applied: the seed is still pending and no second submission started.
+ expect(composerSeedLogic().values.seed).toMatchObject({ prompt: 'second' })
+
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(createCount).toBe(expectedCreates)
+ expect(composerSeedLogic().values.seed).toBeNull()
+ if (autoSubmit) {
+ expect(createBody).toMatchObject({ description: 'second' })
+ } else {
+ expect(logic.values.newTaskData.description).toBe('second')
+ }
+ }
+ )
})
diff --git a/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.ts b/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.ts
index f6b0b6c777b0..30c348956c63 100644
--- a/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.ts
+++ b/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.ts
@@ -17,6 +17,7 @@ import {
import { attachedContextItemKey, attachedContextLogic, runStreamLogic } from '../../api/logics'
import type { SuggestionGroup, SuggestionItem } from '../../api/primitives'
import { DEFAULT_HEADLINES, pickHeadline } from '../../api/primitives'
+import { composerSeedLogic } from '../../logics/composerSeedLogic'
import { runnerPanelLogic } from '../../logics/runnerPanelLogic'
import { tasksLogic } from '../../logics/tasksLogic'
import type { RepositoryConfig, Task } from '../../types/taskTypes'
@@ -78,6 +79,8 @@ export const taskTrackerSceneLogic = kea<taskTrackerSceneLogicType>([
['contextItems'],
aiConsentLogic,
['dataProcessingAccepted'],
+ composerSeedLogic(props),
+ ['seed'],
],
actions: [
runnerPanelLogic(props),
@@ -88,6 +91,8 @@ export const taskTrackerSceneLogic = kea<taskTrackerSceneLogicType>([
['loadIntegrationsSuccess'],
attachedContextLogic,
['markContextSent'],
+ composerSeedLogic(props),
+ ['consumeSeed', 'setSeed'],
],
})),
@@ -108,6 +113,8 @@ export const taskTrackerSceneLogic = kea<taskTrackerSceneLogicType>([
updateActiveCreationRun: (runId: string) => ({ runId }),
blockOnConsent: true,
clearConsentBlock: true,
+ // Pulls any pending `composerSeedLogic` seed into the composer (prefill + optional auto-submit).
+ applyComposerSeed: true,
}),
reducers({
@@ -294,8 +301,10 @@ export const taskTrackerSceneLogic = kea<taskTrackerSceneLogicType>([
router.actions.push(`/tasks/${newTask.id}`)
}
- actions.submitNewTaskSuccess()
+ // Reset before signaling success: the success listener applies any seed held during this
+ // submission, and resetting afterwards would wipe that seed's prefill.
actions.resetNewTaskData()
+ actions.submitNewTaskSuccess()
actions.loadTasks(values.taskListParams)
actions.loadRepositories()
} catch (error) {
@@ -323,6 +332,40 @@ export const taskTrackerSceneLogic = kea<taskTrackerSceneLogicType>([
}
actions.setActiveCreation({ streamKey: runId, taskId: values.activeCreation.taskId, runId })
},
+ // A seed arriving while this composer is already mounted (the panel was open when the host set it).
+ // `setSeed` is connected from this instance's props-keyed seed logic — the bare `composerSeedLogic`
+ // resolves to the default 'scene' key and would leave every embedded (panelId) instance deaf to its
+ // own seeds. (A computed `composerSeedLogic(props).actionTypes.setSeed` key would work too, but the
+ // call expression crashes kea-typegen once the seed logic's type file exists.)
+ setSeed: () => {
+ actions.applyComposerSeed()
+ },
+ applyComposerSeed: () => {
+ const seed = values.seed
+ if (!seed) {
+ return
+ }
+ // A seed applied while a submit is in flight would start a second concurrent create/run (both
+ // fighting over the composer and `activeCreation`), and the in-flight submit's success reset
+ // would wipe a prefill. Leave it pending; the `submitNewTaskSuccess`/`Failure` listeners
+ // re-apply it once the submission resolves, so the newest CTA still lands.
+ if (values.isSubmittingTask) {
+ return
+ }
+ // Consume-once: clear before applying so a re-entrant dispatch can't double-apply/submit.
+ actions.consumeSeed()
+ actions.setNewTaskData({ description: seed.prompt })
+ if (seed.autoSubmit) {
+ actions.submitNewTask()
+ }
+ },
+ // Pick up a seed that was deliberately held while a submission was in flight (see `applyComposerSeed`).
+ submitNewTaskSuccess: () => {
+ actions.applyComposerSeed()
+ },
+ submitNewTaskFailure: () => {
+ actions.applyComposerSeed()
+ },
})),
events(({ actions, values, cache }) => ({
@@ -335,6 +378,9 @@ export const taskTrackerSceneLogic = kea<taskTrackerSceneLogicType>([
// loadIntegrations ourselves. loadIntegrationsSuccess covers that first load; this call covers
// integrations already cached by an earlier mount.
actions.maybeAutoSelectIntegration()
+ // A host commonly seeds the composer before this logic mounts (a CTA opens the panel, then the
+ // panel mounts us), so pick up any pending seed now; the `setSeed` listener covers the reverse order.
+ actions.applyComposerSeed()
},
beforeUnmount: () => {
// Release the manually-mounted optimistic stream if the whole scene unmounts mid-create — the