Skip to content

: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.

13.3 KB
Raw Blame
import { BindLogic, useActions, useValues } from 'kea'
import { router } from 'kea-router'

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'
import { cn } from 'lib/utils/css-classes'
import { urls } from 'scenes/urls'

import type { PhaiViewMode } from '~/layout/ai/aiPanelIds'
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 { useThreadSkin } from 'products/posthog_ai/frontend/api/logics'
import { DebugLogsMenuItem } from 'products/posthog_ai/frontend/api/menus'
import { DebugLogsMenu } from 'products/posthog_ai/frontend/api/primitives'
import { EmbeddedRunner } from 'products/posthog_ai/frontend/api/runner'

import { aiSceneView } from '../aiSceneView'
import { Intro } from '../Intro'
import { maxGlobalLogic } from '../maxGlobalLogic'
import { maxLogic } from '../maxLogic'
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'

/* Sits above the chat area */
export function ChatHeader({
    conversationId,
    tabId,
    children,
    hideBorder,
    isSandboxRuntime,
    hideViewToggle,
    onViewChange,
}: {
    conversationId: string | null
    tabId?: string
    children?: React.ReactNode
    hideBorder?: boolean
    /** Debug rows only exist on the sandbox runtime, so the staff menu that reveals them is hidden elsewhere. */
    isSandboxRuntime?: boolean
    /** For a surface the URL pinned, where the saved view the toggle reads does not match what is shown. */
    hideViewToggle?: boolean
    onViewChange?: (mode: PhaiViewMode) => void
}): JSX.Element {
    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
            className={cn(
                'flex w-full gap-2 py-2 border-b border-primary items-center justify-between px-2',
                hideBorder && 'border-b-0'
            )}
        >
            <div className="flex items-center gap-2 pl-2 text-sm font-medium truncate min-w-0 flex-1">
                {children}
                {chatTitle === null ? null : isTitleLoading ? (
                    <div className="w-100">
                        <SceneName name="New chat" isLoading />
                    </div>
                ) : (
                    <SceneName name={chatTitle} />
                )}
            </div>
            <div className="flex items-center gap-2">
                {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>
    )
}

interface AiFirstMaxInstanceProps {
    tabId: string
    taskId?: string
    /** The legacy conversation the URL names. It pins the legacy chat, as `taskId` pins the runner. */
    chatId?: string
}

export function AiFirstMaxInstance({ tabId, taskId, chatId }: AiFirstMaxInstanceProps): JSX.Element {
    const { threadVisible, threadLogicKey, conversation, conversationId } = useValues(maxLogic({ panelId: tabId }))
    const { 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">
                        {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">
                    <BindLogic logic={phaiAiComposerSeedLogic} props={{ tabId }}>
                        {/* The quill task header carries the debug logs switch in its own overflow menu. */}
                        <EmbeddedRunner
                            taskId={taskId}
                            titleActions={skin === 'lemon' ? <DebugLogsMenu variant="lemon" /> : undefined}
                        />
                    </BindLogic>
                </div>
            </div>
        )
    }

    const threadProps: MaxThreadLogicProps = {
        panelId: tabId,
        conversationId: threadLogicKey,
        conversation,
    }

    return (
        <div className="flex grow overflow-hidden h-full">
            <BindLogic logic={maxLogic} props={{ panelId: tabId }}>
                <BindLogic logic={maxThreadLogic} props={threadProps}>
                    <div className="flex flex-col grow overflow-hidden">
                        <ChatHeader
                            conversationId={conversationId}
                            tabId={tabId}
                            isSandboxRuntime={conversation?.agent_runtime === 'sandbox'}
                            // A chat link opened the legacy chat over the saved new view: the toggle would
                            // offer "legacy" for what is already shown. "New chat" leads back to the runner.
                            hideViewToggle={!!chatId && effectivePhaiView === 'new'}
                            // Legacy Max keeps `?chat=` in the URL once a conversation starts, and that param
                            // pins this chat, so switching to the new view has to leave the conversation too.
                            onViewChange={(mode) => {
                                if (mode === 'new' && chatId) {
                                    router.actions.push(urls.ai())
                                }
                            }}
                        />
                        {isMaxAvailable ? (
                            <ChatArea
                                threadVisible={threadVisible}
                                conversationId={conversationId}
                                conversation={conversation}
                                onStartNewConversation={startNewConversation}
                            />
                        ) : (
                            <MaxNotConfigured />
                        )}
                    </div>
                </BindLogic>
            </BindLogic>
        </div>
    )
}

interface ChatAreaProps {
    threadVisible: boolean
    conversationId: string | null
    conversation: { has_unsupported_content?: boolean } | null
    onStartNewConversation: () => void
}

function ChatArea({ threadVisible, conversation, onStartNewConversation }: ChatAreaProps): JSX.Element {
    const hasMessages = threadVisible

    return (
        <div className="flex flex-col grow overflow-y-auto" data-attr="max-scrollable">
            {/* Top spacer - fills space above content, shrinks when messages appear */}
            <div className={`transition-[flex-grow] duration-300 ease-out ${hasMessages ? 'grow-0' : 'grow'}`} />

            {/* Intro - fades out when messages appear */}
            <div
                className={`flex flex-col items-center transition-[opacity,height,padding] duration-200 ease-out ${
                    hasMessages ? 'opacity-0 h-0 overflow-hidden' : 'opacity-100 pb-3'
                }`}
            >
                <Intro />
            </div>

            {/* Thread content - appears when messages exist */}
            {hasMessages && (
                <ThreadAutoScroller>
                    {conversation?.has_unsupported_content && (
                        <div className="px-4 pt-4">
                            <LemonBanner type="warning">
                                <div className="flex items-center justify-between gap-4">
                                    <span>This thread contains content that is no longer supported.</span>
                                    <LemonButton type="primary" onClick={onStartNewConversation}>
                                        Start a new thread
                                    </LemonButton>
                                </div>
                            </LemonBanner>
                        </div>
                    )}
                    <Thread />
                </ThreadAutoScroller>
            )}

            {/* Input - always in flow, mt-auto pushes to bottom when messages exist */}
            <div
                className={`w-full max-w-3xl mx-auto px-4 transition-[max-width,padding,background-color] duration-300 ease-out z-50 ${
                    hasMessages ? 'sticky bottom-0 bg-primary py-2 max-w-none' : 'pb-4'
                }`}
            >
                {!conversation?.has_unsupported_content && (
                    <SidebarQuestionInputWithSuggestions hideSuggestions={hasMessages} />
                )}
            </div>

            {/* Bottom spacer - fills space below content, shrinks when messages appear */}
            <div className={`transition-[flex-grow] duration-300 ease-out ${hasMessages ? 'grow-0' : 'grow'}`} />
        </div>
    )
}