diff --git a/packages/account-core/src/webSessionInertImport.test.ts b/packages/account-core/src/webSessionInertImport.test.ts index aa2a3450e31..f789c20de9e 100644 --- a/packages/account-core/src/webSessionInertImport.test.ts +++ b/packages/account-core/src/webSessionInertImport.test.ts @@ -11,7 +11,6 @@ it.for([ '@comfyorg/account-core/sessionTokenMint', '@comfyorg/account-core/webSessionIdentity', '@comfyorg/account-core/web', - '@comfyorg/account-core/requestAuth', '@comfyorg/account-core/testing' ])( 'importing %s starts no timer, listener, channel, or request', diff --git a/src/platform/auth/session/cloudWebSessionStore.ts b/src/platform/auth/session/cloudWebSessionStore.ts index 086c72724dc..b3af66e58bc 100644 --- a/src/platform/auth/session/cloudWebSessionStore.ts +++ b/src/platform/auth/session/cloudWebSessionStore.ts @@ -1,6 +1,6 @@ import type { User } from 'firebase/auth' import { defineStore } from 'pinia' -import { onScopeDispose } from 'vue' +import { onScopeDispose, shallowRef, watch } from 'vue' import type { WebSessionAccountChange, @@ -67,6 +67,11 @@ function resetForAccountChange(change: WebSessionAccountChange): void { }) } +function teamWorkspaceId(): string | undefined { + const workspace = useWorkspaceAuthStore().currentWorkspace + return workspace?.type === 'team' ? workspace.id : undefined +} + function sessionOptions(): WebSessionOptions { return { apiBaseUrl: api.apiURL(''), @@ -107,6 +112,16 @@ export const useCloudWebSessionStore = defineStore('cloudWebSession', () => { let pendingSignIn: InteractiveSignIn | null = null let reread: WebSession | null = null let releaseRequests = () => {} + const signedInUserId = shallowRef() + + watch( + () => + signedInUserId.value && + JSON.stringify([signedInUserId.value, teamWorkspaceId()]), + (socketScope) => { + if (socketScope) void api.reconnectSocket() + } + ) onScopeDispose(() => { releaseRequests() @@ -142,10 +157,16 @@ export const useCloudWebSessionStore = defineStore('cloudWebSession', () => { if (!useFeatureFlags().flags.unifiedWebSessionEnabled) return false const session = createCloudIdentity() identity = session - session.subscribe(() => { + session.subscribe((state) => { reread = null + signedInUserId.value = + state.phase === 'signed_in' ? state.session.user.id : undefined + }) + releaseRequests = provideWebSessionRequests({ + scope: requestScope, + workspaceId: () => (currentSession() ? teamWorkspaceId() : undefined), + send }) - releaseRequests = provideWebSessionRequests({ scope: requestScope, send }) ready = whenSettled(session) void bootAfter(session, pendingSignIn) pendingSignIn = null @@ -180,11 +201,11 @@ export const useCloudWebSessionStore = defineStore('cloudWebSession', () => { await ready const session = currentSession() if (!identity || !session) return undefined - const workspace = useWorkspaceAuthStore().currentWorkspace + const workspaceId = teamWorkspaceId() return { session, epoch: identity.getEpoch(), - ...(workspace?.type === 'team' && { workspaceId: workspace.id }) + ...(workspaceId && { workspaceId }) } } diff --git a/src/platform/auth/session/sessionMediaUrl.ts b/src/platform/auth/session/sessionMediaUrl.ts new file mode 100644 index 00000000000..8575b9426b5 --- /dev/null +++ b/src/platform/auth/session/sessionMediaUrl.ts @@ -0,0 +1,16 @@ +const MEDIA_ROUTE = + /^(?:\/api)?\/(?:view|viewvideo|vhs\/viewvideo|vhs\/viewaudio|assets\/[^/?#]+\/content)(?:\?|$)/ + +/** + * Names the workspace on a media route, which an image or video tag loads + * without headers; absent means the personal workspace. + */ +export function scopeMediaRoute( + route: string, + workspaceId: string | undefined +): string { + if (!workspaceId || !MEDIA_ROUTE.test(route)) return route + if (/[?&]workspace_id=/.test(route)) return route + const separator = route.includes('?') ? '&' : '?' + return `${route}${separator}workspace_id=${encodeURIComponent(workspaceId)}` +} diff --git a/src/platform/auth/session/webSessionFetch.ts b/src/platform/auth/session/webSessionFetch.ts index 5884756a00f..e6960e6b4ef 100644 --- a/src/platform/auth/session/webSessionFetch.ts +++ b/src/platform/auth/session/webSessionFetch.ts @@ -74,6 +74,8 @@ export async function fetchOnWebSession( export interface WebSessionRequests { /** Undefined unless this tab is signed in on the session. */ readonly scope: () => Promise + /** The signed-in session's team workspace, for URLs that carry no header. */ + readonly workspaceId: () => string | undefined readonly send: ( url: string, init: RequestInit, diff --git a/src/platform/auth/webSessionFlagOff.test.ts b/src/platform/auth/webSessionFlagOff.test.ts index 2e225321e61..dabe0844ec5 100644 --- a/src/platform/auth/webSessionFlagOff.test.ts +++ b/src/platform/auth/webSessionFlagOff.test.ts @@ -13,7 +13,11 @@ import { remoteConfig } from '@/platform/remoteConfig/remoteConfig' import { TOKEN_REFRESH_BUFFER_MS } from '@/platform/workspace/workspaceConstants' import { api } from '@/scripts/api' import { useAuthStore } from '@/stores/authStore' -import { resultItemPreviewUrl, resultItemUrl } from '@/utils/resultItemUrl' +import { + resultItemPreviewUrl, + resultItemUrl, + resultItemVhsAdvancedPreviewUrl +} from '@/utils/resultItemUrl' import type { useExtensionService } from '@/services/extensionService' import type { ComfyApp } from '@/scripts/app' import type { ComfyExtension } from '@/types/comfy' @@ -279,7 +283,10 @@ const MEDIA_ITEM = { const MEDIA_URLS = [ '/api/view?filename=output.png&type=output&subfolder=', - '/api/view?filename=output.png&type=output&subfolder=&res=512' + '/api/view?filename=output.png&type=output&subfolder=&res=512', + '/api/viewvideo?filename=output.png&type=output&subfolder=', + '/api/vhs/viewaudio?filename=a.wav', + '/api/assets/asset-1/content?disposition=inline' ] const SIGN_OUT: RecordedRequest[] = [ @@ -450,7 +457,10 @@ describe('cloud auth requests with unified_web_session off', () => { expect([ resultItemUrl(MEDIA_ITEM), - resultItemPreviewUrl(MEDIA_ITEM) + resultItemPreviewUrl(MEDIA_ITEM), + resultItemVhsAdvancedPreviewUrl(MEDIA_ITEM), + api.apiURL('/vhs/viewaudio?filename=a.wav'), + api.apiURL('/assets/asset-1/content?disposition=inline') ]).toEqual(MEDIA_URLS) expect(recorder.socketCloses).toBe(0) diff --git a/src/platform/auth/webSessionFlagOn.test.ts b/src/platform/auth/webSessionFlagOn.test.ts index e13b6b80311..0398834ecc5 100644 --- a/src/platform/auth/webSessionFlagOn.test.ts +++ b/src/platform/auth/webSessionFlagOn.test.ts @@ -20,6 +20,10 @@ import type { ComfyApp } from '@/scripts/app' import type { useExtensionService } from '@/services/extensionService' import { useAuthStore } from '@/stores/authStore' import type { ComfyExtension } from '@/types/comfy' +import { + resultItemUrl, + resultItemVhsAdvancedPreviewUrl +} from '@/utils/resultItemUrl' type IdentityObserver = (user: User | null) => void @@ -581,3 +585,167 @@ describe('cloud API requests on the shared web session', () => { } ) }) + +class FakeSocket extends EventTarget { + static readonly CONNECTING = 0 + static readonly OPEN = 1 + static readonly CLOSING = 2 + static readonly CLOSED = 3 + static created: FakeSocket[] = [] + readyState = FakeSocket.CONNECTING + binaryType = 'blob' + readonly path: string + constructor(url: string | URL) { + super() + const parsed = new URL(String(url)) + this.path = parsed.pathname + parsed.search + FakeSocket.created.push(this) + } + send() {} + close() { + this.readyState = FakeSocket.CLOSED + } + closeFromServer() { + this.close() + this.dispatchEvent(new Event('close')) + } +} + +const MEDIA_ITEM = { + filename: 'output.png', + subfolder: '', + type: 'output', + nodeId: '1', + mediaType: 'images' +} as const + +describe('live updates and media on the shared web session', () => { + beforeEach(() => { + identity.reset() + firebaseSignOut.mockReset() + firebaseSignOut.mockImplementation(async () => identity.signOut()) + FakeSocket.created = [] + vi.stubGlobal('WebSocket', FakeSocket) + window.name = '' + api.socket = null + }) + + afterEach(() => { + remoteConfig.value = {} + localStorage.clear() + }) + + async function bootWithSocket() { + const ingest = await bootOnSession() + await api.init() + return ingest + } + + it('opens the socket on the cookie and reconnects it into each workspace without minting a token', async () => { + const ingest = await bootWithSocket() + const workspaceAuth = useWorkspaceAuthStore() + expect(FakeSocket.created.map(({ path }) => path)).toEqual(['/ws']) + + await workspaceAuth.switchWorkspace('ws-team') + await vi.waitFor(() => + expect(api.socket).toEqual( + expect.objectContaining({ path: '/ws?workspace_id=ws-team' }) + ) + ) + await workspaceAuth.switchWorkspace('ws-personal') + await vi.waitFor(() => + expect(api.socket).toEqual(expect.objectContaining({ path: '/ws' })) + ) + + expect(api.socket).toBe(FakeSocket.created.at(-1)) + const replaced = FakeSocket.created.slice(0, -1) + expect(replaced.map(({ readyState }) => readyState)).toEqual( + replaced.map(() => FakeSocket.CLOSED) + ) + expect( + FakeSocket.created.filter(({ path }) => path.includes('token')) + ).toEqual([]) + expect(ingest.requests.map(({ path }) => path)).not.toContain( + '/api/auth/token' + ) + }) + + it.for([ + { workspace: 'ws-team', suffix: '&workspace_id=ws-team' }, + { workspace: 'ws-personal', suffix: '' } + ])( + 'media URLs name the workspace only for a team ($workspace)', + async ({ workspace, suffix }) => { + await bootOnSession() + await useWorkspaceAuthStore().switchWorkspace(workspace) + + expect([ + resultItemUrl(MEDIA_ITEM), + resultItemVhsAdvancedPreviewUrl(MEDIA_ITEM), + api.apiURL('/vhs/viewvideo?filename=a.mp4'), + api.apiURL('/api/view?filename=a.png'), + api.apiURL('/assets/asset-1/content?disposition=inline'), + api.apiURL('/queue?view=1') + ]).toEqual([ + `/api/view?filename=output.png&type=output&subfolder=${suffix}`, + `/api/viewvideo?filename=output.png&type=output&subfolder=${suffix}`, + `/api/vhs/viewvideo?filename=a.mp4${suffix}`, + `/api/view?filename=a.png${suffix}`, + `/api/assets/asset-1/content?disposition=inline${suffix}`, + '/api/queue?view=1' + ]) + } + ) + + it('a media fetch names the team workspace in the header only', async () => { + const ingest = await bootOnSession() + await useWorkspaceAuthStore().switchWorkspace('ws-team') + ingest.requests.length = 0 + + await api.fetchApi('/view?filename=a.png') + + const [url] = vi.mocked(fetch).mock.calls.at(-1) ?? [] + expect(String(url)).toBe('/api/view?filename=a.png') + expect(ingest.requests).toEqual([ + sessionRequest('GET', '/api/view', { + 'x-comfy-workspace-id': 'ws-team', + 'comfy-user': '' + }) + ]) + }) + + it('a server close while signed in reconnects on the session', async () => { + await bootWithSocket() + await useWorkspaceAuthStore().switchWorkspace('ws-team') + await vi.waitFor(() => + expect(api.socket).toEqual( + expect.objectContaining({ path: '/ws?workspace_id=ws-team' }) + ) + ) + const closed = api.socket + assert.instanceOf(closed, FakeSocket) + + closed.closeFromServer() + await vi.advanceTimersByTimeAsync(300) + + await vi.waitFor(() => expect(api.socket).not.toBe(closed)) + expect(api.socket).toEqual( + expect.objectContaining({ path: '/ws?workspace_id=ws-team' }) + ) + }) + + it('sign-out closes the socket and opens no other', async () => { + await bootWithSocket() + const sessionSocket = api.socket + assert.instanceOf(sessionSocket, FakeSocket) + + await useAuthStore().logout() + expect(sessionSocket.readyState).toBe(FakeSocket.CLOSED) + + sessionSocket.closeFromServer() + await vi.advanceTimersByTimeAsync(1_000) + + expect(FakeSocket.created).toEqual([sessionSocket]) + expect(api.socket).toBeNull() + }) +}) diff --git a/src/scripts/api.ts b/src/scripts/api.ts index 543f4f10200..06a7eefae3a 100644 --- a/src/scripts/api.ts +++ b/src/scripts/api.ts @@ -17,6 +17,7 @@ import { trimEnd } from 'es-toolkit' import { ref } from 'vue' import defaultClientFeatureFlags from '@/config/clientFeatureFlags.json' with { type: 'json' } +import { scopeMediaRoute } from '@/platform/auth/session/sessionMediaUrl' import { webSessionRequests } from '@/platform/auth/session/webSessionFetch' import { fetchWithUnifiedRemint, @@ -532,6 +533,14 @@ export class ComfyApi extends EventTarget { } apiURL(route: string): string { + const requests = webSessionRequests() + return this.unscopedApiURL( + requests ? scopeMediaRoute(route, requests.workspaceId()) : route + ) + } + + /** For requests whose headers already name the workspace. */ + private unscopedApiURL(route: string): string { if (route.startsWith('/api')) return this.api_base + route return this.api_base + '/api' + route } @@ -713,7 +722,7 @@ export class ComfyApi extends EventTarget { signal } const response = sendOnWebSession - ? sendOnWebSession(this.apiURL(route), init) + ? sendOnWebSession(this.unscopedApiURL(route), init) : fetchWithUnifiedRemint( this.apiURL(route), init, @@ -881,6 +890,31 @@ export class ComfyApi extends EventTarget { }, 1000) } + /** False when the web session is on and no one is signed in to open it. */ + private async addSocketAuth(params: URLSearchParams): Promise { + const requests = webSessionRequests() + const sessionScope = requests && (await requests.scope()) + if (sessionScope?.workspaceId) { + params.set('workspace_id', sessionScope.workspaceId) + } + if (sessionScope) return true + + // Get auth token and set cloud params if available + // Uses workspace token (if enabled) or Firebase token + try { + const authStore = await this.getAuthStore() + const authToken = await authStore?.getAuthToken() + if (authToken) { + params.set('token', authToken) + } + } catch (error) { + void trackWsTokenUnavailable() + // Continue without auth token if there's an error + console.warn('Could not get auth token for WebSocket connection:', error) + } + return !requests || params.has('token') + } + /** * Creates and connects a WebSocket for realtime updates * @param {boolean} isReconnect If the socket is connection is a reconnect attempt @@ -901,24 +935,7 @@ export class ComfyApi extends EventTarget { params.set('clientId', existingSession) } - // Get auth token and set cloud params if available - // Uses workspace token (if enabled) or Firebase token - if (isCloud) { - try { - const authStore = await this.getAuthStore() - const authToken = await authStore?.getAuthToken() - if (authToken) { - params.set('token', authToken) - } - } catch (error) { - void trackWsTokenUnavailable() - // Continue without auth token if there's an error - console.warn( - 'Could not get auth token for WebSocket connection:', - error - ) - } - } + if (isCloud && !(await this.addSocketAuth(params))) return const protocol = window.location.protocol === 'https:' ? 'wss' : 'ws' const baseUrl = `${protocol}://${this.api_host}${this.api_base}/ws` @@ -1154,6 +1171,25 @@ export class ComfyApi extends EventTarget { * events over a handshake that was authenticated as that account. */ async resetSocket(): Promise { + // Clear every handshake identity source: createSocket() reads the client id + // from window.name (mirrored in session storage), not this.clientId, so the + // next connect must not inherit the prior account's id. + this.clientId = undefined + window.name = '' + sessionStorage.removeItem('clientId') + await this.replaceSocket() + } + + /** + * Re-handshakes the socket for the same account, keeping its client id, so + * a new web session workspace takes effect. Does nothing before init(). + */ + async reconnectSocket(): Promise { + if (this.socketGeneration === 0) return + await this.replaceSocket() + } + + private async replaceSocket(): Promise { const previous = this.socket // serverFeatureFlags deliberately keeps the previous map: clearing it would // downgrade every serverSupportsFeature() caller until the next delivery. @@ -1161,12 +1197,6 @@ export class ComfyApi extends EventTarget { // Detach before closing so the previous socket's close handler sees it is // no longer the active socket and does not start a competing reconnect. this.socket = null - // Clear every handshake identity source: createSocket() reads the client id - // from window.name (mirrored in session storage), not this.clientId, so the - // next connect must not inherit the prior account's id. - this.clientId = undefined - window.name = '' - sessionStorage.removeItem('clientId') if (previous && previous.readyState !== WebSocket.CLOSED) { try { previous.close()