From 15f624032f077175a031082185d56ad992393752 Mon Sep 17 00:00:00 2001 From: bymyself Date: Sat, 12 Sep 2026 07:15:21 +0000 Subject: [PATCH 1/5] test(agent): require product gate before constructing follower --- .../agent/crdt/useAgentCrdtFollower.test.ts | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/src/workbench/extensions/agent/crdt/useAgentCrdtFollower.test.ts b/src/workbench/extensions/agent/crdt/useAgentCrdtFollower.test.ts index 1d366139f48..39abaf6e903 100644 --- a/src/workbench/extensions/agent/crdt/useAgentCrdtFollower.test.ts +++ b/src/workbench/extensions/agent/crdt/useAgentCrdtFollower.test.ts @@ -16,6 +16,7 @@ import type { GraphMutations } from '@/core/graph/graphMutations' import type { ExportedSubgraph } from '@/lib/litegraph/src/types/serialisation' import type { NodeId } from '@/types/nodeId' import { toNodeId } from '@/types/nodeId' +import { useAgentPanelStore } from '@/workbench/extensions/agent/stores/agent/agentPanelStore' import type { MaterializableGraph } from './agentNodeMaterializer' @@ -205,6 +206,7 @@ function dispatchFrame(type: string, detail: unknown): void { describe('useAgentCrdtFollower', () => { beforeEach(() => { + useAgentPanelStore().enabled = true sessionStorage.clear() bridgeState.current = null materializerState.reconcileAgentAdapters.mockReset().mockReturnValue([]) @@ -212,6 +214,21 @@ describe('useAgentCrdtFollower', () => { definitionsState.readSubgraphDefinitions.mockClear() }) + it('does not construct a follower when the product gate is disabled', () => { + useAgentPanelStore().enabled = false + const { status, unmount } = mountFollower('wf-1') + + expect(status()).toMatchObject({ + enabled: false, + connected: false, + workflowId: null, + updatesApplied: 0 + }) + expect(bridgeState.current).toBeNull() + expect(adapterState.bind).not.toHaveBeenCalled() + unmount() + }) + it('subscribes immediately to a bound workflow and reports it in status', () => { const { unmount, status } = mountFollower('wf-1') From 46f8dd8e19b4785789dbbc3f62c84eb3a853ad53 Mon Sep 17 00:00:00 2001 From: bymyself Date: Sat, 12 Sep 2026 07:23:41 +0000 Subject: [PATCH 2/5] test(agent): cover flag revocation and diagnostic isolation --- .../agent/crdt/crossWorkflowPending.test.ts | 25 ++++++ .../agent/crdt/useAgentCrdtFollower.test.ts | 78 +++++++++++++++++++ 2 files changed, 103 insertions(+) diff --git a/src/workbench/extensions/agent/crdt/crossWorkflowPending.test.ts b/src/workbench/extensions/agent/crdt/crossWorkflowPending.test.ts index 623f3eb9007..f497fba685a 100644 --- a/src/workbench/extensions/agent/crdt/crossWorkflowPending.test.ts +++ b/src/workbench/extensions/agent/crdt/crossWorkflowPending.test.ts @@ -5,6 +5,7 @@ import type { Ref } from 'vue' import type { GraphMutations } from '@/core/graph/graphMutations' import { render } from '@testing-library/vue' +import { useAgentPanelStore } from '@/workbench/extensions/agent/stores/agent/agentPanelStore' import type { GraphOperation } from './graphOperations' @@ -176,6 +177,7 @@ function dispatchOpsResult(detail: unknown): void { describe('R-73 cross-workflow pending operation characterization', () => { beforeEach(() => { + useAgentPanelStore().enabled = true bridgeState.current = null bridgeState.transport.up = true clientState.transportUp = true @@ -186,6 +188,29 @@ describe('R-73 cross-workflow pending operation characterization', () => { vi.useFakeTimers() }) + it('cancels pending sends and rejects new operations while the product gate is off', () => { + const store = useAgentPanelStore() + const { enqueue, status } = mountFollower('wf-a') + clientState.transportUp = false + enqueue([deleteNode('queued-before-revocation')]) + expect(clientState.attempts).toHaveLength(1) + + store.enabled = false + clientState.transportUp = true + enqueue([deleteNode('attempted-while-disabled')]) + vi.advanceTimersByTime(60_000) + expect(status().enabled).toBe(false) + expect(clientState.attempts).toHaveLength(1) + expect(clientState.sent).toHaveLength(0) + + store.enabled = true + enqueue([deleteNode('new-lifetime')]) + expect(clientState.sent).toHaveLength(1) + expect(clientState.sent[0].ops).toMatchObject([ + { op: 'delete_node', node_id: 'new-lifetime' } + ]) + }) + it('does not retarget a transport retry after workflow A switches to workflow B', async () => { const { workflowId, enqueue } = mountFollower('wf-a') bridgeState.transport.up = false diff --git a/src/workbench/extensions/agent/crdt/useAgentCrdtFollower.test.ts b/src/workbench/extensions/agent/crdt/useAgentCrdtFollower.test.ts index 39abaf6e903..99487fb67ec 100644 --- a/src/workbench/extensions/agent/crdt/useAgentCrdtFollower.test.ts +++ b/src/workbench/extensions/agent/crdt/useAgentCrdtFollower.test.ts @@ -229,6 +229,84 @@ describe('useAgentCrdtFollower', () => { unmount() }) + it('starts on flag delivery and stops synchronously on revocation', async () => { + const store = useAgentPanelStore() + store.enabled = false + const { status, workflowId, unmount } = mountFollower('wf-1') + expect(bridgeState.current).toBeNull() + + store.enabled = true + const first = bridge() + expect(first.subscribe).toHaveBeenCalledExactlyOnceWith('wf-1') + first.dispatchEvent( + new CustomEvent('doc_subscribed', { detail: { ok: true } }) + ) + expect(status().connected).toBe(true) + + store.enabled = false + expect(first.destroy).toHaveBeenCalledOnce() + expect(clientState.destroy).toHaveBeenCalledOnce() + expect(adapterState.destroy).toHaveBeenCalledOnce() + expect(status()).toMatchObject({ + enabled: false, + connected: false, + workflowId: null + }) + + const applies = adapterState.applyFrame.mock.calls.length + first.dispatchEvent( + new CustomEvent('doc_update', { detail: { workflowId: 'wf-1', seq: 42 } }) + ) + apiState.target.dispatchEvent(new Event('reconnected')) + vi.advanceTimersByTime(STALE_AFTER_MS * 2) + workflowId.value = 'wf-2' + await nextTick() + expect(first.subscribe).toHaveBeenCalledTimes(1) + expect(first.resubscribe).not.toHaveBeenCalled() + expect(adapterState.applyFrame).toHaveBeenCalledTimes(applies) + + store.enabled = true + expect(bridge()).not.toBe(first) + expect(bridge().subscribe).toHaveBeenCalledExactlyOnceWith('wf-2') + unmount() + expect(first.destroy).toHaveBeenCalledOnce() + expect(bridge().destroy).toHaveBeenCalledOnce() + }) + + it('cannot enable transport through diagnostic, legacy URL, storage or build controls', async () => { + vi.stubEnv('DEV', false) + vi.stubEnv('VITE_AGENT_CRDT_FOLLOWER', 'true') + window.history.replaceState({}, '', '/?crdtDebug=1&agentCrdtFollower=1') + localStorage.setItem('Comfy.Agent.CrdtFollower', 'true') + vi.resetModules() + const diagnostics = await import('./crdtDebugGate') + expect(diagnostics.isCrdtDebugEnabled()).toBe(true) + expect(diagnostics.resolveDebugPanelEnabled(false)).toBe(false) + + useAgentPanelStore().enabled = false + const { status, unmount } = mountFollower('wf-1') + expect(status().enabled).toBe(false) + expect(bridgeState.current).toBeNull() + expect('__agentCrdtPoc' in window).toBe(false) + unmount() + }) + + it('keeps product transport enabled when diagnostics and legacy controls are off', async () => { + vi.stubEnv('DEV', false) + vi.stubEnv('VITE_AGENT_CRDT_FOLLOWER', 'false') + window.history.replaceState({}, '', '/?crdtDebug=0&agentCrdtFollower=0') + vi.resetModules() + const diagnostics = await import('./crdtDebugGate') + expect(diagnostics.isCrdtDebugEnabled()).toBe(false) + expect(diagnostics.resolveDebugPanelEnabled(true)).toBe(false) + + const { status, unmount } = mountFollower('wf-1') + expect(status().enabled).toBe(true) + expect(bridge().subscribe).toHaveBeenCalledExactlyOnceWith('wf-1') + expect('__agentCrdtPoc' in window).toBe(false) + unmount() + }) + it('subscribes immediately to a bound workflow and reports it in status', () => { const { unmount, status } = mountFollower('wf-1') From cae9acad329166156ef70b8441343638ead2c4ae Mon Sep 17 00:00:00 2001 From: bymyself Date: Sat, 12 Sep 2026 07:26:56 +0000 Subject: [PATCH 3/5] test(agent): verify product gate at real document transport boundary --- .../agent/crdt/followerProductGate.test.ts | 77 +++++++++++++++++++ 1 file changed, 77 insertions(+) create mode 100644 src/workbench/extensions/agent/crdt/followerProductGate.test.ts diff --git a/src/workbench/extensions/agent/crdt/followerProductGate.test.ts b/src/workbench/extensions/agent/crdt/followerProductGate.test.ts new file mode 100644 index 00000000000..fdbe9ff867d --- /dev/null +++ b/src/workbench/extensions/agent/crdt/followerProductGate.test.ts @@ -0,0 +1,77 @@ +import { fromPartial } from '@total-typescript/shoehorn' +import { render } from '@testing-library/vue' +import { expect, it, onTestFinished, vi } from 'vitest' +import { defineComponent, nextTick, ref } from 'vue' + +import type { GraphMutations } from '@/core/graph/graphMutations' +import { api } from '@/scripts/api' +import { useAgentPanelStore } from '@/workbench/extensions/agent/stores/agent/agentPanelStore' + +import { useAgentCrdtFollower } from './useAgentCrdtFollower' + +it('gates real document transport and removes reconnect listeners on revocation', async () => { + const previousSocket = api.socket + const send = vi.fn<(frame: string) => void>() + api.socket = fromPartial({ readyState: WebSocket.OPEN, send }) + onTestFinished(() => { + api.socket = previousSocket + }) + + const store = useAgentPanelStore() + store.enabled = false + const workflowId = ref('wf-1') + let follower!: ReturnType + const { unmount } = render( + defineComponent({ + setup() { + follower = useAgentCrdtFollower( + workflowId, + fromPartial({}) + ) + return () => null + } + }) + ) + onTestFinished(unmount) + + expect(send).not.toHaveBeenCalled() + expect(follower.debugSnapshot()).toMatchObject({ + status: { enabled: false, workflowId: null }, + tabId: null, + nodeIds: [], + linkIds: [] + }) + + store.enabled = true + expect(send).toHaveBeenCalledOnce() + expect(JSON.parse(send.mock.calls[0][0])).toMatchObject({ + type: 'doc_subscribe', + data: { workflow_id: 'wf-1' } + }) + + store.enabled = false + expect(send).toHaveBeenCalledTimes(2) + expect(JSON.parse(send.mock.calls[1][0])).toMatchObject({ + type: 'doc_unsubscribe', + data: { workflow_id: 'wf-1' } + }) + api.dispatchCustomEvent('reconnected') + api.dispatchCustomEvent('status', null) + workflowId.value = 'wf-2' + await nextTick() + vi.advanceTimersByTime(60_000) + expect(send).toHaveBeenCalledTimes(2) + + store.enabled = true + expect(send).toHaveBeenCalledTimes(3) + expect(JSON.parse(send.mock.calls[2][0])).toMatchObject({ + type: 'doc_subscribe', + data: { workflow_id: 'wf-2' } + }) + unmount() + expect(send).toHaveBeenCalledTimes(4) + expect(JSON.parse(send.mock.calls[3][0])).toMatchObject({ + type: 'doc_unsubscribe', + data: { workflow_id: 'wf-2' } + }) +}) From 46f9d34c37ae792b17e26b624323b8a2f383d251 Mon Sep 17 00:00:00 2001 From: Christian Byrne Date: Sat, 12 Sep 2026 07:34:11 +0000 Subject: [PATCH 4/5] fix(agent): scope follower transport to the runtime product gate --- ...er-and-distribution-resolved-boundaries.md | 73 +++++++++++++++++- .../agent/crdt/useAgentCrdtFollower.ts | 77 ++++++++++++++++++- 2 files changed, 146 insertions(+), 4 deletions(-) diff --git a/docs/adr/CRDT-FOLLOWER-0025-in-app-agent-crdt-follower-and-distribution-resolved-boundaries.md b/docs/adr/CRDT-FOLLOWER-0025-in-app-agent-crdt-follower-and-distribution-resolved-boundaries.md index d459f77d60f..093c8a6031c 100644 --- a/docs/adr/CRDT-FOLLOWER-0025-in-app-agent-crdt-follower-and-distribution-resolved-boundaries.md +++ b/docs/adr/CRDT-FOLLOWER-0025-in-app-agent-crdt-follower-and-distribution-resolved-boundaries.md @@ -78,7 +78,7 @@ snapshot-diff, no `LitegraphMutator` in the end state. This supersedes the ADR-009-style `LitegraphMutator`/snapshot-diff/semantic-projector direction recorded in the workspace; that code remains only as the interim POC behind the -env gate. +product gate described below. **Distribution boundaries.** Keep one branch and one follower implementation, with surface differences isolated behind a small distribution-resolved boundary (rejecting @@ -144,7 +144,8 @@ op-layer package DOM/litegraph-free via the import-graph guard. - The end-state follower depends on the semantic domain stores becoming Yjs-backed; only `layoutStore` is Yjs-backed today, so the real dependency is extending that pattern per - store. Until then the interim `LitegraphMutator` POC remains behind the env gate. + store. The product gate below controls follower lifetime, independently of the + renderer migration. - The largest risk is accidental cloud coupling in the existing same-origin `/ws` transport: if ingest-specific paths, M2M assumptions, or Vite proxy behavior leak past the seam, Local/Desktop can pass contract tests while failing as products. Boundary @@ -208,3 +209,71 @@ The follower code on this branch splits into a durable core and a disposable spi the interim SUBGRAPH-PROMOTION-0009-lineage render path and are deleted when the apply-remote-update→store adapter lands. Coverage or review findings on these files route to the store-adapter work, not to polishing the spike. + +## Amendment (2026-09-12): product gate and developer diagnostics + +The runtime product flag, not a build flag, controls follower transport. The +source of truth is `agentPanelStore.enabled`, also consumed by the docked panel +and human-operation mint wiring. `useAgentCrdtFollower` observes that store: +disabled means no client, bridge, adapter, subscription or operation sender; +enablement starts one scoped follower; revocation synchronously disposes it, +including listeners, retries and graph watchers. Re-enabling starts a new +lifetime against the current workflow. Ordinary reconnects and sequence gaps +within an enabled lifetime retain their existing state-vector recovery behavior. + +### Current gate map + +```text +PostHog agent-in-app-experience ─┐ +existing development override ──┴─> agentPanelStore.enabled + ├─> docked panel mount + ├─> follower lifetime / transport + └─> human-operation mint admission + +crdtDebug URL / saved choice ─> diagnostics resolver ─┐ +agentPanelStore.enabled ──────────────────────────────┴─> debug panel + +host document updates ─> follower ─> frontend stores / canvas +human semantic operations ─> host applier (never raw shared-doc writes) +``` + +`src/extensions/core/agentPanel.ts` currently obtains the product flag from +`utils/postHogFlagSource.ts`. It retains the existing development-mode override +and settles the panel gate separately from flag enablement. The general +`useFeatureFlags` pipeline exists, but is not yet the agent flag's source on +main. [The pending feature-pipeline migration](https://github.com/Comfy-Org/ComfyUI_frontend/pull/16208) +changes that producer; the follower continues to consume the same store rather +than adding a second PostHog or server-feature reader. + +| Surface | Product transport control | Diagnostics | +| ------------- | ------------------------------------------------------- | -------------------------------------------------------- | +| Cloud | `agentPanelStore.enabled` | Existing production-hostname denial on `cloud.comfy.org` | +| Desktop | Same store; no distribution bypass | Existing `crdtDebug` resolver | +| Local ComfyUI | Same store; no distribution bypass | Existing `crdtDebug` resolver | +| Dev/ephemeral | Same store, including the existing development override | URL-controlled; existing development default retained | + +`?crdtDebug=1` enables diagnostics on allowed hosts; `?crdtDebug=0` disables +them. The existing persisted preference and log-level controls are unchanged. +Diagnostics cannot enable follower transport, and disabling diagnostics does +not disable product transport. `window.__agentCrdtPoc` is no longer installed; +the debug panel consumes a read-only snapshot callback. + +The legacy `followerGate.ts` resolver remains unused by production callers. +`agentCrdtFollower`, `Comfy.Agent.CrdtFollower`, and +`VITE_AGENT_CRDT_FOLLOWER` are not product controls. The historical +`dev:cloud:crdt` script still sets the latter, but it does not select transport +enablement. This map supersedes the earlier env-gate descriptions in this ADR. + +This frontend gate is not a server authorization boundary. Endpoint selection, +unified authentication, remote model access, and the one-way shared-document +follower invariant above remain unchanged. No Local or Desktop transport is +claimed operational solely because its feature gate is enabled. + +### Glossary + +- **Product gate:** the existing agent feature flag resolved into the panel store. +- **Follower lifetime:** resources between product enablement and disablement or unmount. +- **Diagnostics:** the optional debug panel, snapshot and logging controls. +- **CRDT:** conflict-free replicated data type; here, the host-produced Yjs document. +- **Distribution:** the build's cloud, desktop or localhost endpoint/configuration category, + not a rollout decision. diff --git a/src/workbench/extensions/agent/crdt/useAgentCrdtFollower.ts b/src/workbench/extensions/agent/crdt/useAgentCrdtFollower.ts index e76af459ef3..237344cac09 100644 --- a/src/workbench/extensions/agent/crdt/useAgentCrdtFollower.ts +++ b/src/workbench/extensions/agent/crdt/useAgentCrdtFollower.ts @@ -1,9 +1,18 @@ -import { computed, onBeforeUnmount, readonly, ref, watch } from 'vue' +import { + computed, + effectScope, + onScopeDispose, + readonly, + ref, + shallowRef, + watch +} from 'vue' import type { Ref } from 'vue' import { api } from '@/scripts/api' import type { RemoteMutationContext } from '@/types/graphMutationContext' import { createUuidv4 } from '@/utils/uuid' +import { useAgentPanelStore } from '@/workbench/extensions/agent/stores/agent/agentPanelStore' import type { MaterializableGraph } from './agentNodeMaterializer' import { reconcileAgentAdapters } from './agentNodeMaterializer' @@ -204,6 +213,70 @@ export function useAgentCrdtFollower( * reconcile without waiting for the next remote frame. */ getGraph: () => MaterializableGraph | null = () => null +) { + const productGate = useAgentPanelStore() + const follower = shallowRef>() + const disabledStatus: AgentCrdtStatus = { + enabled: false, + connected: false, + workflowId: null, + updatesApplied: 0, + lastFrameType: null, + outcomes: { + received: 0, + applied: 0, + skipped: 0, + errored: 0, + gap: 0, + reset: 0, + dropped: 0 + } + } + const status = computed(() => follower.value?.status.value ?? disabledStatus) + + watch( + () => productGate.enabled, + (enabled, _previous, onCleanup) => { + if (!enabled) return + const scope = effectScope() + onCleanup(() => { + follower.value = undefined + scope.stop() + }) + follower.value = scope.run(() => + startAgentCrdtFollower( + workflowId, + graphMutations, + userId, + isTargetActive, + getGraph + ) + ) + }, + { immediate: true, flush: 'sync' } + ) + + return { + status: readonly(status), + debugSnapshot: (): CrdtDebugSnapshot => + follower.value?.debugSnapshot() ?? + readCrdtSnapshot(null, { + status: status.value, + tabId: null, + lastSeq: null, + schemaError: null + }), + enqueueHumanOperations: (operations: GraphOperation[]) => + follower.value?.enqueueHumanOperations(operations) + } +} + +function startAgentCrdtFollower( + workflowId: Ref, + graphMutations: MutationsForTarget, + userId: () => string | null, + isTargetActive: Ref, + getGraph: () => MaterializableGraph | null ) { const connected = ref(false) const updatesApplied = ref(0) @@ -685,7 +758,7 @@ export function useAgentCrdtFollower( { immediate: true } ) - onBeforeUnmount(() => { + onScopeDispose(() => { // Teardown must be total. Anything that survives would apply every later // update twice after a remount. try { From 626f47b2ef75d41bba587871d68a1851606058bb Mon Sep 17 00:00:00 2001 From: Christian Byrne Date: Sat, 12 Sep 2026 07:39:10 +0000 Subject: [PATCH 5/5] fix(agent): keep follower outcome counter type internal --- src/workbench/extensions/agent/crdt/useAgentCrdtFollower.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/workbench/extensions/agent/crdt/useAgentCrdtFollower.ts b/src/workbench/extensions/agent/crdt/useAgentCrdtFollower.ts index 237344cac09..651585e13e9 100644 --- a/src/workbench/extensions/agent/crdt/useAgentCrdtFollower.ts +++ b/src/workbench/extensions/agent/crdt/useAgentCrdtFollower.ts @@ -153,7 +153,7 @@ export const STALE_AFTER_MS = 30_000 * No payload bodies or actor identifiers are recorded here — see * `recordDevEvent` call sites for the (dev-only) frame detail surface. */ -export interface AgentCrdtOutcomeCounters { +interface AgentCrdtOutcomeCounters { /** Every `doc_update` event the composable's listener was invoked with. */ received: number /** Passed this composable's own filter and the adapter had a bound session to apply it to. */