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.

34.9 KB
Raw Blame
import { MOCK_TEAM_ID } from 'lib/api.mock'

import { cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react'
import { BindLogic } from 'kea'
import { expectLogic } from 'kea-test-utils'

import api from 'lib/api'
import { parseMarkdownNotebook } from 'lib/components/MarkdownNotebook/markdown'
import { buildMarkdownNotebookContent, getMarkdownNotebookMarkdown } from 'scenes/notebooks/Notebook/markdownNotebookV2'
import { MarkdownNotebookV2 } from 'scenes/notebooks/Notebook/MarkdownNotebookV2Renderer'
import { NotebookLogicProps, notebookLogic } from 'scenes/notebooks/Notebook/notebookLogic'
import { NotebookType } from 'scenes/notebooks/types'

import { initKeaTests } from '~/test/init'
import { AccessControlLevel } from '~/types'

import {
    notebooksWidgetCancel,
    notebooksWidgetFrame,
    notebooksWidgetPin,
    notebooksWidgetSource,
    notebooksWidgetStatus,
    notebooksWidgetVersions,
} from 'products/notebooks/frontend/generated/api'
import type { WidgetStatusApi } from 'products/notebooks/frontend/generated/api.schemas'

import { notebookNodeGeneratedWidgetLogic } from './notebookNodeGeneratedWidgetLogic'
import { NotebookWidgetGenerationModal } from './NotebookWidgetGenerationModal'
import { NOTEBOOK_FRAME_KEY_PREFIX } from './widgetArtifactBridge'

jest.mock('scenes/notebooks/Notebook/migrations/migrate', () => {
    const actual = jest.requireActual('scenes/notebooks/Notebook/migrations/migrate')
    return { ...actual, migrate: jest.fn(async (notebook: unknown) => notebook) }
})

jest.mock('products/notebooks/frontend/generated/api', () => ({
    notebooksWidgetCancel: jest.fn(),
    notebooksWidgetFrame: jest.fn(),
    notebooksWidgetGenerate: jest.fn(),
    notebooksWidgetPin: jest.fn(),
    notebooksWidgetRevert: jest.fn(),
    notebooksWidgetSource: jest.fn(),
    notebooksWidgetStatus: jest.fn(),
    notebooksWidgetVersions: jest.fn(),
}))

jest.mock('react-intersection-observer', () => ({
    useInView: () => ({ ref: () => undefined, inView: true }),
}))

const SHORT_ID = 'generated-widget-progress'
const MARKDOWN = '<Widget showFilters showResults nodeId="globe" prompt="Render a globe" model="claude-sonnet-4-6" />'
const cachedNotebook = {
    id: 'notebook-id',
    short_id: SHORT_ID,
    title: 'Generated widget progress',
    content: buildMarkdownNotebookContent(MARKDOWN),
    text_content: MARKDOWN,
    version: 1,
    deleted: false,
    is_template: false,
    user_access_level: AccessControlLevel.Editor,
    created_at: '2026-08-27T12:00:00Z',
    created_by: null,
    last_modified_at: '2026-08-27T12:00:00Z',
    last_modified_by: null,
} as unknown as NotebookType
const logicProps: NotebookLogicProps = { shortId: SHORT_ID, mode: 'notebook' }

describe('NotebookNodeGeneratedWidget', () => {
    let logic: ReturnType<typeof notebookLogic.build>

    beforeEach(async () => {
        initKeaTests()
        jest.spyOn(api.notebooks, 'collabStream').mockResolvedValue(undefined as never)
        jest.spyOn(api.notebooks, 'get').mockResolvedValue(cachedNotebook)
        jest.spyOn(api.notebooks, 'markdownSave').mockImplementation(async (_shortId, notebook) => ({
            ...cachedNotebook,
            ...notebook,
            version: notebook.version + 1,
        }))
        jest.mocked(notebooksWidgetStatus).mockResolvedValue({
            lifecycle_status: 'generating',
            error_detail: null,
            artifact_url: null,
            frame_names: [],
            input_bindings: {},
            input_contract: [],
            current_version_id: '00000000-0000-0000-0000-000000000002',
            pinned_version_id: null,
            widget_id: '00000000-0000-0000-0000-000000000003',
            instance_id: '00000000-0000-0000-0000-000000000004',
            has_versions: true,
            active_job: {
                id: '00000000-0000-0000-0000-000000000001',
                status: 'generating',
                phase: 'generating_source',
                model: 'claude-sonnet-4-6',
                created_at: '2026-08-27T12:00:00Z',
                started_at: '2026-08-27T12:00:00Z',
            },
            security_review: null,
            is_reusable: false,
            build_hash: null,
        })
        jest.mocked(notebooksWidgetVersions).mockResolvedValue({
            results: [],
            count: 0,
            next: null,
            previous: null,
            next_offset: null,
        })

        logic = notebookLogic(logicProps)
        logic.mount()
        logic.actions.loadNotebook()
        await expectLogic(logic).toDispatchActions(['loadNotebookSuccess']).toFinishAllListeners()
        logic.actions.setEditable(true)
    })

    afterEach(() => {
        cleanup()
        logic?.unmount()
        jest.restoreAllMocks()
    })

    it('shows generation progress only in filters when filters and results are open', async () => {
        render(
            <BindLogic logic={notebookLogic} props={logicProps}>
                <MarkdownNotebookV2 />
            </BindLogic>
        )

        expect(screen.getByText('Widget')).toBeTruthy()
        await waitFor(() => expect(screen.getAllByText('Regenerating widget…')).toHaveLength(1))
    })

    it('keeps a markdown widget identity when its instructions are edited', async () => {
        const markdown =
            '<Widget showFilters title="Hourly chart" prompt="Plot hourly totals" model="claude-sonnet-5" />'
        const originalId = parseMarkdownNotebook(markdown).nodes[0].id
        logic.unmount()
        const editProps = { ...logicProps, shortId: 'widget-identity-edit' }
        const notebook = {
            ...cachedNotebook,
            short_id: editProps.shortId,
            content: buildMarkdownNotebookContent(markdown),
        }
        jest.mocked(api.notebooks.get).mockResolvedValue(notebook)
        jest.spyOn(api.notebooks, 'update').mockResolvedValue(notebook)
        jest.mocked(notebooksWidgetStatus).mockResolvedValue({
            lifecycle_status: 'awaiting_generation',
            has_versions: false,
            current_version_id: null,
            active_job: null,
            artifact_url: null,
            error_detail: null,
            frame_names: [],
            input_bindings: {},
            input_contract: [],
            pinned_version_id: null,
            is_reusable: false,
            widget_id: null,
            instance_id: null,
            security_review: null,
            build_hash: null,
        })
        logic = notebookLogic(editProps)
        logic.mount()
        logic.actions.loadNotebook()
        await expectLogic(logic).toDispatchActions(['loadNotebookSuccess']).toFinishAllListeners()
        logic.actions.setEditable(true)
        render(
            <BindLogic logic={notebookLogic} props={editProps}>
                <MarkdownNotebookV2 />
            </BindLogic>
        )

        fireEvent.change(await screen.findByLabelText('Instructions'), { target: { value: 'Plot daily totals' } })

        await waitFor(() => {
            const node = parseMarkdownNotebook(getMarkdownNotebookMarkdown(logic.values.content)).nodes.find(
                (node) => node.type === 'component'
            )
            expect(node?.type === 'component' && node.props).toEqual(
                expect.objectContaining({ nodeId: originalId, prompt: 'Plot daily totals' })
            )
        })
    })

    it('renders without crashing when the markdown tag has a non-string prompt or unknown model', async () => {
        logic.unmount()
        const notebookWithMalformedTag = {
            ...cachedNotebook,
            // A valueless `prompt` attribute parses to boolean true, and the model is an unsupported string.
            content: buildMarkdownNotebookContent(
                '<Widget showResults nodeId="globe" prompt model="not-a-real-model" />'
            ),
        }
        jest.mocked(api.notebooks.get).mockResolvedValue(notebookWithMalformedTag)
        logic = notebookLogic(logicProps)
        logic.mount()
        logic.actions.loadNotebook()
        await expectLogic(logic).toDispatchActions(['loadNotebookSuccess']).toFinishAllListeners()
        logic.actions.setEditable(true)

        render(
            <BindLogic logic={notebookLogic} props={logicProps}>
                <MarkdownNotebookV2 />
            </BindLogic>
        )

        expect(await screen.findByText('Regenerating widget…')).toBeTruthy()
    })

    it('does not offer initial generation in the settings panel while status is still loading', async () => {
        // The status request never resolves, so `status` stays null through the render.
        jest.mocked(notebooksWidgetStatus).mockImplementation(() => new Promise(() => {}))

        render(
            <BindLogic logic={notebookLogic} props={logicProps}>
                <MarkdownNotebookV2 />
            </BindLogic>
        )

        expect(await screen.findByText('Widget')).toBeTruthy()
        // Before the first status response the panel must not present the initial form, or an
        // editor could start a job that the backend turns into a regeneration.
        expect(screen.queryByText('Generate widget')).toBeNull()
        expect(screen.queryByText('Instructions')).toBeNull()
    })

    it('shows cancellation errors while initial generation is still running', async () => {
        jest.mocked(notebooksWidgetCancel).mockRejectedValue(new Error('Cancel request failed'))

        render(
            <BindLogic logic={notebookLogic} props={logicProps}>
                <MarkdownNotebookV2 />
            </BindLogic>
        )

        fireEvent.click(await screen.findByText('Cancel'))

        expect(await screen.findByText('Cancel request failed')).toBeTruthy()
    })

    it('shows a generation failure inside the generation modal', async () => {
        const generationModalLogicProps = {
            projectId: MOCK_TEAM_ID,
            notebookShortId: SHORT_ID,
            nodeId: 'globe',
            prompt: 'Render a globe',
            model: 'claude-sonnet-4-6' as const,
            isEditable: true,
            persistNotebook: async (): Promise<void> => undefined,
            getContent: () => null,
        }
        const widgetLogic = notebookNodeGeneratedWidgetLogic(generationModalLogicProps)
        widgetLogic.mount()
        await expectLogic(widgetLogic).toFinishAllListeners()
        widgetLogic.actions.openGenerationModal('improve')
        widgetLogic.actions.generationFailed('The widget could not be generated.')

        render(<NotebookWidgetGenerationModal logicProps={generationModalLogicProps} />)

        // A failed generation keeps the modal open, so the reason must be visible inside it.
        expect(await screen.findByText('The widget could not be generated.')).toBeTruthy()
        widgetLogic.unmount()
    })

    it.each(['showFilters', 'showFilters showResults'])(
        'keeps version controls, publishing, and source available with %s',
        async (panels) => {
            logic.actions.setLocalContent(
                buildMarkdownNotebookContent(`<Widget ${panels} prompt="Render a table" inputs="rows" />`)
            )
            const versionId = '00000000-0000-0000-0000-000000000002'
            const readyStatus: WidgetStatusApi = {
                lifecycle_status: 'ready',
                error_detail: null,
                artifact_url: 'https://example.com/widget.html',
                frame_names: [],
                input_bindings: {},
                input_contract: [],
                current_version_id: versionId,
                pinned_version_id: null,
                widget_id: '00000000-0000-0000-0000-000000000003',
                instance_id: '00000000-0000-0000-0000-000000000004',
                has_versions: true,
                active_job: null,
                security_review: null,
                is_reusable: false,
                build_hash: 'a'.repeat(64),
            }
            jest.mocked(notebooksWidgetStatus).mockResolvedValue(readyStatus)
            jest.mocked(notebooksWidgetPin).mockImplementation(async (_project, _notebook, _node, request) => {
                const nextStatus = { ...readyStatus, pinned_version_id: request.version_id ?? null }
                jest.mocked(notebooksWidgetStatus).mockResolvedValue(nextStatus)
                return nextStatus
            })
            jest.mocked(notebooksWidgetVersions).mockResolvedValue({
                results: [
                    {
                        id: versionId,
                        parent_version_id: null,
                        version: 1,
                        version_operation: 'initial',
                        prompt_delta: 'Render a globe',
                        effective_prompt: 'Render a globe',
                        model: 'claude-sonnet-4-6',
                        created_at: '2026-08-27T12:00:00Z',
                        build_status: 'ready',
                        artifact_url: 'https://example.com/widget.html',
                        frame_names: [],
                        is_current: true,
                        security_review: null,
                        build_hash: 'a'.repeat(64),
                    },
                ],
                count: 1,
                next: null,
                previous: null,
                next_offset: null,
            })
            jest.mocked(notebooksWidgetSource).mockResolvedValue({
                source: 'export default function Widget() {}',
            })
            render(
                <BindLogic logic={notebookLogic} props={logicProps}>
                    <MarkdownNotebookV2 />
                </BindLogic>
            )

            await screen.findByText('Improve…')
            const widgetNodeId = jest.mocked(notebooksWidgetStatus).mock.calls.at(-1)![2]
            expect(await screen.findByText('Following latest version')).toBeTruthy()
            expect(screen.queryByText('Follow latest version')).toBeNull()
            expect(getMarkdownNotebookMarkdown(logic.values.content)).toContain('inputs="rows"')
            fireEvent.click(screen.getByText('Pin this version'))
            await waitFor(() =>
                expect(getMarkdownNotebookMarkdown(logic.values.content)).toContain(`version="${versionId}"`)
            )
            expect(getMarkdownNotebookMarkdown(logic.values.content)).toContain(`nodeId="${widgetNodeId}"`)
            expect(getMarkdownNotebookMarkdown(logic.values.content)).toContain('inputs="rows"')
            fireEvent.click(await screen.findByText('Follow latest version'))
            await waitFor(() => expect(getMarkdownNotebookMarkdown(logic.values.content)).not.toContain('version='))
            expect(getMarkdownNotebookMarkdown(logic.values.content)).toContain(`nodeId="${widgetNodeId}"`)
            expect(getMarkdownNotebookMarkdown(logic.values.content)).toContain('inputs="rows"')
            expect(await screen.findByText('Following latest version')).toBeTruthy()
            fireEvent.click(screen.getByText('Make reusable…'))
            expect(await screen.findAllByText('Make widget reusable')).toHaveLength(1)
            fireEvent.click(screen.getByText('Cancel'))
            const improveButton = await screen.findByText('Improve…')
            const actionContainer = improveButton.closest('button')!.parentElement!
            const actionButtons = [
                improveButton,
                within(actionContainer).getByText('Regenerate…'),
                within(actionContainer).getByText('View source'),
                within(actionContainer).getByText('Reload preview'),
            ]
            actionButtons.slice(0, -1).forEach((button, index) => {
                expect(
                    button.compareDocumentPosition(actionButtons[index + 1]) & Node.DOCUMENT_POSITION_FOLLOWING
                ).toBeTruthy()
            })
            jest.mocked(notebooksWidgetStatus).mockClear()
            fireEvent.click(actionButtons[3])
            await waitFor(() =>
                expect(notebooksWidgetStatus).toHaveBeenCalledWith(
                    String(MOCK_TEAM_ID),
                    SHORT_ID,
                    widgetNodeId,
                    expect.objectContaining({ signal: expect.anything() })
                )
            )

            fireEvent.click(actionButtons[2])

            await waitFor(() =>
                expect(notebooksWidgetSource).toHaveBeenCalledWith(
                    String(MOCK_TEAM_ID),
                    SHORT_ID,
                    widgetNodeId,
                    { version_id: versionId },
                    expect.objectContaining({ signal: expect.anything() })
                )
            )
            expect(screen.getByText('Widget source')).toBeTruthy()
            expect(screen.getByText('What would you like to change?')).toBeTruthy()
            expect(screen.getByText('Build changes')).toBeTruthy()
        }
    )

    it('shows security findings before mounting the exact build', async () => {
        const versionId = '00000000-0000-0000-0000-000000000005'
        const buildHash = 'b'.repeat(64)
        const securityReview = {
            severity: 'high' as const,
            summary: 'The widget may send notebook data to another window.',
            findings: [
                {
                    severity: 'high' as const,
                    title: 'Notebook data may leave the preview',
                    details: 'The source sends rows to the parent window without using the approved bridge.',
                },
            ],
            model: 'claude-haiku-4-5',
            review_version: '1',
            reviewed_at: '2026-08-31T10:00:00Z',
        }
        jest.mocked(notebooksWidgetStatus).mockResolvedValue({
            lifecycle_status: 'ready',
            error_detail: null,
            artifact_url: 'https://example.com/untrusted-widget.html',
            frame_names: [],
            input_bindings: {},
            input_contract: [],
            current_version_id: versionId,
            pinned_version_id: null,
            widget_id: '00000000-0000-0000-0000-000000000006',
            instance_id: '00000000-0000-0000-0000-000000000007',
            has_versions: true,
            active_job: null,
            security_review: securityReview,
            is_reusable: false,
            build_hash: buildHash,
        })
        jest.mocked(notebooksWidgetVersions).mockResolvedValue({
            results: [
                {
                    id: versionId,
                    parent_version_id: null,
                    version: 1,
                    version_operation: 'initial',
                    prompt_delta: 'Render a globe',
                    effective_prompt: 'Render a globe',
                    model: 'claude-sonnet-4-6',
                    created_at: '2026-08-27T12:00:00Z',
                    build_status: 'ready',
                    artifact_url: 'https://example.com/untrusted-widget.html',
                    frame_names: [],
                    is_current: true,
                    security_review: securityReview,
                    build_hash: buildHash,
                },
            ],
            count: 1,
            next: null,
            previous: null,
            next_offset: null,
        })
        const { container } = render(
            <BindLogic logic={notebookLogic} props={logicProps}>
                <MarkdownNotebookV2 />
            </BindLogic>
        )

        await screen.findByText('Security review found potential issues')
        expect(screen.getByText('Notebook data may leave the preview')).toBeTruthy()
        expect(screen.getByText('Run widget anyway')).toBeTruthy()
        await waitFor(() => expect(container.querySelector('[data-attr="notebook-widget-run"]')).not.toBeNull())
        const runButton = container.querySelector('[data-attr="notebook-widget-run"]')!
        expect(container.querySelector('iframe')).toBeNull()

        fireEvent.click(runButton)

        await waitFor(() => expect(container.querySelector('[data-attr="notebook-widget-run"]')).toBeNull())
        await waitFor(() => expect(container.querySelector('iframe')).not.toBeNull())
        expect(container.querySelector('iframe')?.getAttribute('src')).toBe(
            'https://example.com/untrusted-widget.html?sandbox=allow-pointer-lock#theme=light'
        )
        expect(container.querySelector('iframe')?.getAttribute('title')).toBe('Widget')
    })

    it('sends only contract columns to a reusable widget after applying its mapping', async () => {
        jest.spyOn(HTMLIFrameElement.prototype, 'contentWindow', 'get').mockReturnValue(window)
        jest.spyOn(api.hog, 'create').mockResolvedValue({ bytecode: ['_H', 1, 32, 'rows', 1, 1, 38] } as never)
        jest.mocked(notebooksWidgetStatus).mockResolvedValue({
            lifecycle_status: 'ready',
            error_detail: null,
            artifact_url: 'https://example.com/revenue-widget.html',
            frame_names: ['revenue'],
            input_bindings: {
                revenue: { source: 'orders', hog: 'return rows' },
            },
            input_contract: [
                {
                    slot: 'revenue',
                    sourceName: 'orders',
                    schemaHash: 'test-schema',
                    columns: [
                        { name: 'plan', type: 'string' },
                        { name: 'revenue', type: 'float64' },
                    ],
                },
            ],
            current_version_id: '00000000-0000-0000-0000-000000000014',
            pinned_version_id: null,
            widget_id: '00000000-0000-0000-0000-000000000015',
            instance_id: '00000000-0000-0000-0000-000000000016',
            has_versions: true,
            active_job: null,
            security_review: null,
            is_reusable: true,
            build_hash: 'd'.repeat(64),
        })
        jest.mocked(notebooksWidgetFrame).mockResolvedValue({
            name: 'revenue',
            runId: '00000000-0000-0000-0000-000000000017',
            columns: [
                { name: 'plan', type: 'string' },
                { name: 'revenue', type: 'float64' },
                { name: 'internal_note', type: 'string' },
            ],
            rows: [['Enterprise', 500, 'Private note']],
            totalRowCount: 1,
            includedRowCount: 1,
            offset: 0,
            nextOffset: null,
            truncated: false,
        })
        const port = {
            postMessage: jest.fn(),
            addEventListener: jest.fn(),
            removeEventListener: jest.fn(),
            start: jest.fn(),
            close: jest.fn(),
        }
        const { container } = render(
            <BindLogic logic={notebookLogic} props={logicProps}>
                <MarkdownNotebookV2 />
            </BindLogic>
        )
        await waitFor(() => expect(container.querySelector('[data-attr="notebook-widget-run"]')).not.toBeNull())
        fireEvent.click(container.querySelector('[data-attr="notebook-widget-run"]')!)
        const iframe = (await screen.findByTitle('Widget')) as HTMLIFrameElement
        fireEvent(
            window,
            new MessageEvent('message', {
                data: { channel: 'posthog-canvas', type: 'notebook-connect' },
                source: iframe.contentWindow,
                ports: [port as unknown as MessagePort],
            })
        )
        const route = port.addEventListener.mock.calls[0][1] as (event: { data: unknown }) => Promise<void>

        await route({
            data: {
                channel: 'posthog-canvas',
                type: 'data-request',
                id: 'revenue-page',
                method: 'stateGet',
                payload: { key: `${NOTEBOOK_FRAME_KEY_PREFIX}revenue:0:100` },
            },
        })

        expect(port.postMessage).toHaveBeenCalledWith({
            channel: 'posthog-canvas',
            type: 'data-response',
            id: 'revenue-page',
            ok: true,
            result: expect.objectContaining({
                columns: [
                    { name: 'plan', type: 'unknown' },
                    { name: 'revenue', type: 'unknown' },
                ],
                rows: [['Enterprise', 500]],
            }),
        })
    })

    it.each([
        {
            label: 'runs a green widget immediately when it has no data access',
            frameNames: [],
            autoRuns: true,
            isReusable: true,
        },
        {
            label: 'requires consent for a green widget with dataframe access',
            frameNames: ['events_df'],
            autoRuns: false,
            isReusable: false,
        },
    ])('$label', async ({ frameNames, autoRuns, isReusable }) => {
        const versionId = '00000000-0000-0000-0000-000000000008'
        const buildHash = 'c'.repeat(64)
        const securityReview = {
            severity: 'none' as const,
            summary: 'No security issues found.',
            findings: [],
            model: 'claude-haiku-4-5',
            review_version: '1',
            reviewed_at: '2026-08-31T10:00:00Z',
        }
        jest.mocked(notebooksWidgetStatus).mockResolvedValue({
            lifecycle_status: 'ready',
            error_detail: null,
            artifact_url: 'https://example.com/reviewed-widget.html',
            frame_names: frameNames,
            input_bindings: {},
            input_contract: [],
            current_version_id: versionId,
            pinned_version_id: null,
            widget_id: '00000000-0000-0000-0000-000000000009',
            instance_id: '00000000-0000-0000-0000-000000000010',
            has_versions: true,
            active_job: null,
            security_review: securityReview,
            is_reusable: isReusable,
            build_hash: buildHash,
        })
        jest.mocked(notebooksWidgetSource).mockResolvedValue({ source: 'export default function Widget() {}' })
        jest.mocked(notebooksWidgetVersions).mockResolvedValue({
            results: [
                {
                    id: versionId,
                    parent_version_id: null,
                    version: 1,
                    version_operation: 'initial',
                    prompt_delta: 'Render a globe',
                    effective_prompt: 'Render a globe',
                    model: 'claude-sonnet-4-6',
                    created_at: '2026-08-31T10:00:00Z',
                    build_status: 'ready',
                    artifact_url: 'https://example.com/reviewed-widget.html',
                    frame_names: frameNames,
                    is_current: true,
                    security_review: securityReview,
                    build_hash: buildHash,
                },
            ],
            count: 1,
            next: null,
            previous: null,
            next_offset: null,
        })
        const { container } = render(
            <BindLogic logic={notebookLogic} props={logicProps}>
                <MarkdownNotebookV2 />
            </BindLogic>
        )

        await screen.findByLabelText('More actions')
        await waitFor(() => expect(container.querySelector('iframe') !== null).toBe(autoRuns))
        expect(screen.queryByText('Review this widget before running it') !== null).toBe(!autoRuns)
        expect(container.querySelector('[data-attr="notebook-widget-run"]') !== null).toBe(!autoRuns)
        expect(container.querySelector('iframe')?.getAttribute('src') ?? null).toBe(
            autoRuns ? 'https://example.com/reviewed-widget.html?sandbox=allow-pointer-lock#theme=light' : null
        )
        const results = container.querySelector('.MarkdownNotebook__component-panel--results')!
        if (autoRuns) {
            expect(within(results as HTMLElement).queryByText('View source')).toBeNull()
            expect(
                within(results as HTMLElement).queryByText('Automated review: No potential issues flagged')
            ).toBeNull()
            expect(within(results as HTMLElement).queryByText(`Build ${buildHash.slice(0, 12)}`)).toBeNull()
        }
        expect(screen.queryByText('Open reusable widget')).toBeNull()
        fireEvent.click(screen.getByLabelText('More actions'))
        fireEvent.click(screen.getByText('Add to dashboard'))
        expect(await screen.findByText('Add widget to dashboard')).toBeTruthy()
        fireEvent.click(screen.getByText('Cancel'))
        fireEvent.click(screen.getByLabelText('More actions'))
        expect(screen.queryByText('Open reusable widget') !== null).toBe(isReusable)
        if (isReusable) {
            expect(screen.getByText('Open reusable widget').closest('a')?.getAttribute('href')).toContain(
                '/notebooks/widgets/00000000-0000-0000-0000-000000000009'
            )
        }
        const sourceMenuItem = document.querySelector('[role="menuitem"][data-attr="notebook-widget-view-source"]')!
        expect(sourceMenuItem).not.toBeNull()
        expect(screen.getAllByText('Automated review: No potential issues flagged')).toHaveLength(autoRuns ? 1 : 2)
        expect(screen.getAllByText(`Build ${buildHash.slice(0, 12)}`)).toHaveLength(autoRuns ? 1 : 2)
        fireEvent.click(sourceMenuItem)
        await waitFor(() =>
            expect(notebooksWidgetSource).toHaveBeenCalledWith(
                String(MOCK_TEAM_ID),
                SHORT_ID,
                'globe',
                { version_id: versionId },
                expect.objectContaining({ signal: expect.anything() })
            )
        )
        expect(screen.getAllByText('Widget source')).toHaveLength(1)
    })

    it('opens regeneration from a failed preview when the filters are closed', async () => {
        const versionId = '00000000-0000-0000-0000-000000000011'
        jest.mocked(notebooksWidgetStatus).mockResolvedValue({
            lifecycle_status: 'failed',
            error_detail: 'The widget build failed.',
            artifact_url: null,
            frame_names: [],
            input_bindings: {},
            input_contract: [],
            current_version_id: versionId,
            pinned_version_id: null,
            widget_id: '00000000-0000-0000-0000-000000000012',
            instance_id: '00000000-0000-0000-0000-000000000013',
            has_versions: true,
            active_job: null,
            security_review: null,
            is_reusable: false,
            build_hash: null,
        })
        jest.mocked(notebooksWidgetVersions).mockResolvedValue({
            results: [
                {
                    id: versionId,
                    parent_version_id: null,
                    version: 1,
                    version_operation: 'initial',
                    prompt_delta: 'Render a globe',
                    effective_prompt: 'Render a globe',
                    model: 'claude-sonnet-4-6',
                    created_at: '2026-08-31T10:00:00Z',
                    build_status: 'failed',
                    artifact_url: null,
                    frame_names: [],
                    is_current: true,
                    security_review: null,
                    build_hash: null,
                },
            ],
            count: 1,
            next: null,
            previous: null,
            next_offset: null,
        })
        logic.unmount()
        const notebookWithoutFilters = {
            ...cachedNotebook,
            content: buildMarkdownNotebookContent(
                '<Widget showResults nodeId="globe" prompt="Render a globe" model="claude-sonnet-4-6" />'
            ),
        }
        jest.mocked(api.notebooks.get).mockResolvedValue(notebookWithoutFilters)
        logic = notebookLogic(logicProps)
        logic.mount()
        logic.actions.loadNotebook()
        await expectLogic(logic).toDispatchActions(['loadNotebookSuccess']).toFinishAllListeners()
        logic.actions.setEditable(true)

        render(
            <BindLogic logic={notebookLogic} props={logicProps}>
                <MarkdownNotebookV2 />
            </BindLogic>
        )

        fireEvent.click(await screen.findByText('Regenerate…'))

        expect(await screen.findByText('Regenerate widget')).toBeTruthy()
        expect(screen.getByDisplayValue('Render a globe')).toBeTruthy()
    })

    it('keeps source available when the selected version has no preview', async () => {
        const versionId = '00000000-0000-0000-0000-000000000014'
        jest.mocked(notebooksWidgetStatus).mockResolvedValue({
            lifecycle_status: 'ready',
            error_detail: null,
            artifact_url: null,
            frame_names: [],
            input_bindings: {},
            input_contract: [],
            current_version_id: versionId,
            pinned_version_id: null,
            widget_id: '00000000-0000-0000-0000-000000000015',
            instance_id: '00000000-0000-0000-0000-000000000016',
            has_versions: true,
            active_job: null,
            security_review: null,
            is_reusable: false,
            build_hash: null,
        })
        jest.mocked(notebooksWidgetSource).mockResolvedValue({
            source: 'export default function Widget() {}',
        })
        logic.unmount()
        const notebookWithoutFilters = {
            ...cachedNotebook,
            content: buildMarkdownNotebookContent(
                '<Widget showResults nodeId="globe" prompt="Render a globe" model="claude-sonnet-4-6" />'
            ),
        }
        jest.mocked(api.notebooks.get).mockResolvedValue(notebookWithoutFilters)
        logic = notebookLogic(logicProps)
        logic.mount()
        logic.actions.loadNotebook()
        await expectLogic(logic).toDispatchActions(['loadNotebookSuccess']).toFinishAllListeners()
        logic.actions.setEditable(true)

        render(
            <BindLogic logic={notebookLogic} props={logicProps}>
                <MarkdownNotebookV2 />
            </BindLogic>
        )

        const unavailablePreview = await screen.findByText(/preview is no longer available/)
        fireEvent.click(screen.getByLabelText('More actions'))
        expect(screen.queryByText('Add to dashboard')).toBeNull()
        fireEvent.click(screen.getByLabelText('More actions'))
        fireEvent.click(within(unavailablePreview.parentElement!).getByText('View source'))

        await waitFor(() =>
            expect(notebooksWidgetSource).toHaveBeenCalledWith(
                String(MOCK_TEAM_ID),
                SHORT_ID,
                'globe',
                { version_id: versionId },
                expect.objectContaining({ signal: expect.anything() })
            )
        )
        expect(screen.getByText('Widget source')).toBeTruthy()
    })

    it('does not load generated widgets in publicly shared notebooks', async () => {
        logic.unmount()
        jest.mocked(notebooksWidgetStatus).mockClear()
        const sharedLogicProps: NotebookLogicProps = { ...logicProps, cachedNotebook }
        logic = notebookLogic(sharedLogicProps)
        logic.mount()
        logic.actions.loadNotebook()
        await expectLogic(logic).toDispatchActions(['loadNotebookSuccess']).toFinishAllListeners()
        const statusCallCount = jest.mocked(notebooksWidgetStatus).mock.calls.length

        render(
            <BindLogic logic={notebookLogic} props={sharedLogicProps}>
                <MarkdownNotebookV2 />
            </BindLogic>
        )

        expect(await screen.findByText('Node cannot be rendered')).toBeTruthy()
        expect(notebooksWidgetStatus).toHaveBeenCalledTimes(statusCallCount)
    })
})