diff --git a/browser_tests/fixtures/agentFollowerHostSocket.ts b/browser_tests/fixtures/agentFollowerHostSocket.ts index 8384e0b829a..faac537b9c1 100644 --- a/browser_tests/fixtures/agentFollowerHostSocket.ts +++ b/browser_tests/fixtures/agentFollowerHostSocket.ts @@ -88,7 +88,7 @@ function opLabel(op: WireOpEnvelope): string { return `${op.op}:${'node_id' in op ? String(op.node_id) : ''}` } -function parseClientDocFrame( +export function parseClientDocFrame( raw: string | Buffer ): ParsedClientDocFrame | null { const envelope = docFrameEnvelope(raw) diff --git a/browser_tests/fixtures/agentPanelFixture.ts b/browser_tests/fixtures/agentPanelFixture.ts index 80bd63c5f66..9d922e3e601 100644 --- a/browser_tests/fixtures/agentPanelFixture.ts +++ b/browser_tests/fixtures/agentPanelFixture.ts @@ -1,4 +1,5 @@ -import type { Page, Route } from '@playwright/test' +import { expect } from '@playwright/test' +import type { Page, Route, WebSocketRoute } from '@playwright/test' import type { AgentRunMode, @@ -11,13 +12,18 @@ 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 { StorageKeys } from '@/platform/workflow/persistence/base/storageKeys' import type { ComfyWorkflowJSON } from '@/platform/workflow/validation/schemas/workflowSchema' import type { ComfyNodeDef } from '@/schemas/nodeDefSchema' -import type { AgentTurnAccepted } from '@/workbench/extensions/agent/schemas/agentApiSchema' +import type { + AgentTurnAccepted, + AgentWsEvent +} from '@/workbench/extensions/agent/schemas/agentApiSchema' import { cloudAppFixture, waitForCloudApp } from '@e2e/fixtures/cloudAppFixture' import { AgentPanel } from '@e2e/fixtures/components/AgentPanel' +import { Topbar } from '@e2e/fixtures/components/Topbar' import { AGENT_COMPOSER_THREAD_ID, agentComposerRunMode, @@ -194,6 +200,58 @@ 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 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), + 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 } +} + type AgentComposerPerformanceFixtures = { agentComposerTurnCount: number agentComposerPanel: AgentPanel diff --git a/browser_tests/fixtures/ws.ts b/browser_tests/fixtures/ws.ts index 716e9272615..9410fbc0f9c 100644 --- a/browser_tests/fixtures/ws.ts +++ b/browser_tests/fixtures/ws.ts @@ -11,37 +11,95 @@ interface WebSocketTracker { waitForNext: () => Promise } +export class CapturedWebSocketMessages extends Map { + 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) => 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 + captureWebSocketMessages: boolean getWebSocket: () => Promise nextWebSocket: () => Promise webSocketTracker: WebSocketTracker + 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 CapturedWebSocketMessages()) + }, webSocketTracker: [ - async ({ context, connectWebSocketToServer }, 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) => { + createWebSocketRouteHandler(connectWebSocketToServer, (ws, server) => { + 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 new file mode 100644 index 00000000000..d067e0c89ca --- /dev/null +++ b/browser_tests/tests/agent/agentCrdtReload.spec.ts @@ -0,0 +1,190 @@ +import { expect, mergeTests } from '@playwright/test' +import type { + AgentThreadListResponse, + 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 { StorageKeys } from '@/platform/workflow/persistence/base/storageKeys' +import { readPersistedAgentWorkflowTabPath } from '@/workbench/extensions/agent/stores/agent/agentWorkflowTabBindingStorage' +import { + agentTest, + bootAgentApp, + getAgentActiveWorkflowPath, + pushAgentEvent, + 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 { jsonRoute } from '@e2e/fixtures/utils/jsonRoute' +import { webSocketFixture } from '@e2e/fixtures/ws' + +const test = mergeTests(agentTest, webSocketFixture) + +test.describe('Agent CRDT reload', { tag: '@cloud' }, () => { + test.use({ + connectWebSocketToServer: false, + captureWebSocketMessages: true + }) + + 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({})) + ) + const folders: ModelFolderInfo[] = [] + await page.route('**/api/experiment/models', (route) => + route.fulfill(jsonRoute(folders)) + ) + await page.route(/\/api\/workflows\?limit=100$/, (route) => + route.fulfill(jsonRoute(workflows)) + ) + await page.route('**/api/agent/threads', (route) => + 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 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 request its subscription', async () => { + const ws = await getWebSocket() + await agentPanel.open() + pushAgentEvent(ws, { + type: 'agent_active_tab', + data: { workflow_id: workflowId, name: 'Reload receipt' } + }) + + await expect + .poll(() => + webSocketMessages.countFor(ws, matchesDocFrame('doc_subscribe')) + ) + .toBe(1) + return ws + }) + + ws.send( + JSON.stringify({ + type: 'doc_subscribed', + data: { v: 1, workflow_id: workflowId, ok: true, seq: 0 } + }) + ) + + await expect + .poll(() => + page.evaluate( + (key) => sessionStorage.getItem(key), + AGENT_CRDT_DOC_ID_SESSION_KEY + ) + ) + .not.toBeNull() + const recordBeforeReload = await readPersistedAgentDocIdentity(page) + expect(recordBeforeReload).toMatchObject({ docId: workflowId }) + + const rawBindings = await page.evaluate( + (key) => localStorage.getItem(key), + StorageKeys.agentWorkflowTabBindings('personal') + ) + const boundPath = readPersistedAgentWorkflowTabPath(rawBindings, workflowId) + 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')) + ).toBeNull() + + // 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 => webSocketMessages.count(matchesDocFrame(type), ws) + const firstSocketWithFrameAfterReload = ( + type: 'doc_subscribe' | 'doc_unsubscribe' + ) => 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 + // 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) + // 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({ + type: 'status', + 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 readPersistedAgentDocIdentity(page) + 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 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 } + }) + ) + }) + + 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 subscribeCountBeforeReturn = countAfterReload('doc_subscribe') + + await switchToAgentWorkflowTab(page, boundPath) + await expect + .poll(() => countAfterReload('doc_subscribe')) + .toBe(subscribeCountBeforeReturn + 1) + }) + }) +}) diff --git a/browser_tests/tests/agent/agentFollowerReloadBinding.spec.ts b/browser_tests/tests/agent/agentFollowerReloadBinding.spec.ts index 858c35c3b16..5857eb1fba7 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[] = [] @@ -52,6 +55,7 @@ test.describe( path: beforePath, contentType: 'image/png' }) + const subscribesBeforeReload = agentConversation.subscribeCount() const restoredContent = page.waitForResponse( (response) => @@ -75,11 +79,10 @@ 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) + .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. diff --git a/src/platform/workflow/persistence/base/storageIO.ts b/src/platform/workflow/persistence/base/storageIO.ts index e668b3d8d3e..2ace0ae8645 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' @@ -474,7 +475,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.test.ts b/src/workbench/extensions/agent/AgentPanelRoot.test.ts index ed702dd6bed..09d3474c5c5 100644 --- a/src/workbench/extensions/agent/AgentPanelRoot.test.ts +++ b/src/workbench/extensions/agent/AgentPanelRoot.test.ts @@ -250,6 +250,7 @@ import { useAgentComposerStore } from './stores/agent/agentComposerStore' import { useAgentWorkflowTabBindingStore } from './stores/agent/agentWorkflowTabBindingStore' import { attachDocOpMinter } from './crdt/docOpMinter' import type { DocOpMinter, DocOpMinterDeps } from './crdt/docOpMinter' +import { persistDocId } from './crdt/persistedDocId' const docOpMinterDeps = vi.hoisted(() => ({ current: null as DocOpMinterDeps | null @@ -4185,6 +4186,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 @@ -5963,6 +6073,43 @@ 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' }) + 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(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' // bound to the default unsaved path in localStorage, and the thread pointer // survived beside it. On the next boot the thread hydrates and names that diff --git a/src/workbench/extensions/agent/AgentPanelRoot.vue b/src/workbench/extensions/agent/AgentPanelRoot.vue index 1a518a06fbe..c9dee13f5a6 100644 --- a/src/workbench/extensions/agent/AgentPanelRoot.vue +++ b/src/workbench/extensions/agent/AgentPanelRoot.vue @@ -126,6 +126,10 @@ import { resolveDebugPanelEnabled } from './crdt/crdtDebugGate' import { attachDocOpMinter } from './crdt/docOpMinter' +import { + clearPersistedDocId, + reconcilePersistedDocId +} from './crdt/persistedDocId' import { attachRestoreOpMinter } from './crdt/restoreOpMinter' import { useAgentCrdtFollower } from './crdt/useAgentCrdtFollower' @@ -470,7 +474,12 @@ watch( { immediate: true } ) -const workflowDetached = computed(() => selectedTarget.value === null) +const restorableDocId = ref(reconcilePersistedDocId()) +const workflowDetached = computed( + () => + selectedTarget.value === null && + (!agentPanelStore.canRestoreWorkflow || restorableDocId.value === null) +) // 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 @@ -630,7 +639,16 @@ const { initialize: agentPanelStore.initializeTargetTracking, 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 () => { try { await refreshCloudWorkflowIds() @@ -656,8 +674,30 @@ const isSending = computed( () => sessionIsSending.value || composerStore.submission?.phase === 'pending' ) +watch( + [() => 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 followerWorkflowId = computed(() => { + if (workflowDetached.value) return null + if (boundWorkflowId.value !== null) return boundWorkflowId.value + const active = workflowStore.activeWorkflow + if (active === null) return null + return restorableWorkflowIdFor(active.path) +}) + const isBoundWorkflowActive = computed(() => { - const bound = boundWorkflowId.value + const bound = followerWorkflowId.value const active = workflowStore.activeWorkflow return ( bound !== null && @@ -676,7 +716,7 @@ const { enqueueHumanOperations, docInputNames } = useAgentCrdtFollower( - boundWorkflowId, + followerWorkflowId, () => resolvedUserInfo.value?.id ?? null, isBoundWorkflowActive, // `app.isGraphReady` is a plain getter; reading `canvasStore.canvas` (set @@ -720,14 +760,16 @@ const { // this stays the bound workflow's own root id through a tab switch instead of // tracking whichever graph the switch is loading. function boundRootGraphId(): RootGraphId | null { - const bound = boundWorkflowId.value + const bound = followerWorkflowId.value if (bound === null) return null const id = boundOrOpenWorkflowFor(bound)?.activeState?.id return id === undefined ? null : toRootGraphId(id) } const docOpMinter = attachDocOpMinter({ isEnabled: () => agentPanelStore.enabled, - isDocBound: () => isBoundWorkflowActive.value, + isDocBound: () => + crdtStatus.value.connected && + crdtStatus.value.workflowId === followerWorkflowId.value, enqueue: enqueueHumanOperations, getGraph: () => (app.isGraphReady ? app.rootGraph : null), boundRootGraphId, @@ -735,7 +777,9 @@ const docOpMinter = attachDocOpMinter({ }) const restoreOpMinter = attachRestoreOpMinter({ isEnabled: () => agentPanelStore.enabled, - isDocBound: () => isBoundWorkflowActive.value, + isDocBound: () => + crdtStatus.value.connected && + crdtStatus.value.workflowId === followerWorkflowId.value, enqueue: enqueueHumanOperations, getGraph: () => (app.isGraphReady ? app.rootGraph : null), isRestoringState: () => @@ -943,6 +987,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) reportWorkflowBound(data.workflow_id, previousWorkflowId, 'active_tab') @@ -978,6 +1023,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) reportWorkflowBound(data.workflow_id, previousWorkflowId, 'active_tab') useTelemetry()?.trackAgentWorkflowApplied({ @@ -1113,6 +1159,8 @@ void refreshHistory() async function onSelectHistory(id: string): Promise { composerStore.invalidateSubmission() cancelWorkflowSelection() + clearPersistedDocId() + restorableDocId.value = null agentPanelStore.beginWorkflowRestoration() exitNodeSelectionMode() if (await loadThread(id)) @@ -1260,6 +1308,8 @@ function onNewChat(source?: 'new_chat_button' | 'history_delete'): void { exitNodeSelectionMode() composerStore.setWorkflowReferences([]) composerStore.resetPromptHistory() + clearPersistedDocId() + restorableDocId.value = null newChat(source) if (selectionTags.value.length) agentPanelStore.retainWorkflowTarget() else agentPanelStore.startFollowingVisibleWorkflow() diff --git a/src/workbench/extensions/agent/composables/useAgentDockMount.test.ts b/src/workbench/extensions/agent/composables/useAgentDockMount.test.ts index bfd477ac796..b9fbdd96d21 100644 --- a/src/workbench/extensions/agent/composables/useAgentDockMount.test.ts +++ b/src/workbench/extensions/agent/composables/useAgentDockMount.test.ts @@ -1,4 +1,5 @@ import { beforeEach, describe, expect, it, vi } from 'vitest' +import { defineComponent } from 'vue' import { useAgentPanelStore } from '@/workbench/extensions/agent/stores/agent/agentPanelStore' @@ -6,11 +7,15 @@ import { useAgentDockMount } from './useAgentDockMount' vi.mock(import('@/platform/telemetry')) 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 { @@ -27,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 () => { @@ -54,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/agentCrdtDocLifecycle.test.ts b/src/workbench/extensions/agent/crdt/agentCrdtDocLifecycle.test.ts index 53469ddfcae..b40b892f102 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' @@ -9,6 +10,11 @@ import { SUBSCRIBE_CATCHUP_GRACE_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'), () => ({ @@ -342,6 +348,46 @@ describe('AgentCrdtDocLifecycle ack timeout', () => { }) }) +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([ + fromPartial({ type: 'reload' }) + ]) + // 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) + }) +}) + describe('AgentCrdtDocLifecycle refusal exhaustion', () => { beforeEach(() => { vi.useFakeTimers() diff --git a/src/workbench/extensions/agent/crdt/agentCrdtDocLifecycle.ts b/src/workbench/extensions/agent/crdt/agentCrdtDocLifecycle.ts index 56af873228b..0522d961035 100644 --- a/src/workbench/extensions/agent/crdt/agentCrdtDocLifecycle.ts +++ b/src/workbench/extensions/agent/crdt/agentCrdtDocLifecycle.ts @@ -1,32 +1,16 @@ 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' + +// `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. -// 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 @@ -99,72 +83,6 @@ export const STALE_AFTER_MS = 30_000 * `usedCatchUpGrace`. */ export const SUBSCRIBE_CATCHUP_GRACE_MS = 2_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 @@ -221,7 +139,7 @@ export class AgentCrdtDocLifecycle { ) {} readPersistedDocId(): string | null { - return readPersistedDocId() + return reconcilePersistedDocId() } clearPersistedDocId(): void { diff --git a/src/workbench/extensions/agent/crdt/docFrameClient.ts b/src/workbench/extensions/agent/crdt/docFrameClient.ts index d132360a521..8d3680541ba 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 } +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..1ba0c822db1 --- /dev/null +++ b/src/workbench/extensions/agent/crdt/persistedDocId.test.ts @@ -0,0 +1,209 @@ +import { fromPartial } from '@total-typescript/shoehorn' +import { beforeEach, describe, expect, it, vi } from 'vitest' + +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, + 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([ + fromPartial({ type: 'reload' }) + ]) +} + +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 record whose expiry is not finite, even on a reload', () => { + // Written as raw JSON on purpose: `JSON.stringify(Infinity)` emits + // `null`, so the only way to reproduce what a hostile or corrupted + // record actually looks like on the wire is the out-of-range literal + // that `JSON.parse` turns back into `Infinity`. + sessionStorage.setItem( + DOC_ID_SESSION_KEY, + '{"docId":"wf-1","nonce":"a-different-page-load","expiresAt":1e400}' + ) + // Reload is the permissive path: it is the one navigation type allowed + // to adopt a foreign nonce, so it is where a never-expiring record would + // be handed back instead of rejected. + asReloadNavigation() + + expect(reconcilePersistedDocId()).toBeNull() + expect(rawRecord()).toBeNull() + }) + + it('drops a record whose expiry exceeds the five-minute bound', () => { + writeForeignRecord( + 'wf-1', + Date.now() + DOC_ID_TTL_MS + MAX_AGENT_STORAGE_CLOCK_SKEW_MS + 1_000 + ) + 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') + + 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() + }) + + 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', () => { + 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) + 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', () => { + persistDocId('wf-1') + + clearWorkflowRestoreState() + + expect(rawRecord()).toBeNull() + }) + + it('signing out clears it', () => { + 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..b14ecab3597 --- /dev/null +++ b/src/workbench/extensions/agent/crdt/persistedDocId.ts @@ -0,0 +1,126 @@ +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' + +// 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 + +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) => 'type' in entry && entry.type === 'reload') +} + +export function reconcilePersistedDocId(): string | null { + try { + const raw = safeSessionStorage()?.getItem(DOC_ID_SESSION_KEY) + if (!raw) return 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 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 + // 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 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 + } + const now = Date.now() + if ( + now >= record.expiresAt || + record.expiresAt > now + DOC_ID_TTL_MS + MAX_AGENT_STORAGE_CLOCK_SKEW_MS + ) { + clearPersistedDocId() + return null + } + if (record.nonce !== currentPageSessionNonce()) { + if (!isReloadNavigation()) { + clearPersistedDocId() + return null + } + // Adoption preserves the original expiry, so reloads cannot extend the + // fallback window. + writeRecord({ + docId: record.docId, + nonce: currentPageSessionNonce(), + expiresAt: record.expiresAt + }) + } + return record.docId + } catch { + // 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 + } +} + +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 087611dcbb2..ac0ac19841d 100644 --- a/src/workbench/extensions/agent/crdt/useAgentCrdtFollower.test.ts +++ b/src/workbench/extensions/agent/crdt/useAgentCrdtFollower.test.ts @@ -28,8 +28,12 @@ import type { BatchOutcome, OpSenderDeps } from './opSender' 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() @@ -384,6 +388,27 @@ describe('useAgentCrdtFollower', () => { unmount() }) + it('reports a connection only after the server acknowledges it', async () => { + const { unmount, workflowId, status } = mountFollower('wf-1') + + expect(status().connected).toBe(false) + + dispatchFrame('doc_subscribed', { ok: true, workflowId: 'wf-1' }) + expect(status().connected).toBe(true) + + workflowId.value = 'wf-2' + await nextTick() + expect(status().connected).toBe(false) + + dispatchFrame('doc_subscribed', { ok: true, workflowId: 'wf-2' }) + expect(status().connected).toBe(true) + + bridge().subscribedWorkflowId = null + dispatchFrame('doc_subscribed', { ok: false, workflowId: 'wf-2' }) + expect(status().connected).toBe(false) + unmount() + }) + it('FE-1901: retries a refused subscribe with bounded exponential backoff', () => { vi.useFakeTimers() const { unmount } = mountFollower('wf-1') @@ -818,6 +843,21 @@ describe('useAgentCrdtFollower', () => { unmount() }) + 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('surfaces applied updates and the last frame type in status', () => { const { unmount, status } = mountFollower('wf-1') bridge().follower.updatesApplied = 3 diff --git a/src/workbench/extensions/agent/crdt/useAgentCrdtFollower.ts b/src/workbench/extensions/agent/crdt/useAgentCrdtFollower.ts index 2e1b8922960..63810e3dc7e 100644 --- a/src/workbench/extensions/agent/crdt/useAgentCrdtFollower.ts +++ b/src/workbench/extensions/agent/crdt/useAgentCrdtFollower.ts @@ -342,7 +342,7 @@ function startAgentCrdtFollower( events: AgentCrdtFollowerEvents, applierDeps: AgentCrdtApplierDeps ) { - const connected = ref(false) + const acknowledgedWorkflowId = ref(null) const updatesApplied = ref(0) const lastFrameType = ref(null) const subscribedWorkflowId = ref(null) @@ -363,7 +363,7 @@ function startAgentCrdtFollower( () => subscribedWorkflowId.value, () => bridge.resubscribe(), () => { - connected.value = false + acknowledgedWorkflowId.value = null } ) const tabId = createUuidv4() @@ -490,7 +490,7 @@ function startAgentCrdtFollower( message?: unknown } | null const ok = detail?.ok === true - connected.value = ok + acknowledgedWorkflowId.value = ok ? bridge.subscribedWorkflowId : null lastFrameType.value = event.type recordDevEvent('doc_subscribed', event.detail ?? null) if (ok) { @@ -559,7 +559,7 @@ function startAgentCrdtFollower( projection.replaceOnNextFrame(detail.workflowId) sender.abortAll() events.onReset?.(detail.workflowId) - connected.value = false + acknowledgedWorkflowId.value = null updatesApplied.value = 0 lastFrameType.value = event.type lifecycle.clearStaleProbe() @@ -593,7 +593,7 @@ function startAgentCrdtFollower( // 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() const detail = @@ -629,7 +629,7 @@ function startAgentCrdtFollower( lifecycle.onSubscribeSent(detail.workflowId) } const onReconnected: EventListener = () => { - connected.value = false + acknowledgedWorkflowId.value = null lifecycle.onReconnected() recordDevEvent('reconnected', null) bridge.resubscribe() @@ -779,7 +779,7 @@ function startAgentCrdtFollower( // collected changes to apply, the graph watcher covers readiness. const justActivated = active && previous?.[1] === false lifecycle.clearForRetarget() - connected.value = false + acknowledgedWorkflowId.value = null pendingLiveNodeIds.clear() if (!active) { deactivateTarget(next, previous?.[0] ?? null) @@ -821,7 +821,7 @@ function startAgentCrdtFollower( const status = computed(() => ({ enabled: true, - connected: connected.value, + connected: acknowledgedWorkflowId.value !== null, workflowId: subscribedWorkflowId.value, updatesApplied: updatesApplied.value, lastFrameType: lastFrameType.value, 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 new file mode 100644 index 00000000000..16bff73c4df --- /dev/null +++ b/src/workbench/extensions/agent/stores/agent/agentWorkflowTabBindingStorage.test.ts @@ -0,0 +1,100 @@ +import { describe, expect, it } from 'vitest' + +import { MAX_AGENT_STORAGE_CLOCK_SKEW_MS } from '@/workbench/extensions/agent/persistenceTime' + +import { + liveAgentWorkflowTabBindings, + readPersistedAgentWorkflowTabPath +} from './agentWorkflowTabBindingStorage' + +describe('liveAgentWorkflowTabBindings', () => { + const now = Date.UTC(2026, 8, 22) + const binding = { + tabPath: 'workflows/example.json', + graphId: 'graph-1' + } + + 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 } }, + now + ) + ).toEqual({}) + }) + + it('keeps a finite timestamp within the retention window', () => { + const record = { ...binding, confirmedAt: now } + + expect(liveAgentWorkflowTabBindings({ workflow: record }, now)).toEqual({ + 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 }) + }) +}) + +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 + ) + }) +}) 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..ee15f9bab6c --- /dev/null +++ b/src/workbench/extensions/agent/stores/agent/agentWorkflowTabBindingStorage.ts @@ -0,0 +1,60 @@ +import { MAX_AGENT_STORAGE_CLOCK_SKEW_MS } from '@/workbench/extensions/agent/persistenceTime' + +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 isRecord(value: unknown): value is Record { + return typeof value === 'object' && value !== null +} + +function isPersistedBinding( + value: unknown +): value is PersistedAgentWorkflowTabBinding { + if (!isRecord(value)) return false + const { tabPath, graphId, confirmedAt } = value + return ( + typeof tabPath === 'string' && + (graphId === null || typeof graphId === 'string') && + typeof confirmedAt === 'number' && + Number.isFinite(confirmedAt) + ) +} + +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 <= now + MAX_AGENT_STORAGE_CLOCK_SKEW_MS && + 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 (!isRecord(parsed)) return undefined + return liveAgentWorkflowTabBindings(parsed, 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 6596507b10c..2dc0ff52d61 100644 --- a/src/workbench/extensions/agent/stores/agent/agentWorkflowTabBindingStore.ts +++ b/src/workbench/extensions/agent/stores/agent/agentWorkflowTabBindingStore.ts @@ -11,44 +11,17 @@ import { StorageKeys } from '@/platform/workflow/persistence/base/storageKeys' -const BINDING_TTL_MS = 30 * 24 * 60 * 60 * 1000 - -interface PersistedBinding { - tabPath: string - graphId: string | null - confirmedAt: number -} - -type PersistedBindings = Record +import { liveAgentWorkflowTabBindings } from './agentWorkflowTabBindingStorage' +import type { + PersistedAgentWorkflowTabBinding, + PersistedAgentWorkflowTabBindings +} from './agentWorkflowTabBindingStorage' 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 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 - ) - ) -} - function graphIdOf(tab: ComfyWorkflow): string | undefined { const activeId = tab.activeState?.id if (activeId !== undefined) return activeId @@ -70,17 +43,22 @@ export const useAgentWorkflowTabBindingStore = defineStore( 'agentWorkflowTabBinding', () => { clearLegacyAgentStorage() - const tabByWorkflow = useLocalStorage( + const tabByWorkflow = useLocalStorage( StorageKeys.agentWorkflowTabBindings(getWorkspaceId()), {} ) - tabByWorkflow.value = liveBindings(tabByWorkflow.value, Date.now()) + tabByWorkflow.value = liveAgentWorkflowTabBindings( + tabByWorkflow.value, + Date.now() + ) const workflows = useWorkflowStore() 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 @@ -102,7 +80,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 @@ -114,7 +92,7 @@ export const useAgentWorkflowTabBindingStore = defineStore( function blockedByOccupant( workflowId: string, - record: PersistedBinding + record: PersistedAgentWorkflowTabBinding ): boolean { const occupant = workflows.openWorkflows.find( (tab) => tab.path === record.tabPath