: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
import { MakeLogicType, actions, connect, kea, listeners, path, selectors } from 'kea'
import { router } from 'kea-router'
import type { LocationChangedPayload } from 'kea-router/lib/types'
import posthog from 'posthog-js'
import { mainFocusUrl } from 'scenes/max/mainFocusUrl'
import { maxLogic } from 'scenes/max/maxLogic'
import { urls } from 'scenes/urls'
import {
MAX_SIDE_PANEL_ID,
REPORT_AI_PANEL,
SCOUT_AI_PANEL,
SIDE_PANEL_PANEL_ID,
type PhaiViewMode,
} from '~/layout/ai/aiPanelIds'
import { aiShellLogic } from '~/layout/ai/aiShellLogic'
import type { AttachedContextItem } from '~/layout/ai/attachedContext'
import { attachedContextLogic } from '~/layout/ai/attachedContextLogic'
import { type ActiveCreation, runnerPanelLogic } from '~/layout/ai/runnerPanelLogic'
import { sidePanelStateLogic } from '~/layout/navigation-3000/sidepanel/sidePanelStateLogic'
import { SidePanelTab } from '~/types'
import type { 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'
const FULL_SCREEN_CONTEXT_PROVIDER_ID = 'today-context-panel-full-screen'
function timeOf(item: TodayWorkItem): number {
return item.timestamp ? new Date(item.timestamp).getTime() : 0
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface todayAiChatLogicValues {
effectivePhaiView: PhaiViewMode // aiShellLogic
contextItems: AttachedContextItem[] // attachedContextLogic
conversationId: string | null // maxLogic
legacyChatTitle: string | null // maxLogic
activeCreation: ActiveCreation | null // runnerPanelLogic
selectedTabOptions: string | null // sidePanelStateLogic
lastSceneUrl: string | null // todayShellLogic
onAiPage: boolean // todayShellLogic
allRecentItems: TodayWorkItem[] // todaySpacesLogic
pinnedItems: TodayWorkItem[] // todaySpacesLogic
recentLoading: boolean // todaySpacesLogic
taskActivity: TaskActivityDTOApi[] // todaySpacesLogic
unreadSessionIds: Set<string> // todaySpacesLogic
activeItemId: string | null
chatTitle: string
fullScreenUrl: string | null
onTaskRunner: boolean
recentGroups: TodayWorkGroup[]
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface todayAiChatLogicActions {
setPhaiViewMode: (mode: PhaiViewMode) => {
mode: PhaiViewMode
} // aiShellLogic
deregisterContext: (providerId: string) => {
providerId: string
} // attachedContextLogic
registerContext: (
providerId: string,
items: AttachedContextItem[]
) => {
items: AttachedContextItem[]
providerId: string
} // attachedContextLogic
openConversation: (conversationId: string) => {
conversationId: string
} // maxLogic
startNewConversation: () => {
value: true
} // maxLogic
clearActiveCreation: () => {
value: true
} // runnerPanelLogic
setActiveCreation: (creation: ActiveCreation) => {
creation: ActiveCreation
} // runnerPanelLogic
setHistoryExpanded: (expanded: boolean) => {
expanded: boolean
} // runnerPanelLogic
openSidePanel: (
tab: SidePanelTab,
options?: string | undefined
) => {
options: string | undefined
tab: SidePanelTab
} // sidePanelStateLogic
setSidePanelOptions: (options: string | null) => {
options: string | null
} // sidePanelStateLogic
setFloatingOpen: (open: boolean) => {
open: boolean
} // todayContextPanelLogic
setFloatingTab: (tab: SidePanelTab) => {
tab: SidePanelTab
} // todayContextPanelLogic
queuePreviousChatsHint: () => {
value: true
} // todayPanelChatSessionLogic
markSessionRead: (
marker: import('../../../../products/tasks/frontend/generated/api.schemas').TaskActivityReadMarkerApi,
activityIds: string[]
) => {
activityIds: string[]
marker: import('../../../../products/tasks/frontend/generated/api.schemas').TaskActivityReadMarkerApi
} // todaySpacesLogic
carryContextToFullScreen: () => {
value: true
}
moveChatToPanel: (
mode: 'docked' | 'floating',
chat: TodayPanelChatTask | null
) => {
chat: TodayPanelChatTask | null
mode: 'docked' | 'floating'
}
openRecentItem: (item: TodayWorkItem) => {
item: TodayWorkItem
}
startNewChat: () => {
value: true
}
startNewChatForTool: () => {
value: true
}
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface todayAiChatLogicMeta {
__keaTypeGenInternalSelectorTypes: {
recentGroups: (allRecentItems: TodayWorkItem[], pinnedItems: TodayWorkItem[]) => TodayWorkGroup[]
activeItemId: (
effectivePhaiView: PhaiViewMode,
activeCreation: ActiveCreation | null,
conversationId: string | null
) => string | null
chatTitle: (
effectivePhaiView: PhaiViewMode,
activeItemId: string | null,
allRecentItems: TodayWorkItem[],
pinnedItems: TodayWorkItem[],
legacyChatTitle: string | null
) => string
onTaskRunner: (effectivePhaiView: PhaiViewMode, selectedTabOptions: string | null) => boolean
fullScreenUrl: (
onTaskRunner: boolean,
activeCreation: ActiveCreation | null,
conversationId: string | null
) => string | null
}
__keaTypeGenInternalReducerActions: {
'location changed (kea.router)': ({
method,
pathname,
search,
searchParams,
hash,
hashParams,
initial,
url,
routerState,
}: LocationChangedPayload) => {
payload: {
hash: string
hashParams: Record<string, any>
initial: boolean
method: 'POP' | 'PUSH' | 'REPLACE'
pathname: string
routerState: Record<string, any>
search: string
searchParams: Record<string, any>
url: string
}
type: 'location changed (kea.router)'
}
}
}
export type todayAiChatLogicType = MakeLogicType<
todayAiChatLogicValues,
todayAiChatLogicActions,
Record<string, any>,
todayAiChatLogicMeta
>
/** The context panel's PostHog AI chat: which chat is open, its recent chats, and moving it to full screen. */
export const todayAiChatLogic = kea<todayAiChatLogicType>([
path(['layout', 'today', 'todayAiChatLogic']),
connect(() => ({
values: [
todaySpacesLogic,
['allRecentItems', 'pinnedItems', 'unreadSessionIds', 'recentLoading', 'taskActivity'],
aiShellLogic,
['effectivePhaiView'],
maxLogic({ panelId: SIDE_PANEL_PANEL_ID }),
['chatTitle as legacyChatTitle', 'conversationId'],
runnerPanelLogic({ panelId: MAX_SIDE_PANEL_ID }),
['activeCreation'],
attachedContextLogic,
['contextItems'],
todayShellLogic,
['onAiPage', 'lastSceneUrl'],
sidePanelStateLogic,
['selectedTabOptions'],
],
actions: [
aiShellLogic,
['setPhaiViewMode'],
sidePanelStateLogic,
['setSidePanelOptions', 'openSidePanel'],
todayContextPanelLogic,
['setFloatingOpen', 'setFloatingTab'],
todaySpacesLogic,
['markSessionRead'],
maxLogic({ panelId: SIDE_PANEL_PANEL_ID }),
['openConversation', 'startNewConversation'],
runnerPanelLogic({ panelId: MAX_SIDE_PANEL_ID }),
['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 }),
}),
selectors({
recentGroups: [
(s) => [s.allRecentItems, s.pinnedItems],
(allRecentItems: TodayWorkItem[], pinnedItems: TodayWorkItem[]): TodayWorkGroup[] =>
groupByDay([...pinnedItems, ...allRecentItems].sort((first, second) => timeOf(second) - timeOf(first))),
],
activeItemId: [
(s) => [s.effectivePhaiView, s.activeCreation, s.conversationId],
(
effectivePhaiView: PhaiViewMode,
activeCreation: ActiveCreation | null,
conversationId: string | null
): string | null => (effectivePhaiView === 'new' ? (activeCreation?.taskId ?? null) : conversationId),
],
chatTitle: [
(s) => [s.effectivePhaiView, s.activeItemId, s.allRecentItems, s.pinnedItems, s.legacyChatTitle],
(
effectivePhaiView: PhaiViewMode,
activeItemId: string | null,
allRecentItems: TodayWorkItem[],
pinnedItems: TodayWorkItem[],
legacyChatTitle: string | null
): string => {
if (effectivePhaiView === 'legacy') {
return legacyChatTitle || 'PostHog AI'
}
if (!activeItemId) {
return 'New chat'
}
const item = [...pinnedItems, ...allRecentItems].find((recent) => recent.id === activeItemId)
return item?.title || 'Untitled chat'
},
],
// Report and scout chats run on the task runner in either view, the same as the side panel's own header.
onTaskRunner: [
(s) => [s.effectivePhaiView, s.selectedTabOptions],
(effectivePhaiView: PhaiViewMode, selectedTabOptions: string | null): boolean =>
effectivePhaiView === 'new' ||
selectedTabOptions === REPORT_AI_PANEL ||
selectedTabOptions === SCOUT_AI_PANEL,
],
fullScreenUrl: [
(s) => [s.onTaskRunner, s.activeCreation, s.conversationId],
(
onTaskRunner: boolean,
activeCreation: ActiveCreation | null,
conversationId: string | null
): string | null => mainFocusUrl({ isNewView: onTaskRunner, activeCreation, conversationId }),
],
}),
listeners(({ actions, values, cache }) => ({
startNewChat: () => {
if (values.onTaskRunner) {
actions.clearActiveCreation()
// An expanded task history would otherwise stay in place of the composer.
actions.setHistoryExpanded(false)
} else {
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 name
posthog.capture('today context panel recent opened', { kind: item.kind })
// A report or scout panel attaches its own entity's context, so it must not stay mounted on another chat.
if (values.selectedTabOptions) {
actions.setSidePanelOptions(null)
}
const newView = values.effectivePhaiView === 'new'
if (item.kind === 'session') {
if (newView && item.latestRunId) {
actions.setActiveCreation(runnerCreationFor({ taskId: item.id, runId: item.latestRunId }))
// Read tracking follows the /ai URL, which an inline open never changes, so mark it here.
const request = sessionReadRequest(values.taskActivity, item.id)
if (request) {
actions.markSessionRead(request.marker, request.activityIds)
}
} else {
router.actions.push(urls.aiTask(item.id))
}
return
}
if (newView) {
router.actions.push(urls.ai(item.id))
} else {
actions.openConversation(item.id)
}
},
moveChatToPanel: ({ mode, chat }) => {
// pinned: analytics event name
posthog.capture('today ai task moved to panel', { mode, has_task: !!chat })
// A report or scout panel attaches its own entity's context, so it must not stay on another chat.
actions.setSidePanelOptions(null)
if (chat) {
// A task only renders in the new view's runner, so a saved legacy view would show another chat.
if (values.effectivePhaiView !== 'new') {
actions.setPhaiViewMode('new')
}
actions.setActiveCreation(runnerCreationFor(chat))
} else {
actions.clearActiveCreation()
}
router.actions.push(values.lastSceneUrl ?? urls.projectHomepage())
if (mode === 'docked') {
actions.openSidePanel(SidePanelTab.Max)
} else {
actions.setFloatingTab(SidePanelTab.Max)
actions.setFloatingOpen(true)
}
},
// The chat's context comes from the scene behind it, and that scene unmounts on the way to /ai. A copy of
// what the composer shows rides along, so the full screen chat still knows what the user was looking at.
carryContextToFullScreen: () => {
if (values.contextItems.length > 0) {
actions.registerContext(FULL_SCREEN_CONTEXT_PROVIDER_ID, values.contextItems)
cache.fullScreenContext = 'pending'
}
},
// Closing the panel changes the URL before the page leaves the scene, so the copy is dropped only once the
// user has reached /ai and then left it.
[router.actionTypes.locationChanged]: () => {
if (values.onAiPage) {
if (cache.fullScreenContext === 'pending') {
cache.fullScreenContext = 'shown'
}
} else if (cache.fullScreenContext === 'shown') {
cache.fullScreenContext = null
actions.deregisterContext(FULL_SCREEN_CONTEXT_PROVIDER_ID)
}
},
})),
])