: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): expose generated widgets in notebooks (#91535)
Marius Andrac5d60e8651c7
diff --git a/docs/internal/generated-notebook-widgets.md b/docs/internal/generated-notebook-widgets.mdnew file mode 100644index 000000000000..1d106e1aba08--- /dev/null+++ b/docs/internal/generated-notebook-widgets.md@@ -0,0 +1,52 @@+# Generated notebook widgets++Notebooks can generate interactive widgets from instructions and the notebook's SQL and Python dataframe context.++- Generation runs as a durable background job. The notebook shows its phase, elapsed time, cancellation, and terminal errors. Queued jobs stop immediately when canceled.+- Successful source, generated titles, prompts, models, dataframe contracts, and security reviews are stored as immutable versions.+- People can inspect history and source, request source changes, restore an earlier version, improve the current widget, or regenerate it.+- A new widget uses “Create an interactive visualization of the data in this notebook” when its instruction field is left empty.+- Running a widget re-runs only its connected SQL and Python data cells in dependency order. It reloads the existing preview without generating a new version.+- A fast model reviews the exact generated source before Canvas publishes it. A review failure stops publication.+- Every preview stops at a gate that shows the automated review result and links to the source. The viewer must choose to run the exact build.+- Every ready build exposes the SHA-256 of its frozen Canvas artifact manifest. “Run widget” records consent for that exact hash. A later build with different artifact contents requires a new decision. A build whose manifest is byte-identical, such as an identical rebuild, reuses the earlier consent.+- “View source” remains available before a widget runs and reads the source belonging to the selected historical version.+- Every dataframe must have a completed run before generation. Each preview load pins permission-checked pages to one run and reads at most 5,000 rows per connected dataframe without sending values to the model. Across all its dataframes, one preview reads at most 200 pages and 32 MiB of response data.+- Notebook-managed Canvas artifacts use a restricted source policy. Signed artifact URLs can render them, but the ordinary Canvas API cannot list or edit them.+- `<Widget>` is the only notebook markdown tag for generated widgets.+- Organizations must approve AI data processing before a job is queued and when its worker starts.+- Every widget endpoint requires the `notebook-generated-widgets` feature flag: creation, status, history, source, restore, cancellation, and dataframe reads. While it is disabled, existing widget nodes still render but every request they make returns 404. A generation job that is already running does not recheck the flag; it finishes model generation and the Canvas build, bounded by the 10-minute stale window and the 15-minute activity timeout. Keep the flag disabled until the generated-code data boundary and mixed-version Canvas rollout are approved.+- Production artifact delivery requires `CANVAS_ARTIFACT_ORIGIN`, a dedicated bare HTTPS origin with no path, query, fragment, or credentials, set before rollout. A production deploy with it unset boots clean, but every widget builds and then reports its preview unavailable, because no artifact URL is minted. Artifact URLs use Django's rotating `SECRET_KEY` values for signing by default. Deployments can set `CANVAS_ARTIFACT_SIGNING_KEYS` for independent rotation.++“Widget” is the umbrella term. Data visualizations are one possible widget type.++## Generated-code trust model++Generated widget source is arbitrary React and JavaScript. It is not a restricted widget schema, and PostHog does not claim to make it safe by parsing an AST, matching source text, or blocking selected syntax. JavaScript can construct equivalent behavior dynamically, so source-shape validation would create a false security boundary while breaking legitimate widgets.++The generated-code trust flow works as follows:++1. Existing static validation rejects unsupported imports, direct network APIs, dynamic imports, inline scripts, and undeclared dataframe reads.+2. A fast model reviews the validated source as untrusted input. It looks for concrete exfiltration, deception, dynamic execution, browser access, side effects, and resource-abuse risks that static checks cannot reliably identify.+3. The immutable widget version stores the highest severity, summary, findings, review model, review-instruction version, and review time. Restoring a version carries forward the review of that exact source.+4. Canvas publishes the source only after the review returns a valid result. A missing, malformed, or failed review fails the generation job closed.+5. Every reviewed build stops before execution and shows the result. The viewer can inspect the source before choosing to run that exact build.+6. A review with findings changes the gate warning and requires the viewer to run the widget anyway.+7. Legacy versions without a persisted review also stop before execution.+8. Canvas records a SHA-256 over the complete frozen artifact manifest. The hash covers artifact contents only, with no build or version id, so a build with different contents has a different hash and requires a new execution decision when gated. A build with identical contents keeps the same hash and reuses the earlier decision.++Exact-build execution choices are stored in the browser, partitioned by PostHog user ID. Generated widgets are not rendered in publicly shared notebooks. This client-side consent state is a user-experience boundary; server authorization remains the data boundary.++There is intentionally no “trust widgets by this author” option. An author is not the sole authority over a collaborative notebook node: another editor can change its instructions, regenerate it, restore a version, or otherwise replace the artifact after the original author created it. Binding trust to an immutable build is stable; binding it to a mutable ownership label is not.++Same-team scoping reduces exposure but does not eliminate realistic risk. The cases worth guarding against include:++- an editor intentionally adding a deceptive or disruptive widget for teammates;+- a compromised editor account regenerating an existing, previously benign node;+- prompt injection or a generator/supply-chain defect producing behavior nobody intended;+- a future copied or shared notebook carrying active content into a context where the viewer did not create it;+- a notebook changing membership or editorial ownership over time.++The sandboxed cross-origin iframe, Canvas CSP, signed artifact route, capability manifest, and permission-checked dataframe bridge limit blast radius. They do not turn arbitrary JavaScript into trusted code. Runtime navigation interception is defense-in-depth for preview reliability, not a security claim. The Navigation API guard applies only in Chromium. Capturing link clicks and form submissions plus disabling `window.open` blocks common paths in other browsers, but it cannot prove arbitrary programmatic self-navigation is impossible.++The automated review is advisory because a model cannot prove arbitrary or obfuscated JavaScript safe. A clean review improves the first-pass decision but does not replace the runtime controls above or provide a security guarantee.diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 68a427a32066..71cb3eb7393c 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -5389,17 +5389,17 @@ snapshots:products-mcp-analytics-routingbar--all-variants--light:hash: v1.k794b7964.7f57dacddb48fbad29a8614127d42d54425501b1f7755423d84316e1e937720e.thYPF2z3eMW5QvSe5SnvYtn35l6UCvUtsyx9EBLeqxkproducts-notebooks-notebook-widget-trust-controls--gate--dark:- hash: v1.k794b7964.a51e3886b9b210b87ad0165be8e11217f7e6690c4c6fb3f055d91eb743297986.rTe9aGKWZkly97EDDu4Ml4H1iZL-bHzlkuJ4hhxLZGI+ hash: v1.k794b7964.97a5e7b5f92071f677d09773a3dea88ead3c9a71e85dbd6f6de8875ffc7a3036.9u2VOZ-O_aSU002VK8iAydGcjIYBXzRIacAelaDLJ6Yproducts-notebooks-notebook-widget-trust-controls--gate--light:- hash: v1.k794b7964.dba4c5816812fb18955fac3ef7e21d4e2f09ea489f3fd98610e7e2c08cd7b720.v_U6astxnykhOLozpJLNTYhnKqZ2UKlo63c2XV2dIg0+ hash: v1.k794b7964.db2c004b22e5c8c098101130cf153cab0366a18ec4218702f64f0e5fbaa52fd9.cNi_DSrdmSUZpn9RiLWqAXVJotr231Hl1B0Fu80Mnjgproducts-notebooks-notebook-widget-trust-controls--missing-build-hash--dark:- hash: v1.k794b7964.710a8f35d2bb0ff64962fa14422f9b19afedf525ecf888fa1a31d109866edc65.xPoRXj8l2nIWGfk_DEjMPUR3kIAoBAxMcW9uBlGeyGY+ hash: v1.k794b7964.260fe7a0225889c379701f4469916084332cae77401477686bd5ce52cb290b81.peQXbUDXlvGWY-ObtWEe5ZtUwdUGLsL4urRaOb2eLL8products-notebooks-notebook-widget-trust-controls--missing-build-hash--light:- hash: v1.k794b7964.0e2cc5104d4beb9dc308c92f194195156bd5fb48f6d8a1a278cce43e1313af67.eFnIkptK__hsvjhmXeAKmQxJBT1C3NZ6XXlRPLjHRA4+ hash: v1.k794b7964.818bb7c7bbdab7fdefdcaddcb9cd3c93df2dbf819d38209727d48c4fa85165a2.4Pfm4AA9vA5agcGNKh3LGwP6qAR5UyK0Ez6C2ltB7WUproducts-notebooks-notebook-widget-trust-controls--toolbar--dark:- hash: v1.k794b7964.a7394acbef2f45ccce1f0a9ad5d4dc09fa14cb337ffdc0b19642aef2728c65a3.VxLUiUKH_TDO-qiJRfaJ0r-HgJ7M2MAGbUDTd1kR32k+ hash: v1.k794b7964.7152b3d7c5901a84315c4be4bba827bbacc795e169bef6293c557ffa6f6aac3e.dbzTA4TpkRhVxzeO6ZI4yMDDYm5hPp4vlMN2snZuZ_Uproducts-notebooks-notebook-widget-trust-controls--toolbar--light:- hash: v1.k794b7964.54adb15f34d6024fc6e441a77a81146a3eb7a31dfb689071b012df26ab133ab4.PjdDZ6fn1152SwEb7DfcTzJsZwNDQ25XzVL3EgjOiio+ hash: v1.k794b7964.69bffab30393759acd64d77faebacd006a7f898f70bd01fd78bb22de881db16a.-TW2Tbin6bPS5VNWYI86bOekMUtNwEPqmjOHWW0GqvYproducts-posthog-ai-composer--default--dark:hash: v1.k794b7964.4ccf5eb666de2b3315dc3f142ded80b445748d58ce8ae2d7d154272d7b194b3b.E61uR16UwC5qC1XkQquxMh1z3bonN6IYLdYDyzcorTAproducts-posthog-ai-composer--default--light:diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsxindex c44ab599f845..810bf61cd2f7 100644--- a/frontend/src/lib/constants.tsx+++ b/frontend/src/lib/constants.tsx@@ -415,6 +415,7 @@ export const FEATURE_FLAGS = {METRICS_ERROR_OVERLAYS: 'metrics-error-overlays', // owner: #team-apm — gates the error-spike overlay PoC on metrics chartsNEW_TAB_PROJECT_EXPLORER: 'new-tab-project-explorer', // owner: #team-platform-uxNEW_TEAM_CORE_EVENTS: 'new-team-core-events', // owner: @jabahamondes #team-web-analytics+ NOTEBOOK_GENERATED_WIDGETS: 'notebook-generated-widgets', // owner: #team-data-toolsNOTEBOOK_PYTHON: 'notebook-python', // owner: #team-data-toolsNOTEBOOK_SHARING: 'notebook-sharing', // owner: @reecejones #team-platform-featuresONBOARDING_AI_REPORTS: 'onboarding-role-notifications', // owner: @joethreepwood #team-growth multivariate=control,test — offers a role-tailored weekly AI report step at the end of onboarding; code additionally gates on AI subscriptions being available, so keep the flag at 100% rollout (key predates the AI-reports naming; it's bound to the live experiment)diff --git a/frontend/src/scenes/notebooks/Nodes/NodeWrapper.tsx b/frontend/src/scenes/notebooks/Nodes/NodeWrapper.tsxindex 16852bd4abde..8703470e60f8 100644--- a/frontend/src/scenes/notebooks/Nodes/NodeWrapper.tsx+++ b/frontend/src/scenes/notebooks/Nodes/NodeWrapper.tsx@@ -54,6 +54,7 @@ function NodeWrapper<T extends CustomNotebookNodeAttributes>(props: NodeWrapperPtitlePlaceholder,defaultView,views,+ unmountWhenOutOfView = false,} = propsconst mountedNotebookLogic = useMountedLogic(notebookLogic)@@ -97,7 +98,7 @@ function NodeWrapper<T extends CustomNotebookNodeAttributes>(props: NodeWrapperPrunHogqlSqlNodeWithMode,} = useActions(nodeLogic)- const { ref: inViewRef, inView } = useInView({ triggerOnce: true })+ const { ref: inViewRef, inView } = useInView({ triggerOnce: !unmountWhenOutOfView })const setRefs = useCallback((node: HTMLDivElement | null) => {@@ -318,7 +319,10 @@ function NodeWrapper<T extends CustomNotebookNodeAttributes>(props: NodeWrapperP<LemonSkeleton className="w-20" /></div>{/* eslint-disable-next-line react/forbid-dom-props */}- <div className="flex items-center p-2" style={{ height: heightEstimate }}>+ <div+ className="flex items-center p-2"+ style={isResizeable ? { height, minHeight } : { height: heightEstimate }}+ ><LemonSkeleton className="w-full h-full" /></div></>diff --git a/frontend/src/scenes/notebooks/Nodes/notebookNodeContent.ts b/frontend/src/scenes/notebooks/Nodes/notebookNodeContent.tsindex 89fdcfb2bab8..5068e4722fdb 100644--- a/frontend/src/scenes/notebooks/Nodes/notebookNodeContent.ts+++ b/frontend/src/scenes/notebooks/Nodes/notebookNodeContent.ts@@ -852,9 +852,8 @@ export const buildNotebookDependencyGraph = (content?: JSONContent | null): Noteif (node.type === NotebookNodeType.MarkdownNotebook) {// Markdown notebooks (the only V2 surface) store cells as component tags, so both- // V2 cell types must be expanded or the graph misses every markdown-held cell.- expandMarkdownNotebookSqlV2Nodes(node).forEach(walk)- expandMarkdownNotebookNodesOfType(node, NotebookNodeType.PythonV2).forEach(walk)+ // V2 cell types must be expanded in one pass to preserve dependency order.+ expandMarkdownNotebookNodesOfTypes(node, [NotebookNodeType.SQLV2, NotebookNodeType.PythonV2]).forEach(walk)}if (Array.isArray(node.content)) {diff --git a/frontend/src/scenes/notebooks/Notebook/MarkdownNotebookV2Renderer.tsx b/frontend/src/scenes/notebooks/Notebook/MarkdownNotebookV2Renderer.tsxindex d402cf1a45fb..df6fdaabf729 100644--- a/frontend/src/scenes/notebooks/Notebook/MarkdownNotebookV2Renderer.tsx+++ b/frontend/src/scenes/notebooks/Notebook/MarkdownNotebookV2Renderer.tsx@@ -108,7 +108,7 @@ export function MarkdownNotebookV2({ debugOpen, onDebugOpenChange }: MarkdownNotsetMarkdownAIPresenceActive,} = useActions(notebookLogic)const { setShowKernelInfo } = useActions(notebookSettingsLogic)- const remoteMarkdown = getMarkdownNotebookMarkdown(notebook?.content)+ const remoteMarkdown = useMemo(() => getMarkdownNotebookMarkdown(notebook?.content), [notebook?.content])const [inlineAIRequests, setInlineAIRequests] = useState<InlineNotebookAIRequest[]>([])const [aiCaretPosition, setAICaretPosition] = useState<MarkdownNotebookCaretPosition | null>(null)const [aiCaretFading, setAICaretFading] = useState(false)diff --git a/frontend/src/scenes/notebooks/Notebook/markdownNotebookRegistry.test.tsx b/frontend/src/scenes/notebooks/Notebook/markdownNotebookRegistry.test.tsxindex c8366575bc0b..3b221098ed6a 100644--- a/frontend/src/scenes/notebooks/Notebook/markdownNotebookRegistry.test.tsx+++ b/frontend/src/scenes/notebooks/Notebook/markdownNotebookRegistry.test.tsx@@ -85,19 +85,33 @@ describe('markdownNotebookRegistry', () => {expect(flagOff.components.PythonV2.insertCommand).toBeUndefined()})- // An inserted code cell holds no code and no result, so a closed editor panel leaves the- // user an empty box. Resolving through getInsertedComponentPanelVisibility rather than- // reading the prop keeps this honest if the panel prop is renamed again.+ it('gates widget insertion and registers only the Widget component', () => {+ expect(getInsertCommandsByLabel({ [FEATURE_FLAGS.NOTEBOOK_GENERATED_WIDGETS]: true }, 'Widget')).toEqual([+ { key: 'component-Widget', category: 'Common' },+ ])+ expect(getInsertCommandsByLabel({}, 'Widget')).toEqual([])+ for (const legacyTag of ['GeneratedWidget', 'GenUI']) {+ expect(NOTEBOOK_MARKDOWN_REGISTRY.components).not.toHaveProperty(legacyTag)+ }+ expect(NOTEBOOK_MARKDOWN_REGISTRY.components.Widget.ToolbarComponent).toBeTruthy()+ })++ // The panel visibility resolver is the notebook shell's public behavior. Testing through it+ // keeps new programmable blocks usable even if the persisted panel prop changes.it.each([['SQL', 'component-SQLV2'],['Python', 'component-PythonV2'],- ])('inserts a %s cell with its code editor open', (_label, commandKey) => {+ ['Widget', 'component-Widget'],+ ])('inserts a %s block with its input panel open', (_label, commandKey) => {const insertedNodes: NotebookComponentBlockNode[] = []const noop = (): void => {}const commands = buildInsertCommands(mergeMarkdownNotebookRegistries(getMarkdownNotebookDefaultRegistry(),- getMarkdownRegistryForFeatureFlags({ [FEATURE_FLAGS.REVAMPED_PY_NOTEBOOKS]: true })+ getMarkdownRegistryForFeatureFlags({+ [FEATURE_FLAGS.REVAMPED_PY_NOTEBOOKS]: true,+ [FEATURE_FLAGS.NOTEBOOK_GENERATED_WIDGETS]: true,+ })),(_nodeId, node) => insertedNodes.push(node),noop,@@ -340,6 +354,26 @@ describe('markdownNotebookRegistry', () => {expect(fields[1].textContent).toContain('View')})+ it('hides the backing canvas ID from generated widget settings', () => {+ const { container } = render(+ <RealNotebookNodeIdentityAndViewEdit+ node={{+ id: 'generated-widget-node',+ type: 'component',+ tagName: 'Widget',+ props: { id: 'canvas-id' },+ }}+ mode="edit"+ updateProps={jest.fn()}+ deleteNode={jest.fn()}+ notebookNodeType={NotebookNodeType.GeneratedWidget}+ options={KNOWN_NODES[NotebookNodeType.GeneratedWidget]}+ />+ )++ expect(container.childElementCount).toBe(0)+ })+it('selects a referenced object from the same picker used by notebook insertion', () => {const updateProps = jest.fn()const { container } = render(diff --git a/frontend/src/scenes/notebooks/Notebook/markdownNotebookRegistry.tsx b/frontend/src/scenes/notebooks/Notebook/markdownNotebookRegistry.tsxindex 5ef201261803..d9c526ca1caf 100644--- a/frontend/src/scenes/notebooks/Notebook/markdownNotebookRegistry.tsx+++ b/frontend/src/scenes/notebooks/Notebook/markdownNotebookRegistry.tsx@@ -46,6 +46,7 @@ import {useMemo,useRef,} from 'react'+import { useInView } from 'react-intersection-observer'import { IconComment, IconImage } from '@posthog/icons'import { LemonButton, LemonInput, LemonSelect, LemonTextArea, lemonToast } from '@posthog/lemon-ui'@@ -70,11 +71,15 @@ import { getSerializableProps, isNotebookPropValue } from 'lib/components/Markdoimport { FEATURE_FLAGS } from 'lib/constants'import { useUploadFiles } from 'lib/hooks/useUploadFiles'import { LemonFileInput } from 'lib/lemon-ui/LemonFileInput'+import { LemonSkeleton } from 'lib/lemon-ui/LemonSkeleton'import { Spinner } from 'lib/lemon-ui/Spinner'import { type FeatureFlagsSet } from 'lib/logic/featureFlagLogic'import { uuid } from 'lib/utils/dom'import { preflightLogic } from 'scenes/PreflightCheck/preflightLogic'+import 'products/notebooks/frontend/NotebookNodeGeneratedWidget/NotebookNodeGeneratedWidget'+import { NotebookGeneratedWidgetRunButton } from 'products/notebooks/frontend/NotebookNodeGeneratedWidget/NotebookGeneratedWidgetRunButton'+import { NODE_ICONS } from '../nodeIcons'import { NotebookCodeCellRunButton } from '../Nodes/components/NotebookCodeCellRunButton'import { NotebookNodeContext } from '../Nodes/NotebookNodeContext'@@ -170,6 +175,7 @@ export const MARKDOWN_TAG_TO_NOTEBOOK_NODE_TYPE: Partial<Record<string, NotebookDuckSQL: NotebookNodeType.DuckSQL,HogQLSQL: NotebookNodeType.HogQLSQL,SQLV2: NotebookNodeType.SQLV2,+ Widget: NotebookNodeType.GeneratedWidget,Recording: NotebookNodeType.Recording,RecordingPlaylist: NotebookNodeType.RecordingPlaylist,FeatureFlag: NotebookNodeType.FeatureFlag,@@ -228,10 +234,9 @@ function getMarkdownNodeOptions(tagName: string): CreatePostHogWidgetNodeOptionsreturn nodeType ? KNOWN_NODES[nodeType] : null}-// A code cell's `filters` panel is its code editor, and the shell leaves that panel closed-// unless the node carries `showFilters`. A cell the user just inserted holds no code and no-// result, so without this it renders as an empty box with nothing to type into.-const CODE_CELL_EDITOR_OPEN_PROPS: NotebookComponentProps = { showFilters: true }+// The notebook shell closes input panels unless the node carries `showFilters`. New programmable+// blocks need immediate input, so opening the panel avoids an empty block with no visible next step.+const INPUT_PANEL_OPEN_PROPS: NotebookComponentProps = { showFilters: true }export const MARKDOWN_NODE_DEFINITIONS: {tagName: string@@ -261,7 +266,7 @@ export const MARKDOWN_NODE_DEFINITIONS: {aliases: ['python', 'py'],defaultProps: () => ({...getDefaultPropsForNodeType(NotebookNodeType.PythonV2),- ...CODE_CELL_EDITOR_OPEN_PROPS,+ ...INPUT_PANEL_OPEN_PROPS,nodeId: uuid(),}),},@@ -288,7 +293,22 @@ export const MARKDOWN_NODE_DEFINITIONS: {// writes runId/result) would orphan the cell's run history and cross-cell refs.defaultProps: () => ({...getDefaultPropsForNodeType(NotebookNodeType.SQLV2),- ...CODE_CELL_EDITOR_OPEN_PROPS,+ ...INPUT_PANEL_OPEN_PROPS,+ nodeId: uuid(),+ }),+ },+ },+ {+ tagName: 'Widget',+ category: 'Code',+ label: 'Widget',+ ToolbarComponent: NotebookGeneratedWidgetRunButton,+ insertCommand: {+ category: COMMON_INSERT_COMMAND_CATEGORY,+ aliases: ['visualization', 'widget', '3d'],+ defaultProps: () => ({+ ...getDefaultPropsForNodeType(NotebookNodeType.GeneratedWidget),+ ...INPUT_PANEL_OPEN_PROPS,nodeId: uuid(),}),},@@ -384,6 +404,9 @@ export function getMarkdownRegistryForFeatureFlags(featureFlags: FeatureFlagsSetif (!featureFlags[FEATURE_FLAGS.REVAMPED_PY_NOTEBOOKS]) {hiddenTags.push('SQLV2', 'PythonV2')}+ if (!featureFlags[FEATURE_FLAGS.NOTEBOOK_GENERATED_WIDGETS]) {+ hiddenTags.push('Widget')+ }if (hiddenTags.length === 0) {return NOTEBOOK_MARKDOWN_REGISTRY@@ -778,6 +801,17 @@ export function MountedRealNotebookNodeComponent({}): JSX.Element {const mountedNotebookLogic = useMountedLogic(notebookLogic)const contentRef = useRef<HTMLDivElement | null>(null)+ const { ref: inViewRef, inView } = useInView({+ triggerOnce: !options.unmountWhenOutOfView,+ fallbackInView: true,+ })+ const setContentRefs = useCallback(+ (element: HTMLDivElement | null): void => {+ contentRef.current = element+ inViewRef(element)+ },+ [inViewRef]+ )const attributes = useMemo(() => getNodeAttributes(node.props, node.id, options, notebookNodeType, forceEditing),[forceEditing, node.id, node.props, notebookNodeType, options]@@ -932,7 +966,7 @@ export function MountedRealNotebookNodeComponent({) : null}{showContent ? (<div- ref={contentRef}+ ref={setContentRefs}className={clsx('MarkdownNotebook__real-node-content',isResizeable && 'MarkdownNotebook__real-node-content--resizeable'@@ -940,7 +974,11 @@ export function MountedRealNotebookNodeComponent({style={contentStyle}onMouseDown={handleResizeStart}>- <Component attributes={attributes} updateAttributes={updateAttributes} />+ {!options.unmountWhenOutOfView || inView ? (+ <Component attributes={attributes} updateAttributes={updateAttributes} />+ ) : (+ <LemonSkeleton className="h-full w-full" />+ )}{isResizeable ? (<divclassName="MarkdownNotebook__real-node-resize-handle"diff --git a/frontend/src/scenes/notebooks/Notebook/markdownNotebookV2.test.ts b/frontend/src/scenes/notebooks/Notebook/markdownNotebookV2.test.tsindex 46a0fc52a7c8..cdb5733eae39 100644--- a/frontend/src/scenes/notebooks/Notebook/markdownNotebookV2.test.ts+++ b/frontend/src/scenes/notebooks/Notebook/markdownNotebookV2.test.ts@@ -259,6 +259,7 @@ Dashboard 123[NotebookNodeType.Action, 'Action'],[NotebookNodeType.Workflow, 'Workflow'],[NotebookNodeType.ErrorTrackingIssue, 'ErrorTrackingIssue'],+ [NotebookNodeType.GeneratedWidget, 'Widget'],])('converts the %s widget node to its markdown component', (nodeType, tagName) => {expect(convertNotebookContentToMarkdown({diff --git a/frontend/src/scenes/notebooks/Notebook/markdownNotebookV2.ts b/frontend/src/scenes/notebooks/Notebook/markdownNotebookV2.tsindex 0f4cb3e193b9..e4208c12d414 100644--- a/frontend/src/scenes/notebooks/Notebook/markdownNotebookV2.ts+++ b/frontend/src/scenes/notebooks/Notebook/markdownNotebookV2.ts@@ -55,6 +55,7 @@ export const NOTEBOOK_NODE_TYPE_TO_MARKDOWN_TAG: Partial<Record<NotebookNodeType[NotebookNodeType.DuckSQL]: 'DuckSQL',[NotebookNodeType.HogQLSQL]: 'HogQLSQL',[NotebookNodeType.SQLV2]: 'SQLV2',+ [NotebookNodeType.GeneratedWidget]: 'Widget',[NotebookNodeType.Recording]: 'Recording',[NotebookNodeType.RecordingPlaylist]: 'RecordingPlaylist',[NotebookNodeType.FeatureFlag]: 'FeatureFlag',diff --git a/frontend/src/scenes/notebooks/Notebook/notebookNodeStalenessLogic.test.ts b/frontend/src/scenes/notebooks/Notebook/notebookNodeStalenessLogic.test.tsindex 175c8ec85642..762636158f38 100644--- a/frontend/src/scenes/notebooks/Notebook/notebookNodeStalenessLogic.test.ts+++ b/frontend/src/scenes/notebooks/Notebook/notebookNodeStalenessLogic.test.ts@@ -7,6 +7,7 @@ import { initKeaTests } from '~/test/init'import { notebookNodeSQLV2Logic } from '../Nodes/notebookNodeSQLV2Logic'import { NotebookNodeType } from '../types'+import { buildMarkdownNotebookContent, serializeMarkdownNotebookComponent } from './markdownNotebookV2'import { notebookNodeStalenessLogic } from './notebookNodeStalenessLogic'describe('notebookNodeStalenessLogic', () => {@@ -123,6 +124,82 @@ describe('notebookNodeStalenessLogic', () => {expect(stalenessLogic.values.chainQueue).toEqual([])})+ it('runs only the requested widget data chain in dependency order', async () => {+ mountNode('a')+ mountNode('b')+ mountNode('c')+ mountNode('x')++ stalenessLogic.actions.runWidgetDataChain(content, ['a', 'b'])+ await expectLogic(stalenessLogic).toFinishAllListeners()++ expect(runSpy.mock.calls.map((call) => call[1].node_id)).toEqual(['a', 'b'])+ expect(stalenessLogic.values.staleNodeIds).toEqual({ c: 'upstream' })+ expect(stalenessLogic.values.widgetDataChainNodeIds).toEqual([])+ })++ it('preserves mixed SQL and Python order for widget data in markdown notebooks', async () => {+ const markdown = [+ serializeMarkdownNotebookComponent('SQLV2', {+ nodeId: 'a',+ returnVariable: 'sql_df',+ code: 'select 1',+ }),+ serializeMarkdownNotebookComponent('PythonV2', {+ nodeId: 'b',+ returnVariable: 'new_events',+ code: 'new_events = sql_df.head()',+ }),+ serializeMarkdownNotebookComponent('SQLV2', {+ nodeId: 'c',+ returnVariable: 'joined',+ code: 'select * from new_events',+ }),+ ].join('\n\n')+ const markdownContent = buildMarkdownNotebookContent(markdown)+ mountNode('a')+ mountNode('b')+ mountNode('c')++ stalenessLogic.actions.runWidgetDataChain(markdownContent, ['a', 'b', 'c'])+ await expectLogic(stalenessLogic).toFinishAllListeners()++ expect(runSpy.mock.calls.map((call) => call[1].node_id)).toEqual(['a', 'b', 'c'])+ })++ it('does not run a partial widget data chain when a requested cell is unmounted', async () => {+ mountNode('a')++ stalenessLogic.actions.runWidgetDataChain(content, ['a', 'b'])+ await expectLogic(stalenessLogic).toFinishAllListeners()++ expect(runSpy).not.toHaveBeenCalled()+ expect(stalenessLogic.values.chainQueue).toEqual([])+ expect(stalenessLogic.values.widgetDataChainNodeIds).toEqual([])+ })++ it('does not report success when a requested widget cell disappears during the chain', async () => {+ let finishFirstRun: (value: { status: 'done'; result: null; error: null }) => void = () => undefined+ resultSpy.mockImplementationOnce(+ () =>+ new Promise((resolve) => {+ finishFirstRun = resolve+ })+ )+ mountNode('a')+ const secondNode = mountNode('b')++ stalenessLogic.actions.runWidgetDataChain(content, ['a', 'b'])+ await expectLogic(stalenessLogic).toDispatchActions(['dispatchChainRun'])+ secondNode.unmount()+ finishFirstRun({ status: 'done', result: null, error: null })+ await expectLogic(stalenessLogic).toFinishAllListeners()++ expect(runSpy.mock.calls.map((call) => call[1].node_id)).toEqual(['a'])+ expect(stalenessLogic.values.chainQueue).toEqual([])+ expect(stalenessLogic.values.widgetDataChainNodeIds).toEqual([])+ })+it('a chain run picks up cells its own completion marked stale', async () => {// The queue must be rebuilt as the chain advances: a's run marks b and c stale, and// a snapshot taken at chain start would finish "successfully" while they stay flagged.diff --git a/frontend/src/scenes/notebooks/Notebook/notebookNodeStalenessLogic.ts b/frontend/src/scenes/notebooks/Notebook/notebookNodeStalenessLogic.tsindex 20c4e5ae98b2..ce376373bc29 100644--- a/frontend/src/scenes/notebooks/Notebook/notebookNodeStalenessLogic.ts+++ b/frontend/src/scenes/notebooks/Notebook/notebookNodeStalenessLogic.ts@@ -80,6 +80,8 @@ export interface notebookNodeStalenessLogicValues {nodeRunStatuses: Record<string, NotebookNodeRunTerminalStatus>staleCount: numberstaleNodeIds: Record<string, NotebookStaleReason>+ widgetDataChainCompletedNodeIds: string[]+ widgetDataChainNodeIds: string[]}// Generated by kea-typegen. Update if you're an agent, ignore if you're human.@@ -119,6 +121,13 @@ export interface notebookNodeStalenessLogicActions {content: JSONContent | nullrootNodeId: string | null}+ runWidgetDataChain: (+ content: JSONContent | null,+ nodeIds: string[]+ ) => {+ content: JSONContent | null+ nodeIds: string[]+ }setChainQueue: (nodeIds: string[]) => {nodeIds: string[]}@@ -132,6 +141,12 @@ export interface notebookNodeStalenessLogicActions {downstreamNodeIds: string[]nodeId: string}+ setWidgetDataChainCompletedNodeIds: (nodeIds: string[]) => {+ nodeIds: string[]+ }+ setWidgetDataChainNodeIds: (nodeIds: string[]) => {+ nodeIds: string[]+ }unregisterChainNode: (nodeId: string) => {nodeId: string}@@ -142,6 +157,9 @@ export interface notebookNodeStalenessLogicActions {content: JSONContent | nullvariableNames: string[]}+ widgetDataChainFinished: (nodeIds: string[]) => {+ nodeIds: string[]+ }}// Generated by kea-typegen. Update if you're an agent, ignore if you're human.@@ -193,12 +211,16 @@ export const notebookNodeStalenessLogic = kea<notebookNodeStalenessLogicType>([// "run downstream cells" button on the cell that just ran); without one it runs// every stale cell in the notebook.runStaleChain: (content: JSONContent | null, rootNodeId: string | null = null) => ({ content, rootNodeId }),+ runWidgetDataChain: (content: JSONContent | null, nodeIds: string[]) => ({ content, nodeIds }),// Consumed by the matching notebookNodeSQLV2Logic, which builds refs and runs itself.dispatchChainRun: (nodeId: string) => ({ nodeId }),setChainQueue: (nodeIds: string[]) => ({ nodeIds }),setChainRoot: (nodeId: string | null) => ({ nodeId }),setLastRun: (nodeId: string, downstreamNodeIds: string[]) => ({ nodeId, downstreamNodeIds }),abortChain: (reason: string | null) => ({ reason }),+ setWidgetDataChainNodeIds: (nodeIds: string[]) => ({ nodeIds }),+ setWidgetDataChainCompletedNodeIds: (nodeIds: string[]) => ({ nodeIds }),+ widgetDataChainFinished: (nodeIds: string[]) => ({ nodeIds }),// Called by every V2 node logic on mount/unmount so the chain only ever dispatches// to a cell whose logic is mounted and listening.registerChainNode: (nodeId: string) => ({ nodeId }),@@ -237,6 +259,7 @@ export const notebookNodeStalenessLogic = kea<notebookNodeStalenessLogicType>([{setChainQueue: (_, { nodeIds }) => nodeIds,abortChain: () => [],+ widgetDataChainFinished: () => [],},],// The cell whose "run downstream cells" started the active chain; scopes the queue@@ -246,6 +269,7 @@ export const notebookNodeStalenessLogic = kea<notebookNodeStalenessLogicType>([{setChainRoot: (_, { nodeId }) => nodeId,abortChain: () => null,+ widgetDataChainFinished: () => null,},],// The last cell whose run landed, and the downstream set that run marked stale.@@ -284,6 +308,23 @@ export const notebookNodeStalenessLogic = kea<notebookNodeStalenessLogicType>([},},],+ widgetDataChainNodeIds: [+ [] as string[],+ {+ setWidgetDataChainNodeIds: (_, { nodeIds }) => nodeIds,+ abortChain: () => [],+ widgetDataChainFinished: () => [],+ },+ ],+ widgetDataChainCompletedNodeIds: [+ [] as string[],+ {+ setWidgetDataChainCompletedNodeIds: (_, { nodeIds }) => nodeIds,+ setWidgetDataChainNodeIds: () => [],+ abortChain: () => [],+ widgetDataChainFinished: () => [],+ },+ ],}),selectors({staleCount: [@@ -315,6 +356,12 @@ export const notebookNodeStalenessLogic = kea<notebookNodeStalenessLogicType>([actions.abortChain(nodeId)return}+ const completedWidgetNodeIds = values.widgetDataChainNodeIds.length+ ? Array.from(new Set([...values.widgetDataChainCompletedNodeIds, nodeId]))+ : []+ if (completedWidgetNodeIds.length) {+ actions.setWidgetDataChainCompletedNodeIds(completedWidgetNodeIds)+ }// Rebuild the queue from the live stale set instead of shifting the snapshot:// cells marked stale while the chain ran (including by this very run) join in,// and cells deleted or unmounted while queued drop out rather than receiving a@@ -325,10 +372,27 @@ export const notebookNodeStalenessLogic = kea<notebookNodeStalenessLogicType>([if (graph && values.chainRootNodeId) {const scope = collectDependencyNodeIds(graph, values.chainRootNodeId, 'downstream')queue = queue.filter((queuedNodeId) => scope.has(queuedNodeId))+ } else if (values.widgetDataChainNodeIds.length) {+ const scope = new Set(values.widgetDataChainNodeIds)+ queue = queue.filter((queuedNodeId) => scope.has(queuedNodeId))}actions.setChainQueue(queue)if (queue.length) {actions.dispatchChainRun(queue[0])+ } else if (values.widgetDataChainNodeIds.length) {+ const availableNodeIds = new Set(graph?.nodes.map((node) => node.nodeId) ?? [])+ const completedNodeIds = new Set(completedWidgetNodeIds)+ const missingNodeId = values.widgetDataChainNodeIds.find(+ (widgetNodeId) =>+ !availableNodeIds.has(widgetNodeId) ||+ !values.mountedNodeIds[widgetNodeId] ||+ !completedNodeIds.has(widgetNodeId)+ )+ if (missingNodeId) {+ actions.abortChain(missingNodeId)+ } else {+ actions.widgetDataChainFinished(values.widgetDataChainNodeIds)+ }} else {actions.setChainRoot(null)lemonToast.success('Stale cells re-run.')@@ -352,10 +416,44 @@ export const notebookNodeStalenessLogic = kea<notebookNodeStalenessLogicType>([lemonToast.info('No stale cells to run.')return}+ actions.setWidgetDataChainNodeIds([])actions.setChainRoot(rootNodeId)actions.setChainQueue(queue)actions.dispatchChainRun(queue[0])},+ runWidgetDataChain: ({ content, nodeIds }) => {+ if (values.isChainRunning) {+ lemonToast.info('Notebook data cells are already being re-run.')+ return+ }+ if (!content || !nodeIds.length) {+ return+ }+ const graph = buildNotebookDependencyGraph(content)+ const requestedNodeIds = new Set(nodeIds)+ const requestedNodes = graph.nodes.filter(+ (node) => V2_NODE_TYPES.includes(node.nodeType) && requestedNodeIds.has(node.nodeId)+ )+ const allRequestedNodesAreMounted =+ requestedNodes.length === requestedNodeIds.size &&+ requestedNodes.every((node) => values.mountedNodeIds[node.nodeId])+ if (!allRequestedNodesAreMounted) {+ lemonToast.info(+ 'Some connected data cells are not available. Scroll through the notebook and try again.'+ )+ actions.abortChain(null)+ return+ }+ const queue = requestedNodes.map((node) => node.nodeId)+ actions.markStaleNodeIds(queue)+ actions.setChainRoot(null)+ actions.setWidgetDataChainNodeIds(queue)+ actions.setChainQueue(queue)+ actions.dispatchChainRun(queue[0])+ },+ widgetDataChainFinished: () => {+ lemonToast.success('Widget data refreshed.')+ },variablesChanged: ({ variableNames, content }) => {if (!variableNames.length || !content) {returndiff --git a/frontend/src/scenes/notebooks/NotebooksTable/ContainsTypeFilter.tsx b/frontend/src/scenes/notebooks/NotebooksTable/ContainsTypeFilter.tsxindex d1ebef58cfc1..302bdaa40f25 100644--- a/frontend/src/scenes/notebooks/NotebooksTable/ContainsTypeFilter.tsx+++ b/frontend/src/scenes/notebooks/NotebooksTable/ContainsTypeFilter.tsx@@ -16,6 +16,7 @@ export const fromNodeTypeToLabel: Omit<| NotebookNodeType.Embed| NotebookNodeType.Latex| NotebookNodeType.MarkdownNotebook+ | NotebookNodeType.GeneratedWidget> = {[NotebookNodeType.FeatureFlag]: 'Feature flags',[NotebookNodeType.FeatureFlagCodeExample]: 'Feature flag Code Examples',diff --git a/frontend/src/scenes/notebooks/nodeIcons.tsx b/frontend/src/scenes/notebooks/nodeIcons.tsxindex 1434ec6fb4df..e227ad003f94 100644--- a/frontend/src/scenes/notebooks/nodeIcons.tsx+++ b/frontend/src/scenes/notebooks/nodeIcons.tsx@@ -38,6 +38,7 @@ export const NODE_ICONS: Partial<Record<NotebookNodeType, JSX.Element>> = {[NotebookNodeType.SQLV2]: <IconBracketsChart />,[NotebookNodeType.Python]: <IconPython />,[NotebookNodeType.PythonV2]: <IconPython />,+ [NotebookNodeType.GeneratedWidget]: <IconAI />,[NotebookNodeType.Latex]: <IconSquareRoot />,[NotebookNodeType.Recording]: <IconRewindPlay />,[NotebookNodeType.RecordingPlaylist]: <IconRewindPlay />,diff --git a/frontend/src/scenes/notebooks/types.ts b/frontend/src/scenes/notebooks/types.tsindex 0a60b369065c..6ace5e17d720 100644--- a/frontend/src/scenes/notebooks/types.ts+++ b/frontend/src/scenes/notebooks/types.ts@@ -57,6 +57,7 @@ export enum NotebookNodeType {DuckSQL = 'ph-duck-sql',HogQLSQL = 'ph-hogql-sql',SQLV2 = 'ph-sql-v2',+ GeneratedWidget = 'ph-generated-widget',Recording = 'ph-recording',RecordingPlaylist = 'ph-recording-playlist',FeatureFlag = 'ph-feature-flag',@@ -149,6 +150,7 @@ export type NodeWrapperProps<T extends CustomNotebookNodeAttributes> = Omit<NoteautoHideMetadata?: boolean/** Expand the node if the component is clicked */expandOnClick?: boolean+ unmountWhenOutOfView?: booleansettingsPlacement?: NotebookNodeSettingsPlacementdefaultView?: PostHogWidgetDefaultViewviews?: PostHogWidgetViews<T>diff --git a/playwright/e2e/product-analytics/insights/trends.spec.ts b/playwright/e2e/product-analytics/insights/trends.spec.tsindex 65423398a42e..9317aed80ee7 100644--- a/playwright/e2e/product-analytics/insights/trends.spec.ts+++ b/playwright/e2e/product-analytics/insights/trends.spec.ts@@ -297,9 +297,8 @@ test.describe('Trends insights', () => {await test.step('add breakdown and verify tooltip shows Chrome and Firefox', async () => {await insight.trends.addBreakdown('Browser')- await insight.trends.waitForChart()- await insight.trends.selectEvent(0, customEventsWithBreakdown.eventName)- await insight.trends.waitForChart()+ await insight.trends.expectRowTotal('Chrome', pageviews.expected.chromeTotal)+ await insight.trends.expectRowTotal('Firefox', pageviews.expected.firefoxTotal)await insight.trends.hoverChartAt(0.5, 0.5)const multiText = await insight.trends.tooltip.textContent()expect(multiText).toContain('Chrome')@@ -308,9 +307,7 @@ test.describe('Trends insights', () => {await test.step('navigate away and verify no orphaned tooltip', async () => {await insight.goToList()- // This project saves no insight, so the list opens on the product analytics setup- // screen rather than the table.- await expect(page.getByTestId('product-empty-state')).toBeVisible()+ await expect(page.getByRole('heading', { name: 'Product analytics', level: 1 })).toBeVisible()await expect(insight.trends.tooltip).toHaveCount(0, { timeout: 3000 })})})diff --git a/playwright/utils/test-data.ts b/playwright/utils/test-data.tsindex 6e9ffa2ae030..1abb4536f82e 100644--- a/playwright/utils/test-data.ts+++ b/playwright/utils/test-data.ts@@ -75,14 +75,28 @@ export const pageviews = {events: [...createEvent({ event: '$pageview', user: pvUser, timestamp: daysAgo(6) }).repeat(10),...createEvent({ event: '$pageview', user: pvUser, timestamp: daysAgo(5) }).repeat(8),- ...createEvent({ event: '$pageview', user: pvUser, timestamp: daysAgo(4) }).repeat(6),- ...createEvent({ event: '$pageview', user: pvUser, timestamp: daysAgo(3) }).repeat(5),+ ...createEvent({ event: '$pageview', user: pvUser, timestamp: daysAgo(4) }).repeat(3),+ ...createEvent({+ event: '$pageview',+ user: (n) => pvUser(n + 3),+ timestamp: daysAgo(4),+ properties: { $browser: 'Firefox' },+ }).repeat(3),+ ...createEvent({ event: '$pageview', user: pvUser, timestamp: daysAgo(3) }).repeat(3),+ ...createEvent({+ event: '$pageview',+ user: (n) => pvUser(n + 3),+ timestamp: daysAgo(3),+ properties: { $browser: 'Firefox' },+ }).repeat(2),...createEvent({ event: '$pageview', user: pvUser, timestamp: daysAgo(2) }).repeat(4),...createEvent({ event: '$pageview', user: pvUser, timestamp: hoursAgo(36) }).repeat(3),...createEvent({ event: '$pageview', user: pvUser, timestamp: daysAgo(0) }).repeat(2),],expected: {total: '38',+ chromeTotal: '33',+ firefoxTotal: '5',},}diff --git a/products/notebooks/backend/facade/widgets.py b/products/notebooks/backend/facade/widgets.pyindex f5f9feeed24b..7b332e3b53df 100644--- a/products/notebooks/backend/facade/widgets.py+++ b/products/notebooks/backend/facade/widgets.py@@ -1,4 +1,9 @@-from products.notebooks.backend.widget_models import DEFAULT_WIDGET_MODEL, WIDGET_MODEL_CHOICES+from products.notebooks.backend.widget_models import (+ DEFAULT_WIDGET_MODEL,+ MAX_WIDGET_EFFECTIVE_PROMPT_LENGTH,+ MAX_WIDGET_PROMPT_LENGTH,+ WIDGET_MODEL_CHOICES,+)from products.notebooks.backend.widgets import (WidgetConflictError,WidgetError,@@ -17,6 +22,8 @@ from products.notebooks.backend.widgets import (__all__ = ["DEFAULT_WIDGET_MODEL",+ "MAX_WIDGET_EFFECTIVE_PROMPT_LENGTH",+ "MAX_WIDGET_PROMPT_LENGTH","WIDGET_MODEL_CHOICES","WidgetConflictError","WidgetError",diff --git a/products/notebooks/backend/presentation/views/notebook.py b/products/notebooks/backend/presentation/views/notebook.pyindex 16688605a5f6..938ae677ac6f 100644--- a/products/notebooks/backend/presentation/views/notebook.py+++ b/products/notebooks/backend/presentation/views/notebook.py@@ -838,6 +838,7 @@ class NotebookViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, ForbidDmodel=serializer.validated_data["model"],generation_id=serializer.validated_data["generation_id"],operation=serializer.validated_data["generation_operation"],+ expected_current_version_id=serializer.validated_data.get("expected_current_version_id"),)except WidgetError as error:return self._widget_error_response(error)diff --git a/products/notebooks/backend/presentation/widget_serializers.py b/products/notebooks/backend/presentation/widget_serializers.pyindex 04ae851acb65..8b7d14c1b528 100644--- a/products/notebooks/backend/presentation/widget_serializers.py+++ b/products/notebooks/backend/presentation/widget_serializers.py@@ -1,13 +1,26 @@+from typing import Any+from rest_framework import serializers-from products.notebooks.backend.facade.widgets import DEFAULT_WIDGET_MODEL, WIDGET_MODEL_CHOICES+from products.notebooks.backend.facade.widgets import (+ DEFAULT_WIDGET_MODEL,+ MAX_WIDGET_EFFECTIVE_PROMPT_LENGTH,+ MAX_WIDGET_PROMPT_LENGTH,+ WIDGET_MODEL_CHOICES,+)class WidgetGenerateRequestSerializer(serializers.Serializer):prompt = serializers.CharField(- max_length=20_000,+ max_length=MAX_WIDGET_EFFECTIVE_PROMPT_LENGTH,trim_whitespace=False,- help_text="Instructions for the generated widget.",+ error_messages={+ "max_length": f"Keep widget instructions to {MAX_WIDGET_EFFECTIVE_PROMPT_LENGTH:,} characters or fewer."+ },+ help_text=(+ "Instructions for the generated widget. Initial and improvement instructions accept up to 20,000 "+ "characters; regeneration accepts complete instructions up to 50,000 characters."+ ),)generation_id = serializers.UUIDField(help_text="Idempotency key for this generation job.")model = serializers.ChoiceField(@@ -20,6 +33,21 @@ class WidgetGenerateRequestSerializer(serializers.Serializer):default="regenerate",help_text="Whether to generate from scratch or improve the current source.",)+ expected_current_version_id = serializers.UUIDField(+ required=False,+ help_text="Current widget version the improvement is based on. Required for improve operations.",+ )++ def validate(self, attrs: dict[str, Any]) -> dict[str, Any]:+ operation = attrs["generation_operation"]+ prompt = attrs["prompt"].strip()+ if operation != "regenerate" and len(prompt) > MAX_WIDGET_PROMPT_LENGTH:+ raise serializers.ValidationError(+ {"prompt": f"Keep widget instructions to {MAX_WIDGET_PROMPT_LENGTH:,} characters or fewer."}+ )+ if operation == "improve" and "expected_current_version_id" not in attrs:+ raise serializers.ValidationError({"expected_current_version_id": "Reload the widget before improving it."})+ return attrsclass WidgetCancelRequestSerializer(serializers.Serializer):@@ -99,7 +127,10 @@ class WidgetVersionSerializer(serializers.Serializer):help_text="Action that created this version.",)prompt_delta = serializers.CharField(help_text="Instructions added by this version.")- effective_prompt = serializers.CharField(help_text="Complete instructions represented by this version.")+ effective_prompt = serializers.CharField(+ max_length=MAX_WIDGET_EFFECTIVE_PROMPT_LENGTH,+ help_text="Complete instructions represented by this version, up to 50,000 characters.",+ )model = serializers.CharField(allow_null=True, help_text="AI model, or null when this version did not run a model.")created_at = serializers.DateTimeField(help_text="When this version was created.")build_status = serializers.ChoiceField(diff --git a/products/notebooks/backend/test/test_widgets.py b/products/notebooks/backend/test/test_widgets.pyindex 32851383b673..4766fc77f3c3 100644--- a/products/notebooks/backend/test/test_widgets.py+++ b/products/notebooks/backend/test/test_widgets.py@@ -55,7 +55,11 @@ from products.notebooks.backend.widget_generation import (generate_widget_source,review_widget_source,)-from products.notebooks.backend.widget_models import DEFAULT_WIDGET_MODEL+from products.notebooks.backend.widget_models import (+ DEFAULT_WIDGET_MODEL,+ MAX_WIDGET_EFFECTIVE_PROMPT_LENGTH,+ MAX_WIDGET_PROMPT_LENGTH,+)from products.notebooks.backend.widgets import (JOB_STALE_AFTER,MAX_FRAME_BYTES,@@ -350,6 +354,43 @@ class TestWidgetGeneration(SimpleTestCase):assert not serializer.is_valid()assert "model" in serializer.errors+ def test_generate_request_accepts_an_effective_prompt_for_regeneration(self) -> None:+ serializer = WidgetGenerateRequestSerializer(+ data={+ "prompt": "x" * MAX_WIDGET_EFFECTIVE_PROMPT_LENGTH,+ "generation_id": str(uuid4()),+ "generation_operation": "regenerate",+ }+ )++ assert serializer.is_valid(), serializer.errors++ def test_generate_request_keeps_initial_prompts_bounded(self) -> None:+ serializer = WidgetGenerateRequestSerializer(+ data={+ "prompt": "x" * (MAX_WIDGET_PROMPT_LENGTH + 1),+ "generation_id": str(uuid4()),+ "generation_operation": "initial",+ }+ )++ assert not serializer.is_valid()+ assert serializer.errors["prompt"] == [+ f"Keep widget instructions to {MAX_WIDGET_PROMPT_LENGTH:,} characters or fewer."+ ]++ def test_generate_request_requires_the_current_version_for_an_improvement(self) -> None:+ serializer = WidgetGenerateRequestSerializer(+ data={+ "prompt": "Make it lighter",+ "generation_id": str(uuid4()),+ "generation_operation": "improve",+ }+ )++ assert not serializer.is_valid()+ assert "expected_current_version_id" in serializer.errors+def test_canvas_validation_rejects_network(self) -> None:diagnostics = validate_notebook_canvas_source('export default function Canvas() { fetch("https://example.com"); return null }',@@ -385,10 +426,7 @@ class TestWidgetGeneration(SimpleTestCase):assert _strip_legacy_frame_bridge(source) == "export default function Canvas() { return <div /> }"- @parameterized.expand(- [("widget", "Widget"), ("legacy_generated_widget", "GeneratedWidget"), ("legacy_genui", "GenUI")]- )- def test_infers_dataframe_context_from_the_notebook(self, _name: str, tag_name: str) -> None:+ def test_infers_dataframe_context_from_the_notebook(self) -> None:notebook = cast(Notebook,SimpleNamespace(@@ -396,7 +434,7 @@ class TestWidgetGeneration(SimpleTestCase):'<PythonV2 nodeId="source" returnVariable="locations_df" />\n\n''<SQLV2 nodeId="summary" returnVariable="summary_df" />\n\n''<Query nodeId="saved" returnVariable="saved_df" />\n\n'- f'<{tag_name} nodeId="globe" prompt="Render a globe" />\n\n'+ '<Widget nodeId="globe" prompt="Render a globe" />\n\n''<PythonV2 nodeId="later" returnVariable="future_df" />')),@@ -404,17 +442,29 @@ class TestWidgetGeneration(SimpleTestCase):assert infer_widget_inputs(notebook, "globe") == ["locations_df", "summary_df", "future_df"]+ @parameterized.expand([("generated_widget", "GeneratedWidget"), ("genui", "GenUI")])+ def test_rejects_removed_widget_tags(self, _name: str, tag_name: str) -> None:+ notebook = cast(+ Notebook,+ SimpleNamespace(content=markdown_content(f'<{tag_name} nodeId="globe" prompt="Render a globe" />')),+ )++ with self.assertRaises(WidgetError) as error:+ infer_widget_inputs(notebook, "globe")++ assert error.exception.code == "node_not_found"+def test_infers_dataframe_context_without_an_explicit_id(self) -> None:notebook = cast(Notebook,SimpleNamespace(content=markdown_content(- '<SQLV2 nodeId="source" returnVariable="sql_df" />\n\n<GeneratedWidget prompt="Render a globe" />'+ '<SQLV2 nodeId="source" returnVariable="sql_df" />\n\n<Widget prompt="Render a globe" />')),)- assert infer_widget_inputs(notebook, "mdn-mjjdae-0") == ["sql_df"]+ assert infer_widget_inputs(notebook, "mdn-qb29jd-0") == ["sql_df"]def test_rejects_an_explicit_node_id_that_cannot_be_persisted(self) -> None:node_id = "x" * 129@@ -1033,6 +1083,54 @@ class TestWidgetData(APIBaseTest):assert job.status == GeneratedWidgetGenerationJob.Status.QUEUEDassert job.error_code is None+ def test_improvement_rejects_a_stale_current_version_before_creating_a_job(self) -> None:+ self._mapping()++ with (+ patch("products.notebooks.backend.widgets._is_ai_usage_limited", return_value=False),+ self.assertRaises(WidgetError) as error,+ ):+ start_widget_generation(+ notebook=self.notebook,+ node_id=self.NODE_ID,+ prompt="Make it lighter",+ user_id=self.user.id,+ inspection=WidgetInputInspection(resolved_inputs=[]),+ model="claude-sonnet-4-6",+ generation_id=uuid4(),+ operation=GeneratedWidgetVersion.Operation.IMPROVE,+ expected_current_version_id=uuid4(),+ )++ assert error.exception.code == "generation_conflict"+ assert not GeneratedWidgetGenerationJob.objects.for_team(self.team.id).exists()++ def test_improvement_rejects_prompt_history_that_cannot_fit_the_effective_limit(self) -> None:+ instance = self._mapping()+ current_version = self._pinned_version(instance)+ current_version.prompt_delta = "x" * MAX_WIDGET_EFFECTIVE_PROMPT_LENGTH+ current_version.prompt_history = [current_version.prompt_delta]+ current_version.save(update_fields=["prompt_delta", "prompt_history"])++ with (+ patch("products.notebooks.backend.widgets._is_ai_usage_limited", return_value=False),+ self.assertRaises(WidgetError) as error,+ ):+ start_widget_generation(+ notebook=self.notebook,+ node_id=self.NODE_ID,+ prompt="Make it lighter",+ user_id=self.user.id,+ inspection=WidgetInputInspection(resolved_inputs=[]),+ model="claude-sonnet-4-6",+ generation_id=uuid4(),+ operation=GeneratedWidgetVersion.Operation.IMPROVE,+ expected_current_version_id=current_version.id,+ )++ assert error.exception.code == "effective_prompt_too_long"+ assert not GeneratedWidgetGenerationJob.objects.for_team(self.team.id).exists()+def test_generation_requires_ai_data_processing_approval(self) -> None:self.organization.is_ai_data_processing_approved = Falseself.organization.save(update_fields=["is_ai_data_processing_approved"])@@ -1149,6 +1247,7 @@ class TestWidgetData(APIBaseTest):model="claude-sonnet-4-6",generation_id=generation_id,operation=GeneratedWidgetVersion.Operation.IMPROVE,+ expected_current_version_id=current_version.id,)assert result.active_job is not None@@ -1169,6 +1268,7 @@ class TestWidgetData(APIBaseTest):model="claude-sonnet-4-6",generation_id=generation_id,operation=GeneratedWidgetVersion.Operation.IMPROVE,+ expected_current_version_id=current_version.id,)assert error.exception.code == "generation_id_conflict"@@ -1221,6 +1321,7 @@ class TestWidgetData(APIBaseTest):model="claude-sonnet-4-6",generation_id=generation_id,operation=GeneratedWidgetVersion.Operation.IMPROVE,+ expected_current_version_id=self._pinned_version(instance).id,)own_job = GeneratedWidgetGenerationJob.objects.for_team(self.team.id).get(idempotency_key=generation_id)diff --git a/products/notebooks/backend/widget_models.py b/products/notebooks/backend/widget_models.pyindex b45c296396f9..33ca87cea97e 100644--- a/products/notebooks/backend/widget_models.py+++ b/products/notebooks/backend/widget_models.py@@ -6,3 +6,6 @@ WIDGET_MODEL_CHOICES = ()DEFAULT_WIDGET_MODEL = "claude-sonnet-4-6"++MAX_WIDGET_PROMPT_LENGTH = 20_000+MAX_WIDGET_EFFECTIVE_PROMPT_LENGTH = 50_000diff --git a/products/notebooks/backend/widgets.py b/products/notebooks/backend/widgets.pyindex a14568d32ebd..98e55fd505c4 100644--- a/products/notebooks/backend/widgets.py+++ b/products/notebooks/backend/widgets.py@@ -38,13 +38,12 @@ from products.notebooks.backend.util import (_iter_markdown_component_blocks,_parse_markdown_component_props,)+from products.notebooks.backend.widget_models import MAX_WIDGET_EFFECTIVE_PROMPT_LENGTH, MAX_WIDGET_PROMPT_LENGTHlogger = logging.getLogger(__name__)GENERATOR_VERSION = "4"MAX_INPUT_NAME_LENGTH = 128-MAX_PROMPT_LENGTH = 20_000-MAX_EFFECTIVE_PROMPT_LENGTH = 50_000MAX_COLUMNS = 100MAX_CELL_STRING_LENGTH = 4_096MAX_FRAME_BYTES = 512 * 1_024@@ -234,12 +233,17 @@ def _security_review_state(version: GeneratedWidgetVersion) -> WidgetSecurityRev)-def normalize_widget_prompt(prompt: str) -> str:+def normalize_widget_prompt(prompt: str, operation: str) -> str:normalized = prompt.strip()if not normalized:raise WidgetError("Add instructions before generating the widget.", "missing_prompt")- if len(normalized) > MAX_PROMPT_LENGTH:- raise WidgetError("The widget instructions are too long.", "prompt_too_long")+ max_length = (+ MAX_WIDGET_EFFECTIVE_PROMPT_LENGTH+ if operation == GeneratedWidgetVersion.Operation.REGENERATE+ else MAX_WIDGET_PROMPT_LENGTH+ )+ if len(normalized) > max_length:+ raise WidgetError(f"Keep widget instructions to {max_length:,} characters or fewer.", "prompt_too_long")return normalized@@ -263,7 +267,7 @@ def _widget_node_ids(content: object) -> set[str]:if markdown is not None:occurrences: dict[str, int] = {}for tag_name, raw, _next_line_index in _iter_markdown_component_blocks(markdown):- if tag_name not in {"Widget", "GeneratedWidget", "GenUI"}:+ if tag_name != "Widget":continueprops = _parse_markdown_component_props(raw)fingerprint = _get_markdown_component_fingerprint(tag_name, props)@@ -556,6 +560,7 @@ def _validate_generation_retry(prompt: str,model: str,operation: str,+ expected_current_version_id: UUID | None,) -> None:if job.team_id != notebook.team_id or job.instance.notebook_id != notebook.id or job.instance.node_id != node_id:raise WidgetConflictError("This generation identifier belongs to another widget.", "generation_id_conflict")@@ -569,6 +574,11 @@ def _validate_generation_retry("This generation identifier was already used with different instructions.","generation_id_conflict",)+ if operation == GeneratedWidgetVersion.Operation.IMPROVE and job.base_version_id != expected_current_version_id:+ raise WidgetConflictError(+ "This generation identifier was already used for a different widget version.",+ "generation_id_conflict",+ )def _fail_stale_generation_jobs(team_id: int) -> None:@@ -645,9 +655,10 @@ def start_widget_generation(model: str,generation_id: UUID,operation: str,+ expected_current_version_id: UUID | None = None,) -> WidgetStatus:assert_widget_node_exists(notebook, node_id)- normalized_prompt = normalize_widget_prompt(prompt)+ normalized_prompt = normalize_widget_prompt(prompt, operation)if not Team.objects.filter(id=notebook.team_id, organization__is_ai_data_processing_approved=True).exists():raise WidgetError("Approve AI data processing in organization settings before generating widgets.",@@ -662,6 +673,7 @@ def start_widget_generation(prompt=normalized_prompt,model=model,operation=operation,+ expected_current_version_id=expected_current_version_id,)_dispatch_widget_generation(existing_job.id, existing_job.team_id)return get_widget_status(notebook=notebook, node_id=node_id)@@ -683,6 +695,7 @@ def start_widget_generation(prompt=normalized_prompt,model=model,operation=operation,+ expected_current_version_id=expected_current_version_id,)return get_widget_status(notebook=notebook, node_id=node_id)_fail_stale_generation_jobs(notebook.team_id)@@ -715,8 +728,20 @@ def start_widget_generation("generation_in_progress",)base_version = locked_instance.widget.current_version- if operation == GeneratedWidgetVersion.Operation.IMPROVE and base_version is None:- raise WidgetConflictError("Generate the widget before improving it.", "version_missing")+ if operation == GeneratedWidgetVersion.Operation.IMPROVE:+ if base_version is None:+ raise WidgetConflictError("Generate the widget before improving it.", "version_missing")+ if expected_current_version_id is None or base_version.id != expected_current_version_id:+ raise WidgetConflictError(+ "This widget changed since you opened it. Reload the latest version before improving it.",+ "generation_conflict",+ )+ next_prompt_history = _extend_prompt_history(_prompt_history(base_version), normalized_prompt)+ if len(_materialize_prompt_history(next_prompt_history)) > MAX_WIDGET_EFFECTIVE_PROMPT_LENGTH:+ raise WidgetError(+ "The widget's full instructions are too long to improve. Regenerate it with shorter instructions first.",+ "effective_prompt_too_long",+ )resolved_operation = operationif base_version is None:resolved_operation = GeneratedWidgetVersion.Operation.INITIAL@@ -820,7 +845,7 @@ def _materialize_prompt_history(history: list[str]) -> str:def _extend_prompt_history(history: list[str], prompt: str) -> list[str]:bounded = [*history, prompt]- while len(bounded) > 2 and len(_materialize_prompt_history(bounded)) > MAX_EFFECTIVE_PROMPT_LENGTH:+ while len(bounded) > 2 and len(_materialize_prompt_history(bounded)) > MAX_WIDGET_EFFECTIVE_PROMPT_LENGTH:del bounded[1]return boundeddiff --git a/products/notebooks/frontend/NotebookNodeGeneratedWidget/NotebookGeneratedWidgetRunButton.tsx b/products/notebooks/frontend/NotebookNodeGeneratedWidget/NotebookGeneratedWidgetRunButton.tsxnew file mode 100644index 000000000000..59dc95820762--- /dev/null+++ b/products/notebooks/frontend/NotebookNodeGeneratedWidget/NotebookGeneratedWidgetRunButton.tsx@@ -0,0 +1,69 @@+import { useActions, useMountedLogic, useValues } from 'kea'++import { IconPlayFilled } from '@posthog/icons'++import type { NotebookComponentToolbarProps } from 'lib/components/MarkdownNotebook/types'+import { LemonButton } from 'lib/lemon-ui/LemonButton'+import { notebookLogic } from 'scenes/notebooks/Notebook/notebookLogic'+import { teamLogic } from 'scenes/teamLogic'++import { notebookNodeGeneratedWidgetLogic } from './notebookNodeGeneratedWidgetLogic'+import { DEFAULT_WIDGET_MODEL, isWidgetModel } from './widgetModels'++export function NotebookGeneratedWidgetRunButton({ node }: NotebookComponentToolbarProps): JSX.Element | null {+ const mountedNotebookLogic = useMountedLogic(notebookLogic)+ const { canEditNotebook, isShared } = useValues(mountedNotebookLogic)++ if (isShared || !canEditNotebook) {+ return null+ }++ return <EditableNotebookGeneratedWidgetRunButton node={node} />+}++function EditableNotebookGeneratedWidgetRunButton({+ node,+}: {+ node: NotebookComponentToolbarProps['node']+}): JSX.Element {+ const mountedNotebookLogic = useMountedLogic(notebookLogic)+ const { canEditNotebook } = useValues(mountedNotebookLogic)+ const { currentTeamId } = useValues(teamLogic)+ const nodeId = typeof node.props.nodeId === 'string' && node.props.nodeId ? node.props.nodeId : node.id+ const model =+ typeof node.props.model === 'string' && isWidgetModel(node.props.model)+ ? node.props.model+ : DEFAULT_WIDGET_MODEL+ const logic = notebookNodeGeneratedWidgetLogic({+ projectId: currentTeamId,+ notebookShortId: mountedNotebookLogic.props.shortId,+ nodeId,+ prompt: typeof node.props.prompt === 'string' ? node.props.prompt : '',+ model,+ isEditable: canEditNotebook,+ persistNotebook: async (): Promise<void> => {+ await mountedNotebookLogic.asyncActions.saveNotebook({+ content: mountedNotebookLogic.values.content,+ title: mountedNotebookLogic.values.title,+ })+ },+ getContent: () => mountedNotebookLogic.values.content ?? null,+ })+ const { dataRefreshInFlight, runDataDependenciesDisabledReason } = useValues(logic)+ const { runDataDependencies } = useActions(logic)++ return (+ <LemonButton+ data-attr="notebook-generated-widget-run-button"+ size="xsmall"+ type="primary"+ icon={<IconPlayFilled color="var(--success)" />}+ onClick={runDataDependencies}+ loading={dataRefreshInFlight}+ disabledReason={runDataDependenciesDisabledReason ?? undefined}+ tooltip="Run widget data cells"+ >+ Run+ </LemonButton>+ )+}diff --git a/products/notebooks/frontend/NotebookNodeGeneratedWidget/NotebookNodeGeneratedWidget.test.tsx b/products/notebooks/frontend/NotebookNodeGeneratedWidget/NotebookNodeGeneratedWidget.test.tsxnew file mode 100644index 000000000000..0304afc14bdd--- /dev/null+++ b/products/notebooks/frontend/NotebookNodeGeneratedWidget/NotebookNodeGeneratedWidget.test.tsx@@ -0,0 +1,555 @@+import { MOCK_TEAM_ID } from 'lib/api.mock'++import { cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react'+import { BindLogic } from 'kea'+import { expectLogic } from 'kea-test-utils'++import api from 'lib/api'+import { buildMarkdownNotebookContent } from 'scenes/notebooks/Notebook/markdownNotebookV2'+import { MarkdownNotebookV2 } from 'scenes/notebooks/Notebook/MarkdownNotebookV2Renderer'+import { NotebookLogicProps, notebookLogic } from 'scenes/notebooks/Notebook/notebookLogic'+import { NotebookType } from 'scenes/notebooks/types'++import { initKeaTests } from '~/test/init'+import { AccessControlLevel } from '~/types'++import {+ notebooksWidgetCancel,+ notebooksWidgetSource,+ notebooksWidgetStatus,+ notebooksWidgetVersions,+} from 'products/notebooks/frontend/generated/api'++import { notebookNodeGeneratedWidgetLogic } from './notebookNodeGeneratedWidgetLogic'+import { NotebookWidgetGenerationModal } from './NotebookWidgetGenerationModal'++jest.mock('scenes/notebooks/Notebook/migrations/migrate', () => {+ const actual = jest.requireActual('scenes/notebooks/Notebook/migrations/migrate')+ return { ...actual, migrate: jest.fn(async (notebook: unknown) => notebook) }+})++jest.mock('products/notebooks/frontend/generated/api', () => ({+ notebooksWidgetCancel: jest.fn(),+ notebooksWidgetFrame: jest.fn(),+ notebooksWidgetGenerate: jest.fn(),+ notebooksWidgetRevert: jest.fn(),+ notebooksWidgetSource: jest.fn(),+ notebooksWidgetStatus: jest.fn(),+ notebooksWidgetVersions: jest.fn(),+}))++jest.mock('react-intersection-observer', () => ({+ useInView: () => ({ ref: () => undefined, inView: true }),+}))++const SHORT_ID = 'generated-widget-progress'+const MARKDOWN = '<Widget showFilters showResults nodeId="globe" prompt="Render a globe" model="claude-sonnet-4-6" />'+const cachedNotebook = {+ id: 'notebook-id',+ short_id: SHORT_ID,+ title: 'Generated widget progress',+ content: buildMarkdownNotebookContent(MARKDOWN),+ text_content: MARKDOWN,+ version: 1,+ deleted: false,+ is_template: false,+ user_access_level: AccessControlLevel.Editor,+ created_at: '2026-08-27T12:00:00Z',+ created_by: null,+ last_modified_at: '2026-08-27T12:00:00Z',+ last_modified_by: null,+} as unknown as NotebookType+const logicProps: NotebookLogicProps = { shortId: SHORT_ID, mode: 'notebook' }++describe('NotebookNodeGeneratedWidget', () => {+ let logic: ReturnType<typeof notebookLogic.build>++ beforeEach(async () => {+ initKeaTests()+ jest.spyOn(api.notebooks, 'collabStream').mockResolvedValue(undefined as never)+ jest.spyOn(api.notebooks, 'get').mockResolvedValue(cachedNotebook)+ jest.mocked(notebooksWidgetStatus).mockResolvedValue({+ lifecycle_status: 'generating',+ error_detail: null,+ artifact_url: null,+ frame_names: [],+ current_version_id: '00000000-0000-0000-0000-000000000002',+ widget_id: '00000000-0000-0000-0000-000000000003',+ instance_id: '00000000-0000-0000-0000-000000000004',+ has_versions: true,+ active_job: {+ id: '00000000-0000-0000-0000-000000000001',+ status: 'generating',+ phase: 'generating_source',+ model: 'claude-sonnet-4-6',+ created_at: '2026-08-27T12:00:00Z',+ started_at: '2026-08-27T12:00:00Z',+ },+ security_review: null,+ build_hash: null,+ })+ jest.mocked(notebooksWidgetVersions).mockResolvedValue({ results: [], count: 0, next_offset: null })++ logic = notebookLogic(logicProps)+ logic.mount()+ logic.actions.loadNotebook()+ await expectLogic(logic).toDispatchActions(['loadNotebookSuccess']).toFinishAllListeners()+ logic.actions.setEditable(true)+ })++ afterEach(() => {+ cleanup()+ logic?.unmount()+ jest.restoreAllMocks()+ })++ it('shows generation progress only in filters when filters and results are open', async () => {+ render(+ <BindLogic logic={notebookLogic} props={logicProps}>+ <MarkdownNotebookV2 />+ </BindLogic>+ )++ expect(screen.getByText('Widget')).toBeTruthy()+ await waitFor(() => expect(screen.getAllByText('Regenerating widget…')).toHaveLength(1))+ })++ it('renders without crashing when the markdown tag has a non-string prompt or unknown model', async () => {+ logic.unmount()+ const notebookWithMalformedTag = {+ ...cachedNotebook,+ // A valueless `prompt` attribute parses to boolean true, and the model is an unsupported string.+ content: buildMarkdownNotebookContent(+ '<Widget showResults nodeId="globe" prompt model="not-a-real-model" />'+ ),+ }+ jest.mocked(api.notebooks.get).mockResolvedValue(notebookWithMalformedTag)+ logic = notebookLogic(logicProps)+ logic.mount()+ logic.actions.loadNotebook()+ await expectLogic(logic).toDispatchActions(['loadNotebookSuccess']).toFinishAllListeners()+ logic.actions.setEditable(true)++ render(+ <BindLogic logic={notebookLogic} props={logicProps}>+ <MarkdownNotebookV2 />+ </BindLogic>+ )++ expect(await screen.findByText('Regenerating widget…')).toBeTruthy()+ })++ it('does not offer initial generation in the settings panel while status is still loading', async () => {+ // The status request never resolves, so `status` stays null through the render.+ jest.mocked(notebooksWidgetStatus).mockImplementation(() => new Promise(() => {}))++ render(+ <BindLogic logic={notebookLogic} props={logicProps}>+ <MarkdownNotebookV2 />+ </BindLogic>+ )++ expect(await screen.findByText('Widget')).toBeTruthy()+ // Before the first status response the panel must not present the initial form, or an+ // editor could start a job that the backend turns into a regeneration.+ expect(screen.queryByText('Generate widget')).toBeNull()+ expect(screen.queryByText('Instructions')).toBeNull()+ })++ it('shows cancellation errors while initial generation is still running', async () => {+ jest.mocked(notebooksWidgetCancel).mockRejectedValue(new Error('Cancel request failed'))++ render(+ <BindLogic logic={notebookLogic} props={logicProps}>+ <MarkdownNotebookV2 />+ </BindLogic>+ )++ fireEvent.click(await screen.findByText('Cancel'))++ expect(await screen.findByText('Cancel request failed')).toBeTruthy()+ })++ it('shows a generation failure inside the generation modal', async () => {+ const generationModalLogicProps = {+ projectId: MOCK_TEAM_ID,+ notebookShortId: SHORT_ID,+ nodeId: 'globe',+ prompt: 'Render a globe',+ model: 'claude-sonnet-4-6' as const,+ isEditable: true,+ persistNotebook: async (): Promise<void> => undefined,+ getContent: () => null,+ }+ const widgetLogic = notebookNodeGeneratedWidgetLogic(generationModalLogicProps)+ widgetLogic.mount()+ await expectLogic(widgetLogic).toFinishAllListeners()+ widgetLogic.actions.openGenerationModal('improve')+ widgetLogic.actions.generationFailed('The widget could not be generated.')++ render(<NotebookWidgetGenerationModal logicProps={generationModalLogicProps} />)++ // A failed generation keeps the modal open, so the reason must be visible inside it.+ expect(await screen.findByText('The widget could not be generated.')).toBeTruthy()+ widgetLogic.unmount()+ })++ it('opens the current source with an improvement prompt', async () => {+ const versionId = '00000000-0000-0000-0000-000000000002'+ jest.mocked(notebooksWidgetStatus).mockResolvedValue({+ lifecycle_status: 'ready',+ error_detail: null,+ artifact_url: 'https://example.com/widget.html',+ frame_names: [],+ current_version_id: versionId,+ widget_id: '00000000-0000-0000-0000-000000000003',+ instance_id: '00000000-0000-0000-0000-000000000004',+ has_versions: true,+ active_job: null,+ security_review: null,+ build_hash: 'a'.repeat(64),+ })+ jest.mocked(notebooksWidgetVersions).mockResolvedValue({+ results: [+ {+ id: versionId,+ parent_version_id: null,+ version: 1,+ version_operation: 'initial',+ prompt_delta: 'Render a globe',+ effective_prompt: 'Render a globe',+ model: 'claude-sonnet-4-6',+ created_at: '2026-08-27T12:00:00Z',+ build_status: 'ready',+ artifact_url: 'https://example.com/widget.html',+ frame_names: [],+ is_current: true,+ security_review: null,+ build_hash: 'a'.repeat(64),+ },+ ],+ count: 1,+ next_offset: null,+ })+ jest.mocked(notebooksWidgetSource).mockResolvedValue({+ source: 'export default function Widget() {}',+ })+ render(+ <BindLogic logic={notebookLogic} props={logicProps}>+ <MarkdownNotebookV2 />+ </BindLogic>+ )++ const improveButton = await screen.findByText('Improve…')+ const actionContainer = improveButton.closest('button')!.parentElement!+ const actionButtons = [+ improveButton,+ within(actionContainer).getByText('Regenerate…'),+ within(actionContainer).getByText('View source'),+ within(actionContainer).getByText('Reload preview'),+ ]+ actionButtons.slice(0, -1).forEach((button, index) => {+ expect(+ button.compareDocumentPosition(actionButtons[index + 1]) & Node.DOCUMENT_POSITION_FOLLOWING+ ).toBeTruthy()+ })+ jest.mocked(notebooksWidgetStatus).mockClear()+ fireEvent.click(actionButtons[3])+ await waitFor(() =>+ expect(notebooksWidgetStatus).toHaveBeenCalledWith(+ String(MOCK_TEAM_ID),+ SHORT_ID,+ 'globe',+ expect.objectContaining({ signal: expect.anything() })+ )+ )++ fireEvent.click(actionButtons[2])++ await waitFor(() =>+ expect(notebooksWidgetSource).toHaveBeenCalledWith(+ String(MOCK_TEAM_ID),+ SHORT_ID,+ 'globe',+ { version_id: versionId },+ expect.objectContaining({ signal: expect.anything() })+ )+ )+ expect(screen.getByText('Widget source')).toBeTruthy()+ expect(screen.getByText('What would you like to change?')).toBeTruthy()+ expect(screen.getByText('Build changes')).toBeTruthy()+ })++ it('shows security findings before mounting the exact build', async () => {+ const versionId = '00000000-0000-0000-0000-000000000005'+ const buildHash = 'b'.repeat(64)+ const securityReview = {+ severity: 'high' as const,+ summary: 'The widget may send notebook data to another window.',+ findings: [+ {+ severity: 'high' as const,+ title: 'Notebook data may leave the preview',+ details: 'The source sends rows to the parent window without using the approved bridge.',+ },+ ],+ model: 'claude-haiku-4-5',+ review_version: '1',+ reviewed_at: '2026-08-31T10:00:00Z',+ }+ jest.mocked(notebooksWidgetStatus).mockResolvedValue({+ lifecycle_status: 'ready',+ error_detail: null,+ artifact_url: 'https://example.com/untrusted-widget.html',+ frame_names: [],+ current_version_id: versionId,+ widget_id: '00000000-0000-0000-0000-000000000006',+ instance_id: '00000000-0000-0000-0000-000000000007',+ has_versions: true,+ active_job: null,+ security_review: securityReview,+ build_hash: buildHash,+ })+ jest.mocked(notebooksWidgetVersions).mockResolvedValue({+ results: [+ {+ id: versionId,+ parent_version_id: null,+ version: 1,+ version_operation: 'initial',+ prompt_delta: 'Render a globe',+ effective_prompt: 'Render a globe',+ model: 'claude-sonnet-4-6',+ created_at: '2026-08-27T12:00:00Z',+ build_status: 'ready',+ artifact_url: 'https://example.com/untrusted-widget.html',+ frame_names: [],+ is_current: true,+ security_review: securityReview,+ build_hash: buildHash,+ },+ ],+ count: 1,+ next_offset: null,+ })+ const { container } = render(+ <BindLogic logic={notebookLogic} props={logicProps}>+ <MarkdownNotebookV2 />+ </BindLogic>+ )++ await screen.findByText('Security review found potential issues')+ expect(screen.getByText('Notebook data may leave the preview')).toBeTruthy()+ expect(screen.getByText('Run widget anyway')).toBeTruthy()+ await waitFor(() => expect(container.querySelector('[data-attr="notebook-widget-run"]')).not.toBeNull())+ const runButton = container.querySelector('[data-attr="notebook-widget-run"]')!+ expect(container.querySelector('iframe')).toBeNull()++ fireEvent.click(runButton)++ await waitFor(() => expect(container.querySelector('[data-attr="notebook-widget-run"]')).toBeNull())+ await waitFor(() => expect(container.querySelector('iframe')).not.toBeNull())+ expect(container.querySelector('iframe')?.getAttribute('src')).toBe(+ 'https://example.com/untrusted-widget.html#theme=light'+ )+ expect(container.querySelector('iframe')?.getAttribute('title')).toBe('Widget')+ })++ it('requires exact-build consent when the security review passes', async () => {+ const versionId = '00000000-0000-0000-0000-000000000008'+ const buildHash = 'c'.repeat(64)+ const securityReview = {+ severity: 'none' as const,+ summary: 'No security issues found.',+ findings: [],+ model: 'claude-haiku-4-5',+ review_version: '1',+ reviewed_at: '2026-08-31T10:00:00Z',+ }+ jest.mocked(notebooksWidgetStatus).mockResolvedValue({+ lifecycle_status: 'ready',+ error_detail: null,+ artifact_url: 'https://example.com/reviewed-widget.html',+ frame_names: [],+ current_version_id: versionId,+ widget_id: '00000000-0000-0000-0000-000000000009',+ instance_id: '00000000-0000-0000-0000-000000000010',+ has_versions: true,+ active_job: null,+ security_review: securityReview,+ build_hash: buildHash,+ })+ jest.mocked(notebooksWidgetVersions).mockResolvedValue({+ results: [+ {+ id: versionId,+ parent_version_id: null,+ version: 1,+ version_operation: 'initial',+ prompt_delta: 'Render a globe',+ effective_prompt: 'Render a globe',+ model: 'claude-sonnet-4-6',+ created_at: '2026-08-31T10:00:00Z',+ build_status: 'ready',+ artifact_url: 'https://example.com/reviewed-widget.html',+ frame_names: [],+ is_current: true,+ security_review: securityReview,+ build_hash: buildHash,+ },+ ],+ count: 1,+ next_offset: null,+ })+ const { container } = render(+ <BindLogic logic={notebookLogic} props={logicProps}>+ <MarkdownNotebookV2 />+ </BindLogic>+ )++ await screen.findByText('Review this widget before running it')+ expect(container.querySelector('iframe')).toBeNull()+ expect(screen.getByText('Automated review: No potential issues flagged')).toBeTruthy()++ fireEvent.click(container.querySelector('[data-attr="notebook-widget-run"]')!)++ await waitFor(() => expect(container.querySelector('iframe')).not.toBeNull())+ expect(container.querySelector('[data-attr="notebook-widget-run"]')).toBeNull()+ })++ it('opens regeneration from a failed preview when the filters are closed', async () => {+ const versionId = '00000000-0000-0000-0000-000000000011'+ jest.mocked(notebooksWidgetStatus).mockResolvedValue({+ lifecycle_status: 'failed',+ error_detail: 'The widget build failed.',+ artifact_url: null,+ frame_names: [],+ current_version_id: versionId,+ widget_id: '00000000-0000-0000-0000-000000000012',+ instance_id: '00000000-0000-0000-0000-000000000013',+ has_versions: true,+ active_job: null,+ security_review: null,+ build_hash: null,+ })+ jest.mocked(notebooksWidgetVersions).mockResolvedValue({+ results: [+ {+ id: versionId,+ parent_version_id: null,+ version: 1,+ version_operation: 'initial',+ prompt_delta: 'Render a globe',+ effective_prompt: 'Render a globe',+ model: 'claude-sonnet-4-6',+ created_at: '2026-08-31T10:00:00Z',+ build_status: 'failed',+ artifact_url: null,+ frame_names: [],+ is_current: true,+ security_review: null,+ build_hash: null,+ },+ ],+ count: 1,+ next_offset: null,+ })+ logic.unmount()+ const notebookWithoutFilters = {+ ...cachedNotebook,+ content: buildMarkdownNotebookContent(+ '<Widget showResults nodeId="globe" prompt="Render a globe" model="claude-sonnet-4-6" />'+ ),+ }+ jest.mocked(api.notebooks.get).mockResolvedValue(notebookWithoutFilters)+ logic = notebookLogic(logicProps)+ logic.mount()+ logic.actions.loadNotebook()+ await expectLogic(logic).toDispatchActions(['loadNotebookSuccess']).toFinishAllListeners()+ logic.actions.setEditable(true)++ render(+ <BindLogic logic={notebookLogic} props={logicProps}>+ <MarkdownNotebookV2 />+ </BindLogic>+ )++ fireEvent.click(await screen.findByText('Regenerate…'))++ expect(await screen.findByText('Regenerate widget')).toBeTruthy()+ expect(screen.getByDisplayValue('Render a globe')).toBeTruthy()+ })++ it('keeps source available when the selected version has no preview', async () => {+ const versionId = '00000000-0000-0000-0000-000000000014'+ jest.mocked(notebooksWidgetStatus).mockResolvedValue({+ lifecycle_status: 'ready',+ error_detail: null,+ artifact_url: null,+ frame_names: [],+ current_version_id: versionId,+ widget_id: '00000000-0000-0000-0000-000000000015',+ instance_id: '00000000-0000-0000-0000-000000000016',+ has_versions: true,+ active_job: null,+ security_review: null,+ build_hash: null,+ })+ jest.mocked(notebooksWidgetSource).mockResolvedValue({+ source: 'export default function Widget() {}',+ })+ logic.unmount()+ const notebookWithoutFilters = {+ ...cachedNotebook,+ content: buildMarkdownNotebookContent(+ '<Widget showResults nodeId="globe" prompt="Render a globe" model="claude-sonnet-4-6" />'+ ),+ }+ jest.mocked(api.notebooks.get).mockResolvedValue(notebookWithoutFilters)+ logic = notebookLogic(logicProps)+ logic.mount()+ logic.actions.loadNotebook()+ await expectLogic(logic).toDispatchActions(['loadNotebookSuccess']).toFinishAllListeners()+ logic.actions.setEditable(true)++ render(+ <BindLogic logic={notebookLogic} props={logicProps}>+ <MarkdownNotebookV2 />+ </BindLogic>+ )++ expect(await screen.findByText(/preview is no longer available/)).toBeTruthy()+ fireEvent.click(screen.getByText('View source'))++ await waitFor(() =>+ expect(notebooksWidgetSource).toHaveBeenCalledWith(+ String(MOCK_TEAM_ID),+ SHORT_ID,+ 'globe',+ { version_id: versionId },+ expect.objectContaining({ signal: expect.anything() })+ )+ )+ expect(screen.getByText('Widget source')).toBeTruthy()+ })++ it('does not load generated widgets in publicly shared notebooks', async () => {+ logic.unmount()+ jest.mocked(notebooksWidgetStatus).mockClear()+ const sharedLogicProps: NotebookLogicProps = { ...logicProps, cachedNotebook }+ logic = notebookLogic(sharedLogicProps)+ logic.mount()+ logic.actions.loadNotebook()+ await expectLogic(logic).toDispatchActions(['loadNotebookSuccess']).toFinishAllListeners()+ const statusCallCount = jest.mocked(notebooksWidgetStatus).mock.calls.length++ render(+ <BindLogic logic={notebookLogic} props={sharedLogicProps}>+ <MarkdownNotebookV2 />+ </BindLogic>+ )++ expect(await screen.findByText('Node cannot be rendered')).toBeTruthy()+ expect(notebooksWidgetStatus).toHaveBeenCalledTimes(statusCallCount)+ })+})diff --git a/products/notebooks/frontend/NotebookNodeGeneratedWidget/NotebookNodeGeneratedWidget.tsx b/products/notebooks/frontend/NotebookNodeGeneratedWidget/NotebookNodeGeneratedWidget.tsxnew file mode 100644index 000000000000..b1e3f40551c6--- /dev/null+++ b/products/notebooks/frontend/NotebookNodeGeneratedWidget/NotebookNodeGeneratedWidget.tsx@@ -0,0 +1,476 @@+import { useActions, useMountedLogic, useValues } from 'kea'+import type { ReactNode } from 'react'++import { LemonBanner, LemonButton } from '@posthog/lemon-ui'++import { useComponentPanelState } from 'lib/components/MarkdownNotebook/componentPanelContext'+import { LemonSkeleton } from 'lib/lemon-ui/LemonSkeleton'+import { Spinner } from 'lib/lemon-ui/Spinner'+import { createPostHogWidgetNode } from 'scenes/notebooks/Nodes/NodeWrapper'+import { notebookNodeLogic } from 'scenes/notebooks/Nodes/notebookNodeLogic'+import { UnsupportedNodePlaceholder } from 'scenes/notebooks/Nodes/sharedNodeSupport'+import { NotebookNodeAttributes, NotebookNodeProps, NotebookNodeType } from 'scenes/notebooks/types'+import { teamLogic } from 'scenes/teamLogic'+import { userLogic } from 'scenes/userLogic'++import {+ formatWidgetElapsed,+ loadWidgetFrame,+ notebookNodeGeneratedWidgetLogic,+} from './notebookNodeGeneratedWidgetLogic'+import { NotebookNodeGeneratedWidgetSettings } from './NotebookNodeGeneratedWidgetSettings'+import { NotebookWidgetGenerationModal } from './NotebookWidgetGenerationModal'+import { NotebookWidgetSourceModal } from './NotebookWidgetSourceModal'+import { NotebookWidgetTrustControls } from './NotebookWidgetTrustControls'+import { getNotebookWidgetTrust, notebookWidgetTrustLogic } from './notebookWidgetTrustLogic'+import { WidgetArtifactFrame } from './WidgetArtifactFrame'+import { DEFAULT_WIDGET_MODEL, isWidgetModel, type WidgetModel } from './widgetModels'++export type NotebookNodeGeneratedWidgetAttributes = {+ prompt?: string+ model?: WidgetModel+}++function EmptyState({ children }: { children: ReactNode }): JSX.Element {+ return (+ <div className="flex h-full min-h-32 items-center justify-center p-4 text-center text-secondary">+ {children}+ </div>+ )+}++function Component({ attributes }: NotebookNodeProps<NotebookNodeGeneratedWidgetAttributes>): JSX.Element | null {+ const nodeLogic = useMountedLogic(notebookNodeLogic)+ const { expanded, notebookLogic } = useValues(nodeLogic)+ const { isShared } = useValues(notebookLogic)++ if (!expanded) {+ return null+ }+ return isShared ? <UnsupportedNodePlaceholder /> : <ExpandedWidget attributes={attributes} />+}++function ExpandedWidget({+ attributes,+}: {+ attributes: NotebookNodeAttributes<NotebookNodeGeneratedWidgetAttributes>+}): JSX.Element | null {+ const nodeLogic = useMountedLogic(notebookNodeLogic)+ const componentPanelState = useComponentPanelState()+ const { isEditable, notebookLogic } = useValues(nodeLogic)+ const { currentTeamId } = useValues(teamLogic)+ const { user } = useValues(userLogic)+ const notebookShortId = notebookLogic.props.shortId+ // Markdown props are cast without runtime validation, so a hand-written or legacy+ // tag can supply a non-string prompt or an unsupported model. Coerce both here, the+ // same way the run-button toolbar and the sibling code/height nodes do.+ const prompt = typeof attributes.prompt === 'string' ? attributes.prompt : ''+ const model = isWidgetModel(attributes.model) ? attributes.model : DEFAULT_WIDGET_MODEL+ const logicProps = {+ projectId: currentTeamId,+ notebookShortId,+ nodeId: attributes.nodeId,+ prompt,+ model,+ isEditable,+ persistNotebook: async (): Promise<void> => {+ await notebookLogic.asyncActions.saveNotebook({+ content: notebookLogic.values.content,+ title: notebookLogic.values.title,+ })+ },+ getContent: () => notebookLogic.values.content ?? null,+ }+ const logic = notebookNodeGeneratedWidgetLogic(logicProps)+ const trustLogic = useMountedLogic(notebookWidgetTrustLogic)+ const { sessionBuildHashes, trustByUser } = useValues(trustLogic)+ const {+ artifactUnavailable,+ artifactLoading,+ activeFrameNames,+ cancellationInFlight,+ dataRefreshInFlight,+ elapsedSeconds,+ frameRevision,+ generationError,+ generationRequestLoading,+ isWorking,+ runtimeError,+ runDataDependenciesDisabledReason,+ selectedVersion,+ selectedVersionId,+ status,+ statusLoadError,+ statusLoading,+ versionsError,+ versionsLoading,+ workingStatus,+ } = useValues(logic)+ const {+ artifactAvailable,+ artifactUnavailable: markArtifactUnavailable,+ cancelGeneration,+ clearGenerationError,+ generateWidget,+ loadStatus,+ loadVersions,+ openGenerationModal,+ openSourceModal,+ refreshData,+ runDataDependencies,+ setRuntimeError,+ } = useActions(logic)+ const { trustBuild } = useActions(trustLogic)++ if (statusLoading && !status) {+ return (+ <div className="flex h-full flex-col gap-3 p-3">+ <LemonSkeleton className="h-6 w-1/3" />+ <LemonSkeleton className="min-h-32 flex-1 w-full" />+ </div>+ )+ }+ if (statusLoadError && !status) {+ return (+ <EmptyState>+ <div className="flex flex-col items-center gap-3">+ <div>We couldn't load this widget's status.</div>+ <LemonButton onClick={loadStatus} loading={statusLoading}>+ Retry+ </LemonButton>+ </div>+ </EmptyState>+ )+ }++ const initialPrompt = prompt.trim()+ const selectedArtifactUrl =+ selectedVersionId === status?.current_version_id ? status?.artifact_url : selectedVersion?.artifact_url+ const selectedBuildHash =+ selectedVersionId === status?.current_version_id+ ? (status?.build_hash ?? null)+ : (selectedVersion?.build_hash ?? null)+ const selectedSecurityReview =+ selectedVersionId === status?.current_version_id+ ? (status?.security_review ?? null)+ : (selectedVersion?.security_review ?? null)+ const widgetTrust = getNotebookWidgetTrust({+ trustByUser,+ sessionBuildHashes,+ userId: user?.id ?? null,+ buildHash: selectedBuildHash,+ })+ const trustControls = (variant: 'gate' | 'toolbar'): JSX.Element => (+ <NotebookWidgetTrustControls+ buildHash={selectedBuildHash}+ isEditable={isEditable}+ securityReview={selectedSecurityReview}+ variant={variant}+ onRun={() => {+ if (selectedBuildHash) {+ trustBuild(user?.id ?? null, selectedBuildHash)+ }+ }}+ onViewSource={openSourceModal}+ />+ )+ if (artifactUnavailable && selectedArtifactUrl) {+ return (+ <>+ <EmptyState>+ <div className="flex flex-col items-center gap-3">+ <div>This widget's preview didn't load.</div>+ <div className="flex flex-wrap gap-2">+ <LemonButton onClick={refreshData} loading={dataRefreshInFlight}>+ Reload preview+ </LemonButton>+ <LemonButton onClick={openSourceModal}>View source</LemonButton>+ </div>+ </div>+ </EmptyState>+ {!componentPanelState?.showEditPanel ? <NotebookWidgetSourceModal {...logicProps} /> : null}+ </>+ )+ }++ if (selectedArtifactUrl && selectedVersionId && currentTeamId) {+ if (!widgetTrust.buildTrusted) {+ return (+ <>+ {trustControls('gate')}+ {!componentPanelState?.showEditPanel ? <NotebookWidgetSourceModal {...logicProps} /> : null}+ </>+ )+ }+ return (+ <>+ <div className="flex h-full min-h-0 w-full flex-col">+ {trustControls('toolbar')}+ {isWorking && workingStatus && !componentPanelState?.showEditPanel ? (+ <div className="flex flex-wrap items-center gap-2 border-b p-2 text-sm">+ <span className="flex items-center gap-2" role="status" aria-live="polite">+ <Spinner />+ <span>{workingStatus.label}</span>+ </span>+ <span className="font-mono tabular-nums" aria-hidden="true">+ {formatWidgetElapsed(elapsedSeconds)}+ </span>+ <span className="text-muted">{workingStatus.detail}</span>+ {isEditable ? (+ <LemonButton size="xsmall" onClick={cancelGeneration} loading={cancellationInFlight}>+ Cancel+ </LemonButton>+ ) : null}+ </div>+ ) : null}+ {generationError ||+ (!generationRequestLoading && status?.lifecycle_status === 'failed' && status.error_detail) ? (+ <LemonBanner+ type="error"+ className="m-2"+ onClose={generationError ? clearGenerationError : undefined}+ >+ {generationError || status?.error_detail}+ </LemonBanner>+ ) : null}+ {statusLoadError ? (+ <LemonBanner type="warning" className="m-2" action={{ children: 'Retry', onClick: loadStatus }}>+ The widget status couldn't be refreshed. The preview below is the last confirmed version.+ </LemonBanner>+ ) : null}+ {runtimeError ? (+ <LemonBanner+ type="warning"+ className="m-2"+ onClose={() => setRuntimeError(null)}+ action={+ isEditable+ ? {+ children: 'Run data cells',+ onClick: runDataDependencies,+ loading: dataRefreshInFlight,+ disabledReason: runDataDependenciesDisabledReason ?? undefined,+ 'data-attr': 'notebook-widget-runtime-run-data',+ }+ : undefined+ }+ >+ <span className="ph-no-capture">{runtimeError}</span>+ </LemonBanner>+ ) : null}+ <div className="relative min-h-0 flex-1" aria-busy={artifactLoading}>+ {artifactLoading ? (+ <div+ className="absolute inset-0 z-10 flex items-center justify-center gap-2 bg-primary text-secondary"+ role="status"+ aria-live="polite"+ >+ <Spinner />+ Loading widget…+ </div>+ ) : null}+ <WidgetArtifactFrame+ key={`${selectedBuildHash}-${frameRevision}`}+ artifactUrl={selectedArtifactUrl}+ title="Widget"+ allowedFrames={activeFrameNames}+ onReadFrame={(name, offset, limit, runId, signal) =>+ loadWidgetFrame(+ String(currentTeamId),+ notebookShortId,+ attributes.nodeId,+ selectedVersionId,+ name,+ offset,+ limit,+ runId,+ signal+ )+ }+ onArtifactUnavailable={markArtifactUnavailable}+ onError={(message) =>+ setRuntimeError(+ message ||+ 'The widget could not load its notebook data. Run its data cells and try again.'+ )+ }+ onRendered={() => {+ // A failed startup posts `error` before the load-driven `rendered`.+ // Clearing the error here would hide that warning. The reducer already+ // drops a stale error when a new document loads (refresh, generate, version switch).+ artifactAvailable()+ }}+ />+ </div>+ </div>+ {!componentPanelState?.showEditPanel ? <NotebookWidgetSourceModal {...logicProps} /> : null}+ </>+ )+ }++ if (isWorking) {+ if (componentPanelState?.showEditPanel) {+ return null+ }+ return (+ <EmptyState>+ <div className="flex max-w-lg flex-col items-center gap-3">+ <div className="flex items-center gap-2">+ <span className="flex items-center gap-2" role="status" aria-live="polite">+ <Spinner />+ <span>{workingStatus?.label}</span>+ </span>+ <span className="font-mono tabular-nums" aria-hidden="true">+ {formatWidgetElapsed(elapsedSeconds)}+ </span>+ </div>+ {workingStatus ? (+ <div className="flex flex-col gap-1 text-sm">+ <span>{workingStatus.detail}</span>+ <span className={workingStatus.isOverEstimate ? 'text-warning' : 'text-muted'}>+ {workingStatus.timing}+ </span>+ </div>+ ) : null}+ {generationError ? (+ <LemonBanner type="error" onClose={clearGenerationError}>+ {generationError}+ </LemonBanner>+ ) : null}+ {statusLoadError ? (+ <LemonBanner type="warning" action={{ children: 'Retry', onClick: loadStatus }}>+ The widget status couldn't be refreshed. The last confirmed generation state is shown.+ </LemonBanner>+ ) : null}+ {status?.active_job && isEditable ? (+ <LemonButton onClick={cancelGeneration} loading={cancellationInFlight}>+ Cancel+ </LemonButton>+ ) : null}+ </div>+ </EmptyState>+ )+ }++ if (generationRequestLoading) {+ return (+ <EmptyState>+ <div className="flex items-center gap-2" role="status" aria-live="polite">+ <Spinner />+ Starting widget generation…+ </div>+ </EmptyState>+ )+ }++ if (status?.lifecycle_status === 'failed' || generationError) {+ return (+ <>+ <EmptyState>+ <div className="flex flex-col items-center gap-3">+ <div>{status?.error_detail || generationError || 'The widget could not be generated.'}</div>+ {isEditable ? (+ status?.has_versions ? (+ <LemonButton type="primary" onClick={() => openGenerationModal('regenerate')}>+ Regenerate…+ </LemonButton>+ ) : (+ <LemonButton+ type="primary"+ onClick={() => generateWidget(initialPrompt, model, 'initial')}+ loading={generationRequestLoading}+ >+ Generate widget+ </LemonButton>+ )+ ) : (+ <div className="text-sm text-muted">+ Ask an editor to {status?.has_versions ? 'regenerate' : 'generate'} this widget.+ </div>+ )}+ </div>+ </EmptyState>+ {!componentPanelState?.showEditPanel ? <NotebookWidgetGenerationModal logicProps={logicProps} /> : null}+ </>+ )+ }++ if (status?.has_versions && versionsError && !versionsLoading && !selectedVersion) {+ return (+ <>+ <EmptyState>+ <div className="flex flex-col items-center gap-3">+ <div>We couldn't load this widget version.</div>+ <div className="flex flex-wrap gap-2">+ <LemonButton onClick={() => loadVersions(true)}>Retry</LemonButton>+ <LemonButton onClick={openSourceModal}>View source</LemonButton>+ </div>+ </div>+ </EmptyState>+ {!componentPanelState?.showEditPanel ? <NotebookWidgetSourceModal {...logicProps} /> : null}+ </>+ )+ }+ if (status?.has_versions && versionsLoading) {+ return (+ <EmptyState>+ <div className="flex items-center gap-2">+ <Spinner />+ Loading widget version…+ </div>+ </EmptyState>+ )+ }+ if (status?.has_versions) {+ return (+ <>+ <EmptyState>+ <div className="flex flex-col items-center gap-3">+ <div>+ {isEditable+ ? "This version's preview is no longer available. Its prompt and source remain in version history."+ : "This version's preview is no longer available. Ask an editor to restore or regenerate it."}+ </div>+ <LemonButton onClick={openSourceModal}>View source</LemonButton>+ </div>+ </EmptyState>+ {!componentPanelState?.showEditPanel ? <NotebookWidgetSourceModal {...logicProps} /> : null}+ </>+ )+ }+ return (+ <EmptyState>+ <div className="flex flex-col items-center gap-3">+ <div>This widget has not been generated yet.</div>+ {isEditable ? (+ <LemonButton+ type="primary"+ onClick={() => generateWidget(initialPrompt, model, 'initial')}+ loading={generationRequestLoading}+ >+ Generate widget+ </LemonButton>+ ) : (+ <div className="text-sm text-muted">Ask an editor to generate this widget.</div>+ )}+ </div>+ </EmptyState>+ )+}++export const NotebookNodeGeneratedWidget = createPostHogWidgetNode<NotebookNodeGeneratedWidgetAttributes>({+ nodeType: NotebookNodeType.GeneratedWidget,+ titlePlaceholder: 'Widget',+ Component,+ Settings: NotebookNodeGeneratedWidgetSettings,+ serializedText: () => 'Widget',+ heightEstimate: 420,+ minHeight: 180,+ resizeable: true,+ expandable: false,+ unmountWhenOutOfView: true,+ attributes: {+ prompt: { default: '' },+ model: { default: DEFAULT_WIDGET_MODEL },+ },+})diff --git a/products/notebooks/frontend/NotebookNodeGeneratedWidget/NotebookNodeGeneratedWidgetSettings.tsx b/products/notebooks/frontend/NotebookNodeGeneratedWidget/NotebookNodeGeneratedWidgetSettings.tsxnew file mode 100644index 000000000000..a30eee184b41--- /dev/null+++ b/products/notebooks/frontend/NotebookNodeGeneratedWidget/NotebookNodeGeneratedWidgetSettings.tsx@@ -0,0 +1,299 @@+import { useActions, useMountedLogic, useValues } from 'kea'++import { LemonBanner, LemonButton, LemonSelect, LemonTextArea } from '@posthog/lemon-ui'++import { wasNotebookNodeJustInserted } from 'lib/components/MarkdownNotebook/freshlyInserted'+import { LemonLabel } from 'lib/lemon-ui/LemonLabel'+import { LemonSkeleton } from 'lib/lemon-ui/LemonSkeleton'+import { Spinner } from 'lib/lemon-ui/Spinner'+import { humanFriendlyDetailedTime } from 'lib/utils/datetime'+import { notebookNodeLogic } from 'scenes/notebooks/Nodes/notebookNodeLogic'+import type { NotebookNodeAttributeProperties } from 'scenes/notebooks/types'+import { teamLogic } from 'scenes/teamLogic'++import type { NotebookNodeGeneratedWidgetAttributes } from './NotebookNodeGeneratedWidget'+import {+ formatWidgetElapsed,+ type NotebookNodeGeneratedWidgetLogicProps,+ notebookNodeGeneratedWidgetLogic,+ notebookNodeGeneratedWidgetSettingsLogic,+} from './notebookNodeGeneratedWidgetLogic'+import { NotebookWidgetGenerationModal } from './NotebookWidgetGenerationModal'+import { NotebookWidgetSourceModal } from './NotebookWidgetSourceModal'+import { DEFAULT_WIDGET_MODEL, DEFAULT_WIDGET_PROMPT, WIDGET_MODEL_OPTIONS } from './widgetModels'++export function NotebookNodeGeneratedWidgetSettings({+ attributes,+ updateAttributes,+}: NotebookNodeAttributeProperties<NotebookNodeGeneratedWidgetAttributes>): JSX.Element {+ const nodeLogic = useMountedLogic(notebookNodeLogic)+ const { isEditable, notebookLogic } = useValues(nodeLogic)+ const { currentTeamId } = useValues(teamLogic)+ const logicProps: NotebookNodeGeneratedWidgetLogicProps = {+ projectId: currentTeamId,+ notebookShortId: notebookLogic.props.shortId,+ nodeId: attributes.nodeId,+ prompt: attributes.prompt ?? '',+ model: attributes.model ?? DEFAULT_WIDGET_MODEL,+ isEditable,+ persistNotebook: async (): Promise<void> => {+ await notebookLogic.asyncActions.saveNotebook({+ content: notebookLogic.values.content,+ title: notebookLogic.values.title,+ })+ },+ getContent: () => notebookLogic.values.content ?? null,+ }+ useMountedLogic(notebookNodeGeneratedWidgetSettingsLogic(logicProps))+ const logic = notebookNodeGeneratedWidgetLogic(logicProps)+ const {+ cancellationInFlight,+ elapsedSeconds,+ generationError,+ generationRequestLoading,+ isWorking,+ dataRefreshInFlight,+ restoreInFlight,+ selectedVersion,+ selectedVersionId,+ status,+ statusLoadError,+ statusLoading,+ versions,+ versionsCount,+ versionsError,+ versionsLoading,+ versionsNextOffset,+ workingStatus,+ } = useValues(logic)+ const {+ cancelGeneration,+ clearGenerationError,+ generateWidget,+ loadMoreVersions,+ loadStatus,+ loadVersions,+ openGenerationModal,+ openSourceModal,+ refreshData,+ restoreSelectedVersion,+ selectVersion,+ } = useActions(logic)+ const promptId = `widget-prompt-${attributes.nodeId}`+ const modelId = `widget-model-${attributes.nodeId}`+ const versionId = `widget-version-${attributes.nodeId}`+ const hasVersions = Boolean(status?.has_versions)+ const isCurrentVersion = selectedVersionId === status?.current_version_id+ const initialPrompt = attributes.prompt ?? ''+ const visibleGenerationError =+ generationError || (!isWorking && !generationRequestLoading ? status?.error_detail : null)++ // A null status means the first status response has not arrived. Never show the initial+ // generation form here, or an editor could start a job on a widget that already has versions+ // (the backend turns that "initial" request into a regeneration). The node body guards the+ // same window; mirror it with a loading, then retry, state.+ if (!status) {+ if (statusLoadError) {+ return (+ <div className="flex flex-col items-start gap-3 p-3">+ <div className="text-sm">We couldn't load this widget's status.</div>+ <LemonButton onClick={loadStatus} loading={statusLoading}>+ Retry+ </LemonButton>+ </div>+ )+ }+ return (+ <div className="flex flex-col gap-3 p-3">+ <LemonSkeleton className="h-6 w-1/3" />+ <LemonSkeleton className="h-20 w-full" />+ </div>+ )+ }++ return (+ <div className="flex flex-col gap-3 p-3">+ {!hasVersions ? (+ <>+ <div>+ <LemonLabel htmlFor={promptId}>Instructions</LemonLabel>+ <LemonTextArea+ id={promptId}+ value={initialPrompt}+ onChange={(value) => updateAttributes({ prompt: value || undefined })}+ placeholder={DEFAULT_WIDGET_PROMPT}+ minRows={5}+ autoFocus={wasNotebookNodeJustInserted(attributes.nodeId)}+ disabled={!isEditable || isWorking}+ className="mt-1 ph-no-capture"+ />+ </div>+ <div className="text-xs text-muted">+ Run every SQL and Python cell before generating. The widget can use their latest completed+ results automatically.+ </div>+ <div>+ <LemonLabel htmlFor={modelId}>Model</LemonLabel>+ <LemonSelect+ id={modelId}+ value={attributes.model ?? DEFAULT_WIDGET_MODEL}+ options={WIDGET_MODEL_OPTIONS}+ onChange={(model) => updateAttributes({ model })}+ fullWidth+ disabled={!isEditable || isWorking}+ className="mt-1"+ data-attr="widget-model-select"+ />+ </div>+ </>+ ) : (+ <>+ <div>+ <LemonLabel htmlFor={versionId}>Version history</LemonLabel>+ <LemonSelect+ id={versionId}+ value={selectedVersionId ?? undefined}+ options={versions.map((version) => ({+ value: version.id,+ label: `Version ${version.version}${+ version.is_current ? ' (current)' : ''+ } · ${humanFriendlyDetailedTime(version.created_at)}`,+ }))}+ onChange={selectVersion}+ fullWidth+ loading={versionsLoading}+ className="mt-1"+ data-attr="widget-version-select"+ />+ <div className="mt-1 flex items-center justify-between text-xs text-muted">+ <span>+ {versions.length} of {versionsCount} versions loaded+ </span>+ {versionsNextOffset !== null ? (+ <LemonButton size="xsmall" onClick={loadMoreVersions} loading={versionsLoading}>+ Load older versions+ </LemonButton>+ ) : null}+ </div>+ {versionsError && !versionsLoading ? (+ <LemonBanner+ type="warning"+ className="mt-2"+ action={{ children: 'Retry', onClick: () => loadVersions(true) }}+ >+ Couldn't load version history.+ </LemonBanner>+ ) : null}+ </div>+ {selectedVersion ? (+ <div className="rounded border bg-surface-primary p-3">+ <div className="mb-1 text-xs font-semibold text-secondary">+ {selectedVersion.version_operation === 'improve'+ ? 'Change made'+ : 'Instructions for this version'}+ </div>+ <div className="ph-no-capture max-h-48 overflow-auto whitespace-pre-wrap text-sm">+ {selectedVersion.prompt_delta || 'No instructions were recorded for this version.'}+ </div>+ </div>+ ) : null}+ </>+ )}++ <div className="flex flex-wrap items-start gap-2">+ {isWorking && workingStatus ? (+ <>+ <div className="flex min-w-0 flex-1 flex-col gap-1">+ <div className="flex flex-wrap items-center gap-2 text-sm text-secondary">+ <span className="flex items-center gap-2" role="status" aria-live="polite">+ <Spinner />+ <span>{workingStatus.label}</span>+ </span>+ <span+ className="font-mono tabular-nums"+ aria-hidden="true"+ data-attr="widget-elapsed-time"+ >+ {formatWidgetElapsed(elapsedSeconds)}+ </span>+ </div>+ <span className="text-xs text-muted">{workingStatus.detail}</span>+ <span+ className={workingStatus.isOverEstimate ? 'text-xs text-warning' : 'text-xs text-muted'}+ >+ {workingStatus.timing}+ </span>+ </div>+ {status?.active_job && isEditable ? (+ <LemonButton onClick={cancelGeneration} loading={cancellationInFlight}>+ Cancel+ </LemonButton>+ ) : null}+ </>+ ) : hasVersions ? (+ <>+ {!isCurrentVersion && isEditable ? (+ <LemonButton onClick={restoreSelectedVersion} loading={restoreInFlight}>+ Restore as new version+ </LemonButton>+ ) : null}+ {isCurrentVersion && isEditable ? (+ <>+ <LemonButton+ type="primary"+ onClick={() => openGenerationModal('improve')}+ disabledReason={!selectedVersion ? 'Loading the widget version.' : undefined}+ >+ Improve…+ </LemonButton>+ <LemonButton+ onClick={() => openGenerationModal('regenerate')}+ disabledReason={!selectedVersion ? 'Loading the widget version.' : undefined}+ >+ Regenerate…+ </LemonButton>+ <LemonButton onClick={openSourceModal} data-attr="notebook-widget-view-source">+ View source+ </LemonButton>+ <LemonButton+ onClick={refreshData}+ disabledReason={dataRefreshInFlight ? 'Reloading preview.' : undefined}+ data-attr="notebook-widget-reload"+ >+ Reload preview+ </LemonButton>+ </>+ ) : null}+ {!isCurrentVersion && isEditable ? (+ <LemonButton+ onClick={() => openGenerationModal('regenerate')}+ disabledReason={!selectedVersion ? 'Loading the widget version.' : undefined}+ >+ Regenerate…+ </LemonButton>+ ) : null}+ </>+ ) : (+ <LemonButton+ type="primary"+ onClick={() =>+ generateWidget(initialPrompt, attributes.model ?? DEFAULT_WIDGET_MODEL, 'initial')+ }+ loading={generationRequestLoading}+ disabledReason={!isEditable ? 'You need edit access to generate a widget.' : undefined}+ >+ Generate widget+ </LemonButton>+ )}+ </div>+ {visibleGenerationError ? (+ <LemonBanner type="error" onClose={generationError ? clearGenerationError : undefined}>+ {visibleGenerationError}+ </LemonBanner>+ ) : null}++ <NotebookWidgetGenerationModal logicProps={logicProps} />+ <NotebookWidgetSourceModal {...logicProps} />+ </div>+ )+}diff --git a/products/notebooks/frontend/NotebookNodeGeneratedWidget/NotebookWidgetGenerationModal.tsx b/products/notebooks/frontend/NotebookNodeGeneratedWidget/NotebookWidgetGenerationModal.tsxnew file mode 100644index 000000000000..addf2780f950--- /dev/null+++ b/products/notebooks/frontend/NotebookNodeGeneratedWidget/NotebookWidgetGenerationModal.tsx@@ -0,0 +1,122 @@+import { useActions, useValues } from 'kea'++import { LemonBanner, LemonButton, LemonModal, LemonSelect, LemonTextArea } from '@posthog/lemon-ui'++import { LemonLabel } from 'lib/lemon-ui/LemonLabel'++import {+ type NotebookNodeGeneratedWidgetLogicProps,+ notebookNodeGeneratedWidgetLogic,+} from './notebookNodeGeneratedWidgetLogic'+import { MAX_WIDGET_EFFECTIVE_PROMPT_LENGTH, MAX_WIDGET_PROMPT_LENGTH, WIDGET_MODEL_OPTIONS } from './widgetModels'++export function NotebookWidgetGenerationModal({+ logicProps,+}: {+ logicProps: NotebookNodeGeneratedWidgetLogicProps+}): JSX.Element {+ const logic = notebookNodeGeneratedWidgetLogic(logicProps)+ const {+ generationDraftModel,+ generationDraftPrompt,+ generationError,+ generationModalOperation,+ generationRequestLoading,+ isWorking,+ selectedVersion,+ } = useValues(logic)+ const { closeGenerationModal, generateWidget, setGenerationDraftModel, setGenerationDraftPrompt } =+ useActions(logic)+ const promptId = `widget-change-prompt-${logicProps.nodeId}`+ const modelId = `widget-change-model-${logicProps.nodeId}`+ const isRegenerationVersionLoading = generationModalOperation === 'regenerate' && !selectedVersion+ const isImprovementVersionLoading = generationModalOperation === 'improve' && !selectedVersion+ const modalTitle = generationModalOperation === 'improve' ? 'Improve widget' : 'Regenerate widget'+ const modalDescription =+ generationModalOperation === 'improve'+ ? 'Describe one change. The generator will use the current widget as a starting point and create a new version.'+ : 'Edit the complete instructions below. This creates a new version from scratch and keeps existing versions.'+ const submitGenerationDraft = (prompt: string): void => {+ if (+ !generationModalOperation ||+ !prompt.trim() ||+ generationRequestLoading ||+ isWorking ||+ isRegenerationVersionLoading ||+ isImprovementVersionLoading+ ) {+ return+ }+ generateWidget(prompt, generationDraftModel, generationModalOperation, selectedVersion?.id)+ }++ return (+ <LemonModal+ isOpen={generationModalOperation !== null}+ onClose={closeGenerationModal}+ title={modalTitle}+ description={modalDescription}+ width={640}+ footer={+ <>+ <LemonButton onClick={closeGenerationModal}>Cancel</LemonButton>+ <LemonButton+ type="primary"+ onClick={() => submitGenerationDraft(generationDraftPrompt)}+ disabledReason={+ isRegenerationVersionLoading || isImprovementVersionLoading+ ? 'Loading the widget version.'+ : !generationDraftPrompt.trim()+ ? 'Add instructions first'+ : undefined+ }+ loading={generationRequestLoading}+ >+ {generationModalOperation === 'improve' ? 'Improve' : 'Regenerate'}+ </LemonButton>+ </>+ }+ >+ <div className="flex flex-col gap-4">+ <div>+ <LemonLabel htmlFor={promptId}>+ {generationModalOperation === 'improve' ? 'Change to make' : 'Full instructions'}+ </LemonLabel>+ <LemonTextArea+ id={promptId}+ value={generationDraftPrompt}+ onChange={setGenerationDraftPrompt}+ onPressCmdEnter={submitGenerationDraft}+ minRows={6}+ autoFocus+ disabled={isRegenerationVersionLoading || isImprovementVersionLoading}+ maxLength={+ generationModalOperation === 'regenerate'+ ? MAX_WIDGET_EFFECTIVE_PROMPT_LENGTH+ : MAX_WIDGET_PROMPT_LENGTH+ }+ className="mt-1 ph-no-capture"+ placeholder={+ generationModalOperation === 'improve'+ ? 'For example, make the colors lighter and increase the label contrast.'+ : 'Describe the complete widget.'+ }+ />+ </div>+ <div>+ <LemonLabel htmlFor={modelId}>Model</LemonLabel>+ <LemonSelect+ id={modelId}+ value={generationDraftModel}+ options={WIDGET_MODEL_OPTIONS}+ onChange={setGenerationDraftModel}+ disabled={isRegenerationVersionLoading || isImprovementVersionLoading}+ fullWidth+ className="mt-1"+ />+ </div>+ {generationError ? <LemonBanner type="error">{generationError}</LemonBanner> : null}+ </div>+ </LemonModal>+ )+}diff --git a/products/notebooks/frontend/NotebookNodeGeneratedWidget/NotebookWidgetSourceModal.tsx b/products/notebooks/frontend/NotebookNodeGeneratedWidget/NotebookWidgetSourceModal.tsxnew file mode 100644index 000000000000..718913bcda9c--- /dev/null+++ b/products/notebooks/frontend/NotebookNodeGeneratedWidget/NotebookWidgetSourceModal.tsx@@ -0,0 +1,100 @@+import { useActions, useValues } from 'kea'++import { LemonBanner, LemonButton, LemonModal, LemonTextArea } from '@posthog/lemon-ui'++import { LemonLabel } from 'lib/lemon-ui/LemonLabel'+import { LemonSkeleton } from 'lib/lemon-ui/LemonSkeleton'+import { CodeEditorResizeable } from 'lib/monaco/CodeEditorResizable'++import {+ type NotebookNodeGeneratedWidgetLogicProps,+ notebookNodeGeneratedWidgetLogic,+} from './notebookNodeGeneratedWidgetLogic'+import { MAX_WIDGET_PROMPT_LENGTH } from './widgetModels'++export function NotebookWidgetSourceModal(props: NotebookNodeGeneratedWidgetLogicProps): JSX.Element {+ const logic = notebookNodeGeneratedWidgetLogic(props)+ const {+ generationError,+ generationRequestLoading,+ source,+ sourceChangePrompt,+ sourceError,+ sourceImprovementDisabledReason,+ sourceLoading,+ sourceModalOpen,+ } = useValues(logic)+ const { closeSourceModal, improveSource, loadSource, setSourceChangePrompt } = useActions(logic)+ const promptId = `widget-source-change-${props.nodeId}`++ return (+ <LemonModal+ isOpen={sourceModalOpen}+ onClose={closeSourceModal}+ title="Widget source"+ width="70vw"+ footer={+ props.isEditable ? (+ <>+ <LemonButton onClick={closeSourceModal}>Cancel</LemonButton>+ <LemonButton+ type="primary"+ onClick={improveSource}+ disabledReason={sourceImprovementDisabledReason ?? undefined}+ loading={generationRequestLoading}+ data-attr="notebook-widget-build-source-changes"+ >+ Build changes+ </LemonButton>+ </>+ ) : (+ <LemonButton onClick={closeSourceModal}>Close</LemonButton>+ )+ }+ >+ <div className="flex flex-col gap-4">+ <div>+ <LemonLabel>Source</LemonLabel>+ {sourceLoading ? (+ <LemonSkeleton className="mt-1 h-80 w-full" />+ ) : sourceError ? (+ <LemonBanner+ type="error"+ className="mt-1"+ action={{ children: 'Try again', onClick: loadSource }}+ >+ {sourceError}+ </LemonBanner>+ ) : source !== null ? (+ <CodeEditorResizeable+ className="mt-1 ph-no-capture"+ language="typescript"+ value={source}+ minHeight="20rem"+ maxHeight="50vh"+ allowManualResize={false}+ options={{ readOnly: true, minimap: { enabled: false } }}+ />+ ) : null}+ </div>+ {props.isEditable ? (+ <div>+ <LemonLabel htmlFor={promptId}>What would you like to change?</LemonLabel>+ <LemonTextArea+ id={promptId}+ value={sourceChangePrompt}+ onChange={setSourceChangePrompt}+ onPressCmdEnter={improveSource}+ placeholder="Describe the changes you want."+ minRows={4}+ maxLength={MAX_WIDGET_PROMPT_LENGTH}+ autoFocus+ className="mt-1 ph-no-capture"+ />+ </div>+ ) : null}+ {props.isEditable && generationError ? <LemonBanner type="error">{generationError}</LemonBanner> : null}+ </div>+ </LemonModal>+ )+}diff --git a/products/notebooks/frontend/NotebookNodeGeneratedWidget/NotebookWidgetTrustControls.stories.tsx b/products/notebooks/frontend/NotebookNodeGeneratedWidget/NotebookWidgetTrustControls.stories.tsxindex 923f9bb59528..f965df48d40c 100644--- a/products/notebooks/frontend/NotebookNodeGeneratedWidget/NotebookWidgetTrustControls.stories.tsx+++ b/products/notebooks/frontend/NotebookNodeGeneratedWidget/NotebookWidgetTrustControls.stories.tsx@@ -9,6 +9,7 @@ const meta: Meta<NotebookWidgetTrustControlsProps> = {component: NotebookWidgetTrustControls,args: {buildHash: 'a'.repeat(64),+ isEditable: true,securityReview: {severity: 'high',summary: 'The widget may send notebook data to another window.',diff --git a/products/notebooks/frontend/NotebookNodeGeneratedWidget/NotebookWidgetTrustControls.tsx b/products/notebooks/frontend/NotebookNodeGeneratedWidget/NotebookWidgetTrustControls.tsxindex 873d6546d83b..78cb13e9a828 100644--- a/products/notebooks/frontend/NotebookNodeGeneratedWidget/NotebookWidgetTrustControls.tsx+++ b/products/notebooks/frontend/NotebookNodeGeneratedWidget/NotebookWidgetTrustControls.tsx@@ -4,6 +4,7 @@ import type { WidgetSecurityReviewApi } from 'products/notebooks/frontend/generaexport type NotebookWidgetTrustControlsProps = {buildHash: string | null+ isEditable: booleansecurityReview: WidgetSecurityReviewApi | nullvariant: 'gate' | 'toolbar'onRun: () => void@@ -11,7 +12,7 @@ export type NotebookWidgetTrustControlsProps = {}const SEVERITY_LABELS: Record<WidgetSecurityReviewApi['severity'], string> = {- none: 'No issues found',+ none: 'No potential issues flagged',low: 'Low',medium: 'Medium',high: 'High',@@ -30,6 +31,7 @@ function severityTagType(severity: WidgetSecurityReviewApi['severity']): LemonTaexport function NotebookWidgetTrustControls({buildHash,+ isEditable,securityReview,variant,onRun,@@ -38,10 +40,10 @@ export function NotebookWidgetTrustControls({const shortBuildHash = buildHash ? buildHash.slice(0, 12) : nullconst reviewTag = securityReview ? (<LemonTag type={severityTagType(securityReview.severity)}>- Security review: {SEVERITY_LABELS[securityReview.severity]}+ Automated review: {SEVERITY_LABELS[securityReview.severity]}</LemonTag>) : (- <LemonTag type="muted">Not reviewed</LemonTag>+ <LemonTag type="muted">Automated review unavailable</LemonTag>)if (variant === 'toolbar') {@@ -61,6 +63,7 @@ export function NotebookWidgetTrustControls({}const hasFindings = securityReview !== null && securityReview.severity !== 'none'+ const reviewPassed = securityReview?.severity === 'none'return (<div className="h-full min-h-48 overflow-auto p-4"><div className="mx-auto flex min-h-full max-w-2xl flex-col justify-center gap-3">@@ -68,14 +71,18 @@ export function NotebookWidgetTrustControls({<div className="text-base font-semibold">{hasFindings? 'Security review found potential issues'- : 'This widget has not been security reviewed'}+ : reviewPassed+ ? 'Review this widget before running it'+ : 'This widget has not been security reviewed'}</div>{reviewTag}</div><div className="text-secondary">{hasFindings? securityReview.summary- : 'This version was generated before automated reviews were available. View its source before deciding whether to run it.'}+ : reviewPassed+ ? 'The automated review flagged no potential issues, but automated reviews can miss issues. View the source before running this generated widget.'+ : 'This version was generated before automated reviews were available. View its source before deciding whether to run it.'}</div>{hasFindings ? (<ul className="m-0 flex list-disc flex-col gap-2 pl-5 text-left">@@ -96,7 +103,9 @@ export function NotebookWidgetTrustControls({<div className="font-mono text-xs text-muted">Build {shortBuildHash}</div>) : (<div className="text-warning">- This widget version can't be verified. Regenerate the widget before running it.+ {isEditable+ ? "This widget version can't be verified. Regenerate the widget before running it."+ : "This widget version can't be verified. Ask an editor to regenerate it before running it."}</div>)}<div className="flex flex-wrap gap-2">diff --git a/products/notebooks/frontend/NotebookNodeGeneratedWidget/notebookNodeGeneratedWidgetLogic.test.ts b/products/notebooks/frontend/NotebookNodeGeneratedWidget/notebookNodeGeneratedWidgetLogic.test.tsnew file mode 100644index 000000000000..b7131fab99ca--- /dev/null+++ b/products/notebooks/frontend/NotebookNodeGeneratedWidget/notebookNodeGeneratedWidgetLogic.test.ts@@ -0,0 +1,1179 @@+import { MOCK_TEAM_ID } from 'lib/api.mock'++import { expectLogic } from 'kea-test-utils'++import { ApiError } from 'lib/api-error'+import { JSONContent } from 'lib/components/RichContentEditor/types'+import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'+import { NotebookNodeType } from 'scenes/notebooks/types'++import { initKeaTests } from '~/test/init'++import {+ notebooksWidgetCancel,+ notebooksWidgetGenerate,+ notebooksWidgetRevert,+ notebooksWidgetSource,+ notebooksWidgetStatus,+ notebooksWidgetVersions,+} from 'products/notebooks/frontend/generated/api'+import type {+ WidgetStatusApi,+ WidgetVersionApi,+ WidgetVersionPageApi,+} from 'products/notebooks/frontend/generated/api.schemas'++import {+ formatWidgetElapsed,+ getWidgetDataDependencies,+ getWidgetWorkingStatus,+ notebookNodeGeneratedWidgetLogic,+} from './notebookNodeGeneratedWidgetLogic'+import { DEFAULT_WIDGET_PROMPT } from './widgetModels'++jest.mock('products/notebooks/frontend/generated/api', () => ({+ notebooksWidgetCancel: jest.fn(),+ notebooksWidgetFrame: jest.fn(),+ notebooksWidgetGenerate: jest.fn(),+ notebooksWidgetRevert: jest.fn(),+ notebooksWidgetSource: jest.fn(),+ notebooksWidgetStatus: jest.fn(),+ notebooksWidgetVersions: jest.fn(),+}))++function status(overrides: Partial<WidgetStatusApi> = {}): WidgetStatusApi {+ return {+ lifecycle_status: 'awaiting_generation',+ error_detail: null,+ artifact_url: null,+ frame_names: [],+ current_version_id: null,+ widget_id: null,+ instance_id: null,+ has_versions: false,+ active_job: null,+ security_review: null,+ build_hash: null,+ ...overrides,+ }+}++const emptyVersions: WidgetVersionPageApi = { results: [], count: 0, next_offset: null }++describe('notebookNodeGeneratedWidgetLogic', () => {+ const props = {+ projectId: MOCK_TEAM_ID,+ notebookShortId: 'notebook-1',+ nodeId: 'globe',+ prompt: 'Render a globe',+ model: 'claude-sonnet-4-6' as const,+ isEditable: true,+ persistNotebook: jest.fn(async () => undefined),+ getContent: jest.fn(() => null),+ }+ let logic: ReturnType<typeof notebookNodeGeneratedWidgetLogic.build>++ beforeEach(() => {+ initKeaTests()+ jest.mocked(notebooksWidgetCancel).mockReset()+ jest.mocked(notebooksWidgetGenerate).mockReset()+ jest.mocked(notebooksWidgetRevert).mockReset()+ jest.mocked(notebooksWidgetSource).mockReset()+ jest.mocked(notebooksWidgetStatus).mockReset()+ jest.mocked(notebooksWidgetVersions).mockReset().mockResolvedValue(emptyVersions)+ props.persistNotebook.mockClear()+ })++ afterEach(() => {+ logic?.unmount()+ jest.restoreAllMocks()+ jest.useRealTimers()+ })++ it('loads status without generating on mount', async () => {+ jest.mocked(notebooksWidgetStatus).mockResolvedValue(status())+ logic = notebookNodeGeneratedWidgetLogic(props)+ logic.mount()+ await expectLogic(logic).toFinishAllListeners()++ expect(notebooksWidgetStatus).toHaveBeenCalledWith(+ String(MOCK_TEAM_ID),+ 'notebook-1',+ 'globe',+ expect.objectContaining({ signal: expect.anything() })+ )+ expect(notebooksWidgetGenerate).not.toHaveBeenCalled()+ })++ it('times out a status request instead of leaving the widget loading forever', async () => {+ jest.useFakeTimers()+ jest.mocked(notebooksWidgetStatus).mockImplementation(+ (_projectId, _shortId, _nodeId, options) =>+ new Promise((_resolve, reject) => {+ options?.signal?.addEventListener('abort', () => reject(options.signal?.reason), { once: true })+ })+ )+ logic = notebookNodeGeneratedWidgetLogic(props)+ logic.mount()++ await jest.advanceTimersByTimeAsync(30_000)+ await expectLogic(logic).toFinishAllListeners()++ expect(logic.values.statusLoadError).toBe('The widget request timed out.')+ expect(logic.values.statusLoading).toBe(false)+ })++ it('aborts outstanding widget requests when the node unmounts', async () => {+ let requestSignal: AbortSignal | undefined+ jest.mocked(notebooksWidgetStatus).mockImplementation(+ (_projectId, _shortId, _nodeId, options) =>+ new Promise((_resolve, reject) => {+ requestSignal = options?.signal ?? undefined+ requestSignal?.addEventListener('abort', () => reject(requestSignal?.reason), { once: true })+ })+ )+ logic = notebookNodeGeneratedWidgetLogic(props)+ logic.mount()++ logic.unmount()+ await Promise.resolve()++ expect(requestSignal?.aborted).toBe(true)+ })++ it('ignores an aborted mutation request after the node unmounts', async () => {+ jest.mocked(notebooksWidgetStatus).mockResolvedValue(status())+ jest.mocked(notebooksWidgetGenerate).mockImplementation(+ (_projectId, _shortId, _nodeId, _body, options) =>+ new Promise((_resolve, reject) => {+ options?.signal?.addEventListener('abort', () => reject(options?.signal?.reason), { once: true })+ })+ )+ logic = notebookNodeGeneratedWidgetLogic(props)+ logic.mount()+ await expectLogic(logic).toFinishAllListeners()+ const statusCallsBeforeUnmount = jest.mocked(notebooksWidgetStatus).mock.calls.length++ logic.actions.generateWidget('Render a globe', 'claude-sonnet-4-6', 'regenerate')+ await expectLogic(logic).toDispatchActions(['generationRequestStarted'])++ logic.unmount()+ await new Promise((resolve) => setTimeout(resolve, 0))++ // The unmount abort must not open a recovery status read on a logic that is going away.+ expect(jest.mocked(notebooksWidgetStatus).mock.calls.length).toBe(statusCallsBeforeUnmount)+ })++ it.each(['../other-widget', 'folder/widget', 'widget?status', 'widget#status'])(+ 'rejects the unsafe widget identifier %s before making a request',+ async (nodeId) => {+ logic = notebookNodeGeneratedWidgetLogic({ ...props, nodeId })+ logic.mount()+ await expectLogic(logic).toFinishAllListeners()++ expect(notebooksWidgetStatus).not.toHaveBeenCalled()+ expect(logic.values.statusLoadError).toBe('This widget has an invalid identifier.')+ }+ )++ it('loads version history when requested', async () => {+ const version: WidgetVersionApi = {+ id: '00000000-0000-0000-0000-000000000002',+ parent_version_id: null,+ version: 1,+ version_operation: 'initial',+ prompt_delta: 'Render a globe',+ effective_prompt: 'Render a globe',+ model: 'claude-sonnet-4-6',+ created_at: '2026-08-26T12:00:00Z',+ build_status: 'ready',+ artifact_url: 'https://example.com/widget.html',+ frame_names: [],+ is_current: true,+ security_review: null,+ build_hash: 'a'.repeat(64),+ }+ jest.mocked(notebooksWidgetStatus).mockResolvedValue(+ status({+ lifecycle_status: 'ready',+ artifact_url: version.artifact_url,+ current_version_id: version.id,+ has_versions: true,+ })+ )+ jest.mocked(notebooksWidgetVersions).mockResolvedValue({+ results: [version],+ count: 1,+ next_offset: null,+ })+ logic = notebookNodeGeneratedWidgetLogic(props)+ logic.mount()+ await expectLogic(logic).toFinishAllListeners()+ expect(notebooksWidgetVersions).not.toHaveBeenCalled()++ logic.actions.loadVersions(true)+ await expectLogic(logic).toFinishAllListeners()++ expect(notebooksWidgetVersions).toHaveBeenCalledWith(+ String(MOCK_TEAM_ID),+ 'notebook-1',+ 'globe',+ { offset: 0, limit: 25 },+ expect.objectContaining({ signal: expect.anything() })+ )+ expect(logic.values.versions).toEqual([version])+ expect(logic.values.versionsCount).toBe(1)+ expect(logic.values.versionsLoading).toBe(false)+ })++ it('loads version history when the first version appears mid-generation', async () => {+ const firstVersion: WidgetVersionApi = {+ id: '00000000-0000-0000-0000-000000000002',+ parent_version_id: null,+ version: 1,+ version_operation: 'initial',+ prompt_delta: 'Render a globe',+ effective_prompt: 'Render a globe',+ model: 'claude-sonnet-4-6',+ created_at: '2026-08-26T12:00:00Z',+ build_status: 'ready',+ artifact_url: 'https://example.com/widget.html',+ frame_names: [],+ is_current: true,+ security_review: null,+ build_hash: 'a'.repeat(64),+ }+ // The first status carries no version, matching a settings panel opened before generation.+ jest.mocked(notebooksWidgetStatus).mockResolvedValue(status())+ jest.mocked(notebooksWidgetVersions).mockResolvedValue({ results: [firstVersion], count: 1, next_offset: null })+ logic = notebookNodeGeneratedWidgetLogic(props)+ logic.mount()+ await expectLogic(logic).toFinishAllListeners()+ expect(notebooksWidgetVersions).not.toHaveBeenCalled()++ logic.actions.statusReceived(+ status({+ lifecycle_status: 'ready',+ artifact_url: firstVersion.artifact_url,+ current_version_id: firstVersion.id,+ has_versions: true,+ })+ )+ await expectLogic(logic).toFinishAllListeners()++ expect(notebooksWidgetVersions).toHaveBeenCalledTimes(1)+ expect(logic.values.versions).toEqual([firstVersion])+ expect(logic.values.selectedVersion?.id).toBe(firstVersion.id)+ })++ it('ignores repeated status polls and reloads explicit resets during an in-flight request', async () => {+ const initialVersion: WidgetVersionApi = {+ id: '00000000-0000-0000-0000-000000000002',+ parent_version_id: null,+ version: 1,+ version_operation: 'initial',+ prompt_delta: 'Render a globe',+ effective_prompt: 'Render a globe',+ model: 'claude-sonnet-4-6',+ created_at: '2026-08-26T12:00:00Z',+ build_status: 'ready',+ artifact_url: 'https://example.com/widget-v1.html',+ frame_names: [],+ is_current: true,+ security_review: null,+ build_hash: 'b'.repeat(64),+ }+ const currentVersion: WidgetVersionApi = {+ ...initialVersion,+ id: '00000000-0000-0000-0000-000000000003',+ version: 2,+ artifact_url: 'https://example.com/widget-v2.html',+ }+ let resolveInitialRequest: (page: WidgetVersionPageApi) => void = () => undefined+ let resolveResetRequest: (page: WidgetVersionPageApi) => void = () => undefined+ const readyStatus = status({+ lifecycle_status: 'ready',+ artifact_url: initialVersion.artifact_url,+ current_version_id: initialVersion.id,+ has_versions: true,+ })+ jest.mocked(notebooksWidgetStatus).mockResolvedValue(readyStatus)+ jest.mocked(notebooksWidgetVersions)+ .mockImplementationOnce(+ () =>+ new Promise((resolve) => {+ resolveInitialRequest = resolve+ })+ )+ .mockImplementationOnce(+ () =>+ new Promise((resolve) => {+ resolveResetRequest = resolve+ })+ )+ .mockResolvedValueOnce({ results: [currentVersion], count: 1, next_offset: null })+ logic = notebookNodeGeneratedWidgetLogic(props)+ logic.mount()+ await expectLogic(logic).toDispatchActions(['statusReceived'])++ expect(notebooksWidgetVersions).not.toHaveBeenCalled()+ logic.actions.loadVersions(true)++ logic.actions.statusReceived(readyStatus)+ resolveInitialRequest({ results: [initialVersion], count: 1, next_offset: null })+ await expectLogic(logic).toFinishAllListeners()++ expect(notebooksWidgetVersions).toHaveBeenCalledTimes(1)+ expect(logic.values.versions).toEqual([initialVersion])++ logic.actions.loadVersions(true)+ logic.actions.loadVersions(true)+ resolveResetRequest({ results: [initialVersion], count: 1, next_offset: null })+ await expectLogic(logic).toFinishAllListeners()++ expect(notebooksWidgetVersions).toHaveBeenCalledTimes(3)+ expect(logic.values.versions).toEqual([currentVersion])+ })++ it('refreshes the signed preview URL before reloading the frame', async () => {+ let resolveReload: (status: WidgetStatusApi) => void = () => undefined+ jest.mocked(notebooksWidgetStatus)+ .mockResolvedValueOnce(+ status({ lifecycle_status: 'ready', artifact_url: 'https://example.com/widget-old.html' })+ )+ .mockImplementationOnce(+ () =>+ new Promise((resolve) => {+ resolveReload = resolve+ })+ )+ logic = notebookNodeGeneratedWidgetLogic(props)+ logic.mount()+ await expectLogic(logic).toFinishAllListeners()++ logic.actions.refreshData()+ expect(logic.values.dataRefreshInFlight).toBe(true)+ resolveReload(status({ lifecycle_status: 'ready', artifact_url: 'https://example.com/widget-new.html' }))+ await expectLogic(logic).toFinishAllListeners()++ expect(logic.values.status?.artifact_url).toBe('https://example.com/widget-new.html')+ expect(logic.values.frameRevision).toBe(1)+ expect(logic.values.dataRefreshInFlight).toBe(false)+ })++ it('reloads the preview when a newer status request supersedes the refresh', async () => {+ let resolveRefresh: (status: WidgetStatusApi) => void = () => undefined+ jest.mocked(notebooksWidgetStatus)+ .mockResolvedValueOnce(+ status({ lifecycle_status: 'ready', artifact_url: 'https://example.com/widget-old.html' })+ )+ .mockImplementationOnce(+ () =>+ new Promise((resolve) => {+ resolveRefresh = resolve+ })+ )+ .mockResolvedValueOnce(+ status({ lifecycle_status: 'ready', artifact_url: 'https://example.com/widget-current.html' })+ )+ logic = notebookNodeGeneratedWidgetLogic(props)+ logic.mount()+ await expectLogic(logic).toFinishAllListeners()++ logic.actions.refreshData()+ logic.actions.loadStatus()+ resolveRefresh(status({ lifecycle_status: 'ready', artifact_url: 'https://example.com/widget-old.html' }))+ await expectLogic(logic).toFinishAllListeners()++ expect(logic.values.status?.artifact_url).toBe('https://example.com/widget-current.html')+ expect(logic.values.frameRevision).toBe(1)+ expect(logic.values.dataRefreshInFlight).toBe(false)+ })++ it('reloads the preview when a status poll fails while widget data cells are running', async () => {+ jest.mocked(notebooksWidgetStatus)+ .mockResolvedValueOnce(+ status({ lifecycle_status: 'ready', artifact_url: 'https://example.com/widget-old.html' })+ )+ .mockRejectedValueOnce(new Error('Temporary status failure'))+ .mockResolvedValueOnce(+ status({ lifecycle_status: 'ready', artifact_url: 'https://example.com/widget-new.html' })+ )+ logic = notebookNodeGeneratedWidgetLogic(props)+ logic.mount()+ await expectLogic(logic).toFinishAllListeners()++ logic.actions.dataRefreshStarted()+ logic.actions.loadStatus()+ await expectLogic(logic).toFinishAllListeners()+ expect(logic.values.dataRefreshInFlight).toBe(true)++ logic.actions.widgetDataChainFinished([])+ await expectLogic(logic).toFinishAllListeners()++ expect(logic.values.status?.artifact_url).toBe('https://example.com/widget-new.html')+ expect(logic.values.frameRevision).toBe(1)+ expect(logic.values.dataRefreshInFlight).toBe(false)+ })++ it('keeps a widget-specific error when a connected data cell fails', async () => {+ jest.mocked(notebooksWidgetStatus).mockResolvedValue(status())+ logic = notebookNodeGeneratedWidgetLogic(props)+ logic.mount()+ await expectLogic(logic).toFinishAllListeners()++ logic.actions.dataRefreshStarted()+ await expectLogic(logic).toFinishAllListeners()+ logic.actions.abortChain('source-cell')+ await expectLogic(logic).toFinishAllListeners()++ expect(logic.values.dataRefreshInFlight).toBe(false)+ expect(logic.values.runtimeError).toContain('source-cell')+ expect(logic.values.runtimeError).toContain('run the widget data cells again')+ })++ it('refreshes a selected historical version before reloading the frame', async () => {+ const currentVersionId = '00000000-0000-0000-0000-000000000003'+ const historicalVersion: WidgetVersionApi = {+ id: '00000000-0000-0000-0000-000000000002',+ parent_version_id: null,+ version: 1,+ version_operation: 'initial',+ prompt_delta: 'Render a globe',+ effective_prompt: 'Render a globe',+ model: 'claude-sonnet-4-6',+ created_at: '2026-08-26T12:00:00Z',+ build_status: 'ready',+ artifact_url: 'https://example.com/widget-old.html',+ frame_names: [],+ is_current: false,+ security_review: null,+ build_hash: 'c'.repeat(64),+ }+ const readyStatus = status({+ lifecycle_status: 'ready',+ artifact_url: 'https://example.com/widget-current.html',+ current_version_id: currentVersionId,+ has_versions: true,+ })+ jest.mocked(notebooksWidgetStatus).mockResolvedValue(readyStatus)+ jest.mocked(notebooksWidgetVersions)+ .mockResolvedValueOnce({ results: [historicalVersion], count: 1, next_offset: null })+ .mockResolvedValueOnce({+ results: [{ ...historicalVersion, artifact_url: 'https://example.com/widget-new.html' }],+ count: 1,+ next_offset: null,+ })+ logic = notebookNodeGeneratedWidgetLogic(props)+ logic.mount()+ await expectLogic(logic).toFinishAllListeners()+ logic.actions.loadVersions(true)+ await expectLogic(logic).toFinishAllListeners()+ logic.actions.selectVersion(historicalVersion.id)++ logic.actions.refreshData()+ await expectLogic(logic).toFinishAllListeners()++ expect(notebooksWidgetVersions).toHaveBeenLastCalledWith(+ String(MOCK_TEAM_ID),+ 'notebook-1',+ 'globe',+ { offset: 0, limit: 25 },+ expect.objectContaining({ signal: expect.anything() })+ )+ expect(logic.values.selectedVersion?.artifact_url).toBe('https://example.com/widget-new.html')+ expect(logic.values.frameRevision).toBe(1)+ })++ it('keeps the last ready version selected while a replacement builds', async () => {+ const previousVersion: WidgetVersionApi = {+ id: '00000000-0000-0000-0000-000000000002',+ parent_version_id: null,+ version: 1,+ version_operation: 'initial',+ prompt_delta: 'Render a globe',+ effective_prompt: 'Render a globe',+ model: 'claude-sonnet-4-6',+ created_at: '2026-08-26T12:00:00Z',+ build_status: 'ready',+ artifact_url: 'https://example.com/widget-v1.html',+ frame_names: [],+ is_current: true,+ security_review: null,+ build_hash: 'd'.repeat(64),+ }+ const nextVersionId = '00000000-0000-0000-0000-000000000003'+ jest.mocked(notebooksWidgetStatus).mockResolvedValue(+ status({+ lifecycle_status: 'ready',+ artifact_url: previousVersion.artifact_url,+ current_version_id: previousVersion.id,+ has_versions: true,+ })+ )+ jest.mocked(notebooksWidgetVersions).mockResolvedValue({+ results: [previousVersion],+ count: 1,+ next_offset: null,+ })+ logic = notebookNodeGeneratedWidgetLogic(props)+ logic.mount()+ await expectLogic(logic).toFinishAllListeners()+ logic.actions.loadVersions(true)+ await expectLogic(logic).toFinishAllListeners()++ logic.actions.statusReceived(+ status({ lifecycle_status: 'building', current_version_id: nextVersionId, has_versions: true })+ )+ expect(logic.values.selectedVersionId).toBe(previousVersion.id)++ logic.actions.statusReceived(+ status({+ lifecycle_status: 'ready',+ artifact_url: 'https://example.com/widget-v2.html',+ current_version_id: nextVersionId,+ has_versions: true,+ })+ )+ expect(logic.values.selectedVersionId).toBe(nextVersionId)+ })++ it('refreshes version history when a replacement build fails', async () => {+ const previousVersion: WidgetVersionApi = {+ id: '00000000-0000-0000-0000-000000000002',+ parent_version_id: null,+ version: 1,+ version_operation: 'initial',+ prompt_delta: 'Render a globe',+ effective_prompt: 'Render a globe',+ model: 'claude-sonnet-4-6',+ created_at: '2026-08-26T12:00:00Z',+ build_status: 'ready',+ artifact_url: 'https://example.com/widget-v1.html',+ frame_names: [],+ is_current: true,+ security_review: null,+ build_hash: 'e'.repeat(64),+ }+ const failedVersion: WidgetVersionApi = {+ ...previousVersion,+ id: '00000000-0000-0000-0000-000000000003',+ parent_version_id: previousVersion.id,+ version: 2,+ version_operation: 'improve',+ prompt_delta: 'Add labels',+ effective_prompt: 'Render a globe\n\nAdd labels',+ build_status: 'failed',+ artifact_url: null,+ is_current: true,+ }+ jest.mocked(notebooksWidgetStatus).mockResolvedValue(+ status({+ lifecycle_status: 'ready',+ artifact_url: previousVersion.artifact_url,+ current_version_id: previousVersion.id,+ has_versions: true,+ })+ )+ jest.mocked(notebooksWidgetVersions)+ .mockResolvedValueOnce({ results: [previousVersion], count: 1, next_offset: null })+ .mockResolvedValueOnce({+ results: [failedVersion, { ...previousVersion, is_current: false }],+ count: 2,+ next_offset: null,+ })+ logic = notebookNodeGeneratedWidgetLogic(props)+ logic.mount()+ await expectLogic(logic).toFinishAllListeners()++ logic.actions.loadVersions(true)+ await expectLogic(logic).toFinishAllListeners()+ logic.actions.statusReceived(+ status({+ lifecycle_status: 'failed',+ artifact_url: null,+ current_version_id: failedVersion.id,+ has_versions: true,+ })+ )+ await expectLogic(logic).toFinishAllListeners()++ expect(logic.values.versions[0].id).toBe(failedVersion.id)+ expect(logic.values.selectedVersionId).toBe(previousVersion.id)+ })++ it('keeps status errors separate from paid generation', async () => {+ jest.mocked(notebooksWidgetStatus).mockRejectedValue(new Error('offline'))+ logic = notebookNodeGeneratedWidgetLogic(props)+ logic.mount()+ await expectLogic(logic).toFinishAllListeners()++ expect(logic.values.statusLoadError).toBe('offline')+ expect(logic.values.generationError).toBeNull()+ expect(notebooksWidgetGenerate).not.toHaveBeenCalled()+ })++ it.each([+ ['provided instructions', 'Render a globe', 'Render a globe'],+ ['an empty new-widget prompt', '', DEFAULT_WIDGET_PROMPT],+ ])('submits %s once and follows the durable queued job', async (_label, prompt, expectedPrompt) => {+ const queued = status({+ lifecycle_status: 'generating',+ active_job: {+ id: '00000000-0000-0000-0000-000000000001',+ status: 'queued',+ phase: 'queued',+ model: 'claude-sonnet-4-6',+ created_at: '2026-08-26T12:00:00Z',+ started_at: null,+ },+ })+ jest.mocked(notebooksWidgetStatus).mockResolvedValue(status())+ jest.mocked(notebooksWidgetGenerate).mockResolvedValue(queued)+ logic = notebookNodeGeneratedWidgetLogic(props)+ logic.mount()+ await expectLogic(logic).toFinishAllListeners()++ logic.actions.generateWidget(prompt, 'claude-sonnet-4-6', 'initial')+ await expectLogic(logic).toFinishAllListeners()++ expect(notebooksWidgetGenerate).toHaveBeenCalledTimes(1)+ expect(notebooksWidgetGenerate).toHaveBeenCalledWith(+ String(MOCK_TEAM_ID),+ 'notebook-1',+ 'globe',+ expect.objectContaining({+ prompt: expectedPrompt,+ generation_id: expect.any(String),+ model: 'claude-sonnet-4-6',+ generation_operation: 'initial',+ }),+ expect.objectContaining({ signal: expect.anything() })+ )+ expect(logic.values.status?.active_job?.status).toBe('queued')+ expect(logic.values.generationRequestLoading).toBe(false)+ expect(logic.values.isWorking).toBe(true)+ })++ it('does not let an older status request overwrite a newly queued generation', async () => {+ const queued = status({+ lifecycle_status: 'generating',+ active_job: {+ id: '00000000-0000-0000-0000-000000000001',+ status: 'queued',+ phase: 'queued',+ model: 'claude-sonnet-4-6',+ created_at: '2026-08-26T12:00:00Z',+ started_at: null,+ },+ })+ let resolveOldStatus: (value: WidgetStatusApi) => void = () => undefined+ jest.mocked(notebooksWidgetStatus)+ .mockResolvedValueOnce(status())+ .mockImplementationOnce(+ () =>+ new Promise((resolve) => {+ resolveOldStatus = resolve+ })+ )+ jest.mocked(notebooksWidgetGenerate).mockResolvedValue(queued)+ logic = notebookNodeGeneratedWidgetLogic(props)+ logic.mount()+ await expectLogic(logic).toFinishAllListeners()++ logic.actions.loadStatus()+ await expectLogic(logic, () =>+ logic.actions.generateWidget('Render a globe', 'claude-sonnet-4-6', 'initial')+ ).toDispatchActions(['generationRequestStarted', 'statusReceived', 'generationRequestFinished'])++ expect(logic.values.status?.active_job?.status).toBe('queued')+ resolveOldStatus(status({ lifecycle_status: 'ready', artifact_url: 'https://example.com/stale.html' }))+ await expectLogic(logic).toFinishAllListeners()++ expect(logic.values.status?.active_job?.status).toBe('queued')+ expect(logic.values.isWorking).toBe(true)+ })++ it('finds the data producer and its transitive dependencies without unrelated cells', () => {+ const content: JSONContent = {+ type: 'doc',+ content: [+ {+ type: NotebookNodeType.SQLV2,+ attrs: { nodeId: 'source', returnVariable: 'sql_df', code: 'select 1' },+ },+ {+ type: NotebookNodeType.PythonV2,+ attrs: {+ nodeId: 'transform',+ returnVariable: 'locations_df',+ code: 'locations_df = sql_df.copy()',+ },+ },+ {+ type: NotebookNodeType.SQLV2,+ attrs: { nodeId: 'unrelated', returnVariable: 'other_df', code: 'select 2' },+ },+ ],+ }++ expect(getWidgetDataDependencies(content, ['locations_df'])).toEqual({+ missingFrameNames: [],+ nodeIds: ['source', 'transform'],+ })+ })++ it('does not run a partial data chain when a widget frame has no matching cell', async () => {+ const content: JSONContent = {+ type: 'doc',+ content: [+ {+ type: NotebookNodeType.SQLV2,+ attrs: { nodeId: 'source', returnVariable: 'available_df', code: 'select 1' },+ },+ ],+ }+ jest.mocked(notebooksWidgetStatus).mockResolvedValue(+ status({ lifecycle_status: 'ready', frame_names: ['available_df', 'missing_df'], has_versions: true })+ )+ logic = notebookNodeGeneratedWidgetLogic({ ...props, getContent: () => content })+ logic.mount()+ await expectLogic(logic).toFinishAllListeners()++ const toastError = jest.spyOn(lemonToast, 'error').mockReturnValue('toast-id')+ logic.actions.runDataDependencies()+ await expectLogic(logic).toFinishAllListeners()++ expect(logic.values.runtimeError).toContain('notebook data that is no longer available')+ // The banner is unmounted when the widget is collapsed, so the failure must also toast.+ expect(toastError).toHaveBeenCalledWith(expect.stringContaining('notebook data that is no longer available'))+ expect(logic.values.dataRefreshInFlight).toBe(false)+ })++ it('loads the selected version source and queues an improvement from it', async () => {+ const versionId = '00000000-0000-0000-0000-000000000009'+ jest.mocked(notebooksWidgetStatus).mockResolvedValue(+ status({ lifecycle_status: 'ready', current_version_id: versionId, has_versions: true })+ )+ jest.mocked(notebooksWidgetVersions).mockResolvedValue({+ results: [+ {+ id: versionId,+ parent_version_id: null,+ version: 1,+ version_operation: 'initial',+ prompt_delta: 'Render a globe',+ effective_prompt: 'Render a globe',+ model: 'claude-sonnet-4-6',+ created_at: '2026-08-26T12:00:00Z',+ build_status: 'ready',+ artifact_url: null,+ frame_names: [],+ is_current: true,+ security_review: null,+ build_hash: null,+ },+ ],+ count: 1,+ next_offset: null,+ })+ jest.mocked(notebooksWidgetSource).mockResolvedValue({ source: 'export default function Widget() {}' })+ jest.mocked(notebooksWidgetGenerate).mockResolvedValue(status({ lifecycle_status: 'generating' }))+ logic = notebookNodeGeneratedWidgetLogic(props)+ logic.mount()+ await expectLogic(logic).toFinishAllListeners()++ logic.actions.openSourceModal()+ await expectLogic(logic).toFinishAllListeners()++ expect(notebooksWidgetStatus).toHaveBeenCalledTimes(2)+ expect(notebooksWidgetSource).toHaveBeenCalledWith(+ String(MOCK_TEAM_ID),+ 'notebook-1',+ 'globe',+ { version_id: versionId },+ expect.objectContaining({ signal: expect.anything() })+ )+ expect(logic.values.source).toBe('export default function Widget() {}')+ expect(logic.values.sourceModalOpen).toBe(true)++ logic.actions.setSourceChangePrompt('Use a darker background')+ logic.actions.improveSource()+ await expectLogic(logic).toFinishAllListeners()++ expect(notebooksWidgetGenerate).toHaveBeenCalledWith(+ String(MOCK_TEAM_ID),+ 'notebook-1',+ 'globe',+ expect.objectContaining({+ prompt: 'Use a darker background',+ generation_operation: 'improve',+ expected_current_version_id: versionId,+ }),+ expect.objectContaining({ signal: expect.anything() })+ )+ expect(logic.values.sourceModalOpen).toBe(false)+ })++ it('waits for immutable version metadata before improving source', async () => {+ const versionId = '00000000-0000-0000-0000-000000000009'+ jest.mocked(notebooksWidgetStatus).mockResolvedValue(+ status({ lifecycle_status: 'ready', current_version_id: versionId, has_versions: true })+ )+ jest.mocked(notebooksWidgetSource).mockResolvedValue({ source: 'export default function Widget() {}' })+ logic = notebookNodeGeneratedWidgetLogic(props)+ logic.mount()+ await expectLogic(logic).toFinishAllListeners()++ logic.actions.openSourceModal()+ await expectLogic(logic).toFinishAllListeners()+ logic.actions.setSourceChangePrompt('Use a darker background')+ logic.actions.improveSource()+ await expectLogic(logic).toFinishAllListeners()++ expect(logic.values.sourceImprovementDisabledReason).toBe('Loading the widget version.')+ expect(notebooksWidgetGenerate).not.toHaveBeenCalled()+ })++ it('does not improve a historical version as though it were current', async () => {+ const currentVersionId = '00000000-0000-0000-0000-000000000009'+ const historicalVersionId = '00000000-0000-0000-0000-000000000008'+ jest.mocked(notebooksWidgetStatus).mockResolvedValue(+ status({ lifecycle_status: 'ready', current_version_id: currentVersionId, has_versions: true })+ )+ jest.mocked(notebooksWidgetVersions).mockResolvedValue({ results: [], count: 0, next_offset: null })+ jest.mocked(notebooksWidgetSource).mockResolvedValue({ source: 'export default function Widget() {}' })+ logic = notebookNodeGeneratedWidgetLogic(props)+ logic.mount()+ await expectLogic(logic).toFinishAllListeners()++ logic.actions.selectVersion(historicalVersionId)+ logic.actions.openSourceModal()+ await expectLogic(logic).toFinishAllListeners()+ logic.actions.setSourceChangePrompt('Use a darker background')+ logic.actions.improveSource()+ await expectLogic(logic).toFinishAllListeners()++ expect(logic.values.sourceImprovementDisabledReason).toBe('Restore this version before building changes.')+ expect(notebooksWidgetGenerate).not.toHaveBeenCalled()+ })++ it('keeps source responses bound to the selected version', async () => {+ const firstVersionId = '00000000-0000-0000-0000-000000000008'+ const secondVersionId = '00000000-0000-0000-0000-000000000009'+ let resolveFirstSource: (value: { source: string }) => void = () => undefined+ let resolveSecondSource: (value: { source: string }) => void = () => undefined+ jest.mocked(notebooksWidgetStatus).mockResolvedValue(+ status({ lifecycle_status: 'ready', current_version_id: firstVersionId })+ )+ jest.mocked(notebooksWidgetSource)+ .mockImplementationOnce(+ () =>+ new Promise((resolve) => {+ resolveFirstSource = resolve+ })+ )+ .mockImplementationOnce(+ () =>+ new Promise((resolve) => {+ resolveSecondSource = resolve+ })+ )+ logic = notebookNodeGeneratedWidgetLogic(props)+ logic.mount()+ await expectLogic(logic).toFinishAllListeners()++ logic.actions.openSourceModal()+ logic.actions.closeSourceModal()+ logic.actions.statusReceived(status({ lifecycle_status: 'ready', current_version_id: secondVersionId }))+ logic.actions.selectVersion(secondVersionId)+ logic.actions.openSourceModal()++ await expectLogic(logic, () => resolveSecondSource({ source: 'source for version two' })).toDispatchActions([+ 'sourceReceived',+ ])+ expect(logic.values.source).toBe('source for version two')+ expect(logic.values.sourceVersionId).toBe(secondVersionId)++ resolveFirstSource({ source: 'source for version one' })+ await expectLogic(logic).toFinishAllListeners()++ expect(logic.values.source).toBe('source for version two')+ expect(logic.values.sourceVersionId).toBe(secondVersionId)+ })++ it('persists an older Markdown widget and retries with the same generation identifier', async () => {+ const queued = status({+ lifecycle_status: 'generating',+ active_job: {+ id: '00000000-0000-0000-0000-000000000001',+ status: 'queued',+ phase: 'queued',+ model: 'claude-sonnet-4-6',+ created_at: '2026-08-26T12:00:00Z',+ started_at: null,+ },+ })+ jest.mocked(notebooksWidgetStatus).mockResolvedValue(status())+ jest.mocked(notebooksWidgetGenerate)+ .mockRejectedValueOnce(+ new ApiError('Not found', 404, undefined, {+ code: 'node_not_found',+ detail: 'This generated widget is no longer in the notebook.',+ })+ )+ .mockResolvedValueOnce(queued)+ logic = notebookNodeGeneratedWidgetLogic(props)+ logic.mount()+ await expectLogic(logic).toFinishAllListeners()++ logic.actions.generateWidget('Render a globe', 'claude-sonnet-4-6', 'initial')+ await expectLogic(logic).toFinishAllListeners()++ expect(props.persistNotebook).toHaveBeenCalledTimes(1)+ expect(notebooksWidgetGenerate).toHaveBeenCalledTimes(2)+ expect(jest.mocked(notebooksWidgetGenerate).mock.calls[1][3].generation_id).toBe(+ jest.mocked(notebooksWidgetGenerate).mock.calls[0][3].generation_id+ )+ expect(logic.values.status?.active_job?.status).toBe('queued')+ })++ it('recovers a durable generation when its response is lost', async () => {+ jest.mocked(notebooksWidgetStatus).mockImplementation(async () => {+ const generationId = jest.mocked(notebooksWidgetGenerate).mock.calls[0]?.[3].generation_id+ return generationId+ ? status({+ lifecycle_status: 'generating',+ active_job: {+ id: generationId,+ status: 'queued',+ phase: 'queued',+ model: 'claude-sonnet-4-6',+ created_at: '2026-08-26T12:00:00Z',+ started_at: null,+ },+ })+ : status()+ })+ jest.mocked(notebooksWidgetGenerate).mockRejectedValue(new Error('Connection closed'))+ logic = notebookNodeGeneratedWidgetLogic(props)+ logic.mount()+ await expectLogic(logic).toFinishAllListeners()++ logic.actions.generateWidget('Render a globe', 'claude-sonnet-4-6', 'initial')+ await expectLogic(logic).toFinishAllListeners()++ expect(logic.values.status?.active_job?.status).toBe('queued')+ expect(logic.values.generationError).toBeNull()+ expect(logic.values.isWorking).toBe(true)+ })++ it('does not mistake a concurrent version change for a recovered generation', async () => {+ jest.mocked(notebooksWidgetStatus).mockResolvedValue(status())+ jest.mocked(notebooksWidgetGenerate).mockRejectedValue(+ new ApiError('Another generation won the race.', 409, undefined, {+ detail: 'Another generation won the race.',+ })+ )+ logic = notebookNodeGeneratedWidgetLogic(props)+ logic.mount()+ await expectLogic(logic).toFinishAllListeners()++ logic.actions.generateWidget('Render a globe', 'claude-sonnet-4-6', 'initial')+ await expectLogic(logic).toFinishAllListeners()++ expect(notebooksWidgetStatus).toHaveBeenCalledTimes(1)+ expect(logic.values.generationError).toBe('Another generation won the race.')+ expect(logic.values.isWorking).toBe(false)+ })++ it('surfaces field-level generation errors', async () => {+ jest.mocked(notebooksWidgetStatus).mockResolvedValue(status())+ jest.mocked(notebooksWidgetGenerate).mockRejectedValue(+ new ApiError('Invalid request', 400, undefined, {+ prompt: ['Keep widget instructions to 20,000 characters or fewer.'],+ })+ )+ logic = notebookNodeGeneratedWidgetLogic(props)+ logic.mount()+ await expectLogic(logic).toFinishAllListeners()++ logic.actions.generateWidget('Render a globe', 'claude-sonnet-4-6', 'initial')+ await expectLogic(logic).toFinishAllListeners()++ expect(logic.values.generationError).toBe('Keep widget instructions to 20,000 characters or fewer.')+ })++ it('refreshes status without claiming a restore succeeded when its response is lost', async () => {+ const currentVersionId = '00000000-0000-0000-0000-000000000010'+ const historicalVersionId = '00000000-0000-0000-0000-000000000009'+ const restoredVersionId = '00000000-0000-0000-0000-000000000011'+ const initialStatus = status({+ lifecycle_status: 'ready',+ current_version_id: currentVersionId,+ has_versions: true,+ })+ const restoredStatus = status({+ lifecycle_status: 'ready',+ artifact_url: 'https://example.com/restored.html',+ current_version_id: restoredVersionId,+ has_versions: true,+ })+ jest.mocked(notebooksWidgetStatus)+ .mockResolvedValueOnce(initialStatus)+ .mockResolvedValueOnce(restoredStatus)+ .mockResolvedValue(restoredStatus)+ jest.mocked(notebooksWidgetRevert).mockRejectedValue(new Error('Connection closed'))+ logic = notebookNodeGeneratedWidgetLogic(props)+ logic.mount()+ await expectLogic(logic).toFinishAllListeners()++ logic.actions.selectVersion(historicalVersionId)+ logic.actions.restoreSelectedVersion()+ await expectLogic(logic).toFinishAllListeners()++ expect(logic.values.status?.current_version_id).toBe(restoredVersionId)+ expect(logic.values.selectedVersionId).toBe(restoredVersionId)+ expect(logic.values.restoreInFlight).toBe(false)+ expect(logic.values.generationError).toBe('Connection closed')+ })++ it("does not mistake another editor's version for a recovered restore", async () => {+ const currentVersionId = '00000000-0000-0000-0000-000000000010'+ const historicalVersionId = '00000000-0000-0000-0000-000000000009'+ jest.mocked(notebooksWidgetStatus).mockResolvedValue(+ status({+ lifecycle_status: 'ready',+ current_version_id: currentVersionId,+ has_versions: true,+ })+ )+ jest.mocked(notebooksWidgetRevert).mockRejectedValue(+ new ApiError('The current version changed.', 409, undefined, {+ detail: 'The current version changed.',+ })+ )+ logic = notebookNodeGeneratedWidgetLogic(props)+ logic.mount()+ await expectLogic(logic).toFinishAllListeners()++ logic.actions.selectVersion(historicalVersionId)+ logic.actions.restoreSelectedVersion()+ await expectLogic(logic).toFinishAllListeners()++ expect(notebooksWidgetStatus).toHaveBeenCalledTimes(1)+ expect(logic.values.status?.current_version_id).toBe(currentVersionId)+ expect(logic.values.selectedVersionId).toBe(historicalVersionId)+ expect(logic.values.generationError).toBe('The current version changed.')+ expect(logic.values.restoreInFlight).toBe(false)++ logic.actions.statusReceived(+ status({ lifecycle_status: 'ready', current_version_id: currentVersionId, has_versions: true })+ )+ expect(logic.values.generationError).toBeNull()+ })++ it('cancels the shared durable job from its status identifier', async () => {+ const active = status({+ lifecycle_status: 'generating',+ active_job: {+ id: '00000000-0000-0000-0000-000000000001',+ status: 'generating',+ phase: 'generating',+ model: 'claude-sonnet-4-6',+ created_at: '2026-08-26T12:00:00Z',+ started_at: '2026-08-26T12:00:01Z',+ },+ })+ jest.mocked(notebooksWidgetStatus).mockResolvedValue(active)+ jest.mocked(notebooksWidgetCancel).mockResolvedValue(undefined)+ logic = notebookNodeGeneratedWidgetLogic(props)+ logic.mount()+ await expectLogic(logic).toFinishAllListeners()++ logic.actions.cancelGeneration()+ await expectLogic(logic).toFinishAllListeners()++ expect(notebooksWidgetCancel).toHaveBeenCalledWith(+ String(MOCK_TEAM_ID),+ 'notebook-1',+ 'globe',+ { generation_id: active.active_job?.id },+ expect.objectContaining({ signal: expect.anything() })+ )+ })++ it('does not cancel generation from a read-only widget', async () => {+ jest.mocked(notebooksWidgetStatus).mockResolvedValue(+ status({+ lifecycle_status: 'generating',+ active_job: {+ id: '00000000-0000-0000-0000-000000000001',+ status: 'generating',+ phase: 'generating',+ model: 'claude-sonnet-4-6',+ created_at: '2026-08-26T12:00:00Z',+ started_at: '2026-08-26T12:00:01Z',+ },+ })+ )+ logic = notebookNodeGeneratedWidgetLogic({ ...props, isEditable: false })+ logic.mount()+ await expectLogic(logic).toFinishAllListeners()++ logic.actions.cancelGeneration()+ await expectLogic(logic).toFinishAllListeners()++ expect(notebooksWidgetCancel).not.toHaveBeenCalled()+ })++ it('formats elapsed generation time', () => {+ expect(formatWidgetElapsed(65)).toBe('01:05')+ })++ it('shows the security review phase after source generation', () => {+ expect(+ getWidgetWorkingStatus({+ elapsedSeconds: 30,+ hasVersions: false,+ model: 'claude-sonnet-4-6',+ phase: 'reviewing_source',+ })+ ).toEqual({+ detail: 'Checking the generated source for security issues.',+ isOverEstimate: false,+ label: 'Reviewing widget security…',+ timing: 'This usually takes less than a minute.',+ })+ })++ it('keeps the elapsed clock running when generation hands off to publishing', async () => {+ jest.mocked(notebooksWidgetStatus).mockResolvedValue(status())+ logic = notebookNodeGeneratedWidgetLogic(props)+ logic.mount()+ await expectLogic(logic).toFinishAllListeners()+ jest.useFakeTimers()+ jest.setSystemTime(new Date('2026-08-26T12:00:05Z'))++ logic.actions.statusReceived(+ status({+ lifecycle_status: 'generating',+ active_job: {+ id: '00000000-0000-0000-0000-000000000001',+ status: 'generating',+ phase: 'generating_source',+ model: 'claude-sonnet-4-6',+ created_at: '2026-08-26T12:00:00Z',+ started_at: '2026-08-26T12:00:00Z',+ },+ })+ )+ expect(logic.values.elapsedSeconds).toBe(5)++ logic.actions.statusReceived(status({ lifecycle_status: 'building', has_versions: true }))+ jest.advanceTimersByTime(1_000)++ expect(logic.values.elapsedSeconds).toBe(6)+ expect(logic.values.workingStatus?.label).toBe('Publishing widget…')+ })+})diff --git a/products/notebooks/frontend/NotebookNodeGeneratedWidget/notebookNodeGeneratedWidgetLogic.ts b/products/notebooks/frontend/NotebookNodeGeneratedWidget/notebookNodeGeneratedWidgetLogic.tsnew file mode 100644index 000000000000..dcc5d03e6394--- /dev/null+++ b/products/notebooks/frontend/NotebookNodeGeneratedWidget/notebookNodeGeneratedWidgetLogic.ts@@ -0,0 +1,1375 @@+import {+ LogicWrapper,+ MakeLogicType,+ actions,+ afterMount,+ beforeUnmount,+ connect,+ kea,+ key,+ listeners,+ path,+ props,+ reducers,+ selectors,+} from 'kea'+import posthog from 'posthog-js'+import { v4 as uuidv4 } from 'uuid'++import { ApiError, isAbortError } from 'lib/api'+import { JSONContent } from 'lib/components/RichContentEditor/types'+import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'+import {+ buildNotebookDependencyGraph,+ collectDependencyNodeIds,+ collectNotebookFrameNodes,+} from 'scenes/notebooks/Nodes/notebookNodeContent'+import { notebookNodeStalenessLogic } from 'scenes/notebooks/Notebook/notebookNodeStalenessLogic'+import { notebookOperationsLogic } from 'scenes/notebooks/Notebook/notebookOperationsLogic'+import { NotebookNodeType } from 'scenes/notebooks/types'++import {+ notebooksWidgetCancel,+ notebooksWidgetFrame,+ notebooksWidgetGenerate,+ notebooksWidgetRevert,+ notebooksWidgetSource,+ notebooksWidgetStatus,+ notebooksWidgetVersions,+} from 'products/notebooks/frontend/generated/api'+import type {+ WidgetFrameApi,+ WidgetStatusApi,+ WidgetVersionApi,+} from 'products/notebooks/frontend/generated/api.schemas'++import {+ DEFAULT_WIDGET_MODEL,+ DEFAULT_WIDGET_PROMPT,+ MAX_WIDGET_EFFECTIVE_PROMPT_LENGTH,+ MAX_WIDGET_PROMPT_LENGTH,+ WIDGET_MODEL_INFO,+ isWidgetModel,+ type WidgetModel,+} from './widgetModels'++const STATUS_POLL_INTERVAL_MS = 2_000+const STATUS_POLL_MAX_INTERVAL_MS = 30_000+const WIDGET_REQUEST_TIMEOUT_MS = 30_000+const VERSION_PAGE_SIZE = 25+const SAFE_WIDGET_NODE_ID = /^[A-Za-z0-9_-]{1,128}$/++export type WidgetGenerationOperation = 'initial' | 'regenerate' | 'improve'+export type WidgetGenerationModalOperation = Exclude<WidgetGenerationOperation, 'initial'> | null++export type WidgetWorkingStatus = {+ detail: string+ isOverEstimate: boolean+ label: string+ timing: string+}++export type NotebookNodeGeneratedWidgetLogicProps = {+ projectId: number | null+ notebookShortId: string+ nodeId: string+ prompt: string+ model: WidgetModel+ isEditable: boolean+ persistNotebook: () => Promise<void>+ getContent: () => JSONContent | null+}++export interface notebookNodeGeneratedWidgetLogicValues {+ activeGenerationModel: WidgetModel+ artifactLoading: boolean+ activeFrameNames: string[]+ artifactUnavailable: boolean+ cancellationInFlight: boolean+ dataRefreshInFlight: boolean+ elapsedSeconds: number+ frameRevision: number+ generationDraftModel: WidgetModel+ generationDraftPrompt: string+ generationError: string | null+ generationModalOperation: WidgetGenerationModalOperation+ generationRequestLoading: boolean+ isDataChainRunning: boolean+ isWorking: boolean+ notebookIsBusy: boolean+ restoreInFlight: boolean+ runDataDependenciesDisabledReason: string | null+ runtimeError: string | null+ selectedVersion: WidgetVersionApi | null+ selectedVersionId: string | null+ status: WidgetStatusApi | null+ statusLoadError: string | null+ statusLoading: boolean+ source: string | null+ sourceChangePrompt: string+ sourceError: string | null+ sourceLoading: boolean+ sourceModalOpen: boolean+ sourceImprovementDisabledReason: string | null+ sourceVersionId: string | null+ versions: WidgetVersionApi[]+ versionsCount: number+ versionsError: string | null+ versionsLoading: boolean+ versionsNextOffset: number | null+ workingStatus: WidgetWorkingStatus | null+}++export interface notebookNodeGeneratedWidgetLogicActions {+ artifactAvailable: () => { value: true }+ artifactRefreshReady: () => { value: true }+ artifactUnavailable: () => { value: true }+ abortChain: (reason: string | null) => { reason: string | null }+ cancelGeneration: () => { value: true }+ cancellationFailed: (error: string) => { error: string }+ cancellationStarted: () => { value: true }+ clearGenerationError: () => { value: true }+ closeGenerationModal: () => { value: true }+ closeSourceModal: () => { value: true }+ dataRefreshFinished: () => { value: true }+ dataRefreshStarted: () => { value: true }+ generateWidget: (+ prompt: string,+ model: WidgetModel,+ operation: WidgetGenerationOperation,+ expectedCurrentVersionId?: string+ ) => {+ prompt: string+ model: WidgetModel+ operation: WidgetGenerationOperation+ expectedCurrentVersionId?: string+ }+ generationCanceled: () => { value: true }+ generationFailed: (error: string) => { error: string }+ generationRequestFinished: () => { value: true }+ generationRequestStarted: () => { value: true }+ improveSource: () => { value: true }+ loadMoreVersions: () => { value: true }+ loadSource: () => { value: true }+ loadStatus: () => { value: true }+ loadVersions: (reset: boolean) => { reset: boolean }+ openGenerationModal: (operation: Exclude<WidgetGenerationOperation, 'initial'>) => {+ operation: 'regenerate' | 'improve'+ }+ openSourceModal: () => { value: true }+ refreshData: () => { value: true }+ runDataDependencies: () => { value: true }+ runWidgetDataChain: (+ content: JSONContent | null,+ nodeIds: string[]+ ) => {+ content: JSONContent | null+ nodeIds: string[]+ }+ restoreFailed: (error: string) => { error: string }+ restoreSelectedVersion: () => { value: true }+ restoreStarted: () => { value: true }+ selectVersion: (versionId: string) => { versionId: string }+ setGenerationDraftModel: (model: WidgetModel) => { model: WidgetModel }+ setGenerationDraftPrompt: (prompt: string) => { prompt: string }+ setRuntimeError: (error: string | null) => { error: string | null }+ setSourceChangePrompt: (prompt: string) => { prompt: string }+ sourceFailed: (error: string) => { error: string }+ sourceReceived: (source: string, versionId: string | null) => { source: string; versionId: string | null }+ statusFailed: (error: string) => { error: string }+ statusReceived: (status: WidgetStatusApi) => { status: WidgetStatusApi }+ statusRequestFinished: () => { value: true }+ statusRequestStarted: () => { value: true }+ tickElapsed: (elapsedSeconds: number) => { elapsedSeconds: number }+ versionRefreshed: (version: WidgetVersionApi) => { version: WidgetVersionApi }+ versionsFailed: (error: string) => { error: string }+ versionsReceived: (+ versions: WidgetVersionApi[],+ count: number,+ nextOffset: number | null,+ reset: boolean+ ) => { versions: WidgetVersionApi[]; count: number; nextOffset: number | null; reset: boolean }+ widgetDataChainFinished: (nodeIds: string[]) => { nodeIds: string[] }+}++export interface notebookNodeGeneratedWidgetLogicMeta {+ key: string+}++export type notebookNodeGeneratedWidgetLogicType = MakeLogicType<+ notebookNodeGeneratedWidgetLogicValues,+ notebookNodeGeneratedWidgetLogicActions,+ NotebookNodeGeneratedWidgetLogicProps,+ notebookNodeGeneratedWidgetLogicMeta+>++interface notebookNodeGeneratedWidgetSettingsLogicActions {+ loadVersions: (reset: boolean) => { reset: boolean }+}++interface notebookNodeGeneratedWidgetSettingsLogicMeta {+ key: string+}++type notebookNodeGeneratedWidgetSettingsLogicType = MakeLogicType<+ {},+ notebookNodeGeneratedWidgetSettingsLogicActions,+ NotebookNodeGeneratedWidgetLogicProps,+ notebookNodeGeneratedWidgetSettingsLogicMeta+>++function errorMessage(error: unknown): string {+ if (error instanceof ApiError) {+ const response = error.data as Record<string, unknown> | undefined+ if (typeof response?.detail === 'string') {+ return response.detail+ }+ const fieldError = Object.values(response ?? {}).find(+ (value): value is string[] => Array.isArray(value) && typeof value[0] === 'string'+ )+ if (fieldError) {+ return fieldError[0]+ }+ }+ return error instanceof Error ? error.message : 'The widget request failed.'+}++function isMissingNodeError(error: unknown): boolean {+ if (error instanceof ApiError) {+ const response = error.data as { code?: unknown } | undefined+ return error.code === 'node_not_found' || response?.code === 'node_not_found'+ }+ return false+}++function isAmbiguousMutationError(error: unknown): boolean {+ return !(error instanceof ApiError) || error.status === undefined || error.status >= 500+}++function shouldPoll(status: WidgetStatusApi | null): boolean {+ return (+ Boolean(status?.active_job) ||+ status?.lifecycle_status === 'generating' ||+ status?.lifecycle_status === 'building'+ )+}++export function isSafeWidgetNodeId(nodeId: string): boolean {+ return SAFE_WIDGET_NODE_ID.test(nodeId)+}++export function getWidgetDataDependencies(+ content: JSONContent | null,+ frameNames: string[]+): { missingFrameNames: string[]; nodeIds: string[] } {+ if (!content || !frameNames.length) {+ return { missingFrameNames: [], nodeIds: [] }+ }+ const graph = buildNotebookDependencyGraph(content)+ const frameNodes = collectNotebookFrameNodes(content)+ const owners = new Map<string, string>()+ for (const nodeType of ['sql', 'python'] as const) {+ for (const node of frameNodes) {+ if (node.nodeType === nodeType && node.nodeId && !owners.has(node.name)) {+ owners.set(node.name, node.nodeId)+ }+ }+ }+ const connectedNodeIds = new Set<string>()+ const missingFrameNames: string[] = []+ for (const frameName of frameNames) {+ const ownerNodeId = owners.get(frameName)+ if (!ownerNodeId) {+ missingFrameNames.push(frameName)+ continue+ }+ for (const nodeId of collectDependencyNodeIds(graph, ownerNodeId, 'upstream')) {+ connectedNodeIds.add(nodeId)+ }+ }+ return {+ missingFrameNames,+ nodeIds: graph.nodes+ .filter(+ (node) =>+ connectedNodeIds.has(node.nodeId) &&+ (node.nodeType === NotebookNodeType.SQLV2 || node.nodeType === NotebookNodeType.PythonV2)+ )+ .map((node) => node.nodeId),+ }+}++export function formatWidgetElapsed(elapsedSeconds: number): string {+ const minutes = Math.floor(elapsedSeconds / 60)+ const seconds = elapsedSeconds % 60+ return `${String(minutes).padStart(2, '0')}:${String(seconds).padStart(2, '0')}`+}++export function getWidgetWorkingStatus({+ elapsedSeconds,+ hasVersions,+ model,+ phase,+}: {+ elapsedSeconds: number+ hasVersions: boolean+ model: WidgetModel+ phase: string+}): WidgetWorkingStatus {+ if (phase === 'queued') {+ return {+ detail: 'Waiting for generation capacity. You can leave this page and come back later.',+ isOverEstimate: false,+ label: hasVersions ? 'Queued to regenerate widget…' : 'Queued to generate widget…',+ timing: 'Timing starts when generation begins.',+ }+ }+ if (phase.startsWith('reviewing')) {+ return {+ detail: 'Checking the generated source for security issues.',+ isOverEstimate: false,+ label: 'Reviewing widget security…',+ timing: 'This usually takes less than a minute.',+ }+ }+ if (phase.startsWith('publishing')) {+ return {+ detail: 'Preparing the interactive preview.',+ isOverEstimate: false,+ label: 'Publishing widget…',+ timing: 'The preview build usually takes less than a minute.',+ }+ }+ const modelInfo = WIDGET_MODEL_INFO[model]+ const secondsFromEstimate = elapsedSeconds - modelInfo.estimatedSeconds+ const isOverEstimate = secondsFromEstimate > 0+ return {+ detail: `${modelInfo.name} is writing the widget source. You can leave this page and come back later.`,+ isOverEstimate,+ label: hasVersions ? 'Regenerating widget…' : 'Generating widget…',+ timing: isOverEstimate+ ? `Typical: ${modelInfo.estimateLabel} · ${formatWidgetElapsed(secondsFromEstimate)} longer than usual. Generation is still in progress.`+ : `Typical: ${modelInfo.estimateLabel} · Estimated remaining: ${formatWidgetElapsed(+ modelInfo.estimatedSeconds - elapsedSeconds+ )}`,+ }+}++export async function loadWidgetFrame(+ projectId: string,+ notebookShortId: string,+ nodeId: string,+ versionId: string,+ frameName: string,+ offset: number,+ limit: number,+ runId: string | undefined,+ signal: AbortSignal+): Promise<WidgetFrameApi> {+ if (!isSafeWidgetNodeId(nodeId)) {+ throw new Error('This widget has an invalid identifier.')+ }+ return await notebooksWidgetFrame(+ projectId,+ notebookShortId,+ nodeId,+ frameName,+ {+ version_id: versionId,+ run_id: runId,+ offset,+ limit,+ },+ { signal }+ )+}++export const notebookNodeGeneratedWidgetLogic: LogicWrapper<notebookNodeGeneratedWidgetLogicType> =+ kea<notebookNodeGeneratedWidgetLogicType>([+ props({} as NotebookNodeGeneratedWidgetLogicProps),+ key((props) => `${props.projectId}-${props.notebookShortId}-${props.nodeId}`),+ path((key) => ['products', 'notebooks', 'notebookNodeGeneratedWidgetLogic', key]),+ connect((props: NotebookNodeGeneratedWidgetLogicProps) => ({+ values: [+ notebookNodeStalenessLogic({ shortId: props.notebookShortId }),+ ['isChainRunning as isDataChainRunning'],+ notebookOperationsLogic({ shortId: props.notebookShortId }),+ ['isBusy as notebookIsBusy'],+ ],+ actions: [+ notebookNodeStalenessLogic({ shortId: props.notebookShortId }),+ ['abortChain', 'runWidgetDataChain', 'widgetDataChainFinished'],+ ],+ })),+ actions({+ artifactAvailable: true,+ artifactRefreshReady: true,+ artifactUnavailable: true,+ cancelGeneration: true,+ cancellationFailed: (error: string) => ({ error }),+ cancellationStarted: true,+ clearGenerationError: true,+ closeGenerationModal: true,+ closeSourceModal: true,+ dataRefreshFinished: true,+ dataRefreshStarted: true,+ generateWidget: (+ prompt: string,+ model: WidgetModel,+ operation: WidgetGenerationOperation,+ expectedCurrentVersionId?: string+ ) => ({+ prompt,+ model,+ operation,+ expectedCurrentVersionId,+ }),+ generationCanceled: true,+ generationFailed: (error: string) => ({ error }),+ generationRequestFinished: true,+ generationRequestStarted: true,+ improveSource: true,+ loadMoreVersions: true,+ loadSource: true,+ loadStatus: true,+ loadVersions: (reset: boolean) => ({ reset }),+ openGenerationModal: (operation: Exclude<WidgetGenerationOperation, 'initial'>) => ({ operation }),+ openSourceModal: true,+ refreshData: true,+ runDataDependencies: true,+ restoreFailed: (error: string) => ({ error }),+ restoreSelectedVersion: true,+ restoreStarted: true,+ selectVersion: (versionId: string) => ({ versionId }),+ setGenerationDraftModel: (model: WidgetModel) => ({ model }),+ setGenerationDraftPrompt: (prompt: string) => ({ prompt }),+ setRuntimeError: (error: string | null) => ({ error }),+ setSourceChangePrompt: (prompt: string) => ({ prompt }),+ sourceFailed: (error: string) => ({ error }),+ sourceReceived: (source: string, versionId: string | null) => ({ source, versionId }),+ statusFailed: (error: string) => ({ error }),+ statusReceived: (status: WidgetStatusApi) => ({ status }),+ statusRequestFinished: true,+ statusRequestStarted: true,+ tickElapsed: (elapsedSeconds: number) => ({ elapsedSeconds }),+ versionsFailed: (error: string) => ({ error }),+ versionRefreshed: (version: WidgetVersionApi) => ({ version }),+ versionsReceived: (+ versions: WidgetVersionApi[],+ count: number,+ nextOffset: number | null,+ reset: boolean+ ) => ({ versions, count, nextOffset, reset }),+ }),+ reducers(({ props }) => ({+ activeGenerationModel: [+ props.model,+ {+ generateWidget: (_, { model }) => model,+ statusReceived: (activeModel, { status }) =>+ isWidgetModel(status.active_job?.model) ? status.active_job.model : activeModel,+ },+ ],+ artifactUnavailable: [+ false,+ {+ artifactAvailable: () => false,+ artifactRefreshReady: () => false,+ artifactUnavailable: () => true,+ generateWidget: () => false,+ selectVersion: () => false,+ statusReceived: (unavailable, { status }) => (status.artifact_url ? false : unavailable),+ },+ ],+ artifactLoading: [+ true,+ {+ artifactAvailable: () => false,+ artifactRefreshReady: () => true,+ artifactUnavailable: () => false,+ selectVersion: () => true,+ },+ ],+ cancellationInFlight: [+ false,+ {+ cancellationStarted: () => true,+ cancellationFailed: () => false,+ generationCanceled: () => false,+ },+ ],+ elapsedSeconds: [0, { tickElapsed: (_, { elapsedSeconds }) => elapsedSeconds }],+ frameRevision: [+ 0,+ {+ artifactRefreshReady: (revision) => revision + 1,+ },+ ],+ generationDraftModel: [DEFAULT_WIDGET_MODEL, { setGenerationDraftModel: (_, { model }) => model }],+ generationDraftPrompt: ['', { setGenerationDraftPrompt: (_, { prompt }) => prompt }],+ generationError: [+ null as string | null,+ {+ generateWidget: () => null,+ generationCanceled: () => null,+ generationFailed: (_, { error }) => error,+ cancellationFailed: (_, { error }) => error,+ clearGenerationError: () => null,+ restoreFailed: (_, { error }) => error,+ restoreStarted: () => null,+ statusReceived: (error, { status }) => (status.lifecycle_status === 'ready' ? null : error),+ },+ ],+ generationModalOperation: [+ null as WidgetGenerationModalOperation,+ {+ closeGenerationModal: () => null,+ openGenerationModal: (_, { operation }) => operation,+ },+ ],+ generationRequestLoading: [+ false,+ {+ generationRequestStarted: () => true,+ generationRequestFinished: () => false,+ },+ ],+ dataRefreshInFlight: [+ false,+ {+ artifactRefreshReady: () => false,+ dataRefreshStarted: () => true,+ dataRefreshFinished: () => false,+ abortChain: () => false,+ refreshData: () => true,+ },+ ],+ restoreInFlight: [+ false,+ {+ restoreStarted: () => true,+ restoreFailed: () => false,+ statusReceived: () => false,+ },+ ],+ runtimeError: [+ null as string | null,+ {+ setRuntimeError: (_, { error }) => error,+ artifactRefreshReady: () => null,+ generateWidget: () => null,+ selectVersion: () => null,+ },+ ],+ source: [null as string | null, { openSourceModal: () => null, sourceReceived: (_, { source }) => source }],+ sourceChangePrompt: ['', { openSourceModal: () => '', setSourceChangePrompt: (_, { prompt }) => prompt }],+ sourceError: [+ null as string | null,+ { loadSource: () => null, sourceFailed: (_, { error }) => error, sourceReceived: () => null },+ ],+ sourceLoading: [+ false,+ {+ closeSourceModal: () => false,+ loadSource: () => true,+ sourceFailed: () => false,+ sourceReceived: () => false,+ },+ ],+ sourceModalOpen: [false, { closeSourceModal: () => false, openSourceModal: () => true }],+ sourceVersionId: [+ null as string | null,+ {+ openSourceModal: () => null,+ sourceReceived: (_, { versionId }) => versionId,+ },+ ],+ selectedVersionId: [+ null as string | null,+ {+ selectVersion: (_, { versionId }) => versionId,+ statusReceived: (selectedVersionId, { status }) => selectedVersionId ?? status.current_version_id,+ versionsReceived: (selectedVersionId, { versions, reset }) =>+ reset && selectedVersionId && !versions.some(({ id }) => id === selectedVersionId)+ ? (versions.find(({ is_current }) => is_current)?.id ?? selectedVersionId)+ : selectedVersionId,+ },+ ],+ status: [null as WidgetStatusApi | null, { statusReceived: (_, { status }) => status }],+ statusLoadError: [+ null as string | null,+ {+ loadStatus: () => null,+ statusFailed: (_, { error }) => error,+ statusReceived: () => null,+ },+ ],+ statusLoading: [+ false,+ {+ statusFailed: () => false,+ statusReceived: () => false,+ statusRequestFinished: () => false,+ statusRequestStarted: () => true,+ },+ ],+ versions: [+ [] as WidgetVersionApi[],+ {+ versionsReceived: (current, { versions, reset }) => (reset ? versions : [...current, ...versions]),+ versionRefreshed: (current, { version }) =>+ current.map((candidate) => (candidate.id === version.id ? version : candidate)),+ statusReceived: (current, { status }) => (status.has_versions ? current : []),+ },+ ],+ versionsCount: [0, { versionsReceived: (_, { count }) => count }],+ versionsError: [+ null as string | null,+ {+ loadVersions: () => null,+ versionsFailed: (_, { error }) => error,+ versionsReceived: () => null,+ },+ ],+ versionsLoading: [+ false,+ { loadVersions: () => true, versionsFailed: () => false, versionsReceived: () => false },+ ],+ versionsNextOffset: [null as number | null, { versionsReceived: (_, { nextOffset }) => nextOffset }],+ })),+ selectors({+ activeFrameNames: [+ (selectors) => [selectors.selectedVersion, selectors.selectedVersionId, selectors.status],+ (selectedVersion, selectedVersionId, status): string[] =>+ selectedVersion?.frame_names ??+ (selectedVersionId === status?.current_version_id ? (status?.frame_names ?? []) : []),+ ],+ selectedVersion: [+ (selectors) => [selectors.versions, selectors.selectedVersionId],+ (versions: WidgetVersionApi[], selectedVersionId: string | null): WidgetVersionApi | null =>+ versions.find(({ id }) => id === selectedVersionId) ?? null,+ ],+ isWorking: [+ (selectors) => [selectors.status],+ (status: WidgetStatusApi | null): boolean => shouldPoll(status),+ ],+ workingStatus: [+ (selectors) => [selectors.activeGenerationModel, selectors.elapsedSeconds, selectors.status],+ (activeGenerationModel, elapsedSeconds, status): WidgetWorkingStatus | null => {+ if (!shouldPoll(status)) {+ return null+ }+ return getWidgetWorkingStatus({+ elapsedSeconds,+ hasVersions: Boolean(status?.has_versions),+ model: activeGenerationModel,+ phase:+ status?.active_job?.phase ??+ (status?.lifecycle_status === 'building' ? 'publishing' : 'generating'),+ })+ },+ ],+ runDataDependenciesDisabledReason: [+ (selectors) => [+ selectors.activeFrameNames,+ selectors.dataRefreshInFlight,+ selectors.isDataChainRunning,+ selectors.isWorking,+ selectors.notebookIsBusy,+ selectors.status,+ selectors.statusLoading,+ ],+ (+ activeFrameNames,+ dataRefreshInFlight,+ isDataChainRunning,+ isWorking,+ notebookIsBusy,+ status,+ statusLoading+ ): string | null => {+ if (dataRefreshInFlight) {+ return null+ }+ if (isWorking) {+ return 'Wait for widget generation to finish.'+ }+ if (statusLoading && !status) {+ return 'Loading widget status.'+ }+ if (!status?.has_versions) {+ return 'Generate the widget first.'+ }+ if (!activeFrameNames.length) {+ return 'This widget does not use notebook data.'+ }+ if (isDataChainRunning || notebookIsBusy) {+ return 'Another notebook operation is running.'+ }+ return null+ },+ ],+ sourceImprovementDisabledReason: [+ (selectors) => [+ selectors.generationRequestLoading,+ selectors.isWorking,+ selectors.selectedVersionId,+ selectors.selectedVersion,+ selectors.sourceChangePrompt,+ selectors.sourceError,+ selectors.sourceLoading,+ selectors.sourceVersionId,+ selectors.status,+ ],+ (+ generationRequestLoading,+ isWorking,+ selectedVersionId,+ selectedVersion,+ sourceChangePrompt,+ sourceError,+ sourceLoading,+ sourceVersionId,+ status+ ): string | null => {+ if (selectedVersionId !== status?.current_version_id) {+ return 'Restore this version before building changes.'+ }+ if (!sourceChangePrompt.trim()) {+ return 'Describe the changes you want.'+ }+ if (!selectedVersion || selectedVersion.id !== selectedVersionId) {+ return 'Loading the widget version.'+ }+ if (!isWidgetModel(selectedVersion.model)) {+ return 'This widget version uses an unavailable model.'+ }+ if (sourceError) {+ return 'Reload the widget source first.'+ }+ if (sourceLoading || sourceVersionId !== selectedVersionId) {+ return 'Loading the widget source.'+ }+ if (isWorking || generationRequestLoading) {+ return 'Wait for widget generation to finish.'+ }+ return null+ },+ ],+ }),+ listeners(({ actions, values, props, cache }) => {+ const requestWithTimeout = async <T>(request: (signal: AbortSignal) => Promise<T>): Promise<T> => {+ const controller = new AbortController()+ const controllers = (cache.requestControllers ??= new Set<AbortController>()) as Set<AbortController>+ controllers.add(controller)+ const timeoutId = window.setTimeout(+ () => controller.abort(new Error('The widget request timed out.')),+ WIDGET_REQUEST_TIMEOUT_MS+ )+ try {+ return await request(controller.signal)+ } finally {+ window.clearTimeout(timeoutId)+ controllers.delete(controller)+ }+ }++ const nextStatusRequestId = (): number => {+ const requestId = Number(cache.statusRequestId ?? 0) + 1+ cache.statusRequestId = requestId+ return requestId+ }++ const isCurrentStatusRequest = (requestId: number): boolean => requestId === cache.statusRequestId++ const invalidateStatusRequests = (): void => {+ nextStatusRequestId()+ actions.statusRequestFinished()+ }++ const loadStatusAfterMutationFailure = async (): Promise<WidgetStatusApi | null> => {+ if (!props.projectId || !isSafeWidgetNodeId(props.nodeId)) {+ return null+ }+ try {+ return await requestWithTimeout((signal) =>+ notebooksWidgetStatus(String(props.projectId), props.notebookShortId, props.nodeId, { signal })+ )+ } catch {+ return null+ }+ }++ const scheduleStatusPoll = (): void => {+ cache.disposables.dispose('statusPoll')+ if (document.hidden) {+ return+ }+ const attempt = Number(cache.statusPollAttempts ?? 0)+ const delay = Math.min(STATUS_POLL_INTERVAL_MS * 2 ** attempt, STATUS_POLL_MAX_INTERVAL_MS)+ cache.disposables.add(() => {+ const timeoutId = window.setTimeout(() => actions.loadStatus(), delay)+ return () => window.clearTimeout(timeoutId)+ }, 'statusPoll')+ }++ const startElapsedClock = (startedAt: number): void => {+ cache.generationStartedAt = startedAt+ cache.disposables.dispose('elapsedClock')+ const updateElapsed = (): void => {+ actions.tickElapsed(Math.max(0, Math.floor((Date.now() - startedAt) / 1_000)))+ }+ updateElapsed()+ cache.disposables.add(() => {+ const intervalId = window.setInterval(updateElapsed, 1_000)+ return () => window.clearInterval(intervalId)+ }, 'elapsedClock')+ }++ return {+ cancelGeneration: async () => {+ const generationId = values.status?.active_job?.id+ if (+ !props.isEditable ||+ !generationId ||+ !props.projectId ||+ !isSafeWidgetNodeId(props.nodeId) ||+ values.cancellationInFlight+ ) {+ return+ }+ actions.cancellationStarted()+ try {+ await requestWithTimeout((signal) =>+ notebooksWidgetCancel(+ String(props.projectId),+ props.notebookShortId,+ props.nodeId,+ { generation_id: generationId },+ { signal }+ )+ )+ actions.generationCanceled()+ actions.loadStatus()+ } catch (error) {+ // An unmount aborts in-flight requests; that is not a failure to recover from or report.+ if (isAbortError(error)) {+ return+ }+ const recoveredStatus = isAmbiguousMutationError(error)+ ? await loadStatusAfterMutationFailure()+ : null+ if (recoveredStatus && recoveredStatus.active_job?.id !== generationId) {+ actions.generationCanceled()+ invalidateStatusRequests()+ if (recoveredStatus) {+ actions.statusReceived(recoveredStatus)+ }+ return+ }+ const message = errorMessage(error)+ posthog.captureException(error instanceof Error ? error : new Error(message), {+ action: 'cancel notebook widget generation',+ })+ actions.cancellationFailed(message)+ }+ },+ generateWidget: async ({ prompt, model, operation, expectedCurrentVersionId }) => {+ if (!props.isEditable || values.generationRequestLoading || values.isWorking) {+ return+ }+ if (!isSafeWidgetNodeId(props.nodeId)) {+ actions.generationFailed('This widget has an invalid identifier.')+ return+ }+ if (!props.projectId) {+ actions.generationFailed('The current project is unavailable. Refresh and try again.')+ return+ }+ const submittedPrompt = prompt.trim() || (operation === 'initial' ? DEFAULT_WIDGET_PROMPT : '')+ if (!submittedPrompt) {+ actions.generationFailed(+ operation === 'improve'+ ? 'Describe the change you want to make.'+ : 'Add instructions before generating the widget.'+ )+ return+ }+ const maxPromptLength =+ operation === 'regenerate' ? MAX_WIDGET_EFFECTIVE_PROMPT_LENGTH : MAX_WIDGET_PROMPT_LENGTH+ if (submittedPrompt.length > maxPromptLength) {+ actions.generationFailed(+ `Keep widget instructions to ${maxPromptLength.toLocaleString()} characters or fewer.`+ )+ return+ }+ if (operation === 'improve' && !expectedCurrentVersionId) {+ actions.generationFailed('Reload the widget before improving it.')+ return+ }+ actions.generationRequestStarted()+ invalidateStatusRequests()+ const generationId = uuidv4()+ let aborted = false+ try {+ const requestGeneration = async (): Promise<WidgetStatusApi> =>+ await requestWithTimeout((signal) =>+ notebooksWidgetGenerate(+ String(props.projectId),+ props.notebookShortId,+ props.nodeId,+ {+ prompt: submittedPrompt,+ generation_id: generationId,+ model,+ generation_operation: operation,+ expected_current_version_id: expectedCurrentVersionId,+ },+ { signal }+ )+ )+ let queuedStatus: WidgetStatusApi+ try {+ queuedStatus = await requestGeneration()+ } catch (error) {+ if (!isMissingNodeError(error)) {+ throw error+ }+ await props.persistNotebook()+ queuedStatus = await requestGeneration()+ }+ actions.closeGenerationModal()+ actions.closeSourceModal()+ invalidateStatusRequests()+ actions.statusReceived(queuedStatus)+ } catch (error) {+ // An unmount aborts in-flight requests; that is not a failure to recover from or report.+ if (isAbortError(error)) {+ aborted = true+ return+ }+ const recoveredStatus = isAmbiguousMutationError(error)+ ? await loadStatusAfterMutationFailure()+ : null+ if (recoveredStatus?.active_job?.id === generationId) {+ actions.closeGenerationModal()+ actions.closeSourceModal()+ invalidateStatusRequests()+ actions.statusReceived(recoveredStatus)+ return+ }+ const message = errorMessage(error)+ posthog.captureException(error instanceof Error ? error : new Error(message), {+ action: 'generate notebook widget',+ })+ actions.generationFailed(message)+ } finally {+ if (!aborted) {+ actions.generationRequestFinished()+ }+ }+ },+ loadMoreVersions: () => {+ if (values.versionsNextOffset !== null) {+ actions.loadVersions(false)+ }+ },+ improveSource: () => {+ if (values.sourceImprovementDisabledReason) {+ return+ }+ if (values.selectedVersion && isWidgetModel(values.selectedVersion.model)) {+ actions.generateWidget(+ values.sourceChangePrompt,+ values.selectedVersion.model,+ 'improve',+ values.sourceVersionId ?? undefined+ )+ }+ },+ loadSource: async () => {+ if (!props.projectId) {+ actions.sourceFailed('The current project is unavailable.')+ return+ }+ if (!isSafeWidgetNodeId(props.nodeId)) {+ actions.sourceFailed('This widget has an invalid identifier.')+ return+ }+ const requestedVersionId = values.selectedVersionId+ const requestId = Number(cache.sourceRequestId ?? 0) + 1+ cache.sourceRequestId = requestId+ try {+ const result = await requestWithTimeout((signal) =>+ notebooksWidgetSource(+ String(props.projectId),+ props.notebookShortId,+ props.nodeId,+ { version_id: requestedVersionId ?? undefined },+ { signal }+ )+ )+ if (requestId === cache.sourceRequestId && requestedVersionId === values.selectedVersionId) {+ actions.sourceReceived(result.source, requestedVersionId)+ }+ } catch (error) {+ if (requestId === cache.sourceRequestId) {+ actions.sourceFailed(errorMessage(error))+ }+ }+ },+ refreshData: async () => {+ if (!props.projectId) {+ actions.dataRefreshFinished()+ actions.statusFailed('The current project is unavailable. Refresh and try again.')+ return+ }+ if (!isSafeWidgetNodeId(props.nodeId)) {+ actions.dataRefreshFinished()+ actions.statusFailed('This widget has an invalid identifier.')+ return+ }+ if (cache.refreshDataRequestInFlight) {+ return+ }+ cache.refreshDataRequestInFlight = true+ const requestId = nextStatusRequestId()+ const requestedVersionId = values.selectedVersionId+ actions.statusRequestStarted()+ try {+ const refreshedStatus = await requestWithTimeout((signal) =>+ notebooksWidgetStatus(String(props.projectId), props.notebookShortId, props.nodeId, {+ signal,+ })+ )+ if (isCurrentStatusRequest(requestId)) {+ actions.statusReceived(refreshedStatus)+ }+ if (requestedVersionId && requestedVersionId !== refreshedStatus.current_version_id) {+ const selectedIndex = values.versions.findIndex(({ id }) => id === requestedVersionId)+ const offset =+ Math.floor(Math.max(selectedIndex, 0) / VERSION_PAGE_SIZE) * VERSION_PAGE_SIZE+ const page = await requestWithTimeout((signal) =>+ notebooksWidgetVersions(+ String(props.projectId),+ props.notebookShortId,+ props.nodeId,+ { offset, limit: VERSION_PAGE_SIZE },+ { signal }+ )+ )+ const refreshedVersion = page.results.find(({ id }) => id === requestedVersionId)+ if (!refreshedVersion) {+ throw new Error('The selected widget version is no longer available.')+ }+ actions.versionRefreshed(refreshedVersion)+ }+ actions.artifactRefreshReady()+ } catch (error) {+ actions.dataRefreshFinished()+ if (isCurrentStatusRequest(requestId)) {+ actions.statusFailed(errorMessage(error))+ }+ } finally {+ cache.refreshDataRequestInFlight = false+ if (isCurrentStatusRequest(requestId)) {+ actions.statusRequestFinished()+ }+ }+ },+ loadStatus: async () => {+ if (!props.projectId) {+ return+ }+ if (!isSafeWidgetNodeId(props.nodeId)) {+ actions.statusFailed('This widget has an invalid identifier.')+ return+ }+ const requestId = nextStatusRequestId()+ actions.statusRequestStarted()+ try {+ const loadedStatus = await requestWithTimeout((signal) =>+ notebooksWidgetStatus(String(props.projectId), props.notebookShortId, props.nodeId, {+ signal,+ })+ )+ if (isCurrentStatusRequest(requestId)) {+ actions.statusReceived(loadedStatus)+ }+ } catch (error) {+ if (isCurrentStatusRequest(requestId)) {+ actions.statusFailed(errorMessage(error))+ }+ } finally {+ if (isCurrentStatusRequest(requestId)) {+ actions.statusRequestFinished()+ }+ }+ },+ loadVersions: async ({ reset }) => {+ if (!props.projectId) {+ actions.versionsFailed('The current project is unavailable.')+ return+ }+ if (!isSafeWidgetNodeId(props.nodeId)) {+ actions.versionsFailed('This widget has an invalid identifier.')+ return+ }+ if (cache.versionsRequestInFlight) {+ if (reset) {+ cache.versionsResetPending = true+ }+ return+ }+ cache.versionsRequestInFlight = true+ const offset = reset ? 0 : (values.versionsNextOffset ?? values.versions.length)+ try {+ const page = await requestWithTimeout((signal) =>+ notebooksWidgetVersions(+ String(props.projectId),+ props.notebookShortId,+ props.nodeId,+ { offset, limit: VERSION_PAGE_SIZE },+ { signal }+ )+ )+ actions.versionsReceived(page.results, page.count, page.next_offset, reset)+ } catch (error) {+ actions.versionsFailed(errorMessage(error))+ } finally {+ cache.versionsRequestInFlight = false+ if (cache.versionsResetPending) {+ cache.versionsResetPending = false+ actions.loadVersions(true)+ }+ }+ },+ openGenerationModal: ({ operation }) => {+ if (operation === 'regenerate' && values.status?.has_versions && !values.selectedVersion) {+ cache.regenerationDraftVersionId = values.selectedVersionId+ actions.loadVersions(true)+ } else {+ cache.regenerationDraftVersionId = null+ }+ actions.setGenerationDraftPrompt(+ operation === 'regenerate'+ ? values.selectedVersion?.effective_prompt ||+ (values.status?.has_versions ? '' : props.prompt)+ : ''+ )+ actions.setGenerationDraftModel(+ isWidgetModel(values.selectedVersion?.model) ? values.selectedVersion.model : props.model+ )+ },+ openSourceModal: () => {+ actions.loadStatus()+ if (values.status?.has_versions && !values.selectedVersion) {+ actions.loadVersions(true)+ }+ actions.loadSource()+ },+ runDataDependencies: () => {+ if (values.dataRefreshInFlight || values.runDataDependenciesDisabledReason) {+ return+ }+ const content = props.getContent()+ const { missingFrameNames, nodeIds } = getWidgetDataDependencies(content, values.activeFrameNames)+ if (missingFrameNames.length) {+ const message =+ 'The widget expects notebook data that is no longer available. Restore the missing SQL or Python cell, or update the widget source.'+ actions.setRuntimeError(message)+ // The runtimeError banner only renders in the expanded preview, so a toast keeps+ // the failure visible when the widget is collapsed or still behind the trust gate.+ lemonToast.error(message)+ return+ }+ if (!nodeIds.length) {+ const message = 'No matching notebook data cells were found. Check the widget source.'+ actions.setRuntimeError(message)+ lemonToast.error(message)+ return+ }+ actions.setRuntimeError(null)+ cache.widgetDataRefreshRequested = true+ actions.dataRefreshStarted()+ actions.runWidgetDataChain(content, nodeIds)+ },+ restoreSelectedVersion: async () => {+ const expectedCurrentVersionId = values.status?.current_version_id+ if (+ !props.isEditable ||+ !props.projectId ||+ !isSafeWidgetNodeId(props.nodeId) ||+ !values.selectedVersionId ||+ !expectedCurrentVersionId ||+ values.selectedVersionId === expectedCurrentVersionId ||+ values.restoreInFlight+ ) {+ return+ }+ actions.restoreStarted()+ invalidateStatusRequests()+ try {+ const restoredStatus = await requestWithTimeout((signal) =>+ notebooksWidgetRevert(+ String(props.projectId),+ props.notebookShortId,+ props.nodeId,+ {+ version_id: values.selectedVersionId!,+ expected_current_version_id: expectedCurrentVersionId,+ },+ { signal }+ )+ )+ invalidateStatusRequests()+ actions.statusReceived(restoredStatus)+ if (restoredStatus.current_version_id) {+ actions.selectVersion(restoredStatus.current_version_id)+ }+ actions.loadVersions(true)+ actions.refreshData()+ } catch (error) {+ // An unmount aborts in-flight requests; that is not a failure to recover from or report.+ if (isAbortError(error)) {+ return+ }+ const recoveredStatus = isAmbiguousMutationError(error)+ ? await loadStatusAfterMutationFailure()+ : null+ if (recoveredStatus) {+ invalidateStatusRequests()+ actions.statusReceived(recoveredStatus)+ actions.loadVersions(true)+ }+ actions.restoreFailed(errorMessage(error))+ }+ },+ selectVersion: () => {+ if (values.sourceModalOpen) {+ actions.loadSource()+ }+ },+ statusReceived: ({ status }) => {+ cache.disposables.dispose('statusPoll')+ // A null -> id move (the first version appearing) must count as a change, so compare+ // against undefined, which only holds before the first status arrives. Reload even when+ // the list is empty, or a settings panel opened before generation keeps a stale history.+ const currentVersionChanged = Boolean(+ status.current_version_id &&+ cache.currentVersionId !== undefined &&+ cache.currentVersionId !== status.current_version_id+ )+ if (currentVersionChanged) {+ actions.loadVersions(true)+ cache.pendingCurrentVersionId = status.artifact_url ? null : status.current_version_id+ }+ if (+ status.current_version_id &&+ status.artifact_url &&+ (currentVersionChanged || cache.pendingCurrentVersionId === status.current_version_id)+ ) {+ actions.selectVersion(status.current_version_id)+ cache.pendingCurrentVersionId = null+ }+ cache.currentVersionId = status.current_version_id+ if (shouldPoll(status)) {+ cache.statusPollAttempts = Number(cache.statusPollAttempts ?? 0) + 1+ scheduleStatusPoll()+ const startedAtRaw = status.active_job?.started_at ?? status.active_job?.created_at+ const startedAt = startedAtRaw+ ? new Date(startedAtRaw).getTime()+ : (cache.generationStartedAt ?? Date.now())+ if (startedAt !== cache.generationStartedAt) {+ startElapsedClock(startedAt)+ }+ } else {+ cache.statusPollAttempts = 0+ cache.disposables.dispose('elapsedClock')+ cache.generationStartedAt = null+ }+ },+ versionsReceived: () => {+ if (+ values.generationModalOperation !== 'regenerate' ||+ !values.selectedVersion ||+ values.selectedVersion.id !== cache.regenerationDraftVersionId+ ) {+ return+ }+ cache.regenerationDraftVersionId = null+ actions.setGenerationDraftPrompt(values.selectedVersion.effective_prompt)+ if (isWidgetModel(values.selectedVersion.model)) {+ actions.setGenerationDraftModel(values.selectedVersion.model)+ }+ },+ closeGenerationModal: () => {+ cache.regenerationDraftVersionId = null+ },+ statusFailed: () => {+ if (shouldPoll(values.status)) {+ cache.statusPollAttempts = Number(cache.statusPollAttempts ?? 0) + 1+ scheduleStatusPoll()+ }+ },+ abortChain: ({ reason }) => {+ if (!cache.widgetDataRefreshRequested) {+ return+ }+ cache.widgetDataRefreshRequested = false+ actions.setRuntimeError(+ reason+ ? `The connected data cell “${reason}” did not finish successfully. Open that cell, fix its error, then run the widget data cells again.`+ : 'Some connected data cells are unavailable. Scroll through the notebook, then run the widget data cells again.'+ )+ },+ dataRefreshStarted: () => {+ cache.widgetDataRefreshRequested = true+ },+ widgetDataChainFinished: () => {+ if (!values.dataRefreshInFlight) {+ return+ }+ cache.widgetDataRefreshRequested = false+ actions.dataRefreshFinished()+ actions.refreshData()+ },+ }+ }),+ afterMount(({ actions, cache }) => {+ cache.disposables.add(+ () => {+ const handleVisibilityChange = (): void => {+ if (document.hidden) {+ cache.disposables.dispose('statusPoll')+ } else {+ actions.loadStatus()+ }+ }+ document.addEventListener('visibilitychange', handleVisibilityChange)+ return () => document.removeEventListener('visibilitychange', handleVisibilityChange)+ },+ 'visibilityChange',+ { pauseOnPageHidden: false }+ )+ actions.loadStatus()+ }),+ beforeUnmount(({ cache }) => {+ const controllers = cache.requestControllers as Set<AbortController> | undefined+ controllers?.forEach((controller) => controller.abort())+ controllers?.clear()+ }),+ ])++export const notebookNodeGeneratedWidgetSettingsLogic: LogicWrapper<notebookNodeGeneratedWidgetSettingsLogicType> =+ kea<notebookNodeGeneratedWidgetSettingsLogicType>([+ props({} as NotebookNodeGeneratedWidgetLogicProps),+ key((props) => `${props.projectId}-${props.notebookShortId}-${props.nodeId}`),+ path((key) => ['products', 'notebooks', 'notebookNodeGeneratedWidgetSettingsLogic', key]),+ connect((props: NotebookNodeGeneratedWidgetLogicProps) => ({+ actions: [notebookNodeGeneratedWidgetLogic(props), ['loadVersions']],+ })),+ afterMount(({ actions }) => {+ actions.loadVersions(true)+ }),+ ])diff --git a/products/notebooks/frontend/NotebookNodeGeneratedWidget/notebookWidgetTrustLogic.test.ts b/products/notebooks/frontend/NotebookNodeGeneratedWidget/notebookWidgetTrustLogic.test.tsindex b52d076f0c1e..35d903114a50 100644--- a/products/notebooks/frontend/NotebookNodeGeneratedWidget/notebookWidgetTrustLogic.test.ts+++ b/products/notebooks/frontend/NotebookNodeGeneratedWidget/notebookWidgetTrustLogic.test.ts@@ -43,6 +43,7 @@ describe('notebookWidgetTrustLogic', () => {notebookWidgetTrustLogic.actions.trustBuild(null, BUILD_HASH)expect(trustFor({ userId: null }).buildTrusted).toBe(true)+ expect(trustFor({ userId: 12 }).buildTrusted).toBe(false)expect(notebookWidgetTrustLogic.values.trustByUser).toEqual({})})})diff --git a/products/notebooks/frontend/NotebookNodeGeneratedWidget/notebookWidgetTrustLogic.ts b/products/notebooks/frontend/NotebookNodeGeneratedWidget/notebookWidgetTrustLogic.tsindex 06a426bc8d75..1f64eb5f6222 100644--- a/products/notebooks/frontend/NotebookNodeGeneratedWidget/notebookWidgetTrustLogic.ts+++ b/products/notebooks/frontend/NotebookNodeGeneratedWidget/notebookWidgetTrustLogic.ts@@ -60,7 +60,8 @@ export function getNotebookWidgetTrust({const scopes = userId === null ? EMPTY_TRUST_SCOPES : scopesForUser(trustByUser, userId)return {buildTrusted:- validBuildHash && (sessionBuildHashes.includes(buildHash) || scopes.buildHashes.includes(buildHash)),+ validBuildHash &&+ ((userId === null && sessionBuildHashes.includes(buildHash)) || scopes.buildHashes.includes(buildHash)),}}diff --git a/products/notebooks/frontend/NotebookNodeGeneratedWidget/widgetModels.ts b/products/notebooks/frontend/NotebookNodeGeneratedWidget/widgetModels.tsnew file mode 100644index 000000000000..153a57673c16--- /dev/null+++ b/products/notebooks/frontend/NotebookNodeGeneratedWidget/widgetModels.ts@@ -0,0 +1,66 @@+import type { LemonSelectOptions } from '@posthog/lemon-ui'++import type { WidgetGenerateRequestApi } from 'products/notebooks/frontend/generated/api.schemas'++export type WidgetModel = NonNullable<WidgetGenerateRequestApi['model']>++export const DEFAULT_WIDGET_MODEL: WidgetModel = 'claude-sonnet-4-6'+export const DEFAULT_WIDGET_PROMPT = 'Create an interactive visualization of the data in this notebook.'+export const MAX_WIDGET_PROMPT_LENGTH = 20_000+export const MAX_WIDGET_EFFECTIVE_PROMPT_LENGTH = 50_000++export type WidgetModelInfo = {+ name: string+ estimateLabel: string+ estimatedSeconds: number+}++export const WIDGET_MODEL_INFO: Record<WidgetModel, WidgetModelInfo> = {+ 'claude-haiku-4-5': {+ name: 'Claude Haiku 4.5',+ estimateLabel: '~1 min',+ estimatedSeconds: 60,+ },+ 'claude-sonnet-4-6': {+ name: 'Claude Sonnet 4.6',+ estimateLabel: '~2 min',+ estimatedSeconds: 120,+ },+ 'claude-sonnet-5': {+ name: 'Claude Sonnet 5',+ estimateLabel: '~3 min',+ estimatedSeconds: 180,+ },+ 'claude-opus-5': {+ name: 'Claude Opus 5',+ estimateLabel: '~5 min',+ estimatedSeconds: 300,+ },+}++export function isWidgetModel(model: string | null | undefined): model is WidgetModel {+ return model !== null && model !== undefined && model in WIDGET_MODEL_INFO+}++export const WIDGET_MODEL_OPTIONS: LemonSelectOptions<WidgetModel> = [+ {+ value: 'claude-haiku-4-5',+ label: `Fast - ${WIDGET_MODEL_INFO['claude-haiku-4-5'].name} (${WIDGET_MODEL_INFO['claude-haiku-4-5'].estimateLabel})`,+ tooltip: 'Returns simpler widgets more quickly.',+ },+ {+ value: 'claude-sonnet-4-6',+ label: `Balanced - ${WIDGET_MODEL_INFO['claude-sonnet-4-6'].name} (${WIDGET_MODEL_INFO['claude-sonnet-4-6'].estimateLabel})`,+ tooltip: 'Balances generation time and visual detail.',+ },+ {+ value: 'claude-sonnet-5',+ label: `High quality - ${WIDGET_MODEL_INFO['claude-sonnet-5'].name} (${WIDGET_MODEL_INFO['claude-sonnet-5'].estimateLabel})`,+ tooltip: 'Produces more detailed widgets and may take longer.',+ },+ {+ value: 'claude-opus-5',+ label: `Highest quality - ${WIDGET_MODEL_INFO['claude-opus-5'].name} (${WIDGET_MODEL_INFO['claude-opus-5'].estimateLabel})`,+ tooltip: 'Produces the most detailed widgets and may take the longest.',+ },+]diff --git a/products/notebooks/frontend/generated/api.schemas.ts b/products/notebooks/frontend/generated/api.schemas.tsindex 6b4e3ddad0a6..793c1d9ffcef 100644--- a/products/notebooks/frontend/generated/api.schemas.ts+++ b/products/notebooks/frontend/generated/api.schemas.ts@@ -703,8 +703,8 @@ export const GenerationOperationEnumApi = {export interface WidgetGenerateRequestApi {/**- * Instructions for the generated widget.- * @maxLength 20000+ * Instructions for the generated widget. Initial and improvement instructions accept up to 20,000 characters; regeneration accepts complete instructions up to 50,000 characters.+ * @maxLength 50000*/prompt: string/** Idempotency key for this generation job. */@@ -722,6 +722,8 @@ export interface WidgetGenerateRequestApi {* * `regenerate` - regenerate* * `improve` - improve */generation_operation?: GenerationOperationEnumApi+ /** Current widget version the improvement is based on. Required for improve operations. */+ expected_current_version_id?: string}/**@@ -962,7 +964,10 @@ export interface WidgetVersionApi {version_operation: GeneratedWidgetVersionOperationEnumApi/** Instructions added by this version. */prompt_delta: string- /** Complete instructions represented by this version. */+ /**+ * Complete instructions represented by this version, up to 50,000 characters.+ * @maxLength 50000+ */effective_prompt: string/*** AI model, or null when this version did not run a model.diff --git a/products/notebooks/frontend/generated/api.zod.ts b/products/notebooks/frontend/generated/api.zod.tsindex dd4b7ba74243..dd9c7b3ef0d5 100644--- a/products/notebooks/frontend/generated/api.zod.ts+++ b/products/notebooks/frontend/generated/api.zod.ts@@ -739,13 +739,18 @@ export const NotebooksWidgetCancelBody = /* @__PURE__ */ zod.object({/*** The API for interacting with Notebooks. This feature is in early access and the API can have breaking changes without announcement.*/-export const notebooksWidgetGenerateBodyPromptMax = 20000+export const notebooksWidgetGenerateBodyPromptMax = 50000export const notebooksWidgetGenerateBodyModelDefault = `claude-sonnet-4-6`export const notebooksWidgetGenerateBodyGenerationOperationDefault = `regenerate`export const NotebooksWidgetGenerateBody = /* @__PURE__ */ zod.object({- prompt: zod.string().max(notebooksWidgetGenerateBodyPromptMax).describe('Instructions for the generated widget.'),+ prompt: zod+ .string()+ .max(notebooksWidgetGenerateBodyPromptMax)+ .describe(+ 'Instructions for the generated widget. Initial and improvement instructions accept up to 20,000 characters; regeneration accepts complete instructions up to 50,000 characters.'+ ),generation_id: zod.uuid().describe('Idempotency key for this generation job.'),model: zod.enum(['claude-haiku-4-5', 'claude-sonnet-4-6', 'claude-sonnet-5', 'claude-opus-5'])@@ -763,6 +768,10 @@ export const NotebooksWidgetGenerateBody = /* @__PURE__ */ zod.object({.describe('Whether to generate from scratch or improve the current source.\n\n\* `initial` - initial\n\* `regenerate` - regenerate\n\* `improve` - improve'),+ expected_current_version_id: zod+ .uuid()+ .optional()+ .describe('Current widget version the improvement is based on. Required for improve operations.'),})/**diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex e7c603101769..5af2d0b4e195 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -87359,8 +87359,8 @@ export namespace Schemas {export interface WidgetGenerateRequest {/**- * Instructions for the generated widget.- * @maxLength 20000+ * Instructions for the generated widget. Initial and improvement instructions accept up to 20,000 characters; regeneration accepts complete instructions up to 50,000 characters.+ * @maxLength 50000*/prompt: string;/** Idempotency key for this generation job. */@@ -87378,6 +87378,8 @@ export namespace Schemas {* * `regenerate` - regenerate* * `improve` - improve */generation_operation?: GenerationOperationEnum;+ /** Current widget version the improvement is based on. Required for improve operations. */+ expected_current_version_id?: string;}/**@@ -87535,7 +87537,10 @@ export namespace Schemas {version_operation: GeneratedWidgetVersionOperationEnum;/** Instructions added by this version. */prompt_delta: string;- /** Complete instructions represented by this version. */+ /**+ * Complete instructions represented by this version, up to 50,000 characters.+ * @maxLength 50000+ */effective_prompt: string;/*** AI model, or null when this version did not run a model.