diff --git a/browser_tests/tests/agent/agentWidgetFormHookDrift.spec.ts b/browser_tests/tests/agent/agentWidgetFormHookDrift.spec.ts new file mode 100644 index 00000000000..db173d514af --- /dev/null +++ b/browser_tests/tests/agent/agentWidgetFormHookDrift.spec.ts @@ -0,0 +1,98 @@ +import { expect } from '@playwright/test' + +import type { ComfyNodeDef } from '@/schemas/nodeDefSchema' + +import { agentConversationTest as test } from '@e2e/fixtures/agentConversationFixture' + +const NODE_TYPE = 'AgentWidgetFormDriftProbe' + +const nodeDef: ComfyNodeDef = { + name: NODE_TYPE, + display_name: 'Agent Widget Form Drift Probe', + description: '', + category: 'testing', + python_module: 'browser_tests.agent_widget_form_drift', + output_node: false, + output: ['STRING'], + output_is_list: [false], + output_name: ['text'], + input: { + required: { + text: ['STRING', { default: 'initial value', multiline: false }] + } + }, + input_order: { required: ['text'] } +} + +test.describe( + 'Agent widget form under a third-party serializer', + { tag: ['@cloud', '@agent', '@widget', '@vue-nodes'] }, + () => { + test.use({ + conversationCase: 'agent-rec-text-only-answer', + extraNodeDefs: { [NODE_TYPE]: nodeDef }, + humanOpsHost: 'apply' + }) + + test('ignores serializer-private positional state outside the Agent wire', async ({ + agentConversation, + page + }) => { + test.setTimeout(90_000) + + await test.step('bind the seeded workflow', async () => { + await agentConversation.runTurns() + }) + + const control = + await test.step('publish a node nothing interferes with', async () => { + const nodeId = await agentConversation.addNodeOfType( + NODE_TYPE, + [400, 400] + ) + const outcomes = await agentConversation.waitForHumanOps(1) + expect(outcomes[0]?.outcome).toBe('applied') + expect(agentConversation.hostNode(nodeId)).toMatchObject({ + widgets_values: { text: 'initial value' }, + widgets_values_form: { order: ['text'] } + }) + return nodeId + }) + + await test.step('install a pack that appends its own entry after the hook', async () => { + await page.evaluate((type) => { + const proto = window.LiteGraph!.registered_node_types[type].prototype + proto.onSerialize = function (data) { + data.widgets_values = ['initial value', 'pack private state'] + } + }, NODE_TYPE) + }) + + await test.step('the node reaches the host with its named value and form', async () => { + const nodeId = await agentConversation.addNodeOfType( + NODE_TYPE, + [700, 400] + ) + expect(nodeId).not.toBe(control) + + const outcomes = await agentConversation.waitForHumanOps(2) + expect(outcomes[1]).toMatchObject({ + outcome: 'applied' + }) + expect(agentConversation.hostNode(nodeId)).toMatchObject({ + widgets_values: { text: 'initial value' }, + widgets_values_form: { order: ['text'] } + }) + await expect( + agentConversation.vueNodes.getNodeLocator(nodeId) + ).toBeVisible() + }) + + await test.step('the undrifted node remains intact', () => { + expect(agentConversation.hostNode(control)).toMatchObject({ + widgets_values_form: { order: ['text'] } + }) + }) + }) + } +) diff --git a/docs/adr/WIDGET-SERIALIZATION-0047-agent-wire-widget-form-is-proven-not-derived.md b/docs/adr/WIDGET-SERIALIZATION-0047-agent-wire-widget-form-is-proven-not-derived.md new file mode 100644 index 00000000000..ba237950928 --- /dev/null +++ b/docs/adr/WIDGET-SERIALIZATION-0047-agent-wire-widget-form-is-proven-not-derived.md @@ -0,0 +1,170 @@ +# ADR-WIDGET-SERIALIZATION-0047: The Agent wire's widget form is proven, not derived + +Date: 2026-10-23 + +## Status + +Proposed + +## Context + +A workflow stores widget **values** but not the **schema** needed to interpret +them. Three systems reconstruct that schema independently — this frontend from +its own registrations, `comfy-cli` from `object_info` plus a set of +hand-maintained guesses, the doc host from a pinned catalogue — and they drift. +`widgets_values_form` is the minimal self-describing step: it declares the +order the node's named widget values belong in, so the reader needs no +catalogue for that node. + +That makes a form **authoritative**. `comfy-multi-player`'s +`widgetStorageFor` picks self-described storage whenever a form is present, +ahead of the catalogue; `projectWidgets` projects from the form with no +catalogue lookup; and `validateWidgetName` treats the form as closed. A node +that carries a wrong form is therefore worse off than a node that carries +none: there is no later leg at which the mistake can be caught. + +The frontend emits the form at one place only, the Agent wire boundary +(`wireNodeSnapshot` in `src/workbench/extensions/agent/crdt/docOpMinter.ts`). +An ordinary save carries no form. That boundary was chosen deliberately: a +core-serialization producer was reviewed and rejected, because shared +serialization would then be compensating for one consumer's closed-form +interpretation. + +### The claim this ADR exists to refute + +The producer was originally justified by "the values and the order come out of +the same loop, so they cannot drift." That is false, and the falsifier is +specific. `LGraphNode.serializeFromStoreState` does: + +```ts +Object.assign(o, serialiseWidgetValues(widgets)) // core writes both fields +// ... +runExtensionSerializeHook(this, o, NODE_CANONICAL_FIELDS, this.onSerialize) +``` + +`widgets_values` and `widgets_values_named` are both in +`NODE_CANONICAL_FIELDS`, so `runExtensionSerializeHook` copies an extension's +writes to either one back over what core produced. The hook runs **after** +core wrote the values, and a node's `onSerialize` can also mutate +`node.widgets` while it runs. So the values a form would describe can be +replaced, truncated or extended between the derivation and the wire — and in +exactly the population the hook exists for, third-party packs with custom +serializers. A check placed before the hook asserts the one thing that was +never in doubt. + +`SubgraphNode.serializeFromStoreState` is the in-repo instance of the same +shape: it calls `super.serializeFromStoreState(state)`, which already includes +the hook, and then replaces `widgets_values` itself. "Post-hook" is necessary +and not sufficient — the base post-hook is not always the last writer. + +## Decision + +1. **The form is a proof, not a derivation.** The wire declares a form only + where it can prove the declared order describes every named value the Agent + wire carries. Positional compatibility data and extension-private values + that the wire filters out are outside that claim. Where the order cannot be + proven, the wire declares nothing. "Declare nothing" is the behaviour in + every environment; see decision 4. +2. **Every check reads the post-hook payload.** The classifier takes the + serialized node returned by `node.serialize()` — hook already run — and + compares it against the live widget list, rather than inspecting state + core holds before the hook. +3. **Four invariants, stated once and asserted at that one site.** They are + the contract; the list below is the normative text and the assertion + messages name the broken entry. +4. **Suppression is the gate; `assert` is the channel.** `assert` from + `src/base/assert.ts` throws under DEV only, so it cannot be the mechanism + that keeps a wrong form off the wire. Returning no form is. The DEV throw + is deliberately swallowed at this seam, because every one of these + invariants is breakable by a third-party pack: a pack must not be able to + stop the Agent from minting in a developer's browser, only to be unable to + make us publish a form describing the wrong values. The console line and + the production reporter still fire. +5. **Invariant 4 is a signal, not a failure.** "Object-shaped values with no + declared form" is the expected state for much of the ecosystem today. It + reports rather than asserts, and it is the only way to learn _which_ + classes still declare nothing, which is what decides whether the form path + generalises. + +### The four invariants + +Let _live_ be `node.widgets`, _value widgets_ be those whose values survive the +Agent wire filter, _values_ the name-keyed object the wire ships, and _order_ +the declared sequence. + +| # | Invariant | Reason slug | +| --- | ------------------------------------------------------------------------------------------------------------------- | --------------------------------- | +| 1 | Every `order` entry names a live value widget. | `order_names_unserialized_widget` | +| 2 | `order` and `Object.keys(values)` agree as a set difference in **both** directions. | `declared_keys_disagree` | +| 3 | The filtered post-hook named-value key set equals the live value-widget key set. | `hook_changed_serialized_widgets` | +| 4 | Object-shaped values with no declared form are reported, once per class and reason, with 100 distinct keys maximum. | `agent_widget_form_undeclared` | + +Two of these need their exact form recorded, because the obvious version of +each is wrong: + +- **Invariant 2 is bidirectional.** `order` ⊆ `keys(values)` alone misses + residue — a stored value outside the order, which the host would keep and + never project. The VideoHelperSuite shape is the in-ecosystem instance: it + keys its dict from the _unfiltered_ widget list, so its keys and a derived + order differ by exactly the one widget carrying `serialize = false`. +- **Invariant 3 compares key sets, not key sequences.** Key order inside + `widgets_values_named` is not meaningful — an integer-like widget name is + enumeration-reordered by the object itself, which is the reason the form + exists. A pack that reorders keys and changes nothing else has not broken + anything. + +### Shapes that are suppressed without being violations + +A value-dependent layout (`COMFY_AUTOGROW_V3`, `COMFY_DYNAMICCOMBO_V3`, +`COMFY_DYNAMICGROUP_V3`) keeps its order in the catalogue, which expands it +with the selection; a closed form would freeze it. A missing-node shell +(`last_serialization` set) round-trips a stored payload for a class this build +cannot see, so its live widget list — empty or fabricated — cannot order it. A +value with no live widget at all, an unnamed widget, and two value widgets +sharing a name are all shapes a correct producer cannot describe. These report +under invariant 4 with their own reason and never assert. + +A node whose only widgets are buttons is the one suppression that is **not** +reported: it has no named value for a form to order, so counting it as a +declaration gap would bury the signal under every such class in the ecosystem. + +## Consequences + +- One behaviour change relative to the previous derivation: a node whose + filtered post-hook named-value key set was rewritten by an extension no + longer gets a form. Positional or private state the Agent wire does not send + does not suppress the form. +- Invariant 4 turns "what fraction of the ecosystem declares a form" from an + unanswerable question into a queryable one: `error_type` + `agent_widget_form_undeclared`, tagged `node_type` and `reason`, + fingerprinted on all three, one report per class and reason per page session. +- A bulk pass does not go through telemetry at all. + `widgetValuesFormVerdict(node)` runs the node's serialization hook, classifies + and tallies the result, and `widgetFormSuppressionTally()` returns up to 100 + distinct per-class counts. The hook can mutate extension state, so the corpus + runner must use disposable nodes. A thrown hook is classified separately as + `serialization_failed`. +- The frontend follower has no read-back handling for the form, so the round + trip remains the host's. That is unchanged by this ADR and is why the form + stays on the Agent wire rather than in ordinary saves. + +## Alternatives considered + +**Emit the form from core serialization.** Rejected on review: it puts a +consumer's closed-form interpretation into shared serialization, and it needs a +core policy suppressing forms for dynamic combos, groups and autogrow to +compensate. The Agent adapter is the smallest boundary that owns the decision. + +**A stable per-widget UUID instead of an order.** Right idea, wrong boundary. +ECS ids are process-local and minted at graph join, while workflow JSON is +durable, portable and cross-tool: a random id means nothing to a reader that +did not mint it, a derived one is only as stable as what it derives from, and +persisting the mapping re-invents the form plus a layer no human can read in a +diff. `(name, occurrence)` was already rejected for adding a second +widget-identity format; a hash would be a third. + +**Assert and keep emitting.** Rejected. A wrong form is authoritative on every +leg, so the only safe response to an unproven form is not to send one. + +**Throw under DEV.** Rejected for this seam specifically; see decision 4. The +unit suite is what pins each invariant, including that each one still fires. diff --git a/src/workbench/extensions/agent/crdt/docOpMinter.test.ts b/src/workbench/extensions/agent/crdt/docOpMinter.test.ts index 4fea9bca919..0663bc74be0 100644 --- a/src/workbench/extensions/agent/crdt/docOpMinter.test.ts +++ b/src/workbench/extensions/agent/crdt/docOpMinter.test.ts @@ -3212,18 +3212,6 @@ describe('wireNodeSnapshot widget form (schema A24)', () => { n.addWidget('text', 'prompt', 'a', () => {}) n.addWidget('text', 'prompt', 'b', () => {}) } - }, - { - case: 'a stored value whose widget its serializer removed', - definition: nodeDef('Dynamic', {}), - build: (n: LGraphNode) => { - n.addWidget('text', 'prompt', 'a', () => {}) - n.addWidget('text', 'extra', 'b', () => {}) - new LGraph().add(n) - n.onSerialize = () => { - n.widgets?.pop() - } - } } ])('declares no form for a node with $case', ({ definition, build }) => { useNodeDefStore().addNodeDef(definition) @@ -3232,6 +3220,23 @@ describe('wireNodeSnapshot widget form (schema A24)', () => { expect(wireNodeSnapshot(node)).not.toHaveProperty('widgets_values_form') }) + it('declares the filtered form when serialization removes a widget', () => { + useNodeDefStore().addNodeDef(nodeDef('Dynamic', {})) + const node = nodeWith('Dynamic', (n) => { + n.addWidget('text', 'prompt', 'a', () => {}) + n.addWidget('text', 'extra', 'b', () => {}) + new LGraph().add(n) + n.onSerialize = () => { + n.widgets?.pop() + } + }) + + expect(wireNodeSnapshot(node)).toMatchObject({ + widgets_values: { prompt: 'a' }, + widgets_values_form: { order: ['prompt'] } + }) + }) + it('declares the form for a node built by the real widget constructors', () => { const required = { seed: ['INT', { default: 1, control_after_generate: true }], diff --git a/src/workbench/extensions/agent/crdt/docOpMinter.ts b/src/workbench/extensions/agent/crdt/docOpMinter.ts index bf31cc9b016..3ad8c259555 100644 --- a/src/workbench/extensions/agent/crdt/docOpMinter.ts +++ b/src/workbench/extensions/agent/crdt/docOpMinter.ts @@ -15,7 +15,6 @@ import type { NodeId as WireNodeId, PromotedHostWrite, SubgraphDefinition, - WidgetValuesForm, WorkflowNode } from '@comfyorg/comfy-multi-player' import { isEqual } from 'es-toolkit' @@ -32,7 +31,6 @@ import type { Subgraph } from '@/lib/litegraph/src/subgraph/Subgraph' import type { SubgraphNode } from '@/lib/litegraph/src/subgraph/SubgraphNode' import type { ISerialisedNode } from '@/lib/litegraph/src/types/serialisation' import { isWidgetValue } from '@/lib/litegraph/src/types/widgets' -import type { IBaseWidget } from '@/lib/litegraph/src/types/widgets' import { reportError } from '@/platform/telemetry/reportError' import { useNodeDefStore } from '@/stores/nodeDefStore' import type { DynamicComboSelection } from '@/stores/nodeDefStore' @@ -40,7 +38,6 @@ import { useWidgetValueStore } from '@/stores/widgetValueStore' import type { RootGraphId } from '@/types/graphScopeId' import type { NodeId } from '@/types/nodeId' import { widgetId } from '@/types/widgetId' -import type { WidgetState } from '@/types/widgetState' import { findNodeInHierarchy, findSubgraphByUuid, @@ -55,6 +52,11 @@ import { import type { GraphOperation } from './graphOperations' import type { DocPromotedWidgets } from './agentSubgraphDefinitions' import { reportLostEdit } from './reportLostEdit' +import { + isValueWidget, + provenWidgetValuesForm, + valueWidgetsOnly +} from './widgetValuesForm' export interface DocOpMinterDeps { /** Slice 00's product gate. */ @@ -204,69 +206,15 @@ export function wireNodeSnapshot(node: LGraphNode): WorkflowNode | null { const snapshot = { ...rest, flags } satisfies WorkflowNode if (!named || node.isVirtualNode) return snapshot const values = valueWidgetsOnly(node, named) - const form = nodeLocalWidgetForm(node, values) + // The form is proven against the POST-HOOK serialization, not derived from + // the live widget list alone: `serialize()` above already ran the extension + // serialize hook, which may have replaced either widget-values field. + const form = provenWidgetValuesForm(node, values, serialized) return form ? { ...snapshot, widgets_values: values, widgets_values_form: form } : { ...snapshot, widgets_values: values } } -const VALUE_DEPENDENT_LAYOUT_INPUT_TYPES = new Set([ - 'COMFY_AUTOGROW_V3', - 'COMFY_DYNAMICCOMBO_V3', - 'COMFY_DYNAMICGROUP_V3' -]) - -function nodeLocalWidgetForm( - node: LGraphNode, - values: Record -): WidgetValuesForm | undefined { - const definition = useNodeDefStore().fromLGraphNode(node) - const layoutDependsOnValues = Object.values(definition?.inputs ?? {}).some( - (spec) => VALUE_DEPENDENT_LAYOUT_INPUT_TYPES.has(spec.type) - ) - if (layoutDependsOnValues) return undefined - const order = (node.widgets ?? []) - .map((widget) => widget.name) - .filter((name) => Object.hasOwn(values, name)) - const isClosed = - order.length > 0 && - order.length === Object.keys(values).length && - order.every((name) => name.length > 0) && - new Set(order).size === order.length - return isClosed ? { order } : undefined -} - -function valueWidgetsOnly( - node: LGraphNode, - named: object -): Record { - const filtered: Record = {} - const rootGraphId = node.graph?.rootGraph.id - const widgetValueStore = useWidgetValueStore() - for (const [name, value] of Object.entries(named)) { - const widget = node.widgets?.find((candidate) => candidate.name === name) - const stored = rootGraphId - ? widgetValueStore.getWidget(widgetId(rootGraphId, node.id, name)) - : undefined - if (isValueWidget(widget, stored)) filtered[name] = value - } - return filtered -} - -function isValueWidget( - widget: IBaseWidget | undefined, - stored?: WidgetState -): boolean { - if (!widget && !stored) return false - // A destructuring default fires on absent AND present-but-undefined alike, - // which is what `IBaseWidget`'s own optional fields mean: the live widget - // did not state this, so the registration the intent was keyed by answers. - // One construct for both fields, so the two halves of the guard cannot - // drift apart again. - const { type = stored?.type, serialize = stored?.serialize } = widget ?? {} - return type !== 'button' && serialize !== false -} - function nodeKey(graphId: string, nodeId: NodeId): string { return `${graphId}:${String(nodeId)}` } diff --git a/src/workbench/extensions/agent/crdt/widgetValuesForm.test.ts b/src/workbench/extensions/agent/crdt/widgetValuesForm.test.ts new file mode 100644 index 00000000000..896315f7272 --- /dev/null +++ b/src/workbench/extensions/agent/crdt/widgetValuesForm.test.ts @@ -0,0 +1,496 @@ +import { fromPartial } from '@total-typescript/shoehorn' +import { beforeEach, describe, expect, it, onTestFinished, vi } from 'vitest' + +import { setAssertReporter } from '@/base/assert' +import { LGraph, LGraphNode } from '@/lib/litegraph/src/litegraph' +import type { ISerialisedNode } from '@/lib/litegraph/src/types/serialisation' +import { reportError } from '@/platform/telemetry/reportError' +import type { ComfyNodeDef as ComfyNodeDefV1 } from '@/schemas/nodeDefSchema' +import { useNodeDefStore } from '@/stores/nodeDefStore' + +import { + classifyWidgetValuesForm, + provenWidgetValuesForm, + resetWidgetFormSuppressionTally, + valueWidgetsOnly, + widgetFormSuppressionTally, + widgetValuesFormVerdict +} from './widgetValuesForm' + +vi.mock(import('@/platform/telemetry/reportError')) + +function nodeDef( + name: string, + required: NonNullable['required'] +): ComfyNodeDefV1 { + return { + name, + display_name: name, + category: 'test', + python_module: 'custom_nodes.test', + description: '', + input: { required }, + output: [], + output_name: [], + output_is_list: [], + output_node: false + } +} + +function nodeWith(type: string, build: (node: LGraphNode) => void): LGraphNode { + const node = detachedNodeWith(type, build) + new LGraph().add(node) + return node +} + +/** + * Graph registration collapses two widgets that share a name, so a node that + * carries the duplicate has to be built outside a graph. + */ +function detachedNodeWith( + type: string, + build: (node: LGraphNode) => void +): LGraphNode { + const node = new LGraphNode(type, type) + node.serialize_widgets = true + build(node) + return node +} + +/** The post-hook serialization, as `wireNodeSnapshot` reads it. */ +function serializedOf(node: LGraphNode): ISerialisedNode { + return node.serialize() +} + +function recordNoValueClasses(count: number): void { + Array.from({ length: count }, (_, index) => + nodeWith(`OnlyButton${index}`, (node) => { + node.addWidget('button', 'refresh', 'refresh', () => {}) + }) + ).forEach((node) => { + provenWidgetValuesForm(node, {}, serializedOf(node)) + }) +} + +beforeEach(() => { + resetWidgetFormSuppressionTally() + useNodeDefStore().updateNodeDefs([]) +}) + +describe('the proven widget form', () => { + it('declares the live order for a node nothing interfered with', () => { + const node = nodeWith('Plain', (n) => { + n.addWidget('number', 'steps', 20, () => {}) + n.addWidget('text', 'prompt', 'hello', () => {}) + }) + + expect(widgetValuesFormVerdict(node)).toEqual({ + declared: true, + form: { order: ['steps', 'prompt'] } + }) + expect(widgetFormSuppressionTally()).toEqual([]) + }) + + it('declares nothing for a value-dependent layout, which the catalog owns', () => { + useNodeDefStore().addNodeDef( + nodeDef('Dynamic', { mode: ['COMFY_DYNAMICCOMBO_V3', {}] }) + ) + const node = nodeWith('Dynamic', (n) => { + n.addWidget('combo', 'mode', 'a', () => {}, { values: ['a'] }) + n.addWidget('number', 'mode.steps', 4, () => {}) + }) + + expect(widgetValuesFormVerdict(node)).toMatchObject({ + declared: false, + reason: 'value_dependent_layout' + }) + }) + + it('declares nothing for a missing-node shell that round-trips a stored payload', () => { + const node = nodeWith('Uninstalled', (n) => { + n.addWidget('text', 'UNKNOWN', 'fabricated', () => {}) + }) + node.last_serialization = fromPartial({ + id: 1, + type: 'Uninstalled', + widgets_values: ['real value'], + widgets_values_named: { real_name: 'real value' } + }) + + expect(widgetValuesFormVerdict(node)).toMatchObject({ + declared: false, + reason: 'shell_last_serialization' + }) + }) +}) + +describe('invariant 3 — the wire values still fit the live widgets', () => { + it('ignores a hook value the Agent wire filters out', () => { + const node = nodeWith('VHS_Probe', (n) => { + n.addWidget('text', 'filename', 'clip', () => {}) + const hidden = n.addWidget('text', 'vhslatentpreview', 'x', () => {}) + hidden.serialize = false + n.onSerialize = (data: ISerialisedNode) => { + data.widgets_values_named = { + ...data.widgets_values_named, + vhslatentpreview: 'x' + } + } + }) + + expect(widgetValuesFormVerdict(node)).toEqual({ + declared: true, + form: { order: ['filename'] } + }) + }) + + it('uses the post-hook widget list when the hook drops a widget', () => { + const node = nodeWith('Shrinking', (n) => { + n.addWidget('text', 'prompt', 'a', () => {}) + n.addWidget('text', 'extra', 'b', () => {}) + n.onSerialize = () => { + n.widgets?.pop() + } + }) + + expect(widgetValuesFormVerdict(node)).toEqual({ + declared: true, + form: { order: ['prompt'] } + }) + }) + + it('still declares a form when the hook only reorders the named keys', () => { + // Key order inside `widgets_values_named` is not meaningful — an + // integer-like name is enumeration-reordered by the object itself, which + // is the reason the form exists. Comparing sequences here would refuse a + // pack that broke nothing. + const node = nodeWith('Reordering', (n) => { + n.addWidget('text', '2', 'two', () => {}) + n.addWidget('text', '1', 'one', () => {}) + n.onSerialize = (data: ISerialisedNode) => { + data.widgets_values_named = { '1': 'one', '2': 'two' } + } + }) + + expect(widgetValuesFormVerdict(node)).toEqual({ + declared: true, + form: { order: ['2', '1'] } + }) + }) +}) + +describe('positional compatibility data', () => { + it('ignores positional values because the Agent wire sends named values', () => { + const node = nodeWith('Rewriting', (n) => { + n.addWidget('text', 'prompt', 'a', () => {}) + n.addWidget('text', 'extra', 'b', () => {}) + n.onSerialize = (data: ISerialisedNode) => { + data.widgets_values = ['only one'] + } + }) + + expect(widgetValuesFormVerdict(node)).toEqual({ + declared: true, + form: { order: ['prompt', 'extra'] } + }) + }) + + it('counts button widgets, which core serialises and the wire drops', () => { + const node = nodeWith('Buttoned', (n) => { + n.addWidget('text', 'prompt', 'a', () => {}) + n.addWidget('button', 'refresh', 'refresh', () => {}) + }) + + expect(widgetValuesFormVerdict(node)).toEqual({ + declared: true, + form: { order: ['prompt'] } + }) + }) +}) + +describe('the Agent wire value filter', () => { + it('preserves an own __proto__ value', () => { + const node = nodeWith('PrototypeNamed', (n) => { + n.addWidget('text', '__proto__', 'safe', () => {}) + }) + const named = Object.create(null) as Record + Object.defineProperty(named, '__proto__', { + value: 'safe', + enumerable: true + }) + + const values = valueWidgetsOnly(node, named) + + expect(Object.hasOwn(values, '__proto__')).toBe(true) + expect(values.__proto__).toBe('safe') + }) + + it('keeps a value widget when a same-named button appears first', () => { + const node = detachedNodeWith('ButtonTwin', (n) => { + n.addWidget('button', 'shared', 'refresh', () => {}) + n.addWidget('text', 'shared', 'value', () => {}) + }) + + expect(valueWidgetsOnly(node, { shared: 'value' })).toEqual({ + shared: 'value' + }) + }) +}) + +describe('guards on the value filter', () => { + it('refuses an order entry naming a widget core would not serialise', () => { + const node = nodeWith('Hiding', (n) => { + n.addWidget('text', 'prompt', 'a', () => {}) + const hidden = n.addWidget('text', 'hidden', 'b', () => {}) + hidden.serialize = false + }) + + expect( + classifyWidgetValuesForm( + node, + { prompt: 'a', hidden: 'b' }, + serializedOf(node) + ) + ).toMatchObject({ + declared: false, + reason: 'declared_keys_disagree', + detail: { undeclared: ['hidden'] } + }) + }) + + it('refuses an order entry whose value will not travel on the wire', () => { + // `values` goes out as JSON, so only enumerable own keys arrive. An order + // entry backed by a key `Object.hasOwn` can see and `Object.keys` cannot + // would order a value the host never receives. + const node = nodeWith('Residual', (n) => { + n.addWidget('text', 'prompt', 'a', () => {}) + n.addWidget('text', 'residue', 'b', () => {}) + }) + const values: Record = { prompt: 'a' } + Object.defineProperty(values, 'residue', { + value: 'b', + enumerable: false + }) + + expect( + classifyWidgetValuesForm(node, values, serializedOf(node)) + ).toMatchObject({ + declared: false, + reason: 'declared_keys_disagree', + detail: { unvalued: ['residue'] } + }) + }) +}) + +describe('the legitimate shapes a producer cannot describe', () => { + it('reports a value whose widget is gone but whose store entry is not', () => { + const node = nodeWith('Vanishing', (n) => { + n.addWidget('text', 'prompt', 'a', () => {}) + }) + + expect( + classifyWidgetValuesForm( + node, + { prompt: 'a', vanished: 'b' }, + serializedOf(node) + ) + ).toMatchObject({ + declared: false, + reason: 'value_has_no_live_widget', + detail: { names: ['vanished'] } + }) + }) + + it('reports an unnamed value widget', () => { + const node = nodeWith('Unnamed', (n) => { + n.addWidget('text', 'prompt', 'a', () => {}) + n.addWidget('text', '', 'b', () => {}) + }) + + expect(widgetValuesFormVerdict(node)).toMatchObject({ + declared: false, + reason: 'unnamed_value_widget' + }) + }) + + it('reports two value widgets sharing a name', () => { + const node = detachedNodeWith('Duplicated', (n) => { + n.addWidget('text', 'prompt', 'a', () => {}) + n.addWidget('text', 'prompt', 'b', () => {}) + }) + + expect(widgetValuesFormVerdict(node)).toMatchObject({ + declared: false, + reason: 'duplicate_widget_name' + }) + }) + + it('has nothing to declare for a node whose only widget is a button', () => { + const node = nodeWith('OnlyButton', (n) => { + n.addWidget('button', 'refresh', 'refresh', () => {}) + }) + + expect(widgetValuesFormVerdict(node)).toMatchObject({ + declared: false, + reason: 'no_value_widgets' + }) + }) +}) + +describe('the invariant channel', () => { + it('routes a broken invariant through assert without stopping the mint', () => { + const node = nodeWith('Rewriting', (n) => { + n.addWidget('text', 'prompt', 'a', () => {}) + n.addWidget('text', 'extra', 'b', () => {}) + n.onSerialize = (data: ISerialisedNode) => { + data.widgets_values_named = { prompt: 'a' } + } + }) + const serialized = serializedOf(node) + const values = valueWidgetsOnly(node, serialized.widgets_values_named!) + + expect(provenWidgetValuesForm(node, values, serialized)).toBeUndefined() + expect(console.error).toHaveBeenCalledWith( + expect.stringContaining('Agent widget form invariant 3') + ) + }) + + it('names the invariant and the ADR, and keeps values out of the message', () => { + vi.stubEnv('DEV', false) + const reporter = vi.fn() + setAssertReporter(reporter) + onTestFinished(() => setAssertReporter(null)) + const node = nodeWith('Shrinking', (n) => { + n.addWidget('text', 'prompt', 'a', () => {}) + n.addWidget('text', 'extra', 'b', () => {}) + n.onSerialize = (data: ISerialisedNode) => { + data.widgets_values_named = { prompt: 'a' } + } + }) + const serialized = serializedOf(node) + const values = valueWidgetsOnly(node, serialized.widgets_values_named!) + + provenWidgetValuesForm(node, values, serialized) + + expect(reporter).toHaveBeenCalledWith( + expect.stringContaining('Agent widget form invariant 3'), + expect.objectContaining({ nodeType: 'Shrinking' }) + ) + const [message] = reporter.mock.calls[0] as [string] + expect(message).toContain( + 'docs/adr/WIDGET-SERIALIZATION-0047-agent-wire-widget-form-is-proven-not-derived.md' + ) + expect(message).not.toContain('Shrinking') + }) +}) + +describe('invariant 4 — the undeclared-form production signal', () => { + it('reports the class and the reason, once per pair', () => { + useNodeDefStore().addNodeDef( + nodeDef('Dynamic', { mode: ['COMFY_DYNAMICCOMBO_V3', {}] }) + ) + const build = (n: LGraphNode) => { + n.addWidget('combo', 'mode', 'a', () => {}, { values: ['a'] }) + n.addWidget('number', 'mode.steps', 4, () => {}) + } + const values = { mode: 'a', 'mode.steps': 4 } + const first = nodeWith('Dynamic', build) + const repeat = nodeWith('Dynamic', build) + + provenWidgetValuesForm(first, values, serializedOf(first)) + provenWidgetValuesForm(repeat, values, serializedOf(repeat)) + + expect(reportError).toHaveBeenCalledTimes(1) + expect(reportError).toHaveBeenCalledWith( + expect.objectContaining({ + message: expect.stringContaining( + 'object-shaped widget values with no declared form' + ) + }), + expect.objectContaining({ + errorType: 'agent_widget_form_undeclared', + surface: 'agent', + level: 'warning', + tags: { node_type: 'Dynamic', reason: 'value_dependent_layout' }, + fingerprint: [ + 'agent_widget_form_undeclared', + 'value_dependent_layout', + 'Dynamic' + ] + }) + ) + }) + + it('does not report a node that has nothing to declare', () => { + const node = nodeWith('OnlyButton', (n) => { + n.addWidget('button', 'refresh', 'refresh', () => {}) + }) + + expect(provenWidgetValuesForm(node, {}, serializedOf(node))).toBeUndefined() + expect(reportError).not.toHaveBeenCalled() + }) + + it('does not spend the report budget on classes with nothing to declare', () => { + recordNoValueClasses(100) + const node = detachedNodeWith('DuplicatedAfterButtons', (n) => { + n.addWidget('text', 'prompt', 'a', () => {}) + n.addWidget('text', 'prompt', 'b', () => {}) + }) + + provenWidgetValuesForm(node, { prompt: 'b' }, serializedOf(node)) + + expect(reportError).toHaveBeenCalledTimes(1) + expect(reportError).toHaveBeenCalledWith( + expect.any(Error), + expect.objectContaining({ + tags: { + node_type: 'DuplicatedAfterButtons', + reason: 'duplicate_widget_name' + } + }) + ) + }) + + it('keeps a per-class tally a bulk pass can read without telemetry', () => { + useNodeDefStore().addNodeDef( + nodeDef('Dynamic', { mode: ['COMFY_DYNAMICCOMBO_V3', {}] }) + ) + function dynamic(n: LGraphNode) { + n.addWidget('combo', 'mode', 'a', () => {}, { values: ['a'] }) + } + const first = nodeWith('Dynamic', dynamic) + const repeat = nodeWith('Dynamic', dynamic) + const duplicated = detachedNodeWith('Duplicated', (n) => { + n.addWidget('text', 'prompt', 'a', () => {}) + n.addWidget('text', 'prompt', 'b', () => {}) + }) + + provenWidgetValuesForm(first, { mode: 'a' }, serializedOf(first)) + provenWidgetValuesForm(repeat, { mode: 'a' }, serializedOf(repeat)) + provenWidgetValuesForm( + duplicated, + { prompt: 'b' }, + serializedOf(duplicated) + ) + + expect(widgetFormSuppressionTally()).toEqual([ + { nodeType: 'Dynamic', reason: 'value_dependent_layout', count: 2 }, + { nodeType: 'Duplicated', reason: 'duplicate_widget_name', count: 1 } + ]) + }) + + it('classifies and tallies for a bulk pass without reporting', () => { + useNodeDefStore().addNodeDef( + nodeDef('Dynamic', { mode: ['COMFY_DYNAMICCOMBO_V3', {}] }) + ) + const node = nodeWith('Dynamic', (n) => { + n.addWidget('combo', 'mode', 'a', () => {}, { values: ['a'] }) + }) + + expect(widgetValuesFormVerdict(node)).toMatchObject({ declared: false }) + expect(reportError).not.toHaveBeenCalled() + expect(widgetFormSuppressionTally()).toEqual([ + { nodeType: 'Dynamic', reason: 'value_dependent_layout', count: 1 } + ]) + }) +}) diff --git a/src/workbench/extensions/agent/crdt/widgetValuesForm.ts b/src/workbench/extensions/agent/crdt/widgetValuesForm.ts new file mode 100644 index 00000000000..c6556091a06 --- /dev/null +++ b/src/workbench/extensions/agent/crdt/widgetValuesForm.ts @@ -0,0 +1,471 @@ +/** + * Whether the Agent wire may declare a node's widget form, and the four + * invariants that decide it. + * + * `widgets_values_form` tells the host which order its name-keyed registers + * belong in. A node that carries one consults no catalogue on any leg, so a + * wrong form is authoritative and strictly worse than no form: the rule is a + * proof, not a derivation. Where a leg cannot be proven, nothing is declared. + * + * Every check reads the POST-HOOK payload, and that is the whole point. + * `LGraphNode.serializeFromStoreState` writes `widgets_values` / + * `widgets_values_named` from `node.widgets` and *then* calls + * `runExtensionSerializeHook`, which copies an extension's own writes back + * over both fields because they are in `NODE_CANONICAL_FIELDS`. So "one loop + * emits the values and the order, therefore they cannot drift" is false, and + * it is false in exactly the population the hook exists for — third-party + * packs with custom serializers. A pre-hook check would assert the one thing + * that was never in doubt. + * + * See docs/adr/WIDGET-SERIALIZATION-0047-agent-wire-widget-form-is-proven-not-derived.md + */ +import type { WidgetValuesForm } from '@comfyorg/comfy-multi-player' + +import { assert } from '@/base/assert' +import type { LGraphNode } from '@/lib/litegraph/src/LGraphNode' +import type { ISerialisedNode } from '@/lib/litegraph/src/types/serialisation' +import type { IBaseWidget } from '@/lib/litegraph/src/types/widgets' +import { reportError } from '@/platform/telemetry/reportError' +import { useNodeDefStore } from '@/stores/nodeDefStore' +import { useWidgetValueStore } from '@/stores/widgetValueStore' +import type { WidgetState } from '@/types/widgetState' +import { widgetId } from '@/types/widgetId' + +/** The post-hook halves of a serialized node this module reads. */ +type SerializedWidgetValues = Pick + +/** + * Why no form was declared. The first four are invariant violations: the + * values and the order disagree, so declaring either would publish a state no + * other reader sees. The rest are shapes a correct producer legitimately + * cannot describe, and they are the population invariant 4 counts. + */ +type WidgetFormSuppression = + /** Invariant 1 — an entry names no live widget core would serialise. */ + | 'order_names_unserialized_widget' + /** Invariant 2 — declared order and value keys differ in either direction. */ + | 'declared_keys_disagree' + /** Invariant 3 — the hook changed the values carried by the Agent wire. */ + | 'hook_changed_serialized_widgets' + /** The catalogue owns this order: it is a function of the values. */ + | 'value_dependent_layout' + /** A missing-node shell round-trips a stored payload, not live widgets. */ + | 'shell_last_serialization' + /** A custom serialization hook threw before producing a payload. */ + | 'serialization_failed' + /** A value the document carries has no live widget to order. */ + | 'value_has_no_live_widget' + /** Nothing to declare. */ + | 'no_value_widgets' + /** An unnamed widget cannot be addressed by name. */ + | 'unnamed_value_widget' + /** Two value widgets share a name, so the order is ambiguous. */ + | 'duplicate_widget_name' + +/** + * Nothing to declare is not a declaration gap: a node whose only widgets are + * buttons has no named value for a form to order, so counting it would bury + * invariant 4's signal under every such class in the ecosystem. + */ +const UNREPORTED: ReadonlySet = new Set([ + 'no_value_widgets' +]) + +type SuppressedWidgetFormVerdict = { + readonly declared: false + readonly reason: WidgetFormSuppression + readonly detail?: Record +} + +export type WidgetFormVerdict = + | { readonly declared: true; readonly form: WidgetValuesForm } + | SuppressedWidgetFormVerdict + +const ADR = + 'docs/adr/WIDGET-SERIALIZATION-0047-agent-wire-widget-form-is-proven-not-derived.md' + +/** + * Assertion text, one per broken invariant. Membership of this record is what + * makes a reason an invariant violation rather than a shape we cannot + * describe. `assert` forwards the message to external telemetry and groups on + * it, so each is a static description of the invariant that broke plus where + * it is written down — never a value. + */ +const INVARIANT_MESSAGES: Partial> = { + order_names_unserialized_widget: + 'Agent widget form invariant 1: a declared order entry names no live widget with serialize !== false, so the form orders a widget core never serialises — ' + + `see ${ADR}`, + declared_keys_disagree: + 'Agent widget form invariant 2: the declared order and the object-shaped widgets_values keys differ in one direction or the other, so the form either orders an absent value or drops a stored one — ' + + `see ${ADR}`, + hook_changed_serialized_widgets: + 'Agent widget form invariant 3: the extension serialize hook changed which live value widgets reach the Agent wire, so the form no longer describes the values sent — ' + + `see ${ADR}` +} + +const UNDECLARED_FORM_MESSAGE = + 'Agent widget form invariant 4: object-shaped widget values with no declared form' + +const VALUE_DEPENDENT_LAYOUT_INPUT_TYPES = new Set([ + 'COMFY_AUTOGROW_V3', + 'COMFY_DYNAMICCOMBO_V3', + 'COMFY_DYNAMICGROUP_V3' +]) + +export interface WidgetFormSuppressionTally { + /** The node class, so a population is attributable without a join. */ + readonly nodeType: string + readonly reason: WidgetFormSuppression + readonly count: number +} + +const tally = new Map< + string, + { nodeType: string; reason: WidgetFormSuppression; count: number } +>() +const reported = new Set() +const MAX_SUPPRESSION_KEYS = 100 + +const tallyKey = (nodeType: string, reason: WidgetFormSuppression): string => + JSON.stringify([nodeType, reason]) + +/** + * Up to the first 100 distinct suppressions this page session saw, by class + * and reason. + * + * This is the bulk instrument. A corpus run reads it once at the end instead + * of scraping telemetry, and `nodeType` makes the answer a class-by-class + * breakdown rather than a pass/fail. Pair it with + * {@link widgetValuesFormVerdict} to classify a node without minting anything. + */ +export function widgetFormSuppressionTally(): WidgetFormSuppressionTally[] { + return [...tally.values()].map((entry) => ({ ...entry })) +} + +/** Drops the accumulated tally. For tests and for a fresh corpus pass. */ +export function resetWidgetFormSuppressionTally(): void { + tally.clear() + reported.clear() +} + +function record(nodeType: string, reason: WidgetFormSuppression): void { + const key = tallyKey(nodeType, reason) + const seen = tally.get(key) + if (seen) { + seen.count += 1 + return + } + if (tally.size >= MAX_SUPPRESSION_KEYS) return + tally.set(key, { nodeType, reason, count: 1 }) +} + +function firstReport(nodeType: string, reason: WidgetFormSuppression): boolean { + const key = tallyKey(nodeType, reason) + if (reported.has(key) || reported.size >= MAX_SUPPRESSION_KEYS) return false + reported.add(key) + return true +} + +function suppressed( + reason: WidgetFormSuppression, + detail?: Record +): SuppressedWidgetFormVerdict { + return detail + ? { declared: false, reason, detail } + : { declared: false, reason } +} + +function sameNames(left: readonly string[], right: readonly string[]): boolean { + const a = new Set(left) + const b = new Set(right) + return a.size === b.size && [...a].every((name) => b.has(name)) +} + +/** + * Whether the live widget, or the store metadata the intent was keyed by when + * the live widget is missing or omits a field, identifies a value the document + * carries. Unknown widgets fail closed. + */ +export function isValueWidget( + widget: IBaseWidget | undefined, + stored?: WidgetState +): boolean { + if (!widget && !stored) return false + // A destructuring default fires on absent AND present-but-undefined alike, + // which is what `IBaseWidget`'s own optional fields mean: the live widget + // did not state this, so the registration the intent was keyed by answers. + // One construct for both fields, so the two halves of the guard cannot + // drift apart again. + const { type = stored?.type, serialize = stored?.serialize } = widget ?? {} + return type !== 'button' && serialize !== false +} + +/** The named values the document carries, dropping non-value widgets. */ +export function valueWidgetsOnly( + node: LGraphNode, + named: object +): Record { + const filtered: Record = Object.create(null) + const rootGraphId = node.graph?.rootGraph.id + const widgetValueStore = useWidgetValueStore() + for (const [name, value] of Object.entries(named)) { + const stored = rootGraphId + ? widgetValueStore.getWidget(widgetId(rootGraphId, node.id, name)) + : undefined + const carriesValue = node.widgets?.some( + (candidate) => candidate.name === name && isValueWidget(candidate, stored) + ) + if (carriesValue) + Object.defineProperty(filtered, name, { + value, + writable: true, + enumerable: true, + configurable: true + }) + } + return filtered +} + +/** The post-hook payload and the live widget list, read once. */ +interface FormProof { + /** Every live widget's name, serialised or not. */ + readonly liveNames: readonly string[] + /** The names of live widgets whose values the Agent wire carries. */ + readonly valueWidgetNames: readonly string[] + /** The enumerable keys of the object the wire ships. */ + readonly valueNames: readonly string[] + /** The order the form would declare. */ + readonly order: readonly string[] +} + +function formProof( + node: LGraphNode, + values: Record, + _serialized: SerializedWidgetValues +): FormProof { + const live = node.widgets ?? [] + const rootGraphId = node.graph?.rootGraph.id + const widgetValueStore = useWidgetValueStore() + const valueWidgetNames = live + .filter((widget) => { + const stored = rootGraphId + ? widgetValueStore.getWidget( + widgetId(rootGraphId, node.id, widget.name) + ) + : undefined + return isValueWidget(widget, stored) + }) + .map((widget) => widget.name) + return { + liveNames: live.map((widget) => widget.name), + valueWidgetNames, + valueNames: Object.keys(values), + order: valueWidgetNames.filter((name) => Object.hasOwn(values, name)) + } +} + +/** Returns a suppression when this leg of the proof fails, else nothing. */ +type FormProbe = (proof: FormProof) => WidgetFormVerdict | undefined + +/** + * Invariant 3 — compare the key set that survives the Agent wire's value + * filter with the live value widgets. Positional values and extension-private + * entries are not sent, so neither can invalidate this proof. + */ +const hookKeptTheSerialisedWidgets: FormProbe = ({ + valueNames, + valueWidgetNames +}) => + sameNames(valueNames, valueWidgetNames) + ? undefined + : suppressed('hook_changed_serialized_widgets', { + wire: valueNames, + live: valueWidgetNames + }) + +/** + * A document value with no live widget at all is the stored-state family, not + * a broken invariant: the node shed the widget, or was never registered. + * Checked before invariant 1 so the two are not conflated — "there is no + * widget" and "there is one core refuses to serialise" have different causes + * and different fixes. + */ +const everyValueHasALiveWidget: FormProbe = ({ valueNames, liveNames }) => { + const unbacked = valueNames.filter((name) => !liveNames.includes(name)) + return unbacked.length + ? suppressed('value_has_no_live_widget', { names: unbacked }) + : undefined +} + +/** + * Invariant 1 — an order entry must name a live widget core serialises. + * Reachable only if a value for a `serialize: false` widget gets into + * `values`, which `isValueWidget` currently refuses: this is the guard on + * that filter. + */ +const orderNamesSerialisedWidgets: FormProbe = ({ + order, + valueWidgetNames +}) => { + const unserialized = order.filter((name) => !valueWidgetNames.includes(name)) + return unserialized.length + ? suppressed('order_names_unserialized_widget', { names: unserialized }) + : undefined +} + +/** + * Invariant 2 — the object case, as a set difference in BOTH directions. + * Order without a value orders nothing; a value outside the order is residue + * the host would store and never project. Stated against the enumerable keys, + * because those are what travel: the wire ships `values` as JSON, so an own + * property `Object.hasOwn` can see and `Object.keys` cannot is an order entry + * whose value never arrives. + */ +const declaredKeysAgree: FormProbe = ({ valueNames, order }) => { + const undeclared = valueNames.filter((name) => !order.includes(name)) + const unvalued = order.filter((name) => !valueNames.includes(name)) + return undeclared.length || unvalued.length + ? suppressed('declared_keys_disagree', { undeclared, unvalued }) + : undefined +} + +/** Shapes a name-keyed order cannot address, whatever the values say. */ +const orderIsAddressable: FormProbe = ({ order }) => { + if (!order.length) return suppressed('no_value_widgets') + if (order.some((name) => !name.length)) + return suppressed('unnamed_value_widget') + if (new Set(order).size !== order.length) + return suppressed('duplicate_widget_name', { order }) + return undefined +} + +/** + * Ordered most-specific-cause first, so the reason names the thing that + * actually happened rather than its downstream shadow: the hook changing the + * serialised widget set shows up as a key disagreement too, and attributing + * it to the key disagreement would send a reader looking in the wrong place. + */ +const FORM_PROBES: readonly FormProbe[] = [ + everyValueHasALiveWidget, + orderNamesSerialisedWidgets, + declaredKeysAgree, + hookKeptTheSerialisedWidgets, + orderIsAddressable +] + +/** + * Classifies a node's form without declaring, asserting or reporting + * anything. Pure apart from the node-definition read, so a bulk pass can call + * it per node and keep the reason. + */ +export function classifyWidgetValuesForm( + node: LGraphNode, + values: Record, + serialized: SerializedWidgetValues +): WidgetFormVerdict { + // The catalogue owns a value-dependent order; declaring one would close a + // list that is supposed to expand with the selection. + if (layoutDependsOnValues(node)) return suppressed('value_dependent_layout') + + // A missing-node shell round-trips its stored payload verbatim, so the + // serialized values describe a class this build cannot see and the live + // widget list — fabricated or empty — cannot order them. + if (node.last_serialization) return suppressed('shell_last_serialization') + + const proof = formProof(node, values, serialized) + for (const probe of FORM_PROBES) { + const failed = probe(proof) + if (failed) return failed + } + return { declared: true, form: { order: [...proof.order] } } +} + +/** + * Classifies a node end to end, for a bulk pass that holds a node and not a + * serialization. It runs the node's serialization hook and tallies the + * result, but does not assert or report. + */ +export function widgetValuesFormVerdict(node: LGraphNode): WidgetFormVerdict { + if (node.last_serialization) { + const verdict = suppressed('shell_last_serialization') + record(node.type, verdict.reason) + return verdict + } + let serialized: ISerialisedNode + try { + serialized = node.serialize() + } catch { + const verdict = suppressed('serialization_failed') + record(node.type, verdict.reason) + return verdict + } + const named = serialized.widgets_values_named + if (!named) { + const verdict = suppressed('no_value_widgets') + record(node.type, verdict.reason) + return verdict + } + const verdict = classifyWidgetValuesForm( + node, + valueWidgetsOnly(node, named), + serialized + ) + if (!verdict.declared) record(node.type, verdict.reason) + return verdict +} + +/** + * The form to put on the wire, or nothing. + * + * Suppression is the gate in every environment. `assert` throws under DEV + * only, so it is the invariant channel and not the mechanism — and the throw + * is swallowed here on purpose, because every one of these invariants is + * breakable by a third-party pack. A pack must not be able to stop the Agent + * from minting in a developer's browser; it must only be unable to make us + * publish a form that describes the wrong values. + */ +export function provenWidgetValuesForm( + node: LGraphNode, + values: Record, + serialized: SerializedWidgetValues +): WidgetValuesForm | undefined { + const verdict = classifyWidgetValuesForm(node, values, serialized) + if (verdict.declared) return verdict.form + + const nodeType = node.type + record(nodeType, verdict.reason) + const first = + !UNREPORTED.has(verdict.reason) && firstReport(nodeType, verdict.reason) + + const invariantMessage = INVARIANT_MESSAGES[verdict.reason] + if (first && invariantMessage) { + try { + assert(false, invariantMessage, { nodeType, ...verdict.detail }) + } catch { + // Swallowed on purpose; see this function's contract above. + } + } + + // Invariant 4. One report per class and reason: the question is "which + // classes still declare no form, and why", and a corpus pass that mints + // thousands of nodes must answer it without thousands of reports. + if (first) { + reportError(new Error(UNDECLARED_FORM_MESSAGE), { + errorType: 'agent_widget_form_undeclared', + surface: 'agent', + level: 'warning', + tags: { node_type: nodeType, reason: verdict.reason }, + fingerprint: ['agent_widget_form_undeclared', verdict.reason, nodeType], + context: { adr: ADR, ...verdict.detail } + }) + } + + return undefined +} + +function layoutDependsOnValues(node: LGraphNode): boolean { + const definition = useNodeDefStore().fromLGraphNode(node) + return Object.values(definition?.inputs ?? {}).some((spec) => + VALUE_DEPENDENT_LAYOUT_INPUT_TYPES.has(spec.type) + ) +}