:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(flags): refresh flags after AI updates (#100146)
James Gilld511a37a881b
diff --git a/frontend/src/scenes/feature-flags/FeatureFlag.tsx b/frontend/src/scenes/feature-flags/FeatureFlag.tsxindex 02be00e085ad..41ed69c06c38 100644--- a/frontend/src/scenes/feature-flags/FeatureFlag.tsx+++ b/frontend/src/scenes/feature-flags/FeatureFlag.tsx@@ -80,7 +80,7 @@ import {} from '~/types'import { FeatureFlagStaleBanner } from 'products/feature_flags/frontend/FeatureFlagStaleBanner'-import { useAttachedContext } from 'products/posthog_ai/frontend/api/logics'+import { AGENT_TOOL_APPLY_BACK_CONTEXT_ITEM, useAttachedContext } from 'products/posthog_ai/frontend/api/logics'import { featureFlagContextItems } from './featureFlagAiContext'import { openFeatureFlagArchiveDialog } from './featureFlagArchiveDialog'@@ -95,6 +95,7 @@ import FeatureFlagSchedule from './FeatureFlagSchedule'import { FeatureFlagsTab, featureFlagsLogic } from './featureFlagsLogic'import { FeatureFlagTestingTab } from './FeatureFlagTestingTab'import { FeatureFlagUsageMetrics } from './FeatureFlagUsageMetrics'+import { useFeatureFlagAgentRefresh } from './useFeatureFlagAgentRefresh'const RESOURCE_TYPE = 'feature_flag'@@ -150,6 +151,7 @@ export function FeatureFlag({ id }: FeatureFlagLogicProps): JSX.Element {saveDescriptionInline,saveTagsInline,updateFeatureFlagArchived,+ refreshFeatureFlagAfterAgentChange,} = useActions(featureFlagLogic)const { tags } = useValues(tagsModel)@@ -188,11 +190,20 @@ export function FeatureFlag({ id }: FeatureFlagLogicProps): JSX.Element {// and build an equivalent insight. The blast-radius endpoint only returns counts, so without// this the agent on a flag page has no visibility into the targeting.const featureFlagContext = useMemo(- () => (isNewFeatureFlag || !featureFlag?.key ? null : featureFlagContextItems(featureFlag)),+ () =>+ isNewFeatureFlag || !featureFlag?.key+ ? null+ : // Without the apply-back instruction the agent narrates a change instead of making it.+ [...featureFlagContextItems(featureFlag), AGENT_TOOL_APPLY_BACK_CONTEXT_ITEM],[isNewFeatureFlag, featureFlag])useAttachedContext(featureFlagContext)+ useFeatureFlagAgentRefresh({+ flagId: isNewFeatureFlag ? null : (featureFlag?.id ?? null),+ onAgentChange: refreshFeatureFlagAfterAgentChange,+ })+// Mounting the edit form is a multi-second render (Monaco editors + dnd-kit sortables). Mount it// immediately when the scene first renders already in form mode (deep-link/new flag), but when the// user clicks Edit on the readonly view, defer one frame so the click flips state and the loadingdiff --git a/frontend/src/scenes/feature-flags/featureFlagAiContext.test.ts b/frontend/src/scenes/feature-flags/featureFlagAiContext.test.tsindex 32a0be657bfe..2d2a3b60f64b 100644--- a/frontend/src/scenes/feature-flags/featureFlagAiContext.test.ts+++ b/frontend/src/scenes/feature-flags/featureFlagAiContext.test.ts@@ -10,14 +10,14 @@ import {import { wrapWithPosthogContext } from 'products/posthog_ai/frontend/utils/posthogContextBlock'-import { featureFlagContextItems } from './featureFlagAiContext'+import { 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// past what the backend accepts is exactly the regression these cases guard against.const MAX_BACKEND_TEXT_LENGTH = 4096-describe('featureFlagContextItems', () => {+describe('featureFlagAiContext', () => {const baseFeatureFlag: FeatureFlagType = {id: 1,key: 'test-flag',@@ -132,4 +132,19 @@ describe('featureFlagContextItems', () => {// was too large to send.expect(JSON.parse(value).release_condition_count).toBe(1)})++ test.each([+ ['the same id as a number', { id: 1 }, true],+ ['the same id as a string', { id: '1' }, true],+ // Every mutation tool declares these spellings as aliases for `id`, and the server resolves+ // them after this matcher has already seen the raw arguments the model wrote.+ ['the flagId alias', { flagId: 1 }, true],+ ['the feature_flag_id alias', { feature_flag_id: '1' }, true],+ ['an alias naming another flag', { flagId: 2 }, false],+ ['another flag', { id: 2 }, false],+ ['no id', { key: 'test-flag' }, false],+ ['unparseable args', null, false],+ ])('matches a mutation against the open flag with %s', (_name, innerInput, expected) => {+ expect(mutationTargetsFeatureFlag(innerInput, 1)).toBe(expected)+ })})diff --git a/frontend/src/scenes/feature-flags/featureFlagAiContext.ts b/frontend/src/scenes/feature-flags/featureFlagAiContext.tsindex 926660bae143..39fae05480ae 100644--- a/frontend/src/scenes/feature-flags/featureFlagAiContext.ts+++ b/frontend/src/scenes/feature-flags/featureFlagAiContext.ts@@ -63,3 +63,32 @@ function targetingValue(featureFlag: FeatureFlagType): string {conditions_omitted: 'Too large to attach. Read the saved flag to see the property filters.',})}++// `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+// read.+export const FEATURE_FLAG_MUTATION_TOOLS = [+ 'update-feature-flag',+ 'feature-flag-enable',+ 'feature-flag-disable',+ 'feature-flag-archive',+ 'feature-flag-unarchive',+]++// Every mutation tool accepts these spellings for the flag id (`param_overrides.id.aliases` in+// products/feature_flags/mcp/tools.yaml). The MCP server resolves them to `id`, but this matcher+// reads the raw arguments the model wrote. Match all five, or an aliased call never refreshes.+const FLAG_ID_KEYS = ['id', 'flagId', 'flag_id', 'feature_flag_id', 'featureFlagId']++// The bus is global, so an unrelated flag's call arrives here too. The id comes through as a string+// or a number because the tools cast it, and as null args when they could not be parsed.+export function mutationTargetsFeatureFlag(innerInput: Record<string, unknown> | null, flagId: number): boolean {+ return FLAG_ID_KEYS.some((key) => {+ const id = innerInput?.[key]+ if (typeof id !== 'string' && typeof id !== 'number') {+ return false+ }+ return String(id) === String(flagId)+ })+}diff --git a/frontend/src/scenes/feature-flags/featureFlagLogic.test.ts b/frontend/src/scenes/feature-flags/featureFlagLogic.test.tsindex fb5e9ca8c35a..ea5733b5bf1d 100644--- a/frontend/src/scenes/feature-flags/featureFlagLogic.test.ts+++ b/frontend/src/scenes/feature-flags/featureFlagLogic.test.ts@@ -78,12 +78,22 @@ function capturesOf(event: string): any[][] {return (posthog.capture as jest.Mock).mock.calls.filter(([name]) => name === event)}+// A promise the test resolves by hand, so it can hold a request open while something else lands.+function deferred(): { promise: Promise<void>; resolve: () => void } {+ let resolve: () => void = () => {}+ const promise = new Promise<void>((innerResolve) => {+ resolve = innerResolve+ })+ return { promise, resolve }+}+// jest.config.ts sets clearMocks: true, so these mock.fn() call histories reset before every test.jest.mock('lib/lemon-ui/LemonToast/LemonToast', () => ({lemonToast: {success: jest.fn(),error: jest.fn(),warning: jest.fn(),+ info: jest.fn(),},}))@@ -285,11 +295,169 @@ describe('featureFlagLogic', () => {expect(logic.values.featureFlag.active).toBe(true)expect(featureFlagsLogic.values.featureFlags.results[0].active).toBe(true)+ expect(lemonToast.info).not.toHaveBeenCalled()featureFlagsLogic.unmount()})})+ describe('refresh after a PostHog AI change', () => {+ const FLAG_URL = `/api/projects/${MOCK_DEFAULT_PROJECT.id}/feature_flags/${MOCK_FEATURE_FLAG.id}/`++ function serverFlagMock(flag: Record<string, any>): Parameters<typeof useMocks>[0] {+ return { get: { [FLAG_URL]: () => [200, { ...MOCK_FEATURE_FLAG, ...flag }] } }+ }++ // The agent reaches fields no manual mutation path folds, so folding only active/archived+ // would leave the reader on the old name and rollout with nothing saying so.+ it('shows the saved flag when the form is clean', async () => {+ useMocks(serverFlagMock({ name: 'renamed by the agent', active: false }))++ await expectLogic(logic, () => logic.actions.refreshFeatureFlagAfterAgentChange())+ .toDispatchActions(['refreshFeatureFlag', 'loadFeatureFlagStatus', 'refreshFeatureFlagSuccess'])+ .toFinishAllListeners()++ expect(logic.values.featureFlag.name).toBe('renamed by the agent')+ expect(logic.values.featureFlag.active).toBe(false)+ // Re-baselined, so leaving the page must not warn about changes the reader never made.+ expect(logic.values.isFormDirty).toBe(false)+ expect(lemonToast.info).not.toHaveBeenCalled()+ })++ it('keeps unsaved edits, folds the state fields, and offers a reload', async () => {+ logic.actions.setFeatureFlag({ ...logic.values.featureFlag, name: 'half-written local edit' })+ expect(logic.values.isFormDirty).toBe(true)++ useMocks(serverFlagMock({ name: 'renamed by the agent', active: false, version: 9 }))++ await expectLogic(logic, () => logic.actions.refreshFeatureFlagAfterAgentChange())+ .toDispatchActions(['refreshFeatureFlagSuccess'])+ .toFinishAllListeners()++ expect(logic.values.featureFlag.name).toBe('half-written local edit')+ expect(logic.values.featureFlag.active).toBe(false)+ expect(logic.values.isFormDirty).toBe(true)+ // The next save has to submit a version behind the stored row. A folded-in server+ // version disarms the stale-write check, and these edits then overwrite everything the+ // agent wrote, with no error. A save submits the baseline, so the server checks that one.+ expect(logic.values.featureFlag.version).toBe(0)+ expect(logic.values.originalFeatureFlag?.version).toBe(0)+ expect(lemonToast.info).toHaveBeenCalledTimes(1)++ const [, options] = jest.mocked(lemonToast.info).mock.calls[0]+ // Scoped to this flag. The default id hashes the message, which names no flag, so a+ // notice still open for another flag would swallow this one as a duplicate and keep a+ // button that reloads that other flag.+ expect(options?.toastId).toBe('feature-flag-agent-change-1')++ await expectLogic(logic, () => void options?.button?.action())+ .toDispatchActions(['loadFeatureFlag', 'loadFeatureFlagSuccess'])+ .toFinishAllListeners()++ expect(logic.values.featureFlag.name).toBe('renamed by the agent')+ expect(logic.values.isFormDirty).toBe(false)+ })++ // The Enabled switch writes to the same form field the refresh folds, so a rename must not+ // revert a toggle the reader has not saved. The case above edits a field the fold skips,+ // and asserts the opposite outcome, so it cannot carry this one.+ it('keeps an unsaved Enabled toggle instead of folding the server value over it', async () => {+ logic.actions.setFeatureFlag({ ...logic.values.featureFlag, active: false })+ expect(logic.values.isFormDirty).toBe(true)++ useMocks(serverFlagMock({ name: 'renamed by the agent', active: true }))++ await expectLogic(logic, () => logic.actions.refreshFeatureFlagAfterAgentChange())+ .toDispatchActions(['refreshFeatureFlagSuccess'])+ .toFinishAllListeners()++ expect(logic.values.featureFlag.active).toBe(false)+ // The toggle is the only edit, so folding it would also leave the form reading clean+ // while the notice says the edits were kept.+ expect(logic.values.isFormDirty).toBe(true)+ expect(lemonToast.info).toHaveBeenCalledTimes(1)+ })++ // The reaction fires per completed call, so a turn that changes this flag twice starts two+ // refreshes. Needs its own setup: both requests have to be in flight at once, with the test+ // choosing which one answers last.+ it('discards a refresh response that a newer refresh superseded', async () => {+ const firstResponse = deferred()+ let requestCount = 0++ useMocks({+ get: {+ [FLAG_URL]: async () => {+ requestCount += 1+ if (requestCount === 1) {+ await firstResponse.promise+ return [200, { ...MOCK_FEATURE_FLAG, name: 'first agent change' }]+ }+ return [200, { ...MOCK_FEATURE_FLAG, name: 'second agent change' }]+ },+ },+ })++ await expectLogic(logic, () => {+ logic.actions.refreshFeatureFlagAfterAgentChange()+ logic.actions.refreshFeatureFlagAfterAgentChange()+ }).toDispatchActions(['refreshFeatureFlagSuccess'])++ expect(logic.values.featureFlag.name).toBe('second agent change')++ firstResponse.resolve()+ await expectLogic(logic).toFinishAllListeners()++ // The older response must not put the page or its baseline back.+ expect(logic.values.featureFlag.name).toBe('second agent change')+ expect(logic.values.originalFeatureFlag?.name).toBe('second agent change')+ })++ // The case above holds a refresh against a second refresh, which `breakpoint()` covers on+ // its own. A mutation landing mid-request needs a separate guard, so it needs its own case.+ it.each([+ ['a toggle', (flag: FeatureFlagType) => logic.actions.updateFeatureFlagActiveSuccess(flag)],+ // The inline tag and description saves and the cross-project toggle re-baseline without+ // dispatching any loader success, so a guard keyed to those actions cannot see them.+ [+ 'an inline field save',+ (flag: FeatureFlagType) => {+ logic.actions.setFeatureFlag(flag)+ logic.actions.setOriginalFeatureFlag(flag)+ },+ ],+ ['a full reload', (flag: FeatureFlagType) => logic.actions.loadFeatureFlagSuccess(flag)],+ ])('discards a refresh response that %s superseded', async (_label, mutate) => {+ const response = deferred()+ // The loader samples the mutation count before it calls the API, so mutating before the+ // request is open would pass without exercising the guard.+ const requestStarted = deferred()++ useMocks({+ get: {+ [FLAG_URL]: async () => {+ requestStarted.resolve()+ await response.promise+ return [200, { ...MOCK_FEATURE_FLAG, name: 'agent change', active: true, version: 3 }]+ },+ },+ })++ logic.actions.refreshFeatureFlagAfterAgentChange()+ await requestStarted.promise++ mutate({ ...MOCK_FEATURE_FLAG, active: false, version: 7 } as FeatureFlagType)+ expect(logic.values.featureFlag.active).toBe(false)++ response.resolve()+ await expectLogic(logic).toDispatchActions(['refreshFeatureFlagSuccess']).toFinishAllListeners()++ expect(logic.values.featureFlag.active).toBe(false)+ expect(logic.values.featureFlag.name).toBe('test-name')+ expect(logic.values.featureFlag.version).toBe(7)+ })+ })+describe('saveFeatureFlag error handling', () => {it('shows the friendly permission toast on a save-time 403', async () => {useMocks({@@ -2543,6 +2711,7 @@ describe('featureFlagLogic', () => {() => logic.actions.updateFeatureFlagActiveSuccess({ ...MOCK_FEATURE_FLAG, active: false }),],['an edit is saved', () => logic.actions.saveFeatureFlagSuccess(MOCK_FEATURE_FLAG)],+ ['PostHog AI changes the flag', () => logic.actions.refreshFeatureFlagAfterAgentChange()],])('clears the stale banner when %s', async (_name, mutate) => {useMocks(statusMock('stale', 'Flag has not been called in 45 days'))await expectLogic(logic, () => logic.actions.loadFeatureFlagStatus()).toFinishAllListeners()diff --git a/frontend/src/scenes/feature-flags/featureFlagLogic.ts b/frontend/src/scenes/feature-flags/featureFlagLogic.tsindex 9941ef1c5120..8c7ecbd540cc 100644--- a/frontend/src/scenes/feature-flags/featureFlagLogic.ts+++ b/frontend/src/scenes/feature-flags/featureFlagLogic.ts@@ -3,6 +3,7 @@ import {MakeLogicType,actions,afterMount,+ beforeUnmount,connect,kea,key,@@ -20,6 +21,7 @@ import { loaders } from 'kea-loaders'import { beforeUnload, router, urlToAction } from 'kea-router'import { CombinedLocation } from 'kea-router/lib/utils'import { createElement } from 'react'+import { toast } from 'react-toastify'import api, { PaginatedResponse } from 'lib/api'import { isAccessDeniedError } from 'lib/api-error'@@ -819,6 +821,13 @@ function cleanFlag(flag: Partial<FeatureFlagType>): Partial<FeatureFlagType> {}}+// Key the agent-change notice to one flag. The default id hashes the message, and the message names+// no flag, so a notice still open for another flag would swallow this one as a duplicate and leave+// its button reloading that flag.+function agentChangeToastId(id: FeatureFlagLogicProps['id']): string {+ return `feature-flag-agent-change-${id}`+}+// Shape a freshly-loaded server flag into the `originalFeatureFlag` baseline the dirty check// compares against. Callers must pass server-authoritative state — never the in-progress// working copy — or an unsaved edit would be folded into the baseline and read as clean.@@ -983,6 +992,7 @@ export interface featureFlagLogicValues {ValidationErrorType>flagIntent: FlagIntent | null+ flagMutationCount: numberflagStatus: FeatureFlagStatusResponseApi | nullflagStatusLoading: booleanflagType: 'boolean' | 'multivariate' | 'remote_config'@@ -1356,7 +1366,12 @@ export interface featureFlagLogicActions {flagId: numberteamId: number}- refreshFeatureFlag: () => any+ refreshFeatureFlag: (_payload?: { afterAgentChange?: boolean }) => {+ afterAgentChange?: boolean+ }+ refreshFeatureFlagAfterAgentChange: () => {+ value: true+ }refreshFeatureFlagFailure: (error: string,errorObject?: any@@ -1366,10 +1381,14 @@ export interface featureFlagLogicActions {}refreshFeatureFlagSuccess: (featureFlagRefresh: FeatureFlagType | null,- payload?: any+ payload?: {+ afterAgentChange?: boolean+ }) => {featureFlagRefresh: FeatureFlagType | null- payload?: any+ payload?: {+ afterAgentChange?: boolean+ }}removeVariant: (index: number) => {index: number@@ -2162,6 +2181,7 @@ export const featureFlagLogic = kea<featureFlagLogicType>([// Re-establishes the saved-state baseline the unsaved-changes guard diffs against.// Only dispatch with server-authoritative state, so in-progress edits stay dirty.setOriginalFeatureFlag: (featureFlag: FeatureFlagType | null) => ({ featureFlag }),+ refreshFeatureFlagAfterAgentChange: true,setFeatureFlagFilters: (filters: FeatureFlagType['filters'], errors: any) => ({ filters, errors }),setSelectedTab: (tab: FeatureFlagsTab) => ({ tab }),setFeatureFlagMissing: true,@@ -2293,6 +2313,17 @@ export const featureFlagLogic = kea<featureFlagLogicType>([},})),reducers({+ // Read by the refresh loader, which samples it around its request to tell whether newer+ // state landed while the request was open.+ flagMutationCount: [+ 0,+ {+ // loadFeatureFlagSuccess re-baselines in the reducer below rather than dispatching+ // setOriginalFeatureFlag, so it has to be counted separately.+ loadFeatureFlagSuccess: (state) => state + 1,+ setOriginalFeatureFlag: (state) => state + 1,+ },+ ],originalFeatureFlag: [null as FeatureFlagType | null,{@@ -3225,22 +3256,41 @@ export const featureFlagLogic = kea<featureFlagLogicType>([// cache on mount. Has its own loading key so it never triggers the page skeleton,// while reconciling the flag (notably `active`) with the server — otherwise a stale// cached `active` can make the toggle and its confirmation dialog contradict the- // flag's real state.+ // flag's real state. `refreshFeatureFlagAfterAgentChange` also dispatches it.+ // That path is not silent: it replaces the whole flag when the form is clean, and shows a+ // notice when the form is dirty.featureFlagRefresh: [null as FeatureFlagType | null,{- refreshFeatureFlag: async () => {+ // `afterAgentChange` is unused here; refreshFeatureFlagSuccess reads it off the payload.+ // The `= {}` default keeps the generated action's payload optional now that+ // `breakpoint` follows it, so the mount-path `refreshFeatureFlag()` call still+ // typechecks once kea-typegen regenerates this logic's types.+ refreshFeatureFlag: async (_payload: { afterAgentChange?: boolean } = {}, breakpoint) => {if (!props.id || props.id === 'new' || props.id === 'link') {return null}+ const mutationsBefore = values.flagMutationCount+ let retrievedFlag: FeatureFlagTypetry {- const retrievedFlag: FeatureFlagType = await api.featureFlags.get(props.id)- return variantKeyToIndexFeatureFlagPayloads(retrievedFlag)+ retrievedFlag = await api.featureFlags.get(props.id)} catch {// Swallow errors — this is a silent background reconciliation, so a// transient failure shouldn't surface a toast or get reported.return null}+ // A second mutation can start a newer refresh while this one is open. Discard this+ // response if so, or a slow earlier request would overwrite the newer flag, its+ // baseline and its list entry, as the status loader below does for its verdict.+ // The breakpoint sits after the catch, which would otherwise swallow it.+ breakpoint()+ // `breakpoint` only supersedes another refresh. A mutation that lands while this+ // request is open leaves newer state that this response would roll back,+ // `version` included, which makes the next save read as a stale write.+ if (values.flagMutationCount !== mutationsBefore) {+ return null+ }+ return variantKeyToIndexFeatureFlagPayloads(retrievedFlag)},},],@@ -3759,6 +3809,9 @@ export const featureFlagLogic = kea<featureFlagLogicType>([},saveFeatureFlagSuccess: ({ featureFlag }) => {lemonToast.success('Feature flag saved')+ // Plain toast.dismiss, not lemonToast.dismiss, because the latter marks the id+ // cancelled and would swallow the notice for the next agent change on this flag.+ toast.dismiss(agentChangeToastId(props.id))actions.setFeatureFlag(featureFlag)// Whole flag just persisted — the baseline is now the saved state, so the form reads clean.actions.setOriginalFeatureFlag(toFeatureFlagBaseline(featureFlag))@@ -3886,28 +3939,58 @@ export const featureFlagLogic = kea<featureFlagLogicType>([actions.loadFeatureFlagStatus()}},- refreshFeatureFlagSuccess: ({ featureFlagRefresh }) => {- // Reconcile the cache-painted flag with the freshly fetched server state, and keep- // the list cache in sync so the two views agree.- if (featureFlagRefresh) {- if (values.originalFeatureFlag) {- // This refresh exists to correct a stale cached `active`, and it lands while the- // page is already interactive (its own loader key means no skeleton). Replacing- // the whole flag here would discard an edit made during the request and- // re-baseline over it, so the guard would read clean and lose it silently.- const persisted = {- active: featureFlagRefresh.active,- archived: featureFlagRefresh.archived,- version: featureFlagRefresh.version,- }- actions.setFeatureFlag({ ...values.featureFlag, ...persisted })- actions.setOriginalFeatureFlag({ ...values.originalFeatureFlag, ...persisted })- } else {- actions.setFeatureFlag(featureFlagRefresh)- actions.setOriginalFeatureFlag(toFeatureFlagBaseline(featureFlagRefresh))+ refreshFeatureFlagAfterAgentChange: () => {+ actions.refreshFeatureFlag({ afterAgentChange: true })+ // The stale banner is a server verdict, so it outlives the change without this.+ actions.loadFeatureFlagStatus()+ },+ refreshFeatureFlagSuccess: ({ featureFlagRefresh, payload }) => {+ if (!featureFlagRefresh) {+ return+ }+ const afterAgentChange = !!payload?.afterAgentChange+ const baseline = values.originalFeatureFlag+ // Replacing the whole flag would discard an edit made during the request and re-baseline+ // over it, leaving the guard clean. An agent change on a clean form is the one refresh+ // safe to take whole, and it has to be: it can have rewritten any field.+ if (!baseline || (afterAgentChange && !values.isFormDirty)) {+ actions.setFeatureFlag(featureFlagRefresh)+ actions.setOriginalFeatureFlag(toFeatureFlagBaseline(featureFlagRefresh))+ } else {+ // Keep the loaded `version` after an agent change. The server runs its stale-write+ // check only when the submitted version is behind the stored row, and that check is+ // what stops these unsaved edits from overwriting the fields the agent rewrote.+ // `active` and `archived` are form fields, so fold one only where the reader has not+ // edited it. Folding over a local edit drops it, and when it is the only edit the+ // form goes clean again while the notice below says the edits were kept.+ const isEditedLocally = (field: 'active' | 'archived'): boolean =>+ values.featureFlag[field] !== baseline[field]+ const persisted = {+ ...(isEditedLocally('active') ? {} : { active: featureFlagRefresh.active }),+ ...(isEditedLocally('archived') ? {} : { archived: featureFlagRefresh.archived }),+ ...(afterAgentChange ? {} : { version: featureFlagRefresh.version }),+ }+ actions.setFeatureFlag({ ...values.featureFlag, ...persisted })+ actions.setOriginalFeatureFlag({ ...baseline, ...persisted })+ if (afterAgentChange) {+ lemonToast.info(+ 'PostHog AI changed this flag. The page kept your unsaved edits, so it does not show the saved version.',+ {+ // This notice is the only signal that the page and the server disagree,+ // so it waits to be acted on instead of closing on the container's timer.+ autoClose: false,+ toastId: agentChangeToastId(props.id),+ button: {+ label: 'Discard edits and reload',+ action: () => actions.loadFeatureFlag(),+ dataAttr: 'feature-flag-agent-change-reload',+ },+ }+ )}- actions.updateFlag(featureFlagRefresh)}+ // Keep the list cache in sync with the server state either way, so the two views agree.+ actions.updateFlag(featureFlagRefresh)},updateFeatureFlagArchivedSuccess: ({ featureFlagActiveUpdate }) => {if (featureFlagActiveUpdate) {@@ -3994,6 +4077,7 @@ export const featureFlagLogic = kea<featureFlagLogicType>([}},loadFeatureFlagSuccess: async ({ featureFlag }) => {+ toast.dismiss(agentChangeToastId(props.id))// A ?tab=schedule deep link selects the tab before this load finishes, so the// schedule form's default was computed against the NEW_FLAG placeholder. Correct// it once against the loaded flag; only on the first load, so a later reload (e.g.@@ -5079,4 +5163,9 @@ export const featureFlagLogic = kea<featureFlagLogicType>([actions.loadFeatureFlag()}}),++ beforeUnmount(({ props }) => {+ // A notice that survives navigation has a button that reloads an unmounted logic.+ toast.dismiss(agentChangeToastId(props.id))+ }),])diff --git a/frontend/src/scenes/feature-flags/useFeatureFlagAgentRefresh.test.tsx b/frontend/src/scenes/feature-flags/useFeatureFlagAgentRefresh.test.tsxnew file mode 100644index 000000000000..1d9040a833e2--- /dev/null+++ b/frontend/src/scenes/feature-flags/useFeatureFlagAgentRefresh.test.tsx@@ -0,0 +1,93 @@+import { act, cleanup, renderHook } from '@testing-library/react'++import { initKeaTests } from '~/test/init'++import { foregroundStreamLogic, toolStreamEventsLogic } from 'products/posthog_ai/frontend/api/logics'+import type { ToolStreamEvent } from 'products/posthog_ai/frontend/api/types'++import { useFeatureFlagAgentRefresh } from './useFeatureFlagAgentRefresh'++const STREAM_KEY = 'run-1'++function completedToolCall(+ toolName: string,+ args: string,+ source: ToolStreamEvent['source'] = 'live'+): ToolStreamEvent {+ return {+ streamKey: STREAM_KEY,+ toolCallId: `${toolName}-${args}`,+ toolName,+ rawToolName: 'exec',+ phase: 'completed',+ invocation: {+ rawServerName: 'posthog',+ rawToolName: 'exec',+ input: { command: `call ${toolName} ${args}` },+ } as unknown as ToolStreamEvent['invocation'],+ source,+ }+}++describe('useFeatureFlagAgentRefresh', () => {+ beforeEach(() => {+ initKeaTests(false)+ })++ afterEach(() => {+ cleanup()+ })++ function watchFlag(flagId: number | null): jest.Mock {+ const onAgentChange = jest.fn()+ renderHook(() => useFeatureFlagAgentRefresh({ flagId, onAgentChange }))+ act(() => {+ // What sending a prompt from this page leaves behind: the watched run, target claimed.+ foregroundStreamLogic.actions.setForegroundStream(STREAM_KEY, 'side-panel')+ toolStreamEventsLogic.actions.claimApplyBackTargets(STREAM_KEY)+ })+ return onAgentChange+ }++ function emit(event: ToolStreamEvent): void {+ act(() => {+ toolStreamEventsLogic.actions.emitToolEvent(event)+ })+ }++ it('reacts once per completed lifecycle call that changed the open flag', () => {+ const onAgentChange = watchFlag(1)++ emit(completedToolCall('feature-flag-disable', '{"id":"1"}'))+ expect(onAgentChange).toHaveBeenCalledTimes(1)++ // A turn that changes this flag and then another one still has to refresh this page.+ emit(completedToolCall('update-feature-flag', '{"id":1,"name":"Renamed by the agent"}'))+ expect(onAgentChange).toHaveBeenCalledTimes(2)++ // Another flag's call must not refresh this page.+ emit(completedToolCall('feature-flag-archive', '{"id":7}'))+ expect(onAgentChange).toHaveBeenCalledTimes(2)++ // A delete leaves nothing to refresh into, so it stays off the allowlist. Without this case,+ // widening the list to every flag tool breaks no test.+ emit(completedToolCall('delete-feature-flag', '{"id":1}'))+ expect(onAgentChange).toHaveBeenCalledTimes(2)+ })++ it('ignores a replayed call, so reopening the page does not refresh it again', () => {+ const onAgentChange = watchFlag(1)++ emit(completedToolCall('feature-flag-disable', '{"id":1}', 'replay'))++ expect(onAgentChange).not.toHaveBeenCalled()+ })++ it('ignores tool calls while the flag is unsaved or unloaded', () => {+ const onAgentChange = watchFlag(null)++ emit(completedToolCall('update-feature-flag', '{"id":1}'))++ expect(onAgentChange).not.toHaveBeenCalled()+ })+})diff --git a/frontend/src/scenes/feature-flags/useFeatureFlagAgentRefresh.ts b/frontend/src/scenes/feature-flags/useFeatureFlagAgentRefresh.tsnew file mode 100644index 000000000000..548e007804d1--- /dev/null+++ b/frontend/src/scenes/feature-flags/useFeatureFlagAgentRefresh.ts@@ -0,0 +1,25 @@+import { useMcpToolApplyBack } from 'products/posthog_ai/frontend/api/logics'++import { FEATURE_FLAG_MUTATION_TOOLS, mutationTargetsFeatureFlag } from './featureFlagAiContext'++export interface UseFeatureFlagAgentRefreshOptions {+ /** The saved flag on screen, or null while it is unsaved or unloaded. */+ flagId: number | null+ onAgentChange: () => void+}++// Every matching completion is checked rather than only the turn's last one: a turn that changes+// this flag and then another one would otherwise leave this page stale.+export function useFeatureFlagAgentRefresh({ flagId, onAgentChange }: UseFeatureFlagAgentRefreshOptions): void {+ useMcpToolApplyBack({+ tools: FEATURE_FLAG_MUTATION_TOOLS,+ targetKey: `feature_flag:${flagId ?? 'unloaded'}`,+ active: flagId !== null,+ applyOn: 'tool_call_completed',+ onApply: (_event, { innerInput }) => {+ if (flagId !== null && mutationTargetsFeatureFlag(innerInput, flagId)) {+ onAgentChange()+ }+ },+ })+}