From f956411fd03dccb350d74407b06966528313e475 Mon Sep 17 00:00:00 2001 From: dante01yoon Date: Tue, 29 Sep 2026 02:50:38 -0400 Subject: [PATCH 1/2] fix(cloud): remote widgets fetch on the web session workspace --- .../composables/useRemoteWidget.test.ts | 232 +++++++++++++++++- .../widgets/composables/useRemoteWidget.ts | 59 +++++ .../useRemoteWidget.webSession.test.ts | 194 +++++++++++++++ src/scripts/api.ts | 9 + 4 files changed, 487 insertions(+), 7 deletions(-) create mode 100644 src/renderer/extensions/vueNodes/widgets/composables/useRemoteWidget.webSession.test.ts diff --git a/src/renderer/extensions/vueNodes/widgets/composables/useRemoteWidget.test.ts b/src/renderer/extensions/vueNodes/widgets/composables/useRemoteWidget.test.ts index 3ba04ed7e9f..5943b37fd60 100644 --- a/src/renderer/extensions/vueNodes/widgets/composables/useRemoteWidget.test.ts +++ b/src/renderer/extensions/vueNodes/widgets/composables/useRemoteWidget.test.ts @@ -1,23 +1,27 @@ -import { useAuthStore } from '@/stores/authStore' +import { fromPartial } from '@total-typescript/shoehorn' import axios from 'axios' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { beforeEach, describe, expect, it, vi } from 'vitest' +import type { WebSession } from '@comfyorg/account-core/webSession' import type { IWidget } from '@/lib/litegraph/src/litegraph' +import type { WebSessionRequestScope } from '@/platform/auth/session/webSessionFetch' +import { provideWebSessionRequests } from '@/platform/auth/session/webSessionFetch' import { api } from '@/scripts/api' import { useRemoteWidget } from '@/renderer/extensions/vueNodes/widgets/composables/useRemoteWidget' import type { RemoteWidgetConfig } from '@/schemas/nodeDefSchema' import { createMockLGraphNode } from '@/utils/__tests__/litegraphTestUtils' import { stubFirebaseAuthHarness } from '@/utils/__tests__/stubAccountIdentityPort' +import { useAuthStore } from '@/stores/authStore' function createMockWidget(overrides: Partial = {}): IWidget { - return { + const widget = fromPartial({ name: 'test_widget', type: 'text', value: '', - options: {}, - ...overrides - } as Partial as IWidget + options: {} + }) + return Object.assign(widget, overrides) } const mockCloudAuth = vi.hoisted(() => ({ @@ -461,7 +465,7 @@ describe('useRemoteWidget', () => { const hook2 = useRemoteWidget(options) // Since they have the same route, only one request will be made - await Promise.race([getResolvedValue(hook1), getResolvedValue(hook2)]) + await Promise.all([getResolvedValue(hook1), getResolvedValue(hook2)]) const data1 = hook1.getValue() const data2 = hook2.getValue() @@ -583,6 +587,220 @@ describe('useRemoteWidget', () => { }) }) + describe('web session', () => { + const sessionScope = (): WebSessionRequestScope | undefined => ({ + session: fromPartial({}), + epoch: 1 + }) + let release: (() => void) | undefined + let scope: () => WebSessionRequestScope | undefined + let send: ReturnType< + typeof vi.fn<(url: string, init: RequestInit) => Promise> + > + + const provideSession = () => { + release = provideWebSessionRequests({ + scope: async () => scope(), + workspaceId: () => undefined, + send: (url, init) => send(url, init) + }) + } + + beforeEach(() => { + scope = sessionScope + send = vi.fn<(url: string, init: RequestInit) => Promise>() + vi.stubGlobal('fetch', vi.fn()) + }) + + afterEach(() => { + release?.() + release = undefined + mockCloudAuth.isCloud = false + mockCloudAuth.authHeader = null + }) + + const jsonBody = (body: unknown, status = 200) => + new Response(JSON.stringify(body), { status }) + + let routeCount = 0 + const uniqueRoute = () => `/api/models/${routeCount++}` + + it.for([ + { + name: 'a plain route', + suffix: '', + params: undefined, + responseKey: undefined, + body: ['a', 'b'], + value: ['a', 'b'] + }, + { + name: 'a route that already has a query', + suffix: '?a=1', + params: { b: '2' }, + responseKey: undefined, + body: ['a'], + value: ['a'], + query: '?a=1&b=2' + }, + { + name: 'query params on a plain route', + suffix: '', + params: { b: '2' }, + responseKey: undefined, + body: ['a'], + value: ['a'], + query: '?b=2' + }, + { + name: 'a response key', + suffix: '', + params: undefined, + responseKey: 'items', + body: { items: ['k'] }, + value: ['k'] + } + ])( + 'fetches on the web session: $name', + async ({ suffix, params, responseKey, body, value, query = '' }) => { + provideSession() + send.mockResolvedValueOnce(jsonBody(body)) + const route = uniqueRoute() + const hook = useRemoteWidget( + createMockOptions({ + route: `${route}${suffix}`, + query_params: params, + response_key: responseKey + }) + ) + + await getResolvedValue(hook) + + expect(send).toHaveBeenCalledExactlyOnceWith( + `${route}${query || suffix}`, + { + method: 'GET', + signal: expect.any(AbortSignal) + } + ) + expect(vi.mocked(axios.get)).not.toHaveBeenCalled() + expect(hook.getCachedValue()).toEqual(value) + } + ) + + it('keeps a body that is not JSON as text', async () => { + provideSession() + send.mockResolvedValueOnce(new Response('plain')) + const hook = useRemoteWidget(createMockOptions()) + + await getResolvedValue(hook) + + expect(hook.getCachedValue()).toBe('plain') + }) + + it('treats a failed status as an error and keeps the default', async () => { + provideSession() + send.mockResolvedValueOnce(jsonBody({ message: 'no' }, 500)) + const hook = useRemoteWidget(createMockOptions()) + + await getResolvedValue(hook) + + expect(hook.getInventoryStatus()).toBe('error') + expect(hook.getCachedValue()).toBe(DEFAULT_VALUE) + }) + + it('aborts a session request that outlives its timeout', async () => { + provideSession() + send.mockImplementationOnce( + (_url, init) => + new Promise((_resolve, reject) => { + init.signal?.addEventListener('abort', () => + reject(new Error('aborted')) + ) + }) + ) + const hook = useRemoteWidget(createMockOptions({ timeout: 50 })) + + const settled = getResolvedValue(hook) + await vi.advanceTimersByTimeAsync(50) + await settled + + expect(hook.getInventoryStatus()).toBe('error') + }) + + it.for([ + { + name: 'a cross-origin route', + route: 'https://example.com/x', + sessionScope: sessionScope + }, + { + name: 'a protocol-relative route', + route: '//example.com/x', + sessionScope: sessionScope + }, + { + name: 'a tab that is not on the session', + route: uniqueRoute(), + sessionScope: () => undefined + } + ])( + 'stays on axios for $name', + async ({ route, sessionScope: nextScope }) => { + mockCloudAuth.isCloud = true + mockCloudAuth.authHeader = { Authorization: 'Bearer test-token' } + scope = nextScope + provideSession() + mockAxiosResponse(['ax']) + const hook = useRemoteWidget(createMockOptions({ route })) + + await getResolvedValue(hook) + + expect(send).not.toHaveBeenCalled() + expect(vi.mocked(axios.get)).toHaveBeenCalledExactlyOnceWith(route, { + params: undefined, + signal: expect.any(AbortSignal), + timeout: 4096, + headers: { Authorization: 'Bearer test-token' } + }) + expect(hook.getCachedValue()).toEqual(['ax']) + } + ) + + it.for([ + { name: 'not cloud', isCloud: false, headers: {} }, + { + name: 'cloud with a token', + isCloud: true, + headers: { headers: { Authorization: 'Bearer test-token' } } + } + ])( + 'sends flag-off traffic through axios only ($name)', + async ({ isCloud, headers }) => { + mockCloudAuth.isCloud = isCloud + mockCloudAuth.authHeader = isCloud + ? { Authorization: 'Bearer test-token' } + : null + mockAxiosResponse(['ax']) + const options = createMockOptions({ query_params: { q: '1' } }) + const hook = useRemoteWidget(options) + + await getResolvedValue(hook) + + expect(vi.mocked(axios.get)).toHaveBeenCalledExactlyOnceWith( + options.remoteConfig.route, + { + params: { q: '1' }, + signal: expect.any(AbortSignal), + timeout: 4096, + ...headers + } + ) + expect(fetch).not.toHaveBeenCalled() + } + ) + }) + describe('auto-refresh on task completion', () => { it('should add auto-refresh toggle widget', () => { const mockNode = createMockLGraphNode({ diff --git a/src/renderer/extensions/vueNodes/widgets/composables/useRemoteWidget.ts b/src/renderer/extensions/vueNodes/widgets/composables/useRemoteWidget.ts index 6a062968fdd..32c94e64cf9 100644 --- a/src/renderer/extensions/vueNodes/widgets/composables/useRemoteWidget.ts +++ b/src/renderer/extensions/vueNodes/widgets/composables/useRemoteWidget.ts @@ -69,12 +69,71 @@ const isBackingOff = (entry: CacheEntry | undefined) => entry.lastErrorTime && Date.now() - entry.lastErrorTime < getBackoff(entry.retryCount || 0) +class RemoteWidgetRequestError extends Error {} + +const isSameOrigin = (route: string) => + new URL(route, location.href).origin === location.origin + +const withQuery = ( + route: string, + params: RemoteWidgetConfig['query_params'] +) => { + const query = new URLSearchParams(params).toString() + if (!query) return route + return `${route}${route.includes('?') ? '&' : '?'}${query}` +} + +const parseBody = (text: string): unknown => { + try { + return JSON.parse(text) + } catch { + return text + } +} + +const pickKey = (data: unknown, key: string | undefined) => { + if (!key) return data + return typeof data === 'object' && data !== null + ? Reflect.get(data, key) + : undefined +} + +const fetchOnSession = async ( + config: RemoteWidgetConfig, + controller: AbortController +): Promise<{ data: unknown } | undefined> => { + const { route, query_params, timeout = TIMEOUT } = config + if (!isSameOrigin(route)) return undefined + + const timeoutController = new AbortController() + const timer = + timeout > 0 ? setTimeout(() => timeoutController.abort(), timeout) : 0 + try { + const res = await api.fetchOnWebSession(withQuery(route, query_params), { + method: 'GET', + signal: AbortSignal.any([controller.signal, timeoutController.signal]) + }) + if (!res) return undefined + if (!res.ok) { + throw new RemoteWidgetRequestError( + `Request failed with status ${res.status}` + ) + } + return { data: parseBody(await res.text()) } + } finally { + clearTimeout(timer) + } +} + const fetchData = async ( config: RemoteWidgetConfig, controller: AbortController ) => { const { route, response_key, query_params, timeout = TIMEOUT } = config + const sessionRes = await fetchOnSession(config, controller) + if (sessionRes) return pickKey(sessionRes.data, response_key) + const authHeaders = await getAuthHeaders() const res = await axios.get(route, { diff --git a/src/renderer/extensions/vueNodes/widgets/composables/useRemoteWidget.webSession.test.ts b/src/renderer/extensions/vueNodes/widgets/composables/useRemoteWidget.webSession.test.ts new file mode 100644 index 00000000000..8b24f149c13 --- /dev/null +++ b/src/renderer/extensions/vueNodes/widgets/composables/useRemoteWidget.webSession.test.ts @@ -0,0 +1,194 @@ +import { fromPartial } from '@total-typescript/shoehorn' +import type { User } from 'firebase/auth' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' + +import type { FirebaseIdentity } from '@comfyorg/account-core/firebase' +import { COMFY_CLIENT } from '@comfyorg/account-core/requestAuth' + +import type { IWidget } from '@/lib/litegraph/src/litegraph' +import { useSessionCookie } from '@/platform/auth/session/useSessionCookie' +import { refreshRemoteConfig } from '@/platform/remoteConfig/refreshRemoteConfig' +import { remoteConfig } from '@/platform/remoteConfig/remoteConfig' +import { useWorkspaceAuthStore } from '@/platform/workspace/stores/workspaceAuthStore' +import { useRemoteWidget } from '@/renderer/extensions/vueNodes/widgets/composables/useRemoteWidget' +import { api } from '@/scripts/api' +import { useAuthStore } from '@/stores/authStore' +import { createMockLGraphNode } from '@/utils/__tests__/litegraphTestUtils' + +type IdentityObserver = (user: User | null) => void + +const identity = vi.hoisted(() => { + const userObservers = new Set() + const tokenObservers = new Set() + const state: { user: User | null } = { user: null } + return { + userObservers, + tokenObservers, + state, + reset() { + userObservers.clear() + tokenObservers.clear() + state.user = null + }, + signIn(user: User) { + state.user = user + userObservers.forEach((observer) => observer(user)) + tokenObservers.forEach((observer) => observer(user)) + } + } +}) + +vi.mock(import('@/platform/distribution/types'), () => ({ + DISTRIBUTION: 'cloud' as const, + isCloud: true, + isDesktop: false, + isNightly: false +})) + +vi.mock(import('@/platform/auth/firebaseIdentity'), () => ({ + firebaseIdentity: fromPartial({ + onUserChanged: (observer: IdentityObserver) => { + identity.userObservers.add(observer) + return () => identity.userObservers.delete(observer) + }, + onTokenChanged: (observer: IdentityObserver) => { + identity.tokenObservers.add(observer) + return () => identity.tokenObservers.delete(observer) + }, + currentUser: () => identity.state.user + }) +})) + +vi.mock(import('@/platform/telemetry')) + +vi.mock(import('@/platform/telemetry/reportError'), () => ({ + reportError: vi.fn() +})) + +const USER = fromPartial({ + uid: 'user-a', + getIdToken: async () => 'firebase-id-token' +}) + +interface IngestRequest { + method: string + path: string + headers: Record + credentials: RequestCredentials | null +} + +const jsonResponse = (body: unknown, status = 200) => + new Response(JSON.stringify(body), { + status, + headers: { 'Content-Type': 'application/json' } + }) + +const sessionBody = () => ({ + user: { id: 'user-a', email: 'user-a@example.com', email_verified: true }, + csrf_token: 'csrf-1', + expires_at: new Date(Date.now() + 86_400_000).toISOString(), + absolute_expires_at: new Date(Date.now() + 604_800_000).toISOString() +}) + +const workspaceBody = (id: string | null) => ({ + id: id ?? 'ws-personal', + name: id === 'ws-team' ? 'Team' : 'Personal', + type: id === 'ws-team' ? 'team' : 'personal', + role: 'owner', + auth_method: 'web_session', + permissions: ['owner:*'] +}) + +const recordRequest = (path: string, init: RequestInit | undefined) => ({ + method: (init?.method ?? 'GET').toUpperCase(), + path, + headers: Object.fromEntries( + [...new Headers(init?.headers).entries()].map(([name, value]) => [ + name.toLowerCase(), + value + ]) + ), + credentials: init?.credentials ?? null +}) + +const RESPONSES: Record unknown> = { + '/api/features': () => ({ unified_web_session: true }), + '/api/auth/session': sessionBody, + '/api/workspaces/current': workspaceBody +} + +function installIngest() { + const requests: IngestRequest[] = [] + vi.stubGlobal( + 'fetch', + vi.fn(async (input, init) => { + const path = new URL(String(input), location.href).pathname + if (path !== '/api/features') requests.push(recordRequest(path, init)) + const workspaceId = new Headers(init?.headers).get('x-comfy-workspace-id') + const body = RESPONSES[path]?.(workspaceId) ?? ['checkpoint.safetensors'] + return jsonResponse(body) + }) + ) + return requests +} + +const workspaceHeader = (workspace: string): Record => + workspace === 'ws-team' ? { 'x-comfy-workspace-id': workspace } : {} + +const sessionRequest = (path: string, workspace: string): IngestRequest => ({ + method: 'GET', + path, + headers: { 'x-comfy-client': COMFY_CLIENT, ...workspaceHeader(workspace) }, + credentials: 'include' +}) + +describe('remote widgets on the shared web session', () => { + beforeEach(() => { + identity.reset() + vi.spyOn(api, 'resetSocket').mockResolvedValue() + }) + + afterEach(() => { + remoteConfig.value = {} + }) + + it.for([ + { workspace: 'ws-team', other: 'ws-personal' }, + { workspace: 'ws-personal', other: 'ws-team' } + ])( + 'fetches in $workspace on the session and follows a switch without a token', + async ({ workspace, other }) => { + const requests = installIngest() + await refreshRemoteConfig({ useAuth: false }) + useAuthStore() + identity.signIn(USER) + await useSessionCookie().ensureSessionCookie() + const workspaceAuth = useWorkspaceAuthStore() + await workspaceAuth.switchWorkspace(workspace) + requests.length = 0 + + const route = `/api/models/${workspace}` + const widget = fromPartial({ name: 'model', value: '' }) + const hook = useRemoteWidget({ + remoteConfig: { route, timeout: 1000 }, + defaultValue: 'loading', + node: createMockLGraphNode({ + addWidget: vi.fn(), + onRemoved: undefined + }), + widget + }) + + await hook.waitForInventory() + expect(requests).toEqual([sessionRequest(route, workspace)]) + expect(hook.getCachedValue()).toEqual(['checkpoint.safetensors']) + + await workspaceAuth.switchWorkspace(other) + requests.length = 0 + widget.refresh?.() + await hook.waitForInventory() + + expect(requests).toEqual([sessionRequest(route, other)]) + } + ) +}) diff --git a/src/scripts/api.ts b/src/scripts/api.ts index fc9dd479f21..b1316601018 100644 --- a/src/scripts/api.ts +++ b/src/scripts/api.ts @@ -573,6 +573,15 @@ export class ComfyApi extends EventTarget { return scope && ((url, init) => requests.send(url, init, scope)) } + /** Sends a same-origin request on the web session; undefined when this tab is not on it. */ + async fetchOnWebSession( + url: string, + init: RequestInit + ): Promise { + const send = await this.getWebSessionSend() + return send?.(url, init) + } + /** Adds today's token header; true when a 401 may be re-minted. */ private async addCloudAuthHeader( headers: HeadersInit, From 5b813788fd24df626584ca0829ac595ff81c5872 Mon Sep 17 00:00:00 2001 From: dante01yoon Date: Tue, 29 Sep 2026 19:38:46 -0400 Subject: [PATCH 2/2] test: the remote widget session double stays valid as WebSessionRequests grows --- .../widgets/composables/useRemoteWidget.test.ts | 17 +++++++++++------ 1 file changed, 11 insertions(+), 6 deletions(-) diff --git a/src/renderer/extensions/vueNodes/widgets/composables/useRemoteWidget.test.ts b/src/renderer/extensions/vueNodes/widgets/composables/useRemoteWidget.test.ts index 5943b37fd60..31a66444249 100644 --- a/src/renderer/extensions/vueNodes/widgets/composables/useRemoteWidget.test.ts +++ b/src/renderer/extensions/vueNodes/widgets/composables/useRemoteWidget.test.ts @@ -5,7 +5,10 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import type { WebSession } from '@comfyorg/account-core/webSession' import type { IWidget } from '@/lib/litegraph/src/litegraph' -import type { WebSessionRequestScope } from '@/platform/auth/session/webSessionFetch' +import type { + WebSessionRequestScope, + WebSessionRequests +} from '@/platform/auth/session/webSessionFetch' import { provideWebSessionRequests } from '@/platform/auth/session/webSessionFetch' import { api } from '@/scripts/api' import { useRemoteWidget } from '@/renderer/extensions/vueNodes/widgets/composables/useRemoteWidget' @@ -599,11 +602,13 @@ describe('useRemoteWidget', () => { > const provideSession = () => { - release = provideWebSessionRequests({ - scope: async () => scope(), - workspaceId: () => undefined, - send: (url, init) => send(url, init) - }) + release = provideWebSessionRequests( + fromPartial({ + scope: async () => scope(), + workspaceId: () => undefined, + send: (url, init) => send(url, init) + }) + ) } beforeEach(() => {