:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(max): load the tool definitions table only when a tool is active (#126957)
Paul D'Ambra8556bfb1d4b8
diff --git a/frontend/src/scenes/max/MaxTool.tsx b/frontend/src/scenes/max/MaxTool.tsxindex 8fd0b5578a65..718c1ce47e1c 100644--- a/frontend/src/scenes/max/MaxTool.tsx+++ b/frontend/src/scenes/max/MaxTool.tsx@@ -4,7 +4,7 @@ import React from 'react'import { IconPlusSmall, IconSparkles, IconWrench } from '@posthog/icons'import { Tooltip } from '@posthog/lemon-ui'-import { ToolRegistration } from './max-constants'+import type { ToolDefinition, ToolRegistration } from './max-constants'import { useMaxTool } from './useMaxTool'export interface MaxToolProps extends Omit<ToolRegistration, 'name' | 'description'> {@@ -18,6 +18,24 @@ export interface MaxToolProps extends Omit<ToolRegistration, 'name' | 'descriptiposition?: 'top-right' | 'bottom-right' | 'top-left' | 'bottom-left'}+function toolTooltipTitle(definition: ToolDefinition, isMaxOpen: boolean): JSX.Element {+ return !isMaxOpen ? (+ <>+ <IconSparkles className="mr-1.5" />+ {definition.name} with PostHog AI+ </>+ ) : (+ <>+ PostHog AI can use this tool+ <br />+ <div className="flex items-center">+ {definition.icon || <IconWrench />}+ <i className="ml-1.5">{definition.name}</i>+ </div>+ </>+ )+}+/*** @deprecated MaxTool is deprecated and will be removed soon. Context aware AI will replace it. Talk to team-posthog-ai for future plans.*/@@ -48,33 +66,11 @@ export function MaxTool({onMaxOpen,})- let content: JSX.Element- if (!definition) {- content = <>{typeof Children === 'function' ? <Children toolAvailable={false} /> : Children}</>- } else {- content = (- <>- <Tooltip- title={- !isMaxOpen ? (- <>- <IconSparkles className="mr-1.5" />- {definition.name} with PostHog AI- </>- ) : (- <>- PostHog AI can use this tool- <br />- <div className="flex items-center">- {definition.icon || <IconWrench />}- <i className="ml-1.5">{definition.name}</i>- </div>- </>- )- }- placement="top-end"- delayMs={0}- >+ // The button shows while the tool table loads, and the children keep their tree position so they never remount.+ const content = (+ <>+ {openMax && (+ <Tooltip title={definition && toolTooltipTitle(definition, isMaxOpen)} placement="top-end" delayMs={0}><buttonclassName={clsx('absolute z-[750] transition duration-50 cursor-pointer -scale-x-100 hover:scale-y-110 hover:-scale-x-110 rounded-lg border border-dashed border-accent size-7 backdrop-blur-[2px] bg-[rgba(255,255,255,0.5)] dark:bg-[rgba(0,0,0,0.5)]',@@ -85,15 +81,15 @@ export function MaxTool({'border-ai bg-ai/08 dark:bg-ai/20 hover:scale-110')}type="button"- onClick={openMax || undefined}+ onClick={openMax}><IconPlusSmall className="relative size-full text-ai dark:text-white p-0.5" /></button></Tooltip>- {typeof Children === 'function' ? <Children toolAvailable={true} /> : Children}- </>- )- }+ )}+ {typeof Children === 'function' ? <Children toolAvailable={!!openMax} /> : Children}+ </>+ )return (<divclassName={clsx(diff --git a/frontend/src/scenes/max/max-constants.tsx b/frontend/src/scenes/max/max-constants.tsxindex 88d61eb71ede..d1ee63df73d0 100644--- a/frontend/src/scenes/max/max-constants.tsx+++ b/frontend/src/scenes/max/max-constants.tsx@@ -106,7 +106,7 @@ export interface ToolDefinition<N extends string = string> {}/** Active instance of a tool. */-export interface ToolRegistration extends Pick<ToolDefinition, 'name' | 'description'> {+export interface ToolRegistration extends Partial<Pick<ToolDefinition, 'name' | 'description'>> {/** A unique identifier for the tool */identifier: keyof typeof TOOL_DEFINITIONS/**diff --git a/frontend/src/scenes/max/useMaxTool.toolTable.test.tsx b/frontend/src/scenes/max/useMaxTool.toolTable.test.tsxnew file mode 100644index 000000000000..5e3b479c3de3--- /dev/null+++ b/frontend/src/scenes/max/useMaxTool.toolTable.test.tsx@@ -0,0 +1,55 @@+import { act, cleanup, render, waitFor } from '@testing-library/react'+import { useEffect } from 'react'++import * as retryImportModule from 'lib/utils/retryImport'++import { aiShellLogic } from '~/layout/ai/aiShellLogic'+import { initKeaTests } from '~/test/init'++import { MaxTool } from './MaxTool'+import { useMaxTool } from './useMaxTool'++function TestMaxTool(): null {+ useMaxTool({ identifier: 'read_data', context: { query: 'select 1' } })+ return null+}++// Its own file, so the module-level tool table cache starts empty. Only the last test lets the table load.+describe('useMaxTool before the tool table loads', () => {+ let releaseImports: () => void++ beforeEach(() => {+ initKeaTests()+ const imports = new Promise<void>((resolve) => (releaseImports = resolve))+ jest.spyOn(retryImportModule, 'retryImport').mockImplementation((importFn) => imports.then(importFn))+ })++ afterEach(() => {+ cleanup()+ jest.restoreAllMocks()+ })++ it('registers the tool with its context at once', () => {+ render(<TestMaxTool />)++ expect(aiShellLogic.values.registeredToolMap.read_data?.context).toEqual({ query: 'select 1' })+ })++ it('keeps the MaxTool children mounted when the tool table arrives', async () => {+ const onMount = jest.fn()+ function Child(): null {+ useEffect(onMount, [])+ return null+ }+ render(+ <MaxTool identifier="read_data" context={{ query: 'select 1' }}>+ <Child />+ </MaxTool>+ )++ act(() => releaseImports())+ await waitFor(() => expect(aiShellLogic.values.registeredToolMap.read_data?.name).toBeTruthy())++ expect(onMount).toHaveBeenCalledTimes(1)+ })+})diff --git a/frontend/src/scenes/max/useMaxTool.ts b/frontend/src/scenes/max/useMaxTool.tsindex a2791cf5272c..c9c46818a02a 100644--- a/frontend/src/scenes/max/useMaxTool.ts+++ b/frontend/src/scenes/max/useMaxTool.ts@@ -1,6 +1,6 @@import { useActions, useValues } from 'kea'import { router } from 'kea-router'-import { useEffect, useMemo, useRef } from 'react'+import { useEffect, useMemo, useRef, useState } from 'react'import { FEATURE_FLAGS } from 'lib/constants'import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'@@ -21,7 +21,7 @@ import { runnerPanelLogic } from '~/layout/ai/runnerPanelLogic'import { sidePanelLogic } from '~/layout/navigation-3000/sidepanel/sidePanelLogic'import { SidePanelTab } from '~/types'-import { ToolDefinition, ToolRegistration, getToolDefinition } from './max-constants'+import type { ToolDefinition, ToolRegistration } from './max-constants'export interface UseMaxToolOptions extends Omit<ToolRegistration, 'name' | 'description'> {/** Whether MaxTool functionality is active. When false, tool is not registered. */@@ -35,7 +35,7 @@ export interface UseMaxToolOptions extends Omit<ToolRegistration, 'name' | 'desc}export interface UseMaxToolReturn {- /** Tool definition - null if the tool is inactive (i.e. `active` is false or Max is not available) */+ /** Tool definition - null if the tool is inactive (i.e. `active` is false or Max is not available), or while the tool table loads */definition: ToolDefinition | null/** Whether the Max side panel is currently open */isMaxOpen: boolean@@ -47,6 +47,37 @@ export interface UseMaxToolReturn {// The chat logics stay out of the shell chunk. The shell loads them on the first open.const loadMaxToolOpener = (): Promise<typeof import('./maxToolOpener')> => retryImport(() => import('./maxToolOpener'))+// The tool table stays out of the shell chunk, and loads once a page turns a tool on.+type ToolDefinitionsModule = typeof import('./max-constants')+let loadedToolDefinitions: ToolDefinitionsModule | null = null+async function loadToolDefinitions(): Promise<ToolDefinitionsModule> {+ loadedToolDefinitions ??= await retryImport(() => import('./max-constants'))+ return loadedToolDefinitions+}++function useToolDefinitions(active: boolean): ToolDefinitionsModule | null {+ const [toolDefinitions, setToolDefinitions] = useState(loadedToolDefinitions)+ useEffect(() => {+ if (!active || toolDefinitions) {+ return+ }+ let cancelled = false+ loadToolDefinitions().then(+ (module) => {+ if (!cancelled) {+ setToolDefinitions(module)+ }+ },+ // A failed load only hides the tool name. A click on openMax tells the person to reload.+ () => {}+ )+ return (): void => {+ cancelled = true+ }+ }, [active, toolDefinitions])+ return toolDefinitions+}+const MAX_TOOL_CONTEXT_LENGTH = 4096const TOOL_PAGE_CONTEXT_PROVIDER_ID = 'max-tool-page'let toolPageContextOwner: string | null = null@@ -92,7 +123,7 @@ export function useMaxTool({const { activeCreation } = useValues(runnerPanelLogic({ panelId: MAX_SIDE_PANEL_ID }))const openChat = activeCreation ? (activeCreation.taskId ? 'task' : 'draft') : null- const definition = getToolDefinition(identifier)+ const definition = useToolDefinitions(active)?.getToolDefinition(identifier) ?? nullconst isMaxOpen = sidePanelOpen && selectedTab === SidePanelTab.Maxconst activeIdentifierRef = useRef<string | null>(null)const hookIdRef = useRef<string>(uuid())@@ -102,8 +133,9 @@ export function useMaxTool({latestRef.current = { context, active }const contextKey = useMemo(() => JSON.stringify(context), [context])+ // Register before the tool table loads, so a message sent at once still carries the tool context.useEffect(() => {- if (!active || !definition) {+ if (!active) {if (activeIdentifierRef.current) {deregisterTool(activeIdentifierRef.current)activeIdentifierRef.current = null@@ -118,8 +150,8 @@ export function useMaxTool({activeIdentifierRef.current = identifierregisterTool({identifier,- name: definition.name,- description: definition.description,+ name: definition?.name,+ description: definition?.description,context,contextDescription,introOverride,@@ -185,8 +217,9 @@ export function useMaxTool({? null: async (): Promise<void> => {let opener: Awaited<ReturnType<typeof loadMaxToolOpener>>+ let toolDefinitions: ToolDefinitionsModuletry {- opener = await loadMaxToolOpener()+ ;[opener, toolDefinitions] = await Promise.all([loadMaxToolOpener(), loadToolDefinitions()])} catch (error) {// Click handlers drop a rejected promise, and no error boundary sees it.lemonToast.error("Couldn't open PostHog AI. Reload the page to try again.", {@@ -208,8 +241,9 @@ export function useMaxTool({registerContext(TOOL_PAGE_CONTEXT_PROVIDER_ID, items)}// Show the suggestions from this specific tool- if (definition && suggestions && suggestions.length > 0) {- showToolSuggestions(definition.name, suggestions)+ const toolDefinition = toolDefinitions.getToolDefinition(identifier)+ if (toolDefinition && suggestions && suggestions.length > 0) {+ showToolSuggestions(toolDefinition.name, suggestions)}openSidePanel(SidePanelTab.Max, initialMaxPrompt)onMaxOpen?.()