From 93da15218edee3f479f3f8718e8827ac3af2959e Mon Sep 17 00:00:00 2001 From: operator Date: Mon, 26 Oct 2026 13:35:20 -0700 Subject: [PATCH 1/8] feat(litegraph): prove a node's widget form rather than deriving it Adds the predicate that gates emitting `widgets_values_form`, plus the ADR amendment explaining why it is a proof and not a derivation. Nothing emits a form yet -- deliberately, so this can be landed and measured first. A node carrying a form is addressed through it and consults no widget catalog on any leg, so the error asymmetry is total: no form keeps today's behaviour, imperfect but loud, while a WRONG form is authoritative and misplaces values with nothing left downstream to disagree with. Hence: emit only where core can prove the final widgets_values is the array it produced from node.widgets. The obvious implementation -- derive the order after runExtensionSerializeHook, since that hook sees the final values -- is wrong twice over. LGraphNode.serialize is not the last writer: SubgraphNode.serializeFromStoreState calls super, hook included, then rebuilds widgets_values from `inputs` filtered to those carrying a widgetId, a different collection than node.widgets (promoted widgets are linked inputs, ADR-SUBGRAPH-PROMOTION-0009). And node.widgets is a public JS API that extensions splice, truncate, reorder and replace wholesale -- the contract ECS-WIDGETS-0023 already documents, not a defect to fix. The proof catches both on array IDENTITY, deliberately not deep equality, since a rebuilt equal-looking array came from a source core cannot see. The flag trap is the most likely way to get this wrong, so it is pinned as test literals. Three predicates look interchangeable: widget.serialize === false governs widgets_values; widget.options.serialize === false governs the API prompt only; promotion checks either. addWidget does not hoist the options-bag flag, so a widget flagged only there DOES occupy a positional slot -- which is why every KSampler serializes 7 values and every LoadImage 2. Both are asserted so a form built from the wrong flag fails rather than shipping one slot short. Seven refusals, each a shape measured in this repo or a shipping pack. Two worth naming: a replayed payload from an unregistered node type never reaches the hook and its widgets are synthesised FROM the stored values as UNKNOWN, UNKNOWN_1, ... so a form there would be valid, authoritative and meaningless; and two serializing widgets sharing a name collapse in the named projection via defineProperty while the document rejects the second address, so listing both would promise an address that does not resolve. Also adds needsFormButHasNone, identifying object-shaped widget values with no form -- the population a form would rescue and that nothing can currently count, which is much of why this gap stayed invisible. widgets_values is typed `unknown` rather than the serialised-node type's WidgetValue[] on purpose: every interesting input here violates that type, so typing the parameter as the expected shape would make the shapes being checked for unrepresentable and the checks dead. Tests: 16 cases. Typecheck, oxlint and the repo's pre-commit gates clean. --- ...023-widget-entities-with-a-legacy-layer.md | 78 +++++ .../src/node/widgetFormProof.test.ts | 284 ++++++++++++++++++ src/lib/litegraph/src/node/widgetFormProof.ts | 175 +++++++++++ 3 files changed, 537 insertions(+) create mode 100644 src/lib/litegraph/src/node/widgetFormProof.test.ts create mode 100644 src/lib/litegraph/src/node/widgetFormProof.ts diff --git a/docs/adr/ECS-WIDGETS-0023-widget-entities-with-a-legacy-layer.md b/docs/adr/ECS-WIDGETS-0023-widget-entities-with-a-legacy-layer.md index f00db0403ac..b23a8640459 100644 --- a/docs/adr/ECS-WIDGETS-0023-widget-entities-with-a-legacy-layer.md +++ b/docs/adr/ECS-WIDGETS-0023-widget-entities-with-a-legacy-layer.md @@ -161,3 +161,81 @@ the registration boundary instead of adding it to renderer inner loops. Bevy's [ECS callback example](https://bevy.org/examples/ecs-entity-component-system/callbacks/) shows a related behavior boundary: a component holds a registered system ID, and the ECS runs that system on demand. + +--- + +## Amended (2026-10-26): a per-node widget form is emitted only where it can be _proven_ + +`widgets_values_form` is a per-node declaration of which widgets serialize and in what order +(`comfy-multi-player` schema amendment A24). A node carrying one is addressed through that form +and **consults no widget catalog on any leg**. That makes the error asymmetry total: + +- A node with **no** form keeps today's catalog behaviour, which is imperfect but visible — a + name that does not resolve is refused loudly. +- A node with a **wrong** form is authoritative. Values are misplaced silently and nothing + downstream has anything left to disagree with. + +So the rule is not "derive the order from `node.widgets`". It is: + +> **Emit a form only where core can prove the final `widgets_values` is the array it itself +> produced from `node.widgets`. Where it cannot prove that, emit nothing.** + +Deriving is a guess dressed as a declaration; proving is not. `proveWidgetForm` +(`src/lib/litegraph/src/node/widgetFormProof.ts`) is that predicate, and it returns an order +**only** alongside `provable: true` — never a partial order beside a refusal. + +### Why deriving does not work, measured + +The obvious implementation — derive after `runExtensionSerializeHook`, since that hook sees the +final values — is wrong for two independent reasons. + +**`LGraphNode.serialize` is not the last writer.** `SubgraphNode.serializeFromStoreState` calls +`super.serializeFromStoreState(state)` — hook included — and _then_ replaces `widgets_values` +from `this.inputs` filtered to those carrying a `widgetId`, or deletes it. That is a different +collection from `node.widgets` (promoted widgets are linked inputs, per +[ADR-SUBGRAPH-PROMOTION-0009](SUBGRAPH-PROMOTION-0009-represent-promoted-widgets-as-linked-inputs.md)), +so a form written at the end of the base method is already stale when the subclass returns. The +proof catches this on **array identity**, deliberately not deep equality: a rebuilt +equal-looking array came from a source core cannot see, and a coincidental match is not evidence. + +**`node.widgets` is a public JavaScript API that extensions mutate**, as the ADR body above +already describes. Shipping packs splice it, truncate it (`this.widgets.length = n`), reorder +it, and replace it wholesale during `onNodeCreated`; `this.serialize_widgets = false` appears in +the low hundreds of repositories. None of that is a defect to fix — it is the contract this ADR +documents — so the form has to tolerate it rather than assume it away. + +### The flag trap, which is the most likely way to get this wrong + +Three predicates look interchangeable and are deliberately different: + +| predicate | effect on `widgets_values` | +| ------------------------------------ | --------------------------------------------- | +| `widget.serialize === false` | **excluded** — the only one that governs it | +| `widget.options.serialize === false` | **not excluded**; affects the API prompt only | +| either false | neither; governs promotion and preview | + +`addWidget` does not hoist the options-bag flag onto the widget, so a widget flagged only there +**does occupy a positional slot.** That is why every `KSampler` serializes 7 values +(`control_after_generate`) and every `LoadImage` serializes 2 (its upload button). A form built +from `options.serialize` is one slot short on both, and both lengths are pinned as literals in +`widgetFormProof.test.ts` so the mistake cannot land twice. + +### Refusals, each a measured shape + +`replayed_serialization` · `widgets_not_serialized` · `values_replaced` · +`values_not_positional` · `length_mismatch` · `duplicate_widget_name` · `unnameable_widget` + +Two are worth calling out. **`replayed_serialization`** covers an unregistered node type, whose +payload is replayed verbatim and never reaches the hook, and whose widgets are _synthesised from +the stored values_ with names `UNKNOWN`, `UNKNOWN_1`, … A form there would be syntactically +valid, authoritative, and meaningless, so it is refused before any other check can accept it. +**`duplicate_widget_name`** covers two serializing widgets sharing a name: the named projection +collapses them via `defineProperty`, and the document rejects the second address outright, so +listing both would promise an address that does not resolve. + +### Scope + +This amendment adds the predicate and a diagnostic (`needsFormButHasNone`, which identifies +object-shaped values with no form — the population a form would rescue and that nothing can +currently count). **Nothing emits a form yet.** The producer is deliberately a later change, so +the predicate can be landed, measured against the custom-node ecosystem, and trusted first. diff --git a/src/lib/litegraph/src/node/widgetFormProof.test.ts b/src/lib/litegraph/src/node/widgetFormProof.test.ts new file mode 100644 index 00000000000..6b9786ab512 --- /dev/null +++ b/src/lib/litegraph/src/node/widgetFormProof.test.ts @@ -0,0 +1,284 @@ +import { describe, expect, it } from 'vitest' + +import { + needsFormButHasNone, + proveWidgetForm +} from '@/lib/litegraph/src/node/widgetFormProof' +import type { IBaseWidget } from '@/lib/litegraph/src/types/widgets' + +/** + * Each case below is a shape measured in the real frontend or in a shipping custom-node pack, + * not a hypothetical. The invariant under test is one-directional and is the whole point: + * + * **either no form, or a form that agrees. Never a form that disagrees.** + * + * A form-carrying node consults no widget catalog, so a wrong form is authoritative and + * cannot be detected downstream. Every `provable: false` assertion here is therefore a + * success, not a limitation. + */ + +function widget(name: string, extra: Partial = {}): IBaseWidget { + return { name, type: 'number', value: 0, ...extra } as IBaseWidget +} + +/** Serialize the way `serialiseWidgetValues` does, and hand back the array identity. */ +function produce(widgets: IBaseWidget[]) { + const values = widgets + .filter((w) => w.serialize !== false) + .map((w) => w.value as unknown) + return { values, serialised: { widgets_values: values } } +} + +describe('proveWidgetForm', () => { + it('proves an ordinary node whose values it produced itself', () => { + const widgets = [ + widget('seed', { value: 1 }), + widget('steps', { value: 20 }) + ] + const { values, serialised } = produce(widgets) + + const proof = proveWidgetForm(widgets, serialised, values, { + serializeWidgets: true + }) + + expect(proof.provable).toBe(true) + expect(proof.order).toEqual(['seed', 'steps']) + expect(proof.refusal).toBeNull() + }) + + it('counts a widget flagged only in its options bag, because widgets_values does', () => { + // The trap that would have shipped a wrong form. `options.serialize === false` excludes a + // widget from the API prompt but NOT from widgets_values, and `addWidget` does not hoist + // the flag. Reading the options bag here yields an order one slot short of the values. + // Measured: every KSampler serializes 7 values because `control_after_generate` is + // options-bag-only, and every LoadImage serializes 2 because its upload button is. + const widgets = [ + widget('seed', { value: 1 }), + widget('control_after_generate', { + value: 'randomize', + options: { serialize: false } + }) + ] + const { values, serialised } = produce(widgets) + + expect(values).toHaveLength(2) + const proof = proveWidgetForm(widgets, serialised, values, { + serializeWidgets: true + }) + + expect(proof.provable).toBe(true) + expect(proof.order).toEqual(['seed', 'control_after_generate']) + }) + + it('excludes a widget flagged on the widget itself, because widgets_values does too', () => { + const widgets = [ + widget('audio', { value: 'clip.mp3' }), + widget('audioUI', { serialize: false }) + ] + const { values, serialised } = produce(widgets) + + const proof = proveWidgetForm(widgets, serialised, values, { + serializeWidgets: true + }) + + expect(proof.provable).toBe(true) + expect(proof.order).toEqual(['audio']) + }) + + describe('refuses rather than guessing', () => { + it('when a subclass or extension replaced the array after we wrote it', () => { + // SubgraphNode.serializeFromStoreState calls super -- hook included -- and then + // rebuilds widgets_values from `inputs` filtered to those carrying a widgetId. That is + // a different collection from node.widgets, so an order derived from node.widgets + // describes the wrong thing. Identity, not deep equality, is what catches it. + const widgets = [widget('a', { value: 1 }), widget('b', { value: 2 })] + const { values } = produce(widgets) + const replaced = { widgets_values: [1, 2] } // equal-looking, different array + + const proof = proveWidgetForm(widgets, replaced, values, { + serializeWidgets: true + }) + + expect(proof.provable).toBe(false) + expect(proof.refusal).toBe('values_replaced') + expect(proof.order).toBeNull() + }) + + it('when a subgraph deleted the values entirely', () => { + // The `delete serialized.widgets_values` branch, taken when every promoted store value + // is undefined. A non-empty order beside no values would promise addresses for nothing. + const widgets = [widget('promoted_a'), widget('promoted_b')] + const { values } = produce(widgets) + + const proof = proveWidgetForm(widgets, {}, values, { + serializeWidgets: true + }) + + expect(proof.provable).toBe(false) + expect(proof.order).toBeNull() + }) + + it('when an extension replaced the array with an object', () => { + // The VHS family: onSerialize sets widgets_values to a dict keyed by every widget name, + // including ones flagged serialize === false, so the keys and any derived order differ. + const widgets = [ + widget('video', { value: 'clip.mp4' }), + widget('vhslatentpreview', { serialize: false }) + ] + const { values } = produce(widgets) + const dict = { + widgets_values: { video: 'clip.mp4', vhslatentpreview: {}, crf: 23 } + } + + const proof = proveWidgetForm(widgets, dict, values, { + serializeWidgets: true + }) + + expect(proof.provable).toBe(false) + expect(proof.refusal).toBe('values_not_positional') + }) + + it('when the payload was replayed from a previous save', () => { + // An unregistered node type is replayed verbatim and never reaches the hook, and its + // widgets are synthesised placeholders built FROM the stored values. A form there would + // read order: ['UNKNOWN', 'UNKNOWN_1'] -- valid, authoritative, meaningless. + const widgets = [ + widget('UNKNOWN', { value: 1 }), + widget('UNKNOWN_1', { value: 2 }) + ] + const { values, serialised } = produce(widgets) + + const proof = proveWidgetForm(widgets, serialised, values, { + serializeWidgets: true, + replayed: true + }) + + expect(proof.provable).toBe(false) + expect(proof.refusal).toBe('replayed_serialization') + expect(proof.order).toBeNull() + }) + + it('and also when the replay is signalled by has_errors', () => { + const widgets = [widget('UNKNOWN', { value: 1 })] + const { values, serialised } = produce(widgets) + + const proof = proveWidgetForm( + widgets, + { ...serialised, has_errors: true }, + values, + { serializeWidgets: true } + ) + + expect(proof.refusal).toBe('replayed_serialization') + }) + + it('when serialize_widgets is falsy', () => { + // `this.serialize_widgets = false` is in the low hundreds of repositories -- rgthree's + // group muters, was-node-suite's fast groups, Crystools' debugger. Widgets exist and no + // values are written. + const widgets = [widget('mode'), widget('filter')] + + const proof = proveWidgetForm(widgets, {}, undefined, { + serializeWidgets: false + }) + + expect(proof.provable).toBe(false) + expect(proof.refusal).toBe('widgets_not_serialized') + }) + + it('when the widget list was spliced after the values were written', () => { + const widgets = [widget('a', { value: 1 }), widget('b', { value: 2 })] + const { values, serialised } = produce(widgets) + widgets.pop() // a pack truncating node.widgets mid-serialize + + const proof = proveWidgetForm(widgets, serialised, values, { + serializeWidgets: true + }) + + expect(proof.provable).toBe(false) + expect(proof.refusal).toBe('length_mismatch') + }) + + it('when two serializing widgets share a name', () => { + // Measured in the corpus: RecordAudio stores 2 values under 1 name, LoadAudio 3 under + // 2. `serialiseWidgetValues` collapses them via defineProperty, and the document + // rejects the second address outright, so an order listing both promises an address + // that does not resolve. + const widgets = [ + widget('audio', { value: 'a' }), + widget('audio', { value: 'b' }) + ] + const { values, serialised } = produce(widgets) + + const proof = proveWidgetForm(widgets, serialised, values, { + serializeWidgets: true + }) + + expect(proof.provable).toBe(false) + expect(proof.refusal).toBe('duplicate_widget_name') + }) + + it('when a widget has no usable name', () => { + const widgets = [widget('ok', { value: 1 }), widget('', { value: 2 })] + const { values, serialised } = produce(widgets) + + const proof = proveWidgetForm(widgets, serialised, values, { + serializeWidgets: true + }) + + expect(proof.provable).toBe(false) + expect(proof.refusal).toBe('unnameable_widget') + }) + }) + + it('never returns an order alongside a refusal', () => { + // The one-directional invariant, asserted directly: no refusal path may leak a partial + // order, because a caller that reads `order` without checking `provable` would then emit + // a wrong form -- the exact outcome this module prevents. + const widgets = [widget('dup', { value: 1 }), widget('dup', { value: 2 })] + const { values, serialised } = produce(widgets) + + for (const proof of [ + proveWidgetForm(widgets, serialised, values, { serializeWidgets: true }), + proveWidgetForm(widgets, serialised, values, { + serializeWidgets: true, + replayed: true + }), + proveWidgetForm(widgets, { widgets_values: { a: 1 } }, values, { + serializeWidgets: true + }), + proveWidgetForm(widgets, {}, undefined, { serializeWidgets: false }), + proveWidgetForm(undefined, {}, undefined, { serializeWidgets: true }) + ]) { + expect(proof.provable).toBe(false) + expect(proof.order).toBeNull() + expect(proof.refusal).not.toBeNull() + } + }) +}) + +describe('needsFormButHasNone', () => { + it('flags an object-shaped payload with no form', () => { + // This is the population a form would rescue and that nothing can currently count: stored + // whole and opaquely, round-trips but is not name-addressable, and the follower drops it + // because it only accepts an array. + expect(needsFormButHasNone({ widgets_values: { video: 'clip.mp4' } })).toBe( + true + ) + }) + + it('does not flag one that already declares a form', () => { + expect( + needsFormButHasNone({ + widgets_values: { video: 'clip.mp4' }, + widgets_values_form: { order: ['video'] } + }) + ).toBe(false) + }) + + it('does not flag ordinary positional values, or an absent payload', () => { + expect(needsFormButHasNone({ widgets_values: [1, 2] })).toBe(false) + expect(needsFormButHasNone({})).toBe(false) + expect(needsFormButHasNone({ widgets_values: null })).toBe(false) + }) +}) diff --git a/src/lib/litegraph/src/node/widgetFormProof.ts b/src/lib/litegraph/src/node/widgetFormProof.ts new file mode 100644 index 00000000000..c92e1c48e30 --- /dev/null +++ b/src/lib/litegraph/src/node/widgetFormProof.ts @@ -0,0 +1,175 @@ +import type { IBaseWidget } from '@/lib/litegraph/src/types/widgets' + +/** + * Whether a node's serialized widget values can be *proven* to describe its own widget list. + * + * This is the gate for emitting `widgets_values_form` — a per-node declaration of which + * widgets serialize and in what order. A node carrying a form is addressed through that form + * and consults no widget catalog on any leg, so **a wrong form is authoritative**: it would + * silently misplace values with no mismatch anywhere to detect it. A node with no form keeps + * today's catalog behaviour, which is merely imperfect. So the asymmetry is total, and the + * rule follows from it: + * + * **Emit only where we can prove the final `widgets_values` is the array we produced from + * `node.widgets`. Otherwise do not emit.** + * + * The naive version of this — "derive the order from `node.widgets` after the extension + * serialize hook" — is wrong, and measurably so. `node.widgets` is a public JavaScript API + * that extensions splice, truncate, reorder and replace wholesale (see ADR-ECS-WIDGETS-0023), + * and `LGraphNode.serialize` is not the last writer: `SubgraphNode.serializeFromStoreState` + * calls `super` — hook included — and then rebuilds `widgets_values` from a different + * collection entirely. Deriving an order is a guess dressed as a declaration. Proving one is + * not. + * + * Nothing here emits a form. This is the predicate and the diagnosis only, so it can be + * landed, measured and trusted before any producer depends on it. + */ + +/** Why a node's widget values could not be proven. `null` reason means they were. */ +export type WidgetFormRefusal = + /** Replayed verbatim from a previous save; this process never built these values. */ + | 'replayed_serialization' + /** `serialize_widgets` is falsy: widgets exist, values were never written. */ + | 'widgets_not_serialized' + /** Values are not the array we produced — an extension or subclass replaced them. */ + | 'values_replaced' + /** Values are an object; shape is the producer's own, not a positional array. */ + | 'values_not_positional' + /** Length disagrees with the serializable widget list. */ + | 'length_mismatch' + /** Two serializing widgets share a name, so a name-keyed order cannot address both. */ + | 'duplicate_widget_name' + /** A widget's name is absent or not a string, so it cannot be an address. */ + | 'unnameable_widget' + +export interface WidgetFormProof { + /** True only when every check below passed. Emit a form if and only if this is true. */ + provable: boolean + /** Set when `provable` is false. */ + refusal: WidgetFormRefusal | null + /** + * The order, present only when `provable`. Never returned alongside a refusal — a partial + * order is the failure mode this module exists to prevent. + */ + order: string[] | null +} + +function refuse(refusal: WidgetFormRefusal): WidgetFormProof { + return { provable: false, refusal, order: null } +} + +/** + * The widgets that contribute a positional value, in order. + * + * `widget.serialize === false` is the ONLY predicate that governs `widgets_values`, and that + * is easy to get wrong because two other spellings look interchangeable: + * `widget.options.serialize === false` excludes a widget from the API prompt but NOT from + * `widgets_values`, and promotion checks either. `addWidget` does not hoist the options-bag + * flag onto the widget, so widgets flagged only there DO occupy positional slots — which is + * why every `KSampler` serializes 7 values (`control_after_generate` is options-bag-only) and + * every `LoadImage` serializes 2 (the upload button is too). Reading `options.serialize` here + * would silently drop both and produce a form one slot short. + */ +function serializingWidgets(widgets: readonly IBaseWidget[]): IBaseWidget[] { + return widgets.filter((widget) => widget.serialize !== false) +} + +/** + * Prove — or refuse to prove — that `serialised.widgets_values` describes `widgets`. + * + * @param widgets the node's live widget list at serialization time + * @param serialised the node payload as it stands AFTER the extension serialize hook + * @param producedValues the array `serialiseWidgetValues` returned BEFORE the hook ran, or + * `undefined` if it never ran. Identity is the proof: if the post-hook value is not this + * same array, something replaced it and we know nothing about what the replacement means. + * @param options `serializeWidgets` is the node's `serialize_widgets` flag; `replayed` marks a + * payload that was replayed from a previous save rather than built in this process. + */ +export function proveWidgetForm( + widgets: readonly IBaseWidget[] | undefined, + // `widgets_values` is deliberately `unknown` rather than the serialised-node type's + // `WidgetValue[]`. Every interesting input here VIOLATES that type: an extension replaced + // the array with an object, or deleted it. Typing the parameter as the shape we expect + // would make the shapes we are checking for unrepresentable, and the checks dead. + serialised: { + widgets_values?: unknown + /** Present when the payload was replayed rather than built. */ + has_errors?: boolean + }, + producedValues: unknown, + options: { serializeWidgets?: boolean; replayed?: boolean } = {} +): WidgetFormProof { + // A replayed payload carries whatever shape some other frontend wrote, and the widget list + // beside it may be synthesised placeholders: an unregistered node type gets widgets named + // `UNKNOWN`, `UNKNOWN_1`, ... from its stored values. A form built there would be + // syntactically valid, authoritative to every consumer, and meaningless. Refuse first, so + // no later check can accidentally accept it. + if (options.replayed || serialised.has_errors) + return refuse('replayed_serialization') + + if (!widgets?.length || !options.serializeWidgets) { + // No values were written. A form with no array to describe is not a weaker claim than + // usual — it is a claim about nothing, and `order` would be read as authoritative. + return refuse('widgets_not_serialized') + } + + const values = serialised.widgets_values + if (producedValues === undefined || values !== producedValues) { + // Identity, deliberately, not deep equality. A subclass or extension that rebuilt an + // equal-looking array did so from a source we cannot see, and a coincidental match is + // not evidence. This is the check that catches `SubgraphNode` and the packs that + // override `serialize` to write values after `super` returns. + return refuse( + Array.isArray(values) ? 'values_replaced' : 'values_not_positional' + ) + } + if (!Array.isArray(values)) return refuse('values_not_positional') + + const serializing = serializingWidgets(widgets) + if (serializing.length !== values.length) { + // Reachable even with an untouched array: a widget mutated its own `serialize` flag + // between the write and this check, or `widgets` was spliced in between. + return refuse('length_mismatch') + } + + const order: string[] = [] + const seen = new Set() + for (const widget of serializing) { + const name = widget.name + if (typeof name !== 'string' || name.length === 0) + return refuse('unnameable_widget') + // `serialiseWidgetValues` builds its named projection with `defineProperty`, so a repeat + // silently overwrites the earlier value and the two become one key. An `order` array + // would keep both and promise an address for each, but the document rejects the second + // (`name#1` is an unknown widget there). Promising an address that does not resolve is + // worse than declining to describe the node. + if (seen.has(name)) return refuse('duplicate_widget_name') + seen.add(name) + order.push(name) + } + + return { provable: true, refusal: null, order } +} + +/** + * True when a node's values are object-shaped with no form to interpret them. + * + * This is the population that cannot be read back today: an object-shaped `widgets_values` is + * stored whole and opaquely, so it round-trips but is not name-addressable, and the follower + * drops it outright because it only accepts an array. Those nodes are exactly the ones a form + * would rescue, and there is currently no way to count them — which is why the gap has stayed + * invisible and unowned. Report it and the question "which classes still need this?" becomes a + * number instead of an argument. + */ +export function needsFormButHasNone(serialised: { + widgets_values?: unknown + widgets_values_form?: unknown +}): boolean { + const values = serialised.widgets_values + return ( + values !== null && + typeof values === 'object' && + !Array.isArray(values) && + serialised.widgets_values_form === undefined + ) +} From fd6b67dbcad111d9af138a29a874c716b64912fe Mon Sep 17 00:00:00 2001 From: bymyself Date: Mon, 26 Oct 2026 14:32:26 -0700 Subject: [PATCH 2/8] test(litegraph): drive the widget-form proof through the real serialize path Four shapes were raised as the most likely way to get `widgets_values_form` wrong in production -- subgraph nodes, promoted widgets, widget projections, DOM widgets -- and nothing executable had settled any of them. These tests construct each one as closely to the real thing as a unit test allows and assert what `proveWidgetForm` actually returns. The predicate is pure, so the answer lives in what it is HANDED, not in the function. Both files therefore serialize a real node and capture `widgets_values` twice: at core's own write site, and as finally returned. The capture rides on `onSerialize` because that hook receives the very object core wrote into, so the array identity the proof turns on is observable through public API; the first test asserts the capture does not itself replace the array, since `runExtensionSerializeHook` rewrites a canonical field only when it is NOT structured-cloneable. Measured, against the final payload: subgraph hosts REFUSE `values_replaced` because the override rebuilds the array from `inputs`, and refuse again when it deletes it outright. Promoted projections carry no own `serialize` property, so every promoted input occupies a slot; an `addCustomWidget` widget contributes a value at core's site and is then dropped by the override, leaving the payload one short. PREVIEW_3D, LOAD_3D, IMAGEUPLOAD and AUDIO_UI all prove, with the order agreeing: LOAD_3D counts its three unflagged buttons, IMAGEUPLOAD counts the options-bag-flagged upload button that `addWidget` does not hoist, AUDIO_UI excludes only the player flagged on the widget itself. AUDIO_RECORD refuses `duplicate_widget_name` -- its player and its button take the input's name, and neither is excluded. `src/lib/` cannot import app layers, so the DOM-widget half lives in `src/extensions/core/` with the widget constructors it drives, and the subgraph half reaches the widget value store through the projection's own setter rather than importing it. One expected failure, pinned as a live defect: `proveWidgetForm` documents `serialised` as the payload "AFTER the extension serialize hook", and at that point a SubgraphNode has not rewritten `widgets_values` yet -- so identity holds, the proof accepts, and the order it returns names two widgets while the final array holds one value. The identity check cannot see a writer that has not run. The test asserts the refusal that should happen and names the fix: refuse when the node's class can still rewrite the payload, which also covers packs that override `serialize`. Also uses the module's exported `WidgetFormRefusal` type for the refusal assertions, which both type-checks the reason strings and clears the knip `unused exported type` finding the parent commit currently fails on. --- docs/architecture/domains/boundaries.json | 1 + .../domains/records/node-widgets.domain.json | 4 + .../core/widgetFormProof.domWidgets.test.ts | 212 ++++++++++++ .../src/node/widgetFormProof.subgraph.test.ts | 308 ++++++++++++++++++ tools/expected-failures/baseline.json | 4 + tools/expected-failures/src/inventory.ts | 2 +- 6 files changed, 530 insertions(+), 1 deletion(-) create mode 100644 src/extensions/core/widgetFormProof.domWidgets.test.ts create mode 100644 src/lib/litegraph/src/node/widgetFormProof.subgraph.test.ts diff --git a/docs/architecture/domains/boundaries.json b/docs/architecture/domains/boundaries.json index 34846421c11..caeb491ffa2 100644 --- a/docs/architecture/domains/boundaries.json +++ b/docs/architecture/domains/boundaries.json @@ -2462,6 +2462,7 @@ "src/extensions/core/customWidgets.ts", "src/extensions/core/saveImageExtraOutput.test.ts", "src/extensions/core/saveImageExtraOutput.ts", + "src/extensions/core/widgetFormProof.domWidgets.test.ts", "src/extensions/core/widgetInputs.refreshCombo.test.ts", "src/extensions/core/widgetInputs.test.ts", "src/extensions/core/widgetInputs.ts", diff --git a/docs/architecture/domains/records/node-widgets.domain.json b/docs/architecture/domains/records/node-widgets.domain.json index 2c9b620448e..17a65e3cb0f 100644 --- a/docs/architecture/domains/records/node-widgets.domain.json +++ b/docs/architecture/domains/records/node-widgets.domain.json @@ -115,6 +115,10 @@ "path": "src/extensions/core/saveImageExtraOutput.ts", "role": "integration" }, + { + "path": "src/extensions/core/widgetFormProof.domWidgets.test.ts", + "role": "integration" + }, { "path": "src/extensions/core/widgetInputs.refreshCombo.test.ts", "role": "integration" diff --git a/src/extensions/core/widgetFormProof.domWidgets.test.ts b/src/extensions/core/widgetFormProof.domWidgets.test.ts new file mode 100644 index 00000000000..0bae7c6dede --- /dev/null +++ b/src/extensions/core/widgetFormProof.domWidgets.test.ts @@ -0,0 +1,212 @@ +import { fromAny } from '@total-typescript/shoehorn' +import { describe, expect, it } from 'vitest' + +import { load3dWidgets } from '@/extensions/core/load3d/load3dWidgets' +import { + audioWidgetExtension, + recordAudioExtension +} from '@/extensions/core/uploadAudio' +import { LGraphNode } from '@/lib/litegraph/src/litegraph' +import { proveWidgetForm } from '@/lib/litegraph/src/node/widgetFormProof' +import type { WidgetFormRefusal } from '@/lib/litegraph/src/node/widgetFormProof' +import type { ISerialisedNode } from '@/lib/litegraph/src/types/serialisation' +import type { IBaseWidget } from '@/lib/litegraph/src/types/widgets' +import { useImageUploadWidget } from '@/renderer/extensions/vueNodes/widgets/composables/useImageUploadWidget' +// Installs LGraphNode.prototype.addDOMWidget, which the audio widget constructors call. +import '@/scripts/domWidget' + +/** + * What {@link proveWidgetForm} returns for DOM widgets, driven through the shipped widget + * constructors rather than hand-built widget objects: `LOAD_3D`, `PREVIEW_3D`, `AUDIO_UI` and + * `IMAGEUPLOAD`, plus `AUDIO_RECORD` because it is the one that collides. + * + * Every assertion below pins which widgets occupy a positional slot, which is the thing three + * systems reconstruct independently today. The flag trap is the whole game: `widget.serialize` + * governs `widgets_values`, `widget.options.serialize` governs the API prompt ONLY, and + * `addWidget` does not hoist the options-bag flag — so a widget flagged only there DOES occupy a + * slot. A form built from the wrong flag comes out a slot short and silently shifts every value + * after it. + * + * The invariant is one-directional — either no form, or a form that agrees; never a form that + * disagrees — so a `provable: false` here is a pass, not a limitation. Subgraph hosts are the + * other three cases and live in `src/lib/litegraph/src/node/widgetFormProof.subgraph.test.ts`. + */ + +interface CapturedSerialization { + final: ISerialisedNode + /** `widgets_values` as core produced it, observed from inside the extension serialize hook. */ + atCoreSite: unknown + widgetsAtCoreSite: readonly IBaseWidget[] | undefined +} + +function serializeWithCapture(node: LGraphNode): CapturedSerialization { + let atCoreSite: unknown + let widgetsAtCoreSite: readonly IBaseWidget[] | undefined + const previous = node.onSerialize + node.onSerialize = function (data: ISerialisedNode) { + atCoreSite = data.widgets_values + widgetsAtCoreSite = this.widgets + previous?.call(this, data) + } + try { + return { final: node.serialize(), atCoreSite, widgetsAtCoreSite } + } finally { + node.onSerialize = previous + } +} + +function proveSerialization(node: LGraphNode) { + const captured = serializeWithCapture(node) + return { + values: captured.final.widgets_values, + proof: proveWidgetForm( + captured.widgetsAtCoreSite, + captured.final, + captured.atCoreSite, + { serializeWidgets: node.serialize_widgets } + ) + } +} + +/** + * The exact shape a refusal must have. Typing the reason as `WidgetFormRefusal` means a renamed + * or deleted refusal fails typecheck here instead of silently becoming an unasserted string. + */ +function refusal(reason: WidgetFormRefusal) { + return { provable: false, refusal: reason, order: null } +} + +/** + * A node as `litegraphService` registers one: `serialize_widgets = true` is set in the generated + * `ComfyNode` constructor, and nothing in litegraph sets it, so a bare `LGraphNode` writes no + * values at all and every case below would refuse for the uninteresting reason. + */ +function registeredNode(title: string): LGraphNode { + const node = new LGraphNode(title) + node.serialize_widgets = true + return node +} + +describe('case 4 — DOM widgets', () => { + it('proves PREVIEW_3D, whose viewport widget occupies a slot', () => { + // The viewport widget is a ComponentWidgetImpl built with `options: { hideInPanel: true }` + // and no serialize flag of either spelling, so it serializes. + const node = registeredNode('Preview3D') + load3dWidgets.PREVIEW_3D(node, 'image', ['PREVIEW_3D', {}], fromAny({})) + + expect(proveSerialization(node)).toEqual({ + values: [''], + proof: { provable: true, refusal: null, order: ['image'] } + }) + }) + + it('proves LOAD_3D, counting its three unflagged buttons', () => { + // `addModelFileButtons` adds three button widgets with NO options bag at all, so each + // occupies a positional slot and serializes its callback-name string. A form describing only + // `model_file` and the viewport would be two slots short of this array. + const node = registeredNode('Load3D') + node.addWidget('combo', 'model_file', 'a.glb', () => {}, { + values: ['a.glb'] + }) + load3dWidgets.LOAD_3D(node, 'image', ['LOAD_3D', {}], fromAny({})) + + expect(proveSerialization(node)).toEqual({ + values: ['a.glb', 'upload3dmodel', 'uploadExtraResources', 'clear', ''], + proof: { + provable: true, + refusal: null, + order: [ + 'model_file', + 'upload 3d model', + 'upload extra resources', + 'clear', + 'image' + ] + } + }) + }) + + it('proves IMAGEUPLOAD at two slots, because the upload button is options-bag-flagged', () => { + // The button is created with `{ serialize: false }` in the OPTIONS bag, which `addWidget` + // does not hoist, so it occupies a slot -- the measured reason every LoadImage serializes 2 + // values. A form built from `options.serialize` would be one slot short and would address + // the button's value as `image`. + const node = registeredNode('LoadImage') + node.addWidget('combo', 'image', 'x.png', () => {}, { values: ['x.png'] }) + useImageUploadWidget()( + node, + 'upload', + ['IMAGEUPLOAD', { imageInputName: 'image' }], + fromAny({}) + ) + + const uploadWidget = node.widgets?.at(-1) + expect(uploadWidget?.serialize).toBeUndefined() + expect(uploadWidget?.options.serialize).toBe(false) + + expect(proveSerialization(node)).toEqual({ + values: ['x.png', 'image'], + proof: { provable: true, refusal: null, order: ['image', 'upload'] } + }) + }) + + it('excludes the AUDIO_UI player, which is flagged on the widget itself', () => { + // AUDIO_UI sets BOTH spellings: `serialize = false` on the widget (out of widgets_values) and + // `options.serialize = false` (out of the API prompt). The upload button beside it is created + // the way AUDIOUPLOAD creates it -- `{ serialize: false }` in the options bag only -- because + // that constructor also reads `app.rootGraph.id` and cannot run without a booted app. + const node = registeredNode('LoadAudio') + // AUDIO_UI reads `node.constructor.nodeData.output_node` and throws without it. A registered + // ComfyNode carries it on the generated subclass; here it is the only static the constructor + // is asked for. + Object.defineProperty(node, 'constructor', { + value: fromAny({ nodeData: { output_node: false } }), + configurable: true + }) + node.addWidget('combo', 'audio', 'a.mp3', () => {}, { values: ['a.mp3'] }) + const audioWidgets = audioWidgetExtension.getCustomWidgets?.(fromAny({})) + if (typeof audioWidgets !== 'object' || audioWidgets instanceof Promise) + throw new TypeError('AUDIO_UI widget constructor unavailable') + audioWidgets.AUDIO_UI(node, 'audioUI', ['AUDIO_UI', {}], fromAny({})) + node.addWidget('button', 'upload', '', () => {}, { serialize: false }) + + expect( + node.widgets?.map((widget) => [ + widget.name, + widget.serialize, + widget.options.serialize + ]) + ).toEqual([ + ['audio', undefined, undefined], + ['audioUI', false, false], + ['upload', undefined, false] + ]) + + expect(proveSerialization(node)).toEqual({ + values: ['a.mp3', ''], + proof: { provable: true, refusal: null, order: ['audio', 'upload'] } + }) + }) + + it('refuses AUDIO_RECORD, whose player and button share one name', () => { + // The constructor adds a DOM widget named after the input and then a button with the SAME + // name, and neither is excluded: the player sets no `serialize` flag at all (unlike AUDIO_UI) + // and the button is options-bag-flagged only. Two slots, one name. The named projection + // collapses them via defineProperty and the document rejects the second address, so listing + // both would promise an address that does not resolve. + const node = registeredNode('RecordAudio') + const recordWidgets = recordAudioExtension.getCustomWidgets?.(fromAny({})) + if (typeof recordWidgets !== 'object' || recordWidgets instanceof Promise) + throw new TypeError('AUDIO_RECORD widget constructor unavailable') + recordWidgets.AUDIO_RECORD(node, 'audio', ['AUDIO_RECORD', {}], fromAny({})) + + expect(node.widgets?.map((widget) => widget.name)).toEqual([ + 'audio', + 'audio' + ]) + expect(proveSerialization(node)).toEqual({ + values: ['', ''], + proof: refusal('duplicate_widget_name') + }) + }) +}) diff --git a/src/lib/litegraph/src/node/widgetFormProof.subgraph.test.ts b/src/lib/litegraph/src/node/widgetFormProof.subgraph.test.ts new file mode 100644 index 00000000000..46bd3291a44 --- /dev/null +++ b/src/lib/litegraph/src/node/widgetFormProof.subgraph.test.ts @@ -0,0 +1,308 @@ +import { beforeEach, describe, expect, it } from 'vitest' + +import { LegacyWidget, LGraphNode } from '@/lib/litegraph/src/litegraph' +import type { Subgraph, SubgraphNode } from '@/lib/litegraph/src/litegraph' +import { proveWidgetForm } from '@/lib/litegraph/src/node/widgetFormProof' +import type { WidgetFormRefusal } from '@/lib/litegraph/src/node/widgetFormProof' +import { + createTestSubgraph, + createTestSubgraphNode, + resetSubgraphFixtureState +} from '@/lib/litegraph/src/subgraph/__fixtures__/subgraphHelpers' +import type { ISerialisedNode } from '@/lib/litegraph/src/types/serialisation' +import type { IBaseWidget } from '@/lib/litegraph/src/types/widgets' + +/** + * What {@link proveWidgetForm} is handed when a REAL `SubgraphNode` serializes: subgraph nodes, + * promoted widgets, and the store projections that stand in for them. + * + * `widgetFormProof.test.ts` tests the predicate against constructed arguments. This file tests + * the arguments, because for a subgraph host that is where the answer lives — the payload has + * two writers and the predicate only sees whichever one the caller shows it. DOM widgets are the + * fourth case and live in `src/extensions/core/widgetFormProof.domWidgets.test.ts`, with the + * widget constructors they drive. + * + * The invariant is one-directional — either no form, or a form that agrees; never a form that + * disagrees — so every `provable: false` here is a pass, not a limitation. + */ + +interface CapturedSerialization { + /** The payload as finally returned, after the subclass override has run. */ + final: ISerialisedNode + /** + * `widgets_values` at core's own write site: produced by `serialiseWidgetValues` and observed + * from inside the extension serialize hook, which is the moment the predicate's docstring calls + * "AFTER the extension serialize hook". For a plain node that is also the final payload. For a + * `SubgraphNode` it is not. + */ + atCoreSite: unknown + /** `node.widgets` read at that same moment. */ + widgetsAtCoreSite: readonly IBaseWidget[] | undefined +} + +/** + * Serialize for real, capturing the payload at core's write site as well as the final one. + * + * The capture rides on `onSerialize` because that hook receives the very object core wrote into, + * so the array IDENTITY the proof turns on is observable without reaching into the module. + * Installing a hook does not perturb that identity: `runExtensionSerializeHook` rewrites a + * canonical field only when it is NOT structured-cloneable, and an array of plain values always + * is. The first test asserts that rather than assuming it. + */ +function serializeWithCapture(node: LGraphNode): CapturedSerialization { + let atCoreSite: unknown + let widgetsAtCoreSite: readonly IBaseWidget[] | undefined + const previous = node.onSerialize + node.onSerialize = function (data: ISerialisedNode) { + atCoreSite = data.widgets_values + widgetsAtCoreSite = this.widgets + previous?.call(this, data) + } + try { + return { final: node.serialize(), atCoreSite, widgetsAtCoreSite } + } finally { + node.onSerialize = previous + } +} + +/** Prove against the payload the caller will actually persist. */ +function proveAgainstFinalPayload( + node: LGraphNode, + captured: CapturedSerialization +) { + return proveWidgetForm(node.widgets, captured.final, captured.atCoreSite, { + serializeWidgets: node.serialize_widgets + }) +} + +/** Prove against core's own post-hook payload, before any subclass has rewritten it. */ +function proveAgainstCoreSitePayload( + node: LGraphNode, + captured: CapturedSerialization +) { + return proveWidgetForm( + captured.widgetsAtCoreSite, + { widgets_values: captured.atCoreSite }, + captured.atCoreSite, + { serializeWidgets: node.serialize_widgets } + ) +} + +/** An interior node with one widget-backed input, ready to be promoted. */ +function interiorNode(widgetName: string, value: number): LGraphNode { + const node = new LGraphNode('Interior') + const input = node.addInput(widgetName, 'number') + node.addOutput('out', 'number') + const widget: LegacyWidget = new LegacyWidget( + { name: widgetName, type: 'number', value, y: 0, options: {}, node }, + node + ) + node.widgets = [widget] + input.widget = { name: widget.name } + return node +} + +/** A subgraph host whose named inputs are promoted from interior widgets. */ +function subgraphHostWithPromotedInputs( + names: readonly string[] +): SubgraphNode { + const subgraph: Subgraph = createTestSubgraph({ + inputs: names.map((name) => ({ name, type: 'number' as const })) + }) + for (const [index, name] of names.entries()) { + const interior = interiorNode(name, index + 1) + subgraph.add(interior) + subgraph.inputNode.slots[index].connect(interior.inputs[0], interior) + } + const host = createTestSubgraphNode(subgraph) + // Mirrors the real subgraph node class in litegraphService, which sets this in its constructor. + // Nothing in litegraph sets it, so without this line no values are written at all and every + // case below would refuse for the uninteresting reason. + host.serialize_widgets = true + return host +} + +/** + * Clear every promoted value through the projection's own setter, which is the only way a value + * reaches the store in production. An all-undefined promoted set is what takes the subgraph's + * `delete serialized.widgets_values` branch. + */ +function clearPromotedValues(node: SubgraphNode): void { + for (const widget of node.widgets) widget.value = undefined +} + +/** + * The exact shape a refusal must have. Typing the reason as `WidgetFormRefusal` means a renamed + * or deleted refusal fails typecheck here instead of silently becoming an unasserted string. + */ +function refusal(reason: WidgetFormRefusal) { + return { provable: false, refusal: reason, order: null } +} + +beforeEach(() => { + resetSubgraphFixtureState() +}) + +describe('the capture harness itself', () => { + it('observes the produced values without replacing them', () => { + const node = new LGraphNode('Plain') + node.serialize_widgets = true + node.addWidget('number', 'seed', 1, () => {}) + node.addWidget('text', 'prompt', 'hi', () => {}) + + const captured = serializeWithCapture(node) + + // Same array object before and after the hook, so an acceptance below is a fact about the + // node and not an artifact of observing it. + expect(captured.final.widgets_values).toBe(captured.atCoreSite) + expect(proveAgainstFinalPayload(node, captured)).toEqual({ + provable: true, + refusal: null, + order: ['seed', 'prompt'] + }) + }) +}) + +describe('case 1 — subgraph nodes', () => { + it('refuses, because the final widgets_values is not the array core produced', () => { + // SubgraphNode.serializeFromStoreState calls super -- extension hook included -- and then + // rebuilds widgets_values from `inputs` filtered to those carrying a widgetId. Equal-looking + // contents, different array, built from a collection core never saw. Identity catches it. + const host = subgraphHostWithPromotedInputs(['alpha', 'beta']) + + const captured = serializeWithCapture(host) + + expect(captured.final.widgets_values).toEqual([1, 2]) + expect(captured.final.widgets_values).not.toBe(captured.atCoreSite) + expect(proveAgainstFinalPayload(host, captured)).toEqual( + refusal('values_replaced') + ) + }) + + it('refuses when the subgraph deletes the values outright', () => { + // The `delete serialized.widgets_values` branch, taken when every promoted store value is + // undefined. A form here would promise addresses into an array the payload does not carry. + const host = subgraphHostWithPromotedInputs(['alpha']) + clearPromotedValues(host) + + const captured = serializeWithCapture(host) + + expect('widgets_values' in captured.final).toBe(false) + const proof = proveAgainstFinalPayload(host, captured) + expect(proof.provable).toBe(false) + expect(proof.order).toBeNull() + }) + + it('reads a fresh widget array on every access, so widgets cannot be identity-checked', () => { + // `widgets` is a computed getter on SubgraphNode: projections off `inputs`, then + // `_extraWidgets`. The array is new on each access even when nothing changed, which is why + // the proof checks the identity of the VALUES and not of the widget list. + const host = subgraphHostWithPromotedInputs(['alpha']) + + expect(host.widgets).not.toBe(host.widgets) + expect(host.widgets).toEqual(host.widgets) + }) +}) + +describe('case 2 — promoted widgets', () => { + it('counts every promoted input, because a projection carries no serialize flag', () => { + // The projection is built fresh from the store and has no own `serialize` property, so + // `serialize !== false` holds and each promoted input occupies a positional slot. + const host = subgraphHostWithPromotedInputs(['alpha', 'beta']) + + expect(host.widgets.map((widget) => widget.name)).toEqual(['alpha', 'beta']) + expect( + host.widgets.some((widget) => Object.hasOwn(widget, 'serialize')) + ).toBe(false) + + const captured = serializeWithCapture(host) + expect(captured.atCoreSite).toEqual([1, 2]) + }) + + it('refuses a host carrying an addCustomWidget widget the final writer then drops', () => { + // `_extraWidgets` are in `node.widgets`, so they DO contribute a value at core's write site -- + // and they are absent from `inputs`, so the subgraph's final rebuild drops them. The payload + // therefore ends up one value short of the widget list that produced it. + const host = subgraphHostWithPromotedInputs(['alpha']) + host.addCustomWidget({ + name: 'extra', + type: 'text', + value: 'hello' + } as IBaseWidget) + + const captured = serializeWithCapture(host) + + expect(captured.atCoreSite).toEqual([1, 'hello']) + expect(captured.final.widgets_values).toEqual([1]) + expect(proveAgainstFinalPayload(host, captured)).toEqual( + refusal('values_replaced') + ) + }) +}) + +describe('case 3 — widget projections', () => { + it('names a projection from the store, not from its display label', () => { + const host = subgraphHostWithPromotedInputs(['alpha']) + expect(host.widgets[0].name).toBe('alpha') + + // Projections read through the store on every property access, with no cache to invalidate. + // Relabelling is a display change and must not move the address a form would publish: the + // name is the stable identifier the document resolves against. + host.widgets[0].label = 'renamed' + expect(host.widgets[0].label).toBe('renamed') + expect(host.widgets[0].name).toBe('alpha') + }) + + it('refuses a projection the store no longer backs, rather than naming it from nowhere', () => { + // A projection whose store value has gone reports `value: undefined` while still occupying a + // slot. The subgraph then deletes the payload, so there is nothing left to describe. + const host = subgraphHostWithPromotedInputs(['alpha']) + clearPromotedValues(host) + + const captured = serializeWithCapture(host) + + expect(host.widgets[0].value).toBeUndefined() + expect(host.widgets[0].name).toBe('alpha') + expect(proveAgainstFinalPayload(host, captured).provable).toBe(false) + }) +}) + +describe('the call site the predicate documents is not the last writer', () => { + /** + * EXPECTED FAILURE — live defect, not a limitation of the test. + * + * `proveWidgetForm` documents `serialised` as "the node payload as it stands AFTER the + * extension serialize hook", and the only place core holds such a payload is the end of + * `LGraphNode.serializeFromStoreState`. At that point a `SubgraphNode` has not yet rewritten + * `widgets_values`, so the identity check -- the predicate's stated defence against exactly + * this subclass -- passes, and the proof returns a form the final payload contradicts. + * + * Below, the accepted order names two widgets while the array the form would be attached to + * ends up holding one value. Emitted, that form is authoritative and misplaces values with + * nothing downstream able to disagree. + * + * The fix is to stop making the caller responsible for knowing it stands at the last writer: + * refuse when the node's class can still rewrite the payload -- when the node's + * `serializeFromStoreState` is not `LGraphNode.prototype`'s -- as a new refusal reason beside + * the existing seven. Core can make that check from what it already has, it covers packs that + * override `serialize` as well as `SubgraphNode`, and it keeps the module's own rule intact: + * prove core is the last writer, do not assume it. + */ + it.fails('refuses a subgraph host at core own post-hook payload', () => { + const host = subgraphHostWithPromotedInputs(['alpha']) + host.addCustomWidget({ + name: 'extra', + type: 'text', + value: 'hello' + } as IBaseWidget) + + const captured = serializeWithCapture(host) + const proof = proveAgainstCoreSitePayload(host, captured) + + // What the form would claim, against what the payload finally holds. + expect(proof.order).toEqual(['alpha', 'extra']) + expect(captured.final.widgets_values).toEqual([1]) + + expect(proof.provable).toBe(false) + }) +}) diff --git a/tools/expected-failures/baseline.json b/tools/expected-failures/baseline.json index 164e53a62a4..356a1c16c5d 100644 --- a/tools/expected-failures/baseline.json +++ b/tools/expected-failures/baseline.json @@ -83,6 +83,10 @@ "id": "vitest:src/lib/litegraph/src/LGraphCanvas.gesture.test.ts:releases a hovered node with the pointerup event:1", "classification": "live-defect" }, + { + "id": "vitest:src/lib/litegraph/src/node/widgetFormProof.subgraph.test.ts:refuses a subgraph host at core own post-hook payload:1", + "classification": "live-defect" + }, { "id": "vitest:src/platform/workflow/persistence/base/hashUtil.test.ts:produces different hashes for known collision paths:1", "classification": "live-defect" diff --git a/tools/expected-failures/src/inventory.ts b/tools/expected-failures/src/inventory.ts index 13cdcc8eb27..580f17aab8a 100644 --- a/tools/expected-failures/src/inventory.ts +++ b/tools/expected-failures/src/inventory.ts @@ -21,7 +21,7 @@ const baselineEntrySchema = z.object({ const baselineSchema = z.array(baselineEntrySchema) type BaselineEntry = z.infer -const LIVE_DEFECT_CEILING = 16 +const LIVE_DEFECT_CEILING = 17 const SOURCE_ROOTS = [ 'apps', From f29bbd05f71e877e2bf7adf51ae4d0d425fd6da6 Mon Sep 17 00:00:00 2001 From: bymyself Date: Tue, 3 Nov 2026 15:18:15 +0000 Subject: [PATCH 3/8] test: drop the code comments from the widget-form proof tests The it titles already carry the facts each case pins; the rationale is in the PR description. Addresses review feedback: https://github.com/Comfy-Org/ComfyUI_frontend/pull/22017#discussion_r4434090818 --- .../core/widgetFormProof.domWidgets.test.ts | 49 -------------- .../widgets/widgetFormProof.subgraph.test.ts | 67 ------------------- 2 files changed, 116 deletions(-) diff --git a/src/extensions/core/widgetFormProof.domWidgets.test.ts b/src/extensions/core/widgetFormProof.domWidgets.test.ts index 5b620c43ca7..d3cf5bb758e 100644 --- a/src/extensions/core/widgetFormProof.domWidgets.test.ts +++ b/src/extensions/core/widgetFormProof.domWidgets.test.ts @@ -13,29 +13,10 @@ import { LGraphNode } from '@/lib/litegraph/src/litegraph' import { proveWidgetForm } from '@/lib/litegraph/src/widgets/widgetFormProof' import type { WidgetFormProof } from '@/lib/litegraph/src/widgets/widgetFormProof' import { useImageUploadWidget } from '@/renderer/extensions/vueNodes/widgets/composables/useImageUploadWidget' -// Installs LGraphNode.prototype.addDOMWidget, which the audio widget constructors call. import '@/scripts/domWidget' -/** - * What {@link proveWidgetForm} returns for DOM widgets, driven through the shipped widget - * constructors rather than hand-built widget objects: `LOAD_3D`, `PREVIEW_3D`, `AUDIO_UI` and - * `IMAGEUPLOAD`, plus `AUDIO_RECORD` because it is the one that collides. - * - * Every assertion below pins which widgets occupy a positional slot, which is the thing three - * systems reconstruct independently today. The flag trap is the whole game: `widget.serialize` - * governs `widgets_values`, `widget.options.serialize` governs the API prompt ONLY, and - * `addWidget` does not hoist the options-bag flag — so a widget flagged only there DOES occupy a - * slot. A form built from the wrong flag comes out a slot short and silently shifts every value - * after it. - * - * The invariant is one-directional — either no form, or a form that agrees; never a form that - * disagrees — so a `provable: false` here is a pass, not a limitation. Subgraph hosts are the - * other three cases and live in `src/lib/litegraph/src/widgets/widgetFormProof.subgraph.test.ts`. - */ - interface CapturedSerialization { final: ISerialisedNode - /** `widgets_values` as core produced it, observed from inside the extension serialize hook. */ atCoreSite: unknown widgetsAtCoreSite: readonly IBaseWidget[] | undefined } @@ -76,19 +57,10 @@ function proveSerialization(node: LGraphNode) { } } -/** - * The exact shape a refusal must have. Typing the reason as `WidgetFormRefusal` means a renamed - * or deleted refusal fails typecheck here instead of silently becoming an unasserted string. - */ function refusal(reason: NonNullable) { return { provable: false, refusal: reason, order: null } } -/** - * A node as `litegraphService` registers one: `serialize_widgets = true` is set in the generated - * `ComfyNode` constructor, and nothing in litegraph sets it, so a bare `LGraphNode` writes no - * values at all and every case below would refuse for the uninteresting reason. - */ function registeredNode(title: string): LGraphNode { const node = new LGraphNode(title) node.serialize_widgets = true @@ -97,8 +69,6 @@ function registeredNode(title: string): LGraphNode { describe('case 4 — DOM widgets', () => { it('proves PREVIEW_3D, whose viewport widget occupies a slot', () => { - // The viewport widget is a ComponentWidgetImpl built with `options: { hideInPanel: true }` - // and no serialize flag of either spelling, so it serializes. const node = registeredNode('Preview3D') load3dWidgets.PREVIEW_3D(node, 'image', ['PREVIEW_3D', {}], fromAny({})) @@ -109,9 +79,6 @@ describe('case 4 — DOM widgets', () => { }) it('proves LOAD_3D, counting its three unflagged buttons', () => { - // `addModelFileButtons` adds three button widgets with NO options bag at all, so each - // occupies a positional slot and serializes its callback-name string. A form describing only - // `model_file` and the viewport would be two slots short of this array. const node = registeredNode('Load3D') node.addWidget('combo', 'model_file', 'a.glb', () => {}, { values: ['a.glb'] @@ -135,10 +102,6 @@ describe('case 4 — DOM widgets', () => { }) it('proves IMAGEUPLOAD at two slots, because the upload button is options-bag-flagged', () => { - // The button is created with `{ serialize: false }` in the OPTIONS bag, which `addWidget` - // does not hoist, so it occupies a slot -- the measured reason every LoadImage serializes 2 - // values. A form built from `options.serialize` would be one slot short and would address - // the button's value as `image`. const node = registeredNode('LoadImage') node.addWidget('combo', 'image', 'x.png', () => {}, { values: ['x.png'] }) useImageUploadWidget()( @@ -159,14 +122,7 @@ describe('case 4 — DOM widgets', () => { }) it('excludes the AUDIO_UI player, which is flagged on the widget itself', () => { - // AUDIO_UI sets BOTH spellings: `serialize = false` on the widget (out of widgets_values) and - // `options.serialize = false` (out of the API prompt). The upload button beside it is created - // the way AUDIOUPLOAD creates it -- `{ serialize: false }` in the options bag only -- because - // that constructor also reads `app.rootGraph.id` and cannot run without a booted app. const node = registeredNode('LoadAudio') - // AUDIO_UI reads `node.constructor.nodeData.output_node` and throws without it. A registered - // ComfyNode carries it on the generated subclass; here it is the only static the constructor - // is asked for. Object.defineProperty(node, 'constructor', { value: fromAny({ nodeData: { output_node: false } }), configurable: true @@ -197,11 +153,6 @@ describe('case 4 — DOM widgets', () => { }) it('refuses AUDIO_RECORD, whose player and button share one name', () => { - // The constructor adds a DOM widget named after the input and then a button with the SAME - // name, and neither is excluded: the player sets no `serialize` flag at all (unlike AUDIO_UI) - // and the button is options-bag-flagged only. Two slots, one name. The named projection - // collapses them via defineProperty and the document rejects the second address, so listing - // both would promise an address that does not resolve. const node = registeredNode('RecordAudio') const recordWidgets = recordAudioExtension.getCustomWidgets?.(fromAny({})) if (typeof recordWidgets !== 'object' || recordWidgets instanceof Promise) diff --git a/src/lib/litegraph/src/widgets/widgetFormProof.subgraph.test.ts b/src/lib/litegraph/src/widgets/widgetFormProof.subgraph.test.ts index cdcf9bcafe6..3bd85e1985c 100644 --- a/src/lib/litegraph/src/widgets/widgetFormProof.subgraph.test.ts +++ b/src/lib/litegraph/src/widgets/widgetFormProof.subgraph.test.ts @@ -13,43 +13,12 @@ import { import { proveWidgetForm } from '@/lib/litegraph/src/widgets/widgetFormProof' import type { WidgetFormProof } from '@/lib/litegraph/src/widgets/widgetFormProof' -/** - * What {@link proveWidgetForm} is handed when a REAL `SubgraphNode` serializes: subgraph nodes, - * promoted widgets, and the store projections that stand in for them. - * - * `widgetFormProof.test.ts` tests the predicate against constructed arguments. This file tests - * the arguments, because for a subgraph host that is where the answer lives — the payload has - * two writers and the predicate only sees whichever one the caller shows it. DOM widgets are the - * fourth case and live in `src/extensions/core/widgetFormProof.domWidgets.test.ts`, with the - * widget constructors they drive. - * - * The invariant is one-directional — either no form, or a form that agrees; never a form that - * disagrees — so every `provable: false` here is a pass, not a limitation. - */ - interface CapturedSerialization { - /** The payload as finally returned, after the subclass override has run. */ final: ISerialisedNode - /** - * `widgets_values` at core's own write site: produced by `serialiseWidgetValues` and observed - * from inside the extension serialize hook, which is the moment the predicate's docstring calls - * "AFTER the extension serialize hook". For a plain node that is also the final payload. For a - * `SubgraphNode` it is not. - */ atCoreSite: unknown - /** `node.widgets` read at that same moment. */ widgetsAtCoreSite: readonly IBaseWidget[] | undefined } -/** - * Serialize for real, capturing the payload at core's write site as well as the final one. - * - * The capture rides on `onSerialize` because that hook receives the very object core wrote into, - * so the array IDENTITY the proof turns on is observable without reaching into the module. - * Installing a hook does not perturb that identity: `runExtensionSerializeHook` rewrites a - * canonical field only when it is NOT structured-cloneable, and an array of plain values always - * is. The first test asserts that rather than assuming it. - */ function serializeWithCapture(node: LGraphNode): CapturedSerialization { let atCoreSite: unknown let widgetsAtCoreSite: readonly IBaseWidget[] | undefined @@ -74,7 +43,6 @@ function coreIsLastWriter(node: LGraphNode): boolean { ) } -/** Prove against the payload the caller will actually persist. */ function proveAgainstFinalPayload( node: LGraphNode, captured: CapturedSerialization, @@ -87,7 +55,6 @@ function proveAgainstFinalPayload( }) } -/** Prove against core's own post-hook payload, before any subclass has rewritten it. */ function proveAgainstCoreSitePayload( node: LGraphNode, captured: CapturedSerialization @@ -104,7 +71,6 @@ function proveAgainstCoreSitePayload( ) } -/** An interior node with one widget-backed input, ready to be promoted. */ function interiorNode(widgetName: string, value: number): LGraphNode { const node = new LGraphNode('Interior') const input = node.addInput(widgetName, 'number') @@ -118,7 +84,6 @@ function interiorNode(widgetName: string, value: number): LGraphNode { return node } -/** A subgraph host whose named inputs are promoted from interior widgets. */ function subgraphHostWithPromotedInputs( names: readonly string[] ): SubgraphNode { @@ -131,26 +96,14 @@ function subgraphHostWithPromotedInputs( subgraph.inputNode.slots[index].connect(interior.inputs[0], interior) } const host = createTestSubgraphNode(subgraph) - // Mirrors the real subgraph node class in litegraphService, which sets this in its constructor. - // Nothing in litegraph sets it, so without this line no values are written at all and every - // case below would refuse for the uninteresting reason. host.serialize_widgets = true return host } -/** - * Clear every promoted value through the projection's own setter, which is the only way a value - * reaches the store in production. An all-undefined promoted set is what takes the subgraph's - * `delete serialized.widgets_values` branch. - */ function clearPromotedValues(node: SubgraphNode): void { for (const widget of node.widgets) widget.value = undefined } -/** - * The exact shape a refusal must have. Typing the reason as `WidgetFormRefusal` means a renamed - * or deleted refusal fails typecheck here instead of silently becoming an unasserted string. - */ function refusal(reason: NonNullable) { return { provable: false, refusal: reason, order: null } } @@ -168,8 +121,6 @@ describe('the capture harness itself', () => { const captured = serializeWithCapture(node) - // Same array object before and after the hook, so an acceptance below is a fact about the - // node and not an artifact of observing it. expect(captured.final.widgets_values).toBe(captured.atCoreSite) expect(proveAgainstFinalPayload(node, captured)).toEqual({ provable: true, @@ -181,9 +132,6 @@ describe('the capture harness itself', () => { describe('case 1 — subgraph nodes', () => { it('refuses a subgraph host, whose serializeFromStoreState rebuilds widgets_values after core', () => { - // SubgraphNode.serializeFromStoreState calls super -- extension hook included -- and then - // rebuilds widgets_values from `inputs` filtered to those carrying a widgetId. Equal-looking - // contents, different array, built from a collection core never saw. Identity catches it. const host = subgraphHostWithPromotedInputs(['alpha', 'beta']) const captured = serializeWithCapture(host) @@ -206,8 +154,6 @@ describe('case 1 — subgraph nodes', () => { }) it('refuses when the subgraph deletes widgets_values because every promoted value is undefined', () => { - // The `delete serialized.widgets_values` branch, taken when every promoted store value is - // undefined. A form here would promise addresses into an array the payload does not carry. const host = subgraphHostWithPromotedInputs(['alpha']) clearPromotedValues(host) @@ -220,9 +166,6 @@ describe('case 1 — subgraph nodes', () => { }) it('reads a fresh widget array on every access, so widgets cannot be identity-checked', () => { - // `widgets` is a computed getter on SubgraphNode: projections off `inputs`, then - // `_extraWidgets`. The array is new on each access even when nothing changed, which is why - // the proof checks the identity of the VALUES and not of the widget list. const host = subgraphHostWithPromotedInputs(['alpha']) expect(host.widgets).not.toBe(host.widgets) @@ -232,8 +175,6 @@ describe('case 1 — subgraph nodes', () => { describe('case 2 — promoted widgets', () => { it('counts every promoted input at core write site, because a projection carries no own serialize flag', () => { - // The projection is built fresh from the store and has no own `serialize` property, so - // `serialize !== false` holds and each promoted input occupies a positional slot. const host = subgraphHostWithPromotedInputs(['alpha', 'beta']) expect(host.widgets.map((widget) => widget.name)).toEqual(['alpha', 'beta']) @@ -246,9 +187,6 @@ describe('case 2 — promoted widgets', () => { }) it('refuses a host whose added widget core serializes but the subgraph rebuild then drops', () => { - // `_extraWidgets` are in `node.widgets`, so they DO contribute a value at core's write site -- - // and they are absent from `inputs`, so the subgraph's final rebuild drops them. The payload - // therefore ends up one value short of the widget list that produced it. const host = subgraphHostWithPromotedInputs(['alpha']) host.addCustomWidget({ name: 'extra', @@ -271,17 +209,12 @@ describe('case 3 — widget projections', () => { const host = subgraphHostWithPromotedInputs(['alpha']) expect(host.widgets[0].name).toBe('alpha') - // Projections read through the store on every property access, with no cache to invalidate. - // Relabelling is a display change and must not move the address a form would publish: the - // name is the stable identifier the document resolves against. host.widgets[0].label = 'renamed' expect(host.widgets[0].label).toBe('renamed') expect(host.widgets[0].name).toBe('alpha') }) it('refuses a projection the store no longer backs, which keeps its name but reads undefined', () => { - // A projection whose store value has gone reports `value: undefined` while still occupying a - // slot. The subgraph then deletes the payload, so there is nothing left to describe. const host = subgraphHostWithPromotedInputs(['alpha']) clearPromotedValues(host) From 1f36a80850258c9cd614c4dd2a4be3af236f497a Mon Sep 17 00:00:00 2001 From: bymyself Date: Tue, 3 Nov 2026 15:19:04 +0000 Subject: [PATCH 4/8] test: drop the subgraph cases that never reach the proof The fresh-widget-array case asserted a SubgraphNode.widgets getter detail, and the relabel case never called proveWidgetForm. Identity of the values is already covered by the values_replaced case. Addresses review feedback: https://github.com/Comfy-Org/ComfyUI_frontend/pull/22017#discussion_r4434090821 --- .../src/widgets/widgetFormProof.subgraph.test.ts | 16 ---------------- 1 file changed, 16 deletions(-) diff --git a/src/lib/litegraph/src/widgets/widgetFormProof.subgraph.test.ts b/src/lib/litegraph/src/widgets/widgetFormProof.subgraph.test.ts index 3bd85e1985c..bd015cfad97 100644 --- a/src/lib/litegraph/src/widgets/widgetFormProof.subgraph.test.ts +++ b/src/lib/litegraph/src/widgets/widgetFormProof.subgraph.test.ts @@ -164,13 +164,6 @@ describe('case 1 — subgraph nodes', () => { refusal('class_may_rewrite_payload') ) }) - - it('reads a fresh widget array on every access, so widgets cannot be identity-checked', () => { - const host = subgraphHostWithPromotedInputs(['alpha']) - - expect(host.widgets).not.toBe(host.widgets) - expect(host.widgets).toEqual(host.widgets) - }) }) describe('case 2 — promoted widgets', () => { @@ -205,15 +198,6 @@ describe('case 2 — promoted widgets', () => { }) describe('case 3 — widget projections', () => { - it('names a projection from the store, not from its display label', () => { - const host = subgraphHostWithPromotedInputs(['alpha']) - expect(host.widgets[0].name).toBe('alpha') - - host.widgets[0].label = 'renamed' - expect(host.widgets[0].label).toBe('renamed') - expect(host.widgets[0].name).toBe('alpha') - }) - it('refuses a projection the store no longer backs, which keeps its name but reads undefined', () => { const host = subgraphHostWithPromotedInputs(['alpha']) clearPromotedValues(host) From 32b1e383d6d59733b7d80769001f0b6b9b408f0d Mon Sep 17 00:00:00 2001 From: bymyself Date: Tue, 3 Nov 2026 15:19:41 +0000 Subject: [PATCH 5/8] test: add the extra subgraph widget through addWidget instead of a cast addWidget on a SubgraphNode routes through its addCustomWidget override into the extra widget list, so the case keeps the same shape without asserting a literal as IBaseWidget. Addresses review feedback: https://github.com/Comfy-Org/ComfyUI_frontend/pull/22017#discussion_r4434090824 --- .../src/widgets/widgetFormProof.subgraph.test.ts | 12 ++---------- 1 file changed, 2 insertions(+), 10 deletions(-) diff --git a/src/lib/litegraph/src/widgets/widgetFormProof.subgraph.test.ts b/src/lib/litegraph/src/widgets/widgetFormProof.subgraph.test.ts index bd015cfad97..9f5cda2d10d 100644 --- a/src/lib/litegraph/src/widgets/widgetFormProof.subgraph.test.ts +++ b/src/lib/litegraph/src/widgets/widgetFormProof.subgraph.test.ts @@ -181,11 +181,7 @@ describe('case 2 — promoted widgets', () => { it('refuses a host whose added widget core serializes but the subgraph rebuild then drops', () => { const host = subgraphHostWithPromotedInputs(['alpha']) - host.addCustomWidget({ - name: 'extra', - type: 'text', - value: 'hello' - } as IBaseWidget) + host.addWidget('text', 'extra', 'hello', () => {}) const captured = serializeWithCapture(host) @@ -213,11 +209,7 @@ describe('case 3 — widget projections', () => { describe('the last writer', () => { it('refuses a subgraph host at core own post-hook payload, before the subclass rewrites it', () => { const host = subgraphHostWithPromotedInputs(['alpha']) - host.addCustomWidget({ - name: 'extra', - type: 'text', - value: 'hello' - } as IBaseWidget) + host.addWidget('text', 'extra', 'hello', () => {}) const captured = serializeWithCapture(host) From 5ac91eced75adacb9ea681c56ccce00f4c5011f6 Mon Sep 17 00:00:00 2001 From: bymyself Date: Tue, 3 Nov 2026 15:26:28 +0000 Subject: [PATCH 6/8] test: drop the projection case that duplicates the deleted-values case It built the same host and made the same proof call as the deleted-values case, with a weaker assertion, and the store entry it described as gone still existed. --- .../src/widgets/widgetFormProof.subgraph.test.ts | 13 ------------- 1 file changed, 13 deletions(-) diff --git a/src/lib/litegraph/src/widgets/widgetFormProof.subgraph.test.ts b/src/lib/litegraph/src/widgets/widgetFormProof.subgraph.test.ts index 9f5cda2d10d..aa4b622a12a 100644 --- a/src/lib/litegraph/src/widgets/widgetFormProof.subgraph.test.ts +++ b/src/lib/litegraph/src/widgets/widgetFormProof.subgraph.test.ts @@ -193,19 +193,6 @@ describe('case 2 — promoted widgets', () => { }) }) -describe('case 3 — widget projections', () => { - it('refuses a projection the store no longer backs, which keeps its name but reads undefined', () => { - const host = subgraphHostWithPromotedInputs(['alpha']) - clearPromotedValues(host) - - const captured = serializeWithCapture(host) - - expect(host.widgets[0].value).toBeUndefined() - expect(host.widgets[0].name).toBe('alpha') - expect(proveAgainstFinalPayload(host, captured).provable).toBe(false) - }) -}) - describe('the last writer', () => { it('refuses a subgraph host at core own post-hook payload, before the subclass rewrites it', () => { const host = subgraphHostWithPromotedInputs(['alpha']) From 8a2f4d91582f2f9c5c06a9ceb1a4c9099d69d626 Mon Sep 17 00:00:00 2001 From: bymyself Date: Tue, 3 Nov 2026 15:30:28 +0000 Subject: [PATCH 7/8] test: narrow the audio widget constructors with assert instead of a branch Awaiting getCustomWidgets removes its Promise arm, so assert.exists is enough and the test bodies carry no conditional. --- .../core/widgetFormProof.domWidgets.test.ts | 20 ++++++++++--------- 1 file changed, 11 insertions(+), 9 deletions(-) diff --git a/src/extensions/core/widgetFormProof.domWidgets.test.ts b/src/extensions/core/widgetFormProof.domWidgets.test.ts index d3cf5bb758e..0aa8c7a2dc6 100644 --- a/src/extensions/core/widgetFormProof.domWidgets.test.ts +++ b/src/extensions/core/widgetFormProof.domWidgets.test.ts @@ -1,5 +1,5 @@ import { fromAny } from '@total-typescript/shoehorn' -import { describe, expect, it } from 'vitest' +import { assert, describe, expect, it } from 'vitest' import type { ISerialisedNode } from '@comfyorg/graph-model/serialisation' import type { IBaseWidget } from '@comfyorg/graph-model/widgets' @@ -121,16 +121,17 @@ describe('case 4 — DOM widgets', () => { }) }) - it('excludes the AUDIO_UI player, which is flagged on the widget itself', () => { + it('excludes the AUDIO_UI player, which is flagged on the widget itself', async () => { const node = registeredNode('LoadAudio') Object.defineProperty(node, 'constructor', { value: fromAny({ nodeData: { output_node: false } }), configurable: true }) node.addWidget('combo', 'audio', 'a.mp3', () => {}, { values: ['a.mp3'] }) - const audioWidgets = audioWidgetExtension.getCustomWidgets?.(fromAny({})) - if (typeof audioWidgets !== 'object' || audioWidgets instanceof Promise) - throw new TypeError('AUDIO_UI widget constructor unavailable') + const audioWidgets = await audioWidgetExtension.getCustomWidgets?.( + fromAny({}) + ) + assert.exists(audioWidgets) audioWidgets.AUDIO_UI(node, 'audioUI', ['AUDIO_UI', {}], fromAny({})) node.addWidget('button', 'upload', '', () => {}, { serialize: false }) @@ -152,11 +153,12 @@ describe('case 4 — DOM widgets', () => { }) }) - it('refuses AUDIO_RECORD, whose player and button share one name', () => { + it('refuses AUDIO_RECORD, whose player and button share one name', async () => { const node = registeredNode('RecordAudio') - const recordWidgets = recordAudioExtension.getCustomWidgets?.(fromAny({})) - if (typeof recordWidgets !== 'object' || recordWidgets instanceof Promise) - throw new TypeError('AUDIO_RECORD widget constructor unavailable') + const recordWidgets = await recordAudioExtension.getCustomWidgets?.( + fromAny({}) + ) + assert.exists(recordWidgets) recordWidgets.AUDIO_RECORD(node, 'audio', ['AUDIO_RECORD', {}], fromAny({})) expect(node.widgets?.map((widget) => widget.name)).toEqual([ From 3adfd4bd7b19942754709e1428ba873123835b1d Mon Sep 17 00:00:00 2001 From: Christian Byrne Date: Wed, 4 Nov 2026 05:33:29 -0800 Subject: [PATCH 8/8] test: share the serialization capture harness and type the fixtures Moves CapturedSerialization, serializeWithCapture and coreIsLastWriter into one litegraph test fixture so the capture point and the last-writer policy have a single definition. Replaces fromAny with fromPartial so the app and node-constructor fixtures keep their shape checked, and stubs requestAnimationFrame in the IMAGEUPLOAD case, whose constructor otherwise schedules a frame that writes to nodeOutputStore during a later test in the same worker. --- .../core/widgetFormProof.domWidgets.test.ts | 63 +++++++------------ .../__fixtures__/widgetFormProofHarness.ts | 34 ++++++++++ .../widgets/widgetFormProof.subgraph.test.ts | 38 ++--------- 3 files changed, 60 insertions(+), 75 deletions(-) create mode 100644 src/lib/litegraph/src/widgets/__fixtures__/widgetFormProofHarness.ts diff --git a/src/extensions/core/widgetFormProof.domWidgets.test.ts b/src/extensions/core/widgetFormProof.domWidgets.test.ts index 0aa8c7a2dc6..34135815115 100644 --- a/src/extensions/core/widgetFormProof.domWidgets.test.ts +++ b/src/extensions/core/widgetFormProof.domWidgets.test.ts @@ -1,8 +1,5 @@ -import { fromAny } from '@total-typescript/shoehorn' -import { assert, describe, expect, it } from 'vitest' - -import type { ISerialisedNode } from '@comfyorg/graph-model/serialisation' -import type { IBaseWidget } from '@comfyorg/graph-model/widgets' +import { fromPartial } from '@total-typescript/shoehorn' +import { assert, describe, expect, it, vi } from 'vitest' import { load3dWidgets } from '@/extensions/core/load3d/load3dWidgets' import { @@ -10,32 +7,18 @@ import { recordAudioExtension } from '@/extensions/core/uploadAudio' import { LGraphNode } from '@/lib/litegraph/src/litegraph' +import type { LGraphNodeConstructor } from '@/lib/litegraph/src/litegraph' +import { + coreIsLastWriter, + serializeWithCapture +} from '@/lib/litegraph/src/widgets/__fixtures__/widgetFormProofHarness' import { proveWidgetForm } from '@/lib/litegraph/src/widgets/widgetFormProof' import type { WidgetFormProof } from '@/lib/litegraph/src/widgets/widgetFormProof' import { useImageUploadWidget } from '@/renderer/extensions/vueNodes/widgets/composables/useImageUploadWidget' +import type { ComfyApp } from '@/scripts/app' import '@/scripts/domWidget' -interface CapturedSerialization { - final: ISerialisedNode - atCoreSite: unknown - widgetsAtCoreSite: readonly IBaseWidget[] | undefined -} - -function serializeWithCapture(node: LGraphNode): CapturedSerialization { - let atCoreSite: unknown - let widgetsAtCoreSite: readonly IBaseWidget[] | undefined - const previous = node.onSerialize - node.onSerialize = function (data: ISerialisedNode) { - atCoreSite = data.widgets_values - widgetsAtCoreSite = this.widgets - previous?.call(this, data) - } - try { - return { final: node.serialize(), atCoreSite, widgetsAtCoreSite } - } finally { - node.onSerialize = previous - } -} +const noApp = () => fromPartial({}) function proveSerialization(node: LGraphNode) { const captured = serializeWithCapture(node) @@ -48,10 +31,7 @@ function proveSerialization(node: LGraphNode) { { serializeWidgets: node.serialize_widgets, replayed: false, - coreIsLastWriter: - node.serialize === LGraphNode.prototype.serialize && - node.serializeFromStoreState === - LGraphNode.prototype.serializeFromStoreState + coreIsLastWriter: coreIsLastWriter(node) } ) } @@ -70,7 +50,7 @@ function registeredNode(title: string): LGraphNode { describe('case 4 — DOM widgets', () => { it('proves PREVIEW_3D, whose viewport widget occupies a slot', () => { const node = registeredNode('Preview3D') - load3dWidgets.PREVIEW_3D(node, 'image', ['PREVIEW_3D', {}], fromAny({})) + load3dWidgets.PREVIEW_3D(node, 'image', ['PREVIEW_3D', {}], noApp()) expect(proveSerialization(node)).toEqual({ values: [''], @@ -83,7 +63,7 @@ describe('case 4 — DOM widgets', () => { node.addWidget('combo', 'model_file', 'a.glb', () => {}, { values: ['a.glb'] }) - load3dWidgets.LOAD_3D(node, 'image', ['LOAD_3D', {}], fromAny({})) + load3dWidgets.LOAD_3D(node, 'image', ['LOAD_3D', {}], noApp()) expect(proveSerialization(node)).toEqual({ values: ['a.glb', 'upload3dmodel', 'uploadExtraResources', 'clear', ''], @@ -104,11 +84,12 @@ describe('case 4 — DOM widgets', () => { it('proves IMAGEUPLOAD at two slots, because the upload button is options-bag-flagged', () => { const node = registeredNode('LoadImage') node.addWidget('combo', 'image', 'x.png', () => {}, { values: ['x.png'] }) + vi.stubGlobal('requestAnimationFrame', vi.fn()) useImageUploadWidget()( node, 'upload', ['IMAGEUPLOAD', { imageInputName: 'image' }], - fromAny({}) + noApp() ) const uploadWidget = node.widgets?.at(-1) @@ -124,15 +105,15 @@ describe('case 4 — DOM widgets', () => { it('excludes the AUDIO_UI player, which is flagged on the widget itself', async () => { const node = registeredNode('LoadAudio') Object.defineProperty(node, 'constructor', { - value: fromAny({ nodeData: { output_node: false } }), + value: fromPartial({ + nodeData: { output_node: false } + }), configurable: true }) node.addWidget('combo', 'audio', 'a.mp3', () => {}, { values: ['a.mp3'] }) - const audioWidgets = await audioWidgetExtension.getCustomWidgets?.( - fromAny({}) - ) + const audioWidgets = await audioWidgetExtension.getCustomWidgets?.(noApp()) assert.exists(audioWidgets) - audioWidgets.AUDIO_UI(node, 'audioUI', ['AUDIO_UI', {}], fromAny({})) + audioWidgets.AUDIO_UI(node, 'audioUI', ['AUDIO_UI', {}], noApp()) node.addWidget('button', 'upload', '', () => {}, { serialize: false }) expect( @@ -155,11 +136,9 @@ describe('case 4 — DOM widgets', () => { it('refuses AUDIO_RECORD, whose player and button share one name', async () => { const node = registeredNode('RecordAudio') - const recordWidgets = await recordAudioExtension.getCustomWidgets?.( - fromAny({}) - ) + const recordWidgets = await recordAudioExtension.getCustomWidgets?.(noApp()) assert.exists(recordWidgets) - recordWidgets.AUDIO_RECORD(node, 'audio', ['AUDIO_RECORD', {}], fromAny({})) + recordWidgets.AUDIO_RECORD(node, 'audio', ['AUDIO_RECORD', {}], noApp()) expect(node.widgets?.map((widget) => widget.name)).toEqual([ 'audio', diff --git a/src/lib/litegraph/src/widgets/__fixtures__/widgetFormProofHarness.ts b/src/lib/litegraph/src/widgets/__fixtures__/widgetFormProofHarness.ts new file mode 100644 index 00000000000..e65e7034fc9 --- /dev/null +++ b/src/lib/litegraph/src/widgets/__fixtures__/widgetFormProofHarness.ts @@ -0,0 +1,34 @@ +import type { ISerialisedNode } from '@comfyorg/graph-model/serialisation' +import type { IBaseWidget } from '@comfyorg/graph-model/widgets' + +import { LGraphNode } from '@/lib/litegraph/src/litegraph' + +export interface CapturedSerialization { + final: ISerialisedNode + atCoreSite: unknown + widgetsAtCoreSite: readonly IBaseWidget[] | undefined +} + +export function serializeWithCapture(node: LGraphNode): CapturedSerialization { + let atCoreSite: unknown + let widgetsAtCoreSite: readonly IBaseWidget[] | undefined + const previous = node.onSerialize + node.onSerialize = function (data: ISerialisedNode) { + atCoreSite = data.widgets_values + widgetsAtCoreSite = this.widgets + previous?.call(this, data) + } + try { + return { final: node.serialize(), atCoreSite, widgetsAtCoreSite } + } finally { + node.onSerialize = previous + } +} + +export function coreIsLastWriter(node: LGraphNode): boolean { + return ( + node.serialize === LGraphNode.prototype.serialize && + node.serializeFromStoreState === + LGraphNode.prototype.serializeFromStoreState + ) +} diff --git a/src/lib/litegraph/src/widgets/widgetFormProof.subgraph.test.ts b/src/lib/litegraph/src/widgets/widgetFormProof.subgraph.test.ts index aa4b622a12a..0a44946745f 100644 --- a/src/lib/litegraph/src/widgets/widgetFormProof.subgraph.test.ts +++ b/src/lib/litegraph/src/widgets/widgetFormProof.subgraph.test.ts @@ -1,8 +1,5 @@ import { beforeEach, describe, expect, it } from 'vitest' -import type { ISerialisedNode } from '@comfyorg/graph-model/serialisation' -import type { IBaseWidget } from '@comfyorg/graph-model/widgets' - import { LegacyWidget, LGraphNode } from '@/lib/litegraph/src/litegraph' import type { Subgraph, SubgraphNode } from '@/lib/litegraph/src/litegraph' import { @@ -10,39 +7,14 @@ import { createTestSubgraphNode, resetSubgraphFixtureState } from '@/lib/litegraph/src/subgraph/__fixtures__/subgraphHelpers' +import type { CapturedSerialization } from '@/lib/litegraph/src/widgets/__fixtures__/widgetFormProofHarness' +import { + coreIsLastWriter, + serializeWithCapture +} from '@/lib/litegraph/src/widgets/__fixtures__/widgetFormProofHarness' import { proveWidgetForm } from '@/lib/litegraph/src/widgets/widgetFormProof' import type { WidgetFormProof } from '@/lib/litegraph/src/widgets/widgetFormProof' -interface CapturedSerialization { - final: ISerialisedNode - atCoreSite: unknown - widgetsAtCoreSite: readonly IBaseWidget[] | undefined -} - -function serializeWithCapture(node: LGraphNode): CapturedSerialization { - let atCoreSite: unknown - let widgetsAtCoreSite: readonly IBaseWidget[] | undefined - const previous = node.onSerialize - node.onSerialize = function (data: ISerialisedNode) { - atCoreSite = data.widgets_values - widgetsAtCoreSite = this.widgets - previous?.call(this, data) - } - try { - return { final: node.serialize(), atCoreSite, widgetsAtCoreSite } - } finally { - node.onSerialize = previous - } -} - -function coreIsLastWriter(node: LGraphNode): boolean { - return ( - node.serialize === LGraphNode.prototype.serialize && - node.serializeFromStoreState === - LGraphNode.prototype.serializeFromStoreState - ) -} - function proveAgainstFinalPayload( node: LGraphNode, captured: CapturedSerialization,