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.

refactor(posthog-ai): add a shell-owned ai logic (#126786)

Paul D'Ambrae8e7eda5ee61
diff --git a/frontend/bin/layer-baseline.txt b/frontend/bin/layer-baseline.txt
index bdc3f28ddcd4..e4eb2c831918 100644
--- a/frontend/bin/layer-baseline.txt
+++ b/frontend/bin/layer-baseline.txt
@@ -57,7 +57,6 @@ frontend/src/layout/panel-layout/navbar/tabs/navProductsTabLogic.ts -> frontend/
frontend/src/layout/scenes/components/SceneTitlePanelButton.tsx -> frontend/src/scenes/max/useMaxTool.ts
frontend/src/layout/scenes/components/SceneTitleSection.tsx -> frontend/src/scenes/max/components/AnimatedSparkles.tsx
frontend/src/layout/today/TodayAiPanel.tsx -> frontend/src/scenes/max/components/PhaiSidePanelChat.tsx
-frontend/src/layout/today/TodayAiPanel.tsx -> frontend/src/scenes/max/maxGlobalLogic.tsx
frontend/src/layout/today/TodayAiPanel.tsx -> frontend/src/scenes/max/maxLogic.tsx
frontend/src/layout/today/TodayAnalyticsSidebar.tsx -> frontend/src/scenes/analytics/AnalyticsPinButton.tsx
frontend/src/layout/today/TodayAnalyticsSidebar.tsx -> frontend/src/scenes/analytics/AnalyticsSpaceGlyph.tsx
@@ -68,7 +67,6 @@ frontend/src/layout/today/TodayAnalyticsSidebar.tsx -> frontend/src/scenes/analy
frontend/src/layout/today/TodayContextPanelMenu.tsx -> frontend/src/scenes/max/components/PhaiViewSwitchMenuItem.tsx
frontend/src/layout/today/TodayContextPanelMenu.tsx -> products/posthog_ai/frontend/api/menus.ts
frontend/src/layout/today/TodayNewAnalyticsButton.tsx -> frontend/src/scenes/analytics/NewAnalyticsMenu.tsx
-frontend/src/layout/today/TodayNewChatButton.tsx -> frontend/src/scenes/max/maxGlobalLogic.tsx
frontend/src/layout/today/TodayObjectHoverCard.tsx -> frontend/src/scenes/library/libraryUtils.ts
frontend/src/layout/today/TodayObjectHoverCard.tsx -> frontend/src/scenes/project-homepage/today/todayNumbers.ts
frontend/src/layout/today/TodayPanelTaskMenuItems.tsx -> products/posthog_ai/frontend/api/menus.ts
@@ -87,7 +85,6 @@ frontend/src/layout/today/TodaySupportPanel.tsx -> products/conversations/fronte
frontend/src/layout/today/TodaySupportPanel.tsx -> products/conversations/frontend/components/SidePanel/sidepanelTicketsLogic.ts
frontend/src/layout/today/TodaySupportResponseTimes.tsx -> frontend/src/scenes/billing/billingLogic.tsx
frontend/src/layout/today/todayAiChatLogic.ts -> frontend/src/scenes/max/mainFocusUrl.ts
-frontend/src/layout/today/todayAiChatLogic.ts -> frontend/src/scenes/max/maxGlobalLogic.tsx
frontend/src/layout/today/todayAiChatLogic.ts -> frontend/src/scenes/max/maxLogic.tsx
frontend/src/layout/today/todayAiChatLogic.ts -> products/posthog_ai/frontend/api/logics.ts
frontend/src/layout/today/todayAiChatLogic.ts -> products/posthog_ai/frontend/logics/attachedContextLogic.ts
@@ -112,7 +109,6 @@ frontend/src/layout/today/todayPreviewCards.ts -> products/posthog_ai/frontend/a
frontend/src/layout/today/todayRailStatusLogic.ts -> frontend/src/scenes/billing/billingLogic.tsx
frontend/src/layout/today/todayShellLogic.ts -> frontend/src/scenes/analytics/analyticsUtils.ts
frontend/src/layout/today/todayShellLogic.ts -> frontend/src/scenes/library/libraryUtils.ts
-frontend/src/layout/today/todayShellLogic.ts -> frontend/src/scenes/max/maxGlobalLogic.tsx
frontend/src/layout/today/todayShellLogic.ts -> frontend/src/scenes/settings/settingsSectionScenes.ts
frontend/src/layout/today/todaySpacesLogic.ts -> frontend/src/scenes/max/maxGlobalLogic.tsx
frontend/src/layout/today/todaySpacesLogic.ts -> products/tasks/frontend/spaces/taskPullRequests.ts
diff --git a/frontend/src/layout/ai/aiPanelIds.ts b/frontend/src/layout/ai/aiPanelIds.ts
index 4a90e689869c..f7e490b78891 100644
--- a/frontend/src/layout/ai/aiPanelIds.ts
+++ b/frontend/src/layout/ai/aiPanelIds.ts
@@ -18,6 +18,6 @@ export const SCOUT_AI_PANEL = 'inbox-scout'
* Which PostHog AI implementation the Max scene renders. `'new'` is the posthog_ai/frontend surface
* (the tasks product on `/ai`, the new composer + thread viewer in the side panel); `'legacy'` is the
* existing Max chat. Only meaningful while the `PHAI_SANDBOX_MODE` flag is on. See `effectivePhaiView`
- * in `maxGlobalLogic`.
+ * in `aiShellLogic`.
*/
export type PhaiViewMode = 'new' | 'legacy'
diff --git a/frontend/src/layout/ai/aiShellLogic.test.ts b/frontend/src/layout/ai/aiShellLogic.test.ts
new file mode 100644
index 000000000000..f4c66d8da557
--- /dev/null
+++ b/frontend/src/layout/ai/aiShellLogic.test.ts
@@ -0,0 +1,82 @@
+import { expectLogic } from 'kea-test-utils'
+
+import { FEATURE_FLAGS } from 'lib/constants'
+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
+import { preflightLogic } from 'lib/logic/preflightLogic'
+
+import { initKeaTests } from '~/test/init'
+
+import { aiShellLogic } from './aiShellLogic'
+
+describe('aiShellLogic', () => {
+ let logic: ReturnType<typeof aiShellLogic.build>
+
+ beforeEach(() => {
+ localStorage.clear()
+ initKeaTests()
+ logic = aiShellLogic()
+ logic.mount()
+ })
+
+ afterEach(() => {
+ logic.unmount()
+ localStorage.clear()
+ })
+
+ describe('isMaxAvailable selector', () => {
+ it.each([
+ { realm: 'a not-yet-loaded preflight', preflight: null, expected: true },
+ { realm: 'PostHog Cloud', preflight: { cloud: true }, expected: true },
+ {
+ realm: 'self-hosted with an Anthropic key',
+ preflight: { cloud: false, is_debug: false, anthropic_available: true },
+ expected: true,
+ },
+ {
+ realm: 'self-hosted without a key',
+ preflight: { cloud: false, is_debug: false, anthropic_available: false },
+ expected: false,
+ },
+ ])('is $expected on $realm', async ({ preflight, expected }) => {
+ preflightLogic.actions.loadPreflightSuccess(preflight as any)
+
+ await expectLogic(logic).toMatchValues({ isMaxAvailable: expected })
+ })
+ })
+
+ // The flag is the only thing that may expose the new posthog_ai surface — without the gate a stored
+ // preference (or a missing default) would leak it to every user. Lock in: flag off collapses to legacy
+ // regardless of the stored mode; flag on passes the stored mode through.
+ describe('effectivePhaiView selector', () => {
+ it.each([
+ { flagOn: false, mode: 'new', expected: 'legacy' },
+ { flagOn: false, mode: 'legacy', expected: 'legacy' },
+ { flagOn: true, mode: 'new', expected: 'new' },
+ { flagOn: true, mode: 'legacy', expected: 'legacy' },
+ ] as const)(
+ 'is $expected when sandbox flag is $flagOn and stored mode is $mode',
+ async ({ flagOn, mode, expected }) => {
+ featureFlagLogic.actions.setFeatureFlags(
+ flagOn ? [FEATURE_FLAGS.PHAI_SANDBOX_MODE] : [],
+ flagOn ? { [FEATURE_FLAGS.PHAI_SANDBOX_MODE]: true } : {}
+ )
+ logic.actions.setPhaiViewMode(mode)
+
+ await expectLogic(logic).toMatchValues({ effectivePhaiView: expected })
+ }
+ )
+ })
+
+ // Users already chose a view under this key. A renamed key, or a second persisted reducer that wins
+ // the race, would silently reset that choice.
+ it.each(['new', 'legacy'] as const)('restores the view mode %s saved under the existing key', (mode) => {
+ logic.unmount()
+ initKeaTests()
+ localStorage.setItem('posthog_ai_view_mode', JSON.stringify(mode))
+
+ logic = aiShellLogic()
+ logic.mount()
+
+ expect(logic.values.phaiViewMode).toBe(mode)
+ })
+})
diff --git a/frontend/src/layout/ai/aiShellLogic.ts b/frontend/src/layout/ai/aiShellLogic.ts
new file mode 100644
index 000000000000..5ac7474010ef
--- /dev/null
+++ b/frontend/src/layout/ai/aiShellLogic.ts
@@ -0,0 +1,95 @@
+import { MakeLogicType, actions, connect, kea, path, reducers, selectors } from 'kea'
+
+import { FEATURE_FLAGS } from 'lib/constants'
+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
+import type { FeatureFlagsSet } from 'lib/logic/featureFlagLogic'
+import { preflightLogic } from 'lib/logic/preflightLogic'
+
+import type { PhaiViewMode } from '~/layout/ai/aiPanelIds'
+import type { PreflightStatus } from '~/types'
+
+/** Which PostHog AI implementation the Max scene renders when the sandbox flag is on. */
+const PHAI_VIEW_MODE_KEY = 'posthog_ai_view_mode'
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface aiShellLogicValues {
+ featureFlags: FeatureFlagsSet // featureFlagLogic
+ isCloudOrDev: boolean | undefined // preflightLogic
+ preflight: PreflightStatus | null // preflightLogic
+ effectivePhaiView: PhaiViewMode
+ isMaxAvailable: boolean
+ isPhaiSandboxFlagOn: boolean
+ phaiViewMode: PhaiViewMode
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface aiShellLogicActions {
+ setPhaiViewMode: (mode: PhaiViewMode) => {
+ mode: PhaiViewMode
+ }
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface aiShellLogicMeta {
+ __keaTypeGenInternalSelectorTypes: {
+ isMaxAvailable: (isCloudOrDev: boolean | undefined, preflight: PreflightStatus | null) => boolean
+ isPhaiSandboxFlagOn: (featureFlags: FeatureFlagsSet) => boolean
+ effectivePhaiView: (isPhaiSandboxFlagOn: boolean, phaiViewMode: PhaiViewMode) => PhaiViewMode
+ }
+}
+
+export type aiShellLogicType = MakeLogicType<
+ aiShellLogicValues,
+ aiShellLogicActions,
+ Record<string, any>,
+ aiShellLogicMeta
+>
+
+/**
+ * The PostHog AI state the app shell reads on every page. It must stay light: the shell loads it eagerly,
+ * so it must not import the Max scene or the posthog_ai run surface.
+ */
+export const aiShellLogic = kea<aiShellLogicType>([
+ path(['layout', 'ai', 'aiShellLogic']),
+ connect(() => ({
+ values: [featureFlagLogic, ['featureFlags'], preflightLogic, ['preflight', 'isCloudOrDev']],
+ })),
+ actions({
+ setPhaiViewMode: (mode: PhaiViewMode) => ({ mode }),
+ }),
+ reducers({
+ // The user's chosen implementation, persisted per device. Defaults to the new surface so a
+ // flagged user lands there; `effectivePhaiView` collapses this to legacy when the flag is off.
+ phaiViewMode: [
+ 'new' as PhaiViewMode,
+ { persist: true, storageKey: PHAI_VIEW_MODE_KEY },
+ {
+ setPhaiViewMode: (_, { mode }) => mode,
+ },
+ ],
+ }),
+ selectors({
+ // On Cloud/dev a provider key is always present. On a self-hosted (hobby) instance Max only
+ // works once ANTHROPIC_API_KEY is configured, so we surface a "set the key" state instead.
+ // Treat a not-yet-loaded preflight (null) as available so the empty-state doesn't flash
+ // before preflight resolves — once loaded we gate on cloud/dev or the key being present.
+ isMaxAvailable: [
+ (s) => [s.isCloudOrDev, s.preflight],
+ (isCloudOrDev: boolean | undefined, preflight: PreflightStatus | null): boolean =>
+ !preflight || !!isCloudOrDev || !!preflight.anthropic_available,
+ ],
+ // Gates the new-vs-legacy toggle: only flagged users can switch, and the new surface only
+ // exists for them.
+ isPhaiSandboxFlagOn: [
+ (s) => [s.featureFlags],
+ (featureFlags: FeatureFlagsSet): boolean => !!featureFlags[FEATURE_FLAGS.PHAI_SANDBOX_MODE],
+ ],
+ // The implementation the Max scene actually renders: the user's choice while the flag is on,
+ // always legacy otherwise (so non-flagged users are unaffected regardless of any stored value).
+ effectivePhaiView: [
+ (s) => [s.isPhaiSandboxFlagOn, s.phaiViewMode],
+ (isPhaiSandboxFlagOn: boolean, phaiViewMode: PhaiViewMode): PhaiViewMode =>
+ isPhaiSandboxFlagOn ? phaiViewMode : 'legacy',
+ ],
+ }),
+])
diff --git a/frontend/src/layout/today/TodayAiPanel.tsx b/frontend/src/layout/today/TodayAiPanel.tsx
index 08a247b1468a..9210d53e1857 100644
--- a/frontend/src/layout/today/TodayAiPanel.tsx
+++ b/frontend/src/layout/today/TodayAiPanel.tsx
@@ -5,15 +5,15 @@ import { Button, Empty, EmptyContent, EmptyDescription, EmptyHeader, EmptyMedia,
import { useOnMountEffect } from 'lib/hooks/useOnMountEffect'
import { PhaiSidePanelChat } from 'scenes/max/components/PhaiSidePanelChat'
-import { maxGlobalLogic } from 'scenes/max/maxGlobalLogic'
import { sidePanelMaxLogic } from 'scenes/max/maxLogic'
import { REPORT_AI_PANEL, SCOUT_AI_PANEL } from '~/layout/ai/aiPanelIds'
+import { aiShellLogic } from '~/layout/ai/aiShellLogic'
import { SidePanelMax } from '~/layout/navigation-3000/sidepanel/panels/max/SidePanelMax'
import { sidePanelStateLogic } from '~/layout/navigation-3000/sidepanel/sidePanelStateLogic'
export function TodayAiPanel(): JSX.Element {
- const { isMaxAvailable, effectivePhaiView } = useValues(maxGlobalLogic)
+ const { isMaxAvailable, effectivePhaiView } = useValues(aiShellLogic)
const { selectedTabOptions } = useValues(sidePanelStateLogic)
// Closing the panel unmounts this tree, so hold the chat logic to keep the open chat and draft.
diff --git a/frontend/src/layout/today/TodayNewChatButton.tsx b/frontend/src/layout/today/TodayNewChatButton.tsx
index 5bb67d2c0f30..d692425ee5f9 100644
--- a/frontend/src/layout/today/TodayNewChatButton.tsx
+++ b/frontend/src/layout/today/TodayNewChatButton.tsx
@@ -5,13 +5,14 @@ import { IconPlus } from '@posthog/icons'
import { Button, Tooltip, TooltipContent, TooltipTrigger, cn } from '@posthog/quill'
import { LinkPrimitive } from 'lib/lemon-ui/Link'
-import { maxGlobalLogic } from 'scenes/max/maxGlobalLogic'
+
+import { aiShellLogic } from '~/layout/ai/aiShellLogic'
import { todayNewChatUrl } from './todayShellLogic'
export function TodayNewChatButton(): JSX.Element {
const { location, searchParams } = useValues(router)
- const { effectivePhaiView } = useValues(maxGlobalLogic)
+ const { effectivePhaiView } = useValues(aiShellLogic)
const newChatUrl = todayNewChatUrl(effectivePhaiView)
// A legacy chat in progress also sits on `/ai`, with its id in `chat`.
const starting = location.pathname.endsWith(newChatUrl) && !searchParams.chat && !searchParams.task
diff --git a/frontend/src/layout/today/todayAiChatLogic.ts b/frontend/src/layout/today/todayAiChatLogic.ts
index 9d0951d0b91a..cfbf4c168284 100644
--- a/frontend/src/layout/today/todayAiChatLogic.ts
+++ b/frontend/src/layout/today/todayAiChatLogic.ts
@@ -4,7 +4,6 @@ import type { LocationChangedPayload } from 'kea-router/lib/types'
import posthog from 'posthog-js'
import { mainFocusUrl } from 'scenes/max/mainFocusUrl'
-import { maxGlobalLogic } from 'scenes/max/maxGlobalLogic'
import { maxLogic } from 'scenes/max/maxLogic'
import { urls } from 'scenes/urls'
@@ -15,6 +14,7 @@ import {
SIDE_PANEL_PANEL_ID,
type PhaiViewMode,
} from '~/layout/ai/aiPanelIds'
+import { aiShellLogic } from '~/layout/ai/aiShellLogic'
import { sidePanelStateLogic } from '~/layout/navigation-3000/sidepanel/sidePanelStateLogic'
import { SidePanelTab } from '~/types'
@@ -38,8 +38,8 @@ function timeOf(item: TodayWorkItem): number {
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface todayAiChatLogicValues {
+ effectivePhaiView: PhaiViewMode // aiShellLogic
contextItems: AttachedContextItem[] // attachedContextLogic
- effectivePhaiView: PhaiViewMode // maxGlobalLogic
conversationId: string | null // maxLogic
legacyChatTitle: string | null // maxLogic
activeCreation: ActiveCreation | null // runnerPanelLogic
@@ -60,6 +60,9 @@ export interface todayAiChatLogicValues {
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface todayAiChatLogicActions {
+ setPhaiViewMode: (mode: PhaiViewMode) => {
+ mode: PhaiViewMode
+ } // aiShellLogic
deregisterContext: (providerId: string) => {
providerId: string
} // attachedContextLogic
@@ -70,9 +73,6 @@ export interface todayAiChatLogicActions {
items: AttachedContextItem[]
providerId: string
} // attachedContextLogic
- setPhaiViewMode: (mode: PhaiViewMode) => {
- mode: PhaiViewMode
- } // maxGlobalLogic
openConversation: (conversationId: string) => {
conversationId: string
} // maxLogic
@@ -200,7 +200,7 @@ export const todayAiChatLogic = kea<todayAiChatLogicType>([
values: [
todaySpacesLogic,
['allRecentItems', 'pinnedItems', 'unreadSessionIds', 'recentLoading', 'taskActivity'],
- maxGlobalLogic,
+ aiShellLogic,
['effectivePhaiView'],
maxLogic({ panelId: SIDE_PANEL_PANEL_ID }),
['chatTitle as legacyChatTitle', 'conversationId'],
@@ -214,7 +214,7 @@ export const todayAiChatLogic = kea<todayAiChatLogicType>([
['selectedTabOptions'],
],
actions: [
- maxGlobalLogic,
+ aiShellLogic,
['setPhaiViewMode'],
sidePanelStateLogic,
['setSidePanelOptions', 'openSidePanel'],
diff --git a/frontend/src/layout/today/todayShellLogic.ts b/frontend/src/layout/today/todayShellLogic.ts
index 0c438cd2bbb4..c09b33fcc9e4 100644
--- a/frontend/src/layout/today/todayShellLogic.ts
+++ b/frontend/src/layout/today/todayShellLogic.ts
@@ -10,11 +10,11 @@ import { FeatureFlagsSet, featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { isUnderPath, removeProjectIdIfPresent } from 'lib/utils/kea-router'
import { fromPostHogProducts } from 'scenes/analytics/analyticsUtils'
import { libraryTypeForPath } from 'scenes/library/libraryUtils'
-import { maxGlobalLogic } from 'scenes/max/maxGlobalLogic'
import { settingsSectionSceneForPath } from 'scenes/settings/settingsSectionScenes'
import { urls } from 'scenes/urls'
import type { PhaiViewMode } from '~/layout/ai/aiPanelIds'
+import { aiShellLogic } from '~/layout/ai/aiShellLogic'
import { navigationLogic } from '~/layout/navigation/navigationLogic'
import { getNavProductPages, navProductHrefForPath } from '~/layout/panel-layout/navbar/tabs/navProductItems'
import { FileSystemImport } from '~/queries/schema/schema-general'
@@ -139,8 +139,8 @@ function paneAfterNavigation(openPane: TodayRailPane | null, pathname: string):
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface todayShellLogicValues {
+ effectivePhaiView: PhaiViewMode // aiShellLogic
featureFlags: FeatureFlagsSet // featureFlagLogic
- effectivePhaiView: PhaiViewMode // maxGlobalLogic
mobileLayout: boolean // navigationLogic
activePane: TodayRailPane
lastSceneUrl: string | null
@@ -285,7 +285,7 @@ export const todayShellLogic = kea<todayShellLogicType>([
values: [
featureFlagLogic,
['featureFlags'],
- maxGlobalLogic,
+ aiShellLogic,
['effectivePhaiView'],
navigationLogic,
['mobileLayout'],
diff --git a/frontend/src/scenes/max/max-storage-keys.ts b/frontend/src/scenes/max/max-storage-keys.ts
index 9cf644927a77..4c59680b0050 100644
--- a/frontend/src/scenes/max/max-storage-keys.ts
+++ b/frontend/src/scenes/max/max-storage-keys.ts
@@ -6,8 +6,5 @@
/** Key for persisting pending AI prompts across page reloads (e.g., OAuth redirects) */
export const PENDING_AI_PROMPT_KEY = 'posthog_ai_pending_prompt'
-/** Which PostHog AI implementation the Max scene renders when the sandbox flag is on (see maxGlobalLogic). */
-export const PHAI_VIEW_MODE_KEY = 'posthog_ai_view_mode'
-
/** Scene keys whose PostHog AI panel auto-open the user has dismissed (see sceneAgentPanelLogic). */
export const PHAI_SCENE_AUTO_OPEN_DISMISSED_KEY = 'posthog_ai_scene_auto_open_dismissed'
diff --git a/frontend/src/scenes/max/maxGlobalLogic.test.ts b/frontend/src/scenes/max/maxGlobalLogic.test.ts
index 57bd21a3d6e2..d951afac5a75 100644
--- a/frontend/src/scenes/max/maxGlobalLogic.test.ts
+++ b/frontend/src/scenes/max/maxGlobalLogic.test.ts
@@ -2,12 +2,10 @@ import { router } from 'kea-router'
import { expectLogic } from 'kea-test-utils'
import api from 'lib/api'
-import { FEATURE_FLAGS } from 'lib/constants'
-import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
-import { preflightLogic } from 'lib/logic/preflightLogic'
import { aiConsentLogic } from 'scenes/settings/organization/aiConsentLogic'
import { SIDE_PANEL_PANEL_ID } from '~/layout/ai/aiPanelIds'
+import { aiShellLogic } from '~/layout/ai/aiShellLogic'
import { useMocks } from '~/mocks/jest'
import { initKeaTests } from '~/test/init'
@@ -105,27 +103,6 @@ describe('maxGlobalLogic', () => {
})
})
- describe('isMaxAvailable selector', () => {
- it.each([
- { realm: 'a not-yet-loaded preflight', preflight: null, expected: true },
- { realm: 'PostHog Cloud', preflight: { cloud: true }, expected: true },
- {
- realm: 'self-hosted with an Anthropic key',
- preflight: { cloud: false, is_debug: false, anthropic_available: true },
- expected: true,
- },
- {
- realm: 'self-hosted without a key',
- preflight: { cloud: false, is_debug: false, anthropic_available: false },
- expected: false,
- },
- ])('is $expected on $realm', async ({ preflight, expected }) => {
- preflightLogic.actions.loadPreflightSuccess(preflight as any)
-
- await expectLogic(logic).toMatchValues({ isMaxAvailable: expected })
- })
- })
-
// Consent state (accept/dismiss/request-access) now lives in aiConsentLogic (see aiConsentLogic.test.ts)
// and is only forwarded here via `connect` so the ~15 existing consumers keep reading it off
// maxGlobalLogic unchanged. This guards the forwarding wiring itself — a mistake here (e.g. connecting
@@ -168,27 +145,19 @@ describe('maxGlobalLogic', () => {
})
})
- // The flag is the only thing that may expose the new posthog_ai surface — without the gate a stored
- // preference (or a missing default) would leak it to every user. Lock in: flag off collapses to legacy
- // regardless of the stored mode; flag on passes the stored mode through.
- describe('effectivePhaiView selector', () => {
- it.each([
- { flagOn: false, mode: 'new', expected: 'legacy' },
- { flagOn: false, mode: 'legacy', expected: 'legacy' },
- { flagOn: true, mode: 'new', expected: 'new' },
- { flagOn: true, mode: 'legacy', expected: 'legacy' },
- ] as const)(
- 'is $expected when sandbox flag is $flagOn and stored mode is $mode',
- async ({ flagOn, mode, expected }) => {
- featureFlagLogic.actions.setFeatureFlags(
- flagOn ? [FEATURE_FLAGS.PHAI_SANDBOX_MODE] : [],
- flagOn ? { [FEATURE_FLAGS.PHAI_SANDBOX_MODE]: true } : {}
- )
- logic.actions.setPhaiViewMode(mode)
-
- await expectLogic(logic).toMatchValues({ effectivePhaiView: expected })
- }
- )
+ // The view mode has one owner, aiShellLogic. A second copy here would let the shell and the Max scene
+ // disagree about which surface to show.
+ it('shares the view mode with aiShellLogic', () => {
+ const shell = aiShellLogic()
+ shell.mount()
+
+ logic.actions.setPhaiViewMode('legacy')
+ expect(shell.values.phaiViewMode).toBe('legacy')
+
+ shell.actions.setPhaiViewMode('new')
+ expect(logic.values.phaiViewMode).toBe('new')
+
+ shell.unmount()
})
// A chat and its task are deleted together on the server. Each list only knows about its own
diff --git a/frontend/src/scenes/max/maxGlobalLogic.tsx b/frontend/src/scenes/max/maxGlobalLogic.tsx
index e439f5e76398..4ba2becaf32c 100644
--- a/frontend/src/scenes/max/maxGlobalLogic.tsx
+++ b/frontend/src/scenes/max/maxGlobalLogic.tsx
@@ -4,11 +4,9 @@ import { router } from 'kea-router'
import type { LocationChangedPayload } from 'kea-router/lib/types'
import api from 'lib/api'
-import { FEATURE_FLAGS } from 'lib/constants'
import { dayjs } from 'lib/dayjs'
import { lemonToast } from 'lib/lemon-ui/LemonToast'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
-import { preflightLogic } from 'lib/logic/preflightLogic'
import { newInternalTab } from 'lib/utils/newInternalTab'
import { organizationLogic } from 'scenes/organizationLogic'
import { sceneLogic } from 'scenes/sceneLogic'
@@ -17,6 +15,7 @@ import { teamLogic } from 'scenes/teamLogic'
import { urls } from 'scenes/urls'
import type { PhaiViewMode } from '~/layout/ai/aiPanelIds'
+import { aiShellLogic } from '~/layout/ai/aiShellLogic'
import { sidePanelStateLogic } from '~/layout/navigation-3000/sidepanel/sidePanelStateLogic'
import { Conversation, ConversationDetail, SidePanelTab } from '~/types'
@@ -25,10 +24,9 @@ import { taskEventsLogic } from 'products/posthog_ai/frontend/logics/taskEventsL
import { tasksLogic } from 'products/posthog_ai/frontend/logics/tasksLogic'
import type { FeatureFlagsSet } from '../../lib/logic/featureFlagLogic'
-import type { OrganizationType, PreflightStatus } from '../../types'
+import type { OrganizationType } from '../../types'
import type { SceneConfig } from '../sceneTypes'
import { TOOL_DEFINITIONS, ToolRegistration } from './max-constants'
-import { PHAI_VIEW_MODE_KEY } from './max-storage-keys'
import { maxLogic, mergeConversationHistory, mergeConversations, sidePanelMaxLogic } from './maxLogic'
// Keep this stored across all projects, only display this once per device
@@ -90,10 +88,12 @@ export interface maxGlobalLogicValues {
dataProcessingApprovalDisabledReason: string | null // aiConsentLogic
dataProcessingDismissed: boolean // aiConsentLogic
requestingAiAccess: boolean // aiConsentLogic
+ effectivePhaiView: PhaiViewMode // aiShellLogic
+ isMaxAvailable: boolean // aiShellLogic
+ isPhaiSandboxFlagOn: boolean // aiShellLogic
+ phaiViewMode: PhaiViewMode // aiShellLogic
featureFlags: FeatureFlagsSet // featureFlagLogic
currentOrganization: OrganizationType | null // organizationLogic
- isCloudOrDev: boolean | undefined // preflightLogic
- preflight: PreflightStatus | null // preflightLogic
sceneConfig: SceneConfig | null // sceneLogic
sceneId: string | null // sceneLogic
selectedTab: SidePanelTab | null // sidePanelStateLogic
@@ -104,12 +104,8 @@ export interface maxGlobalLogicValues {
conversationHistoryLoading: boolean
currentConversationId: string | null
editInsightToolRegistered: true
- effectivePhaiView: PhaiViewMode
- isMaxAvailable: boolean
isOrganizationCreatedRecently: boolean
- isPhaiSandboxFlagOn: boolean
liabilityNoticeDismissed: boolean
- phaiViewMode: PhaiViewMode
registeredToolMap: Record<string, ToolRegistration>
shouldShowLiabilityNotice: boolean
toolMap: {
@@ -134,6 +130,9 @@ export interface maxGlobalLogicActions {
requestAiAccess: () => {
value: true
} // aiConsentLogic
+ setPhaiViewMode: (mode: PhaiViewMode) => {
+ mode: PhaiViewMode
+ } // aiShellLogic
locationChanged: ({
method,
pathname,
@@ -225,23 +224,17 @@ export interface maxGlobalLogicActions {
registerTool: (tool: ToolRegistration) => {
tool: ToolRegistration
}
- setPhaiViewMode: (mode: PhaiViewMode) => {
- mode: PhaiViewMode
- }
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface maxGlobalLogicMeta {
__keaTypeGenInternalSelectorTypes: {
currentConversationId: (searchParams: Record<string, any>) => string | null
- isMaxAvailable: (isCloudOrDev: boolean | undefined, preflight: PreflightStatus | null) => boolean
isOrganizationCreatedRecently: (currentOrganization: OrganizationType | null) => boolean
shouldShowLiabilityNotice: (
isOrganizationCreatedRecently: boolean,
liabilityNoticeDismissed: boolean
) => boolean
- isPhaiSandboxFlagOn: (featureFlags: FeatureFlagsSet) => boolean
- effectivePhaiView: (isPhaiSandboxFlagOn: boolean, phaiViewMode: PhaiViewMode) => PhaiViewMode
availableStaticTools: (featureFlags: FeatureFlagsSet) => ToolRegistration[]
toolMap: (
registeredToolMap: Record<string, ToolRegistration>,
@@ -266,6 +259,8 @@ export const maxGlobalLogic = kea<maxGlobalLogicType>([
path(['scenes', 'max', 'maxGlobalLogic']),
connect(() => ({
values: [
+ aiShellLogic,
+ ['effectivePhaiView', 'isMaxAvailable', 'isPhaiSandboxFlagOn', 'phaiViewMode'],
organizationLogic,
['currentOrganization'],
sceneLogic,
@@ -276,8 +271,6 @@ export const maxGlobalLogic = kea<maxGlobalLogicType>([
['featureFlags'],
sidePanelStateLogic,
['sidePanelOpen', 'selectedTab'],
- preflightLogic,
- ['preflight', 'isCloudOrDev'],
aiConsentLogic,
[
'dataProcessingAccepted',
@@ -294,6 +287,8 @@ export const maxGlobalLogic = kea<maxGlobalLogicType>([
['openSidePanel'],
aiConsentLogic,
['acceptDataProcessing', 'dismissDataProcessing', 'requestAiAccess'],
+ aiShellLogic,
+ ['setPhaiViewMode'],
],
})),
actions({
@@ -305,7 +300,6 @@ export const maxGlobalLogic = kea<maxGlobalLogicType>([
prependOrReplaceConversation: (conversation: ConversationDetail | Conversation) => ({ conversation }),
deleteConversation: (id: string) => ({ id }),
dismissLiabilityNotice: true,
- setPhaiViewMode: (mode: PhaiViewMode) => ({ mode }),
}),
loaders(({ values }) => ({
@@ -376,25 +370,8 @@ export const maxGlobalLogic = kea<maxGlobalLogicType>([
dismissLiabilityNotice: () => true,
},
],
- // The user's chosen implementation, persisted per device. Defaults to the new surface so a
- // flagged user lands there; `effectivePhaiView` collapses this to legacy when the flag is off.
- phaiViewMode: [
- 'new' as PhaiViewMode,
- { persist: true, storageKey: PHAI_VIEW_MODE_KEY },
- {
- setPhaiViewMode: (_, { mode }) => mode,
- },
- ],
}),
listeners(({ actions, values }) => ({
- setPhaiViewMode: ({ mode }) => {
- // The task list only loads on mount. A chat made on the legacy view has a task copy by the
- // time the user switches, and the merged list shows it as that task once it is loaded.
- const tasks = tasksLogic.findMounted()
- if (mode === 'new' && tasks) {
- tasks.actions.loadTasks(tasks.values.taskListParams)
- }
- },
// A chat and its task are deleted together on the server, so removing a task from the merged
// list must drop the chat row too, or the chat resurfaces as a row of its own.
[taskEventsLogic.actionTypes.taskDeleted]: () => {
@@ -457,15 +434,6 @@ export const maxGlobalLogic = kea<maxGlobalLogicType>([
() => [router.selectors.searchParams],
(searchParams: Record<string, any>): string | null => searchParams?.chat ?? null,
],
- // On Cloud/dev a provider key is always present. On a self-hosted (hobby) instance Max only
- // works once ANTHROPIC_API_KEY is configured, so we surface a "set the key" state instead.
- // Treat a not-yet-loaded preflight (null) as available so the empty-state doesn't flash
- // before preflight resolves — once loaded we gate on cloud/dev or the key being present.
- isMaxAvailable: [
- (s) => [s.isCloudOrDev, s.preflight],
- (isCloudOrDev: boolean | undefined, preflight: null | import('~/types').PreflightStatus): boolean =>
- !preflight || !!isCloudOrDev || !!preflight.anthropic_available,
- ],
isOrganizationCreatedRecently: [
(s) => [s.currentOrganization],
(currentOrganization: null | import('~/types').OrganizationType): boolean => {
@@ -478,20 +446,6 @@ export const maxGlobalLogic = kea<maxGlobalLogicType>([
(isOrganizationCreatedRecently: boolean, liabilityNoticeDismissed: boolean): boolean =>
isOrganizationCreatedRecently && !liabilityNoticeDismissed,
],
- // Gates the new-vs-legacy toggle: only flagged users can switch, and the new surface only
- // exists for them.
- isPhaiSandboxFlagOn: [
- (s) => [s.featureFlags],
- (featureFlags: import('lib/logic/featureFlagLogic').FeatureFlagsSet): boolean =>
- !!featureFlags[FEATURE_FLAGS.PHAI_SANDBOX_MODE],
- ],
- // The implementation the Max scene actually renders: the user's choice while the flag is on,
- // always legacy otherwise (so non-flagged users are unaffected regardless of any stored value).
- effectivePhaiView: [
- (s) => [s.isPhaiSandboxFlagOn, s.phaiViewMode],
- (isPhaiSandboxFlagOn: boolean, phaiViewMode: PhaiViewMode): PhaiViewMode =>
- isPhaiSandboxFlagOn ? phaiViewMode : 'legacy',
- ],
availableStaticTools: [
(s) => [s.featureFlags],
(featureFlags: import('lib/logic/featureFlagLogic').FeatureFlagsSet): ToolRegistration[] => {
diff --git a/products/posthog_ai/frontend/logics/tasksLogic.ts b/products/posthog_ai/frontend/logics/tasksLogic.ts
index b37f01971bf3..bb44334e1499 100644
--- a/products/posthog_ai/frontend/logics/tasksLogic.ts
+++ b/products/posthog_ai/frontend/logics/tasksLogic.ts
@@ -11,6 +11,8 @@ import type { FeatureFlagsSet } from 'lib/logic/featureFlagLogic'
import { addProductIntent } from 'lib/utils/product-intents'
import { userLogic } from 'scenes/userLogic'
+import type { PhaiViewMode } from '~/layout/ai/aiPanelIds'
+import { aiShellLogic } from '~/layout/ai/aiShellLogic'
import { ProductIntentContext, ProductKey } from '~/queries/schema/schema-general'
import { TasksListOrdering } from 'products/tasks/frontend/generated/api.schemas'
@@ -48,6 +50,9 @@ export interface tasksLogicValues {
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface tasksLogicActions {
+ setPhaiViewMode: (mode: PhaiViewMode) => {
+ mode: PhaiViewMode
+ } // aiShellLogic
setFeatureFlags: (
flags: string[],
variants: Record<string, boolean | string>
@@ -223,6 +228,8 @@ export const tasksLogic = kea<tasksLogicType>([
actions: [
featureFlagLogic,
['setFeatureFlags'],
+ aiShellLogic,
+ ['setPhaiViewMode'],
taskEventsLogic,
['taskDeleted'],
userLogic,
@@ -501,6 +508,13 @@ export const tasksLogic = kea<tasksLogicType>([
lemonToast.error(`Couldn't rename the task: ${loadErrorMessage(error, errorObject)}`)
},
setFeatureFlags: loadInitialTasks,
+ // The task list only loads on mount. A chat made on the legacy view has a task copy by the
+ // time the user switches, and the merged list shows it as that task once it is loaded.
+ setPhaiViewMode: ({ mode }) => {
+ if (mode === 'new') {
+ actions.loadTasks(values.taskListParams)
+ }
+ },
loadUserSuccess: () => {
if (cache.tasksLoadPending) {
loadTasksWhenReady()