: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
import { MakeLogicType, actions, connect, kea, listeners, path, reducers, selectors } from 'kea'
import { FEATURE_FLAGS } from 'lib/constants'
import { FeatureFlagsSet, featureFlagLogic } from 'lib/logic/featureFlagLogic'
import type { PhaiViewMode } from '~/layout/ai/aiPanelIds'
import { sidePanelStateLogic } from '~/layout/navigation-3000/sidepanel/sidePanelStateLogic'
import { SidePanelTab } from '~/types'
import { PHAI_SCENE_AUTO_OPEN_DISMISSED_KEY } from './max-storage-keys'
import { maxGlobalLogic } from './maxGlobalLogic'
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface sceneAgentPanelLogicValues {
featureFlags: FeatureFlagsSet // featureFlagLogic
receivedFeatureFlags: boolean // featureFlagLogic
effectivePhaiView: PhaiViewMode // maxGlobalLogic
isMaxAvailable: boolean // maxGlobalLogic
modalMode: boolean // sidePanelStateLogic
selectedTab: SidePanelTab | null // sidePanelStateLogic
sidePanelAvailable: boolean // sidePanelStateLogic
sidePanelOpen: boolean // sidePanelStateLogic
activeSceneKeys: string[]
autoOpenDismissedScenes: Record<string, true>
sceneIntegrationEnabled: boolean
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface sceneAgentPanelLogicActions {
openSidePanel: (
tab: SidePanelTab,
options?: string | undefined
) => {
options: string | undefined
tab: SidePanelTab
} // sidePanelStateLogic
markAutoOpenDismissed: (sceneKeys: string[]) => {
sceneKeys: string[]
}
sceneEntered: (sceneKey: string) => {
sceneKey: string
}
sceneLeft: (sceneKey: string) => {
sceneKey: string
}
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface sceneAgentPanelLogicMeta {
__keaTypeGenInternalSelectorTypes: {
sceneIntegrationEnabled: (
featureFlags: FeatureFlagsSet,
effectivePhaiView: PhaiViewMode,
isMaxAvailable: boolean
) => boolean
}
}
export type sceneAgentPanelLogicType = MakeLogicType<
sceneAgentPanelLogicValues,
sceneAgentPanelLogicActions,
Record<string, any>,
sceneAgentPanelLogicMeta
>
/**
* Auto-opens the PostHog AI side panel for scenes that opt in (via `useSceneAgentPanel`), with a
* persisted per-scene opt-out: once the user closes the panel while such a scene is active, that
* scene stops auto-opening on this device. Only ever opens the new (sandbox) view - the legacy Max
* view has its own scene-context system and predates this behavior.
*/
export const sceneAgentPanelLogic = kea<sceneAgentPanelLogicType>([
path(['scenes', 'max', 'sceneAgentPanelLogic']),
connect(() => ({
values: [
featureFlagLogic,
['featureFlags', 'receivedFeatureFlags'],
maxGlobalLogic,
['effectivePhaiView', 'isMaxAvailable'],
sidePanelStateLogic,
['sidePanelOpen', 'selectedTab', 'sidePanelAvailable', 'modalMode'],
],
actions: [sidePanelStateLogic, ['openSidePanel']],
})),
actions({
sceneEntered: (sceneKey: string) => ({ sceneKey }),
sceneLeft: (sceneKey: string) => ({ sceneKey }),
markAutoOpenDismissed: (sceneKeys: string[]) => ({ sceneKeys }),
}),
reducers({
activeSceneKeys: [
[] as string[],
{
sceneEntered: (state, { sceneKey }) => (state.includes(sceneKey) ? state : [...state, sceneKey]),
sceneLeft: (state, { sceneKey }) => state.filter((key) => key !== sceneKey),
},
],
autoOpenDismissedScenes: [
{} as Record<string, true>,
{ persist: true, storageKey: PHAI_SCENE_AUTO_OPEN_DISMISSED_KEY },
{
markAutoOpenDismissed: (state, { sceneKeys }) => ({
...state,
...Object.fromEntries(sceneKeys.map((key) => [key, true as const])),
}),
},
],
}),
selectors({
// The single gate for the whole scene integration: context attachment and headline overrides
// (applied by useSceneAgentPanel) as well as the auto-open below all hang off this, so no part
// of the feature reaches users the rollout flag hasn't. Only the new (sandbox) view qualifies,
// because only it consumes attached context.
sceneIntegrationEnabled: [
(s) => [s.featureFlags, s.effectivePhaiView, s.isMaxAvailable],
(featureFlags: FeatureFlagsSet, effectivePhaiView: PhaiViewMode, isMaxAvailable: boolean): boolean =>
Boolean(
featureFlags[FEATURE_FLAGS.PHAI_SCENE_AUTO_OPEN] && effectivePhaiView === 'new' && isMaxAvailable
),
],
}),
listeners(({ actions, values }) => {
// Scenes whose auto-open decision has been made with the async gates resolved (flags received,
// side panel mounted). Flags re-resolve throughout a session (identify, reloadFeatureFlags), so
// without this the retry listeners below would re-open a panel the user closed in any state that
// records no dismissal, e.g. closed while a non-Max tab was selected.
const decidedSceneKeys = new Set<string>()
// Shared by the open and dismissal paths: dismissal must be gated exactly like auto-open, or a
// Max close on this scene before the feature reaches the user permanently opts them out.
const autoOpenEligible = (): boolean =>
Boolean(
values.sceneIntegrationEnabled &&
values.sidePanelAvailable &&
// In modal mode (narrow viewports) the panel overlays the whole scene - never force it open.
!values.modalMode
)
const maybeAutoOpen = (sceneKeys: string[]): void => {
if (values.receivedFeatureFlags && values.sidePanelAvailable) {
sceneKeys.forEach((key) => decidedSceneKeys.add(key))
}
if (
!autoOpenEligible() ||
sceneKeys.every((key) => values.autoOpenDismissedScenes[key]) ||
// Already open: either on Max (nothing to do) or on a tab the user chose (don't clobber it).
values.sidePanelOpen
) {
return
}
actions.openSidePanel(SidePanelTab.Max)
}
// The gates resolve asynchronously on a cold load (flags fetch, side panel mount), so a scene
// entered before they land would otherwise silently miss its auto-open until re-entry. One-shot
// per scene: only scenes not yet decided are retried.
const retryUndecidedScenes = (): void => {
const undecided = values.activeSceneKeys.filter((key) => !decidedSceneKeys.has(key))
if (undecided.length > 0) {
maybeAutoOpen(undecided)
}
}
return {
sceneEntered: ({ sceneKey }) => maybeAutoOpen([sceneKey]),
[featureFlagLogic.actionTypes.setFeatureFlags]: retryUndecidedScenes,
[sidePanelStateLogic.actionTypes.setSidePanelAvailable]: retryUndecidedScenes,
[sidePanelStateLogic.actionTypes.closeSidePanel]: ({ tab }: { tab?: SidePanelTab }) => {
// Any close of the Max tab while an opted-in scene is active counts as "stop auto-opening
// here" - regardless of whether this logic or the user opened the panel.
if (values.activeSceneKeys.length === 0 || !autoOpenEligible()) {
return
}
if ((tab && tab !== SidePanelTab.Max) || values.selectedTab !== SidePanelTab.Max) {
return
}
actions.markAutoOpenDismissed(values.activeSceneKeys)
},
}
}),
])