: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
refactor(posthog-ai): register max tools on the shell logic (#126787)
Paul D'Ambraa18652bbbc01
diff --git a/.agents/skills/integrating-with-posthog-ai/references/injecting-context.md b/.agents/skills/integrating-with-posthog-ai/references/injecting-context.mdindex f4597768c7a3..b6a6acedeb61 100644--- a/.agents/skills/integrating-with-posthog-ai/references/injecting-context.md+++ b/.agents/skills/integrating-with-posthog-ai/references/injecting-context.md@@ -4,7 +4,7 @@ Tell the agent what the user is looking at. While a provider is registered, ever## The item shape-`AttachedContextItem` (`products/posthog_ai/frontend/types/contextTypes.ts`, exported from `api/types`):+`AttachedContextItem` (`frontend/src/layout/ai/attachedContext.ts`, owned by the app shell; import it from `~/layout/ai/attachedContext`):| Field | Meaning || -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |diff --git a/frontend/bin/layer-baseline.txt b/frontend/bin/layer-baseline.txtindex e4eb2c831918..7ac745aa8f11 100644--- a/frontend/bin/layer-baseline.txt+++ b/frontend/bin/layer-baseline.txt@@ -86,8 +86,6 @@ frontend/src/layout/today/TodaySupportPanel.tsx -> products/conversations/frontefrontend/src/layout/today/TodaySupportResponseTimes.tsx -> frontend/src/scenes/billing/billingLogic.tsxfrontend/src/layout/today/todayAiChatLogic.ts -> frontend/src/scenes/max/mainFocusUrl.tsfrontend/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.tsfrontend/src/layout/today/todayAnalyticsLogic.ts -> frontend/src/scenes/analytics/analyticsPinnedLogic.tsfrontend/src/layout/today/todayAnalyticsLogic.ts -> frontend/src/scenes/analytics/analyticsUtils.tsfrontend/src/layout/today/todayContextPanelLogic.ts -> frontend/src/scenes/notebooks/NotebookPanel/notebookPanelLogic.ts@@ -102,7 +100,6 @@ frontend/src/layout/today/todayObjectGlances.ts -> products/feature_flags/frontefrontend/src/layout/today/todayOrgMenuLogic.ts -> frontend/src/scenes/billing/billingLogic.tsxfrontend/src/layout/today/todayOrgMenuLogic.ts -> frontend/src/scenes/settings/organization/inviteLogic.tsfrontend/src/layout/today/todayPaneSearch.ts -> frontend/src/scenes/analytics/analyticsUtils.ts-frontend/src/layout/today/todayPanelChatSessionLogic.ts -> products/posthog_ai/frontend/api/logics.tsfrontend/src/layout/today/todayPanelTaskLogic.ts -> products/posthog_ai/frontend/api/logics.tsfrontend/src/layout/today/todayPreviewCards.ts -> frontend/src/scenes/library/libraryUtils.tsfrontend/src/layout/today/todayPreviewCards.ts -> products/posthog_ai/frontend/api/taskSource.ts@@ -250,7 +247,6 @@ frontend/src/lib/components/ChartFilter/ChartFilter.tsx -> frontend/src/scenes/ifrontend/src/lib/components/ChartFilter/ChartFilter.tsx -> frontend/src/scenes/insights/utils/queryUtils.tsfrontend/src/lib/components/ChartFilter/ChartFilter.tsx -> products/product_analytics/frontend/insights/chartAlternatives/ChartDisplayIcon.tsxfrontend/src/lib/components/ChartFilter/ChartFilter.tsx -> products/product_analytics/frontend/insights/chartAlternatives/chartDisplayOptions.ts-frontend/src/lib/components/CommandKSearch/commandKSearchLogic.tsx -> products/posthog_ai/frontend/api/logics.tsfrontend/src/lib/components/CyclotronJob/CyclotronJobInputs.tsx -> frontend/src/scenes/hog-functions/email-templater/EmailTemplater.tsxfrontend/src/lib/components/CyclotronJob/CyclotronJobInputsValidation.ts -> frontend/src/scenes/hog-functions/email-templater/types.tsfrontend/src/lib/components/CyclotronJob/integrations/integrationSetups.tsx -> frontend/src/scenes/integrations/aws-s3/AwsS3SetupModal.tsxdiff --git a/frontend/src/layout/ai/aiShellLogic.ts b/frontend/src/layout/ai/aiShellLogic.tsindex 5ac7474010ef..e87e19bbb3ed 100644--- a/frontend/src/layout/ai/aiShellLogic.ts+++ b/frontend/src/layout/ai/aiShellLogic.ts@@ -4,6 +4,7 @@ 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 { ToolRegistration } from 'scenes/max/max-constants'import type { PhaiViewMode } from '~/layout/ai/aiPanelIds'import type { PreflightStatus } from '~/types'@@ -20,10 +21,17 @@ export interface aiShellLogicValues {isMaxAvailable: booleanisPhaiSandboxFlagOn: booleanphaiViewMode: PhaiViewMode+ registeredToolMap: Record<string, ToolRegistration>}// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface aiShellLogicActions {+ deregisterTool: (key: string) => {+ key: string+ }+ registerTool: (tool: ToolRegistration) => {+ tool: ToolRegistration+ }setPhaiViewMode: (mode: PhaiViewMode) => {mode: PhaiViewMode}@@ -56,6 +64,8 @@ export const aiShellLogic = kea<aiShellLogicType>([})),actions({setPhaiViewMode: (mode: PhaiViewMode) => ({ mode }),+ registerTool: (tool: ToolRegistration) => ({ tool }),+ deregisterTool: (key: string) => ({ key }),}),reducers({// The user's chosen implementation, persisted per device. Defaults to the new surface so a@@ -67,6 +77,22 @@ export const aiShellLogic = kea<aiShellLogicType>([setPhaiViewMode: (_, { mode }) => mode,},],+ // The tools of the scene on screen. Scenes register here, not in the Max logics, so a tool registered+ // before the Max chunk loads is still there when it does.+ registeredToolMap: [+ {} as Record<string, ToolRegistration>,+ {+ registerTool: (state, { tool }) => ({+ ...state,+ [tool.identifier]: tool,+ }),+ deregisterTool: (state, { key }) => {+ const newState = { ...state }+ delete newState[key]+ return newState+ },+ },+ ],}),selectors({// On Cloud/dev a provider key is always present. On a self-hosted (hobby) instance Max onlydiff --git a/products/posthog_ai/frontend/types/contextTypes.ts b/frontend/src/layout/ai/attachedContext.tssimilarity index 100%rename from products/posthog_ai/frontend/types/contextTypes.tsrename to frontend/src/layout/ai/attachedContext.tsdiff --git a/products/posthog_ai/frontend/logics/attachedContextLogic.test.ts b/frontend/src/layout/ai/attachedContextLogic.test.tssimilarity index 97%rename from products/posthog_ai/frontend/logics/attachedContextLogic.test.tsrename to frontend/src/layout/ai/attachedContextLogic.test.tsindex 823687bacc6b..4c8bf710ed38 100644--- a/products/posthog_ai/frontend/logics/attachedContextLogic.test.ts+++ b/frontend/src/layout/ai/attachedContextLogic.test.ts@@ -1,10 +1,9 @@import { expectLogic } from 'kea-test-utils'+import type { AttachedContextItem } from '~/layout/ai/attachedContext'+import { attachedContextLogic } from '~/layout/ai/attachedContextLogic'import { initKeaTests } from '~/test/init'-import type { AttachedContextItem } from '../types/contextTypes'-import { attachedContextLogic } from './attachedContextLogic'-describe('attachedContextLogic', () => {let logic: ReturnType<typeof attachedContextLogic.build>diff --git a/products/posthog_ai/frontend/logics/attachedContextLogic.ts b/frontend/src/layout/ai/attachedContextLogic.tssimilarity index 98%rename from products/posthog_ai/frontend/logics/attachedContextLogic.tsrename to frontend/src/layout/ai/attachedContextLogic.tsindex 08eb7b4af3d5..e90496fd2207 100644--- a/products/posthog_ai/frontend/logics/attachedContextLogic.ts+++ b/frontend/src/layout/ai/attachedContextLogic.ts@@ -1,6 +1,6 @@import { MakeLogicType, actions, kea, path, reducers, selectors } from 'kea'-import { type AttachedContextItem, attachedContextItemKey } from '../types/contextTypes'+import { type AttachedContextItem, attachedContextItemKey } from '~/layout/ai/attachedContext'// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface attachedContextLogicValues {@@ -98,7 +98,7 @@ export type attachedContextLogicType = MakeLogicType<* across a task's whole resume chain.*/export const attachedContextLogic = kea<attachedContextLogicType>([- path(['products', 'posthog_ai', 'frontend', 'logics', 'attachedContextLogic']),+ path(['layout', 'ai', 'attachedContextLogic']),actions({/** Idempotent upsert — re-register the same `providerId` to update its items. */diff --git a/products/posthog_ai/frontend/logics/runnerPanelLogic.test.ts b/frontend/src/layout/ai/runnerPanelLogic.test.tssimilarity index 96%rename from products/posthog_ai/frontend/logics/runnerPanelLogic.test.tsrename to frontend/src/layout/ai/runnerPanelLogic.test.tsindex 8538017b7bc0..a75db501f912 100644--- a/products/posthog_ai/frontend/logics/runnerPanelLogic.test.ts+++ b/frontend/src/layout/ai/runnerPanelLogic.test.ts@@ -1,7 +1,6 @@+import { runnerPanelLogic } from '~/layout/ai/runnerPanelLogic'import { initKeaTests } from '~/test/init'-import { runnerPanelLogic } from './runnerPanelLogic'-describe('runnerPanelLogic', () => {let logic: ReturnType<typeof runnerPanelLogic.build>diff --git a/products/posthog_ai/frontend/logics/runnerPanelLogic.ts b/frontend/src/layout/ai/runnerPanelLogic.tssimilarity index 98%rename from products/posthog_ai/frontend/logics/runnerPanelLogic.tsrename to frontend/src/layout/ai/runnerPanelLogic.tsindex 94f9e2865f71..be2fc66f1902 100644--- a/products/posthog_ai/frontend/logics/runnerPanelLogic.ts+++ b/frontend/src/layout/ai/runnerPanelLogic.ts@@ -68,7 +68,7 @@ export type runnerPanelLogicType = MakeLogicType<>export const runnerPanelLogic = kea<runnerPanelLogicType>([- path(['products', 'posthog_ai', 'frontend', 'logics', 'runnerPanelLogic']),+ path(['layout', 'ai', 'runnerPanelLogic']),props({} as RunnerPanelLogicProps),// No `panelId` resolves to the same 'scene' key `taskTrackerSceneLogic` falls back to, so an unkeyed// caller pairs with the scene's own singleton.diff --git a/frontend/src/layout/today/todayAiChatLogic.ts b/frontend/src/layout/today/todayAiChatLogic.tsindex cfbf4c168284..db0213770657 100644--- a/frontend/src/layout/today/todayAiChatLogic.ts+++ b/frontend/src/layout/today/todayAiChatLogic.ts@@ -15,13 +15,12 @@ import {type PhaiViewMode,} from '~/layout/ai/aiPanelIds'import { aiShellLogic } from '~/layout/ai/aiShellLogic'+import type { AttachedContextItem } from '~/layout/ai/attachedContext'+import { attachedContextLogic } from '~/layout/ai/attachedContextLogic'+import { type ActiveCreation, runnerPanelLogic } from '~/layout/ai/runnerPanelLogic'import { sidePanelStateLogic } from '~/layout/navigation-3000/sidepanel/sidePanelStateLogic'import { SidePanelTab } from '~/types'-import { type ActiveCreation, runnerPanelLogic } from 'products/posthog_ai/frontend/api/logics'-import { attachedContextLogic } from 'products/posthog_ai/frontend/logics/attachedContextLogic'-import type { AttachedContextItem } from 'products/posthog_ai/frontend/types/contextTypes'-import type { TaskActivityDTOApi } from '../../../../products/tasks/frontend/generated/api.schemas'import { todayContextPanelLogic } from './todayContextPanelLogic'import { TodayPanelChatTask, runnerCreationFor } from './todayPanelChat'diff --git a/frontend/src/layout/today/todayPanelChat.ts b/frontend/src/layout/today/todayPanelChat.tsindex 57e28b5b115a..42c7a7746333 100644--- a/frontend/src/layout/today/todayPanelChat.ts+++ b/frontend/src/layout/today/todayPanelChat.ts@@ -1,4 +1,4 @@-import type { ActiveCreation } from 'products/posthog_ai/frontend/api/logics'+import type { ActiveCreation } from '~/layout/ai/runnerPanelLogic'/** A task the PostHog AI panel can show. The panel streams one run, so it needs the run, not only the task. */export interface TodayPanelChatTask {diff --git a/frontend/src/layout/today/todayPanelChatSessionLogic.ts b/frontend/src/layout/today/todayPanelChatSessionLogic.tsindex 93a9b6fe0ae2..329623d6c384 100644--- a/frontend/src/layout/today/todayPanelChatSessionLogic.ts+++ b/frontend/src/layout/today/todayPanelChatSessionLogic.ts@@ -1,8 +1,7 @@import { MakeLogicType, actions, afterMount, connect, kea, listeners, path, reducers } from 'kea'import { MAX_SIDE_PANEL_ID } from '~/layout/ai/aiPanelIds'--import { type ActiveCreation, runnerPanelLogic } from 'products/posthog_ai/frontend/api/logics'+import { type ActiveCreation, runnerPanelLogic } from '~/layout/ai/runnerPanelLogic'import { TodayPanelChatTask, runnerCreationFor } from './todayPanelChat'import { projectSessionKey, readSessionValue, writeSessionValue } from './todaySessionStorage'diff --git a/frontend/src/lib/components/CommandKSearch/commandKSearchLogic.tsx b/frontend/src/lib/components/CommandKSearch/commandKSearchLogic.tsxindex 87721277e49b..713b8d3c849c 100644--- a/frontend/src/lib/components/CommandKSearch/commandKSearchLogic.tsx+++ b/frontend/src/lib/components/CommandKSearch/commandKSearchLogic.tsx@@ -27,6 +27,7 @@ import { teamLogic } from 'scenes/teamLogic'import { userLogic } from 'scenes/userLogic'import { MAX_SIDE_PANEL_ID } from '~/layout/ai/aiPanelIds'+import { runnerPanelLogic } from '~/layout/ai/runnerPanelLogic'import { sidePanelStateLogic } from '~/layout/navigation-3000/sidepanel/sidePanelStateLogic'import { groupsModel } from '~/models/groupsModel'import { membersLogic } from '~/models/membersLogic'@@ -34,8 +35,6 @@ import { recentItemsModel } from '~/models/recentItemsModel'import { FileSystemEntry } from '~/queries/schema/schema-general'import { SidePanelTab } from '~/types'-import { runnerPanelLogic } from 'products/posthog_ai/frontend/api/logics'-import type { Noun } from '../../../models/groupsModel'import type { GroupType, GroupTypeIndex, OrganizationMemberType, UserType } from '../../../types'import type { FeatureFlagsSet } from '../../logic/featureFlagLogic'diff --git a/frontend/src/scenes/activity/activityAgentContext.ts b/frontend/src/scenes/activity/activityAgentContext.tsindex a8fc5307d12f..865add3f74ec 100644--- a/frontend/src/scenes/activity/activityAgentContext.ts+++ b/frontend/src/scenes/activity/activityAgentContext.ts@@ -1,8 +1,7 @@+import { AttachedContextItem } from '~/layout/ai/attachedContext'import { DataTableNode, Node } from '~/queries/schema/schema-general'import { ActivityTab, AnyPropertyFilter } from '~/types'-import { AttachedContextItem } from 'products/posthog_ai/frontend/api/types'-// Closing the chip must also detach the instruction it stands for, so they share a dismiss group.const EXPLORE_DISMISS_GROUP = 'activity-explore-query'const LIVE_DISMISS_GROUP = 'activity-live-filters'diff --git a/frontend/src/scenes/feature-flags/featureFlagAiContext.ts b/frontend/src/scenes/feature-flags/featureFlagAiContext.tsindex fe32c782d838..b518b976833b 100644--- a/frontend/src/scenes/feature-flags/featureFlagAiContext.ts+++ b/frontend/src/scenes/feature-flags/featureFlagAiContext.ts@@ -1,7 +1,7 @@+import type { AttachedContextItem } from '~/layout/ai/attachedContext'import { FeatureFlagType } from '~/types'import { isV1FeatureFlagConfig } from 'products/feature_flags/frontend/featureFlagConfigFormat'-import type { AttachedContextItem } from 'products/posthog_ai/frontend/api/types'// The backend rejects a text attachment longer than this and fails the whole send with a 400// (MAX_TEXT_LENGTH in products/posthog_ai/backend/context_wrapper.py), so an oversized flag has todiff --git a/frontend/src/scenes/max/Max.tsx b/frontend/src/scenes/max/Max.tsxindex c1fd457b8bf8..827a9b5b0743 100644--- a/frontend/src/scenes/max/Max.tsx+++ b/frontend/src/scenes/max/Max.tsx@@ -26,6 +26,7 @@ import { SceneExport } from 'scenes/sceneTypes'import { urls } from 'scenes/urls'import { MAX_SIDE_PANEL_ID, REPORT_AI_PANEL, SCOUT_AI_PANEL, SIDE_PANEL_PANEL_ID } from '~/layout/ai/aiPanelIds'+import { runnerPanelLogic } from '~/layout/ai/runnerPanelLogic'import { SidePanelPaneHeader } from '~/layout/navigation-3000/sidepanel/components/SidePanelPaneHeader'import { SidePanelContentContainer } from '~/layout/navigation-3000/sidepanel/SidePanelContentContainer'import { sidePanelLogic } from '~/layout/navigation-3000/sidepanel/sidePanelLogic'@@ -35,7 +36,6 @@ import { SceneTitleSection } from '~/layout/scenes/components/SceneTitleSection'import { todayShellLogic } from '~/layout/today/todayShellLogic'import { SidePanelTab } from '~/types'-import { runnerPanelLogic } from 'products/posthog_ai/frontend/api/logics'import { DebugLogsMenu } from 'products/posthog_ai/frontend/api/primitives'import { AiFirstMaxInstance } from './components/AiFirstMaxInstance'diff --git a/frontend/src/scenes/max/aiFirstCreate/AiFirstCreateScene.tsx b/frontend/src/scenes/max/aiFirstCreate/AiFirstCreateScene.tsxindex bf72f033679f..43a168ce5504 100644--- a/frontend/src/scenes/max/aiFirstCreate/AiFirstCreateScene.tsx+++ b/frontend/src/scenes/max/aiFirstCreate/AiFirstCreateScene.tsx@@ -8,8 +8,8 @@ import { cn } from 'lib/utils/css-classes'import { SuggestionCard } from 'scenes/max/components/SuggestionCard'import { MAX_SIDE_PANEL_ID } from '~/layout/ai/aiPanelIds'+import { runnerPanelLogic } from '~/layout/ai/runnerPanelLogic'-import { runnerPanelLogic } from 'products/posthog_ai/frontend/api/logics'import { SidePanelRunner } from 'products/posthog_ai/frontend/api/runner'import { AiFirstHandoffLogicProps, aiFirstHandoffLogic } from './aiFirstHandoffLogic'diff --git a/frontend/src/scenes/max/aiFirstCreate/aiFirstHandoffLogic.test.ts b/frontend/src/scenes/max/aiFirstCreate/aiFirstHandoffLogic.test.tsindex d45c7ed12d05..7f7578d61ae3 100644--- a/frontend/src/scenes/max/aiFirstCreate/aiFirstHandoffLogic.test.ts+++ b/frontend/src/scenes/max/aiFirstCreate/aiFirstHandoffLogic.test.ts@@ -6,12 +6,13 @@ import { removeProjectIdIfPresent } from 'lib/utils/kea-router'import { maxMocks } from 'scenes/max/testUtils'import { MAX_SIDE_PANEL_ID } from '~/layout/ai/aiPanelIds'+import { runnerPanelLogic } from '~/layout/ai/runnerPanelLogic'import { sidePanelStateLogic } from '~/layout/navigation-3000/sidepanel/sidePanelStateLogic'import { useMocks } from '~/mocks/jest'import { initKeaTests } from '~/test/init'import { SidePanelTab } from '~/types'-import { composerSeedLogic, runnerPanelLogic, toolStreamEventsLogic } from 'products/posthog_ai/frontend/api/logics'+import { composerSeedLogic, toolStreamEventsLogic } from 'products/posthog_ai/frontend/api/logics'import type { ToolStreamEvent } from 'products/posthog_ai/frontend/api/types'import { AiFirstHandoffLogicProps, aiFirstHandoffLogic } from './aiFirstHandoffLogic'diff --git a/frontend/src/scenes/max/aiFirstCreate/aiFirstHandoffLogic.ts b/frontend/src/scenes/max/aiFirstCreate/aiFirstHandoffLogic.tsindex f50a9ac34d8e..6769e4d209e1 100644--- a/frontend/src/scenes/max/aiFirstCreate/aiFirstHandoffLogic.ts+++ b/frontend/src/scenes/max/aiFirstCreate/aiFirstHandoffLogic.ts@@ -5,6 +5,8 @@ import posthog from 'posthog-js'import { lemonToast } from 'lib/lemon-ui/LemonToast'import { MAX_SIDE_PANEL_ID } from '~/layout/ai/aiPanelIds'+import { runnerPanelLogic } from '~/layout/ai/runnerPanelLogic'+import type { ActiveCreation } from '~/layout/ai/runnerPanelLogic'import { sidePanelStateLogic } from '~/layout/navigation-3000/sidepanel/sidePanelStateLogic'import { SidePanelTab } from '~/types'@@ -12,10 +14,9 @@ import {composerSeedLogic,getToolOutputRecord,resolveToolCall,- runnerPanelLogic,toolStreamEventsLogic,} from 'products/posthog_ai/frontend/api/logics'-import type { ActiveCreation, ComposerSeed } from 'products/posthog_ai/frontend/api/logics'+import type { ComposerSeed } from 'products/posthog_ai/frontend/api/logics'import type { ToolStreamEvent } from 'products/posthog_ai/frontend/api/types'export interface AiFirstHandoffLogicProps {diff --git a/frontend/src/scenes/max/mainFocusUrl.ts b/frontend/src/scenes/max/mainFocusUrl.tsindex d5504086c5fd..b3e4bf471456 100644--- a/frontend/src/scenes/max/mainFocusUrl.ts+++ b/frontend/src/scenes/max/mainFocusUrl.ts@@ -2,7 +2,7 @@ import { combineUrl } from 'kea-router'import { urls } from 'scenes/urls'-import type { ActiveCreation } from 'products/posthog_ai/frontend/api/logics'+import type { ActiveCreation } from '~/layout/ai/runnerPanelLogic'export interface MainFocusUrlInput {/** Whether the panel is running the new PostHog AI view rather than the legacy Max chat. */diff --git a/frontend/src/scenes/max/maxGlobalLogic.tsx b/frontend/src/scenes/max/maxGlobalLogic.tsxindex 4ba2becaf32c..1f29ffede06d 100644--- a/frontend/src/scenes/max/maxGlobalLogic.tsx+++ b/frontend/src/scenes/max/maxGlobalLogic.tsx@@ -92,6 +92,7 @@ export interface maxGlobalLogicValues {isMaxAvailable: boolean // aiShellLogicisPhaiSandboxFlagOn: boolean // aiShellLogicphaiViewMode: PhaiViewMode // aiShellLogic+ registeredToolMap: Record<string, ToolRegistration> // aiShellLogicfeatureFlags: FeatureFlagsSet // featureFlagLogiccurrentOrganization: OrganizationType | null // organizationLogicsceneConfig: SceneConfig | null // sceneLogic@@ -106,7 +107,6 @@ export interface maxGlobalLogicValues {editInsightToolRegistered: trueisOrganizationCreatedRecently: booleanliabilityNoticeDismissed: boolean- registeredToolMap: Record<string, ToolRegistration>shouldShowLiabilityNotice: booleantoolMap: {[x: string]: ToolRegistration@@ -130,6 +130,12 @@ export interface maxGlobalLogicActions {requestAiAccess: () => {value: true} // aiConsentLogic+ deregisterTool: (key: string) => {+ key: string+ } // aiShellLogic+ registerTool: (tool: ToolRegistration) => {+ tool: ToolRegistration+ } // aiShellLogicsetPhaiViewMode: (mode: PhaiViewMode) => {mode: PhaiViewMode} // aiShellLogic@@ -167,9 +173,6 @@ export interface maxGlobalLogicActions {deleteConversation: (id: string) => {id: string}- deregisterTool: (key: string) => {- key: string- }dismissLiabilityNotice: () => {value: true}@@ -221,9 +224,6 @@ export interface maxGlobalLogicActions {prependOrReplaceConversation: (conversation: Conversation | ConversationDetail) => {conversation: Conversation | ConversationDetail}- registerTool: (tool: ToolRegistration) => {- tool: ToolRegistration- }}// Generated by kea-typegen. Update if you're an agent, ignore if you're human.@@ -260,7 +260,7 @@ export const maxGlobalLogic = kea<maxGlobalLogicType>([connect(() => ({values: [aiShellLogic,- ['effectivePhaiView', 'isMaxAvailable', 'isPhaiSandboxFlagOn', 'phaiViewMode'],+ ['effectivePhaiView', 'isMaxAvailable', 'isPhaiSandboxFlagOn', 'phaiViewMode', 'registeredToolMap'],organizationLogic,['currentOrganization'],sceneLogic,@@ -288,15 +288,13 @@ export const maxGlobalLogic = kea<maxGlobalLogicType>([aiConsentLogic,['acceptDataProcessing', 'dismissDataProcessing', 'requestAiAccess'],aiShellLogic,- ['setPhaiViewMode'],+ ['setPhaiViewMode', 'registerTool', 'deregisterTool'],],})),actions({openSidePanelMax: (conversationId?: string) => ({ conversationId }),openSidePanelMaxWithTaskBind: (taskId: string) => ({ taskId }),askSidePanelMax: (prompt: string) => ({ prompt }),- registerTool: (tool: ToolRegistration) => ({ tool }),- deregisterTool: (key: string) => ({ key }),prependOrReplaceConversation: (conversation: ConversationDetail | Conversation) => ({ conversation }),deleteConversation: (id: string) => ({ id }),dismissLiabilityNotice: true,@@ -349,20 +347,6 @@ export const maxGlobalLogic = kea<maxGlobalLogicType>([return mergeConversationHistory(state, conversation)},},- registeredToolMap: [- {} as Record<string, ToolRegistration>,- {- registerTool: (state, { tool }) => ({- ...state,- [tool.identifier]: tool,- }),- deregisterTool: (state, { key }) => {- const newState = { ...state }- delete newState[key]- return newState- },- },- ],liabilityNoticeDismissed: [false,{ persist: true, storageKey: AI_LIABILITY_NOTICE_STORAGE_KEY },diff --git a/frontend/src/scenes/max/maxLogic.test.ts b/frontend/src/scenes/max/maxLogic.test.tsindex 26687191f49a..376d934592ff 100644--- a/frontend/src/scenes/max/maxLogic.test.ts+++ b/frontend/src/scenes/max/maxLogic.test.ts@@ -8,13 +8,14 @@ import { featureFlagLogic } from 'lib/logic/featureFlagLogic'import { urls } from 'scenes/urls'import { REPORT_AI_PANEL, SCOUT_AI_PANEL, SIDE_PANEL_PANEL_ID } from '~/layout/ai/aiPanelIds'+import { runnerPanelLogic } from '~/layout/ai/runnerPanelLogic'import { sidePanelStateLogic } from '~/layout/navigation-3000/sidepanel/sidePanelStateLogic'import { useMocks } from '~/mocks/jest'import { AgentMode } from '~/queries/schema/schema-assistant-messages'import { initKeaTests } from '~/test/init'import { ConversationDetail, SidePanelTab } from '~/types'-import { composerSeedLogic, runnerPanelLogic } from 'products/posthog_ai/frontend/api/logics'+import { composerSeedLogic } from 'products/posthog_ai/frontend/api/logics'import { maxContextLogic } from './maxContextLogic'import { maxGlobalLogic } from './maxGlobalLogic'diff --git a/frontend/src/scenes/max/maxLogic.tsx b/frontend/src/scenes/max/maxLogic.tsxindex 37614135df21..cf867b5fa207 100644--- a/frontend/src/scenes/max/maxLogic.tsx+++ b/frontend/src/scenes/max/maxLogic.tsx@@ -15,6 +15,7 @@ import { Scene } from 'scenes/sceneTypes'import { urls } from 'scenes/urls'import { REPORT_AI_PANEL, SCOUT_AI_PANEL, SIDE_PANEL_PANEL_ID, type PhaiViewMode } from '~/layout/ai/aiPanelIds'+import { runnerPanelLogic } from '~/layout/ai/runnerPanelLogic'import { sidePanelStateLogic } from '~/layout/navigation-3000/sidepanel/sidePanelStateLogic'import { iconForType } from '~/layout/panel-layout/ProjectTree/defaultTree'import { productUrls } from '~/products'@@ -28,12 +29,7 @@ import {SidePanelTab,} from '~/types'-import {- type ComposerSeed,- composerSeedLogic,- runnerPanelLogic,- taskLogic,-} from 'products/posthog_ai/frontend/api/logics'+import { type ComposerSeed, composerSeedLogic, taskLogic } from 'products/posthog_ai/frontend/api/logics'import type { ToolRegistration } from './max-constants'import { PENDING_AI_PROMPT_KEY } from './max-storage-keys'diff --git a/frontend/src/scenes/max/maxThreadLogic.test.ts b/frontend/src/scenes/max/maxThreadLogic.test.tsindex 69609938f5a9..1cbba2080f5b 100644--- a/frontend/src/scenes/max/maxThreadLogic.test.ts+++ b/frontend/src/scenes/max/maxThreadLogic.test.ts@@ -18,6 +18,7 @@ import { sceneLogic } from 'scenes/sceneLogic'import { Scene } from 'scenes/sceneTypes'import { urls } from 'scenes/urls'+import { attachedContextLogic } from '~/layout/ai/attachedContextLogic'import { sidePanelStateLogic } from '~/layout/navigation-3000/sidepanel/sidePanelStateLogic'import { useMocks } from '~/mocks/jest'import { insightsModel } from '~/models/insightsModel'@@ -42,7 +43,7 @@ import {PendingApproval,} from '~/types'-import { attachedContextLogic, runStreamLogic } from 'products/posthog_ai/frontend/api/logics'+import { runStreamLogic } from 'products/posthog_ai/frontend/api/logics'import * as tasksApi from 'products/tasks/frontend/generated/api'import { TaskRunDetailDTOApi, TaskRuntimeEnumApi } from 'products/tasks/frontend/generated/api.schemas'diff --git a/frontend/src/scenes/max/maxThreadLogic.tsx b/frontend/src/scenes/max/maxThreadLogic.tsxindex bc6cbe38d5ea..3ca9870a2e1c 100644--- a/frontend/src/scenes/max/maxThreadLogic.tsx+++ b/frontend/src/scenes/max/maxThreadLogic.tsx@@ -37,6 +37,7 @@ import { urls } from 'scenes/urls'import { userLogic } from 'scenes/userLogic'import { SIDE_PANEL_PANEL_ID } from '~/layout/ai/aiPanelIds'+import { attachedContextLogic } from '~/layout/ai/attachedContextLogic'import { sidePanelStateLogic } from '~/layout/navigation-3000/sidepanel/sidePanelStateLogic'import {AgentMode,@@ -68,7 +69,6 @@ import {} from '~/types'import {- attachedContextLogic,getRandomThinkingMessage,getWebSearchResultsByToolUseId,isTerminalRunStatus,diff --git a/frontend/src/scenes/max/maxToolOpener.ts b/frontend/src/scenes/max/maxToolOpener.tsnew file mode 100644index 000000000000..d4718e29f640--- /dev/null+++ b/frontend/src/scenes/max/maxToolOpener.ts@@ -0,0 +1,41 @@+import React from 'react'++import { IconWrench } from '@posthog/icons'++import { MAX_SIDE_PANEL_ID } from '~/layout/ai/aiPanelIds'+import type { PhaiViewMode } from '~/layout/ai/aiPanelIds'+import { runnerPanelLogic } from '~/layout/ai/runnerPanelLogic'+import { todayAiChatLogic } from '~/layout/today/todayAiChatLogic'++import { sidePanelMaxLogic } from './maxLogic'+import { createSuggestionGroup } from './utils'++/** Starts a new side panel chat, so the tool's prompt does not land in an existing session. */+export function startToolChat({+ todayRailNav,+ effectivePhaiView,+}: {+ todayRailNav: boolean+ effectivePhaiView: PhaiViewMode+}): void {+ if (todayRailNav) {+ // The Today panel can show a task chat too, so its own logic starts the new chat.+ const unmount = todayAiChatLogic.mount()+ todayAiChatLogic.actions.startNewChatForTool()+ unmount()+ } else if (effectivePhaiView === 'new') {+ const runner = runnerPanelLogic({ panelId: MAX_SIDE_PANEL_ID })+ const unmount = runner.mount()+ runner.actions.clearActiveCreation()+ runner.actions.setHistoryExpanded(false)+ unmount()+ } else {+ sidePanelMaxLogic().actions.startNewConversation()+ }+}++export function showToolSuggestions(toolName: string, suggestions: string[]): void {+ sidePanelMaxLogic().actions.setActiveGroup(+ createSuggestionGroup(toolName, React.createElement(IconWrench), suggestions)+ )+}diff --git a/frontend/src/scenes/max/useMaxTool.test.tsx b/frontend/src/scenes/max/useMaxTool.test.tsxindex f0bd397f11e6..7be58486c570 100644--- a/frontend/src/scenes/max/useMaxTool.test.tsx+++ b/frontend/src/scenes/max/useMaxTool.test.tsx@@ -4,17 +4,20 @@ import { expectLogic } from 'kea-test-utils'import api from 'lib/api'import { FEATURE_FLAGS } from 'lib/constants'+import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'import { featureFlagLogic } from 'lib/logic/featureFlagLogic'+import * as retryImportModule from 'lib/utils/retryImport'import { urls } from 'scenes/urls'import { MAX_SIDE_PANEL_ID, SIDE_PANEL_PANEL_ID } from '~/layout/ai/aiPanelIds'+import { aiShellLogic } from '~/layout/ai/aiShellLogic'+import { attachedContextLogic } from '~/layout/ai/attachedContextLogic'+import { runnerPanelLogic } from '~/layout/ai/runnerPanelLogic'import { sidePanelStateLogic } from '~/layout/navigation-3000/sidepanel/sidePanelStateLogic'import { todayPanelChatSessionLogic } from '~/layout/today/todayPanelChatSessionLogic'import { initKeaTests } from '~/test/init'import { SidePanelTab } from '~/types'-import { attachedContextLogic, runnerPanelLogic } from 'products/posthog_ai/frontend/api/logics'-import { maxGlobalLogic } from './maxGlobalLogic'import { maxLogic } from './maxLogic'import { UseMaxToolReturn, useMaxTool } from './useMaxTool'@@ -23,17 +26,20 @@ function TestMaxTool({identifier = 'read_data',context,active = true,+ initialMaxPrompt,onRender,}: {identifier?: 'read_data' | 'create_experiment'context: Record<string, unknown>active?: boolean+ initialMaxPrompt?: stringonRender?: (result: UseMaxToolReturn) => void}): null {const result = useMaxTool({identifier,context,active,+ initialMaxPrompt,suggestions: ['Show me signups'],})onRender?.(result)@@ -57,7 +63,7 @@ describe('useMaxTool', () => {})it('updates the registered tool context without deregistering between updates', () => {- const deregisterTool = jest.spyOn(logic.actions, 'deregisterTool')+ const deregisterTool = jest.spyOn(aiShellLogic.actions, 'deregisterTool')const { rerender, unmount } = render(<TestMaxTool context={{ query: 'select 1' }} />)expect(logic.values.registeredToolMap.read_data?.context).toEqual({ query: 'select 1' })@@ -82,11 +88,98 @@ describe('useMaxTool', () => {expect(listConversations).not.toHaveBeenCalled()})- it('opens the side panel on a new chat with the tool suggestions', () => {+ // Scenes register their tools on the light shell store, before the Max logics load.+ it('keeps a tool registered before the Max logics mount', () => {+ logic.unmount()+ render(<TestMaxTool context={{ query: 'select 1' }} />)++ logic.mount()++ expect(logic.values.toolMap.read_data?.context).toEqual({ query: 'select 1' })+ })++ // The first open waits for the Max chunk. The click must still open the panel with the tool's prompt,+ // and the chat must get the page's context as it is when the chunk arrives, not as it was at the click.+ it.each([+ {+ change: 'the scene unmounts',+ whileLoading: (view: ReturnType<typeof render>): void => view.unmount(),+ expectedToolContext: [],+ },+ {+ change: 'the tool context changes',+ whileLoading: (view: ReturnType<typeof render>): void =>+ view.rerender(<TestMaxTool context={{ query: 'select 2' }} initialMaxPrompt="Why did signups drop?" />),+ expectedToolContext: [JSON.stringify({ query: 'select 2' })],+ },+ {+ change: 'the tool turns inactive',+ whileLoading: (view: ReturnType<typeof render>): void =>+ view.rerender(<TestMaxTool context={{ query: 'select 1' }} active={false} />),+ expectedToolContext: [],+ },+ ])(+ 'opens the panel with the prompt and current context when $change before the chunk arrives',+ async ({ whileLoading, expectedToolContext }) => {+ featureFlagLogic.actions.setFeatureFlags([], { [FEATURE_FLAGS.PHAI_SANDBOX_MODE]: true })+ const unmountContextStore = attachedContextLogic.mount()+ let openMax: UseMaxToolReturn['openMax'] = null+ const view = render(+ <TestMaxTool+ context={{ query: 'select 1' }}+ initialMaxPrompt="Why did signups drop?"+ onRender={(result) => (openMax = result.openMax)}+ />+ )++ let opening: Promise<void> | undefined+ act(() => {+ opening = openMax?.()+ })+ whileLoading(view)+ await act(async () => {+ await opening+ })++ expect(sidePanelStateLogic.values).toMatchObject({+ selectedTab: SidePanelTab.Max,+ selectedTabOptions: 'Why did signups drop?',+ })+ expect(+ attachedContextLogic.values.contextItems+ .filter((item) => item.type === 'tool_context')+ .map((item) => item.value)+ ).toEqual(expectedToolContext)+ unmountContextStore()+ }+ )++ it('tells the person to reload when the Max chunk fails to load', async () => {+ jest.spyOn(retryImportModule, 'retryImport').mockRejectedValue(+ new Error('Failed to fetch dynamically imported module')+ )+ const showError = jest.spyOn(lemonToast, 'error')let openMax: UseMaxToolReturn['openMax'] = nullrender(<TestMaxTool context={{ query: 'select 1' }} onRender={(result) => (openMax = result.openMax)} />)- act(() => openMax?.())+ await act(async () => {+ await expect(openMax?.()).resolves.toBeUndefined()+ })++ expect(showError).toHaveBeenCalledWith(+ expect.any(String),+ expect.objectContaining({ button: expect.objectContaining({ label: 'Reload' }) })+ )+ expect(sidePanelStateLogic.values.sidePanelOpen).toBe(false)+ })++ it('opens the side panel on a new chat with the tool suggestions', async () => {+ let openMax: UseMaxToolReturn['openMax'] = null+ render(<TestMaxTool context={{ query: 'select 1' }} onRender={(result) => (openMax = result.openMax)} />)++ await act(async () => {+ await openMax?.()+ })expect(sidePanelStateLogic.values.selectedTab).toEqual(SidePanelTab.Max)expect(maxLogic({ panelId: SIDE_PANEL_PANEL_ID }).values.activeSuggestionGroup?.suggestions).toEqual([@@ -98,7 +191,7 @@ describe('useMaxTool', () => {{ nav: 'Today', chat: 'task', todayRailNav: true, hintQueued: true, taskId: 'task-1' },{ nav: 'Today', chat: 'draft', todayRailNav: true, hintQueued: true, taskId: undefined },{ nav: 'classic', chat: 'task', todayRailNav: false, hintQueued: false, taskId: 'task-1' },- ])('replaces an open $nav panel $chat chat with a new chat', ({ todayRailNav, hintQueued, taskId }) => {+ ])('replaces an open $nav panel $chat chat with a new chat', async ({ todayRailNav, hintQueued, taskId }) => {featureFlagLogic.actions.setFeatureFlags([], {[FEATURE_FLAGS.TODAY_RAIL_NAV]: todayRailNav,[FEATURE_FLAGS.PHAI_SANDBOX_MODE]: true,@@ -110,7 +203,9 @@ describe('useMaxTool', () => {let openMax: UseMaxToolReturn['openMax'] = nullrender(<TestMaxTool context={{ query: 'select 1' }} onRender={(result) => (openMax = result.openMax)} />)- act(() => openMax?.())+ await act(async () => {+ await openMax?.()+ })expect(runner.values.activeCreation).toBeNull()expect(panelChat.values.previousChatsHintQueued).toBe(hintQueued)@@ -122,7 +217,7 @@ describe('useMaxTool', () => {panelChat.unmount()})- it('attaches only the last clicked tool context, keeps it current, and releases it once a task opens', () => {+ it('attaches only the last clicked tool context, keeps it current, and releases it once a task opens', async () => {featureFlagLogic.actions.setFeatureFlags([], { [FEATURE_FLAGS.PHAI_SANDBOX_MODE]: true })const unmountContextStore = attachedContextLogic.mount()const openers: Record<string, UseMaxToolReturn['openMax']> = {}@@ -142,8 +237,12 @@ describe('useMaxTool', () => {.map((item) => item.value)const { rerender, unmount } = render(tools('select 1'))- act(() => openers.experiment?.())- act(() => openers.sql?.())+ await act(async () => {+ await openers.experiment?.()+ })+ await act(async () => {+ await openers.sql?.()+ })expect(toolContextValues()).toEqual([JSON.stringify({ query: 'select 1' })])rerender(tools('select 2'))@@ -163,7 +262,9 @@ describe('useMaxTool', () => {act(() => runner.actions.clearActiveCreation())expect(attachedContextLogic.values.contextItems).toEqual([])- act(() => openers.sql?.())+ await act(async () => {+ await openers.sql?.()+ })rerender(<TestMaxToolcontext={{ query: 'select 2' }}diff --git a/frontend/src/scenes/max/useMaxTool.ts b/frontend/src/scenes/max/useMaxTool.tsindex b774eb8181a6..a2791cf5272c 100644--- a/frontend/src/scenes/max/useMaxTool.ts+++ b/frontend/src/scenes/max/useMaxTool.ts@@ -1,28 +1,27 @@import { useActions, useValues } from 'kea'import { router } from 'kea-router'-import React, { useEffect, useMemo, useRef } from 'react'--import { IconWrench } from '@posthog/icons'+import { useEffect, useMemo, useRef } from 'react'import { FEATURE_FLAGS } from 'lib/constants'+import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'import { featureFlagLogic } from 'lib/logic/featureFlagLogic'import { uuid } from 'lib/utils/dom'import { removeProjectIdIfPresent } from 'lib/utils/kea-router'+import { retryImport } from 'lib/utils/retryImport'+import { reloadAfterChunkLoadError } from 'lib/utils/stableChunks'import { sceneLogic } from 'scenes/sceneLogic'import { sceneConfigurations } from 'scenes/scenes'import { MAX_SIDE_PANEL_ID } from '~/layout/ai/aiPanelIds'+import { aiShellLogic } from '~/layout/ai/aiShellLogic'+import { attachedContextItemKey } from '~/layout/ai/attachedContext'+import type { AttachedContextItem } from '~/layout/ai/attachedContext'+import { attachedContextLogic } from '~/layout/ai/attachedContextLogic'+import { runnerPanelLogic } from '~/layout/ai/runnerPanelLogic'import { sidePanelLogic } from '~/layout/navigation-3000/sidepanel/sidePanelLogic'-import { todayAiChatLogic } from '~/layout/today/todayAiChatLogic'import { SidePanelTab } from '~/types'-import { attachedContextItemKey, attachedContextLogic, runnerPanelLogic } from 'products/posthog_ai/frontend/api/logics'-import type { AttachedContextItem } from 'products/posthog_ai/frontend/api/types'-import { ToolDefinition, ToolRegistration, getToolDefinition } from './max-constants'-import { maxGlobalLogic } from './maxGlobalLogic'-import { sidePanelMaxLogic } from './maxLogic'-import { createSuggestionGroup } from './utils'export interface UseMaxToolOptions extends Omit<ToolRegistration, 'name' | 'description'> {/** Whether MaxTool functionality is active. When false, tool is not registered. */@@ -40,10 +39,14 @@ export interface UseMaxToolReturn {definition: ToolDefinition | null/** Whether the Max side panel is currently open */isMaxOpen: boolean- /** Function to open Max with the optional initialMaxPrompt and suggestions - null if the tool is inactive */- openMax: (() => void) | null+ /** Function to open Max with the optional initialMaxPrompt and suggestions - null if the tool is inactive.+ * It resolves once the panel is open: the first call waits for the Max chunk. */+ openMax: (() => Promise<void>) | null}+// The chat logics stay out of the shell chunk. The shell loads them on the first open.+const loadMaxToolOpener = (): Promise<typeof import('./maxToolOpener')> => retryImport(() => import('./maxToolOpener'))+const MAX_TOOL_CONTEXT_LENGTH = 4096const TOOL_PAGE_CONTEXT_PROVIDER_ID = 'max-tool-page'let toolPageContextOwner: string | null = null@@ -77,7 +80,8 @@ export function useMaxTool({initialMaxPrompt,onMaxOpen,}: UseMaxToolOptions): UseMaxToolReturn {- const { registerTool, deregisterTool } = useActions(maxGlobalLogic)+ const { registerTool, deregisterTool } = useActions(aiShellLogic)+ const { effectivePhaiView } = useValues(aiShellLogic)const { registerContext, deregisterContext, undismissContext } = useActions(attachedContextLogic)const { openSidePanel } = useActions(sidePanelLogic)const { sidePanelOpen, selectedTab } = useValues(sidePanelLogic)@@ -92,6 +96,10 @@ export function useMaxTool({const isMaxOpen = sidePanelOpen && selectedTab === SidePanelTab.Maxconst activeIdentifierRef = useRef<string | null>(null)const hookIdRef = useRef<string>(uuid())+ const unmountedRef = useRef(false)+ // openMax reads these after the chunk loads, so a change made meanwhile decides what reaches the chat.+ const latestRef = useRef({ context, active })+ latestRef.current = { context, active }const contextKey = useMemo(() => JSON.stringify(context), [context])useEffect(() => {@@ -156,7 +164,9 @@ export function useMaxTool({useEffect(() => {const hookId = hookIdRef.current+ unmountedRef.current = falsereturn (): void => {+ unmountedRef.current = trueif (activeIdentifierRef.current) {deregisterTool(activeIdentifierRef.current)activeIdentifierRef.current = null@@ -173,34 +183,33 @@ export function useMaxTool({isMaxOpen,openMax: !active? null- : (): void => {- const { startNewConversation, setActiveGroup } = sidePanelMaxLogic().actions- // Start a new conversation so the prompt doesn't get added to an existing session- if (featureFlags[FEATURE_FLAGS.TODAY_RAIL_NAV]) {- // The Today panel can show a task chat too, so its own logic starts the new chat.- const unmount = todayAiChatLogic.mount()- todayAiChatLogic.actions.startNewChatForTool()- unmount()- } else if (maxGlobalLogic.values.effectivePhaiView === 'new') {- const runner = runnerPanelLogic({ panelId: MAX_SIDE_PANEL_ID })- const unmount = runner.mount()- runner.actions.clearActiveCreation()- runner.actions.setHistoryExpanded(false)- unmount()- } else {- startNewConversation()+ : async (): Promise<void> => {+ let opener: Awaited<ReturnType<typeof loadMaxToolOpener>>+ try {+ opener = await loadMaxToolOpener()+ } catch (error) {+ // Click handlers drop a rejected promise, and no error boundary sees it.+ lemonToast.error("Couldn't open PostHog AI. Reload the page to try again.", {+ button: { label: 'Reload', action: () => reloadAfterChunkLoadError(error) },+ })+ return}- if (maxGlobalLogic.values.effectivePhaiView === 'new') {+ const { startToolChat, showToolSuggestions } = opener+ startToolChat({ todayRailNav: !!featureFlags[FEATURE_FLAGS.TODAY_RAIL_NAV], effectivePhaiView })+ // The page may have closed, or the tool turned off, while the chunk loaded. Its context would then outlive the hook.+ if (effectivePhaiView === 'new' && !unmountedRef.current && latestRef.current.active) {toolPageContextOwner = hookIdRef.current- const items = toolPageContextItems(identifier, context, TOOL_PAGE_CONTEXT_PROVIDER_ID)+ const items = toolPageContextItems(+ identifier,+ latestRef.current.context,+ TOOL_PAGE_CONTEXT_PROVIDER_ID+ )undismissContext(attachedContextItemKey(items[0]), TOOL_PAGE_CONTEXT_PROVIDER_ID)registerContext(TOOL_PAGE_CONTEXT_PROVIDER_ID, items)}// Show the suggestions from this specific toolif (definition && suggestions && suggestions.length > 0) {- setActiveGroup(- createSuggestionGroup(definition.name, React.createElement(IconWrench), suggestions)- )+ showToolSuggestions(definition.name, suggestions)}openSidePanel(SidePanelTab.Max, initialMaxPrompt)onMaxOpen?.()diff --git a/frontend/src/scenes/max/useSceneAgentPanel.ts b/frontend/src/scenes/max/useSceneAgentPanel.tsindex 011b55e8eb76..13cabd39bd21 100644--- a/frontend/src/scenes/max/useSceneAgentPanel.ts+++ b/frontend/src/scenes/max/useSceneAgentPanel.ts@@ -1,13 +1,14 @@import { useActions, useValues } from 'kea'import { useEffect } from 'react'+import { AttachedContextItem } from '~/layout/ai/attachedContext'+import {ComposerOverride,useAttachedContext,useComposerOverride,useWelcomeOverride,} from 'products/posthog_ai/frontend/api/logics'-import { AttachedContextItem } from 'products/posthog_ai/frontend/api/types'import { sceneAgentPanelLogic } from './sceneAgentPanelLogic'diff --git a/frontend/src/scenes/session-recordings/filters/useRecordingFiltersAssist.ts b/frontend/src/scenes/session-recordings/filters/useRecordingFiltersAssist.tsindex 46611399304a..9acf12fa63a0 100644--- a/frontend/src/scenes/session-recordings/filters/useRecordingFiltersAssist.ts+++ b/frontend/src/scenes/session-recordings/filters/useRecordingFiltersAssist.ts@@ -2,11 +2,11 @@ import { useActions } from 'kea'import { playlistFiltersLogic } from 'scenes/session-recordings/playlist/playlistFiltersLogic'+import type { AttachedContextItem } from '~/layout/ai/attachedContext'import { NodeKind, RecordingsQuery } from '~/queries/schema/schema-general'import { RecordingUniversalFilters } from '~/types'import { useAttachedContext, useMcpToolApplyBack } from 'products/posthog_ai/frontend/api/logics'-import type { AttachedContextItem } from 'products/posthog_ai/frontend/api/types'import {DEFAULT_RECORDING_FILTERS_ORDER_BY,diff --git a/frontend/src/scenes/session-recordings/player/player-meta/debugReplayChatLogic.test.ts b/frontend/src/scenes/session-recordings/player/player-meta/debugReplayChatLogic.test.tsindex 96d2ebd8ce1d..15a533643e2b 100644--- a/frontend/src/scenes/session-recordings/player/player-meta/debugReplayChatLogic.test.ts+++ b/frontend/src/scenes/session-recordings/player/player-meta/debugReplayChatLogic.test.ts@@ -1,11 +1,10 @@import { expectLogic } from 'kea-test-utils'import { MAX_SIDE_PANEL_ID } from '~/layout/ai/aiPanelIds'+import { ActiveCreation, runnerPanelLogic } from '~/layout/ai/runnerPanelLogic'import { useMocks } from '~/mocks/jest'import { initKeaTests } from '~/test/init'-import { ActiveCreation, runnerPanelLogic } from 'products/posthog_ai/frontend/api/logics'-import { DebugChatSummary, debugReplayChatLogic } from './debugReplayChatLogic'describe('debugReplayChatLogic', () => {diff --git a/frontend/src/scenes/session-recordings/player/player-meta/debugReplayChatLogic.ts b/frontend/src/scenes/session-recordings/player/player-meta/debugReplayChatLogic.tsindex 6ef9f944b18c..0203f17e147d 100644--- a/frontend/src/scenes/session-recordings/player/player-meta/debugReplayChatLogic.ts+++ b/frontend/src/scenes/session-recordings/player/player-meta/debugReplayChatLogic.ts@@ -9,10 +9,10 @@ import { sessionRecordingEventUsageLogic } from 'scenes/session-recordings/sessiimport { urls } from 'scenes/urls'import { MAX_SIDE_PANEL_ID, type PhaiViewMode } from '~/layout/ai/aiPanelIds'+import { ActiveCreation, runnerPanelLogic } from '~/layout/ai/runnerPanelLogic'import { sidePanelStateLogic } from '~/layout/navigation-3000/sidepanel/sidePanelStateLogic'import { SidePanelTab } from '~/types'-import { ActiveCreation, runnerPanelLogic } from 'products/posthog_ai/frontend/api/logics'import { tasksRetrieve } from 'products/tasks/frontend/generated/api'import { TaskDetailDTOApi } from 'products/tasks/frontend/generated/api.schemas'diff --git a/frontend/src/scenes/session-recordings/player/player-meta/debugReplayPrompt.ts b/frontend/src/scenes/session-recordings/player/player-meta/debugReplayPrompt.tsindex bd697590435e..ea1506756db6 100644--- a/frontend/src/scenes/session-recordings/player/player-meta/debugReplayPrompt.ts+++ b/frontend/src/scenes/session-recordings/player/player-meta/debugReplayPrompt.ts@@ -1,6 +1,6 @@import { colonDelimitedDuration } from 'lib/utils/durations'-import { AttachedContextItem } from 'products/posthog_ai/frontend/api/types'+import { AttachedContextItem } from '~/layout/ai/attachedContext'const DEBUG_REPLAY_DISMISS_GROUP = 'session_recording_player'diff --git a/frontend/src/scenes/session-recordings/player/sessionRecordingPlayerLogic.ts b/frontend/src/scenes/session-recordings/player/sessionRecordingPlayerLogic.tsindex 4e3eacadb9eb..80fadfcfa317 100644--- a/frontend/src/scenes/session-recordings/player/sessionRecordingPlayerLogic.ts+++ b/frontend/src/scenes/session-recordings/player/sessionRecordingPlayerLogic.ts@@ -64,6 +64,9 @@ import { urls } from 'scenes/urls'import { userLogic } from 'scenes/userLogic'import { MAX_SIDE_PANEL_ID, type PhaiViewMode } from '~/layout/ai/aiPanelIds'+import { AttachedContextItem } from '~/layout/ai/attachedContext'+import { attachedContextLogic } from '~/layout/ai/attachedContextLogic'+import { runnerPanelLogic } from '~/layout/ai/runnerPanelLogic'import { sidePanelStateLogic } from '~/layout/navigation-3000/sidepanel/sidePanelStateLogic'import {AvailableFeature,@@ -74,13 +77,7 @@ import {SidePanelTab,} from '~/types'-import {- ATTACHMENT_MAX_SIZE_BYTES,- attachedContextLogic,- composerAttachmentsLogic,- runnerPanelLogic,-} from 'products/posthog_ai/frontend/api/logics'-import { AttachedContextItem } from 'products/posthog_ai/frontend/api/types'+import { ATTACHMENT_MAX_SIZE_BYTES, composerAttachmentsLogic } from 'products/posthog_ai/frontend/api/logics'import {MAX_REPLAY_IFRAME_HTML_CHARS,ReplayIframeData,diff --git a/frontend/src/scenes/web-analytics/WebAnalyticsFilters.tsx b/frontend/src/scenes/web-analytics/WebAnalyticsFilters.tsxindex a0fc261a7556..f1ca257306b7 100644--- a/frontend/src/scenes/web-analytics/WebAnalyticsFilters.tsx+++ b/frontend/src/scenes/web-analytics/WebAnalyticsFilters.tsx@@ -30,11 +30,11 @@ import { COUNTRY_CODE_TO_LONG_NAME, countryCodeToFlag } from 'lib/utils/country'import { useMaxTool } from 'scenes/max/useMaxTool'import { Scene } from 'scenes/sceneTypes'+import type { AttachedContextItem } from '~/layout/ai/attachedContext'import { ReloadAll } from '~/queries/nodes/DataNode/Reload'import { AnyPropertyFilter, PropertyFilterType, PropertyMathType, PropertyOperator } from '~/types'import { useAttachedContext, useMcpToolApplyBack } from 'products/posthog_ai/frontend/api/logics'-import type { AttachedContextItem } from 'products/posthog_ai/frontend/api/types'import { INITIAL_DATE_FROM, INITIAL_DATE_TO, ProductTab, faviconUrl } from './common'import { webAnalyticsDateMapping } from './constants'diff --git a/products/ai_observability/frontend/customParser/useCustomParserMaxTool.ts b/products/ai_observability/frontend/customParser/useCustomParserMaxTool.tsindex 57439b200636..7c14937bb6dc 100644--- a/products/ai_observability/frontend/customParser/useCustomParserMaxTool.ts+++ b/products/ai_observability/frontend/customParser/useCustomParserMaxTool.ts@@ -7,8 +7,9 @@ import { handleCreateParserRecipeCall, sampleForContext } from '@posthog/llm-norimport { useMaxTool } from 'scenes/max/useMaxTool'import { teamLogic } from 'scenes/teamLogic'+import type { AttachedContextItem } from '~/layout/ai/attachedContext'+import { useAttachedContext, useMcpToolApplyBack } from 'products/posthog_ai/frontend/api/logics'-import type { AttachedContextItem } from 'products/posthog_ai/frontend/api/types'import { llmAnalyticsParserRecipesCreate } from '../generated/api'import { parserRecipesLogic } from '../settings/parserRecipesLogic'diff --git a/products/business_intelligence/frontend/biAgentContext.ts b/products/business_intelligence/frontend/biAgentContext.tsindex ec17fec241fa..06067f125447 100644--- a/products/business_intelligence/frontend/biAgentContext.ts+++ b/products/business_intelligence/frontend/biAgentContext.ts@@ -1,8 +1,8 @@+import { AttachedContextItem } from '~/layout/ai/attachedContext'import { BIVisualizationNode } from '~/queries/schema/schema-business-intelligence'import { validateMetricName } from 'products/data_catalog/frontend/common'import { DATA_CATALOG_CAPABILITY_CONTEXT } from 'products/data_catalog/frontend/dataCatalogAgentContext'-import { AttachedContextItem } from 'products/posthog_ai/frontend/api/types'export function buildBIAgentContext(worksheet?: BIVisualizationNode,diff --git a/products/business_intelligence/frontend/biAgentSyncLogic.test.ts b/products/business_intelligence/frontend/biAgentSyncLogic.test.tsindex 172c17d21429..aeadc10ffb03 100644--- a/products/business_intelligence/frontend/biAgentSyncLogic.test.ts+++ b/products/business_intelligence/frontend/biAgentSyncLogic.test.ts@@ -1,11 +1,9 @@+import { attachedContextItemKey } from '~/layout/ai/attachedContext'+import { attachedContextLogic } from '~/layout/ai/attachedContextLogic'import { NodeKind } from '~/queries/schema/schema-general'import { initKeaTests } from '~/test/init'-import {- attachedContextItemKey,- attachedContextLogic,- toolStreamEventsLogic,-} from 'products/posthog_ai/frontend/api/logics'+import { toolStreamEventsLogic } from 'products/posthog_ai/frontend/api/logics'import { foregroundStreamLogic } from 'products/posthog_ai/frontend/logics/foregroundStreamLogic'import type { ToolStreamEvent } from 'products/posthog_ai/frontend/types/streamTypes'diff --git a/products/data_catalog/frontend/dataCatalogAgentContext.ts b/products/data_catalog/frontend/dataCatalogAgentContext.tsindex ecd825038003..58723415ab98 100644--- a/products/data_catalog/frontend/dataCatalogAgentContext.ts+++ b/products/data_catalog/frontend/dataCatalogAgentContext.ts@@ -1,4 +1,4 @@-import type { AttachedContextItem } from 'products/posthog_ai/frontend/api/types'+import type { AttachedContextItem } from '~/layout/ai/attachedContext'import { validateMetricName } from './common'import type { DataCatalogTab } from './dataCatalogSceneLogic'diff --git a/products/error_tracking/frontend/components/IssueFilteringTool.tsx b/products/error_tracking/frontend/components/IssueFilteringTool.tsxindex b059c465fdc7..3a41a78e2302 100644--- a/products/error_tracking/frontend/components/IssueFilteringTool.tsx+++ b/products/error_tracking/frontend/components/IssueFilteringTool.tsx@@ -5,11 +5,11 @@ import { IconFilter } from '@posthog/icons'import { taxonomicFilterLogic } from 'lib/components/TaxonomicFilter/taxonomicFilterLogic'import MaxTool from 'scenes/max/MaxTool'+import type { AttachedContextItem } from '~/layout/ai/attachedContext'import { ErrorTrackingIssueFilteringToolOutput } from '~/queries/schema/schema-general'import { FilterLogicalOperator, PropertyFilterType, PropertyOperator, UniversalFiltersGroup } from '~/types'import { useAttachedContext, useMcpToolApplyBack } from 'products/posthog_ai/frontend/api/logics'-import type { AttachedContextItem } from 'products/posthog_ai/frontend/api/types'import { errorTrackingSceneLogic } from '../scenes/ErrorTrackingScene/errorTrackingSceneLogic'import { TAXONOMIC_FILTER_LOGIC_KEY, TAXONOMIC_GROUP_TYPES } from './IssueFilters/consts'diff --git a/products/feature_flags/frontend/featureFlagCleanupAssessmentLogic.test.ts b/products/feature_flags/frontend/featureFlagCleanupAssessmentLogic.test.tsindex c674dbc77e74..173cfadb23d2 100644--- a/products/feature_flags/frontend/featureFlagCleanupAssessmentLogic.test.ts+++ b/products/feature_flags/frontend/featureFlagCleanupAssessmentLogic.test.ts@@ -11,6 +11,8 @@ import { maxMocks } from 'scenes/max/testUtils'import { organizationLogic } from 'scenes/organizationLogic'import { MAX_SIDE_PANEL_ID } from '~/layout/ai/aiPanelIds'+import { attachedContextLogic } from '~/layout/ai/attachedContextLogic'+import { runnerPanelLogic } from '~/layout/ai/runnerPanelLogic'import { sidePanelStateLogic } from '~/layout/navigation-3000/sidepanel/sidePanelStateLogic'import { useMocks } from '~/mocks/jest'import { initKeaTests } from '~/test/init'@@ -22,7 +24,7 @@ import {SidePanelTab,} from '~/types'-import { attachedContextLogic, composerSeedLogic, runnerPanelLogic } from 'products/posthog_ai/frontend/api/logics'+import { composerSeedLogic } from 'products/posthog_ai/frontend/api/logics'import { featureFlagCleanupAssessmentLogic } from './featureFlagCleanupAssessmentLogic'diff --git a/products/feature_flags/frontend/featureFlagCleanupAssessmentLogic.ts b/products/feature_flags/frontend/featureFlagCleanupAssessmentLogic.tsindex 13ab35bae09b..68b6a8873672 100644--- a/products/feature_flags/frontend/featureFlagCleanupAssessmentLogic.ts+++ b/products/feature_flags/frontend/featureFlagCleanupAssessmentLogic.ts@@ -22,10 +22,11 @@ import {import { maxGlobalLogic } from 'scenes/max/maxGlobalLogic'import { MAX_SIDE_PANEL_ID, type PhaiViewMode } from '~/layout/ai/aiPanelIds'+import { runnerPanelLogic } from '~/layout/ai/runnerPanelLogic'import { sidePanelStateLogic } from '~/layout/navigation-3000/sidepanel/sidePanelStateLogic'import { SidePanelTab } from '~/types'-import { composerSeedLogic, runnerPanelLogic, type ComposerSeed } from 'products/posthog_ai/frontend/api/logics'+import { composerSeedLogic, type ComposerSeed } from 'products/posthog_ai/frontend/api/logics'export interface FeatureFlagCleanupAssessmentLogicProps {id: numberdiff --git a/products/logs/frontend/components/LogsViewer/LogContextLinks/missingLinkInvestigateLogic.ts b/products/logs/frontend/components/LogsViewer/LogContextLinks/missingLinkInvestigateLogic.tsindex d40204a46b57..c2b7eec5a923 100644--- a/products/logs/frontend/components/LogsViewer/LogContextLinks/missingLinkInvestigateLogic.ts+++ b/products/logs/frontend/components/LogsViewer/LogContextLinks/missingLinkInvestigateLogic.ts@@ -5,17 +5,13 @@ import { maxGlobalLogic } from 'scenes/max/maxGlobalLogic'import { urls } from 'scenes/urls'import { MAX_SIDE_PANEL_ID, type PhaiViewMode } from '~/layout/ai/aiPanelIds'+import { type ActiveCreation, runnerPanelLogic } from '~/layout/ai/runnerPanelLogic'import { sidePanelStateLogic } from '~/layout/navigation-3000/sidepanel/sidePanelStateLogic'import { todayShellLogic } from '~/layout/today/todayShellLogic'import { SidePanelTab } from '~/types'import { logsViewerModalLogic } from 'products/logs/frontend/components/LogsViewer/LogsViewerModal/logsViewerModalLogic'-import {- type ActiveCreation,- type ComposerSeed,- composerSeedLogic,- runnerPanelLogic,-} from 'products/posthog_ai/frontend/api/logics'+import { type ComposerSeed, composerSeedLogic } from 'products/posthog_ai/frontend/api/logics'import { InvestigateRoute, MissingLinkEventContext, captureInvestigate } from './missingLinkTelemetry'diff --git a/products/logs/frontend/logsAgentContext.ts b/products/logs/frontend/logsAgentContext.tsindex ef4e6d49b110..1cb61a740061 100644--- a/products/logs/frontend/logsAgentContext.ts+++ b/products/logs/frontend/logsAgentContext.ts@@ -1,3 +1,4 @@+import { AttachedContextItem } from '~/layout/ai/attachedContext'import { DateRange, LogsQuery } from '~/queries/schema/schema-general'import {FilterLogicalOperator,@@ -7,8 +8,6 @@ import {UniversalFiltersGroupValue,} from '~/types'-import { AttachedContextItem } from 'products/posthog_ai/frontend/api/types'-import { LogsViewerFilters } from './components/LogsViewer/config/types'import {DEFAULT_DATE_RANGE,diff --git a/products/notebooks/frontend/notebookBtwContext.ts b/products/notebooks/frontend/notebookBtwContext.tsindex bb5059ca0f4e..fc8e424b7d59 100644--- a/products/notebooks/frontend/notebookBtwContext.ts+++ b/products/notebooks/frontend/notebookBtwContext.ts@@ -1,7 +1,7 @@import { stripNotebookMediaFromMarkdown } from 'lib/components/MarkdownNotebook/documentModel'import type { NotebookBtwContext } from 'lib/components/MarkdownNotebook/MarkdownNotebook'-import type { AttachedContextItem } from 'products/posthog_ai/frontend/api/types'+import type { AttachedContextItem } from '~/layout/ai/attachedContext'const BTW_INSTRUCTIONS: AttachedContextItem = {type: 'instructions',diff --git a/products/posthog_ai/frontend/AGENTS.md b/products/posthog_ai/frontend/AGENTS.mdindex 07a2ba66d97d..82fa946717cb 100644--- a/products/posthog_ai/frontend/AGENTS.md+++ b/products/posthog_ai/frontend/AGENTS.md@@ -76,12 +76,17 @@ The headline exports per module:- **`api/logics`** — **`runStreamLogic`** (SSE stream + thread projection, see §3),**`runInteractionLogic`** (Max-agnostic follow-up/queue facade), status helpers(`isTerminalRunStatus`, `INITIAL_PERMISSION_MODE`), thinking-message helpers,- **`attachedContextLogic`** + **`useAttachedContext`** (context injection, see §3), and+ **`useAttachedContext`** (context injection, see §3), and**`toolStreamEventsLogic`** + **`useToolStreamListener`** (tool-stream subscriptions, see §3).Imports only `logics/*` + `hooks/*` + `utils/*` — never a component or the registry. The two hooks are adeliberate, mild deviation from the "no React" reading of this lane: they import `react` + `kea` but nocomponents, so the lane stays registry- and presenter-free.-- **`api/types`** — folded-thread + tool domain types, `AttachedContextItem`, `ToolStreamEvent` (pure types).+- **The shell contract (`frontend/src/layout/ai/`)** — the app shell owns the small AI state it reads on every+ page, and this product imports it from there: **`runnerPanelLogic`** (panel view state, `ActiveCreation`),+ **`attachedContextLogic`** (the context store, see §3), and `attachedContext` (`AttachedContextItem`,+ `attachedContextItemKey`). The shell must not import this product, so these files import only `kea` and pure+ types. Never move a stream, interaction or task logic there; those belong in `api/logics`.+- **`api/types`** — folded-thread + tool domain types, `ToolStreamEvent` (pure types).- **`api/tools`** — **`toolRegistry`**, **`ToolRegistryEntry`** (the declaration contract, see §2),`lookupToolRenderer`, `GenericMcpToolRenderer`, `DataToolRow`, `ToolActivity`, `FilePath`, and thediff/exec helpers. Isolated here because importing it pulls the side-effectful registry chunk.@@ -154,7 +159,7 @@ Supporting modules live in `policy/` (tool policy + permission/question utils) a(`streamTypes` = folded thread shapes; `wireTypes` = ACP wire shapes + guards). Wire types areloosely typed — guard at the parse boundary with runtime checks; never assume a field is present.-**Context injection (`logics/attachedContextLogic.ts`):** a global registry of on-screen context. A provider+**Context injection (`~/layout/ai/attachedContextLogic`, shell-owned):** a global registry of on-screen context. A provider(a mounted `useAttachedContext` hook / `AttachedContextProvider` component, or a kea logic registering via`cache.disposables` — setup dispatches `registerContext(providerId, items)`, cleanup `deregisterContext`,with `pauseOnPageHidden: false` since a hide-paused registration would drop context from sends that happen@@ -250,8 +255,8 @@ api/ # public API facade — the contract (import api/<module>, nrunner.ts # Tier 1: EmbeddedRunner (lazy TaskTracker product) for inline hostsprimitives.ts # Tier 2: Thread + atoms, ThreadView, QueuedMessageList, presenters, perm/questioncomposer.ts # Tier 2: Composer + quill composer frame only, for eager surfaces that must not pull the thread- logics.ts # Tier 3: runStreamLogic, runInteractionLogic, context store + hooks, tool-event bus (headless)- types.ts # Tier 3: folded-thread + tool domain types, AttachedContextItem, ToolStreamEvent (pure types)+ logics.ts # Tier 3: runStreamLogic, runInteractionLogic, context hooks, tool-event bus (headless)+ types.ts # Tier 3: folded-thread + tool domain types, ToolStreamEvent (pure types)tools.ts # Tier 4: lookup + declaration contract (registry isolated)components/ # RunSurfaceImpl (the RunSurface compound, heavy chunk); ReadonlyRunSurfaceImpl (prepackaged# read-only layout) + ReadonlyRunSurface (its lazy wrapper, replaces the old RunViewer.tsx);@@ -262,11 +267,11 @@ components/ # RunSurfaceImpl (the RunSurface compound, heavy chunk); Reatool/ # tool registry + renderers (built-ins, generic MCP, EditDiffRenderer, diff/exec utils)widgets/ # PostHog product data-tool widgets (insight/dashboard/recordings/notebook/query)hooks/ # useAttachedContext, useToolStream — mount-scoped registration wrappers over the logics-logics/ # runStreamLogic, runInteractionLogic, attachedContextLogic, contextPickerLogic, toolStreamEventsLogic;+logics/ # runStreamLogic, runInteractionLogic, contextPickerLogic, toolStreamEventsLogic;# tasksLogic/taskLogic data logics (+ *LogicType.ts)policy/ # tool policy + permission/question utils-types/ # streamTypes (folded thread + ToolStreamEvent), wireTypes (ACP), contextTypes- # (AttachedContextItem), toolTypes, taskTypes (task/run domain)+types/ # streamTypes (folded thread + ToolStreamEvent), wireTypes (ACP), toolTypes,+ # taskTypes (task/run domain)messages/ # MessageTemplate, MarkdownMessage, ReasoningAnswer, AssistantFailureMessageutils/ # thinkingMessages, posthogContextBlock (trusted/untrusted context-block builder)lib/ # task/run helpers (parse-logs, task-status, repository, ph-debug, util-functions)diff --git a/products/posthog_ai/frontend/README.md b/products/posthog_ai/frontend/README.mdindex beb4714c0c15..52aa539a548b 100644--- a/products/posthog_ai/frontend/README.md+++ b/products/posthog_ai/frontend/README.md@@ -41,7 +41,7 @@ Pick the **lowest tier** that does the job.| ------------------------------ | ----------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------- || **1 — Prepackaged surfaces** | `api/readableRun` + `api/runSurface` + `api/runner` | `ReadonlyRunSurface` (lazy, code-split read-only embed); the `RunSurface` compound (`Root` + slots, eager) for custom layouts; `EmbeddedRunner` (lazy TaskTracker workspace for inline hosts) | "Just show a run" → `ReadonlyRunSurface` (inbox embeds). "Drive a run / custom layout" → `RunSurface` (tasks). "Embed the `/tasks` workspace" → `EmbeddedRunner` (Max). || **2 — Compound primitives** | `api/primitives` + `api/composer` + `api/dataWidgets` | `Thread` + atoms (`.Message/.Markdown/.Reasoning/.Failure/.Activity/.ToolCall`), `ThreadView`, `AttachedContextBar`, task navigation items and filters, `QueuedMessageList`, `RunLogSkeleton`, activity primitives + `RunActivity`, message presenters, permission/question/resource surfaces; `api/composer` holds `Composer.*` and the quill composer frame | Custom layout, shared navigation, or a bespoke/compact thread. An input box alone imports only `api/composer`. Chart and recording widgets use `api/dataWidgets`. |-| **3 — Headless logic + types** | `api/logics` + `api/types` | `runStreamLogic`, `runInteractionLogic`, `tasksLogic`, status helpers (`isTerminalRunStatus`, `INITIAL_PERMISSION_MODE`), thinking-message helpers, context injection (`attachedContextLogic`, `useAttachedContext`, `contextPickerLogic`), tool-stream subscriptions (`toolStreamEventsLogic`, `useToolStreamListener`); folded-thread, task, and tool types | Status badge, automation, context injection, task navigation, tool-event listeners — no presenters or registry. |+| **3 — Headless logic + types** | `api/logics` + `api/types` | `runStreamLogic`, `runInteractionLogic`, `tasksLogic`, status helpers (`isTerminalRunStatus`, `INITIAL_PERMISSION_MODE`), thinking-message helpers, context injection (`useAttachedContext`, `contextPickerLogic`), tool-stream subscriptions (`toolStreamEventsLogic`, `useToolStreamListener`); folded-thread, task, and tool types | Status badge, automation, context injection, task navigation, tool-event listeners — no presenters or registry. || **4 — Extension seam** | `api/tools` | `toolRegistry`, `lookupToolRenderer`, `GenericMcpToolRenderer`, `DataToolRow`, `ToolActivity`, `FilePath`, diff helpers | Your product renders tool cards (insights, dashboards…). Declare them in your product list and include it in the central manifest. |The Tier 1 surfaces are built on `api/primitives` (Tier 2), which consumes the headless@@ -249,7 +249,7 @@ useAttachedContext([{ type: 'insight', key: insight.short_id, label: insight.namJSX-only call sites can render `<AttachedContextProvider items={...} />` (`api/primitives`) instead.-From a kea logic, connect to `attachedContextLogic` and register through a disposable (the repo-preferred+From a kea logic, connect to the shell-owned `attachedContextLogic` (`~/layout/ai/attachedContextLogic`) and register through a disposable (the repo-preferredteardown idiom — see `/using-kea-disposables`); the returned cleanup deregisters on unmount, no`beforeUnmount` needed. Pass `pauseOnPageHidden: false`: the registration costs nothing while idle, and thedefault hide-pause would silently drop context from a queued follow-up that flushes while the tab is hidden.diff --git a/products/posthog_ai/frontend/api/logics.ts b/products/posthog_ai/frontend/api/logics.tsindex 2b1dd3720c80..aac0c3337b48 100644--- a/products/posthog_ai/frontend/api/logics.ts+++ b/products/posthog_ai/frontend/api/logics.ts@@ -43,13 +43,10 @@ export { tasksLogic } from '../logics/tasksLogic'export { useThreadSkin, ThreadSkinOverrideContext } from '../hooks/useThreadSkin'export type { ThreadSkin } from '../components/quill/quillThreadContext'-// --- Attached-context store + injection hook (headless) ----// Global registry of on-screen context providers; `contextItems` is what the send paths wrap into the-// trusted/untrusted context blocks. `useAttachedContext` registers a provider for the lifetime of a mount.-export { attachedContextLogic } from '../logics/attachedContextLogic'+// --- Attached-context injection hook (headless) ---+// `useAttachedContext` registers a provider in the shell's context store for the lifetime of a mount.export { useAttachedContext } from '../hooks/useAttachedContext'export type { UseAttachedContextOptions } from '../hooks/useAttachedContext'-export { attachedContextItemKey } from '../types/contextTypes'// Contextual welcome headlines: a host registers headlines matching what the user is looking at,// and the composer's empty state picks from them instead of the generic defaults.export { welcomeOverrideLogic } from '../logics/welcomeOverrideLogic'@@ -91,12 +88,6 @@ export { useForegroundStream } from '../hooks/useForegroundStream'export { useMcpToolApplyBack } from '../hooks/useMcpToolApplyBack'export type { ApplyOn, McpToolApplyContext, UseMcpToolApplyBackOptions } from '../hooks/useMcpToolApplyBack'-// --- Panel view state (headless) ----// Panel-level view state (active run vs. history vs. composer) for hosts that render chrome — e.g. a-// header back button — outside the lazy panel chunk (Tier 1 `api/runner`).-export { runnerPanelLogic } from '../logics/runnerPanelLogic'-export type { RunnerPanelLogicProps, ActiveCreation } from '../logics/runnerPanelLogic'-// --- Composer seed hand-off (headless) ---// A one-shot store that lets a host seed a not-yet-mounted composer with an initial prompt (optionally// auto-submitting it); the paired `taskTrackerSceneLogic` consumes it on mount or when it arrives.diff --git a/products/posthog_ai/frontend/api/types.ts b/products/posthog_ai/frontend/api/types.tsindex 6e7ba006537e..78c420224c8e 100644--- a/products/posthog_ai/frontend/api/types.ts+++ b/products/posthog_ai/frontend/api/types.ts@@ -7,7 +7,6 @@ export type {ProgressStep,} from '../types/streamTypes'export type { ToolCallMessage } from '../types/toolTypes'-export type { AttachedContextItem } from '../types/contextTypes'export type { Task, TaskAssigneeFilter, TaskListParams } from '../types/taskTypes'export type {ToolStreamEvent,diff --git a/products/posthog_ai/frontend/components/AttachedContextProvider.tsx b/products/posthog_ai/frontend/components/AttachedContextProvider.tsxindex 3363d00626d7..dedce609812e 100644--- a/products/posthog_ai/frontend/components/AttachedContextProvider.tsx+++ b/products/posthog_ai/frontend/components/AttachedContextProvider.tsx@@ -1,5 +1,6 @@+import type { AttachedContextItem } from '~/layout/ai/attachedContext'+import { useAttachedContext } from '../hooks/useAttachedContext'-import type { AttachedContextItem } from '../types/contextTypes'export interface AttachedContextProviderProps {items: AttachedContextItem[] | nulldiff --git a/products/posthog_ai/frontend/components/composer/AttachedContextBar.test.tsx b/products/posthog_ai/frontend/components/composer/AttachedContextBar.test.tsxindex 1d0a3e1a030a..b2134ddb9070 100644--- a/products/posthog_ai/frontend/components/composer/AttachedContextBar.test.tsx+++ b/products/posthog_ai/frontend/components/composer/AttachedContextBar.test.tsx@@ -2,10 +2,10 @@ import '@testing-library/jest-dom'import { cleanup, fireEvent, render, screen } from '@testing-library/react'+import { attachedContextLogic } from '~/layout/ai/attachedContextLogic'import { useMocks } from '~/mocks/jest'import { initKeaTests } from '~/test/init'-import { attachedContextLogic } from '../../logics/attachedContextLogic'import { AttachedContextBar } from './AttachedContextBar'describe('AttachedContextBar', () => {diff --git a/products/posthog_ai/frontend/components/composer/AttachedContextChips.tsx b/products/posthog_ai/frontend/components/composer/AttachedContextChips.tsxindex 552209ebdafc..70e167ed543c 100644--- a/products/posthog_ai/frontend/components/composer/AttachedContextChips.tsx+++ b/products/posthog_ai/frontend/components/composer/AttachedContextChips.tsx@@ -7,9 +7,10 @@ import { LemonButton, LemonTag, Tooltip } from '@posthog/lemon-ui'import { EmailPreviewThumbnail } from 'lib/components/EmailPreviewThumbnail/EmailPreviewThumbnail'import { IconAction, IconEvent } from 'lib/lemon-ui/icons'-import { attachedContextLogic } from '../../logics/attachedContextLogic'+import { type AttachedContextItem, attachedContextItemKey } from '~/layout/ai/attachedContext'+import { attachedContextLogic } from '~/layout/ai/attachedContextLogic'+import { contextPickerLogic } from '../../logics/contextPickerLogic'-import { type AttachedContextItem, attachedContextItemKey } from '../../types/contextTypes'function iconForType(type: string): JSX.Element {switch (type) {diff --git a/products/posthog_ai/frontend/components/quill/QuillAttachedContextPicker.tsx b/products/posthog_ai/frontend/components/quill/QuillAttachedContextPicker.tsxindex 1d1100ecf682..f55df2146e20 100644--- a/products/posthog_ai/frontend/components/quill/QuillAttachedContextPicker.tsx+++ b/products/posthog_ai/frontend/components/quill/QuillAttachedContextPicker.tsx@@ -19,9 +19,9 @@ import { TaxonomicFilter } from 'lib/components/TaxonomicFilter/TaxonomicFilter'import { TaxonomicFilterGroupType } from 'lib/components/TaxonomicFilter/types'import { cn } from 'lib/utils/css-classes'+import { attachedContextLogic } from '~/layout/ai/attachedContextLogic'import { todayShellLogic } from '~/layout/today/todayShellLogic'-import { attachedContextLogic } from '../../logics/attachedContextLogic'import { CONTEXT_PICKER_GROUP_TYPES, contextPickerLogic } from '../../logics/contextPickerLogic'import { COMPOSER_MENU_CLASS } from './composerMenuClass'diff --git a/products/posthog_ai/frontend/hooks/useAttachedContext.ts b/products/posthog_ai/frontend/hooks/useAttachedContext.tsindex c1b84d574893..f44558a12beb 100644--- a/products/posthog_ai/frontend/hooks/useAttachedContext.ts+++ b/products/posthog_ai/frontend/hooks/useAttachedContext.ts@@ -3,8 +3,8 @@ import { useEffect, useMemo, useRef } from 'react'import { uuid } from 'lib/utils/dom'-import { attachedContextLogic } from '../logics/attachedContextLogic'-import type { AttachedContextItem } from '../types/contextTypes'+import type { AttachedContextItem } from '~/layout/ai/attachedContext'+import { attachedContextLogic } from '~/layout/ai/attachedContextLogic'export interface UseAttachedContextOptions {/** When false, the provider is deregistered (nothing attached). Defaults to true. */diff --git a/products/posthog_ai/frontend/logics/composerSeedLogic.ts b/products/posthog_ai/frontend/logics/composerSeedLogic.tsindex a8b7c264c5ce..48b2515c663e 100644--- a/products/posthog_ai/frontend/logics/composerSeedLogic.ts+++ b/products/posthog_ai/frontend/logics/composerSeedLogic.ts@@ -1,6 +1,6 @@import { MakeLogicType, actions, kea, key, path, props, reducers } from 'kea'-import type { AttachedContextItem } from '../types/contextTypes'+import type { AttachedContextItem } from '~/layout/ai/attachedContext'export interface ComposerSeed {prompt: stringdiff --git a/products/posthog_ai/frontend/logics/contextPickerLogic.test.ts b/products/posthog_ai/frontend/logics/contextPickerLogic.test.tsindex e38e4e57ba8a..3a5e7dbbd6ab 100644--- a/products/posthog_ai/frontend/logics/contextPickerLogic.test.ts+++ b/products/posthog_ai/frontend/logics/contextPickerLogic.test.ts@@ -2,9 +2,9 @@ import { expectLogic } from 'kea-test-utils'import { TaxonomicFilterGroupType } from 'lib/components/TaxonomicFilter/types'+import { attachedContextLogic } from '~/layout/ai/attachedContextLogic'import { initKeaTests } from '~/test/init'-import { attachedContextLogic } from './attachedContextLogic'import { PICKER_PROVIDER_ID, contextPickerLogic, taxonomicItemToAttachedContext } from './contextPickerLogic'describe('contextPickerLogic', () => {diff --git a/products/posthog_ai/frontend/logics/contextPickerLogic.ts b/products/posthog_ai/frontend/logics/contextPickerLogic.tsindex c15c874b0b04..6112dfc6482e 100644--- a/products/posthog_ai/frontend/logics/contextPickerLogic.ts+++ b/products/posthog_ai/frontend/logics/contextPickerLogic.ts@@ -14,8 +14,8 @@ import type { BreakPointFunction } from 'kea'import { TaxonomicFilterGroupType } from 'lib/components/TaxonomicFilter/types'-import { type AttachedContextItem, attachedContextItemKey } from '../types/contextTypes'-import { attachedContextLogic } from './attachedContextLogic'+import { type AttachedContextItem, attachedContextItemKey } from '~/layout/ai/attachedContext'+import { attachedContextLogic } from '~/layout/ai/attachedContextLogic'export const PICKER_PROVIDER_ID = 'user-picker'diff --git a/products/posthog_ai/frontend/logics/runInteractionLogic.test.ts b/products/posthog_ai/frontend/logics/runInteractionLogic.test.tsindex e18248e5d16d..195b5ea0b125 100644--- a/products/posthog_ai/frontend/logics/runInteractionLogic.test.ts+++ b/products/posthog_ai/frontend/logics/runInteractionLogic.test.ts@@ -6,6 +6,7 @@ import { lemonToast } from 'lib/lemon-ui/LemonToast'import { projectLogic } from 'scenes/projectLogic'import { aiConsentLogic } from 'scenes/settings/organization/aiConsentLogic'+import { attachedContextLogic } from '~/layout/ai/attachedContextLogic'import { initKeaTests } from '~/test/init'import {@@ -21,7 +22,6 @@ import type { PermissionRequestRecord } from '../types/streamTypes'import type { StoredLogEntry } from '../types/wireTypes'import { uploadRunAttachments, uploadStagedTaskAttachments } from '../utils/artifactUpload'import { contextItemLine } from '../utils/posthogContextBlock'-import { attachedContextLogic } from './attachedContextLogic'import { composerAttachmentsLogic } from './composerAttachmentsLogic'import { runCancellationLogic } from './runCancellationLogic'import { runInteractionLogic } from './runInteractionLogic'diff --git a/products/posthog_ai/frontend/logics/runInteractionLogic.ts b/products/posthog_ai/frontend/logics/runInteractionLogic.tsindex 2d90472df230..4bed53d70837 100644--- a/products/posthog_ai/frontend/logics/runInteractionLogic.ts+++ b/products/posthog_ai/frontend/logics/runInteractionLogic.ts@@ -21,6 +21,9 @@ import { lemonToast } from 'lib/lemon-ui/LemonToast'import { projectLogic } from 'scenes/projectLogic'import { aiConsentLogic } from 'scenes/settings/organization/aiConsentLogic'+import { type AttachedContextItem, attachedContextItemKey } from '~/layout/ai/attachedContext'+import { attachedContextLogic } from '~/layout/ai/attachedContextLogic'+import {buildRunCreateRequest,getDefaultModelForTaskRuntime,@@ -47,7 +50,6 @@ import {type WarmTaskResumeRequestApi,} from 'products/tasks/frontend/generated/api.schemas'-import { type AttachedContextItem, attachedContextItemKey } from '../types/contextTypes'import type { PermissionRequestRecord, StagedAttachment } from '../types/streamTypes'import { isPiTaskRuntime } from '../types/taskTypes'import { uploadRunAttachments, uploadStagedTaskAttachments } from '../utils/artifactUpload'@@ -56,7 +58,6 @@ import type { PendingAttachment } from '../utils/attachments'import { extractCommentContexts, withCommentContexts } from '../utils/commentContext'import { contextItemLine, wrapWithPosthogContext } from '../utils/posthogContextBlock'import { submitWithWarmRunRetry } from '../utils/warmRunSubmission'-import { attachedContextLogic } from './attachedContextLogic'import { codexBillingLogic, pickedCodexModelAccess, usesChatGptPlan } from './codexBillingLogic'import { composerAttachmentsLogic } from './composerAttachmentsLogic'import { modelCatalogueLogic } from './modelCatalogueLogic'diff --git a/products/posthog_ai/frontend/logics/runStreamLogic.test.ts b/products/posthog_ai/frontend/logics/runStreamLogic.test.tsindex 71a4d1566a3e..fdf36453aa2b 100644--- a/products/posthog_ai/frontend/logics/runStreamLogic.test.ts+++ b/products/posthog_ai/frontend/logics/runStreamLogic.test.ts@@ -6,6 +6,8 @@ import api from 'lib/api'import { lemonToast } from 'lib/lemon-ui/LemonToast'import { projectLogic } from 'scenes/projectLogic'+import type { AttachedContextItem } from '~/layout/ai/attachedContext'+import { attachedContextLogic } from '~/layout/ai/attachedContextLogic'import { initKeaTests } from '~/test/init'import {@@ -20,7 +22,6 @@ import { lookupToolRenderer, toolRegistry } from '../components/tool/toolRegistrimport { extractQueryResult } from '../components/tool/widgets/extractors'import { turnSuggestionsStateRetrieve } from '../generated/api'import { defaultPermissionDecision } from '../policy/toolPolicy'-import type { AttachedContextItem } from '../types/contextTypes'import type { ThreadItem } from '../types/streamTypes'import { TaskRunEnvironment, TaskRunStatus } from '../types/taskTypes'import type { PermissionRequestFrame, StoredLogEntry } from '../types/wireTypes'@@ -28,7 +29,6 @@ import { contextItemLine, wrapWithPosthogContext } from '../utils/posthogContextimport { resolveToolCall } from '../utils/toolResolver'import { SUGGESTION_FRAMES } from '../utils/turnSuggestionFixtures'import { computeTurnTrailers } from '../utils/turnTrailers'-import { attachedContextLogic } from './attachedContextLogic'import {appendToRunLog,emptyRunLog,diff --git a/products/posthog_ai/frontend/logics/runStreamLogic.ts b/products/posthog_ai/frontend/logics/runStreamLogic.tsindex aa2b9d423560..737d603dd1d2 100644--- a/products/posthog_ai/frontend/logics/runStreamLogic.ts+++ b/products/posthog_ai/frontend/logics/runStreamLogic.ts@@ -25,6 +25,8 @@ import { uuid } from 'lib/utils/dom'import { projectLogic } from 'scenes/projectLogic'import { userLogic } from 'scenes/userLogic'+import { attachedContextLogic } from '~/layout/ai/attachedContextLogic'+import {tasksRunsCommandCreate,tasksRunsRetrieve,@@ -96,7 +98,6 @@ import { reconcileThreadItems, reconcileToolInvocations } from '../utils/reconciimport { extractAgentToolName, getClaudeCodeMeta, resolveToolCall } from '../utils/toolResolver'import { parseTurnSuggestionParams } from '../utils/turnSuggestions'import { computeTurnTrailers } from '../utils/turnTrailers'-import { attachedContextLogic } from './attachedContextLogic'import { debugLogsLogic } from './debugLogsLogic'import { registerHmrStreamAbort } from './devHmrStreamAbort'import { foregroundStreamLogic } from './foregroundStreamLogic'diff --git a/products/posthog_ai/frontend/scenes/TaskTracker/components/SidePanelRunnerImpl.test.tsx b/products/posthog_ai/frontend/scenes/TaskTracker/components/SidePanelRunnerImpl.test.tsxindex ddb963498215..75af33e289be 100644--- a/products/posthog_ai/frontend/scenes/TaskTracker/components/SidePanelRunnerImpl.test.tsx+++ b/products/posthog_ai/frontend/scenes/TaskTracker/components/SidePanelRunnerImpl.test.tsx@@ -3,8 +3,9 @@ import '@testing-library/jest-dom'import { cleanup, render, screen } from '@testing-library/react'import { useActions, useValues } from 'kea'+import type { ActiveCreation } from '~/layout/ai/runnerPanelLogic'+import { useForegroundStream } from '../../../hooks/useForegroundStream'-import type { ActiveCreation } from '../../../logics/runnerPanelLogic'import { SidePanelRunnerImpl } from './SidePanelRunnerImpl'jest.mock('kea', () => ({diff --git a/products/posthog_ai/frontend/scenes/TaskTracker/components/SidePanelRunnerImpl.tsx b/products/posthog_ai/frontend/scenes/TaskTracker/components/SidePanelRunnerImpl.tsxindex 311eb2deae38..45870840032e 100644--- a/products/posthog_ai/frontend/scenes/TaskTracker/components/SidePanelRunnerImpl.tsx+++ b/products/posthog_ai/frontend/scenes/TaskTracker/components/SidePanelRunnerImpl.tsx@@ -5,11 +5,12 @@ import { LemonDivider } from '@posthog/lemon-ui'import { cn } from 'lib/utils/css-classes'+import type { AttachedContextItem } from '~/layout/ai/attachedContext'+import { useAttachedContext } from '../../../hooks/useAttachedContext'import { useForegroundStream } from '../../../hooks/useForegroundStream'import { useThreadSkin } from '../../../hooks/useThreadSkin'import type { ComposerOverride } from '../../../logics/composerOverrideLogic'-import type { AttachedContextItem } from '../../../types/contextTypes'import { AGENT_TOOL_APPLY_BACK_CONTEXT_ITEM } from '../../../utils/posthogContextBlock'import { taskTrackerSceneLogic } from '../taskTrackerSceneLogic'import { StartupRunChat } from './StartupRunChat'diff --git a/products/posthog_ai/frontend/scenes/TaskTracker/components/StartupRunChat.tsx b/products/posthog_ai/frontend/scenes/TaskTracker/components/StartupRunChat.tsxindex f8d8314d664c..0a04de36eb8c 100644--- a/products/posthog_ai/frontend/scenes/TaskTracker/components/StartupRunChat.tsx+++ b/products/posthog_ai/frontend/scenes/TaskTracker/components/StartupRunChat.tsx@@ -1,11 +1,12 @@import { BindLogic, useActions, useValues } from 'kea'import { type MutableRefObject, useRef } from 'react'+import type { AttachedContextItem } from '~/layout/ai/attachedContext'+import { RunSurface } from 'products/posthog_ai/frontend/api/runSurface'import { RunEscapeBoundary, type RunEscapeBoundaryProps } from '../../../components/RunEscapeBoundary'import { runInteractionLogic, type RunInteractionLogicProps } from '../../../logics/runInteractionLogic'-import type { AttachedContextItem } from '../../../types/contextTypes'import { taskTrackerSceneLogic } from '../taskTrackerSceneLogic'import { TaskRunComposer } from './TaskRunComposer'diff --git a/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskRunChat.tsx b/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskRunChat.tsxindex a7849d88cc67..fa2c6da04ab1 100644--- a/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskRunChat.tsx+++ b/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskRunChat.tsx@@ -4,6 +4,8 @@ import { type MutableRefObject, useEffect, useMemo, useRef } from 'react'import { cn } from 'lib/utils/css-classes'import { userLogic } from 'scenes/userLogic'+import type { AttachedContextItem } from '~/layout/ai/attachedContext'+import { runInteractionLogic, type RunInteractionLogicProps } from 'products/posthog_ai/frontend/api/logics'// Eager, NOT the lazy `api/readableRun` facade: the runner scene is already a route-split chunk and the run// surface is its primary content, so a second `lazy()` would only add a redundant chunk fetch + Suspense@@ -17,7 +19,6 @@ import { useThreadSkin } from '../../../hooks/useThreadSkin'import { resolveRunStreamKey } from '../../../logics/retainedLogics'import { runCancellationLogic } from '../../../logics/runCancellationLogic'import type { RunContinuationHandoff } from '../../../logics/runInteractionLogic'-import type { AttachedContextItem } from '../../../types/contextTypes'import { taskDetailSceneLogic } from '../taskDetailSceneLogic'import { TaskRunComposer } from './TaskRunComposer'diff --git a/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.test.ts b/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.test.tsindex 501672bf8513..bdc49cb78205 100644--- a/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.test.ts+++ b/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.test.ts@@ -9,6 +9,7 @@ import { phaiAiComposerSeedLogic } from 'scenes/max/phaiAiComposerSeedLogic'import { aiConsentLogic } from 'scenes/settings/organization/aiConsentLogic'import { urls } from 'scenes/urls'+import { attachedContextLogic } from '~/layout/ai/attachedContextLogic'import { todaySpacesLogic } from '~/layout/today/todaySpacesLogic'import { useMocks } from '~/mocks/jest'import { initKeaTests } from '~/test/init'@@ -20,7 +21,7 @@ import {TaskRuntimeEnumApi,} from 'products/tasks/frontend/generated/api.schemas'-import { attachedContextLogic, runStreamLogic } from '../../api/logics'+import { runStreamLogic } from '../../api/logics'import { codexBillingLogic } from '../../logics/codexBillingLogic'import { composerAttachmentsLogic } from '../../logics/composerAttachmentsLogic'import { composerOverrideLogic } from '../../logics/composerOverrideLogic'diff --git a/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.ts b/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.tsindex 8175a4e05851..e94b873e637f 100644--- a/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.ts+++ b/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.ts@@ -15,6 +15,11 @@ import { projectLogic } from 'scenes/projectLogic'import { aiConsentLogic } from 'scenes/settings/organization/aiConsentLogic'import { urls } from 'scenes/urls'+import { attachedContextItemKey } from '~/layout/ai/attachedContext'+import type { AttachedContextItem } from '~/layout/ai/attachedContext'+import { attachedContextLogic } from '~/layout/ai/attachedContextLogic'+import { runnerPanelLogic } from '~/layout/ai/runnerPanelLogic'+import type { ActiveCreation } from '~/layout/ai/runnerPanelLogic'import { todaySpacesLogic } from '~/layout/today/todaySpacesLogic'import { codeInvitesCheckAccessRetrieve, tasksCreate, tasksRunCreate } from 'products/tasks/frontend/generated/api'@@ -37,7 +42,7 @@ import {} from 'products/tasks/frontend/generated/api.schemas'import type { IntegrationType } from '../../../../../frontend/src/types'-import { attachedContextItemKey, attachedContextLogic, runStreamLogic } from '../../api/logics'+import { runStreamLogic } from '../../api/logics'import type { SuggestionGroup, SuggestionItem } from '../../api/primitives'import { DEFAULT_HEADLINES, pickHeadline } from '../../api/primitives'import {@@ -54,8 +59,6 @@ import type { ComposerSeed } from '../../logics/composerSeedLogic'import { modelCatalogueLogic } from '../../logics/modelCatalogueLogic'import { runCancellationLogic } from '../../logics/runCancellationLogic'import { runInteractionLogic, type RunContinuationHandoff } from '../../logics/runInteractionLogic'-import { runnerPanelLogic } from '../../logics/runnerPanelLogic'-import type { ActiveCreation } from '../../logics/runnerPanelLogic'import { taskDefaultsLogic } from '../../logics/taskDefaultsLogic'import { taskRunDefaultsLogic } from '../../logics/taskRunDefaultsLogic'import { tasksLogic } from '../../logics/tasksLogic'@@ -63,7 +66,6 @@ import { taskWarmLogic } from '../../logics/taskWarmLogic'import type { WarmLease, WarmSubmission } from '../../logics/taskWarmLogic'import { toolStreamEventsLogic } from '../../logics/toolStreamEventsLogic'import { welcomeOverrideLogic } from '../../logics/welcomeOverrideLogic'-import type { AttachedContextItem } from '../../types/contextTypes'import type { RepositoryConfig, Task } from '../../types/taskTypes'import type { TaskListParams } from '../../types/taskTypes'import { uploadRunAttachments, uploadStagedTaskAttachments } from '../../utils/artifactUpload'@@ -81,7 +83,7 @@ import { DEFAULT_COMPOSER_MODE, getModesForRuntimeAdapter, type PermissionMode }import { wrapWithPosthogContext } from '../../utils/posthogContextBlock'import { submitWithWarmRunRetry } from '../../utils/warmRunSubmission'-export type { ActiveCreation } from '../../logics/runnerPanelLogic'+export type { ActiveCreation } from '~/layout/ai/runnerPanelLogic'class CloudTargetUnresolvedError extends Error {}diff --git a/products/posthog_ai/frontend/utils/posthogContextBlock.test.ts b/products/posthog_ai/frontend/utils/posthogContextBlock.test.tsindex c9600aaa155f..2df2214a2b29 100644--- a/products/posthog_ai/frontend/utils/posthogContextBlock.test.ts+++ b/products/posthog_ai/frontend/utils/posthogContextBlock.test.ts@@ -1,5 +1,6 @@+import type { AttachedContextItem } from '~/layout/ai/attachedContext'+import { splitUserMessageContent, unwrapUserMessageContent } from '../logics/runStreamLogic'-import type { AttachedContextItem } from '../types/contextTypes'import {AGENT_TOOL_APPLY_BACK_CONTEXT_ITEM,contextItemLine,diff --git a/products/posthog_ai/frontend/utils/posthogContextBlock.ts b/products/posthog_ai/frontend/utils/posthogContextBlock.tsindex dd766a494d42..60aba6c056c5 100644--- a/products/posthog_ai/frontend/utils/posthogContextBlock.ts+++ b/products/posthog_ai/frontend/utils/posthogContextBlock.ts@@ -1,4 +1,4 @@-import type { AttachedContextItem } from '../types/contextTypes'+import type { AttachedContextItem } from '~/layout/ai/attachedContext'/*** Standing instruction attached by the sidebar (foreground) surfaces — the ones wherediff --git a/products/product_analytics/frontend/insights/editor/EditorFilters.test.tsx b/products/product_analytics/frontend/insights/editor/EditorFilters.test.tsxindex 47b0029b2ad2..aa3b137977d0 100644--- a/products/product_analytics/frontend/insights/editor/EditorFilters.test.tsx+++ b/products/product_analytics/frontend/insights/editor/EditorFilters.test.tsx@@ -9,6 +9,7 @@ import { insightDataLogic } from 'scenes/insights/insightDataLogic'import { insightLogic } from 'scenes/insights/insightLogic'import { insightVizDataLogic } from 'scenes/insights/insightVizDataLogic'+import { attachedContextLogic } from '~/layout/ai/attachedContextLogic'import { useMocks } from '~/mocks/jest'import {FunnelsQuery,@@ -22,7 +23,6 @@ import {import { initKeaTests } from '~/test/init'import { BaseMathType, InsightShortId } from '~/types'-import { attachedContextLogic } from 'products/posthog_ai/frontend/api/logics'import { funnelDataLogic } from 'products/product_analytics/frontend/insights/funnels/funnelDataLogic'import { EditorFilters } from './EditorFilters'diff --git a/products/signals/frontend/inbox/components/detail/DiscussReportButton.test.tsx b/products/signals/frontend/inbox/components/detail/DiscussReportButton.test.tsxindex dfa2e492a593..feb5226aaba6 100644--- a/products/signals/frontend/inbox/components/detail/DiscussReportButton.test.tsx+++ b/products/signals/frontend/inbox/components/detail/DiscussReportButton.test.tsx@@ -8,13 +8,12 @@ import { FEATURE_FLAGS } from 'lib/constants'import { featureFlagLogic } from 'lib/logic/featureFlagLogic'import { REPORT_AI_PANEL } from '~/layout/ai/aiPanelIds'+import { attachedContextLogic } from '~/layout/ai/attachedContextLogic'import { sidePanelStateLogic } from '~/layout/navigation-3000/sidepanel/sidePanelStateLogic'import { useMocks } from '~/mocks/jest'import { initKeaTests } from '~/test/init'import { SidePanelTab } from '~/types'-import { attachedContextLogic } from 'products/posthog_ai/frontend/api/logics'-import { captureInboxReportAction } from '../../inboxAnalytics'import {FIX_CI_REQUEST,diff --git a/products/signals/frontend/inbox/components/detail/ImplementButton.test.tsx b/products/signals/frontend/inbox/components/detail/ImplementButton.test.tsxindex fa84ea5da381..3c4f098b5387 100644--- a/products/signals/frontend/inbox/components/detail/ImplementButton.test.tsx+++ b/products/signals/frontend/inbox/components/detail/ImplementButton.test.tsx@@ -7,10 +7,10 @@ import { expectLogic } from 'kea-test-utils'import { copyToClipboard } from 'lib/utils/copyToClipboard'+import { runnerPanelLogic } from '~/layout/ai/runnerPanelLogic'import { useMocks } from '~/mocks/jest'import { initKeaTests } from '~/test/init'-import { runnerPanelLogic } from 'products/posthog_ai/frontend/api/logics'import { TaskRunStatus } from 'products/posthog_ai/frontend/types/taskTypes'import { mockTask } from '../../__mocks__/inboxMocks'diff --git a/products/signals/frontend/inbox/inboxTaskKickoffLogic.test.ts b/products/signals/frontend/inbox/inboxTaskKickoffLogic.test.tsindex 2d6ddba6ea2c..ffee654d55a4 100644--- a/products/signals/frontend/inbox/inboxTaskKickoffLogic.test.ts+++ b/products/signals/frontend/inbox/inboxTaskKickoffLogic.test.ts@@ -8,17 +8,14 @@ import { FEATURE_FLAGS } from 'lib/constants'import { featureFlagLogic } from 'lib/logic/featureFlagLogic'import { REPORT_AI_PANEL } from '~/layout/ai/aiPanelIds'+import { attachedContextLogic } from '~/layout/ai/attachedContextLogic'+import { runnerPanelLogic } from '~/layout/ai/runnerPanelLogic'import { sidePanelStateLogic } from '~/layout/navigation-3000/sidepanel/sidePanelStateLogic'import { useMocks } from '~/mocks/jest'import { initKeaTests } from '~/test/init'import { SidePanelTab } from '~/types'-import {- attachedContextLogic,- runnerPanelLogic,- runStreamLogic,- taskRunDefaultsLogic,-} from 'products/posthog_ai/frontend/api/logics'+import { runStreamLogic, taskRunDefaultsLogic } from 'products/posthog_ai/frontend/api/logics'import { makeReport } from './__mocks__/inboxMocks'import {diff --git a/products/signals/frontend/inbox/inboxTaskKickoffLogic.ts b/products/signals/frontend/inbox/inboxTaskKickoffLogic.tsindex d37f36d18ef9..49eb986a8655 100644--- a/products/signals/frontend/inbox/inboxTaskKickoffLogic.ts+++ b/products/signals/frontend/inbox/inboxTaskKickoffLogic.ts@@ -14,19 +14,15 @@ import { aiConsentLogic } from 'scenes/settings/organization/aiConsentLogic'import { urls } from 'scenes/urls'import { REPORT_AI_PANEL } from '~/layout/ai/aiPanelIds'+import { attachedContextItemKey } from '~/layout/ai/attachedContext'+import type { AttachedContextItem } from '~/layout/ai/attachedContext'+import { attachedContextLogic } from '~/layout/ai/attachedContextLogic'+import { runnerPanelLogic } from '~/layout/ai/runnerPanelLogic'+import type { ActiveCreation } from '~/layout/ai/runnerPanelLogic'import { sidePanelStateLogic } from '~/layout/navigation-3000/sidepanel/sidePanelStateLogic'import { SidePanelTab } from '~/types'-import {- attachedContextItemKey,- attachedContextLogic,- runnerPanelLogic,- runStreamLogic,- taskRunDefaultsLogic,- wrapWithPosthogContext,-} from 'products/posthog_ai/frontend/api/logics'-import type { ActiveCreation } from 'products/posthog_ai/frontend/api/logics'-import type { AttachedContextItem } from 'products/posthog_ai/frontend/api/types'+import { runStreamLogic, taskRunDefaultsLogic, wrapWithPosthogContext } from 'products/posthog_ai/frontend/api/logics'import { submitWithWarmRunRetry } from 'products/posthog_ai/frontend/utils/warmRunSubmission'import {tasksCreate,diff --git a/products/signals/frontend/inbox/logics/inboxReportDetailLogic.test.ts b/products/signals/frontend/inbox/logics/inboxReportDetailLogic.test.tsindex 0f91184272a6..d308bf769667 100644--- a/products/signals/frontend/inbox/logics/inboxReportDetailLogic.test.ts+++ b/products/signals/frontend/inbox/logics/inboxReportDetailLogic.test.ts@@ -10,13 +10,13 @@ import { ApiConfig } from 'lib/api'import { resumeKeaLoadersErrors, silenceKeaLoadersErrors } from '~/initKea'import { REPORT_AI_PANEL } from '~/layout/ai/aiPanelIds'+import { runnerPanelLogic } from '~/layout/ai/runnerPanelLogic'import { sidePanelStateLogic } from '~/layout/navigation-3000/sidepanel/sidePanelStateLogic'import { useMocks } from '~/mocks/jest'import type { MockResolverInfo } from '~/mocks/utils'import { initKeaTests } from '~/test/init'import { SidePanelTab } from '~/types'-import { runnerPanelLogic } from 'products/posthog_ai/frontend/api/logics'import { TaskRunStatus } from 'products/posthog_ai/frontend/types/taskTypes'import type { SignalReportCheckApi } from 'products/signals/frontend/generated/api.schemas'diff --git a/products/signals/frontend/inbox/logics/scoutAiLogic.test.ts b/products/signals/frontend/inbox/logics/scoutAiLogic.test.tsindex c5e7f0f805dc..89a62c32f9c6 100644--- a/products/signals/frontend/inbox/logics/scoutAiLogic.test.ts+++ b/products/signals/frontend/inbox/logics/scoutAiLogic.test.ts@@ -5,12 +5,12 @@ import { expectLogic } from 'kea-test-utils'import { phaiSidePanelComposerSeedLogic } from 'scenes/max/phaiSidePanelComposerSeedLogic'import { SCOUT_AI_PANEL } from '~/layout/ai/aiPanelIds'+import { attachedContextLogic } from '~/layout/ai/attachedContextLogic'import { sidePanelStateLogic } from '~/layout/navigation-3000/sidepanel/sidePanelStateLogic'import { useMocks } from '~/mocks/jest'import { initKeaTests } from '~/test/init'import { SidePanelTab } from '~/types'-import { attachedContextLogic } from 'products/posthog_ai/frontend/api/logics'import { taskTrackerSceneLogic } from 'products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic'import { scoutAiContextItems, scoutAiLogic } from './scoutAiLogic'diff --git a/products/signals/frontend/inbox/logics/scoutAiLogic.ts b/products/signals/frontend/inbox/logics/scoutAiLogic.tsindex 938b663d858d..a230aeaf999f 100644--- a/products/signals/frontend/inbox/logics/scoutAiLogic.ts+++ b/products/signals/frontend/inbox/logics/scoutAiLogic.ts@@ -5,12 +5,14 @@ import { lemonToast } from '@posthog/lemon-ui'import { aiConsentLogic } from 'scenes/settings/organization/aiConsentLogic'import { SCOUT_AI_PANEL } from '~/layout/ai/aiPanelIds'+import type { AttachedContextItem } from '~/layout/ai/attachedContext'+import { runnerPanelLogic } from '~/layout/ai/runnerPanelLogic'+import type { ActiveCreation } from '~/layout/ai/runnerPanelLogic'import { sidePanelStateLogic } from '~/layout/navigation-3000/sidepanel/sidePanelStateLogic'import { SidePanelTab } from '~/types'-import { composerSeedLogic, runnerPanelLogic } from 'products/posthog_ai/frontend/api/logics'-import type { ActiveCreation, ComposerSeed } from 'products/posthog_ai/frontend/api/logics'-import type { AttachedContextItem } from 'products/posthog_ai/frontend/api/types'+import { composerSeedLogic } from 'products/posthog_ai/frontend/api/logics'+import type { ComposerSeed } from 'products/posthog_ai/frontend/api/logics'import { REPORT_AI_PANEL_ID } from '../inboxTaskKickoffLogic'import { aiConsentDisabledReason } from '../utils/aiConsent'diff --git a/products/tracing/frontend/tracingAgentContext.ts b/products/tracing/frontend/tracingAgentContext.tsindex 8671b13caabf..770f35009a0d 100644--- a/products/tracing/frontend/tracingAgentContext.ts+++ b/products/tracing/frontend/tracingAgentContext.ts@@ -1,3 +1,4 @@+import { AttachedContextItem } from '~/layout/ai/attachedContext'import { DateRange } from '~/queries/schema/schema-general'import {FilterLogicalOperator,@@ -7,8 +8,6 @@ import {UniversalFiltersGroupValue,} from '~/types'-import { AttachedContextItem } from 'products/posthog_ai/frontend/api/types'-import {DEFAULT_DATE_RANGE,DEFAULT_ORDER_BY,diff --git a/products/workflows/frontend/Broadcasts/broadcastAgentContext.ts b/products/workflows/frontend/Broadcasts/broadcastAgentContext.tsindex eae9bf1a92ca..21d23e818b56 100644--- a/products/workflows/frontend/Broadcasts/broadcastAgentContext.ts+++ b/products/workflows/frontend/Broadcasts/broadcastAgentContext.ts@@ -1,8 +1,9 @@import type { AiFirstSuggestion } from 'scenes/max/aiFirstCreate/AiFirstCreateScene'import { AI_FIRST_COMPOSER_OVERRIDE } from 'scenes/max/aiFirstCreate/aiFirstMode'+import { AttachedContextItem } from '~/layout/ai/attachedContext'+import type { ComposerOverride } from 'products/posthog_ai/frontend/api/logics'-import { AttachedContextItem } from 'products/posthog_ai/frontend/api/types'// Own dismiss group: a dismissal is global and never resets, so a chip closed elsewhere must not strip this page.const NEW_BROADCAST_DISMISS_GROUP = 'new-broadcast-composer'diff --git a/products/workflows/frontend/Broadcasts/useBroadcastAgentPanel.ts b/products/workflows/frontend/Broadcasts/useBroadcastAgentPanel.tsindex 5cfd81d6316d..4695e47aca53 100644--- a/products/workflows/frontend/Broadcasts/useBroadcastAgentPanel.ts+++ b/products/workflows/frontend/Broadcasts/useBroadcastAgentPanel.ts@@ -5,10 +5,10 @@ import { useDebouncedValue } from 'lib/hooks/useDebouncedValue'import { sceneAgentPanelLogic } from 'scenes/max/sceneAgentPanelLogic'import { useSceneAgentPanel } from 'scenes/max/useSceneAgentPanel'+import { AttachedContextItem } from '~/layout/ai/attachedContext'import { HogFunctionTemplateType } from '~/types'import { resolveToolCall, useToolStreamListener } from 'products/posthog_ai/frontend/api/logics'-import { AttachedContextItem } from 'products/posthog_ai/frontend/api/types'import type { HogFlow } from '../Workflows/hogflows/types'import { EMAIL_EDITOR_AGENT_HEADLINES, buildWorkflowAgentContext } from '../Workflows/workflowAgentContext'diff --git a/products/workflows/frontend/TemplateLibrary/newTemplateAgentLogic.test.ts b/products/workflows/frontend/TemplateLibrary/newTemplateAgentLogic.test.tsindex f0df68711d48..1f53c08a0a56 100644--- a/products/workflows/frontend/TemplateLibrary/newTemplateAgentLogic.test.ts+++ b/products/workflows/frontend/TemplateLibrary/newTemplateAgentLogic.test.ts@@ -7,11 +7,11 @@ import { featureFlagLogic } from 'lib/logic/featureFlagLogic'import { removeProjectIdIfPresent } from 'lib/utils/kea-router'import { maxMocks } from 'scenes/max/testUtils'+import { attachedContextItemKey } from '~/layout/ai/attachedContext'+import { attachedContextLogic } from '~/layout/ai/attachedContextLogic'import { useMocks } from '~/mocks/jest'import { initKeaTests } from '~/test/init'-import { attachedContextItemKey, attachedContextLogic } from 'products/posthog_ai/frontend/api/logics'-import { newTemplateAgentLogic } from './newTemplateAgentLogic'import { PICKED_TEMPLATE_DISMISS_GROUP } from './templateAgentContext'import { MessageTemplate } from './types'diff --git a/products/workflows/frontend/TemplateLibrary/newTemplateAgentLogic.ts b/products/workflows/frontend/TemplateLibrary/newTemplateAgentLogic.tsindex 372a617cc524..475ac2af47d8 100644--- a/products/workflows/frontend/TemplateLibrary/newTemplateAgentLogic.ts+++ b/products/workflows/frontend/TemplateLibrary/newTemplateAgentLogic.ts@@ -16,8 +16,9 @@ import {import { sceneAgentPanelLogic } from 'scenes/max/sceneAgentPanelLogic'import { urls } from 'scenes/urls'-import { attachedContextItemKey, attachedContextLogic } from 'products/posthog_ai/frontend/api/logics'-import type { AttachedContextItem } from 'products/posthog_ai/frontend/api/types'+import { attachedContextItemKey } from '~/layout/ai/attachedContext'+import type { AttachedContextItem } from '~/layout/ai/attachedContext'+import { attachedContextLogic } from '~/layout/ai/attachedContextLogic'import {PICKED_TEMPLATE_DISMISS_GROUP,diff --git a/products/workflows/frontend/TemplateLibrary/templateAgentContext.ts b/products/workflows/frontend/TemplateLibrary/templateAgentContext.tsindex a80597224c02..7320e60eaec7 100644--- a/products/workflows/frontend/TemplateLibrary/templateAgentContext.ts+++ b/products/workflows/frontend/TemplateLibrary/templateAgentContext.ts@@ -1,6 +1,6 @@import type { AiFirstSuggestion } from 'scenes/max/aiFirstCreate/AiFirstCreateScene'-import { AttachedContextItem } from 'products/posthog_ai/frontend/api/types'+import { AttachedContextItem } from '~/layout/ai/attachedContext'import { MessageTemplate } from './types'diff --git a/products/workflows/frontend/Workflows/workflowAgentContext.ts b/products/workflows/frontend/Workflows/workflowAgentContext.tsindex 04973c6335cb..c8e9d948d62c 100644--- a/products/workflows/frontend/Workflows/workflowAgentContext.ts+++ b/products/workflows/frontend/Workflows/workflowAgentContext.ts@@ -1,10 +1,9 @@import { redactSecretHogFunctionInputs } from 'scenes/hog-functions/hog-function-utils'import type { AiFirstSuggestion } from 'scenes/max/aiFirstCreate/AiFirstCreateScene'+import { AttachedContextItem } from '~/layout/ai/attachedContext'import { CyclotronJobInputSchemaType, CyclotronJobInputType, HogFunctionTemplateType } from '~/types'-import { AttachedContextItem } from 'products/posthog_ai/frontend/api/types'-import { isEmailAction, isFunctionAction, isTriggerFunction } from './hogflows/steps/types'import type { HogFlow } from './hogflows/types'