Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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.
Original file line number Diff line number Diff line change
Expand Up @@ -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'

Expand Down Expand Up @@ -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
Expand All @@ -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
Expand Down
77 changes: 77 additions & 0 deletions src/workbench/extensions/agent/crdt/followerProductGate.test.ts
Original file line number Diff line number Diff line change
@@ -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<WebSocket>({ readyState: WebSocket.OPEN, send })
onTestFinished(() => {
api.socket = previousSocket
})

const store = useAgentPanelStore()
store.enabled = false
const workflowId = ref<string | null>('wf-1')
let follower!: ReturnType<typeof useAgentCrdtFollower>
const { unmount } = render(
defineComponent({
setup() {
follower = useAgentCrdtFollower(
workflowId,
fromPartial<GraphMutations>({})
)
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' }
})
})
Original file line number Diff line number Diff line change
Expand Up @@ -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'

Expand Down Expand Up @@ -205,13 +206,107 @@ function dispatchFrame(type: string, detail: unknown): void {

describe('useAgentCrdtFollower', () => {
beforeEach(() => {
useAgentPanelStore().enabled = true
sessionStorage.clear()
bridgeState.current = null
materializerState.reconcileAgentAdapters.mockReset().mockReturnValue([])
definitionsState.readSubgraphDefinitionIds.mockClear()
definitionsState.readSubgraphDefinitions.mockClear()
})

it('does not construct a follower when the product gate is disabled', () => {
useAgentPanelStore().enabled = false
const { status, unmount } = mountFollower('wf-1')
Comment thread
christian-byrne marked this conversation as resolved.
Resolved

expect(status()).toMatchObject({
enabled: false,
connected: false,
workflowId: null,
updatesApplied: 0
})
expect(bridgeState.current).toBeNull()
expect(adapterState.bind).not.toHaveBeenCalled()
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')

Expand Down
Loading
Loading