From 76e7f69f35365d1d46c1583eb7332038ff872e35 Mon Sep 17 00:00:00 2001 From: Christian Byrne Date: Mon, 26 Oct 2026 19:57:53 +0000 Subject: [PATCH 1/9] fix(agent): re-handshake the agent socket on an off-cloud workspace switch FE-3592. Off-cloud the agent events socket carries a workspace-scoped bearer: agentAuth.ts mints it with getWorkspaceAuthTokenOrThrow and agentSocketAuthParams puts it in the socket URL. The only re-handshake trigger keyed on authStore.userId ?? apiKeyAuthStore.currentUser?.id, which has no workspace term. Off-cloud, teamWorkspaceStore.executeWorkspaceSwitch returns before the window.location.reload the cloud path takes, so the page does not reload and nothing else reconnects the socket. Switching workspace mid-session therefore left the open socket on the previous workspace's bearer for the life of the connection, while REST re-minted per call through withAgentAuth. The two then disagree about the principal, which is the class of defect #21575 shipped to fix (wrong principal, stale customers.has_fund, spurious 402 for a funded workspace). This matters now rather than later because the off-cloud path is the one in gradual rollout. Adds the workspace to the key, with an equality guard so an unchanged pair does not reconnect. Two tests: a workspace switch reconnects and re-resolves identity, and an unchanged workspace does not. Verified red without the fix. --- .../extensions/agent/AgentPanelRoot.test.ts | 40 +++++++++++++++++++ .../extensions/agent/AgentPanelRoot.vue | 17 +++++--- 2 files changed, 52 insertions(+), 5 deletions(-) diff --git a/src/workbench/extensions/agent/AgentPanelRoot.test.ts b/src/workbench/extensions/agent/AgentPanelRoot.test.ts index f9d7e10f73c..17623938412 100644 --- a/src/workbench/extensions/agent/AgentPanelRoot.test.ts +++ b/src/workbench/extensions/agent/AgentPanelRoot.test.ts @@ -16025,6 +16025,46 @@ describe('AgentPanelRoot agent socket', () => { } ) + // The socket credential is workspace-scoped off-cloud, and an off-cloud + // workspace switch does not reload the page, so nothing else re-handshakes + // the socket. Without the workspace in the key it keeps the previous + // workspace's bearer for the life of the connection (FE-3592). + it('reconnects the socket and looks the identity up again on a workspace switch', async () => { + const reset = vi.fn() + vi.mocked(resolveAgentIdentity).mockReturnValue({ + state: ref({ + status: 'resolved', + userId: 'account-a' + }), + reset, + stop: () => {} + }) + signInAs({ firebase: 'account-a', apiKeyUser: null }) + const workspaces = useTeamWorkspaceStore() + Object.assign(workspaces, { activeWorkspaceId: 'ws-a' }) + render(AgentPanelRoot, { global: { plugins: [i18n] } }) + agentSocket.reconnect.mockClear() + + Object.assign(workspaces, { activeWorkspaceId: 'ws-b' }) + await nextTick() + + expect(agentSocket.reconnect).toHaveBeenCalledOnce() + expect(reset).toHaveBeenCalledOnce() + }) + + it('leaves the socket alone when neither the account nor the workspace moves', async () => { + signInAs({ firebase: 'account-a', apiKeyUser: null }) + const workspaces = useTeamWorkspaceStore() + Object.assign(workspaces, { activeWorkspaceId: 'ws-a' }) + render(AgentPanelRoot, { global: { plugins: [i18n] } }) + agentSocket.reconnect.mockClear() + + Object.assign(workspaces, { activeWorkspaceId: 'ws-a' }) + await nextTick() + + expect(agentSocket.reconnect).not.toHaveBeenCalled() + }) + it('opens the events socket under the api base path', async () => { vi.mocked(api.apiURL).mockImplementation((route) => `/comfy/api${route}`) render(AgentPanelRoot, { global: { plugins: [i18n] } }) diff --git a/src/workbench/extensions/agent/AgentPanelRoot.vue b/src/workbench/extensions/agent/AgentPanelRoot.vue index b0bac994b68..40a2a21843d 100644 --- a/src/workbench/extensions/agent/AgentPanelRoot.vue +++ b/src/workbench/extensions/agent/AgentPanelRoot.vue @@ -270,10 +270,17 @@ onBeforeUnmount(() => agentIdentity.stop()) const authStore = useAuthStore() const apiKeyAuthStore = useApiKeyAuthStore() -const agentAccountId = computed( - () => authStore.userId ?? apiKeyAuthStore.currentUser?.id ?? null -) -watch(agentAccountId, () => { +const teamWorkspaceStore = useTeamWorkspaceStore() +// The socket credential is workspace-scoped off-cloud (agentAuth.ts mints a +// workspace bearer and puts it in the socket URL), and an off-cloud workspace +// switch does not reload the page the way the cloud path does, so the workspace +// belongs in this key or the socket keeps the previous workspace's bearer. +const agentSocketIdentity = computed(() => [ + authStore.userId ?? apiKeyAuthStore.currentUser?.id ?? null, + teamWorkspaceStore.activeWorkspaceId ?? null +]) +watch(agentSocketIdentity, (next, previous) => { + if (next[0] === previous[0] && next[1] === previous[1]) return events.reconnect() agentIdentity.reset() }) @@ -638,7 +645,7 @@ onBeforeUnmount(() => }) ) const { withConsent } = useAgentConsent() -const workspaceStore = useTeamWorkspaceStore() +const workspaceStore = teamWorkspaceStore const onboardingKey = computed(() => scopedOnboardingKey( resolvedUserInfo.value?.id, From e270516d61a78ae8f554fd8ee19125356181dc12 Mon Sep 17 00:00:00 2001 From: Christian Byrne Date: Wed, 28 Oct 2026 03:50:08 +0000 Subject: [PATCH 2/9] fix(agent): do not handshake on the null leg of a workspace switch Three paths clear the workspace before setting the next one: the desktop host follow, the lazy first read of the workspace store off-cloud, and sign-out clearing the workspace separately from the account. With the workspace in the socket key, each of those produced two handshakes for one change. The null leg is the harmful one: off-cloud the run token can be undefined while the workspace is unset, so that socket fails auth and goes onto the backoff, and the reset discards an identity lookup still in flight. The credential in use is still the previous workspace's, so waiting costs nothing. An account change is never skipped, so sign-out still drops the socket -- covered by its own test. --- .../extensions/agent/AgentPanelRoot.test.ts | 48 +++++++++++++++++++ .../extensions/agent/AgentPanelRoot.vue | 22 +++++++-- 2 files changed, 65 insertions(+), 5 deletions(-) diff --git a/src/workbench/extensions/agent/AgentPanelRoot.test.ts b/src/workbench/extensions/agent/AgentPanelRoot.test.ts index 17623938412..04a3473b411 100644 --- a/src/workbench/extensions/agent/AgentPanelRoot.test.ts +++ b/src/workbench/extensions/agent/AgentPanelRoot.test.ts @@ -16052,6 +16052,54 @@ describe('AgentPanelRoot agent socket', () => { expect(reset).toHaveBeenCalledOnce() }) + // Three paths clear the workspace before setting the next one: the desktop host + // follow, the lazy first read of the store off-cloud, and sign-out. Handshaking on + // the null leg mints against a workspace that is not settled, so the socket fails + // auth and backs off, and it discards an identity lookup still in flight. + it('handshakes once for a workspace switch that passes through null', async () => { + const reset = vi.fn() + vi.mocked(resolveAgentIdentity).mockReturnValue({ + state: ref({ + status: 'resolved', + userId: 'account-a' + }), + reset, + stop: () => {} + }) + signInAs({ firebase: 'account-a', apiKeyUser: null }) + const workspaces = useTeamWorkspaceStore() + Object.assign(workspaces, { activeWorkspaceId: 'ws-a' }) + render(AgentPanelRoot, { global: { plugins: [i18n] } }) + agentSocket.reconnect.mockClear() + + Object.assign(workspaces, { activeWorkspaceId: null }) + await nextTick() + expect(agentSocket.reconnect).not.toHaveBeenCalled() + expect(reset).not.toHaveBeenCalled() + + Object.assign(workspaces, { activeWorkspaceId: 'ws-b' }) + await nextTick() + + expect(agentSocket.reconnect).toHaveBeenCalledOnce() + expect(reset).toHaveBeenCalledOnce() + }) + + // Sign-out clears the account and the workspace separately, and the socket has to + // drop regardless of which half the watcher sees first. + it('still drops the socket when a sign-out clears the workspace too', async () => { + signInAs({ firebase: 'account-a', apiKeyUser: null }) + const workspaces = useTeamWorkspaceStore() + Object.assign(workspaces, { activeWorkspaceId: 'ws-a' }) + render(AgentPanelRoot, { global: { plugins: [i18n] } }) + agentSocket.reconnect.mockClear() + + signInAs({ firebase: null, apiKeyUser: null }) + Object.assign(workspaces, { activeWorkspaceId: null }) + await nextTick() + + expect(agentSocket.reconnect).toHaveBeenCalledOnce() + }) + it('leaves the socket alone when neither the account nor the workspace moves', async () => { signInAs({ firebase: 'account-a', apiKeyUser: null }) const workspaces = useTeamWorkspaceStore() diff --git a/src/workbench/extensions/agent/AgentPanelRoot.vue b/src/workbench/extensions/agent/AgentPanelRoot.vue index 40a2a21843d..7ea40d1ed9c 100644 --- a/src/workbench/extensions/agent/AgentPanelRoot.vue +++ b/src/workbench/extensions/agent/AgentPanelRoot.vue @@ -279,11 +279,23 @@ const agentSocketIdentity = computed(() => [ authStore.userId ?? apiKeyAuthStore.currentUser?.id ?? null, teamWorkspaceStore.activeWorkspaceId ?? null ]) -watch(agentSocketIdentity, (next, previous) => { - if (next[0] === previous[0] && next[1] === previous[1]) return - events.reconnect() - agentIdentity.reset() -}) +watch( + agentSocketIdentity, + ([account, workspace], [wasAccount, wasWorkspace]) => { + if (account === wasAccount && workspace === wasWorkspace) return + // A workspace change arrives as A -> null -> B on three paths: the desktop host + // follow, the lazy first read of the workspace store off-cloud, and sign-out + // clearing the workspace separately from the account. Handshaking on the null leg + // would mint against a workspace that is not settled yet -- off-cloud the token can + // be undefined there, so the socket fails auth and backs off -- and it would discard + // an identity lookup still in flight. Waiting for the workspace costs nothing: the + // credential in use is still the previous workspace's, and B reconnects on arrival. + // An account change is never skipped, so sign-out still drops the socket. + if (workspace === null && account === wasAccount && account !== null) return + events.reconnect() + agentIdentity.reset() + } +) function onPaywallAction( action: AgentPaywallAction, From 7a99905a9c7f2911568e75dba2c8837c6c45339e Mon Sep 17 00:00:00 2001 From: Christian Byrne Date: Wed, 28 Oct 2026 08:17:31 +0000 Subject: [PATCH 3/9] fix(agent): only skip a null workspace when Desktop is not pinning one The transient-null guard treated every null as a leg of A -> null -> B, but followDesktopHostWorkspace clears the id before refreshing and leaves it null when the refresh fails or the host workspace is not listed. That null never resolves, so the socket kept serving the previous workspace while the host had already moved -- a worse failure than the double handshake the guard avoids, because Desktop mints REST and new sockets against the host workspace while the live socket still holds the old one. The skip now applies only when Desktop pins no workspace. The test fails without the condition. --- .../extensions/agent/AgentPanelRoot.test.ts | 50 +++++++++++++++++++ .../extensions/agent/AgentPanelRoot.vue | 15 +++++- 2 files changed, 63 insertions(+), 2 deletions(-) diff --git a/src/workbench/extensions/agent/AgentPanelRoot.test.ts b/src/workbench/extensions/agent/AgentPanelRoot.test.ts index 04a3473b411..67d695b6357 100644 --- a/src/workbench/extensions/agent/AgentPanelRoot.test.ts +++ b/src/workbench/extensions/agent/AgentPanelRoot.test.ts @@ -1,5 +1,10 @@ import { fetchRequests, respondToFetch } from '@comfyorg/test-utils/fetch' import { fromPartial } from '@total-typescript/shoehorn' +import { + startDesktopHostSession, + stopDesktopHostSession +} from '@/platform/auth/desktopHost/desktopHostSession' +import type { DesktopHostAuthState } from '@/platform/auth/desktopHost/desktopHostAuthBridge' import { setImmediate } from 'node:timers/promises' import type { @@ -16084,6 +16089,51 @@ describe('AgentPanelRoot agent socket', () => { expect(reset).toHaveBeenCalledOnce() }) + // followDesktopHostWorkspace clears the id before refreshing and leaves it null if + // the refresh fails or the host workspace is not listed. That null never resolves, + // so skipping it would leave the socket serving the previous workspace while Desktop + // has already moved to another one. + it('drops the socket when the workspace goes null while Desktop pins another', async () => { + const reset = vi.fn() + vi.mocked(resolveAgentIdentity).mockReturnValue({ + state: ref({ + status: 'resolved', + userId: 'account-a' + }), + reset, + stop: () => {} + }) + const hostOn = (workspaceId: string) => + fromPartial({ + status: 'signed_in', + userId: 'account-a', + workspaceId + }) + await startDesktopHostSession({ + getState: async () => hostOn('ws-host'), + getWorkspaceToken: async () => 'host-token', + requestSignIn: async () => hostOn('ws-host'), + signOut: async () => ({ status: 'signed_out' }), + switchWorkspace: async () => hostOn('ws-host'), + onChanged: () => () => {} + }) + try { + signInAs({ firebase: 'account-a', apiKeyUser: null }) + const workspaces = useTeamWorkspaceStore() + Object.assign(workspaces, { activeWorkspaceId: 'ws-a' }) + render(AgentPanelRoot, { global: { plugins: [i18n] } }) + agentSocket.reconnect.mockClear() + + Object.assign(workspaces, { activeWorkspaceId: null }) + await nextTick() + + expect(agentSocket.reconnect).toHaveBeenCalledOnce() + expect(reset).toHaveBeenCalledOnce() + } finally { + stopDesktopHostSession() + } + }) + // Sign-out clears the account and the workspace separately, and the socket has to // drop regardless of which half the watcher sees first. it('still drops the socket when a sign-out clears the workspace too', async () => { diff --git a/src/workbench/extensions/agent/AgentPanelRoot.vue b/src/workbench/extensions/agent/AgentPanelRoot.vue index 7ea40d1ed9c..e5552924e9d 100644 --- a/src/workbench/extensions/agent/AgentPanelRoot.vue +++ b/src/workbench/extensions/agent/AgentPanelRoot.vue @@ -47,6 +47,7 @@ import { isHdrImageFilename } from '@/utils/hdrFormatUtil' import type { DroppedAsset } from '@/utils/eventUtils' import { useAssetsStore } from '@/stores/assetsStore' import { useApiKeyAuthStore } from '@/stores/apiKeyAuthStore' +import { desktopHostUser } from '@/platform/auth/desktopHost/desktopHostSession' import { useAuthStore } from '@/stores/authStore' import { AGENT_ATTACH_ACCEPT, @@ -290,8 +291,18 @@ watch( // be undefined there, so the socket fails auth and backs off -- and it would discard // an identity lookup still in flight. Waiting for the workspace costs nothing: the // credential in use is still the previous workspace's, and B reconnects on arrival. - // An account change is never skipped, so sign-out still drops the socket. - if (workspace === null && account === wasAccount && account !== null) return + // An account change is never skipped, so sign-out still drops the socket. Nor is + // a null skipped while Desktop pins a workspace: followDesktopHostWorkspace clears + // the id before refreshing and leaves it null when the refresh fails or the + // workspace is not listed, and that null never resolves. Holding the socket through + // it would keep serving the previous workspace after the host moved to another. + if ( + workspace === null && + account === wasAccount && + account !== null && + desktopHostUser.value?.workspaceId == null + ) + return events.reconnect() agentIdentity.reset() } From 0c4929a138390300035e83195031e8644b19bc76 Mon Sep 17 00:00:00 2001 From: Christian Byrne Date: Thu, 29 Oct 2026 02:01:34 +0000 Subject: [PATCH 4/9] test(agent): give the api mock resetSocket authStore resets the socket when the signed-in identity changes, and the desktop-host session the new workspace test starts is such a change. The file's api mock had no resetSocket, so the watcher rejected outside any test and vitest failed the shard while reporting every test passed. --- src/workbench/extensions/agent/AgentPanelRoot.test.ts | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/workbench/extensions/agent/AgentPanelRoot.test.ts b/src/workbench/extensions/agent/AgentPanelRoot.test.ts index 67d695b6357..8175d8c8944 100644 --- a/src/workbench/extensions/agent/AgentPanelRoot.test.ts +++ b/src/workbench/extensions/agent/AgentPanelRoot.test.ts @@ -154,6 +154,9 @@ vi.mock(import('@/scripts/api'), () => ({ fetch(route.startsWith('/api') ? route : `/api${route}`, options), getServerFeature, socket: { readyState: 1, send: socketSend }, + // authStore resets the socket when the signed-in identity changes, which a + // desktop-host session in these tests does. + resetSocket: vi.fn(async () => {}), dispatchCustomEvent: vi.fn(), addEventListener: ws.add, removeEventListener: ws.remove, From 8fcc15bc25e53d4c4cd41812625503b7e9a03f91 Mon Sep 17 00:00:00 2001 From: Christian Byrne Date: Thu, 29 Oct 2026 01:27:46 -0700 Subject: [PATCH 5/9] fix(agent): reauthenticate Desktop workspace changes --- .../tests/agent/agentWorkspaceSwitch.spec.ts | 54 ++++++++ .../agent/agentWorkspaceSwitchFixture.ts | 124 ++++++++++++++++++ .../extensions/agent/AgentPanelRoot.test.ts | 61 ++++++--- .../extensions/agent/AgentPanelRoot.vue | 33 ++--- 4 files changed, 236 insertions(+), 36 deletions(-) create mode 100644 browser_tests/tests/agent/agentWorkspaceSwitch.spec.ts create mode 100644 browser_tests/tests/agent/agentWorkspaceSwitchFixture.ts diff --git a/browser_tests/tests/agent/agentWorkspaceSwitch.spec.ts b/browser_tests/tests/agent/agentWorkspaceSwitch.spec.ts new file mode 100644 index 00000000000..5100023944b --- /dev/null +++ b/browser_tests/tests/agent/agentWorkspaceSwitch.spec.ts @@ -0,0 +1,54 @@ +import { expect } from '@playwright/test' +import { + PERSONAL_WORKSPACE_NAME, + TEAM_WORKSPACE_NAME +} from '@e2e/fixtures/data/workspaceSwitcher' +import { agentWorkspaceSwitcherTest as test } from '@e2e/tests/agent/agentWorkspaceSwitchFixture' + +test.describe('Agent workspace switching', { tag: '@ui' }, () => { + test('retires the old socket and recovers the panel under the new workspace identity', async ({ + agentIdentityReads, + agentPanel, + getAgentSocket, + nextAgentSocket, + page + }) => { + await agentPanel.open() + await expect(agentPanel.composer).toBeVisible() + const originalSocket = await getAgentSocket() + expect(new URL(originalSocket.url()).searchParams.get('token')).toBe( + 'mock-workspace-token-ws-personal' + ) + let originalSocketClosed = false + originalSocket.onClose(() => { + originalSocketClosed = true + }) + const replacementSocketOpened = nextAgentSocket() + + await page.getByRole('button', { name: 'Current user' }).click() + await expect(page.getByTestId('workspace-switcher-trigger')).toContainText( + PERSONAL_WORKSPACE_NAME + ) + await page.getByTestId('workspace-switcher-trigger').click() + await page + .getByTestId('workspace-switcher-panel') + .getByText(TEAM_WORKSPACE_NAME, { exact: true }) + .click() + + const replacementSocket = await replacementSocketOpened + await expect.poll(() => originalSocketClosed).toBe(true) + expect(new URL(replacementSocket.url()).searchParams.get('token')).toBe( + 'mock-workspace-token-ws-team' + ) + await expect + .poll(() => agentIdentityReads) + .toContainEqual({ + workspaceId: 'ws-team' + }) + await page.getByRole('button', { name: 'Current user' }).click() + await expect(page.getByTestId('workspace-switcher-trigger')).toContainText( + TEAM_WORKSPACE_NAME + ) + await expect(agentPanel.composer).toBeVisible() + }) +}) diff --git a/browser_tests/tests/agent/agentWorkspaceSwitchFixture.ts b/browser_tests/tests/agent/agentWorkspaceSwitchFixture.ts new file mode 100644 index 00000000000..027aa530096 --- /dev/null +++ b/browser_tests/tests/agent/agentWorkspaceSwitchFixture.ts @@ -0,0 +1,124 @@ +import type { + AgentIdentity, + AgentRunMode, + ListMembersResponse +} from '@comfyorg/ingest-types' +import { mergeTests } from '@playwright/test' + +import type { WorkspaceTokenResponse } from '@/platform/workspace/stores/workspaceAuthStore' + +import { agentTest, bootAgentApp } from '@e2e/fixtures/agentPanelFixture' +import { AgentPanel } from '@e2e/fixtures/components/AgentPanel' +import { emptyAgentThreadList } from '@e2e/fixtures/data/agent/agentThreadList' +import { createBillingCapabilities } from '@e2e/fixtures/data/billingCapabilities' +import { + EMPTY_BILLING_BALANCE, + EMPTY_BILLING_PLANS, + ENDED_STANDARD_BILLING_STATUS +} from '@e2e/fixtures/data/cloudWorkspace' +import { + WORKSPACE_SWITCHER_REMOTE_CONFIG, + WORKSPACE_SWITCHER_WORKSPACES +} from '@e2e/fixtures/data/workspaceSwitcher' +import { jsonRoute } from '@e2e/fixtures/utils/jsonRoute' +import { mockWorkspaceList } from '@e2e/fixtures/utils/workspaceMocks' +import { webSocketFixture } from '@e2e/fixtures/ws' + +interface AgentIdentityRead { + workspaceId: string +} + +const base = mergeTests(agentTest, webSocketFixture) + +export const agentWorkspaceSwitcherTest = base.extend<{ + agentIdentityReads: AgentIdentityRead[] + agentPanel: AgentPanel +}>({ + agentIdentityReads: async ({ page, agentFlagEnabled }, use) => { + const reads: AgentIdentityRead[] = [] + let workspaceId = 'ws-personal' + const runMode: AgentRunMode = { + mode: 'ask_approval', + credit_limit: null + } + + await bootAgentApp(page, agentFlagEnabled, { + features: WORKSPACE_SWITCHER_REMOTE_CONFIG, + settings: { 'Comfy.UseNewMenu': 'Top' }, + beforeNavigate: async (page) => { + await mockWorkspaceList(page, WORKSPACE_SWITCHER_WORKSPACES) + await page.route('**/api/workspace/members**', (route) => + route.fulfill( + jsonRoute({ + members: [], + pagination: { offset: 0, limit: 50, total: 0, has_more: false } + } satisfies ListMembersResponse) + ) + ) + await page.route('**/api/auth/token', async (route) => { + const request = route.request().postDataJSON() as { + workspace_id?: string + } + workspaceId = request.workspace_id ?? 'ws-personal' + const workspace = WORKSPACE_SWITCHER_WORKSPACES.find( + ({ id }) => id === workspaceId + ) + if (!workspace) { + await route.fulfill({ status: 404 }) + return + } + const response: WorkspaceTokenResponse = { + token: `mock-workspace-token-${workspace.id}`, + expires_at: new Date(Date.now() + 60 * 60 * 1000).toISOString(), + user_id: 'uid-1', + workspace: { + id: workspace.id, + name: workspace.name, + type: workspace.type + }, + role: workspace.role, + permissions: [] + } + await route.fulfill(jsonRoute(response)) + }) + await page.route('**/api/auth/session', (route) => + route.fulfill({ status: 204 }) + ) + await page.route('**/api/billing/status', (route) => + route.fulfill(jsonRoute(ENDED_STANDARD_BILLING_STATUS)) + ) + await page.route('**/api/billing/balance', (route) => + route.fulfill(jsonRoute(EMPTY_BILLING_BALANCE)) + ) + await page.route('**/api/billing/plans', (route) => + route.fulfill(jsonRoute(EMPTY_BILLING_PLANS)) + ) + await page.route('**/api/billing/capabilities', (route) => + route.fulfill(jsonRoute(createBillingCapabilities(workspaceId))) + ) + await page.route('**/api/experiment/models', (route) => + route.fulfill(jsonRoute([])) + ) + await page.route('**/api/agent/threads?*', (route) => + route.fulfill(jsonRoute(emptyAgentThreadList())) + ) + await page.route('**/api/agent/run-mode', (route) => + route.fulfill(jsonRoute(runMode)) + ) + await page.route('**/api/agent/identity', (route) => { + reads.push({ workspaceId }) + const identity: AgentIdentity = { + workspace_id: workspaceId, + user_id: 'uid-1' + } + return route.fulfill(jsonRoute(identity)) + }) + } + }) + + await use(reads) + }, + agentPanel: async ({ page }, use) => { + await use(new AgentPanel(page)) + } +}) diff --git a/src/workbench/extensions/agent/AgentPanelRoot.test.ts b/src/workbench/extensions/agent/AgentPanelRoot.test.ts index 8175d8c8944..24c0c65482d 100644 --- a/src/workbench/extensions/agent/AgentPanelRoot.test.ts +++ b/src/workbench/extensions/agent/AgentPanelRoot.test.ts @@ -154,8 +154,6 @@ vi.mock(import('@/scripts/api'), () => ({ fetch(route.startsWith('/api') ? route : `/api${route}`, options), getServerFeature, socket: { readyState: 1, send: socketSend }, - // authStore resets the socket when the signed-in identity changes, which a - // desktop-host session in these tests does. resetSocket: vi.fn(async () => {}), dispatchCustomEvent: vi.fn(), addEventListener: ws.add, @@ -16033,10 +16031,6 @@ describe('AgentPanelRoot agent socket', () => { } ) - // The socket credential is workspace-scoped off-cloud, and an off-cloud - // workspace switch does not reload the page, so nothing else re-handshakes - // the socket. Without the workspace in the key it keeps the previous - // workspace's bearer for the life of the connection (FE-3592). it('reconnects the socket and looks the identity up again on a workspace switch', async () => { const reset = vi.fn() vi.mocked(resolveAgentIdentity).mockReturnValue({ @@ -16060,10 +16054,6 @@ describe('AgentPanelRoot agent socket', () => { expect(reset).toHaveBeenCalledOnce() }) - // Three paths clear the workspace before setting the next one: the desktop host - // follow, the lazy first read of the store off-cloud, and sign-out. Handshaking on - // the null leg mints against a workspace that is not settled, so the socket fails - // auth and backs off, and it discards an identity lookup still in flight. it('handshakes once for a workspace switch that passes through null', async () => { const reset = vi.fn() vi.mocked(resolveAgentIdentity).mockReturnValue({ @@ -16092,10 +16082,6 @@ describe('AgentPanelRoot agent socket', () => { expect(reset).toHaveBeenCalledOnce() }) - // followDesktopHostWorkspace clears the id before refreshing and leaves it null if - // the refresh fails or the host workspace is not listed. That null never resolves, - // so skipping it would leave the socket serving the previous workspace while Desktop - // has already moved to another one. it('drops the socket when the workspace goes null while Desktop pins another', async () => { const reset = vi.fn() vi.mocked(resolveAgentIdentity).mockReturnValue({ @@ -16137,8 +16123,51 @@ describe('AgentPanelRoot agent socket', () => { } }) - // Sign-out clears the account and the workspace separately, and the socket has to - // drop regardless of which half the watcher sees first. + it('reconnects when only the Desktop host workspace moves', async () => { + const reset = vi.fn() + vi.mocked(resolveAgentIdentity).mockReturnValue({ + state: ref({ + status: 'resolved', + userId: 'account-a' + }), + reset, + stop: () => {} + }) + const hostOn = (workspaceId: string) => + fromPartial({ + status: 'signed_in', + userId: 'account-a', + workspaceId + }) + let notifyHostChanged: (state: DesktopHostAuthState) => void = () => {} + await startDesktopHostSession({ + getState: async () => hostOn('ws-a'), + getWorkspaceToken: async () => 'host-token', + requestSignIn: async () => hostOn('ws-a'), + signOut: async () => ({ status: 'signed_out' }), + switchWorkspace: async (workspaceId) => hostOn(workspaceId), + onChanged: (listener) => { + notifyHostChanged = listener + return () => {} + } + }) + try { + signInAs({ firebase: 'account-a', apiKeyUser: null }) + const workspaces = useTeamWorkspaceStore() + Object.assign(workspaces, { activeWorkspaceId: null }) + render(AgentPanelRoot, { global: { plugins: [i18n] } }) + agentSocket.reconnect.mockClear() + + notifyHostChanged(hostOn('ws-b')) + await nextTick() + + expect(agentSocket.reconnect).toHaveBeenCalledOnce() + expect(reset).toHaveBeenCalledOnce() + } finally { + stopDesktopHostSession() + } + }) + it('still drops the socket when a sign-out clears the workspace too', async () => { signInAs({ firebase: 'account-a', apiKeyUser: null }) const workspaces = useTeamWorkspaceStore() diff --git a/src/workbench/extensions/agent/AgentPanelRoot.vue b/src/workbench/extensions/agent/AgentPanelRoot.vue index e5552924e9d..329ae1dca17 100644 --- a/src/workbench/extensions/agent/AgentPanelRoot.vue +++ b/src/workbench/extensions/agent/AgentPanelRoot.vue @@ -272,35 +272,28 @@ onBeforeUnmount(() => agentIdentity.stop()) const authStore = useAuthStore() const apiKeyAuthStore = useApiKeyAuthStore() const teamWorkspaceStore = useTeamWorkspaceStore() -// The socket credential is workspace-scoped off-cloud (agentAuth.ts mints a -// workspace bearer and puts it in the socket URL), and an off-cloud workspace -// switch does not reload the page the way the cloud path does, so the workspace -// belongs in this key or the socket keeps the previous workspace's bearer. const agentSocketIdentity = computed(() => [ authStore.userId ?? apiKeyAuthStore.currentUser?.id ?? null, - teamWorkspaceStore.activeWorkspaceId ?? null + teamWorkspaceStore.activeWorkspaceId ?? null, + desktopHostUser.value?.workspaceId ?? null ]) watch( agentSocketIdentity, - ([account, workspace], [wasAccount, wasWorkspace]) => { - if (account === wasAccount && workspace === wasWorkspace) return - // A workspace change arrives as A -> null -> B on three paths: the desktop host - // follow, the lazy first read of the workspace store off-cloud, and sign-out - // clearing the workspace separately from the account. Handshaking on the null leg - // would mint against a workspace that is not settled yet -- off-cloud the token can - // be undefined there, so the socket fails auth and backs off -- and it would discard - // an identity lookup still in flight. Waiting for the workspace costs nothing: the - // credential in use is still the previous workspace's, and B reconnects on arrival. - // An account change is never skipped, so sign-out still drops the socket. Nor is - // a null skipped while Desktop pins a workspace: followDesktopHostWorkspace clears - // the id before refreshing and leaves it null when the refresh fails or the - // workspace is not listed, and that null never resolves. Holding the socket through - // it would keep serving the previous workspace after the host moved to another. + ( + [account, workspace, hostWorkspace], + [wasAccount, wasWorkspace, wasHostWorkspace] + ) => { + if ( + account === wasAccount && + workspace === wasWorkspace && + hostWorkspace === wasHostWorkspace + ) + return if ( workspace === null && account === wasAccount && account !== null && - desktopHostUser.value?.workspaceId == null + hostWorkspace === null ) return events.reconnect() From d841979e25ef4f5420024e1faa7fed4eda6db7f1 Mon Sep 17 00:00:00 2001 From: Christian Byrne Date: Thu, 29 Oct 2026 01:50:32 -0700 Subject: [PATCH 6/9] test(agent): tighten workspace switch fixtures --- .../agent/agentWorkspaceSwitchFixture.ts | 5 +- .../extensions/agent/AgentPanelRoot.test.ts | 60 +++++++++---------- 2 files changed, 30 insertions(+), 35 deletions(-) diff --git a/browser_tests/tests/agent/agentWorkspaceSwitchFixture.ts b/browser_tests/tests/agent/agentWorkspaceSwitchFixture.ts index 027aa530096..5a93fe7b41b 100644 --- a/browser_tests/tests/agent/agentWorkspaceSwitchFixture.ts +++ b/browser_tests/tests/agent/agentWorkspaceSwitchFixture.ts @@ -1,6 +1,7 @@ import type { AgentIdentity, AgentRunMode, + ExchangeTokenRequest, ListMembersResponse } from '@comfyorg/ingest-types' import { mergeTests } from '@playwright/test' @@ -56,9 +57,7 @@ export const agentWorkspaceSwitcherTest = base.extend<{ ) ) await page.route('**/api/auth/token', async (route) => { - const request = route.request().postDataJSON() as { - workspace_id?: string - } + const request = route.request().postDataJSON() as ExchangeTokenRequest workspaceId = request.workspace_id ?? 'ws-personal' const workspace = WORKSPACE_SWITCHER_WORKSPACES.find( ({ id }) => id === workspaceId diff --git a/src/workbench/extensions/agent/AgentPanelRoot.test.ts b/src/workbench/extensions/agent/AgentPanelRoot.test.ts index 24c0c65482d..3f913259726 100644 --- a/src/workbench/extensions/agent/AgentPanelRoot.test.ts +++ b/src/workbench/extensions/agent/AgentPanelRoot.test.ts @@ -15985,6 +15985,31 @@ function signInAs({ firebase, apiKeyUser }: AgentAccount): void { apiKeyUser === null ? null : { id: apiKeyUser } } +async function startDesktopHostSessionOn(initialWorkspaceId: string) { + const hostOn = (workspaceId: string) => + fromPartial({ + status: 'signed_in', + userId: 'account-a', + workspaceId + }) + let notify: (state: DesktopHostAuthState) => void = () => {} + await startDesktopHostSession({ + getState: async () => hostOn(initialWorkspaceId), + getWorkspaceToken: async () => 'host-token', + requestSignIn: async () => hostOn(initialWorkspaceId), + signOut: async () => ({ status: 'signed_out' }), + switchWorkspace: async (workspaceId) => hostOn(workspaceId), + onChanged: (listener) => { + notify = listener + return () => {} + } + }) + return { + hostOn, + notifyHostChanged: (state: DesktopHostAuthState) => notify(state) + } +} + describe('AgentPanelRoot agent socket', () => { it.for([ { @@ -16092,20 +16117,7 @@ describe('AgentPanelRoot agent socket', () => { reset, stop: () => {} }) - const hostOn = (workspaceId: string) => - fromPartial({ - status: 'signed_in', - userId: 'account-a', - workspaceId - }) - await startDesktopHostSession({ - getState: async () => hostOn('ws-host'), - getWorkspaceToken: async () => 'host-token', - requestSignIn: async () => hostOn('ws-host'), - signOut: async () => ({ status: 'signed_out' }), - switchWorkspace: async () => hostOn('ws-host'), - onChanged: () => () => {} - }) + await startDesktopHostSessionOn('ws-host') try { signInAs({ firebase: 'account-a', apiKeyUser: null }) const workspaces = useTeamWorkspaceStore() @@ -16133,24 +16145,8 @@ describe('AgentPanelRoot agent socket', () => { reset, stop: () => {} }) - const hostOn = (workspaceId: string) => - fromPartial({ - status: 'signed_in', - userId: 'account-a', - workspaceId - }) - let notifyHostChanged: (state: DesktopHostAuthState) => void = () => {} - await startDesktopHostSession({ - getState: async () => hostOn('ws-a'), - getWorkspaceToken: async () => 'host-token', - requestSignIn: async () => hostOn('ws-a'), - signOut: async () => ({ status: 'signed_out' }), - switchWorkspace: async (workspaceId) => hostOn(workspaceId), - onChanged: (listener) => { - notifyHostChanged = listener - return () => {} - } - }) + const { hostOn, notifyHostChanged } = + await startDesktopHostSessionOn('ws-a') try { signInAs({ firebase: 'account-a', apiKeyUser: null }) const workspaces = useTeamWorkspaceStore() From 357db1ec1c2f1d4f2b1d24ed22ff2bb90baf474a Mon Sep 17 00:00:00 2001 From: Christian Byrne Date: Thu, 29 Oct 2026 02:10:10 -0700 Subject: [PATCH 7/9] test(agent): seed workspace onboarding state --- .../tests/agent/agentWorkspaceSwitchFixture.ts | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/browser_tests/tests/agent/agentWorkspaceSwitchFixture.ts b/browser_tests/tests/agent/agentWorkspaceSwitchFixture.ts index 5a93fe7b41b..99506c08bbc 100644 --- a/browser_tests/tests/agent/agentWorkspaceSwitchFixture.ts +++ b/browser_tests/tests/agent/agentWorkspaceSwitchFixture.ts @@ -43,6 +43,18 @@ export const agentWorkspaceSwitcherTest = base.extend<{ credit_limit: null } + await page.addInitScript( + (workspaceIds) => { + for (const workspaceId of workspaceIds) { + localStorage.setItem( + `Comfy.AgentPanel.onboarded.test-user-e2e.${workspaceId}`, + 'true' + ) + } + }, + ['ws-personal', 'ws-team'] + ) + await bootAgentApp(page, agentFlagEnabled, { features: WORKSPACE_SWITCHER_REMOTE_CONFIG, settings: { 'Comfy.UseNewMenu': 'Top' }, From cb7f66f59ba93ef98001791d84fbef0335f14d16 Mon Sep 17 00:00:00 2001 From: Christian Byrne Date: Thu, 29 Oct 2026 02:27:13 -0700 Subject: [PATCH 8/9] test(agent): avoid redundant workspace menu reopen --- browser_tests/tests/agent/agentWorkspaceSwitch.spec.ts | 4 ---- 1 file changed, 4 deletions(-) diff --git a/browser_tests/tests/agent/agentWorkspaceSwitch.spec.ts b/browser_tests/tests/agent/agentWorkspaceSwitch.spec.ts index 5100023944b..79ef92ff92a 100644 --- a/browser_tests/tests/agent/agentWorkspaceSwitch.spec.ts +++ b/browser_tests/tests/agent/agentWorkspaceSwitch.spec.ts @@ -45,10 +45,6 @@ test.describe('Agent workspace switching', { tag: '@ui' }, () => { .toContainEqual({ workspaceId: 'ws-team' }) - await page.getByRole('button', { name: 'Current user' }).click() - await expect(page.getByTestId('workspace-switcher-trigger')).toContainText( - TEAM_WORKSPACE_NAME - ) await expect(agentPanel.composer).toBeVisible() }) }) From 8d5b6c7ccd0f62b2f72082236918afd8aa07ee9d Mon Sep 17 00:00:00 2001 From: Christian Byrne Date: Thu, 29 Oct 2026 02:29:02 -0700 Subject: [PATCH 9/9] test(agent): bind workspace identity to bearer --- .../tests/agent/agentWorkspaceSwitchFixture.ts | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/browser_tests/tests/agent/agentWorkspaceSwitchFixture.ts b/browser_tests/tests/agent/agentWorkspaceSwitchFixture.ts index 99506c08bbc..20671e0398e 100644 --- a/browser_tests/tests/agent/agentWorkspaceSwitchFixture.ts +++ b/browser_tests/tests/agent/agentWorkspaceSwitchFixture.ts @@ -117,9 +117,19 @@ export const agentWorkspaceSwitcherTest = base.extend<{ route.fulfill(jsonRoute(runMode)) ) await page.route('**/api/agent/identity', (route) => { - reads.push({ workspaceId }) + const token = route + .request() + .headers() + ['authorization']?.replace(/^Bearer /, '') + const identityWorkspace = WORKSPACE_SWITCHER_WORKSPACES.find( + ({ id }) => token === `mock-workspace-token-${id}` + ) + if (!identityWorkspace) { + return route.fulfill({ status: 401 }) + } + reads.push({ workspaceId: identityWorkspace.id }) const identity: AgentIdentity = { - workspace_id: workspaceId, + workspace_id: identityWorkspace.id, user_id: 'uid-1' } return route.fulfill(jsonRoute(identity))