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.

50.8 KB
Raw Blame
import { deepEqual as equal } from 'fast-equals'
import {
    LogicWrapper,
    MakeLogicType,
    actions,
    afterMount,
    beforeUnmount,
    connect,
    kea,
    key,
    listeners,
    path,
    props,
    reducers,
    selectors,
} from 'kea'
import { loaders } from 'kea-loaders'
import { beforeUnload, router, urlToAction } from 'kea-router'

import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
import { accessLevelSatisfied, toAccessControlLevel } from 'lib/utils/accessControlUtils'
import { copyToClipboard } from 'lib/utils/copyToClipboard'
import { addProjectIdIfMissing } from 'lib/utils/kea-router'
import { databaseTableListLogic } from 'scenes/data-management/database/databaseTableListLogic'
import { insightsApi } from 'scenes/insights/utils/api'
import { teamLogic } from 'scenes/teamLogic'
import { urls } from 'scenes/urls'

import { refreshTreeItem } from '~/layout/panel-layout/ProjectTree/projectTreeLogic'
import { dataNodeLogic } from '~/queries/nodes/DataNode/dataNodeLogic'
import { isBIVisualizationNode } from '~/queries/schema/node-guards'
import { BIVisualizationNode } from '~/queries/schema/schema-business-intelligence'
import { ChartSettings, HogQLFilters, NodeKind, VisualizationNode } from '~/queries/schema/schema-general'
import { AccessControlLevel, AccessControlResourceType, ChartDisplayType } from '~/types'

import { validateMetricName } from 'products/data_catalog/frontend/common'
import { dataCatalogMetricsRetrieve } from 'products/data_catalog/frontend/generated/api'
import { warehouseSavedQueriesCreate } from 'products/data_warehouse/frontend/generated/api'
import { claimConnectionScope, releaseConnectionScope } from 'products/data_warehouse/frontend/shared/connectionScope'
import { connectionSelectorLogic } from 'products/data_warehouse/frontend/shared/logics/connectionSelectorLogic'
import {
    insightsCreate,
    insightsList,
    insightsPartialUpdate,
    insightsViewedCreate,
} from 'products/product_analytics/frontend/generated/api'
import { BIVisualizationNodeApi, InsightApi } from 'products/product_analytics/frontend/generated/api.schemas'

import type { BIConfig } from '../../../frontend/src/queries/schema/schema-business-intelligence'
import type { DataCatalogMetricApi } from '../../data_catalog/frontend/generated/api.schemas'
import type { DataWarehouseSavedQueryApi } from '../../data_warehouse/frontend/generated/api.schemas'
import type { ExternalDataSourceConnectionOptionApi } from '../../warehouse_sources/frontend/generated/api.schemas'
import { catalogMetricWorksheet } from './biCatalog'
import { captureBIEditorQueryRun, captureBIEditorQuerySaved, captureBIWorksheetAction } from './biEditorAnalytics'
import { biEditorLogic } from './biEditorLogic'
import {
    BIEditorView,
    DEFAULT_BI_CONFIG,
    buildBIQuery,
    mergeBIChartSettings,
    parseBIEditorState,
} from './biEditorTypes'
import type { BIQueryBuildResult } from './biEditorTypes'
import { mergeBITableSettings } from './biMeasureSettings'
import { applyBIDateRange, mergeBIQuerySource } from './biQueryFilters'
import { getBIVisualizationSource } from './biQueryResults'
import { getBIScatterAxisOptions } from './biScatter'

export interface BISceneLogicProps {
    tabId: string
}

export interface BIWorksheetSnapshot {
    worksheet: BIVisualizationNode
    name: string
}

export interface BIWorksheetHistory {
    past: BIWorksheetSnapshot[]
    present: BIWorksheetSnapshot | null
    future: BIWorksheetSnapshot[]
}

function normalizeWorksheetForComparison(query: unknown): unknown {
    return query && typeof query === 'object' && isBIVisualizationNode(query)
        ? JSON.parse(JSON.stringify({ ...query, source: { ...query.source, filters: query.source.filters ?? {} } }))
        : query
}

function emptyWorksheet(): BIVisualizationNode {
    return {
        kind: NodeKind.BIVisualizationNode,
        source: { kind: NodeKind.HogQLQuery, query: '' },
        config: { ...DEFAULT_BI_CONFIG, rows: [], columns: [], values: [], filters: [] },
        display: DEFAULT_BI_CONFIG.chartType,
    }
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface biSceneLogicValues {
    autoUpdate: boolean // biEditorLogic
    config: BIConfig // biEditorLogic
    generatedQuery: BIQueryBuildResult | null // biEditorLogic
    connectionOptions: ExternalDataSourceConnectionOptionApi[] | null // connectionSelectorLogic
    connectionOptionsLoading: boolean // connectionSelectorLogic
    connectionId: string | null // databaseTableListLogic
    currentTeamId: number | null // teamLogic
    agentUpdateConflict: boolean
    agentUpdateState: 'conflict' | 'error' | 'loading' | null
    canRedo: boolean
    canUndo: boolean
    catalogMetric: Awaited<ReturnType<typeof dataCatalogMetricsRetrieve>> | null
    catalogMetricLoading: boolean
    chartSettingsDefaults: ChartSettings | null
    copyDisabledReason: string | undefined
    dataNodeKey: string
    displayedQueryIsCurrent: boolean
    exportViewName: string
    exportViewOpen: boolean
    exportedView: Awaited<ReturnType<typeof warehouseSavedQueriesCreate>> | null
    exportedViewLoading: boolean
    hasUnsavedChanges: boolean
    history: BIWorksheetHistory
    insight: InsightApi | null
    insightLoading: boolean
    lastRunQuery: BIVisualizationNode | null
    loadError: string | null
    name: string
    saveDisabledReason: string | undefined
    sqlEditorUrl: string | null
    sqlPreviewOpen: boolean
    sqlPreviewQuery: BIVisualizationNode | null
    sqlPreviewVersion: 'current' | 'last_run'
    visualization: BIVisualizationNode
    worksheet: BIVisualizationNode
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface biSceneLogicActions {
    resetConfig: () => {
        value: true
    } // biEditorLogic
    restoreState: (state: import('./biEditorTypes').BIEditorState) => {
        state: import('./biEditorTypes').BIEditorState
    } // biEditorLogic
    runAfterChange: () => {
        value: true
    } // biEditorLogic
    setChartType: (chartType: ChartDisplayType) => {
        chartType: ChartDisplayType
    } // biEditorLogic
    cancelQuery: () => {
        value: true
    }
    clearInsight: () => {
        value: true
    }
    discardChanges: (syncUrl?: boolean) => {
        syncUrl: boolean
    }
    exportView: () => any
    exportViewFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    exportViewSuccess: (
        exportedView: DataWarehouseSavedQueryApi | null,
        payload?: any
    ) => {
        exportedView: DataWarehouseSavedQueryApi | null
        payload?: any
    }
    loadInsight: (shortId: string) => string
    loadInsightFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    loadInsightSuccess: (
        insight: InsightApi,
        payload?: string
    ) => {
        insight: InsightApi
        payload?: string
    }
    navigateHierarchy: (worksheet: BIVisualizationNode) => {
        worksheet: BIVisualizationNode
    }
    openCatalogMetric: (name: string) => string
    openCatalogMetricFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    openCatalogMetricSuccess: (
        catalogMetric: DataCatalogMetricApi,
        payload?: string
    ) => {
        catalogMetric: DataCatalogMetricApi
        payload?: string
    }
    openWorksheet: () => {
        value: true
    }
    pushHistory: (
        snapshot: BIWorksheetSnapshot,
        reset: boolean
    ) => {
        reset: boolean
        snapshot: BIWorksheetSnapshot
    }
    reconcileInsightFromAgent: () => {
        value: true
    }
    recordWorksheet: (reset?: any) => {
        reset: any
    }
    redo: () => {
        value: true
    }
    refreshInsightFromAgent: (targetId: unknown) => {
        targetId: unknown
    }
    restoreHistory: () => {
        value: true
    }
    restoreWorksheet: (worksheet: BIVisualizationNode) => {
        worksheet: BIVisualizationNode
    }
    runQuery: () => {
        value: true
    }
    saveInsight: (options?: { asCopy?: boolean }) => {
        asCopy?: boolean
    }
    saveInsightFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    saveInsightSuccess: (
        insight: InsightApi | null,
        payload?: {
            asCopy?: boolean
        }
    ) => {
        insight: InsightApi | null
        payload?: {
            asCopy?: boolean
        }
    }
    selectConnection: (connectionId: string | null) => {
        connectionId: string | null
    }
    setAgentUpdateState: (state: 'conflict' | 'error' | 'loading' | null) => {
        state: 'conflict' | 'error' | 'loading' | null
    }
    setChartSettings: (chartSettings: ChartSettings) => {
        chartSettings: ChartSettings
    }
    setChartSettingsDefaults: (defaults: ChartSettings | undefined) => {
        defaults: ChartSettings | undefined
    }
    setExportViewName: (name: string) => {
        name: string
    }
    setExportViewOpen: (open: boolean) => {
        open: boolean
    }
    setInsightFromAgent: (insight: InsightApi) => {
        insight: InsightApi
    }
    setLastRunQuery: (query: BIVisualizationNode | null) => {
        query: BIVisualizationNode | null
    }
    setName: (name: string) => {
        name: string
    }
    setScatterAxis: (
        axis: 'x' | 'y',
        column: string
    ) => {
        axis: 'x' | 'y'
        column: string
    }
    setSqlPreviewOpen: (open: boolean) => {
        open: boolean
    }
    setSqlPreviewVersion: (version: 'current' | 'last_run') => {
        version: 'current' | 'last_run'
    }
    setVisualization: (visualization: VisualizationNode) => {
        visualization: VisualizationNode
    }
    shareWorksheet: () => {
        value: true
    }
    syncWorksheetUrl: () => {
        value: true
    }
    undo: () => {
        value: true
    }
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface biSceneLogicMeta {
    key: string
    __keaTypeGenInternalSelectorTypes: {
        sqlPreviewQuery: (
            sqlPreviewVersion: 'current' | 'last_run',
            worksheet: BIVisualizationNode,
            lastRunQuery: BIVisualizationNode | null
        ) => BIVisualizationNode | null
        sqlEditorUrl: (sqlPreviewQuery: BIVisualizationNode | null) => string | null
        displayedQueryIsCurrent: (lastRunQuery: BIVisualizationNode | null, worksheet: BIVisualizationNode) => boolean
        canUndo: (history: BIWorksheetHistory) => boolean
        canRedo: (history: BIWorksheetHistory) => boolean
        copyDisabledReason: (generatedQuery: BIQueryBuildResult | null, name: string) => string | undefined
        dataNodeKey: (tabId: string) => string
        worksheet: (
            config: BIConfig,
            generatedQuery: BIQueryBuildResult | null,
            visualization: BIVisualizationNode,
            chartSettingsDefaults: ChartSettings | null
        ) => BIVisualizationNode
        hasUnsavedChanges: (worksheet: BIVisualizationNode, name: string, insight: InsightApi | null) => boolean
        saveDisabledReason: (
            generatedQuery: BIQueryBuildResult | null,
            insight: InsightApi | null,
            name: string,
            agentUpdateState: 'conflict' | 'error' | 'loading' | null
        ) => string | undefined
    }
}

export type biSceneLogicType = MakeLogicType<
    biSceneLogicValues,
    biSceneLogicActions,
    BISceneLogicProps,
    biSceneLogicMeta
>

export const biSceneLogic: LogicWrapper<biSceneLogicType> = kea<biSceneLogicType>([
    props({} as BISceneLogicProps),
    key((props) => props.tabId),
    path((key) => ['products', 'business_intelligence', 'biSceneLogic', key]),
    connect((props: BISceneLogicProps) => ({
        values: [
            teamLogic,
            ['currentTeamId'],
            biEditorLogic(props),
            ['config', 'generatedQuery', 'autoUpdate'],
            databaseTableListLogic,
            ['connectionId'],
            connectionSelectorLogic,
            ['connectionOptions', 'connectionOptionsLoading'],
        ],
        actions: [biEditorLogic(props), ['restoreState', 'runAfterChange', 'resetConfig', 'setChartType']],
    })),
    actions({
        recordWorksheet: (reset = false) => ({ reset }),
        pushHistory: (snapshot: BIWorksheetSnapshot, reset: boolean) => ({ snapshot, reset }),
        undo: true,
        redo: true,
        restoreHistory: true,
        restoreWorksheet: (worksheet: BIVisualizationNode) => ({ worksheet }),
        navigateHierarchy: (worksheet: BIVisualizationNode) => ({ worksheet }),
        setVisualization: (visualization: VisualizationNode) => ({ visualization }),
        setChartSettings: (chartSettings: ChartSettings) => ({ chartSettings }),
        setChartSettingsDefaults: (defaults: ChartSettings | undefined) => ({ defaults }),
        setScatterAxis: (axis: 'x' | 'y', column: string) => ({ axis, column }),
        setName: (name: string) => ({ name }),
        refreshInsightFromAgent: (targetId: unknown) => ({ targetId }),
        reconcileInsightFromAgent: true,
        setInsightFromAgent: (insight: InsightApi) => ({ insight }),
        setAgentUpdateState: (state: 'loading' | 'conflict' | 'error' | null) => ({ state }),
        runQuery: true,
        cancelQuery: true,
        setLastRunQuery: (query: BIVisualizationNode | null) => ({ query }),
        discardChanges: (syncUrl: boolean = true) => ({ syncUrl }),
        shareWorksheet: true,
        syncWorksheetUrl: true,
        openWorksheet: true,
        clearInsight: true,
        selectConnection: (connectionId: string | null) => ({ connectionId }),
        setExportViewName: (name: string) => ({ name }),
        setExportViewOpen: (open: boolean) => ({ open }),
        setSqlPreviewOpen: (open: boolean) => ({ open }),
        setSqlPreviewVersion: (version: 'current' | 'last_run') => ({ version }),
    }),
    loaders(({ values, actions, cache }) => ({
        catalogMetric: [
            null as Awaited<ReturnType<typeof dataCatalogMetricsRetrieve>> | null,
            {
                openCatalogMetric: async (name: string, breakpoint) => {
                    if (validateMetricName(name)) {
                        throw new Error('Invalid metric name')
                    }
                    const metric = await dataCatalogMetricsRetrieve(String(values.currentTeamId), name)
                    breakpoint()
                    if (!catalogMetricWorksheet(metric)) {
                        throw new Error(
                            'Explore in BI currently supports SQL metrics. Open this definition in the catalog.'
                        )
                    }
                    return metric
                },
            },
        ],
        insight: [
            null as InsightApi | null,
            {
                loadInsight: async (shortId: string, breakpoint) => {
                    const response = await insightsList(String(values.currentTeamId), {
                        short_id: shortId,
                        basic: true,
                    })
                    breakpoint()
                    const insight = response.results[0]
                    if (!insight || !isBIVisualizationNode(insight.query)) {
                        throw new Error('This insight is not a BI worksheet.')
                    }
                    return insight
                },
                saveInsight: async (options: { asCopy?: boolean } = {}) => {
                    const asCopy = options.asCopy ?? false
                    if (asCopy ? values.copyDisabledReason : values.saveDisabledReason) {
                        return values.insight
                    }
                    const dashboard = Number(router.values.searchParams.dashboard)
                    const dashboardId =
                        !asCopy && !values.insight && Number.isInteger(dashboard) && dashboard > 0 ? dashboard : null
                    const payload = {
                        name: asCopy ? `${values.name.trim()} (copy)` : values.name.trim(),
                        query: JSON.parse(JSON.stringify(values.worksheet)) as BIVisualizationNodeApi,
                        saved: true,
                    }
                    const state = { editorView: BIEditorView.BI, config: values.config }
                    const operation = values.insight && !asCopy ? 'update' : 'create'
                    const insight =
                        values.insight && !asCopy
                            ? await insightsPartialUpdate(String(values.currentTeamId), values.insight.id, payload)
                            : await insightsCreate(String(values.currentTeamId), payload)
                    if (dashboardId !== null) {
                        await insightsApi.addNewInsightToDashboards(insight.id, [dashboardId])
                    }
                    if (asCopy) {
                        cache.agentRefreshAfterSave = false
                        actions.setAgentUpdateState(null)
                    }
                    captureBIEditorQuerySaved(state, 'insight', operation, dashboardId !== null)
                    captureBIWorksheetAction('saved', state.config, { insight_id: insight.id })
                    if (asCopy) {
                        captureBIWorksheetAction('copied', state.config, { insight_id: insight.id })
                    }
                    if (dashboardId !== null) {
                        captureBIWorksheetAction('added_to_dashboard', state.config, { insight_id: insight.id })
                    }
                    return insight
                },
            },
        ],
        exportedView: [
            null as Awaited<ReturnType<typeof warehouseSavedQueriesCreate>> | null,
            {
                exportView: async () => {
                    if (!values.generatedQuery || !values.exportViewName.trim()) {
                        return null
                    }
                    const view = await warehouseSavedQueriesCreate(String(values.currentTeamId), {
                        name: values.exportViewName.trim(),
                        query: values.worksheet.source,
                    })
                    captureBIEditorQuerySaved({ editorView: BIEditorView.BI, config: values.config }, 'view', 'create')
                    actions.setExportViewOpen(false)
                    lemonToast.success('SQL view created. Save the worksheet as an insight to keep its shelves.')
                    return view
                },
            },
        ],
    })),
    reducers({
        history: [
            { past: [], present: null, future: [] } as BIWorksheetHistory,
            {
                pushHistory: (state, { snapshot, reset }) =>
                    reset
                        ? { past: [], present: snapshot, future: [] }
                        : equal(state.present, snapshot)
                          ? state
                          : {
                                past: state.present ? [...state.past, state.present].slice(-100) : [],
                                present: snapshot,
                                future: [],
                            },
                undo: (state) =>
                    state.past.length
                        ? {
                              past: state.past.slice(0, -1),
                              present: state.past[state.past.length - 1],
                              future: state.present ? [state.present, ...state.future] : state.future,
                          }
                        : state,
                redo: (state) =>
                    state.future.length
                        ? {
                              past: state.present ? [...state.past, state.present] : state.past,
                              present: state.future[0],
                              future: state.future.slice(1),
                          }
                        : state,
            },
        ],
        chartSettingsDefaults: [
            null as ChartSettings | null,
            {
                setChartSettingsDefaults: (_, { defaults }) => defaults ?? null,
                navigateHierarchy: () => null,
                restoreWorksheet: () => null,
                setVisualization: () => null,
            },
        ],
        visualization: [
            emptyWorksheet(),
            {
                restoreWorksheet: (_, { worksheet }) => worksheet,
                navigateHierarchy: (_, { worksheet }) => worksheet,
                setChartSettings: (state, { chartSettings }) => ({ ...state, chartSettings }),
                setVisualization: (state, { visualization }) => ({
                    ...state,
                    ...visualization,
                    kind: NodeKind.BIVisualizationNode,
                }),
            },
        ],
        insight: { clearInsight: () => null, setInsightFromAgent: (_, { insight }) => insight },
        agentUpdateConflict: [
            false,
            {
                setAgentUpdateState: (conflict, { state }) => state === 'conflict' || (state !== null && conflict),
                loadInsightSuccess: () => false,
                clearInsight: () => false,
                discardChanges: () => false,
            },
        ],
        agentUpdateState: [
            null as 'loading' | 'conflict' | 'error' | null,
            {
                setAgentUpdateState: (_, { state }) => state,
                loadInsightSuccess: () => null,
                clearInsight: () => null,
                discardChanges: (state) => (state === 'conflict' ? null : state),
            },
        ],
        name: ['Untitled worksheet', { setName: (_, { name }) => name }],
        lastRunQuery: [null as BIVisualizationNode | null, { setLastRunQuery: (_, { query }) => query }],
        loadError: [
            null as string | null,
            {
                openWorksheet: () => null,
                loadInsight: () => null,
                loadInsightFailure: (_, { error }) => error,
                loadInsightSuccess: () => null,
                openCatalogMetric: () => null,
                openCatalogMetricFailure: (_, { error }) => error,
                openCatalogMetricSuccess: () => null,
            },
        ],
        exportViewName: ['', { setExportViewName: (_, { name }) => name }],
        exportViewOpen: [false, { setExportViewOpen: (_, { open }) => open }],
        sqlPreviewOpen: [false, { setSqlPreviewOpen: (_, { open }) => open, restoreWorksheet: () => false }],
        sqlPreviewVersion: ['current' as 'current' | 'last_run', { setSqlPreviewVersion: (_, { version }) => version }],
    }),
    selectors({
        sqlPreviewQuery: [
            (s) => [s.sqlPreviewVersion, s.worksheet, s.lastRunQuery],
            (
                version: 'current' | 'last_run',
                worksheet: BIVisualizationNode,
                lastRun: BIVisualizationNode | null
            ): BIVisualizationNode | null => {
                const query = version === 'current' ? worksheet : lastRun
                return query?.source.query ? { ...query, source: getBIVisualizationSource(query) } : null
            },
        ],
        sqlEditorUrl: [
            (s) => [s.sqlPreviewQuery],
            (query: BIVisualizationNode | null): string | null =>
                query
                    ? urls.sqlEditor({
                          query: {
                              kind: NodeKind.DataVisualizationNode,
                              source: query.source,
                              display: ChartDisplayType.ActionsTable,
                          },
                      })
                    : null,
        ],
        displayedQueryIsCurrent: [
            (s) => [s.lastRunQuery, s.worksheet],
            (lastRunQuery: BIVisualizationNode | null, worksheet: BIVisualizationNode): boolean =>
                !!lastRunQuery &&
                equal(lastRunQuery.source, worksheet.source) &&
                equal(lastRunQuery.config, worksheet.config),
        ],
        canUndo: [(s) => [s.history], (history: BIWorksheetHistory): boolean => history.past.length > 0],
        canRedo: [(s) => [s.history], (history: BIWorksheetHistory): boolean => history.future.length > 0],
        copyDisabledReason: [
            (s) => [s.generatedQuery, s.name],
            (generatedQuery: BIQueryBuildResult | null, name: string): string | undefined =>
                !generatedQuery
                    ? 'Select a table and resolve any invalid fields before saving'
                    : !name.trim()
                      ? 'Enter a worksheet name'
                      : undefined,
        ],
        dataNodeKey: [(_, props) => [props.tabId], (tabId: string): string => `InsightViz.new-bi-${tabId}`],
        worksheet: [
            (s) => [s.config, s.generatedQuery, s.visualization, s.chartSettingsDefaults],
            (
                config: BIConfig,
                generatedQuery: BIQueryBuildResult | null,
                visualization: BIVisualizationNode,
                chartSettingsDefaults: ChartSettings | null
            ): BIVisualizationNode => ({
                ...visualization,
                ...generatedQuery?.node,
                kind: NodeKind.BIVisualizationNode,
                config,
                display: config.chartType,
                source: generatedQuery
                    ? mergeBIQuerySource(visualization.source, generatedQuery.node.source)
                    : { ...visualization.source, query: '' },
                chartSettings: mergeBIChartSettings(
                    visualization.chartSettings,
                    generatedQuery?.node.chartSettings,
                    chartSettingsDefaults ?? buildBIQuery(visualization.config)?.node.chartSettings,
                    config.chartType === ChartDisplayType.ScatterPlot,
                    config.chartType === ChartDisplayType.ScatterPlot
                        ? getBIScatterAxisOptions(config).map(({ value }) => value)
                        : []
                ),
                tableSettings: mergeBITableSettings(
                    visualization.tableSettings,
                    generatedQuery?.node.tableSettings,
                    buildBIQuery(visualization.config)?.node.tableSettings
                ),
            }),
        ],
        hasUnsavedChanges: [
            (s) => [s.worksheet, s.name, s.insight],
            (worksheet: BIVisualizationNode, name: string, insight: InsightApi | null): boolean =>
                !equal(
                    normalizeWorksheetForComparison(worksheet),
                    normalizeWorksheetForComparison(insight?.query ?? emptyWorksheet())
                ) || name.trim() !== (insight?.name || 'Untitled worksheet'),
        ],
        saveDisabledReason: [
            (s) => [s.generatedQuery, s.insight, s.name, s.agentUpdateState],
            (
                generatedQuery: BIQueryBuildResult | null,
                insight: InsightApi | null,
                name: string,
                agentUpdateState: 'loading' | 'conflict' | 'error' | null
            ): string | undefined => {
                if (agentUpdateState) {
                    return agentUpdateState === 'loading'
                        ? 'Refreshing assistant changes'
                        : agentUpdateState === 'error'
                          ? 'Retry refreshing assistant changes before saving'
                          : 'Discard changes or save a copy to resolve the assistant update'
                }
                if (!generatedQuery) {
                    return 'Select a table and resolve any invalid fields before saving'
                }
                if (!name.trim()) {
                    return 'Enter a worksheet name'
                }
                if (
                    insight &&
                    !accessLevelSatisfied(
                        AccessControlResourceType.Insight,
                        toAccessControlLevel(insight.user_access_level),
                        AccessControlLevel.Editor
                    )
                ) {
                    return 'You do not have permission to edit this insight'
                }
            },
        ],
    }),
    listeners(({ actions, values, props, cache }) => ({
        refreshInsightFromAgent: ({ targetId }) => {
            if (targetId && typeof targetId === 'object' && !Array.isArray(targetId)) {
                const input = targetId as Record<string, unknown>
                targetId = [input.id, input.insightId, input.insight_id, input.short_id, input.shortId].find(
                    (value) => value !== undefined
                )
            }
            const baseline = values.insight
            if (!baseline || (String(targetId) !== String(baseline.id) && targetId !== baseline.short_id)) {
                return
            }
            actions.reconcileInsightFromAgent()
        },
        reconcileInsightFromAgent: async (_, breakpoint) => {
            const baseline = values.insight
            if (!baseline) {
                return
            }
            const hadConflict = values.agentUpdateConflict
            actions.setAgentUpdateState('loading')
            if (values.insightLoading) {
                cache.agentRefreshAfterSave = true
                return
            }
            try {
                const response = await insightsList(String(values.currentTeamId), {
                    short_id: baseline.short_id,
                    basic: true,
                })
                breakpoint()
                if (values.insight !== baseline) {
                    if (values.insight?.id === baseline.id) {
                        actions.reconcileInsightFromAgent()
                    }
                    return
                }
                const updated = response.results[0]
                if (!updated || updated.id !== baseline.id || !isBIVisualizationNode(updated.query)) {
                    throw new Error('The updated worksheet is unavailable')
                }
                const localQuery = normalizeWorksheetForComparison(values.worksheet)
                const baselineQuery = normalizeWorksheetForComparison(baseline.query)
                const updatedQuery = normalizeWorksheetForComparison(updated.query)
                const queryEdited = !equal(localQuery, baselineQuery)
                const nameEdited = values.name !== (baseline.name || 'Untitled worksheet')
                const conflict =
                    (hadConflict && (queryEdited || nameEdited)) ||
                    (queryEdited && !equal(updatedQuery, baselineQuery) && !equal(localQuery, updatedQuery)) ||
                    (nameEdited && updated.name !== baseline.name && values.name !== updated.name)

                actions.setInsightFromAgent(updated)
                if (!queryEdited) {
                    actions.restoreWorksheet(updated.query)
                }
                if (!nameEdited) {
                    actions.setName(updated.name || 'Untitled worksheet')
                }
                actions.setAgentUpdateState(conflict ? 'conflict' : null)
                actions.syncWorksheetUrl()
                actions.recordWorksheet(true)
            } catch {
                breakpoint()
                if (values.insight === baseline) {
                    actions.setAgentUpdateState('error')
                }
            }
        },
        setSqlPreviewOpen: ({ open }) => {
            if (open) {
                actions.setSqlPreviewVersion(values.generatedQuery ? 'current' : 'last_run')
            }
        },
        openCatalogMetricSuccess: ({ catalogMetric: metric, payload: name }) => {
            if (
                router.values.location.pathname !== addProjectIdIfMissing(urls.businessIntelligenceNew()) ||
                router.values.searchParams.metric !== name ||
                router.values.hashParams.q
            ) {
                return
            }
            const worksheet = catalogMetricWorksheet(metric)!
            actions.clearInsight()
            actions.restoreWorksheet(worksheet)
            actions.setLastRunQuery(null)
            actions.setName(metric.display_name || metric.name)
            actions.recordWorksheet(true)
            actions.syncWorksheetUrl()
            captureBIWorksheetAction('catalog_metric_opened', worksheet.config)
        },
        recordWorksheet: ({ reset }) => {
            if (!cache.restoringHistory) {
                actions.pushHistory(
                    JSON.parse(JSON.stringify({ worksheet: values.worksheet, name: values.name })),
                    reset
                )
            }
        },
        undo: () => {
            actions.restoreHistory()
            captureBIWorksheetAction('undo', values.config)
        },
        redo: () => {
            actions.restoreHistory()
            captureBIWorksheetAction('redo', values.config)
        },
        restoreHistory: () => {
            const snapshot = values.history.present
            if (!snapshot) {
                return
            }
            cache.restoringHistory = true
            const lastRunQuery = values.lastRunQuery
            try {
                actions.restoreWorksheet(snapshot.worksheet)
                actions.setName(snapshot.name)
                actions.setLastRunQuery(lastRunQuery)
            } finally {
                cache.restoringHistory = false
            }
            actions.runAfterChange()
        },
        navigateHierarchy: ({ worksheet }) => {
            actions.restoreState({ editorView: BIEditorView.BI, config: worksheet.config })
            actions.runAfterChange()
        },
        setName: () => {
            actions.recordWorksheet()
            if (values.agentUpdateConflict) {
                actions.syncWorksheetUrl()
            }
        },
        [dataNodeLogic({ key: `InsightViz.new-bi-${props.tabId}`, query: emptyWorksheet().source }).actionTypes
            .loadDataSuccess]: ({ response }) => {
            if (
                !cache.firstChartCaptured &&
                values.lastRunQuery &&
                response &&
                'results' in response &&
                Array.isArray(response.results) &&
                response.results.length
            ) {
                cache.firstChartCaptured = true
                captureBIWorksheetAction('first_chart', values.lastRunQuery.config, {
                    insight_id: values.insight?.id,
                    result_count: response.results.length,
                })
            }
        },
        resetConfig: () => {
            const dataLogic = dataNodeLogic.findMounted({ key: values.dataNodeKey })
            dataLogic?.actions.cancelQuery()
            dataLogic?.actions.clearResponse()
            actions.restoreWorksheet({
                ...emptyWorksheet(),
                config: values.config,
                source: { kind: NodeKind.HogQLQuery, query: '', connectionId: values.connectionId ?? undefined },
            })
            actions.syncWorksheetUrl()
            actions.recordWorksheet()
        },
        selectConnection: ({ connectionId }) => {
            if (connectionId !== values.connectionId) {
                actions.restoreWorksheet({
                    ...emptyWorksheet(),
                    source: { kind: NodeKind.HogQLQuery, query: '', connectionId: connectionId ?? undefined },
                })
                actions.syncWorksheetUrl()
                actions.recordWorksheet()
            }
        },
        restoreWorksheet: ({ worksheet }) => {
            const connectionId = worksheet.source.connectionId ?? null
            claimConnectionScope(`bi:${props.tabId}`, connectionId)
            const connectionChanged = connectionId !== values.connectionId
            if (connectionChanged) {
                databaseTableListLogic.actions.setConnection(connectionId)
            }
            const config = { ...applyBIDateRange(worksheet.config, worksheet.source.filters?.dateRange) }
            if (
                worksheet.source.query &&
                config.source &&
                !config.rows.length &&
                !config.columns.length &&
                !config.values.length
            ) {
                config.values = [
                    {
                        field: {
                            id: 'bi-default-count',
                            name: 'Count of rows',
                            expression: '',
                            type: 'integer',
                            source: config.source,
                        },
                        aggregation: 'custom',
                        customExpression: 'count(*)',
                        label: 'Count of rows',
                    },
                ]
            }
            actions.restoreState({
                editorView: BIEditorView.BI,
                config,
            })
            if (connectionChanged || !databaseTableListLogic.values.database) {
                databaseTableListLogic.actions.loadDatabase({ shallow: true })
            }
            actions.setLastRunQuery(worksheet.source.query ? worksheet : null)
        },
        loadInsightSuccess: ({ insight }) => {
            if (insight && isBIVisualizationNode(insight.query)) {
                actions.setName(insight.name || 'Untitled worksheet')
                let worksheet: BIVisualizationNode = insight.query
                const { q, filters, bi_conflict } = router.values.hashParams
                let restoredDraft = false
                if (q) {
                    try {
                        const draft = typeof q === 'string' ? JSON.parse(q) : q
                        if (isBIVisualizationNode(draft) && parseBIEditorState(BIEditorView.BI, draft.config)) {
                            worksheet = draft
                            restoredDraft = true
                        }
                    } catch {
                        lemonToast.error('Could not restore worksheet edits from the link.')
                    }
                }
                if (filters && typeof filters === 'object' && !Array.isArray(filters)) {
                    worksheet = { ...worksheet, source: { ...worksheet.source, filters: filters as HogQLFilters } }
                }
                actions.restoreWorksheet(worksheet)
                if (restoredDraft && bi_conflict?.insightId === insight.id && typeof bi_conflict.name === 'string') {
                    actions.setName(bi_conflict.name)
                    actions.setAgentUpdateState('conflict')
                }
                actions.recordWorksheet(true)
                void insightsViewedCreate(String(values.currentTeamId), { insight_ids: [insight.id] }).catch(() => {})
            }
        },
        saveInsightSuccess: ({ insight }) => {
            if (cache.agentRefreshAfterSave) {
                cache.agentRefreshAfterSave = false
                actions.reconcileInsightFromAgent()
                return
            }
            if (values.agentUpdateState) {
                return
            }
            if (insight) {
                actions.setName(insight.name || 'Untitled worksheet')
                localStorage.removeItem(`bi-worksheet-${values.currentTeamId}-${props.tabId}`)
                refreshTreeItem('insight', insight.short_id)
                const dashboard = router.values.searchParams.dashboard
                router.actions.push(
                    urls.businessIntelligenceWorksheet(insight.short_id),
                    dashboard ? { dashboard } : {}
                )
            }
        },
        saveInsightFailure: () => {
            if (cache.agentRefreshAfterSave) {
                cache.agentRefreshAfterSave = false
                actions.reconcileInsightFromAgent()
            }
        },
        runAfterChange: async (_, breakpoint) => {
            actions.recordWorksheet()
            actions.syncWorksheetUrl()
            if (!values.generatedQuery) {
                const dataLogic = dataNodeLogic.findMounted({ key: values.dataNodeKey })
                dataLogic?.actions.cancelQuery()
                dataLogic?.actions.clearResponse()
                actions.setLastRunQuery(null)
                return
            }
            if (!values.autoUpdate) {
                return
            }
            await breakpoint(400)
            if (values.autoUpdate && values.generatedQuery) {
                const dataLogic = dataNodeLogic.findMounted({ key: values.dataNodeKey })
                if (
                    !values.lastRunQuery ||
                    !equal(getBIVisualizationSource(values.lastRunQuery), getBIVisualizationSource(values.worksheet)) ||
                    (!dataLogic?.values.responseLoading &&
                        (!dataLogic?.values.response ||
                            dataLogic.values.responseError ||
                            dataLogic.values.queryCancelled))
                ) {
                    actions.runQuery()
                } else {
                    actions.setLastRunQuery(values.worksheet)
                }
            }
        },
        setChartType: () => {
            if (
                !values.autoUpdate &&
                values.lastRunQuery &&
                equal({ ...values.lastRunQuery.config, chartType: values.config.chartType }, values.config) &&
                equal(getBIVisualizationSource(values.lastRunQuery), getBIVisualizationSource(values.worksheet))
            ) {
                actions.setLastRunQuery(values.worksheet)
            }
        },
        runQuery: () => {
            if (!values.generatedQuery) {
                return
            }
            captureBIEditorQueryRun({ editorView: BIEditorView.BI, config: values.config })
            const dataLogic = dataNodeLogic.findMounted({ key: values.dataNodeKey })
            const unchanged =
                !!values.lastRunQuery &&
                equal(getBIVisualizationSource(values.lastRunQuery), getBIVisualizationSource(values.worksheet))
            const waitingForFirstRun =
                dataLogic?.props.autoLoad === false &&
                equal(dataLogic.props.query, getBIVisualizationSource(values.worksheet))
            actions.setLastRunQuery(values.worksheet)
            if (unchanged || waitingForFirstRun) {
                dataLogic?.actions.loadData('force_async')
            }
        },
        cancelQuery: () => dataNodeLogic.findMounted({ key: values.dataNodeKey })?.actions.cancelQuery(),
        setScatterAxis: ({ axis, column }) => {
            const options = getBIScatterAxisOptions(values.config)
            const option = options.find((option) => option.value === column)
            if (!option) {
                return
            }
            const settings = values.worksheet.chartSettings ?? {}
            const previousY = settings.yAxis?.find((item) => item.column === column)
            if (axis === 'x') {
                const swap = previousY && settings.xAxis
                actions.setChartSettings({
                    ...settings,
                    xAxis: previousY ?? { column },
                    xAxisLabel:
                        previousY && settings.yAxis?.length === 1
                            ? (settings.leftYAxisSettings?.label ?? option.label)
                            : option.label,
                    yAxis: swap
                        ? settings.yAxis?.map((item) => (item.column === column ? settings.xAxis! : item))
                        : settings.yAxis,
                    leftYAxisSettings: {
                        ...settings.leftYAxisSettings,
                        label:
                            swap && settings.yAxis?.length === 1
                                ? settings.xAxisLabel
                                : settings.leftYAxisSettings?.label,
                    },
                })
            } else if (column !== settings.xAxis?.column) {
                actions.setChartSettings({
                    ...settings,
                    yAxis: [previousY ?? { column }],
                    leftYAxisSettings: { ...settings.leftYAxisSettings, label: option.label },
                })
            }
        },
        setChartSettings: ({ chartSettings }) => {
            actions.setChartSettingsDefaults(
                buildBIQuery(values.lastRunQuery?.config ?? values.config)?.node.chartSettings
            )
            if (values.lastRunQuery) {
                const availableColumns = new Set(
                    getBIScatterAxisOptions(values.lastRunQuery.config).map(({ value }) => value)
                )
                const axes = [chartSettings.xAxis, ...(chartSettings.yAxis ?? [])].filter((axis) => axis !== undefined)
                if (
                    values.lastRunQuery.config.chartType !== ChartDisplayType.ScatterPlot ||
                    axes.every((axis) => availableColumns.has(axis.column))
                ) {
                    actions.setLastRunQuery({ ...values.lastRunQuery, chartSettings })
                }
            }
            actions.syncWorksheetUrl()
            actions.recordWorksheet()
        },
        setVisualization: ({ visualization }) => {
            const config = applyBIDateRange(values.config, visualization.source.filters?.dateRange)
            if (config !== values.config) {
                actions.restoreState({ editorView: BIEditorView.BI, config })
            }
            if (visualization.display && visualization.display !== values.config.chartType) {
                actions.setChartType(visualization.display)
            }
            actions.setLastRunQuery(values.worksheet)
            actions.syncWorksheetUrl()
            actions.recordWorksheet()
        },
        discardChanges: ({ syncUrl }) => {
            if (isBIVisualizationNode(values.insight?.query)) {
                actions.restoreWorksheet(values.insight.query)
                actions.setName(values.insight.name || 'Untitled worksheet')
            } else {
                actions.restoreWorksheet(emptyWorksheet())
                actions.setName('Untitled worksheet')
            }
            if (syncUrl) {
                actions.syncWorksheetUrl()
            } else {
                cache.lastHash = undefined
                localStorage.removeItem(`bi-worksheet-${values.currentTeamId}-${props.tabId}`)
            }
            actions.recordWorksheet(true)
        },
        syncWorksheetUrl: () => {
            localStorage.setItem(
                `bi-worksheet-${values.currentTeamId}-${props.tabId}`,
                JSON.stringify(values.worksheet)
            )
            cache.lastHash = JSON.stringify(values.worksheet)
            cache.syncingWorksheetUrl = true
            try {
                router.actions.replace(
                    values.insight
                        ? urls.businessIntelligenceWorksheet(values.insight.short_id)
                        : urls.businessIntelligenceNew(),
                    router.values.searchParams,
                    {
                        q: cache.lastHash,
                        ...(values.agentUpdateConflict && values.insight
                            ? { bi_conflict: { insightId: values.insight.id, name: values.name } }
                            : {}),
                    }
                )
            } finally {
                cache.syncingWorksheetUrl = false
            }
        },
        shareWorksheet: async () => {
            actions.syncWorksheetUrl()
            await copyToClipboard(window.location.href, 'worksheet link')
        },
        openWorksheet: () => {
            const { searchParams, hashParams } = router.values
            if (typeof searchParams.metric === 'string' && !hashParams.q) {
                actions.openCatalogMetric(searchParams.metric)
                return
            }
            const pathId = router.values.location.pathname.match(/\/bi\/([^/]+)$/)?.[1]
            const insightShortId =
                searchParams.open_insight || (pathId && pathId !== 'new' ? decodeURIComponent(pathId) : undefined)
            if (searchParams.open_view) {
                router.actions.replace(urls.sqlEditor({ view_id: searchParams.open_view }))
                return
            }
            if (insightShortId && cache.loadingId !== insightShortId) {
                cache.loadingId = insightShortId
                cache.firstChartCaptured = false
                actions.loadInsight(insightShortId)
                return
            }
            if (insightShortId) {
                return
            }
            if (cache.lastHash !== undefined && hashParams.q === cache.lastHash) {
                return
            }
            cache.loadingId = undefined
            actions.clearInsight()
            let worksheet = emptyWorksheet()
            try {
                const raw = hashParams.q ?? localStorage.getItem(`bi-worksheet-${values.currentTeamId}-${props.tabId}`)
                const parsed = raw && !hashParams.bi ? (typeof raw === 'string' ? JSON.parse(raw) : raw) : null
                if (isBIVisualizationNode(parsed) && parseBIEditorState(BIEditorView.BI, parsed.config)) {
                    worksheet = parsed
                } else {
                    const state = parseBIEditorState(BIEditorView.BI, hashParams.bi)
                    const built = state && buildBIQuery(state.config)
                    if (state) {
                        worksheet = {
                            ...worksheet,
                            ...built?.node,
                            kind: NodeKind.BIVisualizationNode,
                            config: state.config,
                        }
                    }
                }
            } catch {
                lemonToast.error('Could not restore the worksheet link.')
            }
            actions.restoreWorksheet(worksheet)
            if (searchParams.starter) {
                actions.setLastRunQuery(null)
            }
            actions.setName('Untitled worksheet')
            actions.recordWorksheet(true)
        },
    })),
    beforeUnload(({ values, actions, cache }) => ({
        enabled: (newLocation) =>
            !cache.syncingWorksheetUrl &&
            values.hasUnsavedChanges &&
            (!newLocation || addProjectIdIfMissing(newLocation.pathname) !== router.values.location.pathname),
        message: 'Leave worksheet? Changes you made will be discarded.',
        // On browser Back, replacing the URL would overwrite the destination's history entry.
        onConfirm: () => actions.discardChanges(false),
    })),
    urlToAction(({ actions }) => ({
        '/bi': (_, searchParams, hashParams) => {
            if (searchParams.open_insight || searchParams.open_view || 'q' in hashParams || hashParams.bi) {
                actions.openWorksheet()
            }
        },
        '/bi/new': () => actions.openWorksheet(),
        '/bi/:insightShortId': () => actions.openWorksheet(),
    })),
    beforeUnmount(({ props }) => {
        if (releaseConnectionScope(`bi:${props.tabId}`, databaseTableListLogic.values.connectionId)) {
            databaseTableListLogic.actions.resetConnectionScope()
        }
    }),
    afterMount(({ actions, values }) => {
        captureBIWorksheetAction('opened', values.config)
        connectionSelectorLogic.actions.maybeLoadConnectionOptions()
        actions.openWorksheet()
    }),
])