From 81d243efc14de9be8debf39106bdd5780cfbdad1 Mon Sep 17 00:00:00 2001 From: Christian Byrne Date: Fri, 11 Sep 2026 19:09:25 -0700 Subject: [PATCH 01/48] [FE-1969] Rebind agent CRDT follower on identity change (#16708 rebase) Restore the persisted follower binding after remounts and identity changes. Keep new-chat detach semantics compatible with explicitly selected workflow context. --- browser_tests/fixtures/ws.ts | 51 +++++- .../tests/agent/agentCrdtReload.spec.ts | 129 +++++++++++++++ .../workflow/persistence/base/storageIO.ts | 4 +- .../persistence/base/storageKeyConstants.ts | 1 + .../extensions/agent/AgentPanelRoot.vue | 74 +++++++-- .../composables/useAgentDockMount.test.ts | 52 +++++- .../agent/composables/useAgentDockMount.ts | 3 + .../extensions/agent/crdt/docFrameClient.ts | 57 +++++-- .../agent/crdt/persistedDocId.test.ts | 155 ++++++++++++++++++ .../extensions/agent/crdt/persistedDocId.ts | 113 +++++++++++++ .../agent/crdt/useAgentCrdtFollower.test.ts | 103 +++++++++++- 11 files changed, 694 insertions(+), 48 deletions(-) create mode 100644 browser_tests/tests/agent/agentCrdtReload.spec.ts create mode 100644 src/platform/workflow/persistence/base/storageKeyConstants.ts create mode 100644 src/workbench/extensions/agent/crdt/persistedDocId.test.ts create mode 100644 src/workbench/extensions/agent/crdt/persistedDocId.ts diff --git a/browser_tests/fixtures/ws.ts b/browser_tests/fixtures/ws.ts index b54525c8bd9..9f128ac5f89 100644 --- a/browser_tests/fixtures/ws.ts +++ b/browser_tests/fixtures/ws.ts @@ -1,35 +1,68 @@ import { networkIsolationFixture as base } from '@e2e/fixtures/networkIsolationFixture' import type { WebSocketRoute } from '@playwright/test' +import type { ClientDocFrame } from '@/workbench/extensions/agent/crdt/docFrameClient' + +type SubscriptionFrame = Extract< + ClientDocFrame, + { type: 'doc_subscribe' | 'doc_unsubscribe' } +> + +export function countDocFrames( + messages: string[], + type: SubscriptionFrame['type'], + workflowId: string +): number { + return messages.filter((message) => { + const frame = JSON.parse(message) as ClientDocFrame + return frame.type === type && frame.data.workflow_id === workflowId + }).length +} + function createWebSocketRouteHandler( connectWebSocketToServer: boolean, - onRouted: (ws: WebSocketRoute) => void + onRouted: (ws: WebSocketRoute, server: WebSocketRoute | null) => void ) { return (ws: WebSocketRoute) => { - if (connectWebSocketToServer) { - const server = ws.connectToServer() - server.onMessage((message) => { - ws.send(message) - }) + if (!connectWebSocketToServer) { + onRouted(ws, null) + return } - onRouted(ws) + const server = ws.connectToServer() + server.onMessage((message) => { + ws.send(message) + }) + onRouted(ws, server) } } export const webSocketFixture = base.extend<{ connectWebSocketToServer: boolean getWebSocket: () => Promise + webSocketMessages: string[] }>({ connectWebSocketToServer: [true, { option: true }], + // oxlint-disable-next-line no-empty-pattern -- Playwright requires an object pattern. + webSocketMessages: async ({}, use) => { + await use([]) + }, getWebSocket: [ - async ({ context, connectWebSocketToServer }, use) => { + async ({ context, connectWebSocketToServer, webSocketMessages }, use) => { let latest: WebSocketRoute | undefined let resolve: ((ws: WebSocketRoute) => void) | undefined await context.routeWebSocket( /\/ws/, - createWebSocketRouteHandler(connectWebSocketToServer, (ws) => { + createWebSocketRouteHandler(connectWebSocketToServer, (ws, server) => { + // Registering a page-side handler switches off Playwright's automatic + // page-to-server forwarding, so recording has to re-send the frame + // itself. Without this every spec merging the fixture drops the + // `feature_flags` handshake and leaves `api.serverFeatureFlags` empty. + ws.onMessage((message) => { + if (typeof message === 'string') webSocketMessages.push(message) + server?.send(message) + }) latest = ws resolve?.(ws) }) diff --git a/browser_tests/tests/agent/agentCrdtReload.spec.ts b/browser_tests/tests/agent/agentCrdtReload.spec.ts new file mode 100644 index 00000000000..eb691319ffb --- /dev/null +++ b/browser_tests/tests/agent/agentCrdtReload.spec.ts @@ -0,0 +1,129 @@ +import type { Page, WebSocketRoute } from '@playwright/test' +import { expect, mergeTests } from '@playwright/test' + +import { agentTest, bootAgentApp } from '@e2e/fixtures/agentPanelFixture' +import { waitForCloudApp } from '@e2e/fixtures/cloudAppFixture' +import { jsonRoute } from '@e2e/fixtures/utils/jsonRoute' +import { countDocFrames, webSocketFixture } from '@e2e/fixtures/ws' +import type { WorkspaceStore } from '@e2e/types/globals' + +import enMessages from '@/locales/en/main.json' with { type: 'json' } +import type { AgentWsEvent } from '@/workbench/extensions/agent/schemas/agentApiSchema' + +const test = mergeTests(agentTest, webSocketFixture) + +const OPEN_AGENT_LABEL = enMessages.agent.askComfyAgent + +function pushEvent(ws: WebSocketRoute, event: AgentWsEvent): void { + ws.send(JSON.stringify(event)) +} + +async function activeWorkflowPath(page: Page) { + return await page.evaluate( + () => + (window.app!.extensionManager as WorkspaceStore).workflow.activeWorkflow + ?.path + ) +} + +test.describe('Agent CRDT reload', { tag: '@cloud' }, () => { + test.use({ connectWebSocketToServer: false }) + + test('FE-1969 restores the subscription after reload and suspends it in the background', async ({ + page, + agentFlagEnabled, + getWebSocket, + webSocketMessages + }) => { + test.setTimeout(90_000) + const workflowId = 'a81718a4-02ae-41e6-ae85-c33b7bb880f6' + + await page.route('**/api/internal/cloud_analytics', (route) => + route.fulfill(jsonRoute({})) + ) + await page.route('**/api/experiment/models', (route) => + route.fulfill(jsonRoute([])) + ) + await page.route(/\/api\/workflows\?limit=100$/, (route) => + route.fulfill( + jsonRoute({ + data: [], + pagination: { has_more: false, next_cursor: null } + }) + ) + ) + await page.route('**/api/agent/threads', (route) => + route.fulfill(jsonRoute({ threads: [] })) + ) + await bootAgentApp(page, agentFlagEnabled) + const ws = await getWebSocket() + await page.getByRole('button', { name: OPEN_AGENT_LABEL }).click() + await expect(page.locator('#agent-panel-root')).toBeVisible() + pushEvent(ws, { + type: 'agent_active_tab', + data: { workflow_id: workflowId, name: 'Reload receipt' } + }) + + await expect + .poll(() => + countDocFrames(webSocketMessages, 'doc_subscribe', workflowId) + ) + .toBe(1) + ws.send( + JSON.stringify({ + type: 'doc_subscribed', + data: { v: 1, workflow_id: workflowId, ok: true, seq: 0 } + }) + ) + + await expect + .poll(() => + page.evaluate(() => sessionStorage.getItem('Comfy.Agent.CrdtDocId')) + ) + .not.toBeNull() + const recordBeforeReload = await page.evaluate(() => + JSON.parse(sessionStorage.getItem('Comfy.Agent.CrdtDocId')!) + ) + expect(recordBeforeReload).toMatchObject({ docId: workflowId }) + + const boundPath = await page.evaluate( + ([key, id]) => { + const bindings = JSON.parse( + localStorage.getItem(key) ?? '{}' + ) as Record + return bindings[id] + }, + ['Comfy.Agent.WorkflowTabBindings', workflowId] + ) + expect(boundPath).toBeTruthy() + await expect.poll(() => activeWorkflowPath(page)).toBe(boundPath) + expect( + await page.evaluate(() => localStorage.getItem('Comfy.Agent.ThreadId')) + ).toBeNull() + + await page.reload() + await waitForCloudApp(page) + await expect(page.locator('#agent-panel-root')).toBeVisible() + await expect + .poll(() => + countDocFrames(webSocketMessages, 'doc_subscribe', workflowId) + ) + .toBe(2) + + const recordAfterReload = await page.evaluate(() => + JSON.parse(sessionStorage.getItem('Comfy.Agent.CrdtDocId')!) + ) + expect(recordAfterReload).toMatchObject({ docId: workflowId }) + expect(recordAfterReload.nonce).not.toBe(recordBeforeReload.nonce) + await expect.poll(() => activeWorkflowPath(page)).toBe(boundPath) + + await page.evaluate(() => + window.app!.extensionManager.command.execute('Comfy.NewBlankWorkflow') + ) + await expect + .poll(() => + countDocFrames(webSocketMessages, 'doc_unsubscribe', workflowId) + ) + .toBe(1) + }) +}) diff --git a/src/platform/workflow/persistence/base/storageIO.ts b/src/platform/workflow/persistence/base/storageIO.ts index dede097a90f..ef44c073ab7 100644 --- a/src/platform/workflow/persistence/base/storageIO.ts +++ b/src/platform/workflow/persistence/base/storageIO.ts @@ -10,6 +10,7 @@ import type { DraftPayloadV2, OpenPathsPointer } from './draftTypes' +import { AGENT_CRDT_DOC_ID_SESSION_KEY } from './storageKeyConstants' import { StorageKeys } from './storageKeys' type StorageAvailability = 'available' | 'unavailable' @@ -466,7 +467,8 @@ const sessionRestorePrefixes = [ const sessionRestoreKeys = [ 'Comfy.PreviousWorkflow', 'Comfy.OpenWorkflowsPaths', - 'Comfy.ActiveWorkflowIndex' + 'Comfy.ActiveWorkflowIndex', + AGENT_CRDT_DOC_ID_SESSION_KEY ] function removeStorageKeys( diff --git a/src/platform/workflow/persistence/base/storageKeyConstants.ts b/src/platform/workflow/persistence/base/storageKeyConstants.ts new file mode 100644 index 00000000000..0f8ca17feda --- /dev/null +++ b/src/platform/workflow/persistence/base/storageKeyConstants.ts @@ -0,0 +1 @@ +export const AGENT_CRDT_DOC_ID_SESSION_KEY = 'Comfy.Agent.CrdtDocId' diff --git a/src/workbench/extensions/agent/AgentPanelRoot.vue b/src/workbench/extensions/agent/AgentPanelRoot.vue index 0ed7d403de1..2f04566612b 100644 --- a/src/workbench/extensions/agent/AgentPanelRoot.vue +++ b/src/workbench/extensions/agent/AgentPanelRoot.vue @@ -99,6 +99,10 @@ import { resolveDebugPanelEnabled } from './crdt/crdtDebugGate' import { attachMintPortWiring } from './crdt/mintPortWiring' +import { + clearPersistedDocId, + reconcilePersistedDocId +} from './crdt/persistedDocId' import { useAgentCrdtFollower } from './crdt/useAgentCrdtFollower' const CrdtDevPanel = defineAsyncComponent( @@ -344,7 +348,13 @@ watch( { immediate: true } ) -const workflowDetached = computed(() => selectedTarget.value === null) +const newChatDetached = ref(false) +const workflowDetached = computed( + () => newChatDetached.value || selectedTarget.value === null +) +watch(selectedTarget, (target) => { + if (target !== null) newChatDetached.value = false +}) // Resolves the tab a turn is attributed to. `null` (the send had no origin // tab) resolves to nothing rather than falling back to the selected target, so @@ -476,15 +486,50 @@ const isSending = computed( () => sessionIsSending.value || composerStore.submission?.phase === 'pending' ) -const isBoundWorkflowActive = computed(() => { - const bound = boundWorkflowId.value +// FE-1969: `boundWorkflowId` is the in-memory session binding and is reset +// whenever the session restarts within the same page load — a panel remount, +// or a reload inside the record's TTL. The follower can still rebind to the doc +// it persisted for this page load, but only if this computed drives it with +// `active=true`. "New chat" is deliberately not one of those cases: it ends the +// session, so `onNewChat` drops the record and there is nothing left to +// restore. The +// fallback is scoped to that one doc: the active tab's persisted tab binding +// counts only when it names the doc the follower would restore, so a tab that +// merely carries a stale binding, or a second bound tab, never reads as +// active and never keeps the follower projecting into a background tab. +// `reconcilePersistedDocId()` is not a pure read: it adopts and re-stamps the +// record on a reload, drops it on a nonce mismatch, and consults untracked +// `sessionStorage` and `Date.now()`. Calling it from inside the computed getter +// therefore let an unrelated re-render consume or rewrite the record the +// follower was about to read, and the cached value never invalidated when the +// record lapsed. Resolve it at the explicit lifecycle points that used to drive +// re-evaluation and let the getter read only reactive state. +const restorableDocId = ref(null) +watch( + [workflowDetached, () => workflowStore.activeWorkflow, boundWorkflowId], + () => { + restorableDocId.value = reconcilePersistedDocId() + }, + { immediate: true } +) + +function restorableWorkflowIdFor(tabPath: string): string | null { + const persisted = bindingStore.workflowIdFor(tabPath) + if (persisted === undefined) return null + return persisted === restorableDocId.value ? persisted : null +} +const activeBoundWorkflowId = computed(() => { + if (workflowDetached.value) return null const active = workflowStore.activeWorkflow - return ( - bound !== null && - active !== null && - boundOrOpenWorkflowFor(bound)?.path === active.path - ) + if (active === null) return null + const bound = boundWorkflowId.value ?? restorableWorkflowIdFor(active.path) + return bound !== null && boundOrOpenWorkflowFor(bound)?.path === active.path + ? bound + : null }) +const isBoundWorkflowActive = computed( + () => activeBoundWorkflowId.value !== null +) // The CRDT follower is the inbound content channel: subscribes to the // session's bound workflow while its tab is active. Suspending the background @@ -493,9 +538,10 @@ const isBoundWorkflowActive = computed(() => { const { status: crdtStatus, debugSnapshot: crdtDebugSnapshot, + acknowledgedWorkflowId, enqueueHumanOperations } = useAgentCrdtFollower( - boundWorkflowId, + activeBoundWorkflowId, graphMutations, () => resolvedUserInfo.value?.id ?? null, isBoundWorkflowActive, @@ -506,7 +552,9 @@ const { ) const mintPortWiring = attachMintPortWiring({ isEnabled: () => agentPanelStore.enabled, - isDocBound: () => isBoundWorkflowActive.value, + isDocBound: () => + acknowledgedWorkflowId.value !== null && + acknowledgedWorkflowId.value === activeBoundWorkflowId.value, enqueue: enqueueHumanOperations, layoutChanges: (listener) => layoutStore.onChange(listener), localActorPrefix: ACTOR_CONFIG.USER_PREFIX, @@ -811,7 +859,13 @@ function onNewChat(): void { exitNodeSelectionMode() composerStore.setWorkflowReferences([]) composerStore.resetPromptHistory() + // Ending the session also ends the document's claim on the graph. + clearPersistedDocId() + newChatDetached.value = true newChat() + // A selected target remains explicit context across chats; only a targetless + // new chat stays detached after the session binding is cleared. + if (selectedTarget.value !== null) newChatDetached.value = false } const panelRef = ref>() diff --git a/src/workbench/extensions/agent/composables/useAgentDockMount.test.ts b/src/workbench/extensions/agent/composables/useAgentDockMount.test.ts index 25dde8c79d5..7ce408c0b90 100644 --- a/src/workbench/extensions/agent/composables/useAgentDockMount.test.ts +++ b/src/workbench/extensions/agent/composables/useAgentDockMount.test.ts @@ -1,18 +1,21 @@ import { beforeEach, describe, expect, it, vi } from 'vitest' +import { defineComponent } from 'vue' import { useAgentPanelStore } from '@/workbench/extensions/agent/stores/agent/agentPanelStore' import { useAgentDockMount } from './useAgentDockMount' -vi.mock(import('@/platform/telemetry'), () => ({ - useTelemetry: () => undefined -})) +vi.mock(import('@/platform/telemetry'), () => ({ useTelemetry: () => null })) const { loadDockedAgentPanel } = vi.hoisted(() => ({ - loadDockedAgentPanel: vi.fn(() => ({ name: 'DockedAgentPanel' })) + loadDockedAgentPanel: vi.fn() })) -vi.mock( +const CRDT_DOC_ID_KEY = 'Comfy.Agent.CrdtDocId' +vi.mock( import('@/workbench/extensions/agent/components/agent/DockedAgentPanel.vue'), - () => ({ __esModule: true, default: loadDockedAgentPanel() }) + () => { + loadDockedAgentPanel() + return { default: defineComponent({ name: 'DockedAgentPanel' }) } + } ) function getAsyncLoader(component: unknown): () => Promise { @@ -29,16 +32,28 @@ function getAsyncLoader(component: unknown): () => Promise { describe('useAgentDockMount', () => { beforeEach(() => { + const store = useAgentPanelStore() + store.enabled = false + store.isOpen = false + store.gateSettled = false localStorage.clear() + sessionStorage.clear() }) it('returns an inert mount on non-cloud distributions', () => { vi.stubGlobal('__DISTRIBUTION__', 'localhost') + const inheritedRecord = JSON.stringify({ + docId: 'wf-from-another-tab', + nonce: 'foreign-page', + expiresAt: Date.now() + 60_000 + }) + sessionStorage.setItem(CRDT_DOC_ID_KEY, inheritedRecord) const { docked, DockedAgentPanel } = useAgentDockMount() expect(docked.value).toBe(false) expect(DockedAgentPanel).toBeNull() + expect(sessionStorage.getItem(CRDT_DOC_ID_KEY)).toBe(inheritedRecord) }) it('docks only once the gate enables and the panel opens on cloud', async () => { @@ -56,12 +71,31 @@ describe('useAgentDockMount', () => { expect(docked.value).toBe(false) store.isOpen = true expect(docked.value).toBe(true) - const resolvedPanel = await getAsyncLoader(DockedAgentPanel)() - const { default: expectedPanel } = + const resolvedModule = await getAsyncLoader(DockedAgentPanel)() + const expectedModule = await import('@/workbench/extensions/agent/components/agent/DockedAgentPanel.vue') - expect(resolvedPanel).toBe(expectedPanel) + expect(resolvedModule).toBe(expectedModule) + expect(expectedModule.default.name).toBe('DockedAgentPanel') expect(loadDockedAgentPanel).toHaveBeenCalledOnce() store.close('close_button') expect(docked.value).toBe(false) }) + + it('consumes an inherited CRDT binding before the cloud panel opens', () => { + vi.stubGlobal('__DISTRIBUTION__', 'cloud') + sessionStorage.setItem( + CRDT_DOC_ID_KEY, + JSON.stringify({ + docId: 'wf-from-another-tab', + nonce: 'foreign-page', + expiresAt: Date.now() + 60_000 + }) + ) + + const { docked } = useAgentDockMount() + + expect(docked.value).toBe(false) + expect(loadDockedAgentPanel).not.toHaveBeenCalled() + expect(sessionStorage.getItem(CRDT_DOC_ID_KEY)).toBeNull() + }) }) diff --git a/src/workbench/extensions/agent/composables/useAgentDockMount.ts b/src/workbench/extensions/agent/composables/useAgentDockMount.ts index 9aa70319639..d5b86230121 100644 --- a/src/workbench/extensions/agent/composables/useAgentDockMount.ts +++ b/src/workbench/extensions/agent/composables/useAgentDockMount.ts @@ -3,6 +3,8 @@ import { computed, defineAsyncComponent } from 'vue' import { useAgentPanelStore } from '@/workbench/extensions/agent/stores/agent/agentPanelStore' +import { reconcilePersistedDocId } from '../crdt/persistedDocId' + interface AgentDockMount { docked: ComputedRef DockedAgentPanel: Component | null @@ -23,6 +25,7 @@ export function useAgentDockMount(): AgentDockMount { ) { return { docked: computed(() => false), DockedAgentPanel: null } } + reconcilePersistedDocId() const agentPanelStore = useAgentPanelStore() return { docked: computed(() => agentPanelStore.isVisible), diff --git a/src/workbench/extensions/agent/crdt/docFrameClient.ts b/src/workbench/extensions/agent/crdt/docFrameClient.ts index 53d8d995e56..421c3f7d91a 100644 --- a/src/workbench/extensions/agent/crdt/docFrameClient.ts +++ b/src/workbench/extensions/agent/crdt/docFrameClient.ts @@ -85,6 +85,29 @@ export type ServerDocFrame = | { type: 'doc_reset'; data: DocReset } | { type: 'awareness'; data: DocAwareness } +export type ClientDocFrame = + | { + type: 'doc_subscribe' + data: { + v: typeof DOC_PROTOCOL_VERSION + workflow_id: string + state_vector_b64: string + } + } + | { + type: 'doc_unsubscribe' + data: { v: typeof DOC_PROTOCOL_VERSION; workflow_id: string } + } + | { + type: 'doc_ops' + data: { + v: typeof DOC_PROTOCOL_VERSION + workflow_id: string + tab: string + ops: DocOp[] | Op[] + } + } + /** A frame as it travels the wire, before {@link parseServerDocFrame} reads it. */ export interface DocFrameTransport { /** @@ -418,28 +441,34 @@ export class DocFrameClient extends EventTarget { /** @returns whether the subscribe frame actually left the transport. */ subscribe(workflowId: string, stateVector: Uint8Array): boolean { - return this.send('doc_subscribe', { - v: DOC_PROTOCOL_VERSION, - workflow_id: workflowId, - state_vector_b64: encodeBase64(stateVector) + return this.send({ + type: 'doc_subscribe', + data: { + v: DOC_PROTOCOL_VERSION, + workflow_id: workflowId, + state_vector_b64: encodeBase64(stateVector) + } }) } /** @returns whether the unsubscribe frame actually left the transport. */ unsubscribe(workflowId: string): boolean { - return this.send('doc_unsubscribe', { - v: DOC_PROTOCOL_VERSION, - workflow_id: workflowId + return this.send({ + type: 'doc_unsubscribe', + data: { v: DOC_PROTOCOL_VERSION, workflow_id: workflowId } }) } /** @returns whether the ops frame actually left the transport. */ sendOps(workflowId: string, tab: string, ops: DocOp[] | Op[]): boolean { - return this.send('doc_ops', { - v: DOC_PROTOCOL_VERSION, - workflow_id: workflowId, - tab, - ops + return this.send({ + type: 'doc_ops', + data: { + v: DOC_PROTOCOL_VERSION, + workflow_id: workflowId, + tab, + ops + } }) } @@ -449,7 +478,7 @@ export class DocFrameClient extends EventTarget { this.listeners.clear() } - private send(type: string, data: Record): boolean { - return this.transport.send(JSON.stringify({ type, data })) + private send(frame: ClientDocFrame): boolean { + return this.transport.send(JSON.stringify(frame)) } } diff --git a/src/workbench/extensions/agent/crdt/persistedDocId.test.ts b/src/workbench/extensions/agent/crdt/persistedDocId.test.ts new file mode 100644 index 00000000000..f9c08c27d77 --- /dev/null +++ b/src/workbench/extensions/agent/crdt/persistedDocId.test.ts @@ -0,0 +1,155 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest' + +import { + DOC_ID_SESSION_KEY, + DOC_ID_TTL_MS, + clearPersistedDocId, + persistDocId, + reconcilePersistedDocId +} from './persistedDocId' + +function rawRecord(): { + docId?: unknown + nonce?: unknown + expiresAt?: unknown +} | null { + const raw = sessionStorage.getItem(DOC_ID_SESSION_KEY) + return raw === null ? null : JSON.parse(raw) +} + +/** Impersonate a different page load, the way tab duplication does. */ +function writeForeignRecord(docId: string, expiresAt: number): void { + sessionStorage.setItem( + DOC_ID_SESSION_KEY, + JSON.stringify({ docId, nonce: 'a-different-page-load', expiresAt }) + ) +} + +function asReloadNavigation(): void { + vi.spyOn(performance, 'getEntriesByType').mockReturnValue([ + { type: 'reload' } as PerformanceNavigationTiming + ]) +} + +describe('persistedDocId', () => { + beforeEach(() => { + sessionStorage.clear() + }) + + it('round-trips a doc id persisted by this page load', () => { + persistDocId('wf-1') + + expect(reconcilePersistedDocId()).toBe('wf-1') + }) + + describe('rejection consumes the record', () => { + it('drops an expired record instead of leaving it to be re-rejected', () => { + writeForeignRecord('wf-1', Date.now() - 1) + + expect(reconcilePersistedDocId()).toBeNull() + expect(rawRecord()).toBeNull() + }) + + it('drops a malformed record', () => { + sessionStorage.setItem(DOC_ID_SESSION_KEY, JSON.stringify({ docId: 7 })) + + expect(reconcilePersistedDocId()).toBeNull() + expect(rawRecord()).toBeNull() + }) + + it('drops a pre-FEC-5 bare doc id, which is not valid JSON', () => { + sessionStorage.setItem(DOC_ID_SESSION_KEY, 'wf-legacy') + + expect(reconcilePersistedDocId()).toBeNull() + expect(rawRecord()).toBeNull() + }) + + it('drops an inherited record when the load is not a reload', () => { + writeForeignRecord('wf-1', Date.now() + DOC_ID_TTL_MS) + + expect(reconcilePersistedDocId()).toBeNull() + expect(rawRecord()).toBeNull() + }) + }) + + describe('reload adoption', () => { + it('adopts an inherited record and takes ownership of it', () => { + const expiresAt = Date.now() + DOC_ID_TTL_MS + writeForeignRecord('wf-1', expiresAt) + asReloadNavigation() + + expect(reconcilePersistedDocId()).toBe('wf-1') + expect(rawRecord()?.nonce).not.toBe('a-different-page-load') + }) + + it('renews the owner but never the lifetime', () => { + // One second of life left; a full re-stamp would restore the whole TTL and + // let a tab reloaded inside the window hold the id open indefinitely. + const expiresAt = Date.now() + 1_000 + writeForeignRecord('wf-1', expiresAt) + asReloadNavigation() + + expect(reconcilePersistedDocId()).toBe('wf-1') + expect(rawRecord()?.expiresAt).toBe(expiresAt) + }) + + it('lets an adopted record still lapse on its original schedule', () => { + vi.useFakeTimers() + writeForeignRecord('wf-1', Date.now() + 1_000) + asReloadNavigation() + expect(reconcilePersistedDocId()).toBe('wf-1') + + vi.advanceTimersByTime(2_000) + + expect(reconcilePersistedDocId()).toBeNull() + expect(rawRecord()).toBeNull() + }) + + it('refuses an expired inherited record even on a reload', () => { + writeForeignRecord('wf-1', Date.now() - 1) + asReloadNavigation() + + expect(reconcilePersistedDocId()).toBeNull() + expect(rawRecord()).toBeNull() + }) + }) + + it('clearPersistedDocId removes the record', () => { + persistDocId('wf-1') + + clearPersistedDocId() + + expect(rawRecord()).toBeNull() + expect(reconcilePersistedDocId()).toBeNull() + }) + + describe('identity transitions drop the binding', () => { + it('workspace switching clears it', async () => { + const { clearWorkflowRestoreState } = + await import('@/platform/workflow/persistence/base/storageIO') + persistDocId('wf-1') + + clearWorkflowRestoreState() + + expect(rawRecord()).toBeNull() + }) + + it('signing out clears it', async () => { + const { clearAllWorkflowStorage } = + await import('@/platform/workflow/persistence/base/storageIO') + persistDocId('wf-1') + + clearAllWorkflowStorage() + + expect(rawRecord()).toBeNull() + }) + + it('a reload after the transition has nothing to adopt', () => { + persistDocId('wf-1') + clearPersistedDocId() + asReloadNavigation() + + expect(reconcilePersistedDocId()).toBeNull() + }) + }) +}) diff --git a/src/workbench/extensions/agent/crdt/persistedDocId.ts b/src/workbench/extensions/agent/crdt/persistedDocId.ts new file mode 100644 index 00000000000..00ea67b2fb3 --- /dev/null +++ b/src/workbench/extensions/agent/crdt/persistedDocId.ts @@ -0,0 +1,113 @@ +import { createUuidv4 } from '@/utils/uuid' +import { AGENT_CRDT_DOC_ID_SESSION_KEY } from '@/platform/workflow/persistence/base/storageKeyConstants' + +// FE-1902: the doc id is otherwise held only in memory (set on turn ack), so a +// panel remount or reload loses the binding until the next turn ack. Persist it +// per-tab in sessionStorage so the follower can rebind immediately. +// +// FEC-5: a bare doc id has no owner and no lifetime, so the record carries a +// per-page-load nonce and a short expiry. Browser-tab duplication clones +// sessionStorage, but the cloud dock mount reconciles this record before its +// lazy panel boundary: a duplicated tab gets a fresh nonce and consumes the +// inherited record on its first load, even when the panel stays closed. An +// explicit reload may adopt the previous page load's unexpired record. +export const DOC_ID_SESSION_KEY = AGENT_CRDT_DOC_ID_SESSION_KEY +export const DOC_ID_TTL_MS = 5 * 60 * 1000 +export const DOC_ID_REFRESH_INTERVAL_MS = DOC_ID_TTL_MS / 2 + +let pageSessionNonce: string | undefined + +interface PersistedDocIdRecord { + docId: string + nonce: string + expiresAt: number +} + +function currentPageSessionNonce(): string { + pageSessionNonce ??= createUuidv4() + return pageSessionNonce +} + +function safeSessionStorage(): Storage | null { + try { + return window.sessionStorage + } catch { + return null + } +} + +function writeRecord(record: PersistedDocIdRecord): void { + try { + safeSessionStorage()?.setItem(DOC_ID_SESSION_KEY, JSON.stringify(record)) + } catch { + // Quota / privacy mode: persistence is best-effort. + } +} + +export function persistDocId(docId: string): void { + writeRecord({ + docId, + nonce: currentPageSessionNonce(), + expiresAt: Date.now() + DOC_ID_TTL_MS + }) +} + +function isReloadNavigation(): boolean { + return performance + .getEntriesByType('navigation') + .some((entry) => (entry as PerformanceNavigationTiming).type === 'reload') +} + +export function reconcilePersistedDocId(): string | null { + try { + const raw = safeSessionStorage()?.getItem(DOC_ID_SESSION_KEY) + if (!raw) return null + const record = JSON.parse(raw) as Partial + // Every rejection below also drops the key. Leaving a rejected record in + // place would break the invariant the dock-mount reconcile relies on: a + // duplicated tab that inherits a lapsed or pre-FEC-5 record would keep + // re-reading and re-rejecting it on every reconcile instead of consuming it + // once. + if ( + typeof record.docId !== 'string' || + typeof record.nonce !== 'string' || + typeof record.expiresAt !== 'number' + ) { + clearPersistedDocId() + return null + } + if (Date.now() >= record.expiresAt) { + clearPersistedDocId() + return null + } + if (record.nonce !== currentPageSessionNonce()) { + if (!isReloadNavigation()) { + clearPersistedDocId() + return null + } + // Adoption renews the owner, never the lifetime. Re-stamping a full TTL + // here would let a tab reloaded inside the window keep an arbitrarily old + // doc id rebindable forever, removing the only bound the TTL places on + // the same-page-load workflow-switch case. + writeRecord({ + docId: record.docId, + nonce: currentPageSessionNonce(), + expiresAt: record.expiresAt + }) + } + return record.docId + } catch { + // A pre-FEC-5 bare doc id is not valid JSON, so it lands here rather than + // in the shape check above; drop it so it is consumed exactly once. + clearPersistedDocId() + return null + } +} + +export function clearPersistedDocId(): void { + try { + safeSessionStorage()?.removeItem(DOC_ID_SESSION_KEY) + } catch { + // Best-effort. + } +} diff --git a/src/workbench/extensions/agent/crdt/useAgentCrdtFollower.test.ts b/src/workbench/extensions/agent/crdt/useAgentCrdtFollower.test.ts index 8f66502fe97..1980e2ae265 100644 --- a/src/workbench/extensions/agent/crdt/useAgentCrdtFollower.test.ts +++ b/src/workbench/extensions/agent/crdt/useAgentCrdtFollower.test.ts @@ -22,13 +22,17 @@ import type { MaterializableGraph } from './agentNodeMaterializer' const bridgeState = vi.hoisted(() => { class FakeBridge extends EventTarget { - subscribe = vi.fn() - unsubscribe = vi.fn() + subscribe = vi.fn((workflowId: string) => { + this.subscribedWorkflowId = workflowId + }) + unsubscribe = vi.fn(() => { + this.subscribedWorkflowId = null + }) resubscribe = vi.fn() reconcile = vi.fn() destroy = vi.fn() sendHumanOps = vi.fn() - subscribedWorkflowId: string | null = 'wf-1' + subscribedWorkflowId: string | null = null lastSequence = 41 follower = { updatesApplied: 0, @@ -143,6 +147,7 @@ vi.mock(import('@/scripts/app'), () => ({ import { STALE_AFTER_MS, useAgentCrdtFollower } from './useAgentCrdtFollower' import type { AgentCrdtStatus } from './useAgentCrdtFollower' +import { reconcilePersistedDocId } from './persistedDocId' const graphMutations = {} as GraphMutations const DOC_ID_KEY = 'Comfy.Agent.CrdtDocId' @@ -182,13 +187,15 @@ function mountFollower( workflowId: Ref isTargetActive: Ref status: () => AgentCrdtStatus + acknowledgedWorkflowId: () => string | null } { const workflowId = ref(initial) const isTargetActive = ref(initiallyActive) let exposedStatus!: () => AgentCrdtStatus + let exposedAcknowledgedWorkflowId!: () => string | null const host = defineComponent({ setup() { - const { status } = useAgentCrdtFollower( + const { status, acknowledgedWorkflowId } = useAgentCrdtFollower( workflowId, graphMutations, () => null, @@ -196,11 +203,18 @@ function mountFollower( getGraph ) exposedStatus = () => status.value as AgentCrdtStatus + exposedAcknowledgedWorkflowId = () => acknowledgedWorkflowId.value return () => null } }) const { unmount } = render(host) - return { unmount, workflowId, isTargetActive, status: exposedStatus } + return { + unmount, + workflowId, + isTargetActive, + status: exposedStatus, + acknowledgedWorkflowId: exposedAcknowledgedWorkflowId + } } function bridge(): InstanceType<(typeof bridgeState)['FakeBridge']> { @@ -237,6 +251,28 @@ describe('useAgentCrdtFollower', () => { unmount() }) + it('surfaces a binding only after the server acknowledges it', async () => { + const { unmount, workflowId, acknowledgedWorkflowId } = + mountFollower('wf-1') + + expect(acknowledgedWorkflowId()).toBeNull() + + dispatchFrame('doc_subscribed', { ok: true, workflowId: 'wf-1' }) + expect(acknowledgedWorkflowId()).toBe('wf-1') + + workflowId.value = 'wf-2' + await nextTick() + expect(acknowledgedWorkflowId()).toBeNull() + + dispatchFrame('doc_subscribed', { ok: true, workflowId: 'wf-2' }) + expect(acknowledgedWorkflowId()).toBe('wf-2') + + bridge().subscribedWorkflowId = null + dispatchFrame('doc_subscribed', { ok: false, workflowId: 'wf-2' }) + expect(acknowledgedWorkflowId()).toBeNull() + unmount() + }) + it('FE-1901: retries a refused subscribe with bounded exponential backoff', () => { vi.useFakeTimers() const { unmount } = mountFollower('wf-1') @@ -304,6 +340,30 @@ describe('useAgentCrdtFollower', () => { unmount() }) + it('FE-1969: the persisted doc reconciler mirrors the next rebind', () => { + const { unmount } = mountFollower('wf-1') + expect(reconcilePersistedDocId()).toBeNull() + + dispatchFrame('doc_subscribed', { ok: true }) + expect(reconcilePersistedDocId()).toBe('wf-1') + + writeRawRecord({ docId: 'wf-1', nonce: 'foreign-nonce' }) + expect(reconcilePersistedDocId()).toBeNull() + expect(persistedRecord()).toBeNull() + + // The mismatch branch above consumed the record, so the reload branch needs + // its own; asserting against the emptied store would pass no matter what a + // reload does. A reload is the one navigation permitted to adopt the + // previous page load's record, and it takes ownership when it does. + writeRawRecord({ docId: 'wf-1', nonce: 'foreign-nonce' }) + vi.spyOn(performance, 'getEntriesByType').mockReturnValue([ + { type: 'reload' } as PerformanceNavigationTiming + ]) + expect(reconcilePersistedDocId()).toBe('wf-1') + expect(persistedRecord()?.nonce).not.toBe('foreign-nonce') + unmount() + }) + it('FE-1902: a remount with no in-memory binding rebinds from sessionStorage', () => { const setup = mountFollower('wf-1') dispatchFrame('doc_subscribed', { ok: true }) @@ -317,6 +377,20 @@ describe('useAgentCrdtFollower', () => { unmount() }) + it('FE-1902: a page reload adopts and rebinds the previous navigation record', () => { + vi.spyOn(performance, 'getEntriesByType').mockReturnValue([ + { type: 'reload' } as PerformanceNavigationTiming + ]) + writeRawRecord({ docId: 'wf-1', nonce: 'previous-page-load' }) + + const { unmount, status } = mountFollower(null) + + expect(bridge().subscribe).toHaveBeenCalledWith('wf-1') + expect(status().workflowId).toBe('wf-1') + expect(persistedRecord()?.nonce).not.toBe('previous-page-load') + unmount() + }) + it('FE-1902: a real detach clears the persisted binding and unsubscribes', async () => { const { unmount, workflowId } = mountFollower('wf-1') dispatchFrame('doc_subscribed', { ok: true }) @@ -477,6 +551,25 @@ describe('useAgentCrdtFollower', () => { unmount() }) + // `connected` is derived from `acknowledgedWorkflowId`, not tracked as its + // own ref, so the doc_reset lineage break has to drop the acknowledgement to + // report a disconnect. A rebase that reinstates a separate `connected` write + // here, or drops the acknowledgement reset, silently breaks that. + it('reports a disconnect when a doc_reset breaks the lineage', () => { + const { unmount, status } = mountFollower('wf-1') + dispatchFrame('doc_subscribed', { ok: true }) + expect(status().connected).toBe(true) + + dispatchFrame('doc_reset', { + workflowId: 'wf-1', + actor: 'agent:turn', + seq: 43 + }) + + expect(status().connected).toBe(false) + unmount() + }) + it('clears only for an explicit reset and rebinds after replacement', () => { const { unmount, status } = mountFollower('wf-1') expect(adapterState.bind).toHaveBeenCalledTimes(1) From 6376cbbe84578b0443c4a33681dcb3f79073aea0 Mon Sep 17 00:00:00 2001 From: Christian Byrne Date: Fri, 11 Sep 2026 19:36:26 -0700 Subject: [PATCH 02/48] fix(agent): select idle agent-opened workflow targets --- src/workbench/extensions/agent/AgentPanelRoot.vue | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/workbench/extensions/agent/AgentPanelRoot.vue b/src/workbench/extensions/agent/AgentPanelRoot.vue index 2f04566612b..1cbc14962f6 100644 --- a/src/workbench/extensions/agent/AgentPanelRoot.vue +++ b/src/workbench/extensions/agent/AgentPanelRoot.vue @@ -688,6 +688,7 @@ async function onAgentActiveTab( // boundOrOpenWorkflowFor can resolve by cloud name, which leaves no binding behind // for everything downstream that only reads tabPathFor. bindingStore.bind(data.workflow_id, bound.path) + if (status.value === 'idle') agentPanelStore.setWorkflowTarget(bound) if (status.value !== 'idle') tabActivity.setEditing(bound.path) bindWorkflow(data.workflow_id) useTelemetry()?.trackAgentWorkflowApplied({ @@ -722,6 +723,7 @@ async function onAgentActiveTab( } if (status.value !== 'idle') tabActivity.setEditing(tab.path) bindingStore.bind(data.workflow_id, tab.path) + if (status.value === 'idle') agentPanelStore.setWorkflowTarget(tab) bindWorkflow(data.workflow_id) useTelemetry()?.trackAgentWorkflowApplied({ workflow_id: data.workflow_id, From f43dd7024fa09a94027079aecc1cb09fed62f078 Mon Sep 17 00:00:00 2001 From: Christian Byrne Date: Fri, 11 Sep 2026 20:02:51 -0700 Subject: [PATCH 03/48] test(agent): wake reload follower on mock socket --- browser_tests/fixtures/ws.ts | 6 +++--- browser_tests/tests/agent/agentCrdtReload.spec.ts | 7 +++++++ 2 files changed, 10 insertions(+), 3 deletions(-) diff --git a/browser_tests/fixtures/ws.ts b/browser_tests/fixtures/ws.ts index 9f128ac5f89..5c4d63c3dd3 100644 --- a/browser_tests/fixtures/ws.ts +++ b/browser_tests/fixtures/ws.ts @@ -39,7 +39,7 @@ function createWebSocketRouteHandler( export const webSocketFixture = base.extend<{ connectWebSocketToServer: boolean - getWebSocket: () => Promise + getWebSocket: (after?: WebSocketRoute) => Promise webSocketMessages: string[] }>({ connectWebSocketToServer: [true, { option: true }], @@ -68,8 +68,8 @@ export const webSocketFixture = base.extend<{ }) ) - await use(() => { - if (latest) return Promise.resolve(latest) + await use((after) => { + if (latest && latest !== after) return Promise.resolve(latest) return new Promise((r) => { resolve = r }) diff --git a/browser_tests/tests/agent/agentCrdtReload.spec.ts b/browser_tests/tests/agent/agentCrdtReload.spec.ts index eb691319ffb..389230f5a4d 100644 --- a/browser_tests/tests/agent/agentCrdtReload.spec.ts +++ b/browser_tests/tests/agent/agentCrdtReload.spec.ts @@ -104,6 +104,13 @@ test.describe('Agent CRDT reload', { tag: '@cloud' }, () => { await page.reload() await waitForCloudApp(page) await expect(page.locator('#agent-panel-root')).toBeVisible() + const reloadedWs = await getWebSocket(ws) + reloadedWs.send( + JSON.stringify({ + type: 'status', + data: { status: { exec_info: { queue_remaining: 0 } } } + }) + ) await expect .poll(() => countDocFrames(webSocketMessages, 'doc_subscribe', workflowId) From 31cf1a8c8d9f4b3b47b86f648523a8e6cd053220 Mon Sep 17 00:00:00 2001 From: Christian Byrne Date: Sat, 12 Sep 2026 15:34:00 -0700 Subject: [PATCH 04/48] test(agent): address reload review feedback Addresses review feedback: https://github.com/Comfy-Org/ComfyUI_frontend/pull/16708#discussion_r3994884170 https://github.com/Comfy-Org/ComfyUI_frontend/pull/16708#discussion_r3995539332 https://github.com/Comfy-Org/ComfyUI_frontend/pull/16708#discussion_r3995539337 https://github.com/Comfy-Org/ComfyUI_frontend/pull/16708#discussion_r3995539339 https://github.com/Comfy-Org/ComfyUI_frontend/pull/16708#discussion_r3995738212 --- browser_tests/fixtures/agentPanelFixture.ts | 18 ++- browser_tests/fixtures/ws.ts | 13 +- .../tests/agent/agentCrdtReload.spec.ts | 122 ++++++++++-------- .../extensions/agent/AgentPanelRoot.test.ts | 38 ++++++ .../extensions/agent/crdt/persistedDocId.ts | 1 - .../agent/crdt/useAgentCrdtFollower.test.ts | 39 ------ .../agent/crdt/useAgentCrdtFollower.ts | 7 + 7 files changed, 141 insertions(+), 97 deletions(-) diff --git a/browser_tests/fixtures/agentPanelFixture.ts b/browser_tests/fixtures/agentPanelFixture.ts index 647fb54adf0..48267c62630 100644 --- a/browser_tests/fixtures/agentPanelFixture.ts +++ b/browser_tests/fixtures/agentPanelFixture.ts @@ -1,14 +1,16 @@ -import type { Page } from '@playwright/test' +import type { Page, WebSocketRoute } from '@playwright/test' import type { GlobalSetting, ListAssetsResponse } from '@comfyorg/ingest-types' import type { RemoteConfig } from '@/platform/remoteConfig/types' import { AGENT_CONSENT_SETTING_ID } from '@/platform/settings/constants/agent' +import type { AgentWsEvent } from '@/workbench/extensions/agent/schemas/agentApiSchema' import { cloudAppFixture, waitForCloudApp } from '@e2e/fixtures/cloudAppFixture' import { mockBilling } from '@e2e/fixtures/utils/cloudBillingMocks' import { bootCloud, mockCloudBoot } from '@e2e/fixtures/utils/cloudBootMocks' import { jsonRoute } from '@e2e/fixtures/utils/jsonRoute' +import type { WorkspaceStore } from '@e2e/types/globals' const APP_URL = process.env.PLAYWRIGHT_TEST_URL || 'http://localhost:8188' @@ -86,6 +88,20 @@ export const agentTest = cloudAppFixture.extend({ agentFlagEnabled: [true, { option: true }] }) +export function pushAgentEvent(ws: WebSocketRoute, event: AgentWsEvent): void { + ws.send(JSON.stringify(event)) +} + +export async function getAgentActiveWorkflowPath( + page: Page +): Promise { + return await page.evaluate( + () => + (window.app!.extensionManager as WorkspaceStore).workflow.activeWorkflow + ?.path + ) +} + export async function bootAgentApp( page: Page, agentFlag: boolean, diff --git a/browser_tests/fixtures/ws.ts b/browser_tests/fixtures/ws.ts index 5c4d63c3dd3..ae29a4a8923 100644 --- a/browser_tests/fixtures/ws.ts +++ b/browser_tests/fixtures/ws.ts @@ -9,11 +9,12 @@ type SubscriptionFrame = Extract< > export function countDocFrames( - messages: string[], + messagesBySocket: Map, + ws: WebSocketRoute, type: SubscriptionFrame['type'], workflowId: string ): number { - return messages.filter((message) => { + return (messagesBySocket.get(ws) ?? []).filter((message) => { const frame = JSON.parse(message) as ClientDocFrame return frame.type === type && frame.data.workflow_id === workflowId }).length @@ -40,12 +41,12 @@ function createWebSocketRouteHandler( export const webSocketFixture = base.extend<{ connectWebSocketToServer: boolean getWebSocket: (after?: WebSocketRoute) => Promise - webSocketMessages: string[] + webSocketMessages: Map }>({ connectWebSocketToServer: [true, { option: true }], // oxlint-disable-next-line no-empty-pattern -- Playwright requires an object pattern. webSocketMessages: async ({}, use) => { - await use([]) + await use(new Map()) }, getWebSocket: [ async ({ context, connectWebSocketToServer, webSocketMessages }, use) => { @@ -55,12 +56,14 @@ export const webSocketFixture = base.extend<{ await context.routeWebSocket( /\/ws/, createWebSocketRouteHandler(connectWebSocketToServer, (ws, server) => { + const messages: string[] = [] + webSocketMessages.set(ws, messages) // Registering a page-side handler switches off Playwright's automatic // page-to-server forwarding, so recording has to re-send the frame // itself. Without this every spec merging the fixture drops the // `feature_flags` handshake and leaves `api.serverFeatureFlags` empty. ws.onMessage((message) => { - if (typeof message === 'string') webSocketMessages.push(message) + if (typeof message === 'string') messages.push(message) server?.send(message) }) latest = ws diff --git a/browser_tests/tests/agent/agentCrdtReload.spec.ts b/browser_tests/tests/agent/agentCrdtReload.spec.ts index 389230f5a4d..bfb74daa1fb 100644 --- a/browser_tests/tests/agent/agentCrdtReload.spec.ts +++ b/browser_tests/tests/agent/agentCrdtReload.spec.ts @@ -1,31 +1,21 @@ -import type { Page, WebSocketRoute } from '@playwright/test' import { expect, mergeTests } from '@playwright/test' -import { agentTest, bootAgentApp } from '@e2e/fixtures/agentPanelFixture' +import { + agentTest, + bootAgentApp, + getAgentActiveWorkflowPath, + pushAgentEvent +} from '@e2e/fixtures/agentPanelFixture' import { waitForCloudApp } from '@e2e/fixtures/cloudAppFixture' import { jsonRoute } from '@e2e/fixtures/utils/jsonRoute' import { countDocFrames, webSocketFixture } from '@e2e/fixtures/ws' -import type { WorkspaceStore } from '@e2e/types/globals' import enMessages from '@/locales/en/main.json' with { type: 'json' } -import type { AgentWsEvent } from '@/workbench/extensions/agent/schemas/agentApiSchema' const test = mergeTests(agentTest, webSocketFixture) const OPEN_AGENT_LABEL = enMessages.agent.askComfyAgent -function pushEvent(ws: WebSocketRoute, event: AgentWsEvent): void { - ws.send(JSON.stringify(event)) -} - -async function activeWorkflowPath(page: Page) { - return await page.evaluate( - () => - (window.app!.extensionManager as WorkspaceStore).workflow.activeWorkflow - ?.path - ) -} - test.describe('Agent CRDT reload', { tag: '@cloud' }, () => { test.use({ connectWebSocketToServer: false }) @@ -56,19 +46,25 @@ test.describe('Agent CRDT reload', { tag: '@cloud' }, () => { route.fulfill(jsonRoute({ threads: [] })) ) await bootAgentApp(page, agentFlagEnabled) - const ws = await getWebSocket() - await page.getByRole('button', { name: OPEN_AGENT_LABEL }).click() - await expect(page.locator('#agent-panel-root')).toBeVisible() - pushEvent(ws, { - type: 'agent_active_tab', - data: { workflow_id: workflowId, name: 'Reload receipt' } - }) - await expect - .poll(() => - countDocFrames(webSocketMessages, 'doc_subscribe', workflowId) - ) - .toBe(1) + const ws = + await test.step('Bind the active workflow and persist its reload state', async () => { + const ws = await getWebSocket() + await page.getByRole('button', { name: OPEN_AGENT_LABEL }).click() + await expect(page.locator('#agent-panel-root')).toBeVisible() + pushAgentEvent(ws, { + type: 'agent_active_tab', + data: { workflow_id: workflowId, name: 'Reload receipt' } + }) + + await expect + .poll(() => + countDocFrames(webSocketMessages, ws, 'doc_subscribe', workflowId) + ) + .toBe(1) + return ws + }) + ws.send( JSON.stringify({ type: 'doc_subscribed', @@ -96,41 +92,65 @@ test.describe('Agent CRDT reload', { tag: '@cloud' }, () => { ['Comfy.Agent.WorkflowTabBindings', workflowId] ) expect(boundPath).toBeTruthy() - await expect.poll(() => activeWorkflowPath(page)).toBe(boundPath) + await expect.poll(() => getAgentActiveWorkflowPath(page)).toBe(boundPath) expect( await page.evaluate(() => localStorage.getItem('Comfy.Agent.ThreadId')) ).toBeNull() - await page.reload() - await waitForCloudApp(page) - await expect(page.locator('#agent-panel-root')).toBeVisible() - const reloadedWs = await getWebSocket(ws) - reloadedWs.send( - JSON.stringify({ - type: 'status', - data: { status: { exec_info: { queue_remaining: 0 } } } + const reloadedWs = + await test.step('Reload and restore the workflow subscription', async () => { + await page.reload() + await waitForCloudApp(page) + await expect(page.locator('#agent-panel-root')).toBeVisible() + const reloadedWs = await getWebSocket(ws) + reloadedWs.send( + JSON.stringify({ + type: 'status', + data: { status: { exec_info: { queue_remaining: 0 } } } + }) + ) + await expect + .poll(() => + countDocFrames( + webSocketMessages, + reloadedWs, + 'doc_subscribe', + workflowId + ) + ) + .toBe(1) + return reloadedWs }) - ) - await expect - .poll(() => - countDocFrames(webSocketMessages, 'doc_subscribe', workflowId) - ) - .toBe(2) const recordAfterReload = await page.evaluate(() => JSON.parse(sessionStorage.getItem('Comfy.Agent.CrdtDocId')!) ) expect(recordAfterReload).toMatchObject({ docId: workflowId }) expect(recordAfterReload.nonce).not.toBe(recordBeforeReload.nonce) - await expect.poll(() => activeWorkflowPath(page)).toBe(boundPath) + await expect.poll(() => getAgentActiveWorkflowPath(page)).toBe(boundPath) - await page.evaluate(() => - window.app!.extensionManager.command.execute('Comfy.NewBlankWorkflow') - ) - await expect - .poll(() => - countDocFrames(webSocketMessages, 'doc_unsubscribe', workflowId) + await test.step('Opening a blank workflow suspends the restored follower', async () => { + expect( + countDocFrames( + webSocketMessages, + reloadedWs, + 'doc_unsubscribe', + workflowId + ) + ).toBe(0) + await page.evaluate(() => + window.app!.extensionManager.command.execute('Comfy.NewBlankWorkflow') ) - .toBe(1) + await expect + .poll(() => + countDocFrames( + webSocketMessages, + reloadedWs, + 'doc_unsubscribe', + workflowId + ) + ) + .toBe(1) + }) }) }) diff --git a/src/workbench/extensions/agent/AgentPanelRoot.test.ts b/src/workbench/extensions/agent/AgentPanelRoot.test.ts index 3e4e37e2644..b88acf25ec3 100644 --- a/src/workbench/extensions/agent/AgentPanelRoot.test.ts +++ b/src/workbench/extensions/agent/AgentPanelRoot.test.ts @@ -3524,6 +3524,44 @@ describe('AgentPanelRoot workflow binding', () => { ) }) + it('agent_active_tab selects a bound tab while the agent is idle', async () => { + const tab = makeTab('wf-42') + mockMessagesEndpoint('wf-42') + await renderAndSend('work here') + ws.emit('agent_message_done', { message_id: 'm-1', thread_id: 'th-1' }) + await screen.findByRole('button', { name: 'Send' }) + + ws.emit('agent_active_tab', { workflow_id: 'wf-42', thread_id: 'th-1' }) + + await vi.waitFor(() => + expect(useAgentPanelStore().selectedWorkflow?.path).toBe(tab.path) + ) + }) + + it('agent_active_tab selects a minted tab while the agent is idle', async () => { + makeTab('wf-42') + mockMessagesEndpoint('wf-42') + await renderAndSend('work here') + ws.emit('agent_message_done', { message_id: 'm-1', thread_id: 'th-1' }) + const setWorkflowTarget = vi.spyOn( + useAgentPanelStore(), + 'setWorkflowTarget' + ) + await screen.findByRole('button', { name: 'Send' }) + + ws.emit('agent_active_tab', { + workflow_id: 'wf-77', + name: 'Video test', + thread_id: 'th-1' + }) + + await vi.waitFor(() => + expect(setWorkflowTarget).toHaveBeenCalledWith( + expect.objectContaining({ path: 'workflows/Video test.json' }) + ) + ) + }) + it('agent_active_tab opens an unknown workflow as a blank named tab', async () => { makeTab('wf-42') mockMessagesEndpoint('wf-42') diff --git a/src/workbench/extensions/agent/crdt/persistedDocId.ts b/src/workbench/extensions/agent/crdt/persistedDocId.ts index 00ea67b2fb3..8b0421f28b7 100644 --- a/src/workbench/extensions/agent/crdt/persistedDocId.ts +++ b/src/workbench/extensions/agent/crdt/persistedDocId.ts @@ -13,7 +13,6 @@ import { AGENT_CRDT_DOC_ID_SESSION_KEY } from '@/platform/workflow/persistence/b // explicit reload may adopt the previous page load's unexpired record. export const DOC_ID_SESSION_KEY = AGENT_CRDT_DOC_ID_SESSION_KEY export const DOC_ID_TTL_MS = 5 * 60 * 1000 -export const DOC_ID_REFRESH_INTERVAL_MS = DOC_ID_TTL_MS / 2 let pageSessionNonce: string | undefined diff --git a/src/workbench/extensions/agent/crdt/useAgentCrdtFollower.test.ts b/src/workbench/extensions/agent/crdt/useAgentCrdtFollower.test.ts index 1980e2ae265..30867a0b629 100644 --- a/src/workbench/extensions/agent/crdt/useAgentCrdtFollower.test.ts +++ b/src/workbench/extensions/agent/crdt/useAgentCrdtFollower.test.ts @@ -147,7 +147,6 @@ vi.mock(import('@/scripts/app'), () => ({ import { STALE_AFTER_MS, useAgentCrdtFollower } from './useAgentCrdtFollower' import type { AgentCrdtStatus } from './useAgentCrdtFollower' -import { reconcilePersistedDocId } from './persistedDocId' const graphMutations = {} as GraphMutations const DOC_ID_KEY = 'Comfy.Agent.CrdtDocId' @@ -340,30 +339,6 @@ describe('useAgentCrdtFollower', () => { unmount() }) - it('FE-1969: the persisted doc reconciler mirrors the next rebind', () => { - const { unmount } = mountFollower('wf-1') - expect(reconcilePersistedDocId()).toBeNull() - - dispatchFrame('doc_subscribed', { ok: true }) - expect(reconcilePersistedDocId()).toBe('wf-1') - - writeRawRecord({ docId: 'wf-1', nonce: 'foreign-nonce' }) - expect(reconcilePersistedDocId()).toBeNull() - expect(persistedRecord()).toBeNull() - - // The mismatch branch above consumed the record, so the reload branch needs - // its own; asserting against the emptied store would pass no matter what a - // reload does. A reload is the one navigation permitted to adopt the - // previous page load's record, and it takes ownership when it does. - writeRawRecord({ docId: 'wf-1', nonce: 'foreign-nonce' }) - vi.spyOn(performance, 'getEntriesByType').mockReturnValue([ - { type: 'reload' } as PerformanceNavigationTiming - ]) - expect(reconcilePersistedDocId()).toBe('wf-1') - expect(persistedRecord()?.nonce).not.toBe('foreign-nonce') - unmount() - }) - it('FE-1902: a remount with no in-memory binding rebinds from sessionStorage', () => { const setup = mountFollower('wf-1') dispatchFrame('doc_subscribed', { ok: true }) @@ -377,20 +352,6 @@ describe('useAgentCrdtFollower', () => { unmount() }) - it('FE-1902: a page reload adopts and rebinds the previous navigation record', () => { - vi.spyOn(performance, 'getEntriesByType').mockReturnValue([ - { type: 'reload' } as PerformanceNavigationTiming - ]) - writeRawRecord({ docId: 'wf-1', nonce: 'previous-page-load' }) - - const { unmount, status } = mountFollower(null) - - expect(bridge().subscribe).toHaveBeenCalledWith('wf-1') - expect(status().workflowId).toBe('wf-1') - expect(persistedRecord()?.nonce).not.toBe('previous-page-load') - unmount() - }) - it('FE-1902: a real detach clears the persisted binding and unsubscribes', async () => { const { unmount, workflowId } = mountFollower('wf-1') dispatchFrame('doc_subscribed', { ok: true }) diff --git a/src/workbench/extensions/agent/crdt/useAgentCrdtFollower.ts b/src/workbench/extensions/agent/crdt/useAgentCrdtFollower.ts index fc2fe5968a2..fbb19d11053 100644 --- a/src/workbench/extensions/agent/crdt/useAgentCrdtFollower.ts +++ b/src/workbench/extensions/agent/crdt/useAgentCrdtFollower.ts @@ -100,6 +100,7 @@ export function useAgentCrdtFollower( */ getGraph: () => MaterializableGraph | null = () => null ) { + const acknowledgedWorkflowId = ref(null) const connected = ref(false) const updatesApplied = ref(0) const lastFrameType = ref(null) @@ -174,6 +175,7 @@ export function useAgentCrdtFollower( if (!isTargetActive.value) return const ok = event.detail?.ok === true connected.value = ok + acknowledgedWorkflowId.value = ok ? bridge.subscribedWorkflowId : null lastFrameType.value = event.type recordDevEvent('doc_subscribed', event.detail ?? null) if (ok) { @@ -258,6 +260,7 @@ export function useAgentCrdtFollower( } projection.clearForReset(detail.workflowId, context) connected.value = false + acknowledgedWorkflowId.value = null updatesApplied.value = 0 lastFrameType.value = event.type lifecycle.clearStaleProbe() @@ -295,6 +298,7 @@ export function useAgentCrdtFollower( // nothing was projected. Surface it as its own status rather than as a // generic "disconnected", which is indistinguishable from "never connected". connected.value = false + acknowledgedWorkflowId.value = null lastFrameType.value = event.type lifecycle.clearStaleProbe() const detail = @@ -325,6 +329,7 @@ export function useAgentCrdtFollower( } const onReconnected: EventListener = () => { connected.value = false + acknowledgedWorkflowId.value = null lifecycle.clearStaleProbe() recordDevEvent('reconnected', null) bridge.resubscribe() @@ -396,6 +401,7 @@ export function useAgentCrdtFollower( const justActivated = active && previous?.[1] === false lifecycle.clearForRetarget() connected.value = false + acknowledgedWorkflowId.value = null knownDocNodeIds = new Set() if (!active) { if (next !== null) initialBind = false @@ -486,6 +492,7 @@ export function useAgentCrdtFollower( return { status: readonly(status), debugSnapshot, + acknowledgedWorkflowId: readonly(acknowledgedWorkflowId), enqueueHumanOperations: (operations: GraphOperation[]) => sender.enqueue(operations) } From 510ef4dd875205fd5c87c4cd42c14cb4af597d2d Mon Sep 17 00:00:00 2001 From: Christian Byrne Date: Mon, 14 Sep 2026 22:39:12 -0700 Subject: [PATCH 05/48] fix(agent): derive follower connection from acknowledgment --- .../extensions/agent/crdt/useAgentCrdtFollower.ts | 8 +------- 1 file changed, 1 insertion(+), 7 deletions(-) diff --git a/src/workbench/extensions/agent/crdt/useAgentCrdtFollower.ts b/src/workbench/extensions/agent/crdt/useAgentCrdtFollower.ts index fbb19d11053..ad6be3ff14e 100644 --- a/src/workbench/extensions/agent/crdt/useAgentCrdtFollower.ts +++ b/src/workbench/extensions/agent/crdt/useAgentCrdtFollower.ts @@ -101,7 +101,6 @@ export function useAgentCrdtFollower( getGraph: () => MaterializableGraph | null = () => null ) { const acknowledgedWorkflowId = ref(null) - const connected = ref(false) const updatesApplied = ref(0) const lastFrameType = ref(null) const subscribedWorkflowId = ref(null) @@ -174,7 +173,6 @@ export function useAgentCrdtFollower( if (!(event instanceof CustomEvent)) return if (!isTargetActive.value) return const ok = event.detail?.ok === true - connected.value = ok acknowledgedWorkflowId.value = ok ? bridge.subscribedWorkflowId : null lastFrameType.value = event.type recordDevEvent('doc_subscribed', event.detail ?? null) @@ -259,7 +257,6 @@ export function useAgentCrdtFollower( opId: `doc-reset:${detail.seq ?? 'unknown'}` } projection.clearForReset(detail.workflowId, context) - connected.value = false acknowledgedWorkflowId.value = null updatesApplied.value = 0 lastFrameType.value = event.type @@ -297,7 +294,6 @@ export function useAgentCrdtFollower( // KA-11 fail-closed: the bridge refused to propagate an unreadable doc, so // nothing was projected. Surface it as its own status rather than as a // generic "disconnected", which is indistinguishable from "never connected". - connected.value = false acknowledgedWorkflowId.value = null lastFrameType.value = event.type lifecycle.clearStaleProbe() @@ -328,7 +324,6 @@ export function useAgentCrdtFollower( ) } const onReconnected: EventListener = () => { - connected.value = false acknowledgedWorkflowId.value = null lifecycle.clearStaleProbe() recordDevEvent('reconnected', null) @@ -400,7 +395,6 @@ export function useAgentCrdtFollower( // existing "reconcile on frame or on graph readiness" behaviour. const justActivated = active && previous?.[1] === false lifecycle.clearForRetarget() - connected.value = false acknowledgedWorkflowId.value = null knownDocNodeIds = new Set() if (!active) { @@ -474,7 +468,7 @@ export function useAgentCrdtFollower( const status = computed(() => ({ enabled: true, - connected: connected.value, + connected: acknowledgedWorkflowId.value !== null, workflowId: subscribedWorkflowId.value, updatesApplied: updatesApplied.value, lastFrameType: lastFrameType.value, From 51b2326f2b840b01717c5e892ba3a5dda46a066c Mon Sep 17 00:00:00 2001 From: Christian Byrne Date: Sat, 19 Sep 2026 21:32:37 -0700 Subject: [PATCH 06/48] test(agent-crdt): assert the reload resubscribe across sockets, not one route The exact-head cloud run still failed this assertion with `Received: 0` after arming the socket waiter before the reload, so socket-identity timing was not the cause, or not the only one. The assertion was checking whether one captured `WebSocketRoute` saw the resubscribe. What the test actually claims is that the reloaded app resubscribed, and a reload may route more than one replacement socket, so a product failure and a test-plumbing failure produced the same red. It now counts `doc_subscribe` and `doc_unsubscribe` across every recorded socket except the pre-reload one. This is a better assertion regardless of which way it lands, and it makes the next run decisive: still 0 means the reloaded app genuinely does not resubscribe, which is the behavior this PR claims to restore; 1 means the earlier reds were watching the wrong route. --- .../tests/agent/agentCrdtReload.spec.ts | 84 ++++++++----------- 1 file changed, 37 insertions(+), 47 deletions(-) diff --git a/browser_tests/tests/agent/agentCrdtReload.spec.ts b/browser_tests/tests/agent/agentCrdtReload.spec.ts index 75ec2fd028f..29dea647a35 100644 --- a/browser_tests/tests/agent/agentCrdtReload.spec.ts +++ b/browser_tests/tests/agent/agentCrdtReload.spec.ts @@ -98,35 +98,41 @@ test.describe('Agent CRDT reload', { tag: '@cloud' }, () => { await page.evaluate(() => localStorage.getItem('Comfy.Agent.ThreadId')) ).toBeNull() - const reloadedWs = - await test.step('Reload and restore the workflow subscription', async () => { - // Arm the waiter BEFORE the reload. The replacement socket is routed - // and starts recording as soon as the reloaded page connects, so a - // waiter registered afterwards can miss it and leave the assertion - // below polling a socket that never receives the resubscribe. - const pendingWs = nextWebSocket() - await page.reload() - await waitForCloudApp(page) - await expect(page.locator('#agent-panel-root')).toBeVisible() - const reloadedWs = await pendingWs - reloadedWs.send( - JSON.stringify({ - type: 'status', - data: { status: { exec_info: { queue_remaining: 0 } } } - }) - ) - await expect - .poll(() => - countDocFrames( - webSocketMessages, - reloadedWs, - 'doc_subscribe', - workflowId - ) - ) - .toBe(1) - return reloadedWs - }) + // Count across every socket EXCEPT the pre-reload one. The claim under test + // is "the reloaded app resubscribed", not "one particular WebSocketRoute + // saw it", and a reload can route more than one replacement socket. Binding + // the assertion to a single captured route turns a product failure and a + // test-plumbing failure into the same red, which is what made the earlier + // run ambiguous. + const countAfterReload = ( + type: 'doc_subscribe' | 'doc_unsubscribe' + ): number => { + let total = 0 + for (const socket of webSocketMessages.keys()) { + if (socket === ws) continue + total += countDocFrames(webSocketMessages, socket, type, workflowId) + } + return total + } + + await test.step('Reload and restore the workflow subscription', async () => { + // Arm the waiter BEFORE the reload. The replacement socket is routed + // and starts recording as soon as the reloaded page connects, so a + // waiter registered afterwards can miss it and leave the assertion + // below polling a socket that never receives the resubscribe. + const pendingWs = nextWebSocket() + await page.reload() + await waitForCloudApp(page) + await expect(page.locator('#agent-panel-root')).toBeVisible() + const reloadedWs = await pendingWs + reloadedWs.send( + JSON.stringify({ + type: 'status', + data: { status: { exec_info: { queue_remaining: 0 } } } + }) + ) + await expect.poll(() => countAfterReload('doc_subscribe')).toBe(1) + }) const recordAfterReload = await page.evaluate(() => JSON.parse(sessionStorage.getItem('Comfy.Agent.CrdtDocId')!) @@ -136,27 +142,11 @@ test.describe('Agent CRDT reload', { tag: '@cloud' }, () => { await expect.poll(() => getAgentActiveWorkflowPath(page)).toBe(boundPath) await test.step('Opening a blank workflow suspends the restored follower', async () => { - expect( - countDocFrames( - webSocketMessages, - reloadedWs, - 'doc_unsubscribe', - workflowId - ) - ).toBe(0) + expect(countAfterReload('doc_unsubscribe')).toBe(0) await page.evaluate(() => window.app!.extensionManager.command.execute('Comfy.NewBlankWorkflow') ) - await expect - .poll(() => - countDocFrames( - webSocketMessages, - reloadedWs, - 'doc_unsubscribe', - workflowId - ) - ) - .toBe(1) + await expect.poll(() => countAfterReload('doc_unsubscribe')).toBe(1) }) }) }) From 36f81bac07a13802c2aeca7b8ad500eff98fd2c6 Mon Sep 17 00:00:00 2001 From: Christian Byrne Date: Sat, 19 Sep 2026 21:51:48 -0700 Subject: [PATCH 07/48] test(agent-crdt): stage the reload assertions so a red says where it broke The socket-agnostic count also read 0 at `51b2326f2b`, across every post-reload socket rather than one captured route. That rules out the plumbing explanation: the reloaded app does not resubscribe at all. Since the remaining question is which stage of the restore fails, the two preconditions for resubscribing are now asserted before the subscribe itself: the adopted `Comfy.Agent.CrdtDocId` record, and the rebound tab path. If either is wrong the subscribe count is a downstream symptom; if both hold, the gap is in the follower bind. The trailing copies of those assertions are removed rather than duplicated. No product change. This does not make the test pass, and is not intended to; it makes the next red diagnostic. --- .../tests/agent/agentCrdtReload.spec.ts | 18 +++++++++++------- 1 file changed, 11 insertions(+), 7 deletions(-) diff --git a/browser_tests/tests/agent/agentCrdtReload.spec.ts b/browser_tests/tests/agent/agentCrdtReload.spec.ts index 29dea647a35..46915da725f 100644 --- a/browser_tests/tests/agent/agentCrdtReload.spec.ts +++ b/browser_tests/tests/agent/agentCrdtReload.spec.ts @@ -131,16 +131,20 @@ test.describe('Agent CRDT reload', { tag: '@cloud' }, () => { data: { status: { exec_info: { queue_remaining: 0 } } } }) ) + // Assert the restore in stages so a red says WHERE it broke. The doc-id + // record and the rebound tab are the two preconditions for resubscribing; + // if either is wrong the subscribe assertion below is a downstream + // symptom, and if both hold then the gap is in the follower bind itself. + const record = await page.evaluate(() => + JSON.parse(sessionStorage.getItem('Comfy.Agent.CrdtDocId')!) + ) + expect(record).toMatchObject({ docId: workflowId }) + expect(record.nonce).not.toBe(recordBeforeReload.nonce) + await expect.poll(() => getAgentActiveWorkflowPath(page)).toBe(boundPath) + await expect.poll(() => countAfterReload('doc_subscribe')).toBe(1) }) - const recordAfterReload = await page.evaluate(() => - JSON.parse(sessionStorage.getItem('Comfy.Agent.CrdtDocId')!) - ) - expect(recordAfterReload).toMatchObject({ docId: workflowId }) - expect(recordAfterReload.nonce).not.toBe(recordBeforeReload.nonce) - await expect.poll(() => getAgentActiveWorkflowPath(page)).toBe(boundPath) - await test.step('Opening a blank workflow suspends the restored follower', async () => { expect(countAfterReload('doc_unsubscribe')).toBe(0) await page.evaluate(() => From ae89468928648bdacef24e6930a7e2c624fd7d05 Mon Sep 17 00:00:00 2001 From: Christian Byrne Date: Sun, 20 Sep 2026 00:37:39 -0700 Subject: [PATCH 08/48] docs(agent-crdt): state the doc_reset invariant instead of main's old assignment The comment described what main's `connected.value = false` used to do here, which stops being readable once that ref is gone. `acknowledgedWorkflowId` is the source of truth, so say what is true now: a lineage reset drops the acknowledged binding and therefore disconnects the follower. https://github.com/Comfy-Org/ComfyUI_frontend/pull/16708#discussion_r4056167633 --- src/workbench/extensions/agent/crdt/useAgentCrdtFollower.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/workbench/extensions/agent/crdt/useAgentCrdtFollower.ts b/src/workbench/extensions/agent/crdt/useAgentCrdtFollower.ts index 9132e01e8e3..84b9d557e45 100644 --- a/src/workbench/extensions/agent/crdt/useAgentCrdtFollower.ts +++ b/src/workbench/extensions/agent/crdt/useAgentCrdtFollower.ts @@ -460,8 +460,8 @@ function startAgentCrdtFollower( } projection.clearForReset(detail.workflowId, context) events.onReset?.(detail.workflowId) - // `status.connected` derives from this, so clearing the acknowledgement is - // what main's `connected.value = false` used to do here. + // A lineage reset drops the acknowledged binding, which disconnects the + // follower: `status.connected` is derived from this ref. acknowledgedWorkflowId.value = null updatesApplied.value = 0 lastFrameType.value = event.type From 143beca352e55cbb8afa6112b6b6157c36de9316 Mon Sep 17 00:00:00 2001 From: Christian Byrne Date: Sun, 20 Sep 2026 00:37:49 -0700 Subject: [PATCH 09/48] docs(agent-crdt): drop the rebase history from the finite-expiry comment MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The invariant stays stated — `JSON.parse` turns `1e400` into `Infinity`, which passes a `typeof === 'number'` test and can never expire — but the count of rebases that lost the guard is process history that goes stale in source. The durable protection is the single persistence owner plus the regression test at persistedDocId.test.ts:61-67, which replays that literal. https://github.com/Comfy-Org/ComfyUI_frontend/pull/16708#discussion_r4056167630 --- src/workbench/extensions/agent/crdt/persistedDocId.ts | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/workbench/extensions/agent/crdt/persistedDocId.ts b/src/workbench/extensions/agent/crdt/persistedDocId.ts index 2d9940e71cf..4df523f08ed 100644 --- a/src/workbench/extensions/agent/crdt/persistedDocId.ts +++ b/src/workbench/extensions/agent/crdt/persistedDocId.ts @@ -70,8 +70,7 @@ export function reconcilePersistedDocId(): string | null { // `Number.isFinite`, not `typeof === 'number'`: `JSON.parse` turns an // out-of-range literal such as `1e400` into `Infinity`, which is a number // and is never `<= Date.now()`, so a `typeof` check alone hands back a - // record that can never expire. Do not relax this to a `typeof` test; it - // has been lost to a rebase twice already. + // record that can never expire. if ( typeof record.docId !== 'string' || typeof record.nonce !== 'string' || From 856062e687a209253a14c53b68080effbfd4277e Mon Sep 17 00:00:00 2001 From: Christian Byrne Date: Sun, 20 Sep 2026 00:38:37 -0700 Subject: [PATCH 10/48] test(agent-crdt): open the reload spec's panel through the AgentPanel page object MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The raw entry-button click plus root visibility wait duplicated AgentPanel.open(), which neighboring agent specs already use, so the spec carried a second readiness recipe that would drift from the page object. The post-reload wait stays an assertion rather than an open() call — the panel restores itself there — but now targets agentPanel.root, so the raw '#agent-panel-root' selector is gone from the spec entirely. https://github.com/Comfy-Org/ComfyUI_frontend/pull/16708#discussion_r4056167628 --- browser_tests/tests/agent/agentCrdtReload.spec.ts | 13 ++++++------- 1 file changed, 6 insertions(+), 7 deletions(-) diff --git a/browser_tests/tests/agent/agentCrdtReload.spec.ts b/browser_tests/tests/agent/agentCrdtReload.spec.ts index 46915da725f..0f722d84605 100644 --- a/browser_tests/tests/agent/agentCrdtReload.spec.ts +++ b/browser_tests/tests/agent/agentCrdtReload.spec.ts @@ -7,15 +7,12 @@ import { pushAgentEvent } from '@e2e/fixtures/agentPanelFixture' import { waitForCloudApp } from '@e2e/fixtures/cloudAppFixture' +import { AgentPanel } from '@e2e/fixtures/components/AgentPanel' import { jsonRoute } from '@e2e/fixtures/utils/jsonRoute' import { countDocFrames, webSocketFixture } from '@e2e/fixtures/ws' -import enMessages from '@/locales/en/main.json' with { type: 'json' } - const test = mergeTests(agentTest, webSocketFixture) -const OPEN_AGENT_LABEL = enMessages.agent.entryButton - test.describe('Agent CRDT reload', { tag: '@cloud' }, () => { test.use({ connectWebSocketToServer: false }) @@ -28,6 +25,7 @@ test.describe('Agent CRDT reload', { tag: '@cloud' }, () => { }) => { test.setTimeout(90_000) const workflowId = 'a81718a4-02ae-41e6-ae85-c33b7bb880f6' + const agentPanel = new AgentPanel(page) await page.route('**/api/internal/cloud_analytics', (route) => route.fulfill(jsonRoute({})) @@ -51,8 +49,7 @@ test.describe('Agent CRDT reload', { tag: '@cloud' }, () => { const ws = await test.step('Bind the active workflow and persist its reload state', async () => { const ws = await getWebSocket() - await page.getByRole('button', { name: OPEN_AGENT_LABEL }).click() - await expect(page.locator('#agent-panel-root')).toBeVisible() + await agentPanel.open() pushAgentEvent(ws, { type: 'agent_active_tab', data: { workflow_id: workflowId, name: 'Reload receipt' } @@ -123,7 +120,9 @@ test.describe('Agent CRDT reload', { tag: '@cloud' }, () => { const pendingWs = nextWebSocket() await page.reload() await waitForCloudApp(page) - await expect(page.locator('#agent-panel-root')).toBeVisible() + // Not `agentPanel.open()`: the panel restores itself on reload, so this + // is a readiness wait on the same page object's root, not a second open. + await expect(agentPanel.root).toBeVisible() const reloadedWs = await pendingWs reloadedWs.send( JSON.stringify({ From f129225304794082fed8b01f510016fd77bce49f Mon Sep 17 00:00:00 2001 From: Christian Byrne Date: Sun, 20 Sep 2026 00:43:35 -0700 Subject: [PATCH 11/48] fix(agent-crdt): collapse the persisted doc id onto one owner `agentCrdtDocLifecycle.ts` carried its own copy of the persisted doc-id record: same `Comfy.Agent.CrdtDocId` key, same shape, but a second module-scope page-load nonce. Two owners on one key can never agree. Whichever module wrote last left the other's reader comparing against a foreign nonce, so it reported "nothing persisted" for the rest of the page load. That is the reload path this PR exists to fix, and it is why the new browser spec was red at 36f81bac07 with the staged assertions passing and only the resubscribe failing. On reload `useAgentDockMount` reconciles the record through `persistedDocId.ts`, which adopts it and re-stamps it with THAT module's nonce. The follower's initial bind then asks the lifecycle, whose reader sees the foreign nonce, answers `null`, and `restorePersistedTarget` clears the record and retargets to null. No `doc_subscribe` is ever sent. The lifecycle is now a consumer: `persistDocId`, `clearPersistedDocId` and `reconcilePersistedDocId` all come from `persistedDocId.ts`. Its reader's empty-doc-id guard is not lost in the collapse, it moves into the owner's shape check with its own regression test, since `''` passes a bare `typeof === 'string'` and would be subscribed to. Three tests in agentCrdtDocLifecycle.test.ts are red on the parent (round-trip, reload adoption, confirmed-subscribe persist) and green here; the file's other 13 are unchanged. This also answers the "one persistence owner" half of https://github.com/Comfy-Org/ComfyUI_frontend/pull/16708#discussion_r4056167630 --- .../agent/crdt/agentCrdtDocLifecycle.test.ts | 56 +++++++++ .../agent/crdt/agentCrdtDocLifecycle.ts | 107 +++--------------- .../agent/crdt/persistedDocId.test.ts | 26 +++++ .../extensions/agent/crdt/persistedDocId.ts | 3 + 4 files changed, 101 insertions(+), 91 deletions(-) diff --git a/src/workbench/extensions/agent/crdt/agentCrdtDocLifecycle.test.ts b/src/workbench/extensions/agent/crdt/agentCrdtDocLifecycle.test.ts index 6d9796e42f6..b2fe1f68543 100644 --- a/src/workbench/extensions/agent/crdt/agentCrdtDocLifecycle.test.ts +++ b/src/workbench/extensions/agent/crdt/agentCrdtDocLifecycle.test.ts @@ -8,6 +8,11 @@ import { SUBSCRIBE_ACK_TIMEOUT_MS } from './agentCrdtDocLifecycle' import { recordDevEvent } from './devPanelLog' +import { + DOC_ID_SESSION_KEY, + persistDocId, + reconcilePersistedDocId +} from './persistedDocId' vi.mock(import('./devPanelLog'), () => ({ recordDevEvent: vi.fn() })) vi.mock(import('@/platform/telemetry/reportError'), () => ({ @@ -274,3 +279,54 @@ describe('AgentCrdtDocLifecycle ack timeout', () => { expect(resubscribe).toHaveBeenCalledTimes(3) }) }) + +/** + * FE-1969 regression. This file used to carry its OWN copy of the persisted + * doc-id record — same `Comfy.Agent.CrdtDocId` key, but a second module-scope + * page-load nonce. Two owners on one key can never agree: whichever module + * wrote last left the other's reader looking at a foreign nonce, so + * `readPersistedDocId()` answered "nothing persisted" for the rest of the page + * load. On a reload that is exactly the failing path — `useAgentDockMount` + * reconciles the record through `persistedDocId.ts` and re-stamps it with that + * module's nonce, then the follower's initial bind asks the lifecycle, gets + * `null`, clears the record and never resubscribes. + */ +describe('AgentCrdtDocLifecycle persisted doc id', () => { + beforeEach(() => { + sessionStorage.clear() + }) + + it('reads back a record written through the single persistence owner', () => { + const { lifecycle } = wire() + persistDocId(WORKFLOW_ID) + + expect(lifecycle.readPersistedDocId()).toBe(WORKFLOW_ID) + }) + + it('still sees the record after a reload adoption re-stamps its nonce', () => { + const { lifecycle } = wire() + // A previous page load's record: right key and shape, foreign nonce. + sessionStorage.setItem( + DOC_ID_SESSION_KEY, + JSON.stringify({ + docId: WORKFLOW_ID, + nonce: 'the-pre-reload-page-load', + expiresAt: Date.now() + 60_000 + }) + ) + vi.spyOn(performance, 'getEntriesByType').mockReturnValue([ + { type: 'reload' } as PerformanceNavigationTiming + ]) + // What useAgentDockMount does before the follower ever binds. + expect(reconcilePersistedDocId()).toBe(WORKFLOW_ID) + + expect(lifecycle.readPersistedDocId()).toBe(WORKFLOW_ID) + }) + + it('a confirmed subscribe persists through the same owner', () => { + const { lifecycle } = wire() + lifecycle.onSubscribeConfirmed() + + expect(reconcilePersistedDocId()).toBe(WORKFLOW_ID) + }) +}) diff --git a/src/workbench/extensions/agent/crdt/agentCrdtDocLifecycle.ts b/src/workbench/extensions/agent/crdt/agentCrdtDocLifecycle.ts index e2329661c0f..1b669e04d34 100644 --- a/src/workbench/extensions/agent/crdt/agentCrdtDocLifecycle.ts +++ b/src/workbench/extensions/agent/crdt/agentCrdtDocLifecycle.ts @@ -1,32 +1,22 @@ import { reportError } from '@/platform/telemetry/reportError' -import { createUuidv4 } from '@/utils/uuid' import { recordDevEvent } from './devPanelLog' +import { + DOC_ID_TTL_MS, + clearPersistedDocId, + persistDocId, + reconcilePersistedDocId +} from './persistedDocId' + +// FE-1902 / FEC-5: the persisted doc-id record is owned entirely by +// `persistedDocId.ts` - key, shape, page-load nonce, TTL, and every read and +// write, including the FE-1969 reload adoption. This file is a CONSUMER, not a +// second owner. Two owners cannot coexist on one sessionStorage key: each +// module mints its own page-load nonce, so whichever writes last leaves the +// other's reader looking at a foreign nonce and reporting "nothing persisted" +// for the rest of the page load. The rationale for the nonce and the expiry +// lives with the owner. -// 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 -// in sessionStorage so an in-page remount can rebind immediately. A full page -// reload deliberately does NOT rebind (see the nonce below): it mints a new -// nonce, refuses the pre-reload record, and waits for the next turn ack. -// -// FEC-5: a bare `docId` string has no owner and no lifetime, so it survives -// (a) a workflow switch in the same browser tab - the NEXT panel mount rebinds -// to whichever workflow last confirmed a subscribe, not necessarily the one -// about to become active - and (b) a browser-tab duplication, which clones -// sessionStorage verbatim into a second tab that never subscribed to that doc -// at all. Neither case can be caught by re-checking `workflowId`, because the -// whole reason a rebind is attempted is that the caller does NOT yet know -// which workflow it's asking about. Instead the persisted record carries (1) -// a per-page-load session nonce, so a value only ever rebinds within the -// SAME top-level navigation that wrote it - a duplicated tab gets a fresh -// nonce and its inherited record is refused - and (2) a short expiry that -// slides while the doc keeps delivering frames, so a tab left idle past the -// window a doc realistically stays relevant is refused rather than trusted -// indefinitely. (1) closes case (b). Case (a) happens inside one page load, -// so the nonce cannot see it; it is only BOUNDED by (2), not closed. The -// `fec-docid-1` reproducer tracks the remaining same-tab window. -const DOC_ID_SESSION_KEY = 'Comfy.Agent.CrdtDocId' -const DOC_ID_TTL_MS = 5 * 60 * 1000 // Re-stamp the expiry on doc traffic at most this often, so a busy channel // does not turn every frame into a sessionStorage write. const DOC_ID_REFRESH_INTERVAL_MS = DOC_ID_TTL_MS / 2 @@ -59,71 +49,6 @@ const SUBSCRIBE_ACK_MAX_TIMEOUTS = 3 */ export const STALE_AFTER_MS = 30_000 -// One nonce per page load (module scope = one per top-level navigation, since -// a full reload re-evaluates the module). A tab duplicated mid-session -// inherits sessionStorage's persisted record but gets its own module -// instance and thus its own nonce, so the inherited record's nonce mismatches -// and is refused. -const pageSessionNonce = createUuidv4() - -interface PersistedDocIdRecord { - docId: string - nonce: string - expiresAt: number -} - -function safeSessionStorage(): Storage | null { - try { - return window.sessionStorage - } catch { - return null - } -} - -function persistDocId(docId: string): void { - try { - const record: PersistedDocIdRecord = { - docId, - nonce: pageSessionNonce, - expiresAt: Date.now() + DOC_ID_TTL_MS - } - safeSessionStorage()?.setItem(DOC_ID_SESSION_KEY, JSON.stringify(record)) - } catch { - // Quota / privacy mode: persistence is best-effort. - } -} - -function readPersistedDocId(): string | null { - try { - const raw = safeSessionStorage()?.getItem(DOC_ID_SESSION_KEY) - if (!raw) return null - const record = JSON.parse(raw) as Partial - if ( - typeof record.docId !== 'string' || - record.docId.length === 0 || - typeof record.nonce !== 'string' || - typeof record.expiresAt !== 'number' - ) { - // Legacy/malformed record (e.g. pre-FEC-5 bare-string value): treat as - // absent rather than trusting an unscoped id. - return null - } - if (record.nonce !== pageSessionNonce) return null - if (Date.now() >= record.expiresAt) return null - return record.docId - } catch { - return null - } -} - -function clearPersistedDocId(): void { - try { - safeSessionStorage()?.removeItem(DOC_ID_SESSION_KEY) - } catch { - // Best-effort. - } -} - export class AgentCrdtDocLifecycle { private subscribeRetryTimer: ReturnType | null = null private subscribeRetryAttempt = 0 @@ -155,7 +80,7 @@ export class AgentCrdtDocLifecycle { ) {} readPersistedDocId(): string | null { - return readPersistedDocId() + return reconcilePersistedDocId() } clearPersistedDocId(): void { diff --git a/src/workbench/extensions/agent/crdt/persistedDocId.test.ts b/src/workbench/extensions/agent/crdt/persistedDocId.test.ts index 6961985680e..acf318cda92 100644 --- a/src/workbench/extensions/agent/crdt/persistedDocId.test.ts +++ b/src/workbench/extensions/agent/crdt/persistedDocId.test.ts @@ -171,3 +171,29 @@ describe('persistedDocId', () => { }) }) }) + +/** + * Carried over from the duplicate reader that used to live in + * `agentCrdtDocLifecycle.ts`. Collapsing onto one owner must not drop its + * guards: an empty doc id passes `typeof === 'string'` and would be handed + * back for the follower to subscribe to. + */ +describe('empty doc id', () => { + beforeEach(() => { + sessionStorage.clear() + }) + + it('refuses and consumes a record whose doc id is the empty string', () => { + sessionStorage.setItem( + DOC_ID_SESSION_KEY, + JSON.stringify({ + docId: '', + nonce: 'a-different-page-load', + expiresAt: Date.now() + 60_000 + }) + ) + + expect(reconcilePersistedDocId()).toBeNull() + expect(rawRecord()).toBeNull() + }) +}) diff --git a/src/workbench/extensions/agent/crdt/persistedDocId.ts b/src/workbench/extensions/agent/crdt/persistedDocId.ts index 4df523f08ed..1a82d22bcec 100644 --- a/src/workbench/extensions/agent/crdt/persistedDocId.ts +++ b/src/workbench/extensions/agent/crdt/persistedDocId.ts @@ -71,8 +71,11 @@ export function reconcilePersistedDocId(): string | null { // out-of-range literal such as `1e400` into `Infinity`, which is a number // and is never `<= Date.now()`, so a `typeof` check alone hands back a // record that can never expire. + // The empty string is a string and would subscribe to a doc id of `''`, + // so length is part of the shape check, not a separate caller concern. if ( typeof record.docId !== 'string' || + record.docId.length === 0 || typeof record.nonce !== 'string' || typeof record.expiresAt !== 'number' || !Number.isFinite(record.expiresAt) From 91cd2942a803167668d472dc4a7fefdb6d0e35d6 Mon Sep 17 00:00:00 2001 From: Christian Byrne Date: Mon, 21 Sep 2026 02:27:52 -0700 Subject: [PATCH 12/48] fix(agent): preserve reload-time workflow restore Addresses https://github.com/Comfy-Org/ComfyUI_frontend/pull/16708#discussion_r4056572250 --- src/workbench/extensions/agent/AgentPanelRoot.vue | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/workbench/extensions/agent/AgentPanelRoot.vue b/src/workbench/extensions/agent/AgentPanelRoot.vue index b11401d9985..c89be5a2360 100644 --- a/src/workbench/extensions/agent/AgentPanelRoot.vue +++ b/src/workbench/extensions/agent/AgentPanelRoot.vue @@ -455,7 +455,9 @@ watch( const newChatDetached = ref(false) const workflowDetached = computed( - () => newChatDetached.value || selectedTarget.value === null + () => + newChatDetached.value || + (selectedTarget.value === null && !agentPanelStore.canRestoreWorkflow) ) watch(selectedTarget, (target) => { if (target !== null) newChatDetached.value = false From c8d89059b9770a9f8b482d5af1dfd749245e46cc Mon Sep 17 00:00:00 2001 From: Christian Byrne Date: Mon, 21 Sep 2026 02:28:17 -0700 Subject: [PATCH 13/48] refactor(agent): use CRDT status for mint wiring Addresses https://github.com/Comfy-Org/ComfyUI_frontend/pull/16708#discussion_r4056572252 --- .../extensions/agent/AgentPanelRoot.vue | 5 ++-- .../agent/crdt/useAgentCrdtFollower.test.ts | 23 ++++++++----------- .../agent/crdt/useAgentCrdtFollower.ts | 5 ---- 3 files changed, 11 insertions(+), 22 deletions(-) diff --git a/src/workbench/extensions/agent/AgentPanelRoot.vue b/src/workbench/extensions/agent/AgentPanelRoot.vue index c89be5a2360..11b18efb579 100644 --- a/src/workbench/extensions/agent/AgentPanelRoot.vue +++ b/src/workbench/extensions/agent/AgentPanelRoot.vue @@ -645,7 +645,6 @@ const isBoundWorkflowActive = computed( const { status: crdtStatus, debugSnapshot: crdtDebugSnapshot, - acknowledgedWorkflowId, enqueueHumanOperations } = useAgentCrdtFollower( activeBoundWorkflowId, @@ -672,8 +671,8 @@ const { const mintPortWiring = attachMintPortWiring({ isEnabled: () => agentPanelStore.enabled, isDocBound: () => - acknowledgedWorkflowId.value !== null && - acknowledgedWorkflowId.value === activeBoundWorkflowId.value, + crdtStatus.value.connected && + crdtStatus.value.workflowId === activeBoundWorkflowId.value, enqueue: enqueueHumanOperations, layoutChanges: (listener) => layoutStore.onChange(listener), localActorPrefix: ACTOR_CONFIG.USER_PREFIX, diff --git a/src/workbench/extensions/agent/crdt/useAgentCrdtFollower.test.ts b/src/workbench/extensions/agent/crdt/useAgentCrdtFollower.test.ts index 1bc011c30ab..8422b0890b3 100644 --- a/src/workbench/extensions/agent/crdt/useAgentCrdtFollower.test.ts +++ b/src/workbench/extensions/agent/crdt/useAgentCrdtFollower.test.ts @@ -215,15 +215,13 @@ function mountFollower( workflowId: Ref isTargetActive: Ref status: () => AgentCrdtStatus - acknowledgedWorkflowId: () => string | null } { const workflowId = ref(initial) const isTargetActive = ref(initiallyActive) let exposedStatus!: () => AgentCrdtStatus - let exposedAcknowledgedWorkflowId!: () => string | null const host = defineComponent({ setup() { - const { status, acknowledgedWorkflowId } = useAgentCrdtFollower( + const { status } = useAgentCrdtFollower( workflowId, graphMutations, () => null, @@ -232,7 +230,6 @@ function mountFollower( events ) exposedStatus = () => status.value as AgentCrdtStatus - exposedAcknowledgedWorkflowId = () => acknowledgedWorkflowId.value return () => null } }) @@ -241,8 +238,7 @@ function mountFollower( unmount, workflowId, isTargetActive, - status: exposedStatus, - acknowledgedWorkflowId: exposedAcknowledgedWorkflowId + status: exposedStatus } } @@ -402,25 +398,24 @@ describe('useAgentCrdtFollower', () => { unmount() }) - it('surfaces a binding only after the server acknowledges it', async () => { - const { unmount, workflowId, acknowledgedWorkflowId } = - mountFollower('wf-1') + it('reports a connection only after the server acknowledges it', async () => { + const { unmount, workflowId, status } = mountFollower('wf-1') - expect(acknowledgedWorkflowId()).toBeNull() + expect(status().connected).toBe(false) dispatchFrame('doc_subscribed', { ok: true, workflowId: 'wf-1' }) - expect(acknowledgedWorkflowId()).toBe('wf-1') + expect(status().connected).toBe(true) workflowId.value = 'wf-2' await nextTick() - expect(acknowledgedWorkflowId()).toBeNull() + expect(status().connected).toBe(false) dispatchFrame('doc_subscribed', { ok: true, workflowId: 'wf-2' }) - expect(acknowledgedWorkflowId()).toBe('wf-2') + expect(status().connected).toBe(true) bridge().subscribedWorkflowId = null dispatchFrame('doc_subscribed', { ok: false, workflowId: 'wf-2' }) - expect(acknowledgedWorkflowId()).toBeNull() + expect(status().connected).toBe(false) unmount() }) diff --git a/src/workbench/extensions/agent/crdt/useAgentCrdtFollower.ts b/src/workbench/extensions/agent/crdt/useAgentCrdtFollower.ts index 799d1167581..3c397cc8297 100644 --- a/src/workbench/extensions/agent/crdt/useAgentCrdtFollower.ts +++ b/src/workbench/extensions/agent/crdt/useAgentCrdtFollower.ts @@ -254,11 +254,6 @@ export function useAgentCrdtFollower( lastSeq: null, schemaError: null }), - // Forwarded through the facade: between retargets `follower` is undefined, - // and "no follower" is the same answer as "not acknowledged". - acknowledgedWorkflowId: computed( - () => follower.value?.acknowledgedWorkflowId.value ?? null - ), enqueueHumanOperations: (operations: GraphOperation[]) => follower.value?.enqueueHumanOperations(operations) } From 19d85762d3e3b82ac30d49c3dbc4c1453aa3c45f Mon Sep 17 00:00:00 2001 From: Christian Byrne Date: Mon, 21 Sep 2026 02:28:23 -0700 Subject: [PATCH 14/48] test(agent): state CRDT reset invariant directly Addresses https://github.com/Comfy-Org/ComfyUI_frontend/pull/16708#discussion_r4056572255 --- .../extensions/agent/crdt/useAgentCrdtFollower.test.ts | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/workbench/extensions/agent/crdt/useAgentCrdtFollower.test.ts b/src/workbench/extensions/agent/crdt/useAgentCrdtFollower.test.ts index 8422b0890b3..ad39c851658 100644 --- a/src/workbench/extensions/agent/crdt/useAgentCrdtFollower.test.ts +++ b/src/workbench/extensions/agent/crdt/useAgentCrdtFollower.test.ts @@ -708,8 +708,7 @@ describe('useAgentCrdtFollower', () => { // `connected` is derived from `acknowledgedWorkflowId`, not tracked as its // own ref, so the doc_reset lineage break has to drop the acknowledgement to - // report a disconnect. A rebase that reinstates a separate `connected` write - // here, or drops the acknowledgement reset, silently breaks that. + // report a disconnect. it('reports a disconnect when a doc_reset breaks the lineage', () => { const { unmount, status } = mountFollower('wf-1') dispatchFrame('doc_subscribed', { ok: true }) From 42290c1a47797e860e428ffe16afbdc3966b86a2 Mon Sep 17 00:00:00 2001 From: Christian Byrne Date: Mon, 21 Sep 2026 02:28:31 -0700 Subject: [PATCH 15/48] fix(agent): validate persisted CRDT records Addresses https://github.com/Comfy-Org/ComfyUI_frontend/pull/16708#discussion_r4056572257 --- .../extensions/agent/crdt/persistedDocId.ts | 22 ++++++++++++++----- 1 file changed, 16 insertions(+), 6 deletions(-) diff --git a/src/workbench/extensions/agent/crdt/persistedDocId.ts b/src/workbench/extensions/agent/crdt/persistedDocId.ts index 1a82d22bcec..183da3d4d3c 100644 --- a/src/workbench/extensions/agent/crdt/persistedDocId.ts +++ b/src/workbench/extensions/agent/crdt/persistedDocId.ts @@ -61,7 +61,7 @@ export function reconcilePersistedDocId(): string | null { try { const raw = safeSessionStorage()?.getItem(DOC_ID_SESSION_KEY) if (!raw) return null - const record = JSON.parse(raw) as Partial + const parsed: unknown = JSON.parse(raw) // Every rejection below also drops the key. Leaving a rejected record in // place would break the invariant the dock-mount reconcile relies on: a // duplicated tab that inherits a lapsed or pre-FEC-5 record would keep @@ -74,15 +74,25 @@ export function reconcilePersistedDocId(): string | null { // The empty string is a string and would subscribe to a doc id of `''`, // so length is part of the shape check, not a separate caller concern. if ( - typeof record.docId !== 'string' || - record.docId.length === 0 || - typeof record.nonce !== 'string' || - typeof record.expiresAt !== 'number' || - !Number.isFinite(record.expiresAt) + typeof parsed !== 'object' || + parsed === null || + !('docId' in parsed) || + typeof parsed.docId !== 'string' || + parsed.docId.length === 0 || + !('nonce' in parsed) || + typeof parsed.nonce !== 'string' || + !('expiresAt' in parsed) || + typeof parsed.expiresAt !== 'number' || + !Number.isFinite(parsed.expiresAt) ) { clearPersistedDocId() return null } + const record: PersistedDocIdRecord = { + docId: parsed.docId, + nonce: parsed.nonce, + expiresAt: parsed.expiresAt + } if (Date.now() >= record.expiresAt) { clearPersistedDocId() return null From aebf86540b1f68d20f8c1be9bc9181c88383ae0b Mon Sep 17 00:00:00 2001 From: Christian Byrne Date: Mon, 21 Sep 2026 02:28:43 -0700 Subject: [PATCH 16/48] fix(agent): narrow reload navigation entries Addresses https://github.com/Comfy-Org/ComfyUI_frontend/pull/16708#discussion_r4056572261 --- src/workbench/extensions/agent/crdt/persistedDocId.test.ts | 3 ++- src/workbench/extensions/agent/crdt/persistedDocId.ts | 2 +- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/src/workbench/extensions/agent/crdt/persistedDocId.test.ts b/src/workbench/extensions/agent/crdt/persistedDocId.test.ts index acf318cda92..da734f633ae 100644 --- a/src/workbench/extensions/agent/crdt/persistedDocId.test.ts +++ b/src/workbench/extensions/agent/crdt/persistedDocId.test.ts @@ -1,3 +1,4 @@ +import { fromPartial } from '@total-typescript/shoehorn' import { beforeEach, describe, expect, it, vi } from 'vitest' import { @@ -27,7 +28,7 @@ function writeForeignRecord(docId: string, expiresAt: number): void { function asReloadNavigation(): void { vi.spyOn(performance, 'getEntriesByType').mockReturnValue([ - { type: 'reload' } as PerformanceNavigationTiming + fromPartial({ type: 'reload' }) ]) } diff --git a/src/workbench/extensions/agent/crdt/persistedDocId.ts b/src/workbench/extensions/agent/crdt/persistedDocId.ts index 183da3d4d3c..182528d5a2b 100644 --- a/src/workbench/extensions/agent/crdt/persistedDocId.ts +++ b/src/workbench/extensions/agent/crdt/persistedDocId.ts @@ -54,7 +54,7 @@ export function persistDocId(docId: string): void { function isReloadNavigation(): boolean { return performance .getEntriesByType('navigation') - .some((entry) => (entry as PerformanceNavigationTiming).type === 'reload') + .some((entry) => 'type' in entry && entry.type === 'reload') } export function reconcilePersistedDocId(): string | null { From 6c0719fe3e56757952eac9a7159b6fade6a23cb3 Mon Sep 17 00:00:00 2001 From: Christian Byrne Date: Mon, 21 Sep 2026 02:28:58 -0700 Subject: [PATCH 17/48] test(agent): read reload state through typed owners Addresses https://github.com/Comfy-Org/ComfyUI_frontend/pull/16708#discussion_r4056572264 --- browser_tests/fixtures/agentPanelFixture.ts | 23 ++++++++ .../tests/agent/agentCrdtReload.spec.ts | 54 +++++++++++++------ 2 files changed, 60 insertions(+), 17 deletions(-) diff --git a/browser_tests/fixtures/agentPanelFixture.ts b/browser_tests/fixtures/agentPanelFixture.ts index e9e8e22a37d..b5ce5b5bc35 100644 --- a/browser_tests/fixtures/agentPanelFixture.ts +++ b/browser_tests/fixtures/agentPanelFixture.ts @@ -6,6 +6,7 @@ import type { RemoteConfig } from '@/platform/remoteConfig/types' import type { ComfyNodeDef } from '@/schemas/nodeDefSchema' import { AGENT_CONSENT_SETTING_ID } from '@/platform/settings/constants/agent' import type { AgentWsEvent } from '@/workbench/extensions/agent/schemas/agentApiSchema' +import type { useAgentWorkflowTabBindingStore } from '@/workbench/extensions/agent/stores/agent/agentWorkflowTabBindingStore' import { cloudAppFixture, waitForCloudApp } from '@e2e/fixtures/cloudAppFixture' import { mockBilling } from '@e2e/fixtures/utils/cloudBillingMocks' @@ -118,6 +119,28 @@ export async function getAgentActiveWorkflowPath( ) } +export async function getAgentBoundWorkflowPath( + page: Page, + workflowId: string +): Promise { + return await page.evaluate((workflowId) => { + const root = document.getElementById('vue-app') as (HTMLElement & { + __vue_app__?: { + config: { + globalProperties: { + $pinia?: { _s: Map } + } + } + } + }) | null + const pinia = root?.__vue_app__?.config.globalProperties.$pinia + const store = pinia?._s.get('agentWorkflowTabBinding') as + | ReturnType + | undefined + return store?.tabPathFor(workflowId) + }, workflowId) +} + export async function bootAgentApp( page: Page, agentFlag: boolean, diff --git a/browser_tests/tests/agent/agentCrdtReload.spec.ts b/browser_tests/tests/agent/agentCrdtReload.spec.ts index 0f722d84605..98dc4e3798f 100644 --- a/browser_tests/tests/agent/agentCrdtReload.spec.ts +++ b/browser_tests/tests/agent/agentCrdtReload.spec.ts @@ -1,9 +1,11 @@ -import { expect, mergeTests } from '@playwright/test' +import { expect, mergeTests, type Page } from '@playwright/test' +import { AGENT_CRDT_DOC_ID_SESSION_KEY } from '@/platform/workflow/persistence/base/storageKeyConstants' import { agentTest, bootAgentApp, getAgentActiveWorkflowPath, + getAgentBoundWorkflowPath, pushAgentEvent } from '@e2e/fixtures/agentPanelFixture' import { waitForCloudApp } from '@e2e/fixtures/cloudAppFixture' @@ -13,6 +15,33 @@ import { countDocFrames, webSocketFixture } from '@e2e/fixtures/ws' const test = mergeTests(agentTest, webSocketFixture) +interface PersistedDocIdentity { + docId: string + nonce: string +} + +async function readPersistedDocIdentity( + page: Page +): Promise { + const raw = await page.evaluate( + (key) => sessionStorage.getItem(key), + AGENT_CRDT_DOC_ID_SESSION_KEY + ) + if (raw === null) throw new Error('Persisted CRDT document record is missing') + const parsed: unknown = JSON.parse(raw) + if ( + typeof parsed !== 'object' || + parsed === null || + !('docId' in parsed) || + typeof parsed.docId !== 'string' || + !('nonce' in parsed) || + typeof parsed.nonce !== 'string' + ) { + throw new Error('Persisted CRDT document record is malformed') + } + return { docId: parsed.docId, nonce: parsed.nonce } +} + test.describe('Agent CRDT reload', { tag: '@cloud' }, () => { test.use({ connectWebSocketToServer: false }) @@ -72,23 +101,16 @@ test.describe('Agent CRDT reload', { tag: '@cloud' }, () => { await expect .poll(() => - page.evaluate(() => sessionStorage.getItem('Comfy.Agent.CrdtDocId')) + page.evaluate( + (key) => sessionStorage.getItem(key), + AGENT_CRDT_DOC_ID_SESSION_KEY + ) ) .not.toBeNull() - const recordBeforeReload = await page.evaluate(() => - JSON.parse(sessionStorage.getItem('Comfy.Agent.CrdtDocId')!) - ) + const recordBeforeReload = await readPersistedDocIdentity(page) expect(recordBeforeReload).toMatchObject({ docId: workflowId }) - const boundPath = await page.evaluate( - ([key, id]) => { - const bindings = JSON.parse( - localStorage.getItem(key) ?? '{}' - ) as Record - return bindings[id] - }, - ['Comfy.Agent.WorkflowTabBindings', workflowId] - ) + const boundPath = await getAgentBoundWorkflowPath(page, workflowId) expect(boundPath).toBeTruthy() await expect.poll(() => getAgentActiveWorkflowPath(page)).toBe(boundPath) expect( @@ -134,9 +156,7 @@ test.describe('Agent CRDT reload', { tag: '@cloud' }, () => { // record and the rebound tab are the two preconditions for resubscribing; // if either is wrong the subscribe assertion below is a downstream // symptom, and if both hold then the gap is in the follower bind itself. - const record = await page.evaluate(() => - JSON.parse(sessionStorage.getItem('Comfy.Agent.CrdtDocId')!) - ) + const record = await readPersistedDocIdentity(page) expect(record).toMatchObject({ docId: workflowId }) expect(record.nonce).not.toBe(recordBeforeReload.nonce) await expect.poll(() => getAgentActiveWorkflowPath(page)).toBe(boundPath) From 5013dfe6822fa3b8a785b014f53d99d496b3c033 Mon Sep 17 00:00:00 2001 From: Christian Byrne Date: Mon, 21 Sep 2026 02:29:07 -0700 Subject: [PATCH 18/48] test(agent): load storage transitions at module scope Addresses https://github.com/Comfy-Org/ComfyUI_frontend/pull/16708#discussion_r4056572266 --- .../extensions/agent/crdt/persistedDocId.test.ts | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/src/workbench/extensions/agent/crdt/persistedDocId.test.ts b/src/workbench/extensions/agent/crdt/persistedDocId.test.ts index da734f633ae..e75614330d6 100644 --- a/src/workbench/extensions/agent/crdt/persistedDocId.test.ts +++ b/src/workbench/extensions/agent/crdt/persistedDocId.test.ts @@ -1,6 +1,11 @@ import { fromPartial } from '@total-typescript/shoehorn' import { beforeEach, describe, expect, it, vi } from 'vitest' +import { + clearAllWorkflowStorage, + clearWorkflowRestoreState +} from '@/platform/workflow/persistence/base/storageIO' + import { DOC_ID_SESSION_KEY, DOC_ID_TTL_MS, @@ -143,9 +148,7 @@ describe('persistedDocId', () => { }) describe('identity transitions drop the binding', () => { - it('workspace switching clears it', async () => { - const { clearWorkflowRestoreState } = - await import('@/platform/workflow/persistence/base/storageIO') + it('workspace switching clears it', () => { persistDocId('wf-1') clearWorkflowRestoreState() @@ -153,9 +156,7 @@ describe('persistedDocId', () => { expect(rawRecord()).toBeNull() }) - it('signing out clears it', async () => { - const { clearAllWorkflowStorage } = - await import('@/platform/workflow/persistence/base/storageIO') + it('signing out clears it', () => { persistDocId('wf-1') clearAllWorkflowStorage() From 75383fa1ccd476dd010ed29f6e911d14695fff14 Mon Sep 17 00:00:00 2001 From: Christian Byrne Date: Mon, 21 Sep 2026 02:29:14 -0700 Subject: [PATCH 19/48] test(agent): execute blank workflow through helper Addresses https://github.com/Comfy-Org/ComfyUI_frontend/pull/16708#discussion_r4056572269 --- browser_tests/tests/agent/agentCrdtReload.spec.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/browser_tests/tests/agent/agentCrdtReload.spec.ts b/browser_tests/tests/agent/agentCrdtReload.spec.ts index 98dc4e3798f..4f2253b428a 100644 --- a/browser_tests/tests/agent/agentCrdtReload.spec.ts +++ b/browser_tests/tests/agent/agentCrdtReload.spec.ts @@ -10,6 +10,7 @@ import { } from '@e2e/fixtures/agentPanelFixture' import { waitForCloudApp } from '@e2e/fixtures/cloudAppFixture' import { AgentPanel } from '@e2e/fixtures/components/AgentPanel' +import { CommandHelper } from '@e2e/fixtures/helpers/CommandHelper' import { jsonRoute } from '@e2e/fixtures/utils/jsonRoute' import { countDocFrames, webSocketFixture } from '@e2e/fixtures/ws' @@ -55,6 +56,7 @@ test.describe('Agent CRDT reload', { tag: '@cloud' }, () => { test.setTimeout(90_000) const workflowId = 'a81718a4-02ae-41e6-ae85-c33b7bb880f6' const agentPanel = new AgentPanel(page) + const command = new CommandHelper(page) await page.route('**/api/internal/cloud_analytics', (route) => route.fulfill(jsonRoute({})) @@ -166,9 +168,7 @@ test.describe('Agent CRDT reload', { tag: '@cloud' }, () => { await test.step('Opening a blank workflow suspends the restored follower', async () => { expect(countAfterReload('doc_unsubscribe')).toBe(0) - await page.evaluate(() => - window.app!.extensionManager.command.execute('Comfy.NewBlankWorkflow') - ) + await command.executeCommand('Comfy.NewBlankWorkflow') await expect.poll(() => countAfterReload('doc_unsubscribe')).toBe(1) }) }) From d99538c5ef2aa96671330d0e4c62d7a45f5a550b Mon Sep 17 00:00:00 2001 From: Christian Byrne Date: Mon, 21 Sep 2026 02:29:22 -0700 Subject: [PATCH 20/48] docs(agent): distinguish remount and reload restore Addresses https://github.com/Comfy-Org/ComfyUI_frontend/pull/16708#discussion_r4056572271 --- src/workbench/extensions/agent/AgentPanelRoot.vue | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/src/workbench/extensions/agent/AgentPanelRoot.vue b/src/workbench/extensions/agent/AgentPanelRoot.vue index 11b18efb579..fb2b31b28e5 100644 --- a/src/workbench/extensions/agent/AgentPanelRoot.vue +++ b/src/workbench/extensions/agent/AgentPanelRoot.vue @@ -593,13 +593,13 @@ const isSending = computed( () => sessionIsSending.value || composerStore.submission?.phase === 'pending' ) -// FE-1969: `boundWorkflowId` is the in-memory session binding and is reset -// whenever the session restarts within the same page load — a panel remount, -// or a reload inside the record's TTL. The follower can still rebind to the doc -// it persisted for this page load, but only if this computed drives it with -// `active=true`. "New chat" is deliberately not one of those cases: it ends the -// session, so `onNewChat` drops the record and there is nothing left to -// restore. The +// FE-1969: `boundWorkflowId` is the in-memory session binding. A panel remount +// can restore it within the same page load. A browser reload creates a new page +// load, so `reconcilePersistedDocId()` adopts the previous load's unexpired +// record and replaces its nonce. In either case, the follower can rebind only +// if this computed drives it with `active=true`. "New chat" is deliberately not +// one of those cases: it ends the session, so `onNewChat` drops the record and +// there is nothing left to restore. The // fallback is scoped to that one doc: the active tab's persisted tab binding // counts only when it names the doc the follower would restore, so a tab that // merely carries a stale binding, or a second bound tab, never reads as From aa9e30584eccbccc6811b7f5146d284edd5ce48a Mon Sep 17 00:00:00 2001 From: Christian Byrne Date: Mon, 21 Sep 2026 02:40:15 -0700 Subject: [PATCH 21/48] fix(agent): parse browser binding through store owner Fixes browser typecheck from https://github.com/Comfy-Org/ComfyUI_frontend/actions/runs/35583605835/job/106281775458 --- browser_tests/fixtures/agentPanelFixture.ts | 23 ---------------- .../tests/agent/agentCrdtReload.spec.ts | 11 ++++++-- .../agent/agentWorkflowTabBindingStore.ts | 27 ++++++++++++++++--- 3 files changed, 33 insertions(+), 28 deletions(-) diff --git a/browser_tests/fixtures/agentPanelFixture.ts b/browser_tests/fixtures/agentPanelFixture.ts index b5ce5b5bc35..e9e8e22a37d 100644 --- a/browser_tests/fixtures/agentPanelFixture.ts +++ b/browser_tests/fixtures/agentPanelFixture.ts @@ -6,7 +6,6 @@ import type { RemoteConfig } from '@/platform/remoteConfig/types' import type { ComfyNodeDef } from '@/schemas/nodeDefSchema' import { AGENT_CONSENT_SETTING_ID } from '@/platform/settings/constants/agent' import type { AgentWsEvent } from '@/workbench/extensions/agent/schemas/agentApiSchema' -import type { useAgentWorkflowTabBindingStore } from '@/workbench/extensions/agent/stores/agent/agentWorkflowTabBindingStore' import { cloudAppFixture, waitForCloudApp } from '@e2e/fixtures/cloudAppFixture' import { mockBilling } from '@e2e/fixtures/utils/cloudBillingMocks' @@ -119,28 +118,6 @@ export async function getAgentActiveWorkflowPath( ) } -export async function getAgentBoundWorkflowPath( - page: Page, - workflowId: string -): Promise { - return await page.evaluate((workflowId) => { - const root = document.getElementById('vue-app') as (HTMLElement & { - __vue_app__?: { - config: { - globalProperties: { - $pinia?: { _s: Map } - } - } - } - }) | null - const pinia = root?.__vue_app__?.config.globalProperties.$pinia - const store = pinia?._s.get('agentWorkflowTabBinding') as - | ReturnType - | undefined - return store?.tabPathFor(workflowId) - }, workflowId) -} - export async function bootAgentApp( page: Page, agentFlag: boolean, diff --git a/browser_tests/tests/agent/agentCrdtReload.spec.ts b/browser_tests/tests/agent/agentCrdtReload.spec.ts index 4f2253b428a..abacd44d35d 100644 --- a/browser_tests/tests/agent/agentCrdtReload.spec.ts +++ b/browser_tests/tests/agent/agentCrdtReload.spec.ts @@ -1,11 +1,14 @@ import { expect, mergeTests, type Page } from '@playwright/test' import { AGENT_CRDT_DOC_ID_SESSION_KEY } from '@/platform/workflow/persistence/base/storageKeyConstants' +import { + AGENT_WORKFLOW_TAB_BINDINGS_STORAGE_KEY, + readPersistedAgentWorkflowTabPath +} from '@/workbench/extensions/agent/stores/agent/agentWorkflowTabBindingStore' import { agentTest, bootAgentApp, getAgentActiveWorkflowPath, - getAgentBoundWorkflowPath, pushAgentEvent } from '@e2e/fixtures/agentPanelFixture' import { waitForCloudApp } from '@e2e/fixtures/cloudAppFixture' @@ -112,7 +115,11 @@ test.describe('Agent CRDT reload', { tag: '@cloud' }, () => { const recordBeforeReload = await readPersistedDocIdentity(page) expect(recordBeforeReload).toMatchObject({ docId: workflowId }) - const boundPath = await getAgentBoundWorkflowPath(page, workflowId) + const rawBindings = await page.evaluate( + (key) => localStorage.getItem(key), + AGENT_WORKFLOW_TAB_BINDINGS_STORAGE_KEY + ) + const boundPath = readPersistedAgentWorkflowTabPath(rawBindings, workflowId) expect(boundPath).toBeTruthy() await expect.poll(() => getAgentActiveWorkflowPath(page)).toBe(boundPath) expect( diff --git a/src/workbench/extensions/agent/stores/agent/agentWorkflowTabBindingStore.ts b/src/workbench/extensions/agent/stores/agent/agentWorkflowTabBindingStore.ts index df8da4a0684..cb245dff905 100644 --- a/src/workbench/extensions/agent/stores/agent/agentWorkflowTabBindingStore.ts +++ b/src/workbench/extensions/agent/stores/agent/agentWorkflowTabBindingStore.ts @@ -7,7 +7,8 @@ import type { ComfyWorkflow } from '@/platform/workflow/management/stores/comfyW import { useWorkflowStore } from '@/platform/workflow/management/stores/workflowStore' const LEGACY_STORAGE_KEY = 'Comfy.Agent.WorkflowTabBindings' -const STORAGE_KEY = 'Comfy.Agent.WorkflowTabBindings.v2' +export const AGENT_WORKFLOW_TAB_BINDINGS_STORAGE_KEY = + 'Comfy.Agent.WorkflowTabBindings.v2' const BINDING_TTL_MS = 30 * 24 * 60 * 60 * 1000 interface PersistedBinding { @@ -64,6 +65,22 @@ function liveBindings( ) } +export function readPersistedAgentWorkflowTabPath( + raw: string | null, + workflowId: string, + now = Date.now() +): string | undefined { + if (raw === null) return undefined + try { + const parsed: unknown = JSON.parse(raw) + if (typeof parsed !== 'object' || parsed === null) return undefined + return liveBindings(parsed as Record, now)[workflowId] + ?.tabPath + } catch { + return undefined + } +} + function graphIdOf(tab: ComfyWorkflow): string | undefined { const activeId = tab.activeState?.id if (activeId !== undefined) return activeId @@ -85,8 +102,12 @@ export const useAgentWorkflowTabBindingStore = defineStore( 'agentWorkflowTabBinding', () => { const now = Date.now() - const hasStoredBindings = localStorage.getItem(STORAGE_KEY) !== null - const tabByWorkflow = useLocalStorage(STORAGE_KEY, {}) + const hasStoredBindings = + localStorage.getItem(AGENT_WORKFLOW_TAB_BINDINGS_STORAGE_KEY) !== null + const tabByWorkflow = useLocalStorage( + AGENT_WORKFLOW_TAB_BINDINGS_STORAGE_KEY, + {} + ) tabByWorkflow.value = liveBindings( hasStoredBindings ? tabByWorkflow.value : readLegacyBindings(now), now From 3f5b66648983da40b9725424f4d4fe87e6213151 Mon Sep 17 00:00:00 2001 From: GitHub Action Date: Mon, 21 Sep 2026 09:49:00 +0000 Subject: [PATCH 22/48] [automated] Apply ESLint and Oxfmt fixes --- browser_tests/tests/agent/agentCrdtReload.spec.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/browser_tests/tests/agent/agentCrdtReload.spec.ts b/browser_tests/tests/agent/agentCrdtReload.spec.ts index abacd44d35d..643f1184f4a 100644 --- a/browser_tests/tests/agent/agentCrdtReload.spec.ts +++ b/browser_tests/tests/agent/agentCrdtReload.spec.ts @@ -1,4 +1,5 @@ -import { expect, mergeTests, type Page } from '@playwright/test' +import { expect, mergeTests } from '@playwright/test' +import type { Page } from '@playwright/test' import { AGENT_CRDT_DOC_ID_SESSION_KEY } from '@/platform/workflow/persistence/base/storageKeyConstants' import { From d74cbbcfc915ec375cbb07cd3a8c8294e15c515f Mon Sep 17 00:00:00 2001 From: Christian Byrne Date: Mon, 21 Sep 2026 03:04:06 -0700 Subject: [PATCH 23/48] test(agent): isolate reload storage parser Move persisted binding parsing into a dependency-free storage module so Playwright test discovery does not pull in the Pinia/Vue component graph.\n\nFailed job: https://github.com/Comfy-Org/ComfyUI_frontend/actions/runs/35585605700/job/106289321426 --- .../tests/agent/agentCrdtReload.spec.ts | 2 +- .../agent/agentWorkflowTabBindingStorage.ts | 58 +++++++++++++++ .../agent/agentWorkflowTabBindingStore.ts | 73 +++++-------------- 3 files changed, 76 insertions(+), 57 deletions(-) create mode 100644 src/workbench/extensions/agent/stores/agent/agentWorkflowTabBindingStorage.ts diff --git a/browser_tests/tests/agent/agentCrdtReload.spec.ts b/browser_tests/tests/agent/agentCrdtReload.spec.ts index 643f1184f4a..99938a93693 100644 --- a/browser_tests/tests/agent/agentCrdtReload.spec.ts +++ b/browser_tests/tests/agent/agentCrdtReload.spec.ts @@ -5,7 +5,7 @@ import { AGENT_CRDT_DOC_ID_SESSION_KEY } from '@/platform/workflow/persistence/b import { AGENT_WORKFLOW_TAB_BINDINGS_STORAGE_KEY, readPersistedAgentWorkflowTabPath -} from '@/workbench/extensions/agent/stores/agent/agentWorkflowTabBindingStore' +} from '@/workbench/extensions/agent/stores/agent/agentWorkflowTabBindingStorage' import { agentTest, bootAgentApp, diff --git a/src/workbench/extensions/agent/stores/agent/agentWorkflowTabBindingStorage.ts b/src/workbench/extensions/agent/stores/agent/agentWorkflowTabBindingStorage.ts new file mode 100644 index 00000000000..7568f0f187b --- /dev/null +++ b/src/workbench/extensions/agent/stores/agent/agentWorkflowTabBindingStorage.ts @@ -0,0 +1,58 @@ +export const AGENT_WORKFLOW_TAB_BINDINGS_STORAGE_KEY = + 'Comfy.Agent.WorkflowTabBindings.v2' + +const BINDING_TTL_MS = 30 * 24 * 60 * 60 * 1000 + +export interface PersistedAgentWorkflowTabBinding { + tabPath: string + graphId: string | null + confirmedAt: number +} + +export type PersistedAgentWorkflowTabBindings = Record< + string, + PersistedAgentWorkflowTabBinding +> + +function isPersistedBinding( + value: unknown +): value is PersistedAgentWorkflowTabBinding { + if (typeof value !== 'object' || value === null) return false + const { tabPath, graphId, confirmedAt } = value as Record + return ( + typeof tabPath === 'string' && + (graphId === null || typeof graphId === 'string') && + typeof confirmedAt === 'number' + ) +} + +export function liveAgentWorkflowTabBindings( + bindings: Record, + now: number +): PersistedAgentWorkflowTabBindings { + return Object.fromEntries( + Object.entries(bindings).filter( + (entry): entry is [string, PersistedAgentWorkflowTabBinding] => + isPersistedBinding(entry[1]) && + entry[1].confirmedAt + BINDING_TTL_MS >= now + ) + ) +} + +export function readPersistedAgentWorkflowTabPath( + raw: string | null, + workflowId: string, + now = Date.now() +): string | undefined { + if (raw === null) return undefined + try { + const parsed: unknown = JSON.parse(raw) + if (typeof parsed !== 'object' || parsed === null) return undefined + return liveAgentWorkflowTabBindings( + parsed as Record, + now + )[workflowId]?.tabPath + } catch { + return undefined + } +} diff --git a/src/workbench/extensions/agent/stores/agent/agentWorkflowTabBindingStore.ts b/src/workbench/extensions/agent/stores/agent/agentWorkflowTabBindingStore.ts index cb245dff905..713ef55de02 100644 --- a/src/workbench/extensions/agent/stores/agent/agentWorkflowTabBindingStore.ts +++ b/src/workbench/extensions/agent/stores/agent/agentWorkflowTabBindingStore.ts @@ -6,35 +6,23 @@ import { areWorkflowIdsEquivalent } from '@/platform/workflow/core/utils/workflo import type { ComfyWorkflow } from '@/platform/workflow/management/stores/comfyWorkflow' import { useWorkflowStore } from '@/platform/workflow/management/stores/workflowStore' -const LEGACY_STORAGE_KEY = 'Comfy.Agent.WorkflowTabBindings' -export const AGENT_WORKFLOW_TAB_BINDINGS_STORAGE_KEY = - 'Comfy.Agent.WorkflowTabBindings.v2' -const BINDING_TTL_MS = 30 * 24 * 60 * 60 * 1000 - -interface PersistedBinding { - tabPath: string - graphId: string | null - confirmedAt: number -} +import { + AGENT_WORKFLOW_TAB_BINDINGS_STORAGE_KEY, + liveAgentWorkflowTabBindings +} from './agentWorkflowTabBindingStorage' +import type { + PersistedAgentWorkflowTabBinding, + PersistedAgentWorkflowTabBindings +} from './agentWorkflowTabBindingStorage' -type PersistedBindings = Record +const LEGACY_STORAGE_KEY = 'Comfy.Agent.WorkflowTabBindings' interface OpenTab { tab: ComfyWorkflow path: string } -function isPersistedBinding(value: unknown): value is PersistedBinding { - if (typeof value !== 'object' || value === null) return false - const { tabPath, graphId, confirmedAt } = value as Record - return ( - typeof tabPath === 'string' && - (graphId === null || typeof graphId === 'string') && - typeof confirmedAt === 'number' - ) -} - -function readLegacyBindings(now: number): PersistedBindings { +function readLegacyBindings(now: number): PersistedAgentWorkflowTabBindings { try { const parsed: unknown = JSON.parse( localStorage.getItem(LEGACY_STORAGE_KEY) ?? 'null' @@ -52,35 +40,6 @@ function readLegacyBindings(now: number): PersistedBindings { } } -function liveBindings( - bindings: Record, - now: number -): PersistedBindings { - return Object.fromEntries( - Object.entries(bindings).filter( - (entry): entry is [string, PersistedBinding] => - isPersistedBinding(entry[1]) && - entry[1].confirmedAt + BINDING_TTL_MS >= now - ) - ) -} - -export function readPersistedAgentWorkflowTabPath( - raw: string | null, - workflowId: string, - now = Date.now() -): string | undefined { - if (raw === null) return undefined - try { - const parsed: unknown = JSON.parse(raw) - if (typeof parsed !== 'object' || parsed === null) return undefined - return liveBindings(parsed as Record, now)[workflowId] - ?.tabPath - } catch { - return undefined - } -} - function graphIdOf(tab: ComfyWorkflow): string | undefined { const activeId = tab.activeState?.id if (activeId !== undefined) return activeId @@ -104,11 +63,11 @@ export const useAgentWorkflowTabBindingStore = defineStore( const now = Date.now() const hasStoredBindings = localStorage.getItem(AGENT_WORKFLOW_TAB_BINDINGS_STORAGE_KEY) !== null - const tabByWorkflow = useLocalStorage( + const tabByWorkflow = useLocalStorage( AGENT_WORKFLOW_TAB_BINDINGS_STORAGE_KEY, {} ) - tabByWorkflow.value = liveBindings( + tabByWorkflow.value = liveAgentWorkflowTabBindings( hasStoredBindings ? tabByWorkflow.value : readLegacyBindings(now), now ) @@ -117,7 +76,9 @@ export const useAgentWorkflowTabBindingStore = defineStore( const boundInstances = new Map() const refusedInstances = new Map() - function recordFor(workflowId: string): PersistedBinding | undefined { + function recordFor( + workflowId: string + ): PersistedAgentWorkflowTabBinding | undefined { return Object.hasOwn(tabByWorkflow.value, workflowId) ? tabByWorkflow.value[workflowId] : undefined @@ -139,7 +100,7 @@ export const useAgentWorkflowTabBindingStore = defineStore( // by being saved in place at the record's path. function claimable( workflowId: string, - record: PersistedBinding, + record: PersistedAgentWorkflowTabBinding, tab: ComfyWorkflow ): boolean { if (refusedInstances.get(workflowId) === toRaw(tab)) return false @@ -151,7 +112,7 @@ export const useAgentWorkflowTabBindingStore = defineStore( function blockedByOccupant( workflowId: string, - record: PersistedBinding + record: PersistedAgentWorkflowTabBinding ): boolean { const occupant = workflows.openWorkflows.find( (tab) => tab.path === record.tabPath From 8c01607a56df3013b3bb402d14d20fbfa85aeea0 Mon Sep 17 00:00:00 2001 From: GitHub Action Date: Mon, 21 Sep 2026 10:11:12 +0000 Subject: [PATCH 24/48] [automated] Apply ESLint and Oxfmt fixes --- .../agent/stores/agent/agentWorkflowTabBindingStorage.ts | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/src/workbench/extensions/agent/stores/agent/agentWorkflowTabBindingStorage.ts b/src/workbench/extensions/agent/stores/agent/agentWorkflowTabBindingStorage.ts index 7568f0f187b..0204826eb48 100644 --- a/src/workbench/extensions/agent/stores/agent/agentWorkflowTabBindingStorage.ts +++ b/src/workbench/extensions/agent/stores/agent/agentWorkflowTabBindingStorage.ts @@ -48,10 +48,9 @@ export function readPersistedAgentWorkflowTabPath( try { const parsed: unknown = JSON.parse(raw) if (typeof parsed !== 'object' || parsed === null) return undefined - return liveAgentWorkflowTabBindings( - parsed as Record, - now - )[workflowId]?.tabPath + return liveAgentWorkflowTabBindings(parsed as Record, now)[ + workflowId + ]?.tabPath } catch { return undefined } From 69016386e0df76c02be50a16eecdda11a99a8072 Mon Sep 17 00:00:00 2001 From: Christian Byrne Date: Mon, 21 Sep 2026 03:36:42 -0700 Subject: [PATCH 25/48] fix(agent): preserve follower identity while inactive Keep the CRDT document identity stable across background-tab suspension so pending human-operation suppression survives reactivation. Only treat an uninitialized target as reload-restorable when a persisted document actually exists, and let the saved-reload fixture acknowledge its pre-reload human edit.\n\nFailed job: https://github.com/Comfy-Org/ComfyUI_frontend/actions/runs/35587573197/job/106295656850 --- .../agent/agentFollowerReloadBinding.spec.ts | 5 ++- .../extensions/agent/AgentPanelRoot.vue | 32 +++++++++++-------- 2 files changed, 23 insertions(+), 14 deletions(-) diff --git a/browser_tests/tests/agent/agentFollowerReloadBinding.spec.ts b/browser_tests/tests/agent/agentFollowerReloadBinding.spec.ts index 858c35c3b16..b6afc73b5ee 100644 --- a/browser_tests/tests/agent/agentFollowerReloadBinding.spec.ts +++ b/browser_tests/tests/agent/agentFollowerReloadBinding.spec.ts @@ -13,7 +13,10 @@ test.describe( 'Agent saved-workflow reattachment', { tag: ['@cloud', '@agent', '@vue-nodes'] }, () => { - test.use({ conversationCase: 'agent-rec-set-widget-existing' }) + test.use({ + conversationCase: 'agent-rec-set-widget-existing', + humanOpsHost: 'apply' + }) test.beforeEach(async ({ page }) => { const folders: ModelFolderInfo[] = [] diff --git a/src/workbench/extensions/agent/AgentPanelRoot.vue b/src/workbench/extensions/agent/AgentPanelRoot.vue index fb2b31b28e5..32986a9fee0 100644 --- a/src/workbench/extensions/agent/AgentPanelRoot.vue +++ b/src/workbench/extensions/agent/AgentPanelRoot.vue @@ -454,10 +454,12 @@ watch( ) const newChatDetached = ref(false) +const restorableDocId = ref(reconcilePersistedDocId()) const workflowDetached = computed( () => newChatDetached.value || - (selectedTarget.value === null && !agentPanelStore.canRestoreWorkflow) + (selectedTarget.value === null && + (!agentPanelStore.canRestoreWorkflow || restorableDocId.value === null)) ) watch(selectedTarget, (target) => { if (target !== null) newChatDetached.value = false @@ -611,9 +613,8 @@ const isSending = computed( // follower was about to read, and the cached value never invalidated when the // record lapsed. Resolve it at the explicit lifecycle points that used to drive // re-evaluation and let the getter read only reactive state. -const restorableDocId = ref(null) watch( - [workflowDetached, () => workflowStore.activeWorkflow, boundWorkflowId], + [() => workflowStore.activeWorkflow, boundWorkflowId], () => { restorableDocId.value = reconcilePersistedDocId() }, @@ -625,18 +626,22 @@ function restorableWorkflowIdFor(tabPath: string): string | null { if (persisted === undefined) return null return persisted === restorableDocId.value ? persisted : null } -const activeBoundWorkflowId = computed(() => { +const followerWorkflowId = computed(() => { if (workflowDetached.value) return null + if (boundWorkflowId.value !== null) return boundWorkflowId.value const active = workflowStore.activeWorkflow if (active === null) return null - const bound = boundWorkflowId.value ?? restorableWorkflowIdFor(active.path) - return bound !== null && boundOrOpenWorkflowFor(bound)?.path === active.path - ? bound - : null + return restorableWorkflowIdFor(active.path) +}) +const isBoundWorkflowActive = computed(() => { + const bound = followerWorkflowId.value + const active = workflowStore.activeWorkflow + return ( + bound !== null && + active !== null && + boundOrOpenWorkflowFor(bound)?.path === active.path + ) }) -const isBoundWorkflowActive = computed( - () => activeBoundWorkflowId.value !== null -) // The CRDT follower is the inbound content channel: subscribes to the // session's bound workflow while its tab is active. Suspending the background @@ -647,7 +652,7 @@ const { debugSnapshot: crdtDebugSnapshot, enqueueHumanOperations } = useAgentCrdtFollower( - activeBoundWorkflowId, + followerWorkflowId, graphMutations, () => resolvedUserInfo.value?.id ?? null, isBoundWorkflowActive, @@ -672,7 +677,7 @@ const mintPortWiring = attachMintPortWiring({ isEnabled: () => agentPanelStore.enabled, isDocBound: () => crdtStatus.value.connected && - crdtStatus.value.workflowId === activeBoundWorkflowId.value, + crdtStatus.value.workflowId === followerWorkflowId.value, enqueue: enqueueHumanOperations, layoutChanges: (listener) => layoutStore.onChange(listener), localActorPrefix: ACTOR_CONFIG.USER_PREFIX, @@ -1034,6 +1039,7 @@ function onNewChat(): void { composerStore.resetPromptHistory() // Ending the session also ends the document's claim on the graph. clearPersistedDocId() + restorableDocId.value = null newChatDetached.value = true // A new chat targets whatever tab is on screen right now, not the previous // chat's target - unlike onSelectHistory(), which resets to 'uninitialized' From f2ebb2212397321820c7544c6da686f86187f3b9 Mon Sep 17 00:00:00 2001 From: Christian Byrne Date: Mon, 21 Sep 2026 03:47:16 -0700 Subject: [PATCH 26/48] test(agent): rely on live edit after reload --- browser_tests/tests/agent/agentFollowerReloadBinding.spec.ts | 4 ---- 1 file changed, 4 deletions(-) diff --git a/browser_tests/tests/agent/agentFollowerReloadBinding.spec.ts b/browser_tests/tests/agent/agentFollowerReloadBinding.spec.ts index b6afc73b5ee..879a7fcf898 100644 --- a/browser_tests/tests/agent/agentFollowerReloadBinding.spec.ts +++ b/browser_tests/tests/agent/agentFollowerReloadBinding.spec.ts @@ -78,11 +78,7 @@ test.describe( await expect(picker).toHaveText('Reload reattachment') expect((await restoredContent).ok()).toBe(true) await expect(prompt).toHaveValue('saved before reload') - const before = agentConversation.subscribeCount() await agentConversation.sendPrompt() - await expect - .poll(() => agentConversation.subscribeCount()) - .toBeGreaterThan(before) // This value was never saved or recorded. Only the post-reload live // subscription can deliver it; a stale local canvas cannot satisfy it. From f6d98092dd4e1b89d3d7c1096917b1e35bd11d7d Mon Sep 17 00:00:00 2001 From: bymyself Date: Mon, 21 Sep 2026 18:12:26 -0700 Subject: [PATCH 27/48] fix(agent): close reload follower review gaps --- browser_tests/fixtures/agentPanelFixture.ts | 21 ++++++++++ .../tests/agent/agentCrdtReload.spec.ts | 40 +++++-------------- .../agent/crdt/agentCrdtDocLifecycle.test.ts | 14 +------ .../agent/crdt/persistedDocId.test.ts | 8 ++++ .../extensions/agent/crdt/persistedDocId.ts | 12 +++--- .../agent/crdt/useAgentCrdtFollower.ts | 5 +-- .../agentWorkflowTabBindingStorage.test.ts | 32 +++++++++++++++ .../agent/agentWorkflowTabBindingStorage.ts | 18 +++++---- 8 files changed, 92 insertions(+), 58 deletions(-) create mode 100644 src/workbench/extensions/agent/stores/agent/agentWorkflowTabBindingStorage.test.ts diff --git a/browser_tests/fixtures/agentPanelFixture.ts b/browser_tests/fixtures/agentPanelFixture.ts index 4f80deb0331..55d374ebd30 100644 --- a/browser_tests/fixtures/agentPanelFixture.ts +++ b/browser_tests/fixtures/agentPanelFixture.ts @@ -11,6 +11,7 @@ import type { import type { RemoteConfig } from '@/platform/remoteConfig/types' import type { UserDataFullInfo } from '@/platform/remote/comfyui/types' import { AGENT_CONSENT_SETTING_ID } from '@/platform/settings/constants/agent' +import { AGENT_CRDT_DOC_ID_SESSION_KEY } from '@/platform/workflow/persistence/base/storageKeyConstants' import type { ComfyNodeDef } from '@/schemas/nodeDefSchema' import type { AgentTurnAccepted, @@ -200,6 +201,26 @@ export async function getAgentActiveWorkflowPath( ) } +export async function readPersistedAgentDocIdentity(page: Page) { + const raw = await page.evaluate( + (key) => sessionStorage.getItem(key), + AGENT_CRDT_DOC_ID_SESSION_KEY + ) + if (raw === null) throw new Error('Persisted CRDT document record is missing') + const parsed: unknown = JSON.parse(raw) + if ( + typeof parsed !== 'object' || + parsed === null || + !('docId' in parsed) || + typeof parsed.docId !== 'string' || + !('nonce' in parsed) || + typeof parsed.nonce !== 'string' + ) { + throw new Error('Persisted CRDT document record is malformed') + } + return { docId: parsed.docId, nonce: parsed.nonce } +} + export async function bootAgentApp( page: Page, agentFlag: boolean, diff --git a/browser_tests/tests/agent/agentCrdtReload.spec.ts b/browser_tests/tests/agent/agentCrdtReload.spec.ts index 99938a93693..e95f1d3ab1c 100644 --- a/browser_tests/tests/agent/agentCrdtReload.spec.ts +++ b/browser_tests/tests/agent/agentCrdtReload.spec.ts @@ -1,5 +1,4 @@ import { expect, mergeTests } from '@playwright/test' -import type { Page } from '@playwright/test' import { AGENT_CRDT_DOC_ID_SESSION_KEY } from '@/platform/workflow/persistence/base/storageKeyConstants' import { @@ -10,43 +9,18 @@ import { agentTest, bootAgentApp, getAgentActiveWorkflowPath, - pushAgentEvent + pushAgentEvent, + readPersistedAgentDocIdentity } from '@e2e/fixtures/agentPanelFixture' import { waitForCloudApp } from '@e2e/fixtures/cloudAppFixture' import { AgentPanel } from '@e2e/fixtures/components/AgentPanel' +import { Topbar } from '@e2e/fixtures/components/Topbar' import { CommandHelper } from '@e2e/fixtures/helpers/CommandHelper' import { jsonRoute } from '@e2e/fixtures/utils/jsonRoute' import { countDocFrames, webSocketFixture } from '@e2e/fixtures/ws' const test = mergeTests(agentTest, webSocketFixture) -interface PersistedDocIdentity { - docId: string - nonce: string -} - -async function readPersistedDocIdentity( - page: Page -): Promise { - const raw = await page.evaluate( - (key) => sessionStorage.getItem(key), - AGENT_CRDT_DOC_ID_SESSION_KEY - ) - if (raw === null) throw new Error('Persisted CRDT document record is missing') - const parsed: unknown = JSON.parse(raw) - if ( - typeof parsed !== 'object' || - parsed === null || - !('docId' in parsed) || - typeof parsed.docId !== 'string' || - !('nonce' in parsed) || - typeof parsed.nonce !== 'string' - ) { - throw new Error('Persisted CRDT document record is malformed') - } - return { docId: parsed.docId, nonce: parsed.nonce } -} - test.describe('Agent CRDT reload', { tag: '@cloud' }, () => { test.use({ connectWebSocketToServer: false }) @@ -61,6 +35,7 @@ test.describe('Agent CRDT reload', { tag: '@cloud' }, () => { const workflowId = 'a81718a4-02ae-41e6-ae85-c33b7bb880f6' const agentPanel = new AgentPanel(page) const command = new CommandHelper(page) + const topbar = new Topbar(page) await page.route('**/api/internal/cloud_analytics', (route) => route.fulfill(jsonRoute({})) @@ -113,7 +88,7 @@ test.describe('Agent CRDT reload', { tag: '@cloud' }, () => { ) ) .not.toBeNull() - const recordBeforeReload = await readPersistedDocIdentity(page) + const recordBeforeReload = await readPersistedAgentDocIdentity(page) expect(recordBeforeReload).toMatchObject({ docId: workflowId }) const rawBindings = await page.evaluate( @@ -166,7 +141,7 @@ test.describe('Agent CRDT reload', { tag: '@cloud' }, () => { // record and the rebound tab are the two preconditions for resubscribing; // if either is wrong the subscribe assertion below is a downstream // symptom, and if both hold then the gap is in the follower bind itself. - const record = await readPersistedDocIdentity(page) + const record = await readPersistedAgentDocIdentity(page) expect(record).toMatchObject({ docId: workflowId }) expect(record.nonce).not.toBe(recordBeforeReload.nonce) await expect.poll(() => getAgentActiveWorkflowPath(page)).toBe(boundPath) @@ -178,6 +153,9 @@ test.describe('Agent CRDT reload', { tag: '@cloud' }, () => { expect(countAfterReload('doc_unsubscribe')).toBe(0) await command.executeCommand('Comfy.NewBlankWorkflow') await expect.poll(() => countAfterReload('doc_unsubscribe')).toBe(1) + + await topbar.getTab(0).click() + await expect.poll(() => countAfterReload('doc_subscribe')).toBe(2) }) }) }) diff --git a/src/workbench/extensions/agent/crdt/agentCrdtDocLifecycle.test.ts b/src/workbench/extensions/agent/crdt/agentCrdtDocLifecycle.test.ts index e2e124dcbd6..92b4f5f9cf1 100644 --- a/src/workbench/extensions/agent/crdt/agentCrdtDocLifecycle.test.ts +++ b/src/workbench/extensions/agent/crdt/agentCrdtDocLifecycle.test.ts @@ -1,3 +1,4 @@ +import { fromPartial } from '@total-typescript/shoehorn' import { beforeEach, describe, expect, it, vi } from 'vitest' import { reportError } from '@/platform/telemetry/reportError' @@ -347,17 +348,6 @@ describe('AgentCrdtDocLifecycle ack timeout', () => { }) }) -/** - * FE-1969 regression. This file used to carry its OWN copy of the persisted - * doc-id record — same `Comfy.Agent.CrdtDocId` key, but a second module-scope - * page-load nonce. Two owners on one key can never agree: whichever module - * wrote last left the other's reader looking at a foreign nonce, so - * `readPersistedDocId()` answered "nothing persisted" for the rest of the page - * load. On a reload that is exactly the failing path — `useAgentDockMount` - * reconciles the record through `persistedDocId.ts` and re-stamps it with that - * module's nonce, then the follower's initial bind asks the lifecycle, gets - * `null`, clears the record and never resubscribes. - */ describe('AgentCrdtDocLifecycle persisted doc id', () => { beforeEach(() => { sessionStorage.clear() @@ -382,7 +372,7 @@ describe('AgentCrdtDocLifecycle persisted doc id', () => { }) ) vi.spyOn(performance, 'getEntriesByType').mockReturnValue([ - { type: 'reload' } as PerformanceNavigationTiming + fromPartial({ type: 'reload' }) ]) // What useAgentDockMount does before the follower ever binds. expect(reconcilePersistedDocId()).toBe(WORKFLOW_ID) diff --git a/src/workbench/extensions/agent/crdt/persistedDocId.test.ts b/src/workbench/extensions/agent/crdt/persistedDocId.test.ts index e75614330d6..07c770d2141 100644 --- a/src/workbench/extensions/agent/crdt/persistedDocId.test.ts +++ b/src/workbench/extensions/agent/crdt/persistedDocId.test.ts @@ -81,6 +81,14 @@ describe('persistedDocId', () => { expect(rawRecord()).toBeNull() }) + it('drops a record whose expiry exceeds the five-minute bound', () => { + writeForeignRecord('wf-1', Date.now() + DOC_ID_TTL_MS + 1) + asReloadNavigation() + + expect(reconcilePersistedDocId()).toBeNull() + expect(rawRecord()).toBeNull() + }) + it('drops a pre-FEC-5 bare doc id, which is not valid JSON', () => { sessionStorage.setItem(DOC_ID_SESSION_KEY, 'wf-legacy') diff --git a/src/workbench/extensions/agent/crdt/persistedDocId.ts b/src/workbench/extensions/agent/crdt/persistedDocId.ts index 182528d5a2b..db25abf8f0a 100644 --- a/src/workbench/extensions/agent/crdt/persistedDocId.ts +++ b/src/workbench/extensions/agent/crdt/persistedDocId.ts @@ -93,7 +93,11 @@ export function reconcilePersistedDocId(): string | null { nonce: parsed.nonce, expiresAt: parsed.expiresAt } - if (Date.now() >= record.expiresAt) { + const now = Date.now() + if ( + now >= record.expiresAt || + record.expiresAt > now + DOC_ID_TTL_MS + ) { clearPersistedDocId() return null } @@ -102,10 +106,8 @@ export function reconcilePersistedDocId(): string | null { clearPersistedDocId() return null } - // Adoption renews the owner, never the lifetime. Re-stamping a full TTL - // here would let a tab reloaded inside the window keep an arbitrarily old - // doc id rebindable forever, removing the only bound the TTL places on - // the same-page-load workflow-switch case. + // Adoption preserves the original expiry, so reloads cannot extend the + // fallback window. writeRecord({ docId: record.docId, nonce: currentPageSessionNonce(), diff --git a/src/workbench/extensions/agent/crdt/useAgentCrdtFollower.ts b/src/workbench/extensions/agent/crdt/useAgentCrdtFollower.ts index 26afb42a770..6df88d12658 100644 --- a/src/workbench/extensions/agent/crdt/useAgentCrdtFollower.ts +++ b/src/workbench/extensions/agent/crdt/useAgentCrdtFollower.ts @@ -287,9 +287,8 @@ function startAgentCrdtFollower( const lifecycle = new AgentCrdtDocLifecycle( () => subscribedWorkflowId.value, () => bridge.resubscribe(), - // main's `onGaveUp` cleared a `connected` ref. Connection is derived from - // the acknowledgement here, so dropping the acknowledgement is the same - // signal: a subscribe the retry loop gave up on was never confirmed. + // Exhausting the retry budget drops the acknowledged binding, so derived + // connection status becomes false. () => { acknowledgedWorkflowId.value = null } diff --git a/src/workbench/extensions/agent/stores/agent/agentWorkflowTabBindingStorage.test.ts b/src/workbench/extensions/agent/stores/agent/agentWorkflowTabBindingStorage.test.ts new file mode 100644 index 00000000000..19dfcc39a28 --- /dev/null +++ b/src/workbench/extensions/agent/stores/agent/agentWorkflowTabBindingStorage.test.ts @@ -0,0 +1,32 @@ +import { describe, expect, it } from 'vitest' + +import { liveAgentWorkflowTabBindings } from './agentWorkflowTabBindingStorage' + +describe('liveAgentWorkflowTabBindings', () => { + const now = Date.UTC(2026, 8, 22) + const binding = { + tabPath: 'workflows/example.json', + graphId: 'graph-1' + } + + it.each([ + ['a future timestamp', now + 1], + ['a non-finite timestamp', Number.POSITIVE_INFINITY], + ['an expired timestamp', now - 30 * 24 * 60 * 60 * 1000 - 1] + ])('rejects %s', (_label, confirmedAt) => { + expect( + liveAgentWorkflowTabBindings( + { workflow: { ...binding, confirmedAt } }, + now + ) + ).toEqual({}) + }) + + it('keeps a finite timestamp within the retention window', () => { + const record = { ...binding, confirmedAt: now } + + expect(liveAgentWorkflowTabBindings({ workflow: record }, now)).toEqual({ + workflow: record + }) + }) +}) diff --git a/src/workbench/extensions/agent/stores/agent/agentWorkflowTabBindingStorage.ts b/src/workbench/extensions/agent/stores/agent/agentWorkflowTabBindingStorage.ts index 0204826eb48..bc63b10e1bd 100644 --- a/src/workbench/extensions/agent/stores/agent/agentWorkflowTabBindingStorage.ts +++ b/src/workbench/extensions/agent/stores/agent/agentWorkflowTabBindingStorage.ts @@ -14,15 +14,20 @@ export type PersistedAgentWorkflowTabBindings = Record< PersistedAgentWorkflowTabBinding > +function isRecord(value: unknown): value is Record { + return typeof value === 'object' && value !== null +} + function isPersistedBinding( value: unknown ): value is PersistedAgentWorkflowTabBinding { - if (typeof value !== 'object' || value === null) return false - const { tabPath, graphId, confirmedAt } = value as Record + if (!isRecord(value)) return false + const { tabPath, graphId, confirmedAt } = value return ( typeof tabPath === 'string' && (graphId === null || typeof graphId === 'string') && - typeof confirmedAt === 'number' + typeof confirmedAt === 'number' && + Number.isFinite(confirmedAt) ) } @@ -34,6 +39,7 @@ export function liveAgentWorkflowTabBindings( Object.entries(bindings).filter( (entry): entry is [string, PersistedAgentWorkflowTabBinding] => isPersistedBinding(entry[1]) && + entry[1].confirmedAt <= now && entry[1].confirmedAt + BINDING_TTL_MS >= now ) ) @@ -47,10 +53,8 @@ export function readPersistedAgentWorkflowTabPath( if (raw === null) return undefined try { const parsed: unknown = JSON.parse(raw) - if (typeof parsed !== 'object' || parsed === null) return undefined - return liveAgentWorkflowTabBindings(parsed as Record, now)[ - workflowId - ]?.tabPath + if (!isRecord(parsed)) return undefined + return liveAgentWorkflowTabBindings(parsed, now)[workflowId]?.tabPath } catch { return undefined } From 8e82e681048060e1c990a0723ce5bfe1e3f1fd52 Mon Sep 17 00:00:00 2001 From: Amp Date: Tue, 22 Sep 2026 01:51:36 +0000 Subject: [PATCH 28/48] fix(agent): address reload follower review findings Amp-Thread-ID: https://ampcode.com/threads/T-01a06e6e-17f3-75b9-8543-a8a90cc4479d --- browser_tests/fixtures/agentPanelFixture.ts | 20 ++++++++++++ .../fixtures/utils/countDocFrames.test.ts | 31 +++++++++++++++++++ .../fixtures/utils/countDocFrames.ts | 31 +++++++++++++++++++ browser_tests/fixtures/ws.ts | 19 ------------ .../tests/agent/agentCrdtReload.spec.ts | 26 +++++++++++----- .../agent/crdt/persistedDocId.test.ts | 14 ++++++++- .../extensions/agent/crdt/persistedDocId.ts | 3 +- .../agent/crdt/useAgentCrdtFollower.ts | 1 - .../extensions/agent/persistenceTime.ts | 1 + .../agentWorkflowTabBindingStorage.test.ts | 29 ++++++++++++++--- .../agent/agentWorkflowTabBindingStorage.ts | 4 ++- 11 files changed, 143 insertions(+), 36 deletions(-) create mode 100644 browser_tests/fixtures/utils/countDocFrames.test.ts create mode 100644 browser_tests/fixtures/utils/countDocFrames.ts create mode 100644 src/workbench/extensions/agent/persistenceTime.ts diff --git a/browser_tests/fixtures/agentPanelFixture.ts b/browser_tests/fixtures/agentPanelFixture.ts index 55d374ebd30..c7f9ce8eb27 100644 --- a/browser_tests/fixtures/agentPanelFixture.ts +++ b/browser_tests/fixtures/agentPanelFixture.ts @@ -1,3 +1,4 @@ +import { expect } from '@playwright/test' import type { Page, Route, WebSocketRoute } from '@playwright/test' import type { @@ -19,6 +20,7 @@ import type { } from '@/workbench/extensions/agent/schemas/agentApiSchema' import { cloudAppFixture, waitForCloudApp } from '@e2e/fixtures/cloudAppFixture' +import { Topbar } from '@e2e/fixtures/components/Topbar' import { mockBilling } from '@e2e/fixtures/utils/cloudBillingMocks' import { bootCloud, mockCloudBoot } from '@e2e/fixtures/utils/cloudBootMocks' import { jsonRoute } from '@e2e/fixtures/utils/jsonRoute' @@ -201,6 +203,24 @@ export async function getAgentActiveWorkflowPath( ) } +export async function switchToAgentWorkflowTab( + page: Page, + tabPath: string +): Promise { + const tabIndex = await page.evaluate( + (path) => + ( + window.app!.extensionManager as WorkspaceStore + ).workflow.openWorkflows.findIndex((workflow) => workflow.path === path), + tabPath + ) + if (tabIndex < 0) throw new Error(`Workflow tab is not open: ${tabPath}`) + const tab = new Topbar(page).getTab(tabIndex) + await tab.click() + await expect(tab).toHaveClass(/p-togglebutton-checked/) + await expect.poll(() => getAgentActiveWorkflowPath(page)).toBe(tabPath) +} + export async function readPersistedAgentDocIdentity(page: Page) { const raw = await page.evaluate( (key) => sessionStorage.getItem(key), diff --git a/browser_tests/fixtures/utils/countDocFrames.test.ts b/browser_tests/fixtures/utils/countDocFrames.test.ts new file mode 100644 index 00000000000..aea73aff7bf --- /dev/null +++ b/browser_tests/fixtures/utils/countDocFrames.test.ts @@ -0,0 +1,31 @@ +import { fromPartial } from '@total-typescript/shoehorn' +import type { WebSocketRoute } from '@playwright/test' +import { describe, expect, it } from 'vitest' + +import { countDocFrames } from '@e2e/fixtures/utils/countDocFrames' + +describe('countDocFrames', () => { + it('ignores unrelated and malformed socket messages', () => { + const ws = fromPartial({}) + const messages = new Map([ + [ + ws, + [ + 'not-json', + JSON.stringify({ type: 'status' }), + JSON.stringify({ type: 'doc_subscribe', data: null }), + JSON.stringify({ + type: 'doc_subscribe', + data: { workflow_id: 'other-workflow' } + }), + JSON.stringify({ + type: 'doc_subscribe', + data: { workflow_id: 'workflow-1' } + }) + ] + ] + ]) + + expect(countDocFrames(messages, ws, 'doc_subscribe', 'workflow-1')).toBe(1) + }) +}) diff --git a/browser_tests/fixtures/utils/countDocFrames.ts b/browser_tests/fixtures/utils/countDocFrames.ts new file mode 100644 index 00000000000..5c7c38ffd92 --- /dev/null +++ b/browser_tests/fixtures/utils/countDocFrames.ts @@ -0,0 +1,31 @@ +import type { WebSocketRoute } from '@playwright/test' + +type SubscriptionFrameType = 'doc_subscribe' | 'doc_unsubscribe' + +function isMatchingSubscriptionFrame( + message: string, + type: SubscriptionFrameType, + workflowId: string +): boolean { + try { + const frame: unknown = JSON.parse(message) + if (typeof frame !== 'object' || frame === null) return false + if (!('type' in frame) || frame.type !== type) return false + if (!('data' in frame) || typeof frame.data !== 'object' || !frame.data) + return false + return 'workflow_id' in frame.data && frame.data.workflow_id === workflowId + } catch { + return false + } +} + +export function countDocFrames( + messagesBySocket: Map, + ws: WebSocketRoute, + type: SubscriptionFrameType, + workflowId: string +): number { + return (messagesBySocket.get(ws) ?? []).filter((message) => + isMatchingSubscriptionFrame(message, type, workflowId) + ).length +} diff --git a/browser_tests/fixtures/ws.ts b/browser_tests/fixtures/ws.ts index 8c9bda0dbed..a7e64165b8d 100644 --- a/browser_tests/fixtures/ws.ts +++ b/browser_tests/fixtures/ws.ts @@ -1,25 +1,6 @@ import { networkIsolationFixture as base } from '@e2e/fixtures/networkIsolationFixture' import type { WebSocketRoute } from '@playwright/test' -import type { ClientDocFrame } from '@/workbench/extensions/agent/crdt/docFrameClient' - -type SubscriptionFrame = Extract< - ClientDocFrame, - { type: 'doc_subscribe' | 'doc_unsubscribe' } -> - -export function countDocFrames( - messagesBySocket: Map, - ws: WebSocketRoute, - type: SubscriptionFrame['type'], - workflowId: string -): number { - return (messagesBySocket.get(ws) ?? []).filter((message) => { - const frame = JSON.parse(message) as ClientDocFrame - return frame.type === type && frame.data.workflow_id === workflowId - }).length -} - /** * The `/ws` connections the page opens, in order. A reconnect routes a second * time, so a test that drops the socket needs the route the client opened diff --git a/browser_tests/tests/agent/agentCrdtReload.spec.ts b/browser_tests/tests/agent/agentCrdtReload.spec.ts index e95f1d3ab1c..466c83e73c8 100644 --- a/browser_tests/tests/agent/agentCrdtReload.spec.ts +++ b/browser_tests/tests/agent/agentCrdtReload.spec.ts @@ -10,14 +10,15 @@ import { bootAgentApp, getAgentActiveWorkflowPath, pushAgentEvent, - readPersistedAgentDocIdentity + readPersistedAgentDocIdentity, + switchToAgentWorkflowTab } from '@e2e/fixtures/agentPanelFixture' import { waitForCloudApp } from '@e2e/fixtures/cloudAppFixture' import { AgentPanel } from '@e2e/fixtures/components/AgentPanel' -import { Topbar } from '@e2e/fixtures/components/Topbar' import { CommandHelper } from '@e2e/fixtures/helpers/CommandHelper' +import { countDocFrames } from '@e2e/fixtures/utils/countDocFrames' import { jsonRoute } from '@e2e/fixtures/utils/jsonRoute' -import { countDocFrames, webSocketFixture } from '@e2e/fixtures/ws' +import { webSocketFixture } from '@e2e/fixtures/ws' const test = mergeTests(agentTest, webSocketFixture) @@ -35,7 +36,6 @@ test.describe('Agent CRDT reload', { tag: '@cloud' }, () => { const workflowId = 'a81718a4-02ae-41e6-ae85-c33b7bb880f6' const agentPanel = new AgentPanel(page) const command = new CommandHelper(page) - const topbar = new Topbar(page) await page.route('**/api/internal/cloud_analytics', (route) => route.fulfill(jsonRoute({})) @@ -96,7 +96,7 @@ test.describe('Agent CRDT reload', { tag: '@cloud' }, () => { AGENT_WORKFLOW_TAB_BINDINGS_STORAGE_KEY ) const boundPath = readPersistedAgentWorkflowTabPath(rawBindings, workflowId) - expect(boundPath).toBeTruthy() + if (!boundPath) throw new Error('Persisted workflow tab binding is missing') await expect.poll(() => getAgentActiveWorkflowPath(page)).toBe(boundPath) expect( await page.evaluate(() => localStorage.getItem('Comfy.Agent.ThreadId')) @@ -147,15 +147,25 @@ test.describe('Agent CRDT reload', { tag: '@cloud' }, () => { await expect.poll(() => getAgentActiveWorkflowPath(page)).toBe(boundPath) await expect.poll(() => countAfterReload('doc_subscribe')).toBe(1) + + reloadedWs.send( + JSON.stringify({ + type: 'doc_subscribed', + data: { v: 1, workflow_id: workflowId, ok: true, seq: 0 } + }) + ) }) - await test.step('Opening a blank workflow suspends the restored follower', async () => { + await test.step('Switching away suspends the follower and returning resumes it', async () => { expect(countAfterReload('doc_unsubscribe')).toBe(0) await command.executeCommand('Comfy.NewBlankWorkflow') await expect.poll(() => countAfterReload('doc_unsubscribe')).toBe(1) + const subscribeCountBeforeResume = countAfterReload('doc_subscribe') - await topbar.getTab(0).click() - await expect.poll(() => countAfterReload('doc_subscribe')).toBe(2) + await switchToAgentWorkflowTab(page, boundPath) + await expect + .poll(() => countAfterReload('doc_subscribe')) + .toBe(subscribeCountBeforeResume + 1) }) }) }) diff --git a/src/workbench/extensions/agent/crdt/persistedDocId.test.ts b/src/workbench/extensions/agent/crdt/persistedDocId.test.ts index 07c770d2141..b25b9ac01b2 100644 --- a/src/workbench/extensions/agent/crdt/persistedDocId.test.ts +++ b/src/workbench/extensions/agent/crdt/persistedDocId.test.ts @@ -5,6 +5,7 @@ import { clearAllWorkflowStorage, clearWorkflowRestoreState } from '@/platform/workflow/persistence/base/storageIO' +import { MAX_AGENT_STORAGE_CLOCK_SKEW_MS } from '@/workbench/extensions/agent/persistenceTime' import { DOC_ID_SESSION_KEY, @@ -82,7 +83,10 @@ describe('persistedDocId', () => { }) it('drops a record whose expiry exceeds the five-minute bound', () => { - writeForeignRecord('wf-1', Date.now() + DOC_ID_TTL_MS + 1) + writeForeignRecord( + 'wf-1', + Date.now() + DOC_ID_TTL_MS + MAX_AGENT_STORAGE_CLOCK_SKEW_MS + 1_000 + ) asReloadNavigation() expect(reconcilePersistedDocId()).toBeNull() @@ -105,6 +109,14 @@ describe('persistedDocId', () => { }) describe('reload adoption', () => { + it('keeps a fresh record after a small backward clock adjustment', () => { + vi.useFakeTimers() + persistDocId('wf-1') + vi.setSystemTime(Date.now() - 60_000) + + expect(reconcilePersistedDocId()).toBe('wf-1') + }) + it('adopts an inherited record and takes ownership of it', () => { const expiresAt = Date.now() + DOC_ID_TTL_MS writeForeignRecord('wf-1', expiresAt) diff --git a/src/workbench/extensions/agent/crdt/persistedDocId.ts b/src/workbench/extensions/agent/crdt/persistedDocId.ts index db25abf8f0a..5ae96275c39 100644 --- a/src/workbench/extensions/agent/crdt/persistedDocId.ts +++ b/src/workbench/extensions/agent/crdt/persistedDocId.ts @@ -1,5 +1,6 @@ import { createUuidv4 } from '@/utils/uuid' import { AGENT_CRDT_DOC_ID_SESSION_KEY } from '@/platform/workflow/persistence/base/storageKeyConstants' +import { MAX_AGENT_STORAGE_CLOCK_SKEW_MS } from '@/workbench/extensions/agent/persistenceTime' // FE-1902: the doc id is otherwise held only in memory (set on turn ack), so a // panel remount or reload loses the binding until the next turn ack. Persist it @@ -96,7 +97,7 @@ export function reconcilePersistedDocId(): string | null { const now = Date.now() if ( now >= record.expiresAt || - record.expiresAt > now + DOC_ID_TTL_MS + record.expiresAt > now + DOC_ID_TTL_MS + MAX_AGENT_STORAGE_CLOCK_SKEW_MS ) { clearPersistedDocId() return null diff --git a/src/workbench/extensions/agent/crdt/useAgentCrdtFollower.ts b/src/workbench/extensions/agent/crdt/useAgentCrdtFollower.ts index 6df88d12658..ddd98d88188 100644 --- a/src/workbench/extensions/agent/crdt/useAgentCrdtFollower.ts +++ b/src/workbench/extensions/agent/crdt/useAgentCrdtFollower.ts @@ -785,7 +785,6 @@ function startAgentCrdtFollower( return { status: readonly(status), debugSnapshot, - acknowledgedWorkflowId: readonly(acknowledgedWorkflowId), enqueueHumanOperations: (operations: GraphOperation[]) => coalescer.enqueue(operations) } diff --git a/src/workbench/extensions/agent/persistenceTime.ts b/src/workbench/extensions/agent/persistenceTime.ts new file mode 100644 index 00000000000..b1a5a812883 --- /dev/null +++ b/src/workbench/extensions/agent/persistenceTime.ts @@ -0,0 +1 @@ +export const MAX_AGENT_STORAGE_CLOCK_SKEW_MS = 5 * 60 * 1000 diff --git a/src/workbench/extensions/agent/stores/agent/agentWorkflowTabBindingStorage.test.ts b/src/workbench/extensions/agent/stores/agent/agentWorkflowTabBindingStorage.test.ts index 19dfcc39a28..06d5d836ed5 100644 --- a/src/workbench/extensions/agent/stores/agent/agentWorkflowTabBindingStorage.test.ts +++ b/src/workbench/extensions/agent/stores/agent/agentWorkflowTabBindingStorage.test.ts @@ -1,5 +1,7 @@ import { describe, expect, it } from 'vitest' +import { MAX_AGENT_STORAGE_CLOCK_SKEW_MS } from '@/workbench/extensions/agent/persistenceTime' + import { liveAgentWorkflowTabBindings } from './agentWorkflowTabBindingStorage' describe('liveAgentWorkflowTabBindings', () => { @@ -9,11 +11,20 @@ describe('liveAgentWorkflowTabBindings', () => { graphId: 'graph-1' } - it.each([ - ['a future timestamp', now + 1], - ['a non-finite timestamp', Number.POSITIVE_INFINITY], - ['an expired timestamp', now - 30 * 24 * 60 * 60 * 1000 - 1] - ])('rejects %s', (_label, confirmedAt) => { + it.for([ + { + label: 'a timestamp beyond the clock-skew tolerance', + confirmedAt: now + MAX_AGENT_STORAGE_CLOCK_SKEW_MS + 1 + }, + { + label: 'a non-finite timestamp', + confirmedAt: Number.POSITIVE_INFINITY + }, + { + label: 'an expired timestamp', + confirmedAt: now - 30 * 24 * 60 * 60 * 1000 - 1 + } + ])('rejects $label', ({ confirmedAt }) => { expect( liveAgentWorkflowTabBindings( { workflow: { ...binding, confirmedAt } }, @@ -29,4 +40,12 @@ describe('liveAgentWorkflowTabBindings', () => { workflow: record }) }) + + it('keeps a fresh binding after a small backward clock adjustment', () => { + const record = { ...binding, confirmedAt: now } + + expect( + liveAgentWorkflowTabBindings({ workflow: record }, now - 60_000) + ).toEqual({ workflow: record }) + }) }) diff --git a/src/workbench/extensions/agent/stores/agent/agentWorkflowTabBindingStorage.ts b/src/workbench/extensions/agent/stores/agent/agentWorkflowTabBindingStorage.ts index bc63b10e1bd..21a58fa66d0 100644 --- a/src/workbench/extensions/agent/stores/agent/agentWorkflowTabBindingStorage.ts +++ b/src/workbench/extensions/agent/stores/agent/agentWorkflowTabBindingStorage.ts @@ -1,3 +1,5 @@ +import { MAX_AGENT_STORAGE_CLOCK_SKEW_MS } from '@/workbench/extensions/agent/persistenceTime' + export const AGENT_WORKFLOW_TAB_BINDINGS_STORAGE_KEY = 'Comfy.Agent.WorkflowTabBindings.v2' @@ -39,7 +41,7 @@ export function liveAgentWorkflowTabBindings( Object.entries(bindings).filter( (entry): entry is [string, PersistedAgentWorkflowTabBinding] => isPersistedBinding(entry[1]) && - entry[1].confirmedAt <= now && + entry[1].confirmedAt <= now + MAX_AGENT_STORAGE_CLOCK_SKEW_MS && entry[1].confirmedAt + BINDING_TTL_MS >= now ) ) From ee6c2d61e29df3c92e1866221cf8a592d46bde58 Mon Sep 17 00:00:00 2001 From: bymyself Date: Mon, 21 Sep 2026 21:42:03 -0700 Subject: [PATCH 29/48] refactor(agent): reduce workflow restore complexity --- .../fixtures/utils/countDocFrames.ts | 24 ++-- .../extensions/agent/AgentPanelRoot.vue | 111 ++++++++++-------- 2 files changed, 78 insertions(+), 57 deletions(-) diff --git a/browser_tests/fixtures/utils/countDocFrames.ts b/browser_tests/fixtures/utils/countDocFrames.ts index 5c7c38ffd92..b27adf78e56 100644 --- a/browser_tests/fixtures/utils/countDocFrames.ts +++ b/browser_tests/fixtures/utils/countDocFrames.ts @@ -2,21 +2,27 @@ import type { WebSocketRoute } from '@playwright/test' type SubscriptionFrameType = 'doc_subscribe' | 'doc_unsubscribe' +function isRecord(value: unknown): value is Record { + return typeof value === 'object' && value !== null +} + +function parseFrame(message: string): unknown { + try { + return JSON.parse(message) + } catch { + return null + } +} + function isMatchingSubscriptionFrame( message: string, type: SubscriptionFrameType, workflowId: string ): boolean { - try { - const frame: unknown = JSON.parse(message) - if (typeof frame !== 'object' || frame === null) return false - if (!('type' in frame) || frame.type !== type) return false - if (!('data' in frame) || typeof frame.data !== 'object' || !frame.data) - return false - return 'workflow_id' in frame.data && frame.data.workflow_id === workflowId - } catch { + const frame = parseFrame(message) + if (!isRecord(frame) || frame.type !== type || !isRecord(frame.data)) return false - } + return frame.data.workflow_id === workflowId } export function countDocFrames( diff --git a/src/workbench/extensions/agent/AgentPanelRoot.vue b/src/workbench/extensions/agent/AgentPanelRoot.vue index 1179edece55..6af29383ef9 100644 --- a/src/workbench/extensions/agent/AgentPanelRoot.vue +++ b/src/workbench/extensions/agent/AgentPanelRoot.vue @@ -809,6 +809,67 @@ function agentTabFilename(name: string | undefined): string | undefined { return cleaned.length === 0 ? undefined : `${cleaned}.json` } +async function activateBoundAgentWorkflow( + data: AgentActiveTabData, + bound: ComfyWorkflow, + stale: () => boolean +): Promise { + const opened = await workflowService.openWorkflow(bound) + if (stale()) return + if (!opened) { + warnWorkflowUnavailable() + return + } + // boundOrOpenWorkflowFor can resolve by cloud name, which leaves no binding behind + // for everything downstream that only reads tabPathFor. + bindingStore.bind(data.workflow_id, bound.path) + if (status.value === 'idle') agentPanelStore.setWorkflowTarget(bound) + if (status.value !== 'idle') tabActivity.setEditing(bound.path) + bindWorkflow(data.workflow_id) + useTelemetry()?.trackAgentWorkflowApplied({ + workflow_id: data.workflow_id, + target: 'active_tab_switch' + }) +} + +async function createAgentWorkflow( + data: AgentActiveTabData, + stale: () => boolean +): Promise { + const creatingStartedAt = Date.now() + tabActivity.setCreating(true) + const remainingCreatingTime = + CREATING_TAB_MIN_DURATION_MS - (Date.now() - creatingStartedAt) + if (remainingCreatingTime > 0) + await new Promise((resolve) => setTimeout(resolve, remainingCreatingTime)) + if (stale()) return + const tab = workflowStore.createNewTemporary( + agentTabFilename(data.name), + agentTabGraph + ) + tabActivity.setCreating(false) + let opened: boolean + try { + opened = await workflowService.openWorkflow(tab) + } catch (error) { + await workflowService.closeWorkflow(tab, { warnIfUnsaved: false }) + throw error + } + if (stale() || !opened) { + await workflowService.closeWorkflow(tab, { warnIfUnsaved: false }) + if (!stale()) warnWorkflowUnavailable() + return + } + if (status.value !== 'idle') tabActivity.setEditing(tab.path) + bindingStore.bind(data.workflow_id, tab.path) + if (status.value === 'idle') agentPanelStore.setWorkflowTarget(tab) + bindWorkflow(data.workflow_id) + useTelemetry()?.trackAgentWorkflowApplied({ + workflow_id: data.workflow_id, + target: 'active_tab_open' + }) +} + async function onAgentActiveTab( data: AgentActiveTabData, generation: number @@ -818,56 +879,10 @@ async function onAgentActiveTab( try { const bound = boundOrOpenWorkflowFor(data.workflow_id) if (bound) { - const opened = await workflowService.openWorkflow(bound) - if (stale()) return - if (!opened) { - warnWorkflowUnavailable() - return - } - // boundOrOpenWorkflowFor can resolve by cloud name, which leaves no binding behind - // for everything downstream that only reads tabPathFor. - bindingStore.bind(data.workflow_id, bound.path) - if (status.value === 'idle') agentPanelStore.setWorkflowTarget(bound) - if (status.value !== 'idle') tabActivity.setEditing(bound.path) - bindWorkflow(data.workflow_id) - useTelemetry()?.trackAgentWorkflowApplied({ - workflow_id: data.workflow_id, - target: 'active_tab_switch' - }) + await activateBoundAgentWorkflow(data, bound, stale) return } - const creatingStartedAt = Date.now() - tabActivity.setCreating(true) - const remainingCreatingTime = - CREATING_TAB_MIN_DURATION_MS - (Date.now() - creatingStartedAt) - if (remainingCreatingTime > 0) - await new Promise((resolve) => setTimeout(resolve, remainingCreatingTime)) - if (stale()) return - const tab = workflowStore.createNewTemporary( - agentTabFilename(data.name), - agentTabGraph - ) - tabActivity.setCreating(false) - let opened: boolean - try { - opened = await workflowService.openWorkflow(tab) - } catch (error) { - await workflowService.closeWorkflow(tab, { warnIfUnsaved: false }) - throw error - } - if (stale() || !opened) { - await workflowService.closeWorkflow(tab, { warnIfUnsaved: false }) - if (!stale()) warnWorkflowUnavailable() - return - } - if (status.value !== 'idle') tabActivity.setEditing(tab.path) - bindingStore.bind(data.workflow_id, tab.path) - if (status.value === 'idle') agentPanelStore.setWorkflowTarget(tab) - bindWorkflow(data.workflow_id) - useTelemetry()?.trackAgentWorkflowApplied({ - workflow_id: data.workflow_id, - target: 'active_tab_open' - }) + await createAgentWorkflow(data, stale) } catch (error) { if (stale()) return bindWorkflow(data.workflow_id) From 3d9bc69ed274bdad1094d1d93745dbe8c11a60ff Mon Sep 17 00:00:00 2001 From: bymyself Date: Mon, 21 Sep 2026 22:12:03 -0700 Subject: [PATCH 30/48] chore(agent): keep client frame type internal --- src/workbench/extensions/agent/crdt/docFrameClient.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/workbench/extensions/agent/crdt/docFrameClient.ts b/src/workbench/extensions/agent/crdt/docFrameClient.ts index 421c3f7d91a..352dd5cf701 100644 --- a/src/workbench/extensions/agent/crdt/docFrameClient.ts +++ b/src/workbench/extensions/agent/crdt/docFrameClient.ts @@ -85,7 +85,7 @@ export type ServerDocFrame = | { type: 'doc_reset'; data: DocReset } | { type: 'awareness'; data: DocAwareness } -export type ClientDocFrame = +type ClientDocFrame = | { type: 'doc_subscribe' data: { From 21286faebd94fb692a64354aca2242eb52888a2d Mon Sep 17 00:00:00 2001 From: bymyself Date: Mon, 21 Sep 2026 22:18:30 -0700 Subject: [PATCH 31/48] test(agent): apply reload review cleanup --- .../tests/agent/agentCrdtReload.spec.ts | 48 ++++++++++++------- .../agent/crdt/agentCrdtDocLifecycle.ts | 10 +--- .../agent/crdt/persistedDocId.test.ts | 40 ++++++---------- 3 files changed, 46 insertions(+), 52 deletions(-) diff --git a/browser_tests/tests/agent/agentCrdtReload.spec.ts b/browser_tests/tests/agent/agentCrdtReload.spec.ts index 466c83e73c8..8d33a812e2f 100644 --- a/browser_tests/tests/agent/agentCrdtReload.spec.ts +++ b/browser_tests/tests/agent/agentCrdtReload.spec.ts @@ -1,5 +1,10 @@ import { expect, mergeTests } from '@playwright/test' +import type { + AgentThreadListResponse, + WorkflowListResponse +} from '@comfyorg/ingest-types' + import { AGENT_CRDT_DOC_ID_SESSION_KEY } from '@/platform/workflow/persistence/base/storageKeyConstants' import { AGENT_WORKFLOW_TAB_BINDINGS_STORAGE_KEY, @@ -24,18 +29,17 @@ const test = mergeTests(agentTest, webSocketFixture) test.describe('Agent CRDT reload', { tag: '@cloud' }, () => { test.use({ connectWebSocketToServer: false }) + const workflowId = 'a81718a4-02ae-41e6-ae85-c33b7bb880f6' - test('FE-1969 restores the subscription after reload and suspends it in the background', async ({ - page, - agentFlagEnabled, - getWebSocket, - nextWebSocket, - webSocketMessages - }) => { - test.setTimeout(90_000) - const workflowId = 'a81718a4-02ae-41e6-ae85-c33b7bb880f6' - const agentPanel = new AgentPanel(page) - const command = new CommandHelper(page) + test.beforeEach(async ({ page }) => { + const workflows: WorkflowListResponse = { + data: [], + pagination: { has_more: false, limit: 100, offset: 0, total: 0 } + } + const threads: AgentThreadListResponse = { + threads: [], + pagination: { has_more: false, limit: 100, offset: 0, total: 0 } + } await page.route('**/api/internal/cloud_analytics', (route) => route.fulfill(jsonRoute({})) @@ -44,16 +48,24 @@ test.describe('Agent CRDT reload', { tag: '@cloud' }, () => { route.fulfill(jsonRoute([])) ) await page.route(/\/api\/workflows\?limit=100$/, (route) => - route.fulfill( - jsonRoute({ - data: [], - pagination: { has_more: false, next_cursor: null } - }) - ) + route.fulfill(jsonRoute(workflows)) ) await page.route('**/api/agent/threads', (route) => - route.fulfill(jsonRoute({ threads: [] })) + route.fulfill(jsonRoute(threads)) ) + }) + + test('FE-1969 restores the subscription after reload and suspends it in the background', async ({ + page, + agentFlagEnabled, + getWebSocket, + nextWebSocket, + webSocketMessages + }) => { + test.setTimeout(90_000) + const agentPanel = new AgentPanel(page) + const command = new CommandHelper(page) + await bootAgentApp(page, agentFlagEnabled) const ws = diff --git a/src/workbench/extensions/agent/crdt/agentCrdtDocLifecycle.ts b/src/workbench/extensions/agent/crdt/agentCrdtDocLifecycle.ts index ddd856190ab..173cc0ce113 100644 --- a/src/workbench/extensions/agent/crdt/agentCrdtDocLifecycle.ts +++ b/src/workbench/extensions/agent/crdt/agentCrdtDocLifecycle.ts @@ -8,14 +8,8 @@ import { reconcilePersistedDocId } from './persistedDocId' -// FE-1902 / FEC-5: the persisted doc-id record is owned entirely by -// `persistedDocId.ts` - key, shape, page-load nonce, TTL, and every read and -// write, including the FE-1969 reload adoption. This file is a CONSUMER, not a -// second owner. Two owners cannot coexist on one sessionStorage key: each -// module mints its own page-load nonce, so whichever writes last leaves the -// other's reader looking at a foreign nonce and reporting "nothing persisted" -// for the rest of the page load. The rationale for the nonce and the expiry -// lives with the owner. +// `persistedDocId.ts` is the single owner of the persisted doc-id key, shape, +// page-load nonce, TTL, and reload adoption. This lifecycle only consumes it. // Re-stamp the expiry on doc traffic at most this often, so a busy channel // does not turn every frame into a sessionStorage write. diff --git a/src/workbench/extensions/agent/crdt/persistedDocId.test.ts b/src/workbench/extensions/agent/crdt/persistedDocId.test.ts index b25b9ac01b2..1ba0c822db1 100644 --- a/src/workbench/extensions/agent/crdt/persistedDocId.test.ts +++ b/src/workbench/extensions/agent/crdt/persistedDocId.test.ts @@ -106,6 +106,20 @@ describe('persistedDocId', () => { expect(reconcilePersistedDocId()).toBeNull() expect(rawRecord()).toBeNull() }) + + it('drops a record whose doc id is empty', () => { + sessionStorage.setItem( + DOC_ID_SESSION_KEY, + JSON.stringify({ + docId: '', + nonce: 'a-different-page-load', + expiresAt: Date.now() + 60_000 + }) + ) + + expect(reconcilePersistedDocId()).toBeNull() + expect(rawRecord()).toBeNull() + }) }) describe('reload adoption', () => { @@ -193,29 +207,3 @@ describe('persistedDocId', () => { }) }) }) - -/** - * Carried over from the duplicate reader that used to live in - * `agentCrdtDocLifecycle.ts`. Collapsing onto one owner must not drop its - * guards: an empty doc id passes `typeof === 'string'` and would be handed - * back for the follower to subscribe to. - */ -describe('empty doc id', () => { - beforeEach(() => { - sessionStorage.clear() - }) - - it('refuses and consumes a record whose doc id is the empty string', () => { - sessionStorage.setItem( - DOC_ID_SESSION_KEY, - JSON.stringify({ - docId: '', - nonce: 'a-different-page-load', - expiresAt: Date.now() + 60_000 - }) - ) - - expect(reconcilePersistedDocId()).toBeNull() - expect(rawRecord()).toBeNull() - }) -}) From 3a6b0a844478b03cbba57c61f1c68227a2d3cb09 Mon Sep 17 00:00:00 2001 From: bymyself Date: Tue, 22 Sep 2026 00:36:09 -0700 Subject: [PATCH 32/48] test(agent): cover persisted tab binding reader Addresses review feedback: https://github.com/Comfy-Org/ComfyUI_frontend/pull/16708#discussion_r4068718674 --- .../agentWorkflowTabBindingStorage.test.ts | 51 ++++++++++++++++++- 1 file changed, 50 insertions(+), 1 deletion(-) diff --git a/src/workbench/extensions/agent/stores/agent/agentWorkflowTabBindingStorage.test.ts b/src/workbench/extensions/agent/stores/agent/agentWorkflowTabBindingStorage.test.ts index 06d5d836ed5..16bff73c4df 100644 --- a/src/workbench/extensions/agent/stores/agent/agentWorkflowTabBindingStorage.test.ts +++ b/src/workbench/extensions/agent/stores/agent/agentWorkflowTabBindingStorage.test.ts @@ -2,7 +2,10 @@ import { describe, expect, it } from 'vitest' import { MAX_AGENT_STORAGE_CLOCK_SKEW_MS } from '@/workbench/extensions/agent/persistenceTime' -import { liveAgentWorkflowTabBindings } from './agentWorkflowTabBindingStorage' +import { + liveAgentWorkflowTabBindings, + readPersistedAgentWorkflowTabPath +} from './agentWorkflowTabBindingStorage' describe('liveAgentWorkflowTabBindings', () => { const now = Date.UTC(2026, 8, 22) @@ -49,3 +52,49 @@ describe('liveAgentWorkflowTabBindings', () => { ).toEqual({ workflow: record }) }) }) + +describe('readPersistedAgentWorkflowTabPath', () => { + const now = Date.UTC(2026, 8, 22) + + it.for([ + { label: 'missing storage', raw: null }, + { label: 'invalid JSON', raw: '{' }, + { label: 'a non-object value', raw: 'null' }, + { + label: 'an expired binding', + raw: JSON.stringify({ + requested: { + tabPath: 'workflows/expired.json', + graphId: null, + confirmedAt: now - 30 * 24 * 60 * 60 * 1000 - 1 + } + }) + } + ])('returns undefined for $label', ({ raw }) => { + expect(readPersistedAgentWorkflowTabPath(raw, 'requested', now)).toBe( + undefined + ) + }) + + it('returns only the requested live workflow path', () => { + const raw = JSON.stringify({ + other: { + tabPath: 'workflows/other.json', + graphId: 'graph-other', + confirmedAt: now + }, + requested: { + tabPath: 'workflows/requested.json', + graphId: 'graph-requested', + confirmedAt: now + } + }) + + expect(readPersistedAgentWorkflowTabPath(raw, 'requested', now)).toBe( + 'workflows/requested.json' + ) + expect(readPersistedAgentWorkflowTabPath(raw, 'missing', now)).toBe( + undefined + ) + }) +}) From 7e20fa4d38118bfe9d66f56b03ad70e516fd418c Mon Sep 17 00:00:00 2001 From: bymyself Date: Tue, 22 Sep 2026 00:36:35 -0700 Subject: [PATCH 33/48] test(agent): type reload model folder mock Addresses review feedback: https://github.com/Comfy-Org/ComfyUI_frontend/pull/16708#discussion_r4068718653 --- browser_tests/tests/agent/agentCrdtReload.spec.ts | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/browser_tests/tests/agent/agentCrdtReload.spec.ts b/browser_tests/tests/agent/agentCrdtReload.spec.ts index 8d33a812e2f..c96254203ec 100644 --- a/browser_tests/tests/agent/agentCrdtReload.spec.ts +++ b/browser_tests/tests/agent/agentCrdtReload.spec.ts @@ -5,6 +5,7 @@ import type { WorkflowListResponse } from '@comfyorg/ingest-types' +import type { ModelFolderInfo } from '@/platform/assets/schemas/assetSchema' import { AGENT_CRDT_DOC_ID_SESSION_KEY } from '@/platform/workflow/persistence/base/storageKeyConstants' import { AGENT_WORKFLOW_TAB_BINDINGS_STORAGE_KEY, @@ -44,8 +45,9 @@ test.describe('Agent CRDT reload', { tag: '@cloud' }, () => { await page.route('**/api/internal/cloud_analytics', (route) => route.fulfill(jsonRoute({})) ) + const folders: ModelFolderInfo[] = [] await page.route('**/api/experiment/models', (route) => - route.fulfill(jsonRoute([])) + route.fulfill(jsonRoute(folders)) ) await page.route(/\/api\/workflows\?limit=100$/, (route) => route.fulfill(jsonRoute(workflows)) From 7b5099f133e068596f99657fed24ccca2c83a979 Mon Sep 17 00:00:00 2001 From: bymyself Date: Tue, 22 Sep 2026 00:36:43 -0700 Subject: [PATCH 34/48] test(agent): keep reload workflow id local Addresses review feedback: https://github.com/Comfy-Org/ComfyUI_frontend/pull/16708#discussion_r4068718656 --- browser_tests/tests/agent/agentCrdtReload.spec.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/browser_tests/tests/agent/agentCrdtReload.spec.ts b/browser_tests/tests/agent/agentCrdtReload.spec.ts index c96254203ec..d6817cab2b8 100644 --- a/browser_tests/tests/agent/agentCrdtReload.spec.ts +++ b/browser_tests/tests/agent/agentCrdtReload.spec.ts @@ -30,7 +30,6 @@ const test = mergeTests(agentTest, webSocketFixture) test.describe('Agent CRDT reload', { tag: '@cloud' }, () => { test.use({ connectWebSocketToServer: false }) - const workflowId = 'a81718a4-02ae-41e6-ae85-c33b7bb880f6' test.beforeEach(async ({ page }) => { const workflows: WorkflowListResponse = { @@ -65,6 +64,7 @@ test.describe('Agent CRDT reload', { tag: '@cloud' }, () => { webSocketMessages }) => { test.setTimeout(90_000) + const workflowId = 'a81718a4-02ae-41e6-ae85-c33b7bb880f6' const agentPanel = new AgentPanel(page) const command = new CommandHelper(page) From 865a8d86749d8018158b894ae3b3f3303a97bb61 Mon Sep 17 00:00:00 2001 From: bymyself Date: Tue, 22 Sep 2026 01:35:31 -0700 Subject: [PATCH 35/48] chore(agent): remove redundant follower comments Addresses review feedback: https://github.com/Comfy-Org/ComfyUI_frontend/pull/16708#discussion_r4068718671 --- .../extensions/agent/crdt/useAgentCrdtFollower.test.ts | 3 --- src/workbench/extensions/agent/crdt/useAgentCrdtFollower.ts | 4 ---- 2 files changed, 7 deletions(-) diff --git a/src/workbench/extensions/agent/crdt/useAgentCrdtFollower.test.ts b/src/workbench/extensions/agent/crdt/useAgentCrdtFollower.test.ts index a38602b5745..80acaff04b6 100644 --- a/src/workbench/extensions/agent/crdt/useAgentCrdtFollower.test.ts +++ b/src/workbench/extensions/agent/crdt/useAgentCrdtFollower.test.ts @@ -715,9 +715,6 @@ describe('useAgentCrdtFollower', () => { unmount() }) - // `connected` is derived from `acknowledgedWorkflowId`, not tracked as its - // own ref, so the doc_reset lineage break has to drop the acknowledgement to - // report a disconnect. it('reports a disconnect when a doc_reset breaks the lineage', () => { const { unmount, status } = mountFollower('wf-1') dispatchFrame('doc_subscribed', { ok: true }) diff --git a/src/workbench/extensions/agent/crdt/useAgentCrdtFollower.ts b/src/workbench/extensions/agent/crdt/useAgentCrdtFollower.ts index ddd98d88188..a077cc3ee8e 100644 --- a/src/workbench/extensions/agent/crdt/useAgentCrdtFollower.ts +++ b/src/workbench/extensions/agent/crdt/useAgentCrdtFollower.ts @@ -287,8 +287,6 @@ function startAgentCrdtFollower( const lifecycle = new AgentCrdtDocLifecycle( () => subscribedWorkflowId.value, () => bridge.resubscribe(), - // Exhausting the retry budget drops the acknowledged binding, so derived - // connection status becomes false. () => { acknowledgedWorkflowId.value = null } @@ -491,8 +489,6 @@ function startAgentCrdtFollower( projection.clearForReset(detail.workflowId, context) sender.abortAll() events.onReset?.(detail.workflowId) - // A lineage reset drops the acknowledged binding, which disconnects the - // follower: `status.connected` is derived from this ref. acknowledgedWorkflowId.value = null updatesApplied.value = 0 lastFrameType.value = event.type From d8ac257cb665f31ebc0fd4753de5ee2bff91d494 Mon Sep 17 00:00:00 2001 From: bymyself Date: Tue, 22 Sep 2026 01:35:43 -0700 Subject: [PATCH 36/48] docs(agent): clarify reload nonce adoption Addresses review feedback: https://github.com/Comfy-Org/ComfyUI_frontend/pull/16708#discussion_r4068718677 --- src/workbench/extensions/agent/AgentPanelRoot.vue | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/workbench/extensions/agent/AgentPanelRoot.vue b/src/workbench/extensions/agent/AgentPanelRoot.vue index 3eca953f491..a208dca0934 100644 --- a/src/workbench/extensions/agent/AgentPanelRoot.vue +++ b/src/workbench/extensions/agent/AgentPanelRoot.vue @@ -607,7 +607,8 @@ const isSending = computed( // merely carries a stale binding, or a second bound tab, never reads as // active and never keeps the follower projecting into a background tab. // `reconcilePersistedDocId()` is not a pure read: it adopts and re-stamps the -// record on a reload, drops it on a nonce mismatch, and consults untracked +// record on a reload. A nonce mismatch is adopted and re-stamped during reload +// navigation, but dropped during other navigation. It also consults untracked // `sessionStorage` and `Date.now()`. Calling it from inside the computed getter // therefore let an unrelated re-render consume or rewrite the record the // follower was about to read, and the cached value never invalidated when the From 252508778f42997db86001514038c4fcf52e3d54 Mon Sep 17 00:00:00 2001 From: bymyself Date: Tue, 22 Sep 2026 01:35:52 -0700 Subject: [PATCH 37/48] test(agent): assert minted tab selection and binding Addresses review feedback: https://github.com/Comfy-Org/ComfyUI_frontend/pull/16708#discussion_r4068718676 --- .../extensions/agent/AgentPanelRoot.test.ts | 15 +++++++-------- 1 file changed, 7 insertions(+), 8 deletions(-) diff --git a/src/workbench/extensions/agent/AgentPanelRoot.test.ts b/src/workbench/extensions/agent/AgentPanelRoot.test.ts index d6e61efb919..7553c128d8e 100644 --- a/src/workbench/extensions/agent/AgentPanelRoot.test.ts +++ b/src/workbench/extensions/agent/AgentPanelRoot.test.ts @@ -4247,10 +4247,6 @@ describe('AgentPanelRoot workflow binding', () => { mockMessagesEndpoint('wf-42') await renderAndSend('work here') ws.emit('agent_message_done', { message_id: 'm-1', thread_id: 'th-1' }) - const setWorkflowTarget = vi.spyOn( - useAgentPanelStore(), - 'setWorkflowTarget' - ) await screen.findByRole('button', { name: 'Send' }) ws.emit('agent_active_tab', { @@ -4259,11 +4255,14 @@ describe('AgentPanelRoot workflow binding', () => { thread_id: 'th-1' }) - await vi.waitFor(() => - expect(setWorkflowTarget).toHaveBeenCalledWith( - expect.objectContaining({ path: 'workflows/Video test.json' }) + await vi.waitFor(() => { + expect(useAgentPanelStore().selectedWorkflow?.path).toBe( + 'workflows/Video test.json' ) - ) + expect(useAgentWorkflowTabBindingStore().tabPathFor('wf-77')).toBe( + 'workflows/Video test.json' + ) + }) }) // A browser tab closed without the SPA's own unbind() left 'wf-abandoned' From 3f99ca3713dd04c9f693436856aca274349837e7 Mon Sep 17 00:00:00 2001 From: bymyself Date: Tue, 22 Sep 2026 01:36:02 -0700 Subject: [PATCH 38/48] fix(agent): synchronize target reattachment state Addresses review feedback: https://github.com/Comfy-Org/ComfyUI_frontend/pull/16708#discussion_r4068718668 --- src/workbench/extensions/agent/AgentPanelRoot.vue | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/src/workbench/extensions/agent/AgentPanelRoot.vue b/src/workbench/extensions/agent/AgentPanelRoot.vue index a208dca0934..e37a5799a4f 100644 --- a/src/workbench/extensions/agent/AgentPanelRoot.vue +++ b/src/workbench/extensions/agent/AgentPanelRoot.vue @@ -460,9 +460,13 @@ const workflowDetached = computed( (selectedTarget.value === null && (!agentPanelStore.canRestoreWorkflow || restorableDocId.value === null)) ) -watch(selectedTarget, (target) => { - if (target !== null) newChatDetached.value = false -}) +watch( + selectedTarget, + (target) => { + if (target !== null) newChatDetached.value = false + }, + { flush: 'sync' } +) // Resolves the tab a turn is attributed to. `null` (the send had no origin // tab) resolves to nothing rather than falling back to the selected target, so From 042affd6e78e4078b0530e287ba394f9dd2a1eb9 Mon Sep 17 00:00:00 2001 From: bymyself Date: Tue, 22 Sep 2026 02:36:56 -0700 Subject: [PATCH 39/48] test(agent): assert reload reattachment subscribes Addresses review feedback: https://github.com/Comfy-Org/ComfyUI_frontend/pull/16708#discussion_r4068718666 --- browser_tests/tests/agent/agentFollowerReloadBinding.spec.ts | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/browser_tests/tests/agent/agentFollowerReloadBinding.spec.ts b/browser_tests/tests/agent/agentFollowerReloadBinding.spec.ts index 879a7fcf898..5857eb1fba7 100644 --- a/browser_tests/tests/agent/agentFollowerReloadBinding.spec.ts +++ b/browser_tests/tests/agent/agentFollowerReloadBinding.spec.ts @@ -55,6 +55,7 @@ test.describe( path: beforePath, contentType: 'image/png' }) + const subscribesBeforeReload = agentConversation.subscribeCount() const restoredContent = page.waitForResponse( (response) => @@ -79,6 +80,9 @@ test.describe( expect((await restoredContent).ok()).toBe(true) await expect(prompt).toHaveValue('saved before reload') await agentConversation.sendPrompt() + await expect + .poll(() => agentConversation.subscribeCount()) + .toBe(subscribesBeforeReload + 1) // This value was never saved or recorded. Only the post-reload live // subscription can deliver it; a stale local canvas cannot satisfy it. From a6486cbc8cc9d93355ee2a4ff1316272ae35702d Mon Sep 17 00:00:00 2001 From: bymyself Date: Tue, 22 Sep 2026 02:37:10 -0700 Subject: [PATCH 40/48] test(e2e): make websocket capture opt in Addresses review feedback: https://github.com/Comfy-Org/ComfyUI_frontend/pull/16708#discussion_r4068718647 --- browser_tests/fixtures/ws.ts | 33 ++++++++++++------- .../tests/agent/agentCrdtReload.spec.ts | 5 ++- 2 files changed, 26 insertions(+), 12 deletions(-) diff --git a/browser_tests/fixtures/ws.ts b/browser_tests/fixtures/ws.ts index a7e64165b8d..33c3fc05c05 100644 --- a/browser_tests/fixtures/ws.ts +++ b/browser_tests/fixtures/ws.ts @@ -31,34 +31,45 @@ function createWebSocketRouteHandler( export const webSocketFixture = base.extend<{ connectWebSocketToServer: boolean + captureWebSocketMessages: boolean getWebSocket: () => Promise nextWebSocket: () => Promise webSocketTracker: WebSocketTracker webSocketMessages: Map }>({ connectWebSocketToServer: [true, { option: true }], + captureWebSocketMessages: [false, { option: true }], // oxlint-disable-next-line no-empty-pattern -- Playwright requires an object pattern. webSocketMessages: async ({}, use) => { await use(new Map()) }, webSocketTracker: [ - async ({ context, connectWebSocketToServer, webSocketMessages }, use) => { + async ( + { + context, + connectWebSocketToServer, + captureWebSocketMessages, + webSocketMessages + }, + use + ) => { let current: WebSocketRoute | undefined const waiters = new Set<(ws: WebSocketRoute) => void>() await context.routeWebSocket( /\/ws/, createWebSocketRouteHandler(connectWebSocketToServer, (ws, server) => { - const messages: string[] = [] - webSocketMessages.set(ws, messages) - // Registering a page-side handler switches off Playwright's automatic - // page-to-server forwarding, so recording has to re-send the frame - // itself. Without this every spec merging the fixture drops the - // `feature_flags` handshake and leaves `api.serverFeatureFlags` empty. - ws.onMessage((message) => { - if (typeof message === 'string') messages.push(message) - server?.send(message) - }) + if (captureWebSocketMessages) { + const messages: string[] = [] + webSocketMessages.set(ws, messages) + // Registering a page-side handler switches off Playwright's + // automatic page-to-server forwarding, so recording has to + // re-send the frame itself. + ws.onMessage((message) => { + if (typeof message === 'string') messages.push(message) + server?.send(message) + }) + } current = ws const pending = [...waiters] waiters.clear() diff --git a/browser_tests/tests/agent/agentCrdtReload.spec.ts b/browser_tests/tests/agent/agentCrdtReload.spec.ts index d6817cab2b8..8fe7c7669fa 100644 --- a/browser_tests/tests/agent/agentCrdtReload.spec.ts +++ b/browser_tests/tests/agent/agentCrdtReload.spec.ts @@ -29,7 +29,10 @@ import { webSocketFixture } from '@e2e/fixtures/ws' const test = mergeTests(agentTest, webSocketFixture) test.describe('Agent CRDT reload', { tag: '@cloud' }, () => { - test.use({ connectWebSocketToServer: false }) + test.use({ + connectWebSocketToServer: false, + captureWebSocketMessages: true + }) test.beforeEach(async ({ page }) => { const workflows: WorkflowListResponse = { From b797adb7d580d7dbc43387fd89f4bd35828b9681 Mon Sep 17 00:00:00 2001 From: bymyself Date: Tue, 22 Sep 2026 02:37:23 -0700 Subject: [PATCH 41/48] test(agent): reuse shared client frame parser Addresses review feedback: https://github.com/Comfy-Org/ComfyUI_frontend/pull/16708#discussion_r4068718649 --- .../fixtures/utils/countDocFrames.test.ts | 31 ---------------- .../fixtures/utils/countDocFrames.ts | 37 ------------------- .../tests/agent/agentCrdtReload.spec.ts | 15 +++++++- 3 files changed, 14 insertions(+), 69 deletions(-) delete mode 100644 browser_tests/fixtures/utils/countDocFrames.test.ts delete mode 100644 browser_tests/fixtures/utils/countDocFrames.ts diff --git a/browser_tests/fixtures/utils/countDocFrames.test.ts b/browser_tests/fixtures/utils/countDocFrames.test.ts deleted file mode 100644 index aea73aff7bf..00000000000 --- a/browser_tests/fixtures/utils/countDocFrames.test.ts +++ /dev/null @@ -1,31 +0,0 @@ -import { fromPartial } from '@total-typescript/shoehorn' -import type { WebSocketRoute } from '@playwright/test' -import { describe, expect, it } from 'vitest' - -import { countDocFrames } from '@e2e/fixtures/utils/countDocFrames' - -describe('countDocFrames', () => { - it('ignores unrelated and malformed socket messages', () => { - const ws = fromPartial({}) - const messages = new Map([ - [ - ws, - [ - 'not-json', - JSON.stringify({ type: 'status' }), - JSON.stringify({ type: 'doc_subscribe', data: null }), - JSON.stringify({ - type: 'doc_subscribe', - data: { workflow_id: 'other-workflow' } - }), - JSON.stringify({ - type: 'doc_subscribe', - data: { workflow_id: 'workflow-1' } - }) - ] - ] - ]) - - expect(countDocFrames(messages, ws, 'doc_subscribe', 'workflow-1')).toBe(1) - }) -}) diff --git a/browser_tests/fixtures/utils/countDocFrames.ts b/browser_tests/fixtures/utils/countDocFrames.ts deleted file mode 100644 index b27adf78e56..00000000000 --- a/browser_tests/fixtures/utils/countDocFrames.ts +++ /dev/null @@ -1,37 +0,0 @@ -import type { WebSocketRoute } from '@playwright/test' - -type SubscriptionFrameType = 'doc_subscribe' | 'doc_unsubscribe' - -function isRecord(value: unknown): value is Record { - return typeof value === 'object' && value !== null -} - -function parseFrame(message: string): unknown { - try { - return JSON.parse(message) - } catch { - return null - } -} - -function isMatchingSubscriptionFrame( - message: string, - type: SubscriptionFrameType, - workflowId: string -): boolean { - const frame = parseFrame(message) - if (!isRecord(frame) || frame.type !== type || !isRecord(frame.data)) - return false - return frame.data.workflow_id === workflowId -} - -export function countDocFrames( - messagesBySocket: Map, - ws: WebSocketRoute, - type: SubscriptionFrameType, - workflowId: string -): number { - return (messagesBySocket.get(ws) ?? []).filter((message) => - isMatchingSubscriptionFrame(message, type, workflowId) - ).length -} diff --git a/browser_tests/tests/agent/agentCrdtReload.spec.ts b/browser_tests/tests/agent/agentCrdtReload.spec.ts index 8fe7c7669fa..b44fefbc6d2 100644 --- a/browser_tests/tests/agent/agentCrdtReload.spec.ts +++ b/browser_tests/tests/agent/agentCrdtReload.spec.ts @@ -1,4 +1,5 @@ import { expect, mergeTests } from '@playwright/test' +import type { WebSocketRoute } from '@playwright/test' import type { AgentThreadListResponse, @@ -19,13 +20,25 @@ import { readPersistedAgentDocIdentity, switchToAgentWorkflowTab } from '@e2e/fixtures/agentPanelFixture' +import { parseClientDocFrame } from '@e2e/fixtures/agentFollowerHostSocket' import { waitForCloudApp } from '@e2e/fixtures/cloudAppFixture' import { AgentPanel } from '@e2e/fixtures/components/AgentPanel' import { CommandHelper } from '@e2e/fixtures/helpers/CommandHelper' -import { countDocFrames } from '@e2e/fixtures/utils/countDocFrames' import { jsonRoute } from '@e2e/fixtures/utils/jsonRoute' import { webSocketFixture } from '@e2e/fixtures/ws' +function countDocFrames( + messagesBySocket: Map, + ws: WebSocketRoute, + type: 'doc_subscribe' | 'doc_unsubscribe', + workflowId: string +): number { + return (messagesBySocket.get(ws) ?? []).filter((message) => { + const frame = parseClientDocFrame(message) + return frame?.type === type && frame.workflowId === workflowId + }).length +} + const test = mergeTests(agentTest, webSocketFixture) test.describe('Agent CRDT reload', { tag: '@cloud' }, () => { From 13d790220f3b6f6c4cc460c372e62cb5a5a0b4c4 Mon Sep 17 00:00:00 2001 From: bymyself Date: Tue, 22 Sep 2026 02:37:37 -0700 Subject: [PATCH 42/48] test(agent): acknowledge the subscribing reload socket Addresses review feedback: https://github.com/Comfy-Org/ComfyUI_frontend/pull/16708#discussion_r4068718658 --- .../tests/agent/agentCrdtReload.spec.ts | 17 ++++++++++++++++- 1 file changed, 16 insertions(+), 1 deletion(-) diff --git a/browser_tests/tests/agent/agentCrdtReload.spec.ts b/browser_tests/tests/agent/agentCrdtReload.spec.ts index b44fefbc6d2..82956b703f0 100644 --- a/browser_tests/tests/agent/agentCrdtReload.spec.ts +++ b/browser_tests/tests/agent/agentCrdtReload.spec.ts @@ -148,6 +148,18 @@ test.describe('Agent CRDT reload', { tag: '@cloud' }, () => { } return total } + const firstSocketWithFrameAfterReload = ( + type: 'doc_subscribe' | 'doc_unsubscribe' + ): WebSocketRoute | null => { + for (const socket of webSocketMessages.keys()) { + if ( + socket !== ws && + countDocFrames(webSocketMessages, socket, type, workflowId) > 0 + ) + return socket + } + return null + } await test.step('Reload and restore the workflow subscription', async () => { // Arm the waiter BEFORE the reload. The replacement socket is routed @@ -178,7 +190,10 @@ test.describe('Agent CRDT reload', { tag: '@cloud' }, () => { await expect.poll(() => countAfterReload('doc_subscribe')).toBe(1) - reloadedWs.send( + const subscribedSocket = firstSocketWithFrameAfterReload('doc_subscribe') + if (!subscribedSocket) + throw new Error('Reloaded workflow subscription socket is missing') + subscribedSocket.send( JSON.stringify({ type: 'doc_subscribed', data: { v: 1, workflow_id: workflowId, ok: true, seq: 0 } From f6247e1452b49b050eb94f157e75d27514470134 Mon Sep 17 00:00:00 2001 From: bymyself Date: Tue, 22 Sep 2026 02:37:49 -0700 Subject: [PATCH 43/48] test(agent): narrow tab-return subscription claim Addresses review feedback: https://github.com/Comfy-Org/ComfyUI_frontend/pull/16708#discussion_r4068718662 --- browser_tests/tests/agent/agentCrdtReload.spec.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/browser_tests/tests/agent/agentCrdtReload.spec.ts b/browser_tests/tests/agent/agentCrdtReload.spec.ts index 82956b703f0..35adeba5188 100644 --- a/browser_tests/tests/agent/agentCrdtReload.spec.ts +++ b/browser_tests/tests/agent/agentCrdtReload.spec.ts @@ -201,16 +201,16 @@ test.describe('Agent CRDT reload', { tag: '@cloud' }, () => { ) }) - await test.step('Switching away suspends the follower and returning resumes it', async () => { + await test.step('Switching away unsubscribes and returning requests a subscription', async () => { expect(countAfterReload('doc_unsubscribe')).toBe(0) await command.executeCommand('Comfy.NewBlankWorkflow') await expect.poll(() => countAfterReload('doc_unsubscribe')).toBe(1) - const subscribeCountBeforeResume = countAfterReload('doc_subscribe') + const subscribeCountBeforeReturn = countAfterReload('doc_subscribe') await switchToAgentWorkflowTab(page, boundPath) await expect .poll(() => countAfterReload('doc_subscribe')) - .toBe(subscribeCountBeforeResume + 1) + .toBe(subscribeCountBeforeReturn + 1) }) }) }) From 3d04ff09a2d80ea1168c273a902ec22c2cbc68c9 Mon Sep 17 00:00:00 2001 From: bymyself Date: Tue, 22 Sep 2026 03:35:51 -0700 Subject: [PATCH 44/48] fix(agent): detach persisted follower before history load Addresses review feedback: https://github.com/Comfy-Org/ComfyUI_frontend/pull/16708#discussion_r4068718644 --- .../extensions/agent/AgentPanelRoot.test.ts | 110 ++++++++++++++++++ .../extensions/agent/AgentPanelRoot.vue | 2 + 2 files changed, 112 insertions(+) diff --git a/src/workbench/extensions/agent/AgentPanelRoot.test.ts b/src/workbench/extensions/agent/AgentPanelRoot.test.ts index 7553c128d8e..3530c8d6823 100644 --- a/src/workbench/extensions/agent/AgentPanelRoot.test.ts +++ b/src/workbench/extensions/agent/AgentPanelRoot.test.ts @@ -262,6 +262,7 @@ import { useAgentComposerStore } from './stores/agent/agentComposerStore' import { useAgentWorkflowTabBindingStore } from './stores/agent/agentWorkflowTabBindingStore' import { attachMintPortWiring } from './crdt/mintPortWiring' import type { MintPortWiring, MintPortWiringDeps } from './crdt/mintPortWiring' +import { persistDocId } from './crdt/persistedDocId' const mintPortWiringDeps = vi.hoisted(() => ({ current: null as MintPortWiringDeps | null @@ -2879,6 +2880,115 @@ describe('AgentPanelRoot workflow binding', () => { return bodies } + it.for([ + { label: 'an id-less thread', replacementWorkflowId: null }, + { label: 'a delayed replacement workflow', replacementWorkflowId: 'wf-b' } + ])( + 'detaches the persisted follower before loading $label', + async ({ replacementWorkflowId }) => { + const current = makeTab('wf-a') + persistDocId('wf-a') + if (replacementWorkflowId) { + const replacement = addTab('workflows/replacement.json') + useAgentWorkflowTabBindingStore().bind( + replacementWorkflowId, + replacement.path + ) + } + let resolveHistory!: (response: Response) => void + const historyResponse = new Promise((resolve) => { + resolveHistory = resolve + }) + vi.stubGlobal( + 'fetch', + vi.fn(async (url: string) => { + if (url.includes('/messages')) return historyResponse + if (url.includes('/agent/threads')) + return json( + 200, + agentThreadList([ + agentThread({ + id: 'th-history', + title: 'Earlier chat', + last_message_at: '2026-09-01T00:00:00Z' + }) + ]) + ) + if (url.includes('/workflows')) + return json(200, { + data: [], + pagination: { offset: 0, limit: 100, total: 0, has_more: false } + }) + return json(200, {}) + }) + ) + + renderWithSelectedTarget() + await vi.waitFor(() => + expect( + socketSend.mock.calls.some(([frame]) => + String(frame).includes('"type":"doc_subscribe"') + ) + ).toBe(true) + ) + socketSend.mockClear() + + await userEvent.click( + screen.getByRole('button', { + name: i18n.global.t('agent.showChatHistory') + }) + ) + await userEvent.click(await screen.findByText('Earlier chat')) + + await vi.waitFor(() => + expect( + socketSend.mock.calls.some(([frame]) => + String(frame).includes('"type":"doc_unsubscribe"') + ) + ).toBe(true) + ) + expect(workflowStore.activeWorkflow).toEqual(current) + + resolveHistory( + json(200, [ + { + id: 'history-user', + thread_id: 'th-history', + seq: 1, + role: 'user', + status: 'complete', + turn_id: 'history-turn', + ...(replacementWorkflowId + ? { workflow_id: replacementWorkflowId } + : {}), + content: { text: 'Historical prompt' } + } + ]) + ) + await screen.findAllByText('Historical prompt') + + if (replacementWorkflowId) { + await vi.waitFor(() => + expect( + socketSend.mock.calls.some(([frame]) => { + const raw = String(frame) + return ( + raw.includes('"type":"doc_subscribe"') && + raw.includes(`"workflow_id":"${replacementWorkflowId}"`) + ) + }) + ).toBe(true) + ) + } else { + expect( + socketSend.mock.calls.some(([frame]) => + String(frame).includes('"type":"doc_subscribe"') + ) + ).toBe(false) + } + } + ) + it('preserves active-turn graph activity across remount and delayed hydration', async () => { makeTab('wf-42') let resolveHistory!: (response: Response) => void diff --git a/src/workbench/extensions/agent/AgentPanelRoot.vue b/src/workbench/extensions/agent/AgentPanelRoot.vue index e37a5799a4f..ae110ec1219 100644 --- a/src/workbench/extensions/agent/AgentPanelRoot.vue +++ b/src/workbench/extensions/agent/AgentPanelRoot.vue @@ -972,6 +972,8 @@ void refreshHistory() async function onSelectHistory(id: string): Promise { composerStore.invalidateSubmission() cancelWorkflowSelection() + clearPersistedDocId() + restorableDocId.value = null agentPanelStore.resetWorkflowTarget() exitNodeSelectionMode() await loadThread(id) From 4f2d30f065ea94441fc97ba4c2e7857fafaae56c Mon Sep 17 00:00:00 2001 From: bymyself Date: Tue, 22 Sep 2026 04:37:24 -0700 Subject: [PATCH 45/48] fix(agent): restore hydrated workflow session binding Addresses https://github.com/Comfy-Org/ComfyUI_frontend/pull/16708#discussion_r4070812616 Addresses https://github.com/Comfy-Org/ComfyUI_frontend/pull/16708#discussion_r4070812625 Addresses https://github.com/Comfy-Org/ComfyUI_frontend/pull/16708#discussion_r4070812635 --- .../extensions/agent/AgentPanelRoot.vue | 49 ++++++------------- 1 file changed, 14 insertions(+), 35 deletions(-) diff --git a/src/workbench/extensions/agent/AgentPanelRoot.vue b/src/workbench/extensions/agent/AgentPanelRoot.vue index ae110ec1219..a53da5a80bc 100644 --- a/src/workbench/extensions/agent/AgentPanelRoot.vue +++ b/src/workbench/extensions/agent/AgentPanelRoot.vue @@ -452,20 +452,11 @@ watch( { immediate: true } ) -const newChatDetached = ref(false) const restorableDocId = ref(reconcilePersistedDocId()) const workflowDetached = computed( () => - newChatDetached.value || - (selectedTarget.value === null && - (!agentPanelStore.canRestoreWorkflow || restorableDocId.value === null)) -) -watch( - selectedTarget, - (target) => { - if (target !== null) newChatDetached.value = false - }, - { flush: 'sync' } + selectedTarget.value === null && + (!agentPanelStore.canRestoreWorkflow || restorableDocId.value === null) ) // Resolves the tab a turn is attributed to. `null` (the send had no origin @@ -584,7 +575,16 @@ const { workflow: { current: targetWorkflowTurnContext, adopted: onWorkflowAdopted, - restored: onWorkflowRestored, + restored: async (workflowId, isCurrent) => { + await onWorkflowRestored(workflowId, isCurrent) + if ( + workflowId !== undefined && + isCurrent() && + selectedTarget.value !== null && + bindingStore.tabPathFor(workflowId) === selectedTarget.value.path + ) + bindWorkflow(workflowId) + }, prepare: async () => { await refreshCloudWorkflowIds() }, @@ -599,25 +599,8 @@ const isSending = computed( () => sessionIsSending.value || composerStore.submission?.phase === 'pending' ) -// FE-1969: `boundWorkflowId` is the in-memory session binding. A panel remount -// can restore it within the same page load. A browser reload creates a new page -// load, so `reconcilePersistedDocId()` adopts the previous load's unexpired -// record and replaces its nonce. In either case, the follower can rebind only -// if this computed drives it with `active=true`. "New chat" is deliberately not -// one of those cases: it ends the session, so `onNewChat` drops the record and -// there is nothing left to restore. The -// fallback is scoped to that one doc: the active tab's persisted tab binding -// counts only when it names the doc the follower would restore, so a tab that -// merely carries a stale binding, or a second bound tab, never reads as -// active and never keeps the follower projecting into a background tab. -// `reconcilePersistedDocId()` is not a pure read: it adopts and re-stamps the -// record on a reload. A nonce mismatch is adopted and re-stamped during reload -// navigation, but dropped during other navigation. It also consults untracked -// `sessionStorage` and `Date.now()`. Calling it from inside the computed getter -// therefore let an unrelated re-render consume or rewrite the record the -// follower was about to read, and the cached value never invalidated when the -// record lapsed. Resolve it at the explicit lifecycle points that used to drive -// re-evaluation and let the getter read only reactive state. +// Reconciliation mutates storage, so run it only at explicit lifecycle edges; +// computed getters below read reactive state without consuming the record. watch( [() => workflowStore.activeWorkflow, boundWorkflowId], () => { @@ -1077,15 +1060,11 @@ function onNewChat(): void { // Ending the session also ends the document's claim on the graph. clearPersistedDocId() restorableDocId.value = null - newChatDetached.value = true // A new chat targets whatever tab is on screen right now, not the previous // chat's target - unlike onSelectHistory(), which resets to 'uninitialized' // so restoreTarget() can re-apply the loaded thread's own binding. agentPanelStore.setWorkflowTarget(workflowStore.activeWorkflow) newChat() - // A selected target remains explicit context across chats; only a targetless - // new chat stays detached after the session binding is cleared. - if (selectedTarget.value !== null) newChatDetached.value = false } const panelRef = ref>() From f64267b65a3300ff3fe7240ac040ea585fa50cb1 Mon Sep 17 00:00:00 2001 From: bymyself Date: Tue, 22 Sep 2026 04:37:24 -0700 Subject: [PATCH 46/48] docs(agent): state persisted doc identity contract Addresses https://github.com/Comfy-Org/ComfyUI_frontend/pull/16708#discussion_r4070812643 --- .../extensions/agent/crdt/persistedDocId.ts | 17 +++++------------ 1 file changed, 5 insertions(+), 12 deletions(-) diff --git a/src/workbench/extensions/agent/crdt/persistedDocId.ts b/src/workbench/extensions/agent/crdt/persistedDocId.ts index 5ae96275c39..b14ecab3597 100644 --- a/src/workbench/extensions/agent/crdt/persistedDocId.ts +++ b/src/workbench/extensions/agent/crdt/persistedDocId.ts @@ -2,16 +2,9 @@ import { createUuidv4 } from '@/utils/uuid' import { AGENT_CRDT_DOC_ID_SESSION_KEY } from '@/platform/workflow/persistence/base/storageKeyConstants' import { MAX_AGENT_STORAGE_CLOCK_SKEW_MS } from '@/workbench/extensions/agent/persistenceTime' -// FE-1902: the doc id is otherwise held only in memory (set on turn ack), so a -// panel remount or reload loses the binding until the next turn ack. Persist it -// per-tab in sessionStorage so the follower can rebind immediately. -// -// FEC-5: a bare doc id has no owner and no lifetime, so the record carries a -// per-page-load nonce and a short expiry. Browser-tab duplication clones -// sessionStorage, but the cloud dock mount reconciles this record before its -// lazy panel boundary: a duplicated tab gets a fresh nonce and consumes the -// inherited record on its first load, even when the panel stays closed. An -// explicit reload may adopt the previous page load's unexpired record. +// The per-tab record restores the in-memory doc binding after reload. Its +// per-page-load nonce prevents a duplicated tab from inheriting ownership, +// while the short expiry bounds how long an explicit reload may adopt it. export const DOC_ID_SESSION_KEY = AGENT_CRDT_DOC_ID_SESSION_KEY export const DOC_ID_TTL_MS = 5 * 60 * 1000 @@ -65,7 +58,7 @@ export function reconcilePersistedDocId(): string | null { const parsed: unknown = JSON.parse(raw) // Every rejection below also drops the key. Leaving a rejected record in // place would break the invariant the dock-mount reconcile relies on: a - // duplicated tab that inherits a lapsed or pre-FEC-5 record would keep + // duplicated tab that inherits a lapsed or legacy record would keep // re-reading and re-rejecting it on every reconcile instead of consuming it // once. // `Number.isFinite`, not `typeof === 'number'`: `JSON.parse` turns an @@ -117,7 +110,7 @@ export function reconcilePersistedDocId(): string | null { } return record.docId } catch { - // A pre-FEC-5 bare doc id is not valid JSON, so it lands here rather than + // A legacy bare doc id is not valid JSON, so it lands here rather than // in the shape check above; drop it so it is consumed exactly once. clearPersistedDocId() return null From 33dc07e5b57254b3100b466e5cd82216cdcacef7 Mon Sep 17 00:00:00 2001 From: bymyself Date: Tue, 22 Sep 2026 04:37:24 -0700 Subject: [PATCH 47/48] test(agent): move socket capture queries into fixture Addresses https://github.com/Comfy-Org/ComfyUI_frontend/pull/16708#discussion_r4070812650 Addresses https://github.com/Comfy-Org/ComfyUI_frontend/pull/16708#discussion_r4070812657 --- browser_tests/fixtures/ws.ts | 37 +++++++++++++- .../tests/agent/agentCrdtReload.spec.ts | 48 ++++++------------- 2 files changed, 49 insertions(+), 36 deletions(-) diff --git a/browser_tests/fixtures/ws.ts b/browser_tests/fixtures/ws.ts index 33c3fc05c05..3d2172a31c3 100644 --- a/browser_tests/fixtures/ws.ts +++ b/browser_tests/fixtures/ws.ts @@ -11,6 +11,39 @@ interface WebSocketTracker { waitForNext: () => Promise } +export class CapturedWebSocketMessages extends Map< + WebSocketRoute, + string[] +> { + countFor( + socket: WebSocketRoute, + matches: (message: string) => boolean + ): number { + return (this.get(socket) ?? []).filter(matches).length + } + + count( + matches: (message: string) => boolean, + except?: WebSocketRoute + ): number { + let total = 0 + for (const [socket, messages] of this) { + if (socket !== except) total += messages.filter(matches).length + } + return total + } + + firstSocket( + matches: (message: string) => boolean, + except?: WebSocketRoute + ): WebSocketRoute | null { + for (const [socket, messages] of this) { + if (socket !== except && messages.some(matches)) return socket + } + return null + } +} + function createWebSocketRouteHandler( connectWebSocketToServer: boolean, onRouted: (ws: WebSocketRoute, server: WebSocketRoute | null) => void @@ -35,13 +68,13 @@ export const webSocketFixture = base.extend<{ getWebSocket: () => Promise nextWebSocket: () => Promise webSocketTracker: WebSocketTracker - webSocketMessages: Map + webSocketMessages: CapturedWebSocketMessages }>({ connectWebSocketToServer: [true, { option: true }], captureWebSocketMessages: [false, { option: true }], // oxlint-disable-next-line no-empty-pattern -- Playwright requires an object pattern. webSocketMessages: async ({}, use) => { - await use(new Map()) + await use(new CapturedWebSocketMessages()) }, webSocketTracker: [ async ( diff --git a/browser_tests/tests/agent/agentCrdtReload.spec.ts b/browser_tests/tests/agent/agentCrdtReload.spec.ts index 35adeba5188..ccc4d898fe6 100644 --- a/browser_tests/tests/agent/agentCrdtReload.spec.ts +++ b/browser_tests/tests/agent/agentCrdtReload.spec.ts @@ -1,6 +1,4 @@ import { expect, mergeTests } from '@playwright/test' -import type { WebSocketRoute } from '@playwright/test' - import type { AgentThreadListResponse, WorkflowListResponse @@ -27,18 +25,6 @@ import { CommandHelper } from '@e2e/fixtures/helpers/CommandHelper' import { jsonRoute } from '@e2e/fixtures/utils/jsonRoute' import { webSocketFixture } from '@e2e/fixtures/ws' -function countDocFrames( - messagesBySocket: Map, - ws: WebSocketRoute, - type: 'doc_subscribe' | 'doc_unsubscribe', - workflowId: string -): number { - return (messagesBySocket.get(ws) ?? []).filter((message) => { - const frame = parseClientDocFrame(message) - return frame?.type === type && frame.workflowId === workflowId - }).length -} - const test = mergeTests(agentTest, webSocketFixture) test.describe('Agent CRDT reload', { tag: '@cloud' }, () => { @@ -83,11 +69,18 @@ test.describe('Agent CRDT reload', { tag: '@cloud' }, () => { const workflowId = 'a81718a4-02ae-41e6-ae85-c33b7bb880f6' const agentPanel = new AgentPanel(page) const command = new CommandHelper(page) + const matchesDocFrame = ( + type: 'doc_subscribe' | 'doc_unsubscribe' + ) => + (message: string): boolean => { + const frame = parseClientDocFrame(message) + return frame?.type === type && frame.workflowId === workflowId + } await bootAgentApp(page, agentFlagEnabled) const ws = - await test.step('Bind the active workflow and persist its reload state', async () => { + await test.step('Bind the active workflow and request its subscription', async () => { const ws = await getWebSocket() await agentPanel.open() pushAgentEvent(ws, { @@ -97,7 +90,10 @@ test.describe('Agent CRDT reload', { tag: '@cloud' }, () => { await expect .poll(() => - countDocFrames(webSocketMessages, ws, 'doc_subscribe', workflowId) + webSocketMessages.countFor( + ws, + matchesDocFrame('doc_subscribe') + ) ) .toBe(1) return ws @@ -140,26 +136,10 @@ test.describe('Agent CRDT reload', { tag: '@cloud' }, () => { // run ambiguous. const countAfterReload = ( type: 'doc_subscribe' | 'doc_unsubscribe' - ): number => { - let total = 0 - for (const socket of webSocketMessages.keys()) { - if (socket === ws) continue - total += countDocFrames(webSocketMessages, socket, type, workflowId) - } - return total - } + ): number => webSocketMessages.count(matchesDocFrame(type), ws) const firstSocketWithFrameAfterReload = ( type: 'doc_subscribe' | 'doc_unsubscribe' - ): WebSocketRoute | null => { - for (const socket of webSocketMessages.keys()) { - if ( - socket !== ws && - countDocFrames(webSocketMessages, socket, type, workflowId) > 0 - ) - return socket - } - return null - } + ) => webSocketMessages.firstSocket(matchesDocFrame(type), ws) await test.step('Reload and restore the workflow subscription', async () => { // Arm the waiter BEFORE the reload. The replacement socket is routed From b8cbb4277f150a75cf9e7498ac101aefc78eda40 Mon Sep 17 00:00:00 2001 From: GitHub Action Date: Tue, 22 Sep 2026 11:44:37 +0000 Subject: [PATCH 48/48] [automated] Apply ESLint and Oxfmt fixes --- browser_tests/fixtures/ws.ts | 5 +---- browser_tests/tests/agent/agentCrdtReload.spec.ts | 10 +++------- 2 files changed, 4 insertions(+), 11 deletions(-) diff --git a/browser_tests/fixtures/ws.ts b/browser_tests/fixtures/ws.ts index 3d2172a31c3..9410fbc0f9c 100644 --- a/browser_tests/fixtures/ws.ts +++ b/browser_tests/fixtures/ws.ts @@ -11,10 +11,7 @@ interface WebSocketTracker { waitForNext: () => Promise } -export class CapturedWebSocketMessages extends Map< - WebSocketRoute, - string[] -> { +export class CapturedWebSocketMessages extends Map { countFor( socket: WebSocketRoute, matches: (message: string) => boolean diff --git a/browser_tests/tests/agent/agentCrdtReload.spec.ts b/browser_tests/tests/agent/agentCrdtReload.spec.ts index ccc4d898fe6..675c88d86d0 100644 --- a/browser_tests/tests/agent/agentCrdtReload.spec.ts +++ b/browser_tests/tests/agent/agentCrdtReload.spec.ts @@ -69,9 +69,8 @@ test.describe('Agent CRDT reload', { tag: '@cloud' }, () => { const workflowId = 'a81718a4-02ae-41e6-ae85-c33b7bb880f6' const agentPanel = new AgentPanel(page) const command = new CommandHelper(page) - const matchesDocFrame = ( - type: 'doc_subscribe' | 'doc_unsubscribe' - ) => + const matchesDocFrame = + (type: 'doc_subscribe' | 'doc_unsubscribe') => (message: string): boolean => { const frame = parseClientDocFrame(message) return frame?.type === type && frame.workflowId === workflowId @@ -90,10 +89,7 @@ test.describe('Agent CRDT reload', { tag: '@cloud' }, () => { await expect .poll(() => - webSocketMessages.countFor( - ws, - matchesDocFrame('doc_subscribe') - ) + webSocketMessages.countFor(ws, matchesDocFrame('doc_subscribe')) ) .toBe(1) return ws