diff --git a/browser_tests/tests/widgets/renamableDuplicateWidgetKept.spec.ts b/browser_tests/tests/widgets/renamableDuplicateWidgetKept.spec.ts new file mode 100644 index 00000000000..eb4728a85b9 --- /dev/null +++ b/browser_tests/tests/widgets/renamableDuplicateWidgetKept.spec.ts @@ -0,0 +1,122 @@ +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 '@comfyorg/graph-model/workflowSchema' + +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 } + ) +} + +async function collideNameWhileDetached( + comfyPage: ComfyPage, + nodeId: string +): Promise { + return 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 + 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 } + ) +} + +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) + }) + + 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 () => { + 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) + + expect(savedNode?.widgets_values).toHaveLength(2) + 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 930429b8292..1ce83d89adc 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 `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. +> +> **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/packages/graph-model/src/widgetId.ts b/packages/graph-model/src/widgetId.ts index 14bd2651ac8..71cd2072326 100644 --- a/packages/graph-model/src/widgetId.ts +++ b/packages/graph-model/src/widgetId.ts @@ -41,6 +41,31 @@ function nameIsWritable(widget: object): boolean { } } +/** 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 +} + +/** + * 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: unknown }[], + widget: { name: unknown } +): string | undefined { + const key = readName(widget) + if (key === UNREADABLE_NAME) return undefined + + for (const candidate of widgets) { + if (candidate === widget) return key + if (readName(candidate) === key) return undefined + } + return undefined +} + export function ensureUniqueWidgetNames( widgets: readonly { name: string }[] ): boolean { diff --git a/src/lib/litegraph/src/node/widgetsView.refusalCriterion.test.ts b/src/lib/litegraph/src/node/widgetsView.refusalCriterion.test.ts index af7198c270e..c77900c0d95 100644 --- a/src/lib/litegraph/src/node/widgetsView.refusalCriterion.test.ts +++ b/src/lib/litegraph/src/node/widgetsView.refusalCriterion.test.ts @@ -46,7 +46,6 @@ describe('unique-name refusal criterion', () => { expect(names(node)).toEqual(['seed', 'seed#1']) expect(storedNames(graph, node)).toEqual(['seed', 'seed#1']) expect(reportedTypes()).toEqual([]) - expect(seed.value).toBe(1) expect(steps.value).toBe(2) @@ -56,6 +55,153 @@ 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`). 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') + ]) + + // 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) + 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#1', + 'seed' + ]) + 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(1) + expect(store.getWidget(widgetId(graph.id, node.id, 'seed#1'))?.value).toBe( + 222 + ) + }) + + 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 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 7a2164c3a98..8156ba2b954 100644 --- a/src/lib/litegraph/src/widgets/BaseWidget.ts +++ b/src/lib/litegraph/src/widgets/BaseWidget.ts @@ -21,7 +21,9 @@ import { useWidgetValueStore } from '@/stores/widgetValueStore' import type { WidgetId } from '@comfyorg/graph-model/widgetId' import { ensureUniqueWidgetNames, - widgetId + ownedWidgetNameKey, + widgetId, + widgetNameKey } from '@comfyorg/graph-model/widgetId' import type { WidgetState } from '@comfyorg/graph-model/widgetState' import { @@ -403,8 +405,45 @@ 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 - return widgetId(graphId, nodeId, this.name) + // 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 ownedWidgetNameKey}. + const widgets = this.node.widgets ?? [this] + ensureUniqueWidgetNames(widgets) + // 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 — 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 + * `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 } /** @@ -415,14 +454,53 @@ 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) + // 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, @@ -433,7 +511,28 @@ export abstract class BaseWidget this._visibility ) if (!registered) return - this.bindRegisteredState(nodeId) + this.bindRegisteredState(nodeId, name) + } + + /** + * 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 } releaseRegisteredState(): void { @@ -447,10 +546,10 @@ export abstract class BaseWidget store.deleteWidget(id) } - 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 8a3fb4b62b2..fb21e86387a 100644 --- a/src/types/widgetId.test.ts +++ b/src/types/widgetId.test.ts @@ -5,6 +5,7 @@ import { dropUnrenamableDuplicateWidgets, ensureUniqueWidgetNames, isWidgetId, + ownedWidgetNameKey, parseWidgetId, widgetId } from '@comfyorg/graph-model/widgetId' @@ -341,6 +342,80 @@ 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('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(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(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(ownedWidgetNameKey([shared, shared], shared)).toBe('seed') + }) + + it('collides names that differ as values but coincide as id strings', () => { + const numeric = { name: 1 } + const textual = { name: '1' } + const widgets = [numeric, textual] + + expect(ownedWidgetNameKey(widgets, numeric)).toBe('1') + expect(ownedWidgetNameKey(widgets, textual)).toBeUndefined() + }) + + it('refuses a widget whose own name cannot be read', () => { + const hostile = { + get name(): string { + throw new Error('nope') + } + } + + expect(ownedWidgetNameKey([hostile], hostile)).toBeUndefined() + }) + + 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(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', () => { const graphId = 'a1b2c3d4-e5f6-7890-abcd-ef1234567890'