: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
feat(phai): add context injection and tool stream events to agent surface (#68671)
Georgiy Tarasovd367246cd304
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 27c354bc478b..90427d37fd06 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -4686,10 +4686,10 @@ snapshots:hash: v1.k794b7964.de4a523033a10250834aa0917403e6ec61e3d3cdd99300830676e6ba81869e5b.AD54AJl9xbBHB2tql3MqC62FAcU85AgoIV4-aEgzV3sproducts-posthog-ai-composer--sticky--light:hash: v1.k794b7964.91c7a1b9be80ab39efcb23561be33d7431da793f1e254a9dc4341515603767b6.zTpu8qftYG9C2ZtNdxPVN6GAx47a4kCDE6JGUOd-UJ8- products-posthog-ai-composer--with-footer--dark:- hash: v1.k794b7964.e977c79afa7cb140f9a12a3b293a7b5f4274b0c847df0570fbd7405b2c6fe2ac.p7BBWHL-FLdmdqwtVGk_J0vB2r3rh2VapbBAr0Hk-w4- products-posthog-ai-composer--with-footer--light:- hash: v1.k794b7964.b0f44b7692f6ad25f611d7a2a33c1cfbd67b66c7c884617a09eb5c4c8f5cb887.oWsTs14NYxOkVJ_dZdLZJAvmERZeHYqYM-T4YH9AXGU+ products-posthog-ai-composer--with-header-and-footer--dark:+ hash: v1.k794b7964.22ac7c8b09740244c64d667b8632b8ab2b024a2e8a1483fe532dd8de77471785.QFjXKbpbw8aoCIy5zHmNw1sbnhwOQYwCs5nmwOthF8Y+ products-posthog-ai-composer--with-header-and-footer--light:+ hash: v1.k794b7964.5d937bb4b6cd8476bd83663f71e73e604a69a61fb9f657a90597551f88e2bb9d.VookPDeBGmEcZsM07uyiIAYxtBNUAF4YB4Yg19vFcisproducts-posthog-ai-composer--with-up-next-queue--dark:hash: v1.k794b7964.e893edaa31202a96439233ff254af446b1ae72107ca4d187a0ab27abc87db8ac.ClRtYW3AIl8tt8UNlaLx_52ymgYxs4FUUHPusEIzAs8products-posthog-ai-composer--with-up-next-queue--light:@@ -7035,41 +7035,41 @@ snapshots:scenes-app-surveys-surveyresponsekeysreference--webhook--light:hash: v1.k794b7964.d1b5990c419ba81a718674107ef032126e0931aaffee0b2214f01caf425894c8.yjpNAjkX1uJIayGtXXge8xuVCAloNPgNhPIyEeeh8wQscenes-app-tasks--empty--dark:- hash: v1.k794b7964.3e47bd16c4d484fce15fbfdc105be6d8f1b9e97c33c3e7dd6b8ff56afff35367.UyB13RT0zxd2kAaM7MAr2qFTuC9SUcvH_SxNc_3aFJA+ hash: v1.k794b7964.405b14ddafbb63e74e4ab84caebb74df15e93f9e0c3189ea38b09c5686ab0a27.bn4nO4SaVoRHgEcDMK92cTDc-r496lMPqWp3Rxh98GMscenes-app-tasks--empty--light:- hash: v1.k794b7964.e00727d83bc2a1bb8b3083d86a36cf7ee4c927b3991e5a400f13d765a2ae9d41.od0i2b5a9G1qoeHNH_Eto3O5YnGLhOQr0jAGEHV8slg+ hash: v1.k794b7964.85e94281092fa5de720ee4112e718d9b19ea6bf5d709605114d0e57e1e3d96b4.XluqXxmbbiImkXw45V6_JL5XTu6BiPBAa94JGf_scjcscenes-app-tasks--list-load-error--dark:- hash: v1.k794b7964.50671fee442d15e36b554e1c637b0f056fbc79b8d08fb099fa6899ff16243290.15wmQdQHNZuNU7a6O564_ClBLM-XoExjevBN4w7GnhA+ hash: v1.k794b7964.2ccde154bf1dea4ac1b90185d6e460c42b32e850cbe4c26f82a8762ceb9e101f.gFxzALArNZm0LkDtzpI1Fx_XGq4JI7I_4o672HQH14Mscenes-app-tasks--list-load-error--light:- hash: v1.k794b7964.14c31dffcac501f3e6d2c20677d4abb68afd33e41327bd6d0473c2fc63e9fd4e.M6YmLe31lZwDB-Ey8YkAFLwjv5F69Ne1wH2iMEPP-Xw+ hash: v1.k794b7964.f7b07dba614e290ea1dce43ebe6133cb4bc43edc308c1fbd650bbb5cd30de8a3.6dp6kYfIOxw0Wjf0wIL6Ku5Dbs3CRsSWvesMDqnQgmQscenes-app-tasks--list-with-composer--dark:- hash: v1.k794b7964.aa4fc013197a1895092a74d4ca7dfface2ff9aeee16622f571946362be3d0370.6h6kAEOA2kGH0fIIxe4vsJ-WkP8BGEMvt53-2cUokro+ hash: v1.k794b7964.615f4bcfb1a05771559291a259407f74faf0054ea165efcf0c8095f1e512cefd.19656eH56zPQYhBwOZpPMhqbx8yb3SJSRH9xs6SinHgscenes-app-tasks--list-with-composer--light:- hash: v1.k794b7964.356bb2c802befcd907f0d52081764c7b93cb29893c47e63c95c5090184da7037.Ta_k96s6qFCQU86QtM6Rgx8nMnnxZoiYL95BlrVynvg+ hash: v1.k794b7964.70bff7599903689b14cb213aba8eb589860da342d06b545ee6b30f396f991175.pwucyAD5kAaDq58K0FPhDCc2dfvjjWPptCII47BX4KMscenes-app-tasks--loading--dark:- hash: v1.k794b7964.eb6996e29eebba1b5a16aae2a3568f1341e61c9f42533c96dba831b343cba72b.qycnW8_GlLTKJuTU0r2OyHe6_KNXC7mfZO2unf0lPPE+ hash: v1.k794b7964.d4b019aefa9ec0bbf81ff43dfa82ebe2a955c1cee6205c5ac2a29e3a9d9ed658.BXEt7g1PAsmCYlW6G0k7qCCR5fM67pSJhaXgMHIoh-cscenes-app-tasks--loading--light:- hash: v1.k794b7964.f0e22f44051cdc8f0aa6e8fbae2efb8d2e672cc5c5db3ce04c9df2f3ea4b5bab.H3KRqwm7Z9X2s_IIsx7uC6IylDK5cpITlXMAzErawAk+ hash: v1.k794b7964.eb32420b1c3f34c5b23b331a458b8a68ec09ae65dcd5140c5160acf6a4158cbe.Njw4uhLNcnS5m-kgFddu5qHJJwgPYj2jgwleKc5YcIwscenes-app-tasks--mobile-list--dark:hash: v1.k794b7964.aa12d9283f2d371e340c367e042cc94b3368451aae7648d72a75604e50c32612.JvoQ6Mf3LGKxdkiERXq65fWkNggXdufEyGvsagLl5WEscenes-app-tasks--mobile-list--light:hash: v1.k794b7964.9fd49300ca0d02ce3fe8cf6ea7eb850af2f42332d19a821ac73a6108f33fd651.aHbvQ9EqCKA43njPMkK_xgXEq4rToiJ0U8zAsxjwEWAscenes-app-tasks--mobile-new-task--dark:- hash: v1.k794b7964.925ac11a122dff1a1267cb5a187720dbc2b55d5a59c03abc911a806479e0922e.bPh1Qead2VSXaMYpbE0pno5Ou3K5ik25-oaG3Lo7Tqw+ hash: v1.k794b7964.9b9c40cac551da8e7671c94761af2c1fea8d734127642b41daf0aaf83c21b95c.4GYGN5u7XrKtcu792itWe5FYthARxKS9Zj-7apPTv3Ascenes-app-tasks--mobile-new-task--light:- hash: v1.k794b7964.9a23821e9850e4d74283f7d4f2c746980c22f1cf2bdad658bdd9e3d1d1421784.cp0oGyWmClM9o2F_B7rgCmOP7yKWfM31Pc2ly27jS1s+ hash: v1.k794b7964.dcf36750497b33932f1ab4b6881c04136827a801b777e1907244a31ecf301f65.1obDifj36R2bZNd4c2YID4coIqim-oVjc6lMHJR3NGkscenes-app-tasks--mobile-task-selected--dark:hash: v1.k794b7964.db0156b3fd83b5c3494116788236075e0bc2c5ace019e4c1d9947d2b21fa70fb.4HfTdy-PBBkgEn0HFlUkrJm0D6GCiujf_ljrGGrLrscscenes-app-tasks--mobile-task-selected--light:hash: v1.k794b7964.8de299235efc98c794efccb4501e490a0f77ee19c901ceaf672266cec2b5ada3.rce6dJ7kA184L-8c5CwwlsEO140N_TEYcHSO-_10d18scenes-app-tasks--new-task--dark:- hash: v1.k794b7964.aa4fc013197a1895092a74d4ca7dfface2ff9aeee16622f571946362be3d0370.tZEh4_RJFReOGhgSQVcUVW9J86vwlMyMVF-zayREDeQ+ hash: v1.k794b7964.615f4bcfb1a05771559291a259407f74faf0054ea165efcf0c8095f1e512cefd.QTdkNVp9PpigXRXF58NCqRYjLnSuaYUgKkUmXYW0TjYscenes-app-tasks--new-task--light:- hash: v1.k794b7964.0e397e7cdfc4a410e42550d5b32f1c35aa0936e80db93892abf9a512e2ccdc57.LIPkeVdeZP6O-0OmswsT7dC-yG8w2bLQAsdIacsNRGA+ hash: v1.k794b7964.70bff7599903689b14cb213aba8eb589860da342d06b545ee6b30f396f991175.O4Xehc7Y-Yu1boiifCE7PBntd7V8FtyxU4Z2j02by5cscenes-app-tasks--new-task-with-repository--dark:- hash: v1.k794b7964.dcb83b653f52b3054a687e52970fb533aba4ca546f2737cb3696868793b84d3a.fdb527Daknumo7offHbywTIqZxpnA6l87dQ_YSusBBI+ hash: v1.k794b7964.4b6d502eeaee532c9c1ba178f1f2226abb6e7d2d089f2d631ae4a888f5348977.fVtCTB5pGD-7HiA4yNv0bTF5ULv4pEyBYIE3uWS-CI0scenes-app-tasks--new-task-with-repository--light:- hash: v1.k794b7964.d1b78e6e62c56f49282e85ae23f7854e8684fa9defdde4b05cc85e351f9c2915.ts8hX3ptk6usg9oN-Ad-dRU95f3VwjujK_NkWdLz6lc+ hash: v1.k794b7964.7e443a53cea4d52e48e29e390bb2a78cdf1f4e6193c3aac1cabbda0700995762.l_zflCagGCjsvZpE62UkRHKbT21OOeZgKDs9l9_4TfIscenes-app-tasks--task-detail-loading--dark:hash: v1.k794b7964.bf53a39ab24e8e1b098a736ab97f08e766bae6eb89a984a594f69e0132cf0819.PFdySLAZp_qRvc6NGnoAY7G5heFL-bCBJK955hguUq8scenes-app-tasks--task-detail-loading--light:diff --git a/frontend/src/queries/nodes/InsightViz/EditorFilters.test.tsx b/frontend/src/queries/nodes/InsightViz/EditorFilters.test.tsxindex 335b62158b20..0b82547b1414 100644--- a/frontend/src/queries/nodes/InsightViz/EditorFilters.test.tsx+++ b/frontend/src/queries/nodes/InsightViz/EditorFilters.test.tsx@@ -22,6 +22,8 @@ import {import { initKeaTests } from '~/test/init'import { BaseMathType, InsightShortId } from '~/types'+import { attachedContextLogic } from 'products/posthog_ai/frontend/api/logics'+import { EditorFilters } from './EditorFilters'// MaxTool has AI integration that requires additional setup — render children directly in tests@@ -90,8 +92,10 @@ function makePathsQuery(): PathsQuery {}function setupAndRender(- query: TrendsQuery | LifecycleQuery | StickinessQuery | RetentionQuery | FunnelsQuery | PathsQuery-): void {+ query: TrendsQuery | LifecycleQuery | StickinessQuery | RetentionQuery | FunnelsQuery | PathsQuery,+ showing = true,+ embedded = false+): ReturnType<typeof render> {insightLogic(insightProps).mount()insightDataLogic(insightProps).mount()funnelDataLogic(insightProps).mount()@@ -99,10 +103,10 @@ function setupAndRender(vizDataLogic.mount()vizDataLogic.actions.updateQuerySource(query)- render(+ return render(<Provider><BindLogic logic={insightLogic} props={insightProps}>- <EditorFilters query={query} showing embedded={false} />+ <EditorFilters query={query} showing={showing} embedded={embedded} /></BindLogic></Provider>)@@ -177,6 +181,32 @@ describe('EditorFilters', () => {expect(screen.queryByText('Enable formula mode')).not.toBeInTheDocument()})+ it('only attaches query context while the editor is visible and not embedded', () => {+ const query = makeTrendsQuery()+ const { rerender } = setupAndRender(query)+ const renderEditorFilters = (showing: boolean, embedded: boolean): JSX.Element => (+ <Provider>+ <BindLogic logic={insightLogic} props={insightProps}>+ <EditorFilters query={query} showing={showing} embedded={embedded} />+ </BindLogic>+ </Provider>+ )++ expect(attachedContextLogic.findMounted()?.values.contextItems).toEqual([+ {+ type: 'insight_query',+ value: JSON.stringify(insightVizDataLogic(insightProps).values.querySource),+ label: 'Current query',+ },+ ])++ rerender(renderEditorFilters(false, false))+ expect(attachedContextLogic.findMounted()?.values.contextItems).toEqual([])++ rerender(renderEditorFilters(true, true))+ expect(attachedContextLogic.findMounted()?.values.contextItems).toEqual([])+ })+it('expands advanced options section on click', async () => {setupAndRender(makeFunnelsQuery())diff --git a/frontend/src/queries/nodes/InsightViz/EditorFiltersShell.tsx b/frontend/src/queries/nodes/InsightViz/EditorFiltersShell.tsxindex 549122dbec84..2efb68ade50f 100644--- a/frontend/src/queries/nodes/InsightViz/EditorFiltersShell.tsx+++ b/frontend/src/queries/nodes/InsightViz/EditorFiltersShell.tsx@@ -25,6 +25,8 @@ import {} from '~/queries/schema/schema-general'import { isHogQLQuery, isInsightQueryNode } from '~/queries/utils'+import { useAttachedContext } from 'products/posthog_ai/frontend/api/logics'+import { SessionAnalysisWarning } from './SessionAnalysisWarning'import { SuggestionBanner } from './SuggestionBanner'@@ -53,8 +55,12 @@ export function EditorFiltersShell({ query, showing, embedded, children }: Edito[])const { desiredSize: panelWidth, isResizeInProgress: isResizing } = useValues(resizerLogic(resizerProps))- // MaxTool should not be active when insights are embedded (e.g., in notebooks)- const maxToolActive = !embedded+ // MaxTool should not be active when its editor is hidden or embedded (e.g., in notebooks)+ const maxToolActive = showing && !embedded++ useAttachedContext([{ type: 'insight_query', value: JSON.stringify(querySource), label: 'Current query' }], {+ active: maxToolActive,+ })const QueryTypeIcon = QUERY_TYPES_METADATA[query.kind].icondiff --git a/frontend/src/scenes/dashboard/Dashboard.tsx b/frontend/src/scenes/dashboard/Dashboard.tsxindex 74f6a6617119..4777542ad393 100644--- a/frontend/src/scenes/dashboard/Dashboard.tsx+++ b/frontend/src/scenes/dashboard/Dashboard.tsx@@ -19,6 +19,8 @@ import { SceneStickyBar } from '~/layout/scenes/components/SceneStickyBar'import { ProductKey } from '~/queries/schema/schema-general'import { DashboardPlacement, DashboardType, DataColorThemeModel, QueryBasedInsightModel } from '~/types'+import { useAttachedContext } from 'products/posthog_ai/frontend/api/logics'+import { teamLogic } from '../teamLogic'import { AddInsightToDashboardModal } from './addInsightToDashboardModal/AddInsightToDashboardModal'import { addInsightToDashboardLogic } from './addInsightToDashboardModalLogic'@@ -92,6 +94,10 @@ function DashboardScene({const { reportDashboardViewed, abortAnyRunningQuery, setLayoutZoom } = useActions(dashboardLogic)const { addInsightToDashboardModalVisible } = useValues(addInsightToDashboardLogic)+ useAttachedContext(+ dashboard ? [{ type: 'dashboard', key: dashboard.id, label: dashboard.name ?? undefined }] : null+ )+useFileSystemLogView({type: 'dashboard',ref: dashboard?.id,diff --git a/frontend/src/scenes/data-warehouse/editor/QueryWindow.tsx b/frontend/src/scenes/data-warehouse/editor/QueryWindow.tsxindex 5769e375a61c..599aedbada91 100644--- a/frontend/src/scenes/data-warehouse/editor/QueryWindow.tsx+++ b/frontend/src/scenes/data-warehouse/editor/QueryWindow.tsx@@ -26,6 +26,8 @@ import { SceneTitlePanelButton } from '~/layout/scenes/components/SceneTitleSectimport { dataNodeLogic } from '~/queries/nodes/DataNode/dataNodeLogic'import { AccessControlLevel, AccessControlResourceType } from '~/types'+import { useAttachedContext } from 'products/posthog_ai/frontend/api/logics'+import { FixErrorButton } from './components/FixErrorButton'import { ConnectionSelector } from './ConnectionSelector'import { editorSizingLogic } from './editorSizingLogic'@@ -116,6 +118,12 @@ export function QueryWindow({() => getExecuteSqlToolContext(debouncedMaxToolQueryInput, debouncedMaxToolSourceQuery),[debouncedMaxToolQueryInput, debouncedMaxToolSourceQuery])++ useAttachedContext(+ [{ type: 'sql_editor_state', value: JSON.stringify(executeSqlToolContext), label: 'Current query' }],+ { active: mode === SQLEditorMode.Embedded && showQueryPanel }+ )+const executeSqlToolContextDescription = useMemo(() => ({text: 'Current query',diff --git a/frontend/src/scenes/data-warehouse/editor/SQLEditor.tsx b/frontend/src/scenes/data-warehouse/editor/SQLEditor.tsxindex 7bd3a3111063..b9ddb39f584d 100644--- a/frontend/src/scenes/data-warehouse/editor/SQLEditor.tsx+++ b/frontend/src/scenes/data-warehouse/editor/SQLEditor.tsx@@ -32,6 +32,8 @@ import { displayLogic } from '~/queries/nodes/DataVisualization/displayLogic'import { applyDataVisualizationQueryUpdate } from '~/queries/nodes/DataVisualization/queryUpdateUtils'import { AccessControlLevel, AccessControlResourceType } from '~/types'+import { useAttachedContext } from 'products/posthog_ai/frontend/api/logics'+import { dataWarehouseViewsLogic } from '../saved_queries/dataWarehouseViewsLogic'import { ViewLinkModal } from '../ViewLinkModal'import { connectionSelectorLogic } from './connectionSelectorLogic'@@ -378,6 +380,14 @@ function SQLEditorSceneTitle(): JSX.Element | null {const { response, responseError, responseLoading } = useValues(dataNodeLogic)const { updatingDataWarehouseSavedQuery } = useValues(dataWarehouseViewsLogic)+ useAttachedContext([+ {+ type: 'sql_editor_state',+ value: JSON.stringify(getExecuteSqlToolContext(queryInput, sourceQuery)),+ label: 'Current query',+ },+ ])+const saveAsViewAccessDisabledReason = getAccessControlDisabledReason(AccessControlResourceType.WarehouseObjects,AccessControlLevel.Editordiff --git a/frontend/src/scenes/experiments/components/SummarizeExperimentButton.tsx b/frontend/src/scenes/experiments/components/SummarizeExperimentButton.tsxindex 1a7aaf6360f0..2afad5ab0f64 100644--- a/frontend/src/scenes/experiments/components/SummarizeExperimentButton.tsx+++ b/frontend/src/scenes/experiments/components/SummarizeExperimentButton.tsx@@ -11,6 +11,8 @@ import { useMaxTool } from 'scenes/max/useMaxTool'import { iconForType } from '~/layout/panel-layout/ProjectTree/defaultTree'import { ProductIntentContext, ProductKey } from '~/queries/schema/schema-general'+import { useAttachedContext } from 'products/posthog_ai/frontend/api/logics'+import { experimentLogic } from '../experimentLogic'import { isLaunched } from '../experimentsLogic'@@ -85,6 +87,12 @@ function useExperimentSummaryMaxTool(): ReturnType<typeof useMaxTool> {},})+ useAttachedContext(+ shouldShowMaxSummaryTool+ ? [{ type: 'experiment', key: experiment.id, label: experiment.name || 'Unnamed experiment' }]+ : null+ )+return maxToolResult}diff --git a/frontend/src/scenes/experiments/hooks/useSessionReplaySummaryMaxTool.ts b/frontend/src/scenes/experiments/hooks/useSessionReplaySummaryMaxTool.tsindex cee5bd08cff5..ba3f01351ab1 100644--- a/frontend/src/scenes/experiments/hooks/useSessionReplaySummaryMaxTool.ts+++ b/frontend/src/scenes/experiments/hooks/useSessionReplaySummaryMaxTool.ts@@ -6,6 +6,8 @@ import { useMaxTool } from 'scenes/max/useMaxTool'import { iconForType } from '~/layout/panel-layout/ProjectTree/defaultTree'+import { useAttachedContext } from 'products/posthog_ai/frontend/api/logics'+import { experimentLogic } from '../experimentLogic'import { isLaunched } from '../experimentsLogic'@@ -64,5 +66,11 @@ export const useSessionReplaySummaryMaxTool = (): ReturnType<typeof useMaxTool>},})+ useAttachedContext(+ shouldShowButton+ ? [{ type: 'experiment', key: experiment.id, label: experiment.name || 'Unnamed experiment' }]+ : null+ )+return maxToolResult}diff --git a/frontend/src/scenes/hog-functions/configuration/components/HogFunctionCode.tsx b/frontend/src/scenes/hog-functions/configuration/components/HogFunctionCode.tsxindex 110c8da5df1f..cfcc08885786 100644--- a/frontend/src/scenes/hog-functions/configuration/components/HogFunctionCode.tsx+++ b/frontend/src/scenes/hog-functions/configuration/components/HogFunctionCode.tsx@@ -11,6 +11,8 @@ import MaxTool from 'scenes/max/MaxTool'import { iconForType } from '~/layout/panel-layout/ProjectTree/defaultTree'+import { useAttachedContext } from 'products/posthog_ai/frontend/api/logics'+import { hogFunctionConfigurationLogic } from '../hogFunctionConfigurationLogic'import { HogFunctionTemplateOptions } from './HogFunctionTemplateOptions'@@ -39,6 +41,10 @@ export function HogFunctionCode(): JSX.Element {const sourceCodeRef = useRef<HTMLDivElement>(null)+ useAttachedContext([+ { type: 'hog_code', value: JSON.stringify(configuration.hog ?? ''), label: 'Current Hog code' },+ ])+const content = (<divref={sourceCodeRef}diff --git a/frontend/src/scenes/hog-functions/configuration/components/HogFunctionInputs.tsx b/frontend/src/scenes/hog-functions/configuration/components/HogFunctionInputs.tsxindex 7b8abe57f9a5..7f18d4bb6949 100644--- a/frontend/src/scenes/hog-functions/configuration/components/HogFunctionInputs.tsx+++ b/frontend/src/scenes/hog-functions/configuration/components/HogFunctionInputs.tsx@@ -11,6 +11,8 @@ import MaxTool from 'scenes/max/MaxTool'import { iconForType } from '~/layout/panel-layout/ProjectTree/defaultTree'import { AvailableFeature, CyclotronJobInputSchemaType } from '~/types'+import { useAttachedContext } from 'products/posthog_ai/frontend/api/logics'+import { hogFunctionConfigurationLogic } from '../hogFunctionConfigurationLogic'export function HogFunctionInputs(): JSX.Element {@@ -38,6 +40,17 @@ export function HogFunctionInputs(): JSX.Element {reportAIHogFunctionInputsPromptOpen,} = useActions(hogFunctionConfigurationLogic)+ useAttachedContext([+ {+ type: 'hog_function_inputs_schema',+ value: JSON.stringify({+ inputs_schema: configuration.inputs_schema ?? [],+ hog_code: configuration.hog ?? '',+ }),+ label: 'Current inputs schema',+ },+ ])+const content = (<div className={clsx('p-3 rounded border deprecated-space-y-2 bg-surface-primary')}><div className="deprecated-space-y-2">diff --git a/frontend/src/scenes/hog-functions/filters/HogFunctionFilters.tsx b/frontend/src/scenes/hog-functions/filters/HogFunctionFilters.tsxindex c832f664a0f2..7e06670c8ae3 100644--- a/frontend/src/scenes/hog-functions/filters/HogFunctionFilters.tsx+++ b/frontend/src/scenes/hog-functions/filters/HogFunctionFilters.tsx@@ -19,6 +19,8 @@ import MaxTool from 'scenes/max/MaxTool'import { groupsModel } from '~/models/groupsModel'import { AnyPropertyFilter, CyclotronJobFiltersType, EntityTypes, FilterType } from '~/types'+import { useAttachedContext } from 'products/posthog_ai/frontend/api/logics'+import { hogFunctionConfigurationLogic } from '../configuration/hogFunctionConfigurationLogic'import { HogFunctionFiltersInternal } from './HogFunctionFiltersInternal'@@ -98,6 +100,14 @@ export function HogFunctionFilters({reportAIFiltersPromptOpen,} = useActions(hogFunctionConfigurationLogic)+ useAttachedContext([+ {+ type: 'hog_function_filters',+ value: JSON.stringify({ filters: configuration?.filters ?? {}, function_type: type }),+ label: 'Current filters',+ },+ ])+const isTransformation = type === 'transformation'const isDataWarehouse = configuration?.filters?.source === 'data-warehouse-table'const cdpPersonUpdatesEnabled = useFeatureFlag('CDP_PERSON_UPDATES')diff --git a/frontend/src/scenes/insights/InsightScene.tsx b/frontend/src/scenes/insights/InsightScene.tsxindex 7f1bc70b4b12..d12a33de014f 100644--- a/frontend/src/scenes/insights/InsightScene.tsx+++ b/frontend/src/scenes/insights/InsightScene.tsx@@ -12,8 +12,17 @@ import { urls } from 'scenes/urls'import { NodeKind, ProductKey } from '~/queries/schema/schema-general'import { ItemMode } from '~/types'+import { useAttachedContext } from 'products/posthog_ai/frontend/api/logics'+export function InsightScene(): JSX.Element {const { insightId, insight, insightLogicRef, insightMode, dashboardId } = useValues(insightSceneLogic)++ useAttachedContext(+ insight?.short_id && insight?.query+ ? [{ type: 'insight', key: insight.short_id, label: insight.name || insight.derived_name || undefined }]+ : null+ )+useEffect(() => {// Redirect data viz nodes to the sql editorif (insightId && insight?.query?.kind === NodeKind.DataVisualizationNode && insightMode === ItemMode.Edit) {diff --git a/frontend/src/scenes/marketing-analytics/MarketingAnalyticsScene.tsx b/frontend/src/scenes/marketing-analytics/MarketingAnalyticsScene.tsxindex a0dd6f036233..e42eecd65343 100644--- a/frontend/src/scenes/marketing-analytics/MarketingAnalyticsScene.tsx+++ b/frontend/src/scenes/marketing-analytics/MarketingAnalyticsScene.tsx@@ -23,6 +23,7 @@ import { dataNodeCollectionLogic } from '~/queries/nodes/DataNode/dataNodeCollecimport { ProductKey } from '~/queries/schema/schema-general'import { sourcesDataLogic } from 'products/data_warehouse/frontend/shared/logics/sourcesDataLogic'+import { useAttachedContext } from 'products/posthog_ai/frontend/api/logics'import { MarketingAnalyticsFilters } from '../web-analytics/tabs/marketing-analytics/frontend/components/MarketingAnalyticsFilters/MarketingAnalyticsFilters'import { MarketingAnalyticsSourceStatusBanner } from '../web-analytics/tabs/marketing-analytics/frontend/components/MarketingAnalyticsSourceStatusBanner'@@ -273,6 +274,33 @@ const MarketingAnalyticsAIToolWrapper = ({ children }: { children: React.ReactNouseMaxTool({ identifier: 'marketing_suggest_conversion_goals', context: maxContext, active: aiEnabled })useMaxTool({ identifier: 'marketing_suggest_utm_mappings', context: maxContext, active: aiEnabled })+ useAttachedContext(+ [+ {+ type: 'marketing_analytics_filters',+ value: JSON.stringify({ integrationFilter, compareFilter }),+ label: 'Current filters',+ },+ {+ type: 'marketing_analytics_date_range',+ value: JSON.stringify({ date_from: dateFilter.dateFrom, date_to: dateFilter.dateTo }),+ label: 'Date range',+ },+ {+ type: 'marketing_analytics_config_counts',+ value: JSON.stringify({+ custom_source_mappings_count: Object.keys(marketingAnalyticsConfig?.custom_source_mappings || {})+ .length,+ campaign_name_mappings_count: Object.keys(marketingAnalyticsConfig?.campaign_name_mappings || {})+ .length,+ existing_goal_count: (conversion_goals || []).length,+ }),+ label: 'Marketing config counts',+ },+ ],+ { active: aiEnabled }+ )+return (<MaxToolidentifier="marketing_diagnose_setup"diff --git a/frontend/src/scenes/max/AGENTS.md b/frontend/src/scenes/max/AGENTS.mdindex 007283f96bd9..f0f9ecf57761 100644--- a/frontend/src/scenes/max/AGENTS.md+++ b/frontend/src/scenes/max/AGENTS.md@@ -70,7 +70,8 @@ The first three now live in `products/posthog_ai/frontend` (the shared surface)- **A new permission affordance / auto-approval rule** → `products/posthog_ai/frontend/policy/toolPolicy.ts`, then surface it through `PermissionInput`.- **New stream telemetry** → a guarded `posthog.capture` in the relevant `runStreamLogic` listener (fire-once, suppressed on replay).- **A new product tool renderer** (renders a PostHog entity) → `products/posthog_ai/frontend/components/tool/widgets/*` + register it in `widgets/registerDataToolRenderers` (the surface self-registers; every consumer, including Max's sandbox path, picks it up).-- **New context the agent should see** → extend `AttachedContext` (not `MaxUIContext`).+- **New context the agent should see** → register it from the owning product via the surface's context seam: `useAttachedContext` / `AttachedContextProvider` / `attachedContextLogic.registerContext` (see `products/posthog_ai/frontend/AGENTS.md` §3). Not `MaxUIContext`, and no new fields on the legacy stores. Scenes now register their on-screen context natively into that seam, and `maxThreadLogic`'s sandbox send merges the seam's items into `attached_context` — that bridge lives here and is deleted with `scenes/max`.+- **UI that reacts to the agent calling a tool** (sandbox path) → subscribe via the surface's `useToolStreamListener` / `toolStreamEventsLogic` (resolved tool names, replay suppressed by default). The legacy `useMaxTool` `callback` fires on LangGraph only.## 6. Don'tsdiff --git a/frontend/src/scenes/max/maxThreadLogic.test.ts b/frontend/src/scenes/max/maxThreadLogic.test.tsindex be88d7db9b31..a0048813987b 100644--- a/frontend/src/scenes/max/maxThreadLogic.test.ts+++ b/frontend/src/scenes/max/maxThreadLogic.test.ts@@ -30,7 +30,7 @@ import {import { initKeaTests } from '~/test/init'import { Conversation, ConversationDetail, ConversationStatus, ConversationType } from '~/types'-import { runStreamLogic } from 'products/posthog_ai/frontend/api/logics'+import { attachedContextLogic, runStreamLogic } from 'products/posthog_ai/frontend/api/logics'import { EnhancedToolCall, TOOL_DEFINITIONS } from './max-constants'import { maxContextLogic } from './maxContextLogic'@@ -3641,6 +3641,29 @@ describe('maxThreadLogic', () => {expect(openSpy).not.toHaveBeenCalled()expect(maxLogicInstance.values.activeStreamingThreads).toEqual(0)})++ it('degrades a keyed non-allowlisted context item to a text attachment instead of dropping it', async () => {+ const openSpy = jest.spyOn(api.conversations, 'open').mockResolvedValue(sandboxRunResponse)+ // initKeaTests() in beforeEach resets the kea context, so no explicit unmount is needed+ attachedContextLogic.mount()+ attachedContextLogic.actions.registerContext('test-provider', [+ { type: 'trace', key: '0189-abc', label: 'LLM trace' },+ ])++ await expectLogic(logic, () => {+ logic.actions.streamConversation(+ { agent_mode: null, is_sandbox: true, content: 'hello', conversation: MOCK_CONVERSATION_ID },+ 0+ )+ }).toDispatchActions(['openSandboxSse'])++ expect(openSpy).toHaveBeenCalledWith(+ MOCK_CONVERSATION_ID,+ expect.objectContaining({+ attached_context: expect.arrayContaining([{ type: 'text', value: 'trace 0189-abc ("LLM trace")' }]),+ })+ )+ })})describe('sandbox streamingActive teardown', () => {diff --git a/frontend/src/scenes/max/maxThreadLogic.tsx b/frontend/src/scenes/max/maxThreadLogic.tsxindex 54776d4831bf..feff7b0db29e 100644--- a/frontend/src/scenes/max/maxThreadLogic.tsx+++ b/frontend/src/scenes/max/maxThreadLogic.tsx@@ -65,6 +65,7 @@ import {} from '~/types'import {+ attachedContextLogic,getRandomThinkingMessage,isTerminalRunStatus,INITIAL_PERMISSION_MODE,@@ -713,6 +714,48 @@ export const maxThreadLogic = kea<maxThreadLogicType>([// The sandbox runtime has no agent modes — they're a legacy LangGraph concept. If the// user still picked one, carry it through as a context note so the agent can acknowledge it.const attachedContext: AttachedContext[] = [...values.sandboxAttachments]+ // Merge context from the new `attachedContextLogic` store (e.g. a future @-mention+ // picker, or trace refs only the new store knows) into the legacy send. Known entity+ // types map to `{ type, id, name }`; anything else degrades to a text item (the+ // backend validates against its fixed type set). Server-side `prune_repeated_entity_refs`+ // collapses any overlap with `sandboxAttachments`.+ const allowedEntityTypes = new Set<AttachedContext['type']>([+ 'dashboard',+ 'insight',+ 'event',+ 'action',+ 'error_tracking_issue',+ 'evaluation',+ 'notebook',+ ])+ // `findMounted` — the store is only mounted while something provides context (the+ // scene bridge or a `useAttachedContext` consumer); a bare legacy chat must not+ // fail the send over an unmounted logic.+ for (const item of attachedContextLogic.findMounted()?.values.contextItems ?? []) {+ if (+ item.type !== 'text' &&+ allowedEntityTypes.has(item.type as AttachedContext['type']) &&+ item.key != null &&+ item.key !== ''+ ) {+ attachedContext.push({+ type: item.type as AttachedContext['type'],+ id: item.key,+ name: item.label,+ })+ } else {+ // Keyed items outside the allowlist (e.g. a trace ref) carry no `value`,+ // so render their key/label the way posthogContextBlock's formatItem does.+ const keyedFallback =+ item.key != null && item.key !== ''+ ? `${item.type} ${item.key}${item.label ? ` ("${item.label}")` : ''}`+ : ''+ const fallback = item.value || keyedFallback+ if (fallback.trim()) {+ attachedContext.push({ type: 'text', value: fallback })+ }+ }+ }if (values.agentMode) {attachedContext.push({type: 'text',diff --git a/frontend/src/scenes/session-recordings/filters/RecordingsUniversalFiltersEmbed.tsx b/frontend/src/scenes/session-recordings/filters/RecordingsUniversalFiltersEmbed.tsxindex 48860df60ae6..b318635d9cbe 100644--- a/frontend/src/scenes/session-recordings/filters/RecordingsUniversalFiltersEmbed.tsx+++ b/frontend/src/scenes/session-recordings/filters/RecordingsUniversalFiltersEmbed.tsx@@ -65,6 +65,9 @@ import {UniversalFiltersGroup,} from '~/types'+import { useAttachedContext } from 'products/posthog_ai/frontend/api/logics'+import type { AttachedContextItem } from 'products/posthog_ai/frontend/api/types'+import { sessionRecordingSavedFiltersLogic } from '../filters/sessionRecordingSavedFiltersLogic'import { TimestampFormat, playerSettingsLogic } from '../player/playerSettingsLogic'import { playlistFiltersLogic } from '../playlist/playlistFiltersLogic'@@ -140,6 +143,13 @@ export const RecordingsUniversalFiltersEmbedButton = ({const { playlistTimestampFormat } = useValues(playerSettingsLogic)const { setPlaylistTimestampFormat } = useActions(playerSettingsLogic)+ useAttachedContext([+ { type: 'recording_filters', value: JSON.stringify(filters), label: 'Current filters' },+ ...(currentSessionRecordingId+ ? [{ type: 'session_recording', key: currentSessionRecordingId, label: 'Current session' } as const]+ : []),+ ] as AttachedContextItem[])+return (<><div className="flex gap-2">diff --git a/frontend/src/scenes/settings/environment/ManagedReverseProxy.tsx b/frontend/src/scenes/settings/environment/ManagedReverseProxy.tsxindex 7236b74c8707..c972ea88e6fa 100644--- a/frontend/src/scenes/settings/environment/ManagedReverseProxy.tsx+++ b/frontend/src/scenes/settings/environment/ManagedReverseProxy.tsx@@ -29,6 +29,8 @@ import { isKeyOf } from 'lib/utils/guards'import { useMaxTool } from 'scenes/max/useMaxTool'import { preflightLogic } from 'scenes/PreflightCheck/preflightLogic'+import { useAttachedContext } from 'products/posthog_ai/frontend/api/logics'+import { DiagnosticCheckResult, DiagnosticCheckStatus, DiagnosticReport, ProxyRecord, proxyLogic } from './proxyLogic'import { ProxySDKSetup } from './ProxySDKSetup'@@ -88,6 +90,19 @@ export function ManagedReverseProxy(): JSX.Element {}, [proxyRecords]),})+ useAttachedContext(+ [+ {+ type: 'proxy_records',+ value: JSON.stringify(+ proxyRecords.map((r) => ({ id: r.id, domain: r.domain, status: r.status, message: r.message }))+ ),+ label: 'Reverse proxy records',+ },+ ],+ { active: proxyRecords.length > 0 && !restrictionReason }+ )+const columns: LemonTableColumns<ProxyRecord> = [{title: 'Domain',diff --git a/frontend/src/scenes/surveys/components/AnalyzeResponsesButton.tsx b/frontend/src/scenes/surveys/components/AnalyzeResponsesButton.tsxindex 03d909949d3f..2f41d00c01dc 100644--- a/frontend/src/scenes/surveys/components/AnalyzeResponsesButton.tsx+++ b/frontend/src/scenes/surveys/components/AnalyzeResponsesButton.tsx@@ -12,6 +12,8 @@ import { surveyLogic } from 'scenes/surveys/surveyLogic'import { iconForType } from '~/layout/panel-layout/ProjectTree/defaultTree'import { ProductIntentContext, ProductKey } from '~/queries/schema/schema-general'+import { useAttachedContext } from 'products/posthog_ai/frontend/api/logics'+const NUM_OF_RESPONSES_FOR_MAX_ANALYSIS_TOOL = 5function useSurveyAnalysisMaxTool(): ReturnType<typeof useMaxTool> {@@ -31,6 +33,19 @@ function useSurveyAnalysisMaxTool(): ReturnType<typeof useMaxTool> {return totalResponses >= NUM_OF_RESPONSES_FOR_MAX_ANALYSIS_TOOL}, [formattedOpenEndedResponses])+ useAttachedContext(+ shouldShowMaxAnalysisTool+ ? [+ { type: 'survey', key: survey.id, label: survey.name },+ {+ type: 'survey_open_ended_responses',+ value: JSON.stringify(formattedOpenEndedResponses),+ label: 'Open-ended responses',+ },+ ]+ : null+ )+return useMaxTool({identifier: 'analyze_survey_responses',context: maxToolContext,diff --git a/frontend/src/scenes/surveys/components/SurveyOpportunityButton.tsx b/frontend/src/scenes/surveys/components/SurveyOpportunityButton.tsxindex ec98eb10bd8f..849f01f88986 100644--- a/frontend/src/scenes/surveys/components/SurveyOpportunityButton.tsx+++ b/frontend/src/scenes/surveys/components/SurveyOpportunityButton.tsx@@ -25,6 +25,8 @@ import {} from '~/queries/schema/schema-general'import { InsightLogicProps } from '~/types'+import { useAttachedContext } from 'products/posthog_ai/frontend/api/logics'+import { SURVEY_CREATED_SOURCE } from '../constants'import { QuickSurveyType } from '../quick-create/types'import { QuickSurveyModal } from '../QuickSurveyModal'@@ -104,6 +106,22 @@ export function SurveyOpportunityButton({},})+ useAttachedContext(+ funnelContext+ ? [+ { type: 'insight', key: insight.id, label: funnelContext.insightName },+ {+ type: 'survey_opportunity_funnel_context',+ value: JSON.stringify({+ conversionRate: funnelContext.conversionRate,+ steps: funnelContext.steps,+ }),+ label: 'Funnel conversion context',+ },+ ]+ : null+ )+const handleClick = (): void => {posthog.capture('survey opportunity clicked', {linked_insight_id: insight.id,diff --git a/frontend/src/scenes/web-analytics/WebAnalyticsFilters.tsx b/frontend/src/scenes/web-analytics/WebAnalyticsFilters.tsxindex f56edf050b31..37e7c8ab04fa 100644--- a/frontend/src/scenes/web-analytics/WebAnalyticsFilters.tsx+++ b/frontend/src/scenes/web-analytics/WebAnalyticsFilters.tsx@@ -34,6 +34,8 @@ import { shareNudgeLogic } from 'scenes/web-analytics/shareNudgeLogic'import { ReloadAll } from '~/queries/nodes/DataNode/Reload'import { PropertyFilterType, PropertyMathType } from '~/types'+import { useAttachedContext } from 'products/posthog_ai/frontend/api/logics'+import { ProductTab, faviconUrl } from './common'import { webAnalyticsDateMapping } from './constants'import { PathCleaningToggle } from './PathCleaningToggle'@@ -162,6 +164,20 @@ const WebAnalyticsAIFilters = ({ children }: { children: JSX.Element }): JSX.Eleconst { setDates, setWebAnalyticsFilters, setIsPathCleaningEnabled, setCompareFilter } =useActions(webAnalyticsLogic)+ useAttachedContext([+ {+ type: 'web_analytics_filters',+ value: JSON.stringify({+ date_from: dateFrom,+ date_to: dateTo,+ properties: rawWebAnalyticsFilters,+ doPathCleaning: isPathCleaningEnabled,+ compareFilter,+ }),+ label: 'Current filters',+ },+ ])+return (<MaxToolidentifier="filter_web_analytics"diff --git a/products/ai_observability/frontend/customParser/useCustomParserMaxTool.ts b/products/ai_observability/frontend/customParser/useCustomParserMaxTool.tsindex d2b9030b60ef..9f4d649e0dff 100644--- a/products/ai_observability/frontend/customParser/useCustomParserMaxTool.ts+++ b/products/ai_observability/frontend/customParser/useCustomParserMaxTool.ts@@ -6,6 +6,8 @@ import { lemonToast } from '@posthog/lemon-ui'import { useMaxTool } from 'scenes/max/useMaxTool'import { teamLogic } from 'scenes/teamLogic'+import { useAttachedContext } from 'products/posthog_ai/frontend/api/logics'+import { llmAnalyticsParserRecipesCreate } from '../generated/api'import { parserRecipesLogic } from '../settings/parserRecipesLogic'import { sampleForContext } from './sampleForContext'@@ -100,6 +102,24 @@ export function useCustomParserMaxTool({[eventId, storedForMerge, input, output, tools, inputRecognized, outputRecognized, currentTeamId, loadRecipes])+ useAttachedContext(+ active+ ? [+ { type: 'llm_trace_event', key: eventId },+ {+ type: 'ai_trace_parser_context',+ value: JSON.stringify({+ event_type: isGeneration ? 'generation' : 'span',+ unrecognized,+ sample_input: sampleForContext(input),+ sample_output: sampleForContext(output),+ }),+ label: 'Trace event sample',+ },+ ]+ : null+ )+const { openMax } = useMaxTool({identifier: 'create_ai_trace_parser',active,diff --git a/products/ai_observability/frontend/evaluations/AIObservabilityEvaluation.tsx b/products/ai_observability/frontend/evaluations/AIObservabilityEvaluation.tsxindex 051e91987088..9f657b42af54 100644--- a/products/ai_observability/frontend/evaluations/AIObservabilityEvaluation.tsx+++ b/products/ai_observability/frontend/evaluations/AIObservabilityEvaluation.tsx@@ -29,6 +29,8 @@ import { InsightVizNode, NodeKind } from '~/queries/schema/schema-general'import { urls } from '~/scenes/urls'import { AccessControlLevel, AccessControlResourceType, ChartDisplayType, HogQLMathType } from '~/types'+import { useAttachedContext } from 'products/posthog_ai/frontend/api/logics'+import { getModelPickerFooterLink, ModelPicker } from '../ModelPicker'import { modelPickerLogic } from '../modelPickerLogic'import { providerKeyStateIssueDescription, providerLabel } from '../settings/providerKeyStateUtils'@@ -83,6 +85,10 @@ export function AIObservabilityEvaluation(): JSX.Element {const triggersRef = useRef<HTMLDivElement>(null)const settingsUrl = combineUrl(urls.aiObservabilityEvaluations(), { ...searchParams, tab: 'settings' }).url+ useAttachedContext(+ evaluation ? [{ type: 'evaluation', key: evaluation.id || 'new', label: evaluation.name ?? undefined }] : null+ )+if (evaluationLoading) {return <LemonSkeleton className="w-full h-96" />}diff --git a/products/error_tracking/frontend/components/IssueFilteringTool.tsx b/products/error_tracking/frontend/components/IssueFilteringTool.tsxindex 9ccddd76f146..9d4689dcd13a 100644--- a/products/error_tracking/frontend/components/IssueFilteringTool.tsx+++ b/products/error_tracking/frontend/components/IssueFilteringTool.tsx@@ -8,6 +8,8 @@ import MaxTool from 'scenes/max/MaxTool'import { ErrorTrackingIssueFilteringToolOutput } from '~/queries/schema/schema-general'import { FilterLogicalOperator, UniversalFiltersGroup } from '~/types'+import { useAttachedContext } from 'products/posthog_ai/frontend/api/logics'+import { errorTrackingSceneLogic } from '../scenes/ErrorTrackingScene/errorTrackingSceneLogic'import { TAXONOMIC_FILTER_LOGIC_KEY, TAXONOMIC_GROUP_TYPES } from './IssueFilters/consts'import { issueFiltersLogic } from './IssueFilters/issueFiltersLogic'@@ -75,6 +77,8 @@ export function ErrorTrackingIssueFilteringTool(): JSX.Element {}))+ useAttachedContext([{ type: 'error_tracking_query', value: JSON.stringify(query), label: 'Current filters' }])+const callback = (update: ErrorTrackingIssueFilteringToolOutput): void => {if (update.orderBy) {setOrderBy(update.orderBy)diff --git a/products/error_tracking/frontend/scenes/ErrorTrackingIssueScene/ErrorTrackingIssueScene.tsx b/products/error_tracking/frontend/scenes/ErrorTrackingIssueScene/ErrorTrackingIssueScene.tsxindex cdc680786047..00be330ed2c5 100644--- a/products/error_tracking/frontend/scenes/ErrorTrackingIssueScene/ErrorTrackingIssueScene.tsx+++ b/products/error_tracking/frontend/scenes/ErrorTrackingIssueScene/ErrorTrackingIssueScene.tsx@@ -31,6 +31,8 @@ import { SceneMenuBar, SceneMenuBarItem, SceneMenuBarMenu } from '~/layout/sceneimport { SceneTitleSection } from '~/layout/scenes/components/SceneTitleSection'import { FilterLogicalOperator, PropertyFilterType, PropertyOperator, ReplayTabs } from '~/types'+import { useAttachedContext } from 'products/posthog_ai/frontend/api/logics'+import { PostHogSDKIssueBanner } from '../../components/Banners/PostHogSDKIssueBanner'import { BreakdownsChart } from '../../components/Breakdowns/BreakdownsChart'import { BreakdownsSearchBar } from '../../components/Breakdowns/BreakdownsSearchBar'@@ -75,6 +77,10 @@ export function ErrorTrackingIssueScene(): JSX.Element {const sceneMenuBarEnabled = useFeatureFlag('SCENE_MENU_BAR')const hasIssueSplitting = useFeatureFlag('ERROR_TRACKING_ISSUE_SPLITTING')+ useAttachedContext(+ issueId ? [{ type: 'error_tracking_issue', key: issueId, label: issue?.name ?? undefined }] : null+ )+useEffect(() => {const utmSource = new URLSearchParams(window.location.search).get('utm_source')posthog.capture('error_tracking_issue_viewed', {diff --git a/products/posthog_ai/backend/context_wrapper.py b/products/posthog_ai/backend/context_wrapper.pyindex f888625afc70..d7ae4ad368ca 100644--- a/products/posthog_ai/backend/context_wrapper.py+++ b/products/posthog_ai/backend/context_wrapper.py@@ -116,6 +116,16 @@ class ContextService:lines.append("</posthog_context>")return "\n".join(lines)+ @staticmethod+ def _defang(text: str | int) -> str:+ """Invariant: interpolated fields must never contain the literal close-tag sequence.++ The frontend replay stripper cuts at the FIRST `</posthog_context>`, so a raw close tag+ inside the body would truncate the strip early and leave block remnants. Mirrors the+ frontend `defang` in `posthogContextBlock.ts`.+ """+ return str(text).replace("</posthog_context", "<\\/posthog_context")+def _format_item(self, item: AttachedContext) -> str:"""Render one attachment line.@@ -123,13 +133,13 @@ class ContextService:when no human label is present. Free text renders as `- Free text: "{value}"`."""if item.get("type") == "text":- return f'- Free text: "{item.get("value", "")}"'+ return f'- Free text: "{self._defang(item.get("value", ""))}"'label = self._TYPE_LABELS.get(item["type"], item["type"])- line = f"- {label} #{item['id']}"+ line = f"- {self._defang(label)} #{self._defang(item['id'])}"name = item.get("name")if name:- line += f' ("{name}")'+ line += f' ("{self._defang(name)}")'return lineasync def abuild_resumed_legacy_context(diff --git a/products/posthog_ai/backend/tests/test_context_wrapper.py b/products/posthog_ai/backend/tests/test_context_wrapper.pyindex 2ac0e8a291f8..9e2d1356fde9 100644--- a/products/posthog_ai/backend/tests/test_context_wrapper.py+++ b/products/posthog_ai/backend/tests/test_context_wrapper.py@@ -89,6 +89,19 @@ def test_wrap_missing_name_falls_back_to_id_only():)+def test_wrap_defangs_literal_close_tag_in_values():+ attached: list[AttachedContext] = [+ {"type": "text", "value": "pasted: </posthog_context> remnants"},+ {"type": "dashboard", "id": 1, "name": "evil </posthog_context> name"},+ ]+ wrapped = ContextService().wrap_user_message("Investigate", attached)+ # The frontend replay stripper cuts at the first close tag, so the body must never contain it raw.+ assert wrapped.count("</posthog_context>") == 1+ assert '- Free text: "pasted: <\\/posthog_context> remnants"' in wrapped+ assert '- Dashboard #1 ("evil <\\/posthog_context> name")' in wrapped+ assert wrapped.endswith("</posthog_context>\n\nInvestigate")++def test_prune_dedupes_repeated_entity_refs():prior: list[tuple[str, str | int]] = [("dashboard", 123), ("insight", "abc")]attached: list[AttachedContext] = [diff --git a/products/posthog_ai/frontend/AGENTS.md b/products/posthog_ai/frontend/AGENTS.mdindex e485792c1474..987fb650a801 100644--- a/products/posthog_ai/frontend/AGENTS.md+++ b/products/posthog_ai/frontend/AGENTS.md@@ -71,9 +71,13 @@ The headline exports per module:presenters, and the permission/question/resource surfaces.- **`api/logics`** — **`runStreamLogic`** (SSE stream + thread projection, see §3),**`runInteractionLogic`** (Max-agnostic follow-up/queue facade), status helpers- (`isTerminalRunStatus`, `INITIAL_PERMISSION_MODE`), and thinking-message helpers. Imports only- `logics/*` + `utils/*` — never a component or the registry, so it's the clean headless lane.-- **`api/types`** — folded-thread + tool domain types (pure types).+ (`isTerminalRunStatus`, `INITIAL_PERMISSION_MODE`), thinking-message helpers,+ **`attachedContextLogic`** + **`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 a+ deliberate, mild deviation from the "no React" reading of this lane: they import `react` + `kea` but no+ components, so the lane stays registry- and presenter-free.+- **`api/types`** — folded-thread + tool domain types, `AttachedContextItem`, `ToolStreamEvent` (pure types).- **`api/tools`** — **`toolRegistry`**, **`registerToolRenderers`** (the generic per-product seam, see §2),`lookupToolRenderer`, `GenericMcpToolRenderer`, `DataToolRow`, `ToolActivity`, `FilePath`, and thediff/exec helpers. Isolated here because importing it pulls the side-effectful registry chunk.@@ -131,6 +135,44 @@ 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+(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+while the tab is hidden; `contextPickerLogic` is the exemplar) contributes+abstract `AttachedContextItem`s — `type` is an **arbitrary string** (`'insight'`, `'dashboard'`, `'trace'`,+`'text'`…; never an enumerated union), plus `key`/`label`/`value`. `contextItems` flattens and dedupes by+`${type}:${key ?? value}`. At send time the send paths (`runInteractionLogic.sendNow`/`startNewRun`,+`taskTrackerSceneLogic.submitNewTask`) wrap the outgoing message with+`wrapWithPosthogContext` (`utils/posthogContextBlock.ts`) — a `<posthog_context>` prefix that is **invisible+to the user**: the live echo (`pushHumanMessage`) carries the raw text and `unwrapUserMessageContent` strips+the block on history replay. The open/close **tags** must stay identical to the backend template+(`products/posthog_ai/backend/context_wrapper.py`) — stripping works on the tags, not the body.+The send paths prune entity refs already sent for the task (`attachedContextLogic.sentContextKeysByTask`,+keyed by task id so the dedupe survives a terminal-run send re-pointing to a fresh run, matching the+backend's `prune_repeated_entity_refs`, which dedupes across the task's whole resume chain); `text` items+are never deduped, repeated text is intentional.++**User-picked context (`logics/contextPickerLogic.ts` + `components/composer/AttachedContextBar.tsx`):** the+composer's @-affordance. `AttachedContextBar` (Tier 2, drop into `Composer.Header`, the top-of-frame row above the textarea; already wired into+`TaskComposer` and `TaskRunChat`) renders a `TaxonomicPopover` whose selections are projected to flat refs by+`taxonomicItemToAttachedContext` — no entity loading, the agent fetches details — and stored in+`contextPickerLogic`, which is just another provider (`user-picker`) on `attachedContextLogic`. The bar's chips+render **all** of `contextItems`; closing a picked chip removes it from the picker, closing any other+provider's chip dispatches `attachedContextLogic.dismissContext(key)`. Dismissal filters the key out of+`contextItems` and **survives provider re-registration** (the scene bridge upserts on every scene read — a+closed chip must not resurrect); re-picking the same item `undismissContext`s it.++**Tool-stream events (`logics/toolStreamEventsLogic.ts`):** a global bus `runStreamLogic` publishes+tool-call lifecycle events to — `phase: started/updated/completed/failed`, with `toolName` **resolved** via+`toolResolver` (inner PostHog MCP tool, e.g. `create_dashboard`). Subscribe with `useToolStreamListener({+tools, onEvent })`, or kea-natively by connecting to the bus and listening to+`toolStreamEventsLogic.actionTypes.emitToolEvent`. Replay-sourced events are suppressed unless the+subscription sets `includeReplay` (a reload must not re-trigger UI reactions). Caveat: for exec-wrapped+PostHog tools the resolved name may be `__posthog_exec_unknown__` at `started` (the `command` streams in via+updates) and is reliable by `completed` — match on `completed`, or also check `rawToolName`, when you need+certainty. Subscriber callbacks are isolated (a throwing listener is captured, never breaks ingestion).+## 4. Conventions- **Logic in the logic, never in a component.** Wire parsing, log folding, SSE handling, telemetry, and@@ -163,20 +205,24 @@ api/ # public API facade — the contract (import api/<module>, nrunSurface.ts # Tier 1: RunSurface compound (Root + slots, eager) for custom layoutsrunner.ts # Tier 1: EmbeddedRunner (lazy TaskTracker product) for inline hostsprimitives.ts # Tier 2: Composer, Thread + atoms, ThreadView, QueuedMessageList, presenters, perm/question/resource- logics.ts # Tier 3: runStreamLogic, runInteractionLogic, status + thinking helpers (headless)- types.ts # Tier 3: folded-thread + tool domain types (pure types)+ 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)tools.ts # Tier 4: toolRegistry + registerToolRenderers seam (side-effectful — isolated)components/ # RunSurfaceImpl (the RunSurface compound, heavy chunk); ReadonlyRunSurfaceImpl (prepackaged# read-only layout) + ReadonlyRunSurface (its lazy wrapper, replaces the old RunViewer.tsx);- # RunLogSkeleton (shared loader), Thread, Composer, perm/question/resource surfaces, activity, tool/- composer/ # the Composer compound+ # RunLogSkeleton (shared loader), Thread, Composer, perm/question/resource surfaces, activity, tool/;+ # AttachedContextProvider (render-null context injection wrapper)+ composer/ # the Composer compound; AttachedContextBar (@-picker + context chips)tool/ # tool registry + renderers (built-ins, generic MCP, EditDiffRenderer, diff/exec utils)widgets/ # PostHog product data-tool widgets (insight/dashboard/recordings/error-tracking/notebook/query) + registerDataToolRenderers-logics/ # runStreamLogic, runInteractionLogic; tasksLogic/taskLogic data logics (+ *LogicType.ts)+hooks/ # useAttachedContext, useToolStream — mount-scoped registration wrappers over the logics+logics/ # runStreamLogic, runInteractionLogic, attachedContextLogic, contextPickerLogic, toolStreamEventsLogic;+ # tasksLogic/taskLogic data logics (+ *LogicType.ts)policy/ # tool policy + permission/question utils-types/ # streamTypes (folded thread), wireTypes (ACP), toolTypes, taskTypes (task/run domain)+types/ # streamTypes (folded thread + ToolStreamEvent), wireTypes (ACP), contextTypes+ # (AttachedContextItem), toolTypes, taskTypes (task/run domain)messages/ # MessageTemplate, MarkdownMessage, ReasoningAnswer, AssistantFailureMessage-utils/ # thinkingMessages+utils/ # thinkingMessages, posthogContextBlock (<posthog_context> builder)lib/ # task/run helpers (parse-logs, task-status, repository, ph-debug, util-functions)scenes/ # standalone scenes registered via ../manifest.tsxTaskTracker/ # the runner scene (component, stories, scene logics, scene-specific components/)diff --git a/products/posthog_ai/frontend/README.md b/products/posthog_ai/frontend/README.mdindex 7ab398788ef2..859817475d44 100644--- a/products/posthog_ai/frontend/README.md+++ b/products/posthog_ai/frontend/README.md@@ -30,12 +30,12 @@ re-introduce the exact bundling problem the split solves. Always import an `api/Pick the **lowest tier** that does the job.-| Tier | Module | What's in it | Use when |-| ------------------------------ | --------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |-| **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 product for inline hosts) | "Just show a run" → `ReadonlyRunSurface` (inbox embeds). "Drive a run / custom layout" → `RunSurface` (tasks). "Embed the whole `/tasks` product" → `EmbeddedRunner` (Max). |-| **2 — Compound primitives** | `api/primitives` | `Thread` + atoms (`.Message/.Markdown/.Reasoning/.Failure/.Activity/.ToolCall`), `ThreadView`, `Composer.*`, `QueuedMessageList`, `RunLogSkeleton`, activity primitives + `RunActivity`, message presenters, permission/question/resource surfaces | Custom layout, or a bespoke/compact thread. |-| **3 — Headless logic + types** | `api/logics` + `api/types` | `runStreamLogic`, `runInteractionLogic`, status helpers (`isTerminalRunStatus`, `INITIAL_PERMISSION_MODE`), thinking-message helpers; folded-thread + tool types | Status badge or automation — no React, no registry. |-| **4 — Extension seam** | `api/tools` | `toolRegistry`, `registerToolRenderers`, `lookupToolRenderer`, `GenericMcpToolRenderer`, `DataToolRow`, `ToolActivity`, `FilePath`, diff helpers | Your product renders tool cards (insights, dashboards…). Register them from your own scene. |+| Tier | Module | What's in it | Use when |+| ------------------------------ | --------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |+| **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 product for inline hosts) | "Just show a run" → `ReadonlyRunSurface` (inbox embeds). "Drive a run / custom layout" → `RunSurface` (tasks). "Embed the whole `/tasks` product" → `EmbeddedRunner` (Max). |+| **2 — Compound primitives** | `api/primitives` | `Thread` + atoms (`.Message/.Markdown/.Reasoning/.Failure/.Activity/.ToolCall`), `ThreadView`, `Composer.*`, `AttachedContextBar`, `QueuedMessageList`, `RunLogSkeleton`, activity primitives + `RunActivity`, message presenters, permission/question/resource surfaces | Custom layout, or a bespoke/compact thread. |+| **3 — Headless logic + types** | `api/logics` + `api/types` | `runStreamLogic`, `runInteractionLogic`, status helpers (`isTerminalRunStatus`, `INITIAL_PERMISSION_MODE`), thinking-message helpers, context injection (`attachedContextLogic`, `useAttachedContext`, `contextPickerLogic`), tool-stream subscriptions (`toolStreamEventsLogic`, `useToolStreamListener`); folded-thread + tool types, `AttachedContextItem`, `ToolStreamEvent` | Status badge, automation, context injection, tool-event listeners — no presenters, no registry. |+| **4 — Extension seam** | `api/tools` | `toolRegistry`, `registerToolRenderers`, `lookupToolRenderer`, `GenericMcpToolRenderer`, `DataToolRow`, `ToolActivity`, `FilePath`, diff helpers | Your product renders tool cards (insights, dashboards…). Register them from your own scene. |The Tier 1 surfaces are built on `api/primitives` (Tier 2), which consumes the headless`api/logics`/`api/types` (Tier 3). Going down a tier trades convenience for control and a smaller chunk.@@ -181,6 +181,93 @@ const done = isTerminalRunStatus(currentRunStatus)No React presenters, no tool registry — this import lane stays out of those chunks.+### Inject context the agent should see++Register the resource(s) the user is looking at; while registered, every message sent from the surface is+prefixed with an invisible `<posthog_context>` block describing them (the user only ever sees their own+text). Items are abstract — `type` is any string (`'insight'`, `'trace'`, `'text'`…), plus+`key`/`label`/`value` — and are deduped across providers and across sends within a task (the whole+resume chain of runs, matching the backend's per-task semantics; except `text`, which always resends).++```tsx+import { useAttachedContext } from 'products/posthog_ai/frontend/api/logics'++// In your scene/component — registered while mounted, removed on unmount:+useAttachedContext([{ type: 'insight', key: insight.short_id, label: insight.name }])+```++JSX-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+teardown idiom — see `/using-kea-disposables`); the returned cleanup deregisters on unmount, no+`beforeUnmount` needed. Pass `pauseOnPageHidden: false`: the registration costs nothing while idle, and the+default hide-pause would silently drop context from a queued follow-up that flushes while the tab is hidden.++```ts+afterMount(({ actions, cache, values }) => {+ cache.disposables.add(+ () => {+ actions.registerContext('my-scene', [{ type: 'dashboard', key: values.dashboard.id }])+ return () => actions.deregisterContext('my-scene')+ },+ 'attachedContext',+ { pauseOnPageHidden: false }+ )+})+```++Re-dispatching `registerContext` with the same provider id (e.g. from a `subscriptions` handler when the+resource changes) is an upsert — see `logics/contextPickerLogic.ts` for the full shape.++### Let the user pick context (the composer @-affordance)++`AttachedContextBar` (`api/primitives`) is the prepackaged picker + chips row — drop it into+`Composer.Header`, the wrapping row at the top of the frame above the textarea (that's exactly what+`TaskComposer` and `TaskRunChat` do, so `/tasks` and the side panel already have it; the footer stays+free for the model/effort pickers):++```tsx+import { AttachedContextBar, Composer } from 'products/posthog_ai/frontend/api/primitives'+;<Composer.Header>+ <AttachedContextBar />+</Composer.Header>+```++The @-button opens a `TaxonomicPopover` over events/actions/insights/dashboards/notebooks/error-tracking+issues; a selection becomes a flat `{ type, key, label }` ref in `contextPickerLogic` (`api/logics`) — no+entity loading, the agent fetches details. The chips render **everything** in `contextItems`, whatever+provider contributed it. Closing a chip the picker owns removes the pick; closing any other provider's chip+dismisses that key (`attachedContextLogic.dismissContext`), which sticks even while the provider keeps+re-registering the item — re-picking it through the popover restores it.++### React to the agent invoking a tool++Subscribe to tool-call lifecycle events (resolved tool names) — e.g. refresh a list when the agent creates+a dashboard. Replay events are suppressed by default so a page reload never re-triggers your handler; opt+in with `includeReplay` if you need them.++```ts+import { useToolStreamListener } from 'products/posthog_ai/frontend/api/logics'++useToolStreamListener({+ tools: ['create_dashboard'],+ onEvent: (event) => {+ if (event.phase === 'completed') {+ loadDashboards()+ }+ },+})+```++From a kea logic, either connect to `toolStreamEventsLogic` and listen to its `emitToolEvent` action (you+filter everything yourself, including `event.source`), or register a subscription through a disposable —+same shape as the context recipe above, calling `registerToolListener(listenerId, { tools, onEvent })` in+setup and `deregisterToolListener(listenerId)` in cleanup, with `pauseOnPageHidden: false` (tool events fire+while the tab is hidden and missed live events are not redelivered).++Note: for exec-wrapped PostHog tools the resolved name can be unknown at `phase: 'started'` (the command+streams in later) — match on `completed` when you need certainty.+## 4. Coupling boundaryThis surface **couples to the tasks run API by design** (`products/tasks/frontend/generated/api`) anddiff --git a/products/posthog_ai/frontend/api/logics.ts b/products/posthog_ai/frontend/api/logics.tsindex 65d5420dc20b..fd8216afef16 100644--- a/products/posthog_ai/frontend/api/logics.ts+++ b/products/posthog_ai/frontend/api/logics.ts@@ -22,6 +22,28 @@ export { getThinkingMessageFromResponse, getRandomThinkingMessage, THINKING_MESS// --- Composer model/effort helpers (pure — no component imports) ---export { resolveEffortForModel, DEFAULT_COMPOSER_MODEL, DEFAULT_COMPOSER_EFFORT } from '../utils/composerModels'+// --- Attached-context store + injection hook (headless) ---+// Global registry of on-screen context providers; `contextItems` is what the send paths wrap into a+// `<posthog_context>` block. `useAttachedContext` registers a provider for the lifetime of a mount.+export { attachedContextLogic } from '../logics/attachedContextLogic'+export { useAttachedContext } from '../hooks/useAttachedContext'+export type { UseAttachedContextOptions } from '../hooks/useAttachedContext'+export { attachedContextItemKey } from '../types/contextTypes'++// --- User-picked context (the composer's @-affordance, headless half) ---+// `contextPickerLogic` owns explicit user picks and registers them as the `user-picker` provider;+// the `AttachedContextBar` component (Tier 2 `api/primitives`) is its prepackaged UI.+export { contextPickerLogic, taxonomicItemToAttachedContext, PICKER_PROVIDER_ID } from '../logics/contextPickerLogic'+export type { PickableTaxonomicItem } from '../logics/contextPickerLogic'++// --- Tool-stream event bus + subscription hook (headless) ---+// `runStreamLogic` publishes tool-call lifecycle events (resolved names); subscribe to react when the+// agent invokes a specific tool. `useToolStreamListener` registers a subscription for a mount's life.+export { toolStreamEventsLogic } from '../logics/toolStreamEventsLogic'+export type { ToolStreamSubscription } from '../logics/toolStreamEventsLogic'+export { useToolStreamListener } from '../hooks/useToolStream'+export type { UseToolStreamListenerOptions } from '../hooks/useToolStream'+// --- 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`).diff --git a/products/posthog_ai/frontend/api/primitives.ts b/products/posthog_ai/frontend/api/primitives.tsindex bfe9c5d250fd..2b1b73bd0edf 100644--- a/products/posthog_ai/frontend/api/primitives.ts+++ b/products/posthog_ai/frontend/api/primitives.ts@@ -11,6 +11,10 @@// Part of the `products/posthog_ai/frontend/api/<module>` public surface — import from here, not from// deep `../components/*` paths. See ../README.md for the tier model and ../AGENTS.md for the coupling rule.+// Render-null wrapper that attaches context for JSX-only call sites (the hook flavor is in api/logics).+export { AttachedContextProvider } from '../components/AttachedContextProvider'+export type { AttachedContextProviderProps } from '../components/AttachedContextProvider'+export { Composer } from '../components/composer/Composer'export type {ComposerRootProps,@@ -23,6 +27,10 @@ export type {export { ComposerModelEffortPickers } from '../components/composer/ComposerModelEffortPickers'export type { ComposerModelEffortPickersProps } from '../components/composer/ComposerModelEffortPickers'+// The composer's context affordance: @-picker (TaxonomicPopover) + removable chips over the+// attached-context store. Drop into `Composer.Header`; headless half is in api/logics.+export { AttachedContextBar } from '../components/composer/AttachedContextBar'+// Welcome header (logomark + headline + subheadline) and its overridable default headlines.export { Welcome } from '../components/welcome/Welcome'export type { WelcomeProps } from '../components/welcome/Welcome'diff --git a/products/posthog_ai/frontend/api/types.ts b/products/posthog_ai/frontend/api/types.tsindex ab8ef8955fc8..968d800a8640 100644--- a/products/posthog_ai/frontend/api/types.ts+++ b/products/posthog_ai/frontend/api/types.ts@@ -7,3 +7,5 @@ export type {ProgressStep,} from '../types/streamTypes'export type { ToolCallMessage } from '../types/toolTypes'+export type { AttachedContextItem } from '../types/contextTypes'+export type { ToolStreamEvent, ToolStreamPhase } from '../types/streamTypes'diff --git a/products/posthog_ai/frontend/components/AttachedContextProvider.tsx b/products/posthog_ai/frontend/components/AttachedContextProvider.tsxnew file mode 100644index 000000000000..3363d00626d7--- /dev/null+++ b/products/posthog_ai/frontend/components/AttachedContextProvider.tsx@@ -0,0 +1,16 @@+import { useAttachedContext } from '../hooks/useAttachedContext'+import type { AttachedContextItem } from '../types/contextTypes'++export interface AttachedContextProviderProps {+ items: AttachedContextItem[] | null+ active?: boolean+}++/**+ * Render-null wrapper over `useAttachedContext` for JSX-only call sites that can't call the hook+ * directly. Attaches `items` to the PostHog AI surface for as long as it's mounted.+ */+export function AttachedContextProvider({ items, active }: AttachedContextProviderProps): null {+ useAttachedContext(items, { active })+ return null+}diff --git a/products/posthog_ai/frontend/components/composer/AttachedContextBar.tsx b/products/posthog_ai/frontend/components/composer/AttachedContextBar.tsxnew file mode 100644index 000000000000..beb7792597aa--- /dev/null+++ b/products/posthog_ai/frontend/components/composer/AttachedContextBar.tsx@@ -0,0 +1,107 @@+import { useActions, useValues } from 'kea'++import { IconAtSign, IconBug, IconDashboard, IconGraph, IconNotebook } from '@posthog/icons'+import { LemonTag, Tooltip } from '@posthog/lemon-ui'++import { TaxonomicFilterGroupType } from 'lib/components/TaxonomicFilter/types'+import { TaxonomicPopover } from 'lib/components/TaxonomicPopover/TaxonomicPopover'+import { IconAction, IconEvent } from 'lib/lemon-ui/icons'++import { attachedContextLogic } from '../../logics/attachedContextLogic'+import { contextPickerLogic } from '../../logics/contextPickerLogic'+import { type AttachedContextItem, attachedContextItemKey } from '../../types/contextTypes'++const PICKER_GROUP_TYPES: TaxonomicFilterGroupType[] = [+ TaxonomicFilterGroupType.Events,+ TaxonomicFilterGroupType.Actions,+ TaxonomicFilterGroupType.Insights,+ TaxonomicFilterGroupType.Dashboards,+ TaxonomicFilterGroupType.Notebooks,+ TaxonomicFilterGroupType.ErrorTrackingIssues,+]++function iconForType(type: string): JSX.Element {+ switch (type) {+ case 'dashboard':+ return <IconDashboard />+ case 'insight':+ return <IconGraph />+ case 'event':+ return <IconEvent />+ case 'action':+ return <IconAction />+ case 'notebook':+ return <IconNotebook />+ case 'error_tracking_issue':+ return <IconBug />+ default:+ return <IconAtSign />+ }+}++function labelForItem(item: AttachedContextItem): string {+ if (item.label) {+ return item.label+ }+ if (item.type === 'text') {+ return item.value ?? 'Text'+ }+ return `${item.type} ${item.key ?? ''}`.trim()+}++/**+ * The composer's context affordance: an @-button (TaxonomicPopover) that attaches entity refs to+ * `contextPickerLogic`, plus removable chips for everything currently in+ * `attachedContextLogic.contextItems` — picked items and auto-registered providers (e.g. the scene+ * bridge) alike. Closing a picked chip removes it from the picker; closing any other provider's chip+ * dismisses its key, which sticks even when the provider re-registers the item.+ */+export function AttachedContextBar(): JSX.Element {+ const { contextItems, hasContext } = useValues(attachedContextLogic)+ const { dismissContext } = useActions(attachedContextLogic)+ const { pickedKeys } = useValues(contextPickerLogic)+ const { handleTaxonomicFilterChange, removePickedItem } = useActions(contextPickerLogic)++ return (+ <div className="flex flex-wrap items-center gap-1 min-w-0">+ <Tooltip title="Add context to help PostHog AI answer your question">+ {/* Wrapper span prevents Base UI's Tooltip.Trigger from merging+ props into TaxonomicPopover. Without it, mergeProps treats+ onChange as a DOM event handler and wraps it in a single-arg+ callback, dropping the groupType and item arguments. */}+ <span>+ <TaxonomicPopover+ size="xxsmall"+ type="tertiary"+ className="flex-shrink-0 border"+ groupType={TaxonomicFilterGroupType.Events}+ groupTypes={PICKER_GROUP_TYPES}+ onChange={handleTaxonomicFilterChange}+ icon={<IconAtSign className="text-secondary" />}+ placeholder={hasContext ? null : 'Add context'}+ placeholderClass="text-secondary"+ width={450}+ data-attr="posthog-ai-context-picker"+ />+ </span>+ </Tooltip>+ {contextItems.map((item) => {+ const key = attachedContextItemKey(item)+ const label = labelForItem(item)+ return (+ <Tooltip key={key} title={label}>+ <LemonTag+ icon={iconForType(item.type)}+ onClose={() => (pickedKeys.has(key) ? removePickedItem(key) : dismissContext(key))}+ closable+ closeOnClick+ className="flex items-center text-secondary max-w-48"+ >+ <span className="truncate min-w-0 flex-1">{label}</span>+ </LemonTag>+ </Tooltip>+ )+ })}+ </div>+ )+}diff --git a/products/posthog_ai/frontend/components/composer/Composer.stories.tsx b/products/posthog_ai/frontend/components/composer/Composer.stories.tsxindex 99188807f805..53f53a669501 100644--- a/products/posthog_ai/frontend/components/composer/Composer.stories.tsx+++ b/products/posthog_ai/frontend/components/composer/Composer.stories.tsx@@ -89,21 +89,24 @@ export const Sticky: Story = {],}-/** With a footer row for context chips / actions inside the frame. */-export const WithFooter: Story = {+/** Real-surface composition: context chips in the Header row at the top of the frame, actions in the Footer. */+export const WithHeaderAndFooter: Story = {render: ({ initialValue, placeholder, ...rootProps }) => {const [value, setValue] = useState(initialValue)return (<div className="w-180 mx-auto p-4"><Composer.Root value={value} onChange={setValue} onSubmit={() => setValue('')} {...rootProps}><Composer.Frame>+ <Composer.Header className="flex flex-wrap items-center gap-1">+ <LemonTag type="muted">@ Current dashboard</LemonTag>+ <LemonTag type="muted">@ Weekly signups</LemonTag>+ </Composer.Header><Composer.Field><Composer.Placeholder>{placeholder}</Composer.Placeholder><Composer.Textarea /></Composer.Field><Composer.Footer><div className="flex items-center gap-1 pl-2">- <LemonTag type="muted">@ Current dashboard</LemonTag><LemonButton size="xsmall" type="tertiary" icon={<IconGear />} tooltip="Settings" /></div></Composer.Footer>diff --git a/products/posthog_ai/frontend/components/composer/Composer.tsx b/products/posthog_ai/frontend/components/composer/Composer.tsxindex f4548a2ff20c..dc7380fb0145 100644--- a/products/posthog_ai/frontend/components/composer/Composer.tsx+++ b/products/posthog_ai/frontend/components/composer/Composer.tsx@@ -206,6 +206,18 @@ const ComposerBanner = forwardRef<HTMLDivElement, HTMLAttributes<HTMLDivElement>)})+/** The in-frame top row for context chips / attachments, above the textarea. */+const ComposerHeader = forwardRef<HTMLDivElement, HTMLAttributes<HTMLDivElement>>(function ComposerHeader(+ { className, children, ...rest },+ ref+): JSX.Element {+ return (+ <div data-slot="composer-header" ref={ref} className={cn('pt-2 px-2', className)} {...rest}>+ {children}+ </div>+ )+})+export interface ComposerFrameProps extends HTMLAttributes<HTMLLabelElement> {/** Toggles the AI focus-ring color (off while the agent is streaming, per QuestionInput). */ringActive?: boolean@@ -308,7 +320,7 @@ function ComposerTextarea({)}-/** The in-frame bottom row for context chips / actions. */+/** The in-frame bottom row for pickers / actions. */const ComposerFooter = forwardRef<HTMLDivElement, HTMLAttributes<HTMLDivElement>>(function ComposerFooter({ className, children, ...rest },ref@@ -372,6 +384,7 @@ export const Composer = Object.assign(ComposerRoot, {Root: ComposerRoot,Banner: ComposerBanner,Frame: ComposerFrame,+ Header: ComposerHeader,Field: ComposerField,Placeholder: ComposerPlaceholder,Textarea: ComposerTextarea,diff --git a/products/posthog_ai/frontend/hooks/useAttachedContext.ts b/products/posthog_ai/frontend/hooks/useAttachedContext.tsnew file mode 100644index 000000000000..8839c0614fa2--- /dev/null+++ b/products/posthog_ai/frontend/hooks/useAttachedContext.ts@@ -0,0 +1,40 @@+import { useActions } from 'kea'+import { useEffect, useMemo, useRef } from 'react'++import { uuid } from 'lib/utils/dom'++import { attachedContextLogic } from '../logics/attachedContextLogic'+import type { AttachedContextItem } from '../types/contextTypes'++export interface UseAttachedContextOptions {+ /** When false, the provider is deregistered (nothing attached). Defaults to true. */+ active?: boolean+}++/**+ * Registers `items` into the global `attachedContextLogic` under a stable per-mount provider id, so+ * the PostHog AI surface picks them up as `<posthog_context>` at send time. Re-registers when the+ * items change (memoized on their JSON shape), and deregisters on unmount or when `active: false`.+ */+export function useAttachedContext(items: AttachedContextItem[] | null, options?: UseAttachedContextOptions): void {+ const active = options?.active ?? true+ const { registerContext, deregisterContext } = useActions(attachedContextLogic)+ const providerIdRef = useRef<string>(`ctx-${uuid()}`)+ // Memo key so re-renders that produce an equal array don't churn the registry.+ const itemsKey = useMemo(() => JSON.stringify(items ?? []), [items])++ useEffect(() => {+ const providerId = providerIdRef.current+ if (!active || !items || items.length === 0) {+ deregisterContext(providerId)+ return+ }+ registerContext(providerId, items)+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [active, itemsKey, registerContext, deregisterContext])++ useEffect(() => {+ const providerId = providerIdRef.current+ return () => deregisterContext(providerId)+ }, [deregisterContext])+}diff --git a/products/posthog_ai/frontend/hooks/useToolStream.ts b/products/posthog_ai/frontend/hooks/useToolStream.tsnew file mode 100644index 000000000000..418c577f533d--- /dev/null+++ b/products/posthog_ai/frontend/hooks/useToolStream.ts@@ -0,0 +1,41 @@+import { useActions } from 'kea'+import { useEffect, useRef } from 'react'++import { uuid } from 'lib/utils/dom'++import { toolStreamEventsLogic } from '../logics/toolStreamEventsLogic'+import type { ToolStreamEvent } from '../types/streamTypes'++export interface UseToolStreamListenerOptions {+ /** Resolved tool names to match, or `'*'` for every tool. */+ tools: string[] | '*'+ onEvent: (event: ToolStreamEvent) => void+ /** When true, replay-sourced events are delivered too. Defaults to false (live only). */+ includeReplay?: boolean+}++/**+ * Subscribes to tool-call lifecycle events for the given (resolved) tool names. Registers once per+ * mount under a stable listener id; the latest `onEvent` is held in a ref so re-renders don't churn+ * the registration. Deregisters on unmount.+ */+export function useToolStreamListener({ tools, onEvent, includeReplay }: UseToolStreamListenerOptions): void {+ const { registerToolListener, deregisterToolListener } = useActions(toolStreamEventsLogic)+ const listenerIdRef = useRef<string>(`tool-listener-${uuid()}`)+ const onEventRef = useRef(onEvent)+ onEventRef.current = onEvent++ // Re-register when the matched tools or replay flag change (not on every onEvent identity change).+ const toolsKey = tools === '*' ? '*' : tools.join(',')++ useEffect(() => {+ const listenerId = listenerIdRef.current+ registerToolListener(listenerId, {+ tools,+ includeReplay,+ onEvent: (event) => onEventRef.current(event),+ })+ return () => deregisterToolListener(listenerId)+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [toolsKey, includeReplay, registerToolListener, deregisterToolListener])+}diff --git a/products/posthog_ai/frontend/logics/attachedContextLogic.test.ts b/products/posthog_ai/frontend/logics/attachedContextLogic.test.tsnew file mode 100644index 000000000000..b0e457dc78bd--- /dev/null+++ b/products/posthog_ai/frontend/logics/attachedContextLogic.test.ts@@ -0,0 +1,88 @@+import { expectLogic } from 'kea-test-utils'++import { initKeaTests } from '~/test/init'++import { attachedContextLogic } from './attachedContextLogic'++describe('attachedContextLogic', () => {+ let logic: ReturnType<typeof attachedContextLogic.build>++ beforeEach(() => {+ initKeaTests()+ logic = attachedContextLogic()+ logic.mount()+ })++ afterEach(() => {+ logic?.unmount()+ })++ it('registers and upserts a provider, and deregisters it', async () => {+ await expectLogic(logic, () => {+ logic.actions.registerContext('scene', [{ type: 'insight', key: 'a', label: 'A' }])+ }).toMatchValues({ contextItems: [{ type: 'insight', key: 'a', label: 'A' }], hasContext: true })++ // Re-register the same provider replaces its items (upsert).+ await expectLogic(logic, () => {+ logic.actions.registerContext('scene', [{ type: 'dashboard', key: 1 }])+ }).toMatchValues({ contextItems: [{ type: 'dashboard', key: 1 }] })++ await expectLogic(logic, () => {+ logic.actions.deregisterContext('scene')+ }).toMatchValues({ contextItems: [], hasContext: false })+ })++ it('dedupes across providers by `${type}:${key ?? value}` (first writer wins)', async () => {+ await expectLogic(logic, () => {+ logic.actions.registerContext('p1', [{ type: 'insight', key: 'x', label: 'first' }])+ logic.actions.registerContext('p2', [+ { type: 'insight', key: 'x', label: 'second' },+ { type: 'dashboard', key: 9 },+ ])+ }).toMatchValues({+ contextItems: [+ { type: 'insight', key: 'x', label: 'first' },+ { type: 'dashboard', key: 9 },+ ],+ })+ })++ it('drops items with neither key nor value', async () => {+ await expectLogic(logic, () => {+ logic.actions.registerContext('p', [{ type: 'insight' }, { type: 'text', value: 'keep me' }])+ }).toMatchValues({ contextItems: [{ type: 'text', value: 'keep me' }] })+ })++ // Sent-context keys are scoped per task: a global (unkeyed) store would prune context from the first+ // message of an unrelated task just because the same resource was sent from another one.+ it('accumulates sent context keys per task without leaking across tasks', async () => {+ await expectLogic(logic, () => {+ logic.actions.markContextSent('task-a', ['insight:x'])+ logic.actions.markContextSent('task-a', ['insight:x', 'dashboard:9'])+ logic.actions.markContextSent('task-b', ['insight:x'])+ }).toMatchValues({+ sentContextKeysByTask: {+ 'task-a': ['insight:x', 'dashboard:9'],+ 'task-b': ['insight:x'],+ },+ })+ })++ it('dismissal hides an item, survives provider re-registration, and undismiss restores it', async () => {+ const item = { type: 'insight', key: 'x', label: 'X' }++ await expectLogic(logic, () => {+ logic.actions.registerContext('bridge', [item])+ logic.actions.dismissContext('insight:x')+ }).toMatchValues({ contextItems: [] })++ // A provider upsert (e.g. the scene bridge re-reading the scene) must not resurrect the chip.+ await expectLogic(logic, () => {+ logic.actions.registerContext('bridge', [item])+ }).toMatchValues({ contextItems: [] })++ await expectLogic(logic, () => {+ logic.actions.undismissContext('insight:x')+ }).toMatchValues({ contextItems: [item] })+ })+})diff --git a/products/posthog_ai/frontend/logics/attachedContextLogic.ts b/products/posthog_ai/frontend/logics/attachedContextLogic.tsnew file mode 100644index 000000000000..d338aaa436cb--- /dev/null+++ b/products/posthog_ai/frontend/logics/attachedContextLogic.ts@@ -0,0 +1,115 @@+import { actions, kea, path, reducers, selectors } from 'kea'++import { type AttachedContextItem, attachedContextItemKey } from '../types/contextTypes'+import type { attachedContextLogicType } from './attachedContextLogicType'++/**+ * Global, unkeyed store of attached context for the PostHog AI surface. One mechanism only — a+ * registry of context providers, so registration and removal are symmetric and trivial. Each+ * provider (a mounted hook/component, or a future @-mention picker) owns a stable `providerId` and+ * upserts its items; `contextItems` flattens and dedupes across providers.+ *+ * A consumer reads `contextItems` at send time and wraps the outgoing message with a+ * `<posthog_context>` block (`utils/posthogContextBlock`). Nothing here is keyed by conversation —+ * the on-screen context is global to the app at any instant.+ *+ * This store also keeps the sent-context bookkeeping (`sentContextKeysByTask`): which non-text refs+ * were already wrapped into a sent message, keyed by task id. The send paths mark keys after a+ * successful send and prune already-sent refs from the next wrap. It is task-scoped (not run-scoped)+ * so the dedupe survives a terminal-run send re-pointing the consumer to a fresh run, mirroring the+ * backend's `prune_repeated_entity_refs`, which dedupes across a task's whole resume chain.+ */+export const attachedContextLogic = kea<attachedContextLogicType>([+ path(['products', 'posthog_ai', 'frontend', 'logics', 'attachedContextLogic']),++ actions({+ /** Idempotent upsert — re-register the same `providerId` to update its items. */+ registerContext: (providerId: string, items: AttachedContextItem[]) => ({ providerId, items }),+ deregisterContext: (providerId: string) => ({ providerId }),+ /** Record context item keys already wrapped into a message sent for `taskId`. */+ markContextSent: (taskId: string, keys: string[]) => ({ taskId, keys }),+ /**+ * Hide one item (by `attachedContextItemKey`) regardless of which provider contributed it —+ * the user closing a chip must stick even when the provider re-registers the same item+ * (e.g. the scene bridge upserting on every scene read).+ */+ dismissContext: (key: string) => ({ key }),+ undismissContext: (key: string) => ({ key }),+ }),++ reducers({+ providers: [+ {} as Record<string, AttachedContextItem[]>,+ {+ registerContext: (state, { providerId, items }) => ({ ...state, [providerId]: items }),+ deregisterContext: (state, { providerId }) => {+ if (!(providerId in state)) {+ return state+ }+ const { [providerId]: _dropped, ...rest } = state+ return rest+ },+ },+ ],+ // Per-task set of `attachedContextItemKey`s already wrapped into a sent message. Append-only for+ // the session: entity refs sent once anywhere in a task's resume chain stay pruned from later sends.+ sentContextKeysByTask: [+ {} as Record<string, string[]>,+ {+ markContextSent: (state, { taskId, keys }) => {+ if (keys.length === 0) {+ return state+ }+ const existing = state[taskId] ?? []+ const added = keys.filter((key) => !existing.includes(key))+ if (added.length === 0) {+ return state+ }+ return { ...state, [taskId]: [...existing, ...added] }+ },+ },+ ],+ dismissedKeys: [+ {} as Record<string, true>,+ {+ dismissContext: (state, { key }) => ({ ...state, [key]: true as const }),+ undismissContext: (state, { key }) => {+ if (!(key in state)) {+ return state+ }+ const { [key]: _dropped, ...rest } = state+ return rest+ },+ },+ ],+ }),++ selectors({+ // Flattened across providers, deduped by `${type}:${key ?? value}` (first writer wins).+ // Items with neither `key` nor `value` carry no payload and are dropped, as are dismissed keys.+ contextItems: [+ (s) => [s.providers, s.dismissedKeys],+ (providers, dismissedKeys): AttachedContextItem[] => {+ const seen = new Set<string>()+ const out: AttachedContextItem[] = []+ for (const items of Object.values(providers)) {+ for (const item of items) {+ const hasKey = item.key !== undefined && item.key !== null && item.key !== ''+ const hasValue = item.value !== undefined && item.value !== ''+ if (!hasKey && !hasValue) {+ continue+ }+ const key = attachedContextItemKey(item)+ if (seen.has(key) || dismissedKeys[key]) {+ continue+ }+ seen.add(key)+ out.push(item)+ }+ }+ return out+ },+ ],+ hasContext: [(s) => [s.contextItems], (contextItems): boolean => contextItems.length > 0],+ }),+])diff --git a/products/posthog_ai/frontend/logics/contextPickerLogic.test.ts b/products/posthog_ai/frontend/logics/contextPickerLogic.test.tsnew file mode 100644index 000000000000..e38e4e57ba8a--- /dev/null+++ b/products/posthog_ai/frontend/logics/contextPickerLogic.test.ts@@ -0,0 +1,89 @@+import { expectLogic } from 'kea-test-utils'++import { TaxonomicFilterGroupType } from 'lib/components/TaxonomicFilter/types'++import { initKeaTests } from '~/test/init'++import { attachedContextLogic } from './attachedContextLogic'+import { PICKER_PROVIDER_ID, contextPickerLogic, taxonomicItemToAttachedContext } from './contextPickerLogic'++describe('contextPickerLogic', () => {+ let store: ReturnType<typeof attachedContextLogic.build>+ let logic: ReturnType<typeof contextPickerLogic.build>++ beforeEach(() => {+ initKeaTests()+ store = attachedContextLogic()+ store.mount()+ logic = contextPickerLogic()+ logic.mount()+ })++ afterEach(() => {+ logic?.unmount()+ store?.unmount()+ })++ test.each([+ // Events must key on the name, not the EventDefinition UUID (`item.id`) — tools resolve by name.+ [TaxonomicFilterGroupType.Events, { id: 'ev-uuid', name: '$pageview' }, 'event', '$pageview', '$pageview'],+ [TaxonomicFilterGroupType.Actions, { id: 12, name: 'Signup' }, 'action', 12, 'Signup'],+ [TaxonomicFilterGroupType.Insights, { short_id: 'abc123', name: 'DAU' }, 'insight', 'abc123', 'DAU'],+ [TaxonomicFilterGroupType.Dashboards, { id: 7, name: 'Growth' }, 'dashboard', 7, 'Growth'],+ [TaxonomicFilterGroupType.Notebooks, { short_id: 'nb1', title: 'Notes' }, 'notebook', 'nb1', 'Notes'],+ [+ TaxonomicFilterGroupType.ErrorTrackingIssues,+ { id: 'issue-1', name: 'TypeError' },+ 'error_tracking_issue',+ 'issue-1',+ 'TypeError',+ ],+ ])('taxonomicItemToAttachedContext maps %s', (groupType, item, type, key, label) => {+ expect(taxonomicItemToAttachedContext('fallback', groupType, item)).toEqual({ type, key, label })+ })++ it('returns null for group types the picker does not offer', () => {+ expect(+ taxonomicItemToAttachedContext('x', TaxonomicFilterGroupType.Cohorts, { id: 1, name: 'Cohort' })+ ).toBeNull()+ })++ it('picks flow into the store, removal and unmount take them back out', async () => {+ await expectLogic(logic, () => {+ logic.actions.handleTaxonomicFilterChange('abc123', TaxonomicFilterGroupType.Insights, {+ short_id: 'abc123',+ name: 'DAU',+ })+ }).toFinishAllListeners()+ expect(store.values.contextItems).toEqual([{ type: 'insight', key: 'abc123', label: 'DAU' }])++ await expectLogic(logic, () => {+ logic.actions.removePickedItem('insight:abc123')+ }).toFinishAllListeners()+ expect(store.values.contextItems).toEqual([])++ await expectLogic(logic, () => {+ logic.actions.handleTaxonomicFilterChange('7', TaxonomicFilterGroupType.Dashboards, {+ id: 7,+ name: 'Growth',+ })+ }).toFinishAllListeners()+ logic.unmount()+ expect(store.values.providers[PICKER_PROVIDER_ID]).toBeUndefined()+ expect(store.values.contextItems).toEqual([])+ })++ it('re-picking a dismissed item restores it', async () => {+ store.actions.registerContext('bridge', [{ type: 'insight', key: 'abc123', label: 'DAU' }])+ store.actions.dismissContext('insight:abc123')+ expect(store.values.contextItems).toEqual([])++ await expectLogic(logic, () => {+ logic.actions.handleTaxonomicFilterChange('abc123', TaxonomicFilterGroupType.Insights, {+ short_id: 'abc123',+ name: 'DAU',+ })+ }).toFinishAllListeners()+ expect(store.values.contextItems).toEqual([{ type: 'insight', key: 'abc123', label: 'DAU' }])+ })+})diff --git a/products/posthog_ai/frontend/logics/contextPickerLogic.ts b/products/posthog_ai/frontend/logics/contextPickerLogic.tsnew file mode 100644index 000000000000..835daa0b4dd6--- /dev/null+++ b/products/posthog_ai/frontend/logics/contextPickerLogic.ts@@ -0,0 +1,128 @@+import { actions, connect, events, kea, listeners, path, reducers, selectors, sharedListeners } from 'kea'++import { TaxonomicFilterGroupType } from 'lib/components/TaxonomicFilter/types'++import { type AttachedContextItem, attachedContextItemKey } from '../types/contextTypes'+import { attachedContextLogic } from './attachedContextLogic'+import type { contextPickerLogicType } from './contextPickerLogicType'++export const PICKER_PROVIDER_ID = 'user-picker'++/** Structural subset of the taxonomic item shapes the picker consumes — no scene-tree type imports. */+export interface PickableTaxonomicItem {+ id?: string | number+ short_id?: string+ name?: string | null+ title?: string | null+}++/**+ * Projects a TaxonomicFilter selection down to the surface's abstract `AttachedContextItem`.+ * Refs only — no entity loading; the agent fetches details via its read tools.+ * Returns null for group types the picker doesn't offer.+ */+export function taxonomicItemToAttachedContext(+ value: string | number,+ groupType: TaxonomicFilterGroupType,+ item: PickableTaxonomicItem+): AttachedContextItem | null {+ switch (groupType) {+ case TaxonomicFilterGroupType.Events:+ // Events are keyed by name everywhere (API, HogQL, taxonomy) — `item.id` is the+ // EventDefinition UUID, which the agent's read tools can't resolve.+ return { type: 'event', key: item.name ?? value, label: item.name ?? undefined }+ case TaxonomicFilterGroupType.Actions:+ return { type: 'action', key: item.id ?? value, label: item.name ?? undefined }+ case TaxonomicFilterGroupType.Insights:+ return { type: 'insight', key: item.short_id ?? value, label: item.name ?? undefined }+ case TaxonomicFilterGroupType.Dashboards:+ return { type: 'dashboard', key: item.id ?? value, label: item.name ?? undefined }+ case TaxonomicFilterGroupType.Notebooks:+ return { type: 'notebook', key: item.short_id ?? value, label: item.title ?? undefined }+ case TaxonomicFilterGroupType.ErrorTrackingIssues:+ return { type: 'error_tracking_issue', key: item.id ?? value, label: item.name ?? undefined }+ default:+ return null+ }+}++/**+ * Global store of context the user explicitly picked via the composer's @-affordance. Just another+ * provider on `attachedContextLogic` (id `user-picker`): picks upsert into `pickedItems`, and every+ * change re-registers the provider, so picked refs flow into `contextItems` and the send-time+ * `<posthog_context>` wrap with zero extra plumbing.+ */+export const contextPickerLogic = kea<contextPickerLogicType>([+ path(['products', 'posthog_ai', 'frontend', 'logics', 'contextPickerLogic']),++ connect(() => ({+ actions: [attachedContextLogic, ['registerContext', 'deregisterContext', 'undismissContext']],+ })),++ actions({+ /** Signature matches `TaxonomicPopover.onChange` so the component can pass it straight through. */+ handleTaxonomicFilterChange: (+ value: string | number,+ groupType: TaxonomicFilterGroupType,+ item: PickableTaxonomicItem+ ) => ({ value, groupType, item }),+ pickItem: (item: AttachedContextItem) => ({ item }),+ removePickedItem: (key: string) => ({ key }),+ }),++ reducers({+ pickedItems: [+ [] as AttachedContextItem[],+ {+ pickItem: (state, { item }) => {+ const key = attachedContextItemKey(item)+ return state.filter((existing) => attachedContextItemKey(existing) !== key).concat(item)+ },+ removePickedItem: (state, { key }) =>+ state.filter((existing) => attachedContextItemKey(existing) !== key),+ },+ ],+ }),++ selectors({+ pickedKeys: [+ (s) => [s.pickedItems],+ (pickedItems): Set<string> => new Set(pickedItems.map(attachedContextItemKey)),+ ],+ }),++ sharedListeners(({ actions, values }) => ({+ syncProvider: () => {+ actions.registerContext(PICKER_PROVIDER_ID, values.pickedItems)+ },+ })),++ listeners(({ actions, sharedListeners }) => ({+ handleTaxonomicFilterChange: ({ value, groupType, item }) => {+ const attached = taxonomicItemToAttachedContext(value, groupType, item)+ if (!attached) {+ return+ }+ // Re-picking something the user previously closed must bring it back.+ actions.undismissContext(attachedContextItemKey(attached))+ actions.pickItem(attached)+ },+ pickItem: sharedListeners.syncProvider,+ removePickedItem: sharedListeners.syncProvider,+ })),++ events(({ actions, cache, values }) => ({+ afterMount: () => {+ // `pauseOnPageHidden: false`: a hide-paused registration would drop picked context from a+ // queued follow-up that flushes while the tab is hidden; the registration is idle-cost-free.+ cache.disposables.add(+ () => {+ actions.registerContext(PICKER_PROVIDER_ID, values.pickedItems)+ return () => actions.deregisterContext(PICKER_PROVIDER_ID)+ },+ 'contextPicker',+ { pauseOnPageHidden: false }+ )+ },+ })),+])diff --git a/products/posthog_ai/frontend/logics/runInteractionLogic.test.ts b/products/posthog_ai/frontend/logics/runInteractionLogic.test.tsindex feb958954567..6f1a55c2530f 100644--- a/products/posthog_ai/frontend/logics/runInteractionLogic.test.ts+++ b/products/posthog_ai/frontend/logics/runInteractionLogic.test.ts@@ -7,6 +7,7 @@ import { initKeaTests } from '~/test/init'import { tasksRunCreate, tasksRunsCommandCreate } from 'products/tasks/frontend/generated/api'+import { attachedContextLogic } from './attachedContextLogic'import { runInteractionLogic } from './runInteractionLogic'import { runStreamLogic } from './runStreamLogic'@@ -274,6 +275,83 @@ describe('runInteractionLogic', () => {expect(logic.values.composerForm.draft).toBe('continue from here')})+ it('wraps outgoing content with the attached-context block while echoing the raw text, and dedupes per task', async () => {+ attachedContextLogic().actions.registerContext('scene', [+ { type: 'insight', key: 'sig', label: 'Signups' },+ { type: 'text', value: 'always resend me' },+ ])+ setThinking(false)++ logic.actions.setComposerFormValues({ draft: 'why the drop?' })+ await expectLogic(logic, () => {+ logic.actions.submitComposerForm()+ }).toFinishAllListeners()++ const firstSend = (tasksRunsCommandCreate as jest.Mock).mock.calls[0][3] as {+ params: { content: string }+ }+ // The wire content carries the invisible context block; the echoed human message stays raw.+ expect(firstSend.params.content).toContain('<posthog_context>')+ expect(firstSend.params.content).toContain('- insight sig ("Signups")')+ expect(firstSend.params.content.endsWith('why the drop?')).toBe(true)+ await expectLogic(stream).toDispatchActions([+ (action) =>+ action.type === stream.actionTypes.pushHumanMessage && action.payload.content === 'why the drop?',+ ])++ // A second send on the same task must not re-inflate already-sent entity refs — but `text`+ // items are never deduped (repeated text is intentional, mirroring the backend).+ ;(tasksRunsCommandCreate as jest.Mock).mockClear()+ logic.actions.setComposerFormValues({ draft: 'follow up' })+ await expectLogic(logic, () => {+ logic.actions.submitComposerForm()+ }).toFinishAllListeners()++ const secondSend = (tasksRunsCommandCreate as jest.Mock).mock.calls[0][3] as {+ params: { content: string }+ }+ expect(secondSend.params.content).not.toContain('- insight sig')+ expect(secondSend.params.content).toContain('- text: "always resend me"')+ expect(secondSend.params.content.endsWith('follow up')).toBe(true)+ })++ it('keeps pruning context sent by a terminal-run send after re-pointing to the fresh run', async () => {+ attachedContextLogic().actions.registerContext('scene', [{ type: 'insight', key: 'sig', label: 'Signups' }])++ // A send on a finished run starts a fresh run, wrapping the pending context into its seed message.+ setStatus('completed')+ logic.actions.setComposerFormValues({ draft: 'continue from here' })+ await expectLogic(logic, () => {+ logic.actions.submitComposerForm()+ }).toFinishAllListeners()++ const createRequest = (tasksRunCreate as jest.Mock).mock.calls[0][2] as { pending_user_message: string }+ expect(createRequest.pending_user_message).toContain('- insight sig ("Signups")')+ expect(onRunStarted).toHaveBeenCalledWith('run-2')++ // The consumer re-points to the new run: a fresh logic instance keyed by the new runId, same task.+ // Sent-context bookkeeping is task-scoped, so the first follow-up must not re-wrap the same ref.+ const nextStream = runStreamLogic({ streamKey: 'run-2' })+ nextStream.mount()+ const nextLogic = runInteractionLogic({ taskId: TASK_ID, runId: 'run-2', onRunStarted })+ nextLogic.mount()+ try {+ nextLogic.actions.setComposerFormValues({ draft: 'follow up' })+ await expectLogic(nextLogic, () => {+ nextLogic.actions.submitComposerForm()+ }).toFinishAllListeners()++ const followUp = (tasksRunsCommandCreate as jest.Mock).mock.calls[0][3] as {+ params: { content: string }+ }+ // The only attached item was already sent this task, so no context block is prepended at all.+ expect(followUp.params.content).toBe('follow up')+ } finally {+ nextLogic.unmount()+ nextStream.unmount()+ }+ })+const setProjectId = (id: number | null): void =>(project.actions as unknown as { setCurrentProjectId: (id: number | null) => void }).setCurrentProjectId(id)diff --git a/products/posthog_ai/frontend/logics/runInteractionLogic.ts b/products/posthog_ai/frontend/logics/runInteractionLogic.tsindex 775bd71fab2f..99d288f9f9b6 100644--- a/products/posthog_ai/frontend/logics/runInteractionLogic.ts+++ b/products/posthog_ai/frontend/logics/runInteractionLogic.ts@@ -16,6 +16,9 @@ import {type ReasoningEffortEnumApi,} from 'products/tasks/frontend/generated/api.schemas'+import { type AttachedContextItem, attachedContextItemKey } from '../types/contextTypes'+import { wrapWithPosthogContext } from '../utils/posthogContextBlock'+import { attachedContextLogic } from './attachedContextLogic'import type { runInteractionLogicType } from './runInteractionLogicType'import { isTerminalRunStatus, runStreamLogic } from './runStreamLogic'@@ -76,10 +79,14 @@ export const runInteractionLogic = kea<runInteractionLogicType>([['currentProjectId'],runStreamLogic({ streamKey: props.streamKey ?? props.runId }),['currentRunStatus', 'pendingPermissionRequest', 'respondingToPermission', 'isThinking'],+ attachedContextLogic,+ ['contextItems', 'sentContextKeysByTask'],],actions: [runStreamLogic({ streamKey: props.streamKey ?? props.runId }),['pushHumanMessage', 'respondToPermission', 'cancelRun', 'markTurnComplete'],+ attachedContextLogic,+ ['markContextSent'],],})),@@ -232,130 +239,161 @@ export const runInteractionLogic = kea<runInteractionLogicType>([],// In-flight indicator for the composer's send button — a live send or a new-run start.isSubmitting: [(s) => [s.sending, s.startingRun], (sending, startingRun): boolean => sending || startingRun],+ // Attached context not yet wrapped into a message for this task, the snapshot the next send wraps.+ // The sent-key bookkeeping is task-scoped (`attachedContextLogic.sentContextKeysByTask`), not+ // run-scoped, so the dedupe survives a terminal-run send re-pointing to a fresh run instance.+ // `text` items are never deduped (matches the backend's `prune_repeated_entity_refs`: repeated+ // text is intentional, e.g. consecutive error snippets).+ pendingContextItems: [+ (s) => [s.contextItems, s.sentContextKeysByTask, (_, p: RunInteractionLogicProps) => p.taskId],+ (contextItems, sentContextKeysByTask, taskId): AttachedContextItem[] => {+ const sentKeys = new Set(sentContextKeysByTask[taskId] ?? [])+ return contextItems.filter(+ (item) => item.type === 'text' || !sentKeys.has(attachedContextItemKey(item))+ )+ },+ ],}),- listeners(({ actions, values, props }) => ({- // Drain the staged "Up next" message — only when the run is idle and can actually take it, so a flush- // against a busy/terminal/in-flight send is a no-op rather than dropping the message. The buffer is- // cleared up-front (not after the send) so a follow-up typed during the in-flight send stages cleanly- // instead of being wiped along with this send on success; `sendNow` re-stages it if the send fails.- flushQueue: () => {- const [queued] = values.queuedMessages- if (!queued || values.isBusy || !values.canSend) {- return+ listeners(({ actions, values, props }) => {+ // Record the non-text refs just wrapped into a send under the task, so no later send anywhere in+ // the task's resume chain (including the next run after a terminal-run send) re-inflates them.+ const markPendingContextSent = (pendingContext: AttachedContextItem[]): void => {+ const sentKeys = pendingContext.filter((item) => item.type !== 'text').map(attachedContextItemKey)+ if (sentKeys.length > 0) {+ actions.markContextSent(props.taskId, sentKeys)}- actions.clearQueue()- actions.sendNow(queued.content, 'queue')- },+ }- sendNow: async ({ content, source }) => {- if (values.sending || !content.trim() || values.isTerminal || values.currentProjectId == null) {- // Nothing was sent. The queue buffer was already cleared in `flushQueue`, so re-stage for- // retry; the draft path leaves its content untouched in the composer.- if (source === 'queue') {- actions.prependQueuedMessage(content)+ return {+ // Drain the staged "Up next" message — only when the run is idle and can actually take it, so a flush+ // against a busy/terminal/in-flight send is a no-op rather than dropping the message. The buffer is+ // cleared up-front (not after the send) so a follow-up typed during the in-flight send stages cleanly+ // instead of being wiped along with this send on success; `sendNow` re-stages it if the send fails.+ flushQueue: () => {+ const [queued] = values.queuedMessages+ if (!queued || values.isBusy || !values.canSend) {+ return}- return- }- actions.setSending(true)- // Clear the draft synchronously before the await so text the user types while the send is in- // flight isn't clobbered when the request resolves; a failed send restores it ahead of anything- // typed since. The queue buffer was already cleared up-front in `flushQueue`.- if (source === 'draft') {- actions.resetComposerForm()- }- try {- // Sync the picked model/effort to the agent session first, but only what the user actually- // changed since the last sync — mid-run config lives as session state, so it must go via a- // `set_config_option` command before the message rather than ride inside `user_message`. A- // failure here aborts the send (the catch restores the content); `setSent*` runs only after a- // successful sync so the next send retries an unsent change.- const activeModel = values.sentModel ?? props.currentModel ?? DEFAULT_COMPOSER_MODEL- const activeEffort = resolveEffortForModel(- values.sentEffort ?? props.currentEffort ?? DEFAULT_COMPOSER_EFFORT,- activeModel- )- if (values.selectedModel !== activeModel) {- await tasksRunsCommandCreate(String(values.currentProjectId), props.taskId, props.runId, {- jsonrpc: '2.0',- method: 'set_config_option',- params: { configId: MODEL_CONFIG_ID, value: values.selectedModel },- })- actions.setSentModel(values.selectedModel)+ actions.clearQueue()+ actions.sendNow(queued.content, 'queue')+ },++ sendNow: async ({ content, source }) => {+ if (values.sending || !content.trim() || values.isTerminal || values.currentProjectId == null) {+ // Nothing was sent. The queue buffer was already cleared in `flushQueue`, so re-stage for+ // retry; the draft path leaves its content untouched in the composer.+ if (source === 'queue') {+ actions.prependQueuedMessage(content)+ }+ return}- if (values.selectedEffort !== activeEffort) {+ actions.setSending(true)+ // Clear the draft synchronously before the await so text the user types while the send is in+ // flight isn't clobbered when the request resolves; a failed send restores it ahead of anything+ // typed since. The queue buffer was already cleared up-front in `flushQueue`.+ if (source === 'draft') {+ actions.resetComposerForm()+ }+ try {+ // Sync the picked model/effort to the agent session first, but only what the user actually+ // changed since the last sync — mid-run config lives as session state, so it must go via a+ // `set_config_option` command before the message rather than ride inside `user_message`. A+ // failure here aborts the send (the catch restores the content); `setSent*` runs only after a+ // successful sync so the next send retries an unsent change.+ const activeModel = values.sentModel ?? props.currentModel ?? DEFAULT_COMPOSER_MODEL+ const activeEffort = resolveEffortForModel(+ values.sentEffort ?? props.currentEffort ?? DEFAULT_COMPOSER_EFFORT,+ activeModel+ )+ if (values.selectedModel !== activeModel) {+ await tasksRunsCommandCreate(String(values.currentProjectId), props.taskId, props.runId, {+ jsonrpc: '2.0',+ method: 'set_config_option',+ params: { configId: MODEL_CONFIG_ID, value: values.selectedModel },+ })+ actions.setSentModel(values.selectedModel)+ }+ if (values.selectedEffort !== activeEffort) {+ await tasksRunsCommandCreate(String(values.currentProjectId), props.taskId, props.runId, {+ jsonrpc: '2.0',+ method: 'set_config_option',+ params: { configId: EFFORT_CONFIG_ID, value: values.selectedEffort },+ })+ actions.setSentEffort(values.selectedEffort)+ }+ // Wrap the outgoing content with the on-screen context block (invisible to the user —+ // `runStreamLogic.unwrapUserMessageContent` strips it on replay, and the echo below is raw).+ const pendingContext = values.pendingContextItemsawait tasksRunsCommandCreate(String(values.currentProjectId), props.taskId, props.runId, {jsonrpc: '2.0',- method: 'set_config_option',- params: { configId: EFFORT_CONFIG_ID, value: values.selectedEffort },- })- actions.setSentEffort(values.selectedEffort)- }- await tasksRunsCommandCreate(String(values.currentProjectId), props.taskId, props.runId, {- jsonrpc: '2.0',- method: 'user_message',- params: { content },- })- // The SSE echo (`pushHumanMessage`) reopens the turn.- actions.pushHumanMessage(content)- } catch {- // Restore unsent content for retry, preserving send order — draft content goes back ahead of- // anything typed during the failed send, queue content re-stages ahead of anything staged since.- if (source === 'draft') {- actions.setComposerFormValues({- draft: values.composerForm.draft ? `${content}\n\n${values.composerForm.draft}` : content,+ method: 'user_message',+ params: { content: wrapWithPosthogContext(content, pendingContext) },})- } else {- actions.prependQueuedMessage(content)+ // The SSE echo (`pushHumanMessage`) reopens the turn — always the raw text the user typed.+ actions.pushHumanMessage(content)+ markPendingContextSent(pendingContext)+ } catch {+ // Restore unsent content for retry, preserving send order — draft content goes back ahead of+ // anything typed during the failed send, queue content re-stages ahead of anything staged since.+ if (source === 'draft') {+ actions.setComposerFormValues({+ draft: values.composerForm.draft ? `${content}\n\n${values.composerForm.draft}` : content,+ })+ } else {+ actions.prependQueuedMessage(content)+ }+ lemonToast.error('Failed to send message. Please try again.')+ } finally {+ actions.setSending(false)}- lemonToast.error('Failed to send message. Please try again.')- } finally {- actions.setSending(false)- }- },+ },- // The agent finished a turn — drain any staged follow-ups.- markTurnComplete: () => {- actions.flushQueue()- },+ // The agent finished a turn — drain any staged follow-ups.+ markTurnComplete: () => {+ actions.flushQueue()+ },- // The new model may not support the current effort — clamp the override so it never holds an- // unsupported value. No network here: the pick is synced to the agent at send time.- setModel: ({ model }) => {- const currentEffort = values.effortOverride ?? props.currentEffort- const resolvedEffort = resolveEffortForModel(currentEffort, model)- if (resolvedEffort !== currentEffort) {- actions.setEffort(resolvedEffort)- }- },+ // The new model may not support the current effort — clamp the override so it never holds an+ // unsupported value. No network here: the pick is synced to the agent at send time.+ setModel: ({ model }) => {+ const currentEffort = values.effortOverride ?? props.currentEffort+ const resolvedEffort = resolveEffortForModel(currentEffort, model)+ if (resolvedEffort !== currentEffort) {+ actions.setEffort(resolvedEffort)+ }+ },- startNewRun: async ({ content }) => {- if (values.startingRun || !content.trim() || values.currentProjectId == null) {- return- }- actions.setStartingRun(true)- try {- // Same endpoint as the "Run again" button, but seeded with the user's message and chained- // from the finished run so the new run continues the thread, and carrying the picked model /- // reasoning effort (the resume schema can't, so we send the Claude create shape). The response- // carries the new run id as `latest_run`; the consumer-provided `onRunStarted` re-points to it.- const createRequest: ClaudeTaskRunCreateSchemaApi = {- runtime_adapter: ClaudeRuntimeAdapterEnumApi.Claude,- model: values.selectedModel,- reasoning_effort: values.selectedEffort,- resume_from_run_id: props.runId,- pending_user_message: content,+ startNewRun: async ({ content }) => {+ if (values.startingRun || !content.trim() || values.currentProjectId == null) {+ return}- const result = await tasksRunCreate(String(values.currentProjectId), props.taskId, createRequest)- actions.resetComposerForm()- if (result.latest_run) {- props.onRunStarted?.(result.latest_run)+ actions.setStartingRun(true)+ try {+ // Same endpoint as the "Run again" button, but seeded with the user's message and chained+ // from the finished run so the new run continues the thread, and carrying the picked model /+ // reasoning effort (the resume schema can't, so we send the Claude create shape). The response+ // carries the new run id as `latest_run`; the consumer-provided `onRunStarted` re-points to it.+ const pendingContext = values.pendingContextItems+ const createRequest: ClaudeTaskRunCreateSchemaApi = {+ runtime_adapter: ClaudeRuntimeAdapterEnumApi.Claude,+ model: values.selectedModel,+ reasoning_effort: values.selectedEffort,+ resume_from_run_id: props.runId,+ pending_user_message: wrapWithPosthogContext(content, pendingContext),+ }+ const result = await tasksRunCreate(String(values.currentProjectId), props.taskId, createRequest)+ actions.resetComposerForm()+ markPendingContextSent(pendingContext)+ if (result.latest_run) {+ props.onRunStarted?.(result.latest_run)+ }+ } catch {+ lemonToast.error('Failed to start a new run. Please try again.')+ } finally {+ actions.setStartingRun(false)}- } catch {- lemonToast.error('Failed to start a new run. Please try again.')- } finally {- actions.setStartingRun(false)- }- },- })),+ },+ }+ }),])diff --git a/products/posthog_ai/frontend/logics/runStreamLogic.test.ts b/products/posthog_ai/frontend/logics/runStreamLogic.test.tsindex 1e4bd5f3e2b9..bea8c08f79d9 100644--- a/products/posthog_ai/frontend/logics/runStreamLogic.test.ts+++ b/products/posthog_ai/frontend/logics/runStreamLogic.test.ts@@ -28,6 +28,7 @@ import {SSE_RECONNECT_BASE_DELAY_MS,SSE_RECONNECT_MAX_DELAY_MS,} from './runStreamLogic'+import { toolStreamEventsLogic } from './toolStreamEventsLogic'jest.mock('products/tasks/frontend/generated/api', () => ({tasksRunsCommandCreate: jest.fn(),@@ -290,6 +291,82 @@ describe('runStreamLogic', () => {})})+ describe('tool stream events', () => {+ const issueCall = sessionUpdate({+ sessionUpdate: 'tool_call',+ toolCallId: 'tse1',+ serverName: 'github',+ toolName: 'create_issue',+ status: 'in_progress',+ })+ const issueDone = sessionUpdate({ sessionUpdate: 'tool_call_update', toolCallId: 'tse1', status: 'completed' })++ it('publishes started/completed with resolved names for live frames; replay only reaches includeReplay listeners', async () => {+ const liveListener = jest.fn()+ const replayListener = jest.fn()+ // The bus is connect-mounted by the stream logic, so listeners can register directly.+ toolStreamEventsLogic.actions.registerToolListener('live', {+ tools: ['create_issue'],+ onEvent: liveListener,+ })+ toolStreamEventsLogic.actions.registerToolListener('replay', {+ tools: '*',+ onEvent: replayListener,+ includeReplay: true,+ })++ await expectLogic(logic, () => {+ logic.actions.ingestAcpFrame(issueCall)+ logic.actions.ingestAcpFrame(issueDone)+ }).toFinishAllListeners()++ expect(liveListener.mock.calls.map(([event]) => [event.phase, event.toolName])).toEqual([+ ['started', 'create_issue'],+ ['completed', 'create_issue'],+ ])++ liveListener.mockClear()+ replayListener.mockClear()+ await expectLogic(logic, () => {+ logic.actions.ingestAcpFrame(+ sessionUpdate({+ sessionUpdate: 'tool_call',+ toolCallId: 'tse2',+ serverName: 'github',+ toolName: 'create_issue',+ status: 'in_progress',+ }),+ 'replay'+ )+ }).toFinishAllListeners()++ expect(liveListener).not.toHaveBeenCalled()+ expect(replayListener).toHaveBeenCalledTimes(1)+ expect(replayListener.mock.calls[0][0].source).toEqual('replay')+ })++ it('resolves a live completion against a tool_call ingested during replay with no replay listener', async () => {+ const captureSpy = jest.spyOn(posthog, 'capture').mockImplementation(() => undefined as any)+ const liveListener = jest.fn()+ toolStreamEventsLogic.actions.registerToolListener('live-only', {+ tools: ['create_issue'],+ onEvent: liveListener,+ })++ await expectLogic(logic, () => {+ // No replay subscriber registered, so this frame emits nothing on the bus, but the+ // live terminal update must still resolve its name and phase off it.+ logic.actions.ingestAcpFrame(issueCall, 'replay')+ logic.actions.ingestAcpFrame(issueDone, 'live')+ }).toFinishAllListeners()++ expect(liveListener.mock.calls.map(([event]) => [event.phase, event.toolName])).toEqual([+ ['completed', 'create_issue'],+ ])+ expect(captureSpy.mock.calls.filter((c) => c[0] === 'tool_call_completed')).toHaveLength(1)+ })+ })+describe('showThinkingIndicator', () => {const runStartedFrame = notification('_posthog/run_started', {})const messageChunk = sessionUpdate({diff --git a/products/posthog_ai/frontend/logics/runStreamLogic.ts b/products/posthog_ai/frontend/logics/runStreamLogic.tsindex 62265621d284..7ea4534733d4 100644--- a/products/posthog_ai/frontend/logics/runStreamLogic.ts+++ b/products/posthog_ai/frontend/logics/runStreamLogic.ts@@ -29,6 +29,7 @@ import type {ThreadItemType,ToolInvocation,ToolInvocationStatus,+ ToolStreamPhase,} from '../types/streamTypes'import {type PermissionOption,@@ -50,6 +51,7 @@ import {} from '../types/wireTypes'import { debugLogsLogic } from './debugLogsLogic'import type { runStreamLogicType } from './runStreamLogicType'+import { hasReplayListener, toolStreamEventsLogic } from './toolStreamEventsLogic'export type RunSseStatus = 'idle' | 'connecting' | 'open' | 'reconnecting' | 'closed' | 'error'export type RunStatus = 'queued' | 'in_progress' | 'completed' | 'failed' | 'cancelled'@@ -216,7 +218,7 @@ export function mapHttpStatusToStreamError(status: number | undefined): StreamEr* (`context_wrapper.wrap_user_message`); stripping it keeps a replayed prompt identical to the one* the live send path echoed via `pushHumanMessage`.*/-function unwrapUserMessageContent(content: string): string {+export function unwrapUserMessageContent(content: string): string {const closeTag = '</posthog_context>'if (content.startsWith('<posthog_context>')) {const closeIdx = content.indexOf(closeTag)@@ -808,6 +810,90 @@ function dedupeBufferedAgainstHistory(buffered: StoredLogEntry[], history: Storereturn survivors}+/**+ * The invocation a `tool_call` frame creates, replacing any prior invocation for the id. Shared by+ * the `foldLogToThread` projection and the per-frame tracker in `ingestAcpFrame`, so tool-stream+ * events carry exactly the invocation the projection derives without re-folding the whole log.+ */+function invocationFromToolCall(update: Record<string, unknown>): ToolInvocation | null {+ const toolCallId = String(update.toolCallId ?? '')+ if (!toolCallId) {+ return null+ }+ return {+ toolCallId,+ rawServerName: String(update.serverName ?? 'posthog'),+ rawToolName: String(update.toolName ?? ''),+ input: (update.rawInput ?? update.input ?? {}) as Record<string, unknown>,+ status: mapAcpStatus(update.status),+ title: update.title as string | undefined,+ kind: update.kind as string | undefined,+ locations: update.locations as { path: string; line?: number }[] | undefined,+ contentBlocks: Array.isArray(update.content) ? update.content : [],+ meta: update._meta,+ }+}++/**+ * Folds one `tool_call_update` frame into the existing invocation (field-wise, newer-wins; the+ * invocation-level twin of `mergeToolCallUpdateEntries`). A reconnect can deliver a terminal update+ * whose creating `tool_call` was lost, so with no existing invocation this builds a minimal one and+ * the card still renders instead of vanishing. Shared by the projection and the per-frame tracker.+ */+function invocationFromToolCallUpdate(+ existing: ToolInvocation | undefined,+ update: Record<string, unknown>,+ notification: StoredLogEntry['notification']+): ToolInvocation | null {+ const toolCallId = String(update.toolCallId ?? '')+ if (!toolCallId) {+ return null+ }+ const status = mapAcpStatus(update.status ?? existing?.status)+ const rawInput =+ update.rawInput && typeof update.rawInput === 'object'+ ? (update.rawInput as Record<string, unknown>)+ : update.input && typeof update.input === 'object'+ ? (update.input as Record<string, unknown>)+ : undefined+ const denialReason = status === 'failed' ? extractDenialReason(update._meta) : undefined+ const errorMessage =+ (update.error as { message?: string } | null)?.message ??+ denialReason ??+ (status === 'failed' ? notification.error?.message : undefined)+ const updateContent = Array.isArray(update.content) ? update.content : []++ if (!existing) {+ return {+ toolCallId,+ rawServerName: 'posthog',+ rawToolName: '',+ input: rawInput ?? {},+ status,+ title: update.title as string | undefined,+ locations: update.locations as { path: string; line?: number }[] | undefined,+ contentBlocks: updateContent,+ meta: update._meta,+ ...(errorMessage !== undefined ? { error: { message: errorMessage } } : {}),+ }+ }++ return {+ ...existing,+ status,+ title: (update.title as string | undefined) ?? existing.title,+ progress: update.progress ?? existing.progress,+ output: update.rawOutput ?? existing.output,+ locations: (update.locations as { path: string; line?: number }[] | undefined) ?? existing.locations,+ // ACP update semantics: a present `content` replaces the collection (the agent re-sends+ // the full accumulated blocks) — appending would duplicate every prior snapshot.+ contentBlocks: updateContent.length > 0 ? updateContent : existing.contentBlocks,+ error: errorMessage !== undefined ? { message: errorMessage } : existing.error,+ ...(rawInput ? { input: rawInput } : {}),+ ...(update._meta ? { meta: update._meta } : {}),+ }+}+export interface FoldedThread {threadItems: ThreadItem[]toolInvocations: Map<string, ToolInvocation>@@ -934,60 +1020,15 @@ export function foldLogToThread(entries: StoredEntry[], options: { isResumeRun:update: Record<string, unknown>,notification: StoredLogEntry['notification']): void => {- const toolCallId = String(update.toolCallId ?? '')- if (!toolCallId) {+ const existing = invocations.get(String(update.toolCallId ?? ''))+ const next = invocationFromToolCallUpdate(existing, update, notification)+ if (!next) {return}- const existing = invocations.get(toolCallId)- const status = mapAcpStatus(update.status ?? existing?.status)- const rawInput =- update.rawInput && typeof update.rawInput === 'object'- ? (update.rawInput as Record<string, unknown>)- : update.input && typeof update.input === 'object'- ? (update.input as Record<string, unknown>)- : undefined- const denialReason = status === 'failed' ? extractDenialReason(update._meta) : undefined- const errorMessage =- (update.error as { message?: string } | null)?.message ??- denialReason ??- (status === 'failed' ? notification.error?.message : undefined)- const updateContent = Array.isArray(update.content) ? update.content : []-- if (!existing) {- // A reconnect can deliver a terminal update whose creating `tool_call` was lost — upsert a- // minimal invocation so the card still renders instead of vanishing.- invocations.set(toolCallId, {- toolCallId,- rawServerName: 'posthog',- rawToolName: '',- input: rawInput ?? {},- status,- title: update.title as string | undefined,- locations: update.locations as { path: string; line?: number }[] | undefined,- contentBlocks: updateContent,- meta: update._meta,- ...(errorMessage !== undefined ? { error: { message: errorMessage } } : {}),- })- if (!subagentParentToolCallId(update._meta)) {- upsertInvocationItem(toolCallId)- }- return+ invocations.set(next.toolCallId, next)+ if (!existing && !subagentParentToolCallId(update._meta)) {+ upsertInvocationItem(next.toolCallId)}-- invocations.set(toolCallId, {- ...existing,- status,- title: (update.title as string | undefined) ?? existing.title,- progress: update.progress ?? existing.progress,- output: update.rawOutput ?? existing.output,- locations: (update.locations as { path: string; line?: number }[] | undefined) ?? existing.locations,- // ACP update semantics: a present `content` replaces the collection (the agent re-sends- // the full accumulated blocks) — appending would duplicate every prior snapshot.- contentBlocks: updateContent.length > 0 ? updateContent : existing.contentBlocks,- error: errorMessage !== undefined ? { message: errorMessage } : existing.error,- ...(rawInput ? { input: rawInput } : {}),- ...(update._meta ? { meta: update._meta } : {}),- })}for (const { entry, source } of entries) {@@ -1150,26 +1191,15 @@ export function foldLogToThread(entries: StoredEntry[], options: { isResumeRun:)breakcase 'tool_call': {- const toolCallId = String(update.toolCallId ?? '')- if (!toolCallId) {+ const invocation = invocationFromToolCall(update)+ if (!invocation) {break}- invocations.set(toolCallId, {- toolCallId,- rawServerName: String(update.serverName ?? 'posthog'),- rawToolName: String(update.toolName ?? ''),- input: (update.rawInput ?? update.input ?? {}) as Record<string, unknown>,- status: mapAcpStatus(update.status),- title: update.title as string | undefined,- kind: update.kind as string | undefined,- locations: update.locations as { path: string; line?: number }[] | undefined,- contentBlocks: Array.isArray(update.content) ? update.content : [],- meta: update._meta,- })+ invocations.set(invocation.toolCallId, invocation)// A subagent's inner tool calls carry the parent Task's id; they belong inside that// card, not as top-level siblings, so keep them out of the thread.if (!subagentParentToolCallId(update._meta)) {- upsertInvocationItem(toolCallId)+ upsertInvocationItem(invocation.toolCallId)}break}@@ -1232,7 +1262,10 @@ export const runStreamLogic = kea<runStreamLogicType>([['user'],debugLogsLogic,['showDebugLogs'],+ toolStreamEventsLogic,+ ['toolListeners'],],+ actions: [toolStreamEventsLogic, ['emitToolEvent']],})),actions({/**@@ -2482,7 +2515,9 @@ export const runStreamLogic = kea<runStreamLogicType>([cache.disposables.dispose('event-source')},reset: () => {- // `log` clears via its own reducer on `reset`, so the projection empties with it.+ // `log` clears via its own reducer on `reset`, so the projection empties with it. The+ // per-frame invocation tracker mirrors the log, so it must clear alongside it.+ cache.trackedToolInvocations = undefinedcache.activeRun = undefinedcache.turnStartedAtMs = undefinedcache.isBootstrapping = false@@ -2539,14 +2574,33 @@ export const runStreamLogic = kea<runStreamLogicType>([const method = notification.methodconst isReplay = source === 'replay'- // Pre-update tool status for the once-per-transition `tool_call_completed` telemetry,- // read from the projection BEFORE the append folds this update in. Live only — replay- // suppresses the telemetry, so the lookup (and its O(N) re-fold) is skipped for history.+ // Tool-stream events go out for every live frame; on replay only when a subscriber opted in+ // (so history replay doesn't pay per-frame resolution for nobody).+ const emitToolStream = !isReplay || hasReplayListener(values.toolListeners)++ // Per-frame tool-invocation tracker: the same fold the projection applies, maintained+ // O(1) per tool frame so the telemetry and tool-stream emits below never read the+ // `toolInvocations` projection (each such read re-folds the entire log, which turns a+ // long tool-heavy history replay quadratic). Maintained for every source so a live update+ // whose `tool_call` arrived during replay still sees the right prior status.+ // `preToolStatus` is the status BEFORE this frame folds in; it gates the+ // once-per-transition `tool_call_completed` telemetry and the tool-stream phase.+ const trackedInvocations: Map<string, ToolInvocation> = (cache.trackedToolInvocations ??= new Map())let preToolStatus: ToolInvocationStatus | undefined- if (!isReplay && method === 'session/update') {+ if (method === 'session/update') {const u = notification.params?.update- if (isRecord(u) && u.sessionUpdate === 'tool_call_update') {- preToolStatus = values.toolInvocations.get(String(u.toolCallId ?? ''))?.status+ if (isRecord(u) && u.sessionUpdate === 'tool_call') {+ const invocation = invocationFromToolCall(u)+ if (invocation) {+ trackedInvocations.set(invocation.toolCallId, invocation)+ }+ } else if (isRecord(u) && u.sessionUpdate === 'tool_call_update') {+ const existing = trackedInvocations.get(String(u.toolCallId ?? ''))+ preToolStatus = existing?.status+ const invocation = invocationFromToolCallUpdate(existing, u, notification)+ if (invocation) {+ trackedInvocations.set(invocation.toolCallId, invocation)+ }}}@@ -2661,11 +2715,31 @@ export const runStreamLogic = kea<runStreamLogicType>([actions.setCurrentMode(String(update.currentModeId ?? update.mode ?? ''))return}+ if (update.sessionUpdate === 'tool_call') {+ // A fresh tool call — the tracker folded it in above, so resolve its name off the+ // merged invocation and publish a `started` event on the bus.+ if (emitToolStream) {+ const toolCallId = String(update.toolCallId ?? '')+ const invocation = toolCallId ? trackedInvocations.get(toolCallId) : undefined+ if (invocation) {+ actions.emitToolEvent({+ streamKey: props.streamKey,+ toolCallId,+ toolName: resolveToolCall(invocation).resolvedKey,+ rawToolName: invocation.rawToolName,+ phase: 'started',+ invocation,+ source,+ })+ }+ }+ return+ }if (update.sessionUpdate === 'tool_call_update') {// TOOL_CALL_COMPLETED telemetry — emit once when a tool call first transitions to a// terminal status. `preToolStatus` (read before the upsert) gates the once-only fire;- // the resolved key comes from the merged invocation in the projection. Suppressed on- // replay, and skipped when the creating `tool_call` was lost (no pre-status).+ // the resolved key comes from the tracked merged invocation. Suppressed on replay,+ // and skipped when the creating `tool_call` was lost (no pre-status).const toolCallId = String(update.toolCallId ?? '')if (!toolCallId) {return@@ -2678,7 +2752,7 @@ export const runStreamLogic = kea<runStreamLogicType>([preToolStatus !== 'failed' &&(status === 'completed' || status === 'failed')) {- const invocation = values.toolInvocations.get(toolCallId)+ const invocation = trackedInvocations.get(toolCallId)const startedAt = cache.turnStartedAtMs as number | undefinedposthog.capture('tool_call_completed', {conversation_id: props.conversationId,@@ -2690,9 +2764,32 @@ export const runStreamLogic = kea<runStreamLogicType>([execution_type: 'sandbox',})}+ // Tool-stream event: phase from the pre-fold status → new status transition. A crossing+ // into a terminal status is `completed`/`failed`; any other update is `updated`.+ if (emitToolStream) {+ const invocation = trackedInvocations.get(toolCallId)+ if (invocation) {+ const wasTerminal = preToolStatus === 'completed' || preToolStatus === 'failed'+ const phase: ToolStreamPhase =+ !wasTerminal && status === 'completed'+ ? 'completed'+ : !wasTerminal && status === 'failed'+ ? 'failed'+ : 'updated'+ actions.emitToolEvent({+ streamKey: props.streamKey,+ toolCallId,+ toolName: resolveToolCall(invocation).resolvedKey,+ rawToolName: invocation.rawToolName,+ phase,+ invocation,+ source,+ })+ }+ }return}- // agent_message_chunk / agent_message / agent_thought_chunk / tool_call → projection only.+ // agent_message_chunk / agent_message / agent_thought_chunk → projection only.},})),])diff --git a/products/posthog_ai/frontend/logics/toolStreamEventsLogic.test.ts b/products/posthog_ai/frontend/logics/toolStreamEventsLogic.test.tsnew file mode 100644index 000000000000..bf1d1a09e1fd--- /dev/null+++ b/products/posthog_ai/frontend/logics/toolStreamEventsLogic.test.ts@@ -0,0 +1,67 @@+import { initKeaTests } from '~/test/init'++import type { ToolStreamEvent } from '../types/streamTypes'+import { toolStreamEventsLogic } from './toolStreamEventsLogic'++function event(overrides: Partial<ToolStreamEvent> = {}): ToolStreamEvent {+ return {+ streamKey: 'run-1',+ toolCallId: 'tc-1',+ toolName: 'create_dashboard',+ rawToolName: 'exec',+ phase: 'started',+ // The invocation is opaque to the bus — a minimal cast is enough for matching tests.+ invocation: {} as ToolStreamEvent['invocation'],+ source: 'live',+ ...overrides,+ }+}++describe('toolStreamEventsLogic', () => {+ let logic: ReturnType<typeof toolStreamEventsLogic.build>++ beforeEach(() => {+ initKeaTests()+ logic = toolStreamEventsLogic()+ logic.mount()+ })++ afterEach(() => {+ logic?.unmount()+ })++ it('delivers to matching listeners, honors `*`, and skips non-matches', () => {+ const named = jest.fn()+ const wildcard = jest.fn()+ const other = jest.fn()+ logic.actions.registerToolListener('named', { tools: ['create_dashboard'], onEvent: named })+ logic.actions.registerToolListener('wild', { tools: '*', onEvent: wildcard })+ logic.actions.registerToolListener('other', { tools: ['create_insight'], onEvent: other })++ logic.actions.emitToolEvent(event())++ expect(named).toHaveBeenCalledTimes(1)+ expect(wildcard).toHaveBeenCalledTimes(1)+ expect(other).not.toHaveBeenCalled()+ })++ it('suppresses replay events unless the subscription opts in via includeReplay', () => {+ const liveOnly = jest.fn()+ const withReplay = jest.fn()+ logic.actions.registerToolListener('live', { tools: '*', onEvent: liveOnly })+ logic.actions.registerToolListener('replay', { tools: '*', onEvent: withReplay, includeReplay: true })++ logic.actions.emitToolEvent(event({ source: 'replay' }))++ expect(liveOnly).not.toHaveBeenCalled()+ expect(withReplay).toHaveBeenCalledTimes(1)+ })++ it('stops delivering after deregister', () => {+ const cb = jest.fn()+ logic.actions.registerToolListener('x', { tools: '*', onEvent: cb })+ logic.actions.deregisterToolListener('x')+ logic.actions.emitToolEvent(event())+ expect(cb).not.toHaveBeenCalled()+ })+})diff --git a/products/posthog_ai/frontend/logics/toolStreamEventsLogic.ts b/products/posthog_ai/frontend/logics/toolStreamEventsLogic.tsnew file mode 100644index 000000000000..0621010e4882--- /dev/null+++ b/products/posthog_ai/frontend/logics/toolStreamEventsLogic.ts@@ -0,0 +1,87 @@+import { actions, kea, listeners, path, reducers } from 'kea'+import posthog from 'posthog-js'++import type { ToolStreamEvent } from '../types/streamTypes'+import type { toolStreamEventsLogicType } from './toolStreamEventsLogicType'++export interface ToolStreamSubscription {+ /** Resolved tool names to match, or `'*'` for every tool. */+ tools: string[] | '*'+ onEvent: (event: ToolStreamEvent) => void+ /** When true, replay-sourced events are delivered too. Defaults to false (live only). */+ includeReplay?: boolean+}++function subscriptionMatches(subscription: ToolStreamSubscription, event: ToolStreamEvent): boolean {+ if (event.source === 'replay' && !subscription.includeReplay) {+ return false+ }+ if (subscription.tools === '*') {+ return true+ }+ return subscription.tools.includes(event.toolName)+}++/**+ * Global, unkeyed event bus for tool-call lifecycle events. `runStreamLogic` emits `ToolStreamEvent`s+ * (with resolved tool names); consumers register a listener that fires their `onEvent` for matching+ * tools. Callbacks live in reducer state — the same precedent as `maxGlobalLogic.toolMap`. Replay+ * events are suppressed unless a subscription opts in via `includeReplay`.+ *+ * Kea-native alternative: `connect` to this bus and add+ * `listeners({ [toolStreamEventsLogic.actionTypes.emitToolEvent]: ({ event }) => ... })`.+ */+export const toolStreamEventsLogic = kea<toolStreamEventsLogicType>([+ path(['products', 'posthog_ai', 'frontend', 'logics', 'toolStreamEventsLogic']),++ actions({+ emitToolEvent: (event: ToolStreamEvent) => ({ event }),+ registerToolListener: (listenerId: string, subscription: ToolStreamSubscription) => ({+ listenerId,+ subscription,+ }),+ deregisterToolListener: (listenerId: string) => ({ listenerId }),+ }),++ reducers({+ toolListeners: [+ {} as Record<string, ToolStreamSubscription>,+ {+ registerToolListener: (state, { listenerId, subscription }) => ({+ ...state,+ [listenerId]: subscription,+ }),+ deregisterToolListener: (state, { listenerId }) => {+ if (!(listenerId in state)) {+ return state+ }+ const { [listenerId]: _dropped, ...rest } = state+ return rest+ },+ },+ ],+ }),++ listeners(({ values }) => ({+ emitToolEvent: ({ event }) => {+ for (const subscription of Object.values(values.toolListeners)) {+ if (!subscriptionMatches(subscription, event)) {+ continue+ }+ // The emit is dispatched synchronously from `runStreamLogic`'s frame ingestion — one+ // throwing subscriber must not break the stream (or starve later subscribers).+ try {+ subscription.onEvent(event)+ } catch (error) {+ posthog.captureException(error, { feature: 'posthog_ai_tool_stream_listener' })+ }+ }+ },+ })),+])++/** Whether any registered listener wants replay events — a cheap guard so `runStreamLogic` skips+ * per-frame resolution during history replay when nobody is listening for it. */+export function hasReplayListener(toolListeners: Record<string, ToolStreamSubscription>): boolean {+ return Object.values(toolListeners).some((subscription) => subscription.includeReplay)+}diff --git a/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskComposer.tsx b/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskComposer.tsxindex 95cb8b06ad97..8cf51f25af18 100644--- a/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskComposer.tsx+++ b/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskComposer.tsx@@ -11,6 +11,7 @@ import {} from 'products/posthog_ai/frontend/api/primitives'import { resolveEffortForModel } from 'products/posthog_ai/frontend/utils/composerModels'+import { AttachedContextBar } from '../../../components/composer/AttachedContextBar'import { ComposerModelEffortPickers } from '../../../components/composer/ComposerModelEffortPickers'import { useDebouncedDraft } from '../../../components/composer/useDebouncedDraft'import { taskTrackerSceneLogic } from '../taskTrackerSceneLogic'@@ -60,6 +61,9 @@ export function TaskComposer(): JSX.Element {textAreaRef={textAreaRef}><Composer.Frame>+ <Composer.Header>+ <AttachedContextBar />+ </Composer.Header><Composer.Field><Composer.Placeholder>Describe the task in detail…</Composer.Placeholder><Composer.Textarea autoFocus data-attr="task-composer-input" />diff --git a/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskRunChat.tsx b/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskRunChat.tsxindex 1f50fbe71f18..b81f7de111a0 100644--- a/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskRunChat.tsx+++ b/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskRunChat.tsx@@ -9,6 +9,7 @@ import { Composer, QueuedMessageList } from 'products/posthog_ai/frontend/api/pr// flash. The inbox embeds keep the lazy `ReadonlyRunSurface`.import { RunSurface } from 'products/posthog_ai/frontend/api/runSurface'+import { AttachedContextBar } from '../../../components/composer/AttachedContextBar'import { ComposerModelEffortPickers } from '../../../components/composer/ComposerModelEffortPickers'import { useDebouncedDraft } from '../../../components/composer/useDebouncedDraft'import { taskDetailSceneLogic } from '../taskDetailSceneLogic'@@ -131,6 +132,9 @@ function LiveComposer({ logicProps }: { logicProps: RunInteractionLogicProps }):</Composer.Banner>)}<Composer.Frame>+ <Composer.Header>+ <AttachedContextBar />+ </Composer.Header><Composer.Field><Composer.Placeholder>{isTerminal ? 'Send a message to start a new run…' : 'Send a follow-up message…'}diff --git a/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.test.ts b/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.test.tsindex bbdcec7c3759..f25c12b22b05 100644--- a/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.test.ts+++ b/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.test.ts@@ -4,6 +4,7 @@ import { expectLogic } from 'kea-test-utils'import { useMocks } from '~/mocks/jest'import { initKeaTests } from '~/test/init'+import { attachedContextLogic } from '../../api/logics'import { OriginProduct, Task, TaskRunEnvironment, TaskRunStatus } from '../../types/taskTypes'import { taskTrackerSceneLogic } from './taskTrackerSceneLogic'@@ -84,6 +85,28 @@ describe('taskTrackerSceneLogic', () => {expect(router.values.location.pathname).toContain('/tasks/new-task')})+ // The seeded first message wraps the on-screen context, and the wrapped non-text refs must be marked+ // sent under the created task's id — otherwise the run's first follow-up (sent via+ // `runInteractionLogic`, which prunes against the task-scoped store) re-wraps the same refs.+ it('marks seeded context sent for the created task so the first follow-up will not re-wrap it', async () => {+ logic.mount()+ attachedContextLogic().actions.registerContext('scene', [+ { type: 'insight', key: 'sig', label: 'Signups' },+ { type: 'text', value: 'always resend me' },+ ])++ logic.actions.setNewTaskData({ description: 'why the drop?' })+ logic.actions.submitNewTask()+ await expectLogic(logic).toFinishAllListeners()++ // The message sent to the agent is wrapped; the task description stays raw.+ expect(runBody?.pending_user_message).toContain('<posthog_context>')+ expect(runBody?.pending_user_message).toContain('- insight sig ("Signups")')+ expect(createBody?.description).toBe('why the drop?')+ // Only the entity ref is marked sent (text items always resend), under the created task's id.+ expect(attachedContextLogic().values.sentContextKeysByTask).toEqual({ 'new-task': ['insight:sig'] })+ })+// The repo picker only renders once `repositoryConfig.integrationId` is set (auto-selected from the// connected GitHub org). Submitting resets the form, wiping that id; without re-deriving it the picker// stays blank for every subsequent new task. Guards that the auto-select is restored after a submit.diff --git a/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.ts b/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.tsindex 0263bb1e4386..d93a95bb20a6 100644--- a/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.ts+++ b/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.ts@@ -13,7 +13,7 @@ import {TaskExecutionModeEnumApi,} from 'products/tasks/frontend/generated/api.schemas'-import { runStreamLogic } from '../../api/logics'+import { attachedContextItemKey, attachedContextLogic, runStreamLogic } from '../../api/logics'import type { SuggestionGroup, SuggestionItem } from '../../api/primitives'import { DEFAULT_HEADLINES, pickHeadline } from '../../api/primitives'import { runnerPanelLogic } from '../../logics/runnerPanelLogic'@@ -21,6 +21,7 @@ import { tasksLogic } from '../../logics/tasksLogic'import type { RepositoryConfig, Task } from '../../types/taskTypes'import { OriginProduct, TaskUpsertProps } from '../../types/taskTypes'import { DEFAULT_COMPOSER_EFFORT, DEFAULT_COMPOSER_MODEL, resolveEffortForModel } from '../../utils/composerModels'+import { wrapWithPosthogContext } from '../../utils/posthogContextBlock'import type { taskTrackerSceneLogicType } from './taskTrackerSceneLogicType'export type { ActiveCreation } from '../../logics/runnerPanelLogic'@@ -72,6 +73,8 @@ export const taskTrackerSceneLogic = kea<taskTrackerSceneLogicType>([['tasks', 'repositories', 'taskListParams'],integrationsLogic,['integrations'],+ attachedContextLogic,+ ['contextItems'],],actions: [runnerPanelLogic(props),@@ -80,6 +83,8 @@ export const taskTrackerSceneLogic = kea<taskTrackerSceneLogicType>([['loadTasks', 'loadRepositories', 'deleteTask'],integrationsLogic,['loadIntegrationsSuccess'],+ attachedContextLogic,+ ['markContextSent'],],})),@@ -235,6 +240,8 @@ export const taskTrackerSceneLogic = kea<taskTrackerSceneLogicType>([// Auto-run the task after creation; the detail scene shows the latest run by default. The// run checks out the chosen branch (server falls back to the repo's default branch if unset)// and launches with the picked model / reasoning effort (clamped to one the model supports).+ // Snapshot the context here so the keys marked sent below match exactly what got wrapped.+ const seededContext = values.contextItemsconst runResponse = await api.tasks.run(newTask.id, {branch: repositoryConfig.branch ?? null,runtime_adapter: ClaudeRuntimeAdapterEnumApi.Claude,@@ -246,9 +253,18 @@ export const taskTrackerSceneLogic = kea<taskTrackerSceneLogicType>([// pending_user_message from run state (the workflow doesn't forward it), so seed the// typed message as turn 1 — otherwise the first prompt is lost and the run idles.mode: TaskExecutionModeEnumApi.Interactive,- pending_user_message: description,+ // Wrap only the message sent to the agent with the on-screen context block; the task+ // `description` field and the optimistic seed (`startOptimisticRun`) stay raw.+ pending_user_message: wrapWithPosthogContext(description, seededContext),})+ // Mark the seeded non-text refs sent under the created task, so the run's first follow-up+ // (sent via `runInteractionLogic`) doesn't re-wrap them. Text items always resend.+ const seededKeys = seededContext.filter((item) => item.type !== 'text').map(attachedContextItemKey)+ if (seededKeys.length > 0) {+ actions.markContextSent(newTask.id, seededKeys)+ }+// Attach the real ids to the optimistic creation so the detail page adopts this seeded stream// (same `streamKey` + real `runId`) instead of cold-bootstrapping a fresh, skeleton-flashing one.// Kept set across navigation; cleared by the `urlToAction` below once the user leaves this run.diff --git a/products/posthog_ai/frontend/types/contextTypes.ts b/products/posthog_ai/frontend/types/contextTypes.tsnew file mode 100644index 000000000000..51fcf6290a22--- /dev/null+++ b/products/posthog_ai/frontend/types/contextTypes.ts@@ -0,0 +1,20 @@+/**+ * Abstract, domain-agnostic attached-context shape for the PostHog AI surface. The surface never+ * enumerates entity types — a provider names an arbitrary `type` (e.g. 'insight', 'dashboard',+ * 'trace', 'text') and the block builder renders it as-is.+ */+export interface AttachedContextItem {+ /** Arbitrary resource kind, e.g. 'insight', 'dashboard', 'trace', 'text'. */+ type: string+ /** Resource identifier — entity id, short_id, $ai_trace_id, … */+ key?: string | number+ /** Optional human-readable label. */+ label?: string+ /** Free-text payload (used when there's no keyed resource, e.g. type 'text'). */+ value?: string+}++/** Stable dedupe key for an attached context item: `${type}:${key ?? value}`. */+export function attachedContextItemKey(item: AttachedContextItem): string {+ return `${item.type}:${item.key ?? item.value ?? ''}`+}diff --git a/products/posthog_ai/frontend/types/streamTypes.ts b/products/posthog_ai/frontend/types/streamTypes.tsindex 79284a336d67..e65be94a0111 100644--- a/products/posthog_ai/frontend/types/streamTypes.ts+++ b/products/posthog_ai/frontend/types/streamTypes.ts@@ -71,6 +71,26 @@ export interface ToolInvocation {meta?: unknown}+/**+ * A tool-call lifecycle event published on the global `toolStreamEventsLogic` bus so a consumer can+ * react to the agent invoking a specific (resolved) tool — e.g. a scene that refreshes when the agent+ * creates a dashboard. Carries plain data only; the resolved name is computed in `runStreamLogic`.+ */+export type ToolStreamPhase = 'started' | 'updated' | 'completed' | 'failed'++export interface ToolStreamEvent {+ /** The `runStreamLogic` key the event was emitted from (conversation id or run/task id). */+ streamKey: string+ toolCallId: string+ /** Resolved registry key (inner PostHog MCP tool, e.g. 'create_dashboard') via `resolveToolCall`. */+ toolName: string+ /** The raw ACP tool name before resolution. */+ rawToolName: string+ phase: ToolStreamPhase+ invocation: ToolInvocation+ source: 'live' | 'replay' | 'client'+}+export type ThreadItemType =| 'human_message'| 'assistant_message'diff --git a/products/posthog_ai/frontend/utils/posthogContextBlock.test.ts b/products/posthog_ai/frontend/utils/posthogContextBlock.test.tsnew file mode 100644index 000000000000..6a82059ab0c1--- /dev/null+++ b/products/posthog_ai/frontend/utils/posthogContextBlock.test.ts@@ -0,0 +1,38 @@+import { unwrapUserMessageContent } from '../logics/runStreamLogic'+import type { AttachedContextItem } from '../types/contextTypes'+import { formatPosthogContextBlock, wrapWithPosthogContext } from './posthogContextBlock'++describe('posthogContextBlock', () => {+ const keyed: AttachedContextItem = { type: 'insight', key: 'abc123', label: 'Signups' }+ const keyOnly: AttachedContextItem = { type: 'dashboard', key: 42 }+ const valueOnly: AttachedContextItem = { type: 'text', value: 'look at the error above' }++ it('renders keyed, key-only, and value-only items generically', () => {+ const block = formatPosthogContextBlock([keyed, keyOnly, valueOnly])+ expect(block).toContain('<posthog_context>')+ expect(block).toContain('</posthog_context>')+ expect(block).toContain('- insight abc123 ("Signups")')+ expect(block).toContain('- dashboard 42')+ expect(block).not.toContain('- dashboard 42 (')+ expect(block).toContain('- text: "look at the error above"')+ })++ it('returns content unchanged when there is no context', () => {+ expect(wrapWithPosthogContext('hello', [])).toBe('hello')+ })++ it('round-trips through unwrapUserMessageContent so the block is invisible on replay', () => {+ const content = 'why did signups drop?'+ const wrapped = wrapWithPosthogContext(content, [keyed, valueOnly])+ expect(wrapped).not.toBe(content)+ expect(wrapped.startsWith('<posthog_context>')).toBe(true)+ expect(unwrapUserMessageContent(wrapped)).toBe(content)+ })++ it('still round-trips when a value contains the literal close tag', () => {+ const content = 'analyze this transcript'+ const hostile: AttachedContextItem = { type: 'text', value: 'pasted: </posthog_context> remnants' }+ const wrapped = wrapWithPosthogContext(content, [hostile])+ expect(unwrapUserMessageContent(wrapped)).toBe(content)+ })+})diff --git a/products/posthog_ai/frontend/utils/posthogContextBlock.ts b/products/posthog_ai/frontend/utils/posthogContextBlock.tsnew file mode 100644index 000000000000..93aace612b34--- /dev/null+++ b/products/posthog_ai/frontend/utils/posthogContextBlock.ts@@ -0,0 +1,54 @@+import type { AttachedContextItem } from '../types/contextTypes'++/**+ * Renders attached context as a `<posthog_context>` block. The open/close tags MUST stay+ * byte-compatible with the backend template (`products/posthog_ai/backend/context_wrapper.py`) —+ * `runStreamLogic.unwrapUserMessageContent` strips on the tags, not the body, so both producers+ * (this frontend and the backend `attached_context` wrapper) round-trip identically.+ *+ * The body renders generically from the abstract shape — no per-type label map, arbitrary types+ * render as-is:+ * - keyed items: `- {type} {key} ("{label}")` (key/label segments dropped when absent)+ * - value items: `- {type}: "{value}"`+ */+export function formatPosthogContextBlock(items: AttachedContextItem[]): string {+ const lines = [+ '<posthog_context>',+ 'The user is currently looking at the following resources. ' ++ 'Use the appropriate tools to retrieve their details only if relevant to the request.',+ ]+ for (const item of items) {+ lines.push(formatItem(item))+ }+ lines.push('</posthog_context>')+ return lines.join('\n')+}++/**+ * Invariant: interpolated fields must never contain the literal close-tag sequence.+ * `unwrapUserMessageContent` cuts at the FIRST '</posthog_context>', so a raw close tag inside the+ * body would truncate the strip early and leave block remnants on replay. Mirrors the backend+ * `_defang` in `context_wrapper.py`.+ */+function defang(text: string | number): string {+ return String(text).replace(/<\/posthog_context/g, '<\\/posthog_context')+}++function formatItem(item: AttachedContextItem): string {+ if (item.key === undefined || item.key === null || item.key === '') {+ return `- ${defang(item.type)}: "${defang(item.value ?? '')}"`+ }+ let line = `- ${defang(item.type)} ${defang(item.key)}`+ if (item.label) {+ line += ` ("${defang(item.label)}")`+ }+ return line+}++/** Prefixes `content` with the context block; returns `content` unchanged when `items` is empty. */+export function wrapWithPosthogContext(content: string, items: AttachedContextItem[]): string {+ if (items.length === 0) {+ return content+ }+ return `${formatPosthogContextBlock(items)}\n\n${content}`+}diff --git a/products/replay_vision/frontend/replay_scanners/components/ObservationSearchMaxChat.tsx b/products/replay_vision/frontend/replay_scanners/components/ObservationSearchMaxChat.tsxindex 6508fad8f90f..db5633ff082f 100644--- a/products/replay_vision/frontend/replay_scanners/components/ObservationSearchMaxChat.tsx+++ b/products/replay_vision/frontend/replay_scanners/components/ObservationSearchMaxChat.tsx@@ -7,6 +7,8 @@ import { useMaxTool } from 'scenes/max/useMaxTool'import { iconForType } from '~/layout/panel-layout/ProjectTree/defaultTree'+import { useAttachedContext } from 'products/posthog_ai/frontend/api/logics'+import { replayScannerLogic } from '../replayScannerLogic'/** A scanner-type-specific example question, shown in the copy and prefilled into Max when the user opens it. */@@ -38,6 +40,13 @@ export function ObservationSearchMaxChat({ scannerId }: { scannerId: string }):initialMaxPrompt: example,})+ useAttachedContext(+ scannerId !== 'new'+ ? [{ type: 'replay_vision_scanner', key: scannerId, label: scanner?.name ?? undefined }]+ : null,+ { active: scannerId !== 'new' }+ )+// Summarizer pages already surface a near-identical chat entry point — keep the Max tool, skip the card.if (!openMax || scanner?.scanner_type === 'summarizer') {return nulldiff --git a/products/replay_vision/frontend/replay_scanners/components/ScannerTypeConfigEditor.tsx b/products/replay_vision/frontend/replay_scanners/components/ScannerTypeConfigEditor.tsxindex c459196e5156..273ed5d198a8 100644--- a/products/replay_vision/frontend/replay_scanners/components/ScannerTypeConfigEditor.tsx+++ b/products/replay_vision/frontend/replay_scanners/components/ScannerTypeConfigEditor.tsx@@ -18,6 +18,8 @@ import { useMaxTool } from 'scenes/max/useMaxTool'import { iconForType } from '~/layout/panel-layout/ProjectTree/defaultTree'+import { useAttachedContext } from 'products/posthog_ai/frontend/api/logics'+import { replayScannerLogic } from '../replayScannerLogic'import { ClassifierScannerConfig, SummarizerScannerConfig, scannerTypeLabel } from '../types'@@ -66,6 +68,20 @@ function ScannerPromptField({callback: onDraftedPrompt,})+ useAttachedContext(+ scanner+ ? [+ { type: 'replay_vision_scanner', key: scannerId, label: scannerTypeLabel(scanner?.scanner_type) },+ {+ type: 'replay_vision_scanner_prompt',+ value: JSON.stringify(scanner?.scanner_config?.prompt || ''),+ label: 'Current prompt',+ },+ ]+ : null,+ { active: !!scanner }+ )+return (<div className="space-y-2"><div className="flex items-center justify-between gap-2">diff --git a/products/replay_vision/frontend/replay_scanners/components/SummarizerMaxChat.tsx b/products/replay_vision/frontend/replay_scanners/components/SummarizerMaxChat.tsxindex 70e55cdeb1ba..5fc77751d384 100644--- a/products/replay_vision/frontend/replay_scanners/components/SummarizerMaxChat.tsx+++ b/products/replay_vision/frontend/replay_scanners/components/SummarizerMaxChat.tsx@@ -7,6 +7,8 @@ import { useMaxTool } from 'scenes/max/useMaxTool'import { iconForType } from '~/layout/panel-layout/ProjectTree/defaultTree'+import { useAttachedContext } from 'products/posthog_ai/frontend/api/logics'+import { replayScannerLogic } from '../replayScannerLogic'/** PostHog AI entry point for summarizer scanners — lets the user chat about / digest the per-session summaries. */@@ -24,6 +26,13 @@ export function SummarizerMaxChat({ scannerId }: { scannerId: string }): JSX.EleinitialMaxPrompt: 'Find the common themes and patterns across these session summaries',})+ useAttachedContext(+ scannerId && scannerId !== 'new'+ ? [{ type: 'replay_vision_scanner', key: scannerId, label: scanner?.name ?? undefined }]+ : null,+ { active: isSummarizer && scannerId !== 'new' }+ )+if (!openMax) {return null}diff --git a/products/revenue_analytics/frontend/RevenueAnalyticsFilters.tsx b/products/revenue_analytics/frontend/RevenueAnalyticsFilters.tsxindex ad8dfcbdea3a..b2f7b822146a 100644--- a/products/revenue_analytics/frontend/RevenueAnalyticsFilters.tsx+++ b/products/revenue_analytics/frontend/RevenueAnalyticsFilters.tsx@@ -25,6 +25,8 @@ import { ReloadAll } from '~/queries/nodes/DataNode/Reload'import { RevenueAnalyticsBreakdown } from '~/queries/schema/schema-general'import { DateMappingOption } from '~/types'+import { useAttachedContext } from 'products/posthog_ai/frontend/api/logics'+import { DisplayMode, revenueAnalyticsLogic } from './revenueAnalyticsLogic'const DATE_FILTER_DATE_OPTIONS: DateMappingOption[] = [@@ -156,6 +158,19 @@ const RevenueAnalyticsPropertyFilters = (): JSX.Element => {const [displayFilters, setDisplayFilters] = useState(false)+ useAttachedContext([+ {+ type: 'revenue_analytics_filters',+ value: JSON.stringify({+ date_from: dateFrom,+ date_to: dateTo,+ breakdown: breakdownProperties,+ properties: revenueAnalyticsFilter,+ }),+ label: 'Current filters',+ },+ ])+return (<div className="flex flex-row gap-2"><MaxTooldiff --git a/products/revenue_analytics/frontend/RevenueAnalyticsScene.tsx b/products/revenue_analytics/frontend/RevenueAnalyticsScene.tsxindex 11eb2dda2ecc..3006ceca6a34 100644--- a/products/revenue_analytics/frontend/RevenueAnalyticsScene.tsx+++ b/products/revenue_analytics/frontend/RevenueAnalyticsScene.tsx@@ -18,9 +18,17 @@ import { SceneTitleSection } from '~/layout/scenes/components/SceneTitleSection'import { dataNodeCollectionLogic } from '~/queries/nodes/DataNode/dataNodeCollectionLogic'import { ProductIntentContext, ProductKey } from '~/queries/schema/schema-general'+import { useAttachedContext } from 'products/posthog_ai/frontend/api/logics'+import { Onboarding } from './Onboarding'import { RevenueAnalyticsFilters } from './RevenueAnalyticsFilters'-import { REVENUE_ANALYTICS_DATA_COLLECTION_NODE_ID, revenueAnalyticsLogic } from './revenueAnalyticsLogic'+import {+ REVENUE_ANALYTICS_DATA_COLLECTION_NODE_ID,+ REVENUE_ANALYTICS_QUERY_TO_NAME,+ REVENUE_ANALYTICS_QUERY_TO_SHORT_ID,+ RevenueAnalyticsQuery,+ revenueAnalyticsLogic,+} from './revenueAnalyticsLogic'import { RevenueAnalyticsViewStatusIcon } from './RevenueAnalyticsViewStatusIcon'import { revenueAnalyticsSettingsLogic } from './settings/revenueAnalyticsSettingsLogic'import { GrossRevenueTile, MRRTile, MetricsTile, OverviewTile, TopCustomersTile } from './tiles'@@ -39,6 +47,29 @@ export function RevenueAnalyticsScene(): JSX.Element {const { revenueEnabledDataWarehouseSources } = useValues(revenueAnalyticsLogic)const { featureFlags: enabledFlags } = useValues(enabledFeaturesLogic)+ useAttachedContext([+ {+ type: 'insight',+ key: REVENUE_ANALYTICS_QUERY_TO_SHORT_ID[RevenueAnalyticsQuery.MRR],+ label: REVENUE_ANALYTICS_QUERY_TO_NAME[RevenueAnalyticsQuery.MRR],+ },+ {+ type: 'insight',+ key: REVENUE_ANALYTICS_QUERY_TO_SHORT_ID[RevenueAnalyticsQuery.GROSS_REVENUE],+ label: REVENUE_ANALYTICS_QUERY_TO_NAME[RevenueAnalyticsQuery.GROSS_REVENUE],+ },+ {+ type: 'insight',+ key: REVENUE_ANALYTICS_QUERY_TO_SHORT_ID[RevenueAnalyticsQuery.METRICS],+ label: REVENUE_ANALYTICS_QUERY_TO_NAME[RevenueAnalyticsQuery.METRICS],+ },+ {+ type: 'insight',+ key: REVENUE_ANALYTICS_QUERY_TO_SHORT_ID[RevenueAnalyticsQuery.TOP_CUSTOMERS],+ label: REVENUE_ANALYTICS_QUERY_TO_NAME[RevenueAnalyticsQuery.TOP_CUSTOMERS],+ },+ ])+const sourceRunningForTheFirstTime = revenueEnabledDataWarehouseSources?.find((source) => source.status === 'Running' && !source.last_run_at)