: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(today): start a new panel chat from AI tool buttons (#125149)
Adam Leith6e46d0e30c85
diff --git a/frontend/src/layout/today/TodayAiChatTitleMenu.tsx b/frontend/src/layout/today/TodayAiChatTitleMenu.tsxindex 3fdaae1ba667..ac2afccb2386 100644--- a/frontend/src/layout/today/TodayAiChatTitleMenu.tsx+++ b/frontend/src/layout/today/TodayAiChatTitleMenu.tsx@@ -1,4 +1,5 @@import { useActions, useValues } from 'kea'+import { useEffect, useRef } from 'react'import { IconChevronDown } from '@posthog/icons'import {@@ -13,10 +14,12 @@ import {Tooltip,TooltipContent,TooltipTrigger,+ anchoredToast,cn,} from '@posthog/quill'import { todayAiChatLogic } from './todayAiChatLogic'+import { todayPanelChatSessionLogic } from './todayPanelChatSessionLogic'import { TodaySessionIcon } from './TodaySessionIcon'interface TodayAiChatTitleMenuProps {@@ -26,6 +29,21 @@ interface TodayAiChatTitleMenuProps {export function TodayAiChatTitleMenu({ showChevron = true }: TodayAiChatTitleMenuProps): JSX.Element {const { chatTitle, recentGroups, recentLoading, activeItemId, unreadSessionIds } = useValues(todayAiChatLogic)const { openRecentItem } = useActions(todayAiChatLogic)+ const { previousChatsHintQueued } = useValues(todayPanelChatSessionLogic)+ const { previousChatsHintShown } = useActions(todayPanelChatSessionLogic)+ const triggerRef = useRef<HTMLButtonElement>(null)++ // The hint can be queued while the panel is closed, so it shows when this menu mounts.+ useEffect(() => {+ if (previousChatsHintQueued && triggerRef.current) {+ anchoredToast({+ description: 'Previous chats can be found here',+ anchor: triggerRef.current,+ side: 'bottom',+ })+ previousChatsHintShown()+ }+ }, [previousChatsHintQueued, previousChatsHintShown])return (<DropdownMenu>@@ -35,6 +53,7 @@ export function TodayAiChatTitleMenu({ showChevron = true }: TodayAiChatTitleMen<DropdownMenuTriggerrender={<Button+ ref={triggerRef}className="min-w-0 shrink gap-1.5 px-1.5 font-semibold"data-attr="today-ai-chat-recents">diff --git a/frontend/src/layout/today/todayAiChatLogic.ts b/frontend/src/layout/today/todayAiChatLogic.tsindex aa1a34ff258b..e32f333d33fc 100644--- a/frontend/src/layout/today/todayAiChatLogic.ts+++ b/frontend/src/layout/today/todayAiChatLogic.ts@@ -21,6 +21,7 @@ import { SCOUT_AI_PANEL } from 'products/signals/frontend/inbox/logics/scoutAiLoimport type { TaskActivityDTOApi } from '../../../../products/tasks/frontend/generated/api.schemas'import { todayContextPanelLogic } from './todayContextPanelLogic'import { TodayPanelChatTask, runnerCreationFor } from './todayPanelChat'+import { todayPanelChatSessionLogic } from './todayPanelChatSessionLogic'import { todayShellLogic } from './todayShellLogic'import { todaySpacesLogic } from './todaySpacesLogic'import { TodayWorkGroup, TodayWorkItem, groupByDay, sessionReadRequest } from './todayWorkItems'@@ -99,6 +100,9 @@ export interface todayAiChatLogicActions {setFloatingTab: (tab: SidePanelTab) => {tab: SidePanelTab} // todayContextPanelLogic+ queuePreviousChatsHint: () => {+ value: true+ } // todayPanelChatSessionLogicmarkSessionRead: (marker: import('../../../../products/tasks/frontend/generated/api.schemas').TaskActivityReadMarkerApi,activityIds: string[]@@ -122,6 +126,9 @@ export interface todayAiChatLogicActions {startNewChat: () => {value: true}+ startNewChatForTool: () => {+ value: true+ }}// Generated by kea-typegen. Update if you're an agent, ignore if you're human.@@ -217,11 +224,14 @@ export const todayAiChatLogic = kea<todayAiChatLogicType>([['setActiveCreation', 'clearActiveCreation', 'setHistoryExpanded'],attachedContextLogic,['registerContext', 'deregisterContext'],+ todayPanelChatSessionLogic,+ ['queuePreviousChatsHint'],],})),actions({openRecentItem: (item: TodayWorkItem) => ({ item }),startNewChat: true,+ startNewChatForTool: true,carryContextToFullScreen: true,moveChatToPanel: (mode: 'floating' | 'docked', chat: TodayPanelChatTask | null) => ({ mode, chat }),}),@@ -285,6 +295,20 @@ export const todayAiChatLogic = kea<todayAiChatLogicType>([actions.startNewConversation()}},+ // An AI tool button always starts a new chat. If that replaces an open chat, a hint shows where it went.+ startNewChatForTool: () => {+ const replacedChat = values.activeItemId !== null || (values.onTaskRunner && values.activeCreation !== null)+ // pinned: analytics event name+ posthog.capture('today ai tool chat started', { replaced_chat: replacedChat })+ // A report or scout panel attaches its own entity's context, so it must not stay on the new chat.+ if (values.selectedTabOptions) {+ actions.setSidePanelOptions(null)+ }+ actions.startNewChat()+ if (replacedChat) {+ actions.queuePreviousChatsHint()+ }+ },openRecentItem: ({ item }) => {// pinned: analytics event nameposthog.capture('today context panel recent opened', { kind: item.kind })diff --git a/frontend/src/layout/today/todayPanelChatSessionLogic.ts b/frontend/src/layout/today/todayPanelChatSessionLogic.tsindex deefcfb72653..7853272d1014 100644--- a/frontend/src/layout/today/todayPanelChatSessionLogic.ts+++ b/frontend/src/layout/today/todayPanelChatSessionLogic.ts@@ -1,4 +1,4 @@-import { MakeLogicType, afterMount, connect, kea, listeners, path } from 'kea'+import { MakeLogicType, actions, afterMount, connect, kea, listeners, path, reducers } from 'kea'import { MAX_SIDE_PANEL_ID } from 'scenes/max/components/PhaiSidePanelChat'@@ -16,6 +16,7 @@ function chatOf(creation: ActiveCreation | null): TodayPanelChatTask | null {// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface todayPanelChatSessionLogicValues {activeCreation: ActiveCreation | null // runnerPanelLogic+ previousChatsHintQueued: boolean}// Generated by kea-typegen. Update if you're an agent, ignore if you're human.@@ -26,6 +27,12 @@ export interface todayPanelChatSessionLogicActions {setActiveCreation: (creation: ActiveCreation) => {creation: ActiveCreation} // runnerPanelLogic+ previousChatsHintShown: () => {+ value: true+ }+ queuePreviousChatsHint: () => {+ value: true+ }}export type todayPanelChatSessionLogicType = MakeLogicType<@@ -43,6 +50,20 @@ export const todayPanelChatSessionLogic = kea<todayPanelChatSessionLogicType>([values: [runnerPanelLogic({ panelId: MAX_SIDE_PANEL_ID }), ['activeCreation']],actions: [runnerPanelLogic({ panelId: MAX_SIDE_PANEL_ID }), ['setActiveCreation', 'clearActiveCreation']],})),+ actions({+ queuePreviousChatsHint: true,+ previousChatsHintShown: true,+ }),+ reducers({+ // Kept here, not on the panel, because the panel can still be closed when a new chat replaces the open one.+ previousChatsHintQueued: [+ false,+ {+ queuePreviousChatsHint: () => true,+ previousChatsHintShown: () => false,+ },+ ],+ }),listeners(({ values }) => ({setActiveCreation: () => writeSessionValue(projectSessionKey(CHAT_SESSION_KEY), chatOf(values.activeCreation)),clearActiveCreation: () => writeSessionValue(projectSessionKey(CHAT_SESSION_KEY), null),diff --git a/frontend/src/scenes/max/useMaxTool.test.tsx b/frontend/src/scenes/max/useMaxTool.test.tsxindex 7be000690c56..b4b34e49889e 100644--- a/frontend/src/scenes/max/useMaxTool.test.tsx+++ b/frontend/src/scenes/max/useMaxTool.test.tsx@@ -1,27 +1,37 @@import { act, cleanup, render } from '@testing-library/react'+import { router } from 'kea-router'import { expectLogic } from 'kea-test-utils'import api from 'lib/api'+import { FEATURE_FLAGS } from 'lib/constants'+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'+import { urls } from 'scenes/urls'import { sidePanelStateLogic } from '~/layout/navigation-3000/sidepanel/sidePanelStateLogic'+import { todayPanelChatSessionLogic } from '~/layout/today/todayPanelChatSessionLogic'import { initKeaTests } from '~/test/init'import { SidePanelTab } from '~/types'+import { attachedContextLogic, runnerPanelLogic } from 'products/posthog_ai/frontend/api/logics'++import { MAX_SIDE_PANEL_ID } from './components/PhaiSidePanelChat'import { maxGlobalLogic } from './maxGlobalLogic'import { SIDE_PANEL_PANEL_ID, maxLogic } from './maxLogic'import { UseMaxToolReturn, useMaxTool } from './useMaxTool'function TestMaxTool({+ identifier = 'read_data',context,active = true,onRender,}: {+ identifier?: 'read_data' | 'create_experiment'context: Record<string, unknown>active?: booleanonRender?: (result: UseMaxToolReturn) => void}): null {const result = useMaxTool({- identifier: 'read_data',+ identifier,context,active,suggestions: ['Show me signups'],@@ -83,4 +93,88 @@ describe('useMaxTool', () => {{ content: 'Show me signups' },])})++ it.each([+ { nav: 'Today', chat: 'task', todayRailNav: true, hintQueued: true, taskId: 'task-1' },+ { nav: 'Today', chat: 'draft', todayRailNav: true, hintQueued: true, taskId: undefined },+ { nav: 'classic', chat: 'task', todayRailNav: false, hintQueued: false, taskId: 'task-1' },+ ])('replaces an open $nav panel $chat chat with a new chat', ({ todayRailNav, hintQueued, taskId }) => {+ featureFlagLogic.actions.setFeatureFlags([], {+ [FEATURE_FLAGS.TODAY_RAIL_NAV]: todayRailNav,+ [FEATURE_FLAGS.PHAI_SANDBOX_MODE]: true,+ })+ const panelChat = todayPanelChatSessionLogic()+ panelChat.mount()+ const runner = runnerPanelLogic({ panelId: MAX_SIDE_PANEL_ID })+ runner.actions.setActiveCreation({ streamKey: 'run-1', taskId, runId: taskId && 'run-1' })++ let openMax: UseMaxToolReturn['openMax'] = null+ render(<TestMaxTool context={{ query: 'select 1' }} onRender={(result) => (openMax = result.openMax)} />)+ act(() => openMax?.())++ expect(runner.values.activeCreation).toBeNull()+ expect(panelChat.values.previousChatsHintQueued).toBe(hintQueued)+ expect(attachedContextLogic.values.contextItems).toEqual([+ expect.objectContaining({ type: 'page', key: expect.any(String) }),+ expect.objectContaining({ type: 'tool_context', value: JSON.stringify({ query: 'select 1' }) }),+ ])+ expect(sidePanelStateLogic.values.selectedTab).toEqual(SidePanelTab.Max)+ panelChat.unmount()+ })++ it('attaches only the last clicked tool context, keeps it current, and releases it once a task opens', () => {+ featureFlagLogic.actions.setFeatureFlags([], { [FEATURE_FLAGS.PHAI_SANDBOX_MODE]: true })+ const unmountContextStore = attachedContextLogic.mount()+ const openers: Record<string, UseMaxToolReturn['openMax']> = {}+ const tools = (sqlQuery: string): JSX.Element => (+ <>+ <TestMaxTool context={{ query: sqlQuery }} onRender={(result) => (openers.sql = result.openMax)} />+ <TestMaxTool+ identifier="create_experiment"+ context={{ experiment: 'checkout' }}+ onRender={(result) => (openers.experiment = result.openMax)}+ />+ </>+ )+ const toolContextValues = (): (string | undefined)[] =>+ attachedContextLogic.values.contextItems+ .filter((item) => item.type === 'tool_context')+ .map((item) => item.value)++ const { rerender, unmount } = render(tools('select 1'))+ act(() => openers.experiment?.())+ act(() => openers.sql?.())+ expect(toolContextValues()).toEqual([JSON.stringify({ query: 'select 1' })])++ rerender(tools('select 2'))+ expect(toolContextValues()).toEqual([JSON.stringify({ query: 'select 2' })])++ act(() => router.actions.push(urls.sqlEditor()))+ expect(attachedContextLogic.values.contextItems[0]).toMatchObject({ type: 'page', key: urls.sqlEditor() })++ const runner = runnerPanelLogic({ panelId: MAX_SIDE_PANEL_ID })+ act(() => runner.actions.setActiveCreation({ streamKey: 'draft-1' }))+ expect(attachedContextLogic.values.contextItems).toEqual([])++ act(() => runner.actions.clearActiveCreation())+ expect(toolContextValues()).toEqual([JSON.stringify({ query: 'select 2' })])++ act(() => runner.actions.setActiveCreation({ streamKey: 'draft-2', taskId: 'task-2', runId: 'run-2' }))+ act(() => runner.actions.clearActiveCreation())+ expect(attachedContextLogic.values.contextItems).toEqual([])++ act(() => openers.sql?.())+ rerender(+ <TestMaxTool+ context={{ query: 'select 2' }}+ active={false}+ onRender={(result) => (openers.sql = result.openMax)}+ />+ )+ expect(attachedContextLogic.values.contextItems).toEqual([])++ unmount()+ expect(attachedContextLogic.values.contextItems).toEqual([])+ unmountContextStore()+ })})diff --git a/frontend/src/scenes/max/useMaxTool.ts b/frontend/src/scenes/max/useMaxTool.tsindex 9ee231fb12a3..8f1ba804d7c3 100644--- a/frontend/src/scenes/max/useMaxTool.ts+++ b/frontend/src/scenes/max/useMaxTool.ts@@ -1,11 +1,24 @@import { useActions, useValues } from 'kea'+import { router } from 'kea-router'import React, { useEffect, useMemo, useRef } from 'react'import { IconWrench } from '@posthog/icons'+import { FEATURE_FLAGS } from 'lib/constants'+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'+import { uuid } from 'lib/utils/dom'+import { removeProjectIdIfPresent } from 'lib/utils/kea-router'+import { sceneLogic } from 'scenes/sceneLogic'+import { sceneConfigurations } from 'scenes/scenes'+import { sidePanelLogic } from '~/layout/navigation-3000/sidepanel/sidePanelLogic'+import { todayAiChatLogic } from '~/layout/today/todayAiChatLogic'import { SidePanelTab } from '~/types'+import { attachedContextItemKey, attachedContextLogic, runnerPanelLogic } from 'products/posthog_ai/frontend/api/logics'+import type { AttachedContextItem } from 'products/posthog_ai/frontend/api/types'++import { MAX_SIDE_PANEL_ID } from './components/PhaiSidePanelChat'import { ToolDefinition, ToolRegistration, getToolDefinition } from './max-constants'import { maxGlobalLogic } from './maxGlobalLogic'import { sidePanelMaxLogic } from './maxLogic'@@ -31,6 +44,26 @@ export interface UseMaxToolReturn {openMax: (() => void) | null}+const MAX_TOOL_CONTEXT_LENGTH = 4096+const TOOL_PAGE_CONTEXT_PROVIDER_ID = 'max-tool-page'+let toolPageContextOwner: string | null = null++function toolPageContextItems(+ identifier: string,+ context: Record<string, unknown> | undefined,+ dismissGroup: string+): AttachedContextItem[] {+ const path = removeProjectIdIfPresent(router.values.location.pathname)+ const sceneId = sceneLogic.findMounted()?.values.activeSceneId+ const sceneName = sceneId ? sceneConfigurations[sceneId]?.name : undefined+ const items: AttachedContextItem[] = [{ type: 'page', key: path, label: sceneName || path, dismissGroup }]+ const value = context && Object.keys(context).length > 0 ? JSON.stringify(context) : null+ if (value && value.length <= MAX_TOOL_CONTEXT_LENGTH) {+ items.push({ type: 'tool_context', label: identifier, value, hidden: true, dismissGroup })+ }+ return items+}+/** Hook for registering a MaxTool and handling Max interactions programmatically, without the full MaxTool wrapper. */export function useMaxTool({identifier,@@ -45,12 +78,20 @@ export function useMaxTool({onMaxOpen,}: UseMaxToolOptions): UseMaxToolReturn {const { registerTool, deregisterTool } = useActions(maxGlobalLogic)+ const { registerContext, deregisterContext, undismissContext } = useActions(attachedContextLogic)const { openSidePanel } = useActions(sidePanelLogic)const { sidePanelOpen, selectedTab } = useValues(sidePanelLogic)+ const { featureFlags } = useValues(featureFlagLogic)+ const {+ location: { pathname },+ } = useValues(router)+ const { activeCreation } = useValues(runnerPanelLogic({ panelId: MAX_SIDE_PANEL_ID }))+ const openChat = activeCreation ? (activeCreation.taskId ? 'task' : 'draft') : nullconst definition = getToolDefinition(identifier)const isMaxOpen = sidePanelOpen && selectedTab === SidePanelTab.Maxconst activeIdentifierRef = useRef<string | null>(null)+ const hookIdRef = useRef<string>(uuid())const contextKey = useMemo(() => JSON.stringify(context), [context])useEffect(() => {@@ -94,13 +135,38 @@ export function useMaxTool({])useEffect(() => {+ if (toolPageContextOwner !== hookIdRef.current) {+ return+ }+ if (!active || openChat === 'task') {+ toolPageContextOwner = null+ deregisterContext(TOOL_PAGE_CONTEXT_PROVIDER_ID)+ return+ }+ if (openChat === 'draft') {+ deregisterContext(TOOL_PAGE_CONTEXT_PROVIDER_ID)+ return+ }+ registerContext(+ TOOL_PAGE_CONTEXT_PROVIDER_ID,+ toolPageContextItems(identifier, context, TOOL_PAGE_CONTEXT_PROVIDER_ID)+ )+ // oxlint-disable-next-line react-hooks/exhaustive-deps -- context is tracked via contextKey (serialized)+ }, [active, identifier, contextKey, pathname, openChat, registerContext, deregisterContext])++ useEffect(() => {+ const hookId = hookIdRef.currentreturn (): void => {if (activeIdentifierRef.current) {deregisterTool(activeIdentifierRef.current)activeIdentifierRef.current = null}+ if (toolPageContextOwner === hookId) {+ toolPageContextOwner = null+ deregisterContext(TOOL_PAGE_CONTEXT_PROVIDER_ID)+ }}- }, [deregisterTool])+ }, [deregisterTool, deregisterContext])return {definition: active ? definition : null,@@ -110,7 +176,26 @@ export function useMaxTool({: (): void => {const { startNewConversation, setActiveGroup } = sidePanelMaxLogic().actions// Start a new conversation so the prompt doesn't get added to an existing session- startNewConversation()+ if (featureFlags[FEATURE_FLAGS.TODAY_RAIL_NAV]) {+ // The Today panel can show a task chat too, so its own logic starts the new chat.+ const unmount = todayAiChatLogic.mount()+ todayAiChatLogic.actions.startNewChatForTool()+ unmount()+ } else if (maxGlobalLogic.values.effectivePhaiView === 'new') {+ const runner = runnerPanelLogic({ panelId: MAX_SIDE_PANEL_ID })+ const unmount = runner.mount()+ runner.actions.clearActiveCreation()+ runner.actions.setHistoryExpanded(false)+ unmount()+ } else {+ startNewConversation()+ }+ if (maxGlobalLogic.values.effectivePhaiView === 'new') {+ toolPageContextOwner = hookIdRef.current+ const items = toolPageContextItems(identifier, context, TOOL_PAGE_CONTEXT_PROVIDER_ID)+ undismissContext(attachedContextItemKey(items[0]), TOOL_PAGE_CONTEXT_PROVIDER_ID)+ registerContext(TOOL_PAGE_CONTEXT_PROVIDER_ID, items)+ }// Show the suggestions from this specific toolif (definition && suggestions && suggestions.length > 0) {setActiveGroup(