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.

206 KB
Raw Blame
import { Monaco } from '@monaco-editor/react'
import { deepEqual as equal } from 'fast-equals'
import {
    MakeLogicType,
    actions,
    afterMount,
    beforeUnmount,
    connect,
    isBreakpoint,
    kea,
    key,
    listeners,
    path,
    props,
    propsChanged,
    reducers,
    selectors,
} from 'kea'
import { loaders } from 'kea-loaders'
import { router, urlToAction } from 'kea-router'
import { subscriptions } from 'kea-subscriptions'
import { type IRange, Uri, editor } from 'monaco-editor'
import posthog from 'posthog-js'
import { Suspense } from 'react'

import {
    LemonCheckbox,
    LemonDialog,
    LemonInput,
    LemonSearchableSelect,
    LemonTextArea,
    Spinner,
    lemonToast,
    Tooltip,
} from '@posthog/lemon-ui'

import api, { ApiConfig, ApiError } from 'lib/api'
import { tryShowMCPHint } from 'lib/components/MCPHint/mcpHintLogic'
import { SetupTaskId, globalSetupLogic } from 'lib/components/ProductSetup'
import { FEATURE_FLAGS } from 'lib/constants'
import { LemonField } from 'lib/lemon-ui/LemonField'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { trackedActionToUrl } from 'lib/logic/scenes/trackedActionToUrl'
import { clearLogicReference, initModel } from 'lib/monaco/CodeEditor'
import { codeEditorLogic } from 'lib/monaco/codeEditorLogic'
import { findQueryAtCursor, type QueryRange, splitQueries } from 'lib/monaco/multiQueryUtils'
import { characterOffsetToUtf16 } from 'lib/monaco/offsets'
import { removeProjectIdIfPresent } from 'lib/utils/kea-router'
import { objectsEqual, removeUndefinedAndNull } from 'lib/utils/objects'
import { lazyWithRetry } from 'lib/utils/retryImport'
import { slugify } from 'lib/utils/strings'
import { backLinkParams, withBackLink } from 'scenes/analytics/analyticsBackLink'
import { DashboardLoadAction, dashboardLogic, placeTilesInGroup } from 'scenes/dashboard/dashboardLogic'
import {
    MANAGED_TRINO_SCHEMA_SCOPE,
    databaseTableListLogic,
} from 'scenes/data-management/database/databaseTableListLogic'
import {
    filtersPlaceholderBindings,
    parseQueryTablesAndColumns,
    queryUsesFiltersPlaceholder,
} from 'scenes/data-warehouse/editor/sql-utils'
import { insightLogic } from 'scenes/insights/insightLogic'
import { insightsApi } from 'scenes/insights/utils/api'
import { teamLogic } from 'scenes/teamLogic'
import { urls } from 'scenes/urls'
import { userLogic } from 'scenes/userLogic'

import { dashboardsModel } from '~/models/dashboardsModel'
import { insightsModel } from '~/models/insightsModel'
import { DataNodeLogicProps, dataNodeLogic } from '~/queries/nodes/DataNode/dataNodeLogic'
import { dataVisualizationLogic } from '~/queries/nodes/DataVisualization/dataVisualizationLogic'
import { performQuery, queryExportContext } from '~/queries/query'
import {
    DataTableNode,
    DataVisualizationNode,
    DatabaseSchemaViewTable,
    HogLanguage,
    HogQLFilters,
    HogQLMetadata,
    HogQLMetadataResponse,
    HogQLQuery,
    HogQLQueryModifiers,
    NodeKind,
    PredicateQuickfix,
} from '~/queries/schema/schema-general'
import {
    AccessControlResourceType,
    ChartDisplayType,
    DataModelingEdge,
    DataModelingNode,
    DataWarehouseSavedQuery,
    DataWarehouseSavedQueryDraft,
    DataWarehouseSavedQueryIncremental,
    ExportContext,
    InsightModel,
} from '~/types'

import {
    existingMetricFromNameConflict,
    MetricFormPrefill,
    validateMetricName,
} from 'products/data_catalog/frontend/common'
import {
    createMetricAsUser,
    MetricSaveAction,
    toastCreatedMetric,
} from 'products/data_catalog/frontend/createMetricAsUser'
import {
    dataCatalogMetricsPartialUpdate,
    dataCatalogMetricsRetrieve,
} from 'products/data_catalog/frontend/generated/api'
import { metricsLogic } from 'products/data_catalog/frontend/metricsLogic'
import { openOverwriteMetricDialog } from 'products/data_catalog/frontend/openOverwriteMetricDialog'
import { warehouseSavedQueriesRetrieve } from 'products/data_warehouse/frontend/generated/api'
import { claimConnectionScope, releaseConnectionScope } from 'products/data_warehouse/frontend/shared/connectionScope'
import { sqlEditorDraftStorage } from 'products/data_warehouse/frontend/sqlEditorDraftStorage'
import { validateEndpointName } from 'products/endpoints/frontend/common'

import type { ExternalDataSourceConnectionOptionApi } from '../../../../../products/warehouse_sources/frontend/generated/api.schemas'

// Mirrors MANAGED_WAREHOUSE_SOURCE_PREFIX in products/warehouse_sources/backend/models/external_data_source.py.
export const MANAGED_WAREHOUSE_SOURCE_PREFIX = 'managed_warehouse'
import {
    captureBIEditorQueryRun,
    captureBIEditorQuerySaved,
} from 'products/business_intelligence/frontend/biEditorAnalytics'
import {
    BIEditorState,
    DEFAULT_BI_CONFIG,
    BIEditorView,
    buildBIQuery,
    getBIFilterValidationError,
    parseBIEditorState,
} from 'products/business_intelligence/frontend/biEditorTypes'
import { connectionSelectorLogic } from 'products/data_warehouse/frontend/shared/logics/connectionSelectorLogic'

import type { FeatureFlagsSet } from '../../../lib/logic/featureFlagLogic'
import type { DatabaseSchemaQueryResponse, Node } from '../../../queries/schema/schema-general'
import type { DataWarehouseSavedQueryFolder, UserType } from '../../../types'
import { dataWarehouseViewsLogic } from '../saved_queries/dataWarehouseViewsLogic'
import type { DataWarehouseSavedQuerySummary } from '../saved_queries/dataWarehouseViewsLogic'
import { validateSavedQueryName } from '../saved_queries/savedQueryNameValidation'
import { draftsLogic } from './draftsLogic'
import { fixSQLErrorsLogic } from './fixSQLErrorsLogic'
import type { Response } from './fixSQLErrorsLogic'
import { IncrementalConfigFields } from './IncrementalConfigFields'
import { findInnermostSelectAtOffset } from './multiQueryUtils'
import { OutputTab, outputPaneLogic } from './outputPaneLogic'
import { findSelectionProblem } from './saveCandidateProblems'
import {
    resolveSaveCandidates as resolveSaveCandidatesPure,
    SaveCandidates,
    SaveTargetCycler,
} from './SaveTargetCycler'
import { SQLEditorMode, isEmbeddedSQLEditorMode } from './sqlEditorModes'
import { SQLEditorPlaceholder, placeholderPreviewValues } from './sqlEditorPlaceholders'
import {
    aiSuggestionOnAccept,
    aiSuggestionOnAcceptText,
    aiSuggestionOnReject,
    aiSuggestionOnRejectText,
} from './suggestions/aiSuggestion'
import {
    queryHistorySuggestionOnAccept,
    queryHistorySuggestionOnAcceptText,
    queryHistorySuggestionOnReject,
    queryHistorySuggestionOnRejectText,
} from './suggestions/queryHistorySuggestion'
import { ViewEmptyState } from './ViewLoadingState'

export interface SqlEditorLogicProps {
    tabId: string
    mode?: SQLEditorMode
    singleStatement?: boolean
    hideAgentHints?: boolean
    monaco?: Monaco | null
    editor?: editor.IStandaloneCodeEditor | null
}

// Position the active-query outline overlay around `range` in viewport coords.
// Monaco renders inline decorations per-line, so we can't get a single rectangular
// border from a className. Instead, we maintain an absolutely-positioned `div`
// inside the editor's overlay layer and recompute its bounding box from the pixel
// positions of the range's start/end on each line. Runs on every scroll frame, so it
// stays off the DOM wherever the geometry can be derived from layout math instead.
export function renderQueryOutline(
    editorInstance: editor.IStandaloneCodeEditor,
    node: HTMLElement,
    range: IRange
): void {
    const model = editorInstance.getModel()
    if (!model) {
        node.style.display = 'none'
        return
    }

    // The cached range can outlive the document it was computed against: a paste or edit
    // that removes lines shrinks the model, but this render path runs on scroll/layout
    // without re-clamping. Passing an out-of-range line to `getLineMaxColumn` throws
    // "Illegal value for lineNumber", so clamp every line/column against the live model.
    const lineCount = model.getLineCount()
    const startLine = Math.max(1, Math.min(range.startLineNumber, lineCount))
    const endLine = Math.max(1, Math.min(range.endLineNumber, lineCount))
    const startColumn = Math.min(range.startColumn, model.getLineMaxColumn(startLine))

    // Vertical extent is pure layout math and monotonic in line number, so the range's own
    // first/last line always bound it — no per-line scan, and no DOM reads. `getBottomForLineNumber`
    // measures past the end of the wrapped line, which is exactly what a wrapped range needs.
    const scrollTop = editorInstance.getScrollTop()
    const minTop = editorInstance.getTopForPosition(startLine, startColumn) - scrollTop
    const maxBottom = editorInstance.getBottomForLineNumber(endLine) - scrollTop

    // Horizontal extent has to come from `getScrolledVisiblePosition`, which is expensive:
    // each call forces a synchronous Monaco view render and reads client rects. Only scan
    // lines that are actually rendered — for off-screen lines Monaco returns a placeholder
    // pinned to the gutter edge anyway, so clamping here is more accurate, not less.
    // Folding can yield several ranges; we only need the outer bounds, and don't assume ordering.
    const visibleRanges = editorInstance.getVisibleRanges?.() ?? []
    let loopStart = startLine
    let loopEnd = endLine
    if (visibleRanges.length) {
        const firstVisibleLine = Math.min(...visibleRanges.map((r) => r.startLineNumber))
        const lastVisibleLine = Math.max(...visibleRanges.map((r) => r.endLineNumber))
        loopStart = Math.max(startLine, firstVisibleLine)
        loopEnd = Math.min(endLine, lastVisibleLine)
    }

    let minLeft = Infinity
    let maxRight = -Infinity

    for (let line = loopStart; line <= loopEnd; line++) {
        const lineMaxColumn = model.getLineMaxColumn(line)
        const leftCol = Math.min(line === startLine ? range.startColumn : 1, lineMaxColumn)
        const rightCol = line === endLine ? Math.min(range.endColumn, lineMaxColumn) : lineMaxColumn
        if (leftCol >= rightCol) {
            continue
        }
        const startVis = editorInstance.getScrolledVisiblePosition({ lineNumber: line, column: leftCol })
        const endVis = editorInstance.getScrolledVisiblePosition({ lineNumber: line, column: rightCol })
        if (!startVis || !endVis) {
            continue
        }
        if (startVis.left < minLeft) {
            minLeft = startVis.left
        }
        if (endVis.left > maxRight) {
            maxRight = endVis.left
        }
    }

    // No rendered line intersects the range — it's scrolled fully out of view, so there's
    // nothing to frame.
    if (minLeft === Infinity) {
        node.style.display = 'none'
        return
    }

    // Small padding so the border doesn't touch the glyphs / cursor caret.
    const padX = 3
    const padY = 1
    node.style.display = 'block'
    node.style.left = `${minLeft - padX}px`
    node.style.top = `${minTop - padY}px`
    node.style.width = `${maxRight - minLeft + padX * 2}px`
    node.style.height = `${maxBottom - minTop + padY * 2}px`
}

// A disposed Monaco editor drops its DOM node, but the cached `props.editor` reference lingers.
// `IStandaloneCodeEditor` has no `isDisposed()`, so a null DOM node is the reliable disposed signal.
// Writing to a disposed editor (e.g. `setModel`) throws inside Monaco's `_attachModel` and crashes
// the React commit, so gate every such write on this check. A live editor without a model still
// passes — a fresh tab binds its first model here.
export function isEditorAlive(
    editorInstance: editor.IStandaloneCodeEditor | null | undefined
): editorInstance is editor.IStandaloneCodeEditor {
    return !!editorInstance && editorInstance.getDomNode() !== null
}

function clearQueryOutlineOverlay(
    cache: sqlEditorLogicType['cache'],
    fallbackEditor?: editor.IStandaloneCodeEditor | null
): void {
    cache.scrollDisposable?.dispose()
    cache.scrollDisposable = null
    cache.layoutDisposable?.dispose()
    cache.layoutDisposable = null

    if (cache.outlineRafId != null) {
        cancelAnimationFrame(cache.outlineRafId)
        cache.outlineRafId = null
    }
    cache.scheduleOutlineRender = null

    if (cache.queryOutlineWidget) {
        try {
            ;(cache.queryOutlineEditor ?? fallbackEditor)?.removeOverlayWidget(cache.queryOutlineWidget)
        } catch (e) {
            console.warn('[sqlEditorLogic] failed to remove outline overlay widget', e)
        }
    }

    cache.queryOutlineWidget = null
    cache.queryOutlineEditor = null
    cache.queryOutlineNode = null
    cache.queryOutlineRange = null
    cache.updateQueryOutline = null
}

export const NEW_QUERY = 'Untitled'

export interface QueryTab {
    uri?: Uri
    view?: DataWarehouseSavedQuery
    name: string
    description?: string
    sourceQuery?: DataVisualizationNode
    insight?: InsightModel
    response?: Record<string, any>
    draft?: DataWarehouseSavedQueryDraft
    metricName?: string
    biEditorState?: BIEditorState
}

export type SqlEditorSource = 'insight' | 'endpoint' | 'view' | 'metric'

export interface SaveAsMetricFields {
    name: string
    display_name: string
    description: string
    unit: string
}

export interface SaveAsMetricModalState {
    candidates: SaveCandidates
    selectionProblem: string | null
    prefill: MetricFormPrefill
}

export interface DataWarehouseAccessControlModalProps {
    resource:
        | AccessControlResourceType.WarehouseTable
        | AccessControlResourceType.WarehouseView
        | AccessControlResourceType.ExternalDataSource
    resourceId: string
    name: string
}

export interface SuggestionPayload {
    suggestedValue?: string
    originalValue?: string
    acceptText?: string
    rejectText?: string
    diffShowRunButton?: boolean
    source?: 'max_ai' | 'hogql_fixer' | 'query_history'
    onAccept: (
        shouldRunQuery: boolean,
        actions: sqlEditorLogicType['actions'],
        values: sqlEditorLogicType['values'],
        props: sqlEditorLogicType['props']
    ) => void
    onReject: (
        actions: sqlEditorLogicType['actions'],
        values: sqlEditorLogicType['values'],
        props: sqlEditorLogicType['props']
    ) => void
}

export type UpdateViewPayload = Partial<DatabaseSchemaViewTable> & {
    edited_history_id?: string
    id: string
    lifecycle?: string
    shouldRematerialize?: boolean
    sync_frequency?: string
    types: string[][]
}

type LegacyDataVisualizationNode = DataVisualizationNode & {
    connectionId?: string
}

function hasOwnProperty(object: Record<string, any>, key: string): boolean {
    return Object.prototype.hasOwnProperty.call(object, key)
}

export function normalizeFiltersForUrl(filters: HogQLFilters | null | undefined): HogQLFilters | undefined {
    const normalizedFilters: HogQLFilters = {}

    if (filters?.properties?.length) {
        normalizedFilters.properties = filters.properties
    }

    if (filters?.dateRange?.date_from || filters?.dateRange?.date_to) {
        normalizedFilters.dateRange = filters.dateRange
    }

    if (filters?.filterTestAccounts) {
        normalizedFilters.filterTestAccounts = true
    }

    return Object.keys(normalizedFilters).length ? normalizedFilters : undefined
}

function parseFiltersFromUrl(filters: unknown): HogQLFilters | undefined {
    if (!filters || typeof filters !== 'object' || Array.isArray(filters)) {
        return undefined
    }

    return normalizeFiltersForUrl(filters as HogQLFilters)
}

export function normalizeRawQuerySource(source: HogQLQuery): HogQLQuery {
    return {
        ...source,
        sendRawQuery:
            source.connectionId || source.executionTarget === 'managed_trino'
                ? source.sendRawQuery || undefined
                : undefined,
    }
}

// Raw Trino views run only on hosted Trino, so they have no lineage node and cannot be materialized.
export function isRawTrinoView(view: DataWarehouseSavedQuery): boolean {
    return view.query?.executionTarget === 'managed_trino' && !!view.query?.sendRawQuery
}

function hogQLEditorSourceQuery(source: Partial<HogQLQuery> = {}): DataVisualizationNode {
    return {
        kind: NodeKind.DataVisualizationNode,
        source: {
            ...source,
            kind: NodeKind.HogQLQuery,
            query: typeof source.query === 'string' ? source.query : '',
        },
        display: ChartDisplayType.Auto,
    }
}

function metricEditorSourceQuery(definition: Record<string, unknown> | null | undefined): DataVisualizationNode | null {
    if (!definition) {
        return hogQLEditorSourceQuery()
    }
    if (definition.kind !== NodeKind.HogQLQuery) {
        return null
    }
    return hogQLEditorSourceQuery(definition as Partial<HogQLQuery>)
}

function sanitizeSourceQuery(sourceQuery: DataVisualizationNode): DataVisualizationNode {
    const { connectionId: _ignoredConnectionId, ...sanitizedSourceQuery } = sourceQuery as LegacyDataVisualizationNode

    return {
        ...sanitizedSourceQuery,
        source: normalizeRawQuerySource(sourceQuery.source),
    }
}

export function toDataVisualizationNode(
    query: InsightModel['query'] | null | undefined
): DataVisualizationNode | undefined {
    if (!query) {
        return undefined
    }
    if (query.kind === NodeKind.DataVisualizationNode) {
        // A hand-crafted open_query URL can carry a node with no source; only adopt it when the HogQL source is present
        const source = (query as DataVisualizationNode).source
        return source?.kind === NodeKind.HogQLQuery ? (query as DataVisualizationNode) : undefined
    }
    // Insights created from the old DataTableNode path store the HogQLQuery under `.source`.
    // Wrap it so the SQL editor can render and save it through the visualization pipeline.
    if (query.kind === NodeKind.DataTableNode) {
        const source = (query as DataTableNode).source
        if (source?.kind === NodeKind.HogQLQuery) {
            return {
                kind: NodeKind.DataVisualizationNode,
                source: source as HogQLQuery,
            }
        }
    }
    return undefined
}

export function getCurrentVisualizationQuery(
    dataLogicKey: string,
    fallbackQuery: DataVisualizationNode,
    queryInput: string | null
): DataVisualizationNode {
    // This reads the mounted visualization state so save/update actions can include in-flight
    // axis/display edits. Those edits are also synced back through props.setQuery -> setSourceQuery,
    // so sourceQuery remains the durable fallback when the visualization logic is unmounted.
    const mountedVisualizationLogic = dataVisualizationLogic.findMounted({
        key: dataLogicKey,
    } as any)

    const mountedQuery = mountedVisualizationLogic?.values.query
    const visualizationQuery = mountedQuery?.kind === NodeKind.DataVisualizationNode ? mountedQuery : fallbackQuery
    return {
        ...visualizationQuery,
        source: { ...visualizationQuery.source, query: queryInput ?? visualizationQuery.source.query },
    }
}

function getTabHash(values: sqlEditorLogicType['values']): Record<string, any> {
    const hash: Record<string, any> = {
        q: values.queryInput ?? '',
        output_tab: values.outputActiveTab,
    }
    if (values.sourceQuery?.source.executionTarget) {
        hash['engine'] = values.sourceQuery.source.executionTarget
    } else if (toDataVisualizationNode(values.activeTab?.insight?.query)?.source.executionTarget) {
        hash['engine'] = 'posthog'
    }
    const connectionId = values.sourceQuery?.source.connectionId
    if (connectionId) {
        hash['c'] = connectionId
    }
    if (values.sendRawQueryEnabled) {
        hash['raw'] = '1'
    }
    const filters = normalizeFiltersForUrl(values.sourceQuery?.source.filters)
    if (filters) {
        hash['filters'] = filters
    }
    if (values.activeTab?.view) {
        hash['view'] = values.activeTab.view.id
    }
    if (values.activeTab?.insight) {
        hash['insight'] = values.activeTab.insight.short_id
    }
    if (values.activeTab?.draft) {
        hash['draft'] = values.activeTab.draft.id
    }
    if (values.activeTab?.biEditorState) {
        hash['mode'] = values.activeTab.biEditorState.editorView
        hash['bi'] = values.activeTab.biEditorState.config
    }

    return hash
}

function parseMetricPrefill(value: unknown): MetricFormPrefill | null {
    if (!value || typeof value !== 'object' || Array.isArray(value)) {
        return null
    }

    const source = value as Record<string, unknown>
    const prefill: MetricFormPrefill = {}
    for (const field of ['name', 'display_name', 'description', 'unit'] as const) {
        if (typeof source[field] === 'string') {
            prefill[field] = source[field] as string
        }
    }

    return Object.keys(prefill).length ? prefill : null
}

function parseOutputTab(value: unknown): OutputTab | null {
    if (Object.values(OutputTab).includes(value as OutputTab)) {
        return value as OutputTab
    }

    return null
}

export function getDisplayTypeToSaveInsight(
    outputTab: OutputTab,
    sourceQueryDisplay: ChartDisplayType | undefined,
    effectiveVisualizationType?: ChartDisplayType
): ChartDisplayType {
    if (outputTab === OutputTab.Results) {
        return ChartDisplayType.ActionsTable
    }

    if (sourceQueryDisplay && sourceQueryDisplay !== ChartDisplayType.Auto) {
        return sourceQueryDisplay
    }

    return effectiveVisualizationType || ChartDisplayType.ActionsLineGraph
}

export function activeTabMatchesUrlTarget(
    activeTab: QueryTab | null,
    target: { draftId?: string; insightShortId?: string; viewId?: string }
): boolean {
    if (target.draftId) {
        return activeTab?.draft?.id === target.draftId
    }

    if (target.viewId) {
        return activeTab?.view?.id === target.viewId
    }

    if (target.insightShortId) {
        return activeTab?.insight?.short_id === target.insightShortId
    }

    return !activeTab?.draft && !activeTab?.view && !activeTab?.insight
}

// The Monaco model URI string for a tab's editor content. QueryWindow binds the editor to
// this `path` and createTab creates the model at it — they must agree, so both derive it here.
export function tabModelPath(tabId: string): string {
    return `tab-${tabId}`
}

/** The update has landed when this runs, so a refused placement shows a toast instead of throwing, and the caller still syncs its state. */
async function placeSavedInsightOnDashboard(
    savedInsight: InsightModel,
    dashboardId: number | null
): Promise<{ insight: InsightModel; placed: boolean }> {
    if (!dashboardId) {
        return { insight: savedInsight, placed: false }
    }
    try {
        const tile = await insightsApi.addToDashboard(savedInsight.id, dashboardId)
        return {
            insight: {
                ...savedInsight,
                dashboard_tiles: [
                    ...(savedInsight.dashboard_tiles || []).filter((t) => t.dashboard_id !== dashboardId),
                    tile,
                ],
            },
            placed: true,
        }
    } catch (e) {
        const detail = e instanceof ApiError ? e.detail : null
        lemonToast.error(
            `Insight saved, but it couldn't be added to the dashboard. ${detail ?? 'Add it from the insight page instead.'}`
        )
        return { insight: savedInsight, placed: false }
    }
}

// Apply `text` to the tab's persistent Monaco model as a single undoable edit. The model is
// kept alive across the diff <-> editor swap by `keepCurrentModel` (see QueryWindow), so its
// full undo history survives — pushEditOperations adds one more undoable step rather than
// wiping the stack. This also keeps the editor content in sync after accepting/rejecting a
// suggestion: @monaco-editor/react reuses the existing model on remount without re-applying
// the `value` prop, so the content has to be written onto the model directly. No-ops when the
// editor isn't mounted yet or the content already matches.
function applyUndoableModelEdit(monaco: Monaco | null | undefined, uri: Uri | undefined, text: string): void {
    if (!monaco || !uri) {
        return
    }
    const model = monaco.editor.getModel(uri)
    if (!model || model.getValue() === text) {
        return
    }
    model.pushStackElement()
    model.pushEditOperations([], [{ range: model.getFullModelRange(), text }], () => null)
    model.pushStackElement()
}

const LazyQuery = lazyWithRetry(() =>
    import('~/queries/Query/Query').then((m) => ({ default: m.Query<DataVisualizationNode> }))
)

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface sqlEditorLogicValues {
    connectionOptions: ExternalDataSourceConnectionOptionApi[] | null // connectionSelectorLogic
    dataWarehouseSavedQueries: DataWarehouseSavedQuerySummary[] // dataWarehouseViewsLogic
    dataWarehouseSavedQueryFolders: DataWarehouseSavedQueryFolder[] // dataWarehouseViewsLogic
    dataWarehouseSavedQueryMapById: Record<string, DataWarehouseSavedQuerySummary> // dataWarehouseViewsLogic
    database: Required<DatabaseSchemaQueryResponse> | null // databaseTableListLogic
    databaseConnectionId: string | null // databaseTableListLogic
    databaseLoading: boolean // databaseTableListLogic
    drafts: DataWarehouseSavedQueryDraft[] // draftsLogic
    featureFlags: FeatureFlagsSet // featureFlagLogic
    outputActiveTab: OutputTab // outputPaneLogic
    user: UserType | null // userLogic
    acceptText: string
    accessControlModalOpen: boolean
    activeQueryOffset: number
    activeQueryText: string | null
    activeTab: QueryTab | null
    changesToSave: boolean
    currentDraft: DataWarehouseSavedQueryDraft | null | undefined
    dashboardId: number | null
    dashboardTileGroupKey: string | null
    dataLogicKey: string
    diffShowRunButton: boolean | undefined
    editingAccessControlObject: DataWarehouseAccessControlModalProps | null
    editingInsight: InsightModel | null
    editingMetricName: string | null
    editingView: DataWarehouseSavedQuery | undefined
    editorKey: string
    editorSource: SqlEditorSource
    editorUrl: string
    error: string | null
    exportContext: ExportContext
    filtersPlaceholderBindings: string[] | null
    finishedLoading: boolean
    fixErrorsError: string | null
    hasEditorChanges: boolean
    hasFiltersPlaceholder: boolean
    hasQueryInput: boolean
    hoveredNode: string | null
    inProgressDraftEdits: Record<string, string>
    inProgressViewEdits: Record<string, string>
    indexReportStale: boolean
    insightLoading: boolean
    isDraft: boolean
    isEditingMaterializedView: boolean
    isEmbeddedMode: boolean
    isMultiQuery: boolean
    isSourceQueryLastRun: boolean
    lastRunQuery: DataVisualizationNode | null
    materializationModalOpen: boolean
    materializationModalView: DataWarehouseSavedQuery | null
    metadata: HogQLMetadataResponse | null
    metadataLoading: boolean
    metricPrefill: MetricFormPrefill | null
    metricUpdating: boolean
    originalQueryInput: string | null | undefined
    placeholderValues: Record<string, string> | null
    placeholders: SQLEditorPlaceholder[]
    queryInput: string | null
    queryModifiers: HogQLQueryModifiers | null
    rejectText: string
    saveAsMetricModal: SaveAsMetricModalState | null
    savingMetricAs: MetricSaveAction | null
    selectedConnectionId: string | undefined
    selectedConnectionSupportsHogQL: boolean
    selectedDirectSource: ExternalDataSourceConnectionOptionApi | undefined
    selectedQueryColumns: Record<string, boolean>
    selectedQueryTablesAndColumns: Record<string, Record<string, boolean>>
    selectedSchemaConnectionId: string | undefined
    sendRawQueryEnabled: boolean
    showAgentHints: boolean
    singleStatement: boolean
    singleStatementDisabledReason: string | null
    sourceQuery: DataVisualizationNode
    splitQueryRanges: QueryRange[]
    suggestedQueryInput: string
    suggestedSource: 'hogql_fixer' | 'max_ai' | 'query_history' | null
    suggestionPayload: SuggestionPayload | null
    upstream: {
        edges: DataModelingEdge[]
        modelId: string
        nodes: DataModelingNode[]
    } | null
    upstreamLoadFailed: boolean
    upstreamLoading: boolean
    upstreamViewMode: 'graph' | 'table'
    viewLoading: boolean
    viewQueryLoading: boolean
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface sqlEditorLogicActions {
    loadConnectionOptionsSuccess: (
        connectionOptions: ExternalDataSourceConnectionOptionApi[],
        payload?: any
    ) => {
        connectionOptions: ExternalDataSourceConnectionOptionApi[]
        payload?: any
    } // connectionSelectorLogic
    maybeLoadConnectionOptions: () => {
        value: true
    } // connectionSelectorLogic
    createDataWarehouseSavedQuerySuccess: (
        dataWarehouseSavedQueries: DataWarehouseSavedQuerySummary[],
        payload?:
            | (Partial<DataWarehouseSavedQuery> & {
                  deferCreatedToast?: boolean
                  folder_id?: string | null
                  types: string[][]
              })
            | undefined
    ) => {
        dataWarehouseSavedQueries: DataWarehouseSavedQuerySummary[]
        payload?: Partial<DataWarehouseSavedQuery> & {
            deferCreatedToast?: boolean
            folder_id?: string | null
            types: string[][]
        }
    } // dataWarehouseViewsLogic
    deleteDataWarehouseSavedQuerySuccess: (
        dataWarehouseSavedQueries: DataWarehouseSavedQuerySummary[],
        payload?: string | undefined
    ) => {
        dataWarehouseSavedQueries: DataWarehouseSavedQuerySummary[]
        payload?: string
    } // dataWarehouseViewsLogic
    loadDataWarehouseSavedQueriesSuccess: (
        dataWarehouseSavedQueries: DataWarehouseSavedQuerySummary[],
        payload?: any
    ) => {
        dataWarehouseSavedQueries: DataWarehouseSavedQuerySummary[]
        payload?: any
    } // dataWarehouseViewsLogic
    loadDataWarehouseSavedQueryFolders: () => any // dataWarehouseViewsLogic
    materializeDataWarehouseSavedQuery: (
        viewId: string,
        syncFrequency?: import('~/types').DataModelingSyncInterval | undefined,
        incremental?: DataWarehouseSavedQueryIncremental | null | undefined,
        createdViewName?: string | undefined
    ) => {
        createdViewName: string | undefined
        incremental: DataWarehouseSavedQueryIncremental | null | undefined
        syncFrequency: import('~/types').DataModelingSyncInterval | undefined
        viewId: string
    } // dataWarehouseViewsLogic
    runDataWarehouseSavedQuery: (
        viewId: string,
        fullRefresh?: boolean | undefined
    ) => {
        fullRefresh: boolean | undefined
        viewId: string
    } // dataWarehouseViewsLogic
    updateDataWarehouseSavedQuery: (
        view: import('../saved_queries/dataWarehouseViewsLogic').DataWarehouseSavedQueryUpdate
    ) => import('../saved_queries/dataWarehouseViewsLogic').DataWarehouseSavedQueryUpdate // dataWarehouseViewsLogic
    updateDataWarehouseSavedQueryFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    } // dataWarehouseViewsLogic
    updateDataWarehouseSavedQuerySuccess: (
        dataWarehouseSavedQueries: DataWarehouseSavedQuerySummary[],
        payload?: import('../saved_queries/dataWarehouseViewsLogic').DataWarehouseSavedQueryUpdate | undefined
    ) => {
        dataWarehouseSavedQueries: DataWarehouseSavedQuerySummary[]
        payload?: import('../saved_queries/dataWarehouseViewsLogic').DataWarehouseSavedQueryUpdate
    } // dataWarehouseViewsLogic
    loadDatabase: (
        args_0?:
            | {
                  force?: boolean
                  shallow?: boolean
              }
            | undefined
    ) => {
        force?: boolean
        shallow?: boolean
    } // databaseTableListLogic
    resetConnectionScope: () => {
        value: true
    } // databaseTableListLogic
    setConnection: (connectionId: string | null) => {
        connectionId: string | null
    } // databaseTableListLogic
    deleteDraft: (
        draftId: string,
        viewName?: string | undefined
    ) => {
        draftId: string
        viewName: string | undefined
    } // draftsLogic
    deleteDraftSuccess: (
        draftId: string,
        viewName?: string | undefined
    ) => {
        draftId: string
        viewName: string | undefined
    } // draftsLogic
    saveAsDraft: (
        query: HogQLQuery,
        viewId: string,
        tab: QueryTab
    ) => {
        query: HogQLQuery
        tab: QueryTab
        viewId: string
    } // draftsLogic
    saveAsDraftSuccess: (
        draft: DataWarehouseSavedQueryDraft,
        tab: QueryTab
    ) => {
        draft: DataWarehouseSavedQueryDraft
        tab: QueryTab
    } // draftsLogic
    fixErrors: (
        query: string,
        error?: string | undefined,
        connectionId?: string | undefined
    ) => {
        connectionId: string | undefined
        error: string | undefined
        query: string
    } // fixSQLErrorsLogic
    fixErrorsFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    } // fixSQLErrorsLogic
    fixErrorsSuccess: (
        response: Response,
        payload?:
            | {
                  connectionId: string | undefined
                  error: string | undefined
                  query: string
              }
            | undefined
    ) => {
        payload?: {
            connectionId: string | undefined
            error: string | undefined
            query: string
        }
        response: Response
    } // fixSQLErrorsLogic
    setActiveTab: (tab: OutputTab) => {
        tab: OutputTab
    } // outputPaneLogic
    _setSuggestionPayload: (payload: SuggestionPayload | null) => {
        payload: SuggestionPayload | null
    }
    applyIndexQuickfix: (quickfix: PredicateQuickfix) => {
        quickfix: PredicateQuickfix
    }
    closeAccessControlModal: () => {
        value: true
    }
    closeEditingObject: () => {
        value: true
    }
    closeMaterializationModal: () => {
        value: true
    }
    closeSaveAsMetricModal: () => {
        value: true
    }
    createTab: (
        query?: string,
        view?: DataWarehouseSavedQuery,
        insight?: InsightModel,
        draft?: DataWarehouseSavedQueryDraft,
        metricName?: string,
        biEditorState?: BIEditorState
    ) => {
        biEditorState: BIEditorState | undefined
        draft: DataWarehouseSavedQueryDraft | undefined
        insight: InsightModel<Node<Record<string, any>>> | undefined
        metricName: string | undefined
        query: string | undefined
        view: DataWarehouseSavedQuery | undefined
    }
    deleteInProgressDraftEdit: (draftId: string) => {
        draftId: string
    }
    deleteInProgressViewEdit: (viewId: string) => {
        viewId: string
    }
    discardChanges: () => {
        value: true
    }
    editInsight: (
        query: string,
        insight: InsightModel,
        biEditorState?: BIEditorState
    ) => {
        biEditorState: BIEditorState | undefined
        insight: InsightModel<Node<Record<string, any>>>
        query: string
    }
    editView: (
        query: string,
        view: DataWarehouseSavedQuery,
        biEditorState?: BIEditorState
    ) => {
        biEditorState: BIEditorState | undefined
        query: string
        view: DataWarehouseSavedQuery
    }
    enforceConnectionRawQueryMode: () => {
        value: true
    }
    fixIndexUsageWithAI: (prompt: string) => {
        prompt: string
    }
    initialize: () => {
        value: true
    }
    insertTextAtCursor: (text: string) => {
        text: string
    }
    loadUpstream: (modelId: string) => {
        modelId: string
    }
    loadUpstreamFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    loadUpstreamSuccess: (
        upstream: {
            edges: DataModelingEdge[]
            modelId: string
            nodes: DataModelingNode[]
        },
        payload?: {
            modelId: string
        }
    ) => {
        upstream: {
            edges: DataModelingEdge[]
            modelId: string
            nodes: DataModelingNode[]
        }
        payload?: {
            modelId: string
        }
    }
    onAcceptSuggestedQueryInput: (shouldRunQuery?: boolean) => {
        shouldRunQuery: boolean | undefined
    }
    onRejectSuggestedQueryInput: () => {
        value: true
    }
    openAccessControlModal: (editingAccessControlObject: DataWarehouseAccessControlModalProps) => {
        editingAccessControlObject: DataWarehouseAccessControlModalProps
    }
    openMaterializationModal: (view?: DataWarehouseSavedQuery) => {
        view: DataWarehouseSavedQuery | undefined
    }
    openMetricFromUrl: (
        metricName: string,
        biEditorState: BIEditorState | null
    ) => {
        biEditorState: BIEditorState | null
        metricName: string
    }
    openSaveAsMetricModal: (modal: SaveAsMetricModalState) => {
        modal: SaveAsMetricModalState
    }
    reportAIQueryAccepted: () => {
        value: true
    }
    reportAIQueryPromptOpen: () => {
        value: true
    }
    reportAIQueryPrompted: () => {
        value: true
    }
    reportAIQueryRejected: () => {
        value: true
    }
    reviewEditingViewUpdate: () => {
        value: true
    }
    reviewViewUpdate: (
        view: UpdateViewPayload,
        draftId?: string
    ) => {
        draftId: string | undefined
        view: UpdateViewPayload
    }
    runQuery: (
        queryOverride?: string,
        switchTab?: boolean,
        reuseResults?: boolean
    ) => {
        queryOverride: string | undefined
        reuseResults: boolean
        switchTab: boolean | undefined
    }
    runSubquery: () => {
        value: true
    }
    saveAsEndpoint: () => {
        value: true
    }
    saveAsEndpointSubmit: (
        name: string,
        description?: string,
        queryOverride?: string
    ) => {
        description: string | undefined
        name: string
        queryOverride: string | undefined
    }
    saveAsInsight: () => {
        value: true
    }
    saveAsInsightSubmit: (
        name: string,
        queryOverride?: string
    ) => {
        name: string
        queryOverride: string | undefined
    }
    saveAsMetric: (queryOverride?: string) => {
        queryOverride: string | undefined
    }
    saveAsMetricSubmit: (
        fields: SaveAsMetricFields,
        queryOverride?: string,
        overwrite?: boolean,
        approve?: boolean
    ) => {
        approve: boolean
        fields: SaveAsMetricFields
        overwrite: boolean
        queryOverride: string | undefined
    }
    saveAsView: (
        materializeAfterSave?: any,
        fromDraft?: string
    ) => {
        fromDraft: string | undefined
        materializeAfterSave: any
    }
    saveAsViewSubmit: (
        name: string,
        materializeAfterSave?: any,
        fromDraft?: string,
        folderId?: string | null,
        isTest?: any,
        queryOverride?: string,
        incremental?: DataWarehouseSavedQueryIncremental,
        description?: string
    ) => {
        description: string | undefined
        folderId: string | null | undefined
        fromDraft: string | undefined
        incremental: DataWarehouseSavedQueryIncremental | undefined
        isTest: any
        materializeAfterSave: any
        name: string
        queryOverride: string | undefined
    }
    saveDraft: (
        activeTab: QueryTab,
        queryInput: string,
        viewId: string
    ) => {
        activeTab: QueryTab
        queryInput: string
        viewId: string
    }
    setActiveQueryText: (
        activeQueryText: string | null,
        activeQueryOffset: number
    ) => {
        activeQueryOffset: number
        activeQueryText: string | null
    }
    setDashboardId: (dashboardId: number | null) => {
        dashboardId: number | null
    }
    setDashboardTileGroupKey: (groupKey: string | null) => {
        groupKey: string | null
    }
    setDataError: (error: string | null) => {
        error: string | null
    }
    setEditingInsightDescription: (description: string) => {
        description: string
    }
    setEditingInsightName: (name: string) => {
        name: string
    }
    setEditingMetricName: (metricName: string | null) => {
        metricName: string | null
    }
    setEditorSource: (source: SqlEditorSource) => {
        source: SqlEditorSource
    }
    setError: (error: string | null) => {
        error: string | null
    }
    setExecutionTarget: (executionTarget: HogQLQuery['executionTarget']) => {
        executionTarget: 'default' | 'managed_trino' | undefined
    }
    setFinishedLoading: (loading: boolean) => {
        loading: boolean
    }
    setHoveredNode: (nodeId: string | null) => {
        nodeId: string | null
    }
    setInProgressDraftEdit: (
        draftId: string,
        historyId: string
    ) => {
        draftId: string
        historyId: string
    }
    setInProgressDraftEdits: (inProgressDraftEdits: Record<string, string>) => {
        inProgressDraftEdits: Record<string, string>
    }
    setInProgressViewEdit: (
        viewId: string,
        historyId: string
    ) => {
        historyId: string
        viewId: string
    }
    setInProgressViewEdits: (inProgressViewEdits: Record<string, string>) => {
        inProgressViewEdits: Record<string, string>
    }
    setInsightLoading: (loading: boolean) => {
        loading: boolean
    }
    setLastRunQuery: (lastRunQuery: DataVisualizationNode | null) => {
        lastRunQuery: DataVisualizationNode | null
    }
    setMaterializationModalOpen: (open: boolean) => {
        open: boolean
    }
    setMaterializationModalView: (view: DataWarehouseSavedQuery | null) => {
        view: DataWarehouseSavedQuery | null
    }
    setMetadata: (metadata: HogQLMetadataResponse | null) => {
        metadata: HogQLMetadataResponse | null
    }
    setMetadataLoading: (loading: boolean) => {
        loading: boolean
    }
    setMetricPrefill: (metricPrefill: MetricFormPrefill | null) => {
        metricPrefill: MetricFormPrefill | null
    }
    setMetricUpdating: (updating: boolean) => {
        updating: boolean
    }
    setPlaceholders: (placeholders: SQLEditorPlaceholder[]) => {
        placeholders: SQLEditorPlaceholder[]
    }
    setQueryInput: (queryInput: string | null) => {
        queryInput: string | null
    }
    setQueryModifiers: (queryModifiers: HogQLQueryModifiers | null) => {
        queryModifiers: HogQLQueryModifiers | null
    }
    setSavingMetricAs: (savingMetricAs: MetricSaveAction | null) => {
        savingMetricAs: MetricSaveAction | null
    }
    setSelectedQueryTablesAndColumns: (tablesAndColumns: Record<string, Record<string, boolean>>) => {
        tablesAndColumns: Record<string, Record<string, boolean>>
    }
    setSendRawQuery: (sendRawQuery: boolean) => {
        sendRawQuery: boolean
    }
    setSourceQuery: (sourceQuery: DataVisualizationNode) => {
        sourceQuery: DataVisualizationNode
    }
    setSuggestedQueryInput: (
        suggestedQueryInput: string,
        source?: SuggestionPayload['source']
    ) => {
        source: 'hogql_fixer' | 'max_ai' | 'query_history' | undefined
        suggestedQueryInput: string
    }
    setUpstreamViewMode: (mode: 'graph' | 'table') => {
        mode: 'graph' | 'table'
    }
    setViewLoading: (loading: boolean) => {
        loading: boolean
    }
    setViewQueryLoading: (loading: boolean) => {
        loading: boolean
    }
    syncUrlWithQuery: () => {
        value: true
    }
    updateEditingMetric: () => {
        value: true
    }
    updateInsight: () => {
        value: true
    }
    updateTab: (tab: QueryTab) => {
        tab: QueryTab
    }
    updateView: (
        view: UpdateViewPayload,
        draftId?: string
    ) => {
        draftId: string | undefined
        view: UpdateViewPayload
    }
    updateViewSuccess: (
        view: UpdateViewPayload,
        draftId?: string,
        biEditorState?: BIEditorState
    ) => {
        biEditorState: BIEditorState | undefined
        draftId: string | undefined
        view: UpdateViewPayload
    }
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface sqlEditorLogicMeta {
    key: string
    __keaTypeGenInternalSelectorTypes: {
        editorUrl: (arg: SQLEditorMode | undefined) => string
        placeholderValues: (placeholders: SQLEditorPlaceholder[]) => Record<string, string> | null
        suggestedSource: (
            suggestionPayload: SuggestionPayload | null
        ) => 'hogql_fixer' | 'max_ai' | 'query_history' | null
        diffShowRunButton: (suggestionPayload: SuggestionPayload | null) => boolean | undefined
        acceptText: (suggestionPayload: SuggestionPayload | null) => string
        rejectText: (suggestionPayload: SuggestionPayload | null) => string
        suggestedQueryInput: (suggestionPayload: SuggestionPayload | null, queryInput: string | null) => string
        originalQueryInput: (
            suggestionPayload: SuggestionPayload | null,
            queryInput: string | null
        ) => string | null | undefined
        editingView: (activeTab: QueryTab | null) => DataWarehouseSavedQuery | undefined
        editingMetricName: (activeTab: QueryTab | null) => string | null
        changesToSave: (editingView: DataWarehouseSavedQuery | undefined, queryInput: string | null) => boolean
        hasEditorChanges: (
            activeTab: QueryTab | null,
            queryInput: string | null,
            sourceQuery: DataVisualizationNode
        ) => boolean
        exportContext: (sourceQuery: DataVisualizationNode) => ExportContext
        selectedConnectionId: (sourceQuery: DataVisualizationNode) => string | undefined
        selectedSchemaConnectionId: (
            sourceQuery: DataVisualizationNode,
            selectedConnectionId: string | undefined
        ) => string | undefined
        selectedDirectSource: (
            connectionOptions: ExternalDataSourceConnectionOptionApi[] | null,
            selectedConnectionId: string | undefined
        ) => ExternalDataSourceConnectionOptionApi | undefined
        sendRawQueryEnabled: (sourceQuery: DataVisualizationNode, selectedConnectionId: string | undefined) => boolean
        selectedConnectionSupportsHogQL: (
            connectionOptions: ExternalDataSourceConnectionOptionApi[] | null,
            selectedConnectionId: string | undefined
        ) => boolean
        isEditingMaterializedView: (editingView: DataWarehouseSavedQuery | undefined) => boolean
        splitQueryRanges: (queryInput: string | null) => QueryRange[]
        isMultiQuery: (splitQueryRanges: QueryRange[]) => boolean
        singleStatement: (arg: any) => boolean
        showAgentHints: (arg: any) => boolean
        singleStatementDisabledReason: (singleStatement: boolean, isMultiQuery: boolean) => string | null
        isSourceQueryLastRun: (
            queryInput: string | null,
            lastRunQuery: DataVisualizationNode | null,
            sourceQuery: DataVisualizationNode,
            splitQueryRanges: QueryRange[]
        ) => boolean
        hasFiltersPlaceholder: (queryInput: string | null) => boolean
        filtersPlaceholderBindings: (queryInput: string | null) => string[] | null
        hasQueryInput: (queryInput: string | null) => boolean
        indexReportStale: (
            metadata: HogQLMetadataResponse | null,
            activeQueryText: string | null,
            queryInput: string | null,
            suggestedQueryInput: string,
            metadataLoading: boolean
        ) => boolean
        isEmbeddedMode: (arg: SQLEditorMode | undefined) => boolean
        dataLogicKey: (tabId: string) => string
        isDraft: (activeTab: QueryTab | null) => boolean
        currentDraft: (activeTab: QueryTab | null) => DataWarehouseSavedQueryDraft | null | undefined
        selectedQueryColumns: (
            selectedQueryTablesAndColumns: Record<string, Record<string, boolean>>
        ) => Record<string, boolean>
    }
}

export type sqlEditorLogicType = MakeLogicType<
    sqlEditorLogicValues,
    sqlEditorLogicActions,
    SqlEditorLogicProps,
    sqlEditorLogicMeta
>

function hasSavedQueryDetails(view: DataWarehouseSavedQuerySummary): view is DataWarehouseSavedQuery {
    return 'columns' in view && Array.isArray(view.columns)
}

function schemaLoadOptions(force = false): { force: boolean; shallow: boolean } {
    return { force, shallow: true }
}

export const sqlEditorLogic = kea<sqlEditorLogicType>([
    path(['data-warehouse', 'editor', 'sqlEditorLogic']),
    props({ mode: SQLEditorMode.FullScene } as SqlEditorLogicProps),
    key((props) => props.tabId),
    connect((props: SqlEditorLogicProps) => ({
        values: [
            dataWarehouseViewsLogic,
            ['dataWarehouseSavedQueries', 'dataWarehouseSavedQueryFolders', 'dataWarehouseSavedQueryMapById'],
            userLogic,
            ['user'],
            draftsLogic,
            ['drafts'],
            featureFlagLogic,
            ['featureFlags'],
            connectionSelectorLogic,
            ['connectionOptions'],
            databaseTableListLogic,
            ['database', 'databaseLoading', 'connectionId as databaseConnectionId'],
            outputPaneLogic({ tabId: props.tabId }),
            ['activeTab as outputActiveTab'],
        ],
        actions: [
            dataWarehouseViewsLogic,
            [
                'loadDataWarehouseSavedQueriesSuccess',
                'loadDataWarehouseSavedQueryFolders',
                'deleteDataWarehouseSavedQuerySuccess',
                'createDataWarehouseSavedQuerySuccess',
                'runDataWarehouseSavedQuery',
                'materializeDataWarehouseSavedQuery',
                'updateDataWarehouseSavedQuerySuccess',
                'updateDataWarehouseSavedQueryFailure',
                'updateDataWarehouseSavedQuery',
            ],
            outputPaneLogic({ tabId: props.tabId }),
            ['setActiveTab'],
            fixSQLErrorsLogic,
            ['fixErrors', 'fixErrorsSuccess', 'fixErrorsFailure'],
            draftsLogic,
            ['saveAsDraft', 'deleteDraft', 'saveAsDraftSuccess', 'deleteDraftSuccess'],
            databaseTableListLogic,
            ['setConnection', 'loadDatabase', 'resetConnectionScope'],
            connectionSelectorLogic,
            ['loadConnectionOptionsSuccess', 'maybeLoadConnectionOptions'],
        ],
    })),
    actions(() => ({
        setSelectedQueryTablesAndColumns: (tablesAndColumns: Record<string, Record<string, boolean>>) => ({
            tablesAndColumns,
        }),
        setQueryInput: (queryInput: string | null) => ({ queryInput }),
        discardChanges: true,
        setActiveQueryText: (activeQueryText: string | null, activeQueryOffset: number) => ({
            activeQueryText,
            activeQueryOffset,
        }),
        runQuery: (queryOverride?: string, switchTab?: boolean, reuseResults: boolean = false) => ({
            queryOverride,
            switchTab,
            reuseResults,
        }),
        createTab: (
            query?: string,
            view?: DataWarehouseSavedQuery,
            insight?: InsightModel,
            draft?: DataWarehouseSavedQueryDraft,
            metricName?: string,
            biEditorState?: BIEditorState
        ) => ({
            query,
            view,
            insight,
            draft,
            metricName,
            biEditorState,
        }),
        updateTab: (tab: QueryTab) => ({ tab }),

        initialize: true,
        loadUpstream: (modelId: string) => ({ modelId }),
        saveAsView: (materializeAfterSave = false, fromDraft?: string) => ({
            fromDraft,
            materializeAfterSave,
        }),
        saveAsViewSubmit: (
            name: string,

            materializeAfterSave = false,

            fromDraft?: string,

            folderId?: string | null,
            isTest = false,
            queryOverride?: string,
            incremental?: DataWarehouseSavedQueryIncremental,
            description?: string
        ) => ({
            description,
            name,
            materializeAfterSave,
            fromDraft,
            folderId,
            isTest,
            queryOverride,
            incremental,
        }),
        saveAsInsight: true,
        saveAsInsightSubmit: (name: string, queryOverride?: string) => ({
            name,
            queryOverride,
        }),
        saveAsEndpoint: true,
        saveAsEndpointSubmit: (name: string, description?: string, queryOverride?: string) => ({
            name,
            description,
            queryOverride,
        }),
        saveAsMetric: (queryOverride?: string) => ({ queryOverride }),
        saveAsMetricSubmit: (
            fields: SaveAsMetricFields,
            queryOverride?: string,
            overwrite: boolean = false,
            approve: boolean = true
        ) => ({
            fields,
            queryOverride,
            overwrite,
            approve,
        }),
        openSaveAsMetricModal: (modal: SaveAsMetricModalState) => ({ modal }),
        closeSaveAsMetricModal: true,
        setSavingMetricAs: (savingMetricAs: MetricSaveAction | null) => ({ savingMetricAs }),
        setMetricPrefill: (metricPrefill: MetricFormPrefill | null) => ({ metricPrefill }),
        setEditingMetricName: (metricName: string | null) => ({ metricName }),
        openMetricFromUrl: (metricName: string, biEditorState: BIEditorState | null) => ({ metricName, biEditorState }),
        updateEditingMetric: true,
        setMetricUpdating: (updating: boolean) => ({ updating }),
        updateInsight: true,
        setEditingInsightName: (name: string) => ({ name }),
        setEditingInsightDescription: (description: string) => ({ description }),
        closeEditingObject: true,
        setFinishedLoading: (loading: boolean) => ({ loading }),
        setError: (error: string | null) => ({ error }),
        setDataError: (error: string | null) => ({ error }),
        setSourceQuery: (sourceQuery: DataVisualizationNode) => ({
            sourceQuery,
        }),
        setMetadata: (metadata: HogQLMetadataResponse | null) => ({ metadata }),
        setMetadataLoading: (loading: boolean) => ({ loading }),
        setInsightLoading: (loading: boolean) => ({ loading }),
        setViewLoading: (loading: boolean) => ({ loading }),
        setViewQueryLoading: (loading: boolean) => ({ loading }),
        setMaterializationModalOpen: (open: boolean) => ({ open }),
        setMaterializationModalView: (view: DataWarehouseSavedQuery | null) => ({ view }),
        editView: (query: string, view: DataWarehouseSavedQuery, biEditorState?: BIEditorState) => ({
            query,
            view,
            biEditorState,
        }),
        editInsight: (query: string, insight: InsightModel, biEditorState?: BIEditorState) => ({
            query,
            insight,
            biEditorState,
        }),
        setLastRunQuery: (lastRunQuery: DataVisualizationNode | null) => ({
            lastRunQuery,
        }),
        _setSuggestionPayload: (payload: SuggestionPayload | null) => ({
            payload,
        }),
        setSuggestedQueryInput: (suggestedQueryInput: string, source?: SuggestionPayload['source']) => ({
            suggestedQueryInput,
            source,
        }),
        onAcceptSuggestedQueryInput: (shouldRunQuery?: boolean) => ({
            shouldRunQuery,
        }),
        onRejectSuggestedQueryInput: true,
        reportAIQueryPrompted: true,
        reportAIQueryAccepted: true,
        reportAIQueryRejected: true,
        reportAIQueryPromptOpen: true,
        setInProgressViewEdit: (viewId: string, historyId: string) => ({
            viewId,
            historyId,
        }),
        setInProgressViewEdits: (inProgressViewEdits: Record<string, string>) => ({
            inProgressViewEdits,
        }),
        deleteInProgressViewEdit: (viewId: string) => ({ viewId }),
        setInProgressDraftEdit: (draftId: string, historyId: string) => ({
            draftId,
            historyId,
        }),
        setInProgressDraftEdits: (inProgressDraftEdits: Record<string, string>) => ({
            inProgressDraftEdits,
        }),
        deleteInProgressDraftEdit: (draftId: string) => ({ draftId }),
        reviewEditingViewUpdate: true,
        reviewViewUpdate: (view: UpdateViewPayload, draftId?: string) => ({
            view,
            draftId,
        }),
        updateView: (view: UpdateViewPayload, draftId?: string) => ({
            view,
            draftId,
        }),
        updateViewSuccess: (view: UpdateViewPayload, draftId?: string, biEditorState?: BIEditorState) => ({
            view,
            draftId,
            biEditorState,
        }),
        setUpstreamViewMode: (mode: 'graph' | 'table') => ({ mode }),
        setHoveredNode: (nodeId: string | null) => ({ nodeId }),
        saveDraft: (activeTab: QueryTab, queryInput: string, viewId: string) => ({
            activeTab,
            queryInput,
            viewId,
        }),
        syncUrlWithQuery: true,
        insertTextAtCursor: (text: string) => ({ text }),
        setPlaceholders: (placeholders: SQLEditorPlaceholder[]) => ({ placeholders }),
        setQueryModifiers: (queryModifiers: HogQLQueryModifiers | null) => ({ queryModifiers }),
        applyIndexQuickfix: (quickfix: PredicateQuickfix) => ({ quickfix }),
        fixIndexUsageWithAI: (prompt: string) => ({ prompt }),
        setEditorSource: (source: SqlEditorSource) => ({ source }),
        runSubquery: true,
        setExecutionTarget: (executionTarget: HogQLQuery['executionTarget']) => ({ executionTarget }),
        setSendRawQuery: (sendRawQuery: boolean) => ({ sendRawQuery }),
        enforceConnectionRawQueryMode: true,
        setDashboardId: (dashboardId: number | null) => ({ dashboardId }),
        setDashboardTileGroupKey: (groupKey: string | null) => ({ groupKey }),
        openMaterializationModal: (view?: DataWarehouseSavedQuery) => ({
            view,
        }),
        closeMaterializationModal: true,
        openAccessControlModal: (editingAccessControlObject: DataWarehouseAccessControlModalProps) => ({
            editingAccessControlObject,
        }),
        closeAccessControlModal: true,
    })),
    propsChanged(({ actions, props, cache }, oldProps) => {
        if (oldProps.editor && oldProps.editor !== props.editor) {
            clearQueryOutlineOverlay(cache, oldProps.editor)
        }

        if (
            (!oldProps.monaco || !oldProps.editor || oldProps.editor !== props.editor) &&
            props.monaco &&
            props.editor
        ) {
            actions.initialize()

            if (cache.pendingUrlOpen) {
                // propsChanged runs inside the SQLEditor render, so open the URL target after the render
                cache.disposables.add(() => {
                    const timeoutId = window.setTimeout(() => {
                        const pendingUrlOpen = cache.pendingUrlOpen
                        cache.pendingUrlOpen = null
                        void pendingUrlOpen?.()
                    }, 0)
                    return () => window.clearTimeout(timeoutId)
                }, 'pendingUrlOpen')
            }

            // Listen for cursor position changes to update the active query highlight.
            // Debounced because each run can fire a HogQLMetadata request for the current
            // subquery, which is too expensive to do on every arrow key.
            cache.cursorDisposable?.dispose()
            cache.cursorDisposable = props.editor.onDidChangeCursorPosition(() => {
                cache.scheduleActiveQueryDecoration?.()
            })

            // Set up the active-query outline overlay. We render a single `div` parented
            // to Monaco's overlay layer (viewport-fixed) and reposition it on scroll/layout.
            const editorInstance = props.editor
            const outlineNode = document.createElement('div')
            outlineNode.className = 'active-query-outline'
            outlineNode.style.position = 'absolute'
            outlineNode.style.display = 'none'
            clearQueryOutlineOverlay(cache, editorInstance)
            const outlineWidget: editor.IOverlayWidget = {
                getId: () => `sql-editor.active-query-outline.${props.tabId || 'default'}`,
                getDomNode: () => outlineNode,
                // Returning `null` keeps the widget unanchored — we drive its position
                // manually via inline `top`/`left` styles set in `renderQueryOutline`.
                getPosition: () => null,
            }
            editorInstance.removeOverlayWidget(outlineWidget)
            editorInstance.addOverlayWidget(outlineWidget)
            cache.queryOutlineWidget = outlineWidget
            cache.queryOutlineEditor = editorInstance
            cache.queryOutlineNode = outlineNode

            cache.updateQueryOutline = (range: IRange | null): void => {
                cache.queryOutlineRange = range
                if (!range) {
                    outlineNode.style.display = 'none'
                    return
                }
                renderQueryOutline(editorInstance, outlineNode, range)
            }

            // Reposition the overlay on scroll and layout/resize. These don't change the
            // range, only its pixel coordinates, so we skip the SQL parsing path entirely.
            // Monaco fires scroll events per wheel tick, several per frame, and repositioning
            // reads editor geometry — so coalesce to one render per frame.
            cache.scheduleOutlineRender = (): void => {
                if (cache.outlineRafId != null) {
                    return
                }
                cache.outlineRafId = requestAnimationFrame(() => {
                    cache.outlineRafId = null
                    if (cache.queryOutlineRange) {
                        renderQueryOutline(editorInstance, outlineNode, cache.queryOutlineRange)
                    }
                })
            }
            cache.scrollDisposable?.dispose()
            cache.scrollDisposable = editorInstance.onDidScrollChange(() => {
                cache.scheduleOutlineRender?.()
            })
            cache.layoutDisposable?.dispose()
            cache.layoutDisposable = editorInstance.onDidLayoutChange(() => {
                cache.scheduleOutlineRender?.()
            })
        }
    }),
    loaders(() => ({
        upstream: [
            null as { modelId: string; nodes: DataModelingNode[]; edges: DataModelingEdge[] } | null,
            {
                loadUpstream: async (payload: { modelId: string }) => {
                    const lineage = await api.dataModelingNodes.lineage({ savedQueryId: payload.modelId })
                    return { modelId: payload.modelId, ...lineage }
                },
            },
        ],
    })),
    reducers(({ props }) => ({
        upstream: {
            // The value is shared across views, so a new load must not leave the previous graph on screen.
            loadUpstream: () => null,
        },
        upstreamLoadFailed: [
            false,
            {
                loadUpstream: () => false,
                loadUpstreamSuccess: () => false,
                loadUpstreamFailure: () => true,
            },
        ],
        selectedQueryTablesAndColumns: [
            {} as Record<string, Record<string, boolean>>,
            {
                setSelectedQueryTablesAndColumns: (_, { tablesAndColumns }) => tablesAndColumns,
            },
        ],
        finishedLoading: [
            true,
            {
                setFinishedLoading: (_, { loading }) => loading,
            },
        ],
        sourceQuery: [
            {
                kind: NodeKind.DataVisualizationNode,
                source: {
                    kind: NodeKind.HogQLQuery,
                    query: '',
                },
                display: ChartDisplayType.Auto,
            } as DataVisualizationNode,
            {
                setSourceQuery: (_, { sourceQuery }) => sanitizeSourceQuery(sourceQuery),
            },
        ],
        placeholders: [
            [] as SQLEditorPlaceholder[],
            {
                setPlaceholders: (_, { placeholders }) => placeholders,
            },
        ],
        queryModifiers: [
            null as HogQLQueryModifiers | null,
            {
                setQueryModifiers: (_, { queryModifiers }) => queryModifiers,
            },
        ],
        lastRunQuery: [
            null as DataVisualizationNode | null,
            {
                setLastRunQuery: (_, { lastRunQuery }) => lastRunQuery,
            },
        ],
        queryInput: [
            null as string | null,
            {
                setQueryInput: (_, { queryInput }) => queryInput,
            },
        ],
        activeQueryText: [
            null as string | null,
            {
                setActiveQueryText: (_, { activeQueryText }) => activeQueryText,
            },
        ],
        activeQueryOffset: [
            0 as number,
            {
                setActiveQueryText: (_, { activeQueryOffset }) => activeQueryOffset,
            },
        ],
        editorSource: [
            'insight' as SqlEditorSource,
            {
                setEditorSource: (_, { source }) => source,
            },
        ],
        metricPrefill: [
            null as MetricFormPrefill | null,
            {
                setMetricPrefill: (_, { metricPrefill }) => metricPrefill,
            },
        ],
        saveAsMetricModal: [
            null as SaveAsMetricModalState | null,
            {
                openSaveAsMetricModal: (_, { modal }) => modal,
                closeSaveAsMetricModal: () => null,
            },
        ],
        savingMetricAs: [
            null as MetricSaveAction | null,
            {
                setSavingMetricAs: (_, { savingMetricAs }) => savingMetricAs,
            },
        ],
        dashboardId: [
            null as number | null,
            {
                setDashboardId: (_, { dashboardId }) => dashboardId,
            },
        ],
        dashboardTileGroupKey: [
            null as string | null,
            {
                setDashboardTileGroupKey: (_, { groupKey }) => groupKey,
                setDashboardId: (state, { dashboardId }) => (dashboardId === null ? null : state),
            },
        ],
        materializationModalOpen: [
            false,
            {
                setMaterializationModalOpen: (_, { open }) => open,
                closeMaterializationModal: () => false,
            },
        ],
        materializationModalView: [
            null as DataWarehouseSavedQuery | null,
            {
                setMaterializationModalView: (_, { view }) => view,
                closeMaterializationModal: () => null,
            },
        ],
        accessControlModalOpen: [
            false,
            {
                openAccessControlModal: () => true,
                closeAccessControlModal: () => false,
            },
        ],
        editingAccessControlObject: [
            null as DataWarehouseAccessControlModalProps | null,
            {
                openAccessControlModal: (_, { editingAccessControlObject }) => editingAccessControlObject,
                closeAccessControlModal: () => null,
            },
        ],
        editingInsight: [
            null as InsightModel | null,
            {
                updateTab: (_, { tab }) => tab.insight ?? null,
            },
        ],
        viewLoading: [
            false,
            {
                setViewLoading: (_, { loading }) => loading,
            },
        ],
        // Scoped to the editor "open a view" flow so the editor-pane overlay does not flash
        // during the materialization modal's own (also viewLoading-gated) fetch.
        viewQueryLoading: [
            false,
            {
                setViewQueryLoading: (_, { loading }) => loading,
            },
        ],
        insightLoading: [
            false,
            {
                setInsightLoading: (_, { loading }) => loading,
            },
        ],
        metricUpdating: [
            false,
            {
                setMetricUpdating: (_, { updating }) => updating,
            },
        ],
        activeTab: [
            null as QueryTab | null,
            {
                updateTab: (_, { tab }) => tab,
            },
        ],
        error: [
            null as string | null,
            {
                setError: (_, { error }) => error,
            },
        ],
        metadataLoading: [
            true,
            {
                setMetadataLoading: (_, { loading }) => loading,
            },
        ],
        metadata: [
            null as HogQLMetadataResponse | null,
            {
                setMetadata: (_, { metadata }) => metadata,
            },
        ],
        editorKey: [`hogql-editor-${props.tabId}`, {}],
        suggestionPayload: [
            null as SuggestionPayload | null,
            {
                _setSuggestionPayload: (_, { payload }) => payload,
            },
        ],
        // if a view edit starts, store the historyId in the state
        inProgressViewEdits: [
            {} as Record<string, string>,
            {
                setInProgressViewEdit: (state, { viewId, historyId }) => ({
                    ...state,
                    [viewId]: historyId,
                }),
                deleteInProgressViewEdit: (state, { viewId }) => {
                    const newInProgressViewEdits = { ...state }
                    delete newInProgressViewEdits[viewId]
                    return newInProgressViewEdits
                },
                setInProgressViewEdits: (_, { inProgressViewEdits }) => inProgressViewEdits,
            },
        ],
        inProgressDraftEdits: [
            {} as Record<string, string>,
            {
                setInProgressDraftEdit: (state, { draftId, historyId }) => ({
                    ...state,
                    [draftId]: historyId,
                }),
                deleteInProgressDraftEdit: (state, { draftId }) => {
                    const newInProgressDraftEdits = { ...state }
                    delete newInProgressDraftEdits[draftId]
                    return newInProgressDraftEdits
                },
                setInProgressDraftEdits: (_, { inProgressDraftEdits }) => inProgressDraftEdits,
            },
        ],
        fixErrorsError: [
            null as string | null,
            {
                setQueryInput: () => null,
                fixErrorsFailure: (_, { error }) => error,
            },
        ],
        upstreamViewMode: [
            'graph' as 'graph' | 'table',
            {
                setUpstreamViewMode: (_: 'graph' | 'table', { mode }: { mode: 'graph' | 'table' }) => mode,
            },
        ],
        hoveredNode: [
            null as string | null,
            {
                setHoveredNode: (_, { nodeId }) => nodeId,
            },
        ],
    })),
    listeners(({ values, props, actions, asyncActions, cache }) => {
        const persistEditorDraft = (): void => {
            if (
                values.isEmbeddedMode ||
                values.queryInput === null ||
                !values.activeTab ||
                values.activeTab.metricName
            ) {
                return
            }
            const { draft, view, insight } = values.activeTab
            const target = draft
                ? `draft:${draft.id}`
                : view
                  ? `view:${view.id}`
                  : insight
                    ? `insight:${insight.short_id}`
                    : 'new'
            const storage = sqlEditorDraftStorage(
                values.user?.uuid,
                teamLogic.values.currentTeamId,
                props.mode === SQLEditorMode.BusinessIntelligence ? `bi:${target}` : target
            )
            const savedQuery =
                draft?.query.query ?? view?.query?.query ?? toDataVisualizationNode(insight?.query)?.source.query
            if (savedQuery !== undefined && values.queryInput === savedQuery) {
                storage?.set(null)
                return
            }
            storage?.set({
                ...getTabHash(values),
                q: values.queryInput,
                baseline_query: view?.query?.query,
                edited_history_id: view
                    ? (values.inProgressViewEdits[view.id] ?? view.latest_history_id ?? undefined)
                    : undefined,
            })
        }

        // Extract cursor offset and selection text from monaco and defer to the pure helper.
        const resolveSaveCandidates = (): ReturnType<typeof resolveSaveCandidatesPure> => {
            const fullText = values.queryInput ?? ''
            const editorInstance = props.editor
            let cursorOffset: number | null = null
            let selectionText: string | null = null

            if (editorInstance) {
                const model = editorInstance.getModel()
                const selection = editorInstance.getSelection()
                if (model && selection && !selection.isEmpty()) {
                    selectionText = model.getValueInRange(selection)
                }
                const position = editorInstance.getPosition()
                if (model && position) {
                    cursorOffset = model.getOffsetAt(position)
                }
            }

            return resolveSaveCandidatesPure(fullText, cursorOffset, selectionText)
        }
        const getActiveBIEditorState = (): BIEditorState | undefined =>
            props.mode === SQLEditorMode.BusinessIntelligence && values.featureFlags[FEATURE_FLAGS.SQL_EDITOR_BI_MODE]
                ? values.activeTab?.biEditorState
                : undefined

        return {
            fixErrorsSuccess: ({ response }) => {
                actions.setSuggestedQueryInput(response.query, 'hogql_fixer')

                posthog.capture('ai-error-fixer-success', {
                    trace_id: response.trace_id,
                })
            },
            fixErrorsFailure: () => {
                posthog.capture('ai-error-fixer-failure')
            },
            reportAIQueryPrompted: () => {
                posthog.capture('ai_query_prompted')
            },
            reportAIQueryAccepted: () => {
                posthog.capture('ai_query_accepted')
            },
            reportAIQueryRejected: () => {
                posthog.capture('ai_query_rejected')
            },
            reportAIQueryPromptOpen: () => {
                posthog.capture('ai_query_prompt_open')
            },
            applyIndexQuickfix: ({ quickfix }) => {
                const editor = props.editor
                const model = editor?.getModel()
                if (!editor || !model) {
                    return
                }
                // The offsets describe the SQL the server analyzed. Once the text has moved on they
                // would land the edit somewhere else, so wait for the next report instead of guessing.
                if (values.indexReportStale) {
                    return
                }
                // The offsets count characters; Monaco counts UTF-16 units. Convert against the
                // analyzed statement before adding its offset, which the editor already measures
                // in Monaco's units.
                const analyzed = values.activeQueryText ?? (values.suggestedQueryInput || values.queryInput) ?? ''
                // The model is the authority on what is being edited, and it is not always the text
                // the report describes: with a suggestion open, `props.editor` is the diff's modified
                // editor holding the suggested query while the offsets index the text behind it.
                // Splicing there would corrupt the suggestion, so confirm the analyzed text is still
                // sitting where the offsets say before writing anything.
                if (
                    model.getValue().slice(values.activeQueryOffset, values.activeQueryOffset + analyzed.length) !==
                    analyzed
                ) {
                    lemonToast.info('Still checking the latest version of this query. Try again in a moment.')
                    return
                }
                const start = model.getPositionAt(
                    characterOffsetToUtf16(analyzed, quickfix.start) + values.activeQueryOffset
                )
                const end = model.getPositionAt(
                    characterOffsetToUtf16(analyzed, quickfix.end) + values.activeQueryOffset
                )
                editor.executeEdits('index-quickfix', [
                    {
                        range: {
                            startLineNumber: start.lineNumber,
                            startColumn: start.column,
                            endLineNumber: end.lineNumber,
                            endColumn: end.column,
                        },
                        text: quickfix.text,
                    },
                ])
                posthog.capture('sql-editor-index-quickfix-applied')
            },
            fixIndexUsageWithAI: ({ prompt }) => {
                // The prompt names a filter the server found in the text it analyzed. Sending it with
                // newer text asks for a rewrite of a filter that may no longer be there. The editor
                // lightbulb can still offer the action in that window, so the guard lives here rather
                // than only on the table button, and it says why instead of doing nothing.
                if (values.indexReportStale) {
                    lemonToast.info('Still checking the latest version of this query. Try again in a moment.')
                    return
                }
                // The error fixer takes free text as its "error", so an index instruction rides the
                // same suggestion flow and lands as a reviewable diff rather than a silent rewrite.
                actions.fixErrors(values.queryInput ?? '', prompt, values.selectedConnectionId)
                posthog.capture('sql-editor-index-fix-with-ai')
            },
            insertTextAtCursor: ({ text }) => {
                const editor = props.editor
                if (!editor) {
                    return
                }

                const position = editor.getPosition()
                if (!position) {
                    return
                }

                editor.executeEdits('insert-variable', [
                    {
                        range: {
                            startLineNumber: position.lineNumber,
                            startColumn: position.column,
                            endLineNumber: position.lineNumber,
                            endColumn: position.column,
                        },
                        text,
                    },
                ])

                // Move cursor to end of inserted text
                editor.setPosition({
                    lineNumber: position.lineNumber,
                    column: position.column + text.length,
                })

                editor.focus()
            },
            setSuggestedQueryInput: ({ suggestedQueryInput, source }) => {
                // If there's no active tab, create one first to ensure Monaco Editor is available.
                // Embedded mode has no tabs at all — falling into createTab would replace the query
                // outright instead of showing the accept/reject diff.
                if (!values.activeTab && !values.isEmbeddedMode) {
                    actions.createTab(suggestedQueryInput)
                    return
                }

                const isQueryHistory = source === 'query_history'
                if (isQueryHistory) {
                    // Accept/cancel of the restore is captured via sql-editor-accepted/rejected-suggestion
                    posthog.capture('sql-editor-history-restore-initiated')
                }

                // Always create suggestion payload when a new suggestion comes in, even for consecutive suggestions
                // Only skip diff mode if the editor is completely empty
                if (values.queryInput && values.queryInput.trim() !== '') {
                    actions._setSuggestionPayload({
                        suggestedValue: suggestedQueryInput,
                        originalValue: values.queryInput, // Store the current content as original for diff mode
                        acceptText: isQueryHistory ? queryHistorySuggestionOnAcceptText : aiSuggestionOnAcceptText,
                        rejectText: isQueryHistory ? queryHistorySuggestionOnRejectText : aiSuggestionOnRejectText,
                        onAccept: isQueryHistory ? queryHistorySuggestionOnAccept : aiSuggestionOnAccept,
                        onReject: isQueryHistory ? queryHistorySuggestionOnReject : aiSuggestionOnReject,
                        source,
                        diffShowRunButton: true,
                    })
                } else {
                    actions.setQueryInput(suggestedQueryInput)
                }
            },
            onAcceptSuggestedQueryInput: ({ shouldRunQuery }) => {
                values.suggestionPayload?.onAccept(!!shouldRunQuery, actions, values, props)

                // Write the accepted query onto the tab's persistent model as one undoable
                // edit. The model survives the diff <-> editor swap (keepCurrentModel), so its
                // existing undo history is preserved and cmd+z walks back through the accepted
                // query to the pre-AI query and the rest of the edit history.
                applyUndoableModelEdit(props.monaco, values.activeTab?.uri, values.queryInput ?? '')

                posthog.capture('sql-editor-accepted-suggestion', {
                    source: values.suggestedSource,
                })
                actions._setSuggestionPayload(null)
            },
            onRejectSuggestedQueryInput: () => {
                values.suggestionPayload?.onReject(actions, values, props)

                // Keep the persistent model's content in sync with the reverted query (the
                // suggestion was shown in a throwaway diff model, not this one). This is a
                // no-op when the model already matches, so rejecting adds no undo step.
                applyUndoableModelEdit(props.monaco, values.activeTab?.uri, values.queryInput ?? '')

                posthog.capture('sql-editor-rejected-suggestion', {
                    source: values.suggestedSource,
                })
                actions._setSuggestionPayload(null)
            },
            editView: ({ query, view, biEditorState }) => {
                actions.createTab(query, view, undefined, undefined, undefined, biEditorState)
            },
            editInsight: ({ query, insight, biEditorState }) => {
                actions.createTab(query, undefined, insight, undefined, undefined, biEditorState)
            },
            createTab: async ({ query, view, insight, draft, metricName, biEditorState }) => {
                // Use tabId to ensure each browser tab has its own unique Monaco model
                const tabName = insight ? (insight.name ?? NEW_QUERY) : draft?.name || view?.name || NEW_QUERY
                const tabDescription = insight?.description ?? ''
                const rawInsightVisualizationQuery = toDataVisualizationNode(insight?.query)
                const insightVisualizationQuery = rawInsightVisualizationQuery
                    ? sanitizeSourceQuery(rawInsightVisualizationQuery)
                    : undefined

                if (props.monaco) {
                    const uri = props.monaco.Uri.parse(tabModelPath(props.tabId))
                    let model = props.monaco.editor.getModel(uri)
                    if (!model) {
                        model = props.monaco.editor.createModel(query ?? '', 'hogQL', uri)
                        cache.createdModels = cache.createdModels || []
                        cache.createdModels.push(model)
                        if (isEditorAlive(props.editor)) {
                            props.editor.setModel(model)
                        }
                        initModel(
                            model,
                            codeEditorLogic({
                                key: `hogql-editor-${props.tabId}`,
                                query: values.sourceQuery?.source.query ?? '',
                                language: 'hogQL',
                                indexUsage: true,
                            })
                        )
                    }
                }
                actions.updateTab({
                    uri: props.monaco?.Uri.parse(tabModelPath(props.tabId)),
                    view,
                    insight,
                    name: tabName,
                    description: tabDescription,
                    sourceQuery: insightVisualizationQuery ?? (view ? hogQLEditorSourceQuery(view.query) : undefined),
                    draft,
                    metricName,
                    biEditorState:
                        props.mode === SQLEditorMode.BusinessIntelligence
                            ? {
                                  editorView: BIEditorView.BI,
                                  config: biEditorState?.config ?? {
                                      ...DEFAULT_BI_CONFIG,
                                      rows: [],
                                      columns: [],
                                      values: [],
                                      filters: [],
                                  },
                              }
                            : biEditorState,
                })
                if (insightVisualizationQuery) {
                    actions.setLastRunQuery(insightVisualizationQuery)
                } else if (view) {
                    actions.setSourceQuery(hogQLEditorSourceQuery(view.query))
                }
                if (query !== undefined) {
                    actions.setQueryInput(query)
                } else if (draft) {
                    actions.setQueryInput(draft.query.query)
                } else if (view) {
                    actions.setQueryInput(view.query?.query ?? '')
                } else if (insightVisualizationQuery) {
                    actions.setQueryInput(insightVisualizationQuery.source.query || '')
                }

                // Opening another query can replace sourceQuery without changing the connection,
                // so the schema scope subscription does not run again.
                actions.enforceConnectionRawQueryMode()

                // Focus the editor after creating a new tab
                if (isEditorAlive(props.editor)) {
                    props.editor.focus()
                }
            },
            setSourceQuery: ({ sourceQuery }) => {
                if (!values.activeTab) {
                    return
                }

                const nextSourceQuery = sanitizeSourceQuery(sourceQuery)
                const currentTab = values.activeTab
                if (currentTab) {
                    actions.updateTab({
                        ...currentTab,
                        sourceQuery: nextSourceQuery,
                    })
                }
                persistEditorDraft()
            },
            setExecutionTarget: ({ executionTarget }) => {
                posthog.capture('sql-editor-execution-target-selected', {
                    execution_target: executionTarget ?? 'default',
                })
                actions.setSourceQuery({
                    ...values.sourceQuery,
                    source: {
                        ...values.sourceQuery.source,
                        query: values.queryInput ?? values.sourceQuery.source.query,
                        executionTarget,
                        connectionId: undefined,
                        sendRawQuery: executionTarget === 'managed_trino' ? true : undefined,
                    },
                })
                actions.syncUrlWithQuery()
            },
            setSendRawQuery: ({ sendRawQuery }) => {
                posthog.capture('sql-editor-query-mode-selected', {
                    mode: sendRawQuery ? 'raw' : 'hogql',
                    execution_target: values.sourceQuery.source.executionTarget ?? 'default',
                })
                const currentSourceQuery = values.sourceQuery

                actions.setSourceQuery({
                    ...currentSourceQuery,
                    source: {
                        ...currentSourceQuery.source,
                        sendRawQuery: sendRawQuery || undefined,
                    },
                })
                actions.syncUrlWithQuery()
            },
            enforceConnectionRawQueryMode: () => {
                // Raw-only connections cannot compile HogQL, so force raw SQL mode.
                // Trino and the managed warehouse default to raw so native SQL reaches the engine unchanged.
                // They still advertise HogQL support, which keeps the mode toggle available.
                if (values.selectedConnectionId && !values.sourceQuery.source.sendRawQuery) {
                    const option = (values.connectionOptions ?? []).find(
                        (option) => option.id === values.selectedConnectionId
                    )
                    const isManagedWarehouseSource =
                        option?.prefix === MANAGED_WAREHOUSE_SOURCE_PREFIX && option?.source_type === 'Postgres'
                    // The serializer only sets `engine` for sources that report connection
                    // metadata, and Trino does not, so key off the source type instead.
                    const defaultsToRawQuery = isManagedWarehouseSource || option?.source_type === 'Trino'

                    if (!values.selectedConnectionSupportsHogQL || defaultsToRawQuery) {
                        actions.setSendRawQuery(true)
                    }
                }
            },
            // Options can load after a connection was restored from the URL.
            loadConnectionOptionsSuccess: () => {
                actions.enforceConnectionRawQueryMode()
            },
            runSubquery: async () => {
                if (!props.editor) {
                    actions.runQuery()
                    return
                }
                const model = props.editor.getModel()
                const position = props.editor.getPosition()
                if (!model || !position) {
                    actions.runQuery()
                    return
                }

                const fullText = values.queryInput ?? ''
                const queries = splitQueries(fullText)
                const cursorOffset = model.getOffsetAt(position)
                const activeQuery = findQueryAtCursor(queries, cursorOffset)

                if (!activeQuery) {
                    actions.runQuery()
                    return
                }

                const subquery = await findInnermostSelectAtOffset(activeQuery.query, cursorOffset, activeQuery.start)

                const rangeToRun = subquery ?? activeQuery

                // Flash highlight on the subquery/query about to run
                const startPos = model.getPositionAt(rangeToRun.start)
                const endPos = model.getPositionAt(rangeToRun.end)
                cache.activeQueryDecorationIds = props.editor.deltaDecorations(cache.activeQueryDecorationIds ?? [], [
                    {
                        range: {
                            startLineNumber: startPos.lineNumber,
                            startColumn: startPos.column,
                            endLineNumber: endPos.lineNumber,
                            endColumn: endPos.column,
                        },
                        options: {
                            className: 'active-query-highlight-flash',
                        },
                    },
                ])

                // Remove flash after a short delay and restore normal decoration.
                // Track the timeout so we can clear it on unmount (avoids touching a disposed editor).
                if (cache.activeQueryFlashTimeout) {
                    window.clearTimeout(cache.activeQueryFlashTimeout)
                }
                cache.activeQueryFlashTimeout = window.setTimeout(() => {
                    cache.activeQueryFlashTimeout = null
                    cache.updateActiveQueryDecoration?.()
                }, 600)

                actions.runQuery(rangeToRun.query)
            },
            initialize: async () => {
                actions.setFinishedLoading(false)
            },
            setQueryInput: async ({ queryInput }, breakpoint) => {
                // Keep suggestion payload active - let user make edits and then decide to approve/reject
                // if editing a view, track latest history id changes are based on
                if (values.activeTab?.view && values.activeTab?.view.query?.query) {
                    if (queryInput === values.activeTab.view?.query?.query) {
                        actions.deleteInProgressViewEdit(values.activeTab.view.id)
                    } else if (
                        !values.inProgressViewEdits[values.activeTab.view.id] &&
                        values.activeTab.view.latest_history_id
                    ) {
                        actions.setInProgressViewEdit(values.activeTab.view.id, values.activeTab.view.latest_history_id)
                    }
                }

                // Write before the debounce so navigation or reload cannot drop the last edit.
                persistEditorDraft()
                await breakpoint(500)

                actions.syncUrlWithQuery()
            },
            saveDraft: async ({ queryInput, viewId }) => {
                if (values.activeTab) {
                    actions.saveAsDraft(
                        {
                            ...values.sourceQuery.source,
                            query: queryInput,
                        },
                        viewId,
                        values.activeTab
                    )
                }
            },
            saveAsDraftSuccess: ({ draft, tab: tabToUpdate }) => {
                actions.updateTab({
                    ...tabToUpdate,
                    name: draft.name,
                    draft: draft,
                })
            },
            runQuery: ({ queryOverride, switchTab, reuseResults }) => {
                // Cmd+Enter reaches this listener even while the run button is disabled
                if (values.singleStatementDisabledReason) {
                    return
                }
                const biEditorState = getActiveBIEditorState()
                if (
                    !queryOverride &&
                    biEditorState?.editorView === BIEditorView.BI &&
                    biEditorState.config.filters.some(getBIFilterValidationError)
                ) {
                    actions.setError('Fix invalid worksheet filters before running the query.')
                    return
                }
                captureBIEditorQueryRun(biEditorState)
                const biQuery =
                    !queryOverride && biEditorState?.editorView === BIEditorView.BI
                        ? buildBIQuery(biEditorState.config)
                        : null

                let query: string
                if (queryOverride) {
                    // Explicit override (e.g. user selected text and pressed Cmd+Enter)
                    query = queryOverride
                } else if (biQuery) {
                    query = biQuery.query
                } else {
                    // No override — find the query under the cursor
                    const fullText = values.queryInput ?? ''
                    const queries = splitQueries(fullText)
                    if (queries.length > 1 && props.editor) {
                        const model = props.editor.getModel()
                        const position = props.editor.getPosition()
                        if (model && position) {
                            const cursorOffset = model.getOffsetAt(position)
                            const match = findQueryAtCursor(queries, cursorOffset)
                            query = match?.query ?? fullText
                        } else {
                            query = fullText
                        }
                    } else {
                        query = fullText
                    }
                }

                if (biQuery && query !== values.queryInput) {
                    actions.setQueryInput(query)
                }
                const newSource = normalizeRawQuerySource({
                    ...values.sourceQuery.source,
                    ...biQuery?.node.source,
                    query,
                })

                // Tag only the executed query — keeping tags out of sourceQuery so saved
                // insights/views and change detection never pick them up
                const executedSource: HogQLQuery = {
                    ...newSource,
                    // Like tags, the host's preview values and modifiers stay out of sourceQuery so it never saves them
                    ...(values.placeholderValues
                        ? { values: { ...newSource.values, ...values.placeholderValues } }
                        : {}),
                    ...(values.queryModifiers
                        ? { modifiers: { ...newSource.modifiers, ...values.queryModifiers } }
                        : {}),
                    tags: { ...newSource.tags, productKey: 'sql_editor' },
                }

                const nextSourceQuery: DataVisualizationNode = {
                    ...values.sourceQuery,
                    ...biQuery?.node,
                    chartSettings: biQuery?.node.chartSettings
                        ? {
                              ...values.sourceQuery.chartSettings,
                              ...biQuery.node.chartSettings,
                              heatmap: {
                                  ...values.sourceQuery.chartSettings?.heatmap,
                                  ...biQuery.node.chartSettings.heatmap,
                              },
                          }
                        : values.sourceQuery.chartSettings,
                    source: newSource,
                }
                actions.setSourceQuery(nextSourceQuery)
                actions.setLastRunQuery(nextSourceQuery)
                const dataProps: DataNodeLogicProps = {
                    key: values.dataLogicKey,
                    query: executedSource,
                    autoLoad: false,
                    ...(reuseResults ? { retainResponseOnUnmount: true } : {}),
                }
                if (!cache.umountDataNode) {
                    cache.umountDataNode = dataNodeLogic(dataProps).mount()
                }

                dataNodeLogic(dataProps).actions.loadData(
                    reuseResults || switchTab ? 'async' : 'force_async',
                    undefined,
                    executedSource
                )

                // Mark the first query task as complete when the query is run
                globalSetupLogic.findMounted()?.actions.markTaskAsCompleted(SetupTaskId.RunFirstQuery)
                const compactQuery = query.replace(/\s+/g, ' ').trim()
                const truncated = compactQuery.length > 80 ? compactQuery.slice(0, 77) + '…' : compactQuery
                if (values.showAgentHints) {
                    tryShowMCPHint(
                        'sql.execute',
                        truncated ? { derivedPrompt: `Run this SQL: ${truncated}` } : undefined
                    )
                }
            },
            saveAsView: async ({ fromDraft, materializeAfterSave = false }) => {
                const isStaff = values.user?.is_staff ?? false
                const candidates = resolveSaveCandidates()
                const selectedRef = {
                    current: candidates.queries[candidates.initialIndex],
                }
                const selectionProblem = await findSelectionProblem(candidates, values.sendRawQueryEnabled)
                const isRawTrinoSave =
                    values.sourceQuery.source.executionTarget === 'managed_trino' &&
                    !!values.sourceQuery.source.sendRawQuery

                const folderOptions: { value: string | null; label: string }[] = [
                    { value: null, label: 'No folder' },
                    ...values.dataWarehouseSavedQueryFolders.map((folder) => ({
                        value: folder.id,
                        label: folder.name,
                    })),
                ]
                const createFolderAndSelect = async (onSelect: (newValue: string | null) => void): Promise<void> => {
                    LemonDialog.openForm({
                        title: 'New folder',
                        initialValues: { folderName: '' },
                        content: (
                            <LemonField name="folderName">
                                <LemonInput placeholder="Enter a folder name" autoFocus />
                            </LemonField>
                        ),
                        errors: {
                            folderName: (name) => (!name?.trim() ? 'You must enter a folder name' : undefined),
                        },
                        onSubmit: async ({ folderName }) => {
                            const folder = await api.dataWarehouseSavedQueryFolders.create({ name: folderName.trim() })
                            folderOptions.splice(folderOptions.length - 1, 0, {
                                value: folder.id,
                                label: folder.name,
                            })
                            actions.loadDataWarehouseSavedQueryFolders()
                            onSelect(folder.id)
                            lemonToast.success('Folder created')
                        },
                        shouldAwaitSubmit: true,
                    })
                }

                posthog.capture('save as view dialog opened')
                LemonDialog.openForm({
                    title: 'Save as view',
                    showErrorsOnTouch: true,
                    initialValues: {
                        saveTarget: candidates.initialIndex,
                        viewName: values.activeTab?.name || '',
                        description: '',
                        folderId: null,
                        isTest: false,
                        materializeAfterSave: isRawTrinoSave ? false : materializeAfterSave,
                        incrementalEnabled: false,
                        incrementalKey: null,
                        incrementalUniqueKey: [],
                        incrementalLookbackSeconds: 0,
                    },
                    description: `View names must start with a letter, '_', or '$' and can only contain letters, numbers, '_', '.', or '$'. Spaces are not allowed.`,
                    content: (isLoading) =>
                        isLoading ? (
                            <div className="h-[37px] flex items-center">
                                <ViewEmptyState />
                            </div>
                        ) : (
                            <>
                                <LemonField name="saveTarget">
                                    {({ onChange }) => (
                                        <SaveTargetCycler
                                            candidates={candidates}
                                            onChange={(query, index) => {
                                                selectedRef.current = query
                                                onChange(index)
                                            }}
                                        />
                                    )}
                                </LemonField>
                                <LemonField name="viewName" label="Name">
                                    <LemonInput
                                        data-attr="sql-editor-input-save-view-name"
                                        disabled={isLoading}
                                        placeholder="Please enter the name of the view"
                                        autoFocus
                                    />
                                </LemonField>
                                <LemonField
                                    name="description"
                                    label="Description"
                                    showOptional
                                    help="Agents may use this description to work out how to use this data."
                                    className="mt-2"
                                >
                                    <LemonTextArea
                                        data-attr="sql-editor-input-save-view-description"
                                        disabled={isLoading}
                                        placeholder="For example: one row per paid order, without test orders or refunds. Use it for revenue reports."
                                        minRows={2}
                                        stopPropagation
                                    />
                                </LemonField>
                                <div className="flex gap-2 mt-2">
                                    <LemonField name="folderId" label="Add to folder" className="flex-1">
                                        {({ value, onChange }) => (
                                            <LemonSearchableSelect<string | null>
                                                value={value}
                                                onChange={onChange}
                                                searchPlaceholder="Search folders"
                                                options={[
                                                    ...folderOptions,
                                                    {
                                                        value: '__add_new_folder__',
                                                        label: '+ Add new folder',
                                                        labelInMenu: () => (
                                                            <button
                                                                type="button"
                                                                className="w-full text-left text-primary px-2 py-1.5 cursor-pointer"
                                                                onClick={() => createFolderAndSelect(onChange)}
                                                            >
                                                                + Add new folder
                                                            </button>
                                                        ),
                                                    },
                                                ]}
                                                disabled={isLoading}
                                                placeholder="Select a folder"
                                                fullWidth
                                            />
                                        )}
                                    </LemonField>
                                </div>
                                {isStaff && (
                                    <LemonField name="isTest" className="mt-2">
                                        {({ value, onChange }) => (
                                            <div className="flex items-center gap-2">
                                                <LemonCheckbox
                                                    checked={value}
                                                    onChange={onChange}
                                                    data-attr="sql-editor-input-save-view-is-test"
                                                    label="Is this view for testing only?"
                                                />
                                                <Tooltip title="Test views and any downstream assets that depend on them will be automatically deleted after 1 week.">
                                                    <span className="text-muted cursor-pointer">&#9432;</span>
                                                </Tooltip>
                                            </div>
                                        )}
                                    </LemonField>
                                )}
                                <LemonField name="materializeAfterSave" className="mt-2">
                                    {({ value, onChange }) => (
                                        <>
                                            <div className="flex items-center gap-2">
                                                <LemonCheckbox
                                                    checked={value}
                                                    onChange={onChange}
                                                    data-attr="sql-editor-input-save-view-materialize"
                                                    disabledReason={
                                                        isRawTrinoSave
                                                            ? 'Views that run raw Trino SQL cannot be materialized yet.'
                                                            : undefined
                                                    }
                                                    label="Materialize this view"
                                                />
                                                <Tooltip title="Pre-compute the results into a table for faster queries. Syncs daily by default — you can adjust the frequency later in the view's materialization settings.">
                                                    <span className="text-muted cursor-pointer">&#9432;</span>
                                                </Tooltip>
                                            </div>
                                            <IncrementalConfigFields queries={candidates.queries} />
                                        </>
                                    )}
                                </LemonField>
                            </>
                        ),
                    errors: {
                        saveTarget: () => selectionProblem ?? undefined,
                        viewName: validateSavedQueryName,
                        incrementalKey: (key, { incrementalEnabled, materializeAfterSave: materialize }) =>
                            incrementalEnabled && materialize && !key ? 'Select the incremental column' : undefined,
                        incrementalUniqueKey: (uniqueKey, { incrementalEnabled, materializeAfterSave: materialize }) =>
                            incrementalEnabled && materialize && !uniqueKey?.length
                                ? 'Select at least one unique key column'
                                : undefined,
                    },
                    onSubmit: async ({
                        viewName,
                        description,
                        folderId,
                        isTest,
                        materializeAfterSave: shouldMaterialize,
                        incrementalEnabled,
                        incrementalKey,
                        incrementalUniqueKey,
                        incrementalLookbackSeconds,
                    }) => {
                        const incremental =
                            shouldMaterialize && incrementalEnabled && incrementalKey && incrementalUniqueKey?.length
                                ? {
                                      enabled: true,
                                      incremental_key: incrementalKey,
                                      unique_key: incrementalUniqueKey,
                                      lookback_seconds: incrementalLookbackSeconds ?? 0,
                                  }
                                : undefined
                        await asyncActions.saveAsViewSubmit(
                            viewName,
                            shouldMaterialize ?? false,
                            fromDraft,
                            folderId,
                            isTest ?? false,
                            selectedRef.current,
                            incremental,
                            description?.trim() || undefined
                        )
                    },
                    shouldAwaitSubmit: true,
                })
            },
            saveAsViewSubmit: async ({
                name,
                materializeAfterSave = false,
                fromDraft,
                folderId,
                isTest = false,
                queryOverride,
                incremental,
                description,
            }) => {
                const biEditorState = getActiveBIEditorState()
                const query: HogQLQuery = values.sourceQuery.source

                const queryToSave = normalizeRawQuerySource({
                    ...query,
                    query: queryOverride ?? values.queryInput ?? '',
                })

                const logic = dataNodeLogic({
                    key: values.dataLogicKey,
                    query: queryToSave,
                })

                const response = logic.values.response
                const types = response && 'types' in response ? (response.types ?? []) : []
                // "Partial save" means the user is saving something smaller than the full editor
                // text — either because of multi-query splitting or a specific text selection. In
                // that case the current tab shouldn't be rebound to the new view, because its
                // content is NOT the view's content. We tag the view name so the success listener
                // knows to skip its normal bind-to-tab behavior, then open the view in its own tab.
                const isPartialSave = queryToSave.query.trim() !== (values.queryInput ?? '').trim()
                if (isPartialSave) {
                    if (!cache.viewNamesToSkipTabBinding) {
                        cache.viewNamesToSkipTabBinding = new Set<string>()
                    }
                    cache.viewNamesToSkipTabBinding.add(name)
                }
                try {
                    await dataWarehouseViewsLogic.asyncActions.createDataWarehouseSavedQuery({
                        name,
                        query: queryToSave,
                        types,
                        ...(description ? { description } : {}),
                        ...(folderId ? { folder_id: folderId } : {}),
                        ...(isTest ? { is_test: true } : {}),
                        ...(incremental ? { incremental } : {}),
                        ...(materializeAfterSave ? { deferCreatedToast: true } : {}),
                    })
                    captureBIEditorQuerySaved(biEditorState, 'view', 'create')
                    posthog.capture('save as view dialog submitted', {
                        has_description: !!description,
                        materialize_after_save: materializeAfterSave,
                    })

                    // Saved queries are unique by team,name
                    const savedQuery = dataWarehouseViewsLogic.values.dataWarehouseSavedQueries.find(
                        (q) => q.name === name
                    )

                    if (materializeAfterSave && savedQuery) {
                        await dataWarehouseViewsLogic.asyncActions.materializeDataWarehouseSavedQuery(
                            savedQuery.id,
                            undefined,
                            undefined,
                            savedQuery.name
                        )
                    }
                    if (fromDraft) {
                        actions.deleteDraft(fromDraft, savedQuery?.name)
                    }

                    if (isPartialSave && savedQuery) {
                        const savedView = hasSavedQueryDetails(savedQuery)
                            ? savedQuery
                            : await api.dataWarehouseSavedQueries.get(savedQuery.id)
                        actions.createTab(savedView.query?.query ?? queryToSave.query, savedView)
                    }
                } catch {
                    lemonToast.error('Failed to save view')
                    // On failure, drop the skip marker so a retry with the same name binds normally.
                    cache.viewNamesToSkipTabBinding?.delete(name)
                }
            },
            openMaterializationModal: async ({ view }, breakpoint) => {
                if (!view) {
                    return
                }

                await breakpoint(100)

                if (values.materializationModalView?.id === view.id) {
                    actions.setMaterializationModalOpen(true)
                    return
                }

                actions.setViewLoading(true)

                try {
                    let nextView = view

                    if (!nextView.query) {
                        nextView = await api.dataWarehouseSavedQueries.get(view.id)
                    }

                    await breakpoint(100)
                    actions.setMaterializationModalView(nextView)
                    actions.setMaterializationModalOpen(true)
                } catch {
                    lemonToast.error('View not found')
                    actions.closeMaterializationModal()
                } finally {
                    actions.setViewLoading(false)
                }
            },
            saveAsInsight: async () => {
                const currentVisualizationQuery = getCurrentVisualizationQuery(
                    values.dataLogicKey,
                    values.sourceQuery,
                    values.queryInput
                )
                const effectiveVisualizationType = dataVisualizationLogic.findMounted({
                    key: values.dataLogicKey,
                    query: currentVisualizationQuery,
                    dataNodeCollectionId: values.dataLogicKey,
                    editMode: true,
                })?.values.effectiveVisualizationType

                const defaultDisplay = getDisplayTypeToSaveInsight(
                    values.outputActiveTab,
                    currentVisualizationQuery.display,
                    effectiveVisualizationType
                )

                const candidates = resolveSaveCandidates()
                const selectedRef = {
                    current: candidates.queries[candidates.initialIndex],
                }

                LemonDialog.openForm({
                    title: 'Save as new insight',
                    initialValues: {
                        name: '',
                    },
                    content: (
                        <>
                            <LemonField name="name">
                                <LemonInput
                                    data-attr="insight-name"
                                    placeholder="Please enter the new name"
                                    autoFocus
                                />
                            </LemonField>
                            <SaveTargetCycler
                                candidates={candidates}
                                onChange={(q) => {
                                    selectedRef.current = q
                                }}
                            >
                                {(query) => (
                                    <div className="bg-bg-light max-h-[60vh] overflow-auto">
                                        <Suspense fallback={<Spinner />}>
                                            <LazyQuery
                                                readOnly
                                                embedded
                                                query={{
                                                    ...currentVisualizationQuery,
                                                    source: {
                                                        ...currentVisualizationQuery.source,
                                                        query,
                                                    },
                                                    display: defaultDisplay,
                                                }}
                                            />
                                        </Suspense>
                                    </div>
                                )}
                            </SaveTargetCycler>
                        </>
                    ),
                    errors: {
                        name: (name) => (!name ? 'You must enter a name' : undefined),
                    },
                    onSubmit: async ({ name }) => actions.saveAsInsightSubmit(name, selectedRef.current),
                })
            },
            saveAsInsightSubmit: async ({ name, queryOverride }) => {
                const biEditorState = getActiveBIEditorState()
                const currentVisualizationQuery = getCurrentVisualizationQuery(
                    values.dataLogicKey,
                    values.sourceQuery,
                    values.queryInput
                )
                const effectiveVisualizationType = dataVisualizationLogic.findMounted({
                    key: values.dataLogicKey,
                    query: currentVisualizationQuery,
                    dataNodeCollectionId: values.dataLogicKey,
                    editMode: true,
                })?.values.effectiveVisualizationType

                const display = getDisplayTypeToSaveInsight(
                    values.outputActiveTab,
                    currentVisualizationQuery.display,
                    effectiveVisualizationType
                )

                const sourceQueryToSave: DataVisualizationNode = {
                    ...currentVisualizationQuery,
                    source: {
                        ...currentVisualizationQuery.source,
                        query: queryOverride ?? currentVisualizationQuery.source.query,
                    },
                    display,
                }

                const dashboardId = values.dashboardId
                const insight = await insightsApi.create(
                    { name, query: sourceQueryToSave, saved: true },
                    dashboardId ? [dashboardId] : []
                )
                captureBIEditorQuerySaved(biEditorState, 'insight', 'create', dashboardId !== null)
                const logic = insightLogic({
                    dashboardItemId: insight.short_id,
                    doNotLoad: true,
                })
                const umount = logic.mount()
                logic.actions.setInsight(insight, {
                    fromPersistentApi: true,
                    overrideQuery: true,
                })
                const timeoutId = window.setTimeout(() => umount(), 1000 * 10) // keep mounted for 10 seconds while we redirect
                cache.timeouts = cache.timeouts || []
                cache.timeouts.push(timeoutId)

                if (dashboardId) {
                    const tile = insight.dashboard_tiles?.find((t) => t.dashboard_id === dashboardId)
                    await placeTilesInGroup(
                        teamLogic.values.currentTeamId,
                        dashboardId,
                        tile ? [tile.id] : [],
                        values.dashboardTileGroupKey
                    )
                    dashboardsModel.findMounted()?.actions.updateDashboardInsight(insight)
                    dashboardLogic.findMounted({ id: dashboardId })?.actions.loadDashboard({
                        action: DashboardLoadAction.Update,
                    })
                    lemonToast.success('Insight saved & added to dashboard', {
                        button: {
                            label: 'View Insights list',
                            action: () => router.actions.push(urls.savedInsights()),
                        },
                    })
                    actions.setDashboardId(null)
                    router.actions.push(urls.dashboard(dashboardId, insight.short_id))
                } else {
                    lemonToast.info(`You're now viewing ${insight.name || insight.derived_name || name}`)
                    router.actions.push(withBackLink(urls.insightView(insight.short_id)))
                }
            },
            saveAsEndpoint: async () => {
                const candidates = resolveSaveCandidates()
                const selectedRef = {
                    current: candidates.queries[candidates.initialIndex],
                }
                const selectionProblem = await findSelectionProblem(candidates, values.sendRawQueryEnabled)
                LemonDialog.openForm({
                    title: 'Save as endpoint',
                    initialValues: {
                        saveTarget: candidates.initialIndex,
                        name: '',
                        description: '',
                    },
                    content: (
                        <>
                            <LemonField name="saveTarget">
                                {({ onChange }) => (
                                    <SaveTargetCycler
                                        candidates={candidates}
                                        onChange={(query, index) => {
                                            selectedRef.current = query
                                            onChange(index)
                                        }}
                                    />
                                )}
                            </LemonField>
                            <LemonField name="name">
                                <LemonInput
                                    data-attr="endpoint-name"
                                    placeholder="Please enter the endpoint name"
                                    autoFocus
                                />
                            </LemonField>
                            <LemonField name="description" className="mt-2">
                                <LemonInput
                                    data-attr="endpoint-description"
                                    placeholder="Please enter a description (optional)"
                                />
                            </LemonField>
                        </>
                    ),
                    errors: {
                        saveTarget: () => selectionProblem ?? undefined,
                        name: (name) => validateEndpointName(name?.trim() || ''),
                    },
                    onSubmit: async ({ name, description }) =>
                        actions.saveAsEndpointSubmit(name, description, selectedRef.current),
                })
            },
            saveAsEndpointSubmit: async ({ name, description, queryOverride }) => {
                const biEditorState = getActiveBIEditorState()
                try {
                    const endpoint = await api.endpoint.create({
                        name: slugify(name),
                        description: description || undefined,
                        query: normalizeRawQuerySource({
                            ...(values.sourceQuery.source as HogQLQuery),
                            query: queryOverride ?? values.queryInput ?? '',
                        }),
                    })
                    captureBIEditorQuerySaved(biEditorState, 'endpoint', 'create')
                    lemonToast.success('Endpoint created')
                    globalSetupLogic.findMounted()?.actions.markTaskAsCompleted(SetupTaskId.CreateFirstEndpoint)
                    router.actions.push(urls.endpoint(endpoint.name))
                } catch (error: any) {
                    lemonToast.error(error.detail || 'Failed to create endpoint')
                }
            },
            saveAsMetric: async ({ queryOverride }) => {
                const resolved = resolveSaveCandidates()
                // Reopening after a name conflict keeps the statement the user picked, not the cursor default.
                const restoredIndex = queryOverride === undefined ? -1 : resolved.queries.indexOf(queryOverride)
                const candidates = restoredIndex >= 0 ? { ...resolved, initialIndex: restoredIndex } : resolved
                const selectionProblem = await findSelectionProblem(candidates, values.sendRawQueryEnabled)
                actions.openSaveAsMetricModal({ candidates, selectionProblem, prefill: values.metricPrefill ?? {} })
            },
            saveAsMetricSubmit: async ({ fields, queryOverride, overwrite, approve }) => {
                if (values.savingMetricAs) {
                    return
                }
                actions.setSavingMetricAs(approve ? 'approve' : 'propose')
                const biEditorState = getActiveBIEditorState()
                try {
                    // Blank fields are sent as blank, so an overwrite clears the old values.
                    const created = await createMetricAsUser(
                        {
                            ...fields,
                            definition: normalizeRawQuerySource({
                                ...(values.sourceQuery.source as HogQLQuery),
                                query: queryOverride ?? values.queryInput ?? '',
                            }) as unknown as Record<string, unknown>,
                            overwrite,
                        },
                        approve
                    )
                    captureBIEditorQuerySaved(biEditorState, 'metric', overwrite ? 'update' : 'create')
                    metricsLogic.findMounted()?.actions.loadMetrics()
                    actions.setMetricPrefill(null)
                    actions.closeSaveAsMetricModal()
                    toastCreatedMetric(created, overwrite)
                    router.actions.push(urls.dataCatalogMetric(created.metric.name))
                } catch (error: any) {
                    const existing = existingMetricFromNameConflict(error)
                    if (existing) {
                        openOverwriteMetricDialog({
                            existing,
                            onOverwrite: () => actions.saveAsMetricSubmit(fields, queryOverride, true, approve),
                        })
                    } else {
                        lemonToast.error(error.detail || 'Failed to create metric')
                    }
                } finally {
                    actions.setSavingMetricAs(null)
                }
            },
            openMetricFromUrl: async ({ metricName, biEditorState }, breakpoint) => {
                const openMetricTab = (sourceQuery: DataVisualizationNode, boundMetricName?: string): void => {
                    actions.createTab(
                        sourceQuery.source.query,
                        undefined,
                        undefined,
                        undefined,
                        boundMetricName,
                        biEditorState ?? undefined
                    )
                    actions.setQueryInput(sourceQuery.source.query)
                    actions.setSourceQuery(sourceQuery)
                }
                try {
                    // Validate before it reaches the request path: the value is interpolated
                    // into the URL unencoded, so a name containing "../" could otherwise
                    // traverse to a metric in another project. The name regex forbids slashes.
                    if (validateMetricName(metricName)) {
                        throw new Error('Invalid metric name')
                    }
                    const metric = await dataCatalogMetricsRetrieve(String(ApiConfig.getCurrentTeamId()), metricName)
                    breakpoint()
                    const metricSourceQuery = metricEditorSourceQuery(metric.definition)
                    if (!metricSourceQuery) {
                        throw new Error('Metric is not defined in SQL')
                    }
                    openMetricTab(metricSourceQuery, metric.name)
                } catch (error) {
                    if (isBreakpoint(error as Error)) {
                        throw error
                    }
                    breakpoint()
                    // Invalid name, metric not found, or no access — open an unbound empty tab
                    // rather than binding an update target we couldn't verify.
                    openMetricTab(hogQLEditorSourceQuery())
                }
            },
            updateEditingMetric: async () => {
                if (!values.editingMetricName || values.metricUpdating) {
                    return
                }
                actions.setMetricUpdating(true)
                const biEditorState = getActiveBIEditorState()
                try {
                    await dataCatalogMetricsPartialUpdate(
                        String(ApiConfig.getCurrentTeamId()),
                        values.editingMetricName,
                        {
                            definition: normalizeRawQuerySource({
                                ...(values.sourceQuery.source as HogQLQuery),
                                query: values.queryInput ?? '',
                            }) as unknown as Record<string, unknown>,
                        }
                    )
                    captureBIEditorQuerySaved(biEditorState, 'metric', 'update')
                    metricsLogic.findMounted()?.actions.loadMetrics()
                    lemonToast.success('Metric updated')
                    router.actions.push(urls.dataCatalogMetric(values.editingMetricName))
                } catch (error: any) {
                    lemonToast.error(error.detail || 'Failed to update metric')
                } finally {
                    actions.setMetricUpdating(false)
                }
            },
            setEditingMetricName: ({ metricName }) => {
                if (values.activeTab) {
                    actions.updateTab({ ...values.activeTab, metricName: metricName ?? undefined })
                }
            },
            setEditingInsightName: ({ name }) => {
                if (values.activeTab) {
                    actions.updateTab({ ...values.activeTab, name })
                }
            },
            setEditingInsightDescription: ({ description }) => {
                if (values.activeTab) {
                    actions.updateTab({ ...values.activeTab, description })
                }
            },
            updateInsight: async () => {
                if (!values.editingInsight || values.insightLoading) {
                    return
                }

                actions.setInsightLoading(true)
                const biEditorState = getActiveBIEditorState()

                const insightName = values.activeTab?.name
                const insightDescription = values.activeTab?.description
                const currentVisualizationQuery = getCurrentVisualizationQuery(
                    values.dataLogicKey,
                    values.sourceQuery,
                    values.queryInput
                )

                const insightRequest: Partial<InsightModel> = {
                    name: insightName ?? values.editingInsight.name,
                    description: insightDescription ?? values.editingInsight.description ?? '',
                    query: currentVisualizationQuery,
                }

                const dashboardId = values.dashboardId

                let savedInsight: InsightModel
                try {
                    savedInsight = await insightsApi.update(values.editingInsight.id, insightRequest)
                } catch (e) {
                    actions.setInsightLoading(false)
                    if (e instanceof ApiError) {
                        lemonToast.error(e.detail ?? 'Could not update insight')
                    } else {
                        lemonToast.error('Could not update insight')
                    }
                    throw e
                }
                const placement = await placeSavedInsightOnDashboard(savedInsight, dashboardId)
                savedInsight = placement.insight
                actions.setInsightLoading(false)
                captureBIEditorQuerySaved(biEditorState, 'insight', 'update', dashboardId !== null)

                if (values.activeTab) {
                    actions.updateTab({
                        ...values.activeTab,
                        insight: savedInsight,
                    })
                    persistEditorDraft()
                }
                insightsModel.findMounted()?.actions.renameInsightSuccess(savedInsight)
                const loadedLogic = insightLogic.findMounted({
                    dashboardItemId: values.editingInsight.short_id,
                    dashboardId: undefined,
                })
                if (loadedLogic) {
                    loadedLogic.actions.setInsight(savedInsight, {
                        overrideQuery: true,
                        fromPersistentApi: true,
                    })
                }

                if (dashboardId && placement.placed) {
                    dashboardsModel.findMounted()?.actions.updateDashboardInsight(savedInsight)
                    dashboardLogic.findMounted({ id: dashboardId })?.actions.loadDashboard({
                        action: DashboardLoadAction.Update,
                    })
                    lemonToast.success('Insight updated', {
                        button: {
                            label: 'View Insights list',
                            action: () => router.actions.push(urls.savedInsights()),
                        },
                    })
                    actions.setDashboardId(null)
                    router.actions.push(urls.dashboard(dashboardId, savedInsight.short_id))
                } else {
                    lemonToast.info(
                        `You're now viewing ${savedInsight.name || savedInsight.derived_name || insightName || 'Untitled'}`
                    )
                    router.actions.push(withBackLink(urls.insightView(savedInsight.short_id)))
                }
            },
            discardChanges: async (_, breakpoint) => {
                const tab = values.activeTab
                if (!tab || !values.hasEditorChanges) {
                    return
                }
                const restore = (view?: DataWarehouseSavedQuery, insight?: InsightModel): void => {
                    const savedQuery = view
                        ? hogQLEditorSourceQuery(view.query)
                        : toDataVisualizationNode(insight?.query)
                    if (!savedQuery) {
                        return
                    }
                    actions._setSuggestionPayload(null)
                    actions.createTab(savedQuery.source.query, view, insight, undefined, undefined, tab.biEditorState)
                    actions.setSourceQuery(savedQuery)
                    applyUndoableModelEdit(props.monaco, values.activeTab?.uri, savedQuery.source.query)
                    actions.syncUrlWithQuery()
                }
                restore(
                    tab.view
                        ? {
                              ...tab.view,
                              latest_history_id: values.inProgressViewEdits[tab.view.id] ?? tab.view.latest_history_id,
                          }
                        : undefined,
                    tab.insight
                )
                const restoredTab = values.activeTab
                const restoredQuery = values.queryInput
                const restoredSourceQuery = values.sourceQuery
                try {
                    const view = tab.view
                        ? await warehouseSavedQueriesRetrieve(String(teamLogic.values.currentTeamId), tab.view.id)
                        : undefined
                    const insight = tab.insight ? await insightsApi.getByShortId(tab.insight.short_id) : undefined
                    breakpoint()
                    if (
                        values.activeTab !== restoredTab ||
                        values.queryInput !== restoredQuery ||
                        values.sourceQuery !== restoredSourceQuery
                    ) {
                        return
                    }
                    restore(
                        view && tab.view
                            ? {
                                  ...tab.view,
                                  name: view.name,
                                  query: {
                                      ...view.query,
                                      kind: NodeKind.HogQLQuery,
                                      query: view.query.query ?? '',
                                  },
                                  latest_history_id: view.latest_history_id ?? undefined,
                              }
                            : undefined,
                        insight ?? undefined
                    )
                } catch (error) {
                    if (error instanceof Error && isBreakpoint(error)) {
                        throw error
                    }
                    lemonToast.error('Changes discarded. Could not refresh the saved query.')
                }
            },
            closeEditingObject: () => {
                actions.setInsightLoading(false)
                actions.setViewLoading(false)
                actions.setViewQueryLoading(false)

                if (!values.activeTab) {
                    actions.createTab(values.queryInput ?? '')
                    return
                }

                const nextActiveTab = {
                    ...values.activeTab,
                    name: NEW_QUERY,
                    description: '',
                    view: undefined,
                    insight: undefined,
                    draft: undefined,
                }

                actions.updateTab(nextActiveTab)

                if (!values.isEmbeddedMode) {
                    const nextHash = encodeURIComponent(
                        JSON.stringify(getTabHash({ ...values, activeTab: nextActiveTab }))
                    )
                    const currentUrl = new URL(window.location.href)
                    currentUrl.searchParams.delete('open_insight')
                    currentUrl.searchParams.delete('open_view')
                    currentUrl.searchParams.delete('open_draft')
                    window.history.replaceState(
                        {},
                        '',
                        `${values.editorUrl}${currentUrl.searchParams.toString() ? `?${currentUrl.searchParams.toString()}` : ''}#${nextHash}`
                    )
                }
            },
            loadDataWarehouseSavedQueriesSuccess: ({ dataWarehouseSavedQueries }) => {
                if (values.activeTab?.view) {
                    const updatedView = dataWarehouseSavedQueries.find((v) => v.id === values.activeTab?.view?.id)
                    if (updatedView && values.activeTab) {
                        // List refreshes carry metadata only; keep details fetched for the open tab.
                        const viewWithQuery = {
                            ...updatedView,
                            query: values.activeTab.view.query,
                            columns: values.activeTab.view.columns,
                        }
                        actions.updateTab({
                            ...values.activeTab,
                            view: viewWithQuery,
                        })
                    }
                }
            },
            deleteDataWarehouseSavedQuerySuccess: ({ payload: viewId }) => {
                if (values.activeTab?.view?.id === viewId && !values.activeTab?.draft) {
                    // createTab() alone reuses the existing model and doesn't clear queryInput
                    applyUndoableModelEdit(props.monaco, values.activeTab?.uri, '')
                    actions.setQueryInput('')
                    actions.createTab()
                }
            },
            createDataWarehouseSavedQuerySuccess: async ({ dataWarehouseSavedQueries, payload: view }) => {
                if (view?.name && cache.viewNamesToSkipTabBinding?.has(view.name)) {
                    cache.viewNamesToSkipTabBinding.delete(view.name)
                    return
                }
                const newView = view && dataWarehouseSavedQueries.find((v) => v.name === view.name)
                if (newView) {
                    const oldTab = values.activeTab
                    // Only update the tab if it doesn't have a view (new query being saved)
                    // or if it's the same view being recreated (edge case)
                    if (oldTab && (!oldTab.view || oldTab.view.id === newView.id)) {
                        const nextTab = {
                            ...oldTab,
                            name: newView.name,
                            view: hasSavedQueryDetails(newView)
                                ? newView
                                : await api.dataWarehouseSavedQueries.get(newView.id),
                        }

                        actions.updateTab(nextTab)

                        if (!values.isEmbeddedMode) {
                            router.actions.replace(
                                values.editorUrl,
                                backLinkParams(router.values.searchParams),
                                getTabHash({ ...values, activeTab: nextTab })
                            )
                        }
                    }
                }
            },
            reviewEditingViewUpdate: () => {
                const view = values.editingView
                if (!view) {
                    return
                }
                // The data node is bound inside the editor, so the response is read from the mounted instance.
                const response = dataNodeLogic.findMounted({ key: values.dataLogicKey })?.values.response
                actions.reviewViewUpdate({
                    id: view.id,
                    query: { ...values.sourceQuery.source, query: values.queryInput ?? '' },
                    types: response && 'types' in response ? (response.types ?? []) : [],
                    shouldRematerialize: view.is_materialized === true,
                    edited_history_id: values.inProgressViewEdits[view.id],
                })
            },
            reviewViewUpdate: ({ view, draftId }) => {
                // Reuse the editor's inline accept/reject diff (QueryPane) instead of a separate
                // modal: show the saved query alongside the user's edits, and only run the update
                // once they accept. Mirrors the conflict-review diff in updateView below.
                const savedQuery = values.activeTab?.view?.query?.query ?? ''
                const editedQuery = values.queryInput ?? ''
                if (savedQuery === editedQuery) {
                    actions.updateView(view, draftId)
                    return
                }
                actions._setSuggestionPayload({
                    suggestedValue: editedQuery,
                    originalValue: savedQuery,
                    acceptText: view.shouldRematerialize ? 'Update and re-materialize view' : 'Update view',
                    rejectText: 'Cancel',
                    diffShowRunButton: false,
                    onAccept: () => {
                        actions.updateView(view, draftId)
                    },
                    onReject: () => {},
                })
            },
            updateView: async ({ view, draftId }) => {
                const biEditorState = getActiveBIEditorState()
                const latestView = await api.dataWarehouseSavedQueries.get(view.id)
                // A real conflict means someone else changed the query text since this edit began.
                // Detect it by comparing the server's current query against the baseline this edit
                // started from (the tab's saved query) — not against the user's edited query, which
                // always differs. Keying off history ids alone gives false positives when the
                // editor's cached head has drifted from the server's (e.g. the head advanced for a
                // non-query reason, or the view was opened without one), wrongly telling a sole
                // editor the view was changed by someone else.
                const baselineQuery = values.activeTab?.view?.query?.query
                const foreignEdit =
                    latestView?.latest_history_id != null &&
                    baselineQuery != null &&
                    latestView.query?.query !== baselineQuery
                if (foreignEdit) {
                    actions._setSuggestionPayload({
                        suggestedValue: values.queryInput!,
                        originalValue: latestView?.query?.query,
                        acceptText: 'Confirm changes',
                        rejectText: 'Cancel',
                        diffShowRunButton: false,
                        onAccept: async () => {
                            actions.setQueryInput(view.query?.query ?? '')
                            await dataWarehouseViewsLogic.asyncActions.updateDataWarehouseSavedQuery({
                                ...view,
                                edited_history_id: latestView?.latest_history_id,
                            })
                            actions.updateViewSuccess(view, draftId, biEditorState)
                        },
                        onReject: () => {},
                    })
                    lemonToast.error('View has been edited by another user. Review changes to update.')
                } else {
                    // No foreign edit — send the server's current head so the backend's own
                    // edited_history_id check accepts the save even if the editor's cached head drifted.
                    await dataWarehouseViewsLogic.asyncActions.updateDataWarehouseSavedQuery({
                        ...view,
                        edited_history_id: latestView?.latest_history_id ?? view.edited_history_id,
                    })
                    actions.updateViewSuccess(view, draftId, biEditorState)
                }
            },
            updateViewSuccess: async ({ view, draftId, biEditorState }) => {
                captureBIEditorQuerySaved(biEditorState, 'view', 'update')
                if (draftId) {
                    actions.deleteDraft(draftId, view?.name)
                }
                if (values.activeTab?.view && values.activeTab.view.id === view.id && view.query) {
                    // Refresh the baseline query immediately so `changesToSave` reflects the just-saved
                    // state (and the Update button disables) before we go back to the network.
                    actions.updateTab({
                        ...values.activeTab,
                        view: { ...values.activeTab.view, query: view.query },
                    })
                    persistEditorDraft()
                    // Re-read the server's activity-log head and adopt it as the new base. The concurrency
                    // check — both the frontend guard and the backend's edited_history_id check — keys off
                    // this head; without re-basing, reverting the query and saving again is misread as a
                    // foreign edit and wrongly raises "View has been edited by another user".
                    const refreshedView = await api.dataWarehouseSavedQueries.get(view.id)
                    if (refreshedView?.latest_history_id && values.activeTab?.view?.id === view.id) {
                        actions.updateTab({
                            ...values.activeTab,
                            view: { ...values.activeTab.view, latest_history_id: refreshedView.latest_history_id },
                        })
                        // Point the edit marker at the new head directly (not just clear it) so a fast
                        // revert-and-save can't re-base on the stale pre-save head before this refetch lands.
                        actions.setInProgressViewEdit(view.id, refreshedView.latest_history_id)
                    } else {
                        // No head to adopt — clear the stale marker and let the next edit re-base.
                        actions.deleteInProgressViewEdit(view.id)
                    }
                }
            },
            deleteDraftSuccess: ({ draftId, viewName }) => {
                if (values.activeTab && values.activeTab.draft?.id === draftId) {
                    actions.updateTab({
                        ...values.activeTab,
                        draft: undefined,
                        name: viewName ?? values.activeTab.name,
                    })
                }
            },
        }
    }),
    subscriptions(({ actions, values, cache, props }) => ({
        queryInput: (queryInput: string | null) => {
            // Subquery validation results are keyed by subquery text — but the same text
            // may now refer to a subquery with different surrounding context, so drop
            // everything whenever the editor content changes.
            cache.subqueryValidationCache?.clear()

            // Debounced — updating decorations parses the AST and can hit the metadata endpoint,
            // which is too expensive to run on every keystroke.
            cache.scheduleActiveQueryDecoration?.()

            // Skip re-parsing if the text hasn't changed since the last parse.
            if (cache.lastParsedQueryInput === queryInput && cache.lastParsedQueryResult !== undefined) {
                actions.setSelectedQueryTablesAndColumns(cache.lastParsedQueryResult)
                return
            }

            // Debounce parsing — it walks the HogQL AST and is too heavy to run on every keystroke.
            if (cache.queryInputParseTimeout) {
                window.clearTimeout(cache.queryInputParseTimeout)
            }
            cache.pendingParsedQueryInput = queryInput
            cache.queryInputParseTimeout = window.setTimeout(async () => {
                cache.queryInputParseTimeout = null
                const scheduledInput = cache.pendingParsedQueryInput
                const result = await parseQueryTablesAndColumns(scheduledInput)
                // Drop the result if a newer value was scheduled while we were parsing.
                if (cache.pendingParsedQueryInput !== scheduledInput) {
                    return
                }
                cache.lastParsedQueryInput = scheduledInput
                cache.lastParsedQueryResult = result
                actions.setSelectedQueryTablesAndColumns(result)
            }, 200)
        },
        hasFiltersPlaceholder: (hasFiltersPlaceholder: boolean) => {
            if (hasFiltersPlaceholder) {
                if (typeof values.sourceQuery.source.filters !== 'object') {
                    actions.setSourceQuery({
                        ...values.sourceQuery,
                        source: {
                            ...values.sourceQuery.source,
                            filters: {},
                        },
                    })
                }
            }
        },
        sourceQuery: (sourceQuery: DataVisualizationNode, previousSourceQuery: DataVisualizationNode | undefined) => {
            if (values.isEmbeddedMode || !values.activeTab) {
                return
            }

            const filters = normalizeFiltersForUrl(sourceQuery.source.filters)
            const previousFilters = normalizeFiltersForUrl(previousSourceQuery?.source.filters)
            if (!equal(filters ?? {}, previousFilters ?? {})) {
                actions.syncUrlWithQuery()
            }
        },
        editingView: (editingView) => {
            if (editingView && !isRawTrinoView(editingView)) {
                actions.loadUpstream(editingView.id)
            }
        },
        drafts: (drafts) => {
            if (values.activeTab && values.activeTab.draft) {
                const updatedDraft = drafts.find(
                    (d: DataWarehouseSavedQueryDraft) => d.id === values.activeTab?.draft?.id
                )
                if (updatedDraft) {
                    actions.updateTab({
                        ...values.activeTab,
                        draft: updatedDraft,
                        name: updatedDraft.name ?? values.activeTab.view?.name ?? values.activeTab.name,
                    })
                }
            }
        },
        selectedSchemaConnectionId: (selectedConnectionId) => {
            if (cache.lastSchemaConnectionId === selectedConnectionId) {
                return
            }

            cache.lastSchemaConnectionId = selectedConnectionId
            claimConnectionScope(props.tabId, selectedConnectionId)
            actions.setConnection(selectedConnectionId ?? null)
            actions.loadDatabase(schemaLoadOptions())
            if (values.selectedConnectionId) {
                // Capability data must load wherever a connection is in play — including
                // surfaces that never render the connection selector.
                actions.maybeLoadConnectionOptions()
            }
            actions.enforceConnectionRawQueryMode()
        },
    })),
    selectors({
        editorUrl: [
            () => [(_, p: SqlEditorLogicProps) => p.mode],
            (mode: SQLEditorMode | undefined) =>
                mode === SQLEditorMode.BusinessIntelligence ? urls.businessIntelligence() : urls.sqlEditor(),
        ],
        placeholderValues: [
            (s) => [s.placeholders],
            (placeholders: SQLEditorPlaceholder[]): Record<string, string> | null =>
                placeholderPreviewValues(placeholders),
        ],
        suggestedSource: [
            (s) => [s.suggestionPayload],
            (suggestionPayload: SuggestionPayload | null) => {
                return suggestionPayload?.source ?? null
            },
        ],
        diffShowRunButton: [
            (s) => [s.suggestionPayload],
            (suggestionPayload: SuggestionPayload | null) => {
                return suggestionPayload?.diffShowRunButton
            },
        ],
        acceptText: [
            (s) => [s.suggestionPayload],
            (suggestionPayload: SuggestionPayload | null) => {
                return suggestionPayload?.acceptText ?? 'Accept'
            },
        ],
        rejectText: [
            (s) => [s.suggestionPayload],
            (suggestionPayload: SuggestionPayload | null) => {
                return suggestionPayload?.rejectText ?? 'Reject'
            },
        ],

        suggestedQueryInput: [
            (s) => [s.suggestionPayload, s.queryInput],
            (suggestionPayload: SuggestionPayload | null, queryInput: string | null) => {
                if (suggestionPayload?.suggestedValue && suggestionPayload?.suggestedValue !== queryInput) {
                    return suggestionPayload?.suggestedValue ?? ''
                }

                return queryInput ?? ''
            },
        ],
        originalQueryInput: [
            (s) => [s.suggestionPayload, s.queryInput],
            (suggestionPayload: SuggestionPayload | null, queryInput: string | null) => {
                // If we have a suggestion payload, always show diff mode
                if (suggestionPayload?.suggestedValue) {
                    // Prefer the stored originalValue if available, otherwise use current queryInput
                    return suggestionPayload?.originalValue || queryInput
                }

                return undefined
            },
        ],
        editingView: [
            (s) => [s.activeTab],
            (activeTab: QueryTab | null) => {
                return activeTab?.view
            },
        ],
        editingMetricName: [
            (s) => [s.activeTab],
            (activeTab: QueryTab | null) => {
                return activeTab?.metricName ?? null
            },
        ],
        changesToSave: [
            (s) => [s.editingView, s.queryInput],
            (editingView: DataWarehouseSavedQuery | undefined, queryInput: string | null) => {
                return editingView?.query?.query !== queryInput
            },
        ],
        hasEditorChanges: [
            (s) => [s.activeTab, s.queryInput, s.sourceQuery],
            (activeTab: QueryTab | null, queryInput: string | null, sourceQuery: DataVisualizationNode): boolean => {
                if (!activeTab || queryInput === null || activeTab.draft) {
                    return false
                }
                const savedQuery = activeTab.view
                    ? hogQLEditorSourceQuery(activeTab.view.query)
                    : toDataVisualizationNode(activeTab.insight?.query)
                if (!savedQuery) {
                    return false
                }
                const normalize = (query: DataVisualizationNode): Record<string, unknown> =>
                    removeUndefinedAndNull({
                        ...sanitizeSourceQuery(query),
                        display: query.display ?? ChartDisplayType.Auto,
                        source: {
                            ...normalizeRawQuerySource(query.source),
                            filters: normalizeFiltersForUrl(query.source.filters),
                        },
                    })
                const currentQuery = { ...sourceQuery, source: { ...sourceQuery.source, query: queryInput } }
                return (
                    !equal(
                        normalize(activeTab.view ? hogQLEditorSourceQuery(currentQuery.source) : currentQuery),
                        normalize(savedQuery)
                    ) ||
                    (!!activeTab.insight &&
                        (activeTab.name !== (activeTab.insight.name ?? NEW_QUERY) ||
                            (activeTab.description ?? '') !== (activeTab.insight.description ?? '')))
                )
            },
        ],
        exportContext: [
            (s) => [s.sourceQuery],
            (sourceQuery: DataVisualizationNode) => {
                // TODO: use active tab at some point
                const filename = 'export'

                return {
                    ...queryExportContext(sourceQuery.source, undefined, undefined),
                    filename,
                } as ExportContext
            },
        ],
        selectedConnectionId: [
            (s) => [s.sourceQuery],
            (sourceQuery: DataVisualizationNode) => {
                return sourceQuery.source && 'connectionId' in sourceQuery.source
                    ? sourceQuery.source.connectionId
                    : undefined
            },
        ],
        selectedSchemaConnectionId: [
            (s) => [s.sourceQuery, s.selectedConnectionId],
            (sourceQuery: DataVisualizationNode, selectedConnectionId: string | undefined): string | undefined =>
                sourceQuery.source.executionTarget === 'managed_trino'
                    ? MANAGED_TRINO_SCHEMA_SCOPE
                    : selectedConnectionId,
        ],
        selectedDirectSource: [
            (s) => [s.connectionOptions, s.selectedConnectionId],
            (
                connectionOptions: ExternalDataSourceConnectionOptionApi[] | null,
                selectedConnectionId: string | undefined
            ): ExternalDataSourceConnectionOptionApi | undefined => {
                return connectionOptions?.find((source) => source.id === selectedConnectionId)
            },
        ],
        sendRawQueryEnabled: [
            (s) => [s.sourceQuery, s.selectedConnectionId],
            (sourceQuery: DataVisualizationNode, selectedConnectionId: string | undefined) =>
                (!!selectedConnectionId || sourceQuery.source.executionTarget === 'managed_trino') &&
                (sourceQuery.source.sendRawQuery ?? false),
        ],
        selectedConnectionSupportsHogQL: [
            (s) => [s.connectionOptions, s.selectedConnectionId],
            (
                connectionOptions: ExternalDataSourceConnectionOptionApi[] | null,
                selectedConnectionId: string | undefined
            ): boolean => {
                if (!selectedConnectionId) {
                    return true
                }
                const option = connectionOptions?.find((option) => option.id === selectedConnectionId)
                // Unknown connections (options still loading) default to HogQL.
                return option ? option.supports_hogql !== false : true
            },
        ],
        isEditingMaterializedView: [
            (s) => [s.editingView],
            (editingView: DataWarehouseSavedQuery | undefined) => {
                return !!editingView?.is_materialized
            },
        ],
        splitQueryRanges: [
            (s) => [s.queryInput],
            (queryInput: string | null): QueryRange[] => splitQueries(queryInput ?? ''),
        ],
        isMultiQuery: [(s) => [s.splitQueryRanges], (ranges: QueryRange[]): boolean => ranges.length > 1],
        singleStatement: [
            () => [(_, props) => props.singleStatement],
            (singleStatement?: boolean): boolean => !!singleStatement,
        ],
        showAgentHints: [
            () => [(_, props) => props.hideAgentHints],
            (hideAgentHints?: boolean): boolean => !hideAgentHints,
        ],
        singleStatementDisabledReason: [
            (s) => [s.singleStatement, s.isMultiQuery],
            (singleStatement: boolean, isMultiQuery: boolean): string | null =>
                singleStatement && isMultiQuery
                    ? 'Only one query can run here. Remove the extra statements separated by semicolons.'
                    : null,
        ],
        isSourceQueryLastRun: [
            (s) => [s.queryInput, s.lastRunQuery, s.sourceQuery, s.splitQueryRanges],
            (
                queryInput: string | null,
                lastRunQuery: DataVisualizationNode | null,
                sourceQuery: DataVisualizationNode,
                splitRanges: QueryRange[]
            ) => {
                if (
                    lastRunQuery &&
                    (lastRunQuery.source.executionTarget ?? 'default') !==
                        (sourceQuery.source.executionTarget ?? 'default')
                ) {
                    return false
                }
                const lastRunQueryText = (lastRunQuery?.source.query ?? sourceQuery.source.query ?? '').trim()
                if ((queryInput ?? '').trim() === lastRunQueryText) {
                    return true
                }
                // Multi-query editor: if the last-run text matches any statement in the script,
                // consider it "up to date" — the save flow resolves the target query at submit time.
                return splitRanges.some((q) => q.query.trim() === lastRunQueryText)
            },
        ],
        hasFiltersPlaceholder: [
            (s) => [s.queryInput],
            (queryInput: string | null) => {
                return queryUsesFiltersPlaceholder(queryInput)
            },
        ],
        filtersPlaceholderBindings: [
            (s) => [s.queryInput],
            (queryInput: string | null): string[] | null => filtersPlaceholderBindings(queryInput),
            { resultEqualityCheck: objectsEqual },
        ],
        hasQueryInput: [(s) => [s.queryInput], (queryInput: string | null) => !!queryInput],
        // A quickfix carries character offsets into the SQL the server analyzed, so it can only be
        // applied while the editor still holds that exact text. The comparison mirrors the fallback
        // in `codeEditorLogic`, which analyzes the whole editor text whenever there is no active
        // statement; comparing against the active statement alone reads as stale forever there.
        indexReportStale: [
            (s) => [s.metadata, s.activeQueryText, s.queryInput, s.suggestedQueryInput, s.metadataLoading],
            (
                metadata: HogQLMetadataResponse | null,
                activeQueryText: string | null,
                queryInput: string | null,
                suggestedQueryInput: string,
                metadataLoading: boolean
            ) => metadataLoading || metadata?.query !== (activeQueryText ?? (suggestedQueryInput || queryInput) ?? ''),
        ],
        isEmbeddedMode: [
            () => [(_, p: SqlEditorLogicProps) => p.mode],
            (mode: SQLEditorMode | undefined) => isEmbeddedSQLEditorMode(mode ?? SQLEditorMode.FullScene),
        ],
        dataLogicKey: [(_, p) => [p.tabId], (tabId: string) => `data-warehouse-editor-data-node-${tabId}`],
        isDraft: [(s) => [s.activeTab], (activeTab: QueryTab | null) => (activeTab ? !!activeTab.draft?.id : false)],
        currentDraft: [(s) => [s.activeTab], (activeTab: QueryTab | null) => (activeTab ? activeTab.draft : null)],
        selectedQueryColumns: [
            (s) => [s.selectedQueryTablesAndColumns],
            (tablesAndColumns: Record<string, Record<string, boolean>>): Record<string, boolean> => {
                return Object.fromEntries(
                    Object.entries(tablesAndColumns).flatMap(([table, columns]) => {
                        return Object.keys(columns).map((column) => [`${table}.${column}`, true])
                    })
                )
            },
            { resultEqualityCheck: objectsEqual },
        ],
    }),
    trackedActionToUrl(({ values }) => ({
        syncUrlWithQuery: () => {
            if (
                values.isEmbeddedMode ||
                values.queryInput === null ||
                removeProjectIdIfPresent(router.values.location.pathname) !== values.editorUrl
            ) {
                return
            }
            return [values.editorUrl, undefined, getTabHash(values), { replace: true }]
        },
        createTab: () => {
            if (values.isEmbeddedMode) {
                return
            }
            return [values.editorUrl, undefined, getTabHash(values), { replace: true }]
        },
        setActiveTab: () => {
            if (values.isEmbeddedMode || !values.activeTab) {
                return
            }
            return [values.editorUrl, undefined, getTabHash(values), { replace: true }]
        },
    })),
    urlToAction(({ actions, values, props, cache }) => ({
        [values.editorUrl]: async (_, searchParams, hashParams, { initial }) => {
            if (isEmbeddedSQLEditorMode(props.mode ?? SQLEditorMode.FullScene)) {
                return
            }

            if (
                props.mode !== SQLEditorMode.BusinessIntelligence &&
                hashParams.mode === BIEditorView.BI &&
                values.featureFlags[FEATURE_FLAGS.SQL_EDITOR_BI_MODE]
            ) {
                router.actions.replace(urls.businessIntelligence(), searchParams, hashParams)
                return
            }

            if (
                searchParams.source === 'endpoint' ||
                searchParams.source === 'insight' ||
                searchParams.source === 'view' ||
                searchParams.source === 'metric'
            ) {
                actions.setEditorSource(searchParams.source)
            }
            const metricPrefillFromUrl = parseMetricPrefill(searchParams.metric_prefill)
            if (metricPrefillFromUrl) {
                actions.setMetricPrefill(metricPrefillFromUrl)
            }
            if (searchParams.dashboard) {
                const parsed = parseInt(searchParams.dashboard, 10)
                if (!isNaN(parsed)) {
                    actions.setDashboardId(parsed)
                    const tileGroup = searchParams.tile_group
                    actions.setDashboardTileGroupKey(
                        typeof tileGroup === 'string' || typeof tileGroup === 'number' ? String(tileGroup) : null
                    )
                }
            }

            const draftTarget = searchParams.open_draft || hashParams.draft
            const viewTarget = searchParams.open_view || hashParams.view
            const insightTarget = searchParams.open_insight || hashParams.insight
            const target = draftTarget
                ? `draft:${draftTarget}`
                : viewTarget
                  ? `view:${viewTarget}`
                  : insightTarget
                    ? `insight:${insightTarget}`
                    : 'new'
            const draftStorage = sqlEditorDraftStorage(
                values.user?.uuid,
                teamLogic.values.currentTeamId,
                props.mode === SQLEditorMode.BusinessIntelligence ? `bi:${target}` : target
            )
            const storedDraft = draftStorage?.get()
            const isReload =
                initial &&
                window.performance
                    .getEntriesByType?.('navigation')
                    .some((entry) => (entry as PerformanceNavigationTiming).type === 'reload')
            const restoreWorkingCopy = isReload || router.values.lastMethod === 'POP'
            const localDraft =
                !hasOwnProperty(searchParams, 'open_query') &&
                (!hasOwnProperty(hashParams, 'q') || restoreWorkingCopy) &&
                !searchParams.edit_metric
                    ? restoreWorkingCopy
                        ? draftStorage?.get(true)
                        : storedDraft
                    : null
            if (localDraft) {
                hashParams = restoreWorkingCopy
                    ? {
                          ...hashParams,
                          c: undefined,
                          raw: undefined,
                          filters: undefined,
                          mode: undefined,
                          bi: undefined,
                          ...localDraft,
                      }
                    : { ...localDraft, ...hashParams }
            }

            const outputTabFromUrl = parseOutputTab(searchParams.output_tab ?? hashParams.output_tab)
            const draftIdFromUrl = searchParams.open_draft || hashParams.draft
            const viewIdFromUrl = searchParams.open_view || hashParams.view
            const insightShortIdFromUrl = searchParams.open_insight || hashParams.insight
            const hasFiltersHashParam = hasOwnProperty(hashParams, 'filters')
            const shouldApplyFiltersFromUrl =
                hasFiltersHashParam ||
                (!!(searchParams.open_query || hashParams.q) &&
                    !draftIdFromUrl &&
                    !viewIdFromUrl &&
                    !insightShortIdFromUrl)
            const filtersFromUrl = hasFiltersHashParam ? parseFiltersFromUrl(hashParams.filters) : undefined
            const biEditorStateFromUrl = parseBIEditorState(hashParams.mode, hashParams.bi)
            const applyFiltersFromUrl = (sourceQuery: DataVisualizationNode): DataVisualizationNode => {
                if (!shouldApplyFiltersFromUrl) {
                    return sourceQuery
                }

                return {
                    ...sourceQuery,
                    source: {
                        ...sourceQuery.source,
                        filters: filtersFromUrl ?? {},
                    },
                }
            }
            const expectedDatabaseConnectionId = values.selectedSchemaConnectionId ?? null
            const shouldSyncDatabaseConnection =
                values.databaseConnectionId !== expectedDatabaseConnectionId || !values.database

            if (
                !hasOwnProperty(searchParams, 'open_query') &&
                !searchParams.open_view &&
                !searchParams.open_insight &&
                !searchParams.open_draft &&
                !searchParams.edit_metric &&
                !searchParams.output_tab &&
                !hasOwnProperty(hashParams, 'q') &&
                !hashParams.c &&
                !hashParams.raw &&
                !hasOwnProperty(hashParams, 'engine') &&
                !hasFiltersHashParam &&
                !hashParams.view &&
                !hashParams.insight &&
                !hashParams.draft &&
                !hashParams.output_tab &&
                !hashParams.mode &&
                !hashParams.bi &&
                values.queryInput !== null
            ) {
                if (shouldSyncDatabaseConnection && !values.databaseLoading) {
                    actions.setConnection(expectedDatabaseConnectionId)
                    actions.loadDatabase(schemaLoadOptions())
                }
                return
            }

            const connectionIdFromHash =
                typeof hashParams.c === 'string' && hashParams.c !== '' ? hashParams.c : undefined
            const hasEngineOverride = hasOwnProperty(hashParams, 'engine')
            const executionTargetFromHash = hasEngineOverride
                ? hashParams.engine === 'managed_trino'
                    ? 'managed_trino'
                    : undefined
                : connectionIdFromHash
                  ? undefined
                  : values.sourceQuery.source.executionTarget
            const sendRawQueryFromHash =
                (connectionIdFromHash !== undefined || executionTargetFromHash === 'managed_trino') &&
                String(hashParams.raw) === '1'
            const currentConnectionId = values.sourceQuery.source.connectionId || undefined
            const currentSendRawQuery = values.sourceQuery.source.sendRawQuery ?? false
            const filtersForSourceQuery = applyFiltersFromUrl(values.sourceQuery).source.filters
            const shouldSyncFilters =
                shouldApplyFiltersFromUrl &&
                !equal(
                    normalizeFiltersForUrl(filtersForSourceQuery) ?? {},
                    normalizeFiltersForUrl(values.sourceQuery.source.filters) ?? {}
                )

            if (
                executionTargetFromHash !== values.sourceQuery.source.executionTarget ||
                connectionIdFromHash !== currentConnectionId ||
                sendRawQueryFromHash !== currentSendRawQuery ||
                shouldSyncFilters
            ) {
                actions.setSourceQuery({
                    ...values.sourceQuery,
                    source: {
                        ...values.sourceQuery.source,
                        executionTarget: executionTargetFromHash,
                        connectionId: connectionIdFromHash,
                        sendRawQuery: sendRawQueryFromHash || undefined,
                        filters: filtersForSourceQuery,
                    },
                })
            }

            let tabAdded = false

            const createQueryTab = async (): Promise<void> => {
                if (outputTabFromUrl && values.outputActiveTab !== outputTabFromUrl) {
                    actions.setActiveTab(outputTabFromUrl)
                }

                if (
                    draftIdFromUrl &&
                    (searchParams.open_draft ||
                        !activeTabMatchesUrlTarget(values.activeTab, {
                            draftId: draftIdFromUrl,
                        }))
                ) {
                    const draftId = draftIdFromUrl
                    const draft = values.drafts.find((draft) => {
                        return draft.id === draftId
                    })

                    if (!draft) {
                        lemonToast.error('Draft not found')
                        return
                    }

                    const existingTab = values.activeTab?.draft?.id === draft.id ? values.activeTab : null

                    if (!existingTab) {
                        const associatedView =
                            draft.saved_query_id && values.dataWarehouseSavedQueryMapById[draft.saved_query_id]
                                ? await api.dataWarehouseSavedQueries.get(draft.saved_query_id)
                                : undefined

                        actions.createTab(
                            hasOwnProperty(hashParams, 'q') ? String(hashParams.q) : draft.query.query,
                            associatedView,
                            undefined,
                            draft,
                            undefined,
                            biEditorStateFromUrl ?? undefined
                        )
                    }
                    return
                } else if (
                    viewIdFromUrl &&
                    (searchParams.open_view ||
                        !activeTabMatchesUrlTarget(values.activeTab, {
                            viewId: viewIdFromUrl,
                        }))
                ) {
                    // Open view
                    const viewId = viewIdFromUrl

                    actions.setViewLoading(true)
                    actions.setViewQueryLoading(true)

                    if (values.dataWarehouseSavedQueries.length === 0) {
                        await dataWarehouseViewsLogic.asyncActions.loadDataWarehouseSavedQueries()
                    }

                    const summary = values.dataWarehouseSavedQueries.find((n) => n.id === viewId)
                    if (!summary) {
                        lemonToast.error('View not found')
                        actions.setViewLoading(false)
                        actions.setViewQueryLoading(false)
                        return
                    }

                    let view: DataWarehouseSavedQuery
                    try {
                        view = await api.dataWarehouseSavedQueries.get(viewId)
                    } catch {
                        lemonToast.error('Failed to load view details')
                        actions.setViewLoading(false)
                        actions.setViewQueryLoading(false)
                        return
                    }

                    const queryToOpen =
                        searchParams.open_query ??
                        (hasOwnProperty(hashParams, 'q') ? String(hashParams.q) : (view.query?.query ?? ''))

                    if (localDraft?.baseline_query !== undefined) {
                        view = {
                            ...view,
                            query: { ...view.query, kind: NodeKind.HogQLQuery, query: localDraft.baseline_query },
                        }
                    }
                    if (localDraft?.edited_history_id) {
                        actions.setInProgressViewEdit(view.id, localDraft.edited_history_id)
                    }
                    if (outputTabFromUrl) {
                        actions.createTab(
                            queryToOpen,
                            view,
                            undefined,
                            undefined,
                            undefined,
                            biEditorStateFromUrl ?? undefined
                        )
                    } else {
                        actions.editView(queryToOpen, view, biEditorStateFromUrl ?? undefined)
                    }
                    if (hasFiltersHashParam) {
                        actions.setSourceQuery(applyFiltersFromUrl(values.sourceQuery))
                    }
                    actions.setViewLoading(false)
                    actions.setViewQueryLoading(false)
                    tabAdded = true
                    router.actions.replace(
                        values.editorUrl,
                        backLinkParams(router.values.searchParams),
                        getTabHash(values)
                    )
                } else if (
                    insightShortIdFromUrl &&
                    (searchParams.open_insight ||
                        !activeTabMatchesUrlTarget(values.activeTab, {
                            insightShortId: insightShortIdFromUrl,
                        }))
                ) {
                    // reset current tab
                    if (values.activeTab) {
                        actions.updateTab({
                            ...values.activeTab,
                            insight: undefined,
                        })
                    }
                    actions._setSuggestionPayload(null)

                    const shortId = insightShortIdFromUrl
                    if (shortId === 'new') {
                        // Add new blank tab
                        actions.createTab(
                            '',
                            undefined,
                            undefined,
                            undefined,
                            undefined,
                            biEditorStateFromUrl ?? undefined
                        )
                        tabAdded = true
                        router.actions.replace(
                            values.editorUrl,
                            backLinkParams(router.values.searchParams),
                            getTabHash(values)
                        )
                        return
                    }

                    // Open Insight
                    actions.setInsightLoading(true)
                    let insight: InsightModel | null
                    try {
                        insight = await insightsApi.getByShortId(shortId, undefined, 'async')
                    } catch {
                        actions.setInsightLoading(false)
                        lemonToast.error('Insight not found')
                        return
                    }
                    actions.setInsightLoading(false)
                    if (!insight) {
                        lemonToast.error('Insight not found')
                        return
                    }

                    if (insight.query?.kind === NodeKind.BIVisualizationNode) {
                        router.actions.replace(
                            values.featureFlags[FEATURE_FLAGS.SQL_EDITOR_BI_MODE]
                                ? urls.businessIntelligence({ insightShortId: insight.short_id })
                                : urls.insightView(insight.short_id),
                            searchParams,
                            hashParams
                        )
                        return
                    }
                    const insightVisualizationQuery = toDataVisualizationNode(insight.query)
                    const query = insightVisualizationQuery?.source.query ?? ''

                    const queryToOpen =
                        searchParams.open_query ?? (hasOwnProperty(hashParams, 'q') ? String(hashParams.q) : query)

                    let insightSource = insightVisualizationQuery
                        ? applyFiltersFromUrl(insightVisualizationQuery)
                        : undefined
                    if (insightSource) {
                        if (
                            localDraft ||
                            hasOwnProperty(hashParams, 'c') ||
                            hasOwnProperty(hashParams, 'raw') ||
                            hasEngineOverride
                        ) {
                            insightSource = {
                                ...insightSource,
                                source: {
                                    ...insightSource.source,
                                    executionTarget: connectionIdFromHash
                                        ? undefined
                                        : hasEngineOverride
                                          ? executionTargetFromHash
                                          : insightSource.source.executionTarget,
                                    connectionId: connectionIdFromHash,
                                    sendRawQuery: sendRawQueryFromHash || undefined,
                                },
                            }
                        }
                    }
                    if (insightSource) {
                        actions.setSourceQuery(insightSource)
                    }
                    actions.editInsight(queryToOpen, insight, biEditorStateFromUrl ?? undefined)
                    if (hasEngineOverride) {
                        actions.setSourceQuery({
                            ...values.sourceQuery,
                            source: {
                                ...values.sourceQuery.source,
                                executionTarget: connectionIdFromHash ? undefined : executionTargetFromHash,
                            },
                        })
                    }
                    if (!outputTabFromUrl) {
                        actions.setActiveTab(OutputTab.Visualization)
                    }

                    // Only run the query if the results aren't already cached locally and we're not using the open_query search param
                    if (!hasOwnProperty(hashParams, 'q') || queryToOpen === query) {
                        if (insightVisualizationQuery && !searchParams.open_query) {
                            const mountedDataLogic = dataNodeLogic.findMounted({
                                key: values.dataLogicKey,
                            })
                            const response = mountedDataLogic?.values.response
                            const responseLoading = mountedDataLogic?.values.responseLoading ?? false

                            if (!responseLoading && !response) {
                                actions.runQuery()
                            }
                        } else {
                            actions.runQuery()
                        }
                    }
                    tabAdded = true
                    router.actions.replace(
                        values.editorUrl,
                        backLinkParams(router.values.searchParams),
                        getTabHash(values)
                    )
                } else if (searchParams.edit_metric) {
                    // edit_metric binds the "Update metric" button to overwrite a named metric.
                    // Both edit_metric and open_query are URL-controlled, so we never bind the
                    // update target to URL-supplied SQL — a crafted link could otherwise overwrite
                    // a teammate's metric with arbitrary HogQL. Load the metric server-side and open
                    // its stored query, so the update target and its definition come from the same
                    // authenticated response.
                    actions.openMetricFromUrl(searchParams.edit_metric, biEditorStateFromUrl)
                    tabAdded = true
                } else if (hasOwnProperty(searchParams, 'open_query')) {
                    // kea-router decodes JSON-shaped URL values to objects — a node here carries
                    // visualization settings (display, chartSettings) alongside the SQL
                    const openQueryNode =
                        typeof searchParams.open_query === 'object'
                            ? toDataVisualizationNode(searchParams.open_query)
                            : undefined
                    if (openQueryNode) {
                        actions.createTab(
                            openQueryNode.source.query || '',
                            undefined,
                            undefined,
                            undefined,
                            undefined,
                            biEditorStateFromUrl ?? undefined
                        )
                        actions.setSourceQuery(hasFiltersHashParam ? applyFiltersFromUrl(openQueryNode) : openQueryNode)
                        if (!outputTabFromUrl) {
                            actions.setActiveTab(OutputTab.Visualization)
                        }
                        // Prefill only, don't auto-run: open_query is fully URL-controlled, so running here
                        // would let a crafted link execute arbitrary HogQL in the user's project on load
                    } else {
                        // kea-router also decodes numeric/JSON-shaped values; a non-node object is a
                        // malformed URL, so fall back to an empty query rather than "[object Object]"
                        actions.createTab(
                            typeof searchParams.open_query === 'object' ? '' : String(searchParams.open_query),
                            undefined,
                            undefined,
                            undefined,
                            undefined,
                            biEditorStateFromUrl ?? undefined
                        )
                    }
                    tabAdded = true
                } else if (
                    hasOwnProperty(hashParams, 'q') &&
                    !draftIdFromUrl &&
                    !viewIdFromUrl &&
                    !insightShortIdFromUrl &&
                    (values.queryInput === null ||
                        !activeTabMatchesUrlTarget(values.activeTab, {}) ||
                        values.queryInput !== String(hashParams.q))
                ) {
                    // kea-router decodes numeric/JSON-shaped URL values to non-strings; coerce so queryInput stays a string
                    actions.createTab(
                        String(hashParams.q),
                        undefined,
                        undefined,
                        undefined,
                        undefined,
                        biEditorStateFromUrl ?? undefined
                    )
                    tabAdded = true
                } else if (values.queryInput === null) {
                    actions.createTab('', undefined, undefined, undefined, undefined, biEditorStateFromUrl ?? undefined)
                    tabAdded = true
                }
            }

            if (values.queryInput === null) {
                actions.setInsightLoading(
                    !!(!draftIdFromUrl && !viewIdFromUrl && insightShortIdFromUrl && insightShortIdFromUrl !== 'new')
                )
            }

            if (props.monaco || props.mode === SQLEditorMode.BusinessIntelligence) {
                await createQueryTab()
            } else {
                // The newest URL wins. A run that a newer URL replaced drops its target when its wait times out.
                const urlOpenGeneration = (cache.urlOpenGeneration ?? 0) + 1
                cache.urlOpenGeneration = urlOpenGeneration
                cache.pendingUrlOpen = null
                const waitUntilMonaco = async (): Promise<void> => {
                    return await new Promise((resolve, reject) => {
                        let intervalCount = 0
                        const interval = setInterval(() => {
                            intervalCount++

                            if (props.monaco && !tabAdded) {
                                clearInterval(interval)
                                resolve()
                            } else if (intervalCount >= 10_000 / 300) {
                                clearInterval(interval)
                                reject()
                            }
                        }, 300)
                    })
                }

                try {
                    await waitUntilMonaco()
                    await createQueryTab()
                } catch {
                    // Monaco timed out - still try to create tab if monaco loaded late
                    if (props.monaco) {
                        await createQueryTab()
                    } else if (cache.urlOpenGeneration === urlOpenGeneration) {
                        // A hidden browser tab can delay Monaco past the wait, and nothing runs this handler
                        // again when Monaco loads. propsChanged opens the URL target when Monaco arrives.
                        cache.pendingUrlOpen = createQueryTab
                    }
                }
            }

            if (connectionIdFromHash === undefined && shouldSyncDatabaseConnection && !values.databaseLoading) {
                actions.setConnection(values.selectedSchemaConnectionId ?? null)
                actions.loadDatabase(schemaLoadOptions())
            }
        },
    })),
    afterMount(({ actions, props, values, cache }) => {
        cache.lastSchemaConnectionId = values.selectedSchemaConnectionId
        claimConnectionScope(props.tabId, values.selectedSchemaConnectionId)
        cache.activeQueryDecorationIds = [] as string[]
        cache.decorationGeneration = 0

        // Debounce the active-query decoration. It parses the HogQL AST (WASM, main thread) and
        // can fire a HogQLMetadata request, so running it on every keystroke or arrow key stalls
        // typing on long queries. Cursor moves and content changes both schedule through here.
        cache.scheduleActiveQueryDecoration = (): void => {
            if (cache.activeQueryDecorationDebounceTimeout) {
                window.clearTimeout(cache.activeQueryDecorationDebounceTimeout)
            }
            cache.activeQueryDecorationDebounceTimeout = window.setTimeout(() => {
                cache.activeQueryDecorationDebounceTimeout = null
                cache.updateActiveQueryDecoration?.()
            }, 150)
        }

        cache.updateActiveQueryDecoration = async (): Promise<void> => {
            // Bump the generation counter so any still-running invocation bails out before
            // applying stale decorations. Each run owns its own `generation` token.
            const generation = ++cache.decorationGeneration

            const editorInstance = props.editor
            if (!editorInstance?.getPosition || !editorInstance?.getModel) {
                return
            }
            const model = editorInstance.getModel()
            const position = editorInstance.getPosition()
            if (!model || !position) {
                return
            }

            // A run bails when a newer run superseded it, or when the model was disposed while it
            // awaited the parser or metadata. Switching to the BI view disposes the tab model but
            // keeps this logic mounted, so the generation counter never advances, and
            // `getPositionAt` throws "Model is disposed!" on a dead model.
            const isStale = (): boolean => generation !== cache.decorationGeneration || model.isDisposed()

            const fullText = values.queryInput ?? ''
            const queries = splitQueries(fullText)
            const cursorOffset = model.getOffsetAt(position)

            // Helper to validate a subquery standalone. Results are cached by subquery text
            // to avoid re-hitting the metadata endpoint for the same subquery on every cursor
            // move; the cache is invalidated whenever queryInput changes (see subscription).
            const validateSubquery = async (subqueryText: string): Promise<{ errorMessage: string | null }> => {
                if (!cache.subqueryValidationCache) {
                    cache.subqueryValidationCache = new Map<string, { errorMessage: string | null }>()
                }
                const cached = cache.subqueryValidationCache.get(subqueryText)
                if (cached) {
                    return cached
                }
                try {
                    const response = await performQuery<HogQLMetadata>({
                        kind: NodeKind.HogQLMetadata,
                        language: HogLanguage.hogQL,
                        query: subqueryText,
                    })
                    const errors = response?.errors ?? []
                    const result =
                        errors.length > 0
                            ? {
                                  errorMessage: `This subquery may fail standalone:\n${errors.map((e) => e.message).join('\n')}`,
                              }
                            : { errorMessage: null }
                    cache.subqueryValidationCache.set(subqueryText, result)
                    return result
                } catch {
                    return { errorMessage: 'This subquery may fail standalone' }
                }
            }

            // Resolve the innermost subquery at the cursor and build:
            //   - the range to draw the outline overlay around
            //   - per-line gutter/glyph decorations when the subquery can't run standalone
            // The outline itself is rendered via a DOM overlay (see renderQueryOutline) rather
            // than an inline className, so it reads as a frame around the code instead of a
            // text background that can be confused with selection.
            const buildSubquery = async (
                activeQuery: QueryRange,
                offset: number
            ): Promise<{ range: IRange | null; decorations: editor.IModelDeltaDecoration[] }> => {
                const subquery = await findInnermostSelectAtOffset(activeQuery.query, offset, activeQuery.start)
                if (!subquery || isStale()) {
                    return { range: null, decorations: [] }
                }
                const subStart = model.getPositionAt(subquery.start)
                const subEnd = model.getPositionAt(subquery.end)
                const range: IRange = {
                    startLineNumber: subStart.lineNumber,
                    startColumn: subStart.column,
                    endLineNumber: subEnd.lineNumber,
                    endColumn: subEnd.column,
                }
                const { errorMessage } = await validateSubquery(subquery.query)
                const decorations: editor.IModelDeltaDecoration[] = []
                if (errorMessage) {
                    decorations.push({
                        range,
                        options: {
                            linesDecorationsClassName: 'active-subquery-border-invalid',
                            hoverMessage: { value: errorMessage },
                        },
                    })
                    decorations.push({
                        range: {
                            startLineNumber: subStart.lineNumber,
                            startColumn: 1,
                            endLineNumber: subStart.lineNumber,
                            endColumn: 1,
                        },
                        options: {
                            glyphMarginClassName: 'active-subquery-glyph-invalid',
                            glyphMarginHoverMessage: { value: errorMessage },
                        },
                    })
                }
                return { range, decorations }
            }

            const applyResult = (range: IRange | null, decorations: editor.IModelDeltaDecoration[]): void => {
                cache.updateQueryOutline?.(range)
                cache.activeQueryDecorationIds = editorInstance.deltaDecorations(
                    cache.activeQueryDecorationIds ?? [],
                    decorations
                )
            }

            // Single query — outline the innermost subquery at the cursor. A flat query with no
            // nested SELECT around the cursor gets no outline at all: `findInnermostSelectAtOffset`
            // needs at least two enclosing SELECTs and returns null otherwise.
            if (queries.length <= 1) {
                const singleQuery = queries.length === 1 ? queries[0] : null
                // Offset must be the statement's start in the full text, not 0 — otherwise leading
                // whitespace/newlines desync the metadata markers (squiggles) by that many characters.
                actions.setActiveQueryText(singleQuery?.query ?? null, singleQuery?.start ?? 0)

                if (!singleQuery) {
                    if (isStale()) {
                        return
                    }
                    applyResult(null, [])
                    return
                }

                const { range, decorations } = await buildSubquery(singleQuery, cursorOffset)
                if (isStale()) {
                    return
                }
                applyResult(range, decorations)
                return
            }

            // Multiple queries — outline only the innermost subquery within the active one.
            const match = findQueryAtCursor(queries, cursorOffset)
            if (!match) {
                actions.setActiveQueryText(null, 0)
                if (isStale()) {
                    return
                }
                applyResult(null, [])
                return
            }

            actions.setActiveQueryText(match.query, match.start)

            const { range, decorations } = await buildSubquery(match, cursorOffset)
            if (isStale()) {
                return
            }

            // With several semicolon-separated statements in the editor, the inner-subquery
            // outline alone doesn't tell you which top-level statement Cmd+Enter will run.
            // A soft blue gutter bar spanning the active statement keeps that visible without
            // re-introducing a range-wide background that reads as text selection.
            const matchStart = model.getPositionAt(match.start)
            const matchEnd = model.getPositionAt(match.end)
            decorations.push({
                range: {
                    startLineNumber: matchStart.lineNumber,
                    startColumn: matchStart.column,
                    endLineNumber: matchEnd.lineNumber,
                    endColumn: matchEnd.column,
                },
                options: { linesDecorationsClassName: 'active-query-gutter' },
            })

            applyResult(range, decorations)
        }

        const expectedDatabaseConnectionId = values.selectedSchemaConnectionId ?? null
        const shouldSyncDatabaseConnection =
            values.databaseConnectionId !== expectedDatabaseConnectionId || !values.database
        const hasExplicitEditorUrlState =
            window.location.search.length > 0 ||
            window.location.hash.length > 0 ||
            removeProjectIdIfPresent(window.location.pathname) !== values.editorUrl

        if (
            (isEmbeddedSQLEditorMode(props.mode ?? SQLEditorMode.FullScene) || !hasExplicitEditorUrlState) &&
            shouldSyncDatabaseConnection
        ) {
            actions.setConnection(values.selectedSchemaConnectionId ?? null)
            // `databaseTableListLogic` is a shared singleton. If a prior visit left `databaseLoading`
            // stuck true (a load that never settled), the plain guard would skip the reload and the
            // editor would sit on "Loading..." forever. On remount we still need data, so force a
            // fresh request to bypass any hung in-flight load.
            actions.loadDatabase(schemaLoadOptions(values.databaseLoading))
        }
    }),
    beforeUnmount(({ actions, values, cache, props }) => {
        // The editor scopes the shared schema catalog to whichever connection it was querying, and
        // that logic stays mounted after the editor closes. Hand it back unscoped so pages like the
        // sources list don't render the connection's tables as if they were the project's own. Only
        // once no mounted editor still wants that connection though, or closing one of two editors
        // sharing a connection would leave the survivor with the wrong schema tree.
        if (releaseConnectionScope(props.tabId, values.databaseConnectionId)) {
            actions.resetConnectionScope()
        }

        cache.cursorDisposable?.dispose()
        cache.cursorDisposable = null
        clearQueryOutlineOverlay(cache, props.editor)
        cache.umountDataNode?.()
        cache.umountDataNode = null

        // Drop any pending decoration work so late callbacks don't touch a disposed editor.
        if (cache.activeQueryDecorationDebounceTimeout) {
            window.clearTimeout(cache.activeQueryDecorationDebounceTimeout)
            cache.activeQueryDecorationDebounceTimeout = null
        }
        if (cache.activeQueryFlashTimeout) {
            window.clearTimeout(cache.activeQueryFlashTimeout)
            cache.activeQueryFlashTimeout = null
        }
        if (cache.queryInputParseTimeout) {
            window.clearTimeout(cache.queryInputParseTimeout)
            cache.queryInputParseTimeout = null
        }
        cache.decorationGeneration = (cache.decorationGeneration ?? 0) + 1

        cache.createdModels?.forEach((m: editor.ITextModel) => {
            clearLogicReference(m)
            try {
                m.dispose()
            } catch {}
        })
        cache.createdModels = []

        const timeouts = cache.timeouts as Array<number> | undefined
        timeouts?.forEach((t) => {
            try {
                clearTimeout(t)
            } catch {}
        })
        cache.timeouts = []
    }),
])