: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(notebooks): color the cell gutter by run state (#74220)
Sinan Kucukkoseler185a2eeafdb7
diff --git a/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.scss b/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.scssindex 7738576492c8..690616b25165 100644--- a/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.scss+++ b/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.scss@@ -1606,18 +1606,35 @@ h3.MarkdownNotebook__text-block--heading {padding: 0.25rem;}+// The left gutter carries the block's run state: grey for blocks that don't run or haven't+// run yet, green when the last run succeeded, red when it failed, yellow when the result is+// out of date. Set by the --status- modifiers below..MarkdownNotebook__component-shell {+ --markdown-notebook-component-gutter: var(--markdown-notebook-text-block-gutter);+position: relative;margin: 0.5rem 0 0.5rem var(--markdown-notebook-content-offset);overflow: hidden;background: var(--markdown-notebook-component-background);border: 1px solid var(--markdown-notebook-component-border);- border-left: 3px solid- color-mix(in oklab, var(--color-text-success) 45%, var(--markdown-notebook-component-background));+ border-left: 3px solid var(--markdown-notebook-component-gutter);border-radius: 0.25rem;border-top-left-radius: 0;border-bottom-left-radius: 0;outline: none;+ transition: border-left-color 150ms linear;+}++.MarkdownNotebook__component-shell--status-success {+ --markdown-notebook-component-gutter: var(--color-text-success);+}++.MarkdownNotebook__component-shell--status-error {+ --markdown-notebook-component-gutter: var(--color-text-error);+}++.MarkdownNotebook__component-shell--status-stale {+ --markdown-notebook-component-gutter: var(--color-text-warning);}.MarkdownNotebook__component-shell:focus::after,diff --git a/frontend/src/lib/components/MarkdownNotebook/NotebookComponentShell.test.tsx b/frontend/src/lib/components/MarkdownNotebook/NotebookComponentShell.test.tsxindex 30c538fa4f26..431c881fb4d4 100644--- a/frontend/src/lib/components/MarkdownNotebook/NotebookComponentShell.test.tsx+++ b/frontend/src/lib/components/MarkdownNotebook/NotebookComponentShell.test.tsx@@ -1,6 +1,7 @@import { fireEvent, render, screen } from '@testing-library/react'import { useComponentPanelState } from './componentPanelContext'+import { NotebookComponentRunStatusContext } from './componentRunStatus'import { NotebookComponentShell } from './NotebookComponentShell'import { createMarkdownNotebookRegistry } from './registry'@@ -100,4 +101,46 @@ describe('NotebookComponentShell', () => {expect(toggleComponentPanel).toHaveBeenCalledWith('filters')})++ it('marks the block with the run status the host resolves for it', () => {+ const registry = createMarkdownNotebookRegistry([+ {+ tagName: 'Probe',+ label: 'Probe',+ category: 'Test',+ ViewComponent: () => <div>Results</div>,+ },+ ])++ const { container } = render(+ <NotebookComponentRunStatusContext.Provider value={() => 'stale'}>+ <NotebookComponentShell+ node={{+ id: 'probe-node',+ type: 'component',+ tagName: 'Probe',+ props: {},+ }}+ mode="edit"+ componentPanels={{ filters: false, results: true }}+ persistComponentPanelVisibility={false}+ isSelected={false}+ registry={registry}+ toggleComponentPanel={jest.fn()}+ setLocalComponentPanels={jest.fn()}+ rememberComponentPanels={jest.fn()}+ setBlockRef={jest.fn()}+ updateNode={jest.fn()}+ deleteNode={jest.fn()}+ deleteSelectedNotebookBlocks={jest.fn(() => false)}+ insertParagraphAfterNode={jest.fn()}+ moveFocusToAdjacentNode={jest.fn(() => false)}+ />+ </NotebookComponentRunStatusContext.Provider>+ )++ const shell = container.querySelector('.MarkdownNotebook__component-shell') as HTMLElement++ expect(shell.classList.contains('MarkdownNotebook__component-shell--status-stale')).toBe(true)+ })})diff --git a/frontend/src/lib/components/MarkdownNotebook/NotebookComponentShell.tsx b/frontend/src/lib/components/MarkdownNotebook/NotebookComponentShell.tsxindex 7d8368466c6e..3d6f2a86c6db 100644--- a/frontend/src/lib/components/MarkdownNotebook/NotebookComponentShell.tsx+++ b/frontend/src/lib/components/MarkdownNotebook/NotebookComponentShell.tsx@@ -22,6 +22,7 @@ import {DEFAULT_COMPONENT_PANEL_VISIBILITY,withPersistedComponentPanelProps,} from './componentPanels'+import { useNotebookComponentRunStatus } from './componentRunStatus'import { getNotebookObjectProp, getNotebookStringProp } from './documentModel'import { InsertMenuSelectionDirection } from './editorTypes'import { getMarkdownNotebookComponentDefinition } from './registry'@@ -81,6 +82,7 @@ export function NotebookComponentShell({moveFocusToAdjacentNode,}: NotebookComponentShellProps): JSX.Element {const definition = getMarkdownNotebookComponentDefinition(registry, node.tagName)+ const runStatus = useNotebookComponentRunStatus(node)const errors = [...(node.errors ?? []), ...(definition?.validateProps?.(node.props) ?? [])]const ViewComponent = definition?.ViewComponentconst EditComponent = definition?.EditComponent ?? definition?.ViewComponent@@ -276,6 +278,7 @@ export function NotebookComponentShell({<divclassName={clsx('MarkdownNotebook__component-shell',+ `MarkdownNotebook__component-shell--status-${runStatus}`,isSelected && 'MarkdownNotebook__component-shell--selected',errors.length && 'MarkdownNotebook__component-shell--error')}diff --git a/frontend/src/lib/components/MarkdownNotebook/componentRunStatus.ts b/frontend/src/lib/components/MarkdownNotebook/componentRunStatus.tsnew file mode 100644index 000000000000..19eccaaebfff--- /dev/null+++ b/frontend/src/lib/components/MarkdownNotebook/componentRunStatus.ts@@ -0,0 +1,18 @@+import { createContext, useContext } from 'react'++import { NotebookComponentBlockNode } from './types'++/** Run state of a component block, shown as the colour of the block's left gutter. */+export type NotebookComponentRunStatus = 'idle' | 'success' | 'error' | 'stale'++/** Supplied by the notebook host: this component knows how to colour a block, not how to run one.+ * Blocks with no resolver (and hosts with none) stay 'idle'. */+export type NotebookComponentRunStatusResolver = (node: NotebookComponentBlockNode) => NotebookComponentRunStatus++export const NotebookComponentRunStatusContext = createContext<NotebookComponentRunStatusResolver | null>(null)++export function useNotebookComponentRunStatus(node: NotebookComponentBlockNode): NotebookComponentRunStatus {+ const resolveRunStatus = useContext(NotebookComponentRunStatusContext)++ return resolveRunStatus?.(node) ?? 'idle'+}diff --git a/frontend/src/lib/components/MarkdownNotebook/index.ts b/frontend/src/lib/components/MarkdownNotebook/index.tsindex 5b2acc08a326..7df40406d73f 100644--- a/frontend/src/lib/components/MarkdownNotebook/index.ts+++ b/frontend/src/lib/components/MarkdownNotebook/index.ts@@ -8,6 +8,8 @@ export {getMarkdownNotebookComponentDefaultProps,mergeMarkdownNotebookRegistries,} from './registry'+export { NotebookComponentRunStatusContext } from './componentRunStatus'+export type { NotebookComponentRunStatus, NotebookComponentRunStatusResolver } from './componentRunStatus'export { parseMarkdownNotebook, serializeMarkdownNotebook, htmlElementToInlineNodes } from './markdown'export { MarkdownTextDiff } from './MarkdownTextDiff'export type { MarkdownTextDiffProps } from './MarkdownTextDiff'diff --git a/frontend/src/scenes/notebooks/Nodes/NotebookNodePythonV2.tsx b/frontend/src/scenes/notebooks/Nodes/NotebookNodePythonV2.tsxindex c1d2f6b5ba6f..06ededf28ae7 100644--- a/frontend/src/scenes/notebooks/Nodes/NotebookNodePythonV2.tsx+++ b/frontend/src/scenes/notebooks/Nodes/NotebookNodePythonV2.tsx@@ -7,6 +7,7 @@ import { IconCancel } from 'lib/lemon-ui/icons'import { LemonButton } from 'lib/lemon-ui/LemonButton'import { CodeEditorResizeable } from 'lib/monaco/CodeEditorResizable'import { createPostHogWidgetNode } from 'scenes/notebooks/Nodes/NodeWrapper'+import type { NotebookNodeRunTerminalStatus } from 'scenes/notebooks/Notebook/notebookNodeStalenessLogic'import { NotebookNodeAttributeProperties, NotebookNodeProps, NotebookNodeType } from '../types'import { NotebookDataframeTable } from './components/NotebookDataframeTable'@@ -28,6 +29,9 @@ export type NotebookNodePythonV2Attributes = {returnVariable: stringrunId?: string | nullresult?: NotebookNodeSQLV2Result | null+ // How the run that produced `result` ended. An interrupt persists whatever the cell printed+ // before the stop landed, so the result alone can't tell the two apart on a reload.+ runStatus?: NotebookNodeRunTerminalStatus | null}const toDataframeResult = (result: NotebookNodeSQLV2Result): NotebookDataframeResult => {@@ -318,6 +322,9 @@ export const NotebookNodePythonV2 = createPostHogWidgetNode<NotebookNodePythonV2result: {default: null,},+ runStatus: {+ default: null,+ },},Settings,settingsPlacement: 'inline',diff --git a/frontend/src/scenes/notebooks/Nodes/NotebookNodeSQLV2.tsx b/frontend/src/scenes/notebooks/Nodes/NotebookNodeSQLV2.tsxindex af72db31b4ea..90be785b22ed 100644--- a/frontend/src/scenes/notebooks/Nodes/NotebookNodeSQLV2.tsx+++ b/frontend/src/scenes/notebooks/Nodes/NotebookNodeSQLV2.tsx@@ -6,6 +6,7 @@ import { IconCornerDownRight } from '@posthog/icons'import { LemonTabs } from 'lib/lemon-ui/LemonTabs'import { OutputTab } from 'scenes/data-warehouse/editor/outputPaneLogic'import { createPostHogWidgetNode } from 'scenes/notebooks/Nodes/NodeWrapper'+import type { NotebookNodeRunTerminalStatus } from 'scenes/notebooks/Notebook/notebookNodeStalenessLogic'import { Query } from '~/queries/Query/Query'import { DataVisualizationNode, HogQLQueryResponse, NodeKind } from '~/queries/schema/schema-general'@@ -42,6 +43,9 @@ export type NotebookNodeSQLV2Attributes = {returnVariable: stringrunId?: string | nullresult?: NotebookNodeSQLV2Result | null+ // How the run that produced `result` ended. An interrupt persists a partial result just+ // like a completed run does, so the result alone can't tell the two apart on a reload.+ runStatus?: NotebookNodeRunTerminalStatus | nulloutputTab?: OutputTab | nullvizQuery?: DataVisualizationNode | null}@@ -390,6 +394,9 @@ export const NotebookNodeSQLV2 = createPostHogWidgetNode<NotebookNodeSQLV2Attribresult: {default: null,},+ runStatus: {+ default: null,+ },outputTab: {default: OutputTab.Results,},diff --git a/frontend/src/scenes/notebooks/Nodes/notebookNodeSQLV2Logic.test.ts b/frontend/src/scenes/notebooks/Nodes/notebookNodeSQLV2Logic.test.tsindex 3604200dc571..f716eafbf308 100644--- a/frontend/src/scenes/notebooks/Nodes/notebookNodeSQLV2Logic.test.ts+++ b/frontend/src/scenes/notebooks/Nodes/notebookNodeSQLV2Logic.test.ts@@ -206,7 +206,7 @@ describe('notebookNodeSQLV2Logic', () => {expect(runSpy).toHaveBeenCalledWith('nb1', { node_id: 'n1', code: 'select 1', refs: {} })// runId is persisted so a reload/remount can recover the in-flight run; nodeId is// pinned so the markdown cell's fingerprint id can't drift away from the run's node_id.- expect(updateAttributes).toHaveBeenCalledWith({ nodeId: 'n1', runId: 'r1', result: null })+ expect(updateAttributes).toHaveBeenCalledWith({ nodeId: 'n1', runId: 'r1', result: null, runStatus: null })})it('dispatches a python run with its node type and output name', async () => {@@ -245,6 +245,7 @@ describe('notebookNodeSQLV2Logic', () => {stderr: '',media: [],},+ runStatus: 'done',})expect(logic.values.isRunning).toBe(false)})@@ -267,8 +268,11 @@ describe('notebookNodeSQLV2Logic', () => {})mount({ runId: 'r1', hasResult: false })await expectLogic(logic).toFinishAllListeners()+ // The outcome is persisted with the partial result: without it a reload can't tell this+ // apart from a completed run, since both leave a result behind.expect(updateAttributes).toHaveBeenCalledWith({result: expect.objectContaining({ stdout: 'partial output' }),+ runStatus: 'interrupted',})expect(logic.values.runError).toBe('Run interrupted.')expect(logic.values.isRunning).toBe(false)diff --git a/frontend/src/scenes/notebooks/Nodes/notebookNodeSQLV2Logic.ts b/frontend/src/scenes/notebooks/Nodes/notebookNodeSQLV2Logic.tsindex 7a36683c50d0..d588fd7e67c7 100644--- a/frontend/src/scenes/notebooks/Nodes/notebookNodeSQLV2Logic.ts+++ b/frontend/src/scenes/notebooks/Nodes/notebookNodeSQLV2Logic.ts@@ -18,7 +18,7 @@ import { JSONContent } from 'lib/components/RichContentEditor/types'import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'import { notebookKernelInfoLogic } from '../Notebook/notebookKernelInfoLogic'-import { notebookNodeStalenessLogic } from '../Notebook/notebookNodeStalenessLogic'+import { NotebookNodeRunTerminalStatus, notebookNodeStalenessLogic } from '../Notebook/notebookNodeStalenessLogic'import { NotebookOperation, notebookOperationsLogic } from '../Notebook/notebookOperationsLogic'import { notebookSettingsLogic } from '../Notebook/notebookSettingsLogic'import { NotebookNodeType } from '../types'@@ -100,6 +100,7 @@ export interface NotebookNodeSQLV2LogicProps {nodeId?: stringrunId?: string | nullresult?: NotebookNodeSQLV2Result | null+ runStatus?: NotebookNodeRunTerminalStatus | null}) => void// The live notebook document, for staleness marking and chain-dispatched runs (Journey 10).getContent?: () => JSONContent | null@@ -135,12 +136,12 @@ export interface notebookNodeSQLV2LogicActions {} // notebookNodeStalenessLogicnodeRunFinished: (nodeId: string,- status: import('../Notebook/notebookNodeStalenessLogic').NotebookNodeRunTerminalStatus,+ status: NotebookNodeRunTerminalStatus,content: JSONContent | null) => {content: JSONContent | nullnodeId: string- status: import('../Notebook/notebookNodeStalenessLogic').NotebookNodeRunTerminalStatus+ status: NotebookNodeRunTerminalStatus} // notebookNodeStalenessLogicregisterChainNode: (nodeId: string) => {nodeId: string@@ -504,7 +505,12 @@ export const notebookNodeSQLV2Logic = kea<notebookNodeSQLV2LogicType>([// Persisting nodeId pins the cell's identity: markdown-notebook cell ids are// content fingerprints otherwise, so without the pin any later prop change// would orphan this run's node_id and break refs to this cell.- props.updateAttributes({ nodeId: props.nodeId, runId: run_id, result: null })+ props.updateAttributes({+ nodeId: props.nodeId,+ runId: run_id,+ result: null,+ runStatus: null,+ })actions.startPolling(run_id)} catch (error) {actions.setRunError(error instanceof Error ? error.message : 'Failed to run query')@@ -596,7 +602,9 @@ export const notebookNodeSQLV2Logic = kea<notebookNodeSQLV2LogicType>([}: null)- props.updateAttributes({ result: envelopeResult })+ // The outcome rides along with the result so a reload can tell a completed+ // run from an interrupted one — both leave a result behind.+ props.updateAttributes({ result: envelopeResult, runStatus: 'done' })// A fresh envelope replaces whatever page the user had drilled into.actions.resetPaging()actions.stopPolling()@@ -606,7 +614,7 @@ export const notebookNodeSQLV2Logic = kea<notebookNodeSQLV2LogicType>([} else if (status === 'interrupted') {// A user-requested stop: the envelope still carries whatever stdout,// stderr, and figures the cell produced before the interrupt landed.- props.updateAttributes({ result: envelopeResult })+ props.updateAttributes({ result: envelopeResult, runStatus: 'interrupted' })actions.setRunError(error ?? 'Run interrupted.')actions.resetPaging()actions.stopPolling()diff --git a/frontend/src/scenes/notebooks/Notebook/MarkdownNotebookV2Renderer.tsx b/frontend/src/scenes/notebooks/Notebook/MarkdownNotebookV2Renderer.tsxindex 87203cae1704..56afb88c7a4d 100644--- a/frontend/src/scenes/notebooks/Notebook/MarkdownNotebookV2Renderer.tsx+++ b/frontend/src/scenes/notebooks/Notebook/MarkdownNotebookV2Renderer.tsx@@ -1,4 +1,4 @@-import { useActions, useValues } from 'kea'+import { useActions, useMountedLogic, useValues } from 'kea'import posthog from 'posthog-js'import { useCallback, useEffect, useMemo, useRef, useState } from 'react'@@ -6,7 +6,11 @@ import { IconFlask, IconGraph, IconMessage, IconPeople, IconRocket, IconToggle }import { lemonToast } from '@posthog/lemon-ui'import api from 'lib/api'-import { MarkdownNotebook, parseMarkdownNotebook } from 'lib/components/MarkdownNotebook'+import {+ MarkdownNotebook,+ NotebookComponentRunStatusContext,+ parseMarkdownNotebook,+} from 'lib/components/MarkdownNotebook'import type {InsertCommand,MarkdownNotebookAskAIRequest,@@ -36,6 +40,7 @@ import {import { MarkdownNotebookExperimentPicker } from './MarkdownNotebookExperimentPicker'import { InlineAIAssistantMessage, InlineAICompletion, InlineNotebookAIRunner } from './MarkdownNotebookInlineAI'import { getMarkdownRegistryForFeatureFlags } from './markdownNotebookRegistry'+import { useNotebookComponentRunStatusResolver } from './markdownNotebookRunStatus'import {InlineNotebookAIRequest,MarkdownNotebookRuntimeContext,@@ -80,10 +85,12 @@ type MarkdownNotebookEntityPickerKind =| 'cohort'export function MarkdownNotebookV2({ debugOpen, onDebugOpenChange }: MarkdownNotebookV2Props): JSX.Element {+ const mountedNotebookLogic = useMountedLogic(notebookLogic)const { isEditable, notebook, markdownEditorValue, markdownEditorInteractionActive, markdownRemoteCarets } =useValues(notebookLogic)const { featureFlags } = useValues(featureFlagLogic)const markdownRegistry = useMemo(() => getMarkdownRegistryForFeatureFlags(featureFlags), [featureFlags])+ const resolveComponentRunStatus = useNotebookComponentRunStatusResolver(mountedNotebookLogic.props.shortId)const {handleMarkdownEditorChange,setMarkdownEditorInteractionActive,@@ -729,32 +736,34 @@ export function MarkdownNotebookV2({ debugOpen, onDebugOpenChange }: MarkdownNotreturn (<MarkdownNotebookRuntimeContext.Provider value={runtimeContext}>- <MarkdownNotebook- value={markdownEditorValue}- remoteValue={remoteMarkdown}- remoteVersion={notebook?.version}- mode={isEditable ? 'edit' : 'view'}- registry={markdownRegistry}- extraInsertCommands={isEditable ? buildExtraInsertCommands : undefined}- onChange={isEditable ? handleMarkdownNotebookChange : undefined}- onConflict={reportMarkdownMergeConflicts}- remoteCarets={remoteCarets}- onCaretChange={isEditable ? publishMarkdownCaret : undefined}- onAskAI={isEditable ? handleAskAI : undefined}- convertExternalDataTransferToNodes={isEditable ? convertExternalDataTransferToNodes : undefined}- isAskAIDisabled={inlineAIRequests.length > 0}- createAIConversationId={uuid}- deferRemoteValue={markdownEditorInteractionActive}- onInteractionStateChange={setMarkdownEditorInteractionActive}- className="Notebook__markdown-v2"- data-attr="notebook-markdown-v2"- autoFocus={isEditable}- showDebug={isEditable}- debugOpen={isDebugOpen}- onDebugOpenChange={handleDebugOpenChange}- focusAIPromptRequest={focusAIPromptRequest}- aiWritingNodeIndexes={aiWritingNodeIndexes}- />+ <NotebookComponentRunStatusContext.Provider value={resolveComponentRunStatus}>+ <MarkdownNotebook+ value={markdownEditorValue}+ remoteValue={remoteMarkdown}+ remoteVersion={notebook?.version}+ mode={isEditable ? 'edit' : 'view'}+ registry={markdownRegistry}+ extraInsertCommands={isEditable ? buildExtraInsertCommands : undefined}+ onChange={isEditable ? handleMarkdownNotebookChange : undefined}+ onConflict={reportMarkdownMergeConflicts}+ remoteCarets={remoteCarets}+ onCaretChange={isEditable ? publishMarkdownCaret : undefined}+ onAskAI={isEditable ? handleAskAI : undefined}+ convertExternalDataTransferToNodes={isEditable ? convertExternalDataTransferToNodes : undefined}+ isAskAIDisabled={inlineAIRequests.length > 0}+ createAIConversationId={uuid}+ deferRemoteValue={markdownEditorInteractionActive}+ onInteractionStateChange={setMarkdownEditorInteractionActive}+ className="Notebook__markdown-v2"+ data-attr="notebook-markdown-v2"+ autoFocus={isEditable}+ showDebug={isEditable}+ debugOpen={isDebugOpen}+ onDebugOpenChange={handleDebugOpenChange}+ focusAIPromptRequest={focusAIPromptRequest}+ aiWritingNodeIndexes={aiWritingNodeIndexes}+ />+ </NotebookComponentRunStatusContext.Provider>{inlineAIRequests.map((request) => (<InlineNotebookAIRunnerkey={request.conversationId}diff --git a/frontend/src/scenes/notebooks/Notebook/markdownNotebookRunStatus.test.ts b/frontend/src/scenes/notebooks/Notebook/markdownNotebookRunStatus.test.tsnew file mode 100644index 000000000000..af937bd5ba15--- /dev/null+++ b/frontend/src/scenes/notebooks/Notebook/markdownNotebookRunStatus.test.ts@@ -0,0 +1,97 @@+import type { NotebookComponentRunStatus } from 'lib/components/MarkdownNotebook'+import type { NotebookComponentBlockNode, NotebookComponentProps } from 'lib/components/MarkdownNotebook/types'++import { resolveNotebookComponentRunStatus } from './markdownNotebookRunStatus'+import type { NotebookNodeRunTerminalStatus } from './notebookNodeStalenessLogic'++describe('markdownNotebookRunStatus', () => {+ const sqlCell = (props: NotebookComponentProps = {}, tagName = 'SQLV2'): NotebookComponentBlockNode => ({+ id: 'block-fingerprint',+ type: 'component',+ tagName,+ props,+ })++ const cases: {+ label: string+ node: NotebookComponentBlockNode+ staleNodeIds?: Record<string, true>+ nodeRunStatuses?: Record<string, NotebookNodeRunTerminalStatus>+ expected: NotebookComponentRunStatus+ }[] = [+ { label: 'a block that cannot run', node: sqlCell({}, 'Query'), expected: 'idle' },+ { label: 'a cell that has never run', node: sqlCell(), expected: 'idle' },+ {+ label: 'a successful run',+ node: sqlCell({ nodeId: 'node-1' }),+ nodeRunStatuses: { 'node-1': 'done' },+ expected: 'success',+ },+ {+ label: 'a failed run',+ node: sqlCell({ nodeId: 'node-1' }),+ nodeRunStatuses: { 'node-1': 'failed' },+ expected: 'error',+ },+ {+ label: 'an interrupted run',+ node: sqlCell({ nodeId: 'node-1' }),+ nodeRunStatuses: { 'node-1': 'interrupted' },+ expected: 'error',+ },+ {+ label: 'a cell an upstream re-run outdated',+ node: sqlCell({ nodeId: 'node-1' }),+ staleNodeIds: { 'node-1': true },+ nodeRunStatuses: { 'node-1': 'done' },+ expected: 'stale',+ },+ {+ // The failure, not the staleness, is what the user has to act on.+ label: 'a stale cell whose last run failed',+ node: sqlCell({ nodeId: 'node-1' }),+ staleNodeIds: { 'node-1': true },+ nodeRunStatuses: { 'node-1': 'failed' },+ expected: 'error',+ },+ {+ // The session's run record is gone after a reload, so the cell's own record stands in.+ label: 'a reloaded cell that completed',+ node: sqlCell({ nodeId: 'node-1', result: { row_count: 1 }, runStatus: 'done' }),+ expected: 'success',+ },+ {+ // An interrupted run persists a partial result, so the result can't imply success.+ label: 'a reloaded cell that was interrupted mid-run',+ node: sqlCell({ nodeId: 'node-1', result: { stdout: 'partial' }, runStatus: 'interrupted' }),+ expected: 'error',+ },+ {+ label: 'a reloaded cell that never ran',+ node: sqlCell({ nodeId: 'node-1', result: null, runStatus: null }),+ expected: 'idle',+ },+ {+ // Cells written before the outcome was persisted, and hand-authored markdown.+ label: 'a cell carrying an unrecognized persisted outcome',+ node: sqlCell({ nodeId: 'node-1', result: { row_count: 1 }, runStatus: 'whatever' }),+ expected: 'idle',+ },+ {+ label: 'a cell that has not pinned an id yet, by its block id',+ node: sqlCell(),+ nodeRunStatuses: { 'block-fingerprint': 'done' },+ expected: 'success',+ },+ {+ label: 'a cell that pinned an id, by that id rather than its block id',+ node: sqlCell({ nodeId: 'node-1' }),+ nodeRunStatuses: { 'block-fingerprint': 'done' },+ expected: 'idle',+ },+ ]++ it.each(cases)('resolves $label', ({ node, staleNodeIds, nodeRunStatuses, expected }) => {+ expect(resolveNotebookComponentRunStatus(node, staleNodeIds ?? {}, nodeRunStatuses ?? {})).toBe(expected)+ })+})diff --git a/frontend/src/scenes/notebooks/Notebook/markdownNotebookRunStatus.ts b/frontend/src/scenes/notebooks/Notebook/markdownNotebookRunStatus.tsnew file mode 100644index 000000000000..54bac2c780bc--- /dev/null+++ b/frontend/src/scenes/notebooks/Notebook/markdownNotebookRunStatus.ts@@ -0,0 +1,55 @@+import { useValues } from 'kea'+import { useCallback } from 'react'++import type { NotebookComponentRunStatus, NotebookComponentRunStatusResolver } from 'lib/components/MarkdownNotebook'+import type { NotebookComponentBlockNode } from 'lib/components/MarkdownNotebook/types'++import { NotebookNodeType } from '../types'+import { MARKDOWN_TAG_TO_NOTEBOOK_NODE_TYPE } from './markdownNotebookRegistry'+import { NotebookNodeRunTerminalStatus, notebookNodeStalenessLogic } from './notebookNodeStalenessLogic'++// Only the revamped code cells report run state. Every other block — markdown, insights, images —+// has nothing to run, so it stays grey.+const RUNNABLE_NODE_TYPES: (NotebookNodeType | undefined)[] = [NotebookNodeType.SQLV2, NotebookNodeType.PythonV2]++const TERMINAL_STATUSES: NotebookNodeRunTerminalStatus[] = ['done', 'failed', 'interrupted']++const persistedRunStatus = (value: unknown): NotebookNodeRunTerminalStatus | undefined =>+ TERMINAL_STATUSES.find((status) => status === value)++export function resolveNotebookComponentRunStatus(+ node: NotebookComponentBlockNode,+ staleNodeIds: Record<string, true>,+ nodeRunStatuses: Record<string, NotebookNodeRunTerminalStatus>+): NotebookComponentRunStatus {+ if (!RUNNABLE_NODE_TYPES.includes(MARKDOWN_TAG_TO_NOTEBOOK_NODE_TYPE[node.tagName])) {+ return 'idle'+ }++ // A cell pins its own id the first time it runs; until then the block id is a content+ // fingerprint, which is what the rest of the notebook keys the cell by too.+ const nodeId = typeof node.props.nodeId === 'string' ? node.props.nodeId : node.id+ // The session's own record of the run wins. A cell that produced a result persists how that+ // run ended too, so a reload keeps the color — an interrupted run leaves a partial result+ // behind just like a completed one, so the result alone can't stand in for the outcome.+ const runStatus = nodeRunStatuses[nodeId] ?? persistedRunStatus(node.props.runStatus)++ // A cell that didn't finish has nothing trustworthy to be out of date, so its own outcome+ // outranks an upstream re-run.+ if (runStatus === 'failed' || runStatus === 'interrupted') {+ return 'error'+ }+ if (staleNodeIds[nodeId]) {+ return 'stale'+ }+ return runStatus === 'done' ? 'success' : 'idle'+}++export function useNotebookComponentRunStatusResolver(shortId: string): NotebookComponentRunStatusResolver {+ const { staleNodeIds, nodeRunStatuses } = useValues(notebookNodeStalenessLogic({ shortId }))++ return useCallback(+ (node: NotebookComponentBlockNode) => resolveNotebookComponentRunStatus(node, staleNodeIds, nodeRunStatuses),+ [staleNodeIds, nodeRunStatuses]+ )+}diff --git a/frontend/src/scenes/notebooks/Notebook/notebookNodeStalenessLogic.ts b/frontend/src/scenes/notebooks/Notebook/notebookNodeStalenessLogic.tsindex 8e61d6977830..98dc5ceb83a5 100644--- a/frontend/src/scenes/notebooks/Notebook/notebookNodeStalenessLogic.ts+++ b/frontend/src/scenes/notebooks/Notebook/notebookNodeStalenessLogic.ts@@ -51,6 +51,7 @@ export interface notebookNodeStalenessLogicValues {lastRunNodeId: string | nulllastRunStaleDownstreamNodeIds: string[]mountedNodeIds: Record<string, true>+ nodeRunStatuses: Record<string, NotebookNodeRunTerminalStatus>staleCount: numberstaleNodeIds: Record<string, true>}@@ -221,6 +222,14 @@ export const notebookNodeStalenessLogic = kea<notebookNodeStalenessLogicType>([setLastRun: (_, { downstreamNodeIds }) => downstreamNodeIds,},],+ // How each cell's last run ended, so the cell's gutter can show the outcome. Session-local+ // like the stale flags: a reload falls back to whether the cell has a persisted result.+ nodeRunStatuses: [+ {} as Record<string, NotebookNodeRunTerminalStatus>,+ {+ nodeRunFinished: (state, { nodeId, status }) => ({ ...state, [nodeId]: status }),+ },+ ],mountedNodeIds: [{} as Record<string, true>,{