: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): make the floating ai button dockable and dismissable (#119436)
Adam Leithf7396efa1882
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 692b20237872..3db293eeb757 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -4605,9 +4605,9 @@ snapshots:lemon-ui-icons2--shelf-n--light:hash: v1.k794b7964.943cd26ad3f1cd3729ce4cd5bd077546bf4fe1f7e8908ad93b6bc0a22211ff82.NK0Mllxr902YBaNjL3l2g1Ohcp5fSuE1okazzBtKgXYlemon-ui-icons2--shelf-o--dark:- hash: v1.k794b7964.7d75b1562567dd5342e81a2bdc2e89ab42a39458c6bec8b28669daf6d56126d1.-sPXGYIM3nVW98TKSSAFDeoz8C1AeNT5ojS1-0l3BJY+ hash: v1.k794b7964.5c78959b4195a4a1acfca10c530b3ab80803f01839de41c437c4407b3211e40b.tNbGw7O-Y_7HHolreSY7pz1_BLPRg7K7O-IcTPiyKE0lemon-ui-icons2--shelf-o--light:- hash: v1.k794b7964.2af9cd7fca97270f8ce11698e014a928851ff2021cb6f5ac1f82b49924637295.hNvwQ5qzm6pPgp93CAoYrn-VgjPmzWT7ZiDiE_H5QPs+ hash: v1.k794b7964.76c14e4e35bff1ff494a2cebc91cd8cc4baa12f5fc5c069dd94e886ac9beb474.AN6c7L9lXRqc2nN3SUxch3np2OcoZlVFPS28moHjmVUlemon-ui-icons2--shelf-p--dark:hash: v1.k794b7964.06736fe539d74737a210c19b4e6cd26a271b59819af0bb64463fd31ce54d208a.V2n-b5E0nFYb8_EwOpKsPzLtJz-Nrj-GVKFk-JYOjBwlemon-ui-icons2--shelf-p--light:@@ -4649,9 +4649,9 @@ snapshots:lemon-ui-icons3--shelf-t--light:hash: v1.k794b7964.32b7f9b829c3082b5b3e3dc517b62f234b76f4c3290210f7a524bd9f98a82ab8.UinV4Lq9mrCVtde2PapxbYiSjLZDHeDpzArmyB3GJPIlemon-ui-icons3--shelf-u--dark:- hash: v1.k794b7964.8c34f50c0e4bf5874ee0b544bc35ddb64d76f3dddf15b6d03e00c172dbaabba1.2cX2NWgpIQ23P7HbmyTSaIaUA88m5xVoUjT5djupG-g+ hash: v1.k794b7964.28896fd9d00d07ff2220330d27d1bc7e53328e58c2b32834eeba51b3680e0b2a.AeSyt1goC4KtinqN-R3FAnu34tIFO6s41dRz9mZiYGolemon-ui-icons3--shelf-u--light:- hash: v1.k794b7964.7806f47c9764bddce6768719f8f49ad2735d02ef55c55883daaa23e0ef01ed1e.560ISdnrtRrv145K2SpaUhQGXyUmNHySZzieogXDqho+ hash: v1.k794b7964.33fb378edf43dd49a55684007e3351d67e8de983f42d23598a7caaaecb2d262e.mW-LIPRw_FbtjkaKMRfrI1nrOeHrDhrMVTxmJsw1G_Ulemon-ui-icons3--shelf-v--dark:hash: v1.k794b7964.134236cfb4de7bd8b2a78f6d46d35ee5a36f00ff0b75bbc7f87317d38e3ae7e3.9YVTZAEkua5Li48ge8SlJV5CuNTBXYlGg0xBmnspu4slemon-ui-icons3--shelf-v--light:@@ -9427,9 +9427,9 @@ snapshots:scenes-app-analytics--list-space--light:hash: v1.k794b7964.df1ef949811073830fa620d905b8abdc14cdf4a4ae3129d962ab678186bd8727.uWlFQERiA-1QpohoPbgqHGPOwHU4d9QSg6KQX6qHBxUscenes-app-analytics--mine--dark:- hash: v1.k794b7964.659428eb68d4d634c208995e28dbfe344ddcf0cca992b94675b477c7adbd440f.vH9NIDJc_a7Iwuz5Almo0pe63ikM-JQrv0Un1QM-FS4+ hash: v1.k794b7964.bb59918810a92bfbfc2e3f30ad1eb218c0a6ba58ca25655b6007129d963599b1.Dm6FmdMgZMWl6QMTEWolU0B6Z82WRCgE--ap7yyFO10scenes-app-analytics--mine--light:- hash: v1.k794b7964.b5f523dd51f2e6f3cbaafa4363f455e57836cb02761cc6aaec94b56b4ddea44d.ZnN6FG9-YmW4hFdv3dRyr5HRFZb33OmeNZ5jMNicTJA+ hash: v1.k794b7964.98afd0e9cc82295301ee38ecbac67a15b64f99af446c8efc09d100668512e18a.tuARP9J2x7maARISipcsPmer_sYhiSdp0aVaDhTnN4wscenes-app-analytics--spaces--dark:hash: v1.k794b7964.978b19e47d5106243cfe2873e2a623a4e22cf89139df7bce365824ab34fde2b1.L4q9XBXDrhvtrZUasYZpzrKf2jCcvE7WORywHS7brOcscenes-app-analytics--spaces--light:@@ -10583,9 +10583,9 @@ snapshots:scenes-app-errortracking--group-page-releases-stacked--light:hash: v1.k794b7964.6229ba0294619c7c881929c7375df4700325ee629f842369641e5fe2355c1cd4._sFGlcefvjCQOkjMzoP9-CWeQ054s-pQHQ0vChbYbhEscenes-app-errortracking--group-page-today-rail-nav--dark:- hash: v1.k794b7964.51774301e193ce23aa082825a13a4c8222b1ab7cee5020316650a30a09263ca8.rtaHVo9A6Ks4bR_fBhcE_ti4Y1afBzbXUMGbb7wsQLk+ hash: v1.k794b7964.0a696b9018fe814439ef41070a904b0bf6d5aafd3fb668cf1858b1f78b0a0783.O5x-0QjnG3NmkLmJhxQt3xJZjCeAB5lWE-M1tqJq3KIscenes-app-errortracking--group-page-today-rail-nav--light:- hash: v1.k794b7964.7087fa389913eb61a5e8eca00e0519ec11efd6395e6d4c6e646f080fcbda2333.1SYO_4nSy1Dzp--Kn2CPGcG_GZhFEGF6feO3oHBHcMA+ hash: v1.k794b7964.9c527d3c4158b4d9adfc3f3a28dd18473da4b22bbc1a4eb2777f1f7da62261e5.eDDfQ09EGFBH5OQpxZPRX4ThjCT9wVqrhS49IrKnq7Qscenes-app-errortracking--group-page-with-many-self-driving-reports--dark:hash: v1.k794b7964.0aa0858442d3e422f4825c4665d289c006c87b1c5a22265e447a1c0fa5e5a544.Hy3i1o_nWpWVqH4WqCEDvZTI4LQxeI2c9B6GW9rHDYAscenes-app-errortracking--group-page-with-many-self-driving-reports--light:diff --git a/frontend/src/layout/today/TodayAiChatTitleMenu.tsx b/frontend/src/layout/today/TodayAiChatTitleMenu.tsxindex d2fee3091c39..3fdaae1ba667 100644--- a/frontend/src/layout/today/TodayAiChatTitleMenu.tsx+++ b/frontend/src/layout/today/TodayAiChatTitleMenu.tsx@@ -10,26 +10,47 @@ import {DropdownMenuLabel,DropdownMenuTrigger,Spinner,+ Tooltip,+ TooltipContent,+ TooltipTrigger,cn,} from '@posthog/quill'import { todayAiChatLogic } from './todayAiChatLogic'import { TodaySessionIcon } from './TodaySessionIcon'-export function TodayAiChatTitleMenu(): JSX.Element {+interface TodayAiChatTitleMenuProps {+ showChevron?: boolean+}++export function TodayAiChatTitleMenu({ showChevron = true }: TodayAiChatTitleMenuProps): JSX.Element {const { chatTitle, recentGroups, recentLoading, activeItemId, unreadSessionIds } = useValues(todayAiChatLogic)const { openRecentItem } = useActions(todayAiChatLogic)return (<DropdownMenu>- <DropdownMenuTrigger- render={- <Button className="min-w-0 shrink gap-1.5 px-1.5 font-semibold" data-attr="today-ai-chat-recents">- <span className="min-w-0 truncate">{chatTitle}</span>- <IconChevronDown className="size-3 shrink-0 text-muted-foreground" />- </Button>- }- />+ <Tooltip>+ <TooltipTrigger+ render={+ <DropdownMenuTrigger+ render={+ <Button+ className="min-w-0 shrink gap-1.5 px-1.5 font-semibold"+ data-attr="today-ai-chat-recents"+ >+ <span className="min-w-0 truncate">{chatTitle}</span>+ {showChevron && (+ <IconChevronDown className="size-3 shrink-0 text-muted-foreground" />+ )}+ </Button>+ }+ />+ }+ />+ <TooltipContent side="bottom" align="start" className="max-w-80">+ {chatTitle}+ </TooltipContent>+ </Tooltip><DropdownMenuContent className="w-72">{recentGroups.length === 0 ? (recentLoading ? (diff --git a/frontend/src/layout/today/TodayContextPanelFloating.tsx b/frontend/src/layout/today/TodayContextPanelFloating.tsxindex 961baafc922c..489e0ca64839 100644--- a/frontend/src/layout/today/TodayContextPanelFloating.tsx+++ b/frontend/src/layout/today/TodayContextPanelFloating.tsx@@ -1,31 +1,26 @@import { useActions, useValues } from 'kea'import { useRef } from 'react'-import { IconSparkles } from '@posthog/icons'-import {- Button,- Popover,- PopoverContent,- PopoverTrigger,- Tooltip,- TooltipContent,- TooltipTrigger,-} from '@posthog/quill'+import { Popover, PopoverContent } from '@posthog/quill'import { SidePanelTab } from '~/types'import { TodayContextPanelCard } from './TodayContextPanelCard'-import { TODAY_CONTEXT_PANEL_DOCK_EDGE, todayContextPanelLogic } from './todayContextPanelLogic'+import { TodayContextPanelLauncher } from './TodayContextPanelLauncher'+import {+ TODAY_CONTEXT_PANEL_DOCK_EDGE,+ TODAY_SIDE_PANEL_DEFAULT_WIDTH,+ todayContextPanelLogic,+} from './todayContextPanelLogic'/** Presses on these inside the header act on them instead of moving the panel. */const NOT_A_DRAG_HANDLE = 'button, a, input, [role="menuitem"]'export function TodayContextPanelFloating(): JSX.Element {- const { floatingOpen, floatingOffset, floatingActiveTab, docked, dockHint, panelTabs } =+ const { floatingOpen, floatingOffset, floatingActiveTab, dockHint, launcherAlign } =useValues(todayContextPanelLogic)const { setFloatingOpen, setFloatingTab, setFloatingOffset, setDockHint, dock } = useActions(todayContextPanelLogic)const cardRef = useRef<HTMLDivElement>(null)- const launcherHidden = docked || !panelTabs.includes(SidePanelTab.Max)const startDrag = (event: React.PointerEvent<HTMLDivElement>): void => {if (event.button !== 0 || (event.target as HTMLElement).closest(NOT_A_DRAG_HANDLE)) {@@ -89,41 +84,10 @@ export function TodayContextPanelFloating(): JSX.Element {setFloatingOpen(open)}}>- {/* Stays mounted while docked, so the button can sink away and rise back with the panel. Scenes- without PostHog AI, like a canvas, hide it but keep the host for other undocked tabs. */}- <div- data-quill- className="TodayContextPanelButton pointer-events-none absolute inset-x-0 bottom-4 z-[var(--z-main-nav)] flex justify-center"- data-hidden={launcherHidden || undefined}- {...(launcherHidden ? { inert: '' } : {})}- >- {/* The outline button is see-through, so an opaque pill sits behind it over the page. */}- <span className="pointer-events-auto rounded-full bg-background shadow-md">- <Tooltip>- <TooltipTrigger- delay={0}- render={- <PopoverTrigger- render={- <Button- variant="outline"- size="lg"- aria-label="Ask PostHog AI"- className="w-34 justify-center rounded-full"- data-attr="today-ai-chat-button"- />- }- />- }- >- <IconSparkles />- </TooltipTrigger>- <TooltipContent side="top">Ask PostHog AI</TooltipContent>- </Tooltip>- </span>- </div>+ <TodayContextPanelLauncher /><PopoverContentside="top"+ align={launcherAlign}sideOffset={8}initialFocus={() =>cardRef.current?.querySelector<HTMLElement>('textarea, [contenteditable="true"]') ?? true@@ -147,7 +111,10 @@ export function TodayContextPanelFloating(): JSX.Element {<divdata-quillaria-hidden- className="pointer-events-none fixed top-10 right-1 bottom-1 z-[var(--z-layout-panel)] w-[min(32rem,40vw)] rounded-lg border border-dashed border-ring bg-[var(--fill-hover)] opacity-60"+ className="pointer-events-none fixed top-10 right-1 bottom-1 z-[var(--z-layout-panel)] rounded-lg border border-dashed border-ring bg-[var(--fill-hover)] opacity-60"+ // The docked panel's default width, less its own inset, so the outline shows where the card lands.+ // eslint-disable-next-line react/forbid-dom-props+ style={{ width: `calc(${TODAY_SIDE_PANEL_DEFAULT_WIDTH}px - 0.5rem)` }}/>)}</>diff --git a/frontend/src/layout/today/TodayContextPanelHeader.tsx b/frontend/src/layout/today/TodayContextPanelHeader.tsxindex f651a8607170..a513c0fdd8c5 100644--- a/frontend/src/layout/today/TodayContextPanelHeader.tsx+++ b/frontend/src/layout/today/TodayContextPanelHeader.tsx@@ -1,16 +1,15 @@import { useActions, useValues } from 'kea'-import { IconExpand45, IconExternal, IconPlus, IconSidePanel, IconX } from '@posthog/icons'+import { IconMinus, IconPlus, IconX } from '@posthog/icons'import { Button, CardHeader, Tooltip, TooltipContent, TooltipTrigger, cn } from '@posthog/quill'-import { LinkPrimitive } from 'lib/lemon-ui/Link'-import { SIDE_PANEL_TABS } from '~/layout/navigation-3000/sidepanel/sidePanelTabs'import { SidePanelTab } from '~/types'import { todayAiChatLogic } from './todayAiChatLogic'import { TodayAiChatTitleMenu } from './TodayAiChatTitleMenu'import { todayContextPanelLogic } from './todayContextPanelLogic'+import { TodayContextPanelMenu } from './TodayContextPanelMenu'interface TodayContextPanelHeaderProps {docked: boolean@@ -22,13 +21,11 @@ function HeaderIconButton({label,dataAttr,onClick,- render,children,}: {label: stringdataAttr: stringonClick?: () => void- render?: React.ReactElementchildren: React.ReactNode}): JSX.Element {return (@@ -41,7 +38,6 @@ function HeaderIconButton({aria-label={label}className="text-muted-foreground hover:text-foreground"onClick={onClick}- render={render}data-attr={dataAttr}/>}@@ -54,11 +50,9 @@ function HeaderIconButton({}export function TodayContextPanelHeader({ docked, onDragStart }: TodayContextPanelHeaderProps): JSX.Element {- const { activeTab, fullScreenUrl: tabFullScreenUrl, canUndock } = useValues(todayContextPanelLogic)- const { dock, undock, close, openFullScreen } = useActions(todayContextPanelLogic)- const { fullScreenUrl: aiFullScreenUrl } = useValues(todayAiChatLogic)- const { startNewChat, carryContextToFullScreen } = useActions(todayAiChatLogic)- const fullScreenUrl = activeTab === SidePanelTab.Max ? aiFullScreenUrl : tabFullScreenUrl+ const { activeTab } = useValues(todayContextPanelLogic)+ const { close } = useActions(todayContextPanelLogic)+ const { startNewChat } = useActions(todayAiChatLogic)return (<CardHeader@@ -69,7 +63,7 @@ export function TodayContextPanelHeader({ docked, onDragStart }: TodayContextPanonPointerDown={onDragStart}>{activeTab === SidePanelTab.Max ? (- <TodayAiChatTitleMenu />+ <TodayAiChatTitleMenu showChevron={docked} />) : (// As tall as the chat's title button, so the header keeps its height across tabs.<span className="flex h-7 min-w-0 items-center px-1.5 font-semibold">@@ -82,32 +76,12 @@ export function TodayContextPanelHeader({ docked, onDragStart }: TodayContextPan<IconPlus /></HeaderIconButton>)}- {fullScreenUrl && (- <HeaderIconButton- label="Open full screen"- dataAttr="today-context-panel-full-screen"- onClick={() => {- if (activeTab === SidePanelTab.Max) {- carryContextToFullScreen()- }- openFullScreen()- }}- render={<LinkPrimitive to={fullScreenUrl} />}- >- <IconExpand45 />- </HeaderIconButton>- )}- {docked ? (- canUndock && (- <HeaderIconButton label="Undock" onClick={undock} dataAttr="today-context-panel-undock">- <IconExternal />- </HeaderIconButton>- )- ) : (- <HeaderIconButton label="Dock to the right" onClick={dock} dataAttr="today-context-panel-dock">- <IconSidePanel />+ {!docked && (+ <HeaderIconButton label="Minimize" onClick={close} dataAttr="today-context-panel-minimize">+ <IconMinus /></HeaderIconButton>)}+ <TodayContextPanelMenu docked={docked} /><HeaderIconButton label="Close" onClick={close} dataAttr="today-context-panel-close"><IconX /></HeaderIconButton>diff --git a/frontend/src/layout/today/TodayContextPanelLauncher.tsx b/frontend/src/layout/today/TodayContextPanelLauncher.tsxnew file mode 100644index 000000000000..dec4027a4a76--- /dev/null+++ b/frontend/src/layout/today/TodayContextPanelLauncher.tsx@@ -0,0 +1,183 @@+import { useActions, useValues } from 'kea'+import { useEffect, useRef, useState } from 'react'++import { IconSparkles, IconX } from '@posthog/icons'+import { Button, PopoverTrigger, Tooltip, TooltipContent, TooltipTrigger, cn } from '@posthog/quill'++import { TodayLauncherAlign, todayContextPanelLogic } from './todayContextPanelLogic'++const DRAG_THRESHOLD = 5++const ALIGNS: TodayLauncherAlign[] = ['start', 'center', 'end']++const JUSTIFY_CLASSES: Record<TodayLauncherAlign, string> = {+ start: 'justify-start',+ center: 'justify-center',+ end: 'justify-end',+}++const ZONE_CLASSES: Record<TodayLauncherAlign, string> = {+ start: 'left-0',+ center: 'left-1/2 -translate-x-1/2',+ end: 'right-0',+}++interface LauncherDrag {+ dx: number+ dy: number+ nearest: TodayLauncherAlign+}++/** The zones sit side by side along one edge, so the closest one is whichever third of the edge the button is over. */+function nearestAlign(host: DOMRect, centerX: number): TodayLauncherAlign {+ const third = Math.min(Math.max(Math.floor(((centerX - host.left) / host.width) * 3), 0), 2)+ return ALIGNS[third]+}++export function TodayContextPanelLauncher(): JSX.Element {+ const { launcherAlign, launcherHidden, floatingOpen } = useValues(todayContextPanelLogic)+ const { setLauncherAlign, hideLauncher } = useActions(todayContextPanelLogic)+ const hostRef = useRef<HTMLDivElement>(null)+ // Set when a press turned into a drag, so the click that ends it doesn't also open the panel.+ const draggedRef = useRef(false)+ const [drag, setDrag] = useState<LauncherDrag | null>(null)+ // Ends an active drag. A release outside the window never reaches the listeners, so blur and unmount call this.+ const stopDragRef = useRef<(() => void) | null>(null)++ useEffect(() => () => stopDragRef.current?.(), [])++ const startDrag = (event: React.PointerEvent<HTMLSpanElement>): void => {+ draggedRef.current = false+ const host = hostRef.current?.getBoundingClientRect()+ if (event.button !== 0 || !host || (event.target as HTMLElement).closest('[data-launcher-close]')) {+ return+ }+ const start = { x: event.clientX, y: event.clientY }+ const button = event.currentTarget.getBoundingClientRect()+ const originX = button.left + button.width / 2+ const nearest = (clientX: number): TodayLauncherAlign => nearestAlign(host, originX + clientX - start.x)++ const move = (moveEvent: PointerEvent): void => {+ const dx = moveEvent.clientX - start.x+ const dy = moveEvent.clientY - start.y+ if (!draggedRef.current && Math.hypot(dx, dy) < DRAG_THRESHOLD) {+ return+ }+ draggedRef.current = true+ setDrag({ dx, dy, nearest: nearest(moveEvent.clientX) })+ }+ const stop = (): void => {+ window.removeEventListener('pointermove', move)+ window.removeEventListener('pointerup', end)+ window.removeEventListener('pointercancel', end)+ window.removeEventListener('blur', cancel)+ stopDragRef.current = null+ setDrag(null)+ }+ const end = (endEvent: PointerEvent): void => {+ const align = nearest(endEvent.clientX)+ if (draggedRef.current && endEvent.type === 'pointerup' && align !== launcherAlign) {+ setLauncherAlign(align)+ }+ stop()+ }+ // A cancelled drag leaves the button where it was, and no click follows to swallow.+ const cancel = (): void => {+ draggedRef.current = false+ stop()+ }++ // Window listeners, not pointer capture: capture would retarget the closing click away from the button.+ window.addEventListener('pointermove', move)+ window.addEventListener('pointerup', end)+ window.addEventListener('pointercancel', end)+ window.addEventListener('blur', cancel)+ stopDragRef.current = cancel+ }++ return (+ // Stays mounted while docked, so the button can sink away and rise back with the panel. Scenes without+ // PostHog AI, like a canvas, hide it but keep the host for other undocked tabs.+ <div+ ref={hostRef}+ data-quill+ className={cn(+ 'TodayContextPanelButton pointer-events-none absolute inset-x-4 bottom-4 z-[var(--z-main-nav)] flex',+ JUSTIFY_CLASSES[launcherAlign]+ )}+ data-hidden={launcherHidden || undefined}+ {...(launcherHidden ? { inert: '' } : {})}+ >+ {drag &&+ ALIGNS.map((align) => (+ <div+ key={align}+ aria-hidden+ className={cn(+ 'absolute bottom-0 h-7 w-24 rounded-full border border-dashed border-ring transition-opacity',+ ZONE_CLASSES[align],+ align === drag.nearest ? 'bg-[var(--fill-hover)] opacity-100' : 'opacity-40'+ )}+ />+ ))}+ {/* The outline button is see-through, so an opaque pill sits behind it over the page. */}+ <span+ className="group/launcher pointer-events-auto relative touch-none rounded-full bg-background shadow-md select-none data-[dragging]:cursor-grabbing data-[dragging]:shadow-lg"+ data-dragging={drag ? '' : undefined}+ onPointerDown={startDrag}+ onClickCapture={(event) => {+ if (draggedRef.current) {+ event.stopPropagation()+ draggedRef.current = false+ }+ }}+ // The drag offset changes on every pointer move, which a class can't express.+ // eslint-disable-next-line react/forbid-dom-props+ style={drag ? { translate: `${drag.dx}px ${drag.dy}px` } : undefined}+ >+ <Tooltip>+ <TooltipTrigger+ delay={0}+ render={+ <PopoverTrigger+ render={+ <Button+ variant="outline"+ size="default"+ aria-label="Ask PostHog AI"+ className="w-24 justify-center rounded-full"+ data-attr="today-ai-chat-button"+ />+ }+ />+ }+ >+ <IconSparkles />+ </TooltipTrigger>+ {!drag && <TooltipContent side="top">Ask PostHog AI</TooltipContent>}+ </Tooltip>+ {/* Hiding the button while its card is open would leave the card without an anchor. */}+ {!floatingOpen && (+ <Tooltip>+ <TooltipTrigger+ delay={0}+ render={+ <Button+ size="icon-xs"+ aria-label="Dismiss floating button"+ className="absolute top-1/2 right-1 -translate-y-1/2 rounded-full text-muted-foreground opacity-0 group-hover/launcher:opacity-100 group-has-[:focus-visible]/launcher:opacity-100 group-data-[dragging]/launcher:opacity-0 hover:text-foreground"+ data-launcher-close+ data-attr="today-ai-chat-button-hide"+ onClick={() => hideLauncher()}+ />+ }+ >+ <IconX />+ </TooltipTrigger>+ <TooltipContent side="top">Dismiss floating button</TooltipContent>+ </Tooltip>+ )}+ </span>+ </div>+ )+}diff --git a/frontend/src/layout/today/TodayContextPanelMenu.tsx b/frontend/src/layout/today/TodayContextPanelMenu.tsxnew file mode 100644index 000000000000..1e3028489f1e--- /dev/null+++ b/frontend/src/layout/today/TodayContextPanelMenu.tsx@@ -0,0 +1,115 @@+import { useActions, useValues } from 'kea'++import { IconEllipsis, IconSidePanel } from '@posthog/icons'+import {+ Button,+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuSeparator,+ DropdownMenuTrigger,+ Tooltip,+ TooltipContent,+ TooltipTrigger,+} from '@posthog/quill'++import { IconOpenFullScreen, IconUndockPanel } from 'lib/lemon-ui/icons'+import { PhaiViewSwitchMenuItem } from 'scenes/max/components/PhaiViewSwitchMenuItem'++import { SidePanelTab } from '~/types'++import { DebugLogsMenuItem } from 'products/posthog_ai/frontend/api/menus'++import { todayAiChatLogic } from './todayAiChatLogic'+import { todayContextPanelLogic } from './todayContextPanelLogic'+import { DROPDOWN_PARTS } from './todayMenuParts'+import { TodayPanelTaskMenuItems } from './TodayPanelTaskMenuItems'++export function TodayContextPanelMenu({ docked }: { docked: boolean }): JSX.Element | null {+ const { activeTab, fullScreenUrl: tabFullScreenUrl, canUndock } = useValues(todayContextPanelLogic)+ const { dock, undock, openFullScreen } = useActions(todayContextPanelLogic)+ const { fullScreenUrl: aiFullScreenUrl, onTaskRunner, activeCreation } = useValues(todayAiChatLogic)+ const { carryContextToFullScreen } = useActions(todayAiChatLogic)+ const onAi = activeTab === SidePanelTab.Max+ const fullScreenUrl = onAi ? aiFullScreenUrl : tabFullScreenUrl+ const chatTask = onAi && onTaskRunner ? activeCreation : null+ const canMove = !!fullScreenUrl || !docked || canUndock++ // A docked canvas tab has nowhere to go and no settings, so it gets no menu.+ if (!canMove && !onAi) {+ return null+ }++ const placement = (+ <>+ {fullScreenUrl && (+ <DROPDOWN_PARTS.Item+ to={fullScreenUrl}+ onClick={() => {+ if (onAi) {+ carryContextToFullScreen()+ }+ openFullScreen()+ }}+ dataAttr="today-context-panel-full-screen"+ >+ <IconOpenFullScreen />+ Open full screen+ </DROPDOWN_PARTS.Item>+ )}+ {docked ? (+ canUndock && (+ <DROPDOWN_PARTS.Item onClick={undock} dataAttr="today-context-panel-undock">+ <IconUndockPanel />+ Undock+ </DROPDOWN_PARTS.Item>+ )+ ) : (+ <DROPDOWN_PARTS.Item onClick={dock} dataAttr="today-context-panel-dock">+ <IconSidePanel />+ Dock to the right+ </DROPDOWN_PARTS.Item>+ )}+ </>+ )++ return (+ <DropdownMenu>+ <Tooltip>+ <TooltipTrigger+ delay={0}+ render={+ <DropdownMenuTrigger+ render={+ <Button+ size="icon"+ aria-label="More options"+ className="text-muted-foreground hover:text-foreground"+ data-attr="today-context-panel-more"+ />+ }+ />+ }+ >+ <IconEllipsis />+ </TooltipTrigger>+ <TooltipContent side="bottom">More options</TooltipContent>+ </Tooltip>+ <DropdownMenuContent align="end" className="min-w-56 max-w-80">+ {chatTask?.taskId && chatTask.runId ? (+ <TodayPanelTaskMenuItems taskId={chatTask.taskId} runId={chatTask.runId} placement={placement} />+ ) : (+ <>+ {placement}+ {onAi && (+ <>+ {canMove && <DropdownMenuSeparator />}+ {onTaskRunner && <DebugLogsMenuItem parts={DROPDOWN_PARTS} />}+ <PhaiViewSwitchMenuItem />+ </>+ )}+ </>+ )}+ </DropdownMenuContent>+ </DropdownMenu>+ )+}diff --git a/frontend/src/layout/today/TodayPanelMoveMenuItems.tsx b/frontend/src/layout/today/TodayPanelMoveMenuItems.tsxnew file mode 100644index 000000000000..efffa3590459--- /dev/null+++ b/frontend/src/layout/today/TodayPanelMoveMenuItems.tsx@@ -0,0 +1,39 @@+import { useActions } from 'kea'++import { IconSidePanel } from '@posthog/icons'++import { IconUndockPanel } from 'lib/lemon-ui/icons'++import { todayAiChatLogic } from './todayAiChatLogic'+import type { TodayMenuParts } from './todayMenuParts'+import type { TodayPanelChatTask } from './todayPanelChat'++interface TodayPanelMoveMenuItemsProps {+ parts: TodayMenuParts+ /** The task whose run the panel takes over. Without one, the panel opens on a new chat. */+ chat: TodayPanelChatTask | null+ dataAttrPrefix: string+}++export function TodayPanelMoveMenuItems({ parts, chat, dataAttrPrefix }: TodayPanelMoveMenuItemsProps): JSX.Element {+ const { moveChatToPanel } = useActions(todayAiChatLogic)++ return (+ <>+ <parts.Item+ onClick={() => moveChatToPanel('floating', chat)}+ dataAttr={`${dataAttrPrefix}-move-to-floating-panel`}+ >+ <IconUndockPanel />+ Open in floating panel+ </parts.Item>+ <parts.Item+ onClick={() => moveChatToPanel('docked', chat)}+ dataAttr={`${dataAttrPrefix}-move-to-side-panel`}+ >+ <IconSidePanel />+ Dock to the right+ </parts.Item>+ </>+ )+}diff --git a/frontend/src/layout/today/TodayPanelTaskMenuItems.tsx b/frontend/src/layout/today/TodayPanelTaskMenuItems.tsxnew file mode 100644index 000000000000..bdf31d146e97--- /dev/null+++ b/frontend/src/layout/today/TodayPanelTaskMenuItems.tsx@@ -0,0 +1,23 @@+import { useActions, useValues } from 'kea'+import type { ReactNode } from 'react'++import { TaskMenuItems } from 'products/posthog_ai/frontend/api/menus'++import { DROPDOWN_PARTS } from './todayMenuParts'+import { todayPanelTaskLogic } from './todayPanelTaskLogic'++interface TodayPanelTaskMenuItemsProps {+ taskId: string+ runId: string+ placement: ReactNode+}++export function TodayPanelTaskMenuItems({ taskId, runId, placement }: TodayPanelTaskMenuItemsProps): JSX.Element {+ const { task, run } = useValues(todayPanelTaskLogic({ taskId, runId }))+ const { archive } = useActions(todayPanelTaskLogic({ taskId, runId }))++ if (!task) {+ return <>{placement}</>+ }+ return <TaskMenuItems parts={DROPDOWN_PARTS} task={task} run={run} placement={placement} onArchive={archive} />+}diff --git a/frontend/src/layout/today/TodayShell.tsx b/frontend/src/layout/today/TodayShell.tsxindex d1eddf88ae1b..c737d48ca742 100644--- a/frontend/src/layout/today/TodayShell.tsx+++ b/frontend/src/layout/today/TodayShell.tsx@@ -15,6 +15,7 @@ import { lazyWithRetry } from 'lib/utils/retryImport'import { QuillSceneHeader } from '~/layout/scenes/components/QuillSceneHeader'+import { todayPanelChatSessionLogic } from './todayPanelChatSessionLogic'import { TodayPhoneHeader } from './TodayPhoneHeader'import { TodayRail } from './TodayRail'import { TODAY_PANES } from './todayRailItems'@@ -45,6 +46,7 @@ export function TodayShell({ className }: { className?: string }): JSX.Element {useValues(todayShellLogic)// Records the tools visited while other panes are open, so the Tools pane's Recent group is ready.useMountedLogic(todayRecentsLogic)+ useMountedLogic(todayPanelChatSessionLogic)const { setMobileSidebarOpen, setSidebarOpen, setSidebarWidth, toggleSidebar } = useActions(todayShellLogic)useShortcut({name: 'ToggleLeftNav',diff --git a/frontend/src/layout/today/TodaySidePanel.tsx b/frontend/src/layout/today/TodaySidePanel.tsxindex 1f0014da08c8..ef3bae6a0a0d 100644--- a/frontend/src/layout/today/TodaySidePanel.tsx+++ b/frontend/src/layout/today/TodaySidePanel.tsx@@ -7,12 +7,11 @@ import { cn } from 'lib/utils/css-classes'import { SIDE_PANEL_MIN_WIDTH_COMPACT, useSidePanelFrame } from '~/layout/navigation-3000/sidepanel/useSidePanelFrame'import { TodayContextPanelCard } from './TodayContextPanelCard'+import { TODAY_SIDE_PANEL_DEFAULT_WIDTH } from './todayContextPanelLogic'import { todayShellLogic } from './todayShellLogic'// The Today layout gives the panel its own grid column, so a wider panel takes the space from the scene.const TODAY_SIDE_PANEL_MAX_WIDTH = 720-// Matches the floating card, so docking keeps the panel's width.-const TODAY_SIDE_PANEL_DEFAULT_WIDTH = 340// The scene keeps at least this much width beside a wide panel, so a narrow window never collapses it.const TODAY_SCENE_MIN_WIDTH = 320diff --git a/frontend/src/layout/today/TodayTopBarPanelTab.tsx b/frontend/src/layout/today/TodayTopBarPanelTab.tsxnew file mode 100644index 000000000000..33d919223c0b--- /dev/null+++ b/frontend/src/layout/today/TodayTopBarPanelTab.tsx@@ -0,0 +1,84 @@+import { useActions, useValues } from 'kea'+import { ComponentType, useState } from 'react'++import { IconPulse, IconSparkles } from '@posthog/icons'+import { Button, Kbd, Tooltip, TooltipContent, TooltipTrigger } from '@posthog/quill'++import { sidePanelNotificationsLogic } from '~/layout/navigation-3000/sidepanel/panels/activity/sidePanelNotificationsLogic'+import { SIDE_PANEL_TABS } from '~/layout/navigation-3000/sidepanel/sidePanelTabs'+import { SidePanelTab } from '~/types'++import { todayContextPanelLogic } from './todayContextPanelLogic'++// The top bar's own icons where the side panel's would read wrong at this size.+const TODAY_TAB_ICONS: Partial<Record<SidePanelTab, ComponentType>> = {+ [SidePanelTab.Max]: IconSparkles,+ [SidePanelTab.Activity]: IconPulse,+}++export function TodayTopBarPanelTab({ tab }: { tab: SidePanelTab }): JSX.Element {+ const { activeTab, docked, floatingOpen, launcherHintVisible } = useValues(todayContextPanelLogic)+ const { togglePanelTab, hideLauncherHint } = useActions(todayContextPanelLogic)+ const { unreadCount } = useValues(sidePanelNotificationsLogic)+ // Controlled, so PostHog AI's tooltip can also point here after the user dismisses the floating button.+ const [hovered, setHovered] = useState(false)+ const launcherHint = tab === SidePanelTab.Max && launcherHintVisible++ const { label: tabLabel } = SIDE_PANEL_TABS[tab]+ const Icon = TODAY_TAB_ICONS[tab] ?? SIDE_PANEL_TABS[tab].Icon+ const pressed = (docked || floatingOpen) && activeTab === tab+ const label = pressed ? `Close ${tabLabel}` : tabLabel+ const unread = tab === SidePanelTab.Activity ? unreadCount : 0++ return (+ // The unread dot sits beside the button, so it never shifts the button's centered icon.+ <span className="relative flex">+ <Tooltip+ disableHoverablePopup+ open={launcherHint || hovered}+ onOpenChange={(open) => {+ setHovered(open)+ if (!open && launcherHint) {+ hideLauncherHint()+ }+ }}+ >+ <TooltipTrigger+ delay={0}+ render={+ <Button+ size="icon"+ aria-label={unread > 0 ? `${label}, ${unread} unread` : label}+ aria-pressed={pressed}+ className="text-muted-foreground hover:text-foreground aria-pressed:bg-[var(--fill-selected)] aria-pressed:text-foreground"+ onClick={() => togglePanelTab(tab)}+ // pinned: the PostHog AI button keeps the side panel button's data-attr+ data-attr={+ tab === SidePanelTab.Max ? 'today-top-bar-side-panel' : `today-top-bar-panel-tab-${tab}`+ }+ />+ }+ >+ <Icon />+ </TooltipTrigger>+ <TooltipContent side="bottom" align="end">+ {launcherHint ? (+ "It's here when you need it"+ ) : (+ <>+ {label}+ {unread > 0 && <span className="opacity-70">{unread} unread</span>}+ {tab === SidePanelTab.Max && <Kbd>]</Kbd>}+ </>+ )}+ </TooltipContent>+ </Tooltip>+ {unread > 0 && (+ <span+ aria-hidden+ className="pointer-events-none absolute top-0.5 right-0.5 size-2 rounded-full bg-primary"+ />+ )}+ </span>+ )+}diff --git a/frontend/src/layout/today/TodayTopBarPanelTabs.tsx b/frontend/src/layout/today/TodayTopBarPanelTabs.tsxindex 66097018ff1e..da91b3693705 100644--- a/frontend/src/layout/today/TodayTopBarPanelTabs.tsx+++ b/frontend/src/layout/today/TodayTopBarPanelTabs.tsx@@ -1,74 +1,16 @@-import { useActions, useValues } from 'kea'-import { ComponentType } from 'react'--import { IconPulse, IconSparkles } from '@posthog/icons'-import { Button, Kbd, Tooltip, TooltipContent, TooltipTrigger } from '@posthog/quill'--import { sidePanelNotificationsLogic } from '~/layout/navigation-3000/sidepanel/panels/activity/sidePanelNotificationsLogic'-import { SIDE_PANEL_TABS } from '~/layout/navigation-3000/sidepanel/sidePanelTabs'-import { SidePanelTab } from '~/types'+import { useValues } from 'kea'import { todayContextPanelLogic } from './todayContextPanelLogic'--// The top bar's own icons where the side panel's would read wrong at this size.-const TODAY_TAB_ICONS: Partial<Record<SidePanelTab, ComponentType>> = {- [SidePanelTab.Max]: IconSparkles,- [SidePanelTab.Activity]: IconPulse,-}+import { TodayTopBarPanelTab } from './TodayTopBarPanelTab'export function TodayTopBarPanelTabs(): JSX.Element {- const { panelTabs, activeTab, docked, floatingOpen } = useValues(todayContextPanelLogic)- const { togglePanelTab } = useActions(todayContextPanelLogic)- const { unreadCount } = useValues(sidePanelNotificationsLogic)- const panelOpen = docked || floatingOpen+ const { panelTabs } = useValues(todayContextPanelLogic)return (<div className="flex items-center gap-0.5">- {panelTabs.map((tab) => {- const { label: tabLabel } = SIDE_PANEL_TABS[tab]- const Icon = TODAY_TAB_ICONS[tab] ?? SIDE_PANEL_TABS[tab].Icon- const pressed = panelOpen && activeTab === tab- const label = pressed ? `Close ${tabLabel}` : tabLabel- const unread = tab === SidePanelTab.Activity ? unreadCount : 0- return (- // The unread dot sits beside the button, so it never shifts the button's centered icon.- <span key={tab} className="relative flex">- <Tooltip disableHoverablePopup>- <TooltipTrigger- delay={0}- render={- <Button- size="icon"- aria-label={unread > 0 ? `${label}, ${unread} unread` : label}- aria-pressed={pressed}- className="text-muted-foreground hover:text-foreground aria-pressed:bg-[var(--fill-selected)] aria-pressed:text-foreground"- onClick={() => togglePanelTab(tab)}- // pinned: the PostHog AI button keeps the side panel button's data-attr- data-attr={- tab === SidePanelTab.Max- ? 'today-top-bar-side-panel'- : `today-top-bar-panel-tab-${tab}`- }- />- }- >- <Icon />- </TooltipTrigger>- <TooltipContent side="bottom" align="end">- {label}- {unread > 0 && <span className="opacity-70">{unread} unread</span>}- {tab === SidePanelTab.Max && <Kbd>]</Kbd>}- </TooltipContent>- </Tooltip>- {unread > 0 && (- <span- aria-hidden- className="pointer-events-none absolute top-0.5 right-0.5 size-2 rounded-full bg-primary"- />- )}- </span>- )- })}+ {panelTabs.map((tab) => (+ <TodayTopBarPanelTab key={tab} tab={tab} />+ ))}</div>)}diff --git a/frontend/src/layout/today/todayAiChatLogic.ts b/frontend/src/layout/today/todayAiChatLogic.tsindex 4617e90af3b7..aa1a34ff258b 100644--- a/frontend/src/layout/today/todayAiChatLogic.ts+++ b/frontend/src/layout/today/todayAiChatLogic.ts@@ -10,14 +10,17 @@ import { SIDE_PANEL_PANEL_ID, maxLogic } from 'scenes/max/maxLogic'import { urls } from 'scenes/urls'import { sidePanelStateLogic } from '~/layout/navigation-3000/sidepanel/sidePanelStateLogic'+import { SidePanelTab } from '~/types'+import { type ActiveCreation, runnerPanelLogic } from 'products/posthog_ai/frontend/api/logics'import { attachedContextLogic } from 'products/posthog_ai/frontend/logics/attachedContextLogic'-import { ActiveCreation, runnerPanelLogic } from 'products/posthog_ai/frontend/logics/runnerPanelLogic'import type { AttachedContextItem } from 'products/posthog_ai/frontend/types/contextTypes'import { REPORT_AI_PANEL } from 'products/signals/frontend/inbox/inboxTaskKickoffLogic'import { SCOUT_AI_PANEL } from 'products/signals/frontend/inbox/logics/scoutAiLogic'import type { TaskActivityDTOApi } from '../../../../products/tasks/frontend/generated/api.schemas'+import { todayContextPanelLogic } from './todayContextPanelLogic'+import { TodayPanelChatTask, runnerCreationFor } from './todayPanelChat'import { todayShellLogic } from './todayShellLogic'import { todaySpacesLogic } from './todaySpacesLogic'import { TodayWorkGroup, TodayWorkItem, groupByDay, sessionReadRequest } from './todayWorkItems'@@ -36,6 +39,7 @@ export interface todayAiChatLogicValues {legacyChatTitle: string | null // maxLogicactiveCreation: ActiveCreation | null // runnerPanelLogicselectedTabOptions: string | null // sidePanelStateLogic+ lastSceneUrl: string | null // todayShellLogiconAiPage: boolean // todayShellLogicallRecentItems: TodayWorkItem[] // todaySpacesLogicpinnedItems: TodayWorkItem[] // todaySpacesLogic@@ -61,6 +65,9 @@ export interface todayAiChatLogicActions {items: AttachedContextItem[]providerId: string} // attachedContextLogic+ setPhaiViewMode: (mode: PhaiViewMode) => {+ mode: PhaiViewMode+ } // maxGlobalLogicopenConversation: (conversationId: string) => {conversationId: string} // maxLogic@@ -76,9 +83,22 @@ export interface todayAiChatLogicActions {setHistoryExpanded: (expanded: boolean) => {expanded: boolean} // runnerPanelLogic+ openSidePanel: (+ tab: SidePanelTab,+ options?: string | undefined+ ) => {+ options: string | undefined+ tab: SidePanelTab+ } // sidePanelStateLogicsetSidePanelOptions: (options: string | null) => {options: string | null} // sidePanelStateLogic+ setFloatingOpen: (open: boolean) => {+ open: boolean+ } // todayContextPanelLogic+ setFloatingTab: (tab: SidePanelTab) => {+ tab: SidePanelTab+ } // todayContextPanelLogicmarkSessionRead: (marker: import('../../../../products/tasks/frontend/generated/api.schemas').TaskActivityReadMarkerApi,activityIds: string[]@@ -89,6 +109,13 @@ export interface todayAiChatLogicActions {carryContextToFullScreen: () => {value: true}+ moveChatToPanel: (+ mode: 'docked' | 'floating',+ chat: TodayPanelChatTask | null+ ) => {+ chat: TodayPanelChatTask | null+ mode: 'docked' | 'floating'+ }openRecentItem: (item: TodayWorkItem) => {item: TodayWorkItem}@@ -171,13 +198,17 @@ export const todayAiChatLogic = kea<todayAiChatLogicType>([attachedContextLogic,['contextItems'],todayShellLogic,- ['onAiPage'],+ ['onAiPage', 'lastSceneUrl'],sidePanelStateLogic,['selectedTabOptions'],],actions: [+ maxGlobalLogic,+ ['setPhaiViewMode'],sidePanelStateLogic,- ['setSidePanelOptions'],+ ['setSidePanelOptions', 'openSidePanel'],+ todayContextPanelLogic,+ ['setFloatingOpen', 'setFloatingTab'],todaySpacesLogic,['markSessionRead'],maxLogic({ panelId: SIDE_PANEL_PANEL_ID }),@@ -192,6 +223,7 @@ export const todayAiChatLogic = kea<todayAiChatLogicType>([openRecentItem: (item: TodayWorkItem) => ({ item }),startNewChat: true,carryContextToFullScreen: true,+ moveChatToPanel: (mode: 'floating' | 'docked', chat: TodayPanelChatTask | null) => ({ mode, chat }),}),selectors({recentGroups: [@@ -263,7 +295,7 @@ export const todayAiChatLogic = kea<todayAiChatLogicType>([const newView = values.effectivePhaiView === 'new'if (item.kind === 'session') {if (newView && item.latestRunId) {- actions.setActiveCreation({ streamKey: item.latestRunId, taskId: item.id, runId: 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) {@@ -280,6 +312,28 @@ export const todayAiChatLogic = kea<todayAiChatLogicType>([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: () => {diff --git a/frontend/src/layout/today/todayContextPanelLogic.ts b/frontend/src/layout/today/todayContextPanelLogic.tsindex ebe3122543c0..c513ea1b0df3 100644--- a/frontend/src/layout/today/todayContextPanelLogic.ts+++ b/frontend/src/layout/today/todayContextPanelLogic.ts@@ -1,4 +1,5 @@-import { MakeLogicType, actions, connect, kea, listeners, path, reducers, selectors } from 'kea'+import { MakeLogicType, actions, connect, defaults, kea, listeners, path, reducers, selectors } from 'kea'+import { subscriptions } from 'kea-subscriptions'import posthog from 'posthog-js'import { notebookPanelLogic } from 'scenes/notebooks/NotebookPanel/notebookPanelLogic'@@ -11,6 +12,7 @@ import { SidePanelTab } from '~/types'import { sidepanelTicketsLogic } from 'products/conversations/frontend/components/SidePanel/sidepanelTicketsLogic'import { ConversationTicket, SidePanelViewState } from 'products/conversations/frontend/types'+import { projectSessionKey, readSessionValue, writeSessionValue } from './todaySessionStorage'import { todayShellLogic } from './todayShellLogic'export interface TodayContextPanelOffset {@@ -18,6 +20,26 @@ export interface TodayContextPanelOffset {y: number}+/**+ * Where the PostHog AI button sits along the bottom edge of the scene. The user drags it between these, like the+ * toolbar. The top edge is left out because the scene header and its actions sit there. The values double as the+ * floating card's alignment to the button.+ */+export type TodayLauncherAlign = 'start' | 'center' | 'end'++const LAUNCHER_HIDDEN_HINT_MS = 6000++/** Matches the floating card, so docking keeps the panel's width. The dock silhouette uses it too. */+export const TODAY_SIDE_PANEL_DEFAULT_WIDTH = 340++/** The floating card as it was before a reload. The docked panel restores itself from the URL's `#panel` hash. */+interface TodayFloatingSession {+ tab: SidePanelTab+ offset: TodayContextPanelOffset+}++const FLOATING_SESSION_KEY = 'today-context-panel-floating'+/** How close to the right edge of the window a dragged panel must be released to dock. */export const TODAY_CONTEXT_PANEL_DOCK_EDGE = 64@@ -47,8 +69,13 @@ export interface todayContextPanelLogicValues {floatingActiveTab: SidePanelTabfloatingOffset: TodayContextPanelOffsetfloatingOpen: boolean+ floatingSession: TodayFloatingSession | nullfloatingTab: SidePanelTabfullScreenUrl: string | null+ launcherAlign: TodayLauncherAlign+ launcherHidden: boolean+ launcherHiddenByUser: boolean+ launcherHintVisible: booleanpanelTabs: SidePanelTab[]}@@ -70,6 +97,12 @@ export interface todayContextPanelLogicActions {dock: () => {value: true}+ hideLauncher: () => {+ value: true+ }+ hideLauncherHint: () => {+ value: true+ }openFullScreen: () => {value: true}@@ -85,6 +118,12 @@ export interface todayContextPanelLogicActions {setFloatingTab: (tab: SidePanelTab) => {tab: SidePanelTab}+ setLauncherAlign: (align: TodayLauncherAlign) => {+ align: TodayLauncherAlign+ }+ showLauncherHint: () => {+ value: true+ }togglePanelTab: (tab: SidePanelTab) => {tab: SidePanelTab}@@ -97,6 +136,17 @@ export interface todayContextPanelLogicActions {export interface todayContextPanelLogicMeta {__keaTypeGenInternalSelectorTypes: {docked: (sidePanelOpen: boolean) => boolean+ floatingSession: (+ floatingOpen: boolean,+ floatingActiveTab: SidePanelTab,+ floatingOffset: TodayContextPanelOffset+ ) => TodayFloatingSession | null+ launcherHidden: (+ docked: boolean,+ launcherHiddenByUser: boolean,+ floatingOpen: boolean,+ panelTabs: SidePanelTab[]+ ) => booleanpanelTabs: (enabledTabs: SidePanelTab[]) => SidePanelTab[]floatingActiveTab: (floatingTab: SidePanelTab, enabledTabs: SidePanelTab[]) => SidePanelTabcanUndock: (activeTab: SidePanelTab, onAiPage: boolean) => boolean@@ -145,12 +195,21 @@ export const todayContextPanelLogic = kea<todayContextPanelLogicType>([setFloatingTab: (tab: SidePanelTab) => ({ tab }),setFloatingOffset: (offset: TodayContextPanelOffset) => ({ offset }),setDockHint: (dockHint: boolean) => ({ dockHint }),+ setLauncherAlign: (align: TodayLauncherAlign) => ({ align }),+ hideLauncher: true,+ showLauncherHint: true,+ hideLauncherHint: true,togglePanelTab: (tab: SidePanelTab) => ({ tab }),dock: true,undock: true,close: true,openFullScreen: true,}),+ // A reload opens the card where it was, as state rather than an action, so it doesn't count as the user opening it.+ defaults(() => {+ const saved = readSessionValue<TodayFloatingSession>(projectSessionKey(FLOATING_SESSION_KEY))+ return saved ? { floatingOpen: true, floatingTab: saved.tab, floatingOffset: saved.offset } : {}+ }),reducers({floatingOpen: [false,@@ -173,6 +232,30 @@ export const todayContextPanelLogic = kea<todayContextPanelLogicType>([setFloatingOffset: (_, { offset }) => offset,},],+ launcherAlign: [+ 'end' as TodayLauncherAlign,+ { persist: true },+ {+ setLauncherAlign: (_, { align }) => align,+ },+ ],+ launcherHiddenByUser: [+ false,+ { persist: true },+ {+ hideLauncher: () => true,+ // The card closes back into the floating button, so closing it brings the button back.+ setFloatingOpen: (state, { open }) => (open ? state : false),+ },+ ],+ launcherHintVisible: [+ false,+ {+ showLauncherHint: () => true,+ hideLauncherHint: () => false,+ togglePanelTab: () => false,+ },+ ],dockHint: [false,{@@ -184,6 +267,28 @@ export const todayContextPanelLogic = kea<todayContextPanelLogicType>([}),selectors({docked: [(s) => [s.sidePanelOpen], (sidePanelOpen: boolean): boolean => sidePanelOpen],+ floatingSession: [+ (s) => [s.floatingOpen, s.floatingActiveTab, s.floatingOffset],+ (+ floatingOpen: boolean,+ floatingActiveTab: SidePanelTab,+ floatingOffset: TodayContextPanelOffset+ ): TodayFloatingSession | null =>+ floatingOpen ? { tab: floatingActiveTab, offset: floatingOffset } : null,+ ],+ /**+ * The button sinks away while docked and where the scene has no PostHog AI. The open card hangs off it, so it+ * shows for as long as the card is open, even after the user dismissed it.+ */+ launcherHidden: [+ (s) => [s.docked, s.launcherHiddenByUser, s.floatingOpen, s.panelTabs],+ (+ docked: boolean,+ launcherHiddenByUser: boolean,+ floatingOpen: boolean,+ panelTabs: SidePanelTab[]+ ): boolean => docked || (launcherHiddenByUser && !floatingOpen) || !panelTabs.includes(SidePanelTab.Max),+ ],panelTabs: [(s) => [s.enabledTabs],// PostHog AI goes last, and only where the scene offers it. Canvas scenes bring their own chat.@@ -244,7 +349,22 @@ export const todayContextPanelLogic = kea<todayContextPanelLogicType>([},],}),+ subscriptions({+ floatingSession: (session: TodayFloatingSession | null) =>+ writeSessionValue(projectSessionKey(FLOATING_SESSION_KEY), session),+ }),listeners(({ actions, values }) => ({+ setLauncherAlign: ({ align }) => {+ posthog.capture('today ai button moved', { align })+ },+ hideLauncher: () => {+ posthog.capture('today ai button hidden')+ actions.showLauncherHint()+ },+ showLauncherHint: async (_, breakpoint) => {+ await breakpoint(LAUNCHER_HIDDEN_HINT_MS)+ actions.hideLauncherHint()+ },setFloatingOpen: ({ open }) => {// pinned: analytics event namesposthog.capture(open ? 'today context panel opened' : 'today context panel closed', {diff --git a/frontend/src/layout/today/todayMenuParts.tsx b/frontend/src/layout/today/todayMenuParts.tsxindex b8d5fb81a2e5..70aa65604842 100644--- a/frontend/src/layout/today/todayMenuParts.tsx+++ b/frontend/src/layout/today/todayMenuParts.tsx@@ -45,6 +45,14 @@ export interface TodayMenuSubProps {children: ReactNode}+/** Read-only details, such as a task's facts. A menu shows them in place, a phone sheet on a page of their own. */+export interface TodayMenuSectionProps {+ label: ReactNode+ title: string+ dataAttr: string+ children: ReactNode+}+/*** What a row's action list draws with. Each kind of row writes its actions once against these parts,* like PostHog Desktop, so its hover card and its menus can't drift apart.@@ -54,6 +62,7 @@ export interface TodayMenuParts {Separator: () => JSX.Element | nullShortcut: (props: { children: ReactNode }) => JSX.ElementSub: (props: TodayMenuSubProps) => JSX.Element+ Section: (props: TodayMenuSectionProps) => JSX.Element | null}const SUB_CONTENT_CLASS = 'w-64 [&>div]:max-h-[min(20rem,var(--available-height))]'@@ -79,6 +88,7 @@ export const DROPDOWN_PARTS: TodayMenuParts = {<DropdownMenuSubContent className={SUB_CONTENT_CLASS}>{children}</DropdownMenuSubContent></DropdownMenuSub>),+ Section: ({ children }) => <>{children}</>,}export const CONTEXT_PARTS: TodayMenuParts = {@@ -101,6 +111,7 @@ export const CONTEXT_PARTS: TodayMenuParts = {<ContextMenuSubContent className={SUB_CONTENT_CLASS}>{children}</ContextMenuSubContent></ContextMenuSub>),+ Section: ({ children }) => <>{children}</>,}function SheetItem({ children, dataAttr, onClick, to, disabled, variant }: TodayMenuItemProps): JSX.Element {@@ -133,6 +144,11 @@ export const SHEET_PARTS: TodayMenuParts = {{children}</TodaySheetSub>),+ Section: ({ label, title, dataAttr, children }) => (+ <TodaySheetSub label={label} title={title} dataAttr={dataAttr}>+ <div className="px-4 py-3">{children}</div>+ </TodaySheetSub>+ ),}/**@@ -181,5 +197,7 @@ export function cardMenuParts(onAction: () => void): TodayMenuParts {</DropdownMenuContent></DropdownMenu>),+ // A hover card stays short, so details stay in the menus.+ Section: () => null,}}diff --git a/frontend/src/layout/today/todayPanelChat.ts b/frontend/src/layout/today/todayPanelChat.tsnew file mode 100644index 000000000000..57e28b5b115a--- /dev/null+++ b/frontend/src/layout/today/todayPanelChat.ts@@ -0,0 +1,20 @@+import type { ActiveCreation } from 'products/posthog_ai/frontend/api/logics'++/** A task the PostHog AI panel can show. The panel streams one run, so it needs the run, not only the task. */+export interface TodayPanelChatTask {+ taskId: string+ runId: string+}++/** The run open on the task page, else the latest one. A task that has never run can't move into the panel. */+export function panelChatTaskFor(+ task: { id: string; latest_run?: { id: string } | null },+ run: { id: string } | null+): TodayPanelChatTask | null {+ const runId = run?.id ?? task.latest_run?.id+ return runId ? { taskId: task.id, runId } : null+}++export function runnerCreationFor({ taskId, runId }: TodayPanelChatTask): ActiveCreation {+ return { streamKey: runId, taskId, runId }+}diff --git a/frontend/src/layout/today/todayPanelChatSessionLogic.ts b/frontend/src/layout/today/todayPanelChatSessionLogic.tsnew file mode 100644index 000000000000..deefcfb72653--- /dev/null+++ b/frontend/src/layout/today/todayPanelChatSessionLogic.ts@@ -0,0 +1,56 @@+import { MakeLogicType, afterMount, connect, kea, listeners, path } from 'kea'++import { MAX_SIDE_PANEL_ID } from 'scenes/max/components/PhaiSidePanelChat'++import { type ActiveCreation, runnerPanelLogic } from 'products/posthog_ai/frontend/api/logics'++import { TodayPanelChatTask, runnerCreationFor } from './todayPanelChat'+import { projectSessionKey, readSessionValue, writeSessionValue } from './todaySessionStorage'++const CHAT_SESSION_KEY = 'today-context-panel-chat'++function chatOf(creation: ActiveCreation | null): TodayPanelChatTask | null {+ return creation?.taskId && creation.runId ? { taskId: creation.taskId, runId: creation.runId } : null+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface todayPanelChatSessionLogicValues {+ activeCreation: ActiveCreation | null // runnerPanelLogic+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface todayPanelChatSessionLogicActions {+ clearActiveCreation: () => {+ value: true+ } // runnerPanelLogic+ setActiveCreation: (creation: ActiveCreation) => {+ creation: ActiveCreation+ } // runnerPanelLogic+}++export type todayPanelChatSessionLogicType = MakeLogicType<+ todayPanelChatSessionLogicValues,+ todayPanelChatSessionLogicActions+>++/**+ * Keeps the PostHog AI panel's chat across a reload of this tab. Mounted for the whole session, so it also keeps the+ * panel's runner state alive while a chat moves off /ai and the page changes.+ */+export const todayPanelChatSessionLogic = kea<todayPanelChatSessionLogicType>([+ path(['layout', 'today', 'todayPanelChatSessionLogic']),+ connect(() => ({+ values: [runnerPanelLogic({ panelId: MAX_SIDE_PANEL_ID }), ['activeCreation']],+ actions: [runnerPanelLogic({ panelId: MAX_SIDE_PANEL_ID }), ['setActiveCreation', 'clearActiveCreation']],+ })),+ listeners(({ values }) => ({+ setActiveCreation: () => writeSessionValue(projectSessionKey(CHAT_SESSION_KEY), chatOf(values.activeCreation)),+ clearActiveCreation: () => writeSessionValue(projectSessionKey(CHAT_SESSION_KEY), null),+ })),+ afterMount(({ actions }) => {+ const saved = readSessionValue<TodayPanelChatTask>(projectSessionKey(CHAT_SESSION_KEY))+ if (saved) {+ actions.setActiveCreation(runnerCreationFor(saved))+ }+ }),+])diff --git a/frontend/src/layout/today/todayPanelTaskLogic.ts b/frontend/src/layout/today/todayPanelTaskLogic.tsnew file mode 100644index 000000000000..2f433311308d--- /dev/null+++ b/frontend/src/layout/today/todayPanelTaskLogic.ts@@ -0,0 +1,104 @@+import { MakeLogicType, actions, afterMount, connect, kea, key, listeners, path, props } from 'kea'+import { loaders } from 'kea-loaders'++import { projectLogic } from 'scenes/projectLogic'++import { taskLogic } from 'products/posthog_ai/frontend/api/logics'+import { tasksRunsRetrieve } from 'products/tasks/frontend/generated/api'+import type { TaskRunDetailDTOApi } from 'products/tasks/frontend/generated/api.schemas'++import type { Task } from '../../../../products/posthog_ai/frontend/types/taskTypes'+import { todayAiChatLogic } from './todayAiChatLogic'++export interface TodayPanelTaskLogicProps {+ taskId: string+ /** The run the panel shows, which can be older than the task's latest. */+ runId: string+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface todayPanelTaskLogicValues {+ currentProjectId: number | null // projectLogic+ task: Task | null // taskLogic+ taskLoading: boolean // taskLogic+ run: TaskRunDetailDTOApi | null+ runLoading: boolean+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface todayPanelTaskLogicActions {+ loadTask: () => any // taskLogic+ startNewChat: () => {+ value: true+ } // todayAiChatLogic+ archive: () => {+ value: true+ }+ loadRun: () => any+ loadRunFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ loadRunSuccess: (+ run: TaskRunDetailDTOApi,+ payload?: any+ ) => {+ run: TaskRunDetailDTOApi+ payload?: any+ }+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface todayPanelTaskLogicMeta {+ key: string+}++export type todayPanelTaskLogicType = MakeLogicType<+ todayPanelTaskLogicValues,+ todayPanelTaskLogicActions,+ TodayPanelTaskLogicProps,+ todayPanelTaskLogicMeta+>++export const todayPanelTaskLogic = kea<todayPanelTaskLogicType>([+ props({} as TodayPanelTaskLogicProps),+ key((props) => `${props.taskId}:${props.runId}`),+ path((key) => ['layout', 'today', 'todayPanelTaskLogic', key]),+ connect((props: TodayPanelTaskLogicProps) => ({+ values: [taskLogic({ taskId: props.taskId }), ['task', 'taskLoading'], projectLogic, ['currentProjectId']],+ actions: [taskLogic({ taskId: props.taskId }), ['loadTask'], todayAiChatLogic, ['startNewChat']],+ })),+ actions({+ archive: true,+ }),+ loaders(({ props, values }) => ({+ run: [+ null as TaskRunDetailDTOApi | null,+ {+ loadRun: async () =>+ await tasksRunsRetrieve(String(values.currentProjectId), props.taskId, props.runId),+ },+ ],+ })),+ listeners(({ actions, props }) => ({+ archive: async () => {+ try {+ await taskLogic({ taskId: props.taskId }).asyncActions.deleteTask({ leavePage: false })+ } catch {+ // The loader reports the failure. The panel stays on the task, which is still there.+ return+ }+ // An archived task has nothing left to show, so the panel moves on to a new chat.+ actions.startNewChat()+ },+ })),+ afterMount(({ actions, values }) => {+ if (!values.task && !values.taskLoading) {+ actions.loadTask()+ }+ actions.loadRun()+ }),+])diff --git a/frontend/src/layout/today/todaySessionStorage.ts b/frontend/src/layout/today/todaySessionStorage.tsnew file mode 100644index 000000000000..c37bb9f7fb99--- /dev/null+++ b/frontend/src/layout/today/todaySessionStorage.ts@@ -0,0 +1,31 @@+import { getCurrentTeamIdOrNone } from 'lib/utils/getAppContext'++/** Scopes a key to the current project. Switching projects reloads the page, so a key read once stays right. */+export function projectSessionKey(key: string): string {+ return `${key}:${getCurrentTeamIdOrNone() ?? 'none'}`+}++/**+ * Values that survive a reload of this browser tab and nothing longer, so a later visit starts fresh.+ * Storage can be blocked or full. Reads then return null and writes do nothing, which leaves the default state.+ */+export function readSessionValue<T>(key: string): T | null {+ try {+ const raw = sessionStorage.getItem(key)+ return raw ? (JSON.parse(raw) as T) : null+ } catch {+ return null+ }+}++export function writeSessionValue<T>(key: string, value: T | null): void {+ try {+ if (value === null) {+ sessionStorage.removeItem(key)+ } else {+ sessionStorage.setItem(key, JSON.stringify(value))+ }+ } catch {+ return+ }+}diff --git a/frontend/src/layout/today/todayShellLogic.ts b/frontend/src/layout/today/todayShellLogic.tsindex cd8d9bc97c15..4e49a3344b6f 100644--- a/frontend/src/layout/today/todayShellLogic.ts+++ b/frontend/src/layout/today/todayShellLogic.ts@@ -110,6 +110,7 @@ export interface todayShellLogicValues {featureFlags: FeatureFlagsSet // featureFlagLogicmobileLayout: boolean // navigationLogicactivePane: TodayRailPane+ lastSceneUrl: string | nullleftNavWidth: numbermobileSidebarOpen: booleanonAiPage: boolean@@ -161,6 +162,13 @@ export interface todayShellLogicActions {pickPane: (pane: TodayRailPane) => {pane: TodayRailPane}+ rememberSceneUrl: (location: { hash: string; pathname: string; search: string }) => {+ location: {+ hash: string+ pathname: string+ search: string+ }+ }setMobileSidebarOpen: (open: boolean) => {open: boolean}@@ -226,6 +234,18 @@ export type todayShellLogicType = MakeLogicType<todayShellLogicMeta>+function isAiPath(pathname: string): boolean {+ const path = removeProjectIdIfPresent(pathname)+ return path === urls.ai() || path.startsWith(`${urls.ai()}/`)+}++function sceneUrlOutsideAi(+ current: string | null,+ { pathname, search, hash }: { pathname: string; search: string; hash: string }+): string | null {+ return isAiPath(pathname) ? current : `${pathname}${search}${hash}`+}+export const todayShellLogic = kea<todayShellLogicType>([path(['layout', 'today', 'todayShellLogic']),connect(() => ({@@ -233,6 +253,7 @@ export const todayShellLogic = kea<todayShellLogicType>([actions: [router, ['locationChanged']],})),actions({+ rememberSceneUrl: (location: { pathname: string; search: string; hash: string }) => ({ location }),pickPane: (pane: TodayRailPane) => ({ pane }),goBackOnPhone: true,setPhonePages: (pages: TodayPhonePage[]) => ({ pages }),@@ -285,6 +306,14 @@ export const todayShellLogic = kea<todayShellLogicType>([nextPhonePages(state, method, { pathname, url: `${pathname}${search}${hash}` }),},],+ // Where the user was before /ai, so a chat moved from /ai into the panel opens over that scene again.+ lastSceneUrl: [+ null as string | null,+ {+ locationChanged: (state, location) => sceneUrlOutsideAi(state, location),+ rememberSceneUrl: (state, { location }) => sceneUrlOutsideAi(state, location),+ },+ ],// The resizer persists the width itself. This copy lets the app layout size the main column from it.sidebarWidth: [TODAY_SIDEBAR_DEFAULT_WIDTH, { setSidebarWidth: (_, { width }) => clampSidebarWidth(width) }],}),@@ -327,10 +356,7 @@ export const todayShellLogic = kea<todayShellLogicType>([],onAiPage: [() => [router.selectors.location],- (location: { pathname: string }): boolean => {- const path = removeProjectIdIfPresent(location.pathname)- return path === urls.ai() || path.startsWith(`${urls.ai()}/`)- },+ (location: { pathname: string }): boolean => isAiPath(location.pathname),],phoneHeaderHidden: [(s) => [s.onAiPage, router.selectors.searchParams, s.todayRailEnabled, s.phoneLayout],@@ -448,6 +474,7 @@ export const todayShellLogic = kea<todayShellLogicType>([afterMount(({ actions, cache }) => {const { pathname, search, hash } = router.values.locationcache.lastPathname = pathname+ actions.rememberSceneUrl({ pathname, search, hash })actions.setPhonePages([{ pathname, url: `${pathname}${search}${hash}` }])}),])diff --git a/frontend/src/lib/lemon-ui/icons/icons.tsx b/frontend/src/lib/lemon-ui/icons/icons.tsxindex bff7fdb9d205..463305f13f78 100644--- a/frontend/src/lib/lemon-ui/icons/icons.tsx+++ b/frontend/src/lib/lemon-ui/icons/icons.tsx@@ -1716,3 +1716,21 @@ export function IconChristmasOrnament(props: LemonIconProps): JSX.Element {</LemonIconBase>)}++export function IconUndockPanel(props: LemonIconProps): JSX.Element {+ return (+ <LemonIconBase stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" {...props}>+ <path d="M6.75 13.75V19.25C6.75 20.3546 7.64543 21.25 8.75 21.25H19.25C20.3546 21.25 21.25 20.3546 21.25 19.25V8.75C21.25 7.64543 20.3546 6.75 19.25 6.75H13.75" />+ <path d="M3.75 10.25V4.5C3.75 4.08579 4.08579 3.75 4.5 3.75H10.25" />+ <path d="M4.75 4.75L10.25 10.25" />+ </LemonIconBase>+ )+}++export function IconOpenFullScreen(props: LemonIconProps): JSX.Element {+ return (+ <LemonIconBase stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" {...props}>+ <path d="M3.75 10.25V5.75C3.75 4.64543 4.64543 3.75 5.75 3.75H19.25C20.3546 3.75 21.25 4.64543 21.25 5.75V13.25C21.25 14.3546 20.3546 15.25 19.25 15.25H14.75M17.25 7.75V10.75M17.25 7.75H14.25M17.25 7.75L14 11M9.25 21.25H4.75C3.64543 21.25 2.75 20.3546 2.75 19.25V15.75C2.75 14.6454 3.64543 13.75 4.75 13.75H9.25C10.3546 13.75 11.25 14.6454 11.25 15.75V19.25C11.25 20.3546 10.3546 21.25 9.25 21.25Z" />+ </LemonIconBase>+ )+}diff --git a/frontend/src/scenes/max/Max.tsx b/frontend/src/scenes/max/Max.tsxindex 684b634dfc49..47a8979ae8cd 100644--- a/frontend/src/scenes/max/Max.tsx+++ b/frontend/src/scenes/max/Max.tsx@@ -12,6 +12,7 @@ import {IconSidePanel,} from '@posthog/icons'import { LemonBanner, Link, Spinner, Tooltip } from '@posthog/lemon-ui'+import { Button, Empty, EmptyContent, EmptyDescription, EmptyHeader, EmptyMedia, EmptyTitle } from '@posthog/quill'import { LemonButton } from 'lib/lemon-ui/LemonButton'import { ButtonPrimitive } from 'lib/ui/Button/ButtonPrimitives'@@ -29,6 +30,7 @@ import { sidePanelLogic } from '~/layout/navigation-3000/sidepanel/sidePanelLogiimport { sidePanelStateLogic } from '~/layout/navigation-3000/sidepanel/sidePanelStateLogic'import { SceneContent } from '~/layout/scenes/components/SceneContent'import { SceneTitleSection } from '~/layout/scenes/components/SceneTitleSection'+import { todayShellLogic } from '~/layout/today/todayShellLogic'import { SidePanelTab } from '~/types'import { runnerPanelLogic } from 'products/posthog_ai/frontend/api/logics'@@ -109,9 +111,31 @@ export function Max({ tabId }: MaxProps): JSX.Element {const chatId = selectedChatId(searchParams)const { sidePanelOpen, selectedTab } = useValues(sidePanelLogic)const { closeSidePanel } = useActions(sidePanelLogic)+ const { todayRailEnabled } = useValues(todayShellLogic)const { conversationId: tabConversationId } = useValues(maxLogic({ panelId: tabId }))const { conversationId: sidepanelConversationId } = useValues(maxLogic({ panelId: SIDE_PANEL_PANEL_ID }))if (!taskId && sidePanelOpen && selectedTab === SidePanelTab.Max && sidepanelConversationId === tabConversationId) {+ if (todayRailEnabled) {+ return (+ <Empty className="h-full">+ <EmptyHeader>+ <EmptyMedia variant="icon">+ <IconSidePanel />+ </EmptyMedia>+ <EmptyTitle>This chat is open in the side panel</EmptyTitle>+ <EmptyDescription>+ It stays open while you move around the app. You can also move it back here.+ </EmptyDescription>+ </EmptyHeader>+ <EmptyContent>+ <Button variant="outline" onClick={() => closeSidePanel()} data-attr="ai-move-chat-here">+ <IconArrowLeft />+ Move it here+ </Button>+ </EmptyContent>+ </Empty>+ )+ }return (<SceneContent className="px-4 py-4 min-h-[calc(100vh-var(--scene-layout-header-height)-120px)]"><SceneTitleSection name={null} resourceType={{ type: 'chat' }} />diff --git a/frontend/src/scenes/max/components/AiFirstMaxInstance.tsx b/frontend/src/scenes/max/components/AiFirstMaxInstance.tsxindex f2280644b85a..6dd0c7caf5e3 100644--- a/frontend/src/scenes/max/components/AiFirstMaxInstance.tsx+++ b/frontend/src/scenes/max/components/AiFirstMaxInstance.tsx@@ -1,8 +1,9 @@import { BindLogic, useActions, useValues } from 'kea'import { router } from 'kea-router'-import { IconOpenSidebar, IconShare } from '@posthog/icons'+import { IconOpenSidebar, IconShare, IconSidePanel } from '@posthog/icons'import { LemonBanner } from '@posthog/lemon-ui'+import { DropdownMenuItem, DropdownMenuSeparator } from '@posthog/quill'import { LemonButton } from 'lib/lemon-ui/LemonButton'import { copyToClipboard } from 'lib/utils/copyToClipboard'@@ -10,7 +11,11 @@ import { cn } from 'lib/utils/css-classes'import { urls } from 'scenes/urls'import { SceneName } from '~/layout/scenes/components/SceneTitleSection'+import { DROPDOWN_PARTS } from '~/layout/today/todayMenuParts'+import { TodayPanelMoveMenuItems } from '~/layout/today/TodayPanelMoveMenuItems'+import { todayShellLogic } from '~/layout/today/todayShellLogic'+import { DebugLogsMenuItem } from 'products/posthog_ai/frontend/api/menus'import { DebugLogsMenu, useThreadSkin } from 'products/posthog_ai/frontend/api/primitives'import { EmbeddedRunner } from 'products/posthog_ai/frontend/api/runner'@@ -22,6 +27,8 @@ import { MaxThreadLogicProps, maxThreadLogic } from '../maxThreadLogic'import { phaiAiComposerSeedLogic } from '../phaiAiComposerSeedLogic'import { Thread } from '../Thread'import { MaxNotConfigured } from './MaxNotConfigured'+import { PhaiQuillOverflowMenu } from './PhaiQuillOverflowMenu'+import { PhaiViewSwitchMenuItem } from './PhaiViewSwitchMenuItem'import { PhaiViewToggle } from './PhaiViewToggle'import { SidebarQuestionInputWithSuggestions } from './SidebarQuestionInputWithSuggestions'import { ThreadAutoScroller } from './ThreadAutoScroller'@@ -49,6 +56,13 @@ export function ChatHeader({const { openSidePanelMax } = useActions(maxGlobalLogic)const { chatTitle } = useValues(maxLogic)const isTitleLoading = chatTitle === 'New chat'+ const skin = useThreadSkin()+ const copyLink = (): void => {+ copyToClipboard(+ urls.absolute(urls.currentProject(urls.ai(conversationId ?? undefined))),+ 'conversation sharing link'+ )+ }return (<div@@ -68,35 +82,50 @@ export function ChatHeader({)}</div><div className="flex items-center gap-2">- {isSandboxRuntime && <DebugLogsMenu variant="lemon" />}- {!hideViewToggle && <PhaiViewToggle variant="lemon" onChange={onViewChange} />}- {conversationId ? (- <LemonButton- size="small"- type="secondary"- sideIcon={<IconShare />}- onClick={() => {- copyToClipboard(- urls.absolute(urls.currentProject(urls.ai(conversationId ?? undefined))),- 'conversation sharing link'- )- }}- >- Copy link- </LemonButton>- ) : undefined}- {tabId ? (- <LemonButton- size="small"- type="secondary"- sideIcon={<IconOpenSidebar />}- onClick={() => {- openSidePanelMax(conversationId ?? undefined)- }}- >- Open in context panel- </LemonButton>- ) : undefined}+ {skin === 'quill' ? (+ <PhaiQuillOverflowMenu>+ {conversationId && (+ <DropdownMenuItem onClick={copyLink} data-attr="ai-copy-conversation-link">+ <IconShare />+ Copy link+ </DropdownMenuItem>+ )}+ {tabId && (+ <DropdownMenuItem+ onClick={() => openSidePanelMax(conversationId ?? undefined)}+ data-attr="ai-open-in-side-panel"+ >+ <IconSidePanel />+ Dock to the right+ </DropdownMenuItem>+ )}+ {(conversationId || tabId) && <DropdownMenuSeparator />}+ {isSandboxRuntime && <DebugLogsMenuItem parts={DROPDOWN_PARTS} />}+ {!hideViewToggle && <PhaiViewSwitchMenuItem onChange={onViewChange} />}+ </PhaiQuillOverflowMenu>+ ) : (+ <>+ {isSandboxRuntime && <DebugLogsMenu variant="lemon" />}+ {!hideViewToggle && <PhaiViewToggle variant="lemon" onChange={onViewChange} />}+ {conversationId ? (+ <LemonButton size="small" type="secondary" sideIcon={<IconShare />} onClick={copyLink}>+ Copy link+ </LemonButton>+ ) : undefined}+ {tabId ? (+ <LemonButton+ size="small"+ type="secondary"+ sideIcon={<IconOpenSidebar />}+ onClick={() => {+ openSidePanelMax(conversationId ?? undefined)+ }}+ >+ Open in context panel+ </LemonButton>+ ) : undefined}+ </>+ )}</div></div>)@@ -114,15 +143,36 @@ export function AiFirstMaxInstance({ tabId, taskId, chatId }: AiFirstMaxInstanceconst { startNewConversation } = useActions(maxLogic({ panelId: tabId }))const { isMaxAvailable, effectivePhaiView } = useValues(maxGlobalLogic)const skin = useThreadSkin()+ const { todayRailEnabled, phoneLayout } = useValues(todayShellLogic)if (aiSceneView({ taskId, chatId, effectivePhaiView }) === 'runner') {return (<div className="flex flex-col grow overflow-hidden h-full">{!taskId && (<div className="flex w-full items-center justify-end gap-2 py-2 px-2 border-b border-primary">- {/* The new view is the runner, which is always the sandbox runtime — no runtime check needed. */}- <DebugLogsMenu variant="lemon" />- <PhaiViewToggle variant="lemon" />+ {skin === 'quill' ? (+ <PhaiQuillOverflowMenu>+ {/* Only desktop Today has the floating and docked panel to move the chat into. */}+ {todayRailEnabled && !phoneLayout && (+ <>+ <TodayPanelMoveMenuItems+ parts={DROPDOWN_PARTS}+ chat={null}+ dataAttrPrefix="ai"+ />+ <DropdownMenuSeparator />+ </>+ )}+ <DebugLogsMenuItem parts={DROPDOWN_PARTS} />+ <PhaiViewSwitchMenuItem />+ </PhaiQuillOverflowMenu>+ ) : (+ <>+ {/* The new view is the runner, which is always the sandbox runtime — no runtime check needed. */}+ <DebugLogsMenu variant="lemon" />+ <PhaiViewToggle variant="lemon" />+ </>+ )}</div>)}<div className="flex flex-col flex-1 min-h-0">diff --git a/frontend/src/scenes/max/components/PhaiQuillOverflowMenu.tsx b/frontend/src/scenes/max/components/PhaiQuillOverflowMenu.tsxnew file mode 100644index 000000000000..7a85357f34a2--- /dev/null+++ b/frontend/src/scenes/max/components/PhaiQuillOverflowMenu.tsx@@ -0,0 +1,33 @@+import { IconEllipsis } from '@posthog/icons'+import {+ Button,+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuTrigger,+ Tooltip,+ TooltipContent,+ TooltipTrigger,+} from '@posthog/quill'++export function PhaiQuillOverflowMenu({ children }: { children: React.ReactNode }): JSX.Element {+ return (+ <DropdownMenu>+ <Tooltip>+ <TooltipTrigger+ delay={0}+ render={+ <DropdownMenuTrigger+ render={<Button size="icon" aria-label="More options" data-attr="run-staff-menu" />}+ />+ }+ >+ <IconEllipsis />+ </TooltipTrigger>+ <TooltipContent side="bottom">More options</TooltipContent>+ </Tooltip>+ <DropdownMenuContent align="end" className="w-56">+ {children}+ </DropdownMenuContent>+ </DropdownMenu>+ )+}diff --git a/frontend/src/scenes/max/components/PhaiViewSwitchMenuItem.tsx b/frontend/src/scenes/max/components/PhaiViewSwitchMenuItem.tsxnew file mode 100644index 000000000000..d6b752f44bd4--- /dev/null+++ b/frontend/src/scenes/max/components/PhaiViewSwitchMenuItem.tsx@@ -0,0 +1,28 @@+import { useActions, useValues } from 'kea'++import { IconRevert, IconSparkles } from '@posthog/icons'+import { DropdownMenuItem } from '@posthog/quill'++import { PhaiViewMode, maxGlobalLogic } from '../maxGlobalLogic'++export function PhaiViewSwitchMenuItem({ onChange }: { onChange?: (mode: PhaiViewMode) => void }): JSX.Element | null {+ const { isPhaiSandboxFlagOn, effectivePhaiView } = useValues(maxGlobalLogic)+ const { setPhaiViewMode } = useActions(maxGlobalLogic)++ if (!isPhaiSandboxFlagOn) {+ return null+ }+ const mode: PhaiViewMode = effectivePhaiView === 'new' ? 'legacy' : 'new'+ return (+ <DropdownMenuItem+ onClick={() => {+ setPhaiViewMode(mode)+ onChange?.(mode)+ }}+ data-attr={`phai-switch-to-${mode}`}+ >+ {mode === 'legacy' ? <IconRevert /> : <IconSparkles />}+ {mode === 'legacy' ? 'Switch to legacy view' : 'Switch to new view'}+ </DropdownMenuItem>+ )+}diff --git a/products/posthog_ai/frontend/api/logics.ts b/products/posthog_ai/frontend/api/logics.tsindex 988bd4eb64d0..b58cc2a37f03 100644--- a/products/posthog_ai/frontend/api/logics.ts+++ b/products/posthog_ai/frontend/api/logics.ts@@ -97,3 +97,9 @@ export { composerSeedLogic } from '../logics/composerSeedLogic'export { composerAttachmentsLogic } from '../logics/composerAttachmentsLogic'export { ATTACHMENT_MAX_SIZE_BYTES } from '../utils/attachments'export type { ComposerSeed, ComposerSeedLogicProps } from '../logics/composerSeedLogic'++// The staff debug-logs preference, for hosts that render their own overflow menu around it.+export { debugLogsLogic } from '../logics/debugLogsLogic'++// One task's record, with its archive (delete) loader, for hosts that act on a task outside the runner scene.+export { taskLogic } from '../logics/taskLogic'diff --git a/products/posthog_ai/frontend/api/menus.ts b/products/posthog_ai/frontend/api/menus.tsnew file mode 100644index 000000000000..023179822bd9--- /dev/null+++ b/products/posthog_ai/frontend/api/menus.ts@@ -0,0 +1,11 @@+// Menu items for hosts that render a task's actions in their own menu, such as the PostHog AI panel.+//+// Part of the `products/posthog_ai/frontend/api/<module>` public surface. Kept apart from ./primitives, which pulls the+// thread and its tool widgets, because the panel's menu loads with the app shell.++// A task's overflow menu items: placement, actions and details. Shared by the task page and the PostHog AI panel.+export { TaskMenuItems } from '../scenes/TaskTracker/components/TaskMenuItems'+export type { TaskMenuItemsProps } from '../scenes/TaskTracker/components/TaskMenuItems'++// The staff debug logs switch, drawn with a host's menu parts.+export { DebugLogsMenuItem } from '../components/DebugLogsMenuItem'diff --git a/products/posthog_ai/frontend/components/DebugLogsMenuItem.tsx b/products/posthog_ai/frontend/components/DebugLogsMenuItem.tsxnew file mode 100644index 000000000000..9eca6c1d96de--- /dev/null+++ b/products/posthog_ai/frontend/components/DebugLogsMenuItem.tsx@@ -0,0 +1,22 @@+import { useActions, useValues } from 'kea'++import { IconBug } from '@posthog/icons'++import type { TodayMenuParts } from '~/layout/today/todayMenuParts'++import { debugLogsLogic } from '../logics/debugLogsLogic'++export function DebugLogsMenuItem({ parts }: { parts: TodayMenuParts }): JSX.Element | null {+ const { canControlDebugLogs, debugLogsEnabled } = useValues(debugLogsLogic)+ const { setDebugLogsEnabled } = useActions(debugLogsLogic)++ if (!canControlDebugLogs) {+ return null+ }+ return (+ <parts.Item onClick={() => setDebugLogsEnabled(!debugLogsEnabled)} dataAttr="run-toggle-debug-logs">+ <IconBug />+ {debugLogsEnabled ? 'Hide debug logs' : 'Show debug logs'}+ </parts.Item>+ )+}diff --git a/products/posthog_ai/frontend/logics/taskLogic.ts b/products/posthog_ai/frontend/logics/taskLogic.tsindex 877fb0fe17a8..7710cb4f7256 100644--- a/products/posthog_ai/frontend/logics/taskLogic.ts+++ b/products/posthog_ai/frontend/logics/taskLogic.ts@@ -32,7 +32,9 @@ export interface taskLogicValues {// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface taskLogicActions {- deleteTask: () => any+ deleteTask: (params?: { leavePage?: boolean }) => {+ leavePage?: boolean+ }deleteTaskFailure: (error: string,errorObject?: any@@ -42,10 +44,14 @@ export interface taskLogicActions {}deleteTaskSuccess: (task: null,- payload?: any+ payload?: {+ leavePage?: boolean+ }) => {task: null- payload?: any+ payload?: {+ leavePage?: boolean+ }}loadTask: () => anyloadTaskFailure: (@@ -135,7 +141,8 @@ export const taskLogic = kea<taskLogicType>([...(values.task?.description ? { pending_user_message: values.task.description } : {}),})},- deleteTask: async () => {+ // `leavePage: false` is for a host that shows the task outside its page, such as the PostHog AI panel.+ deleteTask: async (params?: { leavePage?: boolean }) => {await api.tasks.delete(props.taskId)// Reload each mounted list with its own active filter — a bare `loadTasks()`// defaults to `{}`, which drops "For you"'s scout exclusion (and any other@@ -144,11 +151,13 @@ export const taskLogic = kea<taskLogicType>([// The archived task has no page left, so send the user to the list of the host they// are already in: the task page came from `/tasks`, but the shared AI workspace// renders the same detail under `/ai` and must not eject them to another product.- router.actions.push(- removeProjectIdIfPresent(router.values.location.pathname) === urls.ai()- ? urls.ai()- : urls.taskTracker()- )+ if (params?.leavePage !== false) {+ router.actions.push(+ removeProjectIdIfPresent(router.values.location.pathname) === urls.ai()+ ? urls.ai()+ : urls.taskTracker()+ )+ }return null},updateTask: async ({ data }: { data: TaskUpsertProps }) => {diff --git a/products/posthog_ai/frontend/scenes/TaskTracker/components/QuillTaskMenu.tsx b/products/posthog_ai/frontend/scenes/TaskTracker/components/QuillTaskMenu.tsxindex 5a38a6b5abfa..6430f219fb49 100644--- a/products/posthog_ai/frontend/scenes/TaskTracker/components/QuillTaskMenu.tsx+++ b/products/posthog_ai/frontend/scenes/TaskTracker/components/QuillTaskMenu.tsx@@ -1,31 +1,19 @@-import { useActions, useValues } from 'kea'-import { type ReactNode, useState } from 'react'+import { useValues } from 'kea'+import { useState } from 'react'-import { IconArchive, IconBug, IconEllipsis, IconInfo } from '@posthog/icons'-import {- Button,- DropdownMenu,- DropdownMenuCheckboxItem,- DropdownMenuContent,- DropdownMenuItem,- DropdownMenuSeparator,- DropdownMenuTrigger,- MenuLabel,- cn,-} from '@posthog/quill-primitives'+import { IconEllipsis } from '@posthog/icons'+import { Button, DropdownMenu, DropdownMenuContent, DropdownMenuTrigger } from '@posthog/quill-primitives'-import { dayjs } from 'lib/dayjs'--import { SHEET_PARTS } from '~/layout/today/todayMenuParts'+import { DROPDOWN_PARTS, SHEET_PARTS, TodayMenuParts } from '~/layout/today/todayMenuParts'+import { panelChatTaskFor } from '~/layout/today/todayPanelChat'+import { TodayPanelMoveMenuItems } from '~/layout/today/TodayPanelMoveMenuItems'import { TodaySheetMenu } from '~/layout/today/TodaySheetMenu'import { todayShellLogic } from '~/layout/today/todayShellLogic'import type { TaskRunDetailDTOApi } from 'products/tasks/frontend/generated/api.schemas'-import { debugLogsLogic } from '../../../logics/debugLogsLogic'-import { modelCatalogueLogic } from '../../../logics/modelCatalogueLogic'import type { Task } from '../../../types/taskTypes'-import { getTaskRunMetadataFields } from './taskRunMetadataFields'+import { TaskMenuItems } from './TaskMenuItems'export interface QuillTaskMenuProps {task: Task@@ -33,52 +21,21 @@ export interface QuillTaskMenuProps {onArchive: () => void}-function RelativeTime({ time }: { time: string }): JSX.Element {- return (- <time dateTime={time} title={dayjs(time).format('MMM D, YYYY HH:mm:ss')}>- {dayjs(time).fromNow()}- </time>- )-}--function FactList({- facts,- className = 'gap-1 px-2 pb-1 text-xs',-}: {- facts: { label: string; value: ReactNode }[]- className?: string-}): JSX.Element {- return (- <dl className={cn('m-0 flex flex-col', className)}>- {facts.map((fact) => (- <div key={fact.label} className="flex items-baseline justify-between gap-4">- <dt className="text-muted-foreground">{fact.label}</dt>- <dd className="m-0 min-w-0 truncate text-end text-foreground">{fact.value}</dd>- </div>- ))}- </dl>- )-}-export function QuillTaskMenu({ task, selectedRun, onArchive }: QuillTaskMenuProps): JSX.Element {- const { catalogue } = useValues(modelCatalogueLogic)- const { canControlDebugLogs, debugLogsEnabled } = useValues(debugLogsLogic)- const { setDebugLogsEnabled } = useActions(debugLogsLogic)const { todayRailEnabled, phoneLayout } = useValues(todayShellLogic)const [sheetOpen, setSheetOpen] = useState(false)+ // The phone layout has no floating or docked panel to move the chat into.+ const chat = todayRailEnabled && !phoneLayout ? panelChatTaskFor(task, selectedRun) : null- const taskFacts = [- { label: 'Task ID', value: <span className="font-mono">{task.slug}</span> },- ...(task.repository ? [{ label: 'Repository', value: task.repository }] : []),- { label: 'Created by', value: task.created_by?.first_name || task.created_by?.email || 'Unknown' },- { label: 'Created', value: <RelativeTime time={task.created_at} /> },- ]- const runFacts = selectedRun- ? getTaskRunMetadataFields(selectedRun, catalogue).map((field) => ({- label: field.label,- value: field.kind === 'time' ? <RelativeTime time={field.value} /> : field.value,- }))- : []+ const items = (parts: TodayMenuParts): JSX.Element => (+ <TaskMenuItems+ parts={parts}+ task={task}+ run={selectedRun}+ onArchive={onArchive}+ placement={chat && <TodayPanelMoveMenuItems parts={parts} chat={chat} dataAttrPrefix="task" />}+ />+ )if (todayRailEnabled && phoneLayout) {return (@@ -93,43 +50,7 @@ export function QuillTaskMenu({ task, selectedRun, onArchive }: QuillTaskMenuPro<IconEllipsis /></Button><TodaySheetMenu open={sheetOpen} onOpenChange={setSheetOpen} title={task.title || 'Task'}>- <SHEET_PARTS.Sub- label={- <>- <IconInfo />- Task details- </>- }- title="Task details"- dataAttr="task-details"- >- <div className="flex flex-col gap-4 px-4 py-3">- <section className="flex flex-col gap-2">- <MenuLabel className="px-0">Task</MenuLabel>- <FactList facts={taskFacts} className="gap-2 text-sm" />- </section>- {runFacts.length > 0 && (- <section className="flex flex-col gap-2">- <MenuLabel className="px-0">Run</MenuLabel>- <FactList facts={runFacts} className="gap-2 text-sm" />- </section>- )}- </div>- </SHEET_PARTS.Sub>- {canControlDebugLogs && (- <SHEET_PARTS.Item- onClick={() => setDebugLogsEnabled(!debugLogsEnabled)}- dataAttr="run-toggle-debug-logs"- >- <IconBug />- {debugLogsEnabled ? 'Hide debug logs' : 'Show debug logs'}- </SHEET_PARTS.Item>- )}- <SHEET_PARTS.Separator />- <SHEET_PARTS.Item variant="destructive" onClick={onArchive} dataAttr="task-archive">- <IconArchive />- Archive task- </SHEET_PARTS.Item>+ {items(SHEET_PARTS)}</TodaySheetMenu></>)@@ -145,29 +66,7 @@ export function QuillTaskMenu({ task, selectedRun, onArchive }: QuillTaskMenuPro}/><DropdownMenuContent align="end" className="min-w-64 max-w-80">- <MenuLabel>Task</MenuLabel>- <FactList facts={taskFacts} />- {runFacts.length > 0 && (- <>- <DropdownMenuSeparator />- <MenuLabel>Run</MenuLabel>- <FactList facts={runFacts} />- </>- )}- <DropdownMenuSeparator />- {canControlDebugLogs && (- <DropdownMenuCheckboxItem- checked={debugLogsEnabled}- onCheckedChange={setDebugLogsEnabled}- data-attr="run-toggle-debug-logs"- >- Show debug logs- </DropdownMenuCheckboxItem>- )}- <DropdownMenuItem variant="destructive" onClick={onArchive} data-attr="task-archive">- <IconArchive />- Archive task- </DropdownMenuItem>+ {items(DROPDOWN_PARTS)}</DropdownMenuContent></DropdownMenu>)diff --git a/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskMenuFacts.tsx b/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskMenuFacts.tsxnew file mode 100644index 000000000000..d3aa055c4c0e--- /dev/null+++ b/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskMenuFacts.tsx@@ -0,0 +1,75 @@+import { useValues } from 'kea'+import type { ReactNode } from 'react'++import { MenuLabel, Separator, cn } from '@posthog/quill-primitives'++import { dayjs } from 'lib/dayjs'++import type { TaskRunDetailDTOApi } from 'products/tasks/frontend/generated/api.schemas'++import { modelCatalogueLogic } from '../../../logics/modelCatalogueLogic'+import type { Task } from '../../../types/taskTypes'+import { getTaskRunMetadataFields } from './taskRunMetadataFields'++export interface TaskMenuFactsProps {+ task: Task+ run: TaskRunDetailDTOApi | null+}++interface Fact {+ label: string+ value: ReactNode+}++function RelativeTime({ time }: { time: string }): JSX.Element {+ return (+ <time dateTime={time} title={dayjs(time).format('MMM D, YYYY HH:mm:ss')}>+ {dayjs(time).fromNow()}+ </time>+ )+}++function FactList({ facts, className }: { facts: Fact[]; className: string }): JSX.Element {+ return (+ <dl className={cn('m-0 flex flex-col', className)}>+ {facts.map((fact) => (+ <div key={fact.label} className="flex items-baseline justify-between gap-4">+ <dt className="text-muted-foreground">{fact.label}</dt>+ <dd className="m-0 min-w-0 truncate text-end text-foreground">{fact.value}</dd>+ </div>+ ))}+ </dl>+ )+}++export function TaskMenuFacts({ task, run }: TaskMenuFactsProps): JSX.Element {+ const { catalogue } = useValues(modelCatalogueLogic)++ const taskFacts: Fact[] = [+ { label: 'Task ID', value: <span className="font-mono">{task.slug}</span> },+ ...(task.repository ? [{ label: 'Repository', value: task.repository }] : []),+ { label: 'Created by', value: task.created_by?.first_name || task.created_by?.email || 'Unknown' },+ { label: 'Created', value: <RelativeTime time={task.created_at} /> },+ ]+ const runFacts: Fact[] = run+ ? getTaskRunMetadataFields(run, catalogue).map((field) => ({+ label: field.label,+ value: field.kind === 'time' ? <RelativeTime time={field.value} /> : field.value,+ }))+ : []++ return (+ <>+ <MenuLabel>Task</MenuLabel>+ <FactList facts={taskFacts} className="gap-1 px-2 pb-1 text-xs" />+ {runFacts.length > 0 && (+ <>+ {/* A plain separator, so the details render the same inside a menu and on a sheet page. */}+ <Separator className="my-1" />+ <MenuLabel>Run</MenuLabel>+ <FactList facts={runFacts} className="gap-1 px-2 pb-1 text-xs" />+ </>+ )}+ </>+ )+}diff --git a/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskMenuItems.tsx b/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskMenuItems.tsxnew file mode 100644index 000000000000..235ee9be87b8--- /dev/null+++ b/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskMenuItems.tsx@@ -0,0 +1,50 @@+import type { ReactNode } from 'react'++import { IconArchive, IconInfo } from '@posthog/icons'++import type { TodayMenuParts } from '~/layout/today/todayMenuParts'++import type { TaskRunDetailDTOApi } from 'products/tasks/frontend/generated/api.schemas'++import { DebugLogsMenuItem } from '../../../components/DebugLogsMenuItem'+import type { Task } from '../../../types/taskTypes'+import { TaskMenuFacts } from './TaskMenuFacts'++export interface TaskMenuItemsProps {+ parts: TodayMenuParts+ task: Task+ run: TaskRunDetailDTOApi | null+ onArchive: () => void+ placement?: ReactNode+}++export function TaskMenuItems({ parts, task, run, onArchive, placement }: TaskMenuItemsProps): JSX.Element {+ return (+ <>+ {placement && (+ <>+ {placement}+ <parts.Separator />+ </>+ )}+ <DebugLogsMenuItem parts={parts} />+ <parts.Item variant="destructive" onClick={onArchive} dataAttr="task-archive">+ <IconArchive />+ Archive task+ </parts.Item>+ <parts.Separator />+ <parts.Section+ label={+ <>+ <IconInfo />+ Task details+ </>+ }+ title="Task details"+ dataAttr="task-details"+ >+ <TaskMenuFacts task={task} run={run} />+ </parts.Section>+ </>+ )+}diff --git a/products/posthog_ai/frontend/scenes/TaskTracker/taskDetailSceneLogic.ts b/products/posthog_ai/frontend/scenes/TaskTracker/taskDetailSceneLogic.tsindex 064d0ed6feea..312b69bec18f 100644--- a/products/posthog_ai/frontend/scenes/TaskTracker/taskDetailSceneLogic.ts+++ b/products/posthog_ai/frontend/scenes/TaskTracker/taskDetailSceneLogic.ts@@ -58,7 +58,15 @@ export interface taskDetailSceneLogicValues {// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface taskDetailSceneLogicActions {- deleteTask: () => any // taskLogic+ deleteTask: (+ params?:+ | {+ leavePage?: boolean+ }+ | undefined+ ) => {+ leavePage?: boolean+ } // taskLogicloadTask: () => any // taskLogicloadTaskSuccess: (task: Task | null,