From b5a3053208ce62a519ea5ad8824bfe0c32ef8280 Mon Sep 17 00:00:00 2001 From: Christian Byrne Date: Mon, 31 Aug 2026 02:43:28 +0000 Subject: [PATCH 01/14] Fix agent CRDT follower review gaps --- .../components/agent/DockedAgentPanel.test.ts | 5 +++ .../components/agent/DockedAgentPanel.vue | 2 + .../extensions/agent/crdt/linkMintPort.ts | 25 ++++++----- .../agent/crdt/mintPortWiring.test.ts | 43 ++++++++++++++++++- .../extensions/agent/crdt/opSender.test.ts | 32 +++++++++++++- .../extensions/agent/crdt/opSender.ts | 29 +++++++++++++ .../agent/crdt/useAgentCrdtFollower.ts | 11 +---- 7 files changed, 124 insertions(+), 23 deletions(-) diff --git a/src/workbench/extensions/agent/components/agent/DockedAgentPanel.test.ts b/src/workbench/extensions/agent/components/agent/DockedAgentPanel.test.ts index 706506e8639..1a8f148aa7b 100644 --- a/src/workbench/extensions/agent/components/agent/DockedAgentPanel.test.ts +++ b/src/workbench/extensions/agent/components/agent/DockedAgentPanel.test.ts @@ -5,6 +5,7 @@ import { beforeEach, describe, expect, it, vi } from 'vitest' import { defineComponent, nextTick, ref } from 'vue' import { i18n } from '@/i18n' +import { WORKSPACE_INSET_RIGHT } from '@/composables/useWorkspaceInset' import type { TurnId } from '@/workbench/extensions/agent/schemas/agentApiSchema' import { useAgentConversationStore } from '@/workbench/extensions/agent/stores/agent/agentConversationStore' import { useAgentPanelStore } from '@/workbench/extensions/agent/stores/agent/agentPanelStore' @@ -50,6 +51,7 @@ describe('DockedAgentPanel', () => { beforeEach(() => { setActivePinia(createPinia()) localStorage.clear() + document.documentElement.style.removeProperty(WORKSPACE_INSET_RIGHT) rootLiveness.live = 0 rootLiveness.maxLive = 0 }) @@ -66,6 +68,9 @@ describe('DockedAgentPanel', () => { timeout: 5000 }) ).toBeTruthy() + expect( + document.documentElement.style.getPropertyValue(WORKSPACE_INSET_RIGHT) + ).toBe(`${store.width}px`) }) it('T-30 / PM-654 / FE-1285 fills the panel opaquely and draws the canvas seam border', () => { diff --git a/src/workbench/extensions/agent/components/agent/DockedAgentPanel.vue b/src/workbench/extensions/agent/components/agent/DockedAgentPanel.vue index 97c27f2920e..1c475705898 100644 --- a/src/workbench/extensions/agent/components/agent/DockedAgentPanel.vue +++ b/src/workbench/extensions/agent/components/agent/DockedAgentPanel.vue @@ -34,6 +34,7 @@ import { computed, defineAsyncComponent, defineComponent, h, ref } from 'vue' import { useI18n } from 'vue-i18n' import { reportError } from '@/platform/telemetry/reportError' +import { useWorkspaceInsetRight } from '@/composables/useWorkspaceInset' import { useAgentPanelStore } from '@/workbench/extensions/agent/stores/agent/agentPanelStore' const AgentPanelLoadError = defineComponent({ @@ -66,6 +67,7 @@ const AgentPanelRoot = defineAsyncComponent({ const agentPanelStore = useAgentPanelStore() const { isOpen, enabled, width } = storeToRefs(agentPanelStore) const docked = computed(() => enabled.value && isOpen.value) +useWorkspaceInsetRight(() => (docked.value ? width.value : 0)) const isResizing = ref(false) let resizeStartX = 0 diff --git a/src/workbench/extensions/agent/crdt/linkMintPort.ts b/src/workbench/extensions/agent/crdt/linkMintPort.ts index 9fdef0d878a..eaf33babacb 100644 --- a/src/workbench/extensions/agent/crdt/linkMintPort.ts +++ b/src/workbench/extensions/agent/crdt/linkMintPort.ts @@ -86,6 +86,7 @@ export function attachLinkMintPort(deps: LinkMintPortDeps): LinkMintPort { const severancesByNode = new Map() const consumedLinkIds = new Set() let sweepScheduled = false + let detached = false function gateOpen(): boolean { return shouldMint({ @@ -111,17 +112,18 @@ export function attachLinkMintPort(deps: LinkMintPortDeps): LinkMintPort { surfaceUnrepresentable('subgraph-interior connect', topology.id) return } - deps.enqueue([ - { - op: 'connect', - link_id: topology.id, - from_node: topology.originNodeId, - from_slot: topology.originSlot, - to_node: topology.targetNodeId, - to_slot: topology.targetSlot, - link_type: String(topology.type) - } - ]) + const operation: GraphOperation = { + op: 'connect', + link_id: topology.id, + from_node: topology.originNodeId, + from_slot: topology.originSlot, + to_node: topology.targetNodeId, + to_slot: topology.targetSlot, + link_type: String(topology.type) + } + queueMicrotask(() => { + if (!detached) deps.enqueue([operation]) + }) } function scheduleSweep(): void { @@ -183,6 +185,7 @@ export function attachLinkMintPort(deps: LinkMintPortDeps): LinkMintPort { } }, detach() { + detached = true detachPlaced() detachDeleted() } diff --git a/src/workbench/extensions/agent/crdt/mintPortWiring.test.ts b/src/workbench/extensions/agent/crdt/mintPortWiring.test.ts index 9c82e85d286..146f4c251e9 100644 --- a/src/workbench/extensions/agent/crdt/mintPortWiring.test.ts +++ b/src/workbench/extensions/agent/crdt/mintPortWiring.test.ts @@ -113,8 +113,9 @@ describe('attachMintPortWiring', () => { ]) }) - it('mints a concrete connect when the real link store places a link', () => { + it('mints a concrete connect when the real link store places a link', async () => { useLinkStore().registerLink(ROOT_SCOPE, topology(41)) + await afterSweep() expect(minted).toEqual([ { @@ -155,6 +156,7 @@ describe('attachMintPortWiring', () => { const linkStore = useLinkStore() const severed = topology(41) linkStore.registerLink(ROOT_SCOPE, severed) + await afterSweep() minted.length = 0 linkStore.deleteLink(ROOT_SCOPE, severed) @@ -168,6 +170,42 @@ describe('attachMintPortWiring', () => { ]) }) + it('orders a same-task createNode before its connect', async () => { + graphNodes.set('1', { + serialize: () => ({ id: 1, type: 'LoadImage' }) + }) + graphNodes.set('2', { + serialize: () => ({ id: 2, type: 'PreviewImage' }) + }) + + queueMicrotask(() => { + deliverLayoutChange({ + operation: { + type: 'createNode', + actor: 'user-abc', + nodeId: toNodeId(1), + layout: { position: { x: 10, y: 20 } } + } + }) + deliverLayoutChange({ + operation: { + type: 'createNode', + actor: 'user-abc', + nodeId: toNodeId(2), + layout: { position: { x: 30, y: 40 } } + } + }) + }) + useLinkStore().registerLink(ROOT_SCOPE, topology(41)) + await afterSweep() + + expect(minted.map((operation) => operation.op)).toEqual([ + 'add_node', + 'add_node', + 'connect' + ]) + }) + it('mints a name-keyed set_widget with the pre-write value from the real store', () => { const widgetStore = useWidgetValueStore() const id = widgetId(ROOT_ID, toNodeId(7), 'seed') @@ -227,7 +265,7 @@ describe('attachMintPortWiring', () => { expect(minted).toEqual([]) }) - it('suppresses mints between the load-bracket hooks, fail-closed on a failed load', () => { + it('suppresses mints between the load-bracket hooks, fail-closed on a failed load', async () => { wiring.onBeforeGraphLoad() useLinkStore().registerLink(ROOT_SCOPE, topology(41)) expect(minted).toEqual([]) @@ -240,6 +278,7 @@ describe('attachMintPortWiring', () => { wiring.onAfterGraphConfigure() useLinkStore().registerLink(ROOT_SCOPE, topology(43, 4)) + await afterSweep() expect(minted).toHaveLength(1) }) diff --git a/src/workbench/extensions/agent/crdt/opSender.test.ts b/src/workbench/extensions/agent/crdt/opSender.test.ts index d60ff500c32..150ca5a28d9 100644 --- a/src/workbench/extensions/agent/crdt/opSender.test.ts +++ b/src/workbench/extensions/agent/crdt/opSender.test.ts @@ -2,7 +2,7 @@ import type { Op } from '@comfyorg/comfy-multi-player' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import type { GraphOperation } from './graphOperations' -import { createOpSender } from './opSender' +import { createOpSender, toOpsResultView } from './opSender' import type { BatchOutcome, OpsResultView } from './opSender' const WORKFLOW = 'wf-1' @@ -229,6 +229,36 @@ describe('createOpSender', () => { expect(settled[0].state).toBe('acknowledged') }) + it('normalizes shipped doc_ops_result failed object and array shapes', () => { + expect( + toOpsResultView({ + ok: false, + applied: [], + skipped: [], + failed: { index: 0, op: { op_id: 'a'.repeat(32) } } + }) + ).toEqual({ + ok: false, + applied: [], + skipped: [], + failure: { op_id: 'a'.repeat(32) } + }) + + expect( + toOpsResultView({ + ok: false, + applied: [], + skipped: [], + failed: [{ index: 0 }, { op_id: 'b'.repeat(32) }] + }) + ).toEqual({ + ok: false, + applied: [], + skipped: [], + failure: { op_id: 'b'.repeat(32) } + }) + }) + it('an identified failure for other ops never settles the in-flight batch', () => { sender.enqueue([addNode(1)]) diff --git a/src/workbench/extensions/agent/crdt/opSender.ts b/src/workbench/extensions/agent/crdt/opSender.ts index 69c76960d71..afe23945fb2 100644 --- a/src/workbench/extensions/agent/crdt/opSender.ts +++ b/src/workbench/extensions/agent/crdt/opSender.ts @@ -32,6 +32,35 @@ export interface OpsResultView { failure?: { op_id?: string } } +function failureOpId(value: unknown): string | undefined { + if (value === null || typeof value !== 'object') return undefined + const record = value as Record + if (typeof record.op_id === 'string') return record.op_id + const nested = record.op + if (nested !== null && typeof nested === 'object') { + const opId = (nested as Record).op_id + if (typeof opId === 'string') return opId + } + return undefined +} + +export function toOpsResultView( + detail: OpsResultView & { failed?: unknown } +): OpsResultView { + const failures = Array.isArray(detail.failed) + ? detail.failed + : detail.failed === undefined + ? [] + : [detail.failed] + const opId = failures.map(failureOpId).find((id) => id !== undefined) + return { + ok: detail.ok, + applied: detail.applied, + skipped: detail.skipped, + ...(opId !== undefined ? { failure: { op_id: opId } } : {}) + } +} + export interface OpSenderDeps { /** `DocFrameClient.sendOps` shape: false = the transport cannot carry it now. */ sendOps(workflowId: string, tab: string, ops: Op[]): boolean diff --git a/src/workbench/extensions/agent/crdt/useAgentCrdtFollower.ts b/src/workbench/extensions/agent/crdt/useAgentCrdtFollower.ts index 521fed8d104..f95a2b69074 100644 --- a/src/workbench/extensions/agent/crdt/useAgentCrdtFollower.ts +++ b/src/workbench/extensions/agent/crdt/useAgentCrdtFollower.ts @@ -13,7 +13,7 @@ import { EcsFollowerAdapter } from './ecsFollowerAdapter' import type { GraphOperation } from './graphOperations' import { LayoutFollowerBridge } from './layoutFollowerBridge' import type { OpsResultView } from './opSender' -import { createOpSender } from './opSender' +import { createOpSender, toOpsResultView } from './opSender' // FE-1902: the doc id is otherwise held only in memory (set on turn ack), so a // panel remount loses the binding until the NEXT turn ack. Persist it per-tab @@ -186,14 +186,7 @@ export function useAgentCrdtFollower( const handler: EventListener = (event) => { if (!(event instanceof CustomEvent)) return const detail = event.detail as OpsResultView & { failed?: unknown } - listener({ - ok: detail.ok, - applied: detail.applied, - skipped: detail.skipped, - ...(detail.failed && typeof detail.failed === 'object' - ? { failure: detail.failed as OpsResultView['failure'] } - : {}) - }) + listener(toOpsResultView(detail)) } bridge.addEventListener('doc_ops_result', handler) return () => bridge.removeEventListener('doc_ops_result', handler) From 91f7f00735e61b8b740b1797b5b60e18077e489b Mon Sep 17 00:00:00 2001 From: bymyself Date: Mon, 31 Aug 2026 09:07:21 +0000 Subject: [PATCH 02/14] fix(crdt): preserve link mint ordering --- .../store/layoutStoreMintDelivery.test.ts | 1 + .../agent/crdt/linkMintPort.test.ts | 3 +- .../extensions/agent/crdt/linkMintPort.ts | 42 ++++++++++++++----- 3 files changed, 34 insertions(+), 12 deletions(-) diff --git a/src/renderer/core/layout/store/layoutStoreMintDelivery.test.ts b/src/renderer/core/layout/store/layoutStoreMintDelivery.test.ts index 188a81f36b8..782166b6514 100644 --- a/src/renderer/core/layout/store/layoutStoreMintDelivery.test.ts +++ b/src/renderer/core/layout/store/layoutStoreMintDelivery.test.ts @@ -161,6 +161,7 @@ describe('mint ports against the real layout store delivery', () => { const linkStore = useLinkStore() const severed = linkTopology(41, '2') linkStore.registerLink(scope, severed) + await realDelivery() minted.length = 0 const consoleError = vi .spyOn(console, 'error') diff --git a/src/workbench/extensions/agent/crdt/linkMintPort.test.ts b/src/workbench/extensions/agent/crdt/linkMintPort.test.ts index 44b9a18d606..fb5a64b6786 100644 --- a/src/workbench/extensions/agent/crdt/linkMintPort.test.ts +++ b/src/workbench/extensions/agent/crdt/linkMintPort.test.ts @@ -82,8 +82,9 @@ describe('attachLinkMintPort', () => { }) }) - it('mints a concrete connect for a local link placement', () => { + it('mints a concrete connect for a local link placement', async () => { place(ROOT_SCOPE, topology(41)) + await Promise.resolve() expect(minted).toEqual([ { diff --git a/src/workbench/extensions/agent/crdt/linkMintPort.ts b/src/workbench/extensions/agent/crdt/linkMintPort.ts index eaf33babacb..fb7839d6562 100644 --- a/src/workbench/extensions/agent/crdt/linkMintPort.ts +++ b/src/workbench/extensions/agent/crdt/linkMintPort.ts @@ -85,6 +85,10 @@ function isRootScope(scope: LinkScopeView): boolean { export function attachLinkMintPort(deps: LinkMintPortDeps): LinkMintPort { const severancesByNode = new Map() const consumedLinkIds = new Set() + const pendingPlacements = new Map< + string, + { operation: GraphOperation; linkId: string | number } + >() let sweepScheduled = false let detached = false @@ -112,18 +116,31 @@ export function attachLinkMintPort(deps: LinkMintPortDeps): LinkMintPort { surfaceUnrepresentable('subgraph-interior connect', topology.id) return } - const operation: GraphOperation = { - op: 'connect', - link_id: topology.id, - from_node: topology.originNodeId, - from_slot: topology.originSlot, - to_node: topology.targetNodeId, - to_slot: topology.targetSlot, - link_type: String(topology.type) - } - queueMicrotask(() => { - if (!detached) deps.enqueue([operation]) + const key = String(topology.id) + pendingPlacements.set(key, { + linkId: topology.id, + operation: { + op: 'connect', + link_id: topology.id, + from_node: topology.originNodeId, + from_slot: topology.originSlot, + to_node: topology.targetNodeId, + to_slot: topology.targetSlot, + link_type: String(topology.type) + } }) + queueMicrotask(() => flushPlacement(key)) + } + + function flushPlacement(key: string): void { + const pending = pendingPlacements.get(key) + if (!pending) return + pendingPlacements.delete(key) + if (detached || !gateOpen()) { + surfaceUnrepresentable('link connect', pending.linkId) + return + } + deps.enqueue([pending.operation]) } function scheduleSweep(): void { @@ -159,6 +176,8 @@ export function attachLinkMintPort(deps: LinkMintPortDeps): LinkMintPort { } function onDeleted(scope: LinkScopeView, topology: LinkTopologyView): void { + // Preserve mutation order when placement and deletion share a task. + flushPlacement(String(topology.id)) const entry: SeveranceEntry = { linkId: topology.id, mintable: gateOpen() && isRootScope(scope) @@ -186,6 +205,7 @@ export function attachLinkMintPort(deps: LinkMintPortDeps): LinkMintPort { }, detach() { detached = true + for (const key of pendingPlacements.keys()) flushPlacement(key) detachPlaced() detachDeleted() } From d625afa33a010e15e096b5f8bfb7741d368b1cf6 Mon Sep 17 00:00:00 2001 From: cheap-drain Date: Wed, 2 Sep 2026 01:56:15 +0000 Subject: [PATCH 03/14] fix(crdt): harden doc_ops_result normalization in opSender - null/undefined-guard the event detail (was an unguarded cast that could throw a TypeError and stall the batch for the full result timeout) - use isRecord type guards instead of unsafe `as Record` assertions when reading unknown wire payloads - preserve a canonical `failure` from the host instead of only deriving one from `failed` - collect every failure op_id (failureOpIds) instead of picking the first arbitrarily, and match a result against the in-flight batch using any of them, not just the first Addresses review feedback: https://github.com/Comfy-Org/ComfyUI_frontend/pull/16337#discussion_r3892825397 https://github.com/Comfy-Org/ComfyUI_frontend/pull/16337#discussion_r3892825409 https://github.com/Comfy-Org/ComfyUI_frontend/pull/16337#discussion_r3892825424 https://github.com/Comfy-Org/ComfyUI_frontend/pull/16337#discussion_r3893153040 https://github.com/Comfy-Org/ComfyUI_frontend/pull/16337#discussion_r3893153055 --- .../extensions/agent/crdt/opSender.test.ts | 70 ++++++++++++++++++- .../extensions/agent/crdt/opSender.ts | 69 ++++++++++++------ .../agent/crdt/useAgentCrdtFollower.ts | 5 +- 3 files changed, 120 insertions(+), 24 deletions(-) diff --git a/src/workbench/extensions/agent/crdt/opSender.test.ts b/src/workbench/extensions/agent/crdt/opSender.test.ts index 150ca5a28d9..b4dfe3187ff 100644 --- a/src/workbench/extensions/agent/crdt/opSender.test.ts +++ b/src/workbench/extensions/agent/crdt/opSender.test.ts @@ -241,7 +241,8 @@ describe('createOpSender', () => { ok: false, applied: [], skipped: [], - failure: { op_id: 'a'.repeat(32) } + failure: { op_id: 'a'.repeat(32) }, + failureOpIds: ['a'.repeat(32)] }) expect( @@ -255,7 +256,72 @@ describe('createOpSender', () => { ok: false, applied: [], skipped: [], - failure: { op_id: 'b'.repeat(32) } + failure: { op_id: 'b'.repeat(32) }, + failureOpIds: ['b'.repeat(32)] + }) + }) + + it('preserves a canonical failure over a derived one, and collects every failed op_id', () => { + // Addresses review feedback: + // https://github.com/Comfy-Org/ComfyUI_frontend/pull/16337#discussion_r3893153055 + expect( + toOpsResultView({ + ok: false, + applied: [], + skipped: [], + failure: { op_id: 'c'.repeat(32) }, + failed: [{ op_id: 'd'.repeat(32) }] + }) + ).toEqual({ + ok: false, + applied: [], + skipped: [], + failure: { op_id: 'c'.repeat(32) }, + failureOpIds: ['c'.repeat(32)] + }) + + // Addresses review feedback (match any failed op_id, not just the first): + // https://github.com/Comfy-Org/ComfyUI_frontend/pull/16337#discussion_r3892825409 + expect( + toOpsResultView({ + ok: false, + applied: [], + skipped: [], + failed: [{ op_id: 'e'.repeat(32) }, { op_id: 'f'.repeat(32) }] + }) + ).toEqual({ + ok: false, + applied: [], + skipped: [], + failure: { op_id: 'e'.repeat(32) }, + failureOpIds: ['e'.repeat(32), 'f'.repeat(32)] + }) + }) + + it('a canonical empty-list rejection with no failed entries settles as anonymous', () => { + // Addresses review feedback: + // https://github.com/Comfy-Org/ComfyUI_frontend/pull/16337#discussion_r3893153036 + expect( + toOpsResultView({ ok: false, applied: [], skipped: [], failed: [] }) + ).toEqual({ + ok: false, + applied: [], + skipped: [] + }) + }) + + it('returns a safe empty view for a null or undefined doc_ops_result detail', () => { + // Addresses review feedback: + // https://github.com/Comfy-Org/ComfyUI_frontend/pull/16337#discussion_r3892825397 + expect(toOpsResultView(null)).toEqual({ + ok: false, + applied: [], + skipped: [] + }) + expect(toOpsResultView(undefined)).toEqual({ + ok: false, + applied: [], + skipped: [] }) }) diff --git a/src/workbench/extensions/agent/crdt/opSender.ts b/src/workbench/extensions/agent/crdt/opSender.ts index afe23945fb2..c383d6f667a 100644 --- a/src/workbench/extensions/agent/crdt/opSender.ts +++ b/src/workbench/extensions/agent/crdt/opSender.ts @@ -30,34 +30,57 @@ export interface OpsResultView { skipped: string[] /** Failed-batch diagnostics when the host provides them; `op_id` correlates an otherwise empty-list failure to its batch. */ failure?: { op_id?: string } + /** Every `op_id` found in the host's failure payload (canonical `failure` first, then `failed`), for matching against an in-flight batch's op-id set rather than trusting a single arbitrary pick. */ + failureOpIds?: string[] +} + +function isRecord(value: unknown): value is Record { + return value !== null && typeof value === 'object' } function failureOpId(value: unknown): string | undefined { - if (value === null || typeof value !== 'object') return undefined - const record = value as Record - if (typeof record.op_id === 'string') return record.op_id - const nested = record.op - if (nested !== null && typeof nested === 'object') { - const opId = (nested as Record).op_id - if (typeof opId === 'string') return opId - } + if (!isRecord(value)) return undefined + if (typeof value.op_id === 'string') return value.op_id + const nested = value.op + if (isRecord(nested) && typeof nested.op_id === 'string') return nested.op_id return undefined } +/** All `op_id`s findable across the host's `failed` payload, in wire order. */ +function allFailureOpIds(failed: unknown): string[] { + const failures = Array.isArray(failed) + ? failed + : failed === undefined + ? [] + : [failed] + return failures + .map(failureOpId) + .filter((id): id is string => id !== undefined) +} + export function toOpsResultView( - detail: OpsResultView & { failed?: unknown } + detail: (OpsResultView & { failed?: unknown }) | null | undefined ): OpsResultView { - const failures = Array.isArray(detail.failed) - ? detail.failed - : detail.failed === undefined - ? [] - : [detail.failed] - const opId = failures.map(failureOpId).find((id) => id !== undefined) + if (!isRecord(detail)) { + return { ok: false, applied: [], skipped: [] } + } + // A canonical `failure` from the host is authoritative; only derive one + // from `failed` when the host did not supply it. + const canonicalOpId = + isRecord(detail.failure) && typeof detail.failure.op_id === 'string' + ? detail.failure.op_id + : undefined + const candidateOpIds = + canonicalOpId !== undefined + ? [canonicalOpId] + : allFailureOpIds(detail.failed) return { - ok: detail.ok, - applied: detail.applied, - skipped: detail.skipped, - ...(opId !== undefined ? { failure: { op_id: opId } } : {}) + ok: Boolean(detail.ok), + applied: Array.isArray(detail.applied) ? detail.applied : [], + skipped: Array.isArray(detail.skipped) ? detail.skipped : [], + ...(candidateOpIds.length > 0 + ? { failure: { op_id: candidateOpIds[0] }, failureOpIds: candidateOpIds } + : {}) } } @@ -178,8 +201,12 @@ export function createOpSender(deps: OpSenderDeps): OpSender { if (staleAnonymousBudget > 0) staleAnonymousBudget-- return } - const identified = [...result.applied, ...result.skipped] - if (result.failure?.op_id) identified.push(result.failure.op_id) + const identified = [ + ...result.applied, + ...result.skipped, + ...(result.failureOpIds ?? + (result.failure?.op_id ? [result.failure.op_id] : [])) + ] if (identified.length > 0) { if (!identified.some((opId) => inFlight!.opIds.has(opId))) return settle({ state: 'acknowledged', ops: inFlight.ops, result }) diff --git a/src/workbench/extensions/agent/crdt/useAgentCrdtFollower.ts b/src/workbench/extensions/agent/crdt/useAgentCrdtFollower.ts index f95a2b69074..7b337aaf462 100644 --- a/src/workbench/extensions/agent/crdt/useAgentCrdtFollower.ts +++ b/src/workbench/extensions/agent/crdt/useAgentCrdtFollower.ts @@ -185,7 +185,10 @@ export function useAgentCrdtFollower( onOpsResult(listener) { const handler: EventListener = (event) => { if (!(event instanceof CustomEvent)) return - const detail = event.detail as OpsResultView & { failed?: unknown } + const detail = event.detail as + | (OpsResultView & { failed?: unknown }) + | null + | undefined listener(toOpsResultView(detail)) } bridge.addEventListener('doc_ops_result', handler) From 9aef1a93589bf288f5573870e4fadc6bfc1bf1e5 Mon Sep 17 00:00:00 2001 From: cheap-drain Date: Wed, 2 Sep 2026 02:03:34 +0000 Subject: [PATCH 04/14] fix(agent): clear workspace inset on teardown instead of freezing it A docked surface's own `docked.value ? width : 0` branch never runs when its host unmounts in the same flush as closing (a parent v-if beats its own watchEffect to zero), so --workspace-inset-right stuck at the last published width and every body-portaled overlay stayed permanently offset after the agent panel closed. Clear the var directly on scope teardown. Addresses review feedback: https://github.com/Comfy-Org/ComfyUI_frontend/pull/16337#discussion_r3892825318 --- src/composables/useWorkspaceInset.test.ts | 16 +++++++++++++++- src/composables/useWorkspaceInset.ts | 9 ++++++++- 2 files changed, 23 insertions(+), 2 deletions(-) diff --git a/src/composables/useWorkspaceInset.test.ts b/src/composables/useWorkspaceInset.test.ts index 550126a2f4c..7fbcfe72bf6 100644 --- a/src/composables/useWorkspaceInset.test.ts +++ b/src/composables/useWorkspaceInset.test.ts @@ -59,6 +59,20 @@ describe('useWorkspaceInsetRight', () => { width.value = 960 await nextTick() - expect(readInset()).toBe('420px') + // Teardown clears the var rather than freezing it at its last published + // value - a docked surface unmounted mid-close (its host's `v-if` beats + // its own `docked.value ? width : 0` branch to the flush) must not leave + // every portaled overlay permanently offset. + // Addresses review feedback: + // https://github.com/Comfy-Org/ComfyUI_frontend/pull/16337#discussion_r3892825318 + expect(readInset()).toBe('0px') + }) + + it('clears the inset on teardown even when the last published width was already zero', () => { + const scope = effectScope() + scope.run(() => useWorkspaceInsetRight(() => 0)) + scope.stop() + + expect(readInset()).toBe('0px') }) }) diff --git a/src/composables/useWorkspaceInset.ts b/src/composables/useWorkspaceInset.ts index 718760fa553..7f42b889ad9 100644 --- a/src/composables/useWorkspaceInset.ts +++ b/src/composables/useWorkspaceInset.ts @@ -1,4 +1,4 @@ -import { watchEffect } from 'vue' +import { onScopeDispose, watchEffect } from 'vue' /** * Width consumed by docked surfaces on the right of the workspace. @@ -16,4 +16,11 @@ export function useWorkspaceInsetRight(widthPx: () => number): void { `${widthPx()}px` ) }) + // A docked surface's own `docked.value ? width : 0` branch never runs once + // its host is unmounted BEFORE that branch flips (e.g. a parent `v-if` + // unmounts the whole component in the same flush as closing it) - clear + // the var directly on teardown so it cannot survive its publisher. + onScopeDispose(() => { + document.documentElement.style.setProperty(WORKSPACE_INSET_RIGHT, '0px') + }) } From 32d5e2b3bdc5b529c40d04b8c05eecebef9ea269 Mon Sep 17 00:00:00 2001 From: cheap-drain Date: Wed, 2 Sep 2026 02:05:24 +0000 Subject: [PATCH 05/14] fix(crdt): cancel a same-task placement/delete pair without a phantom connect If a link placement passes the mint gate and the same link is deleted before its deferred microtask flushes, flushPlacement() still shipped a connect op even though the deletion made it stale on both the local graph and the doc. Cancel an unflushed pending placement silently on the same-task delete instead of flushing (and reporting) it - the severance sweep's own divergence check still runs, so a real unconsumed disconnect still surfaces exactly as before. Also addresses the stale gateOpen() concern (already fixed by the prior commit's flushPlacement() re-check, not re-litigated here) and confirms F5 (layoutStoreMintDelivery.test.ts) still asserts the correct [delete_node] shape for an already-flushed severed link. Addresses review feedback: https://github.com/Comfy-Org/ComfyUI_frontend/pull/16337#discussion_r3893153026 --- .../agent/crdt/linkMintPort.test.ts | 35 +++++++++++++++++++ .../extensions/agent/crdt/linkMintPort.ts | 16 +++++++-- 2 files changed, 49 insertions(+), 2 deletions(-) diff --git a/src/workbench/extensions/agent/crdt/linkMintPort.test.ts b/src/workbench/extensions/agent/crdt/linkMintPort.test.ts index fb5a64b6786..584c19e6473 100644 --- a/src/workbench/extensions/agent/crdt/linkMintPort.test.ts +++ b/src/workbench/extensions/agent/crdt/linkMintPort.test.ts @@ -199,4 +199,39 @@ describe('attachLinkMintPort', () => { expect(minted).toEqual([]) }) + + it('cancels a same-task deletion of an unflushed placement without a phantom connect', async () => { + // Addresses review feedback: + // https://github.com/Comfy-Org/ComfyUI_frontend/pull/16337#discussion_r3893153026 + const consoleError = vi + .spyOn(console, 'error') + .mockImplementation(() => undefined) + place(ROOT_SCOPE, topology(41)) + remove(ROOT_SCOPE, topology(41)) + await afterSweep() + + // The canceled placement never reaches enqueue and is never reported as + // a `link connect` divergence (it did not ship). The severance sweep + // still runs and correctly reports the unconsumed disconnect - it was a + // real local delete that nothing (e.g. a delete_node mint) consumed. + expect(minted).toEqual([]) + expect(consoleError).toHaveBeenCalledOnce() + expect(consoleError.mock.calls[0][0]).toContain('link disconnect') + consoleError.mockRestore() + }) + + it('flushes and surfaces pending placements on detach instead of discarding them silently', () => { + // Addresses review feedback: + // https://github.com/Comfy-Org/ComfyUI_frontend/pull/16337#discussion_r3892825337 + const consoleError = vi + .spyOn(console, 'error') + .mockImplementation(() => undefined) + place(ROOT_SCOPE, topology(41)) + port.detach() + + expect(minted).toEqual([]) + expect(consoleError).toHaveBeenCalledOnce() + expect(consoleError.mock.calls[0][1]).toBe(41) + consoleError.mockRestore() + }) }) diff --git a/src/workbench/extensions/agent/crdt/linkMintPort.ts b/src/workbench/extensions/agent/crdt/linkMintPort.ts index fb7839d6562..f7ee0b577be 100644 --- a/src/workbench/extensions/agent/crdt/linkMintPort.ts +++ b/src/workbench/extensions/agent/crdt/linkMintPort.ts @@ -143,6 +143,16 @@ export function attachLinkMintPort(deps: LinkMintPortDeps): LinkMintPort { deps.enqueue([pending.operation]) } + /** + * A same-task deletion that cancels an unflushed placement: no connect + * ever reached `deps.enqueue()`, so nothing diverges from the local graph + * (which also omits the link) - drop it silently rather than reporting a + * `link connect` divergence for an op that never shipped. + */ + function cancelPlacement(key: string): void { + pendingPlacements.delete(key) + } + function scheduleSweep(): void { if (sweepScheduled) return sweepScheduled = true @@ -176,8 +186,10 @@ export function attachLinkMintPort(deps: LinkMintPortDeps): LinkMintPort { } function onDeleted(scope: LinkScopeView, topology: LinkTopologyView): void { - // Preserve mutation order when placement and deletion share a task. - flushPlacement(String(topology.id)) + // A same-task placement that never flushed is canceled, not a real + // divergence: the local graph and the doc both end up without the link. + // Preserve mutation order for everything else that already flushed. + cancelPlacement(String(topology.id)) const entry: SeveranceEntry = { linkId: topology.id, mintable: gateOpen() && isRootScope(scope) From 4bc2832bc14cf42cde32ba81d630f3d1b95b3e02 Mon Sep 17 00:00:00 2001 From: christian-byrne Date: Wed, 2 Sep 2026 02:43:09 -0700 Subject: [PATCH 06/14] test: remove ineffective zero-inset teardown case Addresses review feedback: https://github.com/Comfy-Org/ComfyUI_frontend/pull/16337#discussion_r3912743358 --- src/composables/useWorkspaceInset.test.ts | 7 ------- 1 file changed, 7 deletions(-) diff --git a/src/composables/useWorkspaceInset.test.ts b/src/composables/useWorkspaceInset.test.ts index 7fbcfe72bf6..e6005efff6d 100644 --- a/src/composables/useWorkspaceInset.test.ts +++ b/src/composables/useWorkspaceInset.test.ts @@ -68,11 +68,4 @@ describe('useWorkspaceInsetRight', () => { expect(readInset()).toBe('0px') }) - it('clears the inset on teardown even when the last published width was already zero', () => { - const scope = effectScope() - scope.run(() => useWorkspaceInsetRight(() => 0)) - scope.stop() - - expect(readInset()).toBe('0px') - }) }) From cf537d5d1ba6f7cb9ae51685d041acb588903ce0 Mon Sep 17 00:00:00 2001 From: christian-byrne Date: Wed, 2 Sep 2026 02:43:18 -0700 Subject: [PATCH 07/14] test: remove review-history annotation Addresses review feedback: https://github.com/Comfy-Org/ComfyUI_frontend/pull/16337#discussion_r3912743371 --- src/composables/useWorkspaceInset.test.ts | 3 --- 1 file changed, 3 deletions(-) diff --git a/src/composables/useWorkspaceInset.test.ts b/src/composables/useWorkspaceInset.test.ts index e6005efff6d..4f3b5642831 100644 --- a/src/composables/useWorkspaceInset.test.ts +++ b/src/composables/useWorkspaceInset.test.ts @@ -63,9 +63,6 @@ describe('useWorkspaceInsetRight', () => { // value - a docked surface unmounted mid-close (its host's `v-if` beats // its own `docked.value ? width : 0` branch to the flush) must not leave // every portaled overlay permanently offset. - // Addresses review feedback: - // https://github.com/Comfy-Org/ComfyUI_frontend/pull/16337#discussion_r3892825318 expect(readInset()).toBe('0px') }) - }) From bbed53565f8c2773cb0c326347be9d924d256a19 Mon Sep 17 00:00:00 2001 From: Christian Byrne Date: Wed, 2 Sep 2026 14:03:49 -0700 Subject: [PATCH 08/14] fix(crdt): drain mint ports through one ordered queue and thread host failure diagnostics Cross-port mint order was not causal: the link and widget feeds mint synchronously while the layout store delivers a task's changes one microtask late, so a same-task createNode + registerLink shipped its connect before its add_node. All three ports now enqueue into a single mintQueue that drains once per task (double microtask), emits structural ops (add_node/delete_node/clear) in store order first, then connect/set_widget in mint order, and drops dependent ops on nodes the same drain deletes. detach() flushes the queue instead of dropping it. linkMintPort keys pendingPlacements by rootGraphId:topology.id so two scopes sharing a link id cannot cancel each other. opSender.toOpsResultView now takes the raw event detail, threads the host's code/message/index into OpsResultView.failure, and settles the in-flight batch on legacy failed ids even under a foreign canonical op_id. --- .../extensions/agent/crdt/linkMintPort.ts | 25 ++- .../agent/crdt/mintPortWiring.test.ts | 129 ++++++++++--- .../extensions/agent/crdt/mintPortWiring.ts | 16 +- .../extensions/agent/crdt/mintQueue.test.ts | 171 ++++++++++++++++++ .../extensions/agent/crdt/mintQueue.ts | 110 +++++++++++ .../extensions/agent/crdt/opSender.test.ts | 106 ++++++++++- .../extensions/agent/crdt/opSender.ts | 96 +++++++--- .../agent/crdt/useAgentCrdtFollower.ts | 7 +- 8 files changed, 590 insertions(+), 70 deletions(-) create mode 100644 src/workbench/extensions/agent/crdt/mintQueue.test.ts create mode 100644 src/workbench/extensions/agent/crdt/mintQueue.ts diff --git a/src/workbench/extensions/agent/crdt/linkMintPort.ts b/src/workbench/extensions/agent/crdt/linkMintPort.ts index f7ee0b577be..bdc13be64a1 100644 --- a/src/workbench/extensions/agent/crdt/linkMintPort.ts +++ b/src/workbench/extensions/agent/crdt/linkMintPort.ts @@ -2,10 +2,13 @@ * The blessed connect port: litegraph's registerLinkTopology bridge calls * linkStore synchronously for EVERY link change, so nothing escapes this seam. * Register/replace mint a CONCRETE connect (a replace displaces the incumbent - * register by LWW - no severance). Deletes cannot mint (no disconnect op in - * the frozen vocabulary): they feed the severance log for delete_node, and an - * unconsumed local severance surfaces as observable divergence after a double - * microtask (strictly after the layout store's single-microtask delivery). + * register by LWW - no severance). A placement is held for one microtask so + * a same-task delete can cancel it before it ships; cross-port ORDER is not + * this port's concern - the wiring's shared mint queue decides it. Deletes + * cannot mint (no disconnect op in the frozen vocabulary): they feed the + * severance log for delete_node, and an unconsumed local severance surfaces + * as observable divergence after a double microtask (strictly after the + * layout store's single-microtask delivery). */ import type { NodeId as WireNodeId } from '@comfyorg/comfy-multi-player' @@ -63,7 +66,7 @@ export interface LinkMintPortDeps { isEnabled(): boolean /** A semantic doc is bound for the active workflow. */ isDocBound(): boolean - /** Receives minted semantic operations (the sender's inbox). */ + /** Receives minted semantic operations (the wiring's shared mint queue). */ enqueue(operations: GraphOperation[]): void } @@ -82,6 +85,14 @@ function isRootScope(scope: LinkScopeView): boolean { return String(scope.owningGraphId) === String(scope.rootGraphId) } +/** Link ids are per root graph; two open workflows may both own link 41. */ +function placementKey( + scope: LinkScopeView, + topology: LinkTopologyView +): string { + return `${String(scope.rootGraphId)}:${String(topology.id)}` +} + export function attachLinkMintPort(deps: LinkMintPortDeps): LinkMintPort { const severancesByNode = new Map() const consumedLinkIds = new Set() @@ -116,7 +127,7 @@ export function attachLinkMintPort(deps: LinkMintPortDeps): LinkMintPort { surfaceUnrepresentable('subgraph-interior connect', topology.id) return } - const key = String(topology.id) + const key = placementKey(scope, topology) pendingPlacements.set(key, { linkId: topology.id, operation: { @@ -189,7 +200,7 @@ export function attachLinkMintPort(deps: LinkMintPortDeps): LinkMintPort { // A same-task placement that never flushed is canceled, not a real // divergence: the local graph and the doc both end up without the link. // Preserve mutation order for everything else that already flushed. - cancelPlacement(String(topology.id)) + cancelPlacement(placementKey(scope, topology)) const entry: SeveranceEntry = { linkId: topology.id, mintable: gateOpen() && isRootScope(scope) diff --git a/src/workbench/extensions/agent/crdt/mintPortWiring.test.ts b/src/workbench/extensions/agent/crdt/mintPortWiring.test.ts index 146f4c251e9..f84132e4dee 100644 --- a/src/workbench/extensions/agent/crdt/mintPortWiring.test.ts +++ b/src/workbench/extensions/agent/crdt/mintPortWiring.test.ts @@ -47,12 +47,24 @@ function topology(id: number, targetSlot = 3): LinkTopology { } } +/** Past the ports' double-microtask sweep and the shared queue's drain. */ async function afterSweep(): Promise { await Promise.resolve() await Promise.resolve() await Promise.resolve() } +function createNodeChange(id: number): LayoutChangeView { + return { + operation: { + type: 'createNode', + actor: 'user-abc', + nodeId: toNodeId(id), + layout: { position: { x: 10 * id, y: 20 * id } } + } + } +} + describe('attachMintPortWiring', () => { let minted: GraphOperation[] let wiring: MintPortWiring @@ -98,7 +110,7 @@ describe('attachMintPortWiring', () => { afterEach(() => wiring.detach()) - it('mints a root clear through the production intentional-clear entry point', () => { + it('mints a root clear through the production intentional-clear entry point', async () => { graphNodes.set('1', { id: toNodeId(1) }) graphNodes.set('2', { id: toNodeId(2) }) @@ -107,6 +119,7 @@ describe('attachMintPortWiring', () => { operation: { type: 'clearGraph', actor: 'user-abc' } }) }) + await afterSweep() expect(minted).toEqual([ { op: 'clear', removed_nodes: [toNodeId(1), toNodeId(2)] } @@ -170,31 +183,17 @@ describe('attachMintPortWiring', () => { ]) }) - it('orders a same-task createNode before its connect', async () => { - graphNodes.set('1', { - serialize: () => ({ id: 1, type: 'LoadImage' }) - }) + it('orders a same-task createNode before its connect when the store delivers a microtask late', async () => { + graphNodes.set('1', { serialize: () => ({ id: 1, type: 'LoadImage' }) }) graphNodes.set('2', { serialize: () => ({ id: 2, type: 'PreviewImage' }) }) + // The real store queues its whole batch on ONE microtask, so the sync + // link feed mints first; the shared queue still ships add_node first. queueMicrotask(() => { - deliverLayoutChange({ - operation: { - type: 'createNode', - actor: 'user-abc', - nodeId: toNodeId(1), - layout: { position: { x: 10, y: 20 } } - } - }) - deliverLayoutChange({ - operation: { - type: 'createNode', - actor: 'user-abc', - nodeId: toNodeId(2), - layout: { position: { x: 30, y: 40 } } - } - }) + deliverLayoutChange(createNodeChange(1)) + deliverLayoutChange(createNodeChange(2)) }) useLinkStore().registerLink(ROOT_SCOPE, topology(41)) await afterSweep() @@ -206,7 +205,26 @@ describe('attachMintPortWiring', () => { ]) }) - it('mints a name-keyed set_widget with the pre-write value from the real store', () => { + it('orders a same-task createNode before its widget write, whichever port mints first', async () => { + graphNodes.set('7', { serialize: () => ({ id: 7, type: 'KSampler' }) }) + const widgetStore = useWidgetValueStore() + const id = widgetId(ROOT_ID, toNodeId(7), 'seed') + widgetStore.registerWidget(id, { type: 'number', value: 3 } as Parameters< + typeof widgetStore.registerWidget + >[1]) + + widgetStore.setValue(id, 42) + deliverLayoutChange(createNodeChange(7)) + await afterSweep() + + expect(minted.map((operation) => operation.op)).toEqual([ + 'add_node', + 'set_widget' + ]) + expect(minted).toHaveLength(2) + }) + + it('drops a widget write on a node the same task deletes', async () => { const widgetStore = useWidgetValueStore() const id = widgetId(ROOT_ID, toNodeId(7), 'seed') widgetStore.registerWidget(id, { type: 'number', value: 3 } as Parameters< @@ -214,6 +232,45 @@ describe('attachMintPortWiring', () => { >[1]) widgetStore.setValue(id, 42) + deliverLayoutChange({ + operation: { type: 'deleteNode', actor: 'user-abc', nodeId: toNodeId(7) } + }) + await afterSweep() + + expect(minted).toEqual([ + { op: 'delete_node', node_id: '7', removed_links: [] } + ]) + }) + + it('a widget write in a LATER task than the delete is not pruned (drains are per task)', async () => { + const widgetStore = useWidgetValueStore() + const id = widgetId(ROOT_ID, toNodeId(7), 'seed') + widgetStore.registerWidget(id, { type: 'number', value: 3 } as Parameters< + typeof widgetStore.registerWidget + >[1]) + + deliverLayoutChange({ + operation: { type: 'deleteNode', actor: 'user-abc', nodeId: toNodeId(7) } + }) + await afterSweep() + widgetStore.setValue(id, 42) + await afterSweep() + + expect(minted.map((operation) => operation.op)).toEqual([ + 'delete_node', + 'set_widget' + ]) + }) + + it('mints a name-keyed set_widget with the pre-write value from the real store', async () => { + const widgetStore = useWidgetValueStore() + const id = widgetId(ROOT_ID, toNodeId(7), 'seed') + widgetStore.registerWidget(id, { type: 'number', value: 3 } as Parameters< + typeof widgetStore.registerWidget + >[1]) + + widgetStore.setValue(id, 42) + await afterSweep() expect(minted).toEqual([ { @@ -226,13 +283,14 @@ describe('attachMintPortWiring', () => { ]) }) - it('mints nothing for a setValue that did not apply', () => { + it('mints nothing for a setValue that did not apply', async () => { useWidgetValueStore().setValue(widgetId(ROOT_ID, toNodeId(9), 'missing'), 1) + await afterSweep() expect(minted).toEqual([]) }) - it('suppresses every port inside the remote scope', () => { + it('suppresses every port inside the remote scope', async () => { wiring.runRemoteScope(() => { useLinkStore().registerLink(ROOT_SCOPE, topology(41)) const widgetStore = useWidgetValueStore() @@ -242,11 +300,12 @@ describe('attachMintPortWiring', () => { >[1]) widgetStore.setValue(id, 42) }) + await afterSweep() expect(minted).toEqual([]) }) - it('suppresses remote store calls from their call-carried context', () => { + it('suppresses remote store calls from their call-carried context', async () => { const context: RemoteMutationContext = { source: 'agent-remote', actor: 'agent:test', @@ -259,6 +318,7 @@ describe('attachMintPortWiring', () => { typeof widgetStore.registerWidget >[1]) const widget = widgetStore.setValue(id, 42, context) + await afterSweep() expect(link).toBeDefined() expect(widget).toBe(true) @@ -282,7 +342,7 @@ describe('attachMintPortWiring', () => { expect(minted).toHaveLength(1) }) - it('serializes add_node snapshots name-keyed, dropping non-value widgets', () => { + it('serializes add_node snapshots name-keyed, dropping non-value widgets', async () => { graphNodes.set('5', { serialize: () => ({ id: 5, @@ -304,6 +364,7 @@ describe('attachMintPortWiring', () => { layout: { position: { x: 10, y: 20 } } } }) + await afterSweep() expect(minted).toEqual([ { @@ -320,7 +381,7 @@ describe('attachMintPortWiring', () => { ]) }) - it('positive control: an unbound workflow runs normally, zero mint and zero blockage', () => { + it('positive control: an unbound workflow runs normally, zero mint and zero blockage', async () => { bound = false const widgetStore = useWidgetValueStore() const id = widgetId(ROOT_ID, toNodeId(7), 'seed') @@ -330,6 +391,7 @@ describe('attachMintPortWiring', () => { const placed = useLinkStore().registerLink(ROOT_SCOPE, topology(41)) const applied = widgetStore.setValue(id, 42) + await afterSweep() expect(minted).toEqual([]) expect(placed).toBeDefined() @@ -337,7 +399,7 @@ describe('attachMintPortWiring', () => { expect(widgetStore.getWidget(id)?.value).toBe(42) }) - it('stops observing both stores after detach', () => { + it('stops observing both stores after detach', async () => { wiring.detach() useLinkStore().registerLink(ROOT_SCOPE, topology(41)) const widgetStore = useWidgetValueStore() @@ -346,7 +408,18 @@ describe('attachMintPortWiring', () => { typeof widgetStore.registerWidget >[1]) widgetStore.setValue(id, 42) + await afterSweep() + + expect(minted).toEqual([]) + }) + it('detach flushes a queued mint instead of dropping it', () => { + graphNodes.set('5', { serialize: () => ({ id: 5, type: 'LoadImage' }) }) + deliverLayoutChange(createNodeChange(5)) expect(minted).toEqual([]) + + wiring.detach() + + expect(minted.map((operation) => operation.op)).toEqual(['add_node']) }) }) diff --git a/src/workbench/extensions/agent/crdt/mintPortWiring.ts b/src/workbench/extensions/agent/crdt/mintPortWiring.ts index a4a0059f1ce..16988e81de9 100644 --- a/src/workbench/extensions/agent/crdt/mintPortWiring.ts +++ b/src/workbench/extensions/agent/crdt/mintPortWiring.ts @@ -5,6 +5,10 @@ * never DELETED (the store displaces incumbents internally). Load brackets * are a fail-closed boolean over beforeLoadGraph/afterConfigureGraph: a * failed load leaves mints suppressed until the next load's pair recloses. + * + * All three ports mint into ONE {@link MintQueue}, which is the only thing + * that talks to `deps.enqueue`: cross-port order is decided by its drain, not + * by which port's microtask happened to be inserted first. */ import type { LGraph } from '@/lib/litegraph/src/LGraph' import type { LGraphNode } from '@/lib/litegraph/src/LGraphNode' @@ -24,6 +28,8 @@ import { AGENT_REMOTE_ACTOR, attachLayoutMintPort } from './layoutMintPort' import type { LayoutChangeView, LayoutMintPort } from './layoutMintPort' import { attachLinkMintPort } from './linkMintPort' import { attachWidgetMintPort } from './widgetMintPort' +import { createMintQueue } from './mintQueue' +import type { MintQueue } from './mintQueue' import { createMintSession } from './mintSession' import type { MintSession } from './mintSession' @@ -40,7 +46,7 @@ export interface MintPortWiringDeps { isEnabled(): boolean /** A semantic doc is bound for the active workflow. */ isDocBound(): boolean - /** Receives minted semantic operations (the sender's inbox). */ + /** Receives each drained batch of minted operations (the sender's inbox). */ enqueue(operations: GraphOperation[]): void /** The layout store's `onChange`, injected by the composition root. */ layoutChanges(listener: (change: LayoutChangeView) => void): () => void @@ -116,6 +122,7 @@ function serializeForMint(node: LGraphNode): WorkflowNode | null { export function attachMintPortWiring(deps: MintPortWiringDeps): MintPortWiring { const session = createMintSession() + const queue: MintQueue = createMintQueue(deps.enqueue) type PlacedListener = Parameters< Parameters[0]['events']['onPlaced'] @@ -144,7 +151,7 @@ export function attachMintPortWiring(deps: MintPortWiringDeps): MintPortWiring { session, isEnabled: deps.isEnabled, isDocBound: deps.isDocBound, - enqueue: deps.enqueue + enqueue: queue.enqueue }) const layoutPort: LayoutMintPort = attachLayoutMintPort({ @@ -163,7 +170,7 @@ export function attachMintPortWiring(deps: MintPortWiringDeps): MintPortWiring { return (deps.getGraph()?._nodes ?? []).map((node) => node.id) } }, - enqueue: deps.enqueue + enqueue: queue.enqueue }) const widgetPort = attachWidgetMintPort({ @@ -186,7 +193,7 @@ export function attachMintPortWiring(deps: MintPortWiringDeps): MintPortWiring { if (!graph) return null return findSubgraphNodePathById(graph as unknown as LGraph, owningGraphId) }, - enqueue: deps.enqueue + enqueue: queue.enqueue }) const linkStore = useLinkStore() @@ -262,6 +269,7 @@ export function attachMintPortWiring(deps: MintPortWiringDeps): MintPortWiring { widgetPort.detach() layoutPort.detach() linkPort.detach() + queue.flush() } } activeWirings.add(wiring) diff --git a/src/workbench/extensions/agent/crdt/mintQueue.test.ts b/src/workbench/extensions/agent/crdt/mintQueue.test.ts new file mode 100644 index 00000000000..e48f9066ebc --- /dev/null +++ b/src/workbench/extensions/agent/crdt/mintQueue.test.ts @@ -0,0 +1,171 @@ +import { describe, expect, it } from 'vitest' + +import type { GraphOperation } from './graphOperations' +import { createMintQueue, orderMintedOperations } from './mintQueue' + +function addNode(id: number): GraphOperation { + return { + op: 'add_node', + node_id: id, + class_type: 'TestNode', + pos: [0, 0], + node: { id, type: 'TestNode' } + } +} + +function deleteNode(id: number): GraphOperation { + return { op: 'delete_node', node_id: id, removed_links: [] } +} + +function connect(linkId: number, from: number, to: number): GraphOperation { + return { + op: 'connect', + link_id: linkId, + from_node: from, + from_slot: 0, + to_node: to, + to_slot: 0, + link_type: 'IMAGE' + } +} + +function setWidget(nodeId: number, value: unknown): GraphOperation { + return { op: 'set_widget', node_id: nodeId, widget: 'seed', value, old: 0 } +} + +async function afterDrain(): Promise { + await Promise.resolve() + await Promise.resolve() +} + +describe('orderMintedOperations', () => { + it('lands structural ops before the connects and widget writes that need them', () => { + // The sync feeds mint first in a same-task createNode + registerLink + + // setValue; the layout store's add_node arrives a microtask later. + expect( + orderMintedOperations([ + connect(41, 1, 2), + setWidget(2, 'x'), + addNode(1), + addNode(2) + ]) + ).toEqual([addNode(1), addNode(2), connect(41, 1, 2), setWidget(2, 'x')]) + }) + + it('keeps layout-store order within the structural class', () => { + expect( + orderMintedOperations([deleteNode(1), addNode(1), addNode(2)]) + ).toEqual([deleteNode(1), addNode(1), addNode(2)]) + }) + + it('keeps mint order within the dependent class', () => { + expect( + orderMintedOperations([ + setWidget(2, 'a'), + connect(41, 1, 2), + setWidget(2, 'b') + ]) + ).toEqual([setWidget(2, 'a'), connect(41, 1, 2), setWidget(2, 'b')]) + }) + + it('drops a widget write or connect orphaned by a same-drain delete', () => { + expect( + orderMintedOperations([ + setWidget(2, 'x'), + setWidget(3, 'kept'), + connect(41, 1, 2), + connect(42, 1, 3), + deleteNode(2) + ]) + ).toEqual([deleteNode(2), setWidget(3, 'kept'), connect(42, 1, 3)]) + }) + + it("drops writes to a clear's removed nodes but not to nodes added after it", () => { + expect( + orderMintedOperations([ + setWidget(5, 'pre-clear'), + { op: 'clear', removed_nodes: [5, 6] }, + addNode(7), + setWidget(7, 'post-clear'), + connect(41, 6, 7) + ]) + ).toEqual([ + { op: 'clear', removed_nodes: [5, 6] }, + addNode(7), + setWidget(7, 'post-clear') + ]) + }) + + it('keeps a write to a node deleted and re-added in the same drain', () => { + expect( + orderMintedOperations([deleteNode(1), addNode(1), setWidget(1, 'x')]) + ).toEqual([deleteNode(1), addNode(1), setWidget(1, 'x')]) + }) + + it('never prunes a subgraph-interior widget write', () => { + const interior: GraphOperation = { + op: 'set_widget', + node_id: 2, + widget: 'seed', + value: 1, + old: 0, + path: ['2'], + inner_widget: 'seed' + } + expect(orderMintedOperations([interior, deleteNode(2)])).toEqual([ + deleteNode(2), + interior + ]) + }) +}) + +describe('createMintQueue', () => { + it('delivers one ordered batch per task after a double microtask', async () => { + const delivered: GraphOperation[][] = [] + const queue = createMintQueue((operations) => delivered.push(operations)) + + queue.enqueue([connect(41, 1, 2)]) + queueMicrotask(() => queue.enqueue([addNode(1), addNode(2)])) + expect(delivered).toEqual([]) + await Promise.resolve() + expect(delivered).toEqual([]) + await Promise.resolve() + + expect(delivered).toEqual([[addNode(1), addNode(2), connect(41, 1, 2)]]) + }) + + it('prunes the write a same-drain delete orphaned', async () => { + const delivered: GraphOperation[][] = [] + const queue = createMintQueue((operations) => delivered.push(operations)) + + queue.enqueue([setWidget(2, 'x')]) + queue.enqueue([deleteNode(2)]) + await afterDrain() + + expect(delivered).toEqual([[deleteNode(2)]]) + }) + + it('flush delivers synchronously and the scheduled drain then finds nothing', async () => { + const delivered: GraphOperation[][] = [] + const queue = createMintQueue((operations) => delivered.push(operations)) + + queue.enqueue([addNode(1)]) + queue.flush() + expect(delivered).toEqual([[addNode(1)]]) + await afterDrain() + + expect(delivered).toHaveLength(1) + }) + + it('separate tasks drain separately, in task order', async () => { + const delivered: GraphOperation[][] = [] + const queue = createMintQueue((operations) => delivered.push(operations)) + + queue.enqueue([addNode(1)]) + await afterDrain() + queue.enqueue([setWidget(1, 'x')]) + await afterDrain() + + expect(delivered).toEqual([[addNode(1)], [setWidget(1, 'x')]]) + }) +}) diff --git a/src/workbench/extensions/agent/crdt/mintQueue.ts b/src/workbench/extensions/agent/crdt/mintQueue.ts new file mode 100644 index 00000000000..1b22b49ed51 --- /dev/null +++ b/src/workbench/extensions/agent/crdt/mintQueue.ts @@ -0,0 +1,110 @@ +/** + * The single ordered outbox behind the three mint ports. + * + * Each port mints on its own clock: the link and widget feeds fire + * synchronously inside the store action, while the layout store delivers a + * whole task's changes on ONE microtask. Raw mint order across ports is + * therefore NOT causal order - a same-task `createNode` + `registerLink` + * mints its connect before its add_node. Rather than racing per-port + * microtasks against the store's, every port enqueues here and one drain + * (a double microtask from the first enqueue: strictly after the layout + * store's flush and the link port's placement flush, both single-microtask) + * emits the task's ops in dependency order: + * + * 1. structural ops (add_node / delete_node / clear) in layout-store order, + * which IS causal for that class (one store, one queue); + * 2. connect / set_widget in mint order (synchronous feeds, causal within + * the class), which can only depend on nodes rule 1 already placed. + * + * A connect or top-level set_widget naming a node that the same drain + * deletes (delete_node, or a clear's removed_nodes) and does not re-add is + * dropped: rule 1 would land it after the delete, and the local graph + * already lacks the node, so doc and graph agree without it - the same + * argument as the link port's cancelPlacement. Interior set_widget (carries + * `path`) addresses a subgraph definition, not a root node, and is never + * pruned. + */ +import type { GraphOperation } from './graphOperations' + +export interface MintQueue { + /** Port-facing inbox; the drain is scheduled by the first call of a task. */ + enqueue(operations: GraphOperation[]): void + /** Deliver everything queued right now (the detach path). */ + flush(): void +} + +type StructuralOperation = Extract< + GraphOperation, + { op: 'add_node' | 'delete_node' | 'clear' } +> + +function isStructural( + operation: GraphOperation +): operation is StructuralOperation { + return ( + operation.op === 'add_node' || + operation.op === 'delete_node' || + operation.op === 'clear' + ) +} + +/** Pure ordering + pruning of one drain's worth of minted operations. */ +export function orderMintedOperations( + operations: GraphOperation[] +): GraphOperation[] { + const structural = operations.filter(isStructural) + const dependent = operations.filter((operation) => !isStructural(operation)) + const added = new Set() + const removed = new Set() + for (const operation of structural) { + if (operation.op === 'add_node') added.add(String(operation.node_id)) + else if (operation.op === 'delete_node') + removed.add(String(operation.node_id)) + else for (const id of operation.removed_nodes) removed.add(String(id)) + } + const gone = (nodeId: string | number): boolean => { + const key = String(nodeId) + return removed.has(key) && !added.has(key) + } + const kept = dependent.filter((operation) => { + if (operation.op === 'connect') { + return !gone(operation.from_node) && !gone(operation.to_node) + } + if (operation.op === 'set_widget' && operation.path == null) { + return !gone(operation.node_id) + } + return true + }) + return [...structural, ...kept] +} + +export function createMintQueue( + deliver: (operations: GraphOperation[]) => void +): MintQueue { + let queued: GraphOperation[] = [] + let drainScheduled = false + + function drain(): void { + drainScheduled = false + if (queued.length === 0) return + const batch = queued + queued = [] + const ordered = orderMintedOperations(batch) + if (ordered.length > 0) deliver(ordered) + } + + return { + enqueue(operations) { + if (operations.length === 0) return + queued.push(...operations) + if (drainScheduled) return + drainScheduled = true + // Double microtask: the layout store flushes on one, the link port's + // placement window closes on one; this drain must see both. + queueMicrotask(() => queueMicrotask(drain)) + }, + flush() { + drain() + } + } +} diff --git a/src/workbench/extensions/agent/crdt/opSender.test.ts b/src/workbench/extensions/agent/crdt/opSender.test.ts index b4dfe3187ff..fcace72d49a 100644 --- a/src/workbench/extensions/agent/crdt/opSender.test.ts +++ b/src/workbench/extensions/agent/crdt/opSender.test.ts @@ -241,7 +241,7 @@ describe('createOpSender', () => { ok: false, applied: [], skipped: [], - failure: { op_id: 'a'.repeat(32) }, + failure: { op_id: 'a'.repeat(32), index: 0 }, failureOpIds: ['a'.repeat(32)] }) @@ -277,7 +277,7 @@ describe('createOpSender', () => { applied: [], skipped: [], failure: { op_id: 'c'.repeat(32) }, - failureOpIds: ['c'.repeat(32)] + failureOpIds: ['c'.repeat(32), 'd'.repeat(32)] }) // Addresses review feedback (match any failed op_id, not just the first): @@ -298,6 +298,81 @@ describe('createOpSender', () => { }) }) + it('threads the host failure code, message and index through the view', () => { + // Addresses review feedback: + // https://github.com/Comfy-Org/ComfyUI_frontend/pull/16337#discussion_r3892825424 + expect( + toOpsResultView({ + ok: false, + applied: [], + skipped: [], + failed: { + index: 2, + op_id: 'a'.repeat(32), + code: 'op_rejected', + message: 'unknown node 7' + } + }) + ).toEqual({ + ok: false, + applied: [], + skipped: [], + failure: { + op_id: 'a'.repeat(32), + index: 2, + code: 'op_rejected', + message: 'unknown node 7' + }, + failureOpIds: ['a'.repeat(32)] + }) + + // The canonical failure's reason wins over a legacy entry's and the + // frame's top-level code; each field is only taken when on-type. + expect( + toOpsResultView({ + ok: false, + applied: [], + skipped: [], + code: 'frame_code', + message: 'frame message', + failure: { op_id: 'c'.repeat(32), code: 'lww_dropped', index: '0' }, + failed: [{ op_id: 'd'.repeat(32), code: 'legacy', message: 'legacy' }] + }) + ).toEqual({ + ok: false, + applied: [], + skipped: [], + failure: { + op_id: 'c'.repeat(32), + code: 'lww_dropped', + message: 'legacy' + }, + failureOpIds: ['c'.repeat(32), 'd'.repeat(32)] + }) + + // A rejection that names no op still carries its reason (anonymous + // settle keeps working: no failureOpIds). + expect( + toOpsResultView({ + ok: false, + applied: [], + skipped: [], + code: 'batch_too_large', + message: 'too many ops' + }) + ).toEqual({ + ok: false, + applied: [], + skipped: [], + failure: { code: 'batch_too_large', message: 'too many ops' } + }) + + // A successful frame's stray code is not a failure. + expect( + toOpsResultView({ ok: true, applied: ['x'], skipped: [], code: 'noop' }) + ).toEqual({ ok: true, applied: ['x'], skipped: [] }) + }) + it('a canonical empty-list rejection with no failed entries settles as anonymous', () => { // Addresses review feedback: // https://github.com/Comfy-Org/ComfyUI_frontend/pull/16337#discussion_r3893153036 @@ -338,6 +413,33 @@ describe('createOpSender', () => { expect(settled).toHaveLength(0) }) + it('a legacy failed id matching the in-flight batch settles it even under a foreign canonical op_id', () => { + // Addresses review feedback (match against every failure id, not the + // canonical pick alone): + // https://github.com/Comfy-Org/ComfyUI_frontend/pull/16337#discussion_r3915356523 + sender.enqueue([addNode(1)]) + const own = sent[0].ops[0].op_id + + resultListener?.( + toOpsResultView({ + ok: false, + applied: [], + skipped: [], + failure: { op_id: 'ffff'.repeat(8), code: 'op_rejected' }, + failed: [{ op_id: own, code: 'op_rejected', message: 'rejected' }] + }) + ) + + expect(settled).toHaveLength(1) + expect(settled[0]).toMatchObject({ + state: 'acknowledged', + result: { + failure: { op_id: 'ffff'.repeat(8), code: 'op_rejected' }, + failureOpIds: ['ffff'.repeat(8), own] + } + }) + }) + it('idle late results drain the stale credits so a fresh batch can settle anonymously', () => { sender.enqueue([addNode(1)]) vi.advanceTimersByTime(10_000) diff --git a/src/workbench/extensions/agent/crdt/opSender.ts b/src/workbench/extensions/agent/crdt/opSender.ts index c383d6f667a..2ea818de73f 100644 --- a/src/workbench/extensions/agent/crdt/opSender.ts +++ b/src/workbench/extensions/agent/crdt/opSender.ts @@ -28,12 +28,27 @@ export interface OpsResultView { ok: boolean applied: string[] skipped: string[] - /** Failed-batch diagnostics when the host provides them; `op_id` correlates an otherwise empty-list failure to its batch. */ - failure?: { op_id?: string } + /** + * Failed-batch diagnostics when the host provides them. `op_id` correlates + * an otherwise empty-list failure to its batch; `code`, `message` and + * `index` are the host's own reason, threaded through verbatim so the + * settled outcome (dev panel, telemetry) can say WHY a batch failed rather + * than only that it did. + */ + failure?: OpsFailureView /** Every `op_id` found in the host's failure payload (canonical `failure` first, then `failed`), for matching against an in-flight batch's op-id set rather than trusting a single arbitrary pick. */ failureOpIds?: string[] } +interface OpsFailureView { + op_id?: string + /** Wire `DocOpFailure.code` (e.g. `op_rejected`). */ + code?: string + message?: string + /** Position of the failing op within the batch, when the host reports one. */ + index?: number +} + function isRecord(value: unknown): value is Record { return value !== null && typeof value === 'object' } @@ -46,41 +61,76 @@ function failureOpId(value: unknown): string | undefined { return undefined } +/** The host's `failed` payload as a list: absent, one object, or an array. */ +function failedEntries(failed: unknown): unknown[] { + if (Array.isArray(failed)) return failed + return failed === undefined ? [] : [failed] +} + /** All `op_id`s findable across the host's `failed` payload, in wire order. */ function allFailureOpIds(failed: unknown): string[] { - const failures = Array.isArray(failed) - ? failed - : failed === undefined - ? [] - : [failed] - return failures + return failedEntries(failed) .map(failureOpId) .filter((id): id is string => id !== undefined) } -export function toOpsResultView( - detail: (OpsResultView & { failed?: unknown }) | null | undefined -): OpsResultView { +/** `code` / `message` / `index` from one host failure object, dropping anything off-type. */ +function failureDiagnostics(value: unknown): Omit { + if (!isRecord(value)) return {} + return { + ...(typeof value.code === 'string' && { code: value.code }), + ...(typeof value.message === 'string' && { message: value.message }), + ...(typeof value.index === 'number' && { index: value.index }) + } +} + +/** + * Normalize a `doc_ops_result` detail of ANY shape (the bridge forwards the + * frame client's parsed data, but the event contract is `unknown`) into the + * sender's view. A canonical `failure` from the host is authoritative for + * the single correlating `op_id`; `failed` (object or array, the shipped PoC + * shapes) contributes every further op_id so a batch can settle on any of + * them. Diagnostics come from the canonical failure, else the `failed` entry + * that names an op, else the frame's top-level `code` / `message`. + */ +export function toOpsResultView(detail: unknown): OpsResultView { if (!isRecord(detail)) { return { ok: false, applied: [], skipped: [] } } - // A canonical `failure` from the host is authoritative; only derive one - // from `failed` when the host did not supply it. + const canonical = isRecord(detail.failure) ? detail.failure : undefined const canonicalOpId = - isRecord(detail.failure) && typeof detail.failure.op_id === 'string' - ? detail.failure.op_id - : undefined - const candidateOpIds = + typeof canonical?.op_id === 'string' ? canonical.op_id : undefined + const failedIds = allFailureOpIds(detail.failed) + const failureOpIds = canonicalOpId !== undefined - ? [canonicalOpId] - : allFailureOpIds(detail.failed) + ? [canonicalOpId, ...failedIds.filter((id) => id !== canonicalOpId)] + : failedIds + // Legacy diagnostics come from the entry that names an op (so index and + // op_id describe the same failure), else the first entry. + const legacy = failedEntries(detail.failed) + const legacyDiagnostics = + legacy.find((entry) => failureOpId(entry) !== undefined) ?? legacy[0] + const diagnostics = { + ...failureDiagnostics(detail), + ...failureDiagnostics(legacyDiagnostics), + ...failureDiagnostics(canonical) + } + const ok = Boolean(detail.ok) + // Diagnostics alone only describe a failure on a failed frame; a success + // frame's stray `code` is not one. + const hasFailure = + failureOpIds.length > 0 || (!ok && Object.keys(diagnostics).length > 0) return { - ok: Boolean(detail.ok), + ok, applied: Array.isArray(detail.applied) ? detail.applied : [], skipped: Array.isArray(detail.skipped) ? detail.skipped : [], - ...(candidateOpIds.length > 0 - ? { failure: { op_id: candidateOpIds[0] }, failureOpIds: candidateOpIds } - : {}) + ...(hasFailure && { + failure: { + ...(failureOpIds.length > 0 && { op_id: failureOpIds[0] }), + ...diagnostics + } + }), + ...(failureOpIds.length > 0 && { failureOpIds }) } } diff --git a/src/workbench/extensions/agent/crdt/useAgentCrdtFollower.ts b/src/workbench/extensions/agent/crdt/useAgentCrdtFollower.ts index 7b337aaf462..d519608526c 100644 --- a/src/workbench/extensions/agent/crdt/useAgentCrdtFollower.ts +++ b/src/workbench/extensions/agent/crdt/useAgentCrdtFollower.ts @@ -12,7 +12,6 @@ import type { MutationsForTarget } from './ecsFollowerAdapter' import { EcsFollowerAdapter } from './ecsFollowerAdapter' import type { GraphOperation } from './graphOperations' import { LayoutFollowerBridge } from './layoutFollowerBridge' -import type { OpsResultView } from './opSender' import { createOpSender, toOpsResultView } from './opSender' // FE-1902: the doc id is otherwise held only in memory (set on turn ack), so a @@ -185,11 +184,7 @@ export function useAgentCrdtFollower( onOpsResult(listener) { const handler: EventListener = (event) => { if (!(event instanceof CustomEvent)) return - const detail = event.detail as - | (OpsResultView & { failed?: unknown }) - | null - | undefined - listener(toOpsResultView(detail)) + listener(toOpsResultView(event.detail)) } bridge.addEventListener('doc_ops_result', handler) return () => bridge.removeEventListener('doc_ops_result', handler) From 161781ea104a88adcb395218f6cf904eab2fcb08 Mon Sep 17 00:00:00 2001 From: bymyself Date: Fri, 4 Sep 2026 23:52:48 +0000 Subject: [PATCH 09/14] test(crdt): remove review-history annotations Addresses https://github.com/Comfy-Org/ComfyUI_frontend/pull/16337#discussion_r3936083994 --- .../extensions/agent/crdt/linkMintPort.test.ts | 4 ---- .../extensions/agent/crdt/opSender.test.ts | 13 ------------- 2 files changed, 17 deletions(-) diff --git a/src/workbench/extensions/agent/crdt/linkMintPort.test.ts b/src/workbench/extensions/agent/crdt/linkMintPort.test.ts index 584c19e6473..79235da9437 100644 --- a/src/workbench/extensions/agent/crdt/linkMintPort.test.ts +++ b/src/workbench/extensions/agent/crdt/linkMintPort.test.ts @@ -201,8 +201,6 @@ describe('attachLinkMintPort', () => { }) it('cancels a same-task deletion of an unflushed placement without a phantom connect', async () => { - // Addresses review feedback: - // https://github.com/Comfy-Org/ComfyUI_frontend/pull/16337#discussion_r3893153026 const consoleError = vi .spyOn(console, 'error') .mockImplementation(() => undefined) @@ -221,8 +219,6 @@ describe('attachLinkMintPort', () => { }) it('flushes and surfaces pending placements on detach instead of discarding them silently', () => { - // Addresses review feedback: - // https://github.com/Comfy-Org/ComfyUI_frontend/pull/16337#discussion_r3892825337 const consoleError = vi .spyOn(console, 'error') .mockImplementation(() => undefined) diff --git a/src/workbench/extensions/agent/crdt/opSender.test.ts b/src/workbench/extensions/agent/crdt/opSender.test.ts index fcace72d49a..3eeb84c9a36 100644 --- a/src/workbench/extensions/agent/crdt/opSender.test.ts +++ b/src/workbench/extensions/agent/crdt/opSender.test.ts @@ -262,8 +262,6 @@ describe('createOpSender', () => { }) it('preserves a canonical failure over a derived one, and collects every failed op_id', () => { - // Addresses review feedback: - // https://github.com/Comfy-Org/ComfyUI_frontend/pull/16337#discussion_r3893153055 expect( toOpsResultView({ ok: false, @@ -280,8 +278,6 @@ describe('createOpSender', () => { failureOpIds: ['c'.repeat(32), 'd'.repeat(32)] }) - // Addresses review feedback (match any failed op_id, not just the first): - // https://github.com/Comfy-Org/ComfyUI_frontend/pull/16337#discussion_r3892825409 expect( toOpsResultView({ ok: false, @@ -299,8 +295,6 @@ describe('createOpSender', () => { }) it('threads the host failure code, message and index through the view', () => { - // Addresses review feedback: - // https://github.com/Comfy-Org/ComfyUI_frontend/pull/16337#discussion_r3892825424 expect( toOpsResultView({ ok: false, @@ -374,8 +368,6 @@ describe('createOpSender', () => { }) it('a canonical empty-list rejection with no failed entries settles as anonymous', () => { - // Addresses review feedback: - // https://github.com/Comfy-Org/ComfyUI_frontend/pull/16337#discussion_r3893153036 expect( toOpsResultView({ ok: false, applied: [], skipped: [], failed: [] }) ).toEqual({ @@ -386,8 +378,6 @@ describe('createOpSender', () => { }) it('returns a safe empty view for a null or undefined doc_ops_result detail', () => { - // Addresses review feedback: - // https://github.com/Comfy-Org/ComfyUI_frontend/pull/16337#discussion_r3892825397 expect(toOpsResultView(null)).toEqual({ ok: false, applied: [], @@ -414,9 +404,6 @@ describe('createOpSender', () => { }) it('a legacy failed id matching the in-flight batch settles it even under a foreign canonical op_id', () => { - // Addresses review feedback (match against every failure id, not the - // canonical pick alone): - // https://github.com/Comfy-Org/ComfyUI_frontend/pull/16337#discussion_r3915356523 sender.enqueue([addNode(1)]) const own = sent[0].ops[0].op_id From fe1f7bd4afcb4c7a28aa3d4cffb5f0614ba0a07e Mon Sep 17 00:00:00 2001 From: Amp Date: Tue, 8 Sep 2026 08:54:51 +0000 Subject: [PATCH 10/14] fix: prune mint dependents after node deletion Amp-Thread-ID: https://ampcode.com/threads/T-01a06e6b-d121-716d-97b8-9d9d5ac221a3 --- src/workbench/extensions/agent/crdt/mintQueue.test.ts | 11 +++++++++++ src/workbench/extensions/agent/crdt/mintQueue.ts | 6 ++---- 2 files changed, 13 insertions(+), 4 deletions(-) diff --git a/src/workbench/extensions/agent/crdt/mintQueue.test.ts b/src/workbench/extensions/agent/crdt/mintQueue.test.ts index e48f9066ebc..c6ce0574eb4 100644 --- a/src/workbench/extensions/agent/crdt/mintQueue.test.ts +++ b/src/workbench/extensions/agent/crdt/mintQueue.test.ts @@ -80,6 +80,17 @@ describe('orderMintedOperations', () => { ).toEqual([deleteNode(2), setWidget(3, 'kept'), connect(42, 1, 3)]) }) + it('drops dependents when a node is added and then deleted', () => { + expect( + orderMintedOperations([ + addNode(2), + deleteNode(2), + setWidget(2, 'x'), + connect(41, 1, 2) + ]) + ).toEqual([addNode(2), deleteNode(2)]) + }) + it("drops writes to a clear's removed nodes but not to nodes added after it", () => { expect( orderMintedOperations([ diff --git a/src/workbench/extensions/agent/crdt/mintQueue.ts b/src/workbench/extensions/agent/crdt/mintQueue.ts index d8575e72d9b..d5b24353f96 100644 --- a/src/workbench/extensions/agent/crdt/mintQueue.ts +++ b/src/workbench/extensions/agent/crdt/mintQueue.ts @@ -54,17 +54,15 @@ export function orderMintedOperations( ): GraphOperation[] { const structural = operations.filter(isStructural) const dependent = operations.filter((operation) => !isStructural(operation)) - const added = new Set() const removed = new Set() for (const operation of structural) { - if (operation.op === 'add_node') added.add(String(operation.node_id)) + if (operation.op === 'add_node') removed.delete(String(operation.node_id)) else if (operation.op === 'delete_node') removed.add(String(operation.node_id)) else for (const id of operation.removed_nodes) removed.add(String(id)) } const gone = (nodeId: string | number): boolean => { - const key = String(nodeId) - return removed.has(key) && !added.has(key) + return removed.has(String(nodeId)) } const kept = dependent.filter((operation) => { if (operation.op === 'connect') { From f2ff56d863ddea18831ef15af3aeeedd824c1e0b Mon Sep 17 00:00:00 2001 From: christian-byrne Date: Thu, 10 Sep 2026 18:22:26 -0700 Subject: [PATCH 11/14] fix(agent-crdt): key link placements by the branded link id LinkTopologyView.id was typed string | number while its only producer, linkStore's LinkTopology, carries a branded-number LinkId. placementKey's String() therefore mapped 41 and '41' onto one key. Narrowing the view to LinkId makes the collision unrepresentable instead of defending against it in the key. Addresses review feedback: https://github.com/Comfy-Org/ComfyUI_frontend/pull/16337#discussion_r3954716965 --- .../extensions/agent/crdt/linkMintPort.test.ts | 4 +++- src/workbench/extensions/agent/crdt/linkMintPort.ts | 12 +++++++----- 2 files changed, 10 insertions(+), 6 deletions(-) diff --git a/src/workbench/extensions/agent/crdt/linkMintPort.test.ts b/src/workbench/extensions/agent/crdt/linkMintPort.test.ts index 919148afa9b..1fd51bf49c0 100644 --- a/src/workbench/extensions/agent/crdt/linkMintPort.test.ts +++ b/src/workbench/extensions/agent/crdt/linkMintPort.test.ts @@ -1,5 +1,7 @@ import { beforeEach, describe, expect, it, vi } from 'vitest' +import { toLinkId } from '@/types/linkId' + import type { GraphOperation } from './graphOperations' import { attachLinkMintPort } from './linkMintPort' import type { @@ -21,7 +23,7 @@ const SUBGRAPH_SCOPE: LinkScopeView = { function topology(id: number): LinkTopologyView { return { - id, + id: toLinkId(id), originNodeId: 1, originSlot: 0, targetNodeId: 2, diff --git a/src/workbench/extensions/agent/crdt/linkMintPort.ts b/src/workbench/extensions/agent/crdt/linkMintPort.ts index 7daa0662155..6aebd4c5200 100644 --- a/src/workbench/extensions/agent/crdt/linkMintPort.ts +++ b/src/workbench/extensions/agent/crdt/linkMintPort.ts @@ -12,6 +12,8 @@ */ import type { NodeId as WireNodeId } from '@comfyorg/comfy-multi-player' +import type { LinkId } from '@/types/linkId' + import type { GraphOperation } from './graphOperations' import { shouldMint } from './mintGate' import type { MintSession } from './mintSession' @@ -28,7 +30,7 @@ export interface LinkScopeView { * link - the wiring feed filters those out before this port sees them. */ export interface LinkTopologyView { - id: string | number + id: LinkId originNodeId: string | number originSlot: number targetNodeId: string | number @@ -76,7 +78,7 @@ export interface LinkMintPort { } interface SeveranceEntry { - linkId: WireNodeId + linkId: LinkId /** The gate was open at severance: unconsumed means a real divergence. */ mintable: boolean } @@ -90,7 +92,7 @@ function placementKey( scope: LinkScopeView, topology: LinkTopologyView ): string { - return `${scope.rootGraphId}:${String(topology.id)}` + return `${scope.rootGraphId}:${topology.id}` } export function attachLinkMintPort(deps: LinkMintPortDeps): LinkMintPort { @@ -98,7 +100,7 @@ export function attachLinkMintPort(deps: LinkMintPortDeps): LinkMintPort { const consumedLinkIds = new Set() const pendingPlacements = new Map< string, - { operation: GraphOperation; linkId: string | number } + { operation: GraphOperation; linkId: LinkId } >() let sweepScheduled = false let detached = false @@ -111,7 +113,7 @@ export function attachLinkMintPort(deps: LinkMintPortDeps): LinkMintPort { }) } - function surfaceUnrepresentable(what: string, id: string | number): void { + function surfaceUnrepresentable(what: string, id: LinkId): void { // A doc that no longer matches the local graph must be observable, // never silent (the surfacing-honesty principle). console.error( From 1638ac92baf22c5c48f3c7fefd0ce17ab9e0442e Mon Sep 17 00:00:00 2001 From: christian-byrne Date: Thu, 10 Sep 2026 18:22:58 -0700 Subject: [PATCH 12/14] fix(agent-crdt): normalize doc_ops_result strictly detail is an unknown bridge payload: Boolean() turned a wire "false" into a successful result, and the array branches passed non-string entries through as op ids the sender then matched batches on. Addresses review feedback: https://github.com/Comfy-Org/ComfyUI_frontend/pull/16337#discussion_r3954716991 --- .../extensions/agent/crdt/opSender.test.ts | 14 ++++++++++++++ src/workbench/extensions/agent/crdt/opSender.ts | 12 +++++++++--- 2 files changed, 23 insertions(+), 3 deletions(-) diff --git a/src/workbench/extensions/agent/crdt/opSender.test.ts b/src/workbench/extensions/agent/crdt/opSender.test.ts index ef01fbd3408..08b77dd14ce 100644 --- a/src/workbench/extensions/agent/crdt/opSender.test.ts +++ b/src/workbench/extensions/agent/crdt/opSender.test.ts @@ -547,6 +547,20 @@ describe('createOpSender', () => { }) }) + it('reads only a literal true as success and keeps only string op ids', () => { + expect( + toOpsResultView({ + ok: 'false', + applied: ['a'.repeat(32), 7, null], + skipped: [{ op_id: 'b'.repeat(32) }] + }) + ).toEqual({ + ok: false, + applied: ['a'.repeat(32)], + skipped: [] + }) + }) + it('returns a safe empty view for a null or undefined doc_ops_result detail', () => { expect(toOpsResultView(null)).toEqual({ ok: false, diff --git a/src/workbench/extensions/agent/crdt/opSender.ts b/src/workbench/extensions/agent/crdt/opSender.ts index f56106d2527..34f43195c26 100644 --- a/src/workbench/extensions/agent/crdt/opSender.ts +++ b/src/workbench/extensions/agent/crdt/opSender.ts @@ -75,6 +75,12 @@ function allFailureOpIds(failed: unknown): string[] { .filter((id): id is string => id !== undefined) } +/** A host id list, keeping only the `op_id` strings the sender can match on. */ +function opIdList(value: unknown): string[] { + if (!Array.isArray(value)) return [] + return value.filter((entry): entry is string => typeof entry === 'string') +} + /** `code` / `message` / `index` from one host failure object, dropping anything off-type. */ function failureDiagnostics(value: unknown): Omit { if (!isRecord(value)) return {} @@ -116,7 +122,7 @@ export function toOpsResultView(detail: unknown): OpsResultView { ...failureDiagnostics(legacyDiagnostics), ...failureDiagnostics(canonical) } - const ok = Boolean(detail.ok) + const ok = detail.ok === true // Diagnostics alone only describe a failure on a failed frame; a success // frame's stray `code` is not one. const hasFailure = @@ -126,8 +132,8 @@ export function toOpsResultView(detail: unknown): OpsResultView { workflowId: detail.workflowId }), ok, - applied: Array.isArray(detail.applied) ? detail.applied : [], - skipped: Array.isArray(detail.skipped) ? detail.skipped : [], + applied: opIdList(detail.applied), + skipped: opIdList(detail.skipped), ...(hasFailure && { failure: { ...(failureOpIds.length > 0 && { op_id: failureOpIds[0] }), From 187a62b9bd0e8f0eb66815de44685d2dcc9128d7 Mon Sep 17 00:00:00 2001 From: christian-byrne Date: Thu, 10 Sep 2026 18:23:46 -0700 Subject: [PATCH 13/14] fix(agent-crdt): report link divergence through reportError console.error reaches one sink, so an unrepresentable link change read as zero in the other console. reportError() still writes the console line, so the direct call is dropped rather than duplicated. Addresses review feedback: https://github.com/Comfy-Org/ComfyUI_frontend/pull/16337#discussion_r3954716972 --- .../agent/crdt/linkMintPort.test.ts | 62 +++++++++---------- .../extensions/agent/crdt/linkMintPort.ts | 12 +++- 2 files changed, 38 insertions(+), 36 deletions(-) diff --git a/src/workbench/extensions/agent/crdt/linkMintPort.test.ts b/src/workbench/extensions/agent/crdt/linkMintPort.test.ts index 1fd51bf49c0..f32de063063 100644 --- a/src/workbench/extensions/agent/crdt/linkMintPort.test.ts +++ b/src/workbench/extensions/agent/crdt/linkMintPort.test.ts @@ -12,6 +12,9 @@ import type { import { createMintSession } from './mintSession' import type { MintSession } from './mintSession' +const { reportError } = vi.hoisted(() => ({ reportError: vi.fn() })) +vi.mock(import('@/platform/telemetry/reportError'), () => ({ reportError })) + const ROOT_SCOPE: LinkScopeView = { rootGraphId: 'root-uuid', owningGraphId: 'root-uuid' @@ -124,14 +127,10 @@ describe('attachLinkMintPort', () => { }) it('surfaces a subgraph-interior placement observably instead of minting', () => { - const consoleError = vi - .spyOn(console, 'error') - .mockImplementation(() => undefined) place(SUBGRAPH_SCOPE, topology(41)) expect(minted).toEqual([]) - expect(consoleError).toHaveBeenCalledOnce() - consoleError.mockRestore() + expect(reportError).toHaveBeenCalledOnce() }) it('captures a severed link under both endpoints, consumed exactly once', () => { @@ -142,40 +141,34 @@ describe('attachLinkMintPort', () => { }) it('surfaces an unconsumed local disconnect as divergence after the sweep', async () => { - const consoleError = vi - .spyOn(console, 'error') - .mockImplementation(() => undefined) remove(ROOT_SCOPE, topology(41)) await afterSweep() - expect(consoleError).toHaveBeenCalledOnce() - expect(consoleError.mock.calls[0][1]).toBe(41) - consoleError.mockRestore() + expect(reportError).toHaveBeenCalledOnce() + expect(reportError).toHaveBeenCalledWith( + expect.any(Error), + expect.objectContaining({ + errorType: 'agent_crdt_unrepresentable_link_change', + tags: expect.objectContaining({ linkId: 41 }) + }) + ) }) it('stays silent for a consumed severance (the delete carried it)', async () => { - const consoleError = vi - .spyOn(console, 'error') - .mockImplementation(() => undefined) remove(ROOT_SCOPE, topology(41)) port.severances.take('1') await afterSweep() - expect(consoleError).not.toHaveBeenCalled() - consoleError.mockRestore() + expect(reportError).not.toHaveBeenCalled() }) it('stays silent for teardown severances', async () => { - const consoleError = vi - .spyOn(console, 'error') - .mockImplementation(() => undefined) session.beginGraphTeardown() remove(ROOT_SCOPE, topology(41)) session.endGraphTeardown() await afterSweep() - expect(consoleError).not.toHaveBeenCalled() - consoleError.mockRestore() + expect(reportError).not.toHaveBeenCalled() }) it('sweeps the capture window: a later take finds nothing', async () => { @@ -196,9 +189,6 @@ describe('attachLinkMintPort', () => { }) it('cancels a same-task deletion of an unflushed placement without a phantom connect', async () => { - const consoleError = vi - .spyOn(console, 'error') - .mockImplementation(() => undefined) place(ROOT_SCOPE, topology(41)) remove(ROOT_SCOPE, topology(41)) await afterSweep() @@ -208,21 +198,27 @@ describe('attachLinkMintPort', () => { // still runs and correctly reports the unconsumed disconnect - it was a // real local delete that nothing (e.g. a delete_node mint) consumed. expect(minted).toEqual([]) - expect(consoleError).toHaveBeenCalledOnce() - expect(consoleError.mock.calls[0][0]).toContain('link disconnect') - consoleError.mockRestore() + expect(reportError).toHaveBeenCalledOnce() + expect(reportError).toHaveBeenCalledWith( + expect.objectContaining({ + message: expect.stringContaining('link disconnect') + }), + expect.anything() + ) }) it('flushes and surfaces pending placements on detach instead of discarding them silently', () => { - const consoleError = vi - .spyOn(console, 'error') - .mockImplementation(() => undefined) place(ROOT_SCOPE, topology(41)) port.detach() expect(minted).toEqual([]) - expect(consoleError).toHaveBeenCalledOnce() - expect(consoleError.mock.calls[0][1]).toBe(41) - consoleError.mockRestore() + expect(reportError).toHaveBeenCalledOnce() + expect(reportError).toHaveBeenCalledWith( + expect.any(Error), + expect.objectContaining({ + errorType: 'agent_crdt_unrepresentable_link_change', + tags: expect.objectContaining({ linkId: 41 }) + }) + ) }) }) diff --git a/src/workbench/extensions/agent/crdt/linkMintPort.ts b/src/workbench/extensions/agent/crdt/linkMintPort.ts index 6aebd4c5200..725da7e4188 100644 --- a/src/workbench/extensions/agent/crdt/linkMintPort.ts +++ b/src/workbench/extensions/agent/crdt/linkMintPort.ts @@ -12,6 +12,7 @@ */ import type { NodeId as WireNodeId } from '@comfyorg/comfy-multi-player' +import { reportError } from '@/platform/telemetry/reportError' import type { LinkId } from '@/types/linkId' import type { GraphOperation } from './graphOperations' @@ -116,9 +117,14 @@ export function attachLinkMintPort(deps: LinkMintPortDeps): LinkMintPort { function surfaceUnrepresentable(what: string, id: LinkId): void { // A doc that no longer matches the local graph must be observable, // never silent (the surfacing-honesty principle). - console.error( - `[agent-crdt] ${what} has no wire op; the bound doc diverges from the local graph`, - id + reportError( + new Error( + `[agent-crdt] ${what} has no wire op; the bound doc diverges from the local graph` + ), + { + errorType: 'agent_crdt_unrepresentable_link_change', + tags: { change: what, linkId: id } + } ) } From fbcfd6d98683b63bbe5caba1bfbf35a57d4d7113 Mon Sep 17 00:00:00 2001 From: christian-byrne Date: Thu, 10 Sep 2026 18:24:31 -0700 Subject: [PATCH 14/14] fix: only the owning publisher clears the workspace inset GraphCanvas and LinearView both host the agent dock and GraphView swaps them on linearMode, so the incoming panel publishes its width before the outgoing one disposes. The outgoing teardown then wrote 0px over a live value. Addresses review feedback: https://github.com/Comfy-Org/ComfyUI_frontend/pull/16337#discussion_r3954716960 --- src/composables/useWorkspaceInset.test.ts | 11 +++++++++++ src/composables/useWorkspaceInset.ts | 9 +++++++++ 2 files changed, 20 insertions(+) diff --git a/src/composables/useWorkspaceInset.test.ts b/src/composables/useWorkspaceInset.test.ts index 4f3b5642831..4ec41a40169 100644 --- a/src/composables/useWorkspaceInset.test.ts +++ b/src/composables/useWorkspaceInset.test.ts @@ -65,4 +65,15 @@ describe('useWorkspaceInsetRight', () => { // every portaled overlay permanently offset. expect(readInset()).toBe('0px') }) + + it('leaves the incoming publisher alone when the outgoing one disposes', () => { + const outgoing = effectScope() + outgoing.run(() => useWorkspaceInsetRight(() => 420)) + runInScope(() => 960) + + // A mode switch mounts the new docked host before unmounting the old one. + outgoing.stop() + + expect(readInset()).toBe('960px') + }) }) diff --git a/src/composables/useWorkspaceInset.ts b/src/composables/useWorkspaceInset.ts index 7f42b889ad9..c583d4a22d7 100644 --- a/src/composables/useWorkspaceInset.ts +++ b/src/composables/useWorkspaceInset.ts @@ -9,8 +9,12 @@ import { onScopeDispose, watchEffect } from 'vue' */ export const WORKSPACE_INSET_RIGHT = '--workspace-inset-right' +let activePublisher: symbol | null = null + export function useWorkspaceInsetRight(widthPx: () => number): void { + const publisher = Symbol('workspace-inset-right') watchEffect(() => { + activePublisher = publisher document.documentElement.style.setProperty( WORKSPACE_INSET_RIGHT, `${widthPx()}px` @@ -20,7 +24,12 @@ export function useWorkspaceInsetRight(widthPx: () => number): void { // its host is unmounted BEFORE that branch flips (e.g. a parent `v-if` // unmounts the whole component in the same flush as closing it) - clear // the var directly on teardown so it cannot survive its publisher. + // + // Mode switches mount the incoming publisher before the outgoing one + // disposes (GraphCanvas and LinearView both host the dock), so only the + // surface still owning the variable may clear it. onScopeDispose(() => { + if (activePublisher !== publisher) return document.documentElement.style.setProperty(WORKSPACE_INSET_RIGHT, '0px') }) }