diff --git a/browser_tests/README.md b/browser_tests/README.md index d00ead1d440..debb0dc4ace 100644 --- a/browser_tests/README.md +++ b/browser_tests/README.md @@ -353,8 +353,10 @@ await expect(node).toHaveClass(BYPASS_CLASS) before `page.keyboard.press(...)`, or keys go nowhere. - Mark the canvas dirty after programmatic state changes: `window['app'].graph.setDirtyCanvas(true, true)`. -- `dblclick()` on canvas needs a small `{ delay: 5 }`; drags need - `{ steps: 10 }` not `{ steps: 1 }`. +- `dblclick()` on canvas needs a small `{ delay: 5 }`. Use the shared drag + helpers, which emit enough intermediate events for canvas behavior without + making coverage runs process excessive pointer events. For a local drag, + use the fewest steps the behavior needs (usually 5–20), never 100. ### Custom assertions diff --git a/browser_tests/assets/missing/missing_model_nested_promoted_widget.json b/browser_tests/assets/missing/missing_model_nested_promoted_widget.json index 1523fbf6786..1b2df9a28e0 100644 --- a/browser_tests/assets/missing/missing_model_nested_promoted_widget.json +++ b/browser_tests/assets/missing/missing_model_nested_promoted_widget.json @@ -6,7 +6,7 @@ "nodes": [ { "id": 3, - "type": "outer-subgraph-with-promoted-missing-model", + "type": "4e7c1a2b-3d5f-4a6b-8c9d-0e1f2a3b4c5d", "pos": [10, 250], "size": [400, 200], "flags": {}, @@ -20,7 +20,7 @@ }, { "id": 4, - "type": "outer-subgraph-with-promoted-missing-model", + "type": "4e7c1a2b-3d5f-4a6b-8c9d-0e1f2a3b4c5d", "pos": [450, 250], "size": [400, 200], "flags": {}, @@ -38,7 +38,7 @@ "definitions": { "subgraphs": [ { - "id": "outer-subgraph-with-promoted-missing-model", + "id": "4e7c1a2b-3d5f-4a6b-8c9d-0e1f2a3b4c5d", "version": 1, "state": { "lastGroupId": 0, @@ -71,7 +71,7 @@ "nodes": [ { "id": 2, - "type": "inner-subgraph-with-promoted-missing-model", + "type": "5f8d2b3c-4e6a-4b7c-9d0e-1f2a3b4c5d6e", "pos": [250, 180], "size": [400, 200], "flags": {}, @@ -105,7 +105,7 @@ ] }, { - "id": "inner-subgraph-with-promoted-missing-model", + "id": "5f8d2b3c-4e6a-4b7c-9d0e-1f2a3b4c5d6e", "version": 1, "state": { "lastGroupId": 0, diff --git a/browser_tests/assets/missing/missing_models_in_subgraph.json b/browser_tests/assets/missing/missing_models_in_subgraph.json index 613fa77be85..063587e2406 100644 --- a/browser_tests/assets/missing/missing_models_in_subgraph.json +++ b/browser_tests/assets/missing/missing_models_in_subgraph.json @@ -47,7 +47,7 @@ "version": 1, "state": { "lastGroupId": 0, - "lastNodeId": 1, + "lastNodeId": 5, "lastLinkId": 2, "lastRerouteId": 0 }, @@ -100,6 +100,25 @@ "Node name for S&R": "CheckpointLoaderSimple" }, "widgets_values": ["fake_model.safetensors"] + }, + { + "id": 5, + "type": "CheckpointLoaderSimple", + "pos": [250, 320], + "size": [315, 98], + "flags": {}, + "order": 1, + "mode": 0, + "inputs": [], + "outputs": [ + { "name": "MODEL", "type": "MODEL", "links": null }, + { "name": "CLIP", "type": "CLIP", "links": null }, + { "name": "VAE", "type": "VAE", "links": null } + ], + "properties": { + "Node name for S&R": "CheckpointLoaderSimple" + }, + "widgets_values": ["fake_model.safetensors"] } ], "links": [ diff --git a/browser_tests/assets/nodes/duplicate_node_ids.json b/browser_tests/assets/nodes/duplicate_node_ids.json new file mode 100644 index 00000000000..05bc9dba6d3 --- /dev/null +++ b/browser_tests/assets/nodes/duplicate_node_ids.json @@ -0,0 +1,50 @@ +{ + "last_node_id": 9, + "last_link_id": 13, + "nodes": [ + { + "id": 3, + "type": "KSampler", + "pos": [120, 320], + "size": { + "0": 315, + "1": 262 + }, + "flags": {}, + "order": 0, + "mode": 0, + "inputs": [], + "outputs": [], + "properties": { + "Node name for S&R": "KSampler" + } + }, + { + "id": 3, + "type": "KSampler", + "pos": [560, 320], + "size": { + "0": 315, + "1": 262 + }, + "flags": {}, + "order": 1, + "mode": 0, + "inputs": [], + "outputs": [], + "properties": { + "Node name for S&R": "KSampler" + } + } + ], + "links": [], + "groups": [], + "config": {}, + "extra": { + "ds": { + "scale": 1, + "offset": [0, 0] + } + }, + "version": 0.4 +} diff --git a/browser_tests/assets/subgraphs/subgraph-link-identity-collision.json b/browser_tests/assets/subgraphs/subgraph-link-identity-collision.json new file mode 100644 index 00000000000..64ef42d5aac --- /dev/null +++ b/browser_tests/assets/subgraphs/subgraph-link-identity-collision.json @@ -0,0 +1,156 @@ +{ + "id": "987de650-fd73-4f2d-a7d6-ef58909d56cb", + "revision": 0, + "last_node_id": 2, + "last_link_id": 0, + "nodes": [ + { + "id": 1, + "type": "11111111-1111-4111-8111-111111111111", + "pos": [300, 300], + "size": [220, 80], + "flags": {}, + "order": 0, + "mode": 0, + "inputs": [{ "name": "input", "type": "*", "link": null }], + "outputs": [{ "name": "output", "type": "*", "links": null }], + "properties": {}, + "widgets_values": [] + }, + { + "id": 2, + "type": "22222222-2222-4222-8222-222222222222", + "pos": [650, 300], + "size": [220, 80], + "flags": {}, + "order": 1, + "mode": 0, + "inputs": [{ "name": "input", "type": "*", "link": null }], + "outputs": [{ "name": "output", "type": "*", "links": null }], + "properties": {}, + "widgets_values": [] + } + ], + "links": [], + "groups": [], + "definitions": { + "subgraphs": [ + { + "id": "11111111-1111-4111-8111-111111111111", + "version": 1, + "state": { + "lastGroupId": 0, + "lastNodeId": 0, + "lastLinkId": 1, + "lastRerouteId": 101 + }, + "revision": 0, + "config": {}, + "name": "Identity collision A", + "inputNode": { + "id": -10, + "bounding": [100, 200, 120, 60] + }, + "outputNode": { + "id": -20, + "bounding": [500, 200, 120, 60] + }, + "inputs": [ + { + "id": "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa", + "name": "input", + "type": "*", + "linkIds": [1], + "pos": { "0": 200, "1": 220 } + } + ], + "outputs": [ + { + "id": "bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb", + "name": "output", + "type": "*", + "linkIds": [1], + "pos": { "0": 520, "1": 220 } + } + ], + "widgets": [], + "nodes": [], + "groups": [], + "links": [ + { + "id": 1, + "origin_id": -10, + "origin_slot": 0, + "target_id": -20, + "target_slot": 0, + "type": "*", + "parentId": 101 + } + ], + "reroutes": [{ "id": 101, "pos": [300, 220], "linkIds": [1] }], + "extra": {} + }, + { + "id": "22222222-2222-4222-8222-222222222222", + "version": 1, + "state": { + "lastGroupId": 0, + "lastNodeId": 0, + "lastLinkId": 1, + "lastRerouteId": 201 + }, + "revision": 0, + "config": {}, + "name": "Identity collision B", + "inputNode": { + "id": -10, + "bounding": [100, 400, 120, 60] + }, + "outputNode": { + "id": -20, + "bounding": [500, 400, 120, 60] + }, + "inputs": [ + { + "id": "cccccccc-cccc-4ccc-8ccc-cccccccccccc", + "name": "input", + "type": "*", + "linkIds": [1], + "pos": { "0": 200, "1": 420 } + } + ], + "outputs": [ + { + "id": "dddddddd-dddd-4ddd-8ddd-dddddddddddd", + "name": "output", + "type": "*", + "linkIds": [1], + "pos": { "0": 520, "1": 420 } + } + ], + "widgets": [], + "nodes": [], + "groups": [], + "links": [ + { + "id": 1, + "origin_id": -10, + "origin_slot": 0, + "target_id": -20, + "target_slot": 0, + "type": "*", + "parentId": 201 + } + ], + "reroutes": [{ "id": 201, "pos": [400, 420], "linkIds": [1] }], + "extra": {} + } + ] + }, + "config": {}, + "extra": { + "ds": { "scale": 1, "offset": [0, 0] }, + "frontendVersion": "1.24.1" + }, + "version": 0.4 +} diff --git a/browser_tests/assets/vueNodes/collapsed-stacking.json b/browser_tests/assets/vueNodes/collapsed-stacking.json new file mode 100644 index 00000000000..00df3537126 --- /dev/null +++ b/browser_tests/assets/vueNodes/collapsed-stacking.json @@ -0,0 +1,79 @@ +{ + "id": "407522cb-b7cb-491d-b152-3c2de19dc51d", + "revision": 0, + "last_node_id": 2, + "last_link_id": 0, + "nodes": [ + { + "id": 1, + "type": "VAEDecode", + "pos": [140, 100], + "size": [193.25, 107], + "flags": {}, + "order": 0, + "mode": 0, + "inputs": [ + { + "localized_name": "samples", + "name": "samples", + "type": "LATENT", + "link": null + }, + { + "localized_name": "vae", + "name": "vae", + "type": "VAE", + "link": null + } + ], + "outputs": [ + { + "localized_name": "IMAGE", + "name": "IMAGE", + "type": "IMAGE", + "links": null + } + ], + "properties": { "Node name for S&R": "VAEDecode" } + }, + { + "id": 2, + "type": "CLIPTextEncode", + "pos": [100, 100], + "size": [240, 155], + "flags": { "collapsed": true }, + "order": 1, + "mode": 0, + "inputs": [ + { + "localized_name": "clip", + "name": "clip", + "type": "CLIP", + "link": null + }, + { + "localized_name": "text", + "name": "text", + "type": "STRING", + "widget": { "name": "text" }, + "link": null + } + ], + "outputs": [ + { + "localized_name": "CONDITIONING", + "name": "CONDITIONING", + "type": "CONDITIONING", + "links": null + } + ], + "properties": { "Node name for S&R": "CLIPTextEncode" }, + "widgets_values": [""] + } + ], + "links": [], + "groups": [], + "config": {}, + "extra": {}, + "version": 0.4 +} diff --git a/browser_tests/fixtures/VueNodeHelpers.ts b/browser_tests/fixtures/VueNodeHelpers.ts index f2332648d8e..1a24a0d5c50 100644 --- a/browser_tests/fixtures/VueNodeHelpers.ts +++ b/browser_tests/fixtures/VueNodeHelpers.ts @@ -1,6 +1,7 @@ /** * Vue Node Test Helpers */ +import { expect } from '@playwright/test' import type { Locator, Page } from '@playwright/test' import { TestIds } from '@e2e/fixtures/selectors' @@ -66,6 +67,36 @@ export class VueNodeHelpers { }) } + async getNodeCenter(title: string): Promise<{ x: number; y: number }> { + const box = await this.getNodeByTitle(title).first().boundingBox() + if (!box) throw new Error(`Node "${title}" not found`) + return { x: box.x + box.width / 2, y: box.y + box.height / 2 } + } + + async getNodePaintOrder(title: string): Promise { + return await this.getNodeByTitle(title) + .first() + .evaluate((node) => { + const paintOrder = Number.parseInt(getComputedStyle(node).zIndex, 10) + return Number.isNaN(paintOrder) ? -1 : paintOrder + }) + } + + async expectPaintsAbove( + aboveTitle: string, + belowTitle: string + ): Promise { + await expect + .poll(async () => { + const [aboveOrder, belowOrder] = await Promise.all([ + this.getNodePaintOrder(aboveTitle), + this.getNodePaintOrder(belowTitle) + ]) + return aboveOrder - belowOrder + }) + .toBeGreaterThan(0) + } + /** * Get total count of Vue nodes in the DOM */ diff --git a/browser_tests/fixtures/helpers/CanvasHelper.ts b/browser_tests/fixtures/helpers/CanvasHelper.ts index 70853df3f2b..8acecb41234 100644 --- a/browser_tests/fixtures/helpers/CanvasHelper.ts +++ b/browser_tests/fixtures/helpers/CanvasHelper.ts @@ -1,8 +1,10 @@ +import { expect } from '@playwright/test' import type { Locator, Page } from '@playwright/test' import { DefaultGraphPositions } from '@e2e/fixtures/constants/defaultGraphPositions' import type { Position } from '@e2e/fixtures/types' import { nextFrame } from '@e2e/fixtures/utils/timing' +import type { RerouteId } from '@/types/rerouteId' export class CanvasHelper { constructor( @@ -122,7 +124,7 @@ export class CanvasHelper { async dragAndDrop(source: Position, target: Position): Promise { await this.page.mouse.move(source.x, source.y) await this.page.mouse.down() - await this.page.mouse.move(target.x, target.y, { steps: 100 }) + await this.page.mouse.move(target.x, target.y, { steps: 20 }) await this.page.mouse.up() await nextFrame(this.page) } @@ -195,6 +197,30 @@ export class CanvasHelper { }, title) } + async expectRootReroutePositions( + expectedReroutes: Record + ): Promise { + await expect(async () => { + const reroutes = await this.page.evaluate(() => { + const graph = window.app!.canvas.graph?.rootGraph + if (!graph) throw new Error('Graph not available') + return [...graph.reroutes.values()].map((reroute) => ({ + id: reroute.id, + x: reroute.pos[0], + y: reroute.pos[1] + })) + }) + + expect(reroutes).toHaveLength(Object.keys(expectedReroutes).length) + for (const reroute of reroutes) { + const expected = expectedReroutes[reroute.id] + if (!expected) throw new Error(`Unexpected reroute ${reroute.id}`) + expect(reroute.x).toBeCloseTo(expected.x, 1) + expect(reroute.y).toBeCloseTo(expected.y, 1) + } + }).toPass({ timeout: 5000 }) + } + async getGroupPosition(title: string): Promise { const pos = await this.page.evaluate((title) => { const groups = window.app!.graph.groups diff --git a/browser_tests/fixtures/helpers/NodeOperationsHelper.ts b/browser_tests/fixtures/helpers/NodeOperationsHelper.ts index 6e7c4087f51..fd40f31aab8 100644 --- a/browser_tests/fixtures/helpers/NodeOperationsHelper.ts +++ b/browser_tests/fixtures/helpers/NodeOperationsHelper.ts @@ -95,12 +95,6 @@ export class NodeOperationsHelper { return await this.page.evaluate(() => window.app!.graph.nodes.length) } - async getNodes(): Promise { - return await this.page.evaluate(() => { - return window.app!.graph.nodes - }) - } - async waitForGraphNodes(count: number): Promise { await this.page.waitForFunction((count) => { return window.app?.canvas.graph?.nodes?.length === count diff --git a/browser_tests/fixtures/utils/findEmptyCanvasPoint.ts b/browser_tests/fixtures/utils/findEmptyCanvasPoint.ts new file mode 100644 index 00000000000..0f8c62b1958 --- /dev/null +++ b/browser_tests/fixtures/utils/findEmptyCanvasPoint.ts @@ -0,0 +1,43 @@ +import type { Locator } from '@playwright/test' + +import type { Position } from '@e2e/fixtures/types' + +type CanvasScanOrigin = 'top-left' | 'bottom-right' + +export async function findEmptyCanvasPoint( + canvas: Locator, + scanOrigin: CanvasScanOrigin = 'top-left' +): Promise { + return await canvas.evaluate((canvasElement, scanOrigin) => { + const bounds = canvasElement.getBoundingClientRect() + const xCoordinates: number[] = [] + const yCoordinates: number[] = [] + + for (let x = bounds.left + 100; x < bounds.right - 100; x += 50) { + xCoordinates.push(x) + } + for (let y = bounds.top + 100; y < bounds.bottom - 100; y += 50) { + yCoordinates.push(y) + } + + const xs = + scanOrigin === 'bottom-right' ? xCoordinates.toReversed() : xCoordinates + const ys = + scanOrigin === 'bottom-right' ? yCoordinates.toReversed() : yCoordinates + + for (const y of ys) { + for (const x of xs) { + const element = document.elementFromPoint(x, y) + if ( + element && + canvasElement.contains(element) && + !element.closest('[data-node-id]') + ) { + return { x, y } + } + } + } + + throw new Error('No empty canvas point found') + }, scanOrigin) +} diff --git a/browser_tests/fixtures/utils/vueNodeFixtures.ts b/browser_tests/fixtures/utils/vueNodeFixtures.ts index 94e31819fb2..cd1f9e18896 100644 --- a/browser_tests/fixtures/utils/vueNodeFixtures.ts +++ b/browser_tests/fixtures/utils/vueNodeFixtures.ts @@ -124,8 +124,8 @@ export class VueNodeFixture { } const page = this.locator.page() - const startX = box.x + box.width / 2 - const startY = box.y + box.height / 2 + const startX = box.x + (corner === 'NW' ? box.width / 4 : box.width / 2) + const startY = box.y + (corner === 'NW' ? box.height / 4 : box.height / 2) await page.mouse.move(startX, startY) await page.mouse.down() await page.mouse.move(startX + deltaX, startY + deltaY, { diff --git a/browser_tests/tests/appModeBuilder.spec.ts b/browser_tests/tests/appModeBuilder.spec.ts index f86910b59ed..18e365c8f1c 100644 --- a/browser_tests/tests/appModeBuilder.spec.ts +++ b/browser_tests/tests/appModeBuilder.spec.ts @@ -2,35 +2,43 @@ import { comfyPageFixture as test, comfyExpect as expect } from '@e2e/fixtures/ComfyPage' +import { + dismissErrorOverlay, + enableErrorsOverlay +} from '@e2e/fixtures/helpers/ErrorsTabHelper' +import { ExecutionHelper } from '@e2e/fixtures/helpers/ExecutionHelper' test.describe('App mode builder selection', () => { test.beforeEach(async ({ comfyPage }) => { await comfyPage.appMode.enableLinearMode() }) - test('Can independently select inputs of same name', async ({ - comfyPage - }) => { - await comfyPage.settings.setSetting('Comfy.VueNodes.Enabled', true) - const items = comfyPage.appMode.select.inputItems - - await comfyPage.vueNodes.selectNodes(['6', '7']) - await comfyPage.command.executeCommand('Comfy.Graph.ConvertToSubgraph') - - await comfyPage.appMode.enterBuilder() - await comfyPage.appMode.steps.goToInputs() - await expect(items).toHaveCount(0) - - const prompts = comfyPage.vueNodes - .getNodeByTitle('New Subgraph') - .locator('.lg-node-widget') - const count = await prompts.count() - for (let i = 0; i < count; i++) { - await expect(prompts.nth(i)).toBeVisible() - await prompts.nth(i).click() - await expect(items).toHaveCount(i + 1) + test( + 'Can independently select inputs of same name', + { + tag: '@vue-nodes' + }, + async ({ comfyPage }) => { + const items = comfyPage.appMode.select.inputItems + + await comfyPage.vueNodes.selectNodes(['6', '7']) + await comfyPage.command.executeCommand('Comfy.Graph.ConvertToSubgraph') + + await comfyPage.appMode.enterBuilder() + await comfyPage.appMode.steps.goToInputs() + await expect(items).toHaveCount(0) + + const prompts = comfyPage.vueNodes + .getNodeByTitle('New Subgraph') + .locator('.lg-node-widget') + const count = await prompts.count() + for (let i = 0; i < count; i++) { + await expect(prompts.nth(i)).toBeVisible() + await prompts.nth(i).click() + await expect(items).toHaveCount(i + 1) + } } - }) + ) test('Can select outputs', async ({ comfyPage }) => { await comfyPage.appMode.enterBuilder() @@ -94,33 +102,75 @@ test.describe('App mode builder selection', () => { } ) - test('Can not select nodes with errors or notes', async ({ comfyPage }) => { - //Manually set error state on checkpoint loader - //Shouldn't be needed on ci, but has spotty reliability - await comfyPage.page.evaluate(() => (graph!.nodes[6].has_errors = true)) - await comfyPage.settings.setSetting('Comfy.VueNodes.Enabled', true) - - const items = comfyPage.appMode.select.inputItems - await comfyPage.appMode.enterBuilder() - await comfyPage.appMode.steps.goToInputs() - await expect(items).toHaveCount(0) + test( + 'Can not select a node with an error', + { + tag: '@vue-nodes' + }, + async ({ comfyPage }) => { + // This test seeds a real error through a prompt round trip, on top of the + // errors-overlay setting and the builder navigation. + test.slow() + // Without the errors tab, a failed prompt raises a modal error dialog + // instead, and a modal makes the topbar inert (app.ts:1754). + await enableErrorsOverlay(comfyPage) + + const [checkpointLoader] = await comfyPage.nodeOps.getNodeRefsByType( + 'CheckpointLoaderSimple' + ) + await new ExecutionHelper(comfyPage).mockValidationFailure({ + [String(checkpointLoader.id)]: { + class_type: 'CheckpointLoaderSimple', + dependent_outputs: [], + errors: [ + { + type: 'value_not_in_list', + message: 'Value not in list', + details: '', + extra_info: { input_name: 'ckpt_name' } + } + ] + } + }) + await comfyPage.runButton.click() + await dismissErrorOverlay(comfyPage) + + // The error ring is the user-visible signal that the store took the error; + // waiting on it keeps the builder assertions below from racing the response. + await expect( + comfyPage.vueNodes.getNodeInnerWrapper(String(checkpointLoader.id)) + ).toHaveClass(/ring-destructive-background/) + + const items = comfyPage.appMode.select.inputItems + await comfyPage.appMode.enterBuilder() + await comfyPage.appMode.steps.goToInputs() + + await comfyPage.appMode.select.selectInputWidget( + 'Load Checkpoint', + 'ckpt_name' + ) + await expect(items).toHaveCount(0) + } + ) - await comfyPage.appMode.select.selectInputWidget( - 'Load Checkpoint', - 'ckpt_name' - ) - await expect(items).toHaveCount(0) + test( + 'Can not select note nodes', + { + tag: '@vue-nodes' + }, + async ({ comfyPage }) => { + await comfyPage.workflow.loadWorkflow('nodes/note_nodes') - await comfyPage.workflow.loadWorkflow('nodes/note_nodes') - await comfyPage.appMode.enterBuilder() - await comfyPage.appMode.steps.goToInputs() - await expect(items).toHaveCount(0) + const items = comfyPage.appMode.select.inputItems + await comfyPage.appMode.enterBuilder() + await comfyPage.appMode.steps.goToInputs() - await comfyPage.appMode.select.selectInputWidget('Note', 'text') - await comfyPage.appMode.select.selectInputWidget('Markdown Note', 'text') + await comfyPage.appMode.select.selectInputWidget('Note', 'text') + await comfyPage.appMode.select.selectInputWidget('Markdown Note', 'text') - await expect(items).toHaveCount(0) - }) + await expect(items).toHaveCount(0) + } + ) test('Marks canvas readOnly', async ({ comfyPage }) => { await comfyPage.searchBoxV2.openByDoubleClickCanvas() diff --git a/browser_tests/tests/copyPaste.spec.ts b/browser_tests/tests/copyPaste.spec.ts index 236ad701133..b30062dbb51 100644 --- a/browser_tests/tests/copyPaste.spec.ts +++ b/browser_tests/tests/copyPaste.spec.ts @@ -30,6 +30,31 @@ test.describe('Copy Paste', { tag: ['@screenshot', '@workflow'] }, () => { await expect(comfyPage.canvas).toHaveScreenshot('copied-node-with-link.png') }) + test('Pasted copy of a pinned node lands at the cursor', async ({ + comfyPage + }) => { + const node = (await comfyPage.nodeOps.getNodeRefsByType('KSampler'))[0] + await node.clickContextMenuOption('Pin') + await comfyPage.contextMenu.waitForHidden() + await expect.poll(() => node.isPinned()).toBe(true) + + await node.click('title') + await comfyPage.page.mouse.move(10, 10) + await comfyPage.nextFrame() + await comfyPage.clipboard.copy(comfyPage.canvas) + await comfyPage.clipboard.paste(comfyPage.canvas) + + await expect + .poll( + async () => + (await comfyPage.nodeOps.getNodeRefsByType('KSampler')).length + ) + .toBe(2) + const [original, pasted] = + await comfyPage.nodeOps.getNodeRefsByType('KSampler') + expect(await pasted.getPosition()).not.toEqual(await original.getPosition()) + }) + test('Can copy and paste text', async ({ comfyPage }) => { const textBox = comfyPage.widgetTextBox await textBox.click() diff --git a/browser_tests/tests/domWidget.spec.ts-snapshots/focus-mode-on-chromium-linux.png b/browser_tests/tests/domWidget.spec.ts-snapshots/focus-mode-on-chromium-linux.png index 123c8d82b9d..8eb6aae9a2b 100644 Binary files a/browser_tests/tests/domWidget.spec.ts-snapshots/focus-mode-on-chromium-linux.png and b/browser_tests/tests/domWidget.spec.ts-snapshots/focus-mode-on-chromium-linux.png differ diff --git a/browser_tests/tests/graphCanvasMenu.spec.ts-snapshots/canvas-with-visible-links-chromium-linux.png b/browser_tests/tests/graphCanvasMenu.spec.ts-snapshots/canvas-with-visible-links-chromium-linux.png index 1b33d314ce3..acc07754576 100644 Binary files a/browser_tests/tests/graphCanvasMenu.spec.ts-snapshots/canvas-with-visible-links-chromium-linux.png and b/browser_tests/tests/graphCanvasMenu.spec.ts-snapshots/canvas-with-visible-links-chromium-linux.png differ diff --git a/browser_tests/tests/nodeBadge.spec.ts b/browser_tests/tests/nodeBadge.spec.ts index 975225b389c..e2dc2fa99fd 100644 --- a/browser_tests/tests/nodeBadge.spec.ts +++ b/browser_tests/tests/nodeBadge.spec.ts @@ -48,25 +48,6 @@ test.describe('Node Badge', { tag: ['@screenshot', '@smoke', '@node'] }, () => { await expect(comfyPage.canvas).toHaveScreenshot('node-badge-multiple.png') }) - - test('Can add badge left-side', async ({ comfyPage }) => { - await comfyPage.page.evaluate(() => { - const LGraphBadge = window.LGraphBadge! - const app = window.app as ComfyApp - const graph = app.graph - const nodes = graph.nodes - - for (const node of nodes) { - node.badges = [new LGraphBadge({ text: 'Test Badge' })] - // @ts-expect-error - Enum value - node.badgePosition = 'top-left' - } - - graph.setDirtyCanvas(true, true) - }) - - await expect(comfyPage.canvas).toHaveScreenshot('node-badge-left.png') - }) }) test.describe( diff --git a/browser_tests/tests/nodeBadge.spec.ts-snapshots/node-badge-left-chromium-linux.png b/browser_tests/tests/nodeBadge.spec.ts-snapshots/node-badge-left-chromium-linux.png deleted file mode 100644 index 2bdffb1d2e0..00000000000 Binary files a/browser_tests/tests/nodeBadge.spec.ts-snapshots/node-badge-left-chromium-linux.png and /dev/null differ diff --git a/browser_tests/tests/nodeDisplay.spec.ts b/browser_tests/tests/nodeDisplay.spec.ts index cdabd2dcfae..6bc1fd0f91e 100644 --- a/browser_tests/tests/nodeDisplay.spec.ts +++ b/browser_tests/tests/nodeDisplay.spec.ts @@ -1,5 +1,7 @@ import { expect } from '@playwright/test' +import { toNodeId } from '@/types/nodeId' + import { comfyPageFixture as test } from '@e2e/fixtures/ComfyPage' import { TestIds } from '@e2e/fixtures/selectors' @@ -50,26 +52,31 @@ test.describe('Optional input', { tag: ['@screenshot', '@node'] }, () => { test('Old workflow with converted input', async ({ comfyPage }) => { await comfyPage.workflow.loadWorkflow('inputs/old_workflow_converted_input') - const node = await comfyPage.nodeOps.getNodeRefById('1') - const inputs = (await node.getProperty('inputs')) as { - name: string - link?: number | null - }[] - const vaeInput = inputs.find((w) => w.name === 'vae') - const convertedInput = inputs.find((w) => w.name === 'strength') - - expect(vaeInput).toBeDefined() - expect(convertedInput).toBeDefined() - expect(vaeInput!.link).toBeNull() - expect(convertedInput!.link).not.toBeNull() + + const linkState = await comfyPage.page.evaluate((nodeId) => { + const node = window.app!.graph!.getNodeById(nodeId) + if (!node) return null + const linkIdOf = (name: string) => { + const slot = node.inputs.findIndex((input) => input.name === name) + return slot === -1 ? 'missing' : (node.getInputLink(slot)?.id ?? null) + } + return { vae: linkIdOf('vae'), strength: linkIdOf('strength') } + }, toNodeId(1)) + + expect(linkState).not.toBeNull() + expect(linkState!.vae).toBeNull() + expect(linkState!.strength).toEqual(expect.any(Number)) }) test('Renamed converted input', async ({ comfyPage }) => { await comfyPage.workflow.loadWorkflow('inputs/renamed_converted_widget') - const node = await comfyPage.nodeOps.getNodeRefById('3') - const inputs = (await node.getProperty('inputs')) as { name: string }[] - const renamedInput = inputs.find((w) => w.name === 'breadth') - expect(renamedInput).toBeUndefined() + const inputNames = await comfyPage.page.evaluate( + (nodeId) => + window.app!.graph!.getNodeById(nodeId)!.inputs.map(({ name }) => name), + toNodeId(3) + ) + + expect(inputNames).not.toContain('breadth') }) test('slider', async ({ comfyPage }) => { diff --git a/browser_tests/tests/performance.spec.ts b/browser_tests/tests/performance.spec.ts index 3882fa61cdc..47480585ade 100644 --- a/browser_tests/tests/performance.spec.ts +++ b/browser_tests/tests/performance.spec.ts @@ -157,6 +157,55 @@ test.describe('Performance', { tag: ['@perf'] }, () => { ) }) + test('large graph legacy node drag', async ({ comfyPage }) => { + await comfyPage.workflow.loadWorkflow('large-graph-workflow') + + // Legacy drags write to layoutStore every frame because registration is + // renderer-independent. + const nodePos = await comfyPage.page.evaluate(() => { + const app = window.app + if (!app) throw new Error('window.app is not available') + + const { canvas } = app + const node = app.graph.nodes[0] + if (!node) throw new Error('Graph has no nodes') + + canvas.ds.scale = 1 + canvas.centerOnNode(node) + const [x, y] = app.canvasPosToClientPos(node.pos) + return { id: node.id, x, y, graphX: node.pos[0] } + }) + await comfyPage.nextFrame() + + await comfyPage.perf.startMeasuring() + + await comfyPage.page.mouse.move(nodePos.x + 40, nodePos.y + 10) + await comfyPage.page.mouse.down() + for (let i = 0; i < 60; i++) { + await comfyPage.page.mouse.move( + nodePos.x + 40 + i * 4, + nodePos.y + 10 + i * 2 + ) + await comfyPage.nextFrame() + } + await comfyPage.page.mouse.up() + + const m = await comfyPage.perf.stopMeasuring('legacy-node-drag') + recordMeasurement(m) + + // Verify the measured interaction was a node drag, not a canvas pan. + const movedX = await comfyPage.page.evaluate((id) => { + const node = window.app?.graph.getNodeById(id) + if (!node) throw new Error(`Node ${id} not found`) + return node.pos[0] + }, nodePos.id) + expect(movedX).not.toBeCloseTo(nodePos.graphX, 0) + + console.log( + `Legacy node drag: ${m.styleRecalcs} style recalcs, ${m.layouts} layouts, ${m.taskDurationMs.toFixed(1)}ms task` + ) + }) + test('large graph zoom interaction', async ({ comfyPage }) => { await comfyPage.workflow.loadWorkflow('large-graph-workflow') diff --git a/browser_tests/tests/primitiveNode.spec.ts-snapshots/primitive-node-connected-dom-widget-chromium-linux.png b/browser_tests/tests/primitiveNode.spec.ts-snapshots/primitive-node-connected-dom-widget-chromium-linux.png index 7f5d2862485..0c06e72a8ef 100644 Binary files a/browser_tests/tests/primitiveNode.spec.ts-snapshots/primitive-node-connected-dom-widget-chromium-linux.png and b/browser_tests/tests/primitiveNode.spec.ts-snapshots/primitive-node-connected-dom-widget-chromium-linux.png differ diff --git a/browser_tests/tests/propertiesPanel/errorsTabCloudMissingModels.spec.ts b/browser_tests/tests/propertiesPanel/errorsTabCloudMissingModels.spec.ts index bb5b961ac5a..2e123fb14e9 100644 --- a/browser_tests/tests/propertiesPanel/errorsTabCloudMissingModels.spec.ts +++ b/browser_tests/tests/propertiesPanel/errorsTabCloudMissingModels.spec.ts @@ -163,23 +163,17 @@ test.describe( await expect.poll(() => comfyPage.subgraph.isInSubgraph()).toBe(true) await expect(errorOverlay).toBeHidden() - const requestCountBeforeRootReturn = countAssetRequestsByTag( - cloudAssetRequests, - 'diffusion_models' - ) - + // Returning to the root must not resurface the installed model as + // missing. No re-scan runs on graph switch, and none is needed — the + // contract is the absence of the error, not the presence of a re-scan. await comfyPage.subgraph.exitViaBreadcrumb() - await panel.open(comfyPage.actionbar.propertiesButton) - - await expect - .poll( - () => - countAssetRequestsByTag(cloudAssetRequests, 'diffusion_models') > - requestCountBeforeRootReturn, - { timeout: 10_000 } - ) - .toBe(true) + await expect.poll(() => comfyPage.subgraph.isInSubgraph()).toBe(false) + await expect( + comfyPage.vueNodes.getNodeLocator(OUTER_SUBGRAPH_NODE_ID) + ).toBeVisible() + await panel.open(comfyPage.actionbar.propertiesButton) + await expect(errorOverlay).toBeHidden() await expect(errorsTab).toBeHidden() }) diff --git a/browser_tests/tests/propertiesPanel/errorsTabModeAware.spec.ts b/browser_tests/tests/propertiesPanel/errorsTabModeAware.spec.ts index 9fb8d7f2a77..30eb84b0fc0 100644 --- a/browser_tests/tests/propertiesPanel/errorsTabModeAware.spec.ts +++ b/browser_tests/tests/propertiesPanel/errorsTabModeAware.spec.ts @@ -628,9 +628,8 @@ test.describe('Errors tab - Mode-aware errors', { tag: '@ui' }, () => { promotedModelTest( 'Refreshing a resolved promoted missing model clears the combo invalid state', - { tag: ['@widget', '@subgraph'] }, + { tag: ['@widget', '@subgraph', '@vue-nodes'] }, async ({ comfyPage }) => { - await comfyPage.settings.setSetting('Comfy.VueNodes.Enabled', true) await loadWorkflowAndOpenErrorsTab( comfyPage, NESTED_PROMOTED_MISSING_MODEL_WORKFLOW.workflowName @@ -865,10 +864,10 @@ test.describe('Errors tab - Mode-aware errors', { tag: '@ui' }, () => { test('Entering a bypassed subgraph does not resurface interior missing model error', async ({ comfyPage }) => { - // Regression: useGraphNodeManager replays graph.onNodeAdded for - // each interior node on subgraph entry; without an ancestor-aware - // guard in scanSingleNodeErrors, that re-scan reintroduced the - // error that the initial pipeline had correctly suppressed. + // Regression: entering a bypassed subgraph re-scans its interior + // nodes; without an ancestor-aware guard in scanSingleNodeErrors, + // that re-scan reintroduced the error the initial pipeline had + // correctly suppressed. await comfyPage.workflow.loadWorkflow( 'missing/missing_models_in_bypassed_subgraph' ) diff --git a/browser_tests/tests/rightClickMenu.spec.ts b/browser_tests/tests/rightClickMenu.spec.ts index d6d65cb905b..5813c206feb 100644 --- a/browser_tests/tests/rightClickMenu.spec.ts +++ b/browser_tests/tests/rightClickMenu.spec.ts @@ -168,11 +168,12 @@ test.describe('Node Right Click Menu', { tag: ['@screenshot', '@ui'] }, () => { // Get EmptyLatentImage node title position dynamically (for dragging) const emptyLatentNode = await comfyPage.nodeOps.getNodeRefById(5) + const originalPosition = await emptyLatentNode.getPosition() const titlePos = await emptyLatentNode.getTitlePosition() await comfyPage.canvasOps.dragAndDrop(titlePos, { x: 200, y: 590 }) - await expect(comfyPage.canvas).toHaveScreenshot( - 'right-click-unpinned-node-moved.png' - ) + await expect + .poll(() => emptyLatentNode.getPosition()) + .not.toEqual(originalPosition) }) test('Can pin/unpin selected nodes', async ({ comfyPage }) => { diff --git a/browser_tests/tests/saveImageAndWebp.spec.ts-snapshots/save-image-and-webm-preview-chromium-linux.png b/browser_tests/tests/saveImageAndWebp.spec.ts-snapshots/save-image-and-webm-preview-chromium-linux.png index f4eb8c215f7..89b53d92136 100644 Binary files a/browser_tests/tests/saveImageAndWebp.spec.ts-snapshots/save-image-and-webm-preview-chromium-linux.png and b/browser_tests/tests/saveImageAndWebp.spec.ts-snapshots/save-image-and-webm-preview-chromium-linux.png differ diff --git a/browser_tests/tests/selectionToolbox.spec.ts-snapshots/selection-toolbox-multiple-nodes-border-chromium-linux.png b/browser_tests/tests/selectionToolbox.spec.ts-snapshots/selection-toolbox-multiple-nodes-border-chromium-linux.png index 35aa61f6424..c7d0d0a9385 100644 Binary files a/browser_tests/tests/selectionToolbox.spec.ts-snapshots/selection-toolbox-multiple-nodes-border-chromium-linux.png and b/browser_tests/tests/selectionToolbox.spec.ts-snapshots/selection-toolbox-multiple-nodes-border-chromium-linux.png differ diff --git a/browser_tests/tests/selectionToolbox.spec.ts-snapshots/selection-toolbox-multiple-selections-border-chromium-linux.png b/browser_tests/tests/selectionToolbox.spec.ts-snapshots/selection-toolbox-multiple-selections-border-chromium-linux.png index ba01d902d22..f077a0549f1 100644 Binary files a/browser_tests/tests/selectionToolbox.spec.ts-snapshots/selection-toolbox-multiple-selections-border-chromium-linux.png and b/browser_tests/tests/selectionToolbox.spec.ts-snapshots/selection-toolbox-multiple-selections-border-chromium-linux.png differ diff --git a/browser_tests/tests/selectionToolbox.spec.ts-snapshots/selection-toolbox-single-node-no-border-chromium-linux.png b/browser_tests/tests/selectionToolbox.spec.ts-snapshots/selection-toolbox-single-node-no-border-chromium-linux.png index 2d65e3cdb1d..ec8d459bbbe 100644 Binary files a/browser_tests/tests/selectionToolbox.spec.ts-snapshots/selection-toolbox-single-node-no-border-chromium-linux.png and b/browser_tests/tests/selectionToolbox.spec.ts-snapshots/selection-toolbox-single-node-no-border-chromium-linux.png differ diff --git a/browser_tests/tests/subgraph/subgraphLinkIdentity.spec.ts b/browser_tests/tests/subgraph/subgraphLinkIdentity.spec.ts new file mode 100644 index 00000000000..84abc78d00d --- /dev/null +++ b/browser_tests/tests/subgraph/subgraphLinkIdentity.spec.ts @@ -0,0 +1,36 @@ +import { expect } from '@playwright/test' + +import { comfyPageFixture as test } from '@e2e/fixtures/ComfyPage' + +test.describe('Subgraph link topology identity', { tag: ['@subgraph'] }, () => { + test('normalizes link IDs across definitions and preserves reroute chains', async ({ + comfyPage + }) => { + await comfyPage.workflow.loadWorkflow( + 'subgraphs/subgraph-link-identity-collision' + ) + + const topology = await comfyPage.page.evaluate(() => { + const graph = window.app!.canvas.graph! + return [...graph.subgraphs.values()] + .map((subgraph) => { + const [link] = subgraph.links.values() + return { + definitionId: subgraph.id, + linkId: link?.id, + parentId: link?.parentId, + rerouteIds: [...subgraph.reroutes.keys()] + } + }) + .sort((a, b) => a.definitionId.localeCompare(b.definitionId)) + }) + + expect(topology).toHaveLength(2) + expect(new Set(topology.map(({ linkId }) => linkId)).size).toBe(2) + for (const { linkId, parentId, rerouteIds } of topology) { + expect(linkId).toBeDefined() + expect(parentId).toBeDefined() + expect(rerouteIds).toContain(parentId) + } + }) +}) diff --git a/browser_tests/tests/subgraph/subgraphSerialization.spec.ts b/browser_tests/tests/subgraph/subgraphSerialization.spec.ts index ebaae234d91..4c59ee558a7 100644 --- a/browser_tests/tests/subgraph/subgraphSerialization.spec.ts +++ b/browser_tests/tests/subgraph/subgraphSerialization.spec.ts @@ -55,7 +55,7 @@ async function getPrimitiveFanoutSnapshot( [] ) const primitiveOriginLinkCount = [ - ...hostNode.subgraph._links.values() + ...hostNode.subgraph.links.values() ].filter((link) => link.origin_id === primitiveNode?.id).length const serialized = window.app!.graph!.serialize() const serializedNode = serialized.nodes.find( @@ -677,7 +677,7 @@ test.describe('Subgraph Serialization', { tag: ['@subgraph'] }, () => { } return labeledGraphs.flatMap(([label, g]) => - [...g._links.values()].flatMap((link) => + [...g.links.values()].flatMap((link) => [ checkEndpoint(label, 'origin_id', link.origin_id, g), checkEndpoint(label, 'target_id', link.target_id, g) diff --git a/browser_tests/tests/vueNodes/interactions/links/linkInteraction.spec.ts b/browser_tests/tests/vueNodes/interactions/links/linkInteraction.spec.ts index efbedbc9ceb..d0d54cd4e27 100644 --- a/browser_tests/tests/vueNodes/interactions/links/linkInteraction.spec.ts +++ b/browser_tests/tests/vueNodes/interactions/links/linkInteraction.spec.ts @@ -1309,10 +1309,64 @@ test.describe('Vue link drag panning', { tag: '@vue-nodes' }, () => { await expect .poll(() => comfyPage.page.evaluate( - () => graph?.nodes?.at(-1)?.outputs?.[0]?.links?.length === 1 + () => graph?.nodes?.at(-1)?.getOutputNodes(0)?.length === 1 ) ) .toBe(true) }) }) }) + +test('Floating reroutes', { tag: '@vue-nodes' }, async ({ comfyPage }) => { + await comfyPage.nodeOps.clearGraph() + const previewNodePos = { position: { x: 800, y: 200 } } + await comfyPage.searchBoxV2.addNode('Preview Image', previewNodePos) + const previewNode = + await comfyPage.vueNodes.getFixtureByTitle('Preview Image') + + await test.step('Create floating reroute', async () => { + const reroutePos = { targetPosition: { x: 700, y: 400 } } + await previewNode + .getSlot('images') + .first() + .dragTo(comfyPage.canvas, reroutePos) + await comfyPage.contextMenu.clickLitegraphMenuItem('Add Reroute') + await comfyPage.searchBoxV2.addNode('Load Image') + }) + + await test.step('Connect node on top of floating link', async () => { + const loadNode = await comfyPage.vueNodes.getFixtureByTitle('Load Image') + await loadNode + .getSlot('IMAGE') + .first() + .dragTo(previewNode.getSlot('images').first()) + }) + + await test.step('Create node from floating reroute', async () => { + await comfyPage.canvas.dragTo(comfyPage.canvas, { + sourcePosition: { x: 680, y: 400 }, + targetPosition: { x: 500, y: 500 } + }) + await comfyPage.contextMenu.clickLitegraphMenuItem('LoadImage') + }) + + await expect + .poll( + () => + comfyPage.page.evaluate(() => { + if (!graph || graph.links.size !== 1) return 'invalid link count' + if (graph.reroutes.size !== 1) return 'invalid reroutes count' + + const linkId = graph.nodes.find((n) => n.title === 'Preview Image') + ?.inputs[0].link + if (!linkId) return 'failed to resolve link id' + + const rerouteId = graph.getLink(linkId)?.parentId + if (!rerouteId) return 'failed to resolve reroute id' + + return !graph.reroutes.has(rerouteId) && 'reroute does not exist' + }), + 'old link is disconnected, reroute is part of new connection' + ) + .toBe(false) +}) diff --git a/browser_tests/tests/vueNodes/interactions/node/bringToFront.spec.ts b/browser_tests/tests/vueNodes/interactions/node/bringToFront.spec.ts index b068da6cd2e..fb8c79ba17c 100644 --- a/browser_tests/tests/vueNodes/interactions/node/bringToFront.spec.ts +++ b/browser_tests/tests/vueNodes/interactions/node/bringToFront.spec.ts @@ -2,7 +2,6 @@ import { comfyExpect as expect, comfyPageFixture as test } from '@e2e/fixtures/ComfyPage' -import type { ComfyPage } from '@e2e/fixtures/ComfyPage' import { fitToViewInstant } from '@e2e/fixtures/utils/fitToView' test.describe( @@ -15,37 +14,12 @@ test.describe( await fitToViewInstant(comfyPage) }) - /** - * Helper to get the z-index of a node by its title - */ - async function getNodeZIndex( - comfyPage: ComfyPage, - title: string - ): Promise { - const node = comfyPage.vueNodes.getNodeByTitle(title) - const style = await node.getAttribute('style') - const match = style?.match(/z-index:\s*(\d+)/) - return match ? parseInt(match[1], 10) : Number.NaN - } - - /** - * Helper to get the bounding box center of a node - */ - async function getNodeCenter( - comfyPage: ComfyPage, - title: string - ): Promise<{ x: number; y: number }> { - const node = comfyPage.vueNodes.getNodeByTitle(title) - const box = await node.boundingBox() - if (!box) throw new Error(`Node "${title}" not found`) - return { x: box.x + box.width / 2, y: box.y + box.height / 2 } - } - test('should bring overlapped node to front when clicking on it', async ({ comfyPage }) => { // Get initial positions - const clipCenter = await getNodeCenter(comfyPage, 'CLIP Text Encode') + const clipCenter = + await comfyPage.vueNodes.getNodeCenter('CLIP Text Encode') const ksamplerHeader = await comfyPage.page .getByText('KSampler') .boundingBox() @@ -63,14 +37,8 @@ test.describe( 'bring-to-front-overlapped-before.png' ) - // KSampler should be on top (higher z-index) after being dragged - await expect - .poll(async () => { - const ksamplerZ = await getNodeZIndex(comfyPage, 'KSampler') - const clipZ = await getNodeZIndex(comfyPage, 'CLIP Text Encode') - return ksamplerZ - clipZ - }) - .toBeGreaterThan(0) + // KSampler should be on top after being dragged + await comfyPage.vueNodes.expectPaintsAbove('KSampler', 'CLIP Text Encode') // Click on CLIP Text Encode (underneath) - need to click on a visible part // Since KSampler is on top, we click on the edge of CLIP that should still be visible @@ -82,14 +50,16 @@ test.describe( await comfyPage.page.mouse.click(clipBox.x + 30, clipBox.y + 10) await comfyPage.nextFrame() - // CLIP should now be on top - compare post-action z-indices - await expect - .poll(async () => { - const clipZ = await getNodeZIndex(comfyPage, 'CLIP Text Encode') - const ksamplerZ = await getNodeZIndex(comfyPage, 'KSampler') - return clipZ - ksamplerZ - }) - .toBeGreaterThan(0) + // CLIP should now be on top + await comfyPage.vueNodes.expectPaintsAbove('CLIP Text Encode', 'KSampler') + + const clipZ = await clipNode.evaluate((node) => + Number(getComputedStyle(node).zIndex) + ) + const allZIndexes = await comfyPage.vueNodes.nodes.evaluateAll((nodes) => + nodes.map((node) => Number(getComputedStyle(node).zIndex)) + ) + expect(clipZ).toBe(Math.max(...allZIndexes)) // Screenshot showing CLIP now on top await expect(comfyPage.canvas).toHaveScreenshot( @@ -101,7 +71,8 @@ test.describe( comfyPage }) => { // Get CLIP Text Encode position (it has a text widget) - const clipCenter = await getNodeCenter(comfyPage, 'CLIP Text Encode') + const clipCenter = + await comfyPage.vueNodes.getNodeCenter('CLIP Text Encode') // Get VAE Decode position and drag it on top of CLIP const vaeHeader = await comfyPage.page @@ -116,13 +87,10 @@ test.describe( await comfyPage.nextFrame() // VAE should be on top after drag - await expect - .poll(async () => { - const vaeZ = await getNodeZIndex(comfyPage, 'VAE Decode') - const clipZ = await getNodeZIndex(comfyPage, 'CLIP Text Encode') - return vaeZ - clipZ - }) - .toBeGreaterThan(0) + await comfyPage.vueNodes.expectPaintsAbove( + 'VAE Decode', + 'CLIP Text Encode' + ) // Screenshot showing VAE on top await expect(comfyPage.canvas).toHaveScreenshot( @@ -136,14 +104,11 @@ test.describe( await comfyPage.page.mouse.click(clipBox.x + 170, clipBox.y + 80) await comfyPage.nextFrame() - // CLIP should now be on top - compare post-action z-indices - await expect - .poll(async () => { - const clipZ = await getNodeZIndex(comfyPage, 'CLIP Text Encode') - const vaeZ = await getNodeZIndex(comfyPage, 'VAE Decode') - return clipZ - vaeZ - }) - .toBeGreaterThan(0) + // CLIP should now be on top + await comfyPage.vueNodes.expectPaintsAbove( + 'CLIP Text Encode', + 'VAE Decode' + ) // Screenshot showing CLIP now on top after widget click await expect(comfyPage.canvas).toHaveScreenshot( diff --git a/browser_tests/tests/vueNodes/interactions/node/collapsedStacking.spec.ts b/browser_tests/tests/vueNodes/interactions/node/collapsedStacking.spec.ts new file mode 100644 index 00000000000..23eeea8ef7e --- /dev/null +++ b/browser_tests/tests/vueNodes/interactions/node/collapsedStacking.spec.ts @@ -0,0 +1,148 @@ +import { + comfyExpect as expect, + comfyPageFixture as test +} from '@e2e/fixtures/ComfyPage' +import { findEmptyCanvasPoint } from '@e2e/fixtures/utils/findEmptyCanvasPoint' +import { fitToViewInstant } from '@e2e/fixtures/utils/fitToView' +import { toNodeId } from '@/types/nodeId' + +test.describe('Collapsed Vue node stacking', { tag: '@vue-nodes' }, () => { + test.beforeEach(async ({ comfyPage }) => { + await comfyPage.settings.setSetting('Comfy.UseNewMenu', 'Disabled') + await comfyPage.workflow.loadWorkflow('vueNodes/collapsed-stacking') + await fitToViewInstant(comfyPage) + }) + + test('updates pointer hit order for selection and collapse state', async ({ + comfyPage + }) => { + const collapsed = + await comfyPage.vueNodes.getFixtureByTitle('CLIP Text Encode') + const expanded = await comfyPage.vueNodes.getFixtureByTitle('VAE Decode') + const collapsedId = toNodeId(2) + const expandedId = toNodeId(1) + const collapsedBox = await collapsed.boundingBox() + const expandedBox = await expanded.boundingBox() + if (!collapsedBox || !expandedBox) throw new Error('Nodes are not visible') + + const overlap = { + x: Math.max(collapsedBox.x, expandedBox.x) + 100, + y: Math.max(collapsedBox.y, expandedBox.y) + 12 + } + const exposedCollapsed = { + x: collapsedBox.x + 35, + y: collapsedBox.y + collapsedBox.height - 2 + } + expect( + collapsedBox.x + collapsedBox.width - overlap.x, + 'Collapsed node must extend beyond the overlap point horizontally' + ).toBeGreaterThanOrEqual(1) + expect( + collapsedBox.y + collapsedBox.height - overlap.y, + 'Collapsed node must extend beyond the overlap point vertically' + ).toBeGreaterThanOrEqual(1) + await comfyPage.page.mouse.click(overlap.x, overlap.y) + await expect + .poll(() => comfyPage.nodeOps.getSelectedNodeIds()) + .toEqual([expandedId]) + + await expanded.header.click({ modifiers: ['Control'] }) + await expect.poll(() => comfyPage.nodeOps.getSelectedNodeIds()).toEqual([]) + await comfyPage.page.mouse.click(exposedCollapsed.x, exposedCollapsed.y) + await expect + .poll(() => comfyPage.nodeOps.getSelectedNodeIds()) + .toEqual([collapsedId]) + + await comfyPage.page.mouse.click(overlap.x, overlap.y) + await expect + .poll(() => comfyPage.nodeOps.getSelectedNodeIds()) + .toEqual([collapsedId]) + + await collapsed.header.click({ modifiers: ['Control'] }) + await expect.poll(() => comfyPage.nodeOps.getSelectedNodeIds()).toEqual([]) + await comfyPage.vueNodes.expectPaintsAbove('VAE Decode', 'CLIP Text Encode') + await comfyPage.page.mouse.click(overlap.x, overlap.y) + await expect + .poll(() => comfyPage.nodeOps.getSelectedNodeIds()) + .toEqual([expandedId]) + + await expanded.header.click({ modifiers: ['Control'] }) + await expect.poll(() => comfyPage.nodeOps.getSelectedNodeIds()).toEqual([]) + await comfyPage.page.mouse.click(exposedCollapsed.x, exposedCollapsed.y) + await expect + .poll(() => comfyPage.nodeOps.getSelectedNodeIds()) + .toEqual([collapsedId]) + await comfyPage.command.executeCommand( + 'Comfy.Canvas.ToggleSelectedNodes.Collapse' + ) + await expect(collapsed.root).not.toHaveAttribute('data-collapsed', 'true') + await comfyPage.page.mouse.click(overlap.x, overlap.y) + await expect + .poll(() => comfyPage.nodeOps.getSelectedNodeIds()) + .toEqual([collapsedId]) + + await comfyPage.command.executeCommand( + 'Comfy.Canvas.ToggleSelectedNodes.Collapse' + ) + await expect(collapsed.root).toHaveAttribute('data-collapsed', 'true') + await collapsed.header.click({ modifiers: ['Control'] }) + await expect.poll(() => comfyPage.nodeOps.getSelectedNodeIds()).toEqual([]) + await comfyPage.vueNodes.expectPaintsAbove('VAE Decode', 'CLIP Text Encode') + await comfyPage.page.mouse.click(overlap.x, overlap.y) + await expect + .poll(() => comfyPage.nodeOps.getSelectedNodeIds()) + .toEqual([expandedId]) + }) + + test('keeps an unselected collapsed node as the drag owner after promotion', async ({ + comfyPage + }) => { + const collapsed = + await comfyPage.vueNodes.getFixtureByTitle('CLIP Text Encode') + const collapsedNode = await comfyPage.nodeOps.getNodeRefById('2') + const expandedNode = await comfyPage.nodeOps.getNodeRefById('1') + const collapsedBefore = await collapsedNode.getPosition() + const expandedBefore = await expandedNode.getPosition() + const collapsedBox = await collapsed.boundingBox() + if (!collapsedBox) throw new Error('Collapsed node is not visible') + + await comfyPage.vueNodes.clearSelection() + await expect.poll(() => comfyPage.nodeOps.getSelectedNodeIds()).toEqual([]) + + const start = { + x: collapsedBox.x + 10, + y: collapsedBox.y + collapsedBox.height / 2 + } + const emptyCanvasPoint = await findEmptyCanvasPoint( + comfyPage.canvas, + 'bottom-right' + ) + + await comfyPage.page.mouse.move(start.x, start.y) + await comfyPage.page.mouse.down() + try { + await comfyPage.page.mouse.move(start.x + 8, start.y + 8) + await expect + .poll(() => comfyPage.nodeOps.getSelectedNodeIds()) + .toEqual([toNodeId(2)]) + await comfyPage.page.mouse.move(emptyCanvasPoint.x, emptyCanvasPoint.y) + } finally { + await comfyPage.page.mouse.up() + } + await comfyPage.nextFrame() + + const collapsedAfter = await collapsedNode.getPosition() + const expandedAfter = await expandedNode.getPosition() + expect(collapsedAfter).not.toEqual(collapsedBefore) + expect(expandedAfter).toEqual(expandedBefore) + + await comfyPage.page.mouse.move( + emptyCanvasPoint.x - 30, + emptyCanvasPoint.y - 30 + ) + await comfyPage.nextFrame() + + expect(await collapsedNode.getPosition()).toEqual(collapsedAfter) + expect(await expandedNode.getPosition()).toEqual(expandedAfter) + }) +}) diff --git a/browser_tests/tests/vueNodes/interactions/node/move.spec.ts b/browser_tests/tests/vueNodes/interactions/node/move.spec.ts index 1690a896130..a435fd817ab 100644 --- a/browser_tests/tests/vueNodes/interactions/node/move.spec.ts +++ b/browser_tests/tests/vueNodes/interactions/node/move.spec.ts @@ -6,19 +6,30 @@ import { } from '@e2e/fixtures/ComfyPage' import type { ComfyPage } from '@e2e/fixtures/ComfyPage' import type { Position } from '@e2e/fixtures/types' +import { findEmptyCanvasPoint } from '@e2e/fixtures/utils/findEmptyCanvasPoint' import { VueNodeFixture } from '@e2e/fixtures/utils/vueNodeFixtures' +import { getSlotKey } from '@/renderer/core/layout/slots/slotIdentifier' +import { toNodeId } from '@/types/nodeId' +import type { NodeId } from '@/types/nodeId' + +const CREATE_GROUP_HOTKEY = 'Control+g' test.describe('Vue Node Moving', { tag: '@vue-nodes' }, () => { - const getHeaderPos = async ( - comfyPage: ComfyPage, - title: string - ): Promise<{ x: number; y: number }> => { + const getHeaderBounds = async (comfyPage: ComfyPage, title: string) => { const box = await comfyPage.vueNodes .getNodeByTitle(title) .getByTestId('node-title') .first() .boundingBox() if (!box) throw new Error(`${title} header not found`) + return box + } + + const getHeaderPos = async ( + comfyPage: ComfyPage, + title: string + ): Promise<{ x: number; y: number }> => { + const box = await getHeaderBounds(comfyPage, title) return { x: box.x + box.width / 2, y: box.y + box.height / 2 } } @@ -42,6 +53,49 @@ test.describe('Vue Node Moving', { tag: '@vue-nodes' }, () => { expect(Math.abs(a.y - b.y)).toBeLessThanOrEqual(tol) } + const expectSlotPositionTracksDom = async ( + comfyPage: ComfyPage, + nodeId: NodeId, + slotIndex: number, + isInput: boolean + ) => { + const slotKey = getSlotKey(nodeId, slotIndex, isInput) + + await expect(async () => { + const positions = await comfyPage.page.evaluate( + ({ nodeId, slotIndex, isInput, slotKey }) => { + const app = window.app! + const node = app.graph.getNodeById(nodeId) + const slot = document.querySelector( + `[data-slot-key="${slotKey}"]` + ) + if (!node || !slot) return null + + const graphPosition = isInput + ? node.getInputPos(slotIndex) + : node.getOutputPos(slotIndex) + const [linkX, linkY] = app.canvasPosToClientPos(graphPosition) + const slotBounds = slot.getBoundingClientRect() + + return { + link: { x: linkX, y: linkY }, + slot: { + x: slotBounds.x + slotBounds.width / 2, + y: slotBounds.y + slotBounds.height / 2 + } + } + }, + { nodeId, slotIndex, isInput, slotKey } + ) + expect( + positions, + 'Link and DOM slot positions should resolve' + ).not.toBeNull() + expect(Math.abs(positions!.link.x - positions!.slot.x)).toBeLessThan(2) + expect(Math.abs(positions!.link.y - positions!.slot.y)).toBeLessThan(2) + }).toPass({ timeout: 5000 }) + } + const dragFromTabButton = async (comfyPage: ComfyPage, button: Locator) => { const box = await button.boundingBox() if (!box) throw new Error('Tab button has no bounding box') @@ -61,6 +115,103 @@ test.describe('Vue Node Moving', { tag: '@vue-nodes' }, () => { const getAdvancedInputsButton = (node: Locator) => node.getByTestId('advanced-inputs-button') + const armPointerCaptureTracking = async (comfyPage: ComfyPage) => { + await comfyPage.page.evaluate(() => { + window.addEventListener( + 'pointerdown', + (event) => { + document.documentElement.dataset.dragTestPointerId = String( + event.pointerId + ) + }, + { capture: true, once: true } + ) + }) + } + + const releaseActivePointerCapture = async (comfyPage: ComfyPage) => { + const released = await comfyPage.page.evaluate(() => { + const pointerId = Number( + document.documentElement.dataset.dragTestPointerId + ) + if (!Number.isInteger(pointerId)) return false + + const elements = [ + document.documentElement, + ...document.querySelectorAll('*') + ] + const captureOwner = elements.find((element) => + element.hasPointerCapture(pointerId) + ) + if (!captureOwner) return false + + captureOwner.releasePointerCapture(pointerId) + return true + }) + + expect(released, 'A DOM element should own pointer capture').toBe(true) + } + + const getDistantVisibleNode = async ( + comfyPage: ComfyPage, + source: { x: number; y: number; width: number; height: number }, + sourceNodeId: string + ) => { + return await comfyPage.page.evaluate( + ({ source, sourceNodeId }) => { + const sourceCenter = { + x: source.x + source.width / 2, + y: source.y + source.height / 2 + } + + const candidates = Array.from( + document.querySelectorAll('[data-node-id]') + ).flatMap((node) => { + if (node.dataset.nodeId === sourceNodeId) return [] + + const title = node.querySelector( + '[data-testid="node-title"]' + ) + if (!title) return [] + + const bounds = title.getBoundingClientRect() + const center = { + x: bounds.x + bounds.width / 2, + y: bounds.y + bounds.height / 2 + } + const distance = Math.hypot( + center.x - sourceCenter.x, + center.y - sourceCenter.y + ) + if ( + document + .elementFromPoint(center.x, center.y) + ?.closest('[data-node-id]') !== node + ) { + return [] + } + + return [ + { + nodeId: node.dataset.nodeId, + x: bounds.x, + y: bounds.y, + width: bounds.width, + height: bounds.height, + distance + } + ] + }) + + const target = candidates.toSorted((a, b) => b.distance - a.distance)[0] + const nodeId = target?.nodeId + if (!nodeId) throw new Error('No visible target node found') + return { ...target, nodeId } + }, + { source, sourceNodeId } + ) + } + const moveAdvancedButtonRightEdgePastCanvas = async ( comfyPage: ComfyPage, button: Locator, @@ -133,6 +284,69 @@ test.describe('Vue Node Moving', { tag: '@vue-nodes' }, () => { await expectPosChanged(headerPos, afterPos) }) + test('keeps drag ownership after pointer capture is lost', async ({ + comfyPage + }) => { + const sourceBefore = await getHeaderBounds(comfyPage, 'KSampler') + const sourceNodeId = await comfyPage.vueNodes.getNodeIdByTitle('KSampler') + const targetBefore = await getDistantVisibleNode( + comfyPage, + sourceBefore, + sourceNodeId + ) + const targetTitle = comfyPage.vueNodes + .getNodeLocator(targetBefore.nodeId) + .getByTestId('node-title') + const sourceStart = { + x: sourceBefore.x + sourceBefore.width / 2, + y: sourceBefore.y + sourceBefore.height / 2 + } + const targetCenter = { + x: targetBefore.x + targetBefore.width / 2, + y: targetBefore.y + targetBefore.height / 2 + } + await armPointerCaptureTracking(comfyPage) + await comfyPage.page.mouse.move(sourceStart.x, sourceStart.y) + await comfyPage.page.mouse.down() + try { + await comfyPage.page.mouse.move(sourceStart.x + 10, sourceStart.y + 10, { + steps: 5 + }) + await comfyPage.nextFrame() + await releaseActivePointerCapture(comfyPage) + + await comfyPage.page.mouse.move(targetCenter.x, targetCenter.y, { + steps: 1 + }) + await comfyPage.nextFrame() + await releaseActivePointerCapture(comfyPage) + + const releasePoint = await findEmptyCanvasPoint(comfyPage.canvas) + await comfyPage.page.mouse.move(releasePoint.x, releasePoint.y) + } finally { + await comfyPage.page.mouse.up() + } + await comfyPage.nextFrame() + + const sourceAfterRelease = await getHeaderBounds(comfyPage, 'KSampler') + const targetAfterRelease = await targetTitle.boundingBox() + if (!targetAfterRelease) throw new Error('Target node header not found') + + await expectPosChanged(sourceBefore, sourceAfterRelease) + expectSameDelta(targetAfterRelease, targetBefore) + + await comfyPage.page.mouse.move(targetCenter.x + 20, targetCenter.y + 20, { + steps: 5 + }) + await comfyPage.nextFrame() + + const sourceFinal = await getHeaderBounds(comfyPage, 'KSampler') + const targetFinal = await targetTitle.boundingBox() + if (!targetFinal) throw new Error('Target node header not found') + expectSameDelta(sourceFinal, sourceAfterRelease) + expectSameDelta(targetFinal, targetAfterRelease) + }) + test('should not toggle advanced inputs when dragging by the Advanced button', async ({ comfyPage }) => { @@ -332,14 +546,105 @@ test.describe('Vue Node Moving', { tag: '@vue-nodes' }, () => { await comfyPage.canvasOps.moveMouseToEmptyArea() }) - test('pointerCancel stops autopan', async ({ comfyPage }) => { - const ksampler = await comfyPage.vueNodes.getFixtureByTitle('KSampler') - await ksampler.header.click({ trial: true }) + test('keeps link geometry attached while dragging a collapsed node', async ({ + comfyPage + }) => { + await comfyPage.workflow.loadWorkflow('default') + const node = await comfyPage.vueNodes.getFixtureByTitle('Load Checkpoint') + const rawNodeId = await node.root.getAttribute('data-node-id') + if (!rawNodeId) throw new Error('Load Checkpoint node ID not found') + const nodeId = toNodeId(rawNodeId) + + await node.select() + await comfyPage.command.executeCommand( + 'Comfy.Canvas.ToggleSelectedNodes.Collapse' + ) + await expect(node.root).toHaveAttribute('data-collapsed', 'true') + const nodeBounds = await node.boundingBox() + if (!nodeBounds) throw new Error('Collapsed node bounds not found') + + const start = { + x: nodeBounds.x + nodeBounds.width / 2, + y: nodeBounds.y + nodeBounds.height / 2 + } + await comfyPage.page.mouse.move(start.x, start.y) + await comfyPage.page.mouse.down() + try { + await comfyPage.page.mouse.move(start.x + 120, start.y + 80, { + steps: 10 + }) + await comfyPage.nextFrame() + await expectSlotPositionTracksDom(comfyPage, nodeId, 0, false) + } finally { + await comfyPage.page.mouse.up() + } + }) + + test('keeps link geometry attached while dragging a group', async ({ + comfyPage + }) => { + await comfyPage.workflow.loadWorkflow('default') + const checkpoint = + await comfyPage.vueNodes.getFixtureByTitle('Load Checkpoint') + const rawCheckpointId = await checkpoint.root.getAttribute('data-node-id') + if (!rawCheckpointId) throw new Error('Load Checkpoint node ID not found') + const checkpointId = toNodeId(rawCheckpointId) + + await checkpoint.header.click() + const sampler = await comfyPage.vueNodes.getFixtureByTitle('KSampler') + await sampler.header.click({ modifiers: ['Control'] }) + await comfyPage.page.keyboard.press(CREATE_GROUP_HOTKEY) + const titleInput = comfyPage.page.getByTestId('node-title-input') + await titleInput.fill('Linked nodes') + await titleInput.press('Enter') + + await expect + .poll(() => comfyPage.canvasOps.getGroupPosition('Linked nodes')) + .toBeTruthy() + const groupPosition = + await comfyPage.canvasOps.getGroupPosition('Linked nodes') + const groupStart = await comfyPage.page.evaluate(({ x, y }) => { + const [clientX, clientY] = window.app!.canvasPosToClientPos([ + x + 50, + y + 15 + ]) + return { x: clientX, y: clientY } + }, groupPosition) + + await comfyPage.page.mouse.move(groupStart.x, groupStart.y) await comfyPage.page.mouse.down() + try { + await comfyPage.page.mouse.move(groupStart.x + 120, groupStart.y + 80, { + steps: 10 + }) + await comfyPage.nextFrame() + await expectSlotPositionTracksDom(comfyPage, checkpointId, 0, false) + } finally { + await comfyPage.page.mouse.up() + } + await comfyPage.nextFrame() + + await expectSlotPositionTracksDom(comfyPage, checkpointId, 0, false) + }) + + test('pointerCancel stops autopan', async ({ comfyPage, comfyMouse }) => { + const ksampler = await comfyPage.vueNodes.getFixtureByTitle('KSampler') + const canvasBox = await comfyPage.canvas.boundingBox() + const headerBox = await ksampler.header.boundingBox() + if (!canvasBox) throw new Error('Canvas bounding box not found') + if (!headerBox) throw new Error('KSampler header bounding box not found') + const panTarget = { + x: canvasBox.x + canvasBox.width - 2, + y: canvasBox.y + canvasBox.height / 2 + } + await comfyMouse.move({ + x: headerBox.x + headerBox.width / 2, + y: headerBox.y + headerBox.height / 2 + }) const getOffset = () => comfyPage.canvasOps.getOffset() const initialOffset = await getOffset() - await comfyPage.page.mouse.move(10, 10, { steps: 20 }) + await comfyMouse.drag(panTarget, { steps: 20 }) await expect.poll(getOffset, 'drag with autopan').not.toEqual(initialOffset) await test.step('move outside pan range and cancel drag', async () => { @@ -351,7 +656,7 @@ test.describe('Vue Node Moving', { tag: '@vue-nodes' }, () => { const secondaryOffset = await getOffset() - await comfyPage.page.mouse.move(10, 10, { steps: 20 }) + await comfyPage.page.mouse.move(panTarget.x, panTarget.y, { steps: 20 }) await comfyPage.nextFrame() expect(await getOffset(), 'drag canceled').toEqual(secondaryOffset) }) @@ -394,7 +699,10 @@ test.describe('Vue Node Moving', { tag: '@vue-nodes' }, () => { }) const getReroutePos = () => - comfyPage.page.evaluate(() => [...graph!.reroutes.values()][0]) + comfyPage.page.evaluate(() => { + const reroute = graph!.reroutes.values().next().value + return reroute ? [...reroute.pos] : null + }) const getGroupPos = () => comfyPage.page.evaluate(() => graph!.groups[0].pos) const initialReroutePos = await getReroutePos() @@ -403,6 +711,18 @@ test.describe('Vue Node Moving', { tag: '@vue-nodes' }, () => { await expect.poll(getReroutePos).not.toEqual(initialReroutePos) await expect.poll(getGroupPos).not.toEqual(initialGroupPos) + const movedReroutePos = await getReroutePos() + const movedGroupPos = await getGroupPos() + + await comfyPage.keyboard.undo() + + await expect.poll(getReroutePos).toEqual(initialReroutePos) + await expect.poll(getGroupPos).toEqual(initialGroupPos) + + await comfyPage.keyboard.redo() + + await expect.poll(getReroutePos).toEqual(movedReroutePos) + await expect.poll(getGroupPos).toEqual(movedGroupPos) }) test( diff --git a/browser_tests/tests/vueNodes/interactions/node/resize.spec.ts b/browser_tests/tests/vueNodes/interactions/node/resize.spec.ts index 59a27a37ca0..edea4907b86 100644 --- a/browser_tests/tests/vueNodes/interactions/node/resize.spec.ts +++ b/browser_tests/tests/vueNodes/interactions/node/resize.spec.ts @@ -73,6 +73,88 @@ test.describe( } }) + test('should keep a resized width across a save and reload', async ({ + comfyPage + }) => { + test.setTimeout(30000) + + const measureWidth = async (title: string) => { + const node = await comfyPage.vueNodes.getFixtureByTitle(title) + await expect(node.root).toBeVisible() + const box = await node.boundingBox() + if (!box) throw new Error(`Failed to measure node "${title}"`) + return box.width + } + + const initialWidth = await measureWidth('KSampler') + const referenceWidth = await measureWidth('Save Image') + + const vueNode = await comfyPage.vueNodes.getFixtureByTitle('KSampler') + const beforeResize = Date.now() + await vueNode.resizeFromCorner('SE', 120, 0) + await comfyPage.nextFrame() + const resizedWidth = await measureWidth('KSampler') + expect(resizedWidth).toBeGreaterThan(initialWidth + 100) + + await comfyPage.workflow.waitForDraftIndexUpdatedSince(beforeResize) + await comfyPage.workflow.reloadAndWaitForApp() + + // Untouched node keeps its width, proving the viewport scale is + // comparable across the reload. + await expect + .poll(async () => measureWidth('Save Image')) + .toBeCloseTo(referenceWidth, 0) + + await expect + .poll(async () => measureWidth('KSampler')) + .toBeGreaterThan(resizedWidth - 5) + }) + + test('resize handles only receive pointer hits inside the node', async ({ + comfyPage + }) => { + const node = await comfyPage.vueNodes.getFixtureByTitle('KSampler') + const box = await node.boundingBox() + if (!box) throw new Error('Node bounding box not found') + + const points = [ + { + corner: 'NW', + inside: [box.x + 1, box.y + 1], + outside: [box.x - 1, box.y - 1] + }, + { + corner: 'NE', + inside: [box.x + box.width - 1, box.y + 1], + outside: [box.x + box.width + 1, box.y - 1] + }, + { + corner: 'SW', + inside: [box.x + 1, box.y + box.height - 1], + outside: [box.x - 1, box.y + box.height + 1] + }, + { + corner: 'SE', + inside: [box.x + box.width - 1, box.y + box.height - 1], + outside: [box.x + box.width + 1, box.y + box.height + 1] + } + ] as const + + const hitResizeCorner = ([x, y]: readonly [number, number]) => + comfyPage.page.evaluate( + ([clientX, clientY]) => + document + .elementFromPoint(clientX, clientY) + ?.closest('[data-corner]')?.dataset.corner ?? null, + [x, y] as const + ) + + for (const { corner, inside, outside } of points) { + expect(await hitResizeCorner(inside)).toBe(corner) + expect(await hitResizeCorner(outside)).toBeNull() + } + }) + test.describe('minimum size enforcement', () => { test('SW resize clamps width, keeping right edge fixed', async ({ comfyPage @@ -83,14 +165,18 @@ test.describe( const bounds = await node.boundingBox() return bounds ? bounds.x + bounds.width : -1 } - const getWidth = async () => (await node.boundingBox())?.width ?? -1 + const nodeId = await node.root.getAttribute('data-node-id') + if (!nodeId) throw new Error('Node ID not found') + const nodeRef = await comfyPage.nodeOps.getNodeRefById(nodeId) const initialRight = await getRight() await node.resizeFromCorner('SW', box.width + 100, 0) await expect.poll(getRight).toBeCloseTo(initialRight, 0) - await expect.poll(getWidth).toBeGreaterThanOrEqual(MIN_NODE_WIDTH) + await expect + .poll(async () => (await nodeRef.getSize()).width) + .toBeGreaterThanOrEqual(MIN_NODE_WIDTH) }) test('NE resize clamps height at its lower bound', async ({ diff --git a/browser_tests/tests/vueNodes/layout/rendererToggleGeometry.spec.ts b/browser_tests/tests/vueNodes/layout/rendererToggleGeometry.spec.ts new file mode 100644 index 00000000000..50129513e69 --- /dev/null +++ b/browser_tests/tests/vueNodes/layout/rendererToggleGeometry.spec.ts @@ -0,0 +1,293 @@ +import { + comfyExpect as expect, + comfyPageFixture as test +} from '@e2e/fixtures/ComfyPage' +import type { ComfyPage } from '@e2e/fixtures/ComfyPage' +import { fitToViewInstant } from '@e2e/fixtures/utils/fitToView' +import type { Point } from '@/lib/litegraph/src/litegraph' +import type { NodeId } from '@/types/nodeId' +import { toNodeId } from '@/types/nodeId' + +const LEGACY_TITLE_HEIGHT = 30 + +interface NodeGeometry { + pos: Point + size: Point + inputs: Point[] + outputs: Point[] +} + +/** + * Read slots through the accessors used by `drawConnections`; raw fields + * bypass the store projection under test. + */ +async function readGeometry( + comfyPage: ComfyPage, + nodeId: NodeId +): Promise { + return comfyPage.page.evaluate((id): NodeGeometry => { + const node = window.app?.canvas.graph?.getNodeById(id) + if (!node) throw new Error(`Node ${id} not found`) + + return { + pos: [node.pos[0], node.pos[1]], + size: [node.size[0], node.size[1]], + inputs: node.inputs.map((_, i) => node.getInputPos(i)), + outputs: node.outputs.map((_, i) => node.getOutputPos(i)) + } + }, nodeId) +} + +function slotsOf(geometry: NodeGeometry): Point[] { + return [...geometry.inputs, ...geometry.outputs] +} + +function expectSlotsTrackedNode(after: NodeGeometry, before: NodeGeometry) { + const dx = after.pos[0] - before.pos[0] + const dy = after.pos[1] - before.pos[1] + expect(Math.abs(dx) + Math.abs(dy), 'drag moved the node').toBeGreaterThan(1) + + const beforeSlots = slotsOf(before) + const afterSlots = slotsOf(after) + expect(afterSlots, 'slot count after drag').toHaveLength(beforeSlots.length) + afterSlots.forEach(([x, y], i) => { + expect(x, `slot ${i} x tracked the node`).toBeCloseTo( + beforeSlots[i][0] + dx, + 0 + ) + expect(y, `slot ${i} y tracked the node`).toBeCloseTo( + beforeSlots[i][1] + dy, + 0 + ) + }) +} + +function expectGeometryPreserved( + actual: NodeGeometry, + reference: NodeGeometry, + label: string +) { + expect(actual.pos[0], `${label}: x`).toBeCloseTo(reference.pos[0], 0) + expect(actual.pos[1], `${label}: y`).toBeCloseTo(reference.pos[1], 0) + expect(actual.size, `${label}: size`).toEqual(reference.size) + + const referenceSlots = slotsOf(reference) + const actualSlots = slotsOf(actual) + expect(actualSlots, `${label}: slot count`).toHaveLength( + referenceSlots.length + ) + actualSlots.forEach(([x, y], i) => { + expect(x, `${label}: slot ${i} x`).toBeCloseTo(referenceSlots[i][0], 0) + expect(y, `${label}: slot ${i} y`).toBeCloseTo(referenceSlots[i][1], 0) + }) +} + +/** + * Renderers compute different slot offsets, so require slots only to remain + * within their node bounds. + */ +function expectSlotsOnNode(geometry: NodeGeometry, label: string) { + const MARGIN = 20 + const [x, y] = geometry.pos + const [width, height] = geometry.size + + slotsOf(geometry).forEach(([slotX, slotY], i) => { + expect(slotX, `${label}: slot ${i} x within node`).toBeGreaterThanOrEqual( + x - MARGIN + ) + expect(slotX, `${label}: slot ${i} x within node`).toBeLessThanOrEqual( + x + width + MARGIN + ) + expect(slotY, `${label}: slot ${i} y within node`).toBeGreaterThanOrEqual( + y - LEGACY_TITLE_HEIGHT - MARGIN + ) + expect(slotY, `${label}: slot ${i} y within node`).toBeLessThanOrEqual( + y + height + MARGIN + ) + }) +} + +async function setVueMode(comfyPage: ComfyPage, enabled: boolean) { + await comfyPage.settings.setSetting('Comfy.VueNodes.Enabled', enabled) + if (enabled) await comfyPage.vueNodes.waitForNodes() + await comfyPage.nextFrame() +} + +test.describe('Renderer toggle geometry', { tag: ['@vue-nodes'] }, () => { + test('slot geometry survives a Vue to legacy round trip', async ({ + comfyPage + }) => { + const nodeId = toNodeId( + await comfyPage.vueNodes.getNodeIdByTitle('KSampler') + ) + + const before = await readGeometry(comfyPage, nodeId) + expect( + slotsOf(before).length, + 'fixture node must have slots for this test to mean anything' + ).toBeGreaterThan(0) + + const { header } = await comfyPage.vueNodes.getFixtureByTitle('KSampler') + const headerBox = await header.boundingBox() + if (!headerBox) throw new Error('KSampler header not found') + + const startX = headerBox.x + headerBox.width / 2 + const startY = headerBox.y + headerBox.height / 2 + await comfyPage.page.mouse.move(startX, startY) + await comfyPage.page.mouse.down() + await comfyPage.page.mouse.move(startX + 120, startY + 90, { steps: 10 }) + await comfyPage.page.mouse.up() + await comfyPage.nextFrame() + + const moved = await readGeometry(comfyPage, nodeId) + expectSlotsTrackedNode(moved, before) + + await setVueMode(comfyPage, false) + + const legacyGeometry = await readGeometry(comfyPage, nodeId) + expect(legacyGeometry.pos[0], 'legacy x').toBeCloseTo(moved.pos[0], 0) + expect(legacyGeometry.pos[1], 'legacy y').toBeCloseTo(moved.pos[1], 0) + expect(legacyGeometry.size, 'legacy size').toEqual(moved.size) + expectSlotsOnNode(legacyGeometry, 'after switching to legacy') + + await setVueMode(comfyPage, true) + + expectGeometryPreserved( + await readGeometry(comfyPage, nodeId), + moved, + 'after switching back to Vue' + ) + }) + + test( + 'preserves frontmost order after a legacy drag', + { tag: ['@node'] }, + async ({ comfyPage }) => { + await comfyPage.workflow.loadWorkflow('vueNodes/simple-triple') + await setVueMode(comfyPage, false) + await fitToViewInstant(comfyPage) + + const [ksampler] = await comfyPage.nodeOps.getNodeRefsByTitle('KSampler') + const [clip] = await comfyPage.nodeOps.getNodeRefsByTitle( + 'CLIP Text Encode (Prompt)' + ) + const ksamplerPosition = await ksampler.getPosition() + const clipPosition = await clip.getPosition() + + await ksampler.dragBy({ + x: clipPosition.x - ksamplerPosition.x, + y: clipPosition.y - ksamplerPosition.y + }) + await comfyPage.nextFrame() + + const lastNodeId = await comfyPage.page.evaluate( + () => window.app?.graph.nodes.at(-1)?.id + ) + expect(lastNodeId, 'KSampler is frontmost after the legacy drag').toBe( + ksampler.id + ) + + await setVueMode(comfyPage, true) + await expect(comfyPage.vueNodes.nodes).toHaveCount(3) + + const ksamplerNode = comfyPage.vueNodes.getNodeByTitle('KSampler') + const clipNode = comfyPage.vueNodes.getNodeByTitle('CLIP Text Encode') + await expect + .poll(async () => { + const ksamplerZIndex = await ksamplerNode.evaluate((node) => + Number(getComputedStyle(node).zIndex) + ) + const clipZIndex = await clipNode.evaluate((node) => + Number(getComputedStyle(node).zIndex) + ) + return ksamplerZIndex - clipZIndex + }) + .toBeGreaterThan(0) + } + ) + + test( + 'preserves frontmost order when switching to legacy rendering', + { tag: ['@node'] }, + async ({ comfyPage }) => { + await comfyPage.workflow.loadWorkflow('vueNodes/simple-triple') + await fitToViewInstant(comfyPage) + + const [ksampler] = await comfyPage.nodeOps.getNodeRefsByTitle('KSampler') + const [clip] = await comfyPage.nodeOps.getNodeRefsByTitle( + 'CLIP Text Encode (Prompt)' + ) + const ksamplerNode = comfyPage.vueNodes.getNodeByTitle('KSampler') + const clipNode = comfyPage.vueNodes.getNodeByTitle('CLIP Text Encode') + const { header } = await comfyPage.vueNodes.getFixtureByTitle('KSampler') + const { header: clipHeader } = + await comfyPage.vueNodes.getFixtureByTitle('CLIP Text Encode') + const headerBox = await header.boundingBox() + const clipBox = await clipHeader.boundingBox() + if (!headerBox || !clipBox) throw new Error('Fixture nodes not found') + + await comfyPage.canvasOps.dragAndDrop( + { + x: headerBox.x + headerBox.width / 2, + y: headerBox.y + headerBox.height / 2 + }, + { + x: clipBox.x + clipBox.width / 2, + y: clipBox.y + clipBox.height / 2 + } + ) + await comfyPage.nextFrame() + + await expect + .poll(async () => { + const ksamplerZIndex = await ksamplerNode.evaluate((node) => + Number(getComputedStyle(node).zIndex) + ) + const clipZIndex = await clipNode.evaluate((node) => + Number(getComputedStyle(node).zIndex) + ) + return ksamplerZIndex - clipZIndex + }) + .toBeGreaterThan(0) + + await setVueMode(comfyPage, false) + await comfyPage.page.evaluate(() => window.app!.canvas.deselectAll()) + expect(await comfyPage.nodeOps.getSelectedNodeIds()).toEqual([]) + + const ksamplerGeometry = await readGeometry(comfyPage, ksampler.id) + const clipGeometry = await readGeometry(comfyPage, clip.id) + const overlap = { + left: Math.max(ksamplerGeometry.pos[0], clipGeometry.pos[0]), + top: Math.max( + ksamplerGeometry.pos[1] - LEGACY_TITLE_HEIGHT, + clipGeometry.pos[1] - LEGACY_TITLE_HEIGHT + ), + right: Math.min( + ksamplerGeometry.pos[0] + ksamplerGeometry.size[0], + clipGeometry.pos[0] + clipGeometry.size[0] + ), + bottom: Math.min(ksamplerGeometry.pos[1], clipGeometry.pos[1]) + } + if (overlap.left >= overlap.right || overlap.top >= overlap.bottom) { + throw new Error('Fixture nodes do not overlap') + } + + const overlapCenter: Point = [ + (overlap.left + overlap.right) / 2, + (overlap.top + overlap.bottom) / 2 + ] + const clickPosition = await comfyPage.canvasOps.convertOffsetToCanvas([ + overlapCenter[0], + overlapCenter[1] + ]) + await comfyPage.canvasOps.mouseClickAt({ + x: clickPosition[0], + y: clickPosition[1] + }) + + expect(await comfyPage.nodeOps.getSelectedNodeIds()).toEqual([ + ksampler.id + ]) + } + ) +}) diff --git a/browser_tests/tests/vueNodes/layout/subgraphLayoutSync.spec.ts b/browser_tests/tests/vueNodes/layout/subgraphLayoutSync.spec.ts new file mode 100644 index 00000000000..2c49318c7dc --- /dev/null +++ b/browser_tests/tests/vueNodes/layout/subgraphLayoutSync.spec.ts @@ -0,0 +1,78 @@ +import { + comfyExpect as expect, + comfyPageFixture as test +} from '@e2e/fixtures/ComfyPage' +import type { ComfyPage } from '@e2e/fixtures/ComfyPage' +import { toNodeId } from '@/types/nodeId' + +const GROWTH: [number, number] = [90, 100] + +async function renderedBounds(comfyPage: ComfyPage, nodeId: string) { + return comfyPage.vueNodes + .getNodeLocator(nodeId) + .evaluate((element) => [ + element instanceof HTMLElement ? element.offsetWidth : 0, + element instanceof HTMLElement ? element.offsetHeight : 0 + ]) +} + +/** + * Mutate graph size directly to reproduce the legacy custom-node path, which + * has no user-interaction equivalent. + */ +async function expectGrowthRenders( + comfyPage: ComfyPage, + nodeId: string, + label: string +) { + const before = await renderedBounds(comfyPage, nodeId) + expect(before[0], `${label}: node has a rendered width`).toBeGreaterThan(0) + expect(before[1], `${label}: node has a rendered height`).toBeGreaterThan(0) + + await comfyPage.page.evaluate( + ({ id, growWidth, growHeight }) => { + const node = window.app?.canvas.graph?.getNodeById(id) + if (!node) throw new Error(`Node ${id} not found`) + + node.setSize([node.size[0] + growWidth, node.size[1] + growHeight]) + }, + { id: toNodeId(nodeId), growWidth: GROWTH[0], growHeight: GROWTH[1] } + ) + + await expect + .poll(async () => renderedBounds(comfyPage, nodeId), { message: label }) + .toEqual([before[0] + GROWTH[0], before[1] + GROWTH[1]]) +} + +test( + 'nodes keep following graph mutations across every graph transition', + { tag: '@vue-nodes' }, + async ({ comfyPage }) => { + await comfyPage.workflow.loadWorkflow('subgraphs/basic-subgraph') + await comfyPage.vueNodes.waitForNodes() + + const [rootNodeId] = await comfyPage.vueNodes.getNodeIds() + await expectGrowthRenders(comfyPage, rootNodeId, 'at the root graph') + + await comfyPage.vueNodes.enterSubgraph('2') + const [interiorNodeId] = await comfyPage.vueNodes.getNodeIds() + await expectGrowthRenders(comfyPage, interiorNodeId, 'inside the subgraph') + + await comfyPage.subgraph.exitViaBreadcrumb() + await comfyPage.vueNodes.waitForNodes() + await expectGrowthRenders( + comfyPage, + rootNodeId, + 'back at the root graph after leaving the subgraph' + ) + + await comfyPage.workflow.loadWorkflow('default') + await comfyPage.vueNodes.waitForNodes() + const [reloadedNodeId] = await comfyPage.vueNodes.getNodeIds() + await expectGrowthRenders( + comfyPage, + reloadedNodeId, + 'after loading a second workflow' + ) + } +) diff --git a/browser_tests/tests/vueNodes/nodeStates/collapse.spec.ts b/browser_tests/tests/vueNodes/nodeStates/collapse.spec.ts index 0e8f00f9667..afea86163fe 100644 --- a/browser_tests/tests/vueNodes/nodeStates/collapse.spec.ts +++ b/browser_tests/tests/vueNodes/nodeStates/collapse.spec.ts @@ -58,6 +58,42 @@ test.describe('Vue Node Collapse', { tag: '@vue-nodes' }, () => { await expect(vueNode.collapseIcon).not.toHaveClass(/-rotate-90/) }) + test('should keep a resized width across a collapsed save and reload', async ({ + comfyPage + }) => { + test.setTimeout(30000) + + const vueNode = await comfyPage.vueNodes.getFixtureByTitle('KSampler') + await expect(vueNode.root).toBeVisible() + + await vueNode.resizeFromCorner('SE', 120, 0) + await comfyPage.nextFrame() + const resized = await vueNode.boundingBox() + if (!resized) throw new Error('Failed to measure node after resize') + + // Collapse by keybinding: the top-left resize handle overlaps the collapse + // button and intercepts the click. + const beforeCollapse = Date.now() + await vueNode.select() + await comfyPage.keyboard.press('Alt+KeyC') + await expect + .poll(async () => (await vueNode.boundingBox())?.width) + .toBeLessThan(resized.width) + + await comfyPage.workflow.waitForDraftIndexUpdatedSince(beforeCollapse) + await comfyPage.workflow.reloadAndWaitForApp() + + const reloaded = await comfyPage.vueNodes.getFixtureByTitle('KSampler') + await expect(reloaded.root).toBeVisible() + await reloaded.select() + await comfyPage.keyboard.press('Alt+KeyC') + await comfyPage.nextFrame() + + await expect + .poll(async () => (await reloaded.boundingBox())?.width) + .toBeGreaterThan(resized.width - 5) + }) + test('should preserve title when collapsing/expanding', async ({ comfyPage }) => { diff --git a/browser_tests/tests/vueNodes/nodeStates/colors.spec.ts-snapshots/vue-node-custom-colors-dark-all-colors-chromium-linux.png b/browser_tests/tests/vueNodes/nodeStates/colors.spec.ts-snapshots/vue-node-custom-colors-dark-all-colors-chromium-linux.png index 8434c4c0d1f..e22a1a3ca55 100644 Binary files a/browser_tests/tests/vueNodes/nodeStates/colors.spec.ts-snapshots/vue-node-custom-colors-dark-all-colors-chromium-linux.png and b/browser_tests/tests/vueNodes/nodeStates/colors.spec.ts-snapshots/vue-node-custom-colors-dark-all-colors-chromium-linux.png differ diff --git a/browser_tests/tests/vueNodes/nodeStates/colors.spec.ts-snapshots/vue-node-custom-colors-light-all-colors-chromium-linux.png b/browser_tests/tests/vueNodes/nodeStates/colors.spec.ts-snapshots/vue-node-custom-colors-light-all-colors-chromium-linux.png index 6ff40e1e083..32f3eec0ae7 100644 Binary files a/browser_tests/tests/vueNodes/nodeStates/colors.spec.ts-snapshots/vue-node-custom-colors-light-all-colors-chromium-linux.png and b/browser_tests/tests/vueNodes/nodeStates/colors.spec.ts-snapshots/vue-node-custom-colors-light-all-colors-chromium-linux.png differ diff --git a/browser_tests/tests/vueNodes/nodeStates/registration.spec.ts b/browser_tests/tests/vueNodes/nodeStates/registration.spec.ts new file mode 100644 index 00000000000..34cddb73f28 --- /dev/null +++ b/browser_tests/tests/vueNodes/nodeStates/registration.spec.ts @@ -0,0 +1,22 @@ +import { + comfyExpect as expect, + comfyPageFixture as test +} from '@e2e/fixtures/ComfyPage' + +test.describe('Vue Node registration', { tag: '@vue-nodes' }, () => { + test('renders both nodes when a workflow reuses a node id', async ({ + comfyPage + }) => { + await comfyPage.workflow.loadWorkflow('nodes/duplicate_node_ids') + await comfyPage.vueNodes.waitForNodes(2) + + const ids = await comfyPage.vueNodes.getNodeIds() + expect(new Set(ids).size, 'renumbered node keeps a distinct id').toBe(2) + + await comfyPage.vueNodes.selectNodes([ids[0]]) + await comfyPage.page.keyboard.press('Delete') + + await expect(comfyPage.vueNodes.nodes).toHaveCount(1) + await expect(comfyPage.vueNodes.getNodeLocator(ids[1])).toBeVisible() + }) +}) diff --git a/browser_tests/tests/vueNodes/rerouteGeometry.spec.ts b/browser_tests/tests/vueNodes/rerouteGeometry.spec.ts new file mode 100644 index 00000000000..c9c90c068a3 --- /dev/null +++ b/browser_tests/tests/vueNodes/rerouteGeometry.spec.ts @@ -0,0 +1,24 @@ +import { comfyPageFixture as test } from '@e2e/fixtures/ComfyPage' +import { toRerouteId } from '@/types/rerouteId' + +test.describe('Native reroute geometry', { tag: '@vue-nodes' }, () => { + test('survives subgraph navigation', async ({ comfyPage }) => { + await comfyPage.workflow.loadWorkflow( + 'reroute/single-native-reroute-default-workflow' + ) + await comfyPage.canvasOps.expectRootReroutePositions({ + [toRerouteId(1)]: { x: 372.67, y: 415.33 } + }) + + const ksampler = await comfyPage.nodeOps.getNodeRefById('3') + await ksampler.click('title') + const subgraphNode = await ksampler.convertToSubgraph() + + await comfyPage.vueNodes.enterSubgraph(subgraphNode.id) + await comfyPage.subgraph.exitViaBreadcrumb() + + await comfyPage.canvasOps.expectRootReroutePositions({ + [toRerouteId(1)]: { x: 372.67, y: 415.33 } + }) + }) +}) diff --git a/browser_tests/tests/vueNodes/widgets/legacy.spec.ts b/browser_tests/tests/vueNodes/widgets/legacy.spec.ts index edf0e4565f6..257a3449ca0 100644 --- a/browser_tests/tests/vueNodes/widgets/legacy.spec.ts +++ b/browser_tests/tests/vueNodes/widgets/legacy.spec.ts @@ -8,25 +8,32 @@ test('@vue-nodes In App Mode, widget width updates with panel size', async ({ comfyPage, comfyMouse }) => { + let legacyNodeId = toNodeId(10) + await test.step('setup', async () => { - await comfyPage.nodeOps.addNode('DevToolsNodeWithLegacyWidget', undefined, { - x: 0, - y: 0 - }) - await comfyPage.appMode.enterAppModeWithInputs([['10', 'legacy_widget']]) + const legacyNode = await comfyPage.nodeOps.addNode( + 'DevToolsNodeWithLegacyWidget', + undefined, + { + x: 0, + y: 0 + } + ) + legacyNodeId = legacyNode.id + await comfyPage.appMode.enterAppModeWithInputs([ + [String(legacyNodeId), 'legacy_widget'] + ]) }) - const getWidth = () => - comfyPage.page.evaluate( - (nodeId) => graph!.getNodeById(nodeId)!.widgets![0].width ?? 0, - toNodeId(10) - ) + const getWidth = async () => + (await comfyPage.appMode.linearWidgets.locator('canvas').boundingBox()) + ?.width ?? 0 await test.step('Mouse clicks resolve to button regions', async () => { const legacyWidget = comfyPage.appMode.linearWidgets.locator('canvas') const { width, height } = (await legacyWidget.boundingBox())! - const nodeRef = await comfyPage.nodeOps.getNodeRefById(10) + const nodeRef = await comfyPage.nodeOps.getNodeRefById(legacyNodeId) const legacyWidgetRef = await nodeRef.getWidget(0) expect(await legacyWidgetRef.getValue()).toBe(0) await legacyWidget.click({ position: { x: 20, y: height / 2 } }) @@ -36,8 +43,8 @@ test('@vue-nodes In App Mode, widget width updates with panel size', async ({ }) await test.step('Resize to update width', async () => { + await expect.poll(getWidth).toBeGreaterThan(0) const initialWidth = await getWidth() - expect(initialWidth).toBeGreaterThan(0) const gutter = comfyPage.page.getByRole('separator') diff --git a/browser_tests/tests/vueNodes/widgets/widgetReactivity.spec.ts b/browser_tests/tests/vueNodes/widgets/widgetReactivity.spec.ts index e98e6fb97fd..550e071eb7f 100644 --- a/browser_tests/tests/vueNodes/widgets/widgetReactivity.spec.ts +++ b/browser_tests/tests/vueNodes/widgets/widgetReactivity.spec.ts @@ -3,31 +3,43 @@ import { comfyPageFixture as test } from '@e2e/fixtures/ComfyPage' import type { TestGraphAccess } from '@e2e/types/globals' +import { toNodeId } from '@/types/nodeId' test.describe('Vue Widget Reactivity', { tag: '@vue-nodes' }, () => { test('Should display added widgets', async ({ comfyPage }) => { - const loadCheckpointNode = comfyPage.page.locator( - 'css=[data-testid="node-body-4"] > .lg-node-widgets > div' + const nodeId = toNodeId( + await comfyPage.page.evaluate(() => { + const node = window.app!.graph.nodes.find( + (node) => (node.widgets?.length ?? 0) === 1 + ) + if (!node) throw new Error('Node with one widget not found') + return String(node.id) + }) ) - await expect(loadCheckpointNode).toHaveCount(1) - await comfyPage.page.evaluate(() => { - const graph = window.graph as TestGraphAccess - const node = graph._nodes_by_id['4'] + + const widgets = comfyPage.vueNodes + .getNodeLocator(nodeId) + .locator('.lg-node-widget') + + await expect(widgets).toHaveCount(1) + await comfyPage.page.evaluate((nodeId) => { + const node = window.app!.graph.getNodeById(nodeId) + if (!node) throw new Error(`Node ${nodeId} not found`) node.addWidget('text', 'extra_widget_a', '', () => {}) - }) - await expect(loadCheckpointNode).toHaveCount(2) - await comfyPage.page.evaluate(() => { - const graph = window.graph as TestGraphAccess - const node = graph._nodes_by_id['4'] + }, nodeId) + await expect(widgets).toHaveCount(2) + await comfyPage.page.evaluate((nodeId) => { + const node = window.app!.graph.getNodeById(nodeId) + if (!node) throw new Error(`Node ${nodeId} not found`) node.addWidget('text', 'extra_widget_b', '', () => {}) - }) - await expect(loadCheckpointNode).toHaveCount(3) - await comfyPage.page.evaluate(() => { - const graph = window.graph as TestGraphAccess - const node = graph._nodes_by_id['4'] + }, nodeId) + await expect(widgets).toHaveCount(3) + await comfyPage.page.evaluate((nodeId) => { + const node = window.app!.graph.getNodeById(nodeId) + if (!node) throw new Error(`Node ${nodeId} not found`) node.addWidget('text', 'extra_widget_c', '', () => {}) - }) - await expect(loadCheckpointNode).toHaveCount(4) + }, nodeId) + await expect(widgets).toHaveCount(4) }) test('Should hide removed widgets', async ({ comfyPage }) => { diff --git a/browser_tests/tests/workflowPersistence.spec.ts b/browser_tests/tests/workflowPersistence.spec.ts index bd5b44b7bf7..21f54c91cdf 100644 --- a/browser_tests/tests/workflowPersistence.spec.ts +++ b/browser_tests/tests/workflowPersistence.spec.ts @@ -252,10 +252,9 @@ test.describe('Workflow Persistence', () => { await expect.poll(() => comfyPage.nodeOps.getNodeCount()).toBe(1) await expect - .poll(async () => { - const nodes = await comfyPage.nodeOps.getNodes() - return nodes[0]?.type - }) + .poll(() => + comfyPage.page.evaluate(() => window.app!.graph.nodes[0]?.type) + ) .toBe('KSampler') }) diff --git a/docs/adr/0003-crdt-based-layout-system.md b/docs/adr/0003-crdt-based-layout-system.md index 5aca48f4f16..64dfbce5bd4 100644 --- a/docs/adr/0003-crdt-based-layout-system.md +++ b/docs/adr/0003-crdt-based-layout-system.md @@ -118,7 +118,7 @@ This combination provides both architectural and technical benefits: - **Eliminates Polling**: Observer pattern removes O(n) graph traversals, improving performance - **System Modularity**: Independent systems can be developed, tested, and optimized separately - **Renderer Flexibility**: Easy to add WebGL, DOM accessibility, or hybrid rendering systems -- **Rich Interactions**: Command pattern enables robust undo/redo, macros, and interaction history +- **Rich Interactions**: Command pattern enables robust undo/redo and macros - **Collaboration-Ready**: CRDT foundation enables real-time multi-user editing - **Conflict Resolution**: Eliminates position "snap-back" behavior between competing systems - **Better Developer Experience**: Clear separation of concerns and predictable data flow patterns @@ -138,6 +138,78 @@ This combination provides both architectural and technical benefits: - Implement operation history pruning for long-running sessions - Phase implementation to validate approach before full migration +### Amendment (2026-07-30) + +The Yjs operation log is deleted. Nothing ever read it: undo/redo is +snapshot-based through `changeTracker`, and the two query methods +(`getOperationsSince`, `getOperationsByActor`) had no callers outside tests. +It was pure write amplification on every mutation, so the "operation history +storage" memory cost and the history-pruning mitigation above no longer +apply. What is lost is a timestamped, per-actor record: the interaction +history promised above is struck, and the Yjs document runs with the default +`gc: true`, so it is a mergeable state record rather than a replayable one. +Transmission stays a capability of the document rather than of the store: +`applyUpdate` / `getStateAsUpdate` were removed as callerless (see +[Removed CRDT sync seam](../architecture/ecs-migration-plan.md)) and are a few +lines against `this.ydoc` to reinstate. `LayoutOperation` is still the +serializable command shape every mutation goes through. Producers supply the +operation source; the store stamps its session actor at submission. + +Entity geometry registers and unregisters with the entity that owns it +(`LGraph.add` / `LGraph.remove`) rather than being seeded per graph on renderer +entry. All three entity types key by `makeScopedLayoutKey(rootGraphId, id)`, so +a root graph's teardown is one `clearGraph`; graphs sharing that bucket drop +their entries individually through `detachGraphLayouts`. + +### Amendment (2026-08-04): the replicated document holds intent, not measurement + +`NodeLayout.size` conflates two values with different natures. **Requested** +size is what a user, a workflow file, or `computeSize()` asked for. **Rendered** +size is what the DOM produced, which for height is `max(requested, natural +content)` because the node container is `min-h-(--node-height)`. A shared +`ResizeObserver` in `useVueNodeResizeTracking.ts` measures the second and writes +it into the first through `batchUpdateNodeBounds`. + +A measurement is not a command. Replayed on a peer with different fonts, locale, +browser, or installed custom-node versions it produces a different — and equally +correct — answer, so it is neither deterministic nor meaningfully undoable. This +is the contract in ADR 0008 that every mutation is supposed to satisfy, and the +observer's write is the one place in the layout system that structurally cannot. + +Three consequences follow, and they are the reason to act rather than to +document and move on: + +- `serialize()` reads `this.size`, which reads through to the store. Saved + workflows therefore carry a DOM measurement and are not byte-portable across + machines. Saving while a node is collapsed persists the header box as the + node's size; on reload `min-h` heals the height and nothing heals the width. +- Under `min-h` semantics with last-writer-wins, a replicated height converges + to the largest natural height across every connected peer's rendering + environment. Node geometry becomes a function of who has the document open. +- Collapse is not stored. It is inferred from a box shrinking to its header, + which is why the store holds rendered rather than requested geometry at all. + In Vue mode the collapsed width this produces is read by nothing: + `_collapsed_width` is assigned only in the branch `vueNodesMode` skips + (`LGraphNode.ts`), so every reader falls through to `NODE_COLLAPSED_WIDTH`. + +**Decision.** The Yjs document holds requested geometry, written only by named +commands. Measured geometry belongs to the local, view-scoped tier that +`slotLayouts` already occupies — a plain map, not replicated, dropped by +`clearViewGeometry`. Slot geometry is measured from the DOM at higher frequency +than node height and has never been considered a violation, because it lands in +a tier that nothing replicates and nothing writes back into the DOM. Recording a +measurement stays an explicit, named mutation rather than an ambient observer +write. Collapse becomes stored data. + +**This does not forbid measurement.** Content-driven height is real: widget +hydration, media loading, badges, slot changes, and third-party DOM inserted by +reference through `WidgetDOM.vue`. Making layout strictly one-directional would +mean modelling in TypeScript what CSS already computes, enforced as a height +contract across 40+ repositories we do not control, and paid for in clipped +content in someone else's node. The defect was never that a measurement exists. +It was that a view-derived value was promoted into replicated entity state by a +mutation with no name. + ## Notes This centralized state + CRDT architecture follows patterns from modern collaborative applications: diff --git a/docs/adr/0008-entity-component-system.md b/docs/adr/0008-entity-component-system.md index cecfe85bab7..d9c8a7501ae 100644 --- a/docs/adr/0008-entity-component-system.md +++ b/docs/adr/0008-entity-component-system.md @@ -21,6 +21,37 @@ text below says "the World," read "the set of dedicated stores"; where it shows `world.getComponent(id, Component)`, read the matching store getter (for example `widgetValueStore.getWidget(widgetId)`). +### Amendment (2026-07-05, PRs 13436/13449) + +Two stores joined the dedicated-store set: `linkStore` (link topology, +keyed by target input slot in root-graph-scoped buckets — see +[Link Topology Store](../architecture/link-topology-store.md)) and +`rerouteStore` (reroute chain state with link membership derived from +the links' `parentId` chains — see +[Reroute Chain Store](../architecture/reroute-chain-store.md)). Both +follow the proxy-returning registration pattern established by +`BaseWidget`/`widgetValueStore`: the store bucket is a `reactive(Map)`, +registration inserts the class's state object by reference and the class +adopts the reactive proxy read back from the bucket, so class field +writes are tracked without an action chokepoint. The `layoutStore` link +connectivity mirror and the `slot._floatingLinks` sets were deleted in +the same work; the layout store now holds geometry only. + +### Amendment (2026-07-15, PR 13458) + +Node badge rows remain plain `BadgeData`, but they are derived presentation +data rather than authoritative entity state. Materializing them in a dedicated +store duplicated settings, node definitions, palette, pricing, widget, link, +and graph state. It also required registration, teardown, and cache lifecycle +logic. + +Instead, `src/systems/badgeSystem.ts` keeps one lazy computed projection per +node instance. Renderers query that projection through a temporary app-layer +registration seam, which keeps the litegraph layer independent from the badge +system's pricing dependencies. Badge rows remain transient: they are +not serialized, transmitted through CRDT, or included in undo history. See +[Node Badge Store](../architecture/node-badge-store.md) for the design history. + ## Context The litegraph layer is built on deeply coupled OOP classes (`LGraphNode`, `LLink`, `Subgraph`, `BaseWidget`, `Reroute`, `LGraphGroup`, `SlotBase`). Each entity directly references its container and children — nodes hold widget arrays, widgets back-reference their node, links reference origin/target node IDs, subgraphs extend the graph class, and so on. @@ -115,6 +146,15 @@ Components are plain data objects — no methods, no back-references to parent e | `LinkVisual` | `color`, `path`, `_pos` (center point) | | `LinkState` | `_dragging`, `data` | +> **Amended (2026-07-05):** `LinkEndpoints` shipped as +> `LinkTopology { id, originNodeId, originSlot, targetNodeId, +targetSlot, type, parentId? }` in a dedicated `linkStore`, keyed by +> **target input slot** (not link id) in root-graph-scoped buckets, with +> floating and subgraph-output links in an unkeyed side set. `LLink` +> reads through the store's reactive proxy (`_state`). See +> [Link Topology Store](../architecture/link-topology-store.md). +> `LinkVisual` and `LinkState` remain unextracted. + #### Subgraph (Node Components) A node carrying a subgraph gains these additional components. Subgraphs are not a separate entity kind — see [Subgraph Boundaries](../architecture/subgraph-boundaries-and-promotion.md). @@ -140,6 +180,13 @@ A node carrying a subgraph gains these additional components. Subgraphs are not | `SlotConnection` | `link` (input) or `links[]` (output), `widget` locator | | `SlotVisual` | `pos`, `boundingRect`, `color_on`, `color_off`, `shape` | +> **Amended (2026-07-05):** the input side of `SlotConnection` is +> subsumed by the `linkStore` key — the input-slot→link mapping _is_ the +> store's primary index (`isInputSlotConnected` / `getInputSlotLink`). +> The `slot._floatingLinks` sets were deleted; floating-link attachment +> is derived from the links' own endpoints (`slotFloatingLinks`). The +> `input.link` / `output.links` class mirrors remain un-migrated. + #### Reroute | Component | Data (from `Reroute`) | @@ -148,6 +195,13 @@ A node carrying a subgraph gains these additional components. Subgraphs are not | `RerouteLinks` | `parentId`, input/output link IDs | | `RerouteVisual` | `color`, badge config | +> **Amended (2026-07-04):** `RerouteLinks` was superseded during design +> review. The stored component is chain state only — +> `RerouteChain { parentId, floating? }` — and link membership +> (`linkIds` / `floatingLinkIds`) is derived from the links' `parentId` +> chains rather than stored. See +> [Reroute Chain Store](../architecture/reroute-chain-store.md). + #### Group | Component | Data (from `LGraphGroup`) | @@ -199,6 +253,15 @@ Systems are pure functions that query the relevant store(s) for entities with sp - **LayoutSystem** — queries `Position` + `Dimensions` + structural components for auto-layout - **SelectionSystem** — queries `Position` for point entities and `Position` + `Dimensions` for box hit-testing +Until a `RenderSystem` owns render orchestration, node badges use a registered +query function so the legacy canvas can read the app-owned projection without +importing the badge system. Once the `RenderSystem` can query entity data and +compose renderer input, badge lookup should move there. That migration should +delete the registration seam and remove badge projection access from +`LGraphNode`; the render system will query `BadgeData` and pass plain draw data +to the canvas. This keeps badge derivation app-owned without materializing its +output as a second source of truth. + System design is deferred to a future ADR. For detailed before/after walkthroughs of how lifecycle operations (node removal, link creation, subgraph nesting, etc.) transform under ECS, see [ECS Lifecycle Scenarios](../architecture/ecs-lifecycle-scenarios.md). ### Migration Strategy @@ -217,7 +280,7 @@ For the phased migration roadmap with shipping milestones, see [ECS Migration Pl - **Commands** (ADR 0003) describe mutation intent — serializable objects that can be logged, replayed, sent over a wire, or undone. - **Systems** (ADR 0008) are command handlers — they validate and execute mutations against the relevant stores. -- **The dedicated stores** (ADR 0008) hold component data and expose mutation APIs (for example `useLayoutMutations()`, `widgetValueStore.setValue`); each owns its own transaction boundary. +- **The dedicated stores** (ADR 0008) hold component data and expose mutation APIs (for example `useLayoutMutations(source)`, `widgetValueStore.setValue`); each owns its own transaction boundary. A store's imperative mutators are internal implementation. External callers submit commands; each mutating store wraps its writes in a transaction (the Y.js-backed `layoutStore` already does this). This follows Redux: internal mutation is imperative, while the public API is action-based. @@ -271,6 +334,9 @@ Companion architecture documents that expand on the design in this ADR: | [ECS Migration Plan](../architecture/ecs-migration-plan.md) | Phased migration roadmap with shipping milestones and go/no-go criteria | | [ECS Lifecycle Scenarios](../architecture/ecs-lifecycle-scenarios.md) | Before/after walkthroughs of lifecycle operations (node removal, link creation, etc.) | | [Subgraph Boundaries and Widget Promotion](../architecture/subgraph-boundaries-and-promotion.md) | Design rationale for modeling subgraphs as node components, not separate entities | +| [Link Topology Store](../architecture/link-topology-store.md) | Design record for the `linkStore` — target-input-slot keying, root-scoped buckets, registration protocol | +| [Reroute Chain Store](../architecture/reroute-chain-store.md) | Design record for the `rerouteStore` — chain state, derived link membership, load-time id dedup | +| [Domain Glossary](../architecture/domain-glossary.md) | Canonical vocabulary for links, reroutes, chains, and membership | | [ADR 0009: Subgraph promoted widgets](0009-subgraph-promoted-widgets-use-linked-inputs.md) | Follow-up decision for promoted widget identity and value ownership at subgraph boundaries | | [Appendix: Critical Analysis](../architecture/appendix-critical-analysis.md) | Independent verification of the accuracy of the architecture documents | | [Appendix: ECS Pattern Survey](../architecture/appendix-ecs-pattern-survey.md) | Survey of bitECS, miniplex, koota, ECSY, Thyseus, and Bevy — patterns adopted, departed, when to revisit | diff --git a/docs/architecture/appendix-ecs-pattern-survey.md b/docs/architecture/appendix-ecs-pattern-survey.md index 5a3efb75312..2e561a4c572 100644 --- a/docs/architecture/appendix-ecs-pattern-survey.md +++ b/docs/architecture/appendix-ecs-pattern-survey.md @@ -149,7 +149,7 @@ deferred mutations against a command buffer; the substrate applies them at defined sync points in the schedule. This is the same shape Bevy uses and is the closest direct external analog to the per-store mutation layer [ADR 0003](../adr/0003-crdt-based-layout-system.md) describes for this -codebase (realized as store mutation APIs such as `useLayoutMutations()`). +codebase (realized as store mutation APIs such as `useLayoutMutations(source)`). We deliberately match the **shape** of this pattern: external callers submit commands; only the executor calls the World's imperative diff --git a/docs/architecture/domain-glossary.md b/docs/architecture/domain-glossary.md new file mode 100644 index 00000000000..3e144f2e3d1 --- /dev/null +++ b/docs/architecture/domain-glossary.md @@ -0,0 +1,50 @@ +# Domain Glossary + +Canonical vocabulary for the graph domain. Terms are added as they are +resolved during design work; keep entries implementation-free. Intended +to grow into a proper reference document. + +Design records that rely on this vocabulary: +[Link Topology Store](link-topology-store.md), +[Reroute Chain Store](reroute-chain-store.md), +[Node Badge Store](node-badge-store.md), +[ADR 0008](../adr/0008-entity-component-system.md). + +## Badges + +- **Badge** — a small visual annotation rendered on a node: its numeric + id, lifecycle state, source pack, execution price, or an + extension-provided marker. Badges are presentation state; they never + affect execution and are never persisted with the workflow. +- **Badge kind** — the category a badge belongs to: **core** (identity / + lifecycle / source, projected from the node's definition and user + settings), **credits** (price of executing an API node, including + aggregated prices of nodes inside a subgraph), or **extension** + (provided by third-party code). +- **Badge source** — the domain state a badge's content is computed + from (settings, node definition, palette, pricing, widget values, + input connectivity). A badge is always a projection of its sources; + it is never authored directly by a user. + +## Links & Reroutes + +- **Link** — a directed data connection from one node's output slot to + another node's input slot. At most one live link targets a given input + slot. +- **Floating link** — a link with exactly one attached endpoint, kept + alive so a reroute chain survives disconnection. The unattached end is + unassigned. +- **Reroute** — a visual waypoint that a link's rendered path travels + through. Purely organisational; never affects data flow. A reroute's + identity is unique within a workflow, subgraphs included. +- **Reroute chain** — the ordered sequence of reroutes a link passes + through, from the node output toward the input. Each reroute names its + upstream neighbour via _parent_; the link names the chain's most + downstream reroute (the **terminal reroute**). +- **Link membership (of a reroute)** — the set of links whose chains pass + through that reroute. Membership is _defined by_ the chains: a link is a + member of exactly the reroutes on the chain walked from its terminal + reroute upstream. It is never authored independently of the chain. +- **Floating slot marker** — the annotation on the last reroute of a + floating chain recording which side (input or output) the chain still + faces. diff --git a/docs/architecture/ecs-lifecycle-scenarios.md b/docs/architecture/ecs-lifecycle-scenarios.md index 51d413480a6..c9987b6ea6a 100644 --- a/docs/architecture/ecs-lifecycle-scenarios.md +++ b/docs/architecture/ecs-lifecycle-scenarios.md @@ -2,7 +2,7 @@ This document walks through the major entity lifecycle operations — showing the current imperative implementation and how each transforms under the ECS architecture from [ADR 0008](../adr/0008-entity-component-system.md). -ECS principles are realized across a set of dedicated Pinia stores keyed by string IDs (shipped in PR 12617): `widgetValueStore` (keyed by `WidgetId` = `graphId:nodeId:name`, see `src/types/widgetId.ts`), `layoutStore` (mutated via `useLayoutMutations()`), `nodeOutputStore`, `domWidgetStore`, `subgraphNavigationStore`, and `previewExposureStore`. Components live as plain-data entries in these stores; systems read and mutate them through store getters and command-style mutations. +ECS principles are realized across a set of dedicated Pinia stores keyed by string IDs (shipped in PR 12617): `widgetValueStore` (keyed by `WidgetId` = `graphId:nodeId:name`, see `src/types/widgetId.ts`), `layoutStore` (mutated via `useLayoutMutations(source)`), `nodeOutputStore`, `domWidgetStore`, `subgraphNavigationStore`, and `previewExposureStore`. Link topology and reroute chain state shipped later into `linkStore` (PR 13436, keyed by target input slot in root-graph-scoped buckets — see [link-topology-store.md](link-topology-store.md)) and `rerouteStore` (PR 13449, membership derived from the links' `parentId` chains — see [reroute-chain-store.md](reroute-chain-store.md)); `layoutStore` keeps link/reroute geometry only. Components live as plain-data entries in these stores; systems read and mutate them through store getters and command-style mutations. Each scenario follows the same structure: **Current Flow** (what happens today), **ECS Flow** (the store-backed target), and a **Key Differences** table. @@ -66,6 +66,7 @@ sequenceDiagram participant Caller participant CS as ConnectivitySystem participant LM as useLayoutMutations() + participant LKS as linkStore participant LS as layoutStore participant WVS as widgetValueStore participant NOS as nodeOutputStore @@ -73,12 +74,14 @@ sequenceDiagram Caller->>CS: removeNode(nodeId) - CS->>LS: read node links (incoming + outgoing) - LS-->>CS: linkIds + CS->>LKS: read node links (incoming + outgoing) + LKS-->>CS: link topologies - loop each linkId - CS->>LM: deleteLink(linkId) - Note over LM,LS: removes link entry +
updates both slot endpoints + loop each link + CS->>LKS: unregister link topology + Note over CS,LKS: via the LGraph._removeLink chokepoint —
map delete + store unregistration + CS->>LS: drop link geometry + Note over LKS,LS: linkStore owns topology;
layoutStore only drops geometry end loop each widget on node @@ -93,15 +96,15 @@ sequenceDiagram ### Key Differences -| Aspect | Current | ECS | -| ------------------- | ------------------------------------------------ | ----------------------------------------------------------------------------------------------- | -| Lines of code | ~107 in one method | ~30 in system function | -| Entity types known | Graph knows about all 6+ types | ConnectivitySystem coordinates layoutStore + widget/output stores | -| Cleanup | Manual per-slot, per-link, per-reroute | `deleteLink()`/`deleteNode()` mutations per layout entry | -| Canvas notification | `setDirtyCanvas()` called explicitly | Vue reactivity: components re-render when store entries change | -| Store cleanup | WidgetValueStore/LayoutStore NOT cleaned up | Coordinated: `deleteWidget`, `deleteLink`/`deleteNode`, `removeNodeOutputs`, `unregisterWidget` | -| Undo/redo | `beforeChange()`/`afterChange()` manually placed | Layout mutations are command records, replayable and undoable | -| Testability | Needs full LGraph + LGraphCanvas | Needs only the relevant stores + ConnectivitySystem | +| Aspect | Current | ECS | +| ------------------- | ----------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------- | +| Lines of code | ~107 in one method | ~30 in system function | +| Entity types known | Graph knows about all 6+ types | ConnectivitySystem coordinates linkStore + layout/widget/output stores | +| Cleanup | Manual per-slot, per-link, per-reroute | linkStore unregistration per link (via `_removeLink`) + geometry drop per layout entry | +| Canvas notification | `setDirtyCanvas()` called explicitly | Vue reactivity: components re-render when store entries change | +| Store cleanup | WidgetValueStore not cleaned up; link geometry still removed from LayoutStore | Coordinated: `deleteWidget`, linkStore unregister + `deleteNode`, `removeNodeOutputs`, `unregisterWidget` | +| Undo/redo | `beforeChange()`/`afterChange()` manually placed | Layout mutations are command records, replayable and undoable | +| Testability | Needs full LGraph + LGraphCanvas | Needs only the relevant stores + ConnectivitySystem | ## 2. Serialization @@ -223,7 +226,7 @@ sequenceDiagram end opt has subgraph definitions - G->>G: deduplicateSubgraphNodeIds() + G->>G: deduplicateSubgraphNodeIds() + deduplicateSubgraphRerouteIds() loop each subgraph (topological order) G->>G: createSubgraph(data) end @@ -250,7 +253,7 @@ sequenceDiagram end G->>G: add floating links - G->>G: validate reroutes + G->>G: prune reroutes with derived totalLinks === 0 G->>G: _removeDuplicateLinks() loop each serialized group @@ -262,6 +265,8 @@ sequenceDiagram Problems: two-phase creation is necessary because nodes need to reference each other's links during configure. Widget value restoration happens deep inside `node.configure()`. Store population is a side effect of configuration. Subgraph creation requires topological sorting to handle nested subgraphs. +Note on load-time id hygiene: root `configure()` deduplicates **node ids** and **reroute ids** across sibling subgraph definitions before configuring them (`deduplicateSubgraphNodeIds` / `deduplicateSubgraphRerouteIds`), because both share root-graph-scoped store buckets. Link-id dedup is deliberately absent — the linkStore key is the target input slot, not the link id, so duplicate link ids across definitions cannot collide. Orphaned reroutes are pruned by the derived `totalLinks === 0` check; the old `validateLinks` set-repair is gone (membership is derived, so there is no stored set to drift). + ### ECS Flow ```mermaid @@ -532,7 +537,7 @@ sequenceDiagram participant G as LGraph participant L as LLink participant R as Reroute - participant LS as LayoutStore + participant LKS as linkStore Caller->>N1: connectSlots(output, targetNode, input) @@ -545,24 +550,24 @@ sequenceDiagram end N1->>L: new LLink(++lastLinkId, type, ...) - N1->>G: _links.set(link.id, link) - N1->>LS: layoutMutations.createLink() + N1->>G: graph._addLink(link) + G->>LKS: register topology (keyed by target input slot) + Note over G,LKS: chokepoint: _links.set + linkStore registration N1->>N1: output.links.push(link.id) N1->>N2: input.link = link.id - loop each reroute in path - N1->>R: reroute.linkIds.add(link.id) - end + N1->>R: anchorRerouteChain(graph, link) + Note over N1,R: clears floating markers on the chain —
membership is derived from link.parentId,
no per-reroute linkIds writes - N1->>G: _version++ + N1->>G: incrementVersion() N1->>N1: onConnectionsChange?(OUTPUT, ...) N1->>N2: onConnectionsChange?(INPUT, ...) N1->>G: setDirtyCanvas() N1->>G: afterChange() ``` -Problems: the source node orchestrates everything — it reaches into the graph's link map, the target node's slot, the layout store, the reroute chain, and the version counter. 19 steps in one method. +Problems: the source node orchestrates everything — it reaches into the graph's link map (via the `_addLink` chokepoint), the target node's slot, and the version counter. Reroute membership no longer needs writes (derived via rerouteStore), but the slot mirrors (`output.links`, `input.link`) are still mutated by hand. ### ECS Flow @@ -570,29 +575,28 @@ Problems: the source node orchestrates everything — it reaches into the graph' sequenceDiagram participant Caller participant CS as ConnectivitySystem - participant LS as layoutStore - participant LM as useLayoutMutations() + participant LKS as linkStore Caller->>CS: connect(outputSlot, inputSlot) - CS->>LS: read input slot link + CS->>LKS: getInputSlotLink(graphId, targetNodeId, targetSlot) opt already connected - CS->>LM: deleteLink(existingLinkId) + CS->>LKS: unregister existing topology end - CS->>LM: createLink(linkId, {
originNodeId, originSlotIndex,
targetNodeId, targetSlotIndex, type
}) - Note over LM,LS: createLink updates both slot endpoints
and emits a command record + CS->>LKS: register LinkTopology {
id, originNodeId, originSlot,
targetNodeId, targetSlot, type
} + Note over CS,LKS: the target-slot key IS the input-side
slot connection — no separate endpoint update.
Reroute membership derives from parentId;
rerouteStore needs no write ``` ### Key Differences -| Aspect | Current | ECS | -| ---------------- | ------------------------------------------------------------ | ------------------------------------------------------------- | -| Orchestrator | Source node (reaches into graph, target, reroutes) | ConnectivitySystem (reads layoutStore) | -| Side effects | `_version++`, `setDirtyCanvas()`, `afterChange()`, callbacks | `createLink()` command — endpoints + change tracking included | -| Reroute handling | Manual: iterate chain, add linkId to each | Reroute entries updated via layout mutations | -| Slot mutation | Direct: `output.links.push()`, `input.link = id` | `createLink(linkId, ...)` updates both endpoints | -| Validation | `onConnectInput`/`onConnectOutput` callbacks on nodes | Validation system or guard function | +| Aspect | Current | ECS | +| ---------------- | ------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------- | +| Orchestrator | Source node (reaches into graph, target slots) | ConnectivitySystem (reads linkStore) | +| Side effects | `incrementVersion()`, `setDirtyCanvas()`, `afterChange()`, callbacks | topology registration — endpoints + change tracking included | +| Reroute handling | None needed — membership derived from `parentId` chains (rerouteStore); `anchorRerouteChain` only clears floating markers | Same — derived membership is already the target shape | +| Slot mutation | Direct: `output.links.push()`, `input.link = id` | Input side subsumed by the linkStore key; output side pending SlotConnection extraction | +| Validation | `onConnectInput`/`onConnectOutput` callbacks on nodes | Validation system or guard function | ## 7. Copy / Paste diff --git a/docs/architecture/ecs-migration-plan.md b/docs/architecture/ecs-migration-plan.md index 4488e3fd0ed..09bb8c239e3 100644 --- a/docs/architecture/ecs-migration-plan.md +++ b/docs/architecture/ecs-migration-plan.md @@ -12,7 +12,8 @@ For verified accuracy of these documents, see > **Target end-state (revised):** N dedicated Pinia stores keyed by composite > string IDs, one store per concern (widget values, DOM widgets, layout, node -> outputs, subgraph navigation, preview exposure). The earlier "single unified +> outputs, subgraph navigation, preview exposure, link topology, reroute +> chains). The earlier "single unified > World with branded numeric entity IDs and `getComponent`/`setComponent`" model > was rejected. PR 12617 shipped the first stores against composite > `graphId:nodeId:name` string keys (`WidgetId`). Phases below are reframed @@ -73,7 +74,7 @@ Five factual errors verified during code review (see ## Phase 1: Types and Dedicated Stores Introduces the ID type vocabulary and the dedicated stores. Phase 1 end-state is -N dedicated Pinia stores, each keyed by a composite string ID, coexisting with +N dedicated Pinia stores, each keyed by its own entity ID, coexisting with legacy class instances. ### 1a. Branded string ID types ✅ Shipped (PR 12617) @@ -108,19 +109,44 @@ endpoints). ### 1c. Dedicated stores Phase 1 end-state is a set of dedicated Pinia stores, one per concern, each -keyed by its own composite string ID. Each store owns its data and exposes a -narrow accessor surface. There is no single container that fronts all entities. +keyed by its own entity ID — a composite string where the key has to carry the +graph relationship, a bare ID inside root-graph-scoped buckets where the bucket +already supplies it. Each store owns its data and exposes a narrow accessor +surface. There is no single container that fronts all entities. Shipped stores: -| Store | File | -| ------------------------- | ----------------------------------------------- | -| `widgetValueStore` | `src/stores/widgetValueStore.ts` | -| `domWidgetStore` | `src/stores/domWidgetStore.ts` | -| `layoutStore` | `src/renderer/core/layout/store/layoutStore.ts` | -| `nodeOutputStore` | `src/stores/nodeOutputStore.ts` | -| `subgraphNavigationStore` | `src/stores/subgraphNavigationStore.ts` | -| `previewExposureStore` | `src/stores/previewExposureStore.ts` | +| Store | File | +| -------------------------- | ----------------------------------------------- | +| `widgetValueStore` | `src/stores/widgetValueStore.ts` | +| `domWidgetStore` | `src/stores/domWidgetStore.ts` | +| `layoutStore` | `src/renderer/core/layout/store/layoutStore.ts` | +| `nodeOutputStore` | `src/stores/nodeOutputStore.ts` | +| `subgraphNavigationStore` | `src/stores/subgraphNavigationStore.ts` | +| `previewExposureStore` | `src/stores/previewExposureStore.ts` | +| `linkStore` ✅ PR 13436 | `src/stores/linkStore.ts` | +| `rerouteStore` ✅ PR 13449 | `src/stores/rerouteStore.ts` | +| `nodeDataStore` ✅ | `src/stores/nodeDataStore.ts` | + +`nodeBadgeStore` was shipped in PR 13458 and then deleted: badge rows are +cheaper to derive on read than to store, so `src/systems/badgeSystem.ts` +computes them from the stores that already own the inputs. No badge store +exists. See [Node Badge Store](node-badge-store.md) for the reversal. + +`linkStore` holds `LinkTopology` records (`src/types/linkTopology.ts`) in +root-graph-scoped buckets. Link identity is root-wide; input and output query +indexes use owner-qualified slot keys +(`` `${owningGraphId}:${nodeId}:${slot}` ``). Subgraphs share their root's +identity bucket while retaining owner-local queries and teardown. Floating +links remain in the root-wide identity map but are omitted from slot indexes. +Entity store registration is idempotent only when the existing entity has the +same owner and raw object identity. The stores perform every collision check at +the registration mutation boundary. +`rerouteStore` holds `RerouteChain` records keyed by `RerouteId` in +root-graph-scoped buckets; link membership is not stored but derived from the +links' `parentId` chains. +Design records: [Link Topology Store](link-topology-store.md), +[Reroute Chain Store](reroute-chain-store.md). `widgetValueStore` exposes `registerWidget`, `getWidget`, `setValue`, `deleteWidget`, `getNodeWidgets`, and `clearGraph`, all `WidgetId`-native. There @@ -152,7 +178,7 @@ position data for nodes, links, and reroutes into Y.js CRDTs and is the source o truth for layout. **Approach:** New code reads position via `layoutStore` queries (and -`useLayoutMutations()` for writes); legacy code continues to read `node.pos` +`useLayoutMutations(source)` for writes); legacy code continues to read `node.pos` directly during the transition. No second copy of position data is introduced — `layoutStore` stays authoritative. @@ -179,20 +205,140 @@ host-boundary identity (`host node locator + SubgraphInput.name`). Interior source node/widget identity is preserved only as migration and diagnostic metadata. -### 2c. Node metadata stores - -Populate node-metadata records (node type, visual, properties, execution) by -reading from `LGraphNode` instances. These are simple property copies into the -relevant store. - -**Approach:** When a node is added to the graph (`LGraph.add()`), the store -records its metadata. When a node is removed, the store drops it. The -`incrementVersion()` seam from Phase 0a is a candidate hook point for re-sync -when changed. - -**Risk:** Medium. Must handle the full node lifecycle (add, configure, remove) -without breaking existing behavior. Stores mirror the classes during the -transition, which limits blast radius. +### 2c. Node shell state ✅ Shipped + +Node shell state (`title`, `type`, `mode`, `flags`, colours, `shape`, +`resizable`, `showAdvanced`) lives in `nodeDataStore` as one plain `NodeState` +per node. **No copy is made.** `LGraphNode` constructs its `_state` and adopts +the store's reactive proxy at `LGraph.add`; the class fields are accessors over +that proxy, so class, store, and renderer read the same object. The +`incrementVersion()` re-sync hook this phase originally anticipated is +unnecessary — there is nothing to re-sync. + +Registration chokepoints are `LGraph.add` / `LGraph.remove`, with +identity-checked vacate (`toRaw` compare) so only the registered state can free +its key. Design record: [Node Data Store](node-data-store.md). + +**Risk:** taken. Shell-state fields moved from own enumerable data properties to +prototype accessors, so `Object.keys(node)` / `{ ...node }` no longer carry them, +and `type` is read-only. See node-data-store.md Decision 7 for the extension +migration map. + +### 2d. Renderer node lifecycle ✅ Shipped + +`useGraphNodeManager` is **deleted**. Its four responsibilities were resolved +rather than relocated: + +| Responsibility | Resolution | +| ------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------- | +| `VueNodeData` mirror + `node:property:changed` handlers | deleted; the renderer drills the `NodeState` proxy from `nodeDataStore` | +| `getNode()` / `nodeRefs` map | deleted; pinned state is read off the `NodeState` the renderer already holds, live-node lookups go to `graph.getNodeById` | +| `shallowReactive` graft onto `inputs` / `outputs` / `widgets` | deleted; see 2e | +| `layoutStore` seeding on add/remove | moved to `LGraph.add` / `LGraph.remove`, where the entity's geometry registers and unregisters with the entity itself | + +Two consequences worth recording: + +- The **`configuringGraph` deferral is gone.** `LGraph.add` registers the layout + entry with whatever geometry the node has; the `pos`/`size` setters already + write through to `layoutStore`, so `configure()` updates the entry as the real + values land. No `onAfterGraphConfigured` chaining, no `window.app` read. +- The **`onNodeAdded` replay loop is gone.** It re-fired `onNodeAdded` for every + pre-existing node on each graph switch, which leaked spurious node-added + notifications to unrelated subscribers (`useErrorClearingHooks` still carries + a guard written for exactly that). Geometry registers at attach and + unregisters at detach instead, so no bootstrap pass re-seeds a graph on entry. + +`useVueNodeLifecycle` is gone. `GraphCanvas` owns the Layout↔LiteGraph sync +lifecycle and no longer patches `onNodeAdded` — see 2g. + +### 2e. Slot reactivity ✅ Shipped + +Slot arrays and slot objects are reactive from construction, so the renderer +needs no reprojection pass: + +- `LGraphNode.inputs` / `.outputs` are accessors over `shallowReactive` arrays + (`_inputs` / `_outputs`, lazily created). Assignment replaces contents in + place, so the array identity the renderer subscribed to survives + `configure()`, `clone()`, and the several call sites that do + `node.inputs = node.inputs.filter(…)`. +- `NodeSlot`'s constructor returns `shallowReactive(this)`, making every + reference to a slot the tracked one. **Shallow is load-bearing:** nested values + (`boundingRect`, `_widget`, `pos`) stay raw, so identity comparisons like + `input._widget === widget` and the `WeakMap` slot-index cache in + `NodeInputSlot` keep working. A deep `reactive()` would break both. + +This deleted the `node:slot-label:changed` → `node.inputs = [...node.inputs]` +reprojection. The trigger itself stays (`useResolvedSelectedInputs` listens for +it); only the renderer's array-identity churn is gone. Renames now propagate +because `slot.label = …` is a tracked write. + +**Open item:** every slot property read in the canvas draw path now goes through +a proxy get trap. Benchmark against the Phase 4 "Render hot-path performance +gate" below before assuming this is free. + +### 2f. Slot arrays in nodeDataStore ✅ Shipped + +The renderer can ask what slots a node has without resolving the live +`LGraphNode`. `NodeState` carries the node's own `inputs` / `outputs` arrays +**by reference** — not a copy — so they register at the same `LGraph.add` / +`LGraph.remove` chokepoint as the rest of the shell state. This is the shape +`widgetValueStore` already uses for widget order: order data beside record data +in one store, rather than a new store per concern. + +Because the arrays are the node's, array order _is_ slot order and there is +nothing to keep in step. `NodeSlots.vue` no longer calls `getNodeByLocatorId` or +touches `app.rootGraph`; `LGraphNode.vue`'s `hasInputs` / `hasOutputs` / +`hasVideoInput` read the store too. + +**Why no keyed `SlotState` and no slot ids.** The draft above proposed +`getSlotKey(nodeId, index, isInput)`. That is not viable: slot index is a +property of the containing array, not of the slot, and ~25 sites permute it — +including `reorderSubgraphInputs` (`subgraphUtils.ts`), a _pure permutation_ with +no add or remove, reachable by dragging subgraph inputs in the right panel. An +index-keyed store must re-key on every one of them. `linkStore` shows the price: +it survives reorder only via six separate mechanisms, one of which +(`realignInputLinkSlots`, `linkDeduplication.ts`) is a load-time +corruption-repair pass added for the reorder case that was originally missed +(#3348). A link's key is derived from fields the link genuinely owns; a slot's +index is not slot state, so keying on it would be a mirror. + +Holding the array instead makes the question moot — no key, no ids, no re-keying, +no order sync. It rests on one Vue guarantee, which is pinned by test: `reactive()` +returns an already-`shallowReactive` value **unchanged**, so putting the node's +array in a reactive store record does not swap its identity or deep-wrap the +slots inside it. A _plain_ array in the same position would be wrapped — which is +why the arrays must stay `shallowReactive`. + +**Still deferred:** slot data is still class instances with behaviour +(`draw()`, `isValidTarget()`, `renderingColor()`). Splitting plain `SlotState` +rows out of `NodeInputSlot` / `NodeOutputSlot` — ADR 0008's "plain data +components" — is its own phase, and it needs a real consumer first: interaction +code (`useSlotLinkInteraction`) hands the live slot instance to litegraph's +`RenderLink`, and the badge system needs `node.constructor.nodeData.api_node` +and `isSubgraphNode()` alongside the slots, so slot rows alone would not unblock +it. + +### 2g. node:added / node:removed events ✅ Shipped + +`LGraphEventMap` had `node:before-removed` but no add-side counterpart, so every +consumer that needed to know about a node add wrapped the single +`graph.onNodeAdded` callback slot, saving and restoring the previous value. +**Four** did so concurrently: the renderer's empty-graph bootstrap, the +error-clearing hooks, the minimap, and node-added telemetry. Whichever restored +first put back the _pre-its-own-install_ value and silently discarded the others +— order-dependent, per graph switch. + +`LGraph.add` now dispatches `node:added` (after the node is attached and +registered) and `LGraph.remove` dispatches `node:removed` (after detach, so +`node.graph` is already null and execution ids must be derived from the +dispatching graph plus `node.id`). All four consumers are plain +`addEventListener` subscribers; none touches the callback slot. `onNodeAdded` / +`onNodeRemoved` remain for extension compatibility. + +`useNodeReplacement` bypasses `graph.add` by design (it swaps a node in place, +preserving the id), so `replaceWithMapping` announces the add itself. + +Prefer the events for anything new. The callback slots cannot be shared. ### Store sunset criteria (applies to every Phase 2 concern) @@ -260,6 +406,24 @@ link-endpoint records from the relevant stores: Does not perform mutations yet — just queries. Validates that store connectivity data is complete and consistent with the class-based graph. +> **Status (2026-07-05):** The reroute-membership query shipped as `linkStore` + +> `rerouteStore` (PRs 13436, 13449): "what links pass through this reroute" is +> derived per root graph by a cached reverse index over the links' `parentId` +> chains, and input-side connectivity is one lookup via +> `linkStore.isInputSlotConnected()` / `getInputSlotLink()`. +> +> **Status (2026-07-17):** Output-side queries shipped and the `output.links` +> mirror is deleted (PR 13479): `linkStore.isOutputSlotConnected()` / +> `getOutputSlotLinks()`, litegraph internals reading through +> `node/slotLinks.ts` (see +> [output slot connectivity](output-slot-connectivity.md)). Remaining: the +> `input.link` slot mirror and execution order. +> +> **Status (2026-07-18):** The `input.link` mirror is deleted (PR 13498) by the +> same recipe: a deprecated warning getter on `NodeInputSlot`, readers going +> through the `slotLinks` input helpers, and serialization deriving +> `inputs[].link` from the store. Remaining: execution order. + **Risk:** Low. Read-only system with equivalence tests. --- @@ -269,18 +433,93 @@ data is complete and consistent with the class-based graph. Systems begin owning mutations. Legacy class methods delegate to stores and systems. This is the highest-risk phase. -### 4a. Position writes through layoutStore - -New code writes position via `useLayoutMutations()` against `layoutStore`. A -compatibility shim propagates changes back to `LGraphNode.pos` for legacy -readers. - -**This inverts the data flow:** Phase 2 had legacy -> store (read path). Phase 4 -has store -> legacy (write path). Both must work during the transition. - -**Risk:** High. Two-way sync between `layoutStore` and legacy state. Must handle -re-entrant updates (store write triggers the shim, which writes to legacy, which -must NOT trigger another store write). +### 4a. Position writes through layoutStore ✅ Shipped + +Planned as adding a compatibility shim; was mostly about deleting them. Every +entity now has exactly one write path, and the workarounds that existed because +writes bypassed it are gone. + +**One write path per entity.** Whole-value assignment through `pos` / `size` is +the normal path, and the setters commit to the store. `createGeometryView` +commits indexed writes too. Most in-repo indexed writes now use whole-value +assignments. The migration found three forms: + +| Form | Example | Where it hid | +| ------------------ | ------------------------------------ | -------------------- | +| Direct | `node.pos[0] += dx` | greppable | +| Helper-routed | `snapPoint(this.pos, snapTo)` | mutates its argument | +| Destructured local | `const { size } = this; size[0] = w` | not a `this.` write | + +The helper-routed form was the costly one: `LGraphNode.snapToGrid` never +reached the store, and `LGraph.configure` carried a local workaround +(`node.pos = [node.pos[0], node.pos[1]]`) for that one call site while three +others had none. + +**Groups and reroutes joined the store.** `GroupLayout` is id/position/size +with no zIndex or spatial index. Groups draw beneath nodes in insertion order, +and nothing queries them positionally. Geometry is a single +`setGroupBounds` operation, because `pos` and `size` are two views onto one +`Rectangle` and must never be stored apart. Reroutes went further: `posInternal` +is deleted, `pos` reads the stored point, and a reroute registers its own +geometry in its constructor, which removed two seeding sites. + +**`LGraphNode` no longer runs a continuous store-to-class sync.** When code +reads geometry, the node checks the global geometry version and copies the +stored rectangle into `_posSize` if its cache is stale. Serialization and legacy +rendering read current values through `this.pos` and `this.size` without walking +every node after each layout change. + +While Vue-node rendering is active, `notifyLayoutChanges` dirties the canvas for +node layout changes. For non-canvas `resizeNode` and `batchUpdateBounds` +operations, it also calls `onResize`; canvas resizes already own that callback +through `LGraphNode.setSize()`. It does not copy geometry into nodes. + +**Whole-value setters re-read after committing.** `_positionUpdated` and +`_sizeUpdated` write only their own half of `_posSize`, so stamping +`_geometryVersion` to the post-commit store version would mark the untouched +half fresh while it was still stale. The next commit of that half would then +publish the stale value to the store and to CRDT peers. Both invalidate and +refresh instead, which also picks up any value the store clamped or merged. + +**Deferred follow-up: extract geometry projection ownership.** Land this after +the node geometry facade and its CRDT-safety follow-up (PRs 14133 and 14480) so +the ownership and compensation rules are stable before moving them. Preserve +behavior while making one focused projection module responsible for the legacy +geometry cache: + +1. Move `_geometryVersion`, `_layoutRegistered`, and `refreshGeometry()` out of + `LGraphNode`. Keep ephemeral projection state private to the module, keyed by + node identity; do not add another entity store for compatibility-only state. +2. Make layout registration and removal call that module instead of coordinating + node flags and backing buffers directly. `LGraphNode.pos` and `.size` remain + compatibility accessors, but delegate synchronization rather than owning its + lifecycle. +3. Once the lifecycle has one owner, replace the store-wide geometry version + check with node-scoped invalidation. A geometry change should make only the + affected nodes refresh; unrelated node, group, and reroute operations should + not force every rendered node through a Yjs lookup. + +Completion requires no projection lifecycle fields or methods on `LGraphNode`, +no registration code that mutates such fields, unchanged extension-facing +`pos` / `size` behavior, and coverage for store-originated updates, indexed +writes, removal/re-addition, and CRDT compensation. + +**Open decisions:** + +1. The geometry views. The hand-written `size` Proxy is gone, replaced by + `createGeometryView` over `pos` and `size` on `LGraphNode` plus `pos`, + `size` and `bounding` on `LGraphGroup`. The views still handle the indexed + position write in `distributeNodes()` and extension writes such as + `node.size[1] = h`. Retiring them requires whole-value assignment in + `distributeNodes()` and a stable resize API for extensions. +2. Subgraph IO nodes have conforming write paths but no store entry. A keyed + entry needs subgraph scoping (`SUBGRAPH_INPUT_ID` is a constant shared by + every subgraph) and `Subgraph.id` is reassigned by `clear()`, so the key can + go stale. The link store rejected the same pattern. Nothing needs keyed + access, since callers reach them as `subgraph.inputNode`. +3. Two hit-testing systems: litegraph against class geometry, `layoutStore` + against a spatial index. Node bounds are duplicated between `_boundingRect` + and `NodeLayout.bounds`. ### 4b. ConnectivitySystem mutations @@ -311,6 +550,13 @@ the system knowing about the callback API. - Bridge lifecycle events remain internal. Legacy callbacks stay the public compatibility API during Phase 4. +> **Status (2026-07-05):** Link and reroute store registration now funnels +> through canonical `LGraph` mutation chokepoints: `_addLink`/`_removeLink` and +> `_addReroute`/`_removeReroute` pair every map mutation with store +> (un)registration, and `clear()` / subgraph-definition GC unregister whole +> graphs. The callback contract above remains (`output.links` was deleted in +> PR 13479, `input.link` in PR 13498). + **Risk:** High. Extensions depend on callback ordering and timing. Must be validated against real-world extensions. @@ -441,10 +687,12 @@ requires a separate ADR. **Questions to resolve:** - Should non-position stores also be CRDT-backed for collaboration? -- Do the stores need an operation log for undo/redo, or can that remain external - (Y.js undo manager)? - How does conflict resolution work when two users modify the same record? +Settled: the stores do not need an operation log for undo/redo. `layoutStore` +carried one and nothing ever read it — undo/redo is snapshot-based through +`changeTracker` — so it was deleted. + ### Extension API preservation The current system exposes lifecycle callbacks on entity classes: @@ -475,6 +723,64 @@ event listeners instead of callbacks. - Callback order remains: output validation -> input validation -> commit -> output change notification -> input change notification. +### Removed layoutStore queries (custom-node audit pending) + +These `layoutStore` methods were deleted once their last in-repo caller went +away. They were never advertised as extension API, but `layoutStore` is +reachable from custom nodes, so Hyrum's law applies: someone may depend on +them. + +| Removed method | Was | +| ---------------------- | ----------------------------------------------- | +| `getAllNodes()` | Reactive map of every node layout, unscoped | +| `getNodesInBounds()` | Reactive node ids intersecting bounds | +| `queryNodeAtPoint()` | Top-zIndex node containing a point | +| `queryNodesInBounds()` | Node ids intersecting bounds, via spatial index | +| `queryItemsInBounds()` | Nodes, links, slots and reroutes in bounds | + +**Action required:** grep the custom-node ecosystem for these names before the +next release. If any have external dependents, restore them as deprecated +shims per [Extension API preservation](#extension-api-preservation) rather +than reintroducing the call sites. + +Note that the node-facing ones were also _wrong_ by the time they were +removed: node layout was keyed by bare `NodeId` with no root-graph scope, and +registration now happens for every graph including unopened subgraph +definitions, so any of these would have returned nodes the user cannot see. A +restored shim must take a `rootGraphId`, which node layout is now keyed by. + +### Removed CRDT sync seam (prior art for multiplayer) + +`layoutStore` carried three methods reserved for a networked future that has +not arrived: + +| Removed method | Was | +| -------------------- | --------------------------------------------- | +| `getYDoc()` | The raw `Y.Doc`, for a sync provider | +| `applyUpdate()` | `Y.applyUpdate` — merge a remote peer's ops | +| `getStateAsUpdate()` | `Y.encodeStateAsUpdate` — full-state snapshot | + +None had a caller. Removed as YAGNI, not as a change of direction: the layout +store is still a Yjs document and +[ADR 0003](../adr/0003-crdt-based-layout-system.md) still holds. Reinstating +them is a few lines against `this.ydoc`. + +Two things worth carrying forward when multiplayer is actually built, both +learned by deleting this: + +- `applyUpdate` bypassed `applyOperation`, so nothing that derives state from + the operation stream would have seen a remote change. `highestZIndex` (see + `allocateZIndex`) is exactly such a counter — a remote peer's node with a + higher `zIndex` would not have raised it, and the next allocation would + collide. Any real sync path must rebuild that kind of derived state from the + document, or observe `ynodes` rather than the operation stream. +- All three entity types are now keyed by `makeScopedLayoutKey(rootGraphId, id)`, + so two peers in different workflows cannot collide. They still share a bucket + across subgraphs of one root graph, which is safe only because node ids are + unique root-wide — `Subgraph` shares the root graph's `state`, so one counter + issues every id. A sync path that merges documents from peers holding + different workflows must not assume that invariant survives the merge. + ### Extension Migration Examples (old -> new) The bridge keeps legacy callbacks working, but extension authors can migrate @@ -571,7 +877,31 @@ stores. **Current state:** `beforeChange()` / `afterChange()` provide undo/redo checkpoints but not true transactions. The graph can be in an inconsistent -state between these calls. +state between these calls. Link topology mutations are centralized in +`linkStore`: endpoint updates validate their batch before mutation, and link +replacement validates ownership, identity, the expected incumbent, ID, and +target availability before changing its indexes. These operations are atomic +only within `linkStore`; they do not provide rollback across callbacks, layout, +reroutes, graph maps, versioning, or other stores. + +Centralizing each mutation point removes duplicated caller checks, reduces the +number of paths that can violate store invariants, and provides one place for +atomic validation and rollback as the migration continues. Command-executor +transactions should wrap these store mutation points rather than adding +caller-specific compensation. + +Input replacement commits new topology before old-link disconnect callbacks, so +callback queries see the replacement rather than an intermediate empty slot. + +**Rejected transitional options:** + +| Option | Why it was rejected | +| ---------------------------------------- | ---------------------------------------------------------------------------------- | +| Preflight in each graph caller | Duplicates store invariants and leaves a check-to-mutation race. | +| Disconnect, register, then restore | Callbacks and multi-store cleanup make the removed state unsafe to reconstruct. | +| Add caller-specific failure compensation | Spreads rollback policy across paths instead of establishing one transaction seam. | +| Normalize only in `createSubgraph` | Misses workflow load, paste, and conversion paths and can mutate caller input. | +| Add pseudo-live `LinkMap` iterators | Does not preserve native iterator semantics; cached snapshots preserve it instead. | **Phase 4 baseline semantics:** @@ -596,13 +926,16 @@ state between these calls. The dedicated stores use per-concern keying strategies: -| Store | Key Format | -| ------------------------- | ---------------------------------- | -| `widgetValueStore` | `WidgetId` (`graphId:nodeId:name`) | -| `domWidgetStore` | Widget UUID | -| `layoutStore` | Raw nodeId/linkId/rerouteId | -| `nodeOutputStore` | `"${subgraphId}:${nodeId}"` | -| `subgraphNavigationStore` | subgraphId or `'root'` | +| Store | Key Format | +| ------------------------- | ------------------------------------------------------------------------------- | +| `widgetValueStore` | `WidgetId` (`graphId:nodeId:name`) | +| `domWidgetStore` | Widget UUID | +| `layoutStore` | Raw node/link IDs; `${rootGraphId}:${localId}` for group/reroute geometry | +| `nodeOutputStore` | `"${subgraphId}:${nodeId}"` | +| `subgraphNavigationStore` | subgraphId or `'root'` | +| `linkStore` | `` `${owningGraphId}:${nodeId}:${slot}` `` query indexes in root-scoped buckets | +| `rerouteStore` | `RerouteId`, root-graph-scoped buckets | +| `nodeDataStore` | `NodeState` identity (`Set`), root-graph-scoped buckets | ADR 0009 refines the promoted-widget target: promoted value widgets should use host boundary identity (`host node locator + SubgraphInput.name`), not interior @@ -618,6 +951,79 @@ recovers the parts on demand. keeps the key format that matches its concern; there is no forced unification under a single ID space. +### Deferred topology follow-ups + +The scoped-topology migration now has the following boundaries and leaves the +remaining decisions for later work. + +**Implemented boundaries:** + +- `createSubgraphs` and `createSubgraph` share one immutable normalization + boundary used by workflow loading, direct creation, clipboard/paste, and + conversion. It creates shells first and fills leaves first without changing + caller input. Malformed same-owner duplicate IDs are deterministic: + first-wins and later duplicates are dropped because references cannot + disambiguate them. +- Graph clear uses one exact-entity teardown traversal. Lifecycle callbacks run + first while topology remains observable, followed by link, reroute, node, and + layout detachment. Only the root clear defensively clears whole store buckets. +- Root and subgraph serialization consume one owner-local topology partition. + It preserves the regular and floating wire categories in workflow output. + +**Still deferred:** + +- Keep entity identity flat and root-wide. Replacing it with owner-nested + identity would reverse the current architecture rather than simplify it. +- Keep `idsByOwner` for owner-local iteration and teardown; removing it would + replace indexed access with root-bucket scans. +- Keep cached reroute membership; recomputing it would add graph walks to read + paths. +- Do not restore the legacy `_links` mirror or broaden that compatibility + surface. +- Keep registration failure as an explicit return value rather than adding + thrown errors. +- `LinkMap` caches owner-local snapshots, but every topology mutation currently + invalidates all views, including endpoint-only updates. Profile Pinia revision + and cache-rebuild cost before considering owner-scoped revisions; do not + replace the cache with pseudo-live iterators or an `_links` mirror. +- Graph teardown now finishes exact detachment, defensive root-bucket clearing, + graph reset, and canvas clearing after a lifecycle callback fails, then + propagates that same failure. Lifecycle callbacks remain fail-fast, so later + callbacks do not run. This is the current chosen policy: it preserves callback + ordering and topology observation while preventing partially cleared graphs. + + | Future direction | Failure handling | Tradeoff | + | ------------------------------------------------------------- | ------------------------------------------- | ------------------------------------------------------------------------------------------- | + | **1. Current: finish teardown, then propagate first failure** | Fail fast; later callbacks do not run | Preserves current lifecycle semantics, but skips later notifications | + | 2. Run all callbacks, then report | Propagate the first failure or an aggregate | Completes notifications, but changes fail-fast behavior | + | 3. Finish and report without propagating | Swallow and report callback failures | Keeps clear callers running, but hides extension failures from them | + | 4. Detach first, then notify from a queue | Run callbacks after teardown | Simplifies teardown isolation, but breaks compatibility for callbacks that observe topology | + +- Keep the browser hydration test as the workflow-level composition check. +- Investigate separately whether link geometry in `layoutStore`, still keyed by + bare `LinkId`, can collide across simultaneously live root graphs. +- Document that root-wide identity lookup uses `rootGraphId`, while owner-local + iteration and slot queries use `graphScopeOf()` with the directly owning + graph. Callers should not construct root/owner pairs manually. +- Defer a persistent root-wide group ID index until profiling shows it is + warranted. `LGraph.add()` currently scans root and subgraph groups for each + group insertion, which can make loading G groups take quadratic time. A + `Set` per insertion has the same asymptotic cost, while a persistent index + duplicates lifecycle state. Defer evaluation of its real workflow load-speed + impact. Measure representative large workflow load, deserialization, paste, + and unpack paths first. If the scan has material impact, optimize the + insertion path while preserving the existing root-shared high-water allocator + and import-time collision repair. +- Defer floating reroute/link multi-store rollback. Normal root-shared link ID + allocation avoids collisions for minted IDs, while registration can reject + externally supplied runtime IDs that collide. Future transaction work should + wrap the centralized store mutation rather than add compensation here. +- Treat floating as one-ended link state, not a separate entity category. The + runtime topology collection is unified; `graph.links` and + `graph.floatingLinks` remain filtered compatibility views. Keep the separate + serialized `floatingLinks` field until a versioned workflow migration has + enough value to justify its extension and fixture impact. + --- ## Dependency Graph @@ -629,7 +1035,8 @@ Phase 0c (doc fixes) ─────────┤── no dependencies betwe Phase 1a (branded WidgetId) ── ✅ shipped (PR 12617) Phase 1b (store state shapes) ─┐── depends on 1a -Phase 1c (dedicated stores) ──┘── widgetValueStore + 5 others shipped (PR 12617) +Phase 1c (dedicated stores) ──┘── widgetValueStore + 7 others shipped + (PR 12617; linkStore PR 13436; rerouteStore PR 13449) Phase 2a (Position via layoutStore) ─┐── depends on 1c Phase 2b (Widget consolidation) ────┤── ✅ largely shipped; depends on 1a, 1c @@ -642,6 +1049,7 @@ Phase 3c (ConnectivitySystem) ──── depends on 2c Phase 3->4 gate checklist ──────── depends on 3a, 3b, 3c Phase 4a (Position writes) ────── depends on 2a, 3b + Geometry projection ownership ── after PRs 14133, 14480; depends on 4a Phase 4b (Connectivity mutations) ─ depends on 3c, 3->4 gate Phase 4c (Widget writes) ─────── ✅ largely shipped; depends on 2b Phase 4d (Layout decoupling) ─── depends on 2a, 3->4 gate diff --git a/docs/architecture/ecs-target-architecture.md b/docs/architecture/ecs-target-architecture.md index 993b1fe12e7..d87c1479b0f 100644 --- a/docs/architecture/ecs-target-architecture.md +++ b/docs/architecture/ecs-target-architecture.md @@ -18,7 +18,13 @@ Map<WidgetId, WidgetValue>"] DomWidgetStore["domWidgetStore Map<WidgetId, DomWidgetState>"] LayoutStore["layoutStore (Y.js CRDT) -nodeId / linkId / rerouteId → layout"] +raw nodeId/linkId; rootGraphId:localId +for group/reroute geometry"] + LinkStore["linkStore +rootGraphId → linkId → LinkTopology +owner-qualified endpoint indexes"] + RerouteStore["rerouteStore +rootGraphId → RerouteId → RerouteChain"] NodeOutputStore["nodeOutputStore Map<nodeLocatorId, outputs>"] SubgraphNavStore["subgraphNavigationStore @@ -39,7 +45,8 @@ preview exposure state"] RS -->|reads| Stores SS -->|reads/writes| Stores - CS -->|reads/writes| LayoutStore + CS -->|reads/writes| LinkStore + CS -->|reads/writes| RerouteStore LS -->|reads/writes| LayoutStore ES -->|reads| NodeOutputStore VS -->|reads/writes| LayoutStore @@ -61,22 +68,32 @@ graphId:nodeId:name NLID["nodeLocatorId subgraphId:nodeId"] NID["nodeId (raw)"] - LID["linkId (raw)"] - RID["rerouteId (raw)"] + LID["linkId (raw; +root-scoped in linkStore)"] + RID["rootGraphId:rerouteId"] + EPI["owningGraphId:nodeId:slot +(target/origin index)"] end WID -->|widgetValueStore, domWidgetStore| W["keyed lookups"] NLID -->|nodeOutputStore| W NID -->|layoutStore| W - LID -->|layoutStore| W - RID -->|layoutStore| W + LID -->|layoutStore, linkStore identity| W + RID -->|layoutStore, rerouteStore| W + EPI -->|linkStore indexes| W ``` `WidgetId = graphId:nodeId:name` is itself a branded string (see `src/types/widgetId.ts`). `nodeLocatorId = subgraphId:nodeId` addresses node -outputs. `layoutStore` keys layout records by raw `nodeId` / `linkId` / -`rerouteId`. Each store enforces its own key shape; there is no single shared -entity-ID type across stores. +outputs. `layoutStore` keys geometry records by raw `nodeId` / `linkId` / +`rerouteId`. `linkStore` keys `LinkTopology` identity by `linkId` inside +root-graph-scoped buckets. Owner-local and endpoint indexes provide graph +iteration and slot queries; the target index includes only links whose target +slot is unique (see [link-topology-store.md](link-topology-store.md)). +`rerouteStore` keys `RerouteChain` by raw `rerouteId` in root-graph-scoped +buckets (see +[reroute-chain-store.md](reroute-chain-store.md)). Each store enforces its own +key shape; there is no single shared entity-ID type across stores. Note: `graphId` is a scope identifier. It identifies which graph an entity belongs to and forms the prefix of `WidgetId`. Subgraphs are nodes with a @@ -177,14 +194,15 @@ target_id, target_slot, type"] B5["resolve()"] end - subgraph After["linkId-keyed components (layoutStore)"] + subgraph After["link-id-keyed topology (linkStore) + unextracted state"] direction TB - A1["LinkEndpoints -{ originId, originSlot, -targetId, targetSlot, type }"] - A2["LinkVisual + A1["LinkTopology — SHIPPED +{ id, originNodeId, originSlot, +targetNodeId, targetSlot, type, parentId? } +primary linkId; owner-qualified endpoint indexes"] + A2["LinkVisual — not yet extracted { color, path, centerPos }"] - A3["LinkState + A3["LinkState — not yet extracted { dragging, data }"] end @@ -198,6 +216,26 @@ targetId, targetSlot, type }"] style After fill:#1a4a1a,stroke:#2a6a2a,color:#e0e0e0 ``` +`LinkTopology` has shipped in `src/stores/linkStore.ts`: `LLink._state` IS the +store entry — the class fields are accessors over the store's reactive proxy, +so the store and the instance cannot disagree. Registration is first-wins with +identity-checked delete/update. See +[link-topology-store.md](link-topology-store.md) for the full design record. +`LinkVisual` and `LinkState` remain on the `LLink` class. + +### Reroute: RerouteChain (shipped) + +Reroutes follow the same pattern. `RerouteChain { id, parentId?, floating? }` +lives in `src/stores/rerouteStore.ts`, keyed by `RerouteId` in +root-graph-scoped buckets; `Reroute._chain` is the store entry. Link +membership (`Reroute.linkIds` / `floatingLinkIds`) is **not stored** — it is +derived per root graph by a cached computed reverse index walking the links' +`parentId` chains, replacing ~10 hand-maintained write sites and the +`validateLinks` set-repair. See +[reroute-chain-store.md](reroute-chain-store.md). Reroute _position_ has since +migrated too: `Reroute.posInternal` is deleted and the layout store's +`{ id, position }` entry is the source of truth. + ### Widget: Before vs After ```mermaid @@ -248,8 +286,8 @@ graph TD direction TB CS["ConnectivitySystem Manages link/slot mutations. -Writes: LinkEndpoints, SlotConnection, -Connectivity"] +Writes: LinkTopology (shipped), +SlotConnection (future), Connectivity"] VS["VersionSystem Centralizes change tracking. Replaces 15+ scattered _version++. @@ -312,9 +350,11 @@ graph LR Exe["Execution"] Props["Properties"] WC["WidgetContainer"] - LE["LinkEndpoints"] + LE["LinkTopology +(linkStore — shipped)"] LV["LinkVisual"] - SC["SlotConnection"] + SC["SlotConnection +(output side — future)"] SV["SlotVisual"] WVal["WidgetValue"] WL["WidgetLayout"] @@ -333,7 +373,7 @@ graph LR LS -.->|read| WC CS -->|write| LE - CS -->|write| SC + CS -.->|future write| SC CS -->|write| Con ES -.->|read| Con @@ -349,6 +389,14 @@ graph LR VS -.->|read| Con ``` +ConnectivitySystem's `LinkEndpoints` write target is realized as +`LinkTopology` in `linkStore`. The input side of `SlotConnection` +(`input.link`) is subsumed by the linkStore key itself — "which link targets +this input slot" is the store's primary index +(`isInputSlotConnected` / `getInputSlotLink`) — though the `input.link` slot +mirror still exists on the class. The output side (`output.links[]`) remains +future extraction work. + ## 4. Dependency Flow ### Before: Tangled References @@ -478,14 +526,14 @@ sequenceDiagram Legacy->>Class: node.pos = [100, 200] Class->>Bridge: pos setter intercepted - Bridge->>Store: useLayoutMutations().moveNode(nodeId, { pos: [100, 200] }) + Bridge->>Store: useLayoutMutations(source).moveNode(nodeId, { pos: [100, 200] }) New->>Store: layoutStore read for nodeId Store-->>New: { pos: [100, 200], size: [...] } Note over Legacy,New: Phase 2: New features build on ECS directly - New->>Store: useLayoutMutations().moveNode(nodeId, { pos: [150, 250] }) + New->>Store: useLayoutMutations(source).moveNode(nodeId, { pos: [150, 250] }) Store->>Bridge: change detected Bridge->>Class: node._pos = [150, 250] Legacy->>Class: node.pos diff --git a/docs/architecture/entity-interactions.md b/docs/architecture/entity-interactions.md index d6f85c104e1..1d1751daa69 100644 --- a/docs/architecture/entity-interactions.md +++ b/docs/architecture/entity-interactions.md @@ -66,7 +66,7 @@ graph TD Link -.->|"origin_id, target_id"| Node Link -.->|"parentId"| Reroute Slot -.->|"link / links[]"| Link - Reroute -.->|"linkIds"| Link + Reroute -.->|"linkIds (derived, rerouteStore)"| Link Reroute -.->|"parentId"| Reroute Group -.->|"_children Set"| Node Group -.->|"_children Set"| Reroute @@ -103,10 +103,14 @@ type: ISlotType"] Link -.->|"parentId"| R1["Reroute A"] R1 -.->|"parentId"| R2["Reroute B"] - R1 -.-|"linkIds Set"| Link - R2 -.-|"linkIds Set"| Link + R1 -.-|"linkIds (derived)"| Link + R2 -.-|"linkIds (derived)"| Link ``` +`Reroute.linkIds` / `floatingLinkIds` are read-only accessors derived from the +links' own `parentId` chains by `rerouteStore` — membership is never stored +(see [reroute-chain-store.md](reroute-chain-store.md)). + ### Subgraph Boundary Connections ```mermaid @@ -142,14 +146,22 @@ graph TD ```mermaid graph LR Slot["Source Slot"] -->|"drag starts"| FL["Floating LLink -origin_id=-1 or target_id=-1"] - FL -->|"stored in"| FLMap["graph.floatingLinks Map"] +origin or target = UNASSIGNED_NODE_ID"] + FL -->|"registered in"| Store["linkStore.byId"] + Store -->|"filtered view"| FLMap["graph.floatingLinks"] + FL -.->|"excluded from"| Indexes["connectivity indexes"] FL -.->|"may pass through"| Reroute - Reroute -.-|"floatingLinkIds Set"| FL - FL -->|"on drop"| Permanent["Permanent LLink -(registered in graph._links)"] + Reroute -.-|"floatingLinkIds (derived)"| FL + FL -->|"on drop"| Permanent["Fully-assigned LLink +(graph.links view + connectivity indexes)"] ``` +A floating link's slot attachment is fully encoded in its own endpoints — +slots hold no floating-link sets (`slotFloatingLinks()` in `LLink.ts` derives +attachment by scanning the filtered `graph.floatingLinks` view). Floating is an +endpoint state, not a separate entity category; persistent dangling reroute +branches still require that state outside an active drag. + ## 3. Rendering How LGraphCanvas draws each entity type. @@ -254,7 +266,7 @@ stateDiagram-v2 ```mermaid stateDiagram-v2 [*] --> Created: node.connect() or connectSlots() - Created --> Registered: graph._links.set(id, link) + Created --> Registered: graph._addLink(link) state Registered { [*] --> Active @@ -268,12 +280,18 @@ stateDiagram-v2 note right of Created new LLink(id, type, origin, slot, target, slot) + _addLink sets graph._links entry and + registers topology in linkStore + (keyed by target input slot). Output slot.links[] updated. Input slot.link set. end note note right of Removed - Removed from graph._links. + Removed from graph._links and + unregistered from linkStore + (via _removeLink or link.disconnect). + Link geometry dropped from layoutStore. Orphaned reroutes cleaned up. graph._version incremented. end note @@ -362,6 +380,10 @@ graph TD WVS["WidgetValueStore (Pinia)"] PES["PreviewExposureStore +(Pinia)"] + LKS["LinkStore +(Pinia)"] + RRS["RerouteStore (Pinia)"] LM["LayoutMutations (composable)"] @@ -383,10 +405,20 @@ lastRerouteId, lastGroupId)"] SGNode -->|"host-scoped preview exposures"| PES PES -.->|"keyed by host node locator"| SGNode - %% LayoutMutations + %% LinkStore + Graph -->|"_addLink()/_removeLink() register/unregister"| LKS + Link <-->|"_state IS the store entry (endpoint accessors)"| LKS + LKS -.->|"keyed by rootGraphId + targetNodeId:targetSlot"| Link + + %% RerouteStore + Graph -->|"_addReroute()/_removeReroute()"| RRS + Reroute <-->|"_chain (parentId, floating)"| RRS + RRS -.->|"derived linkIds membership"| Reroute + + %% LayoutMutations (geometry only) Node -->|"pos/size setter"| LM Reroute -->|"move()"| LM - Link -->|"connectSlots()/disconnect()"| LM + Link -->|"disconnect(): drop link geometry"| LM Graph -->|"add()/remove()"| LM %% Graph state diff --git a/docs/architecture/entity-problems.md b/docs/architecture/entity-problems.md index 587a6b88b70..1c3ae75ddfd 100644 --- a/docs/architecture/entity-problems.md +++ b/docs/architecture/entity-problems.md @@ -168,12 +168,24 @@ No central mechanism exists. It's easy to forget an increment (stale render) or Domain objects call Pinia composables at the module level or in methods, creating implicit dependencies on the Vue runtime: -- `LLink.ts:24` — `const layoutMutations = useLayoutMutations()` (module scope) -- `Reroute.ts` — same pattern at module scope +- `Reroute.ts:31` — `const layoutMutations = useLayoutMutations()` (module scope) +- `LLink.ts:7` — imports the `layoutStore` singleton at module scope; `useLinkStore()` is called inside methods and helpers (needs an active Pinia, but not eagerly at import time) +- `Reroute.ts` — `useRerouteStore()` called inside methods for derived membership - `BaseWidget.ts` — imports `useWidgetValueStore` These make the domain objects untestable without a Vue app context. +### Reroute Membership Dual-Writes (solved) + +`Reroute.linkIds` / `floatingLinkIds` were hand-maintained `Set`s written from +~10 scattered call sites (connect, disconnect, paste, configure, subgraph +pack/unpack, ...), with `Reroute.validateLinks()` repairing the inevitable +drift on load. Membership is now derived from the links' own `parentId` +chains via `rerouteStore` — the accessors are read-only, the write sites and +`validateLinks` are deleted, and orphaned reroutes are pruned by the derived +`totalLinks === 0` instead of set-repair. See +[reroute-chain-store.md](reroute-chain-store.md) (Decision 1). + ### Change Notification Sprawl `beforeChange()` and `afterChange()` (undo/redo checkpoints) are called from diff --git a/docs/architecture/link-topology-store.md b/docs/architecture/link-topology-store.md new file mode 100644 index 00000000000..5d13df109bd --- /dev/null +++ b/docs/architecture/link-topology-store.md @@ -0,0 +1,135 @@ +# Link Topology Store + +Date: 2026-07-05 (retroactive design record; implemented in PR #13436) +Status: Accepted + +Design record for extracting link topology into a dedicated store per +[ADR 0008](../adr/0008-entity-component-system.md). Amends the +`LinkEndpoints` component described there. The +[Reroute Chain Store](reroute-chain-store.md) builds directly on this +store; shared vocabulary lives in the +[Domain Glossary](domain-glossary.md). + +## Decision 1: One state object, class reads through it + +`LLink` no longer owns copies of its topology fields. A single plain +object, + +```text +LinkTopology { id, graphId, originNodeId, originSlot, targetNodeId, + targetSlot, type, parentId? } +``` + +backs the link: `LLink._state` holds it, and `id`, `type`, `origin_id`, +`origin_slot`, `target_id`, `target_slot`, and `parentId` are accessors +over it. Registration inserts that same object into the store by +reference and re-assigns `_state` to the reactive proxy read back from +the bucket, so subsequent class writes are Vue-tracked (the `BaseWidget` +pattern — see Decision 4 of the reroute chain store record). There is no +store-side copy to drift from the class: the store entry _is_ the +class's state. + +The store is runtime state only; `LLink.asSerialisable` reads the same +fields it always did, and serialization goldens (key order plus +byte-identical round-trips) pin the wire format. + +## Decision 2: Identity ownership with query-specific indexes + +The topology store's root-scoped `byId` map is the sole authority for +`LinkId -> LinkTopology` identity. `LGraph.links` and `LGraph.floatingLinks` +are owner-filtered compatibility views over that map, partitioned by endpoint +state; `LGraph` does not keep separate topology maps. Query indexes are derived +from the authoritative components: + +- `targetIndex`, keyed by + `` `${owningGraphId}:${targetNodeId}:${targetSlot}` ``, answers + input-connectivity queries in one lookup. It contains only links whose target + slot is unique. +- `originIndex`, keyed by + `` `${owningGraphId}:${originNodeId}:${originSlot}` ``, answers + output-connectivity queries without scanning the graph. + +Floating links do not have a unique target key but still belong to `byId`. The +store holds no `LLink` class instances; a weak resolver connects each component +to its compatibility shell. + +Link ids are unique across the root graph and all of its subgraph definitions. +Persisted collisions are remapped before registration, including clipboard +imports. `graphId` is association data, not part of entity identity. + +## Decision 3: Root-and-owner-scoped bucket lifecycle + +Buckets use the shared graph-scoped lifecycle: + +```text +RootGraphId -> { byId, idsByOwner, targetIndex, originIndex } +``` + +The root key groups one loaded workflow. `byId` is flat; `idsByOwner` is a +secondary membership index for owner-local iteration and teardown. Slot keys +include the owner because fixed subgraph boundary node ids are wire sentinels +shared by every definition. + +Callers pass both parts as a `GraphScope`: `rootGraphId` selects the workflow +bucket, while `owningGraphId` identifies the graph that directly owns the node +and link endpoints. The two IDs are equal for root-graph nodes. A node inside a +subgraph definition still uses the root workflow's `rootGraphId`, but uses the +definition's ID as `owningGraphId`; querying it with the root graph as owner +would address a different slot. Code with an `LGraph` should derive this pair +with `graphScopeOf(graph)` rather than constructing it manually. + +## Decision 4: Registration protocol + +- `registerLink` returns the store-held reactive `LinkTopology` when + registration succeeds or the same topology is already registered. It + returns `undefined` when another topology owns the root-wide id or target + slot. +- The `byId` map is the ownership check for deletion, re-registration, and + endpoint updates. Query indexes never establish ownership. +- `deleteLink` is **identity-checked** (`toRaw` comparison): only the + registered topology can vacate its slot. +- updateEndpoints validates a complete endpoint batch before mutation. + Every participant must own its current placement, final target keys must + be unique, and an occupied destination is valid only when its incumbent + participates and vacates that key. After validation, the store removes all + old placements, patches every reactive topology, and inserts all final + placements. Swaps and rotations therefore commit without transient + eviction; an invalid move leaves every topology and index unchanged. + updateEndpoint is the single-item form and rejects occupied targets. + Graph-owned systems disconnect links before removal because only the graph + can coordinate callbacks, reroutes, and link-map lifecycle. + +## Decision 5: Mutation chokepoints + +All `graph.links` mutation funnels through its store-backed `LinkMap` and +`LGraph._addLink` / `_removeLink`, which perform store +registration/unregistration (and link-layout cleanup on removal). +`LinkMap` caches its owner-local regular or floating view so rendering can use +native `Map` reads and snapshot iterators without rebuilding topology on each +access. Store mutations centrally invalidate the reactive view. +`addFloatingLink` / `removeFloatingLink` apply floating-specific lifecycle +policy through the same topology collection. `LLink.disconnect` performs the +equivalent effects inline because it only holds a `LinkNetwork`, and +unregisters before reroute pruning so derived reroute counts exclude the dying +link. `clear()` and subgraph-definition GC unregister whole graphs +(`unregisterAllLinkTopologies` / `clearGraph`). + +`addFloatingLink` is the defensive runtime and extension boundary. It mints +an id for a new link, treats re-adding the same registered link as a no-op, +and returns `undefined` after logging an error when a different link already +owns a supplied id. It does not remint an unexpected runtime collision. +Import and deserialization repair persisted id collisions before calling this +runtime API. See +[Link registration migration](../extensions/link-registration-migration.md) +for extension-facing return-value guidance. + +## Scope + +This design covers link topology (endpoints, type, chain terminus). +Link visual state (`color`, path caches) and the layout store's link +_geometry_ records are out of scope. The `output.links` and `input.link` +slot mirrors have since been deleted — the store is the single source +for slot connectivity in both directions (see +[output slot connectivity](output-slot-connectivity.md) Decision 6); +the remaining fields are deprecated warning getters kept as extension +migration telemetry. diff --git a/docs/architecture/node-badge-store.md b/docs/architecture/node-badge-store.md new file mode 100644 index 00000000000..ad97ba4c2ec --- /dev/null +++ b/docs/architecture/node-badge-store.md @@ -0,0 +1,234 @@ +# Node Badge Store + +Date: 2026-07-05 (updated 2026-07-15) +Status: Superseded on this branch by a derive-on-read prototype — see +[Prototype: derive-on-read](#prototype-derive-on-read-2026-07-15) below. +Slices A and B shipped as described; the prototype then removed the +store. Follow-up to the +[link topology store](link-topology-store.md), +[reroute chain store](reroute-chain-store.md), and the +[node data store draft](node-data-store.md) + +Design record for extracting node badges off `LGraphNode` instances into +a dedicated store per [ADR 0008](../adr/0008-entity-component-system.md), +going straight to plain-data components — no interim closure storage. +Vocabulary: [domain glossary § Badges](domain-glossary.md#badges). + +## Current state (what this replaces) + +`LGraphNode.badges: (LGraphBadge | (() => LGraphBadge))[]` mixes three +things: a **core badge closure** (id / lifecycle / source, re-derived +independently by the Vue renderer, which skips it positionally via +`slice(1)`), **credits badge closures** (`creditsBadgeGetter`, +`buildWrapperAwarePriceBadge` — hand-rolled reactive computeds the +legacy canvas polls per frame), and a public push surface for +extensions. Badge changes are announced by a single manual +`node:property:changed` trigger in `usePriceBadge`; plain pushes are +invisible. Credits badges are classified by icon identity +(`icon.image === componentIconSvg`). Badges never serialize (verified: +no `badges` key in `serialize()`/`configure`). + +Every closure is a reactive computed feeding an unreactive array, and +the Vue renderer has already re-implemented all of their reactivity as +store-tracked dependencies. The design deletes the closures and makes +the store rows the single truth both renderers read. + +## Decision 1: Plain `BadgeData` rows, no interim shape + +The store holds only plain data (ADR 0008 component rule): + +``` +BadgeData = CoreBadgeData | CreditsBadgeData // discriminated on `kind` + // core rows require `part`; credits rows may carry an `iconKey` + // resolved via a small icon registry ('credits' → SVG) +``` + +There is no `extension` kind: resolved decision 1 below keeps +`node.badges` as the raw extension surface, so the store holds only +system-computed rows and the system replaces them wholesale per write. + +No `onClick` (no producer exists; `LGraphButton`/`title_buttons` are a +separate surface and out of scope). No `Image` objects — icons are +referenced by key. A `commandId` field can be added if a clickable badge +requirement ever materialises. + +Rejected: an interim `BadgeEntry { kind, source: LGraphBadge | thunk }` +phase. The public element type of `node.badges` breaks either way; one +break that lands on the end-state shape beats two. + +## Decision 2: Store shape and keying + +`nodeBadgeStore`: root-graph-scoped buckets (`rootGraph.id`) keyed by +`NodeId`, each holding an ordered reactive `BadgeData[]`. Register / +unregister / unregister-all trio at the `LGraph.add` / `LGraph.remove` / +`clear()` chokepoints, identity-checked deletes — the shipped store +conventions. + +Rows are partitioned by `kind` at read time; the positional `slice(1)` +convention and icon-identity credits detection are deleted. The system +emits rows in display order (core, then credits) and replaces a node's +array wholesale, so reads are identity-stable between writes. + +## Decision 3: A reactive BadgeSystem writes the rows + +One system module owns the recomputation: per registered node, an +`effectScope` runs a pure `computeBadges(sources) → BadgeData[]` +function inside a thin watch shell and writes the node's rows. Sources +are the existing stores: `nodeDefStore`, `settingStore`, +`colorPaletteStore`, `useNodePricing` revision refs, `widgetValueStore`, +`linkStore` input connectivity. The pure function is the future +command-pipeline phase body (ADR 0003 systems ADR); only the scheduler +shell changes when that lands. + +`useNodeBadge` / `usePriceBadge` stop pushing closures; their derivation +logic moves into `computeBadges`. The manual `'badges'` +`node:property:changed` trigger, the `badges` case in +`useGraphNodeManager` (now deleted entirely), and `VueNodeData.badges` are +deleted. +`usePartitionedBadges` collapses to a store query partitioned by kind; +its manual dependency-touching (`trackNodePrice`, +`trackSubgraphInnerNodePrices`) moves inside the system. + +## Decision 4: Core badges are system-written rows too + +Core (#id / lifecycle / source) badges are materialized by the system +like every other kind, so both renderers consume one uniform row set. +This kills the current dual derivation (legacy closure + Vue-side +re-derivation). Materialized-by-system is the ECS write path, not a +mirror: no other component stores this projection. + +## Decision 5: Legacy canvas consumes rows via a draw cache + +`drawBadges` renders from `BadgeData`, constructing and caching +`LGraphBadge` draw objects keyed by row content (the `Reroute` id-badge +pattern, memoized). `_boundingRect` hit-test state stays renderer-side. +Frame-budget parity per ADR 0008's render mitigations applies. + +## Implementation notes (slice A) + +- Registration is bucket-key presence: the `LGraph.add`/`remove`/`clear` + chokepoints call the import-light store trio + (`registerNode`/`unregisterNode`/`clearGraph`), and the system watches + `registeredNodeIds` to attach/detach per-node effect scopes. Litegraph + never imports the system, so the pricing/nodeDef dependency graph + (which runtime-imports the litegraph barrel) stays acyclic. The system + takes `resolveGraphId`/`resolveNode` seams and is bootstrapped once at + the app layer by the `Comfy.NodeBadge` extension (`useNodeBadge`). + The graph id is resolved live on every recompute because + `LGraph.clear()` and `configure()` reassign the root graph's id; a + captured id strands the system on a dead bucket. Row writes are + refused for unregistered nodes so a late effect flush cannot + resurrect a bucket key the chokepoints deleted. `LGraph.add` + registers the node only after `onNodeAdded`: the store write wakes + the system's watcher and queues Vue's flush microtask, which must not + overtake the paste-scan microtask `useErrorClearingHooks` enqueues + from `onNodeAdded`. +- One write path: the system replaces a node's rows wholesale via + `setBadges` on every recompute, so no intermediate per-kind state is + ever observable. +- The shell still reads `node.constructor.nodeData` and `node.inputs` + (untracked instance state) to map pricing input names to slot + indices — parity with the legacy closures. Those reads become store + lookups when slot data is store-backed (node data store draft). +- Core rows are fine-grained — one row per part, tagged + `part: 'lifecycle' | 'id' | 'source'` and carrying the raw projected + text — with one visibility rule (`badgeTextVisible`, the legacy + semantics: `HideBuiltIn` respected for every part). Each renderer owns + presentation: the legacy draw cache joins parts in id, lifecycle, + source order and truncates; the Vue partition trims lifecycle + brackets, and replaces a built-in node's source row with its + Comfy-logo chip. Known unification effect: the Vue renderer gains + `HideBuiltIn` handling for id and lifecycle badges on built-in nodes. +- A credits row is emitted only when the display price label is + non-empty; async pricing fills it via the per-node revision ref. + +## Implementation notes (slice B) + +- Wrapper `SubgraphNode` credits rows are aggregated by the system over + the inner (recursively collected, non-wrapper) api nodes — the same + count basis as the old unconditional per-api-node badges: several + collapse to `Partner Nodes x N` (localized), exactly one shows its + price with the wrapper's promoted widget values overriding the inner + node's own. The aggregation tracks the inner nodes' pricing + revisions, the registered-node set, and a structure revision. + `useNodePricing` caches labels per signature so a leaf's own read and + its wrapper's override read do not evict each other and re-schedule + forever. +- Legacy `drawBadges` renders the store rows through a per-node + memoized `LGraphBadge` cache (decision 5) keyed on the rows array's + identity — wholesale replacement makes identity the change signal, so + the per-frame path allocates nothing on cache hits. `iconKey` resolves + through a generic litegraph `badgeIconRegistry`, with the `credits` + icon registered when the system starts. +- The Vue renderer samples `node.badges` whenever its partition computed + re-runs; live array mutation and ticking thunks are visible per frame + only in the legacy canvas. Array interception was considered and + rejected: it cannot see thunk output changes (the dominant ecosystem + pattern), so it buys property patching without covering the real case. + If a pack demonstrably needs live Vue updates, the escalation is a + reactive accessor declared on `LGraphNode` itself, not renderer-side + `defineProperty`. + +## Resolved decisions (2026-07-06 interview) + +1. **Legacy `node.badges` surface — kept as a raw extension-only push + surface.** Directive: delete unless actively used. A GitHub-wide scan + found three custom-node packs actively writing it + (ComfyUI-Wildcard-Pipeline pushes and splices `LGraphBadge` + instances; ComfyUI-Enhancement-Utils and ComfyUI-XENodes push + per-frame getter thunks for ticking execution-time badges), so the + array stays, is no longer written by core/credits code, and both + renderers append it after the store rows — thunks still evaluate per + frame in the legacy canvas. The earlier "zero third-party writers" + scan was wrong. +2. **`node.badgePosition` — deleted**, along with the `BadgePosition` + enum. Zero uses outside this repo; the legacy canvas now always + renders badges top-right (the only surviving behaviour). A no-op + deprecated accessor remains and warns on access. +3. **Subgraph credits aggregation triggers — event-bumped revision.** + `litegraph:set-graph`, `subgraph-converted`, and + `afterConfigureGraph` bump `bumpSubgraphCreditsRevision()`; swap to + reactive `SubgraphStructure` dependencies when that state is + store-backed. Aggregation behaviour itself is preserved (explicit + user requirement). + +## Prototype: derive-on-read (2026-07-15) + +Badge rows are derived presentation, not authoritative entity state: +every row is a pure projection of settings, node definitions, palette, +pricing, and graph structure. Materializing that projection into a store +made the registration/watcher/scope machinery cache invalidation. The +prototype replaces the store with a memoized derivation: + +- `nodeBadges(node)` in `src/systems/badgeSystem.ts` — one lazy + `computed` per node instance in a `WeakMap`. Entries die with their + nodes (workflow loads create new instances), so registration, + unregistration, teardown, and the stale-bucket bug class do not exist. + `computeBadges` stays pure and data-first; the authoritative sources + of truth remain the settings/def/palette/pricing stores and the graph. +- `LGraph`'s ref-backed `id` and `_version` (bumped by + `incrementVersion()` at the `add`/`remove`/`clear` chokepoints and + read by the `nodes` getter) — the revision signals replacing store + bucket membership, `subgraphCreditsRevision`, and the live-graph-id + seams: graph-id-keyed reads and subgraph aggregation re-resolve after + loads and structural changes. Bumps only invalidate; recomputes happen + lazily on the next read. +- `registerBadgeRowsProvider` (in `nodeBadgeDraw.ts`) — a one-function seam + installed by `useNodeBadge`, so litegraph never imports the + derivation's pricing/nodeDef dependency graph (same acyclicity + property the store's import-light trio provided). The identity-keyed + draw cache is unchanged: a computed returns the same array until it + recomputes. + +Trade-offs accepted: badge rows are no longer enumerable per graph +(`PartnerNodesList` traverses the graph via `mapUniqueNodes` +instead of querying a bucket), and the structure revision is coarse — +any structural change invalidates all badge computeds, which is cheap +because invalidation is a flag and recomputation is per-read. + +**Outcome:** the store from slice (A) shipped and was then deleted — see +the derive-on-read update above. `src/systems/badgeSystem.ts` computes +badge rows from the stores that already own the inputs, and +`PartnerNodesList` calls `graphCreditsBadges(rootGraph)` rather than +querying a store by kind. The slice (B) consumer cutover happened as +planned; only the store itself did not survive. diff --git a/docs/architecture/node-data-store.md b/docs/architecture/node-data-store.md new file mode 100644 index 00000000000..6be1b7d3e00 --- /dev/null +++ b/docs/architecture/node-data-store.md @@ -0,0 +1,245 @@ +# Node Data Store + +Date: 2026-07-05 (last revised 2026-07-24) +Status: Implemented. Follow-up to the +[link topology store](link-topology-store.md) and +[reroute chain store](reroute-chain-store.md). + +Design record for extracting the remaining Node-owned components into a +dedicated store per [ADR 0008](../adr/0008-entity-component-system.md), +eliminating the `VueNodeData` mirror and, ultimately, all of +`src/composables/graph/useGraphNodeManager.ts`. + +## Decision 1: One store, one plain state object per node + +`nodeDataStore` holds a single plain `NodeState` object per node, +registered by reference with proxy-returning registration (the +`BaseWidget` pattern, [reroute store Decision 4](reroute-chain-store.md)). +ADR 0008's Node component rows (`NodeVisual`, `Execution`, ...) become +field groupings inside `NodeState`, not separate records or stores. + +The store uses the same flat root-scoped identity model as link and reroute +components: + +```text +RootGraphId -> { byId, idsByOwner } +``` + +The root key groups one loaded workflow. `byId` enforces root-wide node +identity, while `idsByOwner` provides direct owner-local lookup and teardown. +`graphId` is association data, not an identity namespace. Registered ids are +immutable; deletion also verifies component identity and owner. + +## Decision 2: Field set — what is NodeState, what is elsewhere + +```text +NodeState { + id: NodeId + graphId: UUID // owning (sub)graph association + locator ids + type: string // identity + title: string + titleMode?: TitleMode + mode: LGraphEventMode + flags: { collapsed?, pinned?, ghost? } + color?: string + bgcolor?: string + shape?: RenderShape + resizable?: boolean + showAdvanced?: boolean + inputs: INodeInputSlot[] + outputs: INodeOutputSlot[] +} +``` + +Excluded — owned or derived elsewhere; referencing them here would be a +mirror (the hard constraint of this phase): + +| Field | Owner | +| ----------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `selected` | `canvasStore.selectedNodeIds` (already what `LGraphNode.vue` reads) | +| `executing` | `executionStore` via `useNodeExecutionState` (already what Vue reads) | +| `hasErrors` | derived from `executionErrorStore` / missing-model/media stores; `node.has_errors` stays a legacy-canvas class field written by `useNodeErrorFlagSync` | +| position / size / z | `layoutStore` | +| widget values / order | `widgetValueStore` | +| input link connectivity | `linkStore` (`getInputSlotLink` / `isInputSlotConnected`) | +| `badges` | derived on read by `nodeBadges()` in `src/systems/badgeSystem.ts`; the badge store was shipped and then deleted — see [Node Badge Store](node-badge-store.md) | + +`VueNodeData.selected` and `.executing` are dead fields today (no +production consumer reads them); they are deleted, not migrated. + +## Decision 3: Slot identity deferred; `inputs[].link` readers migrate now + +`NodeInputSlot` / `NodeOutputSlot` are class instances with methods — +Slot entity extraction (ADR 0008 `SlotIdentity` etc.) is its own future +phase, so slot _identity_ stays class-side. + +Slot _reactivity_ does not wait for it, and is no longer a graft +(revised 2026-07-24; see ecs-migration-plan.md 2e). `LGraphNode.inputs` / +`.outputs` are accessors over `shallowReactive` arrays whose setters +replace contents in place, and `NodeSlot`'s constructor returns +`shallowReactive(this)`. Both live in the class, so every node is +reactive from construction whether or not the renderer is mounted, and +`makeReactiveNodeArrays`' runtime `Object.defineProperty` grafting is +deleted. Shallow is deliberate: nested values (`boundingRect`, `_widget`, +`pos`) stay raw so identity comparisons and `NodeInputSlot`'s `WeakMap` +index cache keep working. + +The slot arrays are fields on `NodeState`, held by reference rather than +copied. There is no per-slot key and no slot id: index is a property of the +containing array, and reorder operations mutate that array in place. + +What this phase does remove is the last `inputs[].link` dependency: the +three remaining readers (`nodeDataUtils.linkedWidgetedInputs` used by +`NodeSlots`, and `usePartitionedBadges`' badge computed plus its +exported `trackNodePrice`) move to `linkStore.isInputSlotConnected` +queries — presence is all any of them needed — which deletes the +`node:slot-links:changed` → `refreshNodeInputs` reprojection in +`useGraphNodeManager`, the dead `node:slot-errors:changed` handler +(zero emitters repo-wide), and the node-removal refresh-all loop. +With their last listeners gone, both trigger actions are deleted +outright — emitters, event-map entries, and types (the badge system +sources connectivity from `linkStore`, not events; resurrect from git +if a consumer ever materialises). Readers get the root graph id from +`canvasStore.rootGraphId`, the shared tracked accessor, rather than +per-site `canvas?.graph?.rootGraph.id` chains. +Shipped ahead of the store itself (2026-07-05). + +## Decision 4: Renderer consumes the NodeState proxy, `VueNodeData` dies + +`GraphCanvas` reads the active owning graph's bucket and passes the reactive +`NodeState` proxy down +the existing prop-drilling path (`LGraphNode` → `NodeHeader` / +`NodeSlots` / `NodeContent` / `NodeWidgets`). Children read proxy fields +directly; Vue tracks the store state, so the per-property +`node:property:changed` → snapshot-rewrite handlers in +`useGraphNodeManager` are deleted wholesale. + +Slot arrays reach `NodeSlots` through `NodeState`, not via +`getNodeByLocatorId`. + +`LGraphNodePreview` constructs a synthetic `NodeState` (as it does a +synthetic `VueNodeData` today). `AppModeWidgetList` stops calling +`extractVueNodeData` and reads the registered `NodeState` + live node. + +## Decision 5: Registration lifecycle and class adoption + +Follows the shipped trio convention (`LLink` / `Reroute`): + +- `LGraphNode` constructs its `_state: NodeState` at instantiation; + `registerNodeState(graph, node)` inserts it by reference and the class + adopts the returned reactive proxy; `node._graphScope` is the + registration-ownership marker. +- Chokepoints: `LGraph.add` / `LGraph.remove` (the canonical sites), + `unregisterAllNodeStates(graph)` on graph `clear()`, identity-checked + delete (`toRaw` compare) so only the registered state vacates its key. +- Class fields become accessors reading through `_state`. Reads go + through the reactive proxy directly (there is no `_stateRaw` raw view), + so `node.title` / `node.mode` / … track inside Vue effects, matching a + read of the store's `NodeState`. The one measured tight loop that reads + `id` per node — `LGraph.computeExecutionOrder` — hoists it to a local + once per iteration. + `LGraphNodeProperties`' instrumented descriptors keep their + get/set + `node:property:changed` emission but store the value in + `_state` instead of a closure — trigger consumers (minimap, + `useErrorClearingHooks`) keep working unchanged. +- `serialize()` / `toJSON` are unaffected: they read each field through + its accessor, so the wire format is identical. Raw enumeration is not — + see Decision 7. + +## Decision 6: useGraphNodeManager is deleted (revised 2026-07-24) + +Nothing remains. The original plan kept a slimmed successor for layout +seeding and slot reprojection; both were resolved instead: + +| Was | Now | +| -------------------------------------------------------- | ----------------------------------------------------------------------------------- | +| `extractVueNodeData`, `vueNodeData` map, `syncWithGraph` | deleted — renderer drills the `NodeState` proxy | +| `node:property:changed` snapshot-rewrite handlers | deleted — the proxy is already tracked | +| `getNode()` / `nodeRefs` | deleted — `nodeDataStore` for `flags.pinned`, `graph.getNodeById` for the live node | +| `node:slot-links:changed` handler | deleted — `linkStore.isInputSlotConnected` (Decision 3) | +| `makeReactiveNodeArrays` graft | deleted — reactivity is class-side from construction (Decision 3) | +| `node:slot-label:changed` array reprojection | deleted — slot objects are reactive, so `slot.label = …` is tracked | +| layoutStore seeding + `onAfterGraphConfigured` deferral | moved to `LGraph.add` / `LGraph.remove` | +| `onNodeAdded` replay loop over existing nodes | deleted — every node registers its own geometry as it attaches | + +Moving layout seeding to `LGraph.add` needed no configure-time deferral: +the entry is created with whatever geometry the node has, and the +`pos`/`size` setters (which already write through to `layoutStore`) update +it as `configure()` applies the real values. This follows the precedent +already set by `LGraph.createReroute`. + +Geometry now leaves the store the same way: `LGraph.remove` unregisters one +entry, and bulk teardown goes through one of two paths. A root graph's `clear` +calls `layoutStore.clearGraph(graphId)`, beside the five peer stores cleared +there, because layout is keyed by `rootGraphId` and so has a bucket to wipe. +Graphs that share the root's bucket — subgraphs, unconfigured graphs, and the +orphaned subgraph release — call `detachGraphLayouts` to drop entries +individually, mirroring `unregisterAllNodeStates` exactly. Both live in a +dedicated module so no teardown path re-derives the store writes by hand. + +`useVueNodeLifecycle` is gone; `GraphCanvas` owns only the Layout↔LiteGraph +sync lifecycle, and while the Vue renderer is on it drops view-scoped slot and +link geometry when the viewed graph changes. + +## Decision 7: Enumerability & extension migration (implemented 2026-07-22) + +Adopting `_state` moves the shell-state fields (`title`, `type`, `mode`, +`flags`, `color`, `bgcolor`, `resizable`, `shape`, `showAdvanced`) from +own enumerable data properties on each node to getter/setters on +`LGraphNode.prototype` backed by the store proxy. Consequences for +extension authors: + +- **Serialization and reactive reads are unchanged.** `serialize()` / + `toJSON` still emit every field (explicit accessor reads), and + `node.` reads/writes still work and are now reactive — reading + in a Vue effect tracks the store, writing goes through to it. +- **Raw enumeration no longer carries these fields.** They are prototype + accessors, not own properties, so for a non-instrumented node + `Object.keys(node)`, `{ ...node }`, `Object.assign({}, node)`, and + `JSON.stringify(node)` do not include them. (`LGraphNodeProperties` + instruments `title` / `mode` / `color` / `bgcolor` / `showAdvanced` + with own enumerable accessors, so those reappear on instrumented + nodes — do not rely on either behavior.) To snapshot shell state, read + the node's accessors or the registered `NodeState` from + `useNodeDataStore().getNode(rootGraphId, id)`, not a spread of the node. +- **`type` is now read-only.** It is a getter with no setter on every + node class; assigning `node.type = …` fails type-checking and throws in + strict mode. `type` is fixed at construction (`LiteGraph.createNode` / + the `LGraphNode(title, type)` constructor); deserialization sets it via + `configure`. Extensions that need a different type should create the + correct node rather than mutating an existing one. + +`inputs` and `outputs` became prototype accessors in the same way +(Decision 3), with the same enumeration consequence: they are absent from +`Object.keys(node)` and `{ ...node }`, but `serialize()` reads them +explicitly so the wire format is unchanged. Assigning +`node.inputs = [...]` still works and now replaces the array contents in +place rather than swapping the array. + +`node.widgets` remains a plain array, but its render order is owned by +`widgetValueStore`. `addWidget` / `addCustomWidget` / `removeWidget` keep +the two in step; a bare `node.widgets.splice(…)` does not, and the widget +will keep rendering until something else invalidates the computed. This +regressed deliberately — the previous self-healing came from a +`shallowReactive` reconciliation performed _during_ every `node.widgets` +read, which is exactly the augmentation this phase removes. Runtime +detection of a bare splice would require reinstating that proxy, so the +guidance is documented on the field instead of enforced. + +Extension migration map: read a field → `node.` (reactive) or +`useNodeDataStore().getNode(rootGraphId, node.id)`; snapshot all shell +state → read that `NodeState`, not `{ ...node }`; set `title` / `mode` / +colours / `flags` / `shape` / `showAdvanced` → assign the accessor (writes +through to the store); set `type` → construct the intended node type; +add or remove a widget → `node.addWidget` / `node.removeWidget`, not a +`node.widgets` splice. + +## Scope + +Covers node shell state, the `VueNodeData` deletion, and the +`inputs[].link` reader migration. Out of scope: Slot entity extraction, +`Properties` (`properties` / `properties_info`) and `NodeType` metadata +beyond `type`/`apiNode` (`category`, `nodeData`, `description` remain on +the class/constructor), badges, `WidgetContainer` (already owned by +`widgetValueStore`), and command-pattern mutators (future work per +ADR 0003/0008). diff --git a/docs/architecture/output-slot-connectivity.md b/docs/architecture/output-slot-connectivity.md new file mode 100644 index 00000000000..8f44652dd74 --- /dev/null +++ b/docs/architecture/output-slot-connectivity.md @@ -0,0 +1,252 @@ +# Output Slot Connectivity + +Date: 2026-07-06 +Status: Accepted (follow-up to the +[link topology store](link-topology-store.md); the minimal, non-breaking +slice of the deferred `SlotConnection` component work in the +[ECS migration plan](ecs-migration-plan.md)) + +Design record for answering "is this output slot connected, and by what +links?" from `linkStore` instead of the `output.links[]` mirror. It is +the output-side counterpart to the input-side migration shipped in +[node-data-store Decision 3](node-data-store.md) (#13455). Wiring it lets +`SlotConnectionDot` show connected state and removes the last renderer +dependency on `output.links[]`. + +This phase does not extract a Slot entity, add a store, or delete any +mirror field. Those stay in the deferred `SlotConnection` phase. What it +does is the smallest change that clears the reader debt and lets the +output dot show connection state. + +## Motivation + +`SlotConnectionDot.vue` colors slots by type only. It carries a +`//TODO Support connected/disconnected colors?`. `InputSlot` and +`OutputSlot` already declare `connected` / `compatible` props and apply +the `lg-slot--connected` / `lg-slot--compatible` classes, but +`NodeSlots.vue` passes neither, so the styling path is built but unwired. + +Input connectivity is already answerable through +`linkStore.isInputSlotConnected` (shipped in #13455). The matching output +query does not exist yet, so the output dot cannot be wired and +`output.links[]` stays the only source. This phase adds that query and +consumes it. + +## Decision 1: Extend `linkStore`, do not add a store or a Slot entity + +Output connectivity is link topology: the mirror image of the input side +the store already owns. It belongs in `linkStore`, not a new `slotStore`. +A dedicated Slot store (plain `SlotIdentity` / `SlotVisual` rows, retiring +the slot class instances) is the full `SlotConnection` phase and is out +of scope here. Introducing it now would be premature per the +node-data-store record, which keeps the slot arrays class-side. + +This phase adds read-only accessors over state the store already holds. +It needs no new plain-data component, registration trio, chokepoint, or +class adoption, though each sibling store required all four. + +## Decision 2: Output connectivity is a derived reverse index + +The store already exposes `graphTopologies(graphId)` over every +registered `LinkTopology`. "Which links leave output slot _(node, slot)_" +is a reverse index over origin endpoints. This is the same pattern +`rerouteStore` uses for link membership +([reroute store](reroute-chain-store.md)): a per-graph cached `computed` +that Vue invalidates when link state changes. Nothing is stored, so the +membership is always derived and cannot drift from the topology. + +```ts +type OriginIndex = Map< + OriginSlotKey /* `${originNodeId}:${originSlot}` */, + Set +> + +const outputIndexes = new Map>() + +function outputIndex(graphId: UUID): ComputedRef { + const existing = outputIndexes.get(graphId) + if (existing) return existing + const next = computed(() => { + const index: OriginIndex = new Map() + for (const t of graphTopologies(graphId)) { + if (isFloatingTopology(t)) continue + const key = originKey(t.originNodeId, t.originSlot) + const links = index.get(key) ?? new Set() + links.add(t) + index.set(key, links) + } + return index + }) + outputIndexes.set(graphId, next) + return next +} +``` + +The index is populated from the owner-scoped topology collection. Floating +links are skipped (`isFloatingTopology`): the queries see fully-assigned links +only, matching the mirror they replace (Decision 6). A `SUBGRAPH_INPUT_ID` +origin indexes like any other id. + +## Decision 3: Two public queries, mirroring the input pair + +```ts +isOutputSlotConnected(graphId, nodeId, slot): boolean +getOutputSlotLinks(graphId, nodeId, slot): ReadonlySet +``` + +These match `isInputSlotConnected` / `getInputSlotLink` in name and shape. +The input side returns a single `LinkTopology`, since at most one link targets +an input; the output side returns a set, since an output fans out to many. The +set holds topologies rather than bare `LinkId`s because readers need endpoints, +and because `graph.links` deliberately exposes only fully-assigned links. +Floating and fully-assigned links share one root-wide ID namespace and topology +collection; endpoint state determines which compatibility view and indexes +expose them. + +## Decision 4: Migrate readers incrementally, keep the mirror written by hand + +This follows the #13455 discipline for `input.link`: move the readers to +the store, leave the field in place, and keep writing it at the +chokepoints. + +`output.links[]` has roughly 200 read sites but only about 12 write +sites, all in `LGraphNode`, `LGraph`, and the subgraph paths. Most of the +reads are litegraph-internal graph algorithms such as traversal, dedup, +and serialization. Those can keep reading the mirror indefinitely; they +are not renderer policy and nothing blocks on them. + +Migrated readers: the output dot's connected state (`NodeSlots`), the +minimap link extraction (`AbstractMinimapDataSource`), the drag-start +disconnect check (`useSlotLinkInteraction`, where one store query replaces +a mirror read plus a `slotFloatingLinks` scan), widget value propagation +(`widgetValuePropagation`), and matchType link revalidation +(`dynamicWidgets.changeOutputType`). + +## Decision 5: Wire connected state into the dots (the payoff) + +`NodeSlots.vue` passes `connected` to each slot: + +- input: `linkStore.isInputSlotConnected(rootGraphId, nodeId, index)` + (already available) +- output: `linkStore.isOutputSlotConnected(rootGraphId, nodeId, index)` + (Decision 3) + +`InputSlot` and `OutputSlot` already forward `connected` to the +`lg-slot--connected` class. `SlotConnectionDot` needs no prop of its own: +the wrapper class is an ancestor styling hook +(`.lg-slot--connected .slot-dot`), so the visual is one CSS rule away once +the design-standards check (open question 3) picks it. Threading a +`connected` prop into the dot before that would be plumbing with no +consumer. `compatible` stays driven by the existing drag state +(`useSlotLinkDragUIState`), which this phase leaves alone. + +## Decision 6: Delete the mirrors (implemented; extended to `input.link`) + +The runtime `output.links[]` field and all nine of its write sites are +deleted. The same recipe has since been applied to `input.link`: the +field is a deprecated warning getter, litegraph and app code read through +the slotLinks input helpers (`inputHasLink`, `inputLinkId`, `inputLink`) +or `node.isInputConnected` / `node.getInputLink`, serialization derives +`inputs[].link` from the store, and the mirror-carried association +shuffles were reworked — `LGraph.configure()` realigns serialized input +slots through `realignInputLinkSlots`, dynamicWidgets' group rebuilds carry +slot→link association +in a module-scoped WeakMap refreshed from the store, and link +deduplication selects survivors from the store registration (the +`repairInputLinks` mirror repair is gone; the derived view cannot be +wrong). The store is the single source; litegraph internals read through +the pure helpers in `node/slotLinks.ts` (`outputHasLinks`, +`outputLinkIds`, `outputLinks`), and `NodeOutputSlot.isConnected`, +`serialize`, and `configure` derive from the store. Details: + +- **Wire format unchanged.** `outputAsSerialisable` / `toJSON` emit the + serialized `outputs[].links` array from the store, sorted ascending by + id (a determinism choice — equal to push order for organically built + graphs) and `null` when empty. `configure` fires its output + `onConnectionsChange` callbacks from the serialized argument. +- **Floating links are never returned by link queries.** They are + reroute-chain scaffolding, named by `isFloatingTopology` + (`src/types/linkTopology.ts`). `isOutputSlotConnected` / + `getOutputSlotLinks` see fully-assigned links only, matching the + mirror they replace; the one consumer with legacy floating-aware + behavior (the slot-drag disconnect check) keeps its own + `slotFloatingLinks` scan. +- **Extension compat = deprecation telemetry, not compatibility.** A + read-only prototype getter on `NodeOutputSlot` returns a fresh + store-derived `LinkId[] | null` and fires `warnDeprecated`. Writes fire + their own `warnDeprecated` naming the replacement APIs + (`node.connect()` / `node.disconnectOutput()`) and are otherwise + ignored — the store stays authoritative and legacy writers degrade + gracefully instead of crashing. A bare accessor-only property would + instead throw an unactionable `TypeError` in strict mode. + `INodeOutputSlot` keeps `links` as `@deprecated readonly` so + `'links' in slot` discriminants still compile and hold at runtime via + the prototype. The mirror keys are non-enumerable: `{ ...slot }`, + `Object.assign({}, slot)`, and `Object.keys(slot)` do not carry + `link` / `links` (use the store queries to snapshot connectivity); + `JSON.stringify` still emits them via `toJSON`. `addInput` / `addOutput` + drop a stale `link` / `links` key from `extra_info` instead of letting + `Object.assign` collide with the accessor — the store is not consulted + or mutated by such values. +- **Duck-typed slots are upgraded in place.** `_setConcreteSlots` writes + the concrete `NodeInputSlot` / `NodeOutputSlot` wrappers back into + `node.inputs` / `node.outputs`. The concrete classes resolve their slot + index by identity (`inputs.indexOf(this)`), so a wrapper that is not + the array entry would permanently read as disconnected. Plain-object + slots pushed directly into the arrays are therefore upgraded at the + next concretisation (`configure`, paste/convert paths, every canvas + draw); until then their stale `link` value is dead data. Extensions + should use `node.addInput()` / `node.addOutput()` instead of pushing + literals. +- **Serialized-data operators are untouched.** `linkFixer` (serialized + branch), `migrateReroute`, and `unpackSubgraph`'s pre-configure strip + operate on the wire format, which still carries `links`. +- **Behavior changes, deliberate:** `PrimitiveNode.onLastDisconnect` + fires on disconnect-all (the stale mirror previously suppressed it); + `disconnectInput` passes `link_info.origin_slot` — not the old + mirror-array index — as the OUTPUT slot in `onConnectionsChange`; + serialization emits `null` where a lingering `[]` used to persist. + +Extension migration map: presence → `node.isOutputConnected(slot)` / +`slot.isConnected`; enumerate targets → `node.getOutputNodes(slot)`; +enumerate links → `outputLinks(graph, node.id, slot)` / `outputLinkIds` +(`node/slotLinks.ts`); mutate → `node.connect(...)` / +`node.disconnectOutput(slot, target?)`. App/Vue code uses +`useLinkStore().getOutputSlotLinks(...)` (reactive). + +## Scope + +In scope: the derived output-side index, the two queries, the output-dot +reader migration, and wiring `connected` from `NodeSlots` into +`InputSlot` / `OutputSlot` (whose `lg-slot--connected` class reaches the +dot via CSS). + +Since implemented by Decision 6: `output.links` reader migration, write +sites, and field deletion — and the same for `input.link` (PR 13498). + +Out of scope, each a piece of the deferred `SlotConnection` phase: + +- Slot entity extraction: `SlotIdentity`, `SlotVisual`, and retiring the + `NodeInputSlot` / `NodeOutputSlot` class instances and their + `shallowReactive` graft. +- A `compatible`-state source beyond the current drag UI state. +- Floating/regular link-id counter unification (mint floating ids from + the shared `state.lastLinkId`) — only if the internal wart ever bites; + nothing resolves store-returned ids against `graph.links` across the + id spaces anymore. + +## Open questions + +1. **Index granularity.** One `computed` per graph rebuilds the whole + origin index on any link change in that graph, the same cost model as + `rerouteStore`. If profiling on large graphs shows this is hot, the + fallback is an incrementally maintained `Map` updated in `place` and + `displace`, which is more code and carries drift risk. Start with the + derived version and measure before optimizing. +2. **Return type of `getOutputSlotLinks`.** Resolved: a set of + `LinkTopology`, per Decision 3. Bare ids looked sufficient until the + reader migration surfaced both the endpoint needs (minimap, widget + value propagation) and the floating-id collision hazard. +3. **Dot visual.** What "connected" looks like on the dot (fill, ring, or + opacity) is a design-standards question rather than an architecture + one. Check the Comfy Design Standards before implementing Decision 5. diff --git a/docs/architecture/proto-ecs-stores.md b/docs/architecture/proto-ecs-stores.md index e9bd74ca7f9..1a610c125f8 100644 --- a/docs/architecture/proto-ecs-stores.md +++ b/docs/architecture/proto-ecs-stores.md @@ -6,20 +6,45 @@ For the full problem analysis, see [Entity Problems](entity-problems.md). For th ## 1. What's Already Extracted -Six dedicated stores extract entity state out of class instances into focused, +Nine dedicated stores extract entity state out of class instances into focused, queryable registries, each owning one concern. Promoted value-widget topology is no longer a store; ADR 0009 represents it as ordinary linked `SubgraphInput` state, and promoted value data lives in `WidgetValueStore` keyed by the input's `WidgetId`. -| Store | Extracts From | Scoping | Key Format | Data Shape | -| ----------------------- | ------------------- | ----------------- | ---------------------------------- | ----------------------------- | -| WidgetValueStore | `BaseWidget` | `graphId` | `WidgetId` (`graphId:nodeId:name`) | Plain `WidgetState` object | -| DomWidgetStore | `BaseDOMWidget` | Global | `widgetId` (UUID) | Position, visibility, z-index | -| LayoutStore | Node, Link, Reroute | Workflow-level | `nodeId`, `linkId`, `rerouteId` | Y.js CRDT maps (pos, size) | -| NodeOutputStore | Execution results | `nodeLocatorId` | `"${subgraphId}:${nodeId}"` | Output data, preview URLs | -| SubgraphNavigationStore | Canvas viewport | `subgraphId` | `subgraphId` or `'root'` | LRU viewport cache | -| PreviewExposureStore | Subgraph host node | host node locator | host locator + exposure name | Display-only preview state | +| Store | Extracts From | Scoping | Key Format | Data Shape | +| ----------------------- | ----------------------------------- | ------------------------------ | ------------------------------------------------------------------ | ----------------------------- | +| WidgetValueStore | `BaseWidget` | `graphId` | `WidgetId` (`graphId:nodeId:name`) | Plain `WidgetState` object | +| DomWidgetStore | `BaseDOMWidget` | Global | `widgetId` (UUID) | Position, visibility, z-index | +| LayoutStore | Node, Link, Group, Reroute geometry | Root graph for groups/reroutes | Raw node/link IDs; `${rootGraphId}:${localId}` for groups/reroutes | Y.js CRDT maps (pos, size) | +| NodeOutputStore | Execution results | `nodeLocatorId` | `"${subgraphId}:${nodeId}"` | Output data, preview URLs | +| SubgraphNavigationStore | Canvas viewport | `subgraphId` | `subgraphId` or `'root'` | LRU viewport cache | +| PreviewExposureStore | Subgraph host node | host node locator | host locator + exposure name | Display-only preview state | +| LinkStore | `LLink` | Root and owning graph | `LinkId` primary; owner-qualified target/origin indexes | Plain `LinkTopology` object | +| RerouteStore | `Reroute` | Root graph | `RerouteId` | Plain `RerouteChain` object | +| NodeDataStore | `LGraphNode` shell state | Root graph | `NodeId` | Plain `NodeState` object | + +**Update (2026-07-05):** `LinkStore` (`src/stores/linkStore.ts`, PR #13436) and +`RerouteStore` (`src/stores/rerouteStore.ts`, PR #13449) hold plain-data records +in reactive `Map` buckets — not Y.js — scoped by root graph (subgraphs share +their root's bucket). Every link topology lives in one root-wide identity map; +owner and endpoint indexes provide graph-local iteration and connectivity +queries. Design records: +[Link Topology Store](link-topology-store.md), +[Reroute Chain Store](reroute-chain-store.md). + +**Update (2026-07-22):** `NodeDataStore` (`src/stores/nodeDataStore.ts`) holds +one plain `NodeState` per node in root-graph-scoped buckets keyed by `NodeId`. +`LGraphNode` adopts the store's reactive proxy as its `_state` and its shell +fields become accessors over it, so there is no copy. This deleted the +`VueNodeData` mirror and all of `useGraphNodeManager`. Design record: +[Node Data Store](node-data-store.md). + +**Update (2026-07-14, reversed):** `NodeBadgeStore` shipped in PR #13458 and was +then deleted — badge rows are cheaper to derive on read than to store, so +`src/systems/badgeSystem.ts` computes them from the stores that already own the +inputs. There is no `src/stores/nodeBadgeStore.ts`. See +[Node Badge Store](node-badge-store.md) for the reversal. ADR 0009 refines promoted-widget identity: promoted value widgets are keyed by the host boundary (`host node locator + SubgraphInput.name`), while interior @@ -148,42 +173,43 @@ The most architecturally advanced extraction — uses Y.js CRDTs for collaborati ### State Shape ``` -ynodes: Y.Map // nodeId → { pos, size, zIndex, bounds } -ylinks: Y.Map> // linkId → link layout data -yreroutes: Y.Map> // rerouteId → reroute layout data +ynodes: Y.Map // nodeId → { rect, zIndex } +ygroups: Y.Map // rootGraphId:groupId → geometry + +yreroutes: Y.Map> // rootGraphId:rerouteId → { id, position } ``` -### Write API +**Update (2026-07-05):** The link-connectivity mirror (`ylinks`, `LinkData`, +`createLink`/`removeLink` mutations, `findLinksConnectedToNode`) was deleted +when link topology moved to `LinkStore` (PR #13436). LayoutStore now owns only +link/segment _geometry_ caches, and `RerouteData` carries `{ id, position }` +only — the write-only `parentId`/`linkIds` fields were removed. -`useLayoutMutations()` (`src/renderer/core/layout/operations/layoutMutations.ts`) provides the mutation API: +### Write API -- `moveNode(graphId, nodeId, pos)` -- `resizeNode(graphId, nodeId, size)` -- `setNodeZIndex(graphId, nodeId, zIndex)` -- `createLink(graphId, linkId, ...)` -- `removeLink(graphId, linkId)` -- `moveReroute(graphId, rerouteId, pos)` +`useLayoutMutations(source)` (`src/renderer/core/layout/operations/layoutMutations.ts`) provides the mutation API: -### The Scattered Access Problem +- `moveNode(nodeId, pos)` / `batchMoveNodes(...)` +- `setNodeZIndex(nodeId, zIndex)` / `bringNodeToFront(nodeId)` -This composable is called at **module scope** in domain objects: +Entity lifecycle and legacy geometry proxies submit commands through +`graphLayoutAttachment`; link topology is `LinkStore`'s concern. -- `LLink.ts:24` — `const layoutMutations = useLayoutMutations()` -- `Reroute.ts` — same pattern -- `LGraphNode.ts` — imported and called in methods +### Attachment boundary -These module-scope calls create implicit dependencies on the Vue runtime and make the domain objects untestable without a full app context. +`graphLayoutAttachment` owns the temporary instance-to-store bridge. Domain +objects do not instantiate the mutation composable at module scope. ### ECS Alignment -| Aspect | ECS-like | Why | -| ---------------------------- | --------- | ------------------------------------------------------- | -| Position data extracted | Yes | Closest to the ECS `Position` component | -| CRDT-ready | Yes | Enables collaboration (ADR 0003) | -| Covers multiple entity kinds | Yes | Nodes, links, reroutes in one store | -| Mutation API (composable) | Partially | System-like, but called from entities, not a system | -| Module-scope access | **No** | Domain objects import store at module level | -| Per-store keying | Yes | Owns `nodeId`/`linkId`/`rerouteId` keys for its concern | +| Aspect | ECS-like | Why | +| ---------------------------- | --------- | --------------------------------------------------------- | +| Position data extracted | Yes | Closest to the ECS `Position` component | +| CRDT-ready | Yes | Enables collaboration (ADR 0003) | +| Covers multiple entity kinds | Yes | Nodes, links, groups, reroutes in one store | +| Mutation API (composable) | Partially | System-like, but called from entities, not a system | +| Module-scope access | **No** | Domain objects import store at module level | +| Per-store keying | Yes | Uses raw node/link IDs and root-scoped group/reroute keys | ## 5. Pattern Analysis @@ -234,12 +260,14 @@ graph TD Each store owns the identity scheme that fits its concern: -| Store | Key Format | Key Type | Type-Safe? | -| ---------------- | ---------------------------------- | ------------------ | ---------------- | -| WidgetValueStore | `WidgetId` (`graphId:nodeId:name`) | branded string | Yes (`WidgetId`) | -| DomWidgetStore | Widget UUID | UUID (string) | No | -| LayoutStore | Raw nodeId/linkId/rerouteId | Mixed number types | No | -| NodeOutputStore | `"${subgraphId}:${nodeId}"` | Composite string | No | +| Store | Key Format | Key Type | Type-Safe? | +| ---------------- | ------------------------------------------------------------------ | ---------------- | ----------------- | +| WidgetValueStore | `WidgetId` (`graphId:nodeId:name`) | branded string | Yes (`WidgetId`) | +| DomWidgetStore | Widget UUID | UUID (string) | No | +| LayoutStore | Raw node/link IDs; `${rootGraphId}:${localId}` for groups/reroutes | Mixed/composite | Partially | +| NodeOutputStore | `"${subgraphId}:${nodeId}"` | Composite string | No | +| LinkStore | `` `${targetNodeId}:${targetSlot}` `` (root-scoped buckets) | Composite string | No | +| RerouteStore | `RerouteId` (root-scoped buckets) | branded number | Yes (`RerouteId`) | `WidgetValueStore` already keys on a branded `WidgetId` string (`src/types/widgetId.ts`), which carries its scope and survives renames at the store layer. The remaining @@ -286,30 +314,31 @@ graph TD subgraph Link["LLink"] L_ext["Extracted: -- layout data → LayoutStore"] +- id, endpoints, type, parentId → LinkStore + (LLink._state IS the store entry; + fields are accessors over it) +- segment geometry → LayoutStore"] L_rem["Remains on class: -- origin_id, target_id -- origin_slot, target_slot -- type, color, path +- color, path, _pos, _centreAngle - data, _dragging - disconnect(), resolve()"] end subgraph Reroute["Reroute"] R_ext["Extracted: -- pos → LayoutStore"] +- pos → LayoutStore (sole truth) +- parentId, floating → RerouteStore +- linkIds, floatingLinkIds → derived + from links' parentId chains"] R_rem["Remains on class: -- parentId, linkIds -- floatingLinkIds -- color, draw() +- colour, draw() - findSourceOutput()"] end subgraph Group["LGraphGroup"] G_ext["Extracted: -(nothing)"] +- pos, size, bounding → LayoutStore"] G_rem["Remains on class: -- pos, size, bounding - title, font, color - _children, _nodes - draw(), move() @@ -331,7 +360,7 @@ graph TD style W_ext fill:#1a4a1a,stroke:#2a6a2a,color:#e0e0e0 style L_ext fill:#1a4a1a,stroke:#2a6a2a,color:#e0e0e0 style R_ext fill:#1a4a1a,stroke:#2a6a2a,color:#e0e0e0 - style G_ext fill:#4a1a1a,stroke:#6a2a2a,color:#e0e0e0 + style G_ext fill:#1a4a1a,stroke:#2a6a2a,color:#e0e0e0 style S_ext fill:#1a4a1a,stroke:#2a6a2a,color:#e0e0e0 style N_rem fill:#4a1a1a,stroke:#6a2a2a,color:#e0e0e0 @@ -346,15 +375,19 @@ graph TD What each entity needs to reach the ECS target from [ADR 0008](../adr/0008-entity-component-system.md): -| Entity | Already Extracted | Still on Class | ECS Target Components | Gap | -| ------------ | -------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------ | -| **Node** | pos, size (LayoutStore) | type, visual, connectivity, execution, properties, widgets, rendering, serialization | Position, NodeVisual, NodeType, Connectivity, Execution, Properties, WidgetContainer | Large — 6 components unextracted, all behavior on class | -| **Link** | layout (LayoutStore) | endpoints, visual, state, connectivity methods | LinkEndpoints, LinkVisual, LinkState | Medium — 3 components unextracted | -| **Widget** | value, label, disabled (WidgetValueStore); DOM state (DomWidgetStore) | node back-ref, rendering, events, layout | WidgetIdentity, WidgetValue, WidgetLayout | Small — value extraction done; rendering and layout remain | -| **Slot** | (nothing) | name, type, direction, link refs, visual, position | SlotIdentity, SlotConnection, SlotVisual | Full — no extraction started | -| **Reroute** | pos (LayoutStore) | links, visual, chain traversal | Position, RerouteLinks, RerouteVisual | Medium — position done, rest unextracted | -| **Group** | (nothing) | pos, size, meta, visual, children | Position, GroupMeta, GroupVisual, GroupChildren | Full — no extraction started | -| **Subgraph** | promoted value exposure (linked inputs); preview exposure (PreviewExposureStore) | structure, meta, I/O, all LGraph state | SubgraphStructure, SubgraphMeta (as node components) | Large — mostly unextracted; subgraph is a node with components, not a separate entity kind | +| Entity | Already Extracted | Still on Class | ECS Target Components | Gap | +| ------------ | ----------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------ | +| **Node** | pos, size (LayoutStore) | type, visual, connectivity, execution, properties, widgets, rendering, serialization | Position, NodeVisual, NodeType, Connectivity, Execution, Properties, WidgetContainer | Large — 6 components unextracted, all behavior on class | +| **Link** | endpoints, type, parentId (LinkStore, via `_state` proxy); segment geometry (LayoutStore) | visual (color, path), drag state, connectivity methods | LinkEndpoints ✅, LinkVisual, LinkState | Small — topology shipped (PR #13436); visual state and slot mirrors remain | +| **Widget** | value, label, disabled (WidgetValueStore); DOM state (DomWidgetStore) | node back-ref, rendering, events, layout | WidgetIdentity, WidgetValue, WidgetLayout | Small — value extraction done; rendering and layout remain | +| **Slot** | (nothing) | name, type, direction, link refs, visual, position | SlotIdentity, SlotConnection, SlotVisual | Full — no extraction started | +| **Reroute** | parentId, floating (RerouteStore); pos (LayoutStore, sole truth) | visual, chain traversal | Position ✅, RerouteChain ✅, RerouteVisual | Small — chain shipped (PR #13449); visual remains | +| **Group** | pos, size, bounding (LayoutStore) | meta, visual, children | Position ✅, GroupMeta, GroupVisual, GroupChildren | Medium — geometry shipped; meta, visual and children remain | +| **Subgraph** | promoted value exposure (linked inputs); preview exposure (PreviewExposureStore) | structure, meta, I/O, all LGraph state | SubgraphStructure, SubgraphMeta (as node components) | Large — mostly unextracted; subgraph is a node with components, not a separate entity kind | + +`RerouteChain` supersedes the earlier `RerouteLinks` component (ADR 0008 +amendment, 2026-07-04): link membership is never stored — it is derived from +the links' `parentId` chains over `LinkStore`. ### Priority Order for Extraction @@ -362,8 +395,12 @@ Based on existing progress and problem severity: 1. **Widget** — closest to done (value extraction complete, needs rendering/layout extraction) 2. **Node Position** — already in LayoutStore, needs branded ID and formal component type -3. **Link** — small component set, high coupling pain +3. **Link** — ✅ topology shipped (LinkStore, PR #13436); slot mirrors + (`input.link`/`output.links`) and visual state remain 4. **Slot** — no extraction yet, but small and self-contained -5. **Reroute** — partially extracted, moderate complexity -6. **Group** — no extraction, but least coupled to other entities + (`SlotConnection` input side now answerable via LinkStore) +5. **Reroute** — ✅ chain and position shipped (RerouteStore, PR #13449; + LayoutStore, PR #14110); visual remains +6. **Group** — ✅ geometry shipped (LayoutStore, PR #14110); meta, visual and + children remain 7. **Subgraph** — not a separate entity kind; SubgraphStructure and SubgraphMeta become node components. Depends on Node and Link extraction first. See [Subgraph Boundaries](subgraph-boundaries-and-promotion.md) diff --git a/docs/architecture/reroute-chain-store.md b/docs/architecture/reroute-chain-store.md new file mode 100644 index 00000000000..075e9953a2a --- /dev/null +++ b/docs/architecture/reroute-chain-store.md @@ -0,0 +1,130 @@ +# Reroute Chain Store + +Date: 2026-07-04 +Status: Accepted (design review; follow-up to the +[link topology store](link-topology-store.md), PR #13436) + +Design record for extracting reroute connectivity state into a dedicated +store per [ADR 0008](../adr/0008-entity-component-system.md). Amends the +`RerouteLinks` component described there. + +## Decision 1: The chain is the single source of truth for membership + +"Which links pass through reroute R" is encoded twice today: each link's +`parentId` chain (`link.parentId` names the terminal reroute; +`reroute.parentId` walks upstream), and per-reroute `linkIds` / +`floatingLinkIds` Sets maintained by hand at roughly ten write sites +(`LGraphNode.connect`, `LLink.disconnect`, `LGraph.addFloatingLink` / +`removeFloatingLink` / `createReroute`, subgraph unpack, +`SubgraphInput/Output.connect`, `LinkConnector`), with +`Reroute.validateLinks` repairing drift at configure time. + +The chain is primary. Membership becomes a derived reverse index: + +```text +linksThrough(R) = { L : R ∈ chain(L.parentId) } +``` + +computed over the link store's topologies plus the reroute chain states, +cached, and invalidated on chain mutation. The `Reroute` class exposes +`linkIds` / `floatingLinkIds` as derived accessors. The membership write +sites and `validateLinks` are deleted. + +Rejected: storing membership Sets in the store (the `LLink._state` +pattern applied to whole membership). It keeps one _stored_ copy but +preserves the domain-level redundancy — chain and membership can still +disagree, and every dual write site survives. + +## Decision 2: Store shape and keying + +`rerouteStore` holds per-reroute chain state objects, registered by +reference (the class reads through them, mirroring `LLink._state`): + +```text +RerouteChain { id, graphId, parentId?, floating? } +``` + +Buckets use the shared graph-scoped lifecycle: + +```text +RootGraphId -> { chains, idsByOwner, membershipByOwner } +``` + +The root key groups one loaded workflow. `chains` is a flat root-wide identity +map; `idsByOwner` is a secondary index for owner-local lookup and teardown. +`graphId` associates a chain with its owning graph without namespacing its +identity. + +`RerouteId` is the domain key because runtime allocation is already +per-root-unique: `Subgraph.state` delegates to the root graph's state, so +all graphs increment one shared `lastRerouteId` counter. + +## Decision 3: Load-time reroute-id dedup + +Serialized workflows from older frontends or external tools can carry +colliding reroute ids anywhere in one root graph. Registration does not +overwrite the incumbent, so import repairs those collisions before +registration. + +On configure, colliding subgraph reroute ids are rewritten to fresh ids +from the shared counter, patching that subgraph's `link.parentId` and +`reroute.parentId` references — the same repair the node-id and link-id +dedup passes already perform. Rewritten ids serialize back changed. + +Rejected: a first-wins registration protocol (losers detached via an +ownership flag). That is the apparatus the target-keyed link store +redesign existed to delete. + +## Decision 4: Registration returns the reactive proxy + +The derived membership index requires observable chain mutation. +`BaseWidget` already establishes the pattern: the store bucket is a +`reactive(Map)`, registration inserts the raw state and returns the +value read back from the map — the reactive proxy — and the class holds +that proxy as `_state` (`BaseWidget.setNodeId`, +`widgetValueStore.registerWidget`). Every subsequent class write goes +through the proxy and is tracked. + +`rerouteStore.registerReroute` follows this: it returns the proxy when +registration succeeds or the same chain is already registered, and returns +`undefined` when another chain owns the id. This matches `registerLink`; both +APIs leave a colliding state detached instead of returning the incumbent. +The `Reroute` class reads and writes chain state through a successful proxy, +so `reroute.parentId` mutations are tracked with no action chokepoint. + +Each root bucket keeps one derived membership `ComputedRef` per owner. The +chain map and owner indexes are reactive, so chain, link, and lifecycle changes +invalidate the relevant membership view. + +`LLink` previously deviated — `registerLinkTopology` left `link._state` +raw, which is why `linkStore.updateEndpoint` must re-wrap with +`reactive()` before patching, and why bare `link.parentId` writes were +invisible to effects. This migration aligns it with the `BaseWidget` +pattern: link registration re-assigns `_state` to the store proxy, +making `link.parentId` writes tracked. `updateEndpoint` keeps its +`reactive()` wrap as a guard — the store is public API and may be +handed a raw topology object. + +## Decision 5: Serialization + +`SerialisableReroute.linkIds` remains in the wire format, emitted from +the derived membership in ascending link-id order. All runtime producers +append links in ascending id order and the serialization goldens hold +ascending arrays, so chain-consistent workflows round-trip byte-identical. + +Workflows whose stored `linkIds` contradict their chains are repaired on +the next save (membership re-derived, stale ids dropped, order +normalized). A reroute that no chain reaches at all is dropped at load — +where `validateLinks` used to preserve it if its stored ids named live +links — because the chain is primary. No compatibility shim for such +files. `floatingLinkIds` stays unserialized, rebuilt at runtime as +before. + +## Scope + +This design covers chain state, derived membership, and the `LLink` +proxy retrofit from Decision 4 (a small self-contained change, done +first). Reroute visual state (`_colour`, badge) is out of scope. The +`Reroute.pos` class field still mirrors the layout store's position; +that pre-existing duplication is a separate concern, not addressed +here. diff --git a/docs/extensions/README.md b/docs/extensions/README.md index a2e144adf4c..7898ffe0752 100644 --- a/docs/extensions/README.md +++ b/docs/extensions/README.md @@ -17,6 +17,7 @@ Extensions are the primary way to add functionality to ComfyUI. They can be cust - Hook execution sequence - Best practices for extension development - **[Node ID Migration Notes](./node-id-migration.md)** - Compatibility guidance for branded node IDs and subgraph boundary sentinel values +- **[Link Registration Migration Notes](./link-registration-migration.md)** - Guidance for handling defensive floating-link registration failures ## Quick Links diff --git a/docs/extensions/link-registration-migration.md b/docs/extensions/link-registration-migration.md new file mode 100644 index 00000000000..ff5882a53fe --- /dev/null +++ b/docs/extensions/link-registration-migration.md @@ -0,0 +1,48 @@ +# Link Registration Migration Notes + +`LinkNetwork.addFloatingLink(link)` now returns `LLink | undefined`. + +For a new runtime link, pass the unassigned link id and use the returned link: + +```ts +const registeredLink = graph.addFloatingLink(link) +if (!registeredLink) return +``` + +Registration returns the stored link when it succeeds or when the same link is +already present in the topology store. If another runtime link already owns the +id, registration logs an error, leaves the incoming link detached, and returns +`undefined`. It does not silently replace the live link or assign the incoming +link another identity. `graph.floatingLinks` remains the filtered compatibility +view for one-ended links. + +`graph.links` and `graph.floatingLinks` are owner-filtered, store-backed +compatibility views rather than independent native `Map` storage. Their normal +`Map` read methods use a cached membership snapshot; acquire a new iterator +after topology membership changes instead of retaining an existing iterator. +Both views require an active Pinia and no longer represent a missing store as +an empty graph. + +Like native `Map.set()`, `view.set(id, link)` returns the view, not a registration +result. Registration can reject an ID or target collision while preserving the +incumbent, so extensions that insert through a view should confirm success with +`get()` or `has()`. Prefer graph connection and floating-link APIs when they +cover the operation because those APIs coordinate the surrounding lifecycle. +Do not invoke `Map.prototype` methods directly against either view or depend on +native `Map` internal storage. + +Input replacement commits the new link before old-link disconnect callbacks, +so callback queries see the replacement rather than an empty input. Normal +connection callbacks follow. + +Extensions that previously ignored the return value should handle +`undefined` before retaining, rendering, or mutating the incoming link. Do not +preselect a positive link id for a new runtime link; allow the graph to mint +one. + +Persisted-id collision repair belongs to workflow import and +deserialization. Extensions importing serialized topology should normalize +conflicting ids at that boundary before using the runtime registration API. + +Constructing a root `LGraph`, or configuring one from serialized data, requires +an active Pinia because graph topology is store-backed throughout its lifecycle. diff --git a/playwright.config.ts b/playwright.config.ts index db1e49094e4..3febc879dca 100644 --- a/playwright.config.ts +++ b/playwright.config.ts @@ -40,7 +40,7 @@ export default defineConfig({ { name: 'chromium', use: { ...devices['Desktop Chrome'] }, - timeout: 15000, + timeout: 15_000, grepInvert: /@mobile|@perf|@audit|@cloud/ }, diff --git a/src/components/builder/AppModeWidgetList.vue b/src/components/builder/AppModeWidgetList.vue index 61de44ba4e0..535d0161d68 100644 --- a/src/components/builder/AppModeWidgetList.vue +++ b/src/components/builder/AppModeWidgetList.vue @@ -7,10 +7,11 @@ import { useAppModeWidgetResizing } from '@/components/builder/useAppModeWidgetR import { useResolvedSelectedInputs } from '@/components/builder/useResolvedSelectedInputs' import Popover from '@/components/ui/Popover.vue' import Button from '@/components/ui/button/Button.vue' -import { extractVueNodeData } from '@/composables/graph/useGraphNodeManager' import type { LGraphNode } from '@/lib/litegraph/src/LGraphNode' import { LGraphEventMode } from '@/lib/litegraph/src/types/globalEnums' import type { IBaseWidget } from '@/lib/litegraph/src/types/widgets' +import { deriveWidgetRenderState } from '@/lib/litegraph/src/utils/widget' +import type { WidgetId } from '@/types/widgetId' import { useMaskEditor } from '@/composables/maskeditor/useMaskEditor' import { extractWidgetStringValue } from '@/composables/maskeditor/useMaskEditorLoader' import { appendCloudResParam } from '@/platform/distribution/cloudPreviewUtil' @@ -19,6 +20,9 @@ import NodeWidgets from '@/renderer/extensions/vueNodes/components/NodeWidgets.v import { api } from '@/scripts/api' import { app } from '@/scripts/app' import { useExecutionErrorStore } from '@/stores/executionErrorStore' +import { useLinkStore } from '@/stores/linkStore' +import { graphScopeOf } from '@/types/graphScopeId' +import { useWidgetValueStore } from '@/stores/widgetValueStore' import { useAppModeStore } from '@/stores/appModeStore' import { parseImageWidgetValue } from '@/utils/imageUtil' import { cn } from '@comfyorg/tailwind-utils' @@ -29,9 +33,8 @@ import { promptRenameWidget } from '@/utils/widgetUtil' interface WidgetEntry { key: string persistedHeight: number | undefined - nodeData: ReturnType & { - widgets: NonNullable['widgets']> - } + nodeData: ReturnType + widgetIds: readonly WidgetId[] action: { widget: IBaseWidget; node: LGraphNode } description?: string } @@ -44,6 +47,8 @@ const { mobile = false, builderMode = false } = defineProps<{ const { t } = useI18n() const executionErrorStore = useExecutionErrorStore() const appModeStore = useAppModeStore() +const widgetValueStore = useWidgetValueStore() +const linkStore = useLinkStore() const maskEditor = useMaskEditor() const { onPointerDown } = useAppModeWidgetResizing((widget, config) => @@ -55,50 +60,62 @@ provide(WidgetHeightKey, mobile ? 'h-10' : 'h-7') const resolvedInputs = useResolvedSelectedInputs() -const mappedSelections = computed((): WidgetEntry[] => { - const nodeDataByNode = new Map< - LGraphNode, - ReturnType - >() +function ensureSelectedWidgetState( + widgetId: WidgetId, + widget: IBaseWidget +): void { + if (widgetValueStore.getWidget(widgetId)) return + widgetValueStore.registerWidget( + widgetId, + { + type: widget.type, + value: widget.value, + options: widget.options, + label: widget.label, + serialize: widget.serialize, + disabled: widget.disabled + }, + deriveWidgetRenderState(widget) + ) +} + +function isWidgetInputLinked(node: LGraphNode, widgetName: string): boolean { + const graph = node.graph + const slot = node.inputs?.findIndex((i) => i.widget?.name === widgetName) + if (!graph || slot === undefined || slot < 0) return false + return linkStore.isInputSlotConnected(graphScopeOf(graph), node.id, slot) +} + +const mappedSelections = computed((): WidgetEntry[] => { return resolvedInputs.value.flatMap((entry) => { if (entry.status !== 'resolved') return [] const { widgetId, node, widget, config } = entry if (node.mode !== LGraphEventMode.ALWAYS) return [] - if (!nodeDataByNode.has(node)) { - nodeDataByNode.set(node, nodeToNodeData(node)) - } - const fullNodeData = nodeDataByNode.get(node)! - - const matchingWidget = fullNodeData.widgets?.find((vueWidget) => { - if (vueWidget.slotMetadata?.linked) return false - return vueWidget.widgetId === widgetId - }) - if (!matchingWidget) return [] - - matchingWidget.slotMetadata = undefined - matchingWidget.nodeId = node.id + ensureSelectedWidgetState(widgetId, widget) + const fullNodeData = nodeToNodeData(node, widgetId) + if (isWidgetInputLinked(node, widget.name)) return [] return [ { key: widgetId, persistedHeight: config?.height, description: config?.description, - nodeData: { - ...fullNodeData, - widgets: [matchingWidget] - }, + nodeData: fullNodeData, + widgetIds: [widgetId], action: { widget, node } } ] }) }) -function getDropIndicator(node: LGraphNode) { +function getDropIndicator(node: LGraphNode, id: WidgetId) { if (node.type !== 'LoadImage') return undefined - const stringValue = extractWidgetStringValue(node.widgets?.[0]?.value) + const stringValue = extractWidgetStringValue( + widgetValueStore.getWidget(id)?.value + ) const { filename, subfolder, type } = stringValue ? parseImageWidgetValue(stringValue) @@ -122,12 +139,11 @@ function getDropIndicator(node: LGraphNode) { } } -function nodeToNodeData(node: LGraphNode) { - const dropIndicator = getDropIndicator(node) - const nodeData = extractVueNodeData(node) +function nodeToNodeData(node: LGraphNode, id: WidgetId) { + const dropIndicator = getDropIndicator(node, id) return { - ...nodeData, + ...node._state, hasErrors: !!executionErrorStore.surfacedNodeErrors?.[node.id], dropIndicator, onDragDrop: node.onDragDrop, @@ -154,6 +170,7 @@ defineExpose({ handleDragDrop }) key, persistedHeight, nodeData, + widgetIds, action, description } in mappedSelections" @@ -261,6 +278,7 @@ defineExpose({ handleDragDrop }) > @@ -157,8 +153,7 @@ import WorkflowTabs from '@/components/topbar/WorkflowTabs.vue' import { useChainCallback } from '@/composables/functional/useChainCallback' import { useGroupContextMenu } from '@/composables/graph/useGroupContextMenu' import { installErrorClearingHooks } from '@/composables/graph/useErrorClearingHooks' -import type { VueNodeData } from '@/composables/graph/useGraphNodeManager' -import { useVueNodeLifecycle } from '@/composables/graph/useVueNodeLifecycle' +import type { NodeState } from '@/types/nodeState' import { useNodeBadge } from '@/composables/node/useNodeBadge' import { useCanvasDrop } from '@/composables/useCanvasDrop' import { useContextMenuTranslation } from '@/composables/useContextMenuTranslation' @@ -166,6 +161,7 @@ import { useCopy } from '@/composables/useCopy' import { useGlobalLitegraph } from '@/composables/useGlobalLitegraph' import { usePaste } from '@/composables/usePaste' import { useVueFeatureFlags } from '@/composables/useVueFeatureFlags' +import type { LGraph } from '@/lib/litegraph/src/litegraph' import { LiteGraph } from '@/lib/litegraph/src/litegraph' import { useLitegraphSettings } from '@/platform/settings/composables/useLitegraphSettings' import { CORE_SETTINGS } from '@/platform/settings/constants/coreSettings' @@ -175,8 +171,11 @@ import { useWorkflowService } from '@/platform/workflow/core/services/workflowSe import { useWorkflowStore } from '@/platform/workflow/management/stores/workflowStore' import { useWorkflowAutoSave } from '@/platform/workflow/persistence/composables/useWorkflowAutoSave' import { useWorkflowPersistenceV2 as useWorkflowPersistence } from '@/platform/workflow/persistence/composables/useWorkflowPersistenceV2' +import { useNodeDataStore } from '@/stores/nodeDataStore' import { useCanvasStore } from '@/renderer/core/canvas/canvasStore' import { useCanvasInteractions } from '@/renderer/core/canvas/useCanvasInteractions' +import { arrangeForLegacyRender } from '@/renderer/core/canvas/litegraph/arrangeForLegacyRender' +import { notifyLayoutChanges } from '@/renderer/core/canvas/litegraph/notifyLayoutChanges' import { layoutStore } from '@/renderer/core/layout/store/layoutStore' import TransformPane from '@/renderer/core/layout/transform/TransformPane.vue' import type { StartupOutcome } from '@/platform/workflow/persistence/base/draftTypes' @@ -184,6 +183,7 @@ import { useFirstRunEntry } from '@/renderer/extensions/firstRunTour/gettingStar import MiniMap from '@/renderer/extensions/minimap/MiniMap.vue' import LGraphNode from '@/renderer/extensions/vueNodes/components/LGraphNode.vue' import { requestSlotLayoutSyncForAllNodes } from '@/renderer/extensions/vueNodes/composables/useSlotElementTracking' +import { orderNodesForPainting } from '@/renderer/extensions/vueNodes/utils/nodePaintOrder' import { UnauthorizedError } from '@/scripts/api' import { app as comfyApp } from '@/scripts/app' import { ChangeTracker } from '@/scripts/changeTracker' @@ -222,7 +222,7 @@ const workspaceStore = useWorkspaceStore() const { isBuilderMode } = useAppMode() const canvasStore = useCanvasStore() const workflowStore = useWorkflowStore() -const { linearMode } = storeToRefs(canvasStore) +const { linearMode, selectedNodeIds } = storeToRefs(canvasStore) const executionStore = useExecutionStore() const executionErrorStore = useExecutionErrorStore() const toastStore = useToastStore() @@ -259,9 +259,6 @@ const minimapEnabled = computed(() => settingStore.get('Comfy.Minimap.Visible')) // Feature flags const { shouldRenderVueNodes } = useVueFeatureFlags() -// Vue node system -const vueNodeLifecycle = useVueNodeLifecycle() - // Error-clearing hooks run regardless of rendering mode (Vue or legacy canvas). let cleanupErrorHooks: (() => void) | null = null watch( @@ -272,28 +269,68 @@ watch( } ) -const handleVueNodeLifecycleReset = async () => { - if (shouldRenderVueNodes.value) { - vueNodeLifecycle.disposeNodeManagerAndSyncs() - await nextTick() - vueNodeLifecycle.initializeNodeManager() - } +function exitToLegacyRendering(graph: LGraph | null) { + layoutStore.clearViewGeometry() + if (graph) arrangeForLegacyRender(graph) + canvasStore.canvas?.setDirty(true, true) } -watch(() => canvasStore.currentGraph, handleVueNodeLifecycleReset) +watch( + [shouldRenderVueNodes, () => canvasStore.currentGraph], + ([enabled, graph], previous) => { + if (enabled) { + layoutStore.clearViewGeometry() + } else if (previous?.[0]) { + exitToLegacyRendering(graph) + } + }, + { immediate: true } +) + +watchEffect((onCleanup) => { + if (!shouldRenderVueNodes.value) return + + const canvas = canvasStore.canvas + if (canvas) onCleanup(notifyLayoutChanges(canvas)) +}) watch( () => canvasStore.isInSubgraph, - async (newValue, oldValue) => { + (newValue, oldValue) => { if (oldValue && !newValue) { useWorkflowStore().updateActiveGraph() } - await handleVueNodeLifecycleReset() } ) -const allNodes = computed((): VueNodeData[] => - Array.from(vueNodeLifecycle.nodeManager.value?.vueNodeData?.values() ?? []) +const nodeDataStore = useNodeDataStore() +const allNodes = computed((): NodeState[] => { + const { rootGraphId } = canvasStore + const graphId = canvasStore.currentGraph?.id + if (!rootGraphId || graphId === undefined) return [] + return nodeDataStore.getGraphNodesFor(rootGraphId, graphId) +}) + +const nodeLayouts = computed(() => { + const { rootGraphId } = canvasStore + if (!rootGraphId) return new Map() + + return new Map( + allNodes.value.flatMap(({ id }) => { + const layout = layoutStore.getNodeLayoutRef(rootGraphId, id).value + return layout ? [[id, layout] as const] : [] + }) + ) +}) +const nodePaintOrder = computed( + () => + new Map( + orderNodesForPainting( + allNodes.value, + nodeLayouts.value, + selectedNodeIds.value + ).map((node, index) => [node.id, index]) + ) ) watch( () => linearMode.value, @@ -555,8 +592,6 @@ onMounted(async () => { cleanupErrorHooks = installErrorClearingHooks(comfyApp.canvas.graph) } - vueNodeLifecycle.setupEmptyGraphListener() - // Load color palette colorPaletteStore.customPalettes = settingStore.get( 'Comfy.CustomColorPalettes' @@ -605,7 +640,6 @@ onMounted(async () => { onUnmounted(() => { cleanupErrorHooks?.() cleanupErrorHooks = null - vueNodeLifecycle.cleanup() }) function forwardPointerDownPanEvent(e: PointerEvent) { forwardPanEvent(e, isMiddlePointerInput) diff --git a/src/components/graph/widgets/DomWidget.test.ts b/src/components/graph/widgets/DomWidget.test.ts index e4ed2516568..32cdb704db3 100644 --- a/src/components/graph/widgets/DomWidget.test.ts +++ b/src/components/graph/widgets/DomWidget.test.ts @@ -82,11 +82,22 @@ function createWidgetState(disabled: boolean): DomWidgetState { return reactive(state) } -describe('DomWidget disabled style', () => { +describe('DomWidget style', () => { afterEach(() => { useDomWidgetStore().clear() }) + it('positions a newly mounted widget', () => { + const widgetState = createWidgetState(false) + render(DomWidget, { + props: { + widgetState + } + }) + + expect(mockUpdatePosition).toHaveBeenCalledWith(widgetState) + }) + it('uses disabled style when widget is computedDisabled', async () => { const widgetState = createWidgetState(true) const { container } = render(DomWidget, { diff --git a/src/components/graph/widgets/DomWidget.vue b/src/components/graph/widgets/DomWidget.vue index 194c84af6df..28279f4c40e 100644 --- a/src/components/graph/widgets/DomWidget.vue +++ b/src/components/graph/widgets/DomWidget.vue @@ -123,7 +123,7 @@ watch( } composeStyle() }, - { deep: true } + { deep: true, immediate: true } ) // Recompose style when clippingStyle updates asynchronously via RAF. diff --git a/src/components/graph/widgets/domWidgetZIndex.test.ts b/src/components/graph/widgets/domWidgetZIndex.test.ts index d70578844cf..a3aa1301c77 100644 --- a/src/components/graph/widgets/domWidgetZIndex.test.ts +++ b/src/components/graph/widgets/domWidgetZIndex.test.ts @@ -1,9 +1,13 @@ import { fromPartial } from '@total-typescript/shoehorn' -import { describe, expect, it } from 'vitest' +import { createTestingPinia } from '@pinia/testing' +import { setActivePinia } from 'pinia' +import { beforeEach, describe, expect, it } from 'vitest' import { LGraph, LGraphNode } from '@/lib/litegraph/src/litegraph' import { getDomWidgetZIndex } from './domWidgetZIndex' +beforeEach(() => setActivePinia(createTestingPinia({ stubActions: false }))) + describe('getDomWidgetZIndex', () => { it('follows graph node ordering when node.order is stale', () => { const graph = new LGraph() diff --git a/src/components/rightSidePanel/errors/useErrorGroups.test.ts b/src/components/rightSidePanel/errors/useErrorGroups.test.ts index 9f2de184a17..7237c409573 100644 --- a/src/components/rightSidePanel/errors/useErrorGroups.test.ts +++ b/src/components/rightSidePanel/errors/useErrorGroups.test.ts @@ -1271,7 +1271,9 @@ describe('useErrorGroups', () => { // A container selection matches interior errors by execution-id prefix, // even when the interior node does not resolve at the current level. const containerNode = fromAny( - Object.assign(Object.create(SubgraphNode.prototype), { id: '2' }) + Object.assign(Object.create(SubgraphNode.prototype), { + _state: { id: '2' } + }) ) vi.mocked(getNodeByExecutionId).mockReturnValue(null) vi.mocked(getExecutionIdByNode).mockReturnValue( diff --git a/src/components/rightSidePanel/errors/useErrorGroups.ts b/src/components/rightSidePanel/errors/useErrorGroups.ts index 66549b0b8a8..0313e684954 100644 --- a/src/components/rightSidePanel/errors/useErrorGroups.ts +++ b/src/components/rightSidePanel/errors/useErrorGroups.ts @@ -728,7 +728,10 @@ export function useErrorGroups(searchQuery: MaybeRefOrGetter) { const candidates = missingModelStore.missingModelCandidates if (!candidates?.length) return [] const matched = candidates.filter( - (c) => c.nodeId != null && isAssetCandidateInSelection(c.nodeId) + (c) => + (c.nodeId != null && isAssetCandidateInSelection(c.nodeId)) || + (c.sourceExecutionId != null && + isAssetCandidateInSelection(c.sourceExecutionId)) ) if (!matched.length) return [] return groupMissingModelCandidates(matched, isCloud) diff --git a/src/components/rightSidePanel/parameters/SectionWidgets.vue b/src/components/rightSidePanel/parameters/SectionWidgets.vue index 37748639d51..e81509ccebb 100644 --- a/src/components/rightSidePanel/parameters/SectionWidgets.vue +++ b/src/components/rightSidePanel/parameters/SectionWidgets.vue @@ -12,8 +12,6 @@ import { import { useI18n } from 'vue-i18n' import Button from '@/components/ui/button/Button.vue' -import { widgetPromotedSource } from '@/core/graph/subgraph/promotedInputWidget' -import { isWidgetPromotedOnSubgraphNode } from '@/core/graph/subgraph/promotionUtils' import { resolvePromotedWidgetSource } from '@/core/graph/subgraph/resolvePromotedWidgetSource' import type { LGraphGroup, LGraphNode } from '@/lib/litegraph/src/litegraph' import { SubgraphNode } from '@/lib/litegraph/src/litegraph' @@ -46,12 +44,12 @@ const { isDraggable = false, hiddenFavoriteIndicator = false, showNodeName = false, - parents = [], + host, enableEmptyState = false, tooltip } = defineProps<{ label?: string - parents?: SubgraphNode[] + host?: SubgraphNode node?: LGraphNode widgets: { widget: IBaseWidget; node: LGraphNode }[] showLocateButton?: boolean @@ -146,31 +144,6 @@ const { t } = useI18n() const getNodeParentGroup = inject(GetNodeParentGroupKey, null) -function isWidgetShownOnParents( - widgetNode: LGraphNode, - widget: IBaseWidget -): boolean { - const source = widgetPromotedSource(widgetNode, widget) - return parents.some((parent) => { - if (source) { - const widgetNodeId = widgetNode.id - const interiorNodeId = - String(widgetNode.id) === String(parent.id) - ? source.nodeId - : widgetNodeId - - return isWidgetPromotedOnSubgraphNode(parent, { - sourceNodeId: interiorNodeId, - sourceWidgetName: source.widgetName - }) - } - return isWidgetPromotedOnSubgraphNode(parent, { - sourceNodeId: widgetNode.id, - sourceWidgetName: widget.name - }) - }) -} - const isEmpty = computed(() => widgets.value.length === 0) const displayLabel = computed( @@ -262,7 +235,10 @@ function clearWidgetErrors( source.sourceWidgetName, source.sourceWidgetName, value, - options + { + min: source.sourceWidget.options?.min, + max: source.sourceWidget.options?.max + } ) } @@ -407,13 +383,12 @@ defineExpose({ diff --git a/src/components/rightSidePanel/parameters/TabSubgraphInputs.test.ts b/src/components/rightSidePanel/parameters/TabSubgraphInputs.test.ts index 32d6c03ce26..b50ef3c1f52 100644 --- a/src/components/rightSidePanel/parameters/TabSubgraphInputs.test.ts +++ b/src/components/rightSidePanel/parameters/TabSubgraphInputs.test.ts @@ -31,7 +31,7 @@ const captured: { rows: { node: LGraphNode; widget: IBaseWidget }[] } = { } const SectionWidgetsStub = { - props: ['widgets', 'node', 'parents'], + props: ['widgets', 'node', 'host'], setup(props: Record) { captured.rows = props.widgets as { node: LGraphNode diff --git a/src/components/rightSidePanel/parameters/TabSubgraphInputs.vue b/src/components/rightSidePanel/parameters/TabSubgraphInputs.vue index 4ebb5a28727..95e83dc97ac 100644 --- a/src/components/rightSidePanel/parameters/TabSubgraphInputs.vue +++ b/src/components/rightSidePanel/parameters/TabSubgraphInputs.vue @@ -5,7 +5,6 @@ import { useI18n } from 'vue-i18n' import { promotedInputWidgets } from '@/core/graph/subgraph/promotedInputWidget' import { - getWidgetName, isWidgetPromotedOnSubgraphNode, reorderSubgraphInputsByWidgetOrder } from '@/core/graph/subgraph/promotionUtils' @@ -83,13 +82,11 @@ const advancedInputsWidgets = computed((): NodeWidgetsList => { ({ node: interiorNode, widget }) => !isWidgetPromotedOnSubgraphNode(node, { sourceNodeId: interiorNode.id, - sourceWidgetName: getWidgetName(widget) + sourceWidgetName: widget.name }) ) }) -const parents = computed(() => [node]) - const searchedWidgetsList = shallowRef(widgetsList.value) const isSearching = ref(false) @@ -140,7 +137,7 @@ const label = computed(() => { :collapse="firstSectionCollapsed && !isSearching" :node :label - :parents + :host="node" :widgets="searchedWidgetsList" :is-draggable="!isSearching" :enable-empty-state="isSearching" @@ -164,7 +161,7 @@ const label = computed(() => { ref="advancedInputsSectionRef" v-model:collapse="advancedInputsCollapsed" :label="t('rightSidePanel.advancedInputs')" - :parents="parents" + :host="node" :widgets="advancedInputsWidgets" show-node-name class="border-b border-interface-stroke" diff --git a/src/components/rightSidePanel/parameters/WidgetActions.test.ts b/src/components/rightSidePanel/parameters/WidgetActions.test.ts index e56080f87f9..9899b0b0103 100644 --- a/src/components/rightSidePanel/parameters/WidgetActions.test.ts +++ b/src/components/rightSidePanel/parameters/WidgetActions.test.ts @@ -1,13 +1,19 @@ import { render, screen } from '@testing-library/vue' +import { createTestingPinia } from '@pinia/testing' import userEvent from '@testing-library/user-event' import { fromAny } from '@total-typescript/shoehorn' +import { setActivePinia } from 'pinia' import type { Slots } from 'vue' import { h } from 'vue' import { beforeEach, describe, expect, it, vi } from 'vitest' import { createI18n } from 'vue-i18n' +import { promoteWidget } from '@/core/graph/subgraph/promotionUtils' import type { LGraphNode } from '@/lib/litegraph/src/litegraph' +import type { SubgraphNode } from '@/lib/litegraph/src/subgraph/SubgraphNode' import type { IBaseWidget } from '@/lib/litegraph/src/types/widgets' +import { useWidgetValueStore } from '@/stores/widgetValueStore' +import { widgetId } from '@/types/widgetId' import WidgetActions from './WidgetActions.vue' const { @@ -23,9 +29,7 @@ const { })) vi.mock('@/core/graph/subgraph/promotionUtils', () => ({ - demoteWidget: vi.fn(), - promoteWidget: vi.fn(), - isLinkedPromotion: vi.fn(() => false) + promoteWidget: vi.fn() })) vi.mock('@/stores/nodeDefStore', () => ({ @@ -74,7 +78,6 @@ const i18n = createI18n({ enterNewName: 'Enter new name' }, rightSidePanel: { - hideInput: 'Hide input', showInput: 'Show input', addFavorite: 'Favorite', removeFavorite: 'Unfavorite', @@ -86,11 +89,13 @@ const i18n = createI18n({ describe('WidgetActions', () => { beforeEach(() => { + setActivePinia(createTestingPinia({ stubActions: false })) + vi.resetAllMocks() + mockIsFavorited.mockReturnValue(false) mockGetInputSpecForWidget.mockReturnValue({ type: 'INT', default: 42 }) - mockIsFavorited.mockReturnValue(false) }) function createMockWidget( @@ -171,6 +176,21 @@ describe('WidgetActions', () => { expect(screen.getByRole('button', { name: /Reset/ })).toBeDisabled() }) + it('keeps reset enabled when the store value is null and differs from the default', () => { + const node = createMockNode() + const id = widgetId('graph-test', node.id, 'test_widget') + useWidgetValueStore().registerWidget(id, { + type: 'number', + value: null, + options: {} + }) + const widget = { ...createMockWidget(42), widgetId: id } as IBaseWidget + + renderWidgetActions(widget, node) + + expect(screen.getByRole('button', { name: /Reset/ })).toBeEnabled() + }) + it('does not show reset button when no default value exists', () => { mockGetInputSpecForWidget.mockReturnValue({ type: 'CUSTOM' @@ -258,4 +278,57 @@ describe('WidgetActions', () => { source: 'right_side_panel' }) }) + + it('promotes the widget into the host when "Show input" is clicked', async () => { + const widget = createMockWidget() + const node = createMockNode() + const host = fromAny({ id: 2 }) + + const { user } = renderWidgetActions(widget, node, { host }) + + await user.click(screen.getByRole('button', { name: /Show input/ })) + + expect(promoteWidget).toHaveBeenCalledWith(node, widget, [host]) + }) + + it('does not offer "Show input" without a host', () => { + renderWidgetActions(createMockWidget(), createMockNode()) + + expect( + screen.queryByRole('button', { name: /Show input/ }) + ).not.toBeInTheDocument() + }) + + it('does not offer "Show input" when the host input is already linked', () => { + const widget = createMockWidget() + const node = fromAny({ + id: 1, + type: 'TestNode', + rootGraph: { id: 'graph-test' }, + isSubgraphNode: () => true, + getSlotFromWidget: (candidate: IBaseWidget) => + candidate.name === 'test_widget' + ? { widgetId: 'graph-test:1:test_widget' } + : undefined + }) + const host = fromAny({ id: 2 }) + + renderWidgetActions(widget, node, { host }) + + expect( + screen.queryByRole('button', { name: /Show input/ }) + ).not.toBeInTheDocument() + }) + + it("toggles the favorite for the row's node", async () => { + const widget = createMockWidget() + const node = createMockNode() + const host = fromAny({ id: 2 }) + + const { user } = renderWidgetActions(widget, node, { host }) + + await user.click(screen.getByRole('button', { name: /Favorite/ })) + + expect(mockToggleFavorite).toHaveBeenCalledWith(node, 'test_widget') + }) }) diff --git a/src/components/rightSidePanel/parameters/WidgetActions.vue b/src/components/rightSidePanel/parameters/WidgetActions.vue index de55cfe9db8..8b920c09c86 100644 --- a/src/components/rightSidePanel/parameters/WidgetActions.vue +++ b/src/components/rightSidePanel/parameters/WidgetActions.vue @@ -5,34 +5,22 @@ import { useI18n } from 'vue-i18n' import MoreButton from '@/components/button/MoreButton.vue' import Button from '@/components/ui/button/Button.vue' -import { widgetPromotedSource } from '@/core/graph/subgraph/promotedInputWidget' -import { - demotePromotedInput, - demoteWidget, - isLinkedPromotion, - promoteWidget -} from '@/core/graph/subgraph/promotionUtils' +import { inputForWidget } from '@/core/graph/subgraph/promotedInputWidget' +import { promoteWidget } from '@/core/graph/subgraph/promotionUtils' import type { LGraphNode } from '@/lib/litegraph/src/litegraph' import type { SubgraphNode } from '@/lib/litegraph/src/subgraph/SubgraphNode' import type { IBaseWidget } from '@/lib/litegraph/src/types/widgets' import { useTelemetry } from '@/platform/telemetry' -import { useCanvasStore } from '@/renderer/core/canvas/canvasStore' import { useNodeDefStore } from '@/stores/nodeDefStore' import { useWidgetValueStore } from '@/stores/widgetValueStore' import { useFavoritedWidgetsStore } from '@/stores/workspace/favoritedWidgetsStore' import { getWidgetDefaultValue, promptWidgetLabel } from '@/utils/widgetUtil' import type { WidgetValue } from '@/utils/widgetUtil' -const { - widget, - node, - parents = [], - isShownOnParents = false -} = defineProps<{ +const { widget, node, host } = defineProps<{ widget: IBaseWidget node: LGraphNode - parents?: SubgraphNode[] - isShownOnParents?: boolean + host?: SubgraphNode }>() const emit = defineEmits<{ @@ -41,24 +29,17 @@ const emit = defineEmits<{ const label = defineModel('label', { required: true }) -const canvasStore = useCanvasStore() const favoritedWidgetsStore = useFavoritedWidgetsStore() const nodeDefStore = useNodeDefStore() const { t } = useI18n() -const hasParents = computed(() => parents?.length > 0) const isLinked = computed(() => { if (!node.isSubgraphNode()) return false - const source = widgetPromotedSource(node, widget) - if (!source) return false - return isLinkedPromotion(node, source.nodeId, source.widgetName) + return inputForWidget(node, widget)?.widgetId != null }) -const canToggleVisibility = computed(() => hasParents.value && !isLinked.value) -const favoriteNode = computed(() => - isShownOnParents && hasParents.value ? parents[0] : node -) +const canShowInput = computed(() => host != null && !isLinked.value) const isFavorited = computed(() => - favoritedWidgetsStore.isFavorited(favoriteNode.value, widget.name) + favoritedWidgetsStore.isFavorited(node, widget.name) ) const inputSpec = computed(() => @@ -69,12 +50,11 @@ const defaultValue = computed(() => getWidgetDefaultValue(inputSpec.value)) const hasDefault = computed(() => defaultValue.value !== undefined) -const currentValue = computed( - () => - (widget.widgetId && - useWidgetValueStore().getWidget(widget.widgetId)?.value) ?? - widget.value -) +const currentValue = computed(() => { + if (!widget.widgetId) return widget.value + const state = useWidgetValueStore().getWidget(widget.widgetId) + return state ? state.value : widget.value +}) const isCurrentValueDefault = computed(() => { if (!hasDefault.value) return true @@ -86,41 +66,20 @@ async function handleRename() { if (newLabel !== null) label.value = newLabel } -function handleHideInput() { - if (!parents?.length) return - - const source = widgetPromotedSource(node, widget) - if (source) { - const currentNodeId = node.id - for (const parent of parents) { - const sourceNodeId = - String(node.id) === String(parent.id) ? source.nodeId : currentNodeId - demotePromotedInput(parent, { - sourceNodeId, - sourceWidgetName: source.widgetName - }) - } - canvasStore.canvas?.setDirty(true, true) - } else { - demoteWidget(node, widget, parents) - } -} - function handleShowInput() { - if (!parents?.length) return - promoteWidget(node, widget, parents) + if (!host) return + promoteWidget(node, widget, [host]) } function handleToggleFavorite() { - const willBeFavorited = !isFavorited.value useTelemetry()?.trackWidgetFavoriteToggled({ - node_type: favoriteNode.value.type, + node_type: node.type, widget_name: widget.name, widget_type: widget.type, - is_favorited: willBeFavorited, + is_favorited: !isFavorited.value, source: 'right_side_panel' }) - favoritedWidgetsStore.toggleFavorite(favoriteNode.value, widget.name) + favoritedWidgetsStore.toggleFavorite(node, widget.name) } function handleResetToDefault() { @@ -152,26 +111,19 @@ function handleResetToDefault() {