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.

31.2 KB
Raw Blame
import {
    MakeLogicType,
    actions,
    afterMount,
    connect,
    getContext,
    kea,
    key,
    listeners,
    path,
    props,
    reducers,
    selectors,
} from 'kea'
import { loaders } from 'kea-loaders'

import api from 'lib/api'
import { ApiConfig } from 'lib/api'
import { ApiError } from 'lib/api-error'
import { FEATURE_FLAGS } from 'lib/constants'
import { lemonToast } from 'lib/lemon-ui/LemonToast'
import { FeatureFlagsSet, featureFlagLogic } from 'lib/logic/featureFlagLogic'

import { notebooksKernelComputeOptionsRetrieve } from 'products/notebooks/frontend/generated/api'
import type {
    NotebookComputeOptionsResponseApi,
    NotebookComputePresetApi,
} from 'products/notebooks/frontend/generated/api.schemas'

import { PythonKernelExecuteResponse } from '../Nodes/pythonExecution'
import type { NotebookLogicMode } from './notebookLogic'

/** A refused kernel start can stay refused for up to an hour, so "try again" copy would mislead the user. */
export function kernelActionErrorMessage(error: unknown, fallback: string): string {
    if (!(error instanceof ApiError) || error.status !== 429) {
        return fallback
    }
    // The default throttle text counts raw seconds. A sandbox limit sends a sentence written for the user.
    if (error.detail && !error.detail.startsWith('Request was throttled')) {
        return error.detail
    }
    return `Too many kernel starts and restarts. Try again ${error.formattedRetryAfter ?? 'later'}.`
}

/** A DuckDB object a SQL node can currently SELECT from, as reported by the kernel's last run. */
export type NotebookKernelFrame = {
    name: string
    /** 'frame': a dataframe a node produced. 'table'/'view': created by SQL DDL in a DuckDB node. */
    kind: 'frame' | 'table' | 'view'
    /** [column name, DuckDB type] pairs. */
    columns: [string, string][]
    /** Null when counting would need a table scan (a DDL view). */
    row_count: number | null
    /** True when row_count is DuckDB's estimate, which doesn't track deletes and can be wildly off. */
    row_count_is_estimate?: boolean
}

export type NotebookKernelInfo = {
    backend: 'docker' | 'modal' | null
    status: string
    /** Empty unless a live kernel has run something — the backend gates this on the kernel being up. */
    frames?: NotebookKernelFrame[]
    last_used_at?: string | null
    last_error?: string | null
    runtime_id?: string | null
    kernel_id?: string | null
    kernel_pid?: number | null
    sandbox_id?: string | null
    cpu_cores?: number | null
    memory_gb?: number | null
    disk_size_gb?: number | null
    idle_timeout_seconds?: number | null
    /** What this sandbox shape costs per hour while it is alive, in USD. */
    hourly_price?: number | null
    /** Compute preset the shape matches, or null when it was tuned by hand. */
    preset_key?: string | null
}

export type NotebookKernelInfoLogicProps = {
    shortId: string
    /**
     * Anything other than `'notebook'` disables the kernel poll. A canvas notebook is never
     * persisted, so `/kernel/status/` always 404s for its client-made short ID, and a canvas
     * holds no Python or SQL node that could use a kernel. Person and group profile pages
     * render one, so polling them costs a 404 every 10 seconds for as long as the page is open.
     */
    mode?: NotebookLogicMode
    /**
     * True on a shared or exported view, which renders from `cachedNotebook` precisely so it
     * issues no team-scoped requests. Both kernel endpoints are team-scoped, so a logged-out
     * viewer would get a 401 from each. Nobody can start a kernel from such a view anyway.
     */
    isShared?: boolean
}

/**
 * Sizes the sliders offer before the compute options endpoint answers. That endpoint is the
 * source of truth for both the sizes and the rates, so these only cover the first render.
 */
export const fallbackCpuCoreOptions = [0.125, 0.25, 0.5, 1, 2, 4, 6, 8, 16, 32, 64]
export const fallbackMemoryGbOptions = [0.25, 0.5, 1, 2, 4, 8, 16, 32, 64, 128, 256]
export const idleTimeoutOptions = [
    { label: '10 minutes', value: 600 },
    { label: '30 minutes', value: 1800 },
    { label: '1 hour', value: 3600 },
    { label: '3 hours', value: 10800 },
    { label: '6 hours', value: 21600 },
    { label: '12 hours', value: 43200 },
]

export type KernelActionInFlight = {
    start: boolean
    stop: boolean
    restart: boolean
    execute: boolean
    save: boolean
    refresh: boolean
}

const findClosestOptionIndex = (options: number[], value?: number | null): number => {
    if (value == null || Number.isNaN(value)) {
        return 0
    }
    const matchIndex = options.findIndex((option) => Math.abs(option - value) < 1e-6)
    if (matchIndex !== -1) {
        return matchIndex
    }
    return options.reduce((closestIndex, option, index) => {
        const closestValue = options[closestIndex]
        return Math.abs(option - value) < Math.abs(closestValue - value) ? index : closestIndex
    }, 0)
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface notebookKernelInfoLogicValues {
    featureFlags: FeatureFlagsSet // featureFlagLogic
    actionInFlight: KernelActionInFlight
    code: string
    computeBlockedReason: 'Compute rates are unavailable. Refresh to try again.' | 'Loading compute rates' | null
    computeOptions: NotebookComputeOptionsResponseApi | null
    computeOptionsFailed: boolean
    computeOptionsLoading: boolean
    computePresets: NotebookComputePresetApi[]
    cpuIndex: number
    cpuOptions: number[]
    currentCpu: number | null
    currentIdleTimeout: number
    currentMemory: number | null
    executionResult: PythonKernelExecuteResponse | null
    executionResultLoading: boolean
    hasActionInFlight: boolean
    hasConfigChanges: boolean
    idleTimeoutSeconds: number
    isBusyStatus: boolean
    isEditingConfig: boolean
    isModalKernel: boolean
    isRunning: boolean
    isSandboxComputeFree: boolean
    isStarting: boolean
    kernelInfo: NotebookKernelInfo | null
    kernelInfoLoading: boolean
    localFrames: NotebookKernelFrame[]
    memoryIndex: number
    memoryOptions: number[]
    selectedCpu: number | null
    selectedHourlyPrice: number | null
    selectedMemory: number | null
    selectedPresetKey: string | null
    statusInfo: {
        label: string
        tone: 'danger' | 'default' | 'success' | 'warning'
    } | null
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface notebookKernelInfoLogicActions {
    applyComputePreset: (preset: NotebookComputePresetApi) => {
        preset: NotebookComputePresetApi
    }
    clearExecution: () => {
        value: true
    }
    executeKernel: (code: any) => {
        code: any
    }
    executeKernelFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    executeKernelSuccess: (
        executionResult: PythonKernelExecuteResponse | null,
        payload?: {
            code: any
        }
    ) => {
        executionResult: PythonKernelExecuteResponse | null
        payload?: {
            code: any
        }
    }
    loadComputeOptions: () => any
    loadComputeOptionsFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    loadComputeOptionsSuccess: (
        computeOptions: NotebookComputeOptionsResponseApi,
        payload?: any
    ) => {
        computeOptions: NotebookComputeOptionsResponseApi
        payload?: any
    }
    loadKernelInfo: () => any
    loadKernelInfoFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    loadKernelInfoSuccess: (
        kernelInfo: NotebookKernelInfo | null,
        payload?: any
    ) => {
        kernelInfo: NotebookKernelInfo | null
        payload?: any
    }
    resetConfigToKernel: () => {
        value: true
    }
    restartKernel: () => {
        value: true
    }
    saveKernelConfig: (
        config: {
            cpu_cores?: number
            idle_timeout_seconds?: number
            memory_gb?: number
        },
        nextAction: 'restart' | 'start'
    ) => {
        config: {
            cpu_cores?: number | undefined
            idle_timeout_seconds?: number | undefined
            memory_gb?: number | undefined
        }
        nextAction: 'restart' | 'start'
    }
    saveKernelConfigFailure: () => {
        value: true
    }
    setCode: (code: string) => {
        code: string
    }
    setConfigFromKernelInfo: (config: { cpuCores: number; idleTimeoutSeconds: number; memoryGb: number }) => {
        config: {
            cpuCores: number
            idleTimeoutSeconds: number
            memoryGb: number
        }
    }
    setCpuCores: (cpuCores: number) => {
        cpuCores: number
    }
    setIdleTimeoutSeconds: (idleTimeoutSeconds: number) => {
        idleTimeoutSeconds: number
    }
    setMemoryGb: (memoryGb: number) => {
        memoryGb: number
    }
    startKernel: () => {
        value: true
    }
    stopKernel: () => {
        value: true
    }
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface notebookKernelInfoLogicMeta {
    key: string
    __keaTypeGenInternalSelectorTypes: {
        isSandboxComputeFree: (featureFlags: FeatureFlagsSet) => boolean
        isRunning: (kernelInfo: NotebookKernelInfo | null) => boolean
        statusInfo: (
            kernelInfo: NotebookKernelInfo | null,
            actionInFlight: KernelActionInFlight
        ) => {
            label: string
            tone: 'danger' | 'default' | 'success' | 'warning'
        } | null
        isStarting: (kernelInfo: NotebookKernelInfo | null, actionInFlight: KernelActionInFlight) => boolean
        isBusyStatus: (isStarting: boolean, actionInFlight: KernelActionInFlight) => boolean
        hasActionInFlight: (actionInFlight: KernelActionInFlight) => boolean
        isModalKernel: (kernelInfo: NotebookKernelInfo | null) => boolean
        localFrames: (kernelInfo: NotebookKernelInfo | null) => NotebookKernelFrame[]
        cpuOptions: (computeOptions: NotebookComputeOptionsResponseApi | null) => number[]
        memoryOptions: (computeOptions: NotebookComputeOptionsResponseApi | null) => number[]
        computePresets: (computeOptions: NotebookComputeOptionsResponseApi | null) => NotebookComputePresetApi[]
        cpuIndex: (cpuOptions: number[], selectedCpu: number | null) => number
        memoryIndex: (memoryOptions: number[], selectedMemory: number | null) => number
        currentCpu: (kernelInfo: NotebookKernelInfo | null, selectedCpu: number | null) => number | null
        currentMemory: (kernelInfo: NotebookKernelInfo | null, selectedMemory: number | null) => number | null
        selectedHourlyPrice: (
            computeOptions: NotebookComputeOptionsResponseApi | null,
            selectedCpu: number | null,
            selectedMemory: number | null
        ) => number | null
        computeBlockedReason: (
            isModalKernel: boolean,
            computeOptions: NotebookComputeOptionsResponseApi | null,
            computeOptionsLoading: boolean
        ) => 'Compute rates are unavailable. Refresh to try again.' | 'Loading compute rates' | null
        selectedPresetKey: (
            computePresets: NotebookComputePresetApi[],
            selectedCpu: number | null,
            selectedMemory: number | null
        ) => string | null
        currentIdleTimeout: (kernelInfo: NotebookKernelInfo | null) => number
        hasConfigChanges: (
            kernelInfo: NotebookKernelInfo | null,
            selectedCpu: number | null,
            selectedMemory: number | null,
            idleTimeoutSeconds: number,
            currentCpu: number | null,
            currentMemory: number | null,
            currentIdleTimeout: number
        ) => boolean
    }
}

export type notebookKernelInfoLogicType = MakeLogicType<
    notebookKernelInfoLogicValues,
    notebookKernelInfoLogicActions,
    NotebookKernelInfoLogicProps,
    notebookKernelInfoLogicMeta
>

export const notebookKernelInfoLogic = kea<notebookKernelInfoLogicType>([
    props({} as NotebookKernelInfoLogicProps),
    path((key) => ['scenes', 'notebooks', 'Notebook', 'notebookKernelInfoLogic', key]),
    key(({ shortId }) => shortId),
    connect(() => ({
        values: [featureFlagLogic, ['featureFlags']],
    })),
    actions({
        executeKernel: (code) => ({ code }),
        setCode: (code: string) => ({ code }),
        setCpuCores: (cpuCores: number) => ({ cpuCores }),
        setMemoryGb: (memoryGb: number) => ({ memoryGb }),
        applyComputePreset: (preset: NotebookComputePresetApi) => ({ preset }),
        setIdleTimeoutSeconds: (idleTimeoutSeconds: number) => ({ idleTimeoutSeconds }),
        resetConfigToKernel: true,
        setConfigFromKernelInfo: (config: { cpuCores: number; memoryGb: number; idleTimeoutSeconds: number }) => ({
            config,
        }),
        startKernel: true,
        stopKernel: true,
        restartKernel: true,
        saveKernelConfig: (
            config: { cpu_cores?: number; memory_gb?: number; idle_timeout_seconds?: number },
            nextAction: 'start' | 'restart'
        ) => ({
            config,
            nextAction,
        }),
        saveKernelConfigFailure: true,
        clearExecution: true,
    }),
    reducers({
        code: [
            'print("Kernel ready")',
            {
                setCode: (_, { code }) => code,
            },
        ],
        selectedCpu: [
            null as number | null,
            {
                setCpuCores: (_, { cpuCores }) => cpuCores,
                applyComputePreset: (_, { preset }) => preset.cpu_cores,
                setConfigFromKernelInfo: (_, { config }) => config.cpuCores,
            },
        ],
        selectedMemory: [
            null as number | null,
            {
                setMemoryGb: (_, { memoryGb }) => memoryGb,
                applyComputePreset: (_, { preset }) => preset.memory_gb,
                setConfigFromKernelInfo: (_, { config }) => config.memoryGb,
            },
        ],
        idleTimeoutSeconds: [
            idleTimeoutOptions[1].value,
            {
                setIdleTimeoutSeconds: (_, { idleTimeoutSeconds }) => idleTimeoutSeconds,
                setConfigFromKernelInfo: (_, { config }) => config.idleTimeoutSeconds,
            },
        ],
        computeOptionsFailed: [
            false,
            {
                loadComputeOptions: () => false,
                loadComputeOptionsSuccess: () => false,
                loadComputeOptionsFailure: () => true,
            },
        ],
        isEditingConfig: [
            false,
            {
                setCpuCores: () => true,
                setMemoryGb: () => true,
                applyComputePreset: () => true,
                setIdleTimeoutSeconds: () => true,
                setConfigFromKernelInfo: () => false,
                resetConfigToKernel: () => false,
                saveKernelConfig: () => false,
                saveKernelConfigFailure: () => true,
            },
        ],
        actionInFlight: [
            {
                start: false,
                stop: false,
                restart: false,
                execute: false,
                save: false,
                refresh: false,
            } as KernelActionInFlight,
            {
                startKernel: (state) => ({ ...state, start: true }),
                stopKernel: (state) => ({ ...state, stop: true }),
                restartKernel: (state) => ({ ...state, restart: true }),
                executeKernel: (state) => ({ ...state, execute: true }),
                saveKernelConfig: (state) => ({ ...state, save: true }),
                loadKernelInfo: (state) => ({ ...state, refresh: true }),
                loadKernelInfoSuccess: (state, { kernelInfo }) => ({
                    ...state,
                    start: false,
                    stop: state.stop && kernelInfo?.status === 'running',
                    restart: false,
                    save: false,
                    refresh: false,
                }),
                loadKernelInfoFailure: (state) => ({
                    ...state,
                    start: false,
                    stop: false,
                    restart: false,
                    save: false,
                    refresh: false,
                }),
                executeKernelSuccess: (state) => ({ ...state, execute: false }),
                executeKernelFailure: (state) => ({ ...state, execute: false }),
                saveKernelConfigFailure: (state) => ({ ...state, save: false }),
            },
        ],
    }),
    loaders(({ props }) => ({
        computeOptions: [
            null as NotebookComputeOptionsResponseApi | null,
            {
                // Deliberately unguarded: a swallowed failure is indistinguishable from the
                // null the loader starts with, which left the panel quietly unpriced while
                // every control that spends money stayed live.
                loadComputeOptions: async () => {
                    return await notebooksKernelComputeOptionsRetrieve(String(ApiConfig.getCurrentTeamId()))
                },
            },
        ],
        kernelInfo: [
            null as NotebookKernelInfo | null,
            {
                loadKernelInfo: async () => {
                    try {
                        const response = (await api.notebooks.kernelStatus(props.shortId)) as NotebookKernelInfo
                        return response.backend ? response : null
                    } catch {
                        return null
                    }
                },
            },
        ],
        executionResult: [
            null as PythonKernelExecuteResponse | null,
            {
                executeKernel: async ({ code }): Promise<PythonKernelExecuteResponse | null> => {
                    return (await api.notebooks.kernelExecute(props.shortId, {
                        code,
                        return_variables: false,
                    })) as PythonKernelExecuteResponse
                },
            },
        ],
    })),
    selectors({
        isSandboxComputeFree: [
            (s) => [s.featureFlags],
            (featureFlags: FeatureFlagsSet): boolean => !!featureFlags[FEATURE_FLAGS.NOTEBOOK_SANDBOX_FREE_COMPUTE],
        ],
        isRunning: [
            (s) => [s.kernelInfo],
            (kernelInfo: NotebookKernelInfo | null) =>
                kernelInfo?.status === 'running' ||
                (kernelInfo?.status === 'starting' && kernelInfo?.last_error == null),
        ],
        statusInfo: [
            (s) => [s.kernelInfo, s.actionInFlight],
            (kernelInfo: NotebookKernelInfo | null, actionInFlight: KernelActionInFlight) => {
                if (!kernelInfo) {
                    return null
                }
                if (actionInFlight.stop) {
                    return { label: 'Stopping', tone: 'warning' as const }
                }
                if (actionInFlight.restart) {
                    return { label: 'Restarting', tone: 'warning' as const }
                }
                if (actionInFlight.start && kernelInfo.status !== 'starting') {
                    return { label: 'Starting', tone: 'warning' as const }
                }
                if (kernelInfo.last_error) {
                    return { label: 'Error', tone: 'danger' as const }
                }
                const statusTone: Record<
                    string,
                    { label: string; tone: 'success' | 'warning' | 'danger' | 'default' }
                > = {
                    running: { label: 'Running', tone: 'success' },
                    starting: { label: 'Starting', tone: 'warning' },
                    stopped: { label: 'Stopped', tone: 'default' },
                    timed_out: { label: 'Timed out', tone: 'warning' },
                    discarded: { label: 'Discarded', tone: 'default' },
                    error: { label: 'Error', tone: 'danger' },
                }
                return statusTone[kernelInfo.status] ?? { label: kernelInfo.status, tone: 'default' }
            },
        ],
        isStarting: [
            (s) => [s.kernelInfo, s.actionInFlight],
            (kernelInfo: NotebookKernelInfo | null, actionInFlight: KernelActionInFlight) =>
                (kernelInfo?.status === 'starting' && kernelInfo?.last_error == null) || actionInFlight.start,
        ],
        isBusyStatus: [
            (s) => [s.isStarting, s.actionInFlight],
            (isStarting: boolean, actionInFlight: KernelActionInFlight) =>
                isStarting || actionInFlight.stop || actionInFlight.restart,
        ],
        hasActionInFlight: [
            (s) => [s.actionInFlight],
            (actionInFlight: KernelActionInFlight) => Object.values(actionInFlight).some(Boolean),
        ],
        isModalKernel: [
            (s) => [s.kernelInfo],
            (kernelInfo: NotebookKernelInfo | null) => kernelInfo?.backend === 'modal',
        ],
        localFrames: [(s) => [s.kernelInfo], (kernelInfo: NotebookKernelInfo | null) => kernelInfo?.frames ?? []],
        cpuOptions: [
            (s) => [s.computeOptions],
            (computeOptions: NotebookComputeOptionsResponseApi | null) =>
                computeOptions?.allowed_cpu_cores ?? fallbackCpuCoreOptions,
        ],
        memoryOptions: [
            (s) => [s.computeOptions],
            (computeOptions: NotebookComputeOptionsResponseApi | null) =>
                computeOptions?.allowed_memory_gb ?? fallbackMemoryGbOptions,
        ],
        computePresets: [
            (s) => [s.computeOptions],
            (computeOptions: NotebookComputeOptionsResponseApi | null) => computeOptions?.presets ?? [],
        ],
        cpuIndex: [
            (s) => [s.cpuOptions, s.selectedCpu],
            (cpuOptions: number[], selectedCpu: number | null) => findClosestOptionIndex(cpuOptions, selectedCpu),
        ],
        memoryIndex: [
            (s) => [s.memoryOptions, s.selectedMemory],
            (memoryOptions: number[], selectedMemory: number | null) =>
                findClosestOptionIndex(memoryOptions, selectedMemory),
        ],
        currentCpu: [
            (s) => [s.kernelInfo, s.selectedCpu],
            (kernelInfo: NotebookKernelInfo | null, selectedCpu: number | null) => kernelInfo?.cpu_cores ?? selectedCpu,
        ],
        currentMemory: [
            (s) => [s.kernelInfo, s.selectedMemory],
            (kernelInfo: NotebookKernelInfo | null, selectedMemory: number | null) =>
                kernelInfo?.memory_gb ?? selectedMemory,
        ],
        /** Price of the shape the user currently has selected, whether they picked it or tuned it. */
        selectedHourlyPrice: [
            (s) => [s.computeOptions, s.selectedCpu, s.selectedMemory],
            (
                computeOptions: NotebookComputeOptionsResponseApi | null,
                selectedCpu: number | null,
                selectedMemory: number | null
            ) => {
                if (selectedCpu == null || selectedMemory == null) {
                    return null
                }
                if (computeOptions) {
                    return (
                        selectedCpu * computeOptions.cpu_rate_per_core_hour +
                        selectedMemory * computeOptions.memory_rate_per_gb_hour
                    )
                }
                // No fallback to kernelInfo.hourly_price: that prices the sandbox currently
                // running, while cpu_cores and memory_gb describe the configured shape the
                // sliders show. The two differ between a resize and the restart that applies it,
                // so reusing it here would print a price for a shape that is not on screen.
                // Without the rates the panel shows no price and blocks configuration instead.
                return null
            },
        ],
        /**
         * Why compute configuration is blocked, or null when it is allowed. A Modal sandbox is
         * charged, so it may not be started or resized while the rates are unknown.
         */
        computeBlockedReason: [
            (s) => [s.isModalKernel, s.computeOptions, s.computeOptionsLoading],
            (isModalKernel: boolean, computeOptions: NotebookComputeOptionsResponseApi | null, loading: boolean) => {
                if (!isModalKernel || computeOptions) {
                    return null
                }
                return loading ? 'Loading compute rates' : 'Compute rates are unavailable. Refresh to try again.'
            },
        ],
        selectedPresetKey: [
            (s) => [s.computePresets, s.selectedCpu, s.selectedMemory],
            (presets: NotebookComputePresetApi[], selectedCpu: number | null, selectedMemory: number | null) =>
                presets.find(
                    (preset) =>
                        selectedCpu != null &&
                        selectedMemory != null &&
                        Math.abs(preset.cpu_cores - selectedCpu) < 1e-6 &&
                        Math.abs(preset.memory_gb - selectedMemory) < 1e-6
                )?.key ?? null,
        ],
        currentIdleTimeout: [
            (s) => [s.kernelInfo],
            (kernelInfo: NotebookKernelInfo | null) => kernelInfo?.idle_timeout_seconds ?? idleTimeoutOptions[1].value,
        ],
        hasConfigChanges: [
            (s) => [
                s.kernelInfo,
                s.selectedCpu,
                s.selectedMemory,
                s.idleTimeoutSeconds,
                s.currentCpu,
                s.currentMemory,
                s.currentIdleTimeout,
            ],
            (
                kernelInfo: NotebookKernelInfo | null,
                selectedCpu: number | null,
                selectedMemory: number | null,
                idleTimeoutSeconds: number,
                currentCpu: number | null,
                currentMemory: number | null,
                currentIdleTimeout: number
            ) =>
                Boolean(
                    kernelInfo &&
                    selectedCpu != null &&
                    selectedMemory != null &&
                    currentCpu != null &&
                    currentMemory != null &&
                    (Math.abs(selectedCpu - currentCpu) > 1e-6 ||
                        Math.abs(selectedMemory - currentMemory) > 1e-6 ||
                        idleTimeoutSeconds !== currentIdleTimeout)
                ),
        ],
    }),
    listeners(({ actions, props, values }) => ({
        startKernel: async () => {
            try {
                await api.notebooks.kernelStart(props.shortId)
            } catch (error) {
                lemonToast.error(kernelActionErrorMessage(error, 'The kernel could not be started. Try again.'))
            } finally {
                actions.loadKernelInfo()
            }
        },
        stopKernel: async () => {
            try {
                await api.notebooks.kernelStop(props.shortId)
            } finally {
                actions.loadKernelInfo()
            }
        },
        restartKernel: async () => {
            try {
                await api.notebooks.kernelRestart(props.shortId)
            } catch (error) {
                lemonToast.error(kernelActionErrorMessage(error, 'The kernel could not be restarted. Try again.'))
            } finally {
                actions.loadKernelInfo()
            }
        },
        saveKernelConfig: async ({ config, nextAction }) => {
            let restarted = false
            try {
                const response = (await api.notebooks.kernelConfig(props.shortId, config)) as {
                    restarted?: boolean
                }
                restarted = response?.restarted ?? false
            } catch {
                actions.saveKernelConfigFailure()
                return
            }
            if (nextAction === 'start') {
                actions.startKernel()
                return
            }
            // A resize restarts the live kernel server-side. Restarting again would tear down the
            // sandbox that was just built for the new shape.
            if (restarted) {
                actions.loadKernelInfo()
                return
            }
            actions.restartKernel()
        },
        loadKernelInfoSuccess: ({ kernelInfo }) => {
            if (!kernelInfo) {
                return
            }
            if (values.isEditingConfig && values.hasConfigChanges) {
                return
            }
            actions.setConfigFromKernelInfo({
                cpuCores: kernelInfo.cpu_cores ?? values.cpuOptions[0],
                memoryGb: kernelInfo.memory_gb ?? values.memoryOptions[0],
                idleTimeoutSeconds: kernelInfo.idle_timeout_seconds ?? idleTimeoutOptions[1].value,
            })
        },
        resetConfigToKernel: () => {
            if (!values.kernelInfo) {
                return
            }
            actions.setConfigFromKernelInfo({
                cpuCores: values.kernelInfo.cpu_cores ?? values.cpuOptions[0],
                memoryGb: values.kernelInfo.memory_gb ?? values.memoryOptions[0],
                idleTimeoutSeconds: values.kernelInfo.idle_timeout_seconds ?? idleTimeoutOptions[1].value,
            })
        },
        executeKernelSuccess: () => {
            actions.loadKernelInfo()
        },
        executeKernelFailure: () => {
            actions.loadKernelInfo()
        },
        clearExecution: () => {
            actions.executeKernelSuccess(null)
        },
    })),
    afterMount(({ actions, cache, props, values }) => {
        if ((props.mode && props.mode !== 'notebook') || props.isShared) {
            return
        }
        // Replacing the kea context drops this logic's path from the store without unmounting it,
        // so the disposable never runs its cleanup and the timer survives. Storybook does that on
        // every story mount. Reading `values` after it either throws "Can not find path" or, once
        // something else mounts at the same path, reads a store this loop no longer belongs to.
        // Captured out here rather than inside the setup, because the plugin holds every manager
        // in a module-level set and reruns setup when the tab becomes visible. A context read
        // inside the setup would be the context of that rerun, which compares equal to itself and
        // guards nothing.
        const mountedIn = getContext()
        const isLive = (): boolean => getContext() === mountedIn
        actions.loadKernelInfo()
        actions.loadComputeOptions()
        cache.disposables.add(() => {
            // Reschedules itself rather than using setInterval, because a starting kernel is
            // polled five times more often than a settled one.
            let timeoutId = 0
            const scheduleRefresh = (): void => {
                if (!isLive()) {
                    return
                }
                timeoutId = window.setTimeout(
                    () => {
                        if (!isLive()) {
                            return
                        }
                        if (!values.actionInFlight.refresh) {
                            actions.loadKernelInfo()
                        }
                        scheduleRefresh()
                    },
                    values.isStarting ? 2000 : 10000
                )
            }
            scheduleRefresh()
            return () => clearTimeout(timeoutId)
        }, 'kernelInfoRefresh')
    }),
])