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(flags): start a cleanup assessment from the flag page (#106731)

James Gillb93302d2bcdb
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index 731472f4cc4d..cf09a3ed596c 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -8973,9 +8973,13 @@ snapshots:
scenes-app-feature-flags--new-remote-config-flag-payload-error--light:
hash: v1.k794b7964.bbbbecef36aa418ff943f76d2006e75aec34f4ed6b26c4303ad005cbc95771ce.t6SkxtqE_6K7m6nlXwksQYnWs2s91AkmcYNUBy5ao-8
scenes-app-feature-flags--stale-feature-flag--dark:
- hash: v1.k794b7964.214b934af2eb71704ef4af64e7bcfc3fbb28ad3773918bda4e44c20baeafcbad.8sHPg_xq9nSmcUHiVqmWx5xtfnUGFA7o96H2Xe4xWwE
+ hash: v1.k794b7964.a5c6ecebf63f113c10df1a1b54b48141b7763f4d1f19f9223f6e445477b7d7f8.I7PbADnaKTfiWr8aPI3zmO0xG_mPSWRVi29ovh4okrs
scenes-app-feature-flags--stale-feature-flag--light:
- hash: v1.k794b7964.b8b76f0cb2539ca5dace61ff7cdb75ff0d749efbb3c682d79cd5fd7cd9ab95bf.0131PJ9_-uAsdJezfweIeC_AYlVSHdn6Q9WJ2chWHy4
+ hash: v1.k794b7964.1ef0d9bb0fca7ee269757da72cef3a76944c54ac5e9407bdbe94c06235d74d66.Wj3AxyieC5KU2CE2lWUuP023ZGNyZjKbvrVkIwBUtGs
+ scenes-app-feature-flags--stale-feature-flag-with-ai-assessment--dark:
+ hash: v1.k794b7964.879c80254780c71338fb0258376f5469a8944e3a87cfa3c8cc2564ed3a7a5467.f82OTEBhWE3vzszLX0hUYSdbFRGGAFBBJLr6DO6d6SM
+ scenes-app-feature-flags--stale-feature-flag-with-ai-assessment--light:
+ hash: v1.k794b7964.79f79b458c0f5a3173f3242bc43461c49515d6a59bcc6fb8205d66a026c9c1e5.79aA16orR_C8exlJGbtSPlLaYQRUoY4VBJl4AyeDG5M
scenes-app-feature-flags-code-examples--code-instructions-node-with-group-multivariate-flag-local-evaluation--dark:
hash: v1.k794b7964.33b7e69158cdb17991413a077b7dac6e915f6899c917fea9086f39fb02409699.paRiPQ8Dk84qM73rCI6ccr0k9jO1Oy0PpXtRG5PfiTM
scenes-app-feature-flags-code-examples--code-instructions-node-with-group-multivariate-flag-local-evaluation--light:
diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsx
index b034820e50a3..46241f4037cb 100644
--- a/frontend/src/lib/constants.tsx
+++ b/frontend/src/lib/constants.tsx
@@ -330,6 +330,7 @@ export const FEATURE_FLAGS = {
EXPERIMENTS_METRICS_RECALCULATION: 'experiments-metrics-recalculation', // owner: @rodrigoi #team-experiments
EXPERIMENTS_SHOW_SQL: 'experiments-show-sql', // owner: @jurajmajerik #team-experiments
EXPERIMENTS_SYNC_QUERIES: 'experiments-sync-queries', // owner: @andehen #team-experiments
+ FEATURE_FLAG_CLEANUP_ASSESSMENT: 'feature-flag-cleanup-assessment', // owner: #team-feature-flags, kill switch for the flag-page "Review cleanup with AI" action
FEATURE_FLAG_COHORT_CREATION: 'feature-flag-cohort-creation', // owner: #team-feature-flags
FEATURE_FLAG_CREATION_INTENTS: 'feature-flag-creation-intents', // owner: #team-feature-flags
FEATURE_FLAG_DRAG_DROP_CONDITIONS: 'feature-flag-drag-drop-conditions', // owner: @gustavo #team-feature-flags
diff --git a/frontend/src/scenes/feature-flags/FeatureFlags.stories.tsx b/frontend/src/scenes/feature-flags/FeatureFlags.stories.tsx
index bc91ce6bc7d6..120d0612a8da 100644
--- a/frontend/src/scenes/feature-flags/FeatureFlags.stories.tsx
+++ b/frontend/src/scenes/feature-flags/FeatureFlags.stories.tsx
@@ -180,6 +180,27 @@ export const StaleFeatureFlag: Story = {
},
}
+export const StaleFeatureFlagWithAiAssessment: Story = {
+ parameters: {
+ pageUrl: urls.featureFlag(STALE_FLAG_ID),
+ featureFlags: [
+ FEATURE_FLAGS.REALTIME_COHORT_FLAG_TARGETING,
+ FEATURE_FLAGS.PHAI_SANDBOX_MODE,
+ FEATURE_FLAGS.FEATURE_FLAG_CLEANUP_ASSESSMENT,
+ ],
+ },
+ play: async ({ canvasElement }) => {
+ await waitFor(
+ () => {
+ if (!canvasElement.querySelector('[data-attr="feature-flag-stale-banner-review-cleanup"]')) {
+ throw new Error('AI assessment action not rendered')
+ }
+ },
+ { timeout: 30000 }
+ )
+ },
+}
+
export const FeatureFlagNotFound: Story = {
parameters: {
pageUrl: urls.featureFlag(1111111111111),
diff --git a/frontend/src/scenes/feature-flags/featureFlagAiContext.test.ts b/frontend/src/scenes/feature-flags/featureFlagAiContext.test.ts
index 2d2a3b60f64b..c7759671d0eb 100644
--- a/frontend/src/scenes/feature-flags/featureFlagAiContext.test.ts
+++ b/frontend/src/scenes/feature-flags/featureFlagAiContext.test.ts
@@ -10,7 +10,12 @@ import {
import { wrapWithPosthogContext } from 'products/posthog_ai/frontend/utils/posthogContextBlock'
-import { featureFlagContextItems, mutationTargetsFeatureFlag } from './featureFlagAiContext'
+import {
+ FEATURE_FLAG_CLEANUP_SKILL,
+ featureFlagCleanupAssessmentContextItems,
+ featureFlagContextItems,
+ mutationTargetsFeatureFlag,
+} from './featureFlagAiContext'
// The backend's own cap on a text attachment (MAX_TEXT_LENGTH in the posthog_ai backend). Asserting
// the literal rather than importing the frontend constant is deliberate: raising the frontend cap
@@ -133,6 +138,59 @@ describe('featureFlagAiContext', () => {
expect(JSON.parse(value).release_condition_count).toBe(1)
})
+ describe('featureFlagCleanupAssessmentContextItems', () => {
+ it('includes the cleanup skill for the agent', () => {
+ const items = featureFlagCleanupAssessmentContextItems(baseFeatureFlag, 123)
+
+ expect(items).toContainEqual(expect.objectContaining({ type: 'skill', key: FEATURE_FLAG_CLEANUP_SKILL }))
+ })
+
+ it('tells the agent this request is assessment only and not a green light to change the flag', () => {
+ const instructions = featureFlagCleanupAssessmentContextItems(baseFeatureFlag, 123).find(
+ (item) => item.type === 'instructions'
+ )
+
+ expect(instructions?.value).toContain(FEATURE_FLAG_CLEANUP_SKILL)
+ expect(instructions?.value).toMatch(/assessment only/i)
+ expect(instructions?.value).toMatch(/re-fetch its current definition/i)
+ expect(instructions?.value).toMatch(/do not.*change this flag/i)
+ })
+
+ it('never puts the flag key or description inside the trusted instruction text', () => {
+ // The flag's own key/name are project-authored strings a customer chose, so they must stay
+ // in the untrusted `feature_flag_cleanup_target` item, never interpolated into the trusted
+ // block the agent is told to follow unconditionally.
+ const flag = { ...baseFeatureFlag, key: 'a-distinctive-flag-key', name: 'a distinctive description' }
+ const instructions = featureFlagCleanupAssessmentContextItems(flag, 123).find(
+ (item) => item.type === 'instructions'
+ )
+
+ expect(instructions?.value).not.toContain('a-distinctive-flag-key')
+ expect(instructions?.value).not.toContain('a distinctive description')
+ })
+
+ it('carries the saved project, id, and key as untrusted data the agent can act on', () => {
+ const block = wrapWithPosthogContext(
+ 'assess this flag',
+ featureFlagCleanupAssessmentContextItems(baseFeatureFlag, 123)
+ )
+ const target = featureFlagCleanupAssessmentContextItems(baseFeatureFlag, 123).find(
+ (item) => item.type === 'feature_flag_cleanup_target'
+ )
+
+ expect(JSON.parse(target?.value ?? '')).toEqual({
+ project_id: 123,
+ id: baseFeatureFlag.id,
+ key: baseFeatureFlag.key,
+ })
+ // The trusted block may name the item ("the feature_flag_cleanup_target item") without
+ // leaking its data - the flag's own key is the thing that must stay out of it.
+ const trustedBlock = block.match(/<posthog_trusted_context>[\s\S]*?<\/posthog_trusted_context>/)?.[0] ?? ''
+ expect(trustedBlock).not.toContain(baseFeatureFlag.key)
+ expect(block).toContain(baseFeatureFlag.key)
+ })
+ })
+
test.each([
['the same id as a number', { id: 1 }, true],
['the same id as a string', { id: '1' }, true],
diff --git a/frontend/src/scenes/feature-flags/featureFlagAiContext.ts b/frontend/src/scenes/feature-flags/featureFlagAiContext.ts
index 39fae05480ae..43405ee21b68 100644
--- a/frontend/src/scenes/feature-flags/featureFlagAiContext.ts
+++ b/frontend/src/scenes/feature-flags/featureFlagAiContext.ts
@@ -64,6 +64,55 @@ function targetingValue(featureFlag: FeatureFlagType): string {
})
}
+/** Skill the "Review cleanup with AI" action asks PostHog AI to load; bundled into the agent sandbox image. */
+export const FEATURE_FLAG_CLEANUP_SKILL = 'cleaning-up-stale-feature-flags'
+
+export const FEATURE_FLAG_CLEANUP_ASSESSMENT_PROMPT = 'Assess this feature flag for cleanup.'
+const FEATURE_FLAG_CLEANUP_TARGET_TYPE = 'feature_flag_cleanup_target'
+
+const FEATURE_FLAG_CLEANUP_SKILL_CONTEXT_ITEM: AttachedContextItem = {
+ type: 'skill',
+ key: FEATURE_FLAG_CLEANUP_SKILL,
+ label: 'Cleaning up stale feature flags skill',
+}
+
+// Our own static, build-time text only. Never interpolate the flag's key, name, or description into
+// this item, or a project-authored string would ride inside the trusted block the agent is told to
+// follow. The saved identity a reader needs to act on travels separately, as the untrusted
+// `feature_flag_cleanup_target` item below.
+const FEATURE_FLAG_CLEANUP_INSTRUCTIONS_CONTEXT_ITEM: AttachedContextItem = {
+ type: 'instructions',
+ hidden: true,
+ value:
+ `Load the ${FEATURE_FLAG_CLEANUP_SKILL} skill before assessing. The ${FEATURE_FLAG_CLEANUP_TARGET_TYPE} item ` +
+ 'names the flag by project, id, and key. Re-fetch its current definition with the feature-flag tools ' +
+ 'rather than trusting values elsewhere in this conversation, because it can have changed since the page ' +
+ 'that started this request was loaded. Check linked systems (dependent flags, experiments, holdouts, ' +
+ 'schedules) and recent activity before concluding. This request is assessment only: return the evidence ' +
+ 'you gathered, any blockers, and a recommended next step. Do not edit any files, open a pull request, or ' +
+ 'change this flag in PostHog - do not enable, disable, archive, unarchive, or delete it.',
+}
+
+function cleanupTargetValue(featureFlag: Pick<FeatureFlagType, 'id' | 'key'>, projectId: number | null): string {
+ return JSON.stringify({ project_id: projectId, id: featureFlag.id, key: featureFlag.key })
+}
+
+/** The instruction stays trusted text; the flag identity travels separately as untrusted data. */
+export function featureFlagCleanupAssessmentContextItems(
+ featureFlag: Pick<FeatureFlagType, 'id' | 'key'>,
+ projectId: number | null
+): AttachedContextItem[] {
+ return [
+ FEATURE_FLAG_CLEANUP_SKILL_CONTEXT_ITEM,
+ FEATURE_FLAG_CLEANUP_INSTRUCTIONS_CONTEXT_ITEM,
+ {
+ type: FEATURE_FLAG_CLEANUP_TARGET_TYPE,
+ hidden: true,
+ value: cleanupTargetValue(featureFlag, projectId),
+ },
+ ]
+}
+
// `create-feature-flag` is left out because it never targets the flag on screen.
// `delete-feature-flag` and the bulk tools can target it, and are still left out: there is nothing
// to refresh into after a delete, and the bulk tools pass a list of ids that this matcher does not
diff --git a/products/feature_flags/frontend/FeatureFlagStaleBanner.test.tsx b/products/feature_flags/frontend/FeatureFlagStaleBanner.test.tsx
index 7364592ea58e..f4b21b4b530e 100644
--- a/products/feature_flags/frontend/FeatureFlagStaleBanner.test.tsx
+++ b/products/feature_flags/frontend/FeatureFlagStaleBanner.test.tsx
@@ -7,14 +7,17 @@ import { BindLogic, Provider } from 'kea'
import { expectLogic } from 'kea-test-utils'
import posthog from 'posthog-js'
+import { FEATURE_FLAGS } from 'lib/constants'
+import { featureFlagLogic as enabledFeaturesLogic } from 'lib/logic/featureFlagLogic'
import { NEW_FLAG, featureFlagLogic } from 'scenes/feature-flags/featureFlagLogic'
import { FeatureFlagsTab } from 'scenes/feature-flags/featureFlagsLogic'
+import { sidePanelStateLogic } from '~/layout/navigation-3000/sidepanel/sidePanelStateLogic'
import { useMocks } from '~/mocks/jest'
import type { Mocks } from '~/mocks/utils'
import { groupsModel } from '~/models/groupsModel'
import { initKeaTests } from '~/test/init'
-import { FeatureFlagType } from '~/types'
+import { FeatureFlagType, SidePanelTab } from '~/types'
import { FeatureFlagStaleBanner } from './FeatureFlagStaleBanner'
@@ -22,6 +25,17 @@ jest.mock('posthog-js')
const FLAG_ID = 1
const ACTION_SELECTOR = '[data-attr="feature-flag-stale-banner-view-usage"]'
+const REVIEW_CLEANUP_SELECTOR = '[data-attr="feature-flag-stale-banner-review-cleanup"]'
+
+/** Both are required for the action to render: the internal release gate, and the new sandbox view. */
+function setCleanupActionAvailable(available: boolean): void {
+ enabledFeaturesLogic.actions.setFeatureFlags(
+ available ? [FEATURE_FLAGS.PHAI_SANDBOX_MODE, FEATURE_FLAGS.FEATURE_FLAG_CLEANUP_ASSESSMENT] : [],
+ available
+ ? { [FEATURE_FLAGS.PHAI_SANDBOX_MODE]: true, [FEATURE_FLAGS.FEATURE_FLAG_CLEANUP_ASSESSMENT]: true }
+ : {}
+ )
+}
const HEADING = 'This flag may no longer be needed'
const GUIDANCE = 'Review usage and code references before disabling or archiving this flag.'
@@ -104,6 +118,7 @@ describe('FeatureFlagStaleBanner', () => {
})
afterEach(() => {
+ setCleanupActionAvailable(false)
cleanup()
})
@@ -318,4 +333,58 @@ describe('FeatureFlagStaleBanner', () => {
expect(logic.values.activeTab).toBe(FeatureFlagsTab.USAGE)
expect(posthog.capture).toHaveBeenCalledWith('feature flag stale banner view usage clicked')
})
+
+ describe('Review cleanup with AI action', () => {
+ it('is hidden while the internal release flag is off', async () => {
+ enabledFeaturesLogic.actions.setFeatureFlags([FEATURE_FLAGS.PHAI_SANDBOX_MODE], {
+ [FEATURE_FLAGS.PHAI_SANDBOX_MODE]: true,
+ })
+ useMocks(endpointMocks())
+ const logic = mountAndRender()
+ await settle(logic)
+
+ expect(document.querySelector(REVIEW_CLEANUP_SELECTOR)).not.toBeInTheDocument()
+ })
+
+ it('is hidden on the legacy chat view even when the release flag is on', async () => {
+ enabledFeaturesLogic.actions.setFeatureFlags([FEATURE_FLAGS.FEATURE_FLAG_CLEANUP_ASSESSMENT], {
+ [FEATURE_FLAGS.FEATURE_FLAG_CLEANUP_ASSESSMENT]: true,
+ })
+ useMocks(endpointMocks())
+ const logic = mountAndRender()
+ await settle(logic)
+
+ expect(document.querySelector(REVIEW_CLEANUP_SELECTOR)).not.toBeInTheDocument()
+ })
+
+ it('opens PostHog AI on a fresh request, and disables itself so a repeat click cannot start a second one', async () => {
+ setCleanupActionAvailable(true)
+ useMocks(endpointMocks())
+ const logic = mountAndRender()
+ await settle(logic)
+
+ const button = document.querySelector<HTMLButtonElement>(REVIEW_CLEANUP_SELECTOR)
+ expect(button).toBeInTheDocument()
+ expect(button).toHaveAttribute('aria-disabled', 'false')
+
+ act(() => {
+ button?.click()
+ })
+
+ expect(sidePanelStateLogic.values.selectedTab).toBe(SidePanelTab.Max)
+ expect(sidePanelStateLogic.values.sidePanelOpen).toBe(true)
+ expect(posthog.capture).toHaveBeenCalledWith(
+ 'feature flag stale banner review cleanup with ai clicked',
+ expect.objectContaining({ flag_id: FLAG_ID })
+ )
+
+ const captureCallsAfterFirstClick = (posthog.capture as jest.Mock).mock.calls.length
+ act(() => {
+ document.querySelector<HTMLButtonElement>(REVIEW_CLEANUP_SELECTOR)?.click()
+ })
+
+ expect(document.querySelector(REVIEW_CLEANUP_SELECTOR)).toHaveAttribute('aria-disabled', 'true')
+ expect((posthog.capture as jest.Mock).mock.calls.length).toBe(captureCallsAfterFirstClick)
+ })
+ })
})
diff --git a/products/feature_flags/frontend/FeatureFlagStaleBanner.tsx b/products/feature_flags/frontend/FeatureFlagStaleBanner.tsx
index bd732637a6a2..762499d72837 100644
--- a/products/feature_flags/frontend/FeatureFlagStaleBanner.tsx
+++ b/products/feature_flags/frontend/FeatureFlagStaleBanner.tsx
@@ -1,11 +1,15 @@
import { useActions, useValues } from 'kea'
import posthog from 'posthog-js'
+import { IconSparkles } from '@posthog/icons'
+
import { LemonBanner } from 'lib/lemon-ui/LemonBanner'
+import { LemonButton } from 'lib/lemon-ui/LemonButton'
import { endWithPunctation } from 'lib/utils/strings'
import { featureFlagLogic } from 'scenes/feature-flags/featureFlagLogic'
import { FeatureFlagsTab } from 'scenes/feature-flags/featureFlagsLogic'
+import { featureFlagCleanupAssessmentLogic } from './featureFlagCleanupAssessmentLogic'
import { formatPercentage } from './FractionalRolloutWarning'
import type { FeatureFlagRolloutSummaryApi } from './generated/api.schemas'
@@ -51,29 +55,64 @@ function rolloutSentence(
return reasonStatesRollout ? null : `One release condition rolls out to all ${targets}.`
}
+/**
+ * The internally-gated escalation from "review usage" to "ask PostHog AI to assess this flag for
+ * cleanup". A separate component so its `featureFlagCleanupAssessmentLogic` mount (and the hooks that
+ * come with it) only happens once the parent banner has already decided to render - the banner itself
+ * returns null before any flag is confirmed stale, and hooks can't run conditionally in one component.
+ */
+function ReviewCleanupWithAiButton({
+ flagId,
+ flagKey,
+ currentProjectId,
+}: {
+ flagId: number
+ flagKey: string
+ currentProjectId: number | null
+}): JSX.Element | null {
+ const { isCleanupAvailable, assessmentStarted } = useValues(featureFlagCleanupAssessmentLogic({ id: flagId }))
+ const { startAssessment } = useActions(featureFlagCleanupAssessmentLogic({ id: flagId }))
+
+ if (!isCleanupAvailable) {
+ return null
+ }
+
+ return (
+ <LemonButton
+ type="secondary"
+ size="small"
+ icon={<IconSparkles />}
+ data-attr="feature-flag-stale-banner-review-cleanup"
+ disabledReason={assessmentStarted ? 'Assessment started. Continue in PostHog AI.' : undefined}
+ onClick={() => startAssessment(flagKey, currentProjectId)}
+ >
+ Review cleanup with AI
+ </LemonButton>
+ )
+}
+
export function FeatureFlagStaleBanner(): JSX.Element | null {
- const { showStaleFlagBanner, flagStatus, hasExperiment, dependentFlags, aggregationTargetName } =
- useValues(featureFlagLogic)
+ const {
+ showStaleFlagBanner,
+ flagStatus,
+ hasExperiment,
+ dependentFlags,
+ aggregationTargetName,
+ featureFlag,
+ currentProjectId,
+ } = useValues(featureFlagLogic)
const { setSelectedTab } = useActions(featureFlagLogic)
- if (!showStaleFlagBanner || !flagStatus) {
+ // `showStaleFlagBanner` already requires a saved flag (see featureFlagLogic), so `featureFlag.id`
+ // is never null here - the extra check narrows the type for `ReviewCleanupWithAiButton` below.
+ if (!showStaleFlagBanner || !flagStatus || !featureFlag.id) {
return null
}
const rollout = rolloutSentence(flagStatus.rollout, flagStatus.reason_states_rollout, aggregationTargetName)
return (
- <LemonBanner
- type="warning"
- action={{
- children: 'View usage',
- 'data-attr': 'feature-flag-stale-banner-view-usage',
- onClick: () => {
- posthog.capture('feature flag stale banner view usage clicked')
- setSelectedTab(FeatureFlagsTab.USAGE)
- },
- }}
- >
+ <LemonBanner type="warning">
<div className="flex flex-col gap-1">
<strong>This flag may no longer be needed</strong>
<span>
@@ -83,6 +122,24 @@ export function FeatureFlagStaleBanner(): JSX.Element | null {
{hasExperiment && <span>This flag is linked to an experiment.</span>}
{dependentFlags.length > 0 && <span>Other flags depend on this flag.</span>}
<span>Review usage and code references before disabling or archiving this flag.</span>
+ <div className="flex flex-wrap gap-2 mt-1">
+ <LemonButton
+ type="secondary"
+ size="small"
+ data-attr="feature-flag-stale-banner-view-usage"
+ onClick={() => {
+ posthog.capture('feature flag stale banner view usage clicked')
+ setSelectedTab(FeatureFlagsTab.USAGE)
+ }}
+ >
+ View usage
+ </LemonButton>
+ <ReviewCleanupWithAiButton
+ flagId={featureFlag.id}
+ flagKey={featureFlag.key}
+ currentProjectId={currentProjectId}
+ />
+ </div>
</div>
</LemonBanner>
)
diff --git a/products/feature_flags/frontend/featureFlagCleanupAssessmentLogic.test.ts b/products/feature_flags/frontend/featureFlagCleanupAssessmentLogic.test.ts
new file mode 100644
index 000000000000..fedf1b92de6b
--- /dev/null
+++ b/products/feature_flags/frontend/featureFlagCleanupAssessmentLogic.test.ts
@@ -0,0 +1,241 @@
+import { MOCK_DEFAULT_ORGANIZATION } from 'lib/api.mock'
+
+import { expectLogic } from 'kea-test-utils'
+import posthog from 'posthog-js'
+
+import { FEATURE_FLAGS } from 'lib/constants'
+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
+import { FEATURE_FLAG_CLEANUP_SKILL } from 'scenes/feature-flags/featureFlagAiContext'
+import { MAX_SIDE_PANEL_ID } from 'scenes/max/components/PhaiSidePanelChat'
+import { maxMocks } from 'scenes/max/testUtils'
+import { organizationLogic } from 'scenes/organizationLogic'
+import { preflightLogic } from 'scenes/PreflightCheck/preflightLogic'
+
+import { sidePanelStateLogic } from '~/layout/navigation-3000/sidepanel/sidePanelStateLogic'
+import { useMocks } from '~/mocks/jest'
+import { initKeaTests } from '~/test/init'
+import {
+ AccessControlLevel,
+ FeatureFlagBucketingIdentifier,
+ FeatureFlagEvaluationRuntime,
+ FeatureFlagType,
+ SidePanelTab,
+} from '~/types'
+
+import { attachedContextLogic, composerSeedLogic, runnerPanelLogic } from 'products/posthog_ai/frontend/api/logics'
+
+import { featureFlagCleanupAssessmentLogic } from './featureFlagCleanupAssessmentLogic'
+
+jest.mock('posthog-js')
+
+const FLAG_ID = 1
+const PROJECT_ID = 42
+
+const FEATURE_FLAG: FeatureFlagType & { id: number } = {
+ id: FLAG_ID,
+ key: 'stale-flag',
+ name: '',
+ created_at: '2021-01-01',
+ updated_at: '2021-01-01',
+ created_by: null,
+ is_remote_configuration: false,
+ filters: { groups: [], payloads: {}, multivariate: null },
+ deleted: false,
+ archived: false,
+ active: true,
+ experiment_set: null,
+ experiment_set_metadata: null,
+ features: null,
+ surveys: null,
+ can_edit: true,
+ tags: [],
+ ensure_experience_continuity: null,
+ user_access_level: AccessControlLevel.Admin,
+ status: 'ACTIVE',
+ has_encrypted_payloads: false,
+ version: 0,
+ last_modified_by: null,
+ evaluation_runtime: FeatureFlagEvaluationRuntime.ALL,
+ evaluation_contexts: [],
+ bucketing_identifier: FeatureFlagBucketingIdentifier.DISTINCT_ID,
+}
+
+function setCleanupAvailable(available: boolean): void {
+ featureFlagLogic.actions.setFeatureFlags(
+ available ? [FEATURE_FLAGS.PHAI_SANDBOX_MODE, FEATURE_FLAGS.FEATURE_FLAG_CLEANUP_ASSESSMENT] : [],
+ available
+ ? { [FEATURE_FLAGS.PHAI_SANDBOX_MODE]: true, [FEATURE_FLAGS.FEATURE_FLAG_CLEANUP_ASSESSMENT]: true }
+ : {}
+ )
+}
+
+describe('featureFlagCleanupAssessmentLogic', () => {
+ let logic: ReturnType<typeof featureFlagCleanupAssessmentLogic.build>
+
+ beforeEach(() => {
+ useMocks(maxMocks)
+ initKeaTests()
+ sidePanelStateLogic.mount()
+ sidePanelStateLogic.actions.setSidePanelAvailable(true)
+ attachedContextLogic.mount()
+ // The side panel holds the seed store mounted while the runner chunk loads, so a pending seed can
+ // outlive this logic. Mounting it here models that.
+ composerSeedLogic({ panelId: MAX_SIDE_PANEL_ID }).mount()
+ logic = featureFlagCleanupAssessmentLogic({ id: FLAG_ID })
+ logic.mount()
+ ;(posthog.capture as jest.Mock).mockClear()
+ })
+
+ afterEach(() => {
+ setCleanupAvailable(false)
+ logic?.unmount()
+ attachedContextLogic.unmount()
+ composerSeedLogic({ panelId: MAX_SIDE_PANEL_ID }).unmount()
+ })
+
+ it('is unavailable on the legacy view even when the release flag is on', async () => {
+ featureFlagLogic.actions.setFeatureFlags([FEATURE_FLAGS.FEATURE_FLAG_CLEANUP_ASSESSMENT], {
+ [FEATURE_FLAGS.FEATURE_FLAG_CLEANUP_ASSESSMENT]: true,
+ })
+
+ await expectLogic(logic).toMatchValues({ isCleanupAvailable: false })
+ })
+
+ it('is unavailable when the release flag is off, even on the new sandbox view', async () => {
+ featureFlagLogic.actions.setFeatureFlags([FEATURE_FLAGS.PHAI_SANDBOX_MODE], {
+ [FEATURE_FLAGS.PHAI_SANDBOX_MODE]: true,
+ })
+
+ await expectLogic(logic).toMatchValues({ isCleanupAvailable: false })
+ })
+
+ it('is unavailable on a self-hosted instance with no Anthropic key configured', async () => {
+ preflightLogic.actions.loadPreflightSuccess({
+ cloud: false,
+ is_debug: false,
+ anthropic_available: false,
+ } as any)
+ setCleanupAvailable(true)
+
+ await expectLogic(logic).toMatchValues({ isCleanupAvailable: false })
+ })
+
+ it('does nothing when started while unavailable', async () => {
+ await expectLogic(logic, () => {
+ logic.actions.startAssessment(FEATURE_FLAG.key, PROJECT_ID)
+ }).toFinishAllListeners()
+
+ expect(sidePanelStateLogic.values.sidePanelOpen).toBe(false)
+ expect(composerSeedLogic({ panelId: MAX_SIDE_PANEL_ID }).values.seed).toBeNull()
+ })
+
+ describe('when available', () => {
+ beforeEach(() => {
+ setCleanupAvailable(true)
+ })
+
+ it.each([
+ { approved: true, autoSubmit: true },
+ { approved: false, autoSubmit: false },
+ ])(
+ 'sets autoSubmit to $autoSubmit when AI data processing approval is $approved',
+ async ({ approved, autoSubmit }) => {
+ organizationLogic.actions.loadCurrentOrganizationSuccess({
+ ...MOCK_DEFAULT_ORGANIZATION,
+ is_ai_data_processing_approved: approved,
+ })
+ await expectLogic(logic, () => {
+ logic.actions.startAssessment(FEATURE_FLAG.key, PROJECT_ID)
+ }).toFinishAllListeners()
+
+ expect(sidePanelStateLogic.values.sidePanelOpen).toBe(true)
+ expect(sidePanelStateLogic.values.selectedTab).toBe(SidePanelTab.Max)
+ expect(composerSeedLogic({ panelId: MAX_SIDE_PANEL_ID }).values.seed).toMatchObject({
+ prompt: 'Assess this feature flag for cleanup.',
+ autoSubmit,
+ })
+ }
+ )
+
+ it('carries the cleanup skill and saved flag identity only in the request seed', async () => {
+ await expectLogic(logic, () => {
+ logic.actions.startAssessment(FEATURE_FLAG.key, PROJECT_ID)
+ }).toFinishAllListeners()
+
+ const items = composerSeedLogic({ panelId: MAX_SIDE_PANEL_ID }).values.seed?.contextItems ?? []
+ expect(items).toContainEqual(expect.objectContaining({ type: 'skill', key: FEATURE_FLAG_CLEANUP_SKILL }))
+ const target = items.find((item) => item.type === 'feature_flag_cleanup_target')
+ expect(JSON.parse(target?.value ?? '')).toEqual({ project_id: PROJECT_ID, id: FLAG_ID, key: 'stale-flag' })
+ expect(items).toContainEqual(expect.objectContaining({ type: 'instructions' }))
+ expect(attachedContextLogic.values.contextItems).toHaveLength(0)
+ })
+
+ it('does not resume whatever the panel was already showing', async () => {
+ runnerPanelLogic({ panelId: MAX_SIDE_PANEL_ID }).actions.setActiveCreation({ streamKey: 'unrelated-run' })
+ runnerPanelLogic({ panelId: MAX_SIDE_PANEL_ID }).actions.setHistoryExpanded(true)
+
+ await expectLogic(logic, () => {
+ logic.actions.startAssessment(FEATURE_FLAG.key, PROJECT_ID)
+ }).toFinishAllListeners()
+
+ expect(runnerPanelLogic({ panelId: MAX_SIDE_PANEL_ID }).values.activeCreation).toBeNull()
+ expect(runnerPanelLogic({ panelId: MAX_SIDE_PANEL_ID }).values.historyExpanded).toBe(false)
+ })
+
+ it('ignores a repeat click instead of starting a second assessment', async () => {
+ await expectLogic(logic, () => {
+ logic.actions.startAssessment(FEATURE_FLAG.key, PROJECT_ID)
+ logic.actions.startAssessment(FEATURE_FLAG.key, PROJECT_ID)
+ }).toFinishAllListeners()
+
+ // Filtered rather than a raw call count: opening the side panel fires its own "sidebar
+ // opened" capture, so the total call count is not specific to this action.
+ const clicks = (posthog.capture as jest.Mock).mock.calls.filter(
+ ([event]) => event === 'feature flag stale banner review cleanup with ai clicked'
+ )
+ expect(clicks).toHaveLength(1)
+ })
+
+ it('cancels its pending seed on unmount so it cannot reach a later conversation', async () => {
+ await expectLogic(logic, () => {
+ logic.actions.startAssessment(FEATURE_FLAG.key, PROJECT_ID)
+ }).toFinishAllListeners()
+ expect(composerSeedLogic({ panelId: MAX_SIDE_PANEL_ID }).values.seed).not.toBeNull()
+
+ logic.unmount()
+
+ expect(composerSeedLogic({ panelId: MAX_SIDE_PANEL_ID }).values.seed).toBeNull()
+ })
+
+ it.each([
+ { leave: 'close', action: () => sidePanelStateLogic.actions.closeSidePanel() },
+ { leave: 'switch tabs', action: () => sidePanelStateLogic.actions.openSidePanel(SidePanelTab.Support) },
+ ])('cancels a pending seed and allows another assessment after $leave', async ({ action }) => {
+ await expectLogic(logic, () => {
+ logic.actions.startAssessment(FEATURE_FLAG.key, PROJECT_ID)
+ }).toFinishAllListeners()
+
+ action()
+
+ expect(composerSeedLogic({ panelId: MAX_SIDE_PANEL_ID }).values.seed).toBeNull()
+ expect(logic.values.assessmentStarted).toBe(false)
+
+ await expectLogic(logic, () => {
+ logic.actions.startAssessment(FEATURE_FLAG.key, PROJECT_ID)
+ }).toFinishAllListeners()
+ expect(composerSeedLogic({ panelId: MAX_SIDE_PANEL_ID }).values.seed).not.toBeNull()
+ })
+
+ it("leaves another producer's newer seed in place on unmount", async () => {
+ await expectLogic(logic, () => {
+ logic.actions.startAssessment(FEATURE_FLAG.key, PROJECT_ID)
+ }).toFinishAllListeners()
+ const otherSeed = { prompt: 'Something else', autoSubmit: false }
+ composerSeedLogic({ panelId: MAX_SIDE_PANEL_ID }).actions.setSeed(otherSeed)
+
+ logic.unmount()
+
+ expect(composerSeedLogic({ panelId: MAX_SIDE_PANEL_ID }).values.seed).toEqual(otherSeed)
+ })
+ })
+})
diff --git a/products/feature_flags/frontend/featureFlagCleanupAssessmentLogic.ts b/products/feature_flags/frontend/featureFlagCleanupAssessmentLogic.ts
new file mode 100644
index 000000000000..5284d0001c6a
--- /dev/null
+++ b/products/feature_flags/frontend/featureFlagCleanupAssessmentLogic.ts
@@ -0,0 +1,205 @@
+import {
+ MakeLogicType,
+ actions,
+ beforeUnmount,
+ connect,
+ kea,
+ key,
+ listeners,
+ path,
+ props,
+ reducers,
+ selectors,
+} from 'kea'
+import posthog from 'posthog-js'
+
+import { FEATURE_FLAGS } from 'lib/constants'
+import { FeatureFlagsSet, featureFlagLogic as enabledFeaturesLogic } from 'lib/logic/featureFlagLogic'
+import {
+ FEATURE_FLAG_CLEANUP_ASSESSMENT_PROMPT,
+ featureFlagCleanupAssessmentContextItems,
+} from 'scenes/feature-flags/featureFlagAiContext'
+import { MAX_SIDE_PANEL_ID } from 'scenes/max/components/PhaiSidePanelChat'
+import { PhaiViewMode, maxGlobalLogic } from 'scenes/max/maxGlobalLogic'
+
+import { sidePanelStateLogic } from '~/layout/navigation-3000/sidepanel/sidePanelStateLogic'
+import { SidePanelTab } from '~/types'
+
+import { composerSeedLogic, runnerPanelLogic, type ComposerSeed } from 'products/posthog_ai/frontend/api/logics'
+
+export interface FeatureFlagCleanupAssessmentLogicProps {
+ id: number
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface featureFlagCleanupAssessmentLogicValues {
+ seed: ComposerSeed | null // composerSeedLogic
+ featureFlags: FeatureFlagsSet // enabledFeaturesLogic
+ dataProcessingAccepted: boolean // maxGlobalLogic
+ effectivePhaiView: PhaiViewMode // maxGlobalLogic
+ isMaxAvailable: boolean // maxGlobalLogic
+ assessmentStarted: boolean
+ isCleanupAvailable: boolean
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface featureFlagCleanupAssessmentLogicActions {
+ consumeSeed: () => {
+ value: true
+ } // composerSeedLogic
+ setSeed: (seed: ComposerSeed) => {
+ seed: ComposerSeed
+ } // composerSeedLogic
+ clearActiveCreation: () => {
+ value: true
+ } // runnerPanelLogic
+ setHistoryExpanded: (expanded: boolean) => {
+ expanded: boolean
+ } // runnerPanelLogic
+ openSidePanel: (
+ tab: SidePanelTab,
+ options?: string | undefined
+ ) => {
+ options: string | undefined
+ tab: SidePanelTab
+ } // sidePanelStateLogic
+ markAssessmentStarted: () => {
+ value: true
+ }
+ resetAssessmentStarted: () => {
+ value: true
+ }
+ startAssessment: (
+ flagKey: string,
+ projectId: number | null
+ ) => {
+ flagKey: string
+ projectId: number | null
+ }
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface featureFlagCleanupAssessmentLogicMeta {
+ key: number
+ __keaTypeGenInternalSelectorTypes: {
+ isCleanupAvailable: (
+ isMaxAvailable: boolean,
+ effectivePhaiView: PhaiViewMode,
+ featureFlags: FeatureFlagsSet
+ ) => boolean
+ }
+}
+
+export type featureFlagCleanupAssessmentLogicType = MakeLogicType<
+ featureFlagCleanupAssessmentLogicValues,
+ featureFlagCleanupAssessmentLogicActions,
+ FeatureFlagCleanupAssessmentLogicProps,
+ featureFlagCleanupAssessmentLogicMeta
+>
+
+export const featureFlagCleanupAssessmentLogic = kea<featureFlagCleanupAssessmentLogicType>([
+ path((key) => ['products', 'feature_flags', 'frontend', 'featureFlagCleanupAssessmentLogic', key]),
+ props({} as FeatureFlagCleanupAssessmentLogicProps),
+ key((props) => props.id),
+
+ connect(() => ({
+ values: [
+ maxGlobalLogic,
+ ['isMaxAvailable', 'effectivePhaiView', 'dataProcessingAccepted'],
+ enabledFeaturesLogic,
+ ['featureFlags'],
+ composerSeedLogic({ panelId: MAX_SIDE_PANEL_ID }),
+ ['seed'],
+ ],
+ actions: [
+ composerSeedLogic({ panelId: MAX_SIDE_PANEL_ID }),
+ ['setSeed', 'consumeSeed'],
+ runnerPanelLogic({ panelId: MAX_SIDE_PANEL_ID }),
+ ['clearActiveCreation', 'setHistoryExpanded'],
+ sidePanelStateLogic,
+ ['openSidePanel'],
+ ],
+ })),
+
+ actions({
+ startAssessment: (flagKey: string, projectId: number | null) => ({ flagKey, projectId }),
+ markAssessmentStarted: true,
+ resetAssessmentStarted: true,
+ }),
+
+ reducers({
+ assessmentStarted: [
+ false,
+ {
+ markAssessmentStarted: () => true,
+ resetAssessmentStarted: () => false,
+ },
+ ],
+ }),
+
+ selectors({
+ // Scoped to the new sandbox view: legacy Max chat does not run in the agent sandbox, so the
+ // cleanup skill bundled into that image is not present there.
+ isCleanupAvailable: [
+ (s) => [s.isMaxAvailable, s.effectivePhaiView, s.featureFlags],
+ (isMaxAvailable: boolean, effectivePhaiView: PhaiViewMode, featureFlags: FeatureFlagsSet): boolean =>
+ isMaxAvailable &&
+ effectivePhaiView === 'new' &&
+ !!featureFlags[FEATURE_FLAGS.FEATURE_FLAG_CLEANUP_ASSESSMENT],
+ ],
+ }),
+
+ listeners(({ actions, values, cache, props }) => {
+ const cancelAssessment = (): void => {
+ if (!values.assessmentStarted) {
+ return
+ }
+ if (values.seed && values.seed === cache.pendingSeed) {
+ actions.consumeSeed()
+ }
+ actions.resetAssessmentStarted()
+ }
+
+ return {
+ startAssessment: ({ flagKey, projectId }) => {
+ if (values.assessmentStarted || !values.isCleanupAvailable) {
+ return
+ }
+ actions.markAssessmentStarted()
+ const contextItems = featureFlagCleanupAssessmentContextItems({ id: props.id, key: flagKey }, projectId)
+ // Do not resume whatever the panel was already showing - a run in progress, history, or an
+ // unrelated draft - so this action never appends to an unrelated task.
+ actions.clearActiveCreation()
+ actions.setHistoryExpanded(false)
+ cache.pendingSeed = {
+ prompt: FEATURE_FLAG_CLEANUP_ASSESSMENT_PROMPT,
+ autoSubmit: values.dataProcessingAccepted,
+ contextItems,
+ }
+ actions.setSeed(cache.pendingSeed)
+ actions.openSidePanel(SidePanelTab.Max)
+ posthog.capture('feature flag stale banner review cleanup with ai clicked', {
+ flag_id: props.id,
+ flag_key: flagKey,
+ })
+ },
+ [sidePanelStateLogic.actionTypes.setSidePanelOpen]: ({ open }) => {
+ if (!open) {
+ cancelAssessment()
+ }
+ },
+ [sidePanelStateLogic.actionTypes.openSidePanel]: ({ tab }) => {
+ if (tab !== SidePanelTab.Max) {
+ cancelAssessment()
+ }
+ },
+ }
+ }),
+
+ beforeUnmount(({ actions, values, cache }) => {
+ // The runner can mount after this logic unmounts because its chunk loads lazily.
+ if (values.seed && values.seed === cache.pendingSeed) {
+ actions.consumeSeed()
+ }
+ }),
+])
diff --git a/products/posthog_ai/frontend/logics/composerSeedLogic.ts b/products/posthog_ai/frontend/logics/composerSeedLogic.ts
index a2c02f288834..3b31143717fb 100644
--- a/products/posthog_ai/frontend/logics/composerSeedLogic.ts
+++ b/products/posthog_ai/frontend/logics/composerSeedLogic.ts
@@ -1,11 +1,11 @@
import { MakeLogicType, actions, kea, key, path, props, reducers } from 'kea'
-// 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.
+import type { AttachedContextItem } from '../types/contextTypes'
+
export interface ComposerSeed {
prompt: string
autoSubmit: boolean
+ contextItems?: AttachedContextItem[]
}
// `panelId` keys the seed to a specific embedded composer (e.g. Max's side panel runner), matching the
diff --git a/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.test.ts b/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.test.ts
index d7771ee9ecb6..9764a0d4f752 100644
--- a/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.test.ts
+++ b/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.test.ts
@@ -344,7 +344,10 @@ describe('taskTrackerSceneLogic', () => {
})
logic.mount()
router.actions.push('/tasks/new')
- logic.actions.setNewTaskData({ description: 'Explain the example chart' })
+ logic.actions.setNewTaskData({
+ description: 'Explain the example chart',
+ seedContextItems: [{ type: 'skill', key: 'example-skill' }],
+ })
logic.actions.submitNewTask()
const streamKey = logic.values.activeCreation!.streamKey
expect(runStreamLogic({ streamKey }).values.streamPhase).toBe('provisioning')
@@ -369,6 +372,7 @@ describe('taskTrackerSceneLogic', () => {
expect(logic.values.newTaskData.description).toBe(
'Explain the example chart\n\nInclude a weekly comparison\n\nAlso include a chart'
)
+ expect(logic.values.newTaskData.seedContextItems).toEqual([{ type: 'skill', key: 'example-skill' }])
expect(logic.values.isSubmittingTask).toBe(false)
expect(router.values.location.pathname).toContain('/tasks/new')
expect(toolEvents.values.applyBackTargetClaims[streamKey]).toBeUndefined()
@@ -559,24 +563,44 @@ describe('taskTrackerSceneLogic', () => {
// The seeded first message wraps the on-screen context, and the wrapped non-text refs must be marked
// sent under the created task's id — otherwise the run's first follow-up (sent via
// `runInteractionLogic`, which prunes against the task-scoped store) re-wraps the same refs.
- it('marks seeded context sent for the created task so the first follow-up will not re-wrap it', async () => {
- logic.mount()
- attachedContextLogic().actions.registerContext('scene', [
- { type: 'insight', key: 'sig', label: 'Signups' },
- { type: 'text', value: 'always resend me' },
- ])
+ it.each(['scene', 'seed', 'both'])(
+ 'marks %s context sent for the created task without adding it to later sends',
+ async (source) => {
+ logic.mount()
+ const contextItems = [
+ { type: 'insight', key: 'sig', label: 'Signups' },
+ { type: 'text', value: 'always resend me' },
+ ]
+ if (source !== 'seed') {
+ attachedContextLogic().actions.registerContext(
+ 'scene',
+ source === 'both' ? [{ type: 'insight', key: 'scene-sig', label: 'Scene signups' }] : contextItems
+ )
+ }
+ if (source === 'scene') {
+ logic.actions.setNewTaskData({ description: 'why the drop?' })
+ logic.actions.submitNewTask()
+ } else {
+ composerSeedLogic().actions.setSeed({ prompt: 'why the drop?', autoSubmit: true, contextItems })
+ }
- logic.actions.setNewTaskData({ description: 'why the drop?' })
- logic.actions.submitNewTask()
- await expectLogic(logic).toFinishAllListeners()
+ await expectLogic(logic).toFinishAllListeners()
- // The message sent to the agent is wrapped; the task description stays raw.
- expect(runBody?.pending_user_message).toContain('<posthog_untrusted_context>')
- expect(runBody?.pending_user_message).toContain('- insight sig ("Signups")')
- expect(createBody?.description).toBe('why the drop?')
- // Only the entity ref is marked sent (text items always resend), under the created task's id.
- expect(attachedContextLogic().values.sentContextKeysByTask).toEqual({ 'new-task': ['insight:sig'] })
- })
+ expect(runBody?.pending_user_message).toContain('<posthog_untrusted_context>')
+ expect(runBody?.pending_user_message).toContain('- insight sig ("Signups")')
+ expect(runBody?.pending_user_message).toContain(
+ source === 'both' ? '- insight scene-sig ("Scene signups")' : '- insight sig ("Signups")'
+ )
+ expect(createBody?.description).toBe('why the drop?')
+ expect(attachedContextLogic().values.sentContextKeysByTask).toEqual({
+ 'new-task': source === 'both' ? ['insight:scene-sig', 'insight:sig'] : ['insight:sig'],
+ })
+ expect(logic.values.newTaskData.seedContextItems).toBeUndefined()
+ expect(attachedContextLogic().values.contextItems).toHaveLength(
+ source === 'seed' ? 0 : source === 'both' ? 1 : 2
+ )
+ }
+ )
// The tasks backend has no server-side consent check (unlike the conversations coordinator), so a
// send must be blocked client-side before it ever reaches `api.tasks.create` — otherwise a sandbox
@@ -891,16 +915,32 @@ describe('taskTrackerSceneLogic', () => {
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 })
+ const contextItems = [{ type: 'skill', key: 'example-skill' }]
+ seedLogic.actions.setSeed({ prompt: 'analyze churn', autoSubmit: false, contextItems })
logic.mount()
await expectLogic(logic).toFinishAllListeners()
expect(logic.values.newTaskData.description).toBe('analyze churn')
+ expect(logic.values.newTaskData.seedContextItems).toEqual(contextItems)
expect(seedLogic.values.seed).toBeNull()
// No submit: submitting opens an optimistic activeCreation, prefill-only leaves it null.
expect(logic.values.activeCreation).toBeNull()
+ seedLogic.actions.setSeed({ prompt: 'unrelated request', autoSubmit: false })
+ expect(logic.values.newTaskData.seedContextItems).toBeUndefined()
+
+ seedLogic.actions.setSeed({ prompt: 'analyze churn', autoSubmit: false, contextItems })
+ logic.actions.setNewTaskData({ description: 'different request' })
+ expect(logic.values.newTaskData.seedContextItems).toBeUndefined()
+
+ seedLogic.actions.setSeed({ prompt: 'analyze churn', autoSubmit: false, contextItems })
+ logic.actions.setNewTaskData({ description: 'analyze churn' })
+ expect(logic.values.newTaskData.seedContextItems).toEqual(contextItems)
+ logic.unmount()
+ logic.mount()
+ expect(logic.values.newTaskData.seedContextItems).toBeUndefined()
+
seedLogic.unmount()
})
diff --git a/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.ts b/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.ts
index 6922352275e9..fee648e75246 100644
--- a/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.ts
+++ b/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.ts
@@ -67,6 +67,7 @@ export type { ActiveCreation } from '../../logics/runnerPanelLogic'
export interface TaskCreateForm {
description: string
+ seedContextItems?: AttachedContextItem[]
repositoryConfig: RepositoryConfig
/** null = no explicit pick; the run launches with the server-resolved default (user preference
* over project default, else the built-in composer default). An explicit pick applies to this
@@ -467,7 +468,16 @@ export const taskTrackerSceneLogic = kea<taskTrackerSceneLogicType>([
newTaskData: [
EMPTY_TASK_FORM as TaskCreateForm,
{
- setNewTaskData: (state, { data }) => ({ ...state, ...data }),
+ setNewTaskData: (state, { data }) => ({
+ ...state,
+ ...data,
+ seedContextItems:
+ 'seedContextItems' in data
+ ? data.seedContextItems
+ : data.description !== undefined && data.description !== state.description
+ ? undefined
+ : state.seedContextItems,
+ }),
resetNewTaskData: () => EMPTY_TASK_FORM,
},
],
@@ -662,7 +672,7 @@ export const taskTrackerSceneLogic = kea<taskTrackerSceneLogicType>([
// Fill the composer with the suggestion; submit straight away unless it needs the user to finish
// typing (the component focuses the textarea in that case).
applySuggestion: ({ item }) => {
- actions.setNewTaskData({ description: item.content })
+ actions.setNewTaskData({ description: item.content, seedContextItems: undefined })
if (!item.requiresUserInput) {
actions.submitNewTask()
}
@@ -704,7 +714,10 @@ export const taskTrackerSceneLogic = kea<taskTrackerSceneLogicType>([
// pane renders, and survives across the React swap into the detail page (which adopts the same
// instance by binding this `streamKey`). Released by `clearActiveCreation` (failure / leaving the run).
const streamKey = `draft-${uuid()}`
- const seededContext = props.contextItems ?? values.contextItems
+ const seededContext = [
+ ...(props.contextItems ?? values.contextItems),
+ ...(values.newTaskData.seedContextItems ?? []),
+ ]
actions.claimApplyBackTargets(streamKey)
const stream = runStreamLogic({ streamKey })
const interaction = runInteractionLogic({
@@ -944,6 +957,7 @@ export const taskTrackerSceneLogic = kea<taskTrackerSceneLogicType>([
if (unsent.length > 0) {
actions.setNewTaskData({
description: [values.newTaskData.description, ...unsent].join('\n\n'),
+ seedContextItems: values.newTaskData.seedContextItems,
})
}
actions.clearActiveCreation()
@@ -962,6 +976,7 @@ export const taskTrackerSceneLogic = kea<taskTrackerSceneLogicType>([
}
},
openExistingTask: ({ task }) => {
+ actions.setNewTaskData({ seedContextItems: undefined })
if (task.latest_run) {
// No optimistic stream seeding — the run surface bootstraps the thread from the API.
actions.setActiveCreation({ streamKey: task.latest_run.id, taskId: task.id, runId: task.latest_run.id })
@@ -1007,7 +1022,7 @@ export const taskTrackerSceneLogic = kea<taskTrackerSceneLogicType>([
}
// Consume-once: clear before applying so a re-entrant dispatch can't double-apply/submit.
actions.consumeSeed()
- actions.setNewTaskData({ description: seed.prompt })
+ actions.setNewTaskData({ description: seed.prompt, seedContextItems: seed.contextItems })
if (seed.autoSubmit) {
actions.submitNewTask()
}