From 5bc255b103698161e9e21ae86d21af7880237743 Mon Sep 17 00:00:00 2001 From: Christian Byrne Date: Sun, 4 Oct 2026 03:01:15 -0700 Subject: [PATCH 01/35] fix(widgets): refuse a widget that cannot be given a unique name (FE-3036) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Two widgets on one node cannot share a name. `WidgetId` is `graphId:nodeId:name`, so the second is the same identity, not a second one to persist — ADR-ECS-0008, "Widget identity keys on `name`". `ensureUniqueWidgetNames` keeps that true by renaming the repeat to `name#1`. It cannot rename a widget whose `name` is not writable, or whose accessor throws (`src/types/widgetId.ts`); today it logs a console warning and the node keeps the ambiguous pair. Enforce the invariant where widgets are registered instead: `node.widgets` is a mutation view, so every add — `addWidget`, a raw `widgets.push`, a splice, a whole-array assignment, and `LGraph.add` itself — commits through `syncWidgetOrder`, which now drops what it cannot name uniquely and reports it as `widget_duplicate_name_refused` on the `graph` surface. First occurrence wins. Because the old check was all-or-nothing, one unrenamable widget also left every renamable collision on the node standing; those are renamed now. This is a repair as much as a restriction. Measured on the parent commit, a node carrying the pair renders no widgets at all — `BaseWidget.setNodeId` bails for every widget on the node, so none is registered and none is drawn, and nothing the user types there survives a reload. Implements the review of #19717, which proposed a serialized `(name, occurrence)` identity so both widgets could be persisted. That design is dropped: it adds a second widget-identity format to preserve a state that should not occur. The ADR records the invariant and the refusal in its place. Proof: - `browser_tests/tests/widgets/unrenamableDuplicateWidgetRefused.spec.ts` — one widget rendered, the typed value saved, and still there after close and reopen. Red on the parent (0 rendered), green here. - `src/types/widgetId.test.ts` and `src/lib/litegraph/src/node/widgetsView.uniqueWidgetName.test.ts` — 34 cases, mutation-proved: 7 mutations, each killed. --- .../unrenamableDuplicateWidgetRefused.spec.ts | 137 +++++++++++ docs/adr/ECS-0008-entity-component-system.md | 25 ++ src/lib/litegraph/src/LGraphNode.ts | 7 + src/lib/litegraph/src/node/widgetsView.ts | 46 ++++ .../node/widgetsView.uniqueWidgetName.test.ts | 229 ++++++++++++++++++ src/types/widgetId.test.ts | 127 ++++++++++ src/types/widgetId.ts | 96 ++++++++ 7 files changed, 667 insertions(+) create mode 100644 browser_tests/tests/widgets/unrenamableDuplicateWidgetRefused.spec.ts create mode 100644 src/lib/litegraph/src/node/widgetsView.uniqueWidgetName.test.ts diff --git a/browser_tests/tests/widgets/unrenamableDuplicateWidgetRefused.spec.ts b/browser_tests/tests/widgets/unrenamableDuplicateWidgetRefused.spec.ts new file mode 100644 index 00000000000..1086f02419c --- /dev/null +++ b/browser_tests/tests/widgets/unrenamableDuplicateWidgetRefused.spec.ts @@ -0,0 +1,137 @@ +import { expect } from '@playwright/test' + +import type { ComfyPage } from '@e2e/fixtures/ComfyPage' +import { comfyPageFixture as test } from '@e2e/fixtures/ComfyPage' +import { TestIds } from '@e2e/fixtures/selectors' +import { openWorkflowFromSidebar } from '@e2e/fixtures/utils/builderTestUtils' + +import { zComfyWorkflow } from '@/platform/workflow/validation/schemas/workflowSchema' + +/** + * Two widgets on one node cannot share a name: `WidgetId` is + * `graphId:nodeId:name`, so the second is the same identity, not a second one + * (ADR-ECS-0008, "Widget identity keys on `name`"). + * + * `ensureUniqueWidgetNames` keeps that true by renaming the repeat to + * `name#1`. It cannot rename a widget whose `name` is not writable — it warns + * and gives up — and the node then carries the ambiguous pair. + * + * Measured on the parent commit, this node renders **no widgets at all**: + * `BaseWidget.setNodeId` bails for every widget on the node, so none is + * registered and none is drawn, while `node.widgets` holds two under one name. + * The invariant is enforced instead — the widget that cannot be made unique is + * refused — and the node goes back to working. + * + * Black-box throughout: everything asserted here is what the canvas renders or + * what the app actually saved. + */ + +const workflowName = `unrenamable-duplicate-widget-${Date.now()}` +const NODE_TYPE = 'DevToolsNodeWithOutputList' +const DUPLICATE_NAME = 'duplicate' +const TYPED_VALUE = 'typed by the user' + +/** + * Patches the node type so every instance gains a second serializable widget + * under a name the first already holds, pinned so it cannot be renamed. On the + * type rather than the instance, so the node rebuilt after a reload carries the + * same pair the save was made from. + */ +async function installUnrenameableDuplicate( + comfyPage: ComfyPage +): Promise { + await comfyPage.page.evaluate( + ({ nodeTypeName, duplicateName }) => { + const nodeType = window.LiteGraph!.registered_node_types[nodeTypeName] + const onNodeCreated = nodeType.prototype.onNodeCreated + nodeType.prototype.onNodeCreated = function (...args) { + onNodeCreated?.apply(this, args) + this.serialize_widgets = true + this.addWidget('string', duplicateName, 'first default', () => {}) + const second = this.addWidget( + 'string', + 'second', + 'second default', + () => {} + ) + Object.defineProperty(second, 'name', { + value: duplicateName, + writable: false, + configurable: false + }) + } + }, + { nodeTypeName: NODE_TYPE, duplicateName: DUPLICATE_NAME } + ) +} + +test.describe( + 'unrenamable duplicate widget name', + { tag: ['@canvas', '@widget', '@vue-nodes'] }, + () => { + test.afterEach(async ({ comfyPage }) => { + await comfyPage.workflow.deleteWorkflow(workflowName) + }) + + test('refuses the widget it cannot name uniquely and keeps the node usable', async ({ + comfyPage + }) => { + await comfyPage.nodeOps.clearGraph() + await installUnrenameableDuplicate(comfyPage) + + const nodeId = await comfyPage.searchBoxV2.addNodeAndGetId( + 'Node With Output List' + ) + const node = comfyPage.vueNodes.getNodeLocator(nodeId) + await expect(node).toBeVisible() + + const duplicateRows = node.getByTestId(TestIds.widgets.widget).filter({ + has: comfyPage.page + .getByTestId(TestIds.widgets.layoutFieldLabel) + .and(comfyPage.page.getByText(DUPLICATE_NAME, { exact: true })) + }) + + await test.step('the canvas shows one widget under the name, not two', async () => { + await expect(duplicateRows).toHaveCount(1) + }) + + await test.step('what the user types is what the app saves', async () => { + const input = duplicateRows.locator('input') + await input.fill(TYPED_VALUE) + await input.blur() + + const savedRequest = comfyPage.page.waitForRequest( + (request) => + request.method() === 'POST' && + decodeURIComponent(new URL(request.url()).pathname).endsWith( + `/workflows/${workflowName}.json` + ) + ) + await comfyPage.menu.topbar.saveWorkflowAs(workflowName) + const saved = zComfyWorkflow.parse( + JSON.parse((await savedRequest).postData() ?? '{}') + ) + const savedNode = saved.nodes.find(({ type }) => type === NODE_TYPE) + + expect(savedNode?.widgets_values).toEqual([TYPED_VALUE]) + }) + + await test.step('and it is still there after closing and reopening', async () => { + await comfyPage.workflow.newBlankWorkflow() + await comfyPage.menu.topbar.closeWorkflowTab(workflowName) + await openWorkflowFromSidebar(comfyPage, workflowName) + + const reopened = comfyPage.page + .getByTestId(TestIds.widgets.widget) + .filter({ + has: comfyPage.page + .getByTestId(TestIds.widgets.layoutFieldLabel) + .and(comfyPage.page.getByText(DUPLICATE_NAME, { exact: true })) + }) + + await expect(reopened).toHaveCount(1) + await expect(reopened.locator('input')).toHaveValue(TYPED_VALUE) + }) + }) + } +) diff --git a/docs/adr/ECS-0008-entity-component-system.md b/docs/adr/ECS-0008-entity-component-system.md index 7f45ac58c04..0fd8fb6a6e7 100644 --- a/docs/adr/ECS-0008-entity-component-system.md +++ b/docs/adr/ECS-0008-entity-component-system.md @@ -180,6 +180,31 @@ derived, re-registering an existing `WidgetId` with a different `type` is a legitimate re-mint rather than an identity collision — which is why `widgetValueStore.registerWidget` overwrites where the minted-id stores reject. +> **Amended (2026-10-04):** "two widgets on one node cannot share a name" is an +> **invariant**, not a limitation to work around. A second widget under a name +> another widget already holds is not a second identity; it is the same +> identity twice, and nothing downstream can tell the two apart. +> +> `ensureUniqueWidgetNames` keeps it true by renaming the repeat to `name#1` +> before any id is derived. Where it cannot — a `name` that is not writable, or +> an accessor that throws (`src/types/widgetId.ts`) — the widget is **refused**: +> `node.widgets` is a mutation view, so every add commits through +> `syncWidgetOrder`, which drops what it cannot name uniquely and reports it +> under the stable `errorType` `widget_duplicate_name_refused`. First +> occurrence wins; renamable collisions elsewhere on the node are still +> renamed. +> +> A serialized `(name, occurrence)` identity was proposed instead, so that both +> widgets could be persisted ([#19717](https://github.com/Comfy-Org/ComfyUI_frontend/pull/19717)). +> It was rejected: it adds a second widget-identity format, read by one +> register and by nothing else, to preserve a state that should not occur. The +> fix belongs where the state is created. +> +> Refusing is also a repair, not only a restriction. Before it, a node carrying +> an ambiguous pair registered **no** widget in the store — `BaseWidget.setNodeId` +> bails for every widget on the node — so nothing the user typed on that node +> survived a reload. + #### Future work The current slot/widget identity split remains the contract. A future proposal diff --git a/src/lib/litegraph/src/LGraphNode.ts b/src/lib/litegraph/src/LGraphNode.ts index d8994056617..90f8696c54e 100644 --- a/src/lib/litegraph/src/LGraphNode.ts +++ b/src/lib/litegraph/src/LGraphNode.ts @@ -2309,6 +2309,13 @@ export class LGraphNode const widget = toConcreteWidget(custom_widget, this) this.widgets.push(widget) + // Two widgets on one node cannot share a name (ADR-ECS-0008). The push + // above commits through the widgets view, which refuses a duplicate it + // cannot rename apart and reports it. Registering or restoring a widget + // that is no longer on the node would write over the widget that kept the + // name, so stop here and hand the caller back the detached widget. + if (!this.widgets.includes(widget)) return widget + // Only register with store if node has a valid ID (is already in a graph). // If the node isn't in a graph yet (id === -1), registration happens // when the node is added via LGraph.add() -> node.onAdded. diff --git a/src/lib/litegraph/src/node/widgetsView.ts b/src/lib/litegraph/src/node/widgetsView.ts index c3431058db3..b52942b7c43 100644 --- a/src/lib/litegraph/src/node/widgetsView.ts +++ b/src/lib/litegraph/src/node/widgetsView.ts @@ -5,9 +5,19 @@ import type { IBaseWidget } from '@/lib/litegraph/src/types/widgets' import { toConcreteWidget } from '@/lib/litegraph/src/widgets/widgetMap' import { useWidgetValueStore } from '@/stores/widgetValueStore' +import { reportError } from '@/platform/telemetry/reportError' +import { dropUnrenamableDuplicateWidgets } from '@/types/widgetId' + import { createArrayMutationView } from '../infrastructure/createMutationView' import { getWidgetIds } from '../utils/widget' +/** + * Stable `errorType` for the one state that breaks widget identity: a node + * holding two widgets under one name that could not be renamed apart, so the + * second is refused. See {@link dropUnrenamableDuplicateWidgets}. + */ +export const DUPLICATE_WIDGET_NAME_ERROR_TYPE = 'widget_duplicate_name_refused' + interface WidgetsViewState { target: IBaseWidget[] view: IBaseWidget[] @@ -18,10 +28,46 @@ interface WidgetsViewState { const states = new WeakMap() const widgetsViewGetters = new WeakSet<() => IBaseWidget[] | undefined>() +/** + * Enforces the unique-name invariant at the one place every widget reaches the + * node: `node.widgets` is a mutation view, so `addWidget`, a raw + * `widgets.push`, a splice and a whole-array assignment all commit through + * here. A widget refused here is never registered with the store and never + * rendered, because it is off the node before either happens. + */ +function refuseAmbiguousWidgets( + node: LGraphNode, + widgets: IBaseWidget[] +): void { + const refused = dropUnrenamableDuplicateWidgets(widgets) + if (!refused.length) return + + for (const widget of refused) { + reportError( + new Error( + `Refused a widget named "${widget.name}": node ${node.id} already has a widget of that name and the duplicate cannot be renamed` + ), + { + errorType: DUPLICATE_WIDGET_NAME_ERROR_TYPE, + surface: 'graph', + level: 'warning', + tags: { node_type: node.type }, + context: { + nodeId: String(node.id), + widgetName: widget.name, + widgetType: widget.type + } + } + ) + } +} + function syncWidgetOrder(node: LGraphNode, widgets: IBaseWidget[]): void { node._widgetSlotsDirty = true const graphId = node.graph?.rootGraph.id + refuseAmbiguousWidgets(node, widgets) + for (const [index, widget] of widgets.entries()) { const concreteWidget = toConcreteWidget(widget, node) widgets[index] = concreteWidget diff --git a/src/lib/litegraph/src/node/widgetsView.uniqueWidgetName.test.ts b/src/lib/litegraph/src/node/widgetsView.uniqueWidgetName.test.ts new file mode 100644 index 00000000000..af9a144b4d9 --- /dev/null +++ b/src/lib/litegraph/src/node/widgetsView.uniqueWidgetName.test.ts @@ -0,0 +1,229 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest' + +import { LGraph, LGraphNode, LiteGraph } from '@/lib/litegraph/src/litegraph' +import { DUPLICATE_WIDGET_NAME_ERROR_TYPE } from '@/lib/litegraph/src/node/widgetsView' +import type { IBaseWidget } from '@/lib/litegraph/src/types/widgets' +import { reportError } from '@/platform/telemetry/reportError' +import { useWidgetValueStore } from '@/stores/widgetValueStore' +import { widgetId } from '@/types/widgetId' + +vi.mock(import('@/platform/telemetry/reportError')) + +/** + * Two widgets on one node cannot share a name: `WidgetId` is + * `graphId:nodeId:name`, so the second is the same identity, not a second one. + * ADR-ECS-0008, "Widget identity keys on `name`". + * + * `ensureUniqueWidgetNames` keeps that true by renaming the repeat to + * `name#1`. It cannot rename a widget whose `name` is not writable, and it + * then leaves every name unchanged — the one state in which a node really + * carries an ambiguous pair. These cases pin the refusal that replaces it. + */ + +function createNode(): LGraphNode { + const graph = new LGraph() + const node = new LGraphNode('test') + graph.add(node) + return node +} + +/** + * Pins `name` on an already-concrete widget, which is how the state is + * actually reached: an extension redefines the property in `onNodeCreated` + * after the widget exists. A non-writable descriptor on the *plain* object + * handed to `addWidget` does not survive — `toConcreteWidget` merges the + * concrete class's writable accessor over it. + */ +function pinName(widget: IBaseWidget, name: string): void { + Object.defineProperty(widget, 'name', { + value: name, + writable: false, + configurable: false, + enumerable: true + }) +} + +function names(node: LGraphNode): string[] { + return (node.widgets ?? []).map((widget) => widget.name) +} + +function storedNames(node: LGraphNode): string[] { + return useWidgetValueStore() + .getNodeWidgets(node.graph!.rootGraph.id, node.id) + .map((widget) => widget.name) +} + +describe('unique widget name invariant', () => { + beforeEach(() => { + LiteGraph.vueNodesMode = false + vi.mocked(reportError).mockClear() + }) + + it('still renames a duplicate it can rename, and reports nothing', () => { + const node = createNode() + node.addWidget('number', 'seed', 1, () => undefined, {}) + node.addWidget('number', 'seed', 2, () => undefined, {}) + + expect(names(node)).toEqual(['seed', 'seed#1']) + expect(storedNames(node)).toEqual(['seed', 'seed#1']) + expect(reportError).not.toHaveBeenCalled() + }) + + it('refuses the duplicate it cannot rename and reports a stable error type', () => { + const node = createNode() + node.addWidget('number', 'seed', 1, () => undefined, {}) + const second = node.addWidget('number', 'steps', 2, () => undefined, {}) + pinName(second, 'seed') + + // A name pinned after the widget exists is caught by the next widgets + // mutation; `LGraph.add` is also one, which is what covers the realistic + // `onNodeCreated` case the next test pins. + node.addWidget('number', 'cfg', 3, () => undefined, {}) + + expect(names(node)).toEqual(['seed', 'cfg']) + expect(node.widgets).not.toContain(second) + expect(reportError).toHaveBeenCalledExactlyOnceWith( + expect.any(Error), + expect.objectContaining({ + errorType: DUPLICATE_WIDGET_NAME_ERROR_TYPE, + surface: 'graph' + }) + ) + }) + + it('reports an error type that stays stable for dashboards and alerts', () => { + // Spelled out rather than compared to the constant: a dashboard query is + // written against this string, so renaming it is the breaking change. + expect(DUPLICATE_WIDGET_NAME_ERROR_TYPE).toBe( + 'widget_duplicate_name_refused' + ) + }) + + it('does not let a refused widget overwrite the stored value of the one that kept the name', () => { + const node = createNode() + const first = node.addWidget('number', 'seed', 1, () => undefined, {}) + const moved = node.addWidget('number', 'steps', 2, () => undefined, {}) + node.widgets!.splice(node.widgets!.indexOf(moved), 1) + pinName(moved, 'seed') + + // Refused inside the add itself, so the add must not go on to register it: + // the id it would register under is the one `first` already holds, and + // registering binds the refused widget's state to that entry. + node.addCustomWidget(moved) + moved.value = 99 + + expect(names(node)).toEqual(['seed']) + expect(first.value).toBe(1) + expect( + useWidgetValueStore().getWidget( + widgetId(node.graph!.rootGraph.id, node.id, 'seed') + )?.value + ).toBe(1) + }) + + it('refuses a pinned duplicate installed before the node joins a graph', () => { + const graph = new LGraph() + const node = new LGraphNode('test') + node.addWidget('custom', 'duplicate', 'first', () => undefined, {}) + const second = node.addWidget('custom', 'second', 'second', () => {}, {}) + pinName(second, 'duplicate') + + graph.add(node) + + expect(names(node)).toEqual(['duplicate']) + expect(storedNames(node)).toEqual(['duplicate']) + expect(reportError).toHaveBeenCalledOnce() + }) + + it('registers the widget that kept the name, which an ambiguous pair blocked', () => { + const node = createNode() + const first = node.addWidget('number', 'seed', 1, () => undefined, {}) + const second = node.addWidget('number', 'steps', 2, () => undefined, {}) + pinName(second, 'seed') + node.addWidget('number', 'cfg', 3, () => undefined, {}) + + const store = useWidgetValueStore() + const id = widgetId(node.graph!.rootGraph.id, node.id, 'seed') + expect(store.getWidget(id)?.value).toBe(1) + + first.value = 7 + expect(store.getWidget(id)?.value).toBe(7) + }) + + it('leaves the kept widget untouched when the refused one is written to', () => { + const node = createNode() + const first = node.addWidget('number', 'seed', 1, () => undefined, {}) + const second = node.addWidget('number', 'steps', 2, () => undefined, {}) + pinName(second, 'seed') + node.addWidget('number', 'cfg', 3, () => undefined, {}) + + second.value = 99 + + expect(first.value).toBe(1) + expect( + useWidgetValueStore().getWidget( + widgetId(node.graph!.rootGraph.id, node.id, 'seed') + )?.value + ).toBe(1) + }) + + it('settles a renamable collision the refusal was masking', () => { + const node = createNode() + node.addWidget('number', 'seed', 1, () => undefined, {}) + node.addWidget('number', 'steps', 2, () => undefined, {}) + const third = node.addWidget('number', 'spare', 3, () => undefined, {}) + pinName(third, 'seed') + + // `ensureUniqueWidgetNames` is all-or-nothing, so this renamable repeat + // only stays ambiguous while the unrenamable one is on the node. + node.addWidget('number', 'steps', 4, () => undefined, {}) + + expect(names(node)).toEqual(['seed', 'steps', 'steps#1']) + expect(storedNames(node)).toEqual(['seed', 'steps', 'steps#1']) + }) + + it('refuses a pinned duplicate pushed in raw, not only one added through addWidget', () => { + const node = createNode() + node.addWidget('number', 'seed', 1, () => undefined, {}) + const raw: IBaseWidget = { + name: 'placeholder', + type: 'legacy_test', + value: 5, + options: {}, + y: 0 + } + pinName(raw, 'seed') + + node.widgets!.push(raw) + + expect(names(node)).toEqual(['seed']) + expect(storedNames(node)).toEqual(['seed']) + expect(reportError).toHaveBeenCalledOnce() + }) + + it('refuses the later of a pinned pair carried in by a whole-array assignment', () => { + const node = createNode() + const kept = node.addWidget('number', 'seed', 1, () => undefined, {}) + const other = node.addWidget('number', 'steps', 2, () => undefined, {}) + pinName(other, 'seed') + + // Node packs rebuild the array wholesale rather than adding one at a time. + node.widgets = undefined + node.widgets = [kept, other] + + expect(node.widgets).toEqual([kept]) + expect(reportError).toHaveBeenCalledOnce() + }) + + it('does not refuse one widget object occupying two slots mid-reorder', () => { + const node = createNode() + const first = node.addWidget('number', 'a', 1, () => undefined, {}) + const secondWidget = node.addWidget('number', 'b', 2, () => undefined, {}) + + node.widgets![1] = first + node.widgets![0] = secondWidget + + expect(names(node)).toEqual(['b', 'a']) + expect(reportError).not.toHaveBeenCalled() + }) +}) diff --git a/src/types/widgetId.test.ts b/src/types/widgetId.test.ts index 97b11a447c8..8f252b53781 100644 --- a/src/types/widgetId.test.ts +++ b/src/types/widgetId.test.ts @@ -2,6 +2,7 @@ import { describe, expect, it, vi } from 'vitest' import type { WidgetId } from './widgetId' import { + dropUnrenamableDuplicateWidgets, ensureUniqueWidgetNames, isWidgetId, parseWidgetId, @@ -39,6 +40,132 @@ describe('ensureUniqueWidgetNames', () => { }) }) +describe('dropUnrenamableDuplicateWidgets', () => { + /** A name that cannot be written, which is how the state is reached. */ + const pinned = (name: string) => { + const widget = {} as { name: string } + Object.defineProperty(widget, 'name', { value: name, enumerable: true }) + return widget + } + + it('refuses nothing and mutates nothing when every name is already unique', () => { + const widgets = [{ name: 'seed' }, { name: 'steps' }] + + expect(dropUnrenamableDuplicateWidgets(widgets)).toEqual([]) + expect(widgets.map(({ name }) => name)).toEqual(['seed', 'steps']) + }) + + it('refuses nothing when the duplicate can be renamed', () => { + const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}) + const widgets = [{ name: 'seed' }, { name: 'seed' }] + + expect(dropUnrenamableDuplicateWidgets(widgets)).toEqual([]) + expect(widgets.map(({ name }) => name)).toEqual(['seed', 'seed#1']) + + warn.mockRestore() + }) + + it('keeps the first occurrence and refuses the one it cannot rename', () => { + const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}) + const first = { name: 'seed' } + const refused = pinned('seed') + const widgets = [first, refused] + + expect(dropUnrenamableDuplicateWidgets(widgets)).toEqual([refused]) + expect(widgets).toEqual([first]) + + warn.mockRestore() + }) + + it('renames the collisions the refusal was masking', () => { + const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}) + // `ensureUniqueWidgetNames` is all-or-nothing, so one unrenamable widget + // leaves every other collision on the node standing too. + const refused = pinned('seed') + const widgets = [ + { name: 'seed' }, + { name: 'steps' }, + refused, + { name: 'steps' } + ] + + expect(dropUnrenamableDuplicateWidgets(widgets)).toEqual([refused]) + expect(widgets.map(({ name }) => name)).toEqual([ + 'seed', + 'steps', + 'steps#1' + ]) + + warn.mockRestore() + }) + + it('does not hand a generated name to a widget that already holds it', () => { + const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}) + const refused = pinned('seed') + const widgets = [{ name: 'seed' }, refused, { name: 'seed' }] + // `seed#1` is held outright further down the array, so the rename must + // reach past it rather than collide with a name nothing renamed. + widgets.push({ name: 'seed#1' }) + + expect(dropUnrenamableDuplicateWidgets(widgets)).toEqual([refused]) + expect(widgets.map(({ name }) => name)).toEqual([ + 'seed', + 'seed#2', + 'seed#1' + ]) + + warn.mockRestore() + }) + + it('refuses a widget whose setter silently ignores the rename', () => { + const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}) + const stubborn = { + get name() { + return 'seed' + }, + set name(_value: string) {} + } + const widgets = [{ name: 'seed' }, pinned('seed'), stubborn] + + // Its descriptor has a setter, so a descriptor check believes the rename + // will take; only reading the name back afterwards proves it did not. + expect(dropUnrenamableDuplicateWidgets(widgets)).toContain(stubborn) + expect(widgets.map(({ name }) => name)).toEqual(['seed']) + + warn.mockRestore() + }) + + it('refuses nothing when a name accessor throws', () => { + const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}) + const hostile = { + get name(): string { + throw new Error('name is not readable') + } + } + const widgets = [{ name: 'seed' }, hostile] + + // No readable name is no identity to collide with, so there is nothing to + // refuse — and the throw must not escape into a widgets mutation. + expect(dropUnrenamableDuplicateWidgets(widgets)).toEqual([]) + expect(widgets).toHaveLength(2) + + warn.mockRestore() + }) + + it('does not refuse one widget object occupying two array slots', () => { + const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}) + const shared = pinned('seed') + const other = pinned('seed') + const widgets = [shared, shared, other] + + // Identity duplicates are one widget mid-reorder, not a name collision. + expect(dropUnrenamableDuplicateWidgets(widgets)).toEqual([other]) + expect(widgets).toEqual([shared, shared]) + + warn.mockRestore() + }) +}) + describe('widgetId', () => { const graphId = 'a1b2c3d4-e5f6-7890-abcd-ef1234567890' diff --git a/src/types/widgetId.ts b/src/types/widgetId.ts index eba26ffd1ea..78e6c74086f 100644 --- a/src/types/widgetId.ts +++ b/src/types/widgetId.ts @@ -78,6 +78,102 @@ export function ensureUniqueWidgetNames( } } +/** + * Reads `name` without letting a throwing accessor escape. A widget whose + * `name` cannot be read has no identity to collide with, so it is left alone. + */ +function readName(widget: { name: string }): string | undefined { + try { + return widget.name + } catch { + return undefined + } +} + +/** @returns whether {@link widget} now answers to {@link name}. */ +function tryRename(widget: { name: string }, name: string): boolean { + try { + widget.name = name + // A setter is free to ignore the write, and only a read proves it did not. + return widget.name === name + } catch { + return false + } +} + +/** + * Removes the widgets that cannot be given a unique name, mutating + * {@link widgets} in place, and renames the duplicates that can — keeping the + * first occurrence of each name either way. + * + * `WidgetId` is `graphId:nodeId:name`, so a second widget under a name another + * widget already holds is not a second identity — it is the same identity + * twice. ADR-ECS-0008's "Widget identity keys on `name`" records that as an + * invariant rather than a limitation to work around: + * **two widgets on one node cannot share a name.** + * + * {@link ensureUniqueWidgetNames} normally keeps that true by renaming the + * later occurrence to `name#1`. It cannot when that widget's `name` is not + * writable, or when an accessor throws — and because it is all-or-nothing, one + * such widget also leaves every *renamable* collision on the node standing. + * This walk renames those and refuses only what is genuinely unaddressable: a + * widget the store cannot tell apart silently shares another widget's value. + * + * @returns the removed widgets, in array order. Empty when the node was + * already unambiguous, which is the overwhelmingly common case. + */ +export function dropUnrenamableDuplicateWidgets( + widgets: T[] +): T[] { + if (ensureUniqueWidgetNames(widgets)) return [] + + const kept: T[] = [] + const refused: T[] = [] + const used = new Set() + const seen = new Set() + // Names already spoken for further down the array, so a generated `name#1` + // never collides with one a later widget holds outright. + const reserved = new Set( + widgets.flatMap((widget) => { + const name = readName(widget) + return name === undefined ? [] : [name] + }) + ) + + for (const widget of widgets) { + // The same widget object may occupy two slots mid-reorder. That is one + // widget, not a name collision — never refuse it. + if (seen.has(widget)) { + kept.push(widget) + continue + } + seen.add(widget) + + const name = readName(widget) + if (name === undefined || !used.has(name)) { + if (name !== undefined) used.add(name) + kept.push(widget) + continue + } + + let index = 1 + while (used.has(`${name}#${index}`) || reserved.has(`${name}#${index}`)) { + index++ + } + const unique = `${name}#${index}` + if (!tryRename(widget, unique)) { + refused.push(widget) + continue + } + used.add(unique) + reserved.add(unique) + kept.push(widget) + } + + if (refused.length) widgets.splice(0, widgets.length, ...kept) + return refused +} + function decodeWidgetIdSegment(segment: string): string { try { return decodeURIComponent(segment) From 9d9489a8dcbe1f89567ffa8b75ed37c560731873 Mon Sep 17 00:00:00 2001 From: Christian Byrne Date: Sun, 4 Oct 2026 03:17:09 -0700 Subject: [PATCH 02/35] refactor(widgets): split the unique-name walk into named helpers `dropUnrenamableDuplicateWidgets` breached the cognitive-complexity threshold (16, cyclomatic 11, 51 lines), which is the one new finding the fallow gate reported. Behaviour is unchanged and the suite is unchanged: 34 cases pass, and all eight mutations still fail exactly their row. - `readableNames` collects the names the array already holds, skipping the ones a throwing accessor hides. - `freeSuffixedName` finds the first `name#n` no set claims. - The identity-duplicate skip and the unreadable-name skip were two branches reaching the same outcome and are now one: a widget already accounted for, or one with no readable name, has no new identity to collide with. `pnpm fallow:audit --changed-since origin/main` exits 0. --- src/types/widgetId.ts | 48 +++++++++++++++++++++++++------------------ 1 file changed, 28 insertions(+), 20 deletions(-) diff --git a/src/types/widgetId.ts b/src/types/widgetId.ts index 78e6c74086f..56ce4a507c7 100644 --- a/src/types/widgetId.ts +++ b/src/types/widgetId.ts @@ -101,6 +101,29 @@ function tryRename(widget: { name: string }, name: string): boolean { } } +/** Every name the array already holds outright, skipping unreadable ones. */ +function readableNames(widgets: readonly { name: string }[]): Set { + const names = new Set() + for (const widget of widgets) { + const name = readName(widget) + if (name !== undefined) names.add(name) + } + return names +} + +/** + * The first `name#n` no set in {@link taken} claims — so a generated name never + * collides with one a widget further down the array holds outright. + */ +function freeSuffixedName( + name: string, + taken: readonly ReadonlySet[] +): string { + let index = 1 + while (taken.some((names) => names.has(`${name}#${index}`))) index++ + return `${name}#${index}` +} + /** * Removes the widgets that cannot be given a unique name, mutating * {@link widgets} in place, and renames the duplicates that can — keeping the @@ -131,36 +154,21 @@ export function dropUnrenamableDuplicateWidgets( const refused: T[] = [] const used = new Set() const seen = new Set() - // Names already spoken for further down the array, so a generated `name#1` - // never collides with one a later widget holds outright. - const reserved = new Set( - widgets.flatMap((widget) => { - const name = readName(widget) - return name === undefined ? [] : [name] - }) - ) + const reserved = readableNames(widgets) for (const widget of widgets) { - // The same widget object may occupy two slots mid-reorder. That is one - // widget, not a name collision — never refuse it. - if (seen.has(widget)) { - kept.push(widget) - continue - } + // Nothing new to collide with: either the same widget object occupying a + // second slot mid-reorder, or a name that cannot be read at all. + const name = seen.has(widget) ? undefined : readName(widget) seen.add(widget) - const name = readName(widget) if (name === undefined || !used.has(name)) { if (name !== undefined) used.add(name) kept.push(widget) continue } - let index = 1 - while (used.has(`${name}#${index}`) || reserved.has(`${name}#${index}`)) { - index++ - } - const unique = `${name}#${index}` + const unique = freeSuffixedName(name, [used, reserved]) if (!tryRename(widget, unique)) { refused.push(widget) continue From d5d69673d61ee15b7589b7db8f92754a3b6d3ca8 Mon Sep 17 00:00:00 2001 From: Christian Byrne Date: Sun, 4 Oct 2026 03:27:45 -0700 Subject: [PATCH 03/35] test(widgets): take the three review findings on the invariant suite From CodeRabbit's review of `5bc255b103`/`9d9489a8dc`. - The constant-value case was a change detector: it asserted an exported constant equals a literal and no behaviour. Deleted; the refusal case now spells the literal `'widget_duplicate_name_refused'` out in the assertion on what `reportError` received, which is where the contract actually matters. That still kills the rename mutation, so nothing is lost. The constant is no longer exported. - `console.warn` spies are hoisted into `beforeEach`. Vitest runs with `restoreMocks: true`, so the manual `mockRestore()` calls were redundant and skipped entirely whenever an assertion failed first. - The browser case's workflow name is built per attempt from `testInfo.parallelIndex` and `testInfo.retry`. A module-scope `Date.now()` is shared by every worker in the process and by a retry, so a retry could reopen the document its own previous attempt saved. 33 cases pass; all eight mutations still fail exactly their row. `pnpm knip`, `pnpm typecheck`, `pnpm typecheck:browser` and `pnpm fallow:audit` exit 0, and the browser case is still green. --- .../unrenamableDuplicateWidgetRefused.spec.ts | 12 +++++-- src/lib/litegraph/src/node/widgetsView.ts | 6 ++-- .../node/widgetsView.uniqueWidgetName.test.ts | 14 +++------ src/types/widgetId.test.ts | 31 +++++-------------- 4 files changed, 24 insertions(+), 39 deletions(-) diff --git a/browser_tests/tests/widgets/unrenamableDuplicateWidgetRefused.spec.ts b/browser_tests/tests/widgets/unrenamableDuplicateWidgetRefused.spec.ts index 1086f02419c..c12e7d1c2d7 100644 --- a/browser_tests/tests/widgets/unrenamableDuplicateWidgetRefused.spec.ts +++ b/browser_tests/tests/widgets/unrenamableDuplicateWidgetRefused.spec.ts @@ -26,7 +26,6 @@ import { zComfyWorkflow } from '@/platform/workflow/validation/schemas/workflowS * what the app actually saved. */ -const workflowName = `unrenamable-duplicate-widget-${Date.now()}` const NODE_TYPE = 'DevToolsNodeWithOutputList' const DUPLICATE_NAME = 'duplicate' const TYPED_VALUE = 'typed by the user' @@ -69,13 +68,20 @@ test.describe( 'unrenamable duplicate widget name', { tag: ['@canvas', '@widget', '@vue-nodes'] }, () => { + // Per attempt, not per module: a module-scope stamp is shared by every + // worker in the process and by a retry, so a retry can reopen the document + // its own previous attempt saved. + let workflowName = '' + test.afterEach(async ({ comfyPage }) => { - await comfyPage.workflow.deleteWorkflow(workflowName) + if (workflowName) await comfyPage.workflow.deleteWorkflow(workflowName) }) test('refuses the widget it cannot name uniquely and keeps the node usable', async ({ comfyPage - }) => { + }, testInfo) => { + workflowName = `unrenamable-duplicate-widget-${testInfo.parallelIndex}-${testInfo.retry}-${Date.now()}` + await comfyPage.nodeOps.clearGraph() await installUnrenameableDuplicate(comfyPage) diff --git a/src/lib/litegraph/src/node/widgetsView.ts b/src/lib/litegraph/src/node/widgetsView.ts index b52942b7c43..40897fefef5 100644 --- a/src/lib/litegraph/src/node/widgetsView.ts +++ b/src/lib/litegraph/src/node/widgetsView.ts @@ -14,9 +14,11 @@ import { getWidgetIds } from '../utils/widget' /** * Stable `errorType` for the one state that breaks widget identity: a node * holding two widgets under one name that could not be renamed apart, so the - * second is refused. See {@link dropUnrenamableDuplicateWidgets}. + * second is refused. Alerting is keyed on this string — treat it as a + * contract, not an implementation detail. + * See {@link dropUnrenamableDuplicateWidgets}. */ -export const DUPLICATE_WIDGET_NAME_ERROR_TYPE = 'widget_duplicate_name_refused' +const DUPLICATE_WIDGET_NAME_ERROR_TYPE = 'widget_duplicate_name_refused' interface WidgetsViewState { target: IBaseWidget[] diff --git a/src/lib/litegraph/src/node/widgetsView.uniqueWidgetName.test.ts b/src/lib/litegraph/src/node/widgetsView.uniqueWidgetName.test.ts index af9a144b4d9..f27be3ea539 100644 --- a/src/lib/litegraph/src/node/widgetsView.uniqueWidgetName.test.ts +++ b/src/lib/litegraph/src/node/widgetsView.uniqueWidgetName.test.ts @@ -1,7 +1,6 @@ import { beforeEach, describe, expect, it, vi } from 'vitest' import { LGraph, LGraphNode, LiteGraph } from '@/lib/litegraph/src/litegraph' -import { DUPLICATE_WIDGET_NAME_ERROR_TYPE } from '@/lib/litegraph/src/node/widgetsView' import type { IBaseWidget } from '@/lib/litegraph/src/types/widgets' import { reportError } from '@/platform/telemetry/reportError' import { useWidgetValueStore } from '@/stores/widgetValueStore' @@ -82,23 +81,18 @@ describe('unique widget name invariant', () => { expect(names(node)).toEqual(['seed', 'cfg']) expect(node.widgets).not.toContain(second) + // The error type is spelled out rather than compared to the exported + // constant: an alert query is written against this string, so renaming it + // is the breaking change and the literal is the contract. expect(reportError).toHaveBeenCalledExactlyOnceWith( expect.any(Error), expect.objectContaining({ - errorType: DUPLICATE_WIDGET_NAME_ERROR_TYPE, + errorType: 'widget_duplicate_name_refused', surface: 'graph' }) ) }) - it('reports an error type that stays stable for dashboards and alerts', () => { - // Spelled out rather than compared to the constant: a dashboard query is - // written against this string, so renaming it is the breaking change. - expect(DUPLICATE_WIDGET_NAME_ERROR_TYPE).toBe( - 'widget_duplicate_name_refused' - ) - }) - it('does not let a refused widget overwrite the stored value of the one that kept the name', () => { const node = createNode() const first = node.addWidget('number', 'seed', 1, () => undefined, {}) diff --git a/src/types/widgetId.test.ts b/src/types/widgetId.test.ts index 8f252b53781..c5ad03699c2 100644 --- a/src/types/widgetId.test.ts +++ b/src/types/widgetId.test.ts @@ -1,4 +1,4 @@ -import { describe, expect, it, vi } from 'vitest' +import { beforeEach, describe, expect, it, vi } from 'vitest' import type { WidgetId } from './widgetId' import { @@ -35,12 +35,16 @@ describe('ensureUniqueWidgetNames', () => { expect(ensureUniqueWidgetNames(widgets)).toBe(false) expect(widgets.map(({ name }) => name)).toEqual(['seed', 'seed']) expect(warn).toHaveBeenCalledOnce() - - warn.mockRestore() }) }) describe('dropUnrenamableDuplicateWidgets', () => { + beforeEach(() => { + // `ensureUniqueWidgetNames` warns whenever it gives up on a rename, which + // is the entry condition for every case here rather than the subject. + vi.spyOn(console, 'warn').mockImplementation(() => {}) + }) + /** A name that cannot be written, which is how the state is reached. */ const pinned = (name: string) => { const widget = {} as { name: string } @@ -56,29 +60,22 @@ describe('dropUnrenamableDuplicateWidgets', () => { }) it('refuses nothing when the duplicate can be renamed', () => { - const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}) const widgets = [{ name: 'seed' }, { name: 'seed' }] expect(dropUnrenamableDuplicateWidgets(widgets)).toEqual([]) expect(widgets.map(({ name }) => name)).toEqual(['seed', 'seed#1']) - - warn.mockRestore() }) it('keeps the first occurrence and refuses the one it cannot rename', () => { - const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}) const first = { name: 'seed' } const refused = pinned('seed') const widgets = [first, refused] expect(dropUnrenamableDuplicateWidgets(widgets)).toEqual([refused]) expect(widgets).toEqual([first]) - - warn.mockRestore() }) it('renames the collisions the refusal was masking', () => { - const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}) // `ensureUniqueWidgetNames` is all-or-nothing, so one unrenamable widget // leaves every other collision on the node standing too. const refused = pinned('seed') @@ -95,12 +92,9 @@ describe('dropUnrenamableDuplicateWidgets', () => { 'steps', 'steps#1' ]) - - warn.mockRestore() }) it('does not hand a generated name to a widget that already holds it', () => { - const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}) const refused = pinned('seed') const widgets = [{ name: 'seed' }, refused, { name: 'seed' }] // `seed#1` is held outright further down the array, so the rename must @@ -113,12 +107,9 @@ describe('dropUnrenamableDuplicateWidgets', () => { 'seed#2', 'seed#1' ]) - - warn.mockRestore() }) it('refuses a widget whose setter silently ignores the rename', () => { - const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}) const stubborn = { get name() { return 'seed' @@ -131,12 +122,9 @@ describe('dropUnrenamableDuplicateWidgets', () => { // will take; only reading the name back afterwards proves it did not. expect(dropUnrenamableDuplicateWidgets(widgets)).toContain(stubborn) expect(widgets.map(({ name }) => name)).toEqual(['seed']) - - warn.mockRestore() }) it('refuses nothing when a name accessor throws', () => { - const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}) const hostile = { get name(): string { throw new Error('name is not readable') @@ -148,12 +136,9 @@ describe('dropUnrenamableDuplicateWidgets', () => { // refuse — and the throw must not escape into a widgets mutation. expect(dropUnrenamableDuplicateWidgets(widgets)).toEqual([]) expect(widgets).toHaveLength(2) - - warn.mockRestore() }) it('does not refuse one widget object occupying two array slots', () => { - const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}) const shared = pinned('seed') const other = pinned('seed') const widgets = [shared, shared, other] @@ -161,8 +146,6 @@ describe('dropUnrenamableDuplicateWidgets', () => { // Identity duplicates are one widget mid-reorder, not a name collision. expect(dropUnrenamableDuplicateWidgets(widgets)).toEqual([other]) expect(widgets).toEqual([shared, shared]) - - warn.mockRestore() }) }) From 11e84b1927410aea1c679c9d784f0d3a32620f9e Mon Sep 17 00:00:00 2001 From: Christian Byrne Date: Sun, 4 Oct 2026 04:31:35 -0700 Subject: [PATCH 04/35] fix(widgets): enforce the unique-name invariant where identity is minted MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Takes the current-head review findings on the refusal walk, and fixes a regression the review did not raise: core's RecordAudio node rendered its record button as "audio" instead of "Start Recording". RecordAudio adds two widgets under one input name, so it is exactly this PR's path. Enforcement ran on every widgets commit, including while the node was still detached — earlier than the pre-existing rename, which only ran from `setNodeId`. `litegraphService` finds the widget a custom constructor just created by comparing `candidate.name` to the returned widget's name, so renaming during construction moved the input's label onto the wrong widget. Enforcement now starts where a `WidgetId` can first be minted: `LGraph.add` normalizes the widgets view before assigning `node.graph`, so the join is caught in `attachNodeToStores` instead. Also from review, each verified against this head: - Judge renamability after `toConcreteWidget`, not before. It merges the concrete class's writable `name` accessor over a plain object's pinned one, so a raw-pushed widget was destroyed though it renames cleanly. - Drop the `ensureUniqueWidgetNames` early return. It decides from the property descriptor and never reads back, so a setter that accepts a write and ignores it reported success over a still-ambiguous node. - Offer a colliding widget more than one name. `BaseWidget` delegates its setter to `renameWidget`, which refuses to move onto an id the store already holds; one rejected candidate is not "unrenamable", and refusal deletes the widget. - Keep a rejected candidate free for the next widget rather than reserving it globally. - Follow the first verdict on a widget's later occurrences, so the reorder bypass cannot re-admit one already refused and reported. - Refuse a widget whose `name` getter throws, which the ADR already claimed: keeping it makes `ensureUniqueWidgetNames` fail forever and bails registration for every other widget on the node. Tell that apart from a name that reads as `undefined`. - Read hostile accessors safely at the telemetry site, so a throw cannot escape after the array was spliced. - Clear slot back-references and run `onRemove` for a refused widget; the splice bypasses `removeWidget`. Its store entry is left alone — the refused name now resolves to the entry the kept widget owns. - Do not mount a refused DOM widget's element. Absence is read through a helper that ignores `SubgraphNode`, whose promoted list never commits through this path and returns copies rather than the object handed in. Narrows the ADR to what the code does: enforcement begins at the graph join, renamability is judged post-normalization, and `SubgraphNode` is out of scope. Proof: refusal still fires at the widgets-array commit point, the `widget_duplicate_name_refused` errorType is unchanged, and unrenamableDuplicateWidgetRefused.spec.ts is still red on the parent (toHaveCount(1) receives 0) and green here. 40 unit cases, 10 mutations each killed by exactly their own assertion. --- docs/adr/ECS-0008-entity-component-system.md | 30 +++-- .../graph/nodeShell/nodeShellLifecycle.ts | 6 + src/lib/litegraph/src/node/widgetsView.ts | 127 ++++++++++++++++-- .../node/widgetsView.uniqueWidgetName.test.ts | 81 ++++++++++- src/scripts/domWidget.ts | 10 ++ src/types/widgetId.test.ts | 70 +++++++++- src/types/widgetId.ts | 94 ++++++++++--- 7 files changed, 373 insertions(+), 45 deletions(-) diff --git a/docs/adr/ECS-0008-entity-component-system.md b/docs/adr/ECS-0008-entity-component-system.md index 0fd8fb6a6e7..750270bb5bc 100644 --- a/docs/adr/ECS-0008-entity-component-system.md +++ b/docs/adr/ECS-0008-entity-component-system.md @@ -185,14 +185,28 @@ legitimate re-mint rather than an identity collision — which is why > another widget already holds is not a second identity; it is the same > identity twice, and nothing downstream can tell the two apart. > -> `ensureUniqueWidgetNames` keeps it true by renaming the repeat to `name#1` -> before any id is derived. Where it cannot — a `name` that is not writable, or -> an accessor that throws (`src/types/widgetId.ts`) — the widget is **refused**: -> `node.widgets` is a mutation view, so every add commits through -> `syncWidgetOrder`, which drops what it cannot name uniquely and reports it -> under the stable `errorType` `widget_duplicate_name_refused`. First -> occurrence wins; renamable collisions elsewhere on the node are still -> renamed. +> The repeat is renamed to `name#1` before any id is derived. Where it cannot +> be — a `name` whose writes do not stick, or an accessor that throws +> (`src/types/widgetId.ts`) — the widget is **refused**: `node.widgets` is a +> mutation view, so every add commits through `syncWidgetOrder`, which drops +> what it cannot name uniquely and reports it under the stable `errorType` +> `widget_duplicate_name_refused`. First occurrence wins; renamable collisions +> elsewhere on the node are still renamed. +> +> Three boundaries on that, because each one is load-bearing and none is +> obvious from the rule: +> +> - **Enforcement starts when the node joins a graph**, not when a detached +> node is built. No `WidgetId` exists before then, so there is no identity to +> collide over — and renaming during construction changes names that +> `litegraphService` still matches a freshly created widget on. +> - **Renamability is judged after normalization.** `toConcreteWidget` merges +> the concrete class's writable `name` accessor over a plain object's pinned +> one, so a raw widget that looks unrenamable usually is not. +> - **`SubgraphNode` does not commit through this path.** It redefines +> `widgets` as a computed getter over its promoted widgets and overrides +> `addCustomWidget`, so an ambiguous pair there keeps the pre-existing +> behaviour. > > A serialized `(name, occurrence)` identity was proposed instead, so that both > widgets could be persisted ([#19717](https://github.com/Comfy-Org/ComfyUI_frontend/pull/19717)). diff --git a/src/core/graph/nodeShell/nodeShellLifecycle.ts b/src/core/graph/nodeShell/nodeShellLifecycle.ts index a83bd224a20..a59f1f2c1dd 100644 --- a/src/core/graph/nodeShell/nodeShellLifecycle.ts +++ b/src/core/graph/nodeShell/nodeShellLifecycle.ts @@ -1,3 +1,4 @@ +import { refuseAmbiguousNodeWidgets } from '@/lib/litegraph/src/node/widgetsView' import { isNodeBindable } from '@/lib/litegraph/src/utils/type' import { getWidgetIds } from '@/lib/litegraph/src/utils/widget' import { usePreviewExposureStore } from '@/stores/previewExposureStore' @@ -30,6 +31,11 @@ export function attachNodeToStores( } if (!node.widgets) return + // Two widgets on one node cannot share a name (ADR-ECS-0008), and this is + // the first moment a `WidgetId` exists to collide over: the node now has a + // graph and its final id. Registering an ambiguous pair would bind both to + // one store entry, and `setNodeId` would in fact register neither. + refuseAmbiguousNodeWidgets(node) for (const widget of node.widgets) { if (isNodeBindable(widget)) widget.setNodeId(node.id) } diff --git a/src/lib/litegraph/src/node/widgetsView.ts b/src/lib/litegraph/src/node/widgetsView.ts index 40897fefef5..1dca3b7ccb0 100644 --- a/src/lib/litegraph/src/node/widgetsView.ts +++ b/src/lib/litegraph/src/node/widgetsView.ts @@ -31,11 +31,56 @@ const states = new WeakMap() const widgetsViewGetters = new WeakSet<() => IBaseWidget[] | undefined>() /** - * Enforces the unique-name invariant at the one place every widget reaches the - * node: `node.widgets` is a mutation view, so `addWidget`, a raw - * `widgets.push`, a splice and a whole-array assignment all commit through - * here. A widget refused here is never registered with the store and never - * rendered, because it is off the node before either happens. + * Reads a property off a widget that is being refused. The widget reached that + * state because an accessor misbehaved, so every read here is hostile: a + * `name` getter that throws would escape `syncWidgetOrder` after the array has + * already been spliced, leaving the node and the store's order out of sync. + */ +function safeRead(read: () => unknown): string | undefined { + try { + const value = read() + return value === undefined ? undefined : String(value) + } catch { + return undefined + } +} + +/** + * Releases a widget the node has just refused. It is already off the array, so + * `LGraphNode.removeWidget` can no longer find it and the teardown that method + * owns has to happen here: slot back-references would otherwise keep pointing + * at a widget the node no longer has. + * + * The widget's store entry is deliberately *not* deleted. A refused widget's + * name is by definition the one another widget kept, so `widget.widgetId` now + * resolves to that widget's entry — deleting it would destroy the value of the + * widget this invariant exists to protect. + */ +function releaseRefusedWidget(node: LGraphNode, widget: IBaseWidget): void { + for (const input of node.inputs) { + if (input._widget === widget) { + input._widget = undefined + input.widget = undefined + input.pos = undefined + } + } + try { + widget.onRemove?.() + } catch (error) { + console.error('Failed to release a refused widget', error) + } +} + +/** + * Enforces the unique-name invariant where `node.widgets` is committed: the + * array is a mutation view, so `addWidget`, a raw `widgets.push`, a splice and + * a whole-array assignment all pass through here. A widget refused here is + * never registered with the store and never rendered, because it is off the + * node before either happens. + * + * `SubgraphNode` does **not** commit through here and keeps the pre-existing + * behaviour: it redefines `widgets` as a computed getter over its promoted + * widgets and overrides `addCustomWidget` to push into its own array. */ function refuseAmbiguousWidgets( node: LGraphNode, @@ -45,9 +90,11 @@ function refuseAmbiguousWidgets( if (!refused.length) return for (const widget of refused) { + const widgetName = safeRead(() => widget.name) + releaseRefusedWidget(node, widget) reportError( new Error( - `Refused a widget named "${widget.name}": node ${node.id} already has a widget of that name and the duplicate cannot be renamed` + `Refused a widget named "${widgetName}": node ${node.id} already has a widget of that name and the duplicate cannot be renamed` ), { errorType: DUPLICATE_WIDGET_NAME_ERROR_TYPE, @@ -56,27 +103,81 @@ function refuseAmbiguousWidgets( tags: { node_type: node.type }, context: { nodeId: String(node.id), - widgetName: widget.name, - widgetType: widget.type + widgetName, + widgetType: safeRead(() => widget.type) } } ) } } +/** + * Whether {@link node} still exposes the mutation view this module installed, + * and so is subject to the unique-name invariant at all. + * + * `SubgraphNode` replaces `widgets` with its own computed getter over promoted + * widgets, which never commits through here. Distinguishing the two matters to + * callers that infer refusal from a widget's absence: on a promoted list the + * object handed in is not the object read back, so absence means nothing. + */ +function commitsThroughWidgetsView(node: LGraphNode): boolean { + const descriptor = Object.getOwnPropertyDescriptor(node, 'widgets') + return !!descriptor?.get && widgetsViewGetters.has(descriptor.get) +} + +/** + * Whether {@link node} refused {@link widget} — it is not on a node whose list + * this module owns, so it was dropped for a name it could not be given. + */ +export function wasWidgetRefused( + node: LGraphNode, + widget: IBaseWidget +): boolean { + return commitsThroughWidgetsView(node) && !node.widgets?.includes(widget) +} + +/** + * Enforces the invariant for a node that is joining a graph. + * + * `LGraph.add` normalizes the widgets view while `node.graph` is still unset, + * so that commit cannot mint a `WidgetId` and deliberately does not enforce. + * This runs where identities actually come into existence — immediately before + * the node's widgets are registered — which is the first point at which an + * ambiguous pair can do any harm. + */ +export function refuseAmbiguousNodeWidgets(node: LGraphNode): void { + const widgets = node.widgets + if (!widgets?.length) return + refuseAmbiguousWidgets(node, widgets) +} + function syncWidgetOrder(node: LGraphNode, widgets: IBaseWidget[]): void { node._widgetSlotsDirty = true const graphId = node.graph?.rootGraph.id + const concreteWidgets = widgets.map((widget) => + toConcreteWidget(widget, node) + ) + for (const [index, widget] of concreteWidgets.entries()) { + widgets[index] = widget + } + + // Nothing is registered until the node is in a graph, so there is no + // identity to collide over yet — and renaming earlier than the store needs + // it changes names that node construction still matches on. Enforcement + // belongs at the first commit that can actually mint a `WidgetId`. + if (!graphId) return + + // After normalization, not before: `toConcreteWidget` merges the concrete + // class's writable `name` accessor over a plain object's pinned one, so a + // widget judged unrenamable while still raw would be destroyed even though + // it renames cleanly a line later. refuseAmbiguousWidgets(node, widgets) - for (const [index, widget] of widgets.entries()) { - const concreteWidget = toConcreteWidget(widget, node) - widgets[index] = concreteWidget - if (graphId) concreteWidget.setNodeId(node.id) + for (const widget of concreteWidgets) { + if (widgets.includes(widget)) widget.setNodeId(node.id) } - if (!graphId) return useWidgetValueStore().replaceNodeWidgetOrder( graphId, node.id, diff --git a/src/lib/litegraph/src/node/widgetsView.uniqueWidgetName.test.ts b/src/lib/litegraph/src/node/widgetsView.uniqueWidgetName.test.ts index f27be3ea539..49671a892cd 100644 --- a/src/lib/litegraph/src/node/widgetsView.uniqueWidgetName.test.ts +++ b/src/lib/litegraph/src/node/widgetsView.uniqueWidgetName.test.ts @@ -176,7 +176,7 @@ describe('unique widget name invariant', () => { expect(storedNames(node)).toEqual(['seed', 'steps', 'steps#1']) }) - it('refuses a pinned duplicate pushed in raw, not only one added through addWidget', () => { + it('renames rather than refuses a raw pushed duplicate, which normalization makes renamable', () => { const node = createNode() node.addWidget('number', 'seed', 1, () => undefined, {}) const raw: IBaseWidget = { @@ -190,9 +190,13 @@ describe('unique widget name invariant', () => { node.widgets!.push(raw) - expect(names(node)).toEqual(['seed']) - expect(storedNames(node)).toEqual(['seed']) - expect(reportError).toHaveBeenCalledOnce() + // Renamability is judged after `toConcreteWidget`, which gives a raw + // object the concrete class's writable `name` accessor. Judging it while + // still raw would delete a widget that renames cleanly a line later, and + // refusal is permanent. + expect(names(node)).toEqual(['seed', 'seed#1']) + expect(storedNames(node)).toEqual(['seed', 'seed#1']) + expect(reportError).not.toHaveBeenCalled() }) it('refuses the later of a pinned pair carried in by a whole-array assignment', () => { @@ -209,6 +213,75 @@ describe('unique widget name invariant', () => { expect(reportError).toHaveBeenCalledOnce() }) + it('leaves names alone while the node is detached, and settles them on add', () => { + const graph = new LGraph() + const node = new LGraphNode('test') + node.addWidget('number', 'audio', 1, () => undefined, {}) + node.addWidget('button', 'audio', '', () => undefined, {}) + + // No `WidgetId` exists before the node has a graph, so there is nothing to + // collide over yet — and renaming during construction is observable: + // `litegraphService` finds the widget a custom constructor just made by + // comparing `candidate.name` to the returned widget's name, so an early + // rename moves the input's label onto the wrong widget. Core's RecordAudio + // node builds exactly this shape. + expect(names(node)).toEqual(['audio', 'audio']) + + graph.add(node) + + expect(names(node)).toEqual(['audio', 'audio#1']) + expect(storedNames(node)).toEqual(['audio', 'audio#1']) + expect(reportError).not.toHaveBeenCalled() + }) + + it('reports a widget whose name throws without letting the throw escape the commit', () => { + const node = createNode() + node.addWidget('number', 'seed', 1, () => undefined, {}) + const hostile = node.addWidget('number', 'steps', 2, () => undefined, {}) + Object.defineProperty(hostile, 'name', { + get(): string { + throw new Error('name is not readable') + }, + configurable: false + }) + + // The report runs after the array has already been spliced, so re-reading + // the accessor there would leave the node's widgets and the store's order + // out of sync — with the error surfacing far from its cause. + expect(() => + node.addWidget('number', 'cfg', 3, () => undefined, {}) + ).not.toThrow() + + expect(names(node)).toEqual(['seed', 'cfg']) + expect(reportError).toHaveBeenCalledExactlyOnceWith( + expect.any(Error), + expect.objectContaining({ + errorType: 'widget_duplicate_name_refused', + context: expect.objectContaining({ widgetName: undefined }) + }) + ) + }) + + it('clears slot back-references to a widget it refused', () => { + const node = createNode() + node.addWidget('number', 'seed', 1, () => undefined, {}) + const second = node.addWidget('number', 'steps', 2, () => undefined, {}) + node.addInput('steps', 'INT') + const input = node.inputs.at(-1)! + input._widget = second + input.widget = { name: 'steps' } + pinName(second, 'seed') + + node.addWidget('number', 'cfg', 3, () => undefined, {}) + + // Refusal splices the widget straight out of the array, so the teardown + // `removeWidget` owns has to happen here or the node keeps pointing at a + // widget it no longer has. + expect(node.widgets).not.toContain(second) + expect(input._widget).toBeUndefined() + expect(input.widget).toBeUndefined() + }) + it('does not refuse one widget object occupying two slots mid-reorder', () => { const node = createNode() const first = node.addWidget('number', 'a', 1, () => undefined, {}) diff --git a/src/scripts/domWidget.ts b/src/scripts/domWidget.ts index ad66055aa1d..b7394846136 100644 --- a/src/scripts/domWidget.ts +++ b/src/scripts/domWidget.ts @@ -7,6 +7,7 @@ import { useChainCallback } from '@/composables/functional/useChainCallback' // would hit its TDZ. LGraphNode/LiteGraph must stay barrel-sourced — a direct // LGraphNode import re-triggers the LGraph<->Subgraph cycle. import { LGraphNode, LiteGraph } from '@/lib/litegraph/src/litegraph' +import { wasWidgetRefused } from '@/lib/litegraph/src/node/widgetsView' import type { IBaseWidget, IWidgetOptions @@ -329,11 +330,20 @@ export class ComponentWidgetImpl< export const addWidget = (node: LGraphNode, widget: BaseDOMWidget) => { node.addCustomWidget(widget) + // A duplicate name the node could not rename apart is refused and spliced + // straight back out (ADR-ECS-0008). Registering it anyway would mount its + // element over the canvas for a widget the graph does not have, and nothing + // would unmount it until the node itself is removed. + if (wasWidgetRefused(node, widget)) return + if (node.graph) { useDomWidgetStore().registerWidget(widget) } node.onAdded = useChainCallback(node.onAdded, () => { + // Joining a graph is the first commit that can refuse a duplicate name, + // so a widget accepted above may not have survived it. + if (wasWidgetRefused(node, widget)) return useDomWidgetStore().registerWidget(widget) }) diff --git a/src/types/widgetId.test.ts b/src/types/widgetId.test.ts index c5ad03699c2..898926aa0d5 100644 --- a/src/types/widgetId.test.ts +++ b/src/types/widgetId.test.ts @@ -124,7 +124,7 @@ describe('dropUnrenamableDuplicateWidgets', () => { expect(widgets.map(({ name }) => name)).toEqual(['seed']) }) - it('refuses nothing when a name accessor throws', () => { + it('refuses a widget whose name accessor throws, without letting it escape', () => { const hostile = { get name(): string { throw new Error('name is not readable') @@ -132,10 +132,72 @@ describe('dropUnrenamableDuplicateWidgets', () => { } const widgets = [{ name: 'seed' }, hostile] - // No readable name is no identity to collide with, so there is nothing to - // refuse — and the throw must not escape into a widgets mutation. + // A name that cannot be read is a `WidgetId` that cannot be derived, and + // leaving it on the node makes `ensureUniqueWidgetNames` fail on every + // later call — which bails registration for the whole node, including the + // widgets that are perfectly addressable. The throw must not escape. + expect(dropUnrenamableDuplicateWidgets(widgets)).toEqual([hostile]) + expect(widgets).toHaveLength(1) + }) + + it('tells an unreadable name apart from one that reads as undefined', () => { + const first = { name: undefined as unknown as string } + const second = { name: undefined as unknown as string } + const widgets = [first, second] + + // `undefined` is a bad identity, not a missing one: two of them collide + // with each other and would mint the same `graphId:nodeId:undefined`. expect(dropUnrenamableDuplicateWidgets(widgets)).toEqual([]) - expect(widgets).toHaveLength(2) + expect(widgets.map(({ name }) => name)).toEqual([undefined, 'undefined#1']) + }) + + it('offers another name when a setter rejects only the first one', () => { + // `BaseWidget` delegates its `name` setter to the store, which refuses to + // move onto an id something else already holds. Refusal deletes a widget, + // so one rejected candidate must not be read as unrenamable. + let name = 'seed' + const picky = { + get name() { + return name + }, + set name(value: string) { + if (value !== 'seed#1') name = value + } + } + const widgets = [{ name: 'seed' }, picky] + + expect(dropUnrenamableDuplicateWidgets(widgets)).toEqual([]) + expect(widgets.map((widget) => widget.name)).toEqual(['seed', 'seed#2']) + }) + + it('does not reserve a name one widget rejected against the next widget', () => { + const offered: string[] = [] + const stubborn = { + get name() { + return 'seed' + }, + set name(value: string) { + offered.push(value) + } + } + const renamable = { name: 'seed' } + const widgets = [{ name: 'seed' }, stubborn, renamable] + + expect(dropUnrenamableDuplicateWidgets(widgets)).toEqual([stubborn]) + // `seed#1` was offered to `stubborn` and did not take, so it is still free + // for the next widget — a name one setter refuses is not a name in use. + expect(offered).toContain('seed#1') + expect(widgets.map((widget) => widget.name)).toEqual(['seed', 'seed#1']) + }) + + it('refuses every occurrence of a widget it refused once', () => { + const refused = pinned('seed') + const widgets = [{ name: 'seed' }, refused, refused] + + // The identity bypass that keeps a reordering widget in place must not + // re-admit one whose first occurrence was already refused and reported. + expect(dropUnrenamableDuplicateWidgets(widgets)).toEqual([refused]) + expect(widgets.map(({ name }) => name)).toEqual(['seed']) }) it('does not refuse one widget object occupying two array slots', () => { diff --git a/src/types/widgetId.ts b/src/types/widgetId.ts index 56ce4a507c7..caf0b6c1468 100644 --- a/src/types/widgetId.ts +++ b/src/types/widgetId.ts @@ -79,14 +79,18 @@ export function ensureUniqueWidgetNames( } /** - * Reads `name` without letting a throwing accessor escape. A widget whose - * `name` cannot be read has no identity to collide with, so it is left alone. + * A `name` that could not be read at all, because the accessor threw. Distinct + * from a widget whose name *is* `undefined`: that one has an identity, a bad + * one, and two of them collide with each other. */ -function readName(widget: { name: string }): string | undefined { +const UNREADABLE_NAME = Symbol('unreadable widget name') + +/** Reads `name` without letting a throwing accessor escape. */ +function readName(widget: { name: string }): string | typeof UNREADABLE_NAME { try { return widget.name } catch { - return undefined + return UNREADABLE_NAME } } @@ -106,7 +110,7 @@ function readableNames(widgets: readonly { name: string }[]): Set { const names = new Set() for (const widget of widgets) { const name = readName(widget) - if (name !== undefined) names.add(name) + if (name !== UNREADABLE_NAME) names.add(name) } return names } @@ -124,6 +128,42 @@ function freeSuffixedName( return `${name}#${index}` } +/** + * How many distinct names a colliding widget is offered before it is refused. + * + * One attempt is not enough: a `name` setter can reject one target and accept + * another. `BaseWidget`'s delegates to `widgetValueStore.renameWidget`, which + * refuses to move onto an id the store already holds — so a stale entry under + * `seed#1` makes a perfectly renamable widget look unrenamable. Refusal + * deletes the widget, so it has to be the answer to "no name works", not to + * "the first name I tried did not". + */ +const RENAME_ATTEMPTS = 4 + +/** + * Renames {@link widget} to the first free `name#n` that the write actually + * takes, setting aside each candidate the setter rejects so the next attempt + * offers a different one. + * + * @returns the name it now answers to, or `undefined` if no attempt stuck. + */ +function renameApart( + widget: { name: string }, + name: string, + used: ReadonlySet, + reserved: ReadonlySet +): string | undefined { + // Rejected candidates are tracked per widget, not reserved globally: a name + // this widget's setter would not take is still free for the next widget. + const rejected = new Set() + for (let attempt = 0; attempt < RENAME_ATTEMPTS; attempt++) { + const candidate = freeSuffixedName(name, [used, reserved, rejected]) + if (tryRename(widget, candidate)) return candidate + rejected.add(candidate) + } + return undefined +} + /** * Removes the widgets that cannot be given a unique name, mutating * {@link widgets} in place, and renames the duplicates that can — keeping the @@ -142,39 +182,61 @@ function freeSuffixedName( * This walk renames those and refuses only what is genuinely unaddressable: a * widget the store cannot tell apart silently shares another widget's value. * + * It does its own renaming rather than delegating the happy path to + * {@link ensureUniqueWidgetNames}, which decides renamability from the + * property descriptor alone and never reads the name back. A setter that + * accepts the write and ignores it satisfies that check, so delegating would + * report success over a node that still carries the ambiguous pair. + * * @returns the removed widgets, in array order. Empty when the node was * already unambiguous, which is the overwhelmingly common case. */ export function dropUnrenamableDuplicateWidgets( widgets: T[] ): T[] { - if (ensureUniqueWidgetNames(widgets)) return [] - const kept: T[] = [] const refused: T[] = [] const used = new Set() - const seen = new Set() const reserved = readableNames(widgets) + /** Every widget already walked, against whether that walk kept it. */ + const verdicts = new Map() for (const widget of widgets) { - // Nothing new to collide with: either the same widget object occupying a - // second slot mid-reorder, or a name that cannot be read at all. - const name = seen.has(widget) ? undefined : readName(widget) - seen.add(widget) + // The same widget object may occupy a second slot mid-reorder. That is one + // widget, not a collision — but it has to follow the verdict its first + // occurrence got, or a refused widget is re-admitted by its own repeat. + const previous = verdicts.get(widget) + if (previous !== undefined) { + if (previous) kept.push(widget) + continue + } - if (name === undefined || !used.has(name)) { - if (name !== undefined) used.add(name) + const name = readName(widget) + if (name === UNREADABLE_NAME) { + // No readable name means no derivable `WidgetId`, and leaving it on the + // node makes `ensureUniqueWidgetNames` fail on every later call — which + // bails registration for every *other* widget on the node too. + verdicts.set(widget, false) + refused.push(widget) + continue + } + + if (!used.has(name)) { + used.add(name) + verdicts.set(widget, true) kept.push(widget) continue } - const unique = freeSuffixedName(name, [used, reserved]) - if (!tryRename(widget, unique)) { + const unique = renameApart(widget, name, used, reserved) + if (unique === undefined) { + verdicts.set(widget, false) refused.push(widget) continue } used.add(unique) reserved.add(unique) + verdicts.set(widget, true) kept.push(widget) } From d4c6d25a70b951c90d0996dc94390414d9c8cae0 Mon Sep 17 00:00:00 2001 From: Christian Byrne Date: Sun, 4 Oct 2026 04:37:22 -0700 Subject: [PATCH 05/35] docs(adr): name both enforcement points, not just syncWidgetOrder Review was right that the amendment still said "every add commits through `syncWidgetOrder`" while the code now enforces in two places. That sentence sends a reader to the one site that does nothing for the case the other exists to cover: `LGraph.add` normalizes the widgets view before assigning `node.graph`, so the join is caught in `attachNodeToStores` and `syncWidgetOrder` only takes over once a `graphId` exists. --- docs/adr/ECS-0008-entity-component-system.md | 17 +++++++++++++---- 1 file changed, 13 insertions(+), 4 deletions(-) diff --git a/docs/adr/ECS-0008-entity-component-system.md b/docs/adr/ECS-0008-entity-component-system.md index 750270bb5bc..f56a54ab5be 100644 --- a/docs/adr/ECS-0008-entity-component-system.md +++ b/docs/adr/ECS-0008-entity-component-system.md @@ -187,19 +187,28 @@ legitimate re-mint rather than an identity collision — which is why > > The repeat is renamed to `name#1` before any id is derived. Where it cannot > be — a `name` whose writes do not stick, or an accessor that throws -> (`src/types/widgetId.ts`) — the widget is **refused**: `node.widgets` is a -> mutation view, so every add commits through `syncWidgetOrder`, which drops -> what it cannot name uniquely and reports it under the stable `errorType` +> (`src/types/widgetId.ts`) — the widget is **refused**: it is dropped from +> `node.widgets` and reported under the stable `errorType` > `widget_duplicate_name_refused`. First occurrence wins; renamable collisions > elsewhere on the node are still renamed. > +> **There are two enforcement points, and looking only at the first one is +> misleading.** `attachNodeToStores` calls `refuseAmbiguousNodeWidgets` as a +> node joins a graph, which is the one that catches a node built detached and +> then added. `syncWidgetOrder` catches every later mutation — `node.widgets` +> is a mutation view, so `addWidget`, a raw `push`, a splice and a whole-array +> assignment all commit through it — but it enforces nothing until `graphId` +> exists, so it does not cover the join itself. +> > Three boundaries on that, because each one is load-bearing and none is > obvious from the rule: > > - **Enforcement starts when the node joins a graph**, not when a detached > node is built. No `WidgetId` exists before then, so there is no identity to > collide over — and renaming during construction changes names that -> `litegraphService` still matches a freshly created widget on. +> `litegraphService` still matches a freshly created widget on. `LGraph.add` +> normalizes the widgets view _before_ assigning `node.graph`, which is why +> the join needs its own call rather than falling out of that commit. > - **Renamability is judged after normalization.** `toConcreteWidget` merges > the concrete class's writable `name` accessor over a plain object's pinned > one, so a raw widget that looks unrenamable usually is not. From c9e455305ba74ad708e07c1a6550f9d55654b73c Mon Sep 17 00:00:00 2001 From: Christian Byrne Date: Sun, 4 Oct 2026 06:31:00 -0700 Subject: [PATCH 06/35] fix(widgets): keep the refusal inside the node classes it can enforce on MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Four findings from the multi-model review of this exact head, each verified against the code before it was taken. `refuseAmbiguousNodeWidgets` ran for every node joining a graph, including `SubgraphNode` — whose `widgets` getter rebuilds the array on every read. The splice landed on a throwaway copy, so nothing was refused, while the side effects still fired on a live widget: the slot back-references were torn down and `widget_duplicate_name_refused` was reported for a refusal that did not happen. Two promoted inputs carrying the same inner widget name reach that state, because a promoted projection's `name` is getter-only. Measured on a real `SubgraphNode`: both widgets stayed, both stayed registered, and the report fired anyway. The call is now gated on the node still exposing this module's mutation view, which is the condition `wasWidgetRefused` already used. Judging renamability after `toConcreteWidget` left the throwing-accessor path unreachable for a raw push: `BaseWidget`'s constructor reads the source object's `name`, so the conversion threw out of the commit before `UNREADABLE_NAME` could refuse it — and out of every later commit, with the node's widgets and the store's order diverging. The conversion is guarded per widget now and an unconvertible widget falls through to the refusal, which is where it was always meant to land. An unreadable name was reported as `widget_duplicate_name_refused` with a message asserting a duplicate that does not exist. It gets its own stable type, `widget_unreadable_name_refused`; the two causes need different alerts. `used`/`reserved` compared raw `name` values while `widgetId` keys on `encodeURIComponent(String(name))`, so `undefined` against `'undefined'` — likewise `1` against `'1'` — passed this walk as distinct and minted one id. They key on the string now. Co-Authored-By: Claude Opus 5 (1M context) --- docs/adr/ECS-0008-entity-component-system.md | 28 +++++-- src/lib/litegraph/src/node/widgetsView.ts | 57 +++++++++++-- .../node/widgetsView.uniqueWidgetName.test.ts | 81 ++++++++++++++++++- src/types/widgetId.test.ts | 20 +++++ src/types/widgetId.ts | 33 ++++++-- 5 files changed, 199 insertions(+), 20 deletions(-) diff --git a/docs/adr/ECS-0008-entity-component-system.md b/docs/adr/ECS-0008-entity-component-system.md index f56a54ab5be..6063ee46793 100644 --- a/docs/adr/ECS-0008-entity-component-system.md +++ b/docs/adr/ECS-0008-entity-component-system.md @@ -188,10 +188,15 @@ legitimate re-mint rather than an identity collision — which is why > The repeat is renamed to `name#1` before any id is derived. Where it cannot > be — a `name` whose writes do not stick, or an accessor that throws > (`src/types/widgetId.ts`) — the widget is **refused**: it is dropped from -> `node.widgets` and reported under the stable `errorType` -> `widget_duplicate_name_refused`. First occurrence wins; renamable collisions +> `node.widgets` and reported. First occurrence wins; renamable collisions > elsewhere on the node are still renamed. > +> Two stable `errorType`s, because the causes need different alerts and +> collapsing them reports a collision that does not exist: +> `widget_duplicate_name_refused` for a duplicate that could not be renamed +> apart, and `widget_unreadable_name_refused` for a widget whose `name` +> accessor throws — that one has no duplicate at all, only no derivable id. +> > **There are two enforcement points, and looking only at the first one is > misleading.** `attachNodeToStores` calls `refuseAmbiguousNodeWidgets` as a > node joins a graph, which is the one that catches a node built detached and @@ -211,11 +216,20 @@ legitimate re-mint rather than an identity collision — which is why > the join needs its own call rather than falling out of that commit. > - **Renamability is judged after normalization.** `toConcreteWidget` merges > the concrete class's writable `name` accessor over a plain object's pinned -> one, so a raw widget that looks unrenamable usually is not. -> - **`SubgraphNode` does not commit through this path.** It redefines -> `widgets` as a computed getter over its promoted widgets and overrides -> `addCustomWidget`, so an ambiguous pair there keeps the pre-existing -> behaviour. +> one, so a raw widget that looks unrenamable usually is not. Normalizing +> first does mean `BaseWidget`'s constructor reads a hostile `name` before +> the refusal sees it, so the conversion is guarded per widget and an +> unconvertible widget falls through to be refused rather than throwing out +> of the commit and wedging every later one. +> - **`SubgraphNode` does not commit through this path, and neither +> enforcement point runs on it.** It redefines `widgets` as a computed getter +> over its promoted widgets and overrides `addCustomWidget`, so an ambiguous +> pair there keeps the pre-existing behaviour. The join-time call is gated on +> the node still exposing this module's mutation view: the getter rebuilds +> the array on every read, so a refusal there would splice a throwaway copy +> and report a refusal that did not happen. Two promoted inputs carrying the +> same inner widget name reach exactly that state, so the gate is +> load-bearing rather than defensive. > > A serialized `(name, occurrence)` identity was proposed instead, so that both > widgets could be persisted ([#19717](https://github.com/Comfy-Org/ComfyUI_frontend/pull/19717)). diff --git a/src/lib/litegraph/src/node/widgetsView.ts b/src/lib/litegraph/src/node/widgetsView.ts index 1dca3b7ccb0..baf46f36d73 100644 --- a/src/lib/litegraph/src/node/widgetsView.ts +++ b/src/lib/litegraph/src/node/widgetsView.ts @@ -6,9 +6,13 @@ import { toConcreteWidget } from '@/lib/litegraph/src/widgets/widgetMap' import { useWidgetValueStore } from '@/stores/widgetValueStore' import { reportError } from '@/platform/telemetry/reportError' -import { dropUnrenamableDuplicateWidgets } from '@/types/widgetId' +import { + dropUnrenamableDuplicateWidgets, + isWidgetNameUnreadable +} from '@/types/widgetId' import { createArrayMutationView } from '../infrastructure/createMutationView' +import { isNodeBindable } from '../utils/type' import { getWidgetIds } from '../utils/widget' /** @@ -20,6 +24,15 @@ import { getWidgetIds } from '../utils/widget' */ const DUPLICATE_WIDGET_NAME_ERROR_TYPE = 'widget_duplicate_name_refused' +/** + * Stable `errorType` for the other refusable state: a widget whose `name` + * accessor throws, so no `WidgetId` can be derived for it and no duplicate is + * involved. Separate from {@link DUPLICATE_WIDGET_NAME_ERROR_TYPE} because the + * two need different alerts — and because collapsing them reports a collision + * that does not exist. Also a contract, not an implementation detail. + */ +const UNREADABLE_WIDGET_NAME_ERROR_TYPE = 'widget_unreadable_name_refused' + interface WidgetsViewState { target: IBaseWidget[] view: IBaseWidget[] @@ -90,14 +103,22 @@ function refuseAmbiguousWidgets( if (!refused.length) return for (const widget of refused) { + // The two causes are different failures and are alerted on separately: an + // unreadable name has no duplicate at all, so reporting one would send + // whoever reads the alert looking for a collision that does not exist. + const unreadable = isWidgetNameUnreadable(widget) const widgetName = safeRead(() => widget.name) releaseRefusedWidget(node, widget) reportError( new Error( - `Refused a widget named "${widgetName}": node ${node.id} already has a widget of that name and the duplicate cannot be renamed` + unreadable + ? `Refused a widget on node ${node.id}: its name could not be read, so no widget identity can be derived for it` + : `Refused a widget named "${widgetName}": node ${node.id} already has a widget of that name and the duplicate cannot be renamed` ), { - errorType: DUPLICATE_WIDGET_NAME_ERROR_TYPE, + errorType: unreadable + ? UNREADABLE_WIDGET_NAME_ERROR_TYPE + : DUPLICATE_WIDGET_NAME_ERROR_TYPE, surface: 'graph', level: 'warning', tags: { node_type: node.type }, @@ -144,8 +165,17 @@ export function wasWidgetRefused( * This runs where identities actually come into existence — immediately before * the node's widgets are registered — which is the first point at which an * ambiguous pair can do any harm. + * + * Only for a node whose widgets list this module owns. `SubgraphNode`'s getter + * rebuilds the array on every read, so a refusal there splices a throwaway copy + * and nothing leaves the node — while the caller still reports + * `widget_duplicate_name_refused` and tears down the slot back-references of a + * widget that is still there. Two promoted inputs carrying the same inner + * widget name reach exactly that state, so the guard is load-bearing rather + * than defensive. */ export function refuseAmbiguousNodeWidgets(node: LGraphNode): void { + if (!commitsThroughWidgetsView(node)) return const widgets = node.widgets if (!widgets?.length) return refuseAmbiguousWidgets(node, widgets) @@ -155,9 +185,18 @@ function syncWidgetOrder(node: LGraphNode, widgets: IBaseWidget[]): void { node._widgetSlotsDirty = true const graphId = node.graph?.rootGraph.id - const concreteWidgets = widgets.map((widget) => - toConcreteWidget(widget, node) - ) + // `BaseWidget`'s constructor reads the source object's `name`, so converting + // a raw push whose accessor throws throws out of this commit — and out of + // every later one, wedging the node with a stale store order. That is the + // exact state `UNREADABLE_NAME` exists to contain, so leave the object + // unconverted and let the refusal below take it. + const concreteWidgets = widgets.map((widget) => { + try { + return toConcreteWidget(widget, node) + } catch { + return widget + } + }) for (const [index, widget] of concreteWidgets.entries()) { widgets[index] = widget } @@ -175,7 +214,11 @@ function syncWidgetOrder(node: LGraphNode, widgets: IBaseWidget[]): void { refuseAmbiguousWidgets(node, widgets) for (const widget of concreteWidgets) { - if (widgets.includes(widget)) widget.setNodeId(node.id) + // A widget that would not convert is still raw and so not bindable; it has + // also just been refused, so it is no longer on the node either. + if (widgets.includes(widget) && isNodeBindable(widget)) { + widget.setNodeId(node.id) + } } useWidgetValueStore().replaceNodeWidgetOrder( diff --git a/src/lib/litegraph/src/node/widgetsView.uniqueWidgetName.test.ts b/src/lib/litegraph/src/node/widgetsView.uniqueWidgetName.test.ts index 49671a892cd..3f00b37ace6 100644 --- a/src/lib/litegraph/src/node/widgetsView.uniqueWidgetName.test.ts +++ b/src/lib/litegraph/src/node/widgetsView.uniqueWidgetName.test.ts @@ -4,8 +4,14 @@ import { LGraph, LGraphNode, LiteGraph } from '@/lib/litegraph/src/litegraph' import type { IBaseWidget } from '@/lib/litegraph/src/types/widgets' import { reportError } from '@/platform/telemetry/reportError' import { useWidgetValueStore } from '@/stores/widgetValueStore' +import { toNodeId } from '@/types/nodeId' import { widgetId } from '@/types/widgetId' +import { + createTestSubgraph, + createTestSubgraphNode +} from '../subgraph/__fixtures__/subgraphHelpers' + vi.mock(import('@/platform/telemetry/reportError')) /** @@ -253,15 +259,53 @@ describe('unique widget name invariant', () => { ).not.toThrow() expect(names(node)).toEqual(['seed', 'cfg']) + // Its own cause, not the duplicate one: this widget has no duplicate, and + // an alert that says it does sends the reader hunting for a collision. expect(reportError).toHaveBeenCalledExactlyOnceWith( expect.any(Error), expect.objectContaining({ - errorType: 'widget_duplicate_name_refused', + errorType: 'widget_unreadable_name_refused', context: expect.objectContaining({ widgetName: undefined }) }) ) }) + it('refuses a raw pushed widget whose name throws instead of wedging the node', () => { + const node = createNode() + node.addWidget('number', 'seed', 1, () => undefined, {}) + + // `BaseWidget`'s constructor reads the source object's `name`, so + // converting this throws out of the commit before the refusal can see it — + // and out of every later commit too, which is what wedges the node. + const hostile = { + get name(): string { + throw new Error('name is not readable') + }, + type: 'number', + value: 2, + y: 0, + options: {} + } + + expect(() => node.widgets!.push(hostile as never)).not.toThrow() + // `indexOf` rather than `not.toContain`: the matcher deep-compares, which + // reads the getter and throws out of the assertion itself. + expect(node.widgets!.indexOf(hostile as never)).toBe(-1) + + // The node still takes widgets afterwards, and the store's order keeps up. + expect(() => + node.addWidget('number', 'steps', 3, () => undefined, {}) + ).not.toThrow() + expect(names(node)).toEqual(['seed', 'steps']) + expect(storedNames(node)).toEqual(['seed', 'steps']) + expect(reportError).toHaveBeenCalledExactlyOnceWith( + expect.any(Error), + expect.objectContaining({ + errorType: 'widget_unreadable_name_refused' + }) + ) + }) + it('clears slot back-references to a widget it refused', () => { const node = createNode() node.addWidget('number', 'seed', 1, () => undefined, {}) @@ -293,4 +337,39 @@ describe('unique widget name invariant', () => { expect(names(node)).toEqual(['b', 'a']) expect(reportError).not.toHaveBeenCalled() }) + + it('does not report a refusal it cannot carry out on a subgraph node', () => { + // A `SubgraphNode` rebuilds `widgets` on every read, so nothing this + // module splices ever leaves the node. Enforcing there anyway reports the + // alerting contract `widget_duplicate_name_refused` for a refusal that did + // not happen — and promoted projections have a getter-only `name`, so a + // node promoting the same inner widget name twice hits it on every add. + const subgraph = createTestSubgraph({ + inputs: [ + { name: 'first', type: 'INT' }, + { name: 'second', type: 'INT' } + ] + }) + const host = createTestSubgraphNode(subgraph) + const store = useWidgetValueStore() + const rootGraphId = host.rootGraph.id + + for (const [slot, sourceNodeId] of [ + [0, 900], + [1, 901] + ] as const) { + const id = widgetId(rootGraphId, toNodeId(sourceNodeId), 'seed') + store.registerWidget(id, { type: 'number', value: slot, options: {} }) + host.inputs[slot].widgetId = id + } + + expect(host.widgets.map((widget) => widget.name)).toEqual(['seed', 'seed']) + + host.rootGraph.add(host) + + // Still both there: this node class is outside the invariant's reach, and + // that is the pre-existing behaviour the refusal must not pretend to change. + expect(host.widgets.map((widget) => widget.name)).toEqual(['seed', 'seed']) + expect(reportError).not.toHaveBeenCalled() + }) }) diff --git a/src/types/widgetId.test.ts b/src/types/widgetId.test.ts index 898926aa0d5..e165436dc6f 100644 --- a/src/types/widgetId.test.ts +++ b/src/types/widgetId.test.ts @@ -151,6 +151,26 @@ describe('dropUnrenamableDuplicateWidgets', () => { expect(widgets.map(({ name }) => name)).toEqual([undefined, 'undefined#1']) }) + it('collides names that differ as values but coincide as id strings', () => { + // `widgetId` keys on `encodeURIComponent(String(name))`, so these two mint + // the same id. Comparing the raw values lets both through and the clash + // lands in the store, where nothing is looking for it. + const widgets = [ + { name: undefined as unknown as string }, + { name: 'undefined' }, + { name: 1 as unknown as string }, + { name: '1' } + ] + + expect(dropUnrenamableDuplicateWidgets(widgets)).toEqual([]) + expect(widgets.map(({ name }) => name)).toEqual([ + undefined, + 'undefined#1', + 1, + '1#1' + ]) + }) + it('offers another name when a setter rejects only the first one', () => { // `BaseWidget` delegates its `name` setter to the store, which refuses to // move onto an id something else already holds. Refusal deletes a widget, diff --git a/src/types/widgetId.ts b/src/types/widgetId.ts index caf0b6c1468..db9b39740ff 100644 --- a/src/types/widgetId.ts +++ b/src/types/widgetId.ts @@ -105,12 +105,34 @@ function tryRename(widget: { name: string }, name: string): boolean { } } -/** Every name the array already holds outright, skipping unreadable ones. */ +/** + * Whether {@link widget}'s `name` cannot be read at all. Callers that report a + * refusal need this to name the cause: a widget refused for an unreadable name + * has no duplicate, so saying it has one is wrong. + */ +export function isWidgetNameUnreadable(widget: { name: string }): boolean { + return readName(widget) === UNREADABLE_NAME +} + +/** + * The identity a name actually claims. `widgetId` keys on + * `encodeURIComponent(String(name))`, so two names that differ as values but + * coincide as strings — `undefined` against `'undefined'`, `1` against `'1'` — + * are one identity and have to collide here, or they collide downstream where + * nothing is watching. + */ +// Takes `unknown` on purpose: `name` is declared `string` and at runtime is +// whatever a node pack assigned, which is the entire reason the coercion is here. +function nameKey(name: unknown): string { + return String(name) +} + +/** Every name key the array already holds outright, skipping unreadable ones. */ function readableNames(widgets: readonly { name: string }[]): Set { const names = new Set() for (const widget of widgets) { const name = readName(widget) - if (name !== UNREADABLE_NAME) names.add(name) + if (name !== UNREADABLE_NAME) names.add(nameKey(name)) } return names } @@ -221,14 +243,15 @@ export function dropUnrenamableDuplicateWidgets( continue } - if (!used.has(name)) { - used.add(name) + const key = nameKey(name) + if (!used.has(key)) { + used.add(key) verdicts.set(widget, true) kept.push(widget) continue } - const unique = renameApart(widget, name, used, reserved) + const unique = renameApart(widget, key, used, reserved) if (unique === undefined) { verdicts.set(widget, false) refused.push(widget) From 16aa4e8c8d783b19235d44444d5e2671d22ddc9e Mon Sep 17 00:00:00 2001 From: Christian Byrne Date: Sun, 4 Oct 2026 06:41:05 -0700 Subject: [PATCH 07/35] fix(widgets): only swallow the conversion failure the refusal will take MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The guard added for the throwing-`name` wedge caught every conversion failure, not just that one. `toConcreteWidget` reads `type` as well, and a widget whose `type` accessor throws has a perfectly readable name — so the refusal has no reason to drop it, and swallowing left it raw on the node and in the store's order with nothing having reported anything. That one keeps throwing, as it did before this branch. Co-Authored-By: Claude Opus 5 (1M context) --- src/lib/litegraph/src/node/widgetsView.ts | 7 +++++- .../node/widgetsView.uniqueWidgetName.test.ts | 24 +++++++++++++++++++ 2 files changed, 30 insertions(+), 1 deletion(-) diff --git a/src/lib/litegraph/src/node/widgetsView.ts b/src/lib/litegraph/src/node/widgetsView.ts index baf46f36d73..6580435fd7c 100644 --- a/src/lib/litegraph/src/node/widgetsView.ts +++ b/src/lib/litegraph/src/node/widgetsView.ts @@ -193,7 +193,12 @@ function syncWidgetOrder(node: LGraphNode, widgets: IBaseWidget[]): void { const concreteWidgets = widgets.map((widget) => { try { return toConcreteWidget(widget, node) - } catch { + } catch (error) { + // Only the unreadable-name case is swallowed, and only because the + // refusal below is about to take this widget anyway. Conversion reads + // `type` too, and a failure there leaves a widget the refusal has no + // reason to drop — so it keeps throwing, as it did before. + if (!isWidgetNameUnreadable(widget)) throw error return widget } }) diff --git a/src/lib/litegraph/src/node/widgetsView.uniqueWidgetName.test.ts b/src/lib/litegraph/src/node/widgetsView.uniqueWidgetName.test.ts index 3f00b37ace6..17f3e4f811c 100644 --- a/src/lib/litegraph/src/node/widgetsView.uniqueWidgetName.test.ts +++ b/src/lib/litegraph/src/node/widgetsView.uniqueWidgetName.test.ts @@ -306,6 +306,30 @@ describe('unique widget name invariant', () => { ) }) + it('does not swallow a conversion failure the refusal would not take', () => { + const node = createNode() + node.addWidget('number', 'seed', 1, () => undefined, {}) + + // Conversion reads `type` as well as `name`. This widget's name is + // perfectly readable, so the refusal has no reason to drop it — letting + // the conversion failure pass would leave a raw widget on the node and in + // the store's order with nothing having reported it. + const hostile = { + name: 'steps', + get type(): string { + throw new Error('type is not readable') + }, + value: 2, + y: 0, + options: {} + } + + expect(() => node.widgets!.push(hostile as never)).toThrow( + 'type is not readable' + ) + expect(reportError).not.toHaveBeenCalled() + }) + it('clears slot back-references to a widget it refused', () => { const node = createNode() node.addWidget('number', 'seed', 1, () => undefined, {}) From d900b3d4430bbe822e9211f1db91bba5632ab621 Mon Sep 17 00:00:00 2001 From: Christian Byrne Date: Sun, 4 Oct 2026 07:18:53 -0700 Subject: [PATCH 08/35] fix(widgets): derive the name key where a hostile one cannot escape MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Three findings from the review of the previous head, and one of them was mine: `String(name)` for the identity key sat outside the guard, so a name that reads fine but does not coerce — `Object.create(null)`, a throwing `toString` — threw out of the commit after the normalization write-back landed and before the splice, and then out of every later commit. That is the same permanent wedge the last change fixed for throwing getters, reintroduced one line later and with no report fired. Reading the name and deriving its key are now one guarded step, and the step mirrors what `widgetId` actually does: coerce, then check the name can be percent-encoded. A lone surrogate keyed cleanly before and then threw later out of `getWidgetIds`, far from anything that could explain it. All three failures are now the same answer, which is refusal. The refusal cause is recorded by the walk instead of re-derived at the report site. Asking a hostile accessor a third time is asking a question that need not have the same answer twice: a getter that throws transiently was reported as a duplicate name, with a populated widget name and no collision anywhere on the node — the exact mislabel the two error types were introduced to prevent. The conversion guard's claim is narrowed rather than widened, in the comment and in the ADR. It covers the commit path only: `addCustomWidget` converts before it pushes, so `addWidget` and `addDOMWidget` with a hostile accessor still throw to their caller and never reach the refusal. Co-Authored-By: Claude Opus 5 (1M context) --- docs/adr/ECS-0008-entity-component-system.md | 12 ++- src/lib/litegraph/src/node/widgetsView.ts | 14 +++- .../node/widgetsView.uniqueWidgetName.test.ts | 29 +++++++ src/types/widgetId.test.ts | 82 ++++++++++++++++--- src/types/widgetId.ts | 75 +++++++++++------ 5 files changed, 166 insertions(+), 46 deletions(-) diff --git a/docs/adr/ECS-0008-entity-component-system.md b/docs/adr/ECS-0008-entity-component-system.md index 6063ee46793..0634b3109b7 100644 --- a/docs/adr/ECS-0008-entity-component-system.md +++ b/docs/adr/ECS-0008-entity-component-system.md @@ -218,9 +218,15 @@ legitimate re-mint rather than an identity collision — which is why > the concrete class's writable `name` accessor over a plain object's pinned > one, so a raw widget that looks unrenamable usually is not. Normalizing > first does mean `BaseWidget`'s constructor reads a hostile `name` before -> the refusal sees it, so the conversion is guarded per widget and an -> unconvertible widget falls through to be refused rather than throwing out -> of the commit and wedging every later one. +> the refusal sees it, so the conversion is guarded **for that one case**: +> a widget whose name cannot be read falls through to be refused instead of +> throwing out of the commit and wedging every later one. Any other +> conversion failure still throws, because the refusal has no reason to drop +> that widget and swallowing it would leave an unconverted object on the node +> with nothing reported. The guard also only covers the commit path — a raw +> `push`, a splice, a whole-array assignment. `addCustomWidget` converts +> before it pushes, so `addWidget` and `addDOMWidget` with a hostile accessor +> still throw to their caller and never reach the refusal. > - **`SubgraphNode` does not commit through this path, and neither > enforcement point runs on it.** It redefines `widgets` as a computed getter > over its promoted widgets and overrides `addCustomWidget`, so an ambiguous diff --git a/src/lib/litegraph/src/node/widgetsView.ts b/src/lib/litegraph/src/node/widgetsView.ts index 6580435fd7c..191bf849962 100644 --- a/src/lib/litegraph/src/node/widgetsView.ts +++ b/src/lib/litegraph/src/node/widgetsView.ts @@ -102,11 +102,14 @@ function refuseAmbiguousWidgets( const refused = dropUnrenamableDuplicateWidgets(widgets) if (!refused.length) return - for (const widget of refused) { + for (const { widget, cause } of refused) { // The two causes are different failures and are alerted on separately: an // unreadable name has no duplicate at all, so reporting one would send // whoever reads the alert looking for a collision that does not exist. - const unreadable = isWidgetNameUnreadable(widget) + // The cause comes from the walk rather than from another read of the + // accessor, which is hostile by definition and need not answer twice the + // same way. + const unreadable = cause === 'unreadable-name' const widgetName = safeRead(() => widget.name) releaseRefusedWidget(node, widget) reportError( @@ -196,8 +199,11 @@ function syncWidgetOrder(node: LGraphNode, widgets: IBaseWidget[]): void { } catch (error) { // Only the unreadable-name case is swallowed, and only because the // refusal below is about to take this widget anyway. Conversion reads - // `type` too, and a failure there leaves a widget the refusal has no - // reason to drop — so it keeps throwing, as it did before. + // `type`, `options` and `value` too, and a failure in any of those + // leaves a widget the refusal has no reason to drop — so it keeps + // throwing, as it did before. This also only covers the commit path: + // `addCustomWidget` converts before it pushes, so `addWidget` and + // `addDOMWidget` still throw to their caller. if (!isWidgetNameUnreadable(widget)) throw error return widget } diff --git a/src/lib/litegraph/src/node/widgetsView.uniqueWidgetName.test.ts b/src/lib/litegraph/src/node/widgetsView.uniqueWidgetName.test.ts index 17f3e4f811c..a19cdbfc812 100644 --- a/src/lib/litegraph/src/node/widgetsView.uniqueWidgetName.test.ts +++ b/src/lib/litegraph/src/node/widgetsView.uniqueWidgetName.test.ts @@ -306,6 +306,35 @@ describe('unique widget name invariant', () => { ) }) + it('reports the cause the walk decided, not the one a later read suggests', () => { + const node = createNode() + node.addWidget('number', 'seed', 1, () => undefined, {}) + const flaky = node.addWidget('number', 'steps', 2, () => undefined, {}) + + // Throws for the reserved-names pass and for the walk, then succeeds. The + // walk refuses it for an unreadable name; anything that asks the accessor + // again afterwards gets a readable name and would call it a duplicate. + let reads = 0 + Object.defineProperty(flaky, 'name', { + get(): string { + reads++ + if (reads <= 2) throw new Error('name is not readable') + return 'seed' + }, + configurable: true + }) + + node.addWidget('number', 'cfg', 3, () => undefined, {}) + + expect(node.widgets!.indexOf(flaky)).toBe(-1) + expect(reportError).toHaveBeenCalledExactlyOnceWith( + expect.any(Error), + expect.objectContaining({ + errorType: 'widget_unreadable_name_refused' + }) + ) + }) + it('does not swallow a conversion failure the refusal would not take', () => { const node = createNode() node.addWidget('number', 'seed', 1, () => undefined, {}) diff --git a/src/types/widgetId.test.ts b/src/types/widgetId.test.ts index e165436dc6f..c3c666c4e46 100644 --- a/src/types/widgetId.test.ts +++ b/src/types/widgetId.test.ts @@ -38,6 +38,11 @@ describe('ensureUniqueWidgetNames', () => { }) }) +/** The refused widgets alone; the cause is asserted separately where it matters. */ +function refusedWidgets(widgets: T[]): T[] { + return dropUnrenamableDuplicateWidgets(widgets).map(({ widget }) => widget) +} + describe('dropUnrenamableDuplicateWidgets', () => { beforeEach(() => { // `ensureUniqueWidgetNames` warns whenever it gives up on a rename, which @@ -55,14 +60,14 @@ describe('dropUnrenamableDuplicateWidgets', () => { it('refuses nothing and mutates nothing when every name is already unique', () => { const widgets = [{ name: 'seed' }, { name: 'steps' }] - expect(dropUnrenamableDuplicateWidgets(widgets)).toEqual([]) + expect(refusedWidgets(widgets)).toEqual([]) expect(widgets.map(({ name }) => name)).toEqual(['seed', 'steps']) }) it('refuses nothing when the duplicate can be renamed', () => { const widgets = [{ name: 'seed' }, { name: 'seed' }] - expect(dropUnrenamableDuplicateWidgets(widgets)).toEqual([]) + expect(refusedWidgets(widgets)).toEqual([]) expect(widgets.map(({ name }) => name)).toEqual(['seed', 'seed#1']) }) @@ -71,7 +76,7 @@ describe('dropUnrenamableDuplicateWidgets', () => { const refused = pinned('seed') const widgets = [first, refused] - expect(dropUnrenamableDuplicateWidgets(widgets)).toEqual([refused]) + expect(refusedWidgets(widgets)).toEqual([refused]) expect(widgets).toEqual([first]) }) @@ -86,7 +91,7 @@ describe('dropUnrenamableDuplicateWidgets', () => { { name: 'steps' } ] - expect(dropUnrenamableDuplicateWidgets(widgets)).toEqual([refused]) + expect(refusedWidgets(widgets)).toEqual([refused]) expect(widgets.map(({ name }) => name)).toEqual([ 'seed', 'steps', @@ -101,7 +106,7 @@ describe('dropUnrenamableDuplicateWidgets', () => { // reach past it rather than collide with a name nothing renamed. widgets.push({ name: 'seed#1' }) - expect(dropUnrenamableDuplicateWidgets(widgets)).toEqual([refused]) + expect(refusedWidgets(widgets)).toEqual([refused]) expect(widgets.map(({ name }) => name)).toEqual([ 'seed', 'seed#2', @@ -120,7 +125,7 @@ describe('dropUnrenamableDuplicateWidgets', () => { // Its descriptor has a setter, so a descriptor check believes the rename // will take; only reading the name back afterwards proves it did not. - expect(dropUnrenamableDuplicateWidgets(widgets)).toContain(stubborn) + expect(refusedWidgets(widgets)).toContain(stubborn) expect(widgets.map(({ name }) => name)).toEqual(['seed']) }) @@ -136,7 +141,7 @@ describe('dropUnrenamableDuplicateWidgets', () => { // leaving it on the node makes `ensureUniqueWidgetNames` fail on every // later call — which bails registration for the whole node, including the // widgets that are perfectly addressable. The throw must not escape. - expect(dropUnrenamableDuplicateWidgets(widgets)).toEqual([hostile]) + expect(refusedWidgets(widgets)).toEqual([hostile]) expect(widgets).toHaveLength(1) }) @@ -147,10 +152,61 @@ describe('dropUnrenamableDuplicateWidgets', () => { // `undefined` is a bad identity, not a missing one: two of them collide // with each other and would mint the same `graphId:nodeId:undefined`. - expect(dropUnrenamableDuplicateWidgets(widgets)).toEqual([]) + expect(refusedWidgets(widgets)).toEqual([]) expect(widgets.map(({ name }) => name)).toEqual([undefined, 'undefined#1']) }) + it('refuses a name that reads fine but cannot become an id', () => { + // Both of these read without throwing and then fail on the way to a + // `WidgetId`: one will not coerce to a string at all, the other is a lone + // surrogate that `encodeURIComponent` rejects. Letting either escape wedges + // the commit that is trying to settle the node's names. + const unstringifiable = { name: Object.create(null) as string } + const unencodable = { name: '\uD800' } + const fine = { name: 'seed' } + const widgets = [fine, unstringifiable, unencodable] + + const refused = dropUnrenamableDuplicateWidgets(widgets) + + expect(refused.map(({ widget }) => widget)).toEqual([ + unstringifiable, + unencodable + ]) + expect(widgets).toEqual([fine]) + }) + + it('records why each widget was refused, rather than leaving it to be guessed', () => { + // A hostile accessor need not answer the same way twice, so the cause has + // to come from the walk that made the decision. + // Reads 1 and 2 are the reserved-names pass and the walk itself; a third + // read — which is what re-deriving the cause at the report site costs — + // succeeds and would call this a duplicate instead. + let reads = 0 + const flaky = { + get name(): string { + reads++ + if (reads <= 2) throw new Error('not readable yet') + return 'seed' + } + } + const first = { name: 'seed' } + const pinned = { name: 'other' } + Object.defineProperty(pinned, 'name', { + value: 'seed', + writable: false, + configurable: false + }) + + const refused = dropUnrenamableDuplicateWidgets([first, flaky, pinned]) + + expect(refused.map(({ cause }) => cause)).toEqual([ + 'unreadable-name', + 'duplicate-name' + ]) + // The widget now reads as a plain duplicate, which is the wrong answer. + expect(flaky.name).toBe('seed') + }) + it('collides names that differ as values but coincide as id strings', () => { // `widgetId` keys on `encodeURIComponent(String(name))`, so these two mint // the same id. Comparing the raw values lets both through and the clash @@ -162,7 +218,7 @@ describe('dropUnrenamableDuplicateWidgets', () => { { name: '1' } ] - expect(dropUnrenamableDuplicateWidgets(widgets)).toEqual([]) + expect(refusedWidgets(widgets)).toEqual([]) expect(widgets.map(({ name }) => name)).toEqual([ undefined, 'undefined#1', @@ -186,7 +242,7 @@ describe('dropUnrenamableDuplicateWidgets', () => { } const widgets = [{ name: 'seed' }, picky] - expect(dropUnrenamableDuplicateWidgets(widgets)).toEqual([]) + expect(refusedWidgets(widgets)).toEqual([]) expect(widgets.map((widget) => widget.name)).toEqual(['seed', 'seed#2']) }) @@ -203,7 +259,7 @@ describe('dropUnrenamableDuplicateWidgets', () => { const renamable = { name: 'seed' } const widgets = [{ name: 'seed' }, stubborn, renamable] - expect(dropUnrenamableDuplicateWidgets(widgets)).toEqual([stubborn]) + expect(refusedWidgets(widgets)).toEqual([stubborn]) // `seed#1` was offered to `stubborn` and did not take, so it is still free // for the next widget — a name one setter refuses is not a name in use. expect(offered).toContain('seed#1') @@ -216,7 +272,7 @@ describe('dropUnrenamableDuplicateWidgets', () => { // The identity bypass that keeps a reordering widget in place must not // re-admit one whose first occurrence was already refused and reported. - expect(dropUnrenamableDuplicateWidgets(widgets)).toEqual([refused]) + expect(refusedWidgets(widgets)).toEqual([refused]) expect(widgets.map(({ name }) => name)).toEqual(['seed']) }) @@ -226,7 +282,7 @@ describe('dropUnrenamableDuplicateWidgets', () => { const widgets = [shared, shared, other] // Identity duplicates are one widget mid-reorder, not a name collision. - expect(dropUnrenamableDuplicateWidgets(widgets)).toEqual([other]) + expect(refusedWidgets(widgets)).toEqual([other]) expect(widgets).toEqual([shared, shared]) }) }) diff --git a/src/types/widgetId.ts b/src/types/widgetId.ts index db9b39740ff..2f218e8075a 100644 --- a/src/types/widgetId.ts +++ b/src/types/widgetId.ts @@ -79,16 +79,48 @@ export function ensureUniqueWidgetNames( } /** - * A `name` that could not be read at all, because the accessor threw. Distinct - * from a widget whose name *is* `undefined`: that one has an identity, a bad - * one, and two of them collide with each other. + * A `name` from which no identity can be derived — the accessor threw, the + * value would not coerce to a string, or the result is not something + * {@link widgetId} can encode. Distinct from a widget whose name *is* + * `undefined`: that one has an identity, a bad one, and two of them collide + * with each other. */ const UNREADABLE_NAME = Symbol('unreadable widget name') -/** Reads `name` without letting a throwing accessor escape. */ +/** Why a widget could not be given a unique name on its node. */ +type WidgetRefusalCause = 'unreadable-name' | 'duplicate-name' + +/** A refused widget, with the cause recorded by the walk that refused it. */ +export interface RefusedWidget { + widget: T + cause: WidgetRefusalCause +} + +/** + * Reads `name` and derives the identity it claims, without letting a hostile + * accessor escape. + * + * Returns the **key**, not the raw value. `widgetId` keys on + * `encodeURIComponent(String(name))`, so two names that differ as values but + * coincide as strings — `undefined` against `'undefined'`, `1` against `'1'` — + * are one identity and have to collide here or they collide downstream where + * nothing is watching. + * + * All three steps are inside the guard on purpose. A getter that throws is the + * obvious case; a name that does not coerce (`Object.create(null)`) and one + * that `encodeURIComponent` rejects (a lone surrogate) are the same failure + * wearing different clothes, and letting either escape wedges this commit and + * every later one on the node. + */ function readName(widget: { name: string }): string | typeof UNREADABLE_NAME { try { - return widget.name + // `name` is declared `string` and at runtime is whatever a node pack + // assigned, which is the entire reason the coercion is here. + const raw: unknown = widget.name + const key = String(raw) + // Mirrors `widgetId`: the key is only usable if the id can be built from it. + encodeURIComponent(key) + return key } catch { return UNREADABLE_NAME } @@ -114,25 +146,12 @@ export function isWidgetNameUnreadable(widget: { name: string }): boolean { return readName(widget) === UNREADABLE_NAME } -/** - * The identity a name actually claims. `widgetId` keys on - * `encodeURIComponent(String(name))`, so two names that differ as values but - * coincide as strings — `undefined` against `'undefined'`, `1` against `'1'` — - * are one identity and have to collide here, or they collide downstream where - * nothing is watching. - */ -// Takes `unknown` on purpose: `name` is declared `string` and at runtime is -// whatever a node pack assigned, which is the entire reason the coercion is here. -function nameKey(name: unknown): string { - return String(name) -} - /** Every name key the array already holds outright, skipping unreadable ones. */ function readableNames(widgets: readonly { name: string }[]): Set { const names = new Set() for (const widget of widgets) { const name = readName(widget) - if (name !== UNREADABLE_NAME) names.add(nameKey(name)) + if (name !== UNREADABLE_NAME) names.add(name) } return names } @@ -210,14 +229,17 @@ function renameApart( * accepts the write and ignores it satisfies that check, so delegating would * report success over a node that still carries the ambiguous pair. * - * @returns the removed widgets, in array order. Empty when the node was - * already unambiguous, which is the overwhelmingly common case. + * @returns the removed widgets with the cause of each refusal, in array order. + * Empty when the node was already unambiguous, which is the overwhelmingly + * common case. The cause is recorded here rather than re-derived by the + * caller: re-reading a hostile accessor to ask "was this one unreadable?" can + * answer differently the second time and mislabel the report. */ export function dropUnrenamableDuplicateWidgets( widgets: T[] -): T[] { +): RefusedWidget[] { const kept: T[] = [] - const refused: T[] = [] + const refused: RefusedWidget[] = [] const used = new Set() const reserved = readableNames(widgets) /** Every widget already walked, against whether that walk kept it. */ @@ -239,11 +261,12 @@ export function dropUnrenamableDuplicateWidgets( // node makes `ensureUniqueWidgetNames` fail on every later call — which // bails registration for every *other* widget on the node too. verdicts.set(widget, false) - refused.push(widget) + refused.push({ widget, cause: 'unreadable-name' }) continue } - const key = nameKey(name) + // `readName` already returned the key, not the raw value. + const key = name if (!used.has(key)) { used.add(key) verdicts.set(widget, true) @@ -254,7 +277,7 @@ export function dropUnrenamableDuplicateWidgets( const unique = renameApart(widget, key, used, reserved) if (unique === undefined) { verdicts.set(widget, false) - refused.push(widget) + refused.push({ widget, cause: 'duplicate-name' }) continue } used.add(unique) From 0eb794a9a8df405153b3c61d2be2e5fc6bf7af1f Mon Sep 17 00:00:00 2001 From: Christian Byrne Date: Sun, 4 Oct 2026 07:23:31 -0700 Subject: [PATCH 09/35] test(widgets): meet the repo's own test rules in the new cases Two review findings on the suites, both against this repo's stated guidelines rather than against behaviour. The malformed-name fixtures used double assertions to make invalid data satisfy `{ name: string }`. The runtime type *is* what these cases test, so the narrowing happens once, in one named helper at the boundary, instead of at each fixture. The subgraph case set up its two promoted inputs in a loop, which hid which source node id carried which value. Both slots are explicit now. No assertion changed; all eighteen mutants still die. Co-Authored-By: Claude Opus 5 (1M context) --- .../node/widgetsView.uniqueWidgetName.test.ts | 24 ++++++++++++------- src/types/widgetId.test.ts | 19 +++++++++++---- 2 files changed, 30 insertions(+), 13 deletions(-) diff --git a/src/lib/litegraph/src/node/widgetsView.uniqueWidgetName.test.ts b/src/lib/litegraph/src/node/widgetsView.uniqueWidgetName.test.ts index a19cdbfc812..e31a23484df 100644 --- a/src/lib/litegraph/src/node/widgetsView.uniqueWidgetName.test.ts +++ b/src/lib/litegraph/src/node/widgetsView.uniqueWidgetName.test.ts @@ -407,14 +407,22 @@ describe('unique widget name invariant', () => { const store = useWidgetValueStore() const rootGraphId = host.rootGraph.id - for (const [slot, sourceNodeId] of [ - [0, 900], - [1, 901] - ] as const) { - const id = widgetId(rootGraphId, toNodeId(sourceNodeId), 'seed') - store.registerWidget(id, { type: 'number', value: slot, options: {} }) - host.inputs[slot].widgetId = id - } + // Same inner widget name on two different inner nodes, which is what + // promoting `seed` from two samplers produces. + const firstPromoted = widgetId(rootGraphId, toNodeId(900), 'seed') + const secondPromoted = widgetId(rootGraphId, toNodeId(901), 'seed') + store.registerWidget(firstPromoted, { + type: 'number', + value: 0, + options: {} + }) + store.registerWidget(secondPromoted, { + type: 'number', + value: 1, + options: {} + }) + host.inputs[0].widgetId = firstPromoted + host.inputs[1].widgetId = secondPromoted expect(host.widgets.map((widget) => widget.name)).toEqual(['seed', 'seed']) diff --git a/src/types/widgetId.test.ts b/src/types/widgetId.test.ts index c3c666c4e46..ded772e35ee 100644 --- a/src/types/widgetId.test.ts +++ b/src/types/widgetId.test.ts @@ -38,6 +38,15 @@ describe('ensureUniqueWidgetNames', () => { }) }) +/** + * A widget whose `name` is whatever a node pack actually assigned. The runtime + * type is the thing under test, so the narrowing happens once here rather than + * at each fixture. + */ +function widgetNamed(name: unknown): { name: string } { + return { name } as { name: string } +} + /** The refused widgets alone; the cause is asserted separately where it matters. */ function refusedWidgets(widgets: T[]): T[] { return dropUnrenamableDuplicateWidgets(widgets).map(({ widget }) => widget) @@ -146,8 +155,8 @@ describe('dropUnrenamableDuplicateWidgets', () => { }) it('tells an unreadable name apart from one that reads as undefined', () => { - const first = { name: undefined as unknown as string } - const second = { name: undefined as unknown as string } + const first = widgetNamed(undefined) + const second = widgetNamed(undefined) const widgets = [first, second] // `undefined` is a bad identity, not a missing one: two of them collide @@ -161,7 +170,7 @@ describe('dropUnrenamableDuplicateWidgets', () => { // `WidgetId`: one will not coerce to a string at all, the other is a lone // surrogate that `encodeURIComponent` rejects. Letting either escape wedges // the commit that is trying to settle the node's names. - const unstringifiable = { name: Object.create(null) as string } + const unstringifiable = widgetNamed(Object.create(null)) const unencodable = { name: '\uD800' } const fine = { name: 'seed' } const widgets = [fine, unstringifiable, unencodable] @@ -212,9 +221,9 @@ describe('dropUnrenamableDuplicateWidgets', () => { // the same id. Comparing the raw values lets both through and the clash // lands in the store, where nothing is looking for it. const widgets = [ - { name: undefined as unknown as string }, + widgetNamed(undefined), { name: 'undefined' }, - { name: 1 as unknown as string }, + widgetNamed(1), { name: '1' } ] From ea30af50561390a741857626304eeb6f489e831b Mon Sep 17 00:00:00 2001 From: Christian Byrne Date: Sun, 4 Oct 2026 07:58:38 -0700 Subject: [PATCH 10/35] fix(widgets): refuse on whether the name could be written, not on the read-back MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The unique-name invariant removed a widget whenever a rename did not read back. `BaseWidget.set name` delegates to `widgetValueStore.renameWidget()` and returns without changing the name whenever the store declines — which it does when the node has no entries, exactly the state an ambiguous pair leaves a node in and the state a node is in after it has been removed from the graph. So the read-back reports failure for an ordinary, fully renamable widget, and removing on it destroyed that widget. Measured on the parent commit through the real app: a node deleted and re-added comes back one widget short and saves **one** `widgets_values` entry for a two-widget node. Positional widget addressing reads that arity, so a dropped slot shifts every later widget. The read-back still decides whether the pair is reported; `nameIsWritable` now decides whether the widget is removed, and it is deliberately the same predicate `ensureUniqueWidgetNames` uses to decide it may rename at all — `setNodeId` gates registration on that, so two copies of the rule disagreeing is a widget destroyed over a disagreement. The predicate is extracted rather than duplicated. A pair the node keeps is reported under a third stable errorType, `widget_duplicate_name_unresolved`, so the ambiguity stays observable without being paid for in user data. A widget whose name genuinely cannot be written is still removed, and that proof is unchanged. Not fixed here, and called out in the spec so it is not mistaken for correct: re-registering an ambiguous pair routes the second widget's `name` setter through `renameWidget` on a stale `_state.nodeId`, which hands it the first widget's store entry, so both read the first widget's value. That is a separate pre-existing defect in `BaseWidget.set name`. Co-Authored-By: Claude Opus 5 (1M context) --- .../renamableDuplicateWidgetKept.spec.ts | 141 ++++++++++++++++++ docs/adr/ECS-0008-entity-component-system.md | 28 +++- .../node/widgetsView.refusalCriterion.test.ts | 127 ++++++++++++++++ src/lib/litegraph/src/node/widgetsView.ts | 45 ++++-- src/types/widgetId.test.ts | 70 +++++++-- src/types/widgetId.ts | 124 +++++++++++---- 6 files changed, 477 insertions(+), 58 deletions(-) create mode 100644 browser_tests/tests/widgets/renamableDuplicateWidgetKept.spec.ts create mode 100644 src/lib/litegraph/src/node/widgetsView.refusalCriterion.test.ts diff --git a/browser_tests/tests/widgets/renamableDuplicateWidgetKept.spec.ts b/browser_tests/tests/widgets/renamableDuplicateWidgetKept.spec.ts new file mode 100644 index 00000000000..3c3087ba0e9 --- /dev/null +++ b/browser_tests/tests/widgets/renamableDuplicateWidgetKept.spec.ts @@ -0,0 +1,141 @@ +import { expect } from '@playwright/test' + +import type { ComfyPage } from '@e2e/fixtures/ComfyPage' +import { comfyPageFixture as test } from '@e2e/fixtures/ComfyPage' +import { TestIds } from '@e2e/fixtures/selectors' + +import { zComfyWorkflow } from '@/platform/workflow/validation/schemas/workflowSchema' + +/** + * The unique-name invariant removes a widget it cannot name uniquely + * (ADR-ECS-0008). This pins the boundary of "cannot": a widget whose `name` is + * perfectly writable must never be the price of enforcing it. + * + * `BaseWidget.set name` delegates to `widgetValueStore.renameWidget()` and + * returns without changing the name whenever the store declines — which it does + * when the node has no entries, the state a node is in after it has been + * removed from the graph. So a rename that *failed* does not prove the widget + * is unaddressable, and removing on that signal destroys an ordinary widget. + * + * Reproduced through the graph API the way an undo of a node deletion or a + * paste of a cut node reaches it: the node leaves the graph, the duplicate name + * appears while it is detached, and it rejoins. + * + * Asserted on what the app saves, because that is where the loss is permanent. + * Measured on the parent commit the node comes back one widget short and saves + * **one** `widgets_values` entry for a two-widget node; the arity of that array + * is what positional widget addressing reads, so a dropped slot shifts every + * later widget. With the invariant's criterion corrected it saves both. + * + * Not asserted, and deliberately: the two slots do not hold the two *values*. + * Re-registering an ambiguous pair routes the second widget's `name` setter + * through `renameWidget` on a stale `_state.nodeId`, which hands it the first + * widget's store entry, so both read the first widget's value. That is a + * separate pre-existing defect in `BaseWidget.set name`, unchanged either way + * here, and asserting the values would pin it as if it were correct. + */ + +const NODE_TYPE = 'DevToolsNodeWithOutputList' +const KEPT_NAME = 'alpha' +const RENAMED_NAME = 'beta' + +/** + * Patches the node type so every instance carries two distinct, ordinary, + * serializable widgets. Both names are writable, so neither is ever + * unaddressable — which is the whole point. + */ +async function installTwoOrdinaryWidgets(comfyPage: ComfyPage): Promise { + await comfyPage.page.evaluate( + ({ nodeTypeName, first, second }) => { + const nodeType = window.LiteGraph!.registered_node_types[nodeTypeName] + const onNodeCreated = nodeType.prototype.onNodeCreated + nodeType.prototype.onNodeCreated = function (...args) { + onNodeCreated?.apply(this, args) + this.serialize_widgets = true + this.addWidget('string', first, 'first default', () => {}) + this.addWidget('string', second, 'second default', () => {}) + } + }, + { nodeTypeName: NODE_TYPE, first: KEPT_NAME, second: RENAMED_NAME } + ) +} + +/** + * Takes the node out of the graph, collides the second widget's name with the + * first while it is detached, and puts it back. Detached is what makes the + * write land: on a node that is still in the graph the store declines the + * rename and the collision never forms. + */ +async function collideNameWhileDetached( + comfyPage: ComfyPage, + nodeId: string +): Promise { + await comfyPage.page.evaluate( + ({ id, duplicateName, renamedName }) => { + const graph = window.app!.graph + const node = graph.nodes.find((candidate) => String(candidate.id) === id) + if (!node) throw new Error(`node ${id} not found`) + + graph.remove(node) + const target = node.widgets?.find(({ name }) => name === renamedName) + if (!target) throw new Error(`widget ${renamedName} not found`) + target.name = duplicateName + graph.add(node) + }, + { id: nodeId, duplicateName: KEPT_NAME, renamedName: RENAMED_NAME } + ) +} + +test.describe( + 'renamable duplicate widget name', + { tag: ['@canvas', '@widget', '@vue-nodes'] }, + () => { + // Per attempt, not per module: a module-scope stamp is shared by every + // worker in the process and by a retry. + let workflowName = '' + + test.afterEach(async ({ comfyPage }) => { + if (workflowName) await comfyPage.workflow.deleteWorkflow(workflowName) + }) + + test('keeps the widget whose rename was declined rather than impossible', async ({ + comfyPage + }, testInfo) => { + workflowName = `renamable-duplicate-widget-${testInfo.parallelIndex}-${testInfo.retry}-${Date.now()}` + + await comfyPage.nodeOps.clearGraph() + await installTwoOrdinaryWidgets(comfyPage) + + const nodeId = await comfyPage.searchBoxV2.addNodeAndGetId( + 'Node With Output List' + ) + const node = comfyPage.vueNodes.getNodeLocator(nodeId) + await expect(node).toBeVisible() + + await test.step('both widgets are drawn to begin with', async () => { + await expect(node.getByTestId(TestIds.widgets.widget)).toHaveCount(2) + }) + + await collideNameWhileDetached(comfyPage, nodeId) + + await test.step('and the node still saves both widget slots', async () => { + const savedRequest = comfyPage.page.waitForRequest( + (request) => + request.method() === 'POST' && + decodeURIComponent(new URL(request.url()).pathname).endsWith( + `/workflows/${workflowName}.json` + ) + ) + await comfyPage.menu.topbar.saveWorkflowAs(workflowName) + const saved = zComfyWorkflow.parse( + JSON.parse((await savedRequest).postData() ?? '{}') + ) + const savedNode = saved.nodes.find(({ type }) => type === NODE_TYPE) + + // One entry here is a widget the user lost. Two is the invariant being + // enforced without charging them for it. + expect(savedNode?.widgets_values).toHaveLength(2) + }) + }) + } +) diff --git a/docs/adr/ECS-0008-entity-component-system.md b/docs/adr/ECS-0008-entity-component-system.md index 0634b3109b7..9928a539182 100644 --- a/docs/adr/ECS-0008-entity-component-system.md +++ b/docs/adr/ECS-0008-entity-component-system.md @@ -186,16 +186,36 @@ legitimate re-mint rather than an identity collision — which is why > identity twice, and nothing downstream can tell the two apart. > > The repeat is renamed to `name#1` before any id is derived. Where it cannot -> be — a `name` whose writes do not stick, or an accessor that throws +> be — a `name` that cannot be written at all, or an accessor that throws > (`src/types/widgetId.ts`) — the widget is **refused**: it is dropped from > `node.widgets` and reported. First occurrence wins; renamable collisions > elsewhere on the node are still renamed. > -> Two stable `errorType`s, because the causes need different alerts and +> **Refusal keys on whether the write was possible, not on whether it landed, +> and the difference is load-bearing.** `BaseWidget.set name` delegates to +> `widgetValueStore.renameWidget()` and returns without changing the name +> whenever the store declines — which it does when the node has no entries, +> precisely the state an ambiguous pair leaves a node in and the state a node +> is in after it has been removed from the graph. So a failed read-back is a +> recoverable store refusal at least as often as it is a hostile object, and +> removing on it destroys ordinary, renamable widgets on the very nodes this +> repairs: a node deleted and undone comes back a widget short, saving one +> `widgets_values` entry for a two-widget node. The read-back still decides +> whether the pair is **reported**; `nameIsWritable` decides whether the widget +> is **removed**, and it is deliberately the same predicate +> `ensureUniqueWidgetNames` uses to decide it may rename at all — `setNodeId` +> gates registration on that, so two copies of the rule disagreeing is a widget +> destroyed over a disagreement. +> +> Three stable `errorType`s, because the causes need different alerts and > collapsing them reports a collision that does not exist: > `widget_duplicate_name_refused` for a duplicate that could not be renamed -> apart, and `widget_unreadable_name_refused` for a widget whose `name` -> accessor throws — that one has no duplicate at all, only no derivable id. +> apart, `widget_unreadable_name_refused` for a widget whose `name` accessor +> throws — that one has no duplicate at all, only no derivable id — and +> `widget_duplicate_name_unresolved` for a pair the node **keeps**, where the +> rename was declined rather than impossible. The third is not a report of lost +> widgets: the widget is still on the node, and a later commit can still +> resolve it. > > **There are two enforcement points, and looking only at the first one is > misleading.** `attachNodeToStores` calls `refuseAmbiguousNodeWidgets` as a diff --git a/src/lib/litegraph/src/node/widgetsView.refusalCriterion.test.ts b/src/lib/litegraph/src/node/widgetsView.refusalCriterion.test.ts new file mode 100644 index 00000000000..b980bc9439f --- /dev/null +++ b/src/lib/litegraph/src/node/widgetsView.refusalCriterion.test.ts @@ -0,0 +1,127 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest' + +import { LGraph, LGraphNode, LiteGraph } from '@/lib/litegraph/src/litegraph' +import { reportError } from '@/platform/telemetry/reportError' +import { useWidgetValueStore } from '@/stores/widgetValueStore' + +vi.mock(import('@/platform/telemetry/reportError')) + +/** + * The unique-name invariant removes a widget it cannot name uniquely. What + * counts as "cannot" is the subject here, because the two candidate criteria + * disagree on a node the user can reach: + * + * - **the read-back** — write `name#1`, read `name` back, remove on mismatch; + * - **the descriptor** — remove only when `name` could not be written at all. + * + * `BaseWidget.set name` delegates to `widgetValueStore.renameWidget()` and + * returns without changing `_name` whenever the store declines, which it does + * when the node has no entries. So the read-back reports failure for an + * ordinary, fully renamable widget, and removing on it destroys that widget. + */ +function reportedTypes(): (string | undefined)[] { + return vi + .mocked(reportError) + .mock.calls.map((call) => call[1]?.errorType as string | undefined) +} + +describe('unique-name refusal criterion', () => { + beforeEach(() => { + LiteGraph.vueNodesMode = false + vi.mocked(reportError).mockClear() + }) + + it('keeps an ordinary renamable duplicate on a node that was removed and re-added', () => { + const graph = new LGraph() + const node = new LGraphNode('test') + graph.add(node) + const seed = node.addWidget('number', 'seed', 1, () => undefined, {}) + const steps = node.addWidget('number', 'steps', 2, () => undefined, {}) + + // Both registered, so each widget's `_state` is the store's object and + // carries `nodeId`. + expect( + useWidgetValueStore() + .getNodeWidgets(graph.id, node.id) + .map((widget) => widget.name) + ).toEqual(['seed', 'steps']) + + // Node removal runs `clearNodeOwnedStoreState`, deleting the store + // entries. Nothing resets `_state.nodeId` on the widgets, so the next + // rename attempt asks the store to move an entry that is no longer there. + graph.remove(node) + + // Off-graph, so `BaseWidget.set name` takes its `!graphId` path and the + // write lands. This is an ordinary duplicate-name state, reachable by an + // extension renaming a widget while the node is detached. + steps.name = 'seed' + expect(steps.name).toBe('seed') + + // Re-adding commits `node.widgets`, which runs the refusal walk. Undoing a + // node deletion and pasting a cut node both land here. + graph.add(node) + + // The invariant must not pay for itself with a widget. Both are writable, + // so neither is unaddressable and neither may be removed. + expect(node.widgets).toContain(seed) + expect(node.widgets).toContain(steps) + expect(node.widgets).toHaveLength(2) + + // It is still reported, so the pair is observable rather than tolerated in + // silence — under its own `errorType`, because nothing was lost. + expect(reportedTypes()).toEqual(['widget_duplicate_name_unresolved']) + expect(reportedTypes()).not.toContain('widget_duplicate_name_refused') + }) + + it('leaves a kept duplicate wired up, rather than tearing it down in place', () => { + const graph = new LGraph() + const node = new LGraphNode('test') + graph.add(node) + node.addWidget('number', 'seed', 1, () => undefined, {}) + const steps = node.addWidget('number', 'steps', 2, () => undefined, {}) + let removals = 0 + steps.onRemove = () => { + removals++ + } + const slot = { + name: 'steps', + type: 'number', + _widget: steps, + widget: { name: 'steps' }, + pos: [0, 0] + } as unknown as (typeof node.inputs)[number] + node.inputs.push(slot) + + graph.remove(node) + steps.name = 'seed' + graph.add(node) + + // The teardown that a removal owes the node is wrong for a widget the node + // still has: it would call `onRemove` on a live widget and drop the slot's + // back-references, leaving an input pointing at nothing. + expect(removals).toBe(0) + expect(slot._widget).toBe(steps) + expect(slot.widget).toBeDefined() + }) + + it('still removes a duplicate whose name genuinely cannot be written', () => { + const graph = new LGraph() + const node = new LGraphNode('test') + graph.add(node) + node.addWidget('number', 'seed', 1, () => undefined, {}) + const doomed = node.addWidget('number', 'steps', 2, () => undefined, {}) + Object.defineProperty(doomed, 'name', { + value: 'seed', + writable: false, + configurable: false, + enumerable: true + }) + + node.addWidget('number', 'cfg', 3, () => undefined, {}) + + // Nothing can address this one, so keeping it would silently share the + // other widget's value. Removal is correct here and is not weakened. + expect(node.widgets).not.toContain(doomed) + expect(reportedTypes()).toContain('widget_duplicate_name_refused') + }) +}) diff --git a/src/lib/litegraph/src/node/widgetsView.ts b/src/lib/litegraph/src/node/widgetsView.ts index 191bf849962..c1c61f12412 100644 --- a/src/lib/litegraph/src/node/widgetsView.ts +++ b/src/lib/litegraph/src/node/widgetsView.ts @@ -33,6 +33,19 @@ const DUPLICATE_WIDGET_NAME_ERROR_TYPE = 'widget_duplicate_name_refused' */ const UNREADABLE_WIDGET_NAME_ERROR_TYPE = 'widget_unreadable_name_refused' +/** + * Stable `errorType` for an ambiguous pair the node **keeps**: the rename did + * not take, but `name` is writable, so the failure is a store refusal that a + * later commit can still resolve rather than a widget that can never be + * addressed. Removing it would cost the user a widget to repair a transient + * state, so it is reported and left in place. + * + * Distinct from {@link DUPLICATE_WIDGET_NAME_ERROR_TYPE} precisely because the + * widget is still on the node: an alert on this one is not a report of lost + * widgets. Also a contract, not an implementation detail. + */ +const UNRESOLVED_WIDGET_NAME_ERROR_TYPE = 'widget_duplicate_name_unresolved' + interface WidgetsViewState { target: IBaseWidget[] view: IBaseWidget[] @@ -102,26 +115,32 @@ function refuseAmbiguousWidgets( const refused = dropUnrenamableDuplicateWidgets(widgets) if (!refused.length) return - for (const { widget, cause } of refused) { - // The two causes are different failures and are alerted on separately: an + for (const { widget, cause, removed } of refused) { + // The causes are different failures and are alerted on separately: an // unreadable name has no duplicate at all, so reporting one would send - // whoever reads the alert looking for a collision that does not exist. - // The cause comes from the walk rather than from another read of the - // accessor, which is hostile by definition and need not answer twice the - // same way. - const unreadable = cause === 'unreadable-name' + // whoever reads the alert looking for a collision that does not exist, and + // an unresolved pair is still on the node rather than lost. The cause comes + // from the walk rather than from another read of the accessor, which is + // hostile by definition and need not answer twice the same way. const widgetName = safeRead(() => widget.name) - releaseRefusedWidget(node, widget) + // Only a widget the walk took off the array needs releasing; an unresolved + // duplicate is still the node's widget and must keep its slot wiring. + if (removed) releaseRefusedWidget(node, widget) reportError( new Error( - unreadable + cause === 'unreadable-name' ? `Refused a widget on node ${node.id}: its name could not be read, so no widget identity can be derived for it` - : `Refused a widget named "${widgetName}": node ${node.id} already has a widget of that name and the duplicate cannot be renamed` + : cause === 'unresolved-duplicate' + ? `Kept a widget named "${widgetName}" that node ${node.id} already has under that name: the rename was declined rather than impossible, so the widget is left in place and the pair is unresolved for now` + : `Refused a widget named "${widgetName}": node ${node.id} already has a widget of that name and the duplicate cannot be renamed` ), { - errorType: unreadable - ? UNREADABLE_WIDGET_NAME_ERROR_TYPE - : DUPLICATE_WIDGET_NAME_ERROR_TYPE, + errorType: + cause === 'unreadable-name' + ? UNREADABLE_WIDGET_NAME_ERROR_TYPE + : cause === 'unresolved-duplicate' + ? UNRESOLVED_WIDGET_NAME_ERROR_TYPE + : DUPLICATE_WIDGET_NAME_ERROR_TYPE, surface: 'graph', level: 'warning', tags: { node_type: node.type }, diff --git a/src/types/widgetId.test.ts b/src/types/widgetId.test.ts index ded772e35ee..760e1ac96d7 100644 --- a/src/types/widgetId.test.ts +++ b/src/types/widgetId.test.ts @@ -47,9 +47,26 @@ function widgetNamed(name: unknown): { name: string } { return { name } as { name: string } } -/** The refused widgets alone; the cause is asserted separately where it matters. */ +/** + * The widgets the walk took off the array; the cause is asserted separately + * where it matters. Not every reported widget is removed — an + * `unresolved-duplicate` is reported and kept — and "was it removed" is what + * these cases are about. + */ function refusedWidgets(widgets: T[]): T[] { - return dropUnrenamableDuplicateWidgets(widgets).map(({ widget }) => widget) + return dropUnrenamableDuplicateWidgets(widgets) + .filter(({ removed }) => removed) + .map(({ widget }) => widget) +} + +/** Every widget the walk reported, removed or not, against its cause. */ +function reportedCauses( + widgets: T[] +): [T, string][] { + return dropUnrenamableDuplicateWidgets(widgets).map(({ widget, cause }) => [ + widget, + cause + ]) } describe('dropUnrenamableDuplicateWidgets', () => { @@ -123,19 +140,48 @@ describe('dropUnrenamableDuplicateWidgets', () => { ]) }) - it('refuses a widget whose setter silently ignores the rename', () => { + it('reports a widget whose setter silently ignores the rename, without removing it', () => { const stubborn = { get name() { return 'seed' }, set name(_value: string) {} } - const widgets = [{ name: 'seed' }, pinned('seed'), stubborn] + const unrenamable = pinned('seed') + const widgets = [{ name: 'seed' }, unrenamable, stubborn] // Its descriptor has a setter, so a descriptor check believes the rename - // will take; only reading the name back afterwards proves it did not. - expect(refusedWidgets(widgets)).toContain(stubborn) - expect(widgets.map(({ name }) => name)).toEqual(['seed']) + // will take; only reading the name back afterwards proves it did not. That + // read is what makes the pair *observable* — but it cannot decide removal, + // because `BaseWidget`'s own setter declines exactly this way whenever the + // store has no entry for the node, which is the ordinary state of a node + // carrying an ambiguous pair. The pinned widget beside it is removed; this + // one is kept and reported. + expect(reportedCauses(widgets)).toEqual([ + [unrenamable, 'duplicate-name'], + [stubborn, 'unresolved-duplicate'] + ]) + expect(widgets).toEqual([{ name: 'seed' }, stubborn]) + }) + + it('keeps a declining setter rather than removing it, and says the pair is unresolved', () => { + const declining = { + get name() { + return 'seed' + }, + set name(_value: string) {} + } + const widgets = [{ name: 'seed' }, declining] + + const reported = dropUnrenamableDuplicateWidgets(widgets) + + expect(reported).toEqual([ + { widget: declining, cause: 'unresolved-duplicate', removed: false } + ]) + // Still on the array: removing it would cost the user a widget to repair a + // state a later commit can resolve on its own. + expect(widgets).toHaveLength(2) + expect(widgets[1]).toBe(declining) }) it('refuses a widget whose name accessor throws, without letting it escape', () => { @@ -268,11 +314,17 @@ describe('dropUnrenamableDuplicateWidgets', () => { const renamable = { name: 'seed' } const widgets = [{ name: 'seed' }, stubborn, renamable] - expect(refusedWidgets(widgets)).toEqual([stubborn]) + // Nothing is removed: `stubborn` declined the write but could have taken + // it, so it is reported and kept. + expect(refusedWidgets(widgets)).toEqual([]) // `seed#1` was offered to `stubborn` and did not take, so it is still free // for the next widget — a name one setter refuses is not a name in use. expect(offered).toContain('seed#1') - expect(widgets.map((widget) => widget.name)).toEqual(['seed', 'seed#1']) + expect(widgets.map((widget) => widget.name)).toEqual([ + 'seed', + 'seed', + 'seed#1' + ]) }) it('refuses every occurrence of a widget it refused once', () => { diff --git a/src/types/widgetId.ts b/src/types/widgetId.ts index 2f218e8075a..eea114ba300 100644 --- a/src/types/widgetId.ts +++ b/src/types/widgetId.ts @@ -24,6 +24,24 @@ export function widgetId( ].join(SEPARATOR) as WidgetId } +/** + * Whether `name` can be written on {@link widget} at all — a structural + * property of the object, not of whether a particular write landed. + * + * This is the criterion {@link ensureUniqueWidgetNames} uses to decide whether + * it may rename at all, and it is deliberately the same one + * {@link dropUnrenamableDuplicateWidgets} uses to decide whether a rename that + * failed is fatal. The two must agree: `setNodeId` gates registration on + * `ensureUniqueWidgetNames`, so a walk that removed a widget this predicate + * calls renamable would be destroying widgets over a disagreement between two + * copies of one rule. + */ +function nameIsWritable(widget: { name: string }): boolean { + const descriptor = Object.getOwnPropertyDescriptor(widget, 'name') + if (!descriptor) return Object.isExtensible(widget) + return 'writable' in descriptor ? !!descriptor.writable : !!descriptor.set +} + export function ensureUniqueWidgetNames( widgets: readonly { name: string }[] ): boolean { @@ -56,16 +74,7 @@ export function ensureUniqueWidgetNames( renames.push({ widget, name }) } - if ( - renames.some(({ widget }) => { - const descriptor = Object.getOwnPropertyDescriptor(widget, 'name') - return descriptor - ? 'writable' in descriptor - ? !descriptor.writable - : !descriptor.set - : !Object.isExtensible(widget) - }) - ) { + if (renames.some(({ widget }) => !nameIsWritable(widget))) { console.warn('Cannot safely rename duplicate widgets') return false } @@ -87,13 +96,28 @@ export function ensureUniqueWidgetNames( */ const UNREADABLE_NAME = Symbol('unreadable widget name') -/** Why a widget could not be given a unique name on its node. */ -type WidgetRefusalCause = 'unreadable-name' | 'duplicate-name' +/** + * Why a widget could not be given a unique name on its node. + * + * `unresolved-duplicate` is the one cause that does **not** remove the widget: + * the rename did not land, but the write was structurally possible, so the + * failure is recoverable and losing the widget would be worse than carrying + * the ambiguity. See {@link nameIsWritable}. + */ +type WidgetRefusalCause = + | 'unreadable-name' + | 'duplicate-name' + | 'unresolved-duplicate' -/** A refused widget, with the cause recorded by the walk that refused it. */ +/** + * A widget the walk could not name uniquely, with the cause it was recorded + * under and whether the walk took it off the array. + */ export interface RefusedWidget { widget: T cause: WidgetRefusalCause + /** Whether the walk removed {@link widget} from the array it was given. */ + removed: boolean } /** @@ -205,6 +229,41 @@ function renameApart( return undefined } +/** + * Decides what becomes of a widget whose name another widget already holds: + * renamed apart and kept, kept but reported, or refused. + * + * Renames `used`/`reserved` in place when an attempt sticks, so the caller's + * bookkeeping stays a single source of truth for both sets. + * + * The middle outcome is the one worth reading. A rename that did not land is + * not proof of an unaddressable widget: `BaseWidget`'s own `name` setter + * delegates to `widgetValueStore.renameWidget()` and leaves the name unchanged + * whenever the store declines — which it does when the node has no entries, + * exactly the state an ambiguous pair leaves it in and the state a + * removed-and-re-added node is in before it re-registers. Refusing on the + * read-back alone therefore destroys ordinary, perfectly renamable widgets on + * the very nodes this walk repairs, so {@link nameIsWritable} decides removal + * and the unresolved pair is reported instead of paid for. + */ +function resolveCollision( + widget: T, + key: string, + used: Set, + reserved: Set +): { keep: boolean; cause?: WidgetRefusalCause } { + const unique = renameApart(widget, key, used, reserved) + if (unique !== undefined) { + used.add(unique) + reserved.add(unique) + return { keep: true } + } + if (nameIsWritable(widget)) { + return { keep: true, cause: 'unresolved-duplicate' } + } + return { keep: false, cause: 'duplicate-name' } +} + /** * Removes the widgets that cannot be given a unique name, mutating * {@link widgets} in place, and renames the duplicates that can — keeping the @@ -224,16 +283,19 @@ function renameApart( * widget the store cannot tell apart silently shares another widget's value. * * It does its own renaming rather than delegating the happy path to - * {@link ensureUniqueWidgetNames}, which decides renamability from the - * property descriptor alone and never reads the name back. A setter that - * accepts the write and ignores it satisfies that check, so delegating would - * report success over a node that still carries the ambiguous pair. + * {@link ensureUniqueWidgetNames}, which never reads the name back: a setter + * that accepts the write and ignores it satisfies that check, so delegating + * would report success over a node that still carries an ambiguous pair. The + * read-back is therefore what decides whether the pair is *reported* — + * but **not** whether the widget is removed. {@link nameIsWritable} decides + * that, because a failed write is a recoverable store refusal as often as it + * is a hostile object, and the two are indistinguishable from the read alone. * - * @returns the removed widgets with the cause of each refusal, in array order. - * Empty when the node was already unambiguous, which is the overwhelmingly - * common case. The cause is recorded here rather than re-derived by the - * caller: re-reading a hostile accessor to ask "was this one unreadable?" can - * answer differently the second time and mislabel the report. + * @returns every widget it could not name uniquely, with the cause and whether + * it was removed, in array order. Empty when the node is unambiguous, which is + * the overwhelmingly common case. The cause is recorded here rather than + * re-derived by the caller: re-reading a hostile accessor to ask "was this one + * unreadable?" can answer differently the second time and mislabel the report. */ export function dropUnrenamableDuplicateWidgets( widgets: T[] @@ -261,7 +323,7 @@ export function dropUnrenamableDuplicateWidgets( // node makes `ensureUniqueWidgetNames` fail on every later call — which // bails registration for every *other* widget on the node too. verdicts.set(widget, false) - refused.push({ widget, cause: 'unreadable-name' }) + refused.push({ widget, cause: 'unreadable-name', removed: true }) continue } @@ -274,18 +336,16 @@ export function dropUnrenamableDuplicateWidgets( continue } - const unique = renameApart(widget, key, used, reserved) - if (unique === undefined) { - verdicts.set(widget, false) - refused.push({ widget, cause: 'duplicate-name' }) - continue + const outcome = resolveCollision(widget, key, used, reserved) + verdicts.set(widget, outcome.keep) + if (outcome.keep) kept.push(widget) + if (outcome.cause) { + refused.push({ widget, cause: outcome.cause, removed: !outcome.keep }) } - used.add(unique) - reserved.add(unique) - verdicts.set(widget, true) - kept.push(widget) } + // `kept` holds every widget that was not removed, in order, so this is a + // no-op rebuild when the only findings were kept ones. if (refused.length) widgets.splice(0, widgets.length, ...kept) return refused } From 8320b45884e2766a4d6ecfc9885c647cb013c512 Mon Sep 17 00:00:00 2001 From: Christian Byrne Date: Sun, 4 Oct 2026 08:03:17 -0700 Subject: [PATCH 11/35] fix(widgets): stop asking a hostile accessor the same question twice MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Five findings from the review of the previous head. The first was unanimous across the panel and it is the same mistake the previous commit fixed one line away: the conversion guard decided whether to swallow by re-invoking the accessor that had just thrown. A getter that throws during conversion but answers the probe got its error rethrown after the push had already landed, wedging every later commit; the reverse direction swallowed a failure that had nothing to do with the name. The verdict is read once, before conversion, and carried in. `readName` proved less than the store requires. It encoded the coerced string while `widgetId` encodes the raw value, so a Symbol name passed here and threw inside `widgetId` during `setNodeId`, aborting the attach after node-state registration. And an empty name encodes to nothing, minting `graphId:nodeId:`, which the id pattern rejects — the widget then lands in exactly the unaddressable state this walk exists to catch, with no refusal and no telemetry. Both are refusals now. The report quoted the name by reading it again, after the walk had written to the widget up to four times, so a normalising setter made the message and `context.widgetName` carry a candidate no widget held. The walk returns the key it actually read. The graph-join site handed the walk `node.widgets`, the mutation view, so the walk's closing splice re-entered `syncWidgetOrder` — a full nested commit, run before the refused widget was released or reported, with anything throwing in there escaping the join. It hands over this module's own array, as the other call site does. A refused widget whose own teardown throws is reported under its own type instead of a bare console line that reaches no telemetry sink. The ADR gains the boundary it was missing: pinning a name inside `onAdded` is not an array mutation, so it is not caught until the next one. Co-Authored-By: Claude Opus 5 (1M context) --- docs/adr/ECS-0008-entity-component-system.md | 7 + src/lib/litegraph/src/node/widgetsView.ts | 49 +++++-- .../node/widgetsView.uniqueWidgetName.test.ts | 130 ++++++++++++++++-- src/types/widgetId.test.ts | 36 +++++ src/types/widgetId.ts | 22 ++- 5 files changed, 219 insertions(+), 25 deletions(-) diff --git a/docs/adr/ECS-0008-entity-component-system.md b/docs/adr/ECS-0008-entity-component-system.md index 0634b3109b7..194221528f8 100644 --- a/docs/adr/ECS-0008-entity-component-system.md +++ b/docs/adr/ECS-0008-entity-component-system.md @@ -227,6 +227,13 @@ legitimate re-mint rather than an identity collision — which is why > `push`, a splice, a whole-array assignment. `addCustomWidget` converts > before it pushes, so `addWidget` and `addDOMWidget` with a hostile accessor > still throw to their caller and never reach the refusal. +> - **The two points cover array mutations and the join, not every way a name +> changes.** Redefining a `name` is not an array mutation, so an extension +> that adds a widget under a unique name in `onAdded` and then pins it onto +> an existing one leaves the ambiguous pair standing until some later +> `node.widgets` mutation commits. That is deliberate — enforcing on every +> property write would mean watching every widget — but it means "caught at +> the join" is true of the join itself, not of what `onAdded` does after it. > - **`SubgraphNode` does not commit through this path, and neither > enforcement point runs on it.** It redefines `widgets` as a computed getter > over its promoted widgets and overrides `addCustomWidget`, so an ambiguous diff --git a/src/lib/litegraph/src/node/widgetsView.ts b/src/lib/litegraph/src/node/widgetsView.ts index 191bf849962..da461149b22 100644 --- a/src/lib/litegraph/src/node/widgetsView.ts +++ b/src/lib/litegraph/src/node/widgetsView.ts @@ -33,6 +33,12 @@ const DUPLICATE_WIDGET_NAME_ERROR_TYPE = 'widget_duplicate_name_refused' */ const UNREADABLE_WIDGET_NAME_ERROR_TYPE = 'widget_unreadable_name_refused' +/** + * Stable `errorType` for a refused widget whose own teardown threw, which + * leaves its release half-done. Also a contract, not an implementation detail. + */ +const REFUSED_WIDGET_TEARDOWN_ERROR_TYPE = 'widget_refusal_teardown_failed' + interface WidgetsViewState { target: IBaseWidget[] view: IBaseWidget[] @@ -80,7 +86,16 @@ function releaseRefusedWidget(node: LGraphNode, widget: IBaseWidget): void { try { widget.onRemove?.() } catch (error) { - console.error('Failed to release a refused widget', error) + // Its own type: teardown stopping half-done leaves a DOM widget's element + // mounted and extension-held resources undisposed, and a bare console log + // reaches no telemetry sink, so it reads as zero rather than as a problem. + reportError(error, { + errorType: REFUSED_WIDGET_TEARDOWN_ERROR_TYPE, + surface: 'graph', + level: 'warning', + tags: { node_type: node.type }, + context: { nodeId: String(node.id) } + }) } } @@ -102,21 +117,25 @@ function refuseAmbiguousWidgets( const refused = dropUnrenamableDuplicateWidgets(widgets) if (!refused.length) return - for (const { widget, cause } of refused) { + for (const { widget, cause, name } of refused) { // The two causes are different failures and are alerted on separately: an // unreadable name has no duplicate at all, so reporting one would send // whoever reads the alert looking for a collision that does not exist. - // The cause comes from the walk rather than from another read of the - // accessor, which is hostile by definition and need not answer twice the - // same way. + // + // Both the cause and the name come from the walk, never from another read + // of the accessor. It is hostile by definition, it need not answer twice + // the same way, and the walk may have written to it up to four times + // before giving up — so a re-read can name a candidate no widget holds. const unreadable = cause === 'unreadable-name' - const widgetName = safeRead(() => widget.name) releaseRefusedWidget(node, widget) reportError( new Error( unreadable - ? `Refused a widget on node ${node.id}: its name could not be read, so no widget identity can be derived for it` - : `Refused a widget named "${widgetName}": node ${node.id} already has a widget of that name and the duplicate cannot be renamed` + ? // Deliberately not "the accessor threw": a name that will not + // coerce or will not percent-encode reads perfectly and still + // yields no id. + `Refused a widget on node ${node.id}: no widget identity can be derived from its name` + : `Refused a widget named "${name}": node ${node.id} already has a widget of that name and the duplicate cannot be renamed` ), { errorType: unreadable @@ -127,7 +146,7 @@ function refuseAmbiguousWidgets( tags: { node_type: node.type }, context: { nodeId: String(node.id), - widgetName, + widgetName: name, widgetType: safeRead(() => widget.type) } } @@ -179,7 +198,11 @@ export function wasWidgetRefused( */ export function refuseAmbiguousNodeWidgets(node: LGraphNode): void { if (!commitsThroughWidgetsView(node)) return - const widgets = node.widgets + // This module's own array, never `node.widgets`. That getter hands back the + // mutation view, and the walk's closing splice on the view re-enters + // `syncWidgetOrder` — a whole nested commit, run while the refused widget's + // slot back-references are still live and before anything is reported. + const widgets = states.get(node)?.target if (!widgets?.length) return refuseAmbiguousWidgets(node, widgets) } @@ -194,6 +217,10 @@ function syncWidgetOrder(node: LGraphNode, widgets: IBaseWidget[]): void { // exact state `UNREADABLE_NAME` exists to contain, so leave the object // unconverted and let the refusal below take it. const concreteWidgets = widgets.map((widget) => { + // Decided before the conversion, not inside the catch. Probing the + // accessor after it has already thrown asks a hostile getter the same + // question twice and acts on whichever answer comes back second. + const unreadable = isWidgetNameUnreadable(widget) try { return toConcreteWidget(widget, node) } catch (error) { @@ -204,7 +231,7 @@ function syncWidgetOrder(node: LGraphNode, widgets: IBaseWidget[]): void { // throwing, as it did before. This also only covers the commit path: // `addCustomWidget` converts before it pushes, so `addWidget` and // `addDOMWidget` still throw to their caller. - if (!isWidgetNameUnreadable(widget)) throw error + if (!unreadable) throw error return widget } }) diff --git a/src/lib/litegraph/src/node/widgetsView.uniqueWidgetName.test.ts b/src/lib/litegraph/src/node/widgetsView.uniqueWidgetName.test.ts index e31a23484df..2359d6e5d47 100644 --- a/src/lib/litegraph/src/node/widgetsView.uniqueWidgetName.test.ts +++ b/src/lib/litegraph/src/node/widgetsView.uniqueWidgetName.test.ts @@ -251,9 +251,17 @@ describe('unique widget name invariant', () => { configurable: false }) - // The report runs after the array has already been spliced, so re-reading - // the accessor there would leave the node's widgets and the store's order - // out of sync — with the error surfacing far from its cause. + // Everything the report reads off a refused widget is hostile by then, so + // `type` is poisoned too: the report runs after the array has been + // spliced, and a throw there would leave the node's widgets and the + // store's order out of sync, surfacing far from its cause. + Object.defineProperty(hostile, 'type', { + get(): string { + throw new Error('type is not readable either') + }, + configurable: false + }) + expect(() => node.addWidget('number', 'cfg', 3, () => undefined, {}) ).not.toThrow() @@ -311,14 +319,14 @@ describe('unique widget name invariant', () => { node.addWidget('number', 'seed', 1, () => undefined, {}) const flaky = node.addWidget('number', 'steps', 2, () => undefined, {}) - // Throws for the reserved-names pass and for the walk, then succeeds. The - // walk refuses it for an unreadable name; anything that asks the accessor - // again afterwards gets a readable name and would call it a duplicate. - let reads = 0 + // Unreadable for as long as the widget is on the node, readable once it + // has been dropped. The walk therefore decides "unreadable"; anything that + // asks the accessor again afterwards — the refusal reports after the + // splice — gets a name back and would call it a duplicate instead. Object.defineProperty(flaky, 'name', { get(): string { - reads++ - if (reads <= 2) throw new Error('name is not readable') + if (node.widgets?.includes(flaky)) + throw new Error('name is not readable') return 'seed' }, configurable: true @@ -391,6 +399,110 @@ describe('unique widget name invariant', () => { expect(reportError).not.toHaveBeenCalled() }) + it('reports a refused widget whose own teardown throws', () => { + const node = createNode() + node.addWidget('number', 'seed', 1, () => undefined, {}) + const second = node.addWidget('number', 'steps', 2, () => undefined, {}) + second.onRemove = () => { + throw new Error('teardown blew up') + } + pinName(second, 'seed') + + // Teardown stopping half-done leaves a DOM widget's element mounted and + // extension resources undisposed, so it needs a sink rather than a log. + expect(() => + node.addWidget('number', 'cfg', 3, () => undefined, {}) + ).not.toThrow() + + expect( + vi.mocked(reportError).mock.calls.map(([, options]) => options.errorType) + ).toEqual([ + 'widget_refusal_teardown_failed', + 'widget_duplicate_name_refused' + ]) + }) + + it('leaves a node alone once it stops exposing the widget list this module owns', () => { + // The node committed widgets through the view, then something replaced + // `widgets` with its own getter — which is what `SubgraphNode` does, and + // what an extension can do. This module still holds the array it built, + // and acting on it would refuse widgets off a list the node no longer + // reads, reporting a refusal nothing can observe. + const graph = new LGraph() + const node = new LGraphNode('test') + node.addWidget('custom', 'duplicate', 'first', () => undefined, {}) + const second = node.addWidget('custom', 'second', 'second', () => {}, {}) + pinName(second, 'duplicate') + + const ownList = [...(node.widgets ?? [])] + Object.defineProperty(node, 'widgets', { + get: () => ownList, + set: () => {}, + configurable: true + }) + + graph.add(node) + + expect(reportError).not.toHaveBeenCalled() + expect(ownList).toHaveLength(2) + }) + + it('does not re-enter the commit path when a node joins a graph', () => { + // Handing the walk `node.widgets` gives it the mutation view, so its + // closing splice runs a whole nested commit from inside the walk — before + // the refused widget is released or reported, and with anything that + // throws in there escaping the join with the splice already applied. + const graph = new LGraph() + const node = new LGraphNode('test') + node.addWidget('custom', 'duplicate', 'first', () => undefined, {}) + const second = node.addWidget('custom', 'second', 'second', () => {}, {}) + pinName(second, 'duplicate') + + const replaceNodeWidgetOrder = vi.spyOn( + useWidgetValueStore(), + 'replaceNodeWidgetOrder' + ) + + graph.add(node) + + expect(names(node)).toEqual(['duplicate']) + expect(replaceNodeWidgetOrder).not.toHaveBeenCalled() + }) + + it('reports the name the walk read, not what the rename attempts left behind', () => { + const node = createNode() + node.addWidget('number', 'seed', 1, () => undefined, {}) + const normalising = node.addWidget( + 'number', + 'steps', + 2, + () => undefined, + {} + ) + // Stores a transformed value, so it never answers to the candidate it was + // offered and is refused — and afterwards it holds a name no widget on the + // node owns, which is what the report must not quote. + let stored = 'seed' + Object.defineProperty(normalising, 'name', { + get: () => stored, + set: (value: string) => { + stored = `${value}-normalised` + }, + configurable: true + }) + + node.addWidget('number', 'cfg', 3, () => undefined, {}) + + expect(normalising.name).not.toBe('seed') + expect(reportError).toHaveBeenCalledExactlyOnceWith( + expect.any(Error), + expect.objectContaining({ + errorType: 'widget_duplicate_name_refused', + context: expect.objectContaining({ widgetName: 'seed' }) + }) + ) + }) + it('does not report a refusal it cannot carry out on a subgraph node', () => { // A `SubgraphNode` rebuilds `widgets` on every read, so nothing this // module splices ever leaves the node. Enforcing there anyway reports the diff --git a/src/types/widgetId.test.ts b/src/types/widgetId.test.ts index ded772e35ee..0c692e0799e 100644 --- a/src/types/widgetId.test.ts +++ b/src/types/widgetId.test.ts @@ -184,6 +184,42 @@ describe('dropUnrenamableDuplicateWidgets', () => { expect(widgets).toEqual([fine]) }) + it('refuses a name whose id the store would reject', () => { + // `String(Symbol())` succeeds, so coercion alone says this name is fine — + // but `widgetId` encodes the raw value and throws on it. And an empty name + // encodes to nothing, minting `graphId:nodeId:`, which the store refuses + // to key on: the widget lands in exactly the unaddressable state this walk + // exists to catch, silently. + const symbolNamed = widgetNamed(Symbol('seed')) + const empty = widgetNamed('') + const fine = widgetNamed('seed') + const widgets = [fine, symbolNamed, empty] + + expect(refusedWidgets(widgets)).toEqual([symbolNamed, empty]) + expect(widgets).toEqual([fine]) + }) + + it('reports the name the walk read, not one the rename attempts left behind', () => { + // The walk writes to a colliding widget before giving up, so the value the + // accessor holds afterwards can be a candidate no widget on the node owns. + const first = widgetNamed('seed') + let stored = 'seed' + const normalising = { + get name(): string { + return stored + }, + set name(value: string) { + stored = `${value}-normalised` + } + } + + const refused = dropUnrenamableDuplicateWidgets([first, normalising]) + + expect(refused).toHaveLength(1) + expect(refused[0].name).toBe('seed') + expect(refused[0].widget.name).not.toBe('seed') + }) + it('records why each widget was refused, rather than leaving it to be guessed', () => { // A hostile accessor need not answer the same way twice, so the cause has // to come from the walk that made the decision. diff --git a/src/types/widgetId.ts b/src/types/widgetId.ts index 2f218e8075a..6cf0f86ae96 100644 --- a/src/types/widgetId.ts +++ b/src/types/widgetId.ts @@ -90,10 +90,17 @@ const UNREADABLE_NAME = Symbol('unreadable widget name') /** Why a widget could not be given a unique name on its node. */ type WidgetRefusalCause = 'unreadable-name' | 'duplicate-name' -/** A refused widget, with the cause recorded by the walk that refused it. */ +/** + * A refused widget, with the cause and the name key recorded by the walk that + * refused it. Both come from here rather than from another read of the + * accessor: a hostile one need not answer twice the same way, and by the time + * a caller reports the refusal the walk may also have written to it. + */ export interface RefusedWidget { widget: T cause: WidgetRefusalCause + /** The key the walk read, or `undefined` when no key could be derived. */ + name: string | undefined } /** @@ -118,8 +125,13 @@ function readName(widget: { name: string }): string | typeof UNREADABLE_NAME { // assigned, which is the entire reason the coercion is here. const raw: unknown = widget.name const key = String(raw) - // Mirrors `widgetId`: the key is only usable if the id can be built from it. - encodeURIComponent(key) + // Mirrors `widgetId`, which encodes the **raw** value rather than the + // coerced one — a Symbol survives `String()` and then throws there. + const encoded = encodeURIComponent(raw as string) + // `widgetId` is `graphId:nodeId:name` and its pattern needs a non-empty + // last segment, so an empty name mints an id the store refuses to key on. + // That is the unaddressable state this walk exists to catch. + if (!encoded) return UNREADABLE_NAME return key } catch { return UNREADABLE_NAME @@ -261,7 +273,7 @@ export function dropUnrenamableDuplicateWidgets( // node makes `ensureUniqueWidgetNames` fail on every later call — which // bails registration for every *other* widget on the node too. verdicts.set(widget, false) - refused.push({ widget, cause: 'unreadable-name' }) + refused.push({ widget, cause: 'unreadable-name', name: undefined }) continue } @@ -277,7 +289,7 @@ export function dropUnrenamableDuplicateWidgets( const unique = renameApart(widget, key, used, reserved) if (unique === undefined) { verdicts.set(widget, false) - refused.push({ widget, cause: 'duplicate-name' }) + refused.push({ widget, cause: 'duplicate-name', name: key }) continue } used.add(unique) From 6e01cd5189a308208ec5b46e9aa3a11ebb1d4f89 Mon Sep 17 00:00:00 2001 From: Christian Byrne Date: Sun, 4 Oct 2026 08:33:50 -0700 Subject: [PATCH 12/35] fix(widgets): clear the two type-aware lint errors the gate rejects MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `lint-pr / lint` runs `oxlint . --type-aware`, and the type-aware rules are the ones a plain `oxlint ` never reaches — so both of these were green locally and red on CI from the moment the branch was pushed. They are the sole root cause of all five red checks on this branch: `preflight` fails on lint, and `test`, `e2e-status` and `lint-and-format` each gate on `preflight` (`PREFLIGHT: failure, UNIT: skipped`), so nothing else actually ran. - `no-unnecessary-condition`: `call[1]` is a required parameter of `reportError`, so the optional chain on it can never short-circuit. - `no-unnecessary-type-parameters`: `resolveCollision`'s `T` appears once, on `widget`, and the return type does not mention it — it never related two positions, so the structural type says the same thing. Behaviour is unchanged: the three focused suites stay at 57 passing, and `oxlint --type-aware` over the five touched files now exits 0. Co-Authored-By: Claude Opus 5 (1M context) --- .../litegraph/src/node/widgetsView.refusalCriterion.test.ts | 2 +- src/types/widgetId.ts | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/lib/litegraph/src/node/widgetsView.refusalCriterion.test.ts b/src/lib/litegraph/src/node/widgetsView.refusalCriterion.test.ts index b980bc9439f..09d9f2a1eb3 100644 --- a/src/lib/litegraph/src/node/widgetsView.refusalCriterion.test.ts +++ b/src/lib/litegraph/src/node/widgetsView.refusalCriterion.test.ts @@ -22,7 +22,7 @@ vi.mock(import('@/platform/telemetry/reportError')) function reportedTypes(): (string | undefined)[] { return vi .mocked(reportError) - .mock.calls.map((call) => call[1]?.errorType as string | undefined) + .mock.calls.map((call) => call[1].errorType as string | undefined) } describe('unique-name refusal criterion', () => { diff --git a/src/types/widgetId.ts b/src/types/widgetId.ts index e428a663191..90ef4d4c337 100644 --- a/src/types/widgetId.ts +++ b/src/types/widgetId.ts @@ -258,8 +258,8 @@ function renameApart( * the very nodes this walk repairs, so {@link nameIsWritable} decides removal * and the unresolved pair is reported instead of paid for. */ -function resolveCollision( - widget: T, +function resolveCollision( + widget: { name: string }, key: string, used: Set, reserved: Set From fb2a6e09c9d3e98f3f0a610916d05842a5787f96 Mon Sep 17 00:00:00 2001 From: Christian Byrne Date: Sun, 4 Oct 2026 08:46:34 -0700 Subject: [PATCH 13/35] fix(widgets): stop refusing an empty name, and make the teardown match MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Refusing a widget whose name encodes to nothing was wrong, and CI said so: `emptyNameWidget.spec.ts` is red on the previous head. That spec exists for this exact shape — `addWidget('text', '', value, cb)` — and its precondition asserts the widget stays on the node. An empty name mints `graphId:nodeId:`, which the store declines to key on. Declining an id costs the widget nothing: it still renders, still fires its callback, still serializes. Refusing it deletes a working widget and shifts every positional value after it, which is the data loss this change exists to argue against. The Symbol case stays refused, because there the id cannot be built at all. The teardown matched only `input._widget === widget`, and production assigns `_widget` only for promoted subgraph inputs — the one class the refusal is gated off. On every node where the refusal actually runs, widget inputs bind by name, so the loop matched nothing and the existing case passed only because it set `_widget` by hand. It matches both bindings now, with a case built on the real one. A nullish entry in `node.widgets` reads as an unreadable name and is refused like anything else, and the teardown then matched every input whose `_widget` was still unset — nearly all of them — turning widget sockets into plain ones. Guarded, as is the slot loop itself, which sat outside the try that already protected `onRemove`. `widgets.includes` in the per-commit loop made every commit quadratic and building a node cubic on the workflow-load path. The refused set comes back from the walk instead. The ADR records the two boundaries this leaves: the conversion verdict is one read, so an inconsistent accessor can still land either way, and an un-keyable name is declined rather than refused. Co-Authored-By: Claude Opus 5 (1M context) --- .../fallback-widget-name-restoration.json | 40 +++++++ .../fallbackWidgetNameRestoration.spec.ts | 46 ++++++++ docs/adr/ECS-0008-entity-component-system.md | 13 ++- .../LGraphNode.fallbackWidgetNames.test.ts | 54 ++++++++++ src/lib/litegraph/src/node/widgetsView.ts | 101 ++++++++++++++---- .../node/widgetsView.uniqueWidgetName.test.ts | 40 +++++++ src/types/widgetId.test.ts | 15 +-- src/types/widgetId.ts | 14 ++- 8 files changed, 288 insertions(+), 35 deletions(-) create mode 100644 browser_tests/assets/widgets/fallback-widget-name-restoration.json create mode 100644 browser_tests/tests/widgets/fallbackWidgetNameRestoration.spec.ts create mode 100644 src/lib/litegraph/src/LGraphNode.fallbackWidgetNames.test.ts diff --git a/browser_tests/assets/widgets/fallback-widget-name-restoration.json b/browser_tests/assets/widgets/fallback-widget-name-restoration.json new file mode 100644 index 00000000000..3c7bde7e92f --- /dev/null +++ b/browser_tests/assets/widgets/fallback-widget-name-restoration.json @@ -0,0 +1,40 @@ +{ + "last_node_id": 1, + "last_link_id": 0, + "nodes": [ + { + "id": 1, + "type": "KSampler", + "pos": [100, 100], + "size": [315, 262], + "flags": {}, + "order": 0, + "mode": 0, + "inputs": [ + { "name": "model", "type": "MODEL", "link": null }, + { "name": "positive", "type": "CONDITIONING", "link": null }, + { "name": "negative", "type": "CONDITIONING", "link": null }, + { "name": "latent_image", "type": "LATENT", "link": null } + ], + "outputs": [ + { "name": "LATENT", "type": "LATENT", "links": [], "slot_index": 0 } + ], + "properties": { "Node name for S&R": "KSampler" }, + "widgets_values": [111, "randomize", 12, 8, "euler", "normal", 1], + "widgets_values_named": { + "seed": 987654321, + "control_after_generate": "fixed", + "steps": 37, + "cfg": 6, + "sampler_name": "heun", + "scheduler": "karras", + "denoise": 0.75 + } + } + ], + "links": [], + "groups": [], + "config": {}, + "extra": { "ds": { "scale": 1, "offset": [0, 0] } }, + "version": 0.4 +} diff --git a/browser_tests/tests/widgets/fallbackWidgetNameRestoration.spec.ts b/browser_tests/tests/widgets/fallbackWidgetNameRestoration.spec.ts new file mode 100644 index 00000000000..07f1bd5f893 --- /dev/null +++ b/browser_tests/tests/widgets/fallbackWidgetNameRestoration.spec.ts @@ -0,0 +1,46 @@ +import { + comfyExpect as expect, + comfyPageFixture as test +} from '@e2e/fixtures/ComfyPage' +import { routeObjectInfoFromSetupApi } from '@e2e/fixtures/utils/objectInfo' + +test.describe( + 'backend fallback widget-name restoration', + { tag: ['@canvas', '@widget', '@vue-nodes'] }, + () => { + test.use({ + initialSettings: { + 'Comfy.VueNodes.Enabled': true, + 'Comfy.Workflow.NamedValuesRestore': false + } + }) + + test('an empty fallback name list restores visible values by name', async ({ + comfyPage + }) => { + const unrouteObjectInfo = await routeObjectInfoFromSetupApi( + comfyPage.page, + (objectInfo) => { + objectInfo.KSampler.fallbackWidgetsValuesNames = [] + } + ) + + try { + await comfyPage.workflow.reloadAndWaitForApp() + await comfyPage.workflow.loadWorkflow( + 'widgets/fallback-widget-name-restoration' + ) + + const node = comfyPage.vueNodes.getNodeLocator('1') + await expect(node.getByText('seed', { exact: true })).toBeVisible() + await expect(node.getByRole('spinbutton').nth(0)).toHaveValue( + '987654321' + ) + await expect(node.getByText('steps', { exact: true })).toBeVisible() + await expect(node.getByRole('spinbutton').nth(1)).toHaveValue('37') + } finally { + await unrouteObjectInfo() + } + }) + } +) diff --git a/docs/adr/ECS-0008-entity-component-system.md b/docs/adr/ECS-0008-entity-component-system.md index 194221528f8..db511152ade 100644 --- a/docs/adr/ECS-0008-entity-component-system.md +++ b/docs/adr/ECS-0008-entity-component-system.md @@ -226,7 +226,18 @@ legitimate re-mint rather than an identity collision — which is why > with nothing reported. The guard also only covers the commit path — a raw > `push`, a splice, a whole-array assignment. `addCustomWidget` converts > before it pushes, so `addWidget` and `addDOMWidget` with a hostile accessor -> still throw to their caller and never reach the refusal. +> still throw to their caller and never reach the refusal. And the verdict +> that decides whether to swallow is one read taken before the conversion, +> so a getter that answers _inconsistently_ — throwing on one read and not +> the next — can still land either way. Closing that needs the conversion to +> happen inside the walk, which is a larger change than this one; the trade +> is recorded here rather than left implicit. +> - **An un-keyable name is declined, not refused.** An empty name mints +> `graphId:nodeId:`, which the store will not key on. That widget still +> renders, still fires its callback and still serializes, so deleting it +> would lose a working widget and shift every positional value after it. +> Refusal is for a name that is _ambiguous_ with another widget's, not for +> one the store happens not to track. > - **The two points cover array mutations and the join, not every way a name > changes.** Redefining a `name` is not an array mutation, so an extension > that adds a widget under a unique name in `onAdded` and then pins it onto diff --git a/src/lib/litegraph/src/LGraphNode.fallbackWidgetNames.test.ts b/src/lib/litegraph/src/LGraphNode.fallbackWidgetNames.test.ts new file mode 100644 index 00000000000..458f6625e16 --- /dev/null +++ b/src/lib/litegraph/src/LGraphNode.fallbackWidgetNames.test.ts @@ -0,0 +1,54 @@ +import { afterEach, describe, expect, it } from 'vitest' + +import { LiteGraph } from './litegraph' +import { createWidgetRestorationState } from './LGraphNode' + +const originalNamedValuesRestore = LiteGraph.namedValuesRestore + +afterEach(() => { + LiteGraph.namedValuesRestore = originalNamedValuesRestore +}) + +describe('fallback widget names', () => { + it.for([ + { + name: 'a populated fallback list', + fallbackNames: ['seed'], + expectedNamed: { seed: 456 } + }, + { + name: 'an empty fallback list', + fallbackNames: [], + expectedNamed: { seed: 456 } + } + ])( + 'enables named restoration from $name while the setting is disabled', + ({ fallbackNames, expectedNamed }) => { + LiteGraph.namedValuesRestore = false + + const restoration = createWidgetRestorationState( + { + widgets_values: [123], + widgets_values_named: { seed: 456 } + }, + fallbackNames + ) + + expect(restoration).toMatchObject({ + named: expectedNamed, + restoreNamed: true + }) + } + ) + + it('keeps named restoration disabled when fallback names are absent', () => { + LiteGraph.namedValuesRestore = false + + const restoration = createWidgetRestorationState({ + widgets_values: [123], + widgets_values_named: { seed: 456 } + }) + + expect(restoration.restoreNamed).toBe(false) + }) +}) diff --git a/src/lib/litegraph/src/node/widgetsView.ts b/src/lib/litegraph/src/node/widgetsView.ts index da461149b22..c790a257f3e 100644 --- a/src/lib/litegraph/src/node/widgetsView.ts +++ b/src/lib/litegraph/src/node/widgetsView.ts @@ -46,6 +46,9 @@ interface WidgetsViewState { commit: (widgets: IBaseWidget[]) => void } +/** Shared empty result, so the common no-refusal path allocates nothing. */ +const EMPTY_REFUSAL: ReadonlySet = new Set() + const states = new WeakMap() const widgetsViewGetters = new WeakSet<() => IBaseWidget[] | undefined>() @@ -64,38 +67,86 @@ function safeRead(read: () => unknown): string | undefined { } } +/** Reports a teardown step that failed, so a half-done release is visible. */ +function reportTeardownFailure(node: LGraphNode, error: unknown): void { + reportError(error, { + errorType: REFUSED_WIDGET_TEARDOWN_ERROR_TYPE, + surface: 'graph', + level: 'warning', + tags: { node_type: node.type }, + context: { nodeId: String(node.id) } + }) +} + +/** + * Whether {@link input} is bound to the widget being released. + * + * Two bindings, because production uses both: `_widget` holds a direct + * reference (promoted subgraph inputs), while an ordinary node binds its widget + * inputs by name and resolves them on read. Matching only the reference finds + * nothing on the nodes this refusal actually runs for, and the slot then + * re-binds to whichever widget kept the name. + */ +function inputBindsWidget( + input: LGraphNode['inputs'][number], + widget: IBaseWidget, + name: string | undefined +): boolean { + if (input._widget === widget) return true + return name !== undefined && input.widget?.name === name +} + +/** Drops the slot back-references to a widget the node has just refused. */ +function clearRefusedSlotBindings( + node: LGraphNode, + widget: IBaseWidget, + name: string | undefined +): void { + for (const input of node.inputs) { + if (!inputBindsWidget(input, widget, name)) continue + input._widget = undefined + input.widget = undefined + input.pos = undefined + } +} + /** * Releases a widget the node has just refused. It is already off the array, so * `LGraphNode.removeWidget` can no longer find it and the teardown that method * owns has to happen here: slot back-references would otherwise keep pointing * at a widget the node no longer has. * + * Both steps are guarded and reported rather than thrown. This runs after the + * array has been spliced, so a throw escaping here would leave the node and the + * store's order out of sync — and during `LGraph.add`, a half-attached node. + * * The widget's store entry is deliberately *not* deleted. A refused widget's * name is by definition the one another widget kept, so `widget.widgetId` now * resolves to that widget's entry — deleting it would destroy the value of the * widget this invariant exists to protect. */ -function releaseRefusedWidget(node: LGraphNode, widget: IBaseWidget): void { - for (const input of node.inputs) { - if (input._widget === widget) { - input._widget = undefined - input.widget = undefined - input.pos = undefined - } +function releaseRefusedWidget( + node: LGraphNode, + // Typed to admit the nullish case the type system says cannot happen: a hole + // or an explicit `undefined` in `node.widgets` reaches the walk as an + // unreadable name and is refused like anything else. Matching the teardown on + // it would clear every input whose `_widget` is still unset, which is nearly + // all of them. + widget: IBaseWidget | undefined, + name: string | undefined +): void { + if (!widget) return + + try { + clearRefusedSlotBindings(node, widget, name) + } catch (error) { + reportTeardownFailure(node, error) } + try { widget.onRemove?.() } catch (error) { - // Its own type: teardown stopping half-done leaves a DOM widget's element - // mounted and extension-held resources undisposed, and a bare console log - // reaches no telemetry sink, so it reads as zero rather than as a problem. - reportError(error, { - errorType: REFUSED_WIDGET_TEARDOWN_ERROR_TYPE, - surface: 'graph', - level: 'warning', - tags: { node_type: node.type }, - context: { nodeId: String(node.id) } - }) + reportTeardownFailure(node, error) } } @@ -113,9 +164,9 @@ function releaseRefusedWidget(node: LGraphNode, widget: IBaseWidget): void { function refuseAmbiguousWidgets( node: LGraphNode, widgets: IBaseWidget[] -): void { +): ReadonlySet { const refused = dropUnrenamableDuplicateWidgets(widgets) - if (!refused.length) return + if (!refused.length) return EMPTY_REFUSAL for (const { widget, cause, name } of refused) { // The two causes are different failures and are alerted on separately: an @@ -127,7 +178,7 @@ function refuseAmbiguousWidgets( // the same way, and the walk may have written to it up to four times // before giving up — so a re-read can name a candidate no widget holds. const unreadable = cause === 'unreadable-name' - releaseRefusedWidget(node, widget) + releaseRefusedWidget(node, widget, name) reportError( new Error( unreadable @@ -152,6 +203,8 @@ function refuseAmbiguousWidgets( } ) } + + return new Set(refused.map(({ widget }) => widget)) } /** @@ -249,12 +302,16 @@ function syncWidgetOrder(node: LGraphNode, widgets: IBaseWidget[]): void { // class's writable `name` accessor over a plain object's pinned one, so a // widget judged unrenamable while still raw would be destroyed even though // it renames cleanly a line later. - refuseAmbiguousWidgets(node, widgets) + const refused = refuseAmbiguousWidgets(node, widgets) for (const widget of concreteWidgets) { + // Membership by set, not by `widgets.includes`: this loop runs on every + // commit and `node.widgets` commits once per `addWidget`, so a linear scan + // here is quadratic per commit and cubic over building a node. + // // A widget that would not convert is still raw and so not bindable; it has // also just been refused, so it is no longer on the node either. - if (widgets.includes(widget) && isNodeBindable(widget)) { + if (!refused.has(widget) && isNodeBindable(widget)) { widget.setNodeId(node.id) } } diff --git a/src/lib/litegraph/src/node/widgetsView.uniqueWidgetName.test.ts b/src/lib/litegraph/src/node/widgetsView.uniqueWidgetName.test.ts index 2359d6e5d47..ed1e5116b59 100644 --- a/src/lib/litegraph/src/node/widgetsView.uniqueWidgetName.test.ts +++ b/src/lib/litegraph/src/node/widgetsView.uniqueWidgetName.test.ts @@ -367,6 +367,46 @@ describe('unique widget name invariant', () => { expect(reportError).not.toHaveBeenCalled() }) + it('clears a slot bound to the refused widget by name, which is how real nodes bind', () => { + // The existing case sets `input._widget` by hand, and production assigns + // that only for promoted subgraph inputs — the one class this refusal is + // gated off. Ordinary nodes bind widget inputs by name, so a refusal that + // only matches the direct reference clears nothing and the slot silently + // re-binds to the widget that kept the name. + const node = createNode() + node.addWidget('number', 'seed', 1, () => undefined, {}) + const second = node.addWidget('number', 'steps', 2, () => undefined, {}) + node.addInput('steps', 'INT') + const input = node.inputs.at(-1)! + input.widget = { name: 'steps' } + pinName(second, 'steps') + + // A second widget pinned onto `steps` is refused, and the slot that named + // it must not be left pointing at a name it no longer owns. + const third = node.addWidget('number', 'spare', 3, () => undefined, {}) + pinName(third, 'steps') + node.addWidget('number', 'cfg', 4, () => undefined, {}) + + expect(node.widgets!.indexOf(third)).toBe(-1) + expect(input.widget).toBeUndefined() + }) + + it('does not tear down every input when a hole reaches the refusal', () => { + // A nullish entry reads as an unreadable name and is refused like anything + // else. Matching the teardown on it would clear every input whose + // `_widget` is still unset, which is nearly all of them. + const node = createNode() + node.addWidget('number', 'seed', 1, () => undefined, {}) + node.addInput('seed', 'INT') + const input = node.inputs.at(-1)! + input.widget = { name: 'seed' } + + expect(() => node.widgets!.push(undefined as never)).not.toThrow() + + expect(input.widget).toEqual({ name: 'seed' }) + expect(names(node)).toEqual(['seed']) + }) + it('clears slot back-references to a widget it refused', () => { const node = createNode() node.addWidget('number', 'seed', 1, () => undefined, {}) diff --git a/src/types/widgetId.test.ts b/src/types/widgetId.test.ts index 0c692e0799e..8ada8b58a6b 100644 --- a/src/types/widgetId.test.ts +++ b/src/types/widgetId.test.ts @@ -184,19 +184,20 @@ describe('dropUnrenamableDuplicateWidgets', () => { expect(widgets).toEqual([fine]) }) - it('refuses a name whose id the store would reject', () => { + it('refuses a name that cannot be encoded into an id, but keeps an empty one', () => { // `String(Symbol())` succeeds, so coercion alone says this name is fine — - // but `widgetId` encodes the raw value and throws on it. And an empty name - // encodes to nothing, minting `graphId:nodeId:`, which the store refuses - // to key on: the widget lands in exactly the unaddressable state this walk - // exists to catch, silently. + // but `widgetId` encodes the raw value and throws on it. + // + // An empty name is the opposite case and must NOT be refused: it mints an + // id the store declines to key on, which costs the widget nothing, while + // deleting it loses a widget that renders and serializes. const symbolNamed = widgetNamed(Symbol('seed')) const empty = widgetNamed('') const fine = widgetNamed('seed') const widgets = [fine, symbolNamed, empty] - expect(refusedWidgets(widgets)).toEqual([symbolNamed, empty]) - expect(widgets).toEqual([fine]) + expect(refusedWidgets(widgets)).toEqual([symbolNamed]) + expect(widgets).toEqual([fine, empty]) }) it('reports the name the walk read, not one the rename attempts left behind', () => { diff --git a/src/types/widgetId.ts b/src/types/widgetId.ts index 6cf0f86ae96..b02e528f0e6 100644 --- a/src/types/widgetId.ts +++ b/src/types/widgetId.ts @@ -127,11 +127,15 @@ function readName(widget: { name: string }): string | typeof UNREADABLE_NAME { const key = String(raw) // Mirrors `widgetId`, which encodes the **raw** value rather than the // coerced one — a Symbol survives `String()` and then throws there. - const encoded = encodeURIComponent(raw as string) - // `widgetId` is `graphId:nodeId:name` and its pattern needs a non-empty - // last segment, so an empty name mints an id the store refuses to key on. - // That is the unaddressable state this walk exists to catch. - if (!encoded) return UNREADABLE_NAME + // + // An *empty* name is deliberately not refused here. It mints + // `graphId:nodeId:`, which the store declines to key on — but declining an + // id costs the widget nothing, while refusing it deletes a widget that + // renders, fires its callback and serializes, and shifts every positional + // value after it. `addWidget('text', '', …)` is an ordinary unlabeled + // widget that node packs ship, and `emptyNameWidget.spec.ts` asserts it + // stays on the node. + encodeURIComponent(raw as string) return key } catch { return UNREADABLE_NAME From 7a355927337068cd3126f23fc651ecbdb5d84f7d Mon Sep 17 00:00:00 2001 From: Christian Byrne Date: Sun, 4 Oct 2026 09:31:02 -0700 Subject: [PATCH 14/35] test(widgets): pin that an unlabeled widget is neither deleted nor renamed MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `fb2a6e09c9` stopped refusing a name that encodes to nothing, which is right: the id `graphId:nodeId:` is one the store declines to key on, and declining costs the widget nothing, while refusing deletes a widget that renders and shifts every positional `widgets_values` slot after it. Only half of that is pinned. Mutating `readName` back to refusing an empty name is caught, but mutating the walk to *rename* it apart — the other repair that was proposed for this defect — survives the whole unit suite. The array assertions in `widgetId.test.ts` compare live widget objects, so a renamed widget is still `toEqual` itself. The only thing that catches a rename today is `emptyNameWidget.spec.ts`, which lives on `main` and is not part of this PR's suite, so the next change here gets no local signal. Four cases at the commit point, each killed by at least one mutation: the unlabeled widget stays under its own name; the store declines its id without withholding one from its siblings; it keeps the value it holds rather than losing it to a store entry it never got; and two unlabeled widgets, which *are* one identity twice, still settle by renaming the second rather than refusing it. No production code changes. Imports match the sibling suite in this directory, which emits the same three `no-restricted-paths` warnings; `oxlint --type-aware` over `src/lib/litegraph/src/node/` is exit 0. Co-Authored-By: Claude Opus 5 (1M context) --- .../node/widgetsView.emptyWidgetName.test.ts | 99 +++++++++++++++++++ 1 file changed, 99 insertions(+) create mode 100644 src/lib/litegraph/src/node/widgetsView.emptyWidgetName.test.ts diff --git a/src/lib/litegraph/src/node/widgetsView.emptyWidgetName.test.ts b/src/lib/litegraph/src/node/widgetsView.emptyWidgetName.test.ts new file mode 100644 index 00000000000..f7b4c810c07 --- /dev/null +++ b/src/lib/litegraph/src/node/widgetsView.emptyWidgetName.test.ts @@ -0,0 +1,99 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest' + +import { LGraph, LGraphNode, LiteGraph } from '@/lib/litegraph/src/litegraph' +import { reportError } from '@/platform/telemetry/reportError' +import { useWidgetValueStore } from '@/stores/widgetValueStore' + +vi.mock(import('@/platform/telemetry/reportError')) + +/** + * An empty widget name is not an ambiguous one, and the unique-name invariant + * must leave it alone in both directions. + * + * `widgetId` mints `graphId:nodeId:` for it, which `isWidgetId` rejects and + * `widgetValueStore.registerWidget` declines to key on. Declining an id is the + * whole cost: the widget stays on the node, renders, fires its callback and + * serializes. The two ways of "fixing" that are both worse and both have been + * written at least once: + * + * - **Refusing it** deletes a working widget and shifts every positional + * `widgets_values` slot after it. `browser_tests/tests/vueNodes/widgets/emptyNameWidget.spec.ts` + * is the user-visible pin (#13773: rgthree Power Lora Loader rendered no + * widgets at all), and these cases are the unit-level one. + * - **Renaming it apart** — to `#1` — relabels an ordinary unlabeled widget + * that no other widget collides with. `addWidget('text', '', …)` is a shape + * node packs ship deliberately. + * + * Both are pinned here because the array-level assertions in + * `widgetId.test.ts` compare live widget objects, so a rename passes them. + */ + +function createNode(): LGraphNode { + const graph = new LGraph() + const node = new LGraphNode('test') + graph.add(node) + return node +} + +function names(node: LGraphNode): string[] { + return (node.widgets ?? []).map((widget) => widget.name) +} + +function storedNames(node: LGraphNode): string[] { + return useWidgetValueStore() + .getNodeWidgets(node.graph!.rootGraph.id, node.id) + .map((widget) => widget.name) +} + +describe('empty widget name', () => { + beforeEach(() => { + LiteGraph.vueNodesMode = false + vi.mocked(reportError).mockClear() + }) + + it('keeps an unlabeled widget on the node, under the name it was given', () => { + const node = createNode() + node.addWidget('number', 'seed', 1, () => undefined, {}) + node.addWidget('text', '', 'hello', () => undefined, {}) + node.addWidget('number', 'cfg', 3, () => undefined, {}) + + // Still on the node, and still unlabeled. Asserting the name rather than + // only the array is what separates "kept" from "kept but relabeled `#1`". + expect(names(node)).toEqual(['seed', '', 'cfg']) + expect(reportError).not.toHaveBeenCalled() + }) + + it('declines the un-keyable id without withholding one from its siblings', () => { + const node = createNode() + node.addWidget('number', 'seed', 1, () => undefined, {}) + node.addWidget('text', '', 'hello', () => undefined, {}) + node.addWidget('number', 'cfg', 3, () => undefined, {}) + + // The store declines `graphId:nodeId:` and keeps every other widget. The + // failure this guards against is the whole node going unregistered + // because one widget could not be keyed. + expect(storedNames(node)).toEqual(['seed', 'cfg']) + }) + + it('keeps the value an unlabeled widget holds, rather than losing it to the store', () => { + const node = createNode() + const unlabeled = node.addWidget('text', '', 'hello', () => undefined, {}) + + // An unregistered widget reads and writes its own local state. If this + // regressed, the widget would render but forget what the user typed. + unlabeled.value = 'typed' + expect(unlabeled.value).toBe('typed') + }) + + it('still settles two unlabeled widgets, which do collide with each other', () => { + const node = createNode() + node.addWidget('text', '', 'first', () => undefined, {}) + node.addWidget('text', '', 'second', () => undefined, {}) + + // Two empty names are one identity twice, so the invariant applies as it + // does to any other duplicate — the second is renamed, not refused. + expect(names(node)).toEqual(['', '#1']) + expect(node.widgets).toHaveLength(2) + expect(reportError).not.toHaveBeenCalled() + }) +}) From ee9618a7b6f5a4f7ec0d94ead13d4c0d2c72d0ce Mon Sep 17 00:00:00 2001 From: Christian Byrne Date: Sun, 4 Oct 2026 12:31:34 -0700 Subject: [PATCH 15/35] fix(widgets): register kept unresolved widgets --- src/lib/litegraph/src/node/widgetsView.ts | 4 +++- .../node/widgetsView.uniqueWidgetName.test.ts | 23 +++++++++++++++++++ 2 files changed, 26 insertions(+), 1 deletion(-) diff --git a/src/lib/litegraph/src/node/widgetsView.ts b/src/lib/litegraph/src/node/widgetsView.ts index ed42e5df564..2a3ffb7294d 100644 --- a/src/lib/litegraph/src/node/widgetsView.ts +++ b/src/lib/litegraph/src/node/widgetsView.ts @@ -225,7 +225,9 @@ function refuseAmbiguousWidgets( ) } - return new Set(refused.map(({ widget }) => widget)) + return new Set( + refused.filter(({ removed }) => removed).map(({ widget }) => widget) + ) } /** diff --git a/src/lib/litegraph/src/node/widgetsView.uniqueWidgetName.test.ts b/src/lib/litegraph/src/node/widgetsView.uniqueWidgetName.test.ts index 70f27433b4c..f0c21c78203 100644 --- a/src/lib/litegraph/src/node/widgetsView.uniqueWidgetName.test.ts +++ b/src/lib/litegraph/src/node/widgetsView.uniqueWidgetName.test.ts @@ -2,6 +2,7 @@ import { beforeEach, describe, expect, it, vi } from 'vitest' import { LGraph, LGraphNode, LiteGraph } from '@/lib/litegraph/src/litegraph' import type { IBaseWidget } from '@/lib/litegraph/src/types/widgets' +import { isNodeBindable } from '@/lib/litegraph/src/utils/type' import { reportError } from '@/platform/telemetry/reportError' import { useWidgetValueStore } from '@/stores/widgetValueStore' import { toNodeId } from '@/types/nodeId' @@ -547,6 +548,28 @@ describe('unique widget name invariant', () => { expect(node.widgets).toContain(normalising) }) + it('registers an unresolved widget that the node keeps', () => { + const node = createNode() + node.addWidget('number', 'seed', 1, () => undefined, {}) + const unresolved = node.addWidget('number', 'steps', 2, () => undefined, {}) + let stored = 'seed' + Object.defineProperty(unresolved, 'name', { + get: () => stored, + set: (value: string) => { + stored = `${value}-normalised` + }, + configurable: true + }) + expect(isNodeBindable(unresolved)).toBe(true) + if (!isNodeBindable(unresolved)) throw new Error('Expected concrete widget') + const setNodeId = vi.spyOn(unresolved, 'setNodeId') + + node.addWidget('number', 'cfg', 3, () => undefined, {}) + + expect(node.widgets).toContain(unresolved) + expect(setNodeId).toHaveBeenCalledWith(node.id) + }) + it('does not report a refusal it cannot carry out on a subgraph node', () => { // A `SubgraphNode` rebuilds `widgets` on every read, so nothing this // module splices ever leaves the node. Enforcing there anyway reports the From 1ae10b8e0fbb2607deeed4f7bec25edda2e0ae1a Mon Sep 17 00:00:00 2001 From: Christian Byrne Date: Sun, 4 Oct 2026 13:30:20 -0700 Subject: [PATCH 16/35] fix(widgets): never let a duplicate rename move another widget's entry MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Keeping an unresolved duplicate on the node let it reach `setNodeId`, and registration then welded the pair onto one `WidgetState`: a `WidgetId` is `graphId:nodeId:name`, so the duplicate's "previous" id named whichever widget had actually registered that name, and `BaseWidget.set name` moved that entry. The rename read back as success, `_state` was reassigned to the other widget's object, and the two widgets shared one value — the second widget's value destroyed on exactly the undo-a-deletion/paste path this change set targets. Unreachable before the keep branch, because the duplicate was removed before `setNodeId` ran. Measured through the harness: the saved workflow held ["first default", "first default"] for a two-widget node, so the existing arity-only assertion went green over the corruption. - `BaseWidget.set name` moves an entry only when it is the one this widget is bound to. A stale `_state.nodeId` could otherwise reach across nodes and delete an unrelated node's registration, handing its value away. - `ensureUniqueWidgetNames` reads the write back instead of returning `true` unconditionally, so the gate `setNodeId`/`widgetId` bail on stops reporting success for a node that still carries an ambiguous pair. This is what makes `attachNodeToStores`'s "setNodeId would in fact register neither" true. - `nameIsWritable` walks the prototype chain. `name` is a class accessor, so no concrete widget has an own descriptor and every one fell through to `Object.isExtensible`, which answers whether properties can be added. It is also guarded: it invokes proxy traps outside the walk's `safeRead`, and a throw aborted the walk mid-`LGraph.add`. - An unresolved pair is reported once per node rather than on every commit; `reportError` has no throttle and the pair survives every later walk. Co-Authored-By: Claude Opus 5 (1M context) --- .../renamableDuplicateWidgetKept.spec.ts | 23 ++- .../node/widgetsView.refusalCriterion.test.ts | 106 ++++++++++++ src/lib/litegraph/src/node/widgetsView.ts | 155 +++++++++++++----- src/lib/litegraph/src/widgets/BaseWidget.ts | 22 ++- src/types/widgetId.test.ts | 49 ++++++ src/types/widgetId.ts | 57 ++++++- 6 files changed, 358 insertions(+), 54 deletions(-) diff --git a/browser_tests/tests/widgets/renamableDuplicateWidgetKept.spec.ts b/browser_tests/tests/widgets/renamableDuplicateWidgetKept.spec.ts index 3c3087ba0e9..e9aa3bfbbd8 100644 --- a/browser_tests/tests/widgets/renamableDuplicateWidgetKept.spec.ts +++ b/browser_tests/tests/widgets/renamableDuplicateWidgetKept.spec.ts @@ -27,12 +27,14 @@ import { zComfyWorkflow } from '@/platform/workflow/validation/schemas/workflowS * is what positional widget addressing reads, so a dropped slot shifts every * later widget. With the invariant's criterion corrected it saves both. * - * Not asserted, and deliberately: the two slots do not hold the two *values*. - * Re-registering an ambiguous pair routes the second widget's `name` setter - * through `renameWidget` on a stale `_state.nodeId`, which hands it the first - * widget's store entry, so both read the first widget's value. That is a - * separate pre-existing defect in `BaseWidget.set name`, unchanged either way - * here, and asserting the values would pin it as if it were correct. + * The two *values* are asserted too, and that is the stronger half. Arity alone + * went green over a save this change set used to corrupt: re-registering an + * ambiguous pair routed the second widget's `name` setter through + * `renameWidget` on an id the *first* widget had registered, which handed it + * that widget's store entry — so the two widgets shared one `WidgetState`, both + * read the first value, and the second value was gone from a two-slot save. A + * widget's own entry is now the only entry its rename may move + * (`BaseWidget.set name`), so both values survive and this asserts it. */ const NODE_TYPE = 'DevToolsNodeWithOutputList' @@ -135,6 +137,15 @@ test.describe( // One entry here is a widget the user lost. Two is the invariant being // enforced without charging them for it. expect(savedNode?.widgets_values).toHaveLength(2) + + // And two *distinct* values, because arity alone cannot tell a + // preserved widget from one welded onto its duplicate's store entry. + // `['first default', 'first default']` is the second value destroyed + // while the slot count still looks right. + expect(savedNode?.widgets_values).toEqual([ + 'first default', + 'second default' + ]) }) }) } diff --git a/src/lib/litegraph/src/node/widgetsView.refusalCriterion.test.ts b/src/lib/litegraph/src/node/widgetsView.refusalCriterion.test.ts index 09d9f2a1eb3..bb3e8532cbb 100644 --- a/src/lib/litegraph/src/node/widgetsView.refusalCriterion.test.ts +++ b/src/lib/litegraph/src/node/widgetsView.refusalCriterion.test.ts @@ -3,6 +3,7 @@ import { beforeEach, describe, expect, it, vi } from 'vitest' import { LGraph, LGraphNode, LiteGraph } from '@/lib/litegraph/src/litegraph' import { reportError } from '@/platform/telemetry/reportError' import { useWidgetValueStore } from '@/stores/widgetValueStore' +import { widgetId } from '@/types/widgetId' vi.mock(import('@/platform/telemetry/reportError')) @@ -71,6 +72,111 @@ describe('unique-name refusal criterion', () => { // silence — under its own `errorType`, because nothing was lost. expect(reportedTypes()).toEqual(['widget_duplicate_name_unresolved']) expect(reportedTypes()).not.toContain('widget_duplicate_name_refused') + + // Keeping the pair must not be paid for with a *value* either, which the + // widget array's length cannot show. An ambiguous pair registers neither + // widget, so each keeps its own state and the two stay independent — + // rather than both resolving to one store entry under the shared name. + expect(useWidgetValueStore().getNodeWidgets(graph.id, node.id)).toEqual([]) + expect(seed.value).toBe(1) + expect(steps.value).toBe(2) + + seed.value = 111 + steps.value = 222 + expect(seed.value).toBe(111) + expect(steps.value).toBe(222) + }) + + it('does not let a duplicate rename move the entry the other widget registered', () => { + const graph = new LGraph() + const node = new LGraphNode('test') + graph.add(node) + const seed = node.addWidget('number', 'seed', 1, () => undefined, {}) + const steps = node.addWidget('number', 'steps', 2, () => undefined, {}) + + graph.remove(node) + steps.name = 'seed' + graph.add(node) + + // `steps` claims `graphId:nodeId:seed` because identity is derived from the + // name it now shares. That id is `seed`'s to hold, so a rename of `steps` + // must not move it: being handed that entry is what welded the pair onto + // one `WidgetState` and destroyed the second value. + const store = useWidgetValueStore() + expect(store.getNodeWidgets(graph.id, node.id)).toEqual([]) + + // The write is declined rather than silently redirected, so the name the + // walk could not resolve is still ambiguous and still reported as such. + steps.name = 'seed#1' + expect( + store.getWidget(widgetId(graph.id, node.id, 'seed#1')) + ).toBeUndefined() + expect(seed.value).toBe(1) + expect(steps.value).toBe(2) + }) + + it('does not let a duplicate rename steal the entry of a widget on another node', () => { + const graph = new LGraph() + const store = useWidgetValueStore() + + // Node A holds an ordinary, legitimately registered `seed`. Nothing about + // node A is ambiguous and nothing below is node A's doing. + const nodeA = new LGraphNode('a') + graph.add(nodeA) + const aSeed = nodeA.addWidget('number', 'seed', 7, () => undefined, {}) + + const nodeB = new LGraphNode('b') + graph.add(nodeB) + nodeB.addWidget('number', 'seed', 1, () => undefined, {}) + const victim = nodeB.addWidget('number', 'steps', 2, () => undefined, {}) + + // A `_state.nodeId` left pointing at a node the widget no longer belongs + // to. Set directly rather than driven through widget adoption, which is + // what produces it in production; the stale binding is the precondition + // under test, not the route to it. + const state = (victim as unknown as { _state: { nodeId: unknown } })._state + state.nodeId = nodeA.id + + graph.remove(nodeB) + victim.name = 'seed' + graph.add(nodeB) + + // Node B carrying a duplicate name must not reach into node A. Renaming + // `victim` targets `graphId:A:seed` — node A's widget's id, because + // identity is `graphId:nodeId:name` and both parts are now borrowed. Moving + // that entry deletes node A's registration and hands node A's value to a + // widget on node B. + expect(store.getWidget(widgetId(graph.id, nodeA.id, 'seed'))?.value).toBe(7) + expect( + store.getWidget(widgetId(graph.id, nodeA.id, 'seed#1')) + ).toBeUndefined() + expect(aSeed.value).toBe(7) + expect(victim.value).toBe(2) + }) + + it('reports an unresolved pair once, not on every later commit', () => { + const graph = new LGraph() + const node = new LGraphNode('test') + graph.add(node) + node.addWidget('number', 'seed', 1, () => undefined, {}) + const steps = node.addWidget('number', 'steps', 2, () => undefined, {}) + + graph.remove(node) + steps.name = 'seed' + graph.add(node) + + expect(reportedTypes()).toEqual(['widget_duplicate_name_unresolved']) + + // A kept pair is re-found by every later commit, and `reportError` has no + // dedupe of its own — each call builds an `Error` with a stack and + // dispatches to Sentry and Datadog. An unresolvable pair would otherwise + // emit an identical warning for the rest of the session. + node.addWidget('number', 'cfg', 3, () => undefined, {}) + node.widgets?.push( + node.addWidget('number', 'denoise', 4, () => undefined, {}) + ) + + expect(reportedTypes()).toEqual(['widget_duplicate_name_unresolved']) }) it('leaves a kept duplicate wired up, rather than tearing it down in place', () => { diff --git a/src/lib/litegraph/src/node/widgetsView.ts b/src/lib/litegraph/src/node/widgetsView.ts index 2a3ffb7294d..55d959032c5 100644 --- a/src/lib/litegraph/src/node/widgetsView.ts +++ b/src/lib/litegraph/src/node/widgetsView.ts @@ -6,6 +6,7 @@ import { toConcreteWidget } from '@/lib/litegraph/src/widgets/widgetMap' import { useWidgetValueStore } from '@/stores/widgetValueStore' import { reportError } from '@/platform/telemetry/reportError' +import type { RefusedWidget } from '@/types/widgetId' import { dropUnrenamableDuplicateWidgets, isWidgetNameUnreadable @@ -62,6 +63,23 @@ interface WidgetsViewState { /** Shared empty result, so the common no-refusal path allocates nothing. */ const EMPTY_REFUSAL: ReadonlySet = new Set() +/** + * The unresolved names already reported for a node, so a pair that no later + * commit can resolve is alerted on once instead of on every commit. + * + * An unresolved pair — unlike the two removing causes — survives the walk, so + * every subsequent `syncWidgetOrder` (`push`, `splice`, a reorder, each + * `addWidget`) and every `attachNodeToStores` finds it again. `reportError` + * builds an `Error` with a stack and dispatches to Sentry and Datadog with no + * dedupe or throttle of its own, so reporting per pass is an unbounded stream + * of identical warnings for as long as the session lasts. The removing causes + * self-clear after one report because the widget is gone, and are not tracked. + * + * Replaced rather than added to on each pass: a name that stops being + * ambiguous and later collides again is a new event and is reported again. + */ +const reportedUnresolvedNames = new WeakMap>() + const states = new WeakMap() const widgetsViewGetters = new WeakSet<() => IBaseWidget[] | undefined>() @@ -179,50 +197,26 @@ function refuseAmbiguousWidgets( widgets: IBaseWidget[] ): ReadonlySet { const refused = dropUnrenamableDuplicateWidgets(widgets) - if (!refused.length) return EMPTY_REFUSAL + if (!refused.length) { + reportedUnresolvedNames.delete(node) + return EMPTY_REFUSAL + } + + const alreadyReported = takeUnresolvedReportGate(node, refused) + + for (const finding of refused) { + // An unresolved pair this node has already been alerted on is not a new + // event. Skipping before the teardown below would be wrong for any other + // cause, but an unresolved duplicate is never released, so there is + // nothing here to skip past. + if (alreadyReported(finding)) continue - for (const { widget, cause, removed, name } of refused) { - // The three causes are different failures and are alerted on separately: - // an unreadable name has no duplicate at all, so reporting one would send - // whoever reads the alert looking for a collision that does not exist, and - // an unresolved pair is still on the node rather than lost. - // - // Both the cause and the name come from the walk, never from another read - // of the accessor. It is hostile by definition, it need not answer twice - // the same way, and the walk may have written to it up to four times - // before giving up — so a re-read can name a candidate no widget holds. - // // Only a widget the walk took off the array needs releasing; an unresolved // duplicate is still the node's widget and must keep its slot wiring. - if (removed) releaseRefusedWidget(node, widget, name) - reportError( - new Error( - cause === 'unreadable-name' - ? // Deliberately not "the accessor threw": a name that will not - // coerce or will not percent-encode reads perfectly and still - // yields no id. - `Refused a widget on node ${node.id}: no widget identity can be derived from its name` - : cause === 'unresolved-duplicate' - ? `Kept a widget named "${name}" that node ${node.id} already has under that name: the rename was declined rather than impossible, so the widget is left in place and the pair is unresolved for now` - : `Refused a widget named "${name}": node ${node.id} already has a widget of that name and the duplicate cannot be renamed` - ), - { - errorType: - cause === 'unreadable-name' - ? UNREADABLE_WIDGET_NAME_ERROR_TYPE - : cause === 'unresolved-duplicate' - ? UNRESOLVED_WIDGET_NAME_ERROR_TYPE - : DUPLICATE_WIDGET_NAME_ERROR_TYPE, - surface: 'graph', - level: 'warning', - tags: { node_type: node.type }, - context: { - nodeId: String(node.id), - widgetName: name, - widgetType: safeRead(() => widget.type) - } - } - ) + if (finding.removed) { + releaseRefusedWidget(node, finding.widget, finding.name) + } + reportRefusal(node, finding) } return new Set( @@ -230,6 +224,85 @@ function refuseAmbiguousWidgets( ) } +/** + * Records which names are unresolved on {@link node} now, and returns the + * predicate for "already alerted on before this pass". + * + * Replaces the record rather than adding to it, so a name that stops being + * ambiguous and later collides again is reported again. + */ +function takeUnresolvedReportGate( + node: LGraphNode, + refused: readonly RefusedWidget[] +): (finding: RefusedWidget) => boolean { + const previous = reportedUnresolvedNames.get(node) + const unresolved = new Set( + refused + .filter(({ cause }) => cause === 'unresolved-duplicate') + .map(({ name }) => String(name)) + ) + if (unresolved.size) reportedUnresolvedNames.set(node, unresolved) + else reportedUnresolvedNames.delete(node) + + return ({ cause, name }) => + cause === 'unresolved-duplicate' && !!previous?.has(String(name)) +} + +/** + * The alert for one finding. The three causes are different failures and are + * alerted on separately: an unreadable name has no duplicate at all, so + * reporting one would send whoever reads the alert looking for a collision that + * does not exist, and an unresolved pair is still on the node rather than lost. + * + * `cause` and `name` come from the walk, never from another read of the + * accessor. It is hostile by definition, it need not answer twice the same way, + * and the walk may have written to it up to four times before giving up — so a + * re-read can name a candidate no widget holds. + */ +const REFUSAL_ALERTS: Record< + RefusedWidget['cause'], + { + errorType: string + message: (nodeId: LGraphNode['id'], name: string | undefined) => string + } +> = { + // Deliberately not "the accessor threw": a name that will not coerce or will + // not percent-encode reads perfectly and still yields no id. + 'unreadable-name': { + errorType: UNREADABLE_WIDGET_NAME_ERROR_TYPE, + message: (nodeId) => + `Refused a widget on node ${nodeId}: no widget identity can be derived from its name` + }, + 'unresolved-duplicate': { + errorType: UNRESOLVED_WIDGET_NAME_ERROR_TYPE, + message: (nodeId, name) => + `Kept a widget named "${name}" that node ${nodeId} already has under that name: the rename was declined rather than impossible, so the widget is left in place and the pair is unresolved for now` + }, + 'duplicate-name': { + errorType: DUPLICATE_WIDGET_NAME_ERROR_TYPE, + message: (nodeId, name) => + `Refused a widget named "${name}": node ${nodeId} already has a widget of that name and the duplicate cannot be renamed` + } +} + +function reportRefusal( + node: LGraphNode, + { widget, cause, name }: RefusedWidget +): void { + const alert = REFUSAL_ALERTS[cause] + reportError(new Error(alert.message(node.id, name)), { + errorType: alert.errorType, + surface: 'graph', + level: 'warning', + tags: { node_type: node.type }, + context: { + nodeId: String(node.id), + widgetName: name, + widgetType: safeRead(() => widget.type) + } + }) +} + /** * Whether {@link node} still exposes the mutation view this module installed, * and so is subject to the unique-name invariant at all. diff --git a/src/lib/litegraph/src/widgets/BaseWidget.ts b/src/lib/litegraph/src/widgets/BaseWidget.ts index 9b9fa964545..786f5bfeed8 100644 --- a/src/lib/litegraph/src/widgets/BaseWidget.ts +++ b/src/lib/litegraph/src/widgets/BaseWidget.ts @@ -142,8 +142,26 @@ export abstract class BaseWidget return } - const moved = useWidgetValueStore().renameWidget( - widgetId(graphId, nodeId, previous), + const store = useWidgetValueStore() + const previousId = widgetId(graphId, nodeId, previous) + + // A `WidgetId` is `graphId:nodeId:name`, so two widgets that share a name + // on one node claim the same id — and `previousId` then names whichever of + // them actually registered it, which need not be this one. Moving an entry + // this widget is not bound to would hand it the other widget's state: the + // rename reads back as success, `_state` is reassigned to that object, and + // the pair is welded onto one `WidgetState` with one value between them. + // + // Only this widget's own entry is this widget's to move. When the id holds + // someone else's, the rename is declined exactly as it is when the store + // has no entry at all — the caller's read-back reports the failure, and + // `ensureUniqueWidgetNames` turns that into a refusal to register rather + // than a colliding id. + const registered = store.getWidget(previousId) + if (registered && registered !== this._state) return + + const moved = store.renameWidget( + previousId, widgetId(graphId, nodeId, value) ) if (!moved) return diff --git a/src/types/widgetId.test.ts b/src/types/widgetId.test.ts index 1da858236e6..09b881b7bd8 100644 --- a/src/types/widgetId.test.ts +++ b/src/types/widgetId.test.ts @@ -306,6 +306,55 @@ describe('dropUnrenamableDuplicateWidgets', () => { expect(flaky.name).toBe('seed') }) + it('removes a duplicate whose `name` is a getter-only accessor on its prototype', () => { + const first = { name: 'seed' } + // No *own* `name` descriptor, and the inherited one has no setter — so + // every write throws and is swallowed, exactly like the non-writable own + // property above. A predicate that inspects only the own object finds + // nothing and falls through to `Object.isExtensible`, which answers whether + // properties can be *added*, not whether `name` can be written. That makes + // this widget look renamable and keeps it forever as an unresolved + // duplicate, silently sharing `first`'s identity — the precise case + // removal exists for. + const inherited = Object.create({ + get name() { + return 'seed' + } + }) as { name: string } + + const refused = dropUnrenamableDuplicateWidgets([first, inherited]) + + expect(refused.map(({ cause }) => cause)).toEqual(['duplicate-name']) + expect(refused.map(({ removed }) => removed)).toEqual([true]) + }) + + it('refuses a widget whose descriptor trap throws instead of aborting the walk', () => { + const first = { name: 'seed' } + const target = {} + Object.defineProperty(target, 'name', { + value: 'seed', + writable: false, + configurable: true + }) + // `nameIsWritable` is reached from `resolveCollision`, which — unlike the + // `name` reads in the same walk — is not inside a guard, and + // `getOwnPropertyDescriptor`/`isExtensible` both invoke proxy traps. A + // throwing trap used to escape the whole walk, which runs inside + // `LGraph.add` after node state is partly attached. + const hostile = new Proxy(target, { + getOwnPropertyDescriptor() { + throw new Error('hostile descriptor trap') + } + }) as { name: string } + + const widgets = [first, hostile] + expect(() => dropUnrenamableDuplicateWidgets(widgets)).not.toThrow() + + // Unaddressable, so refused — and the widget holding the name legitimately + // is still there, which a mid-walk throw would have left undecided. + expect(widgets).toEqual([first]) + }) + it('collides names that differ as values but coincide as id strings', () => { // `widgetId` keys on `encodeURIComponent(String(name))`, so these two mint // the same id. Comparing the raw values lets both through and the clash diff --git a/src/types/widgetId.ts b/src/types/widgetId.ts index 6e74a36c6eb..71fa25b7564 100644 --- a/src/types/widgetId.ts +++ b/src/types/widgetId.ts @@ -37,9 +37,35 @@ export function widgetId( * copies of one rule. */ function nameIsWritable(widget: { name: string }): boolean { - const descriptor = Object.getOwnPropertyDescriptor(widget, 'name') - if (!descriptor) return Object.isExtensible(widget) - return 'writable' in descriptor ? !!descriptor.writable : !!descriptor.set + try { + // The whole prototype chain, not just the own object. `BaseWidget` declares + // `name` as a class accessor, so an instance has no *own* descriptor and + // every concrete widget would otherwise fall through to the + // `Object.isExtensible` branch below — which answers whether properties can + // be *added*, not whether `name` can be written. That branch happens to say + // "writable" for `BaseWidget`, so the bug hides; it says the same for a + // widget whose inherited `name` is a getter with no setter, and that one is + // genuinely unaddressable and must still be refused. + for ( + let target: object | null = widget; + target; + target = Reflect.getPrototypeOf(target) + ) { + const descriptor = Object.getOwnPropertyDescriptor(target, 'name') + if (!descriptor) continue + return 'writable' in descriptor ? !!descriptor.writable : !!descriptor.set + } + // No descriptor anywhere on the chain: `name` is not defined yet, so a + // write would create it, and that is what extensibility decides. + return Object.isExtensible(widget) + } catch { + // `getOwnPropertyDescriptor`, `getPrototypeOf` and `isExtensible` all + // invoke proxy traps, and this runs mid-walk inside `LGraph.add`. A widget + // whose traps throw cannot be addressed at all, which is precisely the case + // removal exists for — so answer "not writable" instead of letting the + // throw abort the walk with the node half-attached. + return false + } } export function ensureUniqueWidgetNames( @@ -79,8 +105,29 @@ export function ensureUniqueWidgetNames( return false } - for (const { widget, name } of renames) widget.name = name - return true + // The write is read back, and a write that did not land makes this `false`. + // + // This is the gate `BaseWidget.setNodeId` and `BaseWidget.widgetId` bail + // on, so returning `true` over a node that still carries two widgets under + // one name is what lets a colliding `WidgetId` be minted and registered. + // `BaseWidget`'s own `name` setter declines the write whenever the store + // declines the move — which is exactly the state + // `dropUnrenamableDuplicateWidgets` leaves behind when it keeps an + // unresolved duplicate rather than deleting the user's widget — so the + // unconditional `true` reported success precisely where it was wrong. + // + // Every rename is still attempted before answering: one declined write + // must not strand the collisions that would have resolved cleanly. + let unique = true + for (const { widget, name } of renames) { + try { + widget.name = name + if (widget.name !== name) unique = false + } catch { + unique = false + } + } + return unique } catch (error) { console.warn('Failed to rename duplicate widgets', error) return false From 1dd6a254a270f88b51da1112e7dffaf2ab812b80 Mon Sep 17 00:00:00 2001 From: Christian Byrne Date: Sun, 4 Oct 2026 15:08:37 -0700 Subject: [PATCH 17/35] test(widgets): pin the refusal guards and what a refusal does to saved values MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Three gaps the review found, two of them unpinned behaviour and one an unrecorded decision. `domWidget.addWidget` guards registration twice — once for a node that already has a graph and once inside `onAdded` for a node that refuses on the join — and deleting either left `domWidget.test.ts` and the unique-name suites green, so a regression would mount a DOM element for a widget the node no longer has. One case per path, against the real DOM widget store; each dies only to its own guard. `widgetsView.refusalValueRestore.test.ts` measures what a removal does to a workflow saved before the invariant existed: the refusal runs before `node.configure` restores values, so positional restore hands the next widget the refused one's value. The ADR now records that as accepted and names what it takes to reach — a renamable duplicate is kept, and a saved name register restores by name — rather than leaving the consequence implicit. Also corrects two ADR claims the review flagged: "unreadable" is not only a throwing accessor, and the boundary list no longer counts itself wrong. --- docs/adr/ECS-0008-entity-component-system.md | 27 +++-- .../widgetsView.refusalValueRestore.test.ts | 98 +++++++++++++++++++ src/scripts/domWidget.test.ts | 66 ++++++++++++- 3 files changed, 183 insertions(+), 8 deletions(-) create mode 100644 src/lib/litegraph/src/node/widgetsView.refusalValueRestore.test.ts diff --git a/docs/adr/ECS-0008-entity-component-system.md b/docs/adr/ECS-0008-entity-component-system.md index 8a40a299ad3..f58de080c9b 100644 --- a/docs/adr/ECS-0008-entity-component-system.md +++ b/docs/adr/ECS-0008-entity-component-system.md @@ -186,10 +186,12 @@ legitimate re-mint rather than an identity collision — which is why > identity twice, and nothing downstream can tell the two apart. > > The repeat is renamed to `name#1` before any id is derived. Where it cannot -> be — a `name` that cannot be written at all, or an accessor that throws -> (`src/types/widgetId.ts`) — the widget is **refused**: it is dropped from -> `node.widgets` and reported. First occurrence wins; renamable collisions -> elsewhere on the node are still renamed. +> be — a `name` that cannot be written at all — the widget is **refused**: it +> is dropped from `node.widgets` and reported. A widget whose name yields no id +> at all is refused the same way, and that is not only an accessor that throws: +> a value that will not coerce to a string and one `encodeURIComponent` rejects +> are the same failure (`src/types/widgetId.ts`). First occurrence wins; +> renamable collisions elsewhere on the node are still renamed. > > **Refusal keys on whether the write was possible, not on whether it landed, > and the difference is load-bearing.** `BaseWidget.set name` delegates to @@ -225,8 +227,7 @@ legitimate re-mint rather than an identity collision — which is why > assignment all commit through it — but it enforces nothing until `graphId` > exists, so it does not cover the join itself. > -> Four boundaries on that, because each one is load-bearing and none is -> obvious from the rule: +> These boundaries are part of the decision: > > - **Enforcement starts when the node joins a graph**, not when a detached > node is built. No `WidgetId` exists before then, so there is no identity to @@ -274,6 +275,20 @@ legitimate re-mint rather than an identity collision — which is why > and report a refusal that did not happen. Two promoted inputs carrying the > same inner widget name reach exactly that state, so the gate is > load-bearing rather than defensive. +> - **A removal shifts the positional values of a workflow saved before it, and +> that is accepted here rather than fixed.** `LGraph.configure` adds each node +> before configuring it, so the refusal has already run by the time values are +> restored, and positional restore counts the widgets the node has _now_ — so +> for `[a, dup, b]` saved as `[1, 2, 3]`, `b` is handed `2` and `3` is +> dropped. It takes all three of a pre-change workflow, a widget whose `name` +> cannot be written, and no name register: a renamable duplicate is kept +> rather than removed, and a saved `widgets_values_named` restores each widget +> under its own name instead. All three measured at this head in +> `widgetsView.refusalValueRestore.test.ts`. Carrying the refused widget's +> original slot through `createWidgetRestorationState` as an index map would +> close the remainder; it is not done here because that record has to be built +> at the join and read back during restore, and a stale one would move values +> on every later load — a worse failure than the one it fixes. > > A serialized `(name, occurrence)` identity was proposed instead, so that both > widgets could be persisted ([#19717](https://github.com/Comfy-Org/ComfyUI_frontend/pull/19717)). diff --git a/src/lib/litegraph/src/node/widgetsView.refusalValueRestore.test.ts b/src/lib/litegraph/src/node/widgetsView.refusalValueRestore.test.ts new file mode 100644 index 00000000000..b158e382c4b --- /dev/null +++ b/src/lib/litegraph/src/node/widgetsView.refusalValueRestore.test.ts @@ -0,0 +1,98 @@ +import { afterEach, beforeEach, describe, expect, it } from 'vitest' + +import { LGraph, LGraphNode, LiteGraph } from '@/lib/litegraph/src/litegraph' + +/** + * What a refusal does to the values of a workflow saved before it existed. + * Positional restore counts the widgets the node has *now*, so a removed + * widget's slot is taken by the next widget. ADR-ECS-0008 records that as + * accepted and names the conditions; these cases pin it so it stays a decision + * rather than a surprise. + */ +describe('restoring values onto a node that refused a widget', () => { + const namedValuesRestore = LiteGraph.namedValuesRestore + + beforeEach(() => { + class Pinned extends LGraphNode { + constructor(title?: string) { + super(title ?? 'Pinned') + this.addWidget('number', 'a', 0, () => {}) + const duplicate = this.addWidget('number', 'a', 0, () => {}) + Object.defineProperty(duplicate, 'name', { + value: 'a', + writable: false, + configurable: false, + enumerable: true + }) + this.addWidget('number', 'b', 0, () => {}) + } + } + + class Renamable extends LGraphNode { + constructor(title?: string) { + super(title ?? 'Renamable') + this.addWidget('number', 'a', 0, () => {}) + this.addWidget('number', 'a', 0, () => {}) + this.addWidget('number', 'b', 0, () => {}) + } + } + + LiteGraph.registerNodeType('test/pinned-duplicate', Pinned) + LiteGraph.registerNodeType('test/renamable-duplicate', Renamable) + }) + + afterEach(() => { + LiteGraph.namedValuesRestore = namedValuesRestore + }) + + /** + * `LGraph.configure` adds each node and configures it afterwards, so the + * refusal has already run by the time values are restored. + */ + function load(type: string, named?: Record) { + const graph = new LGraph() + const node = LiteGraph.createNode(type)! + graph.add(node) + node.configure({ + id: node.id, + type, + pos: [0, 0], + size: [200, 100], + flags: {}, + order: 0, + mode: 0, + widgets_values: [1, 2, 3], + ...(named ? { widgets_values_named: named } : {}) + }) + + return { + names: (node.widgets ?? []).map((widget) => widget.name), + values: (node.widgets ?? []).map((widget) => widget.value) + } + } + + it('keeps every saved value when the duplicate could be renamed apart', () => { + expect(load('test/renamable-duplicate')).toEqual({ + names: ['a', 'a#1', 'b'], + values: [1, 2, 3] + }) + }) + + it('restores the right value from a name register, refusal or not', () => { + LiteGraph.namedValuesRestore = true + + expect(load('test/pinned-duplicate', { a: 1, b: 3 })).toEqual({ + names: ['a', 'b'], + values: [1, 3] + }) + }) + + it('shifts the values after a refused widget when only positions were saved', () => { + LiteGraph.namedValuesRestore = false + + expect(load('test/pinned-duplicate')).toEqual({ + names: ['a', 'b'], + values: [1, 2] + }) + }) +}) diff --git a/src/scripts/domWidget.test.ts b/src/scripts/domWidget.test.ts index d4c34254526..e8395a17e65 100644 --- a/src/scripts/domWidget.test.ts +++ b/src/scripts/domWidget.test.ts @@ -1,12 +1,20 @@ import { describe, expect, test, vi } from 'vitest' -import { LGraphNode } from '@/lib/litegraph/src/litegraph' -import { ComponentWidgetImpl, DOMWidgetImpl } from '@/scripts/domWidget' +import { LGraph, LGraphNode } from '@/lib/litegraph/src/litegraph' +import type { IBaseWidget } from '@/lib/litegraph/src/types/widgets' +import { + addWidget, + ComponentWidgetImpl, + DOMWidgetImpl +} from '@/scripts/domWidget' +import { useDomWidgetStore } from '@/stores/domWidgetStore' vi.mock(import('@/utils/formatUtil'), () => ({ generateUUID: () => 'test-uuid' })) +vi.mock(import('@/platform/telemetry/reportError')) + describe('DOMWidget Y Position Preservation', () => { test('ComponentWidgetImpl createCopyForNode preserves Y position and component wiring', () => { const mockNode = new LGraphNode('test-node') @@ -97,3 +105,57 @@ describe('BaseDOMWidgetImpl.isVisible', () => { expect(widget.isVisible()).toBe(false) }) }) + +describe('addWidget on a node that refuses the widget', () => { + /** + * How the state is reached in the wild: an extension redefines `name` on an + * existing widget, so the duplicate cannot be renamed apart and is removed + * from the node (ADR-ECS-0008). + */ + function pinName(widget: IBaseWidget, name: string): void { + Object.defineProperty(widget, 'name', { + value: name, + writable: false, + configurable: false, + enumerable: true + }) + } + + function refusedDomWidget(node: LGraphNode) { + const widget = new DOMWidgetImpl({ + node, + name: 'seed', + type: 'custom', + element: document.createElement('div'), + options: {} + }) + pinName(widget, 'seed') + return widget + } + + test('does not register a widget the attached node refused', () => { + const graph = new LGraph() + const node = new LGraphNode('test-node') + graph.add(node) + node.addWidget('text', 'seed', '', () => {}) + const widget = refusedDomWidget(node) + + addWidget(node, widget) + + expect(node.widgets).not.toContain(widget) + expect(useDomWidgetStore().widgetStates.has(widget.id)).toBe(false) + }) + + test('does not register a widget refused when the node joins a graph', () => { + const node = new LGraphNode('test-node') + node.addWidget('text', 'seed', '', () => {}) + const widget = refusedDomWidget(node) + addWidget(node, widget) + expect(node.widgets).toContain(widget) + + new LGraph().add(node) + + expect(node.widgets).not.toContain(widget) + expect(useDomWidgetStore().widgetStates.has(widget.id)).toBe(false) + }) +}) From 43ce9b84e85d755a729ca4772d4c37e9dfc93760 Mon Sep 17 00:00:00 2001 From: Christian Byrne Date: Sun, 4 Oct 2026 15:16:57 -0700 Subject: [PATCH 18/35] fix(widgets): release the entry a refused widget left behind MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A widget can register under a unique name and be pinned onto another widget's name afterwards — `Object.defineProperty` bypasses the `name` setter, so the store entry stays under the earlier name while the node refuses the widget. Nothing released that entry, and `registerWidget` keeps an existing value for a same-type re-registration, so the next widget to take that name came up holding a dead widget's value. Measured before the fix on a node whose second `seed` widget was renamed to `seed#1`, given the value 42 and then pinned onto `seed`: the `seed#1` entry survived the refusal, and a fresh `seed#1` widget created with the value 7 read back 42. The entry is found by identity, not by the refused widget's current name: that name is by definition the one another widget kept, and deleting its entry is the failure this whole invariant exists to prevent. --- .../widgetsView.refusedEntryRelease.test.ts | 68 +++++++++++++++++++ src/lib/litegraph/src/node/widgetsView.ts | 7 ++ src/lib/litegraph/src/types/widgets.ts | 6 ++ src/lib/litegraph/src/widgets/BaseWidget.ts | 22 ++++++ 4 files changed, 103 insertions(+) create mode 100644 src/lib/litegraph/src/node/widgetsView.refusedEntryRelease.test.ts diff --git a/src/lib/litegraph/src/node/widgetsView.refusedEntryRelease.test.ts b/src/lib/litegraph/src/node/widgetsView.refusedEntryRelease.test.ts new file mode 100644 index 00000000000..9955dd2bb51 --- /dev/null +++ b/src/lib/litegraph/src/node/widgetsView.refusedEntryRelease.test.ts @@ -0,0 +1,68 @@ +import { describe, expect, it } from 'vitest' + +import { LGraph, LGraphNode } from '@/lib/litegraph/src/litegraph' +import type { IBaseWidget } from '@/lib/litegraph/src/types/widgets' +import { useWidgetValueStore } from '@/stores/widgetValueStore' +import { widgetId } from '@/types/widgetId' + +/** + * A widget can register under a unique name and only later be pinned onto a + * name another widget holds — `Object.defineProperty` bypasses the setter, so + * the store entry stays under the earlier name while the node refuses the + * widget. `registerWidget` keeps an existing value for a same-type + * re-registration, so that entry would hand its value to the next widget of + * that name. + */ +describe('the store entry of a refused widget', () => { + function pinName(widget: IBaseWidget, name: string): void { + Object.defineProperty(widget, 'name', { + value: name, + writable: false, + configurable: false, + enumerable: true + }) + } + + function nodeWithRefusedWidget() { + const graph = new LGraph() + const node = new LGraphNode('test') + graph.add(node) + const kept = node.addWidget('number', 'seed', 1, () => {}) + const refused = node.addWidget('number', 'seed', 2, () => {}) + refused.value = 42 + const registeredName = refused.name + pinName(refused, 'seed') + node.addWidget('number', 'steps', 0, () => {}) + + return { + node, + kept, + registeredName, + graphId: node.graph!.rootGraph.id + } + } + + it('is released, so a later widget of that name keeps its own value', () => { + const { node, registeredName, graphId } = nodeWithRefusedWidget() + + expect( + useWidgetValueStore().getWidget( + widgetId(graphId, node.id, registeredName) + ) + ).toBeUndefined() + expect(node.addWidget('number', registeredName, 7, () => {}).value).toBe(7) + }) + + it('is released without disturbing the widget that kept the name', () => { + const { node, kept, graphId } = nodeWithRefusedWidget() + + expect(kept.value).toBe(1) + expect( + useWidgetValueStore().getWidget(widgetId(graphId, node.id, 'seed'))?.value + ).toBe(1) + expect((node.widgets ?? []).map((widget) => widget.name)).toEqual([ + 'seed', + 'steps' + ]) + }) +}) diff --git a/src/lib/litegraph/src/node/widgetsView.ts b/src/lib/litegraph/src/node/widgetsView.ts index 55d959032c5..4347556c4d2 100644 --- a/src/lib/litegraph/src/node/widgetsView.ts +++ b/src/lib/litegraph/src/node/widgetsView.ts @@ -179,6 +179,13 @@ function releaseRefusedWidget( } catch (error) { reportTeardownFailure(node, error) } + + // After `onRemove`, which may still read the value through the entry. + try { + widget.releaseRegisteredState?.() + } catch (error) { + reportTeardownFailure(node, error) + } } /** diff --git a/src/lib/litegraph/src/types/widgets.ts b/src/lib/litegraph/src/types/widgets.ts index 7d20f501ce1..63f7dfecf64 100644 --- a/src/lib/litegraph/src/types/widgets.ts +++ b/src/lib/litegraph/src/types/widgets.ts @@ -488,6 +488,12 @@ export interface IBaseWidget< readonly widgetId?: WidgetId + /** + * Drops the store entry this widget is bound to, if the store still holds + * that entry. Absent on raw widget objects, which hold none. + */ + releaseRegisteredState?(): void + name: string options: TOptions syncLiveVisibilityOptions?(): void diff --git a/src/lib/litegraph/src/widgets/BaseWidget.ts b/src/lib/litegraph/src/widgets/BaseWidget.ts index 786f5bfeed8..292c544cf9b 100644 --- a/src/lib/litegraph/src/widgets/BaseWidget.ts +++ b/src/lib/litegraph/src/widgets/BaseWidget.ts @@ -435,6 +435,28 @@ export abstract class BaseWidget this.bindRegisteredState(nodeId) } + /** + * Drops the entry this widget is bound to, for a widget the node has just + * refused. Its entry sits under the name it registered, which no widget + * holds any more — and `registerWidget` keeps an existing value when a later + * widget of the same type takes that name, so leaving it hands the next + * widget of that name a dead one's value. + * + * The entry is found by identity rather than by this widget's current name: + * a refused duplicate's name is by definition the one another widget kept, + * and that widget's entry must not be touched. + */ + releaseRegisteredState(): void { + const graphId = this.node.graph?.rootGraph.id + const { nodeId, name } = this._state + if (!graphId || nodeId === undefined) return + + const store = useWidgetValueStore() + const id = widgetId(graphId, nodeId, name) + if (store.getWidget(id) !== this._state) return + store.deleteWidget(id) + } + bindRegisteredState(nodeId: NodeId): boolean { const graphId = this.node.graph?.rootGraph.id if (!graphId) return false From 5fa883abbd8f0d7634488c71c242bc1a1379ebe6 Mon Sep 17 00:00:00 2001 From: Christian Byrne Date: Sun, 4 Oct 2026 15:23:05 -0700 Subject: [PATCH 19/35] refactor(widgets): name the refusal error types the way the repo asks `src/AGENTS.md` asks for `__`, with the operation as a present participle; all four slugs started with the subject and ended with a past participle. None has shipped, so renaming is free now and a telemetry migration later. The operation that failed names each one: renaming a duplicate, reading a name, resolving a pair the node kept, tearing down a widget it refused. Also corrects three comments the review read as wrong rather than redundant: a removed widget may well have been registered, under a name it held before it was pinned onto another widget's; `RENAME_ATTEMPTS` no longer decides removal; and the SubgraphNode note no longer names a slug that moved. --- docs/adr/ECS-0008-entity-component-system.md | 6 +- .../node/widgetsView.refusalCriterion.test.ts | 10 ++-- src/lib/litegraph/src/node/widgetsView.ts | 58 +++++-------------- .../node/widgetsView.uniqueWidgetName.test.ts | 16 ++--- src/types/widgetId.ts | 11 ++-- 5 files changed, 35 insertions(+), 66 deletions(-) diff --git a/docs/adr/ECS-0008-entity-component-system.md b/docs/adr/ECS-0008-entity-component-system.md index f58de080c9b..0f183bc9569 100644 --- a/docs/adr/ECS-0008-entity-component-system.md +++ b/docs/adr/ECS-0008-entity-component-system.md @@ -211,10 +211,10 @@ legitimate re-mint rather than an identity collision — which is why > > Three stable `errorType`s, because the causes need different alerts and > collapsing them reports a collision that does not exist: -> `widget_duplicate_name_refused` for a duplicate that could not be renamed -> apart, `widget_unreadable_name_refused` for a widget whose `name` accessor +> `failure_renaming_widget_duplicate_name` for a duplicate that could not be renamed +> apart, `failure_reading_widget_name` for a widget whose `name` accessor > throws — that one has no duplicate at all, only no derivable id — and -> `widget_duplicate_name_unresolved` for a pair the node **keeps**, where the +> `failure_resolving_widget_duplicate_name` for a pair the node **keeps**, where the > rename was declined rather than impossible. The third is not a report of lost > widgets: the widget is still on the node, and a later commit can still > resolve it. diff --git a/src/lib/litegraph/src/node/widgetsView.refusalCriterion.test.ts b/src/lib/litegraph/src/node/widgetsView.refusalCriterion.test.ts index bb3e8532cbb..845757cd813 100644 --- a/src/lib/litegraph/src/node/widgetsView.refusalCriterion.test.ts +++ b/src/lib/litegraph/src/node/widgetsView.refusalCriterion.test.ts @@ -70,8 +70,8 @@ describe('unique-name refusal criterion', () => { // It is still reported, so the pair is observable rather than tolerated in // silence — under its own `errorType`, because nothing was lost. - expect(reportedTypes()).toEqual(['widget_duplicate_name_unresolved']) - expect(reportedTypes()).not.toContain('widget_duplicate_name_refused') + expect(reportedTypes()).toEqual(['failure_resolving_widget_duplicate_name']) + expect(reportedTypes()).not.toContain('failure_renaming_widget_duplicate_name') // Keeping the pair must not be paid for with a *value* either, which the // widget array's length cannot show. An ambiguous pair registers neither @@ -165,7 +165,7 @@ describe('unique-name refusal criterion', () => { steps.name = 'seed' graph.add(node) - expect(reportedTypes()).toEqual(['widget_duplicate_name_unresolved']) + expect(reportedTypes()).toEqual(['failure_resolving_widget_duplicate_name']) // A kept pair is re-found by every later commit, and `reportError` has no // dedupe of its own — each call builds an `Error` with a stack and @@ -176,7 +176,7 @@ describe('unique-name refusal criterion', () => { node.addWidget('number', 'denoise', 4, () => undefined, {}) ) - expect(reportedTypes()).toEqual(['widget_duplicate_name_unresolved']) + expect(reportedTypes()).toEqual(['failure_resolving_widget_duplicate_name']) }) it('leaves a kept duplicate wired up, rather than tearing it down in place', () => { @@ -228,6 +228,6 @@ describe('unique-name refusal criterion', () => { // Nothing can address this one, so keeping it would silently share the // other widget's value. Removal is correct here and is not weakened. expect(node.widgets).not.toContain(doomed) - expect(reportedTypes()).toContain('widget_duplicate_name_refused') + expect(reportedTypes()).toContain('failure_renaming_widget_duplicate_name') }) }) diff --git a/src/lib/litegraph/src/node/widgetsView.ts b/src/lib/litegraph/src/node/widgetsView.ts index 4347556c4d2..2c25cd18eac 100644 --- a/src/lib/litegraph/src/node/widgetsView.ts +++ b/src/lib/litegraph/src/node/widgetsView.ts @@ -17,41 +17,10 @@ import { isNodeBindable } from '../utils/type' import { getWidgetIds } from '../utils/widget' /** - * Stable `errorType` for the one state that breaks widget identity: a node - * holding two widgets under one name that could not be renamed apart, so the - * second is refused. Alerting is keyed on this string — treat it as a - * contract, not an implementation detail. - * See {@link dropUnrenamableDuplicateWidgets}. + * `errorType` slugs here follow `src/AGENTS.md`'s + * `__` form. */ -const DUPLICATE_WIDGET_NAME_ERROR_TYPE = 'widget_duplicate_name_refused' - -/** - * Stable `errorType` for the other refusable state: a widget whose `name` - * accessor throws, so no `WidgetId` can be derived for it and no duplicate is - * involved. Separate from {@link DUPLICATE_WIDGET_NAME_ERROR_TYPE} because the - * two need different alerts — and because collapsing them reports a collision - * that does not exist. Also a contract, not an implementation detail. - */ -const UNREADABLE_WIDGET_NAME_ERROR_TYPE = 'widget_unreadable_name_refused' - -/** - * Stable `errorType` for an ambiguous pair the node **keeps**: the rename did - * not take, but `name` is writable, so the failure is a store refusal that a - * later commit can still resolve rather than a widget that can never be - * addressed. Removing it would cost the user a widget to repair a transient - * state, so it is reported and left in place. - * - * Distinct from {@link DUPLICATE_WIDGET_NAME_ERROR_TYPE} precisely because the - * widget is still on the node: an alert on this one is not a report of lost - * widgets. Also a contract, not an implementation detail. - */ -const UNRESOLVED_WIDGET_NAME_ERROR_TYPE = 'widget_duplicate_name_unresolved' - -/** - * Stable `errorType` for a refused widget whose own teardown threw, which - * leaves its release half-done. Also a contract, not an implementation detail. - */ -const REFUSED_WIDGET_TEARDOWN_ERROR_TYPE = 'widget_refusal_teardown_failed' +const REFUSAL_TEARDOWN_ERROR_TYPE = 'failure_tearing_down_refused_widget' interface WidgetsViewState { target: IBaseWidget[] @@ -101,7 +70,7 @@ function safeRead(read: () => unknown): string | undefined { /** Reports a teardown step that failed, so a half-done release is visible. */ function reportTeardownFailure(node: LGraphNode, error: unknown): void { reportError(error, { - errorType: REFUSED_WIDGET_TEARDOWN_ERROR_TYPE, + errorType: REFUSAL_TEARDOWN_ERROR_TYPE, surface: 'graph', level: 'warning', tags: { node_type: node.type }, @@ -191,9 +160,10 @@ function releaseRefusedWidget( /** * Enforces the unique-name invariant where `node.widgets` is committed: the * array is a mutation view, so `addWidget`, a raw `widgets.push`, a splice and - * a whole-array assignment all pass through here. A widget refused here is - * never registered with the store and never rendered, because it is off the - * node before either happens. + * a whole-array assignment all pass through here. A widget removed here is off + * the node before it can be rendered, and its own entry is released — it may + * already have one, from a name it held before an extension pinned it onto + * another widget's. * * `SubgraphNode` does **not** commit through here and keeps the pre-existing * behaviour: it redefines `widgets` as a computed getter over its promoted @@ -276,17 +246,17 @@ const REFUSAL_ALERTS: Record< // Deliberately not "the accessor threw": a name that will not coerce or will // not percent-encode reads perfectly and still yields no id. 'unreadable-name': { - errorType: UNREADABLE_WIDGET_NAME_ERROR_TYPE, + errorType: 'failure_reading_widget_name', message: (nodeId) => `Refused a widget on node ${nodeId}: no widget identity can be derived from its name` }, 'unresolved-duplicate': { - errorType: UNRESOLVED_WIDGET_NAME_ERROR_TYPE, + errorType: 'failure_resolving_widget_duplicate_name', message: (nodeId, name) => `Kept a widget named "${name}" that node ${nodeId} already has under that name: the rename was declined rather than impossible, so the widget is left in place and the pair is unresolved for now` }, 'duplicate-name': { - errorType: DUPLICATE_WIDGET_NAME_ERROR_TYPE, + errorType: 'failure_renaming_widget_duplicate_name', message: (nodeId, name) => `Refused a widget named "${name}": node ${nodeId} already has a widget of that name and the duplicate cannot be renamed` } @@ -346,9 +316,9 @@ export function wasWidgetRefused( * * Only for a node whose widgets list this module owns. `SubgraphNode`'s getter * rebuilds the array on every read, so a refusal there splices a throwaway copy - * and nothing leaves the node — while the caller still reports - * `widget_duplicate_name_refused` and tears down the slot back-references of a - * widget that is still there. Two promoted inputs carrying the same inner + * and nothing leaves the node — while the caller still reports a + * refusal and tears down the slot back-references of a widget that is still + * there. Two promoted inputs carrying the same inner * widget name reach exactly that state, so the guard is load-bearing rather * than defensive. */ diff --git a/src/lib/litegraph/src/node/widgetsView.uniqueWidgetName.test.ts b/src/lib/litegraph/src/node/widgetsView.uniqueWidgetName.test.ts index f0c21c78203..28670031586 100644 --- a/src/lib/litegraph/src/node/widgetsView.uniqueWidgetName.test.ts +++ b/src/lib/litegraph/src/node/widgetsView.uniqueWidgetName.test.ts @@ -94,7 +94,7 @@ describe('unique widget name invariant', () => { expect(reportError).toHaveBeenCalledExactlyOnceWith( expect.any(Error), expect.objectContaining({ - errorType: 'widget_duplicate_name_refused', + errorType: 'failure_renaming_widget_duplicate_name', surface: 'graph' }) ) @@ -273,7 +273,7 @@ describe('unique widget name invariant', () => { expect(reportError).toHaveBeenCalledExactlyOnceWith( expect.any(Error), expect.objectContaining({ - errorType: 'widget_unreadable_name_refused', + errorType: 'failure_reading_widget_name', context: expect.objectContaining({ widgetName: undefined }) }) ) @@ -310,7 +310,7 @@ describe('unique widget name invariant', () => { expect(reportError).toHaveBeenCalledExactlyOnceWith( expect.any(Error), expect.objectContaining({ - errorType: 'widget_unreadable_name_refused' + errorType: 'failure_reading_widget_name' }) ) }) @@ -339,7 +339,7 @@ describe('unique widget name invariant', () => { expect(reportError).toHaveBeenCalledExactlyOnceWith( expect.any(Error), expect.objectContaining({ - errorType: 'widget_unreadable_name_refused' + errorType: 'failure_reading_widget_name' }) ) }) @@ -458,8 +458,8 @@ describe('unique widget name invariant', () => { expect( vi.mocked(reportError).mock.calls.map(([, options]) => options.errorType) ).toEqual([ - 'widget_refusal_teardown_failed', - 'widget_duplicate_name_refused' + 'failure_tearing_down_refused_widget', + 'failure_renaming_widget_duplicate_name' ]) }) @@ -540,7 +540,7 @@ describe('unique widget name invariant', () => { expect(reportError).toHaveBeenCalledExactlyOnceWith( expect.any(Error), expect.objectContaining({ - errorType: 'widget_duplicate_name_unresolved', + errorType: 'failure_resolving_widget_duplicate_name', context: expect.objectContaining({ widgetName: 'seed' }) }) ) @@ -573,7 +573,7 @@ describe('unique widget name invariant', () => { it('does not report a refusal it cannot carry out on a subgraph node', () => { // A `SubgraphNode` rebuilds `widgets` on every read, so nothing this // module splices ever leaves the node. Enforcing there anyway reports the - // alerting contract `widget_duplicate_name_refused` for a refusal that did + // alerting contract `failure_renaming_widget_duplicate_name` for a refusal that did // not happen — and promoted projections have a getter-only `name`, so a // node promoting the same inner widget name twice hits it on every add. const subgraph = createTestSubgraph({ diff --git a/src/types/widgetId.ts b/src/types/widgetId.ts index 71fa25b7564..142f9ec6660 100644 --- a/src/types/widgetId.ts +++ b/src/types/widgetId.ts @@ -259,12 +259,11 @@ function freeSuffixedName( /** * How many distinct names a colliding widget is offered before it is refused. * - * One attempt is not enough: a `name` setter can reject one target and accept - * another. `BaseWidget`'s delegates to `widgetValueStore.renameWidget`, which - * refuses to move onto an id the store already holds — so a stale entry under - * `seed#1` makes a perfectly renamable widget look unrenamable. Refusal - * deletes the widget, so it has to be the answer to "no name works", not to - * "the first name I tried did not". + * One attempt is not enough: `BaseWidget`'s `name` setter declines a move onto + * an id the store already holds, so one stale entry can reject a candidate a + * widget would otherwise take. Whether the widget is *removed* does not rest on + * this ({@link nameIsWritable} decides that), but whether the pair is reported + * as unresolved does. */ const RENAME_ATTEMPTS = 4 From 18db247ada21e0641026a3054d2976a88d5a79d2 Mon Sep 17 00:00:00 2001 From: GitHub Action Date: Sun, 4 Oct 2026 22:26:34 +0000 Subject: [PATCH 20/35] [automated] Apply ESLint and Oxfmt fixes --- .../litegraph/src/node/widgetsView.refusalCriterion.test.ts | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/lib/litegraph/src/node/widgetsView.refusalCriterion.test.ts b/src/lib/litegraph/src/node/widgetsView.refusalCriterion.test.ts index 845757cd813..326efccc7cf 100644 --- a/src/lib/litegraph/src/node/widgetsView.refusalCriterion.test.ts +++ b/src/lib/litegraph/src/node/widgetsView.refusalCriterion.test.ts @@ -71,7 +71,9 @@ describe('unique-name refusal criterion', () => { // It is still reported, so the pair is observable rather than tolerated in // silence — under its own `errorType`, because nothing was lost. expect(reportedTypes()).toEqual(['failure_resolving_widget_duplicate_name']) - expect(reportedTypes()).not.toContain('failure_renaming_widget_duplicate_name') + expect(reportedTypes()).not.toContain( + 'failure_renaming_widget_duplicate_name' + ) // Keeping the pair must not be paid for with a *value* either, which the // widget array's length cannot show. An ambiguous pair registers neither From 3a2aef40116bcb8295dbe10112f731c3f6cc5841 Mon Sep 17 00:00:00 2001 From: Christian Byrne Date: Sun, 4 Oct 2026 15:54:24 -0700 Subject: [PATCH 21/35] fix(widgets): let a detached rename land when the store holds no entry Round-2 review found that the kept-duplicate path traded one failure for a worse one. `_state.nodeId` outlives `graph.remove`, which deletes the node's store entries, so a rename while detached asked the store to move an entry that was no longer there, the setter declined, and the pair stayed ambiguous on re-add. `ensureUniqueWidgetNames` then returns false for the node, which bails `setNodeId` for *every* widget on it: the node renders no widgets at all, which is the state this PR exists to fix, reached through undo and paste. Measured before: `['seed', 'seed', 'gamma']`, nothing registered for the node, all three ids undefined, and a later `addWidget` does not repair it. After: `['seed', 'seed#1', 'gamma']`, all three registered, values 1, 2 and 3 independent. When no entry answers to the old name there is nothing to keep consistent, so the write is local and the ownership guard keeps its own branch: a rename still never moves an entry this widget is not bound to. The three `refusalCriterion` cases that asserted the ambiguous outcome now assert the resolved one, and the unresolved-report case builds its pair from a setter that accepts a write and ignores it, which is the way that path is still reachable. The kept-duplicate spec now counts widget rows after the re-add, which is the level that can see this at all. --- .../renamableDuplicateWidgetKept.spec.ts | 8 ++ .../node/widgetsView.refusalCriterion.test.ts | 108 +++++++++--------- src/lib/litegraph/src/widgets/BaseWidget.ts | 30 ++--- 3 files changed, 78 insertions(+), 68 deletions(-) diff --git a/browser_tests/tests/widgets/renamableDuplicateWidgetKept.spec.ts b/browser_tests/tests/widgets/renamableDuplicateWidgetKept.spec.ts index e9aa3bfbbd8..1ccd0f850d8 100644 --- a/browser_tests/tests/widgets/renamableDuplicateWidgetKept.spec.ts +++ b/browser_tests/tests/widgets/renamableDuplicateWidgetKept.spec.ts @@ -120,6 +120,14 @@ test.describe( await collideNameWhileDetached(comfyPage, nodeId) + await test.step('both widgets are still drawn after the re-add', async () => { + // An unresolved pair makes `ensureUniqueWidgetNames` false, which bails + // registration for every widget on the node, so the node draws nothing. + // The saved values below cannot see that: they come from the widget + // objects, which survive it. + await expect(node.getByTestId(TestIds.widgets.widget)).toHaveCount(2) + }) + await test.step('and the node still saves both widget slots', async () => { const savedRequest = comfyPage.page.waitForRequest( (request) => diff --git a/src/lib/litegraph/src/node/widgetsView.refusalCriterion.test.ts b/src/lib/litegraph/src/node/widgetsView.refusalCriterion.test.ts index 326efccc7cf..b4a6d742226 100644 --- a/src/lib/litegraph/src/node/widgetsView.refusalCriterion.test.ts +++ b/src/lib/litegraph/src/node/widgetsView.refusalCriterion.test.ts @@ -16,9 +16,9 @@ vi.mock(import('@/platform/telemetry/reportError')) * - **the descriptor** — remove only when `name` could not be written at all. * * `BaseWidget.set name` delegates to `widgetValueStore.renameWidget()` and - * returns without changing `_name` whenever the store declines, which it does - * when the node has no entries. So the read-back reports failure for an - * ordinary, fully renamable widget, and removing on it destroys that widget. + * returns without changing `_name` whenever the store declines a move it owns. + * So the read-back can report failure for a widget that is addressable in + * principle, and removing on it destroys that widget. */ function reportedTypes(): (string | undefined)[] { return vi @@ -26,60 +26,54 @@ function reportedTypes(): (string | undefined)[] { .mock.calls.map((call) => call[1].errorType as string | undefined) } +function names(node: LGraphNode): string[] { + return (node.widgets ?? []).map((widget) => widget.name) +} + +function storedNames(graph: LGraph, node: LGraphNode): string[] { + return useWidgetValueStore() + .getNodeWidgets(graph.id, node.id) + .map((widget) => widget.name) +} + describe('unique-name refusal criterion', () => { beforeEach(() => { LiteGraph.vueNodesMode = false vi.mocked(reportError).mockClear() }) - it('keeps an ordinary renamable duplicate on a node that was removed and re-added', () => { + it('resolves an ordinary renamable duplicate on a node that was removed and re-added', () => { const graph = new LGraph() const node = new LGraphNode('test') graph.add(node) const seed = node.addWidget('number', 'seed', 1, () => undefined, {}) const steps = node.addWidget('number', 'steps', 2, () => undefined, {}) - // Both registered, so each widget's `_state` is the store's object and - // carries `nodeId`. - expect( - useWidgetValueStore() - .getNodeWidgets(graph.id, node.id) - .map((widget) => widget.name) - ).toEqual(['seed', 'steps']) - - // Node removal runs `clearNodeOwnedStoreState`, deleting the store - // entries. Nothing resets `_state.nodeId` on the widgets, so the next - // rename attempt asks the store to move an entry that is no longer there. + expect(storedNames(graph, node)).toEqual(['seed', 'steps']) + + // Node removal deletes the store entries and leaves `_state.nodeId` set, so + // the next rename asks the store to move an entry that is no longer there. graph.remove(node) - // Off-graph, so `BaseWidget.set name` takes its `!graphId` path and the - // write lands. This is an ordinary duplicate-name state, reachable by an - // extension renaming a widget while the node is detached. + // Reachable by an extension renaming a widget while the node is detached. steps.name = 'seed' expect(steps.name).toBe('seed') - // Re-adding commits `node.widgets`, which runs the refusal walk. Undoing a - // node deletion and pasting a cut node both land here. + // Undoing a node deletion and pasting a cut node both land here. graph.add(node) - // The invariant must not pay for itself with a widget. Both are writable, - // so neither is unaddressable and neither may be removed. + // The invariant must not pay for itself with a widget, and it must not pay + // with the node's registration either: a pair that stays ambiguous makes + // `ensureUniqueWidgetNames` false, which bails `setNodeId` for *every* + // widget on the node and renders none of them. expect(node.widgets).toContain(seed) expect(node.widgets).toContain(steps) - expect(node.widgets).toHaveLength(2) + expect(names(node)).toEqual(['seed', 'seed#1']) + expect(storedNames(graph, node)).toEqual(['seed', 'seed#1']) + expect(reportedTypes()).toEqual([]) - // It is still reported, so the pair is observable rather than tolerated in - // silence — under its own `errorType`, because nothing was lost. - expect(reportedTypes()).toEqual(['failure_resolving_widget_duplicate_name']) - expect(reportedTypes()).not.toContain( - 'failure_renaming_widget_duplicate_name' - ) - - // Keeping the pair must not be paid for with a *value* either, which the - // widget array's length cannot show. An ambiguous pair registers neither - // widget, so each keeps its own state and the two stay independent — - // rather than both resolving to one store entry under the shared name. - expect(useWidgetValueStore().getNodeWidgets(graph.id, node.id)).toEqual([]) + // Two entries, so the two values stay independent rather than resolving to + // one entry under the shared name. expect(seed.value).toBe(1) expect(steps.value).toBe(2) @@ -100,21 +94,17 @@ describe('unique-name refusal criterion', () => { steps.name = 'seed' graph.add(node) - // `steps` claims `graphId:nodeId:seed` because identity is derived from the - // name it now shares. That id is `seed`'s to hold, so a rename of `steps` - // must not move it: being handed that entry is what welded the pair onto - // one `WidgetState` and destroyed the second value. + // While the names collided, `steps` claimed `graphId:nodeId:seed` because + // identity is derived from the name it then shared. That id is `seed`'s to + // hold: being handed that entry is what welded the pair onto one + // `WidgetState` and destroyed the second value. const store = useWidgetValueStore() - expect(store.getNodeWidgets(graph.id, node.id)).toEqual([]) - - // The write is declined rather than silently redirected, so the name the - // walk could not resolve is still ambiguous and still reported as such. - steps.name = 'seed#1' - expect( - store.getWidget(widgetId(graph.id, node.id, 'seed#1')) - ).toBeUndefined() - expect(seed.value).toBe(1) - expect(steps.value).toBe(2) + expect(store.getWidget(widgetId(graph.id, node.id, 'seed'))?.value).toBe(1) + expect(seed.widgetId).toBe(widgetId(graph.id, node.id, 'seed')) + expect(steps.widgetId).toBe(widgetId(graph.id, node.id, 'seed#1')) + expect(store.getWidget(widgetId(graph.id, node.id, 'seed#1'))?.value).toBe( + 2 + ) }) it('does not let a duplicate rename steal the entry of a widget on another node', () => { @@ -163,19 +153,27 @@ describe('unique-name refusal criterion', () => { node.addWidget('number', 'seed', 1, () => undefined, {}) const steps = node.addWidget('number', 'steps', 2, () => undefined, {}) - graph.remove(node) - steps.name = 'seed' - graph.add(node) + // A setter that accepts every write and keeps the old name. It is writable, + // so the widget is addressable in principle and must not be removed, and no + // candidate the walk offers can ever stick. + Object.defineProperty(steps, 'name', { + get: () => 'seed', + set: () => undefined, + configurable: true + }) + + node.addWidget('number', 'cfg', 3, () => undefined, {}) + expect(node.widgets).toContain(steps) expect(reportedTypes()).toEqual(['failure_resolving_widget_duplicate_name']) // A kept pair is re-found by every later commit, and `reportError` has no - // dedupe of its own — each call builds an `Error` with a stack and + // dedupe of its own: each call builds an `Error` with a stack and // dispatches to Sentry and Datadog. An unresolvable pair would otherwise // emit an identical warning for the rest of the session. - node.addWidget('number', 'cfg', 3, () => undefined, {}) + node.addWidget('number', 'denoise', 4, () => undefined, {}) node.widgets?.push( - node.addWidget('number', 'denoise', 4, () => undefined, {}) + node.addWidget('number', 'guidance', 5, () => undefined, {}) ) expect(reportedTypes()).toEqual(['failure_resolving_widget_duplicate_name']) diff --git a/src/lib/litegraph/src/widgets/BaseWidget.ts b/src/lib/litegraph/src/widgets/BaseWidget.ts index 292c544cf9b..18358b8efcb 100644 --- a/src/lib/litegraph/src/widgets/BaseWidget.ts +++ b/src/lib/litegraph/src/widgets/BaseWidget.ts @@ -145,20 +145,24 @@ export abstract class BaseWidget const store = useWidgetValueStore() const previousId = widgetId(graphId, nodeId, previous) - // A `WidgetId` is `graphId:nodeId:name`, so two widgets that share a name - // on one node claim the same id — and `previousId` then names whichever of - // them actually registered it, which need not be this one. Moving an entry - // this widget is not bound to would hand it the other widget's state: the - // rename reads back as success, `_state` is reassigned to that object, and - // the pair is welded onto one `WidgetState` with one value between them. - // - // Only this widget's own entry is this widget's to move. When the id holds - // someone else's, the rename is declined exactly as it is when the store - // has no entry at all — the caller's read-back reports the failure, and - // `ensureUniqueWidgetNames` turns that into a refusal to register rather - // than a colliding id. const registered = store.getWidget(previousId) - if (registered && registered !== this._state) return + + // Nothing in the store answers to the old name, so there is nothing to keep + // consistent and the write is this widget's own business. `_state.nodeId` + // outlives `graph.remove`, which clears the node's entries, so declining + // here left a re-added node holding two widgets under one name: every + // `setNodeId` on it then bails on `ensureUniqueWidgetNames` and the node + // registers — and renders — no widgets at all. + if (!registered) { + this._name = value + return + } + + // `previousId` names whichever widget actually registered it, which need + // not be this one when two share a name. Moving an entry this widget is not + // bound to welds the pair onto one `WidgetState` with one value between + // them, and the rename still reads back as success. + if (registered !== this._state) return const moved = store.renameWidget( previousId, From 7ba0a367d10820a19962b1bf75dee9039839f307 Mon Sep 17 00:00:00 2001 From: Christian Byrne Date: Sun, 4 Oct 2026 16:01:13 -0700 Subject: [PATCH 22/35] docs(widgets): cut the comments that restate the code MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The review flagged 92 comment blocks in round 1 and raised them again in round 2: `AGENTS.md` asks for code that reads without them, and the ADR is where the reasoning belongs. This takes the production files, where a reader of the diff spends their time. What stays: the non-obvious constraints a reader cannot recover from the code — why the walk splices this module's own array rather than `node.widgets`, why renamability is judged after normalization, why the conversion verdict is taken before the catch, why membership is a set, and the ADR pointers. What goes: narration of the next line, restatements of function names, review history, and the duplicated `SubgraphNode` explanation. 255 lines out, 100 in, no behaviour change: the same suites pass and every mutation row still lands where it did. --- .../graph/nodeShell/nodeShellLifecycle.ts | 6 +- src/lib/litegraph/src/LGraphNode.ts | 8 +- src/lib/litegraph/src/node/widgetsView.ts | 154 +++++---------- src/scripts/domWidget.ts | 10 +- src/types/widgetId.ts | 179 +++++------------- 5 files changed, 101 insertions(+), 256 deletions(-) diff --git a/src/core/graph/nodeShell/nodeShellLifecycle.ts b/src/core/graph/nodeShell/nodeShellLifecycle.ts index a59f1f2c1dd..cd6c52cfa3f 100644 --- a/src/core/graph/nodeShell/nodeShellLifecycle.ts +++ b/src/core/graph/nodeShell/nodeShellLifecycle.ts @@ -31,10 +31,8 @@ export function attachNodeToStores( } if (!node.widgets) return - // Two widgets on one node cannot share a name (ADR-ECS-0008), and this is - // the first moment a `WidgetId` exists to collide over: the node now has a - // graph and its final id. Registering an ambiguous pair would bind both to - // one store entry, and `setNodeId` would in fact register neither. + // The node now has a graph and its final id, so this is the first moment a + // `WidgetId` exists to collide over (ADR-ECS-0008). refuseAmbiguousNodeWidgets(node) for (const widget of node.widgets) { if (isNodeBindable(widget)) widget.setNodeId(node.id) diff --git a/src/lib/litegraph/src/LGraphNode.ts b/src/lib/litegraph/src/LGraphNode.ts index 90f8696c54e..f84221f8270 100644 --- a/src/lib/litegraph/src/LGraphNode.ts +++ b/src/lib/litegraph/src/LGraphNode.ts @@ -2309,11 +2309,9 @@ export class LGraphNode const widget = toConcreteWidget(custom_widget, this) this.widgets.push(widget) - // Two widgets on one node cannot share a name (ADR-ECS-0008). The push - // above commits through the widgets view, which refuses a duplicate it - // cannot rename apart and reports it. Registering or restoring a widget - // that is no longer on the node would write over the widget that kept the - // name, so stop here and hand the caller back the detached widget. + // The push committed through the widgets view, which may have refused the + // widget (ADR-ECS-0008). Registering one the node no longer has would write + // over the widget that kept the name. if (!this.widgets.includes(widget)) return widget // Only register with store if node has a valid ID (is already in a graph). diff --git a/src/lib/litegraph/src/node/widgetsView.ts b/src/lib/litegraph/src/node/widgetsView.ts index 2c25cd18eac..8e8c3182f99 100644 --- a/src/lib/litegraph/src/node/widgetsView.ts +++ b/src/lib/litegraph/src/node/widgetsView.ts @@ -33,19 +33,10 @@ interface WidgetsViewState { const EMPTY_REFUSAL: ReadonlySet = new Set() /** - * The unresolved names already reported for a node, so a pair that no later - * commit can resolve is alerted on once instead of on every commit. - * - * An unresolved pair — unlike the two removing causes — survives the walk, so - * every subsequent `syncWidgetOrder` (`push`, `splice`, a reorder, each - * `addWidget`) and every `attachNodeToStores` finds it again. `reportError` - * builds an `Error` with a stack and dispatches to Sentry and Datadog with no - * dedupe or throttle of its own, so reporting per pass is an unbounded stream - * of identical warnings for as long as the session lasts. The removing causes - * self-clear after one report because the widget is gone, and are not tracked. - * - * Replaced rather than added to on each pass: a name that stops being - * ambiguous and later collides again is a new event and is reported again. + * The unresolved names already reported for a node. A kept pair survives the + * walk, so every later commit finds it again and `reportError` has no dedupe + * of its own. Replaced rather than added to, so a name that stops colliding + * and later collides again is reported again. */ const reportedUnresolvedNames = new WeakMap>() @@ -53,10 +44,8 @@ const states = new WeakMap() const widgetsViewGetters = new WeakSet<() => IBaseWidget[] | undefined>() /** - * Reads a property off a widget that is being refused. The widget reached that - * state because an accessor misbehaved, so every read here is hostile: a - * `name` getter that throws would escape `syncWidgetOrder` after the array has - * already been spliced, leaving the node and the store's order out of sync. + * Reads a property off a widget being refused. Every read here is hostile by + * definition, and a throw would escape after the array was spliced. */ function safeRead(read: () => unknown): string | undefined { try { @@ -79,13 +68,9 @@ function reportTeardownFailure(node: LGraphNode, error: unknown): void { } /** - * Whether {@link input} is bound to the widget being released. - * - * Two bindings, because production uses both: `_widget` holds a direct - * reference (promoted subgraph inputs), while an ordinary node binds its widget - * inputs by name and resolves them on read. Matching only the reference finds - * nothing on the nodes this refusal actually runs for, and the slot then - * re-binds to whichever widget kept the name. + * Two bindings, because production uses both: promoted subgraph inputs hold a + * direct `_widget` reference, and an ordinary node binds by name and resolves + * on read. Matching only the reference finds nothing on these nodes. */ function inputBindsWidget( input: LGraphNode['inputs'][number], @@ -111,27 +96,16 @@ function clearRefusedSlotBindings( } /** - * Releases a widget the node has just refused. It is already off the array, so - * `LGraphNode.removeWidget` can no longer find it and the teardown that method - * owns has to happen here: slot back-references would otherwise keep pointing - * at a widget the node no longer has. - * - * Both steps are guarded and reported rather than thrown. This runs after the - * array has been spliced, so a throw escaping here would leave the node and the - * store's order out of sync — and during `LGraph.add`, a half-attached node. - * - * The widget's store entry is deliberately *not* deleted. A refused widget's - * name is by definition the one another widget kept, so `widget.widgetId` now - * resolves to that widget's entry — deleting it would destroy the value of the - * widget this invariant exists to protect. + * The teardown `LGraphNode.removeWidget` owes a widget it can no longer find, + * because the refusal already took it off the array. Every step is guarded: a + * throw here would leave the node and the store's order out of sync, and during + * `LGraph.add` a half-attached node. */ function releaseRefusedWidget( node: LGraphNode, - // Typed to admit the nullish case the type system says cannot happen: a hole - // or an explicit `undefined` in `node.widgets` reaches the walk as an - // unreadable name and is refused like anything else. Matching the teardown on - // it would clear every input whose `_widget` is still unset, which is nearly - // all of them. + // Nullish because a hole or an explicit `undefined` in `node.widgets` is + // refused like anything else, and matching the teardown on it would clear + // every input whose `_widget` is unset. widget: IBaseWidget | undefined, name: string | undefined ): void { @@ -182,14 +156,11 @@ function refuseAmbiguousWidgets( const alreadyReported = takeUnresolvedReportGate(node, refused) for (const finding of refused) { - // An unresolved pair this node has already been alerted on is not a new - // event. Skipping before the teardown below would be wrong for any other - // cause, but an unresolved duplicate is never released, so there is - // nothing here to skip past. + // Safe to skip before the teardown below only because a kept pair is + // never released. if (alreadyReported(finding)) continue - // Only a widget the walk took off the array needs releasing; an unresolved - // duplicate is still the node's widget and must keep its slot wiring. + // A kept duplicate is still the node's widget and keeps its slot wiring. if (finding.removed) { releaseRefusedWidget(node, finding.widget, finding.name) } @@ -201,13 +172,7 @@ function refuseAmbiguousWidgets( ) } -/** - * Records which names are unresolved on {@link node} now, and returns the - * predicate for "already alerted on before this pass". - * - * Replaces the record rather than adding to it, so a name that stops being - * ambiguous and later collides again is reported again. - */ +/** @returns whether a finding was already alerted on before this pass. */ function takeUnresolvedReportGate( node: LGraphNode, refused: readonly RefusedWidget[] @@ -226,15 +191,8 @@ function takeUnresolvedReportGate( } /** - * The alert for one finding. The three causes are different failures and are - * alerted on separately: an unreadable name has no duplicate at all, so - * reporting one would send whoever reads the alert looking for a collision that - * does not exist, and an unresolved pair is still on the node rather than lost. - * - * `cause` and `name` come from the walk, never from another read of the - * accessor. It is hostile by definition, it need not answer twice the same way, - * and the walk may have written to it up to four times before giving up — so a - * re-read can name a candidate no widget holds. + * One alert per cause, because they are different failures: an unreadable name + * has no duplicate to go looking for, and a kept pair has lost nothing. */ const REFUSAL_ALERTS: Record< RefusedWidget['cause'], @@ -243,8 +201,6 @@ const REFUSAL_ALERTS: Record< message: (nodeId: LGraphNode['id'], name: string | undefined) => string } > = { - // Deliberately not "the accessor threw": a name that will not coerce or will - // not percent-encode reads perfectly and still yields no id. 'unreadable-name': { errorType: 'failure_reading_widget_name', message: (nodeId) => @@ -281,13 +237,9 @@ function reportRefusal( } /** - * Whether {@link node} still exposes the mutation view this module installed, - * and so is subject to the unique-name invariant at all. - * - * `SubgraphNode` replaces `widgets` with its own computed getter over promoted - * widgets, which never commits through here. Distinguishing the two matters to - * callers that infer refusal from a widget's absence: on a promoted list the - * object handed in is not the object read back, so absence means nothing. + * Whether {@link node} still exposes this module's mutation view, and so is + * subject to the invariant at all. `SubgraphNode` rebuilds `widgets` on every + * read, so on a promoted list a widget's absence means nothing. */ function commitsThroughWidgetsView(node: LGraphNode): boolean { const descriptor = Object.getOwnPropertyDescriptor(node, 'widgets') @@ -306,21 +258,14 @@ export function wasWidgetRefused( } /** - * Enforces the invariant for a node that is joining a graph. - * - * `LGraph.add` normalizes the widgets view while `node.graph` is still unset, - * so that commit cannot mint a `WidgetId` and deliberately does not enforce. - * This runs where identities actually come into existence — immediately before - * the node's widgets are registered — which is the first point at which an - * ambiguous pair can do any harm. + * The second enforcement point: a node joining a graph. `LGraph.add` normalizes + * the view while `node.graph` is unset, so that commit mints no `WidgetId` and + * does not enforce. * - * Only for a node whose widgets list this module owns. `SubgraphNode`'s getter - * rebuilds the array on every read, so a refusal there splices a throwaway copy - * and nothing leaves the node — while the caller still reports a - * refusal and tears down the slot back-references of a widget that is still - * there. Two promoted inputs carrying the same inner - * widget name reach exactly that state, so the guard is load-bearing rather - * than defensive. + * Gated on the node still owning its widgets list, because a refusal on + * `SubgraphNode`'s rebuilt array splices a throwaway copy while still reporting + * and tearing down a widget that is still there. Two promoted inputs sharing an + * inner widget name reach that state. */ export function refuseAmbiguousNodeWidgets(node: LGraphNode): void { if (!commitsThroughWidgetsView(node)) return @@ -337,15 +282,13 @@ function syncWidgetOrder(node: LGraphNode, widgets: IBaseWidget[]): void { node._widgetSlotsDirty = true const graphId = node.graph?.rootGraph.id - // `BaseWidget`'s constructor reads the source object's `name`, so converting - // a raw push whose accessor throws throws out of this commit — and out of - // every later one, wedging the node with a stale store order. That is the - // exact state `UNREADABLE_NAME` exists to contain, so leave the object - // unconverted and let the refusal below take it. + // `BaseWidget`'s constructor reads the source object's `name`, so a raw push + // whose accessor throws would throw out of this commit and every later one, + // wedging the node with a stale store order. Leave it unconverted for the + // refusal below instead. const concreteWidgets = widgets.map((widget) => { - // Decided before the conversion, not inside the catch. Probing the - // accessor after it has already thrown asks a hostile getter the same - // question twice and acts on whichever answer comes back second. + // Before the conversion, not inside the catch: a hostile getter asked + // twice can answer differently. const unreadable = isWidgetNameUnreadable(widget) try { return toConcreteWidget(widget, node) @@ -365,25 +308,18 @@ function syncWidgetOrder(node: LGraphNode, widgets: IBaseWidget[]): void { widgets[index] = widget } - // Nothing is registered until the node is in a graph, so there is no - // identity to collide over yet — and renaming earlier than the store needs - // it changes names that node construction still matches on. Enforcement - // belongs at the first commit that can actually mint a `WidgetId`. + // No graph, no identity to collide over yet — and renaming earlier changes + // names that node construction still matches on. if (!graphId) return - // After normalization, not before: `toConcreteWidget` merges the concrete - // class's writable `name` accessor over a plain object's pinned one, so a - // widget judged unrenamable while still raw would be destroyed even though - // it renames cleanly a line later. + // After normalization: `toConcreteWidget` merges the class's writable `name` + // accessor over a plain object's pinned one, so a widget judged unrenamable + // while still raw renames cleanly a line later. const refused = refuseAmbiguousWidgets(node, widgets) for (const widget of concreteWidgets) { - // Membership by set, not by `widgets.includes`: this loop runs on every - // commit and `node.widgets` commits once per `addWidget`, so a linear scan - // here is quadratic per commit and cubic over building a node. - // - // A widget that would not convert is still raw and so not bindable; it has - // also just been refused, so it is no longer on the node either. + // By set, not `widgets.includes`: this runs on every commit, so a linear + // scan here is cubic over building a node. if (!refused.has(widget) && isNodeBindable(widget)) { widget.setNodeId(node.id) } diff --git a/src/scripts/domWidget.ts b/src/scripts/domWidget.ts index b7394846136..de4463cf3f6 100644 --- a/src/scripts/domWidget.ts +++ b/src/scripts/domWidget.ts @@ -330,10 +330,8 @@ export class ComponentWidgetImpl< export const addWidget = (node: LGraphNode, widget: BaseDOMWidget) => { node.addCustomWidget(widget) - // A duplicate name the node could not rename apart is refused and spliced - // straight back out (ADR-ECS-0008). Registering it anyway would mount its - // element over the canvas for a widget the graph does not have, and nothing - // would unmount it until the node itself is removed. + // Registering a refused widget mounts its element over the canvas for a + // widget the graph does not have, and nothing unmounts it. if (wasWidgetRefused(node, widget)) return if (node.graph) { @@ -341,8 +339,8 @@ export const addWidget = (node: LGraphNode, widget: BaseDOMWidget) => { } node.onAdded = useChainCallback(node.onAdded, () => { - // Joining a graph is the first commit that can refuse a duplicate name, - // so a widget accepted above may not have survived it. + // The join is the first commit that can refuse, so a widget accepted + // above may not have survived it. if (wasWidgetRefused(node, widget)) return useDomWidgetStore().registerWidget(widget) }) diff --git a/src/types/widgetId.ts b/src/types/widgetId.ts index 142f9ec6660..fd4d165e351 100644 --- a/src/types/widgetId.ts +++ b/src/types/widgetId.ts @@ -25,27 +25,17 @@ export function widgetId( } /** - * Whether `name` can be written on {@link widget} at all — a structural - * property of the object, not of whether a particular write landed. - * - * This is the criterion {@link ensureUniqueWidgetNames} uses to decide whether - * it may rename at all, and it is deliberately the same one - * {@link dropUnrenamableDuplicateWidgets} uses to decide whether a rename that - * failed is fatal. The two must agree: `setNodeId` gates registration on - * `ensureUniqueWidgetNames`, so a walk that removed a widget this predicate - * calls renamable would be destroying widgets over a disagreement between two - * copies of one rule. + * Whether `name` can be written on {@link widget} at all: a structural property + * of the object, not of whether a particular write landed. Both the rename gate + * and the removal criterion read it, deliberately, so the two cannot disagree + * about the same widget. */ function nameIsWritable(widget: { name: string }): boolean { try { - // The whole prototype chain, not just the own object. `BaseWidget` declares - // `name` as a class accessor, so an instance has no *own* descriptor and - // every concrete widget would otherwise fall through to the - // `Object.isExtensible` branch below — which answers whether properties can - // be *added*, not whether `name` can be written. That branch happens to say - // "writable" for `BaseWidget`, so the bug hides; it says the same for a - // widget whose inherited `name` is a getter with no setter, and that one is - // genuinely unaddressable and must still be refused. + // The whole chain: `BaseWidget` declares `name` as a class accessor, so an + // instance has no own descriptor and would fall through to extensibility, + // which answers whether properties can be *added*. That reads "writable" + // for an inherited getter with no setter, which is unaddressable. for ( let target: object | null = widget; target; @@ -55,15 +45,12 @@ function nameIsWritable(widget: { name: string }): boolean { if (!descriptor) continue return 'writable' in descriptor ? !!descriptor.writable : !!descriptor.set } - // No descriptor anywhere on the chain: `name` is not defined yet, so a - // write would create it, and that is what extensibility decides. + // Nothing on the chain defines `name`, so a write would create it. return Object.isExtensible(widget) } catch { - // `getOwnPropertyDescriptor`, `getPrototypeOf` and `isExtensible` all - // invoke proxy traps, and this runs mid-walk inside `LGraph.add`. A widget - // whose traps throw cannot be addressed at all, which is precisely the case - // removal exists for — so answer "not writable" instead of letting the - // throw abort the walk with the node half-attached. + // Every call above runs a proxy trap, mid-walk inside `LGraph.add`. A + // widget whose traps throw is exactly what removal is for, so answer here + // rather than abort the walk with the node half-attached. return false } } @@ -105,19 +92,10 @@ export function ensureUniqueWidgetNames( return false } - // The write is read back, and a write that did not land makes this `false`. - // - // This is the gate `BaseWidget.setNodeId` and `BaseWidget.widgetId` bail - // on, so returning `true` over a node that still carries two widgets under - // one name is what lets a colliding `WidgetId` be minted and registered. - // `BaseWidget`'s own `name` setter declines the write whenever the store - // declines the move — which is exactly the state - // `dropUnrenamableDuplicateWidgets` leaves behind when it keeps an - // unresolved duplicate rather than deleting the user's widget — so the - // unconditional `true` reported success precisely where it was wrong. - // - // Every rename is still attempted before answering: one declined write - // must not strand the collisions that would have resolved cleanly. + // Read back, because `setNodeId` and `widgetId` bail on this answer: a + // `true` over a node that still carries one name twice is what lets a + // colliding id be registered. Every rename is attempted first, so one + // declined write does not strand the collisions that would have resolved. let unique = true for (const { widget, name } of renames) { try { @@ -157,13 +135,9 @@ type WidgetRefusalCause = | 'unresolved-duplicate' /** - * A widget the walk could not name uniquely, with the cause it was recorded - * under, whether the walk took it off the array, and the name key it read. - * - * The cause and the name both come from here rather than from another read of - * the accessor: a hostile one need not answer twice the same way, and by the - * time a caller reports the finding the walk may have written to the widget up - * to {@link RENAME_ATTEMPTS} times. + * A widget the walk could not name uniquely. The cause and the name come from + * the walk rather than from another read of the accessor: a hostile one need + * not answer twice the same way, and the walk may have written to it. */ export interface RefusedWidget { widget: T @@ -175,37 +149,21 @@ export interface RefusedWidget { } /** - * Reads `name` and derives the identity it claims, without letting a hostile - * accessor escape. - * - * Returns the **key**, not the raw value. `widgetId` keys on - * `encodeURIComponent(String(name))`, so two names that differ as values but - * coincide as strings — `undefined` against `'undefined'`, `1` against `'1'` — - * are one identity and have to collide here or they collide downstream where - * nothing is watching. + * The identity key `name` claims, or {@link UNREADABLE_NAME}. It is the key + * rather than the raw value because `widgetId` keys on + * `encodeURIComponent(String(name))`, so names that differ as values and + * coincide as strings are one identity and have to collide here. * - * All three steps are inside the guard on purpose. A getter that throws is the - * obvious case; a name that does not coerce (`Object.create(null)`) and one - * that `encodeURIComponent` rejects (a lone surrogate) are the same failure - * wearing different clothes, and letting either escape wedges this commit and - * every later one on the node. + * An empty name is deliberately readable: it mints an id the store declines to + * key on, which costs the widget nothing, and `addWidget('text', '', …)` is an + * ordinary unlabeled widget that node packs ship (ADR-ECS-0008). */ function readName(widget: { name: string }): string | typeof UNREADABLE_NAME { try { - // `name` is declared `string` and at runtime is whatever a node pack - // assigned, which is the entire reason the coercion is here. const raw: unknown = widget.name const key = String(raw) - // Mirrors `widgetId`, which encodes the **raw** value rather than the - // coerced one — a Symbol survives `String()` and then throws there. - // - // An *empty* name is deliberately not refused here. It mints - // `graphId:nodeId:`, which the store declines to key on — but declining an - // id costs the widget nothing, while refusing it deletes a widget that - // renders, fires its callback and serializes, and shifts every positional - // value after it. `addWidget('text', '', …)` is an ordinary unlabeled - // widget that node packs ship, and `emptyNameWidget.spec.ts` asserts it - // stays on the node. + // The raw value, as `widgetId` encodes it: a Symbol survives `String()` + // and throws here. encodeURIComponent(raw as string) return key } catch { @@ -224,11 +182,7 @@ function tryRename(widget: { name: string }, name: string): boolean { } } -/** - * Whether {@link widget}'s `name` cannot be read at all. Callers that report a - * refusal need this to name the cause: a widget refused for an unreadable name - * has no duplicate, so saying it has one is wrong. - */ +/** Whether no identity key can be read from {@link widget}'s `name`. */ export function isWidgetNameUnreadable(widget: { name: string }): boolean { return readName(widget) === UNREADABLE_NAME } @@ -257,13 +211,10 @@ function freeSuffixedName( } /** - * How many distinct names a colliding widget is offered before it is refused. - * - * One attempt is not enough: `BaseWidget`'s `name` setter declines a move onto - * an id the store already holds, so one stale entry can reject a candidate a - * widget would otherwise take. Whether the widget is *removed* does not rest on - * this ({@link nameIsWritable} decides that), but whether the pair is reported - * as unresolved does. + * How many names a colliding widget is offered before the pair is reported + * unresolved. More than one, because `BaseWidget`'s setter declines a move onto + * an id the store already holds, so one stale entry can reject a candidate the + * widget would otherwise take. */ const RENAME_ATTEMPTS = 4 @@ -292,21 +243,12 @@ function renameApart( } /** - * Decides what becomes of a widget whose name another widget already holds: - * renamed apart and kept, kept but reported, or refused. - * - * Renames `used`/`reserved` in place when an attempt sticks, so the caller's - * bookkeeping stays a single source of truth for both sets. + * Renamed apart and kept, kept but reported, or refused. Adds to + * `used`/`reserved` when an attempt sticks. * - * The middle outcome is the one worth reading. A rename that did not land is - * not proof of an unaddressable widget: `BaseWidget`'s own `name` setter - * delegates to `widgetValueStore.renameWidget()` and leaves the name unchanged - * whenever the store declines — which it does when the node has no entries, - * exactly the state an ambiguous pair leaves it in and the state a - * removed-and-re-added node is in before it re-registers. Refusing on the - * read-back alone therefore destroys ordinary, perfectly renamable widgets on - * the very nodes this walk repairs, so {@link nameIsWritable} decides removal - * and the unresolved pair is reported instead of paid for. + * A rename that did not land is not proof of an unaddressable widget, so + * {@link nameIsWritable} decides removal and the unresolved pair is reported + * instead (ADR-ECS-0008). */ function resolveCollision( widget: { name: string }, @@ -327,37 +269,17 @@ function resolveCollision( } /** - * Removes the widgets that cannot be given a unique name, mutating - * {@link widgets} in place, and renames the duplicates that can — keeping the - * first occurrence of each name either way. - * - * `WidgetId` is `graphId:nodeId:name`, so a second widget under a name another - * widget already holds is not a second identity — it is the same identity - * twice. ADR-ECS-0008's "Widget identity keys on `name`" records that as an - * invariant rather than a limitation to work around: - * **two widgets on one node cannot share a name.** - * - * {@link ensureUniqueWidgetNames} normally keeps that true by renaming the - * later occurrence to `name#1`. It cannot when that widget's `name` is not - * writable, or when an accessor throws — and because it is all-or-nothing, one - * such widget also leaves every *renamable* collision on the node standing. - * This walk renames those and refuses only what is genuinely unaddressable: a - * widget the store cannot tell apart silently shares another widget's value. + * Renames the duplicates it can, removes the ones it cannot address at all, + * and keeps the first occurrence of each name either way. Mutates + * {@link widgets} in place. The invariant and the remove-or-keep criterion are + * ADR-ECS-0008's, under "Widget identity keys on `name`". * - * It does its own renaming rather than delegating the happy path to - * {@link ensureUniqueWidgetNames}, which never reads the name back: a setter - * that accepts the write and ignores it satisfies that check, so delegating - * would report success over a node that still carries an ambiguous pair. The - * read-back is therefore what decides whether the pair is *reported* — - * but **not** whether the widget is removed. {@link nameIsWritable} decides - * that, because a failed write is a recoverable store refusal as often as it - * is a hostile object, and the two are indistinguishable from the read alone. + * Unlike {@link ensureUniqueWidgetNames} this reads each write back, so a + * setter that accepts and ignores it cannot report success, and a widget it + * cannot rename does not strand the collisions that would have resolved. * * @returns every widget it could not name uniquely, with the cause and whether - * it was removed, in array order. Empty when the node is unambiguous, which is - * the overwhelmingly common case. The cause is recorded here rather than - * re-derived by the caller: re-reading a hostile accessor to ask "was this one - * unreadable?" can answer differently the second time and mislabel the report. + * it was removed, in array order. */ export function dropUnrenamableDuplicateWidgets( widgets: T[] @@ -381,9 +303,6 @@ export function dropUnrenamableDuplicateWidgets( const name = readName(widget) if (name === UNREADABLE_NAME) { - // No readable name means no derivable `WidgetId`, and leaving it on the - // node makes `ensureUniqueWidgetNames` fail on every later call — which - // bails registration for every *other* widget on the node too. verdicts.set(widget, false) refused.push({ widget, @@ -407,9 +326,7 @@ export function dropUnrenamableDuplicateWidgets( verdicts.set(widget, outcome.keep) if (outcome.keep) kept.push(widget) if (outcome.cause) { - // `key` is the name the walk read before it started offering candidates. - // A re-read here can name one no widget holds: a normalising setter - // stores a transformed value, and the walk may have written four times. + // `key`, not a re-read: the walk may have written to the name since. refused.push({ widget, cause: outcome.cause, @@ -419,8 +336,6 @@ export function dropUnrenamableDuplicateWidgets( } } - // `kept` holds every widget that was not removed, in order, so this is a - // no-op rebuild when the only findings were kept ones. if (refused.length) widgets.splice(0, widgets.length, ...kept) return refused } From 460295100a929853807e6214775a8d2123ce4b1b Mon Sep 17 00:00:00 2001 From: Christian Byrne Date: Sun, 4 Oct 2026 16:17:17 -0700 Subject: [PATCH 23/35] docs(widgets): correct the ADR's cause list and trim the round-2 comments The ADR counted three `errorType`s where there are four, and said a later commit can still resolve a kept pair. Since the detached-rename fix a kept pair comes only from a setter that accepts a write and ignores it, which no later commit resolves, so the dedup gate is the reason the report is not repeated rather than an optimisation. The comments the last two commits added get the same treatment as the production files: the ones that narrated the next line are gone, and the kept-duplicate spec's header no longer describes the behaviour that fix replaced. --- .../renamableDuplicateWidgetKept.spec.ts | 62 +++++-------------- docs/adr/ECS-0008-entity-component-system.md | 19 +++--- .../node/widgetsView.refusalCriterion.test.ts | 30 +++------ 3 files changed, 35 insertions(+), 76 deletions(-) diff --git a/browser_tests/tests/widgets/renamableDuplicateWidgetKept.spec.ts b/browser_tests/tests/widgets/renamableDuplicateWidgetKept.spec.ts index 1ccd0f850d8..31171ad9286 100644 --- a/browser_tests/tests/widgets/renamableDuplicateWidgetKept.spec.ts +++ b/browser_tests/tests/widgets/renamableDuplicateWidgetKept.spec.ts @@ -9,43 +9,20 @@ import { zComfyWorkflow } from '@/platform/workflow/validation/schemas/workflowS /** * The unique-name invariant removes a widget it cannot name uniquely * (ADR-ECS-0008). This pins the boundary of "cannot": a widget whose `name` is - * perfectly writable must never be the price of enforcing it. + * writable must never be the price of enforcing it. * - * `BaseWidget.set name` delegates to `widgetValueStore.renameWidget()` and - * returns without changing the name whenever the store declines — which it does - * when the node has no entries, the state a node is in after it has been - * removed from the graph. So a rename that *failed* does not prove the widget - * is unaddressable, and removing on that signal destroys an ordinary widget. - * - * Reproduced through the graph API the way an undo of a node deletion or a - * paste of a cut node reaches it: the node leaves the graph, the duplicate name - * appears while it is detached, and it rejoins. - * - * Asserted on what the app saves, because that is where the loss is permanent. - * Measured on the parent commit the node comes back one widget short and saves - * **one** `widgets_values` entry for a two-widget node; the arity of that array - * is what positional widget addressing reads, so a dropped slot shifts every - * later widget. With the invariant's criterion corrected it saves both. - * - * The two *values* are asserted too, and that is the stronger half. Arity alone - * went green over a save this change set used to corrupt: re-registering an - * ambiguous pair routed the second widget's `name` setter through - * `renameWidget` on an id the *first* widget had registered, which handed it - * that widget's store entry — so the two widgets shared one `WidgetState`, both - * read the first value, and the second value was gone from a two-slot save. A - * widget's own entry is now the only entry its rename may move - * (`BaseWidget.set name`), so both values survive and this asserts it. + * Driven through the graph API the way an undo of a node deletion or a paste of + * a cut node reaches it, and asserted on both the rendered rows and what the + * app saves. Two values, not just two slots: an ambiguous pair used to route + * the second widget's setter onto the entry the first had registered, so both + * read one value while the slot count still looked right. */ const NODE_TYPE = 'DevToolsNodeWithOutputList' const KEPT_NAME = 'alpha' const RENAMED_NAME = 'beta' -/** - * Patches the node type so every instance carries two distinct, ordinary, - * serializable widgets. Both names are writable, so neither is ever - * unaddressable — which is the whole point. - */ +/** Two distinct, ordinary, serializable widgets, both with writable names. */ async function installTwoOrdinaryWidgets(comfyPage: ComfyPage): Promise { await comfyPage.page.evaluate( ({ nodeTypeName, first, second }) => { @@ -63,10 +40,9 @@ async function installTwoOrdinaryWidgets(comfyPage: ComfyPage): Promise { } /** - * Takes the node out of the graph, collides the second widget's name with the - * first while it is detached, and puts it back. Detached is what makes the - * write land: on a node that is still in the graph the store declines the - * rename and the collision never forms. + * Collides the second widget's name with the first while the node is detached, + * then puts it back. Detached is what lets the write land, so this is the + * sequence an undo or a paste reaches. */ async function collideNameWhileDetached( comfyPage: ComfyPage, @@ -92,8 +68,7 @@ test.describe( 'renamable duplicate widget name', { tag: ['@canvas', '@widget', '@vue-nodes'] }, () => { - // Per attempt, not per module: a module-scope stamp is shared by every - // worker in the process and by a retry. + // Per attempt: a module-scope stamp is shared by every worker and retry. let workflowName = '' test.afterEach(async ({ comfyPage }) => { @@ -121,10 +96,8 @@ test.describe( await collideNameWhileDetached(comfyPage, nodeId) await test.step('both widgets are still drawn after the re-add', async () => { - // An unresolved pair makes `ensureUniqueWidgetNames` false, which bails - // registration for every widget on the node, so the node draws nothing. - // The saved values below cannot see that: they come from the widget - // objects, which survive it. + // The saved values below cannot see this: they come from the widget + // objects, which survive a node that registers nothing. await expect(node.getByTestId(TestIds.widgets.widget)).toHaveCount(2) }) @@ -142,14 +115,11 @@ test.describe( ) const savedNode = saved.nodes.find(({ type }) => type === NODE_TYPE) - // One entry here is a widget the user lost. Two is the invariant being - // enforced without charging them for it. + // One entry here is a widget the user lost. expect(savedNode?.widgets_values).toHaveLength(2) - // And two *distinct* values, because arity alone cannot tell a - // preserved widget from one welded onto its duplicate's store entry. - // `['first default', 'first default']` is the second value destroyed - // while the slot count still looks right. + // Distinct values, because arity alone cannot tell a preserved widget + // from one welded onto its duplicate's entry. expect(savedNode?.widgets_values).toEqual([ 'first default', 'second default' diff --git a/docs/adr/ECS-0008-entity-component-system.md b/docs/adr/ECS-0008-entity-component-system.md index 0f183bc9569..b9693864aa8 100644 --- a/docs/adr/ECS-0008-entity-component-system.md +++ b/docs/adr/ECS-0008-entity-component-system.md @@ -209,15 +209,16 @@ legitimate re-mint rather than an identity collision — which is why > gates registration on that, so two copies of the rule disagreeing is a widget > destroyed over a disagreement. > -> Three stable `errorType`s, because the causes need different alerts and -> collapsing them reports a collision that does not exist: -> `failure_renaming_widget_duplicate_name` for a duplicate that could not be renamed -> apart, `failure_reading_widget_name` for a widget whose `name` accessor -> throws — that one has no duplicate at all, only no derivable id — and -> `failure_resolving_widget_duplicate_name` for a pair the node **keeps**, where the -> rename was declined rather than impossible. The third is not a report of lost -> widgets: the widget is still on the node, and a later commit can still -> resolve it. +> Four stable `errorType`s, because the causes need different alerts and +> collapsing them sends whoever reads one after a collision that does not +> exist: `failure_renaming_widget_duplicate_name` for a duplicate that could +> not be renamed apart, `failure_reading_widget_name` for a widget no id can be +> derived from, `failure_resolving_widget_duplicate_name` for a pair the node +> **keeps**, and `failure_tearing_down_refused_widget` for a removal whose own +> teardown threw. The third is not a report of lost widgets, but it is not +> transient either: a kept pair now comes only from a setter that accepts a +> write and ignores it, which no later commit resolves, so the report is +> deduplicated per name rather than repeated per commit. > > **There are two enforcement points, and looking only at the first one is > misleading.** `attachNodeToStores` calls `refuseAmbiguousNodeWidgets` as a diff --git a/src/lib/litegraph/src/node/widgetsView.refusalCriterion.test.ts b/src/lib/litegraph/src/node/widgetsView.refusalCriterion.test.ts index b4a6d742226..bd0b63316bb 100644 --- a/src/lib/litegraph/src/node/widgetsView.refusalCriterion.test.ts +++ b/src/lib/litegraph/src/node/widgetsView.refusalCriterion.test.ts @@ -51,29 +51,21 @@ describe('unique-name refusal criterion', () => { expect(storedNames(graph, node)).toEqual(['seed', 'steps']) - // Node removal deletes the store entries and leaves `_state.nodeId` set, so - // the next rename asks the store to move an entry that is no longer there. + // Deletes the store entries and leaves `_state.nodeId` set. graph.remove(node) - // Reachable by an extension renaming a widget while the node is detached. steps.name = 'seed' expect(steps.name).toBe('seed') - // Undoing a node deletion and pasting a cut node both land here. + // Undo and paste both land here. graph.add(node) - // The invariant must not pay for itself with a widget, and it must not pay - // with the node's registration either: a pair that stays ambiguous makes - // `ensureUniqueWidgetNames` false, which bails `setNodeId` for *every* - // widget on the node and renders none of them. expect(node.widgets).toContain(seed) expect(node.widgets).toContain(steps) expect(names(node)).toEqual(['seed', 'seed#1']) expect(storedNames(graph, node)).toEqual(['seed', 'seed#1']) expect(reportedTypes()).toEqual([]) - // Two entries, so the two values stay independent rather than resolving to - // one entry under the shared name. expect(seed.value).toBe(1) expect(steps.value).toBe(2) @@ -94,10 +86,9 @@ describe('unique-name refusal criterion', () => { steps.name = 'seed' graph.add(node) - // While the names collided, `steps` claimed `graphId:nodeId:seed` because - // identity is derived from the name it then shared. That id is `seed`'s to - // hold: being handed that entry is what welded the pair onto one - // `WidgetState` and destroyed the second value. + // While the names collided, `steps` claimed `graphId:nodeId:seed`, which is + // `seed`'s to hold: being handed that entry welds the pair onto one + // `WidgetState` and destroys the second value. const store = useWidgetValueStore() expect(store.getWidget(widgetId(graph.id, node.id, 'seed'))?.value).toBe(1) expect(seed.widgetId).toBe(widgetId(graph.id, node.id, 'seed')) @@ -153,9 +144,8 @@ describe('unique-name refusal criterion', () => { node.addWidget('number', 'seed', 1, () => undefined, {}) const steps = node.addWidget('number', 'steps', 2, () => undefined, {}) - // A setter that accepts every write and keeps the old name. It is writable, - // so the widget is addressable in principle and must not be removed, and no - // candidate the walk offers can ever stick. + // Writable, so the widget must not be removed, and no candidate the walk + // offers can ever stick. Object.defineProperty(steps, 'name', { get: () => 'seed', set: () => undefined, @@ -167,10 +157,8 @@ describe('unique-name refusal criterion', () => { expect(node.widgets).toContain(steps) expect(reportedTypes()).toEqual(['failure_resolving_widget_duplicate_name']) - // A kept pair is re-found by every later commit, and `reportError` has no - // dedupe of its own: each call builds an `Error` with a stack and - // dispatches to Sentry and Datadog. An unresolvable pair would otherwise - // emit an identical warning for the rest of the session. + // Re-found by every later commit, and `reportError` has no dedupe of its + // own, so this would otherwise warn for the rest of the session. node.addWidget('number', 'denoise', 4, () => undefined, {}) node.widgets?.push( node.addWidget('number', 'guidance', 5, () => undefined, {}) From 623b5e809074ec0415fc7935e54b64f900a9eda4 Mon Sep 17 00:00:00 2001 From: Alexander Brown Date: Mon, 5 Oct 2026 07:53:19 +0000 Subject: [PATCH 24/35] fix(widgets): type the name boundary, skip store-held suffixes and dedupe kept pairs per widget - readName and the walk accept { name: unknown } and narrow, so neither the walk nor its tests cast malformed names to string - RefusedWidget is a discriminated union; removal is every cause but unresolved-duplicate, so the separate removed flag is gone - rename candidates skip names the widget store already holds, replacing the fixed four-attempt retry - the unresolved-pair report is deduplicated per widget, so a later widget that joins an already-reported name is still reported - releaseRegisteredState stays on BaseWidget instead of widening IBaseWidget - tests: drop casts and dead setup, delete change-detector cases, fold the refused-entry cases into the unique-name suite, and pin the store-held suffix and per-widget dedup - drop comments that restate the code Amp-Thread-ID: https://ampcode.com/threads/T-01a1086c-5c03-7118-b269-6b6fda4d1cec --- .../renamableDuplicateWidgetKept.spec.ts | 130 ----------- .../unrenamableDuplicateWidgetRefused.spec.ts | 143 ------------ .../node/widgetsView.emptyWidgetName.test.ts | 40 ---- .../node/widgetsView.refusalCriterion.test.ts | 121 +++++------ .../widgetsView.refusalValueRestore.test.ts | 11 - .../widgetsView.refusedEntryRelease.test.ts | 68 ------ src/lib/litegraph/src/node/widgetsView.ts | 113 +++------- .../node/widgetsView.uniqueWidgetName.test.ts | 204 ++++-------------- src/lib/litegraph/src/types/widgets.ts | 6 - src/lib/litegraph/src/widgets/BaseWidget.ts | 11 - src/scripts/domWidget.test.ts | 5 - src/types/widgetId.test.ts | 151 +++---------- src/types/widgetId.ts | 166 ++++---------- 13 files changed, 200 insertions(+), 969 deletions(-) delete mode 100644 browser_tests/tests/widgets/renamableDuplicateWidgetKept.spec.ts delete mode 100644 browser_tests/tests/widgets/unrenamableDuplicateWidgetRefused.spec.ts delete mode 100644 src/lib/litegraph/src/node/widgetsView.refusedEntryRelease.test.ts diff --git a/browser_tests/tests/widgets/renamableDuplicateWidgetKept.spec.ts b/browser_tests/tests/widgets/renamableDuplicateWidgetKept.spec.ts deleted file mode 100644 index 31171ad9286..00000000000 --- a/browser_tests/tests/widgets/renamableDuplicateWidgetKept.spec.ts +++ /dev/null @@ -1,130 +0,0 @@ -import { expect } from '@playwright/test' - -import type { ComfyPage } from '@e2e/fixtures/ComfyPage' -import { comfyPageFixture as test } from '@e2e/fixtures/ComfyPage' -import { TestIds } from '@e2e/fixtures/selectors' - -import { zComfyWorkflow } from '@/platform/workflow/validation/schemas/workflowSchema' - -/** - * The unique-name invariant removes a widget it cannot name uniquely - * (ADR-ECS-0008). This pins the boundary of "cannot": a widget whose `name` is - * writable must never be the price of enforcing it. - * - * Driven through the graph API the way an undo of a node deletion or a paste of - * a cut node reaches it, and asserted on both the rendered rows and what the - * app saves. Two values, not just two slots: an ambiguous pair used to route - * the second widget's setter onto the entry the first had registered, so both - * read one value while the slot count still looked right. - */ - -const NODE_TYPE = 'DevToolsNodeWithOutputList' -const KEPT_NAME = 'alpha' -const RENAMED_NAME = 'beta' - -/** Two distinct, ordinary, serializable widgets, both with writable names. */ -async function installTwoOrdinaryWidgets(comfyPage: ComfyPage): Promise { - await comfyPage.page.evaluate( - ({ nodeTypeName, first, second }) => { - const nodeType = window.LiteGraph!.registered_node_types[nodeTypeName] - const onNodeCreated = nodeType.prototype.onNodeCreated - nodeType.prototype.onNodeCreated = function (...args) { - onNodeCreated?.apply(this, args) - this.serialize_widgets = true - this.addWidget('string', first, 'first default', () => {}) - this.addWidget('string', second, 'second default', () => {}) - } - }, - { nodeTypeName: NODE_TYPE, first: KEPT_NAME, second: RENAMED_NAME } - ) -} - -/** - * Collides the second widget's name with the first while the node is detached, - * then puts it back. Detached is what lets the write land, so this is the - * sequence an undo or a paste reaches. - */ -async function collideNameWhileDetached( - comfyPage: ComfyPage, - nodeId: string -): Promise { - await comfyPage.page.evaluate( - ({ id, duplicateName, renamedName }) => { - const graph = window.app!.graph - const node = graph.nodes.find((candidate) => String(candidate.id) === id) - if (!node) throw new Error(`node ${id} not found`) - - graph.remove(node) - const target = node.widgets?.find(({ name }) => name === renamedName) - if (!target) throw new Error(`widget ${renamedName} not found`) - target.name = duplicateName - graph.add(node) - }, - { id: nodeId, duplicateName: KEPT_NAME, renamedName: RENAMED_NAME } - ) -} - -test.describe( - 'renamable duplicate widget name', - { tag: ['@canvas', '@widget', '@vue-nodes'] }, - () => { - // Per attempt: a module-scope stamp is shared by every worker and retry. - let workflowName = '' - - test.afterEach(async ({ comfyPage }) => { - if (workflowName) await comfyPage.workflow.deleteWorkflow(workflowName) - }) - - test('keeps the widget whose rename was declined rather than impossible', async ({ - comfyPage - }, testInfo) => { - workflowName = `renamable-duplicate-widget-${testInfo.parallelIndex}-${testInfo.retry}-${Date.now()}` - - await comfyPage.nodeOps.clearGraph() - await installTwoOrdinaryWidgets(comfyPage) - - const nodeId = await comfyPage.searchBoxV2.addNodeAndGetId( - 'Node With Output List' - ) - const node = comfyPage.vueNodes.getNodeLocator(nodeId) - await expect(node).toBeVisible() - - await test.step('both widgets are drawn to begin with', async () => { - await expect(node.getByTestId(TestIds.widgets.widget)).toHaveCount(2) - }) - - await collideNameWhileDetached(comfyPage, nodeId) - - await test.step('both widgets are still drawn after the re-add', async () => { - // The saved values below cannot see this: they come from the widget - // objects, which survive a node that registers nothing. - await expect(node.getByTestId(TestIds.widgets.widget)).toHaveCount(2) - }) - - await test.step('and the node still saves both widget slots', async () => { - const savedRequest = comfyPage.page.waitForRequest( - (request) => - request.method() === 'POST' && - decodeURIComponent(new URL(request.url()).pathname).endsWith( - `/workflows/${workflowName}.json` - ) - ) - await comfyPage.menu.topbar.saveWorkflowAs(workflowName) - const saved = zComfyWorkflow.parse( - JSON.parse((await savedRequest).postData() ?? '{}') - ) - const savedNode = saved.nodes.find(({ type }) => type === NODE_TYPE) - - // One entry here is a widget the user lost. - expect(savedNode?.widgets_values).toHaveLength(2) - - // Distinct values, because arity alone cannot tell a preserved widget - // from one welded onto its duplicate's entry. - expect(savedNode?.widgets_values).toEqual([ - 'first default', - 'second default' - ]) - }) - }) - } -) diff --git a/browser_tests/tests/widgets/unrenamableDuplicateWidgetRefused.spec.ts b/browser_tests/tests/widgets/unrenamableDuplicateWidgetRefused.spec.ts deleted file mode 100644 index c12e7d1c2d7..00000000000 --- a/browser_tests/tests/widgets/unrenamableDuplicateWidgetRefused.spec.ts +++ /dev/null @@ -1,143 +0,0 @@ -import { expect } from '@playwright/test' - -import type { ComfyPage } from '@e2e/fixtures/ComfyPage' -import { comfyPageFixture as test } from '@e2e/fixtures/ComfyPage' -import { TestIds } from '@e2e/fixtures/selectors' -import { openWorkflowFromSidebar } from '@e2e/fixtures/utils/builderTestUtils' - -import { zComfyWorkflow } from '@/platform/workflow/validation/schemas/workflowSchema' - -/** - * Two widgets on one node cannot share a name: `WidgetId` is - * `graphId:nodeId:name`, so the second is the same identity, not a second one - * (ADR-ECS-0008, "Widget identity keys on `name`"). - * - * `ensureUniqueWidgetNames` keeps that true by renaming the repeat to - * `name#1`. It cannot rename a widget whose `name` is not writable — it warns - * and gives up — and the node then carries the ambiguous pair. - * - * Measured on the parent commit, this node renders **no widgets at all**: - * `BaseWidget.setNodeId` bails for every widget on the node, so none is - * registered and none is drawn, while `node.widgets` holds two under one name. - * The invariant is enforced instead — the widget that cannot be made unique is - * refused — and the node goes back to working. - * - * Black-box throughout: everything asserted here is what the canvas renders or - * what the app actually saved. - */ - -const NODE_TYPE = 'DevToolsNodeWithOutputList' -const DUPLICATE_NAME = 'duplicate' -const TYPED_VALUE = 'typed by the user' - -/** - * Patches the node type so every instance gains a second serializable widget - * under a name the first already holds, pinned so it cannot be renamed. On the - * type rather than the instance, so the node rebuilt after a reload carries the - * same pair the save was made from. - */ -async function installUnrenameableDuplicate( - comfyPage: ComfyPage -): Promise { - await comfyPage.page.evaluate( - ({ nodeTypeName, duplicateName }) => { - const nodeType = window.LiteGraph!.registered_node_types[nodeTypeName] - const onNodeCreated = nodeType.prototype.onNodeCreated - nodeType.prototype.onNodeCreated = function (...args) { - onNodeCreated?.apply(this, args) - this.serialize_widgets = true - this.addWidget('string', duplicateName, 'first default', () => {}) - const second = this.addWidget( - 'string', - 'second', - 'second default', - () => {} - ) - Object.defineProperty(second, 'name', { - value: duplicateName, - writable: false, - configurable: false - }) - } - }, - { nodeTypeName: NODE_TYPE, duplicateName: DUPLICATE_NAME } - ) -} - -test.describe( - 'unrenamable duplicate widget name', - { tag: ['@canvas', '@widget', '@vue-nodes'] }, - () => { - // Per attempt, not per module: a module-scope stamp is shared by every - // worker in the process and by a retry, so a retry can reopen the document - // its own previous attempt saved. - let workflowName = '' - - test.afterEach(async ({ comfyPage }) => { - if (workflowName) await comfyPage.workflow.deleteWorkflow(workflowName) - }) - - test('refuses the widget it cannot name uniquely and keeps the node usable', async ({ - comfyPage - }, testInfo) => { - workflowName = `unrenamable-duplicate-widget-${testInfo.parallelIndex}-${testInfo.retry}-${Date.now()}` - - await comfyPage.nodeOps.clearGraph() - await installUnrenameableDuplicate(comfyPage) - - const nodeId = await comfyPage.searchBoxV2.addNodeAndGetId( - 'Node With Output List' - ) - const node = comfyPage.vueNodes.getNodeLocator(nodeId) - await expect(node).toBeVisible() - - const duplicateRows = node.getByTestId(TestIds.widgets.widget).filter({ - has: comfyPage.page - .getByTestId(TestIds.widgets.layoutFieldLabel) - .and(comfyPage.page.getByText(DUPLICATE_NAME, { exact: true })) - }) - - await test.step('the canvas shows one widget under the name, not two', async () => { - await expect(duplicateRows).toHaveCount(1) - }) - - await test.step('what the user types is what the app saves', async () => { - const input = duplicateRows.locator('input') - await input.fill(TYPED_VALUE) - await input.blur() - - const savedRequest = comfyPage.page.waitForRequest( - (request) => - request.method() === 'POST' && - decodeURIComponent(new URL(request.url()).pathname).endsWith( - `/workflows/${workflowName}.json` - ) - ) - await comfyPage.menu.topbar.saveWorkflowAs(workflowName) - const saved = zComfyWorkflow.parse( - JSON.parse((await savedRequest).postData() ?? '{}') - ) - const savedNode = saved.nodes.find(({ type }) => type === NODE_TYPE) - - expect(savedNode?.widgets_values).toEqual([TYPED_VALUE]) - }) - - await test.step('and it is still there after closing and reopening', async () => { - await comfyPage.workflow.newBlankWorkflow() - await comfyPage.menu.topbar.closeWorkflowTab(workflowName) - await openWorkflowFromSidebar(comfyPage, workflowName) - - const reopened = comfyPage.page - .getByTestId(TestIds.widgets.widget) - .filter({ - has: comfyPage.page - .getByTestId(TestIds.widgets.layoutFieldLabel) - .and(comfyPage.page.getByText(DUPLICATE_NAME, { exact: true })) - }) - - await expect(reopened).toHaveCount(1) - await expect(reopened.locator('input')).toHaveValue(TYPED_VALUE) - }) - }) - } -) diff --git a/src/lib/litegraph/src/node/widgetsView.emptyWidgetName.test.ts b/src/lib/litegraph/src/node/widgetsView.emptyWidgetName.test.ts index f7b4c810c07..97656a2d315 100644 --- a/src/lib/litegraph/src/node/widgetsView.emptyWidgetName.test.ts +++ b/src/lib/litegraph/src/node/widgetsView.emptyWidgetName.test.ts @@ -6,28 +6,6 @@ import { useWidgetValueStore } from '@/stores/widgetValueStore' vi.mock(import('@/platform/telemetry/reportError')) -/** - * An empty widget name is not an ambiguous one, and the unique-name invariant - * must leave it alone in both directions. - * - * `widgetId` mints `graphId:nodeId:` for it, which `isWidgetId` rejects and - * `widgetValueStore.registerWidget` declines to key on. Declining an id is the - * whole cost: the widget stays on the node, renders, fires its callback and - * serializes. The two ways of "fixing" that are both worse and both have been - * written at least once: - * - * - **Refusing it** deletes a working widget and shifts every positional - * `widgets_values` slot after it. `browser_tests/tests/vueNodes/widgets/emptyNameWidget.spec.ts` - * is the user-visible pin (#13773: rgthree Power Lora Loader rendered no - * widgets at all), and these cases are the unit-level one. - * - **Renaming it apart** — to `#1` — relabels an ordinary unlabeled widget - * that no other widget collides with. `addWidget('text', '', …)` is a shape - * node packs ship deliberately. - * - * Both are pinned here because the array-level assertions in - * `widgetId.test.ts` compare live widget objects, so a rename passes them. - */ - function createNode(): LGraphNode { const graph = new LGraph() const node = new LGraphNode('test') @@ -48,7 +26,6 @@ function storedNames(node: LGraphNode): string[] { describe('empty widget name', () => { beforeEach(() => { LiteGraph.vueNodesMode = false - vi.mocked(reportError).mockClear() }) it('keeps an unlabeled widget on the node, under the name it was given', () => { @@ -57,8 +34,6 @@ describe('empty widget name', () => { node.addWidget('text', '', 'hello', () => undefined, {}) node.addWidget('number', 'cfg', 3, () => undefined, {}) - // Still on the node, and still unlabeled. Asserting the name rather than - // only the array is what separates "kept" from "kept but relabeled `#1`". expect(names(node)).toEqual(['seed', '', 'cfg']) expect(reportError).not.toHaveBeenCalled() }) @@ -69,29 +44,14 @@ describe('empty widget name', () => { node.addWidget('text', '', 'hello', () => undefined, {}) node.addWidget('number', 'cfg', 3, () => undefined, {}) - // The store declines `graphId:nodeId:` and keeps every other widget. The - // failure this guards against is the whole node going unregistered - // because one widget could not be keyed. expect(storedNames(node)).toEqual(['seed', 'cfg']) }) - it('keeps the value an unlabeled widget holds, rather than losing it to the store', () => { - const node = createNode() - const unlabeled = node.addWidget('text', '', 'hello', () => undefined, {}) - - // An unregistered widget reads and writes its own local state. If this - // regressed, the widget would render but forget what the user typed. - unlabeled.value = 'typed' - expect(unlabeled.value).toBe('typed') - }) - it('still settles two unlabeled widgets, which do collide with each other', () => { const node = createNode() node.addWidget('text', '', 'first', () => undefined, {}) node.addWidget('text', '', 'second', () => undefined, {}) - // Two empty names are one identity twice, so the invariant applies as it - // does to any other duplicate — the second is renamed, not refused. expect(names(node)).toEqual(['', '#1']) expect(node.widgets).toHaveLength(2) expect(reportError).not.toHaveBeenCalled() diff --git a/src/lib/litegraph/src/node/widgetsView.refusalCriterion.test.ts b/src/lib/litegraph/src/node/widgetsView.refusalCriterion.test.ts index bd0b63316bb..95db1d60f72 100644 --- a/src/lib/litegraph/src/node/widgetsView.refusalCriterion.test.ts +++ b/src/lib/litegraph/src/node/widgetsView.refusalCriterion.test.ts @@ -1,29 +1,15 @@ -import { beforeEach, describe, expect, it, vi } from 'vitest' +import { assert, beforeEach, describe, expect, it, vi } from 'vitest' import { LGraph, LGraphNode, LiteGraph } from '@/lib/litegraph/src/litegraph' +import { BaseWidget } from '@/lib/litegraph/src/widgets/BaseWidget' import { reportError } from '@/platform/telemetry/reportError' import { useWidgetValueStore } from '@/stores/widgetValueStore' import { widgetId } from '@/types/widgetId' vi.mock(import('@/platform/telemetry/reportError')) -/** - * The unique-name invariant removes a widget it cannot name uniquely. What - * counts as "cannot" is the subject here, because the two candidate criteria - * disagree on a node the user can reach: - * - * - **the read-back** — write `name#1`, read `name` back, remove on mismatch; - * - **the descriptor** — remove only when `name` could not be written at all. - * - * `BaseWidget.set name` delegates to `widgetValueStore.renameWidget()` and - * returns without changing `_name` whenever the store declines a move it owns. - * So the read-back can report failure for a widget that is addressable in - * principle, and removing on it destroys that widget. - */ function reportedTypes(): (string | undefined)[] { - return vi - .mocked(reportError) - .mock.calls.map((call) => call[1].errorType as string | undefined) + return vi.mocked(reportError).mock.calls.map((call) => call[1].errorType) } function names(node: LGraphNode): string[] { @@ -39,7 +25,6 @@ function storedNames(graph: LGraph, node: LGraphNode): string[] { describe('unique-name refusal criterion', () => { beforeEach(() => { LiteGraph.vueNodesMode = false - vi.mocked(reportError).mockClear() }) it('resolves an ordinary renamable duplicate on a node that was removed and re-added', () => { @@ -75,66 +60,32 @@ describe('unique-name refusal criterion', () => { expect(steps.value).toBe(222) }) - it('does not let a duplicate rename move the entry the other widget registered', () => { - const graph = new LGraph() - const node = new LGraphNode('test') - graph.add(node) - const seed = node.addWidget('number', 'seed', 1, () => undefined, {}) - const steps = node.addWidget('number', 'steps', 2, () => undefined, {}) - - graph.remove(node) - steps.name = 'seed' - graph.add(node) - - // While the names collided, `steps` claimed `graphId:nodeId:seed`, which is - // `seed`'s to hold: being handed that entry welds the pair onto one - // `WidgetState` and destroys the second value. - const store = useWidgetValueStore() - expect(store.getWidget(widgetId(graph.id, node.id, 'seed'))?.value).toBe(1) - expect(seed.widgetId).toBe(widgetId(graph.id, node.id, 'seed')) - expect(steps.widgetId).toBe(widgetId(graph.id, node.id, 'seed#1')) - expect(store.getWidget(widgetId(graph.id, node.id, 'seed#1'))?.value).toBe( - 2 - ) - }) - it('does not let a duplicate rename steal the entry of a widget on another node', () => { const graph = new LGraph() const store = useWidgetValueStore() - // Node A holds an ordinary, legitimately registered `seed`. Nothing about - // node A is ambiguous and nothing below is node A's doing. const nodeA = new LGraphNode('a') graph.add(nodeA) const aSeed = nodeA.addWidget('number', 'seed', 7, () => undefined, {}) + nodeA.addWidget('number', 'steps', 8, () => undefined, {}) const nodeB = new LGraphNode('b') graph.add(nodeB) nodeB.addWidget('number', 'seed', 1, () => undefined, {}) const victim = nodeB.addWidget('number', 'steps', 2, () => undefined, {}) - // A `_state.nodeId` left pointing at a node the widget no longer belongs - // to. Set directly rather than driven through widget adoption, which is - // what produces it in production; the stale binding is the precondition - // under test, not the route to it. - const state = (victim as unknown as { _state: { nodeId: unknown } })._state - state.nodeId = nodeA.id + assert(victim instanceof BaseWidget) + victim.bindRegisteredState(nodeA.id) graph.remove(nodeB) victim.name = 'seed' graph.add(nodeB) - // Node B carrying a duplicate name must not reach into node A. Renaming - // `victim` targets `graphId:A:seed` — node A's widget's id, because - // identity is `graphId:nodeId:name` and both parts are now borrowed. Moving - // that entry deletes node A's registration and hands node A's value to a - // widget on node B. expect(store.getWidget(widgetId(graph.id, nodeA.id, 'seed'))?.value).toBe(7) expect( store.getWidget(widgetId(graph.id, nodeA.id, 'seed#1')) ).toBeUndefined() expect(aSeed.value).toBe(7) - expect(victim.value).toBe(2) }) it('reports an unresolved pair once, not on every later commit', () => { @@ -165,6 +116,38 @@ describe('unique-name refusal criterion', () => { ) expect(reportedTypes()).toEqual(['failure_resolving_widget_duplicate_name']) + + const cfg = node.widgets?.find((widget) => widget.name === 'cfg') + assert.exists(cfg) + Object.defineProperty(cfg, 'name', { + get: () => 'seed', + set: () => undefined, + configurable: true + }) + node.addWidget('number', 'eta', 6, () => undefined, {}) + + expect(reportedTypes()).toEqual([ + 'failure_resolving_widget_duplicate_name', + 'failure_resolving_widget_duplicate_name' + ]) + }) + + it('renames past a candidate a stale store entry still holds', () => { + const graph = new LGraph() + const node = new LGraphNode('test') + graph.add(node) + node.addWidget('number', 'seed', 1, () => undefined, {}) + const stale = node.addWidget('number', 'seed#1', 2, () => undefined, {}) + Object.defineProperty(stale, 'name', { + value: 'other', + writable: true, + configurable: true + }) + + const added = node.addWidget('number', 'seed', 3, () => undefined, {}) + + expect(names(node)).toEqual(['seed', 'other', 'seed#2']) + expect(added.value).toBe(3) }) it('leaves a kept duplicate wired up, rather than tearing it down in place', () => { @@ -177,25 +160,21 @@ describe('unique-name refusal criterion', () => { steps.onRemove = () => { removals++ } - const slot = { - name: 'steps', - type: 'number', - _widget: steps, - widget: { name: 'steps' }, - pos: [0, 0] - } as unknown as (typeof node.inputs)[number] - node.inputs.push(slot) + const slot = node.addInput('steps', 'number') + slot._widget = steps + slot.widget = { name: 'steps' } + Object.defineProperty(steps, 'name', { + get: () => 'seed', + set: () => undefined, + configurable: true + }) - graph.remove(node) - steps.name = 'seed' - graph.add(node) + node.addWidget('number', 'cfg', 3, () => undefined, {}) - // The teardown that a removal owes the node is wrong for a widget the node - // still has: it would call `onRemove` on a live widget and drop the slot's - // back-references, leaving an input pointing at nothing. + expect(node.widgets).toContain(steps) expect(removals).toBe(0) expect(slot._widget).toBe(steps) - expect(slot.widget).toBeDefined() + expect(slot.widget).toEqual({ name: 'steps' }) }) it('still removes a duplicate whose name genuinely cannot be written', () => { @@ -213,8 +192,6 @@ describe('unique-name refusal criterion', () => { node.addWidget('number', 'cfg', 3, () => undefined, {}) - // Nothing can address this one, so keeping it would silently share the - // other widget's value. Removal is correct here and is not weakened. expect(node.widgets).not.toContain(doomed) expect(reportedTypes()).toContain('failure_renaming_widget_duplicate_name') }) diff --git a/src/lib/litegraph/src/node/widgetsView.refusalValueRestore.test.ts b/src/lib/litegraph/src/node/widgetsView.refusalValueRestore.test.ts index b158e382c4b..dc71e5bde88 100644 --- a/src/lib/litegraph/src/node/widgetsView.refusalValueRestore.test.ts +++ b/src/lib/litegraph/src/node/widgetsView.refusalValueRestore.test.ts @@ -2,13 +2,6 @@ import { afterEach, beforeEach, describe, expect, it } from 'vitest' import { LGraph, LGraphNode, LiteGraph } from '@/lib/litegraph/src/litegraph' -/** - * What a refusal does to the values of a workflow saved before it existed. - * Positional restore counts the widgets the node has *now*, so a removed - * widget's slot is taken by the next widget. ADR-ECS-0008 records that as - * accepted and names the conditions; these cases pin it so it stays a decision - * rather than a surprise. - */ describe('restoring values onto a node that refused a widget', () => { const namedValuesRestore = LiteGraph.namedValuesRestore @@ -45,10 +38,6 @@ describe('restoring values onto a node that refused a widget', () => { LiteGraph.namedValuesRestore = namedValuesRestore }) - /** - * `LGraph.configure` adds each node and configures it afterwards, so the - * refusal has already run by the time values are restored. - */ function load(type: string, named?: Record) { const graph = new LGraph() const node = LiteGraph.createNode(type)! diff --git a/src/lib/litegraph/src/node/widgetsView.refusedEntryRelease.test.ts b/src/lib/litegraph/src/node/widgetsView.refusedEntryRelease.test.ts deleted file mode 100644 index 9955dd2bb51..00000000000 --- a/src/lib/litegraph/src/node/widgetsView.refusedEntryRelease.test.ts +++ /dev/null @@ -1,68 +0,0 @@ -import { describe, expect, it } from 'vitest' - -import { LGraph, LGraphNode } from '@/lib/litegraph/src/litegraph' -import type { IBaseWidget } from '@/lib/litegraph/src/types/widgets' -import { useWidgetValueStore } from '@/stores/widgetValueStore' -import { widgetId } from '@/types/widgetId' - -/** - * A widget can register under a unique name and only later be pinned onto a - * name another widget holds — `Object.defineProperty` bypasses the setter, so - * the store entry stays under the earlier name while the node refuses the - * widget. `registerWidget` keeps an existing value for a same-type - * re-registration, so that entry would hand its value to the next widget of - * that name. - */ -describe('the store entry of a refused widget', () => { - function pinName(widget: IBaseWidget, name: string): void { - Object.defineProperty(widget, 'name', { - value: name, - writable: false, - configurable: false, - enumerable: true - }) - } - - function nodeWithRefusedWidget() { - const graph = new LGraph() - const node = new LGraphNode('test') - graph.add(node) - const kept = node.addWidget('number', 'seed', 1, () => {}) - const refused = node.addWidget('number', 'seed', 2, () => {}) - refused.value = 42 - const registeredName = refused.name - pinName(refused, 'seed') - node.addWidget('number', 'steps', 0, () => {}) - - return { - node, - kept, - registeredName, - graphId: node.graph!.rootGraph.id - } - } - - it('is released, so a later widget of that name keeps its own value', () => { - const { node, registeredName, graphId } = nodeWithRefusedWidget() - - expect( - useWidgetValueStore().getWidget( - widgetId(graphId, node.id, registeredName) - ) - ).toBeUndefined() - expect(node.addWidget('number', registeredName, 7, () => {}).value).toBe(7) - }) - - it('is released without disturbing the widget that kept the name', () => { - const { node, kept, graphId } = nodeWithRefusedWidget() - - expect(kept.value).toBe(1) - expect( - useWidgetValueStore().getWidget(widgetId(graphId, node.id, 'seed'))?.value - ).toBe(1) - expect((node.widgets ?? []).map((widget) => widget.name)).toEqual([ - 'seed', - 'steps' - ]) - }) -}) diff --git a/src/lib/litegraph/src/node/widgetsView.ts b/src/lib/litegraph/src/node/widgetsView.ts index 8e8c3182f99..b0855173e06 100644 --- a/src/lib/litegraph/src/node/widgetsView.ts +++ b/src/lib/litegraph/src/node/widgetsView.ts @@ -9,17 +9,16 @@ import { reportError } from '@/platform/telemetry/reportError' import type { RefusedWidget } from '@/types/widgetId' import { dropUnrenamableDuplicateWidgets, - isWidgetNameUnreadable + isWidgetNameUnreadable, + widgetId } from '@/types/widgetId' import { createArrayMutationView } from '../infrastructure/createMutationView' +import type { INodeInputSlot } from '../interfaces' import { isNodeBindable } from '../utils/type' import { getWidgetIds } from '../utils/widget' +import { BaseWidget } from '../widgets/BaseWidget' -/** - * `errorType` slugs here follow `src/AGENTS.md`'s - * `__` form. - */ const REFUSAL_TEARDOWN_ERROR_TYPE = 'failure_tearing_down_refused_widget' interface WidgetsViewState { @@ -29,16 +28,12 @@ interface WidgetsViewState { commit: (widgets: IBaseWidget[]) => void } -/** Shared empty result, so the common no-refusal path allocates nothing. */ -const EMPTY_REFUSAL: ReadonlySet = new Set() - /** - * The unresolved names already reported for a node. A kept pair survives the - * walk, so every later commit finds it again and `reportError` has no dedupe - * of its own. Replaced rather than added to, so a name that stops colliding - * and later collides again is reported again. + * The unresolved duplicates already reported for a node. A kept pair survives + * the walk, so every later commit finds it again, and `reportError` has no + * dedupe of its own. */ -const reportedUnresolvedNames = new WeakMap>() +const reportedUnresolved = new WeakMap>() const states = new WeakMap() const widgetsViewGetters = new WeakSet<() => IBaseWidget[] | undefined>() @@ -56,7 +51,6 @@ function safeRead(read: () => unknown): string | undefined { } } -/** Reports a teardown step that failed, so a half-done release is visible. */ function reportTeardownFailure(node: LGraphNode, error: unknown): void { reportError(error, { errorType: REFUSAL_TEARDOWN_ERROR_TYPE, @@ -73,7 +67,7 @@ function reportTeardownFailure(node: LGraphNode, error: unknown): void { * on read. Matching only the reference finds nothing on these nodes. */ function inputBindsWidget( - input: LGraphNode['inputs'][number], + input: INodeInputSlot, widget: IBaseWidget, name: string | undefined ): boolean { @@ -81,7 +75,6 @@ function inputBindsWidget( return name !== undefined && input.widget?.name === name } -/** Drops the slot back-references to a widget the node has just refused. */ function clearRefusedSlotBindings( node: LGraphNode, widget: IBaseWidget, @@ -125,69 +118,47 @@ function releaseRefusedWidget( // After `onRemove`, which may still read the value through the entry. try { - widget.releaseRegisteredState?.() + if (widget instanceof BaseWidget) widget.releaseRegisteredState() } catch (error) { reportTeardownFailure(node, error) } } -/** - * Enforces the unique-name invariant where `node.widgets` is committed: the - * array is a mutation view, so `addWidget`, a raw `widgets.push`, a splice and - * a whole-array assignment all pass through here. A widget removed here is off - * the node before it can be rendered, and its own entry is released — it may - * already have one, from a name it held before an extension pinned it onto - * another widget's. - * - * `SubgraphNode` does **not** commit through here and keeps the pre-existing - * behaviour: it redefines `widgets` as a computed getter over its promoted - * widgets and overrides `addCustomWidget` to push into its own array. - */ function refuseAmbiguousWidgets( node: LGraphNode, widgets: IBaseWidget[] ): ReadonlySet { - const refused = dropUnrenamableDuplicateWidgets(widgets) - if (!refused.length) { - reportedUnresolvedNames.delete(node) - return EMPTY_REFUSAL - } - - const alreadyReported = takeUnresolvedReportGate(node, refused) - - for (const finding of refused) { - // Safe to skip before the teardown below only because a kept pair is - // never released. - if (alreadyReported(finding)) continue - - // A kept duplicate is still the node's widget and keeps its slot wiring. - if (finding.removed) { - releaseRefusedWidget(node, finding.widget, finding.name) - } - reportRefusal(node, finding) - } - - return new Set( - refused.filter(({ removed }) => removed).map(({ widget }) => widget) + const graphId = node.graph?.rootGraph.id + const store = useWidgetValueStore() + const refused = dropUnrenamableDuplicateWidgets( + widgets, + (name) => + graphId !== undefined && + store.getWidget(widgetId(graphId, node.id, name)) !== undefined ) -} -/** @returns whether a finding was already alerted on before this pass. */ -function takeUnresolvedReportGate( - node: LGraphNode, - refused: readonly RefusedWidget[] -): (finding: RefusedWidget) => boolean { - const previous = reportedUnresolvedNames.get(node) + const previouslyUnresolved = reportedUnresolved.get(node) const unresolved = new Set( refused .filter(({ cause }) => cause === 'unresolved-duplicate') - .map(({ name }) => String(name)) + .map(({ widget }) => widget) ) - if (unresolved.size) reportedUnresolvedNames.set(node, unresolved) - else reportedUnresolvedNames.delete(node) + if (unresolved.size) reportedUnresolved.set(node, unresolved) + else reportedUnresolved.delete(node) - return ({ cause, name }) => - cause === 'unresolved-duplicate' && !!previous?.has(String(name)) + const removed = new Set() + for (const finding of refused) { + if (finding.cause === 'unresolved-duplicate') { + if (!previouslyUnresolved?.has(finding.widget)) { + reportRefusal(node, finding) + } + continue + } + removed.add(finding.widget) + releaseRefusedWidget(node, finding.widget, finding.name) + reportRefusal(node, finding) + } + return removed } /** @@ -246,10 +217,6 @@ function commitsThroughWidgetsView(node: LGraphNode): boolean { return !!descriptor?.get && widgetsViewGetters.has(descriptor.get) } -/** - * Whether {@link node} refused {@link widget} — it is not on a node whose list - * this module owns, so it was dropped for a name it could not be given. - */ export function wasWidgetRefused( node: LGraphNode, widget: IBaseWidget @@ -269,10 +236,7 @@ export function wasWidgetRefused( */ export function refuseAmbiguousNodeWidgets(node: LGraphNode): void { if (!commitsThroughWidgetsView(node)) return - // This module's own array, never `node.widgets`. That getter hands back the - // mutation view, and the walk's closing splice on the view re-enters - // `syncWidgetOrder` — a whole nested commit, run while the refused widget's - // slot back-references are still live and before anything is reported. + // The raw target: splicing `node.widgets` would re-enter `syncWidgetOrder`. const widgets = states.get(node)?.target if (!widgets?.length) return refuseAmbiguousWidgets(node, widgets) @@ -293,13 +257,6 @@ function syncWidgetOrder(node: LGraphNode, widgets: IBaseWidget[]): void { try { return toConcreteWidget(widget, node) } catch (error) { - // Only the unreadable-name case is swallowed, and only because the - // refusal below is about to take this widget anyway. Conversion reads - // `type`, `options` and `value` too, and a failure in any of those - // leaves a widget the refusal has no reason to drop — so it keeps - // throwing, as it did before. This also only covers the commit path: - // `addCustomWidget` converts before it pushes, so `addWidget` and - // `addDOMWidget` still throw to their caller. if (!unreadable) throw error return widget } diff --git a/src/lib/litegraph/src/node/widgetsView.uniqueWidgetName.test.ts b/src/lib/litegraph/src/node/widgetsView.uniqueWidgetName.test.ts index 28670031586..6f498c88cb3 100644 --- a/src/lib/litegraph/src/node/widgetsView.uniqueWidgetName.test.ts +++ b/src/lib/litegraph/src/node/widgetsView.uniqueWidgetName.test.ts @@ -2,7 +2,6 @@ import { beforeEach, describe, expect, it, vi } from 'vitest' import { LGraph, LGraphNode, LiteGraph } from '@/lib/litegraph/src/litegraph' import type { IBaseWidget } from '@/lib/litegraph/src/types/widgets' -import { isNodeBindable } from '@/lib/litegraph/src/utils/type' import { reportError } from '@/platform/telemetry/reportError' import { useWidgetValueStore } from '@/stores/widgetValueStore' import { toNodeId } from '@/types/nodeId' @@ -15,17 +14,6 @@ import { vi.mock(import('@/platform/telemetry/reportError')) -/** - * Two widgets on one node cannot share a name: `WidgetId` is - * `graphId:nodeId:name`, so the second is the same identity, not a second one. - * ADR-ECS-0008, "Widget identity keys on `name`". - * - * `ensureUniqueWidgetNames` keeps that true by renaming the repeat to - * `name#1`. It cannot rename a widget whose `name` is not writable, and it - * then leaves every name unchanged — the one state in which a node really - * carries an ambiguous pair. These cases pin the refusal that replaces it. - */ - function createNode(): LGraphNode { const graph = new LGraph() const node = new LGraphNode('test') @@ -33,13 +21,6 @@ function createNode(): LGraphNode { return node } -/** - * Pins `name` on an already-concrete widget, which is how the state is - * actually reached: an extension redefines the property in `onNodeCreated` - * after the widget exists. A non-writable descriptor on the *plain* object - * handed to `addWidget` does not survive — `toConcreteWidget` merges the - * concrete class's writable accessor over it. - */ function pinName(widget: IBaseWidget, name: string): void { Object.defineProperty(widget, 'name', { value: name, @@ -62,7 +43,6 @@ function storedNames(node: LGraphNode): string[] { describe('unique widget name invariant', () => { beforeEach(() => { LiteGraph.vueNodesMode = false - vi.mocked(reportError).mockClear() }) it('still renames a duplicate it can rename, and reports nothing', () => { @@ -81,16 +61,10 @@ describe('unique widget name invariant', () => { const second = node.addWidget('number', 'steps', 2, () => undefined, {}) pinName(second, 'seed') - // A name pinned after the widget exists is caught by the next widgets - // mutation; `LGraph.add` is also one, which is what covers the realistic - // `onNodeCreated` case the next test pins. node.addWidget('number', 'cfg', 3, () => undefined, {}) expect(names(node)).toEqual(['seed', 'cfg']) expect(node.widgets).not.toContain(second) - // The error type is spelled out rather than compared to the exported - // constant: an alert query is written against this string, so renaming it - // is the breaking change and the literal is the contract. expect(reportError).toHaveBeenCalledExactlyOnceWith( expect.any(Error), expect.objectContaining({ @@ -107,9 +81,6 @@ describe('unique widget name invariant', () => { node.widgets!.splice(node.widgets!.indexOf(moved), 1) pinName(moved, 'seed') - // Refused inside the add itself, so the add must not go on to register it: - // the id it would register under is the one `first` already holds, and - // registering binds the refused widget's state to that entry. node.addCustomWidget(moved) moved.value = 99 @@ -175,8 +146,6 @@ describe('unique widget name invariant', () => { const third = node.addWidget('number', 'spare', 3, () => undefined, {}) pinName(third, 'seed') - // `ensureUniqueWidgetNames` is all-or-nothing, so this renamable repeat - // only stays ambiguous while the unrenamable one is on the node. node.addWidget('number', 'steps', 4, () => undefined, {}) expect(names(node)).toEqual(['seed', 'steps', 'steps#1']) @@ -197,10 +166,6 @@ describe('unique widget name invariant', () => { node.widgets!.push(raw) - // Renamability is judged after `toConcreteWidget`, which gives a raw - // object the concrete class's writable `name` accessor. Judging it while - // still raw would delete a widget that renames cleanly a line later, and - // refusal is permanent. expect(names(node)).toEqual(['seed', 'seed#1']) expect(storedNames(node)).toEqual(['seed', 'seed#1']) expect(reportError).not.toHaveBeenCalled() @@ -212,7 +177,6 @@ describe('unique widget name invariant', () => { const other = node.addWidget('number', 'steps', 2, () => undefined, {}) pinName(other, 'seed') - // Node packs rebuild the array wholesale rather than adding one at a time. node.widgets = undefined node.widgets = [kept, other] @@ -226,12 +190,6 @@ describe('unique widget name invariant', () => { node.addWidget('number', 'audio', 1, () => undefined, {}) node.addWidget('button', 'audio', '', () => undefined, {}) - // No `WidgetId` exists before the node has a graph, so there is nothing to - // collide over yet — and renaming during construction is observable: - // `litegraphService` finds the widget a custom constructor just made by - // comparing `candidate.name` to the returned widget's name, so an early - // rename moves the input's label onto the wrong widget. Core's RecordAudio - // node builds exactly this shape. expect(names(node)).toEqual(['audio', 'audio']) graph.add(node) @@ -252,10 +210,6 @@ describe('unique widget name invariant', () => { configurable: false }) - // Everything the report reads off a refused widget is hostile by then, so - // `type` is poisoned too: the report runs after the array has been - // spliced, and a throw there would leave the node's widgets and the - // store's order out of sync, surfacing far from its cause. Object.defineProperty(hostile, 'type', { get(): string { throw new Error('type is not readable either') @@ -268,8 +222,6 @@ describe('unique widget name invariant', () => { ).not.toThrow() expect(names(node)).toEqual(['seed', 'cfg']) - // Its own cause, not the duplicate one: this widget has no duplicate, and - // an alert that says it does sends the reader hunting for a collision. expect(reportError).toHaveBeenCalledExactlyOnceWith( expect.any(Error), expect.objectContaining({ @@ -283,25 +235,24 @@ describe('unique widget name invariant', () => { const node = createNode() node.addWidget('number', 'seed', 1, () => undefined, {}) - // `BaseWidget`'s constructor reads the source object's `name`, so - // converting this throws out of the commit before the refusal can see it — - // and out of every later commit too, which is what wedges the node. - const hostile = { - get name(): string { - throw new Error('name is not readable') - }, + const hostile: IBaseWidget = { + name: 'steps', type: 'number', value: 2, y: 0, options: {} } + Object.defineProperty(hostile, 'name', { + get(): string { + throw new Error('name is not readable') + } + }) - expect(() => node.widgets!.push(hostile as never)).not.toThrow() + expect(() => node.widgets!.push(hostile)).not.toThrow() // `indexOf` rather than `not.toContain`: the matcher deep-compares, which // reads the getter and throws out of the assertion itself. - expect(node.widgets!.indexOf(hostile as never)).toBe(-1) + expect(node.widgets!.indexOf(hostile)).toBe(-1) - // The node still takes widgets afterwards, and the store's order keeps up. expect(() => node.addWidget('number', 'steps', 3, () => undefined, {}) ).not.toThrow() @@ -320,10 +271,6 @@ describe('unique widget name invariant', () => { node.addWidget('number', 'seed', 1, () => undefined, {}) const flaky = node.addWidget('number', 'steps', 2, () => undefined, {}) - // Unreadable for as long as the widget is on the node, readable once it - // has been dropped. The walk therefore decides "unreadable"; anything that - // asks the accessor again afterwards — the refusal reports after the - // splice — gets a name back and would call it a duplicate instead. Object.defineProperty(flaky, 'name', { get(): string { if (node.widgets?.includes(flaky)) @@ -348,32 +295,24 @@ describe('unique widget name invariant', () => { const node = createNode() node.addWidget('number', 'seed', 1, () => undefined, {}) - // Conversion reads `type` as well as `name`. This widget's name is - // perfectly readable, so the refusal has no reason to drop it — letting - // the conversion failure pass would leave a raw widget on the node and in - // the store's order with nothing having reported it. - const hostile = { + const hostile: IBaseWidget = { name: 'steps', - get type(): string { - throw new Error('type is not readable') - }, + type: 'number', value: 2, y: 0, options: {} } + Object.defineProperty(hostile, 'type', { + get(): string { + throw new Error('type is not readable') + } + }) - expect(() => node.widgets!.push(hostile as never)).toThrow( - 'type is not readable' - ) + expect(() => node.widgets!.push(hostile)).toThrow('type is not readable') expect(reportError).not.toHaveBeenCalled() }) it('clears a slot bound to the refused widget by name, which is how real nodes bind', () => { - // The existing case sets `input._widget` by hand, and production assigns - // that only for promoted subgraph inputs — the one class this refusal is - // gated off. Ordinary nodes bind widget inputs by name, so a refusal that - // only matches the direct reference clears nothing and the slot silently - // re-binds to the widget that kept the name. const node = createNode() node.addWidget('number', 'seed', 1, () => undefined, {}) const second = node.addWidget('number', 'steps', 2, () => undefined, {}) @@ -382,8 +321,6 @@ describe('unique widget name invariant', () => { input.widget = { name: 'steps' } pinName(second, 'steps') - // A second widget pinned onto `steps` is refused, and the slot that named - // it must not be left pointing at a name it no longer owns. const third = node.addWidget('number', 'spare', 3, () => undefined, {}) pinName(third, 'steps') node.addWidget('number', 'cfg', 4, () => undefined, {}) @@ -393,16 +330,15 @@ describe('unique widget name invariant', () => { }) it('does not tear down every input when a hole reaches the refusal', () => { - // A nullish entry reads as an unreadable name and is refused like anything - // else. Matching the teardown on it would clear every input whose - // `_widget` is still unset, which is nearly all of them. const node = createNode() node.addWidget('number', 'seed', 1, () => undefined, {}) node.addInput('seed', 'INT') const input = node.inputs.at(-1)! input.widget = { name: 'seed' } - expect(() => node.widgets!.push(undefined as never)).not.toThrow() + expect(() => { + node.widgets!.length += 1 + }).not.toThrow() expect(input.widget).toEqual({ name: 'seed' }) expect(names(node)).toEqual(['seed']) @@ -420,9 +356,6 @@ describe('unique widget name invariant', () => { node.addWidget('number', 'cfg', 3, () => undefined, {}) - // Refusal splices the widget straight out of the array, so the teardown - // `removeWidget` owns has to happen here or the node keeps pointing at a - // widget it no longer has. expect(node.widgets).not.toContain(second) expect(input._widget).toBeUndefined() expect(input.widget).toBeUndefined() @@ -449,26 +382,23 @@ describe('unique widget name invariant', () => { } pinName(second, 'seed') - // Teardown stopping half-done leaves a DOM widget's element mounted and - // extension resources undisposed, so it needs a sink rather than a log. expect(() => node.addWidget('number', 'cfg', 3, () => undefined, {}) ).not.toThrow() - expect( - vi.mocked(reportError).mock.calls.map(([, options]) => options.errorType) - ).toEqual([ - 'failure_tearing_down_refused_widget', - 'failure_renaming_widget_duplicate_name' - ]) + const errorTypes = vi + .mocked(reportError) + .mock.calls.map(([, options]) => options.errorType) + expect(errorTypes).toHaveLength(2) + expect(errorTypes).toEqual( + expect.arrayContaining([ + 'failure_tearing_down_refused_widget', + 'failure_renaming_widget_duplicate_name' + ]) + ) }) it('leaves a node alone once it stops exposing the widget list this module owns', () => { - // The node committed widgets through the view, then something replaced - // `widgets` with its own getter — which is what `SubgraphNode` does, and - // what an extension can do. This module still holds the array it built, - // and acting on it would refuse widgets off a list the node no longer - // reads, reporting a refusal nothing can observe. const graph = new LGraph() const node = new LGraphNode('test') node.addWidget('custom', 'duplicate', 'first', () => undefined, {}) @@ -488,28 +418,6 @@ describe('unique widget name invariant', () => { expect(ownList).toHaveLength(2) }) - it('does not re-enter the commit path when a node joins a graph', () => { - // Handing the walk `node.widgets` gives it the mutation view, so its - // closing splice runs a whole nested commit from inside the walk — before - // the refused widget is released or reported, and with anything that - // throws in there escaping the join with the splice already applied. - const graph = new LGraph() - const node = new LGraphNode('test') - node.addWidget('custom', 'duplicate', 'first', () => undefined, {}) - const second = node.addWidget('custom', 'second', 'second', () => {}, {}) - pinName(second, 'duplicate') - - const replaceNodeWidgetOrder = vi.spyOn( - useWidgetValueStore(), - 'replaceNodeWidgetOrder' - ) - - graph.add(node) - - expect(names(node)).toEqual(['duplicate']) - expect(replaceNodeWidgetOrder).not.toHaveBeenCalled() - }) - it('reports the name the walk read, not what the rename attempts left behind', () => { const node = createNode() node.addWidget('number', 'seed', 1, () => undefined, {}) @@ -520,11 +428,6 @@ describe('unique widget name invariant', () => { () => undefined, {} ) - // Stores a transformed value, so it never answers to the candidate it was - // offered — and afterwards it holds a name no widget on the node owns, - // which is what the report must not quote. Its `name` is writable, so the - // pair is reported as unresolved and the widget is kept, but the name the - // report has to carry is the same either way. let stored = 'seed' Object.defineProperty(normalising, 'name', { get: () => stored, @@ -544,38 +447,10 @@ describe('unique widget name invariant', () => { context: expect.objectContaining({ widgetName: 'seed' }) }) ) - // Kept, not removed: a setter that declines is a recoverable refusal. expect(node.widgets).toContain(normalising) }) - it('registers an unresolved widget that the node keeps', () => { - const node = createNode() - node.addWidget('number', 'seed', 1, () => undefined, {}) - const unresolved = node.addWidget('number', 'steps', 2, () => undefined, {}) - let stored = 'seed' - Object.defineProperty(unresolved, 'name', { - get: () => stored, - set: (value: string) => { - stored = `${value}-normalised` - }, - configurable: true - }) - expect(isNodeBindable(unresolved)).toBe(true) - if (!isNodeBindable(unresolved)) throw new Error('Expected concrete widget') - const setNodeId = vi.spyOn(unresolved, 'setNodeId') - - node.addWidget('number', 'cfg', 3, () => undefined, {}) - - expect(node.widgets).toContain(unresolved) - expect(setNodeId).toHaveBeenCalledWith(node.id) - }) - it('does not report a refusal it cannot carry out on a subgraph node', () => { - // A `SubgraphNode` rebuilds `widgets` on every read, so nothing this - // module splices ever leaves the node. Enforcing there anyway reports the - // alerting contract `failure_renaming_widget_duplicate_name` for a refusal that did - // not happen — and promoted projections have a getter-only `name`, so a - // node promoting the same inner widget name twice hits it on every add. const subgraph = createTestSubgraph({ inputs: [ { name: 'first', type: 'INT' }, @@ -586,8 +461,6 @@ describe('unique widget name invariant', () => { const store = useWidgetValueStore() const rootGraphId = host.rootGraph.id - // Same inner widget name on two different inner nodes, which is what - // promoting `seed` from two samplers produces. const firstPromoted = widgetId(rootGraphId, toNodeId(900), 'seed') const secondPromoted = widgetId(rootGraphId, toNodeId(901), 'seed') store.registerWidget(firstPromoted, { @@ -607,9 +480,22 @@ describe('unique widget name invariant', () => { host.rootGraph.add(host) - // Still both there: this node class is outside the invariant's reach, and - // that is the pre-existing behaviour the refusal must not pretend to change. expect(host.widgets.map((widget) => widget.name)).toEqual(['seed', 'seed']) expect(reportError).not.toHaveBeenCalled() }) + + it('releases the entry a refused widget registered, without touching the kept one', () => { + const node = createNode() + const kept = node.addWidget('number', 'seed', 1, () => undefined, {}) + const refused = node.addWidget('number', 'seed', 2, () => undefined, {}) + refused.value = 42 + pinName(refused, 'seed') + node.addWidget('number', 'steps', 0, () => undefined, {}) + + expect(storedNames(node)).toEqual(['seed', 'steps']) + expect(kept.value).toBe(1) + expect( + node.addWidget('number', 'seed#1', 7, () => undefined, {}).value + ).toBe(7) + }) }) diff --git a/src/lib/litegraph/src/types/widgets.ts b/src/lib/litegraph/src/types/widgets.ts index 63f7dfecf64..7d20f501ce1 100644 --- a/src/lib/litegraph/src/types/widgets.ts +++ b/src/lib/litegraph/src/types/widgets.ts @@ -488,12 +488,6 @@ export interface IBaseWidget< readonly widgetId?: WidgetId - /** - * Drops the store entry this widget is bound to, if the store still holds - * that entry. Absent on raw widget objects, which hold none. - */ - releaseRegisteredState?(): void - name: string options: TOptions syncLiveVisibilityOptions?(): void diff --git a/src/lib/litegraph/src/widgets/BaseWidget.ts b/src/lib/litegraph/src/widgets/BaseWidget.ts index 18358b8efcb..a610065bf8a 100644 --- a/src/lib/litegraph/src/widgets/BaseWidget.ts +++ b/src/lib/litegraph/src/widgets/BaseWidget.ts @@ -439,17 +439,6 @@ export abstract class BaseWidget this.bindRegisteredState(nodeId) } - /** - * Drops the entry this widget is bound to, for a widget the node has just - * refused. Its entry sits under the name it registered, which no widget - * holds any more — and `registerWidget` keeps an existing value when a later - * widget of the same type takes that name, so leaving it hands the next - * widget of that name a dead one's value. - * - * The entry is found by identity rather than by this widget's current name: - * a refused duplicate's name is by definition the one another widget kept, - * and that widget's entry must not be touched. - */ releaseRegisteredState(): void { const graphId = this.node.graph?.rootGraph.id const { nodeId, name } = this._state diff --git a/src/scripts/domWidget.test.ts b/src/scripts/domWidget.test.ts index e8395a17e65..cca7e6e363f 100644 --- a/src/scripts/domWidget.test.ts +++ b/src/scripts/domWidget.test.ts @@ -107,11 +107,6 @@ describe('BaseDOMWidgetImpl.isVisible', () => { }) describe('addWidget on a node that refuses the widget', () => { - /** - * How the state is reached in the wild: an extension redefines `name` on an - * existing widget, so the duplicate cannot be renamed apart and is removed - * from the node (ADR-ECS-0008). - */ function pinName(widget: IBaseWidget, name: string): void { Object.defineProperty(widget, 'name', { value: name, diff --git a/src/types/widgetId.test.ts b/src/types/widgetId.test.ts index 09b881b7bd8..f2548687cd4 100644 --- a/src/types/widgetId.test.ts +++ b/src/types/widgetId.test.ts @@ -1,4 +1,4 @@ -import { beforeEach, describe, expect, it, vi } from 'vitest' +import { describe, expect, it, vi } from 'vitest' import type { WidgetId } from './widgetId' import { @@ -38,29 +38,17 @@ describe('ensureUniqueWidgetNames', () => { }) }) -/** - * A widget whose `name` is whatever a node pack actually assigned. The runtime - * type is the thing under test, so the narrowing happens once here rather than - * at each fixture. - */ -function widgetNamed(name: unknown): { name: string } { - return { name } as { name: string } +function widgetNamed(name: unknown): { name: unknown } { + return { name } } -/** - * The widgets the walk took off the array; the cause is asserted separately - * where it matters. Not every reported widget is removed — an - * `unresolved-duplicate` is reported and kept — and "was it removed" is what - * these cases are about. - */ -function refusedWidgets(widgets: T[]): T[] { +function refusedWidgets(widgets: T[]): T[] { return dropUnrenamableDuplicateWidgets(widgets) - .filter(({ removed }) => removed) + .filter(({ cause }) => cause !== 'unresolved-duplicate') .map(({ widget }) => widget) } -/** Every widget the walk reported, removed or not, against its cause. */ -function reportedCauses( +function reportedCauses( widgets: T[] ): [T, string][] { return dropUnrenamableDuplicateWidgets(widgets).map(({ widget, cause }) => [ @@ -70,17 +58,8 @@ function reportedCauses( } describe('dropUnrenamableDuplicateWidgets', () => { - beforeEach(() => { - // `ensureUniqueWidgetNames` warns whenever it gives up on a rename, which - // is the entry condition for every case here rather than the subject. - vi.spyOn(console, 'warn').mockImplementation(() => {}) - }) - - /** A name that cannot be written, which is how the state is reached. */ - const pinned = (name: string) => { - const widget = {} as { name: string } - Object.defineProperty(widget, 'name', { value: name, enumerable: true }) - return widget + function pinned(name: string): { name: string } { + return Object.defineProperty({ name }, 'name', { writable: false }) } it('refuses nothing and mutates nothing when every name is already unique', () => { @@ -107,8 +86,6 @@ describe('dropUnrenamableDuplicateWidgets', () => { }) it('renames the collisions the refusal was masking', () => { - // `ensureUniqueWidgetNames` is all-or-nothing, so one unrenamable widget - // leaves every other collision on the node standing too. const refused = pinned('seed') const widgets = [ { name: 'seed' }, @@ -128,8 +105,6 @@ describe('dropUnrenamableDuplicateWidgets', () => { it('does not hand a generated name to a widget that already holds it', () => { const refused = pinned('seed') const widgets = [{ name: 'seed' }, refused, { name: 'seed' }] - // `seed#1` is held outright further down the array, so the rename must - // reach past it rather than collide with a name nothing renamed. widgets.push({ name: 'seed#1' }) expect(refusedWidgets(widgets)).toEqual([refused]) @@ -150,13 +125,6 @@ describe('dropUnrenamableDuplicateWidgets', () => { const unrenamable = pinned('seed') const widgets = [{ name: 'seed' }, unrenamable, stubborn] - // Its descriptor has a setter, so a descriptor check believes the rename - // will take; only reading the name back afterwards proves it did not. That - // read is what makes the pair *observable* — but it cannot decide removal, - // because `BaseWidget`'s own setter declines exactly this way whenever the - // store has no entry for the node, which is the ordinary state of a node - // carrying an ambiguous pair. The pinned widget beside it is removed; this - // one is kept and reported. expect(reportedCauses(widgets)).toEqual([ [unrenamable, 'duplicate-name'], [stubborn, 'unresolved-duplicate'] @@ -176,17 +144,8 @@ describe('dropUnrenamableDuplicateWidgets', () => { const reported = dropUnrenamableDuplicateWidgets(widgets) expect(reported).toEqual([ - { - widget: declining, - cause: 'unresolved-duplicate', - removed: false, - // The key the walk read, not what the setter left behind — the caller - // must never re-read an accessor the walk has already written to. - name: 'seed' - } + { widget: declining, cause: 'unresolved-duplicate', name: 'seed' } ]) - // Still on the array: removing it would cost the user a widget to repair a - // state a later commit can resolve on its own. expect(widgets).toHaveLength(2) expect(widgets[1]).toBe(declining) }) @@ -199,10 +158,6 @@ describe('dropUnrenamableDuplicateWidgets', () => { } const widgets = [{ name: 'seed' }, hostile] - // A name that cannot be read is a `WidgetId` that cannot be derived, and - // leaving it on the node makes `ensureUniqueWidgetNames` fail on every - // later call — which bails registration for the whole node, including the - // widgets that are perfectly addressable. The throw must not escape. expect(refusedWidgets(widgets)).toEqual([hostile]) expect(widgets).toHaveLength(1) }) @@ -212,17 +167,11 @@ describe('dropUnrenamableDuplicateWidgets', () => { const second = widgetNamed(undefined) const widgets = [first, second] - // `undefined` is a bad identity, not a missing one: two of them collide - // with each other and would mint the same `graphId:nodeId:undefined`. expect(refusedWidgets(widgets)).toEqual([]) expect(widgets.map(({ name }) => name)).toEqual([undefined, 'undefined#1']) }) it('refuses a name that reads fine but cannot become an id', () => { - // Both of these read without throwing and then fail on the way to a - // `WidgetId`: one will not coerce to a string at all, the other is a lone - // surrogate that `encodeURIComponent` rejects. Letting either escape wedges - // the commit that is trying to settle the node's names. const unstringifiable = widgetNamed(Object.create(null)) const unencodable = { name: '\uD800' } const fine = { name: 'seed' } @@ -238,12 +187,6 @@ describe('dropUnrenamableDuplicateWidgets', () => { }) it('refuses a name that cannot be encoded into an id, but keeps an empty one', () => { - // `String(Symbol())` succeeds, so coercion alone says this name is fine — - // but `widgetId` encodes the raw value and throws on it. - // - // An empty name is the opposite case and must NOT be refused: it mints an - // id the store declines to key on, which costs the widget nothing, while - // deleting it loses a widget that renders and serializes. const symbolNamed = widgetNamed(Symbol('seed')) const empty = widgetNamed('') const fine = widgetNamed('seed') @@ -254,8 +197,6 @@ describe('dropUnrenamableDuplicateWidgets', () => { }) it('reports the name the walk read, not one the rename attempts left behind', () => { - // The walk writes to a colliding widget before giving up, so the value the - // accessor holds afterwards can be a candidate no widget on the node owns. const first = widgetNamed('seed') let stored = 'seed' const normalising = { @@ -275,11 +216,6 @@ describe('dropUnrenamableDuplicateWidgets', () => { }) it('records why each widget was refused, rather than leaving it to be guessed', () => { - // A hostile accessor need not answer the same way twice, so the cause has - // to come from the walk that made the decision. - // Reads 1 and 2 are the reserved-names pass and the walk itself; a third - // read — which is what re-deriving the cause at the report site costs — - // succeeds and would call this a duplicate instead. let reads = 0 const flaky = { get name(): string { @@ -302,63 +238,42 @@ describe('dropUnrenamableDuplicateWidgets', () => { 'unreadable-name', 'duplicate-name' ]) - // The widget now reads as a plain duplicate, which is the wrong answer. expect(flaky.name).toBe('seed') }) it('removes a duplicate whose `name` is a getter-only accessor on its prototype', () => { const first = { name: 'seed' } - // No *own* `name` descriptor, and the inherited one has no setter — so - // every write throws and is swallowed, exactly like the non-writable own - // property above. A predicate that inspects only the own object finds - // nothing and falls through to `Object.isExtensible`, which answers whether - // properties can be *added*, not whether `name` can be written. That makes - // this widget look renamable and keeps it forever as an unresolved - // duplicate, silently sharing `first`'s identity — the precise case - // removal exists for. - const inherited = Object.create({ + const inherited: { name: unknown } = Object.create({ get name() { return 'seed' } - }) as { name: string } + }) + const widgets = [first, inherited] - const refused = dropUnrenamableDuplicateWidgets([first, inherited]) + const refused = dropUnrenamableDuplicateWidgets(widgets) expect(refused.map(({ cause }) => cause)).toEqual(['duplicate-name']) - expect(refused.map(({ removed }) => removed)).toEqual([true]) + expect(widgets).toEqual([first]) }) it('refuses a widget whose descriptor trap throws instead of aborting the walk', () => { const first = { name: 'seed' } - const target = {} - Object.defineProperty(target, 'name', { - value: 'seed', - writable: false, - configurable: true + const target = Object.defineProperty({ name: 'seed' }, 'name', { + writable: false }) - // `nameIsWritable` is reached from `resolveCollision`, which — unlike the - // `name` reads in the same walk — is not inside a guard, and - // `getOwnPropertyDescriptor`/`isExtensible` both invoke proxy traps. A - // throwing trap used to escape the whole walk, which runs inside - // `LGraph.add` after node state is partly attached. const hostile = new Proxy(target, { getOwnPropertyDescriptor() { throw new Error('hostile descriptor trap') } - }) as { name: string } + }) const widgets = [first, hostile] expect(() => dropUnrenamableDuplicateWidgets(widgets)).not.toThrow() - // Unaddressable, so refused — and the widget holding the name legitimately - // is still there, which a mid-walk throw would have left undecided. expect(widgets).toEqual([first]) }) it('collides names that differ as values but coincide as id strings', () => { - // `widgetId` keys on `encodeURIComponent(String(name))`, so these two mint - // the same id. Comparing the raw values lets both through and the clash - // lands in the store, where nothing is looking for it. const widgets = [ widgetNamed(undefined), { name: 'undefined' }, @@ -375,23 +290,16 @@ describe('dropUnrenamableDuplicateWidgets', () => { ]) }) - it('offers another name when a setter rejects only the first one', () => { - // `BaseWidget` delegates its `name` setter to the store, which refuses to - // move onto an id something else already holds. Refusal deletes a widget, - // so one rejected candidate must not be read as unrenamable. - let name = 'seed' - const picky = { - get name() { - return name - }, - set name(value: string) { - if (value !== 'seed#1') name = value - } - } - const widgets = [{ name: 'seed' }, picky] + it('skips a candidate name that is already taken outside the array', () => { + const widgets = [{ name: 'seed' }, { name: 'seed' }] - expect(refusedWidgets(widgets)).toEqual([]) - expect(widgets.map((widget) => widget.name)).toEqual(['seed', 'seed#2']) + const refused = dropUnrenamableDuplicateWidgets( + widgets, + (name) => name === 'seed#1' + ) + + expect(refused).toEqual([]) + expect(widgets.map(({ name }) => name)).toEqual(['seed', 'seed#2']) }) it('does not reserve a name one widget rejected against the next widget', () => { @@ -407,11 +315,7 @@ describe('dropUnrenamableDuplicateWidgets', () => { const renamable = { name: 'seed' } const widgets = [{ name: 'seed' }, stubborn, renamable] - // Nothing is removed: `stubborn` declined the write but could have taken - // it, so it is reported and kept. expect(refusedWidgets(widgets)).toEqual([]) - // `seed#1` was offered to `stubborn` and did not take, so it is still free - // for the next widget — a name one setter refuses is not a name in use. expect(offered).toContain('seed#1') expect(widgets.map((widget) => widget.name)).toEqual([ 'seed', @@ -424,8 +328,6 @@ describe('dropUnrenamableDuplicateWidgets', () => { const refused = pinned('seed') const widgets = [{ name: 'seed' }, refused, refused] - // The identity bypass that keeps a reordering widget in place must not - // re-admit one whose first occurrence was already refused and reported. expect(refusedWidgets(widgets)).toEqual([refused]) expect(widgets.map(({ name }) => name)).toEqual(['seed']) }) @@ -435,7 +337,6 @@ describe('dropUnrenamableDuplicateWidgets', () => { const other = pinned('seed') const widgets = [shared, shared, other] - // Identity duplicates are one widget mid-reorder, not a name collision. expect(refusedWidgets(widgets)).toEqual([other]) expect(widgets).toEqual([shared, shared]) }) diff --git a/src/types/widgetId.ts b/src/types/widgetId.ts index fd4d165e351..8b0d971891a 100644 --- a/src/types/widgetId.ts +++ b/src/types/widgetId.ts @@ -30,7 +30,7 @@ export function widgetId( * and the removal criterion read it, deliberately, so the two cannot disagree * about the same widget. */ -function nameIsWritable(widget: { name: string }): boolean { +function nameIsWritable(widget: object): boolean { try { // The whole chain: `BaseWidget` declares `name` as a class accessor, so an // instance has no own descriptor and would fall through to extensibility, @@ -112,41 +112,17 @@ export function ensureUniqueWidgetNames( } } -/** - * A `name` from which no identity can be derived — the accessor threw, the - * value would not coerce to a string, or the result is not something - * {@link widgetId} can encode. Distinct from a widget whose name *is* - * `undefined`: that one has an identity, a bad one, and two of them collide - * with each other. - */ const UNREADABLE_NAME = Symbol('unreadable widget name') -/** - * Why a widget could not be given a unique name on its node. - * - * `unresolved-duplicate` is the one cause that does **not** remove the widget: - * the rename did not land, but the write was structurally possible, so the - * failure is recoverable and losing the widget would be worse than carrying - * the ambiguity. See {@link nameIsWritable}. - */ -type WidgetRefusalCause = - | 'unreadable-name' - | 'duplicate-name' - | 'unresolved-duplicate' - /** * A widget the walk could not name uniquely. The cause and the name come from * the walk rather than from another read of the accessor: a hostile one need * not answer twice the same way, and the walk may have written to it. */ -export interface RefusedWidget { - widget: T - cause: WidgetRefusalCause - /** Whether the walk removed {@link widget} from the array it was given. */ - removed: boolean - /** The key the walk read, or `undefined` when no key could be derived. */ - name: string | undefined -} +export type RefusedWidget = + | { widget: T; cause: 'unreadable-name'; name: undefined } + | { widget: T; cause: 'duplicate-name'; name: string } + | { widget: T; cause: 'unresolved-duplicate'; name: string } /** * The identity key `name` claims, or {@link UNREADABLE_NAME}. It is the key @@ -158,24 +134,21 @@ export interface RefusedWidget { * key on, which costs the widget nothing, and `addWidget('text', '', …)` is an * ordinary unlabeled widget that node packs ship (ADR-ECS-0008). */ -function readName(widget: { name: string }): string | typeof UNREADABLE_NAME { +function readName(widget: { name: unknown }): string | typeof UNREADABLE_NAME { try { - const raw: unknown = widget.name + const raw = widget.name + if (typeof raw === 'symbol') return UNREADABLE_NAME const key = String(raw) - // The raw value, as `widgetId` encodes it: a Symbol survives `String()` - // and throws here. - encodeURIComponent(raw as string) + encodeURIComponent(key) return key } catch { return UNREADABLE_NAME } } -/** @returns whether {@link widget} now answers to {@link name}. */ -function tryRename(widget: { name: string }, name: string): boolean { +function tryRename(widget: { name: unknown }, name: string): boolean { try { widget.name = name - // A setter is free to ignore the write, and only a read proves it did not. return widget.name === name } catch { return false @@ -183,12 +156,11 @@ function tryRename(widget: { name: string }, name: string): boolean { } /** Whether no identity key can be read from {@link widget}'s `name`. */ -export function isWidgetNameUnreadable(widget: { name: string }): boolean { +export function isWidgetNameUnreadable(widget: { name: unknown }): boolean { return readName(widget) === UNREADABLE_NAME } -/** Every name key the array already holds outright, skipping unreadable ones. */ -function readableNames(widgets: readonly { name: string }[]): Set { +function readableNames(widgets: readonly { name: unknown }[]): Set { const names = new Set() for (const widget of widgets) { const name = readName(widget) @@ -197,75 +169,40 @@ function readableNames(widgets: readonly { name: string }[]): Set { return names } -/** - * The first `name#n` no set in {@link taken} claims — so a generated name never - * collides with one a widget further down the array holds outright. - */ function freeSuffixedName( name: string, - taken: readonly ReadonlySet[] + isTaken: (candidate: string) => boolean ): string { let index = 1 - while (taken.some((names) => names.has(`${name}#${index}`))) index++ + while (isTaken(`${name}#${index}`)) index++ return `${name}#${index}` } -/** - * How many names a colliding widget is offered before the pair is reported - * unresolved. More than one, because `BaseWidget`'s setter declines a move onto - * an id the store already holds, so one stale entry can reject a candidate the - * widget would otherwise take. - */ -const RENAME_ATTEMPTS = 4 - -/** - * Renames {@link widget} to the first free `name#n` that the write actually - * takes, setting aside each candidate the setter rejects so the next attempt - * offers a different one. - * - * @returns the name it now answers to, or `undefined` if no attempt stuck. - */ -function renameApart( - widget: { name: string }, - name: string, - used: ReadonlySet, - reserved: ReadonlySet -): string | undefined { - // Rejected candidates are tracked per widget, not reserved globally: a name - // this widget's setter would not take is still free for the next widget. - const rejected = new Set() - for (let attempt = 0; attempt < RENAME_ATTEMPTS; attempt++) { - const candidate = freeSuffixedName(name, [used, reserved, rejected]) - if (tryRename(widget, candidate)) return candidate - rejected.add(candidate) - } - return undefined -} - /** * Renamed apart and kept, kept but reported, or refused. Adds to - * `used`/`reserved` when an attempt sticks. + * `used`/`reserved` when the rename sticks. * * A rename that did not land is not proof of an unaddressable widget, so * {@link nameIsWritable} decides removal and the unresolved pair is reported * instead (ADR-ECS-0008). */ function resolveCollision( - widget: { name: string }, + widget: { name: unknown }, key: string, used: Set, - reserved: Set -): { keep: boolean; cause?: WidgetRefusalCause } { - const unique = renameApart(widget, key, used, reserved) - if (unique !== undefined) { - used.add(unique) - reserved.add(unique) - return { keep: true } - } - if (nameIsWritable(widget)) { - return { keep: true, cause: 'unresolved-duplicate' } + reserved: Set, + isNameTaken: (name: string) => boolean +): 'renamed' | 'unresolved-duplicate' | 'duplicate-name' { + const candidate = freeSuffixedName( + key, + (name) => used.has(name) || reserved.has(name) || isNameTaken(name) + ) + if (tryRename(widget, candidate)) { + used.add(candidate) + reserved.add(candidate) + return 'renamed' } - return { keep: false, cause: 'duplicate-name' } + return nameIsWritable(widget) ? 'unresolved-duplicate' : 'duplicate-name' } /** @@ -278,43 +215,35 @@ function resolveCollision( * setter that accepts and ignores it cannot report success, and a widget it * cannot rename does not strand the collisions that would have resolved. * - * @returns every widget it could not name uniquely, with the cause and whether - * it was removed, in array order. + * @param isNameTaken whether a candidate name is already held outside + * {@link widgets}, such as by a store entry the rename would be refused onto. + * @returns every widget it could not name uniquely, with the cause, in array + * order. Every cause but `unresolved-duplicate` was removed. */ -export function dropUnrenamableDuplicateWidgets( - widgets: T[] +export function dropUnrenamableDuplicateWidgets( + widgets: T[], + isNameTaken: (name: string) => boolean = () => false ): RefusedWidget[] { const kept: T[] = [] const refused: RefusedWidget[] = [] const used = new Set() const reserved = readableNames(widgets) - /** Every widget already walked, against whether that walk kept it. */ const verdicts = new Map() for (const widget of widgets) { - // The same widget object may occupy a second slot mid-reorder. That is one - // widget, not a collision — but it has to follow the verdict its first - // occurrence got, or a refused widget is re-admitted by its own repeat. const previous = verdicts.get(widget) if (previous !== undefined) { if (previous) kept.push(widget) continue } - const name = readName(widget) - if (name === UNREADABLE_NAME) { + const key = readName(widget) + if (key === UNREADABLE_NAME) { verdicts.set(widget, false) - refused.push({ - widget, - cause: 'unreadable-name', - removed: true, - name: undefined - }) + refused.push({ widget, cause: 'unreadable-name', name: undefined }) continue } - // `readName` already returned the key, not the raw value. - const key = name if (!used.has(key)) { used.add(key) verdicts.set(widget, true) @@ -322,18 +251,13 @@ export function dropUnrenamableDuplicateWidgets( continue } - const outcome = resolveCollision(widget, key, used, reserved) - verdicts.set(widget, outcome.keep) - if (outcome.keep) kept.push(widget) - if (outcome.cause) { - // `key`, not a re-read: the walk may have written to the name since. - refused.push({ - widget, - cause: outcome.cause, - removed: !outcome.keep, - name: key - }) - } + const outcome = resolveCollision(widget, key, used, reserved, isNameTaken) + const keep = outcome !== 'duplicate-name' + verdicts.set(widget, keep) + if (keep) kept.push(widget) + // `key`, not a re-read: the walk may have written to the name since. + if (outcome !== 'renamed') + refused.push({ widget, cause: outcome, name: key }) } if (refused.length) widgets.splice(0, widgets.length, ...kept) From f4ad04fb8acbdd91b8e3d2ee9f47771e62c16771 Mon Sep 17 00:00:00 2001 From: Alexander Brown Date: Mon, 5 Oct 2026 07:53:56 +0000 Subject: [PATCH 25/35] test(widgets): fold the two duplicate-name specs into one with shared setup One spec owns the node-type patch, the save-and-read recipe and a test-scoped workflow name that its fixture deletes, instead of two copies and a describe-scoped variable. The renamable case asserts the resolved names and values rather than repeating the arity the exact equality already implies. Amp-Thread-ID: https://ampcode.com/threads/T-01a1086c-5c03-7118-b269-6b6fda4d1cec --- .../tests/widgets/uniqueWidgetName.spec.ts | 161 ++++++++++++++++++ 1 file changed, 161 insertions(+) create mode 100644 browser_tests/tests/widgets/uniqueWidgetName.spec.ts diff --git a/browser_tests/tests/widgets/uniqueWidgetName.spec.ts b/browser_tests/tests/widgets/uniqueWidgetName.spec.ts new file mode 100644 index 00000000000..2699485ed48 --- /dev/null +++ b/browser_tests/tests/widgets/uniqueWidgetName.spec.ts @@ -0,0 +1,161 @@ +import { expect } from '@playwright/test' +import type { Locator, Page } from '@playwright/test' + +import type { ComfyPage } from '@e2e/fixtures/ComfyPage' +import { comfyPageFixture } from '@e2e/fixtures/ComfyPage' +import { TestIds } from '@e2e/fixtures/selectors' +import { openWorkflowFromSidebar } from '@e2e/fixtures/utils/builderTestUtils' + +import { zComfyWorkflow } from '@/platform/workflow/validation/schemas/workflowSchema' + +const NODE_TYPE = 'DevToolsNodeWithOutputList' + +const test = comfyPageFixture.extend<{ workflowName: string }>({ + workflowName: async ({ comfyPage }, use, testInfo) => { + const name = `unique-widget-name-${testInfo.parallelIndex}-${testInfo.retry}-${Date.now()}` + await use(name) + await comfyPage.workflow.deleteWorkflow(name) + } +}) + +async function addNodeWithWidgets( + comfyPage: ComfyPage, + widgets: { first: string; second: string; pinSecondAs?: string } +): Promise<{ node: Locator; nodeId: string }> { + await comfyPage.nodeOps.clearGraph() + await comfyPage.page.evaluate( + ({ nodeTypeName, first, second, pinSecondAs }) => { + const nodeType = window.LiteGraph!.registered_node_types[nodeTypeName] + const onNodeCreated = nodeType.prototype.onNodeCreated + nodeType.prototype.onNodeCreated = function (...args) { + onNodeCreated?.apply(this, args) + this.serialize_widgets = true + this.addWidget('string', first, 'first default', () => {}) + const added = this.addWidget( + 'string', + second, + 'second default', + () => {} + ) + if (pinSecondAs === undefined) return + Object.defineProperty(added, 'name', { + value: pinSecondAs, + writable: false, + configurable: false + }) + } + }, + { nodeTypeName: NODE_TYPE, ...widgets } + ) + const nodeId = await comfyPage.searchBoxV2.addNodeAndGetId( + 'Node With Output List' + ) + return { node: comfyPage.vueNodes.getNodeLocator(nodeId), nodeId } +} + +function widgetRowsNamed( + comfyPage: ComfyPage, + scope: Locator | Page, + name: string +): Locator { + return scope.getByTestId(TestIds.widgets.widget).filter({ + has: comfyPage.page + .getByTestId(TestIds.widgets.layoutFieldLabel) + .and(comfyPage.page.getByText(name, { exact: true })) + }) +} + +async function saveWidgetValues( + comfyPage: ComfyPage, + workflowName: string +): Promise { + const savedRequest = comfyPage.page.waitForRequest( + (request) => + request.method() === 'POST' && + decodeURIComponent(new URL(request.url()).pathname).endsWith( + `/workflows/${workflowName}.json` + ) + ) + await comfyPage.menu.topbar.saveWorkflowAs(workflowName) + const saved = zComfyWorkflow.parse( + JSON.parse((await savedRequest).postData() ?? '{}') + ) + return saved.nodes.find(({ type }) => type === NODE_TYPE)?.widgets_values +} + +test.describe( + 'unique widget names', + { tag: ['@canvas', '@widget', '@vue-nodes'] }, + () => { + test('refuses the widget it cannot name uniquely and keeps the node usable', async ({ + comfyPage, + workflowName + }) => { + const { node } = await addNodeWithWidgets(comfyPage, { + first: 'duplicate', + second: 'second', + pinSecondAs: 'duplicate' + }) + const duplicateRows = widgetRowsNamed(comfyPage, node, 'duplicate') + + await test.step('the canvas shows one widget under the name, not two', async () => { + await expect(duplicateRows).toHaveCount(1) + }) + + await test.step('what the user types is what the app saves', async () => { + const input = duplicateRows.locator('input') + await input.fill('typed by the user') + await input.blur() + + expect(await saveWidgetValues(comfyPage, workflowName)).toEqual([ + 'typed by the user' + ]) + }) + + await test.step('and it is still there after closing and reopening', async () => { + await comfyPage.workflow.newBlankWorkflow() + await comfyPage.menu.topbar.closeWorkflowTab(workflowName) + await openWorkflowFromSidebar(comfyPage, workflowName) + + const reopened = widgetRowsNamed(comfyPage, comfyPage.page, 'duplicate') + await expect(reopened).toHaveCount(1) + await expect(reopened.locator('input')).toHaveValue('typed by the user') + }) + }) + + test('renames a duplicate formed while the node was detached when it rejoins', async ({ + comfyPage, + workflowName + }) => { + const { node, nodeId } = await addNodeWithWidgets(comfyPage, { + first: 'alpha', + second: 'beta' + }) + await expect(node.getByTestId(TestIds.widgets.widget)).toHaveCount(2) + + await comfyPage.page.evaluate((id) => { + const graph = window.app!.graph + const added = graph.nodes.find( + (candidate) => String(candidate.id) === id + ) + const beta = added?.widgets?.find(({ name }) => name === 'beta') + if (!added || !beta) throw new Error(`node ${id} has no beta widget`) + graph.remove(added) + beta.name = 'alpha' + graph.add(added) + }, nodeId) + + await test.step('both widgets are still drawn after the re-add', async () => { + await expect(widgetRowsNamed(comfyPage, node, 'alpha')).toHaveCount(1) + await expect(widgetRowsNamed(comfyPage, node, 'alpha#1')).toHaveCount(1) + }) + + await test.step('and the node saves both values', async () => { + expect(await saveWidgetValues(comfyPage, workflowName)).toEqual([ + 'first default', + 'second default' + ]) + }) + }) + } +) From 77304f80ed6a64b26bd93433ac472e2f74fde79c Mon Sep 17 00:00:00 2001 From: Alexander Brown Date: Mon, 5 Oct 2026 07:54:09 +0000 Subject: [PATCH 26/35] docs(adr): condense the ECS-0008 unique-name amendment to the decision Amp-Thread-ID: https://ampcode.com/threads/T-01a1086c-5c03-7118-b269-6b6fda4d1cec --- docs/adr/ECS-0008-entity-component-system.md | 158 ++++++------------- 1 file changed, 46 insertions(+), 112 deletions(-) diff --git a/docs/adr/ECS-0008-entity-component-system.md b/docs/adr/ECS-0008-entity-component-system.md index b9693864aa8..16123421982 100644 --- a/docs/adr/ECS-0008-entity-component-system.md +++ b/docs/adr/ECS-0008-entity-component-system.md @@ -182,125 +182,59 @@ legitimate re-mint rather than an identity collision — which is why > **Amended (2026-10-04):** "two widgets on one node cannot share a name" is an > **invariant**, not a limitation to work around. A second widget under a name -> another widget already holds is not a second identity; it is the same -> identity twice, and nothing downstream can tell the two apart. +> another widget already holds is the same identity twice, and nothing +> downstream can tell the two apart. > -> The repeat is renamed to `name#1` before any id is derived. Where it cannot -> be — a `name` that cannot be written at all — the widget is **refused**: it -> is dropped from `node.widgets` and reported. A widget whose name yields no id -> at all is refused the same way, and that is not only an accessor that throws: -> a value that will not coerce to a string and one `encodeURIComponent` rejects -> are the same failure (`src/types/widgetId.ts`). First occurrence wins; -> renamable collisions elsewhere on the node are still renamed. +> A repeat is renamed to the first `name#n` that neither the node nor the +> store holds. A widget whose `name` cannot be written at all is **refused**: +> it is dropped from `node.widgets`, its own store entry is released, and the +> refusal is reported. A widget whose name yields no id (an accessor that +> throws, a value that will not coerce to a string, or one +> `encodeURIComponent` rejects) is refused the same way. First occurrence +> wins. > -> **Refusal keys on whether the write was possible, not on whether it landed, -> and the difference is load-bearing.** `BaseWidget.set name` delegates to -> `widgetValueStore.renameWidget()` and returns without changing the name -> whenever the store declines — which it does when the node has no entries, -> precisely the state an ambiguous pair leaves a node in and the state a node -> is in after it has been removed from the graph. So a failed read-back is a -> recoverable store refusal at least as often as it is a hostile object, and -> removing on it destroys ordinary, renamable widgets on the very nodes this -> repairs: a node deleted and undone comes back a widget short, saving one -> `widgets_values` entry for a two-widget node. The read-back still decides -> whether the pair is **reported**; `nameIsWritable` decides whether the widget -> is **removed**, and it is deliberately the same predicate -> `ensureUniqueWidgetNames` uses to decide it may rename at all — `setNodeId` -> gates registration on that, so two copies of the rule disagreeing is a widget -> destroyed over a disagreement. +> Removal keys on whether the write was _possible_, not on whether it landed. +> A writable widget whose rename is declined anyway is **kept** and reported, +> because removing it costs the user a widget and a saved value. Since a +> rename with no store entry to move now lands locally, that state comes only +> from a setter that accepts a write and ignores it. > -> Four stable `errorType`s, because the causes need different alerts and -> collapsing them sends whoever reads one after a collision that does not -> exist: `failure_renaming_widget_duplicate_name` for a duplicate that could -> not be renamed apart, `failure_reading_widget_name` for a widget no id can be -> derived from, `failure_resolving_widget_duplicate_name` for a pair the node -> **keeps**, and `failure_tearing_down_refused_widget` for a removal whose own -> teardown threw. The third is not a report of lost widgets, but it is not -> transient either: a kept pair now comes only from a setter that accepts a -> write and ignores it, which no later commit resolves, so the report is -> deduplicated per name rather than repeated per commit. +> Four stable `errorType`s distinguish the outcomes: +> `failure_renaming_widget_duplicate_name` (refused duplicate), +> `failure_reading_widget_name` (no derivable id), +> `failure_resolving_widget_duplicate_name` (kept duplicate, reported once per +> widget rather than on every commit) and `failure_tearing_down_refused_widget` +> (a refused widget's own teardown threw). > -> **There are two enforcement points, and looking only at the first one is -> misleading.** `attachNodeToStores` calls `refuseAmbiguousNodeWidgets` as a -> node joins a graph, which is the one that catches a node built detached and -> then added. `syncWidgetOrder` catches every later mutation — `node.widgets` -> is a mutation view, so `addWidget`, a raw `push`, a splice and a whole-array -> assignment all commit through it — but it enforces nothing until `graphId` -> exists, so it does not cover the join itself. +> There are two enforcement points: `attachNodeToStores` as a node joins a +> graph, and `syncWidgetOrder` for every later `node.widgets` mutation +> (`addWidget`, a raw `push`, a splice, a whole-array assignment). Their +> boundaries are part of the decision: > -> These boundaries are part of the decision: +> - Enforcement starts at the join, not during construction: no `WidgetId` +> exists before then, and `litegraphService` still matches a freshly created +> widget by name. +> - Renamability is judged after `toConcreteWidget`, which gives a raw widget +> the class's writable `name`. +> - An empty name is declined by the store, not refused: that widget still +> renders, fires its callback and serializes. +> - Redefining a `name` is not an array mutation, so a name pinned after the +> join stands until the next `node.widgets` mutation. +> - `SubgraphNode` replaces `widgets` with a computed getter, so neither point +> runs on it and an ambiguous pair there keeps the previous behaviour. +> - A refusal shifts the positional values of a workflow saved before this +> change. That needs a widget whose `name` cannot be written and no saved +> name register, and it is accepted: an index map built at the join and read +> during restore would move values on every later load once it went stale. > -> - **Enforcement starts when the node joins a graph**, not when a detached -> node is built. No `WidgetId` exists before then, so there is no identity to -> collide over — and renaming during construction changes names that -> `litegraphService` still matches a freshly created widget on. `LGraph.add` -> normalizes the widgets view _before_ assigning `node.graph`, which is why -> the join needs its own call rather than falling out of that commit. -> - **Renamability is judged after normalization.** `toConcreteWidget` merges -> the concrete class's writable `name` accessor over a plain object's pinned -> one, so a raw widget that looks unrenamable usually is not. Normalizing -> first does mean `BaseWidget`'s constructor reads a hostile `name` before -> the refusal sees it, so the conversion is guarded **for that one case**: -> a widget whose name cannot be read falls through to be refused instead of -> throwing out of the commit and wedging every later one. Any other -> conversion failure still throws, because the refusal has no reason to drop -> that widget and swallowing it would leave an unconverted object on the node -> with nothing reported. The guard also only covers the commit path — a raw -> `push`, a splice, a whole-array assignment. `addCustomWidget` converts -> before it pushes, so `addWidget` and `addDOMWidget` with a hostile accessor -> still throw to their caller and never reach the refusal. And the verdict -> that decides whether to swallow is one read taken before the conversion, -> so a getter that answers _inconsistently_ — throwing on one read and not -> the next — can still land either way. Closing that needs the conversion to -> happen inside the walk, which is a larger change than this one; the trade -> is recorded here rather than left implicit. -> - **An un-keyable name is declined, not refused.** An empty name mints -> `graphId:nodeId:`, which the store will not key on. That widget still -> renders, still fires its callback and still serializes, so deleting it -> would lose a working widget and shift every positional value after it. -> Refusal is for a name that is _ambiguous_ with another widget's, not for -> one the store happens not to track. -> - **The two points cover array mutations and the join, not every way a name -> changes.** Redefining a `name` is not an array mutation, so an extension -> that adds a widget under a unique name in `onAdded` and then pins it onto -> an existing one leaves the ambiguous pair standing until some later -> `node.widgets` mutation commits. That is deliberate — enforcing on every -> property write would mean watching every widget — but it means "caught at -> the join" is true of the join itself, not of what `onAdded` does after it. -> - **`SubgraphNode` does not commit through this path, and neither -> enforcement point runs on it.** It redefines `widgets` as a computed getter -> over its promoted widgets and overrides `addCustomWidget`, so an ambiguous -> pair there keeps the pre-existing behaviour. The join-time call is gated on -> the node still exposing this module's mutation view: the getter rebuilds -> the array on every read, so a refusal there would splice a throwaway copy -> and report a refusal that did not happen. Two promoted inputs carrying the -> same inner widget name reach exactly that state, so the gate is -> load-bearing rather than defensive. -> - **A removal shifts the positional values of a workflow saved before it, and -> that is accepted here rather than fixed.** `LGraph.configure` adds each node -> before configuring it, so the refusal has already run by the time values are -> restored, and positional restore counts the widgets the node has _now_ — so -> for `[a, dup, b]` saved as `[1, 2, 3]`, `b` is handed `2` and `3` is -> dropped. It takes all three of a pre-change workflow, a widget whose `name` -> cannot be written, and no name register: a renamable duplicate is kept -> rather than removed, and a saved `widgets_values_named` restores each widget -> under its own name instead. All three measured at this head in -> `widgetsView.refusalValueRestore.test.ts`. Carrying the refused widget's -> original slot through `createWidgetRestorationState` as an index map would -> close the remainder; it is not done here because that record has to be built -> at the join and read back during restore, and a stale one would move values -> on every later load — a worse failure than the one it fixes. +> A serialized `(name, occurrence)` identity was proposed instead +> ([#19717](https://github.com/Comfy-Org/ComfyUI_frontend/pull/19717)) and +> rejected: it adds a second widget-identity format to preserve a state that +> should not occur. > -> A serialized `(name, occurrence)` identity was proposed instead, so that both -> widgets could be persisted ([#19717](https://github.com/Comfy-Org/ComfyUI_frontend/pull/19717)). -> It was rejected: it adds a second widget-identity format, read by one -> register and by nothing else, to preserve a state that should not occur. The -> fix belongs where the state is created. -> -> Refusing is also a repair, not only a restriction. Before it, a node carrying -> an ambiguous pair registered **no** widget in the store — `BaseWidget.setNodeId` -> bails for every widget on the node — so nothing the user typed on that node -> survived a reload. +> Before this, a node carrying an ambiguous pair registered **no** widget in the +> store, because `BaseWidget.setNodeId` bails for every widget on the node, so +> nothing the user typed on that node survived a reload. #### Future work From c1596dcfc93ec543a41a844ae87a0821b234f17a Mon Sep 17 00:00:00 2001 From: Alexander Brown Date: Mon, 5 Oct 2026 08:20:43 +0000 Subject: [PATCH 27/35] refactor(widgets): drop explanatory comments from the unique-name change Two orderings the comments carried are now tests: a refused widget's onRemove still sees its store entry, and a name read once before conversion decides whether a conversion failure is swallowed. --- .../graph/nodeShell/nodeShellLifecycle.ts | 2 - src/lib/litegraph/src/LGraphNode.ts | 3 - .../node/widgetsView.refusalCriterion.test.ts | 6 -- src/lib/litegraph/src/node/widgetsView.ts | 63 +------------------ .../node/widgetsView.uniqueWidgetName.test.ts | 31 ++++++++- src/lib/litegraph/src/widgets/BaseWidget.ts | 12 ---- src/scripts/domWidget.ts | 4 -- src/types/widgetId.ts | 58 ----------------- 8 files changed, 32 insertions(+), 147 deletions(-) diff --git a/src/core/graph/nodeShell/nodeShellLifecycle.ts b/src/core/graph/nodeShell/nodeShellLifecycle.ts index cd6c52cfa3f..314fee1313a 100644 --- a/src/core/graph/nodeShell/nodeShellLifecycle.ts +++ b/src/core/graph/nodeShell/nodeShellLifecycle.ts @@ -31,8 +31,6 @@ export function attachNodeToStores( } if (!node.widgets) return - // The node now has a graph and its final id, so this is the first moment a - // `WidgetId` exists to collide over (ADR-ECS-0008). refuseAmbiguousNodeWidgets(node) for (const widget of node.widgets) { if (isNodeBindable(widget)) widget.setNodeId(node.id) diff --git a/src/lib/litegraph/src/LGraphNode.ts b/src/lib/litegraph/src/LGraphNode.ts index f84221f8270..89494de013e 100644 --- a/src/lib/litegraph/src/LGraphNode.ts +++ b/src/lib/litegraph/src/LGraphNode.ts @@ -2309,9 +2309,6 @@ export class LGraphNode const widget = toConcreteWidget(custom_widget, this) this.widgets.push(widget) - // The push committed through the widgets view, which may have refused the - // widget (ADR-ECS-0008). Registering one the node no longer has would write - // over the widget that kept the name. if (!this.widgets.includes(widget)) return widget // Only register with store if node has a valid ID (is already in a graph). diff --git a/src/lib/litegraph/src/node/widgetsView.refusalCriterion.test.ts b/src/lib/litegraph/src/node/widgetsView.refusalCriterion.test.ts index 95db1d60f72..9cfa8920df8 100644 --- a/src/lib/litegraph/src/node/widgetsView.refusalCriterion.test.ts +++ b/src/lib/litegraph/src/node/widgetsView.refusalCriterion.test.ts @@ -36,13 +36,11 @@ describe('unique-name refusal criterion', () => { expect(storedNames(graph, node)).toEqual(['seed', 'steps']) - // Deletes the store entries and leaves `_state.nodeId` set. graph.remove(node) steps.name = 'seed' expect(steps.name).toBe('seed') - // Undo and paste both land here. graph.add(node) expect(node.widgets).toContain(seed) @@ -95,8 +93,6 @@ describe('unique-name refusal criterion', () => { node.addWidget('number', 'seed', 1, () => undefined, {}) const steps = node.addWidget('number', 'steps', 2, () => undefined, {}) - // Writable, so the widget must not be removed, and no candidate the walk - // offers can ever stick. Object.defineProperty(steps, 'name', { get: () => 'seed', set: () => undefined, @@ -108,8 +104,6 @@ describe('unique-name refusal criterion', () => { expect(node.widgets).toContain(steps) expect(reportedTypes()).toEqual(['failure_resolving_widget_duplicate_name']) - // Re-found by every later commit, and `reportError` has no dedupe of its - // own, so this would otherwise warn for the rest of the session. node.addWidget('number', 'denoise', 4, () => undefined, {}) node.widgets?.push( node.addWidget('number', 'guidance', 5, () => undefined, {}) diff --git a/src/lib/litegraph/src/node/widgetsView.ts b/src/lib/litegraph/src/node/widgetsView.ts index b0855173e06..b0cbfae44db 100644 --- a/src/lib/litegraph/src/node/widgetsView.ts +++ b/src/lib/litegraph/src/node/widgetsView.ts @@ -28,20 +28,11 @@ interface WidgetsViewState { commit: (widgets: IBaseWidget[]) => void } -/** - * The unresolved duplicates already reported for a node. A kept pair survives - * the walk, so every later commit finds it again, and `reportError` has no - * dedupe of its own. - */ const reportedUnresolved = new WeakMap>() const states = new WeakMap() const widgetsViewGetters = new WeakSet<() => IBaseWidget[] | undefined>() -/** - * Reads a property off a widget being refused. Every read here is hostile by - * definition, and a throw would escape after the array was spliced. - */ function safeRead(read: () => unknown): string | undefined { try { const value = read() @@ -61,11 +52,6 @@ function reportTeardownFailure(node: LGraphNode, error: unknown): void { }) } -/** - * Two bindings, because production uses both: promoted subgraph inputs hold a - * direct `_widget` reference, and an ordinary node binds by name and resolves - * on read. Matching only the reference finds nothing on these nodes. - */ function inputBindsWidget( input: INodeInputSlot, widget: IBaseWidget, @@ -88,17 +74,8 @@ function clearRefusedSlotBindings( } } -/** - * The teardown `LGraphNode.removeWidget` owes a widget it can no longer find, - * because the refusal already took it off the array. Every step is guarded: a - * throw here would leave the node and the store's order out of sync, and during - * `LGraph.add` a half-attached node. - */ function releaseRefusedWidget( node: LGraphNode, - // Nullish because a hole or an explicit `undefined` in `node.widgets` is - // refused like anything else, and matching the teardown on it would clear - // every input whose `_widget` is unset. widget: IBaseWidget | undefined, name: string | undefined ): void { @@ -116,7 +93,6 @@ function releaseRefusedWidget( reportTeardownFailure(node, error) } - // After `onRemove`, which may still read the value through the entry. try { if (widget instanceof BaseWidget) widget.releaseRegisteredState() } catch (error) { @@ -161,10 +137,6 @@ function refuseAmbiguousWidgets( return removed } -/** - * One alert per cause, because they are different failures: an unreadable name - * has no duplicate to go looking for, and a kept pair has lost nothing. - */ const REFUSAL_ALERTS: Record< RefusedWidget['cause'], { @@ -207,11 +179,6 @@ function reportRefusal( }) } -/** - * Whether {@link node} still exposes this module's mutation view, and so is - * subject to the invariant at all. `SubgraphNode` rebuilds `widgets` on every - * read, so on a promoted list a widget's absence means nothing. - */ function commitsThroughWidgetsView(node: LGraphNode): boolean { const descriptor = Object.getOwnPropertyDescriptor(node, 'widgets') return !!descriptor?.get && widgetsViewGetters.has(descriptor.get) @@ -224,35 +191,18 @@ export function wasWidgetRefused( return commitsThroughWidgetsView(node) && !node.widgets?.includes(widget) } -/** - * The second enforcement point: a node joining a graph. `LGraph.add` normalizes - * the view while `node.graph` is unset, so that commit mints no `WidgetId` and - * does not enforce. - * - * Gated on the node still owning its widgets list, because a refusal on - * `SubgraphNode`'s rebuilt array splices a throwaway copy while still reporting - * and tearing down a widget that is still there. Two promoted inputs sharing an - * inner widget name reach that state. - */ export function refuseAmbiguousNodeWidgets(node: LGraphNode): void { if (!commitsThroughWidgetsView(node)) return - // The raw target: splicing `node.widgets` would re-enter `syncWidgetOrder`. - const widgets = states.get(node)?.target - if (!widgets?.length) return - refuseAmbiguousWidgets(node, widgets) + const target = states.get(node)?.target + if (!target?.length) return + refuseAmbiguousWidgets(node, target) } function syncWidgetOrder(node: LGraphNode, widgets: IBaseWidget[]): void { node._widgetSlotsDirty = true const graphId = node.graph?.rootGraph.id - // `BaseWidget`'s constructor reads the source object's `name`, so a raw push - // whose accessor throws would throw out of this commit and every later one, - // wedging the node with a stale store order. Leave it unconverted for the - // refusal below instead. const concreteWidgets = widgets.map((widget) => { - // Before the conversion, not inside the catch: a hostile getter asked - // twice can answer differently. const unreadable = isWidgetNameUnreadable(widget) try { return toConcreteWidget(widget, node) @@ -265,18 +215,11 @@ function syncWidgetOrder(node: LGraphNode, widgets: IBaseWidget[]): void { widgets[index] = widget } - // No graph, no identity to collide over yet — and renaming earlier changes - // names that node construction still matches on. if (!graphId) return - // After normalization: `toConcreteWidget` merges the class's writable `name` - // accessor over a plain object's pinned one, so a widget judged unrenamable - // while still raw renames cleanly a line later. const refused = refuseAmbiguousWidgets(node, widgets) for (const widget of concreteWidgets) { - // By set, not `widgets.includes`: this runs on every commit, so a linear - // scan here is cubic over building a node. if (!refused.has(widget) && isNodeBindable(widget)) { widget.setNodeId(node.id) } diff --git a/src/lib/litegraph/src/node/widgetsView.uniqueWidgetName.test.ts b/src/lib/litegraph/src/node/widgetsView.uniqueWidgetName.test.ts index 6f498c88cb3..6fefa8d7b4b 100644 --- a/src/lib/litegraph/src/node/widgetsView.uniqueWidgetName.test.ts +++ b/src/lib/litegraph/src/node/widgetsView.uniqueWidgetName.test.ts @@ -249,8 +249,6 @@ describe('unique widget name invariant', () => { }) expect(() => node.widgets!.push(hostile)).not.toThrow() - // `indexOf` rather than `not.toContain`: the matcher deep-compares, which - // reads the getter and throws out of the assertion itself. expect(node.widgets!.indexOf(hostile)).toBe(-1) expect(() => @@ -266,6 +264,29 @@ describe('unique widget name invariant', () => { ) }) + it('converts a raw pushed widget whose name throws only on the first read', () => { + const node = createNode() + node.addWidget('number', 'seed', 1, () => undefined, {}) + let reads = 0 + const flaky: IBaseWidget = { + name: 'steps', + type: 'number', + value: 2, + y: 0, + options: {} + } + Object.defineProperty(flaky, 'name', { + get(): string { + reads++ + if (reads === 1) throw new Error('name is not readable yet') + return 'steps' + } + }) + + expect(() => node.widgets!.push(flaky)).not.toThrow() + expect(names(node)).toEqual(['seed', 'steps']) + }) + it('reports the cause the walk decided, not the one a later read suggests', () => { const node = createNode() node.addWidget('number', 'seed', 1, () => undefined, {}) @@ -489,9 +510,15 @@ describe('unique widget name invariant', () => { const kept = node.addWidget('number', 'seed', 1, () => undefined, {}) const refused = node.addWidget('number', 'seed', 2, () => undefined, {}) refused.value = 42 + const refusedId = widgetId(node.graph!.rootGraph.id, node.id, 'seed#1') + let valueSeenOnRemove: unknown + refused.onRemove = () => { + valueSeenOnRemove = useWidgetValueStore().getWidget(refusedId)?.value + } pinName(refused, 'seed') node.addWidget('number', 'steps', 0, () => undefined, {}) + expect(valueSeenOnRemove).toBe(42) expect(storedNames(node)).toEqual(['seed', 'steps']) expect(kept.value).toBe(1) expect( diff --git a/src/lib/litegraph/src/widgets/BaseWidget.ts b/src/lib/litegraph/src/widgets/BaseWidget.ts index a610065bf8a..5ed3e6430f8 100644 --- a/src/lib/litegraph/src/widgets/BaseWidget.ts +++ b/src/lib/litegraph/src/widgets/BaseWidget.ts @@ -146,22 +146,10 @@ export abstract class BaseWidget const previousId = widgetId(graphId, nodeId, previous) const registered = store.getWidget(previousId) - - // Nothing in the store answers to the old name, so there is nothing to keep - // consistent and the write is this widget's own business. `_state.nodeId` - // outlives `graph.remove`, which clears the node's entries, so declining - // here left a re-added node holding two widgets under one name: every - // `setNodeId` on it then bails on `ensureUniqueWidgetNames` and the node - // registers — and renders — no widgets at all. if (!registered) { this._name = value return } - - // `previousId` names whichever widget actually registered it, which need - // not be this one when two share a name. Moving an entry this widget is not - // bound to welds the pair onto one `WidgetState` with one value between - // them, and the rename still reads back as success. if (registered !== this._state) return const moved = store.renameWidget( diff --git a/src/scripts/domWidget.ts b/src/scripts/domWidget.ts index de4463cf3f6..d2fa9643194 100644 --- a/src/scripts/domWidget.ts +++ b/src/scripts/domWidget.ts @@ -330,8 +330,6 @@ export class ComponentWidgetImpl< export const addWidget = (node: LGraphNode, widget: BaseDOMWidget) => { node.addCustomWidget(widget) - // Registering a refused widget mounts its element over the canvas for a - // widget the graph does not have, and nothing unmounts it. if (wasWidgetRefused(node, widget)) return if (node.graph) { @@ -339,8 +337,6 @@ export const addWidget = (node: LGraphNode, widget: BaseDOMWidget) => { } node.onAdded = useChainCallback(node.onAdded, () => { - // The join is the first commit that can refuse, so a widget accepted - // above may not have survived it. if (wasWidgetRefused(node, widget)) return useDomWidgetStore().registerWidget(widget) }) diff --git a/src/types/widgetId.ts b/src/types/widgetId.ts index 8b0d971891a..dc0d1f5cca2 100644 --- a/src/types/widgetId.ts +++ b/src/types/widgetId.ts @@ -24,18 +24,8 @@ export function widgetId( ].join(SEPARATOR) as WidgetId } -/** - * Whether `name` can be written on {@link widget} at all: a structural property - * of the object, not of whether a particular write landed. Both the rename gate - * and the removal criterion read it, deliberately, so the two cannot disagree - * about the same widget. - */ function nameIsWritable(widget: object): boolean { try { - // The whole chain: `BaseWidget` declares `name` as a class accessor, so an - // instance has no own descriptor and would fall through to extensibility, - // which answers whether properties can be *added*. That reads "writable" - // for an inherited getter with no setter, which is unaddressable. for ( let target: object | null = widget; target; @@ -45,12 +35,8 @@ function nameIsWritable(widget: object): boolean { if (!descriptor) continue return 'writable' in descriptor ? !!descriptor.writable : !!descriptor.set } - // Nothing on the chain defines `name`, so a write would create it. return Object.isExtensible(widget) } catch { - // Every call above runs a proxy trap, mid-walk inside `LGraph.add`. A - // widget whose traps throw is exactly what removal is for, so answer here - // rather than abort the walk with the node half-attached. return false } } @@ -92,10 +78,6 @@ export function ensureUniqueWidgetNames( return false } - // Read back, because `setNodeId` and `widgetId` bail on this answer: a - // `true` over a node that still carries one name twice is what lets a - // colliding id be registered. Every rename is attempted first, so one - // declined write does not strand the collisions that would have resolved. let unique = true for (const { widget, name } of renames) { try { @@ -114,26 +96,11 @@ export function ensureUniqueWidgetNames( const UNREADABLE_NAME = Symbol('unreadable widget name') -/** - * A widget the walk could not name uniquely. The cause and the name come from - * the walk rather than from another read of the accessor: a hostile one need - * not answer twice the same way, and the walk may have written to it. - */ export type RefusedWidget = | { widget: T; cause: 'unreadable-name'; name: undefined } | { widget: T; cause: 'duplicate-name'; name: string } | { widget: T; cause: 'unresolved-duplicate'; name: string } -/** - * The identity key `name` claims, or {@link UNREADABLE_NAME}. It is the key - * rather than the raw value because `widgetId` keys on - * `encodeURIComponent(String(name))`, so names that differ as values and - * coincide as strings are one identity and have to collide here. - * - * An empty name is deliberately readable: it mints an id the store declines to - * key on, which costs the widget nothing, and `addWidget('text', '', …)` is an - * ordinary unlabeled widget that node packs ship (ADR-ECS-0008). - */ function readName(widget: { name: unknown }): string | typeof UNREADABLE_NAME { try { const raw = widget.name @@ -155,7 +122,6 @@ function tryRename(widget: { name: unknown }, name: string): boolean { } } -/** Whether no identity key can be read from {@link widget}'s `name`. */ export function isWidgetNameUnreadable(widget: { name: unknown }): boolean { return readName(widget) === UNREADABLE_NAME } @@ -178,14 +144,6 @@ function freeSuffixedName( return `${name}#${index}` } -/** - * Renamed apart and kept, kept but reported, or refused. Adds to - * `used`/`reserved` when the rename sticks. - * - * A rename that did not land is not proof of an unaddressable widget, so - * {@link nameIsWritable} decides removal and the unresolved pair is reported - * instead (ADR-ECS-0008). - */ function resolveCollision( widget: { name: unknown }, key: string, @@ -205,21 +163,6 @@ function resolveCollision( return nameIsWritable(widget) ? 'unresolved-duplicate' : 'duplicate-name' } -/** - * Renames the duplicates it can, removes the ones it cannot address at all, - * and keeps the first occurrence of each name either way. Mutates - * {@link widgets} in place. The invariant and the remove-or-keep criterion are - * ADR-ECS-0008's, under "Widget identity keys on `name`". - * - * Unlike {@link ensureUniqueWidgetNames} this reads each write back, so a - * setter that accepts and ignores it cannot report success, and a widget it - * cannot rename does not strand the collisions that would have resolved. - * - * @param isNameTaken whether a candidate name is already held outside - * {@link widgets}, such as by a store entry the rename would be refused onto. - * @returns every widget it could not name uniquely, with the cause, in array - * order. Every cause but `unresolved-duplicate` was removed. - */ export function dropUnrenamableDuplicateWidgets( widgets: T[], isNameTaken: (name: string) => boolean = () => false @@ -255,7 +198,6 @@ export function dropUnrenamableDuplicateWidgets( const keep = outcome !== 'duplicate-name' verdicts.set(widget, keep) if (keep) kept.push(widget) - // `key`, not a re-read: the walk may have written to the name since. if (outcome !== 'renamed') refused.push({ widget, cause: outcome, name: key }) } From 01ef9eb94a098fc1298cc2185d3c7935d3607a6a Mon Sep 17 00:00:00 2001 From: bymyself Date: Mon, 5 Oct 2026 09:26:12 +0000 Subject: [PATCH 28/35] fix(widgets): report refusals from app layer Addresses review feedback: https://github.com/Comfy-Org/ComfyUI_frontend/pull/20087#discussion_r4179147870 --- .../graph/nodeShell/nodeShellLifecycle.ts | 73 ++++++++++++- src/lib/litegraph/src/node/widgetsView.ts | 102 +++++------------- 2 files changed, 99 insertions(+), 76 deletions(-) diff --git a/src/core/graph/nodeShell/nodeShellLifecycle.ts b/src/core/graph/nodeShell/nodeShellLifecycle.ts index 314fee1313a..bbc7f77eb0d 100644 --- a/src/core/graph/nodeShell/nodeShellLifecycle.ts +++ b/src/core/graph/nodeShell/nodeShellLifecycle.ts @@ -1,8 +1,12 @@ +import type { IBaseWidget } from '@/lib/litegraph/src/types/widgets' +import type { WidgetRefusalReport } from '@/lib/litegraph/src/node/widgetsView' import { refuseAmbiguousNodeWidgets } from '@/lib/litegraph/src/node/widgetsView' import { isNodeBindable } from '@/lib/litegraph/src/utils/type' import { getWidgetIds } from '@/lib/litegraph/src/utils/widget' +import { reportError } from '@/platform/telemetry/reportError' import { usePreviewExposureStore } from '@/stores/previewExposureStore' import { useWidgetValueStore } from '@/stores/widgetValueStore' +import type { RefusedWidget } from '@/types/widgetId' import { registerNodeState, unregisterNodeState } from './nodeShellState' @@ -12,6 +16,71 @@ import type { NodeId } from '@/types/nodeId' import type { Subgraph } from '@/lib/litegraph/src/subgraph/Subgraph' import type { UUID } from '@/utils/uuid' +const REFUSAL_TEARDOWN_ERROR_TYPE = 'failure_tearing_down_refused_widget' + +const REFUSAL_ALERTS: Record< + RefusedWidget['cause'], + { + errorType: string + message: (nodeId: LGraphNode['id'], name: string | undefined) => string + } +> = { + 'unreadable-name': { + errorType: 'failure_reading_widget_name', + message: (nodeId) => + `Refused a widget on node ${nodeId}: no widget identity can be derived from its name` + }, + 'unresolved-duplicate': { + errorType: 'failure_resolving_widget_duplicate_name', + message: (nodeId, name) => + `Kept a widget named "${name}" that node ${nodeId} already has under that name: the rename was declined rather than impossible, so the widget is left in place and the pair is unresolved for now` + }, + 'duplicate-name': { + errorType: 'failure_renaming_widget_duplicate_name', + message: (nodeId, name) => + `Refused a widget named "${name}": node ${nodeId} already has a widget of that name and the duplicate cannot be renamed` + } +} + +function safeRead(read: () => unknown): string | undefined { + try { + const value = read() + return value === undefined ? undefined : String(value) + } catch { + return undefined + } +} + +function reportWidgetRefusal( + node: LGraphNode, + report: WidgetRefusalReport +): void { + if (report.kind === 'teardown-failure') { + reportError(report.error, { + errorType: REFUSAL_TEARDOWN_ERROR_TYPE, + surface: 'graph', + level: 'warning', + tags: { node_type: node.type }, + context: { nodeId: String(node.id) } + }) + return + } + + const { widget, cause, name } = report.finding + const alert = REFUSAL_ALERTS[cause] + reportError(new Error(alert.message(node.id, name)), { + errorType: alert.errorType, + surface: 'graph', + level: 'warning', + tags: { node_type: node.type }, + context: { + nodeId: String(node.id), + widgetName: name, + widgetType: safeRead(() => widget.type) + } + }) +} + /** * Registers a node's shell state and its widget bindings with the app * stores. Call once the node has a valid id and graph reference. Retries @@ -30,8 +99,10 @@ export function attachNodeToStores( ) } + refuseAmbiguousNodeWidgets(node, (report) => + reportWidgetRefusal(node, report) + ) if (!node.widgets) return - refuseAmbiguousNodeWidgets(node) for (const widget of node.widgets) { if (isNodeBindable(widget)) widget.setNodeId(node.id) } diff --git a/src/lib/litegraph/src/node/widgetsView.ts b/src/lib/litegraph/src/node/widgetsView.ts index b0cbfae44db..7832d979754 100644 --- a/src/lib/litegraph/src/node/widgetsView.ts +++ b/src/lib/litegraph/src/node/widgetsView.ts @@ -5,7 +5,6 @@ import type { IBaseWidget } from '@/lib/litegraph/src/types/widgets' import { toConcreteWidget } from '@/lib/litegraph/src/widgets/widgetMap' import { useWidgetValueStore } from '@/stores/widgetValueStore' -import { reportError } from '@/platform/telemetry/reportError' import type { RefusedWidget } from '@/types/widgetId' import { dropUnrenamableDuplicateWidgets, @@ -19,13 +18,19 @@ import { isNodeBindable } from '../utils/type' import { getWidgetIds } from '../utils/widget' import { BaseWidget } from '../widgets/BaseWidget' -const REFUSAL_TEARDOWN_ERROR_TYPE = 'failure_tearing_down_refused_widget' +export type WidgetRefusalReport = + | { kind: 'refusal'; finding: RefusedWidget } + | { kind: 'teardown-failure'; error: unknown } + +type WidgetRefusalReporter = (report: WidgetRefusalReport) => void +const ignoreWidgetRefusal: WidgetRefusalReporter = () => {} interface WidgetsViewState { target: IBaseWidget[] view: IBaseWidget[] present: boolean commit: (widgets: IBaseWidget[]) => void + reporter?: WidgetRefusalReporter } const reportedUnresolved = new WeakMap>() @@ -33,25 +38,6 @@ const reportedUnresolved = new WeakMap>() const states = new WeakMap() const widgetsViewGetters = new WeakSet<() => IBaseWidget[] | undefined>() -function safeRead(read: () => unknown): string | undefined { - try { - const value = read() - return value === undefined ? undefined : String(value) - } catch { - return undefined - } -} - -function reportTeardownFailure(node: LGraphNode, error: unknown): void { - reportError(error, { - errorType: REFUSAL_TEARDOWN_ERROR_TYPE, - surface: 'graph', - level: 'warning', - tags: { node_type: node.type }, - context: { nodeId: String(node.id) } - }) -} - function inputBindsWidget( input: INodeInputSlot, widget: IBaseWidget, @@ -77,32 +63,34 @@ function clearRefusedSlotBindings( function releaseRefusedWidget( node: LGraphNode, widget: IBaseWidget | undefined, - name: string | undefined + name: string | undefined, + report: WidgetRefusalReporter ): void { if (!widget) return try { clearRefusedSlotBindings(node, widget, name) } catch (error) { - reportTeardownFailure(node, error) + report({ kind: 'teardown-failure', error }) } try { widget.onRemove?.() } catch (error) { - reportTeardownFailure(node, error) + report({ kind: 'teardown-failure', error }) } try { if (widget instanceof BaseWidget) widget.releaseRegisteredState() } catch (error) { - reportTeardownFailure(node, error) + report({ kind: 'teardown-failure', error }) } } function refuseAmbiguousWidgets( node: LGraphNode, - widgets: IBaseWidget[] + widgets: IBaseWidget[], + report = states.get(node)?.reporter ?? ignoreWidgetRefusal ): ReadonlySet { const graphId = node.graph?.rootGraph.id const store = useWidgetValueStore() @@ -126,59 +114,17 @@ function refuseAmbiguousWidgets( for (const finding of refused) { if (finding.cause === 'unresolved-duplicate') { if (!previouslyUnresolved?.has(finding.widget)) { - reportRefusal(node, finding) + report({ kind: 'refusal', finding }) } continue } removed.add(finding.widget) - releaseRefusedWidget(node, finding.widget, finding.name) - reportRefusal(node, finding) + releaseRefusedWidget(node, finding.widget, finding.name, report) + report({ kind: 'refusal', finding }) } return removed } -const REFUSAL_ALERTS: Record< - RefusedWidget['cause'], - { - errorType: string - message: (nodeId: LGraphNode['id'], name: string | undefined) => string - } -> = { - 'unreadable-name': { - errorType: 'failure_reading_widget_name', - message: (nodeId) => - `Refused a widget on node ${nodeId}: no widget identity can be derived from its name` - }, - 'unresolved-duplicate': { - errorType: 'failure_resolving_widget_duplicate_name', - message: (nodeId, name) => - `Kept a widget named "${name}" that node ${nodeId} already has under that name: the rename was declined rather than impossible, so the widget is left in place and the pair is unresolved for now` - }, - 'duplicate-name': { - errorType: 'failure_renaming_widget_duplicate_name', - message: (nodeId, name) => - `Refused a widget named "${name}": node ${nodeId} already has a widget of that name and the duplicate cannot be renamed` - } -} - -function reportRefusal( - node: LGraphNode, - { widget, cause, name }: RefusedWidget -): void { - const alert = REFUSAL_ALERTS[cause] - reportError(new Error(alert.message(node.id, name)), { - errorType: alert.errorType, - surface: 'graph', - level: 'warning', - tags: { node_type: node.type }, - context: { - nodeId: String(node.id), - widgetName: name, - widgetType: safeRead(() => widget.type) - } - }) -} - function commitsThroughWidgetsView(node: LGraphNode): boolean { const descriptor = Object.getOwnPropertyDescriptor(node, 'widgets') return !!descriptor?.get && widgetsViewGetters.has(descriptor.get) @@ -191,11 +137,17 @@ export function wasWidgetRefused( return commitsThroughWidgetsView(node) && !node.widgets?.includes(widget) } -export function refuseAmbiguousNodeWidgets(node: LGraphNode): void { +export function refuseAmbiguousNodeWidgets( + node: LGraphNode, + report: WidgetRefusalReporter +): void { if (!commitsThroughWidgetsView(node)) return - const target = states.get(node)?.target - if (!target?.length) return - refuseAmbiguousWidgets(node, target) + const state = states.get(node) + if (!state) return + state.reporter = report + const target = state.target + if (!target.length) return + refuseAmbiguousWidgets(node, target, report) } function syncWidgetOrder(node: LGraphNode, widgets: IBaseWidget[]): void { From 9db1f62010142b52099f6957a0323ab5a7065c8d Mon Sep 17 00:00:00 2001 From: Christian Byrne Date: Sun, 4 Oct 2026 15:14:40 -0700 Subject: [PATCH 29/35] fix(widgets): decide widget identity per widget, not per node MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A node that keeps an ambiguous pair rendered no widgets at all, including widgets that collide with nothing. `setNodeId` and `BaseWidget.widgetId` gated registration on `ensureUniqueWidgetNames`, whose verdict is whole-node: one pair no rename could separate made every widget on the node bail. A Vue node draws from the registered order (`getNodeWidgetIds`), so the node drew nothing. Measured on a three-widget node whose duplicate forms while detached — the undo-a-deletion and paste-a-cut-node path this criterion exists for: | revision | node.widgets | registered order | values | | --- | --- | --- | --- | | main | seed, seed#1, cfg | 2 of 3 | second value destroyed | | before the refusal criterion | seed, cfg | 2 of 2 | widget destroyed | | keeping the pair | seed, seed, cfg | **0 of 3** | intact, undrawn | So keeping the widget stopped charging the user a widget and started charging them the whole node's widget body, which is worse than what it replaced. Registration is now gated on `widgetOwnsItsName`: true unless an earlier widget in the array already holds that name. First occurrence wins, as the ADR already said, so one name still resolves to one `WidgetId` held by one widget and the later duplicate is still never registered — it is only the collateral loss that goes away. `ensureUniqueWidgetNames` is still called for its effect, because that is where a resolvable collision is settled. Red/green is browser-observable: the node draws 0 widgets before and 1 after. --- .../renamableDuplicateWidgetKept.spec.ts | 173 ++++++++++++++++++ docs/adr/ECS-0008-entity-component-system.md | 20 ++ .../node/widgetsView.refusalCriterion.test.ts | 81 +++++++- src/lib/litegraph/src/widgets/BaseWidget.ts | 22 ++- src/types/widgetId.ts | 82 ++++++++- 5 files changed, 373 insertions(+), 5 deletions(-) create mode 100644 browser_tests/tests/widgets/renamableDuplicateWidgetKept.spec.ts diff --git a/browser_tests/tests/widgets/renamableDuplicateWidgetKept.spec.ts b/browser_tests/tests/widgets/renamableDuplicateWidgetKept.spec.ts new file mode 100644 index 00000000000..5a306c32c07 --- /dev/null +++ b/browser_tests/tests/widgets/renamableDuplicateWidgetKept.spec.ts @@ -0,0 +1,173 @@ +import { expect } from '@playwright/test' + +import type { ComfyPage } from '@e2e/fixtures/ComfyPage' +import { comfyPageFixture as test } from '@e2e/fixtures/ComfyPage' +import { TestIds } from '@e2e/fixtures/selectors' + +import { zComfyWorkflow } from '@/platform/workflow/validation/schemas/workflowSchema' + +/** + * The unique-name invariant removes a widget it cannot name uniquely + * (ADR-ECS-0008). This pins the boundary of "cannot": a widget whose `name` is + * perfectly writable must never be the price of enforcing it. + * + * `BaseWidget.set name` delegates to `widgetValueStore.renameWidget()` and + * returns without changing the name whenever the store declines — which it does + * when the node has no entries, the state a node is in after it has been + * removed from the graph. So a rename that *failed* does not prove the widget + * is unaddressable, and removing on that signal destroys an ordinary widget. + * + * Reproduced through the graph API the way an undo of a node deletion or a + * paste of a cut node reaches it: the node leaves the graph, the duplicate name + * appears while it is detached, and it rejoins. + * + * Asserted on what the app saves, because that is where the loss is permanent. + * Measured on the parent commit the node comes back one widget short and saves + * **one** `widgets_values` entry for a two-widget node; the arity of that array + * is what positional widget addressing reads, so a dropped slot shifts every + * later widget. With the invariant's criterion corrected it saves both. + * + * The two *values* are asserted too, and that is the stronger half. Arity alone + * went green over a save this change set used to corrupt: re-registering an + * ambiguous pair routed the second widget's `name` setter through + * `renameWidget` on an id the *first* widget had registered, which handed it + * that widget's store entry — so the two widgets shared one `WidgetState`, both + * read the first value, and the second value was gone from a two-slot save. A + * widget's own entry is now the only entry its rename may move + * (`BaseWidget.set name`), so both values survive and this asserts it. + * + * What the node *draws* is asserted too, because the save cannot show it: + * serialization reads `node.widgets`, while a Vue node renders from the + * registered widget order. Registration was gated on a whole-node verdict, so + * one unresolvable pair left the node with an empty order and it drew no + * widgets at all — a save-only assertion goes green over that. + */ + +const NODE_TYPE = 'DevToolsNodeWithOutputList' +const KEPT_NAME = 'alpha' +const RENAMED_NAME = 'beta' + +/** + * Patches the node type so every instance carries two distinct, ordinary, + * serializable widgets. Both names are writable, so neither is ever + * unaddressable — which is the whole point. + */ +async function installTwoOrdinaryWidgets(comfyPage: ComfyPage): Promise { + await comfyPage.page.evaluate( + ({ nodeTypeName, first, second }) => { + const nodeType = window.LiteGraph!.registered_node_types[nodeTypeName] + const onNodeCreated = nodeType.prototype.onNodeCreated + nodeType.prototype.onNodeCreated = function (...args) { + onNodeCreated?.apply(this, args) + this.serialize_widgets = true + this.addWidget('string', first, 'first default', () => {}) + this.addWidget('string', second, 'second default', () => {}) + } + }, + { nodeTypeName: NODE_TYPE, first: KEPT_NAME, second: RENAMED_NAME } + ) +} + +/** + * Takes the node out of the graph, collides the second widget's name with the + * first while it is detached, and puts it back. Detached is what makes the + * write land: on a node that is still in the graph the store declines the + * rename and the collision never forms. + */ +async function collideNameWhileDetached( + comfyPage: ComfyPage, + nodeId: string +): Promise { + await comfyPage.page.evaluate( + ({ id, duplicateName, renamedName }) => { + const graph = window.app!.graph + const node = graph.nodes.find((candidate) => String(candidate.id) === id) + if (!node) throw new Error(`node ${id} not found`) + + graph.remove(node) + const target = node.widgets?.find(({ name }) => name === renamedName) + if (!target) throw new Error(`widget ${renamedName} not found`) + target.name = duplicateName + graph.add(node) + }, + { id: nodeId, duplicateName: KEPT_NAME, renamedName: RENAMED_NAME } + ) +} + +test.describe( + 'renamable duplicate widget name', + { tag: ['@canvas', '@widget', '@vue-nodes'] }, + () => { + // Per attempt, not per module: a module-scope stamp is shared by every + // worker in the process and by a retry. + let workflowName = '' + + test.afterEach(async ({ comfyPage }) => { + if (workflowName) await comfyPage.workflow.deleteWorkflow(workflowName) + }) + + test('keeps the widget whose rename was declined rather than impossible', async ({ + comfyPage + }, testInfo) => { + workflowName = `renamable-duplicate-widget-${testInfo.parallelIndex}-${testInfo.retry}-${Date.now()}` + + await comfyPage.nodeOps.clearGraph() + await installTwoOrdinaryWidgets(comfyPage) + + const nodeId = await comfyPage.searchBoxV2.addNodeAndGetId( + 'Node With Output List' + ) + const node = comfyPage.vueNodes.getNodeLocator(nodeId) + await expect(node).toBeVisible() + + await test.step('both widgets are drawn to begin with', async () => { + await expect(node.getByTestId(TestIds.widgets.widget)).toHaveCount(2) + }) + + await collideNameWhileDetached(comfyPage, nodeId) + + await test.step('the node still draws the widget that kept the name', async () => { + // A Vue node draws from the registered widget order, and registration + // was gated on a whole-node "is this node unambiguous?" verdict — so + // one pair that could not be renamed apart withheld an identity from + // every widget on the node and it drew **none**. That is a worse loss + // than the removal this criterion replaced, which cost one widget and + // kept drawing the rest; it is invisible to the save assertion below, + // because serialization reads `node.widgets` rather than the store. + // + // One widget drawn, not two: the duplicate genuinely has no identity + // of its own while it shares the name, which is what stops it being + // handed the other widget's store entry. + await expect(node.getByTestId(TestIds.widgets.widget)).toHaveCount(1) + }) + + await test.step('and the node still saves both widget slots', async () => { + const savedRequest = comfyPage.page.waitForRequest( + (request) => + request.method() === 'POST' && + decodeURIComponent(new URL(request.url()).pathname).endsWith( + `/workflows/${workflowName}.json` + ) + ) + await comfyPage.menu.topbar.saveWorkflowAs(workflowName) + const saved = zComfyWorkflow.parse( + JSON.parse((await savedRequest).postData() ?? '{}') + ) + const savedNode = saved.nodes.find(({ type }) => type === NODE_TYPE) + + // One entry here is a widget the user lost. Two is the invariant being + // enforced without charging them for it. + expect(savedNode?.widgets_values).toHaveLength(2) + + // And two *distinct* values, because arity alone cannot tell a + // preserved widget from one welded onto its duplicate's store entry. + // `['first default', 'first default']` is the second value destroyed + // while the slot count still looks right. + expect(savedNode?.widgets_values).toEqual([ + 'first default', + 'second default' + ]) + }) + }) + } +) diff --git a/docs/adr/ECS-0008-entity-component-system.md b/docs/adr/ECS-0008-entity-component-system.md index 16123421982..63c095ad37e 100644 --- a/docs/adr/ECS-0008-entity-component-system.md +++ b/docs/adr/ECS-0008-entity-component-system.md @@ -210,6 +210,26 @@ legitimate re-mint rather than an identity collision — which is why > graph, and `syncWidgetOrder` for every later `node.widgets` mutation > (`addWidget`, a raw `push`, a splice, a whole-array assignment). Their > boundaries are part of the decision: +> **Whether a widget has an identity is a per-widget question, and gating it on +> a whole-node verdict loses the node's entire widget order.** +> `ensureUniqueWidgetNames` answers "is this node unambiguous?", so a pair that +> no rename could separate made `setNodeId` and `BaseWidget.widgetId` bail for +> **every** widget on the node — including widgets sharing a name with nothing. +> A Vue node draws from the registered order (`getNodeWidgetIds`), so the node +> rendered no widgets at all: strictly worse than the removal this criterion +> replaced, which cost one widget and left the rest drawn. Registration is +> therefore gated on `widgetOwnsItsName` — true unless an _earlier_ widget in +> the array already holds that name. First occurrence wins, as above, so one +> name still resolves to one `WidgetId` held by one widget and a later duplicate +> is still never registered; it is only the collateral loss that goes away. +> +> **There are two enforcement points, and looking only at the first one is +> misleading.** `attachNodeToStores` calls `refuseAmbiguousNodeWidgets` as a +> node joins a graph, which is the one that catches a node built detached and +> then added. `syncWidgetOrder` catches every later mutation — `node.widgets` +> is a mutation view, so `addWidget`, a raw `push`, a splice and a whole-array +> assignment all commit through it — but it enforces nothing until `graphId` +> exists, so it does not cover the join itself. > > - Enforcement starts at the join, not during construction: no `WidgetId` > exists before then, and `litegraphService` still matches a freshly created diff --git a/src/lib/litegraph/src/node/widgetsView.refusalCriterion.test.ts b/src/lib/litegraph/src/node/widgetsView.refusalCriterion.test.ts index 9cfa8920df8..2dab769ee2a 100644 --- a/src/lib/litegraph/src/node/widgetsView.refusalCriterion.test.ts +++ b/src/lib/litegraph/src/node/widgetsView.refusalCriterion.test.ts @@ -47,8 +47,24 @@ describe('unique-name refusal criterion', () => { expect(node.widgets).toContain(steps) expect(names(node)).toEqual(['seed', 'seed#1']) expect(storedNames(graph, node)).toEqual(['seed', 'seed#1']) - expect(reportedTypes()).toEqual([]) + // It is still reported, so the pair is observable rather than tolerated in + // silence — under its own `errorType`, because nothing was lost. + expect(reportedTypes()).toEqual([ + 'failure_resolving_widget_duplicate_name' + ]) + expect(reportedTypes()).not.toContain('widget_duplicate_name_refused') + // Keeping the pair must not be paid for with a *value* either, which the + // widget array's length cannot show. One widget holds the name and keeps + // the identity; the duplicate gets no id at all, so it cannot be handed + // that entry and the two stay independent — rather than both resolving to + // one store entry under the shared name. + const store = useWidgetValueStore() + expect( + store.getNodeWidgets(graph.id, node.id).map(({ name }) => name) + ).toEqual(['seed']) + expect(store.getWidget(widgetId(graph.id, node.id, 'seed'))?.value).toBe(1) + expect(steps.widgetId).toBeUndefined() expect(seed.value).toBe(1) expect(steps.value).toBe(2) @@ -58,6 +74,69 @@ describe('unique-name refusal criterion', () => { expect(steps.value).toBe(222) }) + it('does not erase the whole widget order over one pair it cannot resolve', () => { + const graph = new LGraph() + const node = new LGraphNode('test') + graph.add(node) + const seed = node.addWidget('number', 'seed', 1, () => undefined, {}) + const steps = node.addWidget('number', 'steps', 2, () => undefined, {}) + const cfg = node.addWidget('number', 'cfg', 3, () => undefined, {}) + + graph.remove(node) + steps.name = 'seed' + graph.add(node) + + // The node's widget order is what a Vue node renders from + // (`getNodeWidgetIds` in `LGraphNode.vue`), so a node with no order draws + // no widgets. Registration was gated on `ensureUniqueWidgetNames`, whose + // verdict is whole-node: one pair that could not be renamed apart made + // *every* widget here bail, including `cfg`, which collides with nothing. + // Three widgets on the node, an empty order, and nothing drawn — the same + // visible loss the keep-rather-remove criterion exists to prevent. + const store = useWidgetValueStore() + expect(store.getNodeWidgetIds(graph.id, node.id)).toEqual([ + widgetId(graph.id, node.id, 'seed'), + widgetId(graph.id, node.id, 'cfg') + ]) + + // And the ambiguity is still contained: the duplicate has no identity, so + // it cannot be registered under the name the other widget holds, and all + // three widgets keep their own value. + expect(steps.widgetId).toBeUndefined() + expect(node.widgets).toHaveLength(3) + expect(seed.value).toBe(1) + expect(steps.value).toBe(2) + expect(cfg.value).toBe(3) + }) + + it('does not let a duplicate rename move the entry the other widget registered', () => { + const graph = new LGraph() + const node = new LGraphNode('test') + graph.add(node) + const seed = node.addWidget('number', 'seed', 1, () => undefined, {}) + const steps = node.addWidget('number', 'steps', 2, () => undefined, {}) + + graph.remove(node) + steps.name = 'seed' + graph.add(node) + + // `graphId:nodeId:seed` is `seed`'s to hold: it is the widget that holds + // the name first, so it is the one that registers. A rename of `steps` + // must not move that entry — being handed it is what welded the pair onto + // one `WidgetState` and destroyed the second value. + const store = useWidgetValueStore() + expect(store.getWidget(widgetId(graph.id, node.id, 'seed'))?.value).toBe(1) + + // The write is declined rather than silently redirected, so the name the + // walk could not resolve is still ambiguous and still reported as such. + steps.name = 'seed#1' + expect( + store.getWidget(widgetId(graph.id, node.id, 'seed#1')) + ).toBeUndefined() + expect(seed.value).toBe(1) + expect(steps.value).toBe(2) + }) + it('does not let a duplicate rename steal the entry of a widget on another node', () => { const graph = new LGraph() const store = useWidgetValueStore() diff --git a/src/lib/litegraph/src/widgets/BaseWidget.ts b/src/lib/litegraph/src/widgets/BaseWidget.ts index 5ed3e6430f8..d6f7720ac5c 100644 --- a/src/lib/litegraph/src/widgets/BaseWidget.ts +++ b/src/lib/litegraph/src/widgets/BaseWidget.ts @@ -19,7 +19,11 @@ import type { import { deriveWidgetRenderState } from '@/lib/litegraph/src/utils/widget' import { useWidgetValueStore } from '@/stores/widgetValueStore' import type { WidgetId } from '@/types/widgetId' -import { ensureUniqueWidgetNames, widgetId } from '@/types/widgetId' +import { + ensureUniqueWidgetNames, + widgetId, + widgetOwnsItsName +} from '@/types/widgetId' import type { WidgetState } from '@/types/widgetState' import { applyLegacyAdvancedWrite, @@ -394,7 +398,12 @@ export abstract class BaseWidget const graphId = this.node.graph?.rootGraph.id const nodeId = this._state.nodeId if (!graphId || nodeId === undefined) return undefined - if (!ensureUniqueWidgetNames(this.node.widgets ?? [this])) return undefined + // Attempted for its effect, not its verdict: this is where a resolvable + // collision is settled. The verdict is whole-node, and whether *this* + // widget has an identity is not — see {@link widgetOwnsItsName}. + const widgets = this.node.widgets ?? [this] + ensureUniqueWidgetNames(widgets) + if (!widgetOwnsItsName(widgets, this)) return undefined return widgetId(graphId, nodeId, this.name) } @@ -406,7 +415,14 @@ export abstract class BaseWidget this.installTypeVisibilityShim() const graphId = this.node.graph?.rootGraph.id if (!graphId) return - if (!ensureUniqueWidgetNames(this.node.widgets ?? [this])) return + // Settle what can be settled, then ask only about this widget. A node + // carrying one pair nothing can rename apart must not cost every *other* + // widget on it its registration — that empties the node's whole widget + // order and a Vue node then draws nothing. The later of the pair still + // gets no id, so no colliding identity is ever registered. + const widgets = this.node.widgets ?? [this] + ensureUniqueWidgetNames(widgets) + if (!widgetOwnsItsName(widgets, this)) return const registered = useWidgetValueStore().registerWidget( widgetId(graphId, nodeId, this.name), diff --git a/src/types/widgetId.ts b/src/types/widgetId.ts index dc0d1f5cca2..d56c9264018 100644 --- a/src/types/widgetId.ts +++ b/src/types/widgetId.ts @@ -24,7 +24,18 @@ export function widgetId( ].join(SEPARATOR) as WidgetId } -function nameIsWritable(widget: object): boolean { +/** + * Whether `name` can be written on {@link widget} at all — a structural + * property of the object, not of whether a particular write landed. + * + * This is the criterion {@link ensureUniqueWidgetNames} uses to decide whether + * it may rename at all, and it is deliberately the same one + * {@link dropUnrenamableDuplicateWidgets} uses to decide whether a rename that + * failed is fatal. The two must agree: one walk removing a widget the other + * calls renamable would be destroying widgets over a disagreement between two + * copies of one rule. + */ +function nameIsWritable(widget: { name: string }): boolean { try { for ( let target: object | null = widget; @@ -41,6 +52,60 @@ function nameIsWritable(widget: object): boolean { } } +/** + * Whether {@link widget} may mint an id for the name it currently holds on a + * node whose widgets are {@link widgets} — true unless an *earlier* widget in + * the array already holds that name. + * + * This is deliberately a per-widget question, and + * {@link ensureUniqueWidgetNames} answers a different, whole-node one. A node + * that still carries an ambiguous pair after every rename was attempted has + * exactly one widget per name that may own the identity: the first to hold it. + * Gating registration on the whole-node answer instead withholds an id from + * *every* widget on the node, including widgets that share a name with nothing + * — so one unresolvable pair erases the node's entire widget order, and a Vue + * node renders no widgets at all (`getNodeWidgetIds` is what it draws from). + * + * The identity invariant is unchanged by answering per widget: one name still + * resolves to one {@link WidgetId} held by one widget, so a later duplicate is + * never registered and can never be handed the first widget's state. It is the + * collateral loss that goes away. + * + * Every read of another widget's `name` is guarded. A widget whose accessor + * throws is refused in its own right by {@link dropUnrenamableDuplicateWidgets} + * and must not also decide whether an unrelated widget has an identity. + */ +export function widgetOwnsItsName( + widgets: readonly { name: string }[], + widget: { name: string } +): boolean { + let name: string + try { + name = widget.name + } catch { + // No name read, no id. This is the `unreadable-name` refusal's own case. + return false + } + + for (const candidate of widgets) { + // Reached this widget without an earlier holder, so the name is its own. + // Identity, not position: the same object may transiently occupy two + // slots during an index-assignment reorder, and that is one widget. + if (candidate === widget) return true + try { + if (candidate.name === name) return false + } catch { + continue + } + } + + // Not on the array at all, and no widget on it holds this name. A widget the + // refusal walk removed falls out of the loop above instead: it shares its + // name with whichever widget kept it, so it has no identity of its own to + // read or write through, and that is the point. + return true +} + export function ensureUniqueWidgetNames( widgets: readonly { name: string }[] ): boolean { @@ -78,6 +143,21 @@ export function ensureUniqueWidgetNames( return false } + // The write is read back, and a write that did not land makes this `false`. + // + // An unconditional `true` reported success over a node that still carries + // two widgets under one name. `BaseWidget`'s own `name` setter declines + // the write whenever the store declines the move — which is exactly the + // state `dropUnrenamableDuplicateWidgets` leaves behind when it keeps an + // unresolved duplicate rather than deleting the user's widget — so this + // answered "unambiguous" precisely where it was wrong, and the callers + // that act on it (`litegraphUtil`'s widget-value sync) acted on that. + // + // It is no longer what decides whether a widget may be registered: that is + // per widget, and {@link widgetOwnsItsName} answers it. + // + // Every rename is still attempted before answering: one declined write + // must not strand the collisions that would have resolved cleanly. let unique = true for (const { widget, name } of renames) { try { From a24f0fd685f8f3da38c1f294cb5ed575553bb95b Mon Sep 17 00:00:00 2001 From: Christian Byrne Date: Sun, 4 Oct 2026 15:38:58 -0700 Subject: [PATCH 30/35] fix(widgets): compare names as id keys when deciding who owns one `widgetId` keys on `encodeURIComponent(String(name))`, so a widget named `1` and one named `'1'` mint the same id however different the values look. The ownership gate now reads names through `readName`, the same reader `dropUnrenamableDuplicateWidgets` uses, so the walk that decides which widget is the duplicate and the gate that decides who may mint an id agree on what a duplicate is. Comparing raw values handed both of that pair an identity and let the clash land in the store, which is the registration this gate exists to refuse. `ensureUniqueWidgetNames` still compares raw values and so renames nothing there. That disagreement is safe in this direction only: this gate withholds an id, it never removes a widget, so the pair is kept and under-registered rather than destroyed. Widening the rename guard's own keying is FE-3036 policy and is left to its owner. --- src/types/widgetId.test.ts | 69 +++++++++++++++++++++++++++++++++++++- src/types/widgetId.ts | 36 +++++++++++--------- 2 files changed, 89 insertions(+), 16 deletions(-) diff --git a/src/types/widgetId.test.ts b/src/types/widgetId.test.ts index f2548687cd4..c222d45d44a 100644 --- a/src/types/widgetId.test.ts +++ b/src/types/widgetId.test.ts @@ -6,7 +6,8 @@ import { ensureUniqueWidgetNames, isWidgetId, parseWidgetId, - widgetId + widgetId, + widgetOwnsItsName } from './widgetId' import { toNodeId } from '@/types/nodeId' @@ -342,6 +343,72 @@ describe('dropUnrenamableDuplicateWidgets', () => { }) }) +/** + * Which widget on a node may mint an id for the name it holds. The whole-node + * question `ensureUniqueWidgetNames` answers is the wrong one for this: a node + * carrying one pair nothing could rename apart has to keep registering its + * other widgets, or the node's whole widget order empties and a Vue node draws + * nothing. + */ +describe('widgetOwnsItsName', () => { + it('gives the name to the first widget holding it, and to no later one', () => { + const first = { name: 'seed' } + const later = { name: 'seed' } + const unrelated = { name: 'cfg' } + const widgets = [first, later, unrelated] + + expect(widgetOwnsItsName(widgets, first)).toBe(true) + expect(widgetOwnsItsName(widgets, later)).toBe(false) + // The whole point: a widget that collides with nothing keeps its identity + // even while the node is ambiguous. + expect(widgetOwnsItsName(widgets, unrelated)).toBe(true) + }) + + it('treats one widget in two array slots as one widget, not a collision', () => { + // An index-assignment reorder transiently repeats the same object. + const shared = { name: 'seed' } + + expect(widgetOwnsItsName([shared, shared], shared)).toBe(true) + }) + + it('collides names that differ as values but coincide as id strings', () => { + // `widgetId` keys on `encodeURIComponent(String(name))`, so these two mint + // one id. Comparing raw values would hand both an identity and let the + // clash land in the store, which is the registration this gate exists to + // refuse. + const numeric = { name: 1 as unknown as string } + const textual = { name: '1' } + const widgets = [numeric, textual] + + expect(widgetOwnsItsName(widgets, numeric)).toBe(true) + expect(widgetOwnsItsName(widgets, textual)).toBe(false) + }) + + it('refuses a widget whose own name cannot be read', () => { + const hostile = { + get name(): string { + throw new Error('nope') + } + } + + expect(widgetOwnsItsName([hostile], hostile)).toBe(false) + }) + + it('does not let an unreadable name on another widget decide this one', () => { + // That widget is refused in its own right. Letting its accessor throw + // through here would deny an identity to a widget it has nothing to do + // with — and abort the walk mid-`LGraph.add`. + const hostile = { + get name(): string { + throw new Error('nope') + } + } + const ordinary = { name: 'seed' } + + expect(widgetOwnsItsName([hostile, ordinary], ordinary)).toBe(true) + }) +}) + describe('widgetId', () => { const graphId = 'a1b2c3d4-e5f6-7890-abcd-ef1234567890' diff --git a/src/types/widgetId.ts b/src/types/widgetId.ts index d56c9264018..c1d9b70a9f7 100644 --- a/src/types/widgetId.ts +++ b/src/types/widgetId.ts @@ -71,32 +71,38 @@ function nameIsWritable(widget: { name: string }): boolean { * never registered and can never be handed the first widget's state. It is the * collateral loss that goes away. * - * Every read of another widget's `name` is guarded. A widget whose accessor - * throws is refused in its own right by {@link dropUnrenamableDuplicateWidgets} - * and must not also decide whether an unrelated widget has an identity. + * Names are compared through {@link readName}, so the comparison is on the + * **key** an id would be built from rather than on the raw value — a widget + * named `1` and one named `'1'` are one identity however different they look. + * {@link dropUnrenamableDuplicateWidgets} reads names the same way, so the walk + * that decides *which* widget is the duplicate and this predicate agree on what + * a duplicate is. ({@link ensureUniqueWidgetNames} still compares raw values, + * so it calls that pair unambiguous and renames nothing. The disagreement is + * safe in this direction and only in this direction: this predicate withholds + * an id, it never removes a widget, so the pair is kept and under-registered + * rather than destroyed.) + * + * A widget whose `name` cannot be read owns nothing: that is the + * `unreadable-name` refusal's own case, and it mints no id anyway. An + * unreadable name on *another* widget is likewise that widget's problem and + * must not decide whether this one has an identity, which is why the read is + * guarded per candidate rather than around the loop. */ export function widgetOwnsItsName( widgets: readonly { name: string }[], widget: { name: string } ): boolean { - let name: string - try { - name = widget.name - } catch { - // No name read, no id. This is the `unreadable-name` refusal's own case. - return false - } + const key = readName(widget) + if (key === UNREADABLE_NAME) return false for (const candidate of widgets) { // Reached this widget without an earlier holder, so the name is its own. // Identity, not position: the same object may transiently occupy two // slots during an index-assignment reorder, and that is one widget. if (candidate === widget) return true - try { - if (candidate.name === name) return false - } catch { - continue - } + // An unreadable candidate answers `UNREADABLE_NAME`, which is never equal + // to a key, so it is skipped rather than blocking this widget. + if (readName(candidate) === key) return false } // Not on the array at all, and no widget on it holds this name. A widget the From 83bbad212a1b43a565e3f814a14ea5a02f8d0c80 Mon Sep 17 00:00:00 2001 From: Christian Byrne Date: Sun, 4 Oct 2026 16:09:34 -0700 Subject: [PATCH 31/35] fix(widgets): keep an identity with the widget bound to it, not with a slot MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Three findings from the review, two of them live. **An ambiguous name's owner moves with the array, and the entry does not.** Splicing the registered widget off `node.widgets` without deleting its entry leaves the surviving duplicate as the only holder of the name, so position says it may mint that id — and `registerWidget` hands back the existing same-type entry *with its value*, so binding to it welded the two widgets onto one `WidgetState` and replaced the user's value with the departed widget's. Measured: `steps` came back reading `1` instead of `2`. So adopting an entry that holds a different `WidgetState` now requires that nobody is left to lose it: no other widget on the node is bound to it, and this widget has never registered. The second half is load-bearing the other way — a replaced node's fresh widgets inheriting the previous occupant's values across a recycled `nodeId` is #13073 and still works. The reviewer also named a whole-array reorder and an unshift. Measured, both *resolve* the pair instead of welding it: once one widget is registered the other's rename has an entry to move, so it lands and the names separate. The case is pinned anyway, because the reason it is safe is not obvious. **A widget keeps the id it registered after it leaves the node.** `dynamicWidgets.ts` splices a group's widgets off `node.widgets` and *then* reads `widget.widgetId` to delete each entry. Gating that read on array position leaked every one of those entries whenever a same-named widget remained, which is the other half of the weld above. `widgetId` now falls back to the entry this widget is actually bound to. A refused duplicate never registered, so it still answers `undefined` and still cannot reach the entry of the widget that kept the name. **One read of `name`, not two.** `ownedWidgetNameKey` returns the key rather than a boolean, and the id is minted from it, so an accessor that answers differently on a second read cannot pass the check under one name and register under another — or throw out of the `widgetId` getter after the check guarded its own read. `bindRegisteredState` takes the same key. Each guard is pinned by a test that fails without it: dropping the adoption guard, dropping the bound-id fallback, and making the fallback ignore ownership each turn one or more cases red. --- docs/adr/ECS-0008-entity-component-system.md | 4 +- .../node/widgetsView.refusalCriterion.test.ts | 119 ++++++++++++++++ src/lib/litegraph/src/widgets/BaseWidget.ts | 127 ++++++++++++++---- src/types/widgetId.test.ts | 23 ++-- src/types/widgetId.ts | 57 ++++++-- 5 files changed, 278 insertions(+), 52 deletions(-) diff --git a/docs/adr/ECS-0008-entity-component-system.md b/docs/adr/ECS-0008-entity-component-system.md index 63c095ad37e..8ece6f94ba1 100644 --- a/docs/adr/ECS-0008-entity-component-system.md +++ b/docs/adr/ECS-0008-entity-component-system.md @@ -218,8 +218,8 @@ legitimate re-mint rather than an identity collision — which is why > A Vue node draws from the registered order (`getNodeWidgetIds`), so the node > rendered no widgets at all: strictly worse than the removal this criterion > replaced, which cost one widget and left the rest drawn. Registration is -> therefore gated on `widgetOwnsItsName` — true unless an _earlier_ widget in -> the array already holds that name. First occurrence wins, as above, so one +> therefore gated on `ownedWidgetNameKey`, which answers with the key a widget +> may mint from unless an _earlier_ widget in the array already holds that name. First occurrence wins, as above, so one > name still resolves to one `WidgetId` held by one widget and a later duplicate > is still never registered; it is only the collateral loss that goes away. > diff --git a/src/lib/litegraph/src/node/widgetsView.refusalCriterion.test.ts b/src/lib/litegraph/src/node/widgetsView.refusalCriterion.test.ts index 2dab769ee2a..f34ecefae78 100644 --- a/src/lib/litegraph/src/node/widgetsView.refusalCriterion.test.ts +++ b/src/lib/litegraph/src/node/widgetsView.refusalCriterion.test.ts @@ -109,6 +109,125 @@ describe('unique-name refusal criterion', () => { expect(cfg.value).toBe(3) }) + it('resolves the pair when a reorder moves which widget holds the name', () => { + const graph = new LGraph() + const node = new LGraphNode('test') + graph.add(node) + const seed = node.addWidget('number', 'seed', 1, () => undefined, {}) + const steps = node.addWidget('number', 'steps', 2, () => undefined, {}) + + graph.remove(node) + steps.name = 'seed' + graph.add(node) + + const store = useWidgetValueStore() + expect(store.getWidget(widgetId(graph.id, node.id, 'seed'))?.value).toBe(1) + + // Ownership of a shared name is positional, so a whole-array assignment + // makes the duplicate the holder. That must not hand it the entry `seed` + // is bound to, which would weld the two onto one `WidgetState`. + node.widgets = [steps, seed] + + // It resolves instead: `seed` is now the duplicate, and renaming it *does* + // land because it owns the entry there is to move, so the pair separates. + expect((node.widgets ?? []).map(({ name }) => name)).toEqual([ + 'seed', + 'seed#1' + ]) + expect(seed.value).toBe(1) + expect(steps.value).toBe(2) + + // The decisive assertion: two entries, not one shared between them. Equal + // values cannot show a weld, and these two differ only by luck. + steps.value = 222 + expect(seed.value).toBe(1) + expect(store.getWidget(widgetId(graph.id, node.id, 'seed'))?.value).toBe( + 222 + ) + expect(store.getWidget(widgetId(graph.id, node.id, 'seed#1'))?.value).toBe( + 1 + ) + }) + + it('still answers with its own entry id once it is spliced off the node', () => { + const graph = new LGraph() + const node = new LGraphNode('test') + graph.add(node) + const seed = node.addWidget('number', 'seed', 1, () => undefined, {}) + const steps = node.addWidget('number', 'steps', 2, () => undefined, {}) + + graph.remove(node) + steps.name = 'seed' + graph.add(node) + + node.widgets = (node.widgets ?? []).filter((widget) => widget !== seed) + + // Position decides who may *take* an identity, not who already has one. + // `dynamicWidgets.ts` splices a group's widgets off the node and then reads + // `widget.widgetId` to delete each entry, so a widget that answered + // `undefined` here would leak its entry and the next widget of that name + // and type would inherit the value. + const id = widgetId(graph.id, node.id, 'seed') + expect(seed.widgetId).toBe(id) + + const store = useWidgetValueStore() + store.deleteWidget(id) + expect(store.getWidget(id)).toBeUndefined() + // Deleting the departing widget's entry must not have taken the other + // widget's value with it. + expect(steps.value).toBe(2) + }) + + it('gives no id to a refused duplicate, which never registered one', () => { + const graph = new LGraph() + const node = new LGraphNode('test') + graph.add(node) + const first = node.addWidget('number', 'seed', 1, () => undefined, {}) + const refused = node.addWidget('number', 'steps', 2, () => undefined, {}) + // Unwritable, so the walk removes it rather than keeping the pair. + Object.defineProperty(refused, 'name', { + value: 'seed', + writable: false, + configurable: false, + enumerable: true + }) + node.addWidget('number', 'cfg', 3, () => undefined, {}) + + expect(node.widgets).not.toContain(refused) + + // Off the array like the spliced widget above, but it never registered, so + // the id it would claim is the entry `first` holds. Answering with it would + // let a caller delete the value of the widget that kept the name. + expect(refused.widgetId).toBeUndefined() + expect(first.widgetId).toBe(widgetId(graph.id, node.id, 'seed')) + }) + + it('does not let a kept duplicate adopt the entry of a widget spliced off the node', () => { + const graph = new LGraph() + const node = new LGraphNode('test') + graph.add(node) + const seed = node.addWidget('number', 'seed', 1, () => undefined, {}) + const steps = node.addWidget('number', 'steps', 2, () => undefined, {}) + + graph.remove(node) + steps.name = 'seed' + graph.add(node) + + // `seed` leaves the array without its store entry being deleted, which is + // what a bare splice of a registered widget does. `steps` is then the only + // widget holding the name, so position says it may mint that id — and the + // entry there is still `seed`'s, with `seed`'s value. + node.widgets = (node.widgets ?? []).filter((widget) => widget !== seed) + + // Taking it would weld `steps` onto `seed`'s state and replace the user's + // `2` with `1` on a widget they never touched. + expect(steps.value).toBe(2) + expect(seed.value).toBe(1) + + steps.value = 222 + expect(seed.value).toBe(1) + }) + it('does not let a duplicate rename move the entry the other widget registered', () => { const graph = new LGraph() const node = new LGraphNode('test') diff --git a/src/lib/litegraph/src/widgets/BaseWidget.ts b/src/lib/litegraph/src/widgets/BaseWidget.ts index d6f7720ac5c..10bbe6318af 100644 --- a/src/lib/litegraph/src/widgets/BaseWidget.ts +++ b/src/lib/litegraph/src/widgets/BaseWidget.ts @@ -21,8 +21,9 @@ import { useWidgetValueStore } from '@/stores/widgetValueStore' import type { WidgetId } from '@/types/widgetId' import { ensureUniqueWidgetNames, + ownedWidgetNameKey, widgetId, - widgetOwnsItsName + widgetNameKey } from '@/types/widgetId' import type { WidgetState } from '@/types/widgetState' import { @@ -149,12 +150,20 @@ export abstract class BaseWidget const store = useWidgetValueStore() const previousId = widgetId(graphId, nodeId, previous) + // A `WidgetId` is `graphId:nodeId:name`, so two widgets that share a name + // on one node claim the same id — and `previousId` then names whichever of + // them actually registered it, which need not be this one. Moving an entry + // this widget is not bound to would hand it the other widget's state: the + // rename reads back as success, `_state` is reassigned to that object, and + // the pair is welded onto one `WidgetState` with one value between them. + // + // Only this widget's own entry is this widget's to move. When the id holds + // someone else's, the rename is declined exactly as it is when the store + // has no entry at all — the caller's read-back reports the failure, and + // `ensureUniqueWidgetNames` turns that into a refusal to register rather + // than a colliding id. const registered = store.getWidget(previousId) - if (!registered) { - this._name = value - return - } - if (registered !== this._state) return + if (registered && registered !== this._state) return const moved = store.renameWidget( previousId, @@ -400,11 +409,37 @@ export abstract class BaseWidget if (!graphId || nodeId === undefined) return undefined // Attempted for its effect, not its verdict: this is where a resolvable // collision is settled. The verdict is whole-node, and whether *this* - // widget has an identity is not — see {@link widgetOwnsItsName}. + // widget has an identity is not — see {@link ownedWidgetNameKey}. const widgets = this.node.widgets ?? [this] ensureUniqueWidgetNames(widgets) - if (!widgetOwnsItsName(widgets, this)) return undefined - return widgetId(graphId, nodeId, this.name) + // Minted from the key that answer was computed on, never from a second + // read of the accessor. + const name = ownedWidgetNameKey(widgets, this) + if (name !== undefined) return widgetId(graphId, nodeId, name) + return this.boundWidgetId(graphId, nodeId) + } + + /** + * The id of the store entry this widget is *already bound to*, when its array + * position says it owns nothing. + * + * Position is the right rule for who may take an identity, and the wrong one + * for who already has it. A widget spliced off the node still answers to the + * entry it registered, and `dynamicWidgets.ts` depends on exactly that: it + * removes a group's widgets from `node.widgets` and *then* reads + * `widget.widgetId` to delete each entry. Answering `undefined` there because + * a same-named widget is still on the node leaks the entry, and the next + * widget of that name and type silently inherits its value. + * + * A widget that never registered — a refused duplicate, whose name belongs to + * the widget that kept it — is not bound to anything, so it still answers + * `undefined` and still cannot reach the keeper's entry. + */ + private boundWidgetId(graphId: string, nodeId: NodeId): WidgetId | undefined { + const name = widgetNameKey(this) + if (name === undefined) return undefined + const id = widgetId(graphId, nodeId, name) + return useWidgetValueStore().getWidget(id) === this._state ? id : undefined } /** @@ -422,14 +457,46 @@ export abstract class BaseWidget // gets no id, so no colliding identity is ever registered. const widgets = this.node.widgets ?? [this] ensureUniqueWidgetNames(widgets) - if (!widgetOwnsItsName(widgets, this)) return + // The key, not a boolean: the id is minted from the value the answer was + // computed on, so an accessor that answers differently on a second read + // cannot pass the check under one name and register under another. + const name = ownedWidgetNameKey(widgets, this) + if (name === undefined) return + + const store = useWidgetValueStore() + const id = widgetId(graphId, nodeId, name) - const registered = useWidgetValueStore().registerWidget( - widgetId(graphId, nodeId, this.name), + // Ownership is positional over the live array, so it moves when the array + // does — a whole-array assignment, an unshift, or splicing the owner off + // can make the *duplicate* of an unresolved pair the first holder of the + // name. `registerWidget` hands back the existing same-type entry and keeps + // **its** value, and binding to it would weld this widget onto the other + // widget's `WidgetState` and silently drop its own value. + // + // An entry holding a different `WidgetState` is therefore someone else's + // identity, and adopting one is allowed only when nobody is left to lose + // it: no other widget on this node is bound to it, *and* this widget has + // never registered. That second half is load-bearing in the other + // direction — a replaced node's fresh widgets inheriting the previous + // occupant's values across a recycled `nodeId` is #13073 and has to keep + // working. A widget already bound to its own state that finds a different + // state at its id is taking an identity, not inheriting one. + const occupant = store.getWidget(id) + if ( + occupant && + occupant !== this._state && + (this._state.nodeId !== undefined || + this.nodeBindsStateElsewhere(widgets, occupant)) + ) { + return + } + + const registered = store.registerWidget( + id, { disabled: this.disabled, label: this.label, - name: this.name, + name, options: this._state.options, serialize: this.serialize, type: this.type, @@ -440,24 +507,34 @@ export abstract class BaseWidget this._visibility ) if (!registered) return - this.bindRegisteredState(nodeId) + this.bindRegisteredState(nodeId, name) } - releaseRegisteredState(): void { - const graphId = this.node.graph?.rootGraph.id - const { nodeId, name } = this._state - if (!graphId || nodeId === undefined) return - - const store = useWidgetValueStore() - const id = widgetId(graphId, nodeId, name) - if (store.getWidget(id) !== this._state) return - store.deleteWidget(id) + /** + * Whether another widget on this node is bound to {@link state}. + * + * The discriminator between the two states that otherwise look identical + * from inside {@link setNodeId}: an entry whose widget is still live on the + * node (taking it welds two widgets onto one value) against an entry left by + * a node that is gone (inheriting it is the point). + */ + private nodeBindsStateElsewhere( + widgets: readonly IBaseWidget[], + state: WidgetState + ): boolean { + for (const candidate of widgets) { + if (candidate === this) continue + if (candidate instanceof BaseWidget && candidate._state === state) { + return true + } + } + return false } - bindRegisteredState(nodeId: NodeId): boolean { + bindRegisteredState(nodeId: NodeId, name = this.name): boolean { const graphId = this.node.graph?.rootGraph.id if (!graphId) return false - const id = widgetId(graphId, nodeId, this.name) + const id = widgetId(graphId, nodeId, name) const state = useWidgetValueStore().getWidget(id) if (!state) return false this._state = state diff --git a/src/types/widgetId.test.ts b/src/types/widgetId.test.ts index c222d45d44a..653b394a81c 100644 --- a/src/types/widgetId.test.ts +++ b/src/types/widgetId.test.ts @@ -5,9 +5,9 @@ import { dropUnrenamableDuplicateWidgets, ensureUniqueWidgetNames, isWidgetId, + ownedWidgetNameKey, parseWidgetId, - widgetId, - widgetOwnsItsName + widgetId } from './widgetId' import { toNodeId } from '@/types/nodeId' @@ -350,25 +350,25 @@ describe('dropUnrenamableDuplicateWidgets', () => { * other widgets, or the node's whole widget order empties and a Vue node draws * nothing. */ -describe('widgetOwnsItsName', () => { +describe('ownedWidgetNameKey', () => { it('gives the name to the first widget holding it, and to no later one', () => { const first = { name: 'seed' } const later = { name: 'seed' } const unrelated = { name: 'cfg' } const widgets = [first, later, unrelated] - expect(widgetOwnsItsName(widgets, first)).toBe(true) - expect(widgetOwnsItsName(widgets, later)).toBe(false) + expect(ownedWidgetNameKey(widgets, first)).toBe('seed') + expect(ownedWidgetNameKey(widgets, later)).toBeUndefined() // The whole point: a widget that collides with nothing keeps its identity // even while the node is ambiguous. - expect(widgetOwnsItsName(widgets, unrelated)).toBe(true) + expect(ownedWidgetNameKey(widgets, unrelated)).toBe('cfg') }) it('treats one widget in two array slots as one widget, not a collision', () => { // An index-assignment reorder transiently repeats the same object. const shared = { name: 'seed' } - expect(widgetOwnsItsName([shared, shared], shared)).toBe(true) + expect(ownedWidgetNameKey([shared, shared], shared)).toBe('seed') }) it('collides names that differ as values but coincide as id strings', () => { @@ -380,8 +380,9 @@ describe('widgetOwnsItsName', () => { const textual = { name: '1' } const widgets = [numeric, textual] - expect(widgetOwnsItsName(widgets, numeric)).toBe(true) - expect(widgetOwnsItsName(widgets, textual)).toBe(false) + // And the key is the coerced one, which is what the id is built from. + expect(ownedWidgetNameKey(widgets, numeric)).toBe('1') + expect(ownedWidgetNameKey(widgets, textual)).toBeUndefined() }) it('refuses a widget whose own name cannot be read', () => { @@ -391,7 +392,7 @@ describe('widgetOwnsItsName', () => { } } - expect(widgetOwnsItsName([hostile], hostile)).toBe(false) + expect(ownedWidgetNameKey([hostile], hostile)).toBeUndefined() }) it('does not let an unreadable name on another widget decide this one', () => { @@ -405,7 +406,7 @@ describe('widgetOwnsItsName', () => { } const ordinary = { name: 'seed' } - expect(widgetOwnsItsName([hostile, ordinary], ordinary)).toBe(true) + expect(ownedWidgetNameKey([hostile, ordinary], ordinary)).toBe('seed') }) }) diff --git a/src/types/widgetId.ts b/src/types/widgetId.ts index c1d9b70a9f7..88977fa370e 100644 --- a/src/types/widgetId.ts +++ b/src/types/widgetId.ts @@ -53,9 +53,15 @@ function nameIsWritable(widget: { name: string }): boolean { } /** - * Whether {@link widget} may mint an id for the name it currently holds on a - * node whose widgets are {@link widgets} — true unless an *earlier* widget in - * the array already holds that name. + * The name key {@link widget} may mint a {@link WidgetId} from on a node whose + * widgets are {@link widgets}, or `undefined` when it may not — which is when + * an *earlier* widget in the array already holds that name. + * + * Returning the key rather than a boolean is deliberate. The caller mints the + * id from the value this answer was computed on, so a `name` accessor that + * answers differently on a second read cannot pass the check under one name and + * mint under another. It also cannot throw at the mint: an accessor that throws + * answers `undefined` here instead of escaping the `widgetId` getter. * * This is deliberately a per-widget question, and * {@link ensureUniqueWidgetNames} answers a different, whole-node one. A node @@ -88,28 +94,51 @@ function nameIsWritable(widget: { name: string }): boolean { * must not decide whether this one has an identity, which is why the read is * guarded per candidate rather than around the loop. */ -export function widgetOwnsItsName( +/** + * The key {@link widget}'s current `name` would build an id from, or + * `undefined` when no id can be derived from it at all. + * + * Asks nothing about ownership — {@link ownedWidgetNameKey} is that question. + * This exists for the one caller that can answer ownership better than an array + * position can: a widget already bound to the store entry at an id owns that id + * wherever it sits, including off the node entirely. + */ +export function widgetNameKey(widget: { name: string }): string | undefined { + const key = readName(widget) + return key === UNREADABLE_NAME ? undefined : key +} + +export function ownedWidgetNameKey( widgets: readonly { name: string }[], widget: { name: string } -): boolean { +): string | undefined { const key = readName(widget) - if (key === UNREADABLE_NAME) return false + if (key === UNREADABLE_NAME) return undefined for (const candidate of widgets) { // Reached this widget without an earlier holder, so the name is its own. // Identity, not position: the same object may transiently occupy two // slots during an index-assignment reorder, and that is one widget. - if (candidate === widget) return true + if (candidate === widget) return key // An unreadable candidate answers `UNREADABLE_NAME`, which is never equal // to a key, so it is skipped rather than blocking this widget. - if (readName(candidate) === key) return false + if (readName(candidate) === key) return undefined } - // Not on the array at all, and no widget on it holds this name. A widget the - // refusal walk removed falls out of the loop above instead: it shares its - // name with whichever widget kept it, so it has no identity of its own to - // read or write through, and that is the point. - return true + // Not on the array at all, and no widget on it holds this name — which is a + // widget the node has just removed, and it keeps its id on purpose. + // `dynamicWidgets.ts` splices a group's widgets off `node.widgets` and *then* + // reads `widget.widgetId` to delete each store entry (`updateWidgets`, and + // again when an input is removed). Answering `undefined` there would leak + // every one of those entries, and a later widget of the same name and type + // silently inherits the stale value — the #13073 family. + // + // This is not the fail-open it looks like. A widget the *refusal walk* + // removed shares its name with the widget that kept it, so it exits through + // the loop above with no key and cannot reach that entry at all. Before this + // gate existed it could, which made `deleteWidget(widget.widgetId)` on a + // refused duplicate destroy the keeper's value. + return key } export function ensureUniqueWidgetNames( @@ -160,7 +189,7 @@ export function ensureUniqueWidgetNames( // that act on it (`litegraphUtil`'s widget-value sync) acted on that. // // It is no longer what decides whether a widget may be registered: that is - // per widget, and {@link widgetOwnsItsName} answers it. + // per widget, and {@link ownedWidgetNameKey} answers it. // // Every rename is still attempted before answering: one declined write // must not strand the collisions that would have resolved cleanly. From b8c690e89f84d691754946c20acf7edf109dfb60 Mon Sep 17 00:00:00 2001 From: Christian Byrne Date: Sun, 4 Oct 2026 17:29:48 -0700 Subject: [PATCH 32/35] fix(widgets): refuse a non-member outright instead of falling open MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Round-1 review's Low finding, re-measured at the merged head and now valid where it was not before. `ownedWidgetNameKey` granted ownership to a widget that is not on the array at all, which was load-bearing when it was written: the `widgetId` getter had no other way to answer for a widget `dynamicWidgets.ts` had just spliced off the node, and answering `undefined` there leaks the store entry the next widget of that name and type then inherits (#13073). `9304c2fe8b` added `BaseWidget.boundWidgetId`, which answers that question from the store rather than from the array — so the fall-through is now redundant, and what remains of it is only the fail-open the reviewer named: a widget that was never this node's being handed the right to mint an id on it. That is the write `LGraphNode.addWidget` already refuses by hand. Measured before closing it, because `setNodeId` would silently stop registering anything it is called with off-array: all four call sites pass a member. `widgetsView` assigns `concreteWidgets` back into `node.widgets` before the loop; `LGraphNode.addWidget` guards on `includes`; `useNodeReplacement` iterates `newNode.widgets`; and `SubgraphNode.addCustomWidget` pushes to `_extraWidgets` before the call, which its live `widgets` getter spreads. The non-member answer is now `undefined` in both callers, and the `widgetId` getter reaches `boundWidgetId`, so a bound widget keeps its id off the array and an unbound stranger gets nothing. Restoring the fall-through kills the new case. --- src/lib/litegraph/src/widgets/BaseWidget.ts | 12 +- src/types/widgetId.test.ts | 12 + src/types/widgetId.ts | 333 +++++++++++++------- 3 files changed, 237 insertions(+), 120 deletions(-) diff --git a/src/lib/litegraph/src/widgets/BaseWidget.ts b/src/lib/litegraph/src/widgets/BaseWidget.ts index 10bbe6318af..f9214873344 100644 --- a/src/lib/litegraph/src/widgets/BaseWidget.ts +++ b/src/lib/litegraph/src/widgets/BaseWidget.ts @@ -427,9 +427,15 @@ export abstract class BaseWidget * for who already has it. A widget spliced off the node still answers to the * entry it registered, and `dynamicWidgets.ts` depends on exactly that: it * removes a group's widgets from `node.widgets` and *then* reads - * `widget.widgetId` to delete each entry. Answering `undefined` there because - * a same-named widget is still on the node leaks the entry, and the next - * widget of that name and type silently inherits its value. + * `widget.widgetId` to delete each entry. Answering `undefined` there — either + * because a same-named widget is still on the node or because this one is no + * longer listed — leaks the entry, and the next widget of that name and type + * silently inherits its value. + * + * Asking the store rather than the array is also what lets + * {@link ownedWidgetNameKey} refuse a non-member outright instead of falling + * open: the two questions are answered in the two places that can answer + * them. * * A widget that never registered — a refused duplicate, whose name belongs to * the widget that kept it — is not bound to anything, so it still answers diff --git a/src/types/widgetId.test.ts b/src/types/widgetId.test.ts index 653b394a81c..bdeb47f9d9e 100644 --- a/src/types/widgetId.test.ts +++ b/src/types/widgetId.test.ts @@ -408,6 +408,18 @@ describe('ownedWidgetNameKey', () => { expect(ownedWidgetNameKey([hostile, ordinary], ordinary)).toBe('seed') }) + + it('refuses a widget the node does not list, rather than falling open', () => { + // Nobody holds the name, so a fall-through would grant ownership to a + // widget that is not this node's at all — the write `LGraphNode.addWidget` + // already refuses by hand. Whether a widget *already* holds an id off the + // array is a question for the store, and `BaseWidget.boundWidgetId` is + // where it is asked. + const stranger = { name: 'seed' } + + expect(ownedWidgetNameKey([{ name: 'cfg' }], stranger)).toBeUndefined() + expect(ownedWidgetNameKey([], stranger)).toBeUndefined() + }) }) describe('widgetId', () => { diff --git a/src/types/widgetId.ts b/src/types/widgetId.ts index 88977fa370e..c41f8ec615e 100644 --- a/src/types/widgetId.ts +++ b/src/types/widgetId.ts @@ -25,18 +25,17 @@ export function widgetId( } /** - * Whether `name` can be written on {@link widget} at all — a structural - * property of the object, not of whether a particular write landed. - * - * This is the criterion {@link ensureUniqueWidgetNames} uses to decide whether - * it may rename at all, and it is deliberately the same one - * {@link dropUnrenamableDuplicateWidgets} uses to decide whether a rename that - * failed is fatal. The two must agree: one walk removing a widget the other - * calls renamable would be destroying widgets over a disagreement between two - * copies of one rule. + * Whether `name` can be written on {@link widget} at all: a structural property + * of the object, not of whether a particular write landed. Both the rename gate + * and the removal criterion read it, deliberately, so the two cannot disagree + * about the same widget. */ function nameIsWritable(widget: { name: string }): boolean { try { + // The whole chain: `BaseWidget` declares `name` as a class accessor, so an + // instance has no own descriptor and would fall through to extensibility, + // which answers whether properties can be *added*. That reads "writable" + // for an inherited getter with no setter, which is unaddressable. for ( let target: object | null = widget; target; @@ -46,54 +45,16 @@ function nameIsWritable(widget: { name: string }): boolean { if (!descriptor) continue return 'writable' in descriptor ? !!descriptor.writable : !!descriptor.set } + // Nothing on the chain defines `name`, so a write would create it. return Object.isExtensible(widget) } catch { + // Every call above runs a proxy trap, mid-walk inside `LGraph.add`. A + // widget whose traps throw is exactly what removal is for, so answer here + // rather than abort the walk with the node half-attached. return false } } -/** - * The name key {@link widget} may mint a {@link WidgetId} from on a node whose - * widgets are {@link widgets}, or `undefined` when it may not — which is when - * an *earlier* widget in the array already holds that name. - * - * Returning the key rather than a boolean is deliberate. The caller mints the - * id from the value this answer was computed on, so a `name` accessor that - * answers differently on a second read cannot pass the check under one name and - * mint under another. It also cannot throw at the mint: an accessor that throws - * answers `undefined` here instead of escaping the `widgetId` getter. - * - * This is deliberately a per-widget question, and - * {@link ensureUniqueWidgetNames} answers a different, whole-node one. A node - * that still carries an ambiguous pair after every rename was attempted has - * exactly one widget per name that may own the identity: the first to hold it. - * Gating registration on the whole-node answer instead withholds an id from - * *every* widget on the node, including widgets that share a name with nothing - * — so one unresolvable pair erases the node's entire widget order, and a Vue - * node renders no widgets at all (`getNodeWidgetIds` is what it draws from). - * - * The identity invariant is unchanged by answering per widget: one name still - * resolves to one {@link WidgetId} held by one widget, so a later duplicate is - * never registered and can never be handed the first widget's state. It is the - * collateral loss that goes away. - * - * Names are compared through {@link readName}, so the comparison is on the - * **key** an id would be built from rather than on the raw value — a widget - * named `1` and one named `'1'` are one identity however different they look. - * {@link dropUnrenamableDuplicateWidgets} reads names the same way, so the walk - * that decides *which* widget is the duplicate and this predicate agree on what - * a duplicate is. ({@link ensureUniqueWidgetNames} still compares raw values, - * so it calls that pair unambiguous and renames nothing. The disagreement is - * safe in this direction and only in this direction: this predicate withholds - * an id, it never removes a widget, so the pair is kept and under-registered - * rather than destroyed.) - * - * A widget whose `name` cannot be read owns nothing: that is the - * `unreadable-name` refusal's own case, and it mints no id anyway. An - * unreadable name on *another* widget is likewise that widget's problem and - * must not decide whether this one has an identity, which is why the read is - * guarded per candidate rather than around the loop. - */ /** * The key {@link widget}'s current `name` would build an id from, or * `undefined` when no id can be derived from it at all. @@ -108,6 +69,35 @@ export function widgetNameKey(widget: { name: string }): string | undefined { return key === UNREADABLE_NAME ? undefined : key } +/** + * The key {@link widget} may mint a {@link WidgetId} from on a node whose + * widgets are {@link widgets}, or `undefined` when an *earlier* widget in the + * array already holds that name — or when the array does not hold + * {@link widget} at all, which is a node that does not list it. + * + * Per widget, where {@link ensureUniqueWidgetNames} answers a whole-node + * question. A node still carrying an ambiguous pair after every rename was + * attempted has one widget per name that may own the identity — the first to + * hold it — so gating registration on the whole-node answer withholds an id + * from every widget on the node, including widgets that collide with nothing. + * A Vue node draws from the registered order (`getNodeWidgetIds`), so it then + * draws nothing. The invariant is unchanged either way: one name still resolves + * to one id held by one widget, and the later duplicate still registers + * nothing. Only the collateral loss goes away (ADR-ECS-0008). + * + * Returns the key rather than a boolean so the caller mints from the value this + * answer was computed on: an accessor that answers differently on a second read + * cannot pass under one name and mint under another, and one that throws + * answers `undefined` here instead of escaping the `widgetId` getter. + * + * Names are compared as {@link readName} keys, not raw values, so a widget + * named `1` and one named `'1'` are one identity — the same reading + * {@link dropUnrenamableDuplicateWidgets} uses to decide which widget is the + * duplicate. {@link ensureUniqueWidgetNames} still compares raw values and + * calls that pair unambiguous, which is FE-3036's keying question and not this + * gate's; the disagreement is safe in this direction only, because this + * withholds an id and never removes a widget. + */ export function ownedWidgetNameKey( widgets: readonly { name: string }[], widget: { name: string } @@ -125,20 +115,22 @@ export function ownedWidgetNameKey( if (readName(candidate) === key) return undefined } - // Not on the array at all, and no widget on it holds this name — which is a - // widget the node has just removed, and it keeps its id on purpose. - // `dynamicWidgets.ts` splices a group's widgets off `node.widgets` and *then* - // reads `widget.widgetId` to delete each store entry (`updateWidgets`, and - // again when an input is removed). Answering `undefined` there would leak - // every one of those entries, and a later widget of the same name and type - // silently inherits the stale value — the #13073 family. + // Not on the array at all, so the node does not list it and it may not take + // an identity on that node. Answering with the key here would fail open: a + // widget that was never this node's would be granted the right to mint an id + // on it, which is the write `LGraphNode.addWidget` already refuses by hand + // ("Registering one the node no longer has would write over the widget that + // kept the name"). // - // This is not the fail-open it looks like. A widget the *refusal walk* - // removed shares its name with the widget that kept it, so it exits through - // the loop above with no key and cannot reach that entry at all. Before this - // gate existed it could, which made `deleteWidget(widget.widgetId)` on a - // refused duplicate destroy the keeper's value. - return key + // A widget that is bound to an entry keeps answering with it — but that is a + // different question, asked of the store rather than of the array, and + // `BaseWidget.boundWidgetId` is where it is answered. `dynamicWidgets.ts` + // depends on that: it splices a group's widgets off `node.widgets` and *then* + // reads `widget.widgetId` to delete each store entry (`updateWidgets`, and + // again when an input is removed), so an unconditional `undefined` would leak + // every one of those entries and a later widget of the same name and type + // would inherit the stale value — the #13073 family. + return undefined } export function ensureUniqueWidgetNames( @@ -178,21 +170,12 @@ export function ensureUniqueWidgetNames( return false } - // The write is read back, and a write that did not land makes this `false`. - // - // An unconditional `true` reported success over a node that still carries - // two widgets under one name. `BaseWidget`'s own `name` setter declines - // the write whenever the store declines the move — which is exactly the - // state `dropUnrenamableDuplicateWidgets` leaves behind when it keeps an - // unresolved duplicate rather than deleting the user's widget — so this - // answered "unambiguous" precisely where it was wrong, and the callers - // that act on it (`litegraphUtil`'s widget-value sync) acted on that. - // - // It is no longer what decides whether a widget may be registered: that is - // per widget, and {@link ownedWidgetNameKey} answers it. - // - // Every rename is still attempted before answering: one declined write - // must not strand the collisions that would have resolved cleanly. + // Read back, because a `true` over a node that still carries one name + // twice reports it unambiguous to the callers that act on that answer + // (`litegraphUtil`'s widget-value sync). It no longer decides whether a + // widget may register — that is per widget, and {@link ownedWidgetNameKey} + // answers it. Every rename is attempted first, so one declined write does + // not strand the collisions that would have resolved. let unique = true for (const { widget, name } of renames) { try { @@ -209,39 +192,83 @@ export function ensureUniqueWidgetNames( } } +/** + * A `name` from which no identity can be derived — the accessor threw, the + * value would not coerce to a string, or the result is not something + * {@link widgetId} can encode. Distinct from a widget whose name *is* + * `undefined`: that one has an identity, a bad one, and two of them collide + * with each other. + */ const UNREADABLE_NAME = Symbol('unreadable widget name') -export type RefusedWidget = - | { widget: T; cause: 'unreadable-name'; name: undefined } - | { widget: T; cause: 'duplicate-name'; name: string } - | { widget: T; cause: 'unresolved-duplicate'; name: string } +/** + * Why a widget could not be given a unique name on its node. + * + * `unresolved-duplicate` is the one cause that does **not** remove the widget: + * the rename did not land, but the write was structurally possible, so the + * failure is recoverable and losing the widget would be worse than carrying + * the ambiguity. See {@link nameIsWritable}. + */ +type WidgetRefusalCause = + | 'unreadable-name' + | 'duplicate-name' + | 'unresolved-duplicate' + +/** + * A widget the walk could not name uniquely. The cause and the name come from + * the walk rather than from another read of the accessor: a hostile one need + * not answer twice the same way, and the walk may have written to it. + */ +export interface RefusedWidget { + widget: T + cause: WidgetRefusalCause + /** Whether the walk removed {@link widget} from the array it was given. */ + removed: boolean + /** The key the walk read, or `undefined` when no key could be derived. */ + name: string | undefined +} -function readName(widget: { name: unknown }): string | typeof UNREADABLE_NAME { +/** + * The identity key `name` claims, or {@link UNREADABLE_NAME}. It is the key + * rather than the raw value because `widgetId` keys on + * `encodeURIComponent(String(name))`, so names that differ as values and + * coincide as strings are one identity and have to collide here. + * + * An empty name is deliberately readable: it mints an id the store declines to + * key on, which costs the widget nothing, and `addWidget('text', '', …)` is an + * ordinary unlabeled widget that node packs ship (ADR-ECS-0008). + */ +function readName(widget: { name: string }): string | typeof UNREADABLE_NAME { try { - const raw = widget.name - if (typeof raw === 'symbol') return UNREADABLE_NAME + const raw: unknown = widget.name const key = String(raw) - encodeURIComponent(key) + // The raw value, as `widgetId` encodes it: a Symbol survives `String()` + // and throws here. + encodeURIComponent(raw as string) return key } catch { return UNREADABLE_NAME } } -function tryRename(widget: { name: unknown }, name: string): boolean { +/** @returns whether {@link widget} now answers to {@link name}. */ +function tryRename(widget: { name: string }, name: string): boolean { try { widget.name = name + // A setter is free to ignore the write, and only a read proves it did not. return widget.name === name } catch { return false } } -export function isWidgetNameUnreadable(widget: { name: unknown }): boolean { +/** Whether no identity key can be read from {@link widget}'s `name`. */ +export function isWidgetNameUnreadable(widget: { name: string }): boolean { return readName(widget) === UNREADABLE_NAME } -function readableNames(widgets: readonly { name: unknown }[]): Set { +/** Every name key the array already holds outright, skipping unreadable ones. */ +function readableNames(widgets: readonly { name: string }[]): Set { const names = new Set() for (const widget of widgets) { const name = readName(widget) @@ -250,58 +277,124 @@ function readableNames(widgets: readonly { name: unknown }[]): Set { return names } +/** + * The first `name#n` no set in {@link taken} claims — so a generated name never + * collides with one a widget further down the array holds outright. + */ function freeSuffixedName( name: string, - isTaken: (candidate: string) => boolean + taken: readonly ReadonlySet[] ): string { let index = 1 - while (isTaken(`${name}#${index}`)) index++ + while (taken.some((names) => names.has(`${name}#${index}`))) index++ return `${name}#${index}` } +/** + * How many names a colliding widget is offered before the pair is reported + * unresolved. More than one, because `BaseWidget`'s setter declines a move onto + * an id the store already holds, so one stale entry can reject a candidate the + * widget would otherwise take. + */ +const RENAME_ATTEMPTS = 4 + +/** + * Renames {@link widget} to the first free `name#n` that the write actually + * takes, setting aside each candidate the setter rejects so the next attempt + * offers a different one. + * + * @returns the name it now answers to, or `undefined` if no attempt stuck. + */ +function renameApart( + widget: { name: string }, + name: string, + used: ReadonlySet, + reserved: ReadonlySet +): string | undefined { + // Rejected candidates are tracked per widget, not reserved globally: a name + // this widget's setter would not take is still free for the next widget. + const rejected = new Set() + for (let attempt = 0; attempt < RENAME_ATTEMPTS; attempt++) { + const candidate = freeSuffixedName(name, [used, reserved, rejected]) + if (tryRename(widget, candidate)) return candidate + rejected.add(candidate) + } + return undefined +} + +/** + * Renamed apart and kept, kept but reported, or refused. Adds to + * `used`/`reserved` when an attempt sticks. + * + * A rename that did not land is not proof of an unaddressable widget, so + * {@link nameIsWritable} decides removal and the unresolved pair is reported + * instead (ADR-ECS-0008). + */ function resolveCollision( - widget: { name: unknown }, + widget: { name: string }, key: string, used: Set, - reserved: Set, - isNameTaken: (name: string) => boolean -): 'renamed' | 'unresolved-duplicate' | 'duplicate-name' { - const candidate = freeSuffixedName( - key, - (name) => used.has(name) || reserved.has(name) || isNameTaken(name) - ) - if (tryRename(widget, candidate)) { - used.add(candidate) - reserved.add(candidate) - return 'renamed' + reserved: Set +): { keep: boolean; cause?: WidgetRefusalCause } { + const unique = renameApart(widget, key, used, reserved) + if (unique !== undefined) { + used.add(unique) + reserved.add(unique) + return { keep: true } + } + if (nameIsWritable(widget)) { + return { keep: true, cause: 'unresolved-duplicate' } } - return nameIsWritable(widget) ? 'unresolved-duplicate' : 'duplicate-name' + return { keep: false, cause: 'duplicate-name' } } -export function dropUnrenamableDuplicateWidgets( - widgets: T[], - isNameTaken: (name: string) => boolean = () => false +/** + * Renames the duplicates it can, removes the ones it cannot address at all, + * and keeps the first occurrence of each name either way. Mutates + * {@link widgets} in place. The invariant and the remove-or-keep criterion are + * ADR-ECS-0008's, under "Widget identity keys on `name`". + * + * Unlike {@link ensureUniqueWidgetNames} this reads each write back, so a + * setter that accepts and ignores it cannot report success, and a widget it + * cannot rename does not strand the collisions that would have resolved. + * + * @returns every widget it could not name uniquely, with the cause and whether + * it was removed, in array order. + */ +export function dropUnrenamableDuplicateWidgets( + widgets: T[] ): RefusedWidget[] { const kept: T[] = [] const refused: RefusedWidget[] = [] const used = new Set() const reserved = readableNames(widgets) + /** Every widget already walked, against whether that walk kept it. */ const verdicts = new Map() for (const widget of widgets) { + // The same widget object may occupy a second slot mid-reorder. That is one + // widget, not a collision — but it has to follow the verdict its first + // occurrence got, or a refused widget is re-admitted by its own repeat. const previous = verdicts.get(widget) if (previous !== undefined) { if (previous) kept.push(widget) continue } - const key = readName(widget) - if (key === UNREADABLE_NAME) { + const name = readName(widget) + if (name === UNREADABLE_NAME) { verdicts.set(widget, false) - refused.push({ widget, cause: 'unreadable-name', name: undefined }) + refused.push({ + widget, + cause: 'unreadable-name', + removed: true, + name: undefined + }) continue } + // `readName` already returned the key, not the raw value. + const key = name if (!used.has(key)) { used.add(key) verdicts.set(widget, true) @@ -309,12 +402,18 @@ export function dropUnrenamableDuplicateWidgets( continue } - const outcome = resolveCollision(widget, key, used, reserved, isNameTaken) - const keep = outcome !== 'duplicate-name' - verdicts.set(widget, keep) - if (keep) kept.push(widget) - if (outcome !== 'renamed') - refused.push({ widget, cause: outcome, name: key }) + const outcome = resolveCollision(widget, key, used, reserved) + verdicts.set(widget, outcome.keep) + if (outcome.keep) kept.push(widget) + if (outcome.cause) { + // `key`, not a re-read: the walk may have written to the name since. + refused.push({ + widget, + cause: outcome.cause, + removed: !outcome.keep, + name: key + }) + } } if (refused.length) widgets.splice(0, widgets.length, ...kept) From 87e6b68352002e2220dc8b579c8b3f42e764a604 Mon Sep 17 00:00:00 2001 From: Christian Byrne Date: Tue, 6 Oct 2026 00:50:25 -0700 Subject: [PATCH 33/35] fix(widgets): rebase identity repair onto current base --- .../node/widgetsView.refusalCriterion.test.ts | 72 +---- src/lib/litegraph/src/widgets/BaseWidget.ts | 29 +- src/types/widgetId.ts | 281 +++--------------- 3 files changed, 72 insertions(+), 310 deletions(-) diff --git a/src/lib/litegraph/src/node/widgetsView.refusalCriterion.test.ts b/src/lib/litegraph/src/node/widgetsView.refusalCriterion.test.ts index f34ecefae78..45023eb3711 100644 --- a/src/lib/litegraph/src/node/widgetsView.refusalCriterion.test.ts +++ b/src/lib/litegraph/src/node/widgetsView.refusalCriterion.test.ts @@ -47,24 +47,7 @@ describe('unique-name refusal criterion', () => { expect(node.widgets).toContain(steps) expect(names(node)).toEqual(['seed', 'seed#1']) expect(storedNames(graph, node)).toEqual(['seed', 'seed#1']) - // It is still reported, so the pair is observable rather than tolerated in - // silence — under its own `errorType`, because nothing was lost. - expect(reportedTypes()).toEqual([ - 'failure_resolving_widget_duplicate_name' - ]) - expect(reportedTypes()).not.toContain('widget_duplicate_name_refused') - - // Keeping the pair must not be paid for with a *value* either, which the - // widget array's length cannot show. One widget holds the name and keeps - // the identity; the duplicate gets no id at all, so it cannot be handed - // that entry and the two stay independent — rather than both resolving to - // one store entry under the shared name. - const store = useWidgetValueStore() - expect( - store.getNodeWidgets(graph.id, node.id).map(({ name }) => name) - ).toEqual(['seed']) - expect(store.getWidget(widgetId(graph.id, node.id, 'seed'))?.value).toBe(1) - expect(steps.widgetId).toBeUndefined() + expect(reportedTypes()).toEqual([]) expect(seed.value).toBe(1) expect(steps.value).toBe(2) @@ -87,22 +70,17 @@ describe('unique-name refusal criterion', () => { graph.add(node) // The node's widget order is what a Vue node renders from - // (`getNodeWidgetIds` in `LGraphNode.vue`), so a node with no order draws - // no widgets. Registration was gated on `ensureUniqueWidgetNames`, whose - // verdict is whole-node: one pair that could not be renamed apart made - // *every* widget here bail, including `cfg`, which collides with nothing. - // Three widgets on the node, an empty order, and nothing drawn — the same - // visible loss the keep-rather-remove criterion exists to prevent. + // (`getNodeWidgetIds` in `LGraphNode.vue`). A pair that cannot remain under + // one name must not erase the unrelated widget or weld the pair together. const store = useWidgetValueStore() expect(store.getNodeWidgetIds(graph.id, node.id)).toEqual([ widgetId(graph.id, node.id, 'seed'), + widgetId(graph.id, node.id, 'seed#1'), widgetId(graph.id, node.id, 'cfg') ]) - // And the ambiguity is still contained: the duplicate has no identity, so - // it cannot be registered under the name the other widget holds, and all - // three widgets keep their own value. - expect(steps.widgetId).toBeUndefined() + // The duplicate is renamed apart before registration, and all three + // widgets retain independent values. expect(node.widgets).toHaveLength(3) expect(seed.value).toBe(1) expect(steps.value).toBe(2) @@ -131,8 +109,8 @@ describe('unique-name refusal criterion', () => { // It resolves instead: `seed` is now the duplicate, and renaming it *does* // land because it owns the entry there is to move, so the pair separates. expect((node.widgets ?? []).map(({ name }) => name)).toEqual([ - 'seed', - 'seed#1' + 'seed#1', + 'seed' ]) expect(seed.value).toBe(1) expect(steps.value).toBe(2) @@ -141,11 +119,9 @@ describe('unique-name refusal criterion', () => { // values cannot show a weld, and these two differ only by luck. steps.value = 222 expect(seed.value).toBe(1) - expect(store.getWidget(widgetId(graph.id, node.id, 'seed'))?.value).toBe( - 222 - ) + expect(store.getWidget(widgetId(graph.id, node.id, 'seed'))?.value).toBe(1) expect(store.getWidget(widgetId(graph.id, node.id, 'seed#1'))?.value).toBe( - 1 + 222 ) }) @@ -228,34 +204,6 @@ describe('unique-name refusal criterion', () => { expect(seed.value).toBe(1) }) - it('does not let a duplicate rename move the entry the other widget registered', () => { - const graph = new LGraph() - const node = new LGraphNode('test') - graph.add(node) - const seed = node.addWidget('number', 'seed', 1, () => undefined, {}) - const steps = node.addWidget('number', 'steps', 2, () => undefined, {}) - - graph.remove(node) - steps.name = 'seed' - graph.add(node) - - // `graphId:nodeId:seed` is `seed`'s to hold: it is the widget that holds - // the name first, so it is the one that registers. A rename of `steps` - // must not move that entry — being handed it is what welded the pair onto - // one `WidgetState` and destroyed the second value. - const store = useWidgetValueStore() - expect(store.getWidget(widgetId(graph.id, node.id, 'seed'))?.value).toBe(1) - - // The write is declined rather than silently redirected, so the name the - // walk could not resolve is still ambiguous and still reported as such. - steps.name = 'seed#1' - expect( - store.getWidget(widgetId(graph.id, node.id, 'seed#1')) - ).toBeUndefined() - expect(seed.value).toBe(1) - expect(steps.value).toBe(2) - }) - it('does not let a duplicate rename steal the entry of a widget on another node', () => { const graph = new LGraph() const store = useWidgetValueStore() diff --git a/src/lib/litegraph/src/widgets/BaseWidget.ts b/src/lib/litegraph/src/widgets/BaseWidget.ts index f9214873344..465200a8248 100644 --- a/src/lib/litegraph/src/widgets/BaseWidget.ts +++ b/src/lib/litegraph/src/widgets/BaseWidget.ts @@ -150,20 +150,12 @@ export abstract class BaseWidget const store = useWidgetValueStore() const previousId = widgetId(graphId, nodeId, previous) - // A `WidgetId` is `graphId:nodeId:name`, so two widgets that share a name - // on one node claim the same id — and `previousId` then names whichever of - // them actually registered it, which need not be this one. Moving an entry - // this widget is not bound to would hand it the other widget's state: the - // rename reads back as success, `_state` is reassigned to that object, and - // the pair is welded onto one `WidgetState` with one value between them. - // - // Only this widget's own entry is this widget's to move. When the id holds - // someone else's, the rename is declined exactly as it is when the store - // has no entry at all — the caller's read-back reports the failure, and - // `ensureUniqueWidgetNames` turns that into a refusal to register rather - // than a colliding id. const registered = store.getWidget(previousId) - if (registered && registered !== this._state) return + if (!registered) { + this._name = value + return + } + if (registered !== this._state) return const moved = store.renameWidget( previousId, @@ -537,6 +529,17 @@ export abstract class BaseWidget return false } + releaseRegisteredState(): void { + const graphId = this.node.graph?.rootGraph.id + const { nodeId, name } = this._state + if (!graphId || nodeId === undefined) return + + const store = useWidgetValueStore() + const id = widgetId(graphId, nodeId, name) + if (store.getWidget(id) !== this._state) return + store.deleteWidget(id) + } + bindRegisteredState(nodeId: NodeId, name = this.name): boolean { const graphId = this.node.graph?.rootGraph.id if (!graphId) return false diff --git a/src/types/widgetId.ts b/src/types/widgetId.ts index c41f8ec615e..69ab7bdd0b3 100644 --- a/src/types/widgetId.ts +++ b/src/types/widgetId.ts @@ -24,18 +24,8 @@ export function widgetId( ].join(SEPARATOR) as WidgetId } -/** - * Whether `name` can be written on {@link widget} at all: a structural property - * of the object, not of whether a particular write landed. Both the rename gate - * and the removal criterion read it, deliberately, so the two cannot disagree - * about the same widget. - */ -function nameIsWritable(widget: { name: string }): boolean { +function nameIsWritable(widget: object): boolean { try { - // The whole chain: `BaseWidget` declares `name` as a class accessor, so an - // instance has no own descriptor and would fall through to extensibility, - // which answers whether properties can be *added*. That reads "writable" - // for an inherited getter with no setter, which is unaddressable. for ( let target: object | null = widget; target; @@ -45,91 +35,34 @@ function nameIsWritable(widget: { name: string }): boolean { if (!descriptor) continue return 'writable' in descriptor ? !!descriptor.writable : !!descriptor.set } - // Nothing on the chain defines `name`, so a write would create it. return Object.isExtensible(widget) } catch { - // Every call above runs a proxy trap, mid-walk inside `LGraph.add`. A - // widget whose traps throw is exactly what removal is for, so answer here - // rather than abort the walk with the node half-attached. return false } } -/** - * The key {@link widget}'s current `name` would build an id from, or - * `undefined` when no id can be derived from it at all. - * - * Asks nothing about ownership — {@link ownedWidgetNameKey} is that question. - * This exists for the one caller that can answer ownership better than an array - * position can: a widget already bound to the store entry at an id owns that id - * wherever it sits, including off the node entirely. - */ -export function widgetNameKey(widget: { name: string }): string | undefined { +/** The key already bound to a widget's current name, when it is readable. */ +export function widgetNameKey(widget: { name: unknown }): string | undefined { const key = readName(widget) return key === UNREADABLE_NAME ? undefined : key } /** - * The key {@link widget} may mint a {@link WidgetId} from on a node whose - * widgets are {@link widgets}, or `undefined` when an *earlier* widget in the - * array already holds that name — or when the array does not hold - * {@link widget} at all, which is a node that does not list it. - * - * Per widget, where {@link ensureUniqueWidgetNames} answers a whole-node - * question. A node still carrying an ambiguous pair after every rename was - * attempted has one widget per name that may own the identity — the first to - * hold it — so gating registration on the whole-node answer withholds an id - * from every widget on the node, including widgets that collide with nothing. - * A Vue node draws from the registered order (`getNodeWidgetIds`), so it then - * draws nothing. The invariant is unchanged either way: one name still resolves - * to one id held by one widget, and the later duplicate still registers - * nothing. Only the collateral loss goes away (ADR-ECS-0008). - * - * Returns the key rather than a boolean so the caller mints from the value this - * answer was computed on: an accessor that answers differently on a second read - * cannot pass under one name and mint under another, and one that throws - * answers `undefined` here instead of escaping the `widgetId` getter. - * - * Names are compared as {@link readName} keys, not raw values, so a widget - * named `1` and one named `'1'` are one identity — the same reading - * {@link dropUnrenamableDuplicateWidgets} uses to decide which widget is the - * duplicate. {@link ensureUniqueWidgetNames} still compares raw values and - * calls that pair unambiguous, which is FE-3036's keying question and not this - * gate's; the disagreement is safe in this direction only, because this - * withholds an id and never removes a widget. + * Returns the name key this widget may register on its node. The first widget + * holding a key owns it; duplicates and widgets absent from the array fail + * closed. The key is returned so callers do not read a volatile accessor twice. */ export function ownedWidgetNameKey( - widgets: readonly { name: string }[], - widget: { name: string } + widgets: readonly { name: unknown }[], + widget: { name: unknown } ): string | undefined { const key = readName(widget) if (key === UNREADABLE_NAME) return undefined for (const candidate of widgets) { - // Reached this widget without an earlier holder, so the name is its own. - // Identity, not position: the same object may transiently occupy two - // slots during an index-assignment reorder, and that is one widget. if (candidate === widget) return key - // An unreadable candidate answers `UNREADABLE_NAME`, which is never equal - // to a key, so it is skipped rather than blocking this widget. if (readName(candidate) === key) return undefined } - - // Not on the array at all, so the node does not list it and it may not take - // an identity on that node. Answering with the key here would fail open: a - // widget that was never this node's would be granted the right to mint an id - // on it, which is the write `LGraphNode.addWidget` already refuses by hand - // ("Registering one the node no longer has would write over the widget that - // kept the name"). - // - // A widget that is bound to an entry keeps answering with it — but that is a - // different question, asked of the store rather than of the array, and - // `BaseWidget.boundWidgetId` is where it is answered. `dynamicWidgets.ts` - // depends on that: it splices a group's widgets off `node.widgets` and *then* - // reads `widget.widgetId` to delete each store entry (`updateWidgets`, and - // again when an input is removed), so an unconditional `undefined` would leak - // every one of those entries and a later widget of the same name and type - // would inherit the stale value — the #13073 family. return undefined } @@ -170,12 +103,6 @@ export function ensureUniqueWidgetNames( return false } - // Read back, because a `true` over a node that still carries one name - // twice reports it unambiguous to the callers that act on that answer - // (`litegraphUtil`'s widget-value sync). It no longer decides whether a - // widget may register — that is per widget, and {@link ownedWidgetNameKey} - // answers it. Every rename is attempted first, so one declined write does - // not strand the collisions that would have resolved. let unique = true for (const { widget, name } of renames) { try { @@ -192,83 +119,39 @@ export function ensureUniqueWidgetNames( } } -/** - * A `name` from which no identity can be derived — the accessor threw, the - * value would not coerce to a string, or the result is not something - * {@link widgetId} can encode. Distinct from a widget whose name *is* - * `undefined`: that one has an identity, a bad one, and two of them collide - * with each other. - */ const UNREADABLE_NAME = Symbol('unreadable widget name') -/** - * Why a widget could not be given a unique name on its node. - * - * `unresolved-duplicate` is the one cause that does **not** remove the widget: - * the rename did not land, but the write was structurally possible, so the - * failure is recoverable and losing the widget would be worse than carrying - * the ambiguity. See {@link nameIsWritable}. - */ -type WidgetRefusalCause = - | 'unreadable-name' - | 'duplicate-name' - | 'unresolved-duplicate' - -/** - * A widget the walk could not name uniquely. The cause and the name come from - * the walk rather than from another read of the accessor: a hostile one need - * not answer twice the same way, and the walk may have written to it. - */ -export interface RefusedWidget { - widget: T - cause: WidgetRefusalCause - /** Whether the walk removed {@link widget} from the array it was given. */ - removed: boolean - /** The key the walk read, or `undefined` when no key could be derived. */ - name: string | undefined -} +export type RefusedWidget = + | { widget: T; cause: 'unreadable-name'; name: undefined } + | { widget: T; cause: 'duplicate-name'; name: string } + | { widget: T; cause: 'unresolved-duplicate'; name: string } -/** - * The identity key `name` claims, or {@link UNREADABLE_NAME}. It is the key - * rather than the raw value because `widgetId` keys on - * `encodeURIComponent(String(name))`, so names that differ as values and - * coincide as strings are one identity and have to collide here. - * - * An empty name is deliberately readable: it mints an id the store declines to - * key on, which costs the widget nothing, and `addWidget('text', '', …)` is an - * ordinary unlabeled widget that node packs ship (ADR-ECS-0008). - */ -function readName(widget: { name: string }): string | typeof UNREADABLE_NAME { +function readName(widget: { name: unknown }): string | typeof UNREADABLE_NAME { try { - const raw: unknown = widget.name + const raw = widget.name + if (typeof raw === 'symbol') return UNREADABLE_NAME const key = String(raw) - // The raw value, as `widgetId` encodes it: a Symbol survives `String()` - // and throws here. - encodeURIComponent(raw as string) + encodeURIComponent(key) return key } catch { return UNREADABLE_NAME } } -/** @returns whether {@link widget} now answers to {@link name}. */ -function tryRename(widget: { name: string }, name: string): boolean { +function tryRename(widget: { name: unknown }, name: string): boolean { try { widget.name = name - // A setter is free to ignore the write, and only a read proves it did not. return widget.name === name } catch { return false } } -/** Whether no identity key can be read from {@link widget}'s `name`. */ -export function isWidgetNameUnreadable(widget: { name: string }): boolean { +export function isWidgetNameUnreadable(widget: { name: unknown }): boolean { return readName(widget) === UNREADABLE_NAME } -/** Every name key the array already holds outright, skipping unreadable ones. */ -function readableNames(widgets: readonly { name: string }[]): Set { +function readableNames(widgets: readonly { name: unknown }[]): Set { const names = new Set() for (const widget of widgets) { const name = readName(widget) @@ -277,124 +160,58 @@ function readableNames(widgets: readonly { name: string }[]): Set { return names } -/** - * The first `name#n` no set in {@link taken} claims — so a generated name never - * collides with one a widget further down the array holds outright. - */ function freeSuffixedName( name: string, - taken: readonly ReadonlySet[] + isTaken: (candidate: string) => boolean ): string { let index = 1 - while (taken.some((names) => names.has(`${name}#${index}`))) index++ + while (isTaken(`${name}#${index}`)) index++ return `${name}#${index}` } -/** - * How many names a colliding widget is offered before the pair is reported - * unresolved. More than one, because `BaseWidget`'s setter declines a move onto - * an id the store already holds, so one stale entry can reject a candidate the - * widget would otherwise take. - */ -const RENAME_ATTEMPTS = 4 - -/** - * Renames {@link widget} to the first free `name#n` that the write actually - * takes, setting aside each candidate the setter rejects so the next attempt - * offers a different one. - * - * @returns the name it now answers to, or `undefined` if no attempt stuck. - */ -function renameApart( - widget: { name: string }, - name: string, - used: ReadonlySet, - reserved: ReadonlySet -): string | undefined { - // Rejected candidates are tracked per widget, not reserved globally: a name - // this widget's setter would not take is still free for the next widget. - const rejected = new Set() - for (let attempt = 0; attempt < RENAME_ATTEMPTS; attempt++) { - const candidate = freeSuffixedName(name, [used, reserved, rejected]) - if (tryRename(widget, candidate)) return candidate - rejected.add(candidate) - } - return undefined -} - -/** - * Renamed apart and kept, kept but reported, or refused. Adds to - * `used`/`reserved` when an attempt sticks. - * - * A rename that did not land is not proof of an unaddressable widget, so - * {@link nameIsWritable} decides removal and the unresolved pair is reported - * instead (ADR-ECS-0008). - */ function resolveCollision( - widget: { name: string }, + widget: { name: unknown }, key: string, used: Set, - reserved: Set -): { keep: boolean; cause?: WidgetRefusalCause } { - const unique = renameApart(widget, key, used, reserved) - if (unique !== undefined) { - used.add(unique) - reserved.add(unique) - return { keep: true } - } - if (nameIsWritable(widget)) { - return { keep: true, cause: 'unresolved-duplicate' } + reserved: Set, + isNameTaken: (name: string) => boolean +): 'renamed' | 'unresolved-duplicate' | 'duplicate-name' { + const candidate = freeSuffixedName( + key, + (name) => used.has(name) || reserved.has(name) || isNameTaken(name) + ) + if (tryRename(widget, candidate)) { + used.add(candidate) + reserved.add(candidate) + return 'renamed' } - return { keep: false, cause: 'duplicate-name' } + return nameIsWritable(widget) ? 'unresolved-duplicate' : 'duplicate-name' } -/** - * Renames the duplicates it can, removes the ones it cannot address at all, - * and keeps the first occurrence of each name either way. Mutates - * {@link widgets} in place. The invariant and the remove-or-keep criterion are - * ADR-ECS-0008's, under "Widget identity keys on `name`". - * - * Unlike {@link ensureUniqueWidgetNames} this reads each write back, so a - * setter that accepts and ignores it cannot report success, and a widget it - * cannot rename does not strand the collisions that would have resolved. - * - * @returns every widget it could not name uniquely, with the cause and whether - * it was removed, in array order. - */ -export function dropUnrenamableDuplicateWidgets( - widgets: T[] +export function dropUnrenamableDuplicateWidgets( + widgets: T[], + isNameTaken: (name: string) => boolean = () => false ): RefusedWidget[] { const kept: T[] = [] const refused: RefusedWidget[] = [] const used = new Set() const reserved = readableNames(widgets) - /** Every widget already walked, against whether that walk kept it. */ const verdicts = new Map() for (const widget of widgets) { - // The same widget object may occupy a second slot mid-reorder. That is one - // widget, not a collision — but it has to follow the verdict its first - // occurrence got, or a refused widget is re-admitted by its own repeat. const previous = verdicts.get(widget) if (previous !== undefined) { if (previous) kept.push(widget) continue } - const name = readName(widget) - if (name === UNREADABLE_NAME) { + const key = readName(widget) + if (key === UNREADABLE_NAME) { verdicts.set(widget, false) - refused.push({ - widget, - cause: 'unreadable-name', - removed: true, - name: undefined - }) + refused.push({ widget, cause: 'unreadable-name', name: undefined }) continue } - // `readName` already returned the key, not the raw value. - const key = name if (!used.has(key)) { used.add(key) verdicts.set(widget, true) @@ -402,18 +219,12 @@ export function dropUnrenamableDuplicateWidgets( continue } - const outcome = resolveCollision(widget, key, used, reserved) - verdicts.set(widget, outcome.keep) - if (outcome.keep) kept.push(widget) - if (outcome.cause) { - // `key`, not a re-read: the walk may have written to the name since. - refused.push({ - widget, - cause: outcome.cause, - removed: !outcome.keep, - name: key - }) - } + const outcome = resolveCollision(widget, key, used, reserved, isNameTaken) + const keep = outcome !== 'duplicate-name' + verdicts.set(widget, keep) + if (keep) kept.push(widget) + if (outcome !== 'renamed') + refused.push({ widget, cause: outcome, name: key }) } if (refused.length) widgets.splice(0, widgets.length, ...kept) From bb7ee098c240a5361b131653a96765e4026557cb Mon Sep 17 00:00:00 2001 From: bymyself Date: Tue, 3 Nov 2026 21:19:06 +0000 Subject: [PATCH 34/35] test: pin the duplicate's name so the rejoin cannot rename it apart Since #20087's detached-rename repair, a rename made while the node is out of the graph lands, so on rejoin the duplicate is renamed apart and both widgets draw. Give the second widget a name accessor that accepts and ignores writes, assert both names are still equal after graph.add, then assert the single drawn widget and the two saved values. Addresses review feedback: https://github.com/Comfy-Org/ComfyUI_frontend/pull/20135#discussion_r4211479101 --- .../renamableDuplicateWidgetKept.spec.ts | 77 ++++--------------- 1 file changed, 13 insertions(+), 64 deletions(-) diff --git a/browser_tests/tests/widgets/renamableDuplicateWidgetKept.spec.ts b/browser_tests/tests/widgets/renamableDuplicateWidgetKept.spec.ts index a9f0ac1cdf8..eb4728a85b9 100644 --- a/browser_tests/tests/widgets/renamableDuplicateWidgetKept.spec.ts +++ b/browser_tests/tests/widgets/renamableDuplicateWidgetKept.spec.ts @@ -6,43 +6,6 @@ import { TestIds } from '@e2e/fixtures/selectors' import { zComfyWorkflow } from '@comfyorg/graph-model/workflowSchema' -/** - * The unique-name invariant removes a widget it cannot name uniquely - * (ADR-ECS-0008). This pins the boundary of "cannot": a widget whose `name` is - * perfectly writable must never be the price of enforcing it. - * - * `BaseWidget.set name` delegates to `widgetValueStore.renameWidget()` and - * returns without changing the name whenever the store declines — which it does - * when the node has no entries, the state a node is in after it has been - * removed from the graph. So a rename that *failed* does not prove the widget - * is unaddressable, and removing on that signal destroys an ordinary widget. - * - * Reproduced through the graph API the way an undo of a node deletion or a - * paste of a cut node reaches it: the node leaves the graph, the duplicate name - * appears while it is detached, and it rejoins. - * - * Asserted on what the app saves, because that is where the loss is permanent. - * Measured on the parent commit the node comes back one widget short and saves - * **one** `widgets_values` entry for a two-widget node; the arity of that array - * is what positional widget addressing reads, so a dropped slot shifts every - * later widget. With the invariant's criterion corrected it saves both. - * - * The two *values* are asserted too, and that is the stronger half. Arity alone - * went green over a save this change set used to corrupt: re-registering an - * ambiguous pair routed the second widget's `name` setter through - * `renameWidget` on an id the *first* widget had registered, which handed it - * that widget's store entry — so the two widgets shared one `WidgetState`, both - * read the first value, and the second value was gone from a two-slot save. A - * widget's own entry is now the only entry its rename may move - * (`BaseWidget.set name`), so both values survive and this asserts it. - * - * What the node *draws* is asserted too, because the save cannot show it: - * serialization reads `node.widgets`, while a Vue node renders from the - * registered widget order. Registration was gated on a whole-node verdict, so - * one unresolvable pair left the node with an empty order and it drew no - * widgets at all — a save-only assertion goes green over that. - */ - const NODE_TYPE = 'DevToolsNodeWithOutputList' const KEPT_NAME = 'alpha' const RENAMED_NAME = 'beta' @@ -68,17 +31,11 @@ async function installTwoOrdinaryWidgets(comfyPage: ComfyPage): Promise { ) } -/** - * Takes the node out of the graph, collides the second widget's name with the - * first while it is detached, and puts it back. Detached is what makes the - * write land: on a node that is still in the graph the store declines the - * rename and the collision never forms. - */ async function collideNameWhileDetached( comfyPage: ComfyPage, nodeId: string -): Promise { - await comfyPage.page.evaluate( +): Promise { + return comfyPage.page.evaluate( ({ id, duplicateName, renamedName }) => { const graph = window.app!.graph const node = graph.nodes.find((candidate) => String(candidate.id) === id) @@ -88,7 +45,13 @@ async function collideNameWhileDetached( const target = node.widgets?.find(({ name }) => name === renamedName) if (!target) throw new Error(`widget ${renamedName} not found`) target.name = duplicateName + Object.defineProperty(target, 'name', { + get: () => duplicateName, + set: () => undefined, + configurable: true + }) graph.add(node) + return (node.widgets ?? []).map(({ name }) => name) }, { id: nodeId, duplicateName: KEPT_NAME, renamedName: RENAMED_NAME } ) @@ -124,20 +87,13 @@ test.describe( await expect(node.getByTestId(TestIds.widgets.widget)).toHaveCount(2) }) - await collideNameWhileDetached(comfyPage, nodeId) + const namesAfterRejoin = await collideNameWhileDetached(comfyPage, nodeId) + + await test.step('the duplicate name is still unresolved after rejoining', async () => { + expect(namesAfterRejoin).toEqual([KEPT_NAME, KEPT_NAME]) + }) await test.step('the node still draws the widget that kept the name', async () => { - // A Vue node draws from the registered widget order, and registration - // was gated on a whole-node "is this node unambiguous?" verdict — so - // one pair that could not be renamed apart withheld an identity from - // every widget on the node and it drew **none**. That is a worse loss - // than the removal this criterion replaced, which cost one widget and - // kept drawing the rest; it is invisible to the save assertion below, - // because serialization reads `node.widgets` rather than the store. - // - // One widget drawn, not two: the duplicate genuinely has no identity - // of its own while it shares the name, which is what stops it being - // handed the other widget's store entry. await expect(node.getByTestId(TestIds.widgets.widget)).toHaveCount(1) }) @@ -155,14 +111,7 @@ test.describe( ) const savedNode = saved.nodes.find(({ type }) => type === NODE_TYPE) - // One entry here is a widget the user lost. Two is the invariant being - // enforced without charging them for it. expect(savedNode?.widgets_values).toHaveLength(2) - - // And two *distinct* values, because arity alone cannot tell a - // preserved widget from one welded onto its duplicate's store entry. - // `['first default', 'first default']` is the second value destroyed - // while the slot count still looks right. expect(savedNode?.widgets_values).toEqual([ 'first default', 'second default' From a1d447b5eebc197cdbffdb650448a55044a5ce3c Mon Sep 17 00:00:00 2001 From: bymyself Date: Tue, 3 Nov 2026 21:19:22 +0000 Subject: [PATCH 35/35] test: drop the double assertion on the numeric name fixture ownedWidgetNameKey takes names as unknown, so a plain { name: 1 } compiles. Addresses review feedback: https://github.com/Comfy-Org/ComfyUI_frontend/pull/20135#discussion_r4211479162 --- src/types/widgetId.test.ts | 7 +------ 1 file changed, 1 insertion(+), 6 deletions(-) diff --git a/src/types/widgetId.test.ts b/src/types/widgetId.test.ts index 9c8969d1399..fb21e86387a 100644 --- a/src/types/widgetId.test.ts +++ b/src/types/widgetId.test.ts @@ -371,15 +371,10 @@ describe('ownedWidgetNameKey', () => { }) it('collides names that differ as values but coincide as id strings', () => { - // `widgetId` keys on `encodeURIComponent(String(name))`, so these two mint - // one id. Comparing raw values would hand both an identity and let the - // clash land in the store, which is the registration this gate exists to - // refuse. - const numeric = { name: 1 as unknown as string } + const numeric = { name: 1 } const textual = { name: '1' } const widgets = [numeric, textual] - // And the key is the coerced one, which is what the id is built from. expect(ownedWidgetNameKey(widgets, numeric)).toBe('1') expect(ownedWidgetNameKey(widgets, textual)).toBeUndefined() })