From c9344394d765b661b4aded37264c160e48daa13c Mon Sep 17 00:00:00 2001 From: Christian Byrne Date: Thu, 3 Sep 2026 14:34:47 -0700 Subject: [PATCH 1/7] fix(agent-crdt): preserve same-document acknowledgement --- .../useAgentCrdtFollower.integration.test.ts | 149 ++++++++++++++++++ .../agent/crdt/useAgentCrdtFollower.ts | 1 + 2 files changed, 150 insertions(+) create mode 100644 src/workbench/extensions/agent/crdt/useAgentCrdtFollower.integration.test.ts diff --git a/src/workbench/extensions/agent/crdt/useAgentCrdtFollower.integration.test.ts b/src/workbench/extensions/agent/crdt/useAgentCrdtFollower.integration.test.ts new file mode 100644 index 00000000000..2f32859a67f --- /dev/null +++ b/src/workbench/extensions/agent/crdt/useAgentCrdtFollower.integration.test.ts @@ -0,0 +1,149 @@ +import { fromPartial } from '@total-typescript/shoehorn' +import { beforeEach, describe, expect, it, vi } from 'vitest' +import { defineComponent, nextTick, ref } from 'vue' +import type { Ref } from 'vue' + +import { render } from '@testing-library/vue' + +import type { GraphMutations } from '@/core/graph/graphMutations' + +const apiState = vi.hoisted(() => { + const docFrames = new EventTarget() + const socketEvents = new EventTarget() + const send = vi.fn() + + return { + docFrames, + socketEvents, + send, + api: { + socket: { readyState: 1, send }, + addCustomEventListener: (type: string, listener: EventListener) => + docFrames.addEventListener(type, listener), + removeCustomEventListener: (type: string, listener: EventListener) => + docFrames.removeEventListener(type, listener), + addEventListener: (type: string, listener: EventListener) => + socketEvents.addEventListener(type, listener), + removeEventListener: (type: string, listener: EventListener) => + socketEvents.removeEventListener(type, listener) + } + } +}) + +vi.mock('@/scripts/api', () => ({ api: apiState.api })) +vi.mock('@/scripts/app', () => ({ app: { graph: null, canvas: null } })) + +import { STALE_AFTER_MS, useAgentCrdtFollower } from './useAgentCrdtFollower' +import type { AgentCrdtStatus } from './useAgentCrdtFollower' + +const graphMutations = fromPartial({ + clearSemanticGraph: vi.fn(() => true) +}) + +interface SentFrame { + type: string + data: { workflow_id: string } +} + +function framesSent(): SentFrame[] { + return apiState.send.mock.calls.map( + ([frame]) => JSON.parse(frame) as SentFrame + ) +} + +function dispatchServerFrame( + type: string, + data: Record +): void { + apiState.docFrames.dispatchEvent( + new CustomEvent(type, { detail: { v: 1, ...data } }) + ) +} + +function mountFollower(initialWorkflowId: string | null): { + unmount: () => void + workflowId: Ref + status: () => AgentCrdtStatus +} { + const workflowId = ref(initialWorkflowId) + let readStatus!: () => AgentCrdtStatus + const host = defineComponent({ + setup() { + const { status } = useAgentCrdtFollower(workflowId, graphMutations) + readStatus = () => status.value as AgentCrdtStatus + return () => null + } + }) + const { unmount } = render(host) + return { unmount, workflowId, status: readStatus } +} + +describe('useAgentCrdtFollower production subscription composition', () => { + beforeEach(() => { + sessionStorage.clear() + apiState.send.mockClear() + }) + + it('preserves a restored same-document subscription through acknowledgement', async () => { + vi.useFakeTimers() + const initial = mountFollower('doc-a') + dispatchServerFrame('doc_subscribed', { + workflow_id: 'doc-a', + ok: true, + seq: 1 + }) + initial.unmount() + apiState.send.mockClear() + + const restored = mountFollower(null) + expect(framesSent()).toEqual([ + expect.objectContaining({ + type: 'doc_subscribe', + data: expect.objectContaining({ workflow_id: 'doc-a' }) + }) + ]) + dispatchServerFrame('doc_subscribed', { + workflow_id: 'doc-a', + ok: true, + seq: 1 + }) + apiState.send.mockClear() + + restored.workflowId.value = 'doc-a' + await nextTick() + + expect(restored.status().connected).toBe(true) + expect(framesSent()).toEqual([]) + + vi.advanceTimersByTime(STALE_AFTER_MS) + expect(framesSent()).toEqual([ + expect.objectContaining({ + type: 'doc_subscribe', + data: expect.objectContaining({ workflow_id: 'doc-a' }) + }) + ]) + expect(framesSent()).not.toContainEqual( + expect.objectContaining({ type: 'doc_ops' }) + ) + apiState.send.mockClear() + + restored.workflowId.value = 'doc-b' + await nextTick() + + expect(restored.status()).toMatchObject({ + connected: false, + workflowId: 'doc-b' + }) + expect(framesSent()).toEqual([ + expect.objectContaining({ + type: 'doc_unsubscribe', + data: expect.objectContaining({ workflow_id: 'doc-a' }) + }), + expect.objectContaining({ + type: 'doc_subscribe', + data: expect.objectContaining({ workflow_id: 'doc-b' }) + }) + ]) + restored.unmount() + }) +}) diff --git a/src/workbench/extensions/agent/crdt/useAgentCrdtFollower.ts b/src/workbench/extensions/agent/crdt/useAgentCrdtFollower.ts index 2926a4089b5..a1a946c4042 100644 --- a/src/workbench/extensions/agent/crdt/useAgentCrdtFollower.ts +++ b/src/workbench/extensions/agent/crdt/useAgentCrdtFollower.ts @@ -631,6 +631,7 @@ export function useAgentCrdtFollower( // (`previous` is undefined there), so a plain mount or retarget keeps its // existing "reconcile on frame or on graph readiness" behaviour. const justActivated = active && previous?.[1] === false + if (active && next !== null && next === subscribedWorkflowId.value) return clearSubscribeRetry() clearStaleProbe() connected.value = false From 621cc6e9f1e86e4022a92c69f250a4429d035ea1 Mon Sep 17 00:00:00 2001 From: Christian Byrne Date: Thu, 3 Sep 2026 15:24:45 -0700 Subject: [PATCH 2/7] fix(agent-crdt): document the same-document acknowledgement guard and pin its activation boundary --- .../agent/crdt/useAgentCrdtFollower.test.ts | 19 +++++++++++++++++++ .../agent/crdt/useAgentCrdtFollower.ts | 11 ++++++++++- 2 files changed, 29 insertions(+), 1 deletion(-) diff --git a/src/workbench/extensions/agent/crdt/useAgentCrdtFollower.test.ts b/src/workbench/extensions/agent/crdt/useAgentCrdtFollower.test.ts index 6e805620ef1..38e76fdf68d 100644 --- a/src/workbench/extensions/agent/crdt/useAgentCrdtFollower.test.ts +++ b/src/workbench/extensions/agent/crdt/useAgentCrdtFollower.test.ts @@ -877,6 +877,25 @@ describe('useAgentCrdtFollower', () => { unmount() }) + it('FE-1969: a same-document activation edge still resets and re-subscribes', async () => { + const { unmount, isTargetActive, status } = mountFollower('wf-a') + dispatchFrame('doc_subscribed', { ok: true }) + expect(status().connected).toBe(true) + expect(bridge().subscribe).toHaveBeenCalledTimes(1) + + isTargetActive.value = false + await nextTick() + expect(status()).toMatchObject({ connected: false, workflowId: null }) + expect(bridge().unsubscribe).toHaveBeenCalledTimes(1) + + isTargetActive.value = true + await nextTick() + expect(status()).toMatchObject({ connected: false, workflowId: 'wf-a' }) + expect(bridge().subscribe).toHaveBeenCalledTimes(2) + expect(bridge().subscribe).toHaveBeenLastCalledWith('wf-a') + unmount() + }) + it('sends minted human operations through the doc client', () => { const workflowId = ref('wf-1') let enqueue!: ReturnType< diff --git a/src/workbench/extensions/agent/crdt/useAgentCrdtFollower.ts b/src/workbench/extensions/agent/crdt/useAgentCrdtFollower.ts index a1a946c4042..8deee5137fd 100644 --- a/src/workbench/extensions/agent/crdt/useAgentCrdtFollower.ts +++ b/src/workbench/extensions/agent/crdt/useAgentCrdtFollower.ts @@ -627,11 +627,20 @@ export function useAgentCrdtFollower( [next, active], previous: [string | null | undefined, boolean | undefined] | undefined ) => { + // An acknowledgement of the doc we already follow (FE-1969: a persisted + // rebind lands first, then the reactive layer names the same id) is not + // a retarget. `bridge.subscribe(same)` is a `reconcile()` no-op because + // `sentWorkflowId === desired`, so running the reset below would zero + // `connected` and cancel the stale probe and any pending retry with no + // frame on its way to restore them. Safe to skip the rest: the inactive + // branch nulls `subscribedWorkflowId`, so an activation edge can never + // match here, and `initialBind` is already false on every path that + // leaves `subscribedWorkflowId` set. + if (active && next !== null && next === subscribedWorkflowId.value) return // Only the inactive->active edge, and never the `immediate` first run // (`previous` is undefined there), so a plain mount or retarget keeps its // existing "reconcile on frame or on graph readiness" behaviour. const justActivated = active && previous?.[1] === false - if (active && next !== null && next === subscribedWorkflowId.value) return clearSubscribeRetry() clearStaleProbe() connected.value = false From ec6f16ebb014b68cb6b98a03c7d1b77067491c3e Mon Sep 17 00:00:00 2001 From: bymyself Date: Fri, 18 Sep 2026 09:55:16 -0700 Subject: [PATCH 3/7] test(agent): type follower integration mocks --- .../crdt/useAgentCrdtFollower.integration.test.ts | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/src/workbench/extensions/agent/crdt/useAgentCrdtFollower.integration.test.ts b/src/workbench/extensions/agent/crdt/useAgentCrdtFollower.integration.test.ts index 2f32859a67f..e0fec48e10e 100644 --- a/src/workbench/extensions/agent/crdt/useAgentCrdtFollower.integration.test.ts +++ b/src/workbench/extensions/agent/crdt/useAgentCrdtFollower.integration.test.ts @@ -6,6 +6,8 @@ import type { Ref } from 'vue' import { render } from '@testing-library/vue' import type { GraphMutations } from '@/core/graph/graphMutations' +import type { ComfyApi } from '@/scripts/api' +import type { ComfyApp } from '@/scripts/app' const apiState = vi.hoisted(() => { const docFrames = new EventTarget() @@ -17,7 +19,7 @@ const apiState = vi.hoisted(() => { socketEvents, send, api: { - socket: { readyState: 1, send }, + socket: { readyState: 1 as const, send }, addCustomEventListener: (type: string, listener: EventListener) => docFrames.addEventListener(type, listener), removeCustomEventListener: (type: string, listener: EventListener) => @@ -30,8 +32,12 @@ const apiState = vi.hoisted(() => { } }) -vi.mock('@/scripts/api', () => ({ api: apiState.api })) -vi.mock('@/scripts/app', () => ({ app: { graph: null, canvas: null } })) +vi.mock(import('@/scripts/api'), () => ({ + api: fromPartial(apiState.api) +})) +vi.mock(import('@/scripts/app'), () => ({ + app: fromPartial({}) +})) import { STALE_AFTER_MS, useAgentCrdtFollower } from './useAgentCrdtFollower' import type { AgentCrdtStatus } from './useAgentCrdtFollower' From 13c5d316ea7cdc4d90fb44c11d0c03140c4f7d99 Mon Sep 17 00:00:00 2001 From: bymyself Date: Fri, 18 Sep 2026 10:16:09 -0700 Subject: [PATCH 4/7] refactor(agent): extract follower update handlers --- .../agent/crdt/useAgentCrdtFollower.ts | 137 ++++++++++-------- 1 file changed, 75 insertions(+), 62 deletions(-) diff --git a/src/workbench/extensions/agent/crdt/useAgentCrdtFollower.ts b/src/workbench/extensions/agent/crdt/useAgentCrdtFollower.ts index 8deee5137fd..609efa25d6a 100644 --- a/src/workbench/extensions/agent/crdt/useAgentCrdtFollower.ts +++ b/src/workbench/extensions/agent/crdt/useAgentCrdtFollower.ts @@ -390,6 +390,38 @@ export function useAgentCrdtFollower( sender.abortIfUnbound() } } + const recordUpdateOutcome = (applied: boolean): void => { + outcomes.value = applied + ? { ...outcomes.value, applied: outcomes.value.applied + 1 } + : { ...outcomes.value, skipped: outcomes.value.skipped + 1 } + } + + const recordDocNodeChanges = (): void => { + const ids = currentDocNodeIds() + const added = [...ids].filter((id) => !knownDocNodeIds.has(id)) + const removed = [...knownDocNodeIds].filter((id) => !ids.has(id)) + if (added.length > 0 || removed.length > 0) + recordDevEvent('doc_nodes_changed', { added, removed }) + knownDocNodeIds = ids + } + + const applyIncomingUpdate = (update: DocUpdate, frameType: string): void => { + if (staleProbeTimer !== null) armStaleProbe() + refreshPersistedDocId() + updatesApplied.value = bridge.follower.updatesApplied + lastFrameType.value = frameType + const applied = adapter.applyFrame(update) + recordUpdateOutcome(applied) + if (applied) reconcileLiveGraph(update.workflowId) + recordDevEvent('doc_update', { + workflowId: update.workflowId, + seq: update.seq, + actor: update.actor, + bytes: update.update instanceof Uint8Array ? update.update.length : null + }) + recordDocNodeChanges() + } + const onUpdate: EventListener = (event) => { if (!(event instanceof CustomEvent)) return const update = event.detail as DocUpdate @@ -401,33 +433,10 @@ export function useAgentCrdtFollower( !isTargetActive.value || update.workflowId !== subscribedWorkflowId.value ) { - outcomes.value = { - ...outcomes.value, - skipped: outcomes.value.skipped + 1 - } + recordUpdateOutcome(false) return } - if (staleProbeTimer !== null) armStaleProbe() - refreshPersistedDocId() - updatesApplied.value = bridge.follower.updatesApplied - lastFrameType.value = event.type - const applied = adapter.applyFrame(update) - outcomes.value = applied - ? { ...outcomes.value, applied: outcomes.value.applied + 1 } - : { ...outcomes.value, skipped: outcomes.value.skipped + 1 } - if (applied) reconcileLiveGraph(update.workflowId) - recordDevEvent('doc_update', { - workflowId: update.workflowId, - seq: update.seq, - actor: update.actor, - bytes: update.update instanceof Uint8Array ? update.update.length : null - }) - const ids = currentDocNodeIds() - const added = [...ids].filter((id) => !knownDocNodeIds.has(id)) - const removed = [...knownDocNodeIds].filter((id) => !ids.has(id)) - if (added.length > 0 || removed.length > 0) - recordDevEvent('doc_nodes_changed', { added, removed }) - knownDocNodeIds = ids + applyIncomingUpdate(update, event.type) } const onOpsResult: EventListener = (event) => { if (!(event instanceof CustomEvent)) return @@ -621,6 +630,44 @@ export function useAgentCrdtFollower( else bridge.subscribe(next) sender.abortIfUnbound() } + const unbindCurrentWorkflow = (): void => { + if (boundWorkflowId === null) return + adapter.unbind(boundWorkflowId) + boundWorkflowId = null + } + const bindWorkflow = (workflowId: string): void => { + if (boundWorkflowId === workflowId) return + unbindCurrentWorkflow() + adapter.bind(workflowId, bridge.follower) + boundWorkflowId = workflowId + } + const disconnectTarget = (next: string | null): void => { + if (next !== null) initialBind = false + unbindCurrentWorkflow() + subscribedWorkflowId.value = null + retarget(null) + } + const restorePersistedTarget = (justActivated: boolean): void => { + const persisted = initialBind ? readPersistedDocId() : null + initialBind = false + if (persisted === null) { + clearPersistedDocId() + disconnectTarget(null) + return + } + recordDevEvent('rebind', { workflowId: persisted }) + bindWorkflow(persisted) + subscribedWorkflowId.value = persisted + retarget(persisted) + if (justActivated) reconcileLiveGraph(persisted) + } + const activateTarget = (next: string, justActivated: boolean): void => { + initialBind = false + bindWorkflow(next) + subscribedWorkflowId.value = next + retarget(next) + if (justActivated) reconcileLiveGraph(next) + } watch( [workflowId, isTargetActive], ( @@ -646,48 +693,14 @@ export function useAgentCrdtFollower( connected.value = false knownDocNodeIds = new Set() if (!active) { - if (next !== null) initialBind = false - if (boundWorkflowId !== null) { - adapter.unbind(boundWorkflowId) - boundWorkflowId = null - } - subscribedWorkflowId.value = null - retarget(null) + disconnectTarget(next) return } if (next === null) { - const persisted = initialBind ? readPersistedDocId() : null - initialBind = false - if (persisted !== null) { - recordDevEvent('rebind', { workflowId: persisted }) - if (boundWorkflowId !== persisted) { - if (boundWorkflowId !== null) adapter.unbind(boundWorkflowId) - adapter.bind(persisted, bridge.follower) - boundWorkflowId = persisted - } - subscribedWorkflowId.value = persisted - retarget(persisted) - if (justActivated) reconcileLiveGraph(persisted) - return - } - clearPersistedDocId() - if (boundWorkflowId !== null) { - adapter.unbind(boundWorkflowId) - boundWorkflowId = null - } - subscribedWorkflowId.value = null - retarget(null) + restorePersistedTarget(justActivated) return } - initialBind = false - if (boundWorkflowId !== next) { - if (boundWorkflowId !== null) adapter.unbind(boundWorkflowId) - adapter.bind(next, bridge.follower) - boundWorkflowId = next - } - subscribedWorkflowId.value = next - retarget(next) - if (justActivated) reconcileLiveGraph(next) + activateTarget(next, justActivated) }, { immediate: true } ) From 36cfd0212ca0dc1d32c243054150a6acdf7cd3ec Mon Sep 17 00:00:00 2001 From: bymyself Date: Fri, 18 Sep 2026 12:42:41 -0700 Subject: [PATCH 5/7] test(agent): avoid duplicating sent-frame contract Addresses review feedback: https://github.com/Comfy-Org/ComfyUI_frontend/pull/16849#discussion_r4049809661 --- .../crdt/useAgentCrdtFollower.integration.test.ts | 11 ++--------- 1 file changed, 2 insertions(+), 9 deletions(-) diff --git a/src/workbench/extensions/agent/crdt/useAgentCrdtFollower.integration.test.ts b/src/workbench/extensions/agent/crdt/useAgentCrdtFollower.integration.test.ts index e0fec48e10e..707f40acc72 100644 --- a/src/workbench/extensions/agent/crdt/useAgentCrdtFollower.integration.test.ts +++ b/src/workbench/extensions/agent/crdt/useAgentCrdtFollower.integration.test.ts @@ -46,15 +46,8 @@ const graphMutations = fromPartial({ clearSemanticGraph: vi.fn(() => true) }) -interface SentFrame { - type: string - data: { workflow_id: string } -} - -function framesSent(): SentFrame[] { - return apiState.send.mock.calls.map( - ([frame]) => JSON.parse(frame) as SentFrame - ) +function framesSent(): unknown[] { + return apiState.send.mock.calls.map(([frame]) => JSON.parse(frame) as unknown) } function dispatchServerFrame( From 6ec0c079b26fa46b400cec396627c4142967e1af Mon Sep 17 00:00:00 2001 From: bymyself Date: Fri, 18 Sep 2026 12:42:59 -0700 Subject: [PATCH 6/7] test(agent): preserve readonly follower status Addresses review feedback: https://github.com/Comfy-Org/ComfyUI_frontend/pull/16849#discussion_r4049809672 --- .../agent/crdt/useAgentCrdtFollower.integration.test.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/workbench/extensions/agent/crdt/useAgentCrdtFollower.integration.test.ts b/src/workbench/extensions/agent/crdt/useAgentCrdtFollower.integration.test.ts index 707f40acc72..f98a4b32cfc 100644 --- a/src/workbench/extensions/agent/crdt/useAgentCrdtFollower.integration.test.ts +++ b/src/workbench/extensions/agent/crdt/useAgentCrdtFollower.integration.test.ts @@ -62,14 +62,14 @@ function dispatchServerFrame( function mountFollower(initialWorkflowId: string | null): { unmount: () => void workflowId: Ref - status: () => AgentCrdtStatus + status: () => Readonly } { const workflowId = ref(initialWorkflowId) - let readStatus!: () => AgentCrdtStatus + let readStatus!: () => Readonly const host = defineComponent({ setup() { const { status } = useAgentCrdtFollower(workflowId, graphMutations) - readStatus = () => status.value as AgentCrdtStatus + readStatus = () => status.value return () => null } }) From 62be621061566ec90caea7afc30acc691b63f644 Mon Sep 17 00:00:00 2001 From: Amp Date: Mon, 12 Oct 2026 08:50:35 +0000 Subject: [PATCH 7/7] refactor: keep same-document guard below complexity limit Amp-Thread-ID: https://ampcode.com/threads/T-01a0894f-6bfb-7251-b544-8f6e096ed917 --- .../agent/crdt/useAgentCrdtFollower.ts | 29 ++++++++++++------- 1 file changed, 18 insertions(+), 11 deletions(-) diff --git a/src/workbench/extensions/agent/crdt/useAgentCrdtFollower.ts b/src/workbench/extensions/agent/crdt/useAgentCrdtFollower.ts index de581c234c5..3ebf3bafa69 100644 --- a/src/workbench/extensions/agent/crdt/useAgentCrdtFollower.ts +++ b/src/workbench/extensions/agent/crdt/useAgentCrdtFollower.ts @@ -843,6 +843,21 @@ function startAgentCrdtFollower( if (justActivated) applyCollected(persisted) } + type TargetSnapshot = [string | null | undefined, boolean | undefined] + const isActivationEdge = ( + active: boolean, + previous: TargetSnapshot | undefined + ): boolean => active && previous?.[1] === false + const acknowledgesFollowedDoc = ( + next: string | null, + active: boolean, + justActivated: boolean + ): boolean => + active && + !justActivated && + next !== null && + next === subscribedWorkflowId.value + const activateTarget = (next: string, justActivated: boolean): void => { initialBind = false rebindProjection(next) @@ -853,20 +868,12 @@ function startAgentCrdtFollower( watch( [workflowId, isTargetActive], - ( - [next, active], - previous: [string | null | undefined, boolean | undefined] | undefined - ) => { + ([next, active], previous: TargetSnapshot | undefined) => { // Only the inactive->active edge, and never the `immediate` first run // (`previous` is undefined there): a plain mount or retarget has no // collected changes to apply, the graph watcher covers readiness. - const justActivated = active && previous?.[1] === false - const acknowledgesFollowedDoc = - active && - !justActivated && - next !== null && - next === subscribedWorkflowId.value - if (acknowledgesFollowedDoc) return + const justActivated = isActivationEdge(active, previous) + if (acknowledgesFollowedDoc(next, active, justActivated)) return lifecycle.clearForRetarget() connected.value = false pendingLiveNodeIds.clear()