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.

35.7 KB
Raw Blame
import { MOCK_DEFAULT_ORGANIZATION } from 'lib/api.mock'

import { router } from 'kea-router'
import { expectLogic, partial } from 'kea-test-utils'

import { FEATURE_FLAGS } from 'lib/constants'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { urls } from 'scenes/urls'

import { REPORT_AI_PANEL, SCOUT_AI_PANEL, SIDE_PANEL_PANEL_ID } from '~/layout/ai/aiPanelIds'
import { runnerPanelLogic } from '~/layout/ai/runnerPanelLogic'
import { sidePanelStateLogic } from '~/layout/navigation-3000/sidepanel/sidePanelStateLogic'
import { useMocks } from '~/mocks/jest'
import { AgentMode } from '~/queries/schema/schema-assistant-messages'
import { initKeaTests } from '~/test/init'
import { ConversationDetail, SidePanelTab } from '~/types'

import { composerSeedLogic } from 'products/posthog_ai/frontend/api/logics'

import { maxContextLogic } from './maxContextLogic'
import { maxGlobalLogic } from './maxGlobalLogic'
import {
    PENDING_MAX_CONTEXT_KEY,
    QUESTION_SUGGESTIONS_DATA,
    maxLogic,
    mergeConversationHistory,
    mergeConversations,
} from './maxLogic'
import { maxThreadLogic } from './maxThreadLogic'
import { MOCK_CONVERSATION, MOCK_CONVERSATION_ID, maxMocks } from './testUtils'

describe('maxLogic', () => {
    let logic: ReturnType<typeof maxLogic.build>
    let threadLogic: ReturnType<typeof maxThreadLogic.build> | null = null
    let actionsRequestCount: number
    let conversationRequestCount: number

    beforeEach(() => {
        localStorage.clear()
        sessionStorage.clear()
        actionsRequestCount = 0
        conversationRequestCount = 0
        useMocks({
            ...maxMocks,
            get: {
                ...maxMocks.get,
                '/api/environments/:team_id/conversations/': () => {
                    conversationRequestCount++
                    return [200, { results: [] }]
                },
                '/api/projects/:team/actions/': () => {
                    actionsRequestCount++
                    return [200, { results: [], count: 0 }]
                },
            },
        })
        initKeaTests()
    })

    it.each(['scene', SIDE_PANEL_PANEL_ID])(
        'moves files and the draft to the new composer from %s',
        async (panelId) => {
            logic = maxLogic({ panelId })
            logic.mount()
            featureFlagLogic.actions.setFeatureFlags([], { [FEATURE_FLAGS.PHAI_SANDBOX_MODE]: true })
            maxGlobalLogic.actions.setPhaiViewMode('legacy')
            const files = [new File(['demo'], 'notes.txt', { type: 'text/plain' })]
            const seed = composerSeedLogic({ panelId: panelId === SIDE_PANEL_PANEL_ID ? 'max-side-panel' : undefined })

            const panel = runnerPanelLogic({ panelId: panelId === SIDE_PANEL_PANEL_ID ? 'max-side-panel' : undefined })
            const unmountPanel = panel.mount()
            panel.actions.setActiveCreation({
                streamKey: 'previous-task',
                taskId: 'previous-task',
                runId: 'previous-run',
            })
            panel.actions.setHistoryExpanded(true)
            maxContextLogic.actions.addOrUpdateContextNotebook({ short_id: 'example-notebook', title: 'Demo notebook' })

            logic.actions.attachFilesToNewChat(files, 'Read these notes')

            expect(seed.values.seed).toMatchObject({ prompt: 'Read these notes', files, autoSubmit: false })
            expect(maxGlobalLogic.values.effectivePhaiView).toBe('new')
            expect(panel.values.activeCreation).toBeNull()
            expect(panel.values.historyExpanded).toBe(false)
            expect(JSON.parse(seed.values.seed!.contextItems![0].value!).notebooks).toEqual([
                expect.objectContaining({ id: 'example-notebook', name: 'Demo notebook' }),
            ])
            unmountPanel()
        }
    )

    it('keeps the legacy view when file selection is canceled or the new runtime is unavailable', () => {
        logic = maxLogic({ panelId: 'scene' })
        logic.mount()
        maxGlobalLogic.actions.setPhaiViewMode('legacy')
        featureFlagLogic.actions.setFeatureFlags([], { [FEATURE_FLAGS.PHAI_SANDBOX_MODE]: true })
        logic.actions.attachFilesToNewChat([], 'Keep this draft')
        expect(maxGlobalLogic.values.effectivePhaiView).toBe('legacy')
        expect(composerSeedLogic().values.seed).toBeNull()

        featureFlagLogic.actions.setFeatureFlags([], { [FEATURE_FLAGS.PHAI_SANDBOX_MODE]: false })
        logic.actions.attachFilesToNewChat([new File(['demo'], 'notes.txt')], 'Keep this draft')
        expect(maxGlobalLogic.values.phaiViewMode).toBe('legacy')
        expect(composerSeedLogic().values.seed).toBeNull()
    })

    afterEach(async () => {
        if (logic?.isMounted()) {
            await expectLogic(logic).toFinishAllListeners()
        }
        threadLogic?.unmount()
        threadLogic = null
        sidePanelStateLogic.unmount()
        // Reset maxLogic state before unmounting to prevent state leaking to next test
        if (logic?.isMounted()) {
            logic.actions.startNewConversation()
        }
        logic?.unmount()
    })

    it('passes panelId through thread logic props', () => {
        logic = maxLogic({ panelId: 'notebook-inline-inline-chat-id', initialFrontendConversationId: 'chat-id' })
        logic.mount()

        expect(logic.values.threadLogicProps).toMatchObject({
            panelId: 'notebook-inline-inline-chat-id',
            conversationId: 'chat-id',
        })
    })

    it.each([
        { age: 0, expectedRequests: 1 },
        { age: 29_999, expectedRequests: 1 },
        { age: 30_000, expectedRequests: 2 },
    ])('shares history requests until the result is stale ($age ms)', async ({ age, expectedRequests }) => {
        logic = maxLogic({ panelId: 'test' })
        logic.mount()

        await expectLogic(logic).toDispatchActions(['loadConversationHistorySuccess'])

        expect(actionsRequestCount).toBe(0)
        expect(conversationRequestCount).toBe(1)

        const loadedAt = maxGlobalLogic.values.conversationHistoryLoadedAt!
        const clock = jest.spyOn(Date, 'now').mockReturnValue(loadedAt + age)
        const unmountPanel = maxLogic({ panelId: 'another-panel' }).mount()
        try {
            await expectLogic(maxGlobalLogic).toFinishAllListeners()
            expect(conversationRequestCount).toBe(expectedRequests)
        } finally {
            unmountPanel()
            clock.mockRestore()
        }
    })

    it.each([
        ['Foo', 'Foo'],
        [REPORT_AI_PANEL, ''],
        [SCOUT_AI_PANEL, ''],
    ])('seeds the question from side panel option %s', async (options, question) => {
        sidePanelStateLogic.mount()
        await expectLogic(sidePanelStateLogic, () => {
            sidePanelStateLogic.actions.openSidePanel(SidePanelTab.Max, options)
        }).toDispatchActions(['openSidePanel'])

        logic = maxLogic({ panelId: SIDE_PANEL_PANEL_ID })
        logic.mount()

        await expectLogic(logic).toMatchValues({ question, autoRun: false })
        logic.actions.setQuestion('Existing draft')
        sidePanelStateLogic.actions.openSidePanel(SidePanelTab.Max, REPORT_AI_PANEL)
        expect(logic.values.question).toBe('Existing draft')
    })

    it('sets autoRun and question when URL has hash param #panel=max:!Foo', async () => {
        // Set up sidePanelStateLogic with the options before mounting maxLogic
        sidePanelStateLogic.mount()
        await expectLogic(sidePanelStateLogic, () => {
            sidePanelStateLogic.actions.openSidePanel(SidePanelTab.Max, '!Foo')
        }).toDispatchActions(['openSidePanel'])

        // Must create the logic first to spy on its actions
        logic = maxLogic({ panelId: SIDE_PANEL_PANEL_ID })
        logic.mount()

        // Only mount maxLogic after setting up the router and sidePanelStateLogic
        await expectLogic(logic).toMatchValues({
            autoRun: true,
            question: 'Foo',
        })
    })

    it('does not set autoRun for #panel=max:!Foo when the new panel view is active', async () => {
        // In the new view the prompt is consumed by phaiSidePanelComposerSeedLogic; autoRun here too
        // would make the hidden legacy thread fire askMax on top of the new composer's submit.
        featureFlagLogic.mount()
        featureFlagLogic.actions.setFeatureFlags([], { [FEATURE_FLAGS.PHAI_SANDBOX_MODE]: true })

        sidePanelStateLogic.mount()
        await expectLogic(sidePanelStateLogic, () => {
            sidePanelStateLogic.actions.openSidePanel(SidePanelTab.Max, '!Foo')
        }).toDispatchActions(['openSidePanel'])

        logic = maxLogic({ panelId: SIDE_PANEL_PANEL_ID })
        logic.mount()

        await expectLogic(logic).toMatchValues({
            autoRun: false,
            question: 'Foo',
        })

        featureFlagLogic.unmount()
    })

    it('keeps the selected task URL when navigating from a legacy chat', async () => {
        logic = maxLogic({ panelId: 'scene' })
        logic.mount()
        logic.actions.openConversation(MOCK_CONVERSATION_ID)
        await expectLogic(logic).toFinishAllListeners()
        router.actions.push(urls.aiTask('task-1'))
        await expectLogic(logic).toFinishAllListeners()

        expect(router.values.location.pathname).toBe(urls.currentProject(urls.ai()))
        expect(router.values.searchParams).toEqual({ task: 'task-1' })
    })

    // Regression coverage: the `/ai` handler deliberately leaves the previous chat in this logic
    // while a task is open, and `maxGlobalLogic` clears that chat from every mounted logic when it
    // is deleted. Mapping `startNewConversation` to a bare `/ai` then dropped `?task=` and closed
    // the task the user was reading, without the user navigating at all.
    it('keeps the selected task URL when the retained chat is deleted', async () => {
        useMocks({ ...maxMocks, delete: { '/api/environments/:team_id/conversations/:id': [200, {}] } })
        logic = maxLogic({ panelId: 'scene' })
        logic.mount()
        logic.actions.openConversation(MOCK_CONVERSATION_ID)
        await expectLogic(logic).toFinishAllListeners()
        router.actions.push(urls.aiTask('task-1'))
        await expectLogic(logic).toFinishAllListeners()

        maxGlobalLogic.actions.deleteConversation(MOCK_CONVERSATION_ID)
        await expectLogic(maxGlobalLogic).toFinishAllListeners()

        // The stale chat is still released, it just must not take the route with it.
        expect(logic.values.conversationId).toBeNull()
        expect(router.values.location.pathname).toBe(urls.currentProject(urls.ai()))
        expect(router.values.searchParams).toEqual({ task: 'task-1' })
    })

    // The /ai?ask= deep link (e.g. "Start with AI") must not silently vanish when the org hasn't
    // granted AI data-processing consent: askMax no-ops in that case, so the handler has to fall back
    // to prefilling the composer. With consent it auto-sends via askMax instead.
    describe('ask URL parameter', () => {
        it('prefills the composer without auto-sending when AI consent is not granted', async () => {
            initKeaTests(true, undefined, undefined, {
                ...MOCK_DEFAULT_ORGANIZATION,
                is_ai_data_processing_approved: false,
            })
            useMocks(maxMocks)
            router.actions.push(urls.ai(undefined, 'Explore my traces'))

            logic = maxLogic({ panelId: 'test' })
            logic.mount()

            await expectLogic(logic).toMatchValues({ question: 'Explore my traces' })
        })

        it('clears any pending deep-link context even when consent is not granted', async () => {
            initKeaTests(true, undefined, undefined, {
                ...MOCK_DEFAULT_ORGANIZATION,
                is_ai_data_processing_approved: false,
            })
            useMocks(maxMocks)
            sessionStorage.setItem(
                PENDING_MAX_CONTEXT_KEY,
                JSON.stringify({ context: { dashboards: [] }, timestamp: Date.now() })
            )
            router.actions.push(urls.ai(undefined, 'Explore my traces'))

            logic = maxLogic({ panelId: 'test' })
            logic.mount()

            await expectLogic(logic).toMatchValues({ question: 'Explore my traces' })
            expect(sessionStorage.getItem(PENDING_MAX_CONTEXT_KEY)).toBeNull()
        })

        it('auto-sends via askMax without prefilling when AI consent is granted', async () => {
            initKeaTests(true, undefined, undefined, {
                ...MOCK_DEFAULT_ORGANIZATION,
                is_ai_data_processing_approved: true,
            })
            useMocks(maxMocks)
            router.actions.push(urls.ai(undefined, 'Explore my traces'))

            logic = maxLogic({ panelId: 'test' })
            logic.mount()

            await expectLogic(logic).toDispatchActions([
                logic.actionCreators.askMax('Explore my traces', true, undefined),
            ])
            expect(logic.values.question).toBe('')
        })
    })

    it('does not reset conversation when 404 occurs during active message generation', async () => {
        router.actions.push('', {}, { panel: 'max' })
        sidePanelStateLogic.mount()

        const mockConversationId = 'new-conversation-id'

        useMocks({
            ...maxMocks,
            get: {
                ...maxMocks.get,
                '/api/environments/:team_id/conversations/': { results: [] },
                [`/api/environments/:team_id/conversations/${mockConversationId}`]: () => [
                    404,
                    { detail: 'Not found' },
                ],
            },
        })

        logic = maxLogic({ panelId: 'test' })
        logic.mount()

        // Wait for initial conversationHistory load to complete
        await expectLogic(logic).toDispatchActions(['loadConversationHistorySuccess'])

        // Simulate asking Max a question (which starts a new conversation)
        await expectLogic(logic, () => {
            logic.actions.setQuestion('Test question')
            logic.actions.setConversationId(mockConversationId)
        }).toDispatchActions(['setQuestion', 'setConversationId'])

        // Now simulate the race condition: when pollConversation is called from loadConversationHistorySuccess,
        // it will get a 404 for the conversation that doesn't exist yet on the backend
        // but is being generated on the frontend
        await expectLogic(logic, () => {
            logic.actions.pollConversation(mockConversationId, 0, 0)
        }).toFinishAllListeners()

        // Wait a bit for any async operations
        await expectLogic(logic).delay(50)

        // The conversation should NOT be reset - conversationId should still be set
        await expectLogic(logic).toMatchValues({
            conversationId: mockConversationId,
        })

        // Verify no error toast was shown and no reset occurred
        expect(Array.isArray(logic.values.conversationHistory)).toBe(true)
    })

    it('manages suggestion group selection correctly', async () => {
        logic = maxLogic({ panelId: 'test' })
        logic.mount()

        await expectLogic(logic).toMatchValues({
            activeSuggestionGroup: null,
        })

        await expectLogic(logic, () => {
            logic.actions.setActiveGroup(QUESTION_SUGGESTIONS_DATA[1])
        })
            .toDispatchActions(['setActiveGroup'])
            .toMatchValues({
                activeSuggestionGroup: partial({
                    label: 'SQL',
                }),
            })

        // Test setting to null clears the selection
        logic.actions.setActiveGroup(null)

        await expectLogic(logic).toMatchValues({
            activeSuggestionGroup: null,
        })

        // Test setting to a different index
        logic.actions.setActiveGroup(QUESTION_SUGGESTIONS_DATA[0])

        await expectLogic(logic).toMatchValues({
            activeSuggestionGroup: partial({
                label: 'Product analytics',
            }),
        })
    })

    it('generates and uses frontendConversationId correctly', async () => {
        logic = maxLogic({ panelId: 'test' })
        logic.mount()

        const initialFrontendId = logic.values.frontendConversationId
        expect(initialFrontendId).toBeTruthy()
        expect(typeof initialFrontendId).toBe('string')

        // Test that the ID is a valid UUID
        const uuidRegex = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i
        expect(initialFrontendId).toMatch(uuidRegex)

        // Test that starting a new conversation generates a new frontend ID
        await expectLogic(logic, () => {
            logic.actions.startNewConversation()
        }).toMatchValues({
            frontendConversationId: expect.not.stringMatching(initialFrontendId),
        })

        expect(logic.values.frontendConversationId).toBeTruthy()
        expect(logic.values.frontendConversationId).not.toBe(initialFrontendId)

        // Test that the new ID is also a valid UUID
        expect(logic.values.frontendConversationId).toMatch(uuidRegex)
    })

    // The side panel chat floats over whatever scene you're on (e.g. an insight or survey). The
    // rendered scene is chosen by the route, so if the side panel pushes /ai it replaces the main
    // content — which is the regression. Only the scene instance, which owns /ai, may navigate.
    // These are every route-affecting action; the side panel must stay silent on all of them,
    // including setConversationId, which fires a replace nav when a brand-new conversation is minted.
    // The harness prefixes the project id (/project/<id>/…), so match the path suffix.
    const PAGES = ['/insights/abc123', '/surveys/xyz789']
    const routeActions = [
        { name: 'startNewConversation', act: () => logic.actions.startNewConversation() },
        { name: 'openConversation', act: () => logic.actions.openConversation(MOCK_CONVERSATION_ID) },
        { name: 'setConversationId', act: () => logic.actions.setConversationId(logic.values.frontendConversationId) },
        { name: 'toggleConversationHistory', act: () => logic.actions.toggleConversationHistory() },
    ]
    const sidePanelCases = PAGES.flatMap((page) => routeActions.map((action) => ({ page, ...action })))

    it.each(sidePanelCases)('side panel chat keeps the main content on $page on $name', async ({ page, act }) => {
        useMocks({ get: { '/api/environments/:team_id/conversations/:id': MOCK_CONVERSATION } })
        router.actions.push(page)

        logic = maxLogic({ panelId: SIDE_PANEL_PANEL_ID })
        logic.mount()

        await expectLogic(logic, () => act()).toFinishAllListeners()

        expect(router.values.location.pathname.endsWith(page)).toBe(true)
    })

    it.each(routeActions)('embedded chat keeps the current route on $name', async ({ act }) => {
        useMocks({ get: { '/api/environments/:team_id/conversations/:id': MOCK_CONVERSATION } })
        router.actions.push('/notebooks/notebook-short-id')

        logic = maxLogic({
            panelId: 'notebook-inline-inline-chat-id',
            initialFrontendConversationId: 'chat-id',
            syncUrl: false,
        })
        logic.mount()

        await expectLogic(logic, () => act()).toFinishAllListeners()

        expect(router.values.location.pathname).toContain('/notebooks/notebook-short-id')
    })

    it.each(routeActions)('scene chat navigates to /ai on $name', async ({ act }) => {
        useMocks({ get: { '/api/environments/:team_id/conversations/:id': MOCK_CONVERSATION } })
        router.actions.push('/insights/abc123')

        logic = maxLogic({ panelId: 'test' })
        logic.mount()

        await expectLogic(logic, () => act()).toFinishAllListeners()

        expect(router.values.location.pathname).toContain(urls.ai())
    })

    it('uses threadLogicKey correctly with frontendConversationId', async () => {
        logic = maxLogic({ panelId: 'test' })
        logic.mount()

        // When no conversation ID is set, should use frontendConversationId
        await expectLogic(logic).toMatchValues({
            threadLogicKey: logic.values.frontendConversationId,
        })

        // When conversation ID is set, should use it
        await expectLogic(logic, () => {
            logic.actions.setConversationId('test-conversation-id')
        }).toMatchValues({
            threadLogicKey: 'test-conversation-id',
        })
    })

    describe('mode URL parameter', () => {
        beforeEach(() => {
            // Enable feature flags for gated modes
            featureFlagLogic.mount()
            featureFlagLogic.actions.setFeatureFlags([], {
                [FEATURE_FLAGS.MAX_DEEP_RESEARCH]: true,
                [FEATURE_FLAGS.PHAI_PLAN_MODE]: true,
            })
        })

        afterEach(() => {
            featureFlagLogic.unmount()
        })

        it('parses mode=research:!Question correctly', async () => {
            sidePanelStateLogic.mount()
            await expectLogic(sidePanelStateLogic, () => {
                sidePanelStateLogic.actions.openSidePanel(SidePanelTab.Max, 'mode=research:!Question')
            }).toDispatchActions(['openSidePanel'])

            logic = maxLogic({ panelId: SIDE_PANEL_PANEL_ID })
            logic.mount()

            await expectLogic(logic).toMatchValues({
                autoRun: true,
                question: 'Question',
            })

            threadLogic = maxThreadLogic({
                panelId: SIDE_PANEL_PANEL_ID,
                conversationId: logic.values.frontendConversationId,
                conversation: null,
            })
            threadLogic.mount()

            await expectLogic(threadLogic).toMatchValues({
                agentMode: AgentMode.Research,
            })
        })

        it('parses mode=product_analytics:Question correctly', async () => {
            sidePanelStateLogic.mount()
            await expectLogic(sidePanelStateLogic, () => {
                sidePanelStateLogic.actions.openSidePanel(SidePanelTab.Max, 'mode=product_analytics:Question')
            }).toDispatchActions(['openSidePanel'])

            logic = maxLogic({ panelId: SIDE_PANEL_PANEL_ID })
            logic.mount()

            await expectLogic(logic).toMatchValues({
                autoRun: false,
                question: 'Question',
            })

            threadLogic = maxThreadLogic({
                panelId: SIDE_PANEL_PANEL_ID,
                conversationId: logic.values.frontendConversationId,
                conversation: null,
            })
            threadLogic.mount()

            await expectLogic(threadLogic).toMatchValues({
                agentMode: AgentMode.ProductAnalytics,
            })
        })

        it('parses mode=sql:!Write a query correctly', async () => {
            sidePanelStateLogic.mount()
            await expectLogic(sidePanelStateLogic, () => {
                sidePanelStateLogic.actions.openSidePanel(SidePanelTab.Max, 'mode=sql:!Write a query')
            }).toDispatchActions(['openSidePanel'])

            logic = maxLogic({ panelId: SIDE_PANEL_PANEL_ID })
            logic.mount()

            await expectLogic(logic).toMatchValues({
                autoRun: true,
                question: 'Write a query',
            })

            threadLogic = maxThreadLogic({
                panelId: SIDE_PANEL_PANEL_ID,
                conversationId: logic.values.frontendConversationId,
                conversation: null,
            })
            threadLogic.mount()

            await expectLogic(threadLogic).toMatchValues({
                agentMode: AgentMode.SQL,
            })
        })

        it('parses mode=auto:!Question correctly (null mode)', async () => {
            // Mount maxLogic first and reset state to ensure clean slate
            logic = maxLogic({ panelId: SIDE_PANEL_PANEL_ID })
            logic.mount()
            logic.actions.startNewConversation()

            // Now set up sidePanelStateLogic with the options
            sidePanelStateLogic.mount()

            // Dispatch openSidePanel - the listener in maxLogic will process this
            await expectLogic(logic, () => {
                sidePanelStateLogic.actions.openSidePanel(SidePanelTab.Max, 'mode=auto:!Question')
            }).toMatchValues({
                autoRun: true,
                question: 'Question',
            })

            threadLogic = maxThreadLogic({
                panelId: SIDE_PANEL_PANEL_ID,
                conversationId: logic.values.frontendConversationId,
                conversation: null,
            })
            threadLogic.mount()

            await expectLogic(threadLogic).toMatchValues({
                agentMode: null,
            })
        })

        it('parses mode=research correctly (mode only, no question)', async () => {
            // Mount maxLogic first and reset state to ensure clean slate
            logic = maxLogic({ panelId: SIDE_PANEL_PANEL_ID })
            logic.mount()
            logic.actions.startNewConversation()

            // Now set up sidePanelStateLogic with the options
            sidePanelStateLogic.mount()

            // Dispatch openSidePanel - the listener in maxLogic will process this
            await expectLogic(logic, () => {
                sidePanelStateLogic.actions.openSidePanel(SidePanelTab.Max, 'mode=research')
            }).toMatchValues({
                autoRun: false,
                question: '',
            })

            threadLogic = maxThreadLogic({
                panelId: SIDE_PANEL_PANEL_ID,
                conversationId: logic.values.frontendConversationId,
                conversation: null,
            })
            threadLogic.mount()

            await expectLogic(threadLogic).toMatchValues({
                agentMode: AgentMode.Research,
            })
        })

        it('parses mode=invalid_mode:!Question correctly (ignores invalid mode)', async () => {
            sidePanelStateLogic.mount()
            await expectLogic(sidePanelStateLogic, () => {
                sidePanelStateLogic.actions.openSidePanel(SidePanelTab.Max, 'mode=invalid_mode:!Question')
            }).toDispatchActions(['openSidePanel'])

            logic = maxLogic({ panelId: SIDE_PANEL_PANEL_ID })
            logic.mount()

            await expectLogic(logic).toMatchValues({
                autoRun: true,
                question: 'Question',
            })

            threadLogic = maxThreadLogic({
                panelId: SIDE_PANEL_PANEL_ID,
                conversationId: logic.values.frontendConversationId,
                conversation: null,
            })
            threadLogic.mount()

            await expectLogic(threadLogic).toMatchValues({
                agentMode: null,
            })
        })

        it('parses !My question correctly (backwards compatibility)', async () => {
            // Mount maxLogic first and reset state to ensure clean slate
            logic = maxLogic({ panelId: SIDE_PANEL_PANEL_ID })
            logic.mount()
            logic.actions.startNewConversation()

            // Now set up sidePanelStateLogic with the options
            sidePanelStateLogic.mount()

            // Dispatch openSidePanel - the listener in maxLogic will process this
            await expectLogic(logic, () => {
                sidePanelStateLogic.actions.openSidePanel(SidePanelTab.Max, '!My question')
            }).toMatchValues({
                autoRun: true,
                question: 'My question',
            })

            threadLogic = maxThreadLogic({
                panelId: SIDE_PANEL_PANEL_ID,
                conversationId: logic.values.frontendConversationId,
                conversation: null,
            })
            threadLogic.mount()

            await expectLogic(threadLogic).toMatchValues({
                agentMode: null,
            })
        })
    })

    describe('chatTitle selector', () => {
        it('returns the conversation title when the conversation has a title', async () => {
            useMocks({
                ...maxMocks,
                get: {
                    ...maxMocks.get,
                    '/api/environments/:team_id/conversations/': { results: [MOCK_CONVERSATION] },
                },
            })

            logic = maxLogic({ panelId: 'test' })
            logic.mount()

            // Wait for conversation history to load, then set conversationId
            await expectLogic(logic).toDispatchActions(['loadConversationHistorySuccess']).toFinishAllListeners()

            await expectLogic(logic, () => {
                logic.actions.setConversationId(MOCK_CONVERSATION_ID)
            }).toMatchValues({
                chatTitle: MOCK_CONVERSATION.title,
            })
        })

        it('returns "New chat" when there is a conversationId but no matching conversation in history', async () => {
            logic = maxLogic({ panelId: 'test' })
            logic.mount()

            await expectLogic(logic, () => {
                logic.actions.setConversationId('unknown-id')
            }).toMatchValues({
                chatTitle: 'New chat',
            })
        })

        it('returns "Chat history" when conversation history is visible', async () => {
            logic = maxLogic({ panelId: 'test' })
            logic.mount()

            await expectLogic(logic, () => {
                logic.actions.toggleConversationHistory(true)
            }).toMatchValues({
                chatTitle: 'Chat history',
            })
        })

        it('returns null when there is no conversationId and history is not visible', async () => {
            logic = maxLogic({ panelId: 'test' })
            logic.mount()

            await expectLogic(logic).toMatchValues({
                conversationId: null,
                conversationHistoryVisible: false,
                chatTitle: null,
            })
        })
    })

    describe('breadcrumbs', () => {
        it('shows "New chat" as the first breadcrumb name when no conversationId is set', async () => {
            logic = maxLogic({ panelId: 'test' })
            logic.mount()

            await expectLogic(logic).toMatchValues({
                conversationId: null,
            })

            const breadcrumbs = logic.values.breadcrumbs
            expect(breadcrumbs[0].name).toBe('New chat')
        })

        it('shows "AI" as the first breadcrumb name and chat title in second breadcrumb when conversationId is set', async () => {
            useMocks({
                ...maxMocks,
                get: {
                    ...maxMocks.get,
                    '/api/environments/:team_id/conversations/': { results: [MOCK_CONVERSATION] },
                },
            })

            logic = maxLogic({ panelId: 'test' })
            logic.mount()

            // Wait for conversation history to load, then set conversationId
            await expectLogic(logic).toDispatchActions(['loadConversationHistorySuccess']).toFinishAllListeners()

            logic.actions.setConversationId(MOCK_CONVERSATION_ID)

            const breadcrumbs = logic.values.breadcrumbs
            expect(breadcrumbs[0].name).toBe('AI')
            expect(breadcrumbs[1].name).toBe(MOCK_CONVERSATION.title)
        })
    })

    describe('conversation merging', () => {
        const detailedConversation: ConversationDetail = {
            ...MOCK_CONVERSATION,
            messages: [],
            has_unsupported_content: true,
            agent_mode: AgentMode.Research,
            is_sandbox: true,
            pending_approvals: [
                {
                    proposal_id: 'approval-1',
                    decision_status: 'pending',
                    tool_name: 'dangerous_tool',
                    preview: 'Preview',
                    payload: {},
                },
            ],
        }

        it('preserves detail-only fields when a summary conversation refreshes an existing full conversation', () => {
            const merged = mergeConversations(
                {
                    ...MOCK_CONVERSATION,
                    title: 'Updated title',
                    updated_at: '2026-04-01T12:00:00Z',
                },
                detailedConversation
            )

            expect(merged).toEqual({
                ...detailedConversation,
                title: 'Updated title',
                updated_at: '2026-04-01T12:00:00Z',
            })
        })

        it('preserves detail-only fields when conversation history is refreshed from list results', () => {
            const mergedHistory = mergeConversationHistory([detailedConversation], {
                ...MOCK_CONVERSATION,
                title: 'Updated title',
                updated_at: '2026-04-01T12:00:00Z',
            })

            expect(mergedHistory).toEqual([
                {
                    ...detailedConversation,
                    title: 'Updated title',
                    updated_at: '2026-04-01T12:00:00Z',
                },
            ])
        })

        it('replaces cached detail fields when a full conversation response is loaded', () => {
            const merged = mergeConversations(
                {
                    ...MOCK_CONVERSATION,
                    messages: [],
                    has_unsupported_content: false,
                    agent_mode: AgentMode.ProductAnalytics,
                    is_sandbox: false,
                    pending_approvals: [],
                },
                detailedConversation
            )

            expect(merged).toEqual({
                ...MOCK_CONVERSATION,
                messages: [],
                has_unsupported_content: false,
                agent_mode: AgentMode.ProductAnalytics,
                is_sandbox: false,
                pending_approvals: [],
            })
        })
    })

    describe('suggestion typewriter', () => {
        const SUGGESTION = { content: 'What is the retention in the last two weeks?' }

        beforeEach(() => {
            jest.useFakeTimers()
            logic = maxLogic({ panelId: 'test' })
            logic.mount()
        })

        afterEach(() => {
            jest.useRealTimers()
        })

        it('holds the whole suggestion while the composer still shows a prefix', () => {
            logic.actions.runSuggestion(SUGGESTION)

            // The composer is mid-animation, so a send right now would carry this prefix. Keeping the
            // whole suggestion is what lets the send substitute it.
            expect(logic.values.question).toBe('W')
            expect(logic.values.typingSuggestion).toBe(SUGGESTION.content)
        })

        it('sends the whole suggestion once the animation finishes', async () => {
            await expectLogic(logic, () => {
                logic.actions.runSuggestion(SUGGESTION)
                jest.advanceTimersByTime(60000)
            }).toDispatchActions([
                (action: any) =>
                    action.type === logic.actionTypes.askMax && action.payload.prompt === SUGGESTION.content,
            ])

            expect(logic.values.typingSuggestion).toBeNull()
        })

        it('stops the animation when the user types over it', () => {
            logic.actions.runSuggestion(SUGGESTION)
            logic.actions.setQuestion('my own question')

            // The user's input wins: no pending send, and the animation stops writing over them.
            expect(logic.values.typingSuggestion).toBeNull()
            jest.advanceTimersByTime(60000)
            expect(logic.values.question).toBe('my own question')
        })

        it('leaves a fill-in suggestion for the user to complete instead of sending it', async () => {
            await expectLogic(logic, () => {
                logic.actions.runSuggestion({
                    content: 'Tell me about feature flag',
                    requiresUserInput: true,
                    hint: 'insert feature flag name',
                })
                jest.advanceTimersByTime(60000)
            }).toNotHaveDispatchedActions(['askMax'])

            expect(logic.values.question).toBe('Tell me about feature flag ')
            expect(logic.values.fillInHint).toBe('insert feature flag name')
            expect(logic.values.typingSuggestion).toBeNull()
        })
    })
})